diff --git a/README.md b/README.md index 2b863da..12b7336 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,34 @@ If you plan to host this, make sure only /web is reachable! # Sources - https://rules.sonarsource.com/ -- https://semgrep.dev/docs/cheat-sheets \ No newline at end of file +- https://semgrep.dev/docs/cheat-sheets + +# List of Intended vulnerabilities + +## Dependencies + +* go (`go.mod`) + * grafana v8.2.3 +* java + * maven (`pom.xml`) + * jackson-databind 2.9.2 + * log4j-core 2.10.0 +* javascript + * Static file (`jquery.min.js`) + * jQuery v3.4.1 +* nodejs + * npm (`yarn.lock` & `package.json`) + * tenvoy 7.0.2 + * yarn (`package-lock.json` & `package.json`) + * tenvoy 7.0.2 +* php + * composer (`composer.lock` & `composer.json`) + * phpmailer/phpmaile 6.4.1 + * league/flysystem 1.1.3 ("forced" inherit dependency vulnerability) +* python + * pip (`requirements.txt`) + * tendenci 12.0.10 + +## Code + +TODO \ No newline at end of file diff --git a/php/libraries/composer/composer.json b/php/libraries/composer/composer.json index 4cc8252..76a492b 100644 --- a/php/libraries/composer/composer.json +++ b/php/libraries/composer/composer.json @@ -1,5 +1,6 @@ { "require": { - "phpmailer/phpmailer": "6.4.1" + "phpmailer/phpmailer": "6.4.1", + "laravel/laravel": "8.6.10" } -} +} \ No newline at end of file diff --git a/php/libraries/composer/composer.lock b/php/libraries/composer/composer.lock index 9d76e16..be2919b 100644 --- a/php/libraries/composer/composer.lock +++ b/php/libraries/composer/composer.lock @@ -4,83 +4,5557 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "43e203bf7a6d233bd97b1d666e5bddb5", + "content-hash": "ff89a28f725dbb24c301988940d17c6d", "packages": [ + { + "name": "asm89/stack-cors", + "version": "v2.2.0", + "source": { + "type": "git", + "url": "https://github.com/asm89/stack-cors.git", + "reference": "50f57105bad3d97a43ec4a485eb57daf347eafea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/asm89/stack-cors/zipball/50f57105bad3d97a43ec4a485eb57daf347eafea", + "reference": "50f57105bad3d97a43ec4a485eb57daf347eafea", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0", + "symfony/http-foundation": "^5.3|^6|^7", + "symfony/http-kernel": "^5.3|^6|^7" + }, + "require-dev": { + "phpunit/phpunit": "^9", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev" + } + }, + "autoload": { + "psr-4": { + "Asm89\\Stack\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alexander", + "email": "iam.asm89@gmail.com" + } + ], + "description": "Cross-origin resource sharing library and stack middleware", + "homepage": "https://github.com/asm89/stack-cors", + "keywords": [ + "cors", + "stack" + ], + "support": { + "issues": "https://github.com/asm89/stack-cors/issues", + "source": "https://github.com/asm89/stack-cors/tree/v2.2.0" + }, + "time": "2023-11-14T13:51:46+00:00" + }, + { + "name": "brick/math", + "version": "0.11.0", + "source": { + "type": "git", + "url": "https://github.com/brick/math.git", + "reference": "0ad82ce168c82ba30d1c01ec86116ab52f589478" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brick/math/zipball/0ad82ce168c82ba30d1c01ec86116ab52f589478", + "reference": "0ad82ce168c82ba30d1c01ec86116ab52f589478", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.2", + "phpunit/phpunit": "^9.0", + "vimeo/psalm": "5.0.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Brick\\Math\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Arbitrary-precision arithmetic library", + "keywords": [ + "Arbitrary-precision", + "BigInteger", + "BigRational", + "arithmetic", + "bigdecimal", + "bignum", + "brick", + "math" + ], + "support": { + "issues": "https://github.com/brick/math/issues", + "source": "https://github.com/brick/math/tree/0.11.0" + }, + "funding": [ + { + "url": "https://github.com/BenMorel", + "type": "github" + } + ], + "time": "2023-01-15T23:15:59+00:00" + }, + { + "name": "carbonphp/carbon-doctrine-types", + "version": "3.2.0", + "source": { + "type": "git", + "url": "https://github.com/CarbonPHP/carbon-doctrine-types.git", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "conflict": { + "doctrine/dbal": "<4.0.0 || >=5.0.0" + }, + "require-dev": { + "doctrine/dbal": "^4.0.0", + "nesbot/carbon": "^2.71.0 || ^3.0.0", + "phpunit/phpunit": "^10.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Carbon\\Doctrine\\": "src/Carbon/Doctrine/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "KyleKatarn", + "email": "kylekatarnls@gmail.com" + } + ], + "description": "Types to use Carbon in Doctrine", + "keywords": [ + "carbon", + "date", + "datetime", + "doctrine", + "time" + ], + "support": { + "issues": "https://github.com/CarbonPHP/carbon-doctrine-types/issues", + "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.0" + }, + "funding": [ + { + "url": "https://github.com/kylekatarnls", + "type": "github" + }, + { + "url": "https://opencollective.com/Carbon", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "type": "tidelift" + } + ], + "time": "2024-02-09T16:56:22+00:00" + }, + { + "name": "dflydev/dot-access-data", + "version": "v3.0.2", + "source": { + "type": "git", + "url": "https://github.com/dflydev/dflydev-dot-access-data.git", + "reference": "f41715465d65213d644d3141a6a93081be5d3549" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dflydev/dflydev-dot-access-data/zipball/f41715465d65213d644d3141a6a93081be5d3549", + "reference": "f41715465d65213d644d3141a6a93081be5d3549", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.42", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.3", + "scrutinizer/ocular": "1.6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Dflydev\\DotAccessData\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dragonfly Development Inc.", + "email": "info@dflydev.com", + "homepage": "http://dflydev.com" + }, + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Carlos Frutos", + "email": "carlos@kiwing.it", + "homepage": "https://github.com/cfrutos" + }, + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com" + } + ], + "description": "Given a deep data structure, access data by dot notation.", + "homepage": "https://github.com/dflydev/dflydev-dot-access-data", + "keywords": [ + "access", + "data", + "dot", + "notation" + ], + "support": { + "issues": "https://github.com/dflydev/dflydev-dot-access-data/issues", + "source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.2" + }, + "time": "2022-10-27T11:44:00+00:00" + }, + { + "name": "doctrine/inflector", + "version": "2.0.10", + "source": { + "type": "git", + "url": "https://github.com/doctrine/inflector.git", + "reference": "5817d0659c5b50c9b950feb9af7b9668e2c436bc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/inflector/zipball/5817d0659c5b50c9b950feb9af7b9668e2c436bc", + "reference": "5817d0659c5b50c9b950feb9af7b9668e2c436bc", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^11.0", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-phpunit": "^1.1", + "phpstan/phpstan-strict-rules": "^1.3", + "phpunit/phpunit": "^8.5 || ^9.5", + "vimeo/psalm": "^4.25 || ^5.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\Inflector\\": "lib/Doctrine/Inflector" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.", + "homepage": "https://www.doctrine-project.org/projects/inflector.html", + "keywords": [ + "inflection", + "inflector", + "lowercase", + "manipulation", + "php", + "plural", + "singular", + "strings", + "uppercase", + "words" + ], + "support": { + "issues": "https://github.com/doctrine/inflector/issues", + "source": "https://github.com/doctrine/inflector/tree/2.0.10" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finflector", + "type": "tidelift" + } + ], + "time": "2024-02-18T20:23:39+00:00" + }, + { + "name": "doctrine/lexer", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "c268e882d4dbdd85e36e4ad69e02dc284f89d229" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/c268e882d4dbdd85e36e4ad69e02dc284f89d229", + "reference": "c268e882d4dbdd85e36e4ad69e02dc284f89d229", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^9.0", + "phpstan/phpstan": "^1.3", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", + "vimeo/psalm": "^4.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\Common\\Lexer\\": "lib/Doctrine/Common/Lexer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https://www.doctrine-project.org/projects/lexer.html", + "keywords": [ + "annotations", + "docblock", + "lexer", + "parser", + "php" + ], + "support": { + "issues": "https://github.com/doctrine/lexer/issues", + "source": "https://github.com/doctrine/lexer/tree/1.2.3" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Flexer", + "type": "tidelift" + } + ], + "time": "2022-02-28T11:07:21+00:00" + }, + { + "name": "dragonmantank/cron-expression", + "version": "v3.3.3", + "source": { + "type": "git", + "url": "https://github.com/dragonmantank/cron-expression.git", + "reference": "adfb1f505deb6384dc8b39804c5065dd3c8c8c0a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/adfb1f505deb6384dc8b39804c5065dd3c8c8c0a", + "reference": "adfb1f505deb6384dc8b39804c5065dd3c8c8c0a", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0", + "webmozart/assert": "^1.0" + }, + "replace": { + "mtdowling/cron-expression": "^1.0" + }, + "require-dev": { + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-webmozart-assert": "^1.0", + "phpunit/phpunit": "^7.0|^8.0|^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Cron\\": "src/Cron/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Tankersley", + "email": "chris@ctankersley.com", + "homepage": "https://github.com/dragonmantank" + } + ], + "description": "CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due", + "keywords": [ + "cron", + "schedule" + ], + "support": { + "issues": "https://github.com/dragonmantank/cron-expression/issues", + "source": "https://github.com/dragonmantank/cron-expression/tree/v3.3.3" + }, + "funding": [ + { + "url": "https://github.com/dragonmantank", + "type": "github" + } + ], + "time": "2023-08-10T19:36:49+00:00" + }, + { + "name": "egulias/email-validator", + "version": "2.1.25", + "source": { + "type": "git", + "url": "https://github.com/egulias/EmailValidator.git", + "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "shasum": "" + }, + "require": { + "doctrine/lexer": "^1.0.1", + "php": ">=5.5", + "symfony/polyfill-intl-idn": "^1.10" + }, + "require-dev": { + "dominicsayers/isemail": "^3.0.7", + "phpunit/phpunit": "^4.8.36|^7.5.15", + "satooshi/php-coveralls": "^1.0.1" + }, + "suggest": { + "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Egulias\\EmailValidator\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eduardo Gulias Davis" + } + ], + "description": "A library for validating emails against several RFCs", + "homepage": "https://github.com/egulias/EmailValidator", + "keywords": [ + "email", + "emailvalidation", + "emailvalidator", + "validation", + "validator" + ], + "support": { + "issues": "https://github.com/egulias/EmailValidator/issues", + "source": "https://github.com/egulias/EmailValidator/tree/2.1.25" + }, + "funding": [ + { + "url": "https://github.com/egulias", + "type": "github" + } + ], + "time": "2020-12-29T14:50:06+00:00" + }, + { + "name": "fruitcake/laravel-cors", + "version": "v2.2.0", + "source": { + "type": "git", + "url": "https://github.com/fruitcake/laravel-cors.git", + "reference": "783a74f5e3431d7b9805be8afb60fd0a8f743534" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fruitcake/laravel-cors/zipball/783a74f5e3431d7b9805be8afb60fd0a8f743534", + "reference": "783a74f5e3431d7b9805be8afb60fd0a8f743534", + "shasum": "" + }, + "require": { + "asm89/stack-cors": "^2.0.1", + "illuminate/contracts": "^6|^7|^8|^9", + "illuminate/support": "^6|^7|^8|^9", + "php": ">=7.2" + }, + "require-dev": { + "laravel/framework": "^6|^7.24|^8", + "orchestra/testbench-dusk": "^4|^5|^6|^7", + "phpunit/phpunit": "^6|^7|^8|^9", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + }, + "laravel": { + "providers": [ + "Fruitcake\\Cors\\CorsServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Fruitcake\\Cors\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fruitcake", + "homepage": "https://fruitcake.nl" + }, + { + "name": "Barry vd. Heuvel", + "email": "barryvdh@gmail.com" + } + ], + "description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application", + "keywords": [ + "api", + "cors", + "crossdomain", + "laravel" + ], + "support": { + "issues": "https://github.com/fruitcake/laravel-cors/issues", + "source": "https://github.com/fruitcake/laravel-cors/tree/v2.2.0" + }, + "funding": [ + { + "url": "https://fruitcake.nl", + "type": "custom" + }, + { + "url": "https://github.com/barryvdh", + "type": "github" + } + ], + "abandoned": true, + "time": "2022-02-23T14:25:13+00:00" + }, + { + "name": "graham-campbell/result-type", + "version": "v1.1.2", + "source": { + "type": "git", + "url": "https://github.com/GrahamCampbell/Result-Type.git", + "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862", + "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "An Implementation Of The Result Type", + "keywords": [ + "Graham Campbell", + "GrahamCampbell", + "Result Type", + "Result-Type", + "result" + ], + "support": { + "issues": "https://github.com/GrahamCampbell/Result-Type/issues", + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", + "type": "tidelift" + } + ], + "time": "2023-11-12T22:16:48+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.8.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/41042bc7ab002487b876a0683fc8dce04ddce104", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.1", + "guzzlehttp/psr7": "^1.9.1 || ^2.5.1", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.36 || ^9.6.15", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.8.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2023-12-03T20:35:24+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/bbff78d96034045e58e13dedd6ad91b5d1253223", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2023-12-03T20:19:20+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.6.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/45b30f99ac27b5ca93cb4831afe16285f57b8221", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.6.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2023-12-03T20:05:35+00:00" + }, + { + "name": "laravel/framework", + "version": "v8.83.27", + "source": { + "type": "git", + "url": "https://github.com/laravel/framework.git", + "reference": "e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/framework/zipball/e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49", + "reference": "e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49", + "shasum": "" + }, + "require": { + "doctrine/inflector": "^1.4|^2.0", + "dragonmantank/cron-expression": "^3.0.2", + "egulias/email-validator": "^2.1.10", + "ext-json": "*", + "ext-mbstring": "*", + "ext-openssl": "*", + "laravel/serializable-closure": "^1.0", + "league/commonmark": "^1.3|^2.0.2", + "league/flysystem": "^1.1", + "monolog/monolog": "^2.0", + "nesbot/carbon": "^2.53.1", + "opis/closure": "^3.6", + "php": "^7.3|^8.0", + "psr/container": "^1.0", + "psr/log": "^1.0|^2.0", + "psr/simple-cache": "^1.0", + "ramsey/uuid": "^4.2.2", + "swiftmailer/swiftmailer": "^6.3", + "symfony/console": "^5.4", + "symfony/error-handler": "^5.4", + "symfony/finder": "^5.4", + "symfony/http-foundation": "^5.4", + "symfony/http-kernel": "^5.4", + "symfony/mime": "^5.4", + "symfony/process": "^5.4", + "symfony/routing": "^5.4", + "symfony/var-dumper": "^5.4", + "tijsverkoyen/css-to-inline-styles": "^2.2.2", + "vlucas/phpdotenv": "^5.4.1", + "voku/portable-ascii": "^1.6.1" + }, + "conflict": { + "tightenco/collect": "<5.5.33" + }, + "provide": { + "psr/container-implementation": "1.0", + "psr/simple-cache-implementation": "1.0" + }, + "replace": { + "illuminate/auth": "self.version", + "illuminate/broadcasting": "self.version", + "illuminate/bus": "self.version", + "illuminate/cache": "self.version", + "illuminate/collections": "self.version", + "illuminate/config": "self.version", + "illuminate/console": "self.version", + "illuminate/container": "self.version", + "illuminate/contracts": "self.version", + "illuminate/cookie": "self.version", + "illuminate/database": "self.version", + "illuminate/encryption": "self.version", + "illuminate/events": "self.version", + "illuminate/filesystem": "self.version", + "illuminate/hashing": "self.version", + "illuminate/http": "self.version", + "illuminate/log": "self.version", + "illuminate/macroable": "self.version", + "illuminate/mail": "self.version", + "illuminate/notifications": "self.version", + "illuminate/pagination": "self.version", + "illuminate/pipeline": "self.version", + "illuminate/queue": "self.version", + "illuminate/redis": "self.version", + "illuminate/routing": "self.version", + "illuminate/session": "self.version", + "illuminate/support": "self.version", + "illuminate/testing": "self.version", + "illuminate/translation": "self.version", + "illuminate/validation": "self.version", + "illuminate/view": "self.version" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.198.1", + "doctrine/dbal": "^2.13.3|^3.1.4", + "filp/whoops": "^2.14.3", + "guzzlehttp/guzzle": "^6.5.5|^7.0.1", + "league/flysystem-cached-adapter": "^1.0", + "mockery/mockery": "^1.4.4", + "orchestra/testbench-core": "^6.27", + "pda/pheanstalk": "^4.0", + "phpunit/phpunit": "^8.5.19|^9.5.8", + "predis/predis": "^1.1.9", + "symfony/cache": "^5.4" + }, + "suggest": { + "ably/ably-php": "Required to use the Ably broadcast driver (^1.0).", + "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.198.1).", + "brianium/paratest": "Required to run tests in parallel (^6.0).", + "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.13.3|^3.1.4).", + "ext-bcmath": "Required to use the multiple_of validation rule.", + "ext-ftp": "Required to use the Flysystem FTP driver.", + "ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().", + "ext-memcached": "Required to use the memcache cache driver.", + "ext-pcntl": "Required to use all features of the queue worker.", + "ext-posix": "Required to use all features of the queue worker.", + "ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).", + "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", + "filp/whoops": "Required for friendly error pages in development (^2.14.3).", + "guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.5.5|^7.0.1).", + "laravel/tinker": "Required to use the tinker console command (^2.0).", + "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", + "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", + "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", + "mockery/mockery": "Required to use mocking (^1.4.4).", + "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", + "pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).", + "phpunit/phpunit": "Required to use assertions and run tests (^8.5.19|^9.5.8).", + "predis/predis": "Required to use the predis connector (^1.1.9).", + "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", + "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0|^5.0|^6.0|^7.0).", + "symfony/cache": "Required to PSR-6 cache bridge (^5.4).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^5.4).", + "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0).", + "wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "autoload": { + "files": [ + "src/Illuminate/Collections/helpers.php", + "src/Illuminate/Events/functions.php", + "src/Illuminate/Foundation/helpers.php", + "src/Illuminate/Support/helpers.php" + ], + "psr-4": { + "Illuminate\\": "src/Illuminate/", + "Illuminate\\Support\\": [ + "src/Illuminate/Macroable/", + "src/Illuminate/Collections/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Laravel Framework.", + "homepage": "https://laravel.com", + "keywords": [ + "framework", + "laravel" + ], + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "time": "2022-12-08T15:28:55+00:00" + }, + { + "name": "laravel/laravel", + "version": "v8.6.10", + "source": { + "type": "git", + "url": "https://github.com/laravel/laravel.git", + "reference": "56a73db2e34f5aa8befffcce40aaaa92e2d7393c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/laravel/zipball/56a73db2e34f5aa8befffcce40aaaa92e2d7393c", + "reference": "56a73db2e34f5aa8befffcce40aaaa92e2d7393c", + "shasum": "" + }, + "require": { + "fruitcake/laravel-cors": "^2.0", + "guzzlehttp/guzzle": "^7.0.1", + "laravel/framework": "^8.75", + "laravel/sanctum": "^2.11", + "laravel/tinker": "^2.5", + "php": "^7.3|^8.0" + }, + "require-dev": { + "facade/ignition": "^2.5", + "fakerphp/faker": "^1.9.1", + "laravel/sail": "^1.0.1", + "mockery/mockery": "^1.4.4", + "nunomaduro/collision": "^5.10", + "phpunit/phpunit": "^9.5.10" + }, + "type": "project", + "extra": { + "laravel": { + "dont-discover": [] + } + }, + "autoload": { + "psr-4": { + "App\\": "app/", + "Database\\Seeders\\": "database/seeders/", + "Database\\Factories\\": "database/factories/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The Laravel Framework.", + "keywords": [ + "framework", + "laravel" + ], + "support": { + "source": "https://github.com/laravel/laravel/tree/v8.6.10" + }, + "time": "2021-12-22T10:07:28+00:00" + }, + { + "name": "laravel/sanctum", + "version": "v2.15.1", + "source": { + "type": "git", + "url": "https://github.com/laravel/sanctum.git", + "reference": "31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/sanctum/zipball/31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473", + "reference": "31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/console": "^6.9|^7.0|^8.0|^9.0", + "illuminate/contracts": "^6.9|^7.0|^8.0|^9.0", + "illuminate/database": "^6.9|^7.0|^8.0|^9.0", + "illuminate/support": "^6.9|^7.0|^8.0|^9.0", + "php": "^7.2|^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0", + "phpunit/phpunit": "^8.0|^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + }, + "laravel": { + "providers": [ + "Laravel\\Sanctum\\SanctumServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Laravel\\Sanctum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.", + "keywords": [ + "auth", + "laravel", + "sanctum" + ], + "support": { + "issues": "https://github.com/laravel/sanctum/issues", + "source": "https://github.com/laravel/sanctum" + }, + "time": "2022-04-08T13:39:49+00:00" + }, + { + "name": "laravel/serializable-closure", + "version": "v1.3.3", + "source": { + "type": "git", + "url": "https://github.com/laravel/serializable-closure.git", + "reference": "3dbf8a8e914634c48d389c1234552666b3d43754" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/3dbf8a8e914634c48d389c1234552666b3d43754", + "reference": "3dbf8a8e914634c48d389c1234552666b3d43754", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "nesbot/carbon": "^2.61", + "pestphp/pest": "^1.21.3", + "phpstan/phpstan": "^1.8.2", + "symfony/var-dumper": "^5.4.11" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": [ + "closure", + "laravel", + "serializable" + ], + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "time": "2023-11-08T14:08:06+00:00" + }, + { + "name": "laravel/tinker", + "version": "v2.9.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/tinker.git", + "reference": "502e0fe3f0415d06d5db1f83a472f0f3b754bafe" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/tinker/zipball/502e0fe3f0415d06d5db1f83a472f0f3b754bafe", + "reference": "502e0fe3f0415d06d5db1f83a472f0f3b754bafe", + "shasum": "" + }, + "require": { + "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/contracts": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "php": "^7.2.5|^8.0", + "psy/psysh": "^0.11.1|^0.12.0", + "symfony/var-dumper": "^4.3.4|^5.0|^6.0|^7.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.3|^1.4.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^8.5.8|^9.3.3" + }, + "suggest": { + "illuminate/database": "The Illuminate Database package (^6.0|^7.0|^8.0|^9.0|^10.0|^11.0)." + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Tinker\\TinkerServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Laravel\\Tinker\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Powerful REPL for the Laravel framework.", + "keywords": [ + "REPL", + "Tinker", + "laravel", + "psysh" + ], + "support": { + "issues": "https://github.com/laravel/tinker/issues", + "source": "https://github.com/laravel/tinker/tree/v2.9.0" + }, + "time": "2024-01-04T16:10:04+00:00" + }, + { + "name": "league/commonmark", + "version": "2.4.2", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/commonmark.git", + "reference": "91c24291965bd6d7c46c46a12ba7492f83b1cadf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/91c24291965bd6d7c46c46a12ba7492f83b1cadf", + "reference": "91c24291965bd6d7c46c46a12ba7492f83b1cadf", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "league/config": "^1.1.1", + "php": "^7.4 || ^8.0", + "psr/event-dispatcher": "^1.0", + "symfony/deprecation-contracts": "^2.1 || ^3.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "cebe/markdown": "^1.0", + "commonmark/cmark": "0.30.3", + "commonmark/commonmark.js": "0.30.0", + "composer/package-versions-deprecated": "^1.8", + "embed/embed": "^4.4", + "erusev/parsedown": "^1.0", + "ext-json": "*", + "github/gfm": "0.29.0", + "michelf/php-markdown": "^1.4 || ^2.0", + "nyholm/psr7": "^1.5", + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.21 || ^10.5.9 || ^11.0.0", + "scrutinizer/ocular": "^1.8.1", + "symfony/finder": "^5.3 | ^6.0 || ^7.0", + "symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0 || ^7.0", + "unleashedtech/php-coding-standard": "^3.1.1", + "vimeo/psalm": "^4.24.0 || ^5.0.0" + }, + "suggest": { + "symfony/yaml": "v2.3+ required if using the Front Matter extension" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + } + }, + "autoload": { + "psr-4": { + "League\\CommonMark\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)", + "homepage": "https://commonmark.thephpleague.com", + "keywords": [ + "commonmark", + "flavored", + "gfm", + "github", + "github-flavored", + "markdown", + "md", + "parser" + ], + "support": { + "docs": "https://commonmark.thephpleague.com/", + "forum": "https://github.com/thephpleague/commonmark/discussions", + "issues": "https://github.com/thephpleague/commonmark/issues", + "rss": "https://github.com/thephpleague/commonmark/releases.atom", + "source": "https://github.com/thephpleague/commonmark" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/commonmark", + "type": "tidelift" + } + ], + "time": "2024-02-02T11:59:32+00:00" + }, + { + "name": "league/config", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/config.git", + "reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/config/zipball/754b3604fb2984c71f4af4a9cbe7b57f346ec1f3", + "reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3", + "shasum": "" + }, + "require": { + "dflydev/dot-access-data": "^3.0.1", + "nette/schema": "^1.2", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + } + }, + "autoload": { + "psr-4": { + "League\\Config\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Define configuration arrays with strict schemas and access values with dot notation", + "homepage": "https://config.thephpleague.com", + "keywords": [ + "array", + "config", + "configuration", + "dot", + "dot-access", + "nested", + "schema" + ], + "support": { + "docs": "https://config.thephpleague.com/", + "issues": "https://github.com/thephpleague/config/issues", + "rss": "https://github.com/thephpleague/config/releases.atom", + "source": "https://github.com/thephpleague/config" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + } + ], + "time": "2022-12-11T20:36:23+00:00" + }, + { + "name": "league/flysystem", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/flysystem.git", + "reference": "9be3b16c877d477357c015cec057548cf9b2a14a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/9be3b16c877d477357c015cec057548cf9b2a14a", + "reference": "9be3b16c877d477357c015cec057548cf9b2a14a", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "league/mime-type-detection": "^1.3", + "php": "^7.2.5 || ^8.0" + }, + "conflict": { + "league/flysystem-sftp": "<1.0.6" + }, + "require-dev": { + "phpspec/prophecy": "^1.11.1", + "phpunit/phpunit": "^8.5.8" + }, + "suggest": { + "ext-ftp": "Allows you to use FTP server storage", + "ext-openssl": "Allows you to use FTPS server storage", + "league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2", + "league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3", + "league/flysystem-azure": "Allows you to use Windows Azure Blob storage", + "league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching", + "league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem", + "league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files", + "league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib", + "league/flysystem-webdav": "Allows you to use WebDAV storage", + "league/flysystem-ziparchive": "Allows you to use ZipArchive adapter", + "spatie/flysystem-dropbox": "Allows you to use Dropbox storage", + "srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "League\\Flysystem\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frenky.net" + } + ], + "description": "Filesystem abstraction: Many filesystems, one API.", + "keywords": [ + "Cloud Files", + "WebDAV", + "abstraction", + "aws", + "cloud", + "copy.com", + "dropbox", + "file systems", + "files", + "filesystem", + "filesystems", + "ftp", + "rackspace", + "remote", + "s3", + "sftp", + "storage" + ], + "support": { + "issues": "https://github.com/thephpleague/flysystem/issues", + "source": "https://github.com/thephpleague/flysystem/tree/1.1.10" + }, + "funding": [ + { + "url": "https://offset.earth/frankdejonge", + "type": "other" + } + ], + "time": "2022-10-04T09:16:37+00:00" + }, + { + "name": "league/mime-type-detection", + "version": "1.15.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/mime-type-detection.git", + "reference": "ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/mime-type-detection/zipball/ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301", + "reference": "ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.2", + "phpstan/phpstan": "^0.12.68", + "phpunit/phpunit": "^8.5.8 || ^9.3 || ^10.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\MimeTypeDetection\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "Mime-type detection for Flysystem", + "support": { + "issues": "https://github.com/thephpleague/mime-type-detection/issues", + "source": "https://github.com/thephpleague/mime-type-detection/tree/1.15.0" + }, + "funding": [ + { + "url": "https://github.com/frankdejonge", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/flysystem", + "type": "tidelift" + } + ], + "time": "2024-01-28T23:22:08+00:00" + }, + { + "name": "monolog/monolog", + "version": "2.9.2", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", + "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", + "shasum": "" + }, + "require": { + "php": ">=7.2", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" + }, + "provide": { + "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + }, + "require-dev": { + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "elasticsearch/elasticsearch": "^7 || ^8", + "ext-json": "*", + "graylog2/gelf-php": "^1.4.2 || ^2@dev", + "guzzlehttp/guzzle": "^7.4", + "guzzlehttp/psr7": "^2.2", + "mongodb/mongodb": "^1.8", + "php-amqplib/php-amqplib": "~2.4 || ^3", + "phpspec/prophecy": "^1.15", + "phpstan/phpstan": "^0.12.91", + "phpunit/phpunit": "^8.5.14", + "predis/predis": "^1.1 || ^2.0", + "rollbar/rollbar": "^1.3 || ^2 || ^3", + "ruflin/elastica": "^7", + "swiftmailer/swiftmailer": "^5.3|^6.0", + "symfony/mailer": "^5.4 || ^6", + "symfony/mime": "^5.4 || ^6" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler", + "ext-mbstring": "Allow to work properly with unicode symbols", + "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)", + "ext-openssl": "Required to send log messages using SSL", + "ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "https://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "support": { + "issues": "https://github.com/Seldaek/monolog/issues", + "source": "https://github.com/Seldaek/monolog/tree/2.9.2" + }, + "funding": [ + { + "url": "https://github.com/Seldaek", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/monolog/monolog", + "type": "tidelift" + } + ], + "time": "2023-10-27T15:25:26+00:00" + }, + { + "name": "nesbot/carbon", + "version": "2.72.3", + "source": { + "type": "git", + "url": "https://github.com/briannesbitt/Carbon.git", + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/0c6fd108360c562f6e4fd1dedb8233b423e91c83", + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83", + "shasum": "" + }, + "require": { + "carbonphp/carbon-doctrine-types": "*", + "ext-json": "*", + "php": "^7.1.8 || ^8.0", + "psr/clock": "^1.0", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.16", + "symfony/translation": "^3.4 || ^4.0 || ^5.0 || ^6.0" + }, + "provide": { + "psr/clock-implementation": "1.0" + }, + "require-dev": { + "doctrine/dbal": "^2.0 || ^3.1.4 || ^4.0", + "doctrine/orm": "^2.7 || ^3.0", + "friendsofphp/php-cs-fixer": "^3.0", + "kylekatarnls/multi-tester": "^2.0", + "ondrejmirtes/better-reflection": "*", + "phpmd/phpmd": "^2.9", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12.99 || ^1.7.14", + "phpunit/php-file-iterator": "^2.0.5 || ^3.0.6", + "phpunit/phpunit": "^7.5.20 || ^8.5.26 || ^9.5.20", + "squizlabs/php_codesniffer": "^3.4" + }, + "bin": [ + "bin/carbon" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-3.x": "3.x-dev", + "dev-master": "2.x-dev" + }, + "laravel": { + "providers": [ + "Carbon\\Laravel\\ServiceProvider" + ] + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "autoload": { + "psr-4": { + "Carbon\\": "src/Carbon/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brian Nesbitt", + "email": "brian@nesbot.com", + "homepage": "https://markido.com" + }, + { + "name": "kylekatarnls", + "homepage": "https://github.com/kylekatarnls" + } + ], + "description": "An API extension for DateTime that supports 281 different languages.", + "homepage": "https://carbon.nesbot.com", + "keywords": [ + "date", + "datetime", + "time" + ], + "support": { + "docs": "https://carbon.nesbot.com/docs", + "issues": "https://github.com/briannesbitt/Carbon/issues", + "source": "https://github.com/briannesbitt/Carbon" + }, + "funding": [ + { + "url": "https://github.com/sponsors/kylekatarnls", + "type": "github" + }, + { + "url": "https://opencollective.com/Carbon#sponsor", + "type": "opencollective" + }, + { + "url": "https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme", + "type": "tidelift" + } + ], + "time": "2024-01-25T10:35:09+00:00" + }, + { + "name": "nette/schema", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/nette/schema.git", + "reference": "a6d3a6d1f545f01ef38e60f375d1cf1f4de98188" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/schema/zipball/a6d3a6d1f545f01ef38e60f375d1cf1f4de98188", + "reference": "a6d3a6d1f545f01ef38e60f375d1cf1f4de98188", + "shasum": "" + }, + "require": { + "nette/utils": "^4.0", + "php": "8.1 - 8.3" + }, + "require-dev": { + "nette/tester": "^2.4", + "phpstan/phpstan-nette": "^1.0", + "tracy/tracy": "^2.8" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "📐 Nette Schema: validating data structures against a given Schema.", + "homepage": "https://nette.org", + "keywords": [ + "config", + "nette" + ], + "support": { + "issues": "https://github.com/nette/schema/issues", + "source": "https://github.com/nette/schema/tree/v1.3.0" + }, + "time": "2023-12-11T11:54:22+00:00" + }, + { + "name": "nette/utils", + "version": "v4.0.4", + "source": { + "type": "git", + "url": "https://github.com/nette/utils.git", + "reference": "d3ad0aa3b9f934602cb3e3902ebccf10be34d218" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/utils/zipball/d3ad0aa3b9f934602cb3e3902ebccf10be34d218", + "reference": "d3ad0aa3b9f934602cb3e3902ebccf10be34d218", + "shasum": "" + }, + "require": { + "php": ">=8.0 <8.4" + }, + "conflict": { + "nette/finder": "<3", + "nette/schema": "<1.2.2" + }, + "require-dev": { + "jetbrains/phpstorm-attributes": "dev-master", + "nette/tester": "^2.5", + "phpstan/phpstan": "^1.0", + "tracy/tracy": "^2.9" + }, + "suggest": { + "ext-gd": "to use Image", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "homepage": "https://nette.org", + "keywords": [ + "array", + "core", + "datetime", + "images", + "json", + "nette", + "paginator", + "password", + "slugify", + "string", + "unicode", + "utf-8", + "utility", + "validation" + ], + "support": { + "issues": "https://github.com/nette/utils/issues", + "source": "https://github.com/nette/utils/tree/v4.0.4" + }, + "time": "2024-01-17T16:50:36+00:00" + }, + { + "name": "nikic/php-parser", + "version": "v5.0.2", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "139676794dc1e9231bf7bcd123cfc0c99182cb13" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/139676794dc1e9231bf7bcd123cfc0c99182cb13", + "reference": "139676794dc1e9231bf7bcd123cfc0c99182cb13", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v5.0.2" + }, + "time": "2024-03-05T20:51:40+00:00" + }, + { + "name": "opis/closure", + "version": "3.6.3", + "source": { + "type": "git", + "url": "https://github.com/opis/closure.git", + "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opis/closure/zipball/3d81e4309d2a927abbe66df935f4bb60082805ad", + "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad", + "shasum": "" + }, + "require": { + "php": "^5.4 || ^7.0 || ^8.0" + }, + "require-dev": { + "jeremeamia/superclosure": "^2.0", + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.6.x-dev" + } + }, + "autoload": { + "files": [ + "functions.php" + ], + "psr-4": { + "Opis\\Closure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marius Sarca", + "email": "marius.sarca@gmail.com" + }, + { + "name": "Sorin Sarca", + "email": "sarca_sorin@hotmail.com" + } + ], + "description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.", + "homepage": "https://opis.io/closure", + "keywords": [ + "anonymous functions", + "closure", + "function", + "serializable", + "serialization", + "serialize" + ], + "support": { + "issues": "https://github.com/opis/closure/issues", + "source": "https://github.com/opis/closure/tree/3.6.3" + }, + "time": "2022-01-27T09:35:39+00:00" + }, { "name": "phpmailer/phpmailer", "version": "v6.4.1", "source": { "type": "git", - "url": "https://github.com/PHPMailer/PHPMailer.git", - "reference": "9256f12d8fb0cd0500f93b19e18c356906cbed3d" + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "9256f12d8fb0cd0500f93b19e18c356906cbed3d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/9256f12d8fb0cd0500f93b19e18c356906cbed3d", + "reference": "9256f12d8fb0cd0500f93b19e18c356906cbed3d", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.5.6", + "yoast/phpunit-polyfills": "^0.2.0" + }, + "suggest": { + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "support": { + "issues": "https://github.com/PHPMailer/PHPMailer/issues", + "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.4.1" + }, + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "time": "2021-04-29T12:25:04+00:00" + }, + { + "name": "phpoption/phpoption", + "version": "1.9.2", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820", + "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + }, + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "support": { + "issues": "https://github.com/schmittjoh/php-option/issues", + "source": "https://github.com/schmittjoh/php-option/tree/1.9.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", + "type": "tidelift" + } + ], + "time": "2023-11-12T21:59:55+00:00" + }, + { + "name": "psr/clock", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/clock.git", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/clock/zipball/e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for reading the clock.", + "homepage": "https://github.com/php-fig/clock", + "keywords": [ + "clock", + "now", + "psr", + "psr-20", + "time" + ], + "support": { + "issues": "https://github.com/php-fig/clock/issues", + "source": "https://github.com/php-fig/clock/tree/1.0.0" + }, + "time": "2022-11-25T14:36:26+00:00" + }, + { + "name": "psr/container", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/513e0666f7216c7459170d56df27dfcefe1689ea", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "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/1.1.2" + }, + "time": "2021-11-05T16:50:12+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/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "e616d01114759c4c489f93b099585439f795fe35" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35", + "reference": "e616d01114759c4c489f93b099585439f795fe35", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/1.0.2" + }, + "time": "2023-04-10T20:10:41+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "psr/log", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/ef29f6d262798707a9edd554e2b82517ef3a9376", + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.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/2.0.0" + }, + "time": "2021-07-14T16:41:46+00:00" + }, + { + "name": "psr/simple-cache", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/simple-cache.git", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\SimpleCache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for simple caching", + "keywords": [ + "cache", + "caching", + "psr", + "psr-16", + "simple-cache" + ], + "support": { + "source": "https://github.com/php-fig/simple-cache/tree/master" + }, + "time": "2017-10-23T01:57:42+00:00" + }, + { + "name": "psy/psysh", + "version": "v0.12.0", + "source": { + "type": "git", + "url": "https://github.com/bobthecow/psysh.git", + "reference": "750bf031a48fd07c673dbe3f11f72362ea306d0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bobthecow/psysh/zipball/750bf031a48fd07c673dbe3f11f72362ea306d0d", + "reference": "750bf031a48fd07c673dbe3f11f72362ea306d0d", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-tokenizer": "*", + "nikic/php-parser": "^5.0 || ^4.0", + "php": "^8.0 || ^7.4", + "symfony/console": "^7.0 || ^6.0 || ^5.0 || ^4.0 || ^3.4", + "symfony/var-dumper": "^7.0 || ^6.0 || ^5.0 || ^4.0 || ^3.4" + }, + "conflict": { + "symfony/console": "4.4.37 || 5.3.14 || 5.3.15 || 5.4.3 || 5.4.4 || 6.0.3 || 6.0.4" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.2" + }, + "suggest": { + "ext-pcntl": "Enabling the PCNTL extension makes PsySH a lot happier :)", + "ext-pdo-sqlite": "The doc command requires SQLite to work.", + "ext-posix": "If you have PCNTL, you'll want the POSIX extension as well." + }, + "bin": [ + "bin/psysh" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "0.12.x-dev" + }, + "bamarni-bin": { + "bin-links": false, + "forward-command": false + } + }, + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Psy\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Justin Hileman", + "email": "justin@justinhileman.info", + "homepage": "http://justinhileman.com" + } + ], + "description": "An interactive shell for modern PHP.", + "homepage": "http://psysh.org", + "keywords": [ + "REPL", + "console", + "interactive", + "shell" + ], + "support": { + "issues": "https://github.com/bobthecow/psysh/issues", + "source": "https://github.com/bobthecow/psysh/tree/v0.12.0" + }, + "time": "2023-12-20T15:28:09+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "ramsey/collection", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/collection.git", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/collection/zipball/a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "captainhook/plugin-composer": "^5.3", + "ergebnis/composer-normalize": "^2.28.3", + "fakerphp/faker": "^1.21", + "hamcrest/hamcrest-php": "^2.0", + "jangregor/phpstan-prophecy": "^1.0", + "mockery/mockery": "^1.5", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpcsstandards/phpcsutils": "^1.0.0-rc1", + "phpspec/prophecy-phpunit": "^2.0", + "phpstan/extension-installer": "^1.2", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.3", + "phpunit/phpunit": "^9.5", + "psalm/plugin-mockery": "^1.1", + "psalm/plugin-phpunit": "^0.18.4", + "ramsey/coding-standard": "^2.0.3", + "ramsey/conventional-commits": "^1.3", + "vimeo/psalm": "^5.4" + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + }, + "ramsey/conventional-commits": { + "configFile": "conventional-commits.json" + } + }, + "autoload": { + "psr-4": { + "Ramsey\\Collection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" + } + ], + "description": "A PHP library for representing and manipulating collections.", + "keywords": [ + "array", + "collection", + "hash", + "map", + "queue", + "set" + ], + "support": { + "issues": "https://github.com/ramsey/collection/issues", + "source": "https://github.com/ramsey/collection/tree/2.0.0" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/collection", + "type": "tidelift" + } + ], + "time": "2022-12-31T21:50:55+00:00" + }, + { + "name": "ramsey/uuid", + "version": "4.7.5", + "source": { + "type": "git", + "url": "https://github.com/ramsey/uuid.git", + "reference": "5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e", + "reference": "5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e", + "shasum": "" + }, + "require": { + "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11", + "ext-json": "*", + "php": "^8.0", + "ramsey/collection": "^1.2 || ^2.0" + }, + "replace": { + "rhumsaa/uuid": "self.version" + }, + "require-dev": { + "captainhook/captainhook": "^5.10", + "captainhook/plugin-composer": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.8", + "ergebnis/composer-normalize": "^2.15", + "mockery/mockery": "^1.3", + "paragonie/random-lib": "^2", + "php-mock/php-mock": "^2.2", + "php-mock/php-mock-mockery": "^1.3", + "php-parallel-lint/php-parallel-lint": "^1.1", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.1", + "phpunit/phpunit": "^8.5 || ^9", + "ramsey/composer-repl": "^1.4", + "slevomat/coding-standard": "^8.4", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.9" + }, + "suggest": { + "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", + "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + } + }, + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Ramsey\\Uuid\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "keywords": [ + "guid", + "identifier", + "uuid" + ], + "support": { + "issues": "https://github.com/ramsey/uuid/issues", + "source": "https://github.com/ramsey/uuid/tree/4.7.5" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/uuid", + "type": "tidelift" + } + ], + "time": "2023-11-08T05:53:05+00:00" + }, + { + "name": "swiftmailer/swiftmailer", + "version": "v6.3.0", + "source": { + "type": "git", + "url": "https://github.com/swiftmailer/swiftmailer.git", + "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/8a5d5072dca8f48460fce2f4131fcc495eec654c", + "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c", + "shasum": "" + }, + "require": { + "egulias/email-validator": "^2.0|^3.1", + "php": ">=7.0.0", + "symfony/polyfill-iconv": "^1.0", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "symfony/phpunit-bridge": "^4.4|^5.4" + }, + "suggest": { + "ext-intl": "Needed to support internationalized email addresses" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + }, + "autoload": { + "files": [ + "lib/swift_required.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Corbyn" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Swiftmailer, free feature-rich PHP mailer", + "homepage": "https://swiftmailer.symfony.com", + "keywords": [ + "email", + "mail", + "mailer" + ], + "support": { + "issues": "https://github.com/swiftmailer/swiftmailer/issues", + "source": "https://github.com/swiftmailer/swiftmailer/tree/v6.3.0" + }, + "funding": [ + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/swiftmailer/swiftmailer", + "type": "tidelift" + } + ], + "abandoned": "symfony/mailer", + "time": "2021-10-18T15:26:12+00:00" + }, + { + "name": "symfony/console", + "version": "v5.4.36", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e", + "reference": "39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.16", + "symfony/service-contracts": "^1.1|^2|^3", + "symfony/string": "^5.1|^6.0" + }, + "conflict": { + "psr/log": ">=3", + "symfony/dependency-injection": "<4.4", + "symfony/dotenv": "<5.1", + "symfony/event-dispatcher": "<4.4", + "symfony/lock": "<4.4", + "symfony/process": "<4.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0" + }, + "require-dev": { + "psr/log": "^1|^2", + "symfony/config": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/event-dispatcher": "^4.4|^5.0|^6.0", + "symfony/lock": "^4.4|^5.0|^6.0", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/var-dumper": "^4.4|^5.0|^6.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/lock": "", + "symfony/process": "" + }, + "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/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-20T16:33:57+00:00" + }, + { + "name": "symfony/css-selector", + "version": "v7.0.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/css-selector.git", + "reference": "ec60a4edf94e63b0556b6a0888548bb400a3a3be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/ec60a4edf94e63b0556b6a0888548bb400a3a3be", + "reference": "ec60a4edf94e63b0556b6a0888548bb400a3a3be", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\CssSelector\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Converts CSS selectors to XPath expressions", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/css-selector/tree/v7.0.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-23T15:02:46+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-05-23T14:45:45+00:00" + }, + { + "name": "symfony/error-handler", + "version": "v5.4.36", + "source": { + "type": "git", + "url": "https://github.com/symfony/error-handler.git", + "reference": "90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1", + "reference": "90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "^1|^2|^3", + "symfony/var-dumper": "^4.4|^5.0|^6.0" + }, + "require-dev": { + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/http-kernel": "^4.4|^5.0|^6.0", + "symfony/serializer": "^4.4|^5.0|^6.0" + }, + "bin": [ + "Resources/bin/patch-type-declarations" + ], + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\ErrorHandler\\": "" + }, + "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 to manage errors and ease debugging PHP code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/error-handler/tree/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-22T11:40:53+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v6.4.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "ae9d3a6f3003a6caf56acd7466d8d52378d44fef" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/ae9d3a6f3003a6caf56acd7466d8d52378d44fef", + "reference": "ae9d3a6f3003a6caf56acd7466d8d52378d44fef", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/dependency-injection": "<5.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": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/expression-language": "^5.4|^6.0|^7.0", + "symfony/http-foundation": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^5.4|^6.0|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v6.4.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-23T14:51:35+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/a76aed96a42d2b521153fb382d418e30d18b59df", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-05-23T14:45:45+00:00" + }, + { + "name": "symfony/finder", + "version": "v5.4.35", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "abe6d6f77d9465fed3cd2d029b29d03b56b56435" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/abe6d6f77d9465fed3cd2d029b29d03b56b56435", + "reference": "abe6d6f77d9465fed3cd2d029b29d03b56b56435", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "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/v5.4.35" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-23T13:51:25+00:00" + }, + { + "name": "symfony/http-foundation", + "version": "v5.4.35", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-foundation.git", + "reference": "f2ab692a22aef1cd54beb893aa0068bdfb093928" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/f2ab692a22aef1cd54beb893aa0068bdfb093928", + "reference": "f2ab692a22aef1cd54beb893aa0068bdfb093928", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "predis/predis": "~1.0", + "symfony/cache": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/http-kernel": "^5.4.12|^6.0.12|^6.1.4", + "symfony/mime": "^4.4|^5.0|^6.0", + "symfony/rate-limiter": "^5.2|^6.0" + }, + "suggest": { + "symfony/mime": "To use the file extension guesser" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpFoundation\\": "" + }, + "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": "Defines an object-oriented layer for the HTTP specification", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-foundation/tree/v5.4.35" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-23T13:51:25+00:00" + }, + { + "name": "symfony/http-kernel", + "version": "v5.4.37", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-kernel.git", + "reference": "4ef7ed872564852b3c6c15fecf492975a52cbff3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/4ef7ed872564852b3c6c15fecf492975a52cbff3", + "reference": "4ef7ed872564852b3c6c15fecf492975a52cbff3", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "^1|^2", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/error-handler": "^4.4|^5.0|^6.0", + "symfony/event-dispatcher": "^5.0|^6.0", + "symfony/http-foundation": "^5.4.21|^6.2.7", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "symfony/browser-kit": "<5.4", + "symfony/cache": "<5.0", + "symfony/config": "<5.0", + "symfony/console": "<4.4", + "symfony/dependency-injection": "<5.3", + "symfony/doctrine-bridge": "<5.0", + "symfony/form": "<5.0", + "symfony/http-client": "<5.0", + "symfony/mailer": "<5.0", + "symfony/messenger": "<5.0", + "symfony/translation": "<5.0", + "symfony/twig-bridge": "<5.0", + "symfony/validator": "<5.0", + "twig/twig": "<2.13" + }, + "provide": { + "psr/log-implementation": "1.0|2.0" + }, + "require-dev": { + "psr/cache": "^1.0|^2.0|^3.0", + "symfony/browser-kit": "^5.4|^6.0", + "symfony/config": "^5.0|^6.0", + "symfony/console": "^4.4|^5.0|^6.0", + "symfony/css-selector": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.3|^6.0", + "symfony/dom-crawler": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/finder": "^4.4|^5.0|^6.0", + "symfony/http-client-contracts": "^1.1|^2|^3", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/routing": "^4.4|^5.0|^6.0", + "symfony/stopwatch": "^4.4|^5.0|^6.0", + "symfony/translation": "^4.4|^5.0|^6.0", + "symfony/translation-contracts": "^1.1|^2|^3", + "twig/twig": "^2.13|^3.0.4" + }, + "suggest": { + "symfony/browser-kit": "", + "symfony/config": "", + "symfony/console": "", + "symfony/dependency-injection": "" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpKernel\\": "" + }, + "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 structured process for converting a Request into a Response", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-kernel/tree/v5.4.37" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-03-04T20:55:44+00:00" + }, + { + "name": "symfony/mime", + "version": "v5.4.35", + "source": { + "type": "git", + "url": "https://github.com/symfony/mime.git", + "reference": "ee94d9b538f93abbbc1ee4ccff374593117b04a9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mime/zipball/ee94d9b538f93abbbc1ee4ccff374593117b04a9", + "reference": "ee94d9b538f93abbbc1ee4ccff374593117b04a9", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "egulias/email-validator": "~3.0.0", + "phpdocumentor/reflection-docblock": "<3.2.2", + "phpdocumentor/type-resolver": "<1.4.0", + "symfony/mailer": "<4.4", + "symfony/serializer": "<5.4.35|>=6,<6.3.12|>=6.4,<6.4.3" + }, + "require-dev": { + "egulias/email-validator": "^2.1.10|^3.1|^4", + "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/property-access": "^4.4|^5.1|^6.0", + "symfony/property-info": "^4.4|^5.1|^6.0", + "symfony/serializer": "^5.4.35|~6.3.12|^6.4.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mime\\": "" + }, + "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": "Allows manipulating MIME messages", + "homepage": "https://symfony.com", + "keywords": [ + "mime", + "mime-type" + ], + "support": { + "source": "https://github.com/symfony/mime/tree/v5.4.35" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-30T08:00:51+00:00" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "ef4d7e442ca910c4764bce785146269b30cb5fc4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ef4d7e442ca910c4764bce785146269b30cb5fc4", + "reference": "ef4d7e442ca910c4764bce785146269b30cb5fc4", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-iconv", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-iconv.git", + "reference": "cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-iconv/zipball/cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f", + "reference": "cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-iconv": "*" + }, + "suggest": { + "ext-iconv": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Iconv\\": "" + } + }, + "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 Iconv extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "iconv", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-iconv/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "32a9da87d7b3245e09ac426c83d334ae9f06f80f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/32a9da87d7b3245e09ac426c83d334ae9f06f80f", + "reference": "32a9da87d7b3245e09ac426c83d334ae9f06f80f", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-intl-idn", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-idn.git", + "reference": "a287ed7475f85bf6f61890146edbc932c0fff919" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/a287ed7475f85bf6f61890146edbc932c0fff919", + "reference": "a287ed7475f85bf6f61890146edbc932c0fff919", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "symfony/polyfill-intl-normalizer": "^1.10", + "symfony/polyfill-php72": "^1.10" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Idn\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Laurent Bassin", + "email": "laurent@bassin.info" + }, + { + "name": "Trevor Rowbotham", + "email": "trevor.rowbotham@pm.me" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "idn", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "bc45c394692b948b4d383a08d7753968bed9a83d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/bc45c394692b948b4d383a08d7753968bed9a83d", + "reference": "bc45c394692b948b4d383a08d7753968bed9a83d", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9773676c8a1bb1f8d4340a62efe641cf76eda7ec", + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-php72", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "861391a8da9a04cbad2d232ddd9e4893220d6e25" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/861391a8da9a04cbad2d232ddd9e4893220d6e25", + "reference": "861391a8da9a04cbad2d232ddd9e4893220d6e25", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php72\\": "" + } + }, + "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 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php72/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-php73", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php73.git", + "reference": "21bd091060673a1177ae842c0ef8fe30893114d2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/21bd091060673a1177ae842c0ef8fe30893114d2", + "reference": "21bd091060673a1177ae842c0ef8fe30893114d2", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php73\\": "" + }, + "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 7.3+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php73/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.29.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-29T20:11:03+00:00" + }, + { + "name": "symfony/process", + "version": "v5.4.36", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "4fdf34004f149cc20b2f51d7d119aa500caad975" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/4fdf34004f149cc20b2f51d7d119aa500caad975", + "reference": "4fdf34004f149cc20b2f51d7d119aa500caad975", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-php80": "^1.16" + }, + "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/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-12T15:49:53+00:00" + }, + { + "name": "symfony/routing", + "version": "v5.4.37", + "source": { + "type": "git", + "url": "https://github.com/symfony/routing.git", + "reference": "48ae43e443693ddb4e574f7c12f0d17ce287694e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/routing/zipball/48ae43e443693ddb4e574f7c12f0d17ce287694e", + "reference": "48ae43e443693ddb4e574f7c12f0d17ce287694e", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "doctrine/annotations": "<1.12", + "symfony/config": "<5.3", + "symfony/dependency-injection": "<4.4", + "symfony/yaml": "<4.4" + }, + "require-dev": { + "doctrine/annotations": "^1.12|^2", + "psr/log": "^1|^2|^3", + "symfony/config": "^5.3|^6.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/http-foundation": "^4.4|^5.0|^6.0", + "symfony/yaml": "^4.4|^5.0|^6.0" + }, + "suggest": { + "symfony/config": "For using the all-in-one router or any loader", + "symfony/expression-language": "For using expression matching", + "symfony/http-foundation": "For using a Symfony Request object", + "symfony/yaml": "For using the YAML loader" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Routing\\": "" + }, + "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": "Maps an HTTP request to a set of configuration variables", + "homepage": "https://symfony.com", + "keywords": [ + "router", + "routing", + "uri", + "url" + ], + "support": { + "source": "https://github.com/symfony/routing/tree/v5.4.37" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-27T09:52:32+00:00" + }, + { + "name": "symfony/service-contracts", + "version": "v3.4.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "fe07cbc8d837f60caf7018068e350cc5163681a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/fe07cbc8d837f60caf7018068e350cc5163681a0", + "reference": "fe07cbc8d837f60caf7018068e350cc5163681a0", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.4.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-12-26T14:02:43+00:00" + }, + { + "name": "symfony/string", + "version": "v6.4.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9", + "reference": "4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/http-client": "^5.4|^6.0|^7.0", + "symfony/intl": "^6.2|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^5.4|^6.0|^7.0" + }, + "type": "library", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v6.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-01T13:16:41+00:00" + }, + { + "name": "symfony/translation", + "version": "v6.4.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation.git", + "reference": "bce6a5a78e94566641b2594d17e48b0da3184a8e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation/zipball/bce6a5a78e94566641b2594d17e48b0da3184a8e", + "reference": "bce6a5a78e94566641b2594d17e48b0da3184a8e", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/translation-contracts": "^2.5|^3.0" + }, + "conflict": { + "symfony/config": "<5.4", + "symfony/console": "<5.4", + "symfony/dependency-injection": "<5.4", + "symfony/http-client-contracts": "<2.5", + "symfony/http-kernel": "<5.4", + "symfony/service-contracts": "<2.5", + "symfony/twig-bundle": "<5.4", + "symfony/yaml": "<5.4" + }, + "provide": { + "symfony/translation-implementation": "2.3|3.0" + }, + "require-dev": { + "nikic/php-parser": "^4.18|^5.0", + "psr/log": "^1|^2|^3", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/finder": "^5.4|^6.0|^7.0", + "symfony/http-client-contracts": "^2.5|^3.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", + "symfony/polyfill-intl-icu": "^1.21", + "symfony/routing": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^5.4|^6.0|^7.0" + }, + "type": "library", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\Translation\\": "" + }, + "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 to internationalize your application", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/translation/tree/v6.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-20T13:16:58+00:00" + }, + { + "name": "symfony/translation-contracts", + "version": "v3.4.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation-contracts.git", + "reference": "06450585bf65e978026bda220cdebca3f867fde7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/9256f12d8fb0cd0500f93b19e18c356906cbed3d", - "reference": "9256f12d8fb0cd0500f93b19e18c356906cbed3d", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/06450585bf65e978026bda220cdebca3f867fde7", + "reference": "06450585bf65e978026bda220cdebca3f867fde7", "shasum": "" }, "require": { - "ext-ctype": "*", - "ext-filter": "*", - "ext-hash": "*", - "php": ">=5.5.0" + "php": ">=8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Translation\\": "" + }, + "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 translation", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/translation-contracts/tree/v3.4.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-12-26T14:02:43+00:00" + }, + { + "name": "symfony/var-dumper", + "version": "v5.4.36", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90", + "reference": "2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "symfony/console": "<4.4" }, "require-dev": { - "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", - "doctrine/annotations": "^1.2", - "phpcompatibility/php-compatibility": "^9.3.5", - "roave/security-advisories": "dev-latest", - "squizlabs/php_codesniffer": "^3.5.6", - "yoast/phpunit-polyfills": "^0.2.0" + "ext-iconv": "*", + "symfony/console": "^4.4|^5.0|^6.0", + "symfony/http-kernel": "^4.4|^5.0|^6.0", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/uid": "^5.1|^6.0", + "twig/twig": "^2.13|^3.0.4" }, "suggest": { - "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", - "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", - "league/oauth2-google": "Needed for Google XOAUTH2 authentication", - "psr/log": "For optional PSR-3 debug logging", - "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication", - "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" + "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", + "ext-intl": "To show region name in time zone dump", + "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" }, + "bin": [ + "Resources/bin/var-dump-server" + ], "type": "library", "autoload": { + "files": [ + "Resources/functions/dump.php" + ], "psr-4": { - "PHPMailer\\PHPMailer\\": "src/" + "Symfony\\Component\\VarDumper\\": "" + }, + "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 mechanisms for walking through any arbitrary PHP variable", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "support": { + "source": "https://github.com/symfony/var-dumper/tree/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-15T11:19:14+00:00" + }, + { + "name": "tijsverkoyen/css-to-inline-styles", + "version": "v2.2.7", + "source": { + "type": "git", + "url": "https://github.com/tijsverkoyen/CssToInlineStyles.git", + "reference": "83ee6f38df0a63106a9e4536e3060458b74ccedb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/tijsverkoyen/CssToInlineStyles/zipball/83ee6f38df0a63106a9e4536e3060458b74ccedb", + "reference": "83ee6f38df0a63106a9e4536e3060458b74ccedb", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "php": "^5.5 || ^7.0 || ^8.0", + "symfony/css-selector": "^2.7 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0 || ^7.5 || ^8.5.21 || ^9.5.10" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "TijsVerkoyen\\CssToInlineStyles\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "LGPL-2.1-only" + "BSD-3-Clause" ], "authors": [ { - "name": "Marcus Bointon", - "email": "phpmailer@synchromedia.co.uk" + "name": "Tijs Verkoyen", + "email": "css_to_inline_styles@verkoyen.eu", + "role": "Developer" + } + ], + "description": "CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.", + "homepage": "https://github.com/tijsverkoyen/CssToInlineStyles", + "support": { + "issues": "https://github.com/tijsverkoyen/CssToInlineStyles/issues", + "source": "https://github.com/tijsverkoyen/CssToInlineStyles/tree/v2.2.7" + }, + "time": "2023-12-08T13:03:43+00:00" + }, + { + "name": "vlucas/phpdotenv", + "version": "v5.6.0", + "source": { + "type": "git", + "url": "https://github.com/vlucas/phpdotenv.git", + "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4", + "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4", + "shasum": "" + }, + "require": { + "ext-pcre": "*", + "graham-campbell/result-type": "^1.1.2", + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.2", + "symfony/polyfill-ctype": "^1.24", + "symfony/polyfill-mbstring": "^1.24", + "symfony/polyfill-php80": "^1.24" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-filter": "*", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "suggest": { + "ext-filter": "Required to use the boolean validator." + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true }, + "branch-alias": { + "dev-master": "5.6-dev" + } + }, + "autoload": { + "psr-4": { + "Dotenv\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ { - "name": "Jim Jagielski", - "email": "jimjag@gmail.com" + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" }, { - "name": "Andy Prevost", - "email": "codeworxtech@users.sourceforge.net" + "name": "Vance Lucas", + "email": "vance@vancelucas.com", + "homepage": "https://github.com/vlucas" + } + ], + "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", + "keywords": [ + "dotenv", + "env", + "environment" + ], + "support": { + "issues": "https://github.com/vlucas/phpdotenv/issues", + "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" }, { - "name": "Brent R. Matzelle" + "url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv", + "type": "tidelift" } ], - "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "time": "2023-11-12T22:43:29+00:00" + }, + { + "name": "voku/portable-ascii", + "version": "1.6.1", + "source": { + "type": "git", + "url": "https://github.com/voku/portable-ascii.git", + "reference": "87337c91b9dfacee02452244ee14ab3c43bc485a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/voku/portable-ascii/zipball/87337c91b9dfacee02452244ee14ab3c43bc485a", + "reference": "87337c91b9dfacee02452244ee14ab3c43bc485a", + "shasum": "" + }, + "require": { + "php": ">=7.0.0" + }, + "require-dev": { + "phpunit/phpunit": "~6.0 || ~7.0 || ~9.0" + }, + "suggest": { + "ext-intl": "Use Intl for transliterator_transliterate() support" + }, + "type": "library", + "autoload": { + "psr-4": { + "voku\\": "src/voku/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Lars Moelleken", + "homepage": "http://www.moelleken.org/" + } + ], + "description": "Portable ASCII library - performance optimized (ascii) string functions for php.", + "homepage": "https://github.com/voku/portable-ascii", + "keywords": [ + "ascii", + "clean", + "php" + ], "support": { - "issues": "https://github.com/PHPMailer/PHPMailer/issues", - "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.4.1" + "issues": "https://github.com/voku/portable-ascii/issues", + "source": "https://github.com/voku/portable-ascii/tree/1.6.1" }, "funding": [ { - "url": "https://github.com/Synchro", + "url": "https://www.paypal.me/moelleken", + "type": "custom" + }, + { + "url": "https://github.com/voku", "type": "github" + }, + { + "url": "https://opencollective.com/portable-ascii", + "type": "open_collective" + }, + { + "url": "https://www.patreon.com/voku", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/voku/portable-ascii", + "type": "tidelift" } ], - "time": "2021-04-29T12:25:04+00:00" + "time": "2022-01-24T18:55:24+00:00" + }, + { + "name": "webmozart/assert", + "version": "1.11.0", + "source": { + "type": "git", + "url": "https://github.com/webmozarts/assert.git", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/11cb2199493b2f8a3b53e7f19068fc6aac760991", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "php": "^7.2 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<0.12.20", + "vimeo/psalm": "<4.6.1 || 4.6.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.13" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/1.11.0" + }, + "time": "2022-06-03T18:03:27+00:00" } ], "packages-dev": [], @@ -91,5 +5565,5 @@ "prefer-lowest": false, "platform": [], "platform-dev": [], - "plugin-api-version": "2.1.0" -} + "plugin-api-version": "2.6.0" +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/asm89/stack-cors/LICENSE b/php/libraries/composer/vendor/asm89/stack-cors/LICENSE new file mode 100644 index 0000000..d9f2067 --- /dev/null +++ b/php/libraries/composer/vendor/asm89/stack-cors/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2017 Alexander + +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/php/libraries/composer/vendor/asm89/stack-cors/README.md b/php/libraries/composer/vendor/asm89/stack-cors/README.md new file mode 100644 index 0000000..9385060 --- /dev/null +++ b/php/libraries/composer/vendor/asm89/stack-cors/README.md @@ -0,0 +1,85 @@ +# Stack/Cors + +Library and middleware enabling cross-origin resource sharing for your +http-{foundation,kernel} using application. It attempts to implement the +[W3C Recommendation] for cross-origin resource sharing. + +[W3C Recommendation]: http://www.w3.org/TR/cors/ + +Build status: ![.github/workflows/run-tests.yml](https://github.com/asm89/stack-cors/workflows/.github/workflows/run-tests.yml/badge.svg) + +## Installation + +Require `asm89/stack-cors` using composer. + +## Usage + +This package can be used as a library or as [stack middleware]. + +[stack middleware]: http://stackphp.com/ + +### Options + +| Option | Description | Default value | +|------------------------|------------------------------------------------------------|---------------| +| `allowedMethods` | Matches the request method. | `[]` | +| `allowedOrigins` | Matches the request origin. | `[]` | +| `allowedOriginsPatterns` | Matches the request origin with `preg_match`. | `[]` | +| `allowedHeaders` | Sets the Access-Control-Allow-Headers response header. | `[]` | +| `exposedHeaders` | Sets the Access-Control-Expose-Headers response header. | `false` | +| `maxAge` | Sets the Access-Control-Max-Age response header.
Set to `null` to omit the header/use browser default. | `0` | +| `supportsCredentials` | Sets the Access-Control-Allow-Credentials header. | `false` | + +The _allowedMethods_ and _allowedHeaders_ options are case-insensitive. + +You don't need to provide both _allowedOrigins_ and _allowedOriginsPatterns_. If one of the strings passed matches, it is considered a valid origin. + +If `['*']` is provided to _allowedMethods_, _allowedOrigins_ or _allowedHeaders_ all methods / origins / headers are allowed. + +If _supportsCredentials_ is `true`, you must [explicitly set](https://fetch.spec.whatwg.org/#cors-protocol-and-credentials) `allowedHeaders` for any headers which are not CORS safelisted. + +### Example: using the library + +```php + ['x-allowed-header', 'x-other-allowed-header'], + 'allowedMethods' => ['DELETE', 'GET', 'POST', 'PUT'], + 'allowedOrigins' => ['http://localhost'], + 'allowedOriginsPatterns' => ['/localhost:\d/'], + 'exposedHeaders' => false, + 'maxAge' => 600, + 'supportsCredentials' => true, +]); + +$cors->addActualRequestHeaders(Response $response, $origin); +$cors->handlePreflightRequest(Request $request); +$cors->isActualRequestAllowed(Request $request); +$cors->isCorsRequest(Request $request); +$cors->isPreflightRequest(Request $request); +``` + +## Example: using the stack middleware + +```php + ['x-allowed-header', 'x-other-allowed-header'], + // you can use ['*'] to allow any methods + 'allowedMethods' => ['DELETE', 'GET', 'POST', 'PUT'], + // you can use ['*'] to allow requests from any origin + 'allowedOrigins' => ['localhost'], + // you can enter regexes that are matched to the origin request header + 'allowedOriginsPatterns' => ['/localhost:\d/'], + 'exposedHeaders' => false, + 'maxAge' => 600, + 'supportsCredentials' => false, +]); +``` diff --git a/php/libraries/composer/vendor/asm89/stack-cors/composer.json b/php/libraries/composer/vendor/asm89/stack-cors/composer.json new file mode 100644 index 0000000..f755c9f --- /dev/null +++ b/php/libraries/composer/vendor/asm89/stack-cors/composer.json @@ -0,0 +1,45 @@ +{ + "name": "asm89/stack-cors", + "description": "Cross-origin resource sharing library and stack middleware", + "keywords": ["stack", "cors"], + "homepage": "https://github.com/asm89/stack-cors", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Alexander", + "email": "iam.asm89@gmail.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "symfony/http-foundation": "^5.3|^6|^7", + "symfony/http-kernel": "^5.3|^6|^7" + }, + "require-dev": { + "phpunit/phpunit": "^9", + "squizlabs/php_codesniffer": "^3.5" + }, + "autoload": { + "psr-4": { + "Asm89\\Stack\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Asm89\\Stack\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit", + "check-style": "phpcs -p --standard=PSR12 --exclude=Generic.Files.LineLength --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src", + "fix-style": "phpcbf -p --standard=PSR12 --exclude=Generic.Files.LineLength --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src" + }, + "extra": { + "branch-alias": { + "dev-master": "2.2-dev" + } + }, + "minimum-stability": "beta", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/asm89/stack-cors/src/Cors.php b/php/libraries/composer/vendor/asm89/stack-cors/src/Cors.php new file mode 100644 index 0000000..9e9bd6d --- /dev/null +++ b/php/libraries/composer/vendor/asm89/stack-cors/src/Cors.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Asm89\Stack; + +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpFoundation\Request; + +class Cors implements HttpKernelInterface +{ + /** + * @var \Symfony\Component\HttpKernel\HttpKernelInterface + */ + private $app; + + /** + * @var \Asm89\Stack\CorsService + */ + private $cors; + + private $defaultOptions = [ + 'allowedHeaders' => [], + 'allowedMethods' => [], + 'allowedOrigins' => [], + 'allowedOriginsPatterns' => [], + 'exposedHeaders' => [], + 'maxAge' => 0, + 'supportsCredentials' => false, + ]; + + public function __construct(HttpKernelInterface $app, array $options = []) + { + $this->app = $app; + $this->cors = new CorsService(array_merge($this->defaultOptions, $options)); + } + + public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response + { + if ($this->cors->isPreflightRequest($request)) { + $response = $this->cors->handlePreflightRequest($request); + return $this->cors->varyHeader($response, 'Access-Control-Request-Method'); + } + + $response = $this->app->handle($request, $type, $catch); + + if ($request->getMethod() === 'OPTIONS') { + $this->cors->varyHeader($response, 'Access-Control-Request-Method'); + } + + return $this->cors->addActualRequestHeaders($response, $request); + } +} diff --git a/php/libraries/composer/vendor/asm89/stack-cors/src/CorsService.php b/php/libraries/composer/vendor/asm89/stack-cors/src/CorsService.php new file mode 100644 index 0000000..b8c3de9 --- /dev/null +++ b/php/libraries/composer/vendor/asm89/stack-cors/src/CorsService.php @@ -0,0 +1,225 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Asm89\Stack; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +class CorsService +{ + private $options; + + public function __construct(array $options = []) + { + $this->options = $this->normalizeOptions($options); + } + + private function normalizeOptions(array $options = []): array + { + $options += [ + 'allowedOrigins' => [], + 'allowedOriginsPatterns' => [], + 'supportsCredentials' => false, + 'allowedHeaders' => [], + 'exposedHeaders' => [], + 'allowedMethods' => [], + 'maxAge' => 0, + ]; + + // normalize array('*') to true + if (in_array('*', $options['allowedOrigins'])) { + $options['allowedOrigins'] = true; + } + if (in_array('*', $options['allowedHeaders'])) { + $options['allowedHeaders'] = true; + } else { + $options['allowedHeaders'] = array_map('strtolower', $options['allowedHeaders']); + } + + if (in_array('*', $options['allowedMethods'])) { + $options['allowedMethods'] = true; + } else { + $options['allowedMethods'] = array_map('strtoupper', $options['allowedMethods']); + } + + return $options; + } + + /** + * @deprecated use isOriginAllowed + */ + public function isActualRequestAllowed(Request $request): bool + { + return $this->isOriginAllowed($request); + } + + public function isCorsRequest(Request $request): bool + { + return $request->headers->has('Origin'); + } + + public function isPreflightRequest(Request $request): bool + { + return $request->getMethod() === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method'); + } + + public function handlePreflightRequest(Request $request): Response + { + $response = new Response(); + + $response->setStatusCode(204); + + return $this->addPreflightRequestHeaders($response, $request); + } + + public function addPreflightRequestHeaders(Response $response, Request $request): Response + { + $this->configureAllowedOrigin($response, $request); + + if ($response->headers->has('Access-Control-Allow-Origin')) { + $this->configureAllowCredentials($response, $request); + + $this->configureAllowedMethods($response, $request); + + $this->configureAllowedHeaders($response, $request); + + $this->configureMaxAge($response, $request); + } + + return $response; + } + + public function isOriginAllowed(Request $request): bool + { + if ($this->options['allowedOrigins'] === true) { + return true; + } + + if (!$request->headers->has('Origin')) { + return false; + } + + $origin = $request->headers->get('Origin'); + + if (in_array($origin, $this->options['allowedOrigins'])) { + return true; + } + + foreach ($this->options['allowedOriginsPatterns'] as $pattern) { + if (preg_match($pattern, $origin)) { + return true; + } + } + + return false; + } + + public function addActualRequestHeaders(Response $response, Request $request): Response + { + $this->configureAllowedOrigin($response, $request); + + if ($response->headers->has('Access-Control-Allow-Origin')) { + $this->configureAllowCredentials($response, $request); + + $this->configureExposedHeaders($response, $request); + } + + return $response; + } + + private function configureAllowedOrigin(Response $response, Request $request) + { + if ($this->options['allowedOrigins'] === true && !$this->options['supportsCredentials']) { + // Safe+cacheable, allow everything + $response->headers->set('Access-Control-Allow-Origin', '*'); + } elseif ($this->isSingleOriginAllowed()) { + // Single origins can be safely set + $response->headers->set('Access-Control-Allow-Origin', array_values($this->options['allowedOrigins'])[0]); + } else { + // For dynamic headers, set the requested Origin header when set and allowed + if ($this->isCorsRequest($request) && $this->isOriginAllowed($request)) { + $response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin')); + } + + $this->varyHeader($response, 'Origin'); + } + } + + private function isSingleOriginAllowed(): bool + { + if ($this->options['allowedOrigins'] === true || !empty($this->options['allowedOriginsPatterns'])) { + return false; + } + + return count($this->options['allowedOrigins']) === 1; + } + + private function configureAllowedMethods(Response $response, Request $request) + { + if ($this->options['allowedMethods'] === true) { + $allowMethods = strtoupper($request->headers->get('Access-Control-Request-Method')); + $this->varyHeader($response, 'Access-Control-Request-Method'); + } else { + $allowMethods = implode(', ', $this->options['allowedMethods']); + } + + $response->headers->set('Access-Control-Allow-Methods', $allowMethods); + } + + private function configureAllowedHeaders(Response $response, Request $request) + { + if ($this->options['allowedHeaders'] === true) { + $allowHeaders = $request->headers->get('Access-Control-Request-Headers'); + $this->varyHeader($response, 'Access-Control-Request-Headers'); + } else { + $allowHeaders = implode(', ', $this->options['allowedHeaders']); + } + $response->headers->set('Access-Control-Allow-Headers', $allowHeaders); + } + + private function configureAllowCredentials(Response $response, Request $request) + { + if ($this->options['supportsCredentials']) { + $response->headers->set('Access-Control-Allow-Credentials', 'true'); + } + } + + private function configureExposedHeaders(Response $response, Request $request) + { + if ($this->options['exposedHeaders']) { + $response->headers->set('Access-Control-Expose-Headers', implode(', ', $this->options['exposedHeaders'])); + } + } + + private function configureMaxAge(Response $response, Request $request) + { + if ($this->options['maxAge'] !== null) { + $response->headers->set('Access-Control-Max-Age', (int) $this->options['maxAge']); + } + } + + public function varyHeader(Response $response, $header): Response + { + if (!$response->headers->has('Vary')) { + $response->headers->set('Vary', $header); + } elseif (!in_array($header, explode(', ', $response->headers->get('Vary')))) { + $response->headers->set('Vary', $response->headers->get('Vary') . ', ' . $header); + } + + return $response; + } + + private function isSameHost(Request $request): bool + { + return $request->headers->get('Origin') === $request->getSchemeAndHttpHost(); + } +} diff --git a/php/libraries/composer/vendor/autoload.php b/php/libraries/composer/vendor/autoload.php new file mode 100644 index 0000000..9afcf70 --- /dev/null +++ b/php/libraries/composer/vendor/autoload.php @@ -0,0 +1,25 @@ +realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); + $this->position = 0; + + return (bool) $this->handle; + } + + public function stream_read($count) + { + $data = fread($this->handle, $count); + + if ($this->position === 0) { + $data = preg_replace('{^#!.*\r?\n}', '', $data); + } + + $this->position += strlen($data); + + return $data; + } + + public function stream_cast($castAs) + { + return $this->handle; + } + + public function stream_close() + { + fclose($this->handle); + } + + public function stream_lock($operation) + { + return $operation ? flock($this->handle, $operation) : true; + } + + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return feof($this->handle); + } + + public function stream_stat() + { + return array(); + } + + public function stream_set_option($option, $arg1, $arg2) + { + return true; + } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } + } + } + + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/nesbot/carbon/bin/carbon'); + } +} + +return include __DIR__ . '/..'.'/nesbot/carbon/bin/carbon'; diff --git a/php/libraries/composer/vendor/bin/patch-type-declarations b/php/libraries/composer/vendor/bin/patch-type-declarations new file mode 100755 index 0000000..4e63fef --- /dev/null +++ b/php/libraries/composer/vendor/bin/patch-type-declarations @@ -0,0 +1,119 @@ +#!/usr/bin/env php +realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); + $this->position = 0; + + return (bool) $this->handle; + } + + public function stream_read($count) + { + $data = fread($this->handle, $count); + + if ($this->position === 0) { + $data = preg_replace('{^#!.*\r?\n}', '', $data); + } + + $this->position += strlen($data); + + return $data; + } + + public function stream_cast($castAs) + { + return $this->handle; + } + + public function stream_close() + { + fclose($this->handle); + } + + public function stream_lock($operation) + { + return $operation ? flock($this->handle, $operation) : true; + } + + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return feof($this->handle); + } + + public function stream_stat() + { + return array(); + } + + public function stream_set_option($option, $arg1, $arg2) + { + return true; + } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } + } + } + + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/symfony/error-handler/Resources/bin/patch-type-declarations'); + } +} + +return include __DIR__ . '/..'.'/symfony/error-handler/Resources/bin/patch-type-declarations'; diff --git a/php/libraries/composer/vendor/bin/php-parse b/php/libraries/composer/vendor/bin/php-parse new file mode 100755 index 0000000..61566e6 --- /dev/null +++ b/php/libraries/composer/vendor/bin/php-parse @@ -0,0 +1,119 @@ +#!/usr/bin/env php +realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); + $this->position = 0; + + return (bool) $this->handle; + } + + public function stream_read($count) + { + $data = fread($this->handle, $count); + + if ($this->position === 0) { + $data = preg_replace('{^#!.*\r?\n}', '', $data); + } + + $this->position += strlen($data); + + return $data; + } + + public function stream_cast($castAs) + { + return $this->handle; + } + + public function stream_close() + { + fclose($this->handle); + } + + public function stream_lock($operation) + { + return $operation ? flock($this->handle, $operation) : true; + } + + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return feof($this->handle); + } + + public function stream_stat() + { + return array(); + } + + public function stream_set_option($option, $arg1, $arg2) + { + return true; + } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } + } + } + + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/nikic/php-parser/bin/php-parse'); + } +} + +return include __DIR__ . '/..'.'/nikic/php-parser/bin/php-parse'; diff --git a/php/libraries/composer/vendor/bin/psysh b/php/libraries/composer/vendor/bin/psysh new file mode 100755 index 0000000..7b98393 --- /dev/null +++ b/php/libraries/composer/vendor/bin/psysh @@ -0,0 +1,119 @@ +#!/usr/bin/env php +realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); + $this->position = 0; + + return (bool) $this->handle; + } + + public function stream_read($count) + { + $data = fread($this->handle, $count); + + if ($this->position === 0) { + $data = preg_replace('{^#!.*\r?\n}', '', $data); + } + + $this->position += strlen($data); + + return $data; + } + + public function stream_cast($castAs) + { + return $this->handle; + } + + public function stream_close() + { + fclose($this->handle); + } + + public function stream_lock($operation) + { + return $operation ? flock($this->handle, $operation) : true; + } + + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return feof($this->handle); + } + + public function stream_stat() + { + return array(); + } + + public function stream_set_option($option, $arg1, $arg2) + { + return true; + } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } + } + } + + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/psy/psysh/bin/psysh'); + } +} + +return include __DIR__ . '/..'.'/psy/psysh/bin/psysh'; diff --git a/php/libraries/composer/vendor/bin/var-dump-server b/php/libraries/composer/vendor/bin/var-dump-server new file mode 100755 index 0000000..18db1c1 --- /dev/null +++ b/php/libraries/composer/vendor/bin/var-dump-server @@ -0,0 +1,119 @@ +#!/usr/bin/env php +realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); + $this->position = 0; + + return (bool) $this->handle; + } + + public function stream_read($count) + { + $data = fread($this->handle, $count); + + if ($this->position === 0) { + $data = preg_replace('{^#!.*\r?\n}', '', $data); + } + + $this->position += strlen($data); + + return $data; + } + + public function stream_cast($castAs) + { + return $this->handle; + } + + public function stream_close() + { + fclose($this->handle); + } + + public function stream_lock($operation) + { + return $operation ? flock($this->handle, $operation) : true; + } + + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return feof($this->handle); + } + + public function stream_stat() + { + return array(); + } + + public function stream_set_option($option, $arg1, $arg2) + { + return true; + } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } + } + } + + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server'); + } +} + +return include __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server'; diff --git a/php/libraries/composer/vendor/brick/math/CHANGELOG.md b/php/libraries/composer/vendor/brick/math/CHANGELOG.md new file mode 100644 index 0000000..17cea8d --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/CHANGELOG.md @@ -0,0 +1,445 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## [0.11.0](https://github.com/brick/math/releases/tag/0.11.0) - 2023-01-16 + +💥 **Breaking changes** + +- Minimum PHP version is now 8.0 +- Methods accepting a union of types are now strongly typed* +- `MathException` now extends `Exception` instead of `RuntimeException` + +* You may now run into type errors if you were passing `Stringable` objects to `of()` or any of the methods +internally calling `of()`, with `strict_types` enabled. You can fix this by casting `Stringable` objects to `string` +first. + +## [0.10.2](https://github.com/brick/math/releases/tag/0.10.2) - 2022-08-11 + +👌 **Improvements** + +- `BigRational::toFloat()` now simplifies the fraction before performing division (#73) thanks to @olsavmic + +## [0.10.1](https://github.com/brick/math/releases/tag/0.10.1) - 2022-08-02 + +✨ **New features** + +- `BigInteger::gcdMultiple()` returns the GCD of multiple `BigInteger` numbers + +## [0.10.0](https://github.com/brick/math/releases/tag/0.10.0) - 2022-06-18 + +💥 **Breaking changes** + +- Minimum PHP version is now 7.4 + +## [0.9.3](https://github.com/brick/math/releases/tag/0.9.3) - 2021-08-15 + +🚀 **Compatibility with PHP 8.1** + +- Support for custom object serialization; this removes a warning on PHP 8.1 due to the `Serializable` interface being deprecated (#60) thanks @TRowbotham + +## [0.9.2](https://github.com/brick/math/releases/tag/0.9.2) - 2021-01-20 + +🐛 **Bug fix** + +- Incorrect results could be returned when using the BCMath calculator, with a default scale set with `bcscale()`, on PHP >= 7.2 (#55). + +## [0.9.1](https://github.com/brick/math/releases/tag/0.9.1) - 2020-08-19 + +✨ **New features** + +- `BigInteger::not()` returns the bitwise `NOT` value + +🐛 **Bug fixes** + +- `BigInteger::toBytes()` could return an incorrect binary representation for some numbers +- The bitwise operations `and()`, `or()`, `xor()` on `BigInteger` could return an incorrect result when the GMP extension is not available + +## [0.9.0](https://github.com/brick/math/releases/tag/0.9.0) - 2020-08-18 + +👌 **Improvements** + +- `BigNumber::of()` now accepts `.123` and `123.` formats, both of which return a `BigDecimal` + +💥 **Breaking changes** + +- Deprecated method `BigInteger::powerMod()` has been removed - use `modPow()` instead +- Deprecated method `BigInteger::parse()` has been removed - use `fromBase()` instead + +## [0.8.17](https://github.com/brick/math/releases/tag/0.8.17) - 2020-08-19 + +🐛 **Bug fix** + +- `BigInteger::toBytes()` could return an incorrect binary representation for some numbers +- The bitwise operations `and()`, `or()`, `xor()` on `BigInteger` could return an incorrect result when the GMP extension is not available + +## [0.8.16](https://github.com/brick/math/releases/tag/0.8.16) - 2020-08-18 + +🚑 **Critical fix** + +- This version reintroduces the deprecated `BigInteger::parse()` method, that has been removed by mistake in version `0.8.9` and should have lasted for the whole `0.8` release cycle. + +✨ **New features** + +- `BigInteger::modInverse()` calculates a modular multiplicative inverse +- `BigInteger::fromBytes()` creates a `BigInteger` from a byte string +- `BigInteger::toBytes()` converts a `BigInteger` to a byte string +- `BigInteger::randomBits()` creates a pseudo-random `BigInteger` of a given bit length +- `BigInteger::randomRange()` creates a pseudo-random `BigInteger` between two bounds + +💩 **Deprecations** + +- `BigInteger::powerMod()` is now deprecated in favour of `modPow()` + +## [0.8.15](https://github.com/brick/math/releases/tag/0.8.15) - 2020-04-15 + +🐛 **Fixes** + +- added missing `ext-json` requirement, due to `BigNumber` implementing `JsonSerializable` + +⚡️ **Optimizations** + +- additional optimization in `BigInteger::remainder()` + +## [0.8.14](https://github.com/brick/math/releases/tag/0.8.14) - 2020-02-18 + +✨ **New features** + +- `BigInteger::getLowestSetBit()` returns the index of the rightmost one bit + +## [0.8.13](https://github.com/brick/math/releases/tag/0.8.13) - 2020-02-16 + +✨ **New features** + +- `BigInteger::isEven()` tests whether the number is even +- `BigInteger::isOdd()` tests whether the number is odd +- `BigInteger::testBit()` tests if a bit is set +- `BigInteger::getBitLength()` returns the number of bits in the minimal representation of the number + +## [0.8.12](https://github.com/brick/math/releases/tag/0.8.12) - 2020-02-03 + +🛠️ **Maintenance release** + +Classes are now annotated for better static analysis with [psalm](https://psalm.dev/). + +This is a maintenance release: no bug fixes, no new features, no breaking changes. + +## [0.8.11](https://github.com/brick/math/releases/tag/0.8.11) - 2020-01-23 + +✨ **New feature** + +`BigInteger::powerMod()` performs a power-with-modulo operation. Useful for crypto. + +## [0.8.10](https://github.com/brick/math/releases/tag/0.8.10) - 2020-01-21 + +✨ **New feature** + +`BigInteger::mod()` returns the **modulo** of two numbers. The *modulo* differs from the *remainder* when the signs of the operands are different. + +## [0.8.9](https://github.com/brick/math/releases/tag/0.8.9) - 2020-01-08 + +⚡️ **Performance improvements** + +A few additional optimizations in `BigInteger` and `BigDecimal` when one of the operands can be returned as is. Thanks to @tomtomsen in #24. + +## [0.8.8](https://github.com/brick/math/releases/tag/0.8.8) - 2019-04-25 + +🐛 **Bug fixes** + +- `BigInteger::toBase()` could return an empty string for zero values (BCMath & Native calculators only, GMP calculator unaffected) + +✨ **New features** + +- `BigInteger::toArbitraryBase()` converts a number to an arbitrary base, using a custom alphabet +- `BigInteger::fromArbitraryBase()` converts a string in an arbitrary base, using a custom alphabet, back to a number + +These methods can be used as the foundation to convert strings between different bases/alphabets, using BigInteger as an intermediate representation. + +💩 **Deprecations** + +- `BigInteger::parse()` is now deprecated in favour of `fromBase()` + +`BigInteger::fromBase()` works the same way as `parse()`, with 2 minor differences: + +- the `$base` parameter is required, it does not default to `10` +- it throws a `NumberFormatException` instead of an `InvalidArgumentException` when the number is malformed + +## [0.8.7](https://github.com/brick/math/releases/tag/0.8.7) - 2019-04-20 + +**Improvements** + +- Safer conversion from `float` when using custom locales +- **Much faster** `NativeCalculator` implementation 🚀 + +You can expect **at least a 3x performance improvement** for common arithmetic operations when using the library on systems without GMP or BCMath; it gets exponentially faster on multiplications with a high number of digits. This is due to calculations now being performed on whole blocks of digits (the block size depending on the platform, 32-bit or 64-bit) instead of digit-by-digit as before. + +## [0.8.6](https://github.com/brick/math/releases/tag/0.8.6) - 2019-04-11 + +**New method** + +`BigNumber::sum()` returns the sum of one or more numbers. + +## [0.8.5](https://github.com/brick/math/releases/tag/0.8.5) - 2019-02-12 + +**Bug fix**: `of()` factory methods could fail when passing a `float` in environments using a `LC_NUMERIC` locale with a decimal separator other than `'.'` (#20). + +Thanks @manowark 👍 + +## [0.8.4](https://github.com/brick/math/releases/tag/0.8.4) - 2018-12-07 + +**New method** + +`BigDecimal::sqrt()` calculates the square root of a decimal number, to a given scale. + +## [0.8.3](https://github.com/brick/math/releases/tag/0.8.3) - 2018-12-06 + +**New method** + +`BigInteger::sqrt()` calculates the square root of a number (thanks @peter279k). + +**New exception** + +`NegativeNumberException` is thrown when calling `sqrt()` on a negative number. + +## [0.8.2](https://github.com/brick/math/releases/tag/0.8.2) - 2018-11-08 + +**Performance update** + +- Further improvement of `toInt()` performance +- `NativeCalculator` can now perform some multiplications more efficiently + +## [0.8.1](https://github.com/brick/math/releases/tag/0.8.1) - 2018-11-07 + +Performance optimization of `toInt()` methods. + +## [0.8.0](https://github.com/brick/math/releases/tag/0.8.0) - 2018-10-13 + +**Breaking changes** + +The following deprecated methods have been removed. Use the new method name instead: + +| Method removed | Replacement method | +| --- | --- | +| `BigDecimal::getIntegral()` | `BigDecimal::getIntegralPart()` | +| `BigDecimal::getFraction()` | `BigDecimal::getFractionalPart()` | + +--- + +**New features** + +`BigInteger` has been augmented with 5 new methods for bitwise operations: + +| New method | Description | +| --- | --- | +| `and()` | performs a bitwise `AND` operation on two numbers | +| `or()` | performs a bitwise `OR` operation on two numbers | +| `xor()` | performs a bitwise `XOR` operation on two numbers | +| `shiftedLeft()` | returns the number shifted left by a number of bits | +| `shiftedRight()` | returns the number shifted right by a number of bits | + +Thanks to @DASPRiD 👍 + +## [0.7.3](https://github.com/brick/math/releases/tag/0.7.3) - 2018-08-20 + +**New method:** `BigDecimal::hasNonZeroFractionalPart()` + +**Renamed/deprecated methods:** + +- `BigDecimal::getIntegral()` has been renamed to `getIntegralPart()` and is now deprecated +- `BigDecimal::getFraction()` has been renamed to `getFractionalPart()` and is now deprecated + +## [0.7.2](https://github.com/brick/math/releases/tag/0.7.2) - 2018-07-21 + +**Performance update** + +`BigInteger::parse()` and `toBase()` now use GMP's built-in base conversion features when available. + +## [0.7.1](https://github.com/brick/math/releases/tag/0.7.1) - 2018-03-01 + +This is a maintenance release, no code has been changed. + +- When installed with `--no-dev`, the autoloader does not autoload tests anymore +- Tests and other files unnecessary for production are excluded from the dist package + +This will help make installations more compact. + +## [0.7.0](https://github.com/brick/math/releases/tag/0.7.0) - 2017-10-02 + +Methods renamed: + +- `BigNumber:sign()` has been renamed to `getSign()` +- `BigDecimal::unscaledValue()` has been renamed to `getUnscaledValue()` +- `BigDecimal::scale()` has been renamed to `getScale()` +- `BigDecimal::integral()` has been renamed to `getIntegral()` +- `BigDecimal::fraction()` has been renamed to `getFraction()` +- `BigRational::numerator()` has been renamed to `getNumerator()` +- `BigRational::denominator()` has been renamed to `getDenominator()` + +Classes renamed: + +- `ArithmeticException` has been renamed to `MathException` + +## [0.6.2](https://github.com/brick/math/releases/tag/0.6.2) - 2017-10-02 + +The base class for all exceptions is now `MathException`. +`ArithmeticException` has been deprecated, and will be removed in 0.7.0. + +## [0.6.1](https://github.com/brick/math/releases/tag/0.6.1) - 2017-10-02 + +A number of methods have been renamed: + +- `BigNumber:sign()` is deprecated; use `getSign()` instead +- `BigDecimal::unscaledValue()` is deprecated; use `getUnscaledValue()` instead +- `BigDecimal::scale()` is deprecated; use `getScale()` instead +- `BigDecimal::integral()` is deprecated; use `getIntegral()` instead +- `BigDecimal::fraction()` is deprecated; use `getFraction()` instead +- `BigRational::numerator()` is deprecated; use `getNumerator()` instead +- `BigRational::denominator()` is deprecated; use `getDenominator()` instead + +The old methods will be removed in version 0.7.0. + +## [0.6.0](https://github.com/brick/math/releases/tag/0.6.0) - 2017-08-25 + +- Minimum PHP version is now [7.1](https://gophp71.org/); for PHP 5.6 and PHP 7.0 support, use version `0.5` +- Deprecated method `BigDecimal::withScale()` has been removed; use `toScale()` instead +- Method `BigNumber::toInteger()` has been renamed to `toInt()` + +## [0.5.4](https://github.com/brick/math/releases/tag/0.5.4) - 2016-10-17 + +`BigNumber` classes now implement [JsonSerializable](http://php.net/manual/en/class.jsonserializable.php). +The JSON output is always a string. + +## [0.5.3](https://github.com/brick/math/releases/tag/0.5.3) - 2016-03-31 + +This is a bugfix release. Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6. + +## [0.5.2](https://github.com/brick/math/releases/tag/0.5.2) - 2015-08-06 + +The `$scale` parameter of `BigDecimal::dividedBy()` is now optional again. + +## [0.5.1](https://github.com/brick/math/releases/tag/0.5.1) - 2015-07-05 + +**New method: `BigNumber::toScale()`** + +This allows to convert any `BigNumber` to a `BigDecimal` with a given scale, using rounding if necessary. + +## [0.5.0](https://github.com/brick/math/releases/tag/0.5.0) - 2015-07-04 + +**New features** +- Common `BigNumber` interface for all classes, with the following methods: + - `sign()` and derived methods (`isZero()`, `isPositive()`, ...) + - `compareTo()` and derived methods (`isEqualTo()`, `isGreaterThan()`, ...) that work across different `BigNumber` types + - `toBigInteger()`, `toBigDecimal()`, `toBigRational`() conversion methods + - `toInteger()` and `toFloat()` conversion methods to native types +- Unified `of()` behaviour: every class now accepts any type of number, provided that it can be safely converted to the current type +- New method: `BigDecimal::exactlyDividedBy()`; this method automatically computes the scale of the result, provided that the division yields a finite number of digits +- New methods: `BigRational::quotient()` and `remainder()` +- Fine-grained exceptions: `DivisionByZeroException`, `RoundingNecessaryException`, `NumberFormatException` +- Factory methods `zero()`, `one()` and `ten()` available in all classes +- Rounding mode reintroduced in `BigInteger::dividedBy()` + +This release also comes with many performance improvements. + +--- + +**Breaking changes** +- `BigInteger`: + - `getSign()` is renamed to `sign()` + - `toString()` is renamed to `toBase()` + - `BigInteger::dividedBy()` now throws an exception by default if the remainder is not zero; use `quotient()` to get the previous behaviour +- `BigDecimal`: + - `getSign()` is renamed to `sign()` + - `getUnscaledValue()` is renamed to `unscaledValue()` + - `getScale()` is renamed to `scale()` + - `getIntegral()` is renamed to `integral()` + - `getFraction()` is renamed to `fraction()` + - `divideAndRemainder()` is renamed to `quotientAndRemainder()` + - `dividedBy()` now takes a **mandatory** `$scale` parameter **before** the rounding mode + - `toBigInteger()` does not accept a `$roundingMode` parameter anymore + - `toBigRational()` does not simplify the fraction anymore; explicitly add `->simplified()` to get the previous behaviour +- `BigRational`: + - `getSign()` is renamed to `sign()` + - `getNumerator()` is renamed to `numerator()` + - `getDenominator()` is renamed to `denominator()` + - `of()` is renamed to `nd()`, while `parse()` is renamed to `of()` +- Miscellaneous: + - `ArithmeticException` is moved to an `Exception\` sub-namespace + - `of()` factory methods now throw `NumberFormatException` instead of `InvalidArgumentException` + +## [0.4.3](https://github.com/brick/math/releases/tag/0.4.3) - 2016-03-31 + +Backport of two bug fixes from the 0.5 branch: +- `BigInteger::parse()` did not always throw `InvalidArgumentException` as expected +- Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6. + +## [0.4.2](https://github.com/brick/math/releases/tag/0.4.2) - 2015-06-16 + +New method: `BigDecimal::stripTrailingZeros()` + +## [0.4.1](https://github.com/brick/math/releases/tag/0.4.1) - 2015-06-12 + +Introducing a `BigRational` class, to perform calculations on fractions of any size. + +## [0.4.0](https://github.com/brick/math/releases/tag/0.4.0) - 2015-06-12 + +Rounding modes have been removed from `BigInteger`, and are now a concept specific to `BigDecimal`. + +`BigInteger::dividedBy()` now always returns the quotient of the division. + +## [0.3.5](https://github.com/brick/math/releases/tag/0.3.5) - 2016-03-31 + +Backport of two bug fixes from the 0.5 branch: + +- `BigInteger::parse()` did not always throw `InvalidArgumentException` as expected +- Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6. + +## [0.3.4](https://github.com/brick/math/releases/tag/0.3.4) - 2015-06-11 + +New methods: +- `BigInteger::remainder()` returns the remainder of a division only +- `BigInteger::gcd()` returns the greatest common divisor of two numbers + +## [0.3.3](https://github.com/brick/math/releases/tag/0.3.3) - 2015-06-07 + +Fix `toString()` not handling negative numbers. + +## [0.3.2](https://github.com/brick/math/releases/tag/0.3.2) - 2015-06-07 + +`BigInteger` and `BigDecimal` now have a `getSign()` method that returns: +- `-1` if the number is negative +- `0` if the number is zero +- `1` if the number is positive + +## [0.3.1](https://github.com/brick/math/releases/tag/0.3.1) - 2015-06-05 + +Minor performance improvements + +## [0.3.0](https://github.com/brick/math/releases/tag/0.3.0) - 2015-06-04 + +The `$roundingMode` and `$scale` parameters have been swapped in `BigDecimal::dividedBy()`. + +## [0.2.2](https://github.com/brick/math/releases/tag/0.2.2) - 2015-06-04 + +Stronger immutability guarantee for `BigInteger` and `BigDecimal`. + +So far, it would have been possible to break immutability of these classes by calling the `unserialize()` internal function. This release fixes that. + +## [0.2.1](https://github.com/brick/math/releases/tag/0.2.1) - 2015-06-02 + +Added `BigDecimal::divideAndRemainder()` + +## [0.2.0](https://github.com/brick/math/releases/tag/0.2.0) - 2015-05-22 + +- `min()` and `max()` do not accept an `array` anymore, but a variable number of parameters +- **minimum PHP version is now 5.6** +- continuous integration with PHP 7 + +## [0.1.1](https://github.com/brick/math/releases/tag/0.1.1) - 2014-09-01 + +- Added `BigInteger::power()` +- Added HHVM support + +## [0.1.0](https://github.com/brick/math/releases/tag/0.1.0) - 2014-08-31 + +First beta release. + diff --git a/php/libraries/composer/vendor/brick/math/LICENSE b/php/libraries/composer/vendor/brick/math/LICENSE new file mode 100644 index 0000000..f9b724f --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-present Benjamin Morel + +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/php/libraries/composer/vendor/brick/math/composer.json b/php/libraries/composer/vendor/brick/math/composer.json new file mode 100644 index 0000000..ed817bd --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/composer.json @@ -0,0 +1,34 @@ +{ + "name": "brick/math", + "description": "Arbitrary-precision arithmetic library", + "type": "library", + "keywords": [ + "Brick", + "Math", + "Arbitrary-precision", + "Arithmetic", + "BigInteger", + "BigDecimal", + "BigRational", + "Bignum" + ], + "license": "MIT", + "require": { + "php": "^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.0", + "php-coveralls/php-coveralls": "^2.2", + "vimeo/psalm": "5.0.0" + }, + "autoload": { + "psr-4": { + "Brick\\Math\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Brick\\Math\\Tests\\": "tests/" + } + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/BigDecimal.php b/php/libraries/composer/vendor/brick/math/src/BigDecimal.php new file mode 100644 index 0000000..02fc656 --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/BigDecimal.php @@ -0,0 +1,786 @@ +value = $value; + $this->scale = $scale; + } + + /** + * Creates a BigDecimal of the given value. + * + * @throws MathException If the value cannot be converted to a BigDecimal. + * + * @psalm-pure + */ + public static function of(BigNumber|int|float|string $value) : BigDecimal + { + return parent::of($value)->toBigDecimal(); + } + + /** + * Creates a BigDecimal from an unscaled value and a scale. + * + * Example: `(12345, 3)` will result in the BigDecimal `12.345`. + * + * @param BigNumber|int|float|string $value The unscaled value. Must be convertible to a BigInteger. + * @param int $scale The scale of the number, positive or zero. + * + * @throws \InvalidArgumentException If the scale is negative. + * + * @psalm-pure + */ + public static function ofUnscaledValue(BigNumber|int|float|string $value, int $scale = 0) : BigDecimal + { + if ($scale < 0) { + throw new \InvalidArgumentException('The scale cannot be negative.'); + } + + return new BigDecimal((string) BigInteger::of($value), $scale); + } + + /** + * Returns a BigDecimal representing zero, with a scale of zero. + * + * @psalm-pure + */ + public static function zero() : BigDecimal + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigDecimal|null $zero + */ + static $zero; + + if ($zero === null) { + $zero = new BigDecimal('0'); + } + + return $zero; + } + + /** + * Returns a BigDecimal representing one, with a scale of zero. + * + * @psalm-pure + */ + public static function one() : BigDecimal + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigDecimal|null $one + */ + static $one; + + if ($one === null) { + $one = new BigDecimal('1'); + } + + return $one; + } + + /** + * Returns a BigDecimal representing ten, with a scale of zero. + * + * @psalm-pure + */ + public static function ten() : BigDecimal + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigDecimal|null $ten + */ + static $ten; + + if ($ten === null) { + $ten = new BigDecimal('10'); + } + + return $ten; + } + + /** + * Returns the sum of this number and the given one. + * + * The result has a scale of `max($this->scale, $that->scale)`. + * + * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigDecimal. + * + * @throws MathException If the number is not valid, or is not convertible to a BigDecimal. + */ + public function plus(BigNumber|int|float|string $that) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->value === '0' && $that->scale <= $this->scale) { + return $this; + } + + if ($this->value === '0' && $this->scale <= $that->scale) { + return $that; + } + + [$a, $b] = $this->scaleValues($this, $that); + + $value = Calculator::get()->add($a, $b); + $scale = $this->scale > $that->scale ? $this->scale : $that->scale; + + return new BigDecimal($value, $scale); + } + + /** + * Returns the difference of this number and the given one. + * + * The result has a scale of `max($this->scale, $that->scale)`. + * + * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigDecimal. + * + * @throws MathException If the number is not valid, or is not convertible to a BigDecimal. + */ + public function minus(BigNumber|int|float|string $that) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->value === '0' && $that->scale <= $this->scale) { + return $this; + } + + [$a, $b] = $this->scaleValues($this, $that); + + $value = Calculator::get()->sub($a, $b); + $scale = $this->scale > $that->scale ? $this->scale : $that->scale; + + return new BigDecimal($value, $scale); + } + + /** + * Returns the product of this number and the given one. + * + * The result has a scale of `$this->scale + $that->scale`. + * + * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigDecimal. + * + * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigDecimal. + */ + public function multipliedBy(BigNumber|int|float|string $that) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->value === '1' && $that->scale === 0) { + return $this; + } + + if ($this->value === '1' && $this->scale === 0) { + return $that; + } + + $value = Calculator::get()->mul($this->value, $that->value); + $scale = $this->scale + $that->scale; + + return new BigDecimal($value, $scale); + } + + /** + * Returns the result of the division of this number by the given one, at the given scale. + * + * @param BigNumber|int|float|string $that The divisor. + * @param int|null $scale The desired scale, or null to use the scale of this number. + * @param int $roundingMode An optional rounding mode. + * + * @throws \InvalidArgumentException If the scale or rounding mode is invalid. + * @throws MathException If the number is invalid, is zero, or rounding was necessary. + */ + public function dividedBy(BigNumber|int|float|string $that, ?int $scale = null, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->isZero()) { + throw DivisionByZeroException::divisionByZero(); + } + + if ($scale === null) { + $scale = $this->scale; + } elseif ($scale < 0) { + throw new \InvalidArgumentException('Scale cannot be negative.'); + } + + if ($that->value === '1' && $that->scale === 0 && $scale === $this->scale) { + return $this; + } + + $p = $this->valueWithMinScale($that->scale + $scale); + $q = $that->valueWithMinScale($this->scale - $scale); + + $result = Calculator::get()->divRound($p, $q, $roundingMode); + + return new BigDecimal($result, $scale); + } + + /** + * Returns the exact result of the division of this number by the given one. + * + * The scale of the result is automatically calculated to fit all the fraction digits. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. + * + * @throws MathException If the divisor is not a valid number, is not convertible to a BigDecimal, is zero, + * or the result yields an infinite number of digits. + */ + public function exactlyDividedBy(BigNumber|int|float|string $that) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->value === '0') { + throw DivisionByZeroException::divisionByZero(); + } + + [, $b] = $this->scaleValues($this, $that); + + $d = \rtrim($b, '0'); + $scale = \strlen($b) - \strlen($d); + + $calculator = Calculator::get(); + + foreach ([5, 2] as $prime) { + for (;;) { + $lastDigit = (int) $d[-1]; + + if ($lastDigit % $prime !== 0) { + break; + } + + $d = $calculator->divQ($d, (string) $prime); + $scale++; + } + } + + return $this->dividedBy($that, $scale)->stripTrailingZeros(); + } + + /** + * Returns this number exponentiated to the given value. + * + * The result has a scale of `$this->scale * $exponent`. + * + * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. + */ + public function power(int $exponent) : BigDecimal + { + if ($exponent === 0) { + return BigDecimal::one(); + } + + if ($exponent === 1) { + return $this; + } + + if ($exponent < 0 || $exponent > Calculator::MAX_POWER) { + throw new \InvalidArgumentException(\sprintf( + 'The exponent %d is not in the range 0 to %d.', + $exponent, + Calculator::MAX_POWER + )); + } + + return new BigDecimal(Calculator::get()->pow($this->value, $exponent), $this->scale * $exponent); + } + + /** + * Returns the quotient of the division of this number by this given one. + * + * The quotient has a scale of `0`. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. + * + * @throws MathException If the divisor is not a valid decimal number, or is zero. + */ + public function quotient(BigNumber|int|float|string $that) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->isZero()) { + throw DivisionByZeroException::divisionByZero(); + } + + $p = $this->valueWithMinScale($that->scale); + $q = $that->valueWithMinScale($this->scale); + + $quotient = Calculator::get()->divQ($p, $q); + + return new BigDecimal($quotient, 0); + } + + /** + * Returns the remainder of the division of this number by this given one. + * + * The remainder has a scale of `max($this->scale, $that->scale)`. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. + * + * @throws MathException If the divisor is not a valid decimal number, or is zero. + */ + public function remainder(BigNumber|int|float|string $that) : BigDecimal + { + $that = BigDecimal::of($that); + + if ($that->isZero()) { + throw DivisionByZeroException::divisionByZero(); + } + + $p = $this->valueWithMinScale($that->scale); + $q = $that->valueWithMinScale($this->scale); + + $remainder = Calculator::get()->divR($p, $q); + + $scale = $this->scale > $that->scale ? $this->scale : $that->scale; + + return new BigDecimal($remainder, $scale); + } + + /** + * Returns the quotient and remainder of the division of this number by the given one. + * + * The quotient has a scale of `0`, and the remainder has a scale of `max($this->scale, $that->scale)`. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. + * + * @return BigDecimal[] An array containing the quotient and the remainder. + * + * @throws MathException If the divisor is not a valid decimal number, or is zero. + */ + public function quotientAndRemainder(BigNumber|int|float|string $that) : array + { + $that = BigDecimal::of($that); + + if ($that->isZero()) { + throw DivisionByZeroException::divisionByZero(); + } + + $p = $this->valueWithMinScale($that->scale); + $q = $that->valueWithMinScale($this->scale); + + [$quotient, $remainder] = Calculator::get()->divQR($p, $q); + + $scale = $this->scale > $that->scale ? $this->scale : $that->scale; + + $quotient = new BigDecimal($quotient, 0); + $remainder = new BigDecimal($remainder, $scale); + + return [$quotient, $remainder]; + } + + /** + * Returns the square root of this number, rounded down to the given number of decimals. + * + * @throws \InvalidArgumentException If the scale is negative. + * @throws NegativeNumberException If this number is negative. + */ + public function sqrt(int $scale) : BigDecimal + { + if ($scale < 0) { + throw new \InvalidArgumentException('Scale cannot be negative.'); + } + + if ($this->value === '0') { + return new BigDecimal('0', $scale); + } + + if ($this->value[0] === '-') { + throw new NegativeNumberException('Cannot calculate the square root of a negative number.'); + } + + $value = $this->value; + $addDigits = 2 * $scale - $this->scale; + + if ($addDigits > 0) { + // add zeros + $value .= \str_repeat('0', $addDigits); + } elseif ($addDigits < 0) { + // trim digits + if (-$addDigits >= \strlen($this->value)) { + // requesting a scale too low, will always yield a zero result + return new BigDecimal('0', $scale); + } + + $value = \substr($value, 0, $addDigits); + } + + $value = Calculator::get()->sqrt($value); + + return new BigDecimal($value, $scale); + } + + /** + * Returns a copy of this BigDecimal with the decimal point moved $n places to the left. + */ + public function withPointMovedLeft(int $n) : BigDecimal + { + if ($n === 0) { + return $this; + } + + if ($n < 0) { + return $this->withPointMovedRight(-$n); + } + + return new BigDecimal($this->value, $this->scale + $n); + } + + /** + * Returns a copy of this BigDecimal with the decimal point moved $n places to the right. + */ + public function withPointMovedRight(int $n) : BigDecimal + { + if ($n === 0) { + return $this; + } + + if ($n < 0) { + return $this->withPointMovedLeft(-$n); + } + + $value = $this->value; + $scale = $this->scale - $n; + + if ($scale < 0) { + if ($value !== '0') { + $value .= \str_repeat('0', -$scale); + } + $scale = 0; + } + + return new BigDecimal($value, $scale); + } + + /** + * Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part. + */ + public function stripTrailingZeros() : BigDecimal + { + if ($this->scale === 0) { + return $this; + } + + $trimmedValue = \rtrim($this->value, '0'); + + if ($trimmedValue === '') { + return BigDecimal::zero(); + } + + $trimmableZeros = \strlen($this->value) - \strlen($trimmedValue); + + if ($trimmableZeros === 0) { + return $this; + } + + if ($trimmableZeros > $this->scale) { + $trimmableZeros = $this->scale; + } + + $value = \substr($this->value, 0, -$trimmableZeros); + $scale = $this->scale - $trimmableZeros; + + return new BigDecimal($value, $scale); + } + + /** + * Returns the absolute value of this number. + */ + public function abs() : BigDecimal + { + return $this->isNegative() ? $this->negated() : $this; + } + + /** + * Returns the negated value of this number. + */ + public function negated() : BigDecimal + { + return new BigDecimal(Calculator::get()->neg($this->value), $this->scale); + } + + public function compareTo(BigNumber|int|float|string $that) : int + { + $that = BigNumber::of($that); + + if ($that instanceof BigInteger) { + $that = $that->toBigDecimal(); + } + + if ($that instanceof BigDecimal) { + [$a, $b] = $this->scaleValues($this, $that); + + return Calculator::get()->cmp($a, $b); + } + + return - $that->compareTo($this); + } + + public function getSign() : int + { + return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1); + } + + public function getUnscaledValue() : BigInteger + { + return self::newBigInteger($this->value); + } + + public function getScale() : int + { + return $this->scale; + } + + /** + * Returns a string representing the integral part of this decimal number. + * + * Example: `-123.456` => `-123`. + */ + public function getIntegralPart() : string + { + if ($this->scale === 0) { + return $this->value; + } + + $value = $this->getUnscaledValueWithLeadingZeros(); + + return \substr($value, 0, -$this->scale); + } + + /** + * Returns a string representing the fractional part of this decimal number. + * + * If the scale is zero, an empty string is returned. + * + * Examples: `-123.456` => '456', `123` => ''. + */ + public function getFractionalPart() : string + { + if ($this->scale === 0) { + return ''; + } + + $value = $this->getUnscaledValueWithLeadingZeros(); + + return \substr($value, -$this->scale); + } + + /** + * Returns whether this decimal number has a non-zero fractional part. + */ + public function hasNonZeroFractionalPart() : bool + { + return $this->getFractionalPart() !== \str_repeat('0', $this->scale); + } + + public function toBigInteger() : BigInteger + { + $zeroScaleDecimal = $this->scale === 0 ? $this : $this->dividedBy(1, 0); + + return self::newBigInteger($zeroScaleDecimal->value); + } + + public function toBigDecimal() : BigDecimal + { + return $this; + } + + public function toBigRational() : BigRational + { + $numerator = self::newBigInteger($this->value); + $denominator = self::newBigInteger('1' . \str_repeat('0', $this->scale)); + + return self::newBigRational($numerator, $denominator, false); + } + + public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal + { + if ($scale === $this->scale) { + return $this; + } + + return $this->dividedBy(BigDecimal::one(), $scale, $roundingMode); + } + + public function toInt() : int + { + return $this->toBigInteger()->toInt(); + } + + public function toFloat() : float + { + return (float) (string) $this; + } + + public function __toString() : string + { + if ($this->scale === 0) { + return $this->value; + } + + $value = $this->getUnscaledValueWithLeadingZeros(); + + return \substr($value, 0, -$this->scale) . '.' . \substr($value, -$this->scale); + } + + /** + * This method is required for serializing the object and SHOULD NOT be accessed directly. + * + * @internal + * + * @return array{value: string, scale: int} + */ + public function __serialize(): array + { + return ['value' => $this->value, 'scale' => $this->scale]; + } + + /** + * This method is only here to allow unserializing the object and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @param array{value: string, scale: int} $data + * + * @throws \LogicException + */ + public function __unserialize(array $data): void + { + if (isset($this->value)) { + throw new \LogicException('__unserialize() is an internal function, it must not be called directly.'); + } + + $this->value = $data['value']; + $this->scale = $data['scale']; + } + + /** + * This method is required by interface Serializable and SHOULD NOT be accessed directly. + * + * @internal + */ + public function serialize() : string + { + return $this->value . ':' . $this->scale; + } + + /** + * This method is only here to implement interface Serializable and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @throws \LogicException + */ + public function unserialize($value) : void + { + if (isset($this->value)) { + throw new \LogicException('unserialize() is an internal function, it must not be called directly.'); + } + + [$value, $scale] = \explode(':', $value); + + $this->value = $value; + $this->scale = (int) $scale; + } + + /** + * Puts the internal values of the given decimal numbers on the same scale. + * + * @return array{string, string} The scaled integer values of $x and $y. + */ + private function scaleValues(BigDecimal $x, BigDecimal $y) : array + { + $a = $x->value; + $b = $y->value; + + if ($b !== '0' && $x->scale > $y->scale) { + $b .= \str_repeat('0', $x->scale - $y->scale); + } elseif ($a !== '0' && $x->scale < $y->scale) { + $a .= \str_repeat('0', $y->scale - $x->scale); + } + + return [$a, $b]; + } + + private function valueWithMinScale(int $scale) : string + { + $value = $this->value; + + if ($this->value !== '0' && $scale > $this->scale) { + $value .= \str_repeat('0', $scale - $this->scale); + } + + return $value; + } + + /** + * Adds leading zeros if necessary to the unscaled value to represent the full decimal number. + */ + private function getUnscaledValueWithLeadingZeros() : string + { + $value = $this->value; + $targetLength = $this->scale + 1; + $negative = ($value[0] === '-'); + $length = \strlen($value); + + if ($negative) { + $length--; + } + + if ($length >= $targetLength) { + return $this->value; + } + + if ($negative) { + $value = \substr($value, 1); + } + + $value = \str_pad($value, $targetLength, '0', STR_PAD_LEFT); + + if ($negative) { + $value = '-' . $value; + } + + return $value; + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/BigInteger.php b/php/libraries/composer/vendor/brick/math/src/BigInteger.php new file mode 100644 index 0000000..4356793 --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/BigInteger.php @@ -0,0 +1,1079 @@ +value = $value; + } + + /** + * Creates a BigInteger of the given value. + * + * @throws MathException If the value cannot be converted to a BigInteger. + * + * @psalm-pure + */ + public static function of(BigNumber|int|float|string $value) : BigInteger + { + return parent::of($value)->toBigInteger(); + } + + /** + * Creates a number from a string in a given base. + * + * The string can optionally be prefixed with the `+` or `-` sign. + * + * Bases greater than 36 are not supported by this method, as there is no clear consensus on which of the lowercase + * or uppercase characters should come first. Instead, this method accepts any base up to 36, and does not + * differentiate lowercase and uppercase characters, which are considered equal. + * + * For bases greater than 36, and/or custom alphabets, use the fromArbitraryBase() method. + * + * @param string $number The number to convert, in the given base. + * @param int $base The base of the number, between 2 and 36. + * + * @throws NumberFormatException If the number is empty, or contains invalid chars for the given base. + * @throws \InvalidArgumentException If the base is out of range. + * + * @psalm-pure + */ + public static function fromBase(string $number, int $base) : BigInteger + { + if ($number === '') { + throw new NumberFormatException('The number cannot be empty.'); + } + + if ($base < 2 || $base > 36) { + throw new \InvalidArgumentException(\sprintf('Base %d is not in range 2 to 36.', $base)); + } + + if ($number[0] === '-') { + $sign = '-'; + $number = \substr($number, 1); + } elseif ($number[0] === '+') { + $sign = ''; + $number = \substr($number, 1); + } else { + $sign = ''; + } + + if ($number === '') { + throw new NumberFormatException('The number cannot be empty.'); + } + + $number = \ltrim($number, '0'); + + if ($number === '') { + // The result will be the same in any base, avoid further calculation. + return BigInteger::zero(); + } + + if ($number === '1') { + // The result will be the same in any base, avoid further calculation. + return new BigInteger($sign . '1'); + } + + $pattern = '/[^' . \substr(Calculator::ALPHABET, 0, $base) . ']/'; + + if (\preg_match($pattern, \strtolower($number), $matches) === 1) { + throw new NumberFormatException(\sprintf('"%s" is not a valid character in base %d.', $matches[0], $base)); + } + + if ($base === 10) { + // The number is usable as is, avoid further calculation. + return new BigInteger($sign . $number); + } + + $result = Calculator::get()->fromBase($number, $base); + + return new BigInteger($sign . $result); + } + + /** + * Parses a string containing an integer in an arbitrary base, using a custom alphabet. + * + * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers. + * + * @param string $number The number to parse. + * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8. + * + * @throws NumberFormatException If the given number is empty or contains invalid chars for the given alphabet. + * @throws \InvalidArgumentException If the alphabet does not contain at least 2 chars. + * + * @psalm-pure + */ + public static function fromArbitraryBase(string $number, string $alphabet) : BigInteger + { + if ($number === '') { + throw new NumberFormatException('The number cannot be empty.'); + } + + $base = \strlen($alphabet); + + if ($base < 2) { + throw new \InvalidArgumentException('The alphabet must contain at least 2 chars.'); + } + + $pattern = '/[^' . \preg_quote($alphabet, '/') . ']/'; + + if (\preg_match($pattern, $number, $matches) === 1) { + throw NumberFormatException::charNotInAlphabet($matches[0]); + } + + $number = Calculator::get()->fromArbitraryBase($number, $alphabet, $base); + + return new BigInteger($number); + } + + /** + * Translates a string of bytes containing the binary representation of a BigInteger into a BigInteger. + * + * The input string is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element. + * + * If `$signed` is true, the input is assumed to be in two's-complement representation, and the leading bit is + * interpreted as a sign bit. If `$signed` is false, the input is interpreted as an unsigned number, and the + * resulting BigInteger will always be positive or zero. + * + * This method can be used to retrieve a number exported by `toBytes()`, as long as the `$signed` flags match. + * + * @param string $value The byte string. + * @param bool $signed Whether to interpret as a signed number in two's-complement representation with a leading + * sign bit. + * + * @throws NumberFormatException If the string is empty. + */ + public static function fromBytes(string $value, bool $signed = true) : BigInteger + { + if ($value === '') { + throw new NumberFormatException('The byte string must not be empty.'); + } + + $twosComplement = false; + + if ($signed) { + $x = \ord($value[0]); + + if (($twosComplement = ($x >= 0x80))) { + $value = ~$value; + } + } + + $number = self::fromBase(\bin2hex($value), 16); + + if ($twosComplement) { + return $number->plus(1)->negated(); + } + + return $number; + } + + /** + * Generates a pseudo-random number in the range 0 to 2^numBits - 1. + * + * Using the default random bytes generator, this method is suitable for cryptographic use. + * + * @psalm-param (callable(int): string)|null $randomBytesGenerator + * + * @param int $numBits The number of bits. + * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, and returns a + * string of random bytes of the given length. Defaults to the + * `random_bytes()` function. + * + * @throws \InvalidArgumentException If $numBits is negative. + */ + public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null) : BigInteger + { + if ($numBits < 0) { + throw new \InvalidArgumentException('The number of bits cannot be negative.'); + } + + if ($numBits === 0) { + return BigInteger::zero(); + } + + if ($randomBytesGenerator === null) { + $randomBytesGenerator = 'random_bytes'; + } + + $byteLength = \intdiv($numBits - 1, 8) + 1; + + $extraBits = ($byteLength * 8 - $numBits); + $bitmask = \chr(0xFF >> $extraBits); + + $randomBytes = $randomBytesGenerator($byteLength); + $randomBytes[0] = $randomBytes[0] & $bitmask; + + return self::fromBytes($randomBytes, false); + } + + /** + * Generates a pseudo-random number between `$min` and `$max`. + * + * Using the default random bytes generator, this method is suitable for cryptographic use. + * + * @psalm-param (callable(int): string)|null $randomBytesGenerator + * + * @param BigNumber|int|float|string $min The lower bound. Must be convertible to a BigInteger. + * @param BigNumber|int|float|string $max The upper bound. Must be convertible to a BigInteger. + * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, + * and returns a string of random bytes of the given length. + * Defaults to the `random_bytes()` function. + * + * @throws MathException If one of the parameters cannot be converted to a BigInteger, + * or `$min` is greater than `$max`. + */ + public static function randomRange( + BigNumber|int|float|string $min, + BigNumber|int|float|string $max, + ?callable $randomBytesGenerator = null + ) : BigInteger { + $min = BigInteger::of($min); + $max = BigInteger::of($max); + + if ($min->isGreaterThan($max)) { + throw new MathException('$min cannot be greater than $max.'); + } + + if ($min->isEqualTo($max)) { + return $min; + } + + $diff = $max->minus($min); + $bitLength = $diff->getBitLength(); + + // try until the number is in range (50% to 100% chance of success) + do { + $randomNumber = self::randomBits($bitLength, $randomBytesGenerator); + } while ($randomNumber->isGreaterThan($diff)); + + return $randomNumber->plus($min); + } + + /** + * Returns a BigInteger representing zero. + * + * @psalm-pure + */ + public static function zero() : BigInteger + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigInteger|null $zero + */ + static $zero; + + if ($zero === null) { + $zero = new BigInteger('0'); + } + + return $zero; + } + + /** + * Returns a BigInteger representing one. + * + * @psalm-pure + */ + public static function one() : BigInteger + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigInteger|null $one + */ + static $one; + + if ($one === null) { + $one = new BigInteger('1'); + } + + return $one; + } + + /** + * Returns a BigInteger representing ten. + * + * @psalm-pure + */ + public static function ten() : BigInteger + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigInteger|null $ten + */ + static $ten; + + if ($ten === null) { + $ten = new BigInteger('10'); + } + + return $ten; + } + + public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger + { + $result = $a; + + foreach ($n as $next) { + $result = $result->gcd($next); + + if ($result->isEqualTo(1)) { + return $result; + } + } + + return $result; + } + + /** + * Returns the sum of this number and the given one. + * + * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger. + * + * @throws MathException If the number is not valid, or is not convertible to a BigInteger. + */ + public function plus(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '0') { + return $this; + } + + if ($this->value === '0') { + return $that; + } + + $value = Calculator::get()->add($this->value, $that->value); + + return new BigInteger($value); + } + + /** + * Returns the difference of this number and the given one. + * + * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigInteger. + * + * @throws MathException If the number is not valid, or is not convertible to a BigInteger. + */ + public function minus(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '0') { + return $this; + } + + $value = Calculator::get()->sub($this->value, $that->value); + + return new BigInteger($value); + } + + /** + * Returns the product of this number and the given one. + * + * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger. + * + * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger. + */ + public function multipliedBy(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '1') { + return $this; + } + + if ($this->value === '1') { + return $that; + } + + $value = Calculator::get()->mul($this->value, $that->value); + + return new BigInteger($value); + } + + /** + * Returns the result of the division of this number by the given one. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. + * @param int $roundingMode An optional rounding mode. + * + * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero, + * or RoundingMode::UNNECESSARY is used and the remainder is not zero. + */ + public function dividedBy(BigNumber|int|float|string $that, int $roundingMode = RoundingMode::UNNECESSARY) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '1') { + return $this; + } + + if ($that->value === '0') { + throw DivisionByZeroException::divisionByZero(); + } + + $result = Calculator::get()->divRound($this->value, $that->value, $roundingMode); + + return new BigInteger($result); + } + + /** + * Returns this number exponentiated to the given value. + * + * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. + */ + public function power(int $exponent) : BigInteger + { + if ($exponent === 0) { + return BigInteger::one(); + } + + if ($exponent === 1) { + return $this; + } + + if ($exponent < 0 || $exponent > Calculator::MAX_POWER) { + throw new \InvalidArgumentException(\sprintf( + 'The exponent %d is not in the range 0 to %d.', + $exponent, + Calculator::MAX_POWER + )); + } + + return new BigInteger(Calculator::get()->pow($this->value, $exponent)); + } + + /** + * Returns the quotient of the division of this number by the given one. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. + * + * @throws DivisionByZeroException If the divisor is zero. + */ + public function quotient(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '1') { + return $this; + } + + if ($that->value === '0') { + throw DivisionByZeroException::divisionByZero(); + } + + $quotient = Calculator::get()->divQ($this->value, $that->value); + + return new BigInteger($quotient); + } + + /** + * Returns the remainder of the division of this number by the given one. + * + * The remainder, when non-zero, has the same sign as the dividend. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. + * + * @throws DivisionByZeroException If the divisor is zero. + */ + public function remainder(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '1') { + return BigInteger::zero(); + } + + if ($that->value === '0') { + throw DivisionByZeroException::divisionByZero(); + } + + $remainder = Calculator::get()->divR($this->value, $that->value); + + return new BigInteger($remainder); + } + + /** + * Returns the quotient and remainder of the division of this number by the given one. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. + * + * @return BigInteger[] An array containing the quotient and the remainder. + * + * @throws DivisionByZeroException If the divisor is zero. + */ + public function quotientAndRemainder(BigNumber|int|float|string $that) : array + { + $that = BigInteger::of($that); + + if ($that->value === '0') { + throw DivisionByZeroException::divisionByZero(); + } + + [$quotient, $remainder] = Calculator::get()->divQR($this->value, $that->value); + + return [ + new BigInteger($quotient), + new BigInteger($remainder) + ]; + } + + /** + * Returns the modulo of this number and the given one. + * + * The modulo operation yields the same result as the remainder operation when both operands are of the same sign, + * and may differ when signs are different. + * + * The result of the modulo operation, when non-zero, has the same sign as the divisor. + * + * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. + * + * @throws DivisionByZeroException If the divisor is zero. + */ + public function mod(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '0') { + throw DivisionByZeroException::modulusMustNotBeZero(); + } + + $value = Calculator::get()->mod($this->value, $that->value); + + return new BigInteger($value); + } + + /** + * Returns the modular multiplicative inverse of this BigInteger modulo $m. + * + * @throws DivisionByZeroException If $m is zero. + * @throws NegativeNumberException If $m is negative. + * @throws MathException If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger + * is not relatively prime to m). + */ + public function modInverse(BigInteger $m) : BigInteger + { + if ($m->value === '0') { + throw DivisionByZeroException::modulusMustNotBeZero(); + } + + if ($m->isNegative()) { + throw new NegativeNumberException('Modulus must not be negative.'); + } + + if ($m->value === '1') { + return BigInteger::zero(); + } + + $value = Calculator::get()->modInverse($this->value, $m->value); + + if ($value === null) { + throw new MathException('Unable to compute the modInverse for the given modulus.'); + } + + return new BigInteger($value); + } + + /** + * Returns this number raised into power with modulo. + * + * This operation only works on positive numbers. + * + * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero. + * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive. + * + * @throws NegativeNumberException If any of the operands is negative. + * @throws DivisionByZeroException If the modulus is zero. + */ + public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod) : BigInteger + { + $exp = BigInteger::of($exp); + $mod = BigInteger::of($mod); + + if ($this->isNegative() || $exp->isNegative() || $mod->isNegative()) { + throw new NegativeNumberException('The operands cannot be negative.'); + } + + if ($mod->isZero()) { + throw DivisionByZeroException::modulusMustNotBeZero(); + } + + $result = Calculator::get()->modPow($this->value, $exp->value, $mod->value); + + return new BigInteger($result); + } + + /** + * Returns the greatest common divisor of this number and the given one. + * + * The GCD is always positive, unless both operands are zero, in which case it is zero. + * + * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + */ + public function gcd(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + if ($that->value === '0' && $this->value[0] !== '-') { + return $this; + } + + if ($this->value === '0' && $that->value[0] !== '-') { + return $that; + } + + $value = Calculator::get()->gcd($this->value, $that->value); + + return new BigInteger($value); + } + + /** + * Returns the integer square root number of this number, rounded down. + * + * The result is the largest x such that x² ≤ n. + * + * @throws NegativeNumberException If this number is negative. + */ + public function sqrt() : BigInteger + { + if ($this->value[0] === '-') { + throw new NegativeNumberException('Cannot calculate the square root of a negative number.'); + } + + $value = Calculator::get()->sqrt($this->value); + + return new BigInteger($value); + } + + /** + * Returns the absolute value of this number. + */ + public function abs() : BigInteger + { + return $this->isNegative() ? $this->negated() : $this; + } + + /** + * Returns the inverse of this number. + */ + public function negated() : BigInteger + { + return new BigInteger(Calculator::get()->neg($this->value)); + } + + /** + * Returns the integer bitwise-and combined with another integer. + * + * This method returns a negative BigInteger if and only if both operands are negative. + * + * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + */ + public function and(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + return new BigInteger(Calculator::get()->and($this->value, $that->value)); + } + + /** + * Returns the integer bitwise-or combined with another integer. + * + * This method returns a negative BigInteger if and only if either of the operands is negative. + * + * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + */ + public function or(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + return new BigInteger(Calculator::get()->or($this->value, $that->value)); + } + + /** + * Returns the integer bitwise-xor combined with another integer. + * + * This method returns a negative BigInteger if and only if exactly one of the operands is negative. + * + * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + */ + public function xor(BigNumber|int|float|string $that) : BigInteger + { + $that = BigInteger::of($that); + + return new BigInteger(Calculator::get()->xor($this->value, $that->value)); + } + + /** + * Returns the bitwise-not of this BigInteger. + */ + public function not() : BigInteger + { + return $this->negated()->minus(1); + } + + /** + * Returns the integer left shifted by a given number of bits. + */ + public function shiftedLeft(int $distance) : BigInteger + { + if ($distance === 0) { + return $this; + } + + if ($distance < 0) { + return $this->shiftedRight(- $distance); + } + + return $this->multipliedBy(BigInteger::of(2)->power($distance)); + } + + /** + * Returns the integer right shifted by a given number of bits. + */ + public function shiftedRight(int $distance) : BigInteger + { + if ($distance === 0) { + return $this; + } + + if ($distance < 0) { + return $this->shiftedLeft(- $distance); + } + + $operand = BigInteger::of(2)->power($distance); + + if ($this->isPositiveOrZero()) { + return $this->quotient($operand); + } + + return $this->dividedBy($operand, RoundingMode::UP); + } + + /** + * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit. + * + * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. + * Computes (ceil(log2(this < 0 ? -this : this+1))). + */ + public function getBitLength() : int + { + if ($this->value === '0') { + return 0; + } + + if ($this->isNegative()) { + return $this->abs()->minus(1)->getBitLength(); + } + + return \strlen($this->toBase(2)); + } + + /** + * Returns the index of the rightmost (lowest-order) one bit in this BigInteger. + * + * Returns -1 if this BigInteger contains no one bits. + */ + public function getLowestSetBit() : int + { + $n = $this; + $bitLength = $this->getBitLength(); + + for ($i = 0; $i <= $bitLength; $i++) { + if ($n->isOdd()) { + return $i; + } + + $n = $n->shiftedRight(1); + } + + return -1; + } + + /** + * Returns whether this number is even. + */ + public function isEven() : bool + { + return \in_array($this->value[-1], ['0', '2', '4', '6', '8'], true); + } + + /** + * Returns whether this number is odd. + */ + public function isOdd() : bool + { + return \in_array($this->value[-1], ['1', '3', '5', '7', '9'], true); + } + + /** + * Returns true if and only if the designated bit is set. + * + * Computes ((this & (1<shiftedRight($n)->isOdd(); + } + + public function compareTo(BigNumber|int|float|string $that) : int + { + $that = BigNumber::of($that); + + if ($that instanceof BigInteger) { + return Calculator::get()->cmp($this->value, $that->value); + } + + return - $that->compareTo($this); + } + + public function getSign() : int + { + return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1); + } + + public function toBigInteger() : BigInteger + { + return $this; + } + + public function toBigDecimal() : BigDecimal + { + return self::newBigDecimal($this->value); + } + + public function toBigRational() : BigRational + { + return self::newBigRational($this, BigInteger::one(), false); + } + + public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal + { + return $this->toBigDecimal()->toScale($scale, $roundingMode); + } + + public function toInt() : int + { + $intValue = (int) $this->value; + + if ($this->value !== (string) $intValue) { + throw IntegerOverflowException::toIntOverflow($this); + } + + return $intValue; + } + + public function toFloat() : float + { + return (float) $this->value; + } + + /** + * Returns a string representation of this number in the given base. + * + * The output will always be lowercase for bases greater than 10. + * + * @throws \InvalidArgumentException If the base is out of range. + */ + public function toBase(int $base) : string + { + if ($base === 10) { + return $this->value; + } + + if ($base < 2 || $base > 36) { + throw new \InvalidArgumentException(\sprintf('Base %d is out of range [2, 36]', $base)); + } + + return Calculator::get()->toBase($this->value, $base); + } + + /** + * Returns a string representation of this number in an arbitrary base with a custom alphabet. + * + * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers; + * a NegativeNumberException will be thrown when attempting to call this method on a negative number. + * + * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8. + * + * @throws NegativeNumberException If this number is negative. + * @throws \InvalidArgumentException If the given alphabet does not contain at least 2 chars. + */ + public function toArbitraryBase(string $alphabet) : string + { + $base = \strlen($alphabet); + + if ($base < 2) { + throw new \InvalidArgumentException('The alphabet must contain at least 2 chars.'); + } + + if ($this->value[0] === '-') { + throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.'); + } + + return Calculator::get()->toArbitraryBase($this->value, $alphabet, $base); + } + + /** + * Returns a string of bytes containing the binary representation of this BigInteger. + * + * The string is in big-endian byte-order: the most significant byte is in the zeroth element. + * + * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to + * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the + * number is negative. + * + * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit + * if `$signed` is true. + * + * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match. + * + * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit. + * + * @throws NegativeNumberException If $signed is false, and the number is negative. + */ + public function toBytes(bool $signed = true) : string + { + if (! $signed && $this->isNegative()) { + throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.'); + } + + $hex = $this->abs()->toBase(16); + + if (\strlen($hex) % 2 !== 0) { + $hex = '0' . $hex; + } + + $baseHexLength = \strlen($hex); + + if ($signed) { + if ($this->isNegative()) { + $bin = \hex2bin($hex); + assert($bin !== false); + + $hex = \bin2hex(~$bin); + $hex = self::fromBase($hex, 16)->plus(1)->toBase(16); + + $hexLength = \strlen($hex); + + if ($hexLength < $baseHexLength) { + $hex = \str_repeat('0', $baseHexLength - $hexLength) . $hex; + } + + if ($hex[0] < '8') { + $hex = 'FF' . $hex; + } + } else { + if ($hex[0] >= '8') { + $hex = '00' . $hex; + } + } + } + + return \hex2bin($hex); + } + + public function __toString() : string + { + return $this->value; + } + + /** + * This method is required for serializing the object and SHOULD NOT be accessed directly. + * + * @internal + * + * @return array{value: string} + */ + public function __serialize(): array + { + return ['value' => $this->value]; + } + + /** + * This method is only here to allow unserializing the object and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @param array{value: string} $data + * + * @throws \LogicException + */ + public function __unserialize(array $data): void + { + if (isset($this->value)) { + throw new \LogicException('__unserialize() is an internal function, it must not be called directly.'); + } + + $this->value = $data['value']; + } + + /** + * This method is required by interface Serializable and SHOULD NOT be accessed directly. + * + * @internal + */ + public function serialize() : string + { + return $this->value; + } + + /** + * This method is only here to implement interface Serializable and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @throws \LogicException + */ + public function unserialize($value) : void + { + if (isset($this->value)) { + throw new \LogicException('unserialize() is an internal function, it must not be called directly.'); + } + + $this->value = $value; + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/BigNumber.php b/php/libraries/composer/vendor/brick/math/src/BigNumber.php new file mode 100644 index 0000000..80146d2 --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/BigNumber.php @@ -0,0 +1,512 @@ +[\-\+])?' . + '(?:' . + '(?:' . + '(?[0-9]+)?' . + '(?\.)?' . + '(?[0-9]+)?' . + '(?:[eE](?[\-\+]?[0-9]+))?' . + ')|(?:' . + '(?[0-9]+)' . + '\/?' . + '(?[0-9]+)' . + ')' . + ')' . + '$/'; + + /** + * Creates a BigNumber of the given value. + * + * The concrete return type is dependent on the given value, with the following rules: + * + * - BigNumber instances are returned as is + * - integer numbers are returned as BigInteger + * - floating point numbers are converted to a string then parsed as such + * - strings containing a `/` character are returned as BigRational + * - strings containing a `.` character or using an exponential notation are returned as BigDecimal + * - strings containing only digits with an optional leading `+` or `-` sign are returned as BigInteger + * + * @throws NumberFormatException If the format of the number is not valid. + * @throws DivisionByZeroException If the value represents a rational number with a denominator of zero. + * + * @psalm-pure + */ + public static function of(BigNumber|int|float|string $value) : BigNumber + { + if ($value instanceof BigNumber) { + return $value; + } + + if (\is_int($value)) { + return new BigInteger((string) $value); + } + + $value = \is_float($value) ? self::floatToString($value) : $value; + + $throw = static function() use ($value) : void { + throw new NumberFormatException(\sprintf( + 'The given value "%s" does not represent a valid number.', + $value + )); + }; + + if (\preg_match(self::PARSE_REGEXP, $value, $matches) !== 1) { + $throw(); + } + + $getMatch = static fn(string $value): ?string => (($matches[$value] ?? '') !== '') ? $matches[$value] : null; + + $sign = $getMatch('sign'); + $numerator = $getMatch('numerator'); + $denominator = $getMatch('denominator'); + + if ($numerator !== null) { + assert($denominator !== null); + + if ($sign !== null) { + $numerator = $sign . $numerator; + } + + $numerator = self::cleanUp($numerator); + $denominator = self::cleanUp($denominator); + + if ($denominator === '0') { + throw DivisionByZeroException::denominatorMustNotBeZero(); + } + + return new BigRational( + new BigInteger($numerator), + new BigInteger($denominator), + false + ); + } + + $point = $getMatch('point'); + $integral = $getMatch('integral'); + $fractional = $getMatch('fractional'); + $exponent = $getMatch('exponent'); + + if ($integral === null && $fractional === null) { + $throw(); + } + + if ($integral === null) { + $integral = '0'; + } + + if ($point !== null || $exponent !== null) { + $fractional = ($fractional ?? ''); + $exponent = ($exponent !== null) ? (int) $exponent : 0; + + if ($exponent === PHP_INT_MIN || $exponent === PHP_INT_MAX) { + throw new NumberFormatException('Exponent too large.'); + } + + $unscaledValue = self::cleanUp(($sign ?? ''). $integral . $fractional); + + $scale = \strlen($fractional) - $exponent; + + if ($scale < 0) { + if ($unscaledValue !== '0') { + $unscaledValue .= \str_repeat('0', - $scale); + } + $scale = 0; + } + + return new BigDecimal($unscaledValue, $scale); + } + + $integral = self::cleanUp(($sign ?? '') . $integral); + + return new BigInteger($integral); + } + + /** + * Safely converts float to string, avoiding locale-dependent issues. + * + * @see https://github.com/brick/math/pull/20 + * + * @psalm-pure + * @psalm-suppress ImpureFunctionCall + */ + private static function floatToString(float $float) : string + { + $currentLocale = \setlocale(LC_NUMERIC, '0'); + \setlocale(LC_NUMERIC, 'C'); + + $result = (string) $float; + + \setlocale(LC_NUMERIC, $currentLocale); + + return $result; + } + + /** + * Proxy method to access BigInteger's protected constructor from sibling classes. + * + * @internal + * @psalm-pure + */ + protected function newBigInteger(string $value) : BigInteger + { + return new BigInteger($value); + } + + /** + * Proxy method to access BigDecimal's protected constructor from sibling classes. + * + * @internal + * @psalm-pure + */ + protected function newBigDecimal(string $value, int $scale = 0) : BigDecimal + { + return new BigDecimal($value, $scale); + } + + /** + * Proxy method to access BigRational's protected constructor from sibling classes. + * + * @internal + * @psalm-pure + */ + protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator) : BigRational + { + return new BigRational($numerator, $denominator, $checkDenominator); + } + + /** + * Returns the minimum of the given values. + * + * @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers need to be convertible + * to an instance of the class this method is called on. + * + * @throws \InvalidArgumentException If no values are given. + * @throws MathException If an argument is not valid. + * + * @psalm-suppress LessSpecificReturnStatement + * @psalm-suppress MoreSpecificReturnType + * @psalm-pure + */ + public static function min(BigNumber|int|float|string ...$values) : static + { + $min = null; + + foreach ($values as $value) { + $value = static::of($value); + + if ($min === null || $value->isLessThan($min)) { + $min = $value; + } + } + + if ($min === null) { + throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.'); + } + + return $min; + } + + /** + * Returns the maximum of the given values. + * + * @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers need to be convertible + * to an instance of the class this method is called on. + * + * @throws \InvalidArgumentException If no values are given. + * @throws MathException If an argument is not valid. + * + * @psalm-suppress LessSpecificReturnStatement + * @psalm-suppress MoreSpecificReturnType + * @psalm-pure + */ + public static function max(BigNumber|int|float|string ...$values) : static + { + $max = null; + + foreach ($values as $value) { + $value = static::of($value); + + if ($max === null || $value->isGreaterThan($max)) { + $max = $value; + } + } + + if ($max === null) { + throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.'); + } + + return $max; + } + + /** + * Returns the sum of the given values. + * + * @param BigNumber|int|float|string ...$values The numbers to add. All the numbers need to be convertible + * to an instance of the class this method is called on. + * + * @throws \InvalidArgumentException If no values are given. + * @throws MathException If an argument is not valid. + * + * @psalm-pure + */ + public static function sum(BigNumber|int|float|string ...$values) : static + { + /** @var static|null $sum */ + $sum = null; + + foreach ($values as $value) { + $value = static::of($value); + + $sum = $sum === null ? $value : self::add($sum, $value); + } + + if ($sum === null) { + throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.'); + } + + return $sum; + } + + /** + * Adds two BigNumber instances in the correct order to avoid a RoundingNecessaryException. + * + * @todo This could be better resolved by creating an abstract protected method in BigNumber, and leaving to + * concrete classes the responsibility to perform the addition themselves or delegate it to the given number, + * depending on their ability to perform the operation. This will also require a version bump because we're + * potentially breaking custom BigNumber implementations (if any...) + * + * @psalm-pure + */ + private static function add(BigNumber $a, BigNumber $b) : BigNumber + { + if ($a instanceof BigRational) { + return $a->plus($b); + } + + if ($b instanceof BigRational) { + return $b->plus($a); + } + + if ($a instanceof BigDecimal) { + return $a->plus($b); + } + + if ($b instanceof BigDecimal) { + return $b->plus($a); + } + + /** @var BigInteger $a */ + + return $a->plus($b); + } + + /** + * Removes optional leading zeros and + sign from the given number. + * + * @param string $number The number, validated as a non-empty string of digits with optional leading sign. + * + * @psalm-pure + */ + private static function cleanUp(string $number) : string + { + $firstChar = $number[0]; + + if ($firstChar === '+' || $firstChar === '-') { + $number = \substr($number, 1); + } + + $number = \ltrim($number, '0'); + + if ($number === '') { + return '0'; + } + + if ($firstChar === '-') { + return '-' . $number; + } + + return $number; + } + + /** + * Checks if this number is equal to the given one. + */ + public function isEqualTo(BigNumber|int|float|string $that) : bool + { + return $this->compareTo($that) === 0; + } + + /** + * Checks if this number is strictly lower than the given one. + */ + public function isLessThan(BigNumber|int|float|string $that) : bool + { + return $this->compareTo($that) < 0; + } + + /** + * Checks if this number is lower than or equal to the given one. + */ + public function isLessThanOrEqualTo(BigNumber|int|float|string $that) : bool + { + return $this->compareTo($that) <= 0; + } + + /** + * Checks if this number is strictly greater than the given one. + */ + public function isGreaterThan(BigNumber|int|float|string $that) : bool + { + return $this->compareTo($that) > 0; + } + + /** + * Checks if this number is greater than or equal to the given one. + */ + public function isGreaterThanOrEqualTo(BigNumber|int|float|string $that) : bool + { + return $this->compareTo($that) >= 0; + } + + /** + * Checks if this number equals zero. + */ + public function isZero() : bool + { + return $this->getSign() === 0; + } + + /** + * Checks if this number is strictly negative. + */ + public function isNegative() : bool + { + return $this->getSign() < 0; + } + + /** + * Checks if this number is negative or zero. + */ + public function isNegativeOrZero() : bool + { + return $this->getSign() <= 0; + } + + /** + * Checks if this number is strictly positive. + */ + public function isPositive() : bool + { + return $this->getSign() > 0; + } + + /** + * Checks if this number is positive or zero. + */ + public function isPositiveOrZero() : bool + { + return $this->getSign() >= 0; + } + + /** + * Returns the sign of this number. + * + * @return int -1 if the number is negative, 0 if zero, 1 if positive. + */ + abstract public function getSign() : int; + + /** + * Compares this number to the given one. + * + * @return int [-1,0,1] If `$this` is lower than, equal to, or greater than `$that`. + * + * @throws MathException If the number is not valid. + */ + abstract public function compareTo(BigNumber|int|float|string $that) : int; + + /** + * Converts this number to a BigInteger. + * + * @throws RoundingNecessaryException If this number cannot be converted to a BigInteger without rounding. + */ + abstract public function toBigInteger() : BigInteger; + + /** + * Converts this number to a BigDecimal. + * + * @throws RoundingNecessaryException If this number cannot be converted to a BigDecimal without rounding. + */ + abstract public function toBigDecimal() : BigDecimal; + + /** + * Converts this number to a BigRational. + */ + abstract public function toBigRational() : BigRational; + + /** + * Converts this number to a BigDecimal with the given scale, using rounding if necessary. + * + * @param int $scale The scale of the resulting `BigDecimal`. + * @param int $roundingMode A `RoundingMode` constant. + * + * @throws RoundingNecessaryException If this number cannot be converted to the given scale without rounding. + * This only applies when RoundingMode::UNNECESSARY is used. + */ + abstract public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal; + + /** + * Returns the exact value of this number as a native integer. + * + * If this number cannot be converted to a native integer without losing precision, an exception is thrown. + * Note that the acceptable range for an integer depends on the platform and differs for 32-bit and 64-bit. + * + * @throws MathException If this number cannot be exactly converted to a native integer. + */ + abstract public function toInt() : int; + + /** + * Returns an approximation of this number as a floating-point value. + * + * Note that this method can discard information as the precision of a floating-point value + * is inherently limited. + * + * If the number is greater than the largest representable floating point number, positive infinity is returned. + * If the number is less than the smallest representable floating point number, negative infinity is returned. + */ + abstract public function toFloat() : float; + + /** + * Returns a string representation of this number. + * + * The output of this method can be parsed by the `of()` factory method; + * this will yield an object equal to this one, without any information loss. + */ + abstract public function __toString() : string; + + public function jsonSerialize() : string + { + return $this->__toString(); + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/BigRational.php b/php/libraries/composer/vendor/brick/math/src/BigRational.php new file mode 100644 index 0000000..31f2904 --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/BigRational.php @@ -0,0 +1,445 @@ +isZero()) { + throw DivisionByZeroException::denominatorMustNotBeZero(); + } + + if ($denominator->isNegative()) { + $numerator = $numerator->negated(); + $denominator = $denominator->negated(); + } + } + + $this->numerator = $numerator; + $this->denominator = $denominator; + } + + /** + * Creates a BigRational of the given value. + * + * @throws MathException If the value cannot be converted to a BigRational. + * + * @psalm-pure + */ + public static function of(BigNumber|int|float|string $value) : BigRational + { + return parent::of($value)->toBigRational(); + } + + /** + * Creates a BigRational out of a numerator and a denominator. + * + * If the denominator is negative, the signs of both the numerator and the denominator + * will be inverted to ensure that the denominator is always positive. + * + * @param BigNumber|int|float|string $numerator The numerator. Must be convertible to a BigInteger. + * @param BigNumber|int|float|string $denominator The denominator. Must be convertible to a BigInteger. + * + * @throws NumberFormatException If an argument does not represent a valid number. + * @throws RoundingNecessaryException If an argument represents a non-integer number. + * @throws DivisionByZeroException If the denominator is zero. + * + * @psalm-pure + */ + public static function nd( + BigNumber|int|float|string $numerator, + BigNumber|int|float|string $denominator, + ) : BigRational { + $numerator = BigInteger::of($numerator); + $denominator = BigInteger::of($denominator); + + return new BigRational($numerator, $denominator, true); + } + + /** + * Returns a BigRational representing zero. + * + * @psalm-pure + */ + public static function zero() : BigRational + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigRational|null $zero + */ + static $zero; + + if ($zero === null) { + $zero = new BigRational(BigInteger::zero(), BigInteger::one(), false); + } + + return $zero; + } + + /** + * Returns a BigRational representing one. + * + * @psalm-pure + */ + public static function one() : BigRational + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigRational|null $one + */ + static $one; + + if ($one === null) { + $one = new BigRational(BigInteger::one(), BigInteger::one(), false); + } + + return $one; + } + + /** + * Returns a BigRational representing ten. + * + * @psalm-pure + */ + public static function ten() : BigRational + { + /** + * @psalm-suppress ImpureStaticVariable + * @var BigRational|null $ten + */ + static $ten; + + if ($ten === null) { + $ten = new BigRational(BigInteger::ten(), BigInteger::one(), false); + } + + return $ten; + } + + public function getNumerator() : BigInteger + { + return $this->numerator; + } + + public function getDenominator() : BigInteger + { + return $this->denominator; + } + + /** + * Returns the quotient of the division of the numerator by the denominator. + */ + public function quotient() : BigInteger + { + return $this->numerator->quotient($this->denominator); + } + + /** + * Returns the remainder of the division of the numerator by the denominator. + */ + public function remainder() : BigInteger + { + return $this->numerator->remainder($this->denominator); + } + + /** + * Returns the quotient and remainder of the division of the numerator by the denominator. + * + * @return BigInteger[] + */ + public function quotientAndRemainder() : array + { + return $this->numerator->quotientAndRemainder($this->denominator); + } + + /** + * Returns the sum of this number and the given one. + * + * @param BigNumber|int|float|string $that The number to add. + * + * @throws MathException If the number is not valid. + */ + public function plus(BigNumber|int|float|string $that) : BigRational + { + $that = BigRational::of($that); + + $numerator = $this->numerator->multipliedBy($that->denominator); + $numerator = $numerator->plus($that->numerator->multipliedBy($this->denominator)); + $denominator = $this->denominator->multipliedBy($that->denominator); + + return new BigRational($numerator, $denominator, false); + } + + /** + * Returns the difference of this number and the given one. + * + * @param BigNumber|int|float|string $that The number to subtract. + * + * @throws MathException If the number is not valid. + */ + public function minus(BigNumber|int|float|string $that) : BigRational + { + $that = BigRational::of($that); + + $numerator = $this->numerator->multipliedBy($that->denominator); + $numerator = $numerator->minus($that->numerator->multipliedBy($this->denominator)); + $denominator = $this->denominator->multipliedBy($that->denominator); + + return new BigRational($numerator, $denominator, false); + } + + /** + * Returns the product of this number and the given one. + * + * @param BigNumber|int|float|string $that The multiplier. + * + * @throws MathException If the multiplier is not a valid number. + */ + public function multipliedBy(BigNumber|int|float|string $that) : BigRational + { + $that = BigRational::of($that); + + $numerator = $this->numerator->multipliedBy($that->numerator); + $denominator = $this->denominator->multipliedBy($that->denominator); + + return new BigRational($numerator, $denominator, false); + } + + /** + * Returns the result of the division of this number by the given one. + * + * @param BigNumber|int|float|string $that The divisor. + * + * @throws MathException If the divisor is not a valid number, or is zero. + */ + public function dividedBy(BigNumber|int|float|string $that) : BigRational + { + $that = BigRational::of($that); + + $numerator = $this->numerator->multipliedBy($that->denominator); + $denominator = $this->denominator->multipliedBy($that->numerator); + + return new BigRational($numerator, $denominator, true); + } + + /** + * Returns this number exponentiated to the given value. + * + * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. + */ + public function power(int $exponent) : BigRational + { + if ($exponent === 0) { + $one = BigInteger::one(); + + return new BigRational($one, $one, false); + } + + if ($exponent === 1) { + return $this; + } + + return new BigRational( + $this->numerator->power($exponent), + $this->denominator->power($exponent), + false + ); + } + + /** + * Returns the reciprocal of this BigRational. + * + * The reciprocal has the numerator and denominator swapped. + * + * @throws DivisionByZeroException If the numerator is zero. + */ + public function reciprocal() : BigRational + { + return new BigRational($this->denominator, $this->numerator, true); + } + + /** + * Returns the absolute value of this BigRational. + */ + public function abs() : BigRational + { + return new BigRational($this->numerator->abs(), $this->denominator, false); + } + + /** + * Returns the negated value of this BigRational. + */ + public function negated() : BigRational + { + return new BigRational($this->numerator->negated(), $this->denominator, false); + } + + /** + * Returns the simplified value of this BigRational. + */ + public function simplified() : BigRational + { + $gcd = $this->numerator->gcd($this->denominator); + + $numerator = $this->numerator->quotient($gcd); + $denominator = $this->denominator->quotient($gcd); + + return new BigRational($numerator, $denominator, false); + } + + public function compareTo(BigNumber|int|float|string $that) : int + { + return $this->minus($that)->getSign(); + } + + public function getSign() : int + { + return $this->numerator->getSign(); + } + + public function toBigInteger() : BigInteger + { + $simplified = $this->simplified(); + + if (! $simplified->denominator->isEqualTo(1)) { + throw new RoundingNecessaryException('This rational number cannot be represented as an integer value without rounding.'); + } + + return $simplified->numerator; + } + + public function toBigDecimal() : BigDecimal + { + return $this->numerator->toBigDecimal()->exactlyDividedBy($this->denominator); + } + + public function toBigRational() : BigRational + { + return $this; + } + + public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal + { + return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode); + } + + public function toInt() : int + { + return $this->toBigInteger()->toInt(); + } + + public function toFloat() : float + { + $simplified = $this->simplified(); + return $simplified->numerator->toFloat() / $simplified->denominator->toFloat(); + } + + public function __toString() : string + { + $numerator = (string) $this->numerator; + $denominator = (string) $this->denominator; + + if ($denominator === '1') { + return $numerator; + } + + return $this->numerator . '/' . $this->denominator; + } + + /** + * This method is required for serializing the object and SHOULD NOT be accessed directly. + * + * @internal + * + * @return array{numerator: BigInteger, denominator: BigInteger} + */ + public function __serialize(): array + { + return ['numerator' => $this->numerator, 'denominator' => $this->denominator]; + } + + /** + * This method is only here to allow unserializing the object and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @param array{numerator: BigInteger, denominator: BigInteger} $data + * + * @throws \LogicException + */ + public function __unserialize(array $data): void + { + if (isset($this->numerator)) { + throw new \LogicException('__unserialize() is an internal function, it must not be called directly.'); + } + + $this->numerator = $data['numerator']; + $this->denominator = $data['denominator']; + } + + /** + * This method is required by interface Serializable and SHOULD NOT be accessed directly. + * + * @internal + */ + public function serialize() : string + { + return $this->numerator . '/' . $this->denominator; + } + + /** + * This method is only here to implement interface Serializable and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @throws \LogicException + */ + public function unserialize($value) : void + { + if (isset($this->numerator)) { + throw new \LogicException('unserialize() is an internal function, it must not be called directly.'); + } + + [$numerator, $denominator] = \explode('/', $value); + + $this->numerator = BigInteger::of($numerator); + $this->denominator = BigInteger::of($denominator); + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/Exception/DivisionByZeroException.php b/php/libraries/composer/vendor/brick/math/src/Exception/DivisionByZeroException.php new file mode 100644 index 0000000..ce7769a --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/Exception/DivisionByZeroException.php @@ -0,0 +1,35 @@ + 126) { + $char = \strtoupper(\dechex($ord)); + + if ($ord < 10) { + $char = '0' . $char; + } + } else { + $char = '"' . $char . '"'; + } + + return new self(sprintf('Char %s is not a valid character in the given alphabet.', $char)); + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/Exception/RoundingNecessaryException.php b/php/libraries/composer/vendor/brick/math/src/Exception/RoundingNecessaryException.php new file mode 100644 index 0000000..57bfcd8 --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/Exception/RoundingNecessaryException.php @@ -0,0 +1,19 @@ +init($a, $b); + + if ($aNeg && ! $bNeg) { + return -1; + } + + if ($bNeg && ! $aNeg) { + return 1; + } + + $aLen = \strlen($aDig); + $bLen = \strlen($bDig); + + if ($aLen < $bLen) { + $result = -1; + } elseif ($aLen > $bLen) { + $result = 1; + } else { + $result = $aDig <=> $bDig; + } + + return $aNeg ? -$result : $result; + } + + /** + * Adds two numbers. + */ + abstract public function add(string $a, string $b) : string; + + /** + * Subtracts two numbers. + */ + abstract public function sub(string $a, string $b) : string; + + /** + * Multiplies two numbers. + */ + abstract public function mul(string $a, string $b) : string; + + /** + * Returns the quotient of the division of two numbers. + * + * @param string $a The dividend. + * @param string $b The divisor, must not be zero. + * + * @return string The quotient. + */ + abstract public function divQ(string $a, string $b) : string; + + /** + * Returns the remainder of the division of two numbers. + * + * @param string $a The dividend. + * @param string $b The divisor, must not be zero. + * + * @return string The remainder. + */ + abstract public function divR(string $a, string $b) : string; + + /** + * Returns the quotient and remainder of the division of two numbers. + * + * @param string $a The dividend. + * @param string $b The divisor, must not be zero. + * + * @return array{string, string} An array containing the quotient and remainder. + */ + abstract public function divQR(string $a, string $b) : array; + + /** + * Exponentiates a number. + * + * @param string $a The base number. + * @param int $e The exponent, validated as an integer between 0 and MAX_POWER. + * + * @return string The power. + */ + abstract public function pow(string $a, int $e) : string; + + /** + * @param string $b The modulus; must not be zero. + */ + public function mod(string $a, string $b) : string + { + return $this->divR($this->add($this->divR($a, $b), $b), $b); + } + + /** + * Returns the modular multiplicative inverse of $x modulo $m. + * + * If $x has no multiplicative inverse mod m, this method must return null. + * + * This method can be overridden by the concrete implementation if the underlying library has built-in support. + * + * @param string $m The modulus; must not be negative or zero. + */ + public function modInverse(string $x, string $m) : ?string + { + if ($m === '1') { + return '0'; + } + + $modVal = $x; + + if ($x[0] === '-' || ($this->cmp($this->abs($x), $m) >= 0)) { + $modVal = $this->mod($x, $m); + } + + [$g, $x] = $this->gcdExtended($modVal, $m); + + if ($g !== '1') { + return null; + } + + return $this->mod($this->add($this->mod($x, $m), $m), $m); + } + + /** + * Raises a number into power with modulo. + * + * @param string $base The base number; must be positive or zero. + * @param string $exp The exponent; must be positive or zero. + * @param string $mod The modulus; must be strictly positive. + */ + abstract public function modPow(string $base, string $exp, string $mod) : string; + + /** + * Returns the greatest common divisor of the two numbers. + * + * This method can be overridden by the concrete implementation if the underlying library + * has built-in support for GCD calculations. + * + * @return string The GCD, always positive, or zero if both arguments are zero. + */ + public function gcd(string $a, string $b) : string + { + if ($a === '0') { + return $this->abs($b); + } + + if ($b === '0') { + return $this->abs($a); + } + + return $this->gcd($b, $this->divR($a, $b)); + } + + /** + * @return array{string, string, string} GCD, X, Y + */ + private function gcdExtended(string $a, string $b) : array + { + if ($a === '0') { + return [$b, '0', '1']; + } + + [$gcd, $x1, $y1] = $this->gcdExtended($this->mod($b, $a), $a); + + $x = $this->sub($y1, $this->mul($this->divQ($b, $a), $x1)); + $y = $x1; + + return [$gcd, $x, $y]; + } + + /** + * Returns the square root of the given number, rounded down. + * + * The result is the largest x such that x² ≤ n. + * The input MUST NOT be negative. + */ + abstract public function sqrt(string $n) : string; + + /** + * Converts a number from an arbitrary base. + * + * This method can be overridden by the concrete implementation if the underlying library + * has built-in support for base conversion. + * + * @param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base. + * @param int $base The base of the number, validated from 2 to 36. + * + * @return string The converted number, following the Calculator conventions. + */ + public function fromBase(string $number, int $base) : string + { + return $this->fromArbitraryBase(\strtolower($number), self::ALPHABET, $base); + } + + /** + * Converts a number to an arbitrary base. + * + * This method can be overridden by the concrete implementation if the underlying library + * has built-in support for base conversion. + * + * @param string $number The number to convert, following the Calculator conventions. + * @param int $base The base to convert to, validated from 2 to 36. + * + * @return string The converted number, lowercase. + */ + public function toBase(string $number, int $base) : string + { + $negative = ($number[0] === '-'); + + if ($negative) { + $number = \substr($number, 1); + } + + $number = $this->toArbitraryBase($number, self::ALPHABET, $base); + + if ($negative) { + return '-' . $number; + } + + return $number; + } + + /** + * Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10. + * + * @param string $number The number to convert, validated as a non-empty string, + * containing only chars in the given alphabet/base. + * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum. + * @param int $base The base of the number, validated from 2 to alphabet length. + * + * @return string The number in base 10, following the Calculator conventions. + */ + final public function fromArbitraryBase(string $number, string $alphabet, int $base) : string + { + // remove leading "zeros" + $number = \ltrim($number, $alphabet[0]); + + if ($number === '') { + return '0'; + } + + // optimize for "one" + if ($number === $alphabet[1]) { + return '1'; + } + + $result = '0'; + $power = '1'; + + $base = (string) $base; + + for ($i = \strlen($number) - 1; $i >= 0; $i--) { + $index = \strpos($alphabet, $number[$i]); + + if ($index !== 0) { + $result = $this->add($result, ($index === 1) + ? $power + : $this->mul($power, (string) $index) + ); + } + + if ($i !== 0) { + $power = $this->mul($power, $base); + } + } + + return $result; + } + + /** + * Converts a non-negative number to an arbitrary base using a custom alphabet. + * + * @param string $number The number to convert, positive or zero, following the Calculator conventions. + * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum. + * @param int $base The base to convert to, validated from 2 to alphabet length. + * + * @return string The converted number in the given alphabet. + */ + final public function toArbitraryBase(string $number, string $alphabet, int $base) : string + { + if ($number === '0') { + return $alphabet[0]; + } + + $base = (string) $base; + $result = ''; + + while ($number !== '0') { + [$number, $remainder] = $this->divQR($number, $base); + $remainder = (int) $remainder; + + $result .= $alphabet[$remainder]; + } + + return \strrev($result); + } + + /** + * Performs a rounded division. + * + * Rounding is performed when the remainder of the division is not zero. + * + * @param string $a The dividend. + * @param string $b The divisor, must not be zero. + * @param int $roundingMode The rounding mode. + * + * @throws \InvalidArgumentException If the rounding mode is invalid. + * @throws RoundingNecessaryException If RoundingMode::UNNECESSARY is provided but rounding is necessary. + * + * @psalm-suppress ImpureFunctionCall + */ + final public function divRound(string $a, string $b, int $roundingMode) : string + { + [$quotient, $remainder] = $this->divQR($a, $b); + + $hasDiscardedFraction = ($remainder !== '0'); + $isPositiveOrZero = ($a[0] === '-') === ($b[0] === '-'); + + $discardedFractionSign = function() use ($remainder, $b) : int { + $r = $this->abs($this->mul($remainder, '2')); + $b = $this->abs($b); + + return $this->cmp($r, $b); + }; + + $increment = false; + + switch ($roundingMode) { + case RoundingMode::UNNECESSARY: + if ($hasDiscardedFraction) { + throw RoundingNecessaryException::roundingNecessary(); + } + break; + + case RoundingMode::UP: + $increment = $hasDiscardedFraction; + break; + + case RoundingMode::DOWN: + break; + + case RoundingMode::CEILING: + $increment = $hasDiscardedFraction && $isPositiveOrZero; + break; + + case RoundingMode::FLOOR: + $increment = $hasDiscardedFraction && ! $isPositiveOrZero; + break; + + case RoundingMode::HALF_UP: + $increment = $discardedFractionSign() >= 0; + break; + + case RoundingMode::HALF_DOWN: + $increment = $discardedFractionSign() > 0; + break; + + case RoundingMode::HALF_CEILING: + $increment = $isPositiveOrZero ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0; + break; + + case RoundingMode::HALF_FLOOR: + $increment = $isPositiveOrZero ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0; + break; + + case RoundingMode::HALF_EVEN: + $lastDigit = (int) $quotient[-1]; + $lastDigitIsEven = ($lastDigit % 2 === 0); + $increment = $lastDigitIsEven ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0; + break; + + default: + throw new \InvalidArgumentException('Invalid rounding mode.'); + } + + if ($increment) { + return $this->add($quotient, $isPositiveOrZero ? '1' : '-1'); + } + + return $quotient; + } + + /** + * Calculates bitwise AND of two numbers. + * + * This method can be overridden by the concrete implementation if the underlying library + * has built-in support for bitwise operations. + */ + public function and(string $a, string $b) : string + { + return $this->bitwise('and', $a, $b); + } + + /** + * Calculates bitwise OR of two numbers. + * + * This method can be overridden by the concrete implementation if the underlying library + * has built-in support for bitwise operations. + */ + public function or(string $a, string $b) : string + { + return $this->bitwise('or', $a, $b); + } + + /** + * Calculates bitwise XOR of two numbers. + * + * This method can be overridden by the concrete implementation if the underlying library + * has built-in support for bitwise operations. + */ + public function xor(string $a, string $b) : string + { + return $this->bitwise('xor', $a, $b); + } + + /** + * Performs a bitwise operation on a decimal number. + * + * @param 'and'|'or'|'xor' $operator The operator to use. + * @param string $a The left operand. + * @param string $b The right operand. + */ + private function bitwise(string $operator, string $a, string $b) : string + { + [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b); + + $aBin = $this->toBinary($aDig); + $bBin = $this->toBinary($bDig); + + $aLen = \strlen($aBin); + $bLen = \strlen($bBin); + + if ($aLen > $bLen) { + $bBin = \str_repeat("\x00", $aLen - $bLen) . $bBin; + } elseif ($bLen > $aLen) { + $aBin = \str_repeat("\x00", $bLen - $aLen) . $aBin; + } + + if ($aNeg) { + $aBin = $this->twosComplement($aBin); + } + if ($bNeg) { + $bBin = $this->twosComplement($bBin); + } + + switch ($operator) { + case 'and': + $value = $aBin & $bBin; + $negative = ($aNeg and $bNeg); + break; + + case 'or': + $value = $aBin | $bBin; + $negative = ($aNeg or $bNeg); + break; + + case 'xor': + $value = $aBin ^ $bBin; + $negative = ($aNeg xor $bNeg); + break; + + // @codeCoverageIgnoreStart + default: + throw new \InvalidArgumentException('Invalid bitwise operator.'); + // @codeCoverageIgnoreEnd + } + + if ($negative) { + $value = $this->twosComplement($value); + } + + $result = $this->toDecimal($value); + + return $negative ? $this->neg($result) : $result; + } + + /** + * @param string $number A positive, binary number. + */ + private function twosComplement(string $number) : string + { + $xor = \str_repeat("\xff", \strlen($number)); + + $number ^= $xor; + + for ($i = \strlen($number) - 1; $i >= 0; $i--) { + $byte = \ord($number[$i]); + + if (++$byte !== 256) { + $number[$i] = \chr($byte); + break; + } + + $number[$i] = "\x00"; + + if ($i === 0) { + $number = "\x01" . $number; + } + } + + return $number; + } + + /** + * Converts a decimal number to a binary string. + * + * @param string $number The number to convert, positive or zero, only digits. + */ + private function toBinary(string $number) : string + { + $result = ''; + + while ($number !== '0') { + [$number, $remainder] = $this->divQR($number, '256'); + $result .= \chr((int) $remainder); + } + + return \strrev($result); + } + + /** + * Returns the positive decimal representation of a binary number. + * + * @param string $bytes The bytes representing the number. + */ + private function toDecimal(string $bytes) : string + { + $result = '0'; + $power = '1'; + + for ($i = \strlen($bytes) - 1; $i >= 0; $i--) { + $index = \ord($bytes[$i]); + + if ($index !== 0) { + $result = $this->add($result, ($index === 1) + ? $power + : $this->mul($power, (string) $index) + ); + } + + if ($i !== 0) { + $power = $this->mul($power, '256'); + } + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php b/php/libraries/composer/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php new file mode 100644 index 0000000..5457a3c --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php @@ -0,0 +1,75 @@ +maxDigits = 9; + break; + + case 8: + $this->maxDigits = 18; + break; + + default: + throw new \RuntimeException('The platform is not 32-bit or 64-bit as expected.'); + } + } + + public function add(string $a, string $b) : string + { + /** + * @psalm-var numeric-string $a + * @psalm-var numeric-string $b + */ + $result = $a + $b; + + if (is_int($result)) { + return (string) $result; + } + + if ($a === '0') { + return $b; + } + + if ($b === '0') { + return $a; + } + + [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b); + + $result = $aNeg === $bNeg ? $this->doAdd($aDig, $bDig) : $this->doSub($aDig, $bDig); + + if ($aNeg) { + $result = $this->neg($result); + } + + return $result; + } + + public function sub(string $a, string $b) : string + { + return $this->add($a, $this->neg($b)); + } + + public function mul(string $a, string $b) : string + { + /** + * @psalm-var numeric-string $a + * @psalm-var numeric-string $b + */ + $result = $a * $b; + + if (is_int($result)) { + return (string) $result; + } + + if ($a === '0' || $b === '0') { + return '0'; + } + + if ($a === '1') { + return $b; + } + + if ($b === '1') { + return $a; + } + + if ($a === '-1') { + return $this->neg($b); + } + + if ($b === '-1') { + return $this->neg($a); + } + + [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b); + + $result = $this->doMul($aDig, $bDig); + + if ($aNeg !== $bNeg) { + $result = $this->neg($result); + } + + return $result; + } + + public function divQ(string $a, string $b) : string + { + return $this->divQR($a, $b)[0]; + } + + public function divR(string $a, string $b): string + { + return $this->divQR($a, $b)[1]; + } + + public function divQR(string $a, string $b) : array + { + if ($a === '0') { + return ['0', '0']; + } + + if ($a === $b) { + return ['1', '0']; + } + + if ($b === '1') { + return [$a, '0']; + } + + if ($b === '-1') { + return [$this->neg($a), '0']; + } + + /** @psalm-var numeric-string $a */ + $na = $a * 1; // cast to number + + if (is_int($na)) { + /** @psalm-var numeric-string $b */ + $nb = $b * 1; + + if (is_int($nb)) { + // the only division that may overflow is PHP_INT_MIN / -1, + // which cannot happen here as we've already handled a divisor of -1 above. + $r = $na % $nb; + $q = ($na - $r) / $nb; + + assert(is_int($q)); + + return [ + (string) $q, + (string) $r + ]; + } + } + + [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b); + + [$q, $r] = $this->doDiv($aDig, $bDig); + + if ($aNeg !== $bNeg) { + $q = $this->neg($q); + } + + if ($aNeg) { + $r = $this->neg($r); + } + + return [$q, $r]; + } + + public function pow(string $a, int $e) : string + { + if ($e === 0) { + return '1'; + } + + if ($e === 1) { + return $a; + } + + $odd = $e % 2; + $e -= $odd; + + $aa = $this->mul($a, $a); + + /** @psalm-suppress PossiblyInvalidArgument We're sure that $e / 2 is an int now */ + $result = $this->pow($aa, $e / 2); + + if ($odd === 1) { + $result = $this->mul($result, $a); + } + + return $result; + } + + /** + * Algorithm from: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/ + */ + public function modPow(string $base, string $exp, string $mod) : string + { + // special case: the algorithm below fails with 0 power 0 mod 1 (returns 1 instead of 0) + if ($base === '0' && $exp === '0' && $mod === '1') { + return '0'; + } + + // special case: the algorithm below fails with power 0 mod 1 (returns 1 instead of 0) + if ($exp === '0' && $mod === '1') { + return '0'; + } + + $x = $base; + + $res = '1'; + + // numbers are positive, so we can use remainder instead of modulo + $x = $this->divR($x, $mod); + + while ($exp !== '0') { + if (in_array($exp[-1], ['1', '3', '5', '7', '9'])) { // odd + $res = $this->divR($this->mul($res, $x), $mod); + } + + $exp = $this->divQ($exp, '2'); + $x = $this->divR($this->mul($x, $x), $mod); + } + + return $res; + } + + /** + * Adapted from https://cp-algorithms.com/num_methods/roots_newton.html + */ + public function sqrt(string $n) : string + { + if ($n === '0') { + return '0'; + } + + // initial approximation + $x = \str_repeat('9', \intdiv(\strlen($n), 2) ?: 1); + + $decreased = false; + + for (;;) { + $nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2'); + + if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) { + break; + } + + $decreased = $this->cmp($nx, $x) < 0; + $x = $nx; + } + + return $x; + } + + /** + * Performs the addition of two non-signed large integers. + */ + private function doAdd(string $a, string $b) : string + { + [$a, $b, $length] = $this->pad($a, $b); + + $carry = 0; + $result = ''; + + for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) { + $blockLength = $this->maxDigits; + + if ($i < 0) { + $blockLength += $i; + /** @psalm-suppress LoopInvalidation */ + $i = 0; + } + + /** @psalm-var numeric-string $blockA */ + $blockA = \substr($a, $i, $blockLength); + + /** @psalm-var numeric-string $blockB */ + $blockB = \substr($b, $i, $blockLength); + + $sum = (string) ($blockA + $blockB + $carry); + $sumLength = \strlen($sum); + + if ($sumLength > $blockLength) { + $sum = \substr($sum, 1); + $carry = 1; + } else { + if ($sumLength < $blockLength) { + $sum = \str_repeat('0', $blockLength - $sumLength) . $sum; + } + $carry = 0; + } + + $result = $sum . $result; + + if ($i === 0) { + break; + } + } + + if ($carry === 1) { + $result = '1' . $result; + } + + return $result; + } + + /** + * Performs the subtraction of two non-signed large integers. + */ + private function doSub(string $a, string $b) : string + { + if ($a === $b) { + return '0'; + } + + // Ensure that we always subtract to a positive result: biggest minus smallest. + $cmp = $this->doCmp($a, $b); + + $invert = ($cmp === -1); + + if ($invert) { + $c = $a; + $a = $b; + $b = $c; + } + + [$a, $b, $length] = $this->pad($a, $b); + + $carry = 0; + $result = ''; + + $complement = 10 ** $this->maxDigits; + + for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) { + $blockLength = $this->maxDigits; + + if ($i < 0) { + $blockLength += $i; + /** @psalm-suppress LoopInvalidation */ + $i = 0; + } + + /** @psalm-var numeric-string $blockA */ + $blockA = \substr($a, $i, $blockLength); + + /** @psalm-var numeric-string $blockB */ + $blockB = \substr($b, $i, $blockLength); + + $sum = $blockA - $blockB - $carry; + + if ($sum < 0) { + $sum += $complement; + $carry = 1; + } else { + $carry = 0; + } + + $sum = (string) $sum; + $sumLength = \strlen($sum); + + if ($sumLength < $blockLength) { + $sum = \str_repeat('0', $blockLength - $sumLength) . $sum; + } + + $result = $sum . $result; + + if ($i === 0) { + break; + } + } + + // Carry cannot be 1 when the loop ends, as a > b + assert($carry === 0); + + $result = \ltrim($result, '0'); + + if ($invert) { + $result = $this->neg($result); + } + + return $result; + } + + /** + * Performs the multiplication of two non-signed large integers. + */ + private function doMul(string $a, string $b) : string + { + $x = \strlen($a); + $y = \strlen($b); + + $maxDigits = \intdiv($this->maxDigits, 2); + $complement = 10 ** $maxDigits; + + $result = '0'; + + for ($i = $x - $maxDigits;; $i -= $maxDigits) { + $blockALength = $maxDigits; + + if ($i < 0) { + $blockALength += $i; + /** @psalm-suppress LoopInvalidation */ + $i = 0; + } + + $blockA = (int) \substr($a, $i, $blockALength); + + $line = ''; + $carry = 0; + + for ($j = $y - $maxDigits;; $j -= $maxDigits) { + $blockBLength = $maxDigits; + + if ($j < 0) { + $blockBLength += $j; + /** @psalm-suppress LoopInvalidation */ + $j = 0; + } + + $blockB = (int) \substr($b, $j, $blockBLength); + + $mul = $blockA * $blockB + $carry; + $value = $mul % $complement; + $carry = ($mul - $value) / $complement; + + $value = (string) $value; + $value = \str_pad($value, $maxDigits, '0', STR_PAD_LEFT); + + $line = $value . $line; + + if ($j === 0) { + break; + } + } + + if ($carry !== 0) { + $line = $carry . $line; + } + + $line = \ltrim($line, '0'); + + if ($line !== '') { + $line .= \str_repeat('0', $x - $blockALength - $i); + $result = $this->add($result, $line); + } + + if ($i === 0) { + break; + } + } + + return $result; + } + + /** + * Performs the division of two non-signed large integers. + * + * @return string[] The quotient and remainder. + */ + private function doDiv(string $a, string $b) : array + { + $cmp = $this->doCmp($a, $b); + + if ($cmp === -1) { + return ['0', $a]; + } + + $x = \strlen($a); + $y = \strlen($b); + + // we now know that a >= b && x >= y + + $q = '0'; // quotient + $r = $a; // remainder + $z = $y; // focus length, always $y or $y+1 + + for (;;) { + $focus = \substr($a, 0, $z); + + $cmp = $this->doCmp($focus, $b); + + if ($cmp === -1) { + if ($z === $x) { // remainder < dividend + break; + } + + $z++; + } + + $zeros = \str_repeat('0', $x - $z); + + $q = $this->add($q, '1' . $zeros); + $a = $this->sub($a, $b . $zeros); + + $r = $a; + + if ($r === '0') { // remainder == 0 + break; + } + + $x = \strlen($a); + + if ($x < $y) { // remainder < dividend + break; + } + + $z = $y; + } + + return [$q, $r]; + } + + /** + * Compares two non-signed large numbers. + * + * @return int [-1, 0, 1] + */ + private function doCmp(string $a, string $b) : int + { + $x = \strlen($a); + $y = \strlen($b); + + $cmp = $x <=> $y; + + if ($cmp !== 0) { + return $cmp; + } + + return \strcmp($a, $b) <=> 0; // enforce [-1, 0, 1] + } + + /** + * Pads the left of one of the given numbers with zeros if necessary to make both numbers the same length. + * + * The numbers must only consist of digits, without leading minus sign. + * + * @return array{string, string, int} + */ + private function pad(string $a, string $b) : array + { + $x = \strlen($a); + $y = \strlen($b); + + if ($x > $y) { + $b = \str_repeat('0', $x - $y) . $b; + + return [$a, $b, $x]; + } + + if ($x < $y) { + $a = \str_repeat('0', $y - $x) . $a; + + return [$a, $b, $y]; + } + + return [$a, $b, $x]; + } +} diff --git a/php/libraries/composer/vendor/brick/math/src/RoundingMode.php b/php/libraries/composer/vendor/brick/math/src/RoundingMode.php new file mode 100644 index 0000000..06936d8 --- /dev/null +++ b/php/libraries/composer/vendor/brick/math/src/RoundingMode.php @@ -0,0 +1,107 @@ += 0.5; otherwise, behaves as for DOWN. + * Note that this is the rounding mode commonly taught at school. + */ + public const HALF_UP = 5; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. + * + * Behaves as for UP if the discarded fraction is > 0.5; otherwise, behaves as for DOWN. + */ + public const HALF_DOWN = 6; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards positive infinity. + * + * If the result is positive, behaves as for HALF_UP; if negative, behaves as for HALF_DOWN. + */ + public const HALF_CEILING = 7; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards negative infinity. + * + * If the result is positive, behaves as for HALF_DOWN; if negative, behaves as for HALF_UP. + */ + public const HALF_FLOOR = 8; + + /** + * Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the even neighbor. + * + * Behaves as for HALF_UP if the digit to the left of the discarded fraction is odd; + * behaves as for HALF_DOWN if it's even. + * + * Note that this is the rounding mode that statistically minimizes + * cumulative error when applied repeatedly over a sequence of calculations. + * It is sometimes known as "Banker's rounding", and is chiefly used in the USA. + */ + public const HALF_EVEN = 9; +} diff --git a/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/LICENSE b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/LICENSE new file mode 100644 index 0000000..2ee1671 --- /dev/null +++ b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Carbon + +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/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/README.md b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/README.md new file mode 100644 index 0000000..5a18121 --- /dev/null +++ b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/README.md @@ -0,0 +1,14 @@ +# carbonphp/carbon-doctrine-types + +Types to use Carbon in Doctrine + +## Documentation + +[Check how to use in the official Carbon documentation](https://carbon.nesbot.com/symfony/) + +This package is an externalization of [src/Carbon/Doctrine](https://github.com/briannesbitt/Carbon/tree/2.71.0/src/Carbon/Doctrine) +from `nestbot/carbon` package. + +Externalization allows to better deal with different versions of dbal. With +version 4.0 of dbal, it no longer sustainable to be compatible with all version +using a single code. diff --git a/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/composer.json b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/composer.json new file mode 100644 index 0000000..abf45c5 --- /dev/null +++ b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/composer.json @@ -0,0 +1,36 @@ +{ + "name": "carbonphp/carbon-doctrine-types", + "description": "Types to use Carbon in Doctrine", + "type": "library", + "keywords": [ + "date", + "time", + "DateTime", + "Carbon", + "Doctrine" + ], + "require": { + "php": "^8.1" + }, + "require-dev": { + "doctrine/dbal": "^4.0.0", + "nesbot/carbon": "^2.71.0 || ^3.0.0", + "phpunit/phpunit": "^10.3" + }, + "conflict": { + "doctrine/dbal": "<4.0.0 || >=5.0.0" + }, + "license": "MIT", + "autoload": { + "psr-4": { + "Carbon\\Doctrine\\": "src/Carbon/Doctrine/" + } + }, + "authors": [ + { + "name": "KyleKatarn", + "email": "kylekatarnls@gmail.com" + } + ], + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/CarbonDoctrineType.php b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/CarbonDoctrineType.php new file mode 100644 index 0000000..a63a9b8 --- /dev/null +++ b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/CarbonDoctrineType.php @@ -0,0 +1,16 @@ + + */ + protected function getCarbonClassName(): string + { + return Carbon::class; + } + + public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string + { + $precision = min( + $fieldDeclaration['precision'] ?? DateTimeDefaultPrecision::get(), + $this->getMaximumPrecision($platform), + ); + + $type = parent::getSQLDeclaration($fieldDeclaration, $platform); + + if (!$precision) { + return $type; + } + + if (str_contains($type, '(')) { + return preg_replace('/\(\d+\)/', "($precision)", $type); + } + + [$before, $after] = explode(' ', "$type "); + + return trim("$before($precision) $after"); + } + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string + { + if ($value === null) { + return $value; + } + + if ($value instanceof DateTimeInterface) { + return $value->format('Y-m-d H:i:s.u'); + } + + throw InvalidType::new( + $value, + static::class, + ['null', 'DateTime', 'Carbon'] + ); + } + + private function doConvertToPHPValue(mixed $value) + { + $class = $this->getCarbonClassName(); + + if ($value === null || is_a($value, $class)) { + return $value; + } + + if ($value instanceof DateTimeInterface) { + return $class::instance($value); + } + + $date = null; + $error = null; + + try { + $date = $class::parse($value); + } catch (Exception $exception) { + $error = $exception; + } + + if (!$date) { + throw ValueNotConvertible::new( + $value, + static::class, + 'Y-m-d H:i:s.u or any format supported by '.$class.'::parse()', + $error + ); + } + + return $date; + } + + private function getMaximumPrecision(AbstractPlatform $platform): int + { + if ($platform instanceof DB2Platform) { + return 12; + } + + if ($platform instanceof OraclePlatform) { + return 9; + } + + if ($platform instanceof SQLServerPlatform || $platform instanceof SQLitePlatform) { + return 3; + } + + return 6; + } +} diff --git a/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeDefaultPrecision.php b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeDefaultPrecision.php new file mode 100644 index 0000000..cd9896f --- /dev/null +++ b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeDefaultPrecision.php @@ -0,0 +1,30 @@ + */ + use CarbonTypeConverter; + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?CarbonImmutable + { + return $this->doConvertToPHPValue($value); + } + + /** + * @return class-string + */ + protected function getCarbonClassName(): string + { + return CarbonImmutable::class; + } +} diff --git a/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeType.php b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeType.php new file mode 100644 index 0000000..89e4b79 --- /dev/null +++ b/php/libraries/composer/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeType.php @@ -0,0 +1,24 @@ + */ + use CarbonTypeConverter; + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?Carbon + { + return $this->doConvertToPHPValue($value); + } +} diff --git a/php/libraries/composer/vendor/composer/ClassLoader.php b/php/libraries/composer/vendor/composer/ClassLoader.php new file mode 100644 index 0000000..7824d8f --- /dev/null +++ b/php/libraries/composer/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/php/libraries/composer/vendor/composer/InstalledVersions.php b/php/libraries/composer/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..51e734a --- /dev/null +++ b/php/libraries/composer/vendor/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/php/libraries/composer/vendor/composer/LICENSE b/php/libraries/composer/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/php/libraries/composer/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/php/libraries/composer/vendor/composer/autoload_classmap.php b/php/libraries/composer/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..b3c40ae --- /dev/null +++ b/php/libraries/composer/vendor/composer/autoload_classmap.php @@ -0,0 +1,78 @@ + $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'JsonException' => $vendorDir . '/symfony/polyfill-php73/Resources/stubs/JsonException.php', + 'Nette\\ArgumentOutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\DeprecatedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\DirectoryNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\FileNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\HtmlStringable' => $vendorDir . '/nette/utils/src/HtmlStringable.php', + 'Nette\\IOException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidArgumentException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidStateException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\Iterators\\CachingIterator' => $vendorDir . '/nette/utils/src/Iterators/CachingIterator.php', + 'Nette\\Iterators\\Mapper' => $vendorDir . '/nette/utils/src/Iterators/Mapper.php', + 'Nette\\Localization\\ITranslator' => $vendorDir . '/nette/utils/src/compatibility.php', + 'Nette\\Localization\\Translator' => $vendorDir . '/nette/utils/src/Translator.php', + 'Nette\\MemberAccessException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\NotImplementedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\NotSupportedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\OutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\Schema\\Context' => $vendorDir . '/nette/schema/src/Schema/Context.php', + 'Nette\\Schema\\DynamicParameter' => $vendorDir . '/nette/schema/src/Schema/DynamicParameter.php', + 'Nette\\Schema\\Elements\\AnyOf' => $vendorDir . '/nette/schema/src/Schema/Elements/AnyOf.php', + 'Nette\\Schema\\Elements\\Base' => $vendorDir . '/nette/schema/src/Schema/Elements/Base.php', + 'Nette\\Schema\\Elements\\Structure' => $vendorDir . '/nette/schema/src/Schema/Elements/Structure.php', + 'Nette\\Schema\\Elements\\Type' => $vendorDir . '/nette/schema/src/Schema/Elements/Type.php', + 'Nette\\Schema\\Expect' => $vendorDir . '/nette/schema/src/Schema/Expect.php', + 'Nette\\Schema\\Helpers' => $vendorDir . '/nette/schema/src/Schema/Helpers.php', + 'Nette\\Schema\\Message' => $vendorDir . '/nette/schema/src/Schema/Message.php', + 'Nette\\Schema\\Processor' => $vendorDir . '/nette/schema/src/Schema/Processor.php', + 'Nette\\Schema\\Schema' => $vendorDir . '/nette/schema/src/Schema/Schema.php', + 'Nette\\Schema\\ValidationException' => $vendorDir . '/nette/schema/src/Schema/ValidationException.php', + 'Nette\\SmartObject' => $vendorDir . '/nette/utils/src/SmartObject.php', + 'Nette\\StaticClass' => $vendorDir . '/nette/utils/src/StaticClass.php', + 'Nette\\UnexpectedValueException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\Utils\\ArrayHash' => $vendorDir . '/nette/utils/src/Utils/ArrayHash.php', + 'Nette\\Utils\\ArrayList' => $vendorDir . '/nette/utils/src/Utils/ArrayList.php', + 'Nette\\Utils\\Arrays' => $vendorDir . '/nette/utils/src/Utils/Arrays.php', + 'Nette\\Utils\\AssertionException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Callback' => $vendorDir . '/nette/utils/src/Utils/Callback.php', + 'Nette\\Utils\\DateTime' => $vendorDir . '/nette/utils/src/Utils/DateTime.php', + 'Nette\\Utils\\FileInfo' => $vendorDir . '/nette/utils/src/Utils/FileInfo.php', + 'Nette\\Utils\\FileSystem' => $vendorDir . '/nette/utils/src/Utils/FileSystem.php', + 'Nette\\Utils\\Finder' => $vendorDir . '/nette/utils/src/Utils/Finder.php', + 'Nette\\Utils\\Floats' => $vendorDir . '/nette/utils/src/Utils/Floats.php', + 'Nette\\Utils\\Helpers' => $vendorDir . '/nette/utils/src/Utils/Helpers.php', + 'Nette\\Utils\\Html' => $vendorDir . '/nette/utils/src/Utils/Html.php', + 'Nette\\Utils\\IHtmlString' => $vendorDir . '/nette/utils/src/compatibility.php', + 'Nette\\Utils\\Image' => $vendorDir . '/nette/utils/src/Utils/Image.php', + 'Nette\\Utils\\ImageColor' => $vendorDir . '/nette/utils/src/Utils/ImageColor.php', + 'Nette\\Utils\\ImageException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\ImageType' => $vendorDir . '/nette/utils/src/Utils/ImageType.php', + 'Nette\\Utils\\Iterables' => $vendorDir . '/nette/utils/src/Utils/Iterables.php', + 'Nette\\Utils\\Json' => $vendorDir . '/nette/utils/src/Utils/Json.php', + 'Nette\\Utils\\JsonException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\ObjectHelpers' => $vendorDir . '/nette/utils/src/Utils/ObjectHelpers.php', + 'Nette\\Utils\\Paginator' => $vendorDir . '/nette/utils/src/Utils/Paginator.php', + 'Nette\\Utils\\Random' => $vendorDir . '/nette/utils/src/Utils/Random.php', + 'Nette\\Utils\\Reflection' => $vendorDir . '/nette/utils/src/Utils/Reflection.php', + 'Nette\\Utils\\ReflectionMethod' => $vendorDir . '/nette/utils/src/Utils/ReflectionMethod.php', + 'Nette\\Utils\\RegexpException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Strings' => $vendorDir . '/nette/utils/src/Utils/Strings.php', + 'Nette\\Utils\\Type' => $vendorDir . '/nette/utils/src/Utils/Type.php', + 'Nette\\Utils\\UnknownImageFileException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Validators' => $vendorDir . '/nette/utils/src/Utils/Validators.php', + 'Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.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/php/libraries/composer/vendor/composer/autoload_files.php b/php/libraries/composer/vendor/composer/autoload_files.php new file mode 100644 index 0000000..48c8689 --- /dev/null +++ b/php/libraries/composer/vendor/composer/autoload_files.php @@ -0,0 +1,32 @@ + $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + 'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + '667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php', + '25072dd6e2470089de65ae7bf11d3109' => $vendorDir . '/symfony/polyfill-php72/bootstrap.php', + 'f598d06aa772fa33d905e87be6398fb1' => $vendorDir . '/symfony/polyfill-intl-idn/bootstrap.php', + '0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir . '/symfony/polyfill-php73/bootstrap.php', + '8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php', + '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + 'def43f6c87e4f8dfd0c9e1b1bab14fe8' => $vendorDir . '/symfony/polyfill-iconv/bootstrap.php', + 'a1105708a18b76903365ca1c4aa61b02' => $vendorDir . '/symfony/translation/Resources/functions.php', + '538ca81a9a966a6716601ecf48f4eaef' => $vendorDir . '/opis/closure/functions.php', + '801c31d8ed748cfa537fa45402288c95' => $vendorDir . '/psy/psysh/src/functions.php', + 'e39a8b23c42d4e1452234d762b03835a' => $vendorDir . '/ramsey/uuid/src/functions.php', + '2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', + '265b4faa2b3a9766332744949e83bf97' => $vendorDir . '/laravel/framework/src/Illuminate/Collections/helpers.php', + 'c7a3c339e7e14b60e06a2d7fcce9476b' => $vendorDir . '/laravel/framework/src/Illuminate/Events/functions.php', + 'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php', + '58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php', +); diff --git a/php/libraries/composer/vendor/composer/autoload_namespaces.php b/php/libraries/composer/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/php/libraries/composer/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/voku/portable-ascii/src/voku'), + 'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'), + 'TijsVerkoyen\\CssToInlineStyles\\' => array($vendorDir . '/tijsverkoyen/css-to-inline-styles/src'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Php73\\' => array($vendorDir . '/symfony/polyfill-php73'), + 'Symfony\\Polyfill\\Php72\\' => array($vendorDir . '/symfony/polyfill-php72'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'), + 'Symfony\\Polyfill\\Intl\\Idn\\' => array($vendorDir . '/symfony/polyfill-intl-idn'), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'), + 'Symfony\\Polyfill\\Iconv\\' => array($vendorDir . '/symfony/polyfill-iconv'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Symfony\\Contracts\\Translation\\' => array($vendorDir . '/symfony/translation-contracts'), + 'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'), + 'Symfony\\Contracts\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher-contracts'), + 'Symfony\\Component\\VarDumper\\' => array($vendorDir . '/symfony/var-dumper'), + 'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'), + 'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'), + 'Symfony\\Component\\Routing\\' => array($vendorDir . '/symfony/routing'), + 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'), + 'Symfony\\Component\\Mime\\' => array($vendorDir . '/symfony/mime'), + 'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'), + 'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'), + 'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'), + 'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'), + 'Symfony\\Component\\ErrorHandler\\' => array($vendorDir . '/symfony/error-handler'), + 'Symfony\\Component\\CssSelector\\' => array($vendorDir . '/symfony/css-selector'), + 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), + 'Ramsey\\Uuid\\' => array($vendorDir . '/ramsey/uuid/src'), + 'Ramsey\\Collection\\' => array($vendorDir . '/ramsey/collection/src'), + 'Psy\\' => array($vendorDir . '/psy/psysh/src'), + 'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'), + 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), + 'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'Psr\\Clock\\' => array($vendorDir . '/psr/clock/src'), + 'PhpParser\\' => array($vendorDir . '/nikic/php-parser/lib/PhpParser'), + 'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'), + 'PHPMailer\\PHPMailer\\' => array($vendorDir . '/phpmailer/phpmailer/src'), + 'Opis\\Closure\\' => array($vendorDir . '/opis/closure/src'), + 'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'), + 'League\\MimeTypeDetection\\' => array($vendorDir . '/league/mime-type-detection/src'), + 'League\\Flysystem\\' => array($vendorDir . '/league/flysystem/src'), + 'League\\Config\\' => array($vendorDir . '/league/config/src'), + 'League\\CommonMark\\' => array($vendorDir . '/league/commonmark/src'), + 'Laravel\\Tinker\\' => array($vendorDir . '/laravel/tinker/src'), + 'Laravel\\SerializableClosure\\' => array($vendorDir . '/laravel/serializable-closure/src'), + 'Laravel\\Sanctum\\' => array($vendorDir . '/laravel/sanctum/src'), + 'Illuminate\\Support\\' => array($vendorDir . '/laravel/framework/src/Illuminate/Macroable', $vendorDir . '/laravel/framework/src/Illuminate/Collections'), + 'Illuminate\\' => array($vendorDir . '/laravel/framework/src/Illuminate'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'), + 'Fruitcake\\Cors\\' => array($vendorDir . '/fruitcake/laravel-cors/src'), + 'Egulias\\EmailValidator\\' => array($vendorDir . '/egulias/email-validator/src'), + 'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'), + 'Doctrine\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib/Doctrine/Inflector'), + 'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib/Doctrine/Common/Lexer'), + 'Dflydev\\DotAccessData\\' => array($vendorDir . '/dflydev/dot-access-data/src'), + 'Database\\Seeders\\' => array($vendorDir . '/laravel/laravel/database/seeders'), + 'Database\\Factories\\' => array($vendorDir . '/laravel/laravel/database/factories'), + 'Cron\\' => array($vendorDir . '/dragonmantank/cron-expression/src/Cron'), + 'Carbon\\Doctrine\\' => array($vendorDir . '/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine'), + 'Carbon\\' => array($vendorDir . '/nesbot/carbon/src/Carbon'), + 'Brick\\Math\\' => array($vendorDir . '/brick/math/src'), + 'Asm89\\Stack\\' => array($vendorDir . '/asm89/stack-cors/src'), + 'App\\' => array($vendorDir . '/laravel/laravel/app'), +); diff --git a/php/libraries/composer/vendor/composer/autoload_real.php b/php/libraries/composer/vendor/composer/autoload_real.php new file mode 100644 index 0000000..b33dd88 --- /dev/null +++ b/php/libraries/composer/vendor/composer/autoload_real.php @@ -0,0 +1,50 @@ +register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInitda4df0130c662759d398fc41895ca400::$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/php/libraries/composer/vendor/composer/autoload_static.php b/php/libraries/composer/vendor/composer/autoload_static.php new file mode 100644 index 0000000..75c3712 --- /dev/null +++ b/php/libraries/composer/vendor/composer/autoload_static.php @@ -0,0 +1,525 @@ + __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + 'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + '667aeda72477189d0494fecd327c3641' => __DIR__ . '/..' . '/symfony/var-dumper/Resources/functions/dump.php', + '25072dd6e2470089de65ae7bf11d3109' => __DIR__ . '/..' . '/symfony/polyfill-php72/bootstrap.php', + 'f598d06aa772fa33d905e87be6398fb1' => __DIR__ . '/..' . '/symfony/polyfill-intl-idn/bootstrap.php', + '0d59ee240a4cd96ddbb4ff164fccea4d' => __DIR__ . '/..' . '/symfony/polyfill-php73/bootstrap.php', + '8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php', + '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + 'def43f6c87e4f8dfd0c9e1b1bab14fe8' => __DIR__ . '/..' . '/symfony/polyfill-iconv/bootstrap.php', + 'a1105708a18b76903365ca1c4aa61b02' => __DIR__ . '/..' . '/symfony/translation/Resources/functions.php', + '538ca81a9a966a6716601ecf48f4eaef' => __DIR__ . '/..' . '/opis/closure/functions.php', + '801c31d8ed748cfa537fa45402288c95' => __DIR__ . '/..' . '/psy/psysh/src/functions.php', + 'e39a8b23c42d4e1452234d762b03835a' => __DIR__ . '/..' . '/ramsey/uuid/src/functions.php', + '2c102faa651ef8ea5874edb585946bce' => __DIR__ . '/..' . '/swiftmailer/swiftmailer/lib/swift_required.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + '265b4faa2b3a9766332744949e83bf97' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Collections/helpers.php', + 'c7a3c339e7e14b60e06a2d7fcce9476b' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Events/functions.php', + 'f0906e6318348a765ffb6eb24e0d0938' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Foundation/helpers.php', + '58571171fd5812e6e447dce228f52f4d' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Support/helpers.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'v' => + array ( + 'voku\\' => 5, + ), + 'W' => + array ( + 'Webmozart\\Assert\\' => 17, + ), + 'T' => + array ( + 'TijsVerkoyen\\CssToInlineStyles\\' => 31, + ), + 'S' => + array ( + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Php73\\' => 23, + 'Symfony\\Polyfill\\Php72\\' => 23, + 'Symfony\\Polyfill\\Mbstring\\' => 26, + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => 33, + 'Symfony\\Polyfill\\Intl\\Idn\\' => 26, + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => 31, + 'Symfony\\Polyfill\\Iconv\\' => 23, + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Symfony\\Contracts\\Translation\\' => 30, + 'Symfony\\Contracts\\Service\\' => 26, + 'Symfony\\Contracts\\EventDispatcher\\' => 34, + 'Symfony\\Component\\VarDumper\\' => 28, + 'Symfony\\Component\\Translation\\' => 30, + 'Symfony\\Component\\String\\' => 25, + 'Symfony\\Component\\Routing\\' => 26, + 'Symfony\\Component\\Process\\' => 26, + 'Symfony\\Component\\Mime\\' => 23, + 'Symfony\\Component\\HttpKernel\\' => 29, + 'Symfony\\Component\\HttpFoundation\\' => 33, + 'Symfony\\Component\\Finder\\' => 25, + 'Symfony\\Component\\EventDispatcher\\' => 34, + 'Symfony\\Component\\ErrorHandler\\' => 31, + 'Symfony\\Component\\CssSelector\\' => 30, + 'Symfony\\Component\\Console\\' => 26, + ), + 'R' => + array ( + 'Ramsey\\Uuid\\' => 12, + 'Ramsey\\Collection\\' => 18, + ), + 'P' => + array ( + 'Psy\\' => 4, + 'Psr\\SimpleCache\\' => 16, + 'Psr\\Log\\' => 8, + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Http\\Client\\' => 16, + 'Psr\\EventDispatcher\\' => 20, + 'Psr\\Container\\' => 14, + 'Psr\\Clock\\' => 10, + 'PhpParser\\' => 10, + 'PhpOption\\' => 10, + 'PHPMailer\\PHPMailer\\' => 20, + ), + 'O' => + array ( + 'Opis\\Closure\\' => 13, + ), + 'M' => + array ( + 'Monolog\\' => 8, + ), + 'L' => + array ( + 'League\\MimeTypeDetection\\' => 25, + 'League\\Flysystem\\' => 17, + 'League\\Config\\' => 14, + 'League\\CommonMark\\' => 18, + 'Laravel\\Tinker\\' => 15, + 'Laravel\\SerializableClosure\\' => 28, + 'Laravel\\Sanctum\\' => 16, + ), + 'I' => + array ( + 'Illuminate\\Support\\' => 19, + 'Illuminate\\' => 11, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + 'GrahamCampbell\\ResultType\\' => 26, + ), + 'F' => + array ( + 'Fruitcake\\Cors\\' => 15, + ), + 'E' => + array ( + 'Egulias\\EmailValidator\\' => 23, + ), + 'D' => + array ( + 'Dotenv\\' => 7, + 'Doctrine\\Inflector\\' => 19, + 'Doctrine\\Common\\Lexer\\' => 22, + 'Dflydev\\DotAccessData\\' => 22, + 'Database\\Seeders\\' => 17, + 'Database\\Factories\\' => 19, + ), + 'C' => + array ( + 'Cron\\' => 5, + 'Carbon\\Doctrine\\' => 16, + 'Carbon\\' => 7, + ), + 'B' => + array ( + 'Brick\\Math\\' => 11, + ), + 'A' => + array ( + 'Asm89\\Stack\\' => 12, + 'App\\' => 4, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'voku\\' => + array ( + 0 => __DIR__ . '/..' . '/voku/portable-ascii/src/voku', + ), + 'Webmozart\\Assert\\' => + array ( + 0 => __DIR__ . '/..' . '/webmozart/assert/src', + ), + 'TijsVerkoyen\\CssToInlineStyles\\' => + array ( + 0 => __DIR__ . '/..' . '/tijsverkoyen/css-to-inline-styles/src', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Php73\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php73', + ), + 'Symfony\\Polyfill\\Php72\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php72', + ), + 'Symfony\\Polyfill\\Mbstring\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', + ), + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer', + ), + 'Symfony\\Polyfill\\Intl\\Idn\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-idn', + ), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme', + ), + 'Symfony\\Polyfill\\Iconv\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-iconv', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Symfony\\Contracts\\Translation\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/translation-contracts', + ), + 'Symfony\\Contracts\\Service\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/service-contracts', + ), + 'Symfony\\Contracts\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher-contracts', + ), + 'Symfony\\Component\\VarDumper\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/var-dumper', + ), + 'Symfony\\Component\\Translation\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/translation', + ), + 'Symfony\\Component\\String\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/string', + ), + 'Symfony\\Component\\Routing\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/routing', + ), + 'Symfony\\Component\\Process\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/process', + ), + 'Symfony\\Component\\Mime\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/mime', + ), + 'Symfony\\Component\\HttpKernel\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/http-kernel', + ), + 'Symfony\\Component\\HttpFoundation\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/http-foundation', + ), + 'Symfony\\Component\\Finder\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/finder', + ), + 'Symfony\\Component\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher', + ), + 'Symfony\\Component\\ErrorHandler\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/error-handler', + ), + 'Symfony\\Component\\CssSelector\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/css-selector', + ), + 'Symfony\\Component\\Console\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/console', + ), + 'Ramsey\\Uuid\\' => + array ( + 0 => __DIR__ . '/..' . '/ramsey/uuid/src', + ), + 'Ramsey\\Collection\\' => + array ( + 0 => __DIR__ . '/..' . '/ramsey/collection/src', + ), + 'Psy\\' => + array ( + 0 => __DIR__ . '/..' . '/psy/psysh/src', + ), + 'Psr\\SimpleCache\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/simple-cache/src', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/src', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-factory/src', + 1 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Psr\\Http\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-client/src', + ), + 'Psr\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/event-dispatcher/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'Psr\\Clock\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/clock/src', + ), + 'PhpParser\\' => + array ( + 0 => __DIR__ . '/..' . '/nikic/php-parser/lib/PhpParser', + ), + 'PhpOption\\' => + array ( + 0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption', + ), + 'PHPMailer\\PHPMailer\\' => + array ( + 0 => __DIR__ . '/..' . '/phpmailer/phpmailer/src', + ), + 'Opis\\Closure\\' => + array ( + 0 => __DIR__ . '/..' . '/opis/closure/src', + ), + 'Monolog\\' => + array ( + 0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog', + ), + 'League\\MimeTypeDetection\\' => + array ( + 0 => __DIR__ . '/..' . '/league/mime-type-detection/src', + ), + 'League\\Flysystem\\' => + array ( + 0 => __DIR__ . '/..' . '/league/flysystem/src', + ), + 'League\\Config\\' => + array ( + 0 => __DIR__ . '/..' . '/league/config/src', + ), + 'League\\CommonMark\\' => + array ( + 0 => __DIR__ . '/..' . '/league/commonmark/src', + ), + 'Laravel\\Tinker\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/tinker/src', + ), + 'Laravel\\SerializableClosure\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/serializable-closure/src', + ), + 'Laravel\\Sanctum\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/sanctum/src', + ), + 'Illuminate\\Support\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Macroable', + 1 => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Collections', + ), + 'Illuminate\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/framework/src/Illuminate', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + 'GrahamCampbell\\ResultType\\' => + array ( + 0 => __DIR__ . '/..' . '/graham-campbell/result-type/src', + ), + 'Fruitcake\\Cors\\' => + array ( + 0 => __DIR__ . '/..' . '/fruitcake/laravel-cors/src', + ), + 'Egulias\\EmailValidator\\' => + array ( + 0 => __DIR__ . '/..' . '/egulias/email-validator/src', + ), + 'Dotenv\\' => + array ( + 0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src', + ), + 'Doctrine\\Inflector\\' => + array ( + 0 => __DIR__ . '/..' . '/doctrine/inflector/lib/Doctrine/Inflector', + ), + 'Doctrine\\Common\\Lexer\\' => + array ( + 0 => __DIR__ . '/..' . '/doctrine/lexer/lib/Doctrine/Common/Lexer', + ), + 'Dflydev\\DotAccessData\\' => + array ( + 0 => __DIR__ . '/..' . '/dflydev/dot-access-data/src', + ), + 'Database\\Seeders\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/laravel/database/seeders', + ), + 'Database\\Factories\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/laravel/database/factories', + ), + 'Cron\\' => + array ( + 0 => __DIR__ . '/..' . '/dragonmantank/cron-expression/src/Cron', + ), + 'Carbon\\Doctrine\\' => + array ( + 0 => __DIR__ . '/..' . '/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine', + ), + 'Carbon\\' => + array ( + 0 => __DIR__ . '/..' . '/nesbot/carbon/src/Carbon', + ), + 'Brick\\Math\\' => + array ( + 0 => __DIR__ . '/..' . '/brick/math/src', + ), + 'Asm89\\Stack\\' => + array ( + 0 => __DIR__ . '/..' . '/asm89/stack-cors/src', + ), + 'App\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/laravel/app', + ), + ); + + public static $classMap = array ( + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'JsonException' => __DIR__ . '/..' . '/symfony/polyfill-php73/Resources/stubs/JsonException.php', + 'Nette\\ArgumentOutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\DeprecatedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\DirectoryNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\FileNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\HtmlStringable' => __DIR__ . '/..' . '/nette/utils/src/HtmlStringable.php', + 'Nette\\IOException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidArgumentException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidStateException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\Iterators\\CachingIterator' => __DIR__ . '/..' . '/nette/utils/src/Iterators/CachingIterator.php', + 'Nette\\Iterators\\Mapper' => __DIR__ . '/..' . '/nette/utils/src/Iterators/Mapper.php', + 'Nette\\Localization\\ITranslator' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php', + 'Nette\\Localization\\Translator' => __DIR__ . '/..' . '/nette/utils/src/Translator.php', + 'Nette\\MemberAccessException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\NotImplementedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\NotSupportedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\OutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\Schema\\Context' => __DIR__ . '/..' . '/nette/schema/src/Schema/Context.php', + 'Nette\\Schema\\DynamicParameter' => __DIR__ . '/..' . '/nette/schema/src/Schema/DynamicParameter.php', + 'Nette\\Schema\\Elements\\AnyOf' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/AnyOf.php', + 'Nette\\Schema\\Elements\\Base' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Base.php', + 'Nette\\Schema\\Elements\\Structure' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Structure.php', + 'Nette\\Schema\\Elements\\Type' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Type.php', + 'Nette\\Schema\\Expect' => __DIR__ . '/..' . '/nette/schema/src/Schema/Expect.php', + 'Nette\\Schema\\Helpers' => __DIR__ . '/..' . '/nette/schema/src/Schema/Helpers.php', + 'Nette\\Schema\\Message' => __DIR__ . '/..' . '/nette/schema/src/Schema/Message.php', + 'Nette\\Schema\\Processor' => __DIR__ . '/..' . '/nette/schema/src/Schema/Processor.php', + 'Nette\\Schema\\Schema' => __DIR__ . '/..' . '/nette/schema/src/Schema/Schema.php', + 'Nette\\Schema\\ValidationException' => __DIR__ . '/..' . '/nette/schema/src/Schema/ValidationException.php', + 'Nette\\SmartObject' => __DIR__ . '/..' . '/nette/utils/src/SmartObject.php', + 'Nette\\StaticClass' => __DIR__ . '/..' . '/nette/utils/src/StaticClass.php', + 'Nette\\UnexpectedValueException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\Utils\\ArrayHash' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayHash.php', + 'Nette\\Utils\\ArrayList' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayList.php', + 'Nette\\Utils\\Arrays' => __DIR__ . '/..' . '/nette/utils/src/Utils/Arrays.php', + 'Nette\\Utils\\AssertionException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Callback' => __DIR__ . '/..' . '/nette/utils/src/Utils/Callback.php', + 'Nette\\Utils\\DateTime' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTime.php', + 'Nette\\Utils\\FileInfo' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileInfo.php', + 'Nette\\Utils\\FileSystem' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileSystem.php', + 'Nette\\Utils\\Finder' => __DIR__ . '/..' . '/nette/utils/src/Utils/Finder.php', + 'Nette\\Utils\\Floats' => __DIR__ . '/..' . '/nette/utils/src/Utils/Floats.php', + 'Nette\\Utils\\Helpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/Helpers.php', + 'Nette\\Utils\\Html' => __DIR__ . '/..' . '/nette/utils/src/Utils/Html.php', + 'Nette\\Utils\\IHtmlString' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php', + 'Nette\\Utils\\Image' => __DIR__ . '/..' . '/nette/utils/src/Utils/Image.php', + 'Nette\\Utils\\ImageColor' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageColor.php', + 'Nette\\Utils\\ImageException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\ImageType' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageType.php', + 'Nette\\Utils\\Iterables' => __DIR__ . '/..' . '/nette/utils/src/Utils/Iterables.php', + 'Nette\\Utils\\Json' => __DIR__ . '/..' . '/nette/utils/src/Utils/Json.php', + 'Nette\\Utils\\JsonException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\ObjectHelpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectHelpers.php', + 'Nette\\Utils\\Paginator' => __DIR__ . '/..' . '/nette/utils/src/Utils/Paginator.php', + 'Nette\\Utils\\Random' => __DIR__ . '/..' . '/nette/utils/src/Utils/Random.php', + 'Nette\\Utils\\Reflection' => __DIR__ . '/..' . '/nette/utils/src/Utils/Reflection.php', + 'Nette\\Utils\\ReflectionMethod' => __DIR__ . '/..' . '/nette/utils/src/Utils/ReflectionMethod.php', + 'Nette\\Utils\\RegexpException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Strings' => __DIR__ . '/..' . '/nette/utils/src/Utils/Strings.php', + 'Nette\\Utils\\Type' => __DIR__ . '/..' . '/nette/utils/src/Utils/Type.php', + 'Nette\\Utils\\UnknownImageFileException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Validators' => __DIR__ . '/..' . '/nette/utils/src/Utils/Validators.php', + 'Normalizer' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.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 = ComposerStaticInitda4df0130c662759d398fc41895ca400::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitda4df0130c662759d398fc41895ca400::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitda4df0130c662759d398fc41895ca400::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/php/libraries/composer/vendor/composer/installed.json b/php/libraries/composer/vendor/composer/installed.json new file mode 100644 index 0000000..cad8817 --- /dev/null +++ b/php/libraries/composer/vendor/composer/installed.json @@ -0,0 +1,5775 @@ +{ + "packages": [ + { + "name": "asm89/stack-cors", + "version": "v2.2.0", + "version_normalized": "2.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/asm89/stack-cors.git", + "reference": "50f57105bad3d97a43ec4a485eb57daf347eafea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/asm89/stack-cors/zipball/50f57105bad3d97a43ec4a485eb57daf347eafea", + "reference": "50f57105bad3d97a43ec4a485eb57daf347eafea", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0", + "symfony/http-foundation": "^5.3|^6|^7", + "symfony/http-kernel": "^5.3|^6|^7" + }, + "require-dev": { + "phpunit/phpunit": "^9", + "squizlabs/php_codesniffer": "^3.5" + }, + "time": "2023-11-14T13:51:46+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Asm89\\Stack\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alexander", + "email": "iam.asm89@gmail.com" + } + ], + "description": "Cross-origin resource sharing library and stack middleware", + "homepage": "https://github.com/asm89/stack-cors", + "keywords": [ + "cors", + "stack" + ], + "support": { + "issues": "https://github.com/asm89/stack-cors/issues", + "source": "https://github.com/asm89/stack-cors/tree/v2.2.0" + }, + "install-path": "../asm89/stack-cors" + }, + { + "name": "brick/math", + "version": "0.11.0", + "version_normalized": "0.11.0.0", + "source": { + "type": "git", + "url": "https://github.com/brick/math.git", + "reference": "0ad82ce168c82ba30d1c01ec86116ab52f589478" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brick/math/zipball/0ad82ce168c82ba30d1c01ec86116ab52f589478", + "reference": "0ad82ce168c82ba30d1c01ec86116ab52f589478", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.2", + "phpunit/phpunit": "^9.0", + "vimeo/psalm": "5.0.0" + }, + "time": "2023-01-15T23:15:59+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Brick\\Math\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Arbitrary-precision arithmetic library", + "keywords": [ + "Arbitrary-precision", + "BigInteger", + "BigRational", + "arithmetic", + "bigdecimal", + "bignum", + "brick", + "math" + ], + "support": { + "issues": "https://github.com/brick/math/issues", + "source": "https://github.com/brick/math/tree/0.11.0" + }, + "funding": [ + { + "url": "https://github.com/BenMorel", + "type": "github" + } + ], + "install-path": "../brick/math" + }, + { + "name": "carbonphp/carbon-doctrine-types", + "version": "3.2.0", + "version_normalized": "3.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/CarbonPHP/carbon-doctrine-types.git", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "conflict": { + "doctrine/dbal": "<4.0.0 || >=5.0.0" + }, + "require-dev": { + "doctrine/dbal": "^4.0.0", + "nesbot/carbon": "^2.71.0 || ^3.0.0", + "phpunit/phpunit": "^10.3" + }, + "time": "2024-02-09T16:56:22+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Carbon\\Doctrine\\": "src/Carbon/Doctrine/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "KyleKatarn", + "email": "kylekatarnls@gmail.com" + } + ], + "description": "Types to use Carbon in Doctrine", + "keywords": [ + "carbon", + "date", + "datetime", + "doctrine", + "time" + ], + "support": { + "issues": "https://github.com/CarbonPHP/carbon-doctrine-types/issues", + "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.0" + }, + "funding": [ + { + "url": "https://github.com/kylekatarnls", + "type": "github" + }, + { + "url": "https://opencollective.com/Carbon", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "type": "tidelift" + } + ], + "install-path": "../carbonphp/carbon-doctrine-types" + }, + { + "name": "dflydev/dot-access-data", + "version": "v3.0.2", + "version_normalized": "3.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/dflydev/dflydev-dot-access-data.git", + "reference": "f41715465d65213d644d3141a6a93081be5d3549" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dflydev/dflydev-dot-access-data/zipball/f41715465d65213d644d3141a6a93081be5d3549", + "reference": "f41715465d65213d644d3141a6a93081be5d3549", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.42", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.3", + "scrutinizer/ocular": "1.6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.0.0" + }, + "time": "2022-10-27T11:44:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Dflydev\\DotAccessData\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dragonfly Development Inc.", + "email": "info@dflydev.com", + "homepage": "http://dflydev.com" + }, + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Carlos Frutos", + "email": "carlos@kiwing.it", + "homepage": "https://github.com/cfrutos" + }, + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com" + } + ], + "description": "Given a deep data structure, access data by dot notation.", + "homepage": "https://github.com/dflydev/dflydev-dot-access-data", + "keywords": [ + "access", + "data", + "dot", + "notation" + ], + "support": { + "issues": "https://github.com/dflydev/dflydev-dot-access-data/issues", + "source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.2" + }, + "install-path": "../dflydev/dot-access-data" + }, + { + "name": "doctrine/inflector", + "version": "2.0.10", + "version_normalized": "2.0.10.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/inflector.git", + "reference": "5817d0659c5b50c9b950feb9af7b9668e2c436bc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/inflector/zipball/5817d0659c5b50c9b950feb9af7b9668e2c436bc", + "reference": "5817d0659c5b50c9b950feb9af7b9668e2c436bc", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^11.0", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-phpunit": "^1.1", + "phpstan/phpstan-strict-rules": "^1.3", + "phpunit/phpunit": "^8.5 || ^9.5", + "vimeo/psalm": "^4.25 || ^5.4" + }, + "time": "2024-02-18T20:23:39+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Doctrine\\Inflector\\": "lib/Doctrine/Inflector" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.", + "homepage": "https://www.doctrine-project.org/projects/inflector.html", + "keywords": [ + "inflection", + "inflector", + "lowercase", + "manipulation", + "php", + "plural", + "singular", + "strings", + "uppercase", + "words" + ], + "support": { + "issues": "https://github.com/doctrine/inflector/issues", + "source": "https://github.com/doctrine/inflector/tree/2.0.10" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finflector", + "type": "tidelift" + } + ], + "install-path": "../doctrine/inflector" + }, + { + "name": "doctrine/lexer", + "version": "1.2.3", + "version_normalized": "1.2.3.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "c268e882d4dbdd85e36e4ad69e02dc284f89d229" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/c268e882d4dbdd85e36e4ad69e02dc284f89d229", + "reference": "c268e882d4dbdd85e36e4ad69e02dc284f89d229", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^9.0", + "phpstan/phpstan": "^1.3", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", + "vimeo/psalm": "^4.11" + }, + "time": "2022-02-28T11:07:21+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Doctrine\\Common\\Lexer\\": "lib/Doctrine/Common/Lexer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https://www.doctrine-project.org/projects/lexer.html", + "keywords": [ + "annotations", + "docblock", + "lexer", + "parser", + "php" + ], + "support": { + "issues": "https://github.com/doctrine/lexer/issues", + "source": "https://github.com/doctrine/lexer/tree/1.2.3" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Flexer", + "type": "tidelift" + } + ], + "install-path": "../doctrine/lexer" + }, + { + "name": "dragonmantank/cron-expression", + "version": "v3.3.3", + "version_normalized": "3.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/dragonmantank/cron-expression.git", + "reference": "adfb1f505deb6384dc8b39804c5065dd3c8c8c0a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/adfb1f505deb6384dc8b39804c5065dd3c8c8c0a", + "reference": "adfb1f505deb6384dc8b39804c5065dd3c8c8c0a", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0", + "webmozart/assert": "^1.0" + }, + "replace": { + "mtdowling/cron-expression": "^1.0" + }, + "require-dev": { + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-webmozart-assert": "^1.0", + "phpunit/phpunit": "^7.0|^8.0|^9.0" + }, + "time": "2023-08-10T19:36:49+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Cron\\": "src/Cron/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Tankersley", + "email": "chris@ctankersley.com", + "homepage": "https://github.com/dragonmantank" + } + ], + "description": "CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due", + "keywords": [ + "cron", + "schedule" + ], + "support": { + "issues": "https://github.com/dragonmantank/cron-expression/issues", + "source": "https://github.com/dragonmantank/cron-expression/tree/v3.3.3" + }, + "funding": [ + { + "url": "https://github.com/dragonmantank", + "type": "github" + } + ], + "install-path": "../dragonmantank/cron-expression" + }, + { + "name": "egulias/email-validator", + "version": "2.1.25", + "version_normalized": "2.1.25.0", + "source": { + "type": "git", + "url": "https://github.com/egulias/EmailValidator.git", + "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "shasum": "" + }, + "require": { + "doctrine/lexer": "^1.0.1", + "php": ">=5.5", + "symfony/polyfill-intl-idn": "^1.10" + }, + "require-dev": { + "dominicsayers/isemail": "^3.0.7", + "phpunit/phpunit": "^4.8.36|^7.5.15", + "satooshi/php-coveralls": "^1.0.1" + }, + "suggest": { + "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" + }, + "time": "2020-12-29T14:50:06+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Egulias\\EmailValidator\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eduardo Gulias Davis" + } + ], + "description": "A library for validating emails against several RFCs", + "homepage": "https://github.com/egulias/EmailValidator", + "keywords": [ + "email", + "emailvalidation", + "emailvalidator", + "validation", + "validator" + ], + "support": { + "issues": "https://github.com/egulias/EmailValidator/issues", + "source": "https://github.com/egulias/EmailValidator/tree/2.1.25" + }, + "funding": [ + { + "url": "https://github.com/egulias", + "type": "github" + } + ], + "install-path": "../egulias/email-validator" + }, + { + "name": "fruitcake/laravel-cors", + "version": "v2.2.0", + "version_normalized": "2.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/fruitcake/laravel-cors.git", + "reference": "783a74f5e3431d7b9805be8afb60fd0a8f743534" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fruitcake/laravel-cors/zipball/783a74f5e3431d7b9805be8afb60fd0a8f743534", + "reference": "783a74f5e3431d7b9805be8afb60fd0a8f743534", + "shasum": "" + }, + "require": { + "asm89/stack-cors": "^2.0.1", + "illuminate/contracts": "^6|^7|^8|^9", + "illuminate/support": "^6|^7|^8|^9", + "php": ">=7.2" + }, + "require-dev": { + "laravel/framework": "^6|^7.24|^8", + "orchestra/testbench-dusk": "^4|^5|^6|^7", + "phpunit/phpunit": "^6|^7|^8|^9", + "squizlabs/php_codesniffer": "^3.5" + }, + "time": "2022-02-23T14:25:13+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + }, + "laravel": { + "providers": [ + "Fruitcake\\Cors\\CorsServiceProvider" + ] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Fruitcake\\Cors\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fruitcake", + "homepage": "https://fruitcake.nl" + }, + { + "name": "Barry vd. Heuvel", + "email": "barryvdh@gmail.com" + } + ], + "description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application", + "keywords": [ + "api", + "cors", + "crossdomain", + "laravel" + ], + "support": { + "issues": "https://github.com/fruitcake/laravel-cors/issues", + "source": "https://github.com/fruitcake/laravel-cors/tree/v2.2.0" + }, + "funding": [ + { + "url": "https://fruitcake.nl", + "type": "custom" + }, + { + "url": "https://github.com/barryvdh", + "type": "github" + } + ], + "abandoned": true, + "install-path": "../fruitcake/laravel-cors" + }, + { + "name": "graham-campbell/result-type", + "version": "v1.1.2", + "version_normalized": "1.1.2.0", + "source": { + "type": "git", + "url": "https://github.com/GrahamCampbell/Result-Type.git", + "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862", + "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "time": "2023-11-12T22:16:48+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "An Implementation Of The Result Type", + "keywords": [ + "Graham Campbell", + "GrahamCampbell", + "Result Type", + "Result-Type", + "result" + ], + "support": { + "issues": "https://github.com/GrahamCampbell/Result-Type/issues", + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", + "type": "tidelift" + } + ], + "install-path": "../graham-campbell/result-type" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.8.1", + "version_normalized": "7.8.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/41042bc7ab002487b876a0683fc8dce04ddce104", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.1", + "guzzlehttp/psr7": "^1.9.1 || ^2.5.1", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.36 || ^9.6.15", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "time": "2023-12-03T20:35:24+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.8.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/guzzle" + }, + { + "name": "guzzlehttp/promises", + "version": "2.0.2", + "version_normalized": "2.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/bbff78d96034045e58e13dedd6ad91b5d1253223", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "time": "2023-12-03T20:19:20+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/promises" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.6.2", + "version_normalized": "2.6.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/45b30f99ac27b5ca93cb4831afe16285f57b8221", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2023-12-03T20:05:35+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.6.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/psr7" + }, + { + "name": "laravel/framework", + "version": "v8.83.27", + "version_normalized": "8.83.27.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/framework.git", + "reference": "e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/framework/zipball/e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49", + "reference": "e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49", + "shasum": "" + }, + "require": { + "doctrine/inflector": "^1.4|^2.0", + "dragonmantank/cron-expression": "^3.0.2", + "egulias/email-validator": "^2.1.10", + "ext-json": "*", + "ext-mbstring": "*", + "ext-openssl": "*", + "laravel/serializable-closure": "^1.0", + "league/commonmark": "^1.3|^2.0.2", + "league/flysystem": "^1.1", + "monolog/monolog": "^2.0", + "nesbot/carbon": "^2.53.1", + "opis/closure": "^3.6", + "php": "^7.3|^8.0", + "psr/container": "^1.0", + "psr/log": "^1.0|^2.0", + "psr/simple-cache": "^1.0", + "ramsey/uuid": "^4.2.2", + "swiftmailer/swiftmailer": "^6.3", + "symfony/console": "^5.4", + "symfony/error-handler": "^5.4", + "symfony/finder": "^5.4", + "symfony/http-foundation": "^5.4", + "symfony/http-kernel": "^5.4", + "symfony/mime": "^5.4", + "symfony/process": "^5.4", + "symfony/routing": "^5.4", + "symfony/var-dumper": "^5.4", + "tijsverkoyen/css-to-inline-styles": "^2.2.2", + "vlucas/phpdotenv": "^5.4.1", + "voku/portable-ascii": "^1.6.1" + }, + "conflict": { + "tightenco/collect": "<5.5.33" + }, + "provide": { + "psr/container-implementation": "1.0", + "psr/simple-cache-implementation": "1.0" + }, + "replace": { + "illuminate/auth": "self.version", + "illuminate/broadcasting": "self.version", + "illuminate/bus": "self.version", + "illuminate/cache": "self.version", + "illuminate/collections": "self.version", + "illuminate/config": "self.version", + "illuminate/console": "self.version", + "illuminate/container": "self.version", + "illuminate/contracts": "self.version", + "illuminate/cookie": "self.version", + "illuminate/database": "self.version", + "illuminate/encryption": "self.version", + "illuminate/events": "self.version", + "illuminate/filesystem": "self.version", + "illuminate/hashing": "self.version", + "illuminate/http": "self.version", + "illuminate/log": "self.version", + "illuminate/macroable": "self.version", + "illuminate/mail": "self.version", + "illuminate/notifications": "self.version", + "illuminate/pagination": "self.version", + "illuminate/pipeline": "self.version", + "illuminate/queue": "self.version", + "illuminate/redis": "self.version", + "illuminate/routing": "self.version", + "illuminate/session": "self.version", + "illuminate/support": "self.version", + "illuminate/testing": "self.version", + "illuminate/translation": "self.version", + "illuminate/validation": "self.version", + "illuminate/view": "self.version" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.198.1", + "doctrine/dbal": "^2.13.3|^3.1.4", + "filp/whoops": "^2.14.3", + "guzzlehttp/guzzle": "^6.5.5|^7.0.1", + "league/flysystem-cached-adapter": "^1.0", + "mockery/mockery": "^1.4.4", + "orchestra/testbench-core": "^6.27", + "pda/pheanstalk": "^4.0", + "phpunit/phpunit": "^8.5.19|^9.5.8", + "predis/predis": "^1.1.9", + "symfony/cache": "^5.4" + }, + "suggest": { + "ably/ably-php": "Required to use the Ably broadcast driver (^1.0).", + "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.198.1).", + "brianium/paratest": "Required to run tests in parallel (^6.0).", + "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.13.3|^3.1.4).", + "ext-bcmath": "Required to use the multiple_of validation rule.", + "ext-ftp": "Required to use the Flysystem FTP driver.", + "ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().", + "ext-memcached": "Required to use the memcache cache driver.", + "ext-pcntl": "Required to use all features of the queue worker.", + "ext-posix": "Required to use all features of the queue worker.", + "ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).", + "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", + "filp/whoops": "Required for friendly error pages in development (^2.14.3).", + "guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.5.5|^7.0.1).", + "laravel/tinker": "Required to use the tinker console command (^2.0).", + "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", + "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", + "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", + "mockery/mockery": "Required to use mocking (^1.4.4).", + "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", + "pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).", + "phpunit/phpunit": "Required to use assertions and run tests (^8.5.19|^9.5.8).", + "predis/predis": "Required to use the predis connector (^1.1.9).", + "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", + "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0|^5.0|^6.0|^7.0).", + "symfony/cache": "Required to PSR-6 cache bridge (^5.4).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^5.4).", + "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0).", + "wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)." + }, + "time": "2022-12-08T15:28:55+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/Illuminate/Collections/helpers.php", + "src/Illuminate/Events/functions.php", + "src/Illuminate/Foundation/helpers.php", + "src/Illuminate/Support/helpers.php" + ], + "psr-4": { + "Illuminate\\": "src/Illuminate/", + "Illuminate\\Support\\": [ + "src/Illuminate/Macroable/", + "src/Illuminate/Collections/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Laravel Framework.", + "homepage": "https://laravel.com", + "keywords": [ + "framework", + "laravel" + ], + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../laravel/framework" + }, + { + "name": "laravel/laravel", + "version": "v8.6.10", + "version_normalized": "8.6.10.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/laravel.git", + "reference": "56a73db2e34f5aa8befffcce40aaaa92e2d7393c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/laravel/zipball/56a73db2e34f5aa8befffcce40aaaa92e2d7393c", + "reference": "56a73db2e34f5aa8befffcce40aaaa92e2d7393c", + "shasum": "" + }, + "require": { + "fruitcake/laravel-cors": "^2.0", + "guzzlehttp/guzzle": "^7.0.1", + "laravel/framework": "^8.75", + "laravel/sanctum": "^2.11", + "laravel/tinker": "^2.5", + "php": "^7.3|^8.0" + }, + "require-dev": { + "facade/ignition": "^2.5", + "fakerphp/faker": "^1.9.1", + "laravel/sail": "^1.0.1", + "mockery/mockery": "^1.4.4", + "nunomaduro/collision": "^5.10", + "phpunit/phpunit": "^9.5.10" + }, + "time": "2021-12-22T10:07:28+00:00", + "type": "project", + "extra": { + "laravel": { + "dont-discover": [] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "App\\": "app/", + "Database\\Seeders\\": "database/seeders/", + "Database\\Factories\\": "database/factories/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The Laravel Framework.", + "keywords": [ + "framework", + "laravel" + ], + "support": { + "source": "https://github.com/laravel/laravel/tree/v8.6.10" + }, + "install-path": "../laravel/laravel" + }, + { + "name": "laravel/sanctum", + "version": "v2.15.1", + "version_normalized": "2.15.1.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/sanctum.git", + "reference": "31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/sanctum/zipball/31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473", + "reference": "31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/console": "^6.9|^7.0|^8.0|^9.0", + "illuminate/contracts": "^6.9|^7.0|^8.0|^9.0", + "illuminate/database": "^6.9|^7.0|^8.0|^9.0", + "illuminate/support": "^6.9|^7.0|^8.0|^9.0", + "php": "^7.2|^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0", + "phpunit/phpunit": "^8.0|^9.3" + }, + "time": "2022-04-08T13:39:49+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + }, + "laravel": { + "providers": [ + "Laravel\\Sanctum\\SanctumServiceProvider" + ] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Laravel\\Sanctum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.", + "keywords": [ + "auth", + "laravel", + "sanctum" + ], + "support": { + "issues": "https://github.com/laravel/sanctum/issues", + "source": "https://github.com/laravel/sanctum" + }, + "install-path": "../laravel/sanctum" + }, + { + "name": "laravel/serializable-closure", + "version": "v1.3.3", + "version_normalized": "1.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/serializable-closure.git", + "reference": "3dbf8a8e914634c48d389c1234552666b3d43754" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/3dbf8a8e914634c48d389c1234552666b3d43754", + "reference": "3dbf8a8e914634c48d389c1234552666b3d43754", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "nesbot/carbon": "^2.61", + "pestphp/pest": "^1.21.3", + "phpstan/phpstan": "^1.8.2", + "symfony/var-dumper": "^5.4.11" + }, + "time": "2023-11-08T14:08:06+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": [ + "closure", + "laravel", + "serializable" + ], + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "install-path": "../laravel/serializable-closure" + }, + { + "name": "laravel/tinker", + "version": "v2.9.0", + "version_normalized": "2.9.0.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/tinker.git", + "reference": "502e0fe3f0415d06d5db1f83a472f0f3b754bafe" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/tinker/zipball/502e0fe3f0415d06d5db1f83a472f0f3b754bafe", + "reference": "502e0fe3f0415d06d5db1f83a472f0f3b754bafe", + "shasum": "" + }, + "require": { + "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/contracts": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "php": "^7.2.5|^8.0", + "psy/psysh": "^0.11.1|^0.12.0", + "symfony/var-dumper": "^4.3.4|^5.0|^6.0|^7.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.3|^1.4.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^8.5.8|^9.3.3" + }, + "suggest": { + "illuminate/database": "The Illuminate Database package (^6.0|^7.0|^8.0|^9.0|^10.0|^11.0)." + }, + "time": "2024-01-04T16:10:04+00:00", + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Tinker\\TinkerServiceProvider" + ] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Laravel\\Tinker\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Powerful REPL for the Laravel framework.", + "keywords": [ + "REPL", + "Tinker", + "laravel", + "psysh" + ], + "support": { + "issues": "https://github.com/laravel/tinker/issues", + "source": "https://github.com/laravel/tinker/tree/v2.9.0" + }, + "install-path": "../laravel/tinker" + }, + { + "name": "league/commonmark", + "version": "2.4.2", + "version_normalized": "2.4.2.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/commonmark.git", + "reference": "91c24291965bd6d7c46c46a12ba7492f83b1cadf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/91c24291965bd6d7c46c46a12ba7492f83b1cadf", + "reference": "91c24291965bd6d7c46c46a12ba7492f83b1cadf", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "league/config": "^1.1.1", + "php": "^7.4 || ^8.0", + "psr/event-dispatcher": "^1.0", + "symfony/deprecation-contracts": "^2.1 || ^3.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "cebe/markdown": "^1.0", + "commonmark/cmark": "0.30.3", + "commonmark/commonmark.js": "0.30.0", + "composer/package-versions-deprecated": "^1.8", + "embed/embed": "^4.4", + "erusev/parsedown": "^1.0", + "ext-json": "*", + "github/gfm": "0.29.0", + "michelf/php-markdown": "^1.4 || ^2.0", + "nyholm/psr7": "^1.5", + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.21 || ^10.5.9 || ^11.0.0", + "scrutinizer/ocular": "^1.8.1", + "symfony/finder": "^5.3 | ^6.0 || ^7.0", + "symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0 || ^7.0", + "unleashedtech/php-coding-standard": "^3.1.1", + "vimeo/psalm": "^4.24.0 || ^5.0.0" + }, + "suggest": { + "symfony/yaml": "v2.3+ required if using the Front Matter extension" + }, + "time": "2024-02-02T11:59:32+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\CommonMark\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)", + "homepage": "https://commonmark.thephpleague.com", + "keywords": [ + "commonmark", + "flavored", + "gfm", + "github", + "github-flavored", + "markdown", + "md", + "parser" + ], + "support": { + "docs": "https://commonmark.thephpleague.com/", + "forum": "https://github.com/thephpleague/commonmark/discussions", + "issues": "https://github.com/thephpleague/commonmark/issues", + "rss": "https://github.com/thephpleague/commonmark/releases.atom", + "source": "https://github.com/thephpleague/commonmark" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/commonmark", + "type": "tidelift" + } + ], + "install-path": "../league/commonmark" + }, + { + "name": "league/config", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/config.git", + "reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/config/zipball/754b3604fb2984c71f4af4a9cbe7b57f346ec1f3", + "reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3", + "shasum": "" + }, + "require": { + "dflydev/dot-access-data": "^3.0.1", + "nette/schema": "^1.2", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "time": "2022-12-11T20:36:23+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\Config\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Define configuration arrays with strict schemas and access values with dot notation", + "homepage": "https://config.thephpleague.com", + "keywords": [ + "array", + "config", + "configuration", + "dot", + "dot-access", + "nested", + "schema" + ], + "support": { + "docs": "https://config.thephpleague.com/", + "issues": "https://github.com/thephpleague/config/issues", + "rss": "https://github.com/thephpleague/config/releases.atom", + "source": "https://github.com/thephpleague/config" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + } + ], + "install-path": "../league/config" + }, + { + "name": "league/flysystem", + "version": "1.1.3", + "version_normalized": "1.1.3.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/flysystem.git", + "reference": "9be3b16c877d477357c015cec057548cf9b2a14a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/9be3b16c877d477357c015cec057548cf9b2a14a", + "reference": "9be3b16c877d477357c015cec057548cf9b2a14a", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "league/mime-type-detection": "^1.3", + "php": "^7.2.5 || ^8.0" + }, + "conflict": { + "league/flysystem-sftp": "<1.0.6" + }, + "require-dev": { + "phpspec/prophecy": "^1.11.1", + "phpunit/phpunit": "^8.5.8" + }, + "suggest": { + "ext-ftp": "Allows you to use FTP server storage", + "ext-openssl": "Allows you to use FTPS server storage", + "league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2", + "league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3", + "league/flysystem-azure": "Allows you to use Windows Azure Blob storage", + "league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching", + "league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem", + "league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files", + "league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib", + "league/flysystem-webdav": "Allows you to use WebDAV storage", + "league/flysystem-ziparchive": "Allows you to use ZipArchive adapter", + "spatie/flysystem-dropbox": "Allows you to use Dropbox storage", + "srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications" + }, + "time": "2022-10-04T09:16:37+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\Flysystem\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frenky.net" + } + ], + "description": "Filesystem abstraction: Many filesystems, one API.", + "keywords": [ + "Cloud Files", + "WebDAV", + "abstraction", + "aws", + "cloud", + "copy.com", + "dropbox", + "file systems", + "files", + "filesystem", + "filesystems", + "ftp", + "rackspace", + "remote", + "s3", + "sftp", + "storage" + ], + "support": { + "issues": "https://github.com/thephpleague/flysystem/issues", + "source": "https://github.com/thephpleague/flysystem/tree/1.1.10" + }, + "funding": [ + { + "url": "https://offset.earth/frankdejonge", + "type": "other" + } + ], + "install-path": "../league/flysystem" + }, + { + "name": "league/mime-type-detection", + "version": "1.15.0", + "version_normalized": "1.15.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/mime-type-detection.git", + "reference": "ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/mime-type-detection/zipball/ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301", + "reference": "ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.2", + "phpstan/phpstan": "^0.12.68", + "phpunit/phpunit": "^8.5.8 || ^9.3 || ^10.0" + }, + "time": "2024-01-28T23:22:08+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\MimeTypeDetection\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "Mime-type detection for Flysystem", + "support": { + "issues": "https://github.com/thephpleague/mime-type-detection/issues", + "source": "https://github.com/thephpleague/mime-type-detection/tree/1.15.0" + }, + "funding": [ + { + "url": "https://github.com/frankdejonge", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/flysystem", + "type": "tidelift" + } + ], + "install-path": "../league/mime-type-detection" + }, + { + "name": "monolog/monolog", + "version": "2.9.2", + "version_normalized": "2.9.2.0", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", + "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", + "shasum": "" + }, + "require": { + "php": ">=7.2", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" + }, + "provide": { + "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + }, + "require-dev": { + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "elasticsearch/elasticsearch": "^7 || ^8", + "ext-json": "*", + "graylog2/gelf-php": "^1.4.2 || ^2@dev", + "guzzlehttp/guzzle": "^7.4", + "guzzlehttp/psr7": "^2.2", + "mongodb/mongodb": "^1.8", + "php-amqplib/php-amqplib": "~2.4 || ^3", + "phpspec/prophecy": "^1.15", + "phpstan/phpstan": "^0.12.91", + "phpunit/phpunit": "^8.5.14", + "predis/predis": "^1.1 || ^2.0", + "rollbar/rollbar": "^1.3 || ^2 || ^3", + "ruflin/elastica": "^7", + "swiftmailer/swiftmailer": "^5.3|^6.0", + "symfony/mailer": "^5.4 || ^6", + "symfony/mime": "^5.4 || ^6" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler", + "ext-mbstring": "Allow to work properly with unicode symbols", + "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)", + "ext-openssl": "Required to send log messages using SSL", + "ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server" + }, + "time": "2023-10-27T15:25:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "https://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "support": { + "issues": "https://github.com/Seldaek/monolog/issues", + "source": "https://github.com/Seldaek/monolog/tree/2.9.2" + }, + "funding": [ + { + "url": "https://github.com/Seldaek", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/monolog/monolog", + "type": "tidelift" + } + ], + "install-path": "../monolog/monolog" + }, + { + "name": "nesbot/carbon", + "version": "2.72.3", + "version_normalized": "2.72.3.0", + "source": { + "type": "git", + "url": "https://github.com/briannesbitt/Carbon.git", + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/0c6fd108360c562f6e4fd1dedb8233b423e91c83", + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83", + "shasum": "" + }, + "require": { + "carbonphp/carbon-doctrine-types": "*", + "ext-json": "*", + "php": "^7.1.8 || ^8.0", + "psr/clock": "^1.0", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.16", + "symfony/translation": "^3.4 || ^4.0 || ^5.0 || ^6.0" + }, + "provide": { + "psr/clock-implementation": "1.0" + }, + "require-dev": { + "doctrine/dbal": "^2.0 || ^3.1.4 || ^4.0", + "doctrine/orm": "^2.7 || ^3.0", + "friendsofphp/php-cs-fixer": "^3.0", + "kylekatarnls/multi-tester": "^2.0", + "ondrejmirtes/better-reflection": "*", + "phpmd/phpmd": "^2.9", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12.99 || ^1.7.14", + "phpunit/php-file-iterator": "^2.0.5 || ^3.0.6", + "phpunit/phpunit": "^7.5.20 || ^8.5.26 || ^9.5.20", + "squizlabs/php_codesniffer": "^3.4" + }, + "time": "2024-01-25T10:35:09+00:00", + "bin": [ + "bin/carbon" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-3.x": "3.x-dev", + "dev-master": "2.x-dev" + }, + "laravel": { + "providers": [ + "Carbon\\Laravel\\ServiceProvider" + ] + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Carbon\\": "src/Carbon/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brian Nesbitt", + "email": "brian@nesbot.com", + "homepage": "https://markido.com" + }, + { + "name": "kylekatarnls", + "homepage": "https://github.com/kylekatarnls" + } + ], + "description": "An API extension for DateTime that supports 281 different languages.", + "homepage": "https://carbon.nesbot.com", + "keywords": [ + "date", + "datetime", + "time" + ], + "support": { + "docs": "https://carbon.nesbot.com/docs", + "issues": "https://github.com/briannesbitt/Carbon/issues", + "source": "https://github.com/briannesbitt/Carbon" + }, + "funding": [ + { + "url": "https://github.com/sponsors/kylekatarnls", + "type": "github" + }, + { + "url": "https://opencollective.com/Carbon#sponsor", + "type": "opencollective" + }, + { + "url": "https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme", + "type": "tidelift" + } + ], + "install-path": "../nesbot/carbon" + }, + { + "name": "nette/schema", + "version": "v1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/nette/schema.git", + "reference": "a6d3a6d1f545f01ef38e60f375d1cf1f4de98188" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/schema/zipball/a6d3a6d1f545f01ef38e60f375d1cf1f4de98188", + "reference": "a6d3a6d1f545f01ef38e60f375d1cf1f4de98188", + "shasum": "" + }, + "require": { + "nette/utils": "^4.0", + "php": "8.1 - 8.3" + }, + "require-dev": { + "nette/tester": "^2.4", + "phpstan/phpstan-nette": "^1.0", + "tracy/tracy": "^2.8" + }, + "time": "2023-12-11T11:54:22+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "📐 Nette Schema: validating data structures against a given Schema.", + "homepage": "https://nette.org", + "keywords": [ + "config", + "nette" + ], + "support": { + "issues": "https://github.com/nette/schema/issues", + "source": "https://github.com/nette/schema/tree/v1.3.0" + }, + "install-path": "../nette/schema" + }, + { + "name": "nette/utils", + "version": "v4.0.4", + "version_normalized": "4.0.4.0", + "source": { + "type": "git", + "url": "https://github.com/nette/utils.git", + "reference": "d3ad0aa3b9f934602cb3e3902ebccf10be34d218" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/utils/zipball/d3ad0aa3b9f934602cb3e3902ebccf10be34d218", + "reference": "d3ad0aa3b9f934602cb3e3902ebccf10be34d218", + "shasum": "" + }, + "require": { + "php": ">=8.0 <8.4" + }, + "conflict": { + "nette/finder": "<3", + "nette/schema": "<1.2.2" + }, + "require-dev": { + "jetbrains/phpstorm-attributes": "dev-master", + "nette/tester": "^2.5", + "phpstan/phpstan": "^1.0", + "tracy/tracy": "^2.9" + }, + "suggest": { + "ext-gd": "to use Image", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" + }, + "time": "2024-01-17T16:50:36+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "homepage": "https://nette.org", + "keywords": [ + "array", + "core", + "datetime", + "images", + "json", + "nette", + "paginator", + "password", + "slugify", + "string", + "unicode", + "utf-8", + "utility", + "validation" + ], + "support": { + "issues": "https://github.com/nette/utils/issues", + "source": "https://github.com/nette/utils/tree/v4.0.4" + }, + "install-path": "../nette/utils" + }, + { + "name": "nikic/php-parser", + "version": "v5.0.2", + "version_normalized": "5.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "139676794dc1e9231bf7bcd123cfc0c99182cb13" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/139676794dc1e9231bf7bcd123cfc0c99182cb13", + "reference": "139676794dc1e9231bf7bcd123cfc0c99182cb13", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "time": "2024-03-05T20:51:40+00:00", + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v5.0.2" + }, + "install-path": "../nikic/php-parser" + }, + { + "name": "opis/closure", + "version": "3.6.3", + "version_normalized": "3.6.3.0", + "source": { + "type": "git", + "url": "https://github.com/opis/closure.git", + "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opis/closure/zipball/3d81e4309d2a927abbe66df935f4bb60082805ad", + "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad", + "shasum": "" + }, + "require": { + "php": "^5.4 || ^7.0 || ^8.0" + }, + "require-dev": { + "jeremeamia/superclosure": "^2.0", + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0" + }, + "time": "2022-01-27T09:35:39+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.6.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "functions.php" + ], + "psr-4": { + "Opis\\Closure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marius Sarca", + "email": "marius.sarca@gmail.com" + }, + { + "name": "Sorin Sarca", + "email": "sarca_sorin@hotmail.com" + } + ], + "description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.", + "homepage": "https://opis.io/closure", + "keywords": [ + "anonymous functions", + "closure", + "function", + "serializable", + "serialization", + "serialize" + ], + "support": { + "issues": "https://github.com/opis/closure/issues", + "source": "https://github.com/opis/closure/tree/3.6.3" + }, + "install-path": "../opis/closure" + }, + { + "name": "phpmailer/phpmailer", + "version": "v6.4.1", + "version_normalized": "6.4.1.0", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "9256f12d8fb0cd0500f93b19e18c356906cbed3d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/9256f12d8fb0cd0500f93b19e18c356906cbed3d", + "reference": "9256f12d8fb0cd0500f93b19e18c356906cbed3d", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.5.6", + "yoast/phpunit-polyfills": "^0.2.0" + }, + "suggest": { + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" + }, + "time": "2021-04-29T12:25:04+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "support": { + "issues": "https://github.com/PHPMailer/PHPMailer/issues", + "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.4.1" + }, + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "install-path": "../phpmailer/phpmailer" + }, + { + "name": "phpoption/phpoption", + "version": "1.9.2", + "version_normalized": "1.9.2.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820", + "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "time": "2023-11-12T21:59:55+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "support": { + "issues": "https://github.com/schmittjoh/php-option/issues", + "source": "https://github.com/schmittjoh/php-option/tree/1.9.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", + "type": "tidelift" + } + ], + "install-path": "../phpoption/phpoption" + }, + { + "name": "psr/clock", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/clock.git", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/clock/zipball/e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0" + }, + "time": "2022-11-25T14:36:26+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for reading the clock.", + "homepage": "https://github.com/php-fig/clock", + "keywords": [ + "clock", + "now", + "psr", + "psr-20", + "time" + ], + "support": { + "issues": "https://github.com/php-fig/clock/issues", + "source": "https://github.com/php-fig/clock/tree/1.0.0" + }, + "install-path": "../psr/clock" + }, + { + "name": "psr/container", + "version": "1.1.2", + "version_normalized": "1.1.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/513e0666f7216c7459170d56df27dfcefe1689ea", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "time": "2021-11-05T16:50:12+00:00", + "type": "library", + "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/1.1.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/http-client", + "version": "1.0.3", + "version_normalized": "1.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2023-09-23T14:17:50+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "install-path": "../psr/http-client" + }, + { + "name": "psr/http-factory", + "version": "1.0.2", + "version_normalized": "1.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "e616d01114759c4c489f93b099585439f795fe35" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35", + "reference": "e616d01114759c4c489f93b099585439f795fe35", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2023-04-10T20:10:41+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/1.0.2" + }, + "install-path": "../psr/http-factory" + }, + { + "name": "psr/http-message", + "version": "2.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "time": "2023-04-04T09:54:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "install-path": "../psr/http-message" + }, + { + "name": "psr/log", + "version": "2.0.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/ef29f6d262798707a9edd554e2b82517ef3a9376", + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2021-07-14T16:41:46+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.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/2.0.0" + }, + "install-path": "../psr/log" + }, + { + "name": "psr/simple-cache", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/simple-cache.git", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2017-10-23T01:57:42+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\SimpleCache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for simple caching", + "keywords": [ + "cache", + "caching", + "psr", + "psr-16", + "simple-cache" + ], + "support": { + "source": "https://github.com/php-fig/simple-cache/tree/master" + }, + "install-path": "../psr/simple-cache" + }, + { + "name": "psy/psysh", + "version": "v0.12.0", + "version_normalized": "0.12.0.0", + "source": { + "type": "git", + "url": "https://github.com/bobthecow/psysh.git", + "reference": "750bf031a48fd07c673dbe3f11f72362ea306d0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bobthecow/psysh/zipball/750bf031a48fd07c673dbe3f11f72362ea306d0d", + "reference": "750bf031a48fd07c673dbe3f11f72362ea306d0d", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-tokenizer": "*", + "nikic/php-parser": "^5.0 || ^4.0", + "php": "^8.0 || ^7.4", + "symfony/console": "^7.0 || ^6.0 || ^5.0 || ^4.0 || ^3.4", + "symfony/var-dumper": "^7.0 || ^6.0 || ^5.0 || ^4.0 || ^3.4" + }, + "conflict": { + "symfony/console": "4.4.37 || 5.3.14 || 5.3.15 || 5.4.3 || 5.4.4 || 6.0.3 || 6.0.4" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.2" + }, + "suggest": { + "ext-pcntl": "Enabling the PCNTL extension makes PsySH a lot happier :)", + "ext-pdo-sqlite": "The doc command requires SQLite to work.", + "ext-posix": "If you have PCNTL, you'll want the POSIX extension as well." + }, + "time": "2023-12-20T15:28:09+00:00", + "bin": [ + "bin/psysh" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "0.12.x-dev" + }, + "bamarni-bin": { + "bin-links": false, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Psy\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Justin Hileman", + "email": "justin@justinhileman.info", + "homepage": "http://justinhileman.com" + } + ], + "description": "An interactive shell for modern PHP.", + "homepage": "http://psysh.org", + "keywords": [ + "REPL", + "console", + "interactive", + "shell" + ], + "support": { + "issues": "https://github.com/bobthecow/psysh/issues", + "source": "https://github.com/bobthecow/psysh/tree/v0.12.0" + }, + "install-path": "../psy/psysh" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "install-path": "../ralouphie/getallheaders" + }, + { + "name": "ramsey/collection", + "version": "2.0.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/collection.git", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/collection/zipball/a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "captainhook/plugin-composer": "^5.3", + "ergebnis/composer-normalize": "^2.28.3", + "fakerphp/faker": "^1.21", + "hamcrest/hamcrest-php": "^2.0", + "jangregor/phpstan-prophecy": "^1.0", + "mockery/mockery": "^1.5", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpcsstandards/phpcsutils": "^1.0.0-rc1", + "phpspec/prophecy-phpunit": "^2.0", + "phpstan/extension-installer": "^1.2", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.3", + "phpunit/phpunit": "^9.5", + "psalm/plugin-mockery": "^1.1", + "psalm/plugin-phpunit": "^0.18.4", + "ramsey/coding-standard": "^2.0.3", + "ramsey/conventional-commits": "^1.3", + "vimeo/psalm": "^5.4" + }, + "time": "2022-12-31T21:50:55+00:00", + "type": "library", + "extra": { + "captainhook": { + "force-install": true + }, + "ramsey/conventional-commits": { + "configFile": "conventional-commits.json" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Ramsey\\Collection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" + } + ], + "description": "A PHP library for representing and manipulating collections.", + "keywords": [ + "array", + "collection", + "hash", + "map", + "queue", + "set" + ], + "support": { + "issues": "https://github.com/ramsey/collection/issues", + "source": "https://github.com/ramsey/collection/tree/2.0.0" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/collection", + "type": "tidelift" + } + ], + "install-path": "../ramsey/collection" + }, + { + "name": "ramsey/uuid", + "version": "4.7.5", + "version_normalized": "4.7.5.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/uuid.git", + "reference": "5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e", + "reference": "5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e", + "shasum": "" + }, + "require": { + "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11", + "ext-json": "*", + "php": "^8.0", + "ramsey/collection": "^1.2 || ^2.0" + }, + "replace": { + "rhumsaa/uuid": "self.version" + }, + "require-dev": { + "captainhook/captainhook": "^5.10", + "captainhook/plugin-composer": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.8", + "ergebnis/composer-normalize": "^2.15", + "mockery/mockery": "^1.3", + "paragonie/random-lib": "^2", + "php-mock/php-mock": "^2.2", + "php-mock/php-mock-mockery": "^1.3", + "php-parallel-lint/php-parallel-lint": "^1.1", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.1", + "phpunit/phpunit": "^8.5 || ^9", + "ramsey/composer-repl": "^1.4", + "slevomat/coding-standard": "^8.4", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.9" + }, + "suggest": { + "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", + "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + }, + "time": "2023-11-08T05:53:05+00:00", + "type": "library", + "extra": { + "captainhook": { + "force-install": true + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Ramsey\\Uuid\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "keywords": [ + "guid", + "identifier", + "uuid" + ], + "support": { + "issues": "https://github.com/ramsey/uuid/issues", + "source": "https://github.com/ramsey/uuid/tree/4.7.5" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/uuid", + "type": "tidelift" + } + ], + "install-path": "../ramsey/uuid" + }, + { + "name": "swiftmailer/swiftmailer", + "version": "v6.3.0", + "version_normalized": "6.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/swiftmailer/swiftmailer.git", + "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/8a5d5072dca8f48460fce2f4131fcc495eec654c", + "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c", + "shasum": "" + }, + "require": { + "egulias/email-validator": "^2.0|^3.1", + "php": ">=7.0.0", + "symfony/polyfill-iconv": "^1.0", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "symfony/phpunit-bridge": "^4.4|^5.4" + }, + "suggest": { + "ext-intl": "Needed to support internationalized email addresses" + }, + "time": "2021-10-18T15:26:12+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "lib/swift_required.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Corbyn" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Swiftmailer, free feature-rich PHP mailer", + "homepage": "https://swiftmailer.symfony.com", + "keywords": [ + "email", + "mail", + "mailer" + ], + "support": { + "issues": "https://github.com/swiftmailer/swiftmailer/issues", + "source": "https://github.com/swiftmailer/swiftmailer/tree/v6.3.0" + }, + "funding": [ + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/swiftmailer/swiftmailer", + "type": "tidelift" + } + ], + "abandoned": "symfony/mailer", + "install-path": "../swiftmailer/swiftmailer" + }, + { + "name": "symfony/console", + "version": "v5.4.36", + "version_normalized": "5.4.36.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e", + "reference": "39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.16", + "symfony/service-contracts": "^1.1|^2|^3", + "symfony/string": "^5.1|^6.0" + }, + "conflict": { + "psr/log": ">=3", + "symfony/dependency-injection": "<4.4", + "symfony/dotenv": "<5.1", + "symfony/event-dispatcher": "<4.4", + "symfony/lock": "<4.4", + "symfony/process": "<4.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0" + }, + "require-dev": { + "psr/log": "^1|^2", + "symfony/config": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/event-dispatcher": "^4.4|^5.0|^6.0", + "symfony/lock": "^4.4|^5.0|^6.0", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/var-dumper": "^4.4|^5.0|^6.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/lock": "", + "symfony/process": "" + }, + "time": "2024-02-20T16:33:57+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/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/console" + }, + { + "name": "symfony/css-selector", + "version": "v7.0.3", + "version_normalized": "7.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/css-selector.git", + "reference": "ec60a4edf94e63b0556b6a0888548bb400a3a3be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/ec60a4edf94e63b0556b6a0888548bb400a3a3be", + "reference": "ec60a4edf94e63b0556b6a0888548bb400a3a3be", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "time": "2024-01-23T15:02:46+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\CssSelector\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Converts CSS selectors to XPath expressions", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/css-selector/tree/v7.0.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/css-selector" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "time": "2023-05-23T14:45:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/deprecation-contracts" + }, + { + "name": "symfony/error-handler", + "version": "v5.4.36", + "version_normalized": "5.4.36.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/error-handler.git", + "reference": "90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1", + "reference": "90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "^1|^2|^3", + "symfony/var-dumper": "^4.4|^5.0|^6.0" + }, + "require-dev": { + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/http-kernel": "^4.4|^5.0|^6.0", + "symfony/serializer": "^4.4|^5.0|^6.0" + }, + "time": "2024-02-22T11:40:53+00:00", + "bin": [ + "Resources/bin/patch-type-declarations" + ], + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\ErrorHandler\\": "" + }, + "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 to manage errors and ease debugging PHP code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/error-handler/tree/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/error-handler" + }, + { + "name": "symfony/event-dispatcher", + "version": "v6.4.3", + "version_normalized": "6.4.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "ae9d3a6f3003a6caf56acd7466d8d52378d44fef" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/ae9d3a6f3003a6caf56acd7466d8d52378d44fef", + "reference": "ae9d3a6f3003a6caf56acd7466d8d52378d44fef", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/dependency-injection": "<5.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": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/expression-language": "^5.4|^6.0|^7.0", + "symfony/http-foundation": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^5.4|^6.0|^7.0" + }, + "time": "2024-01-23T14:51:35+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/v6.4.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/a76aed96a42d2b521153fb382d418e30d18b59df", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "time": "2023-05-23T14:45:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher-contracts" + }, + { + "name": "symfony/finder", + "version": "v5.4.35", + "version_normalized": "5.4.35.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "abe6d6f77d9465fed3cd2d029b29d03b56b56435" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/abe6d6f77d9465fed3cd2d029b29d03b56b56435", + "reference": "abe6d6f77d9465fed3cd2d029b29d03b56b56435", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "time": "2024-01-23T13:51:25+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/v5.4.35" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/finder" + }, + { + "name": "symfony/http-foundation", + "version": "v5.4.35", + "version_normalized": "5.4.35.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-foundation.git", + "reference": "f2ab692a22aef1cd54beb893aa0068bdfb093928" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/f2ab692a22aef1cd54beb893aa0068bdfb093928", + "reference": "f2ab692a22aef1cd54beb893aa0068bdfb093928", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "predis/predis": "~1.0", + "symfony/cache": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/http-kernel": "^5.4.12|^6.0.12|^6.1.4", + "symfony/mime": "^4.4|^5.0|^6.0", + "symfony/rate-limiter": "^5.2|^6.0" + }, + "suggest": { + "symfony/mime": "To use the file extension guesser" + }, + "time": "2024-01-23T13:51:25+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpFoundation\\": "" + }, + "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": "Defines an object-oriented layer for the HTTP specification", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-foundation/tree/v5.4.35" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/http-foundation" + }, + { + "name": "symfony/http-kernel", + "version": "v5.4.37", + "version_normalized": "5.4.37.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-kernel.git", + "reference": "4ef7ed872564852b3c6c15fecf492975a52cbff3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/4ef7ed872564852b3c6c15fecf492975a52cbff3", + "reference": "4ef7ed872564852b3c6c15fecf492975a52cbff3", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "^1|^2", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/error-handler": "^4.4|^5.0|^6.0", + "symfony/event-dispatcher": "^5.0|^6.0", + "symfony/http-foundation": "^5.4.21|^6.2.7", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "symfony/browser-kit": "<5.4", + "symfony/cache": "<5.0", + "symfony/config": "<5.0", + "symfony/console": "<4.4", + "symfony/dependency-injection": "<5.3", + "symfony/doctrine-bridge": "<5.0", + "symfony/form": "<5.0", + "symfony/http-client": "<5.0", + "symfony/mailer": "<5.0", + "symfony/messenger": "<5.0", + "symfony/translation": "<5.0", + "symfony/twig-bridge": "<5.0", + "symfony/validator": "<5.0", + "twig/twig": "<2.13" + }, + "provide": { + "psr/log-implementation": "1.0|2.0" + }, + "require-dev": { + "psr/cache": "^1.0|^2.0|^3.0", + "symfony/browser-kit": "^5.4|^6.0", + "symfony/config": "^5.0|^6.0", + "symfony/console": "^4.4|^5.0|^6.0", + "symfony/css-selector": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.3|^6.0", + "symfony/dom-crawler": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/finder": "^4.4|^5.0|^6.0", + "symfony/http-client-contracts": "^1.1|^2|^3", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/routing": "^4.4|^5.0|^6.0", + "symfony/stopwatch": "^4.4|^5.0|^6.0", + "symfony/translation": "^4.4|^5.0|^6.0", + "symfony/translation-contracts": "^1.1|^2|^3", + "twig/twig": "^2.13|^3.0.4" + }, + "suggest": { + "symfony/browser-kit": "", + "symfony/config": "", + "symfony/console": "", + "symfony/dependency-injection": "" + }, + "time": "2024-03-04T20:55:44+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpKernel\\": "" + }, + "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 structured process for converting a Request into a Response", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-kernel/tree/v5.4.37" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/http-kernel" + }, + { + "name": "symfony/mime", + "version": "v5.4.35", + "version_normalized": "5.4.35.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/mime.git", + "reference": "ee94d9b538f93abbbc1ee4ccff374593117b04a9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mime/zipball/ee94d9b538f93abbbc1ee4ccff374593117b04a9", + "reference": "ee94d9b538f93abbbc1ee4ccff374593117b04a9", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "egulias/email-validator": "~3.0.0", + "phpdocumentor/reflection-docblock": "<3.2.2", + "phpdocumentor/type-resolver": "<1.4.0", + "symfony/mailer": "<4.4", + "symfony/serializer": "<5.4.35|>=6,<6.3.12|>=6.4,<6.4.3" + }, + "require-dev": { + "egulias/email-validator": "^2.1.10|^3.1|^4", + "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/property-access": "^4.4|^5.1|^6.0", + "symfony/property-info": "^4.4|^5.1|^6.0", + "symfony/serializer": "^5.4.35|~6.3.12|^6.4.3" + }, + "time": "2024-01-30T08:00:51+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mime\\": "" + }, + "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": "Allows manipulating MIME messages", + "homepage": "https://symfony.com", + "keywords": [ + "mime", + "mime-type" + ], + "support": { + "source": "https://github.com/symfony/mime/tree/v5.4.35" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/mime" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "ef4d7e442ca910c4764bce785146269b30cb5fc4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ef4d7e442ca910c4764bce785146269b30cb5fc4", + "reference": "ef4d7e442ca910c4764bce785146269b30cb5fc4", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-ctype" + }, + { + "name": "symfony/polyfill-iconv", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-iconv.git", + "reference": "cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-iconv/zipball/cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f", + "reference": "cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-iconv": "*" + }, + "suggest": { + "ext-iconv": "For best performance" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Iconv\\": "" + } + }, + "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 Iconv extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "iconv", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-iconv/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-iconv" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "32a9da87d7b3245e09ac426c83d334ae9f06f80f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/32a9da87d7b3245e09ac426c83d334ae9f06f80f", + "reference": "32a9da87d7b3245e09ac426c83d334ae9f06f80f", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-grapheme" + }, + { + "name": "symfony/polyfill-intl-idn", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-idn.git", + "reference": "a287ed7475f85bf6f61890146edbc932c0fff919" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/a287ed7475f85bf6f61890146edbc932c0fff919", + "reference": "a287ed7475f85bf6f61890146edbc932c0fff919", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "symfony/polyfill-intl-normalizer": "^1.10", + "symfony/polyfill-php72": "^1.10" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Idn\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Laurent Bassin", + "email": "laurent@bassin.info" + }, + { + "name": "Trevor Rowbotham", + "email": "trevor.rowbotham@pm.me" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "idn", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-idn" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "bc45c394692b948b4d383a08d7753968bed9a83d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/bc45c394692b948b4d383a08d7753968bed9a83d", + "reference": "bc45c394692b948b4d383a08d7753968bed9a83d", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-normalizer" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9773676c8a1bb1f8d4340a62efe641cf76eda7ec", + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-mbstring" + }, + { + "name": "symfony/polyfill-php72", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "861391a8da9a04cbad2d232ddd9e4893220d6e25" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/861391a8da9a04cbad2d232ddd9e4893220d6e25", + "reference": "861391a8da9a04cbad2d232ddd9e4893220d6e25", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php72\\": "" + } + }, + "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 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php72/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php72" + }, + { + "name": "symfony/polyfill-php73", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php73.git", + "reference": "21bd091060673a1177ae842c0ef8fe30893114d2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/21bd091060673a1177ae842c0ef8fe30893114d2", + "reference": "21bd091060673a1177ae842c0ef8fe30893114d2", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php73\\": "" + }, + "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 7.3+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php73/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php73" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2024-01-29T20:11:03+00:00", + "type": "library", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.29.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php80" + }, + { + "name": "symfony/process", + "version": "v5.4.36", + "version_normalized": "5.4.36.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "4fdf34004f149cc20b2f51d7d119aa500caad975" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/4fdf34004f149cc20b2f51d7d119aa500caad975", + "reference": "4fdf34004f149cc20b2f51d7d119aa500caad975", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-php80": "^1.16" + }, + "time": "2024-02-12T15:49:53+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/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/process" + }, + { + "name": "symfony/routing", + "version": "v5.4.37", + "version_normalized": "5.4.37.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/routing.git", + "reference": "48ae43e443693ddb4e574f7c12f0d17ce287694e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/routing/zipball/48ae43e443693ddb4e574f7c12f0d17ce287694e", + "reference": "48ae43e443693ddb4e574f7c12f0d17ce287694e", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "doctrine/annotations": "<1.12", + "symfony/config": "<5.3", + "symfony/dependency-injection": "<4.4", + "symfony/yaml": "<4.4" + }, + "require-dev": { + "doctrine/annotations": "^1.12|^2", + "psr/log": "^1|^2|^3", + "symfony/config": "^5.3|^6.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/http-foundation": "^4.4|^5.0|^6.0", + "symfony/yaml": "^4.4|^5.0|^6.0" + }, + "suggest": { + "symfony/config": "For using the all-in-one router or any loader", + "symfony/expression-language": "For using expression matching", + "symfony/http-foundation": "For using a Symfony Request object", + "symfony/yaml": "For using the YAML loader" + }, + "time": "2024-02-27T09:52:32+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Routing\\": "" + }, + "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": "Maps an HTTP request to a set of configuration variables", + "homepage": "https://symfony.com", + "keywords": [ + "router", + "routing", + "uri", + "url" + ], + "support": { + "source": "https://github.com/symfony/routing/tree/v5.4.37" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/routing" + }, + { + "name": "symfony/service-contracts", + "version": "v3.4.1", + "version_normalized": "3.4.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "fe07cbc8d837f60caf7018068e350cc5163681a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/fe07cbc8d837f60caf7018068e350cc5163681a0", + "reference": "fe07cbc8d837f60caf7018068e350cc5163681a0", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "time": "2023-12-26T14:02:43+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.4.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/service-contracts" + }, + { + "name": "symfony/string", + "version": "v6.4.4", + "version_normalized": "6.4.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9", + "reference": "4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/http-client": "^5.4|^6.0|^7.0", + "symfony/intl": "^6.2|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^5.4|^6.0|^7.0" + }, + "time": "2024-02-01T13:16:41+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/v6.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/string" + }, + { + "name": "symfony/translation", + "version": "v6.4.4", + "version_normalized": "6.4.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation.git", + "reference": "bce6a5a78e94566641b2594d17e48b0da3184a8e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation/zipball/bce6a5a78e94566641b2594d17e48b0da3184a8e", + "reference": "bce6a5a78e94566641b2594d17e48b0da3184a8e", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/translation-contracts": "^2.5|^3.0" + }, + "conflict": { + "symfony/config": "<5.4", + "symfony/console": "<5.4", + "symfony/dependency-injection": "<5.4", + "symfony/http-client-contracts": "<2.5", + "symfony/http-kernel": "<5.4", + "symfony/service-contracts": "<2.5", + "symfony/twig-bundle": "<5.4", + "symfony/yaml": "<5.4" + }, + "provide": { + "symfony/translation-implementation": "2.3|3.0" + }, + "require-dev": { + "nikic/php-parser": "^4.18|^5.0", + "psr/log": "^1|^2|^3", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/finder": "^5.4|^6.0|^7.0", + "symfony/http-client-contracts": "^2.5|^3.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", + "symfony/polyfill-intl-icu": "^1.21", + "symfony/routing": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^5.4|^6.0|^7.0" + }, + "time": "2024-02-20T13:16:58+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\Translation\\": "" + }, + "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 to internationalize your application", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/translation/tree/v6.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/translation" + }, + { + "name": "symfony/translation-contracts", + "version": "v3.4.1", + "version_normalized": "3.4.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation-contracts.git", + "reference": "06450585bf65e978026bda220cdebca3f867fde7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/06450585bf65e978026bda220cdebca3f867fde7", + "reference": "06450585bf65e978026bda220cdebca3f867fde7", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "time": "2023-12-26T14:02:43+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Translation\\": "" + }, + "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 translation", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/translation-contracts/tree/v3.4.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/translation-contracts" + }, + { + "name": "symfony/var-dumper", + "version": "v5.4.36", + "version_normalized": "5.4.36.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90", + "reference": "2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "symfony/console": "<4.4" + }, + "require-dev": { + "ext-iconv": "*", + "symfony/console": "^4.4|^5.0|^6.0", + "symfony/http-kernel": "^4.4|^5.0|^6.0", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/uid": "^5.1|^6.0", + "twig/twig": "^2.13|^3.0.4" + }, + "suggest": { + "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", + "ext-intl": "To show region name in time zone dump", + "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" + }, + "time": "2024-02-15T11:19:14+00:00", + "bin": [ + "Resources/bin/var-dump-server" + ], + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "Resources/functions/dump.php" + ], + "psr-4": { + "Symfony\\Component\\VarDumper\\": "" + }, + "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 mechanisms for walking through any arbitrary PHP variable", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "support": { + "source": "https://github.com/symfony/var-dumper/tree/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/var-dumper" + }, + { + "name": "tijsverkoyen/css-to-inline-styles", + "version": "v2.2.7", + "version_normalized": "2.2.7.0", + "source": { + "type": "git", + "url": "https://github.com/tijsverkoyen/CssToInlineStyles.git", + "reference": "83ee6f38df0a63106a9e4536e3060458b74ccedb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/tijsverkoyen/CssToInlineStyles/zipball/83ee6f38df0a63106a9e4536e3060458b74ccedb", + "reference": "83ee6f38df0a63106a9e4536e3060458b74ccedb", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "php": "^5.5 || ^7.0 || ^8.0", + "symfony/css-selector": "^2.7 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0 || ^7.5 || ^8.5.21 || ^9.5.10" + }, + "time": "2023-12-08T13:03:43+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "TijsVerkoyen\\CssToInlineStyles\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Tijs Verkoyen", + "email": "css_to_inline_styles@verkoyen.eu", + "role": "Developer" + } + ], + "description": "CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.", + "homepage": "https://github.com/tijsverkoyen/CssToInlineStyles", + "support": { + "issues": "https://github.com/tijsverkoyen/CssToInlineStyles/issues", + "source": "https://github.com/tijsverkoyen/CssToInlineStyles/tree/v2.2.7" + }, + "install-path": "../tijsverkoyen/css-to-inline-styles" + }, + { + "name": "vlucas/phpdotenv", + "version": "v5.6.0", + "version_normalized": "5.6.0.0", + "source": { + "type": "git", + "url": "https://github.com/vlucas/phpdotenv.git", + "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4", + "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4", + "shasum": "" + }, + "require": { + "ext-pcre": "*", + "graham-campbell/result-type": "^1.1.2", + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.2", + "symfony/polyfill-ctype": "^1.24", + "symfony/polyfill-mbstring": "^1.24", + "symfony/polyfill-php80": "^1.24" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-filter": "*", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "suggest": { + "ext-filter": "Required to use the boolean validator." + }, + "time": "2023-11-12T22:43:29+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + }, + "branch-alias": { + "dev-master": "5.6-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Dotenv\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Vance Lucas", + "email": "vance@vancelucas.com", + "homepage": "https://github.com/vlucas" + } + ], + "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", + "keywords": [ + "dotenv", + "env", + "environment" + ], + "support": { + "issues": "https://github.com/vlucas/phpdotenv/issues", + "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv", + "type": "tidelift" + } + ], + "install-path": "../vlucas/phpdotenv" + }, + { + "name": "voku/portable-ascii", + "version": "1.6.1", + "version_normalized": "1.6.1.0", + "source": { + "type": "git", + "url": "https://github.com/voku/portable-ascii.git", + "reference": "87337c91b9dfacee02452244ee14ab3c43bc485a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/voku/portable-ascii/zipball/87337c91b9dfacee02452244ee14ab3c43bc485a", + "reference": "87337c91b9dfacee02452244ee14ab3c43bc485a", + "shasum": "" + }, + "require": { + "php": ">=7.0.0" + }, + "require-dev": { + "phpunit/phpunit": "~6.0 || ~7.0 || ~9.0" + }, + "suggest": { + "ext-intl": "Use Intl for transliterator_transliterate() support" + }, + "time": "2022-01-24T18:55:24+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "voku\\": "src/voku/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Lars Moelleken", + "homepage": "http://www.moelleken.org/" + } + ], + "description": "Portable ASCII library - performance optimized (ascii) string functions for php.", + "homepage": "https://github.com/voku/portable-ascii", + "keywords": [ + "ascii", + "clean", + "php" + ], + "support": { + "issues": "https://github.com/voku/portable-ascii/issues", + "source": "https://github.com/voku/portable-ascii/tree/1.6.1" + }, + "funding": [ + { + "url": "https://www.paypal.me/moelleken", + "type": "custom" + }, + { + "url": "https://github.com/voku", + "type": "github" + }, + { + "url": "https://opencollective.com/portable-ascii", + "type": "open_collective" + }, + { + "url": "https://www.patreon.com/voku", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/voku/portable-ascii", + "type": "tidelift" + } + ], + "install-path": "../voku/portable-ascii" + }, + { + "name": "webmozart/assert", + "version": "1.11.0", + "version_normalized": "1.11.0.0", + "source": { + "type": "git", + "url": "https://github.com/webmozarts/assert.git", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/11cb2199493b2f8a3b53e7f19068fc6aac760991", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "php": "^7.2 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<0.12.20", + "vimeo/psalm": "<4.6.1 || 4.6.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.13" + }, + "time": "2022-06-03T18:03:27+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/1.11.0" + }, + "install-path": "../webmozart/assert" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/php/libraries/composer/vendor/composer/installed.php b/php/libraries/composer/vendor/composer/installed.php new file mode 100644 index 0000000..7551604 --- /dev/null +++ b/php/libraries/composer/vendor/composer/installed.php @@ -0,0 +1,939 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => 'c9f5d921997fd62164963bdc9c597a981d57936c', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => 'c9f5d921997fd62164963bdc9c597a981d57936c', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'asm89/stack-cors' => array( + 'pretty_version' => 'v2.2.0', + 'version' => '2.2.0.0', + 'reference' => '50f57105bad3d97a43ec4a485eb57daf347eafea', + 'type' => 'library', + 'install_path' => __DIR__ . '/../asm89/stack-cors', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'brick/math' => array( + 'pretty_version' => '0.11.0', + 'version' => '0.11.0.0', + 'reference' => '0ad82ce168c82ba30d1c01ec86116ab52f589478', + 'type' => 'library', + 'install_path' => __DIR__ . '/../brick/math', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'carbonphp/carbon-doctrine-types' => array( + 'pretty_version' => '3.2.0', + 'version' => '3.2.0.0', + 'reference' => '18ba5ddfec8976260ead6e866180bd5d2f71aa1d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../carbonphp/carbon-doctrine-types', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'dflydev/dot-access-data' => array( + 'pretty_version' => 'v3.0.2', + 'version' => '3.0.2.0', + 'reference' => 'f41715465d65213d644d3141a6a93081be5d3549', + 'type' => 'library', + 'install_path' => __DIR__ . '/../dflydev/dot-access-data', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'doctrine/inflector' => array( + 'pretty_version' => '2.0.10', + 'version' => '2.0.10.0', + 'reference' => '5817d0659c5b50c9b950feb9af7b9668e2c436bc', + 'type' => 'library', + 'install_path' => __DIR__ . '/../doctrine/inflector', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'doctrine/lexer' => array( + 'pretty_version' => '1.2.3', + 'version' => '1.2.3.0', + 'reference' => 'c268e882d4dbdd85e36e4ad69e02dc284f89d229', + 'type' => 'library', + 'install_path' => __DIR__ . '/../doctrine/lexer', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'dragonmantank/cron-expression' => array( + 'pretty_version' => 'v3.3.3', + 'version' => '3.3.3.0', + 'reference' => 'adfb1f505deb6384dc8b39804c5065dd3c8c8c0a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../dragonmantank/cron-expression', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'egulias/email-validator' => array( + 'pretty_version' => '2.1.25', + 'version' => '2.1.25.0', + 'reference' => '0dbf5d78455d4d6a41d186da50adc1122ec066f4', + 'type' => 'library', + 'install_path' => __DIR__ . '/../egulias/email-validator', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'fruitcake/laravel-cors' => array( + 'pretty_version' => 'v2.2.0', + 'version' => '2.2.0.0', + 'reference' => '783a74f5e3431d7b9805be8afb60fd0a8f743534', + 'type' => 'library', + 'install_path' => __DIR__ . '/../fruitcake/laravel-cors', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'graham-campbell/result-type' => array( + 'pretty_version' => 'v1.1.2', + 'version' => '1.1.2.0', + 'reference' => 'fbd48bce38f73f8a4ec8583362e732e4095e5862', + 'type' => 'library', + 'install_path' => __DIR__ . '/../graham-campbell/result-type', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/guzzle' => array( + 'pretty_version' => '7.8.1', + 'version' => '7.8.1.0', + 'reference' => '41042bc7ab002487b876a0683fc8dce04ddce104', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/guzzle', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/promises' => array( + 'pretty_version' => '2.0.2', + 'version' => '2.0.2.0', + 'reference' => 'bbff78d96034045e58e13dedd6ad91b5d1253223', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/promises', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/psr7' => array( + 'pretty_version' => '2.6.2', + 'version' => '2.6.2.0', + 'reference' => '45b30f99ac27b5ca93cb4831afe16285f57b8221', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/psr7', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'illuminate/auth' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/broadcasting' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/bus' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/cache' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/collections' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/config' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/console' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/container' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/contracts' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/cookie' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/database' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/encryption' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/events' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/filesystem' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/hashing' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/http' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/log' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/macroable' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/mail' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/notifications' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/pagination' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/pipeline' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/queue' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/redis' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/routing' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/session' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/support' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/testing' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/translation' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/validation' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'illuminate/view' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => 'v8.83.27', + ), + ), + 'laravel/framework' => array( + 'pretty_version' => 'v8.83.27', + 'version' => '8.83.27.0', + 'reference' => 'e1afe088b4ca613fb96dc57e6d8dbcb8cc2c6b49', + 'type' => 'library', + 'install_path' => __DIR__ . '/../laravel/framework', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'laravel/laravel' => array( + 'pretty_version' => 'v8.6.10', + 'version' => '8.6.10.0', + 'reference' => '56a73db2e34f5aa8befffcce40aaaa92e2d7393c', + 'type' => 'project', + 'install_path' => __DIR__ . '/../laravel/laravel', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'laravel/sanctum' => array( + 'pretty_version' => 'v2.15.1', + 'version' => '2.15.1.0', + 'reference' => '31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473', + 'type' => 'library', + 'install_path' => __DIR__ . '/../laravel/sanctum', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'laravel/serializable-closure' => array( + 'pretty_version' => 'v1.3.3', + 'version' => '1.3.3.0', + 'reference' => '3dbf8a8e914634c48d389c1234552666b3d43754', + 'type' => 'library', + 'install_path' => __DIR__ . '/../laravel/serializable-closure', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'laravel/tinker' => array( + 'pretty_version' => 'v2.9.0', + 'version' => '2.9.0.0', + 'reference' => '502e0fe3f0415d06d5db1f83a472f0f3b754bafe', + 'type' => 'library', + 'install_path' => __DIR__ . '/../laravel/tinker', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/commonmark' => array( + 'pretty_version' => '2.4.2', + 'version' => '2.4.2.0', + 'reference' => '91c24291965bd6d7c46c46a12ba7492f83b1cadf', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/commonmark', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/config' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'reference' => '754b3604fb2984c71f4af4a9cbe7b57f346ec1f3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/config', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/flysystem' => array( + 'pretty_version' => '1.1.3', + 'version' => '1.1.3.0', + 'reference' => '9be3b16c877d477357c015cec057548cf9b2a14a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/flysystem', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/mime-type-detection' => array( + 'pretty_version' => '1.15.0', + 'version' => '1.15.0.0', + 'reference' => 'ce0f4d1e8a6f4eb0ddff33f57c69c50fd09f4301', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/mime-type-detection', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'monolog/monolog' => array( + 'pretty_version' => '2.9.2', + 'version' => '2.9.2.0', + 'reference' => '437cb3628f4cf6042cc10ae97fc2b8472e48ca1f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../monolog/monolog', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'mtdowling/cron-expression' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '^1.0', + ), + ), + 'nesbot/carbon' => array( + 'pretty_version' => '2.72.3', + 'version' => '2.72.3.0', + 'reference' => '0c6fd108360c562f6e4fd1dedb8233b423e91c83', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nesbot/carbon', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nette/schema' => array( + 'pretty_version' => 'v1.3.0', + 'version' => '1.3.0.0', + 'reference' => 'a6d3a6d1f545f01ef38e60f375d1cf1f4de98188', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nette/schema', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nette/utils' => array( + 'pretty_version' => 'v4.0.4', + 'version' => '4.0.4.0', + 'reference' => 'd3ad0aa3b9f934602cb3e3902ebccf10be34d218', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nette/utils', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nikic/php-parser' => array( + 'pretty_version' => 'v5.0.2', + 'version' => '5.0.2.0', + 'reference' => '139676794dc1e9231bf7bcd123cfc0c99182cb13', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nikic/php-parser', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'opis/closure' => array( + 'pretty_version' => '3.6.3', + 'version' => '3.6.3.0', + 'reference' => '3d81e4309d2a927abbe66df935f4bb60082805ad', + 'type' => 'library', + 'install_path' => __DIR__ . '/../opis/closure', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'phpmailer/phpmailer' => array( + 'pretty_version' => 'v6.4.1', + 'version' => '6.4.1.0', + 'reference' => '9256f12d8fb0cd0500f93b19e18c356906cbed3d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../phpmailer/phpmailer', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'phpoption/phpoption' => array( + 'pretty_version' => '1.9.2', + 'version' => '1.9.2.0', + 'reference' => '80735db690fe4fc5c76dfa7f9b770634285fa820', + 'type' => 'library', + 'install_path' => __DIR__ . '/../phpoption/phpoption', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/clock' => array( + 'pretty_version' => '1.0.0', + 'version' => '1.0.0.0', + 'reference' => 'e41a24703d4560fd0acb709162f73b8adfc3aa0d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/clock', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/clock-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/container' => array( + 'pretty_version' => '1.1.2', + 'version' => '1.1.2.0', + 'reference' => '513e0666f7216c7459170d56df27dfcefe1689ea', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/container', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/container-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + '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' => false, + ), + 'psr/event-dispatcher-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-client' => array( + 'pretty_version' => '1.0.3', + 'version' => '1.0.3.0', + 'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-factory' => array( + 'pretty_version' => '1.0.2', + 'version' => '1.0.2.0', + 'reference' => 'e616d01114759c4c489f93b099585439f795fe35', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-factory', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-message' => array( + 'pretty_version' => '2.0', + 'version' => '2.0.0.0', + 'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/log' => array( + 'pretty_version' => '2.0.0', + 'version' => '2.0.0.0', + 'reference' => 'ef29f6d262798707a9edd554e2b82517ef3a9376', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/log', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/log-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0.0 || 2.0.0 || 3.0.0', + 1 => '1.0|2.0', + ), + ), + 'psr/simple-cache' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => '408d5eafb83c57f6365a3ca330ff23aa4a5fa39b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/simple-cache', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/simple-cache-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psy/psysh' => array( + 'pretty_version' => 'v0.12.0', + 'version' => '0.12.0.0', + 'reference' => '750bf031a48fd07c673dbe3f11f72362ea306d0d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psy/psysh', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'ralouphie/getallheaders' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'reference' => '120b605dfeb996808c31b6477290a714d356e822', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ralouphie/getallheaders', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'ramsey/collection' => array( + 'pretty_version' => '2.0.0', + 'version' => '2.0.0.0', + 'reference' => 'a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ramsey/collection', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'ramsey/uuid' => array( + 'pretty_version' => '4.7.5', + 'version' => '4.7.5.0', + 'reference' => '5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ramsey/uuid', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'rhumsaa/uuid' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '4.7.5', + ), + ), + 'swiftmailer/swiftmailer' => array( + 'pretty_version' => 'v6.3.0', + 'version' => '6.3.0.0', + 'reference' => '8a5d5072dca8f48460fce2f4131fcc495eec654c', + 'type' => 'library', + 'install_path' => __DIR__ . '/../swiftmailer/swiftmailer', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/console' => array( + 'pretty_version' => 'v5.4.36', + 'version' => '5.4.36.0', + 'reference' => '39f75d9d73d0c11952fdcecf4877b4d0f62a8f6e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/console', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/css-selector' => array( + 'pretty_version' => 'v7.0.3', + 'version' => '7.0.3.0', + 'reference' => 'ec60a4edf94e63b0556b6a0888548bb400a3a3be', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/css-selector', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/deprecation-contracts' => array( + 'pretty_version' => 'v3.4.0', + 'version' => '3.4.0.0', + 'reference' => '7c3aff79d10325257a001fcf92d991f24fc967cf', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/error-handler' => array( + 'pretty_version' => 'v5.4.36', + 'version' => '5.4.36.0', + 'reference' => '90b1d7799bfc1b3ed5f902e8b334eeb7dba537a1', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/error-handler', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/event-dispatcher' => array( + 'pretty_version' => 'v6.4.3', + 'version' => '6.4.3.0', + 'reference' => 'ae9d3a6f3003a6caf56acd7466d8d52378d44fef', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/event-dispatcher', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/event-dispatcher-contracts' => array( + 'pretty_version' => 'v3.4.0', + 'version' => '3.4.0.0', + 'reference' => 'a76aed96a42d2b521153fb382d418e30d18b59df', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/event-dispatcher-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/event-dispatcher-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '2.0|3.0', + ), + ), + 'symfony/finder' => array( + 'pretty_version' => 'v5.4.35', + 'version' => '5.4.35.0', + 'reference' => 'abe6d6f77d9465fed3cd2d029b29d03b56b56435', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/finder', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/http-foundation' => array( + 'pretty_version' => 'v5.4.35', + 'version' => '5.4.35.0', + 'reference' => 'f2ab692a22aef1cd54beb893aa0068bdfb093928', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/http-foundation', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/http-kernel' => array( + 'pretty_version' => 'v5.4.37', + 'version' => '5.4.37.0', + 'reference' => '4ef7ed872564852b3c6c15fecf492975a52cbff3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/http-kernel', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/mime' => array( + 'pretty_version' => 'v5.4.35', + 'version' => '5.4.35.0', + 'reference' => 'ee94d9b538f93abbbc1ee4ccff374593117b04a9', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/mime', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-ctype' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => 'ef4d7e442ca910c4764bce785146269b30cb5fc4', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-iconv' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => 'cd4226d140ecd3d0f13d32ed0a4a095ffe871d2f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-iconv', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-intl-grapheme' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '32a9da87d7b3245e09ac426c83d334ae9f06f80f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-grapheme', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-intl-idn' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => 'a287ed7475f85bf6f61890146edbc932c0fff919', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-idn', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-intl-normalizer' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => 'bc45c394692b948b4d383a08d7753968bed9a83d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-normalizer', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-mbstring' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '9773676c8a1bb1f8d4340a62efe641cf76eda7ec', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php72' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '861391a8da9a04cbad2d232ddd9e4893220d6e25', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php72', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php73' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '21bd091060673a1177ae842c0ef8fe30893114d2', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php73', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php80' => array( + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '87b68208d5c1188808dd7839ee1e6c8ec3b02f1b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php80', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/process' => array( + 'pretty_version' => 'v5.4.36', + 'version' => '5.4.36.0', + 'reference' => '4fdf34004f149cc20b2f51d7d119aa500caad975', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/process', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/routing' => array( + 'pretty_version' => 'v5.4.37', + 'version' => '5.4.37.0', + 'reference' => '48ae43e443693ddb4e574f7c12f0d17ce287694e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/routing', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/service-contracts' => array( + 'pretty_version' => 'v3.4.1', + 'version' => '3.4.1.0', + 'reference' => 'fe07cbc8d837f60caf7018068e350cc5163681a0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/service-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/string' => array( + 'pretty_version' => 'v6.4.4', + 'version' => '6.4.4.0', + 'reference' => '4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/string', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/translation' => array( + 'pretty_version' => 'v6.4.4', + 'version' => '6.4.4.0', + 'reference' => 'bce6a5a78e94566641b2594d17e48b0da3184a8e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/translation', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/translation-contracts' => array( + 'pretty_version' => 'v3.4.1', + 'version' => '3.4.1.0', + 'reference' => '06450585bf65e978026bda220cdebca3f867fde7', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/translation-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/translation-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '2.3|3.0', + ), + ), + 'symfony/var-dumper' => array( + 'pretty_version' => 'v5.4.36', + 'version' => '5.4.36.0', + 'reference' => '2e9c2b11267119d9c90d6b3fdce5e4e9f15e2e90', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/var-dumper', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'tijsverkoyen/css-to-inline-styles' => array( + 'pretty_version' => 'v2.2.7', + 'version' => '2.2.7.0', + 'reference' => '83ee6f38df0a63106a9e4536e3060458b74ccedb', + 'type' => 'library', + 'install_path' => __DIR__ . '/../tijsverkoyen/css-to-inline-styles', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'vlucas/phpdotenv' => array( + 'pretty_version' => 'v5.6.0', + 'version' => '5.6.0.0', + 'reference' => '2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4', + 'type' => 'library', + 'install_path' => __DIR__ . '/../vlucas/phpdotenv', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'voku/portable-ascii' => array( + 'pretty_version' => '1.6.1', + 'version' => '1.6.1.0', + 'reference' => '87337c91b9dfacee02452244ee14ab3c43bc485a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../voku/portable-ascii', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'webmozart/assert' => array( + 'pretty_version' => '1.11.0', + 'version' => '1.11.0.0', + 'reference' => '11cb2199493b2f8a3b53e7f19068fc6aac760991', + 'type' => 'library', + 'install_path' => __DIR__ . '/../webmozart/assert', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/php/libraries/composer/vendor/composer/platform_check.php b/php/libraries/composer/vendor/composer/platform_check.php new file mode 100644 index 0000000..d32d90c --- /dev/null +++ b/php/libraries/composer/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 80200)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/CHANGELOG.md b/php/libraries/composer/vendor/dflydev/dot-access-data/CHANGELOG.md new file mode 100644 index 0000000..8e92c23 --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/CHANGELOG.md @@ -0,0 +1,67 @@ +# 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] + +## [3.0.2] - 2022-10-27 + +### Fixed + + - Added missing return types to docblocks (#44, #45) + +## [3.0.1] - 2021-08-13 + +### Added + + - Adds ReturnTypeWillChange to suppress PHP 8.1 warnings (#40) + +## [3.0.0] - 2021-01-01 + +### Added + - Added support for both `.` and `/`-delimited key paths (#24) + - Added parameter and return types to everything; enabled strict type checks (#18) + - Added new exception classes to better identify certain types of errors (#20) + - `Data` now implements `ArrayAccess` (#17) + - Added ability to merge non-associative array values (#31, #32) + +### Changed + - All thrown exceptions are now instances or subclasses of `DataException` (#20) + - Calling `get()` on a missing key path without providing a default will throw a `MissingPathException` instead of returning `null` (#29) + - Bumped supported PHP versions to 7.1 - 8.x (#18) + +### Fixed + - Fixed incorrect merging of array values into string values (#32) + - Fixed `get()` method behaving as if keys with `null` values didn't exist + +## [2.0.0] - 2017-12-21 + +### Changed + - Bumped supported PHP versions to 7.0 - 7.4 (#12) + - Switched to PSR-4 autoloading + +## [1.1.0] - 2017-01-20 + +### Added + - Added new `has()` method to check for the existence of the given key (#4, #7) + +## [1.0.1] - 2015-08-12 + +### Added + - Added new optional `$default` parameter to the `get()` method (#2) + +## [1.0.0] - 2012-07-17 + +**Initial release!** + +[Unreleased]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.2...main +[3.0.2]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v2.0.0...v3.0.0 +[2.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.1.0...v2.0.0 +[1.1.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.1...v1.1.0 +[1.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/dflydev/dflydev-dot-access-data/releases/tag/v1.0.0 diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/LICENSE b/php/libraries/composer/vendor/dflydev/dot-access-data/LICENSE new file mode 100644 index 0000000..b6880d4 --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Dragonfly Development Inc. + +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/php/libraries/composer/vendor/dflydev/dot-access-data/README.md b/php/libraries/composer/vendor/dflydev/dot-access-data/README.md new file mode 100644 index 0000000..775fbdf --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/README.md @@ -0,0 +1,158 @@ +Dot Access Data +=============== + +[![Latest Version](https://img.shields.io/packagist/v/dflydev/dot-access-data.svg?style=flat-square)](https://packagist.org/packages/dflydev/dot-access-data) +[![Total Downloads](https://img.shields.io/packagist/dt/dflydev/dot-access-data.svg?style=flat-square)](https://packagist.org/packages/dflydev/dot-access-data) +[![Software License](https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/github/workflow/status/dflydev/dflydev-dot-access-data/Tests/main.svg?style=flat-square)](https://github.com/dflydev/dflydev-dot-access-data/actions?query=workflow%3ATests+branch%3Amain) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/dflydev/dflydev-dot-access-data.svg?style=flat-square)](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data/code-structure/) +[![Quality Score](https://img.shields.io/scrutinizer/g/dflydev/dflydev-dot-access-data.svg?style=flat-square)](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data) + +Given a deep data structure, access data by dot notation. + + +Requirements +------------ + + * PHP (7.1+) + +> For PHP (5.3+) please refer to version `1.0`. + + +Usage +----- + +Abstract example: + +```php +use Dflydev\DotAccessData\Data; + +$data = new Data; + +$data->set('a.b.c', 'C'); +$data->set('a.b.d', 'D1'); +$data->append('a.b.d', 'D2'); +$data->set('a.b.e', ['E0', 'E1', 'E2']); + +// C +$data->get('a.b.c'); + +// ['D1', 'D2'] +$data->get('a.b.d'); + +// ['E0', 'E1', 'E2'] +$data->get('a.b.e'); + +// true +$data->has('a.b.c'); + +// false +$data->has('a.b.d.j'); + + +// 'some-default-value' +$data->get('some.path.that.does.not.exist', 'some-default-value'); + +// throws a MissingPathException because no default was given +$data->get('some.path.that.does.not.exist'); +``` + +A more concrete example: + +```php +use Dflydev\DotAccessData\Data; + +$data = new Data([ + 'hosts' => [ + 'hewey' => [ + 'username' => 'hman', + 'password' => 'HPASS', + 'roles' => ['web'], + ], + 'dewey' => [ + 'username' => 'dman', + 'password' => 'D---S', + 'roles' => ['web', 'db'], + 'nick' => 'dewey dman', + ], + 'lewey' => [ + 'username' => 'lman', + 'password' => 'LP@$$', + 'roles' => ['db'], + ], + ], +]); + +// hman +$username = $data->get('hosts.hewey.username'); +// HPASS +$password = $data->get('hosts.hewey.password'); +// ['web'] +$roles = $data->get('hosts.hewey.roles'); +// dewey dman +$nick = $data->get('hosts.dewey.nick'); +// Unknown +$nick = $data->get('hosts.lewey.nick', 'Unknown'); + +// DataInterface instance +$dewey = $data->getData('hosts.dewey'); +// dman +$username = $dewey->get('username'); +// D---S +$password = $dewey->get('password'); +// ['web', 'db'] +$roles = $dewey->get('roles'); + +// No more lewey +$data->remove('hosts.lewey'); + +// Add DB to hewey's roles +$data->append('hosts.hewey.roles', 'db'); + +$data->set('hosts.april', [ + 'username' => 'aman', + 'password' => '@---S', + 'roles' => ['web'], +]); + +// Check if a key exists (true to this case) +$hasKey = $data->has('hosts.dewey.username'); +``` + +`Data` may be used as an array, since it implements `ArrayAccess` interface: + +```php +// Get +$data->get('name') === $data['name']; // true + +$data['name'] = 'Dewey'; +// is equivalent to +$data->set($name, 'Dewey'); + +isset($data['name']) === $data->has('name'); + +// Remove key +unset($data['name']); +``` + +`/` can also be used as a path delimiter: + +```php +$data->set('a/b/c', 'd'); +echo $data->get('a/b/c'); // "d" + +$data->get('a/b/c') === $data->get('a.b.c'); // true +``` + +License +------- + +This library is licensed under the MIT License - see the LICENSE file +for details. + + +Community +--------- + +If you have questions or want to help out, join us in the +[#dflydev](irc://irc.freenode.net/#dflydev) channel on irc.freenode.net. diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/composer.json b/php/libraries/composer/vendor/dflydev/dot-access-data/composer.json new file mode 100644 index 0000000..44dc5ed --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/composer.json @@ -0,0 +1,67 @@ +{ + "name": "dflydev/dot-access-data", + "type": "library", + "description": "Given a deep data structure, access data by dot notation.", + "homepage": "https://github.com/dflydev/dflydev-dot-access-data", + "keywords": ["dot", "access", "data", "notation"], + "license": "MIT", + "authors": [ + { + "name": "Dragonfly Development Inc.", + "email": "info@dflydev.com", + "homepage": "http://dflydev.com" + }, + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Carlos Frutos", + "email": "carlos@kiwing.it", + "homepage": "https://github.com/cfrutos" + }, + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com" + } + ], + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.42", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.3", + "scrutinizer/ocular": "1.6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.0.0" + }, + "autoload": { + "psr-4": { + "Dflydev\\DotAccessData\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Dflydev\\DotAccessData\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "phpcs": "phpcs", + "phpstan": "phpstan analyse", + "phpunit": "phpunit --no-coverage", + "psalm": "psalm", + "test": [ + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit" + ] + } +} diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/src/Data.php b/php/libraries/composer/vendor/dflydev/dot-access-data/src/Data.php new file mode 100644 index 0000000..3409b8e --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/src/Data.php @@ -0,0 +1,286 @@ + + */ +class Data implements DataInterface, ArrayAccess +{ + private const DELIMITERS = ['.', '/']; + + /** + * Internal representation of data data + * + * @var array + */ + protected $data; + + /** + * Constructor + * + * @param array $data + */ + public function __construct(array $data = []) + { + $this->data = $data; + } + + /** + * {@inheritdoc} + */ + public function append(string $key, $value = null): void + { + $currentValue =& $this->data; + $keyPath = self::keyToPathArray($key); + + $endKey = array_pop($keyPath); + foreach ($keyPath as $currentKey) { + if (! isset($currentValue[$currentKey])) { + $currentValue[$currentKey] = []; + } + $currentValue =& $currentValue[$currentKey]; + } + + if (!isset($currentValue[$endKey])) { + $currentValue[$endKey] = []; + } + + if (!is_array($currentValue[$endKey])) { + // Promote this key to an array. + // TODO: Is this really what we want to do? + $currentValue[$endKey] = [$currentValue[$endKey]]; + } + + $currentValue[$endKey][] = $value; + } + + /** + * {@inheritdoc} + */ + public function set(string $key, $value = null): void + { + $currentValue =& $this->data; + $keyPath = self::keyToPathArray($key); + + $endKey = array_pop($keyPath); + foreach ($keyPath as $currentKey) { + if (!isset($currentValue[$currentKey])) { + $currentValue[$currentKey] = []; + } + if (!is_array($currentValue[$currentKey])) { + throw new DataException(sprintf('Key path "%s" within "%s" cannot be indexed into (is not an array)', $currentKey, self::formatPath($key))); + } + $currentValue =& $currentValue[$currentKey]; + } + $currentValue[$endKey] = $value; + } + + /** + * {@inheritdoc} + */ + public function remove(string $key): void + { + $currentValue =& $this->data; + $keyPath = self::keyToPathArray($key); + + $endKey = array_pop($keyPath); + foreach ($keyPath as $currentKey) { + if (!isset($currentValue[$currentKey])) { + return; + } + $currentValue =& $currentValue[$currentKey]; + } + unset($currentValue[$endKey]); + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function get(string $key, $default = null) + { + /** @psalm-suppress ImpureFunctionCall */ + $hasDefault = \func_num_args() > 1; + + $currentValue = $this->data; + $keyPath = self::keyToPathArray($key); + + foreach ($keyPath as $currentKey) { + if (!is_array($currentValue) || !array_key_exists($currentKey, $currentValue)) { + if ($hasDefault) { + return $default; + } + + throw new MissingPathException($key, sprintf('No data exists at the given path: "%s"', self::formatPath($keyPath))); + } + + $currentValue = $currentValue[$currentKey]; + } + + return $currentValue === null ? $default : $currentValue; + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function has(string $key): bool + { + $currentValue = $this->data; + + foreach (self::keyToPathArray($key) as $currentKey) { + if ( + !is_array($currentValue) || + !array_key_exists($currentKey, $currentValue) + ) { + return false; + } + $currentValue = $currentValue[$currentKey]; + } + + return true; + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function getData(string $key): DataInterface + { + $value = $this->get($key); + if (is_array($value) && Util::isAssoc($value)) { + return new Data($value); + } + + throw new DataException(sprintf('Value at "%s" could not be represented as a DataInterface', self::formatPath($key))); + } + + /** + * {@inheritdoc} + */ + public function import(array $data, int $mode = self::REPLACE): void + { + $this->data = Util::mergeAssocArray($this->data, $data, $mode); + } + + /** + * {@inheritdoc} + */ + public function importData(DataInterface $data, int $mode = self::REPLACE): void + { + $this->import($data->export(), $mode); + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function export(): array + { + return $this->data; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->has($key); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->get($key, null); + } + + /** + * {@inheritdoc} + * + * @param string $key + * @param mixed $value + * + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->set($key, $value); + } + + /** + * {@inheritdoc} + * + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + $this->remove($key); + } + + /** + * @param string $path + * + * @return string[] + * + * @psalm-return non-empty-list + * + * @psalm-pure + */ + protected static function keyToPathArray(string $path): array + { + if (\strlen($path) === 0) { + throw new InvalidPathException('Path cannot be an empty string'); + } + + $path = \str_replace(self::DELIMITERS, '.', $path); + + return \explode('.', $path); + } + + /** + * @param string|string[] $path + * + * @return string + * + * @psalm-pure + */ + protected static function formatPath($path): string + { + if (is_string($path)) { + $path = self::keyToPathArray($path); + } + + return implode(' » ', $path); + } +} diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/src/DataInterface.php b/php/libraries/composer/vendor/dflydev/dot-access-data/src/DataInterface.php new file mode 100644 index 0000000..5909a8c --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/src/DataInterface.php @@ -0,0 +1,131 @@ + $data + * @param self::PRESERVE|self::REPLACE|self::MERGE $mode + */ + public function import(array $data, int $mode = self::REPLACE): void; + + /** + * Import data from an external data into existing data + * + * @param DataInterface $data + * @param self::PRESERVE|self::REPLACE|self::MERGE $mode + */ + public function importData(DataInterface $data, int $mode = self::REPLACE): void; + + /** + * Export data as raw data + * + * @return array + * + * @psalm-mutation-free + */ + public function export(): array; +} diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/src/Exception/DataException.php b/php/libraries/composer/vendor/dflydev/dot-access-data/src/Exception/DataException.php new file mode 100644 index 0000000..2faf9f5 --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/src/Exception/DataException.php @@ -0,0 +1,21 @@ +path = $path; + + parent::__construct($message, $code, $previous); + } + + public function getPath(): string + { + return $this->path; + } +} diff --git a/php/libraries/composer/vendor/dflydev/dot-access-data/src/Util.php b/php/libraries/composer/vendor/dflydev/dot-access-data/src/Util.php new file mode 100644 index 0000000..5634c51 --- /dev/null +++ b/php/libraries/composer/vendor/dflydev/dot-access-data/src/Util.php @@ -0,0 +1,78 @@ + $arr + * + * @return bool + * + * @psalm-pure + */ + public static function isAssoc(array $arr): bool + { + return !count($arr) || count(array_filter(array_keys($arr), 'is_string')) == count($arr); + } + + /** + * Merge contents from one associtative array to another + * + * @param mixed $to + * @param mixed $from + * @param DataInterface::PRESERVE|DataInterface::REPLACE|DataInterface::MERGE $mode + * + * @return mixed + * + * @psalm-pure + */ + public static function mergeAssocArray($to, $from, int $mode = DataInterface::REPLACE) + { + if ($mode === DataInterface::MERGE && self::isList($to) && self::isList($from)) { + return array_merge($to, $from); + } + + if (is_array($from) && is_array($to)) { + foreach ($from as $k => $v) { + if (!isset($to[$k])) { + $to[$k] = $v; + } else { + $to[$k] = self::mergeAssocArray($to[$k], $v, $mode); + } + } + + return $to; + } + + return $mode === DataInterface::PRESERVE ? $to : $from; + } + + /** + * @param mixed $value + * + * @return bool + * + * @psalm-pure + */ + private static function isList($value): bool + { + return is_array($value) && array_values($value) === $value; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/LICENSE b/php/libraries/composer/vendor/doctrine/inflector/LICENSE new file mode 100644 index 0000000..8c38cc1 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2006-2015 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. + +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/php/libraries/composer/vendor/doctrine/inflector/README.md b/php/libraries/composer/vendor/doctrine/inflector/README.md new file mode 100644 index 0000000..6e3a97f --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/README.md @@ -0,0 +1,7 @@ +# Doctrine Inflector + +Doctrine Inflector is a small library that can perform string manipulations +with regard to uppercase/lowercase and singular/plural forms of words. + +[![Build Status](https://github.com/doctrine/inflector/workflows/Continuous%20Integration/badge.svg)](https://github.com/doctrine/inflector/actions?query=workflow%3A%22Continuous+Integration%22+branch%3A4.0.x) +[![Code Coverage](https://codecov.io/gh/doctrine/inflector/branch/2.0.x/graph/badge.svg)](https://codecov.io/gh/doctrine/inflector/branch/2.0.x) diff --git a/php/libraries/composer/vendor/doctrine/inflector/composer.json b/php/libraries/composer/vendor/doctrine/inflector/composer.json new file mode 100644 index 0000000..91d7707 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/composer.json @@ -0,0 +1,41 @@ +{ + "name": "doctrine/inflector", + "type": "library", + "description": "PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.", + "keywords": ["php", "strings", "words", "manipulation", "inflector", "inflection", "uppercase", "lowercase", "singular", "plural"], + "homepage": "https://www.doctrine-project.org/projects/inflector.html", + "license": "MIT", + "authors": [ + {"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"}, + {"name": "Roman Borschel", "email": "roman@code-factory.org"}, + {"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"}, + {"name": "Jonathan Wage", "email": "jonwage@gmail.com"}, + {"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"} + ], + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^11.0", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-phpunit": "^1.1", + "phpstan/phpstan-strict-rules": "^1.3", + "phpunit/phpunit": "^8.5 || ^9.5", + "vimeo/psalm": "^4.25 || ^5.4" + }, + "autoload": { + "psr-4": { + "Doctrine\\Inflector\\": "lib/Doctrine/Inflector" + } + }, + "autoload-dev": { + "psr-4": { + "Doctrine\\Tests\\Inflector\\": "tests/Doctrine/Tests/Inflector" + } + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/docs/en/index.rst b/php/libraries/composer/vendor/doctrine/inflector/docs/en/index.rst new file mode 100644 index 0000000..29866f4 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/docs/en/index.rst @@ -0,0 +1,226 @@ +Introduction +============ + +The Doctrine Inflector has methods for inflecting text. The features include pluralization, +singularization, converting between camelCase and under_score and capitalizing +words. + +Installation +============ + +You can install the Inflector with composer: + +.. code-block:: console + + $ composer require doctrine/inflector + +Usage +===== + +Using the inflector is easy, you can create a new ``Doctrine\Inflector\Inflector`` instance by using +the ``Doctrine\Inflector\InflectorFactory`` class: + +.. code-block:: php + + use Doctrine\Inflector\InflectorFactory; + + $inflector = InflectorFactory::create()->build(); + +By default it will create an English inflector. If you want to use another language, just pass the language +you want to create an inflector for to the ``createForLanguage()`` method: + +.. code-block:: php + + use Doctrine\Inflector\InflectorFactory; + use Doctrine\Inflector\Language; + + $inflector = InflectorFactory::createForLanguage(Language::SPANISH)->build(); + +The supported languages are as follows: + +- ``Language::ENGLISH`` +- ``Language::FRENCH`` +- ``Language::NORWEGIAN_BOKMAL`` +- ``Language::PORTUGUESE`` +- ``Language::SPANISH`` +- ``Language::TURKISH`` + +If you want to manually construct the inflector instead of using a factory, you can do so like this: + +.. code-block:: php + + use Doctrine\Inflector\CachedWordInflector; + use Doctrine\Inflector\RulesetInflector; + use Doctrine\Inflector\Rules\English; + + $inflector = new Inflector( + new CachedWordInflector(new RulesetInflector( + English\Rules::getSingularRuleset() + )), + new CachedWordInflector(new RulesetInflector( + English\Rules::getPluralRuleset() + )) + ); + +Adding Languages +---------------- + +If you are interested in adding support for your language, take a look at the other languages defined in the +``Doctrine\Inflector\Rules`` namespace and the tests located in ``Doctrine\Tests\Inflector\Rules``. You can copy +one of the languages and update the rules for your language. + +Once you have done this, send a pull request to the ``doctrine/inflector`` repository with the additions. + +Custom Setup +============ + +If you want to setup custom singular and plural rules, you can configure these in the factory: + +.. code-block:: php + + use Doctrine\Inflector\InflectorFactory; + use Doctrine\Inflector\Rules\Pattern; + use Doctrine\Inflector\Rules\Patterns; + use Doctrine\Inflector\Rules\Ruleset; + use Doctrine\Inflector\Rules\Substitution; + use Doctrine\Inflector\Rules\Substitutions; + use Doctrine\Inflector\Rules\Transformation; + use Doctrine\Inflector\Rules\Transformations; + use Doctrine\Inflector\Rules\Word; + + $inflector = InflectorFactory::create() + ->withSingularRules( + new Ruleset( + new Transformations( + new Transformation(new Pattern('/^(bil)er$/i'), '\1'), + new Transformation(new Pattern('/^(inflec|contribu)tors$/i'), '\1ta') + ), + new Patterns(new Pattern('singulars')), + new Substitutions(new Substitution(new Word('spins'), new Word('spinor'))) + ) + ) + ->withPluralRules( + new Ruleset( + new Transformations( + new Transformation(new Pattern('^(bil)er$'), '\1'), + new Transformation(new Pattern('^(inflec|contribu)tors$'), '\1ta') + ), + new Patterns(new Pattern('noflect'), new Pattern('abtuse')), + new Substitutions( + new Substitution(new Word('amaze'), new Word('amazable')), + new Substitution(new Word('phone'), new Word('phonezes')) + ) + ) + ) + ->build(); + +No operation inflector +---------------------- + +The ``Doctrine\Inflector\NoopWordInflector`` may be used to configure an inflector that doesn't perform any operation for +pluralization and/or singularization. If will simply return the input as output. + +This is an implementation of the `Null Object design pattern `_. + +.. code-block:: php + + use Doctrine\Inflector\Inflector; + use Doctrine\Inflector\NoopWordInflector; + + $inflector = new Inflector(new NoopWordInflector(), new NoopWordInflector()); + +Tableize +======== + +Converts ``ModelName`` to ``model_name``: + +.. code-block:: php + + echo $inflector->tableize('ModelName'); // model_name + +Classify +======== + +Converts ``model_name`` to ``ModelName``: + +.. code-block:: php + + echo $inflector->classify('model_name'); // ModelName + +Camelize +======== + +This method uses `Classify`_ and then converts the first character to lowercase: + +.. code-block:: php + + echo $inflector->camelize('model_name'); // modelName + +Capitalize +========== + +Takes a string and capitalizes all of the words, like PHP's built-in +``ucwords`` function. This extends that behavior, however, by allowing the +word delimiters to be configured, rather than only separating on +whitespace. + +Here is an example: + +.. code-block:: php + + $string = 'top-o-the-morning to all_of_you!'; + + echo $inflector->capitalize($string); // Top-O-The-Morning To All_of_you! + + echo $inflector->capitalize($string, '-_ '); // Top-O-The-Morning To All_Of_You! + +Pluralize +========= + +Returns a word in plural form. + +.. code-block:: php + + echo $inflector->pluralize('browser'); // browsers + +Singularize +=========== + +Returns a word in singular form. + +.. code-block:: php + + echo $inflector->singularize('browsers'); // browser + +Urlize +====== + +Generate a URL friendly string from a string of text: + +.. code-block:: php + + echo $inflector->urlize('My first blog post'); // my-first-blog-post + +Unaccent +======== + +You can unaccent a string of text using the ``unaccent()`` method: + +.. code-block:: php + + echo $inflector->unaccent('año'); // ano + +Legacy API +========== + +The API present in Inflector 1.x is still available, but will be deprecated in a future release and dropped for 3.0. +Support for languages other than English is available in the 2.0 API only. + +Acknowledgements +================ + +The language rules in this library have been adapted from several different sources, including but not limited to: + +- `Ruby On Rails Inflector `_ +- `ICanBoogie Inflector `_ +- `CakePHP Inflector `_ diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/CachedWordInflector.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/CachedWordInflector.php new file mode 100644 index 0000000..2d52908 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/CachedWordInflector.php @@ -0,0 +1,24 @@ +wordInflector = $wordInflector; + } + + public function inflect(string $word): string + { + return $this->cache[$word] ?? $this->cache[$word] = $this->wordInflector->inflect($word); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/GenericLanguageInflectorFactory.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/GenericLanguageInflectorFactory.php new file mode 100644 index 0000000..166061d --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/GenericLanguageInflectorFactory.php @@ -0,0 +1,66 @@ +singularRulesets[] = $this->getSingularRuleset(); + $this->pluralRulesets[] = $this->getPluralRuleset(); + } + + final public function build(): Inflector + { + return new Inflector( + new CachedWordInflector(new RulesetInflector( + ...$this->singularRulesets + )), + new CachedWordInflector(new RulesetInflector( + ...$this->pluralRulesets + )) + ); + } + + final public function withSingularRules(?Ruleset $singularRules, bool $reset = false): LanguageInflectorFactory + { + if ($reset) { + $this->singularRulesets = []; + } + + if ($singularRules instanceof Ruleset) { + array_unshift($this->singularRulesets, $singularRules); + } + + return $this; + } + + final public function withPluralRules(?Ruleset $pluralRules, bool $reset = false): LanguageInflectorFactory + { + if ($reset) { + $this->pluralRulesets = []; + } + + if ($pluralRules instanceof Ruleset) { + array_unshift($this->pluralRulesets, $pluralRules); + } + + return $this; + } + + abstract protected function getSingularRuleset(): Ruleset; + + abstract protected function getPluralRuleset(): Ruleset; +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Inflector.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Inflector.php new file mode 100644 index 0000000..610a4cf --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Inflector.php @@ -0,0 +1,507 @@ + 'A', + 'Á' => 'A', + 'Â' => 'A', + 'Ã' => 'A', + 'Ä' => 'Ae', + 'Æ' => 'Ae', + 'Å' => 'Aa', + 'æ' => 'a', + 'Ç' => 'C', + 'È' => 'E', + 'É' => 'E', + 'Ê' => 'E', + 'Ë' => 'E', + 'Ì' => 'I', + 'Í' => 'I', + 'Î' => 'I', + 'Ï' => 'I', + 'Ñ' => 'N', + 'Ò' => 'O', + 'Ó' => 'O', + 'Ô' => 'O', + 'Õ' => 'O', + 'Ö' => 'Oe', + 'Ù' => 'U', + 'Ú' => 'U', + 'Û' => 'U', + 'Ü' => 'Ue', + 'Ý' => 'Y', + 'ß' => 'ss', + 'à' => 'a', + 'á' => 'a', + 'â' => 'a', + 'ã' => 'a', + 'ä' => 'ae', + 'å' => 'aa', + 'ç' => 'c', + 'è' => 'e', + 'é' => 'e', + 'ê' => 'e', + 'ë' => 'e', + 'ì' => 'i', + 'í' => 'i', + 'î' => 'i', + 'ï' => 'i', + 'ñ' => 'n', + 'ò' => 'o', + 'ó' => 'o', + 'ô' => 'o', + 'õ' => 'o', + 'ö' => 'oe', + 'ù' => 'u', + 'ú' => 'u', + 'û' => 'u', + 'ü' => 'ue', + 'ý' => 'y', + 'ÿ' => 'y', + 'Ā' => 'A', + 'ā' => 'a', + 'Ă' => 'A', + 'ă' => 'a', + 'Ą' => 'A', + 'ą' => 'a', + 'Ć' => 'C', + 'ć' => 'c', + 'Ĉ' => 'C', + 'ĉ' => 'c', + 'Ċ' => 'C', + 'ċ' => 'c', + 'Č' => 'C', + 'č' => 'c', + 'Ď' => 'D', + 'ď' => 'd', + 'Đ' => 'D', + 'đ' => 'd', + 'Ē' => 'E', + 'ē' => 'e', + 'Ĕ' => 'E', + 'ĕ' => 'e', + 'Ė' => 'E', + 'ė' => 'e', + 'Ę' => 'E', + 'ę' => 'e', + 'Ě' => 'E', + 'ě' => 'e', + 'Ĝ' => 'G', + 'ĝ' => 'g', + 'Ğ' => 'G', + 'ğ' => 'g', + 'Ġ' => 'G', + 'ġ' => 'g', + 'Ģ' => 'G', + 'ģ' => 'g', + 'Ĥ' => 'H', + 'ĥ' => 'h', + 'Ħ' => 'H', + 'ħ' => 'h', + 'Ĩ' => 'I', + 'ĩ' => 'i', + 'Ī' => 'I', + 'ī' => 'i', + 'Ĭ' => 'I', + 'ĭ' => 'i', + 'Į' => 'I', + 'į' => 'i', + 'İ' => 'I', + 'ı' => 'i', + 'IJ' => 'IJ', + 'ij' => 'ij', + 'Ĵ' => 'J', + 'ĵ' => 'j', + 'Ķ' => 'K', + 'ķ' => 'k', + 'ĸ' => 'k', + 'Ĺ' => 'L', + 'ĺ' => 'l', + 'Ļ' => 'L', + 'ļ' => 'l', + 'Ľ' => 'L', + 'ľ' => 'l', + 'Ŀ' => 'L', + 'ŀ' => 'l', + 'Ł' => 'L', + 'ł' => 'l', + 'Ń' => 'N', + 'ń' => 'n', + 'Ņ' => 'N', + 'ņ' => 'n', + 'Ň' => 'N', + 'ň' => 'n', + 'ʼn' => 'N', + 'Ŋ' => 'n', + 'ŋ' => 'N', + 'Ō' => 'O', + 'ō' => 'o', + 'Ŏ' => 'O', + 'ŏ' => 'o', + 'Ő' => 'O', + 'ő' => 'o', + 'Œ' => 'OE', + 'œ' => 'oe', + 'Ø' => 'O', + 'ø' => 'o', + 'Ŕ' => 'R', + 'ŕ' => 'r', + 'Ŗ' => 'R', + 'ŗ' => 'r', + 'Ř' => 'R', + 'ř' => 'r', + 'Ś' => 'S', + 'ś' => 's', + 'Ŝ' => 'S', + 'ŝ' => 's', + 'Ş' => 'S', + 'ş' => 's', + 'Š' => 'S', + 'š' => 's', + 'Ţ' => 'T', + 'ţ' => 't', + 'Ť' => 'T', + 'ť' => 't', + 'Ŧ' => 'T', + 'ŧ' => 't', + 'Ũ' => 'U', + 'ũ' => 'u', + 'Ū' => 'U', + 'ū' => 'u', + 'Ŭ' => 'U', + 'ŭ' => 'u', + 'Ů' => 'U', + 'ů' => 'u', + 'Ű' => 'U', + 'ű' => 'u', + 'Ų' => 'U', + 'ų' => 'u', + 'Ŵ' => 'W', + 'ŵ' => 'w', + 'Ŷ' => 'Y', + 'ŷ' => 'y', + 'Ÿ' => 'Y', + 'Ź' => 'Z', + 'ź' => 'z', + 'Ż' => 'Z', + 'ż' => 'z', + 'Ž' => 'Z', + 'ž' => 'z', + 'ſ' => 's', + '€' => 'E', + '£' => '', + ]; + + /** @var WordInflector */ + private $singularizer; + + /** @var WordInflector */ + private $pluralizer; + + public function __construct(WordInflector $singularizer, WordInflector $pluralizer) + { + $this->singularizer = $singularizer; + $this->pluralizer = $pluralizer; + } + + /** + * Converts a word into the format for a Doctrine table name. Converts 'ModelName' to 'model_name'. + */ + public function tableize(string $word): string + { + $tableized = preg_replace('~(?<=\\w)([A-Z])~u', '_$1', $word); + + if ($tableized === null) { + throw new RuntimeException(sprintf( + 'preg_replace returned null for value "%s"', + $word + )); + } + + return mb_strtolower($tableized); + } + + /** + * Converts a word into the format for a Doctrine class name. Converts 'table_name' to 'TableName'. + */ + public function classify(string $word): string + { + return str_replace([' ', '_', '-'], '', ucwords($word, ' _-')); + } + + /** + * Camelizes a word. This uses the classify() method and turns the first character to lowercase. + */ + public function camelize(string $word): string + { + return lcfirst($this->classify($word)); + } + + /** + * Uppercases words with configurable delimiters between words. + * + * Takes a string and capitalizes all of the words, like PHP's built-in + * ucwords function. This extends that behavior, however, by allowing the + * word delimiters to be configured, rather than only separating on + * whitespace. + * + * Here is an example: + * + * capitalize($string); + * // Top-O-The-Morning To All_of_you! + * + * echo $inflector->capitalize($string, '-_ '); + * // Top-O-The-Morning To All_Of_You! + * ?> + * + * + * @param string $string The string to operate on. + * @param string $delimiters A list of word separators. + * + * @return string The string with all delimiter-separated words capitalized. + */ + public function capitalize(string $string, string $delimiters = " \n\t\r\0\x0B-"): string + { + return ucwords($string, $delimiters); + } + + /** + * Checks if the given string seems like it has utf8 characters in it. + * + * @param string $string The string to check for utf8 characters in. + */ + public function seemsUtf8(string $string): bool + { + for ($i = 0; $i < strlen($string); $i++) { + if (ord($string[$i]) < 0x80) { + continue; // 0bbbbbbb + } + + if ((ord($string[$i]) & 0xE0) === 0xC0) { + $n = 1; // 110bbbbb + } elseif ((ord($string[$i]) & 0xF0) === 0xE0) { + $n = 2; // 1110bbbb + } elseif ((ord($string[$i]) & 0xF8) === 0xF0) { + $n = 3; // 11110bbb + } elseif ((ord($string[$i]) & 0xFC) === 0xF8) { + $n = 4; // 111110bb + } elseif ((ord($string[$i]) & 0xFE) === 0xFC) { + $n = 5; // 1111110b + } else { + return false; // Does not match any model + } + + for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ? + if (++$i === strlen($string) || ((ord($string[$i]) & 0xC0) !== 0x80)) { + return false; + } + } + } + + return true; + } + + /** + * Remove any illegal characters, accents, etc. + * + * @param string $string String to unaccent + * + * @return string Unaccented string + */ + public function unaccent(string $string): string + { + if (preg_match('/[\x80-\xff]/', $string) === false) { + return $string; + } + + if ($this->seemsUtf8($string)) { + $string = strtr($string, self::ACCENTED_CHARACTERS); + } else { + $characters = []; + + // Assume ISO-8859-1 if not UTF-8 + $characters['in'] = + chr(128) + . chr(131) + . chr(138) + . chr(142) + . chr(154) + . chr(158) + . chr(159) + . chr(162) + . chr(165) + . chr(181) + . chr(192) + . chr(193) + . chr(194) + . chr(195) + . chr(196) + . chr(197) + . chr(199) + . chr(200) + . chr(201) + . chr(202) + . chr(203) + . chr(204) + . chr(205) + . chr(206) + . chr(207) + . chr(209) + . chr(210) + . chr(211) + . chr(212) + . chr(213) + . chr(214) + . chr(216) + . chr(217) + . chr(218) + . chr(219) + . chr(220) + . chr(221) + . chr(224) + . chr(225) + . chr(226) + . chr(227) + . chr(228) + . chr(229) + . chr(231) + . chr(232) + . chr(233) + . chr(234) + . chr(235) + . chr(236) + . chr(237) + . chr(238) + . chr(239) + . chr(241) + . chr(242) + . chr(243) + . chr(244) + . chr(245) + . chr(246) + . chr(248) + . chr(249) + . chr(250) + . chr(251) + . chr(252) + . chr(253) + . chr(255); + + $characters['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'; + + $string = strtr($string, $characters['in'], $characters['out']); + + $doubleChars = []; + + $doubleChars['in'] = [ + chr(140), + chr(156), + chr(198), + chr(208), + chr(222), + chr(223), + chr(230), + chr(240), + chr(254), + ]; + + $doubleChars['out'] = ['OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th']; + + $string = str_replace($doubleChars['in'], $doubleChars['out'], $string); + } + + return $string; + } + + /** + * Convert any passed string to a url friendly string. + * Converts 'My first blog post' to 'my-first-blog-post' + * + * @param string $string String to urlize. + * + * @return string Urlized string. + */ + public function urlize(string $string): string + { + // Remove all non url friendly characters with the unaccent function + $unaccented = $this->unaccent($string); + + if (function_exists('mb_strtolower')) { + $lowered = mb_strtolower($unaccented); + } else { + $lowered = strtolower($unaccented); + } + + $replacements = [ + '/\W/' => ' ', + '/([A-Z]+)([A-Z][a-z])/' => '\1_\2', + '/([a-z\d])([A-Z])/' => '\1_\2', + '/[^A-Z^a-z^0-9^\/]+/' => '-', + ]; + + $urlized = $lowered; + + foreach ($replacements as $pattern => $replacement) { + $replaced = preg_replace($pattern, $replacement, $urlized); + + if ($replaced === null) { + throw new RuntimeException(sprintf( + 'preg_replace returned null for value "%s"', + $urlized + )); + } + + $urlized = $replaced; + } + + return trim($urlized, '-'); + } + + /** + * Returns a word in singular form. + * + * @param string $word The word in plural form. + * + * @return string The word in singular form. + */ + public function singularize(string $word): string + { + return $this->singularizer->inflect($word); + } + + /** + * Returns a word in plural form. + * + * @param string $word The word in singular form. + * + * @return string The word in plural form. + */ + public function pluralize(string $word): string + { + return $this->pluralizer->inflect($word); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/InflectorFactory.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/InflectorFactory.php new file mode 100644 index 0000000..a0740a7 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/InflectorFactory.php @@ -0,0 +1,52 @@ +getFlippedSubstitutions() + ); + } + + public static function getPluralRuleset(): Ruleset + { + return new Ruleset( + new Transformations(...Inflectible::getPlural()), + new Patterns(...Uninflected::getPlural()), + new Substitutions(...Inflectible::getIrregular()) + ); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/English/Uninflected.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/English/Uninflected.php new file mode 100644 index 0000000..02257de --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/English/Uninflected.php @@ -0,0 +1,189 @@ +getFlippedSubstitutions() + ); + } + + public static function getPluralRuleset(): Ruleset + { + return new Ruleset( + new Transformations(...Inflectible::getPlural()), + new Patterns(...Uninflected::getPlural()), + new Substitutions(...Inflectible::getIrregular()) + ); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/French/Uninflected.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/French/Uninflected.php new file mode 100644 index 0000000..9747f91 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/French/Uninflected.php @@ -0,0 +1,28 @@ +getFlippedSubstitutions() + ); + } + + public static function getPluralRuleset(): Ruleset + { + return new Ruleset( + new Transformations(...Inflectible::getPlural()), + new Patterns(...Uninflected::getPlural()), + new Substitutions(...Inflectible::getIrregular()) + ); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/NorwegianBokmal/Uninflected.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/NorwegianBokmal/Uninflected.php new file mode 100644 index 0000000..5d8d3b3 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/NorwegianBokmal/Uninflected.php @@ -0,0 +1,30 @@ +pattern = $pattern; + + if (isset($this->pattern[0]) && $this->pattern[0] === '/') { + $this->regex = $this->pattern; + } else { + $this->regex = '/' . $this->pattern . '/i'; + } + } + + public function getPattern(): string + { + return $this->pattern; + } + + public function getRegex(): string + { + return $this->regex; + } + + public function matches(string $word): bool + { + return preg_match($this->getRegex(), $word) === 1; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Patterns.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Patterns.php new file mode 100644 index 0000000..e8d45cb --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Patterns.php @@ -0,0 +1,34 @@ +patterns = $patterns; + + $patterns = array_map(static function (Pattern $pattern): string { + return $pattern->getPattern(); + }, $this->patterns); + + $this->regex = '/^(?:' . implode('|', $patterns) . ')$/i'; + } + + public function matches(string $word): bool + { + return preg_match($this->regex, $word, $regs) === 1; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Portuguese/Inflectible.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Portuguese/Inflectible.php new file mode 100644 index 0000000..0d41fe7 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Portuguese/Inflectible.php @@ -0,0 +1,98 @@ +getFlippedSubstitutions() + ); + } + + public static function getPluralRuleset(): Ruleset + { + return new Ruleset( + new Transformations(...Inflectible::getPlural()), + new Patterns(...Uninflected::getPlural()), + new Substitutions(...Inflectible::getIrregular()) + ); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Portuguese/Uninflected.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Portuguese/Uninflected.php new file mode 100644 index 0000000..b8e988f --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Portuguese/Uninflected.php @@ -0,0 +1,32 @@ +regular = $regular; + $this->uninflected = $uninflected; + $this->irregular = $irregular; + } + + public function getRegular(): Transformations + { + return $this->regular; + } + + public function getUninflected(): Patterns + { + return $this->uninflected; + } + + public function getIrregular(): Substitutions + { + return $this->irregular; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Spanish/Inflectible.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Spanish/Inflectible.php new file mode 100644 index 0000000..9129460 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Spanish/Inflectible.php @@ -0,0 +1,47 @@ +getFlippedSubstitutions() + ); + } + + public static function getPluralRuleset(): Ruleset + { + return new Ruleset( + new Transformations(...Inflectible::getPlural()), + new Patterns(...Uninflected::getPlural()), + new Substitutions(...Inflectible::getIrregular()) + ); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Spanish/Uninflected.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Spanish/Uninflected.php new file mode 100644 index 0000000..c26ebe9 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Spanish/Uninflected.php @@ -0,0 +1,30 @@ +from = $from; + $this->to = $to; + } + + public function getFrom(): Word + { + return $this->from; + } + + public function getTo(): Word + { + return $this->to; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Substitutions.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Substitutions.php new file mode 100644 index 0000000..17ee296 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Substitutions.php @@ -0,0 +1,57 @@ +substitutions[$substitution->getFrom()->getWord()] = $substitution; + } + } + + public function getFlippedSubstitutions(): Substitutions + { + $substitutions = []; + + foreach ($this->substitutions as $substitution) { + $substitutions[] = new Substitution( + $substitution->getTo(), + $substitution->getFrom() + ); + } + + return new Substitutions(...$substitutions); + } + + public function inflect(string $word): string + { + $lowerWord = strtolower($word); + + if (isset($this->substitutions[$lowerWord])) { + $firstLetterUppercase = $lowerWord[0] !== $word[0]; + + $toWord = $this->substitutions[$lowerWord]->getTo()->getWord(); + + if ($firstLetterUppercase) { + return strtoupper($toWord[0]) . substr($toWord, 1); + } + + return $toWord; + } + + return $word; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Transformation.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Transformation.php new file mode 100644 index 0000000..30dcd59 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Transformation.php @@ -0,0 +1,39 @@ +pattern = $pattern; + $this->replacement = $replacement; + } + + public function getPattern(): Pattern + { + return $this->pattern; + } + + public function getReplacement(): string + { + return $this->replacement; + } + + public function inflect(string $word): string + { + return (string) preg_replace($this->pattern->getRegex(), $this->replacement, $word); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Transformations.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Transformations.php new file mode 100644 index 0000000..b6a48fa --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Transformations.php @@ -0,0 +1,29 @@ +transformations = $transformations; + } + + public function inflect(string $word): string + { + foreach ($this->transformations as $transformation) { + if ($transformation->getPattern()->matches($word)) { + return $transformation->inflect($word); + } + } + + return $word; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Turkish/Inflectible.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Turkish/Inflectible.php new file mode 100644 index 0000000..a2bda0d --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Turkish/Inflectible.php @@ -0,0 +1,34 @@ +getFlippedSubstitutions() + ); + } + + public static function getPluralRuleset(): Ruleset + { + return new Ruleset( + new Transformations(...Inflectible::getPlural()), + new Patterns(...Uninflected::getPlural()), + new Substitutions(...Inflectible::getIrregular()) + ); + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Turkish/Uninflected.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Turkish/Uninflected.php new file mode 100644 index 0000000..ec1c37d --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/Rules/Turkish/Uninflected.php @@ -0,0 +1,30 @@ +word = $word; + } + + public function getWord(): string + { + return $this->word; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/RulesetInflector.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/RulesetInflector.php new file mode 100644 index 0000000..12b2ed5 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/RulesetInflector.php @@ -0,0 +1,56 @@ +rulesets = array_merge([$ruleset], $rulesets); + } + + public function inflect(string $word): string + { + if ($word === '') { + return ''; + } + + foreach ($this->rulesets as $ruleset) { + if ($ruleset->getUninflected()->matches($word)) { + return $word; + } + + $inflected = $ruleset->getIrregular()->inflect($word); + + if ($inflected !== $word) { + return $inflected; + } + + $inflected = $ruleset->getRegular()->inflect($word); + + if ($inflected !== $word) { + return $inflected; + } + } + + return $word; + } +} diff --git a/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/WordInflector.php b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/WordInflector.php new file mode 100644 index 0000000..b88b1d6 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/inflector/lib/Doctrine/Inflector/WordInflector.php @@ -0,0 +1,10 @@ + + */ + private $tokens = []; + + /** + * Current lexer position in input string. + * + * @var int + */ + private $position = 0; + + /** + * Current peek of current lexer position. + * + * @var int + */ + private $peek = 0; + + /** + * The next token in the input. + * + * @var mixed[]|null + * @psalm-var Token|null + */ + public $lookahead; + + /** + * The last matched/seen token. + * + * @var mixed[]|null + * @psalm-var Token|null + */ + public $token; + + /** + * Composed regex for input parsing. + * + * @var string|null + */ + private $regex; + + /** + * Sets the input data to be tokenized. + * + * The Lexer is immediately reset and the new input tokenized. + * Any unprocessed tokens from any previous input are lost. + * + * @param string $input The input to be tokenized. + * + * @return void + */ + public function setInput($input) + { + $this->input = $input; + $this->tokens = []; + + $this->reset(); + $this->scan($input); + } + + /** + * Resets the lexer. + * + * @return void + */ + public function reset() + { + $this->lookahead = null; + $this->token = null; + $this->peek = 0; + $this->position = 0; + } + + /** + * Resets the peek pointer to 0. + * + * @return void + */ + public function resetPeek() + { + $this->peek = 0; + } + + /** + * Resets the lexer position on the input to the given position. + * + * @param int $position Position to place the lexical scanner. + * + * @return void + */ + public function resetPosition($position = 0) + { + $this->position = $position; + } + + /** + * Retrieve the original lexer's input until a given position. + * + * @param int $position + * + * @return string + */ + public function getInputUntilPosition($position) + { + return substr($this->input, 0, $position); + } + + /** + * Checks whether a given token matches the current lookahead. + * + * @param int|string $type + * + * @return bool + */ + public function isNextToken($type) + { + return $this->lookahead !== null && $this->lookahead['type'] === $type; + } + + /** + * Checks whether any of the given tokens matches the current lookahead. + * + * @param list $types + * + * @return bool + */ + public function isNextTokenAny(array $types) + { + return $this->lookahead !== null && in_array($this->lookahead['type'], $types, true); + } + + /** + * Moves to the next token in the input string. + * + * @return bool + */ + public function moveNext() + { + $this->peek = 0; + $this->token = $this->lookahead; + $this->lookahead = isset($this->tokens[$this->position]) + ? $this->tokens[$this->position++] : null; + + return $this->lookahead !== null; + } + + /** + * Tells the lexer to skip input tokens until it sees a token with the given value. + * + * @param string $type The token type to skip until. + * + * @return void + */ + public function skipUntil($type) + { + while ($this->lookahead !== null && $this->lookahead['type'] !== $type) { + $this->moveNext(); + } + } + + /** + * Checks if given value is identical to the given token. + * + * @param mixed $value + * @param int|string $token + * + * @return bool + */ + public function isA($value, $token) + { + return $this->getType($value) === $token; + } + + /** + * Moves the lookahead token forward. + * + * @return mixed[]|null The next token or NULL if there are no more tokens ahead. + * @psalm-return Token|null + */ + public function peek() + { + if (isset($this->tokens[$this->position + $this->peek])) { + return $this->tokens[$this->position + $this->peek++]; + } + + return null; + } + + /** + * Peeks at the next token, returns it and immediately resets the peek. + * + * @return mixed[]|null The next token or NULL if there are no more tokens ahead. + * @psalm-return Token|null + */ + public function glimpse() + { + $peek = $this->peek(); + $this->peek = 0; + + return $peek; + } + + /** + * Scans the input string for tokens. + * + * @param string $input A query string. + * + * @return void + */ + protected function scan($input) + { + if (! isset($this->regex)) { + $this->regex = sprintf( + '/(%s)|%s/%s', + implode(')|(', $this->getCatchablePatterns()), + implode('|', $this->getNonCatchablePatterns()), + $this->getModifiers() + ); + } + + $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE; + $matches = preg_split($this->regex, $input, -1, $flags); + + if ($matches === false) { + // Work around https://bugs.php.net/78122 + $matches = [[$input, 0]]; + } + + foreach ($matches as $match) { + // Must remain before 'value' assignment since it can change content + $type = $this->getType($match[0]); + + $this->tokens[] = [ + 'value' => $match[0], + 'type' => $type, + 'position' => $match[1], + ]; + } + } + + /** + * Gets the literal for a given token. + * + * @param int|string $token + * + * @return int|string + */ + public function getLiteral($token) + { + $className = static::class; + $reflClass = new ReflectionClass($className); + $constants = $reflClass->getConstants(); + + foreach ($constants as $name => $value) { + if ($value === $token) { + return $className . '::' . $name; + } + } + + return $token; + } + + /** + * Regex modifiers + * + * @return string + */ + protected function getModifiers() + { + return 'iu'; + } + + /** + * Lexical catchable patterns. + * + * @return string[] + */ + abstract protected function getCatchablePatterns(); + + /** + * Lexical non-catchable patterns. + * + * @return string[] + */ + abstract protected function getNonCatchablePatterns(); + + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @param string $value + * + * @return int|string|null + */ + abstract protected function getType(&$value); +} diff --git a/php/libraries/composer/vendor/doctrine/lexer/psalm.xml b/php/libraries/composer/vendor/doctrine/lexer/psalm.xml new file mode 100644 index 0000000..f331e50 --- /dev/null +++ b/php/libraries/composer/vendor/doctrine/lexer/psalm.xml @@ -0,0 +1,15 @@ + + + + + + + + + diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/CHANGELOG.md b/php/libraries/composer/vendor/dragonmantank/cron-expression/CHANGELOG.md new file mode 100644 index 0000000..17ab2ce --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/CHANGELOG.md @@ -0,0 +1,240 @@ +# Change Log + +## [3.3.3] - 2024-08-10 + +### Added +- N/A + +### Changed +- N/A + +### Fixed +- Added fixes for making sure `?` is not passed for both DOM and DOW (#148, thank you https://github.com/LeoVie) +- Fixed bug in Next Execution Time by sorting minutes properly (#160, thank you https://github.com/imyip) + +## [3.3.2] - 2022-09-19 + +### Added +- N/A + +### Changed +- Skip some daylight savings time tests for PHP 8.1 daylight savings time weirdness (#146) + +### Fixed +- Changed string interpolations to work better with PHP 8.2 (#142) + +## [3.3.1] - 2022-01-18 + +### Added +- N/A + +### Changed +- N/A + +### Fixed +- Fixed issue when timezones had no transition, which can occur over very short timespans (#134) + +## [3.3.0] - 2022-01-13 + +### Added +- Added ability to register your own expression aliases (#132) + +### Changed +- Changed how Day of Week and Day of Month resolve when one or the other is `*` or `?` + +### Fixed +- PHPStan should no longer error out + +## [3.2.4] - 2022-01-12 + +### Added +- N/A + +### Changed +- Changed how Day of Week increment/decrement to help with DST changes (#131) + +### Fixed +- N/A + +## [3.2.3] - 2022-01-05 + +### Added +- N/A + +### Changed +- Changed how minutes and hours increment/decrement to help with DST changes (#131) + +### Fixed +- N/A + +## [3.2.2] - 2022-01-05 + +### Added +- N/A + +### Changed +- Marked some methods `@internal` (#124) + +### Fixed +- Fixed issue with small ranges and large steps that caused an error with `range()` (#88) +- Fixed issue where wraparound logic incorrectly considered high bound on range (#89) + +## [3.2.1] - 2022-01-04 + +### Added +- N/A + +### Changed +- Added PHP 8.1 to testing (#125) + +### Fixed +- Allow better mixture of ranges, steps, and lists (#122) +- Fixed return order when multiple dates are requested and inverted (#121) +- Better handling over DST (#115) +- Fixed PHPStan tests (#130) + +## [3.2.0] - 2022-01-04 + +### Added +- Added alias for `@midnight` (#117) + +### Changed +- Improved testing for instance of field in tests (#105) +- Optimization for determining multiple run dates (#75) +- `CronExpression` properties changed from private to protected (#106) + +### Fixed +- N/A + +## [3.1.0] - 2020-11-24 + +### Added +- Added `CronExpression::getParts()` method to get parts of the expression as an array (#83) + +### Changed +- Changed to Interfaces for some type hints (#97, #86) +- Dropped minimum PHP version to 7.2 +- Few syntax changes for phpstan compatibility (#93) + +### Fixed +- N/A + +### Deprecated +- Deprecated `CronExpression::factory` in favor of the constructor (#56) +- Deprecated `CronExpression::YEAR` as a formality, the functionality is already removed (#87) + +## [3.0.1] - 2020-10-12 +### Added +- Added support for PHP 8 (#92) +### Changed +- N/A +### Fixed +- N/A + +## [3.0.0] - 2020-03-25 + +**MAJOR CHANGE** - In previous versions of this library, setting both a "Day of Month" and a "Day of Week" would be interpreted as an `AND` statement, not an `OR` statement. For example: + +`30 0 1 * 1` + +would evaluate to "Run 30 minutes after the 0 hour when the Day Of Month is 1 AND a Monday" instead of "Run 30 minutes after the 0 hour on Day Of Month 1 OR a Monday", where the latter is more inline with most cron systems. This means that if your cron expression has both of these fields set, you may see your expression fire more often starting with v3.0.0. + +### Added +- Additional docblocks for IDE and documentation +- Added phpstan as a development dependency +- Added a `Cron\FieldFactoryInterface` to make migrations easier (#38) +### Changed +- Changed some DI testing during TravisCI runs +- `\Cron\CronExpression::determineTimezone()` now checks for `\DateTimeInterface` instead of just `\DateTime` +- Errors with fields now report a more human-understandable error and are 1-based instead of 0-based +- Better support for `\DateTimeImmutable` across the library by typehinting for `\DateTimeInterface` now +- Literals should now be less case-sensative across the board +- Changed logic for when both a Day of Week and a Day of Month are supplied to now be an OR statement, not an AND +### Fixed +- Fixed infinite loop when determining last day of week from literals +- Fixed bug where single number ranges were allowed (ex: `1/10`) +- Fixed nullable FieldFactory in CronExpression where no factory could be supplied +- Fixed issue where logic for dropping seconds to 0 could lead to a timezone change + +## [2.3.1] - 2020-10-12 +### Added +- Added support for PHP 8 (#92) +### Changed +- N/A +### Fixed +- N/A + +## [2.3.0] - 2019-03-30 +### Added +- Added support for DateTimeImmutable via DateTimeInterface +- Added support for PHP 7.3 +- Started listing projects that use the library +### Changed +- Errors should now report a human readable position in the cron expression, instead of starting at 0 +### Fixed +- N/A + +## [2.2.0] - 2018-06-05 +### Added +- Added support for steps larger than field ranges (#6) +## Changed +- N/A +### Fixed +- Fixed validation for numbers with leading 0s (#12) + +## [2.1.0] - 2018-04-06 +### Added +- N/A +### Changed +- Upgraded to PHPUnit 6 (#2) +### Fixed +- Refactored timezones to deal with some inconsistent behavior (#3) +- Allow ranges and lists in same expression (#5) +- Fixed regression where literals were not converted to their numerical counterpart (#) + +## [2.0.0] - 2017-10-12 +### Added +- N/A + +### Changed +- Dropped support for PHP 5.x +- Dropped support for the YEAR field, as it was not part of the cron standard + +### Fixed +- Reworked validation for all the field types +- Stepping should now work for 1-indexed fields like Month (#153) + +## [1.2.0] - 2017-01-22 +### Added +- Added IDE, CodeSniffer, and StyleCI.IO support + +### Changed +- Switched to PSR-4 Autoloading + +### Fixed +- 0 step expressions are handled better +- Fixed `DayOfMonth` validation to be more strict +- Typos + +## [1.1.0] - 2016-01-26 +### Added +- Support for non-hourly offset timezones +- Checks for valid expressions + +### Changed +- Max Iterations no longer hardcoded for `getRunDate()` +- Supports DateTimeImmutable for newer PHP verions + +### Fixed +- Fixed looping bug for PHP 7 when determining the last specified weekday of a month + +## [1.0.3] - 2013-11-23 +### Added +- Now supports expressions with any number of extra spaces, tabs, or newlines + +### Changed +- Using static instead of self in `CronExpression::factory` + +### Fixed +- Fixes issue [#28](https://github.com/mtdowling/cron-expression/issues/28) where PHP increments of ranges were failing due to PHP casting hyphens to 0 +- Only set default timezone if the given $currentTime is not a DateTime instance ([#34](https://github.com/mtdowling/cron-expression/issues/34)) diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/LICENSE b/php/libraries/composer/vendor/dragonmantank/cron-expression/LICENSE new file mode 100644 index 0000000..3e38bbc --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Michael Dowling , 2016 Chris Tankersley , and contributors + +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/php/libraries/composer/vendor/dragonmantank/cron-expression/README.md b/php/libraries/composer/vendor/dragonmantank/cron-expression/README.md new file mode 100644 index 0000000..494652c --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/README.md @@ -0,0 +1,87 @@ +PHP Cron Expression Parser +========================== + +[![Latest Stable Version](https://poser.pugx.org/dragonmantank/cron-expression/v/stable.png)](https://packagist.org/packages/dragonmantank/cron-expression) [![Total Downloads](https://poser.pugx.org/dragonmantank/cron-expression/downloads.png)](https://packagist.org/packages/dragonmantank/cron-expression) [![Build Status](https://secure.travis-ci.org/dragonmantank/cron-expression.png)](http://travis-ci.org/dragonmantank/cron-expression) [![StyleCI](https://github.styleci.io/repos/103715337/shield?branch=master)](https://github.styleci.io/repos/103715337) + +The PHP cron expression parser can parse a CRON expression, determine if it is +due to run, calculate the next run date of the expression, and calculate the previous +run date of the expression. You can calculate dates far into the future or past by +skipping **n** number of matching dates. + +The parser can handle increments of ranges (e.g. */12, 2-59/3), intervals (e.g. 0-9), +lists (e.g. 1,2,3), **W** to find the nearest weekday for a given day of the month, **L** to +find the last day of the month, **L** to find the last given weekday of a month, and hash +(#) to find the nth weekday of a given month. + +More information about this fork can be found in the blog post [here](http://ctankersley.com/2017/10/12/cron-expression-update/). tl;dr - v2.0.0 is a major breaking change, and @dragonmantank can better take care of the project in a separate fork. + +Installing +========== + +Add the dependency to your project: + +```bash +composer require dragonmantank/cron-expression +``` + +Usage +===== +```php +isDue(); +echo $cron->getNextRunDate()->format('Y-m-d H:i:s'); +echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s'); + +// Works with complex expressions +$cron = new Cron\CronExpression('3-59/15 6-12 */15 1 2-5'); +echo $cron->getNextRunDate()->format('Y-m-d H:i:s'); + +// Calculate a run date two iterations into the future +$cron = new Cron\CronExpression('@daily'); +echo $cron->getNextRunDate(null, 2)->format('Y-m-d H:i:s'); + +// Calculate a run date relative to a specific time +$cron = new Cron\CronExpression('@monthly'); +echo $cron->getNextRunDate('2010-01-12 00:00:00')->format('Y-m-d H:i:s'); +``` + +CRON Expressions +================ + +A CRON expression is a string representing the schedule for a particular command to execute. The parts of a CRON schedule are as follows: + + * * * * * + - - - - - + | | | | | + | | | | | + | | | | +----- day of week (0 - 7) (Sunday=0 or 7) + | | | +---------- month (1 - 12) + | | +--------------- day of month (1 - 31) + | +-------------------- hour (0 - 23) + +------------------------- min (0 - 59) + +This library also supports a few macros: + +* `@yearly`, `@annually` - Run once a year, midnight, Jan. 1 - `0 0 1 1 *` +* `@monthly` - Run once a month, midnight, first of month - `0 0 1 * *` +* `@weekly` - Run once a week, midnight on Sun - `0 0 * * 0` +* `@daily`, `@midnight` - Run once a day, midnight - `0 0 * * *` +* `@hourly` - Run once an hour, first minute - `0 * * * *` + +Requirements +============ + +- PHP 7.2+ +- PHPUnit is required to run the unit tests +- Composer is required to run the unit tests + +Projects that Use cron-expression +================================= +* Part of the [Laravel Framework](https://github.com/laravel/framework/) +* Available as a [Symfony Bundle - setono/cron-expression-bundle](https://github.com/Setono/CronExpressionBundle) +* Framework agnostic, PHP-based job scheduler - [Crunz](https://github.com/crunzphp/crunz) diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/composer.json b/php/libraries/composer/vendor/dragonmantank/cron-expression/composer.json new file mode 100644 index 0000000..657a5b4 --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/composer.json @@ -0,0 +1,47 @@ +{ + "name": "dragonmantank/cron-expression", + "type": "library", + "description": "CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due", + "keywords": ["cron", "schedule"], + "license": "MIT", + "authors": [ + { + "name": "Chris Tankersley", + "email": "chris@ctankersley.com", + "homepage": "https://github.com/dragonmantank" + } + ], + "require": { + "php": "^7.2|^8.0", + "webmozart/assert": "^1.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpunit/phpunit": "^7.0|^8.0|^9.0", + "phpstan/phpstan-webmozart-assert": "^1.0", + "phpstan/extension-installer": "^1.0" + }, + "autoload": { + "psr-4": { + "Cron\\": "src/Cron/" + } + }, + "autoload-dev": { + "psr-4": { + "Cron\\Tests\\": "tests/Cron/" + } + }, + "replace": { + "mtdowling/cron-expression": "^1.0" + }, + "scripts": { + "phpstan": "./vendor/bin/phpstan analyze", + "test": "phpunit" + }, + "config": { + "allow-plugins": { + "ocramius/package-versions": true, + "phpstan/extension-installer": true + } + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/AbstractField.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/AbstractField.php new file mode 100644 index 0000000..df2848d --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/AbstractField.php @@ -0,0 +1,346 @@ +fullRange = range($this->rangeStart, $this->rangeEnd); + } + + /** + * Check to see if a field is satisfied by a value. + * + * @internal + * @param int $dateValue Date value to check + * @param string $value Value to test + * + * @return bool + */ + public function isSatisfied(int $dateValue, string $value): bool + { + if ($this->isIncrementsOfRanges($value)) { + return $this->isInIncrementsOfRanges($dateValue, $value); + } + + if ($this->isRange($value)) { + return $this->isInRange($dateValue, $value); + } + + return '*' === $value || $dateValue === (int) $value; + } + + /** + * Check if a value is a range. + * + * @internal + * @param string $value Value to test + * + * @return bool + */ + public function isRange(string $value): bool + { + return false !== strpos($value, '-'); + } + + /** + * Check if a value is an increments of ranges. + * + * @internal + * @param string $value Value to test + * + * @return bool + */ + public function isIncrementsOfRanges(string $value): bool + { + return false !== strpos($value, '/'); + } + + /** + * Test if a value is within a range. + * + * @internal + * @param int $dateValue Set date value + * @param string $value Value to test + * + * @return bool + */ + public function isInRange(int $dateValue, $value): bool + { + $parts = array_map( + function ($value) { + $value = trim($value); + + return $this->convertLiterals($value); + }, + explode('-', $value, 2) + ); + + return $dateValue >= $parts[0] && $dateValue <= $parts[1]; + } + + /** + * Test if a value is within an increments of ranges (offset[-to]/step size). + * + * @internal + * @param int $dateValue Set date value + * @param string $value Value to test + * + * @return bool + */ + public function isInIncrementsOfRanges(int $dateValue, string $value): bool + { + $chunks = array_map('trim', explode('/', $value, 2)); + $range = $chunks[0]; + $step = $chunks[1] ?? 0; + + // No step or 0 steps aren't cool + /** @phpstan-ignore-next-line */ + if (null === $step || '0' === $step || 0 === $step) { + return false; + } + + // Expand the * to a full range + if ('*' === $range) { + $range = $this->rangeStart . '-' . $this->rangeEnd; + } + + // Generate the requested small range + $rangeChunks = explode('-', $range, 2); + $rangeStart = (int) $rangeChunks[0]; + $rangeEnd = $rangeChunks[1] ?? $rangeStart; + $rangeEnd = (int) $rangeEnd; + + if ($rangeStart < $this->rangeStart || $rangeStart > $this->rangeEnd || $rangeStart > $rangeEnd) { + throw new \OutOfRangeException('Invalid range start requested'); + } + + if ($rangeEnd < $this->rangeStart || $rangeEnd > $this->rangeEnd || $rangeEnd < $rangeStart) { + throw new \OutOfRangeException('Invalid range end requested'); + } + + // Steps larger than the range need to wrap around and be handled + // slightly differently than smaller steps + + // UPDATE - This is actually false. The C implementation will allow a + // larger step as valid syntax, it never wraps around. It will stop + // once it hits the end. Unfortunately this means in future versions + // we will not wrap around. However, because the logic exists today + // per the above documentation, fixing the bug from #89 + if ($step > $this->rangeEnd) { + $thisRange = [$this->fullRange[$step % \count($this->fullRange)]]; + } else { + if ($step > ($rangeEnd - $rangeStart)) { + $thisRange[$rangeStart] = (int) $rangeStart; + } else { + $thisRange = range($rangeStart, $rangeEnd, (int) $step); + } + } + + return \in_array($dateValue, $thisRange, true); + } + + /** + * Returns a range of values for the given cron expression. + * + * @param string $expression The expression to evaluate + * @param int $max Maximum offset for range + * + * @return array + */ + public function getRangeForExpression(string $expression, int $max): array + { + $values = []; + $expression = $this->convertLiterals($expression); + + if (false !== strpos($expression, ',')) { + $ranges = explode(',', $expression); + $values = []; + foreach ($ranges as $range) { + $expanded = $this->getRangeForExpression($range, $this->rangeEnd); + $values = array_merge($values, $expanded); + } + + return $values; + } + + if ($this->isRange($expression) || $this->isIncrementsOfRanges($expression)) { + if (!$this->isIncrementsOfRanges($expression)) { + [$offset, $to] = explode('-', $expression); + $offset = $this->convertLiterals($offset); + $to = $this->convertLiterals($to); + $stepSize = 1; + } else { + $range = array_map('trim', explode('/', $expression, 2)); + $stepSize = $range[1] ?? 0; + $range = $range[0]; + $range = explode('-', $range, 2); + $offset = $range[0]; + $to = $range[1] ?? $max; + } + $offset = '*' === $offset ? $this->rangeStart : $offset; + if ($stepSize >= $this->rangeEnd) { + $values = [$this->fullRange[$stepSize % \count($this->fullRange)]]; + } else { + for ($i = $offset; $i <= $to; $i += $stepSize) { + $values[] = (int) $i; + } + } + sort($values); + } else { + $values = [$expression]; + } + + return $values; + } + + /** + * Convert literal. + * + * @param string $value + * + * @return string + */ + protected function convertLiterals(string $value): string + { + if (\count($this->literals)) { + $key = array_search(strtoupper($value), $this->literals, true); + if (false !== $key) { + return (string) $key; + } + } + + return $value; + } + + /** + * Checks to see if a value is valid for the field. + * + * @param string $value + * + * @return bool + */ + public function validate(string $value): bool + { + $value = $this->convertLiterals($value); + + // All fields allow * as a valid value + if ('*' === $value) { + return true; + } + + // Validate each chunk of a list individually + if (false !== strpos($value, ',')) { + foreach (explode(',', $value) as $listItem) { + if (!$this->validate($listItem)) { + return false; + } + } + + return true; + } + + if (false !== strpos($value, '/')) { + [$range, $step] = explode('/', $value); + + // Don't allow numeric ranges + if (is_numeric($range)) { + return false; + } + + return $this->validate($range) && filter_var($step, FILTER_VALIDATE_INT); + } + + if (false !== strpos($value, '-')) { + if (substr_count($value, '-') > 1) { + return false; + } + + $chunks = explode('-', $value); + $chunks[0] = $this->convertLiterals($chunks[0]); + $chunks[1] = $this->convertLiterals($chunks[1]); + + if ('*' === $chunks[0] || '*' === $chunks[1]) { + return false; + } + + return $this->validate($chunks[0]) && $this->validate($chunks[1]); + } + + if (!is_numeric($value)) { + return false; + } + + if (false !== strpos($value, '.')) { + return false; + } + + // We should have a numeric by now, so coerce this into an integer + $value = (int) $value; + + return \in_array($value, $this->fullRange, true); + } + + protected function timezoneSafeModify(DateTimeInterface $dt, string $modification): DateTimeInterface + { + $timezone = $dt->getTimezone(); + $dt = $dt->setTimezone(new \DateTimeZone("UTC")); + $dt = $dt->modify($modification); + $dt = $dt->setTimezone($timezone); + return $dt; + } + + protected function setTimeHour(DateTimeInterface $date, bool $invert, int $originalTimestamp): DateTimeInterface + { + $date = $date->setTime((int)$date->format('H'), ($invert ? 59 : 0)); + + // setTime caused the offset to change, moving time in the wrong direction + $actualTimestamp = $date->format('U'); + if ((! $invert) && ($actualTimestamp <= $originalTimestamp)) { + $date = $this->timezoneSafeModify($date, "+1 hour"); + } elseif ($invert && ($actualTimestamp >= $originalTimestamp)) { + $date = $this->timezoneSafeModify($date, "-1 hour"); + } + + return $date; + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/CronExpression.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/CronExpression.php new file mode 100644 index 0000000..216ce43 --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/CronExpression.php @@ -0,0 +1,578 @@ + '0 0 1 1 *', + '@annually' => '0 0 1 1 *', + '@monthly' => '0 0 1 * *', + '@weekly' => '0 0 * * 0', + '@daily' => '0 0 * * *', + '@midnight' => '0 0 * * *', + '@hourly' => '0 * * * *', + ]; + + /** + * @var array CRON expression parts + */ + protected $cronParts; + + /** + * @var FieldFactoryInterface CRON field factory + */ + protected $fieldFactory; + + /** + * @var int Max iteration count when searching for next run date + */ + protected $maxIterationCount = 1000; + + /** + * @var array Order in which to test of cron parts + */ + protected static $order = [ + self::YEAR, + self::MONTH, + self::DAY, + self::WEEKDAY, + self::HOUR, + self::MINUTE, + ]; + + /** + * @var array + */ + private static $registeredAliases = self::MAPPINGS; + + /** + * Registered a user defined CRON Expression Alias. + * + * @throws LogicException If the expression or the alias name are invalid + * or if the alias is already registered. + */ + public static function registerAlias(string $alias, string $expression): void + { + try { + new self($expression); + } catch (InvalidArgumentException $exception) { + throw new LogicException("The expression `$expression` is invalid", 0, $exception); + } + + $shortcut = strtolower($alias); + if (1 !== preg_match('/^@\w+$/', $shortcut)) { + throw new LogicException("The alias `$alias` is invalid. It must start with an `@` character and contain alphanumeric (letters, numbers, regardless of case) plus underscore (_)."); + } + + if (isset(self::$registeredAliases[$shortcut])) { + throw new LogicException("The alias `$alias` is already registered."); + } + + self::$registeredAliases[$shortcut] = $expression; + } + + /** + * Unregistered a user defined CRON Expression Alias. + * + * @throws LogicException If the user tries to unregister a built-in alias + */ + public static function unregisterAlias(string $alias): bool + { + $shortcut = strtolower($alias); + if (isset(self::MAPPINGS[$shortcut])) { + throw new LogicException("The alias `$alias` is a built-in alias; it can not be unregistered."); + } + + if (!isset(self::$registeredAliases[$shortcut])) { + return false; + } + + unset(self::$registeredAliases[$shortcut]); + + return true; + } + + /** + * Tells whether a CRON Expression alias is registered. + */ + public static function supportsAlias(string $alias): bool + { + return isset(self::$registeredAliases[strtolower($alias)]); + } + + /** + * Returns all registered aliases as an associated array where the aliases are the key + * and their associated expressions are the values. + * + * @return array + */ + public static function getAliases(): array + { + return self::$registeredAliases; + } + + /** + * @deprecated since version 3.0.2, use __construct instead. + */ + public static function factory(string $expression, FieldFactoryInterface $fieldFactory = null): CronExpression + { + /** @phpstan-ignore-next-line */ + return new static($expression, $fieldFactory); + } + + /** + * Validate a CronExpression. + * + * @param string $expression the CRON expression to validate + * + * @return bool True if a valid CRON expression was passed. False if not. + */ + public static function isValidExpression(string $expression): bool + { + try { + new CronExpression($expression); + } catch (InvalidArgumentException $e) { + return false; + } + + return true; + } + + /** + * Parse a CRON expression. + * + * @param string $expression CRON expression (e.g. '8 * * * *') + * @param null|FieldFactoryInterface $fieldFactory Factory to create cron fields + * @throws InvalidArgumentException + */ + public function __construct(string $expression, FieldFactoryInterface $fieldFactory = null) + { + $shortcut = strtolower($expression); + $expression = self::$registeredAliases[$shortcut] ?? $expression; + + $this->fieldFactory = $fieldFactory ?: new FieldFactory(); + $this->setExpression($expression); + } + + /** + * Set or change the CRON expression. + * + * @param string $value CRON expression (e.g. 8 * * * *) + * + * @throws \InvalidArgumentException if not a valid CRON expression + * + * @return CronExpression + */ + public function setExpression(string $value): CronExpression + { + $split = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY); + Assert::isArray($split); + + $notEnoughParts = \count($split) < 5; + + $questionMarkInInvalidPart = array_key_exists(0, $split) && $split[0] === '?' + || array_key_exists(1, $split) && $split[1] === '?' + || array_key_exists(3, $split) && $split[3] === '?'; + + $tooManyQuestionMarks = array_key_exists(2, $split) && $split[2] === '?' + && array_key_exists(4, $split) && $split[4] === '?'; + + if ($notEnoughParts || $questionMarkInInvalidPart || $tooManyQuestionMarks) { + throw new InvalidArgumentException( + $value . ' is not a valid CRON expression' + ); + } + + $this->cronParts = $split; + foreach ($this->cronParts as $position => $part) { + $this->setPart($position, $part); + } + + return $this; + } + + /** + * Set part of the CRON expression. + * + * @param int $position The position of the CRON expression to set + * @param string $value The value to set + * + * @throws \InvalidArgumentException if the value is not valid for the part + * + * @return CronExpression + */ + public function setPart(int $position, string $value): CronExpression + { + if (!$this->fieldFactory->getField($position)->validate($value)) { + throw new InvalidArgumentException( + 'Invalid CRON field value ' . $value . ' at position ' . $position + ); + } + + $this->cronParts[$position] = $value; + + return $this; + } + + /** + * Set max iteration count for searching next run dates. + * + * @param int $maxIterationCount Max iteration count when searching for next run date + * + * @return CronExpression + */ + public function setMaxIterationCount(int $maxIterationCount): CronExpression + { + $this->maxIterationCount = $maxIterationCount; + + return $this; + } + + /** + * Get a next run date relative to the current date or a specific date + * + * @param string|\DateTimeInterface $currentTime Relative calculation date + * @param int $nth Number of matches to skip before returning a + * matching next run date. 0, the default, will return the + * current date and time if the next run date falls on the + * current date and time. Setting this value to 1 will + * skip the first match and go to the second match. + * Setting this value to 2 will skip the first 2 + * matches and so on. + * @param bool $allowCurrentDate Set to TRUE to return the current date if + * it matches the cron expression. + * @param null|string $timeZone TimeZone to use instead of the system default + * + * @throws \RuntimeException on too many iterations + * @throws \Exception + * + * @return \DateTime + */ + public function getNextRunDate($currentTime = 'now', int $nth = 0, bool $allowCurrentDate = false, $timeZone = null): DateTime + { + return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate, $timeZone); + } + + /** + * Get a previous run date relative to the current date or a specific date. + * + * @param string|\DateTimeInterface $currentTime Relative calculation date + * @param int $nth Number of matches to skip before returning + * @param bool $allowCurrentDate Set to TRUE to return the + * current date if it matches the cron expression + * @param null|string $timeZone TimeZone to use instead of the system default + * + * @throws \RuntimeException on too many iterations + * @throws \Exception + * + * @return \DateTime + * + * @see \Cron\CronExpression::getNextRunDate + */ + public function getPreviousRunDate($currentTime = 'now', int $nth = 0, bool $allowCurrentDate = false, $timeZone = null): DateTime + { + return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate, $timeZone); + } + + /** + * Get multiple run dates starting at the current date or a specific date. + * + * @param int $total Set the total number of dates to calculate + * @param string|\DateTimeInterface|null $currentTime Relative calculation date + * @param bool $invert Set to TRUE to retrieve previous dates + * @param bool $allowCurrentDate Set to TRUE to return the + * current date if it matches the cron expression + * @param null|string $timeZone TimeZone to use instead of the system default + * + * @return \DateTime[] Returns an array of run dates + */ + public function getMultipleRunDates(int $total, $currentTime = 'now', bool $invert = false, bool $allowCurrentDate = false, $timeZone = null): array + { + $timeZone = $this->determineTimeZone($currentTime, $timeZone); + + if ('now' === $currentTime) { + $currentTime = new DateTime(); + } elseif ($currentTime instanceof DateTime) { + $currentTime = clone $currentTime; + } elseif ($currentTime instanceof DateTimeImmutable) { + $currentTime = DateTime::createFromFormat('U', $currentTime->format('U')); + } elseif (\is_string($currentTime)) { + $currentTime = new DateTime($currentTime); + } + + Assert::isInstanceOf($currentTime, DateTime::class); + $currentTime->setTimezone(new DateTimeZone($timeZone)); + + $matches = []; + for ($i = 0; $i < $total; ++$i) { + try { + $result = $this->getRunDate($currentTime, 0, $invert, $allowCurrentDate, $timeZone); + } catch (RuntimeException $e) { + break; + } + + $allowCurrentDate = false; + $currentTime = clone $result; + $matches[] = $result; + } + + return $matches; + } + + /** + * Get all or part of the CRON expression. + * + * @param int|string|null $part specify the part to retrieve or NULL to get the full + * cron schedule string + * + * @return null|string Returns the CRON expression, a part of the + * CRON expression, or NULL if the part was specified but not found + */ + public function getExpression($part = null): ?string + { + if (null === $part) { + return implode(' ', $this->cronParts); + } + + if (array_key_exists($part, $this->cronParts)) { + return $this->cronParts[$part]; + } + + return null; + } + + /** + * Gets the parts of the cron expression as an array. + * + * @return string[] + * The array of parts that make up this expression. + */ + public function getParts() + { + return $this->cronParts; + } + + /** + * Helper method to output the full expression. + * + * @return string Full CRON expression + */ + public function __toString(): string + { + return (string) $this->getExpression(); + } + + /** + * Determine if the cron is due to run based on the current date or a + * specific date. This method assumes that the current number of + * seconds are irrelevant, and should be called once per minute. + * + * @param string|\DateTimeInterface $currentTime Relative calculation date + * @param null|string $timeZone TimeZone to use instead of the system default + * + * @return bool Returns TRUE if the cron is due to run or FALSE if not + */ + public function isDue($currentTime = 'now', $timeZone = null): bool + { + $timeZone = $this->determineTimeZone($currentTime, $timeZone); + + if ('now' === $currentTime) { + $currentTime = new DateTime(); + } elseif ($currentTime instanceof DateTime) { + $currentTime = clone $currentTime; + } elseif ($currentTime instanceof DateTimeImmutable) { + $currentTime = DateTime::createFromFormat('U', $currentTime->format('U')); + } elseif (\is_string($currentTime)) { + $currentTime = new DateTime($currentTime); + } + + Assert::isInstanceOf($currentTime, DateTime::class); + $currentTime->setTimezone(new DateTimeZone($timeZone)); + + // drop the seconds to 0 + $currentTime->setTime((int) $currentTime->format('H'), (int) $currentTime->format('i'), 0); + + try { + return $this->getNextRunDate($currentTime, 0, true)->getTimestamp() === $currentTime->getTimestamp(); + } catch (Exception $e) { + return false; + } + } + + /** + * Get the next or previous run date of the expression relative to a date. + * + * @param string|\DateTimeInterface|null $currentTime Relative calculation date + * @param int $nth Number of matches to skip before returning + * @param bool $invert Set to TRUE to go backwards in time + * @param bool $allowCurrentDate Set to TRUE to return the + * current date if it matches the cron expression + * @param string|null $timeZone TimeZone to use instead of the system default + * + * @throws \RuntimeException on too many iterations + * @throws Exception + * + * @return \DateTime + */ + protected function getRunDate($currentTime = null, int $nth = 0, bool $invert = false, bool $allowCurrentDate = false, $timeZone = null): DateTime + { + $timeZone = $this->determineTimeZone($currentTime, $timeZone); + + if ($currentTime instanceof DateTime) { + $currentDate = clone $currentTime; + } elseif ($currentTime instanceof DateTimeImmutable) { + $currentDate = DateTime::createFromFormat('U', $currentTime->format('U')); + } elseif (\is_string($currentTime)) { + $currentDate = new DateTime($currentTime); + } else { + $currentDate = new DateTime('now'); + } + + Assert::isInstanceOf($currentDate, DateTime::class); + $currentDate->setTimezone(new DateTimeZone($timeZone)); + // Workaround for setTime causing an offset change: https://bugs.php.net/bug.php?id=81074 + $currentDate = DateTime::createFromFormat("!Y-m-d H:iO", $currentDate->format("Y-m-d H:iP"), $currentDate->getTimezone()); + if ($currentDate === false) { + throw new \RuntimeException('Unable to create date from format'); + } + $currentDate->setTimezone(new DateTimeZone($timeZone)); + + $nextRun = clone $currentDate; + + // We don't have to satisfy * or null fields + $parts = []; + $fields = []; + foreach (self::$order as $position) { + $part = $this->getExpression($position); + if (null === $part || '*' === $part) { + continue; + } + $parts[$position] = $part; + $fields[$position] = $this->fieldFactory->getField($position); + } + + if (isset($parts[self::DAY]) && isset($parts[self::WEEKDAY])) { + $domExpression = sprintf('%s %s %s %s *', $this->getExpression(0), $this->getExpression(1), $this->getExpression(2), $this->getExpression(3)); + $dowExpression = sprintf('%s %s * %s %s', $this->getExpression(0), $this->getExpression(1), $this->getExpression(3), $this->getExpression(4)); + + $domExpression = new self($domExpression); + $dowExpression = new self($dowExpression); + + $domRunDates = $domExpression->getMultipleRunDates($nth + 1, $currentTime, $invert, $allowCurrentDate, $timeZone); + $dowRunDates = $dowExpression->getMultipleRunDates($nth + 1, $currentTime, $invert, $allowCurrentDate, $timeZone); + + if ($parts[self::DAY] === '?' || $parts[self::DAY] === '*') { + $domRunDates = []; + } + + if ($parts[self::WEEKDAY] === '?' || $parts[self::WEEKDAY] === '*') { + $dowRunDates = []; + } + + $combined = array_merge($domRunDates, $dowRunDates); + usort($combined, function ($a, $b) { + return $a->format('Y-m-d H:i:s') <=> $b->format('Y-m-d H:i:s'); + }); + if ($invert) { + $combined = array_reverse($combined); + } + + return $combined[$nth]; + } + + // Set a hard limit to bail on an impossible date + for ($i = 0; $i < $this->maxIterationCount; ++$i) { + foreach ($parts as $position => $part) { + $satisfied = false; + // Get the field object used to validate this part + $field = $fields[$position]; + // Check if this is singular or a list + if (false === strpos($part, ',')) { + $satisfied = $field->isSatisfiedBy($nextRun, $part, $invert); + } else { + foreach (array_map('trim', explode(',', $part)) as $listPart) { + if ($field->isSatisfiedBy($nextRun, $listPart, $invert)) { + $satisfied = true; + + break; + } + } + } + + // If the field is not satisfied, then start over + if (!$satisfied) { + $field->increment($nextRun, $invert, $part); + + continue 2; + } + } + + // Skip this match if needed + if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) { + $this->fieldFactory->getField(self::MINUTE)->increment($nextRun, $invert, $parts[self::MINUTE] ?? null); + continue; + } + + return $nextRun; + } + + // @codeCoverageIgnoreStart + throw new RuntimeException('Impossible CRON expression'); + // @codeCoverageIgnoreEnd + } + + /** + * Workout what timeZone should be used. + * + * @param string|\DateTimeInterface|null $currentTime Relative calculation date + * @param string|null $timeZone TimeZone to use instead of the system default + * + * @return string + */ + protected function determineTimeZone($currentTime, ?string $timeZone): string + { + if (null !== $timeZone) { + return $timeZone; + } + + if ($currentTime instanceof DateTimeInterface) { + return $currentTime->getTimezone()->getName(); + } + + return date_default_timezone_get(); + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/DayOfMonthField.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/DayOfMonthField.php new file mode 100644 index 0000000..39ff597 --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/DayOfMonthField.php @@ -0,0 +1,164 @@ + + */ +class DayOfMonthField extends AbstractField +{ + /** + * {@inheritdoc} + */ + protected $rangeStart = 1; + + /** + * {@inheritdoc} + */ + protected $rangeEnd = 31; + + /** + * Get the nearest day of the week for a given day in a month. + * + * @param int $currentYear Current year + * @param int $currentMonth Current month + * @param int $targetDay Target day of the month + * + * @return \DateTime|null Returns the nearest date + */ + private static function getNearestWeekday(int $currentYear, int $currentMonth, int $targetDay): ?DateTime + { + $tday = str_pad((string) $targetDay, 2, '0', STR_PAD_LEFT); + $target = DateTime::createFromFormat('Y-m-d', "{$currentYear}-{$currentMonth}-{$tday}"); + + if ($target === false) { + return null; + } + + $currentWeekday = (int) $target->format('N'); + + if ($currentWeekday < 6) { + return $target; + } + + $lastDayOfMonth = $target->format('t'); + foreach ([-1, 1, -2, 2] as $i) { + $adjusted = $targetDay + $i; + if ($adjusted > 0 && $adjusted <= $lastDayOfMonth) { + $target->setDate($currentYear, $currentMonth, $adjusted); + + if ((int) $target->format('N') < 6 && (int) $target->format('m') === $currentMonth) { + return $target; + } + } + } + + return null; + } + + /** + * {@inheritdoc} + */ + public function isSatisfiedBy(DateTimeInterface $date, $value, bool $invert): bool + { + // ? states that the field value is to be skipped + if ('?' === $value) { + return true; + } + + $fieldValue = $date->format('d'); + + // Check to see if this is the last day of the month + if ('L' === $value) { + return $fieldValue === $date->format('t'); + } + + // Check to see if this is the nearest weekday to a particular value + if ($wPosition = strpos($value, 'W')) { + // Parse the target day + $targetDay = (int) substr($value, 0, $wPosition); + // Find out if the current day is the nearest day of the week + $nearest = self::getNearestWeekday( + (int) $date->format('Y'), + (int) $date->format('m'), + $targetDay + ); + if ($nearest) { + return $date->format('j') === $nearest->format('j'); + } + + throw new \RuntimeException('Unable to return nearest weekday'); + } + + return $this->isSatisfied((int) $date->format('d'), $value); + } + + /** + * @inheritDoc + * + * @param \DateTime|\DateTimeImmutable $date + */ + public function increment(DateTimeInterface &$date, $invert = false, $parts = null): FieldInterface + { + if (! $invert) { + $date = $date->add(new \DateInterval('P1D')); + $date = $date->setTime(0, 0); + } else { + $date = $date->sub(new \DateInterval('P1D')); + $date = $date->setTime(23, 59); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function validate(string $value): bool + { + $basicChecks = parent::validate($value); + + // Validate that a list don't have W or L + if (false !== strpos($value, ',') && (false !== strpos($value, 'W') || false !== strpos($value, 'L'))) { + return false; + } + + if (!$basicChecks) { + if ('?' === $value) { + return true; + } + + if ('L' === $value) { + return true; + } + + if (preg_match('/^(.*)W$/', $value, $matches)) { + return $this->validate($matches[1]); + } + + return false; + } + + return $basicChecks; + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/DayOfWeekField.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/DayOfWeekField.php new file mode 100644 index 0000000..b9bbf48 --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/DayOfWeekField.php @@ -0,0 +1,194 @@ + 'MON', 2 => 'TUE', 3 => 'WED', 4 => 'THU', 5 => 'FRI', 6 => 'SAT', 7 => 'SUN']; + + /** + * Constructor + */ + public function __construct() + { + $this->nthRange = range(1, 5); + parent::__construct(); + } + + /** + * @inheritDoc + */ + public function isSatisfiedBy(DateTimeInterface $date, $value, bool $invert): bool + { + if ('?' === $value) { + return true; + } + + // Convert text day of the week values to integers + $value = $this->convertLiterals($value); + + $currentYear = (int) $date->format('Y'); + $currentMonth = (int) $date->format('m'); + $lastDayOfMonth = (int) $date->format('t'); + + // Find out if this is the last specific weekday of the month + if ($lPosition = strpos($value, 'L')) { + $weekday = $this->convertLiterals(substr($value, 0, $lPosition)); + $weekday %= 7; + + $daysInMonth = (int) $date->format('t'); + $remainingDaysInMonth = $daysInMonth - (int) $date->format('d'); + return (($weekday === (int) $date->format('w')) && ($remainingDaysInMonth < 7)); + } + + // Handle # hash tokens + if (strpos($value, '#')) { + [$weekday, $nth] = explode('#', $value); + + if (!is_numeric($nth)) { + throw new InvalidArgumentException("Hashed weekdays must be numeric, {$nth} given"); + } else { + $nth = (int) $nth; + } + + // 0 and 7 are both Sunday, however 7 matches date('N') format ISO-8601 + if ('0' === $weekday) { + $weekday = 7; + } + + $weekday = (int) $this->convertLiterals((string) $weekday); + + // Validate the hash fields + if ($weekday < 0 || $weekday > 7) { + throw new InvalidArgumentException("Weekday must be a value between 0 and 7. {$weekday} given"); + } + + if (!\in_array($nth, $this->nthRange, true)) { + throw new InvalidArgumentException("There are never more than 5 or less than 1 of a given weekday in a month, {$nth} given"); + } + + // The current weekday must match the targeted weekday to proceed + if ((int) $date->format('N') !== $weekday) { + return false; + } + + $tdate = clone $date; + $tdate = $tdate->setDate($currentYear, $currentMonth, 1); + $dayCount = 0; + $currentDay = 1; + while ($currentDay < $lastDayOfMonth + 1) { + if ((int) $tdate->format('N') === $weekday) { + if (++$dayCount >= $nth) { + break; + } + } + $tdate = $tdate->setDate($currentYear, $currentMonth, ++$currentDay); + } + + return (int) $date->format('j') === $currentDay; + } + + // Handle day of the week values + if (false !== strpos($value, '-')) { + $parts = explode('-', $value); + if ('7' === $parts[0]) { + $parts[0] = 0; + } elseif ('0' === $parts[1]) { + $parts[1] = 7; + } + $value = implode('-', $parts); + } + + // Test to see which Sunday to use -- 0 == 7 == Sunday + $format = \in_array(7, array_map(function ($value) { + return (int) $value; + }, str_split($value)), true) ? 'N' : 'w'; + $fieldValue = (int) $date->format($format); + + return $this->isSatisfied($fieldValue, $value); + } + + /** + * @inheritDoc + */ + public function increment(DateTimeInterface &$date, $invert = false, $parts = null): FieldInterface + { + if (! $invert) { + $date = $date->add(new \DateInterval('P1D')); + $date = $date->setTime(0, 0); + } else { + $date = $date->sub(new \DateInterval('P1D')); + $date = $date->setTime(23, 59); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function validate(string $value): bool + { + $basicChecks = parent::validate($value); + + if (!$basicChecks) { + if ('?' === $value) { + return true; + } + + // Handle the # value + if (false !== strpos($value, '#')) { + $chunks = explode('#', $value); + $chunks[0] = $this->convertLiterals($chunks[0]); + + if (parent::validate($chunks[0]) && is_numeric($chunks[1]) && \in_array((int) $chunks[1], $this->nthRange, true)) { + return true; + } + } + + if (preg_match('/^(.*)L$/', $value, $matches)) { + return $this->validate($matches[1]); + } + + return false; + } + + return $basicChecks; + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/FieldFactory.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/FieldFactory.php new file mode 100644 index 0000000..839b275 --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/FieldFactory.php @@ -0,0 +1,52 @@ +fields[$position] ?? $this->fields[$position] = $this->instantiateField($position); + } + + private function instantiateField(int $position): FieldInterface + { + switch ($position) { + case CronExpression::MINUTE: + return new MinutesField(); + case CronExpression::HOUR: + return new HoursField(); + case CronExpression::DAY: + return new DayOfMonthField(); + case CronExpression::MONTH: + return new MonthField(); + case CronExpression::WEEKDAY: + return new DayOfWeekField(); + } + + throw new InvalidArgumentException( + ($position + 1) . ' is not a valid position' + ); + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/FieldFactoryInterface.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/FieldFactoryInterface.php new file mode 100644 index 0000000..8bd3c65 --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/FieldFactoryInterface.php @@ -0,0 +1,8 @@ +format('H'); + $retval = $this->isSatisfied($checkValue, $value); + if ($retval) { + return $retval; + } + + // Are we on the edge of a transition + $lastTransition = $this->getPastTransition($date); + if (($lastTransition !== null) && ($lastTransition["ts"] > ((int) $date->format('U') - 3600))) { + $dtLastOffset = clone $date; + $this->timezoneSafeModify($dtLastOffset, "-1 hour"); + $lastOffset = $dtLastOffset->getOffset(); + + $dtNextOffset = clone $date; + $this->timezoneSafeModify($dtNextOffset, "+1 hour"); + $nextOffset = $dtNextOffset->getOffset(); + + $offsetChange = $nextOffset - $lastOffset; + if ($offsetChange >= 3600) { + $checkValue -= 1; + return $this->isSatisfied($checkValue, $value); + } + if ((! $invert) && ($offsetChange <= -3600)) { + $checkValue += 1; + return $this->isSatisfied($checkValue, $value); + } + } + + return $retval; + } + + public function getPastTransition(DateTimeInterface $date): ?array + { + $currentTimestamp = (int) $date->format('U'); + if ( + ($this->transitions === null) + || ($this->transitionsStart < ($currentTimestamp + 86400)) + || ($this->transitionsEnd > ($currentTimestamp - 86400)) + ) { + // We start a day before current time so we can differentiate between the first transition entry + // and a change that happens now + $dtLimitStart = clone $date; + $dtLimitStart = $dtLimitStart->modify("-12 months"); + $dtLimitEnd = clone $date; + $dtLimitEnd = $dtLimitEnd->modify('+12 months'); + + $this->transitions = $date->getTimezone()->getTransitions( + $dtLimitStart->getTimestamp(), + $dtLimitEnd->getTimestamp() + ); + if (empty($this->transitions)) { + return null; + } + $this->transitionsStart = $dtLimitStart->getTimestamp(); + $this->transitionsEnd = $dtLimitEnd->getTimestamp(); + } + + $nextTransition = null; + foreach ($this->transitions as $transition) { + if ($transition["ts"] > $currentTimestamp) { + continue; + } + + if (($nextTransition !== null) && ($transition["ts"] < $nextTransition["ts"])) { + continue; + } + + $nextTransition = $transition; + } + + return ($nextTransition ?? null); + } + + /** + * {@inheritdoc} + * + * @param string|null $parts + */ + public function increment(DateTimeInterface &$date, $invert = false, $parts = null): FieldInterface + { + $originalTimestamp = (int) $date->format('U'); + + // Change timezone to UTC temporarily. This will + // allow us to go back or forwards and hour even + // if DST will be changed between the hours. + if (null === $parts || '*' === $parts) { + if ($invert) { + $date = $date->sub(new \DateInterval('PT1H')); + } else { + $date = $date->add(new \DateInterval('PT1H')); + } + + $date = $this->setTimeHour($date, $invert, $originalTimestamp); + return $this; + } + + $parts = false !== strpos($parts, ',') ? explode(',', $parts) : [$parts]; + $hours = []; + foreach ($parts as $part) { + $hours = array_merge($hours, $this->getRangeForExpression($part, 23)); + } + + $current_hour = (int) $date->format('H'); + $position = $invert ? \count($hours) - 1 : 0; + $countHours = \count($hours); + if ($countHours > 1) { + for ($i = 0; $i < $countHours - 1; ++$i) { + if ((!$invert && $current_hour >= $hours[$i] && $current_hour < $hours[$i + 1]) || + ($invert && $current_hour > $hours[$i] && $current_hour <= $hours[$i + 1])) { + $position = $invert ? $i : $i + 1; + + break; + } + } + } + + $target = (int) $hours[$position]; + $originalHour = (int)$date->format('H'); + + $originalDay = (int)$date->format('d'); + $previousOffset = $date->getOffset(); + + if (! $invert) { + if ($originalHour >= $target) { + $distance = 24 - $originalHour; + $date = $this->timezoneSafeModify($date, "+{$distance} hours"); + + $actualDay = (int)$date->format('d'); + $actualHour = (int)$date->format('H'); + if (($actualDay !== ($originalDay + 1)) && ($actualHour !== 0)) { + $offsetChange = ($previousOffset - $date->getOffset()); + $date = $this->timezoneSafeModify($date, "+{$offsetChange} seconds"); + } + + $originalHour = (int)$date->format('H'); + } + + $distance = $target - $originalHour; + $date = $this->timezoneSafeModify($date, "+{$distance} hours"); + } else { + if ($originalHour <= $target) { + $distance = ($originalHour + 1); + $date = $this->timezoneSafeModify($date, "-" . $distance . " hours"); + + $actualDay = (int)$date->format('d'); + $actualHour = (int)$date->format('H'); + if (($actualDay !== ($originalDay - 1)) && ($actualHour !== 23)) { + $offsetChange = ($previousOffset - $date->getOffset()); + $date = $this->timezoneSafeModify($date, "+{$offsetChange} seconds"); + } + + $originalHour = (int)$date->format('H'); + } + + $distance = $originalHour - $target; + $date = $this->timezoneSafeModify($date, "-{$distance} hours"); + } + + $date = $this->setTimeHour($date, $invert, $originalTimestamp); + + $actualHour = (int)$date->format('H'); + if ($invert && ($actualHour === ($target - 1) || (($actualHour === 23) && ($target === 0)))) { + $date = $this->timezoneSafeModify($date, "+1 hour"); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/MinutesField.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/MinutesField.php new file mode 100644 index 0000000..f077e6e --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/MinutesField.php @@ -0,0 +1,97 @@ +isSatisfied((int)$date->format('i'), $value); + } + + /** + * {@inheritdoc} + * {@inheritDoc} + * + * @param string|null $parts + */ + public function increment(DateTimeInterface &$date, $invert = false, $parts = null): FieldInterface + { + if (is_null($parts)) { + $date = $this->timezoneSafeModify($date, ($invert ? "-" : "+") ."1 minute"); + return $this; + } + + $current_minute = (int) $date->format('i'); + + $parts = false !== strpos($parts, ',') ? explode(',', $parts) : [$parts]; + sort($parts); + $minutes = []; + foreach ($parts as $part) { + $minutes = array_merge($minutes, $this->getRangeForExpression($part, 59)); + } + + $position = $invert ? \count($minutes) - 1 : 0; + if (\count($minutes) > 1) { + for ($i = 0; $i < \count($minutes) - 1; ++$i) { + if ((!$invert && $current_minute >= $minutes[$i] && $current_minute < $minutes[$i + 1]) || + ($invert && $current_minute > $minutes[$i] && $current_minute <= $minutes[$i + 1])) { + $position = $invert ? $i : $i + 1; + + break; + } + } + } + + $target = (int) $minutes[$position]; + $originalMinute = (int) $date->format("i"); + + if (! $invert) { + if ($originalMinute >= $target) { + $distance = 60 - $originalMinute; + $date = $this->timezoneSafeModify($date, "+{$distance} minutes"); + + $originalMinute = (int) $date->format("i"); + } + + $distance = $target - $originalMinute; + $date = $this->timezoneSafeModify($date, "+{$distance} minutes"); + } else { + if ($originalMinute <= $target) { + $distance = ($originalMinute + 1); + $date = $this->timezoneSafeModify($date, "-{$distance} minutes"); + + $originalMinute = (int) $date->format("i"); + } + + $distance = $originalMinute - $target; + $date = $this->timezoneSafeModify($date, "-{$distance} minutes"); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/MonthField.php b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/MonthField.php new file mode 100644 index 0000000..5a15fbb --- /dev/null +++ b/php/libraries/composer/vendor/dragonmantank/cron-expression/src/Cron/MonthField.php @@ -0,0 +1,61 @@ + 'JAN', 2 => 'FEB', 3 => 'MAR', 4 => 'APR', 5 => 'MAY', 6 => 'JUN', 7 => 'JUL', + 8 => 'AUG', 9 => 'SEP', 10 => 'OCT', 11 => 'NOV', 12 => 'DEC', ]; + + /** + * {@inheritdoc} + */ + public function isSatisfiedBy(DateTimeInterface $date, $value, bool $invert): bool + { + if ($value === '?') { + return true; + } + + $value = $this->convertLiterals($value); + + return $this->isSatisfied((int) $date->format('m'), $value); + } + + /** + * @inheritDoc + * + * @param \DateTime|\DateTimeImmutable $date + */ + public function increment(DateTimeInterface &$date, $invert = false, $parts = null): FieldInterface + { + if (! $invert) { + $date = $date->modify('first day of next month'); + $date = $date->setTime(0, 0); + } else { + $date = $date->modify('last day of previous month'); + $date = $date->setTime(23, 59); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/LICENSE b/php/libraries/composer/vendor/egulias/email-validator/LICENSE new file mode 100644 index 0000000..c34d2c1 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2016 Eduardo Gulias Davis + +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/php/libraries/composer/vendor/egulias/email-validator/composer.json b/php/libraries/composer/vendor/egulias/email-validator/composer.json new file mode 100644 index 0000000..a275696 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/composer.json @@ -0,0 +1,38 @@ +{ + "name": "egulias/email-validator", + "description": "A library for validating emails against several RFCs", + "homepage": "https://github.com/egulias/EmailValidator", + "keywords": ["email", "validation", "validator", "emailvalidation", "emailvalidator"], + "license": "MIT", + "authors": [ + {"name": "Eduardo Gulias Davis"} + ], + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev" + } + }, + "require": { + "php": ">=5.5", + "doctrine/lexer": "^1.0.1", + "symfony/polyfill-intl-idn": "^1.10" + }, + "require-dev": { + "dominicsayers/isemail": "^3.0.7", + "phpunit/phpunit": "^4.8.36|^7.5.15", + "satooshi/php-coveralls": "^1.0.1" + }, + "suggest": { + "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" + }, + "autoload": { + "psr-4": { + "Egulias\\EmailValidator\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Egulias\\EmailValidator\\Tests\\": "tests" + } + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/EmailLexer.php b/php/libraries/composer/vendor/egulias/email-validator/src/EmailLexer.php new file mode 100644 index 0000000..59dcd58 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/EmailLexer.php @@ -0,0 +1,283 @@ + self::S_OPENPARENTHESIS, + ')' => self::S_CLOSEPARENTHESIS, + '<' => self::S_LOWERTHAN, + '>' => self::S_GREATERTHAN, + '[' => self::S_OPENBRACKET, + ']' => self::S_CLOSEBRACKET, + ':' => self::S_COLON, + ';' => self::S_SEMICOLON, + '@' => self::S_AT, + '\\' => self::S_BACKSLASH, + '/' => self::S_SLASH, + ',' => self::S_COMMA, + '.' => self::S_DOT, + "'" => self::S_SQUOTE, + "`" => self::S_BACKTICK, + '"' => self::S_DQUOTE, + '-' => self::S_HYPHEN, + '::' => self::S_DOUBLECOLON, + ' ' => self::S_SP, + "\t" => self::S_HTAB, + "\r" => self::S_CR, + "\n" => self::S_LF, + "\r\n" => self::CRLF, + 'IPv6' => self::S_IPV6TAG, + '{' => self::S_OPENQBRACKET, + '}' => self::S_CLOSEQBRACKET, + '' => self::S_EMPTY, + '\0' => self::C_NUL, + ); + + /** + * @var bool + */ + protected $hasInvalidTokens = false; + + /** + * @var array + * + * @psalm-var array{value:string, type:null|int, position:int}|array + */ + protected $previous = []; + + /** + * The last matched/seen token. + * + * @var array + * + * @psalm-var array{value:string, type:null|int, position:int} + */ + public $token; + + /** + * The next token in the input. + * + * @var array|null + */ + public $lookahead; + + /** + * @psalm-var array{value:'', type:null, position:0} + */ + private static $nullToken = [ + 'value' => '', + 'type' => null, + 'position' => 0, + ]; + + public function __construct() + { + $this->previous = $this->token = self::$nullToken; + $this->lookahead = null; + } + + /** + * @return void + */ + public function reset() + { + $this->hasInvalidTokens = false; + parent::reset(); + $this->previous = $this->token = self::$nullToken; + } + + /** + * @return bool + */ + public function hasInvalidTokens() + { + return $this->hasInvalidTokens; + } + + /** + * @param int $type + * @throws \UnexpectedValueException + * @return boolean + * + * @psalm-suppress InvalidScalarArgument + */ + public function find($type) + { + $search = clone $this; + $search->skipUntil($type); + + if (!$search->lookahead) { + throw new \UnexpectedValueException($type . ' not found'); + } + return true; + } + + /** + * getPrevious + * + * @return array + */ + public function getPrevious() + { + return $this->previous; + } + + /** + * moveNext + * + * @return boolean + */ + public function moveNext() + { + $this->previous = $this->token; + $hasNext = parent::moveNext(); + $this->token = $this->token ?: self::$nullToken; + + return $hasNext; + } + + /** + * Lexical catchable patterns. + * + * @return string[] + */ + protected function getCatchablePatterns() + { + return array( + '[a-zA-Z_]+[46]?', //ASCII and domain literal + '[^\x00-\x7F]', //UTF-8 + '[0-9]+', + '\r\n', + '::', + '\s+?', + '.', + ); + } + + /** + * Lexical non-catchable patterns. + * + * @return string[] + */ + protected function getNonCatchablePatterns() + { + return array('[\xA0-\xff]+'); + } + + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @param string $value + * @throws \InvalidArgumentException + * @return integer + */ + protected function getType(&$value) + { + if ($this->isNullType($value)) { + return self::C_NUL; + } + + if ($this->isValid($value)) { + return $this->charValue[$value]; + } + + if ($this->isUTF8Invalid($value)) { + $this->hasInvalidTokens = true; + return self::INVALID; + } + + return self::GENERIC; + } + + /** + * @param string $value + * + * @return bool + */ + protected function isValid($value) + { + if (isset($this->charValue[$value])) { + return true; + } + + return false; + } + + /** + * @param string $value + * @return bool + */ + protected function isNullType($value) + { + if ($value === "\0") { + return true; + } + + return false; + } + + /** + * @param string $value + * @return bool + */ + protected function isUTF8Invalid($value) + { + if (preg_match('/\p{Cc}+/u', $value)) { + return true; + } + + return false; + } + + /** + * @return string + */ + protected function getModifiers() + { + return 'iu'; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/EmailParser.php b/php/libraries/composer/vendor/egulias/email-validator/src/EmailParser.php new file mode 100644 index 0000000..6b7bad6 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/EmailParser.php @@ -0,0 +1,137 @@ + + */ +class EmailParser +{ + const EMAIL_MAX_LENGTH = 254; + + /** + * @var array + */ + protected $warnings = []; + + /** + * @var string + */ + protected $domainPart = ''; + + /** + * @var string + */ + protected $localPart = ''; + /** + * @var EmailLexer + */ + protected $lexer; + + /** + * @var LocalPart + */ + protected $localPartParser; + + /** + * @var DomainPart + */ + protected $domainPartParser; + + public function __construct(EmailLexer $lexer) + { + $this->lexer = $lexer; + $this->localPartParser = new LocalPart($this->lexer); + $this->domainPartParser = new DomainPart($this->lexer); + } + + /** + * @param string $str + * @return array + */ + public function parse($str) + { + $this->lexer->setInput($str); + + if (!$this->hasAtToken()) { + throw new NoLocalPart(); + } + + + $this->localPartParser->parse($str); + $this->domainPartParser->parse($str); + + $this->setParts($str); + + if ($this->lexer->hasInvalidTokens()) { + throw new ExpectingATEXT(); + } + + return array('local' => $this->localPart, 'domain' => $this->domainPart); + } + + /** + * @return Warning\Warning[] + */ + public function getWarnings() + { + $localPartWarnings = $this->localPartParser->getWarnings(); + $domainPartWarnings = $this->domainPartParser->getWarnings(); + $this->warnings = array_merge($localPartWarnings, $domainPartWarnings); + + $this->addLongEmailWarning($this->localPart, $this->domainPart); + + return $this->warnings; + } + + /** + * @return string + */ + public function getParsedDomainPart() + { + return $this->domainPart; + } + + /** + * @param string $email + */ + protected function setParts($email) + { + $parts = explode('@', $email); + $this->domainPart = $this->domainPartParser->getDomainPart(); + $this->localPart = $parts[0]; + } + + /** + * @return bool + */ + protected function hasAtToken() + { + $this->lexer->moveNext(); + $this->lexer->moveNext(); + if ($this->lexer->token['type'] === EmailLexer::S_AT) { + return false; + } + + return true; + } + + /** + * @param string $localPart + * @param string $parsedDomainPart + */ + protected function addLongEmailWarning($localPart, $parsedDomainPart) + { + if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) { + $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); + } + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/EmailValidator.php b/php/libraries/composer/vendor/egulias/email-validator/src/EmailValidator.php new file mode 100644 index 0000000..a30f21d --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/EmailValidator.php @@ -0,0 +1,67 @@ +lexer = new EmailLexer(); + } + + /** + * @param string $email + * @param EmailValidation $emailValidation + * @return bool + */ + public function isValid($email, EmailValidation $emailValidation) + { + $isValid = $emailValidation->isValid($email, $this->lexer); + $this->warnings = $emailValidation->getWarnings(); + $this->error = $emailValidation->getError(); + + return $isValid; + } + + /** + * @return boolean + */ + public function hasWarnings() + { + return !empty($this->warnings); + } + + /** + * @return array + */ + public function getWarnings() + { + return $this->warnings; + } + + /** + * @return InvalidEmail|null + */ + public function getError() + { + return $this->error; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Exception/AtextAfterCFWS.php b/php/libraries/composer/vendor/egulias/email-validator/src/Exception/AtextAfterCFWS.php new file mode 100644 index 0000000..97f41a2 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Exception/AtextAfterCFWS.php @@ -0,0 +1,9 @@ +lexer->moveNext(); + + $this->performDomainStartChecks(); + + $domain = $this->doParseDomainPart(); + + $prev = $this->lexer->getPrevious(); + $length = strlen($domain); + + if ($prev['type'] === EmailLexer::S_DOT) { + throw new DotAtEnd(); + } + if ($prev['type'] === EmailLexer::S_HYPHEN) { + throw new DomainHyphened(); + } + if ($length > self::DOMAIN_MAX_LENGTH) { + $this->warnings[DomainTooLong::CODE] = new DomainTooLong(); + } + if ($prev['type'] === EmailLexer::S_CR) { + throw new CRLFAtTheEnd(); + } + $this->domainPart = $domain; + } + + private function performDomainStartChecks() + { + $this->checkInvalidTokensAfterAT(); + $this->checkEmptyDomain(); + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->warnings[DeprecatedComment::CODE] = new DeprecatedComment(); + $this->parseDomainComments(); + } + } + + private function checkEmptyDomain() + { + $thereIsNoDomain = $this->lexer->token['type'] === EmailLexer::S_EMPTY || + ($this->lexer->token['type'] === EmailLexer::S_SP && + !$this->lexer->isNextToken(EmailLexer::GENERIC)); + + if ($thereIsNoDomain) { + throw new NoDomainPart(); + } + } + + private function checkInvalidTokensAfterAT() + { + if ($this->lexer->token['type'] === EmailLexer::S_DOT) { + throw new DotAtStart(); + } + if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) { + throw new DomainHyphened(); + } + } + + /** + * @return string + */ + public function getDomainPart() + { + return $this->domainPart; + } + + /** + * @param string $addressLiteral + * @param int $maxGroups + */ + public function checkIPV6Tag($addressLiteral, $maxGroups = 8) + { + $prev = $this->lexer->getPrevious(); + if ($prev['type'] === EmailLexer::S_COLON) { + $this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd(); + } + + $IPv6 = substr($addressLiteral, 5); + //Daniel Marschall's new IPv6 testing strategy + $matchesIP = explode(':', $IPv6); + $groupCount = count($matchesIP); + $colons = strpos($IPv6, '::'); + + if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) { + $this->warnings[IPV6BadChar::CODE] = new IPV6BadChar(); + } + + if ($colons === false) { + // We need exactly the right number of groups + if ($groupCount !== $maxGroups) { + $this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount(); + } + return; + } + + if ($colons !== strrpos($IPv6, '::')) { + $this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon(); + return; + } + + if ($colons === 0 || $colons === (strlen($IPv6) - 2)) { + // RFC 4291 allows :: at the start or end of an address + //with 7 other groups in addition + ++$maxGroups; + } + + if ($groupCount > $maxGroups) { + $this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups(); + } elseif ($groupCount === $maxGroups) { + $this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated(); + } + } + + /** + * @return string + */ + protected function doParseDomainPart() + { + $domain = ''; + $label = ''; + $openedParenthesis = 0; + do { + $prev = $this->lexer->getPrevious(); + + $this->checkNotAllowedChars($this->lexer->token); + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->parseComments(); + $openedParenthesis += $this->getOpenedParenthesis(); + $this->lexer->moveNext(); + $tmpPrev = $this->lexer->getPrevious(); + if ($tmpPrev['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + $openedParenthesis--; + } + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + if ($openedParenthesis === 0) { + throw new UnopenedComment(); + } else { + $openedParenthesis--; + } + } + + $this->checkConsecutiveDots(); + $this->checkDomainPartExceptions($prev); + + if ($this->hasBrackets()) { + $this->parseDomainLiteral(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_DOT) { + $this->checkLabelLength($label); + $label = ''; + } else { + $label .= $this->lexer->token['value']; + } + + if ($this->isFWS()) { + $this->parseFWS(); + } + + $domain .= $this->lexer->token['value']; + $this->lexer->moveNext(); + if ($this->lexer->token['type'] === EmailLexer::S_SP) { + throw new CharNotAllowed(); + } + } while (null !== $this->lexer->token['type']); + + $this->checkLabelLength($label); + + return $domain; + } + + private function checkNotAllowedChars(array $token) + { + $notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH=> true]; + if (isset($notAllowed[$token['type']])) { + throw new CharNotAllowed(); + } + } + + /** + * @return string|false + */ + protected function parseDomainLiteral() + { + if ($this->lexer->isNextToken(EmailLexer::S_COLON)) { + $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); + } + if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) { + $lexer = clone $this->lexer; + $lexer->moveNext(); + if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) { + $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); + } + } + + return $this->doParseDomainLiteral(); + } + + /** + * @return string|false + */ + protected function doParseDomainLiteral() + { + $IPv6TAG = false; + $addressLiteral = ''; + do { + if ($this->lexer->token['type'] === EmailLexer::C_NUL) { + throw new ExpectingDTEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::INVALID || + $this->lexer->token['type'] === EmailLexer::C_DEL || + $this->lexer->token['type'] === EmailLexer::S_LF + ) { + $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); + } + + if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENQBRACKET, EmailLexer::S_OPENBRACKET))) { + throw new ExpectingDTEXT(); + } + + if ($this->lexer->isNextTokenAny( + array(EmailLexer::S_HTAB, EmailLexer::S_SP, $this->lexer->token['type'] === EmailLexer::CRLF) + )) { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + $this->parseFWS(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_CR)) { + throw new CRNoLF(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH) { + $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); + $addressLiteral .= $this->lexer->token['value']; + $this->lexer->moveNext(); + $this->validateQuotedPair(); + } + if ($this->lexer->token['type'] === EmailLexer::S_IPV6TAG) { + $IPv6TAG = true; + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEQBRACKET) { + break; + } + + $addressLiteral .= $this->lexer->token['value']; + + } while ($this->lexer->moveNext()); + + $addressLiteral = str_replace('[', '', $addressLiteral); + $addressLiteral = $this->checkIPV4Tag($addressLiteral); + + if (false === $addressLiteral) { + return $addressLiteral; + } + + if (!$IPv6TAG) { + $this->warnings[DomainLiteral::CODE] = new DomainLiteral(); + return $addressLiteral; + } + + $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); + + $this->checkIPV6Tag($addressLiteral); + + return $addressLiteral; + } + + /** + * @param string $addressLiteral + * + * @return string|false + */ + protected function checkIPV4Tag($addressLiteral) + { + $matchesIP = array(); + + // Extract IPv4 part from the end of the address-literal (if there is one) + if (preg_match( + '/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/', + $addressLiteral, + $matchesIP + ) > 0 + ) { + $index = strrpos($addressLiteral, $matchesIP[0]); + if ($index === 0) { + $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); + return false; + } + // Convert IPv4 part to IPv6 format for further testing + $addressLiteral = substr($addressLiteral, 0, (int) $index) . '0:0'; + } + + return $addressLiteral; + } + + protected function checkDomainPartExceptions(array $prev) + { + $invalidDomainTokens = array( + EmailLexer::S_DQUOTE => true, + EmailLexer::S_SQUOTE => true, + EmailLexer::S_BACKTICK => true, + EmailLexer::S_SEMICOLON => true, + EmailLexer::S_GREATERTHAN => true, + EmailLexer::S_LOWERTHAN => true, + ); + + if (isset($invalidDomainTokens[$this->lexer->token['type']])) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_COMMA) { + throw new CommaInDomain(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_AT) { + throw new ConsecutiveAt(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENQBRACKET && $prev['type'] !== EmailLexer::S_AT) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN && $this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new DomainHyphened(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH + && $this->lexer->isNextToken(EmailLexer::GENERIC)) { + throw new ExpectingATEXT(); + } + } + + /** + * @return bool + */ + protected function hasBrackets() + { + if ($this->lexer->token['type'] !== EmailLexer::S_OPENBRACKET) { + return false; + } + + try { + $this->lexer->find(EmailLexer::S_CLOSEBRACKET); + } catch (\RuntimeException $e) { + throw new ExpectingDomainLiteralClose(); + } + + return true; + } + + /** + * @param string $label + */ + protected function checkLabelLength($label) + { + if ($this->isLabelTooLong($label)) { + $this->warnings[LabelTooLong::CODE] = new LabelTooLong(); + } + } + + /** + * @param string $label + * @return bool + */ + private function isLabelTooLong($label) + { + if (preg_match('/[^\x00-\x7F]/', $label)) { + idn_to_ascii($label, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, $idnaInfo); + + return (bool) ($idnaInfo['errors'] & IDNA_ERROR_LABEL_TOO_LONG); + } + + return strlen($label) > self::LABEL_MAX_LENGTH; + } + + protected function parseDomainComments() + { + $this->isUnclosedComment(); + while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { + $this->warnEscaping(); + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + if ($this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new ExpectingATEXT(); + } + } + + protected function addTLDWarnings() + { + if ($this->warnings[DomainLiteral::CODE]) { + $this->warnings[TLD::CODE] = new TLD(); + } + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Parser/LocalPart.php b/php/libraries/composer/vendor/egulias/email-validator/src/Parser/LocalPart.php new file mode 100644 index 0000000..3c21f34 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Parser/LocalPart.php @@ -0,0 +1,145 @@ +lexer->token['type'] !== EmailLexer::S_AT && null !== $this->lexer->token['type']) { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && null === $this->lexer->getPrevious()['type']) { + throw new DotAtStart(); + } + + $closingQuote = $this->checkDQUOTE($closingQuote); + if ($closingQuote && $parseDQuote) { + $parseDQuote = $this->parseDoubleQuote(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->parseComments(); + $openedParenthesis += $this->getOpenedParenthesis(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + if ($openedParenthesis === 0) { + throw new UnopenedComment(); + } + + $openedParenthesis--; + } + + $this->checkConsecutiveDots(); + + if ($this->lexer->token['type'] === EmailLexer::S_DOT && + $this->lexer->isNextToken(EmailLexer::S_AT) + ) { + throw new DotAtEnd(); + } + + $this->warnEscaping(); + $this->isInvalidToken($this->lexer->token, $closingQuote); + + if ($this->isFWS()) { + $this->parseFWS(); + } + + $totalLength += strlen($this->lexer->token['value']); + $this->lexer->moveNext(); + } + + if ($totalLength > LocalTooLong::LOCAL_PART_LENGTH) { + $this->warnings[LocalTooLong::CODE] = new LocalTooLong(); + } + } + + /** + * @return bool + */ + protected function parseDoubleQuote() + { + $parseAgain = true; + $special = array( + EmailLexer::S_CR => true, + EmailLexer::S_HTAB => true, + EmailLexer::S_LF => true + ); + + $invalid = array( + EmailLexer::C_NUL => true, + EmailLexer::S_HTAB => true, + EmailLexer::S_CR => true, + EmailLexer::S_LF => true + ); + $setSpecialsWarning = true; + + $this->lexer->moveNext(); + + while ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE && null !== $this->lexer->token['type']) { + $parseAgain = false; + if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + $setSpecialsWarning = false; + } + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) { + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + + if (!$this->escaped() && isset($invalid[$this->lexer->token['type']])) { + throw new ExpectingATEXT(); + } + } + + $prev = $this->lexer->getPrevious(); + + if ($prev['type'] === EmailLexer::S_BACKSLASH) { + if (!$this->checkDQUOTE(false)) { + throw new UnclosedQuotedString(); + } + } + + if (!$this->lexer->isNextToken(EmailLexer::S_AT) && $prev['type'] !== EmailLexer::S_BACKSLASH) { + throw new ExpectingAT(); + } + + return $parseAgain; + } + + /** + * @param bool $closingQuote + */ + protected function isInvalidToken(array $token, $closingQuote) + { + $forbidden = array( + EmailLexer::S_COMMA, + EmailLexer::S_CLOSEBRACKET, + EmailLexer::S_OPENBRACKET, + EmailLexer::S_GREATERTHAN, + EmailLexer::S_LOWERTHAN, + EmailLexer::S_COLON, + EmailLexer::S_SEMICOLON, + EmailLexer::INVALID + ); + + if (in_array($token['type'], $forbidden) && !$closingQuote) { + throw new ExpectingATEXT(); + } + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Parser/Parser.php b/php/libraries/composer/vendor/egulias/email-validator/src/Parser/Parser.php new file mode 100644 index 0000000..ccdc938 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Parser/Parser.php @@ -0,0 +1,249 @@ +lexer = $lexer; + } + + /** + * @return \Egulias\EmailValidator\Warning\Warning[] + */ + public function getWarnings() + { + return $this->warnings; + } + + /** + * @param string $str + */ + abstract public function parse($str); + + /** @return int */ + public function getOpenedParenthesis() + { + return $this->openedParenthesis; + } + + /** + * validateQuotedPair + */ + protected function validateQuotedPair() + { + if (!($this->lexer->token['type'] === EmailLexer::INVALID + || $this->lexer->token['type'] === EmailLexer::C_DEL)) { + throw new ExpectingQPair(); + } + + $this->warnings[QuotedPart::CODE] = + new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); + } + + protected function parseComments() + { + $this->openedParenthesis = 1; + $this->isUnclosedComment(); + $this->warnings[Comment::CODE] = new Comment(); + while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { + if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) { + $this->openedParenthesis++; + } + $this->warnEscaping(); + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + if ($this->lexer->isNextTokenAny(array(EmailLexer::GENERIC, EmailLexer::S_EMPTY))) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_AT)) { + $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); + } + } + + /** + * @return bool + */ + protected function isUnclosedComment() + { + try { + $this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS); + return true; + } catch (\RuntimeException $e) { + throw new UnclosedComment(); + } + } + + protected function parseFWS() + { + $previous = $this->lexer->getPrevious(); + + $this->checkCRLFInFWS(); + + if ($this->lexer->token['type'] === EmailLexer::S_CR) { + throw new CRNoLF(); + } + + if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] !== EmailLexer::S_AT) { + throw new AtextAfterCFWS(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_LF || $this->lexer->token['type'] === EmailLexer::C_NUL) { + throw new ExpectingCTEXT(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous['type'] === EmailLexer::S_AT) { + $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); + } else { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + } + } + + protected function checkConsecutiveDots() + { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new ConsecutiveDot(); + } + } + + /** + * @return bool + */ + protected function isFWS() + { + if ($this->escaped()) { + return false; + } + + if ($this->lexer->token['type'] === EmailLexer::S_SP || + $this->lexer->token['type'] === EmailLexer::S_HTAB || + $this->lexer->token['type'] === EmailLexer::S_CR || + $this->lexer->token['type'] === EmailLexer::S_LF || + $this->lexer->token['type'] === EmailLexer::CRLF + ) { + return true; + } + + return false; + } + + /** + * @return bool + */ + protected function escaped() + { + $previous = $this->lexer->getPrevious(); + + if ($previous && $previous['type'] === EmailLexer::S_BACKSLASH + && + $this->lexer->token['type'] !== EmailLexer::GENERIC + ) { + return true; + } + + return false; + } + + /** + * @return bool + */ + protected function warnEscaping() + { + if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) { + return false; + } + + if ($this->lexer->isNextToken(EmailLexer::GENERIC)) { + throw new ExpectingATEXT(); + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) { + return false; + } + + $this->warnings[QuotedPart::CODE] = + new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); + return true; + + } + + /** + * @param bool $hasClosingQuote + * + * @return bool + */ + protected function checkDQUOTE($hasClosingQuote) + { + if ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE) { + return $hasClosingQuote; + } + if ($hasClosingQuote) { + return $hasClosingQuote; + } + $previous = $this->lexer->getPrevious(); + if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] === EmailLexer::GENERIC) { + throw new ExpectingATEXT(); + } + + try { + $this->lexer->find(EmailLexer::S_DQUOTE); + $hasClosingQuote = true; + } catch (\Exception $e) { + throw new UnclosedQuotedString(); + } + $this->warnings[QuotedString::CODE] = new QuotedString($previous['value'], $this->lexer->token['value']); + + return $hasClosingQuote; + } + + protected function checkCRLFInFWS() + { + if ($this->lexer->token['type'] !== EmailLexer::CRLF) { + return; + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { + throw new CRLFX2(); + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { + throw new CRLFAtTheEnd(); + } + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php new file mode 100644 index 0000000..491082a --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php @@ -0,0 +1,166 @@ +error = new LocalOrReservedDomain(); + return false; + } + + return $this->checkDns($host); + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return $this->warnings; + } + + /** + * @param string $host + * + * @return bool + */ + protected function checkDns($host) + { + $variant = INTL_IDNA_VARIANT_UTS46; + + $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.') . '.'; + + return $this->validateDnsRecords($host); + } + + + /** + * Validate the DNS records for given host. + * + * @param string $host A set of DNS records in the format returned by dns_get_record. + * + * @return bool True on success. + */ + private function validateDnsRecords($host) + { + // Get all MX, A and AAAA DNS records for host + // Using @ as workaround to fix https://bugs.php.net/bug.php?id=73149 + $dnsRecords = @dns_get_record($host, DNS_MX + DNS_A + DNS_AAAA); + + + // No MX, A or AAAA DNS records + if (empty($dnsRecords)) { + $this->error = new NoDNSRecord(); + return false; + } + + // For each DNS record + foreach ($dnsRecords as $dnsRecord) { + if (!$this->validateMXRecord($dnsRecord)) { + return false; + } + } + + // No MX records (fallback to A or AAAA records) + if (empty($this->mxRecords)) { + $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord(); + } + + return true; + } + + /** + * Validate an MX record + * + * @param array $dnsRecord Given DNS record. + * + * @return bool True if valid. + */ + private function validateMxRecord($dnsRecord) + { + if ($dnsRecord['type'] !== 'MX') { + return true; + } + + // "Null MX" record indicates the domain accepts no mail (https://tools.ietf.org/html/rfc7505) + if (empty($dnsRecord['target']) || $dnsRecord['target'] === '.') { + $this->error = new DomainAcceptsNoMail(); + return false; + } + + $this->mxRecords[] = $dnsRecord; + + return true; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Validation/EmailValidation.php b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/EmailValidation.php new file mode 100644 index 0000000..d5a015b --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/EmailValidation.php @@ -0,0 +1,34 @@ +errors = $errors; + parent::__construct(); + } + + /** + * @return InvalidEmail[] + */ + public function getErrors() + { + return $this->errors; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Validation/MultipleValidationWithAnd.php b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/MultipleValidationWithAnd.php new file mode 100644 index 0000000..feb2240 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/MultipleValidationWithAnd.php @@ -0,0 +1,124 @@ +validations = $validations; + $this->mode = $mode; + } + + /** + * {@inheritdoc} + */ + public function isValid($email, EmailLexer $emailLexer) + { + $result = true; + $errors = []; + foreach ($this->validations as $validation) { + $emailLexer->reset(); + $validationResult = $validation->isValid($email, $emailLexer); + $result = $result && $validationResult; + $this->warnings = array_merge($this->warnings, $validation->getWarnings()); + $errors = $this->addNewError($validation->getError(), $errors); + + if ($this->shouldStop($result)) { + break; + } + } + + if (!empty($errors)) { + $this->error = new MultipleErrors($errors); + } + + return $result; + } + + /** + * @param \Egulias\EmailValidator\Exception\InvalidEmail|null $possibleError + * @param \Egulias\EmailValidator\Exception\InvalidEmail[] $errors + * + * @return \Egulias\EmailValidator\Exception\InvalidEmail[] + */ + private function addNewError($possibleError, array $errors) + { + if (null !== $possibleError) { + $errors[] = $possibleError; + } + + return $errors; + } + + /** + * @param bool $result + * + * @return bool + */ + private function shouldStop($result) + { + return !$result && $this->mode === self::STOP_ON_ERROR; + } + + /** + * Returns the validation errors. + * + * @return MultipleErrors|null + */ + public function getError() + { + return $this->error; + } + + /** + * {@inheritdoc} + */ + public function getWarnings() + { + return $this->warnings; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Validation/NoRFCWarningsValidation.php b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/NoRFCWarningsValidation.php new file mode 100644 index 0000000..6b31e54 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/NoRFCWarningsValidation.php @@ -0,0 +1,41 @@ +getWarnings())) { + return true; + } + + $this->error = new RFCWarnings(); + + return false; + } + + /** + * {@inheritdoc} + */ + public function getError() + { + return $this->error ?: parent::getError(); + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Validation/RFCValidation.php b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/RFCValidation.php new file mode 100644 index 0000000..8781e0b --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/RFCValidation.php @@ -0,0 +1,49 @@ +parser = new EmailParser($emailLexer); + try { + $this->parser->parse((string)$email); + } catch (InvalidEmail $invalid) { + $this->error = $invalid; + return false; + } + + $this->warnings = $this->parser->getWarnings(); + return true; + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return $this->warnings; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Validation/SpoofCheckValidation.php b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/SpoofCheckValidation.php new file mode 100644 index 0000000..e10bfab --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Validation/SpoofCheckValidation.php @@ -0,0 +1,51 @@ +setChecks(Spoofchecker::SINGLE_SCRIPT); + + if ($checker->isSuspicious($email)) { + $this->error = new SpoofEmail(); + } + + return $this->error === null; + } + + /** + * @return InvalidEmail|null + */ + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return []; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/AddressLiteral.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/AddressLiteral.php new file mode 100644 index 0000000..77e70f7 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/AddressLiteral.php @@ -0,0 +1,14 @@ +message = 'Address literal in domain part'; + $this->rfcNumber = 5321; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/CFWSNearAt.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/CFWSNearAt.php new file mode 100644 index 0000000..be43bbe --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/CFWSNearAt.php @@ -0,0 +1,13 @@ +message = "Deprecated folding white space near @"; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/CFWSWithFWS.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/CFWSWithFWS.php new file mode 100644 index 0000000..dea3450 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/CFWSWithFWS.php @@ -0,0 +1,13 @@ +message = 'Folding whites space followed by folding white space'; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/Comment.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/Comment.php new file mode 100644 index 0000000..704c290 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/Comment.php @@ -0,0 +1,13 @@ +message = "Comments found in this email"; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DeprecatedComment.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DeprecatedComment.php new file mode 100644 index 0000000..ad43bd7 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DeprecatedComment.php @@ -0,0 +1,13 @@ +message = 'Deprecated comments'; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DomainLiteral.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DomainLiteral.php new file mode 100644 index 0000000..6f36b5e --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DomainLiteral.php @@ -0,0 +1,14 @@ +message = 'Domain Literal'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DomainTooLong.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DomainTooLong.php new file mode 100644 index 0000000..61ff17a --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/DomainTooLong.php @@ -0,0 +1,14 @@ +message = 'Domain is too long, exceeds 255 chars'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/EmailTooLong.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/EmailTooLong.php new file mode 100644 index 0000000..497309d --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/EmailTooLong.php @@ -0,0 +1,15 @@ +message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6BadChar.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6BadChar.php new file mode 100644 index 0000000..ba2fcc0 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6BadChar.php @@ -0,0 +1,14 @@ +message = 'Bad char in IPV6 domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6ColonEnd.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6ColonEnd.php new file mode 100644 index 0000000..41afa78 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6ColonEnd.php @@ -0,0 +1,14 @@ +message = ':: found at the end of the domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6ColonStart.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6ColonStart.php new file mode 100644 index 0000000..1bf754e --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6ColonStart.php @@ -0,0 +1,14 @@ +message = ':: found at the start of the domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6Deprecated.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6Deprecated.php new file mode 100644 index 0000000..d752caa --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6Deprecated.php @@ -0,0 +1,14 @@ +message = 'Deprecated form of IPV6'; + $this->rfcNumber = 5321; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6DoubleColon.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6DoubleColon.php new file mode 100644 index 0000000..4f82394 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6DoubleColon.php @@ -0,0 +1,14 @@ +message = 'Double colon found after IPV6 tag'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6GroupCount.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6GroupCount.php new file mode 100644 index 0000000..a59d317 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6GroupCount.php @@ -0,0 +1,14 @@ +message = 'Group count is not IPV6 valid'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6MaxGroups.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6MaxGroups.php new file mode 100644 index 0000000..936274c --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/IPV6MaxGroups.php @@ -0,0 +1,14 @@ +message = 'Reached the maximum number of IPV6 groups allowed'; + $this->rfcNumber = 5321; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/LabelTooLong.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/LabelTooLong.php new file mode 100644 index 0000000..daf07f4 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/LabelTooLong.php @@ -0,0 +1,14 @@ +message = 'Label too long'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/LocalTooLong.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/LocalTooLong.php new file mode 100644 index 0000000..0d08d8b --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/LocalTooLong.php @@ -0,0 +1,15 @@ +message = 'Local part is too long, exceeds 64 chars (octets)'; + $this->rfcNumber = 5322; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/NoDNSMXRecord.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/NoDNSMXRecord.php new file mode 100644 index 0000000..b3c21a1 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/NoDNSMXRecord.php @@ -0,0 +1,14 @@ +message = 'No MX DSN record was found for this email'; + $this->rfcNumber = 5321; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/ObsoleteDTEXT.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/ObsoleteDTEXT.php new file mode 100644 index 0000000..10f19e3 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/ObsoleteDTEXT.php @@ -0,0 +1,14 @@ +rfcNumber = 5322; + $this->message = 'Obsolete DTEXT in domain literal'; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/QuotedPart.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/QuotedPart.php new file mode 100644 index 0000000..36a4265 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/QuotedPart.php @@ -0,0 +1,17 @@ +message = "Deprecated Quoted String found between $prevToken and $postToken"; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/QuotedString.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/QuotedString.php new file mode 100644 index 0000000..817e4e8 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/QuotedString.php @@ -0,0 +1,17 @@ +message = "Quoted String found between $prevToken and $postToken"; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/TLD.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/TLD.php new file mode 100644 index 0000000..2338b9f --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/TLD.php @@ -0,0 +1,13 @@ +message = "RFC5321, TLD"; + } +} diff --git a/php/libraries/composer/vendor/egulias/email-validator/src/Warning/Warning.php b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/Warning.php new file mode 100644 index 0000000..a2ee7b0 --- /dev/null +++ b/php/libraries/composer/vendor/egulias/email-validator/src/Warning/Warning.php @@ -0,0 +1,47 @@ +message; + } + + /** + * @return int + */ + public function code() + { + return static::CODE; + } + + /** + * @return int + */ + public function RFCNumber() + { + return $this->rfcNumber; + } + + public function __toString() + { + return $this->message() . " rfc: " . $this->rfcNumber . "interal code: " . static::CODE; + } +} diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/.editorconfig b/php/libraries/composer/vendor/fruitcake/laravel-cors/.editorconfig new file mode 100644 index 0000000..a7c44dd --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/LICENSE b/php/libraries/composer/vendor/fruitcake/laravel-cors/LICENSE new file mode 100644 index 0000000..3bf9128 --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2013-2016 Barry vd. Heuvel + +Copyright for portions of this project are held by [asm89 (Alexander)] as part of project asm89/stack-cors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/changelog.md b/php/libraries/composer/vendor/fruitcake/laravel-cors/changelog.md new file mode 100644 index 0000000..4cf9220 --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/changelog.md @@ -0,0 +1,43 @@ +# Change Log +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## v2.0 (2020-05-11) + +[asm89/stack-cors 2.x](https://github.com/asm89/stack-cors/releases/tag/2.0.0) is now used, with these notable changes: + +### Added +- CORS headers are better cachable now, with correct Vary headers (#https://github.com/asm89/stack-cors/pull/70, #https://github.com/asm89/stack-cors/pull/74) + +### Changed +- CORS headers are added to non-Origin requests when possible (#https://github.com/asm89/stack-cors/pull/73) +- Requests are no longer blocked by the server, only by the browser (#https://github.com/asm89/stack-cors/pull/70) + +## v1.0 (2019-12-27) + +### Breaking changes + - Adding the middleware on Route groups is no longer supported. You can use the new `paths` option to match your routes + - The config file has been changed from `camelCase` to `snake_case`, please update your own config. + - The deprecated Lumen ServiceProvider has been removed. + - There is no need to manually configure the `cors` config in Lumen. + +### Added + - The `paths` option is added to match certain routes only, while still using global middleware. This allows for better error handling. + +## v0.11.0 (2017-12-xx) +### Breaking changes + - The wildcard matcher is changed. You can use `allowedOriginPatterns` for your own patterns, + or simple wildcards in the normal origins. Eg. `*.laravel.com` should still work. + +## v0.9.0 (2016-03-2017) +### Breaking changes + - The `cors` alias is no longer added by default. Use the full class or add the alias yourself. + - The Lumen ServiceProvider has been removed. Both Laravel and Lumen should use `Barryvdh\Cors\ServiceProvider::class`. + - `Barryvdh\Cors\Stack\CorsService` moves to `\Barryvdh\Cors\CorsService` (namespace changed). + - `Barryvdh\Cors@addActualRequestHeaders` will automatically attached when Exception occured. + +### Added + - Better error-handling when exceptions occur. + - A lot of tests, also on older Laravel versions. diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/composer.json b/php/libraries/composer/vendor/fruitcake/laravel-cors/composer.json new file mode 100644 index 0000000..93c5cea --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/composer.json @@ -0,0 +1,54 @@ +{ + "name": "fruitcake/laravel-cors", + "description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application", + "keywords": ["laravel", "cors", "crossdomain", "api"], + "license": "MIT", + "authors": [ + { + "name": "Fruitcake", + "homepage": "https://fruitcake.nl" + }, + { + "name": "Barry vd. Heuvel", + "email": "barryvdh@gmail.com" + } + ], + "require": { + "php": ">=7.2", + "illuminate/support": "^6|^7|^8|^9", + "illuminate/contracts": "^6|^7|^8|^9", + "asm89/stack-cors": "^2.0.1" + }, + "require-dev": { + "laravel/framework": "^6|^7.24|^8", + "phpunit/phpunit": "^6|^7|^8|^9", + "squizlabs/php_codesniffer": "^3.5", + "orchestra/testbench-dusk": "^4|^5|^6|^7" + }, + "autoload": { + "psr-4": { + "Fruitcake\\Cors\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Fruitcake\\Cors\\Tests\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + }, + "laravel": { + "providers": [ + "Fruitcake\\Cors\\CorsServiceProvider" + ] + } + }, + "scripts": { + "test": "phpunit", + "check-style": "phpcs -p --standard=psr12 src/", + "fix-style": "phpcbf -p --standard=psr12 src/" + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/config/cors.php b/php/libraries/composer/vendor/fruitcake/laravel-cors/config/cors.php new file mode 100644 index 0000000..ea0c98b --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/config/cors.php @@ -0,0 +1,60 @@ + [], + + /* + * Matches the request method. `['*']` allows all methods. + */ + 'allowed_methods' => ['*'], + + /* + * Matches the request origin. `['*']` allows all origins. Wildcards can be used, eg `*.mydomain.com` + */ + 'allowed_origins' => ['*'], + + /* + * Patterns that can be used with `preg_match` to match the origin. + */ + 'allowed_origins_patterns' => [], + + /* + * Sets the Access-Control-Allow-Headers response header. `['*']` allows all headers. + */ + 'allowed_headers' => ['*'], + + /* + * Sets the Access-Control-Expose-Headers response header with these headers. + */ + 'exposed_headers' => [], + + /* + * Sets the Access-Control-Max-Age response header when > 0. + */ + 'max_age' => 0, + + /* + * Sets the Access-Control-Allow-Credentials header. + */ + 'supports_credentials' => false, +]; diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/readme.md b/php/libraries/composer/vendor/fruitcake/laravel-cors/readme.md new file mode 100644 index 0000000..93f716a --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/readme.md @@ -0,0 +1,174 @@ +# CORS Middleware for Laravel + +[![Build Status][ico-actions]][link-actions] +[![Software License][ico-license]](LICENSE.md) +[![Total Downloads][ico-downloads]][link-downloads] +[![Fruitcake](https://img.shields.io/badge/Powered%20By-Fruitcake-b2bc35.svg)](https://fruitcake.nl/) + +Implements https://github.com/fruitcake/php-cors for Laravel + +## About + +The `laravel-cors` package allows you to send [Cross-Origin Resource Sharing](http://enable-cors.org/) +headers with Laravel middleware configuration. + +If you want to have a global overview of CORS workflow, you can browse +this [image](http://www.html5rocks.com/static/images/cors_server_flowchart.png). + +## Upgrading from 0.x (barryvdh/laravel-cors) +When upgrading from 0.x versions, there are some breaking changes: + - **A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!** + - **Group middleware is no longer supported, use the global middleware** + - The vendor name has changed (see installation/usage) + - The casing on the props in `cors.php` has changed from camelCase to snake_case, so if you already have a `cors.php` file you will need to update the props in there to match the new casing. + +## Features + +* Handles CORS pre-flight OPTIONS requests +* Adds CORS headers to your responses +* Match routes to only add CORS to certain Requests + +## Installation + +Require the `fruitcake/laravel-cors` package in your `composer.json` and update your dependencies: +```sh +composer require fruitcake/laravel-cors +``` + +If you get a conflict, this could be because an older version of barryvdh/laravel-cors or fruitcake/laravel-cors is installed. Remove the conflicting package first, then try install again: + +```sh +composer remove barryvdh/laravel-cors fruitcake/laravel-cors +composer require fruitcake/laravel-cors +``` + +## Global usage + +To allow CORS for all your routes, add the `HandleCors` middleware at the top of the `$middleware` property of `app/Http/Kernel.php` class: + +```php +protected $middleware = [ + \Fruitcake\Cors\HandleCors::class, + // ... +]; +``` + +Now update the config to define the paths you want to run the CORS service on, (see Configuration below): + +```php +'paths' => ['api/*'], +``` + +## Configuration + +The defaults are set in `config/cors.php`. Publish the config to copy the file to your own config: +```sh +php artisan vendor:publish --tag="cors" +``` +> **Note:** When using custom headers, like `X-Auth-Token` or `X-Requested-With`, you must set the `allowed_headers` to include those headers. You can also set it to `['*']` to allow all custom headers. + +> **Note:** If you are explicitly whitelisting headers, you must include `Origin` or requests will fail to be recognized as CORS. + + +### Options + +| Option | Description | Default value | +|--------------------------|--------------------------------------------------------------------------|---------------| +| paths | You can enable CORS for 1 or multiple paths, eg. `['api/*'] ` | `[]` | +| allowed_origins | Matches the request origin. Wildcards can be used, eg. `*.mydomain.com` or `mydomain.com:*` | `['*']` | +| allowed_origins_patterns | Matches the request origin with `preg_match`. | `[]` | +| allowed_methods | Matches the request method. | `['*']` | +| allowed_headers | Sets the Access-Control-Allow-Headers response header. | `['*']` | +| exposed_headers | Sets the Access-Control-Expose-Headers response header. | `false` | +| max_age | Sets the Access-Control-Max-Age response header. | `0` | +| supports_credentials | Sets the Access-Control-Allow-Credentials header. | `[]` | + + +`allowed_origins`, `allowed_headers` and `allowed_methods` can be set to `['*']` to accept any value. + +> **Note:** For `allowed_origins` you must include the scheme when not using a wildcard, eg. `['http://example.com', 'https://example.com']`. You must also take into account that the scheme will be present when using `allowed_origins_patterns`. + +> **Note:** Try to be a specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible! + +> **Note:** Because of [http method overriding](http://symfony.com/doc/current/reference/configuration/framework.html#http-method-override) in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well. + +> **Note:** Sometimes it's necessary to specify the port _(when you're coding your app in a local environment for example)_. You can specify the port or using a wildcard here too, eg. `localhost:3000`, `localhost:*` or even using a FQDN `app.mydomain.com:8080` + +### Lumen + +On Lumen, just register the ServiceProvider manually in your `bootstrap/app.php` file: + +```php +$app->register(Fruitcake\Cors\CorsServiceProvider::class); +``` + +Also copy the [cors.php](https://github.com/fruitcake/laravel-cors/blob/master/config/cors.php) config file to `config/cors.php` and put it into action: + +```php +$app->configure('cors'); +``` + +## Global usage for Lumen + +To allow CORS for all your routes, add the `HandleCors` middleware to the global middleware and set the `paths` property in the config. + +```php +$app->middleware([ + // ... + Fruitcake\Cors\HandleCors::class, +]); +``` + +## Common problems + +### Wrong config + +Make sure the `path` option in the config is correct and actually matches the route you are using. Remember to clear the config cache as well. + +### Error handling, Middleware order + +Sometimes errors/middleware that return own responses can prevent the CORS Middleware from being run. Try changing the order of the Middleware and make sure it's the first entry in the global middleware, not a route group. Also check your logs for actual errors, because without CORS, the errors will be swallowed by the browser, only showing CORS errors. Also try running it without CORS to make sure it actually works. + +### Authorization headers / Credentials + +If your Request includes an Authorization header or uses Credentials mode, set the `supports_credentials` value in the config to true. This will set the [Access-Control-Allow-Credentials](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials) Header to `true`. + +### Echo/die + +If you `echo()`, `dd()`, `die()`, `exit()`, `dump()` etc in your code, you will break the Middleware flow. When output is sent before headers, CORS cannot be added. When the scripts exits before the CORS middleware finished, CORS headers will not be added. Always return a proper response or throw an Exception. + +### Disabling CSRF protection for your API + +If possible, use a route group with CSRF protection disabled. +Otherwise you can disable CSRF for certain requests in `App\Http\Middleware\VerifyCsrfToken`: + +```php +protected $except = [ + 'api/*', + 'sub.domain.zone' => [ + 'prefix/*' + ], +]; +``` + +### Duplicate headers +The CORS Middleware should be the only place you add these headers. If you also add headers in .htaccess, nginx or your index.php file, you will get duplicate headers and unexpected results. + +## License + +Released under the MIT License, see [LICENSE](LICENSE). + +[ico-version]: https://img.shields.io/packagist/v/fruitcake/laravel-cors.svg?style=flat-square +[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square +[ico-actions]: https://github.com/fruitcake/laravel-cors/actions/workflows/run-tests.yml/badge.svg +[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/fruitcake/laravel-cors.svg?style=flat-square +[ico-code-quality]: https://img.shields.io/scrutinizer/g/fruitcake/laravel-cors.svg?style=flat-square +[ico-downloads]: https://img.shields.io/packagist/dt/fruitcake/laravel-cors.svg?style=flat-square + +[link-packagist]: https://packagist.org/packages/fruitcake/laravel-cors +[link-actions]: https://github.com/fruitcake/laravel-cors/actions +[link-scrutinizer]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors/code-structure +[link-code-quality]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors +[link-downloads]: https://packagist.org/packages/fruitcake/laravel-cors +[link-author]: https://github.com/fruitcake +[link-contributors]: ../../contributors diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/src/CorsServiceProvider.php b/php/libraries/composer/vendor/fruitcake/laravel-cors/src/CorsServiceProvider.php new file mode 100644 index 0000000..5894815 --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/src/CorsServiceProvider.php @@ -0,0 +1,115 @@ +mergeConfigFrom($this->configPath(), 'cors'); + + $this->app->singleton(CorsService::class, function ($app) { + return new CorsService($this->corsOptions(), $app); + }); + } + + /** + * Register the config for publishing + * + */ + public function boot() + { + if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { + $this->publishes([$this->configPath() => config_path('cors.php')], 'cors'); + } elseif ($this->app instanceof LumenApplication) { + $this->app->configure('cors'); + } + + // Add the headers on the Request Handled event as fallback in case of exceptions + if (class_exists(RequestHandled::class) && $this->app->bound('events')) { + $this->app->make('events')->listen(RequestHandled::class, function (RequestHandled $event) { + $this->app->make(HandleCors::class)->onRequestHandled($event); + }); + } + } + + /** + * Set the config path + * + * @return string + */ + protected function configPath() + { + return __DIR__ . '/../config/cors.php'; + } + + /** + * Get options for CorsService + * + * @return array + */ + protected function corsOptions() + { + $config = $this->app['config']->get('cors'); + + if ($config['exposed_headers'] && !is_array($config['exposed_headers'])) { + throw new \RuntimeException('CORS config `exposed_headers` should be `false` or an array'); + } + + foreach (['allowed_origins', 'allowed_origins_patterns', 'allowed_headers', 'allowed_methods'] as $key) { + if (!is_array($config[$key])) { + throw new \RuntimeException('CORS config `' . $key . '` should be an array'); + } + } + + // Convert case to supported options + $options = [ + 'supportsCredentials' => $config['supports_credentials'], + 'allowedOrigins' => $config['allowed_origins'], + 'allowedOriginsPatterns' => $config['allowed_origins_patterns'], + 'allowedHeaders' => $config['allowed_headers'], + 'allowedMethods' => $config['allowed_methods'], + 'exposedHeaders' => $config['exposed_headers'], + 'maxAge' => $config['max_age'], + ]; + + // Transform wildcard pattern + foreach ($options['allowedOrigins'] as $origin) { + if (strpos($origin, '*') !== false) { + $options['allowedOriginsPatterns'][] = $this->convertWildcardToPattern($origin); + } + } + + return $options; + } + + /** + * Create a pattern for a wildcard, based on Str::is() from Laravel + * + * @see https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Str.php + * @param string $pattern + * @return string + */ + protected function convertWildcardToPattern($pattern) + { + $pattern = preg_quote($pattern, '#'); + + // Asterisks are translated into zero-or-more regular expression wildcards + // to make it convenient to check if the strings starts with the given + // pattern such as "library/*", making any string check convenient. + $pattern = str_replace('\*', '.*', $pattern); + + return '#^' . $pattern . '\z#u'; + } +} diff --git a/php/libraries/composer/vendor/fruitcake/laravel-cors/src/HandleCors.php b/php/libraries/composer/vendor/fruitcake/laravel-cors/src/HandleCors.php new file mode 100644 index 0000000..a876b3f --- /dev/null +++ b/php/libraries/composer/vendor/fruitcake/laravel-cors/src/HandleCors.php @@ -0,0 +1,145 @@ +cors = $cors; + $this->container = $container; + } + + /** + * Handle an incoming request. Based on Asm89\Stack\Cors by asm89 + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return Response + */ + public function handle($request, Closure $next) + { + // Check if we're dealing with CORS and if we should handle it + if (! $this->shouldRun($request)) { + return $next($request); + } + + // For Preflight, return the Preflight response + if ($this->cors->isPreflightRequest($request)) { + $response = $this->cors->handlePreflightRequest($request); + + $this->cors->varyHeader($response, 'Access-Control-Request-Method'); + + return $response; + } + + + // Handle the request + $response = $next($request); + + if ($request->getMethod() === 'OPTIONS') { + $this->cors->varyHeader($response, 'Access-Control-Request-Method'); + } + + return $this->addHeaders($request, $response); + } + + /** + * Add the headers to the Response, if they don't exist yet. + * + * @param Request $request + * @param Response $response + * @return Response + */ + protected function addHeaders(Request $request, Response $response): Response + { + if (! $response->headers->has('Access-Control-Allow-Origin')) { + // Add the CORS headers to the Response + $response = $this->cors->addActualRequestHeaders($response, $request); + } + + return $response; + } + + /** + * Add the headers to the Response, if they don't exist yet. + * + * @param RequestHandled $event + * @deprecated + */ + public function onRequestHandled(RequestHandled $event) + { + if ($this->shouldRun($event->request) && $this->container->make(Kernel::class)->hasMiddleware(static::class)) { + $this->addHeaders($event->request, $event->response); + } + } + + + /** + * Determine if the request has a URI that should pass through the CORS flow. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function shouldRun(Request $request): bool + { + return $this->isMatchingPath($request); + } + + /** + * The the path from the config, to see if the CORS Service should run + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function isMatchingPath(Request $request): bool + { + // Get the paths from the config or the middleware + $paths = $this->getPathsByHost($request->getHost()); + + foreach ($paths as $path) { + if ($path !== '/') { + $path = trim($path, '/'); + } + + if ($request->fullUrlIs($path) || $request->is($path)) { + return true; + } + } + + return false; + } + + /** + * Paths by given host or string values in config by default + * + * @param string $host + * @return array + */ + protected function getPathsByHost(string $host) + { + $paths = $this->container['config']->get('cors.paths', []); + // If where are paths by given host + if (isset($paths[$host])) { + return $paths[$host]; + } + // Defaults + return array_filter($paths, function ($path) { + return is_string($path); + }); + } +} diff --git a/php/libraries/composer/vendor/graham-campbell/result-type/LICENSE b/php/libraries/composer/vendor/graham-campbell/result-type/LICENSE new file mode 100644 index 0000000..bbd75d1 --- /dev/null +++ b/php/libraries/composer/vendor/graham-campbell/result-type/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020-2023 Graham Campbell + +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/php/libraries/composer/vendor/graham-campbell/result-type/composer.json b/php/libraries/composer/vendor/graham-campbell/result-type/composer.json new file mode 100644 index 0000000..b1ba15a --- /dev/null +++ b/php/libraries/composer/vendor/graham-campbell/result-type/composer.json @@ -0,0 +1,33 @@ +{ + "name": "graham-campbell/result-type", + "description": "An Implementation Of The Result Type", + "keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GrahamCampbell\\Tests\\ResultType\\": "tests/" + } + }, + "config": { + "preferred-install": "dist" + } +} diff --git a/php/libraries/composer/vendor/graham-campbell/result-type/src/Error.php b/php/libraries/composer/vendor/graham-campbell/result-type/src/Error.php new file mode 100644 index 0000000..2c37c3e --- /dev/null +++ b/php/libraries/composer/vendor/graham-campbell/result-type/src/Error.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace GrahamCampbell\ResultType; + +use PhpOption\None; +use PhpOption\Some; + +/** + * @template T + * @template E + * + * @extends \GrahamCampbell\ResultType\Result + */ +final class Error extends Result +{ + /** + * @var E + */ + private $value; + + /** + * Internal constructor for an error value. + * + * @param E $value + * + * @return void + */ + private function __construct($value) + { + $this->value = $value; + } + + /** + * Create a new error value. + * + * @template F + * + * @param F $value + * + * @return \GrahamCampbell\ResultType\Result + */ + public static function create($value) + { + return new self($value); + } + + /** + * Get the success option value. + * + * @return \PhpOption\Option + */ + public function success() + { + return None::create(); + } + + /** + * Map over the success value. + * + * @template S + * + * @param callable(T):S $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function map(callable $f) + { + return self::create($this->value); + } + + /** + * Flat map over the success value. + * + * @template S + * @template F + * + * @param callable(T):\GrahamCampbell\ResultType\Result $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function flatMap(callable $f) + { + /** @var \GrahamCampbell\ResultType\Result */ + return self::create($this->value); + } + + /** + * Get the error option value. + * + * @return \PhpOption\Option + */ + public function error() + { + return Some::create($this->value); + } + + /** + * Map over the error value. + * + * @template F + * + * @param callable(E):F $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function mapError(callable $f) + { + return self::create($f($this->value)); + } +} diff --git a/php/libraries/composer/vendor/graham-campbell/result-type/src/Result.php b/php/libraries/composer/vendor/graham-campbell/result-type/src/Result.php new file mode 100644 index 0000000..8c67bcd --- /dev/null +++ b/php/libraries/composer/vendor/graham-campbell/result-type/src/Result.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace GrahamCampbell\ResultType; + +/** + * @template T + * @template E + */ +abstract class Result +{ + /** + * Get the success option value. + * + * @return \PhpOption\Option + */ + abstract public function success(); + + /** + * Map over the success value. + * + * @template S + * + * @param callable(T):S $f + * + * @return \GrahamCampbell\ResultType\Result + */ + abstract public function map(callable $f); + + /** + * Flat map over the success value. + * + * @template S + * @template F + * + * @param callable(T):\GrahamCampbell\ResultType\Result $f + * + * @return \GrahamCampbell\ResultType\Result + */ + abstract public function flatMap(callable $f); + + /** + * Get the error option value. + * + * @return \PhpOption\Option + */ + abstract public function error(); + + /** + * Map over the error value. + * + * @template F + * + * @param callable(E):F $f + * + * @return \GrahamCampbell\ResultType\Result + */ + abstract public function mapError(callable $f); +} diff --git a/php/libraries/composer/vendor/graham-campbell/result-type/src/Success.php b/php/libraries/composer/vendor/graham-campbell/result-type/src/Success.php new file mode 100644 index 0000000..27cd85e --- /dev/null +++ b/php/libraries/composer/vendor/graham-campbell/result-type/src/Success.php @@ -0,0 +1,120 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace GrahamCampbell\ResultType; + +use PhpOption\None; +use PhpOption\Some; + +/** + * @template T + * @template E + * + * @extends \GrahamCampbell\ResultType\Result + */ +final class Success extends Result +{ + /** + * @var T + */ + private $value; + + /** + * Internal constructor for a success value. + * + * @param T $value + * + * @return void + */ + private function __construct($value) + { + $this->value = $value; + } + + /** + * Create a new error value. + * + * @template S + * + * @param S $value + * + * @return \GrahamCampbell\ResultType\Result + */ + public static function create($value) + { + return new self($value); + } + + /** + * Get the success option value. + * + * @return \PhpOption\Option + */ + public function success() + { + return Some::create($this->value); + } + + /** + * Map over the success value. + * + * @template S + * + * @param callable(T):S $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function map(callable $f) + { + return self::create($f($this->value)); + } + + /** + * Flat map over the success value. + * + * @template S + * @template F + * + * @param callable(T):\GrahamCampbell\ResultType\Result $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function flatMap(callable $f) + { + return $f($this->value); + } + + /** + * Get the error option value. + * + * @return \PhpOption\Option + */ + public function error() + { + return None::create(); + } + + /** + * Map over the error value. + * + * @template F + * + * @param callable(E):F $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function mapError(callable $f) + { + return self::create($this->value); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/CHANGELOG.md b/php/libraries/composer/vendor/guzzlehttp/guzzle/CHANGELOG.md new file mode 100644 index 0000000..13709d1 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/CHANGELOG.md @@ -0,0 +1,1633 @@ +# Change Log + +Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. + + +## 7.8.1 - 2023-12-03 + +### Changed + +- Updated links in docs to their canonical versions +- Replaced `call_user_func*` with native calls + + +## 7.8.0 - 2023-08-27 + +### Added + +- Support for PHP 8.3 +- Added automatic closing of handles on `CurlFactory` object destruction + + +## 7.7.1 - 2023-08-27 + +### Changed + +- Remove the need for `AllowDynamicProperties` in `CurlMultiHandler` + + +## 7.7.0 - 2023-05-21 + +### Added + +- Support `guzzlehttp/promises` v2 + + +## 7.6.1 - 2023-05-15 + +### Fixed + +- Fix `SetCookie::fromString` MaxAge deprecation warning and skip invalid MaxAge values + + +## 7.6.0 - 2023-05-14 + +### Added + +- Support for setting the minimum TLS version in a unified way +- Apply on request the version set in options parameters + + +## 7.5.2 - 2023-05-14 + +### Fixed + +- Fixed set cookie constructor validation +- Fixed handling of files with `'0'` body + +### Changed + +- Corrected docs and default connect timeout value to 300 seconds + + +## 7.5.1 - 2023-04-17 + +### Fixed + +- Fixed `NO_PROXY` settings so that setting the `proxy` option to `no` overrides the env variable + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^1.9.1 || ^2.4.5` + + +## 7.5.0 - 2022-08-28 + +### Added + +- Support PHP 8.2 +- Add request to delay closure params + + +## 7.4.5 - 2022-06-20 + +### Fixed + +* Fix change in port should be considered a change in origin +* Fix `CURLOPT_HTTPAUTH` option not cleared on change of origin + + +## 7.4.4 - 2022-06-09 + +### Fixed + +* Fix failure to strip Authorization header on HTTP downgrade +* Fix failure to strip the Cookie header on change in host or HTTP downgrade + + +## 7.4.3 - 2022-05-25 + +### Fixed + +* Fix cross-domain cookie leakage + + +## 7.4.2 - 2022-03-20 + +### Fixed + +- Remove curl auth on cross-domain redirects to align with the Authorization HTTP header +- Reject non-HTTP schemes in StreamHandler +- Set a default ssl.peer_name context in StreamHandler to allow `force_ip_resolve` + + +## 7.4.1 - 2021-12-06 + +### Changed + +- Replaced implicit URI to string coercion [#2946](https://github.com/guzzle/guzzle/pull/2946) +- Allow `symfony/deprecation-contracts` version 3 [#2961](https://github.com/guzzle/guzzle/pull/2961) + +### Fixed + +- Only close curl handle if it's done [#2950](https://github.com/guzzle/guzzle/pull/2950) + + +## 7.4.0 - 2021-10-18 + +### Added + +- Support PHP 8.1 [#2929](https://github.com/guzzle/guzzle/pull/2929), [#2939](https://github.com/guzzle/guzzle/pull/2939) +- Support `psr/log` version 2 and 3 [#2943](https://github.com/guzzle/guzzle/pull/2943) + +### Fixed + +- Make sure we always call `restore_error_handler()` [#2915](https://github.com/guzzle/guzzle/pull/2915) +- Fix progress parameter type compatibility between the cURL and stream handlers [#2936](https://github.com/guzzle/guzzle/pull/2936) +- Throw `InvalidArgumentException` when an incorrect `headers` array is provided [#2916](https://github.com/guzzle/guzzle/pull/2916), [#2942](https://github.com/guzzle/guzzle/pull/2942) + +### Changed + +- Be more strict with types [#2914](https://github.com/guzzle/guzzle/pull/2914), [#2917](https://github.com/guzzle/guzzle/pull/2917), [#2919](https://github.com/guzzle/guzzle/pull/2919), [#2945](https://github.com/guzzle/guzzle/pull/2945) + + +## 7.3.0 - 2021-03-23 + +### Added + +- Support for DER and P12 certificates [#2413](https://github.com/guzzle/guzzle/pull/2413) +- Support the cURL (http://) scheme for StreamHandler proxies [#2850](https://github.com/guzzle/guzzle/pull/2850) +- Support for `guzzlehttp/psr7:^2.0` [#2878](https://github.com/guzzle/guzzle/pull/2878) + +### Fixed + +- Handle exceptions on invalid header consistently between PHP versions and handlers [#2872](https://github.com/guzzle/guzzle/pull/2872) + + +## 7.2.0 - 2020-10-10 + +### Added + +- Support for PHP 8 [#2712](https://github.com/guzzle/guzzle/pull/2712), [#2715](https://github.com/guzzle/guzzle/pull/2715), [#2789](https://github.com/guzzle/guzzle/pull/2789) +- Support passing a body summarizer to the http errors middleware [#2795](https://github.com/guzzle/guzzle/pull/2795) + +### Fixed + +- Handle exceptions during response creation [#2591](https://github.com/guzzle/guzzle/pull/2591) +- Fix CURLOPT_ENCODING not to be overwritten [#2595](https://github.com/guzzle/guzzle/pull/2595) +- Make sure the Request always has a body object [#2804](https://github.com/guzzle/guzzle/pull/2804) + +### Changed + +- The `TooManyRedirectsException` has a response [#2660](https://github.com/guzzle/guzzle/pull/2660) +- Avoid "functions" from dependencies [#2712](https://github.com/guzzle/guzzle/pull/2712) + +### Deprecated + +- Using environment variable GUZZLE_CURL_SELECT_TIMEOUT [#2786](https://github.com/guzzle/guzzle/pull/2786) + + +## 7.1.1 - 2020-09-30 + +### Fixed + +- Incorrect EOF detection for response body streams on Windows. + +### Changed + +- We dont connect curl `sink` on HEAD requests. +- Removed some PHP 5 workarounds + + +## 7.1.0 - 2020-09-22 + +### Added + +- `GuzzleHttp\MessageFormatterInterface` + +### Fixed + +- Fixed issue that caused cookies with no value not to be stored. +- On redirects, we allow all safe methods like GET, HEAD and OPTIONS. +- Fixed logging on empty responses. +- Make sure MessageFormatter::format returns string + +### Deprecated + +- All functions in `GuzzleHttp` has been deprecated. Use static methods on `Utils` instead. +- `ClientInterface::getConfig()` +- `Client::getConfig()` +- `Client::__call()` +- `Utils::defaultCaBundle()` +- `CurlFactory::LOW_CURL_VERSION_NUMBER` + + +## 7.0.1 - 2020-06-27 + +* Fix multiply defined functions fatal error [#2699](https://github.com/guzzle/guzzle/pull/2699) + + +## 7.0.0 - 2020-06-27 + +No changes since 7.0.0-rc1. + + +## 7.0.0-rc1 - 2020-06-15 + +### Changed + +* Use error level for logging errors in Middleware [#2629](https://github.com/guzzle/guzzle/pull/2629) +* Disabled IDN support by default and require ext-intl to use it [#2675](https://github.com/guzzle/guzzle/pull/2675) + + +## 7.0.0-beta2 - 2020-05-25 + +### Added + +* Using `Utils` class instead of functions in the `GuzzleHttp` namespace. [#2546](https://github.com/guzzle/guzzle/pull/2546) +* `ClientInterface::MAJOR_VERSION` [#2583](https://github.com/guzzle/guzzle/pull/2583) + +### Changed + +* Avoid the `getenv` function when unsafe [#2531](https://github.com/guzzle/guzzle/pull/2531) +* Added real client methods [#2529](https://github.com/guzzle/guzzle/pull/2529) +* Avoid functions due to global install conflicts [#2546](https://github.com/guzzle/guzzle/pull/2546) +* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550) +* Adding methods for HTTP verbs like `Client::get()`, `Client::head()`, `Client::patch()` etc [#2529](https://github.com/guzzle/guzzle/pull/2529) +* `ConnectException` extends `TransferException` [#2541](https://github.com/guzzle/guzzle/pull/2541) +* Updated the default User Agent to "GuzzleHttp/7" [#2654](https://github.com/guzzle/guzzle/pull/2654) + +### Fixed + +* Various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626) + +### Removed + +* Pool option `pool_size` [#2528](https://github.com/guzzle/guzzle/pull/2528) + + +## 7.0.0-beta1 - 2019-12-30 + +The diff might look very big but 95% of Guzzle users will be able to upgrade without modification. +Please see [the upgrade document](UPGRADING.md) that describes all BC breaking changes. + +### Added + +* Implement PSR-18 and dropped PHP 5 support [#2421](https://github.com/guzzle/guzzle/pull/2421) [#2474](https://github.com/guzzle/guzzle/pull/2474) +* PHP 7 types [#2442](https://github.com/guzzle/guzzle/pull/2442) [#2449](https://github.com/guzzle/guzzle/pull/2449) [#2466](https://github.com/guzzle/guzzle/pull/2466) [#2497](https://github.com/guzzle/guzzle/pull/2497) [#2499](https://github.com/guzzle/guzzle/pull/2499) +* IDN support for redirects [2424](https://github.com/guzzle/guzzle/pull/2424) + +### Changed + +* Dont allow passing null as third argument to `BadResponseException::__construct()` [#2427](https://github.com/guzzle/guzzle/pull/2427) +* Use SAPI constant instead of method call [#2450](https://github.com/guzzle/guzzle/pull/2450) +* Use native function invocation [#2444](https://github.com/guzzle/guzzle/pull/2444) +* Better defaults for PHP installations with old ICU lib [2454](https://github.com/guzzle/guzzle/pull/2454) +* Added visibility to all constants [#2462](https://github.com/guzzle/guzzle/pull/2462) +* Dont allow passing `null` as URI to `Client::request()` and `Client::requestAsync()` [#2461](https://github.com/guzzle/guzzle/pull/2461) +* Widen the exception argument to throwable [#2495](https://github.com/guzzle/guzzle/pull/2495) + +### Fixed + +* Logging when Promise rejected with a string [#2311](https://github.com/guzzle/guzzle/pull/2311) + +### Removed + +* Class `SeekException` [#2162](https://github.com/guzzle/guzzle/pull/2162) +* `RequestException::getResponseBodySummary()` [#2425](https://github.com/guzzle/guzzle/pull/2425) +* `CookieJar::getCookieValue()` [#2433](https://github.com/guzzle/guzzle/pull/2433) +* `uri_template()` and `UriTemplate` [#2440](https://github.com/guzzle/guzzle/pull/2440) +* Request options `save_to` and `exceptions` [#2464](https://github.com/guzzle/guzzle/pull/2464) + + +## 6.5.2 - 2019-12-23 + +* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489) + + +## 6.5.1 - 2019-12-21 + +* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454) +* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424) + + +## 6.5.0 - 2019-12-07 + +* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143) +* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287) +* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: `RetryMiddleware` did not do exponential delay between retires due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348) +* Deprecated `ClientInterface::VERSION` + + +## 6.4.1 - 2019-10-23 + +* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that +* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar` + + +## 6.4.0 - 2019-10-23 + +* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108) +* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081) +* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161) +* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163) +* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242) +* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284) +* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273) +* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335) +* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362) + + +## 6.3.3 - 2018-04-22 + +* Fix: Default headers when decode_content is specified + + +## 6.3.2 - 2018-03-26 + +* Fix: Release process + + +## 6.3.1 - 2018-03-26 + +* Bug fix: Parsing 0 epoch expiry times in cookies [#2014](https://github.com/guzzle/guzzle/pull/2014) +* Improvement: Better ConnectException detection [#2012](https://github.com/guzzle/guzzle/pull/2012) +* Bug fix: Malformed domain that contains a "/" [#1999](https://github.com/guzzle/guzzle/pull/1999) +* Bug fix: Undefined offset when a cookie has no first key-value pair [#1998](https://github.com/guzzle/guzzle/pull/1998) +* Improvement: Support PHPUnit 6 [#1953](https://github.com/guzzle/guzzle/pull/1953) +* Bug fix: Support empty headers [#1915](https://github.com/guzzle/guzzle/pull/1915) +* Bug fix: Ignore case during header modifications [#1916](https://github.com/guzzle/guzzle/pull/1916) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.3.0 - 2017-06-22 + +* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) +* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) +* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) +* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) +* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) +* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) +* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) +* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) +* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) +* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) +* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) +* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) +* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) +* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) +* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.2.3 - 2017-02-28 + +* Fix deprecations with guzzle/psr7 version 1.4 + + +## 6.2.2 - 2016-10-08 + +* Allow to pass nullable Response to delay callable +* Only add scheme when host is present +* Fix drain case where content-length is the literal string zero +* Obfuscate in-URL credentials in exceptions + + +## 6.2.1 - 2016-07-18 + +* Address HTTP_PROXY security vulnerability, CVE-2016-5385: + https://httpoxy.org/ +* Fixing timeout bug with StreamHandler: + https://github.com/guzzle/guzzle/pull/1488 +* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when + a server does not honor `Connection: close`. +* Ignore URI fragment when sending requests. + + +## 6.2.0 - 2016-03-21 + +* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. + https://github.com/guzzle/guzzle/pull/1389 +* Bug fix: Fix sleep calculation when waiting for delayed requests. + https://github.com/guzzle/guzzle/pull/1324 +* Feature: More flexible history containers. + https://github.com/guzzle/guzzle/pull/1373 +* Bug fix: defer sink stream opening in StreamHandler. + https://github.com/guzzle/guzzle/pull/1377 +* Bug fix: do not attempt to escape cookie values. + https://github.com/guzzle/guzzle/pull/1406 +* Feature: report original content encoding and length on decoded responses. + https://github.com/guzzle/guzzle/pull/1409 +* Bug fix: rewind seekable request bodies before dispatching to cURL. + https://github.com/guzzle/guzzle/pull/1422 +* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. + https://github.com/guzzle/guzzle/pull/1367 + + +## 6.1.1 - 2015-11-22 + +* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler + https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 +* Feature: HandlerStack is now more generic. + https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e +* Bug fix: setting verify to false in the StreamHandler now disables peer + verification. https://github.com/guzzle/guzzle/issues/1256 +* Feature: Middleware now uses an exception factory, including more error + context. https://github.com/guzzle/guzzle/pull/1282 +* Feature: better support for disabled functions. + https://github.com/guzzle/guzzle/pull/1287 +* Bug fix: fixed regression where MockHandler was not using `sink`. + https://github.com/guzzle/guzzle/pull/1292 + + +## 6.1.0 - 2015-09-08 + +* Feature: Added the `on_stats` request option to provide access to transfer + statistics for requests. https://github.com/guzzle/guzzle/pull/1202 +* Feature: Added the ability to persist session cookies in CookieJars. + https://github.com/guzzle/guzzle/pull/1195 +* Feature: Some compatibility updates for Google APP Engine + https://github.com/guzzle/guzzle/pull/1216 +* Feature: Added support for NO_PROXY to prevent the use of a proxy based on + a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 +* Feature: Cookies can now contain square brackets. + https://github.com/guzzle/guzzle/pull/1237 +* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. + https://github.com/guzzle/guzzle/pull/1232 +* Bug fix: Cusotm cURL options now correctly override curl options of the + same name. https://github.com/guzzle/guzzle/pull/1221 +* Bug fix: Content-Type header is now added when using an explicitly provided + multipart body. https://github.com/guzzle/guzzle/pull/1218 +* Bug fix: Now ignoring Set-Cookie headers that have no name. +* Bug fix: Reason phrase is no longer cast to an int in some cases in the + cURL handler. https://github.com/guzzle/guzzle/pull/1187 +* Bug fix: Remove the Authorization header when redirecting if the Host + header changes. https://github.com/guzzle/guzzle/pull/1207 +* Bug fix: Cookie path matching fixes + https://github.com/guzzle/guzzle/issues/1129 +* Bug fix: Fixing the cURL `body_as_string` setting + https://github.com/guzzle/guzzle/pull/1201 +* Bug fix: quotes are no longer stripped when parsing cookies. + https://github.com/guzzle/guzzle/issues/1172 +* Bug fix: `form_params` and `query` now always uses the `&` separator. + https://github.com/guzzle/guzzle/pull/1163 +* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. + https://github.com/guzzle/guzzle/pull/1189 + + +## 6.0.2 - 2015-07-04 + +* Fixed a memory leak in the curl handlers in which references to callbacks + were not being removed by `curl_reset`. +* Cookies are now extracted properly before redirects. +* Cookies now allow more character ranges. +* Decoded Content-Encoding responses are now modified to correctly reflect + their state if the encoding was automatically removed by a handler. This + means that the `Content-Encoding` header may be removed an the + `Content-Length` modified to reflect the message size after removing the + encoding. +* Added a more explicit error message when trying to use `form_params` and + `multipart` in the same request. +* Several fixes for HHVM support. +* Functions are now conditionally required using an additional level of + indirection to help with global Composer installations. + + +## 6.0.1 - 2015-05-27 + +* Fixed a bug with serializing the `query` request option where the `&` + separator was missing. +* Added a better error message for when `body` is provided as an array. Please + use `form_params` or `multipart` instead. +* Various doc fixes. + + +## 6.0.0 - 2015-05-26 + +* See the UPGRADING.md document for more information. +* Added `multipart` and `form_params` request options. +* Added `synchronous` request option. +* Added the `on_headers` request option. +* Fixed `expect` handling. +* No longer adding default middlewares in the client ctor. These need to be + present on the provided handler in order to work. +* Requests are no longer initiated when sending async requests with the + CurlMultiHandler. This prevents unexpected recursion from requests completing + while ticking the cURL loop. +* Removed the semantics of setting `default` to `true`. This is no longer + required now that the cURL loop is not ticked for async requests. +* Added request and response logging middleware. +* No longer allowing self signed certificates when using the StreamHandler. +* Ensuring that `sink` is valid if saving to a file. +* Request exceptions now include a "handler context" which provides handler + specific contextual information. +* Added `GuzzleHttp\RequestOptions` to allow request options to be applied + using constants. +* `$maxHandles` has been removed from CurlMultiHandler. +* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. + + +## 5.3.0 - 2015-05-19 + +* Mock now supports `save_to` +* Marked `AbstractRequestEvent::getTransaction()` as public. +* Fixed a bug in which multiple headers using different casing would overwrite + previous headers in the associative array. +* Added `Utils::getDefaultHandler()` +* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. +* URL scheme is now always lowercased. + + +## 6.0.0-beta.1 + +* Requires PHP >= 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See + https://datatracker.ietf.org/doc/html/rfc3986#appendix-A + + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: https://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on https://datatracker.ietf.org/doc/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/LICENSE b/php/libraries/composer/vendor/guzzlehttp/guzzle/LICENSE new file mode 100644 index 0000000..fd2375d --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2011 Michael Dowling +Copyright (c) 2012 Jeremy Lindblom +Copyright (c) 2014 Graham Campbell +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Tobias Schultze +Copyright (c) 2016 Tobias Nyholm +Copyright (c) 2016 George Mponos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/README.md b/php/libraries/composer/vendor/guzzlehttp/guzzle/README.md new file mode 100644 index 0000000..6d78a93 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/README.md @@ -0,0 +1,94 @@ +![Guzzle](.github/logo.png?raw=true) + +# Guzzle, PHP HTTP client + +[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases) +[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI) +[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle) + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +```php +$client = new \GuzzleHttp\Client(); +$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); + +echo $response->getStatusCode(); // 200 +echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' +echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' + +// Send an asynchronous request. +$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); +$promise = $client->sendAsync($request)->then(function ($response) { + echo 'I completed! ' . $response->getBody(); +}); + +$promise->wait(); +``` + +## Help and docs + +We use GitHub issues only to discuss bugs and new features. For support please refer to: + +- [Documentation](https://docs.guzzlephp.org) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle) +- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/) +- [Gitter](https://gitter.im/guzzle/guzzle) + + +## Installing Guzzle + +The recommended way to install Guzzle is through +[Composer](https://getcomposer.org/). + +```bash +composer require guzzlehttp/guzzle +``` + + +## Version Guidance + +| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | +|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------| +| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 | +| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 | +| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 | +| 6.x | Security fixes only | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 | +| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.4 | + +[guzzle-3-repo]: https://github.com/guzzle/guzzle3 +[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x +[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 +[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5 +[guzzle-7-repo]: https://github.com/guzzle/guzzle +[guzzle-3-docs]: https://guzzle3.readthedocs.io/ +[guzzle-5-docs]: https://docs.guzzlephp.org/en/5.3/ +[guzzle-6-docs]: https://docs.guzzlephp.org/en/6.5/ +[guzzle-7-docs]: https://docs.guzzlephp.org/en/latest/ + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/UPGRADING.md b/php/libraries/composer/vendor/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 0000000..4efbb59 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,1253 @@ +Guzzle Upgrade Guide +==================== + +6.0 to 7.0 +---------- + +In order to take advantage of the new features of PHP, Guzzle dropped the support +of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return +types for functions and methods have been added wherever possible. + +Please make sure: +- You are calling a function or a method with the correct type. +- If you extend a class of Guzzle; update all signatures on methods you override. + +#### Other backwards compatibility breaking changes + +- Class `GuzzleHttp\UriTemplate` is removed. +- Class `GuzzleHttp\Exception\SeekException` is removed. +- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`, + `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty + Response as argument. +- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException` + instead of `GuzzleHttp\Exception\RequestException`. +- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed. +- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed. +- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead. +- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed. + Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative. +- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed. +- Request option `exceptions` is removed. Please use `http_errors`. +- Request option `save_to` is removed. Please use `sink`. +- Pool option `pool_size` is removed. Please use `concurrency`. +- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility. +- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation. +- The `log` middleware will log the errors with level `error` instead of `notice` +- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher). + +#### Native functions calls + +All internal native functions calls of Guzzle are now prefixed with a slash. This +change makes it impossible for method overloading by other libraries or applications. +Example: + +```php +// Before: +curl_version(); + +// After: +\curl_version(); +``` + +For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..master). + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](https://docs.guzzlephp.org/en/latest/request-options.html#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](https://docs.guzzlephp.org/en/latest/request-options.html#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](https://ringphp.readthedocs.org/en/latest) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +See: https://docs.guzzlephp.org/en/latest/events.html + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- https://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- https://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/composer.json b/php/libraries/composer/vendor/guzzlehttp/guzzle/composer.json new file mode 100644 index 0000000..69583d7 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/composer.json @@ -0,0 +1,103 @@ +{ + "name": "guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "framework", + "http", + "rest", + "web service", + "curl", + "client", + "HTTP client", + "PSR-7", + "PSR-18" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.1", + "guzzlehttp/psr7": "^1.9.1 || ^2.5.1", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "bamarni/composer-bin-plugin": "^1.8.2", + "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.36 || ^9.6.15", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/BodySummarizer.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/BodySummarizer.php new file mode 100644 index 0000000..6eca94e --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/BodySummarizer.php @@ -0,0 +1,28 @@ +truncateAt = $truncateAt; + } + + /** + * Returns a summarized message body. + */ + public function summarize(MessageInterface $message): ?string + { + return $this->truncateAt === null + ? \GuzzleHttp\Psr7\Message::bodySummary($message) + : \GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php new file mode 100644 index 0000000..3e02e03 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php @@ -0,0 +1,13 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. + * If no handler is provided, a default handler will be created + * that enables all of the request options below by attaching all of the + * default middleware to the handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - **: any request option + * + * @param array $config Client configuration settings. + * + * @see \GuzzleHttp\RequestOptions for a list of available request options. + */ + public function __construct(array $config = []) + { + if (!isset($config['handler'])) { + $config['handler'] = HandlerStack::create(); + } elseif (!\is_callable($config['handler'])) { + throw new InvalidArgumentException('handler must be a callable'); + } + + // Convert the base_uri to a UriInterface + if (isset($config['base_uri'])) { + $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']); + } + + $this->configureDefaults($config); + } + + /** + * @param string $method + * @param array $args + * + * @return PromiseInterface|ResponseInterface + * + * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0. + */ + public function __call($method, $args) + { + if (\count($args) < 1) { + throw new InvalidArgumentException('Magic request methods require a URI and optional options array'); + } + + $uri = $args[0]; + $opts = $args[1] ?? []; + + return \substr($method, -5) === 'Async' + ? $this->requestAsync(\substr($method, 0, -5), $uri, $opts) + : $this->request($method, $uri, $opts); + } + + /** + * Asynchronously send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + */ + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface + { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), + $options + ); + } + + /** + * Send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * The HttpClient PSR (PSR-18) specify this method. + * + * {@inheritDoc} + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + $options[RequestOptions::ALLOW_REDIRECTS] = false; + $options[RequestOptions::HTTP_ERRORS] = false; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + */ + public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface + { + $options = $this->prepareDefaults($options); + // Remove request modifying parameter because it can be done up-front. + $headers = $options['headers'] ?? []; + $body = $options['body'] ?? null; + $version = $options['version'] ?? '1.1'; + // Merge the URI into the base URI. + $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options); + if (\is_array($body)) { + throw $this->invalidBody(); + } + $request = new Psr7\Request($method, $uri, $headers, $body, $version); + // Remove the option so that they are not doubly-applied. + unset($options['headers'], $options['body'], $options['version']); + + return $this->transfer($request, $options); + } + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function request(string $method, $uri = '', array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + + return $this->requestAsync($method, $uri, $options)->wait(); + } + + /** + * Get a client configuration option. + * + * These options include default request options of the client, a "handler" + * (if utilized by the concrete client), and a "base_uri" if utilized by + * the concrete client. + * + * @param string|null $option The config option to retrieve. + * + * @return mixed + * + * @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0. + */ + public function getConfig(string $option = null) + { + return $option === null + ? $this->config + : ($this->config[$option] ?? null); + } + + private function buildUri(UriInterface $uri, array $config): UriInterface + { + if (isset($config['base_uri'])) { + $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri); + } + + if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) { + $idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; + } + + /** + * Configures the default options for a client. + */ + private function configureDefaults(array $config): void + { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::$defaultSettings, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) { + $defaults['proxy']['http'] = $proxy; + } + + if ($proxy = Utils::getenv('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + if ($noProxy = Utils::getenv('NO_PROXY')) { + $cleanedNoProxy = \str_replace(' ', '', $noProxy); + $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy); + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()]; + } else { + // Add the User-Agent header if one was not already set. + foreach (\array_keys($this->config['headers']) as $name) { + if (\strtolower($name) === 'user-agent') { + return; + } + } + $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + */ + private function prepareDefaults(array $options): array + { + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (\array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = []; + unset($options['headers']); + } elseif (!\is_array($options['headers'])) { + throw new InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + return $result; + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param array $options See \GuzzleHttp\RequestOptions. + */ + private function transfer(RequestInterface $request, array $options): PromiseInterface + { + $request = $this->applyOptions($request, $options); + /** @var HandlerStack $handler */ + $handler = $options['handler']; + + try { + return P\Create::promiseFor($handler($request, $options)); + } catch (\Exception $e) { + return P\Create::rejectionFor($e); + } + } + + /** + * Applies the array of request options to a request. + */ + private function applyOptions(RequestInterface $request, array &$options): RequestInterface + { + $modify = [ + 'set_headers' => [], + ]; + + if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new InvalidArgumentException('The headers array must have header name as keys.'); + } + $modify['set_headers'] = $options['headers']; + unset($options['headers']); + } + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new InvalidArgumentException('You cannot use ' + .'form_params and multipart at the same time. Use the ' + .'form_params option if you want to send application/' + .'x-www-form-urlencoded requests, and the multipart ' + .'option to send multipart/form-data requests.'); + } + $options['body'] = \http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + $options['body'] = Utils::jsonEncode($options['json']); + unset($options['json']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (!empty($options['decode_content']) + && $options['decode_content'] !== true + ) { + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']); + $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; + } + + if (isset($options['body'])) { + if (\is_array($options['body'])) { + throw $this->invalidBody(); + } + $modify['body'] = Psr7\Utils::streamFor($options['body']); + unset($options['body']); + } + + if (!empty($options['auth']) && \is_array($options['auth'])) { + $value = $options['auth']; + $type = isset($value[2]) ? \strtolower($value[2]) : 'basic'; + switch ($type) { + case 'basic': + // Ensure that we don't have the header in different case and set the new value. + $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']); + $modify['set_headers']['Authorization'] = 'Basic ' + .\base64_encode("$value[0]:$value[1]"); + break; + case 'digest': + // @todo: Do not rely on curl + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + case 'ntlm': + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + } + } + + if (isset($options['query'])) { + $value = $options['query']; + if (\is_array($value)) { + $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986); + } + if (!\is_string($value)) { + throw new InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + // Ensure that sink is not an invalid value. + if (isset($options['sink'])) { + // TODO: Add more sink validation? + if (\is_bool($options['sink'])) { + throw new InvalidArgumentException('sink must not be a boolean'); + } + } + + if (isset($options['version'])) { + $modify['version'] = $options['version']; + } + + $request = Psr7\Utils::modifyRequest($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' + .$request->getBody()->getBoundary(); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + if (!$request->hasHeader($k)) { + $modify['set_headers'][$k] = $v; + } + } + $request = Psr7\Utils::modifyRequest($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + /** + * Return an InvalidArgumentException with pre-set message. + */ + private function invalidBody(): InvalidArgumentException + { + return new InvalidArgumentException('Passing in the "body" request ' + .'option as an array to send a request is not supported. ' + .'Please use the "form_params" request option to send a ' + .'application/x-www-form-urlencoded request, or the "multipart" ' + .'request option to send a multipart/form-data request.'); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 0000000..1788e16 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,84 @@ +request('GET', $uri, $options); + } + + /** + * Create and send an HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function head($uri, array $options = []): ResponseInterface + { + return $this->request('HEAD', $uri, $options); + } + + /** + * Create and send an HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function put($uri, array $options = []): ResponseInterface + { + return $this->request('PUT', $uri, $options); + } + + /** + * Create and send an HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function post($uri, array $options = []): ResponseInterface + { + return $this->request('POST', $uri, $options); + } + + /** + * Create and send an HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function patch($uri, array $options = []): ResponseInterface + { + return $this->request('PATCH', $uri, $options); + } + + /** + * Create and send an HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function delete($uri, array $options = []): ResponseInterface + { + return $this->request('DELETE', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; + + /** + * Create and send an asynchronous HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function getAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('GET', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function headAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('HEAD', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function putAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PUT', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function postAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('POST', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function patchAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PATCH', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function deleteAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('DELETE', $uri, $options); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php new file mode 100644 index 0000000..c29b4b7 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php @@ -0,0 +1,307 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!($cookie instanceof SetCookie)) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + */ + public static function fromArray(array $cookies, string $domain): self + { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true, + ])); + } + + return $cookieJar; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + */ + public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool + { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName(string $name): ?SetCookie + { + foreach ($this->cookies as $cookie) { + if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) { + return $cookie; + } + } + + return null; + } + + public function toArray(): array + { + return \array_map(static function (SetCookie $cookie): array { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + public function clear(string $domain = null, string $path = null, string $name = null): void + { + if (!$domain) { + $this->cookies = []; + + return; + } elseif (!$path) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($domain): bool { + return !$cookie->matchesDomain($domain); + } + ); + } elseif (!$name) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain): bool { + return !($cookie->matchesPath($path) + && $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain, $name) { + return !($cookie->getName() == $name + && $cookie->matchesPath($path) + && $cookie->matchesDomain($domain)); + } + ); + } + } + + public function clearSessionCookies(): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie): bool { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + public function setCookie(SetCookie $cookie): bool + { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: '.$result); + } + $this->removeCookieIfEmpty($cookie); + + return false; + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() != $cookie->getPath() + || $c->getDomain() != $cookie->getDomain() + || $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is + // not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then + // replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + public function count(): int + { + return \count($this->cookies); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator(\array_values($this->cookies)); + } + + public function extractCookies(RequestInterface $request, ResponseInterface $response): void + { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + foreach ($cookieHeader as $cookie) { + $sc = SetCookie::fromString($cookie); + if (!$sc->getDomain()) { + $sc->setDomain($request->getUri()->getHost()); + } + if (0 !== \strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + if (!$sc->matchesDomain($request->getUri()->getHost())) { + continue; + } + // Note: At this point `$sc->getDomain()` being a public suffix should + // be rejected, but we don't want to pull in the full PSL dependency. + $this->setCookie($sc); + } + } + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4 + */ + private function getCookiePathFromRequest(RequestInterface $request): string + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== \strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + $lastSlashPos = \strrpos($uriPath, '/'); + if (0 === $lastSlashPos || false === $lastSlashPos) { + return '/'; + } + + return \substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader(RequestInterface $request): RequestInterface + { + $values = []; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = $uri->getHost(); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->matchesPath($path) + && $cookie->matchesDomain($host) + && !$cookie->isExpired() + && (!$cookie->getSecure() || $scheme === 'https') + ) { + $values[] = $cookie->getName().'=' + .$cookie->getValue(); + } + } + + return $values + ? $request->withHeader('Cookie', \implode('; ', $values)) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + */ + private function removeCookieIfEmpty(SetCookie $cookie): void + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->clear( + $cookie->getDomain(), + $cookie->getPath(), + $cookie->getName() + ); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 0000000..8c55cc6 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,80 @@ + + */ +interface CookieJarInterface extends \Countable, \IteratorAggregate +{ + /** + * Create a request with added cookie headers. + * + * If no matching cookies are found in the cookie jar, then no Cookie + * header is added to the request and the same request is returned. + * + * @param RequestInterface $request Request object to modify. + * + * @return RequestInterface returns the modified request. + */ + public function withCookieHeader(RequestInterface $request): RequestInterface; + + /** + * Extract cookies from an HTTP response and store them in the CookieJar. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + */ + public function extractCookies(RequestInterface $request, ResponseInterface $response): void; + + /** + * Sets a cookie in the cookie jar. + * + * @param SetCookie $cookie Cookie to set. + * + * @return bool Returns true on success or false on failure + */ + public function setCookie(SetCookie $cookie): bool; + + /** + * Remove cookies currently held in the cookie jar. + * + * Invoking this method without arguments will empty the whole cookie jar. + * If given a $domain argument only cookies belonging to that domain will + * be removed. If given a $domain and $path argument, cookies belonging to + * the specified path within that domain are removed. If given all three + * arguments, then the cookie with the specified name, path and domain is + * removed. + * + * @param string|null $domain Clears cookies matching a domain + * @param string|null $path Clears cookies matching a domain and path + * @param string|null $name Clears cookies matching a domain, path, and name + */ + public function clear(string $domain = null, string $path = null, string $name = null): void; + + /** + * Discard all sessions cookies. + * + * Removes cookies that don't have an expire field or a have a discard + * field set to true. To be called when the user agent shuts down according + * to RFC 2965. + */ + public function clearSessionCookies(): void; + + /** + * Converts the cookie jar to an array. + */ + public function toArray(): array; +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php new file mode 100644 index 0000000..290236d --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php @@ -0,0 +1,101 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (\file_exists($cookieFile)) { + $this->load($cookieFile); + } + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->save($this->filename); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * + * @throws \RuntimeException if the file cannot be found or created + */ + public function save(string $filename): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $jsonStr = Utils::jsonEncode($json); + if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { + throw new \RuntimeException("Unable to save file {$filename}"); + } + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * + * @param string $filename Cookie file to load. + * + * @throws \RuntimeException if the file cannot be loaded. + */ + public function load(string $filename): void + { + $json = \file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException("Unable to load file {$filename}"); + } + if ($json === '') { + return; + } + + $data = Utils::jsonDecode($json, true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\is_scalar($data) && !empty($data)) { + throw new \RuntimeException("Invalid cookie file: {$filename}"); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 0000000..cb3e67c --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,77 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + $this->save(); + } + + /** + * Save cookies to the client session + */ + public function save(): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $_SESSION[$this->sessionKey] = \json_encode($json); + } + + /** + * Load the contents of the client session into the data array + */ + protected function load(): void + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + $data = \json_decode($_SESSION[$this->sessionKey], true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\strlen($data)) { + throw new \RuntimeException('Invalid cookie data'); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 0000000..c9806da --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,488 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false, + ]; + + /** + * @var array Cookie data + */ + private $data; + + /** + * Create a new SetCookie object from a string. + * + * @param string $cookie Set-Cookie header string + */ + public static function fromString(string $cookie): self + { + // Create the default return array + $data = self::$defaults; + // Explode the cookie string using a series of semicolons + $pieces = \array_filter(\array_map('trim', \explode(';', $cookie))); + // The name of the cookie (first kvp) must exist and include an equal sign. + if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + $cookieParts = \explode('=', $part, 2); + $key = \trim($cookieParts[0]); + $value = isset($cookieParts[1]) + ? \trim($cookieParts[1], " \n\r\t\0\x0B") + : true; + + // Only check for non-cookies when cookies have been found + if (!isset($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (\array_keys(self::$defaults) as $search) { + if (!\strcasecmp($search, $key)) { + if ($search === 'Max-Age') { + if (is_numeric($value)) { + $data[$search] = (int) $value; + } + } else { + $data[$search] = $value; + } + continue 2; + } + } + $data[$key] = $value; + } + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct(array $data = []) + { + $this->data = self::$defaults; + + if (isset($data['Name'])) { + $this->setName($data['Name']); + } + + if (isset($data['Value'])) { + $this->setValue($data['Value']); + } + + if (isset($data['Domain'])) { + $this->setDomain($data['Domain']); + } + + if (isset($data['Path'])) { + $this->setPath($data['Path']); + } + + if (isset($data['Max-Age'])) { + $this->setMaxAge($data['Max-Age']); + } + + if (isset($data['Expires'])) { + $this->setExpires($data['Expires']); + } + + if (isset($data['Secure'])) { + $this->setSecure($data['Secure']); + } + + if (isset($data['Discard'])) { + $this->setDiscard($data['Discard']); + } + + if (isset($data['HttpOnly'])) { + $this->setHttpOnly($data['HttpOnly']); + } + + // Set the remaining values that don't have extra validation logic + foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) { + $this->data[$key] = $data[$key]; + } + + // Extract the Expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the Expires date + $this->setExpires(\time() + $this->getMaxAge()); + } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) { + $this->setExpires($expires); + } + } + + public function __toString() + { + $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; '; + foreach ($this->data as $k => $v) { + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}").'; '; + } + } + } + + return \rtrim($str, '; '); + } + + public function toArray(): array + { + return $this->data; + } + + /** + * Get the cookie name. + * + * @return string + */ + public function getName() + { + return $this->data['Name']; + } + + /** + * Set the cookie name. + * + * @param string $name Cookie name + */ + public function setName($name): void + { + if (!is_string($name)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Name'] = (string) $name; + } + + /** + * Get the cookie value. + * + * @return string|null + */ + public function getValue() + { + return $this->data['Value']; + } + + /** + * Set the cookie value. + * + * @param string $value Cookie value + */ + public function setValue($value): void + { + if (!is_string($value)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Value'] = (string) $value; + } + + /** + * Get the domain. + * + * @return string|null + */ + public function getDomain() + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie. + * + * @param string|null $domain + */ + public function setDomain($domain): void + { + if (!is_string($domain) && null !== $domain) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Domain'] = null === $domain ? null : (string) $domain; + } + + /** + * Get the path. + * + * @return string + */ + public function getPath() + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie. + * + * @param string $path Path of the cookie + */ + public function setPath($path): void + { + if (!is_string($path)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Path'] = (string) $path; + } + + /** + * Maximum lifetime of the cookie in seconds. + * + * @return int|null + */ + public function getMaxAge() + { + return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie. + * + * @param int|null $maxAge Max age of the cookie in seconds + */ + public function setMaxAge($maxAge): void + { + if (!is_int($maxAge) && null !== $maxAge) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires. + * + * @return string|int|null + */ + public function getExpires() + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire. + * + * @param int|string|null $timestamp Unix timestamp or any English textual datetime description. + */ + public function setExpires($timestamp): void + { + if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp)); + } + + /** + * Get whether or not this is a secure cookie. + * + * @return bool + */ + public function getSecure() + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure. + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure($secure): void + { + if (!is_bool($secure)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Secure'] = (bool) $secure; + } + + /** + * Get whether or not this is a session cookie. + * + * @return bool|null + */ + public function getDiscard() + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie. + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard($discard): void + { + if (!is_bool($discard)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Discard'] = (bool) $discard; + } + + /** + * Get whether or not this is an HTTP only cookie. + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie. + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly($httpOnly): void + { + if (!is_bool($httpOnly)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['HttpOnly'] = (bool) $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + */ + public function matchesPath(string $requestPath): bool + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath == $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== \strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (\substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return \substr($requestPath, \strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value. + * + * @param string $domain Domain to check against + */ + public function matchesDomain(string $domain): bool + { + $cookieDomain = $this->getDomain(); + if (null === $cookieDomain) { + return true; + } + + // Remove the leading '.' as per spec in RFC 6265. + // https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3 + $cookieDomain = \ltrim(\strtolower($cookieDomain), '.'); + + $domain = \strtolower($domain); + + // Domain not set or exact match. + if ('' === $cookieDomain || $domain === $cookieDomain) { + return true; + } + + // Matching the subdomain according to RFC 6265. + // https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3 + if (\filter_var($domain, \FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain); + } + + /** + * Check if the cookie is expired. + */ + public function isExpired(): bool + { + return $this->getExpires() !== null && \time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265. + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + $name = $this->getName(); + if ($name === '') { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (\preg_match( + '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', + $name + )) { + return 'Cookie name must not contain invalid characters: ASCII ' + .'Control characters (0-31;127), space, tab and the ' + .'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be null. 0 and empty string are valid. Empty strings + // are technically against RFC 6265, but known to happen in the wild. + $value = $this->getValue(); + if ($value === null) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0. "0" is not a valid internet + // domain, but may be used as server name in a private network. + $domain = $this->getDomain(); + if ($domain === null || $domain === '') { + return 'The cookie domain must not be empty'; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php new file mode 100644 index 0000000..a80956c --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php @@ -0,0 +1,39 @@ +request = $request; + $this->handlerContext = $handlerContext; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php new file mode 100644 index 0000000..fa3ed69 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php @@ -0,0 +1,9 @@ +getStatusCode() : 0; + parent::__construct($message, $code, $previous); + $this->request = $request; + $this->response = $response; + $this->handlerContext = $handlerContext; + } + + /** + * Wrap non-RequestExceptions with a RequestException + */ + public static function wrapException(RequestInterface $request, \Throwable $e): RequestException + { + return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e); + } + + /** + * Factory method to create a new exception with a normalized error message + * + * @param RequestInterface $request Request sent + * @param ResponseInterface $response Response received + * @param \Throwable|null $previous Previous exception + * @param array $handlerContext Optional handler context + * @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer + */ + public static function create( + RequestInterface $request, + ResponseInterface $response = null, + \Throwable $previous = null, + array $handlerContext = [], + BodySummarizerInterface $bodySummarizer = null + ): self { + if (!$response) { + return new self( + 'Error completing request', + $request, + null, + $previous, + $handlerContext + ); + } + + $level = (int) \floor($response->getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + $className = ClientException::class; + } elseif ($level === 5) { + $label = 'Server error'; + $className = ServerException::class; + } else { + $label = 'Unsuccessful request'; + $className = __CLASS__; + } + + $uri = $request->getUri(); + $uri = static::obfuscateUri($uri); + + // Client Error: `GET /` resulted in a `404 Not Found` response: + // ... (truncated) + $message = \sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + $request->getMethod(), + $uri->__toString(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + $summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response); + + if ($summary !== null) { + $message .= ":\n{$summary}\n"; + } + + return new $className($message, $request, $response, $previous, $handlerContext); + } + + /** + * Obfuscates URI if there is a username and a password present + */ + private static function obfuscateUri(UriInterface $uri): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = \strpos($userInfo, ':'))) { + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get the associated response + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Check if a response was received + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php new file mode 100644 index 0000000..8055e06 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php @@ -0,0 +1,10 @@ +maxHandles = $maxHandles; + } + + public function create(RequestInterface $request, array $options): EasyHandle + { + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + $easy = new EasyHandle(); + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = \array_replace($conf, $options['curl']); + } + + $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); + curl_setopt_array($easy->handle, $conf); + + return $easy; + } + + public function release(EasyHandle $easy): void + { + $resource = $easy->handle; + unset($easy->handle); + + if (\count($this->handles) >= $this->maxHandles) { + \curl_close($resource); + } else { + // Remove all callback functions as they can hold onto references + // and are not cleaned up by curl_reset. Using curl_setopt_array + // does not work for some reason, so removing each one + // individually. + \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); + \curl_setopt($resource, \CURLOPT_READFUNCTION, null); + \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); + \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); + \curl_reset($resource); + $this->handles[] = $resource; + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param CurlFactoryInterface $factory Dictates how the handle is released + */ + public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + if (isset($easy->options['on_stats'])) { + self::invokeStats($easy); + } + + if (!$easy->response || $easy->errno) { + return self::finishError($handler, $easy, $factory); + } + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. + $body = $easy->response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + return new FulfilledPromise($easy->response); + } + + private static function invokeStats(EasyHandle $easy): void + { + $curlStats = \curl_getinfo($easy->handle); + $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); + $stats = new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $easy->errno, + $curlStats + ); + ($easy->options['on_stats'])($stats); + } + + /** + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + // Get error information and release the handle to the factory. + $ctx = [ + 'errno' => $easy->errno, + 'error' => \curl_error($easy->handle), + 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME), + ] + \curl_getinfo($easy->handle); + $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; + $factory->release($easy); + + // Retry when nothing is present or when curl failed to rewind. + if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { + return self::retryFailedRewind($handler, $easy, $ctx); + } + + return self::createRejection($easy, $ctx); + } + + private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface + { + static $connectionErrors = [ + \CURLE_OPERATION_TIMEOUTED => true, + \CURLE_COULDNT_RESOLVE_HOST => true, + \CURLE_COULDNT_CONNECT => true, + \CURLE_SSL_CONNECT_ERROR => true, + \CURLE_GOT_NOTHING => true, + ]; + + if ($easy->createResponseException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered while creating the response', + $easy->request, + $easy->response, + $easy->createResponseException, + $ctx + ) + ); + } + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered during the on_headers event', + $easy->request, + $easy->response, + $easy->onHeadersException, + $ctx + ) + ); + } + + $message = \sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $ctx['error'], + 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' + ); + $uriString = (string) $easy->request->getUri(); + if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) { + $message .= \sprintf(' for %s', $uriString); + } + + // Create a connection exception if it was a specific error code. + $error = isset($connectionErrors[$easy->errno]) + ? new ConnectException($message, $easy->request, null, $ctx) + : new RequestException($message, $easy->request, $easy->response, null, $ctx); + + return P\Create::rejectionFor($error); + } + + /** + * @return array + */ + private function getDefaultConf(EasyHandle $easy): array + { + $conf = [ + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + \CURLOPT_RETURNTRANSFER => false, + \CURLOPT_HEADER => false, + \CURLOPT_CONNECTTIMEOUT => 300, + ]; + + if (\defined('CURLOPT_PROTOCOLS')) { + $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; + } + + $version = $easy->request->getProtocolVersion(); + if ($version == 1.1) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } elseif ($version == 2.0) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; + } else { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; + } + + return $conf; + } + + private function applyMethod(EasyHandle $easy, array &$conf): void + { + $body = $easy->request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size > 0) { + $this->applyBody($easy->request, $easy->options, $conf); + + return; + } + + $method = $easy->request->getMethod(); + if ($method === 'PUT' || $method === 'POST') { + // See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2 + if (!$easy->request->hasHeader('Content-Length')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; + } + } elseif ($method === 'HEAD') { + $conf[\CURLOPT_NOBODY] = true; + unset( + $conf[\CURLOPT_WRITEFUNCTION], + $conf[\CURLOPT_READFUNCTION], + $conf[\CURLOPT_FILE], + $conf[\CURLOPT_INFILE] + ); + } + } + + private function applyBody(RequestInterface $request, array $options, array &$conf): void + { + $size = $request->hasHeader('Content-Length') + ? (int) $request->getHeaderLine('Content-Length') + : null; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) { + $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[\CURLOPT_UPLOAD] = true; + if ($size !== null) { + $conf[\CURLOPT_INFILESIZE] = $size; + $this->removeHeader('Content-Length', $conf); + } + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { + return $body->read($length); + }; + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private function applyHeaders(EasyHandle $easy, array &$conf): void + { + foreach ($conf['_headers'] as $name => $values) { + foreach ($values as $value) { + $value = (string) $value; + if ($value === '') { + // cURL requires a special format for empty headers. + // See https://github.com/guzzle/guzzle/issues/1882 for more details. + $conf[\CURLOPT_HTTPHEADER][] = "$name;"; + } else { + $conf[\CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader(string $name, array &$options): void + { + foreach (\array_keys($options['_headers']) as $key) { + if (!\strcasecmp($key, $name)) { + unset($options['_headers'][$key]); + + return; + } + } + } + + private function applyHandlerOptions(EasyHandle $easy, array &$conf): void + { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[\CURLOPT_CAINFO]); + $conf[\CURLOPT_SSL_VERIFYHOST] = 0; + $conf[\CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[\CURLOPT_SSL_VERIFYHOST] = 2; + $conf[\CURLOPT_SSL_VERIFYPEER] = true; + if (\is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!\file_exists($options['verify'])) { + throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}"); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if ( + \is_dir($options['verify']) + || ( + \is_link($options['verify']) === true + && ($verifyLink = \readlink($options['verify'])) !== false + && \is_dir($verifyLink) + ) + ) { + $conf[\CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[\CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept) { + $conf[\CURLOPT_ENCODING] = $accept; + } else { + // The empty string enables all available decoders and implicitly + // sets a matching 'Accept-Encoding' header. + $conf[\CURLOPT_ENCODING] = ''; + // But as the user did not specify any acceptable encodings we need + // to overwrite this implicit header with an empty one. + $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + if (!isset($options['sink'])) { + // Use a default temp stream if no sink was set. + $options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+'); + } + $sink = $options['sink']; + if (!\is_string($sink)) { + $sink = \GuzzleHttp\Psr7\Utils::streamFor($sink); + } elseif (!\is_dir(\dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink)); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int { + return $sink->write($write); + }; + + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeoutRequiresNoSignal |= $options['timeout'] < 1; + $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; + } elseif ('v6' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; + } + + if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') { + $conf[\CURLOPT_NOSIGNAL] = true; + } + + if (isset($options['proxy'])) { + if (!\is_array($options['proxy'])) { + $conf[\CURLOPT_PROXY] = $options['proxy']; + } else { + $scheme = $easy->request->getUri()->getScheme(); + if (isset($options['proxy'][$scheme])) { + $host = $easy->request->getUri()->getHost(); + if (isset($options['proxy']['no']) && Utils::isHostInNoProxy($host, $options['proxy']['no'])) { + unset($conf[\CURLOPT_PROXY]); + } else { + $conf[\CURLOPT_PROXY] = $options['proxy'][$scheme]; + } + } + } + } + + if (isset($options['crypto_method'])) { + if (\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_0')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.0 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_0; + } elseif (\STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_1')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.1 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_1; + } elseif (\STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_2')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2; + } elseif (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_3')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3; + } else { + throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); + } + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (\is_array($cert)) { + $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; + } + if (!\file_exists($cert)) { + throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); + } + // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + $ext = pathinfo($cert, \PATHINFO_EXTENSION); + if (preg_match('#^(der|p12)$#i', $ext)) { + $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext); + } + $conf[\CURLOPT_SSLCERT] = $cert; + } + + if (isset($options['ssl_key'])) { + if (\is_array($options['ssl_key'])) { + if (\count($options['ssl_key']) === 2) { + [$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key']; + } else { + [$sslKey] = $options['ssl_key']; + } + } + + $sslKey = $sslKey ?? $options['ssl_key']; + + if (!\file_exists($sslKey)) { + throw new \InvalidArgumentException("SSL private key not found: {$sslKey}"); + } + $conf[\CURLOPT_SSLKEY] = $sslKey; + } + + if (isset($options['progress'])) { + $progress = $options['progress']; + if (!\is_callable($progress)) { + throw new \InvalidArgumentException('progress client option must be callable'); + } + $conf[\CURLOPT_NOPROGRESS] = false; + $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) { + $progress($downloadSize, $downloaded, $uploadSize, $uploaded); + }; + } + + if (!empty($options['debug'])) { + $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']); + $conf[\CURLOPT_VERBOSE] = true; + } + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface + { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\RuntimeException $e) { + $ctx['error'] = 'The connection unexpectedly failed without ' + .'providing an error. The request would have been retried, ' + .'but attempting to rewind the request body failed. ' + .'Exception: '.$e; + + return self::createRejection($easy, $ctx); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + .'and did not succeed. The most likely reason for the failure ' + .'is that cURL was unable to rewind the body of the request ' + .'and subsequent retries resulted in the same error. Turn on ' + .'the debug option to see what went wrong. See ' + .'https://bugs.php.net/bug.php?id=47204 for more information.'; + + return self::createRejection($easy, $ctx); + } else { + ++$easy->options['_curl_retries']; + } + + return $handler($easy->request, $easy->options); + } + + private function createHeaderFn(EasyHandle $easy): callable + { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!\is_callable($onHeaders)) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + return static function ($ch, $h) use ( + $onHeaders, + $easy, + &$startingResponse + ) { + $value = \trim($h); + if ($value === '') { + $startingResponse = true; + try { + $easy->createResponse(); + } catch (\Exception $e) { + $easy->createResponseException = $e; + + return -1; + } + if ($onHeaders !== null) { + try { + $onHeaders($easy->response); + } catch (\Exception $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + + return -1; + } + } + } elseif ($startingResponse) { + $startingResponse = false; + $easy->headers = [$value]; + } else { + $easy->headers[] = $value; + } + + return \strlen($h); + }; + } + + public function __destruct() + { + foreach ($this->handles as $id => $handle) { + \curl_close($handle); + unset($this->handles[$id]); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 0000000..fe57ed5 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,25 @@ +factory = $options['handle_factory'] + ?? new CurlFactory(3); + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (isset($options['delay'])) { + \usleep($options['delay'] * 1000); + } + + $easy = $this->factory->create($request, $options); + \curl_exec($easy->handle); + $easy->errno = \curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 0000000..a64e182 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,267 @@ + An array of delay times, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private $delays = []; + + /** + * @var array An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() + */ + private $options = []; + + /** @var resource|\CurlMultiHandle */ + private $_mh; + + /** + * This handler accepts the following options: + * + * - handle_factory: An optional factory used to create curl handles + * - select_timeout: Optional timeout (in seconds) to block before timing + * out while selecting curl handles. Defaults to 1 second. + * - options: An associative array of CURLMOPT_* options and + * corresponding values for curl_multi_setopt() + */ + public function __construct(array $options = []) + { + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); + + if (isset($options['select_timeout'])) { + $this->selectTimeout = $options['select_timeout']; + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { + @trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); + $this->selectTimeout = (int) $selectTimeout; + } else { + $this->selectTimeout = 1; + } + + $this->options = $options['options'] ?? []; + + // unsetting the property forces the first access to go through + // __get(). + unset($this->_mh); + } + + /** + * @param string $name + * + * @return resource|\CurlMultiHandle + * + * @throws \BadMethodCallException when another field as `_mh` will be gotten + * @throws \RuntimeException when curl can not initialize a multi handle + */ + public function __get($name) + { + if ($name !== '_mh') { + throw new \BadMethodCallException("Can not get other property as '_mh'."); + } + + $multiHandle = \curl_multi_init(); + + if (false === $multiHandle) { + throw new \RuntimeException('Can not initialize curl multi handle.'); + } + + $this->_mh = $multiHandle; + + foreach ($this->options as $option => $value) { + // A warning is raised in case of a wrong option. + curl_multi_setopt($this->_mh, $option, $value); + } + + return $this->_mh; + } + + public function __destruct() + { + if (isset($this->_mh)) { + \curl_multi_close($this->_mh); + unset($this->_mh); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $easy = $this->factory->create($request, $options); + $id = (int) $easy->handle; + + $promise = new Promise( + [$this, 'execute'], + function () use ($id) { + return $this->cancel($id); + } + ); + + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); + + return $promise; + } + + /** + * Ticks the curl event loop. + */ + public function tick(): void + { + // Add any delayed handles if needed. + if ($this->delays) { + $currentTime = Utils::currentTime(); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + unset($this->delays[$id]); + \curl_multi_add_handle( + $this->_mh, + $this->handles[$id]['easy']->handle + ); + } + } + } + + // Step through the task queue which may add additional requests. + P\Utils::queue()->run(); + + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + \usleep(250); + } + + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { + } + + $this->processMessages(); + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute(): void + { + $queue = P\Utils::queue(); + + while ($this->handles || !$queue->isEmpty()) { + // If there are no transfers, then sleep for the next delay + if (!$this->active && $this->delays) { + \usleep($this->timeToNext()); + } + $this->tick(); + } + } + + private function addRequest(array $entry): void + { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $this->handles[$id] = $entry; + if (empty($easy->options['delay'])) { + \curl_multi_add_handle($this->_mh, $easy->handle); + } else { + $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * + * @return bool True on success, false on failure. + */ + private function cancel($id): bool + { + if (!is_int($id)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + // Cannot cancel if it has been processed. + if (!isset($this->handles[$id])) { + return false; + } + + $handle = $this->handles[$id]['easy']->handle; + unset($this->delays[$id], $this->handles[$id]); + \curl_multi_remove_handle($this->_mh, $handle); + \curl_close($handle); + + return true; + } + + private function processMessages(): void + { + while ($done = \curl_multi_info_read($this->_mh)) { + if ($done['msg'] !== \CURLMSG_DONE) { + // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 + continue; + } + $id = (int) $done['handle']; + \curl_multi_remove_handle($this->_mh, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + $entry['deferred']->resolve( + CurlFactory::finish($this, $entry['easy'], $this->factory) + ); + } + } + + private function timeToNext(): int + { + $currentTime = Utils::currentTime(); + $nextTime = \PHP_INT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return ((int) \max(0, $nextTime - $currentTime)) * 1000000; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 0000000..1bc39f4 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,112 @@ +headers); + + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + + if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + + $bodyLength = (int) $this->sink->getSize(); + if ($bodyLength) { + $headers[$normalizedKeys['content-length']] = $bodyLength; + } else { + unset($headers[$normalizedKeys['content-length']]); + } + } + } + + // Attach a response to the easy handle with the parsed headers. + $this->response = new Response( + $status, + $headers, + $this->sink, + $ver, + $reason + ); + } + + /** + * @param string $name + * + * @return void + * + * @throws \BadMethodCallException + */ + public function __get($name) + { + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name; + throw new \BadMethodCallException($msg); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php new file mode 100644 index 0000000..5554b8f --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php @@ -0,0 +1,42 @@ +|null $queue The parameters to be passed to the append function, as an indexed array. + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param callable|null $onRejected Callback to invoke when the return value is rejected. + */ + public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) + { + $this->onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + // array_values included for BC + $this->append(...array_values($queue)); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay']) && \is_numeric($options['delay'])) { + \usleep((int) $options['delay'] * 1000); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = \array_shift($this->queue); + + if (isset($options['on_headers'])) { + if (!\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $response = new RequestException($msg, $request, $response, $e); + } + } + + if (\is_callable($response)) { + $response = $response($request, $options); + } + + $response = $response instanceof \Throwable + ? P\Create::rejectionFor($response) + : P\Create::promiseFor($response); + + return $response->then( + function (?ResponseInterface $value) use ($request, $options) { + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + ($this->onFulfilled)($value); + } + + if ($value !== null && isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (\is_resource($sink)) { + \fwrite($sink, $contents); + } elseif (\is_string($sink)) { + \file_put_contents($sink, $contents); + } elseif ($sink instanceof StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ($reason) use ($request, $options) { + $this->invokeStats($request, $options, null, $reason); + if ($this->onRejected) { + ($this->onRejected)($reason); + } + + return P\Create::rejectionFor($reason); + } + ); + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + * + * @param mixed ...$values + */ + public function append(...$values): void + { + foreach ($values as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Throwable + || $value instanceof PromiseInterface + || \is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value)); + } + } + } + + /** + * Get the last received request. + */ + public function getLastRequest(): ?RequestInterface + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + */ + public function getLastOptions(): array + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + */ + public function count(): int + { + return \count($this->queue); + } + + public function reset(): void + { + $this->queue = []; + } + + /** + * @param mixed $reason Promise or reason. + */ + private function invokeStats( + RequestInterface $request, + array $options, + ResponseInterface $response = null, + $reason = null + ): void { + if (isset($options['on_stats'])) { + $transferTime = $options['transfer_time'] ?? 0; + $stats = new TransferStats($request, $response, $transferTime, $reason); + ($options['on_stats'])($stats); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php new file mode 100644 index 0000000..f045b52 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php @@ -0,0 +1,51 @@ +withoutHeader('Expect'); + + // Append a content-length header if body size is zero to match + // cURL's behavior. + if (0 === $request->getBody()->getSize()) { + $request = $request->withHeader('Content-Length', '0'); + } + + return $this->createResponse( + $request, + $options, + $this->createStream($request, $options), + $startTime + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + // Determine if the error was a networking error. + $message = $e->getMessage(); + // This list can probably get more comprehensive. + if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed + || false !== \strpos($message, 'Connection refused') + || false !== \strpos($message, "couldn't connect to host") // error on HHVM + || false !== \strpos($message, 'connection attempt failed') + ) { + $e = new ConnectException($e->getMessage(), $request, $e); + } else { + $e = RequestException::wrapException($request, $e); + } + $this->invokeStats($options, $request, $startTime, null, $e); + + return P\Create::rejectionFor($e); + } + } + + private function invokeStats( + array $options, + RequestInterface $request, + ?float $startTime, + ResponseInterface $response = null, + \Throwable $error = null + ): void { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); + ($options['on_stats'])($stats); + } + } + + /** + * @param resource $stream + */ + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface + { + $hdrs = $this->lastHeaders; + $this->lastHeaders = []; + + try { + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); + $stream = Psr7\Utils::streamFor($stream); + $sink = $stream; + + if (\strcasecmp('HEAD', $request->getMethod())) { + $sink = $this->createSink($stream, $options); + } + + try { + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered during the on_headers event', $request, $response, $e) + ); + } + } + + // Do not drain when the request is a HEAD request because they have + // no body. + if ($sink !== $stream) { + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + return new FulfilledPromise($response); + } + + private function createSink(StreamInterface $stream, array $options): StreamInterface + { + if (!empty($options['stream'])) { + return $stream; + } + + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); + + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); + } + + /** + * @param resource $stream + */ + private function checkDecode(array $options, array $headers, $stream): array + { + // Automatically decode responses when instructed. + if (!empty($options['decode_content'])) { + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + + // Fix content-length header + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + $length = (int) $stream->getSize(); + if ($length === 0) { + unset($headers[$normalizedKeys['content-length']]); + } else { + $headers[$normalizedKeys['content-length']] = [$length]; + } + } + } + } + } + + return [$stream, $headers]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @param string $contentLength Header specifying the amount of + * data to read. + * + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface + { + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not honor + // Connection: Close headers. + Psr7\Utils::copyToStream( + $source, + $sink, + (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 + ); + + $sink->seek(0); + $source->close(); + + return $sink; + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Callable that returns stream resource + * + * @return resource + * + * @throws \RuntimeException on error + */ + private function createResource(callable $callback) + { + $errors = []; + \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { + $errors[] = [ + 'message' => $msg, + 'file' => $file, + 'line' => $line, + ]; + + return true; + }); + + try { + $resource = $callback(); + } finally { + \restore_error_handler(); + } + + if (!$resource) { + $message = 'Error creating resource: '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value".\PHP_EOL; + } + } + throw new \RuntimeException(\trim($message)); + } + + return $resource; + } + + /** + * @return resource + */ + private function createStream(RequestInterface $request, array $options) + { + static $methods; + if (!$methods) { + $methods = \array_flip(\get_class_methods(__CLASS__)); + } + + if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { + throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); + } + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() == '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request); + + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + + if (!empty($options)) { + foreach ($options as $key => $value) { + $method = "add_{$key}"; + if (isset($methods[$method])) { + $this->{$method}($request, $context, $value, $params); + } + } + } + + if (isset($options['stream_context'])) { + if (!\is_array($options['stream_context'])) { + throw new \InvalidArgumentException('stream_context must be an array'); + } + $context = \array_replace_recursive($context, $options['stream_context']); + } + + // Microsoft NTLM authentication only supported with curl handler + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); + } + + $uri = $this->resolveHost($request, $options); + + $contextResource = $this->createResource( + static function () use ($context, $params) { + return \stream_context_create($context, $params); + } + ); + + return $this->createResource( + function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { + $resource = @\fopen((string) $uri, 'r', false, $contextResource); + $this->lastHeaders = $http_response_header ?? []; + + if (false === $resource) { + throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); + } + + if (isset($options['read_timeout'])) { + $readTimeout = $options['read_timeout']; + $sec = (int) $readTimeout; + $usec = ($readTimeout - $sec) * 100000; + \stream_set_timeout($resource, $sec, $usec); + } + + return $resource; + } + ); + } + + private function resolveHost(RequestInterface $request, array $options): UriInterface + { + $uri = $request->getUri(); + + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_A); + if (false === $records || !isset($records[0]['ip'])) { + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); + } + + return $uri->withHost($records[0]['ip']); + } + if ('v6' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); + if (false === $records || !isset($records[0]['ipv6'])) { + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); + } + + return $uri->withHost('['.$records[0]['ipv6'].']'); + } + } + + return $uri; + } + + private function getDefaultContext(RequestInterface $request): array + { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + foreach ($value as $val) { + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + 'ssl' => [ + 'peer_name' => $request->getUri()->getHost(), + ], + ]; + + $body = (string) $request->getBody(); + + if ('' !== $body) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = \rtrim($context['http']['header']); + + return $context; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void + { + $uri = null; + + if (!\is_array($value)) { + $uri = $value; + } else { + $scheme = $request->getUri()->getScheme(); + if (isset($value[$scheme])) { + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { + $uri = $value[$scheme]; + } + } + } + + if (!$uri) { + return; + } + + $parsed = $this->parse_proxy($uri); + $options['http']['proxy'] = $parsed['proxy']; + + if ($parsed['auth']) { + if (!isset($options['http']['header'])) { + $options['http']['header'] = []; + } + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; + } + } + + /** + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. + */ + private function parse_proxy(string $url): array + { + $parsed = \parse_url($url); + + if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { + if (isset($parsed['host']) && isset($parsed['port'])) { + $auth = null; + if (isset($parsed['user']) && isset($parsed['pass'])) { + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); + } + + return [ + 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", + 'auth' => $auth ? "Basic {$auth}" : null, + ]; + } + } + + // Return proxy as-is. + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value > 0) { + $options['http']['timeout'] = $value; + } + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void + { + if ( + $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT + || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT + || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) + ) { + $options['http']['crypto_method'] = $value; + + return; + } + + throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + $options['ssl']['verify_peer'] = false; + $options['ssl']['verify_peer_name'] = false; + + return; + } + + if (\is_string($value)) { + $options['ssl']['cafile'] = $value; + if (!\file_exists($value)) { + throw new \RuntimeException("SSL CA bundle not found: $value"); + } + } elseif ($value !== true) { + throw new \InvalidArgumentException('Invalid verify request option'); + } + + $options['ssl']['verify_peer'] = true; + $options['ssl']['verify_peer_name'] = true; + $options['ssl']['allow_self_signed'] = false; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void + { + if (\is_array($value)) { + $options['ssl']['passphrase'] = $value[1]; + $value = $value[0]; + } + + if (!\file_exists($value)) { + throw new \RuntimeException("SSL certificate not found: {$value}"); + } + + $options['ssl']['local_cert'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void + { + self::addNotification( + $params, + static function ($code, $a, $b, $c, $transferred, $total) use ($value) { + if ($code == \STREAM_NOTIFY_PROGRESS) { + // The upload progress cannot be determined. Use 0 for cURL compatibility: + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html + $value($total, $transferred, 0, 0); + } + } + ); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + return; + } + + static $map = [ + \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; + + $value = Utils::debugResource($value); + $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); + self::addNotification( + $params, + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (\array_filter($passed) as $i => $v) { + \fwrite($value, $args[$i].': "'.$v.'" '); + } + \fwrite($value, "\n"); + } + ); + } + + private static function addNotification(array &$params, callable $notify): void + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = self::callArray([ + $params['notification'], + $notify, + ]); + } + } + + private static function callArray(array $functions): callable + { + return static function (...$args) use ($functions) { + foreach ($functions as $fn) { + $fn(...$args); + } + }; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 0000000..6cb12f0 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,275 @@ +push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler. + */ + public function __construct(callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @return ResponseInterface|PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Dumps a string representation of the stack. + * + * @return string + */ + public function __toString() + { + $depth = 0; + $stack = []; + + if ($this->handler !== null) { + $stack[] = '0) Handler: '.$this->debugCallable($this->handler); + } + + $result = ''; + foreach (\array_reverse($this->stack) as $tuple) { + ++$depth; + $str = "{$depth}) Name: '{$tuple[1]}', "; + $str .= 'Function: '.$this->debugCallable($tuple[0]); + $result = "> {$str}\n{$result}"; + $stack[] = $str; + } + + foreach (\array_keys($stack) as $k) { + $result .= "< {$stack[$k]}\n"; + } + + return $result; + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and + * returns a Promise. + */ + public function setHandler(callable $handler): void + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + */ + public function hasHandler(): bool + { + return $this->handler !== null; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, string $name = null): void + { + \array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, string $name = ''): void + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param callable|string $remove Middleware to remove by instance or name. + */ + public function remove($remove): void + { + if (!is_string($remove) && !is_callable($remove)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->cached = null; + $idx = \is_callable($remove) ? 0 : 1; + $this->stack = \array_values(\array_filter( + $this->stack, + static function ($tuple) use ($idx, $remove) { + return $tuple[$idx] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable(RequestInterface, array): PromiseInterface + */ + public function resolve(): callable + { + if ($this->cached === null) { + if (($prev = $this->handler) === null) { + throw new \LogicException('No handler has been specified'); + } + + foreach (\array_reverse($this->stack) as $fn) { + /** @var callable(RequestInterface, array): PromiseInterface $prev */ + $prev = $fn[0]($prev); + } + + $this->cached = $prev; + } + + return $this->cached; + } + + private function findByName(string $name): int + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException("Middleware not found: $name"); + } + + /** + * Splices a function into the middleware list at a specific position. + */ + private function splice(string $findName, string $withName, callable $middleware, bool $before): void + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + \array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === \count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } + + /** + * Provides a debug string for a given callable. + * + * @param callable|string $fn Function to write as a string. + */ + private function debugCallable($fn): string + { + if (\is_string($fn)) { + return "callable({$fn})"; + } + + if (\is_array($fn)) { + return \is_string($fn[0]) + ? "callable({$fn[0]}::{$fn[1]})" + : "callable(['".\get_class($fn[0])."', '{$fn[1]}'])"; + } + + /** @var object $fn */ + return 'callable('.\spl_object_hash($fn).')'; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 0000000..04e9eb3 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,199 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + private $template; + + /** + * @param string $template Log message template + */ + public function __construct(?string $template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface|null $response Response that was received + * @param \Throwable|null $error Exception that was received + */ + public function format(RequestInterface $request, ResponseInterface $response = null, \Throwable $error = null): string + { + $cache = []; + + /** @var string */ + return \preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache) { + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\Message::toString($request); + break; + case 'response': + $result = $response ? Psr7\Message::toString($response) : ''; + break; + case 'req_headers': + $result = \trim($request->getMethod() + .' '.$request->getRequestTarget()) + .' HTTP/'.$request->getProtocolVersion()."\r\n" + .$this->headers($request); + break; + case 'res_headers': + $result = $response ? + \sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + )."\r\n".$this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody()->__toString(); + break; + case 'res_body': + if (!$response instanceof ResponseInterface) { + $result = 'NULL'; + break; + } + + $body = $response->getBody(); + + if (!$body->isSeekable()) { + $result = 'RESPONSE_NOT_LOGGEABLE'; + break; + } + + $result = $response->getBody()->__toString(); + break; + case 'ts': + case 'date_iso_8601': + $result = \gmdate('c'); + break; + case 'date_common_log': + $result = \date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri()->__toString(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = \gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (\strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(\substr($matches[1], 11)); + } elseif (\strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(\substr($matches[1], 11)) + : 'NULL'; + } + } + + $cache[$matches[1]] = $result; + + return $result; + }, + $this->template + ); + } + + /** + * Get headers from message as string + */ + private function headers(MessageInterface $message): string + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name.': '.\implode(', ', $values)."\r\n"; + } + + return \trim($result); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php new file mode 100644 index 0000000..4793461 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php @@ -0,0 +1,18 @@ +withCookieHeader($request); + + return $handler($request, $options) + ->then( + static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface { + $cookieJar->extractCookies($request, $response); + + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_errors" request option is set to true. + * + * @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages. + * + * @return callable(callable): callable Returns a function that accepts the next handler. + */ + public static function httpErrors(BodySummarizerInterface $bodySummarizer = null): callable + { + return static function (callable $handler) use ($bodySummarizer): callable { + return static function ($request, array $options) use ($handler, $bodySummarizer) { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + + return $handler($request, $options)->then( + static function (ResponseInterface $response) use ($request, $bodySummarizer) { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response, null, [], $bodySummarizer); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array|\ArrayAccess $container Container to hold the history (by reference). + * + * @return callable(callable): callable Returns a function that accepts the next handler. + * + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container): callable + { + if (!\is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return static function (callable $handler) use (&$container): callable { + return static function (RequestInterface $request, array $options) use ($handler, &$container) { + return $handler($request, $options)->then( + static function ($value) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options, + ]; + + return $value; + }, + static function ($reason) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options, + ]; + + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * Middleware that invokes a callback before and after sending a request. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param callable $before Function to invoke before forwarding the request. + * @param callable $after Function invoked after forwarding. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function tap(callable $before = null, callable $after = null): callable + { + return static function (callable $handler) use ($before, $after): callable { + return static function (RequestInterface $request, array $options) use ($handler, $before, $after) { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function redirect(): callable + { + return static function (callable $handler): RedirectMiddleware { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable $decider Function that accepts the number of retries, + * a request, [response], and [exception] and + * returns true if the request is to be retried. + * @param callable $delay Function that accepts the number of retries and + * returns the number of milliseconds to delay. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function retry(callable $decider, callable $delay = null): callable + { + return static function (callable $handler) use ($decider, $delay): RetryMiddleware { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable + { + // To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter + if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) { + throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class)); + } + + return static function (callable $handler) use ($logger, $formatter, $logLevel): callable { + return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) { + return $handler($request, $options)->then( + static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + + return $response; + }, + static function ($reason) use ($logger, $request, $formatter): PromiseInterface { + $response = $reason instanceof RequestException ? $reason->getResponse() : null; + $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); + $logger->error($message); + + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + */ + public static function prepareBody(): callable + { + return static function (callable $handler): PrepareBodyMiddleware { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + */ + public static function mapRequest(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + */ + public static function mapResponse(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Pool.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Pool.php new file mode 100644 index 0000000..6277c61 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Pool.php @@ -0,0 +1,125 @@ + $rfn) { + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $opts); + } elseif (\is_callable($rfn)) { + yield $key => $rfn($opts); + } else { + throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requests(), $config); + } + + /** + * Get promise + */ + public function promise(): PromiseInterface + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param array|\Iterator $requests Requests to send concurrently. + * @param array $options Passes through the options available in + * {@see \GuzzleHttp\Pool::__construct} + * + * @return array Returns an array containing the response or an exception + * in the same order that the requests were sent. + * + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch(ClientInterface $client, $requests, array $options = []): array + { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + \ksort($res); + + return $res; + } + + /** + * Execute callback(s) + */ + private static function cmpCallback(array &$options, string $name, array &$results): void + { + if (!isset($options[$name])) { + $options[$name] = static function ($v, $k) use (&$results) { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = static function ($v, $k) use (&$results, $currentFn) { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 0000000..0a8de81 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,105 @@ +nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + // Don't do anything if the request has no body. + if ($request->getBody()->getSize() === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + $size = $request->getBody()->getSize(); + if ($size !== null) { + $modify['set_headers']['Content-Length'] = $size; + } else { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify); + + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); + } + + /** + * Add expect header + */ + private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void + { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = $options['expect'] ?? null; + + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 + if ($expect === false || $request->getProtocolVersion() < 1.1) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 0000000..7aa21a6 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,228 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::$defaultSettings; + } elseif (!\is_array($options['allow_redirects'])) { + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::$defaultSettings; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function (ResponseInterface $response) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) + { + if (\strpos((string) $response->getStatusCode(), '3') !== 0 + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $response, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + // If authorization is handled by curl, unset it if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) { + unset( + $options['curl'][\CURLOPT_HTTPAUTH], + $options['curl'][\CURLOPT_USERPWD] + ); + } + + if (isset($options['allow_redirects']['on_redirect'])) { + ($options['allow_redirects']['on_redirect'])( + $request, + $response, + $nextRequest->getUri() + ); + } + + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + /** + * Enable tracking on promise. + */ + private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface + { + return $promise->then( + static function (ResponseInterface $response) use ($uri, $statusCode) { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + \array_unshift($historyHeader, $uri); + \array_unshift($statusHeader, (string) $statusCode); + + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + /** + * Check for too many redirects. + * + * @throws TooManyRedirectsException Too many redirects. + */ + private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void + { + $current = $options['__redirect_count'] + ?? 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); + } + } + + public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface + { + // Request modifications to apply. + $modify = []; + $protocols = $options['allow_redirects']['protocols']; + + // Use a GET request if this is an entity enclosing request and we are + // not forcing RFC compliance, but rather emulating what all browsers + // would do. + $statusCode = $response->getStatusCode(); + if ($statusCode == 303 + || ($statusCode <= 302 && !$options['allow_redirects']['strict']) + ) { + $safeMethods = ['GET', 'HEAD', 'OPTIONS']; + $requestMethod = $request->getMethod(); + + $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; + $modify['body'] = ''; + } + + $uri = self::redirectUri($request, $response, $protocols); + if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { + $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + $modify['uri'] = $uri; + Psr7\Message::rewindBody($request); + + // Add the Referer header if it is told to do so and only + // add the header if we are not redirecting from https to http. + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $uri = $request->getUri()->withUserInfo(''); + $modify['set_headers']['Referer'] = (string) $uri; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization and Cookie headers if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { + $modify['remove_headers'][] = 'Authorization'; + $modify['remove_headers'][] = 'Cookie'; + } + + return Psr7\Utils::modifyRequest($request, $modify); + } + + /** + * Set the appropriate URL on the request based on the location header. + */ + private static function redirectUri( + RequestInterface $request, + ResponseInterface $response, + array $protocols + ): UriInterface { + $location = Psr7\UriResolver::resolve( + $request->getUri(), + new Psr7\Uri($response->getHeaderLine('Location')) + ); + + // Ensure that the redirect URI is allowed based on the protocols. + if (!\in_array($location->getScheme(), $protocols)) { + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); + } + + return $location; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 0000000..a38768c --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,274 @@ +decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: __CLASS__.'::exponentialDelay'; + } + + /** + * Default exponential backoff delay function. + * + * @return int milliseconds. + */ + public static function exponentialDelay(int $retries): int + { + return (int) 2 ** ($retries - 1) * 1000; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } + + $fn = $this->nextHandler; + + return $fn($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + /** + * Execute fulfilled closure + */ + private function onFulfilled(RequestInterface $request, array $options): callable + { + return function ($value) use ($request, $options) { + if (!($this->decider)( + $options['retries'], + $request, + $value, + null + )) { + return $value; + } + + return $this->doRetry($request, $options, $value); + }; + } + + /** + * Execute rejected closure + */ + private function onRejected(RequestInterface $req, array $options): callable + { + return function ($reason) use ($req, $options) { + if (!($this->decider)( + $options['retries'], + $req, + null, + $reason + )) { + return P\Create::rejectionFor($reason); + } + + return $this->doRetry($req, $options); + }; + } + + private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface + { + $options['delay'] = ($this->delay)(++$options['retries'], $response, $request); + + return $this($request, $options); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/TransferStats.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 0000000..2ce9e38 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,133 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Returns true if a response was received. + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + */ + public function getEffectiveUri(): UriInterface + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float|null Time in seconds. + */ + public function getTransferTime(): ?float + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + */ + public function getHandlerStats(): array + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat(string $stat) + { + return $this->handlerStats[$stat] ?? null; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Utils.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Utils.php new file mode 100644 index 0000000..93d6d39 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/Utils.php @@ -0,0 +1,384 @@ +getHost()) { + $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); + if ($asciiHost === false) { + $errorBitSet = $info['errors'] ?? 0; + + $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool { + return substr($name, 0, 11) === 'IDNA_ERROR_'; + }); + + $errors = []; + foreach ($errorConstants as $errorConstant) { + if ($errorBitSet & constant($errorConstant)) { + $errors[] = $errorConstant; + } + } + + $errorMessage = 'IDN conversion failed'; + if ($errors) { + $errorMessage .= ' (errors: '.implode(', ', $errors).')'; + } + + throw new InvalidArgumentException($errorMessage); + } + if ($uri->getHost() !== $asciiHost) { + // Replace URI only if the ASCII version is different + $uri = $uri->withHost($asciiHost); + } + } + + return $uri; + } + + /** + * @internal + */ + public static function getenv(string $name): ?string + { + if (isset($_SERVER[$name])) { + return (string) $_SERVER[$name]; + } + + if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) { + return (string) $value; + } + + return null; + } + + /** + * @return string|false + */ + private static function idnToAsci(string $domain, int $options, ?array &$info = []) + { + if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) { + return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); + } + + throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old'); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/guzzle/src/functions.php b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/functions.php new file mode 100644 index 0000000..5edc66a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/guzzle/src/functions.php @@ -0,0 +1,167 @@ + +Copyright (c) 2015 Graham Campbell +Copyright (c) 2017 Tobias Schultze +Copyright (c) 2020 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/README.md b/php/libraries/composer/vendor/guzzlehttp/promises/README.md new file mode 100644 index 0000000..a32d3d2 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/README.md @@ -0,0 +1,559 @@ +# Guzzle Promises + +[Promises/A+](https://promisesaplus.com/) implementation that handles promise +chaining and resolution iteratively, allowing for "infinite" promise chaining +while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) +for a general introduction to promises. + +- [Features](#features) +- [Quick start](#quick-start) +- [Synchronous wait](#synchronous-wait) +- [Cancellation](#cancellation) +- [API](#api) + - [Promise](#promise) + - [FulfilledPromise](#fulfilledpromise) + - [RejectedPromise](#rejectedpromise) +- [Promise interop](#promise-interop) +- [Implementation notes](#implementation-notes) + + +## Features + +- [Promises/A+](https://promisesaplus.com/) implementation. +- Promise resolution and chaining is handled iteratively, allowing for + "infinite" promise chaining. +- Promises have a synchronous `wait` method. +- Promises can be cancelled. +- Works with any object that has a `then` function. +- C# style async/await coroutine promises using + `GuzzleHttp\Promise\Coroutine::of()`. + + +## Installation + +```shell +composer require guzzlehttp/promises +``` + + +## Version Guidance + +| Version | Status | PHP Version | +|---------|------------------------|--------------| +| 1.x | Bug and security fixes | >=5.5,<8.3 | +| 2.x | Latest | >=7.2.5,<8.4 | + + +## Quick Start + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either a promise's eventual value or the reason +why the promise cannot be fulfilled. + +### Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Resolving a promise triggers callbacks +registered with the promise's `then` method. These callbacks are triggered +only once and in the order in which they were added. + +### Resolving a Promise + +Promises are fulfilled using the `resolve($value)` method. Resolving a promise +with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger +all of the onFulfilled callbacks (resolving a promise with a rejected promise +will reject the promise and trigger the `$onRejected` callbacks). + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(function ($value) { + // Return a value and don't break the chain + return "Hello, " . $value; + }) + // This then is executed after the first then and receives the value + // returned from the first then. + ->then(function ($value) { + echo $value; + }); + +// Resolving the promise triggers the $onFulfilled callbacks and outputs +// "Hello, reader." +$promise->resolve('reader.'); +``` + +### Promise Forwarding + +Promises can be chained one after the other. Each then in the chain is a new +promise. The return value of a promise is what's forwarded to the next +promise in the chain. Returning a promise in a `then` callback will cause the +subsequent promises in the chain to only be fulfilled when the returned promise +has been fulfilled. The next promise in the chain will be invoked with the +resolved value of the promise. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +// Triggers the first callback and outputs "A" +$promise->resolve('A'); +// Triggers the second callback and outputs "B" +$nextPromise->resolve('B'); +``` + +### Promise Rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +// Outputs "Error!" +``` + +### Rejection Forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks are invoked with the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +If an exception is not thrown in a `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +``` + + +## Synchronous Wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously force a promise to complete. When a wait function is invoked +it is expected to deliver a value to the promise or reject the promise. If the +wait function does not deliver a value, then an exception is thrown. The wait +function provided to a promise constructor is invoked when the `wait` function +of the promise is called. + +```php +$promise = new Promise(function () use (&$promise) { + $promise->resolve('foo'); +}); + +// Calling wait will return the value of the promise. +echo $promise->wait(); // outputs "foo" +``` + +If an exception is encountered while invoking the wait function of a promise, +the promise is rejected with the exception and the exception is thrown. + +```php +$promise = new Promise(function () use (&$promise) { + throw new Exception('foo'); +}); + +$promise->wait(); // throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function () { die('this is not called!'); }); +$promise->resolve('foo'); +echo $promise->wait(); // outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw an exception. If +the rejection reason is an instance of `\Exception` the reason is thrown. +Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason +can be obtained by calling the `getReason` method of the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' + +### Unwrapping a Promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current state of execution (i.e., return the value of the +promise if it was fulfilled or throw an exception if it was rejected). This is +called "unwrapping" the promise. Waiting on a promise will by default unwrap +the promise state. + +You can force a promise to resolve and *not* unwrap the state of the promise +by passing `false` to the first argument of the `wait` function: + +```php +$promise = new Promise(); +$promise->reject('foo'); +// This will not throw an exception. It simply ensures the promise has +// been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited +upon until the unwrapped value is not a promise. This means that if you resolve +promise A with a promise B and unwrap promise A, the value returned by the +wait function will be the value delivered to promise B. + +**Note**: when you do not unwrap the promise, no value is returned. + + +## Cancellation + +You can cancel a promise that has not yet been fulfilled using the `cancel()` +method of a promise. When creating a promise you can provide an optional +cancel function that when invoked cancels the action of computing a resolution +of the promise. + + +## API + +### Promise + +When creating a promise object, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is +expected to resolve the promise. `$cancelFn` is a function with no arguments +that is expected to cancel the computation of a promise. It is invoked when the +`cancel()` method of a promise is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function () use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // do something that will cancel the promise computation (e.g., close + // a socket, cancel a database query, etc...) + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` + + Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. + +- `otherwise(callable $onRejected) : PromiseInterface` + + Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. + +- `wait($unwrap = true) : mixed` + + Synchronously waits on the promise to complete. + + `$unwrap` controls whether or not the value of the promise is returned for a + fulfilled promise or if an exception is thrown if the promise is rejected. + This is set to `true` by default. + +- `cancel()` + + Attempts to cancel the promise if possible. The promise being cancelled and + the parent most ancestor that has not yet been resolved will also be + cancelled. Any promises waiting on the cancelled promise to resolve will also + be cancelled. + +- `getState() : string` + + Returns the state of the promise. One of `pending`, `fulfilled`, or + `rejected`. + +- `resolve($value)` + + Fulfills the promise with the given `$value`. + +- `reject($reason)` + + Rejects the promise with the given `$reason`. + + +### FulfilledPromise + +A fulfilled promise can be created to represent a promise that has been +fulfilled. + +```php +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = new FulfilledPromise('value'); + +// Fulfilled callbacks are immediately invoked. +$promise->then(function ($value) { + echo $value; +}); +``` + + +### RejectedPromise + +A rejected promise can be created to represent a promise that has been +rejected. + +```php +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new RejectedPromise('Error'); + +// Rejected callbacks are immediately invoked. +$promise->then(null, function ($reason) { + echo $reason; +}); +``` + + +## Promise Interoperability + +This library works with foreign promises that have a `then` method. This means +you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) +for example. When a foreign promise is returned inside of a then method +callback, promise resolution will occur recursively. + +```php +// Create a React promise +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +// Create a Guzzle promise that is fulfilled with a React promise. +$guzzlePromise = new GuzzleHttp\Promise\Promise(); +$guzzlePromise->then(function ($value) use ($reactPromise) { + // Do something something with the value... + // Return the React promise + return $reactPromise; +}); +``` + +Please note that wait and cancel chaining is no longer possible when forwarding +a foreign promise. You will need to wrap a third-party promise with a Guzzle +promise in order to utilize wait and cancel functions with foreign promises. + + +### Event Loop Integration + +In order to keep the stack size constant, Guzzle promises are resolved +asynchronously using a task queue. When waiting on promises synchronously, the +task queue will be automatically run to ensure that the blocking promise and +any forwarded promises are resolved. When using promises asynchronously in an +event loop, you will need to run the task queue on each tick of the loop. If +you do not run the task queue, then promises will not be resolved. + +You can run the task queue using the `run()` method of the global task queue +instance. + +```php +// Get the global task queue +$queue = GuzzleHttp\Promise\Utils::queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a periodic timer: + +```php +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0, [$queue, 'run']); +``` + + +## Implementation Notes + +### Promise Resolution and Chaining is Handled Iteratively + +By shuffling pending handlers from one owner to another, promises are +resolved iteratively, allowing for "infinite" then chaining. + +```php +then(function ($v) { + // The stack size remains constant (a good thing) + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +then takes ownership of the handlers of each child promise and delivers values +down the chain without using recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all of the pending handlers are delivered the forwarded +value. + +### A Promise is the Deferred + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. This is a nice separation of computation and delivery because +consumers of the promise cannot modify the value that will be eventually +delivered. + +One side effect of being able to implement promise resolution and chaining +iteratively is that you need to be able for one promise to reach into the state +of another promise to shuffle around ownership of handlers. In order to achieve +this without making the handlers of a promise publicly mutable, a promise is +also the deferred value, allowing promises of the same parent class to reach +into and modify the private properties of promises of the same type. While this +does allow consumers of the value to modify the resolution or rejection of the +deferred, it is a small price to pay for keeping the stack size constant. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +// prints "foo" +``` + + +## Upgrading from Function API + +A static API was first introduced in 1.4.0, in order to mitigate problems with +functions conflicting between global and local copies of the package. The +function API was removed in 2.0.0. A migration table has been provided here for +your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `queue` | `Utils::queue` | +| `task` | `Utils::task` | +| `promise_for` | `Create::promiseFor` | +| `rejection_for` | `Create::rejectionFor` | +| `exception_for` | `Create::exceptionFor` | +| `iter_for` | `Create::iterFor` | +| `inspect` | `Utils::inspect` | +| `inspect_all` | `Utils::inspectAll` | +| `unwrap` | `Utils::unwrap` | +| `all` | `Utils::all` | +| `some` | `Utils::some` | +| `any` | `Utils::any` | +| `settle` | `Utils::settle` | +| `each` | `Each::of` | +| `each_limit` | `Each::ofLimit` | +| `each_limit_all` | `Each::ofLimitAll` | +| `!is_fulfilled` | `Is::pending` | +| `is_fulfilled` | `Is::fulfilled` | +| `is_rejected` | `Is::rejected` | +| `is_settled` | `Is::settled` | +| `coroutine` | `Coroutine::of` | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/promises/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/composer.json b/php/libraries/composer/vendor/guzzlehttp/promises/composer.json new file mode 100644 index 0000000..6c5bdd6 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/composer.json @@ -0,0 +1,58 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "keywords": ["promise"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Promise\\Tests\\": "tests/" + } + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/AggregateException.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 0000000..40ffdbc --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,19 @@ +then(function ($v) { echo $v; }); + * + * @param callable $generatorFn Generator function to wrap into a promise. + * + * @return Promise + * + * @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + /** + * @var PromiseInterface|null + */ + private $currentPromise; + + /** + * @var Generator + */ + private $generator; + + /** + * @var Promise + */ + private $result; + + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function (): void { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }); + try { + $this->nextCoroutine($this->generator->current()); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * Create a new coroutine. + */ + public static function of(callable $generatorFn): self + { + return new self($generatorFn); + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + return $this->result->then($onFulfilled, $onRejected); + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->result->otherwise($onRejected); + } + + public function wait(bool $unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState(): string + { + return $this->result->getState(); + } + + public function resolve($value): void + { + $this->result->resolve($value); + } + + public function reject($reason): void + { + $this->result->reject($reason); + } + + public function cancel(): void + { + $this->currentPromise->cancel(); + $this->result->cancel(); + } + + private function nextCoroutine($yielded): void + { + $this->currentPromise = Create::promiseFor($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value): void + { + unset($this->currentPromise); + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason): void + { + unset($this->currentPromise); + try { + $nextYield = $this->generator->throw(Create::exceptionFor($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/Create.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/Create.php new file mode 100644 index 0000000..9d3fc4a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/Create.php @@ -0,0 +1,79 @@ +then([$promise, 'resolve'], [$promise, 'reject']); + + return $promise; + } + + return new FulfilledPromise($value); + } + + /** + * Creates a rejected promise for a reason if the reason is not a promise. + * If the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + */ + public static function rejectionFor($reason): PromiseInterface + { + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); + } + + /** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + */ + public static function exceptionFor($reason): \Throwable + { + if ($reason instanceof \Throwable) { + return $reason; + } + + return new RejectionException($reason); + } + + /** + * Returns an iterator for the given value. + * + * @param mixed $value + */ + public static function iterFor($value): \Iterator + { + if ($value instanceof \Iterator) { + return $value; + } + + if (is_array($value)) { + return new \ArrayIterator($value); + } + + return new \ArrayIterator([$value]); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/Each.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/Each.php new file mode 100644 index 0000000..c09d23c --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/Each.php @@ -0,0 +1,81 @@ + $onFulfilled, + 'rejected' => $onRejected, + ]))->promise(); + } + + /** + * Like of, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow + * for dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + */ + public static function ofLimit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected, + 'concurrency' => $concurrency, + ]))->promise(); + } + + /** + * Like limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + */ + public static function ofLimitAll( + $iterable, + $concurrency, + callable $onFulfilled = null + ): PromiseInterface { + return self::ofLimit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate): void { + $aggregate->reject($reason); + } + ); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/EachPromise.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 0000000..e123898 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,248 @@ +iterable = Create::iterFor($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + /** @psalm-suppress InvalidNullableReturnType */ + public function promise(): PromiseInterface + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + /** @psalm-assert Promise $this->aggregate */ + $this->iterable->rewind(); + $this->refillPending(); + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } + + /** + * @psalm-suppress NullableReturnStatement + */ + return $this->aggregate; + } + + private function createPromise(): void + { + $this->mutex = false; + $this->aggregate = new Promise(function (): void { + if ($this->checkIfFinished()) { + return; + } + reset($this->pending); + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if (Is::settled($this->aggregate)) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function (): void { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + $this->nextPendingIndex = 0; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending(): void + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()) { + } + + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? ($this->concurrency)(count($this->pending)) + : $this->concurrency; + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()) { + } + } + + private function addPending(): bool + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = Create::promiseFor($this->iterable->current()); + $key = $this->iterable->key(); + + // Iterable keys may not be unique, so we use a counter to + // guarantee uniqueness + $idx = $this->nextPendingIndex++; + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx, $key): void { + if ($this->onFulfilled) { + ($this->onFulfilled)( + $value, + $key, + $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx, $key): void { + if ($this->onRejected) { + ($this->onRejected)( + $reason, + $key, + $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator(): bool + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + + return true; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + + return false; + } + } + + private function step(int $idx): void + { + // If the promise was already resolved, then ignore this step. + if (Is::settled($this->aggregate)) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + private function checkIfFinished(): bool + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 0000000..ab71296 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,89 @@ +value = $value; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = Utils::queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled): void { + if (Is::pending($p)) { + try { + $p->resolve($onFulfilled($value)); + } catch (\Throwable $e) { + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + return $unwrap ? $this->value : null; + } + + public function getState(): string + { + return self::FULFILLED; + } + + public function resolve($value): void + { + if ($value !== $this->value) { + throw new \LogicException('Cannot resolve a fulfilled promise'); + } + } + + public function reject($reason): void + { + throw new \LogicException('Cannot reject a fulfilled promise'); + } + + public function cancel(): void + { + // pass + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/Is.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/Is.php new file mode 100644 index 0000000..f3f0503 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/Is.php @@ -0,0 +1,40 @@ +getState() === PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled or rejected. + */ + public static function settled(PromiseInterface $promise): bool + { + return $promise->getState() !== PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled. + */ + public static function fulfilled(PromiseInterface $promise): bool + { + return $promise->getState() === PromiseInterface::FULFILLED; + } + + /** + * Returns true if a promise is rejected. + */ + public static function rejected(PromiseInterface $promise): bool + { + return $promise->getState() === PromiseInterface::REJECTED; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/Promise.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/Promise.php new file mode 100644 index 0000000..1b07bdc --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/Promise.php @@ -0,0 +1,281 @@ +waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + $promise = Create::promiseFor($this->result); + + return $onFulfilled ? $promise->then($onFulfilled) : $promise; + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = Create::rejectionFor($this->result); + + return $onRejected ? $rejection->then(null, $onRejected) : $rejection; + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + $this->waitIfPending(); + + if ($this->result instanceof PromiseInterface) { + return $this->result->wait($unwrap); + } + if ($unwrap) { + if ($this->state === self::FULFILLED) { + return $this->result; + } + // It's rejected so "unwrap" and throw an exception. + throw Create::exceptionFor($this->result); + } + } + + public function getState(): string + { + return $this->state; + } + + public function cancel(): void + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value): void + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason): void + { + $this->settle(self::REJECTED, $reason); + } + + private function settle(string $state, $value): void + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $this->handlers = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!is_object($value) || !method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + Utils::queue()->add(static function () use ($id, $value, $handlers): void { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } elseif ($value instanceof Promise && Is::pending($value)) { + // We can just merge our handlers onto the next promise. + $value->handlers = array_merge($value->handlers, $handlers); + } else { + // Resolve the handlers when the forwarded promise is resolved. + $value->then( + static function ($value) use ($handlers): void { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use ($handlers): void { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + */ + private static function callHandler(int $index, $value, array $handler): void + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if (Is::settled($promise)) { + return; + } + + try { + if (isset($handler[$index])) { + /* + * If $f throws an exception, then $handler will be in the exception + * stack trace. Since $handler contains a reference to the callable + * itself we get a circular reference. We clear the $handler + * here to avoid that memory leak. + */ + $f = $handler[$index]; + unset($handler); + $promise->resolve($f($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + $promise->reject($reason); + } + } + + private function waitIfPending(): void + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's no wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + .'no internal wait function. You must provide a wait ' + .'function when constructing the promise to be able to ' + .'wait on a promise.'); + } + + Utils::queue()->run(); + + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn(): void + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Throwable $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList(): void + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + do { + $result->waitIfPending(); + $result = $result->result; + } while ($result instanceof Promise); + + if ($result instanceof PromiseInterface) { + $result->wait(false); + } + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/PromiseInterface.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 0000000..2824802 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,91 @@ +reason = $reason; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = Utils::queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected): void { + if (Is::pending($p)) { + try { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + if ($unwrap) { + throw Create::exceptionFor($this->reason); + } + + return null; + } + + public function getState(): string + { + return self::REJECTED; + } + + public function resolve($value): void + { + throw new \LogicException('Cannot resolve a rejected promise'); + } + + public function reject($reason): void + { + if ($reason !== $this->reason) { + throw new \LogicException('Cannot reject a rejected promise'); + } + } + + public function cancel(): void + { + // pass + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/RejectionException.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 0000000..72a81ba --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,49 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: '.$description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: '.$this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: '.json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/TaskQueue.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 0000000..503e0b2 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,71 @@ +run(); + * + * @final + */ +class TaskQueue implements TaskQueueInterface +{ + private $enableShutdown = true; + private $queue = []; + + public function __construct(bool $withShutdown = true) + { + if ($withShutdown) { + register_shutdown_function(function (): void { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function isEmpty(): bool + { + return !$this->queue; + } + + public function add(callable $task): void + { + $this->queue[] = $task; + } + + public function run(): void + { + while ($task = array_shift($this->queue)) { + /** @var callable $task */ + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown(): void + { + $this->enableShutdown = false; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/php/libraries/composer/vendor/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 0000000..34c561a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,24 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\Utils::queue()->run(); + * } + * + * + * @param TaskQueueInterface|null $assign Optionally specify a new queue instance. + */ + public static function queue(TaskQueueInterface $assign = null): TaskQueueInterface + { + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; + } + + /** + * Adds a function to run in the task queue when it is next `run()` and + * returns a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + */ + public static function task(callable $task): PromiseInterface + { + $queue = self::queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise): void { + try { + if (Is::pending($promise)) { + $promise->resolve($task()); + } + } catch (\Throwable $e) { + $promise->reject($e); + } + }); + + return $promise; + } + + /** + * Synchronously waits on a promise to resolve and returns an inspection + * state array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the + * array will contain a "value" key mapping to the fulfilled value of the + * promise. If the promise is rejected, the array will contain a "reason" + * key mapping to the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + */ + public static function inspect(PromiseInterface $promise): array + { + try { + return [ + 'state' => PromiseInterface::FULFILLED, + 'value' => $promise->wait(), + ]; + } catch (RejectionException $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; + } catch (\Throwable $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } + } + + /** + * Waits on all of the provided promises, but does not unwrap rejected + * promises as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + */ + public static function inspectAll($promises): array + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = self::inspect($promise); + } + + return $results; + } + + /** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same + * order the promises were provided). An exception is thrown if any of the + * promises are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @throws \Throwable on error + */ + public static function unwrap($promises): array + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; + } + + /** + * Given an array of promises, return a promise that is fulfilled when all + * the items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + */ + public static function all($promises, bool $recursive = false): PromiseInterface + { + $results = []; + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results): void { + $results[$idx] = $value; + }, + function ($reason, $idx, Promise $aggregate): void { + $aggregate->reject($reason); + } + )->then(function () use (&$results) { + ksort($results); + + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use ($recursive, &$promises) { + foreach ($promises as $promise) { + if (Is::pending($promise)) { + return self::all($promises, $recursive); + } + } + + return $results; + }); + } + + return $promise; + } + + /** + * Initiate a competitive race between multiple promises or values (values + * will become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise + * is fulfilled with an array that contains the fulfillment values of the + * winners in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number + * of fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + */ + public static function some(int $count, $promises): PromiseInterface + { + $results = []; + $rejections = []; + + return Each::of( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count): void { + if (Is::settled($p)) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections): void { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + + return array_values($results); + } + ); + } + + /** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + */ + public static function any($promises): PromiseInterface + { + return self::some(1, $promises)->then(function ($values) { + return $values[0]; + }); + } + + /** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + */ + public static function settle($promises): PromiseInterface + { + $results = []; + + return Each::of( + $promises, + function ($value, $idx) use (&$results): void { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results): void { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + )->then(function () use (&$results) { + ksort($results); + + return $results; + }); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/CHANGELOG.md b/php/libraries/composer/vendor/guzzlehttp/psr7/CHANGELOG.md new file mode 100644 index 0000000..fe3eda7 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/CHANGELOG.md @@ -0,0 +1,448 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## 2.6.2 - 2023-12-03 + +### Fixed + +- Fixed another issue with the fact that PHP transforms numeric strings in array keys to ints + +### Changed + +- Updated links in docs to their canonical versions +- Replaced `call_user_func*` with native calls + +## 2.6.1 - 2023-08-27 + +### Fixed + +- Properly handle the fact that PHP transforms numeric strings in array keys to ints + +## 2.6.0 - 2023-08-03 + +### Changed + +- Updated the mime type map to add some new entries, fix a couple of invalid entries, and remove an invalid entry +- Fallback to `application/octet-stream` if we are unable to guess the content type for a multipart file upload + +## 2.5.1 - 2023-08-03 + +### Fixed + +- Corrected mime type for `.acc` files to `audio/aac` + +### Changed + +- PHP 8.3 support + +## 2.5.0 - 2023-04-17 + +### Changed + +- Adjusted `psr/http-message` version constraint to `^1.1 || ^2.0` + +## 2.4.5 - 2023-04-17 + +### Fixed + +- Prevent possible warnings on unset variables in `ServerRequest::normalizeNestedFileSpec` +- Fixed `Message::bodySummary` when `preg_match` fails +- Fixed header validation issue + +## 2.4.4 - 2023-03-09 + +### Changed + +- Removed the need for `AllowDynamicProperties` in `LazyOpenStream` + +## 2.4.3 - 2022-10-26 + +### Changed + +- Replaced `sha1(uniqid())` by `bin2hex(random_bytes(20))` + +## 2.4.2 - 2022-10-25 + +### Fixed + +- Fixed erroneous behaviour when combining host and relative path + +## 2.4.1 - 2022-08-28 + +### Fixed + +- Rewind body before reading in `Message::bodySummary` + +## 2.4.0 - 2022-06-20 + +### Added + +- Added provisional PHP 8.2 support +- Added `UriComparator::isCrossOrigin` method + +## 2.3.0 - 2022-06-09 + +### Fixed + +- Added `Header::splitList` method +- Added `Utils::tryGetContents` method +- Improved `Stream::getContents` method +- Updated mimetype mappings + +## 2.2.2 - 2022-06-08 + +### Fixed + +- Fix `Message::parseRequestUri` for numeric headers +- Re-wrap exceptions thrown in `fread` into runtime exceptions +- Throw an exception when multipart options is misformatted + +## 2.2.1 - 2022-03-20 + +### Fixed + +- Correct header value validation + +## 2.2.0 - 2022-03-20 + +### Added + +- A more compressive list of mime types +- Add JsonSerializable to Uri +- Missing return types + +### Fixed + +- Bug MultipartStream no `uri` metadata +- Bug MultipartStream with filename for `data://` streams +- Fixed new line handling in MultipartStream +- Reduced RAM usage when copying streams +- Updated parsing in `Header::normalize()` + +## 2.1.1 - 2022-03-20 + +### Fixed + +- Validate header values properly + +## 2.1.0 - 2021-10-06 + +### Changed + +- Attempting to create a `Uri` object from a malformed URI will no longer throw a generic + `InvalidArgumentException`, but rather a `MalformedUriException`, which inherits from the former + for backwards compatibility. Callers relying on the exception being thrown to detect invalid + URIs should catch the new exception. + +### Fixed + +- Return `null` in caching stream size if remote size is `null` + +## 2.0.0 - 2021-06-30 + +Identical to the RC release. + +## 2.0.0@RC-1 - 2021-04-29 + +### Fixed + +- Handle possibly unset `url` in `stream_get_meta_data` + +## 2.0.0@beta-1 - 2021-03-21 + +### Added + +- PSR-17 factories +- Made classes final +- PHP7 type hints + +### Changed + +- When building a query string, booleans are represented as 1 and 0. + +### Removed + +- PHP < 7.2 support +- All functions in the `GuzzleHttp\Psr7` namespace + +## 1.8.1 - 2021-03-21 + +### Fixed + +- Issue parsing IPv6 URLs +- Issue modifying ServerRequest lost all its attributes + +## 1.8.0 - 2021-03-21 + +### Added + +- Locale independent URL parsing +- Most classes got a `@final` annotation to prepare for 2.0 + +### Fixed + +- Issue when creating stream from `php://input` and curl-ext is not installed +- Broken `Utils::tryFopen()` on PHP 8 + +## 1.7.0 - 2020-09-30 + +### Added + +- Replaced functions by static methods + +### Fixed + +- Converting a non-seekable stream to a string +- Handle multiple Set-Cookie correctly +- Ignore array keys in header values when merging +- Allow multibyte characters to be parsed in `Message:bodySummary()` + +### Changed + +- Restored partial HHVM 3 support + + +## [1.6.1] - 2019-07-02 + +### Fixed + +- Accept null and bool header values again + + +## [1.6.0] - 2019-06-30 + +### Added + +- Allowed version `^3.0` of `ralouphie/getallheaders` dependency (#244) +- Added MIME type for WEBP image format (#246) +- Added more validation of values according to PSR-7 and RFC standards, e.g. status code range (#250, #272) + +### Changed + +- Tests don't pass with HHVM 4.0, so HHVM support got dropped. Other libraries like composer have done the same. (#262) +- Accept port number 0 to be valid (#270) + +### Fixed + +- Fixed subsequent reads from `php://input` in ServerRequest (#247) +- Fixed readable/writable detection for certain stream modes (#248) +- Fixed encoding of special characters in the `userInfo` component of an URI (#253) + + +## [1.5.2] - 2018-12-04 + +### Fixed + +- Check body size when getting the message summary + + +## [1.5.1] - 2018-12-04 + +### Fixed + +- Get the summary of a body only if it is readable + + +## [1.5.0] - 2018-12-03 + +### Added + +- Response first-line to response string exception (fixes #145) +- A test for #129 behavior +- `get_message_body_summary` function in order to get the message summary +- `3gp` and `mkv` mime types + +### Changed + +- Clarify exception message when stream is detached + +### Deprecated + +- Deprecated parsing folded header lines as per RFC 7230 + +### Fixed + +- Fix `AppendStream::detach` to not close streams +- `InflateStream` preserves `isSeekable` attribute of the underlying stream +- `ServerRequest::getUriFromGlobals` to support URLs in query parameters + + +Several other fixes and improvements. + + +## [1.4.2] - 2017-03-20 + +### Fixed + +- Reverted BC break to `Uri::resolve` and `Uri::removeDotSegments` by removing + calls to `trigger_error` when deprecated methods are invoked. + + +## [1.4.1] - 2017-02-27 + +### Added + +- Rriggering of silenced deprecation warnings. + +### Fixed + +- Reverted BC break by reintroducing behavior to automagically fix a URI with a + relative path and an authority by adding a leading slash to the path. It's only + deprecated now. + + +## [1.4.0] - 2017-02-21 + +### Added + +- Added common URI utility methods based on RFC 3986 (see documentation in the readme): + - `Uri::isDefaultPort` + - `Uri::isAbsolute` + - `Uri::isNetworkPathReference` + - `Uri::isAbsolutePathReference` + - `Uri::isRelativePathReference` + - `Uri::isSameDocumentReference` + - `Uri::composeComponents` + - `UriNormalizer::normalize` + - `UriNormalizer::isEquivalent` + - `UriResolver::relativize` + +### Changed + +- Ensure `ServerRequest::getUriFromGlobals` returns a URI in absolute form. +- Allow `parse_response` to parse a response without delimiting space and reason. +- Ensure each URI modification results in a valid URI according to PSR-7 discussions. + Invalid modifications will throw an exception instead of returning a wrong URI or + doing some magic. + - `(new Uri)->withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/LICENSE b/php/libraries/composer/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 0000000..51c7ec8 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/README.md b/php/libraries/composer/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 0000000..850fa9d --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,880 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](https://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + +![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg) +![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg) + + +## Features + +This package comes with a number of stream implementations and stream +decorators. + + +## Installation + +```shell +composer require guzzlehttp/psr7 +``` + +## Version Guidance + +| Version | Status | PHP Version | +|---------|---------------------|--------------| +| 1.x | Security fixes only | >=5.4,<8.1 | +| 2.x | Latest | >=7.2.5,<8.4 | + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content. + +This stream decorator converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + private $stream; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + ($this->callback)(); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Static API + +There are various static methods available under the `GuzzleHttp\Psr7` namespace. + + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` +returns a value other than `0`. + + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the "start-line" key containing the start line of +the message, "headers" key containing an associative array of header +array values, and a "body" key containing the body of the message. + + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): Request` + +Parses a request message string into a request object. + + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): Response` + +Parses a response message string into a response object. + + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parse an array of header values containing ";" separated data into an +array of associative arrays representing the header key value pair data +of the header. When a parameter does not contain a value, but just +contains a key, this function will inject a key with a '' string value. + + +## `GuzzleHttp\Psr7\Header::splitList` + +`public static function splitList(string|string[] $header): string[]` + +Splits a HTTP header defined to contain a comma-separated list into +each individual value: + +``` +$knownEtags = Header::splitList($request->getHeader('if-none-match')); +``` + +Example headers include `accept`, `cache-control` and `if-none-match`. + + +## `GuzzleHttp\Psr7\Header::normalize` (deprecated) + +`public static function normalize(string|array $header): array` + +`Header::normalize()` is deprecated in favor of [`Header::splitList()`](README.md#guzzlehttppsr7headersplitlist) +which performs the same operation with a cleaned up API and improved +documentation. + +Converts an array of header values that may contain comma separated +headers into an array of headers with no comma separated values. + + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key +value pair will become an array. This function does not parse nested +PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` +will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. + + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` + +Build a query string from an array of key value pairs. + +This function can use the return value of `parse()` to build a query +string. This function does not modify the provided keys when an array is +encountered (like `http_build_query()` would). + + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(iterable $keys, $keys, array $data): array` + +Remove the items given by the keys, case insensitively from the data. + + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void` + +Copy the contents of a stream into another stream until the given number +of bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of +bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on +PHP's `hash_init` functions. + + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate +a message. + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an +error handler that checks for errors and throws an exception instead. + + +## `GuzzleHttp\Psr7\Utils::tryGetContents` + +`public static function tryGetContents(resource $stream): string` + +Safely gets the contents of a given stream. + +When stream_get_contents fails, PHP normally raises a warning. This +function adds an error handler that checks for errors and throws an +exception instead. + + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a UriInterface for the given value. + +This function accepts a string or UriInterface and returns a +UriInterface for the given value. If the value is already a +UriInterface, it is returned as-is. + + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the mimetype of a file by looking at its extension. + + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extensions to a mimetype. + + +## Upgrading from Function API + +The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://datatracker.ietf.org/doc/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://datatracker.ietf.org/doc/html/rfc3986#section-5.3). Usually this method does not need +to be called manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an +associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Cross-Origin Detection + +`GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin. + +### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin` + +`public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool` + +Determines if a modified URL should be considered cross-origin with respect to an original URL. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://datatracker.ietf.org/doc/html/rfc3986#section-5). This is for example also what web +browsers do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://datatracker.ietf.org/doc/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/composer.json b/php/libraries/composer/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 0000000..70293fc --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,93 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "request", + "response", + "message", + "stream", + "http", + "uri", + "url", + "psr-7" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/AppendStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 0000000..ee8f378 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,248 @@ +addStream($stream); + } + } + + public function __toString(): string + { + try { + $this->rewind(); + + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream): void + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + */ + public function close(): void + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell(): int + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + */ + public function getSize(): ?int + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof(): bool + { + return !$this->streams + || ($this->current >= count($this->streams) - 1 + && $this->streams[$this->current]->eof()); + } + + public function rewind(): void + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + .$i.' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + */ + public function read($length): string + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + ++$this->current; + } + + $result = $this->streams[$this->current]->read($remaining); + + if ($result === '') { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/BufferStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 0000000..2b0eb77 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,147 @@ +hwm = $hwm; + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close(): void + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize(): ?int + { + return strlen($this->buffer); + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return true; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof(): bool + { + return strlen($this->buffer) === 0; + } + + public function tell(): int + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length): string + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string): int + { + $this->buffer .= $string; + + if (strlen($this->buffer) >= $this->hwm) { + return 0; + } + + return strlen($string); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + if ($key === 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/CachingStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 0000000..f34722c --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,153 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize(): ?int + { + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence === SEEK_SET) { + $byte = $offset; + } elseif ($whence === SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence === SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length): string + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string): int + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof(): bool + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close(): void + { + $this->remoteStream->close(); + $this->stream->close(); + } + + private function cacheEntireStream(): int + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/DroppingStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 0000000..6e3d209 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,49 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string): int + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php new file mode 100644 index 0000000..3a08477 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php @@ -0,0 +1,14 @@ + */ + private $methods; + + /** + * @param array $methods Hash of method name to a callable. + */ + public function __construct(array $methods) + { + $this->methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_'.$name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + .'() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + ($this->_fn_close)(); + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup(): void + { + throw new \LogicException('FnStream should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::SLOTS, array_keys($methods)) as $diff) { + /** @var callable $callable */ + $callable = [$stream, $diff]; + $methods[$diff] = $callable; + } + + return new self($methods); + } + + public function __toString(): string + { + try { + /** @var string */ + return ($this->_fn___toString)(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function close(): void + { + ($this->_fn_close)(); + } + + public function detach() + { + return ($this->_fn_detach)(); + } + + public function getSize(): ?int + { + return ($this->_fn_getSize)(); + } + + public function tell(): int + { + return ($this->_fn_tell)(); + } + + public function eof(): bool + { + return ($this->_fn_eof)(); + } + + public function isSeekable(): bool + { + return ($this->_fn_isSeekable)(); + } + + public function rewind(): void + { + ($this->_fn_rewind)(); + } + + public function seek($offset, $whence = SEEK_SET): void + { + ($this->_fn_seek)($offset, $whence); + } + + public function isWritable(): bool + { + return ($this->_fn_isWritable)(); + } + + public function write($string): int + { + return ($this->_fn_write)($string); + } + + public function isReadable(): bool + { + return ($this->_fn_isReadable)(); + } + + public function read($length): string + { + return ($this->_fn_read)($length); + } + + public function getContents(): string + { + return ($this->_fn_getContents)(); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + return ($this->_fn_getMetadata)($key); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Header.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Header.php new file mode 100644 index 0000000..bbce8b0 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,134 @@ +]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + } + + return $params; + } + + /** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @deprecated Use self::splitList() instead. + */ + public static function normalize($header): array + { + $result = []; + foreach ((array) $header as $value) { + foreach (self::splitList($value) as $parsed) { + $result[] = $parsed; + } + } + + return $result; + } + + /** + * Splits a HTTP header defined to contain a comma-separated list into + * each individual value. Empty values will be removed. + * + * Example headers include 'accept', 'cache-control' and 'if-none-match'. + * + * This method must not be used to parse headers that are not defined as + * a list, such as 'user-agent' or 'set-cookie'. + * + * @param string|string[] $values Header value as returned by MessageInterface::getHeader() + * + * @return string[] + */ + public static function splitList($values): array + { + if (!\is_array($values)) { + $values = [$values]; + } + + $result = []; + foreach ($values as $value) { + if (!\is_string($value)) { + throw new \TypeError('$header must either be a string or an array containing strings.'); + } + + $v = ''; + $isQuoted = false; + $isEscaped = false; + for ($i = 0, $max = \strlen($value); $i < $max; ++$i) { + if ($isEscaped) { + $v .= $value[$i]; + $isEscaped = false; + + continue; + } + + if (!$isQuoted && $value[$i] === ',') { + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + + $v = ''; + continue; + } + + if ($isQuoted && $value[$i] === '\\') { + $isEscaped = true; + $v .= $value[$i]; + + continue; + } + if ($value[$i] === '"') { + $isQuoted = !$isQuoted; + $v .= $value[$i]; + + continue; + } + + $v .= $value[$i]; + } + + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/HttpFactory.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/HttpFactory.php new file mode 100644 index 0000000..73d17e3 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/HttpFactory.php @@ -0,0 +1,94 @@ +getSize(); + } + + return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); + } + + public function createStream(string $content = ''): StreamInterface + { + return Utils::streamFor($content); + } + + public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface + { + try { + $resource = Utils::tryFopen($file, $mode); + } catch (\RuntimeException $e) { + if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true)) { + throw new \InvalidArgumentException(sprintf('Invalid file opening mode "%s"', $mode), 0, $e); + } + + throw $e; + } + + return Utils::streamFor($resource); + } + + public function createStreamFromResource($resource): StreamInterface + { + return Utils::streamFor($resource); + } + + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + if (empty($method)) { + if (!empty($serverParams['REQUEST_METHOD'])) { + $method = $serverParams['REQUEST_METHOD']; + } else { + throw new \InvalidArgumentException('Cannot determine HTTP method'); + } + } + + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); + } + + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface + { + return new Response($code, [], null, '1.1', $reasonPhrase); + } + + public function createRequest(string $method, $uri): RequestInterface + { + return new Request($method, $uri); + } + + public function createUri(string $uri = ''): UriInterface + { + return new Uri($uri); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/InflateStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 0000000..e674c9a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,37 @@ + 15 + 32]); + $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 0000000..f6c8490 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,49 @@ +filename = $filename; + $this->mode = $mode; + + // unsetting the property forces the first access to go through + // __get(). + unset($this->stream); + } + + /** + * Creates the underlying stream lazily when required. + */ + protected function createStream(): StreamInterface + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/LimitStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 0000000..fb22325 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,157 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof(): bool + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit === -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + */ + public function getSize(): ?int + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit === -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + */ + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + */ + public function tell(): int + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset(int $offset): void + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + public function read($length): string + { + if ($this->limit === -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Message.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Message.php new file mode 100644 index 0000000..5561a51 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,246 @@ +getMethod().' ' + .$message->getRequestTarget()) + .' HTTP/'.$message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: ".$message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/'.$message->getProtocolVersion().' ' + .$message->getStatusCode().' ' + .$message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (is_string($name) && strtolower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: ".$value; + } + } else { + $msg .= "\r\n{$name}: ".implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n".$message->getBody(); + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + */ + public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string + { + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $body->rewind(); + $summary = $body->read($truncateAt); + $body->rewind(); + + if ($size > $truncateAt) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary) !== 0) { + return null; + } + + return $summary; + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message): void + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + */ + public static function parseMessage(string $message): array + { + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + $message = ltrim($message, "\r\n"); + + $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); + + if ($messageParts === false || count($messageParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); + } + + [$rawHeaders, $body] = $messageParts; + $rawHeaders .= "\r\n"; // Put back the delimiter we split previously + $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); + + if ($headerParts === false || count($headerParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing status line'); + } + + [$startLine, $rawHeaders] = $headerParts; + + if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { + // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 + $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); + } + + /** @var array[] $headerLines */ + $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4 + if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + /** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + */ + public static function parseRequestUri(string $path, array $headers): string + { + $hostKey = array_filter(array_keys($headers), function ($k) { + // Numeric array keys are converted to int by PHP. + $k = (string) $k; + + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme.'://'.$host.'/'.ltrim($path, '/'); + } + + /** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + */ + public static function parseRequest(string $message): RequestInterface + { + $data = self::parseMessage($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + */ + public static function parseResponse(string $message): ResponseInterface + { + $data = self::parseMessage($message); + // According to https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + // the space between status-code and reason-phrase is required. But + // browsers accept responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string: '.$data['start-line']); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + (int) $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + $parts[2] ?? null + ); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/MessageTrait.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 0000000..65dbc4b --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,265 @@ + array of values */ + private $headers = []; + + /** @var string[] Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface|null */ + private $stream; + + public function getProtocolVersion(): string + { + return $this->protocol; + } + + public function withProtocolVersion($version): MessageInterface + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + + return $new; + } + + public function getHeaders(): array + { + return $this->headers; + } + + public function hasHeader($header): bool + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header): array + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header): string + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header): MessageInterface + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody(): StreamInterface + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body): MessageInterface + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + + return $new; + } + + /** + * @param (string|string[])[] $headers + */ + private function setHeaders(array $headers): void + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + // Numeric array keys are converted to int by PHP. + $header = (string) $header; + + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * @param mixed $value + * + * @return string[] + */ + private function normalizeHeaderValue($value): array + { + if (!is_array($value)) { + return $this->trimAndValidateHeaderValues([$value]); + } + + if (count($value) === 0) { + throw new \InvalidArgumentException('Header value can not be an empty array.'); + } + + return $this->trimAndValidateHeaderValues($value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param mixed[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4 + */ + private function trimAndValidateHeaderValues(array $values): array + { + return array_map(function ($value) { + if (!is_scalar($value) && null !== $value) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be scalar or null but %s provided.', + is_object($value) ? get_class($value) : gettype($value) + )); + } + + $trimmed = trim((string) $value, " \t"); + $this->assertValue($trimmed); + + return $trimmed; + }, array_values($values)); + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + * + * @param mixed $header + */ + private function assertHeader($header): void + { + if (!is_string($header)) { + throw new \InvalidArgumentException(sprintf( + 'Header name must be a string but %s provided.', + is_object($header) ? get_class($header) : gettype($header) + )); + } + + if (!preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not valid header name.', $header) + ); + } + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + * + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * VCHAR = %x21-7E + * obs-text = %x80-FF + * obs-fold = CRLF 1*( SP / HTAB ) + */ + private function assertValue(string $value): void + { + // The regular expression intentionally does not support the obs-fold production, because as + // per RFC 7230#3.2.4: + // + // A sender MUST NOT generate a message that includes + // line folding (i.e., that has any field-value that contains a match to + // the obs-fold rule) unless the message is intended for packaging + // within the message/http media type. + // + // Clients must not send a request with line folding and a server sending folded headers is + // likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting + // folding is not likely to break any legitimate use case. + if (!preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not valid header value.', $value) + ); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/MimeType.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 0000000..b131bdb --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,1259 @@ + 'application/vnd.1000minds.decision-model+xml', + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gp', + '3gpp' => 'video/3gpp', + '3mf' => 'model/3mf', + '7z' => 'application/x-7z-compressed', + '7zip' => 'application/x-7z-compressed', + '123' => 'application/vnd.lotus-1-2-3', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/aac', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/vnd.nokia.n-gage.ac+xml', + 'ac3' => 'audio/ac3', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'adts' => 'audio/aac', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'age' => 'application/vnd.age', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/pdf', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'aml' => 'application/automationml-aml+xml', + 'amlx' => 'application/automationml-amlx+zip', + 'amr' => 'audio/amr', + 'apk' => 'application/vnd.android.package-archive', + 'apng' => 'image/apng', + 'appcache' => 'text/cache-manifest', + 'appinstaller' => 'application/appinstaller', + 'application' => 'application/x-ms-application', + 'appx' => 'application/appx', + 'appxbundle' => 'application/appxbundle', + 'apr' => 'application/vnd.lotus-approach', + 'arc' => 'application/x-freearc', + 'arj' => 'application/x-arj', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomdeleted' => 'application/atomdeleted+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/x-au', + 'avci' => 'image/avci', + 'avcs' => 'image/avcs', + 'avi' => 'video/x-msvideo', + 'avif' => 'image/avif', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azv' => 'image/vnd.airzip.accelerator.azv', + 'azw' => 'application/vnd.amazon.ebook', + 'b16' => 'image/vnd.pco.b16', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bdoc' => 'application/x-bdoc', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmml' => 'application/vnd.balsamiq.bmml+xml', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'bpmn' => 'application/octet-stream', + 'bsp' => 'model/vnd.valve.source.compiled-map', + 'btf' => 'image/prs.btif', + 'btif' => 'image/prs.btif', + 'buffer' => 'application/octet-stream', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cco' => 'application/x-cocoa', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdfx' => 'application/cdfx+xml', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdr' => 'application/cdr', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cjs' => 'application/node', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/octet-stream', + 'cld' => 'model/vnd.cld', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'coffee' => 'text/coffeescript', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpl' => 'application/cpl+xml', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'crx' => 'application/x-chrome-extension', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'csh' => 'application/x-csh', + 'csl' => 'application/vnd.citationstyles.style+xml', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'csr' => 'application/octet-stream', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cwl' => 'application/cwl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbf' => 'application/vnd.dbf', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'ddf' => 'application/vnd.syncml.dmddf+xml', + 'dds' => 'image/vnd.ms-dds', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dib' => 'image/bmp', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'disposition-notification' => 'message/disposition-notification', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/x-apple-diskimage', + 'dmn' => 'application/octet-stream', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dpx' => 'image/dpx', + 'dra' => 'audio/vnd.dra', + 'drle' => 'image/dicom-rle', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwd' => 'application/atsc-dwd+xml', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ear' => 'application/java-archive', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'image/emf', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emotionml' => 'application/emotionml+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'exi' => 'application/exi', + 'exp' => 'application/express', + 'exr' => 'image/aces', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/mp4', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fdt' => 'application/fdt+xml', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fits' => 'image/fits', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'fo' => 'application/vnd.software602.filler.form+xml', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'gdoc' => 'application/vnd.google-apps.document', + 'ged' => 'text/vnd.familysearch.gedcom', + 'geo' => 'application/vnd.dynageo', + 'geojson' => 'application/geo+json', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'glb' => 'model/gltf-binary', + 'gltf' => 'model/gltf+json', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gpg' => 'application/gpg-keys', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gsheet' => 'application/vnd.google-apps.spreadsheet', + 'gslides' => 'application/vnd.google-apps.presentation', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/gzip', + 'gzip' => 'application/gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hbs' => 'text/x-handlebars-template', + 'hdd' => 'application/x-virtualbox-hdd', + 'hdf' => 'application/x-hdf', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'hej2' => 'image/hej2k', + 'held' => 'application/atsc-held+xml', + 'hh' => 'text/x-c', + 'hjson' => 'application/hjson', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'hsj2' => 'image/hsj2', + 'htc' => 'text/x-component', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'img' => 'application/octet-stream', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ini' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'its' => 'application/its+xml', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jade' => 'text/jade', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'jardiff' => 'application/x-java-archive-diff', + 'java' => 'text/x-java-source', + 'jhc' => 'image/jphc', + 'jisp' => 'application/vnd.jisp', + 'jls' => 'image/jls', + 'jlt' => 'application/vnd.hp-jlyt', + 'jng' => 'image/x-jng', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpf' => 'image/jpx', + 'jpg' => 'image/jpeg', + 'jpg2' => 'image/jp2', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jph' => 'image/jph', + 'jpm' => 'video/jpm', + 'jpx' => 'image/jpx', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'json5' => 'application/json5', + 'jsonld' => 'application/ld+json', + 'jsonml' => 'application/jsonml+json', + 'jsx' => 'text/jsx', + 'jt' => 'model/jt', + 'jxr' => 'image/jxr', + 'jxra' => 'image/jxra', + 'jxrs' => 'image/jxrs', + 'jxs' => 'image/jxs', + 'jxsc' => 'image/jxsc', + 'jxsi' => 'image/jxsi', + 'jxss' => 'image/jxss', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kdb' => 'application/octet-stream', + 'kdbx' => 'application/x-keepass2', + 'key' => 'application/x-iwork-keynote-sffkey', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktx2' => 'image/ktx2', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'less' => 'text/less', + 'lgr' => 'application/lgr+xml', + 'lha' => 'application/octet-stream', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'litcoffee' => 'text/coffeescript', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lua' => 'text/x-lua', + 'luac' => 'application/x-lua-bytecode', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/octet-stream', + 'm1v' => 'video/mpeg', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'text/plain', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/x-m4a', + 'm4p' => 'application/mp4', + 'm4s' => 'video/iso.segment', + 'm4u' => 'application/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm21' => 'application/mp21', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'maei' => 'application/mmt-aei+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'manifest' => 'text/cache-manifest', + 'map' => 'application/json', + 'mar' => 'application/octet-stream', + 'markdown' => 'text/markdown', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'md' => 'text/markdown', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'mdx' => 'text/mdx', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mjs' => 'text/javascript', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mkd' => 'text/x-markdown', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mml' => 'text/mathml', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mp21' => 'application/mp21', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpd' => 'application/dash+xml', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpf' => 'application/media-policy-dataset+xml', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msg' => 'application/vnd.ms-outlook', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msix' => 'application/msix', + 'msixbundle' => 'application/msixbundle', + 'msl' => 'application/vnd.mobius.msl', + 'msm' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msty' => 'application/vnd.muvee.style', + 'mtl' => 'model/mtl', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musd' => 'application/mmt-usd+xml', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mvt' => 'application/vnd.mapbox-vector-tile', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxmf' => 'audio/mobile-xmf', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nq' => 'application/n-quads', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'nt' => 'application/n-triples', + 'ntf' => 'application/vnd.nitf', + 'numbers' => 'application/x-iwork-numbers-sffnumbers', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obgx' => 'application/vnd.openblox.game+xml', + 'obj' => 'model/obj', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogex' => 'model/vnd.opengex', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'opus' => 'audio/ogg', + 'org' => 'text/x-org', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'osm' => 'application/vnd.openstreetmap.data+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'font/otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'ova' => 'application/x-virtualbox-ova', + 'ovf' => 'application/x-virtualbox-ovf', + 'owl' => 'application/rdf+xml', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p7a' => 'application/x-pkcs7-signature', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'p10' => 'application/x-pkcs10', + 'p12' => 'application/x-pkcs12', + 'pac' => 'application/x-ns-proxy-autoconfig', + 'pages' => 'application/x-iwork-pages-sffpages', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/x-pilot', + 'pde' => 'text/x-processing', + 'pdf' => 'application/pdf', + 'pem' => 'application/x-x509-user-cert', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp', + 'phar' => 'application/octet-stream', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'pkpass' => 'application/vnd.apple.pkpass', + 'pl' => 'application/x-perl', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pm' => 'application/x-perl', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'model/prc', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'provx' => 'application/provenance+xml', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'application/x-photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'pti' => 'image/prs.pti', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyo' => 'model/vnd.pytha.pyox', + 'pyox' => 'model/vnd.pytha.pyox', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'raml' => 'application/raml+yaml', + 'rapd' => 'application/route-apd+xml', + 'rar' => 'application/x-rar', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'relo' => 'application/p2p-overlay+xml', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'audio/x-pn-realaudio', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'rng' => 'application/xml', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsa' => 'application/x-pkcs7', + 'rsat' => 'application/atsc-rsat+xml', + 'rsd' => 'application/rsd+xml', + 'rsheet' => 'application/urc-ressheet+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'run' => 'application/x-makeself', + 'rusd' => 'application/route-usd+xml', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sass' => 'text/x-sass', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scss' => 'text/x-scss', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'sea' => 'application/octet-stream', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'senmlx' => 'application/senml+xml', + 'sensmlx' => 'application/sensml+xml', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shex' => 'text/shex', + 'shf' => 'application/shf+xml', + 'shtml' => 'text/html', + 'sid' => 'image/x-mrsid-image', + 'sieve' => 'application/sieve', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'siv' => 'application/sieve', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slim' => 'text/slim', + 'slm' => 'text/slim', + 'sls' => 'application/route-s-tsid+xml', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spdx' => 'text/spdx', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'sst' => 'application/octet-stream', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'step' => 'application/STEP', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'model/stl', + 'stp' => 'application/STEP', + 'stpx' => 'model/step+xml', + 'stpxz' => 'model/step-xml+zip', + 'stpz' => 'model/step+zip', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'styl' => 'text/stylus', + 'stylus' => 'text/stylus', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'swidtag' => 'application/swid+xml', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 't38' => 'image/t38', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tap' => 'image/vnd.tencent.tap', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'td' => 'application/urc-targetdesc+xml', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tfx' => 'image/tiff-fx', + 'tga' => 'image/x-tga', + 'tgz' => 'application/x-tar', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tk' => 'application/x-tcl', + 'tmo' => 'application/vnd.tmobile-livetv', + 'toml' => 'application/toml', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trig' => 'application/trig', + 'trm' => 'application/x-msterminal', + 'ts' => 'video/mp2t', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'font/collection', + 'ttf' => 'font/ttf', + 'ttl' => 'text/turtle', + 'ttml' => 'application/ttml+xml', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u3d' => 'model/u3d', + 'u8dsn' => 'message/global-delivery-status', + 'u8hdr' => 'message/global-headers', + 'u8mdn' => 'message/global-disposition-notification', + 'u8msg' => 'message/global', + 'u32' => 'application/x-authorware-bin', + 'ubj' => 'application/ubjson', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uo' => 'application/vnd.uoml+xml', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'usda' => 'model/vnd.usda', + 'usdz' => 'model/vnd.usdz+zip', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vbox' => 'application/x-virtualbox-vbox', + 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vdi' => 'application/x-virtualbox-vdi', + 'vds' => 'model/vnd.sap.vds', + 'vhd' => 'application/x-virtualbox-vhd', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vlc' => 'application/videolan', + 'vmdk' => 'application/x-virtualbox-vmdk', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtf' => 'image/vnd.valve.source.texture', + 'vtt' => 'text/vtt', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wadl' => 'application/vnd.sun.wadl+xml', + 'war' => 'application/java-archive', + 'wasm' => 'application/wasm', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webapp' => 'application/x-web-app-manifest+json', + 'webm' => 'video/webm', + 'webmanifest' => 'application/manifest+json', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgsl' => 'text/wgsl', + 'wgt' => 'application/widget', + 'wif' => 'application/watcherinfo+xml', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'image/wmf', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + 'word' => 'application/msword', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsc' => 'message/vnd.wfa.wsc', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+fastinfoset', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d-vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'x32' => 'application/x-authorware-bin', + 'x_b' => 'model/vnd.parasolid.transmit.binary', + 'x_t' => 'model/vnd.parasolid.transmit.text', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xav' => 'application/xcap-att+xml', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xca' => 'application/xcap-caps+xml', + 'xcs' => 'application/calendar+xml', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xel' => 'application/xcap-el+xml', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtm' => 'application/vnd.pwg-xhtml-print+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/excel', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xns' => 'application/xcap-ns+xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsd' => 'application/xml', + 'xsf' => 'application/prs.xsf+xml', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'ymp' => 'text/x-suse-ymp', + 'z' => 'application/x-compress', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + 'zsh' => 'text/x-scriptzsh', + ]; + + /** + * Determines the mimetype of a file by looking at its extension. + * + * @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromFilename(string $filename): ?string + { + return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Maps a file extensions to a mimetype. + * + * @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromExtension(string $extension): ?string + { + return self::MIME_TYPES[strtolower($extension)] ?? null; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/MultipartStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 0000000..d23fba8 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,165 @@ +boundary = $boundary ?: bin2hex(random_bytes(20)); + $this->stream = $this->createStream($elements); + } + + public function getBoundary(): string + { + return $this->boundary; + } + + public function isWritable(): bool + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + * + * @param string[] $headers + */ + private function getHeaders(array $headers): string + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n".trim($str)."\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements = []): StreamInterface + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + if (!is_array($element)) { + throw new \UnexpectedValueException('An array is expected'); + } + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element): void + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = Utils::streamFor($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { + $element['filename'] = $uri; + } + } + + [$body, $headers] = $this->createElement( + $element['name'], + $element['contents'], + $element['filename'] ?? null, + $element['headers'] ?? [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + /** + * @param string[] $headers + * + * @return array{0: StreamInterface, 1: string[]} + */ + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array + { + // Set a default content-disposition header if one was no provided + $disposition = self::getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $name, + basename($filename) + ) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = self::getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = self::getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + $headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream'; + } + + return [$stream, $headers]; + } + + /** + * @param string[] $headers + */ + private static function getHeader(array $headers, string $key): ?string + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower((string) $k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..161a224 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,28 @@ +source = $source; + $this->size = $options['size'] ?? null; + $this->metadata = $options['metadata'] ?? []; + $this->buffer = new BufferStream(); + } + + public function __toString(): string + { + try { + return Utils::copyToString($this); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function close(): void + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = 0; + $this->source = null; + + return null; + } + + public function getSize(): ?int + { + return $this->size; + } + + public function tell(): int + { + return $this->tellPos; + } + + public function eof(): bool + { + return $this->source === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable(): bool + { + return false; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable(): bool + { + return true; + } + + public function read($length): string + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents(): string + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return $this->metadata[$key] ?? null; + } + + private function pump(int $length): void + { + if ($this->source !== null) { + do { + $data = ($this->source)($length); + if ($data === false || $data === null) { + $this->source = null; + + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Query.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Query.php new file mode 100644 index 0000000..8b94927 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,113 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + */ + public static function parse(string $str, $urlEncoding = true): array + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', (string) $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!array_key_exists($key, $result)) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? (int) $v : $v; + if ($v !== null) { + $qs .= '='.$encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? (int) $vv : $vv; + if ($vv !== null) { + $qs .= '='.$encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Request.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 0000000..faafe1a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,159 @@ +assertMethod($method); + if (!($uri instanceof UriInterface)) { + $uri = new Uri($uri); + } + + $this->method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget(): string + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target === '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?'.$this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget): RequestInterface + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + + return $new; + } + + public function getMethod(): string + { + return $this->method; + } + + public function withMethod($method): RequestInterface + { + $this->assertMethod($method); + $new = clone $this; + $new->method = strtoupper($method); + + return $new; + } + + public function getUri(): UriInterface + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost || !isset($this->headerNames['host'])) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri(): void + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':'.$port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: https://datatracker.ietf.org/doc/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } + + /** + * @param mixed $method + */ + private function assertMethod($method): void + { + if (!is_string($method) || $method === '') { + throw new InvalidArgumentException('Method must be a non-empty string.'); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Response.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 0000000..00f16e2 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,161 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase; + + /** @var int */ + private $statusCode; + + /** + * @param int $status Status code + * @param (string|string[])[] $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + int $status = 200, + array $headers = [], + $body = null, + string $version = '1.1', + string $reason = null + ) { + $this->assertStatusCodeRange($status); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { + $this->reasonPhrase = self::PHRASES[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getReasonPhrase(): string + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = ''): ResponseInterface + { + $this->assertStatusCodeIsInteger($code); + $code = (int) $code; + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { + $reasonPhrase = self::PHRASES[$new->statusCode]; + } + $new->reasonPhrase = (string) $reasonPhrase; + + return $new; + } + + /** + * @param mixed $statusCode + */ + private function assertStatusCodeIsInteger($statusCode): void + { + if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { + throw new \InvalidArgumentException('Status code must be an integer value.'); + } + } + + private function assertStatusCodeRange(int $statusCode): void + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Rfc7230.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Rfc7230.php new file mode 100644 index 0000000..8219dba --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Rfc7230.php @@ -0,0 +1,23 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/ServerRequest.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 0000000..3cc9534 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,340 @@ +serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files An array which respect $_FILES structure + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files): array + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return UploadedFileInterface|UploadedFileInterface[] + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []): array + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key] ?? null, + 'error' => $files['error'][$key] ?? null, + 'name' => $files['name'][$key] ?? null, + 'type' => $files['type'][$key] ?? null, + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + */ + public static function fromGlobals(): ServerRequestInterface + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + $headers = getallheaders(); + $uri = self::getUriFromGlobals(); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + private static function extractHostAndPortFromAuthority(string $authority): array + { + $uri = 'http://'.$authority; + $parts = parse_url($uri); + if (false === $parts) { + return [null, null]; + } + + $host = $parts['host'] ?? null; + $port = $parts['port'] ?? null; + + return [$host, $port]; + } + + /** + * Get a Uri populated with values from $_SERVER. + */ + public static function getUriFromGlobals(): UriInterface + { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + [$host, $port] = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); + if ($host !== null) { + $uri = $uri->withHost($host); + } + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + public function getServerParams(): array + { + return $this->serverParams; + } + + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + public function getCookieParams(): array + { + return $this->cookieParams; + } + + public function withCookieParams(array $cookies): ServerRequestInterface + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + public function getQueryParams(): array + { + return $this->queryParams; + } + + public function withQueryParams(array $query): ServerRequestInterface + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * @return array|object|null + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data): ServerRequestInterface + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @return mixed + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + public function withAttribute($attribute, $value): ServerRequestInterface + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + public function withoutAttribute($attribute): ServerRequestInterface + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Stream.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 0000000..0aff9b2 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,283 @@ +size = $options['size']; + } + + $this->customMetadata = $options['metadata'] ?? []; + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = (bool) preg_match(self::READABLE_MODES, $meta['mode']); + $this->writable = (bool) preg_match(self::WRITABLE_MODES, $meta['mode']); + $this->uri = $this->getMetadata('uri'); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function getContents(): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + + return Utils::tryGetContents($this->stream); + } + + public function close(): void + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize(): ?int + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (is_array($stats) && isset($stats['size'])) { + $this->size = $stats['size']; + + return $this->size; + } + + return null; + } + + public function isReadable(): bool + { + return $this->readable; + } + + public function isWritable(): bool + { + return $this->writable; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function eof(): bool + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell(): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $whence = (int) $whence; + + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + .$offset.' with whence '.var_export($whence, true)); + } + } + + public function read($length): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + try { + $string = fread($this->stream, $length); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to read from stream', 0, $e); + } + + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return $meta[$key] ?? null; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..601c13a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,156 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @return StreamInterface + */ + public function __get(string $name) + { + if ($name === 'stream') { + $this->stream = $this->createStream(); + + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @return mixed + */ + public function __call(string $method, array $args) + { + /** @var callable $callable */ + $callable = [$this->stream, $method]; + $result = ($callable)(...$args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close(): void + { + $this->stream->close(); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int + { + return $this->stream->getSize(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function read($length): string + { + return $this->stream->read($length); + } + + public function write($string): int + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @throws \BadMethodCallException + */ + protected function createStream(): StreamInterface + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..ae85388 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,203 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + .'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream)); + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream], + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register(): void + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read(int $count): string + { + return $this->stream->read($count); + } + + public function stream_write(string $data): int + { + return $this->stream->write($data); + } + + public function stream_tell(): int + { + return $this->stream->tell(); + } + + public function stream_eof(): bool + { + return $this->stream->eof(); + } + + public function stream_seek(int $offset, int $whence): bool + { + $this->stream->seek($offset, $whence); + + return true; + } + + /** + * @return resource|false + */ + public function stream_cast(int $cast_as) + { + $stream = clone $this->stream; + $resource = $stream->detach(); + + return $resource ?? false; + } + + /** + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } + */ + public function stream_stat(): array + { + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188, + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + ]; + } + + /** + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } + */ + public function url_stat(string $path, int $flags): array + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + ]; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/UploadedFile.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 0000000..b267199 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,211 @@ +setError($errorStatus); + $this->size = $size; + $this->clientFilename = $clientFilename; + $this->clientMediaType = $clientMediaType; + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param StreamInterface|string|resource $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile): void + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @throws InvalidArgumentException + */ + private function setError(int $error): void + { + if (false === in_array($error, UploadedFile::ERRORS, true)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + private static function isStringNotEmpty($param): bool + { + return is_string($param) && false === empty($param); + } + + /** + * Return true if there is no upload error + */ + private function isOk(): bool + { + return $this->error === UPLOAD_ERR_OK; + } + + public function isMoved(): bool + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive(): void + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + public function getStream(): StreamInterface + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + /** @var string $file */ + $file = $this->file; + + return new LazyOpenStream($file, 'r+'); + } + + public function moveTo($targetPath): void + { + $this->validateActive(); + + if (false === self::isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = PHP_SAPI === 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + Utils::copyToStream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + public function getSize(): ?int + { + return $this->size; + } + + public function getError(): int + { + return $this->error; + } + + public function getClientFilename(): ?string + { + return $this->clientFilename; + } + + public function getClientMediaType(): ?string + { + return $this->clientMediaType; + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Uri.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 0000000..f1feee8 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,743 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + /** + * Unreserved characters for use in a regex. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.3 + */ + private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~'; + + /** + * Sub-delims for use in a regex. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 + */ + private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;='; + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** @var string|null String representation */ + private $composedComponents; + + public function __construct(string $uri = '') + { + if ($uri !== '') { + $parts = self::parse($uri); + if ($parts === false) { + throw new MalformedUriException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + + /** + * UTF-8 aware \parse_url() replacement. + * + * The internal function produces broken output for non ASCII domain names + * (IDN) when used with locales other than "C". + * + * On the other hand, cURL understands IDN correctly only when UTF-8 locale + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). + * + * @see https://bugs.php.net/bug.php?id=52923 + * @see https://www.php.net/manual/en/function.parse-url.php#114817 + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING + * + * @return array|false + */ + private static function parse(string $url) + { + // If IPv6 + $prefix = ''; + if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) { + /** @var array{0:string, 1:string, 2:string} $matches */ + $prefix = $matches[1]; + $url = $matches[2]; + } + + /** @var string */ + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%usD', + static function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $result = parse_url($prefix.$encodedUrl); + + if ($result === false) { + return false; + } + + return array_map('urldecode', $result); + } + + public function __toString(): string + { + if ($this->composedComponents === null) { + $this->composedComponents = self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + return $this->composedComponents; + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3 + */ + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme.':'; + } + + if ($authority != '' || $scheme === 'file') { + $uri .= '//'.$authority; + } + + if ($authority != '' && $path != '' && $path[0] != '/') { + $path = '/'.$path; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?'.$query; + } + + if ($fragment != '') { + $uri .= '#'.$fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + */ + public static function isDefaultPort(UriInterface $uri): bool + { + return $uri->getPort() === null + || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri): bool + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + */ + public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + */ + public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple specific query string values. + * + * It has the same behavior as withQueryValue() but for an associative array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param (string|null)[] $keyValueArray Associative array of key and values + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @see https://www.php.net/manual/en/function.parse-url.php + * + * @throws MalformedUriException If the components do not form a valid URI. + */ + public static function fromParts(array $parts): UriInterface + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getAuthority(): string + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo.'@'.$authority; + } + + if ($this->port !== null) { + $authority .= ':'.$this->port; + } + + return $authority; + } + + public function getUserInfo(): string + { + return $this->userInfo; + } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): ?int + { + return $this->port; + } + + public function getPath(): string + { + return $this->path; + } + + public function getQuery(): string + { + return $this->query; + } + + public function getFragment(): string + { + return $this->fragment; + } + + public function withScheme($scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null): UriInterface + { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':'.$this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withHost($host): UriInterface + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withPort($port): UriInterface + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path): UriInterface + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withQuery($query): UriInterface + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + $new->composedComponents = null; + + return $new; + } + + public function withFragment($fragment): UriInterface + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + $new->composedComponents = null; + + return $new; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts): void + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':'.$this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @param mixed $scheme + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme): string + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $component + * + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent($component): string + { + if (!is_string($component)) { + throw new \InvalidArgumentException('User info must be a string'); + } + + return preg_replace_callback( + '/(?:[^%'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.']+|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $component + ); + } + + /** + * @param mixed $host + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host): string + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $port + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port): ?int + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (0 > $port || 0xFFFF < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param (string|int)[] $keys + * + * @return string[] + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys): array + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map(function ($k): string { + return rawurldecode((string) $k); + }, $keys); + + return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + private static function generateQueryString(string $key, ?string $value): string + { + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); + + if ($value !== null) { + $queryString .= '='.strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); + } + + return $queryString; + } + + private function removeDefaultPort(): void + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param mixed $path + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path): string + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.'%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param mixed $str + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str): string + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match): string + { + return rawurlencode($match[0]); + } + + private function validateState(): void + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriComparator.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriComparator.php new file mode 100644 index 0000000..70c582a --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriComparator.php @@ -0,0 +1,52 @@ +getHost(), $modified->getHost()) !== 0) { + return true; + } + + if ($original->getScheme() !== $modified->getScheme()) { + return true; + } + + if (self::computePort($original) !== self::computePort($modified)) { + return true; + } + + return false; + } + + private static function computePort(UriInterface $uri): int + { + $port = $uri->getPort(); + + if (null !== $port) { + return $port; + } + + return 'https' === $uri->getScheme() ? 443 : 80; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 0000000..e174557 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,220 @@ +getPath() === '' + && ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri): UriInterface + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match): string { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match): string { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriResolver.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 0000000..3737be1 --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,211 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/'.$rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1).$rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + */ + public static function relativize(UriInterface $base, UriInterface $target): UriInterface + { + if ($target->getScheme() !== '' + && ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + /** @var string $lastSegment */ + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target): string + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)).implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/php/libraries/composer/vendor/guzzlehttp/psr7/src/Utils.php b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 0000000..bf5ea9d --- /dev/null +++ b/php/libraries/composer/vendor/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,463 @@ + $v) { + if (!in_array(strtolower((string) $k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void + { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, int $maxLen = -1): string + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + if ($buf === '') { + break; + } + $buffer .= $buf; + } + + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + if ($buf === '') { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based + * on PHP's `hash_init` functions. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + */ + public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface + { + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':'.$port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + $new = (new ServerRequest( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion(), + $request->getServerParams() + )) + ->withParsedBody($request->getParsedBody()) + ->withQueryParams($request->getQueryParams()) + ->withCookieParams($request->getCookieParams()) + ->withUploadedFiles($request->getUploadedFiles()); + + foreach ($request->getAttributes() as $key => $value) { + $new = $new->withAttribute($key, $value); + } + + return $new; + } + + return new Request( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion() + ); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + */ + public static function readLine(StreamInterface $stream, int $maxLength = null): string + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + if ('' === ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the contents. + * - `resource`: Creates a stream object that wraps the given PHP stream resource. + * - `Iterator`: If the provided value implements `Iterator`, then a read-only + * stream object will be created that wraps the given iterable. Each time the + * stream is read from, data from the iterator will fill a buffer and will be + * continuously called until the buffer is equal to the requested read size. + * Subsequent read calls will first read from the buffer and then call `next` + * on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` method, + * the object will be cast to a string and then a stream will be returned that + * uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable` When a callable is passed, a read-only stream object will be + * created that invokes the given callable. The callable is invoked with the + * number of suggested bytes to read. The callable can return any number of + * bytes, but MUST return `false` when there is no more data to return. The + * stream object that wraps the callable will invoke the callable until the + * number of requested bytes are available. Any additional bytes will be + * buffered and used in subsequent reads. + * + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data + * @param array{size?: int, metadata?: array} $options Additional options + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []): StreamInterface + { + if (is_scalar($resource)) { + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, (string) $resource); + fseek($stream, 0); + } + + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + + /** @var resource $resource */ + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + stream_copy_to_stream($resource, $stream); + fseek($stream, 0); + $resource = $stream; + } + + return new Stream($resource, $options); + case 'object': + /** @var object $resource */ + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return self::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: '.gettype($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen(string $filename, string $mode) + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $errstr + )); + + return true; + }); + + try { + /** @var resource $handle */ + $handle = fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; + } + + /** + * Safely gets the contents of a given stream. + * + * When stream_get_contents fails, PHP normally raises a warning. This + * function adds an error handler that checks for errors and throws an + * exception instead. + * + * @param resource $stream + * + * @throws \RuntimeException if the stream cannot be read + */ + public static function tryGetContents($stream): string + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $errstr + )); + + return true; + }); + + try { + /** @var string|false $contents */ + $contents = stream_get_contents($stream); + + if ($contents === false) { + $ex = new \RuntimeException('Unable to read stream contents'); + } + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $contents; + } + + /** + * Returns a UriInterface for the given value. + * + * This function accepts a string or UriInterface and returns a + * UriInterface for the given value. If the value is already a + * UriInterface, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/README.md b/php/libraries/composer/vendor/laravel/framework/README.md new file mode 100644 index 0000000..6e9702b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/README.md @@ -0,0 +1,45 @@ +

+ +

+Build Status +Total Downloads +Latest Stable Version +License +

+ +## About Laravel + +> **Note:** This repository contains the core code of the Laravel framework. If you want to build an application using Laravel, visit the main [Laravel repository](https://github.com/laravel/laravel). + +Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as: + +- [Simple, fast routing engine](https://laravel.com/docs/routing). +- [Powerful dependency injection container](https://laravel.com/docs/container). +- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage. +- Database agnostic [schema migrations](https://laravel.com/docs/migrations). +- [Robust background job processing](https://laravel.com/docs/queues). +- [Real-time event broadcasting](https://laravel.com/docs/broadcasting). + +Laravel is accessible, yet powerful, providing tools needed for large, robust applications. A superb combination of simplicity, elegance, and innovation gives you a complete toolset required to build any application with which you are tasked. + +## Learning Laravel + +Laravel has the most extensive and thorough documentation and video tutorial library of any modern web application framework. The [Laravel documentation](https://laravel.com/docs) is in-depth and complete, making it a breeze to get started learning the framework. + +If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 1100 video tutorials covering a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library. + +## Contributing + +Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +Please review [our security policy](https://github.com/laravel/framework/security/policy) on how to report security vulnerabilities. + +## License + +The Laravel framework is open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/php/libraries/composer/vendor/laravel/framework/composer.json b/php/libraries/composer/vendor/laravel/framework/composer.json new file mode 100644 index 0000000..ea01401 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/composer.json @@ -0,0 +1,166 @@ +{ + "name": "laravel/framework", + "description": "The Laravel Framework.", + "keywords": ["framework", "laravel"], + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "ext-mbstring": "*", + "ext-openssl": "*", + "doctrine/inflector": "^1.4|^2.0", + "dragonmantank/cron-expression": "^3.0.2", + "egulias/email-validator": "^2.1.10", + "laravel/serializable-closure": "^1.0", + "league/commonmark": "^1.3|^2.0.2", + "league/flysystem": "^1.1", + "monolog/monolog": "^2.0", + "nesbot/carbon": "^2.53.1", + "opis/closure": "^3.6", + "psr/container": "^1.0", + "psr/log": "^1.0|^2.0", + "psr/simple-cache": "^1.0", + "ramsey/uuid": "^4.2.2", + "swiftmailer/swiftmailer": "^6.3", + "symfony/console": "^5.4", + "symfony/error-handler": "^5.4", + "symfony/finder": "^5.4", + "symfony/http-foundation": "^5.4", + "symfony/http-kernel": "^5.4", + "symfony/mime": "^5.4", + "symfony/process": "^5.4", + "symfony/routing": "^5.4", + "symfony/var-dumper": "^5.4", + "tijsverkoyen/css-to-inline-styles": "^2.2.2", + "vlucas/phpdotenv": "^5.4.1", + "voku/portable-ascii": "^1.6.1" + }, + "replace": { + "illuminate/auth": "self.version", + "illuminate/broadcasting": "self.version", + "illuminate/bus": "self.version", + "illuminate/cache": "self.version", + "illuminate/collections": "self.version", + "illuminate/config": "self.version", + "illuminate/console": "self.version", + "illuminate/container": "self.version", + "illuminate/contracts": "self.version", + "illuminate/cookie": "self.version", + "illuminate/database": "self.version", + "illuminate/encryption": "self.version", + "illuminate/events": "self.version", + "illuminate/filesystem": "self.version", + "illuminate/hashing": "self.version", + "illuminate/http": "self.version", + "illuminate/log": "self.version", + "illuminate/macroable": "self.version", + "illuminate/mail": "self.version", + "illuminate/notifications": "self.version", + "illuminate/pagination": "self.version", + "illuminate/pipeline": "self.version", + "illuminate/queue": "self.version", + "illuminate/redis": "self.version", + "illuminate/routing": "self.version", + "illuminate/session": "self.version", + "illuminate/support": "self.version", + "illuminate/testing": "self.version", + "illuminate/translation": "self.version", + "illuminate/validation": "self.version", + "illuminate/view": "self.version" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.198.1", + "doctrine/dbal": "^2.13.3|^3.1.4", + "filp/whoops": "^2.14.3", + "guzzlehttp/guzzle": "^6.5.5|^7.0.1", + "league/flysystem-cached-adapter": "^1.0", + "mockery/mockery": "^1.4.4", + "orchestra/testbench-core": "^6.27", + "pda/pheanstalk": "^4.0", + "phpunit/phpunit": "^8.5.19|^9.5.8", + "predis/predis": "^1.1.9", + "symfony/cache": "^5.4" + }, + "provide": { + "psr/container-implementation": "1.0", + "psr/simple-cache-implementation": "1.0" + }, + "conflict": { + "tightenco/collect": "<5.5.33" + }, + "autoload": { + "files": [ + "src/Illuminate/Collections/helpers.php", + "src/Illuminate/Events/functions.php", + "src/Illuminate/Foundation/helpers.php", + "src/Illuminate/Support/helpers.php" + ], + "psr-4": { + "Illuminate\\": "src/Illuminate/", + "Illuminate\\Support\\": ["src/Illuminate/Macroable/", "src/Illuminate/Collections/"] + } + }, + "autoload-dev": { + "files": [ + "tests/Database/stubs/MigrationCreatorFakeMigration.php" + ], + "psr-4": { + "Illuminate\\Tests\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "ext-bcmath": "Required to use the multiple_of validation rule.", + "ext-ftp": "Required to use the Flysystem FTP driver.", + "ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().", + "ext-memcached": "Required to use the memcache cache driver.", + "ext-pcntl": "Required to use all features of the queue worker.", + "ext-posix": "Required to use all features of the queue worker.", + "ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).", + "ably/ably-php": "Required to use the Ably broadcast driver (^1.0).", + "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.198.1).", + "brianium/paratest": "Required to run tests in parallel (^6.0).", + "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.13.3|^3.1.4).", + "filp/whoops": "Required for friendly error pages in development (^2.14.3).", + "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", + "guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.5.5|^7.0.1).", + "laravel/tinker": "Required to use the tinker console command (^2.0).", + "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", + "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", + "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", + "mockery/mockery": "Required to use mocking (^1.4.4).", + "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", + "pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).", + "phpunit/phpunit": "Required to use assertions and run tests (^8.5.19|^9.5.8).", + "predis/predis": "Required to use the predis connector (^1.1.9).", + "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", + "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0|^5.0|^6.0|^7.0).", + "symfony/cache": "Required to PSR-6 cache bridge (^5.4).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^5.4).", + "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0).", + "wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)." + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "composer/package-versions-deprecated": true + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/AuthorizationException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/AuthorizationException.php new file mode 100644 index 0000000..7fe6ceb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/AuthorizationException.php @@ -0,0 +1,64 @@ +code = $code ?: 0; + } + + /** + * Get the response from the gate. + * + * @return \Illuminate\Auth\Access\Response + */ + public function response() + { + return $this->response; + } + + /** + * Set the response from the gate. + * + * @param \Illuminate\Auth\Access\Response $response + * @return $this + */ + public function setResponse($response) + { + $this->response = $response; + + return $this; + } + + /** + * Create a deny response object from this exception. + * + * @return \Illuminate\Auth\Access\Response + */ + public function toResponse() + { + return Response::deny($this->message, $this->code); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/Events/GateEvaluated.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/Events/GateEvaluated.php new file mode 100644 index 0000000..f77a9c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/Events/GateEvaluated.php @@ -0,0 +1,51 @@ +user = $user; + $this->ability = $ability; + $this->result = $result; + $this->arguments = $arguments; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php new file mode 100644 index 0000000..fe8d93f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php @@ -0,0 +1,875 @@ +policies = $policies; + $this->container = $container; + $this->abilities = $abilities; + $this->userResolver = $userResolver; + $this->afterCallbacks = $afterCallbacks; + $this->beforeCallbacks = $beforeCallbacks; + $this->guessPolicyNamesUsingCallback = $guessPolicyNamesUsingCallback; + } + + /** + * Determine if a given ability has been defined. + * + * @param string|array $ability + * @return bool + */ + public function has($ability) + { + $abilities = is_array($ability) ? $ability : func_get_args(); + + foreach ($abilities as $ability) { + if (! isset($this->abilities[$ability])) { + return false; + } + } + + return true; + } + + /** + * Perform an on-demand authorization check. Throw an authorization exception if the condition or callback is false. + * + * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition + * @param string|null $message + * @param string|null $code + * @return \Illuminate\Auth\Access\Response + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function allowIf($condition, $message = null, $code = null) + { + return $this->authorizeOnDemand($condition, $message, $code, true); + } + + /** + * Perform an on-demand authorization check. Throw an authorization exception if the condition or callback is true. + * + * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition + * @param string|null $message + * @param string|null $code + * @return \Illuminate\Auth\Access\Response + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function denyIf($condition, $message = null, $code = null) + { + return $this->authorizeOnDemand($condition, $message, $code, false); + } + + /** + * Authorize a given condition or callback. + * + * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition + * @param string|null $message + * @param string|null $code + * @param bool $allowWhenResponseIs + * @return \Illuminate\Auth\Access\Response + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + protected function authorizeOnDemand($condition, $message, $code, $allowWhenResponseIs) + { + $user = $this->resolveUser(); + + if ($condition instanceof Closure) { + $response = $this->canBeCalledWithUser($user, $condition) + ? $condition($user) + : new Response(false, $message, $code); + } else { + $response = $condition; + } + + return with($response instanceof Response ? $response : new Response( + (bool) $response === $allowWhenResponseIs, $message, $code + ))->authorize(); + } + + /** + * Define a new ability. + * + * @param string $ability + * @param callable|string $callback + * @return $this + * + * @throws \InvalidArgumentException + */ + public function define($ability, $callback) + { + if (is_array($callback) && isset($callback[0]) && is_string($callback[0])) { + $callback = $callback[0].'@'.$callback[1]; + } + + if (is_callable($callback)) { + $this->abilities[$ability] = $callback; + } elseif (is_string($callback)) { + $this->stringCallbacks[$ability] = $callback; + + $this->abilities[$ability] = $this->buildAbilityCallback($ability, $callback); + } else { + throw new InvalidArgumentException("Callback must be a callable or a 'Class@method' string."); + } + + return $this; + } + + /** + * Define abilities for a resource. + * + * @param string $name + * @param string $class + * @param array|null $abilities + * @return $this + */ + public function resource($name, $class, array $abilities = null) + { + $abilities = $abilities ?: [ + 'viewAny' => 'viewAny', + 'view' => 'view', + 'create' => 'create', + 'update' => 'update', + 'delete' => 'delete', + ]; + + foreach ($abilities as $ability => $method) { + $this->define($name.'.'.$ability, $class.'@'.$method); + } + + return $this; + } + + /** + * Create the ability callback for a callback string. + * + * @param string $ability + * @param string $callback + * @return \Closure + */ + protected function buildAbilityCallback($ability, $callback) + { + return function () use ($ability, $callback) { + if (Str::contains($callback, '@')) { + [$class, $method] = Str::parseCallback($callback); + } else { + $class = $callback; + } + + $policy = $this->resolvePolicy($class); + + $arguments = func_get_args(); + + $user = array_shift($arguments); + + $result = $this->callPolicyBefore( + $policy, $user, $ability, $arguments + ); + + if (! is_null($result)) { + return $result; + } + + return isset($method) + ? $policy->{$method}(...func_get_args()) + : $policy(...func_get_args()); + }; + } + + /** + * Define a policy class for a given class type. + * + * @param string $class + * @param string $policy + * @return $this + */ + public function policy($class, $policy) + { + $this->policies[$class] = $policy; + + return $this; + } + + /** + * Register a callback to run before all Gate checks. + * + * @param callable $callback + * @return $this + */ + public function before(callable $callback) + { + $this->beforeCallbacks[] = $callback; + + return $this; + } + + /** + * Register a callback to run after all Gate checks. + * + * @param callable $callback + * @return $this + */ + public function after(callable $callback) + { + $this->afterCallbacks[] = $callback; + + return $this; + } + + /** + * Determine if the given ability should be granted for the current user. + * + * @param string $ability + * @param array|mixed $arguments + * @return bool + */ + public function allows($ability, $arguments = []) + { + return $this->check($ability, $arguments); + } + + /** + * Determine if the given ability should be denied for the current user. + * + * @param string $ability + * @param array|mixed $arguments + * @return bool + */ + public function denies($ability, $arguments = []) + { + return ! $this->allows($ability, $arguments); + } + + /** + * Determine if all of the given abilities should be granted for the current user. + * + * @param iterable|string $abilities + * @param array|mixed $arguments + * @return bool + */ + public function check($abilities, $arguments = []) + { + return collect($abilities)->every(function ($ability) use ($arguments) { + return $this->inspect($ability, $arguments)->allowed(); + }); + } + + /** + * Determine if any one of the given abilities should be granted for the current user. + * + * @param iterable|string $abilities + * @param array|mixed $arguments + * @return bool + */ + public function any($abilities, $arguments = []) + { + return collect($abilities)->contains(function ($ability) use ($arguments) { + return $this->check($ability, $arguments); + }); + } + + /** + * Determine if all of the given abilities should be denied for the current user. + * + * @param iterable|string $abilities + * @param array|mixed $arguments + * @return bool + */ + public function none($abilities, $arguments = []) + { + return ! $this->any($abilities, $arguments); + } + + /** + * Determine if the given ability should be granted for the current user. + * + * @param string $ability + * @param array|mixed $arguments + * @return \Illuminate\Auth\Access\Response + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function authorize($ability, $arguments = []) + { + return $this->inspect($ability, $arguments)->authorize(); + } + + /** + * Inspect the user for the given ability. + * + * @param string $ability + * @param array|mixed $arguments + * @return \Illuminate\Auth\Access\Response + */ + public function inspect($ability, $arguments = []) + { + try { + $result = $this->raw($ability, $arguments); + + if ($result instanceof Response) { + return $result; + } + + return $result ? Response::allow() : Response::deny(); + } catch (AuthorizationException $e) { + return $e->toResponse(); + } + } + + /** + * Get the raw result from the authorization callback. + * + * @param string $ability + * @param array|mixed $arguments + * @return mixed + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function raw($ability, $arguments = []) + { + $arguments = Arr::wrap($arguments); + + $user = $this->resolveUser(); + + // First we will call the "before" callbacks for the Gate. If any of these give + // back a non-null response, we will immediately return that result in order + // to let the developers override all checks for some authorization cases. + $result = $this->callBeforeCallbacks( + $user, $ability, $arguments + ); + + if (is_null($result)) { + $result = $this->callAuthCallback($user, $ability, $arguments); + } + + // After calling the authorization callback, we will call the "after" callbacks + // that are registered with the Gate, which allows a developer to do logging + // if that is required for this application. Then we'll return the result. + return tap($this->callAfterCallbacks( + $user, $ability, $arguments, $result + ), function ($result) use ($user, $ability, $arguments) { + $this->dispatchGateEvaluatedEvent($user, $ability, $arguments, $result); + }); + } + + /** + * Determine whether the callback/method can be called with the given user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param \Closure|string|array $class + * @param string|null $method + * @return bool + */ + protected function canBeCalledWithUser($user, $class, $method = null) + { + if (! is_null($user)) { + return true; + } + + if (! is_null($method)) { + return $this->methodAllowsGuests($class, $method); + } + + if (is_array($class)) { + $className = is_string($class[0]) ? $class[0] : get_class($class[0]); + + return $this->methodAllowsGuests($className, $class[1]); + } + + return $this->callbackAllowsGuests($class); + } + + /** + * Determine if the given class method allows guests. + * + * @param string $class + * @param string $method + * @return bool + */ + protected function methodAllowsGuests($class, $method) + { + try { + $reflection = new ReflectionClass($class); + + $method = $reflection->getMethod($method); + } catch (Exception $e) { + return false; + } + + if ($method) { + $parameters = $method->getParameters(); + + return isset($parameters[0]) && $this->parameterAllowsGuests($parameters[0]); + } + + return false; + } + + /** + * Determine if the callback allows guests. + * + * @param callable $callback + * @return bool + * + * @throws \ReflectionException + */ + protected function callbackAllowsGuests($callback) + { + $parameters = (new ReflectionFunction($callback))->getParameters(); + + return isset($parameters[0]) && $this->parameterAllowsGuests($parameters[0]); + } + + /** + * Determine if the given parameter allows guests. + * + * @param \ReflectionParameter $parameter + * @return bool + */ + protected function parameterAllowsGuests($parameter) + { + return ($parameter->hasType() && $parameter->allowsNull()) || + ($parameter->isDefaultValueAvailable() && is_null($parameter->getDefaultValue())); + } + + /** + * Resolve and call the appropriate authorization callback. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param string $ability + * @param array $arguments + * @return bool + */ + protected function callAuthCallback($user, $ability, array $arguments) + { + $callback = $this->resolveAuthCallback($user, $ability, $arguments); + + return $callback($user, ...$arguments); + } + + /** + * Call all of the before callbacks and return if a result is given. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param string $ability + * @param array $arguments + * @return bool|null + */ + protected function callBeforeCallbacks($user, $ability, array $arguments) + { + foreach ($this->beforeCallbacks as $before) { + if (! $this->canBeCalledWithUser($user, $before)) { + continue; + } + + if (! is_null($result = $before($user, $ability, $arguments))) { + return $result; + } + } + } + + /** + * Call all of the after callbacks with check result. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string $ability + * @param array $arguments + * @param bool $result + * @return bool|null + */ + protected function callAfterCallbacks($user, $ability, array $arguments, $result) + { + foreach ($this->afterCallbacks as $after) { + if (! $this->canBeCalledWithUser($user, $after)) { + continue; + } + + $afterResult = $after($user, $ability, $result, $arguments); + + $result = $result ?? $afterResult; + } + + return $result; + } + + /** + * Dispatch a gate evaluation event. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param string $ability + * @param array $arguments + * @param bool|null $result + * @return void + */ + protected function dispatchGateEvaluatedEvent($user, $ability, array $arguments, $result) + { + if ($this->container->bound(Dispatcher::class)) { + $this->container->make(Dispatcher::class)->dispatch( + new Events\GateEvaluated($user, $ability, $result, $arguments) + ); + } + } + + /** + * Resolve the callable for the given ability and arguments. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param string $ability + * @param array $arguments + * @return callable + */ + protected function resolveAuthCallback($user, $ability, array $arguments) + { + if (isset($arguments[0]) && + ! is_null($policy = $this->getPolicyFor($arguments[0])) && + $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)) { + return $callback; + } + + if (isset($this->stringCallbacks[$ability])) { + [$class, $method] = Str::parseCallback($this->stringCallbacks[$ability]); + + if ($this->canBeCalledWithUser($user, $class, $method ?: '__invoke')) { + return $this->abilities[$ability]; + } + } + + if (isset($this->abilities[$ability]) && + $this->canBeCalledWithUser($user, $this->abilities[$ability])) { + return $this->abilities[$ability]; + } + + return function () { + // + }; + } + + /** + * Get a policy instance for a given class. + * + * @param object|string $class + * @return mixed + */ + public function getPolicyFor($class) + { + if (is_object($class)) { + $class = get_class($class); + } + + if (! is_string($class)) { + return; + } + + if (isset($this->policies[$class])) { + return $this->resolvePolicy($this->policies[$class]); + } + + foreach ($this->guessPolicyName($class) as $guessedPolicy) { + if (class_exists($guessedPolicy)) { + return $this->resolvePolicy($guessedPolicy); + } + } + + foreach ($this->policies as $expected => $policy) { + if (is_subclass_of($class, $expected)) { + return $this->resolvePolicy($policy); + } + } + } + + /** + * Guess the policy name for the given class. + * + * @param string $class + * @return array + */ + protected function guessPolicyName($class) + { + if ($this->guessPolicyNamesUsingCallback) { + return Arr::wrap(call_user_func($this->guessPolicyNamesUsingCallback, $class)); + } + + $classDirname = str_replace('/', '\\', dirname(str_replace('\\', '/', $class))); + + $classDirnameSegments = explode('\\', $classDirname); + + return Arr::wrap(Collection::times(count($classDirnameSegments), function ($index) use ($class, $classDirnameSegments) { + $classDirname = implode('\\', array_slice($classDirnameSegments, 0, $index)); + + return $classDirname.'\\Policies\\'.class_basename($class).'Policy'; + })->reverse()->values()->first(function ($class) { + return class_exists($class); + }) ?: [$classDirname.'\\Policies\\'.class_basename($class).'Policy']); + } + + /** + * Specify a callback to be used to guess policy names. + * + * @param callable $callback + * @return $this + */ + public function guessPolicyNamesUsing(callable $callback) + { + $this->guessPolicyNamesUsingCallback = $callback; + + return $this; + } + + /** + * Build a policy class instance of the given type. + * + * @param object|string $class + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function resolvePolicy($class) + { + return $this->container->make($class); + } + + /** + * Resolve the callback for a policy check. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string $ability + * @param array $arguments + * @param mixed $policy + * @return bool|callable + */ + protected function resolvePolicyCallback($user, $ability, array $arguments, $policy) + { + if (! is_callable([$policy, $this->formatAbilityToMethod($ability)])) { + return false; + } + + return function () use ($user, $ability, $arguments, $policy) { + // This callback will be responsible for calling the policy's before method and + // running this policy method if necessary. This is used to when objects are + // mapped to policy objects in the user's configurations or on this class. + $result = $this->callPolicyBefore( + $policy, $user, $ability, $arguments + ); + + // When we receive a non-null result from this before method, we will return it + // as the "final" results. This will allow developers to override the checks + // in this policy to return the result for all rules defined in the class. + if (! is_null($result)) { + return $result; + } + + $method = $this->formatAbilityToMethod($ability); + + return $this->callPolicyMethod($policy, $method, $user, $arguments); + }; + } + + /** + * Call the "before" method on the given policy, if applicable. + * + * @param mixed $policy + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string $ability + * @param array $arguments + * @return mixed + */ + protected function callPolicyBefore($policy, $user, $ability, $arguments) + { + if (! method_exists($policy, 'before')) { + return; + } + + if ($this->canBeCalledWithUser($user, $policy, 'before')) { + return $policy->before($user, $ability, ...$arguments); + } + } + + /** + * Call the appropriate method on the given policy. + * + * @param mixed $policy + * @param string $method + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param array $arguments + * @return mixed + */ + protected function callPolicyMethod($policy, $method, $user, array $arguments) + { + // If this first argument is a string, that means they are passing a class name + // to the policy. We will remove the first argument from this argument array + // because this policy already knows what type of models it can authorize. + if (isset($arguments[0]) && is_string($arguments[0])) { + array_shift($arguments); + } + + if (! is_callable([$policy, $method])) { + return; + } + + if ($this->canBeCalledWithUser($user, $policy, $method)) { + return $policy->{$method}($user, ...$arguments); + } + } + + /** + * Format the policy ability into a method name. + * + * @param string $ability + * @return string + */ + protected function formatAbilityToMethod($ability) + { + return strpos($ability, '-') !== false ? Str::camel($ability) : $ability; + } + + /** + * Get a gate instance for the given user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user + * @return static + */ + public function forUser($user) + { + $callback = function () use ($user) { + return $user; + }; + + return new static( + $this->container, $callback, $this->abilities, + $this->policies, $this->beforeCallbacks, $this->afterCallbacks, + $this->guessPolicyNamesUsingCallback + ); + } + + /** + * Resolve the user from the user resolver. + * + * @return mixed + */ + protected function resolveUser() + { + return call_user_func($this->userResolver); + } + + /** + * Get all of the defined abilities. + * + * @return array + */ + public function abilities() + { + return $this->abilities; + } + + /** + * Get all of the defined policies. + * + * @return array + */ + public function policies() + { + return $this->policies; + } + + /** + * Set the container instance used by the gate. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/HandlesAuthorization.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/HandlesAuthorization.php new file mode 100644 index 0000000..66e5786 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Access/HandlesAuthorization.php @@ -0,0 +1,30 @@ +code = $code; + $this->allowed = $allowed; + $this->message = $message; + } + + /** + * Create a new "allow" Response. + * + * @param string|null $message + * @param mixed $code + * @return \Illuminate\Auth\Access\Response + */ + public static function allow($message = null, $code = null) + { + return new static(true, $message, $code); + } + + /** + * Create a new "deny" Response. + * + * @param string|null $message + * @param mixed $code + * @return \Illuminate\Auth\Access\Response + */ + public static function deny($message = null, $code = null) + { + return new static(false, $message, $code); + } + + /** + * Determine if the response was allowed. + * + * @return bool + */ + public function allowed() + { + return $this->allowed; + } + + /** + * Determine if the response was denied. + * + * @return bool + */ + public function denied() + { + return ! $this->allowed(); + } + + /** + * Get the response message. + * + * @return string|null + */ + public function message() + { + return $this->message; + } + + /** + * Get the response code / reason. + * + * @return mixed + */ + public function code() + { + return $this->code; + } + + /** + * Throw authorization exception if response was denied. + * + * @return \Illuminate\Auth\Access\Response + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function authorize() + { + if ($this->denied()) { + throw (new AuthorizationException($this->message(), $this->code())) + ->setResponse($this); + } + + return $this; + } + + /** + * Convert the response to an array. + * + * @return array + */ + public function toArray() + { + return [ + 'allowed' => $this->allowed(), + 'message' => $this->message(), + 'code' => $this->code(), + ]; + } + + /** + * Get the string representation of the message. + * + * @return string + */ + public function __toString() + { + return (string) $this->message(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php new file mode 100755 index 0000000..b72f391 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php @@ -0,0 +1,342 @@ +app = $app; + + $this->userResolver = function ($guard = null) { + return $this->guard($guard)->user(); + }; + } + + /** + * Attempt to get the guard from the local cache. + * + * @param string|null $name + * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard + */ + public function guard($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + return $this->guards[$name] ?? $this->guards[$name] = $this->resolve($name); + } + + /** + * Resolve the given guard. + * + * @param string $name + * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Auth guard [{$name}] is not defined."); + } + + if (isset($this->customCreators[$config['driver']])) { + return $this->callCustomCreator($name, $config); + } + + $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; + + if (method_exists($this, $driverMethod)) { + return $this->{$driverMethod}($name, $config); + } + + throw new InvalidArgumentException( + "Auth driver [{$config['driver']}] for guard [{$name}] is not defined." + ); + } + + /** + * Call a custom driver creator. + * + * @param string $name + * @param array $config + * @return mixed + */ + protected function callCustomCreator($name, array $config) + { + return $this->customCreators[$config['driver']]($this->app, $name, $config); + } + + /** + * Create a session based authentication guard. + * + * @param string $name + * @param array $config + * @return \Illuminate\Auth\SessionGuard + */ + public function createSessionDriver($name, $config) + { + $provider = $this->createUserProvider($config['provider'] ?? null); + + $guard = new SessionGuard( + $name, + $provider, + $this->app['session.store'], + ); + + // When using the remember me functionality of the authentication services we + // will need to be set the encryption instance of the guard, which allows + // secure, encrypted cookie values to get generated for those cookies. + if (method_exists($guard, 'setCookieJar')) { + $guard->setCookieJar($this->app['cookie']); + } + + if (method_exists($guard, 'setDispatcher')) { + $guard->setDispatcher($this->app['events']); + } + + if (method_exists($guard, 'setRequest')) { + $guard->setRequest($this->app->refresh('request', $guard, 'setRequest')); + } + + if (isset($config['remember'])) { + $guard->setRememberDuration($config['remember']); + } + + return $guard; + } + + /** + * Create a token based authentication guard. + * + * @param string $name + * @param array $config + * @return \Illuminate\Auth\TokenGuard + */ + public function createTokenDriver($name, $config) + { + // The token guard implements a basic API token based guard implementation + // that takes an API token field from the request and matches it to the + // user in the database or another persistence layer where users are. + $guard = new TokenGuard( + $this->createUserProvider($config['provider'] ?? null), + $this->app['request'], + $config['input_key'] ?? 'api_token', + $config['storage_key'] ?? 'api_token', + $config['hash'] ?? false + ); + + $this->app->refresh('request', $guard, 'setRequest'); + + return $guard; + } + + /** + * Get the guard configuration. + * + * @param string $name + * @return array + */ + protected function getConfig($name) + { + return $this->app['config']["auth.guards.{$name}"]; + } + + /** + * Get the default authentication driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->app['config']['auth.defaults.guard']; + } + + /** + * Set the default guard driver the factory should serve. + * + * @param string $name + * @return void + */ + public function shouldUse($name) + { + $name = $name ?: $this->getDefaultDriver(); + + $this->setDefaultDriver($name); + + $this->userResolver = function ($name = null) { + return $this->guard($name)->user(); + }; + } + + /** + * Set the default authentication driver name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->app['config']['auth.defaults.guard'] = $name; + } + + /** + * Register a new callback based request guard. + * + * @param string $driver + * @param callable $callback + * @return $this + */ + public function viaRequest($driver, callable $callback) + { + return $this->extend($driver, function () use ($callback) { + $guard = new RequestGuard($callback, $this->app['request'], $this->createUserProvider()); + + $this->app->refresh('request', $guard, 'setRequest'); + + return $guard; + }); + } + + /** + * Get the user resolver callback. + * + * @return \Closure + */ + public function userResolver() + { + return $this->userResolver; + } + + /** + * Set the callback to be used to resolve users. + * + * @param \Closure $userResolver + * @return $this + */ + public function resolveUsersUsing(Closure $userResolver) + { + $this->userResolver = $userResolver; + + return $this; + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback; + + return $this; + } + + /** + * Register a custom provider creator Closure. + * + * @param string $name + * @param \Closure $callback + * @return $this + */ + public function provider($name, Closure $callback) + { + $this->customProviderCreators[$name] = $callback; + + return $this; + } + + /** + * Determines if any guards have already been resolved. + * + * @return bool + */ + public function hasResolvedGuards() + { + return count($this->guards) > 0; + } + + /** + * Forget all of the resolved guard instances. + * + * @return $this + */ + public function forgetGuards() + { + $this->guards = []; + + return $this; + } + + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication($app) + { + $this->app = $app; + + return $this; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->guard()->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php new file mode 100755 index 0000000..9c17edf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php @@ -0,0 +1,120 @@ +registerAuthenticator(); + $this->registerUserResolver(); + $this->registerAccessGate(); + $this->registerRequirePassword(); + $this->registerRequestRebindHandler(); + $this->registerEventRebindHandler(); + } + + /** + * Register the authenticator services. + * + * @return void + */ + protected function registerAuthenticator() + { + $this->app->singleton('auth', function ($app) { + return new AuthManager($app); + }); + + $this->app->singleton('auth.driver', function ($app) { + return $app['auth']->guard(); + }); + } + + /** + * Register a resolver for the authenticated user. + * + * @return void + */ + protected function registerUserResolver() + { + $this->app->bind(AuthenticatableContract::class, function ($app) { + return call_user_func($app['auth']->userResolver()); + }); + } + + /** + * Register the access gate service. + * + * @return void + */ + protected function registerAccessGate() + { + $this->app->singleton(GateContract::class, function ($app) { + return new Gate($app, function () use ($app) { + return call_user_func($app['auth']->userResolver()); + }); + }); + } + + /** + * Register a resolver for the authenticated user. + * + * @return void + */ + protected function registerRequirePassword() + { + $this->app->bind(RequirePassword::class, function ($app) { + return new RequirePassword( + $app[ResponseFactory::class], + $app[UrlGenerator::class], + $app['config']->get('auth.password_timeout') + ); + }); + } + + /** + * Handle the re-binding of the request binding. + * + * @return void + */ + protected function registerRequestRebindHandler() + { + $this->app->rebinding('request', function ($app, $request) { + $request->setUserResolver(function ($guard = null) use ($app) { + return call_user_func($app['auth']->userResolver(), $guard); + }); + }); + } + + /** + * Handle the re-binding of the event dispatcher binding. + * + * @return void + */ + protected function registerEventRebindHandler() + { + $this->app->rebinding('events', function ($app, $dispatcher) { + if (! $app->resolved('auth') || + $app['auth']->hasResolvedGuards() === false) { + return; + } + + if (method_exists($guard = $app['auth']->guard(), 'setDispatcher')) { + $guard->setDispatcher($dispatcher); + } + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Authenticatable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Authenticatable.php new file mode 100644 index 0000000..f1c0115 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Authenticatable.php @@ -0,0 +1,88 @@ +getKeyName(); + } + + /** + * Get the unique identifier for the user. + * + * @return mixed + */ + public function getAuthIdentifier() + { + return $this->{$this->getAuthIdentifierName()}; + } + + /** + * Get the unique broadcast identifier for the user. + * + * @return mixed + */ + public function getAuthIdentifierForBroadcasting() + { + return $this->getAuthIdentifier(); + } + + /** + * Get the password for the user. + * + * @return string + */ + public function getAuthPassword() + { + return $this->password; + } + + /** + * Get the token value for the "remember me" session. + * + * @return string|null + */ + public function getRememberToken() + { + if (! empty($this->getRememberTokenName())) { + return (string) $this->{$this->getRememberTokenName()}; + } + } + + /** + * Set the token value for the "remember me" session. + * + * @param string $value + * @return void + */ + public function setRememberToken($value) + { + if (! empty($this->getRememberTokenName())) { + $this->{$this->getRememberTokenName()} = $value; + } + } + + /** + * Get the column name for the "remember me" token. + * + * @return string + */ + public function getRememberTokenName() + { + return $this->rememberTokenName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthenticationException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthenticationException.php new file mode 100644 index 0000000..66808c3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/AuthenticationException.php @@ -0,0 +1,58 @@ +guards = $guards; + $this->redirectTo = $redirectTo; + } + + /** + * Get the guards that were checked. + * + * @return array + */ + public function guards() + { + return $this->guards; + } + + /** + * Get the path the user should be redirected to. + * + * @return string|null + */ + public function redirectTo() + { + return $this->redirectTo; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Console/ClearResetsCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Console/ClearResetsCommand.php new file mode 100644 index 0000000..57c3bd5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Console/ClearResetsCommand.php @@ -0,0 +1,34 @@ +laravel['auth.password']->broker($this->argument('name'))->getRepository()->deleteExpired(); + + $this->info('Expired reset tokens cleared!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Console/stubs/make/views/layouts/app.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Console/stubs/make/views/layouts/app.stub new file mode 100644 index 0000000..d182236 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Console/stubs/make/views/layouts/app.stub @@ -0,0 +1,80 @@ + + + + + + + + + + {{ config('app.name', 'Laravel') }} + + + + + + + + + + + + +
+ + +
+ @yield('content') +
+
+ + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/CreatesUserProviders.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/CreatesUserProviders.php new file mode 100644 index 0000000..c2135f7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/CreatesUserProviders.php @@ -0,0 +1,94 @@ +getProviderConfiguration($provider))) { + return; + } + + if (isset($this->customProviderCreators[$driver = ($config['driver'] ?? null)])) { + return call_user_func( + $this->customProviderCreators[$driver], $this->app, $config + ); + } + + switch ($driver) { + case 'database': + return $this->createDatabaseProvider($config); + case 'eloquent': + return $this->createEloquentProvider($config); + default: + throw new InvalidArgumentException( + "Authentication user provider [{$driver}] is not defined." + ); + } + } + + /** + * Get the user provider configuration. + * + * @param string|null $provider + * @return array|null + */ + protected function getProviderConfiguration($provider) + { + if ($provider = $provider ?: $this->getDefaultUserProvider()) { + return $this->app['config']['auth.providers.'.$provider]; + } + } + + /** + * Create an instance of the database user provider. + * + * @param array $config + * @return \Illuminate\Auth\DatabaseUserProvider + */ + protected function createDatabaseProvider($config) + { + $connection = $this->app['db']->connection($config['connection'] ?? null); + + return new DatabaseUserProvider($connection, $this->app['hash'], $config['table']); + } + + /** + * Create an instance of the Eloquent user provider. + * + * @param array $config + * @return \Illuminate\Auth\EloquentUserProvider + */ + protected function createEloquentProvider($config) + { + return new EloquentUserProvider($this->app['hash'], $config['model']); + } + + /** + * Get the default user provider name. + * + * @return string + */ + public function getDefaultUserProvider() + { + return $this->app['config']['auth.defaults.provider']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php new file mode 100755 index 0000000..111e552 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php @@ -0,0 +1,162 @@ +conn = $conn; + $this->table = $table; + $this->hasher = $hasher; + } + + /** + * Retrieve a user by their unique identifier. + * + * @param mixed $identifier + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveById($identifier) + { + $user = $this->conn->table($this->table)->find($identifier); + + return $this->getGenericUser($user); + } + + /** + * Retrieve a user by their unique identifier and "remember me" token. + * + * @param mixed $identifier + * @param string $token + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveByToken($identifier, $token) + { + $user = $this->getGenericUser( + $this->conn->table($this->table)->find($identifier) + ); + + return $user && $user->getRememberToken() && hash_equals($user->getRememberToken(), $token) + ? $user : null; + } + + /** + * Update the "remember me" token for the given user in storage. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string $token + * @return void + */ + public function updateRememberToken(UserContract $user, $token) + { + $this->conn->table($this->table) + ->where($user->getAuthIdentifierName(), $user->getAuthIdentifier()) + ->update([$user->getRememberTokenName() => $token]); + } + + /** + * Retrieve a user by the given credentials. + * + * @param array $credentials + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveByCredentials(array $credentials) + { + if (empty($credentials) || + (count($credentials) === 1 && + array_key_exists('password', $credentials))) { + return; + } + + // First we will add each credential element to the query as a where clause. + // Then we can execute the query and, if we found a user, return it in a + // generic "user" object that will be utilized by the Guard instances. + $query = $this->conn->table($this->table); + + foreach ($credentials as $key => $value) { + if (Str::contains($key, 'password')) { + continue; + } + + if (is_array($value) || $value instanceof Arrayable) { + $query->whereIn($key, $value); + } elseif ($value instanceof Closure) { + $value($query); + } else { + $query->where($key, $value); + } + } + + // Now we are ready to execute the query to see if we have an user matching + // the given credentials. If not, we will just return nulls and indicate + // that there are no matching users for these given credential arrays. + $user = $query->first(); + + return $this->getGenericUser($user); + } + + /** + * Get the generic user. + * + * @param mixed $user + * @return \Illuminate\Auth\GenericUser|null + */ + protected function getGenericUser($user) + { + if (! is_null($user)) { + return new GenericUser((array) $user); + } + } + + /** + * Validate a user against the given credentials. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param array $credentials + * @return bool + */ + public function validateCredentials(UserContract $user, array $credentials) + { + return $this->hasher->check( + $credentials['password'], $user->getAuthPassword() + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php new file mode 100755 index 0000000..54dff6b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php @@ -0,0 +1,234 @@ +model = $model; + $this->hasher = $hasher; + } + + /** + * Retrieve a user by their unique identifier. + * + * @param mixed $identifier + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveById($identifier) + { + $model = $this->createModel(); + + return $this->newModelQuery($model) + ->where($model->getAuthIdentifierName(), $identifier) + ->first(); + } + + /** + * Retrieve a user by their unique identifier and "remember me" token. + * + * @param mixed $identifier + * @param string $token + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveByToken($identifier, $token) + { + $model = $this->createModel(); + + $retrievedModel = $this->newModelQuery($model)->where( + $model->getAuthIdentifierName(), $identifier + )->first(); + + if (! $retrievedModel) { + return; + } + + $rememberToken = $retrievedModel->getRememberToken(); + + return $rememberToken && hash_equals($rememberToken, $token) + ? $retrievedModel : null; + } + + /** + * Update the "remember me" token for the given user in storage. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|\Illuminate\Database\Eloquent\Model $user + * @param string $token + * @return void + */ + public function updateRememberToken(UserContract $user, $token) + { + $user->setRememberToken($token); + + $timestamps = $user->timestamps; + + $user->timestamps = false; + + $user->save(); + + $user->timestamps = $timestamps; + } + + /** + * Retrieve a user by the given credentials. + * + * @param array $credentials + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveByCredentials(array $credentials) + { + if (empty($credentials) || + (count($credentials) === 1 && + Str::contains($this->firstCredentialKey($credentials), 'password'))) { + return; + } + + // First we will add each credential element to the query as a where clause. + // Then we can execute the query and, if we found a user, return it in a + // Eloquent User "model" that will be utilized by the Guard instances. + $query = $this->newModelQuery(); + + foreach ($credentials as $key => $value) { + if (Str::contains($key, 'password')) { + continue; + } + + if (is_array($value) || $value instanceof Arrayable) { + $query->whereIn($key, $value); + } elseif ($value instanceof Closure) { + $value($query); + } else { + $query->where($key, $value); + } + } + + return $query->first(); + } + + /** + * Get the first key from the credential array. + * + * @param array $credentials + * @return string|null + */ + protected function firstCredentialKey(array $credentials) + { + foreach ($credentials as $key => $value) { + return $key; + } + } + + /** + * Validate a user against the given credentials. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param array $credentials + * @return bool + */ + public function validateCredentials(UserContract $user, array $credentials) + { + $plain = $credentials['password']; + + return $this->hasher->check($plain, $user->getAuthPassword()); + } + + /** + * Get a new query builder for the model instance. + * + * @param \Illuminate\Database\Eloquent\Model|null $model + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function newModelQuery($model = null) + { + return is_null($model) + ? $this->createModel()->newQuery() + : $model->newQuery(); + } + + /** + * Create a new instance of the model. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function createModel() + { + $class = '\\'.ltrim($this->model, '\\'); + + return new $class; + } + + /** + * Gets the hasher implementation. + * + * @return \Illuminate\Contracts\Hashing\Hasher + */ + public function getHasher() + { + return $this->hasher; + } + + /** + * Sets the hasher implementation. + * + * @param \Illuminate\Contracts\Hashing\Hasher $hasher + * @return $this + */ + public function setHasher(HasherContract $hasher) + { + $this->hasher = $hasher; + + return $this; + } + + /** + * Gets the name of the Eloquent user model. + * + * @return string + */ + public function getModel() + { + return $this->model; + } + + /** + * Sets the name of the Eloquent user model. + * + * @param string $model + * @return $this + */ + public function setModel($model) + { + $this->model = $model; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Attempting.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Attempting.php new file mode 100644 index 0000000..3f911ba --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Attempting.php @@ -0,0 +1,42 @@ +guard = $guard; + $this->remember = $remember; + $this->credentials = $credentials; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Authenticated.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Authenticated.php new file mode 100644 index 0000000..faefcbe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Authenticated.php @@ -0,0 +1,37 @@ +user = $user; + $this->guard = $guard; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/CurrentDeviceLogout.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/CurrentDeviceLogout.php new file mode 100644 index 0000000..32d31fa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/CurrentDeviceLogout.php @@ -0,0 +1,37 @@ +user = $user; + $this->guard = $guard; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Failed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Failed.php new file mode 100644 index 0000000..34f8124 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Failed.php @@ -0,0 +1,42 @@ +user = $user; + $this->guard = $guard; + $this->credentials = $credentials; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Lockout.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Lockout.php new file mode 100644 index 0000000..347943f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Lockout.php @@ -0,0 +1,26 @@ +request = $request; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Login.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Login.php new file mode 100644 index 0000000..87a399e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Login.php @@ -0,0 +1,46 @@ +user = $user; + $this->guard = $guard; + $this->remember = $remember; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Logout.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Logout.php new file mode 100644 index 0000000..c47341d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Logout.php @@ -0,0 +1,37 @@ +user = $user; + $this->guard = $guard; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/OtherDeviceLogout.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/OtherDeviceLogout.php new file mode 100644 index 0000000..ea139a7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/OtherDeviceLogout.php @@ -0,0 +1,37 @@ +user = $user; + $this->guard = $guard; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/PasswordReset.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/PasswordReset.php new file mode 100644 index 0000000..f57b3c9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/PasswordReset.php @@ -0,0 +1,28 @@ +user = $user; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Registered.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Registered.php new file mode 100644 index 0000000..f84058c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Registered.php @@ -0,0 +1,28 @@ +user = $user; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Validated.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Validated.php new file mode 100644 index 0000000..ebc3b2c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Validated.php @@ -0,0 +1,37 @@ +user = $user; + $this->guard = $guard; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Verified.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Verified.php new file mode 100644 index 0000000..1d6e4c0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Events/Verified.php @@ -0,0 +1,28 @@ +user = $user; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/GenericUser.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/GenericUser.php new file mode 100755 index 0000000..c87bc23 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/GenericUser.php @@ -0,0 +1,132 @@ +attributes = $attributes; + } + + /** + * Get the name of the unique identifier for the user. + * + * @return string + */ + public function getAuthIdentifierName() + { + return 'id'; + } + + /** + * Get the unique identifier for the user. + * + * @return mixed + */ + public function getAuthIdentifier() + { + return $this->attributes[$this->getAuthIdentifierName()]; + } + + /** + * Get the password for the user. + * + * @return string + */ + public function getAuthPassword() + { + return $this->attributes['password']; + } + + /** + * Get the "remember me" token value. + * + * @return string + */ + public function getRememberToken() + { + return $this->attributes[$this->getRememberTokenName()]; + } + + /** + * Set the "remember me" token value. + * + * @param string $value + * @return void + */ + public function setRememberToken($value) + { + $this->attributes[$this->getRememberTokenName()] = $value; + } + + /** + * Get the column name for the "remember me" token. + * + * @return string + */ + public function getRememberTokenName() + { + return 'remember_token'; + } + + /** + * Dynamically access the user's attributes. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->attributes[$key]; + } + + /** + * Dynamically set an attribute on the user. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function __set($key, $value) + { + $this->attributes[$key] = $value; + } + + /** + * Dynamically check if a value is set on the user. + * + * @param string $key + * @return bool + */ + public function __isset($key) + { + return isset($this->attributes[$key]); + } + + /** + * Dynamically unset a value on the user. + * + * @param string $key + * @return void + */ + public function __unset($key) + { + unset($this->attributes[$key]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/GuardHelpers.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/GuardHelpers.php new file mode 100644 index 0000000..aa9ebf9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/GuardHelpers.php @@ -0,0 +1,118 @@ +user())) { + return $user; + } + + throw new AuthenticationException; + } + + /** + * Determine if the guard has a user instance. + * + * @return bool + */ + public function hasUser() + { + return ! is_null($this->user); + } + + /** + * Determine if the current user is authenticated. + * + * @return bool + */ + public function check() + { + return ! is_null($this->user()); + } + + /** + * Determine if the current user is a guest. + * + * @return bool + */ + public function guest() + { + return ! $this->check(); + } + + /** + * Get the ID for the currently authenticated user. + * + * @return int|string|null + */ + public function id() + { + if ($this->user()) { + return $this->user()->getAuthIdentifier(); + } + } + + /** + * Set the current user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return $this + */ + public function setUser(AuthenticatableContract $user) + { + $this->user = $user; + + return $this; + } + + /** + * Get the user provider used by the guard. + * + * @return \Illuminate\Contracts\Auth\UserProvider + */ + public function getProvider() + { + return $this->provider; + } + + /** + * Set the user provider used by the guard. + * + * @param \Illuminate\Contracts\Auth\UserProvider $provider + * @return void + */ + public function setProvider(UserProvider $provider) + { + $this->provider = $provider; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Listeners/SendEmailVerificationNotification.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Listeners/SendEmailVerificationNotification.php new file mode 100644 index 0000000..12dfa69 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Listeners/SendEmailVerificationNotification.php @@ -0,0 +1,22 @@ +user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) { + $event->user->sendEmailVerificationNotification(); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php new file mode 100644 index 0000000..7eda342 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php @@ -0,0 +1,97 @@ +auth = $auth; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string[] ...$guards + * @return mixed + * + * @throws \Illuminate\Auth\AuthenticationException + */ + public function handle($request, Closure $next, ...$guards) + { + $this->authenticate($request, $guards); + + return $next($request); + } + + /** + * Determine if the user is logged in to any of the given guards. + * + * @param \Illuminate\Http\Request $request + * @param array $guards + * @return void + * + * @throws \Illuminate\Auth\AuthenticationException + */ + protected function authenticate($request, array $guards) + { + if (empty($guards)) { + $guards = [null]; + } + + foreach ($guards as $guard) { + if ($this->auth->guard($guard)->check()) { + return $this->auth->shouldUse($guard); + } + } + + $this->unauthenticated($request, $guards); + } + + /** + * Handle an unauthenticated user. + * + * @param \Illuminate\Http\Request $request + * @param array $guards + * @return void + * + * @throws \Illuminate\Auth\AuthenticationException + */ + protected function unauthenticated($request, array $guards) + { + throw new AuthenticationException( + 'Unauthenticated.', $guards, $this->redirectTo($request) + ); + } + + /** + * Get the path the user should be redirected to when they are not authenticated. + * + * @param \Illuminate\Http\Request $request + * @return string|null + */ + protected function redirectTo($request) + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php new file mode 100644 index 0000000..92c81e6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php @@ -0,0 +1,45 @@ +auth = $auth; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $guard + * @param string|null $field + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException + */ + public function handle($request, Closure $next, $guard = null, $field = null) + { + $this->auth->guard($guard)->basic($field ?: 'email'); + + return $next($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authorize.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authorize.php new file mode 100644 index 0000000..aea9801 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authorize.php @@ -0,0 +1,93 @@ +gate = $gate; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string $ability + * @param array|null ...$models + * @return mixed + * + * @throws \Illuminate\Auth\AuthenticationException + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function handle($request, Closure $next, $ability, ...$models) + { + $this->gate->authorize($ability, $this->getGateArguments($request, $models)); + + return $next($request); + } + + /** + * Get the arguments parameter for the gate. + * + * @param \Illuminate\Http\Request $request + * @param array|null $models + * @return \Illuminate\Database\Eloquent\Model|array|string + */ + protected function getGateArguments($request, $models) + { + if (is_null($models)) { + return []; + } + + return collect($models)->map(function ($model) use ($request) { + return $model instanceof Model ? $model : $this->getModel($request, $model); + })->all(); + } + + /** + * Get the model to authorize. + * + * @param \Illuminate\Http\Request $request + * @param string $model + * @return \Illuminate\Database\Eloquent\Model|string + */ + protected function getModel($request, $model) + { + if ($this->isClassName($model)) { + return trim($model); + } else { + return $request->route($model, null) ?: + ((preg_match("/^['\"](.*)['\"]$/", trim($model), $matches)) ? $matches[1] : null); + } + } + + /** + * Checks if the given string looks like a fully qualified class name. + * + * @param string $value + * @return bool + */ + protected function isClassName($value) + { + return strpos($value, '\\') !== false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/EnsureEmailIsVerified.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/EnsureEmailIsVerified.php new file mode 100644 index 0000000..8f2b33a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/EnsureEmailIsVerified.php @@ -0,0 +1,32 @@ +user() || + ($request->user() instanceof MustVerifyEmail && + ! $request->user()->hasVerifiedEmail())) { + return $request->expectsJson() + ? abort(403, 'Your email address is not verified.') + : Redirect::guest(URL::route($redirectToRoute ?: 'verification.notice')); + } + + return $next($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/RequirePassword.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/RequirePassword.php new file mode 100644 index 0000000..315bdb8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Middleware/RequirePassword.php @@ -0,0 +1,84 @@ +responseFactory = $responseFactory; + $this->urlGenerator = $urlGenerator; + $this->passwordTimeout = $passwordTimeout ?: 10800; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $redirectToRoute + * @return mixed + */ + public function handle($request, Closure $next, $redirectToRoute = null) + { + if ($this->shouldConfirmPassword($request)) { + if ($request->expectsJson()) { + return $this->responseFactory->json([ + 'message' => 'Password confirmation required.', + ], 423); + } + + return $this->responseFactory->redirectGuest( + $this->urlGenerator->route($redirectToRoute ?? 'password.confirm') + ); + } + + return $next($request); + } + + /** + * Determine if the confirmation timeout has expired. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function shouldConfirmPassword($request) + { + $confirmedAt = time() - $request->session()->get('auth.password_confirmed_at', 0); + + return $confirmedAt > $this->passwordTimeout; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/MustVerifyEmail.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/MustVerifyEmail.php new file mode 100644 index 0000000..8e1ce33 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/MustVerifyEmail.php @@ -0,0 +1,50 @@ +email_verified_at); + } + + /** + * Mark the given user's email as verified. + * + * @return bool + */ + public function markEmailAsVerified() + { + return $this->forceFill([ + 'email_verified_at' => $this->freshTimestamp(), + ])->save(); + } + + /** + * Send the email verification notification. + * + * @return void + */ + public function sendEmailVerificationNotification() + { + $this->notify(new VerifyEmail); + } + + /** + * Get the email address that should be used for verification. + * + * @return string + */ + public function getEmailForVerification() + { + return $this->email; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword.php new file mode 100644 index 0000000..f1c13f4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword.php @@ -0,0 +1,124 @@ +token = $token; + } + + /** + * Get the notification's channels. + * + * @param mixed $notifiable + * @return array|string + */ + public function via($notifiable) + { + return ['mail']; + } + + /** + * Build the mail representation of the notification. + * + * @param mixed $notifiable + * @return \Illuminate\Notifications\Messages\MailMessage + */ + public function toMail($notifiable) + { + if (static::$toMailCallback) { + return call_user_func(static::$toMailCallback, $notifiable, $this->token); + } + + return $this->buildMailMessage($this->resetUrl($notifiable)); + } + + /** + * Get the reset password notification mail message for the given URL. + * + * @param string $url + * @return \Illuminate\Notifications\Messages\MailMessage + */ + protected function buildMailMessage($url) + { + return (new MailMessage) + ->subject(Lang::get('Reset Password Notification')) + ->line(Lang::get('You are receiving this email because we received a password reset request for your account.')) + ->action(Lang::get('Reset Password'), $url) + ->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')])) + ->line(Lang::get('If you did not request a password reset, no further action is required.')); + } + + /** + * Get the reset URL for the given notifiable. + * + * @param mixed $notifiable + * @return string + */ + protected function resetUrl($notifiable) + { + if (static::$createUrlCallback) { + return call_user_func(static::$createUrlCallback, $notifiable, $this->token); + } + + return url(route('password.reset', [ + 'token' => $this->token, + 'email' => $notifiable->getEmailForPasswordReset(), + ], false)); + } + + /** + * Set a callback that should be used when creating the reset password button URL. + * + * @param \Closure $callback + * @return void + */ + public static function createUrlUsing($callback) + { + static::$createUrlCallback = $callback; + } + + /** + * Set a callback that should be used when building the notification mail message. + * + * @param \Closure $callback + * @return void + */ + public static function toMailUsing($callback) + { + static::$toMailCallback = $callback; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php new file mode 100644 index 0000000..7a5cf91 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php @@ -0,0 +1,114 @@ +verificationUrl($notifiable); + + if (static::$toMailCallback) { + return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl); + } + + return $this->buildMailMessage($verificationUrl); + } + + /** + * Get the verify email notification mail message for the given URL. + * + * @param string $url + * @return \Illuminate\Notifications\Messages\MailMessage + */ + protected function buildMailMessage($url) + { + return (new MailMessage) + ->subject(Lang::get('Verify Email Address')) + ->line(Lang::get('Please click the button below to verify your email address.')) + ->action(Lang::get('Verify Email Address'), $url) + ->line(Lang::get('If you did not create an account, no further action is required.')); + } + + /** + * Get the verification URL for the given notifiable. + * + * @param mixed $notifiable + * @return string + */ + protected function verificationUrl($notifiable) + { + if (static::$createUrlCallback) { + return call_user_func(static::$createUrlCallback, $notifiable); + } + + return URL::temporarySignedRoute( + 'verification.verify', + Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)), + [ + 'id' => $notifiable->getKey(), + 'hash' => sha1($notifiable->getEmailForVerification()), + ] + ); + } + + /** + * Set a callback that should be used when creating the email verification URL. + * + * @param \Closure $callback + * @return void + */ + public static function createUrlUsing($callback) + { + static::$createUrlCallback = $callback; + } + + /** + * Set a callback that should be used when building the notification mail message. + * + * @param \Closure $callback + * @return void + */ + public static function toMailUsing($callback) + { + static::$toMailCallback = $callback; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/CanResetPassword.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/CanResetPassword.php new file mode 100644 index 0000000..918a288 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/CanResetPassword.php @@ -0,0 +1,29 @@ +email; + } + + /** + * Send the password reset notification. + * + * @param string $token + * @return void + */ + public function sendPasswordResetNotification($token) + { + $this->notify(new ResetPasswordNotification($token)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php new file mode 100755 index 0000000..fe5f54b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php @@ -0,0 +1,246 @@ +table = $table; + $this->hasher = $hasher; + $this->hashKey = $hashKey; + $this->expires = $expires * 60; + $this->connection = $connection; + $this->throttle = $throttle; + } + + /** + * Create a new token record. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @return string + */ + public function create(CanResetPasswordContract $user) + { + $email = $user->getEmailForPasswordReset(); + + $this->deleteExisting($user); + + // We will create a new, random token for the user so that we can e-mail them + // a safe link to the password reset form. Then we will insert a record in + // the database so that we can verify the token within the actual reset. + $token = $this->createNewToken(); + + $this->getTable()->insert($this->getPayload($email, $token)); + + return $token; + } + + /** + * Delete all existing reset tokens from the database. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @return int + */ + protected function deleteExisting(CanResetPasswordContract $user) + { + return $this->getTable()->where('email', $user->getEmailForPasswordReset())->delete(); + } + + /** + * Build the record payload for the table. + * + * @param string $email + * @param string $token + * @return array + */ + protected function getPayload($email, $token) + { + return ['email' => $email, 'token' => $this->hasher->make($token), 'created_at' => new Carbon]; + } + + /** + * Determine if a token record exists and is valid. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @param string $token + * @return bool + */ + public function exists(CanResetPasswordContract $user, $token) + { + $record = (array) $this->getTable()->where( + 'email', $user->getEmailForPasswordReset() + )->first(); + + return $record && + ! $this->tokenExpired($record['created_at']) && + $this->hasher->check($token, $record['token']); + } + + /** + * Determine if the token has expired. + * + * @param string $createdAt + * @return bool + */ + protected function tokenExpired($createdAt) + { + return Carbon::parse($createdAt)->addSeconds($this->expires)->isPast(); + } + + /** + * Determine if the given user recently created a password reset token. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @return bool + */ + public function recentlyCreatedToken(CanResetPasswordContract $user) + { + $record = (array) $this->getTable()->where( + 'email', $user->getEmailForPasswordReset() + )->first(); + + return $record && $this->tokenRecentlyCreated($record['created_at']); + } + + /** + * Determine if the token was recently created. + * + * @param string $createdAt + * @return bool + */ + protected function tokenRecentlyCreated($createdAt) + { + if ($this->throttle <= 0) { + return false; + } + + return Carbon::parse($createdAt)->addSeconds( + $this->throttle + )->isFuture(); + } + + /** + * Delete a token record by user. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @return void + */ + public function delete(CanResetPasswordContract $user) + { + $this->deleteExisting($user); + } + + /** + * Delete expired tokens. + * + * @return void + */ + public function deleteExpired() + { + $expiredAt = Carbon::now()->subSeconds($this->expires); + + $this->getTable()->where('created_at', '<', $expiredAt)->delete(); + } + + /** + * Create a new token for the user. + * + * @return string + */ + public function createNewToken() + { + return hash_hmac('sha256', Str::random(40), $this->hashKey); + } + + /** + * Get the database connection instance. + * + * @return \Illuminate\Database\ConnectionInterface + */ + public function getConnection() + { + return $this->connection; + } + + /** + * Begin a new database query against the table. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function getTable() + { + return $this->connection->table($this->table); + } + + /** + * Get the hasher instance. + * + * @return \Illuminate\Contracts\Hashing\Hasher + */ + public function getHasher() + { + return $this->hasher; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php new file mode 100755 index 0000000..cbbc897 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php @@ -0,0 +1,190 @@ +users = $users; + $this->tokens = $tokens; + } + + /** + * Send a password reset link to a user. + * + * @param array $credentials + * @param \Closure|null $callback + * @return string + */ + public function sendResetLink(array $credentials, Closure $callback = null) + { + // First we will check to see if we found a user at the given credentials and + // if we did not we will redirect back to this current URI with a piece of + // "flash" data in the session to indicate to the developers the errors. + $user = $this->getUser($credentials); + + if (is_null($user)) { + return static::INVALID_USER; + } + + if ($this->tokens->recentlyCreatedToken($user)) { + return static::RESET_THROTTLED; + } + + $token = $this->tokens->create($user); + + if ($callback) { + $callback($user, $token); + } else { + // Once we have the reset token, we are ready to send the message out to this + // user with a link to reset their password. We will then redirect back to + // the current URI having nothing set in the session to indicate errors. + $user->sendPasswordResetNotification($token); + } + + return static::RESET_LINK_SENT; + } + + /** + * Reset the password for the given token. + * + * @param array $credentials + * @param \Closure $callback + * @return mixed + */ + public function reset(array $credentials, Closure $callback) + { + $user = $this->validateReset($credentials); + + // If the responses from the validate method is not a user instance, we will + // assume that it is a redirect and simply return it from this method and + // the user is properly redirected having an error message on the post. + if (! $user instanceof CanResetPasswordContract) { + return $user; + } + + $password = $credentials['password']; + + // Once the reset has been validated, we'll call the given callback with the + // new password. This gives the user an opportunity to store the password + // in their persistent storage. Then we'll delete the token and return. + $callback($user, $password); + + $this->tokens->delete($user); + + return static::PASSWORD_RESET; + } + + /** + * Validate a password reset for the given credentials. + * + * @param array $credentials + * @return \Illuminate\Contracts\Auth\CanResetPassword|string + */ + protected function validateReset(array $credentials) + { + if (is_null($user = $this->getUser($credentials))) { + return static::INVALID_USER; + } + + if (! $this->tokens->exists($user, $credentials['token'])) { + return static::INVALID_TOKEN; + } + + return $user; + } + + /** + * Get the user for the given credentials. + * + * @param array $credentials + * @return \Illuminate\Contracts\Auth\CanResetPassword|null + * + * @throws \UnexpectedValueException + */ + public function getUser(array $credentials) + { + $credentials = Arr::except($credentials, ['token']); + + $user = $this->users->retrieveByCredentials($credentials); + + if ($user && ! $user instanceof CanResetPasswordContract) { + throw new UnexpectedValueException('User must implement CanResetPassword interface.'); + } + + return $user; + } + + /** + * Create a new password reset token for the given user. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @return string + */ + public function createToken(CanResetPasswordContract $user) + { + return $this->tokens->create($user); + } + + /** + * Delete password reset tokens of the given user. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @return void + */ + public function deleteToken(CanResetPasswordContract $user) + { + $this->tokens->delete($user); + } + + /** + * Validate the given password reset token. + * + * @param \Illuminate\Contracts\Auth\CanResetPassword $user + * @param string $token + * @return bool + */ + public function tokenExists(CanResetPasswordContract $user, $token) + { + return $this->tokens->exists($user, $token); + } + + /** + * Get the password reset token repository implementation. + * + * @return \Illuminate\Auth\Passwords\TokenRepositoryInterface + */ + public function getRepository() + { + return $this->tokens; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBrokerManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBrokerManager.php new file mode 100644 index 0000000..f761726 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBrokerManager.php @@ -0,0 +1,146 @@ +app = $app; + } + + /** + * Attempt to get the broker from the local cache. + * + * @param string|null $name + * @return \Illuminate\Contracts\Auth\PasswordBroker + */ + public function broker($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + return $this->brokers[$name] ?? ($this->brokers[$name] = $this->resolve($name)); + } + + /** + * Resolve the given broker. + * + * @param string $name + * @return \Illuminate\Contracts\Auth\PasswordBroker + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Password resetter [{$name}] is not defined."); + } + + // The password broker uses a token repository to validate tokens and send user + // password e-mails, as well as validating that password reset process as an + // aggregate service of sorts providing a convenient interface for resets. + return new PasswordBroker( + $this->createTokenRepository($config), + $this->app['auth']->createUserProvider($config['provider'] ?? null) + ); + } + + /** + * Create a token repository instance based on the given configuration. + * + * @param array $config + * @return \Illuminate\Auth\Passwords\TokenRepositoryInterface + */ + protected function createTokenRepository(array $config) + { + $key = $this->app['config']['app.key']; + + if (Str::startsWith($key, 'base64:')) { + $key = base64_decode(substr($key, 7)); + } + + $connection = $config['connection'] ?? null; + + return new DatabaseTokenRepository( + $this->app['db']->connection($connection), + $this->app['hash'], + $config['table'], + $key, + $config['expire'], + $config['throttle'] ?? 0 + ); + } + + /** + * Get the password broker configuration. + * + * @param string $name + * @return array + */ + protected function getConfig($name) + { + return $this->app['config']["auth.passwords.{$name}"]; + } + + /** + * Get the default password broker name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->app['config']['auth.defaults.passwords']; + } + + /** + * Set the default password broker name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->app['config']['auth.defaults.passwords'] = $name; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->broker()->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordResetServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordResetServiceProvider.php new file mode 100755 index 0000000..a26b7e6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordResetServiceProvider.php @@ -0,0 +1,45 @@ +registerPasswordBroker(); + } + + /** + * Register the password broker instance. + * + * @return void + */ + protected function registerPasswordBroker() + { + $this->app->singleton('auth.password', function ($app) { + return new PasswordBrokerManager($app); + }); + + $this->app->bind('auth.password.broker', function ($app) { + return $app->make('auth.password')->broker(); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['auth.password', 'auth.password.broker']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/TokenRepositoryInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/TokenRepositoryInterface.php new file mode 100755 index 0000000..47c1758 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/Passwords/TokenRepositoryInterface.php @@ -0,0 +1,48 @@ +recaller = @unserialize($recaller, ['allowed_classes' => false]) ?: $recaller; + } + + /** + * Get the user ID from the recaller. + * + * @return string + */ + public function id() + { + return explode('|', $this->recaller, 3)[0]; + } + + /** + * Get the "remember token" token from the recaller. + * + * @return string + */ + public function token() + { + return explode('|', $this->recaller, 3)[1]; + } + + /** + * Get the password from the recaller. + * + * @return string + */ + public function hash() + { + return explode('|', $this->recaller, 3)[2]; + } + + /** + * Determine if the recaller is valid. + * + * @return bool + */ + public function valid() + { + return $this->properString() && $this->hasAllSegments(); + } + + /** + * Determine if the recaller is an invalid string. + * + * @return bool + */ + protected function properString() + { + return is_string($this->recaller) && Str::contains($this->recaller, '|'); + } + + /** + * Determine if the recaller has all segments. + * + * @return bool + */ + protected function hasAllSegments() + { + $segments = explode('|', $this->recaller); + + return count($segments) === 3 && trim($segments[0]) !== '' && trim($segments[1]) !== ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/RequestGuard.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/RequestGuard.php new file mode 100644 index 0000000..d0af83c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/RequestGuard.php @@ -0,0 +1,87 @@ +request = $request; + $this->callback = $callback; + $this->provider = $provider; + } + + /** + * Get the currently authenticated user. + * + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function user() + { + // If we've already retrieved the user for the current request we can just + // return it back immediately. We do not want to fetch the user data on + // every call to this method because that would be tremendously slow. + if (! is_null($this->user)) { + return $this->user; + } + + return $this->user = call_user_func( + $this->callback, $this->request, $this->getProvider() + ); + } + + /** + * Validate a user's credentials. + * + * @param array $credentials + * @return bool + */ + public function validate(array $credentials = []) + { + return ! is_null((new static( + $this->callback, $credentials['request'], $this->getProvider() + ))->user()); + } + + /** + * Set the current request instance. + * + * @param \Illuminate\Http\Request $request + * @return $this + */ + public function setRequest(Request $request) + { + $this->request = $request; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php new file mode 100644 index 0000000..cd9ec98 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php @@ -0,0 +1,981 @@ +name = $name; + $this->session = $session; + $this->request = $request; + $this->provider = $provider; + $this->timebox = $timebox ?: new Timebox; + } + + /** + * Get the currently authenticated user. + * + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function user() + { + if ($this->loggedOut) { + return; + } + + // If we've already retrieved the user for the current request we can just + // return it back immediately. We do not want to fetch the user data on + // every call to this method because that would be tremendously slow. + if (! is_null($this->user)) { + return $this->user; + } + + $id = $this->session->get($this->getName()); + + // First we will try to load the user using the identifier in the session if + // one exists. Otherwise we will check for a "remember me" cookie in this + // request, and if one exists, attempt to retrieve the user using that. + if (! is_null($id) && $this->user = $this->provider->retrieveById($id)) { + $this->fireAuthenticatedEvent($this->user); + } + + // If the user is null, but we decrypt a "recaller" cookie we can attempt to + // pull the user data on that cookie which serves as a remember cookie on + // the application. Once we have a user we can return it to the caller. + if (is_null($this->user) && ! is_null($recaller = $this->recaller())) { + $this->user = $this->userFromRecaller($recaller); + + if ($this->user) { + $this->updateSession($this->user->getAuthIdentifier()); + + $this->fireLoginEvent($this->user, true); + } + } + + return $this->user; + } + + /** + * Pull a user from the repository by its "remember me" cookie token. + * + * @param \Illuminate\Auth\Recaller $recaller + * @return mixed + */ + protected function userFromRecaller($recaller) + { + if (! $recaller->valid() || $this->recallAttempted) { + return; + } + + // If the user is null, but we decrypt a "recaller" cookie we can attempt to + // pull the user data on that cookie which serves as a remember cookie on + // the application. Once we have a user we can return it to the caller. + $this->recallAttempted = true; + + $this->viaRemember = ! is_null($user = $this->provider->retrieveByToken( + $recaller->id(), $recaller->token() + )); + + return $user; + } + + /** + * Get the decrypted recaller cookie for the request. + * + * @return \Illuminate\Auth\Recaller|null + */ + protected function recaller() + { + if (is_null($this->request)) { + return; + } + + if ($recaller = $this->request->cookies->get($this->getRecallerName())) { + return new Recaller($recaller); + } + } + + /** + * Get the ID for the currently authenticated user. + * + * @return int|string|null + */ + public function id() + { + if ($this->loggedOut) { + return; + } + + return $this->user() + ? $this->user()->getAuthIdentifier() + : $this->session->get($this->getName()); + } + + /** + * Log a user into the application without sessions or cookies. + * + * @param array $credentials + * @return bool + */ + public function once(array $credentials = []) + { + $this->fireAttemptEvent($credentials); + + if ($this->validate($credentials)) { + $this->setUser($this->lastAttempted); + + return true; + } + + return false; + } + + /** + * Log the given user ID into the application without sessions or cookies. + * + * @param mixed $id + * @return \Illuminate\Contracts\Auth\Authenticatable|false + */ + public function onceUsingId($id) + { + if (! is_null($user = $this->provider->retrieveById($id))) { + $this->setUser($user); + + return $user; + } + + return false; + } + + /** + * Validate a user's credentials. + * + * @param array $credentials + * @return bool + */ + public function validate(array $credentials = []) + { + $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); + + return $this->hasValidCredentials($user, $credentials); + } + + /** + * Attempt to authenticate using HTTP Basic Auth. + * + * @param string $field + * @param array $extraConditions + * @return \Symfony\Component\HttpFoundation\Response|null + */ + public function basic($field = 'email', $extraConditions = []) + { + if ($this->check()) { + return; + } + + // If a username is set on the HTTP basic request, we will return out without + // interrupting the request lifecycle. Otherwise, we'll need to generate a + // request indicating that the given credentials were invalid for login. + if ($this->attemptBasic($this->getRequest(), $field, $extraConditions)) { + return; + } + + return $this->failedBasicResponse(); + } + + /** + * Perform a stateless HTTP Basic login attempt. + * + * @param string $field + * @param array $extraConditions + * @return \Symfony\Component\HttpFoundation\Response|null + */ + public function onceBasic($field = 'email', $extraConditions = []) + { + $credentials = $this->basicCredentials($this->getRequest(), $field); + + if (! $this->once(array_merge($credentials, $extraConditions))) { + return $this->failedBasicResponse(); + } + } + + /** + * Attempt to authenticate using basic authentication. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param string $field + * @param array $extraConditions + * @return bool + */ + protected function attemptBasic(Request $request, $field, $extraConditions = []) + { + if (! $request->getUser()) { + return false; + } + + return $this->attempt(array_merge( + $this->basicCredentials($request, $field), $extraConditions + )); + } + + /** + * Get the credential array for an HTTP Basic request. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param string $field + * @return array + */ + protected function basicCredentials(Request $request, $field) + { + return [$field => $request->getUser(), 'password' => $request->getPassword()]; + } + + /** + * Get the response for basic authentication. + * + * @return void + * + * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException + */ + protected function failedBasicResponse() + { + throw new UnauthorizedHttpException('Basic', 'Invalid credentials.'); + } + + /** + * Attempt to authenticate a user using the given credentials. + * + * @param array $credentials + * @param bool $remember + * @return bool + */ + public function attempt(array $credentials = [], $remember = false) + { + $this->fireAttemptEvent($credentials, $remember); + + $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); + + // If an implementation of UserInterface was returned, we'll ask the provider + // to validate the user against the given credentials, and if they are in + // fact valid we'll log the users into the application and return true. + if ($this->hasValidCredentials($user, $credentials)) { + $this->login($user, $remember); + + return true; + } + + // If the authentication attempt fails we will fire an event so that the user + // may be notified of any suspicious attempts to access their account from + // an unrecognized user. A developer may listen to this event as needed. + $this->fireFailedEvent($user, $credentials); + + return false; + } + + /** + * Attempt to authenticate a user with credentials and additional callbacks. + * + * @param array $credentials + * @param array|callable $callbacks + * @param false $remember + * @return bool + */ + public function attemptWhen(array $credentials = [], $callbacks = null, $remember = false) + { + $this->fireAttemptEvent($credentials, $remember); + + $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); + + // This method does the exact same thing as attempt, but also executes callbacks after + // the user is retrieved and validated. If one of the callbacks returns falsy we do + // not login the user. Instead, we will fail the specific authentication attempt. + if ($this->hasValidCredentials($user, $credentials) && $this->shouldLogin($callbacks, $user)) { + $this->login($user, $remember); + + return true; + } + + $this->fireFailedEvent($user, $credentials); + + return false; + } + + /** + * Determine if the user matches the credentials. + * + * @param mixed $user + * @param array $credentials + * @return bool + */ + protected function hasValidCredentials($user, $credentials) + { + return $this->timebox->call(function ($timebox) use ($user, $credentials) { + $validated = ! is_null($user) && $this->provider->validateCredentials($user, $credentials); + + if ($validated) { + $timebox->returnEarly(); + + $this->fireValidatedEvent($user); + } + + return $validated; + }, 200 * 1000); + } + + /** + * Determine if the user should login by executing the given callbacks. + * + * @param array|callable|null $callbacks + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return bool + */ + protected function shouldLogin($callbacks, AuthenticatableContract $user) + { + foreach (Arr::wrap($callbacks) as $callback) { + if (! $callback($user, $this)) { + return false; + } + } + + return true; + } + + /** + * Log the given user ID into the application. + * + * @param mixed $id + * @param bool $remember + * @return \Illuminate\Contracts\Auth\Authenticatable|false + */ + public function loginUsingId($id, $remember = false) + { + if (! is_null($user = $this->provider->retrieveById($id))) { + $this->login($user, $remember); + + return $user; + } + + return false; + } + + /** + * Log a user into the application. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param bool $remember + * @return void + */ + public function login(AuthenticatableContract $user, $remember = false) + { + $this->updateSession($user->getAuthIdentifier()); + + // If the user should be permanently "remembered" by the application we will + // queue a permanent cookie that contains the encrypted copy of the user + // identifier. We will then decrypt this later to retrieve the users. + if ($remember) { + $this->ensureRememberTokenIsSet($user); + + $this->queueRecallerCookie($user); + } + + // If we have an event dispatcher instance set we will fire an event so that + // any listeners will hook into the authentication events and run actions + // based on the login and logout events fired from the guard instances. + $this->fireLoginEvent($user, $remember); + + $this->setUser($user); + } + + /** + * Update the session with the given ID. + * + * @param string $id + * @return void + */ + protected function updateSession($id) + { + $this->session->put($this->getName(), $id); + + $this->session->migrate(true); + } + + /** + * Create a new "remember me" token for the user if one doesn't already exist. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return void + */ + protected function ensureRememberTokenIsSet(AuthenticatableContract $user) + { + if (empty($user->getRememberToken())) { + $this->cycleRememberToken($user); + } + } + + /** + * Queue the recaller cookie into the cookie jar. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return void + */ + protected function queueRecallerCookie(AuthenticatableContract $user) + { + $this->getCookieJar()->queue($this->createRecaller( + $user->getAuthIdentifier().'|'.$user->getRememberToken().'|'.$user->getAuthPassword() + )); + } + + /** + * Create a "remember me" cookie for a given ID. + * + * @param string $value + * @return \Symfony\Component\HttpFoundation\Cookie + */ + protected function createRecaller($value) + { + return $this->getCookieJar()->make($this->getRecallerName(), $value, $this->getRememberDuration()); + } + + /** + * Log the user out of the application. + * + * @return void + */ + public function logout() + { + $user = $this->user(); + + $this->clearUserDataFromStorage(); + + if (! is_null($this->user) && ! empty($user->getRememberToken())) { + $this->cycleRememberToken($user); + } + + // If we have an event dispatcher instance, we can fire off the logout event + // so any further processing can be done. This allows the developer to be + // listening for anytime a user signs out of this application manually. + if (isset($this->events)) { + $this->events->dispatch(new Logout($this->name, $user)); + } + + // Once we have fired the logout event we will clear the users out of memory + // so they are no longer available as the user is no longer considered as + // being signed into this application and should not be available here. + $this->user = null; + + $this->loggedOut = true; + } + + /** + * Log the user out of the application on their current device only. + * + * This method does not cycle the "remember" token. + * + * @return void + */ + public function logoutCurrentDevice() + { + $user = $this->user(); + + $this->clearUserDataFromStorage(); + + // If we have an event dispatcher instance, we can fire off the logout event + // so any further processing can be done. This allows the developer to be + // listening for anytime a user signs out of this application manually. + if (isset($this->events)) { + $this->events->dispatch(new CurrentDeviceLogout($this->name, $user)); + } + + // Once we have fired the logout event we will clear the users out of memory + // so they are no longer available as the user is no longer considered as + // being signed into this application and should not be available here. + $this->user = null; + + $this->loggedOut = true; + } + + /** + * Remove the user data from the session and cookies. + * + * @return void + */ + protected function clearUserDataFromStorage() + { + $this->session->remove($this->getName()); + + if (! is_null($this->recaller())) { + $this->getCookieJar()->queue($this->getCookieJar() + ->forget($this->getRecallerName())); + } + } + + /** + * Refresh the "remember me" token for the user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return void + */ + protected function cycleRememberToken(AuthenticatableContract $user) + { + $user->setRememberToken($token = Str::random(60)); + + $this->provider->updateRememberToken($user, $token); + } + + /** + * Invalidate other sessions for the current user. + * + * The application must be using the AuthenticateSession middleware. + * + * @param string $password + * @param string $attribute + * @return \Illuminate\Contracts\Auth\Authenticatable|null + * + * @throws \Illuminate\Auth\AuthenticationException + */ + public function logoutOtherDevices($password, $attribute = 'password') + { + if (! $this->user()) { + return; + } + + $result = $this->rehashUserPassword($password, $attribute); + + if ($this->recaller() || + $this->getCookieJar()->hasQueued($this->getRecallerName())) { + $this->queueRecallerCookie($this->user()); + } + + $this->fireOtherDeviceLogoutEvent($this->user()); + + return $result; + } + + /** + * Rehash the current user's password. + * + * @param string $password + * @param string $attribute + * @return \Illuminate\Contracts\Auth\Authenticatable|null + * + * @throws \InvalidArgumentException + */ + protected function rehashUserPassword($password, $attribute) + { + if (! Hash::check($password, $this->user()->{$attribute})) { + throw new InvalidArgumentException('The given password does not match the current password.'); + } + + return tap($this->user()->forceFill([ + $attribute => Hash::make($password), + ]))->save(); + } + + /** + * Register an authentication attempt event listener. + * + * @param mixed $callback + * @return void + */ + public function attempting($callback) + { + if (isset($this->events)) { + $this->events->listen(Events\Attempting::class, $callback); + } + } + + /** + * Fire the attempt event with the arguments. + * + * @param array $credentials + * @param bool $remember + * @return void + */ + protected function fireAttemptEvent(array $credentials, $remember = false) + { + if (isset($this->events)) { + $this->events->dispatch(new Attempting( + $this->name, $credentials, $remember + )); + } + } + + /** + * Fires the validated event if the dispatcher is set. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return void + */ + protected function fireValidatedEvent($user) + { + if (isset($this->events)) { + $this->events->dispatch(new Validated( + $this->name, $user + )); + } + } + + /** + * Fire the login event if the dispatcher is set. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param bool $remember + * @return void + */ + protected function fireLoginEvent($user, $remember = false) + { + if (isset($this->events)) { + $this->events->dispatch(new Login( + $this->name, $user, $remember + )); + } + } + + /** + * Fire the authenticated event if the dispatcher is set. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return void + */ + protected function fireAuthenticatedEvent($user) + { + if (isset($this->events)) { + $this->events->dispatch(new Authenticated( + $this->name, $user + )); + } + } + + /** + * Fire the other device logout event if the dispatcher is set. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return void + */ + protected function fireOtherDeviceLogoutEvent($user) + { + if (isset($this->events)) { + $this->events->dispatch(new OtherDeviceLogout( + $this->name, $user + )); + } + } + + /** + * Fire the failed authentication attempt event with the given arguments. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param array $credentials + * @return void + */ + protected function fireFailedEvent($user, array $credentials) + { + if (isset($this->events)) { + $this->events->dispatch(new Failed( + $this->name, $user, $credentials + )); + } + } + + /** + * Get the last user we attempted to authenticate. + * + * @return \Illuminate\Contracts\Auth\Authenticatable + */ + public function getLastAttempted() + { + return $this->lastAttempted; + } + + /** + * Get a unique identifier for the auth session value. + * + * @return string + */ + public function getName() + { + return 'login_'.$this->name.'_'.sha1(static::class); + } + + /** + * Get the name of the cookie used to store the "recaller". + * + * @return string + */ + public function getRecallerName() + { + return 'remember_'.$this->name.'_'.sha1(static::class); + } + + /** + * Determine if the user was authenticated via "remember me" cookie. + * + * @return bool + */ + public function viaRemember() + { + return $this->viaRemember; + } + + /** + * Get the number of minutes the remember me cookie should be valid for. + * + * @return int + */ + protected function getRememberDuration() + { + return $this->rememberDuration; + } + + /** + * Set the number of minutes the remember me cookie should be valid for. + * + * @param int $minutes + * @return $this + */ + public function setRememberDuration($minutes) + { + $this->rememberDuration = $minutes; + + return $this; + } + + /** + * Get the cookie creator instance used by the guard. + * + * @return \Illuminate\Contracts\Cookie\QueueingFactory + * + * @throws \RuntimeException + */ + public function getCookieJar() + { + if (! isset($this->cookie)) { + throw new RuntimeException('Cookie jar has not been set.'); + } + + return $this->cookie; + } + + /** + * Set the cookie creator instance used by the guard. + * + * @param \Illuminate\Contracts\Cookie\QueueingFactory $cookie + * @return void + */ + public function setCookieJar(CookieJar $cookie) + { + $this->cookie = $cookie; + } + + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public function getDispatcher() + { + return $this->events; + } + + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + */ + public function setDispatcher(Dispatcher $events) + { + $this->events = $events; + } + + /** + * Get the session store used by the guard. + * + * @return \Illuminate\Contracts\Session\Session + */ + public function getSession() + { + return $this->session; + } + + /** + * Return the currently cached user. + * + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function getUser() + { + return $this->user; + } + + /** + * Set the current user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return $this + */ + public function setUser(AuthenticatableContract $user) + { + $this->user = $user; + + $this->loggedOut = false; + + $this->fireAuthenticatedEvent($user); + + return $this; + } + + /** + * Get the current request instance. + * + * @return \Symfony\Component\HttpFoundation\Request + */ + public function getRequest() + { + return $this->request ?: Request::createFromGlobals(); + } + + /** + * Set the current request instance. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @return $this + */ + public function setRequest(Request $request) + { + $this->request = $request; + + return $this; + } + + /** + * Get the timebox instance used by the guard. + * + * @return \Illuminate\Support\Timebox + */ + public function getTimebox() + { + return $this->timebox; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/TokenGuard.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/TokenGuard.php new file mode 100644 index 0000000..b1aa7a7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/TokenGuard.php @@ -0,0 +1,149 @@ +hash = $hash; + $this->request = $request; + $this->provider = $provider; + $this->inputKey = $inputKey; + $this->storageKey = $storageKey; + } + + /** + * Get the currently authenticated user. + * + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function user() + { + // If we've already retrieved the user for the current request we can just + // return it back immediately. We do not want to fetch the user data on + // every call to this method because that would be tremendously slow. + if (! is_null($this->user)) { + return $this->user; + } + + $user = null; + + $token = $this->getTokenForRequest(); + + if (! empty($token)) { + $user = $this->provider->retrieveByCredentials([ + $this->storageKey => $this->hash ? hash('sha256', $token) : $token, + ]); + } + + return $this->user = $user; + } + + /** + * Get the token for the current request. + * + * @return string + */ + public function getTokenForRequest() + { + $token = $this->request->query($this->inputKey); + + if (empty($token)) { + $token = $this->request->input($this->inputKey); + } + + if (empty($token)) { + $token = $this->request->bearerToken(); + } + + if (empty($token)) { + $token = $this->request->getPassword(); + } + + return $token; + } + + /** + * Validate a user's credentials. + * + * @param array $credentials + * @return bool + */ + public function validate(array $credentials = []) + { + if (empty($credentials[$this->inputKey])) { + return false; + } + + $credentials = [$this->storageKey => $credentials[$this->inputKey]]; + + if ($this->provider->retrieveByCredentials($credentials)) { + return true; + } + + return false; + } + + /** + * Set the current request instance. + * + * @param \Illuminate\Http\Request $request + * @return $this + */ + public function setRequest(Request $request) + { + $this->request = $request; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/composer.json new file mode 100644 index 0000000..842066c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Auth/composer.json @@ -0,0 +1,44 @@ +{ + "name": "illuminate/auth", + "description": "The Illuminate Auth package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/http": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/queue": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Auth\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "illuminate/console": "Required to use the auth:clear-resets command (^8.0).", + "illuminate/queue": "Required to fire login / logout events (^8.0).", + "illuminate/session": "Required to use the session based guard (^8.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastController.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastController.php new file mode 100644 index 0000000..486a602 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastController.php @@ -0,0 +1,25 @@ +hasSession()) { + $request->session()->reflash(); + } + + return Broadcast::auth($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php new file mode 100644 index 0000000..24a1c33 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php @@ -0,0 +1,140 @@ +event = $event; + $this->tries = property_exists($event, 'tries') ? $event->tries : null; + $this->timeout = property_exists($event, 'timeout') ? $event->timeout : null; + $this->afterCommit = property_exists($event, 'afterCommit') ? $event->afterCommit : null; + } + + /** + * Handle the queued job. + * + * @param \Illuminate\Contracts\Broadcasting\Factory $manager + * @return void + */ + public function handle(BroadcastingFactory $manager) + { + $name = method_exists($this->event, 'broadcastAs') + ? $this->event->broadcastAs() : get_class($this->event); + + $channels = Arr::wrap($this->event->broadcastOn()); + + if (empty($channels)) { + return; + } + + $connections = method_exists($this->event, 'broadcastConnections') + ? $this->event->broadcastConnections() + : [null]; + + $payload = $this->getPayloadFromEvent($this->event); + + foreach ($connections as $connection) { + $manager->connection($connection)->broadcast( + $channels, $name, $payload + ); + } + } + + /** + * Get the payload for the given event. + * + * @param mixed $event + * @return array + */ + protected function getPayloadFromEvent($event) + { + if (method_exists($event, 'broadcastWith') && + ! is_null($payload = $event->broadcastWith())) { + return array_merge($payload, ['socket' => data_get($event, 'socket')]); + } + + $payload = []; + + foreach ((new ReflectionClass($event))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + $payload[$property->getName()] = $this->formatProperty($property->getValue($event)); + } + + unset($payload['broadcastQueue']); + + return $payload; + } + + /** + * Format the given value for a property. + * + * @param mixed $value + * @return mixed + */ + protected function formatProperty($value) + { + if ($value instanceof Arrayable) { + return $value->toArray(); + } + + return $value; + } + + /** + * Get the display name for the queued job. + * + * @return string + */ + public function displayName() + { + return get_class($this->event); + } + + /** + * Prepare the instance for cloning. + * + * @return void + */ + public function __clone() + { + $this->event = clone $this->event; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastException.php new file mode 100644 index 0000000..8fd55f7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastException.php @@ -0,0 +1,10 @@ +app = $app; + } + + /** + * Register the routes for handling broadcast authentication and sockets. + * + * @param array|null $attributes + * @return void + */ + public function routes(array $attributes = null) + { + if ($this->app instanceof CachesRoutes && $this->app->routesAreCached()) { + return; + } + + $attributes = $attributes ?: ['middleware' => ['web']]; + + $this->app['router']->group($attributes, function ($router) { + $router->match( + ['get', 'post'], '/broadcasting/auth', + '\\'.BroadcastController::class.'@authenticate' + )->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]); + }); + } + + /** + * Get the socket ID for the given request. + * + * @param \Illuminate\Http\Request|null $request + * @return string|null + */ + public function socket($request = null) + { + if (! $request && ! $this->app->bound('request')) { + return; + } + + $request = $request ?: $this->app['request']; + + return $request->header('X-Socket-ID'); + } + + /** + * Begin broadcasting an event. + * + * @param mixed|null $event + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + public function event($event = null) + { + return new PendingBroadcast($this->app->make('events'), $event); + } + + /** + * Queue the given event for broadcast. + * + * @param mixed $event + * @return void + */ + public function queue($event) + { + if ($event instanceof ShouldBroadcastNow || + (is_object($event) && + method_exists($event, 'shouldBroadcastNow') && + $event->shouldBroadcastNow())) { + return $this->app->make(BusDispatcherContract::class)->dispatchNow(new BroadcastEvent(clone $event)); + } + + $queue = null; + + if (method_exists($event, 'broadcastQueue')) { + $queue = $event->broadcastQueue(); + } elseif (isset($event->broadcastQueue)) { + $queue = $event->broadcastQueue; + } elseif (isset($event->queue)) { + $queue = $event->queue; + } + + $this->app->make('queue')->connection($event->connection ?? null)->pushOn( + $queue, new BroadcastEvent(clone $event) + ); + } + + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + */ + public function connection($driver = null) + { + return $this->driver($driver); + } + + /** + * Get a driver instance. + * + * @param string|null $name + * @return mixed + */ + public function driver($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + return $this->drivers[$name] = $this->get($name); + } + + /** + * Attempt to get the connection from the local cache. + * + * @param string $name + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + */ + protected function get($name) + { + return $this->drivers[$name] ?? $this->resolve($name); + } + + /** + * Resolve the given broadcaster. + * + * @param string $name + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getConfig($name); + + if (isset($this->customCreators[$config['driver']])) { + return $this->callCustomCreator($config); + } + + $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; + + if (! method_exists($this, $driverMethod)) { + throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported."); + } + + return $this->{$driverMethod}($config); + } + + /** + * Call a custom driver creator. + * + * @param array $config + * @return mixed + */ + protected function callCustomCreator(array $config) + { + return $this->customCreators[$config['driver']]($this->app, $config); + } + + /** + * Create an instance of the driver. + * + * @param array $config + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + */ + protected function createPusherDriver(array $config) + { + $pusher = new Pusher( + $config['key'], $config['secret'], + $config['app_id'], $config['options'] ?? [] + ); + + if ($config['log'] ?? false) { + $pusher->setLogger($this->app->make(LoggerInterface::class)); + } + + return new PusherBroadcaster($pusher); + } + + /** + * Create an instance of the driver. + * + * @param array $config + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + */ + protected function createAblyDriver(array $config) + { + return new AblyBroadcaster(new AblyRest($config)); + } + + /** + * Create an instance of the driver. + * + * @param array $config + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + */ + protected function createRedisDriver(array $config) + { + return new RedisBroadcaster( + $this->app->make('redis'), $config['connection'] ?? null, + $this->app['config']->get('database.redis.options.prefix', '') + ); + } + + /** + * Create an instance of the driver. + * + * @param array $config + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + */ + protected function createLogDriver(array $config) + { + return new LogBroadcaster( + $this->app->make(LoggerInterface::class) + ); + } + + /** + * Create an instance of the driver. + * + * @param array $config + * @return \Illuminate\Contracts\Broadcasting\Broadcaster + */ + protected function createNullDriver(array $config) + { + return new NullBroadcaster; + } + + /** + * Get the connection configuration. + * + * @param string $name + * @return array + */ + protected function getConfig($name) + { + if (! is_null($name) && $name !== 'null') { + return $this->app['config']["broadcasting.connections.{$name}"]; + } + + return ['driver' => 'null']; + } + + /** + * Get the default driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->app['config']['broadcasting.default']; + } + + /** + * Set the default driver name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->app['config']['broadcasting.default'] = $name; + } + + /** + * Disconnect the given disk and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?? $this->getDefaultDriver(); + + unset($this->drivers[$name]); + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback; + + return $this; + } + + /** + * Get the application instance used by the manager. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public function getApplication() + { + return $this->app; + } + + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication($app) + { + $this->app = $app; + + return $this; + } + + /** + * Forget all of the resolved driver instances. + * + * @return $this + */ + public function forgetDrivers() + { + $this->drivers = []; + + return $this; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->driver()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastServiceProvider.php new file mode 100644 index 0000000..e6897e2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastServiceProvider.php @@ -0,0 +1,45 @@ +app->singleton(BroadcastManager::class, function ($app) { + return new BroadcastManager($app); + }); + + $this->app->singleton(BroadcasterContract::class, function ($app) { + return $app->make(BroadcastManager::class)->connection(); + }); + + $this->app->alias( + BroadcastManager::class, BroadcastingFactory::class + ); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + BroadcastManager::class, + BroadcastingFactory::class, + BroadcasterContract::class, + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php new file mode 100644 index 0000000..ead68a1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php @@ -0,0 +1,225 @@ +ably = $ably; + } + + /** + * Authenticate the incoming request for a given channel. + * + * @param \Illuminate\Http\Request $request + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException + */ + public function auth($request) + { + $channelName = $this->normalizeChannelName($request->channel_name); + + if (empty($request->channel_name) || + ($this->isGuardedChannel($request->channel_name) && + ! $this->retrieveUser($request, $channelName))) { + throw new AccessDeniedHttpException; + } + + return parent::verifyUserCanAccessChannel( + $request, $channelName + ); + } + + /** + * Return the valid authentication response. + * + * @param \Illuminate\Http\Request $request + * @param mixed $result + * @return mixed + */ + public function validAuthenticationResponse($request, $result) + { + if (Str::startsWith($request->channel_name, 'private')) { + $signature = $this->generateAblySignature( + $request->channel_name, $request->socket_id + ); + + return ['auth' => $this->getPublicToken().':'.$signature]; + } + + $channelName = $this->normalizeChannelName($request->channel_name); + + $user = $this->retrieveUser($request, $channelName); + + $broadcastIdentifier = method_exists($user, 'getAuthIdentifierForBroadcasting') + ? $user->getAuthIdentifierForBroadcasting() + : $user->getAuthIdentifier(); + + $signature = $this->generateAblySignature( + $request->channel_name, + $request->socket_id, + $userData = array_filter([ + 'user_id' => (string) $broadcastIdentifier, + 'user_info' => $result, + ]) + ); + + return [ + 'auth' => $this->getPublicToken().':'.$signature, + 'channel_data' => json_encode($userData), + ]; + } + + /** + * Generate the signature needed for Ably authentication headers. + * + * @param string $channelName + * @param string $socketId + * @param array|null $userData + * @return string + */ + public function generateAblySignature($channelName, $socketId, $userData = null) + { + return hash_hmac( + 'sha256', + sprintf('%s:%s%s', $socketId, $channelName, $userData ? ':'.json_encode($userData) : ''), + $this->getPrivateToken(), + ); + } + + /** + * Broadcast the given event. + * + * @param array $channels + * @param string $event + * @param array $payload + * @return void + */ + public function broadcast(array $channels, $event, array $payload = []) + { + foreach ($this->formatChannels($channels) as $channel) { + $this->ably->channels->get($channel)->publish( + $this->buildAblyMessage($event, $payload) + ); + } + } + + /** + * Build an Ably message object for broadcasting. + * + * @param string $event + * @param array $payload + * @return \Ably\Models\Message + */ + protected function buildAblyMessage($event, array $payload = []) + { + return tap(new AblyMessage, function ($message) use ($event, $payload) { + $message->name = $event; + $message->data = $payload; + $message->connectionKey = data_get($payload, 'socket'); + }); + } + + /** + * Return true if the channel is protected by authentication. + * + * @param string $channel + * @return bool + */ + public function isGuardedChannel($channel) + { + return Str::startsWith($channel, ['private-', 'presence-']); + } + + /** + * Remove prefix from channel name. + * + * @param string $channel + * @return string + */ + public function normalizeChannelName($channel) + { + if ($this->isGuardedChannel($channel)) { + return Str::startsWith($channel, 'private-') + ? Str::replaceFirst('private-', '', $channel) + : Str::replaceFirst('presence-', '', $channel); + } + + return $channel; + } + + /** + * Format the channel array into an array of strings. + * + * @param array $channels + * @return array + */ + protected function formatChannels(array $channels) + { + return array_map(function ($channel) { + $channel = (string) $channel; + + if (Str::startsWith($channel, ['private-', 'presence-'])) { + return Str::startsWith($channel, 'private-') + ? Str::replaceFirst('private-', 'private:', $channel) + : Str::replaceFirst('presence-', 'presence:', $channel); + } + + return 'public:'.$channel; + }, $channels); + } + + /** + * Get the public token value from the Ably key. + * + * @return mixed + */ + protected function getPublicToken() + { + return Str::before($this->ably->options->key, ':'); + } + + /** + * Get the private token value from the Ably key. + * + * @return mixed + */ + protected function getPrivateToken() + { + return Str::after($this->ably->options->key, ':'); + } + + /** + * Get the underlying Ably SDK instance. + * + * @return \Ably\AblyRest + */ + public function getAbly() + { + return $this->ably; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php new file mode 100644 index 0000000..a25b2ff --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php @@ -0,0 +1,337 @@ +broadcastChannelRoute(); + } elseif (is_string($channel) && class_exists($channel) && is_a($channel, HasBroadcastChannel::class, true)) { + $channel = (new $channel)->broadcastChannelRoute(); + } + + $this->channels[$channel] = $callback; + + $this->channelOptions[$channel] = $options; + + return $this; + } + + /** + * Authenticate the incoming request for a given channel. + * + * @param \Illuminate\Http\Request $request + * @param string $channel + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException + */ + protected function verifyUserCanAccessChannel($request, $channel) + { + foreach ($this->channels as $pattern => $callback) { + if (! $this->channelNameMatchesPattern($channel, $pattern)) { + continue; + } + + $parameters = $this->extractAuthParameters($pattern, $channel, $callback); + + $handler = $this->normalizeChannelHandlerToCallable($callback); + + if ($result = $handler($this->retrieveUser($request, $channel), ...$parameters)) { + return $this->validAuthenticationResponse($request, $result); + } + } + + throw new AccessDeniedHttpException; + } + + /** + * Extract the parameters from the given pattern and channel. + * + * @param string $pattern + * @param string $channel + * @param callable|string $callback + * @return array + */ + protected function extractAuthParameters($pattern, $channel, $callback) + { + $callbackParameters = $this->extractParameters($callback); + + return collect($this->extractChannelKeys($pattern, $channel))->reject(function ($value, $key) { + return is_numeric($key); + })->map(function ($value, $key) use ($callbackParameters) { + return $this->resolveBinding($key, $value, $callbackParameters); + })->values()->all(); + } + + /** + * Extracts the parameters out of what the user passed to handle the channel authentication. + * + * @param callable|string $callback + * @return \ReflectionParameter[] + * + * @throws \Exception + */ + protected function extractParameters($callback) + { + if (is_callable($callback)) { + return (new ReflectionFunction($callback))->getParameters(); + } elseif (is_string($callback)) { + return $this->extractParametersFromClass($callback); + } + + throw new Exception('Given channel handler is an unknown type.'); + } + + /** + * Extracts the parameters out of a class channel's "join" method. + * + * @param string $callback + * @return \ReflectionParameter[] + * + * @throws \Exception + */ + protected function extractParametersFromClass($callback) + { + $reflection = new ReflectionClass($callback); + + if (! $reflection->hasMethod('join')) { + throw new Exception('Class based channel must define a "join" method.'); + } + + return $reflection->getMethod('join')->getParameters(); + } + + /** + * Extract the channel keys from the incoming channel name. + * + * @param string $pattern + * @param string $channel + * @return array + */ + protected function extractChannelKeys($pattern, $channel) + { + preg_match('/^'.preg_replace('/\{(.*?)\}/', '(?<$1>[^\.]+)', $pattern).'/', $channel, $keys); + + return $keys; + } + + /** + * Resolve the given parameter binding. + * + * @param string $key + * @param string $value + * @param array $callbackParameters + * @return mixed + */ + protected function resolveBinding($key, $value, $callbackParameters) + { + $newValue = $this->resolveExplicitBindingIfPossible($key, $value); + + return $newValue === $value ? $this->resolveImplicitBindingIfPossible( + $key, $value, $callbackParameters + ) : $newValue; + } + + /** + * Resolve an explicit parameter binding if applicable. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function resolveExplicitBindingIfPossible($key, $value) + { + $binder = $this->binder(); + + if ($binder && $binder->getBindingCallback($key)) { + return call_user_func($binder->getBindingCallback($key), $value); + } + + return $value; + } + + /** + * Resolve an implicit parameter binding if applicable. + * + * @param string $key + * @param mixed $value + * @param array $callbackParameters + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException + */ + protected function resolveImplicitBindingIfPossible($key, $value, $callbackParameters) + { + foreach ($callbackParameters as $parameter) { + if (! $this->isImplicitlyBindable($key, $parameter)) { + continue; + } + + $className = Reflector::getParameterClassName($parameter); + + if (is_null($model = (new $className)->resolveRouteBinding($value))) { + throw new AccessDeniedHttpException; + } + + return $model; + } + + return $value; + } + + /** + * Determine if a given key and parameter is implicitly bindable. + * + * @param string $key + * @param \ReflectionParameter $parameter + * @return bool + */ + protected function isImplicitlyBindable($key, $parameter) + { + return $parameter->getName() === $key && + Reflector::isParameterSubclassOf($parameter, UrlRoutable::class); + } + + /** + * Format the channel array into an array of strings. + * + * @param array $channels + * @return array + */ + protected function formatChannels(array $channels) + { + return array_map(function ($channel) { + return (string) $channel; + }, $channels); + } + + /** + * Get the model binding registrar instance. + * + * @return \Illuminate\Contracts\Routing\BindingRegistrar + */ + protected function binder() + { + if (! $this->bindingRegistrar) { + $this->bindingRegistrar = Container::getInstance()->bound(BindingRegistrar::class) + ? Container::getInstance()->make(BindingRegistrar::class) : null; + } + + return $this->bindingRegistrar; + } + + /** + * Normalize the given callback into a callable. + * + * @param mixed $callback + * @return callable + */ + protected function normalizeChannelHandlerToCallable($callback) + { + return is_callable($callback) ? $callback : function (...$args) use ($callback) { + return Container::getInstance() + ->make($callback) + ->join(...$args); + }; + } + + /** + * Retrieve the authenticated user using the configured guard (if any). + * + * @param \Illuminate\Http\Request $request + * @param string $channel + * @return mixed + */ + protected function retrieveUser($request, $channel) + { + $options = $this->retrieveChannelOptions($channel); + + $guards = $options['guards'] ?? null; + + if (is_null($guards)) { + return $request->user(); + } + + foreach (Arr::wrap($guards) as $guard) { + if ($user = $request->user($guard)) { + return $user; + } + } + } + + /** + * Retrieve options for a certain channel. + * + * @param string $channel + * @return array + */ + protected function retrieveChannelOptions($channel) + { + foreach ($this->channelOptions as $pattern => $options) { + if (! $this->channelNameMatchesPattern($channel, $pattern)) { + continue; + } + + return $options; + } + + return []; + } + + /** + * Check if the channel name from the request matches a pattern from registered channels. + * + * @param string $channel + * @param string $pattern + * @return bool + */ + protected function channelNameMatchesPattern($channel, $pattern) + { + return Str::is(preg_replace('/\{(.*?)\}/', '*', $pattern), $channel); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/LogBroadcaster.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/LogBroadcaster.php new file mode 100644 index 0000000..50877dc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/LogBroadcaster.php @@ -0,0 +1,54 @@ +logger = $logger; + } + + /** + * {@inheritdoc} + */ + public function auth($request) + { + // + } + + /** + * {@inheritdoc} + */ + public function validAuthenticationResponse($request, $result) + { + // + } + + /** + * {@inheritdoc} + */ + public function broadcast(array $channels, $event, array $payload = []) + { + $channels = implode(', ', $this->formatChannels($channels)); + + $payload = json_encode($payload, JSON_PRETTY_PRINT); + + $this->logger->info('Broadcasting ['.$event.'] on channels ['.$channels.'] with payload:'.PHP_EOL.$payload); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/NullBroadcaster.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/NullBroadcaster.php new file mode 100644 index 0000000..6205c90 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/NullBroadcaster.php @@ -0,0 +1,30 @@ +pusher = $pusher; + } + + /** + * Authenticate the incoming request for a given channel. + * + * @param \Illuminate\Http\Request $request + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException + */ + public function auth($request) + { + $channelName = $this->normalizeChannelName($request->channel_name); + + if (empty($request->channel_name) || + ($this->isGuardedChannel($request->channel_name) && + ! $this->retrieveUser($request, $channelName))) { + throw new AccessDeniedHttpException; + } + + return parent::verifyUserCanAccessChannel( + $request, $channelName + ); + } + + /** + * Return the valid authentication response. + * + * @param \Illuminate\Http\Request $request + * @param mixed $result + * @return mixed + */ + public function validAuthenticationResponse($request, $result) + { + if (Str::startsWith($request->channel_name, 'private')) { + return $this->decodePusherResponse( + $request, $this->pusher->socket_auth($request->channel_name, $request->socket_id) + ); + } + + $channelName = $this->normalizeChannelName($request->channel_name); + + $user = $this->retrieveUser($request, $channelName); + + $broadcastIdentifier = method_exists($user, 'getAuthIdentifierForBroadcasting') + ? $user->getAuthIdentifierForBroadcasting() + : $user->getAuthIdentifier(); + + return $this->decodePusherResponse( + $request, + $this->pusher->presence_auth( + $request->channel_name, $request->socket_id, + $broadcastIdentifier, $result + ) + ); + } + + /** + * Decode the given Pusher response. + * + * @param \Illuminate\Http\Request $request + * @param mixed $response + * @return array + */ + protected function decodePusherResponse($request, $response) + { + if (! $request->input('callback', false)) { + return json_decode($response, true); + } + + return response()->json(json_decode($response, true)) + ->withCallback($request->callback); + } + + /** + * Broadcast the given event. + * + * @param array $channels + * @param string $event + * @param array $payload + * @return void + * + * @throws \Illuminate\Broadcasting\BroadcastException + */ + public function broadcast(array $channels, $event, array $payload = []) + { + $socket = Arr::pull($payload, 'socket'); + + if ($this->pusherServerIsVersionFiveOrGreater()) { + $parameters = $socket !== null ? ['socket_id' => $socket] : []; + + try { + $this->pusher->trigger( + $this->formatChannels($channels), $event, $payload, $parameters + ); + } catch (ApiErrorException $e) { + throw new BroadcastException( + sprintf('Pusher error: %s.', $e->getMessage()) + ); + } + } else { + $response = $this->pusher->trigger( + $this->formatChannels($channels), $event, $payload, $socket, true + ); + + if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299) + || $response === true) { + return; + } + + throw new BroadcastException( + ! empty($response['body']) + ? sprintf('Pusher error: %s.', $response['body']) + : 'Failed to connect to Pusher.' + ); + } + } + + /** + * Determine if the Pusher PHP server is version 5.0 or greater. + * + * @return bool + */ + protected function pusherServerIsVersionFiveOrGreater() + { + return class_exists(ApiErrorException::class); + } + + /** + * Get the Pusher SDK instance. + * + * @return \Pusher\Pusher + */ + public function getPusher() + { + return $this->pusher; + } + + /** + * Set the Pusher SDK instance. + * + * @param \Pusher\Pusher $pusher + * @return void + */ + public function setPusher($pusher) + { + $this->pusher = $pusher; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/RedisBroadcaster.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/RedisBroadcaster.php new file mode 100644 index 0000000..2c2dc88 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/RedisBroadcaster.php @@ -0,0 +1,158 @@ +redis = $redis; + $this->prefix = $prefix; + $this->connection = $connection; + } + + /** + * Authenticate the incoming request for a given channel. + * + * @param \Illuminate\Http\Request $request + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException + */ + public function auth($request) + { + $channelName = $this->normalizeChannelName( + str_replace($this->prefix, '', $request->channel_name) + ); + + if (empty($request->channel_name) || + ($this->isGuardedChannel($request->channel_name) && + ! $this->retrieveUser($request, $channelName))) { + throw new AccessDeniedHttpException; + } + + return parent::verifyUserCanAccessChannel( + $request, $channelName + ); + } + + /** + * Return the valid authentication response. + * + * @param \Illuminate\Http\Request $request + * @param mixed $result + * @return mixed + */ + public function validAuthenticationResponse($request, $result) + { + if (is_bool($result)) { + return json_encode($result); + } + + $channelName = $this->normalizeChannelName($request->channel_name); + + $user = $this->retrieveUser($request, $channelName); + + $broadcastIdentifier = method_exists($user, 'getAuthIdentifierForBroadcasting') + ? $user->getAuthIdentifierForBroadcasting() + : $user->getAuthIdentifier(); + + return json_encode(['channel_data' => [ + 'user_id' => $broadcastIdentifier, + 'user_info' => $result, + ]]); + } + + /** + * Broadcast the given event. + * + * @param array $channels + * @param string $event + * @param array $payload + * @return void + */ + public function broadcast(array $channels, $event, array $payload = []) + { + if (empty($channels)) { + return; + } + + $connection = $this->redis->connection($this->connection); + + $payload = json_encode([ + 'event' => $event, + 'data' => $payload, + 'socket' => Arr::pull($payload, 'socket'), + ]); + + $connection->eval( + $this->broadcastMultipleChannelsScript(), + 0, $payload, ...$this->formatChannels($channels) + ); + } + + /** + * Get the Lua script for broadcasting to multiple channels. + * + * ARGV[1] - The payload + * ARGV[2...] - The channels + * + * @return string + */ + protected function broadcastMultipleChannelsScript() + { + return <<<'LUA' +for i = 2, #ARGV do + redis.call('publish', ARGV[i], ARGV[1]) +end +LUA; + } + + /** + * Format the channel array into an array of strings. + * + * @param array $channels + * @return array + */ + protected function formatChannels(array $channels) + { + return array_map(function ($channel) { + return $this->prefix.$channel; + }, parent::formatChannels($channels)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php new file mode 100644 index 0000000..690cf3d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php @@ -0,0 +1,36 @@ +name = $name instanceof HasBroadcastChannel ? $name->broadcastChannel() : $name; + } + + /** + * Convert the channel instance to a string. + * + * @return string + */ + public function __toString() + { + return $this->name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/EncryptedPrivateChannel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/EncryptedPrivateChannel.php new file mode 100644 index 0000000..76977c1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/EncryptedPrivateChannel.php @@ -0,0 +1,17 @@ +broadcastConnection = is_null($connection) + ? [null] + : Arr::wrap($connection); + + return $this; + } + + /** + * Get the broadcaster connections the event should be broadcast on. + * + * @return array + */ + public function broadcastConnections() + { + return $this->broadcastConnection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/InteractsWithSockets.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/InteractsWithSockets.php new file mode 100644 index 0000000..6be0791 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/InteractsWithSockets.php @@ -0,0 +1,39 @@ +socket = Broadcast::socket(); + + return $this; + } + + /** + * Broadcast the event to everyone. + * + * @return $this + */ + public function broadcastToEveryone() + { + $this->socket = null; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/PendingBroadcast.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/PendingBroadcast.php new file mode 100644 index 0000000..191b905 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/PendingBroadcast.php @@ -0,0 +1,74 @@ +event = $event; + $this->events = $events; + } + + /** + * Broadcast the event using a specific broadcaster. + * + * @param string|null $connection + * @return $this + */ + public function via($connection = null) + { + if (method_exists($this->event, 'broadcastVia')) { + $this->event->broadcastVia($connection); + } + + return $this; + } + + /** + * Broadcast the event to everyone except the current user. + * + * @return $this + */ + public function toOthers() + { + if (method_exists($this->event, 'dontBroadcastToCurrentUser')) { + $this->event->dontBroadcastToCurrentUser(); + } + + return $this; + } + + /** + * Handle the object's destruction. + * + * @return void + */ + public function __destruct() + { + $this->events->dispatch($this->event); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/PresenceChannel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/PresenceChannel.php new file mode 100644 index 0000000..22de12d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/PresenceChannel.php @@ -0,0 +1,17 @@ +broadcastChannel() : $name; + + parent::__construct('private-'.$name); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/composer.json new file mode 100644 index 0000000..42852c2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Broadcasting/composer.json @@ -0,0 +1,44 @@ +{ + "name": "illuminate/broadcasting", + "description": "The Illuminate Broadcasting package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "psr/log": "^1.0|^2.0", + "illuminate/bus": "^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/queue": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Broadcasting\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "ably/ably-php": "Required to use the Ably broadcast driver (^1.0).", + "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0|^5.0|^6.0|^7.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Batch.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Batch.php new file mode 100644 index 0000000..d1464e4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Batch.php @@ -0,0 +1,481 @@ +queue = $queue; + $this->repository = $repository; + $this->id = $id; + $this->name = $name; + $this->totalJobs = $totalJobs; + $this->pendingJobs = $pendingJobs; + $this->failedJobs = $failedJobs; + $this->failedJobIds = $failedJobIds; + $this->options = $options; + $this->createdAt = $createdAt; + $this->cancelledAt = $cancelledAt; + $this->finishedAt = $finishedAt; + } + + /** + * Get a fresh instance of the batch represented by this ID. + * + * @return self + */ + public function fresh() + { + return $this->repository->find($this->id); + } + + /** + * Add additional jobs to the batch. + * + * @param \Illuminate\Support\Enumerable|array $jobs + * @return self + */ + public function add($jobs) + { + $count = 0; + + $jobs = Collection::wrap($jobs)->map(function ($job) use (&$count) { + $job = $job instanceof Closure ? CallQueuedClosure::create($job) : $job; + + if (is_array($job)) { + $count += count($job); + + return with($this->prepareBatchedChain($job), function ($chain) { + return $chain->first() + ->allOnQueue($this->options['queue'] ?? null) + ->allOnConnection($this->options['connection'] ?? null) + ->chain($chain->slice(1)->values()->all()); + }); + } else { + $job->withBatchId($this->id); + + $count++; + } + + return $job; + }); + + $this->repository->transaction(function () use ($jobs, $count) { + $this->repository->incrementTotalJobs($this->id, $count); + + $this->queue->connection($this->options['connection'] ?? null)->bulk( + $jobs->all(), + $data = '', + $this->options['queue'] ?? null + ); + }); + + return $this->fresh(); + } + + /** + * Prepare a chain that exists within the jobs being added. + * + * @param array $chain + * @return \Illuminate\Support\Collection + */ + protected function prepareBatchedChain(array $chain) + { + return collect($chain)->map(function ($job) { + $job = $job instanceof Closure ? CallQueuedClosure::create($job) : $job; + + return $job->withBatchId($this->id); + }); + } + + /** + * Get the total number of jobs that have been processed by the batch thus far. + * + * @return int + */ + public function processedJobs() + { + return $this->totalJobs - $this->pendingJobs; + } + + /** + * Get the percentage of jobs that have been processed (between 0-100). + * + * @return int + */ + public function progress() + { + return $this->totalJobs > 0 ? round(($this->processedJobs() / $this->totalJobs) * 100) : 0; + } + + /** + * Record that a job within the batch finished successfully, executing any callbacks if necessary. + * + * @param string $jobId + * @return void + */ + public function recordSuccessfulJob(string $jobId) + { + $counts = $this->decrementPendingJobs($jobId); + + if ($counts->pendingJobs === 0) { + $this->repository->markAsFinished($this->id); + } + + if ($counts->pendingJobs === 0 && $this->hasThenCallbacks()) { + $batch = $this->fresh(); + + collect($this->options['then'])->each(function ($handler) use ($batch) { + $this->invokeHandlerCallback($handler, $batch); + }); + } + + if ($counts->allJobsHaveRanExactlyOnce() && $this->hasFinallyCallbacks()) { + $batch = $this->fresh(); + + collect($this->options['finally'])->each(function ($handler) use ($batch) { + $this->invokeHandlerCallback($handler, $batch); + }); + } + } + + /** + * Decrement the pending jobs for the batch. + * + * @param string $jobId + * @return \Illuminate\Bus\UpdatedBatchJobCounts + */ + public function decrementPendingJobs(string $jobId) + { + return $this->repository->decrementPendingJobs($this->id, $jobId); + } + + /** + * Determine if the batch has finished executing. + * + * @return bool + */ + public function finished() + { + return ! is_null($this->finishedAt); + } + + /** + * Determine if the batch has "success" callbacks. + * + * @return bool + */ + public function hasThenCallbacks() + { + return isset($this->options['then']) && ! empty($this->options['then']); + } + + /** + * Determine if the batch allows jobs to fail without cancelling the batch. + * + * @return bool + */ + public function allowsFailures() + { + return Arr::get($this->options, 'allowFailures', false) === true; + } + + /** + * Determine if the batch has job failures. + * + * @return bool + */ + public function hasFailures() + { + return $this->failedJobs > 0; + } + + /** + * Record that a job within the batch failed to finish successfully, executing any callbacks if necessary. + * + * @param string $jobId + * @param \Throwable $e + * @return void + */ + public function recordFailedJob(string $jobId, $e) + { + $counts = $this->incrementFailedJobs($jobId); + + if ($counts->failedJobs === 1 && ! $this->allowsFailures()) { + $this->cancel(); + } + + if ($counts->failedJobs === 1 && $this->hasCatchCallbacks()) { + $batch = $this->fresh(); + + collect($this->options['catch'])->each(function ($handler) use ($batch, $e) { + $this->invokeHandlerCallback($handler, $batch, $e); + }); + } + + if ($counts->allJobsHaveRanExactlyOnce() && $this->hasFinallyCallbacks()) { + $batch = $this->fresh(); + + collect($this->options['finally'])->each(function ($handler) use ($batch, $e) { + $this->invokeHandlerCallback($handler, $batch, $e); + }); + } + } + + /** + * Increment the failed jobs for the batch. + * + * @param string $jobId + * @return \Illuminate\Bus\UpdatedBatchJobCounts + */ + public function incrementFailedJobs(string $jobId) + { + return $this->repository->incrementFailedJobs($this->id, $jobId); + } + + /** + * Determine if the batch has "catch" callbacks. + * + * @return bool + */ + public function hasCatchCallbacks() + { + return isset($this->options['catch']) && ! empty($this->options['catch']); + } + + /** + * Determine if the batch has "finally" callbacks. + * + * @return bool + */ + public function hasFinallyCallbacks() + { + return isset($this->options['finally']) && ! empty($this->options['finally']); + } + + /** + * Cancel the batch. + * + * @return void + */ + public function cancel() + { + $this->repository->cancel($this->id); + } + + /** + * Determine if the batch has been cancelled. + * + * @return bool + */ + public function canceled() + { + return $this->cancelled(); + } + + /** + * Determine if the batch has been cancelled. + * + * @return bool + */ + public function cancelled() + { + return ! is_null($this->cancelledAt); + } + + /** + * Delete the batch from storage. + * + * @return void + */ + public function delete() + { + $this->repository->delete($this->id); + } + + /** + * Invoke a batch callback handler. + * + * @param callable $handler + * @param \Illuminate\Bus\Batch $batch + * @param \Throwable|null $e + * @return void + */ + protected function invokeHandlerCallback($handler, Batch $batch, Throwable $e = null) + { + try { + return $handler($batch, $e); + } catch (Throwable $e) { + if (function_exists('report')) { + report($e); + } + } + } + + /** + * Convert the batch to an array. + * + * @return array + */ + public function toArray() + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'totalJobs' => $this->totalJobs, + 'pendingJobs' => $this->pendingJobs, + 'processedJobs' => $this->processedJobs(), + 'progress' => $this->progress(), + 'failedJobs' => $this->failedJobs, + 'options' => $this->options, + 'createdAt' => $this->createdAt, + 'cancelledAt' => $this->cancelledAt, + 'finishedAt' => $this->finishedAt, + ]; + } + + /** + * Get the JSON serializable representation of the object. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Dynamically access the batch's "options" via properties. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->options[$key] ?? null; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BatchFactory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BatchFactory.php new file mode 100644 index 0000000..2c3a4e9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BatchFactory.php @@ -0,0 +1,58 @@ +queue = $queue; + } + + /** + * Create a new batch instance. + * + * @param \Illuminate\Bus\BatchRepository $repository + * @param string $id + * @param string $name + * @param int $totalJobs + * @param int $pendingJobs + * @param int $failedJobs + * @param array $failedJobIds + * @param array $options + * @param \Carbon\CarbonImmutable $createdAt + * @param \Carbon\CarbonImmutable|null $cancelledAt + * @param \Carbon\CarbonImmutable|null $finishedAt + * @return \Illuminate\Bus\Batch + */ + public function make(BatchRepository $repository, + string $id, + string $name, + int $totalJobs, + int $pendingJobs, + int $failedJobs, + array $failedJobIds, + array $options, + CarbonImmutable $createdAt, + ?CarbonImmutable $cancelledAt, + ?CarbonImmutable $finishedAt) + { + return new Batch($this->queue, $repository, $id, $name, $totalJobs, $pendingJobs, $failedJobs, $failedJobIds, $options, $createdAt, $cancelledAt, $finishedAt); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BatchRepository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BatchRepository.php new file mode 100644 index 0000000..098ccef --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BatchRepository.php @@ -0,0 +1,92 @@ +batchId) { + return Container::getInstance()->make(BatchRepository::class)->find($this->batchId); + } + } + + /** + * Determine if the batch is still active and processing. + * + * @return bool + */ + public function batching() + { + $batch = $this->batch(); + + return $batch && ! $batch->cancelled(); + } + + /** + * Set the batch ID on the job. + * + * @param string $batchId + * @return $this + */ + public function withBatchId(string $batchId) + { + $this->batchId = $batchId; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BusServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BusServiceProvider.php new file mode 100644 index 0000000..ff3eef8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/BusServiceProvider.php @@ -0,0 +1,69 @@ +app->singleton(Dispatcher::class, function ($app) { + return new Dispatcher($app, function ($connection = null) use ($app) { + return $app[QueueFactoryContract::class]->connection($connection); + }); + }); + + $this->registerBatchServices(); + + $this->app->alias( + Dispatcher::class, DispatcherContract::class + ); + + $this->app->alias( + Dispatcher::class, QueueingDispatcherContract::class + ); + } + + /** + * Register the batch handling services. + * + * @return void + */ + protected function registerBatchServices() + { + $this->app->singleton(BatchRepository::class, DatabaseBatchRepository::class); + + $this->app->singleton(DatabaseBatchRepository::class, function ($app) { + return new DatabaseBatchRepository( + $app->make(BatchFactory::class), + $app->make('db')->connection($app->config->get('queue.batching.database')), + $app->config->get('queue.batching.table', 'job_batches') + ); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + Dispatcher::class, + DispatcherContract::class, + QueueingDispatcherContract::class, + BatchRepository::class, + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/DatabaseBatchRepository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/DatabaseBatchRepository.php new file mode 100644 index 0000000..ee544b0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/DatabaseBatchRepository.php @@ -0,0 +1,347 @@ +factory = $factory; + $this->connection = $connection; + $this->table = $table; + } + + /** + * Retrieve a list of batches. + * + * @param int $limit + * @param mixed $before + * @return \Illuminate\Bus\Batch[] + */ + public function get($limit = 50, $before = null) + { + return $this->connection->table($this->table) + ->orderByDesc('id') + ->take($limit) + ->when($before, function ($q) use ($before) { + return $q->where('id', '<', $before); + }) + ->get() + ->map(function ($batch) { + return $this->toBatch($batch); + }) + ->all(); + } + + /** + * Retrieve information about an existing batch. + * + * @param string $batchId + * @return \Illuminate\Bus\Batch|null + */ + public function find(string $batchId) + { + $batch = $this->connection->table($this->table) + ->where('id', $batchId) + ->first(); + + if ($batch) { + return $this->toBatch($batch); + } + } + + /** + * Store a new pending batch. + * + * @param \Illuminate\Bus\PendingBatch $batch + * @return \Illuminate\Bus\Batch + */ + public function store(PendingBatch $batch) + { + $id = (string) Str::orderedUuid(); + + $this->connection->table($this->table)->insert([ + 'id' => $id, + 'name' => $batch->name, + 'total_jobs' => 0, + 'pending_jobs' => 0, + 'failed_jobs' => 0, + 'failed_job_ids' => '[]', + 'options' => $this->serialize($batch->options), + 'created_at' => time(), + 'cancelled_at' => null, + 'finished_at' => null, + ]); + + return $this->find($id); + } + + /** + * Increment the total number of jobs within the batch. + * + * @param string $batchId + * @param int $amount + * @return void + */ + public function incrementTotalJobs(string $batchId, int $amount) + { + $this->connection->table($this->table)->where('id', $batchId)->update([ + 'total_jobs' => new Expression('total_jobs + '.$amount), + 'pending_jobs' => new Expression('pending_jobs + '.$amount), + 'finished_at' => null, + ]); + } + + /** + * Decrement the total number of pending jobs for the batch. + * + * @param string $batchId + * @param string $jobId + * @return \Illuminate\Bus\UpdatedBatchJobCounts + */ + public function decrementPendingJobs(string $batchId, string $jobId) + { + $values = $this->updateAtomicValues($batchId, function ($batch) use ($jobId) { + return [ + 'pending_jobs' => $batch->pending_jobs - 1, + 'failed_jobs' => $batch->failed_jobs, + 'failed_job_ids' => json_encode(array_values(array_diff(json_decode($batch->failed_job_ids, true), [$jobId]))), + ]; + }); + + return new UpdatedBatchJobCounts( + $values['pending_jobs'], + $values['failed_jobs'] + ); + } + + /** + * Increment the total number of failed jobs for the batch. + * + * @param string $batchId + * @param string $jobId + * @return \Illuminate\Bus\UpdatedBatchJobCounts + */ + public function incrementFailedJobs(string $batchId, string $jobId) + { + $values = $this->updateAtomicValues($batchId, function ($batch) use ($jobId) { + return [ + 'pending_jobs' => $batch->pending_jobs, + 'failed_jobs' => $batch->failed_jobs + 1, + 'failed_job_ids' => json_encode(array_values(array_unique(array_merge(json_decode($batch->failed_job_ids, true), [$jobId])))), + ]; + }); + + return new UpdatedBatchJobCounts( + $values['pending_jobs'], + $values['failed_jobs'] + ); + } + + /** + * Update an atomic value within the batch. + * + * @param string $batchId + * @param \Closure $callback + * @return int|null + */ + protected function updateAtomicValues(string $batchId, Closure $callback) + { + return $this->connection->transaction(function () use ($batchId, $callback) { + $batch = $this->connection->table($this->table)->where('id', $batchId) + ->lockForUpdate() + ->first(); + + return is_null($batch) ? [] : tap($callback($batch), function ($values) use ($batchId) { + $this->connection->table($this->table)->where('id', $batchId)->update($values); + }); + }); + } + + /** + * Mark the batch that has the given ID as finished. + * + * @param string $batchId + * @return void + */ + public function markAsFinished(string $batchId) + { + $this->connection->table($this->table)->where('id', $batchId)->update([ + 'finished_at' => time(), + ]); + } + + /** + * Cancel the batch that has the given ID. + * + * @param string $batchId + * @return void + */ + public function cancel(string $batchId) + { + $this->connection->table($this->table)->where('id', $batchId)->update([ + 'cancelled_at' => time(), + 'finished_at' => time(), + ]); + } + + /** + * Delete the batch that has the given ID. + * + * @param string $batchId + * @return void + */ + public function delete(string $batchId) + { + $this->connection->table($this->table)->where('id', $batchId)->delete(); + } + + /** + * Prune all of the entries older than the given date. + * + * @param \DateTimeInterface $before + * @return int + */ + public function prune(DateTimeInterface $before) + { + $query = $this->connection->table($this->table) + ->whereNotNull('finished_at') + ->where('finished_at', '<', $before->getTimestamp()); + + $totalDeleted = 0; + + do { + $deleted = $query->take(1000)->delete(); + + $totalDeleted += $deleted; + } while ($deleted !== 0); + + return $totalDeleted; + } + + /** + * Prune all of the unfinished entries older than the given date. + * + * @param \DateTimeInterface $before + * @return int + */ + public function pruneUnfinished(DateTimeInterface $before) + { + $query = $this->connection->table($this->table) + ->whereNull('finished_at') + ->where('created_at', '<', $before->getTimestamp()); + + $totalDeleted = 0; + + do { + $deleted = $query->take(1000)->delete(); + + $totalDeleted += $deleted; + } while ($deleted !== 0); + + return $totalDeleted; + } + + /** + * Execute the given Closure within a storage specific transaction. + * + * @param \Closure $callback + * @return mixed + */ + public function transaction(Closure $callback) + { + return $this->connection->transaction(function () use ($callback) { + return $callback(); + }); + } + + /** + * Serialize the given value. + * + * @param mixed $value + * @return string + */ + protected function serialize($value) + { + $serialized = serialize($value); + + return $this->connection instanceof PostgresConnection + ? base64_encode($serialized) + : $serialized; + } + + /** + * Unserialize the given value. + * + * @param string $serialized + * @return mixed + */ + protected function unserialize($serialized) + { + if ($this->connection instanceof PostgresConnection && + ! Str::contains($serialized, [':', ';'])) { + $serialized = base64_decode($serialized); + } + + return unserialize($serialized); + } + + /** + * Convert the given raw batch to a Batch object. + * + * @param object $batch + * @return \Illuminate\Bus\Batch + */ + protected function toBatch($batch) + { + return $this->factory->make( + $this, + $batch->id, + $batch->name, + (int) $batch->total_jobs, + (int) $batch->pending_jobs, + (int) $batch->failed_jobs, + json_decode($batch->failed_job_ids, true), + $this->unserialize($batch->options), + CarbonImmutable::createFromTimestamp($batch->created_at), + $batch->cancelled_at ? CarbonImmutable::createFromTimestamp($batch->cancelled_at) : $batch->cancelled_at, + $batch->finished_at ? CarbonImmutable::createFromTimestamp($batch->finished_at) : $batch->finished_at + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php new file mode 100644 index 0000000..4dc390e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php @@ -0,0 +1,295 @@ +container = $container; + $this->queueResolver = $queueResolver; + $this->pipeline = new Pipeline($container); + } + + /** + * Dispatch a command to its appropriate handler. + * + * @param mixed $command + * @return mixed + */ + public function dispatch($command) + { + return $this->queueResolver && $this->commandShouldBeQueued($command) + ? $this->dispatchToQueue($command) + : $this->dispatchNow($command); + } + + /** + * Dispatch a command to its appropriate handler in the current process. + * + * Queueable jobs will be dispatched to the "sync" queue. + * + * @param mixed $command + * @param mixed $handler + * @return mixed + */ + public function dispatchSync($command, $handler = null) + { + if ($this->queueResolver && + $this->commandShouldBeQueued($command) && + method_exists($command, 'onConnection')) { + return $this->dispatchToQueue($command->onConnection('sync')); + } + + return $this->dispatchNow($command, $handler); + } + + /** + * Dispatch a command to its appropriate handler in the current process without using the synchronous queue. + * + * @param mixed $command + * @param mixed $handler + * @return mixed + */ + public function dispatchNow($command, $handler = null) + { + $uses = class_uses_recursive($command); + + if (in_array(InteractsWithQueue::class, $uses) && + in_array(Queueable::class, $uses) && + ! $command->job) { + $command->setJob(new SyncJob($this->container, json_encode([]), 'sync', 'sync')); + } + + if ($handler || $handler = $this->getCommandHandler($command)) { + $callback = function ($command) use ($handler) { + $method = method_exists($handler, 'handle') ? 'handle' : '__invoke'; + + return $handler->{$method}($command); + }; + } else { + $callback = function ($command) { + $method = method_exists($command, 'handle') ? 'handle' : '__invoke'; + + return $this->container->call([$command, $method]); + }; + } + + return $this->pipeline->send($command)->through($this->pipes)->then($callback); + } + + /** + * Attempt to find the batch with the given ID. + * + * @param string $batchId + * @return \Illuminate\Bus\Batch|null + */ + public function findBatch(string $batchId) + { + return $this->container->make(BatchRepository::class)->find($batchId); + } + + /** + * Create a new batch of queueable jobs. + * + * @param \Illuminate\Support\Collection|array|mixed $jobs + * @return \Illuminate\Bus\PendingBatch + */ + public function batch($jobs) + { + return new PendingBatch($this->container, Collection::wrap($jobs)); + } + + /** + * Create a new chain of queueable jobs. + * + * @param \Illuminate\Support\Collection|array $jobs + * @return \Illuminate\Foundation\Bus\PendingChain + */ + public function chain($jobs) + { + $jobs = Collection::wrap($jobs); + + return new PendingChain($jobs->shift(), $jobs->toArray()); + } + + /** + * Determine if the given command has a handler. + * + * @param mixed $command + * @return bool + */ + public function hasCommandHandler($command) + { + return array_key_exists(get_class($command), $this->handlers); + } + + /** + * Retrieve the handler for a command. + * + * @param mixed $command + * @return bool|mixed + */ + public function getCommandHandler($command) + { + if ($this->hasCommandHandler($command)) { + return $this->container->make($this->handlers[get_class($command)]); + } + + return false; + } + + /** + * Determine if the given command should be queued. + * + * @param mixed $command + * @return bool + */ + protected function commandShouldBeQueued($command) + { + return $command instanceof ShouldQueue; + } + + /** + * Dispatch a command to its appropriate handler behind a queue. + * + * @param mixed $command + * @return mixed + * + * @throws \RuntimeException + */ + public function dispatchToQueue($command) + { + $connection = $command->connection ?? null; + + $queue = call_user_func($this->queueResolver, $connection); + + if (! $queue instanceof Queue) { + throw new RuntimeException('Queue resolver did not return a Queue implementation.'); + } + + if (method_exists($command, 'queue')) { + return $command->queue($queue, $command); + } + + return $this->pushCommandToQueue($queue, $command); + } + + /** + * Push the command onto the given queue instance. + * + * @param \Illuminate\Contracts\Queue\Queue $queue + * @param mixed $command + * @return mixed + */ + protected function pushCommandToQueue($queue, $command) + { + if (isset($command->queue, $command->delay)) { + return $queue->laterOn($command->queue, $command->delay, $command); + } + + if (isset($command->queue)) { + return $queue->pushOn($command->queue, $command); + } + + if (isset($command->delay)) { + return $queue->later($command->delay, $command); + } + + return $queue->push($command); + } + + /** + * Dispatch a command to its appropriate handler after the current process. + * + * @param mixed $command + * @param mixed $handler + * @return void + */ + public function dispatchAfterResponse($command, $handler = null) + { + $this->container->terminating(function () use ($command, $handler) { + $this->dispatchNow($command, $handler); + }); + } + + /** + * Set the pipes through which commands should be piped before dispatching. + * + * @param array $pipes + * @return $this + */ + public function pipeThrough(array $pipes) + { + $this->pipes = $pipes; + + return $this; + } + + /** + * Map a command to a handler. + * + * @param array $map + * @return $this + */ + public function map(array $map) + { + $this->handlers = array_merge($this->handlers, $map); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Events/BatchDispatched.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Events/BatchDispatched.php new file mode 100644 index 0000000..b9a161a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/Events/BatchDispatched.php @@ -0,0 +1,26 @@ +batch = $batch; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/PendingBatch.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/PendingBatch.php new file mode 100644 index 0000000..77cb7fa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/PendingBatch.php @@ -0,0 +1,272 @@ +container = $container; + $this->jobs = $jobs; + } + + /** + * Add jobs to the batch. + * + * @param iterable $jobs + * @return $this + */ + public function add($jobs) + { + foreach ($jobs as $job) { + $this->jobs->push($job); + } + + return $this; + } + + /** + * Add a callback to be executed after all jobs in the batch have executed successfully. + * + * @param callable $callback + * @return $this + */ + public function then($callback) + { + $this->options['then'][] = $callback instanceof Closure + ? SerializableClosureFactory::make($callback) + : $callback; + + return $this; + } + + /** + * Get the "then" callbacks that have been registered with the pending batch. + * + * @return array + */ + public function thenCallbacks() + { + return $this->options['then'] ?? []; + } + + /** + * Add a callback to be executed after the first failing job in the batch. + * + * @param callable $callback + * @return $this + */ + public function catch($callback) + { + $this->options['catch'][] = $callback instanceof Closure + ? SerializableClosureFactory::make($callback) + : $callback; + + return $this; + } + + /** + * Get the "catch" callbacks that have been registered with the pending batch. + * + * @return array + */ + public function catchCallbacks() + { + return $this->options['catch'] ?? []; + } + + /** + * Add a callback to be executed after the batch has finished executing. + * + * @param callable $callback + * @return $this + */ + public function finally($callback) + { + $this->options['finally'][] = $callback instanceof Closure + ? SerializableClosureFactory::make($callback) + : $callback; + + return $this; + } + + /** + * Get the "finally" callbacks that have been registered with the pending batch. + * + * @return array + */ + public function finallyCallbacks() + { + return $this->options['finally'] ?? []; + } + + /** + * Indicate that the batch should not be cancelled when a job within the batch fails. + * + * @param bool $allowFailures + * @return $this + */ + public function allowFailures($allowFailures = true) + { + $this->options['allowFailures'] = $allowFailures; + + return $this; + } + + /** + * Determine if the pending batch allows jobs to fail without cancelling the batch. + * + * @return bool + */ + public function allowsFailures() + { + return Arr::get($this->options, 'allowFailures', false) === true; + } + + /** + * Set the name for the batch. + * + * @param string $name + * @return $this + */ + public function name(string $name) + { + $this->name = $name; + + return $this; + } + + /** + * Specify the queue connection that the batched jobs should run on. + * + * @param string $connection + * @return $this + */ + public function onConnection(string $connection) + { + $this->options['connection'] = $connection; + + return $this; + } + + /** + * Get the connection used by the pending batch. + * + * @return string|null + */ + public function connection() + { + return $this->options['connection'] ?? null; + } + + /** + * Specify the queue that the batched jobs should run on. + * + * @param string $queue + * @return $this + */ + public function onQueue(string $queue) + { + $this->options['queue'] = $queue; + + return $this; + } + + /** + * Get the queue used by the pending batch. + * + * @return string|null + */ + public function queue() + { + return $this->options['queue'] ?? null; + } + + /** + * Add additional data into the batch's options array. + * + * @param string $key + * @param mixed $value + * @return $this + */ + public function withOption(string $key, $value) + { + $this->options[$key] = $value; + + return $this; + } + + /** + * Dispatch the batch. + * + * @return \Illuminate\Bus\Batch + * + * @throws \Throwable + */ + public function dispatch() + { + $repository = $this->container->make(BatchRepository::class); + + try { + $batch = $repository->store($this); + + $batch = $batch->add($this->jobs); + } catch (Throwable $e) { + if (isset($batch)) { + $repository->delete($batch->id); + } + + throw $e; + } + + $this->container->make(EventDispatcher::class)->dispatch( + new BatchDispatched($batch) + ); + + return $batch; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/PrunableBatchRepository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/PrunableBatchRepository.php new file mode 100644 index 0000000..3f97255 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/PrunableBatchRepository.php @@ -0,0 +1,16 @@ +connection = $connection; + + return $this; + } + + /** + * Set the desired queue for the job. + * + * @param string|null $queue + * @return $this + */ + public function onQueue($queue) + { + $this->queue = $queue; + + return $this; + } + + /** + * Set the desired connection for the chain. + * + * @param string|null $connection + * @return $this + */ + public function allOnConnection($connection) + { + $this->chainConnection = $connection; + $this->connection = $connection; + + return $this; + } + + /** + * Set the desired queue for the chain. + * + * @param string|null $queue + * @return $this + */ + public function allOnQueue($queue) + { + $this->chainQueue = $queue; + $this->queue = $queue; + + return $this; + } + + /** + * Set the desired delay for the job. + * + * @param \DateTimeInterface|\DateInterval|int|null $delay + * @return $this + */ + public function delay($delay) + { + $this->delay = $delay; + + return $this; + } + + /** + * Indicate that the job should be dispatched after all database transactions have committed. + * + * @return $this + */ + public function afterCommit() + { + $this->afterCommit = true; + + return $this; + } + + /** + * Indicate that the job should not wait until database transactions have been committed before dispatching. + * + * @return $this + */ + public function beforeCommit() + { + $this->afterCommit = false; + + return $this; + } + + /** + * Specify the middleware the job should be dispatched through. + * + * @param array|object $middleware + * @return $this + */ + public function through($middleware) + { + $this->middleware = Arr::wrap($middleware); + + return $this; + } + + /** + * Set the jobs that should run if this job is successful. + * + * @param array $chain + * @return $this + */ + public function chain($chain) + { + $this->chained = collect($chain)->map(function ($job) { + return $this->serializeJob($job); + })->all(); + + return $this; + } + + /** + * Serialize a job for queuing. + * + * @param mixed $job + * @return string + * + * @throws \RuntimeException + */ + protected function serializeJob($job) + { + if ($job instanceof Closure) { + if (! class_exists(CallQueuedClosure::class)) { + throw new RuntimeException( + 'To enable support for closure jobs, please install the illuminate/queue package.' + ); + } + + $job = CallQueuedClosure::create($job); + } + + return serialize($job); + } + + /** + * Dispatch the next job on the chain. + * + * @return void + */ + public function dispatchNextJobInChain() + { + if (! empty($this->chained)) { + dispatch(tap(unserialize(array_shift($this->chained)), function ($next) { + $next->chained = $this->chained; + + $next->onConnection($next->connection ?: $this->chainConnection); + $next->onQueue($next->queue ?: $this->chainQueue); + + $next->chainConnection = $this->chainConnection; + $next->chainQueue = $this->chainQueue; + $next->chainCatchCallbacks = $this->chainCatchCallbacks; + })); + } + } + + /** + * Invoke all of the chain's failed job callbacks. + * + * @param \Throwable $e + * @return void + */ + public function invokeChainCatchCallbacks($e) + { + collect($this->chainCatchCallbacks)->each(function ($callback) use ($e) { + $callback($e); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/UniqueLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/UniqueLock.php new file mode 100644 index 0000000..a937b18 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/UniqueLock.php @@ -0,0 +1,48 @@ +cache = $cache; + } + + /** + * Attempt to acquire a lock for the given job. + * + * @param mixed $job + * @return bool + */ + public function acquire($job) + { + $uniqueId = method_exists($job, 'uniqueId') + ? $job->uniqueId() + : ($job->uniqueId ?? ''); + + $cache = method_exists($job, 'uniqueVia') + ? $job->uniqueVia() + : $this->cache; + + return (bool) $cache->lock( + $key = 'laravel_unique_job:'.get_class($job).$uniqueId, + $job->uniqueFor ?? 0 + )->get(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/UpdatedBatchJobCounts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/UpdatedBatchJobCounts.php new file mode 100644 index 0000000..83d33a4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/UpdatedBatchJobCounts.php @@ -0,0 +1,43 @@ +pendingJobs = $pendingJobs; + $this->failedJobs = $failedJobs; + } + + /** + * Determine if all jobs have run exactly once. + * + * @return bool + */ + public function allJobsHaveRanExactlyOnce() + { + return ($this->pendingJobs - $this->failedJobs) === 0; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/composer.json new file mode 100644 index 0000000..12713a6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Bus/composer.json @@ -0,0 +1,40 @@ +{ + "name": "illuminate/bus", + "description": "The Illuminate Bus package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/pipeline": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Bus\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "illuminate/queue": "Required to use closures when chaining jobs (^7.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ApcStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ApcStore.php new file mode 100755 index 0000000..90132c1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ApcStore.php @@ -0,0 +1,130 @@ +apc = $apc; + $this->prefix = $prefix; + } + + /** + * Retrieve an item from the cache by key. + * + * @param string|array $key + * @return mixed + */ + public function get($key) + { + $value = $this->apc->get($this->prefix.$key); + + if ($value !== false) { + return $value; + } + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + return $this->apc->put($this->prefix.$key, $value, $seconds); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + return $this->apc->increment($this->prefix.$key, $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + return $this->apc->decrement($this->prefix.$key, $value); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return $this->put($key, $value, 0); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + return $this->apc->delete($this->prefix.$key); + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + return $this->apc->flush(); + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ApcWrapper.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ApcWrapper.php new file mode 100755 index 0000000..6c129c6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ApcWrapper.php @@ -0,0 +1,92 @@ +apcu = function_exists('apcu_fetch'); + } + + /** + * Get an item from the cache. + * + * @param string $key + * @return mixed + */ + public function get($key) + { + return $this->apcu ? apcu_fetch($key) : apc_fetch($key); + } + + /** + * Store an item in the cache. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return array|bool + */ + public function put($key, $value, $seconds) + { + return $this->apcu ? apcu_store($key, $value, $seconds) : apc_store($key, $value, $seconds); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value) + { + return $this->apcu ? apcu_inc($key, $value) : apc_inc($key, $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value) + { + return $this->apcu ? apcu_dec($key, $value) : apc_dec($key, $value); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function delete($key) + { + return $this->apcu ? apcu_delete($key) : apc_delete($key); + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + return $this->apcu ? apcu_clear_cache() : apc_clear_cache('user'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ArrayLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ArrayLock.php new file mode 100644 index 0000000..4c20783 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ArrayLock.php @@ -0,0 +1,102 @@ +store = $store; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + $expiration = $this->store->locks[$this->name]['expiresAt'] ?? Carbon::now()->addSecond(); + + if ($this->exists() && $expiration->isFuture()) { + return false; + } + + $this->store->locks[$this->name] = [ + 'owner' => $this->owner, + 'expiresAt' => $this->seconds === 0 ? null : Carbon::now()->addSeconds($this->seconds), + ]; + + return true; + } + + /** + * Determine if the current lock exists. + * + * @return bool + */ + protected function exists() + { + return isset($this->store->locks[$this->name]); + } + + /** + * Release the lock. + * + * @return bool + */ + public function release() + { + if (! $this->exists()) { + return false; + } + + if (! $this->isOwnedByCurrentProcess()) { + return false; + } + + $this->forceRelease(); + + return true; + } + + /** + * Returns the owner value written into the driver for this lock. + * + * @return string + */ + protected function getCurrentOwner() + { + return $this->store->locks[$this->name]['owner']; + } + + /** + * Releases this lock in disregard of ownership. + * + * @return void + */ + public function forceRelease() + { + unset($this->store->locks[$this->name]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ArrayStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ArrayStore.php new file mode 100644 index 0000000..22b42ba --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/ArrayStore.php @@ -0,0 +1,218 @@ +serializesValues = $serializesValues; + } + + /** + * Retrieve an item from the cache by key. + * + * @param string|array $key + * @return mixed + */ + public function get($key) + { + if (! isset($this->storage[$key])) { + return; + } + + $item = $this->storage[$key]; + + $expiresAt = $item['expiresAt'] ?? 0; + + if ($expiresAt !== 0 && $this->currentTime() > $expiresAt) { + $this->forget($key); + + return; + } + + return $this->serializesValues ? unserialize($item['value']) : $item['value']; + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + $this->storage[$key] = [ + 'value' => $this->serializesValues ? serialize($value) : $value, + 'expiresAt' => $this->calculateExpiration($seconds), + ]; + + return true; + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int + */ + public function increment($key, $value = 1) + { + if (! is_null($existing = $this->get($key))) { + return tap(((int) $existing) + $value, function ($incremented) use ($key) { + $value = $this->serializesValues ? serialize($incremented) : $incremented; + + $this->storage[$key]['value'] = $value; + }); + } + + $this->forever($key, $value); + + return $value; + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int + */ + public function decrement($key, $value = 1) + { + return $this->increment($key, $value * -1); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return $this->put($key, $value, 0); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + if (array_key_exists($key, $this->storage)) { + unset($this->storage[$key]); + + return true; + } + + return false; + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + $this->storage = []; + + return true; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return ''; + } + + /** + * Get the expiration time of the key. + * + * @param int $seconds + * @return int + */ + protected function calculateExpiration($seconds) + { + return $this->toTimestamp($seconds); + } + + /** + * Get the UNIX timestamp for the given number of seconds. + * + * @param int $seconds + * @return int + */ + protected function toTimestamp($seconds) + { + return $seconds > 0 ? $this->availableAt($seconds) : 0; + } + + /** + * Get a lock instance. + * + * @param string $name + * @param int $seconds + * @param string|null $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function lock($name, $seconds = 0, $owner = null) + { + return new ArrayLock($this, $name, $seconds, $owner); + } + + /** + * Restore a lock instance using the owner identifier. + * + * @param string $name + * @param string $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function restoreLock($name, $owner) + { + return $this->lock($name, 0, $owner); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheLock.php new file mode 100644 index 0000000..310d9fb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheLock.php @@ -0,0 +1,85 @@ +store = $store; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + if (method_exists($this->store, 'add') && $this->seconds > 0) { + return $this->store->add( + $this->name, $this->owner, $this->seconds + ); + } + + if (! is_null($this->store->get($this->name))) { + return false; + } + + return ($this->seconds > 0) + ? $this->store->put($this->name, $this->owner, $this->seconds) + : $this->store->forever($this->name, $this->owner, $this->seconds); + } + + /** + * Release the lock. + * + * @return bool + */ + public function release() + { + if ($this->isOwnedByCurrentProcess()) { + return $this->store->forget($this->name); + } + + return false; + } + + /** + * Releases this lock regardless of ownership. + * + * @return void + */ + public function forceRelease() + { + $this->store->forget($this->name); + } + + /** + * Returns the owner value written into the driver for this lock. + * + * @return mixed + */ + protected function getCurrentOwner() + { + return $this->store->get($this->name); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php new file mode 100755 index 0000000..145b3e6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php @@ -0,0 +1,420 @@ +app = $app; + } + + /** + * Get a cache store instance by name, wrapped in a repository. + * + * @param string|null $name + * @return \Illuminate\Contracts\Cache\Repository + */ + public function store($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + return $this->stores[$name] = $this->get($name); + } + + /** + * Get a cache driver instance. + * + * @param string|null $driver + * @return \Illuminate\Contracts\Cache\Repository + */ + public function driver($driver = null) + { + return $this->store($driver); + } + + /** + * Attempt to get the store from the local cache. + * + * @param string $name + * @return \Illuminate\Contracts\Cache\Repository + */ + protected function get($name) + { + return $this->stores[$name] ?? $this->resolve($name); + } + + /** + * Resolve the given store. + * + * @param string $name + * @return \Illuminate\Contracts\Cache\Repository + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Cache store [{$name}] is not defined."); + } + + if (isset($this->customCreators[$config['driver']])) { + return $this->callCustomCreator($config); + } else { + $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; + + if (method_exists($this, $driverMethod)) { + return $this->{$driverMethod}($config); + } else { + throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported."); + } + } + } + + /** + * Call a custom driver creator. + * + * @param array $config + * @return mixed + */ + protected function callCustomCreator(array $config) + { + return $this->customCreators[$config['driver']]($this->app, $config); + } + + /** + * Create an instance of the APC cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createApcDriver(array $config) + { + $prefix = $this->getPrefix($config); + + return $this->repository(new ApcStore(new ApcWrapper, $prefix)); + } + + /** + * Create an instance of the array cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createArrayDriver(array $config) + { + return $this->repository(new ArrayStore($config['serialize'] ?? false)); + } + + /** + * Create an instance of the file cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createFileDriver(array $config) + { + return $this->repository(new FileStore($this->app['files'], $config['path'], $config['permission'] ?? null)); + } + + /** + * Create an instance of the Memcached cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createMemcachedDriver(array $config) + { + $prefix = $this->getPrefix($config); + + $memcached = $this->app['memcached.connector']->connect( + $config['servers'], + $config['persistent_id'] ?? null, + $config['options'] ?? [], + array_filter($config['sasl'] ?? []) + ); + + return $this->repository(new MemcachedStore($memcached, $prefix)); + } + + /** + * Create an instance of the Null cache driver. + * + * @return \Illuminate\Cache\Repository + */ + protected function createNullDriver() + { + return $this->repository(new NullStore); + } + + /** + * Create an instance of the Redis cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createRedisDriver(array $config) + { + $redis = $this->app['redis']; + + $connection = $config['connection'] ?? 'default'; + + $store = new RedisStore($redis, $this->getPrefix($config), $connection); + + return $this->repository( + $store->setLockConnection($config['lock_connection'] ?? $connection) + ); + } + + /** + * Create an instance of the database cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createDatabaseDriver(array $config) + { + $connection = $this->app['db']->connection($config['connection'] ?? null); + + $store = new DatabaseStore( + $connection, + $config['table'], + $this->getPrefix($config), + $config['lock_table'] ?? 'cache_locks', + $config['lock_lottery'] ?? [2, 100] + ); + + return $this->repository($store->setLockConnection( + $this->app['db']->connection($config['lock_connection'] ?? $config['connection'] ?? null) + )); + } + + /** + * Create an instance of the DynamoDB cache driver. + * + * @param array $config + * @return \Illuminate\Cache\Repository + */ + protected function createDynamodbDriver(array $config) + { + $client = $this->newDynamodbClient($config); + + return $this->repository( + new DynamoDbStore( + $client, + $config['table'], + $config['attributes']['key'] ?? 'key', + $config['attributes']['value'] ?? 'value', + $config['attributes']['expiration'] ?? 'expires_at', + $this->getPrefix($config) + ) + ); + } + + /** + * Create new DynamoDb Client instance. + * + * @return DynamoDbClient + */ + protected function newDynamodbClient(array $config) + { + $dynamoConfig = [ + 'region' => $config['region'], + 'version' => 'latest', + 'endpoint' => $config['endpoint'] ?? null, + ]; + + if (isset($config['key']) && isset($config['secret'])) { + $dynamoConfig['credentials'] = Arr::only( + $config, ['key', 'secret', 'token'] + ); + } + + return new DynamoDbClient($dynamoConfig); + } + + /** + * Create a new cache repository with the given implementation. + * + * @param \Illuminate\Contracts\Cache\Store $store + * @return \Illuminate\Cache\Repository + */ + public function repository(Store $store) + { + return tap(new Repository($store), function ($repository) { + $this->setEventDispatcher($repository); + }); + } + + /** + * Set the event dispatcher on the given repository instance. + * + * @param \Illuminate\Cache\Repository $repository + * @return void + */ + protected function setEventDispatcher(Repository $repository) + { + if (! $this->app->bound(DispatcherContract::class)) { + return; + } + + $repository->setEventDispatcher( + $this->app[DispatcherContract::class] + ); + } + + /** + * Re-set the event dispatcher on all resolved cache repositories. + * + * @return void + */ + public function refreshEventDispatcher() + { + array_map([$this, 'setEventDispatcher'], $this->stores); + } + + /** + * Get the cache prefix. + * + * @param array $config + * @return string + */ + protected function getPrefix(array $config) + { + return $config['prefix'] ?? $this->app['config']['cache.prefix']; + } + + /** + * Get the cache connection configuration. + * + * @param string $name + * @return array + */ + protected function getConfig($name) + { + if (! is_null($name) && $name !== 'null') { + return $this->app['config']["cache.stores.{$name}"]; + } + + return ['driver' => 'null']; + } + + /** + * Get the default cache driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->app['config']['cache.default']; + } + + /** + * Set the default cache driver name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->app['config']['cache.default'] = $name; + } + + /** + * Unset the given driver instances. + * + * @param array|string|null $name + * @return $this + */ + public function forgetDriver($name = null) + { + $name = $name ?? $this->getDefaultDriver(); + + foreach ((array) $name as $cacheName) { + if (isset($this->stores[$cacheName])) { + unset($this->stores[$cacheName]); + } + } + + return $this; + } + + /** + * Disconnect the given driver and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?? $this->getDefaultDriver(); + + unset($this->stores[$name]); + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback->bindTo($this, $this); + + return $this; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->store()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php new file mode 100755 index 0000000..662d556 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php @@ -0,0 +1,52 @@ +app->singleton('cache', function ($app) { + return new CacheManager($app); + }); + + $this->app->singleton('cache.store', function ($app) { + return $app['cache']->driver(); + }); + + $this->app->singleton('cache.psr6', function ($app) { + return new Psr16Adapter($app['cache.store']); + }); + + $this->app->singleton('memcached.connector', function () { + return new MemcachedConnector; + }); + + $this->app->singleton(RateLimiter::class, function ($app) { + return new RateLimiter($app->make('cache')->driver( + $app['config']->get('cache.limiter') + )); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + 'cache', 'cache.store', 'cache.psr6', 'memcached.connector', RateLimiter::class, + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/CacheTableCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/CacheTableCommand.php new file mode 100644 index 0000000..a8c78c9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/CacheTableCommand.php @@ -0,0 +1,81 @@ +files = $files; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $fullPath = $this->createBaseMigration(); + + $this->files->put($fullPath, $this->files->get(__DIR__.'/stubs/cache.stub')); + + $this->info('Migration created successfully!'); + + $this->composer->dumpAutoloads(); + } + + /** + * Create a base migration file for the table. + * + * @return string + */ + protected function createBaseMigration() + { + $name = 'create_cache_table'; + + $path = $this->laravel->databasePath().'/migrations'; + + return $this->laravel['migration.creator']->create($name, $path); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/ClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/ClearCommand.php new file mode 100755 index 0000000..8a37b8b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/ClearCommand.php @@ -0,0 +1,145 @@ +cache = $cache; + $this->files = $files; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->laravel['events']->dispatch( + 'cache:clearing', [$this->argument('store'), $this->tags()] + ); + + $successful = $this->cache()->flush(); + + $this->flushFacades(); + + if (! $successful) { + return $this->error('Failed to clear cache. Make sure you have the appropriate permissions.'); + } + + $this->laravel['events']->dispatch( + 'cache:cleared', [$this->argument('store'), $this->tags()] + ); + + $this->info('Application cache cleared!'); + } + + /** + * Flush the real-time facades stored in the cache directory. + * + * @return void + */ + public function flushFacades() + { + if (! $this->files->exists($storagePath = storage_path('framework/cache'))) { + return; + } + + foreach ($this->files->files($storagePath) as $file) { + if (preg_match('/facade-.*\.php$/', $file)) { + $this->files->delete($file); + } + } + } + + /** + * Get the cache instance for the command. + * + * @return \Illuminate\Cache\Repository + */ + protected function cache() + { + $cache = $this->cache->store($this->argument('store')); + + return empty($this->tags()) ? $cache : $cache->tags($this->tags()); + } + + /** + * Get the tags passed to the command. + * + * @return array + */ + protected function tags() + { + return array_filter(explode(',', $this->option('tags') ?? '')); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['store', InputArgument::OPTIONAL, 'The name of the store you would like to clear'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['tags', null, InputOption::VALUE_OPTIONAL, 'The cache tags you would like to clear', null], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/ForgetCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/ForgetCommand.php new file mode 100755 index 0000000..eb0c066 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/ForgetCommand.php @@ -0,0 +1,57 @@ +cache = $cache; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->cache->store($this->argument('store'))->forget( + $this->argument('key') + ); + + $this->info('The ['.$this->argument('key').'] key has been removed from the cache.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/stubs/cache.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/stubs/cache.stub new file mode 100644 index 0000000..88cd445 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Console/stubs/cache.stub @@ -0,0 +1,39 @@ +string('key')->primary(); + $table->mediumText('value'); + $table->integer('expiration'); + }); + + Schema::create('cache_locks', function (Blueprint $table) { + $table->string('key')->primary(); + $table->string('owner'); + $table->integer('expiration'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('cache'); + Schema::dropIfExists('cache_locks'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DatabaseLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DatabaseLock.php new file mode 100644 index 0000000..7fd05c1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DatabaseLock.php @@ -0,0 +1,149 @@ +connection = $connection; + $this->table = $table; + $this->lottery = $lottery; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + $acquired = false; + + try { + $this->connection->table($this->table)->insert([ + 'key' => $this->name, + 'owner' => $this->owner, + 'expiration' => $this->expiresAt(), + ]); + + $acquired = true; + } catch (QueryException $e) { + $updated = $this->connection->table($this->table) + ->where('key', $this->name) + ->where(function ($query) { + return $query->where('owner', $this->owner)->orWhere('expiration', '<=', time()); + })->update([ + 'owner' => $this->owner, + 'expiration' => $this->expiresAt(), + ]); + + $acquired = $updated >= 1; + } + + if (random_int(1, $this->lottery[1]) <= $this->lottery[0]) { + $this->connection->table($this->table)->where('expiration', '<=', time())->delete(); + } + + return $acquired; + } + + /** + * Get the UNIX timestamp indicating when the lock should expire. + * + * @return int + */ + protected function expiresAt() + { + return $this->seconds > 0 ? time() + $this->seconds : Carbon::now()->addDays(1)->getTimestamp(); + } + + /** + * Release the lock. + * + * @return bool + */ + public function release() + { + if ($this->isOwnedByCurrentProcess()) { + $this->connection->table($this->table) + ->where('key', $this->name) + ->where('owner', $this->owner) + ->delete(); + + return true; + } + + return false; + } + + /** + * Releases this lock in disregard of ownership. + * + * @return void + */ + public function forceRelease() + { + $this->connection->table($this->table) + ->where('key', $this->name) + ->delete(); + } + + /** + * Returns the owner value written into the driver for this lock. + * + * @return string + */ + protected function getCurrentOwner() + { + return optional($this->connection->table($this->table)->where('key', $this->name)->first())->owner; + } + + /** + * Get the name of the database connection being used to manage the lock. + * + * @return string + */ + public function getConnectionName() + { + return $this->connection->getName(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DatabaseStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DatabaseStore.php new file mode 100755 index 0000000..32d7a9f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DatabaseStore.php @@ -0,0 +1,395 @@ +table = $table; + $this->prefix = $prefix; + $this->connection = $connection; + $this->lockTable = $lockTable; + $this->lockLottery = $lockLottery; + } + + /** + * Retrieve an item from the cache by key. + * + * @param string|array $key + * @return mixed + */ + public function get($key) + { + $prefixed = $this->prefix.$key; + + $cache = $this->table()->where('key', '=', $prefixed)->first(); + + // If we have a cache record we will check the expiration time against current + // time on the system and see if the record has expired. If it has, we will + // remove the records from the database table so it isn't returned again. + if (is_null($cache)) { + return; + } + + $cache = is_array($cache) ? (object) $cache : $cache; + + // If this cache expiration date is past the current time, we will remove this + // item from the cache. Then we will return a null value since the cache is + // expired. We will use "Carbon" to make this comparison with the column. + if ($this->currentTime() >= $cache->expiration) { + $this->forget($key); + + return; + } + + return $this->unserialize($cache->value); + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + $key = $this->prefix.$key; + $value = $this->serialize($value); + $expiration = $this->getTime() + $seconds; + + try { + return $this->table()->insert(compact('key', 'value', 'expiration')); + } catch (Exception $e) { + $result = $this->table()->where('key', $key)->update(compact('value', 'expiration')); + + return $result > 0; + } + } + + /** + * Store an item in the cache if the key doesn't exist. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function add($key, $value, $seconds) + { + $key = $this->prefix.$key; + $value = $this->serialize($value); + $expiration = $this->getTime() + $seconds; + + try { + return $this->table()->insert(compact('key', 'value', 'expiration')); + } catch (QueryException $e) { + return $this->table() + ->where('key', $key) + ->where('expiration', '<=', $this->getTime()) + ->update([ + 'value' => $value, + 'expiration' => $expiration, + ]) >= 1; + } + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + return $this->incrementOrDecrement($key, $value, function ($current, $value) { + return $current + $value; + }); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + return $this->incrementOrDecrement($key, $value, function ($current, $value) { + return $current - $value; + }); + } + + /** + * Increment or decrement an item in the cache. + * + * @param string $key + * @param mixed $value + * @param \Closure $callback + * @return int|bool + */ + protected function incrementOrDecrement($key, $value, Closure $callback) + { + return $this->connection->transaction(function () use ($key, $value, $callback) { + $prefixed = $this->prefix.$key; + + $cache = $this->table()->where('key', $prefixed) + ->lockForUpdate()->first(); + + // If there is no value in the cache, we will return false here. Otherwise the + // value will be decrypted and we will proceed with this function to either + // increment or decrement this value based on the given action callbacks. + if (is_null($cache)) { + return false; + } + + $cache = is_array($cache) ? (object) $cache : $cache; + + $current = $this->unserialize($cache->value); + + // Here we'll call this callback function that was given to the function which + // is used to either increment or decrement the function. We use a callback + // so we do not have to recreate all this logic in each of the functions. + $new = $callback((int) $current, $value); + + if (! is_numeric($current)) { + return false; + } + + // Here we will update the values in the table. We will also encrypt the value + // since database cache values are encrypted by default with secure storage + // that can't be easily read. We will return the new value after storing. + $this->table()->where('key', $prefixed)->update([ + 'value' => $this->serialize($new), + ]); + + return $new; + }); + } + + /** + * Get the current system time. + * + * @return int + */ + protected function getTime() + { + return $this->currentTime(); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return $this->put($key, $value, 315360000); + } + + /** + * Get a lock instance. + * + * @param string $name + * @param int $seconds + * @param string|null $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function lock($name, $seconds = 0, $owner = null) + { + return new DatabaseLock( + $this->lockConnection ?? $this->connection, + $this->lockTable, + $this->prefix.$name, + $seconds, + $owner, + $this->lockLottery + ); + } + + /** + * Restore a lock instance using the owner identifier. + * + * @param string $name + * @param string $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function restoreLock($name, $owner) + { + return $this->lock($name, 0, $owner); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + $this->table()->where('key', '=', $this->prefix.$key)->delete(); + + return true; + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + $this->table()->delete(); + + return true; + } + + /** + * Get a query builder for the cache table. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function table() + { + return $this->connection->table($this->table); + } + + /** + * Get the underlying database connection. + * + * @return \Illuminate\Database\ConnectionInterface + */ + public function getConnection() + { + return $this->connection; + } + + /** + * Specify the name of the connection that should be used to manage locks. + * + * @param \Illuminate\Database\ConnectionInterface $connection + * @return $this + */ + public function setLockConnection($connection) + { + $this->lockConnection = $connection; + + return $this; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * Serialize the given value. + * + * @param mixed $value + * @return string + */ + protected function serialize($value) + { + $result = serialize($value); + + if ($this->connection instanceof PostgresConnection && Str::contains($result, "\0")) { + $result = base64_encode($result); + } + + return $result; + } + + /** + * Unserialize the given value. + * + * @param string $value + * @return mixed + */ + protected function unserialize($value) + { + if ($this->connection instanceof PostgresConnection && ! Str::contains($value, [':', ';'])) { + $value = base64_decode($value); + } + + return unserialize($value); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DynamoDbLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DynamoDbLock.php new file mode 100644 index 0000000..9222607 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DynamoDbLock.php @@ -0,0 +1,77 @@ +dynamo = $dynamo; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + if ($this->seconds > 0) { + return $this->dynamo->add($this->name, $this->owner, $this->seconds); + } else { + return $this->dynamo->add($this->name, $this->owner, 86400); + } + } + + /** + * Release the lock. + * + * @return bool + */ + public function release() + { + if ($this->isOwnedByCurrentProcess()) { + return $this->dynamo->forget($this->name); + } + + return false; + } + + /** + * Release this lock in disregard of ownership. + * + * @return void + */ + public function forceRelease() + { + $this->dynamo->forget($this->name); + } + + /** + * Returns the owner value written into the driver for this lock. + * + * @return mixed + */ + protected function getCurrentOwner() + { + return $this->dynamo->get($this->name); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DynamoDbStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DynamoDbStore.php new file mode 100644 index 0000000..aa28a78 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/DynamoDbStore.php @@ -0,0 +1,538 @@ +table = $table; + $this->dynamo = $dynamo; + $this->keyAttribute = $keyAttribute; + $this->valueAttribute = $valueAttribute; + $this->expirationAttribute = $expirationAttribute; + + $this->setPrefix($prefix); + } + + /** + * Retrieve an item from the cache by key. + * + * @param string $key + * @return mixed + */ + public function get($key) + { + $response = $this->dynamo->getItem([ + 'TableName' => $this->table, + 'ConsistentRead' => false, + 'Key' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + ], + ]); + + if (! isset($response['Item'])) { + return; + } + + if ($this->isExpired($response['Item'])) { + return; + } + + if (isset($response['Item'][$this->valueAttribute])) { + return $this->unserialize( + $response['Item'][$this->valueAttribute]['S'] ?? + $response['Item'][$this->valueAttribute]['N'] ?? + null + ); + } + } + + /** + * Retrieve multiple items from the cache by key. + * + * Items not found in the cache will have a null value. + * + * @param array $keys + * @return array + */ + public function many(array $keys) + { + $prefixedKeys = array_map(function ($key) { + return $this->prefix.$key; + }, $keys); + + $response = $this->dynamo->batchGetItem([ + 'RequestItems' => [ + $this->table => [ + 'ConsistentRead' => false, + 'Keys' => collect($prefixedKeys)->map(function ($key) { + return [ + $this->keyAttribute => [ + 'S' => $key, + ], + ]; + })->all(), + ], + ], + ]); + + $now = Carbon::now(); + + return array_merge(collect(array_flip($keys))->map(function () { + // + })->all(), collect($response['Responses'][$this->table])->mapWithKeys(function ($response) use ($now) { + if ($this->isExpired($response, $now)) { + $value = null; + } else { + $value = $this->unserialize( + $response[$this->valueAttribute]['S'] ?? + $response[$this->valueAttribute]['N'] ?? + null + ); + } + + return [Str::replaceFirst($this->prefix, '', $response[$this->keyAttribute]['S']) => $value]; + })->all()); + } + + /** + * Determine if the given item is expired. + * + * @param array $item + * @param \DateTimeInterface|null $expiration + * @return bool + */ + protected function isExpired(array $item, $expiration = null) + { + $expiration = $expiration ?: Carbon::now(); + + return isset($item[$this->expirationAttribute]) && + $expiration->getTimestamp() >= $item[$this->expirationAttribute]['N']; + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + $this->dynamo->putItem([ + 'TableName' => $this->table, + 'Item' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + $this->valueAttribute => [ + $this->type($value) => $this->serialize($value), + ], + $this->expirationAttribute => [ + 'N' => (string) $this->toTimestamp($seconds), + ], + ], + ]); + + return true; + } + + /** + * Store multiple items in the cache for a given number of $seconds. + * + * @param array $values + * @param int $seconds + * @return bool + */ + public function putMany(array $values, $seconds) + { + $expiration = $this->toTimestamp($seconds); + + $this->dynamo->batchWriteItem([ + 'RequestItems' => [ + $this->table => collect($values)->map(function ($value, $key) use ($expiration) { + return [ + 'PutRequest' => [ + 'Item' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + $this->valueAttribute => [ + $this->type($value) => $this->serialize($value), + ], + $this->expirationAttribute => [ + 'N' => (string) $expiration, + ], + ], + ], + ]; + })->values()->all(), + ], + ]); + + return true; + } + + /** + * Store an item in the cache if the key doesn't exist. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function add($key, $value, $seconds) + { + try { + $this->dynamo->putItem([ + 'TableName' => $this->table, + 'Item' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + $this->valueAttribute => [ + $this->type($value) => $this->serialize($value), + ], + $this->expirationAttribute => [ + 'N' => (string) $this->toTimestamp($seconds), + ], + ], + 'ConditionExpression' => 'attribute_not_exists(#key) OR #expires_at < :now', + 'ExpressionAttributeNames' => [ + '#key' => $this->keyAttribute, + '#expires_at' => $this->expirationAttribute, + ], + 'ExpressionAttributeValues' => [ + ':now' => [ + 'N' => (string) Carbon::now()->getTimestamp(), + ], + ], + ]); + + return true; + } catch (DynamoDbException $e) { + if (Str::contains($e->getMessage(), 'ConditionalCheckFailed')) { + return false; + } + + throw $e; + } + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + try { + $response = $this->dynamo->updateItem([ + 'TableName' => $this->table, + 'Key' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + ], + 'ConditionExpression' => 'attribute_exists(#key) AND #expires_at > :now', + 'UpdateExpression' => 'SET #value = #value + :amount', + 'ExpressionAttributeNames' => [ + '#key' => $this->keyAttribute, + '#value' => $this->valueAttribute, + '#expires_at' => $this->expirationAttribute, + ], + 'ExpressionAttributeValues' => [ + ':now' => [ + 'N' => (string) Carbon::now()->getTimestamp(), + ], + ':amount' => [ + 'N' => (string) $value, + ], + ], + 'ReturnValues' => 'UPDATED_NEW', + ]); + + return (int) $response['Attributes'][$this->valueAttribute]['N']; + } catch (DynamoDbException $e) { + if (Str::contains($e->getMessage(), 'ConditionalCheckFailed')) { + return false; + } + + throw $e; + } + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + try { + $response = $this->dynamo->updateItem([ + 'TableName' => $this->table, + 'Key' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + ], + 'ConditionExpression' => 'attribute_exists(#key) AND #expires_at > :now', + 'UpdateExpression' => 'SET #value = #value - :amount', + 'ExpressionAttributeNames' => [ + '#key' => $this->keyAttribute, + '#value' => $this->valueAttribute, + '#expires_at' => $this->expirationAttribute, + ], + 'ExpressionAttributeValues' => [ + ':now' => [ + 'N' => (string) Carbon::now()->getTimestamp(), + ], + ':amount' => [ + 'N' => (string) $value, + ], + ], + 'ReturnValues' => 'UPDATED_NEW', + ]); + + return (int) $response['Attributes'][$this->valueAttribute]['N']; + } catch (DynamoDbException $e) { + if (Str::contains($e->getMessage(), 'ConditionalCheckFailed')) { + return false; + } + + throw $e; + } + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return $this->put($key, $value, Carbon::now()->addYears(5)->getTimestamp()); + } + + /** + * Get a lock instance. + * + * @param string $name + * @param int $seconds + * @param string|null $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function lock($name, $seconds = 0, $owner = null) + { + return new DynamoDbLock($this, $this->prefix.$name, $seconds, $owner); + } + + /** + * Restore a lock instance using the owner identifier. + * + * @param string $name + * @param string $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function restoreLock($name, $owner) + { + return $this->lock($name, 0, $owner); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + $this->dynamo->deleteItem([ + 'TableName' => $this->table, + 'Key' => [ + $this->keyAttribute => [ + 'S' => $this->prefix.$key, + ], + ], + ]); + + return true; + } + + /** + * Remove all items from the cache. + * + * @return bool + * + * @throws \RuntimeException + */ + public function flush() + { + throw new RuntimeException('DynamoDb does not support flushing an entire table. Please create a new table.'); + } + + /** + * Get the UNIX timestamp for the given number of seconds. + * + * @param int $seconds + * @return int + */ + protected function toTimestamp($seconds) + { + return $seconds > 0 + ? $this->availableAt($seconds) + : Carbon::now()->getTimestamp(); + } + + /** + * Serialize the value. + * + * @param mixed $value + * @return mixed + */ + protected function serialize($value) + { + return is_numeric($value) ? (string) $value : serialize($value); + } + + /** + * Unserialize the value. + * + * @param mixed $value + * @return mixed + */ + protected function unserialize($value) + { + if (filter_var($value, FILTER_VALIDATE_INT) !== false) { + return (int) $value; + } + + if (is_numeric($value)) { + return (float) $value; + } + + return unserialize($value); + } + + /** + * Get the DynamoDB type for the given value. + * + * @param mixed $value + * @return string + */ + protected function type($value) + { + return is_numeric($value) ? 'N' : 'S'; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * Set the cache key prefix. + * + * @param string $prefix + * @return void + */ + public function setPrefix($prefix) + { + $this->prefix = ! empty($prefix) ? $prefix.':' : ''; + } + + /** + * Get the DynamoDb Client instance. + * + * @return DynamoDbClient + */ + public function getClient() + { + return $this->dynamo; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheEvent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheEvent.php new file mode 100644 index 0000000..6c9d42c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheEvent.php @@ -0,0 +1,46 @@ +key = $key; + $this->tags = $tags; + } + + /** + * Set the tags for the cache event. + * + * @param array $tags + * @return $this + */ + public function setTags($tags) + { + $this->tags = $tags; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheHit.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheHit.php new file mode 100644 index 0000000..976c9e4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheHit.php @@ -0,0 +1,28 @@ +value = $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheMissed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheMissed.php new file mode 100644 index 0000000..d2a5c9f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Events/CacheMissed.php @@ -0,0 +1,8 @@ +value = $value; + $this->seconds = $seconds; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php new file mode 100755 index 0000000..4229229 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php @@ -0,0 +1,351 @@ +files = $files; + $this->directory = $directory; + $this->filePermission = $filePermission; + } + + /** + * Retrieve an item from the cache by key. + * + * @param string|array $key + * @return mixed + */ + public function get($key) + { + return $this->getPayload($key)['data'] ?? null; + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + $this->ensureCacheDirectoryExists($path = $this->path($key)); + + $result = $this->files->put( + $path, $this->expiration($seconds).serialize($value), true + ); + + if ($result !== false && $result > 0) { + $this->ensurePermissionsAreCorrect($path); + + return true; + } + + return false; + } + + /** + * Store an item in the cache if the key doesn't exist. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function add($key, $value, $seconds) + { + $this->ensureCacheDirectoryExists($path = $this->path($key)); + + $file = new LockableFile($path, 'c+'); + + try { + $file->getExclusiveLock(); + } catch (LockTimeoutException $e) { + $file->close(); + + return false; + } + + $expire = $file->read(10); + + if (empty($expire) || $this->currentTime() >= $expire) { + $file->truncate() + ->write($this->expiration($seconds).serialize($value)) + ->close(); + + $this->ensurePermissionsAreCorrect($path); + + return true; + } + + $file->close(); + + return false; + } + + /** + * Create the file cache directory if necessary. + * + * @param string $path + * @return void + */ + protected function ensureCacheDirectoryExists($path) + { + $directory = dirname($path); + + if (! $this->files->exists($directory)) { + $this->files->makeDirectory($directory, 0777, true, true); + + // We're creating two levels of directories (e.g. 7e/24), so we check them both... + $this->ensurePermissionsAreCorrect($directory); + $this->ensurePermissionsAreCorrect(dirname($directory)); + } + } + + /** + * Ensure the created node has the correct permissions. + * + * @param string $path + * @return void + */ + protected function ensurePermissionsAreCorrect($path) + { + if (is_null($this->filePermission) || + intval($this->files->chmod($path), 8) == $this->filePermission) { + return; + } + + $this->files->chmod($path, $this->filePermission); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int + */ + public function increment($key, $value = 1) + { + $raw = $this->getPayload($key); + + return tap(((int) $raw['data']) + $value, function ($newValue) use ($key, $raw) { + $this->put($key, $newValue, $raw['time'] ?? 0); + }); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int + */ + public function decrement($key, $value = 1) + { + return $this->increment($key, $value * -1); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return $this->put($key, $value, 0); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + if ($this->files->exists($file = $this->path($key))) { + return $this->files->delete($file); + } + + return false; + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + if (! $this->files->isDirectory($this->directory)) { + return false; + } + + foreach ($this->files->directories($this->directory) as $directory) { + $deleted = $this->files->deleteDirectory($directory); + + if (! $deleted || $this->files->exists($directory)) { + return false; + } + } + + return true; + } + + /** + * Retrieve an item and expiry time from the cache by key. + * + * @param string $key + * @return array + */ + protected function getPayload($key) + { + $path = $this->path($key); + + // If the file doesn't exist, we obviously cannot return the cache so we will + // just return null. Otherwise, we'll get the contents of the file and get + // the expiration UNIX timestamps from the start of the file's contents. + try { + $expire = substr( + $contents = $this->files->get($path, true), 0, 10 + ); + } catch (Exception $e) { + return $this->emptyPayload(); + } + + // If the current time is greater than expiration timestamps we will delete + // the file and return null. This helps clean up the old files and keeps + // this directory much cleaner for us as old files aren't hanging out. + if ($this->currentTime() >= $expire) { + $this->forget($key); + + return $this->emptyPayload(); + } + + try { + $data = unserialize(substr($contents, 10)); + } catch (Exception $e) { + $this->forget($key); + + return $this->emptyPayload(); + } + + // Next, we'll extract the number of seconds that are remaining for a cache + // so that we can properly retain the time for things like the increment + // operation that may be performed on this cache on a later operation. + $time = $expire - $this->currentTime(); + + return compact('data', 'time'); + } + + /** + * Get a default empty payload for the cache. + * + * @return array + */ + protected function emptyPayload() + { + return ['data' => null, 'time' => null]; + } + + /** + * Get the full path for the given cache key. + * + * @param string $key + * @return string + */ + protected function path($key) + { + $parts = array_slice(str_split($hash = sha1($key), 2), 0, 2); + + return $this->directory.'/'.implode('/', $parts).'/'.$hash; + } + + /** + * Get the expiration time based on the given seconds. + * + * @param int $seconds + * @return int + */ + protected function expiration($seconds) + { + $time = $this->availableAt($seconds); + + return $seconds === 0 || $time > 9999999999 ? 9999999999 : $time; + } + + /** + * Get the Filesystem instance. + * + * @return \Illuminate\Filesystem\Filesystem + */ + public function getFilesystem() + { + return $this->files; + } + + /** + * Get the working directory of the cache. + * + * @return string + */ + public function getDirectory() + { + return $this->directory; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/HasCacheLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/HasCacheLock.php new file mode 100644 index 0000000..82ad9c2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/HasCacheLock.php @@ -0,0 +1,31 @@ +lock($name, 0, $owner); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Lock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Lock.php new file mode 100644 index 0000000..bed1705 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Lock.php @@ -0,0 +1,167 @@ +name = $name; + $this->owner = $owner; + $this->seconds = $seconds; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + abstract public function acquire(); + + /** + * Release the lock. + * + * @return bool + */ + abstract public function release(); + + /** + * Returns the owner value written into the driver for this lock. + * + * @return string + */ + abstract protected function getCurrentOwner(); + + /** + * Attempt to acquire the lock. + * + * @param callable|null $callback + * @return mixed + */ + public function get($callback = null) + { + $result = $this->acquire(); + + if ($result && is_callable($callback)) { + try { + return $callback(); + } finally { + $this->release(); + } + } + + return $result; + } + + /** + * Attempt to acquire the lock for the given number of seconds. + * + * @param int $seconds + * @param callable|null $callback + * @return mixed + * + * @throws \Illuminate\Contracts\Cache\LockTimeoutException + */ + public function block($seconds, $callback = null) + { + $starting = $this->currentTime(); + + while (! $this->acquire()) { + usleep($this->sleepMilliseconds * 1000); + + if ($this->currentTime() - $seconds >= $starting) { + throw new LockTimeoutException; + } + } + + if (is_callable($callback)) { + try { + return $callback(); + } finally { + $this->release(); + } + } + + return true; + } + + /** + * Returns the current owner of the lock. + * + * @return string + */ + public function owner() + { + return $this->owner; + } + + /** + * Determines whether this lock is allowed to release the lock in the driver. + * + * @return bool + */ + protected function isOwnedByCurrentProcess() + { + return $this->getCurrentOwner() === $this->owner; + } + + /** + * Specify the number of milliseconds to sleep in between blocked lock acquisition attempts. + * + * @param int $milliseconds + * @return $this + */ + public function betweenBlockedAttemptsSleepFor($milliseconds) + { + $this->sleepMilliseconds = $milliseconds; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/LuaScripts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/LuaScripts.php new file mode 100644 index 0000000..6d22fcd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/LuaScripts.php @@ -0,0 +1,25 @@ +getMemcached( + $connectionId, $credentials, $options + ); + + if (! $memcached->getServerList()) { + // For each server in the array, we'll just extract the configuration and add + // the server to the Memcached connection. Once we have added all of these + // servers we'll verify the connection is successful and return it back. + foreach ($servers as $server) { + $memcached->addServer( + $server['host'], $server['port'], $server['weight'] + ); + } + } + + return $memcached; + } + + /** + * Get a new Memcached instance. + * + * @param string|null $connectionId + * @param array $credentials + * @param array $options + * @return \Memcached + */ + protected function getMemcached($connectionId, array $credentials, array $options) + { + $memcached = $this->createMemcachedInstance($connectionId); + + if (count($credentials) === 2) { + $this->setCredentials($memcached, $credentials); + } + + if (count($options)) { + $memcached->setOptions($options); + } + + return $memcached; + } + + /** + * Create the Memcached instance. + * + * @param string|null $connectionId + * @return \Memcached + */ + protected function createMemcachedInstance($connectionId) + { + return empty($connectionId) ? new Memcached : new Memcached($connectionId); + } + + /** + * Set the SASL credentials on the Memcached connection. + * + * @param \Memcached $memcached + * @param array $credentials + * @return void + */ + protected function setCredentials($memcached, $credentials) + { + [$username, $password] = $credentials; + + $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); + + $memcached->setSaslAuthData($username, $password); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/MemcachedLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/MemcachedLock.php new file mode 100644 index 0000000..0078a09 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/MemcachedLock.php @@ -0,0 +1,75 @@ +memcached = $memcached; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + return $this->memcached->add( + $this->name, $this->owner, $this->seconds + ); + } + + /** + * Release the lock. + * + * @return bool + */ + public function release() + { + if ($this->isOwnedByCurrentProcess()) { + return $this->memcached->delete($this->name); + } + + return false; + } + + /** + * Releases this lock in disregard of ownership. + * + * @return void + */ + public function forceRelease() + { + $this->memcached->delete($this->name); + } + + /** + * Returns the owner value written into the driver for this lock. + * + * @return mixed + */ + protected function getCurrentOwner() + { + return $this->memcached->get($this->name); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/MemcachedStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/MemcachedStore.php new file mode 100755 index 0000000..299dab9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/MemcachedStore.php @@ -0,0 +1,279 @@ += 3.0.0. + * + * @var bool + */ + protected $onVersionThree; + + /** + * Create a new Memcached store. + * + * @param \Memcached $memcached + * @param string $prefix + * @return void + */ + public function __construct($memcached, $prefix = '') + { + $this->setPrefix($prefix); + $this->memcached = $memcached; + + $this->onVersionThree = (new ReflectionMethod('Memcached', 'getMulti')) + ->getNumberOfParameters() == 2; + } + + /** + * Retrieve an item from the cache by key. + * + * @param string $key + * @return mixed + */ + public function get($key) + { + $value = $this->memcached->get($this->prefix.$key); + + if ($this->memcached->getResultCode() == 0) { + return $value; + } + } + + /** + * Retrieve multiple items from the cache by key. + * + * Items not found in the cache will have a null value. + * + * @param array $keys + * @return array + */ + public function many(array $keys) + { + $prefixedKeys = array_map(function ($key) { + return $this->prefix.$key; + }, $keys); + + if ($this->onVersionThree) { + $values = $this->memcached->getMulti($prefixedKeys, Memcached::GET_PRESERVE_ORDER); + } else { + $null = null; + + $values = $this->memcached->getMulti($prefixedKeys, $null, Memcached::GET_PRESERVE_ORDER); + } + + if ($this->memcached->getResultCode() != 0) { + return array_fill_keys($keys, null); + } + + return array_combine($keys, $values); + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + return $this->memcached->set( + $this->prefix.$key, $value, $this->calculateExpiration($seconds) + ); + } + + /** + * Store multiple items in the cache for a given number of seconds. + * + * @param array $values + * @param int $seconds + * @return bool + */ + public function putMany(array $values, $seconds) + { + $prefixedValues = []; + + foreach ($values as $key => $value) { + $prefixedValues[$this->prefix.$key] = $value; + } + + return $this->memcached->setMulti( + $prefixedValues, $this->calculateExpiration($seconds) + ); + } + + /** + * Store an item in the cache if the key doesn't exist. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function add($key, $value, $seconds) + { + return $this->memcached->add( + $this->prefix.$key, $value, $this->calculateExpiration($seconds) + ); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + return $this->memcached->increment($this->prefix.$key, $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + return $this->memcached->decrement($this->prefix.$key, $value); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return $this->put($key, $value, 0); + } + + /** + * Get a lock instance. + * + * @param string $name + * @param int $seconds + * @param string|null $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function lock($name, $seconds = 0, $owner = null) + { + return new MemcachedLock($this->memcached, $this->prefix.$name, $seconds, $owner); + } + + /** + * Restore a lock instance using the owner identifier. + * + * @param string $name + * @param string $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function restoreLock($name, $owner) + { + return $this->lock($name, 0, $owner); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + return $this->memcached->delete($this->prefix.$key); + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + return $this->memcached->flush(); + } + + /** + * Get the expiration time of the key. + * + * @param int $seconds + * @return int + */ + protected function calculateExpiration($seconds) + { + return $this->toTimestamp($seconds); + } + + /** + * Get the UNIX timestamp for the given number of seconds. + * + * @param int $seconds + * @return int + */ + protected function toTimestamp($seconds) + { + return $seconds > 0 ? $this->availableAt($seconds) : 0; + } + + /** + * Get the underlying Memcached connection. + * + * @return \Memcached + */ + public function getMemcached() + { + return $this->memcached; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * Set the cache key prefix. + * + * @param string $prefix + * @return void + */ + public function setPrefix($prefix) + { + $this->prefix = ! empty($prefix) ? $prefix.':' : ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/NoLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/NoLock.php new file mode 100644 index 0000000..68560f8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/NoLock.php @@ -0,0 +1,46 @@ +owner; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/NullStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/NullStore.php new file mode 100755 index 0000000..5694e6c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/NullStore.php @@ -0,0 +1,126 @@ +lock($name, 0, $owner); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + return true; + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + return true; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/PhpRedisLock.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/PhpRedisLock.php new file mode 100644 index 0000000..6cfce79 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/PhpRedisLock.php @@ -0,0 +1,35 @@ +redis->eval( + LuaScripts::releaseLock(), + 1, + $this->name, + ...$this->redis->pack([$this->owner]) + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiter.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiter.php new file mode 100644 index 0000000..3786e90 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiter.php @@ -0,0 +1,223 @@ +cache = $cache; + } + + /** + * Register a named limiter configuration. + * + * @param string $name + * @param \Closure $callback + * @return $this + */ + public function for(string $name, Closure $callback) + { + $this->limiters[$name] = $callback; + + return $this; + } + + /** + * Get the given named rate limiter. + * + * @param string $name + * @return \Closure + */ + public function limiter(string $name) + { + return $this->limiters[$name] ?? null; + } + + /** + * Attempts to execute a callback if it's not limited. + * + * @param string $key + * @param int $maxAttempts + * @param \Closure $callback + * @param int $decaySeconds + * @return mixed + */ + public function attempt($key, $maxAttempts, Closure $callback, $decaySeconds = 60) + { + if ($this->tooManyAttempts($key, $maxAttempts)) { + return false; + } + + return tap($callback() ?: true, function () use ($key, $decaySeconds) { + $this->hit($key, $decaySeconds); + }); + } + + /** + * Determine if the given key has been "accessed" too many times. + * + * @param string $key + * @param int $maxAttempts + * @return bool + */ + public function tooManyAttempts($key, $maxAttempts) + { + $key = $this->cleanRateLimiterKey($key); + + if ($this->attempts($key) >= $maxAttempts) { + if ($this->cache->has($key.':timer')) { + return true; + } + + $this->resetAttempts($key); + } + + return false; + } + + /** + * Increment the counter for a given key for a given decay time. + * + * @param string $key + * @param int $decaySeconds + * @return int + */ + public function hit($key, $decaySeconds = 60) + { + $key = $this->cleanRateLimiterKey($key); + + $this->cache->add( + $key.':timer', $this->availableAt($decaySeconds), $decaySeconds + ); + + $added = $this->cache->add($key, 0, $decaySeconds); + + $hits = (int) $this->cache->increment($key); + + if (! $added && $hits == 1) { + $this->cache->put($key, 1, $decaySeconds); + } + + return $hits; + } + + /** + * Get the number of attempts for the given key. + * + * @param string $key + * @return mixed + */ + public function attempts($key) + { + $key = $this->cleanRateLimiterKey($key); + + return $this->cache->get($key, 0); + } + + /** + * Reset the number of attempts for the given key. + * + * @param string $key + * @return mixed + */ + public function resetAttempts($key) + { + $key = $this->cleanRateLimiterKey($key); + + return $this->cache->forget($key); + } + + /** + * Get the number of retries left for the given key. + * + * @param string $key + * @param int $maxAttempts + * @return int + */ + public function remaining($key, $maxAttempts) + { + $key = $this->cleanRateLimiterKey($key); + + $attempts = $this->attempts($key); + + return $maxAttempts - $attempts; + } + + /** + * Get the number of retries left for the given key. + * + * @param string $key + * @param int $maxAttempts + * @return int + */ + public function retriesLeft($key, $maxAttempts) + { + return $this->remaining($key, $maxAttempts); + } + + /** + * Clear the hits and lockout timer for the given key. + * + * @param string $key + * @return void + */ + public function clear($key) + { + $key = $this->cleanRateLimiterKey($key); + + $this->resetAttempts($key); + + $this->cache->forget($key.':timer'); + } + + /** + * Get the number of seconds until the "key" is accessible again. + * + * @param string $key + * @return int + */ + public function availableIn($key) + { + $key = $this->cleanRateLimiterKey($key); + + return max(0, $this->cache->get($key.':timer') - $this->currentTime()); + } + + /** + * Clean the rate limiter key from unicode characters. + * + * @param string $key + * @return string + */ + public function cleanRateLimiterKey($key) + { + return preg_replace('/&([a-z])[a-z]+;/i', '$1', htmlentities($key)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiting/GlobalLimit.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiting/GlobalLimit.php new file mode 100644 index 0000000..4f084eb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiting/GlobalLimit.php @@ -0,0 +1,18 @@ +key = $key; + $this->maxAttempts = $maxAttempts; + $this->decayMinutes = $decayMinutes; + } + + /** + * Create a new rate limit. + * + * @param int $maxAttempts + * @return static + */ + public static function perMinute($maxAttempts) + { + return new static('', $maxAttempts); + } + + /** + * Create a new rate limit using minutes as decay time. + * + * @param int $decayMinutes + * @param int $maxAttempts + * @return static + */ + public static function perMinutes($decayMinutes, $maxAttempts) + { + return new static('', $maxAttempts, $decayMinutes); + } + + /** + * Create a new rate limit using hours as decay time. + * + * @param int $maxAttempts + * @param int $decayHours + * @return static + */ + public static function perHour($maxAttempts, $decayHours = 1) + { + return new static('', $maxAttempts, 60 * $decayHours); + } + + /** + * Create a new rate limit using days as decay time. + * + * @param int $maxAttempts + * @param int $decayDays + * @return static + */ + public static function perDay($maxAttempts, $decayDays = 1) + { + return new static('', $maxAttempts, 60 * 24 * $decayDays); + } + + /** + * Create a new unlimited rate limit. + * + * @return static + */ + public static function none() + { + return new Unlimited; + } + + /** + * Set the key of the rate limit. + * + * @param string $key + * @return $this + */ + public function by($key) + { + $this->key = $key; + + return $this; + } + + /** + * Set the callback that should generate the response when the limit is exceeded. + * + * @param callable $callback + * @return $this + */ + public function response(callable $callback) + { + $this->responseCallback = $callback; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiting/Unlimited.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiting/Unlimited.php new file mode 100644 index 0000000..fcfaa31 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RateLimiting/Unlimited.php @@ -0,0 +1,16 @@ +redis = $redis; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + if ($this->seconds > 0) { + return $this->redis->set($this->name, $this->owner, 'EX', $this->seconds, 'NX') == true; + } else { + return $this->redis->setnx($this->name, $this->owner) === 1; + } + } + + /** + * Release the lock. + * + * @return bool + */ + public function release() + { + return (bool) $this->redis->eval(LuaScripts::releaseLock(), 1, $this->name, $this->owner); + } + + /** + * Releases this lock in disregard of ownership. + * + * @return void + */ + public function forceRelease() + { + $this->redis->del($this->name); + } + + /** + * Returns the owner value written into the driver for this lock. + * + * @return string + */ + protected function getCurrentOwner() + { + return $this->redis->get($this->name); + } + + /** + * Get the name of the Redis connection being used to manage the lock. + * + * @return string + */ + public function getConnectionName() + { + return $this->redis->getName(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php new file mode 100755 index 0000000..4896c91 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php @@ -0,0 +1,347 @@ +redis = $redis; + $this->setPrefix($prefix); + $this->setConnection($connection); + } + + /** + * Retrieve an item from the cache by key. + * + * @param string|array $key + * @return mixed + */ + public function get($key) + { + $value = $this->connection()->get($this->prefix.$key); + + return ! is_null($value) ? $this->unserialize($value) : null; + } + + /** + * Retrieve multiple items from the cache by key. + * + * Items not found in the cache will have a null value. + * + * @param array $keys + * @return array + */ + public function many(array $keys) + { + $results = []; + + $values = $this->connection()->mget(array_map(function ($key) { + return $this->prefix.$key; + }, $keys)); + + foreach ($values as $index => $value) { + $results[$keys[$index]] = ! is_null($value) ? $this->unserialize($value) : null; + } + + return $results; + } + + /** + * Store an item in the cache for a given number of seconds. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function put($key, $value, $seconds) + { + return (bool) $this->connection()->setex( + $this->prefix.$key, (int) max(1, $seconds), $this->serialize($value) + ); + } + + /** + * Store multiple items in the cache for a given number of seconds. + * + * @param array $values + * @param int $seconds + * @return bool + */ + public function putMany(array $values, $seconds) + { + $this->connection()->multi(); + + $manyResult = null; + + foreach ($values as $key => $value) { + $result = $this->put($key, $value, $seconds); + + $manyResult = is_null($manyResult) ? $result : $result && $manyResult; + } + + $this->connection()->exec(); + + return $manyResult ?: false; + } + + /** + * Store an item in the cache if the key doesn't exist. + * + * @param string $key + * @param mixed $value + * @param int $seconds + * @return bool + */ + public function add($key, $value, $seconds) + { + $lua = "return redis.call('exists',KEYS[1])<1 and redis.call('setex',KEYS[1],ARGV[2],ARGV[1])"; + + return (bool) $this->connection()->eval( + $lua, 1, $this->prefix.$key, $this->serialize($value), (int) max(1, $seconds) + ); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int + */ + public function increment($key, $value = 1) + { + return $this->connection()->incrby($this->prefix.$key, $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int + */ + public function decrement($key, $value = 1) + { + return $this->connection()->decrby($this->prefix.$key, $value); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + return (bool) $this->connection()->set($this->prefix.$key, $this->serialize($value)); + } + + /** + * Get a lock instance. + * + * @param string $name + * @param int $seconds + * @param string|null $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function lock($name, $seconds = 0, $owner = null) + { + $lockName = $this->prefix.$name; + + $lockConnection = $this->lockConnection(); + + if ($lockConnection instanceof PhpRedisConnection) { + return new PhpRedisLock($lockConnection, $lockName, $seconds, $owner); + } + + return new RedisLock($lockConnection, $lockName, $seconds, $owner); + } + + /** + * Restore a lock instance using the owner identifier. + * + * @param string $name + * @param string $owner + * @return \Illuminate\Contracts\Cache\Lock + */ + public function restoreLock($name, $owner) + { + return $this->lock($name, 0, $owner); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + return (bool) $this->connection()->del($this->prefix.$key); + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + $this->connection()->flushdb(); + + return true; + } + + /** + * Begin executing a new tags operation. + * + * @param array|mixed $names + * @return \Illuminate\Cache\RedisTaggedCache + */ + public function tags($names) + { + return new RedisTaggedCache( + $this, new TagSet($this, is_array($names) ? $names : func_get_args()) + ); + } + + /** + * Get the Redis connection instance. + * + * @return \Illuminate\Redis\Connections\Connection + */ + public function connection() + { + return $this->redis->connection($this->connection); + } + + /** + * Get the Redis connection instance that should be used to manage locks. + * + * @return \Illuminate\Redis\Connections\Connection + */ + public function lockConnection() + { + return $this->redis->connection($this->lockConnection ?? $this->connection); + } + + /** + * Specify the name of the connection that should be used to store data. + * + * @param string $connection + * @return void + */ + public function setConnection($connection) + { + $this->connection = $connection; + } + + /** + * Specify the name of the connection that should be used to manage locks. + * + * @param string $connection + * @return $this + */ + public function setLockConnection($connection) + { + $this->lockConnection = $connection; + + return $this; + } + + /** + * Get the Redis database instance. + * + * @return \Illuminate\Contracts\Redis\Factory + */ + public function getRedis() + { + return $this->redis; + } + + /** + * Get the cache key prefix. + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * Set the cache key prefix. + * + * @param string $prefix + * @return void + */ + public function setPrefix($prefix) + { + $this->prefix = ! empty($prefix) ? $prefix.':' : ''; + } + + /** + * Serialize the value. + * + * @param mixed $value + * @return mixed + */ + protected function serialize($value) + { + return is_numeric($value) && ! in_array($value, [INF, -INF]) && ! is_nan($value) ? $value : serialize($value); + } + + /** + * Unserialize the value. + * + * @param mixed $value + * @return mixed + */ + protected function unserialize($value) + { + return is_numeric($value) ? $value : unserialize($value); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RedisTaggedCache.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RedisTaggedCache.php new file mode 100644 index 0000000..7863dbc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RedisTaggedCache.php @@ -0,0 +1,214 @@ +forever($key, $value); + } + + $this->pushStandardKeys($this->tags->getNamespace(), $key); + + return parent::put($key, $value, $ttl); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + $this->pushStandardKeys($this->tags->getNamespace(), $key); + + return parent::increment($key, $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + $this->pushStandardKeys($this->tags->getNamespace(), $key); + + return parent::decrement($key, $value); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + $this->pushForeverKeys($this->tags->getNamespace(), $key); + + return parent::forever($key, $value); + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + $this->deleteForeverKeys(); + $this->deleteStandardKeys(); + + $this->tags->flush(); + + return true; + } + + /** + * Store standard key references into store. + * + * @param string $namespace + * @param string $key + * @return void + */ + protected function pushStandardKeys($namespace, $key) + { + $this->pushKeys($namespace, $key, self::REFERENCE_KEY_STANDARD); + } + + /** + * Store forever key references into store. + * + * @param string $namespace + * @param string $key + * @return void + */ + protected function pushForeverKeys($namespace, $key) + { + $this->pushKeys($namespace, $key, self::REFERENCE_KEY_FOREVER); + } + + /** + * Store a reference to the cache key against the reference key. + * + * @param string $namespace + * @param string $key + * @param string $reference + * @return void + */ + protected function pushKeys($namespace, $key, $reference) + { + $fullKey = $this->store->getPrefix().sha1($namespace).':'.$key; + + foreach (explode('|', $namespace) as $segment) { + $this->store->connection()->sadd($this->referenceKey($segment, $reference), $fullKey); + } + } + + /** + * Delete all of the items that were stored forever. + * + * @return void + */ + protected function deleteForeverKeys() + { + $this->deleteKeysByReference(self::REFERENCE_KEY_FOREVER); + } + + /** + * Delete all standard items. + * + * @return void + */ + protected function deleteStandardKeys() + { + $this->deleteKeysByReference(self::REFERENCE_KEY_STANDARD); + } + + /** + * Find and delete all of the items that were stored against a reference. + * + * @param string $reference + * @return void + */ + protected function deleteKeysByReference($reference) + { + foreach (explode('|', $this->tags->getNamespace()) as $segment) { + $this->deleteValues($segment = $this->referenceKey($segment, $reference)); + + $this->store->connection()->del($segment); + } + } + + /** + * Delete item keys that have been stored against a reference. + * + * @param string $referenceKey + * @return void + */ + protected function deleteValues($referenceKey) + { + $cursor = $defaultCursorValue = '0'; + + do { + [$cursor, $valuesChunk] = $this->store->connection()->sscan( + $referenceKey, $cursor, ['match' => '*', 'count' => 1000] + ); + + // PhpRedis client returns false if set does not exist or empty. Array destruction + // on false stores null in each variable. If valuesChunk is null, it means that + // there were not results from the previously executed "sscan" Redis command. + if (is_null($valuesChunk)) { + break; + } + + $valuesChunk = array_unique($valuesChunk); + + if (count($valuesChunk) > 0) { + $this->store->connection()->del(...$valuesChunk); + } + } while (((string) $cursor) !== $defaultCursorValue); + } + + /** + * Get the reference key for the segment. + * + * @param string $segment + * @param string $suffix + * @return string + */ + protected function referenceKey($segment, $suffix) + { + return $this->store->getPrefix().$segment.':'.$suffix; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Repository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Repository.php new file mode 100755 index 0000000..c7934c0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/Repository.php @@ -0,0 +1,686 @@ +store = $store; + } + + /** + * Determine if an item exists in the cache. + * + * @param string $key + * @return bool + */ + public function has($key) + { + return ! is_null($this->get($key)); + } + + /** + * Determine if an item doesn't exist in the cache. + * + * @param string $key + * @return bool + */ + public function missing($key) + { + return ! $this->has($key); + } + + /** + * Retrieve an item from the cache by key. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + if (is_array($key)) { + return $this->many($key); + } + + $value = $this->store->get($this->itemKey($key)); + + // If we could not find the cache value, we will fire the missed event and get + // the default value for this cache value. This default could be a callback + // so we will execute the value function which will resolve it if needed. + if (is_null($value)) { + $this->event(new CacheMissed($key)); + + $value = value($default); + } else { + $this->event(new CacheHit($key, $value)); + } + + return $value; + } + + /** + * Retrieve multiple items from the cache by key. + * + * Items not found in the cache will have a null value. + * + * @param array $keys + * @return array + */ + public function many(array $keys) + { + $values = $this->store->many(collect($keys)->map(function ($value, $key) { + return is_string($key) ? $key : $value; + })->values()->all()); + + return collect($values)->map(function ($value, $key) use ($keys) { + return $this->handleManyResult($keys, $key, $value); + })->all(); + } + + /** + * {@inheritdoc} + * + * @return iterable + */ + public function getMultiple($keys, $default = null) + { + $defaults = []; + + foreach ($keys as $key) { + $defaults[$key] = $default; + } + + return $this->many($defaults); + } + + /** + * Handle a result for the "many" method. + * + * @param array $keys + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function handleManyResult($keys, $key, $value) + { + // If we could not find the cache value, we will fire the missed event and get + // the default value for this cache value. This default could be a callback + // so we will execute the value function which will resolve it if needed. + if (is_null($value)) { + $this->event(new CacheMissed($key)); + + return isset($keys[$key]) ? value($keys[$key]) : null; + } + + // If we found a valid value we will fire the "hit" event and return the value + // back from this function. The "hit" event gives developers an opportunity + // to listen for every possible cache "hit" throughout this applications. + $this->event(new CacheHit($key, $value)); + + return $value; + } + + /** + * Retrieve an item from the cache and delete it. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function pull($key, $default = null) + { + return tap($this->get($key, $default), function () use ($key) { + $this->forget($key); + }); + } + + /** + * Store an item in the cache. + * + * @param string $key + * @param mixed $value + * @param \DateTimeInterface|\DateInterval|int|null $ttl + * @return bool + */ + public function put($key, $value, $ttl = null) + { + if (is_array($key)) { + return $this->putMany($key, $value); + } + + if ($ttl === null) { + return $this->forever($key, $value); + } + + $seconds = $this->getSeconds($ttl); + + if ($seconds <= 0) { + return $this->forget($key); + } + + $result = $this->store->put($this->itemKey($key), $value, $seconds); + + if ($result) { + $this->event(new KeyWritten($key, $value, $seconds)); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function set($key, $value, $ttl = null) + { + return $this->put($key, $value, $ttl); + } + + /** + * Store multiple items in the cache for a given number of seconds. + * + * @param array $values + * @param \DateTimeInterface|\DateInterval|int|null $ttl + * @return bool + */ + public function putMany(array $values, $ttl = null) + { + if ($ttl === null) { + return $this->putManyForever($values); + } + + $seconds = $this->getSeconds($ttl); + + if ($seconds <= 0) { + return $this->deleteMultiple(array_keys($values)); + } + + $result = $this->store->putMany($values, $seconds); + + if ($result) { + foreach ($values as $key => $value) { + $this->event(new KeyWritten($key, $value, $seconds)); + } + } + + return $result; + } + + /** + * Store multiple items in the cache indefinitely. + * + * @param array $values + * @return bool + */ + protected function putManyForever(array $values) + { + $result = true; + + foreach ($values as $key => $value) { + if (! $this->forever($key, $value)) { + $result = false; + } + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function setMultiple($values, $ttl = null) + { + return $this->putMany(is_array($values) ? $values : iterator_to_array($values), $ttl); + } + + /** + * Store an item in the cache if the key does not exist. + * + * @param string $key + * @param mixed $value + * @param \DateTimeInterface|\DateInterval|int|null $ttl + * @return bool + */ + public function add($key, $value, $ttl = null) + { + $seconds = null; + + if ($ttl !== null) { + $seconds = $this->getSeconds($ttl); + + if ($seconds <= 0) { + return false; + } + + // If the store has an "add" method we will call the method on the store so it + // has a chance to override this logic. Some drivers better support the way + // this operation should work with a total "atomic" implementation of it. + if (method_exists($this->store, 'add')) { + return $this->store->add( + $this->itemKey($key), $value, $seconds + ); + } + } + + // If the value did not exist in the cache, we will put the value in the cache + // so it exists for subsequent requests. Then, we will return true so it is + // easy to know if the value gets added. Otherwise, we will return false. + if (is_null($this->get($key))) { + return $this->put($key, $value, $seconds); + } + + return false; + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + return $this->store->increment($key, $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + return $this->store->decrement($key, $value); + } + + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function forever($key, $value) + { + $result = $this->store->forever($this->itemKey($key), $value); + + if ($result) { + $this->event(new KeyWritten($key, $value)); + } + + return $result; + } + + /** + * Get an item from the cache, or execute the given Closure and store the result. + * + * @param string $key + * @param \Closure|\DateTimeInterface|\DateInterval|int|null $ttl + * @param \Closure $callback + * @return mixed + */ + public function remember($key, $ttl, Closure $callback) + { + $value = $this->get($key); + + // If the item exists in the cache we will just return this immediately and if + // not we will execute the given Closure and cache the result of that for a + // given number of seconds so it's available for all subsequent requests. + if (! is_null($value)) { + return $value; + } + + $this->put($key, $value = $callback(), value($ttl)); + + return $value; + } + + /** + * Get an item from the cache, or execute the given Closure and store the result forever. + * + * @param string $key + * @param \Closure $callback + * @return mixed + */ + public function sear($key, Closure $callback) + { + return $this->rememberForever($key, $callback); + } + + /** + * Get an item from the cache, or execute the given Closure and store the result forever. + * + * @param string $key + * @param \Closure $callback + * @return mixed + */ + public function rememberForever($key, Closure $callback) + { + $value = $this->get($key); + + // If the item exists in the cache we will just return this immediately + // and if not we will execute the given Closure and cache the result + // of that forever so it is available for all subsequent requests. + if (! is_null($value)) { + return $value; + } + + $this->forever($key, $value = $callback()); + + return $value; + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + */ + public function forget($key) + { + return tap($this->store->forget($this->itemKey($key)), function ($result) use ($key) { + if ($result) { + $this->event(new KeyForgotten($key)); + } + }); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function delete($key) + { + return $this->forget($key); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function deleteMultiple($keys) + { + $result = true; + + foreach ($keys as $key) { + if (! $this->forget($key)) { + $result = false; + } + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function clear() + { + return $this->store->flush(); + } + + /** + * Begin executing a new tags operation if the store supports it. + * + * @param array|mixed $names + * @return \Illuminate\Cache\TaggedCache + * + * @throws \BadMethodCallException + */ + public function tags($names) + { + if (! $this->supportsTags()) { + throw new BadMethodCallException('This cache store does not support tagging.'); + } + + $cache = $this->store->tags(is_array($names) ? $names : func_get_args()); + + if (! is_null($this->events)) { + $cache->setEventDispatcher($this->events); + } + + return $cache->setDefaultCacheTime($this->default); + } + + /** + * Format the key for a cache item. + * + * @param string $key + * @return string + */ + protected function itemKey($key) + { + return $key; + } + + /** + * Calculate the number of seconds for the given TTL. + * + * @param \DateTimeInterface|\DateInterval|int $ttl + * @return int + */ + protected function getSeconds($ttl) + { + $duration = $this->parseDateInterval($ttl); + + if ($duration instanceof DateTimeInterface) { + $duration = Carbon::now()->diffInRealSeconds($duration, false); + } + + return (int) ($duration > 0 ? $duration : 0); + } + + /** + * Determine if the current store supports tags. + * + * @return bool + */ + public function supportsTags() + { + return method_exists($this->store, 'tags'); + } + + /** + * Get the default cache time. + * + * @return int|null + */ + public function getDefaultCacheTime() + { + return $this->default; + } + + /** + * Set the default cache time in seconds. + * + * @param int|null $seconds + * @return $this + */ + public function setDefaultCacheTime($seconds) + { + $this->default = $seconds; + + return $this; + } + + /** + * Get the cache store implementation. + * + * @return \Illuminate\Contracts\Cache\Store + */ + public function getStore() + { + return $this->store; + } + + /** + * Fire an event for this cache instance. + * + * @param object|string $event + * @return void + */ + protected function event($event) + { + if (isset($this->events)) { + $this->events->dispatch($event); + } + } + + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public function getEventDispatcher() + { + return $this->events; + } + + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + */ + public function setEventDispatcher(Dispatcher $events) + { + $this->events = $events; + } + + /** + * Determine if a cached value exists. + * + * @param string $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->has($key); + } + + /** + * Retrieve an item from the cache by key. + * + * @param string $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->get($key); + } + + /** + * Store an item in the cache for the default time. + * + * @param string $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->put($key, $value, $this->default); + } + + /** + * Remove an item from the cache. + * + * @param string $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + $this->forget($key); + } + + /** + * Handle dynamic calls into macros or pass missing methods to the store. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + return $this->store->$method(...$parameters); + } + + /** + * Clone cache repository instance. + * + * @return void + */ + public function __clone() + { + $this->store = clone $this->store; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RetrievesMultipleKeys.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RetrievesMultipleKeys.php new file mode 100644 index 0000000..7db7a0a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/RetrievesMultipleKeys.php @@ -0,0 +1,49 @@ +mapWithKeys(function ($value, $key) { + return [is_string($key) ? $key : $value => is_string($key) ? $value : null]; + })->all(); + + foreach ($keys as $key => $default) { + $return[$key] = $this->get($key, $default); + } + + return $return; + } + + /** + * Store multiple items in the cache for a given number of seconds. + * + * @param array $values + * @param int $seconds + * @return bool + */ + public function putMany(array $values, $seconds) + { + $manyResult = null; + + foreach ($values as $key => $value) { + $result = $this->put($key, $value, $seconds); + + $manyResult = is_null($manyResult) ? $result : $result && $manyResult; + } + + return $manyResult ?: false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/TagSet.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/TagSet.php new file mode 100644 index 0000000..471dc67 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/TagSet.php @@ -0,0 +1,130 @@ +store = $store; + $this->names = $names; + } + + /** + * Reset all tags in the set. + * + * @return void + */ + public function reset() + { + array_walk($this->names, [$this, 'resetTag']); + } + + /** + * Reset the tag and return the new tag identifier. + * + * @param string $name + * @return string + */ + public function resetTag($name) + { + $this->store->forever($this->tagKey($name), $id = str_replace('.', '', uniqid('', true))); + + return $id; + } + + /** + * Flush all the tags in the set. + * + * @return void + */ + public function flush() + { + array_walk($this->names, [$this, 'flushTag']); + } + + /** + * Flush the tag from the cache. + * + * @param string $name + */ + public function flushTag($name) + { + $this->store->forget($this->tagKey($name)); + } + + /** + * Get a unique namespace that changes when any of the tags are flushed. + * + * @return string + */ + public function getNamespace() + { + return implode('|', $this->tagIds()); + } + + /** + * Get an array of tag identifiers for all of the tags in the set. + * + * @return array + */ + protected function tagIds() + { + return array_map([$this, 'tagId'], $this->names); + } + + /** + * Get the unique tag identifier for a given tag. + * + * @param string $name + * @return string + */ + public function tagId($name) + { + return $this->store->get($this->tagKey($name)) ?: $this->resetTag($name); + } + + /** + * Get the tag identifier key for a given tag. + * + * @param string $name + * @return string + */ + public function tagKey($name) + { + return 'tag:'.$name.':key'; + } + + /** + * Get all of the tag names in the set. + * + * @return array + */ + public function getNames() + { + return $this->names; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/TaggableStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/TaggableStore.php new file mode 100644 index 0000000..6a12b45 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/TaggableStore.php @@ -0,0 +1,19 @@ +tags = $tags; + } + + /** + * Store multiple items in the cache for a given number of seconds. + * + * @param array $values + * @param int|null $ttl + * @return bool + */ + public function putMany(array $values, $ttl = null) + { + if ($ttl === null) { + return $this->putManyForever($values); + } + + return $this->putManyAlias($values, $ttl); + } + + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function increment($key, $value = 1) + { + return $this->store->increment($this->itemKey($key), $value); + } + + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + */ + public function decrement($key, $value = 1) + { + return $this->store->decrement($this->itemKey($key), $value); + } + + /** + * Remove all items from the cache. + * + * @return bool + */ + public function flush() + { + $this->tags->reset(); + + return true; + } + + /** + * {@inheritdoc} + */ + protected function itemKey($key) + { + return $this->taggedItemKey($key); + } + + /** + * Get a fully qualified key for a tagged item. + * + * @param string $key + * @return string + */ + public function taggedItemKey($key) + { + return sha1($this->tags->getNamespace()).':'.$key; + } + + /** + * Fire an event for this cache instance. + * + * @param \Illuminate\Cache\Events\CacheEvent $event + * @return void + */ + protected function event($event) + { + parent::event($event->setTags($this->tags->getNames())); + } + + /** + * Get the tag set instance. + * + * @return \Illuminate\Cache\TagSet + */ + public function getTags() + { + return $this->tags; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/composer.json new file mode 100755 index 0000000..69f553f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cache/composer.json @@ -0,0 +1,47 @@ +{ + "name": "illuminate/cache", + "description": "The Illuminate Cache package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0" + }, + "provide": { + "psr/simple-cache-implementation": "1.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Cache\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "ext-memcached": "Required to use the memcache cache driver.", + "illuminate/database": "Required to use the database cache driver (^8.0).", + "illuminate/filesystem": "Required to use the file cache driver (^8.0).", + "illuminate/redis": "Required to use the redis cache driver (^8.0).", + "symfony/cache": "Required to PSR-6 cache bridge (^5.4)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Arr.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Arr.php new file mode 100644 index 0000000..fd7dca8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Arr.php @@ -0,0 +1,747 @@ +all(); + } elseif (! is_array($values)) { + continue; + } + + $results[] = $values; + } + + return array_merge([], ...$results); + } + + /** + * Cross join the given arrays, returning all possible permutations. + * + * @param iterable ...$arrays + * @return array + */ + public static function crossJoin(...$arrays) + { + $results = [[]]; + + foreach ($arrays as $index => $array) { + $append = []; + + foreach ($results as $product) { + foreach ($array as $item) { + $product[$index] = $item; + + $append[] = $product; + } + } + + $results = $append; + } + + return $results; + } + + /** + * Divide an array into two arrays. One with keys and the other with values. + * + * @param array $array + * @return array + */ + public static function divide($array) + { + return [array_keys($array), array_values($array)]; + } + + /** + * Flatten a multi-dimensional associative array with dots. + * + * @param iterable $array + * @param string $prepend + * @return array + */ + public static function dot($array, $prepend = '') + { + $results = []; + + foreach ($array as $key => $value) { + if (is_array($value) && ! empty($value)) { + $results = array_merge($results, static::dot($value, $prepend.$key.'.')); + } else { + $results[$prepend.$key] = $value; + } + } + + return $results; + } + + /** + * Convert a flatten "dot" notation array into an expanded array. + * + * @param iterable $array + * @return array + */ + public static function undot($array) + { + $results = []; + + foreach ($array as $key => $value) { + static::set($results, $key, $value); + } + + return $results; + } + + /** + * Get all of the given array except for a specified array of keys. + * + * @param array $array + * @param array|string $keys + * @return array + */ + public static function except($array, $keys) + { + static::forget($array, $keys); + + return $array; + } + + /** + * Determine if the given key exists in the provided array. + * + * @param \ArrayAccess|array $array + * @param string|int $key + * @return bool + */ + public static function exists($array, $key) + { + if ($array instanceof Enumerable) { + return $array->has($key); + } + + if ($array instanceof ArrayAccess) { + return $array->offsetExists($key); + } + + return array_key_exists($key, $array); + } + + /** + * Return the first element in an array passing a given truth test. + * + * @param iterable $array + * @param callable|null $callback + * @param mixed $default + * @return mixed + */ + public static function first($array, callable $callback = null, $default = null) + { + if (is_null($callback)) { + if (empty($array)) { + return value($default); + } + + foreach ($array as $item) { + return $item; + } + } + + foreach ($array as $key => $value) { + if ($callback($value, $key)) { + return $value; + } + } + + return value($default); + } + + /** + * Return the last element in an array passing a given truth test. + * + * @param array $array + * @param callable|null $callback + * @param mixed $default + * @return mixed + */ + public static function last($array, callable $callback = null, $default = null) + { + if (is_null($callback)) { + return empty($array) ? value($default) : end($array); + } + + return static::first(array_reverse($array, true), $callback, $default); + } + + /** + * Flatten a multi-dimensional array into a single level. + * + * @param iterable $array + * @param int $depth + * @return array + */ + public static function flatten($array, $depth = INF) + { + $result = []; + + foreach ($array as $item) { + $item = $item instanceof Collection ? $item->all() : $item; + + if (! is_array($item)) { + $result[] = $item; + } else { + $values = $depth === 1 + ? array_values($item) + : static::flatten($item, $depth - 1); + + foreach ($values as $value) { + $result[] = $value; + } + } + } + + return $result; + } + + /** + * Remove one or many array items from a given array using "dot" notation. + * + * @param array $array + * @param array|string $keys + * @return void + */ + public static function forget(&$array, $keys) + { + $original = &$array; + + $keys = (array) $keys; + + if (count($keys) === 0) { + return; + } + + foreach ($keys as $key) { + // if the exact key exists in the top-level, remove it + if (static::exists($array, $key)) { + unset($array[$key]); + + continue; + } + + $parts = explode('.', $key); + + // clean up before each pass + $array = &$original; + + while (count($parts) > 1) { + $part = array_shift($parts); + + if (isset($array[$part]) && is_array($array[$part])) { + $array = &$array[$part]; + } else { + continue 2; + } + } + + unset($array[array_shift($parts)]); + } + } + + /** + * Get an item from an array using "dot" notation. + * + * @param \ArrayAccess|array $array + * @param string|int|null $key + * @param mixed $default + * @return mixed + */ + public static function get($array, $key, $default = null) + { + if (! static::accessible($array)) { + return value($default); + } + + if (is_null($key)) { + return $array; + } + + if (static::exists($array, $key)) { + return $array[$key]; + } + + if (strpos($key, '.') === false) { + return $array[$key] ?? value($default); + } + + foreach (explode('.', $key) as $segment) { + if (static::accessible($array) && static::exists($array, $segment)) { + $array = $array[$segment]; + } else { + return value($default); + } + } + + return $array; + } + + /** + * Check if an item or items exist in an array using "dot" notation. + * + * @param \ArrayAccess|array $array + * @param string|array $keys + * @return bool + */ + public static function has($array, $keys) + { + $keys = (array) $keys; + + if (! $array || $keys === []) { + return false; + } + + foreach ($keys as $key) { + $subKeyArray = $array; + + if (static::exists($array, $key)) { + continue; + } + + foreach (explode('.', $key) as $segment) { + if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) { + $subKeyArray = $subKeyArray[$segment]; + } else { + return false; + } + } + } + + return true; + } + + /** + * Determine if any of the keys exist in an array using "dot" notation. + * + * @param \ArrayAccess|array $array + * @param string|array $keys + * @return bool + */ + public static function hasAny($array, $keys) + { + if (is_null($keys)) { + return false; + } + + $keys = (array) $keys; + + if (! $array) { + return false; + } + + if ($keys === []) { + return false; + } + + foreach ($keys as $key) { + if (static::has($array, $key)) { + return true; + } + } + + return false; + } + + /** + * Determines if an array is associative. + * + * An array is "associative" if it doesn't have sequential numerical keys beginning with zero. + * + * @param array $array + * @return bool + */ + public static function isAssoc(array $array) + { + $keys = array_keys($array); + + return array_keys($keys) !== $keys; + } + + /** + * Determines if an array is a list. + * + * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between. + * + * @param array $array + * @return bool + */ + public static function isList($array) + { + return ! self::isAssoc($array); + } + + /** + * Get a subset of the items from the given array. + * + * @param array $array + * @param array|string $keys + * @return array + */ + public static function only($array, $keys) + { + return array_intersect_key($array, array_flip((array) $keys)); + } + + /** + * Pluck an array of values from an array. + * + * @param iterable $array + * @param string|array|int|null $value + * @param string|array|null $key + * @return array + */ + public static function pluck($array, $value, $key = null) + { + $results = []; + + [$value, $key] = static::explodePluckParameters($value, $key); + + foreach ($array as $item) { + $itemValue = data_get($item, $value); + + // If the key is "null", we will just append the value to the array and keep + // looping. Otherwise we will key the array using the value of the key we + // received from the developer. Then we'll return the final array form. + if (is_null($key)) { + $results[] = $itemValue; + } else { + $itemKey = data_get($item, $key); + + if (is_object($itemKey) && method_exists($itemKey, '__toString')) { + $itemKey = (string) $itemKey; + } + + $results[$itemKey] = $itemValue; + } + } + + return $results; + } + + /** + * Explode the "value" and "key" arguments passed to "pluck". + * + * @param string|array $value + * @param string|array|null $key + * @return array + */ + protected static function explodePluckParameters($value, $key) + { + $value = is_string($value) ? explode('.', $value) : $value; + + $key = is_null($key) || is_array($key) ? $key : explode('.', $key); + + return [$value, $key]; + } + + /** + * Push an item onto the beginning of an array. + * + * @param array $array + * @param mixed $value + * @param mixed $key + * @return array + */ + public static function prepend($array, $value, $key = null) + { + if (func_num_args() == 2) { + array_unshift($array, $value); + } else { + $array = [$key => $value] + $array; + } + + return $array; + } + + /** + * Get a value from the array, and remove it. + * + * @param array $array + * @param string|int $key + * @param mixed $default + * @return mixed + */ + public static function pull(&$array, $key, $default = null) + { + $value = static::get($array, $key, $default); + + static::forget($array, $key); + + return $value; + } + + /** + * Convert the array into a query string. + * + * @param array $array + * @return string + */ + public static function query($array) + { + return http_build_query($array, '', '&', PHP_QUERY_RFC3986); + } + + /** + * Get one or a specified number of random values from an array. + * + * @param array $array + * @param int|null $number + * @param bool|false $preserveKeys + * @return mixed + * + * @throws \InvalidArgumentException + */ + public static function random($array, $number = null, $preserveKeys = false) + { + $requested = is_null($number) ? 1 : $number; + + $count = count($array); + + if ($requested > $count) { + throw new InvalidArgumentException( + "You requested {$requested} items, but there are only {$count} items available." + ); + } + + if (is_null($number)) { + return $array[array_rand($array)]; + } + + if ((int) $number === 0) { + return []; + } + + $keys = array_rand($array, $number); + + $results = []; + + if ($preserveKeys) { + foreach ((array) $keys as $key) { + $results[$key] = $array[$key]; + } + } else { + foreach ((array) $keys as $key) { + $results[] = $array[$key]; + } + } + + return $results; + } + + /** + * Set an array item to a given value using "dot" notation. + * + * If no key is given to the method, the entire array will be replaced. + * + * @param array $array + * @param string|null $key + * @param mixed $value + * @return array + */ + public static function set(&$array, $key, $value) + { + if (is_null($key)) { + return $array = $value; + } + + $keys = explode('.', $key); + + foreach ($keys as $i => $key) { + if (count($keys) === 1) { + break; + } + + unset($keys[$i]); + + // If the key doesn't exist at this depth, we will just create an empty array + // to hold the next value, allowing us to create the arrays to hold final + // values at the correct depth. Then we'll keep digging into the array. + if (! isset($array[$key]) || ! is_array($array[$key])) { + $array[$key] = []; + } + + $array = &$array[$key]; + } + + $array[array_shift($keys)] = $value; + + return $array; + } + + /** + * Shuffle the given array and return the result. + * + * @param array $array + * @param int|null $seed + * @return array + */ + public static function shuffle($array, $seed = null) + { + if (is_null($seed)) { + shuffle($array); + } else { + mt_srand($seed); + shuffle($array); + mt_srand(); + } + + return $array; + } + + /** + * Sort the array using the given callback or "dot" notation. + * + * @param array $array + * @param callable|array|string|null $callback + * @return array + */ + public static function sort($array, $callback = null) + { + return Collection::make($array)->sortBy($callback)->all(); + } + + /** + * Recursively sort an array by keys and values. + * + * @param array $array + * @param int $options + * @param bool $descending + * @return array + */ + public static function sortRecursive($array, $options = SORT_REGULAR, $descending = false) + { + foreach ($array as &$value) { + if (is_array($value)) { + $value = static::sortRecursive($value, $options, $descending); + } + } + + if (static::isAssoc($array)) { + $descending + ? krsort($array, $options) + : ksort($array, $options); + } else { + $descending + ? rsort($array, $options) + : sort($array, $options); + } + + return $array; + } + + /** + * Conditionally compile classes from an array into a CSS class list. + * + * @param array $array + * @return string + */ + public static function toCssClasses($array) + { + $classList = static::wrap($array); + + $classes = []; + + foreach ($classList as $class => $constraint) { + if (is_numeric($class)) { + $classes[] = $constraint; + } elseif ($constraint) { + $classes[] = $class; + } + } + + return implode(' ', $classes); + } + + /** + * Filter the array using the given callback. + * + * @param array $array + * @param callable $callback + * @return array + */ + public static function where($array, callable $callback) + { + return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH); + } + + /** + * Filter items where the value is not null. + * + * @param array $array + * @return array + */ + public static function whereNotNull($array) + { + return static::where($array, function ($value) { + return ! is_null($value); + }); + } + + /** + * If the given value is not an array and not null, wrap it in one. + * + * @param mixed $value + * @return array + */ + public static function wrap($value) + { + if (is_null($value)) { + return []; + } + + return is_array($value) ? $value : [$value]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Collection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Collection.php new file mode 100644 index 0000000..61a4884 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Collection.php @@ -0,0 +1,1672 @@ +items = $this->getArrayableItems($items); + } + + /** + * Create a collection with the given range. + * + * @param int $from + * @param int $to + * @return static + */ + public static function range($from, $to) + { + return new static(range($from, $to)); + } + + /** + * Get all of the items in the collection. + * + * @return array + */ + public function all() + { + return $this->items; + } + + /** + * Get a lazy collection for the items in this collection. + * + * @return \Illuminate\Support\LazyCollection + */ + public function lazy() + { + return new LazyCollection($this->items); + } + + /** + * Get the average value of a given key. + * + * @param callable|string|null $callback + * @return mixed + */ + public function avg($callback = null) + { + $callback = $this->valueRetriever($callback); + + $items = $this->map(function ($value) use ($callback) { + return $callback($value); + })->filter(function ($value) { + return ! is_null($value); + }); + + if ($count = $items->count()) { + return $items->sum() / $count; + } + } + + /** + * Get the median of a given key. + * + * @param string|array|null $key + * @return mixed + */ + public function median($key = null) + { + $values = (isset($key) ? $this->pluck($key) : $this) + ->filter(function ($item) { + return ! is_null($item); + })->sort()->values(); + + $count = $values->count(); + + if ($count === 0) { + return; + } + + $middle = (int) ($count / 2); + + if ($count % 2) { + return $values->get($middle); + } + + return (new static([ + $values->get($middle - 1), $values->get($middle), + ]))->average(); + } + + /** + * Get the mode of a given key. + * + * @param string|array|null $key + * @return array|null + */ + public function mode($key = null) + { + if ($this->count() === 0) { + return; + } + + $collection = isset($key) ? $this->pluck($key) : $this; + + $counts = new static; + + $collection->each(function ($value) use ($counts) { + $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1; + }); + + $sorted = $counts->sort(); + + $highestValue = $sorted->last(); + + return $sorted->filter(function ($value) use ($highestValue) { + return $value == $highestValue; + })->sort()->keys()->all(); + } + + /** + * Collapse the collection of items into a single array. + * + * @return static + */ + public function collapse() + { + return new static(Arr::collapse($this->items)); + } + + /** + * Determine if an item exists in the collection. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function contains($key, $operator = null, $value = null) + { + if (func_num_args() === 1) { + if ($this->useAsCallable($key)) { + $placeholder = new stdClass; + + return $this->first($key, $placeholder) !== $placeholder; + } + + return in_array($key, $this->items); + } + + return $this->contains($this->operatorForWhere(...func_get_args())); + } + + /** + * Determine if an item is not contained in the collection. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function doesntContain($key, $operator = null, $value = null) + { + return ! $this->contains(...func_get_args()); + } + + /** + * Cross join with the given lists, returning all possible permutations. + * + * @param mixed ...$lists + * @return static + */ + public function crossJoin(...$lists) + { + return new static(Arr::crossJoin( + $this->items, ...array_map([$this, 'getArrayableItems'], $lists) + )); + } + + /** + * Get the items in the collection that are not present in the given items. + * + * @param mixed $items + * @return static + */ + public function diff($items) + { + return new static(array_diff($this->items, $this->getArrayableItems($items))); + } + + /** + * Get the items in the collection that are not present in the given items, using the callback. + * + * @param mixed $items + * @param callable $callback + * @return static + */ + public function diffUsing($items, callable $callback) + { + return new static(array_udiff($this->items, $this->getArrayableItems($items), $callback)); + } + + /** + * Get the items in the collection whose keys and values are not present in the given items. + * + * @param mixed $items + * @return static + */ + public function diffAssoc($items) + { + return new static(array_diff_assoc($this->items, $this->getArrayableItems($items))); + } + + /** + * Get the items in the collection whose keys and values are not present in the given items, using the callback. + * + * @param mixed $items + * @param callable $callback + * @return static + */ + public function diffAssocUsing($items, callable $callback) + { + return new static(array_diff_uassoc($this->items, $this->getArrayableItems($items), $callback)); + } + + /** + * Get the items in the collection whose keys are not present in the given items. + * + * @param mixed $items + * @return static + */ + public function diffKeys($items) + { + return new static(array_diff_key($this->items, $this->getArrayableItems($items))); + } + + /** + * Get the items in the collection whose keys are not present in the given items, using the callback. + * + * @param mixed $items + * @param callable $callback + * @return static + */ + public function diffKeysUsing($items, callable $callback) + { + return new static(array_diff_ukey($this->items, $this->getArrayableItems($items), $callback)); + } + + /** + * Retrieve duplicate items from the collection. + * + * @param callable|string|null $callback + * @param bool $strict + * @return static + */ + public function duplicates($callback = null, $strict = false) + { + $items = $this->map($this->valueRetriever($callback)); + + $uniqueItems = $items->unique(null, $strict); + + $compare = $this->duplicateComparator($strict); + + $duplicates = new static; + + foreach ($items as $key => $value) { + if ($uniqueItems->isNotEmpty() && $compare($value, $uniqueItems->first())) { + $uniqueItems->shift(); + } else { + $duplicates[$key] = $value; + } + } + + return $duplicates; + } + + /** + * Retrieve duplicate items from the collection using strict comparison. + * + * @param callable|string|null $callback + * @return static + */ + public function duplicatesStrict($callback = null) + { + return $this->duplicates($callback, true); + } + + /** + * Get the comparison function to detect duplicates. + * + * @param bool $strict + * @return \Closure + */ + protected function duplicateComparator($strict) + { + if ($strict) { + return function ($a, $b) { + return $a === $b; + }; + } + + return function ($a, $b) { + return $a == $b; + }; + } + + /** + * Get all items except for those with the specified keys. + * + * @param \Illuminate\Support\Collection|mixed $keys + * @return static + */ + public function except($keys) + { + if ($keys instanceof Enumerable) { + $keys = $keys->all(); + } elseif (! is_array($keys)) { + $keys = func_get_args(); + } + + return new static(Arr::except($this->items, $keys)); + } + + /** + * Run a filter over each of the items. + * + * @param callable|null $callback + * @return static + */ + public function filter(callable $callback = null) + { + if ($callback) { + return new static(Arr::where($this->items, $callback)); + } + + return new static(array_filter($this->items)); + } + + /** + * Get the first item from the collection passing the given truth test. + * + * @param callable|null $callback + * @param mixed $default + * @return mixed + */ + public function first(callable $callback = null, $default = null) + { + return Arr::first($this->items, $callback, $default); + } + + /** + * Get a flattened array of the items in the collection. + * + * @param int $depth + * @return static + */ + public function flatten($depth = INF) + { + return new static(Arr::flatten($this->items, $depth)); + } + + /** + * Flip the items in the collection. + * + * @return static + */ + public function flip() + { + return new static(array_flip($this->items)); + } + + /** + * Remove an item from the collection by key. + * + * @param string|int|array $keys + * @return $this + */ + public function forget($keys) + { + foreach ((array) $keys as $key) { + $this->offsetUnset($key); + } + + return $this; + } + + /** + * Get an item from the collection by key. + * + * @param mixed $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + if (array_key_exists($key, $this->items)) { + return $this->items[$key]; + } + + return value($default); + } + + /** + * Get an item from the collection by key or add it to collection if it does not exist. + * + * @param mixed $key + * @param mixed $value + * @return mixed + */ + public function getOrPut($key, $value) + { + if (array_key_exists($key, $this->items)) { + return $this->items[$key]; + } + + $this->offsetSet($key, $value = value($value)); + + return $value; + } + + /** + * Group an associative array by a field or using a callback. + * + * @param array|callable|string $groupBy + * @param bool $preserveKeys + * @return static + */ + public function groupBy($groupBy, $preserveKeys = false) + { + if (! $this->useAsCallable($groupBy) && is_array($groupBy)) { + $nextGroups = $groupBy; + + $groupBy = array_shift($nextGroups); + } + + $groupBy = $this->valueRetriever($groupBy); + + $results = []; + + foreach ($this->items as $key => $value) { + $groupKeys = $groupBy($value, $key); + + if (! is_array($groupKeys)) { + $groupKeys = [$groupKeys]; + } + + foreach ($groupKeys as $groupKey) { + $groupKey = is_bool($groupKey) ? (int) $groupKey : $groupKey; + + if (! array_key_exists($groupKey, $results)) { + $results[$groupKey] = new static; + } + + $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value); + } + } + + $result = new static($results); + + if (! empty($nextGroups)) { + return $result->map->groupBy($nextGroups, $preserveKeys); + } + + return $result; + } + + /** + * Key an associative array by a field or using a callback. + * + * @param callable|string $keyBy + * @return static + */ + public function keyBy($keyBy) + { + $keyBy = $this->valueRetriever($keyBy); + + $results = []; + + foreach ($this->items as $key => $item) { + $resolvedKey = $keyBy($item, $key); + + if (is_object($resolvedKey)) { + $resolvedKey = (string) $resolvedKey; + } + + $results[$resolvedKey] = $item; + } + + return new static($results); + } + + /** + * Determine if an item exists in the collection by key. + * + * @param mixed $key + * @return bool + */ + public function has($key) + { + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $value) { + if (! array_key_exists($value, $this->items)) { + return false; + } + } + + return true; + } + + /** + * Determine if any of the keys exist in the collection. + * + * @param mixed $key + * @return bool + */ + public function hasAny($key) + { + if ($this->isEmpty()) { + return false; + } + + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $value) { + if ($this->has($value)) { + return true; + } + } + + return false; + } + + /** + * Concatenate values of a given key as a string. + * + * @param string $value + * @param string|null $glue + * @return string + */ + public function implode($value, $glue = null) + { + $first = $this->first(); + + if (is_array($first) || (is_object($first) && ! $first instanceof Stringable)) { + return implode($glue ?? '', $this->pluck($value)->all()); + } + + return implode($value ?? '', $this->items); + } + + /** + * Intersect the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function intersect($items) + { + return new static(array_intersect($this->items, $this->getArrayableItems($items))); + } + + /** + * Intersect the collection with the given items by key. + * + * @param mixed $items + * @return static + */ + public function intersectByKeys($items) + { + return new static(array_intersect_key( + $this->items, $this->getArrayableItems($items) + )); + } + + /** + * Determine if the collection is empty or not. + * + * @return bool + */ + public function isEmpty() + { + return empty($this->items); + } + + /** + * Determine if the collection contains a single item. + * + * @return bool + */ + public function containsOneItem() + { + return $this->count() === 1; + } + + /** + * Join all items from the collection using a string. The final items can use a separate glue string. + * + * @param string $glue + * @param string $finalGlue + * @return string + */ + public function join($glue, $finalGlue = '') + { + if ($finalGlue === '') { + return $this->implode($glue); + } + + $count = $this->count(); + + if ($count === 0) { + return ''; + } + + if ($count === 1) { + return $this->last(); + } + + $collection = new static($this->items); + + $finalItem = $collection->pop(); + + return $collection->implode($glue).$finalGlue.$finalItem; + } + + /** + * Get the keys of the collection items. + * + * @return static + */ + public function keys() + { + return new static(array_keys($this->items)); + } + + /** + * Get the last item from the collection. + * + * @param callable|null $callback + * @param mixed $default + * @return mixed + */ + public function last(callable $callback = null, $default = null) + { + return Arr::last($this->items, $callback, $default); + } + + /** + * Get the values of a given key. + * + * @param string|array|int|null $value + * @param string|null $key + * @return static + */ + public function pluck($value, $key = null) + { + return new static(Arr::pluck($this->items, $value, $key)); + } + + /** + * Run a map over each of the items. + * + * @param callable $callback + * @return static + */ + public function map(callable $callback) + { + $keys = array_keys($this->items); + + $items = array_map($callback, $this->items, $keys); + + return new static(array_combine($keys, $items)); + } + + /** + * Run a dictionary map over the items. + * + * The callback should return an associative array with a single key/value pair. + * + * @param callable $callback + * @return static + */ + public function mapToDictionary(callable $callback) + { + $dictionary = []; + + foreach ($this->items as $key => $item) { + $pair = $callback($item, $key); + + $key = key($pair); + + $value = reset($pair); + + if (! isset($dictionary[$key])) { + $dictionary[$key] = []; + } + + $dictionary[$key][] = $value; + } + + return new static($dictionary); + } + + /** + * Run an associative map over each of the items. + * + * The callback should return an associative array with a single key/value pair. + * + * @param callable $callback + * @return static + */ + public function mapWithKeys(callable $callback) + { + $result = []; + + foreach ($this->items as $key => $value) { + $assoc = $callback($value, $key); + + foreach ($assoc as $mapKey => $mapValue) { + $result[$mapKey] = $mapValue; + } + } + + return new static($result); + } + + /** + * Merge the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function merge($items) + { + return new static(array_merge($this->items, $this->getArrayableItems($items))); + } + + /** + * Recursively merge the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function mergeRecursive($items) + { + return new static(array_merge_recursive($this->items, $this->getArrayableItems($items))); + } + + /** + * Create a collection by using this collection for keys and another for its values. + * + * @param mixed $values + * @return static + */ + public function combine($values) + { + return new static(array_combine($this->all(), $this->getArrayableItems($values))); + } + + /** + * Union the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function union($items) + { + return new static($this->items + $this->getArrayableItems($items)); + } + + /** + * Create a new collection consisting of every n-th element. + * + * @param int $step + * @param int $offset + * @return static + */ + public function nth($step, $offset = 0) + { + $new = []; + + $position = 0; + + foreach ($this->slice($offset)->items as $item) { + if ($position % $step === 0) { + $new[] = $item; + } + + $position++; + } + + return new static($new); + } + + /** + * Get the items with the specified keys. + * + * @param mixed $keys + * @return static + */ + public function only($keys) + { + if (is_null($keys)) { + return new static($this->items); + } + + if ($keys instanceof Enumerable) { + $keys = $keys->all(); + } + + $keys = is_array($keys) ? $keys : func_get_args(); + + return new static(Arr::only($this->items, $keys)); + } + + /** + * Get and remove the last N items from the collection. + * + * @param int $count + * @return mixed + */ + public function pop($count = 1) + { + if ($count === 1) { + return array_pop($this->items); + } + + if ($this->isEmpty()) { + return new static; + } + + $results = []; + + $collectionCount = $this->count(); + + foreach (range(1, min($count, $collectionCount)) as $item) { + array_push($results, array_pop($this->items)); + } + + return new static($results); + } + + /** + * Push an item onto the beginning of the collection. + * + * @param mixed $value + * @param mixed $key + * @return $this + */ + public function prepend($value, $key = null) + { + $this->items = Arr::prepend($this->items, ...func_get_args()); + + return $this; + } + + /** + * Push one or more items onto the end of the collection. + * + * @param mixed $values + * @return $this + */ + public function push(...$values) + { + foreach ($values as $value) { + $this->items[] = $value; + } + + return $this; + } + + /** + * Push all of the given items onto the collection. + * + * @param iterable $source + * @return static + */ + public function concat($source) + { + $result = new static($this); + + foreach ($source as $item) { + $result->push($item); + } + + return $result; + } + + /** + * Get and remove an item from the collection. + * + * @param mixed $key + * @param mixed $default + * @return mixed + */ + public function pull($key, $default = null) + { + return Arr::pull($this->items, $key, $default); + } + + /** + * Put an item in the collection by key. + * + * @param mixed $key + * @param mixed $value + * @return $this + */ + public function put($key, $value) + { + $this->offsetSet($key, $value); + + return $this; + } + + /** + * Get one or a specified number of items randomly from the collection. + * + * @param int|null $number + * @return static|mixed + * + * @throws \InvalidArgumentException + */ + public function random($number = null) + { + if (is_null($number)) { + return Arr::random($this->items); + } + + return new static(Arr::random($this->items, $number)); + } + + /** + * Replace the collection items with the given items. + * + * @param mixed $items + * @return static + */ + public function replace($items) + { + return new static(array_replace($this->items, $this->getArrayableItems($items))); + } + + /** + * Recursively replace the collection items with the given items. + * + * @param mixed $items + * @return static + */ + public function replaceRecursive($items) + { + return new static(array_replace_recursive($this->items, $this->getArrayableItems($items))); + } + + /** + * Reverse items order. + * + * @return static + */ + public function reverse() + { + return new static(array_reverse($this->items, true)); + } + + /** + * Search the collection for a given value and return the corresponding key if successful. + * + * @param mixed $value + * @param bool $strict + * @return mixed + */ + public function search($value, $strict = false) + { + if (! $this->useAsCallable($value)) { + return array_search($value, $this->items, $strict); + } + + foreach ($this->items as $key => $item) { + if ($value($item, $key)) { + return $key; + } + } + + return false; + } + + /** + * Get and remove the first N items from the collection. + * + * @param int $count + * @return mixed + */ + public function shift($count = 1) + { + if ($count === 1) { + return array_shift($this->items); + } + + if ($this->isEmpty()) { + return new static; + } + + $results = []; + + $collectionCount = $this->count(); + + foreach (range(1, min($count, $collectionCount)) as $item) { + array_push($results, array_shift($this->items)); + } + + return new static($results); + } + + /** + * Shuffle the items in the collection. + * + * @param int|null $seed + * @return static + */ + public function shuffle($seed = null) + { + return new static(Arr::shuffle($this->items, $seed)); + } + + /** + * Create chunks representing a "sliding window" view of the items in the collection. + * + * @param int $size + * @param int $step + * @return static + */ + public function sliding($size = 2, $step = 1) + { + $chunks = floor(($this->count() - $size) / $step) + 1; + + return static::times($chunks, function ($number) use ($size, $step) { + return $this->slice(($number - 1) * $step, $size); + }); + } + + /** + * Skip the first {$count} items. + * + * @param int $count + * @return static + */ + public function skip($count) + { + return $this->slice($count); + } + + /** + * Skip items in the collection until the given condition is met. + * + * @param mixed $value + * @return static + */ + public function skipUntil($value) + { + return new static($this->lazy()->skipUntil($value)->all()); + } + + /** + * Skip items in the collection while the given condition is met. + * + * @param mixed $value + * @return static + */ + public function skipWhile($value) + { + return new static($this->lazy()->skipWhile($value)->all()); + } + + /** + * Slice the underlying collection array. + * + * @param int $offset + * @param int|null $length + * @return static + */ + public function slice($offset, $length = null) + { + return new static(array_slice($this->items, $offset, $length, true)); + } + + /** + * Split a collection into a certain number of groups. + * + * @param int $numberOfGroups + * @return static + */ + public function split($numberOfGroups) + { + if ($this->isEmpty()) { + return new static; + } + + $groups = new static; + + $groupSize = floor($this->count() / $numberOfGroups); + + $remain = $this->count() % $numberOfGroups; + + $start = 0; + + for ($i = 0; $i < $numberOfGroups; $i++) { + $size = $groupSize; + + if ($i < $remain) { + $size++; + } + + if ($size) { + $groups->push(new static(array_slice($this->items, $start, $size))); + + $start += $size; + } + } + + return $groups; + } + + /** + * Split a collection into a certain number of groups, and fill the first groups completely. + * + * @param int $numberOfGroups + * @return static + */ + public function splitIn($numberOfGroups) + { + return $this->chunk(ceil($this->count() / $numberOfGroups)); + } + + /** + * Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return mixed + * + * @throws \Illuminate\Support\ItemNotFoundException + * @throws \Illuminate\Support\MultipleItemsFoundException + */ + public function sole($key = null, $operator = null, $value = null) + { + $filter = func_num_args() > 1 + ? $this->operatorForWhere(...func_get_args()) + : $key; + + $items = $this->when($filter)->filter($filter); + + if ($items->isEmpty()) { + throw new ItemNotFoundException; + } + + if ($items->count() > 1) { + throw new MultipleItemsFoundException; + } + + return $items->first(); + } + + /** + * Get the first item in the collection but throw an exception if no matching items exist. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return mixed + * + * @throws \Illuminate\Support\ItemNotFoundException + */ + public function firstOrFail($key = null, $operator = null, $value = null) + { + $filter = func_num_args() > 1 + ? $this->operatorForWhere(...func_get_args()) + : $key; + + $placeholder = new stdClass(); + + $item = $this->first($filter, $placeholder); + + if ($item === $placeholder) { + throw new ItemNotFoundException; + } + + return $item; + } + + /** + * Chunk the collection into chunks of the given size. + * + * @param int $size + * @return static + */ + public function chunk($size) + { + if ($size <= 0) { + return new static; + } + + $chunks = []; + + foreach (array_chunk($this->items, $size, true) as $chunk) { + $chunks[] = new static($chunk); + } + + return new static($chunks); + } + + /** + * Chunk the collection into chunks with a callback. + * + * @param callable $callback + * @return static + */ + public function chunkWhile(callable $callback) + { + return new static( + $this->lazy()->chunkWhile($callback)->mapInto(static::class) + ); + } + + /** + * Sort through each item with a callback. + * + * @param callable|int|null $callback + * @return static + */ + public function sort($callback = null) + { + $items = $this->items; + + $callback && is_callable($callback) + ? uasort($items, $callback) + : asort($items, $callback ?? SORT_REGULAR); + + return new static($items); + } + + /** + * Sort items in descending order. + * + * @param int $options + * @return static + */ + public function sortDesc($options = SORT_REGULAR) + { + $items = $this->items; + + arsort($items, $options); + + return new static($items); + } + + /** + * Sort the collection using the given callback. + * + * @param callable|array|string $callback + * @param int $options + * @param bool $descending + * @return static + */ + public function sortBy($callback, $options = SORT_REGULAR, $descending = false) + { + if (is_array($callback) && ! is_callable($callback)) { + return $this->sortByMany($callback); + } + + $results = []; + + $callback = $this->valueRetriever($callback); + + // First we will loop through the items and get the comparator from a callback + // function which we were given. Then, we will sort the returned values and + // grab all the corresponding values for the sorted keys from this array. + foreach ($this->items as $key => $value) { + $results[$key] = $callback($value, $key); + } + + $descending ? arsort($results, $options) + : asort($results, $options); + + // Once we have sorted all of the keys in the array, we will loop through them + // and grab the corresponding model so we can set the underlying items list + // to the sorted version. Then we'll just return the collection instance. + foreach (array_keys($results) as $key) { + $results[$key] = $this->items[$key]; + } + + return new static($results); + } + + /** + * Sort the collection using multiple comparisons. + * + * @param array $comparisons + * @return static + */ + protected function sortByMany(array $comparisons = []) + { + $items = $this->items; + + usort($items, function ($a, $b) use ($comparisons) { + foreach ($comparisons as $comparison) { + $comparison = Arr::wrap($comparison); + + $prop = $comparison[0]; + + $ascending = Arr::get($comparison, 1, true) === true || + Arr::get($comparison, 1, true) === 'asc'; + + $result = 0; + + if (! is_string($prop) && is_callable($prop)) { + $result = $prop($a, $b); + } else { + $values = [data_get($a, $prop), data_get($b, $prop)]; + + if (! $ascending) { + $values = array_reverse($values); + } + + $result = $values[0] <=> $values[1]; + } + + if ($result === 0) { + continue; + } + + return $result; + } + }); + + return new static($items); + } + + /** + * Sort the collection in descending order using the given callback. + * + * @param callable|string $callback + * @param int $options + * @return static + */ + public function sortByDesc($callback, $options = SORT_REGULAR) + { + return $this->sortBy($callback, $options, true); + } + + /** + * Sort the collection keys. + * + * @param int $options + * @param bool $descending + * @return static + */ + public function sortKeys($options = SORT_REGULAR, $descending = false) + { + $items = $this->items; + + $descending ? krsort($items, $options) : ksort($items, $options); + + return new static($items); + } + + /** + * Sort the collection keys in descending order. + * + * @param int $options + * @return static + */ + public function sortKeysDesc($options = SORT_REGULAR) + { + return $this->sortKeys($options, true); + } + + /** + * Sort the collection keys using a callback. + * + * @param callable $callback + * @return static + */ + public function sortKeysUsing(callable $callback) + { + $items = $this->items; + + uksort($items, $callback); + + return new static($items); + } + + /** + * Splice a portion of the underlying collection array. + * + * @param int $offset + * @param int|null $length + * @param mixed $replacement + * @return static + */ + public function splice($offset, $length = null, $replacement = []) + { + if (func_num_args() === 1) { + return new static(array_splice($this->items, $offset)); + } + + return new static(array_splice($this->items, $offset, $length, $this->getArrayableItems($replacement))); + } + + /** + * Take the first or last {$limit} items. + * + * @param int $limit + * @return static + */ + public function take($limit) + { + if ($limit < 0) { + return $this->slice($limit, abs($limit)); + } + + return $this->slice(0, $limit); + } + + /** + * Take items in the collection until the given condition is met. + * + * @param mixed $value + * @return static + */ + public function takeUntil($value) + { + return new static($this->lazy()->takeUntil($value)->all()); + } + + /** + * Take items in the collection while the given condition is met. + * + * @param mixed $value + * @return static + */ + public function takeWhile($value) + { + return new static($this->lazy()->takeWhile($value)->all()); + } + + /** + * Transform each item in the collection using a callback. + * + * @param callable $callback + * @return $this + */ + public function transform(callable $callback) + { + $this->items = $this->map($callback)->all(); + + return $this; + } + + /** + * Convert a flatten "dot" notation array into an expanded array. + * + * @return static + */ + public function undot() + { + return new static(Arr::undot($this->all())); + } + + /** + * Return only unique items from the collection array. + * + * @param string|callable|null $key + * @param bool $strict + * @return static + */ + public function unique($key = null, $strict = false) + { + if (is_null($key) && $strict === false) { + return new static(array_unique($this->items, SORT_REGULAR)); + } + + $callback = $this->valueRetriever($key); + + $exists = []; + + return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) { + if (in_array($id = $callback($item, $key), $exists, $strict)) { + return true; + } + + $exists[] = $id; + }); + } + + /** + * Reset the keys on the underlying array. + * + * @return static + */ + public function values() + { + return new static(array_values($this->items)); + } + + /** + * Zip the collection together with one or more arrays. + * + * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]); + * => [[1, 4], [2, 5], [3, 6]] + * + * @param mixed ...$items + * @return static + */ + public function zip($items) + { + $arrayableItems = array_map(function ($items) { + return $this->getArrayableItems($items); + }, func_get_args()); + + $params = array_merge([function () { + return new static(func_get_args()); + }, $this->items], $arrayableItems); + + return new static(array_map(...$params)); + } + + /** + * Pad collection to the specified length with a value. + * + * @param int $size + * @param mixed $value + * @return static + */ + public function pad($size, $value) + { + return new static(array_pad($this->items, $size, $value)); + } + + /** + * Get an iterator for the items. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new ArrayIterator($this->items); + } + + /** + * Count the number of items in the collection. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return count($this->items); + } + + /** + * Count the number of items in the collection by a field or using a callback. + * + * @param callable|string $countBy + * @return static + */ + public function countBy($countBy = null) + { + return new static($this->lazy()->countBy($countBy)->all()); + } + + /** + * Add an item to the collection. + * + * @param mixed $item + * @return $this + */ + public function add($item) + { + $this->items[] = $item; + + return $this; + } + + /** + * Get a base Support collection instance from this collection. + * + * @return \Illuminate\Support\Collection + */ + public function toBase() + { + return new self($this); + } + + /** + * Determine if an item exists at an offset. + * + * @param mixed $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return isset($this->items[$key]); + } + + /** + * Get an item at a given offset. + * + * @param mixed $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->items[$key]; + } + + /** + * Set the item at a given offset. + * + * @param mixed $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + if (is_null($key)) { + $this->items[] = $value; + } else { + $this->items[$key] = $value; + } + } + + /** + * Unset the item at a given offset. + * + * @param mixed $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + unset($this->items[$key]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Enumerable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Enumerable.php new file mode 100644 index 0000000..261a0c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/Enumerable.php @@ -0,0 +1,1027 @@ +zip([4, 5, 6]); + * => [[1, 4], [2, 5], [3, 6]] + * + * @param mixed ...$items + * @return static + */ + public function zip($items); + + /** + * Collect the values into a collection. + * + * @return \Illuminate\Support\Collection + */ + public function collect(); + + /** + * Convert the collection to its string representation. + * + * @return string + */ + public function __toString(); + + /** + * Add a method to the list of proxied methods. + * + * @param string $method + * @return void + */ + public static function proxy($method); + + /** + * Dynamically access collection proxies. + * + * @param string $key + * @return mixed + * + * @throws \Exception + */ + public function __get($key); +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/HigherOrderCollectionProxy.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/HigherOrderCollectionProxy.php new file mode 100644 index 0000000..106356c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/HigherOrderCollectionProxy.php @@ -0,0 +1,63 @@ +method = $method; + $this->collection = $collection; + } + + /** + * Proxy accessing an attribute onto the collection items. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->collection->{$this->method}(function ($value) use ($key) { + return is_array($value) ? $value[$key] : $value->{$key}; + }); + } + + /** + * Proxy a method call onto the collection items. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->collection->{$this->method}(function ($value) use ($method, $parameters) { + return $value->{$method}(...$parameters); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/HigherOrderWhenProxy.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/HigherOrderWhenProxy.php new file mode 100644 index 0000000..6653c03 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/HigherOrderWhenProxy.php @@ -0,0 +1,63 @@ +condition = $condition; + $this->collection = $collection; + } + + /** + * Proxy accessing an attribute onto the collection. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->condition + ? $this->collection->{$key} + : $this->collection; + } + + /** + * Proxy a method call onto the collection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->condition + ? $this->collection->{$method}(...$parameters) + : $this->collection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/ItemNotFoundException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/ItemNotFoundException.php new file mode 100644 index 0000000..05a51d9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/ItemNotFoundException.php @@ -0,0 +1,9 @@ +source = $source; + } elseif (is_null($source)) { + $this->source = static::empty(); + } else { + $this->source = $this->getArrayableItems($source); + } + } + + /** + * Create a collection with the given range. + * + * @param int $from + * @param int $to + * @return static + */ + public static function range($from, $to) + { + return new static(function () use ($from, $to) { + if ($from <= $to) { + for (; $from <= $to; $from++) { + yield $from; + } + } else { + for (; $from >= $to; $from--) { + yield $from; + } + } + }); + } + + /** + * Get all items in the enumerable. + * + * @return array + */ + public function all() + { + if (is_array($this->source)) { + return $this->source; + } + + return iterator_to_array($this->getIterator()); + } + + /** + * Eager load all items into a new lazy collection backed by an array. + * + * @return static + */ + public function eager() + { + return new static($this->all()); + } + + /** + * Cache values as they're enumerated. + * + * @return static + */ + public function remember() + { + $iterator = $this->getIterator(); + + $iteratorIndex = 0; + + $cache = []; + + return new static(function () use ($iterator, &$iteratorIndex, &$cache) { + for ($index = 0; true; $index++) { + if (array_key_exists($index, $cache)) { + yield $cache[$index][0] => $cache[$index][1]; + + continue; + } + + if ($iteratorIndex < $index) { + $iterator->next(); + + $iteratorIndex++; + } + + if (! $iterator->valid()) { + break; + } + + $cache[$index] = [$iterator->key(), $iterator->current()]; + + yield $cache[$index][0] => $cache[$index][1]; + } + }); + } + + /** + * Get the average value of a given key. + * + * @param callable|string|null $callback + * @return mixed + */ + public function avg($callback = null) + { + return $this->collect()->avg($callback); + } + + /** + * Get the median of a given key. + * + * @param string|array|null $key + * @return mixed + */ + public function median($key = null) + { + return $this->collect()->median($key); + } + + /** + * Get the mode of a given key. + * + * @param string|array|null $key + * @return array|null + */ + public function mode($key = null) + { + return $this->collect()->mode($key); + } + + /** + * Collapse the collection of items into a single array. + * + * @return static + */ + public function collapse() + { + return new static(function () { + foreach ($this as $values) { + if (is_array($values) || $values instanceof Enumerable) { + foreach ($values as $value) { + yield $value; + } + } + } + }); + } + + /** + * Determine if an item exists in the enumerable. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function contains($key, $operator = null, $value = null) + { + if (func_num_args() === 1 && $this->useAsCallable($key)) { + $placeholder = new stdClass; + + return $this->first($key, $placeholder) !== $placeholder; + } + + if (func_num_args() === 1) { + $needle = $key; + + foreach ($this as $value) { + if ($value == $needle) { + return true; + } + } + + return false; + } + + return $this->contains($this->operatorForWhere(...func_get_args())); + } + + /** + * Determine if an item is not contained in the enumerable. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function doesntContain($key, $operator = null, $value = null) + { + return ! $this->contains(...func_get_args()); + } + + /** + * Cross join the given iterables, returning all possible permutations. + * + * @param array ...$arrays + * @return static + */ + public function crossJoin(...$arrays) + { + return $this->passthru('crossJoin', func_get_args()); + } + + /** + * Count the number of items in the collection by a field or using a callback. + * + * @param callable|string $countBy + * @return static + */ + public function countBy($countBy = null) + { + $countBy = is_null($countBy) + ? $this->identity() + : $this->valueRetriever($countBy); + + return new static(function () use ($countBy) { + $counts = []; + + foreach ($this as $key => $value) { + $group = $countBy($value, $key); + + if (empty($counts[$group])) { + $counts[$group] = 0; + } + + $counts[$group]++; + } + + yield from $counts; + }); + } + + /** + * Get the items that are not present in the given items. + * + * @param mixed $items + * @return static + */ + public function diff($items) + { + return $this->passthru('diff', func_get_args()); + } + + /** + * Get the items that are not present in the given items, using the callback. + * + * @param mixed $items + * @param callable $callback + * @return static + */ + public function diffUsing($items, callable $callback) + { + return $this->passthru('diffUsing', func_get_args()); + } + + /** + * Get the items whose keys and values are not present in the given items. + * + * @param mixed $items + * @return static + */ + public function diffAssoc($items) + { + return $this->passthru('diffAssoc', func_get_args()); + } + + /** + * Get the items whose keys and values are not present in the given items, using the callback. + * + * @param mixed $items + * @param callable $callback + * @return static + */ + public function diffAssocUsing($items, callable $callback) + { + return $this->passthru('diffAssocUsing', func_get_args()); + } + + /** + * Get the items whose keys are not present in the given items. + * + * @param mixed $items + * @return static + */ + public function diffKeys($items) + { + return $this->passthru('diffKeys', func_get_args()); + } + + /** + * Get the items whose keys are not present in the given items, using the callback. + * + * @param mixed $items + * @param callable $callback + * @return static + */ + public function diffKeysUsing($items, callable $callback) + { + return $this->passthru('diffKeysUsing', func_get_args()); + } + + /** + * Retrieve duplicate items. + * + * @param callable|string|null $callback + * @param bool $strict + * @return static + */ + public function duplicates($callback = null, $strict = false) + { + return $this->passthru('duplicates', func_get_args()); + } + + /** + * Retrieve duplicate items using strict comparison. + * + * @param callable|string|null $callback + * @return static + */ + public function duplicatesStrict($callback = null) + { + return $this->passthru('duplicatesStrict', func_get_args()); + } + + /** + * Get all items except for those with the specified keys. + * + * @param mixed $keys + * @return static + */ + public function except($keys) + { + return $this->passthru('except', func_get_args()); + } + + /** + * Run a filter over each of the items. + * + * @param callable|null $callback + * @return static + */ + public function filter(callable $callback = null) + { + if (is_null($callback)) { + $callback = function ($value) { + return (bool) $value; + }; + } + + return new static(function () use ($callback) { + foreach ($this as $key => $value) { + if ($callback($value, $key)) { + yield $key => $value; + } + } + }); + } + + /** + * Get the first item from the enumerable passing the given truth test. + * + * @param callable|null $callback + * @param mixed $default + * @return mixed + */ + public function first(callable $callback = null, $default = null) + { + $iterator = $this->getIterator(); + + if (is_null($callback)) { + if (! $iterator->valid()) { + return value($default); + } + + return $iterator->current(); + } + + foreach ($iterator as $key => $value) { + if ($callback($value, $key)) { + return $value; + } + } + + return value($default); + } + + /** + * Get a flattened list of the items in the collection. + * + * @param int $depth + * @return static + */ + public function flatten($depth = INF) + { + $instance = new static(function () use ($depth) { + foreach ($this as $item) { + if (! is_array($item) && ! $item instanceof Enumerable) { + yield $item; + } elseif ($depth === 1) { + yield from $item; + } else { + yield from (new static($item))->flatten($depth - 1); + } + } + }); + + return $instance->values(); + } + + /** + * Flip the items in the collection. + * + * @return static + */ + public function flip() + { + return new static(function () { + foreach ($this as $key => $value) { + yield $value => $key; + } + }); + } + + /** + * Get an item by key. + * + * @param mixed $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + if (is_null($key)) { + return; + } + + foreach ($this as $outerKey => $outerValue) { + if ($outerKey == $key) { + return $outerValue; + } + } + + return value($default); + } + + /** + * Group an associative array by a field or using a callback. + * + * @param array|callable|string $groupBy + * @param bool $preserveKeys + * @return static + */ + public function groupBy($groupBy, $preserveKeys = false) + { + return $this->passthru('groupBy', func_get_args()); + } + + /** + * Key an associative array by a field or using a callback. + * + * @param callable|string $keyBy + * @return static + */ + public function keyBy($keyBy) + { + return new static(function () use ($keyBy) { + $keyBy = $this->valueRetriever($keyBy); + + foreach ($this as $key => $item) { + $resolvedKey = $keyBy($item, $key); + + if (is_object($resolvedKey)) { + $resolvedKey = (string) $resolvedKey; + } + + yield $resolvedKey => $item; + } + }); + } + + /** + * Determine if an item exists in the collection by key. + * + * @param mixed $key + * @return bool + */ + public function has($key) + { + $keys = array_flip(is_array($key) ? $key : func_get_args()); + $count = count($keys); + + foreach ($this as $key => $value) { + if (array_key_exists($key, $keys) && --$count == 0) { + return true; + } + } + + return false; + } + + /** + * Determine if any of the keys exist in the collection. + * + * @param mixed $key + * @return bool + */ + public function hasAny($key) + { + $keys = array_flip(is_array($key) ? $key : func_get_args()); + + foreach ($this as $key => $value) { + if (array_key_exists($key, $keys)) { + return true; + } + } + + return false; + } + + /** + * Concatenate values of a given key as a string. + * + * @param string $value + * @param string|null $glue + * @return string + */ + public function implode($value, $glue = null) + { + return $this->collect()->implode(...func_get_args()); + } + + /** + * Intersect the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function intersect($items) + { + return $this->passthru('intersect', func_get_args()); + } + + /** + * Intersect the collection with the given items by key. + * + * @param mixed $items + * @return static + */ + public function intersectByKeys($items) + { + return $this->passthru('intersectByKeys', func_get_args()); + } + + /** + * Determine if the items are empty or not. + * + * @return bool + */ + public function isEmpty() + { + return ! $this->getIterator()->valid(); + } + + /** + * Determine if the collection contains a single item. + * + * @return bool + */ + public function containsOneItem() + { + return $this->take(2)->count() === 1; + } + + /** + * Join all items from the collection using a string. The final items can use a separate glue string. + * + * @param string $glue + * @param string $finalGlue + * @return string + */ + public function join($glue, $finalGlue = '') + { + return $this->collect()->join(...func_get_args()); + } + + /** + * Get the keys of the collection items. + * + * @return static + */ + public function keys() + { + return new static(function () { + foreach ($this as $key => $value) { + yield $key; + } + }); + } + + /** + * Get the last item from the collection. + * + * @param callable|null $callback + * @param mixed $default + * @return mixed + */ + public function last(callable $callback = null, $default = null) + { + $needle = $placeholder = new stdClass; + + foreach ($this as $key => $value) { + if (is_null($callback) || $callback($value, $key)) { + $needle = $value; + } + } + + return $needle === $placeholder ? value($default) : $needle; + } + + /** + * Get the values of a given key. + * + * @param string|array $value + * @param string|null $key + * @return static + */ + public function pluck($value, $key = null) + { + return new static(function () use ($value, $key) { + [$value, $key] = $this->explodePluckParameters($value, $key); + + foreach ($this as $item) { + $itemValue = data_get($item, $value); + + if (is_null($key)) { + yield $itemValue; + } else { + $itemKey = data_get($item, $key); + + if (is_object($itemKey) && method_exists($itemKey, '__toString')) { + $itemKey = (string) $itemKey; + } + + yield $itemKey => $itemValue; + } + } + }); + } + + /** + * Run a map over each of the items. + * + * @param callable $callback + * @return static + */ + public function map(callable $callback) + { + return new static(function () use ($callback) { + foreach ($this as $key => $value) { + yield $key => $callback($value, $key); + } + }); + } + + /** + * Run a dictionary map over the items. + * + * The callback should return an associative array with a single key/value pair. + * + * @param callable $callback + * @return static + */ + public function mapToDictionary(callable $callback) + { + return $this->passthru('mapToDictionary', func_get_args()); + } + + /** + * Run an associative map over each of the items. + * + * The callback should return an associative array with a single key/value pair. + * + * @param callable $callback + * @return static + */ + public function mapWithKeys(callable $callback) + { + return new static(function () use ($callback) { + foreach ($this as $key => $value) { + yield from $callback($value, $key); + } + }); + } + + /** + * Merge the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function merge($items) + { + return $this->passthru('merge', func_get_args()); + } + + /** + * Recursively merge the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function mergeRecursive($items) + { + return $this->passthru('mergeRecursive', func_get_args()); + } + + /** + * Create a collection by using this collection for keys and another for its values. + * + * @param mixed $values + * @return static + */ + public function combine($values) + { + return new static(function () use ($values) { + $values = $this->makeIterator($values); + + $errorMessage = 'Both parameters should have an equal number of elements'; + + foreach ($this as $key) { + if (! $values->valid()) { + trigger_error($errorMessage, E_USER_WARNING); + + break; + } + + yield $key => $values->current(); + + $values->next(); + } + + if ($values->valid()) { + trigger_error($errorMessage, E_USER_WARNING); + } + }); + } + + /** + * Union the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function union($items) + { + return $this->passthru('union', func_get_args()); + } + + /** + * Create a new collection consisting of every n-th element. + * + * @param int $step + * @param int $offset + * @return static + */ + public function nth($step, $offset = 0) + { + return new static(function () use ($step, $offset) { + $position = 0; + + foreach ($this->slice($offset) as $item) { + if ($position % $step === 0) { + yield $item; + } + + $position++; + } + }); + } + + /** + * Get the items with the specified keys. + * + * @param mixed $keys + * @return static + */ + public function only($keys) + { + if ($keys instanceof Enumerable) { + $keys = $keys->all(); + } elseif (! is_null($keys)) { + $keys = is_array($keys) ? $keys : func_get_args(); + } + + return new static(function () use ($keys) { + if (is_null($keys)) { + yield from $this; + } else { + $keys = array_flip($keys); + + foreach ($this as $key => $value) { + if (array_key_exists($key, $keys)) { + yield $key => $value; + + unset($keys[$key]); + + if (empty($keys)) { + break; + } + } + } + } + }); + } + + /** + * Push all of the given items onto the collection. + * + * @param iterable $source + * @return static + */ + public function concat($source) + { + return (new static(function () use ($source) { + yield from $this; + yield from $source; + }))->values(); + } + + /** + * Get one or a specified number of items randomly from the collection. + * + * @param int|null $number + * @return static|mixed + * + * @throws \InvalidArgumentException + */ + public function random($number = null) + { + $result = $this->collect()->random(...func_get_args()); + + return is_null($number) ? $result : new static($result); + } + + /** + * Replace the collection items with the given items. + * + * @param mixed $items + * @return static + */ + public function replace($items) + { + return new static(function () use ($items) { + $items = $this->getArrayableItems($items); + + foreach ($this as $key => $value) { + if (array_key_exists($key, $items)) { + yield $key => $items[$key]; + + unset($items[$key]); + } else { + yield $key => $value; + } + } + + foreach ($items as $key => $value) { + yield $key => $value; + } + }); + } + + /** + * Recursively replace the collection items with the given items. + * + * @param mixed $items + * @return static + */ + public function replaceRecursive($items) + { + return $this->passthru('replaceRecursive', func_get_args()); + } + + /** + * Reverse items order. + * + * @return static + */ + public function reverse() + { + return $this->passthru('reverse', func_get_args()); + } + + /** + * Search the collection for a given value and return the corresponding key if successful. + * + * @param mixed $value + * @param bool $strict + * @return mixed + */ + public function search($value, $strict = false) + { + $predicate = $this->useAsCallable($value) + ? $value + : function ($item) use ($value, $strict) { + return $strict ? $item === $value : $item == $value; + }; + + foreach ($this as $key => $item) { + if ($predicate($item, $key)) { + return $key; + } + } + + return false; + } + + /** + * Shuffle the items in the collection. + * + * @param int|null $seed + * @return static + */ + public function shuffle($seed = null) + { + return $this->passthru('shuffle', func_get_args()); + } + + /** + * Create chunks representing a "sliding window" view of the items in the collection. + * + * @param int $size + * @param int $step + * @return static + */ + public function sliding($size = 2, $step = 1) + { + return new static(function () use ($size, $step) { + $iterator = $this->getIterator(); + + $chunk = []; + + while ($iterator->valid()) { + $chunk[$iterator->key()] = $iterator->current(); + + if (count($chunk) == $size) { + yield tap(new static($chunk), function () use (&$chunk, $step) { + $chunk = array_slice($chunk, $step, null, true); + }); + + // If the $step between chunks is bigger than each chunk's $size + // we will skip the extra items (which should never be in any + // chunk) before we continue to the next chunk in the loop. + if ($step > $size) { + $skip = $step - $size; + + for ($i = 0; $i < $skip && $iterator->valid(); $i++) { + $iterator->next(); + } + } + } + + $iterator->next(); + } + }); + } + + /** + * Skip the first {$count} items. + * + * @param int $count + * @return static + */ + public function skip($count) + { + return new static(function () use ($count) { + $iterator = $this->getIterator(); + + while ($iterator->valid() && $count--) { + $iterator->next(); + } + + while ($iterator->valid()) { + yield $iterator->key() => $iterator->current(); + + $iterator->next(); + } + }); + } + + /** + * Skip items in the collection until the given condition is met. + * + * @param mixed $value + * @return static + */ + public function skipUntil($value) + { + $callback = $this->useAsCallable($value) ? $value : $this->equality($value); + + return $this->skipWhile($this->negate($callback)); + } + + /** + * Skip items in the collection while the given condition is met. + * + * @param mixed $value + * @return static + */ + public function skipWhile($value) + { + $callback = $this->useAsCallable($value) ? $value : $this->equality($value); + + return new static(function () use ($callback) { + $iterator = $this->getIterator(); + + while ($iterator->valid() && $callback($iterator->current(), $iterator->key())) { + $iterator->next(); + } + + while ($iterator->valid()) { + yield $iterator->key() => $iterator->current(); + + $iterator->next(); + } + }); + } + + /** + * Get a slice of items from the enumerable. + * + * @param int $offset + * @param int|null $length + * @return static + */ + public function slice($offset, $length = null) + { + if ($offset < 0 || $length < 0) { + return $this->passthru('slice', func_get_args()); + } + + $instance = $this->skip($offset); + + return is_null($length) ? $instance : $instance->take($length); + } + + /** + * Split a collection into a certain number of groups. + * + * @param int $numberOfGroups + * @return static + */ + public function split($numberOfGroups) + { + return $this->passthru('split', func_get_args()); + } + + /** + * Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return mixed + * + * @throws \Illuminate\Support\ItemNotFoundException + * @throws \Illuminate\Support\MultipleItemsFoundException + */ + public function sole($key = null, $operator = null, $value = null) + { + $filter = func_num_args() > 1 + ? $this->operatorForWhere(...func_get_args()) + : $key; + + return $this + ->when($filter) + ->filter($filter) + ->take(2) + ->collect() + ->sole(); + } + + /** + * Get the first item in the collection but throw an exception if no matching items exist. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return mixed + * + * @throws \Illuminate\Support\ItemNotFoundException + */ + public function firstOrFail($key = null, $operator = null, $value = null) + { + $filter = func_num_args() > 1 + ? $this->operatorForWhere(...func_get_args()) + : $key; + + return $this + ->when($filter) + ->filter($filter) + ->take(1) + ->collect() + ->firstOrFail(); + } + + /** + * Chunk the collection into chunks of the given size. + * + * @param int $size + * @return static + */ + public function chunk($size) + { + if ($size <= 0) { + return static::empty(); + } + + return new static(function () use ($size) { + $iterator = $this->getIterator(); + + while ($iterator->valid()) { + $chunk = []; + + while (true) { + $chunk[$iterator->key()] = $iterator->current(); + + if (count($chunk) < $size) { + $iterator->next(); + + if (! $iterator->valid()) { + break; + } + } else { + break; + } + } + + yield new static($chunk); + + $iterator->next(); + } + }); + } + + /** + * Split a collection into a certain number of groups, and fill the first groups completely. + * + * @param int $numberOfGroups + * @return static + */ + public function splitIn($numberOfGroups) + { + return $this->chunk(ceil($this->count() / $numberOfGroups)); + } + + /** + * Chunk the collection into chunks with a callback. + * + * @param callable $callback + * @return static + */ + public function chunkWhile(callable $callback) + { + return new static(function () use ($callback) { + $iterator = $this->getIterator(); + + $chunk = new Collection; + + if ($iterator->valid()) { + $chunk[$iterator->key()] = $iterator->current(); + + $iterator->next(); + } + + while ($iterator->valid()) { + if (! $callback($iterator->current(), $iterator->key(), $chunk)) { + yield new static($chunk); + + $chunk = new Collection; + } + + $chunk[$iterator->key()] = $iterator->current(); + + $iterator->next(); + } + + if ($chunk->isNotEmpty()) { + yield new static($chunk); + } + }); + } + + /** + * Sort through each item with a callback. + * + * @param callable|null|int $callback + * @return static + */ + public function sort($callback = null) + { + return $this->passthru('sort', func_get_args()); + } + + /** + * Sort items in descending order. + * + * @param int $options + * @return static + */ + public function sortDesc($options = SORT_REGULAR) + { + return $this->passthru('sortDesc', func_get_args()); + } + + /** + * Sort the collection using the given callback. + * + * @param callable|string $callback + * @param int $options + * @param bool $descending + * @return static + */ + public function sortBy($callback, $options = SORT_REGULAR, $descending = false) + { + return $this->passthru('sortBy', func_get_args()); + } + + /** + * Sort the collection in descending order using the given callback. + * + * @param callable|string $callback + * @param int $options + * @return static + */ + public function sortByDesc($callback, $options = SORT_REGULAR) + { + return $this->passthru('sortByDesc', func_get_args()); + } + + /** + * Sort the collection keys. + * + * @param int $options + * @param bool $descending + * @return static + */ + public function sortKeys($options = SORT_REGULAR, $descending = false) + { + return $this->passthru('sortKeys', func_get_args()); + } + + /** + * Sort the collection keys in descending order. + * + * @param int $options + * @return static + */ + public function sortKeysDesc($options = SORT_REGULAR) + { + return $this->passthru('sortKeysDesc', func_get_args()); + } + + /** + * Sort the collection keys using a callback. + * + * @param callable $callback + * @return static + */ + public function sortKeysUsing(callable $callback) + { + return $this->passthru('sortKeysUsing', func_get_args()); + } + + /** + * Take the first or last {$limit} items. + * + * @param int $limit + * @return static + */ + public function take($limit) + { + if ($limit < 0) { + return $this->passthru('take', func_get_args()); + } + + return new static(function () use ($limit) { + $iterator = $this->getIterator(); + + while ($limit--) { + if (! $iterator->valid()) { + break; + } + + yield $iterator->key() => $iterator->current(); + + if ($limit) { + $iterator->next(); + } + } + }); + } + + /** + * Take items in the collection until the given condition is met. + * + * @param mixed $value + * @return static + */ + public function takeUntil($value) + { + $callback = $this->useAsCallable($value) ? $value : $this->equality($value); + + return new static(function () use ($callback) { + foreach ($this as $key => $item) { + if ($callback($item, $key)) { + break; + } + + yield $key => $item; + } + }); + } + + /** + * Take items in the collection until a given point in time. + * + * @param \DateTimeInterface $timeout + * @return static + */ + public function takeUntilTimeout(DateTimeInterface $timeout) + { + $timeout = $timeout->getTimestamp(); + + return $this->takeWhile(function () use ($timeout) { + return $this->now() < $timeout; + }); + } + + /** + * Take items in the collection while the given condition is met. + * + * @param mixed $value + * @return static + */ + public function takeWhile($value) + { + $callback = $this->useAsCallable($value) ? $value : $this->equality($value); + + return $this->takeUntil(function ($item, $key) use ($callback) { + return ! $callback($item, $key); + }); + } + + /** + * Pass each item in the collection to the given callback, lazily. + * + * @param callable $callback + * @return static + */ + public function tapEach(callable $callback) + { + return new static(function () use ($callback) { + foreach ($this as $key => $value) { + $callback($value, $key); + + yield $key => $value; + } + }); + } + + /** + * Convert a flatten "dot" notation array into an expanded array. + * + * @return static + */ + public function undot() + { + return $this->passthru('undot', []); + } + + /** + * Return only unique items from the collection array. + * + * @param string|callable|null $key + * @param bool $strict + * @return static + */ + public function unique($key = null, $strict = false) + { + $callback = $this->valueRetriever($key); + + return new static(function () use ($callback, $strict) { + $exists = []; + + foreach ($this as $key => $item) { + if (! in_array($id = $callback($item, $key), $exists, $strict)) { + yield $key => $item; + + $exists[] = $id; + } + } + }); + } + + /** + * Reset the keys on the underlying array. + * + * @return static + */ + public function values() + { + return new static(function () { + foreach ($this as $item) { + yield $item; + } + }); + } + + /** + * Zip the collection together with one or more arrays. + * + * e.g. new LazyCollection([1, 2, 3])->zip([4, 5, 6]); + * => [[1, 4], [2, 5], [3, 6]] + * + * @param mixed ...$items + * @return static + */ + public function zip($items) + { + $iterables = func_get_args(); + + return new static(function () use ($iterables) { + $iterators = Collection::make($iterables)->map(function ($iterable) { + return $this->makeIterator($iterable); + })->prepend($this->getIterator()); + + while ($iterators->contains->valid()) { + yield new static($iterators->map->current()); + + $iterators->each->next(); + } + }); + } + + /** + * Pad collection to the specified length with a value. + * + * @param int $size + * @param mixed $value + * @return static + */ + public function pad($size, $value) + { + if ($size < 0) { + return $this->passthru('pad', func_get_args()); + } + + return new static(function () use ($size, $value) { + $yielded = 0; + + foreach ($this as $index => $item) { + yield $index => $item; + + $yielded++; + } + + while ($yielded++ < $size) { + yield $value; + } + }); + } + + /** + * Get the values iterator. + * + * @return \Traversable + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return $this->makeIterator($this->source); + } + + /** + * Count the number of items in the collection. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + if (is_array($this->source)) { + return count($this->source); + } + + return iterator_count($this->getIterator()); + } + + /** + * Make an iterator from the given source. + * + * @param mixed $source + * @return \Traversable + */ + protected function makeIterator($source) + { + if ($source instanceof IteratorAggregate) { + return $source->getIterator(); + } + + if (is_array($source)) { + return new ArrayIterator($source); + } + + return $source(); + } + + /** + * Explode the "value" and "key" arguments passed to "pluck". + * + * @param string|array $value + * @param string|array|null $key + * @return array + */ + protected function explodePluckParameters($value, $key) + { + $value = is_string($value) ? explode('.', $value) : $value; + + $key = is_null($key) || is_array($key) ? $key : explode('.', $key); + + return [$value, $key]; + } + + /** + * Pass this lazy collection through a method on the collection class. + * + * @param string $method + * @param array $params + * @return static + */ + protected function passthru($method, array $params) + { + return new static(function () use ($method, $params) { + yield from $this->collect()->$method(...$params); + }); + } + + /** + * Get the current time. + * + * @return int + */ + protected function now() + { + return time(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/MultipleItemsFoundException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/MultipleItemsFoundException.php new file mode 100644 index 0000000..944b2dc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/MultipleItemsFoundException.php @@ -0,0 +1,9 @@ +all() : $value; + } + + /** + * Create a new instance with no items. + * + * @return static + */ + public static function empty() + { + return new static([]); + } + + /** + * Create a new collection by invoking the callback a given amount of times. + * + * @param int $number + * @param callable|null $callback + * @return static + */ + public static function times($number, callable $callback = null) + { + if ($number < 1) { + return new static; + } + + return static::range(1, $number) + ->when($callback) + ->map($callback); + } + + /** + * Alias for the "avg" method. + * + * @param callable|string|null $callback + * @return mixed + */ + public function average($callback = null) + { + return $this->avg($callback); + } + + /** + * Alias for the "contains" method. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function some($key, $operator = null, $value = null) + { + return $this->contains(...func_get_args()); + } + + /** + * Determine if an item exists, using strict comparison. + * + * @param mixed $key + * @param mixed $value + * @return bool + */ + public function containsStrict($key, $value = null) + { + if (func_num_args() === 2) { + return $this->contains(function ($item) use ($key, $value) { + return data_get($item, $key) === $value; + }); + } + + if ($this->useAsCallable($key)) { + return ! is_null($this->first($key)); + } + + foreach ($this as $item) { + if ($item === $key) { + return true; + } + } + + return false; + } + + /** + * Dump the items and end the script. + * + * @param mixed ...$args + * @return void + */ + public function dd(...$args) + { + $this->dump(...$args); + + exit(1); + } + + /** + * Dump the items. + * + * @return $this + */ + public function dump() + { + (new Collection(func_get_args())) + ->push($this->all()) + ->each(function ($item) { + VarDumper::dump($item); + }); + + return $this; + } + + /** + * Execute a callback over each item. + * + * @param callable $callback + * @return $this + */ + public function each(callable $callback) + { + foreach ($this as $key => $item) { + if ($callback($item, $key) === false) { + break; + } + } + + return $this; + } + + /** + * Execute a callback over each nested chunk of items. + * + * @param callable $callback + * @return static + */ + public function eachSpread(callable $callback) + { + return $this->each(function ($chunk, $key) use ($callback) { + $chunk[] = $key; + + return $callback(...$chunk); + }); + } + + /** + * Determine if all items pass the given truth test. + * + * @param string|callable $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function every($key, $operator = null, $value = null) + { + if (func_num_args() === 1) { + $callback = $this->valueRetriever($key); + + foreach ($this as $k => $v) { + if (! $callback($v, $k)) { + return false; + } + } + + return true; + } + + return $this->every($this->operatorForWhere(...func_get_args())); + } + + /** + * Get the first item by the given key value pair. + * + * @param string $key + * @param mixed $operator + * @param mixed $value + * @return mixed + */ + public function firstWhere($key, $operator = null, $value = null) + { + return $this->first($this->operatorForWhere(...func_get_args())); + } + + /** + * Determine if the collection is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return ! $this->isEmpty(); + } + + /** + * Run a map over each nested chunk of items. + * + * @param callable $callback + * @return static + */ + public function mapSpread(callable $callback) + { + return $this->map(function ($chunk, $key) use ($callback) { + $chunk[] = $key; + + return $callback(...$chunk); + }); + } + + /** + * Run a grouping map over the items. + * + * The callback should return an associative array with a single key/value pair. + * + * @param callable $callback + * @return static + */ + public function mapToGroups(callable $callback) + { + $groups = $this->mapToDictionary($callback); + + return $groups->map([$this, 'make']); + } + + /** + * Map a collection and flatten the result by a single level. + * + * @param callable $callback + * @return static + */ + public function flatMap(callable $callback) + { + return $this->map($callback)->collapse(); + } + + /** + * Map the values into a new class. + * + * @param string $class + * @return static + */ + public function mapInto($class) + { + return $this->map(function ($value, $key) use ($class) { + return new $class($value, $key); + }); + } + + /** + * Get the min value of a given key. + * + * @param callable|string|null $callback + * @return mixed + */ + public function min($callback = null) + { + $callback = $this->valueRetriever($callback); + + return $this->map(function ($value) use ($callback) { + return $callback($value); + })->filter(function ($value) { + return ! is_null($value); + })->reduce(function ($result, $value) { + return is_null($result) || $value < $result ? $value : $result; + }); + } + + /** + * Get the max value of a given key. + * + * @param callable|string|null $callback + * @return mixed + */ + public function max($callback = null) + { + $callback = $this->valueRetriever($callback); + + return $this->filter(function ($value) { + return ! is_null($value); + })->reduce(function ($result, $item) use ($callback) { + $value = $callback($item); + + return is_null($result) || $value > $result ? $value : $result; + }); + } + + /** + * "Paginate" the collection by slicing it into a smaller collection. + * + * @param int $page + * @param int $perPage + * @return static + */ + public function forPage($page, $perPage) + { + $offset = max(0, ($page - 1) * $perPage); + + return $this->slice($offset, $perPage); + } + + /** + * Partition the collection into two arrays using the given callback or key. + * + * @param callable|string $key + * @param mixed $operator + * @param mixed $value + * @return static + */ + public function partition($key, $operator = null, $value = null) + { + $passed = []; + $failed = []; + + $callback = func_num_args() === 1 + ? $this->valueRetriever($key) + : $this->operatorForWhere(...func_get_args()); + + foreach ($this as $key => $item) { + if ($callback($item, $key)) { + $passed[$key] = $item; + } else { + $failed[$key] = $item; + } + } + + return new static([new static($passed), new static($failed)]); + } + + /** + * Get the sum of the given values. + * + * @param callable|string|null $callback + * @return mixed + */ + public function sum($callback = null) + { + $callback = is_null($callback) + ? $this->identity() + : $this->valueRetriever($callback); + + return $this->reduce(function ($result, $item) use ($callback) { + return $result + $callback($item); + }, 0); + } + + /** + * Apply the callback if the value is truthy. + * + * @param bool|mixed $value + * @param callable|null $callback + * @param callable|null $default + * @return static|mixed + */ + public function when($value, callable $callback = null, callable $default = null) + { + if (! $callback) { + return new HigherOrderWhenProxy($this, $value); + } + + if ($value) { + return $callback($this, $value); + } elseif ($default) { + return $default($this, $value); + } + + return $this; + } + + /** + * Apply the callback if the collection is empty. + * + * @param callable $callback + * @param callable|null $default + * @return static|mixed + */ + public function whenEmpty(callable $callback, callable $default = null) + { + return $this->when($this->isEmpty(), $callback, $default); + } + + /** + * Apply the callback if the collection is not empty. + * + * @param callable $callback + * @param callable|null $default + * @return static|mixed + */ + public function whenNotEmpty(callable $callback, callable $default = null) + { + return $this->when($this->isNotEmpty(), $callback, $default); + } + + /** + * Apply the callback if the value is falsy. + * + * @param bool $value + * @param callable $callback + * @param callable|null $default + * @return static|mixed + */ + public function unless($value, callable $callback, callable $default = null) + { + return $this->when(! $value, $callback, $default); + } + + /** + * Apply the callback unless the collection is empty. + * + * @param callable $callback + * @param callable|null $default + * @return static|mixed + */ + public function unlessEmpty(callable $callback, callable $default = null) + { + return $this->whenNotEmpty($callback, $default); + } + + /** + * Apply the callback unless the collection is not empty. + * + * @param callable $callback + * @param callable|null $default + * @return static|mixed + */ + public function unlessNotEmpty(callable $callback, callable $default = null) + { + return $this->whenEmpty($callback, $default); + } + + /** + * Filter items by the given key value pair. + * + * @param string $key + * @param mixed $operator + * @param mixed $value + * @return static + */ + public function where($key, $operator = null, $value = null) + { + return $this->filter($this->operatorForWhere(...func_get_args())); + } + + /** + * Filter items where the value for the given key is null. + * + * @param string|null $key + * @return static + */ + public function whereNull($key = null) + { + return $this->whereStrict($key, null); + } + + /** + * Filter items where the value for the given key is not null. + * + * @param string|null $key + * @return static + */ + public function whereNotNull($key = null) + { + return $this->where($key, '!==', null); + } + + /** + * Filter items by the given key value pair using strict comparison. + * + * @param string $key + * @param mixed $value + * @return static + */ + public function whereStrict($key, $value) + { + return $this->where($key, '===', $value); + } + + /** + * Filter items by the given key value pair. + * + * @param string $key + * @param mixed $values + * @param bool $strict + * @return static + */ + public function whereIn($key, $values, $strict = false) + { + $values = $this->getArrayableItems($values); + + return $this->filter(function ($item) use ($key, $values, $strict) { + return in_array(data_get($item, $key), $values, $strict); + }); + } + + /** + * Filter items by the given key value pair using strict comparison. + * + * @param string $key + * @param mixed $values + * @return static + */ + public function whereInStrict($key, $values) + { + return $this->whereIn($key, $values, true); + } + + /** + * Filter items such that the value of the given key is between the given values. + * + * @param string $key + * @param array $values + * @return static + */ + public function whereBetween($key, $values) + { + return $this->where($key, '>=', reset($values))->where($key, '<=', end($values)); + } + + /** + * Filter items such that the value of the given key is not between the given values. + * + * @param string $key + * @param array $values + * @return static + */ + public function whereNotBetween($key, $values) + { + return $this->filter(function ($item) use ($key, $values) { + return data_get($item, $key) < reset($values) || data_get($item, $key) > end($values); + }); + } + + /** + * Filter items by the given key value pair. + * + * @param string $key + * @param mixed $values + * @param bool $strict + * @return static + */ + public function whereNotIn($key, $values, $strict = false) + { + $values = $this->getArrayableItems($values); + + return $this->reject(function ($item) use ($key, $values, $strict) { + return in_array(data_get($item, $key), $values, $strict); + }); + } + + /** + * Filter items by the given key value pair using strict comparison. + * + * @param string $key + * @param mixed $values + * @return static + */ + public function whereNotInStrict($key, $values) + { + return $this->whereNotIn($key, $values, true); + } + + /** + * Filter the items, removing any items that don't match the given type(s). + * + * @param string|string[] $type + * @return static + */ + public function whereInstanceOf($type) + { + return $this->filter(function ($value) use ($type) { + if (is_array($type)) { + foreach ($type as $classType) { + if ($value instanceof $classType) { + return true; + } + } + + return false; + } + + return $value instanceof $type; + }); + } + + /** + * Pass the collection to the given callback and return the result. + * + * @param callable $callback + * @return mixed + */ + public function pipe(callable $callback) + { + return $callback($this); + } + + /** + * Pass the collection into a new class. + * + * @param string $class + * @return mixed + */ + public function pipeInto($class) + { + return new $class($this); + } + + /** + * Pass the collection through a series of callable pipes and return the result. + * + * @param array $pipes + * @return mixed + */ + public function pipeThrough($pipes) + { + return static::make($pipes)->reduce( + function ($carry, $pipe) { + return $pipe($carry); + }, + $this, + ); + } + + /** + * Pass the collection to the given callback and then return it. + * + * @param callable $callback + * @return $this + */ + public function tap(callable $callback) + { + $callback(clone $this); + + return $this; + } + + /** + * Reduce the collection to a single value. + * + * @param callable $callback + * @param mixed $initial + * @return mixed + */ + public function reduce(callable $callback, $initial = null) + { + $result = $initial; + + foreach ($this as $key => $value) { + $result = $callback($result, $value, $key); + } + + return $result; + } + + /** + * Reduce the collection to multiple aggregate values. + * + * @param callable $callback + * @param mixed ...$initial + * @return array + * + * @deprecated Use "reduceSpread" instead + * + * @throws \UnexpectedValueException + */ + public function reduceMany(callable $callback, ...$initial) + { + return $this->reduceSpread($callback, ...$initial); + } + + /** + * Reduce the collection to multiple aggregate values. + * + * @param callable $callback + * @param mixed ...$initial + * @return array + * + * @throws \UnexpectedValueException + */ + public function reduceSpread(callable $callback, ...$initial) + { + $result = $initial; + + foreach ($this as $key => $value) { + $result = call_user_func_array($callback, array_merge($result, [$value, $key])); + + if (! is_array($result)) { + throw new UnexpectedValueException(sprintf( + "%s::reduceMany expects reducer to return an array, but got a '%s' instead.", + class_basename(static::class), gettype($result) + )); + } + } + + return $result; + } + + /** + * Reduce an associative collection to a single value. + * + * @param callable $callback + * @param mixed $initial + * @return mixed + */ + public function reduceWithKeys(callable $callback, $initial = null) + { + return $this->reduce($callback, $initial); + } + + /** + * Create a collection of all elements that do not pass a given truth test. + * + * @param callable|mixed $callback + * @return static + */ + public function reject($callback = true) + { + $useAsCallable = $this->useAsCallable($callback); + + return $this->filter(function ($value, $key) use ($callback, $useAsCallable) { + return $useAsCallable + ? ! $callback($value, $key) + : $value != $callback; + }); + } + + /** + * Return only unique items from the collection array using strict comparison. + * + * @param string|callable|null $key + * @return static + */ + public function uniqueStrict($key = null) + { + return $this->unique($key, true); + } + + /** + * Collect the values into a collection. + * + * @return \Illuminate\Support\Collection + */ + public function collect() + { + return new Collection($this->all()); + } + + /** + * Get the collection of items as a plain array. + * + * @return array + */ + public function toArray() + { + return $this->map(function ($value) { + return $value instanceof Arrayable ? $value->toArray() : $value; + })->all(); + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return array_map(function ($value) { + if ($value instanceof JsonSerializable) { + return $value->jsonSerialize(); + } elseif ($value instanceof Jsonable) { + return json_decode($value->toJson(), true); + } elseif ($value instanceof Arrayable) { + return $value->toArray(); + } + + return $value; + }, $this->all()); + } + + /** + * Get the collection of items as JSON. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } + + /** + * Get a CachingIterator instance. + * + * @param int $flags + * @return \CachingIterator + */ + public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING) + { + return new CachingIterator($this->getIterator(), $flags); + } + + /** + * Convert the collection to its string representation. + * + * @return string + */ + public function __toString() + { + return $this->escapeWhenCastingToString + ? e($this->toJson()) + : $this->toJson(); + } + + /** + * Indicate that the model's string representation should be escaped when __toString is invoked. + * + * @param bool $escape + * @return $this + */ + public function escapeWhenCastingToString($escape = true) + { + $this->escapeWhenCastingToString = $escape; + + return $this; + } + + /** + * Add a method to the list of proxied methods. + * + * @param string $method + * @return void + */ + public static function proxy($method) + { + static::$proxies[] = $method; + } + + /** + * Dynamically access collection proxies. + * + * @param string $key + * @return mixed + * + * @throws \Exception + */ + public function __get($key) + { + if (! in_array($key, static::$proxies)) { + throw new Exception("Property [{$key}] does not exist on this collection instance."); + } + + return new HigherOrderCollectionProxy($this, $key); + } + + /** + * Results array of items from Collection or Arrayable. + * + * @param mixed $items + * @return array + */ + protected function getArrayableItems($items) + { + if (is_array($items)) { + return $items; + } elseif ($items instanceof Enumerable) { + return $items->all(); + } elseif ($items instanceof Arrayable) { + return $items->toArray(); + } elseif ($items instanceof Jsonable) { + return json_decode($items->toJson(), true); + } elseif ($items instanceof JsonSerializable) { + return (array) $items->jsonSerialize(); + } elseif ($items instanceof Traversable) { + return iterator_to_array($items); + } elseif ($items instanceof UnitEnum) { + return [$items]; + } + + return (array) $items; + } + + /** + * Get an operator checker callback. + * + * @param string $key + * @param string|null $operator + * @param mixed $value + * @return \Closure + */ + protected function operatorForWhere($key, $operator = null, $value = null) + { + if (func_num_args() === 1) { + $value = true; + + $operator = '='; + } + + if (func_num_args() === 2) { + $value = $operator; + + $operator = '='; + } + + return function ($item) use ($key, $operator, $value) { + $retrieved = data_get($item, $key); + + $strings = array_filter([$retrieved, $value], function ($value) { + return is_string($value) || (is_object($value) && method_exists($value, '__toString')); + }); + + if (count($strings) < 2 && count(array_filter([$retrieved, $value], 'is_object')) == 1) { + return in_array($operator, ['!=', '<>', '!==']); + } + + switch ($operator) { + default: + case '=': + case '==': return $retrieved == $value; + case '!=': + case '<>': return $retrieved != $value; + case '<': return $retrieved < $value; + case '>': return $retrieved > $value; + case '<=': return $retrieved <= $value; + case '>=': return $retrieved >= $value; + case '===': return $retrieved === $value; + case '!==': return $retrieved !== $value; + } + }; + } + + /** + * Determine if the given value is callable, but not a string. + * + * @param mixed $value + * @return bool + */ + protected function useAsCallable($value) + { + return ! is_string($value) && is_callable($value); + } + + /** + * Get a value retrieving callback. + * + * @param callable|string|null $value + * @return callable + */ + protected function valueRetriever($value) + { + if ($this->useAsCallable($value)) { + return $value; + } + + return function ($item) use ($value) { + return data_get($item, $value); + }; + } + + /** + * Make a function to check an item's equality. + * + * @param mixed $value + * @return \Closure + */ + protected function equality($value) + { + return function ($item) use ($value) { + return $item === $value; + }; + } + + /** + * Make a function using another function, by negating its result. + * + * @param \Closure $callback + * @return \Closure + */ + protected function negate(Closure $callback) + { + return function (...$params) use ($callback) { + return ! $callback(...$params); + }; + } + + /** + * Make a function that returns what's passed to it. + * + * @return \Closure + */ + protected function identity() + { + return function ($value) { + return $value; + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/composer.json new file mode 100644 index 0000000..ecc4537 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/composer.json @@ -0,0 +1,41 @@ +{ + "name": "illuminate/collections", + "description": "The Illuminate Collections package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Support\\": "" + }, + "files": [ + "helpers.php" + ] + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "symfony/var-dumper": "Required to use the dump method (^5.4)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/helpers.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/helpers.php new file mode 100644 index 0000000..67669e5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Collections/helpers.php @@ -0,0 +1,186 @@ + $segment) { + unset($key[$i]); + + if (is_null($segment)) { + return $target; + } + + if ($segment === '*') { + if ($target instanceof Collection) { + $target = $target->all(); + } elseif (! is_array($target)) { + return value($default); + } + + $result = []; + + foreach ($target as $item) { + $result[] = data_get($item, $key); + } + + return in_array('*', $key) ? Arr::collapse($result) : $result; + } + + if (Arr::accessible($target) && Arr::exists($target, $segment)) { + $target = $target[$segment]; + } elseif (is_object($target) && isset($target->{$segment})) { + $target = $target->{$segment}; + } else { + return value($default); + } + } + + return $target; + } +} + +if (! function_exists('data_set')) { + /** + * Set an item on an array or object using dot notation. + * + * @param mixed $target + * @param string|array $key + * @param mixed $value + * @param bool $overwrite + * @return mixed + */ + function data_set(&$target, $key, $value, $overwrite = true) + { + $segments = is_array($key) ? $key : explode('.', $key); + + if (($segment = array_shift($segments)) === '*') { + if (! Arr::accessible($target)) { + $target = []; + } + + if ($segments) { + foreach ($target as &$inner) { + data_set($inner, $segments, $value, $overwrite); + } + } elseif ($overwrite) { + foreach ($target as &$inner) { + $inner = $value; + } + } + } elseif (Arr::accessible($target)) { + if ($segments) { + if (! Arr::exists($target, $segment)) { + $target[$segment] = []; + } + + data_set($target[$segment], $segments, $value, $overwrite); + } elseif ($overwrite || ! Arr::exists($target, $segment)) { + $target[$segment] = $value; + } + } elseif (is_object($target)) { + if ($segments) { + if (! isset($target->{$segment})) { + $target->{$segment} = []; + } + + data_set($target->{$segment}, $segments, $value, $overwrite); + } elseif ($overwrite || ! isset($target->{$segment})) { + $target->{$segment} = $value; + } + } else { + $target = []; + + if ($segments) { + data_set($target[$segment], $segments, $value, $overwrite); + } elseif ($overwrite) { + $target[$segment] = $value; + } + } + + return $target; + } +} + +if (! function_exists('head')) { + /** + * Get the first element of an array. Useful for method chaining. + * + * @param array $array + * @return mixed + */ + function head($array) + { + return reset($array); + } +} + +if (! function_exists('last')) { + /** + * Get the last element from an array. + * + * @param array $array + * @return mixed + */ + function last($array) + { + return end($array); + } +} + +if (! function_exists('value')) { + /** + * Return the default value of the given value. + * + * @param mixed $value + * @return mixed + */ + function value($value, ...$args) + { + return $value instanceof Closure ? $value(...$args) : $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/Repository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/Repository.php new file mode 100644 index 0000000..1719e90 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/Repository.php @@ -0,0 +1,183 @@ +items = $items; + } + + /** + * Determine if the given configuration value exists. + * + * @param string $key + * @return bool + */ + public function has($key) + { + return Arr::has($this->items, $key); + } + + /** + * Get the specified configuration value. + * + * @param array|string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + if (is_array($key)) { + return $this->getMany($key); + } + + return Arr::get($this->items, $key, $default); + } + + /** + * Get many configuration values. + * + * @param array $keys + * @return array + */ + public function getMany($keys) + { + $config = []; + + foreach ($keys as $key => $default) { + if (is_numeric($key)) { + [$key, $default] = [$default, null]; + } + + $config[$key] = Arr::get($this->items, $key, $default); + } + + return $config; + } + + /** + * Set a given configuration value. + * + * @param array|string $key + * @param mixed $value + * @return void + */ + public function set($key, $value = null) + { + $keys = is_array($key) ? $key : [$key => $value]; + + foreach ($keys as $key => $value) { + Arr::set($this->items, $key, $value); + } + } + + /** + * Prepend a value onto an array configuration value. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function prepend($key, $value) + { + $array = $this->get($key, []); + + array_unshift($array, $value); + + $this->set($key, $array); + } + + /** + * Push a value onto an array configuration value. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function push($key, $value) + { + $array = $this->get($key, []); + + $array[] = $value; + + $this->set($key, $array); + } + + /** + * Get all of the configuration items for the application. + * + * @return array + */ + public function all() + { + return $this->items; + } + + /** + * Determine if the given configuration option exists. + * + * @param string $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->has($key); + } + + /** + * Get a configuration option. + * + * @param string $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->get($key); + } + + /** + * Set a configuration option. + * + * @param string $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->set($key, $value); + } + + /** + * Unset a configuration option. + * + * @param string $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + $this->set($key, null); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/composer.json new file mode 100755 index 0000000..9d577bb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Config/composer.json @@ -0,0 +1,35 @@ +{ + "name": "illuminate/config", + "description": "The Illuminate Config package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Config\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Application.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Application.php new file mode 100755 index 0000000..88c65c7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Application.php @@ -0,0 +1,317 @@ +laravel = $laravel; + $this->events = $events; + $this->setAutoExit(false); + $this->setCatchExceptions(false); + + $this->events->dispatch(new ArtisanStarting($this)); + + $this->bootstrap(); + } + + /** + * {@inheritdoc} + * + * @return int + */ + public function run(InputInterface $input = null, OutputInterface $output = null) + { + $commandName = $this->getCommandName( + $input = $input ?: new ArgvInput + ); + + $this->events->dispatch( + new CommandStarting( + $commandName, $input, $output = $output ?: new BufferedConsoleOutput + ) + ); + + $exitCode = parent::run($input, $output); + + $this->events->dispatch( + new CommandFinished($commandName, $input, $output, $exitCode) + ); + + return $exitCode; + } + + /** + * Determine the proper PHP executable. + * + * @return string + */ + public static function phpBinary() + { + return ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)); + } + + /** + * Determine the proper Artisan executable. + * + * @return string + */ + public static function artisanBinary() + { + return ProcessUtils::escapeArgument(defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan'); + } + + /** + * Format the given command as a fully-qualified executable command. + * + * @param string $string + * @return string + */ + public static function formatCommandString($string) + { + return sprintf('%s %s %s', static::phpBinary(), static::artisanBinary(), $string); + } + + /** + * Register a console "starting" bootstrapper. + * + * @param \Closure $callback + * @return void + */ + public static function starting(Closure $callback) + { + static::$bootstrappers[] = $callback; + } + + /** + * Bootstrap the console application. + * + * @return void + */ + protected function bootstrap() + { + foreach (static::$bootstrappers as $bootstrapper) { + $bootstrapper($this); + } + } + + /** + * Clear the console application bootstrappers. + * + * @return void + */ + public static function forgetBootstrappers() + { + static::$bootstrappers = []; + } + + /** + * Run an Artisan console command by name. + * + * @param string $command + * @param array $parameters + * @param \Symfony\Component\Console\Output\OutputInterface|null $outputBuffer + * @return int + * + * @throws \Symfony\Component\Console\Exception\CommandNotFoundException + */ + public function call($command, array $parameters = [], $outputBuffer = null) + { + [$command, $input] = $this->parseCommand($command, $parameters); + + if (! $this->has($command)) { + throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $command)); + } + + return $this->run( + $input, $this->lastOutput = $outputBuffer ?: new BufferedOutput + ); + } + + /** + * Parse the incoming Artisan command and its input. + * + * @param string $command + * @param array $parameters + * @return array + */ + protected function parseCommand($command, $parameters) + { + if (is_subclass_of($command, SymfonyCommand::class)) { + $callingClass = true; + + $command = $this->laravel->make($command)->getName(); + } + + if (! isset($callingClass) && empty($parameters)) { + $command = $this->getCommandName($input = new StringInput($command)); + } else { + array_unshift($parameters, $command); + + $input = new ArrayInput($parameters); + } + + return [$command, $input]; + } + + /** + * Get the output for the last run command. + * + * @return string + */ + public function output() + { + return $this->lastOutput && method_exists($this->lastOutput, 'fetch') + ? $this->lastOutput->fetch() + : ''; + } + + /** + * Add a command to the console. + * + * @param \Symfony\Component\Console\Command\Command $command + * @return \Symfony\Component\Console\Command\Command + */ + public function add(SymfonyCommand $command) + { + if ($command instanceof Command) { + $command->setLaravel($this->laravel); + } + + return $this->addToParent($command); + } + + /** + * Add the command to the parent instance. + * + * @param \Symfony\Component\Console\Command\Command $command + * @return \Symfony\Component\Console\Command\Command + */ + protected function addToParent(SymfonyCommand $command) + { + return parent::add($command); + } + + /** + * Add a command, resolving through the application. + * + * @param string $command + * @return \Symfony\Component\Console\Command\Command + */ + public function resolve($command) + { + return $this->add($this->laravel->make($command)); + } + + /** + * Resolve an array of commands through the application. + * + * @param array|mixed $commands + * @return $this + */ + public function resolveCommands($commands) + { + $commands = is_array($commands) ? $commands : func_get_args(); + + foreach ($commands as $command) { + $this->resolve($command); + } + + return $this; + } + + /** + * Get the default input definition for the application. + * + * This is used to add the --env option to every available command. + * + * @return \Symfony\Component\Console\Input\InputDefinition + */ + protected function getDefaultInputDefinition() + { + return tap(parent::getDefaultInputDefinition(), function ($definition) { + $definition->addOption($this->getEnvironmentOption()); + }); + } + + /** + * Get the global environment option for the definition. + * + * @return \Symfony\Component\Console\Input\InputOption + */ + protected function getEnvironmentOption() + { + $message = 'The environment the command should run under'; + + return new InputOption('--env', null, InputOption::VALUE_OPTIONAL, $message); + } + + /** + * Get the Laravel application instance. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public function getLaravel() + { + return $this->laravel; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/BufferedConsoleOutput.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/BufferedConsoleOutput.php new file mode 100644 index 0000000..4bb5ca2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/BufferedConsoleOutput.php @@ -0,0 +1,41 @@ +buffer, function () { + $this->buffer = ''; + }); + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $message, bool $newline) + { + $this->buffer .= $message; + + if ($newline) { + $this->buffer .= \PHP_EOL; + } + + return parent::doWrite($message, $newline); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Command.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Command.php new file mode 100755 index 0000000..5c8c179 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Command.php @@ -0,0 +1,206 @@ +signature)) { + $this->configureUsingFluentDefinition(); + } else { + parent::__construct($this->name); + } + + // Once we have constructed the command, we'll set the description and other + // related properties of the command. If a signature wasn't used to build + // the command we'll set the arguments and the options on this command. + $this->setDescription((string) $this->description); + + $this->setHelp((string) $this->help); + + $this->setHidden($this->isHidden()); + + if (! isset($this->signature)) { + $this->specifyParameters(); + } + } + + /** + * Configure the console command using a fluent definition. + * + * @return void + */ + protected function configureUsingFluentDefinition() + { + [$name, $arguments, $options] = Parser::parse($this->signature); + + parent::__construct($this->name = $name); + + // After parsing the signature we will spin through the arguments and options + // and set them on this command. These will already be changed into proper + // instances of these "InputArgument" and "InputOption" Symfony classes. + $this->getDefinition()->addArguments($arguments); + $this->getDefinition()->addOptions($options); + } + + /** + * Run the console command. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @return int + */ + public function run(InputInterface $input, OutputInterface $output) + { + $this->output = $this->laravel->make( + OutputStyle::class, ['input' => $input, 'output' => $output] + ); + + return parent::run( + $this->input = $input, $this->output + ); + } + + /** + * Execute the console command. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @return int + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $method = method_exists($this, 'handle') ? 'handle' : '__invoke'; + + return (int) $this->laravel->call([$this, $method]); + } + + /** + * Resolve the console command instance for the given command. + * + * @param \Symfony\Component\Console\Command\Command|string $command + * @return \Symfony\Component\Console\Command\Command + */ + protected function resolveCommand($command) + { + if (! class_exists($command)) { + return $this->getApplication()->find($command); + } + + $command = $this->laravel->make($command); + + if ($command instanceof SymfonyCommand) { + $command->setApplication($this->getApplication()); + } + + if ($command instanceof self) { + $command->setLaravel($this->getLaravel()); + } + + return $command; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function isHidden() + { + return $this->hidden; + } + + /** + * {@inheritdoc} + * + * @return static + */ + public function setHidden(bool $hidden) + { + parent::setHidden($this->hidden = $hidden); + + return $this; + } + + /** + * Get the Laravel application instance. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public function getLaravel() + { + return $this->laravel; + } + + /** + * Set the Laravel application instance. + * + * @param \Illuminate\Contracts\Container\Container $laravel + * @return void + */ + public function setLaravel($laravel) + { + $this->laravel = $laravel; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/CallsCommands.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/CallsCommands.php new file mode 100644 index 0000000..7e69b9b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/CallsCommands.php @@ -0,0 +1,104 @@ +runCommand($command, $arguments, $this->output); + } + + /** + * Call another console command without output. + * + * @param \Symfony\Component\Console\Command\Command|string $command + * @param array $arguments + * @return int + */ + public function callSilent($command, array $arguments = []) + { + return $this->runCommand($command, $arguments, new NullOutput); + } + + /** + * Call another console command without output. + * + * @param \Symfony\Component\Console\Command\Command|string $command + * @param array $arguments + * @return int + */ + public function callSilently($command, array $arguments = []) + { + return $this->callSilent($command, $arguments); + } + + /** + * Run the given the console command. + * + * @param \Symfony\Component\Console\Command\Command|string $command + * @param array $arguments + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @return int + */ + protected function runCommand($command, array $arguments, OutputInterface $output) + { + $arguments['command'] = $command; + + return $this->resolveCommand($command)->run( + $this->createInputFromArguments($arguments), $output + ); + } + + /** + * Create an input instance from the given arguments. + * + * @param array $arguments + * @return \Symfony\Component\Console\Input\ArrayInput + */ + protected function createInputFromArguments(array $arguments) + { + return tap(new ArrayInput(array_merge($this->context(), $arguments)), function ($input) { + if ($input->getParameterOption('--no-interaction')) { + $input->setInteractive(false); + } + }); + } + + /** + * Get all of the context passed to the command. + * + * @return array + */ + protected function context() + { + return collect($this->option())->only([ + 'ansi', + 'no-ansi', + 'no-interaction', + 'quiet', + 'verbose', + ])->filter()->mapWithKeys(function ($value, $key) { + return ["--{$key}" => $value]; + })->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/CreatesMatchingTest.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/CreatesMatchingTest.php new file mode 100644 index 0000000..a360c28 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/CreatesMatchingTest.php @@ -0,0 +1,44 @@ + 'PHPUnit', 'pest' => 'Pest'] as $option => $name) { + $this->getDefinition()->addOption(new InputOption( + $option, + null, + InputOption::VALUE_NONE, + "Generate an accompanying {$name} test for the {$this->type}" + )); + } + } + + /** + * Create the matching test case if requested. + * + * @param string $path + * @return void + */ + protected function handleTestCreation($path) + { + if (! $this->option('test') && ! $this->option('pest')) { + return; + } + + $this->call('make:test', [ + 'name' => Str::of($path)->after($this->laravel['path'])->beforeLast('.php')->append('Test')->replace('\\', '/'), + '--pest' => $this->option('pest'), + ]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/HasParameters.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/HasParameters.php new file mode 100644 index 0000000..e860ec2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/HasParameters.php @@ -0,0 +1,56 @@ +getArguments() as $arguments) { + if ($arguments instanceof InputArgument) { + $this->getDefinition()->addArgument($arguments); + } else { + $this->addArgument(...array_values($arguments)); + } + } + + foreach ($this->getOptions() as $options) { + if ($options instanceof InputOption) { + $this->getDefinition()->addOption($options); + } else { + $this->addOption(...array_values($options)); + } + } + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return []; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/InteractsWithIO.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/InteractsWithIO.php new file mode 100644 index 0000000..69d295c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Concerns/InteractsWithIO.php @@ -0,0 +1,441 @@ + OutputInterface::VERBOSITY_VERBOSE, + 'vv' => OutputInterface::VERBOSITY_VERY_VERBOSE, + 'vvv' => OutputInterface::VERBOSITY_DEBUG, + 'quiet' => OutputInterface::VERBOSITY_QUIET, + 'normal' => OutputInterface::VERBOSITY_NORMAL, + ]; + + /** + * Determine if the given argument is present. + * + * @param string|int $name + * @return bool + */ + public function hasArgument($name) + { + return $this->input->hasArgument($name); + } + + /** + * Get the value of a command argument. + * + * @param string|null $key + * @return string|array|null + */ + public function argument($key = null) + { + if (is_null($key)) { + return $this->input->getArguments(); + } + + return $this->input->getArgument($key); + } + + /** + * Get all of the arguments passed to the command. + * + * @return array + */ + public function arguments() + { + return $this->argument(); + } + + /** + * Determine if the given option is present. + * + * @param string $name + * @return bool + */ + public function hasOption($name) + { + return $this->input->hasOption($name); + } + + /** + * Get the value of a command option. + * + * @param string|null $key + * @return string|array|bool|null + */ + public function option($key = null) + { + if (is_null($key)) { + return $this->input->getOptions(); + } + + return $this->input->getOption($key); + } + + /** + * Get all of the options passed to the command. + * + * @return array + */ + public function options() + { + return $this->option(); + } + + /** + * Confirm a question with the user. + * + * @param string $question + * @param bool $default + * @return bool + */ + public function confirm($question, $default = false) + { + return $this->output->confirm($question, $default); + } + + /** + * Prompt the user for input. + * + * @param string $question + * @param string|null $default + * @return mixed + */ + public function ask($question, $default = null) + { + return $this->output->ask($question, $default); + } + + /** + * Prompt the user for input with auto completion. + * + * @param string $question + * @param array|callable $choices + * @param string|null $default + * @return mixed + */ + public function anticipate($question, $choices, $default = null) + { + return $this->askWithCompletion($question, $choices, $default); + } + + /** + * Prompt the user for input with auto completion. + * + * @param string $question + * @param array|callable $choices + * @param string|null $default + * @return mixed + */ + public function askWithCompletion($question, $choices, $default = null) + { + $question = new Question($question, $default); + + is_callable($choices) + ? $question->setAutocompleterCallback($choices) + : $question->setAutocompleterValues($choices); + + return $this->output->askQuestion($question); + } + + /** + * Prompt the user for input but hide the answer from the console. + * + * @param string $question + * @param bool $fallback + * @return mixed + */ + public function secret($question, $fallback = true) + { + $question = new Question($question); + + $question->setHidden(true)->setHiddenFallback($fallback); + + return $this->output->askQuestion($question); + } + + /** + * Give the user a single choice from an array of answers. + * + * @param string $question + * @param array $choices + * @param string|null $default + * @param mixed|null $attempts + * @param bool $multiple + * @return string|array + */ + public function choice($question, array $choices, $default = null, $attempts = null, $multiple = false) + { + $question = new ChoiceQuestion($question, $choices, $default); + + $question->setMaxAttempts($attempts)->setMultiselect($multiple); + + return $this->output->askQuestion($question); + } + + /** + * Format input to textual table. + * + * @param array $headers + * @param \Illuminate\Contracts\Support\Arrayable|array $rows + * @param string $tableStyle + * @param array $columnStyles + * @return void + */ + public function table($headers, $rows, $tableStyle = 'default', array $columnStyles = []) + { + $table = new Table($this->output); + + if ($rows instanceof Arrayable) { + $rows = $rows->toArray(); + } + + $table->setHeaders((array) $headers)->setRows($rows)->setStyle($tableStyle); + + foreach ($columnStyles as $columnIndex => $columnStyle) { + $table->setColumnStyle($columnIndex, $columnStyle); + } + + $table->render(); + } + + /** + * Execute a given callback while advancing a progress bar. + * + * @param iterable|int $totalSteps + * @param \Closure $callback + * @return mixed|void + */ + public function withProgressBar($totalSteps, Closure $callback) + { + $bar = $this->output->createProgressBar( + is_iterable($totalSteps) ? count($totalSteps) : $totalSteps + ); + + $bar->start(); + + if (is_iterable($totalSteps)) { + foreach ($totalSteps as $value) { + $callback($value, $bar); + + $bar->advance(); + } + } else { + $callback($bar); + } + + $bar->finish(); + + if (is_iterable($totalSteps)) { + return $totalSteps; + } + } + + /** + * Write a string as information output. + * + * @param string $string + * @param int|string|null $verbosity + * @return void + */ + public function info($string, $verbosity = null) + { + $this->line($string, 'info', $verbosity); + } + + /** + * Write a string as standard output. + * + * @param string $string + * @param string|null $style + * @param int|string|null $verbosity + * @return void + */ + public function line($string, $style = null, $verbosity = null) + { + $styled = $style ? "<$style>$string" : $string; + + $this->output->writeln($styled, $this->parseVerbosity($verbosity)); + } + + /** + * Write a string as comment output. + * + * @param string $string + * @param int|string|null $verbosity + * @return void + */ + public function comment($string, $verbosity = null) + { + $this->line($string, 'comment', $verbosity); + } + + /** + * Write a string as question output. + * + * @param string $string + * @param int|string|null $verbosity + * @return void + */ + public function question($string, $verbosity = null) + { + $this->line($string, 'question', $verbosity); + } + + /** + * Write a string as error output. + * + * @param string $string + * @param int|string|null $verbosity + * @return void + */ + public function error($string, $verbosity = null) + { + $this->line($string, 'error', $verbosity); + } + + /** + * Write a string as warning output. + * + * @param string $string + * @param int|string|null $verbosity + * @return void + */ + public function warn($string, $verbosity = null) + { + if (! $this->output->getFormatter()->hasStyle('warning')) { + $style = new OutputFormatterStyle('yellow'); + + $this->output->getFormatter()->setStyle('warning', $style); + } + + $this->line($string, 'warning', $verbosity); + } + + /** + * Write a string in an alert box. + * + * @param string $string + * @return void + */ + public function alert($string) + { + $length = Str::length(strip_tags($string)) + 12; + + $this->comment(str_repeat('*', $length)); + $this->comment('* '.$string.' *'); + $this->comment(str_repeat('*', $length)); + + $this->newLine(); + } + + /** + * Write a blank line. + * + * @param int $count + * @return void + */ + public function newLine($count = 1) + { + $this->output->newLine($count); + } + + /** + * Set the input interface implementation. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @return void + */ + public function setInput(InputInterface $input) + { + $this->input = $input; + } + + /** + * Set the output interface implementation. + * + * @param \Illuminate\Console\OutputStyle $output + * @return void + */ + public function setOutput(OutputStyle $output) + { + $this->output = $output; + } + + /** + * Set the verbosity level. + * + * @param string|int $level + * @return void + */ + protected function setVerbosity($level) + { + $this->verbosity = $this->parseVerbosity($level); + } + + /** + * Get the verbosity level in terms of Symfony's OutputInterface level. + * + * @param string|int|null $level + * @return int + */ + protected function parseVerbosity($level = null) + { + if (isset($this->verbosityMap[$level])) { + $level = $this->verbosityMap[$level]; + } elseif (! is_int($level)) { + $level = $this->verbosity; + } + + return $level; + } + + /** + * Get the output implementation. + * + * @return \Illuminate\Console\OutputStyle + */ + public function getOutput() + { + return $this->output; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/ConfirmableTrait.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/ConfirmableTrait.php new file mode 100644 index 0000000..8d0d6df --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/ConfirmableTrait.php @@ -0,0 +1,52 @@ +getDefaultConfirmCallback() : $callback; + + $shouldConfirm = value($callback); + + if ($shouldConfirm) { + if ($this->hasOption('force') && $this->option('force')) { + return true; + } + + $this->alert($warning); + + $confirmed = $this->confirm('Do you really wish to run this command?'); + + if (! $confirmed) { + $this->comment('Command Canceled!'); + + return false; + } + } + + return true; + } + + /** + * Get the default confirmation callback. + * + * @return \Closure + */ + protected function getDefaultConfirmCallback() + { + return function () { + return $this->getLaravel()->environment() === 'production'; + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ArtisanStarting.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ArtisanStarting.php new file mode 100644 index 0000000..f228ac5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ArtisanStarting.php @@ -0,0 +1,24 @@ +artisan = $artisan; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/CommandFinished.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/CommandFinished.php new file mode 100644 index 0000000..ef066af --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/CommandFinished.php @@ -0,0 +1,54 @@ +input = $input; + $this->output = $output; + $this->command = $command; + $this->exitCode = $exitCode; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/CommandStarting.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/CommandStarting.php new file mode 100644 index 0000000..c6238b5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/CommandStarting.php @@ -0,0 +1,45 @@ +input = $input; + $this->output = $output; + $this->command = $command; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledBackgroundTaskFinished.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledBackgroundTaskFinished.php new file mode 100644 index 0000000..d9e63c2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledBackgroundTaskFinished.php @@ -0,0 +1,26 @@ +task = $task; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskFailed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskFailed.php new file mode 100644 index 0000000..46857ad --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskFailed.php @@ -0,0 +1,36 @@ +task = $task; + $this->exception = $exception; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskFinished.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskFinished.php new file mode 100644 index 0000000..6146966 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskFinished.php @@ -0,0 +1,35 @@ +task = $task; + $this->runtime = $runtime; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskSkipped.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskSkipped.php new file mode 100644 index 0000000..cfa7141 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskSkipped.php @@ -0,0 +1,26 @@ +task = $task; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskStarting.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskStarting.php new file mode 100644 index 0000000..66aaaa4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Events/ScheduledTaskStarting.php @@ -0,0 +1,26 @@ +task = $task; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/GeneratorCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/GeneratorCommand.php new file mode 100644 index 0000000..5c12e05 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/GeneratorCommand.php @@ -0,0 +1,425 @@ +addTestOptions(); + } + + $this->files = $files; + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + abstract protected function getStub(); + + /** + * Execute the console command. + * + * @return bool|null + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function handle() + { + // First we need to ensure that the given name is not a reserved word within the PHP + // language and that the class name will actually be valid. If it is not valid we + // can error now and prevent from polluting the filesystem using invalid files. + if ($this->isReservedName($this->getNameInput())) { + $this->error('The name "'.$this->getNameInput().'" is reserved by PHP.'); + + return false; + } + + $name = $this->qualifyClass($this->getNameInput()); + + $path = $this->getPath($name); + + // Next, We will check to see if the class already exists. If it does, we don't want + // to create the class and overwrite the user's code. So, we will bail out so the + // code is untouched. Otherwise, we will continue generating this class' files. + if ((! $this->hasOption('force') || + ! $this->option('force')) && + $this->alreadyExists($this->getNameInput())) { + $this->error($this->type.' already exists!'); + + return false; + } + + // Next, we will generate the path to the location where this class' file should get + // written. Then, we will build the class and make the proper replacements on the + // stub files so that it gets the correctly formatted namespace and class name. + $this->makeDirectory($path); + + $this->files->put($path, $this->sortImports($this->buildClass($name))); + + $this->info($this->type.' created successfully.'); + + if (in_array(CreatesMatchingTest::class, class_uses_recursive($this))) { + $this->handleTestCreation($path); + } + } + + /** + * Parse the class name and format according to the root namespace. + * + * @param string $name + * @return string + */ + protected function qualifyClass($name) + { + $name = ltrim($name, '\\/'); + + $name = str_replace('/', '\\', $name); + + $rootNamespace = $this->rootNamespace(); + + if (Str::startsWith($name, $rootNamespace)) { + return $name; + } + + return $this->qualifyClass( + $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name + ); + } + + /** + * Qualify the given model class base name. + * + * @param string $model + * @return string + */ + protected function qualifyModel(string $model) + { + $model = ltrim($model, '\\/'); + + $model = str_replace('/', '\\', $model); + + $rootNamespace = $this->rootNamespace(); + + if (Str::startsWith($model, $rootNamespace)) { + return $model; + } + + return is_dir(app_path('Models')) + ? $rootNamespace.'Models\\'.$model + : $rootNamespace.$model; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace; + } + + /** + * Determine if the class already exists. + * + * @param string $rawName + * @return bool + */ + protected function alreadyExists($rawName) + { + return $this->files->exists($this->getPath($this->qualifyClass($rawName))); + } + + /** + * Get the destination class path. + * + * @param string $name + * @return string + */ + protected function getPath($name) + { + $name = Str::replaceFirst($this->rootNamespace(), '', $name); + + return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php'; + } + + /** + * Build the directory for the class if necessary. + * + * @param string $path + * @return string + */ + protected function makeDirectory($path) + { + if (! $this->files->isDirectory(dirname($path))) { + $this->files->makeDirectory(dirname($path), 0777, true, true); + } + + return $path; + } + + /** + * Build the class with the given name. + * + * @param string $name + * @return string + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + protected function buildClass($name) + { + $stub = $this->files->get($this->getStub()); + + return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name); + } + + /** + * Replace the namespace for the given stub. + * + * @param string $stub + * @param string $name + * @return $this + */ + protected function replaceNamespace(&$stub, $name) + { + $searches = [ + ['DummyNamespace', 'DummyRootNamespace', 'NamespacedDummyUserModel'], + ['{{ namespace }}', '{{ rootNamespace }}', '{{ namespacedUserModel }}'], + ['{{namespace}}', '{{rootNamespace}}', '{{namespacedUserModel}}'], + ]; + + foreach ($searches as $search) { + $stub = str_replace( + $search, + [$this->getNamespace($name), $this->rootNamespace(), $this->userProviderModel()], + $stub + ); + } + + return $this; + } + + /** + * Get the full namespace for a given class, without the class name. + * + * @param string $name + * @return string + */ + protected function getNamespace($name) + { + return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\'); + } + + /** + * Replace the class name for the given stub. + * + * @param string $stub + * @param string $name + * @return string + */ + protected function replaceClass($stub, $name) + { + $class = str_replace($this->getNamespace($name).'\\', '', $name); + + return str_replace(['DummyClass', '{{ class }}', '{{class}}'], $class, $stub); + } + + /** + * Alphabetically sorts the imports for the given stub. + * + * @param string $stub + * @return string + */ + protected function sortImports($stub) + { + if (preg_match('/(?P(?:use [^;]+;$\n?)+)/m', $stub, $match)) { + $imports = explode("\n", trim($match['imports'])); + + sort($imports); + + return str_replace(trim($match['imports']), implode("\n", $imports), $stub); + } + + return $stub; + } + + /** + * Get the desired class name from the input. + * + * @return string + */ + protected function getNameInput() + { + return trim($this->argument('name')); + } + + /** + * Get the root namespace for the class. + * + * @return string + */ + protected function rootNamespace() + { + return $this->laravel->getNamespace(); + } + + /** + * Get the model for the default guard's user provider. + * + * @return string|null + */ + protected function userProviderModel() + { + $config = $this->laravel['config']; + + $provider = $config->get('auth.guards.'.$config->get('auth.defaults.guard').'.provider'); + + return $config->get("auth.providers.{$provider}.model"); + } + + /** + * Checks whether the given name is reserved. + * + * @param string $name + * @return bool + */ + protected function isReservedName($name) + { + $name = strtolower($name); + + return in_array($name, $this->reservedNames); + } + + /** + * Get the first view directory path from the application configuration. + * + * @param string $path + * @return string + */ + protected function viewPath($path = '') + { + $views = $this->laravel['config']['view.paths'][0] ?? resource_path('views'); + + return $views.($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the class'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/OutputStyle.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/OutputStyle.php new file mode 100644 index 0000000..1e7c153 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/OutputStyle.php @@ -0,0 +1,81 @@ +output = $output; + + parent::__construct($input, $output); + } + + /** + * Returns whether verbosity is quiet (-q). + * + * @return bool + */ + public function isQuiet() + { + return $this->output->isQuiet(); + } + + /** + * Returns whether verbosity is verbose (-v). + * + * @return bool + */ + public function isVerbose() + { + return $this->output->isVerbose(); + } + + /** + * Returns whether verbosity is very verbose (-vv). + * + * @return bool + */ + public function isVeryVerbose() + { + return $this->output->isVeryVerbose(); + } + + /** + * Returns whether verbosity is debug (-vvv). + * + * @return bool + */ + public function isDebug() + { + return $this->output->isDebug(); + } + + /** + * Get the underlying Symfony output implementation. + * + * @return \Symfony\Component\Console\Output\OutputInterface + */ + public function getOutput() + { + return $this->output; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Parser.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Parser.php new file mode 100644 index 0000000..00dca1c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Parser.php @@ -0,0 +1,144 @@ +cache = $cache; + } + + /** + * Attempt to obtain an event mutex for the given event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return bool + */ + public function create(Event $event) + { + return $this->cache->store($this->store)->add( + $event->mutexName(), true, $event->expiresAt * 60 + ); + } + + /** + * Determine if an event mutex exists for the given event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return bool + */ + public function exists(Event $event) + { + return $this->cache->store($this->store)->has($event->mutexName()); + } + + /** + * Clear the event mutex for the given event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return void + */ + public function forget(Event $event) + { + $this->cache->store($this->store)->forget($event->mutexName()); + } + + /** + * Specify the cache store that should be used. + * + * @param string $store + * @return $this + */ + public function useStore($store) + { + $this->store = $store; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CacheSchedulingMutex.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CacheSchedulingMutex.php new file mode 100644 index 0000000..ca8e2cb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CacheSchedulingMutex.php @@ -0,0 +1,75 @@ +cache = $cache; + } + + /** + * Attempt to obtain a scheduling mutex for the given event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @param \DateTimeInterface $time + * @return bool + */ + public function create(Event $event, DateTimeInterface $time) + { + return $this->cache->store($this->store)->add( + $event->mutexName().$time->format('Hi'), true, 3600 + ); + } + + /** + * Determine if a scheduling mutex exists for the given event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @param \DateTimeInterface $time + * @return bool + */ + public function exists(Event $event, DateTimeInterface $time) + { + return $this->cache->store($this->store)->has( + $event->mutexName().$time->format('Hi') + ); + } + + /** + * Specify the cache store that should be used. + * + * @param string $store + * @return $this + */ + public function useStore($store) + { + $this->store = $store; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CallbackEvent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CallbackEvent.php new file mode 100644 index 0000000..dde5d7d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CallbackEvent.php @@ -0,0 +1,176 @@ +mutex = $mutex; + $this->callback = $callback; + $this->parameters = $parameters; + $this->timezone = $timezone; + } + + /** + * Run the given event. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return mixed + * + * @throws \Exception + */ + public function run(Container $container) + { + if ($this->description && $this->withoutOverlapping && + ! $this->mutex->create($this)) { + return; + } + + $pid = getmypid(); + + register_shutdown_function(function () use ($pid) { + if ($pid === getmypid()) { + $this->removeMutex(); + } + }); + + parent::callBeforeCallbacks($container); + + try { + $response = is_object($this->callback) + ? $container->call([$this->callback, '__invoke'], $this->parameters) + : $container->call($this->callback, $this->parameters); + + $this->exitCode = $response === false ? 1 : 0; + } catch (Throwable $e) { + $this->exitCode = 1; + + throw $e; + } finally { + $this->removeMutex(); + + parent::callAfterCallbacks($container); + } + + return $response; + } + + /** + * Clear the mutex for the event. + * + * @return void + */ + protected function removeMutex() + { + if ($this->description && $this->withoutOverlapping) { + $this->mutex->forget($this); + } + } + + /** + * Do not allow the event to overlap each other. + * + * @param int $expiresAt + * @return $this + * + * @throws \LogicException + */ + public function withoutOverlapping($expiresAt = 1440) + { + if (! isset($this->description)) { + throw new LogicException( + "A scheduled event name is required to prevent overlapping. Use the 'name' method before 'withoutOverlapping'." + ); + } + + $this->withoutOverlapping = true; + + $this->expiresAt = $expiresAt; + + return $this->skip(function () { + return $this->mutex->exists($this); + }); + } + + /** + * Allow the event to only run on one server for each cron expression. + * + * @return $this + * + * @throws \LogicException + */ + public function onOneServer() + { + if (! isset($this->description)) { + throw new LogicException( + "A scheduled event name is required to only run on one server. Use the 'name' method before 'onOneServer'." + ); + } + + $this->onOneServer = true; + + return $this; + } + + /** + * Get the mutex name for the scheduled command. + * + * @return string + */ + public function mutexName() + { + return 'framework/schedule-'.sha1($this->description); + } + + /** + * Get the summary of the event for display. + * + * @return string + */ + public function getSummaryForDisplay() + { + if (is_string($this->description)) { + return $this->description; + } + + return is_string($this->callback) ? $this->callback : 'Callback'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CommandBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CommandBuilder.php new file mode 100644 index 0000000..ee13c5e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CommandBuilder.php @@ -0,0 +1,75 @@ +runInBackground) { + return $this->buildBackgroundCommand($event); + } + + return $this->buildForegroundCommand($event); + } + + /** + * Build the command for running the event in the foreground. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return string + */ + protected function buildForegroundCommand(Event $event) + { + $output = ProcessUtils::escapeArgument($event->output); + + return $this->ensureCorrectUser( + $event, $event->command.($event->shouldAppendOutput ? ' >> ' : ' > ').$output.' 2>&1' + ); + } + + /** + * Build the command for running the event in the background. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return string + */ + protected function buildBackgroundCommand(Event $event) + { + $output = ProcessUtils::escapeArgument($event->output); + + $redirect = $event->shouldAppendOutput ? ' >> ' : ' > '; + + $finished = Application::formatCommandString('schedule:finish').' "'.$event->mutexName().'"'; + + if (windows_os()) { + return 'start /b cmd /v:on /c "('.$event->command.' & '.$finished.' ^!ERRORLEVEL^!)'.$redirect.$output.' 2>&1"'; + } + + return $this->ensureCorrectUser($event, + '('.$event->command.$redirect.$output.' 2>&1 ; '.$finished.' "$?") > ' + .ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &' + ); + } + + /** + * Finalize the event's command syntax with the correct user. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @param string $command + * @return string + */ + protected function ensureCorrectUser(Event $event, $command) + { + return $event->user && ! windows_os() ? 'sudo -u '.$event->user.' -- sh -c \''.$command.'\'' : $command; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Event.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Event.php new file mode 100644 index 0000000..4de88f1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Event.php @@ -0,0 +1,945 @@ +mutex = $mutex; + $this->command = $command; + $this->timezone = $timezone; + + $this->output = $this->getDefaultOutput(); + } + + /** + * Get the default output depending on the OS. + * + * @return string + */ + public function getDefaultOutput() + { + return (DIRECTORY_SEPARATOR === '\\') ? 'NUL' : '/dev/null'; + } + + /** + * Run the given event. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function run(Container $container) + { + if ($this->withoutOverlapping && + ! $this->mutex->create($this)) { + return; + } + + $this->runInBackground + ? $this->runCommandInBackground($container) + : $this->runCommandInForeground($container); + } + + /** + * Get the mutex name for the scheduled command. + * + * @return string + */ + public function mutexName() + { + return 'framework'.DIRECTORY_SEPARATOR.'schedule-'.sha1($this->expression.$this->command); + } + + /** + * Run the command in the foreground. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + protected function runCommandInForeground(Container $container) + { + try { + $this->callBeforeCallbacks($container); + + $this->exitCode = Process::fromShellCommandline( + $this->buildCommand(), base_path(), null, null, null + )->run(); + + $this->callAfterCallbacks($container); + } finally { + $this->removeMutex(); + } + } + + /** + * Run the command in the background. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + protected function runCommandInBackground(Container $container) + { + try { + $this->callBeforeCallbacks($container); + + Process::fromShellCommandline($this->buildCommand(), base_path(), null, null, null)->run(); + } catch (Throwable $exception) { + $this->removeMutex(); + + throw $exception; + } + } + + /** + * Call all of the "before" callbacks for the event. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function callBeforeCallbacks(Container $container) + { + foreach ($this->beforeCallbacks as $callback) { + $container->call($callback); + } + } + + /** + * Call all of the "after" callbacks for the event. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function callAfterCallbacks(Container $container) + { + foreach ($this->afterCallbacks as $callback) { + $container->call($callback); + } + } + + /** + * Call all of the "after" callbacks for the event. + * + * @param \Illuminate\Contracts\Container\Container $container + * @param int $exitCode + * @return void + */ + public function callAfterCallbacksWithExitCode(Container $container, $exitCode) + { + $this->exitCode = (int) $exitCode; + + try { + $this->callAfterCallbacks($container); + } finally { + $this->removeMutex(); + } + } + + /** + * Build the command string. + * + * @return string + */ + public function buildCommand() + { + return (new CommandBuilder)->buildCommand($this); + } + + /** + * Determine if the given event should run based on the Cron expression. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return bool + */ + public function isDue($app) + { + if (! $this->runsInMaintenanceMode() && $app->isDownForMaintenance()) { + return false; + } + + return $this->expressionPasses() && + $this->runsInEnvironment($app->environment()); + } + + /** + * Determine if the event runs in maintenance mode. + * + * @return bool + */ + public function runsInMaintenanceMode() + { + return $this->evenInMaintenanceMode; + } + + /** + * Determine if the Cron expression passes. + * + * @return bool + */ + protected function expressionPasses() + { + $date = Date::now(); + + if ($this->timezone) { + $date = $date->setTimezone($this->timezone); + } + + return (new CronExpression($this->expression))->isDue($date->toDateTimeString()); + } + + /** + * Determine if the event runs in the given environment. + * + * @param string $environment + * @return bool + */ + public function runsInEnvironment($environment) + { + return empty($this->environments) || in_array($environment, $this->environments); + } + + /** + * Determine if the filters pass for the event. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return bool + */ + public function filtersPass($app) + { + foreach ($this->filters as $callback) { + if (! $app->call($callback)) { + return false; + } + } + + foreach ($this->rejects as $callback) { + if ($app->call($callback)) { + return false; + } + } + + return true; + } + + /** + * Ensure that the output is stored on disk in a log file. + * + * @return $this + */ + public function storeOutput() + { + $this->ensureOutputIsBeingCaptured(); + + return $this; + } + + /** + * Send the output of the command to a given location. + * + * @param string $location + * @param bool $append + * @return $this + */ + public function sendOutputTo($location, $append = false) + { + $this->output = $location; + + $this->shouldAppendOutput = $append; + + return $this; + } + + /** + * Append the output of the command to a given location. + * + * @param string $location + * @return $this + */ + public function appendOutputTo($location) + { + return $this->sendOutputTo($location, true); + } + + /** + * E-mail the results of the scheduled operation. + * + * @param array|mixed $addresses + * @param bool $onlyIfOutputExists + * @return $this + * + * @throws \LogicException + */ + public function emailOutputTo($addresses, $onlyIfOutputExists = false) + { + $this->ensureOutputIsBeingCaptured(); + + $addresses = Arr::wrap($addresses); + + return $this->then(function (Mailer $mailer) use ($addresses, $onlyIfOutputExists) { + $this->emailOutput($mailer, $addresses, $onlyIfOutputExists); + }); + } + + /** + * E-mail the results of the scheduled operation if it produces output. + * + * @param array|mixed $addresses + * @return $this + * + * @throws \LogicException + */ + public function emailWrittenOutputTo($addresses) + { + return $this->emailOutputTo($addresses, true); + } + + /** + * E-mail the results of the scheduled operation if it fails. + * + * @param array|mixed $addresses + * @return $this + */ + public function emailOutputOnFailure($addresses) + { + $this->ensureOutputIsBeingCaptured(); + + $addresses = Arr::wrap($addresses); + + return $this->onFailure(function (Mailer $mailer) use ($addresses) { + $this->emailOutput($mailer, $addresses, false); + }); + } + + /** + * Ensure that the command output is being captured. + * + * @return void + */ + protected function ensureOutputIsBeingCaptured() + { + if (is_null($this->output) || $this->output == $this->getDefaultOutput()) { + $this->sendOutputTo(storage_path('logs/schedule-'.sha1($this->mutexName()).'.log')); + } + } + + /** + * E-mail the output of the event to the recipients. + * + * @param \Illuminate\Contracts\Mail\Mailer $mailer + * @param array $addresses + * @param bool $onlyIfOutputExists + * @return void + */ + protected function emailOutput(Mailer $mailer, $addresses, $onlyIfOutputExists = false) + { + $text = is_file($this->output) ? file_get_contents($this->output) : ''; + + if ($onlyIfOutputExists && empty($text)) { + return; + } + + $mailer->raw($text, function ($m) use ($addresses) { + $m->to($addresses)->subject($this->getEmailSubject()); + }); + } + + /** + * Get the e-mail subject line for output results. + * + * @return string + */ + protected function getEmailSubject() + { + if ($this->description) { + return $this->description; + } + + return "Scheduled Job Output For [{$this->command}]"; + } + + /** + * Register a callback to ping a given URL before the job runs. + * + * @param string $url + * @return $this + */ + public function pingBefore($url) + { + return $this->before($this->pingCallback($url)); + } + + /** + * Register a callback to ping a given URL before the job runs if the given condition is true. + * + * @param bool $value + * @param string $url + * @return $this + */ + public function pingBeforeIf($value, $url) + { + return $value ? $this->pingBefore($url) : $this; + } + + /** + * Register a callback to ping a given URL after the job runs. + * + * @param string $url + * @return $this + */ + public function thenPing($url) + { + return $this->then($this->pingCallback($url)); + } + + /** + * Register a callback to ping a given URL after the job runs if the given condition is true. + * + * @param bool $value + * @param string $url + * @return $this + */ + public function thenPingIf($value, $url) + { + return $value ? $this->thenPing($url) : $this; + } + + /** + * Register a callback to ping a given URL if the operation succeeds. + * + * @param string $url + * @return $this + */ + public function pingOnSuccess($url) + { + return $this->onSuccess($this->pingCallback($url)); + } + + /** + * Register a callback to ping a given URL if the operation fails. + * + * @param string $url + * @return $this + */ + public function pingOnFailure($url) + { + return $this->onFailure($this->pingCallback($url)); + } + + /** + * Get the callback that pings the given URL. + * + * @param string $url + * @return \Closure + */ + protected function pingCallback($url) + { + return function (Container $container, HttpClient $http) use ($url) { + try { + $http->request('GET', $url); + } catch (ClientExceptionInterface|TransferException $e) { + $container->make(ExceptionHandler::class)->report($e); + } + }; + } + + /** + * State that the command should run in the background. + * + * @return $this + */ + public function runInBackground() + { + $this->runInBackground = true; + + return $this; + } + + /** + * Set which user the command should run as. + * + * @param string $user + * @return $this + */ + public function user($user) + { + $this->user = $user; + + return $this; + } + + /** + * Limit the environments the command should run in. + * + * @param array|mixed $environments + * @return $this + */ + public function environments($environments) + { + $this->environments = is_array($environments) ? $environments : func_get_args(); + + return $this; + } + + /** + * State that the command should run even in maintenance mode. + * + * @return $this + */ + public function evenInMaintenanceMode() + { + $this->evenInMaintenanceMode = true; + + return $this; + } + + /** + * Do not allow the event to overlap each other. + * + * @param int $expiresAt + * @return $this + */ + public function withoutOverlapping($expiresAt = 1440) + { + $this->withoutOverlapping = true; + + $this->expiresAt = $expiresAt; + + return $this->skip(function () { + return $this->mutex->exists($this); + }); + } + + /** + * Allow the event to only run on one server for each cron expression. + * + * @return $this + */ + public function onOneServer() + { + $this->onOneServer = true; + + return $this; + } + + /** + * Register a callback to further filter the schedule. + * + * @param \Closure|bool $callback + * @return $this + */ + public function when($callback) + { + $this->filters[] = Reflector::isCallable($callback) ? $callback : function () use ($callback) { + return $callback; + }; + + return $this; + } + + /** + * Register a callback to further filter the schedule. + * + * @param \Closure|bool $callback + * @return $this + */ + public function skip($callback) + { + $this->rejects[] = Reflector::isCallable($callback) ? $callback : function () use ($callback) { + return $callback; + }; + + return $this; + } + + /** + * Register a callback to be called before the operation. + * + * @param \Closure $callback + * @return $this + */ + public function before(Closure $callback) + { + $this->beforeCallbacks[] = $callback; + + return $this; + } + + /** + * Register a callback to be called after the operation. + * + * @param \Closure $callback + * @return $this + */ + public function after(Closure $callback) + { + return $this->then($callback); + } + + /** + * Register a callback to be called after the operation. + * + * @param \Closure $callback + * @return $this + */ + public function then(Closure $callback) + { + $parameters = $this->closureParameterTypes($callback); + + if (Arr::get($parameters, 'output') === Stringable::class) { + return $this->thenWithOutput($callback); + } + + $this->afterCallbacks[] = $callback; + + return $this; + } + + /** + * Register a callback that uses the output after the job runs. + * + * @param \Closure $callback + * @param bool $onlyIfOutputExists + * @return $this + */ + public function thenWithOutput(Closure $callback, $onlyIfOutputExists = false) + { + $this->ensureOutputIsBeingCaptured(); + + return $this->then($this->withOutputCallback($callback, $onlyIfOutputExists)); + } + + /** + * Register a callback to be called if the operation succeeds. + * + * @param \Closure $callback + * @return $this + */ + public function onSuccess(Closure $callback) + { + $parameters = $this->closureParameterTypes($callback); + + if (Arr::get($parameters, 'output') === Stringable::class) { + return $this->onSuccessWithOutput($callback); + } + + return $this->then(function (Container $container) use ($callback) { + if (0 === $this->exitCode) { + $container->call($callback); + } + }); + } + + /** + * Register a callback that uses the output if the operation succeeds. + * + * @param \Closure $callback + * @param bool $onlyIfOutputExists + * @return $this + */ + public function onSuccessWithOutput(Closure $callback, $onlyIfOutputExists = false) + { + $this->ensureOutputIsBeingCaptured(); + + return $this->onSuccess($this->withOutputCallback($callback, $onlyIfOutputExists)); + } + + /** + * Register a callback to be called if the operation fails. + * + * @param \Closure $callback + * @return $this + */ + public function onFailure(Closure $callback) + { + $parameters = $this->closureParameterTypes($callback); + + if (Arr::get($parameters, 'output') === Stringable::class) { + return $this->onFailureWithOutput($callback); + } + + return $this->then(function (Container $container) use ($callback) { + if (0 !== $this->exitCode) { + $container->call($callback); + } + }); + } + + /** + * Register a callback that uses the output if the operation fails. + * + * @param \Closure $callback + * @param bool $onlyIfOutputExists + * @return $this + */ + public function onFailureWithOutput(Closure $callback, $onlyIfOutputExists = false) + { + $this->ensureOutputIsBeingCaptured(); + + return $this->onFailure($this->withOutputCallback($callback, $onlyIfOutputExists)); + } + + /** + * Get a callback that provides output. + * + * @param \Closure $callback + * @param bool $onlyIfOutputExists + * @return \Closure + */ + protected function withOutputCallback(Closure $callback, $onlyIfOutputExists = false) + { + return function (Container $container) use ($callback, $onlyIfOutputExists) { + $output = $this->output && is_file($this->output) ? file_get_contents($this->output) : ''; + + return $onlyIfOutputExists && empty($output) + ? null + : $container->call($callback, ['output' => new Stringable($output)]); + }; + } + + /** + * Set the human-friendly description of the event. + * + * @param string $description + * @return $this + */ + public function name($description) + { + return $this->description($description); + } + + /** + * Set the human-friendly description of the event. + * + * @param string $description + * @return $this + */ + public function description($description) + { + $this->description = $description; + + return $this; + } + + /** + * Get the summary of the event for display. + * + * @return string + */ + public function getSummaryForDisplay() + { + if (is_string($this->description)) { + return $this->description; + } + + return $this->buildCommand(); + } + + /** + * Determine the next due date for an event. + * + * @param \DateTimeInterface|string $currentTime + * @param int $nth + * @param bool $allowCurrentDate + * @return \Illuminate\Support\Carbon + */ + public function nextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false) + { + return Date::instance((new CronExpression($this->getExpression())) + ->getNextRunDate($currentTime, $nth, $allowCurrentDate, $this->timezone)); + } + + /** + * Get the Cron expression for the event. + * + * @return string + */ + public function getExpression() + { + return $this->expression; + } + + /** + * Set the event mutex implementation to be used. + * + * @param \Illuminate\Console\Scheduling\EventMutex $mutex + * @return $this + */ + public function preventOverlapsUsing(EventMutex $mutex) + { + $this->mutex = $mutex; + + return $this; + } + + /** + * Delete the mutex for the event. + * + * @return void + */ + protected function removeMutex() + { + if ($this->withoutOverlapping) { + $this->mutex->forget($this); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/EventMutex.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/EventMutex.php new file mode 100644 index 0000000..1840e24 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/EventMutex.php @@ -0,0 +1,30 @@ +expression = $expression; + + return $this; + } + + /** + * Schedule the event to run between start and end time. + * + * @param string $startTime + * @param string $endTime + * @return $this + */ + public function between($startTime, $endTime) + { + return $this->when($this->inTimeInterval($startTime, $endTime)); + } + + /** + * Schedule the event to not run between start and end time. + * + * @param string $startTime + * @param string $endTime + * @return $this + */ + public function unlessBetween($startTime, $endTime) + { + return $this->skip($this->inTimeInterval($startTime, $endTime)); + } + + /** + * Schedule the event to run between start and end time. + * + * @param string $startTime + * @param string $endTime + * @return \Closure + */ + private function inTimeInterval($startTime, $endTime) + { + [$now, $startTime, $endTime] = [ + Carbon::now($this->timezone), + Carbon::parse($startTime, $this->timezone), + Carbon::parse($endTime, $this->timezone), + ]; + + if ($endTime->lessThan($startTime)) { + if ($startTime->greaterThan($now)) { + $startTime->subDay(1); + } else { + $endTime->addDay(1); + } + } + + return function () use ($now, $startTime, $endTime) { + return $now->between($startTime, $endTime); + }; + } + + /** + * Schedule the event to run every minute. + * + * @return $this + */ + public function everyMinute() + { + return $this->spliceIntoPosition(1, '*'); + } + + /** + * Schedule the event to run every two minutes. + * + * @return $this + */ + public function everyTwoMinutes() + { + return $this->spliceIntoPosition(1, '*/2'); + } + + /** + * Schedule the event to run every three minutes. + * + * @return $this + */ + public function everyThreeMinutes() + { + return $this->spliceIntoPosition(1, '*/3'); + } + + /** + * Schedule the event to run every four minutes. + * + * @return $this + */ + public function everyFourMinutes() + { + return $this->spliceIntoPosition(1, '*/4'); + } + + /** + * Schedule the event to run every five minutes. + * + * @return $this + */ + public function everyFiveMinutes() + { + return $this->spliceIntoPosition(1, '*/5'); + } + + /** + * Schedule the event to run every ten minutes. + * + * @return $this + */ + public function everyTenMinutes() + { + return $this->spliceIntoPosition(1, '*/10'); + } + + /** + * Schedule the event to run every fifteen minutes. + * + * @return $this + */ + public function everyFifteenMinutes() + { + return $this->spliceIntoPosition(1, '*/15'); + } + + /** + * Schedule the event to run every thirty minutes. + * + * @return $this + */ + public function everyThirtyMinutes() + { + return $this->spliceIntoPosition(1, '0,30'); + } + + /** + * Schedule the event to run hourly. + * + * @return $this + */ + public function hourly() + { + return $this->spliceIntoPosition(1, 0); + } + + /** + * Schedule the event to run hourly at a given offset in the hour. + * + * @param array|int $offset + * @return $this + */ + public function hourlyAt($offset) + { + $offset = is_array($offset) ? implode(',', $offset) : $offset; + + return $this->spliceIntoPosition(1, $offset); + } + + /** + * Schedule the event to run every two hours. + * + * @return $this + */ + public function everyTwoHours() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, '*/2'); + } + + /** + * Schedule the event to run every three hours. + * + * @return $this + */ + public function everyThreeHours() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, '*/3'); + } + + /** + * Schedule the event to run every four hours. + * + * @return $this + */ + public function everyFourHours() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, '*/4'); + } + + /** + * Schedule the event to run every six hours. + * + * @return $this + */ + public function everySixHours() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, '*/6'); + } + + /** + * Schedule the event to run daily. + * + * @return $this + */ + public function daily() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, 0); + } + + /** + * Schedule the command at a given time. + * + * @param string $time + * @return $this + */ + public function at($time) + { + return $this->dailyAt($time); + } + + /** + * Schedule the event to run daily at a given time (10:00, 19:30, etc). + * + * @param string $time + * @return $this + */ + public function dailyAt($time) + { + $segments = explode(':', $time); + + return $this->spliceIntoPosition(2, (int) $segments[0]) + ->spliceIntoPosition(1, count($segments) === 2 ? (int) $segments[1] : '0'); + } + + /** + * Schedule the event to run twice daily. + * + * @param int $first + * @param int $second + * @return $this + */ + public function twiceDaily($first = 1, $second = 13) + { + return $this->twiceDailyAt($first, $second, 0); + } + + /** + * Schedule the event to run twice daily at a given offset. + * + * @param int $first + * @param int $second + * @param int $offset + * @return $this + */ + public function twiceDailyAt($first = 1, $second = 13, $offset = 0) + { + $hours = $first.','.$second; + + return $this->spliceIntoPosition(1, $offset) + ->spliceIntoPosition(2, $hours); + } + + /** + * Schedule the event to run only on weekdays. + * + * @return $this + */ + public function weekdays() + { + return $this->days(Schedule::MONDAY.'-'.Schedule::FRIDAY); + } + + /** + * Schedule the event to run only on weekends. + * + * @return $this + */ + public function weekends() + { + return $this->days(Schedule::SATURDAY.','.Schedule::SUNDAY); + } + + /** + * Schedule the event to run only on Mondays. + * + * @return $this + */ + public function mondays() + { + return $this->days(Schedule::MONDAY); + } + + /** + * Schedule the event to run only on Tuesdays. + * + * @return $this + */ + public function tuesdays() + { + return $this->days(Schedule::TUESDAY); + } + + /** + * Schedule the event to run only on Wednesdays. + * + * @return $this + */ + public function wednesdays() + { + return $this->days(Schedule::WEDNESDAY); + } + + /** + * Schedule the event to run only on Thursdays. + * + * @return $this + */ + public function thursdays() + { + return $this->days(Schedule::THURSDAY); + } + + /** + * Schedule the event to run only on Fridays. + * + * @return $this + */ + public function fridays() + { + return $this->days(Schedule::FRIDAY); + } + + /** + * Schedule the event to run only on Saturdays. + * + * @return $this + */ + public function saturdays() + { + return $this->days(Schedule::SATURDAY); + } + + /** + * Schedule the event to run only on Sundays. + * + * @return $this + */ + public function sundays() + { + return $this->days(Schedule::SUNDAY); + } + + /** + * Schedule the event to run weekly. + * + * @return $this + */ + public function weekly() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, 0) + ->spliceIntoPosition(5, 0); + } + + /** + * Schedule the event to run weekly on a given day and time. + * + * @param array|mixed $dayOfWeek + * @param string $time + * @return $this + */ + public function weeklyOn($dayOfWeek, $time = '0:0') + { + $this->dailyAt($time); + + return $this->days($dayOfWeek); + } + + /** + * Schedule the event to run monthly. + * + * @return $this + */ + public function monthly() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, 0) + ->spliceIntoPosition(3, 1); + } + + /** + * Schedule the event to run monthly on a given day and time. + * + * @param int $dayOfMonth + * @param string $time + * @return $this + */ + public function monthlyOn($dayOfMonth = 1, $time = '0:0') + { + $this->dailyAt($time); + + return $this->spliceIntoPosition(3, $dayOfMonth); + } + + /** + * Schedule the event to run twice monthly at a given time. + * + * @param int $first + * @param int $second + * @param string $time + * @return $this + */ + public function twiceMonthly($first = 1, $second = 16, $time = '0:0') + { + $daysOfMonth = $first.','.$second; + + $this->dailyAt($time); + + return $this->spliceIntoPosition(3, $daysOfMonth); + } + + /** + * Schedule the event to run on the last day of the month. + * + * @param string $time + * @return $this + */ + public function lastDayOfMonth($time = '0:0') + { + $this->dailyAt($time); + + return $this->spliceIntoPosition(3, Carbon::now()->endOfMonth()->day); + } + + /** + * Schedule the event to run quarterly. + * + * @return $this + */ + public function quarterly() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, 0) + ->spliceIntoPosition(3, 1) + ->spliceIntoPosition(4, '1-12/3'); + } + + /** + * Schedule the event to run yearly. + * + * @return $this + */ + public function yearly() + { + return $this->spliceIntoPosition(1, 0) + ->spliceIntoPosition(2, 0) + ->spliceIntoPosition(3, 1) + ->spliceIntoPosition(4, 1); + } + + /** + * Schedule the event to run yearly on a given month, day, and time. + * + * @param int $month + * @param int|string $dayOfMonth + * @param string $time + * @return $this + */ + public function yearlyOn($month = 1, $dayOfMonth = 1, $time = '0:0') + { + $this->dailyAt($time); + + return $this->spliceIntoPosition(3, $dayOfMonth) + ->spliceIntoPosition(4, $month); + } + + /** + * Set the days of the week the command should run on. + * + * @param array|mixed $days + * @return $this + */ + public function days($days) + { + $days = is_array($days) ? $days : func_get_args(); + + return $this->spliceIntoPosition(5, implode(',', $days)); + } + + /** + * Set the timezone the date should be evaluated on. + * + * @param \DateTimeZone|string $timezone + * @return $this + */ + public function timezone($timezone) + { + $this->timezone = $timezone; + + return $this; + } + + /** + * Splice the given value into the given position of the expression. + * + * @param int $position + * @param string $value + * @return $this + */ + protected function spliceIntoPosition($position, $value) + { + $segments = explode(' ', $this->expression); + + $segments[$position - 1] = $value; + + return $this->cron(implode(' ', $segments)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Schedule.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Schedule.php new file mode 100644 index 0000000..ee5412b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Schedule.php @@ -0,0 +1,362 @@ +timezone = $timezone; + + if (! class_exists(Container::class)) { + throw new RuntimeException( + 'A container implementation is required to use the scheduler. Please install the illuminate/container package.' + ); + } + + $container = Container::getInstance(); + + $this->eventMutex = $container->bound(EventMutex::class) + ? $container->make(EventMutex::class) + : $container->make(CacheEventMutex::class); + + $this->schedulingMutex = $container->bound(SchedulingMutex::class) + ? $container->make(SchedulingMutex::class) + : $container->make(CacheSchedulingMutex::class); + } + + /** + * Add a new callback event to the schedule. + * + * @param string|callable $callback + * @param array $parameters + * @return \Illuminate\Console\Scheduling\CallbackEvent + */ + public function call($callback, array $parameters = []) + { + $this->events[] = $event = new CallbackEvent( + $this->eventMutex, $callback, $parameters, $this->timezone + ); + + return $event; + } + + /** + * Add a new Artisan command event to the schedule. + * + * @param string $command + * @param array $parameters + * @return \Illuminate\Console\Scheduling\Event + */ + public function command($command, array $parameters = []) + { + if (class_exists($command)) { + $command = Container::getInstance()->make($command); + + return $this->exec( + Application::formatCommandString($command->getName()), $parameters, + )->description($command->getDescription()); + } + + return $this->exec( + Application::formatCommandString($command), $parameters + ); + } + + /** + * Add a new job callback event to the schedule. + * + * @param object|string $job + * @param string|null $queue + * @param string|null $connection + * @return \Illuminate\Console\Scheduling\CallbackEvent + */ + public function job($job, $queue = null, $connection = null) + { + return $this->call(function () use ($job, $queue, $connection) { + $job = is_string($job) ? Container::getInstance()->make($job) : $job; + + if ($job instanceof ShouldQueue) { + $this->dispatchToQueue($job, $queue ?? $job->queue, $connection ?? $job->connection); + } else { + $this->dispatchNow($job); + } + })->name(is_string($job) ? $job : get_class($job)); + } + + /** + * Dispatch the given job to the queue. + * + * @param object $job + * @param string|null $queue + * @param string|null $connection + * @return void + * + * @throws \RuntimeException + */ + protected function dispatchToQueue($job, $queue, $connection) + { + if ($job instanceof Closure) { + if (! class_exists(CallQueuedClosure::class)) { + throw new RuntimeException( + 'To enable support for closure jobs, please install the illuminate/queue package.' + ); + } + + $job = CallQueuedClosure::create($job); + } + + if ($job instanceof ShouldBeUnique) { + return $this->dispatchUniqueJobToQueue($job, $queue, $connection); + } + + $this->getDispatcher()->dispatch( + $job->onConnection($connection)->onQueue($queue) + ); + } + + /** + * Dispatch the given unique job to the queue. + * + * @param object $job + * @param string|null $queue + * @param string|null $connection + * @return void + * + * @throws \RuntimeException + */ + protected function dispatchUniqueJobToQueue($job, $queue, $connection) + { + if (! Container::getInstance()->bound(Cache::class)) { + throw new RuntimeException('Cache driver not available. Scheduling unique jobs not supported.'); + } + + if (! (new UniqueLock(Container::getInstance()->make(Cache::class)))->acquire($job)) { + return; + } + + $this->getDispatcher()->dispatch( + $job->onConnection($connection)->onQueue($queue) + ); + } + + /** + * Dispatch the given job right now. + * + * @param object $job + * @return void + */ + protected function dispatchNow($job) + { + $this->getDispatcher()->dispatchNow($job); + } + + /** + * Add a new command event to the schedule. + * + * @param string $command + * @param array $parameters + * @return \Illuminate\Console\Scheduling\Event + */ + public function exec($command, array $parameters = []) + { + if (count($parameters)) { + $command .= ' '.$this->compileParameters($parameters); + } + + $this->events[] = $event = new Event($this->eventMutex, $command, $this->timezone); + + return $event; + } + + /** + * Compile parameters for a command. + * + * @param array $parameters + * @return string + */ + protected function compileParameters(array $parameters) + { + return collect($parameters)->map(function ($value, $key) { + if (is_array($value)) { + return $this->compileArrayInput($key, $value); + } + + if (! is_numeric($value) && ! preg_match('/^(-.$|--.*)/i', $value)) { + $value = ProcessUtils::escapeArgument($value); + } + + return is_numeric($key) ? $value : "{$key}={$value}"; + })->implode(' '); + } + + /** + * Compile array input for a command. + * + * @param string|int $key + * @param array $value + * @return string + */ + public function compileArrayInput($key, $value) + { + $value = collect($value)->map(function ($value) { + return ProcessUtils::escapeArgument($value); + }); + + if (Str::startsWith($key, '--')) { + $value = $value->map(function ($value) use ($key) { + return "{$key}={$value}"; + }); + } elseif (Str::startsWith($key, '-')) { + $value = $value->map(function ($value) use ($key) { + return "{$key} {$value}"; + }); + } + + return $value->implode(' '); + } + + /** + * Determine if the server is allowed to run this event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @param \DateTimeInterface $time + * @return bool + */ + public function serverShouldRun(Event $event, DateTimeInterface $time) + { + return $this->schedulingMutex->create($event, $time); + } + + /** + * Get all of the events on the schedule that are due. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Support\Collection + */ + public function dueEvents($app) + { + return collect($this->events)->filter->isDue($app); + } + + /** + * Get all of the events on the schedule. + * + * @return \Illuminate\Console\Scheduling\Event[] + */ + public function events() + { + return $this->events; + } + + /** + * Specify the cache store that should be used to store mutexes. + * + * @param string $store + * @return $this + */ + public function useCache($store) + { + if ($this->eventMutex instanceof CacheAware) { + $this->eventMutex->useStore($store); + } + + if ($this->schedulingMutex instanceof CacheAware) { + $this->schedulingMutex->useStore($store); + } + + return $this; + } + + /** + * Get the job dispatcher, if available. + * + * @return \Illuminate\Contracts\Bus\Dispatcher + * + * @throws \RuntimeException + */ + protected function getDispatcher() + { + if ($this->dispatcher === null) { + try { + $this->dispatcher = Container::getInstance()->make(Dispatcher::class); + } catch (BindingResolutionException $e) { + throw new RuntimeException( + 'Unable to resolve the dispatcher from the service container. Please bind it or install the illuminate/bus package.', + $e->getCode(), $e + ); + } + } + + return $this->dispatcher; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleClearCacheCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleClearCacheCommand.php new file mode 100644 index 0000000..0dd9424 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleClearCacheCommand.php @@ -0,0 +1,47 @@ +events($this->laravel) as $event) { + if ($event->mutex->exists($event)) { + $this->line('Deleting mutex for: '.$event->command); + + $event->mutex->forget($event); + + $mutexCleared = true; + } + } + + if (! $mutexCleared) { + $this->info('No mutex files were found.'); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php new file mode 100644 index 0000000..4857d69 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php @@ -0,0 +1,48 @@ +events())->filter(function ($value) { + return $value->mutexName() == $this->argument('id'); + })->each(function ($event) { + $event->callafterCallbacksWithExitCode($this->laravel, $this->argument('code')); + + $this->laravel->make(Dispatcher::class)->dispatch(new ScheduledBackgroundTaskFinished($event)); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleListCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleListCommand.php new file mode 100644 index 0000000..b1b0bdd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleListCommand.php @@ -0,0 +1,55 @@ +events() as $event) { + $rows[] = [ + $event->command, + $event->expression, + $event->description, + (new CronExpression($event->expression)) + ->getNextRunDate(Carbon::now()->setTimezone($event->timezone)) + ->setTimezone(new DateTimeZone($this->option('timezone') ?? config('app.timezone'))) + ->format('Y-m-d H:i:s P'), + ]; + } + + $this->table([ + 'Command', + 'Interval', + 'Description', + 'Next Due', + ], $rows ?? []); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php new file mode 100644 index 0000000..4193408 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php @@ -0,0 +1,157 @@ +startedAt = Date::now(); + + parent::__construct(); + } + + /** + * Execute the console command. + * + * @param \Illuminate\Console\Scheduling\Schedule $schedule + * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher + * @param \Illuminate\Contracts\Debug\ExceptionHandler $handler + * @return void + */ + public function handle(Schedule $schedule, Dispatcher $dispatcher, ExceptionHandler $handler) + { + $this->schedule = $schedule; + $this->dispatcher = $dispatcher; + $this->handler = $handler; + + foreach ($this->schedule->dueEvents($this->laravel) as $event) { + if (! $event->filtersPass($this->laravel)) { + $this->dispatcher->dispatch(new ScheduledTaskSkipped($event)); + + continue; + } + + if ($event->onOneServer) { + $this->runSingleServerEvent($event); + } else { + $this->runEvent($event); + } + + $this->eventsRan = true; + } + + if (! $this->eventsRan) { + $this->info('No scheduled commands are ready to run.'); + } + } + + /** + * Run the given single server event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return void + */ + protected function runSingleServerEvent($event) + { + if ($this->schedule->serverShouldRun($event, $this->startedAt)) { + $this->runEvent($event); + } else { + $this->line('Skipping command (has already run on another server): '.$event->getSummaryForDisplay()); + } + } + + /** + * Run the given event. + * + * @param \Illuminate\Console\Scheduling\Event $event + * @return void + */ + protected function runEvent($event) + { + $this->line('['.date('c').'] Running scheduled command: '.$event->getSummaryForDisplay()); + + $this->dispatcher->dispatch(new ScheduledTaskStarting($event)); + + $start = microtime(true); + + try { + $event->run($this->laravel); + + $this->dispatcher->dispatch(new ScheduledTaskFinished( + $event, + round(microtime(true) - $start, 2) + )); + + $this->eventsRan = true; + } catch (Throwable $e) { + $this->dispatcher->dispatch(new ScheduledTaskFailed($event, $e)); + + $this->handler->report($e); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleTestCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleTestCommand.php new file mode 100644 index 0000000..2818864 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleTestCommand.php @@ -0,0 +1,47 @@ +events(); + + $commandNames = []; + + foreach ($commands as $command) { + $commandNames[] = $command->command ?? $command->getSummaryForDisplay(); + } + + $index = array_search($this->choice('Which command would you like to run?', $commandNames), $commandNames); + + $event = $commands[$index]; + + $this->line('['.date('c').'] Running scheduled command: '.$event->getSummaryForDisplay()); + + $event->run($this->laravel); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleWorkCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleWorkCommand.php new file mode 100644 index 0000000..165124a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleWorkCommand.php @@ -0,0 +1,72 @@ +info('Schedule worker started successfully.'); + + [$lastExecutionStartedAt, $keyOfLastExecutionWithOutput, $executions] = [null, null, []]; + + while (true) { + usleep(100 * 1000); + + if (Carbon::now()->second === 0 && + ! Carbon::now()->startOfMinute()->equalTo($lastExecutionStartedAt)) { + $executions[] = $execution = new Process([ + PHP_BINARY, + defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan', + 'schedule:run', + ]); + + $execution->start(); + + $lastExecutionStartedAt = Carbon::now()->startOfMinute(); + } + + foreach ($executions as $key => $execution) { + $output = trim($execution->getIncrementalOutput()). + trim($execution->getIncrementalErrorOutput()); + + if (! empty($output)) { + if ($key !== $keyOfLastExecutionWithOutput) { + $this->info(PHP_EOL.'['.date('c').'] Execution #'.($key + 1).' output:'); + + $keyOfLastExecutionWithOutput = $key; + } + + $this->output->writeln($output); + } + + if (! $execution->isRunning()) { + unset($executions[$key]); + } + } + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/SchedulingMutex.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/SchedulingMutex.php new file mode 100644 index 0000000..ab4e87d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Console/Scheduling/SchedulingMutex.php @@ -0,0 +1,26 @@ +make($segments[0]), $method], $parameters + ); + } + + /** + * Call a method that has been bound to the container. + * + * @param \Illuminate\Container\Container $container + * @param callable $callback + * @param mixed $default + * @return mixed + */ + protected static function callBoundMethod($container, $callback, $default) + { + if (! is_array($callback)) { + return Util::unwrapIfClosure($default); + } + + // Here we need to turn the array callable into a Class@method string we can use to + // examine the container and see if there are any method bindings for this given + // method. If there are, we can call this method binding callback immediately. + $method = static::normalizeMethod($callback); + + if ($container->hasMethodBinding($method)) { + return $container->callMethodBinding($method, $callback[0]); + } + + return Util::unwrapIfClosure($default); + } + + /** + * Normalize the given callback into a Class@method string. + * + * @param callable $callback + * @return string + */ + protected static function normalizeMethod($callback) + { + $class = is_string($callback[0]) ? $callback[0] : get_class($callback[0]); + + return "{$class}@{$callback[1]}"; + } + + /** + * Get all dependencies for a given method. + * + * @param \Illuminate\Container\Container $container + * @param callable|string $callback + * @param array $parameters + * @return array + * + * @throws \ReflectionException + */ + protected static function getMethodDependencies($container, $callback, array $parameters = []) + { + $dependencies = []; + + foreach (static::getCallReflector($callback)->getParameters() as $parameter) { + static::addDependencyForCallParameter($container, $parameter, $parameters, $dependencies); + } + + return array_merge($dependencies, array_values($parameters)); + } + + /** + * Get the proper reflection instance for the given callback. + * + * @param callable|string $callback + * @return \ReflectionFunctionAbstract + * + * @throws \ReflectionException + */ + protected static function getCallReflector($callback) + { + if (is_string($callback) && strpos($callback, '::') !== false) { + $callback = explode('::', $callback); + } elseif (is_object($callback) && ! $callback instanceof Closure) { + $callback = [$callback, '__invoke']; + } + + return is_array($callback) + ? new ReflectionMethod($callback[0], $callback[1]) + : new ReflectionFunction($callback); + } + + /** + * Get the dependency for the given call parameter. + * + * @param \Illuminate\Container\Container $container + * @param \ReflectionParameter $parameter + * @param array $parameters + * @param array $dependencies + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected static function addDependencyForCallParameter($container, $parameter, + array &$parameters, &$dependencies) + { + if (array_key_exists($paramName = $parameter->getName(), $parameters)) { + $dependencies[] = $parameters[$paramName]; + + unset($parameters[$paramName]); + } elseif (! is_null($className = Util::getParameterClassName($parameter))) { + if (array_key_exists($className, $parameters)) { + $dependencies[] = $parameters[$className]; + + unset($parameters[$className]); + } else { + if ($parameter->isVariadic()) { + $variadicDependencies = $container->make($className); + + $dependencies = array_merge($dependencies, is_array($variadicDependencies) + ? $variadicDependencies + : [$variadicDependencies]); + } else { + $dependencies[] = $container->make($className); + } + } + } elseif ($parameter->isDefaultValueAvailable()) { + $dependencies[] = $parameter->getDefaultValue(); + } elseif (! $parameter->isOptional() && ! array_key_exists($paramName, $parameters)) { + $message = "Unable to resolve dependency [{$parameter}] in class {$parameter->getDeclaringClass()->getName()}"; + + throw new BindingResolutionException($message); + } + } + + /** + * Determine if the given string is in Class@method syntax. + * + * @param mixed $callback + * @return bool + */ + protected static function isCallableWithAtSign($callback) + { + return is_string($callback) && strpos($callback, '@') !== false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/Container.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/Container.php new file mode 100755 index 0000000..e6cd346 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/Container.php @@ -0,0 +1,1471 @@ +getAlias($c); + } + + return new ContextualBindingBuilder($this, $aliases); + } + + /** + * Determine if the given abstract type has been bound. + * + * @param string $abstract + * @return bool + */ + public function bound($abstract) + { + return isset($this->bindings[$abstract]) || + isset($this->instances[$abstract]) || + $this->isAlias($abstract); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + public function has($id) + { + return $this->bound($id); + } + + /** + * Determine if the given abstract type has been resolved. + * + * @param string $abstract + * @return bool + */ + public function resolved($abstract) + { + if ($this->isAlias($abstract)) { + $abstract = $this->getAlias($abstract); + } + + return isset($this->resolved[$abstract]) || + isset($this->instances[$abstract]); + } + + /** + * Determine if a given type is shared. + * + * @param string $abstract + * @return bool + */ + public function isShared($abstract) + { + return isset($this->instances[$abstract]) || + (isset($this->bindings[$abstract]['shared']) && + $this->bindings[$abstract]['shared'] === true); + } + + /** + * Determine if a given string is an alias. + * + * @param string $name + * @return bool + */ + public function isAlias($name) + { + return isset($this->aliases[$name]); + } + + /** + * Register a binding with the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + * + * @throws \TypeError + */ + public function bind($abstract, $concrete = null, $shared = false) + { + $this->dropStaleInstances($abstract); + + // If no concrete type was given, we will simply set the concrete type to the + // abstract type. After that, the concrete type to be registered as shared + // without being forced to state their classes in both of the parameters. + if (is_null($concrete)) { + $concrete = $abstract; + } + + // If the factory is not a Closure, it means it is just a class name which is + // bound into this container to the abstract type and we will just wrap it + // up inside its own Closure to give us more convenience when extending. + if (! $concrete instanceof Closure) { + if (! is_string($concrete)) { + throw new TypeError(self::class.'::bind(): Argument #2 ($concrete) must be of type Closure|string|null'); + } + + $concrete = $this->getClosure($abstract, $concrete); + } + + $this->bindings[$abstract] = compact('concrete', 'shared'); + + // If the abstract type was already resolved in this container we'll fire the + // rebound listener so that any objects which have already gotten resolved + // can have their copy of the object updated via the listener callbacks. + if ($this->resolved($abstract)) { + $this->rebound($abstract); + } + } + + /** + * Get the Closure to be used when building a type. + * + * @param string $abstract + * @param string $concrete + * @return \Closure + */ + protected function getClosure($abstract, $concrete) + { + return function ($container, $parameters = []) use ($abstract, $concrete) { + if ($abstract == $concrete) { + return $container->build($concrete); + } + + return $container->resolve( + $concrete, $parameters, $raiseEvents = false + ); + }; + } + + /** + * Determine if the container has a method binding. + * + * @param string $method + * @return bool + */ + public function hasMethodBinding($method) + { + return isset($this->methodBindings[$method]); + } + + /** + * Bind a callback to resolve with Container::call. + * + * @param array|string $method + * @param \Closure $callback + * @return void + */ + public function bindMethod($method, $callback) + { + $this->methodBindings[$this->parseBindMethod($method)] = $callback; + } + + /** + * Get the method to be bound in class@method format. + * + * @param array|string $method + * @return string + */ + protected function parseBindMethod($method) + { + if (is_array($method)) { + return $method[0].'@'.$method[1]; + } + + return $method; + } + + /** + * Get the method binding for the given method. + * + * @param string $method + * @param mixed $instance + * @return mixed + */ + public function callMethodBinding($method, $instance) + { + return call_user_func($this->methodBindings[$method], $instance, $this); + } + + /** + * Add a contextual binding to the container. + * + * @param string $concrete + * @param string $abstract + * @param \Closure|string $implementation + * @return void + */ + public function addContextualBinding($concrete, $abstract, $implementation) + { + $this->contextual[$concrete][$this->getAlias($abstract)] = $implementation; + } + + /** + * Register a binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + */ + public function bindIf($abstract, $concrete = null, $shared = false) + { + if (! $this->bound($abstract)) { + $this->bind($abstract, $concrete, $shared); + } + } + + /** + * Register a shared binding in the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function singleton($abstract, $concrete = null) + { + $this->bind($abstract, $concrete, true); + } + + /** + * Register a shared binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function singletonIf($abstract, $concrete = null) + { + if (! $this->bound($abstract)) { + $this->singleton($abstract, $concrete); + } + } + + /** + * Register a scoped binding in the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function scoped($abstract, $concrete = null) + { + $this->scopedInstances[] = $abstract; + + $this->singleton($abstract, $concrete); + } + + /** + * Register a scoped binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function scopedIf($abstract, $concrete = null) + { + if (! $this->bound($abstract)) { + $this->scopedInstances[] = $abstract; + + $this->singleton($abstract, $concrete); + } + } + + /** + * "Extend" an abstract type in the container. + * + * @param string $abstract + * @param \Closure $closure + * @return void + * + * @throws \InvalidArgumentException + */ + public function extend($abstract, Closure $closure) + { + $abstract = $this->getAlias($abstract); + + if (isset($this->instances[$abstract])) { + $this->instances[$abstract] = $closure($this->instances[$abstract], $this); + + $this->rebound($abstract); + } else { + $this->extenders[$abstract][] = $closure; + + if ($this->resolved($abstract)) { + $this->rebound($abstract); + } + } + } + + /** + * Register an existing instance as shared in the container. + * + * @param string $abstract + * @param mixed $instance + * @return mixed + */ + public function instance($abstract, $instance) + { + $this->removeAbstractAlias($abstract); + + $isBound = $this->bound($abstract); + + unset($this->aliases[$abstract]); + + // We'll check to determine if this type has been bound before, and if it has + // we will fire the rebound callbacks registered with the container and it + // can be updated with consuming classes that have gotten resolved here. + $this->instances[$abstract] = $instance; + + if ($isBound) { + $this->rebound($abstract); + } + + return $instance; + } + + /** + * Remove an alias from the contextual binding alias cache. + * + * @param string $searched + * @return void + */ + protected function removeAbstractAlias($searched) + { + if (! isset($this->aliases[$searched])) { + return; + } + + foreach ($this->abstractAliases as $abstract => $aliases) { + foreach ($aliases as $index => $alias) { + if ($alias == $searched) { + unset($this->abstractAliases[$abstract][$index]); + } + } + } + } + + /** + * Assign a set of tags to a given binding. + * + * @param array|string $abstracts + * @param array|mixed ...$tags + * @return void + */ + public function tag($abstracts, $tags) + { + $tags = is_array($tags) ? $tags : array_slice(func_get_args(), 1); + + foreach ($tags as $tag) { + if (! isset($this->tags[$tag])) { + $this->tags[$tag] = []; + } + + foreach ((array) $abstracts as $abstract) { + $this->tags[$tag][] = $abstract; + } + } + } + + /** + * Resolve all of the bindings for a given tag. + * + * @param string $tag + * @return iterable + */ + public function tagged($tag) + { + if (! isset($this->tags[$tag])) { + return []; + } + + return new RewindableGenerator(function () use ($tag) { + foreach ($this->tags[$tag] as $abstract) { + yield $this->make($abstract); + } + }, count($this->tags[$tag])); + } + + /** + * Alias a type to a different name. + * + * @param string $abstract + * @param string $alias + * @return void + * + * @throws \LogicException + */ + public function alias($abstract, $alias) + { + if ($alias === $abstract) { + throw new LogicException("[{$abstract}] is aliased to itself."); + } + + $this->aliases[$alias] = $abstract; + + $this->abstractAliases[$abstract][] = $alias; + } + + /** + * Bind a new callback to an abstract's rebind event. + * + * @param string $abstract + * @param \Closure $callback + * @return mixed + */ + public function rebinding($abstract, Closure $callback) + { + $this->reboundCallbacks[$abstract = $this->getAlias($abstract)][] = $callback; + + if ($this->bound($abstract)) { + return $this->make($abstract); + } + } + + /** + * Refresh an instance on the given target and method. + * + * @param string $abstract + * @param mixed $target + * @param string $method + * @return mixed + */ + public function refresh($abstract, $target, $method) + { + return $this->rebinding($abstract, function ($app, $instance) use ($target, $method) { + $target->{$method}($instance); + }); + } + + /** + * Fire the "rebound" callbacks for the given abstract type. + * + * @param string $abstract + * @return void + */ + protected function rebound($abstract) + { + $instance = $this->make($abstract); + + foreach ($this->getReboundCallbacks($abstract) as $callback) { + call_user_func($callback, $this, $instance); + } + } + + /** + * Get the rebound callbacks for a given type. + * + * @param string $abstract + * @return array + */ + protected function getReboundCallbacks($abstract) + { + return $this->reboundCallbacks[$abstract] ?? []; + } + + /** + * Wrap the given closure such that its dependencies will be injected when executed. + * + * @param \Closure $callback + * @param array $parameters + * @return \Closure + */ + public function wrap(Closure $callback, array $parameters = []) + { + return function () use ($callback, $parameters) { + return $this->call($callback, $parameters); + }; + } + + /** + * Call the given Closure / class@method and inject its dependencies. + * + * @param callable|string $callback + * @param array $parameters + * @param string|null $defaultMethod + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function call($callback, array $parameters = [], $defaultMethod = null) + { + return BoundMethod::call($this, $callback, $parameters, $defaultMethod); + } + + /** + * Get a closure to resolve the given type from the container. + * + * @param string $abstract + * @return \Closure + */ + public function factory($abstract) + { + return function () use ($abstract) { + return $this->make($abstract); + }; + } + + /** + * An alias function name for make(). + * + * @param string|callable $abstract + * @param array $parameters + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function makeWith($abstract, array $parameters = []) + { + return $this->make($abstract, $parameters); + } + + /** + * Resolve the given type from the container. + * + * @param string|callable $abstract + * @param array $parameters + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function make($abstract, array $parameters = []) + { + return $this->resolve($abstract, $parameters); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function get($id) + { + try { + return $this->resolve($id); + } catch (Exception $e) { + if ($this->has($id) || $e instanceof CircularDependencyException) { + throw $e; + } + + throw new EntryNotFoundException($id, $e->getCode(), $e); + } + } + + /** + * Resolve the given type from the container. + * + * @param string|callable $abstract + * @param array $parameters + * @param bool $raiseEvents + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @throws \Illuminate\Contracts\Container\CircularDependencyException + */ + protected function resolve($abstract, $parameters = [], $raiseEvents = true) + { + $abstract = $this->getAlias($abstract); + + // First we'll fire any event handlers which handle the "before" resolving of + // specific types. This gives some hooks the chance to add various extends + // calls to change the resolution of objects that they're interested in. + if ($raiseEvents) { + $this->fireBeforeResolvingCallbacks($abstract, $parameters); + } + + $concrete = $this->getContextualConcrete($abstract); + + $needsContextualBuild = ! empty($parameters) || ! is_null($concrete); + + // If an instance of the type is currently being managed as a singleton we'll + // just return an existing instance instead of instantiating new instances + // so the developer can keep using the same objects instance every time. + if (isset($this->instances[$abstract]) && ! $needsContextualBuild) { + return $this->instances[$abstract]; + } + + $this->with[] = $parameters; + + if (is_null($concrete)) { + $concrete = $this->getConcrete($abstract); + } + + // We're ready to instantiate an instance of the concrete type registered for + // the binding. This will instantiate the types, as well as resolve any of + // its "nested" dependencies recursively until all have gotten resolved. + if ($this->isBuildable($concrete, $abstract)) { + $object = $this->build($concrete); + } else { + $object = $this->make($concrete); + } + + // If we defined any extenders for this type, we'll need to spin through them + // and apply them to the object being built. This allows for the extension + // of services, such as changing configuration or decorating the object. + foreach ($this->getExtenders($abstract) as $extender) { + $object = $extender($object, $this); + } + + // If the requested type is registered as a singleton we'll want to cache off + // the instances in "memory" so we can return it later without creating an + // entirely new instance of an object on each subsequent request for it. + if ($this->isShared($abstract) && ! $needsContextualBuild) { + $this->instances[$abstract] = $object; + } + + if ($raiseEvents) { + $this->fireResolvingCallbacks($abstract, $object); + } + + // Before returning, we will also set the resolved flag to "true" and pop off + // the parameter overrides for this build. After those two things are done + // we will be ready to return back the fully constructed class instance. + $this->resolved[$abstract] = true; + + array_pop($this->with); + + return $object; + } + + /** + * Get the concrete type for a given abstract. + * + * @param string|callable $abstract + * @return mixed + */ + protected function getConcrete($abstract) + { + // If we don't have a registered resolver or concrete for the type, we'll just + // assume each type is a concrete name and will attempt to resolve it as is + // since the container should be able to resolve concretes automatically. + if (isset($this->bindings[$abstract])) { + return $this->bindings[$abstract]['concrete']; + } + + return $abstract; + } + + /** + * Get the contextual concrete binding for the given abstract. + * + * @param string|callable $abstract + * @return \Closure|string|array|null + */ + protected function getContextualConcrete($abstract) + { + if (! is_null($binding = $this->findInContextualBindings($abstract))) { + return $binding; + } + + // Next we need to see if a contextual binding might be bound under an alias of the + // given abstract type. So, we will need to check if any aliases exist with this + // type and then spin through them and check for contextual bindings on these. + if (empty($this->abstractAliases[$abstract])) { + return; + } + + foreach ($this->abstractAliases[$abstract] as $alias) { + if (! is_null($binding = $this->findInContextualBindings($alias))) { + return $binding; + } + } + } + + /** + * Find the concrete binding for the given abstract in the contextual binding array. + * + * @param string|callable $abstract + * @return \Closure|string|null + */ + protected function findInContextualBindings($abstract) + { + return $this->contextual[end($this->buildStack)][$abstract] ?? null; + } + + /** + * Determine if the given concrete is buildable. + * + * @param mixed $concrete + * @param string $abstract + * @return bool + */ + protected function isBuildable($concrete, $abstract) + { + return $concrete === $abstract || $concrete instanceof Closure; + } + + /** + * Instantiate a concrete instance of the given type. + * + * @param \Closure|string $concrete + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @throws \Illuminate\Contracts\Container\CircularDependencyException + */ + public function build($concrete) + { + // If the concrete type is actually a Closure, we will just execute it and + // hand back the results of the functions, which allows functions to be + // used as resolvers for more fine-tuned resolution of these objects. + if ($concrete instanceof Closure) { + return $concrete($this, $this->getLastParameterOverride()); + } + + try { + $reflector = new ReflectionClass($concrete); + } catch (ReflectionException $e) { + throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e); + } + + // If the type is not instantiable, the developer is attempting to resolve + // an abstract type such as an Interface or Abstract Class and there is + // no binding registered for the abstractions so we need to bail out. + if (! $reflector->isInstantiable()) { + return $this->notInstantiable($concrete); + } + + $this->buildStack[] = $concrete; + + $constructor = $reflector->getConstructor(); + + // If there are no constructors, that means there are no dependencies then + // we can just resolve the instances of the objects right away, without + // resolving any other types or dependencies out of these containers. + if (is_null($constructor)) { + array_pop($this->buildStack); + + return new $concrete; + } + + $dependencies = $constructor->getParameters(); + + // Once we have all the constructor's parameters we can create each of the + // dependency instances and then use the reflection instances to make a + // new instance of this class, injecting the created dependencies in. + try { + $instances = $this->resolveDependencies($dependencies); + } catch (BindingResolutionException $e) { + array_pop($this->buildStack); + + throw $e; + } + + array_pop($this->buildStack); + + return $reflector->newInstanceArgs($instances); + } + + /** + * Resolve all of the dependencies from the ReflectionParameters. + * + * @param \ReflectionParameter[] $dependencies + * @return array + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function resolveDependencies(array $dependencies) + { + $results = []; + + foreach ($dependencies as $dependency) { + // If the dependency has an override for this particular build we will use + // that instead as the value. Otherwise, we will continue with this run + // of resolutions and let reflection attempt to determine the result. + if ($this->hasParameterOverride($dependency)) { + $results[] = $this->getParameterOverride($dependency); + + continue; + } + + // If the class is null, it means the dependency is a string or some other + // primitive type which we can not resolve since it is not a class and + // we will just bomb out with an error since we have no-where to go. + $result = is_null(Util::getParameterClassName($dependency)) + ? $this->resolvePrimitive($dependency) + : $this->resolveClass($dependency); + + if ($dependency->isVariadic()) { + $results = array_merge($results, $result); + } else { + $results[] = $result; + } + } + + return $results; + } + + /** + * Determine if the given dependency has a parameter override. + * + * @param \ReflectionParameter $dependency + * @return bool + */ + protected function hasParameterOverride($dependency) + { + return array_key_exists( + $dependency->name, $this->getLastParameterOverride() + ); + } + + /** + * Get a parameter override for a dependency. + * + * @param \ReflectionParameter $dependency + * @return mixed + */ + protected function getParameterOverride($dependency) + { + return $this->getLastParameterOverride()[$dependency->name]; + } + + /** + * Get the last parameter override. + * + * @return array + */ + protected function getLastParameterOverride() + { + return count($this->with) ? end($this->with) : []; + } + + /** + * Resolve a non-class hinted primitive dependency. + * + * @param \ReflectionParameter $parameter + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function resolvePrimitive(ReflectionParameter $parameter) + { + if (! is_null($concrete = $this->getContextualConcrete('$'.$parameter->getName()))) { + return $concrete instanceof Closure ? $concrete($this) : $concrete; + } + + if ($parameter->isDefaultValueAvailable()) { + return $parameter->getDefaultValue(); + } + + $this->unresolvablePrimitive($parameter); + } + + /** + * Resolve a class based dependency from the container. + * + * @param \ReflectionParameter $parameter + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function resolveClass(ReflectionParameter $parameter) + { + try { + return $parameter->isVariadic() + ? $this->resolveVariadicClass($parameter) + : $this->make(Util::getParameterClassName($parameter)); + } + + // If we can not resolve the class instance, we will check to see if the value + // is optional, and if it is we will return the optional parameter value as + // the value of the dependency, similarly to how we do this with scalars. + catch (BindingResolutionException $e) { + if ($parameter->isDefaultValueAvailable()) { + array_pop($this->with); + + return $parameter->getDefaultValue(); + } + + if ($parameter->isVariadic()) { + array_pop($this->with); + + return []; + } + + throw $e; + } + } + + /** + * Resolve a class based variadic dependency from the container. + * + * @param \ReflectionParameter $parameter + * @return mixed + */ + protected function resolveVariadicClass(ReflectionParameter $parameter) + { + $className = Util::getParameterClassName($parameter); + + $abstract = $this->getAlias($className); + + if (! is_array($concrete = $this->getContextualConcrete($abstract))) { + return $this->make($className); + } + + return array_map(function ($abstract) { + return $this->resolve($abstract); + }, $concrete); + } + + /** + * Throw an exception that the concrete is not instantiable. + * + * @param string $concrete + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function notInstantiable($concrete) + { + if (! empty($this->buildStack)) { + $previous = implode(', ', $this->buildStack); + + $message = "Target [$concrete] is not instantiable while building [$previous]."; + } else { + $message = "Target [$concrete] is not instantiable."; + } + + throw new BindingResolutionException($message); + } + + /** + * Throw an exception for an unresolvable primitive. + * + * @param \ReflectionParameter $parameter + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function unresolvablePrimitive(ReflectionParameter $parameter) + { + $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}"; + + throw new BindingResolutionException($message); + } + + /** + * Register a new before resolving callback for all types. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + */ + public function beforeResolving($abstract, Closure $callback = null) + { + if (is_string($abstract)) { + $abstract = $this->getAlias($abstract); + } + + if ($abstract instanceof Closure && is_null($callback)) { + $this->globalBeforeResolvingCallbacks[] = $abstract; + } else { + $this->beforeResolvingCallbacks[$abstract][] = $callback; + } + } + + /** + * Register a new resolving callback. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + */ + public function resolving($abstract, Closure $callback = null) + { + if (is_string($abstract)) { + $abstract = $this->getAlias($abstract); + } + + if (is_null($callback) && $abstract instanceof Closure) { + $this->globalResolvingCallbacks[] = $abstract; + } else { + $this->resolvingCallbacks[$abstract][] = $callback; + } + } + + /** + * Register a new after resolving callback for all types. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + */ + public function afterResolving($abstract, Closure $callback = null) + { + if (is_string($abstract)) { + $abstract = $this->getAlias($abstract); + } + + if ($abstract instanceof Closure && is_null($callback)) { + $this->globalAfterResolvingCallbacks[] = $abstract; + } else { + $this->afterResolvingCallbacks[$abstract][] = $callback; + } + } + + /** + * Fire all of the before resolving callbacks. + * + * @param string $abstract + * @param array $parameters + * @return void + */ + protected function fireBeforeResolvingCallbacks($abstract, $parameters = []) + { + $this->fireBeforeCallbackArray($abstract, $parameters, $this->globalBeforeResolvingCallbacks); + + foreach ($this->beforeResolvingCallbacks as $type => $callbacks) { + if ($type === $abstract || is_subclass_of($abstract, $type)) { + $this->fireBeforeCallbackArray($abstract, $parameters, $callbacks); + } + } + } + + /** + * Fire an array of callbacks with an object. + * + * @param string $abstract + * @param array $parameters + * @param array $callbacks + * @return void + */ + protected function fireBeforeCallbackArray($abstract, $parameters, array $callbacks) + { + foreach ($callbacks as $callback) { + $callback($abstract, $parameters, $this); + } + } + + /** + * Fire all of the resolving callbacks. + * + * @param string $abstract + * @param mixed $object + * @return void + */ + protected function fireResolvingCallbacks($abstract, $object) + { + $this->fireCallbackArray($object, $this->globalResolvingCallbacks); + + $this->fireCallbackArray( + $object, $this->getCallbacksForType($abstract, $object, $this->resolvingCallbacks) + ); + + $this->fireAfterResolvingCallbacks($abstract, $object); + } + + /** + * Fire all of the after resolving callbacks. + * + * @param string $abstract + * @param mixed $object + * @return void + */ + protected function fireAfterResolvingCallbacks($abstract, $object) + { + $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks); + + $this->fireCallbackArray( + $object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks) + ); + } + + /** + * Get all callbacks for a given type. + * + * @param string $abstract + * @param object $object + * @param array $callbacksPerType + * @return array + */ + protected function getCallbacksForType($abstract, $object, array $callbacksPerType) + { + $results = []; + + foreach ($callbacksPerType as $type => $callbacks) { + if ($type === $abstract || $object instanceof $type) { + $results = array_merge($results, $callbacks); + } + } + + return $results; + } + + /** + * Fire an array of callbacks with an object. + * + * @param mixed $object + * @param array $callbacks + * @return void + */ + protected function fireCallbackArray($object, array $callbacks) + { + foreach ($callbacks as $callback) { + $callback($object, $this); + } + } + + /** + * Get the container's bindings. + * + * @return array + */ + public function getBindings() + { + return $this->bindings; + } + + /** + * Get the alias for an abstract if available. + * + * @param string $abstract + * @return string + */ + public function getAlias($abstract) + { + return isset($this->aliases[$abstract]) + ? $this->getAlias($this->aliases[$abstract]) + : $abstract; + } + + /** + * Get the extender callbacks for a given type. + * + * @param string $abstract + * @return array + */ + protected function getExtenders($abstract) + { + return $this->extenders[$this->getAlias($abstract)] ?? []; + } + + /** + * Remove all of the extender callbacks for a given type. + * + * @param string $abstract + * @return void + */ + public function forgetExtenders($abstract) + { + unset($this->extenders[$this->getAlias($abstract)]); + } + + /** + * Drop all of the stale instances and aliases. + * + * @param string $abstract + * @return void + */ + protected function dropStaleInstances($abstract) + { + unset($this->instances[$abstract], $this->aliases[$abstract]); + } + + /** + * Remove a resolved instance from the instance cache. + * + * @param string $abstract + * @return void + */ + public function forgetInstance($abstract) + { + unset($this->instances[$abstract]); + } + + /** + * Clear all of the instances from the container. + * + * @return void + */ + public function forgetInstances() + { + $this->instances = []; + } + + /** + * Clear all of the scoped instances from the container. + * + * @return void + */ + public function forgetScopedInstances() + { + foreach ($this->scopedInstances as $scoped) { + unset($this->instances[$scoped]); + } + } + + /** + * Flush the container of all bindings and resolved instances. + * + * @return void + */ + public function flush() + { + $this->aliases = []; + $this->resolved = []; + $this->bindings = []; + $this->instances = []; + $this->abstractAliases = []; + $this->scopedInstances = []; + } + + /** + * Get the globally available instance of the container. + * + * @return static + */ + public static function getInstance() + { + if (is_null(static::$instance)) { + static::$instance = new static; + } + + return static::$instance; + } + + /** + * Set the shared instance of the container. + * + * @param \Illuminate\Contracts\Container\Container|null $container + * @return \Illuminate\Contracts\Container\Container|static + */ + public static function setInstance(ContainerContract $container = null) + { + return static::$instance = $container; + } + + /** + * Determine if a given offset exists. + * + * @param string $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->bound($key); + } + + /** + * Get the value at a given offset. + * + * @param string $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->make($key); + } + + /** + * Set the value at a given offset. + * + * @param string $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->bind($key, $value instanceof Closure ? $value : function () use ($value) { + return $value; + }); + } + + /** + * Unset the value at a given offset. + * + * @param string $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]); + } + + /** + * Dynamically access container services. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this[$key]; + } + + /** + * Dynamically set container services. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function __set($key, $value) + { + $this[$key] = $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/ContextualBindingBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/ContextualBindingBuilder.php new file mode 100644 index 0000000..1d15dcd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/ContextualBindingBuilder.php @@ -0,0 +1,98 @@ +concrete = $concrete; + $this->container = $container; + } + + /** + * Define the abstract target that depends on the context. + * + * @param string $abstract + * @return $this + */ + public function needs($abstract) + { + $this->needs = $abstract; + + return $this; + } + + /** + * Define the implementation for the contextual binding. + * + * @param \Closure|string|array $implementation + * @return void + */ + public function give($implementation) + { + foreach (Util::arrayWrap($this->concrete) as $concrete) { + $this->container->addContextualBinding($concrete, $this->needs, $implementation); + } + } + + /** + * Define tagged services to be used as the implementation for the contextual binding. + * + * @param string $tag + * @return void + */ + public function giveTagged($tag) + { + $this->give(function ($container) use ($tag) { + $taggedServices = $container->tagged($tag); + + return is_array($taggedServices) ? $taggedServices : iterator_to_array($taggedServices); + }); + } + + /** + * Specify the configuration item to bind as a primitive. + * + * @param string $key + * @param ?string $default + * @return void + */ + public function giveConfig($key, $default = null) + { + $this->give(function ($container) use ($key, $default) { + return $container->get('config')->get($key, $default); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/EntryNotFoundException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/EntryNotFoundException.php new file mode 100644 index 0000000..4266921 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/EntryNotFoundException.php @@ -0,0 +1,11 @@ +count = $count; + $this->generator = $generator; + } + + /** + * Get an iterator from the generator. + * + * @return mixed + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return ($this->generator)(); + } + + /** + * Get the total number of tagged services. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + if (is_callable($count = $this->count)) { + $this->count = $count(); + } + + return $this->count; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/Util.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/Util.php new file mode 100644 index 0000000..8f7e917 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/Util.php @@ -0,0 +1,73 @@ +getType(); + + if (! $type instanceof ReflectionNamedType || $type->isBuiltin()) { + return null; + } + + $name = $type->getName(); + + if (! is_null($class = $parameter->getDeclaringClass())) { + if ($name === 'self') { + return $class->getName(); + } + + if ($name === 'parent' && $parent = $class->getParentClass()) { + return $parent->getName(); + } + } + + return $name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/composer.json new file mode 100755 index 0000000..cf93160 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Container/composer.json @@ -0,0 +1,38 @@ +{ + "name": "illuminate/container", + "description": "The Illuminate Container package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/contracts": "^8.0", + "psr/container": "^1.0" + }, + "provide": { + "psr/container-implementation": "1.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Container\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Contracts/Auth/Access/Authorizable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Contracts/Auth/Access/Authorizable.php new file mode 100644 index 0000000..cedeb6e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Contracts/Auth/Access/Authorizable.php @@ -0,0 +1,15 @@ +id = $id; + $this->class = $class; + $this->relations = $relations; + $this->connection = $connection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Contracts/Debug/ExceptionHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Contracts/Debug/ExceptionHandler.php new file mode 100644 index 0000000..54381a1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Contracts/Debug/ExceptionHandler.php @@ -0,0 +1,46 @@ +getPathAndDomain($path, $domain, $secure, $sameSite); + + $time = ($minutes == 0) ? 0 : $this->availableAt($minutes * 60); + + return new Cookie($name, $value, $time, $path, $domain, $secure, $httpOnly, $raw, $sameSite); + } + + /** + * Create a cookie that lasts "forever" (five years). + * + * @param string $name + * @param string $value + * @param string|null $path + * @param string|null $domain + * @param bool|null $secure + * @param bool $httpOnly + * @param bool $raw + * @param string|null $sameSite + * @return \Symfony\Component\HttpFoundation\Cookie + */ + public function forever($name, $value, $path = null, $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = null) + { + return $this->make($name, $value, 2628000, $path, $domain, $secure, $httpOnly, $raw, $sameSite); + } + + /** + * Expire the given cookie. + * + * @param string $name + * @param string|null $path + * @param string|null $domain + * @return \Symfony\Component\HttpFoundation\Cookie + */ + public function forget($name, $path = null, $domain = null) + { + return $this->make($name, null, -2628000, $path, $domain); + } + + /** + * Determine if a cookie has been queued. + * + * @param string $key + * @param string|null $path + * @return bool + */ + public function hasQueued($key, $path = null) + { + return ! is_null($this->queued($key, null, $path)); + } + + /** + * Get a queued cookie instance. + * + * @param string $key + * @param mixed $default + * @param string|null $path + * @return \Symfony\Component\HttpFoundation\Cookie|null + */ + public function queued($key, $default = null, $path = null) + { + $queued = Arr::get($this->queued, $key, $default); + + if ($path === null) { + return Arr::last($queued, null, $default); + } + + return Arr::get($queued, $path, $default); + } + + /** + * Queue a cookie to send with the next response. + * + * @param array $parameters + * @return void + */ + public function queue(...$parameters) + { + if (isset($parameters[0]) && $parameters[0] instanceof Cookie) { + $cookie = $parameters[0]; + } else { + $cookie = $this->make(...array_values($parameters)); + } + + if (! isset($this->queued[$cookie->getName()])) { + $this->queued[$cookie->getName()] = []; + } + + $this->queued[$cookie->getName()][$cookie->getPath()] = $cookie; + } + + /** + * Queue a cookie to expire with the next response. + * + * @param string $name + * @param string|null $path + * @param string|null $domain + * @return void + */ + public function expire($name, $path = null, $domain = null) + { + $this->queue($this->forget($name, $path, $domain)); + } + + /** + * Remove a cookie from the queue. + * + * @param string $name + * @param string|null $path + * @return void + */ + public function unqueue($name, $path = null) + { + if ($path === null) { + unset($this->queued[$name]); + + return; + } + + unset($this->queued[$name][$path]); + + if (empty($this->queued[$name])) { + unset($this->queued[$name]); + } + } + + /** + * Get the path and domain, or the default values. + * + * @param string $path + * @param string $domain + * @param bool|null $secure + * @param string|null $sameSite + * @return array + */ + protected function getPathAndDomain($path, $domain, $secure = null, $sameSite = null) + { + return [$path ?: $this->path, $domain ?: $this->domain, is_bool($secure) ? $secure : $this->secure, $sameSite ?: $this->sameSite]; + } + + /** + * Set the default path and domain for the jar. + * + * @param string $path + * @param string $domain + * @param bool $secure + * @param string|null $sameSite + * @return $this + */ + public function setDefaultPathAndDomain($path, $domain, $secure = false, $sameSite = null) + { + [$this->path, $this->domain, $this->secure, $this->sameSite] = [$path, $domain, $secure, $sameSite]; + + return $this; + } + + /** + * Get the cookies which have been queued for the next request. + * + * @return \Symfony\Component\HttpFoundation\Cookie[] + */ + public function getQueuedCookies() + { + return Arr::flatten($this->queued); + } + + /** + * Flush the cookies which have been queued for the next request. + * + * @return $this + */ + public function flushQueuedCookies() + { + $this->queued = []; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/CookieServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/CookieServiceProvider.php new file mode 100755 index 0000000..7c82dc1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/CookieServiceProvider.php @@ -0,0 +1,24 @@ +app->singleton('cookie', function ($app) { + $config = $app->make('config')->get('session'); + + return (new CookieJar)->setDefaultPathAndDomain( + $config['path'], $config['domain'], $config['secure'], $config['same_site'] ?? null + ); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/CookieValuePrefix.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/CookieValuePrefix.php new file mode 100644 index 0000000..e39cb69 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/CookieValuePrefix.php @@ -0,0 +1,29 @@ +cookies = $cookies; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + $response = $next($request); + + foreach ($this->cookies->getQueuedCookies() as $cookie) { + $response->headers->setCookie($cookie); + } + + return $response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php new file mode 100644 index 0000000..4a116cf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php @@ -0,0 +1,194 @@ +encrypter = $encrypter; + } + + /** + * Disable encryption for the given cookie name(s). + * + * @param string|array $name + * @return void + */ + public function disableFor($name) + { + $this->except = array_merge($this->except, (array) $name); + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return \Symfony\Component\HttpFoundation\Response + */ + public function handle($request, Closure $next) + { + return $this->encrypt($next($this->decrypt($request))); + } + + /** + * Decrypt the cookies on the request. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @return \Symfony\Component\HttpFoundation\Request + */ + protected function decrypt(Request $request) + { + foreach ($request->cookies as $key => $cookie) { + if ($this->isDisabled($key) || is_array($cookie)) { + continue; + } + + try { + $value = $this->decryptCookie($key, $cookie); + + $hasValidPrefix = strpos($value, CookieValuePrefix::create($key, $this->encrypter->getKey())) === 0; + + $request->cookies->set( + $key, $hasValidPrefix ? CookieValuePrefix::remove($value) : null + ); + } catch (DecryptException $e) { + $request->cookies->set($key, null); + } + } + + return $request; + } + + /** + * Decrypt the given cookie and return the value. + * + * @param string $name + * @param string|array $cookie + * @return string|array + */ + protected function decryptCookie($name, $cookie) + { + return is_array($cookie) + ? $this->decryptArray($cookie) + : $this->encrypter->decrypt($cookie, static::serialized($name)); + } + + /** + * Decrypt an array based cookie. + * + * @param array $cookie + * @return array + */ + protected function decryptArray(array $cookie) + { + $decrypted = []; + + foreach ($cookie as $key => $value) { + if (is_string($value)) { + $decrypted[$key] = $this->encrypter->decrypt($value, static::serialized($key)); + } + } + + return $decrypted; + } + + /** + * Encrypt the cookies on an outgoing response. + * + * @param \Symfony\Component\HttpFoundation\Response $response + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function encrypt(Response $response) + { + foreach ($response->headers->getCookies() as $cookie) { + if ($this->isDisabled($cookie->getName())) { + continue; + } + + $response->headers->setCookie($this->duplicate( + $cookie, + $this->encrypter->encrypt( + CookieValuePrefix::create($cookie->getName(), $this->encrypter->getKey()).$cookie->getValue(), + static::serialized($cookie->getName()) + ) + )); + } + + return $response; + } + + /** + * Duplicate a cookie with a new value. + * + * @param \Symfony\Component\HttpFoundation\Cookie $cookie + * @param mixed $value + * @return \Symfony\Component\HttpFoundation\Cookie + */ + protected function duplicate(Cookie $cookie, $value) + { + return new Cookie( + $cookie->getName(), $value, $cookie->getExpiresTime(), + $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), + $cookie->isHttpOnly(), $cookie->isRaw(), $cookie->getSameSite() + ); + } + + /** + * Determine whether encryption has been disabled for the given cookie. + * + * @param string $name + * @return bool + */ + public function isDisabled($name) + { + return in_array($name, $this->except); + } + + /** + * Determine if the cookie contents should be serialized. + * + * @param string $name + * @return bool + */ + public static function serialized($name) + { + return static::$serialize; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/composer.json new file mode 100755 index 0000000..fb587b7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Cookie/composer.json @@ -0,0 +1,39 @@ +{ + "name": "illuminate/cookie", + "description": "The Illuminate Cookie package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "symfony/http-foundation": "^5.4", + "symfony/http-kernel": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Cookie\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Capsule/Manager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Capsule/Manager.php new file mode 100755 index 0000000..b877e7c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Capsule/Manager.php @@ -0,0 +1,202 @@ +setupContainer($container ?: new Container); + + // Once we have the container setup, we will setup the default configuration + // options in the container "config" binding. This will make the database + // manager work correctly out of the box without extreme configuration. + $this->setupDefaultConfiguration(); + + $this->setupManager(); + } + + /** + * Setup the default database configuration options. + * + * @return void + */ + protected function setupDefaultConfiguration() + { + $this->container['config']['database.fetch'] = PDO::FETCH_OBJ; + + $this->container['config']['database.default'] = 'default'; + } + + /** + * Build the database manager instance. + * + * @return void + */ + protected function setupManager() + { + $factory = new ConnectionFactory($this->container); + + $this->manager = new DatabaseManager($this->container, $factory); + } + + /** + * Get a connection instance from the global manager. + * + * @param string|null $connection + * @return \Illuminate\Database\Connection + */ + public static function connection($connection = null) + { + return static::$instance->getConnection($connection); + } + + /** + * Get a fluent query builder instance. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $table + * @param string|null $as + * @param string|null $connection + * @return \Illuminate\Database\Query\Builder + */ + public static function table($table, $as = null, $connection = null) + { + return static::$instance->connection($connection)->table($table, $as); + } + + /** + * Get a schema builder instance. + * + * @param string|null $connection + * @return \Illuminate\Database\Schema\Builder + */ + public static function schema($connection = null) + { + return static::$instance->connection($connection)->getSchemaBuilder(); + } + + /** + * Get a registered connection instance. + * + * @param string|null $name + * @return \Illuminate\Database\Connection + */ + public function getConnection($name = null) + { + return $this->manager->connection($name); + } + + /** + * Register a connection with the manager. + * + * @param array $config + * @param string $name + * @return void + */ + public function addConnection(array $config, $name = 'default') + { + $connections = $this->container['config']['database.connections']; + + $connections[$name] = $config; + + $this->container['config']['database.connections'] = $connections; + } + + /** + * Bootstrap Eloquent so it is ready for usage. + * + * @return void + */ + public function bootEloquent() + { + Eloquent::setConnectionResolver($this->manager); + + // If we have an event dispatcher instance, we will go ahead and register it + // with the Eloquent ORM, allowing for model callbacks while creating and + // updating "model" instances; however, it is not necessary to operate. + if ($dispatcher = $this->getEventDispatcher()) { + Eloquent::setEventDispatcher($dispatcher); + } + } + + /** + * Set the fetch mode for the database connections. + * + * @param int $fetchMode + * @return $this + */ + public function setFetchMode($fetchMode) + { + $this->container['config']['database.fetch'] = $fetchMode; + + return $this; + } + + /** + * Get the database manager instance. + * + * @return \Illuminate\Database\DatabaseManager + */ + public function getDatabaseManager() + { + return $this->manager; + } + + /** + * Get the current event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher|null + */ + public function getEventDispatcher() + { + if ($this->container->bound('events')) { + return $this->container['events']; + } + } + + /** + * Set the event dispatcher instance to be used by connections. + * + * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher + * @return void + */ + public function setEventDispatcher(Dispatcher $dispatcher) + { + $this->container->instance('events', $dispatcher); + } + + /** + * Dynamically pass methods to the default connection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public static function __callStatic($method, $parameters) + { + return static::connection()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ClassMorphViolationException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ClassMorphViolationException.php new file mode 100644 index 0000000..6594d2d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ClassMorphViolationException.php @@ -0,0 +1,29 @@ +model = $class; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php new file mode 100644 index 0000000..7a49d77 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php @@ -0,0 +1,496 @@ +enforceOrderBy(); + + $page = 1; + + do { + // We'll execute the query for the given page and get the results. If there are + // no results we can just break and return from here. When there are results + // we will call the callback with the current chunk of these results here. + $results = $this->forPage($page, $count)->get(); + + $countResults = $results->count(); + + if ($countResults == 0) { + break; + } + + // On each chunk result set, we will pass them to the callback and then let the + // developer take care of everything within the callback, which allows us to + // keep the memory low for spinning through large result sets for working. + if ($callback($results, $page) === false) { + return false; + } + + unset($results); + + $page++; + } while ($countResults == $count); + + return true; + } + + /** + * Run a map over each item while chunking. + * + * @param callable $callback + * @param int $count + * @return \Illuminate\Support\Collection + */ + public function chunkMap(callable $callback, $count = 1000) + { + $collection = Collection::make(); + + $this->chunk($count, function ($items) use ($collection, $callback) { + $items->each(function ($item) use ($collection, $callback) { + $collection->push($callback($item)); + }); + }); + + return $collection; + } + + /** + * Execute a callback over each item while chunking. + * + * @param callable $callback + * @param int $count + * @return bool + * + * @throws \RuntimeException + */ + public function each(callable $callback, $count = 1000) + { + return $this->chunk($count, function ($results) use ($callback) { + foreach ($results as $key => $value) { + if ($callback($value, $key) === false) { + return false; + } + } + }); + } + + /** + * Chunk the results of a query by comparing IDs. + * + * @param int $count + * @param callable $callback + * @param string|null $column + * @param string|null $alias + * @return bool + */ + public function chunkById($count, callable $callback, $column = null, $alias = null) + { + $column = $column ?? $this->defaultKeyName(); + + $alias = $alias ?? $column; + + $lastId = null; + + $page = 1; + + do { + $clone = clone $this; + + // We'll execute the query for the given page and get the results. If there are + // no results we can just break and return from here. When there are results + // we will call the callback with the current chunk of these results here. + $results = $clone->forPageAfterId($count, $lastId, $column)->get(); + + $countResults = $results->count(); + + if ($countResults == 0) { + break; + } + + // On each chunk result set, we will pass them to the callback and then let the + // developer take care of everything within the callback, which allows us to + // keep the memory low for spinning through large result sets for working. + if ($callback($results, $page) === false) { + return false; + } + + $lastId = $results->last()->{$alias}; + + if ($lastId === null) { + throw new RuntimeException("The chunkById operation was aborted because the [{$alias}] column is not present in the query result."); + } + + unset($results); + + $page++; + } while ($countResults == $count); + + return true; + } + + /** + * Execute a callback over each item while chunking by ID. + * + * @param callable $callback + * @param int $count + * @param string|null $column + * @param string|null $alias + * @return bool + */ + public function eachById(callable $callback, $count = 1000, $column = null, $alias = null) + { + return $this->chunkById($count, function ($results, $page) use ($callback, $count) { + foreach ($results as $key => $value) { + if ($callback($value, (($page - 1) * $count) + $key) === false) { + return false; + } + } + }, $column, $alias); + } + + /** + * Query lazily, by chunks of the given size. + * + * @param int $chunkSize + * @return \Illuminate\Support\LazyCollection + * + * @throws \InvalidArgumentException + */ + public function lazy($chunkSize = 1000) + { + if ($chunkSize < 1) { + throw new InvalidArgumentException('The chunk size should be at least 1'); + } + + $this->enforceOrderBy(); + + return LazyCollection::make(function () use ($chunkSize) { + $page = 1; + + while (true) { + $results = $this->forPage($page++, $chunkSize)->get(); + + foreach ($results as $result) { + yield $result; + } + + if ($results->count() < $chunkSize) { + return; + } + } + }); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @return \Illuminate\Support\LazyCollection + * + * @throws \InvalidArgumentException + */ + public function lazyById($chunkSize = 1000, $column = null, $alias = null) + { + return $this->orderedLazyById($chunkSize, $column, $alias); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs in descending order. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @return \Illuminate\Support\LazyCollection + * + * @throws \InvalidArgumentException + */ + public function lazyByIdDesc($chunkSize = 1000, $column = null, $alias = null) + { + return $this->orderedLazyById($chunkSize, $column, $alias, true); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs in a given order. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @param bool $descending + * @return \Illuminate\Support\LazyCollection + * + * @throws \InvalidArgumentException + */ + protected function orderedLazyById($chunkSize = 1000, $column = null, $alias = null, $descending = false) + { + if ($chunkSize < 1) { + throw new InvalidArgumentException('The chunk size should be at least 1'); + } + + $column = $column ?? $this->defaultKeyName(); + + $alias = $alias ?? $column; + + return LazyCollection::make(function () use ($chunkSize, $column, $alias, $descending) { + $lastId = null; + + while (true) { + $clone = clone $this; + + if ($descending) { + $results = $clone->forPageBeforeId($chunkSize, $lastId, $column)->get(); + } else { + $results = $clone->forPageAfterId($chunkSize, $lastId, $column)->get(); + } + + foreach ($results as $result) { + yield $result; + } + + if ($results->count() < $chunkSize) { + return; + } + + $lastId = $results->last()->{$alias}; + } + }); + } + + /** + * Execute the query and get the first result. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|object|static|null + */ + public function first($columns = ['*']) + { + return $this->take(1)->get($columns)->first(); + } + + /** + * Execute the query and get the first result if it's the sole matching record. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|object|static|null + * + * @throws \Illuminate\Database\RecordsNotFoundException + * @throws \Illuminate\Database\MultipleRecordsFoundException + */ + public function sole($columns = ['*']) + { + $result = $this->take(2)->get($columns); + + if ($result->isEmpty()) { + throw new RecordsNotFoundException; + } + + if ($result->count() > 1) { + throw new MultipleRecordsFoundException; + } + + return $result->first(); + } + + /** + * Paginate the given query using a cursor paginator. + * + * @param int $perPage + * @param array $columns + * @param string $cursorName + * @param \Illuminate\Pagination\Cursor|string|null $cursor + * @return \Illuminate\Contracts\Pagination\CursorPaginator + */ + protected function paginateUsingCursor($perPage, $columns = ['*'], $cursorName = 'cursor', $cursor = null) + { + if (! $cursor instanceof Cursor) { + $cursor = is_string($cursor) + ? Cursor::fromEncoded($cursor) + : CursorPaginator::resolveCurrentCursor($cursorName, $cursor); + } + + $orders = $this->ensureOrderForCursorPagination(! is_null($cursor) && $cursor->pointsToPreviousItems()); + + if (! is_null($cursor)) { + $addCursorConditions = function (self $builder, $previousColumn, $i) use (&$addCursorConditions, $cursor, $orders) { + $unionBuilders = isset($builder->unions) ? collect($builder->unions)->pluck('query') : collect(); + + if (! is_null($previousColumn)) { + $builder->where( + $this->getOriginalColumnNameForCursorPagination($this, $previousColumn), + '=', + $cursor->parameter($previousColumn) + ); + + $unionBuilders->each(function ($unionBuilder) use ($previousColumn, $cursor) { + $unionBuilder->where( + $this->getOriginalColumnNameForCursorPagination($this, $previousColumn), + '=', + $cursor->parameter($previousColumn) + ); + + $this->addBinding($unionBuilder->getRawBindings()['where'], 'union'); + }); + } + + $builder->where(function (self $builder) use ($addCursorConditions, $cursor, $orders, $i, $unionBuilders) { + ['column' => $column, 'direction' => $direction] = $orders[$i]; + + $builder->where( + $this->getOriginalColumnNameForCursorPagination($this, $column), + $direction === 'asc' ? '>' : '<', + $cursor->parameter($column) + ); + + if ($i < $orders->count() - 1) { + $builder->orWhere(function (self $builder) use ($addCursorConditions, $column, $i) { + $addCursorConditions($builder, $column, $i + 1); + }); + } + + $unionBuilders->each(function ($unionBuilder) use ($column, $direction, $cursor, $i, $orders, $addCursorConditions) { + $unionBuilder->where(function ($unionBuilder) use ($column, $direction, $cursor, $i, $orders, $addCursorConditions) { + $unionBuilder->where( + $this->getOriginalColumnNameForCursorPagination($this, $column), + $direction === 'asc' ? '>' : '<', + $cursor->parameter($column) + ); + + if ($i < $orders->count() - 1) { + $unionBuilder->orWhere(function (self $builder) use ($addCursorConditions, $column, $i) { + $addCursorConditions($builder, $column, $i + 1); + }); + } + + $this->addBinding($unionBuilder->getRawBindings()['where'], 'union'); + }); + }); + }); + }; + + $addCursorConditions($this, null, 0); + } + + $this->limit($perPage + 1); + + return $this->cursorPaginator($this->get($columns), $perPage, $cursor, [ + 'path' => Paginator::resolveCurrentPath(), + 'cursorName' => $cursorName, + 'parameters' => $orders->pluck('column')->toArray(), + ]); + } + + /** + * Get the original column name of the given column, without any aliasing. + * + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + * @param string $parameter + * @return string + */ + protected function getOriginalColumnNameForCursorPagination($builder, string $parameter) + { + $columns = $builder instanceof Builder ? $builder->getQuery()->columns : $builder->columns; + + if (! is_null($columns)) { + foreach ($columns as $column) { + if (($position = stripos($column, ' as ')) !== false) { + $as = substr($column, $position, 4); + + [$original, $alias] = explode($as, $column); + + if ($parameter === $alias) { + return $original; + } + } + } + } + + return $parameter; + } + + /** + * Create a new length-aware paginator instance. + * + * @param \Illuminate\Support\Collection $items + * @param int $total + * @param int $perPage + * @param int $currentPage + * @param array $options + * @return \Illuminate\Pagination\LengthAwarePaginator + */ + protected function paginator($items, $total, $perPage, $currentPage, $options) + { + return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact( + 'items', 'total', 'perPage', 'currentPage', 'options' + )); + } + + /** + * Create a new simple paginator instance. + * + * @param \Illuminate\Support\Collection $items + * @param int $perPage + * @param int $currentPage + * @param array $options + * @return \Illuminate\Pagination\Paginator + */ + protected function simplePaginator($items, $perPage, $currentPage, $options) + { + return Container::getInstance()->makeWith(Paginator::class, compact( + 'items', 'perPage', 'currentPage', 'options' + )); + } + + /** + * Create a new cursor paginator instance. + * + * @param \Illuminate\Support\Collection $items + * @param int $perPage + * @param \Illuminate\Pagination\Cursor $cursor + * @param array $options + * @return \Illuminate\Pagination\CursorPaginator + */ + protected function cursorPaginator($items, $perPage, $cursor, $options) + { + return Container::getInstance()->makeWith(CursorPaginator::class, compact( + 'items', 'perPage', 'cursor', 'options' + )); + } + + /** + * Pass the query to a given callback. + * + * @param callable $callback + * @return $this|mixed + */ + public function tap($callback) + { + return $this->when(true, $callback); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/ExplainsQueries.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/ExplainsQueries.php new file mode 100644 index 0000000..7168de1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/ExplainsQueries.php @@ -0,0 +1,24 @@ +toSql(); + + $bindings = $this->getBindings(); + + $explanation = $this->getConnection()->select('EXPLAIN '.$sql, $bindings); + + return new Collection($explanation); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php new file mode 100644 index 0000000..fac7029 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php @@ -0,0 +1,334 @@ +beginTransaction(); + + // We'll simply execute the given callback within a try / catch block and if we + // catch any exception we can rollback this transaction so that none of this + // gets actually persisted to a database or stored in a permanent fashion. + try { + $callbackResult = $callback($this); + } + + // If we catch an exception we'll rollback this transaction and try again if we + // are not out of attempts. If we are out of attempts we will just throw the + // exception back out and let the developer handle an uncaught exceptions. + catch (Throwable $e) { + $this->handleTransactionException( + $e, $currentAttempt, $attempts + ); + + continue; + } + + try { + if ($this->transactions == 1) { + $this->getPdo()->commit(); + } + + $this->transactions = max(0, $this->transactions - 1); + + if ($this->transactions == 0) { + optional($this->transactionsManager)->commit($this->getName()); + } + } catch (Throwable $e) { + $this->handleCommitTransactionException( + $e, $currentAttempt, $attempts + ); + + continue; + } + + $this->fireConnectionEvent('committed'); + + return $callbackResult; + } + } + + /** + * Handle an exception encountered when running a transacted statement. + * + * @param \Throwable $e + * @param int $currentAttempt + * @param int $maxAttempts + * @return void + * + * @throws \Throwable + */ + protected function handleTransactionException(Throwable $e, $currentAttempt, $maxAttempts) + { + // On a deadlock, MySQL rolls back the entire transaction so we can't just + // retry the query. We have to throw this exception all the way out and + // let the developer handle it in another way. We will decrement too. + if ($this->causedByConcurrencyError($e) && + $this->transactions > 1) { + $this->transactions--; + + optional($this->transactionsManager)->rollback( + $this->getName(), $this->transactions + ); + + throw $e; + } + + // If there was an exception we will rollback this transaction and then we + // can check if we have exceeded the maximum attempt count for this and + // if we haven't we will return and try this query again in our loop. + $this->rollBack(); + + if ($this->causedByConcurrencyError($e) && + $currentAttempt < $maxAttempts) { + return; + } + + throw $e; + } + + /** + * Start a new database transaction. + * + * @return void + * + * @throws \Throwable + */ + public function beginTransaction() + { + $this->createTransaction(); + + $this->transactions++; + + optional($this->transactionsManager)->begin( + $this->getName(), $this->transactions + ); + + $this->fireConnectionEvent('beganTransaction'); + } + + /** + * Create a transaction within the database. + * + * @return void + * + * @throws \Throwable + */ + protected function createTransaction() + { + if ($this->transactions == 0) { + $this->reconnectIfMissingConnection(); + + try { + $this->getPdo()->beginTransaction(); + } catch (Throwable $e) { + $this->handleBeginTransactionException($e); + } + } elseif ($this->transactions >= 1 && $this->queryGrammar->supportsSavepoints()) { + $this->createSavepoint(); + } + } + + /** + * Create a save point within the database. + * + * @return void + * + * @throws \Throwable + */ + protected function createSavepoint() + { + $this->getPdo()->exec( + $this->queryGrammar->compileSavepoint('trans'.($this->transactions + 1)) + ); + } + + /** + * Handle an exception from a transaction beginning. + * + * @param \Throwable $e + * @return void + * + * @throws \Throwable + */ + protected function handleBeginTransactionException(Throwable $e) + { + if ($this->causedByLostConnection($e)) { + $this->reconnect(); + + $this->getPdo()->beginTransaction(); + } else { + throw $e; + } + } + + /** + * Commit the active database transaction. + * + * @return void + * + * @throws \Throwable + */ + public function commit() + { + if ($this->transactions == 1) { + $this->getPdo()->commit(); + } + + $this->transactions = max(0, $this->transactions - 1); + + if ($this->transactions == 0) { + optional($this->transactionsManager)->commit($this->getName()); + } + + $this->fireConnectionEvent('committed'); + } + + /** + * Handle an exception encountered when committing a transaction. + * + * @param \Throwable $e + * @param int $currentAttempt + * @param int $maxAttempts + * @return void + * + * @throws \Throwable + */ + protected function handleCommitTransactionException(Throwable $e, $currentAttempt, $maxAttempts) + { + $this->transactions = max(0, $this->transactions - 1); + + if ($this->causedByConcurrencyError($e) && + $currentAttempt < $maxAttempts) { + return; + } + + if ($this->causedByLostConnection($e)) { + $this->transactions = 0; + } + + throw $e; + } + + /** + * Rollback the active database transaction. + * + * @param int|null $toLevel + * @return void + * + * @throws \Throwable + */ + public function rollBack($toLevel = null) + { + // We allow developers to rollback to a certain transaction level. We will verify + // that this given transaction level is valid before attempting to rollback to + // that level. If it's not we will just return out and not attempt anything. + $toLevel = is_null($toLevel) + ? $this->transactions - 1 + : $toLevel; + + if ($toLevel < 0 || $toLevel >= $this->transactions) { + return; + } + + // Next, we will actually perform this rollback within this database and fire the + // rollback event. We will also set the current transaction level to the given + // level that was passed into this method so it will be right from here out. + try { + $this->performRollBack($toLevel); + } catch (Throwable $e) { + $this->handleRollBackException($e); + } + + $this->transactions = $toLevel; + + optional($this->transactionsManager)->rollback( + $this->getName(), $this->transactions + ); + + $this->fireConnectionEvent('rollingBack'); + } + + /** + * Perform a rollback within the database. + * + * @param int $toLevel + * @return void + * + * @throws \Throwable + */ + protected function performRollBack($toLevel) + { + if ($toLevel == 0) { + $this->getPdo()->rollBack(); + } elseif ($this->queryGrammar->supportsSavepoints()) { + $this->getPdo()->exec( + $this->queryGrammar->compileSavepointRollBack('trans'.($toLevel + 1)) + ); + } + } + + /** + * Handle an exception from a rollback. + * + * @param \Throwable $e + * @return void + * + * @throws \Throwable + */ + protected function handleRollBackException(Throwable $e) + { + if ($this->causedByLostConnection($e)) { + $this->transactions = 0; + + optional($this->transactionsManager)->rollback( + $this->getName(), $this->transactions + ); + } + + throw $e; + } + + /** + * Get the number of active transactions. + * + * @return int + */ + public function transactionLevel() + { + return $this->transactions; + } + + /** + * Execute the callback after a transaction commits. + * + * @param callable $callback + * @return void + * + * @throws \RuntimeException + */ + public function afterCommit($callback) + { + if ($this->transactionsManager) { + return $this->transactionsManager->addCallback($callback); + } + + throw new RuntimeException('Transactions Manager has not been set.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConfigurationUrlParser.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConfigurationUrlParser.php new file mode 100644 index 0000000..bc7c624 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConfigurationUrlParser.php @@ -0,0 +1,10 @@ +pdo = $pdo; + + // First we will setup the default properties. We keep track of the DB + // name we are connected to since it is needed when some reflective + // type commands are run such as checking whether a table exists. + $this->database = $database; + + $this->tablePrefix = $tablePrefix; + + $this->config = $config; + + // We need to initialize a query grammar and the query post processors + // which are both very important parts of the database abstractions + // so we initialize these to their default values while starting. + $this->useDefaultQueryGrammar(); + + $this->useDefaultPostProcessor(); + } + + /** + * Set the query grammar to the default implementation. + * + * @return void + */ + public function useDefaultQueryGrammar() + { + $this->queryGrammar = $this->getDefaultQueryGrammar(); + } + + /** + * Get the default query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\Grammar + */ + protected function getDefaultQueryGrammar() + { + return new QueryGrammar; + } + + /** + * Set the schema grammar to the default implementation. + * + * @return void + */ + public function useDefaultSchemaGrammar() + { + $this->schemaGrammar = $this->getDefaultSchemaGrammar(); + } + + /** + * Get the default schema grammar instance. + * + * @return \Illuminate\Database\Schema\Grammars\Grammar + */ + protected function getDefaultSchemaGrammar() + { + // + } + + /** + * Set the query post processor to the default implementation. + * + * @return void + */ + public function useDefaultPostProcessor() + { + $this->postProcessor = $this->getDefaultPostProcessor(); + } + + /** + * Get the default post processor instance. + * + * @return \Illuminate\Database\Query\Processors\Processor + */ + protected function getDefaultPostProcessor() + { + return new Processor; + } + + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\Builder + */ + public function getSchemaBuilder() + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new SchemaBuilder($this); + } + + /** + * Begin a fluent query against a database table. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $table + * @param string|null $as + * @return \Illuminate\Database\Query\Builder + */ + public function table($table, $as = null) + { + return $this->query()->from($table, $as); + } + + /** + * Get a new query builder instance. + * + * @return \Illuminate\Database\Query\Builder + */ + public function query() + { + return new QueryBuilder( + $this, $this->getQueryGrammar(), $this->getPostProcessor() + ); + } + + /** + * Run a select statement and return a single result. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return mixed + */ + public function selectOne($query, $bindings = [], $useReadPdo = true) + { + $records = $this->select($query, $bindings, $useReadPdo); + + return array_shift($records); + } + + /** + * Run a select statement against the database. + * + * @param string $query + * @param array $bindings + * @return array + */ + public function selectFromWriteConnection($query, $bindings = []) + { + return $this->select($query, $bindings, false); + } + + /** + * Run a select statement against the database. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return array + */ + public function select($query, $bindings = [], $useReadPdo = true) + { + return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) { + if ($this->pretending()) { + return []; + } + + // For select statements, we'll simply execute the query and return an array + // of the database result set. Each element in the array will be a single + // row from the database table, and will either be an array or objects. + $statement = $this->prepared( + $this->getPdoForSelect($useReadPdo)->prepare($query) + ); + + $this->bindValues($statement, $this->prepareBindings($bindings)); + + $statement->execute(); + + return $statement->fetchAll(); + }); + } + + /** + * Run a select statement against the database and returns a generator. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return \Generator + */ + public function cursor($query, $bindings = [], $useReadPdo = true) + { + $statement = $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) { + if ($this->pretending()) { + return []; + } + + // First we will create a statement for the query. Then, we will set the fetch + // mode and prepare the bindings for the query. Once that's done we will be + // ready to execute the query against the database and return the cursor. + $statement = $this->prepared($this->getPdoForSelect($useReadPdo) + ->prepare($query)); + + $this->bindValues( + $statement, $this->prepareBindings($bindings) + ); + + // Next, we'll execute the query against the database and return the statement + // so we can return the cursor. The cursor will use a PHP generator to give + // back one row at a time without using a bunch of memory to render them. + $statement->execute(); + + return $statement; + }); + + while ($record = $statement->fetch()) { + yield $record; + } + } + + /** + * Configure the PDO prepared statement. + * + * @param \PDOStatement $statement + * @return \PDOStatement + */ + protected function prepared(PDOStatement $statement) + { + $statement->setFetchMode($this->fetchMode); + + $this->event(new StatementPrepared( + $this, $statement + )); + + return $statement; + } + + /** + * Get the PDO connection to use for a select query. + * + * @param bool $useReadPdo + * @return \PDO + */ + protected function getPdoForSelect($useReadPdo = true) + { + return $useReadPdo ? $this->getReadPdo() : $this->getPdo(); + } + + /** + * Run an insert statement against the database. + * + * @param string $query + * @param array $bindings + * @return bool + */ + public function insert($query, $bindings = []) + { + return $this->statement($query, $bindings); + } + + /** + * Run an update statement against the database. + * + * @param string $query + * @param array $bindings + * @return int + */ + public function update($query, $bindings = []) + { + return $this->affectingStatement($query, $bindings); + } + + /** + * Run a delete statement against the database. + * + * @param string $query + * @param array $bindings + * @return int + */ + public function delete($query, $bindings = []) + { + return $this->affectingStatement($query, $bindings); + } + + /** + * Execute an SQL statement and return the boolean result. + * + * @param string $query + * @param array $bindings + * @return bool + */ + public function statement($query, $bindings = []) + { + return $this->run($query, $bindings, function ($query, $bindings) { + if ($this->pretending()) { + return true; + } + + $statement = $this->getPdo()->prepare($query); + + $this->bindValues($statement, $this->prepareBindings($bindings)); + + $this->recordsHaveBeenModified(); + + return $statement->execute(); + }); + } + + /** + * Run an SQL statement and get the number of rows affected. + * + * @param string $query + * @param array $bindings + * @return int + */ + public function affectingStatement($query, $bindings = []) + { + return $this->run($query, $bindings, function ($query, $bindings) { + if ($this->pretending()) { + return 0; + } + + // For update or delete statements, we want to get the number of rows affected + // by the statement and return that back to the developer. We'll first need + // to execute the statement and then we'll use PDO to fetch the affected. + $statement = $this->getPdo()->prepare($query); + + $this->bindValues($statement, $this->prepareBindings($bindings)); + + $statement->execute(); + + $this->recordsHaveBeenModified( + ($count = $statement->rowCount()) > 0 + ); + + return $count; + }); + } + + /** + * Run a raw, unprepared query against the PDO connection. + * + * @param string $query + * @return bool + */ + public function unprepared($query) + { + return $this->run($query, [], function ($query) { + if ($this->pretending()) { + return true; + } + + $this->recordsHaveBeenModified( + $change = $this->getPdo()->exec($query) !== false + ); + + return $change; + }); + } + + /** + * Execute the given callback in "dry run" mode. + * + * @param \Closure $callback + * @return array + */ + public function pretend(Closure $callback) + { + return $this->withFreshQueryLog(function () use ($callback) { + $this->pretending = true; + + // Basically to make the database connection "pretend", we will just return + // the default values for all the query methods, then we will return an + // array of queries that were "executed" within the Closure callback. + $callback($this); + + $this->pretending = false; + + return $this->queryLog; + }); + } + + /** + * Execute the given callback in "dry run" mode. + * + * @param \Closure $callback + * @return array + */ + protected function withFreshQueryLog($callback) + { + $loggingQueries = $this->loggingQueries; + + // First we will back up the value of the logging queries property and then + // we'll be ready to run callbacks. This query log will also get cleared + // so we will have a new log of all the queries that are executed now. + $this->enableQueryLog(); + + $this->queryLog = []; + + // Now we'll execute this callback and capture the result. Once it has been + // executed we will restore the value of query logging and give back the + // value of the callback so the original callers can have the results. + $result = $callback(); + + $this->loggingQueries = $loggingQueries; + + return $result; + } + + /** + * Bind values to their parameters in the given statement. + * + * @param \PDOStatement $statement + * @param array $bindings + * @return void + */ + public function bindValues($statement, $bindings) + { + foreach ($bindings as $key => $value) { + $statement->bindValue( + is_string($key) ? $key : $key + 1, + $value, + is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR + ); + } + } + + /** + * Prepare the query bindings for execution. + * + * @param array $bindings + * @return array + */ + public function prepareBindings(array $bindings) + { + $grammar = $this->getQueryGrammar(); + + foreach ($bindings as $key => $value) { + // We need to transform all instances of DateTimeInterface into the actual + // date string. Each query grammar maintains its own date string format + // so we'll just ask the grammar for the format to get from the date. + if ($value instanceof DateTimeInterface) { + $bindings[$key] = $value->format($grammar->getDateFormat()); + } elseif (is_bool($value)) { + $bindings[$key] = (int) $value; + } + } + + return $bindings; + } + + /** + * Run a SQL statement and log its execution context. + * + * @param string $query + * @param array $bindings + * @param \Closure $callback + * @return mixed + * + * @throws \Illuminate\Database\QueryException + */ + protected function run($query, $bindings, Closure $callback) + { + foreach ($this->beforeExecutingCallbacks as $beforeExecutingCallback) { + $beforeExecutingCallback($query, $bindings, $this); + } + + $this->reconnectIfMissingConnection(); + + $start = microtime(true); + + // Here we will run this query. If an exception occurs we'll determine if it was + // caused by a connection that has been lost. If that is the cause, we'll try + // to re-establish connection and re-run the query with a fresh connection. + try { + $result = $this->runQueryCallback($query, $bindings, $callback); + } catch (QueryException $e) { + $result = $this->handleQueryException( + $e, $query, $bindings, $callback + ); + } + + // Once we have run the query we will calculate the time that it took to run and + // then log the query, bindings, and execution time so we will report them on + // the event that the developer needs them. We'll log time in milliseconds. + $this->logQuery( + $query, $bindings, $this->getElapsedTime($start) + ); + + return $result; + } + + /** + * Run a SQL statement. + * + * @param string $query + * @param array $bindings + * @param \Closure $callback + * @return mixed + * + * @throws \Illuminate\Database\QueryException + */ + protected function runQueryCallback($query, $bindings, Closure $callback) + { + // To execute the statement, we'll simply call the callback, which will actually + // run the SQL against the PDO connection. Then we can calculate the time it + // took to execute and log the query SQL, bindings and time in our memory. + try { + return $callback($query, $bindings); + } + + // If an exception occurs when attempting to run a query, we'll format the error + // message to include the bindings with SQL, which will make this exception a + // lot more helpful to the developer instead of just the database's errors. + catch (Exception $e) { + throw new QueryException( + $query, $this->prepareBindings($bindings), $e + ); + } + } + + /** + * Log a query in the connection's query log. + * + * @param string $query + * @param array $bindings + * @param float|null $time + * @return void + */ + public function logQuery($query, $bindings, $time = null) + { + $this->event(new QueryExecuted($query, $bindings, $time, $this)); + + if ($this->loggingQueries) { + $this->queryLog[] = compact('query', 'bindings', 'time'); + } + } + + /** + * Get the elapsed time since a given starting point. + * + * @param int $start + * @return float + */ + protected function getElapsedTime($start) + { + return round((microtime(true) - $start) * 1000, 2); + } + + /** + * Handle a query exception. + * + * @param \Illuminate\Database\QueryException $e + * @param string $query + * @param array $bindings + * @param \Closure $callback + * @return mixed + * + * @throws \Illuminate\Database\QueryException + */ + protected function handleQueryException(QueryException $e, $query, $bindings, Closure $callback) + { + if ($this->transactions >= 1) { + throw $e; + } + + return $this->tryAgainIfCausedByLostConnection( + $e, $query, $bindings, $callback + ); + } + + /** + * Handle a query exception that occurred during query execution. + * + * @param \Illuminate\Database\QueryException $e + * @param string $query + * @param array $bindings + * @param \Closure $callback + * @return mixed + * + * @throws \Illuminate\Database\QueryException + */ + protected function tryAgainIfCausedByLostConnection(QueryException $e, $query, $bindings, Closure $callback) + { + if ($this->causedByLostConnection($e->getPrevious())) { + $this->reconnect(); + + return $this->runQueryCallback($query, $bindings, $callback); + } + + throw $e; + } + + /** + * Reconnect to the database. + * + * @return void + * + * @throws \LogicException + */ + public function reconnect() + { + if (is_callable($this->reconnector)) { + $this->doctrineConnection = null; + + return call_user_func($this->reconnector, $this); + } + + throw new LogicException('Lost connection and no reconnector available.'); + } + + /** + * Reconnect to the database if a PDO connection is missing. + * + * @return void + */ + protected function reconnectIfMissingConnection() + { + if (is_null($this->pdo)) { + $this->reconnect(); + } + } + + /** + * Disconnect from the underlying PDO connection. + * + * @return void + */ + public function disconnect() + { + $this->setPdo(null)->setReadPdo(null); + + $this->doctrineConnection = null; + } + + /** + * Register a hook to be run just before a database query is executed. + * + * @param \Closure $callback + * @return $this + */ + public function beforeExecuting(Closure $callback) + { + $this->beforeExecutingCallbacks[] = $callback; + + return $this; + } + + /** + * Register a database query listener with the connection. + * + * @param \Closure $callback + * @return void + */ + public function listen(Closure $callback) + { + if (isset($this->events)) { + $this->events->listen(Events\QueryExecuted::class, $callback); + } + } + + /** + * Fire an event for this connection. + * + * @param string $event + * @return array|null + */ + protected function fireConnectionEvent($event) + { + if (! isset($this->events)) { + return; + } + + switch ($event) { + case 'beganTransaction': + return $this->events->dispatch(new TransactionBeginning($this)); + case 'committed': + return $this->events->dispatch(new TransactionCommitted($this)); + case 'rollingBack': + return $this->events->dispatch(new TransactionRolledBack($this)); + } + } + + /** + * Fire the given event if possible. + * + * @param mixed $event + * @return void + */ + protected function event($event) + { + if (isset($this->events)) { + $this->events->dispatch($event); + } + } + + /** + * Get a new raw query expression. + * + * @param mixed $value + * @return \Illuminate\Database\Query\Expression + */ + public function raw($value) + { + return new Expression($value); + } + + /** + * Determine if the database connection has modified any database records. + * + * @return bool + */ + public function hasModifiedRecords() + { + return $this->recordsModified; + } + + /** + * Indicate if any records have been modified. + * + * @param bool $value + * @return void + */ + public function recordsHaveBeenModified($value = true) + { + if (! $this->recordsModified) { + $this->recordsModified = $value; + } + } + + /** + * Set the record modification state. + * + * @param bool $value + * @return $this + */ + public function setRecordModificationState(bool $value) + { + $this->recordsModified = $value; + + return $this; + } + + /** + * Reset the record modification state. + * + * @return void + */ + public function forgetRecordModificationState() + { + $this->recordsModified = false; + } + + /** + * Indicate that the connection should use the write PDO connection for reads. + * + * @param bool $value + * @return $this + */ + public function useWriteConnectionWhenReading($value = true) + { + $this->readOnWriteConnection = $value; + + return $this; + } + + /** + * Is Doctrine available? + * + * @return bool + */ + public function isDoctrineAvailable() + { + return class_exists('Doctrine\DBAL\Connection'); + } + + /** + * Get a Doctrine Schema Column instance. + * + * @param string $table + * @param string $column + * @return \Doctrine\DBAL\Schema\Column + */ + public function getDoctrineColumn($table, $column) + { + $schema = $this->getDoctrineSchemaManager(); + + return $schema->listTableDetails($table)->getColumn($column); + } + + /** + * Get the Doctrine DBAL schema manager for the connection. + * + * @return \Doctrine\DBAL\Schema\AbstractSchemaManager + */ + public function getDoctrineSchemaManager() + { + $connection = $this->getDoctrineConnection(); + + // Doctrine v2 expects one parameter while v3 expects two. 2nd will be ignored on v2... + return $this->getDoctrineDriver()->getSchemaManager( + $connection, + $connection->getDatabasePlatform() + ); + } + + /** + * Get the Doctrine DBAL database connection instance. + * + * @return \Doctrine\DBAL\Connection + */ + public function getDoctrineConnection() + { + if (is_null($this->doctrineConnection)) { + $driver = $this->getDoctrineDriver(); + + $this->doctrineConnection = new DoctrineConnection(array_filter([ + 'pdo' => $this->getPdo(), + 'dbname' => $this->getDatabaseName(), + 'driver' => method_exists($driver, 'getName') ? $driver->getName() : null, + 'serverVersion' => $this->getConfig('server_version'), + ]), $driver); + + foreach ($this->doctrineTypeMappings as $name => $type) { + $this->doctrineConnection + ->getDatabasePlatform() + ->registerDoctrineTypeMapping($type, $name); + } + } + + return $this->doctrineConnection; + } + + /** + * Register a custom Doctrine mapping type. + * + * @param string $class + * @param string $name + * @param string $type + * @return void + * + * @throws \Doctrine\DBAL\DBALException + * @throws \RuntimeException + */ + public function registerDoctrineType(string $class, string $name, string $type): void + { + if (! $this->isDoctrineAvailable()) { + throw new RuntimeException( + 'Registering a custom Doctrine type requires Doctrine DBAL (doctrine/dbal).' + ); + } + + if (! Type::hasType($name)) { + Type::addType($name, $class); + } + + $this->doctrineTypeMappings[$name] = $type; + } + + /** + * Get the current PDO connection. + * + * @return \PDO + */ + public function getPdo() + { + if ($this->pdo instanceof Closure) { + return $this->pdo = call_user_func($this->pdo); + } + + return $this->pdo; + } + + /** + * Get the current PDO connection parameter without executing any reconnect logic. + * + * @return \PDO|\Closure|null + */ + public function getRawPdo() + { + return $this->pdo; + } + + /** + * Get the current PDO connection used for reading. + * + * @return \PDO + */ + public function getReadPdo() + { + if ($this->transactions > 0) { + return $this->getPdo(); + } + + if ($this->readOnWriteConnection || + ($this->recordsModified && $this->getConfig('sticky'))) { + return $this->getPdo(); + } + + if ($this->readPdo instanceof Closure) { + return $this->readPdo = call_user_func($this->readPdo); + } + + return $this->readPdo ?: $this->getPdo(); + } + + /** + * Get the current read PDO connection parameter without executing any reconnect logic. + * + * @return \PDO|\Closure|null + */ + public function getRawReadPdo() + { + return $this->readPdo; + } + + /** + * Set the PDO connection. + * + * @param \PDO|\Closure|null $pdo + * @return $this + */ + public function setPdo($pdo) + { + $this->transactions = 0; + + $this->pdo = $pdo; + + return $this; + } + + /** + * Set the PDO connection used for reading. + * + * @param \PDO|\Closure|null $pdo + * @return $this + */ + public function setReadPdo($pdo) + { + $this->readPdo = $pdo; + + return $this; + } + + /** + * Set the reconnect instance on the connection. + * + * @param callable $reconnector + * @return $this + */ + public function setReconnector(callable $reconnector) + { + $this->reconnector = $reconnector; + + return $this; + } + + /** + * Get the database connection name. + * + * @return string|null + */ + public function getName() + { + return $this->getConfig('name'); + } + + /** + * Get the database connection full name. + * + * @return string|null + */ + public function getNameWithReadWriteType() + { + return $this->getName().($this->readWriteType ? '::'.$this->readWriteType : ''); + } + + /** + * Get an option from the configuration options. + * + * @param string|null $option + * @return mixed + */ + public function getConfig($option = null) + { + return Arr::get($this->config, $option); + } + + /** + * Get the PDO driver name. + * + * @return string + */ + public function getDriverName() + { + return $this->getConfig('driver'); + } + + /** + * Get the query grammar used by the connection. + * + * @return \Illuminate\Database\Query\Grammars\Grammar + */ + public function getQueryGrammar() + { + return $this->queryGrammar; + } + + /** + * Set the query grammar used by the connection. + * + * @param \Illuminate\Database\Query\Grammars\Grammar $grammar + * @return $this + */ + public function setQueryGrammar(Query\Grammars\Grammar $grammar) + { + $this->queryGrammar = $grammar; + + return $this; + } + + /** + * Get the schema grammar used by the connection. + * + * @return \Illuminate\Database\Schema\Grammars\Grammar + */ + public function getSchemaGrammar() + { + return $this->schemaGrammar; + } + + /** + * Set the schema grammar used by the connection. + * + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @return $this + */ + public function setSchemaGrammar(Schema\Grammars\Grammar $grammar) + { + $this->schemaGrammar = $grammar; + + return $this; + } + + /** + * Get the query post processor used by the connection. + * + * @return \Illuminate\Database\Query\Processors\Processor + */ + public function getPostProcessor() + { + return $this->postProcessor; + } + + /** + * Set the query post processor used by the connection. + * + * @param \Illuminate\Database\Query\Processors\Processor $processor + * @return $this + */ + public function setPostProcessor(Processor $processor) + { + $this->postProcessor = $processor; + + return $this; + } + + /** + * Get the event dispatcher used by the connection. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public function getEventDispatcher() + { + return $this->events; + } + + /** + * Set the event dispatcher instance on the connection. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return $this + */ + public function setEventDispatcher(Dispatcher $events) + { + $this->events = $events; + + return $this; + } + + /** + * Unset the event dispatcher for this connection. + * + * @return void + */ + public function unsetEventDispatcher() + { + $this->events = null; + } + + /** + * Set the transaction manager instance on the connection. + * + * @param \Illuminate\Database\DatabaseTransactionsManager $manager + * @return $this + */ + public function setTransactionManager($manager) + { + $this->transactionsManager = $manager; + + return $this; + } + + /** + * Unset the transaction manager for this connection. + * + * @return void + */ + public function unsetTransactionManager() + { + $this->transactionsManager = null; + } + + /** + * Determine if the connection is in a "dry run". + * + * @return bool + */ + public function pretending() + { + return $this->pretending === true; + } + + /** + * Get the connection query log. + * + * @return array + */ + public function getQueryLog() + { + return $this->queryLog; + } + + /** + * Clear the query log. + * + * @return void + */ + public function flushQueryLog() + { + $this->queryLog = []; + } + + /** + * Enable the query log on the connection. + * + * @return void + */ + public function enableQueryLog() + { + $this->loggingQueries = true; + } + + /** + * Disable the query log on the connection. + * + * @return void + */ + public function disableQueryLog() + { + $this->loggingQueries = false; + } + + /** + * Determine whether we're logging queries. + * + * @return bool + */ + public function logging() + { + return $this->loggingQueries; + } + + /** + * Get the name of the connected database. + * + * @return string + */ + public function getDatabaseName() + { + return $this->database; + } + + /** + * Set the name of the connected database. + * + * @param string $database + * @return $this + */ + public function setDatabaseName($database) + { + $this->database = $database; + + return $this; + } + + /** + * Set the read / write type of the connection. + * + * @param string|null $readWriteType + * @return $this + */ + public function setReadWriteType($readWriteType) + { + $this->readWriteType = $readWriteType; + + return $this; + } + + /** + * Get the table prefix for the connection. + * + * @return string + */ + public function getTablePrefix() + { + return $this->tablePrefix; + } + + /** + * Set the table prefix in use by the connection. + * + * @param string $prefix + * @return $this + */ + public function setTablePrefix($prefix) + { + $this->tablePrefix = $prefix; + + $this->getQueryGrammar()->setTablePrefix($prefix); + + return $this; + } + + /** + * Set the table prefix and return the grammar. + * + * @param \Illuminate\Database\Grammar $grammar + * @return \Illuminate\Database\Grammar + */ + public function withTablePrefix(Grammar $grammar) + { + $grammar->setTablePrefix($this->tablePrefix); + + return $grammar; + } + + /** + * Register a connection resolver. + * + * @param string $driver + * @param \Closure $callback + * @return void + */ + public static function resolverFor($driver, Closure $callback) + { + static::$resolvers[$driver] = $callback; + } + + /** + * Get the connection resolver for the given driver. + * + * @param string $driver + * @return mixed + */ + public static function getResolver($driver) + { + return static::$resolvers[$driver] ?? null; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConnectionInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConnectionInterface.php new file mode 100755 index 0000000..00b2395 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConnectionInterface.php @@ -0,0 +1,170 @@ + $connection) { + $this->addConnection($name, $connection); + } + } + + /** + * Get a database connection instance. + * + * @param string|null $name + * @return \Illuminate\Database\ConnectionInterface + */ + public function connection($name = null) + { + if (is_null($name)) { + $name = $this->getDefaultConnection(); + } + + return $this->connections[$name]; + } + + /** + * Add a connection to the resolver. + * + * @param string $name + * @param \Illuminate\Database\ConnectionInterface $connection + * @return void + */ + public function addConnection($name, ConnectionInterface $connection) + { + $this->connections[$name] = $connection; + } + + /** + * Check if a connection has been registered. + * + * @param string $name + * @return bool + */ + public function hasConnection($name) + { + return isset($this->connections[$name]); + } + + /** + * Get the default connection name. + * + * @return string + */ + public function getDefaultConnection() + { + return $this->default; + } + + /** + * Set the default connection name. + * + * @param string $name + * @return void + */ + public function setDefaultConnection($name) + { + $this->default = $name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConnectionResolverInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConnectionResolverInterface.php new file mode 100755 index 0000000..b31e5a7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/ConnectionResolverInterface.php @@ -0,0 +1,29 @@ +container = $container; + } + + /** + * Establish a PDO connection based on the configuration. + * + * @param array $config + * @param string|null $name + * @return \Illuminate\Database\Connection + */ + public function make(array $config, $name = null) + { + $config = $this->parseConfig($config, $name); + + if (isset($config['read'])) { + return $this->createReadWriteConnection($config); + } + + return $this->createSingleConnection($config); + } + + /** + * Parse and prepare the database configuration. + * + * @param array $config + * @param string $name + * @return array + */ + protected function parseConfig(array $config, $name) + { + return Arr::add(Arr::add($config, 'prefix', ''), 'name', $name); + } + + /** + * Create a single database connection instance. + * + * @param array $config + * @return \Illuminate\Database\Connection + */ + protected function createSingleConnection(array $config) + { + $pdo = $this->createPdoResolver($config); + + return $this->createConnection( + $config['driver'], $pdo, $config['database'], $config['prefix'], $config + ); + } + + /** + * Create a read / write database connection instance. + * + * @param array $config + * @return \Illuminate\Database\Connection + */ + protected function createReadWriteConnection(array $config) + { + $connection = $this->createSingleConnection($this->getWriteConfig($config)); + + return $connection->setReadPdo($this->createReadPdo($config)); + } + + /** + * Create a new PDO instance for reading. + * + * @param array $config + * @return \Closure + */ + protected function createReadPdo(array $config) + { + return $this->createPdoResolver($this->getReadConfig($config)); + } + + /** + * Get the read configuration for a read / write connection. + * + * @param array $config + * @return array + */ + protected function getReadConfig(array $config) + { + return $this->mergeReadWriteConfig( + $config, $this->getReadWriteConfig($config, 'read') + ); + } + + /** + * Get the write configuration for a read / write connection. + * + * @param array $config + * @return array + */ + protected function getWriteConfig(array $config) + { + return $this->mergeReadWriteConfig( + $config, $this->getReadWriteConfig($config, 'write') + ); + } + + /** + * Get a read / write level configuration. + * + * @param array $config + * @param string $type + * @return array + */ + protected function getReadWriteConfig(array $config, $type) + { + return isset($config[$type][0]) + ? Arr::random($config[$type]) + : $config[$type]; + } + + /** + * Merge a configuration for a read / write connection. + * + * @param array $config + * @param array $merge + * @return array + */ + protected function mergeReadWriteConfig(array $config, array $merge) + { + return Arr::except(array_merge($config, $merge), ['read', 'write']); + } + + /** + * Create a new Closure that resolves to a PDO instance. + * + * @param array $config + * @return \Closure + */ + protected function createPdoResolver(array $config) + { + return array_key_exists('host', $config) + ? $this->createPdoResolverWithHosts($config) + : $this->createPdoResolverWithoutHosts($config); + } + + /** + * Create a new Closure that resolves to a PDO instance with a specific host or an array of hosts. + * + * @param array $config + * @return \Closure + * + * @throws \PDOException + */ + protected function createPdoResolverWithHosts(array $config) + { + return function () use ($config) { + foreach (Arr::shuffle($hosts = $this->parseHosts($config)) as $key => $host) { + $config['host'] = $host; + + try { + return $this->createConnector($config)->connect($config); + } catch (PDOException $e) { + continue; + } + } + + throw $e; + }; + } + + /** + * Parse the hosts configuration item into an array. + * + * @param array $config + * @return array + * + * @throws \InvalidArgumentException + */ + protected function parseHosts(array $config) + { + $hosts = Arr::wrap($config['host']); + + if (empty($hosts)) { + throw new InvalidArgumentException('Database hosts array is empty.'); + } + + return $hosts; + } + + /** + * Create a new Closure that resolves to a PDO instance where there is no configured host. + * + * @param array $config + * @return \Closure + */ + protected function createPdoResolverWithoutHosts(array $config) + { + return function () use ($config) { + return $this->createConnector($config)->connect($config); + }; + } + + /** + * Create a connector instance based on the configuration. + * + * @param array $config + * @return \Illuminate\Database\Connectors\ConnectorInterface + * + * @throws \InvalidArgumentException + */ + public function createConnector(array $config) + { + if (! isset($config['driver'])) { + throw new InvalidArgumentException('A driver must be specified.'); + } + + if ($this->container->bound($key = "db.connector.{$config['driver']}")) { + return $this->container->make($key); + } + + switch ($config['driver']) { + case 'mysql': + return new MySqlConnector; + case 'pgsql': + return new PostgresConnector; + case 'sqlite': + return new SQLiteConnector; + case 'sqlsrv': + return new SqlServerConnector; + } + + throw new InvalidArgumentException("Unsupported driver [{$config['driver']}]."); + } + + /** + * Create a new connection instance. + * + * @param string $driver + * @param \PDO|\Closure $connection + * @param string $database + * @param string $prefix + * @param array $config + * @return \Illuminate\Database\Connection + * + * @throws \InvalidArgumentException + */ + protected function createConnection($driver, $connection, $database, $prefix = '', array $config = []) + { + if ($resolver = Connection::getResolver($driver)) { + return $resolver($connection, $database, $prefix, $config); + } + + switch ($driver) { + case 'mysql': + return new MySqlConnection($connection, $database, $prefix, $config); + case 'pgsql': + return new PostgresConnection($connection, $database, $prefix, $config); + case 'sqlite': + return new SQLiteConnection($connection, $database, $prefix, $config); + case 'sqlsrv': + return new SqlServerConnection($connection, $database, $prefix, $config); + } + + throw new InvalidArgumentException("Unsupported driver [{$driver}]."); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php new file mode 100755 index 0000000..0fecfb5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php @@ -0,0 +1,139 @@ + PDO::CASE_NATURAL, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + PDO::ATTR_STRINGIFY_FETCHES => false, + PDO::ATTR_EMULATE_PREPARES => false, + ]; + + /** + * Create a new PDO connection. + * + * @param string $dsn + * @param array $config + * @param array $options + * @return \PDO + * + * @throws \Exception + */ + public function createConnection($dsn, array $config, array $options) + { + [$username, $password] = [ + $config['username'] ?? null, $config['password'] ?? null, + ]; + + try { + return $this->createPdoConnection( + $dsn, $username, $password, $options + ); + } catch (Exception $e) { + return $this->tryAgainIfCausedByLostConnection( + $e, $dsn, $username, $password, $options + ); + } + } + + /** + * Create a new PDO connection instance. + * + * @param string $dsn + * @param string $username + * @param string $password + * @param array $options + * @return \PDO + */ + protected function createPdoConnection($dsn, $username, $password, $options) + { + if (class_exists(PDOConnection::class) && ! $this->isPersistentConnection($options)) { + return new PDOConnection($dsn, $username, $password, $options); + } + + return new PDO($dsn, $username, $password, $options); + } + + /** + * Determine if the connection is persistent. + * + * @param array $options + * @return bool + */ + protected function isPersistentConnection($options) + { + return isset($options[PDO::ATTR_PERSISTENT]) && + $options[PDO::ATTR_PERSISTENT]; + } + + /** + * Handle an exception that occurred during connect execution. + * + * @param \Throwable $e + * @param string $dsn + * @param string $username + * @param string $password + * @param array $options + * @return \PDO + * + * @throws \Exception + */ + protected function tryAgainIfCausedByLostConnection(Throwable $e, $dsn, $username, $password, $options) + { + if ($this->causedByLostConnection($e)) { + return $this->createPdoConnection($dsn, $username, $password, $options); + } + + throw $e; + } + + /** + * Get the PDO options based on the configuration. + * + * @param array $config + * @return array + */ + public function getOptions(array $config) + { + $options = $config['options'] ?? []; + + return array_diff_key($this->options, $options) + $options; + } + + /** + * Get the default PDO connection options. + * + * @return array + */ + public function getDefaultOptions() + { + return $this->options; + } + + /** + * Set the default PDO connection options. + * + * @param array $options + * @return void + */ + public function setDefaultOptions(array $options) + { + $this->options = $options; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectorInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectorInterface.php new file mode 100755 index 0000000..08597ac --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectorInterface.php @@ -0,0 +1,14 @@ +getDsn($config); + + $options = $this->getOptions($config); + + // We need to grab the PDO options that should be used while making the brand + // new connection instance. The PDO options control various aspects of the + // connection's behavior, and some might be specified by the developers. + $connection = $this->createConnection($dsn, $config, $options); + + if (! empty($config['database'])) { + $connection->exec("use `{$config['database']}`;"); + } + + $this->configureIsolationLevel($connection, $config); + + $this->configureEncoding($connection, $config); + + // Next, we will check to see if a timezone has been specified in this config + // and if it has we will issue a statement to modify the timezone with the + // database. Setting this DB timezone is an optional configuration item. + $this->configureTimezone($connection, $config); + + $this->setModes($connection, $config); + + return $connection; + } + + /** + * Set the connection transaction isolation level. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureIsolationLevel($connection, array $config) + { + if (! isset($config['isolation_level'])) { + return; + } + + $connection->prepare( + "SET SESSION TRANSACTION ISOLATION LEVEL {$config['isolation_level']}" + )->execute(); + } + + /** + * Set the connection character set and collation. + * + * @param \PDO $connection + * @param array $config + * @return void|\PDO + */ + protected function configureEncoding($connection, array $config) + { + if (! isset($config['charset'])) { + return $connection; + } + + $connection->prepare( + "set names '{$config['charset']}'".$this->getCollation($config) + )->execute(); + } + + /** + * Get the collation for the configuration. + * + * @param array $config + * @return string + */ + protected function getCollation(array $config) + { + return isset($config['collation']) ? " collate '{$config['collation']}'" : ''; + } + + /** + * Set the timezone on the connection. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureTimezone($connection, array $config) + { + if (isset($config['timezone'])) { + $connection->prepare('set time_zone="'.$config['timezone'].'"')->execute(); + } + } + + /** + * Create a DSN string from a configuration. + * + * Chooses socket or host/port based on the 'unix_socket' config value. + * + * @param array $config + * @return string + */ + protected function getDsn(array $config) + { + return $this->hasSocket($config) + ? $this->getSocketDsn($config) + : $this->getHostDsn($config); + } + + /** + * Determine if the given configuration array has a UNIX socket value. + * + * @param array $config + * @return bool + */ + protected function hasSocket(array $config) + { + return isset($config['unix_socket']) && ! empty($config['unix_socket']); + } + + /** + * Get the DSN string for a socket configuration. + * + * @param array $config + * @return string + */ + protected function getSocketDsn(array $config) + { + return "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}"; + } + + /** + * Get the DSN string for a host / port configuration. + * + * @param array $config + * @return string + */ + protected function getHostDsn(array $config) + { + extract($config, EXTR_SKIP); + + return isset($port) + ? "mysql:host={$host};port={$port};dbname={$database}" + : "mysql:host={$host};dbname={$database}"; + } + + /** + * Set the modes for the connection. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function setModes(PDO $connection, array $config) + { + if (isset($config['modes'])) { + $this->setCustomModes($connection, $config); + } elseif (isset($config['strict'])) { + if ($config['strict']) { + $connection->prepare($this->strictMode($connection, $config))->execute(); + } else { + $connection->prepare("set session sql_mode='NO_ENGINE_SUBSTITUTION'")->execute(); + } + } + } + + /** + * Set the custom modes on the connection. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function setCustomModes(PDO $connection, array $config) + { + $modes = implode(',', $config['modes']); + + $connection->prepare("set session sql_mode='{$modes}'")->execute(); + } + + /** + * Get the query to enable strict mode. + * + * @param \PDO $connection + * @param array $config + * @return string + */ + protected function strictMode(PDO $connection, $config) + { + $version = $config['version'] ?? $connection->getAttribute(PDO::ATTR_SERVER_VERSION); + + if (version_compare($version, '8.0.11') >= 0) { + return "set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"; + } + + return "set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/PostgresConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/PostgresConnector.php new file mode 100755 index 0000000..a507d9a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/PostgresConnector.php @@ -0,0 +1,210 @@ + PDO::CASE_NATURAL, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + PDO::ATTR_STRINGIFY_FETCHES => false, + ]; + + /** + * Establish a database connection. + * + * @param array $config + * @return \PDO + */ + public function connect(array $config) + { + // First we'll create the basic DSN and connection instance connecting to the + // using the configuration option specified by the developer. We will also + // set the default character set on the connections to UTF-8 by default. + $connection = $this->createConnection( + $this->getDsn($config), $config, $this->getOptions($config) + ); + + $this->configureIsolationLevel($connection, $config); + + $this->configureEncoding($connection, $config); + + // Next, we will check to see if a timezone has been specified in this config + // and if it has we will issue a statement to modify the timezone with the + // database. Setting this DB timezone is an optional configuration item. + $this->configureTimezone($connection, $config); + + $this->configureSchema($connection, $config); + + // Postgres allows an application_name to be set by the user and this name is + // used to when monitoring the application with pg_stat_activity. So we'll + // determine if the option has been specified and run a statement if so. + $this->configureApplicationName($connection, $config); + + $this->configureSynchronousCommit($connection, $config); + + return $connection; + } + + /** + * Set the connection transaction isolation level. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureIsolationLevel($connection, array $config) + { + if (isset($config['isolation_level'])) { + $connection->prepare("set session characteristics as transaction isolation level {$config['isolation_level']}")->execute(); + } + } + + /** + * Set the connection character set and collation. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureEncoding($connection, $config) + { + if (! isset($config['charset'])) { + return; + } + + $connection->prepare("set names '{$config['charset']}'")->execute(); + } + + /** + * Set the timezone on the connection. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureTimezone($connection, array $config) + { + if (isset($config['timezone'])) { + $timezone = $config['timezone']; + + $connection->prepare("set time zone '{$timezone}'")->execute(); + } + } + + /** + * Set the schema on the connection. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureSchema($connection, $config) + { + if (isset($config['schema'])) { + $schema = $this->formatSchema($config['schema']); + + $connection->prepare("set search_path to {$schema}")->execute(); + } + } + + /** + * Format the schema for the DSN. + * + * @param array|string $schema + * @return string + */ + protected function formatSchema($schema) + { + if (is_array($schema)) { + return '"'.implode('", "', $schema).'"'; + } + + return '"'.$schema.'"'; + } + + /** + * Set the schema on the connection. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureApplicationName($connection, $config) + { + if (isset($config['application_name'])) { + $applicationName = $config['application_name']; + + $connection->prepare("set application_name to '$applicationName'")->execute(); + } + } + + /** + * Create a DSN string from a configuration. + * + * @param array $config + * @return string + */ + protected function getDsn(array $config) + { + // First we will create the basic DSN setup as well as the port if it is in + // in the configuration options. This will give us the basic DSN we will + // need to establish the PDO connections and return them back for use. + extract($config, EXTR_SKIP); + + $host = isset($host) ? "host={$host};" : ''; + + $dsn = "pgsql:{$host}dbname='{$database}'"; + + // If a port was specified, we will add it to this Postgres DSN connections + // format. Once we have done that we are ready to return this connection + // string back out for usage, as this has been fully constructed here. + if (isset($config['port'])) { + $dsn .= ";port={$port}"; + } + + return $this->addSslOptions($dsn, $config); + } + + /** + * Add the SSL options to the DSN. + * + * @param string $dsn + * @param array $config + * @return string + */ + protected function addSslOptions($dsn, array $config) + { + foreach (['sslmode', 'sslcert', 'sslkey', 'sslrootcert'] as $option) { + if (isset($config[$option])) { + $dsn .= ";{$option}={$config[$option]}"; + } + } + + return $dsn; + } + + /** + * Configure the synchronous_commit setting. + * + * @param \PDO $connection + * @param array $config + * @return void + */ + protected function configureSynchronousCommit($connection, array $config) + { + if (! isset($config['synchronous_commit'])) { + return; + } + + $connection->prepare("set synchronous_commit to '{$config['synchronous_commit']}'")->execute(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/SQLiteConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/SQLiteConnector.php new file mode 100755 index 0000000..90dc16b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/SQLiteConnector.php @@ -0,0 +1,39 @@ +getOptions($config); + + // SQLite supports "in-memory" databases that only last as long as the owning + // connection does. These are useful for tests or for short lifetime store + // querying. In-memory databases may only have a single open connection. + if ($config['database'] === ':memory:') { + return $this->createConnection('sqlite::memory:', $config, $options); + } + + $path = realpath($config['database']); + + // Here we'll verify that the SQLite database exists before going any further + // as the developer probably wants to know if the database exists and this + // SQLite driver will not throw any exception if it does not by default. + if ($path === false) { + throw new InvalidArgumentException("Database ({$config['database']}) does not exist."); + } + + return $this->createConnection("sqlite:{$path}", $config, $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/SqlServerConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/SqlServerConnector.php new file mode 100755 index 0000000..caefa68 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Connectors/SqlServerConnector.php @@ -0,0 +1,205 @@ + PDO::CASE_NATURAL, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + PDO::ATTR_STRINGIFY_FETCHES => false, + ]; + + /** + * Establish a database connection. + * + * @param array $config + * @return \PDO + */ + public function connect(array $config) + { + $options = $this->getOptions($config); + + return $this->createConnection($this->getDsn($config), $config, $options); + } + + /** + * Create a DSN string from a configuration. + * + * @param array $config + * @return string + */ + protected function getDsn(array $config) + { + // First we will create the basic DSN setup as well as the port if it is in + // in the configuration options. This will give us the basic DSN we will + // need to establish the PDO connections and return them back for use. + if ($this->prefersOdbc($config)) { + return $this->getOdbcDsn($config); + } + + if (in_array('sqlsrv', $this->getAvailableDrivers())) { + return $this->getSqlSrvDsn($config); + } else { + return $this->getDblibDsn($config); + } + } + + /** + * Determine if the database configuration prefers ODBC. + * + * @param array $config + * @return bool + */ + protected function prefersOdbc(array $config) + { + return in_array('odbc', $this->getAvailableDrivers()) && + ($config['odbc'] ?? null) === true; + } + + /** + * Get the DSN string for a DbLib connection. + * + * @param array $config + * @return string + */ + protected function getDblibDsn(array $config) + { + return $this->buildConnectString('dblib', array_merge([ + 'host' => $this->buildHostString($config, ':'), + 'dbname' => $config['database'], + ], Arr::only($config, ['appname', 'charset', 'version']))); + } + + /** + * Get the DSN string for an ODBC connection. + * + * @param array $config + * @return string + */ + protected function getOdbcDsn(array $config) + { + return isset($config['odbc_datasource_name']) + ? 'odbc:'.$config['odbc_datasource_name'] : ''; + } + + /** + * Get the DSN string for a SqlSrv connection. + * + * @param array $config + * @return string + */ + protected function getSqlSrvDsn(array $config) + { + $arguments = [ + 'Server' => $this->buildHostString($config, ','), + ]; + + if (isset($config['database'])) { + $arguments['Database'] = $config['database']; + } + + if (isset($config['readonly'])) { + $arguments['ApplicationIntent'] = 'ReadOnly'; + } + + if (isset($config['pooling']) && $config['pooling'] === false) { + $arguments['ConnectionPooling'] = '0'; + } + + if (isset($config['appname'])) { + $arguments['APP'] = $config['appname']; + } + + if (isset($config['encrypt'])) { + $arguments['Encrypt'] = $config['encrypt']; + } + + if (isset($config['trust_server_certificate'])) { + $arguments['TrustServerCertificate'] = $config['trust_server_certificate']; + } + + if (isset($config['multiple_active_result_sets']) && $config['multiple_active_result_sets'] === false) { + $arguments['MultipleActiveResultSets'] = 'false'; + } + + if (isset($config['transaction_isolation'])) { + $arguments['TransactionIsolation'] = $config['transaction_isolation']; + } + + if (isset($config['multi_subnet_failover'])) { + $arguments['MultiSubnetFailover'] = $config['multi_subnet_failover']; + } + + if (isset($config['column_encryption'])) { + $arguments['ColumnEncryption'] = $config['column_encryption']; + } + + if (isset($config['key_store_authentication'])) { + $arguments['KeyStoreAuthentication'] = $config['key_store_authentication']; + } + + if (isset($config['key_store_principal_id'])) { + $arguments['KeyStorePrincipalId'] = $config['key_store_principal_id']; + } + + if (isset($config['key_store_secret'])) { + $arguments['KeyStoreSecret'] = $config['key_store_secret']; + } + + if (isset($config['login_timeout'])) { + $arguments['LoginTimeout'] = $config['login_timeout']; + } + + return $this->buildConnectString('sqlsrv', $arguments); + } + + /** + * Build a connection string from the given arguments. + * + * @param string $driver + * @param array $arguments + * @return string + */ + protected function buildConnectString($driver, array $arguments) + { + return $driver.':'.implode(';', array_map(function ($key) use ($arguments) { + return sprintf('%s=%s', $key, $arguments[$key]); + }, array_keys($arguments))); + } + + /** + * Build a host string from the given configuration. + * + * @param array $config + * @param string $separator + * @return string + */ + protected function buildHostString(array $config, $separator) + { + if (empty($config['port'])) { + return $config['host']; + } + + return $config['host'].$separator.$config['port']; + } + + /** + * Get the available PDO drivers. + * + * @return array + */ + protected function getAvailableDrivers() + { + return PDO::getAvailableDrivers(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/DbCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/DbCommand.php new file mode 100644 index 0000000..c2c4593 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/DbCommand.php @@ -0,0 +1,219 @@ +getConnection(); + + (new Process( + array_merge([$this->getCommand($connection)], $this->commandArguments($connection)), + null, + $this->commandEnvironment($connection) + ))->setTimeout(null)->setTty(true)->mustRun(function ($type, $buffer) { + $this->output->write($buffer); + }); + + return 0; + } + + /** + * Get the database connection configuration. + * + * @return array + * + * @throws \UnexpectedValueException + */ + public function getConnection() + { + $connection = $this->laravel['config']['database.connections.'. + (($db = $this->argument('connection')) ?? $this->laravel['config']['database.default']) + ]; + + if (empty($connection)) { + throw new UnexpectedValueException("Invalid database connection [{$db}]."); + } + + if (! empty($connection['url'])) { + $connection = (new ConfigurationUrlParser)->parseConfiguration($connection); + } + + if ($this->option('read')) { + if (is_array($connection['read']['host'])) { + $connection['read']['host'] = $connection['read']['host'][0]; + } + + $connection = array_merge($connection, $connection['read']); + } elseif ($this->option('write')) { + if (is_array($connection['write']['host'])) { + $connection['write']['host'] = $connection['write']['host'][0]; + } + + $connection = array_merge($connection, $connection['write']); + } + + return $connection; + } + + /** + * Get the arguments for the database client command. + * + * @param array $connection + * @return array + */ + public function commandArguments(array $connection) + { + $driver = ucfirst($connection['driver']); + + return $this->{"get{$driver}Arguments"}($connection); + } + + /** + * Get the environment variables for the database client command. + * + * @param array $connection + * @return array|null + */ + public function commandEnvironment(array $connection) + { + $driver = ucfirst($connection['driver']); + + if (method_exists($this, "get{$driver}Environment")) { + return $this->{"get{$driver}Environment"}($connection); + } + + return null; + } + + /** + * Get the database client command to run. + * + * @param array $connection + * @return string + */ + public function getCommand(array $connection) + { + return [ + 'mysql' => 'mysql', + 'pgsql' => 'psql', + 'sqlite' => 'sqlite3', + 'sqlsrv' => 'sqlcmd', + ][$connection['driver']]; + } + + /** + * Get the arguments for the MySQL CLI. + * + * @param array $connection + * @return array + */ + protected function getMysqlArguments(array $connection) + { + return array_merge([ + '--host='.$connection['host'], + '--port='.$connection['port'], + '--user='.$connection['username'], + ], $this->getOptionalArguments([ + 'password' => '--password='.$connection['password'], + 'unix_socket' => '--socket='.($connection['unix_socket'] ?? ''), + 'charset' => '--default-character-set='.($connection['charset'] ?? ''), + ], $connection), [$connection['database']]); + } + + /** + * Get the arguments for the Postgres CLI. + * + * @param array $connection + * @return array + */ + protected function getPgsqlArguments(array $connection) + { + return [$connection['database']]; + } + + /** + * Get the arguments for the SQLite CLI. + * + * @param array $connection + * @return array + */ + protected function getSqliteArguments(array $connection) + { + return [$connection['database']]; + } + + /** + * Get the arguments for the SQL Server CLI. + * + * @param array $connection + * @return array + */ + protected function getSqlsrvArguments(array $connection) + { + return array_merge(...$this->getOptionalArguments([ + 'database' => ['-d', $connection['database']], + 'username' => ['-U', $connection['username']], + 'password' => ['-P', $connection['password']], + 'host' => ['-S', 'tcp:'.$connection['host'] + .($connection['port'] ? ','.$connection['port'] : ''), ], + ], $connection)); + } + + /** + * Get the environment variables for the Postgres CLI. + * + * @param array $connection + * @return array|null + */ + protected function getPgsqlEnvironment(array $connection) + { + return array_merge(...$this->getOptionalArguments([ + 'username' => ['PGUSER' => $connection['username']], + 'host' => ['PGHOST' => $connection['host']], + 'port' => ['PGPORT' => $connection['port']], + 'password' => ['PGPASSWORD' => $connection['password']], + ], $connection)); + } + + /** + * Get the optional arguments based on the connection configuration. + * + * @param array $args + * @param array $connection + * @return array + */ + protected function getOptionalArguments(array $args, array $connection) + { + return array_values(array_filter($args, function ($key) use ($connection) { + return ! empty($connection[$key]); + }, ARRAY_FILTER_USE_KEY)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/DumpCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/DumpCommand.php new file mode 100644 index 0000000..fe73fb2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/DumpCommand.php @@ -0,0 +1,86 @@ +connection($database = $this->input->getOption('database')); + + $this->schemaState($connection)->dump( + $connection, $path = $this->path($connection) + ); + + $dispatcher->dispatch(new SchemaDumped($connection, $path)); + + $this->info('Database schema dumped successfully.'); + + if ($this->option('prune')) { + (new Filesystem)->deleteDirectory( + database_path('migrations'), $preserve = false + ); + + $this->info('Migrations pruned successfully.'); + } + } + + /** + * Create a schema state instance for the given connection. + * + * @param \Illuminate\Database\Connection $connection + * @return mixed + */ + protected function schemaState(Connection $connection) + { + return $connection->getSchemaState() + ->withMigrationTable($connection->getTablePrefix().Config::get('database.migrations', 'migrations')) + ->handleOutputUsing(function ($type, $buffer) { + $this->output->write($buffer); + }); + } + + /** + * Get the path that the dump should be written to. + * + * @param \Illuminate\Database\Connection $connection + */ + protected function path(Connection $connection) + { + return tap($this->option('path') ?: database_path('schema/'.$connection->getName().'-schema.dump'), function ($path) { + (new Filesystem)->ensureDirectoryExists(dirname($path)); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php new file mode 100644 index 0000000..6233fe2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php @@ -0,0 +1,143 @@ +resolveStubPath('/stubs/factory.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Build the class with the given name. + * + * @param string $name + * @return string + */ + protected function buildClass($name) + { + $factory = class_basename(Str::ucfirst(str_replace('Factory', '', $name))); + + $namespaceModel = $this->option('model') + ? $this->qualifyModel($this->option('model')) + : $this->qualifyModel($this->guessModelName($name)); + + $model = class_basename($namespaceModel); + + if (Str::startsWith($namespaceModel, $this->rootNamespace().'Models')) { + $namespace = Str::beforeLast('Database\\Factories\\'.Str::after($namespaceModel, $this->rootNamespace().'Models\\'), '\\'); + } else { + $namespace = 'Database\\Factories'; + } + + $replace = [ + '{{ factoryNamespace }}' => $namespace, + 'NamespacedDummyModel' => $namespaceModel, + '{{ namespacedModel }}' => $namespaceModel, + '{{namespacedModel}}' => $namespaceModel, + 'DummyModel' => $model, + '{{ model }}' => $model, + '{{model}}' => $model, + '{{ factory }}' => $factory, + '{{factory}}' => $factory, + ]; + + return str_replace( + array_keys($replace), array_values($replace), parent::buildClass($name) + ); + } + + /** + * Get the destination class path. + * + * @param string $name + * @return string + */ + protected function getPath($name) + { + $name = (string) Str::of($name)->replaceFirst($this->rootNamespace(), '')->finish('Factory'); + + return $this->laravel->databasePath().'/factories/'.str_replace('\\', '/', $name).'.php'; + } + + /** + * Guess the model name from the Factory name or return a default model name. + * + * @param string $name + * @return string + */ + protected function guessModelName($name) + { + if (Str::endsWith($name, 'Factory')) { + $name = substr($name, 0, -7); + } + + $modelName = $this->qualifyModel(Str::after($name, $this->rootNamespace())); + + if (class_exists($modelName)) { + return $modelName; + } + + if (is_dir(app_path('Models/'))) { + return $this->rootNamespace().'Models\Model'; + } + + return $this->rootNamespace().'Model'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['model', 'm', InputOption::VALUE_OPTIONAL, 'The name of the model'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Factories/stubs/factory.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Factories/stubs/factory.stub new file mode 100644 index 0000000..3e00f36 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Factories/stubs/factory.stub @@ -0,0 +1,20 @@ +input->hasOption('path') && $this->option('path')) { + return collect($this->option('path'))->map(function ($path) { + return ! $this->usingRealPath() + ? $this->laravel->basePath().'/'.$path + : $path; + })->all(); + } + + return array_merge( + $this->migrator->paths(), [$this->getMigrationPath()] + ); + } + + /** + * Determine if the given path(s) are pre-resolved "real" paths. + * + * @return bool + */ + protected function usingRealPath() + { + return $this->input->hasOption('realpath') && $this->option('realpath'); + } + + /** + * Get the path to the migration directory. + * + * @return string + */ + protected function getMigrationPath() + { + return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/FreshCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/FreshCommand.php new file mode 100644 index 0000000..7bfba0d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/FreshCommand.php @@ -0,0 +1,116 @@ +confirmToProceed()) { + return 1; + } + + $database = $this->input->getOption('database'); + + $this->call('db:wipe', array_filter([ + '--database' => $database, + '--drop-views' => $this->option('drop-views'), + '--drop-types' => $this->option('drop-types'), + '--force' => true, + ])); + + $this->call('migrate', array_filter([ + '--database' => $database, + '--path' => $this->input->getOption('path'), + '--realpath' => $this->input->getOption('realpath'), + '--schema-path' => $this->input->getOption('schema-path'), + '--force' => true, + '--step' => $this->option('step'), + ])); + + if ($this->laravel->bound(Dispatcher::class)) { + $this->laravel[Dispatcher::class]->dispatch( + new DatabaseRefreshed + ); + } + + if ($this->needsSeeding()) { + $this->runSeeder($database); + } + + return 0; + } + + /** + * Determine if the developer has requested database seeding. + * + * @return bool + */ + protected function needsSeeding() + { + return $this->option('seed') || $this->option('seeder'); + } + + /** + * Run the database seeder command. + * + * @param string $database + * @return void + */ + protected function runSeeder($database) + { + $this->call('db:seed', array_filter([ + '--database' => $database, + '--class' => $this->option('seeder') ?: 'Database\\Seeders\\DatabaseSeeder', + '--force' => true, + ])); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + ['drop-views', null, InputOption::VALUE_NONE, 'Drop all tables and views'], + ['drop-types', null, InputOption::VALUE_NONE, 'Drop all tables and types (Postgres only)'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + ['path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The path(s) to the migrations files to be executed'], + ['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'], + ['schema-path', null, InputOption::VALUE_OPTIONAL, 'The path to a schema dump file'], + ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run'], + ['seeder', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder'], + ['step', null, InputOption::VALUE_NONE, 'Force the migrations to be run so they can be rolled back individually'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/InstallCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/InstallCommand.php new file mode 100755 index 0000000..d69c2ab --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/InstallCommand.php @@ -0,0 +1,70 @@ +repository = $repository; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->repository->setSource($this->input->getOption('database')); + + $this->repository->createRepository(); + + $this->info('Migration table created successfully.'); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php new file mode 100755 index 0000000..ea379e3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php @@ -0,0 +1,181 @@ +migrator = $migrator; + $this->dispatcher = $dispatcher; + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + if (! $this->confirmToProceed()) { + return 1; + } + + $this->migrator->usingConnection($this->option('database'), function () { + $this->prepareDatabase(); + + // Next, we will check to see if a path option has been defined. If it has + // we will use the path relative to the root of this installation folder + // so that migrations may be run for any path within the applications. + $this->migrator->setOutput($this->output) + ->run($this->getMigrationPaths(), [ + 'pretend' => $this->option('pretend'), + 'step' => $this->option('step'), + ]); + + // Finally, if the "seed" option has been given, we will re-run the database + // seed task to re-populate the database, which is convenient when adding + // a migration and a seed at the same time, as it is only this command. + if ($this->option('seed') && ! $this->option('pretend')) { + $this->call('db:seed', [ + '--class' => $this->option('seeder') ?: 'Database\\Seeders\\DatabaseSeeder', + '--force' => true, + ]); + } + }); + + return 0; + } + + /** + * Prepare the migration database for running. + * + * @return void + */ + protected function prepareDatabase() + { + if (! $this->migrator->repositoryExists()) { + $this->call('migrate:install', array_filter([ + '--database' => $this->option('database'), + ])); + } + + if (! $this->migrator->hasRunAnyMigrations() && ! $this->option('pretend')) { + $this->loadSchemaState(); + } + } + + /** + * Load the schema state to seed the initial database schema structure. + * + * @return void + */ + protected function loadSchemaState() + { + $connection = $this->migrator->resolveConnection($this->option('database')); + + // First, we will make sure that the connection supports schema loading and that + // the schema file exists before we proceed any further. If not, we will just + // continue with the standard migration operation as normal without errors. + if ($connection instanceof SqlServerConnection || + ! is_file($path = $this->schemaPath($connection))) { + return; + } + + $this->line('Loading stored database schema: '.$path); + + $startTime = microtime(true); + + // Since the schema file will create the "migrations" table and reload it to its + // proper state, we need to delete it here so we don't get an error that this + // table already exists when the stored database schema file gets executed. + $this->migrator->deleteRepository(); + + $connection->getSchemaState()->handleOutputUsing(function ($type, $buffer) { + $this->output->write($buffer); + })->load($path); + + $runTime = number_format((microtime(true) - $startTime) * 1000, 2); + + // Finally, we will fire an event that this schema has been loaded so developers + // can perform any post schema load tasks that are necessary in listeners for + // this event, which may seed the database tables with some necessary data. + $this->dispatcher->dispatch( + new SchemaLoaded($connection, $path) + ); + + $this->line('Loaded stored database schema. ('.$runTime.'ms)'); + } + + /** + * Get the path to the stored schema for the given connection. + * + * @param \Illuminate\Database\Connection $connection + * @return string + */ + protected function schemaPath($connection) + { + if ($this->option('schema-path')) { + return $this->option('schema-path'); + } + + if (file_exists($path = database_path('schema/'.$connection->getName().'-schema.dump'))) { + return $path; + } + + return database_path('schema/'.$connection->getName().'-schema.sql'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php new file mode 100644 index 0000000..95c3a20 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php @@ -0,0 +1,135 @@ +creator = $creator; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + // It's possible for the developer to specify the tables to modify in this + // schema operation. The developer may also specify if this table needs + // to be freshly created so we can create the appropriate migrations. + $name = Str::snake(trim($this->input->getArgument('name'))); + + $table = $this->input->getOption('table'); + + $create = $this->input->getOption('create') ?: false; + + // If no table was given as an option but a create option is given then we + // will use the "create" option as the table name. This allows the devs + // to pass a table name into this option as a short-cut for creating. + if (! $table && is_string($create)) { + $table = $create; + + $create = true; + } + + // Next, we will attempt to guess the table name if this the migration has + // "create" in the name. This will allow us to provide a convenient way + // of creating migrations that create new tables for the application. + if (! $table) { + [$table, $create] = TableGuesser::guess($name); + } + + // Now we are ready to write the migration out to disk. Once we've written + // the migration out, we will dump-autoload for the entire framework to + // make sure that the migrations are registered by the class loaders. + $this->writeMigration($name, $table, $create); + + $this->composer->dumpAutoloads(); + } + + /** + * Write the migration file to disk. + * + * @param string $name + * @param string $table + * @param bool $create + * @return string + */ + protected function writeMigration($name, $table, $create) + { + $file = $this->creator->create( + $name, $this->getMigrationPath(), $table, $create + ); + + if (! $this->option('fullpath')) { + $file = pathinfo($file, PATHINFO_FILENAME); + } + + $this->line("Created Migration: {$file}"); + } + + /** + * Get migration path (either specified by '--path' option or default location). + * + * @return string + */ + protected function getMigrationPath() + { + if (! is_null($targetPath = $this->input->getOption('path'))) { + return ! $this->usingRealPath() + ? $this->laravel->basePath().'/'.$targetPath + : $targetPath; + } + + return parent::getMigrationPath(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RefreshCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RefreshCommand.php new file mode 100755 index 0000000..2073cd9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RefreshCommand.php @@ -0,0 +1,159 @@ +confirmToProceed()) { + return 1; + } + + // Next we'll gather some of the options so that we can have the right options + // to pass to the commands. This includes options such as which database to + // use and the path to use for the migration. Then we'll run the command. + $database = $this->input->getOption('database'); + + $path = $this->input->getOption('path'); + + // If the "step" option is specified it means we only want to rollback a small + // number of migrations before migrating again. For example, the user might + // only rollback and remigrate the latest four migrations instead of all. + $step = $this->input->getOption('step') ?: 0; + + if ($step > 0) { + $this->runRollback($database, $path, $step); + } else { + $this->runReset($database, $path); + } + + // The refresh command is essentially just a brief aggregate of a few other of + // the migration commands and just provides a convenient wrapper to execute + // them in succession. We'll also see if we need to re-seed the database. + $this->call('migrate', array_filter([ + '--database' => $database, + '--path' => $path, + '--realpath' => $this->input->getOption('realpath'), + '--force' => true, + ])); + + if ($this->laravel->bound(Dispatcher::class)) { + $this->laravel[Dispatcher::class]->dispatch( + new DatabaseRefreshed + ); + } + + if ($this->needsSeeding()) { + $this->runSeeder($database); + } + + return 0; + } + + /** + * Run the rollback command. + * + * @param string $database + * @param string $path + * @param int $step + * @return void + */ + protected function runRollback($database, $path, $step) + { + $this->call('migrate:rollback', array_filter([ + '--database' => $database, + '--path' => $path, + '--realpath' => $this->input->getOption('realpath'), + '--step' => $step, + '--force' => true, + ])); + } + + /** + * Run the reset command. + * + * @param string $database + * @param string $path + * @return void + */ + protected function runReset($database, $path) + { + $this->call('migrate:reset', array_filter([ + '--database' => $database, + '--path' => $path, + '--realpath' => $this->input->getOption('realpath'), + '--force' => true, + ])); + } + + /** + * Determine if the developer has requested database seeding. + * + * @return bool + */ + protected function needsSeeding() + { + return $this->option('seed') || $this->option('seeder'); + } + + /** + * Run the database seeder command. + * + * @param string $database + * @return void + */ + protected function runSeeder($database) + { + $this->call('db:seed', array_filter([ + '--database' => $database, + '--class' => $this->option('seeder') ?: 'Database\\Seeders\\DatabaseSeeder', + '--force' => true, + ])); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + ['path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The path(s) to the migrations files to be executed'], + ['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'], + ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run'], + ['seeder', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder'], + ['step', null, InputOption::VALUE_OPTIONAL, 'The number of migrations to be reverted & re-run'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/ResetCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/ResetCommand.php new file mode 100755 index 0000000..1f2babb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/ResetCommand.php @@ -0,0 +1,91 @@ +migrator = $migrator; + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + if (! $this->confirmToProceed()) { + return 1; + } + + return $this->migrator->usingConnection($this->option('database'), function () { + // First, we'll make sure that the migration table actually exists before we + // start trying to rollback and re-run all of the migrations. If it's not + // present we'll just bail out with an info message for the developers. + if (! $this->migrator->repositoryExists()) { + return $this->comment('Migration table not found.'); + } + + $this->migrator->setOutput($this->output)->reset( + $this->getMigrationPaths(), $this->option('pretend') + ); + }); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + + ['path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The path(s) to the migrations files to be executed'], + + ['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'], + + ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RollbackCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RollbackCommand.php new file mode 100755 index 0000000..c851360 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RollbackCommand.php @@ -0,0 +1,91 @@ +migrator = $migrator; + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + if (! $this->confirmToProceed()) { + return 1; + } + + $this->migrator->usingConnection($this->option('database'), function () { + $this->migrator->setOutput($this->output)->rollback( + $this->getMigrationPaths(), [ + 'pretend' => $this->option('pretend'), + 'step' => (int) $this->option('step'), + ] + ); + }); + + return 0; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + + ['path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The path(s) to the migrations files to be executed'], + + ['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'], + + ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run'], + + ['step', null, InputOption::VALUE_OPTIONAL, 'The number of migrations to be reverted'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/StatusCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/StatusCommand.php new file mode 100644 index 0000000..2cf82f9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/StatusCommand.php @@ -0,0 +1,115 @@ +migrator = $migrator; + } + + /** + * Execute the console command. + * + * @return int|null + */ + public function handle() + { + return $this->migrator->usingConnection($this->option('database'), function () { + if (! $this->migrator->repositoryExists()) { + $this->error('Migration table not found.'); + + return 1; + } + + $ran = $this->migrator->getRepository()->getRan(); + + $batches = $this->migrator->getRepository()->getMigrationBatches(); + + if (count($migrations = $this->getStatusFor($ran, $batches)) > 0) { + $this->table(['Ran?', 'Migration', 'Batch'], $migrations); + } else { + $this->error('No migrations found'); + } + }); + } + + /** + * Get the status for the given ran migrations. + * + * @param array $ran + * @param array $batches + * @return \Illuminate\Support\Collection + */ + protected function getStatusFor(array $ran, array $batches) + { + return Collection::make($this->getAllMigrationFiles()) + ->map(function ($migration) use ($ran, $batches) { + $migrationName = $this->migrator->getMigrationName($migration); + + return in_array($migrationName, $ran) + ? ['Yes', $migrationName, $batches[$migrationName]] + : ['No', $migrationName]; + }); + } + + /** + * Get an array of all of the migration files. + * + * @return array + */ + protected function getAllMigrationFiles() + { + return $this->migrator->getMigrationFiles($this->getMigrationPaths()); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + + ['path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The path(s) to the migrations files to use'], + + ['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/TableGuesser.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/TableGuesser.php new file mode 100644 index 0000000..82dfbdd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/TableGuesser.php @@ -0,0 +1,37 @@ +models(); + + if ($models->isEmpty()) { + $this->info('No prunable models found.'); + + return; + } + + if ($this->option('pretend')) { + $models->each(function ($model) { + $this->pretendToPrune($model); + }); + + return; + } + + $events->listen(ModelsPruned::class, function ($event) { + $this->info("{$event->count} [{$event->model}] records have been pruned."); + }); + + $models->each(function ($model) { + $instance = new $model; + + $chunkSize = property_exists($instance, 'prunableChunkSize') + ? $instance->prunableChunkSize + : $this->option('chunk'); + + $total = $this->isPrunable($model) + ? $instance->pruneAll($chunkSize) + : 0; + + if ($total == 0) { + $this->info("No prunable [$model] records found."); + } + }); + + $events->forget(ModelsPruned::class); + } + + /** + * Determine the models that should be pruned. + * + * @return \Illuminate\Support\Collection + */ + protected function models() + { + if (! empty($models = $this->option('model'))) { + return collect($models)->filter(function ($model) { + return class_exists($model); + })->values(); + } + + $except = $this->option('except'); + + if (! empty($models) && ! empty($except)) { + throw new InvalidArgumentException('The --models and --except options cannot be combined.'); + } + + return collect((new Finder)->in($this->getDefaultPath())->files()->name('*.php')) + ->map(function ($model) { + $namespace = $this->laravel->getNamespace(); + + return $namespace.str_replace( + ['/', '.php'], + ['\\', ''], + Str::after($model->getRealPath(), realpath(app_path()).DIRECTORY_SEPARATOR) + ); + })->when(! empty($except), function ($models) use ($except) { + return $models->reject(function ($model) use ($except) { + return in_array($model, $except); + }); + })->filter(function ($model) { + return $this->isPrunable($model); + })->filter(function ($model) { + return class_exists($model); + })->values(); + } + + /** + * Get the default path where models are located. + * + * @return string + */ + protected function getDefaultPath() + { + return app_path('Models'); + } + + /** + * Determine if the given model class is prunable. + * + * @param string $model + * @return bool + */ + protected function isPrunable($model) + { + $uses = class_uses_recursive($model); + + return in_array(Prunable::class, $uses) || in_array(MassPrunable::class, $uses); + } + + /** + * Display how many models will be pruned. + * + * @param string $model + * @return void + */ + protected function pretendToPrune($model) + { + $instance = new $model; + + $count = $instance->prunable() + ->when(in_array(SoftDeletes::class, class_uses_recursive(get_class($instance))), function ($query) { + $query->withTrashed(); + })->count(); + + if ($count === 0) { + $this->info("No prunable [$model] records found."); + } else { + $this->info("{$count} [{$model}] records will be pruned."); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php new file mode 100644 index 0000000..058e545 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php @@ -0,0 +1,138 @@ +resolver = $resolver; + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + if (! $this->confirmToProceed()) { + return 1; + } + + $previousConnection = $this->resolver->getDefaultConnection(); + + $this->resolver->setDefaultConnection($this->getDatabase()); + + Model::unguarded(function () { + $this->getSeeder()->__invoke(); + }); + + if ($previousConnection) { + $this->resolver->setDefaultConnection($previousConnection); + } + + $this->info('Database seeding completed successfully.'); + + return 0; + } + + /** + * Get a seeder instance from the container. + * + * @return \Illuminate\Database\Seeder + */ + protected function getSeeder() + { + $class = $this->input->getArgument('class') ?? $this->input->getOption('class'); + + if (strpos($class, '\\') === false) { + $class = 'Database\\Seeders\\'.$class; + } + + if ($class === 'Database\\Seeders\\DatabaseSeeder' && + ! class_exists($class)) { + $class = 'DatabaseSeeder'; + } + + return $this->laravel->make($class) + ->setContainer($this->laravel) + ->setCommand($this); + } + + /** + * Get the name of the database connection to use. + * + * @return string + */ + protected function getDatabase() + { + $database = $this->input->getOption('database'); + + return $database ?: $this->laravel['config']['database.default']; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['class', InputArgument::OPTIONAL, 'The class name of the root seeder', null], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder', 'Database\\Seeders\\DatabaseSeeder'], + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php new file mode 100644 index 0000000..aef7a77 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php @@ -0,0 +1,88 @@ +resolveStubPath('/stubs/seeder.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return is_file($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the destination class path. + * + * @param string $name + * @return string + */ + protected function getPath($name) + { + if (is_dir($this->laravel->databasePath().'/seeds')) { + return $this->laravel->databasePath().'/seeds/'.$name.'.php'; + } else { + return $this->laravel->databasePath().'/seeders/'.$name.'.php'; + } + } + + /** + * Parse the class name and format according to the root namespace. + * + * @param string $name + * @return string + */ + protected function qualifyClass($name) + { + return $name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/stubs/seeder.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/stubs/seeder.stub new file mode 100644 index 0000000..5662969 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/stubs/seeder.stub @@ -0,0 +1,18 @@ +confirmToProceed()) { + return 1; + } + + $database = $this->input->getOption('database'); + + if ($this->option('drop-views')) { + $this->dropAllViews($database); + + $this->info('Dropped all views successfully.'); + } + + $this->dropAllTables($database); + + $this->info('Dropped all tables successfully.'); + + if ($this->option('drop-types')) { + $this->dropAllTypes($database); + + $this->info('Dropped all types successfully.'); + } + + return 0; + } + + /** + * Drop all of the database tables. + * + * @param string $database + * @return void + */ + protected function dropAllTables($database) + { + $this->laravel['db']->connection($database) + ->getSchemaBuilder() + ->dropAllTables(); + } + + /** + * Drop all of the database views. + * + * @param string $database + * @return void + */ + protected function dropAllViews($database) + { + $this->laravel['db']->connection($database) + ->getSchemaBuilder() + ->dropAllViews(); + } + + /** + * Drop all of the database types. + * + * @param string $database + * @return void + */ + protected function dropAllTypes($database) + { + $this->laravel['db']->connection($database) + ->getSchemaBuilder() + ->dropAllTypes(); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'], + ['drop-views', null, InputOption::VALUE_NONE, 'Drop all tables and views'], + ['drop-types', null, InputOption::VALUE_NONE, 'Drop all tables and types (Postgres only)'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DBAL/TimestampType.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DBAL/TimestampType.php new file mode 100644 index 0000000..1557f12 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DBAL/TimestampType.php @@ -0,0 +1,110 @@ +getName(); + + switch ($name) { + case 'mysql': + case 'mysql2': + return $this->getMySqlPlatformSQLDeclaration($fieldDeclaration); + + case 'postgresql': + case 'pgsql': + case 'postgres': + return $this->getPostgresPlatformSQLDeclaration($fieldDeclaration); + + case 'mssql': + return $this->getSqlServerPlatformSQLDeclaration($fieldDeclaration); + + case 'sqlite': + case 'sqlite3': + return $this->getSQLitePlatformSQLDeclaration($fieldDeclaration); + + default: + throw new RuntimeException('Invalid platform: '.$name); + } + } + + /** + * Get the SQL declaration for MySQL. + * + * @param array $fieldDeclaration + * @return string + */ + protected function getMySqlPlatformSQLDeclaration(array $fieldDeclaration) + { + $columnType = 'TIMESTAMP'; + + if ($fieldDeclaration['precision']) { + $columnType = 'TIMESTAMP('.$fieldDeclaration['precision'].')'; + } + + $notNull = $fieldDeclaration['notnull'] ?? false; + + if (! $notNull) { + return $columnType.' NULL'; + } + + return $columnType; + } + + /** + * Get the SQL declaration for PostgreSQL. + * + * @param array $fieldDeclaration + * @return string + */ + protected function getPostgresPlatformSQLDeclaration(array $fieldDeclaration) + { + return 'TIMESTAMP('.(int) $fieldDeclaration['precision'].')'; + } + + /** + * Get the SQL declaration for SQL Server. + * + * @param array $fieldDeclaration + * @return string + */ + protected function getSqlServerPlatformSQLDeclaration(array $fieldDeclaration) + { + return $fieldDeclaration['precision'] ?? false + ? 'DATETIME2('.$fieldDeclaration['precision'].')' + : 'DATETIME'; + } + + /** + * Get the SQL declaration for SQLite. + * + * @param array $fieldDeclaration + * @return string + */ + protected function getSQLitePlatformSQLDeclaration(array $fieldDeclaration) + { + return 'DATETIME'; + } + + /** + * {@inheritdoc} + * + * @return string + */ + public function getName() + { + return 'timestamp'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php new file mode 100755 index 0000000..cb823bf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php @@ -0,0 +1,444 @@ +app = $app; + $this->factory = $factory; + + $this->reconnector = function ($connection) { + $this->reconnect($connection->getNameWithReadWriteType()); + }; + } + + /** + * Get a database connection instance. + * + * @param string|null $name + * @return \Illuminate\Database\Connection + */ + public function connection($name = null) + { + [$database, $type] = $this->parseConnectionName($name); + + $name = $name ?: $database; + + // If we haven't created this connection, we'll create it based on the config + // provided in the application. Once we've created the connections we will + // set the "fetch mode" for PDO which determines the query return types. + if (! isset($this->connections[$name])) { + $this->connections[$name] = $this->configure( + $this->makeConnection($database), $type + ); + } + + return $this->connections[$name]; + } + + /** + * Parse the connection into an array of the name and read / write type. + * + * @param string $name + * @return array + */ + protected function parseConnectionName($name) + { + $name = $name ?: $this->getDefaultConnection(); + + return Str::endsWith($name, ['::read', '::write']) + ? explode('::', $name, 2) : [$name, null]; + } + + /** + * Make the database connection instance. + * + * @param string $name + * @return \Illuminate\Database\Connection + */ + protected function makeConnection($name) + { + $config = $this->configuration($name); + + // First we will check by the connection name to see if an extension has been + // registered specifically for that connection. If it has we will call the + // Closure and pass it the config allowing it to resolve the connection. + if (isset($this->extensions[$name])) { + return call_user_func($this->extensions[$name], $config, $name); + } + + // Next we will check to see if an extension has been registered for a driver + // and will call the Closure if so, which allows us to have a more generic + // resolver for the drivers themselves which applies to all connections. + if (isset($this->extensions[$driver = $config['driver']])) { + return call_user_func($this->extensions[$driver], $config, $name); + } + + return $this->factory->make($config, $name); + } + + /** + * Get the configuration for a connection. + * + * @param string $name + * @return array + * + * @throws \InvalidArgumentException + */ + protected function configuration($name) + { + $name = $name ?: $this->getDefaultConnection(); + + // To get the database connection configuration, we will just pull each of the + // connection configurations and get the configurations for the given name. + // If the configuration doesn't exist, we'll throw an exception and bail. + $connections = $this->app['config']['database.connections']; + + if (is_null($config = Arr::get($connections, $name))) { + throw new InvalidArgumentException("Database connection [{$name}] not configured."); + } + + return (new ConfigurationUrlParser) + ->parseConfiguration($config); + } + + /** + * Prepare the database connection instance. + * + * @param \Illuminate\Database\Connection $connection + * @param string $type + * @return \Illuminate\Database\Connection + */ + protected function configure(Connection $connection, $type) + { + $connection = $this->setPdoForType($connection, $type)->setReadWriteType($type); + + // First we'll set the fetch mode and a few other dependencies of the database + // connection. This method basically just configures and prepares it to get + // used by the application. Once we're finished we'll return it back out. + if ($this->app->bound('events')) { + $connection->setEventDispatcher($this->app['events']); + } + + if ($this->app->bound('db.transactions')) { + $connection->setTransactionManager($this->app['db.transactions']); + } + + // Here we'll set a reconnector callback. This reconnector can be any callable + // so we will set a Closure to reconnect from this manager with the name of + // the connection, which will allow us to reconnect from the connections. + $connection->setReconnector($this->reconnector); + + $this->registerConfiguredDoctrineTypes($connection); + + return $connection; + } + + /** + * Prepare the read / write mode for database connection instance. + * + * @param \Illuminate\Database\Connection $connection + * @param string|null $type + * @return \Illuminate\Database\Connection + */ + protected function setPdoForType(Connection $connection, $type = null) + { + if ($type === 'read') { + $connection->setPdo($connection->getReadPdo()); + } elseif ($type === 'write') { + $connection->setReadPdo($connection->getPdo()); + } + + return $connection; + } + + /** + * Register custom Doctrine types with the connection. + * + * @param \Illuminate\Database\Connection $connection + * @return void + */ + protected function registerConfiguredDoctrineTypes(Connection $connection): void + { + foreach ($this->app['config']->get('database.dbal.types', []) as $name => $class) { + $this->registerDoctrineType($class, $name, $name); + } + + foreach ($this->doctrineTypes as $name => [$type, $class]) { + $connection->registerDoctrineType($class, $name, $type); + } + } + + /** + * Register a custom Doctrine type. + * + * @param string $class + * @param string $name + * @param string $type + * @return void + * + * @throws \Doctrine\DBAL\DBALException + * @throws \RuntimeException + */ + public function registerDoctrineType(string $class, string $name, string $type): void + { + if (! class_exists('Doctrine\DBAL\Connection')) { + throw new RuntimeException( + 'Registering a custom Doctrine type requires Doctrine DBAL (doctrine/dbal).' + ); + } + + if (! Type::hasType($name)) { + Type::addType($name, $class); + } + + $this->doctrineTypes[$name] = [$type, $class]; + } + + /** + * Disconnect from the given database and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?: $this->getDefaultConnection(); + + $this->disconnect($name); + + unset($this->connections[$name]); + } + + /** + * Disconnect from the given database. + * + * @param string|null $name + * @return void + */ + public function disconnect($name = null) + { + if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) { + $this->connections[$name]->disconnect(); + } + } + + /** + * Reconnect to the given database. + * + * @param string|null $name + * @return \Illuminate\Database\Connection + */ + public function reconnect($name = null) + { + $this->disconnect($name = $name ?: $this->getDefaultConnection()); + + if (! isset($this->connections[$name])) { + return $this->connection($name); + } + + return $this->refreshPdoConnections($name); + } + + /** + * Set the default database connection for the callback execution. + * + * @param string $name + * @param callable $callback + * @return mixed + */ + public function usingConnection($name, callable $callback) + { + $previousName = $this->getDefaultConnection(); + + $this->setDefaultConnection($name); + + return tap($callback(), function () use ($previousName) { + $this->setDefaultConnection($previousName); + }); + } + + /** + * Refresh the PDO connections on a given connection. + * + * @param string $name + * @return \Illuminate\Database\Connection + */ + protected function refreshPdoConnections($name) + { + [$database, $type] = $this->parseConnectionName($name); + + $fresh = $this->configure( + $this->makeConnection($database), $type + ); + + return $this->connections[$name] + ->setPdo($fresh->getRawPdo()) + ->setReadPdo($fresh->getRawReadPdo()); + } + + /** + * Get the default connection name. + * + * @return string + */ + public function getDefaultConnection() + { + return $this->app['config']['database.default']; + } + + /** + * Set the default connection name. + * + * @param string $name + * @return void + */ + public function setDefaultConnection($name) + { + $this->app['config']['database.default'] = $name; + } + + /** + * Get all of the support drivers. + * + * @return array + */ + public function supportedDrivers() + { + return ['mysql', 'pgsql', 'sqlite', 'sqlsrv']; + } + + /** + * Get all of the drivers that are actually available. + * + * @return array + */ + public function availableDrivers() + { + return array_intersect( + $this->supportedDrivers(), + str_replace('dblib', 'sqlsrv', PDO::getAvailableDrivers()) + ); + } + + /** + * Register an extension connection resolver. + * + * @param string $name + * @param callable $resolver + * @return void + */ + public function extend($name, callable $resolver) + { + $this->extensions[$name] = $resolver; + } + + /** + * Return all of the created connections. + * + * @return array + */ + public function getConnections() + { + return $this->connections; + } + + /** + * Set the database reconnector callback. + * + * @param callable $reconnector + * @return void + */ + public function setReconnector(callable $reconnector) + { + $this->reconnector = $reconnector; + } + + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication($app) + { + $this->app = $app; + + return $this; + } + + /** + * Dynamically pass methods to the default connection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->connection()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php new file mode 100755 index 0000000..4b6521b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php @@ -0,0 +1,109 @@ +app['db']); + + Model::setEventDispatcher($this->app['events']); + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + Model::clearBootedModels(); + + $this->registerConnectionServices(); + $this->registerEloquentFactory(); + $this->registerQueueableEntityResolver(); + } + + /** + * Register the primary database bindings. + * + * @return void + */ + protected function registerConnectionServices() + { + // The connection factory is used to create the actual connection instances on + // the database. We will inject the factory into the manager so that it may + // make the connections while they are actually needed and not of before. + $this->app->singleton('db.factory', function ($app) { + return new ConnectionFactory($app); + }); + + // The database manager is used to resolve various connections, since multiple + // connections might be managed. It also implements the connection resolver + // interface which may be used by other components requiring connections. + $this->app->singleton('db', function ($app) { + return new DatabaseManager($app, $app['db.factory']); + }); + + $this->app->bind('db.connection', function ($app) { + return $app['db']->connection(); + }); + + $this->app->singleton('db.transactions', function ($app) { + return new DatabaseTransactionsManager; + }); + } + + /** + * Register the Eloquent factory instance in the container. + * + * @return void + */ + protected function registerEloquentFactory() + { + $this->app->singleton(FakerGenerator::class, function ($app, $parameters) { + $locale = $parameters['locale'] ?? $app['config']->get('app.faker_locale', 'en_US'); + + if (! isset(static::$fakers[$locale])) { + static::$fakers[$locale] = FakerFactory::create($locale); + } + + static::$fakers[$locale]->unique(true); + + return static::$fakers[$locale]; + }); + } + + /** + * Register the queueable entity resolver implementation. + * + * @return void + */ + protected function registerQueueableEntityResolver() + { + $this->app->singleton(EntityResolver::class, function () { + return new QueueEntityResolver; + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseTransactionRecord.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseTransactionRecord.php new file mode 100755 index 0000000..3259552 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseTransactionRecord.php @@ -0,0 +1,73 @@ +connection = $connection; + $this->level = $level; + } + + /** + * Register a callback to be executed after committing. + * + * @param callable $callback + * @return void + */ + public function addCallback($callback) + { + $this->callbacks[] = $callback; + } + + /** + * Execute all of the callbacks. + * + * @return void + */ + public function executeCallbacks() + { + foreach ($this->callbacks as $callback) { + call_user_func($callback); + } + } + + /** + * Get all of the callbacks. + * + * @return array + */ + public function getCallbacks() + { + return $this->callbacks; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseTransactionsManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseTransactionsManager.php new file mode 100755 index 0000000..add2f7c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DatabaseTransactionsManager.php @@ -0,0 +1,96 @@ +transactions = collect(); + } + + /** + * Start a new database transaction. + * + * @param string $connection + * @param int $level + * @return void + */ + public function begin($connection, $level) + { + $this->transactions->push( + new DatabaseTransactionRecord($connection, $level) + ); + } + + /** + * Rollback the active database transaction. + * + * @param string $connection + * @param int $level + * @return void + */ + public function rollback($connection, $level) + { + $this->transactions = $this->transactions->reject(function ($transaction) use ($connection, $level) { + return $transaction->connection == $connection && + $transaction->level > $level; + })->values(); + } + + /** + * Commit the active database transaction. + * + * @param string $connection + * @return void + */ + public function commit($connection) + { + [$forThisConnection, $forOtherConnections] = $this->transactions->partition( + function ($transaction) use ($connection) { + return $transaction->connection == $connection; + } + ); + + $this->transactions = $forOtherConnections->values(); + + $forThisConnection->map->executeCallbacks(); + } + + /** + * Register a transaction callback. + * + * @param callable $callback + * @return void + */ + public function addCallback($callback) + { + if ($current = $this->transactions->last()) { + return $current->addCallback($callback); + } + + call_user_func($callback); + } + + /** + * Get all the transactions. + * + * @return \Illuminate\Support\Collection + */ + public function getTransactions() + { + return $this->transactions; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DetectsConcurrencyErrors.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DetectsConcurrencyErrors.php new file mode 100644 index 0000000..c6c66f4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DetectsConcurrencyErrors.php @@ -0,0 +1,37 @@ +getCode() === 40001 || $e->getCode() === '40001')) { + return true; + } + + $message = $e->getMessage(); + + return Str::contains($message, [ + 'Deadlock found when trying to get lock', + 'deadlock detected', + 'The database file is locked', + 'database is locked', + 'database table is locked', + 'A table in the database is locked', + 'has been chosen as the deadlock victim', + 'Lock wait timeout exceeded; try restarting transaction', + 'WSREP detected deadlock/conflict and aborted the transaction. Try restarting the transaction', + ]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DetectsLostConnections.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DetectsLostConnections.php new file mode 100644 index 0000000..16c8687 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/DetectsLostConnections.php @@ -0,0 +1,62 @@ +getMessage(); + + return Str::contains($message, [ + 'server has gone away', + 'no connection to the server', + 'Lost connection', + 'is dead or not enabled', + 'Error while sending', + 'decryption failed or bad record mac', + 'server closed the connection unexpectedly', + 'SSL connection has been closed unexpectedly', + 'Error writing data to the connection', + 'Resource deadlock avoided', + 'Transaction() on null', + 'child connection forced to terminate due to client_idle_limit', + 'query_wait_timeout', + 'reset by peer', + 'Physical connection is not usable', + 'TCP Provider: Error code 0x68', + 'ORA-03114', + 'Packets out of order. Expected', + 'Adaptive Server connection failed', + 'Communication link failure', + 'connection is no longer usable', + 'Login timeout expired', + 'SQLSTATE[HY000] [2002] Connection refused', + 'running with the --read-only option so it cannot execute this statement', + 'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.', + 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Try again', + 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known', + 'SQLSTATE[HY000]: General error: 7 SSL SYSCALL error: EOF detected', + 'SQLSTATE[HY000] [2002] Connection timed out', + 'SSL: Connection timed out', + 'SQLSTATE[HY000]: General error: 1105 The last transaction was aborted due to Seamless Scaling. Please retry.', + 'Temporary failure in name resolution', + 'SSL: Broken pipe', + 'SQLSTATE[08S01]: Communication link failure', + 'SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host', + 'SQLSTATE[HY000]: General error: 7 SSL SYSCALL error: No route to host', + 'The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.', + 'SQLSTATE[08006] [7] could not translate host name', + 'TCP Provider: Error code 0x274C', + ]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/BroadcastableModelEventOccurred.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/BroadcastableModelEventOccurred.php new file mode 100644 index 0000000..14be425 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/BroadcastableModelEventOccurred.php @@ -0,0 +1,137 @@ +model = $model; + $this->event = $event; + } + + /** + * The channels the event should broadcast on. + * + * @return array + */ + public function broadcastOn() + { + $channels = empty($this->channels) + ? ($this->model->broadcastOn($this->event) ?: []) + : $this->channels; + + return collect($channels)->map(function ($channel) { + return $channel instanceof Model ? new PrivateChannel($channel) : $channel; + })->all(); + } + + /** + * The name the event should broadcast as. + * + * @return string + */ + public function broadcastAs() + { + $default = class_basename($this->model).ucfirst($this->event); + + return method_exists($this->model, 'broadcastAs') + ? ($this->model->broadcastAs($this->event) ?: $default) + : $default; + } + + /** + * Get the data that should be sent with the broadcasted event. + * + * @return array|null + */ + public function broadcastWith() + { + return method_exists($this->model, 'broadcastWith') + ? $this->model->broadcastWith($this->event) + : null; + } + + /** + * Manually specify the channels the event should broadcast on. + * + * @param array $channels + * @return $this + */ + public function onChannels(array $channels) + { + $this->channels = $channels; + + return $this; + } + + /** + * Determine if the event should be broadcast synchronously. + * + * @return bool + */ + public function shouldBroadcastNow() + { + return $this->event === 'deleted' && + ! method_exists($this->model, 'bootSoftDeletes'); + } + + /** + * Get the event name. + * + * @return string + */ + public function event() + { + return $this->event; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/BroadcastsEvents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/BroadcastsEvents.php new file mode 100644 index 0000000..79dc02d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/BroadcastsEvents.php @@ -0,0 +1,197 @@ +broadcastCreated(); + }); + + static::updated(function ($model) { + $model->broadcastUpdated(); + }); + + if (method_exists(static::class, 'bootSoftDeletes')) { + static::softDeleted(function ($model) { + $model->broadcastTrashed(); + }); + + static::restored(function ($model) { + $model->broadcastRestored(); + }); + } + + static::deleted(function ($model) { + $model->broadcastDeleted(); + }); + } + + /** + * Broadcast that the model was created. + * + * @param \Illuminate\Broadcasting\Channel|\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|array|null $channels + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + public function broadcastCreated($channels = null) + { + return $this->broadcastIfBroadcastChannelsExistForEvent( + $this->newBroadcastableModelEvent('created'), 'created', $channels + ); + } + + /** + * Broadcast that the model was updated. + * + * @param \Illuminate\Broadcasting\Channel|\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|array|null $channels + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + public function broadcastUpdated($channels = null) + { + return $this->broadcastIfBroadcastChannelsExistForEvent( + $this->newBroadcastableModelEvent('updated'), 'updated', $channels + ); + } + + /** + * Broadcast that the model was trashed. + * + * @param \Illuminate\Broadcasting\Channel|\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|array|null $channels + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + public function broadcastTrashed($channels = null) + { + return $this->broadcastIfBroadcastChannelsExistForEvent( + $this->newBroadcastableModelEvent('trashed'), 'trashed', $channels + ); + } + + /** + * Broadcast that the model was restored. + * + * @param \Illuminate\Broadcasting\Channel|\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|array|null $channels + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + public function broadcastRestored($channels = null) + { + return $this->broadcastIfBroadcastChannelsExistForEvent( + $this->newBroadcastableModelEvent('restored'), 'restored', $channels + ); + } + + /** + * Broadcast that the model was deleted. + * + * @param \Illuminate\Broadcasting\Channel|\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|array|null $channels + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + public function broadcastDeleted($channels = null) + { + return $this->broadcastIfBroadcastChannelsExistForEvent( + $this->newBroadcastableModelEvent('deleted'), 'deleted', $channels + ); + } + + /** + * Broadcast the given event instance if channels are configured for the model event. + * + * @param mixed $instance + * @param string $event + * @param mixed $channels + * @return \Illuminate\Broadcasting\PendingBroadcast|null + */ + protected function broadcastIfBroadcastChannelsExistForEvent($instance, $event, $channels = null) + { + if (! static::$isBroadcasting) { + return; + } + + if (! empty($this->broadcastOn($event)) || ! empty($channels)) { + return broadcast($instance->onChannels(Arr::wrap($channels))); + } + } + + /** + * Create a new broadcastable model event event. + * + * @param string $event + * @return mixed + */ + public function newBroadcastableModelEvent($event) + { + return tap($this->newBroadcastableEvent($event), function ($event) { + $event->connection = property_exists($this, 'broadcastConnection') + ? $this->broadcastConnection + : $this->broadcastConnection(); + + $event->queue = property_exists($this, 'broadcastQueue') + ? $this->broadcastQueue + : $this->broadcastQueue(); + + $event->afterCommit = property_exists($this, 'broadcastAfterCommit') + ? $this->broadcastAfterCommit + : $this->broadcastAfterCommit(); + }); + } + + /** + * Create a new broadcastable model event for the model. + * + * @param string $event + * @return \Illuminate\Database\Eloquent\BroadcastableModelEventOccurred + */ + protected function newBroadcastableEvent($event) + { + return new BroadcastableModelEventOccurred($this, $event); + } + + /** + * Get the channels that model events should broadcast on. + * + * @param string $event + * @return \Illuminate\Broadcasting\Channel|array + */ + public function broadcastOn($event) + { + return [$this]; + } + + /** + * Get the queue connection that should be used to broadcast model events. + * + * @return string|null + */ + public function broadcastConnection() + { + // + } + + /** + * Get the queue that should be used to broadcast model events. + * + * @return string|null + */ + public function broadcastQueue() + { + // + } + + /** + * Determine if the model event broadcast queued job should be dispatched after all transactions are committed. + * + * @return bool + */ + public function broadcastAfterCommit() + { + return false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php new file mode 100755 index 0000000..babd44b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php @@ -0,0 +1,1740 @@ +query = $query; + } + + /** + * Create and return an un-saved model instance. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function make(array $attributes = []) + { + return $this->newModelInstance($attributes); + } + + /** + * Register a new global scope. + * + * @param string $identifier + * @param \Illuminate\Database\Eloquent\Scope|\Closure $scope + * @return $this + */ + public function withGlobalScope($identifier, $scope) + { + $this->scopes[$identifier] = $scope; + + if (method_exists($scope, 'extend')) { + $scope->extend($this); + } + + return $this; + } + + /** + * Remove a registered global scope. + * + * @param \Illuminate\Database\Eloquent\Scope|string $scope + * @return $this + */ + public function withoutGlobalScope($scope) + { + if (! is_string($scope)) { + $scope = get_class($scope); + } + + unset($this->scopes[$scope]); + + $this->removedScopes[] = $scope; + + return $this; + } + + /** + * Remove all or passed registered global scopes. + * + * @param array|null $scopes + * @return $this + */ + public function withoutGlobalScopes(array $scopes = null) + { + if (! is_array($scopes)) { + $scopes = array_keys($this->scopes); + } + + foreach ($scopes as $scope) { + $this->withoutGlobalScope($scope); + } + + return $this; + } + + /** + * Get an array of global scopes that were removed from the query. + * + * @return array + */ + public function removedScopes() + { + return $this->removedScopes; + } + + /** + * Add a where clause on the primary key to the query. + * + * @param mixed $id + * @return $this + */ + public function whereKey($id) + { + if ($id instanceof Model) { + $id = $id->getKey(); + } + + if (is_array($id) || $id instanceof Arrayable) { + $this->query->whereIn($this->model->getQualifiedKeyName(), $id); + + return $this; + } + + if ($id !== null && $this->model->getKeyType() === 'string') { + $id = (string) $id; + } + + return $this->where($this->model->getQualifiedKeyName(), '=', $id); + } + + /** + * Add a where clause on the primary key to the query. + * + * @param mixed $id + * @return $this + */ + public function whereKeyNot($id) + { + if ($id instanceof Model) { + $id = $id->getKey(); + } + + if (is_array($id) || $id instanceof Arrayable) { + $this->query->whereNotIn($this->model->getQualifiedKeyName(), $id); + + return $this; + } + + if ($id !== null && $this->model->getKeyType() === 'string') { + $id = (string) $id; + } + + return $this->where($this->model->getQualifiedKeyName(), '!=', $id); + } + + /** + * Add a basic where clause to the query. + * + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return $this + */ + public function where($column, $operator = null, $value = null, $boolean = 'and') + { + if ($column instanceof Closure && is_null($operator)) { + $column($query = $this->model->newQueryWithoutRelationships()); + + $this->query->addNestedWhereQuery($query->getQuery(), $boolean); + } else { + $this->query->where(...func_get_args()); + } + + return $this; + } + + /** + * Add a basic where clause to the query, and return the first result. + * + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Model|static|null + */ + public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') + { + return $this->where($column, $operator, $value, $boolean)->first(); + } + + /** + * Add an "or where" clause to the query. + * + * @param \Closure|array|string|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return $this + */ + public function orWhere($column, $operator = null, $value = null) + { + [$value, $operator] = $this->query->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->where($column, $operator, $value, 'or'); + } + + /** + * Add an "order by" clause for a timestamp to the query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return $this + */ + public function latest($column = null) + { + if (is_null($column)) { + $column = $this->model->getCreatedAtColumn() ?? 'created_at'; + } + + $this->query->latest($column); + + return $this; + } + + /** + * Add an "order by" clause for a timestamp to the query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return $this + */ + public function oldest($column = null) + { + if (is_null($column)) { + $column = $this->model->getCreatedAtColumn() ?? 'created_at'; + } + + $this->query->oldest($column); + + return $this; + } + + /** + * Create a collection of models from plain arrays. + * + * @param array $items + * @return \Illuminate\Database\Eloquent\Collection + */ + public function hydrate(array $items) + { + $instance = $this->newModelInstance(); + + return $instance->newCollection(array_map(function ($item) use ($items, $instance) { + $model = $instance->newFromBuilder($item); + + if (count($items) > 1) { + $model->preventsLazyLoading = Model::preventsLazyLoading(); + } + + return $model; + }, $items)); + } + + /** + * Create a collection of models from a raw query. + * + * @param string $query + * @param array $bindings + * @return \Illuminate\Database\Eloquent\Collection + */ + public function fromQuery($query, $bindings = []) + { + return $this->hydrate( + $this->query->getConnection()->select($query, $bindings) + ); + } + + /** + * Find a model by its primary key. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null + */ + public function find($id, $columns = ['*']) + { + if (is_array($id) || $id instanceof Arrayable) { + return $this->findMany($id, $columns); + } + + return $this->whereKey($id)->first($columns); + } + + /** + * Find multiple models by their primary keys. + * + * @param \Illuminate\Contracts\Support\Arrayable|array $ids + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function findMany($ids, $columns = ['*']) + { + $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; + + if (empty($ids)) { + return $this->model->newCollection(); + } + + return $this->whereKey($ids)->get($columns); + } + + /** + * Find a model by its primary key or throw an exception. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static|static[] + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function findOrFail($id, $columns = ['*']) + { + $result = $this->find($id, $columns); + + $id = $id instanceof Arrayable ? $id->toArray() : $id; + + if (is_array($id)) { + if (count($result) === count(array_unique($id))) { + return $result; + } + } elseif (! is_null($result)) { + return $result; + } + + throw (new ModelNotFoundException)->setModel( + get_class($this->model), $id + ); + } + + /** + * Find a model by its primary key or return fresh model instance. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function findOrNew($id, $columns = ['*']) + { + if (! is_null($model = $this->find($id, $columns))) { + return $model; + } + + return $this->newModelInstance(); + } + + /** + * Get the first record matching the attributes or instantiate it. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function firstOrNew(array $attributes = [], array $values = []) + { + if (! is_null($instance = $this->where($attributes)->first())) { + return $instance; + } + + return $this->newModelInstance(array_merge($attributes, $values)); + } + + /** + * Get the first record matching the attributes or create it. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function firstOrCreate(array $attributes = [], array $values = []) + { + if (! is_null($instance = $this->where($attributes)->first())) { + return $instance; + } + + return tap($this->newModelInstance(array_merge($attributes, $values)), function ($instance) { + $instance->save(); + }); + } + + /** + * Create or update a record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function updateOrCreate(array $attributes, array $values = []) + { + return tap($this->firstOrNew($attributes), function ($instance) use ($values) { + $instance->fill($values)->save(); + }); + } + + /** + * Execute the query and get the first result or throw an exception. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|static + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function firstOrFail($columns = ['*']) + { + if (! is_null($model = $this->first($columns))) { + return $model; + } + + throw (new ModelNotFoundException)->setModel(get_class($this->model)); + } + + /** + * Execute the query and get the first result or call a callback. + * + * @param \Closure|array $columns + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Model|static|mixed + */ + public function firstOr($columns = ['*'], Closure $callback = null) + { + if ($columns instanceof Closure) { + $callback = $columns; + + $columns = ['*']; + } + + if (! is_null($model = $this->first($columns))) { + return $model; + } + + return $callback(); + } + + /** + * Execute the query and get the first result if it's the sole matching record. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + * @throws \Illuminate\Database\MultipleRecordsFoundException + */ + public function sole($columns = ['*']) + { + try { + return $this->baseSole($columns); + } catch (RecordsNotFoundException $exception) { + throw (new ModelNotFoundException)->setModel(get_class($this->model)); + } + } + + /** + * Get a single column's value from the first result of a query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return mixed + */ + public function value($column) + { + if ($result = $this->first([$column])) { + return $result->{Str::afterLast($column, '.')}; + } + } + + /** + * Get a single column's value from the first result of the query or throw an exception. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return mixed + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function valueOrFail($column) + { + return $this->firstOrFail([$column])->{Str::afterLast($column, '.')}; + } + + /** + * Execute the query as a "select" statement. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Collection|static[] + */ + public function get($columns = ['*']) + { + $builder = $this->applyScopes(); + + // If we actually found models we will also eager load any relationships that + // have been specified as needing to be eager loaded, which will solve the + // n+1 query issue for the developers to avoid running a lot of queries. + if (count($models = $builder->getModels($columns)) > 0) { + $models = $builder->eagerLoadRelations($models); + } + + return $builder->getModel()->newCollection($models); + } + + /** + * Get the hydrated models without eager loading. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model[]|static[] + */ + public function getModels($columns = ['*']) + { + return $this->model->hydrate( + $this->query->get($columns)->all() + )->all(); + } + + /** + * Eager load the relationships for the models. + * + * @param array $models + * @return array + */ + public function eagerLoadRelations(array $models) + { + foreach ($this->eagerLoad as $name => $constraints) { + // For nested eager loads we'll skip loading them here and they will be set as an + // eager load on the query to retrieve the relation so that they will be eager + // loaded on that query, because that is where they get hydrated as models. + if (strpos($name, '.') === false) { + $models = $this->eagerLoadRelation($models, $name, $constraints); + } + } + + return $models; + } + + /** + * Eagerly load the relationship on a set of models. + * + * @param array $models + * @param string $name + * @param \Closure $constraints + * @return array + */ + protected function eagerLoadRelation(array $models, $name, Closure $constraints) + { + // First we will "back up" the existing where conditions on the query so we can + // add our eager constraints. Then we will merge the wheres that were on the + // query back to it in order that any where conditions might be specified. + $relation = $this->getRelation($name); + + $relation->addEagerConstraints($models); + + $constraints($relation); + + // Once we have the results, we just match those back up to their parent models + // using the relationship instance. Then we just return the finished arrays + // of models which have been eagerly hydrated and are readied for return. + return $relation->match( + $relation->initRelation($models, $name), + $relation->getEager(), $name + ); + } + + /** + * Get the relation instance for the given relation name. + * + * @param string $name + * @return \Illuminate\Database\Eloquent\Relations\Relation + */ + public function getRelation($name) + { + // We want to run a relationship query without any constrains so that we will + // not have to remove these where clauses manually which gets really hacky + // and error prone. We don't want constraints because we add eager ones. + $relation = Relation::noConstraints(function () use ($name) { + try { + return $this->getModel()->newInstance()->$name(); + } catch (BadMethodCallException $e) { + throw RelationNotFoundException::make($this->getModel(), $name); + } + }); + + $nested = $this->relationsNestedUnder($name); + + // If there are nested relationships set on the query, we will put those onto + // the query instances so that they can be handled after this relationship + // is loaded. In this way they will all trickle down as they are loaded. + if (count($nested) > 0) { + $relation->getQuery()->with($nested); + } + + return $relation; + } + + /** + * Get the deeply nested relations for a given top-level relation. + * + * @param string $relation + * @return array + */ + protected function relationsNestedUnder($relation) + { + $nested = []; + + // We are basically looking for any relationships that are nested deeper than + // the given top-level relationship. We will just check for any relations + // that start with the given top relations and adds them to our arrays. + foreach ($this->eagerLoad as $name => $constraints) { + if ($this->isNestedUnder($relation, $name)) { + $nested[substr($name, strlen($relation.'.'))] = $constraints; + } + } + + return $nested; + } + + /** + * Determine if the relationship is nested. + * + * @param string $relation + * @param string $name + * @return bool + */ + protected function isNestedUnder($relation, $name) + { + return Str::contains($name, '.') && Str::startsWith($name, $relation.'.'); + } + + /** + * Get a lazy collection for the given query. + * + * @return \Illuminate\Support\LazyCollection + */ + public function cursor() + { + return $this->applyScopes()->query->cursor()->map(function ($record) { + return $this->newModelInstance()->newFromBuilder($record); + }); + } + + /** + * Add a generic "order by" clause if the query doesn't already have one. + * + * @return void + */ + protected function enforceOrderBy() + { + if (empty($this->query->orders) && empty($this->query->unionOrders)) { + $this->orderBy($this->model->getQualifiedKeyName(), 'asc'); + } + } + + /** + * Get an array with the values of a given column. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @param string|null $key + * @return \Illuminate\Support\Collection + */ + public function pluck($column, $key = null) + { + $results = $this->toBase()->pluck($column, $key); + + // If the model has a mutator for the requested column, we will spin through + // the results and mutate the values so that the mutated version of these + // columns are returned as you would expect from these Eloquent models. + if (! $this->model->hasGetMutator($column) && + ! $this->model->hasCast($column) && + ! in_array($column, $this->model->getDates())) { + return $results; + } + + return $results->map(function ($value) use ($column) { + return $this->model->newFromBuilder([$column => $value])->{$column}; + }); + } + + /** + * Paginate the given query. + * + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + * + * @throws \InvalidArgumentException + */ + public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) + { + $page = $page ?: Paginator::resolveCurrentPage($pageName); + + $perPage = $perPage ?: $this->model->getPerPage(); + + $results = ($total = $this->toBase()->getCountForPagination()) + ? $this->forPage($page, $perPage)->get($columns) + : $this->model->newCollection(); + + return $this->paginator($results, $total, $perPage, $page, [ + 'path' => Paginator::resolveCurrentPath(), + 'pageName' => $pageName, + ]); + } + + /** + * Paginate the given query into a simple paginator. + * + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\Paginator + */ + public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) + { + $page = $page ?: Paginator::resolveCurrentPage($pageName); + + $perPage = $perPage ?: $this->model->getPerPage(); + + // Next we will set the limit and offset for this query so that when we get the + // results we get the proper section of results. Then, we'll create the full + // paginator instances for these results with the given page and per page. + $this->skip(($page - 1) * $perPage)->take($perPage + 1); + + return $this->simplePaginator($this->get($columns), $perPage, $page, [ + 'path' => Paginator::resolveCurrentPath(), + 'pageName' => $pageName, + ]); + } + + /** + * Paginate the given query into a cursor paginator. + * + * @param int|null $perPage + * @param array $columns + * @param string $cursorName + * @param \Illuminate\Pagination\Cursor|string|null $cursor + * @return \Illuminate\Contracts\Pagination\CursorPaginator + */ + public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null) + { + $perPage = $perPage ?: $this->model->getPerPage(); + + return $this->paginateUsingCursor($perPage, $columns, $cursorName, $cursor); + } + + /** + * Ensure the proper order by required for cursor pagination. + * + * @param bool $shouldReverse + * @return \Illuminate\Support\Collection + */ + protected function ensureOrderForCursorPagination($shouldReverse = false) + { + if (empty($this->query->orders) && empty($this->query->unionOrders)) { + $this->enforceOrderBy(); + } + + if ($shouldReverse) { + $this->query->orders = collect($this->query->orders)->map(function ($order) { + $order['direction'] = $order['direction'] === 'asc' ? 'desc' : 'asc'; + + return $order; + })->toArray(); + } + + if ($this->query->unionOrders) { + return collect($this->query->unionOrders); + } + + return collect($this->query->orders); + } + + /** + * Save a new model and return the instance. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|$this + */ + public function create(array $attributes = []) + { + return tap($this->newModelInstance($attributes), function ($instance) { + $instance->save(); + }); + } + + /** + * Save a new model and return the instance. Allow mass-assignment. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|$this + */ + public function forceCreate(array $attributes) + { + return $this->model->unguarded(function () use ($attributes) { + return $this->newModelInstance()->create($attributes); + }); + } + + /** + * Update records in the database. + * + * @param array $values + * @return int + */ + public function update(array $values) + { + return $this->toBase()->update($this->addUpdatedAtColumn($values)); + } + + /** + * Insert new records or update the existing ones. + * + * @param array $values + * @param array|string $uniqueBy + * @param array|null $update + * @return int + */ + public function upsert(array $values, $uniqueBy, $update = null) + { + if (empty($values)) { + return 0; + } + + if (! is_array(reset($values))) { + $values = [$values]; + } + + if (is_null($update)) { + $update = array_keys(reset($values)); + } + + return $this->toBase()->upsert( + $this->addTimestampsToUpsertValues($values), + $uniqueBy, + $this->addUpdatedAtToUpsertColumns($update) + ); + } + + /** + * Increment a column's value by a given amount. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @param float|int $amount + * @param array $extra + * @return int + */ + public function increment($column, $amount = 1, array $extra = []) + { + return $this->toBase()->increment( + $column, $amount, $this->addUpdatedAtColumn($extra) + ); + } + + /** + * Decrement a column's value by a given amount. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @param float|int $amount + * @param array $extra + * @return int + */ + public function decrement($column, $amount = 1, array $extra = []) + { + return $this->toBase()->decrement( + $column, $amount, $this->addUpdatedAtColumn($extra) + ); + } + + /** + * Add the "updated at" column to an array of values. + * + * @param array $values + * @return array + */ + protected function addUpdatedAtColumn(array $values) + { + if (! $this->model->usesTimestamps() || + is_null($this->model->getUpdatedAtColumn())) { + return $values; + } + + $column = $this->model->getUpdatedAtColumn(); + + $values = array_merge( + [$column => $this->model->freshTimestampString()], + $values + ); + + $segments = preg_split('/\s+as\s+/i', $this->query->from); + + $qualifiedColumn = end($segments).'.'.$column; + + $values[$qualifiedColumn] = Arr::get($values, $qualifiedColumn, $values[$column]); + + unset($values[$column]); + + return $values; + } + + /** + * Add timestamps to the inserted values. + * + * @param array $values + * @return array + */ + protected function addTimestampsToUpsertValues(array $values) + { + if (! $this->model->usesTimestamps()) { + return $values; + } + + $timestamp = $this->model->freshTimestampString(); + + $columns = array_filter([ + $this->model->getCreatedAtColumn(), + $this->model->getUpdatedAtColumn(), + ]); + + foreach ($columns as $column) { + foreach ($values as &$row) { + $row = array_merge([$column => $timestamp], $row); + } + } + + return $values; + } + + /** + * Add the "updated at" column to the updated columns. + * + * @param array $update + * @return array + */ + protected function addUpdatedAtToUpsertColumns(array $update) + { + if (! $this->model->usesTimestamps()) { + return $update; + } + + $column = $this->model->getUpdatedAtColumn(); + + if (! is_null($column) && + ! array_key_exists($column, $update) && + ! in_array($column, $update)) { + $update[] = $column; + } + + return $update; + } + + /** + * Delete records from the database. + * + * @return mixed + */ + public function delete() + { + if (isset($this->onDelete)) { + return call_user_func($this->onDelete, $this); + } + + return $this->toBase()->delete(); + } + + /** + * Run the default delete function on the builder. + * + * Since we do not apply scopes here, the row will actually be deleted. + * + * @return mixed + */ + public function forceDelete() + { + return $this->query->delete(); + } + + /** + * Register a replacement for the default delete function. + * + * @param \Closure $callback + * @return void + */ + public function onDelete(Closure $callback) + { + $this->onDelete = $callback; + } + + /** + * Determine if the given model has a scope. + * + * @param string $scope + * @return bool + */ + public function hasNamedScope($scope) + { + return $this->model && $this->model->hasNamedScope($scope); + } + + /** + * Call the given local model scopes. + * + * @param array|string $scopes + * @return static|mixed + */ + public function scopes($scopes) + { + $builder = $this; + + foreach (Arr::wrap($scopes) as $scope => $parameters) { + // If the scope key is an integer, then the scope was passed as the value and + // the parameter list is empty, so we will format the scope name and these + // parameters here. Then, we'll be ready to call the scope on the model. + if (is_int($scope)) { + [$scope, $parameters] = [$parameters, []]; + } + + // Next we'll pass the scope callback to the callScope method which will take + // care of grouping the "wheres" properly so the logical order doesn't get + // messed up when adding scopes. Then we'll return back out the builder. + $builder = $builder->callNamedScope( + $scope, Arr::wrap($parameters) + ); + } + + return $builder; + } + + /** + * Apply the scopes to the Eloquent builder instance and return it. + * + * @return static + */ + public function applyScopes() + { + if (! $this->scopes) { + return $this; + } + + $builder = clone $this; + + foreach ($this->scopes as $identifier => $scope) { + if (! isset($builder->scopes[$identifier])) { + continue; + } + + $builder->callScope(function (self $builder) use ($scope) { + // If the scope is a Closure we will just go ahead and call the scope with the + // builder instance. The "callScope" method will properly group the clauses + // that are added to this query so "where" clauses maintain proper logic. + if ($scope instanceof Closure) { + $scope($builder); + } + + // If the scope is a scope object, we will call the apply method on this scope + // passing in the builder and the model instance. After we run all of these + // scopes we will return back the builder instance to the outside caller. + if ($scope instanceof Scope) { + $scope->apply($builder, $this->getModel()); + } + }); + } + + return $builder; + } + + /** + * Apply the given scope on the current builder instance. + * + * @param callable $scope + * @param array $parameters + * @return mixed + */ + protected function callScope(callable $scope, array $parameters = []) + { + array_unshift($parameters, $this); + + $query = $this->getQuery(); + + // We will keep track of how many wheres are on the query before running the + // scope so that we can properly group the added scope constraints in the + // query as their own isolated nested where statement and avoid issues. + $originalWhereCount = is_null($query->wheres) + ? 0 : count($query->wheres); + + $result = $scope(...array_values($parameters)) ?? $this; + + if (count((array) $query->wheres) > $originalWhereCount) { + $this->addNewWheresWithinGroup($query, $originalWhereCount); + } + + return $result; + } + + /** + * Apply the given named scope on the current builder instance. + * + * @param string $scope + * @param array $parameters + * @return mixed + */ + protected function callNamedScope($scope, array $parameters = []) + { + return $this->callScope(function (...$parameters) use ($scope) { + return $this->model->callNamedScope($scope, $parameters); + }, $parameters); + } + + /** + * Nest where conditions by slicing them at the given where count. + * + * @param \Illuminate\Database\Query\Builder $query + * @param int $originalWhereCount + * @return void + */ + protected function addNewWheresWithinGroup(QueryBuilder $query, $originalWhereCount) + { + // Here, we totally remove all of the where clauses since we are going to + // rebuild them as nested queries by slicing the groups of wheres into + // their own sections. This is to prevent any confusing logic order. + $allWheres = $query->wheres; + + $query->wheres = []; + + $this->groupWhereSliceForScope( + $query, array_slice($allWheres, 0, $originalWhereCount) + ); + + $this->groupWhereSliceForScope( + $query, array_slice($allWheres, $originalWhereCount) + ); + } + + /** + * Slice where conditions at the given offset and add them to the query as a nested condition. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $whereSlice + * @return void + */ + protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice) + { + $whereBooleans = collect($whereSlice)->pluck('boolean'); + + // Here we'll check if the given subset of where clauses contains any "or" + // booleans and in this case create a nested where expression. That way + // we don't add any unnecessary nesting thus keeping the query clean. + if ($whereBooleans->contains('or')) { + $query->wheres[] = $this->createNestedWhere( + $whereSlice, $whereBooleans->first() + ); + } else { + $query->wheres = array_merge($query->wheres, $whereSlice); + } + } + + /** + * Create a where array with nested where conditions. + * + * @param array $whereSlice + * @param string $boolean + * @return array + */ + protected function createNestedWhere($whereSlice, $boolean = 'and') + { + $whereGroup = $this->getQuery()->forNestedWhere(); + + $whereGroup->wheres = $whereSlice; + + return ['type' => 'Nested', 'query' => $whereGroup, 'boolean' => $boolean]; + } + + /** + * Set the relationships that should be eager loaded. + * + * @param string|array $relations + * @param string|\Closure|null $callback + * @return $this + */ + public function with($relations, $callback = null) + { + if ($callback instanceof Closure) { + $eagerLoad = $this->parseWithRelations([$relations => $callback]); + } else { + $eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations); + } + + $this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad); + + return $this; + } + + /** + * Prevent the specified relations from being eager loaded. + * + * @param mixed $relations + * @return $this + */ + public function without($relations) + { + $this->eagerLoad = array_diff_key($this->eagerLoad, array_flip( + is_string($relations) ? func_get_args() : $relations + )); + + return $this; + } + + /** + * Set the relationships that should be eager loaded while removing any previously added eager loading specifications. + * + * @param mixed $relations + * @return $this + */ + public function withOnly($relations) + { + $this->eagerLoad = []; + + return $this->with($relations); + } + + /** + * Create a new instance of the model being queried. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function newModelInstance($attributes = []) + { + return $this->model->newInstance($attributes)->setConnection( + $this->query->getConnection()->getName() + ); + } + + /** + * Parse a list of relations into individuals. + * + * @param array $relations + * @return array + */ + protected function parseWithRelations(array $relations) + { + $results = []; + + foreach ($relations as $name => $constraints) { + // If the "name" value is a numeric key, we can assume that no constraints + // have been specified. We will just put an empty Closure there so that + // we can treat these all the same while we are looping through them. + if (is_numeric($name)) { + $name = $constraints; + + [$name, $constraints] = Str::contains($name, ':') + ? $this->createSelectWithConstraint($name) + : [$name, static function () { + // + }]; + } + + // We need to separate out any nested includes, which allows the developers + // to load deep relationships using "dots" without stating each level of + // the relationship with its own key in the array of eager-load names. + $results = $this->addNestedWiths($name, $results); + + $results[$name] = $constraints; + } + + return $results; + } + + /** + * Create a constraint to select the given columns for the relation. + * + * @param string $name + * @return array + */ + protected function createSelectWithConstraint($name) + { + return [explode(':', $name)[0], static function ($query) use ($name) { + $query->select(array_map(static function ($column) use ($query) { + if (Str::contains($column, '.')) { + return $column; + } + + return $query instanceof BelongsToMany + ? $query->getRelated()->getTable().'.'.$column + : $column; + }, explode(',', explode(':', $name)[1]))); + }]; + } + + /** + * Parse the nested relationships in a relation. + * + * @param string $name + * @param array $results + * @return array + */ + protected function addNestedWiths($name, $results) + { + $progress = []; + + // If the relation has already been set on the result array, we will not set it + // again, since that would override any constraints that were already placed + // on the relationships. We will only set the ones that are not specified. + foreach (explode('.', $name) as $segment) { + $progress[] = $segment; + + if (! isset($results[$last = implode('.', $progress)])) { + $results[$last] = static function () { + // + }; + } + } + + return $results; + } + + /** + * Apply query-time casts to the model instance. + * + * @param array $casts + * @return $this + */ + public function withCasts($casts) + { + $this->model->mergeCasts($casts); + + return $this; + } + + /** + * Get the underlying query builder instance. + * + * @return \Illuminate\Database\Query\Builder + */ + public function getQuery() + { + return $this->query; + } + + /** + * Set the underlying query builder instance. + * + * @param \Illuminate\Database\Query\Builder $query + * @return $this + */ + public function setQuery($query) + { + $this->query = $query; + + return $this; + } + + /** + * Get a base query builder instance. + * + * @return \Illuminate\Database\Query\Builder + */ + public function toBase() + { + return $this->applyScopes()->getQuery(); + } + + /** + * Get the relationships being eagerly loaded. + * + * @return array + */ + public function getEagerLoads() + { + return $this->eagerLoad; + } + + /** + * Set the relationships being eagerly loaded. + * + * @param array $eagerLoad + * @return $this + */ + public function setEagerLoads(array $eagerLoad) + { + $this->eagerLoad = $eagerLoad; + + return $this; + } + + /** + * Get the default key name of the table. + * + * @return string + */ + protected function defaultKeyName() + { + return $this->getModel()->getKeyName(); + } + + /** + * Get the model instance being queried. + * + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function getModel() + { + return $this->model; + } + + /** + * Set a model instance for the model being queried. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return $this + */ + public function setModel(Model $model) + { + $this->model = $model; + + $this->query->from($model->getTable()); + + return $this; + } + + /** + * Qualify the given column name by the model's table. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return string + */ + public function qualifyColumn($column) + { + return $this->model->qualifyColumn($column); + } + + /** + * Qualify the given columns with the model's table. + * + * @param array|\Illuminate\Database\Query\Expression $columns + * @return array + */ + public function qualifyColumns($columns) + { + return $this->model->qualifyColumns($columns); + } + + /** + * Get the given macro by name. + * + * @param string $name + * @return \Closure + */ + public function getMacro($name) + { + return Arr::get($this->localMacros, $name); + } + + /** + * Checks if a macro is registered. + * + * @param string $name + * @return bool + */ + public function hasMacro($name) + { + return isset($this->localMacros[$name]); + } + + /** + * Get the given global macro by name. + * + * @param string $name + * @return \Closure + */ + public static function getGlobalMacro($name) + { + return Arr::get(static::$macros, $name); + } + + /** + * Checks if a global macro is registered. + * + * @param string $name + * @return bool + */ + public static function hasGlobalMacro($name) + { + return isset(static::$macros[$name]); + } + + /** + * Dynamically access builder proxies. + * + * @param string $key + * @return mixed + * + * @throws \Exception + */ + public function __get($key) + { + if ($key === 'orWhere') { + return new HigherOrderBuilderProxy($this, $key); + } + + if (in_array($key, $this->propertyPassthru)) { + return $this->toBase()->{$key}; + } + + throw new Exception("Property [{$key}] does not exist on the Eloquent builder instance."); + } + + /** + * Dynamically handle calls into the query instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if ($method === 'macro') { + $this->localMacros[$parameters[0]] = $parameters[1]; + + return; + } + + if ($this->hasMacro($method)) { + array_unshift($parameters, $this); + + return $this->localMacros[$method](...$parameters); + } + + if (static::hasGlobalMacro($method)) { + $callable = static::$macros[$method]; + + if ($callable instanceof Closure) { + $callable = $callable->bindTo($this, static::class); + } + + return $callable(...$parameters); + } + + if ($this->hasNamedScope($method)) { + return $this->callNamedScope($method, $parameters); + } + + if (in_array($method, $this->passthru)) { + return $this->toBase()->{$method}(...$parameters); + } + + $this->forwardCallTo($this->query, $method, $parameters); + + return $this; + } + + /** + * Dynamically handle calls into the query instance. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public static function __callStatic($method, $parameters) + { + if ($method === 'macro') { + static::$macros[$parameters[0]] = $parameters[1]; + + return; + } + + if ($method === 'mixin') { + return static::registerMixin($parameters[0], $parameters[1] ?? true); + } + + if (! static::hasGlobalMacro($method)) { + static::throwBadMethodCallException($method); + } + + $callable = static::$macros[$method]; + + if ($callable instanceof Closure) { + $callable = $callable->bindTo(null, static::class); + } + + return $callable(...$parameters); + } + + /** + * Register the given mixin with the builder. + * + * @param string $mixin + * @param bool $replace + * @return void + */ + protected static function registerMixin($mixin, $replace) + { + $methods = (new ReflectionClass($mixin))->getMethods( + ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED + ); + + foreach ($methods as $method) { + if ($replace || ! static::hasGlobalMacro($method->name)) { + $method->setAccessible(true); + + static::macro($method->name, $method->invoke($mixin)); + } + } + } + + /** + * Clone the Eloquent query builder. + * + * @return static + */ + public function clone() + { + return clone $this; + } + + /** + * Force a clone of the underlying query builder when cloning. + * + * @return void + */ + public function __clone() + { + $this->query = clone $this->query; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/ArrayObject.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/ArrayObject.php new file mode 100644 index 0000000..6f1713c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/ArrayObject.php @@ -0,0 +1,41 @@ +getArrayCopy()); + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return $this->getArrayCopy(); + } + + /** + * Get the array that should be JSON serialized. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->getArrayCopy(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsArrayObject.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsArrayObject.php new file mode 100644 index 0000000..db9a21b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsArrayObject.php @@ -0,0 +1,36 @@ + json_encode($value)]; + } + + public function serialize($model, string $key, $value, array $attributes) + { + return $value->getArrayCopy(); + } + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsCollection.php new file mode 100644 index 0000000..585b6cf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsCollection.php @@ -0,0 +1,32 @@ + json_encode($value)]; + } + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsEncryptedArrayObject.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsEncryptedArrayObject.php new file mode 100644 index 0000000..cd65624 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsEncryptedArrayObject.php @@ -0,0 +1,45 @@ + Crypt::encryptString(json_encode($value))]; + } + + return null; + } + + public function serialize($model, string $key, $value, array $attributes) + { + return ! is_null($value) ? $value->getArrayCopy() : null; + } + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsEncryptedCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsEncryptedCollection.php new file mode 100644 index 0000000..4d9fee7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsEncryptedCollection.php @@ -0,0 +1,41 @@ + Crypt::encryptString(json_encode($value))]; + } + + return null; + } + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsStringable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsStringable.php new file mode 100644 index 0000000..912659f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Casts/AsStringable.php @@ -0,0 +1,32 @@ +get = $get; + $this->set = $set; + } + + /** + * Create a new attribute accessor. + * + * @param callable $get + * @return static + */ + public static function get(callable $get) + { + return new static($get); + } + + /** + * Create a new attribute mutator. + * + * @param callable $set + * @return static + */ + public static function set(callable $set) + { + return new static(null, $set); + } + + /** + * Disable object caching for the attribute. + * + * @return static + */ + public function withoutObjectCaching() + { + $this->withObjectCaching = false; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php new file mode 100755 index 0000000..cdd972c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php @@ -0,0 +1,750 @@ +getKey(); + } + + if ($key instanceof Arrayable) { + $key = $key->toArray(); + } + + if (is_array($key)) { + if ($this->isEmpty()) { + return new static; + } + + return $this->whereIn($this->first()->getKeyName(), $key); + } + + return Arr::first($this->items, function ($model) use ($key) { + return $model->getKey() == $key; + }, $default); + } + + /** + * Load a set of relationships onto the collection. + * + * @param array|string $relations + * @return $this + */ + public function load($relations) + { + if ($this->isNotEmpty()) { + if (is_string($relations)) { + $relations = func_get_args(); + } + + $query = $this->first()->newQueryWithoutRelationships()->with($relations); + + $this->items = $query->eagerLoadRelations($this->items); + } + + return $this; + } + + /** + * Load a set of aggregations over relationship's column onto the collection. + * + * @param array|string $relations + * @param string $column + * @param string $function + * @return $this + */ + public function loadAggregate($relations, $column, $function = null) + { + if ($this->isEmpty()) { + return $this; + } + + $models = $this->first()->newModelQuery() + ->whereKey($this->modelKeys()) + ->select($this->first()->getKeyName()) + ->withAggregate($relations, $column, $function) + ->get() + ->keyBy($this->first()->getKeyName()); + + $attributes = Arr::except( + array_keys($models->first()->getAttributes()), + $models->first()->getKeyName() + ); + + $this->each(function ($model) use ($models, $attributes) { + $extraAttributes = Arr::only($models->get($model->getKey())->getAttributes(), $attributes); + + $model->forceFill($extraAttributes) + ->syncOriginalAttributes($attributes) + ->mergeCasts($models->get($model->getKey())->getCasts()); + }); + + return $this; + } + + /** + * Load a set of relationship counts onto the collection. + * + * @param array|string $relations + * @return $this + */ + public function loadCount($relations) + { + return $this->loadAggregate($relations, '*', 'count'); + } + + /** + * Load a set of relationship's max column values onto the collection. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadMax($relations, $column) + { + return $this->loadAggregate($relations, $column, 'max'); + } + + /** + * Load a set of relationship's min column values onto the collection. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadMin($relations, $column) + { + return $this->loadAggregate($relations, $column, 'min'); + } + + /** + * Load a set of relationship's column summations onto the collection. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadSum($relations, $column) + { + return $this->loadAggregate($relations, $column, 'sum'); + } + + /** + * Load a set of relationship's average column values onto the collection. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadAvg($relations, $column) + { + return $this->loadAggregate($relations, $column, 'avg'); + } + + /** + * Load a set of related existences onto the collection. + * + * @param array|string $relations + * @return $this + */ + public function loadExists($relations) + { + return $this->loadAggregate($relations, '*', 'exists'); + } + + /** + * Load a set of relationships onto the collection if they are not already eager loaded. + * + * @param array|string $relations + * @return $this + */ + public function loadMissing($relations) + { + if (is_string($relations)) { + $relations = func_get_args(); + } + + foreach ($relations as $key => $value) { + if (is_numeric($key)) { + $key = $value; + } + + $segments = explode('.', explode(':', $key)[0]); + + if (Str::contains($key, ':')) { + $segments[count($segments) - 1] .= ':'.explode(':', $key)[1]; + } + + $path = []; + + foreach ($segments as $segment) { + $path[] = [$segment => $segment]; + } + + if (is_callable($value)) { + $path[count($segments) - 1][end($segments)] = $value; + } + + $this->loadMissingRelation($this, $path); + } + + return $this; + } + + /** + * Load a relationship path if it is not already eager loaded. + * + * @param \Illuminate\Database\Eloquent\Collection $models + * @param array $path + * @return void + */ + protected function loadMissingRelation(self $models, array $path) + { + $relation = array_shift($path); + + $name = explode(':', key($relation))[0]; + + if (is_string(reset($relation))) { + $relation = reset($relation); + } + + $models->filter(function ($model) use ($name) { + return ! is_null($model) && ! $model->relationLoaded($name); + })->load($relation); + + if (empty($path)) { + return; + } + + $models = $models->pluck($name)->whereNotNull(); + + if ($models->first() instanceof BaseCollection) { + $models = $models->collapse(); + } + + $this->loadMissingRelation(new static($models), $path); + } + + /** + * Load a set of relationships onto the mixed relationship collection. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorph($relation, $relations) + { + $this->pluck($relation) + ->filter() + ->groupBy(function ($model) { + return get_class($model); + }) + ->each(function ($models, $className) use ($relations) { + static::make($models)->load($relations[$className] ?? []); + }); + + return $this; + } + + /** + * Load a set of relationship counts onto the mixed relationship collection. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorphCount($relation, $relations) + { + $this->pluck($relation) + ->filter() + ->groupBy(function ($model) { + return get_class($model); + }) + ->each(function ($models, $className) use ($relations) { + static::make($models)->loadCount($relations[$className] ?? []); + }); + + return $this; + } + + /** + * Determine if a key exists in the collection. + * + * @param mixed $key + * @param mixed $operator + * @param mixed $value + * @return bool + */ + public function contains($key, $operator = null, $value = null) + { + if (func_num_args() > 1 || $this->useAsCallable($key)) { + return parent::contains(...func_get_args()); + } + + if ($key instanceof Model) { + return parent::contains(function ($model) use ($key) { + return $model->is($key); + }); + } + + return parent::contains(function ($model) use ($key) { + return $model->getKey() == $key; + }); + } + + /** + * Get the array of primary keys. + * + * @return array + */ + public function modelKeys() + { + return array_map(function ($model) { + return $model->getKey(); + }, $this->items); + } + + /** + * Merge the collection with the given items. + * + * @param \ArrayAccess|array $items + * @return static + */ + public function merge($items) + { + $dictionary = $this->getDictionary(); + + foreach ($items as $item) { + $dictionary[$item->getKey()] = $item; + } + + return new static(array_values($dictionary)); + } + + /** + * Run a map over each of the items. + * + * @param callable $callback + * @return \Illuminate\Support\Collection|static + */ + public function map(callable $callback) + { + $result = parent::map($callback); + + return $result->contains(function ($item) { + return ! $item instanceof Model; + }) ? $result->toBase() : $result; + } + + /** + * Run an associative map over each of the items. + * + * The callback should return an associative array with a single key / value pair. + * + * @param callable $callback + * @return \Illuminate\Support\Collection|static + */ + public function mapWithKeys(callable $callback) + { + $result = parent::mapWithKeys($callback); + + return $result->contains(function ($item) { + return ! $item instanceof Model; + }) ? $result->toBase() : $result; + } + + /** + * Reload a fresh model instance from the database for all the entities. + * + * @param array|string $with + * @return static + */ + public function fresh($with = []) + { + if ($this->isEmpty()) { + return new static; + } + + $model = $this->first(); + + $freshModels = $model->newQueryWithoutScopes() + ->with(is_string($with) ? func_get_args() : $with) + ->whereIn($model->getKeyName(), $this->modelKeys()) + ->get() + ->getDictionary(); + + return $this->filter(function ($model) use ($freshModels) { + return $model->exists && isset($freshModels[$model->getKey()]); + }) + ->map(function ($model) use ($freshModels) { + return $freshModels[$model->getKey()]; + }); + } + + /** + * Diff the collection with the given items. + * + * @param \ArrayAccess|array $items + * @return static + */ + public function diff($items) + { + $diff = new static; + + $dictionary = $this->getDictionary($items); + + foreach ($this->items as $item) { + if (! isset($dictionary[$item->getKey()])) { + $diff->add($item); + } + } + + return $diff; + } + + /** + * Intersect the collection with the given items. + * + * @param \ArrayAccess|array $items + * @return static + */ + public function intersect($items) + { + $intersect = new static; + + if (empty($items)) { + return $intersect; + } + + $dictionary = $this->getDictionary($items); + + foreach ($this->items as $item) { + if (isset($dictionary[$item->getKey()])) { + $intersect->add($item); + } + } + + return $intersect; + } + + /** + * Return only unique items from the collection. + * + * @param string|callable|null $key + * @param bool $strict + * @return static + */ + public function unique($key = null, $strict = false) + { + if (! is_null($key)) { + return parent::unique($key, $strict); + } + + return new static(array_values($this->getDictionary())); + } + + /** + * Returns only the models from the collection with the specified keys. + * + * @param mixed $keys + * @return static + */ + public function only($keys) + { + if (is_null($keys)) { + return new static($this->items); + } + + $dictionary = Arr::only($this->getDictionary(), $keys); + + return new static(array_values($dictionary)); + } + + /** + * Returns all models in the collection except the models with specified keys. + * + * @param mixed $keys + * @return static + */ + public function except($keys) + { + $dictionary = Arr::except($this->getDictionary(), $keys); + + return new static(array_values($dictionary)); + } + + /** + * Make the given, typically visible, attributes hidden across the entire collection. + * + * @param array|string $attributes + * @return $this + */ + public function makeHidden($attributes) + { + return $this->each->makeHidden($attributes); + } + + /** + * Make the given, typically hidden, attributes visible across the entire collection. + * + * @param array|string $attributes + * @return $this + */ + public function makeVisible($attributes) + { + return $this->each->makeVisible($attributes); + } + + /** + * Append an attribute across the entire collection. + * + * @param array|string $attributes + * @return $this + */ + public function append($attributes) + { + return $this->each->append($attributes); + } + + /** + * Get a dictionary keyed by primary keys. + * + * @param \ArrayAccess|array|null $items + * @return array + */ + public function getDictionary($items = null) + { + $items = is_null($items) ? $this->items : $items; + + $dictionary = []; + + foreach ($items as $value) { + $dictionary[$value->getKey()] = $value; + } + + return $dictionary; + } + + /** + * The following methods are intercepted to always return base collections. + */ + + /** + * Get an array with the values of a given key. + * + * @param string|array $value + * @param string|null $key + * @return \Illuminate\Support\Collection + */ + public function pluck($value, $key = null) + { + return $this->toBase()->pluck($value, $key); + } + + /** + * Get the keys of the collection items. + * + * @return \Illuminate\Support\Collection + */ + public function keys() + { + return $this->toBase()->keys(); + } + + /** + * Zip the collection together with one or more arrays. + * + * @param mixed ...$items + * @return \Illuminate\Support\Collection + */ + public function zip($items) + { + return $this->toBase()->zip(...func_get_args()); + } + + /** + * Collapse the collection of items into a single array. + * + * @return \Illuminate\Support\Collection + */ + public function collapse() + { + return $this->toBase()->collapse(); + } + + /** + * Get a flattened array of the items in the collection. + * + * @param int $depth + * @return \Illuminate\Support\Collection + */ + public function flatten($depth = INF) + { + return $this->toBase()->flatten($depth); + } + + /** + * Flip the items in the collection. + * + * @return \Illuminate\Support\Collection + */ + public function flip() + { + return $this->toBase()->flip(); + } + + /** + * Pad collection to the specified length with a value. + * + * @param int $size + * @param mixed $value + * @return \Illuminate\Support\Collection + */ + public function pad($size, $value) + { + return $this->toBase()->pad($size, $value); + } + + /** + * Get the comparison function to detect duplicates. + * + * @param bool $strict + * @return \Closure + */ + protected function duplicateComparator($strict) + { + return function ($a, $b) { + return $a->is($b); + }; + } + + /** + * Get the type of the entities being queued. + * + * @return string|null + * + * @throws \LogicException + */ + public function getQueueableClass() + { + if ($this->isEmpty()) { + return; + } + + $class = get_class($this->first()); + + $this->each(function ($model) use ($class) { + if (get_class($model) !== $class) { + throw new LogicException('Queueing collections with multiple model types is not supported.'); + } + }); + + return $class; + } + + /** + * Get the identifiers for all of the entities. + * + * @return array + */ + public function getQueueableIds() + { + if ($this->isEmpty()) { + return []; + } + + return $this->first() instanceof QueueableEntity + ? $this->map->getQueueableId()->all() + : $this->modelKeys(); + } + + /** + * Get the relationships of the entities being queued. + * + * @return array + */ + public function getQueueableRelations() + { + if ($this->isEmpty()) { + return []; + } + + $relations = $this->map->getQueueableRelations()->all(); + + if (count($relations) === 0 || $relations === [[]]) { + return []; + } elseif (count($relations) === 1) { + return reset($relations); + } else { + return array_intersect(...array_values($relations)); + } + } + + /** + * Get the connection of the entities being queued. + * + * @return string|null + * + * @throws \LogicException + */ + public function getQueueableConnection() + { + if ($this->isEmpty()) { + return; + } + + $connection = $this->first()->getConnectionName(); + + $this->each(function ($model) use ($connection) { + if ($model->getConnectionName() !== $connection) { + throw new LogicException('Queueing collections with multiple model connections is not supported.'); + } + }); + + return $connection; + } + + /** + * Get the Eloquent query builder from the collection. + * + * @return \Illuminate\Database\Eloquent\Builder + * + * @throws \LogicException + */ + public function toQuery() + { + $model = $this->first(); + + if (! $model) { + throw new LogicException('Unable to create query for empty collection.'); + } + + $class = get_class($model); + + if ($this->filter(function ($model) use ($class) { + return ! $model instanceof $class; + })->isNotEmpty()) { + throw new LogicException('Unable to create query for collection with mixed types.'); + } + + return $model->newModelQuery()->whereKey($this->modelKeys()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php new file mode 100644 index 0000000..3e85fb9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php @@ -0,0 +1,257 @@ +fillable; + } + + /** + * Set the fillable attributes for the model. + * + * @param array $fillable + * @return $this + */ + public function fillable(array $fillable) + { + $this->fillable = $fillable; + + return $this; + } + + /** + * Merge new fillable attributes with existing fillable attributes on the model. + * + * @param array $fillable + * @return $this + */ + public function mergeFillable(array $fillable) + { + $this->fillable = array_merge($this->fillable, $fillable); + + return $this; + } + + /** + * Get the guarded attributes for the model. + * + * @return array + */ + public function getGuarded() + { + return $this->guarded === false + ? [] + : $this->guarded; + } + + /** + * Set the guarded attributes for the model. + * + * @param array $guarded + * @return $this + */ + public function guard(array $guarded) + { + $this->guarded = $guarded; + + return $this; + } + + /** + * Merge new guarded attributes with existing guarded attributes on the model. + * + * @param array $guarded + * @return $this + */ + public function mergeGuarded(array $guarded) + { + $this->guarded = array_merge($this->guarded, $guarded); + + return $this; + } + + /** + * Disable all mass assignable restrictions. + * + * @param bool $state + * @return void + */ + public static function unguard($state = true) + { + static::$unguarded = $state; + } + + /** + * Enable the mass assignment restrictions. + * + * @return void + */ + public static function reguard() + { + static::$unguarded = false; + } + + /** + * Determine if the current state is "unguarded". + * + * @return bool + */ + public static function isUnguarded() + { + return static::$unguarded; + } + + /** + * Run the given callable while being unguarded. + * + * @param callable $callback + * @return mixed + */ + public static function unguarded(callable $callback) + { + if (static::$unguarded) { + return $callback(); + } + + static::unguard(); + + try { + return $callback(); + } finally { + static::reguard(); + } + } + + /** + * Determine if the given attribute may be mass assigned. + * + * @param string $key + * @return bool + */ + public function isFillable($key) + { + if (static::$unguarded) { + return true; + } + + // If the key is in the "fillable" array, we can of course assume that it's + // a fillable attribute. Otherwise, we will check the guarded array when + // we need to determine if the attribute is black-listed on the model. + if (in_array($key, $this->getFillable())) { + return true; + } + + // If the attribute is explicitly listed in the "guarded" array then we can + // return false immediately. This means this attribute is definitely not + // fillable and there is no point in going any further in this method. + if ($this->isGuarded($key)) { + return false; + } + + return empty($this->getFillable()) && + strpos($key, '.') === false && + ! Str::startsWith($key, '_'); + } + + /** + * Determine if the given key is guarded. + * + * @param string $key + * @return bool + */ + public function isGuarded($key) + { + if (empty($this->getGuarded())) { + return false; + } + + return $this->getGuarded() == ['*'] || + ! empty(preg_grep('/^'.preg_quote($key).'$/i', $this->getGuarded())) || + ! $this->isGuardableColumn($key); + } + + /** + * Determine if the given column is a valid, guardable column. + * + * @param string $key + * @return bool + */ + protected function isGuardableColumn($key) + { + if (! isset(static::$guardableColumns[get_class($this)])) { + $columns = $this->getConnection() + ->getSchemaBuilder() + ->getColumnListing($this->getTable()); + + if (empty($columns)) { + return true; + } + static::$guardableColumns[get_class($this)] = $columns; + } + + return in_array($key, static::$guardableColumns[get_class($this)]); + } + + /** + * Determine if the model is totally guarded. + * + * @return bool + */ + public function totallyGuarded() + { + return count($this->getFillable()) === 0 && $this->getGuarded() == ['*']; + } + + /** + * Get the fillable attributes of a given array. + * + * @param array $attributes + * @return array + */ + protected function fillableFromArray(array $attributes) + { + if (count($this->getFillable()) > 0 && ! static::$unguarded) { + return array_intersect_key($attributes, array_flip($this->getFillable())); + } + + return $attributes; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php new file mode 100644 index 0000000..95d07e7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -0,0 +1,2129 @@ +addDateAttributesToArray( + $attributes = $this->getArrayableAttributes() + ); + + $attributes = $this->addMutatedAttributesToArray( + $attributes, $mutatedAttributes = $this->getMutatedAttributes() + ); + + // Next we will handle any casts that have been setup for this model and cast + // the values to their appropriate type. If the attribute has a mutator we + // will not perform the cast on those attributes to avoid any confusion. + $attributes = $this->addCastAttributesToArray( + $attributes, $mutatedAttributes + ); + + // Here we will grab all of the appended, calculated attributes to this model + // as these attributes are not really in the attributes array, but are run + // when we need to array or JSON the model for convenience to the coder. + foreach ($this->getArrayableAppends() as $key) { + $attributes[$key] = $this->mutateAttributeForArray($key, null); + } + + return $attributes; + } + + /** + * Add the date attributes to the attributes array. + * + * @param array $attributes + * @return array + */ + protected function addDateAttributesToArray(array $attributes) + { + foreach ($this->getDates() as $key) { + if (! isset($attributes[$key])) { + continue; + } + + $attributes[$key] = $this->serializeDate( + $this->asDateTime($attributes[$key]) + ); + } + + return $attributes; + } + + /** + * Add the mutated attributes to the attributes array. + * + * @param array $attributes + * @param array $mutatedAttributes + * @return array + */ + protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) + { + foreach ($mutatedAttributes as $key) { + // We want to spin through all the mutated attributes for this model and call + // the mutator for the attribute. We cache off every mutated attributes so + // we don't have to constantly check on attributes that actually change. + if (! array_key_exists($key, $attributes)) { + continue; + } + + // Next, we will call the mutator for this attribute so that we can get these + // mutated attribute's actual values. After we finish mutating each of the + // attributes we will return this final array of the mutated attributes. + $attributes[$key] = $this->mutateAttributeForArray( + $key, $attributes[$key] + ); + } + + return $attributes; + } + + /** + * Add the casted attributes to the attributes array. + * + * @param array $attributes + * @param array $mutatedAttributes + * @return array + */ + protected function addCastAttributesToArray(array $attributes, array $mutatedAttributes) + { + foreach ($this->getCasts() as $key => $value) { + if (! array_key_exists($key, $attributes) || + in_array($key, $mutatedAttributes)) { + continue; + } + + // Here we will cast the attribute. Then, if the cast is a date or datetime cast + // then we will serialize the date for the array. This will convert the dates + // to strings based on the date format specified for these Eloquent models. + $attributes[$key] = $this->castAttribute( + $key, $attributes[$key] + ); + + // If the attribute cast was a date or a datetime, we will serialize the date as + // a string. This allows the developers to customize how dates are serialized + // into an array without affecting how they are persisted into the storage. + if ($attributes[$key] && in_array($value, ['date', 'datetime', 'immutable_date', 'immutable_datetime'])) { + $attributes[$key] = $this->serializeDate($attributes[$key]); + } + + if ($attributes[$key] && ($this->isCustomDateTimeCast($value) || + $this->isImmutableCustomDateTimeCast($value))) { + $attributes[$key] = $attributes[$key]->format(explode(':', $value, 2)[1]); + } + + if ($attributes[$key] && $attributes[$key] instanceof DateTimeInterface && + $this->isClassCastable($key)) { + $attributes[$key] = $this->serializeDate($attributes[$key]); + } + + if ($attributes[$key] && $this->isClassSerializable($key)) { + $attributes[$key] = $this->serializeClassCastableAttribute($key, $attributes[$key]); + } + + if ($this->isEnumCastable($key) && (! ($attributes[$key] ?? null) instanceof Arrayable)) { + $attributes[$key] = isset($attributes[$key]) ? $attributes[$key]->value : null; + } + + if ($attributes[$key] instanceof Arrayable) { + $attributes[$key] = $attributes[$key]->toArray(); + } + } + + return $attributes; + } + + /** + * Get an attribute array of all arrayable attributes. + * + * @return array + */ + protected function getArrayableAttributes() + { + return $this->getArrayableItems($this->getAttributes()); + } + + /** + * Get all of the appendable values that are arrayable. + * + * @return array + */ + protected function getArrayableAppends() + { + if (! count($this->appends)) { + return []; + } + + return $this->getArrayableItems( + array_combine($this->appends, $this->appends) + ); + } + + /** + * Get the model's relationships in array form. + * + * @return array + */ + public function relationsToArray() + { + $attributes = []; + + foreach ($this->getArrayableRelations() as $key => $value) { + // If the values implements the Arrayable interface we can just call this + // toArray method on the instances which will convert both models and + // collections to their proper array form and we'll set the values. + if ($value instanceof Arrayable) { + $relation = $value->toArray(); + } + + // If the value is null, we'll still go ahead and set it in this list of + // attributes since null is used to represent empty relationships if + // if it a has one or belongs to type relationships on the models. + elseif (is_null($value)) { + $relation = $value; + } + + // If the relationships snake-casing is enabled, we will snake case this + // key so that the relation attribute is snake cased in this returned + // array to the developers, making this consistent with attributes. + if (static::$snakeAttributes) { + $key = Str::snake($key); + } + + // If the relation value has been set, we will set it on this attributes + // list for returning. If it was not arrayable or null, we'll not set + // the value on the array because it is some type of invalid value. + if (isset($relation) || is_null($value)) { + $attributes[$key] = $relation; + } + + unset($relation); + } + + return $attributes; + } + + /** + * Get an attribute array of all arrayable relations. + * + * @return array + */ + protected function getArrayableRelations() + { + return $this->getArrayableItems($this->relations); + } + + /** + * Get an attribute array of all arrayable values. + * + * @param array $values + * @return array + */ + protected function getArrayableItems(array $values) + { + if (count($this->getVisible()) > 0) { + $values = array_intersect_key($values, array_flip($this->getVisible())); + } + + if (count($this->getHidden()) > 0) { + $values = array_diff_key($values, array_flip($this->getHidden())); + } + + return $values; + } + + /** + * Get an attribute from the model. + * + * @param string $key + * @return mixed + */ + public function getAttribute($key) + { + if (! $key) { + return; + } + + // If the attribute exists in the attribute array or has a "get" mutator we will + // get the attribute's value. Otherwise, we will proceed as if the developers + // are asking for a relationship's value. This covers both types of values. + if (array_key_exists($key, $this->attributes) || + array_key_exists($key, $this->casts) || + $this->hasGetMutator($key) || + $this->hasAttributeMutator($key) || + $this->isClassCastable($key)) { + return $this->getAttributeValue($key); + } + + // Here we will determine if the model base class itself contains this given key + // since we don't want to treat any of those methods as relationships because + // they are all intended as helper methods and none of these are relations. + if (method_exists(self::class, $key)) { + return; + } + + return $this->getRelationValue($key); + } + + /** + * Get a plain attribute (not a relationship). + * + * @param string $key + * @return mixed + */ + public function getAttributeValue($key) + { + return $this->transformModelValue($key, $this->getAttributeFromArray($key)); + } + + /** + * Get an attribute from the $attributes array. + * + * @param string $key + * @return mixed + */ + protected function getAttributeFromArray($key) + { + return $this->getAttributes()[$key] ?? null; + } + + /** + * Get a relationship. + * + * @param string $key + * @return mixed + */ + public function getRelationValue($key) + { + // If the key already exists in the relationships array, it just means the + // relationship has already been loaded, so we'll just return it out of + // here because there is no need to query within the relations twice. + if ($this->relationLoaded($key)) { + return $this->relations[$key]; + } + + if (! $this->isRelation($key)) { + return; + } + + if ($this->preventsLazyLoading) { + $this->handleLazyLoadingViolation($key); + } + + // If the "attribute" exists as a method on the model, we will just assume + // it is a relationship and will load and return results from the query + // and hydrate the relationship's value on the "relationships" array. + return $this->getRelationshipFromMethod($key); + } + + /** + * Determine if the given key is a relationship method on the model. + * + * @param string $key + * @return bool + */ + public function isRelation($key) + { + if ($this->hasAttributeMutator($key)) { + return false; + } + + return method_exists($this, $key) || + (static::$relationResolvers[get_class($this)][$key] ?? null); + } + + /** + * Handle a lazy loading violation. + * + * @param string $key + * @return mixed + */ + protected function handleLazyLoadingViolation($key) + { + if (isset(static::$lazyLoadingViolationCallback)) { + return call_user_func(static::$lazyLoadingViolationCallback, $this, $key); + } + + if (! $this->exists || $this->wasRecentlyCreated) { + return; + } + + throw new LazyLoadingViolationException($this, $key); + } + + /** + * Get a relationship value from a method. + * + * @param string $method + * @return mixed + * + * @throws \LogicException + */ + protected function getRelationshipFromMethod($method) + { + $relation = $this->$method(); + + if (! $relation instanceof Relation) { + if (is_null($relation)) { + throw new LogicException(sprintf( + '%s::%s must return a relationship instance, but "null" was returned. Was the "return" keyword used?', static::class, $method + )); + } + + throw new LogicException(sprintf( + '%s::%s must return a relationship instance.', static::class, $method + )); + } + + return tap($relation->getResults(), function ($results) use ($method) { + $this->setRelation($method, $results); + }); + } + + /** + * Determine if a get mutator exists for an attribute. + * + * @param string $key + * @return bool + */ + public function hasGetMutator($key) + { + return method_exists($this, 'get'.Str::studly($key).'Attribute'); + } + + /** + * Determine if a "Attribute" return type marked mutator exists for an attribute. + * + * @param string $key + * @return bool + */ + public function hasAttributeMutator($key) + { + if (isset(static::$attributeMutatorCache[get_class($this)][$key])) { + return static::$attributeMutatorCache[get_class($this)][$key]; + } + + if (! method_exists($this, $method = Str::camel($key))) { + return static::$attributeMutatorCache[get_class($this)][$key] = false; + } + + $returnType = (new ReflectionMethod($this, $method))->getReturnType(); + + return static::$attributeMutatorCache[get_class($this)][$key] = $returnType && + $returnType instanceof ReflectionNamedType && + $returnType->getName() === Attribute::class; + } + + /** + * Determine if a "Attribute" return type marked get mutator exists for an attribute. + * + * @param string $key + * @return bool + */ + public function hasAttributeGetMutator($key) + { + if (isset(static::$getAttributeMutatorCache[get_class($this)][$key])) { + return static::$getAttributeMutatorCache[get_class($this)][$key]; + } + + if (! $this->hasAttributeMutator($key)) { + return static::$getAttributeMutatorCache[get_class($this)][$key] = false; + } + + return static::$getAttributeMutatorCache[get_class($this)][$key] = is_callable($this->{Str::camel($key)}()->get); + } + + /** + * Get the value of an attribute using its mutator. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function mutateAttribute($key, $value) + { + return $this->{'get'.Str::studly($key).'Attribute'}($value); + } + + /** + * Get the value of an "Attribute" return type marked attribute using its mutator. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function mutateAttributeMarkedAttribute($key, $value) + { + if (isset($this->attributeCastCache[$key])) { + return $this->attributeCastCache[$key]; + } + + $attribute = $this->{Str::camel($key)}(); + + $value = call_user_func($attribute->get ?: function ($value) { + return $value; + }, $value, $this->attributes); + + if (! is_object($value) || ! $attribute->withObjectCaching) { + unset($this->attributeCastCache[$key]); + } else { + $this->attributeCastCache[$key] = $value; + } + + return $value; + } + + /** + * Get the value of an attribute using its mutator for array conversion. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function mutateAttributeForArray($key, $value) + { + if ($this->isClassCastable($key)) { + $value = $this->getClassCastableAttributeValue($key, $value); + } elseif (isset(static::$getAttributeMutatorCache[get_class($this)][$key]) && + static::$getAttributeMutatorCache[get_class($this)][$key] === true) { + $value = $this->mutateAttributeMarkedAttribute($key, $value); + + $value = $value instanceof DateTimeInterface + ? $this->serializeDate($value) + : $value; + } else { + $value = $this->mutateAttribute($key, $value); + } + + return $value instanceof Arrayable ? $value->toArray() : $value; + } + + /** + * Merge new casts with existing casts on the model. + * + * @param array $casts + * @return $this + */ + public function mergeCasts($casts) + { + $this->casts = array_merge($this->casts, $casts); + + return $this; + } + + /** + * Cast an attribute to a native PHP type. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function castAttribute($key, $value) + { + $castType = $this->getCastType($key); + + if (is_null($value) && in_array($castType, static::$primitiveCastTypes)) { + return $value; + } + + // If the key is one of the encrypted castable types, we'll first decrypt + // the value and update the cast type so we may leverage the following + // logic for casting this value to any additionally specified types. + if ($this->isEncryptedCastable($key)) { + $value = $this->fromEncryptedString($value); + + $castType = Str::after($castType, 'encrypted:'); + } + + switch ($castType) { + case 'int': + case 'integer': + return (int) $value; + case 'real': + case 'float': + case 'double': + return $this->fromFloat($value); + case 'decimal': + return $this->asDecimal($value, explode(':', $this->getCasts()[$key], 2)[1]); + case 'string': + return (string) $value; + case 'bool': + case 'boolean': + return (bool) $value; + case 'object': + return $this->fromJson($value, true); + case 'array': + case 'json': + return $this->fromJson($value); + case 'collection': + return new BaseCollection($this->fromJson($value)); + case 'date': + return $this->asDate($value); + case 'datetime': + case 'custom_datetime': + return $this->asDateTime($value); + case 'immutable_date': + return $this->asDate($value)->toImmutable(); + case 'immutable_custom_datetime': + case 'immutable_datetime': + return $this->asDateTime($value)->toImmutable(); + case 'timestamp': + return $this->asTimestamp($value); + } + + if ($this->isEnumCastable($key)) { + return $this->getEnumCastableAttributeValue($key, $value); + } + + if ($this->isClassCastable($key)) { + return $this->getClassCastableAttributeValue($key, $value); + } + + return $value; + } + + /** + * Cast the given attribute using a custom cast class. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function getClassCastableAttributeValue($key, $value) + { + if (isset($this->classCastCache[$key])) { + return $this->classCastCache[$key]; + } else { + $caster = $this->resolveCasterClass($key); + + $value = $caster instanceof CastsInboundAttributes + ? $value + : $caster->get($this, $key, $value, $this->attributes); + + if ($caster instanceof CastsInboundAttributes || ! is_object($value)) { + unset($this->classCastCache[$key]); + } else { + $this->classCastCache[$key] = $value; + } + + return $value; + } + } + + /** + * Cast the given attribute to an enum. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function getEnumCastableAttributeValue($key, $value) + { + if (is_null($value)) { + return; + } + + $castType = $this->getCasts()[$key]; + + if ($value instanceof $castType) { + return $value; + } + + return $castType::from($value); + } + + /** + * Get the type of cast for a model attribute. + * + * @param string $key + * @return string + */ + protected function getCastType($key) + { + if ($this->isCustomDateTimeCast($this->getCasts()[$key])) { + return 'custom_datetime'; + } + + if ($this->isImmutableCustomDateTimeCast($this->getCasts()[$key])) { + return 'immutable_custom_datetime'; + } + + if ($this->isDecimalCast($this->getCasts()[$key])) { + return 'decimal'; + } + + return trim(strtolower($this->getCasts()[$key])); + } + + /** + * Increment or decrement the given attribute using the custom cast class. + * + * @param string $method + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function deviateClassCastableAttribute($method, $key, $value) + { + return $this->resolveCasterClass($key)->{$method}( + $this, $key, $value, $this->attributes + ); + } + + /** + * Serialize the given attribute using the custom cast class. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function serializeClassCastableAttribute($key, $value) + { + return $this->resolveCasterClass($key)->serialize( + $this, $key, $value, $this->attributes + ); + } + + /** + * Determine if the cast type is a custom date time cast. + * + * @param string $cast + * @return bool + */ + protected function isCustomDateTimeCast($cast) + { + return strncmp($cast, 'date:', 5) === 0 || + strncmp($cast, 'datetime:', 9) === 0; + } + + /** + * Determine if the cast type is an immutable custom date time cast. + * + * @param string $cast + * @return bool + */ + protected function isImmutableCustomDateTimeCast($cast) + { + return strncmp($cast, 'immutable_date:', 15) === 0 || + strncmp($cast, 'immutable_datetime:', 19) === 0; + } + + /** + * Determine if the cast type is a decimal cast. + * + * @param string $cast + * @return bool + */ + protected function isDecimalCast($cast) + { + return strncmp($cast, 'decimal:', 8) === 0; + } + + /** + * Set a given attribute on the model. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + public function setAttribute($key, $value) + { + // First we will check for the presence of a mutator for the set operation + // which simply lets the developers tweak the attribute as it is set on + // this model, such as "json_encoding" a listing of data for storage. + if ($this->hasSetMutator($key)) { + return $this->setMutatedAttributeValue($key, $value); + } elseif ($this->hasAttributeSetMutator($key)) { + return $this->setAttributeMarkedMutatedAttributeValue($key, $value); + } + + // If an attribute is listed as a "date", we'll convert it from a DateTime + // instance into a form proper for storage on the database tables using + // the connection grammar's date format. We will auto set the values. + elseif ($value && $this->isDateAttribute($key)) { + $value = $this->fromDateTime($value); + } + + if ($this->isEnumCastable($key)) { + $this->setEnumCastableAttribute($key, $value); + + return $this; + } + + if ($this->isClassCastable($key)) { + $this->setClassCastableAttribute($key, $value); + + return $this; + } + + if (! is_null($value) && $this->isJsonCastable($key)) { + $value = $this->castAttributeAsJson($key, $value); + } + + // If this attribute contains a JSON ->, we'll set the proper value in the + // attribute's underlying array. This takes care of properly nesting an + // attribute in the array's value in the case of deeply nested items. + if (Str::contains($key, '->')) { + return $this->fillJsonAttribute($key, $value); + } + + if (! is_null($value) && $this->isEncryptedCastable($key)) { + $value = $this->castAttributeAsEncryptedString($key, $value); + } + + $this->attributes[$key] = $value; + + return $this; + } + + /** + * Determine if a set mutator exists for an attribute. + * + * @param string $key + * @return bool + */ + public function hasSetMutator($key) + { + return method_exists($this, 'set'.Str::studly($key).'Attribute'); + } + + /** + * Determine if an "Attribute" return type marked set mutator exists for an attribute. + * + * @param string $key + * @return bool + */ + public function hasAttributeSetMutator($key) + { + $class = get_class($this); + + if (isset(static::$setAttributeMutatorCache[$class][$key])) { + return static::$setAttributeMutatorCache[$class][$key]; + } + + if (! method_exists($this, $method = Str::camel($key))) { + return static::$setAttributeMutatorCache[$class][$key] = false; + } + + $returnType = (new ReflectionMethod($this, $method))->getReturnType(); + + return static::$setAttributeMutatorCache[$class][$key] = $returnType && + $returnType instanceof ReflectionNamedType && + $returnType->getName() === Attribute::class && + is_callable($this->{$method}()->set); + } + + /** + * Set the value of an attribute using its mutator. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function setMutatedAttributeValue($key, $value) + { + return $this->{'set'.Str::studly($key).'Attribute'}($value); + } + + /** + * Set the value of a "Attribute" return type marked attribute using its mutator. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function setAttributeMarkedMutatedAttributeValue($key, $value) + { + $attribute = $this->{Str::camel($key)}(); + + $callback = $attribute->set ?: function ($value) use ($key) { + $this->attributes[$key] = $value; + }; + + $this->attributes = array_merge( + $this->attributes, + $this->normalizeCastClassResponse( + $key, call_user_func($callback, $value, $this->attributes) + ) + ); + + if (! is_object($value) || ! $attribute->withObjectCaching) { + unset($this->attributeCastCache[$key]); + } else { + $this->attributeCastCache[$key] = $value; + } + } + + /** + * Determine if the given attribute is a date or date castable. + * + * @param string $key + * @return bool + */ + protected function isDateAttribute($key) + { + return in_array($key, $this->getDates(), true) || + $this->isDateCastable($key); + } + + /** + * Set a given JSON attribute on the model. + * + * @param string $key + * @param mixed $value + * @return $this + */ + public function fillJsonAttribute($key, $value) + { + [$key, $path] = explode('->', $key, 2); + + $value = $this->asJson($this->getArrayAttributeWithValue( + $path, $key, $value + )); + + $this->attributes[$key] = $this->isEncryptedCastable($key) + ? $this->castAttributeAsEncryptedString($key, $value) + : $value; + + return $this; + } + + /** + * Set the value of a class castable attribute. + * + * @param string $key + * @param mixed $value + * @return void + */ + protected function setClassCastableAttribute($key, $value) + { + $caster = $this->resolveCasterClass($key); + + if (is_null($value)) { + $this->attributes = array_merge($this->attributes, array_map( + function () { + }, + $this->normalizeCastClassResponse($key, $caster->set( + $this, $key, $this->{$key}, $this->attributes + )) + )); + } else { + $this->attributes = array_merge( + $this->attributes, + $this->normalizeCastClassResponse($key, $caster->set( + $this, $key, $value, $this->attributes + )) + ); + } + + if ($caster instanceof CastsInboundAttributes || ! is_object($value)) { + unset($this->classCastCache[$key]); + } else { + $this->classCastCache[$key] = $value; + } + } + + /** + * Set the value of an enum castable attribute. + * + * @param string $key + * @param \BackedEnum $value + * @return void + */ + protected function setEnumCastableAttribute($key, $value) + { + $enumClass = $this->getCasts()[$key]; + + if (! isset($value)) { + $this->attributes[$key] = null; + } elseif ($value instanceof $enumClass) { + $this->attributes[$key] = $value->value; + } else { + $this->attributes[$key] = $enumClass::from($value)->value; + } + } + + /** + * Get an array attribute with the given key and value set. + * + * @param string $path + * @param string $key + * @param mixed $value + * @return $this + */ + protected function getArrayAttributeWithValue($path, $key, $value) + { + return tap($this->getArrayAttributeByKey($key), function (&$array) use ($path, $value) { + Arr::set($array, str_replace('->', '.', $path), $value); + }); + } + + /** + * Get an array attribute or return an empty array if it is not set. + * + * @param string $key + * @return array + */ + protected function getArrayAttributeByKey($key) + { + if (! isset($this->attributes[$key])) { + return []; + } + + return $this->fromJson( + $this->isEncryptedCastable($key) + ? $this->fromEncryptedString($this->attributes[$key]) + : $this->attributes[$key] + ); + } + + /** + * Cast the given attribute to JSON. + * + * @param string $key + * @param mixed $value + * @return string + */ + protected function castAttributeAsJson($key, $value) + { + $value = $this->asJson($value); + + if ($value === false) { + throw JsonEncodingException::forAttribute( + $this, $key, json_last_error_msg() + ); + } + + return $value; + } + + /** + * Encode the given value as JSON. + * + * @param mixed $value + * @return string + */ + protected function asJson($value) + { + return json_encode($value); + } + + /** + * Decode the given JSON back into an array or object. + * + * @param string $value + * @param bool $asObject + * @return mixed + */ + public function fromJson($value, $asObject = false) + { + return json_decode($value, ! $asObject); + } + + /** + * Decrypt the given encrypted string. + * + * @param string $value + * @return mixed + */ + public function fromEncryptedString($value) + { + return (static::$encrypter ?? Crypt::getFacadeRoot())->decrypt($value, false); + } + + /** + * Cast the given attribute to an encrypted string. + * + * @param string $key + * @param mixed $value + * @return string + */ + protected function castAttributeAsEncryptedString($key, $value) + { + return (static::$encrypter ?? Crypt::getFacadeRoot())->encrypt($value, false); + } + + /** + * Set the encrypter instance that will be used to encrypt attributes. + * + * @param \Illuminate\Contracts\Encryption\Encrypter $encrypter + * @return void + */ + public static function encryptUsing($encrypter) + { + static::$encrypter = $encrypter; + } + + /** + * Decode the given float. + * + * @param mixed $value + * @return mixed + */ + public function fromFloat($value) + { + switch ((string) $value) { + case 'Infinity': + return INF; + case '-Infinity': + return -INF; + case 'NaN': + return NAN; + default: + return (float) $value; + } + } + + /** + * Return a decimal as string. + * + * @param float $value + * @param int $decimals + * @return string + */ + protected function asDecimal($value, $decimals) + { + return number_format($value, $decimals, '.', ''); + } + + /** + * Return a timestamp as DateTime object with time set to 00:00:00. + * + * @param mixed $value + * @return \Illuminate\Support\Carbon + */ + protected function asDate($value) + { + return $this->asDateTime($value)->startOfDay(); + } + + /** + * Return a timestamp as DateTime object. + * + * @param mixed $value + * @return \Illuminate\Support\Carbon + */ + protected function asDateTime($value) + { + // If this value is already a Carbon instance, we shall just return it as is. + // This prevents us having to re-instantiate a Carbon instance when we know + // it already is one, which wouldn't be fulfilled by the DateTime check. + if ($value instanceof CarbonInterface) { + return Date::instance($value); + } + + // If the value is already a DateTime instance, we will just skip the rest of + // these checks since they will be a waste of time, and hinder performance + // when checking the field. We will just return the DateTime right away. + if ($value instanceof DateTimeInterface) { + return Date::parse( + $value->format('Y-m-d H:i:s.u'), $value->getTimezone() + ); + } + + // If this value is an integer, we will assume it is a UNIX timestamp's value + // and format a Carbon object from this timestamp. This allows flexibility + // when defining your date fields as they might be UNIX timestamps here. + if (is_numeric($value)) { + return Date::createFromTimestamp($value); + } + + // If the value is in simply year, month, day format, we will instantiate the + // Carbon instances from that format. Again, this provides for simple date + // fields on the database, while still supporting Carbonized conversion. + if ($this->isStandardDateFormat($value)) { + return Date::instance(Carbon::createFromFormat('Y-m-d', $value)->startOfDay()); + } + + $format = $this->getDateFormat(); + + // Finally, we will just assume this date is in the format used by default on + // the database connection and use that format to create the Carbon object + // that is returned back out to the developers after we convert it here. + try { + $date = Date::createFromFormat($format, $value); + } catch (InvalidArgumentException $e) { + $date = false; + } + + return $date ?: Date::parse($value); + } + + /** + * Determine if the given value is a standard date format. + * + * @param string $value + * @return bool + */ + protected function isStandardDateFormat($value) + { + return preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value); + } + + /** + * Convert a DateTime to a storable string. + * + * @param mixed $value + * @return string|null + */ + public function fromDateTime($value) + { + return empty($value) ? $value : $this->asDateTime($value)->format( + $this->getDateFormat() + ); + } + + /** + * Return a timestamp as unix timestamp. + * + * @param mixed $value + * @return int + */ + protected function asTimestamp($value) + { + return $this->asDateTime($value)->getTimestamp(); + } + + /** + * Prepare a date for array / JSON serialization. + * + * @param \DateTimeInterface $date + * @return string + */ + protected function serializeDate(DateTimeInterface $date) + { + return $date instanceof \DateTimeImmutable ? + CarbonImmutable::instance($date)->toJSON() : + Carbon::instance($date)->toJSON(); + } + + /** + * Get the attributes that should be converted to dates. + * + * @return array + */ + public function getDates() + { + if (! $this->usesTimestamps()) { + return $this->dates; + } + + $defaults = [ + $this->getCreatedAtColumn(), + $this->getUpdatedAtColumn(), + ]; + + return array_unique(array_merge($this->dates, $defaults)); + } + + /** + * Get the format for database stored dates. + * + * @return string + */ + public function getDateFormat() + { + return $this->dateFormat ?: $this->getConnection()->getQueryGrammar()->getDateFormat(); + } + + /** + * Set the date format used by the model. + * + * @param string $format + * @return $this + */ + public function setDateFormat($format) + { + $this->dateFormat = $format; + + return $this; + } + + /** + * Determine whether an attribute should be cast to a native type. + * + * @param string $key + * @param array|string|null $types + * @return bool + */ + public function hasCast($key, $types = null) + { + if (array_key_exists($key, $this->getCasts())) { + return $types ? in_array($this->getCastType($key), (array) $types, true) : true; + } + + return false; + } + + /** + * Get the casts array. + * + * @return array + */ + public function getCasts() + { + if ($this->getIncrementing()) { + return array_merge([$this->getKeyName() => $this->getKeyType()], $this->casts); + } + + return $this->casts; + } + + /** + * Determine whether a value is Date / DateTime castable for inbound manipulation. + * + * @param string $key + * @return bool + */ + protected function isDateCastable($key) + { + return $this->hasCast($key, ['date', 'datetime', 'immutable_date', 'immutable_datetime']); + } + + /** + * Determine whether a value is Date / DateTime custom-castable for inbound manipulation. + * + * @param string $key + * @return bool + */ + protected function isDateCastableWithCustomFormat($key) + { + return $this->hasCast($key, ['custom_datetime', 'immutable_custom_datetime']); + } + + /** + * Determine whether a value is JSON castable for inbound manipulation. + * + * @param string $key + * @return bool + */ + protected function isJsonCastable($key) + { + return $this->hasCast($key, ['array', 'json', 'object', 'collection', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']); + } + + /** + * Determine whether a value is an encrypted castable for inbound manipulation. + * + * @param string $key + * @return bool + */ + protected function isEncryptedCastable($key) + { + return $this->hasCast($key, ['encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']); + } + + /** + * Determine if the given key is cast using a custom class. + * + * @param string $key + * @return bool + * + * @throws \Illuminate\Database\Eloquent\InvalidCastException + */ + protected function isClassCastable($key) + { + if (! array_key_exists($key, $this->getCasts())) { + return false; + } + + $castType = $this->parseCasterClass($this->getCasts()[$key]); + + if (in_array($castType, static::$primitiveCastTypes)) { + return false; + } + + if (class_exists($castType)) { + return true; + } + + throw new InvalidCastException($this->getModel(), $key, $castType); + } + + /** + * Determine if the given key is cast using an enum. + * + * @param string $key + * @return bool + */ + protected function isEnumCastable($key) + { + if (! array_key_exists($key, $this->getCasts())) { + return false; + } + + $castType = $this->getCasts()[$key]; + + if (in_array($castType, static::$primitiveCastTypes)) { + return false; + } + + if (function_exists('enum_exists') && enum_exists($castType)) { + return true; + } + } + + /** + * Determine if the key is deviable using a custom class. + * + * @param string $key + * @return bool + * + * @throws \Illuminate\Database\Eloquent\InvalidCastException + */ + protected function isClassDeviable($key) + { + return $this->isClassCastable($key) && + method_exists($castType = $this->parseCasterClass($this->getCasts()[$key]), 'increment') && + method_exists($castType, 'decrement'); + } + + /** + * Determine if the key is serializable using a custom class. + * + * @param string $key + * @return bool + * + * @throws \Illuminate\Database\Eloquent\InvalidCastException + */ + protected function isClassSerializable($key) + { + return ! $this->isEnumCastable($key) && + $this->isClassCastable($key) && + method_exists($this->resolveCasterClass($key), 'serialize'); + } + + /** + * Resolve the custom caster class for a given key. + * + * @param string $key + * @return mixed + */ + protected function resolveCasterClass($key) + { + $castType = $this->getCasts()[$key]; + + $arguments = []; + + if (is_string($castType) && strpos($castType, ':') !== false) { + $segments = explode(':', $castType, 2); + + $castType = $segments[0]; + $arguments = explode(',', $segments[1]); + } + + if (is_subclass_of($castType, Castable::class)) { + $castType = $castType::castUsing($arguments); + } + + if (is_object($castType)) { + return $castType; + } + + return new $castType(...$arguments); + } + + /** + * Parse the given caster class, removing any arguments. + * + * @param string $class + * @return string + */ + protected function parseCasterClass($class) + { + return strpos($class, ':') === false + ? $class + : explode(':', $class, 2)[0]; + } + + /** + * Merge the cast class and attribute cast attributes back into the model. + * + * @return void + */ + protected function mergeAttributesFromCachedCasts() + { + $this->mergeAttributesFromClassCasts(); + $this->mergeAttributesFromAttributeCasts(); + } + + /** + * Merge the cast class attributes back into the model. + * + * @return void + */ + protected function mergeAttributesFromClassCasts() + { + foreach ($this->classCastCache as $key => $value) { + $caster = $this->resolveCasterClass($key); + + $this->attributes = array_merge( + $this->attributes, + $caster instanceof CastsInboundAttributes + ? [$key => $value] + : $this->normalizeCastClassResponse($key, $caster->set($this, $key, $value, $this->attributes)) + ); + } + } + + /** + * Merge the cast class attributes back into the model. + * + * @return void + */ + protected function mergeAttributesFromAttributeCasts() + { + foreach ($this->attributeCastCache as $key => $value) { + $attribute = $this->{Str::camel($key)}(); + + if ($attribute->get && ! $attribute->set) { + continue; + } + + $callback = $attribute->set ?: function ($value) use ($key) { + $this->attributes[$key] = $value; + }; + + $this->attributes = array_merge( + $this->attributes, + $this->normalizeCastClassResponse( + $key, call_user_func($callback, $value, $this->attributes) + ) + ); + } + } + + /** + * Normalize the response from a custom class caster. + * + * @param string $key + * @param mixed $value + * @return array + */ + protected function normalizeCastClassResponse($key, $value) + { + return is_array($value) ? $value : [$key => $value]; + } + + /** + * Get all of the current attributes on the model. + * + * @return array + */ + public function getAttributes() + { + $this->mergeAttributesFromCachedCasts(); + + return $this->attributes; + } + + /** + * Get all of the current attributes on the model for an insert operation. + * + * @return array + */ + protected function getAttributesForInsert() + { + return $this->getAttributes(); + } + + /** + * Set the array of model attributes. No checking is done. + * + * @param array $attributes + * @param bool $sync + * @return $this + */ + public function setRawAttributes(array $attributes, $sync = false) + { + $this->attributes = $attributes; + + if ($sync) { + $this->syncOriginal(); + } + + $this->classCastCache = []; + $this->attributeCastCache = []; + + return $this; + } + + /** + * Get the model's original attribute values. + * + * @param string|null $key + * @param mixed $default + * @return mixed|array + */ + public function getOriginal($key = null, $default = null) + { + return (new static)->setRawAttributes( + $this->original, $sync = true + )->getOriginalWithoutRewindingModel($key, $default); + } + + /** + * Get the model's original attribute values. + * + * @param string|null $key + * @param mixed $default + * @return mixed|array + */ + protected function getOriginalWithoutRewindingModel($key = null, $default = null) + { + if ($key) { + return $this->transformModelValue( + $key, Arr::get($this->original, $key, $default) + ); + } + + return collect($this->original)->mapWithKeys(function ($value, $key) { + return [$key => $this->transformModelValue($key, $value)]; + })->all(); + } + + /** + * Get the model's raw original attribute values. + * + * @param string|null $key + * @param mixed $default + * @return mixed|array + */ + public function getRawOriginal($key = null, $default = null) + { + return Arr::get($this->original, $key, $default); + } + + /** + * Get a subset of the model's attributes. + * + * @param array|mixed $attributes + * @return array + */ + public function only($attributes) + { + $results = []; + + foreach (is_array($attributes) ? $attributes : func_get_args() as $attribute) { + $results[$attribute] = $this->getAttribute($attribute); + } + + return $results; + } + + /** + * Sync the original attributes with the current. + * + * @return $this + */ + public function syncOriginal() + { + $this->original = $this->getAttributes(); + + return $this; + } + + /** + * Sync a single original attribute with its current value. + * + * @param string $attribute + * @return $this + */ + public function syncOriginalAttribute($attribute) + { + return $this->syncOriginalAttributes($attribute); + } + + /** + * Sync multiple original attribute with their current values. + * + * @param array|string $attributes + * @return $this + */ + public function syncOriginalAttributes($attributes) + { + $attributes = is_array($attributes) ? $attributes : func_get_args(); + + $modelAttributes = $this->getAttributes(); + + foreach ($attributes as $attribute) { + $this->original[$attribute] = $modelAttributes[$attribute]; + } + + return $this; + } + + /** + * Sync the changed attributes. + * + * @return $this + */ + public function syncChanges() + { + $this->changes = $this->getDirty(); + + return $this; + } + + /** + * Determine if the model or any of the given attribute(s) have been modified. + * + * @param array|string|null $attributes + * @return bool + */ + public function isDirty($attributes = null) + { + return $this->hasChanges( + $this->getDirty(), is_array($attributes) ? $attributes : func_get_args() + ); + } + + /** + * Determine if the model or all the given attribute(s) have remained the same. + * + * @param array|string|null $attributes + * @return bool + */ + public function isClean($attributes = null) + { + return ! $this->isDirty(...func_get_args()); + } + + /** + * Determine if the model or any of the given attribute(s) have been modified. + * + * @param array|string|null $attributes + * @return bool + */ + public function wasChanged($attributes = null) + { + return $this->hasChanges( + $this->getChanges(), is_array($attributes) ? $attributes : func_get_args() + ); + } + + /** + * Determine if any of the given attributes were changed. + * + * @param array $changes + * @param array|string|null $attributes + * @return bool + */ + protected function hasChanges($changes, $attributes = null) + { + // If no specific attributes were provided, we will just see if the dirty array + // already contains any attributes. If it does we will just return that this + // count is greater than zero. Else, we need to check specific attributes. + if (empty($attributes)) { + return count($changes) > 0; + } + + // Here we will spin through every attribute and see if this is in the array of + // dirty attributes. If it is, we will return true and if we make it through + // all of the attributes for the entire array we will return false at end. + foreach (Arr::wrap($attributes) as $attribute) { + if (array_key_exists($attribute, $changes)) { + return true; + } + } + + return false; + } + + /** + * Get the attributes that have been changed since the last sync. + * + * @return array + */ + public function getDirty() + { + $dirty = []; + + foreach ($this->getAttributes() as $key => $value) { + if (! $this->originalIsEquivalent($key)) { + $dirty[$key] = $value; + } + } + + return $dirty; + } + + /** + * Get the attributes that were changed. + * + * @return array + */ + public function getChanges() + { + return $this->changes; + } + + /** + * Determine if the new and old values for a given key are equivalent. + * + * @param string $key + * @return bool + */ + public function originalIsEquivalent($key) + { + if (! array_key_exists($key, $this->original)) { + return false; + } + + $attribute = Arr::get($this->attributes, $key); + $original = Arr::get($this->original, $key); + + if ($attribute === $original) { + return true; + } elseif (is_null($attribute)) { + return false; + } elseif ($this->isDateAttribute($key) || $this->isDateCastableWithCustomFormat($key)) { + return $this->fromDateTime($attribute) === + $this->fromDateTime($original); + } elseif ($this->hasCast($key, ['object', 'collection'])) { + return $this->fromJson($attribute) === + $this->fromJson($original); + } elseif ($this->hasCast($key, ['real', 'float', 'double'])) { + if (($attribute === null && $original !== null) || ($attribute !== null && $original === null)) { + return false; + } + + return abs($this->castAttribute($key, $attribute) - $this->castAttribute($key, $original)) < PHP_FLOAT_EPSILON * 4; + } elseif ($this->hasCast($key, static::$primitiveCastTypes)) { + return $this->castAttribute($key, $attribute) === + $this->castAttribute($key, $original); + } elseif ($this->isClassCastable($key) && in_array($this->getCasts()[$key], [AsArrayObject::class, AsCollection::class])) { + return $this->fromJson($attribute) === $this->fromJson($original); + } + + return is_numeric($attribute) && is_numeric($original) + && strcmp((string) $attribute, (string) $original) === 0; + } + + /** + * Transform a raw model value using mutators, casts, etc. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function transformModelValue($key, $value) + { + // If the attribute has a get mutator, we will call that then return what + // it returns as the value, which is useful for transforming values on + // retrieval from the model to a form that is more useful for usage. + if ($this->hasGetMutator($key)) { + return $this->mutateAttribute($key, $value); + } elseif ($this->hasAttributeGetMutator($key)) { + return $this->mutateAttributeMarkedAttribute($key, $value); + } + + // If the attribute exists within the cast array, we will convert it to + // an appropriate native PHP type dependent upon the associated value + // given with the key in the pair. Dayle made this comment line up. + if ($this->hasCast($key)) { + return $this->castAttribute($key, $value); + } + + // If the attribute is listed as a date, we will convert it to a DateTime + // instance on retrieval, which makes it quite convenient to work with + // date fields without having to create a mutator for each property. + if ($value !== null + && \in_array($key, $this->getDates(), false)) { + return $this->asDateTime($value); + } + + return $value; + } + + /** + * Append attributes to query when building a query. + * + * @param array|string $attributes + * @return $this + */ + public function append($attributes) + { + $this->appends = array_unique( + array_merge($this->appends, is_string($attributes) ? func_get_args() : $attributes) + ); + + return $this; + } + + /** + * Set the accessors to append to model arrays. + * + * @param array $appends + * @return $this + */ + public function setAppends(array $appends) + { + $this->appends = $appends; + + return $this; + } + + /** + * Return whether the accessor attribute has been appended. + * + * @param string $attribute + * @return bool + */ + public function hasAppended($attribute) + { + return in_array($attribute, $this->appends); + } + + /** + * Get the mutated attributes for a given instance. + * + * @return array + */ + public function getMutatedAttributes() + { + $class = static::class; + + if (! isset(static::$mutatorCache[$class])) { + static::cacheMutatedAttributes($class); + } + + return static::$mutatorCache[$class]; + } + + /** + * Extract and cache all the mutated attributes of a class. + * + * @param string $class + * @return void + */ + public static function cacheMutatedAttributes($class) + { + static::$getAttributeMutatorCache[$class] = + collect($attributeMutatorMethods = static::getAttributeMarkedMutatorMethods($class)) + ->mapWithKeys(function ($match) { + return [lcfirst(static::$snakeAttributes ? Str::snake($match) : $match) => true]; + })->all(); + + static::$mutatorCache[$class] = collect(static::getMutatorMethods($class)) + ->merge($attributeMutatorMethods) + ->map(function ($match) { + return lcfirst(static::$snakeAttributes ? Str::snake($match) : $match); + })->all(); + } + + /** + * Get all of the attribute mutator methods. + * + * @param mixed $class + * @return array + */ + protected static function getMutatorMethods($class) + { + preg_match_all('/(?<=^|;)get([^;]+?)Attribute(;|$)/', implode(';', get_class_methods($class)), $matches); + + return $matches[1]; + } + + /** + * Get all of the "Attribute" return typed attribute mutator methods. + * + * @param mixed $class + * @return array + */ + protected static function getAttributeMarkedMutatorMethods($class) + { + $instance = is_object($class) ? $class : new $class; + + return collect((new ReflectionClass($instance))->getMethods())->filter(function ($method) use ($instance) { + $returnType = $method->getReturnType(); + + if ($returnType && + $returnType instanceof ReflectionNamedType && + $returnType->getName() === Attribute::class) { + $method->setAccessible(true); + + if (is_callable($method->invoke($instance)->get)) { + return true; + } + } + + return false; + })->map->name->values()->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php new file mode 100644 index 0000000..eb6a970 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php @@ -0,0 +1,415 @@ +registerObserver($class); + } + } + + /** + * Register a single observer with the model. + * + * @param object|string $class + * @return void + * + * @throws \RuntimeException + */ + protected function registerObserver($class) + { + $className = $this->resolveObserverClassName($class); + + // When registering a model observer, we will spin through the possible events + // and determine if this observer has that method. If it does, we will hook + // it into the model's event system, making it convenient to watch these. + foreach ($this->getObservableEvents() as $event) { + if (method_exists($class, $event)) { + static::registerModelEvent($event, $className.'@'.$event); + } + } + } + + /** + * Resolve the observer's class name from an object or string. + * + * @param object|string $class + * @return string + * + * @throws \InvalidArgumentException + */ + private function resolveObserverClassName($class) + { + if (is_object($class)) { + return get_class($class); + } + + if (class_exists($class)) { + return $class; + } + + throw new InvalidArgumentException('Unable to find observer: '.$class); + } + + /** + * Get the observable event names. + * + * @return array + */ + public function getObservableEvents() + { + return array_merge( + [ + 'retrieved', 'creating', 'created', 'updating', 'updated', + 'saving', 'saved', 'restoring', 'restored', 'replicating', + 'deleting', 'deleted', 'forceDeleted', + ], + $this->observables + ); + } + + /** + * Set the observable event names. + * + * @param array $observables + * @return $this + */ + public function setObservableEvents(array $observables) + { + $this->observables = $observables; + + return $this; + } + + /** + * Add an observable event name. + * + * @param array|mixed $observables + * @return void + */ + public function addObservableEvents($observables) + { + $this->observables = array_unique(array_merge( + $this->observables, is_array($observables) ? $observables : func_get_args() + )); + } + + /** + * Remove an observable event name. + * + * @param array|mixed $observables + * @return void + */ + public function removeObservableEvents($observables) + { + $this->observables = array_diff( + $this->observables, is_array($observables) ? $observables : func_get_args() + ); + } + + /** + * Register a model event with the dispatcher. + * + * @param string $event + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + protected static function registerModelEvent($event, $callback) + { + if (isset(static::$dispatcher)) { + $name = static::class; + + static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback); + } + } + + /** + * Fire the given event for the model. + * + * @param string $event + * @param bool $halt + * @return mixed + */ + protected function fireModelEvent($event, $halt = true) + { + if (! isset(static::$dispatcher)) { + return true; + } + + // First, we will get the proper method to call on the event dispatcher, and then we + // will attempt to fire a custom, object based event for the given event. If that + // returns a result we can return that result, or we'll call the string events. + $method = $halt ? 'until' : 'dispatch'; + + $result = $this->filterModelEventResults( + $this->fireCustomModelEvent($event, $method) + ); + + if ($result === false) { + return false; + } + + return ! empty($result) ? $result : static::$dispatcher->{$method}( + "eloquent.{$event}: ".static::class, $this + ); + } + + /** + * Fire a custom model event for the given event. + * + * @param string $event + * @param string $method + * @return mixed|null + */ + protected function fireCustomModelEvent($event, $method) + { + if (! isset($this->dispatchesEvents[$event])) { + return; + } + + $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this)); + + if (! is_null($result)) { + return $result; + } + } + + /** + * Filter the model event results. + * + * @param mixed $result + * @return mixed + */ + protected function filterModelEventResults($result) + { + if (is_array($result)) { + $result = array_filter($result, function ($response) { + return ! is_null($response); + }); + } + + return $result; + } + + /** + * Register a retrieved model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function retrieved($callback) + { + static::registerModelEvent('retrieved', $callback); + } + + /** + * Register a saving model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function saving($callback) + { + static::registerModelEvent('saving', $callback); + } + + /** + * Register a saved model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function saved($callback) + { + static::registerModelEvent('saved', $callback); + } + + /** + * Register an updating model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function updating($callback) + { + static::registerModelEvent('updating', $callback); + } + + /** + * Register an updated model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function updated($callback) + { + static::registerModelEvent('updated', $callback); + } + + /** + * Register a creating model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function creating($callback) + { + static::registerModelEvent('creating', $callback); + } + + /** + * Register a created model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function created($callback) + { + static::registerModelEvent('created', $callback); + } + + /** + * Register a replicating model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function replicating($callback) + { + static::registerModelEvent('replicating', $callback); + } + + /** + * Register a deleting model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function deleting($callback) + { + static::registerModelEvent('deleting', $callback); + } + + /** + * Register a deleted model event with the dispatcher. + * + * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback + * @return void + */ + public static function deleted($callback) + { + static::registerModelEvent('deleted', $callback); + } + + /** + * Remove all of the event listeners for the model. + * + * @return void + */ + public static function flushEventListeners() + { + if (! isset(static::$dispatcher)) { + return; + } + + $instance = new static; + + foreach ($instance->getObservableEvents() as $event) { + static::$dispatcher->forget("eloquent.{$event}: ".static::class); + } + + foreach (array_values($instance->dispatchesEvents) as $event) { + static::$dispatcher->forget($event); + } + } + + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public static function getEventDispatcher() + { + return static::$dispatcher; + } + + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher + * @return void + */ + public static function setEventDispatcher(Dispatcher $dispatcher) + { + static::$dispatcher = $dispatcher; + } + + /** + * Unset the event dispatcher for models. + * + * @return void + */ + public static function unsetEventDispatcher() + { + static::$dispatcher = null; + } + + /** + * Execute a callback without firing any model events for any model type. + * + * @param callable $callback + * @return mixed + */ + public static function withoutEvents(callable $callback) + { + $dispatcher = static::getEventDispatcher(); + + if ($dispatcher) { + static::setEventDispatcher(new NullDispatcher($dispatcher)); + } + + try { + return $callback(); + } finally { + if ($dispatcher) { + static::setEventDispatcher($dispatcher); + } + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php new file mode 100644 index 0000000..1742679 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php @@ -0,0 +1,71 @@ + [$name => $callback]] + ); + } + + /** + * Define a one-to-one relationship. + * + * @param string $related + * @param string|null $foreignKey + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function hasOne($related, $foreignKey = null, $localKey = null) + { + $instance = $this->newRelatedInstance($related); + + $foreignKey = $foreignKey ?: $this->getForeignKey(); + + $localKey = $localKey ?: $this->getKeyName(); + + return $this->newHasOne($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey); + } + + /** + * Instantiate a new HasOne relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $foreignKey + * @param string $localKey + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + protected function newHasOne(Builder $query, Model $parent, $foreignKey, $localKey) + { + return new HasOne($query, $parent, $foreignKey, $localKey); + } + + /** + * Define a has-one-through relationship. + * + * @param string $related + * @param string $through + * @param string|null $firstKey + * @param string|null $secondKey + * @param string|null $localKey + * @param string|null $secondLocalKey + * @return \Illuminate\Database\Eloquent\Relations\HasOneThrough + */ + public function hasOneThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null) + { + $through = new $through; + + $firstKey = $firstKey ?: $this->getForeignKey(); + + $secondKey = $secondKey ?: $through->getForeignKey(); + + return $this->newHasOneThrough( + $this->newRelatedInstance($related)->newQuery(), $this, $through, + $firstKey, $secondKey, $localKey ?: $this->getKeyName(), + $secondLocalKey ?: $through->getKeyName() + ); + } + + /** + * Instantiate a new HasOneThrough relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $farParent + * @param \Illuminate\Database\Eloquent\Model $throughParent + * @param string $firstKey + * @param string $secondKey + * @param string $localKey + * @param string $secondLocalKey + * @return \Illuminate\Database\Eloquent\Relations\HasOneThrough + */ + protected function newHasOneThrough(Builder $query, Model $farParent, Model $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey) + { + return new HasOneThrough($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey); + } + + /** + * Define a polymorphic one-to-one relationship. + * + * @param string $related + * @param string $name + * @param string|null $type + * @param string|null $id + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function morphOne($related, $name, $type = null, $id = null, $localKey = null) + { + $instance = $this->newRelatedInstance($related); + + [$type, $id] = $this->getMorphs($name, $type, $id); + + $table = $instance->getTable(); + + $localKey = $localKey ?: $this->getKeyName(); + + return $this->newMorphOne($instance->newQuery(), $this, $table.'.'.$type, $table.'.'.$id, $localKey); + } + + /** + * Instantiate a new MorphOne relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $type + * @param string $id + * @param string $localKey + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + protected function newMorphOne(Builder $query, Model $parent, $type, $id, $localKey) + { + return new MorphOne($query, $parent, $type, $id, $localKey); + } + + /** + * Define an inverse one-to-one or many relationship. + * + * @param string $related + * @param string|null $foreignKey + * @param string|null $ownerKey + * @param string|null $relation + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null) + { + // If no relation name was given, we will use this debug backtrace to extract + // the calling method's name and use that as the relationship name as most + // of the time this will be what we desire to use for the relationships. + if (is_null($relation)) { + $relation = $this->guessBelongsToRelation(); + } + + $instance = $this->newRelatedInstance($related); + + // If no foreign key was supplied, we can use a backtrace to guess the proper + // foreign key name by using the name of the relationship function, which + // when combined with an "_id" should conventionally match the columns. + if (is_null($foreignKey)) { + $foreignKey = Str::snake($relation).'_'.$instance->getKeyName(); + } + + // Once we have the foreign key names, we'll just create a new Eloquent query + // for the related models and returns the relationship instance which will + // actually be responsible for retrieving and hydrating every relations. + $ownerKey = $ownerKey ?: $instance->getKeyName(); + + return $this->newBelongsTo( + $instance->newQuery(), $this, $foreignKey, $ownerKey, $relation + ); + } + + /** + * Instantiate a new BelongsTo relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $child + * @param string $foreignKey + * @param string $ownerKey + * @param string $relation + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + protected function newBelongsTo(Builder $query, Model $child, $foreignKey, $ownerKey, $relation) + { + return new BelongsTo($query, $child, $foreignKey, $ownerKey, $relation); + } + + /** + * Define a polymorphic, inverse one-to-one or many relationship. + * + * @param string|null $name + * @param string|null $type + * @param string|null $id + * @param string|null $ownerKey + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function morphTo($name = null, $type = null, $id = null, $ownerKey = null) + { + // If no name is provided, we will use the backtrace to get the function name + // since that is most likely the name of the polymorphic interface. We can + // use that to get both the class and foreign key that will be utilized. + $name = $name ?: $this->guessBelongsToRelation(); + + [$type, $id] = $this->getMorphs( + Str::snake($name), $type, $id + ); + + // If the type value is null it is probably safe to assume we're eager loading + // the relationship. In this case we'll just pass in a dummy query where we + // need to remove any eager loads that may already be defined on a model. + return is_null($class = $this->getAttributeFromArray($type)) || $class === '' + ? $this->morphEagerTo($name, $type, $id, $ownerKey) + : $this->morphInstanceTo($class, $name, $type, $id, $ownerKey); + } + + /** + * Define a polymorphic, inverse one-to-one or many relationship. + * + * @param string $name + * @param string $type + * @param string $id + * @param string $ownerKey + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + protected function morphEagerTo($name, $type, $id, $ownerKey) + { + return $this->newMorphTo( + $this->newQuery()->setEagerLoads([]), $this, $id, $ownerKey, $type, $name + ); + } + + /** + * Define a polymorphic, inverse one-to-one or many relationship. + * + * @param string $target + * @param string $name + * @param string $type + * @param string $id + * @param string $ownerKey + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + protected function morphInstanceTo($target, $name, $type, $id, $ownerKey) + { + $instance = $this->newRelatedInstance( + static::getActualClassNameForMorph($target) + ); + + return $this->newMorphTo( + $instance->newQuery(), $this, $id, $ownerKey ?? $instance->getKeyName(), $type, $name + ); + } + + /** + * Instantiate a new MorphTo relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $foreignKey + * @param string $ownerKey + * @param string $type + * @param string $relation + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + protected function newMorphTo(Builder $query, Model $parent, $foreignKey, $ownerKey, $type, $relation) + { + return new MorphTo($query, $parent, $foreignKey, $ownerKey, $type, $relation); + } + + /** + * Retrieve the actual class name for a given morph class. + * + * @param string $class + * @return string + */ + public static function getActualClassNameForMorph($class) + { + return Arr::get(Relation::morphMap() ?: [], $class, $class); + } + + /** + * Guess the "belongs to" relationship name. + * + * @return string + */ + protected function guessBelongsToRelation() + { + [$one, $two, $caller] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); + + return $caller['function']; + } + + /** + * Define a one-to-many relationship. + * + * @param string $related + * @param string|null $foreignKey + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function hasMany($related, $foreignKey = null, $localKey = null) + { + $instance = $this->newRelatedInstance($related); + + $foreignKey = $foreignKey ?: $this->getForeignKey(); + + $localKey = $localKey ?: $this->getKeyName(); + + return $this->newHasMany( + $instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey + ); + } + + /** + * Instantiate a new HasMany relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $foreignKey + * @param string $localKey + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + protected function newHasMany(Builder $query, Model $parent, $foreignKey, $localKey) + { + return new HasMany($query, $parent, $foreignKey, $localKey); + } + + /** + * Define a has-many-through relationship. + * + * @param string $related + * @param string $through + * @param string|null $firstKey + * @param string|null $secondKey + * @param string|null $localKey + * @param string|null $secondLocalKey + * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough + */ + public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null) + { + $through = new $through; + + $firstKey = $firstKey ?: $this->getForeignKey(); + + $secondKey = $secondKey ?: $through->getForeignKey(); + + return $this->newHasManyThrough( + $this->newRelatedInstance($related)->newQuery(), + $this, + $through, + $firstKey, + $secondKey, + $localKey ?: $this->getKeyName(), + $secondLocalKey ?: $through->getKeyName() + ); + } + + /** + * Instantiate a new HasManyThrough relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $farParent + * @param \Illuminate\Database\Eloquent\Model $throughParent + * @param string $firstKey + * @param string $secondKey + * @param string $localKey + * @param string $secondLocalKey + * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough + */ + protected function newHasManyThrough(Builder $query, Model $farParent, Model $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey) + { + return new HasManyThrough($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey); + } + + /** + * Define a polymorphic one-to-many relationship. + * + * @param string $related + * @param string $name + * @param string|null $type + * @param string|null $id + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function morphMany($related, $name, $type = null, $id = null, $localKey = null) + { + $instance = $this->newRelatedInstance($related); + + // Here we will gather up the morph type and ID for the relationship so that we + // can properly query the intermediate table of a relation. Finally, we will + // get the table and create the relationship instances for the developers. + [$type, $id] = $this->getMorphs($name, $type, $id); + + $table = $instance->getTable(); + + $localKey = $localKey ?: $this->getKeyName(); + + return $this->newMorphMany($instance->newQuery(), $this, $table.'.'.$type, $table.'.'.$id, $localKey); + } + + /** + * Instantiate a new MorphMany relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $type + * @param string $id + * @param string $localKey + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + protected function newMorphMany(Builder $query, Model $parent, $type, $id, $localKey) + { + return new MorphMany($query, $parent, $type, $id, $localKey); + } + + /** + * Define a many-to-many relationship. + * + * @param string $related + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param string|null $relation + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + */ + public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, + $parentKey = null, $relatedKey = null, $relation = null) + { + // If no relationship name was passed, we will pull backtraces to get the + // name of the calling function. We will use that function name as the + // title of this relation since that is a great convention to apply. + if (is_null($relation)) { + $relation = $this->guessBelongsToManyRelation(); + } + + // First, we'll need to determine the foreign key and "other key" for the + // relationship. Once we have determined the keys we'll make the query + // instances as well as the relationship instances we need for this. + $instance = $this->newRelatedInstance($related); + + $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey(); + + $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey(); + + // If no table name was provided, we can guess it by concatenating the two + // models using underscores in alphabetical order. The two model names + // are transformed to snake case from their default CamelCase also. + if (is_null($table)) { + $table = $this->joiningTable($related, $instance); + } + + return $this->newBelongsToMany( + $instance->newQuery(), $this, $table, $foreignPivotKey, + $relatedPivotKey, $parentKey ?: $this->getKeyName(), + $relatedKey ?: $instance->getKeyName(), $relation + ); + } + + /** + * Instantiate a new BelongsToMany relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $table + * @param string $foreignPivotKey + * @param string $relatedPivotKey + * @param string $parentKey + * @param string $relatedKey + * @param string|null $relationName + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + */ + protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, + $parentKey, $relatedKey, $relationName = null) + { + return new BelongsToMany($query, $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName); + } + + /** + * Define a polymorphic many-to-many relationship. + * + * @param string $related + * @param string $name + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param bool $inverse + * @return \Illuminate\Database\Eloquent\Relations\MorphToMany + */ + public function morphToMany($related, $name, $table = null, $foreignPivotKey = null, + $relatedPivotKey = null, $parentKey = null, + $relatedKey = null, $inverse = false) + { + $caller = $this->guessBelongsToManyRelation(); + + // First, we will need to determine the foreign key and "other key" for the + // relationship. Once we have determined the keys we will make the query + // instances, as well as the relationship instances we need for these. + $instance = $this->newRelatedInstance($related); + + $foreignPivotKey = $foreignPivotKey ?: $name.'_id'; + + $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey(); + + // Now we're ready to create a new query builder for this related model and + // the relationship instances for this relation. This relations will set + // appropriate query constraints then entirely manages the hydrations. + if (! $table) { + $words = preg_split('/(_)/u', $name, -1, PREG_SPLIT_DELIM_CAPTURE); + + $lastWord = array_pop($words); + + $table = implode('', $words).Str::plural($lastWord); + } + + return $this->newMorphToMany( + $instance->newQuery(), $this, $name, $table, + $foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(), + $relatedKey ?: $instance->getKeyName(), $caller, $inverse + ); + } + + /** + * Instantiate a new MorphToMany relationship. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Model $parent + * @param string $name + * @param string $table + * @param string $foreignPivotKey + * @param string $relatedPivotKey + * @param string $parentKey + * @param string $relatedKey + * @param string|null $relationName + * @param bool $inverse + * @return \Illuminate\Database\Eloquent\Relations\MorphToMany + */ + protected function newMorphToMany(Builder $query, Model $parent, $name, $table, $foreignPivotKey, + $relatedPivotKey, $parentKey, $relatedKey, + $relationName = null, $inverse = false) + { + return new MorphToMany($query, $parent, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, + $relationName, $inverse); + } + + /** + * Define a polymorphic, inverse many-to-many relationship. + * + * @param string $related + * @param string $name + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @return \Illuminate\Database\Eloquent\Relations\MorphToMany + */ + public function morphedByMany($related, $name, $table = null, $foreignPivotKey = null, + $relatedPivotKey = null, $parentKey = null, $relatedKey = null) + { + $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey(); + + // For the inverse of the polymorphic many-to-many relations, we will change + // the way we determine the foreign and other keys, as it is the opposite + // of the morph-to-many method since we're figuring out these inverses. + $relatedPivotKey = $relatedPivotKey ?: $name.'_id'; + + return $this->morphToMany( + $related, $name, $table, $foreignPivotKey, + $relatedPivotKey, $parentKey, $relatedKey, true + ); + } + + /** + * Get the relationship name of the belongsToMany relationship. + * + * @return string|null + */ + protected function guessBelongsToManyRelation() + { + $caller = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) { + return ! in_array( + $trace['function'], + array_merge(static::$manyMethods, ['guessBelongsToManyRelation']) + ); + }); + + return ! is_null($caller) ? $caller['function'] : null; + } + + /** + * Get the joining table name for a many-to-many relation. + * + * @param string $related + * @param \Illuminate\Database\Eloquent\Model|null $instance + * @return string + */ + public function joiningTable($related, $instance = null) + { + // The joining table name, by convention, is simply the snake cased models + // sorted alphabetically and concatenated with an underscore, so we can + // just sort the models and join them together to get the table name. + $segments = [ + $instance ? $instance->joiningTableSegment() + : Str::snake(class_basename($related)), + $this->joiningTableSegment(), + ]; + + // Now that we have the model names in an array we can just sort them and + // use the implode function to join them together with an underscores, + // which is typically used by convention within the database system. + sort($segments); + + return strtolower(implode('_', $segments)); + } + + /** + * Get this model's half of the intermediate table name for belongsToMany relationships. + * + * @return string + */ + public function joiningTableSegment() + { + return Str::snake(class_basename($this)); + } + + /** + * Determine if the model touches a given relation. + * + * @param string $relation + * @return bool + */ + public function touches($relation) + { + return in_array($relation, $this->getTouchedRelations()); + } + + /** + * Touch the owning relations of the model. + * + * @return void + */ + public function touchOwners() + { + foreach ($this->getTouchedRelations() as $relation) { + $this->$relation()->touch(); + + if ($this->$relation instanceof self) { + $this->$relation->fireModelEvent('saved', false); + + $this->$relation->touchOwners(); + } elseif ($this->$relation instanceof Collection) { + $this->$relation->each->touchOwners(); + } + } + } + + /** + * Get the polymorphic relationship columns. + * + * @param string $name + * @param string $type + * @param string $id + * @return array + */ + protected function getMorphs($name, $type, $id) + { + return [$type ?: $name.'_type', $id ?: $name.'_id']; + } + + /** + * Get the class name for polymorphic relations. + * + * @return string + */ + public function getMorphClass() + { + $morphMap = Relation::morphMap(); + + if (! empty($morphMap) && in_array(static::class, $morphMap)) { + return array_search(static::class, $morphMap, true); + } + + if (Relation::requiresMorphMap()) { + throw new ClassMorphViolationException($this); + } + + return static::class; + } + + /** + * Create a new model instance for a related model. + * + * @param string $class + * @return mixed + */ + protected function newRelatedInstance($class) + { + return tap(new $class, function ($instance) { + if (! $instance->getConnectionName()) { + $instance->setConnection($this->connection); + } + }); + } + + /** + * Get all the loaded relations for the instance. + * + * @return array + */ + public function getRelations() + { + return $this->relations; + } + + /** + * Get a specified relationship. + * + * @param string $relation + * @return mixed + */ + public function getRelation($relation) + { + return $this->relations[$relation]; + } + + /** + * Determine if the given relation is loaded. + * + * @param string $key + * @return bool + */ + public function relationLoaded($key) + { + return array_key_exists($key, $this->relations); + } + + /** + * Set the given relationship on the model. + * + * @param string $relation + * @param mixed $value + * @return $this + */ + public function setRelation($relation, $value) + { + $this->relations[$relation] = $value; + + return $this; + } + + /** + * Unset a loaded relationship. + * + * @param string $relation + * @return $this + */ + public function unsetRelation($relation) + { + unset($this->relations[$relation]); + + return $this; + } + + /** + * Set the entire relations array on the model. + * + * @param array $relations + * @return $this + */ + public function setRelations(array $relations) + { + $this->relations = $relations; + + return $this; + } + + /** + * Duplicate the instance and unset all the loaded relations. + * + * @return $this + */ + public function withoutRelations() + { + $model = clone $this; + + return $model->unsetRelations(); + } + + /** + * Unset all the loaded relations for the instance. + * + * @return $this + */ + public function unsetRelations() + { + $this->relations = []; + + return $this; + } + + /** + * Get the relationships that are touched on save. + * + * @return array + */ + public function getTouchedRelations() + { + return $this->touches; + } + + /** + * Set the relationships that are touched on save. + * + * @param array $touches + * @return $this + */ + public function setTouchedRelations(array $touches) + { + $this->touches = $touches; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php new file mode 100644 index 0000000..13ebd31 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php @@ -0,0 +1,149 @@ +usesTimestamps()) { + return false; + } + + $this->updateTimestamps(); + + return $this->save(); + } + + /** + * Update the creation and update timestamps. + * + * @return void + */ + public function updateTimestamps() + { + $time = $this->freshTimestamp(); + + $updatedAtColumn = $this->getUpdatedAtColumn(); + + if (! is_null($updatedAtColumn) && ! $this->isDirty($updatedAtColumn)) { + $this->setUpdatedAt($time); + } + + $createdAtColumn = $this->getCreatedAtColumn(); + + if (! $this->exists && ! is_null($createdAtColumn) && ! $this->isDirty($createdAtColumn)) { + $this->setCreatedAt($time); + } + } + + /** + * Set the value of the "created at" attribute. + * + * @param mixed $value + * @return $this + */ + public function setCreatedAt($value) + { + $this->{$this->getCreatedAtColumn()} = $value; + + return $this; + } + + /** + * Set the value of the "updated at" attribute. + * + * @param mixed $value + * @return $this + */ + public function setUpdatedAt($value) + { + $this->{$this->getUpdatedAtColumn()} = $value; + + return $this; + } + + /** + * Get a fresh timestamp for the model. + * + * @return \Illuminate\Support\Carbon + */ + public function freshTimestamp() + { + return Date::now(); + } + + /** + * Get a fresh timestamp for the model. + * + * @return string + */ + public function freshTimestampString() + { + return $this->fromDateTime($this->freshTimestamp()); + } + + /** + * Determine if the model uses timestamps. + * + * @return bool + */ + public function usesTimestamps() + { + return $this->timestamps; + } + + /** + * Get the name of the "created at" column. + * + * @return string|null + */ + public function getCreatedAtColumn() + { + return static::CREATED_AT; + } + + /** + * Get the name of the "updated at" column. + * + * @return string|null + */ + public function getUpdatedAtColumn() + { + return static::UPDATED_AT; + } + + /** + * Get the fully qualified "created at" column. + * + * @return string|null + */ + public function getQualifiedCreatedAtColumn() + { + return $this->qualifyColumn($this->getCreatedAtColumn()); + } + + /** + * Get the fully qualified "updated at" column. + * + * @return string|null + */ + public function getQualifiedUpdatedAtColumn() + { + return $this->qualifyColumn($this->getUpdatedAtColumn()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HidesAttributes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HidesAttributes.php new file mode 100644 index 0000000..065d48a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HidesAttributes.php @@ -0,0 +1,126 @@ +hidden; + } + + /** + * Set the hidden attributes for the model. + * + * @param array $hidden + * @return $this + */ + public function setHidden(array $hidden) + { + $this->hidden = $hidden; + + return $this; + } + + /** + * Get the visible attributes for the model. + * + * @return array + */ + public function getVisible() + { + return $this->visible; + } + + /** + * Set the visible attributes for the model. + * + * @param array $visible + * @return $this + */ + public function setVisible(array $visible) + { + $this->visible = $visible; + + return $this; + } + + /** + * Make the given, typically hidden, attributes visible. + * + * @param array|string|null $attributes + * @return $this + */ + public function makeVisible($attributes) + { + $attributes = is_array($attributes) ? $attributes : func_get_args(); + + $this->hidden = array_diff($this->hidden, $attributes); + + if (! empty($this->visible)) { + $this->visible = array_merge($this->visible, $attributes); + } + + return $this; + } + + /** + * Make the given, typically hidden, attributes visible if the given truth test passes. + * + * @param bool|Closure $condition + * @param array|string|null $attributes + * @return $this + */ + public function makeVisibleIf($condition, $attributes) + { + return value($condition, $this) ? $this->makeVisible($attributes) : $this; + } + + /** + * Make the given, typically visible, attributes hidden. + * + * @param array|string|null $attributes + * @return $this + */ + public function makeHidden($attributes) + { + $this->hidden = array_merge( + $this->hidden, is_array($attributes) ? $attributes : func_get_args() + ); + + return $this; + } + + /** + * Make the given, typically visible, attributes hidden if the given truth test passes. + * + * @param bool|Closure $condition + * @param array|string|null $attributes + * @return $this + */ + public function makeHiddenIf($condition, $attributes) + { + return value($condition, $this) ? $this->makeHidden($attributes) : $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php new file mode 100644 index 0000000..c16af1f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -0,0 +1,758 @@ +=', $count = 1, $boolean = 'and', Closure $callback = null) + { + if (is_string($relation)) { + if (strpos($relation, '.') !== false) { + return $this->hasNested($relation, $operator, $count, $boolean, $callback); + } + + $relation = $this->getRelationWithoutConstraints($relation); + } + + if ($relation instanceof MorphTo) { + return $this->hasMorph($relation, ['*'], $operator, $count, $boolean, $callback); + } + + // If we only need to check for the existence of the relation, then we can optimize + // the subquery to only run a "where exists" clause instead of this full "count" + // clause. This will make these queries run much faster compared with a count. + $method = $this->canUseExistsForExistenceCheck($operator, $count) + ? 'getRelationExistenceQuery' + : 'getRelationExistenceCountQuery'; + + $hasQuery = $relation->{$method}( + $relation->getRelated()->newQueryWithoutRelationships(), $this + ); + + // Next we will call any given callback as an "anonymous" scope so they can get the + // proper logical grouping of the where clauses if needed by this Eloquent query + // builder. Then, we will be ready to finalize and return this query instance. + if ($callback) { + $hasQuery->callScope($callback); + } + + return $this->addHasWhere( + $hasQuery, $relation, $operator, $count, $boolean + ); + } + + /** + * Add nested relationship count / exists conditions to the query. + * + * Sets up recursive call to whereHas until we finish the nested relation. + * + * @param string $relations + * @param string $operator + * @param int $count + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + protected function hasNested($relations, $operator = '>=', $count = 1, $boolean = 'and', $callback = null) + { + $relations = explode('.', $relations); + + $doesntHave = $operator === '<' && $count === 1; + + if ($doesntHave) { + $operator = '>='; + $count = 1; + } + + $closure = function ($q) use (&$closure, &$relations, $operator, $count, $callback) { + // In order to nest "has", we need to add count relation constraints on the + // callback Closure. We'll do this by simply passing the Closure its own + // reference to itself so it calls itself recursively on each segment. + count($relations) > 1 + ? $q->whereHas(array_shift($relations), $closure) + : $q->has(array_shift($relations), $operator, $count, 'and', $callback); + }; + + return $this->has(array_shift($relations), $doesntHave ? '<' : '>=', 1, $boolean, $closure); + } + + /** + * Add a relationship count / exists condition to the query with an "or". + * + * @param string $relation + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orHas($relation, $operator = '>=', $count = 1) + { + return $this->has($relation, $operator, $count, 'or'); + } + + /** + * Add a relationship count / exists condition to the query. + * + * @param string $relation + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function doesntHave($relation, $boolean = 'and', Closure $callback = null) + { + return $this->has($relation, '<', 1, $boolean, $callback); + } + + /** + * Add a relationship count / exists condition to the query with an "or". + * + * @param string $relation + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orDoesntHave($relation) + { + return $this->doesntHave($relation, 'or'); + } + + /** + * Add a relationship count / exists condition to the query with where clauses. + * + * @param string $relation + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereHas($relation, Closure $callback = null, $operator = '>=', $count = 1) + { + return $this->has($relation, $operator, $count, 'and', $callback); + } + + /** + * Add a relationship count / exists condition to the query with where clauses and an "or". + * + * @param string $relation + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereHas($relation, Closure $callback = null, $operator = '>=', $count = 1) + { + return $this->has($relation, $operator, $count, 'or', $callback); + } + + /** + * Add a relationship count / exists condition to the query with where clauses. + * + * @param string $relation + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereDoesntHave($relation, Closure $callback = null) + { + return $this->doesntHave($relation, 'and', $callback); + } + + /** + * Add a relationship count / exists condition to the query with where clauses and an "or". + * + * @param string $relation + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereDoesntHave($relation, Closure $callback = null) + { + return $this->doesntHave($relation, 'or', $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param string $operator + * @param int $count + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) + { + if (is_string($relation)) { + $relation = $this->getRelationWithoutConstraints($relation); + } + + $types = (array) $types; + + if ($types === ['*']) { + $types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())->filter()->all(); + } + + foreach ($types as &$type) { + $type = Relation::getMorphedModel($type) ?? $type; + } + + return $this->where(function ($query) use ($relation, $callback, $operator, $count, $types) { + foreach ($types as $type) { + $query->orWhere(function ($query) use ($relation, $callback, $operator, $count, $type) { + $belongsTo = $this->getBelongsToRelation($relation, $type); + + if ($callback) { + $callback = function ($query) use ($callback, $type) { + return $callback($query, $type); + }; + } + + $query->where($this->qualifyColumn($relation->getMorphType()), '=', (new $type)->getMorphClass()) + ->whereHas($belongsTo, $callback, $operator, $count); + }); + } + }, null, null, $boolean); + } + + /** + * Get the BelongsTo relationship for a single polymorphic type. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo $relation + * @param string $type + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + protected function getBelongsToRelation(MorphTo $relation, $type) + { + $belongsTo = Relation::noConstraints(function () use ($relation, $type) { + return $this->model->belongsTo( + $type, + $relation->getForeignKeyName(), + $relation->getOwnerKeyName() + ); + }); + + $belongsTo->getQuery()->mergeConstraintsFrom($relation->getQuery()); + + return $belongsTo; + } + + /** + * Add a polymorphic relationship count / exists condition to the query with an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orHasMorph($relation, $types, $operator = '>=', $count = 1) + { + return $this->hasMorph($relation, $types, $operator, $count, 'or'); + } + + /** + * Add a polymorphic relationship count / exists condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function doesntHaveMorph($relation, $types, $boolean = 'and', Closure $callback = null) + { + return $this->hasMorph($relation, $types, '<', 1, $boolean, $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orDoesntHaveMorph($relation, $types) + { + return $this->doesntHaveMorph($relation, $types, 'or'); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereHasMorph($relation, $types, Closure $callback = null, $operator = '>=', $count = 1) + { + return $this->hasMorph($relation, $types, $operator, $count, 'and', $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses and an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereHasMorph($relation, $types, Closure $callback = null, $operator = '>=', $count = 1) + { + return $this->hasMorph($relation, $types, $operator, $count, 'or', $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereDoesntHaveMorph($relation, $types, Closure $callback = null) + { + return $this->doesntHaveMorph($relation, $types, 'and', $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses and an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereDoesntHaveMorph($relation, $types, Closure $callback = null) + { + return $this->doesntHaveMorph($relation, $types, 'or', $callback); + } + + /** + * Add a basic where clause to a relationship query. + * + * @param string $relation + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereRelation($relation, $column, $operator = null, $value = null) + { + return $this->whereHas($relation, function ($query) use ($column, $operator, $value) { + $query->where($column, $operator, $value); + }); + } + + /** + * Add an "or where" clause to a relationship query. + * + * @param string $relation + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereRelation($relation, $column, $operator = null, $value = null) + { + return $this->orWhereHas($relation, function ($query) use ($column, $operator, $value) { + $query->where($column, $operator, $value); + }); + } + + /** + * Add a polymorphic relationship condition to the query with a where clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereMorphRelation($relation, $types, $column, $operator = null, $value = null) + { + return $this->whereHasMorph($relation, $types, function ($query) use ($column, $operator, $value) { + $query->where($column, $operator, $value); + }); + } + + /** + * Add a polymorphic relationship condition to the query with an "or where" clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereMorphRelation($relation, $types, $column, $operator = null, $value = null) + { + return $this->orWhereHasMorph($relation, $types, function ($query) use ($column, $operator, $value) { + $query->where($column, $operator, $value); + }); + } + + /** + * Add a morph-to relationship condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param \Illuminate\Database\Eloquent\Model|string $model + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function whereMorphedTo($relation, $model, $boolean = 'and') + { + if (is_string($relation)) { + $relation = $this->getRelationWithoutConstraints($relation); + } + + if (is_string($model)) { + $morphMap = Relation::morphMap(); + + if (! empty($morphMap) && in_array($model, $morphMap)) { + $model = array_search($model, $morphMap, true); + } + + return $this->where($relation->getMorphType(), $model, null, $boolean); + } + + return $this->where(function ($query) use ($relation, $model) { + $query->where($relation->getMorphType(), $model->getMorphClass()) + ->where($relation->getForeignKeyName(), $model->getKey()); + }, null, null, $boolean); + } + + /** + * Add a morph-to relationship condition to the query with an "or where" clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param \Illuminate\Database\Eloquent\Model|string $model + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function orWhereMorphedTo($relation, $model) + { + return $this->whereMorphedTo($relation, $model, 'or'); + } + + /** + * Add a "belongs to" relationship where clause to the query. + * + * @param \Illuminate\Database\Eloquent\Model $related + * @param string $relationship + * @param string $boolean + * @return $this + * + * @throws \RuntimeException + */ + public function whereBelongsTo($related, $relationshipName = null, $boolean = 'and') + { + if ($relationshipName === null) { + $relationshipName = Str::camel(class_basename($related)); + } + + try { + $relationship = $this->model->{$relationshipName}(); + } catch (BadMethodCallException $exception) { + throw RelationNotFoundException::make($this->model, $relationshipName); + } + + if (! $relationship instanceof BelongsTo) { + throw RelationNotFoundException::make($this->model, $relationshipName, BelongsTo::class); + } + + $this->where( + $relationship->getQualifiedForeignKeyName(), + '=', + $related->getAttributeValue($relationship->getOwnerKeyName()), + $boolean, + ); + + return $this; + } + + /** + * Add an "BelongsTo" relationship with an "or where" clause to the query. + * + * @param \Illuminate\Database\Eloquent\Model $related + * @param string $relationship + * @return $this + * + * @throws \RuntimeException + */ + public function orWhereBelongsTo($related, $relationshipName = null) + { + return $this->whereBelongsTo($related, $relationshipName, 'or'); + } + + /** + * Add subselect queries to include an aggregate value for a relationship. + * + * @param mixed $relations + * @param string $column + * @param string $function + * @return $this + */ + public function withAggregate($relations, $column, $function = null) + { + if (empty($relations)) { + return $this; + } + + if (is_null($this->query->columns)) { + $this->query->select([$this->query->from.'.*']); + } + + $relations = is_array($relations) ? $relations : [$relations]; + + foreach ($this->parseWithRelations($relations) as $name => $constraints) { + // First we will determine if the name has been aliased using an "as" clause on the name + // and if it has we will extract the actual relationship name and the desired name of + // the resulting column. This allows multiple aggregates on the same relationships. + $segments = explode(' ', $name); + + unset($alias); + + if (count($segments) === 3 && Str::lower($segments[1]) === 'as') { + [$name, $alias] = [$segments[0], $segments[2]]; + } + + $relation = $this->getRelationWithoutConstraints($name); + + if ($function) { + $hashedColumn = $this->getQuery()->from === $relation->getQuery()->getQuery()->from + ? "{$relation->getRelationCountHash(false)}.$column" + : $column; + + $wrappedColumn = $this->getQuery()->getGrammar()->wrap( + $column === '*' ? $column : $relation->getRelated()->qualifyColumn($hashedColumn) + ); + + $expression = $function === 'exists' ? $wrappedColumn : sprintf('%s(%s)', $function, $wrappedColumn); + } else { + $expression = $column; + } + + // Here, we will grab the relationship sub-query and prepare to add it to the main query + // as a sub-select. First, we'll get the "has" query and use that to get the relation + // sub-query. We'll format this relationship name and append this column if needed. + $query = $relation->getRelationExistenceQuery( + $relation->getRelated()->newQuery(), $this, new Expression($expression) + )->setBindings([], 'select'); + + $query->callScope($constraints); + + $query = $query->mergeConstraintsFrom($relation->getQuery())->toBase(); + + // If the query contains certain elements like orderings / more than one column selected + // then we will remove those elements from the query so that it will execute properly + // when given to the database. Otherwise, we may receive SQL errors or poor syntax. + $query->orders = null; + $query->setBindings([], 'order'); + + if (count($query->columns) > 1) { + $query->columns = [$query->columns[0]]; + $query->bindings['select'] = []; + } + + // Finally, we will make the proper column alias to the query and run this sub-select on + // the query builder. Then, we will return the builder instance back to the developer + // for further constraint chaining that needs to take place on the query as needed. + $alias = $alias ?? Str::snake( + preg_replace('/[^[:alnum:][:space:]_]/u', '', "$name $function $column") + ); + + if ($function === 'exists') { + $this->selectRaw( + sprintf('exists(%s) as %s', $query->toSql(), $this->getQuery()->grammar->wrap($alias)), + $query->getBindings() + )->withCasts([$alias => 'bool']); + } else { + $this->selectSub( + $function ? $query : $query->limit(1), + $alias + ); + } + } + + return $this; + } + + /** + * Add subselect queries to count the relations. + * + * @param mixed $relations + * @return $this + */ + public function withCount($relations) + { + return $this->withAggregate(is_array($relations) ? $relations : func_get_args(), '*', 'count'); + } + + /** + * Add subselect queries to include the max of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return $this + */ + public function withMax($relation, $column) + { + return $this->withAggregate($relation, $column, 'max'); + } + + /** + * Add subselect queries to include the min of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return $this + */ + public function withMin($relation, $column) + { + return $this->withAggregate($relation, $column, 'min'); + } + + /** + * Add subselect queries to include the sum of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return $this + */ + public function withSum($relation, $column) + { + return $this->withAggregate($relation, $column, 'sum'); + } + + /** + * Add subselect queries to include the average of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return $this + */ + public function withAvg($relation, $column) + { + return $this->withAggregate($relation, $column, 'avg'); + } + + /** + * Add subselect queries to include the existence of related models. + * + * @param string|array $relation + * @return $this + */ + public function withExists($relation) + { + return $this->withAggregate($relation, '*', 'exists'); + } + + /** + * Add the "has" condition where clause to the query. + * + * @param \Illuminate\Database\Eloquent\Builder $hasQuery + * @param \Illuminate\Database\Eloquent\Relations\Relation $relation + * @param string $operator + * @param int $count + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Builder|static + */ + protected function addHasWhere(Builder $hasQuery, Relation $relation, $operator, $count, $boolean) + { + $hasQuery->mergeConstraintsFrom($relation->getQuery()); + + return $this->canUseExistsForExistenceCheck($operator, $count) + ? $this->addWhereExistsQuery($hasQuery->toBase(), $boolean, $operator === '<' && $count === 1) + : $this->addWhereCountQuery($hasQuery->toBase(), $operator, $count, $boolean); + } + + /** + * Merge the where constraints from another query to the current query. + * + * @param \Illuminate\Database\Eloquent\Builder $from + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function mergeConstraintsFrom(Builder $from) + { + $whereBindings = $from->getQuery()->getRawBindings()['where'] ?? []; + + // Here we have some other query that we want to merge the where constraints from. We will + // copy over any where constraints on the query as well as remove any global scopes the + // query might have removed. Then we will return ourselves with the finished merging. + return $this->withoutGlobalScopes( + $from->removedScopes() + )->mergeWheres( + $from->getQuery()->wheres, $whereBindings + ); + } + + /** + * Add a sub-query count clause to this query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $operator + * @param int $count + * @param string $boolean + * @return $this + */ + protected function addWhereCountQuery(QueryBuilder $query, $operator = '>=', $count = 1, $boolean = 'and') + { + $this->query->addBinding($query->getBindings(), 'where'); + + return $this->where( + new Expression('('.$query->toSql().')'), + $operator, + is_numeric($count) ? new Expression($count) : $count, + $boolean + ); + } + + /** + * Get the "has relation" base query instance. + * + * @param string $relation + * @return \Illuminate\Database\Eloquent\Relations\Relation + */ + protected function getRelationWithoutConstraints($relation) + { + return Relation::noConstraints(function () use ($relation) { + return $this->getModel()->{$relation}(); + }); + } + + /** + * Check if we can run an "exists" query to optimize performance. + * + * @param string $operator + * @param int $count + * @return bool + */ + protected function canUseExistsForExistenceCheck($operator, $count) + { + return ($operator === '>=' || $operator === '<') && $count === 1; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php new file mode 100644 index 0000000..e0c42c4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php @@ -0,0 +1,61 @@ +factory = $factory; + $this->pivot = $pivot; + $this->relationship = $relationship; + } + + /** + * Create the attached relationship for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return void + */ + public function createFor(Model $model) + { + Collection::wrap($this->factory instanceof Factory ? $this->factory->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { + $model->{$this->relationship}()->attach( + $attachable, + is_callable($this->pivot) ? call_user_func($this->pivot, $model) : $this->pivot + ); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/BelongsToRelationship.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/BelongsToRelationship.php new file mode 100644 index 0000000..55747fd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/BelongsToRelationship.php @@ -0,0 +1,80 @@ +factory = $factory; + $this->relationship = $relationship; + } + + /** + * Get the parent model attributes and resolvers for the given child model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return array + */ + public function attributesFor(Model $model) + { + $relationship = $model->{$this->relationship}(); + + return $relationship instanceof MorphTo ? [ + $relationship->getMorphType() => $this->factory instanceof Factory ? $this->factory->newModel()->getMorphClass() : $this->factory->getMorphClass(), + $relationship->getForeignKeyName() => $this->resolver($relationship->getOwnerKeyName()), + ] : [ + $relationship->getForeignKeyName() => $this->resolver($relationship->getOwnerKeyName()), + ]; + } + + /** + * Get the deferred resolver for this relationship's parent ID. + * + * @param string|null $key + * @return \Closure + */ + protected function resolver($key) + { + return function () use ($key) { + if (! $this->resolved) { + $instance = $this->factory instanceof Factory ? $this->factory->create() : $this->factory; + + return $this->resolved = $key ? $instance->{$key} : $instance->getKey(); + } + + return $this->resolved; + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/CrossJoinSequence.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/CrossJoinSequence.php new file mode 100644 index 0000000..b0efbd0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/CrossJoinSequence.php @@ -0,0 +1,26 @@ +count = $count; + $this->states = $states ?: new Collection; + $this->has = $has ?: new Collection; + $this->for = $for ?: new Collection; + $this->afterMaking = $afterMaking ?: new Collection; + $this->afterCreating = $afterCreating ?: new Collection; + $this->connection = $connection; + $this->faker = $this->withFaker(); + } + + /** + * Define the model's default state. + * + * @return array + */ + abstract public function definition(); + + /** + * Get a new factory instance for the given attributes. + * + * @param callable|array $attributes + * @return static + */ + public static function new($attributes = []) + { + return (new static)->state($attributes)->configure(); + } + + /** + * Get a new factory instance for the given number of models. + * + * @param int $count + * @return static + */ + public static function times(int $count) + { + return static::new()->count($count); + } + + /** + * Configure the factory. + * + * @return $this + */ + public function configure() + { + return $this; + } + + /** + * Get the raw attributes generated by the factory. + * + * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return array + */ + public function raw($attributes = [], ?Model $parent = null) + { + if ($this->count === null) { + return $this->state($attributes)->getExpandedAttributes($parent); + } + + return array_map(function () use ($attributes, $parent) { + return $this->state($attributes)->getExpandedAttributes($parent); + }, range(1, $this->count)); + } + + /** + * Create a single model and persist it to the database. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function createOne($attributes = []) + { + return $this->count(null)->create($attributes); + } + + /** + * Create a single model and persist it to the database. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function createOneQuietly($attributes = []) + { + return $this->count(null)->createQuietly($attributes); + } + + /** + * Create a collection of models and persist them to the database. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection + */ + public function createMany(iterable $records) + { + return new EloquentCollection( + collect($records)->map(function ($record) { + return $this->state($record)->create(); + }) + ); + } + + /** + * Create a collection of models and persist them to the database. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection + */ + public function createManyQuietly(iterable $records) + { + return Model::withoutEvents(function () use ($records) { + return $this->createMany($records); + }); + } + + /** + * Create a collection of models and persist them to the database. + * + * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model + */ + public function create($attributes = [], ?Model $parent = null) + { + if (! empty($attributes)) { + return $this->state($attributes)->create([], $parent); + } + + $results = $this->make($attributes, $parent); + + if ($results instanceof Model) { + $this->store(collect([$results])); + + $this->callAfterCreating(collect([$results]), $parent); + } else { + $this->store($results); + + $this->callAfterCreating($results, $parent); + } + + return $results; + } + + /** + * Create a collection of models and persist them to the database. + * + * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model + */ + public function createQuietly($attributes = [], ?Model $parent = null) + { + return Model::withoutEvents(function () use ($attributes, $parent) { + return $this->create($attributes, $parent); + }); + } + + /** + * Create a callback that persists a model in the database when invoked. + * + * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return \Closure + */ + public function lazy(array $attributes = [], ?Model $parent = null) + { + return function () use ($attributes, $parent) { + return $this->create($attributes, $parent); + }; + } + + /** + * Set the connection name on the results and store them. + * + * @param \Illuminate\Support\Collection $results + * @return void + */ + protected function store(Collection $results) + { + $results->each(function ($model) { + if (! isset($this->connection)) { + $model->setConnection($model->newQueryWithoutScopes()->getConnection()->getName()); + } + + $model->save(); + + $this->createChildren($model); + }); + } + + /** + * Create the children for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return void + */ + protected function createChildren(Model $model) + { + Model::unguarded(function () use ($model) { + $this->has->each(function ($has) use ($model) { + $has->createFor($model); + }); + }); + } + + /** + * Make a single instance of the model. + * + * @param callable|array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function makeOne($attributes = []) + { + return $this->count(null)->make($attributes); + } + + /** + * Create a collection of models. + * + * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model + */ + public function make($attributes = [], ?Model $parent = null) + { + if (! empty($attributes)) { + return $this->state($attributes)->make([], $parent); + } + + if ($this->count === null) { + return tap($this->makeInstance($parent), function ($instance) { + $this->callAfterMaking(collect([$instance])); + }); + } + + if ($this->count < 1) { + return $this->newModel()->newCollection(); + } + + $instances = $this->newModel()->newCollection(array_map(function () use ($parent) { + return $this->makeInstance($parent); + }, range(1, $this->count))); + + $this->callAfterMaking($instances); + + return $instances; + } + + /** + * Make an instance of the model with the given attributes. + * + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return \Illuminate\Database\Eloquent\Model + */ + protected function makeInstance(?Model $parent) + { + return Model::unguarded(function () use ($parent) { + return tap($this->newModel($this->getExpandedAttributes($parent)), function ($instance) { + if (isset($this->connection)) { + $instance->setConnection($this->connection); + } + }); + }); + } + + /** + * Get a raw attributes array for the model. + * + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return mixed + */ + protected function getExpandedAttributes(?Model $parent) + { + return $this->expandAttributes($this->getRawAttributes($parent)); + } + + /** + * Get the raw attributes for the model as an array. + * + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return array + */ + protected function getRawAttributes(?Model $parent) + { + return $this->states->pipe(function ($states) { + return $this->for->isEmpty() ? $states : new Collection(array_merge([function () { + return $this->parentResolvers(); + }], $states->all())); + })->reduce(function ($carry, $state) use ($parent) { + if ($state instanceof Closure) { + $state = $state->bindTo($this); + } + + return array_merge($carry, $state($carry, $parent)); + }, $this->definition()); + } + + /** + * Create the parent relationship resolvers (as deferred Closures). + * + * @return array + */ + protected function parentResolvers() + { + $model = $this->newModel(); + + return $this->for->map(function (BelongsToRelationship $for) use ($model) { + return $for->attributesFor($model); + })->collapse()->all(); + } + + /** + * Expand all attributes to their underlying values. + * + * @param array $definition + * @return array + */ + protected function expandAttributes(array $definition) + { + return collect($definition)->map(function ($attribute, $key) use (&$definition) { + if (is_callable($attribute) && ! is_string($attribute) && ! is_array($attribute)) { + $attribute = $attribute($definition); + } + + if ($attribute instanceof self) { + $attribute = $attribute->create()->getKey(); + } elseif ($attribute instanceof Model) { + $attribute = $attribute->getKey(); + } + + $definition[$key] = $attribute; + + return $attribute; + })->all(); + } + + /** + * Add a new state transformation to the model definition. + * + * @param callable|array $state + * @return static + */ + public function state($state) + { + return $this->newInstance([ + 'states' => $this->states->concat([ + is_callable($state) ? $state : function () use ($state) { + return $state; + }, + ]), + ]); + } + + /** + * Add a new sequenced state transformation to the model definition. + * + * @param array $sequence + * @return static + */ + public function sequence(...$sequence) + { + return $this->state(new Sequence(...$sequence)); + } + + /** + * Add a new cross joined sequenced state transformation to the model definition. + * + * @param array $sequence + * @return static + */ + public function crossJoinSequence(...$sequence) + { + return $this->state(new CrossJoinSequence(...$sequence)); + } + + /** + * Define a child relationship for the model. + * + * @param \Illuminate\Database\Eloquent\Factories\Factory $factory + * @param string|null $relationship + * @return static + */ + public function has(self $factory, $relationship = null) + { + return $this->newInstance([ + 'has' => $this->has->concat([new Relationship( + $factory, $relationship ?: $this->guessRelationship($factory->modelName()) + )]), + ]); + } + + /** + * Attempt to guess the relationship name for a "has" relationship. + * + * @param string $related + * @return string + */ + protected function guessRelationship(string $related) + { + $guess = Str::camel(Str::plural(class_basename($related))); + + return method_exists($this->modelName(), $guess) ? $guess : Str::singular($guess); + } + + /** + * Define an attached relationship for the model. + * + * @param \Illuminate\Database\Eloquent\Factories\Factory|\Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model $factory + * @param callable|array $pivot + * @param string|null $relationship + * @return static + */ + public function hasAttached($factory, $pivot = [], $relationship = null) + { + return $this->newInstance([ + 'has' => $this->has->concat([new BelongsToManyRelationship( + $factory, + $pivot, + $relationship ?: Str::camel(Str::plural(class_basename( + $factory instanceof Factory + ? $factory->modelName() + : Collection::wrap($factory)->first() + ))) + )]), + ]); + } + + /** + * Define a parent relationship for the model. + * + * @param \Illuminate\Database\Eloquent\Factories\Factory|\Illuminate\Database\Eloquent\Model $factory + * @param string|null $relationship + * @return static + */ + public function for($factory, $relationship = null) + { + return $this->newInstance(['for' => $this->for->concat([new BelongsToRelationship( + $factory, + $relationship ?: Str::camel(class_basename( + $factory instanceof Factory ? $factory->modelName() : $factory + )) + )])]); + } + + /** + * Add a new "after making" callback to the model definition. + * + * @param \Closure $callback + * @return static + */ + public function afterMaking(Closure $callback) + { + return $this->newInstance(['afterMaking' => $this->afterMaking->concat([$callback])]); + } + + /** + * Add a new "after creating" callback to the model definition. + * + * @param \Closure $callback + * @return static + */ + public function afterCreating(Closure $callback) + { + return $this->newInstance(['afterCreating' => $this->afterCreating->concat([$callback])]); + } + + /** + * Call the "after making" callbacks for the given model instances. + * + * @param \Illuminate\Support\Collection $instances + * @return void + */ + protected function callAfterMaking(Collection $instances) + { + $instances->each(function ($model) { + $this->afterMaking->each(function ($callback) use ($model) { + $callback($model); + }); + }); + } + + /** + * Call the "after creating" callbacks for the given model instances. + * + * @param \Illuminate\Support\Collection $instances + * @param \Illuminate\Database\Eloquent\Model|null $parent + * @return void + */ + protected function callAfterCreating(Collection $instances, ?Model $parent = null) + { + $instances->each(function ($model) use ($parent) { + $this->afterCreating->each(function ($callback) use ($model, $parent) { + $callback($model, $parent); + }); + }); + } + + /** + * Specify how many models should be generated. + * + * @param int|null $count + * @return static + */ + public function count(?int $count) + { + return $this->newInstance(['count' => $count]); + } + + /** + * Specify the database connection that should be used to generate models. + * + * @param string $connection + * @return static + */ + public function connection(string $connection) + { + return $this->newInstance(['connection' => $connection]); + } + + /** + * Create a new instance of the factory builder with the given mutated properties. + * + * @param array $arguments + * @return static + */ + protected function newInstance(array $arguments = []) + { + return new static(...array_values(array_merge([ + 'count' => $this->count, + 'states' => $this->states, + 'has' => $this->has, + 'for' => $this->for, + 'afterMaking' => $this->afterMaking, + 'afterCreating' => $this->afterCreating, + 'connection' => $this->connection, + ], $arguments))); + } + + /** + * Get a new model instance. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function newModel(array $attributes = []) + { + $model = $this->modelName(); + + return new $model($attributes); + } + + /** + * Get the name of the model that is generated by the factory. + * + * @return string + */ + public function modelName() + { + $resolver = static::$modelNameResolver ?: function (self $factory) { + $namespacedFactoryBasename = Str::replaceLast( + 'Factory', '', Str::replaceFirst(static::$namespace, '', get_class($factory)) + ); + + $factoryBasename = Str::replaceLast('Factory', '', class_basename($factory)); + + $appNamespace = static::appNamespace(); + + return class_exists($appNamespace.'Models\\'.$namespacedFactoryBasename) + ? $appNamespace.'Models\\'.$namespacedFactoryBasename + : $appNamespace.$factoryBasename; + }; + + return $this->model ?: $resolver($this); + } + + /** + * Specify the callback that should be invoked to guess model names based on factory names. + * + * @param callable $callback + * @return void + */ + public static function guessModelNamesUsing(callable $callback) + { + static::$modelNameResolver = $callback; + } + + /** + * Specify the default namespace that contains the application's model factories. + * + * @param string $namespace + * @return void + */ + public static function useNamespace(string $namespace) + { + static::$namespace = $namespace; + } + + /** + * Get a new factory instance for the given model name. + * + * @param string $modelName + * @return static + */ + public static function factoryForModel(string $modelName) + { + $factory = static::resolveFactoryName($modelName); + + return $factory::new(); + } + + /** + * Specify the callback that should be invoked to guess factory names based on dynamic relationship names. + * + * @param callable $callback + * @return void + */ + public static function guessFactoryNamesUsing(callable $callback) + { + static::$factoryNameResolver = $callback; + } + + /** + * Get a new Faker instance. + * + * @return \Faker\Generator + */ + protected function withFaker() + { + return Container::getInstance()->make(Generator::class); + } + + /** + * Get the factory name for the given model name. + * + * @param string $modelName + * @return string + */ + public static function resolveFactoryName(string $modelName) + { + $resolver = static::$factoryNameResolver ?: function (string $modelName) { + $appNamespace = static::appNamespace(); + + $modelName = Str::startsWith($modelName, $appNamespace.'Models\\') + ? Str::after($modelName, $appNamespace.'Models\\') + : Str::after($modelName, $appNamespace); + + return static::$namespace.$modelName.'Factory'; + }; + + return $resolver($modelName); + } + + /** + * Get the application namespace for the application. + * + * @return string + */ + protected static function appNamespace() + { + try { + return Container::getInstance() + ->make(Application::class) + ->getNamespace(); + } catch (Throwable $e) { + return 'App\\'; + } + } + + /** + * Proxy dynamic factory methods onto their proper methods. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + if (! Str::startsWith($method, ['for', 'has'])) { + static::throwBadMethodCallException($method); + } + + $relationship = Str::camel(Str::substr($method, 3)); + + $relatedModel = get_class($this->newModel()->{$relationship}()->getRelated()); + + if (method_exists($relatedModel, 'newFactory')) { + $factory = $relatedModel::newFactory() ?: static::factoryForModel($relatedModel); + } else { + $factory = static::factoryForModel($relatedModel); + } + + if (Str::startsWith($method, 'for')) { + return $this->for($factory->state($parameters[0] ?? []), $relationship); + } elseif (Str::startsWith($method, 'has')) { + return $this->has( + $factory + ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : 1) + ->state((is_callable($parameters[0] ?? null) || is_array($parameters[0] ?? null)) ? $parameters[0] : ($parameters[1] ?? [])), + $relationship + ); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/HasFactory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/HasFactory.php new file mode 100644 index 0000000..7d2be22 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/HasFactory.php @@ -0,0 +1,31 @@ +count(is_numeric($parameters[0] ?? null) ? $parameters[0] : null) + ->state(is_array($parameters[0] ?? null) ? $parameters[0] : ($parameters[1] ?? [])); + } + + /** + * Create a new factory instance for the model. + * + * @return \Illuminate\Database\Eloquent\Factories\Factory + */ + protected static function newFactory() + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Relationship.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Relationship.php new file mode 100644 index 0000000..788f6bc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Relationship.php @@ -0,0 +1,62 @@ +factory = $factory; + $this->relationship = $relationship; + } + + /** + * Create the child relationship for the given parent model. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return void + */ + public function createFor(Model $parent) + { + $relationship = $parent->{$this->relationship}(); + + if ($relationship instanceof MorphOneOrMany) { + $this->factory->state([ + $relationship->getMorphType() => $relationship->getMorphClass(), + $relationship->getForeignKeyName() => $relationship->getParentKey(), + ])->create([], $parent); + } elseif ($relationship instanceof HasOneOrMany) { + $this->factory->state([ + $relationship->getForeignKeyName() => $relationship->getParentKey(), + ])->create([], $parent); + } elseif ($relationship instanceof BelongsToMany) { + $relationship->attach($this->factory->create([], $parent)); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Sequence.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Sequence.php new file mode 100644 index 0000000..064cc4a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Sequence.php @@ -0,0 +1,63 @@ +sequence = $sequence; + $this->count = count($sequence); + } + + /** + * Get the current count of the sequence items. + * + * @return int + */ + public function count(): int + { + return $this->count; + } + + /** + * Get the next value in the sequence. + * + * @return mixed + */ + public function __invoke() + { + return tap(value($this->sequence[$this->index % $this->count], $this), function () { + $this->index = $this->index + 1; + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/HigherOrderBuilderProxy.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/HigherOrderBuilderProxy.php new file mode 100644 index 0000000..16b49a1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/HigherOrderBuilderProxy.php @@ -0,0 +1,50 @@ +method = $method; + $this->builder = $builder; + } + + /** + * Proxy a scope call onto the query builder. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->builder->{$this->method}(function ($value) use ($method, $parameters) { + return $value->{$method}(...$parameters); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/InvalidCastException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/InvalidCastException.php new file mode 100644 index 0000000..9d00eb3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/InvalidCastException.php @@ -0,0 +1,48 @@ +model = $class; + $this->column = $column; + $this->castType = $castType; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/JsonEncodingException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/JsonEncodingException.php new file mode 100644 index 0000000..f62abd4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/JsonEncodingException.php @@ -0,0 +1,49 @@ +getKey().'] to JSON: '.$message); + } + + /** + * Create a new JSON encoding exception for the resource. + * + * @param \Illuminate\Http\Resources\Json\JsonResource $resource + * @param string $message + * @return static + */ + public static function forResource($resource, $message) + { + $model = $resource->resource; + + return new static('Error encoding resource ['.get_class($resource).'] with model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message); + } + + /** + * Create a new JSON encoding exception for an attribute. + * + * @param mixed $model + * @param mixed $key + * @param string $message + * @return static + */ + public static function forAttribute($model, $key, $message) + { + $class = get_class($model); + + return new static("Unable to encode attribute [{$key}] for model [{$class}] to JSON: {$message}."); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/MassAssignmentException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/MassAssignmentException.php new file mode 100755 index 0000000..7c81aae --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/MassAssignmentException.php @@ -0,0 +1,10 @@ +prunable(), function ($query) use ($chunkSize) { + $query->when(! $query->getQuery()->limit, function ($query) use ($chunkSize) { + $query->limit($chunkSize); + }); + }); + + $total = 0; + + do { + $total += $count = in_array(SoftDeletes::class, class_uses_recursive(get_class($this))) + ? $query->forceDelete() + : $query->delete(); + + if ($count > 0) { + event(new ModelsPruned(static::class, $total)); + } + } while ($count > 0); + + return $total; + } + + /** + * Get the prunable model query. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public function prunable() + { + throw new LogicException('Please implement the prunable method on your model.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php new file mode 100644 index 0000000..d1742bb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php @@ -0,0 +1,2198 @@ +bootIfNotBooted(); + + $this->initializeTraits(); + + $this->syncOriginal(); + + $this->fill($attributes); + } + + /** + * Check if the model needs to be booted and if so, do it. + * + * @return void + */ + protected function bootIfNotBooted() + { + if (! isset(static::$booted[static::class])) { + static::$booted[static::class] = true; + + $this->fireModelEvent('booting', false); + + static::booting(); + static::boot(); + static::booted(); + + $this->fireModelEvent('booted', false); + } + } + + /** + * Perform any actions required before the model boots. + * + * @return void + */ + protected static function booting() + { + // + } + + /** + * Bootstrap the model and its traits. + * + * @return void + */ + protected static function boot() + { + static::bootTraits(); + } + + /** + * Boot all of the bootable traits on the model. + * + * @return void + */ + protected static function bootTraits() + { + $class = static::class; + + $booted = []; + + static::$traitInitializers[$class] = []; + + foreach (class_uses_recursive($class) as $trait) { + $method = 'boot'.class_basename($trait); + + if (method_exists($class, $method) && ! in_array($method, $booted)) { + forward_static_call([$class, $method]); + + $booted[] = $method; + } + + if (method_exists($class, $method = 'initialize'.class_basename($trait))) { + static::$traitInitializers[$class][] = $method; + + static::$traitInitializers[$class] = array_unique( + static::$traitInitializers[$class] + ); + } + } + } + + /** + * Initialize any initializable traits on the model. + * + * @return void + */ + protected function initializeTraits() + { + foreach (static::$traitInitializers[static::class] as $method) { + $this->{$method}(); + } + } + + /** + * Perform any actions required after the model boots. + * + * @return void + */ + protected static function booted() + { + // + } + + /** + * Clear the list of booted models so they will be re-booted. + * + * @return void + */ + public static function clearBootedModels() + { + static::$booted = []; + + static::$globalScopes = []; + } + + /** + * Disables relationship model touching for the current class during given callback scope. + * + * @param callable $callback + * @return void + */ + public static function withoutTouching(callable $callback) + { + static::withoutTouchingOn([static::class], $callback); + } + + /** + * Disables relationship model touching for the given model classes during given callback scope. + * + * @param array $models + * @param callable $callback + * @return void + */ + public static function withoutTouchingOn(array $models, callable $callback) + { + static::$ignoreOnTouch = array_values(array_merge(static::$ignoreOnTouch, $models)); + + try { + $callback(); + } finally { + static::$ignoreOnTouch = array_values(array_diff(static::$ignoreOnTouch, $models)); + } + } + + /** + * Determine if the given model is ignoring touches. + * + * @param string|null $class + * @return bool + */ + public static function isIgnoringTouch($class = null) + { + $class = $class ?: static::class; + + if (! get_class_vars($class)['timestamps'] || ! $class::UPDATED_AT) { + return true; + } + + foreach (static::$ignoreOnTouch as $ignoredClass) { + if ($class === $ignoredClass || is_subclass_of($class, $ignoredClass)) { + return true; + } + } + + return false; + } + + /** + * Prevent model relationships from being lazy loaded. + * + * @param bool $value + * @return void + */ + public static function preventLazyLoading($value = true) + { + static::$modelsShouldPreventLazyLoading = $value; + } + + /** + * Register a callback that is responsible for handling lazy loading violations. + * + * @param callable|null $callback + * @return void + */ + public static function handleLazyLoadingViolationUsing(?callable $callback) + { + static::$lazyLoadingViolationCallback = $callback; + } + + /** + * Execute a callback without broadcasting any model events for all model types. + * + * @param callable $callback + * @return mixed + */ + public static function withoutBroadcasting(callable $callback) + { + $isBroadcasting = static::$isBroadcasting; + + static::$isBroadcasting = false; + + try { + return $callback(); + } finally { + static::$isBroadcasting = $isBroadcasting; + } + } + + /** + * Fill the model with an array of attributes. + * + * @param array $attributes + * @return $this + * + * @throws \Illuminate\Database\Eloquent\MassAssignmentException + */ + public function fill(array $attributes) + { + $totallyGuarded = $this->totallyGuarded(); + + foreach ($this->fillableFromArray($attributes) as $key => $value) { + // The developers may choose to place some attributes in the "fillable" array + // which means only those attributes may be set through mass assignment to + // the model, and all others will just get ignored for security reasons. + if ($this->isFillable($key)) { + $this->setAttribute($key, $value); + } elseif ($totallyGuarded) { + throw new MassAssignmentException(sprintf( + 'Add [%s] to fillable property to allow mass assignment on [%s].', + $key, get_class($this) + )); + } + } + + return $this; + } + + /** + * Fill the model with an array of attributes. Force mass assignment. + * + * @param array $attributes + * @return $this + */ + public function forceFill(array $attributes) + { + return static::unguarded(function () use ($attributes) { + return $this->fill($attributes); + }); + } + + /** + * Qualify the given column name by the model's table. + * + * @param string $column + * @return string + */ + public function qualifyColumn($column) + { + if (Str::contains($column, '.')) { + return $column; + } + + return $this->getTable().'.'.$column; + } + + /** + * Qualify the given columns with the model's table. + * + * @param array $columns + * @return array + */ + public function qualifyColumns($columns) + { + return collect($columns)->map(function ($column) { + return $this->qualifyColumn($column); + })->all(); + } + + /** + * Create a new instance of the given model. + * + * @param array $attributes + * @param bool $exists + * @return static + */ + public function newInstance($attributes = [], $exists = false) + { + // This method just provides a convenient way for us to generate fresh model + // instances of this current model. It is particularly useful during the + // hydration of new objects via the Eloquent query builder instances. + $model = new static((array) $attributes); + + $model->exists = $exists; + + $model->setConnection( + $this->getConnectionName() + ); + + $model->setTable($this->getTable()); + + $model->mergeCasts($this->casts); + + return $model; + } + + /** + * Create a new model instance that is existing. + * + * @param array $attributes + * @param string|null $connection + * @return static + */ + public function newFromBuilder($attributes = [], $connection = null) + { + $model = $this->newInstance([], true); + + $model->setRawAttributes((array) $attributes, true); + + $model->setConnection($connection ?: $this->getConnectionName()); + + $model->fireModelEvent('retrieved', false); + + return $model; + } + + /** + * Begin querying the model on a given connection. + * + * @param string|null $connection + * @return \Illuminate\Database\Eloquent\Builder + */ + public static function on($connection = null) + { + // First we will just create a fresh instance of this model, and then we can set the + // connection on the model so that it is used for the queries we execute, as well + // as being set on every relation we retrieve without a custom connection name. + $instance = new static; + + $instance->setConnection($connection); + + return $instance->newQuery(); + } + + /** + * Begin querying the model on the write connection. + * + * @return \Illuminate\Database\Query\Builder + */ + public static function onWriteConnection() + { + return static::query()->useWritePdo(); + } + + /** + * Get all of the models from the database. + * + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Collection|static[] + */ + public static function all($columns = ['*']) + { + return static::query()->get( + is_array($columns) ? $columns : func_get_args() + ); + } + + /** + * Begin querying a model with eager loading. + * + * @param array|string $relations + * @return \Illuminate\Database\Eloquent\Builder + */ + public static function with($relations) + { + return static::query()->with( + is_string($relations) ? func_get_args() : $relations + ); + } + + /** + * Eager load relations on the model. + * + * @param array|string $relations + * @return $this + */ + public function load($relations) + { + $query = $this->newQueryWithoutRelationships()->with( + is_string($relations) ? func_get_args() : $relations + ); + + $query->eagerLoadRelations([$this]); + + return $this; + } + + /** + * Eager load relationships on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorph($relation, $relations) + { + if (! $this->{$relation}) { + return $this; + } + + $className = get_class($this->{$relation}); + + $this->{$relation}->load($relations[$className] ?? []); + + return $this; + } + + /** + * Eager load relations on the model if they are not already eager loaded. + * + * @param array|string $relations + * @return $this + */ + public function loadMissing($relations) + { + $relations = is_string($relations) ? func_get_args() : $relations; + + $this->newCollection([$this])->loadMissing($relations); + + return $this; + } + + /** + * Eager load relation's column aggregations on the model. + * + * @param array|string $relations + * @param string $column + * @param string $function + * @return $this + */ + public function loadAggregate($relations, $column, $function = null) + { + $this->newCollection([$this])->loadAggregate($relations, $column, $function); + + return $this; + } + + /** + * Eager load relation counts on the model. + * + * @param array|string $relations + * @return $this + */ + public function loadCount($relations) + { + $relations = is_string($relations) ? func_get_args() : $relations; + + return $this->loadAggregate($relations, '*', 'count'); + } + + /** + * Eager load relation max column values on the model. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadMax($relations, $column) + { + return $this->loadAggregate($relations, $column, 'max'); + } + + /** + * Eager load relation min column values on the model. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadMin($relations, $column) + { + return $this->loadAggregate($relations, $column, 'min'); + } + + /** + * Eager load relation's column summations on the model. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadSum($relations, $column) + { + return $this->loadAggregate($relations, $column, 'sum'); + } + + /** + * Eager load relation average column values on the model. + * + * @param array|string $relations + * @param string $column + * @return $this + */ + public function loadAvg($relations, $column) + { + return $this->loadAggregate($relations, $column, 'avg'); + } + + /** + * Eager load related model existence values on the model. + * + * @param array|string $relations + * @return $this + */ + public function loadExists($relations) + { + return $this->loadAggregate($relations, '*', 'exists'); + } + + /** + * Eager load relationship column aggregation on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @param string $function + * @return $this + */ + public function loadMorphAggregate($relation, $relations, $column, $function = null) + { + if (! $this->{$relation}) { + return $this; + } + + $className = get_class($this->{$relation}); + + $this->{$relation}->loadAggregate($relations[$className] ?? [], $column, $function); + + return $this; + } + + /** + * Eager load relationship counts on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorphCount($relation, $relations) + { + return $this->loadMorphAggregate($relation, $relations, '*', 'count'); + } + + /** + * Eager load relationship max column values on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return $this + */ + public function loadMorphMax($relation, $relations, $column) + { + return $this->loadMorphAggregate($relation, $relations, $column, 'max'); + } + + /** + * Eager load relationship min column values on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return $this + */ + public function loadMorphMin($relation, $relations, $column) + { + return $this->loadMorphAggregate($relation, $relations, $column, 'min'); + } + + /** + * Eager load relationship column summations on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return $this + */ + public function loadMorphSum($relation, $relations, $column) + { + return $this->loadMorphAggregate($relation, $relations, $column, 'sum'); + } + + /** + * Eager load relationship average column values on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return $this + */ + public function loadMorphAvg($relation, $relations, $column) + { + return $this->loadMorphAggregate($relation, $relations, $column, 'avg'); + } + + /** + * Increment a column's value by a given amount. + * + * @param string $column + * @param float|int $amount + * @param array $extra + * @return int + */ + protected function increment($column, $amount = 1, array $extra = []) + { + return $this->incrementOrDecrement($column, $amount, $extra, 'increment'); + } + + /** + * Decrement a column's value by a given amount. + * + * @param string $column + * @param float|int $amount + * @param array $extra + * @return int + */ + protected function decrement($column, $amount = 1, array $extra = []) + { + return $this->incrementOrDecrement($column, $amount, $extra, 'decrement'); + } + + /** + * Run the increment or decrement method on the model. + * + * @param string $column + * @param float|int $amount + * @param array $extra + * @param string $method + * @return int + */ + protected function incrementOrDecrement($column, $amount, $extra, $method) + { + $query = $this->newQueryWithoutRelationships(); + + if (! $this->exists) { + return $query->{$method}($column, $amount, $extra); + } + + $this->{$column} = $this->isClassDeviable($column) + ? $this->deviateClassCastableAttribute($method, $column, $amount) + : $this->{$column} + ($method === 'increment' ? $amount : $amount * -1); + + $this->forceFill($extra); + + if ($this->fireModelEvent('updating') === false) { + return false; + } + + return tap($this->setKeysForSaveQuery($query)->{$method}($column, $amount, $extra), function () use ($column) { + $this->syncChanges(); + + $this->fireModelEvent('updated', false); + + $this->syncOriginalAttribute($column); + }); + } + + /** + * Update the model in the database. + * + * @param array $attributes + * @param array $options + * @return bool + */ + public function update(array $attributes = [], array $options = []) + { + if (! $this->exists) { + return false; + } + + return $this->fill($attributes)->save($options); + } + + /** + * Update the model in the database within a transaction. + * + * @param array $attributes + * @param array $options + * @return bool + * + * @throws \Throwable + */ + public function updateOrFail(array $attributes = [], array $options = []) + { + if (! $this->exists) { + return false; + } + + return $this->fill($attributes)->saveOrFail($options); + } + + /** + * Update the model in the database without raising any events. + * + * @param array $attributes + * @param array $options + * @return bool + */ + public function updateQuietly(array $attributes = [], array $options = []) + { + if (! $this->exists) { + return false; + } + + return $this->fill($attributes)->saveQuietly($options); + } + + /** + * Save the model and all of its relationships. + * + * @return bool + */ + public function push() + { + if (! $this->save()) { + return false; + } + + // To sync all of the relationships to the database, we will simply spin through + // the relationships and save each model via this "push" method, which allows + // us to recurse into all of these nested relations for the model instance. + foreach ($this->relations as $models) { + $models = $models instanceof Collection + ? $models->all() : [$models]; + + foreach (array_filter($models) as $model) { + if (! $model->push()) { + return false; + } + } + } + + return true; + } + + /** + * Save the model to the database without raising any events. + * + * @param array $options + * @return bool + */ + public function saveQuietly(array $options = []) + { + return static::withoutEvents(function () use ($options) { + return $this->save($options); + }); + } + + /** + * Save the model to the database. + * + * @param array $options + * @return bool + */ + public function save(array $options = []) + { + $this->mergeAttributesFromCachedCasts(); + + $query = $this->newModelQuery(); + + // If the "saving" event returns false we'll bail out of the save and return + // false, indicating that the save failed. This provides a chance for any + // listeners to cancel save operations if validations fail or whatever. + if ($this->fireModelEvent('saving') === false) { + return false; + } + + // If the model already exists in the database we can just update our record + // that is already in this database using the current IDs in this "where" + // clause to only update this model. Otherwise, we'll just insert them. + if ($this->exists) { + $saved = $this->isDirty() ? + $this->performUpdate($query) : true; + } + + // If the model is brand new, we'll insert it into our database and set the + // ID attribute on the model to the value of the newly inserted row's ID + // which is typically an auto-increment value managed by the database. + else { + $saved = $this->performInsert($query); + + if (! $this->getConnectionName() && + $connection = $query->getConnection()) { + $this->setConnection($connection->getName()); + } + } + + // If the model is successfully saved, we need to do a few more things once + // that is done. We will call the "saved" method here to run any actions + // we need to happen after a model gets successfully saved right here. + if ($saved) { + $this->finishSave($options); + } + + return $saved; + } + + /** + * Save the model to the database within a transaction. + * + * @param array $options + * @return bool + * + * @throws \Throwable + */ + public function saveOrFail(array $options = []) + { + return $this->getConnection()->transaction(function () use ($options) { + return $this->save($options); + }); + } + + /** + * Perform any actions that are necessary after the model is saved. + * + * @param array $options + * @return void + */ + protected function finishSave(array $options) + { + $this->fireModelEvent('saved', false); + + if ($this->isDirty() && ($options['touch'] ?? true)) { + $this->touchOwners(); + } + + $this->syncOriginal(); + } + + /** + * Perform a model update operation. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return bool + */ + protected function performUpdate(Builder $query) + { + // If the updating event returns false, we will cancel the update operation so + // developers can hook Validation systems into their models and cancel this + // operation if the model does not pass validation. Otherwise, we update. + if ($this->fireModelEvent('updating') === false) { + return false; + } + + // First we need to create a fresh query instance and touch the creation and + // update timestamp on the model which are maintained by us for developer + // convenience. Then we will just continue saving the model instances. + if ($this->usesTimestamps()) { + $this->updateTimestamps(); + } + + // Once we have run the update operation, we will fire the "updated" event for + // this model instance. This will allow developers to hook into these after + // models are updated, giving them a chance to do any special processing. + $dirty = $this->getDirty(); + + if (count($dirty) > 0) { + $this->setKeysForSaveQuery($query)->update($dirty); + + $this->syncChanges(); + + $this->fireModelEvent('updated', false); + } + + return true; + } + + /** + * Set the keys for a select query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function setKeysForSelectQuery($query) + { + $query->where($this->getKeyName(), '=', $this->getKeyForSelectQuery()); + + return $query; + } + + /** + * Get the primary key value for a select query. + * + * @return mixed + */ + protected function getKeyForSelectQuery() + { + return $this->original[$this->getKeyName()] ?? $this->getKey(); + } + + /** + * Set the keys for a save update query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function setKeysForSaveQuery($query) + { + $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery()); + + return $query; + } + + /** + * Get the primary key value for a save query. + * + * @return mixed + */ + protected function getKeyForSaveQuery() + { + return $this->original[$this->getKeyName()] ?? $this->getKey(); + } + + /** + * Perform a model insert operation. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return bool + */ + protected function performInsert(Builder $query) + { + if ($this->fireModelEvent('creating') === false) { + return false; + } + + // First we'll need to create a fresh query instance and touch the creation and + // update timestamps on this model, which are maintained by us for developer + // convenience. After, we will just continue saving these model instances. + if ($this->usesTimestamps()) { + $this->updateTimestamps(); + } + + // If the model has an incrementing key, we can use the "insertGetId" method on + // the query builder, which will give us back the final inserted ID for this + // table from the database. Not all tables have to be incrementing though. + $attributes = $this->getAttributesForInsert(); + + if ($this->getIncrementing()) { + $this->insertAndSetId($query, $attributes); + } + + // If the table isn't incrementing we'll simply insert these attributes as they + // are. These attribute arrays must contain an "id" column previously placed + // there by the developer as the manually determined key for these models. + else { + if (empty($attributes)) { + return true; + } + + $query->insert($attributes); + } + + // We will go ahead and set the exists property to true, so that it is set when + // the created event is fired, just in case the developer tries to update it + // during the event. This will allow them to do so and run an update here. + $this->exists = true; + + $this->wasRecentlyCreated = true; + + $this->fireModelEvent('created', false); + + return true; + } + + /** + * Insert the given attributes and set the ID on the model. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param array $attributes + * @return void + */ + protected function insertAndSetId(Builder $query, $attributes) + { + $id = $query->insertGetId($attributes, $keyName = $this->getKeyName()); + + $this->setAttribute($keyName, $id); + } + + /** + * Destroy the models for the given IDs. + * + * @param \Illuminate\Support\Collection|array|int|string $ids + * @return int + */ + public static function destroy($ids) + { + if ($ids instanceof EloquentCollection) { + $ids = $ids->modelKeys(); + } + + if ($ids instanceof BaseCollection) { + $ids = $ids->all(); + } + + $ids = is_array($ids) ? $ids : func_get_args(); + + if (count($ids) === 0) { + return 0; + } + + // We will actually pull the models from the database table and call delete on + // each of them individually so that their events get fired properly with a + // correct set of attributes in case the developers wants to check these. + $key = ($instance = new static)->getKeyName(); + + $count = 0; + + foreach ($instance->whereIn($key, $ids)->get() as $model) { + if ($model->delete()) { + $count++; + } + } + + return $count; + } + + /** + * Delete the model from the database. + * + * @return bool|null + * + * @throws \LogicException + */ + public function delete() + { + $this->mergeAttributesFromCachedCasts(); + + if (is_null($this->getKeyName())) { + throw new LogicException('No primary key defined on model.'); + } + + // If the model doesn't exist, there is nothing to delete so we'll just return + // immediately and not do anything else. Otherwise, we will continue with a + // deletion process on the model, firing the proper events, and so forth. + if (! $this->exists) { + return; + } + + if ($this->fireModelEvent('deleting') === false) { + return false; + } + + // Here, we'll touch the owning models, verifying these timestamps get updated + // for the models. This will allow any caching to get broken on the parents + // by the timestamp. Then we will go ahead and delete the model instance. + $this->touchOwners(); + + $this->performDeleteOnModel(); + + // Once the model has been deleted, we will fire off the deleted event so that + // the developers may hook into post-delete operations. We will then return + // a boolean true as the delete is presumably successful on the database. + $this->fireModelEvent('deleted', false); + + return true; + } + + /** + * Delete the model from the database within a transaction. + * + * @return bool|null + * + * @throws \Throwable + */ + public function deleteOrFail() + { + if (! $this->exists) { + return false; + } + + return $this->getConnection()->transaction(function () { + return $this->delete(); + }); + } + + /** + * Force a hard delete on a soft deleted model. + * + * This method protects developers from running forceDelete when the trait is missing. + * + * @return bool|null + */ + public function forceDelete() + { + return $this->delete(); + } + + /** + * Perform the actual delete query on this model instance. + * + * @return void + */ + protected function performDeleteOnModel() + { + $this->setKeysForSaveQuery($this->newModelQuery())->delete(); + + $this->exists = false; + } + + /** + * Begin querying the model. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public static function query() + { + return (new static)->newQuery(); + } + + /** + * Get a new query builder for the model's table. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public function newQuery() + { + return $this->registerGlobalScopes($this->newQueryWithoutScopes()); + } + + /** + * Get a new query builder that doesn't have any global scopes or eager loading. + * + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function newModelQuery() + { + return $this->newEloquentBuilder( + $this->newBaseQueryBuilder() + )->setModel($this); + } + + /** + * Get a new query builder with no relationships loaded. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public function newQueryWithoutRelationships() + { + return $this->registerGlobalScopes($this->newModelQuery()); + } + + /** + * Register the global scopes for this builder instance. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return \Illuminate\Database\Eloquent\Builder + */ + public function registerGlobalScopes($builder) + { + foreach ($this->getGlobalScopes() as $identifier => $scope) { + $builder->withGlobalScope($identifier, $scope); + } + + return $builder; + } + + /** + * Get a new query builder that doesn't have any global scopes. + * + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function newQueryWithoutScopes() + { + return $this->newModelQuery() + ->with($this->with) + ->withCount($this->withCount); + } + + /** + * Get a new query instance without a given scope. + * + * @param \Illuminate\Database\Eloquent\Scope|string $scope + * @return \Illuminate\Database\Eloquent\Builder + */ + public function newQueryWithoutScope($scope) + { + return $this->newQuery()->withoutGlobalScope($scope); + } + + /** + * Get a new query to restore one or more models by their queueable IDs. + * + * @param array|int $ids + * @return \Illuminate\Database\Eloquent\Builder + */ + public function newQueryForRestoration($ids) + { + return is_array($ids) + ? $this->newQueryWithoutScopes()->whereIn($this->getQualifiedKeyName(), $ids) + : $this->newQueryWithoutScopes()->whereKey($ids); + } + + /** + * Create a new Eloquent query builder for the model. + * + * @param \Illuminate\Database\Query\Builder $query + * @return \Illuminate\Database\Eloquent\Builder|static + */ + public function newEloquentBuilder($query) + { + return new Builder($query); + } + + /** + * Get a new query builder instance for the connection. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function newBaseQueryBuilder() + { + return $this->getConnection()->query(); + } + + /** + * Create a new Eloquent Collection instance. + * + * @param array $models + * @return \Illuminate\Database\Eloquent\Collection + */ + public function newCollection(array $models = []) + { + return new Collection($models); + } + + /** + * Create a new pivot model instance. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @param array $attributes + * @param string $table + * @param bool $exists + * @param string|null $using + * @return \Illuminate\Database\Eloquent\Relations\Pivot + */ + public function newPivot(self $parent, array $attributes, $table, $exists, $using = null) + { + return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists) + : Pivot::fromAttributes($parent, $attributes, $table, $exists); + } + + /** + * Determine if the model has a given scope. + * + * @param string $scope + * @return bool + */ + public function hasNamedScope($scope) + { + return method_exists($this, 'scope'.ucfirst($scope)); + } + + /** + * Apply the given named scope if possible. + * + * @param string $scope + * @param array $parameters + * @return mixed + */ + public function callNamedScope($scope, array $parameters = []) + { + return $this->{'scope'.ucfirst($scope)}(...$parameters); + } + + /** + * Convert the model instance to an array. + * + * @return array + */ + public function toArray() + { + return array_merge($this->attributesToArray(), $this->relationsToArray()); + } + + /** + * Convert the model instance to JSON. + * + * @param int $options + * @return string + * + * @throws \Illuminate\Database\Eloquent\JsonEncodingException + */ + public function toJson($options = 0) + { + $json = json_encode($this->jsonSerialize(), $options); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw JsonEncodingException::forModel($this, json_last_error_msg()); + } + + return $json; + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Reload a fresh model instance from the database. + * + * @param array|string $with + * @return static|null + */ + public function fresh($with = []) + { + if (! $this->exists) { + return; + } + + return $this->setKeysForSelectQuery($this->newQueryWithoutScopes()) + ->with(is_string($with) ? func_get_args() : $with) + ->first(); + } + + /** + * Reload the current model instance with fresh attributes from the database. + * + * @return $this + */ + public function refresh() + { + if (! $this->exists) { + return $this; + } + + $this->setRawAttributes( + $this->setKeysForSelectQuery($this->newQueryWithoutScopes())->firstOrFail()->attributes + ); + + $this->load(collect($this->relations)->reject(function ($relation) { + return $relation instanceof Pivot + || (is_object($relation) && in_array(AsPivot::class, class_uses_recursive($relation), true)); + })->keys()->all()); + + $this->syncOriginal(); + + return $this; + } + + /** + * Clone the model into a new, non-existing instance. + * + * @param array|null $except + * @return static + */ + public function replicate(array $except = null) + { + $defaults = [ + $this->getKeyName(), + $this->getCreatedAtColumn(), + $this->getUpdatedAtColumn(), + ]; + + $attributes = Arr::except( + $this->getAttributes(), $except ? array_unique(array_merge($except, $defaults)) : $defaults + ); + + return tap(new static, function ($instance) use ($attributes) { + $instance->setRawAttributes($attributes); + + $instance->setRelations($this->relations); + + $instance->fireModelEvent('replicating', false); + }); + } + + /** + * Determine if two models have the same ID and belong to the same table. + * + * @param \Illuminate\Database\Eloquent\Model|null $model + * @return bool + */ + public function is($model) + { + return ! is_null($model) && + $this->getKey() === $model->getKey() && + $this->getTable() === $model->getTable() && + $this->getConnectionName() === $model->getConnectionName(); + } + + /** + * Determine if two models are not the same. + * + * @param \Illuminate\Database\Eloquent\Model|null $model + * @return bool + */ + public function isNot($model) + { + return ! $this->is($model); + } + + /** + * Get the database connection for the model. + * + * @return \Illuminate\Database\Connection + */ + public function getConnection() + { + return static::resolveConnection($this->getConnectionName()); + } + + /** + * Get the current connection name for the model. + * + * @return string|null + */ + public function getConnectionName() + { + return $this->connection; + } + + /** + * Set the connection associated with the model. + * + * @param string|null $name + * @return $this + */ + public function setConnection($name) + { + $this->connection = $name; + + return $this; + } + + /** + * Resolve a connection instance. + * + * @param string|null $connection + * @return \Illuminate\Database\Connection + */ + public static function resolveConnection($connection = null) + { + return static::$resolver->connection($connection); + } + + /** + * Get the connection resolver instance. + * + * @return \Illuminate\Database\ConnectionResolverInterface + */ + public static function getConnectionResolver() + { + return static::$resolver; + } + + /** + * Set the connection resolver instance. + * + * @param \Illuminate\Database\ConnectionResolverInterface $resolver + * @return void + */ + public static function setConnectionResolver(Resolver $resolver) + { + static::$resolver = $resolver; + } + + /** + * Unset the connection resolver for models. + * + * @return void + */ + public static function unsetConnectionResolver() + { + static::$resolver = null; + } + + /** + * Get the table associated with the model. + * + * @return string + */ + public function getTable() + { + return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this))); + } + + /** + * Set the table associated with the model. + * + * @param string $table + * @return $this + */ + public function setTable($table) + { + $this->table = $table; + + return $this; + } + + /** + * Get the primary key for the model. + * + * @return string + */ + public function getKeyName() + { + return $this->primaryKey; + } + + /** + * Set the primary key for the model. + * + * @param string $key + * @return $this + */ + public function setKeyName($key) + { + $this->primaryKey = $key; + + return $this; + } + + /** + * Get the table qualified key name. + * + * @return string + */ + public function getQualifiedKeyName() + { + return $this->qualifyColumn($this->getKeyName()); + } + + /** + * Get the auto-incrementing key type. + * + * @return string + */ + public function getKeyType() + { + return $this->keyType; + } + + /** + * Set the data type for the primary key. + * + * @param string $type + * @return $this + */ + public function setKeyType($type) + { + $this->keyType = $type; + + return $this; + } + + /** + * Get the value indicating whether the IDs are incrementing. + * + * @return bool + */ + public function getIncrementing() + { + return $this->incrementing; + } + + /** + * Set whether IDs are incrementing. + * + * @param bool $value + * @return $this + */ + public function setIncrementing($value) + { + $this->incrementing = $value; + + return $this; + } + + /** + * Get the value of the model's primary key. + * + * @return mixed + */ + public function getKey() + { + return $this->getAttribute($this->getKeyName()); + } + + /** + * Get the queueable identity for the entity. + * + * @return mixed + */ + public function getQueueableId() + { + return $this->getKey(); + } + + /** + * Get the queueable relationships for the entity. + * + * @return array + */ + public function getQueueableRelations() + { + $relations = []; + + foreach ($this->getRelations() as $key => $relation) { + if (! method_exists($this, $key)) { + continue; + } + + $relations[] = $key; + + if ($relation instanceof QueueableCollection) { + foreach ($relation->getQueueableRelations() as $collectionValue) { + $relations[] = $key.'.'.$collectionValue; + } + } + + if ($relation instanceof QueueableEntity) { + foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) { + $relations[] = $key.'.'.$entityValue; + } + } + } + + return array_unique($relations); + } + + /** + * Get the queueable connection for the entity. + * + * @return string|null + */ + public function getQueueableConnection() + { + return $this->getConnectionName(); + } + + /** + * Get the value of the model's route key. + * + * @return mixed + */ + public function getRouteKey() + { + return $this->getAttribute($this->getRouteKeyName()); + } + + /** + * Get the route key for the model. + * + * @return string + */ + public function getRouteKeyName() + { + return $this->getKeyName(); + } + + /** + * Retrieve the model for a bound value. + * + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + */ + public function resolveRouteBinding($value, $field = null) + { + return $this->resolveRouteBindingQuery($this, $value, $field)->first(); + } + + /** + * Retrieve the model for a bound value. + * + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + */ + public function resolveSoftDeletableRouteBinding($value, $field = null) + { + return $this->resolveRouteBindingQuery($this, $value, $field)->withTrashed()->first(); + } + + /** + * Retrieve the child model for a bound value. + * + * @param string $childType + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + */ + public function resolveChildRouteBinding($childType, $value, $field) + { + return $this->resolveChildRouteBindingQuery($childType, $value, $field)->first(); + } + + /** + * Retrieve the child model for a bound value. + * + * @param string $childType + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + */ + public function resolveSoftDeletableChildRouteBinding($childType, $value, $field) + { + return $this->resolveChildRouteBindingQuery($childType, $value, $field)->withTrashed()->first(); + } + + /** + * Retrieve the child model query for a bound value. + * + * @param string $childType + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Relations\Relation + */ + protected function resolveChildRouteBindingQuery($childType, $value, $field) + { + $relationship = $this->{Str::plural(Str::camel($childType))}(); + + $field = $field ?: $relationship->getRelated()->getRouteKeyName(); + + if ($relationship instanceof HasManyThrough || + $relationship instanceof BelongsToMany) { + $field = $relationship->getRelated()->getTable().'.'.$field; + } + + return $relationship instanceof Model + ? $relationship->resolveRouteBindingQuery($relationship, $value, $field) + : $relationship->getRelated()->resolveRouteBindingQuery($relationship, $value, $field); + } + + /** + * Retrieve the model for a bound value. + * + * @param \Illuminate\Database\Eloquent\Model|Illuminate\Database\Eloquent\Relations\Relation $query + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Relations\Relation + */ + public function resolveRouteBindingQuery($query, $value, $field = null) + { + return $query->where($field ?? $this->getRouteKeyName(), $value); + } + + /** + * Get the default foreign key name for the model. + * + * @return string + */ + public function getForeignKey() + { + return Str::snake(class_basename($this)).'_'.$this->getKeyName(); + } + + /** + * Get the number of models to return per page. + * + * @return int + */ + public function getPerPage() + { + return $this->perPage; + } + + /** + * Set the number of models to return per page. + * + * @param int $perPage + * @return $this + */ + public function setPerPage($perPage) + { + $this->perPage = $perPage; + + return $this; + } + + /** + * Determine if lazy loading is disabled. + * + * @return bool + */ + public static function preventsLazyLoading() + { + return static::$modelsShouldPreventLazyLoading; + } + + /** + * Get the broadcast channel route definition that is associated with the given entity. + * + * @return string + */ + public function broadcastChannelRoute() + { + return str_replace('\\', '.', get_class($this)).'.{'.Str::camel(class_basename($this)).'}'; + } + + /** + * Get the broadcast channel name that is associated with the given entity. + * + * @return string + */ + public function broadcastChannel() + { + return str_replace('\\', '.', get_class($this)).'.'.$this->getKey(); + } + + /** + * Dynamically retrieve attributes on the model. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->getAttribute($key); + } + + /** + * Dynamically set attributes on the model. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function __set($key, $value) + { + $this->setAttribute($key, $value); + } + + /** + * Determine if the given attribute exists. + * + * @param mixed $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return ! is_null($this->getAttribute($offset)); + } + + /** + * Get the value for a given offset. + * + * @param mixed $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->getAttribute($offset); + } + + /** + * Set the value for a given offset. + * + * @param mixed $offset + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + $this->setAttribute($offset, $value); + } + + /** + * Unset the value for a given offset. + * + * @param mixed $offset + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + unset($this->attributes[$offset], $this->relations[$offset]); + } + + /** + * Determine if an attribute or relation exists on the model. + * + * @param string $key + * @return bool + */ + public function __isset($key) + { + return $this->offsetExists($key); + } + + /** + * Unset an attribute on the model. + * + * @param string $key + * @return void + */ + public function __unset($key) + { + $this->offsetUnset($key); + } + + /** + * Handle dynamic method calls into the model. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (in_array($method, ['increment', 'decrement'])) { + return $this->$method(...$parameters); + } + + if ($resolver = (static::$relationResolvers[get_class($this)][$method] ?? null)) { + return $resolver($this); + } + + return $this->forwardCallTo($this->newQuery(), $method, $parameters); + } + + /** + * Handle dynamic static method calls into the model. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public static function __callStatic($method, $parameters) + { + return (new static)->$method(...$parameters); + } + + /** + * Convert the model to its string representation. + * + * @return string + */ + public function __toString() + { + return $this->escapeWhenCastingToString + ? e($this->toJson()) + : $this->toJson(); + } + + /** + * Indicate that the object's string representation should be escaped when __toString is invoked. + * + * @param bool $escape + * @return $this + */ + public function escapeWhenCastingToString($escape = true) + { + $this->escapeWhenCastingToString = $escape; + + return $this; + } + + /** + * Prepare the object for serialization. + * + * @return array + */ + public function __sleep() + { + $this->mergeAttributesFromCachedCasts(); + + $this->classCastCache = []; + $this->attributeCastCache = []; + + return array_keys(get_object_vars($this)); + } + + /** + * When a model is being unserialized, check if it needs to be booted. + * + * @return void + */ + public function __wakeup() + { + $this->bootIfNotBooted(); + + $this->initializeTraits(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/ModelNotFoundException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/ModelNotFoundException.php new file mode 100755 index 0000000..c35598b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/ModelNotFoundException.php @@ -0,0 +1,66 @@ +model = $model; + $this->ids = Arr::wrap($ids); + + $this->message = "No query results for model [{$model}]"; + + if (count($this->ids) > 0) { + $this->message .= ' '.implode(', ', $this->ids); + } else { + $this->message .= '.'; + } + + return $this; + } + + /** + * Get the affected Eloquent model. + * + * @return string + */ + public function getModel() + { + return $this->model; + } + + /** + * Get the affected Eloquent model IDs. + * + * @return int|array + */ + public function getIds() + { + return $this->ids; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Prunable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Prunable.php new file mode 100644 index 0000000..b4ce1b0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Prunable.php @@ -0,0 +1,67 @@ +prunable() + ->when(in_array(SoftDeletes::class, class_uses_recursive(get_class($this))), function ($query) { + $query->withTrashed(); + })->chunkById($chunkSize, function ($models) use (&$total) { + $models->each->prune(); + + $total += $models->count(); + + event(new ModelsPruned(static::class, $total)); + }); + + return $total; + } + + /** + * Get the prunable model query. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public function prunable() + { + throw new LogicException('Please implement the prunable method on your model.'); + } + + /** + * Prune the model in the database. + * + * @return bool|null + */ + public function prune() + { + $this->pruning(); + + return in_array(SoftDeletes::class, class_uses_recursive(get_class($this))) + ? $this->forceDelete() + : $this->delete(); + } + + /** + * Prepare the model for pruning. + * + * @return void + */ + protected function pruning() + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/QueueEntityResolver.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/QueueEntityResolver.php new file mode 100644 index 0000000..22fccf2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/QueueEntityResolver.php @@ -0,0 +1,29 @@ +find($id); + + if ($instance) { + return $instance; + } + + throw new EntityNotFoundException($type, $id); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php new file mode 100755 index 0000000..73257bb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php @@ -0,0 +1,46 @@ +model = $class; + $instance->relation = $relation; + + return $instance; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php new file mode 100755 index 0000000..c17b733 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php @@ -0,0 +1,383 @@ +ownerKey = $ownerKey; + $this->relationName = $relationName; + $this->foreignKey = $foreignKey; + + // In the underlying base relationship class, this variable is referred to as + // the "parent" since most relationships are not inversed. But, since this + // one is we will create a "child" variable for much better readability. + $this->child = $child; + + parent::__construct($query, $child); + } + + /** + * Get the results of the relationship. + * + * @return mixed + */ + public function getResults() + { + if (is_null($this->child->{$this->foreignKey})) { + return $this->getDefaultFor($this->parent); + } + + return $this->query->first() ?: $this->getDefaultFor($this->parent); + } + + /** + * Set the base constraints on the relation query. + * + * @return void + */ + public function addConstraints() + { + if (static::$constraints) { + // For belongs to relationships, which are essentially the inverse of has one + // or has many relationships, we need to actually query on the primary key + // of the related models matching on the foreign key that's on a parent. + $table = $this->related->getTable(); + + $this->query->where($table.'.'.$this->ownerKey, '=', $this->child->{$this->foreignKey}); + } + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + // We'll grab the primary key name of the related models since it could be set to + // a non-standard name and not "id". We will then construct the constraint for + // our eagerly loading query so it returns the proper models from execution. + $key = $this->related->getTable().'.'.$this->ownerKey; + + $whereIn = $this->whereInMethod($this->related, $this->ownerKey); + + $this->query->{$whereIn}($key, $this->getEagerModelKeys($models)); + } + + /** + * Gather the keys from an array of related models. + * + * @param array $models + * @return array + */ + protected function getEagerModelKeys(array $models) + { + $keys = []; + + // First we need to gather all of the keys from the parent models so we know what + // to query for via the eager loading query. We will add them to an array then + // execute a "where in" statement to gather up all of those related records. + foreach ($models as $model) { + if (! is_null($value = $model->{$this->foreignKey})) { + $keys[] = $value; + } + } + + sort($keys); + + return array_values(array_unique($keys)); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->getDefaultFor($model)); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + $foreign = $this->foreignKey; + + $owner = $this->ownerKey; + + // First we will get to build a dictionary of the child models by their primary + // key of the relationship, then we can easily match the children back onto + // the parents using that dictionary and the primary key of the children. + $dictionary = []; + + foreach ($results as $result) { + $attribute = $this->getDictionaryKey($result->getAttribute($owner)); + + $dictionary[$attribute] = $result; + } + + // Once we have the dictionary constructed, we can loop through all the parents + // and match back onto their children using these keys of the dictionary and + // the primary key of the children to map them onto the correct instances. + foreach ($models as $model) { + $attribute = $this->getDictionaryKey($model->{$foreign}); + + if (isset($dictionary[$attribute])) { + $model->setRelation($relation, $dictionary[$attribute]); + } + } + + return $models; + } + + /** + * Associate the model instance to the given parent. + * + * @param \Illuminate\Database\Eloquent\Model|int|string|null $model + * @return \Illuminate\Database\Eloquent\Model + */ + public function associate($model) + { + $ownerKey = $model instanceof Model ? $model->getAttribute($this->ownerKey) : $model; + + $this->child->setAttribute($this->foreignKey, $ownerKey); + + if ($model instanceof Model) { + $this->child->setRelation($this->relationName, $model); + } else { + $this->child->unsetRelation($this->relationName); + } + + return $this->child; + } + + /** + * Dissociate previously associated model from the given parent. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function dissociate() + { + $this->child->setAttribute($this->foreignKey, null); + + return $this->child->setRelation($this->relationName, null); + } + + /** + * Alias of "dissociate" method. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function disassociate() + { + return $this->dissociate(); + } + + /** + * Add the constraints for a relationship query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + if ($parentQuery->getQuery()->from == $query->getQuery()->from) { + return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); + } + + return $query->select($columns)->whereColumn( + $this->getQualifiedForeignKeyName(), '=', $query->qualifyColumn($this->ownerKey) + ); + } + + /** + * Add the constraints for a relationship query on the same table. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) + { + $query->select($columns)->from( + $query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash() + ); + + $query->getModel()->setTable($hash); + + return $query->whereColumn( + $hash.'.'.$this->ownerKey, '=', $this->getQualifiedForeignKeyName() + ); + } + + /** + * Determine if the related model has an auto-incrementing ID. + * + * @return bool + */ + protected function relationHasIncrementingId() + { + return $this->related->getIncrementing() && + in_array($this->related->getKeyType(), ['int', 'integer']); + } + + /** + * Make a new related instance for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return \Illuminate\Database\Eloquent\Model + */ + protected function newRelatedInstanceFor(Model $parent) + { + return $this->related->newInstance(); + } + + /** + * Get the child of the relationship. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function getChild() + { + return $this->child; + } + + /** + * Get the foreign key of the relationship. + * + * @return string + */ + public function getForeignKeyName() + { + return $this->foreignKey; + } + + /** + * Get the fully qualified foreign key of the relationship. + * + * @return string + */ + public function getQualifiedForeignKeyName() + { + return $this->child->qualifyColumn($this->foreignKey); + } + + /** + * Get the key value of the child's foreign key. + * + * @return mixed + */ + public function getParentKey() + { + return $this->child->{$this->foreignKey}; + } + + /** + * Get the associated key of the relationship. + * + * @return string + */ + public function getOwnerKeyName() + { + return $this->ownerKey; + } + + /** + * Get the fully qualified associated key of the relationship. + * + * @return string + */ + public function getQualifiedOwnerKeyName() + { + return $this->related->qualifyColumn($this->ownerKey); + } + + /** + * Get the value of the model's associated key. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return mixed + */ + protected function getRelatedKeyFrom(Model $model) + { + return $model->{$this->ownerKey}; + } + + /** + * Get the name of the relationship. + * + * @return string + */ + public function getRelationName() + { + return $this->relationName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php new file mode 100755 index 0000000..4cadd74 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -0,0 +1,1435 @@ +parentKey = $parentKey; + $this->relatedKey = $relatedKey; + $this->relationName = $relationName; + $this->relatedPivotKey = $relatedPivotKey; + $this->foreignPivotKey = $foreignPivotKey; + $this->table = $this->resolveTableName($table); + + parent::__construct($query, $parent); + } + + /** + * Attempt to resolve the intermediate table name from the given string. + * + * @param string $table + * @return string + */ + protected function resolveTableName($table) + { + if (! Str::contains($table, '\\') || ! class_exists($table)) { + return $table; + } + + $model = new $table; + + if (! $model instanceof Model) { + return $table; + } + + if (in_array(AsPivot::class, class_uses_recursive($model))) { + $this->using($table); + } + + return $model->getTable(); + } + + /** + * Set the base constraints on the relation query. + * + * @return void + */ + public function addConstraints() + { + $this->performJoin(); + + if (static::$constraints) { + $this->addWhereConstraints(); + } + } + + /** + * Set the join clause for the relation query. + * + * @param \Illuminate\Database\Eloquent\Builder|null $query + * @return $this + */ + protected function performJoin($query = null) + { + $query = $query ?: $this->query; + + // We need to join to the intermediate table on the related model's primary + // key column with the intermediate table's foreign key for the related + // model instance. Then we can set the "where" for the parent models. + $query->join( + $this->table, + $this->getQualifiedRelatedKeyName(), + '=', + $this->getQualifiedRelatedPivotKeyName() + ); + + return $this; + } + + /** + * Set the where clause for the relation query. + * + * @return $this + */ + protected function addWhereConstraints() + { + $this->query->where( + $this->getQualifiedForeignPivotKeyName(), '=', $this->parent->{$this->parentKey} + ); + + return $this; + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + $whereIn = $this->whereInMethod($this->parent, $this->parentKey); + + $this->query->{$whereIn}( + $this->getQualifiedForeignPivotKeyName(), + $this->getKeys($models, $this->parentKey) + ); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->related->newCollection()); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + $dictionary = $this->buildDictionary($results); + + // Once we have an array dictionary of child objects we can easily match the + // children back to their parent using the dictionary and the keys on the + // parent models. Then we should return these hydrated models back out. + foreach ($models as $model) { + $key = $this->getDictionaryKey($model->{$this->parentKey}); + + if (isset($dictionary[$key])) { + $model->setRelation( + $relation, $this->related->newCollection($dictionary[$key]) + ); + } + } + + return $models; + } + + /** + * Build model dictionary keyed by the relation's foreign key. + * + * @param \Illuminate\Database\Eloquent\Collection $results + * @return array + */ + protected function buildDictionary(Collection $results) + { + // First we will build a dictionary of child models keyed by the foreign key + // of the relation so that we will easily and quickly match them to their + // parents without having a possibly slow inner loops for every models. + $dictionary = []; + + foreach ($results as $result) { + $value = $this->getDictionaryKey($result->{$this->accessor}->{$this->foreignPivotKey}); + + $dictionary[$value][] = $result; + } + + return $dictionary; + } + + /** + * Get the class being used for pivot models. + * + * @return string + */ + public function getPivotClass() + { + return $this->using ?? Pivot::class; + } + + /** + * Specify the custom pivot model to use for the relationship. + * + * @param string $class + * @return $this + */ + public function using($class) + { + $this->using = $class; + + return $this; + } + + /** + * Specify the custom pivot accessor to use for the relationship. + * + * @param string $accessor + * @return $this + */ + public function as($accessor) + { + $this->accessor = $accessor; + + return $this; + } + + /** + * Set a where clause for a pivot table column. + * + * @param string $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return $this + */ + public function wherePivot($column, $operator = null, $value = null, $boolean = 'and') + { + $this->pivotWheres[] = func_get_args(); + + return $this->where($this->qualifyPivotColumn($column), $operator, $value, $boolean); + } + + /** + * Set a "where between" clause for a pivot table column. + * + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function wherePivotBetween($column, array $values, $boolean = 'and', $not = false) + { + return $this->whereBetween($this->qualifyPivotColumn($column), $values, $boolean, $not); + } + + /** + * Set a "or where between" clause for a pivot table column. + * + * @param string $column + * @param array $values + * @return $this + */ + public function orWherePivotBetween($column, array $values) + { + return $this->wherePivotBetween($column, $values, 'or'); + } + + /** + * Set a "where pivot not between" clause for a pivot table column. + * + * @param string $column + * @param array $values + * @param string $boolean + * @return $this + */ + public function wherePivotNotBetween($column, array $values, $boolean = 'and') + { + return $this->wherePivotBetween($column, $values, $boolean, true); + } + + /** + * Set a "or where not between" clause for a pivot table column. + * + * @param string $column + * @param array $values + * @return $this + */ + public function orWherePivotNotBetween($column, array $values) + { + return $this->wherePivotBetween($column, $values, 'or', true); + } + + /** + * Set a "where in" clause for a pivot table column. + * + * @param string $column + * @param mixed $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function wherePivotIn($column, $values, $boolean = 'and', $not = false) + { + $this->pivotWhereIns[] = func_get_args(); + + return $this->whereIn($this->qualifyPivotColumn($column), $values, $boolean, $not); + } + + /** + * Set an "or where" clause for a pivot table column. + * + * @param string $column + * @param mixed $operator + * @param mixed $value + * @return $this + */ + public function orWherePivot($column, $operator = null, $value = null) + { + return $this->wherePivot($column, $operator, $value, 'or'); + } + + /** + * Set a where clause for a pivot table column. + * + * In addition, new pivot records will receive this value. + * + * @param string|array $column + * @param mixed $value + * @return $this + * + * @throws \InvalidArgumentException + */ + public function withPivotValue($column, $value = null) + { + if (is_array($column)) { + foreach ($column as $name => $value) { + $this->withPivotValue($name, $value); + } + + return $this; + } + + if (is_null($value)) { + throw new InvalidArgumentException('The provided value may not be null.'); + } + + $this->pivotValues[] = compact('column', 'value'); + + return $this->wherePivot($column, '=', $value); + } + + /** + * Set an "or where in" clause for a pivot table column. + * + * @param string $column + * @param mixed $values + * @return $this + */ + public function orWherePivotIn($column, $values) + { + return $this->wherePivotIn($column, $values, 'or'); + } + + /** + * Set a "where not in" clause for a pivot table column. + * + * @param string $column + * @param mixed $values + * @param string $boolean + * @return $this + */ + public function wherePivotNotIn($column, $values, $boolean = 'and') + { + return $this->wherePivotIn($column, $values, $boolean, true); + } + + /** + * Set an "or where not in" clause for a pivot table column. + * + * @param string $column + * @param mixed $values + * @return $this + */ + public function orWherePivotNotIn($column, $values) + { + return $this->wherePivotNotIn($column, $values, 'or'); + } + + /** + * Set a "where null" clause for a pivot table column. + * + * @param string $column + * @param string $boolean + * @param bool $not + * @return $this + */ + public function wherePivotNull($column, $boolean = 'and', $not = false) + { + $this->pivotWhereNulls[] = func_get_args(); + + return $this->whereNull($this->qualifyPivotColumn($column), $boolean, $not); + } + + /** + * Set a "where not null" clause for a pivot table column. + * + * @param string $column + * @param string $boolean + * @return $this + */ + public function wherePivotNotNull($column, $boolean = 'and') + { + return $this->wherePivotNull($column, $boolean, true); + } + + /** + * Set a "or where null" clause for a pivot table column. + * + * @param string $column + * @param bool $not + * @return $this + */ + public function orWherePivotNull($column, $not = false) + { + return $this->wherePivotNull($column, 'or', $not); + } + + /** + * Set a "or where not null" clause for a pivot table column. + * + * @param string $column + * @return $this + */ + public function orWherePivotNotNull($column) + { + return $this->orWherePivotNull($column, true); + } + + /** + * Add an "order by" clause for a pivot table column. + * + * @param string $column + * @param string $direction + * @return $this + */ + public function orderByPivot($column, $direction = 'asc') + { + return $this->orderBy($this->qualifyPivotColumn($column), $direction); + } + + /** + * Find a related model by its primary key or return a new instance of the related model. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model + */ + public function findOrNew($id, $columns = ['*']) + { + if (is_null($instance = $this->find($id, $columns))) { + $instance = $this->related->newInstance(); + } + + return $instance; + } + + /** + * Get the first related model record matching the attributes or instantiate it. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function firstOrNew(array $attributes) + { + if (is_null($instance = $this->where($attributes)->first())) { + $instance = $this->related->newInstance($attributes); + } + + return $instance; + } + + /** + * Get the first related record matching the attributes or create it. + * + * @param array $attributes + * @param array $joining + * @param bool $touch + * @return \Illuminate\Database\Eloquent\Model + */ + public function firstOrCreate(array $attributes, array $joining = [], $touch = true) + { + if (is_null($instance = $this->where($attributes)->first())) { + $instance = $this->create($attributes, $joining, $touch); + } + + return $instance; + } + + /** + * Create or update a related record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @param array $joining + * @param bool $touch + * @return \Illuminate\Database\Eloquent\Model + */ + public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true) + { + if (is_null($instance = $this->where($attributes)->first())) { + return $this->create($values, $joining, $touch); + } + + $instance->fill($values); + + $instance->save(['touch' => false]); + + return $instance; + } + + /** + * Find a related model by its primary key. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null + */ + public function find($id, $columns = ['*']) + { + if (! $id instanceof Model && (is_array($id) || $id instanceof Arrayable)) { + return $this->findMany($id, $columns); + } + + return $this->where( + $this->getRelated()->getQualifiedKeyName(), '=', $this->parseId($id) + )->first($columns); + } + + /** + * Find multiple related models by their primary keys. + * + * @param \Illuminate\Contracts\Support\Arrayable|array $ids + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function findMany($ids, $columns = ['*']) + { + $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; + + if (empty($ids)) { + return $this->getRelated()->newCollection(); + } + + return $this->whereIn( + $this->getRelated()->getQualifiedKeyName(), $this->parseIds($ids) + )->get($columns); + } + + /** + * Find a related model by its primary key or throw an exception. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function findOrFail($id, $columns = ['*']) + { + $result = $this->find($id, $columns); + + $id = $id instanceof Arrayable ? $id->toArray() : $id; + + if (is_array($id)) { + if (count($result) === count(array_unique($id))) { + return $result; + } + } elseif (! is_null($result)) { + return $result; + } + + throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); + } + + /** + * Add a basic where clause to the query, and return the first result. + * + * @param \Closure|string|array $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') + { + return $this->where($column, $operator, $value, $boolean)->first(); + } + + /** + * Execute the query and get the first result. + * + * @param array $columns + * @return mixed + */ + public function first($columns = ['*']) + { + $results = $this->take(1)->get($columns); + + return count($results) > 0 ? $results->first() : null; + } + + /** + * Execute the query and get the first result or throw an exception. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|static + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function firstOrFail($columns = ['*']) + { + if (! is_null($model = $this->first($columns))) { + return $model; + } + + throw (new ModelNotFoundException)->setModel(get_class($this->related)); + } + + /** + * Execute the query and get the first result or call a callback. + * + * @param \Closure|array $columns + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Model|static|mixed + */ + public function firstOr($columns = ['*'], Closure $callback = null) + { + if ($columns instanceof Closure) { + $callback = $columns; + + $columns = ['*']; + } + + if (! is_null($model = $this->first($columns))) { + return $model; + } + + return $callback(); + } + + /** + * Get the results of the relationship. + * + * @return mixed + */ + public function getResults() + { + return ! is_null($this->parent->{$this->parentKey}) + ? $this->get() + : $this->related->newCollection(); + } + + /** + * Execute the query as a "select" statement. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function get($columns = ['*']) + { + // First we'll add the proper select columns onto the query so it is run with + // the proper columns. Then, we will get the results and hydrate our pivot + // models with the result of those columns as a separate model relation. + $builder = $this->query->applyScopes(); + + $columns = $builder->getQuery()->columns ? [] : $columns; + + $models = $builder->addSelect( + $this->shouldSelect($columns) + )->getModels(); + + $this->hydratePivotRelation($models); + + // If we actually found models we will also eager load any relationships that + // have been specified as needing to be eager loaded. This will solve the + // n + 1 query problem for the developer and also increase performance. + if (count($models) > 0) { + $models = $builder->eagerLoadRelations($models); + } + + return $this->related->newCollection($models); + } + + /** + * Get the select columns for the relation query. + * + * @param array $columns + * @return array + */ + protected function shouldSelect(array $columns = ['*']) + { + if ($columns == ['*']) { + $columns = [$this->related->getTable().'.*']; + } + + return array_merge($columns, $this->aliasedPivotColumns()); + } + + /** + * Get the pivot columns for the relation. + * + * "pivot_" is prefixed ot each column for easy removal later. + * + * @return array + */ + protected function aliasedPivotColumns() + { + $defaults = [$this->foreignPivotKey, $this->relatedPivotKey]; + + return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { + return $this->qualifyPivotColumn($column).' as pivot_'.$column; + })->unique()->all(); + } + + /** + * Get a paginator for the "select" statement. + * + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + */ + public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) + { + $this->query->addSelect($this->shouldSelect($columns)); + + return tap($this->query->paginate($perPage, $columns, $pageName, $page), function ($paginator) { + $this->hydratePivotRelation($paginator->items()); + }); + } + + /** + * Paginate the given query into a simple paginator. + * + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\Paginator + */ + public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) + { + $this->query->addSelect($this->shouldSelect($columns)); + + return tap($this->query->simplePaginate($perPage, $columns, $pageName, $page), function ($paginator) { + $this->hydratePivotRelation($paginator->items()); + }); + } + + /** + * Paginate the given query into a cursor paginator. + * + * @param int|null $perPage + * @param array $columns + * @param string $cursorName + * @param string|null $cursor + * @return \Illuminate\Contracts\Pagination\CursorPaginator + */ + public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null) + { + $this->query->addSelect($this->shouldSelect($columns)); + + return tap($this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor), function ($paginator) { + $this->hydratePivotRelation($paginator->items()); + }); + } + + /** + * Chunk the results of the query. + * + * @param int $count + * @param callable $callback + * @return bool + */ + public function chunk($count, callable $callback) + { + return $this->prepareQueryBuilder()->chunk($count, function ($results, $page) use ($callback) { + $this->hydratePivotRelation($results->all()); + + return $callback($results, $page); + }); + } + + /** + * Chunk the results of a query by comparing numeric IDs. + * + * @param int $count + * @param callable $callback + * @param string|null $column + * @param string|null $alias + * @return bool + */ + public function chunkById($count, callable $callback, $column = null, $alias = null) + { + $this->prepareQueryBuilder(); + + $column = $column ?? $this->getRelated()->qualifyColumn( + $this->getRelatedKeyName() + ); + + $alias = $alias ?? $this->getRelatedKeyName(); + + return $this->query->chunkById($count, function ($results) use ($callback) { + $this->hydratePivotRelation($results->all()); + + return $callback($results); + }, $column, $alias); + } + + /** + * Execute a callback over each item while chunking. + * + * @param callable $callback + * @param int $count + * @return bool + */ + public function each(callable $callback, $count = 1000) + { + return $this->chunk($count, function ($results) use ($callback) { + foreach ($results as $key => $value) { + if ($callback($value, $key) === false) { + return false; + } + } + }); + } + + /** + * Query lazily, by chunks of the given size. + * + * @param int $chunkSize + * @return \Illuminate\Support\LazyCollection + */ + public function lazy($chunkSize = 1000) + { + return $this->prepareQueryBuilder()->lazy($chunkSize)->map(function ($model) { + $this->hydratePivotRelation([$model]); + + return $model; + }); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @return \Illuminate\Support\LazyCollection + */ + public function lazyById($chunkSize = 1000, $column = null, $alias = null) + { + $column = $column ?? $this->getRelated()->qualifyColumn( + $this->getRelatedKeyName() + ); + + $alias = $alias ?? $this->getRelatedKeyName(); + + return $this->prepareQueryBuilder()->lazyById($chunkSize, $column, $alias)->map(function ($model) { + $this->hydratePivotRelation([$model]); + + return $model; + }); + } + + /** + * Get a lazy collection for the given query. + * + * @return \Illuminate\Support\LazyCollection + */ + public function cursor() + { + return $this->prepareQueryBuilder()->cursor()->map(function ($model) { + $this->hydratePivotRelation([$model]); + + return $model; + }); + } + + /** + * Prepare the query builder for query execution. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function prepareQueryBuilder() + { + return $this->query->addSelect($this->shouldSelect()); + } + + /** + * Hydrate the pivot table relationship on the models. + * + * @param array $models + * @return void + */ + protected function hydratePivotRelation(array $models) + { + // To hydrate the pivot relationship, we will just gather the pivot attributes + // and create a new Pivot model, which is basically a dynamic model that we + // will set the attributes, table, and connections on it so it will work. + foreach ($models as $model) { + $model->setRelation($this->accessor, $this->newExistingPivot( + $this->migratePivotAttributes($model) + )); + } + } + + /** + * Get the pivot attributes from a model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return array + */ + protected function migratePivotAttributes(Model $model) + { + $values = []; + + foreach ($model->getAttributes() as $key => $value) { + // To get the pivots attributes we will just take any of the attributes which + // begin with "pivot_" and add those to this arrays, as well as unsetting + // them from the parent's models since they exist in a different table. + if (strpos($key, 'pivot_') === 0) { + $values[substr($key, 6)] = $value; + + unset($model->$key); + } + } + + return $values; + } + + /** + * If we're touching the parent model, touch. + * + * @return void + */ + public function touchIfTouching() + { + if ($this->touchingParent()) { + $this->getParent()->touch(); + } + + if ($this->getParent()->touches($this->relationName)) { + $this->touch(); + } + } + + /** + * Determine if we should touch the parent on sync. + * + * @return bool + */ + protected function touchingParent() + { + return $this->getRelated()->touches($this->guessInverseRelation()); + } + + /** + * Attempt to guess the name of the inverse of the relation. + * + * @return string + */ + protected function guessInverseRelation() + { + return Str::camel(Str::pluralStudly(class_basename($this->getParent()))); + } + + /** + * Touch all of the related models for the relationship. + * + * E.g.: Touch all roles associated with this user. + * + * @return void + */ + public function touch() + { + $key = $this->getRelated()->getKeyName(); + + $columns = [ + $this->related->getUpdatedAtColumn() => $this->related->freshTimestampString(), + ]; + + // If we actually have IDs for the relation, we will run the query to update all + // the related model's timestamps, to make sure these all reflect the changes + // to the parent models. This will help us keep any caching synced up here. + if (count($ids = $this->allRelatedIds()) > 0) { + $this->getRelated()->newQueryWithoutRelationships()->whereIn($key, $ids)->update($columns); + } + } + + /** + * Get all of the IDs for the related models. + * + * @return \Illuminate\Support\Collection + */ + public function allRelatedIds() + { + return $this->newPivotQuery()->pluck($this->relatedPivotKey); + } + + /** + * Save a new model and attach it to the parent model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param array $pivotAttributes + * @param bool $touch + * @return \Illuminate\Database\Eloquent\Model + */ + public function save(Model $model, array $pivotAttributes = [], $touch = true) + { + $model->save(['touch' => false]); + + $this->attach($model, $pivotAttributes, $touch); + + return $model; + } + + /** + * Save an array of new models and attach them to the parent model. + * + * @param \Illuminate\Support\Collection|array $models + * @param array $pivotAttributes + * @return array + */ + public function saveMany($models, array $pivotAttributes = []) + { + foreach ($models as $key => $model) { + $this->save($model, (array) ($pivotAttributes[$key] ?? []), false); + } + + $this->touchIfTouching(); + + return $models; + } + + /** + * Create a new instance of the related model. + * + * @param array $attributes + * @param array $joining + * @param bool $touch + * @return \Illuminate\Database\Eloquent\Model + */ + public function create(array $attributes = [], array $joining = [], $touch = true) + { + $instance = $this->related->newInstance($attributes); + + // Once we save the related model, we need to attach it to the base model via + // through intermediate table so we'll use the existing "attach" method to + // accomplish this which will insert the record and any more attributes. + $instance->save(['touch' => false]); + + $this->attach($instance, $joining, $touch); + + return $instance; + } + + /** + * Create an array of new instances of the related models. + * + * @param iterable $records + * @param array $joinings + * @return array + */ + public function createMany(iterable $records, array $joinings = []) + { + $instances = []; + + foreach ($records as $key => $record) { + $instances[] = $this->create($record, (array) ($joinings[$key] ?? []), false); + } + + $this->touchIfTouching(); + + return $instances; + } + + /** + * Add the constraints for a relationship query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + if ($parentQuery->getQuery()->from == $query->getQuery()->from) { + return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns); + } + + $this->performJoin($query); + + return parent::getRelationExistenceQuery($query, $parentQuery, $columns); + } + + /** + * Add the constraints for a relationship query on the same table. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*']) + { + $query->select($columns); + + $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash()); + + $this->related->setTable($hash); + + $this->performJoin($query); + + return parent::getRelationExistenceQuery($query, $parentQuery, $columns); + } + + /** + * Get the key for comparing against the parent key in "has" query. + * + * @return string + */ + public function getExistenceCompareKey() + { + return $this->getQualifiedForeignPivotKeyName(); + } + + /** + * Specify that the pivot table has creation and update timestamps. + * + * @param mixed $createdAt + * @param mixed $updatedAt + * @return $this + */ + public function withTimestamps($createdAt = null, $updatedAt = null) + { + $this->withTimestamps = true; + + $this->pivotCreatedAt = $createdAt; + $this->pivotUpdatedAt = $updatedAt; + + return $this->withPivot($this->createdAt(), $this->updatedAt()); + } + + /** + * Get the name of the "created at" column. + * + * @return string + */ + public function createdAt() + { + return $this->pivotCreatedAt ?: $this->parent->getCreatedAtColumn(); + } + + /** + * Get the name of the "updated at" column. + * + * @return string + */ + public function updatedAt() + { + return $this->pivotUpdatedAt ?: $this->parent->getUpdatedAtColumn(); + } + + /** + * Get the foreign key for the relation. + * + * @return string + */ + public function getForeignPivotKeyName() + { + return $this->foreignPivotKey; + } + + /** + * Get the fully qualified foreign key for the relation. + * + * @return string + */ + public function getQualifiedForeignPivotKeyName() + { + return $this->qualifyPivotColumn($this->foreignPivotKey); + } + + /** + * Get the "related key" for the relation. + * + * @return string + */ + public function getRelatedPivotKeyName() + { + return $this->relatedPivotKey; + } + + /** + * Get the fully qualified "related key" for the relation. + * + * @return string + */ + public function getQualifiedRelatedPivotKeyName() + { + return $this->qualifyPivotColumn($this->relatedPivotKey); + } + + /** + * Get the parent key for the relationship. + * + * @return string + */ + public function getParentKeyName() + { + return $this->parentKey; + } + + /** + * Get the fully qualified parent key name for the relation. + * + * @return string + */ + public function getQualifiedParentKeyName() + { + return $this->parent->qualifyColumn($this->parentKey); + } + + /** + * Get the related key for the relationship. + * + * @return string + */ + public function getRelatedKeyName() + { + return $this->relatedKey; + } + + /** + * Get the fully qualified related key name for the relation. + * + * @return string + */ + public function getQualifiedRelatedKeyName() + { + return $this->related->qualifyColumn($this->relatedKey); + } + + /** + * Get the intermediate table for the relationship. + * + * @return string + */ + public function getTable() + { + return $this->table; + } + + /** + * Get the relationship name for the relationship. + * + * @return string + */ + public function getRelationName() + { + return $this->relationName; + } + + /** + * Get the name of the pivot accessor for this relationship. + * + * @return string + */ + public function getPivotAccessor() + { + return $this->accessor; + } + + /** + * Get the pivot columns for this relationship. + * + * @return array + */ + public function getPivotColumns() + { + return $this->pivotColumns; + } + + /** + * Qualify the given column name by the pivot table. + * + * @param string $column + * @return string + */ + public function qualifyPivotColumn($column) + { + return Str::contains($column, '.') + ? $column + : $this->table.'.'.$column; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php new file mode 100644 index 0000000..af9defb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php @@ -0,0 +1,332 @@ +timestamps = $instance->hasTimestampAttributes($attributes); + + // The pivot model is a "dynamic" model since we will set the tables dynamically + // for the instance. This allows it work for any intermediate tables for the + // many to many relationship that are defined by this developer's classes. + $instance->setConnection($parent->getConnectionName()) + ->setTable($table) + ->forceFill($attributes) + ->syncOriginal(); + + // We store off the parent instance so we will access the timestamp column names + // for the model, since the pivot model timestamps aren't easily configurable + // from the developer's point of view. We can use the parents to get these. + $instance->pivotParent = $parent; + + $instance->exists = $exists; + + return $instance; + } + + /** + * Create a new pivot model from raw values returned from a query. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @param array $attributes + * @param string $table + * @param bool $exists + * @return static + */ + public static function fromRawAttributes(Model $parent, $attributes, $table, $exists = false) + { + $instance = static::fromAttributes($parent, [], $table, $exists); + + $instance->timestamps = $instance->hasTimestampAttributes($attributes); + + $instance->setRawAttributes($attributes, $exists); + + return $instance; + } + + /** + * Set the keys for a select query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function setKeysForSelectQuery($query) + { + if (isset($this->attributes[$this->getKeyName()])) { + return parent::setKeysForSelectQuery($query); + } + + $query->where($this->foreignKey, $this->getOriginal( + $this->foreignKey, $this->getAttribute($this->foreignKey) + )); + + return $query->where($this->relatedKey, $this->getOriginal( + $this->relatedKey, $this->getAttribute($this->relatedKey) + )); + } + + /** + * Set the keys for a save update query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function setKeysForSaveQuery($query) + { + return $this->setKeysForSelectQuery($query); + } + + /** + * Delete the pivot model record from the database. + * + * @return int + */ + public function delete() + { + if (isset($this->attributes[$this->getKeyName()])) { + return (int) parent::delete(); + } + + if ($this->fireModelEvent('deleting') === false) { + return 0; + } + + $this->touchOwners(); + + return tap($this->getDeleteQuery()->delete(), function () { + $this->exists = false; + + $this->fireModelEvent('deleted', false); + }); + } + + /** + * Get the query builder for a delete operation on the pivot. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function getDeleteQuery() + { + return $this->newQueryWithoutRelationships()->where([ + $this->foreignKey => $this->getOriginal($this->foreignKey, $this->getAttribute($this->foreignKey)), + $this->relatedKey => $this->getOriginal($this->relatedKey, $this->getAttribute($this->relatedKey)), + ]); + } + + /** + * Get the table associated with the model. + * + * @return string + */ + public function getTable() + { + if (! isset($this->table)) { + $this->setTable(str_replace( + '\\', '', Str::snake(Str::singular(class_basename($this))) + )); + } + + return $this->table; + } + + /** + * Get the foreign key column name. + * + * @return string + */ + public function getForeignKey() + { + return $this->foreignKey; + } + + /** + * Get the "related key" column name. + * + * @return string + */ + public function getRelatedKey() + { + return $this->relatedKey; + } + + /** + * Get the "related key" column name. + * + * @return string + */ + public function getOtherKey() + { + return $this->getRelatedKey(); + } + + /** + * Set the key names for the pivot model instance. + * + * @param string $foreignKey + * @param string $relatedKey + * @return $this + */ + public function setPivotKeys($foreignKey, $relatedKey) + { + $this->foreignKey = $foreignKey; + + $this->relatedKey = $relatedKey; + + return $this; + } + + /** + * Determine if the pivot model or given attributes has timestamp attributes. + * + * @param array|null $attributes + * @return bool + */ + public function hasTimestampAttributes($attributes = null) + { + return array_key_exists($this->getCreatedAtColumn(), $attributes ?? $this->attributes); + } + + /** + * Get the name of the "created at" column. + * + * @return string + */ + public function getCreatedAtColumn() + { + return $this->pivotParent + ? $this->pivotParent->getCreatedAtColumn() + : parent::getCreatedAtColumn(); + } + + /** + * Get the name of the "updated at" column. + * + * @return string + */ + public function getUpdatedAtColumn() + { + return $this->pivotParent + ? $this->pivotParent->getUpdatedAtColumn() + : parent::getUpdatedAtColumn(); + } + + /** + * Get the queueable identity for the entity. + * + * @return mixed + */ + public function getQueueableId() + { + if (isset($this->attributes[$this->getKeyName()])) { + return $this->getKey(); + } + + return sprintf( + '%s:%s:%s:%s', + $this->foreignKey, $this->getAttribute($this->foreignKey), + $this->relatedKey, $this->getAttribute($this->relatedKey) + ); + } + + /** + * Get a new query to restore one or more models by their queueable IDs. + * + * @param int[]|string[]|string $ids + * @return \Illuminate\Database\Eloquent\Builder + */ + public function newQueryForRestoration($ids) + { + if (is_array($ids)) { + return $this->newQueryForCollectionRestoration($ids); + } + + if (! Str::contains($ids, ':')) { + return parent::newQueryForRestoration($ids); + } + + $segments = explode(':', $ids); + + return $this->newQueryWithoutScopes() + ->where($segments[0], $segments[1]) + ->where($segments[2], $segments[3]); + } + + /** + * Get a new query to restore multiple models by their queueable IDs. + * + * @param int[]|string[] $ids + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function newQueryForCollectionRestoration(array $ids) + { + $ids = array_values($ids); + + if (! Str::contains($ids[0], ':')) { + return parent::newQueryForRestoration($ids); + } + + $query = $this->newQueryWithoutScopes(); + + foreach ($ids as $id) { + $segments = explode(':', $id); + + $query->orWhere(function ($query) use ($segments) { + return $query->where($segments[0], $segments[1]) + ->where($segments[2], $segments[3]); + }); + } + + return $query; + } + + /** + * Unset all the loaded relations for the instance. + * + * @return $this + */ + public function unsetRelations() + { + $this->pivotParent = null; + $this->relations = []; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php new file mode 100644 index 0000000..6f6b1b7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php @@ -0,0 +1,313 @@ +isOneOfMany = true; + + $this->relationName = $relation ?: $this->getDefaultOneOfManyJoinAlias( + $this->guessRelationship() + ); + + $keyName = $this->query->getModel()->getKeyName(); + + $columns = is_string($columns = $column) ? [ + $column => $aggregate, + $keyName => $aggregate, + ] : $column; + + if (! array_key_exists($keyName, $columns)) { + $columns[$keyName] = 'MAX'; + } + + if ($aggregate instanceof Closure) { + $closure = $aggregate; + } + + foreach ($columns as $column => $aggregate) { + if (! in_array(strtolower($aggregate), ['min', 'max'])) { + throw new InvalidArgumentException("Invalid aggregate [{$aggregate}] used within ofMany relation. Available aggregates: MIN, MAX"); + } + + $subQuery = $this->newOneOfManySubQuery( + $this->getOneOfManySubQuerySelectColumns(), + $column, $aggregate + ); + + if (isset($previous)) { + $this->addOneOfManyJoinSubQuery($subQuery, $previous['subQuery'], $previous['column']); + } + + if (isset($closure)) { + $closure($subQuery); + } + + if (! isset($previous)) { + $this->oneOfManySubQuery = $subQuery; + } + + if (array_key_last($columns) == $column) { + $this->addOneOfManyJoinSubQuery($this->query, $subQuery, $column); + } + + $previous = [ + 'subQuery' => $subQuery, + 'column' => $column, + ]; + } + + $this->addConstraints(); + + $columns = $this->query->getQuery()->columns; + + if (is_null($columns) || $columns === ['*']) { + $this->select([$this->qualifyColumn('*')]); + } + + return $this; + } + + /** + * Indicate that the relation is the latest single result of a larger one-to-many relationship. + * + * @param string|array|null $column + * @param string|Closure|null $aggregate + * @param string|null $relation + * @return $this + */ + public function latestOfMany($column = 'id', $relation = null) + { + return $this->ofMany(collect(Arr::wrap($column))->mapWithKeys(function ($column) { + return [$column => 'MAX']; + })->all(), 'MAX', $relation); + } + + /** + * Indicate that the relation is the oldest single result of a larger one-to-many relationship. + * + * @param string|array|null $column + * @param string|Closure|null $aggregate + * @param string|null $relation + * @return $this + */ + public function oldestOfMany($column = 'id', $relation = null) + { + return $this->ofMany(collect(Arr::wrap($column))->mapWithKeys(function ($column) { + return [$column => 'MIN']; + })->all(), 'MIN', $relation); + } + + /** + * Get the default alias for the one of many inner join clause. + * + * @param string $relation + * @return string + */ + protected function getDefaultOneOfManyJoinAlias($relation) + { + return $relation == $this->query->getModel()->getTable() + ? $relation.'_of_many' + : $relation; + } + + /** + * Get a new query for the related model, grouping the query by the given column, often the foreign key of the relationship. + * + * @param string|array $groupBy + * @param string|null $column + * @param string|null $aggregate + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function newOneOfManySubQuery($groupBy, $column = null, $aggregate = null) + { + $subQuery = $this->query->getModel() + ->newQuery() + ->withoutGlobalScopes($this->removedScopes()); + + foreach (Arr::wrap($groupBy) as $group) { + $subQuery->groupBy($this->qualifyRelatedColumn($group)); + } + + if (! is_null($column)) { + $subQuery->selectRaw($aggregate.'('.$subQuery->getQuery()->grammar->wrap($subQuery->qualifyColumn($column)).') as '.$subQuery->getQuery()->grammar->wrap($column.'_aggregate')); + } + + $this->addOneOfManySubQueryConstraints($subQuery, $groupBy, $column, $aggregate); + + return $subQuery; + } + + /** + * Add the join subquery to the given query on the given column and the relationship's foreign key. + * + * @param \Illuminate\Database\Eloquent\Builder $parent + * @param \Illuminate\Database\Eloquent\Builder $subQuery + * @param string $on + * @return void + */ + protected function addOneOfManyJoinSubQuery(Builder $parent, Builder $subQuery, $on) + { + $parent->beforeQuery(function ($parent) use ($subQuery, $on) { + $subQuery->applyBeforeQueryCallbacks(); + + $parent->joinSub($subQuery, $this->relationName, function ($join) use ($on) { + $join->on($this->qualifySubSelectColumn($on.'_aggregate'), '=', $this->qualifyRelatedColumn($on)); + + $this->addOneOfManyJoinSubQueryConstraints($join, $on); + }); + }); + } + + /** + * Merge the relationship query joins to the given query builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return void + */ + protected function mergeOneOfManyJoinsTo(Builder $query) + { + $query->getQuery()->beforeQueryCallbacks = $this->query->getQuery()->beforeQueryCallbacks; + + $query->applyBeforeQueryCallbacks(); + } + + /** + * Get the query builder that will contain the relationship constraints. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function getRelationQuery() + { + return $this->isOneOfMany() + ? $this->oneOfManySubQuery + : $this->query; + } + + /** + * Get the one of many inner join subselect builder instance. + * + * @return \Illuminate\Database\Eloquent\Builder|void + */ + public function getOneOfManySubQuery() + { + return $this->oneOfManySubQuery; + } + + /** + * Get the qualified column name for the one-of-many relationship using the subselect join query's alias. + * + * @param string $column + * @return string + */ + public function qualifySubSelectColumn($column) + { + return $this->getRelationName().'.'.last(explode('.', $column)); + } + + /** + * Qualify related column using the related table name if it is not already qualified. + * + * @param string $column + * @return string + */ + protected function qualifyRelatedColumn($column) + { + return Str::contains($column, '.') ? $column : $this->query->getModel()->getTable().'.'.$column; + } + + /** + * Guess the "hasOne" relationship's name via backtrace. + * + * @return string + */ + protected function guessRelationship() + { + return debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function']; + } + + /** + * Determine whether the relationship is a one-of-many relationship. + * + * @return bool + */ + public function isOneOfMany() + { + return $this->isOneOfMany; + } + + /** + * Get the name of the relationship. + * + * @return string + */ + public function getRelationName() + { + return $this->relationName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/ComparesRelatedModels.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/ComparesRelatedModels.php new file mode 100644 index 0000000..ca06698 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/ComparesRelatedModels.php @@ -0,0 +1,77 @@ +compareKeys($this->getParentKey(), $this->getRelatedKeyFrom($model)) && + $this->related->getTable() === $model->getTable() && + $this->related->getConnectionName() === $model->getConnectionName(); + + if ($match && $this instanceof SupportsPartialRelations && $this->isOneOfMany()) { + return $this->query + ->whereKey($model->getKey()) + ->exists(); + } + + return $match; + } + + /** + * Determine if the model is not the related instance of the relationship. + * + * @param \Illuminate\Database\Eloquent\Model|null $model + * @return bool + */ + public function isNot($model) + { + return ! $this->is($model); + } + + /** + * Get the value of the parent model's key. + * + * @return mixed + */ + abstract public function getParentKey(); + + /** + * Get the value of the model's related key. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return mixed + */ + abstract protected function getRelatedKeyFrom(Model $model); + + /** + * Compare the parent key with the related key. + * + * @param mixed $parentKey + * @param mixed $relatedKey + * @return bool + */ + protected function compareKeys($parentKey, $relatedKey) + { + if (empty($parentKey) || empty($relatedKey)) { + return false; + } + + if (is_int($parentKey) || is_int($relatedKey)) { + return (int) $parentKey === (int) $relatedKey; + } + + return $parentKey === $relatedKey; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithDictionary.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithDictionary.php new file mode 100644 index 0000000..ba4ae9a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithDictionary.php @@ -0,0 +1,35 @@ +__toString(); + } + + if (function_exists('enum_exists') && + $attribute instanceof BackedEnum) { + return $attribute->value; + } + + throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.'); + } + + return $attribute; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php new file mode 100644 index 0000000..7a1cbfa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -0,0 +1,686 @@ + [], 'detached' => [], + ]; + + $records = $this->formatRecordsList($this->parseIds($ids)); + + // Next, we will determine which IDs should get removed from the join table by + // checking which of the given ID/records is in the list of current records + // and removing all of those rows from this "intermediate" joining table. + $detach = array_values(array_intersect( + $this->newPivotQuery()->pluck($this->relatedPivotKey)->all(), + array_keys($records) + )); + + if (count($detach) > 0) { + $this->detach($detach, false); + + $changes['detached'] = $this->castKeys($detach); + } + + // Finally, for all of the records which were not "detached", we'll attach the + // records into the intermediate table. Then, we will add those attaches to + // this change list and get ready to return these results to the callers. + $attach = array_diff_key($records, array_flip($detach)); + + if (count($attach) > 0) { + $this->attach($attach, [], false); + + $changes['attached'] = array_keys($attach); + } + + // Once we have finished attaching or detaching the records, we will see if we + // have done any attaching or detaching, and if we have we will touch these + // relationships if they are configured to touch on any database updates. + if ($touch && (count($changes['attached']) || + count($changes['detached']))) { + $this->touchIfTouching(); + } + + return $changes; + } + + /** + * Sync the intermediate tables with a list of IDs without detaching. + * + * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids + * @return array + */ + public function syncWithoutDetaching($ids) + { + return $this->sync($ids, false); + } + + /** + * Sync the intermediate tables with a list of IDs or collection of models. + * + * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids + * @param bool $detaching + * @return array + */ + public function sync($ids, $detaching = true) + { + $changes = [ + 'attached' => [], 'detached' => [], 'updated' => [], + ]; + + // First we need to attach any of the associated models that are not currently + // in this joining table. We'll spin through the given IDs, checking to see + // if they exist in the array of current ones, and if not we will insert. + $current = $this->getCurrentlyAttachedPivots() + ->pluck($this->relatedPivotKey)->all(); + + $detach = array_diff($current, array_keys( + $records = $this->formatRecordsList($this->parseIds($ids)) + )); + + // Next, we will take the differences of the currents and given IDs and detach + // all of the entities that exist in the "current" array but are not in the + // array of the new IDs given to the method which will complete the sync. + if ($detaching && count($detach) > 0) { + $this->detach($detach); + + $changes['detached'] = $this->castKeys($detach); + } + + // Now we are finally ready to attach the new records. Note that we'll disable + // touching until after the entire operation is complete so we don't fire a + // ton of touch operations until we are totally done syncing the records. + $changes = array_merge( + $changes, $this->attachNew($records, $current, false) + ); + + // Once we have finished attaching or detaching the records, we will see if we + // have done any attaching or detaching, and if we have we will touch these + // relationships if they are configured to touch on any database updates. + if (count($changes['attached']) || + count($changes['updated']) || + count($changes['detached'])) { + $this->touchIfTouching(); + } + + return $changes; + } + + /** + * Sync the intermediate tables with a list of IDs or collection of models with the given pivot values. + * + * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids + * @param array $values + * @param bool $detaching + * @return array + */ + public function syncWithPivotValues($ids, array $values, bool $detaching = true) + { + return $this->sync(collect($this->parseIds($ids))->mapWithKeys(function ($id) use ($values) { + return [$id => $values]; + }), $detaching); + } + + /** + * Format the sync / toggle record list so that it is keyed by ID. + * + * @param array $records + * @return array + */ + protected function formatRecordsList(array $records) + { + return collect($records)->mapWithKeys(function ($attributes, $id) { + if (! is_array($attributes)) { + [$id, $attributes] = [$attributes, []]; + } + + return [$id => $attributes]; + })->all(); + } + + /** + * Attach all of the records that aren't in the given current records. + * + * @param array $records + * @param array $current + * @param bool $touch + * @return array + */ + protected function attachNew(array $records, array $current, $touch = true) + { + $changes = ['attached' => [], 'updated' => []]; + + foreach ($records as $id => $attributes) { + // If the ID is not in the list of existing pivot IDs, we will insert a new pivot + // record, otherwise, we will just update this existing record on this joining + // table, so that the developers will easily update these records pain free. + if (! in_array($id, $current)) { + $this->attach($id, $attributes, $touch); + + $changes['attached'][] = $this->castKey($id); + } + + // Now we'll try to update an existing pivot record with the attributes that were + // given to the method. If the model is actually updated we will add it to the + // list of updated pivot records so we return them back out to the consumer. + elseif (count($attributes) > 0 && + $this->updateExistingPivot($id, $attributes, $touch)) { + $changes['updated'][] = $this->castKey($id); + } + } + + return $changes; + } + + /** + * Update an existing pivot record on the table. + * + * @param mixed $id + * @param array $attributes + * @param bool $touch + * @return int + */ + public function updateExistingPivot($id, array $attributes, $touch = true) + { + if ($this->using && + empty($this->pivotWheres) && + empty($this->pivotWhereIns) && + empty($this->pivotWhereNulls)) { + return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch); + } + + if (in_array($this->updatedAt(), $this->pivotColumns)) { + $attributes = $this->addTimestampsToAttachment($attributes, true); + } + + $updated = $this->newPivotStatementForId($this->parseId($id))->update( + $this->castAttributes($attributes) + ); + + if ($touch) { + $this->touchIfTouching(); + } + + return $updated; + } + + /** + * Update an existing pivot record on the table via a custom class. + * + * @param mixed $id + * @param array $attributes + * @param bool $touch + * @return int + */ + protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch) + { + $pivot = $this->getCurrentlyAttachedPivots() + ->where($this->foreignPivotKey, $this->parent->{$this->parentKey}) + ->where($this->relatedPivotKey, $this->parseId($id)) + ->first(); + + $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false; + + if ($updated) { + $pivot->save(); + } + + if ($touch) { + $this->touchIfTouching(); + } + + return (int) $updated; + } + + /** + * Attach a model to the parent. + * + * @param mixed $id + * @param array $attributes + * @param bool $touch + * @return void + */ + public function attach($id, array $attributes = [], $touch = true) + { + if ($this->using) { + $this->attachUsingCustomClass($id, $attributes); + } else { + // Here we will insert the attachment records into the pivot table. Once we have + // inserted the records, we will touch the relationships if necessary and the + // function will return. We can parse the IDs before inserting the records. + $this->newPivotStatement()->insert($this->formatAttachRecords( + $this->parseIds($id), $attributes + )); + } + + if ($touch) { + $this->touchIfTouching(); + } + } + + /** + * Attach a model to the parent using a custom class. + * + * @param mixed $id + * @param array $attributes + * @return void + */ + protected function attachUsingCustomClass($id, array $attributes) + { + $records = $this->formatAttachRecords( + $this->parseIds($id), $attributes + ); + + foreach ($records as $record) { + $this->newPivot($record, false)->save(); + } + } + + /** + * Create an array of records to insert into the pivot table. + * + * @param array $ids + * @param array $attributes + * @return array + */ + protected function formatAttachRecords($ids, array $attributes) + { + $records = []; + + $hasTimestamps = ($this->hasPivotColumn($this->createdAt()) || + $this->hasPivotColumn($this->updatedAt())); + + // To create the attachment records, we will simply spin through the IDs given + // and create a new record to insert for each ID. Each ID may actually be a + // key in the array, with extra attributes to be placed in other columns. + foreach ($ids as $key => $value) { + $records[] = $this->formatAttachRecord( + $key, $value, $attributes, $hasTimestamps + ); + } + + return $records; + } + + /** + * Create a full attachment record payload. + * + * @param int $key + * @param mixed $value + * @param array $attributes + * @param bool $hasTimestamps + * @return array + */ + protected function formatAttachRecord($key, $value, $attributes, $hasTimestamps) + { + [$id, $attributes] = $this->extractAttachIdAndAttributes($key, $value, $attributes); + + return array_merge( + $this->baseAttachRecord($id, $hasTimestamps), $this->castAttributes($attributes) + ); + } + + /** + * Get the attach record ID and extra attributes. + * + * @param mixed $key + * @param mixed $value + * @param array $attributes + * @return array + */ + protected function extractAttachIdAndAttributes($key, $value, array $attributes) + { + return is_array($value) + ? [$key, array_merge($value, $attributes)] + : [$value, $attributes]; + } + + /** + * Create a new pivot attachment record. + * + * @param int $id + * @param bool $timed + * @return array + */ + protected function baseAttachRecord($id, $timed) + { + $record[$this->relatedPivotKey] = $id; + + $record[$this->foreignPivotKey] = $this->parent->{$this->parentKey}; + + // If the record needs to have creation and update timestamps, we will make + // them by calling the parent model's "freshTimestamp" method which will + // provide us with a fresh timestamp in this model's preferred format. + if ($timed) { + $record = $this->addTimestampsToAttachment($record); + } + + foreach ($this->pivotValues as $value) { + $record[$value['column']] = $value['value']; + } + + return $record; + } + + /** + * Set the creation and update timestamps on an attach record. + * + * @param array $record + * @param bool $exists + * @return array + */ + protected function addTimestampsToAttachment(array $record, $exists = false) + { + $fresh = $this->parent->freshTimestamp(); + + if ($this->using) { + $pivotModel = new $this->using; + + $fresh = $fresh->format($pivotModel->getDateFormat()); + } + + if (! $exists && $this->hasPivotColumn($this->createdAt())) { + $record[$this->createdAt()] = $fresh; + } + + if ($this->hasPivotColumn($this->updatedAt())) { + $record[$this->updatedAt()] = $fresh; + } + + return $record; + } + + /** + * Determine whether the given column is defined as a pivot column. + * + * @param string $column + * @return bool + */ + public function hasPivotColumn($column) + { + return in_array($column, $this->pivotColumns); + } + + /** + * Detach models from the relationship. + * + * @param mixed $ids + * @param bool $touch + * @return int + */ + public function detach($ids = null, $touch = true) + { + if ($this->using && + ! empty($ids) && + empty($this->pivotWheres) && + empty($this->pivotWhereIns) && + empty($this->pivotWhereNulls)) { + $results = $this->detachUsingCustomClass($ids); + } else { + $query = $this->newPivotQuery(); + + // If associated IDs were passed to the method we will only delete those + // associations, otherwise all of the association ties will be broken. + // We'll return the numbers of affected rows when we do the deletes. + if (! is_null($ids)) { + $ids = $this->parseIds($ids); + + if (empty($ids)) { + return 0; + } + + $query->whereIn($this->getQualifiedRelatedPivotKeyName(), (array) $ids); + } + + // Once we have all of the conditions set on the statement, we are ready + // to run the delete on the pivot table. Then, if the touch parameter + // is true, we will go ahead and touch all related models to sync. + $results = $query->delete(); + } + + if ($touch) { + $this->touchIfTouching(); + } + + return $results; + } + + /** + * Detach models from the relationship using a custom class. + * + * @param mixed $ids + * @return int + */ + protected function detachUsingCustomClass($ids) + { + $results = 0; + + foreach ($this->parseIds($ids) as $id) { + $results += $this->newPivot([ + $this->foreignPivotKey => $this->parent->{$this->parentKey}, + $this->relatedPivotKey => $id, + ], true)->delete(); + } + + return $results; + } + + /** + * Get the pivot models that are currently attached. + * + * @return \Illuminate\Support\Collection + */ + protected function getCurrentlyAttachedPivots() + { + return $this->newPivotQuery()->get()->map(function ($record) { + $class = $this->using ?: Pivot::class; + + $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); + + return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey); + }); + } + + /** + * Create a new pivot model instance. + * + * @param array $attributes + * @param bool $exists + * @return \Illuminate\Database\Eloquent\Relations\Pivot + */ + public function newPivot(array $attributes = [], $exists = false) + { + $pivot = $this->related->newPivot( + $this->parent, $attributes, $this->table, $exists, $this->using + ); + + return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey); + } + + /** + * Create a new existing pivot model instance. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Relations\Pivot + */ + public function newExistingPivot(array $attributes = []) + { + return $this->newPivot($attributes, true); + } + + /** + * Get a new plain query builder for the pivot table. + * + * @return \Illuminate\Database\Query\Builder + */ + public function newPivotStatement() + { + return $this->query->getQuery()->newQuery()->from($this->table); + } + + /** + * Get a new pivot statement for a given "other" ID. + * + * @param mixed $id + * @return \Illuminate\Database\Query\Builder + */ + public function newPivotStatementForId($id) + { + return $this->newPivotQuery()->whereIn($this->relatedPivotKey, $this->parseIds($id)); + } + + /** + * Create a new query builder for the pivot table. + * + * @return \Illuminate\Database\Query\Builder + */ + public function newPivotQuery() + { + $query = $this->newPivotStatement(); + + foreach ($this->pivotWheres as $arguments) { + $query->where(...$arguments); + } + + foreach ($this->pivotWhereIns as $arguments) { + $query->whereIn(...$arguments); + } + + foreach ($this->pivotWhereNulls as $arguments) { + $query->whereNull(...$arguments); + } + + return $query->where($this->getQualifiedForeignPivotKeyName(), $this->parent->{$this->parentKey}); + } + + /** + * Set the columns on the pivot table to retrieve. + * + * @param array|mixed $columns + * @return $this + */ + public function withPivot($columns) + { + $this->pivotColumns = array_merge( + $this->pivotColumns, is_array($columns) ? $columns : func_get_args() + ); + + return $this; + } + + /** + * Get all of the IDs from the given mixed value. + * + * @param mixed $value + * @return array + */ + protected function parseIds($value) + { + if ($value instanceof Model) { + return [$value->{$this->relatedKey}]; + } + + if ($value instanceof Collection) { + return $value->pluck($this->relatedKey)->all(); + } + + if ($value instanceof BaseCollection) { + return $value->toArray(); + } + + return (array) $value; + } + + /** + * Get the ID from the given mixed value. + * + * @param mixed $value + * @return mixed + */ + protected function parseId($value) + { + return $value instanceof Model ? $value->{$this->relatedKey} : $value; + } + + /** + * Cast the given keys to integers if they are numeric and string otherwise. + * + * @param array $keys + * @return array + */ + protected function castKeys(array $keys) + { + return array_map(function ($v) { + return $this->castKey($v); + }, $keys); + } + + /** + * Cast the given key to convert to primary key type. + * + * @param mixed $key + * @return mixed + */ + protected function castKey($key) + { + return $this->getTypeSwapValue( + $this->related->getKeyType(), + $key + ); + } + + /** + * Cast the given pivot attributes. + * + * @param array $attributes + * @return array + */ + protected function castAttributes($attributes) + { + return $this->using + ? $this->newPivot()->fill($attributes)->getAttributes() + : $attributes; + } + + /** + * Converts a given value to a given type value. + * + * @param string $type + * @param mixed $value + * @return mixed + */ + protected function getTypeSwapValue($type, $value) + { + switch (strtolower($type)) { + case 'int': + case 'integer': + return (int) $value; + case 'real': + case 'float': + case 'double': + return (float) $value; + case 'string': + return (string) $value; + default: + return $value; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsDefaultModels.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsDefaultModels.php new file mode 100644 index 0000000..74e758f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsDefaultModels.php @@ -0,0 +1,63 @@ +withDefault = $callback; + + return $this; + } + + /** + * Get the default value for this relation. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return \Illuminate\Database\Eloquent\Model|null + */ + protected function getDefaultFor(Model $parent) + { + if (! $this->withDefault) { + return; + } + + $instance = $this->newRelatedInstanceFor($parent); + + if (is_callable($this->withDefault)) { + return call_user_func($this->withDefault, $instance, $parent) ?: $instance; + } + + if (is_array($this->withDefault)) { + $instance->forceFill($this->withDefault); + } + + return $instance; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasMany.php new file mode 100755 index 0000000..b005d4f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasMany.php @@ -0,0 +1,49 @@ +getParentKey()) + ? $this->query->get() + : $this->related->newCollection(); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->related->newCollection()); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + return $this->matchMany($models, $results, $relation); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php new file mode 100644 index 0000000..2074816 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php @@ -0,0 +1,718 @@ +localKey = $localKey; + $this->firstKey = $firstKey; + $this->secondKey = $secondKey; + $this->farParent = $farParent; + $this->throughParent = $throughParent; + $this->secondLocalKey = $secondLocalKey; + + parent::__construct($query, $throughParent); + } + + /** + * Set the base constraints on the relation query. + * + * @return void + */ + public function addConstraints() + { + $localValue = $this->farParent[$this->localKey]; + + $this->performJoin(); + + if (static::$constraints) { + $this->query->where($this->getQualifiedFirstKeyName(), '=', $localValue); + } + } + + /** + * Set the join clause on the query. + * + * @param \Illuminate\Database\Eloquent\Builder|null $query + * @return void + */ + protected function performJoin(Builder $query = null) + { + $query = $query ?: $this->query; + + $farKey = $this->getQualifiedFarKeyName(); + + $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $farKey); + + if ($this->throughParentSoftDeletes()) { + $query->withGlobalScope('SoftDeletableHasManyThrough', function ($query) { + $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn()); + }); + } + } + + /** + * Get the fully qualified parent key name. + * + * @return string + */ + public function getQualifiedParentKeyName() + { + return $this->parent->qualifyColumn($this->secondLocalKey); + } + + /** + * Determine whether "through" parent of the relation uses Soft Deletes. + * + * @return bool + */ + public function throughParentSoftDeletes() + { + return in_array(SoftDeletes::class, class_uses_recursive($this->throughParent)); + } + + /** + * Indicate that trashed "through" parents should be included in the query. + * + * @return $this + */ + public function withTrashedParents() + { + $this->query->withoutGlobalScope('SoftDeletableHasManyThrough'); + + return $this; + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + $whereIn = $this->whereInMethod($this->farParent, $this->localKey); + + $this->query->{$whereIn}( + $this->getQualifiedFirstKeyName(), $this->getKeys($models, $this->localKey) + ); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->related->newCollection()); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + $dictionary = $this->buildDictionary($results); + + // Once we have the dictionary we can simply spin through the parent models to + // link them up with their children using the keyed dictionary to make the + // matching very convenient and easy work. Then we'll just return them. + foreach ($models as $model) { + if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) { + $model->setRelation( + $relation, $this->related->newCollection($dictionary[$key]) + ); + } + } + + return $models; + } + + /** + * Build model dictionary keyed by the relation's foreign key. + * + * @param \Illuminate\Database\Eloquent\Collection $results + * @return array + */ + protected function buildDictionary(Collection $results) + { + $dictionary = []; + + // First we will create a dictionary of models keyed by the foreign key of the + // relationship as this will allow us to quickly access all of the related + // models without having to do nested looping which will be quite slow. + foreach ($results as $result) { + $dictionary[$result->laravel_through_key][] = $result; + } + + return $dictionary; + } + + /** + * Get the first related model record matching the attributes or instantiate it. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function firstOrNew(array $attributes) + { + if (is_null($instance = $this->where($attributes)->first())) { + $instance = $this->related->newInstance($attributes); + } + + return $instance; + } + + /** + * Create or update a related record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model + */ + public function updateOrCreate(array $attributes, array $values = []) + { + $instance = $this->firstOrNew($attributes); + + $instance->fill($values)->save(); + + return $instance; + } + + /** + * Add a basic where clause to the query, and return the first result. + * + * @param \Closure|string|array $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') + { + return $this->where($column, $operator, $value, $boolean)->first(); + } + + /** + * Execute the query and get the first related model. + * + * @param array $columns + * @return mixed + */ + public function first($columns = ['*']) + { + $results = $this->take(1)->get($columns); + + return count($results) > 0 ? $results->first() : null; + } + + /** + * Execute the query and get the first result or throw an exception. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|static + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function firstOrFail($columns = ['*']) + { + if (! is_null($model = $this->first($columns))) { + return $model; + } + + throw (new ModelNotFoundException)->setModel(get_class($this->related)); + } + + /** + * Find a related model by its primary key. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null + */ + public function find($id, $columns = ['*']) + { + if (is_array($id) || $id instanceof Arrayable) { + return $this->findMany($id, $columns); + } + + return $this->where( + $this->getRelated()->getQualifiedKeyName(), '=', $id + )->first($columns); + } + + /** + * Find multiple related models by their primary keys. + * + * @param \Illuminate\Contracts\Support\Arrayable|array $ids + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function findMany($ids, $columns = ['*']) + { + $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; + + if (empty($ids)) { + return $this->getRelated()->newCollection(); + } + + return $this->whereIn( + $this->getRelated()->getQualifiedKeyName(), $ids + )->get($columns); + } + + /** + * Find a related model by its primary key or throw an exception. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function findOrFail($id, $columns = ['*']) + { + $result = $this->find($id, $columns); + + $id = $id instanceof Arrayable ? $id->toArray() : $id; + + if (is_array($id)) { + if (count($result) === count(array_unique($id))) { + return $result; + } + } elseif (! is_null($result)) { + return $result; + } + + throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); + } + + /** + * Get the results of the relationship. + * + * @return mixed + */ + public function getResults() + { + return ! is_null($this->farParent->{$this->localKey}) + ? $this->get() + : $this->related->newCollection(); + } + + /** + * Execute the query as a "select" statement. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function get($columns = ['*']) + { + $builder = $this->prepareQueryBuilder($columns); + + $models = $builder->getModels(); + + // If we actually found models we will also eager load any relationships that + // have been specified as needing to be eager loaded. This will solve the + // n + 1 query problem for the developer and also increase performance. + if (count($models) > 0) { + $models = $builder->eagerLoadRelations($models); + } + + return $this->related->newCollection($models); + } + + /** + * Get a paginator for the "select" statement. + * + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int $page + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + */ + public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) + { + $this->query->addSelect($this->shouldSelect($columns)); + + return $this->query->paginate($perPage, $columns, $pageName, $page); + } + + /** + * Paginate the given query into a simple paginator. + * + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\Paginator + */ + public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) + { + $this->query->addSelect($this->shouldSelect($columns)); + + return $this->query->simplePaginate($perPage, $columns, $pageName, $page); + } + + /** + * Paginate the given query into a cursor paginator. + * + * @param int|null $perPage + * @param array $columns + * @param string $cursorName + * @param string|null $cursor + * @return \Illuminate\Contracts\Pagination\CursorPaginator + */ + public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null) + { + $this->query->addSelect($this->shouldSelect($columns)); + + return $this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor); + } + + /** + * Set the select clause for the relation query. + * + * @param array $columns + * @return array + */ + protected function shouldSelect(array $columns = ['*']) + { + if ($columns == ['*']) { + $columns = [$this->related->getTable().'.*']; + } + + return array_merge($columns, [$this->getQualifiedFirstKeyName().' as laravel_through_key']); + } + + /** + * Chunk the results of the query. + * + * @param int $count + * @param callable $callback + * @return bool + */ + public function chunk($count, callable $callback) + { + return $this->prepareQueryBuilder()->chunk($count, $callback); + } + + /** + * Chunk the results of a query by comparing numeric IDs. + * + * @param int $count + * @param callable $callback + * @param string|null $column + * @param string|null $alias + * @return bool + */ + public function chunkById($count, callable $callback, $column = null, $alias = null) + { + $column = $column ?? $this->getRelated()->getQualifiedKeyName(); + + $alias = $alias ?? $this->getRelated()->getKeyName(); + + return $this->prepareQueryBuilder()->chunkById($count, $callback, $column, $alias); + } + + /** + * Get a generator for the given query. + * + * @return \Generator + */ + public function cursor() + { + return $this->prepareQueryBuilder()->cursor(); + } + + /** + * Execute a callback over each item while chunking. + * + * @param callable $callback + * @param int $count + * @return bool + */ + public function each(callable $callback, $count = 1000) + { + return $this->chunk($count, function ($results) use ($callback) { + foreach ($results as $key => $value) { + if ($callback($value, $key) === false) { + return false; + } + } + }); + } + + /** + * Query lazily, by chunks of the given size. + * + * @param int $chunkSize + * @return \Illuminate\Support\LazyCollection + */ + public function lazy($chunkSize = 1000) + { + return $this->prepareQueryBuilder()->lazy($chunkSize); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @return \Illuminate\Support\LazyCollection + */ + public function lazyById($chunkSize = 1000, $column = null, $alias = null) + { + $column = $column ?? $this->getRelated()->getQualifiedKeyName(); + + $alias = $alias ?? $this->getRelated()->getKeyName(); + + return $this->prepareQueryBuilder()->lazyById($chunkSize, $column, $alias); + } + + /** + * Prepare the query builder for query execution. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function prepareQueryBuilder($columns = ['*']) + { + $builder = $this->query->applyScopes(); + + return $builder->addSelect( + $this->shouldSelect($builder->getQuery()->columns ? [] : $columns) + ); + } + + /** + * Add the constraints for a relationship query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + if ($parentQuery->getQuery()->from === $query->getQuery()->from) { + return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); + } + + if ($parentQuery->getQuery()->from === $this->throughParent->getTable()) { + return $this->getRelationExistenceQueryForThroughSelfRelation($query, $parentQuery, $columns); + } + + $this->performJoin($query); + + return $query->select($columns)->whereColumn( + $this->getQualifiedLocalKeyName(), '=', $this->getQualifiedFirstKeyName() + ); + } + + /** + * Add the constraints for a relationship query on the same table. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) + { + $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()); + + $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->secondKey); + + if ($this->throughParentSoftDeletes()) { + $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn()); + } + + $query->getModel()->setTable($hash); + + return $query->select($columns)->whereColumn( + $parentQuery->getQuery()->from.'.'.$this->localKey, '=', $this->getQualifiedFirstKeyName() + ); + } + + /** + * Add the constraints for a relationship query on the same table as the through parent. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQueryForThroughSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) + { + $table = $this->throughParent->getTable().' as '.$hash = $this->getRelationCountHash(); + + $query->join($table, $hash.'.'.$this->secondLocalKey, '=', $this->getQualifiedFarKeyName()); + + if ($this->throughParentSoftDeletes()) { + $query->whereNull($hash.'.'.$this->throughParent->getDeletedAtColumn()); + } + + return $query->select($columns)->whereColumn( + $parentQuery->getQuery()->from.'.'.$this->localKey, '=', $hash.'.'.$this->firstKey + ); + } + + /** + * Get the qualified foreign key on the related model. + * + * @return string + */ + public function getQualifiedFarKeyName() + { + return $this->getQualifiedForeignKeyName(); + } + + /** + * Get the foreign key on the "through" model. + * + * @return string + */ + public function getFirstKeyName() + { + return $this->firstKey; + } + + /** + * Get the qualified foreign key on the "through" model. + * + * @return string + */ + public function getQualifiedFirstKeyName() + { + return $this->throughParent->qualifyColumn($this->firstKey); + } + + /** + * Get the foreign key on the related model. + * + * @return string + */ + public function getForeignKeyName() + { + return $this->secondKey; + } + + /** + * Get the qualified foreign key on the related model. + * + * @return string + */ + public function getQualifiedForeignKeyName() + { + return $this->related->qualifyColumn($this->secondKey); + } + + /** + * Get the local key on the far parent model. + * + * @return string + */ + public function getLocalKeyName() + { + return $this->localKey; + } + + /** + * Get the qualified local key on the far parent model. + * + * @return string + */ + public function getQualifiedLocalKeyName() + { + return $this->farParent->qualifyColumn($this->localKey); + } + + /** + * Get the local key on the intermediary model. + * + * @return string + */ + public function getSecondLocalKeyName() + { + return $this->secondLocalKey; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOne.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOne.php new file mode 100755 index 0000000..15c735c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOne.php @@ -0,0 +1,137 @@ +getParentKey())) { + return $this->getDefaultFor($this->parent); + } + + return $this->query->first() ?: $this->getDefaultFor($this->parent); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->getDefaultFor($model)); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + return $this->matchOne($models, $results, $relation); + } + + /** + * Add the constraints for an internal relationship existence query. + * + * Essentially, these queries compare on column names like "whereColumn". + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + if ($this->isOneOfMany()) { + $this->mergeOneOfManyJoinsTo($query); + } + + return parent::getRelationExistenceQuery($query, $parentQuery, $columns); + } + + /** + * Add constraints for inner join subselect for one of many relationships. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param string|null $column + * @param string|null $aggregate + * @return void + */ + public function addOneOfManySubQueryConstraints(Builder $query, $column = null, $aggregate = null) + { + $query->addSelect($this->foreignKey); + } + + /** + * Get the columns that should be selected by the one of many subquery. + * + * @return array|string + */ + public function getOneOfManySubQuerySelectColumns() + { + return $this->foreignKey; + } + + /** + * Add join query constraints for one of many relationships. + * + * @param \Illuminate\Database\Eloquent\JoinClause $join + * @return void + */ + public function addOneOfManyJoinSubQueryConstraints(JoinClause $join) + { + $join->on($this->qualifySubSelectColumn($this->foreignKey), '=', $this->qualifyRelatedColumn($this->foreignKey)); + } + + /** + * Make a new related instance for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return \Illuminate\Database\Eloquent\Model + */ + public function newRelatedInstanceFor(Model $parent) + { + return $this->related->newInstance()->setAttribute( + $this->getForeignKeyName(), $parent->{$this->localKey} + ); + } + + /** + * Get the value of the model's foreign key. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return mixed + */ + protected function getRelatedKeyFrom(Model $model) + { + return $model->getAttribute($this->getForeignKeyName()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php new file mode 100755 index 0000000..ff738b9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -0,0 +1,438 @@ +localKey = $localKey; + $this->foreignKey = $foreignKey; + + parent::__construct($query, $parent); + } + + /** + * Create and return an un-saved instance of the related model. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function make(array $attributes = []) + { + return tap($this->related->newInstance($attributes), function ($instance) { + $this->setForeignAttributesForCreate($instance); + }); + } + + /** + * Create and return an un-saved instance of the related models. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection + */ + public function makeMany($records) + { + $instances = $this->related->newCollection(); + + foreach ($records as $record) { + $instances->push($this->make($record)); + } + + return $instances; + } + + /** + * Set the base constraints on the relation query. + * + * @return void + */ + public function addConstraints() + { + if (static::$constraints) { + $query = $this->getRelationQuery(); + + $query->where($this->foreignKey, '=', $this->getParentKey()); + + $query->whereNotNull($this->foreignKey); + } + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + $whereIn = $this->whereInMethod($this->parent, $this->localKey); + + $this->getRelationQuery()->{$whereIn}( + $this->foreignKey, $this->getKeys($models, $this->localKey) + ); + } + + /** + * Match the eagerly loaded results to their single parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function matchOne(array $models, Collection $results, $relation) + { + return $this->matchOneOrMany($models, $results, $relation, 'one'); + } + + /** + * Match the eagerly loaded results to their many parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function matchMany(array $models, Collection $results, $relation) + { + return $this->matchOneOrMany($models, $results, $relation, 'many'); + } + + /** + * Match the eagerly loaded results to their many parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @param string $type + * @return array + */ + protected function matchOneOrMany(array $models, Collection $results, $relation, $type) + { + $dictionary = $this->buildDictionary($results); + + // Once we have the dictionary we can simply spin through the parent models to + // link them up with their children using the keyed dictionary to make the + // matching very convenient and easy work. Then we'll just return them. + foreach ($models as $model) { + if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) { + $model->setRelation( + $relation, $this->getRelationValue($dictionary, $key, $type) + ); + } + } + + return $models; + } + + /** + * Get the value of a relationship by one or many type. + * + * @param array $dictionary + * @param string $key + * @param string $type + * @return mixed + */ + protected function getRelationValue(array $dictionary, $key, $type) + { + $value = $dictionary[$key]; + + return $type === 'one' ? reset($value) : $this->related->newCollection($value); + } + + /** + * Build model dictionary keyed by the relation's foreign key. + * + * @param \Illuminate\Database\Eloquent\Collection $results + * @return array + */ + protected function buildDictionary(Collection $results) + { + $foreign = $this->getForeignKeyName(); + + return $results->mapToDictionary(function ($result) use ($foreign) { + return [$this->getDictionaryKey($result->{$foreign}) => $result]; + })->all(); + } + + /** + * Find a model by its primary key or return a new instance of the related model. + * + * @param mixed $id + * @param array $columns + * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model + */ + public function findOrNew($id, $columns = ['*']) + { + if (is_null($instance = $this->find($id, $columns))) { + $instance = $this->related->newInstance(); + + $this->setForeignAttributesForCreate($instance); + } + + return $instance; + } + + /** + * Get the first related model record matching the attributes or instantiate it. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model + */ + public function firstOrNew(array $attributes = [], array $values = []) + { + if (is_null($instance = $this->where($attributes)->first())) { + $instance = $this->related->newInstance(array_merge($attributes, $values)); + + $this->setForeignAttributesForCreate($instance); + } + + return $instance; + } + + /** + * Get the first related record matching the attributes or create it. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model + */ + public function firstOrCreate(array $attributes = [], array $values = []) + { + if (is_null($instance = $this->where($attributes)->first())) { + $instance = $this->create(array_merge($attributes, $values)); + } + + return $instance; + } + + /** + * Create or update a related record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model + */ + public function updateOrCreate(array $attributes, array $values = []) + { + return tap($this->firstOrNew($attributes), function ($instance) use ($values) { + $instance->fill($values); + + $instance->save(); + }); + } + + /** + * Attach a model instance to the parent model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return \Illuminate\Database\Eloquent\Model|false + */ + public function save(Model $model) + { + $this->setForeignAttributesForCreate($model); + + return $model->save() ? $model : false; + } + + /** + * Attach a collection of models to the parent instance. + * + * @param iterable $models + * @return iterable + */ + public function saveMany($models) + { + foreach ($models as $model) { + $this->save($model); + } + + return $models; + } + + /** + * Create a new instance of the related model. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function create(array $attributes = []) + { + return tap($this->related->newInstance($attributes), function ($instance) { + $this->setForeignAttributesForCreate($instance); + + $instance->save(); + }); + } + + /** + * Create a new instance of the related model. Allow mass-assignment. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function forceCreate(array $attributes = []) + { + $attributes[$this->getForeignKeyName()] = $this->getParentKey(); + + return $this->related->forceCreate($attributes); + } + + /** + * Create a Collection of new instances of the related model. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection + */ + public function createMany(iterable $records) + { + $instances = $this->related->newCollection(); + + foreach ($records as $record) { + $instances->push($this->create($record)); + } + + return $instances; + } + + /** + * Set the foreign ID for creating a related model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return void + */ + protected function setForeignAttributesForCreate(Model $model) + { + $model->setAttribute($this->getForeignKeyName(), $this->getParentKey()); + } + + /** + * Add the constraints for a relationship query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + if ($query->getQuery()->from == $parentQuery->getQuery()->from) { + return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); + } + + return parent::getRelationExistenceQuery($query, $parentQuery, $columns); + } + + /** + * Add the constraints for a relationship query on the same table. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*']) + { + $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()); + + $query->getModel()->setTable($hash); + + return $query->select($columns)->whereColumn( + $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName() + ); + } + + /** + * Get the key for comparing against the parent key in "has" query. + * + * @return string + */ + public function getExistenceCompareKey() + { + return $this->getQualifiedForeignKeyName(); + } + + /** + * Get the key value of the parent's local key. + * + * @return mixed + */ + public function getParentKey() + { + return $this->parent->getAttribute($this->localKey); + } + + /** + * Get the fully qualified parent key name. + * + * @return string + */ + public function getQualifiedParentKeyName() + { + return $this->parent->qualifyColumn($this->localKey); + } + + /** + * Get the plain foreign key. + * + * @return string + */ + public function getForeignKeyName() + { + $segments = explode('.', $this->getQualifiedForeignKeyName()); + + return end($segments); + } + + /** + * Get the foreign key for the relationship. + * + * @return string + */ + public function getQualifiedForeignKeyName() + { + return $this->foreignKey; + } + + /** + * Get the local key for the relationship. + * + * @return string + */ + public function getLocalKeyName() + { + return $this->localKey; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneThrough.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneThrough.php new file mode 100644 index 0000000..ed9c7ba --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneThrough.php @@ -0,0 +1,77 @@ +first() ?: $this->getDefaultFor($this->farParent); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->getDefaultFor($model)); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + $dictionary = $this->buildDictionary($results); + + // Once we have the dictionary we can simply spin through the parent models to + // link them up with their children using the keyed dictionary to make the + // matching very convenient and easy work. Then we'll just return them. + foreach ($models as $model) { + if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) { + $value = $dictionary[$key]; + $model->setRelation( + $relation, reset($value) + ); + } + } + + return $models; + } + + /** + * Make a new related instance for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return \Illuminate\Database\Eloquent\Model + */ + public function newRelatedInstanceFor(Model $parent) + { + return $this->related->newInstance(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphMany.php new file mode 100755 index 0000000..282ba2e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphMany.php @@ -0,0 +1,62 @@ +getParentKey()) + ? $this->query->get() + : $this->related->newCollection(); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->related->newCollection()); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + return $this->matchMany($models, $results, $relation); + } + + /** + * Create a new instance of the related model. Allow mass-assignment. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model + */ + public function forceCreate(array $attributes = []) + { + $attributes[$this->getMorphType()] = $this->morphClass; + + return parent::forceCreate($attributes); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphOne.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphOne.php new file mode 100755 index 0000000..ff52684 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphOne.php @@ -0,0 +1,137 @@ +getParentKey())) { + return $this->getDefaultFor($this->parent); + } + + return $this->query->first() ?: $this->getDefaultFor($this->parent); + } + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + public function initRelation(array $models, $relation) + { + foreach ($models as $model) { + $model->setRelation($relation, $this->getDefaultFor($model)); + } + + return $models; + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + return $this->matchOne($models, $results, $relation); + } + + /** + * Get the relationship query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + if ($this->isOneOfMany()) { + $this->mergeOneOfManyJoinsTo($query); + } + + return parent::getRelationExistenceQuery($query, $parentQuery, $columns); + } + + /** + * Add constraints for inner join subselect for one of many relationships. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param string|null $column + * @param string|null $aggregate + * @return void + */ + public function addOneOfManySubQueryConstraints(Builder $query, $column = null, $aggregate = null) + { + $query->addSelect($this->foreignKey, $this->morphType); + } + + /** + * Get the columns that should be selected by the one of many subquery. + * + * @return array|string + */ + public function getOneOfManySubQuerySelectColumns() + { + return [$this->foreignKey, $this->morphType]; + } + + /** + * Add join query constraints for one of many relationships. + * + * @param \Illuminate\Database\Eloquent\JoinClause $join + * @return void + */ + public function addOneOfManyJoinSubQueryConstraints(JoinClause $join) + { + $join + ->on($this->qualifySubSelectColumn($this->morphType), '=', $this->qualifyRelatedColumn($this->morphType)) + ->on($this->qualifySubSelectColumn($this->foreignKey), '=', $this->qualifyRelatedColumn($this->foreignKey)); + } + + /** + * Make a new related instance for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return \Illuminate\Database\Eloquent\Model + */ + public function newRelatedInstanceFor(Model $parent) + { + return $this->related->newInstance() + ->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey}) + ->setAttribute($this->getMorphType(), $this->morphClass); + } + + /** + * Get the value of the model's foreign key. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return mixed + */ + protected function getRelatedKeyFrom(Model $model) + { + return $model->getAttribute($this->getForeignKeyName()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php new file mode 100755 index 0000000..6e2297f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php @@ -0,0 +1,127 @@ +morphType = $type; + + $this->morphClass = $parent->getMorphClass(); + + parent::__construct($query, $parent, $id, $localKey); + } + + /** + * Set the base constraints on the relation query. + * + * @return void + */ + public function addConstraints() + { + if (static::$constraints) { + $this->getRelationQuery()->where($this->morphType, $this->morphClass); + + parent::addConstraints(); + } + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + parent::addEagerConstraints($models); + + $this->getRelationQuery()->where($this->morphType, $this->morphClass); + } + + /** + * Set the foreign ID and type for creating a related model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return void + */ + protected function setForeignAttributesForCreate(Model $model) + { + $model->{$this->getForeignKeyName()} = $this->getParentKey(); + + $model->{$this->getMorphType()} = $this->morphClass; + } + + /** + * Get the relationship query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + return parent::getRelationExistenceQuery($query, $parentQuery, $columns)->where( + $query->qualifyColumn($this->getMorphType()), $this->morphClass + ); + } + + /** + * Get the foreign key "type" name. + * + * @return string + */ + public function getQualifiedMorphType() + { + return $this->morphType; + } + + /** + * Get the plain morph type name without the table. + * + * @return string + */ + public function getMorphType() + { + return last(explode('.', $this->morphType)); + } + + /** + * Get the class name of the parent model. + * + * @return string + */ + public function getMorphClass() + { + return $this->morphClass; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphPivot.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphPivot.php new file mode 100644 index 0000000..7fbe484 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphPivot.php @@ -0,0 +1,184 @@ +where($this->morphType, $this->morphClass); + + return parent::setKeysForSaveQuery($query); + } + + /** + * Set the keys for a select query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function setKeysForSelectQuery($query) + { + $query->where($this->morphType, $this->morphClass); + + return parent::setKeysForSelectQuery($query); + } + + /** + * Delete the pivot model record from the database. + * + * @return int + */ + public function delete() + { + if (isset($this->attributes[$this->getKeyName()])) { + return (int) parent::delete(); + } + + if ($this->fireModelEvent('deleting') === false) { + return 0; + } + + $query = $this->getDeleteQuery(); + + $query->where($this->morphType, $this->morphClass); + + return tap($query->delete(), function () { + $this->fireModelEvent('deleted', false); + }); + } + + /** + * Get the morph type for the pivot. + * + * @return string + */ + public function getMorphType() + { + return $this->morphType; + } + + /** + * Set the morph type for the pivot. + * + * @param string $morphType + * @return $this + */ + public function setMorphType($morphType) + { + $this->morphType = $morphType; + + return $this; + } + + /** + * Set the morph class for the pivot. + * + * @param string $morphClass + * @return \Illuminate\Database\Eloquent\Relations\MorphPivot + */ + public function setMorphClass($morphClass) + { + $this->morphClass = $morphClass; + + return $this; + } + + /** + * Get the queueable identity for the entity. + * + * @return mixed + */ + public function getQueueableId() + { + if (isset($this->attributes[$this->getKeyName()])) { + return $this->getKey(); + } + + return sprintf( + '%s:%s:%s:%s:%s:%s', + $this->foreignKey, $this->getAttribute($this->foreignKey), + $this->relatedKey, $this->getAttribute($this->relatedKey), + $this->morphType, $this->morphClass + ); + } + + /** + * Get a new query to restore one or more models by their queueable IDs. + * + * @param array|int $ids + * @return \Illuminate\Database\Eloquent\Builder + */ + public function newQueryForRestoration($ids) + { + if (is_array($ids)) { + return $this->newQueryForCollectionRestoration($ids); + } + + if (! Str::contains($ids, ':')) { + return parent::newQueryForRestoration($ids); + } + + $segments = explode(':', $ids); + + return $this->newQueryWithoutScopes() + ->where($segments[0], $segments[1]) + ->where($segments[2], $segments[3]) + ->where($segments[4], $segments[5]); + } + + /** + * Get a new query to restore multiple models by their queueable IDs. + * + * @param array $ids + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function newQueryForCollectionRestoration(array $ids) + { + $ids = array_values($ids); + + if (! Str::contains($ids[0], ':')) { + return parent::newQueryForRestoration($ids); + } + + $query = $this->newQueryWithoutScopes(); + + foreach ($ids as $id) { + $segments = explode(':', $id); + + $query->orWhere(function ($query) use ($segments) { + return $query->where($segments[0], $segments[1]) + ->where($segments[2], $segments[3]) + ->where($segments[4], $segments[5]); + }); + } + + return $query; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphTo.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphTo.php new file mode 100644 index 0000000..262741f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphTo.php @@ -0,0 +1,396 @@ +morphType = $type; + + parent::__construct($query, $parent, $foreignKey, $ownerKey, $relation); + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + $this->buildDictionary($this->models = Collection::make($models)); + } + + /** + * Build a dictionary with the models. + * + * @param \Illuminate\Database\Eloquent\Collection $models + * @return void + */ + protected function buildDictionary(Collection $models) + { + foreach ($models as $model) { + if ($model->{$this->morphType}) { + $morphTypeKey = $this->getDictionaryKey($model->{$this->morphType}); + $foreignKeyKey = $this->getDictionaryKey($model->{$this->foreignKey}); + + $this->dictionary[$morphTypeKey][$foreignKeyKey][] = $model; + } + } + } + + /** + * Get the results of the relationship. + * + * Called via eager load method of Eloquent query builder. + * + * @return mixed + */ + public function getEager() + { + foreach (array_keys($this->dictionary) as $type) { + $this->matchToMorphParents($type, $this->getResultsByType($type)); + } + + return $this->models; + } + + /** + * Get all of the relation results for a type. + * + * @param string $type + * @return \Illuminate\Database\Eloquent\Collection + */ + protected function getResultsByType($type) + { + $instance = $this->createModelByType($type); + + $ownerKey = $this->ownerKey ?? $instance->getKeyName(); + + $query = $this->replayMacros($instance->newQuery()) + ->mergeConstraintsFrom($this->getQuery()) + ->with(array_merge( + $this->getQuery()->getEagerLoads(), + (array) ($this->morphableEagerLoads[get_class($instance)] ?? []) + )) + ->withCount( + (array) ($this->morphableEagerLoadCounts[get_class($instance)] ?? []) + ); + + if ($callback = ($this->morphableConstraints[get_class($instance)] ?? null)) { + $callback($query); + } + + $whereIn = $this->whereInMethod($instance, $ownerKey); + + return $query->{$whereIn}( + $instance->getTable().'.'.$ownerKey, $this->gatherKeysByType($type, $instance->getKeyType()) + )->get(); + } + + /** + * Gather all of the foreign keys for a given type. + * + * @param string $type + * @param string $keyType + * @return array + */ + protected function gatherKeysByType($type, $keyType) + { + return $keyType !== 'string' + ? array_keys($this->dictionary[$type]) + : array_map(function ($modelId) { + return (string) $modelId; + }, array_filter(array_keys($this->dictionary[$type]))); + } + + /** + * Create a new model instance by type. + * + * @param string $type + * @return \Illuminate\Database\Eloquent\Model + */ + public function createModelByType($type) + { + $class = Model::getActualClassNameForMorph($type); + + return tap(new $class, function ($instance) { + if (! $instance->getConnectionName()) { + $instance->setConnection($this->getConnection()->getName()); + } + }); + } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, Collection $results, $relation) + { + return $models; + } + + /** + * Match the results for a given type to their parents. + * + * @param string $type + * @param \Illuminate\Database\Eloquent\Collection $results + * @return void + */ + protected function matchToMorphParents($type, Collection $results) + { + foreach ($results as $result) { + $ownerKey = ! is_null($this->ownerKey) ? $this->getDictionaryKey($result->{$this->ownerKey}) : $result->getKey(); + + if (isset($this->dictionary[$type][$ownerKey])) { + foreach ($this->dictionary[$type][$ownerKey] as $model) { + $model->setRelation($this->relationName, $result); + } + } + } + } + + /** + * Associate the model instance to the given parent. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return \Illuminate\Database\Eloquent\Model + */ + public function associate($model) + { + if ($model instanceof Model) { + $foreignKey = $this->ownerKey && $model->{$this->ownerKey} + ? $this->ownerKey + : $model->getKeyName(); + } + + $this->parent->setAttribute( + $this->foreignKey, $model instanceof Model ? $model->{$foreignKey} : null + ); + + $this->parent->setAttribute( + $this->morphType, $model instanceof Model ? $model->getMorphClass() : null + ); + + return $this->parent->setRelation($this->relationName, $model); + } + + /** + * Dissociate previously associated model from the given parent. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function dissociate() + { + $this->parent->setAttribute($this->foreignKey, null); + + $this->parent->setAttribute($this->morphType, null); + + return $this->parent->setRelation($this->relationName, null); + } + + /** + * Touch all of the related models for the relationship. + * + * @return void + */ + public function touch() + { + if (! is_null($this->child->{$this->foreignKey})) { + parent::touch(); + } + } + + /** + * Make a new related instance for the given model. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @return \Illuminate\Database\Eloquent\Model + */ + protected function newRelatedInstanceFor(Model $parent) + { + return $parent->{$this->getRelationName()}()->getRelated()->newInstance(); + } + + /** + * Get the foreign key "type" name. + * + * @return string + */ + public function getMorphType() + { + return $this->morphType; + } + + /** + * Get the dictionary used by the relationship. + * + * @return array + */ + public function getDictionary() + { + return $this->dictionary; + } + + /** + * Specify which relations to load for a given morph type. + * + * @param array $with + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function morphWith(array $with) + { + $this->morphableEagerLoads = array_merge( + $this->morphableEagerLoads, $with + ); + + return $this; + } + + /** + * Specify which relationship counts to load for a given morph type. + * + * @param array $withCount + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function morphWithCount(array $withCount) + { + $this->morphableEagerLoadCounts = array_merge( + $this->morphableEagerLoadCounts, $withCount + ); + + return $this; + } + + /** + * Specify constraints on the query for a given morph type. + * + * @param array $callbacks + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function constrain(array $callbacks) + { + $this->morphableConstraints = array_merge( + $this->morphableConstraints, $callbacks + ); + + return $this; + } + + /** + * Replay stored macro calls on the actual related instance. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function replayMacros(Builder $query) + { + foreach ($this->macroBuffer as $macro) { + $query->{$macro['method']}(...$macro['parameters']); + } + + return $query; + } + + /** + * Handle dynamic method calls to the relationship. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + try { + $result = parent::__call($method, $parameters); + + if (in_array($method, ['select', 'selectRaw', 'selectSub', 'addSelect', 'withoutGlobalScopes'])) { + $this->macroBuffer[] = compact('method', 'parameters'); + } + + return $result; + } + + // If we tried to call a method that does not exist on the parent Builder instance, + // we'll assume that we want to call a query macro (e.g. withTrashed) that only + // exists on related models. We will just store the call and replay it later. + catch (BadMethodCallException $e) { + $this->macroBuffer[] = compact('method', 'parameters'); + + return $this; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphToMany.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphToMany.php new file mode 100644 index 0000000..c2d5745 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphToMany.php @@ -0,0 +1,209 @@ +inverse = $inverse; + $this->morphType = $name.'_type'; + $this->morphClass = $inverse ? $query->getModel()->getMorphClass() : $parent->getMorphClass(); + + parent::__construct( + $query, $parent, $table, $foreignPivotKey, + $relatedPivotKey, $parentKey, $relatedKey, $relationName + ); + } + + /** + * Set the where clause for the relation query. + * + * @return $this + */ + protected function addWhereConstraints() + { + parent::addWhereConstraints(); + + $this->query->where($this->qualifyPivotColumn($this->morphType), $this->morphClass); + + return $this; + } + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + public function addEagerConstraints(array $models) + { + parent::addEagerConstraints($models); + + $this->query->where($this->qualifyPivotColumn($this->morphType), $this->morphClass); + } + + /** + * Create a new pivot attachment record. + * + * @param int $id + * @param bool $timed + * @return array + */ + protected function baseAttachRecord($id, $timed) + { + return Arr::add( + parent::baseAttachRecord($id, $timed), $this->morphType, $this->morphClass + ); + } + + /** + * Add the constraints for a relationship count query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + return parent::getRelationExistenceQuery($query, $parentQuery, $columns)->where( + $this->qualifyPivotColumn($this->morphType), $this->morphClass + ); + } + + /** + * Get the pivot models that are currently attached. + * + * @return \Illuminate\Support\Collection + */ + protected function getCurrentlyAttachedPivots() + { + return parent::getCurrentlyAttachedPivots()->map(function ($record) { + return $record instanceof MorphPivot + ? $record->setMorphType($this->morphType) + ->setMorphClass($this->morphClass) + : $record; + }); + } + + /** + * Create a new query builder for the pivot table. + * + * @return \Illuminate\Database\Query\Builder + */ + public function newPivotQuery() + { + return parent::newPivotQuery()->where($this->morphType, $this->morphClass); + } + + /** + * Create a new pivot model instance. + * + * @param array $attributes + * @param bool $exists + * @return \Illuminate\Database\Eloquent\Relations\Pivot + */ + public function newPivot(array $attributes = [], $exists = false) + { + $using = $this->using; + + $pivot = $using ? $using::fromRawAttributes($this->parent, $attributes, $this->table, $exists) + : MorphPivot::fromAttributes($this->parent, $attributes, $this->table, $exists); + + $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey) + ->setMorphType($this->morphType) + ->setMorphClass($this->morphClass); + + return $pivot; + } + + /** + * Get the pivot columns for the relation. + * + * "pivot_" is prefixed at each column for easy removal later. + * + * @return array + */ + protected function aliasedPivotColumns() + { + $defaults = [$this->foreignPivotKey, $this->relatedPivotKey, $this->morphType]; + + return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { + return $this->qualifyPivotColumn($column).' as pivot_'.$column; + })->unique()->all(); + } + + /** + * Get the foreign key "type" name. + * + * @return string + */ + public function getMorphType() + { + return $this->morphType; + } + + /** + * Get the class name of the parent model. + * + * @return string + */ + public function getMorphClass() + { + return $this->morphClass; + } + + /** + * Get the indicator for a reverse relationship. + * + * @return bool + */ + public function getInverse() + { + return $this->inverse; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Pivot.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Pivot.php new file mode 100755 index 0000000..a65ecde --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Pivot.php @@ -0,0 +1,25 @@ +query = $query; + $this->parent = $parent; + $this->related = $query->getModel(); + + $this->addConstraints(); + } + + /** + * Run a callback with constraints disabled on the relation. + * + * @param \Closure $callback + * @return mixed + */ + public static function noConstraints(Closure $callback) + { + $previous = static::$constraints; + + static::$constraints = false; + + // When resetting the relation where clause, we want to shift the first element + // off of the bindings, leaving only the constraints that the developers put + // as "extra" on the relationships, and not original relation constraints. + try { + return $callback(); + } finally { + static::$constraints = $previous; + } + } + + /** + * Set the base constraints on the relation query. + * + * @return void + */ + abstract public function addConstraints(); + + /** + * Set the constraints for an eager load of the relation. + * + * @param array $models + * @return void + */ + abstract public function addEagerConstraints(array $models); + + /** + * Initialize the relation on a set of models. + * + * @param array $models + * @param string $relation + * @return array + */ + abstract public function initRelation(array $models, $relation); + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + abstract public function match(array $models, Collection $results, $relation); + + /** + * Get the results of the relationship. + * + * @return mixed + */ + abstract public function getResults(); + + /** + * Get the relationship for eager loading. + * + * @return \Illuminate\Database\Eloquent\Collection + */ + public function getEager() + { + return $this->get(); + } + + /** + * Execute the query and get the first result if it's the sole matching record. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + * @throws \Illuminate\Database\MultipleRecordsFoundException + */ + public function sole($columns = ['*']) + { + $result = $this->take(2)->get($columns); + + if ($result->isEmpty()) { + throw (new ModelNotFoundException)->setModel(get_class($this->related)); + } + + if ($result->count() > 1) { + throw new MultipleRecordsFoundException; + } + + return $result->first(); + } + + /** + * Execute the query as a "select" statement. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function get($columns = ['*']) + { + return $this->query->get($columns); + } + + /** + * Touch all of the related models for the relationship. + * + * @return void + */ + public function touch() + { + $model = $this->getRelated(); + + if (! $model::isIgnoringTouch()) { + $this->rawUpdate([ + $model->getUpdatedAtColumn() => $model->freshTimestampString(), + ]); + } + } + + /** + * Run a raw update against the base query. + * + * @param array $attributes + * @return int + */ + public function rawUpdate(array $attributes = []) + { + return $this->query->withoutGlobalScopes()->update($attributes); + } + + /** + * Add the constraints for a relationship count query. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceCountQuery(Builder $query, Builder $parentQuery) + { + return $this->getRelationExistenceQuery( + $query, $parentQuery, new Expression('count(*)') + )->setBindings([], 'select'); + } + + /** + * Add the constraints for an internal relationship existence query. + * + * Essentially, these queries compare on column names like whereColumn. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Database\Eloquent\Builder $parentQuery + * @param array|mixed $columns + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) + { + return $query->select($columns)->whereColumn( + $this->getQualifiedParentKeyName(), '=', $this->getExistenceCompareKey() + ); + } + + /** + * Get a relationship join table hash. + * + * @param bool $incrementJoinCount + * @return string + */ + public function getRelationCountHash($incrementJoinCount = true) + { + return 'laravel_reserved_'.($incrementJoinCount ? static::$selfJoinCount++ : static::$selfJoinCount); + } + + /** + * Get all of the primary keys for an array of models. + * + * @param array $models + * @param string|null $key + * @return array + */ + protected function getKeys(array $models, $key = null) + { + return collect($models)->map(function ($value) use ($key) { + return $key ? $value->getAttribute($key) : $value->getKey(); + })->values()->unique(null, true)->sort()->all(); + } + + /** + * Get the query builder that will contain the relationship constraints. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function getRelationQuery() + { + return $this->query; + } + + /** + * Get the underlying query for the relation. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public function getQuery() + { + return $this->query; + } + + /** + * Get the base query builder driving the Eloquent builder. + * + * @return \Illuminate\Database\Query\Builder + */ + public function getBaseQuery() + { + return $this->query->getQuery(); + } + + /** + * Get the parent model of the relation. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function getParent() + { + return $this->parent; + } + + /** + * Get the fully qualified parent key name. + * + * @return string + */ + public function getQualifiedParentKeyName() + { + return $this->parent->getQualifiedKeyName(); + } + + /** + * Get the related model of the relation. + * + * @return \Illuminate\Database\Eloquent\Model + */ + public function getRelated() + { + return $this->related; + } + + /** + * Get the name of the "created at" column. + * + * @return string + */ + public function createdAt() + { + return $this->parent->getCreatedAtColumn(); + } + + /** + * Get the name of the "updated at" column. + * + * @return string + */ + public function updatedAt() + { + return $this->parent->getUpdatedAtColumn(); + } + + /** + * Get the name of the related model's "updated at" column. + * + * @return string + */ + public function relatedUpdatedAt() + { + return $this->related->getUpdatedAtColumn(); + } + + /** + * Get the name of the "where in" method for eager loading. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(Model $model, $key) + { + return $model->getKeyName() === last(explode('.', $key)) + && in_array($model->getKeyType(), ['int', 'integer']) + ? 'whereIntegerInRaw' + : 'whereIn'; + } + + /** + * Prevent polymorphic relationships from being used without model mappings. + * + * @param bool $requireMorphMap + * @return void + */ + public static function requireMorphMap($requireMorphMap = true) + { + static::$requireMorphMap = $requireMorphMap; + } + + /** + * Determine if polymorphic relationships require explicit model mapping. + * + * @return bool + */ + public static function requiresMorphMap() + { + return static::$requireMorphMap; + } + + /** + * Define the morph map for polymorphic relations and require all morphed models to be explicitly mapped. + * + * @param array $map + * @param bool $merge + * @return array + */ + public static function enforceMorphMap(array $map, $merge = true) + { + static::requireMorphMap(); + + return static::morphMap($map, $merge); + } + + /** + * Set or get the morph map for polymorphic relations. + * + * @param array|null $map + * @param bool $merge + * @return array + */ + public static function morphMap(array $map = null, $merge = true) + { + $map = static::buildMorphMapFromModels($map); + + if (is_array($map)) { + static::$morphMap = $merge && static::$morphMap + ? $map + static::$morphMap : $map; + } + + return static::$morphMap; + } + + /** + * Builds a table-keyed array from model class names. + * + * @param string[]|null $models + * @return array|null + */ + protected static function buildMorphMapFromModels(array $models = null) + { + if (is_null($models) || Arr::isAssoc($models)) { + return $models; + } + + return array_combine(array_map(function ($model) { + return (new $model)->getTable(); + }, $models), $models); + } + + /** + * Get the model associated with a custom polymorphic type. + * + * @param string $alias + * @return string|null + */ + public static function getMorphedModel($alias) + { + return static::$morphMap[$alias] ?? null; + } + + /** + * Handle dynamic method calls to the relationship. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + return $this->forwardDecoratedCallTo($this->query, $method, $parameters); + } + + /** + * Force a clone of the underlying query builder when cloning. + * + * @return void + */ + public function __clone() + { + $this->query = clone $this->query; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Scope.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Scope.php new file mode 100644 index 0000000..63cba6a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Scope.php @@ -0,0 +1,15 @@ +casts[$this->getDeletedAtColumn()])) { + $this->casts[$this->getDeletedAtColumn()] = 'datetime'; + } + } + + /** + * Force a hard delete on a soft deleted model. + * + * @return bool|null + */ + public function forceDelete() + { + $this->forceDeleting = true; + + return tap($this->delete(), function ($deleted) { + $this->forceDeleting = false; + + if ($deleted) { + $this->fireModelEvent('forceDeleted', false); + } + }); + } + + /** + * Perform the actual delete query on this model instance. + * + * @return mixed + */ + protected function performDeleteOnModel() + { + if ($this->forceDeleting) { + return tap($this->setKeysForSaveQuery($this->newModelQuery())->forceDelete(), function () { + $this->exists = false; + }); + } + + return $this->runSoftDelete(); + } + + /** + * Perform the actual delete query on this model instance. + * + * @return void + */ + protected function runSoftDelete() + { + $query = $this->setKeysForSaveQuery($this->newModelQuery()); + + $time = $this->freshTimestamp(); + + $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)]; + + $this->{$this->getDeletedAtColumn()} = $time; + + if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) { + $this->{$this->getUpdatedAtColumn()} = $time; + + $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time); + } + + $query->update($columns); + + $this->syncOriginalAttributes(array_keys($columns)); + + $this->fireModelEvent('trashed', false); + } + + /** + * Restore a soft-deleted model instance. + * + * @return bool|null + */ + public function restore() + { + // If the restoring event does not return false, we will proceed with this + // restore operation. Otherwise, we bail out so the developer will stop + // the restore totally. We will clear the deleted timestamp and save. + if ($this->fireModelEvent('restoring') === false) { + return false; + } + + $this->{$this->getDeletedAtColumn()} = null; + + // Once we have saved the model, we will fire the "restored" event so this + // developer will do anything they need to after a restore operation is + // totally finished. Then we will return the result of the save call. + $this->exists = true; + + $result = $this->save(); + + $this->fireModelEvent('restored', false); + + return $result; + } + + /** + * Determine if the model instance has been soft-deleted. + * + * @return bool + */ + public function trashed() + { + return ! is_null($this->{$this->getDeletedAtColumn()}); + } + + /** + * Register a "softDeleted" model event callback with the dispatcher. + * + * @param \Closure|string $callback + * @return void + */ + public static function softDeleted($callback) + { + static::registerModelEvent('trashed', $callback); + } + + /** + * Register a "restoring" model event callback with the dispatcher. + * + * @param \Closure|string $callback + * @return void + */ + public static function restoring($callback) + { + static::registerModelEvent('restoring', $callback); + } + + /** + * Register a "restored" model event callback with the dispatcher. + * + * @param \Closure|string $callback + * @return void + */ + public static function restored($callback) + { + static::registerModelEvent('restored', $callback); + } + + /** + * Register a "forceDeleted" model event callback with the dispatcher. + * + * @param \Closure|string $callback + * @return void + */ + public static function forceDeleted($callback) + { + static::registerModelEvent('forceDeleted', $callback); + } + + /** + * Determine if the model is currently force deleting. + * + * @return bool + */ + public function isForceDeleting() + { + return $this->forceDeleting; + } + + /** + * Get the name of the "deleted at" column. + * + * @return string + */ + public function getDeletedAtColumn() + { + return defined('static::DELETED_AT') ? static::DELETED_AT : 'deleted_at'; + } + + /** + * Get the fully qualified "deleted at" column. + * + * @return string + */ + public function getQualifiedDeletedAtColumn() + { + return $this->qualifyColumn($this->getDeletedAtColumn()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/SoftDeletingScope.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/SoftDeletingScope.php new file mode 100644 index 0000000..7528964 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Eloquent/SoftDeletingScope.php @@ -0,0 +1,131 @@ +whereNull($model->getQualifiedDeletedAtColumn()); + } + + /** + * Extend the query builder with the needed functions. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return void + */ + public function extend(Builder $builder) + { + foreach ($this->extensions as $extension) { + $this->{"add{$extension}"}($builder); + } + + $builder->onDelete(function (Builder $builder) { + $column = $this->getDeletedAtColumn($builder); + + return $builder->update([ + $column => $builder->getModel()->freshTimestampString(), + ]); + }); + } + + /** + * Get the "deleted at" column for the builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return string + */ + protected function getDeletedAtColumn(Builder $builder) + { + if (count((array) $builder->getQuery()->joins) > 0) { + return $builder->getModel()->getQualifiedDeletedAtColumn(); + } + + return $builder->getModel()->getDeletedAtColumn(); + } + + /** + * Add the restore extension to the builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return void + */ + protected function addRestore(Builder $builder) + { + $builder->macro('restore', function (Builder $builder) { + $builder->withTrashed(); + + return $builder->update([$builder->getModel()->getDeletedAtColumn() => null]); + }); + } + + /** + * Add the with-trashed extension to the builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return void + */ + protected function addWithTrashed(Builder $builder) + { + $builder->macro('withTrashed', function (Builder $builder, $withTrashed = true) { + if (! $withTrashed) { + return $builder->withoutTrashed(); + } + + return $builder->withoutGlobalScope($this); + }); + } + + /** + * Add the without-trashed extension to the builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return void + */ + protected function addWithoutTrashed(Builder $builder) + { + $builder->macro('withoutTrashed', function (Builder $builder) { + $model = $builder->getModel(); + + $builder->withoutGlobalScope($this)->whereNull( + $model->getQualifiedDeletedAtColumn() + ); + + return $builder; + }); + } + + /** + * Add the only-trashed extension to the builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return void + */ + protected function addOnlyTrashed(Builder $builder) + { + $builder->macro('onlyTrashed', function (Builder $builder) { + $model = $builder->getModel(); + + $builder->withoutGlobalScope($this)->whereNotNull( + $model->getQualifiedDeletedAtColumn() + ); + + return $builder; + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/ConnectionEvent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/ConnectionEvent.php new file mode 100644 index 0000000..818c785 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/ConnectionEvent.php @@ -0,0 +1,32 @@ +connection = $connection; + $this->connectionName = $connection->getName(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/DatabaseRefreshed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/DatabaseRefreshed.php new file mode 100644 index 0000000..5b1fb45 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/DatabaseRefreshed.php @@ -0,0 +1,10 @@ +method = $method; + $this->migration = $migration; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/MigrationStarted.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/MigrationStarted.php new file mode 100644 index 0000000..3f206b4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/MigrationStarted.php @@ -0,0 +1,8 @@ +method = $method; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/MigrationsStarted.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/MigrationsStarted.php new file mode 100644 index 0000000..5283b49 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/MigrationsStarted.php @@ -0,0 +1,8 @@ +model = $model; + $this->count = $count; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/NoPendingMigrations.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/NoPendingMigrations.php new file mode 100644 index 0000000..100f786 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/NoPendingMigrations.php @@ -0,0 +1,24 @@ +method = $method; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/QueryExecuted.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/QueryExecuted.php new file mode 100644 index 0000000..833a21e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/QueryExecuted.php @@ -0,0 +1,59 @@ +sql = $sql; + $this->time = $time; + $this->bindings = $bindings; + $this->connection = $connection; + $this->connectionName = $connection->getName(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/SchemaDumped.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/SchemaDumped.php new file mode 100644 index 0000000..1cbbfff --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/SchemaDumped.php @@ -0,0 +1,41 @@ +connection = $connection; + $this->connectionName = $connection->getName(); + $this->path = $path; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/SchemaLoaded.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/SchemaLoaded.php new file mode 100644 index 0000000..061a079 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/SchemaLoaded.php @@ -0,0 +1,41 @@ +connection = $connection; + $this->connectionName = $connection->getName(); + $this->path = $path; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/StatementPrepared.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/StatementPrepared.php new file mode 100644 index 0000000..2f60323 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/StatementPrepared.php @@ -0,0 +1,33 @@ +statement = $statement; + $this->connection = $connection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/TransactionBeginning.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/TransactionBeginning.php new file mode 100644 index 0000000..3287b5c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Events/TransactionBeginning.php @@ -0,0 +1,8 @@ +isExpression($table)) { + return $this->wrap($this->tablePrefix.$table, true); + } + + return $this->getValue($table); + } + + /** + * Wrap a value in keyword identifiers. + * + * @param \Illuminate\Database\Query\Expression|string $value + * @param bool $prefixAlias + * @return string + */ + public function wrap($value, $prefixAlias = false) + { + if ($this->isExpression($value)) { + return $this->getValue($value); + } + + // If the value being wrapped has a column alias we will need to separate out + // the pieces so we can wrap each of the segments of the expression on its + // own, and then join these both back together using the "as" connector. + if (stripos($value, ' as ') !== false) { + return $this->wrapAliasedValue($value, $prefixAlias); + } + + return $this->wrapSegments(explode('.', $value)); + } + + /** + * Wrap a value that has an alias. + * + * @param string $value + * @param bool $prefixAlias + * @return string + */ + protected function wrapAliasedValue($value, $prefixAlias = false) + { + $segments = preg_split('/\s+as\s+/i', $value); + + // If we are wrapping a table we need to prefix the alias with the table prefix + // as well in order to generate proper syntax. If this is a column of course + // no prefix is necessary. The condition will be true when from wrapTable. + if ($prefixAlias) { + $segments[1] = $this->tablePrefix.$segments[1]; + } + + return $this->wrap($segments[0]).' as '.$this->wrapValue($segments[1]); + } + + /** + * Wrap the given value segments. + * + * @param array $segments + * @return string + */ + protected function wrapSegments($segments) + { + return collect($segments)->map(function ($segment, $key) use ($segments) { + return $key == 0 && count($segments) > 1 + ? $this->wrapTable($segment) + : $this->wrapValue($segment); + })->implode('.'); + } + + /** + * Wrap a single string in keyword identifiers. + * + * @param string $value + * @return string + */ + protected function wrapValue($value) + { + if ($value !== '*') { + return '"'.str_replace('"', '""', $value).'"'; + } + + return $value; + } + + /** + * Convert an array of column names into a delimited string. + * + * @param array $columns + * @return string + */ + public function columnize(array $columns) + { + return implode(', ', array_map([$this, 'wrap'], $columns)); + } + + /** + * Create query parameter place-holders for an array. + * + * @param array $values + * @return string + */ + public function parameterize(array $values) + { + return implode(', ', array_map([$this, 'parameter'], $values)); + } + + /** + * Get the appropriate query parameter place-holder for a value. + * + * @param mixed $value + * @return string + */ + public function parameter($value) + { + return $this->isExpression($value) ? $this->getValue($value) : '?'; + } + + /** + * Quote the given string literal. + * + * @param string|array $value + * @return string + */ + public function quoteString($value) + { + if (is_array($value)) { + return implode(', ', array_map([$this, __FUNCTION__], $value)); + } + + return "'$value'"; + } + + /** + * Determine if the given value is a raw expression. + * + * @param mixed $value + * @return bool + */ + public function isExpression($value) + { + return $value instanceof Expression; + } + + /** + * Get the value of a raw expression. + * + * @param \Illuminate\Database\Query\Expression $expression + * @return mixed + */ + public function getValue($expression) + { + return $expression->getValue(); + } + + /** + * Get the format for database stored dates. + * + * @return string + */ + public function getDateFormat() + { + return 'Y-m-d H:i:s'; + } + + /** + * Get the grammar's table prefix. + * + * @return string + */ + public function getTablePrefix() + { + return $this->tablePrefix; + } + + /** + * Set the grammar's table prefix. + * + * @param string $prefix + * @return $this + */ + public function setTablePrefix($prefix) + { + $this->tablePrefix = $prefix; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/LazyLoadingViolationException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/LazyLoadingViolationException.php new file mode 100644 index 0000000..1bcd40c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/LazyLoadingViolationException.php @@ -0,0 +1,39 @@ +model = $class; + $this->relation = $relation; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php new file mode 100755 index 0000000..9ae7685 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php @@ -0,0 +1,226 @@ + 'command.migrate', + 'MigrateFresh' => 'command.migrate.fresh', + 'MigrateInstall' => 'command.migrate.install', + 'MigrateRefresh' => 'command.migrate.refresh', + 'MigrateReset' => 'command.migrate.reset', + 'MigrateRollback' => 'command.migrate.rollback', + 'MigrateStatus' => 'command.migrate.status', + 'MigrateMake' => 'command.migrate.make', + ]; + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $this->registerRepository(); + + $this->registerMigrator(); + + $this->registerCreator(); + + $this->registerCommands($this->commands); + } + + /** + * Register the migration repository service. + * + * @return void + */ + protected function registerRepository() + { + $this->app->singleton('migration.repository', function ($app) { + $table = $app['config']['database.migrations']; + + return new DatabaseMigrationRepository($app['db'], $table); + }); + } + + /** + * Register the migrator service. + * + * @return void + */ + protected function registerMigrator() + { + // The migrator is responsible for actually running and rollback the migration + // files in the application. We'll pass in our database connection resolver + // so the migrator can resolve any of these connections when it needs to. + $this->app->singleton('migrator', function ($app) { + $repository = $app['migration.repository']; + + return new Migrator($repository, $app['db'], $app['files'], $app['events']); + }); + } + + /** + * Register the migration creator. + * + * @return void + */ + protected function registerCreator() + { + $this->app->singleton('migration.creator', function ($app) { + return new MigrationCreator($app['files'], $app->basePath('stubs')); + }); + } + + /** + * Register the given commands. + * + * @param array $commands + * @return void + */ + protected function registerCommands(array $commands) + { + foreach (array_keys($commands) as $command) { + $this->{"register{$command}Command"}(); + } + + $this->commands(array_values($commands)); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateCommand() + { + $this->app->singleton('command.migrate', function ($app) { + return new MigrateCommand($app['migrator'], $app[Dispatcher::class]); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateFreshCommand() + { + $this->app->singleton('command.migrate.fresh', function () { + return new FreshCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateInstallCommand() + { + $this->app->singleton('command.migrate.install', function ($app) { + return new InstallCommand($app['migration.repository']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateMakeCommand() + { + $this->app->singleton('command.migrate.make', function ($app) { + // Once we have the migration creator registered, we will create the command + // and inject the creator. The creator is responsible for the actual file + // creation of the migrations, and may be extended by these developers. + $creator = $app['migration.creator']; + + $composer = $app['composer']; + + return new MigrateMakeCommand($creator, $composer); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateRefreshCommand() + { + $this->app->singleton('command.migrate.refresh', function () { + return new RefreshCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateResetCommand() + { + $this->app->singleton('command.migrate.reset', function ($app) { + return new ResetCommand($app['migrator']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateRollbackCommand() + { + $this->app->singleton('command.migrate.rollback', function ($app) { + return new RollbackCommand($app['migrator']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMigrateStatusCommand() + { + $this->app->singleton('command.migrate.status', function ($app) { + return new StatusCommand($app['migrator']); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return array_merge([ + 'migrator', 'migration.repository', 'migration.creator', + ], array_values($this->commands)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php new file mode 100755 index 0000000..ed42756 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php @@ -0,0 +1,224 @@ +table = $table; + $this->resolver = $resolver; + } + + /** + * Get the completed migrations. + * + * @return array + */ + public function getRan() + { + return $this->table() + ->orderBy('batch', 'asc') + ->orderBy('migration', 'asc') + ->pluck('migration')->all(); + } + + /** + * Get list of migrations. + * + * @param int $steps + * @return array + */ + public function getMigrations($steps) + { + $query = $this->table()->where('batch', '>=', '1'); + + return $query->orderBy('batch', 'desc') + ->orderBy('migration', 'desc') + ->take($steps)->get()->all(); + } + + /** + * Get the last migration batch. + * + * @return array + */ + public function getLast() + { + $query = $this->table()->where('batch', $this->getLastBatchNumber()); + + return $query->orderBy('migration', 'desc')->get()->all(); + } + + /** + * Get the completed migrations with their batch numbers. + * + * @return array + */ + public function getMigrationBatches() + { + return $this->table() + ->orderBy('batch', 'asc') + ->orderBy('migration', 'asc') + ->pluck('batch', 'migration')->all(); + } + + /** + * Log that a migration was run. + * + * @param string $file + * @param int $batch + * @return void + */ + public function log($file, $batch) + { + $record = ['migration' => $file, 'batch' => $batch]; + + $this->table()->insert($record); + } + + /** + * Remove a migration from the log. + * + * @param object $migration + * @return void + */ + public function delete($migration) + { + $this->table()->where('migration', $migration->migration)->delete(); + } + + /** + * Get the next migration batch number. + * + * @return int + */ + public function getNextBatchNumber() + { + return $this->getLastBatchNumber() + 1; + } + + /** + * Get the last migration batch number. + * + * @return int + */ + public function getLastBatchNumber() + { + return $this->table()->max('batch'); + } + + /** + * Create the migration repository data store. + * + * @return void + */ + public function createRepository() + { + $schema = $this->getConnection()->getSchemaBuilder(); + + $schema->create($this->table, function ($table) { + // The migrations table is responsible for keeping track of which of the + // migrations have actually run for the application. We'll create the + // table to hold the migration file's path as well as the batch ID. + $table->increments('id'); + $table->string('migration'); + $table->integer('batch'); + }); + } + + /** + * Determine if the migration repository exists. + * + * @return bool + */ + public function repositoryExists() + { + $schema = $this->getConnection()->getSchemaBuilder(); + + return $schema->hasTable($this->table); + } + + /** + * Delete the migration repository data store. + * + * @return void + */ + public function deleteRepository() + { + $schema = $this->getConnection()->getSchemaBuilder(); + + $schema->drop($this->table); + } + + /** + * Get a query builder for the migration table. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function table() + { + return $this->getConnection()->table($this->table)->useWritePdo(); + } + + /** + * Get the connection resolver instance. + * + * @return \Illuminate\Database\ConnectionResolverInterface + */ + public function getConnectionResolver() + { + return $this->resolver; + } + + /** + * Resolve the database connection instance. + * + * @return \Illuminate\Database\Connection + */ + public function getConnection() + { + return $this->resolver->connection($this->connection); + } + + /** + * Set the information source to gather data. + * + * @param string $name + * @return void + */ + public function setSource($name) + { + $this->connection = $name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migration.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migration.php new file mode 100755 index 0000000..a58f784 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migration.php @@ -0,0 +1,30 @@ +connection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationCreator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationCreator.php new file mode 100755 index 0000000..a79039a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationCreator.php @@ -0,0 +1,236 @@ +files = $files; + $this->customStubPath = $customStubPath; + } + + /** + * Create a new migration at the given path. + * + * @param string $name + * @param string $path + * @param string|null $table + * @param bool $create + * @return string + * + * @throws \Exception + */ + public function create($name, $path, $table = null, $create = false) + { + $this->ensureMigrationDoesntAlreadyExist($name, $path); + + // First we will get the stub file for the migration, which serves as a type + // of template for the migration. Once we have those we will populate the + // various place-holders, save the file, and run the post create event. + $stub = $this->getStub($table, $create); + + $path = $this->getPath($name, $path); + + $this->files->ensureDirectoryExists(dirname($path)); + + $this->files->put( + $path, $this->populateStub($name, $stub, $table) + ); + + // Next, we will fire any hooks that are supposed to fire after a migration is + // created. Once that is done we'll be ready to return the full path to the + // migration file so it can be used however it's needed by the developer. + $this->firePostCreateHooks($table); + + return $path; + } + + /** + * Ensure that a migration with the given name doesn't already exist. + * + * @param string $name + * @param string $migrationPath + * @return void + * + * @throws \InvalidArgumentException + */ + protected function ensureMigrationDoesntAlreadyExist($name, $migrationPath = null) + { + if (! empty($migrationPath)) { + $migrationFiles = $this->files->glob($migrationPath.'/*.php'); + + foreach ($migrationFiles as $migrationFile) { + $this->files->requireOnce($migrationFile); + } + } + + if (class_exists($className = $this->getClassName($name))) { + throw new InvalidArgumentException("A {$className} class already exists."); + } + } + + /** + * Get the migration stub file. + * + * @param string|null $table + * @param bool $create + * @return string + */ + protected function getStub($table, $create) + { + if (is_null($table)) { + $stub = $this->files->exists($customPath = $this->customStubPath.'/migration.stub') + ? $customPath + : $this->stubPath().'/migration.stub'; + } elseif ($create) { + $stub = $this->files->exists($customPath = $this->customStubPath.'/migration.create.stub') + ? $customPath + : $this->stubPath().'/migration.create.stub'; + } else { + $stub = $this->files->exists($customPath = $this->customStubPath.'/migration.update.stub') + ? $customPath + : $this->stubPath().'/migration.update.stub'; + } + + return $this->files->get($stub); + } + + /** + * Populate the place-holders in the migration stub. + * + * @param string $name + * @param string $stub + * @param string|null $table + * @return string + */ + protected function populateStub($name, $stub, $table) + { + $stub = str_replace( + ['DummyClass', '{{ class }}', '{{class}}'], + $this->getClassName($name), $stub + ); + + // Here we will replace the table place-holders with the table specified by + // the developer, which is useful for quickly creating a tables creation + // or update migration from the console instead of typing it manually. + if (! is_null($table)) { + $stub = str_replace( + ['DummyTable', '{{ table }}', '{{table}}'], + $table, $stub + ); + } + + return $stub; + } + + /** + * Get the class name of a migration name. + * + * @param string $name + * @return string + */ + protected function getClassName($name) + { + return Str::studly($name); + } + + /** + * Get the full path to the migration. + * + * @param string $name + * @param string $path + * @return string + */ + protected function getPath($name, $path) + { + return $path.'/'.$this->getDatePrefix().'_'.$name.'.php'; + } + + /** + * Fire the registered post create hooks. + * + * @param string|null $table + * @return void + */ + protected function firePostCreateHooks($table) + { + foreach ($this->postCreate as $callback) { + $callback($table); + } + } + + /** + * Register a post migration create hook. + * + * @param \Closure $callback + * @return void + */ + public function afterCreate(Closure $callback) + { + $this->postCreate[] = $callback; + } + + /** + * Get the date prefix for the migration. + * + * @return string + */ + protected function getDatePrefix() + { + return date('Y_m_d_His'); + } + + /** + * Get the path to the stubs. + * + * @return string + */ + public function stubPath() + { + return __DIR__.'/stubs'; + } + + /** + * Get the filesystem instance. + * + * @return \Illuminate\Filesystem\Filesystem + */ + public function getFilesystem() + { + return $this->files; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationRepositoryInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationRepositoryInterface.php new file mode 100755 index 0000000..840a5e1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationRepositoryInterface.php @@ -0,0 +1,88 @@ +files = $files; + $this->events = $dispatcher; + $this->resolver = $resolver; + $this->repository = $repository; + } + + /** + * Run the pending migrations at a given path. + * + * @param array|string $paths + * @param array $options + * @return array + */ + public function run($paths = [], array $options = []) + { + // Once we grab all of the migration files for the path, we will compare them + // against the migrations that have already been run for this package then + // run each of the outstanding migrations against a database connection. + $files = $this->getMigrationFiles($paths); + + $this->requireFiles($migrations = $this->pendingMigrations( + $files, $this->repository->getRan() + )); + + // Once we have all these migrations that are outstanding we are ready to run + // we will go ahead and run them "up". This will execute each migration as + // an operation against a database. Then we'll return this list of them. + $this->runPending($migrations, $options); + + return $migrations; + } + + /** + * Get the migration files that have not yet run. + * + * @param array $files + * @param array $ran + * @return array + */ + protected function pendingMigrations($files, $ran) + { + return Collection::make($files) + ->reject(function ($file) use ($ran) { + return in_array($this->getMigrationName($file), $ran); + })->values()->all(); + } + + /** + * Run an array of migrations. + * + * @param array $migrations + * @param array $options + * @return void + */ + public function runPending(array $migrations, array $options = []) + { + // First we will just make sure that there are any migrations to run. If there + // aren't, we will just make a note of it to the developer so they're aware + // that all of the migrations have been run against this database system. + if (count($migrations) === 0) { + $this->fireMigrationEvent(new NoPendingMigrations('up')); + + $this->note('Nothing to migrate.'); + + return; + } + + // Next, we will get the next batch number for the migrations so we can insert + // correct batch number in the database migrations repository when we store + // each migration's execution. We will also extract a few of the options. + $batch = $this->repository->getNextBatchNumber(); + + $pretend = $options['pretend'] ?? false; + + $step = $options['step'] ?? false; + + $this->fireMigrationEvent(new MigrationsStarted('up')); + + // Once we have the array of migrations, we will spin through them and run the + // migrations "up" so the changes are made to the databases. We'll then log + // that the migration was run so we don't repeat it next time we execute. + foreach ($migrations as $file) { + $this->runUp($file, $batch, $pretend); + + if ($step) { + $batch++; + } + } + + $this->fireMigrationEvent(new MigrationsEnded('up')); + } + + /** + * Run "up" a migration instance. + * + * @param string $file + * @param int $batch + * @param bool $pretend + * @return void + */ + protected function runUp($file, $batch, $pretend) + { + // First we will resolve a "real" instance of the migration class from this + // migration file name. Once we have the instances we can run the actual + // command such as "up" or "down", or we can just simulate the action. + $migration = $this->resolvePath($file); + + $name = $this->getMigrationName($file); + + if ($pretend) { + return $this->pretendToRun($migration, 'up'); + } + + $this->note("Migrating: {$name}"); + + $startTime = microtime(true); + + $this->runMigration($migration, 'up'); + + $runTime = number_format((microtime(true) - $startTime) * 1000, 2); + + // Once we have run a migrations class, we will log that it was run in this + // repository so that we don't try to run it next time we do a migration + // in the application. A migration repository keeps the migrate order. + $this->repository->log($name, $batch); + + $this->note("Migrated: {$name} ({$runTime}ms)"); + } + + /** + * Rollback the last migration operation. + * + * @param array|string $paths + * @param array $options + * @return array + */ + public function rollback($paths = [], array $options = []) + { + // We want to pull in the last batch of migrations that ran on the previous + // migration operation. We'll then reverse those migrations and run each + // of them "down" to reverse the last migration "operation" which ran. + $migrations = $this->getMigrationsForRollback($options); + + if (count($migrations) === 0) { + $this->fireMigrationEvent(new NoPendingMigrations('down')); + + $this->note('Nothing to rollback.'); + + return []; + } + + return $this->rollbackMigrations($migrations, $paths, $options); + } + + /** + * Get the migrations for a rollback operation. + * + * @param array $options + * @return array + */ + protected function getMigrationsForRollback(array $options) + { + if (($steps = $options['step'] ?? 0) > 0) { + return $this->repository->getMigrations($steps); + } + + return $this->repository->getLast(); + } + + /** + * Rollback the given migrations. + * + * @param array $migrations + * @param array|string $paths + * @param array $options + * @return array + */ + protected function rollbackMigrations(array $migrations, $paths, array $options) + { + $rolledBack = []; + + $this->requireFiles($files = $this->getMigrationFiles($paths)); + + $this->fireMigrationEvent(new MigrationsStarted('down')); + + // Next we will run through all of the migrations and call the "down" method + // which will reverse each migration in order. This getLast method on the + // repository already returns these migration's names in reverse order. + foreach ($migrations as $migration) { + $migration = (object) $migration; + + if (! $file = Arr::get($files, $migration->migration)) { + $this->note("Migration not found: {$migration->migration}"); + + continue; + } + + $rolledBack[] = $file; + + $this->runDown( + $file, $migration, + $options['pretend'] ?? false + ); + } + + $this->fireMigrationEvent(new MigrationsEnded('down')); + + return $rolledBack; + } + + /** + * Rolls all of the currently applied migrations back. + * + * @param array|string $paths + * @param bool $pretend + * @return array + */ + public function reset($paths = [], $pretend = false) + { + // Next, we will reverse the migration list so we can run them back in the + // correct order for resetting this database. This will allow us to get + // the database back into its "empty" state ready for the migrations. + $migrations = array_reverse($this->repository->getRan()); + + if (count($migrations) === 0) { + $this->note('Nothing to rollback.'); + + return []; + } + + return $this->resetMigrations($migrations, $paths, $pretend); + } + + /** + * Reset the given migrations. + * + * @param array $migrations + * @param array $paths + * @param bool $pretend + * @return array + */ + protected function resetMigrations(array $migrations, array $paths, $pretend = false) + { + // Since the getRan method that retrieves the migration name just gives us the + // migration name, we will format the names into objects with the name as a + // property on the objects so that we can pass it to the rollback method. + $migrations = collect($migrations)->map(function ($m) { + return (object) ['migration' => $m]; + })->all(); + + return $this->rollbackMigrations( + $migrations, $paths, compact('pretend') + ); + } + + /** + * Run "down" a migration instance. + * + * @param string $file + * @param object $migration + * @param bool $pretend + * @return void + */ + protected function runDown($file, $migration, $pretend) + { + // First we will get the file name of the migration so we can resolve out an + // instance of the migration. Once we get an instance we can either run a + // pretend execution of the migration or we can run the real migration. + $instance = $this->resolvePath($file); + + $name = $this->getMigrationName($file); + + $this->note("Rolling back: {$name}"); + + if ($pretend) { + return $this->pretendToRun($instance, 'down'); + } + + $startTime = microtime(true); + + $this->runMigration($instance, 'down'); + + $runTime = number_format((microtime(true) - $startTime) * 1000, 2); + + // Once we have successfully run the migration "down" we will remove it from + // the migration repository so it will be considered to have not been run + // by the application then will be able to fire by any later operation. + $this->repository->delete($migration); + + $this->note("Rolled back: {$name} ({$runTime}ms)"); + } + + /** + * Run a migration inside a transaction if the database supports it. + * + * @param object $migration + * @param string $method + * @return void + */ + protected function runMigration($migration, $method) + { + $connection = $this->resolveConnection( + $migration->getConnection() + ); + + $callback = function () use ($connection, $migration, $method) { + if (method_exists($migration, $method)) { + $this->fireMigrationEvent(new MigrationStarted($migration, $method)); + + $this->runMethod($connection, $migration, $method); + + $this->fireMigrationEvent(new MigrationEnded($migration, $method)); + } + }; + + $this->getSchemaGrammar($connection)->supportsSchemaTransactions() + && $migration->withinTransaction + ? $connection->transaction($callback) + : $callback(); + } + + /** + * Pretend to run the migrations. + * + * @param object $migration + * @param string $method + * @return void + */ + protected function pretendToRun($migration, $method) + { + try { + foreach ($this->getQueries($migration, $method) as $query) { + $name = get_class($migration); + + $reflectionClass = new ReflectionClass($migration); + + if ($reflectionClass->isAnonymous()) { + $name = $this->getMigrationName($reflectionClass->getFileName()); + } + + $this->note("{$name}: {$query['query']}"); + } + } catch (SchemaException $e) { + $name = get_class($migration); + + $this->note("{$name}: failed to dump queries. This may be due to changing database columns using Doctrine, which is not supported while pretending to run migrations."); + } + } + + /** + * Get all of the queries that would be run for a migration. + * + * @param object $migration + * @param string $method + * @return array + */ + protected function getQueries($migration, $method) + { + // Now that we have the connections we can resolve it and pretend to run the + // queries against the database returning the array of raw SQL statements + // that would get fired against the database system for this migration. + $db = $this->resolveConnection( + $migration->getConnection() + ); + + return $db->pretend(function () use ($db, $migration, $method) { + if (method_exists($migration, $method)) { + $this->runMethod($db, $migration, $method); + } + }); + } + + /** + * Run a migration method on the given connection. + * + * @param \Illuminate\Database\Connection $connection + * @param object $migration + * @param string $method + * @return void + */ + protected function runMethod($connection, $migration, $method) + { + $previousConnection = $this->resolver->getDefaultConnection(); + + try { + $this->resolver->setDefaultConnection($connection->getName()); + + $migration->{$method}(); + } finally { + $this->resolver->setDefaultConnection($previousConnection); + } + } + + /** + * Resolve a migration instance from a file. + * + * @param string $file + * @return object + */ + public function resolve($file) + { + $class = $this->getMigrationClass($file); + + return new $class; + } + + /** + * Resolve a migration instance from a migration path. + * + * @param string $path + * @return object + */ + protected function resolvePath(string $path) + { + $class = $this->getMigrationClass($this->getMigrationName($path)); + + if (class_exists($class) && realpath($path) == (new ReflectionClass($class))->getFileName()) { + return new $class; + } + + $migration = $this->files->getRequire($path); + + return is_object($migration) ? $migration : new $class; + } + + /** + * Generate a migration class name based on the migration file name. + * + * @param string $migrationName + * @return string + */ + protected function getMigrationClass(string $migrationName): string + { + return Str::studly(implode('_', array_slice(explode('_', $migrationName), 4))); + } + + /** + * Get all of the migration files in a given path. + * + * @param string|array $paths + * @return array + */ + public function getMigrationFiles($paths) + { + return Collection::make($paths)->flatMap(function ($path) { + return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php'); + })->filter()->values()->keyBy(function ($file) { + return $this->getMigrationName($file); + })->sortBy(function ($file, $key) { + return $key; + })->all(); + } + + /** + * Require in all the migration files in a given path. + * + * @param array $files + * @return void + */ + public function requireFiles(array $files) + { + foreach ($files as $file) { + $this->files->requireOnce($file); + } + } + + /** + * Get the name of the migration. + * + * @param string $path + * @return string + */ + public function getMigrationName($path) + { + return str_replace('.php', '', basename($path)); + } + + /** + * Register a custom migration path. + * + * @param string $path + * @return void + */ + public function path($path) + { + $this->paths = array_unique(array_merge($this->paths, [$path])); + } + + /** + * Get all of the custom migration paths. + * + * @return array + */ + public function paths() + { + return $this->paths; + } + + /** + * Get the default connection name. + * + * @return string + */ + public function getConnection() + { + return $this->connection; + } + + /** + * Execute the given callback using the given connection as the default connection. + * + * @param string $name + * @param callable $callback + * @return mixed + */ + public function usingConnection($name, callable $callback) + { + $previousConnection = $this->resolver->getDefaultConnection(); + + $this->setConnection($name); + + return tap($callback(), function () use ($previousConnection) { + $this->setConnection($previousConnection); + }); + } + + /** + * Set the default connection name. + * + * @param string $name + * @return void + */ + public function setConnection($name) + { + if (! is_null($name)) { + $this->resolver->setDefaultConnection($name); + } + + $this->repository->setSource($name); + + $this->connection = $name; + } + + /** + * Resolve the database connection instance. + * + * @param string $connection + * @return \Illuminate\Database\Connection + */ + public function resolveConnection($connection) + { + return $this->resolver->connection($connection ?: $this->connection); + } + + /** + * Get the schema grammar out of a migration connection. + * + * @param \Illuminate\Database\Connection $connection + * @return \Illuminate\Database\Schema\Grammars\Grammar + */ + protected function getSchemaGrammar($connection) + { + if (is_null($grammar = $connection->getSchemaGrammar())) { + $connection->useDefaultSchemaGrammar(); + + $grammar = $connection->getSchemaGrammar(); + } + + return $grammar; + } + + /** + * Get the migration repository instance. + * + * @return \Illuminate\Database\Migrations\MigrationRepositoryInterface + */ + public function getRepository() + { + return $this->repository; + } + + /** + * Determine if the migration repository exists. + * + * @return bool + */ + public function repositoryExists() + { + return $this->repository->repositoryExists(); + } + + /** + * Determine if any migrations have been run. + * + * @return bool + */ + public function hasRunAnyMigrations() + { + return $this->repositoryExists() && count($this->repository->getRan()) > 0; + } + + /** + * Delete the migration repository data store. + * + * @return void + */ + public function deleteRepository() + { + return $this->repository->deleteRepository(); + } + + /** + * Get the file system instance. + * + * @return \Illuminate\Filesystem\Filesystem + */ + public function getFilesystem() + { + return $this->files; + } + + /** + * Set the output implementation that should be used by the console. + * + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @return $this + */ + public function setOutput(OutputInterface $output) + { + $this->output = $output; + + return $this; + } + + /** + * Write a note to the console's output. + * + * @param string $message + * @return void + */ + protected function note($message) + { + if ($this->output) { + $this->output->writeln($message); + } + } + + /** + * Fire the given event for the migration. + * + * @param \Illuminate\Contracts\Database\Events\MigrationEvent $event + * @return void + */ + public function fireMigrationEvent($event) + { + if ($this->events) { + $this->events->dispatch($event); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/migration.create.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/migration.create.stub new file mode 100755 index 0000000..f4a56a0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/migration.create.stub @@ -0,0 +1,31 @@ +id(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('{{ table }}'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/migration.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/migration.stub new file mode 100755 index 0000000..fd0e437 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/migration.stub @@ -0,0 +1,28 @@ +getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), 'MariaDB') !== false; + } + + /** + * Get the default query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\MySqlGrammar + */ + protected function getDefaultQueryGrammar() + { + return $this->withTablePrefix(new QueryGrammar); + } + + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\MySqlBuilder + */ + public function getSchemaBuilder() + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new MySqlBuilder($this); + } + + /** + * Get the default schema grammar instance. + * + * @return \Illuminate\Database\Schema\Grammars\MySqlGrammar + */ + protected function getDefaultSchemaGrammar() + { + return $this->withTablePrefix(new SchemaGrammar); + } + + /** + * Get the schema state for the connection. + * + * @param \Illuminate\Filesystem\Filesystem|null $files + * @param callable|null $processFactory + * @return \Illuminate\Database\Schema\MySqlSchemaState + */ + public function getSchemaState(Filesystem $files = null, callable $processFactory = null) + { + return new MySqlSchemaState($this, $files, $processFactory); + } + + /** + * Get the default post processor instance. + * + * @return \Illuminate\Database\Query\Processors\MySqlProcessor + */ + protected function getDefaultPostProcessor() + { + return new MySqlProcessor; + } + + /** + * Get the Doctrine DBAL driver. + * + * @return \Doctrine\DBAL\Driver\PDOMySql\Driver|\Illuminate\Database\PDO\MySqlDriver + */ + protected function getDoctrineDriver() + { + return class_exists(Version::class) ? new DoctrineDriver : new MySqlDriver; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/Concerns/ConnectsToDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/Concerns/ConnectsToDatabase.php new file mode 100644 index 0000000..84c3338 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/Concerns/ConnectsToDatabase.php @@ -0,0 +1,27 @@ +connection = $connection; + } + + /** + * Execute an SQL statement. + * + * @param string $statement + * @return int + */ + public function exec(string $statement): int + { + try { + $result = $this->connection->exec($statement); + + \assert($result !== false); + + return $result; + } catch (PDOException $exception) { + throw Exception::new($exception); + } + } + + /** + * Prepare a new SQL statement. + * + * @param string $sql + * @return \Doctrine\DBAL\Driver\Statement + */ + public function prepare(string $sql): StatementInterface + { + try { + return $this->createStatement( + $this->connection->prepare($sql) + ); + } catch (PDOException $exception) { + throw Exception::new($exception); + } + } + + /** + * Execute a new query against the connection. + * + * @param string $sql + * @return \Doctrine\DBAL\Driver\Result + */ + public function query(string $sql): ResultInterface + { + try { + $stmt = $this->connection->query($sql); + + \assert($stmt instanceof PDOStatement); + + return new Result($stmt); + } catch (PDOException $exception) { + throw Exception::new($exception); + } + } + + /** + * Get the last insert ID. + * + * @param string|null $name + * @return mixed + */ + public function lastInsertId($name = null) + { + try { + if ($name === null) { + return $this->connection->lastInsertId(); + } + + return $this->connection->lastInsertId($name); + } catch (PDOException $exception) { + throw Exception::new($exception); + } + } + + /** + * Create a new statement instance. + * + * @param \PDOStatement $stmt + * @return \Doctrine\DBAL\Driver\PDO\Statement + */ + protected function createStatement(PDOStatement $stmt): Statement + { + return new Statement($stmt); + } + + /** + * Begin a new database transaction. + * + * @return void + */ + public function beginTransaction() + { + return $this->connection->beginTransaction(); + } + + /** + * Commit a database transaction. + * + * @return void + */ + public function commit() + { + return $this->connection->commit(); + } + + /** + * Rollback a database transaction. + * + * @return void + */ + public function rollBack() + { + return $this->connection->rollBack(); + } + + /** + * Wrap quotes around the given input. + * + * @param string $input + * @param string $type + * @return string + */ + public function quote($input, $type = ParameterType::STRING) + { + return $this->connection->quote($input, $type); + } + + /** + * Get the server version for the connection. + * + * @return string + */ + public function getServerVersion() + { + return $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION); + } + + /** + * Get the wrapped PDO connection. + * + * @return \PDO + */ + public function getWrappedConnection(): PDO + { + return $this->connection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/MySqlDriver.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/MySqlDriver.php new file mode 100644 index 0000000..5f68c6f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/MySqlDriver.php @@ -0,0 +1,11 @@ +connection = $connection; + } + + /** + * Prepare a new SQL statement. + * + * @param string $sql + * @return \Doctrine\DBAL\Driver\Statement + */ + public function prepare(string $sql): StatementInterface + { + return new Statement( + $this->connection->prepare($sql) + ); + } + + /** + * Execute a new query against the connection. + * + * @param string $sql + * @return \Doctrine\DBAL\Driver\Result + */ + public function query(string $sql): Result + { + return $this->connection->query($sql); + } + + /** + * Execute an SQL statement. + * + * @param string $statement + * @return int + */ + public function exec(string $statement): int + { + return $this->connection->exec($statement); + } + + /** + * Get the last insert ID. + * + * @param string|null $name + * @return mixed + */ + public function lastInsertId($name = null) + { + if ($name === null) { + return $this->connection->lastInsertId($name); + } + + return $this->prepare('SELECT CONVERT(VARCHAR(MAX), current_value) FROM sys.sequences WHERE name = ?') + ->execute([$name]) + ->fetchOne(); + } + + /** + * Begin a new database transaction. + * + * @return void + */ + public function beginTransaction() + { + return $this->connection->beginTransaction(); + } + + /** + * Commit a database transaction. + * + * @return void + */ + public function commit() + { + return $this->connection->commit(); + } + + /** + * Rollback a database transaction. + * + * @return void + */ + public function rollBack() + { + return $this->connection->rollBack(); + } + + /** + * Wrap quotes around the given input. + * + * @param string $value + * @param int $type + * @return string + */ + public function quote($value, $type = ParameterType::STRING) + { + $val = $this->connection->quote($value, $type); + + // Fix for a driver version terminating all values with null byte... + if (\is_string($val) && \strpos($val, "\0") !== false) { + $val = \substr($val, 0, -1); + } + + return $val; + } + + /** + * Get the server version for the connection. + * + * @return string + */ + public function getServerVersion() + { + return $this->connection->getServerVersion(); + } + + /** + * Get the wrapped PDO connection. + * + * @return \PDO + */ + public function getWrappedConnection(): PDO + { + return $this->connection->getWrappedConnection(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/SqlServerDriver.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/SqlServerDriver.php new file mode 100644 index 0000000..1373fc4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/PDO/SqlServerDriver.php @@ -0,0 +1,18 @@ + $value) { + if (is_int($value)) { + $pdoParam = PDO::PARAM_INT; + } elseif (is_resource($value)) { + $pdoParam = PDO::PARAM_LOB; + } else { + $pdoParam = PDO::PARAM_STR; + } + + $statement->bindValue( + is_string($key) ? $key : $key + 1, + $value, + $pdoParam + ); + } + } + + /** + * Get the default query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\PostgresGrammar + */ + protected function getDefaultQueryGrammar() + { + return $this->withTablePrefix(new QueryGrammar); + } + + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\PostgresBuilder + */ + public function getSchemaBuilder() + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new PostgresBuilder($this); + } + + /** + * Get the default schema grammar instance. + * + * @return \Illuminate\Database\Schema\Grammars\PostgresGrammar + */ + protected function getDefaultSchemaGrammar() + { + return $this->withTablePrefix(new SchemaGrammar); + } + + /** + * Get the schema state for the connection. + * + * @param \Illuminate\Filesystem\Filesystem|null $files + * @param callable|null $processFactory + * @return \Illuminate\Database\Schema\PostgresSchemaState + */ + public function getSchemaState(Filesystem $files = null, callable $processFactory = null) + { + return new PostgresSchemaState($this, $files, $processFactory); + } + + /** + * Get the default post processor instance. + * + * @return \Illuminate\Database\Query\Processors\PostgresProcessor + */ + protected function getDefaultPostProcessor() + { + return new PostgresProcessor; + } + + /** + * Get the Doctrine DBAL driver. + * + * @return \Doctrine\DBAL\Driver\PDOPgSql\Driver|\Illuminate\Database\PDO\PostgresDriver + */ + protected function getDoctrineDriver() + { + return class_exists(Version::class) ? new DoctrineDriver : new PostgresDriver; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php new file mode 100755 index 0000000..40bd0b9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php @@ -0,0 +1,3540 @@ + [], + 'from' => [], + 'join' => [], + 'where' => [], + 'groupBy' => [], + 'having' => [], + 'order' => [], + 'union' => [], + 'unionOrder' => [], + ]; + + /** + * An aggregate function and column to be run. + * + * @var array + */ + public $aggregate; + + /** + * The columns that should be returned. + * + * @var array + */ + public $columns; + + /** + * Indicates if the query returns distinct results. + * + * Occasionally contains the columns that should be distinct. + * + * @var bool|array + */ + public $distinct = false; + + /** + * The table which the query is targeting. + * + * @var string + */ + public $from; + + /** + * The table joins for the query. + * + * @var array + */ + public $joins; + + /** + * The where constraints for the query. + * + * @var array + */ + public $wheres = []; + + /** + * The groupings for the query. + * + * @var array + */ + public $groups; + + /** + * The having constraints for the query. + * + * @var array + */ + public $havings; + + /** + * The orderings for the query. + * + * @var array + */ + public $orders; + + /** + * The maximum number of records to return. + * + * @var int + */ + public $limit; + + /** + * The number of records to skip. + * + * @var int + */ + public $offset; + + /** + * The query union statements. + * + * @var array + */ + public $unions; + + /** + * The maximum number of union records to return. + * + * @var int + */ + public $unionLimit; + + /** + * The number of union records to skip. + * + * @var int + */ + public $unionOffset; + + /** + * The orderings for the union query. + * + * @var array + */ + public $unionOrders; + + /** + * Indicates whether row locking is being used. + * + * @var string|bool + */ + public $lock; + + /** + * The callbacks that should be invoked before the query is executed. + * + * @var array + */ + public $beforeQueryCallbacks = []; + + /** + * All of the available clause operators. + * + * @var string[] + */ + public $operators = [ + '=', '<', '>', '<=', '>=', '<>', '!=', '<=>', + 'like', 'like binary', 'not like', 'ilike', + '&', '|', '^', '<<', '>>', '&~', + 'rlike', 'not rlike', 'regexp', 'not regexp', + '~', '~*', '!~', '!~*', 'similar to', + 'not similar to', 'not ilike', '~~*', '!~~*', + ]; + + /** + * All of the available bitwise operators. + * + * @var string[] + */ + public $bitwiseOperators = [ + '&', '|', '^', '<<', '>>', '&~', + ]; + + /** + * Whether to use write pdo for the select. + * + * @var bool + */ + public $useWritePdo = false; + + /** + * Create a new query builder instance. + * + * @param \Illuminate\Database\ConnectionInterface $connection + * @param \Illuminate\Database\Query\Grammars\Grammar|null $grammar + * @param \Illuminate\Database\Query\Processors\Processor|null $processor + * @return void + */ + public function __construct(ConnectionInterface $connection, + Grammar $grammar = null, + Processor $processor = null) + { + $this->connection = $connection; + $this->grammar = $grammar ?: $connection->getQueryGrammar(); + $this->processor = $processor ?: $connection->getPostProcessor(); + } + + /** + * Set the columns to be selected. + * + * @param array|mixed $columns + * @return $this + */ + public function select($columns = ['*']) + { + $this->columns = []; + $this->bindings['select'] = []; + $columns = is_array($columns) ? $columns : func_get_args(); + + foreach ($columns as $as => $column) { + if (is_string($as) && $this->isQueryable($column)) { + $this->selectSub($column, $as); + } else { + $this->columns[] = $column; + } + } + + return $this; + } + + /** + * Add a subselect expression to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @return $this + * + * @throws \InvalidArgumentException + */ + public function selectSub($query, $as) + { + [$query, $bindings] = $this->createSub($query); + + return $this->selectRaw( + '('.$query.') as '.$this->grammar->wrap($as), $bindings + ); + } + + /** + * Add a new "raw" select expression to the query. + * + * @param string $expression + * @param array $bindings + * @return $this + */ + public function selectRaw($expression, array $bindings = []) + { + $this->addSelect(new Expression($expression)); + + if ($bindings) { + $this->addBinding($bindings, 'select'); + } + + return $this; + } + + /** + * Makes "from" fetch from a subquery. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $query + * @param string $as + * @return $this + * + * @throws \InvalidArgumentException + */ + public function fromSub($query, $as) + { + [$query, $bindings] = $this->createSub($query); + + return $this->fromRaw('('.$query.') as '.$this->grammar->wrapTable($as), $bindings); + } + + /** + * Add a raw from clause to the query. + * + * @param string $expression + * @param mixed $bindings + * @return $this + */ + public function fromRaw($expression, $bindings = []) + { + $this->from = new Expression($expression); + + $this->addBinding($bindings, 'from'); + + return $this; + } + + /** + * Creates a subquery and parse it. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $query + * @return array + */ + protected function createSub($query) + { + // If the given query is a Closure, we will execute it while passing in a new + // query instance to the Closure. This will give the developer a chance to + // format and work with the query before we cast it to a raw SQL string. + if ($query instanceof Closure) { + $callback = $query; + + $callback($query = $this->forSubQuery()); + } + + return $this->parseSub($query); + } + + /** + * Parse the subquery into SQL and bindings. + * + * @param mixed $query + * @return array + * + * @throws \InvalidArgumentException + */ + protected function parseSub($query) + { + if ($query instanceof self || $query instanceof EloquentBuilder || $query instanceof Relation) { + $query = $this->prependDatabaseNameIfCrossDatabaseQuery($query); + + return [$query->toSql(), $query->getBindings()]; + } elseif (is_string($query)) { + return [$query, []]; + } else { + throw new InvalidArgumentException( + 'A subquery must be a query builder instance, a Closure, or a string.' + ); + } + } + + /** + * Prepend the database name if the given query is on another database. + * + * @param mixed $query + * @return mixed + */ + protected function prependDatabaseNameIfCrossDatabaseQuery($query) + { + if ($query->getConnection()->getDatabaseName() !== + $this->getConnection()->getDatabaseName()) { + $databaseName = $query->getConnection()->getDatabaseName(); + + if (strpos($query->from, $databaseName) !== 0 && strpos($query->from, '.') === false) { + $query->from($databaseName.'.'.$query->from); + } + } + + return $query; + } + + /** + * Add a new select column to the query. + * + * @param array|mixed $column + * @return $this + */ + public function addSelect($column) + { + $columns = is_array($column) ? $column : func_get_args(); + + foreach ($columns as $as => $column) { + if (is_string($as) && $this->isQueryable($column)) { + if (is_null($this->columns)) { + $this->select($this->from.'.*'); + } + + $this->selectSub($column, $as); + } else { + $this->columns[] = $column; + } + } + + return $this; + } + + /** + * Force the query to only return distinct results. + * + * @param mixed ...$distinct + * @return $this + */ + public function distinct() + { + $columns = func_get_args(); + + if (count($columns) > 0) { + $this->distinct = is_array($columns[0]) || is_bool($columns[0]) ? $columns[0] : $columns; + } else { + $this->distinct = true; + } + + return $this; + } + + /** + * Set the table which the query is targeting. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $table + * @param string|null $as + * @return $this + */ + public function from($table, $as = null) + { + if ($this->isQueryable($table)) { + return $this->fromSub($table, $as); + } + + $this->from = $as ? "{$table} as {$as}" : $table; + + return $this; + } + + /** + * Add a join clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @param string $type + * @param bool $where + * @return $this + */ + public function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false) + { + $join = $this->newJoinClause($this, $type, $table); + + // If the first "column" of the join is really a Closure instance the developer + // is trying to build a join with a complex "on" clause containing more than + // one condition, so we'll add the join and call a Closure with the query. + if ($first instanceof Closure) { + $first($join); + + $this->joins[] = $join; + + $this->addBinding($join->getBindings(), 'join'); + } + + // If the column is simply a string, we can assume the join simply has a basic + // "on" clause with a single condition. So we will just build the join with + // this simple join clauses attached to it. There is not a join callback. + else { + $method = $where ? 'where' : 'on'; + + $this->joins[] = $join->$method($first, $operator, $second); + + $this->addBinding($join->getBindings(), 'join'); + } + + return $this; + } + + /** + * Add a "join where" clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string $operator + * @param string $second + * @param string $type + * @return $this + */ + public function joinWhere($table, $first, $operator, $second, $type = 'inner') + { + return $this->join($table, $first, $operator, $second, $type, true); + } + + /** + * Add a subquery join clause to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @param string $type + * @param bool $where + * @return $this + * + * @throws \InvalidArgumentException + */ + public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) + { + [$query, $bindings] = $this->createSub($query); + + $expression = '('.$query.') as '.$this->grammar->wrapTable($as); + + $this->addBinding($bindings, 'join'); + + return $this->join(new Expression($expression), $first, $operator, $second, $type, $where); + } + + /** + * Add a left join to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return $this + */ + public function leftJoin($table, $first, $operator = null, $second = null) + { + return $this->join($table, $first, $operator, $second, 'left'); + } + + /** + * Add a "join where" clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string $operator + * @param string $second + * @return $this + */ + public function leftJoinWhere($table, $first, $operator, $second) + { + return $this->joinWhere($table, $first, $operator, $second, 'left'); + } + + /** + * Add a subquery left join to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return $this + */ + public function leftJoinSub($query, $as, $first, $operator = null, $second = null) + { + return $this->joinSub($query, $as, $first, $operator, $second, 'left'); + } + + /** + * Add a right join to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return $this + */ + public function rightJoin($table, $first, $operator = null, $second = null) + { + return $this->join($table, $first, $operator, $second, 'right'); + } + + /** + * Add a "right join where" clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string $operator + * @param string $second + * @return $this + */ + public function rightJoinWhere($table, $first, $operator, $second) + { + return $this->joinWhere($table, $first, $operator, $second, 'right'); + } + + /** + * Add a subquery right join to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return $this + */ + public function rightJoinSub($query, $as, $first, $operator = null, $second = null) + { + return $this->joinSub($query, $as, $first, $operator, $second, 'right'); + } + + /** + * Add a "cross join" clause to the query. + * + * @param string $table + * @param \Closure|string|null $first + * @param string|null $operator + * @param string|null $second + * @return $this + */ + public function crossJoin($table, $first = null, $operator = null, $second = null) + { + if ($first) { + return $this->join($table, $first, $operator, $second, 'cross'); + } + + $this->joins[] = $this->newJoinClause($this, 'cross', $table); + + return $this; + } + + /** + * Add a subquery cross join to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $query + * @param string $as + * @return $this + */ + public function crossJoinSub($query, $as) + { + [$query, $bindings] = $this->createSub($query); + + $expression = '('.$query.') as '.$this->grammar->wrapTable($as); + + $this->addBinding($bindings, 'join'); + + $this->joins[] = $this->newJoinClause($this, 'cross', new Expression($expression)); + + return $this; + } + + /** + * Get a new join clause. + * + * @param \Illuminate\Database\Query\Builder $parentQuery + * @param string $type + * @param string $table + * @return \Illuminate\Database\Query\JoinClause + */ + protected function newJoinClause(self $parentQuery, $type, $table) + { + return new JoinClause($parentQuery, $type, $table); + } + + /** + * Merge an array of where clauses and bindings. + * + * @param array $wheres + * @param array $bindings + * @return void + */ + public function mergeWheres($wheres, $bindings) + { + $this->wheres = array_merge($this->wheres, (array) $wheres); + + $this->bindings['where'] = array_values( + array_merge($this->bindings['where'], (array) $bindings) + ); + } + + /** + * Add a basic where clause to the query. + * + * @param \Closure|string|array $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return $this + */ + public function where($column, $operator = null, $value = null, $boolean = 'and') + { + // If the column is an array, we will assume it is an array of key-value pairs + // and can add them each as a where clause. We will maintain the boolean we + // received when the method was called and pass it into the nested where. + if (is_array($column)) { + return $this->addArrayOfWheres($column, $boolean); + } + + // Here we will make some assumptions about the operator. If only 2 values are + // passed to the method, we will assume that the operator is an equals sign + // and keep going. Otherwise, we'll require the operator to be passed in. + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + // If the columns is actually a Closure instance, we will assume the developer + // wants to begin a nested where statement which is wrapped in parenthesis. + // We'll add that Closure to the query then return back out immediately. + if ($column instanceof Closure && is_null($operator)) { + return $this->whereNested($column, $boolean); + } + + // If the column is a Closure instance and there is an operator value, we will + // assume the developer wants to run a subquery and then compare the result + // of that subquery with the given value that was provided to the method. + if ($this->isQueryable($column) && ! is_null($operator)) { + [$sub, $bindings] = $this->createSub($column); + + return $this->addBinding($bindings, 'where') + ->where(new Expression('('.$sub.')'), $operator, $value, $boolean); + } + + // If the given operator is not found in the list of valid operators we will + // assume that the developer is just short-cutting the '=' operators and + // we will set the operators to '=' and set the values appropriately. + if ($this->invalidOperator($operator)) { + [$value, $operator] = [$operator, '=']; + } + + // If the value is a Closure, it means the developer is performing an entire + // sub-select within the query and we will need to compile the sub-select + // within the where clause to get the appropriate query record results. + if ($value instanceof Closure) { + return $this->whereSub($column, $operator, $value, $boolean); + } + + // If the value is "null", we will just assume the developer wants to add a + // where null clause to the query. So, we will allow a short-cut here to + // that method for convenience so the developer doesn't have to check. + if (is_null($value)) { + return $this->whereNull($column, $boolean, $operator !== '='); + } + + $type = 'Basic'; + + // If the column is making a JSON reference we'll check to see if the value + // is a boolean. If it is, we'll add the raw boolean string as an actual + // value to the query to ensure this is properly handled by the query. + if (Str::contains($column, '->') && is_bool($value)) { + $value = new Expression($value ? 'true' : 'false'); + + if (is_string($column)) { + $type = 'JsonBoolean'; + } + } + + if ($this->isBitwiseOperator($operator)) { + $type = 'Bitwise'; + } + + // Now that we are working with just a simple query we can put the elements + // in our array and add the query binding to our array of bindings that + // will be bound to each SQL statements when it is finally executed. + $this->wheres[] = compact( + 'type', 'column', 'operator', 'value', 'boolean' + ); + + if (! $value instanceof Expression) { + $this->addBinding($this->flattenValue($value), 'where'); + } + + return $this; + } + + /** + * Add an array of where clauses to the query. + * + * @param array $column + * @param string $boolean + * @param string $method + * @return $this + */ + protected function addArrayOfWheres($column, $boolean, $method = 'where') + { + return $this->whereNested(function ($query) use ($column, $method, $boolean) { + foreach ($column as $key => $value) { + if (is_numeric($key) && is_array($value)) { + $query->{$method}(...array_values($value)); + } else { + $query->$method($key, '=', $value, $boolean); + } + } + }, $boolean); + } + + /** + * Prepare the value and operator for a where clause. + * + * @param string $value + * @param string $operator + * @param bool $useDefault + * @return array + * + * @throws \InvalidArgumentException + */ + public function prepareValueAndOperator($value, $operator, $useDefault = false) + { + if ($useDefault) { + return [$operator, '=']; + } elseif ($this->invalidOperatorAndValue($operator, $value)) { + throw new InvalidArgumentException('Illegal operator and value combination.'); + } + + return [$value, $operator]; + } + + /** + * Determine if the given operator and value combination is legal. + * + * Prevents using Null values with invalid operators. + * + * @param string $operator + * @param mixed $value + * @return bool + */ + protected function invalidOperatorAndValue($operator, $value) + { + return is_null($value) && in_array($operator, $this->operators) && + ! in_array($operator, ['=', '<>', '!=']); + } + + /** + * Determine if the given operator is supported. + * + * @param string $operator + * @return bool + */ + protected function invalidOperator($operator) + { + return ! is_string($operator) || (! in_array(strtolower($operator), $this->operators, true) && + ! in_array(strtolower($operator), $this->grammar->getOperators(), true)); + } + + /** + * Determine if the operator is a bitwise operator. + * + * @param string $operator + * @return bool + */ + protected function isBitwiseOperator($operator) + { + return in_array(strtolower($operator), $this->bitwiseOperators, true) || + in_array(strtolower($operator), $this->grammar->getBitwiseOperators(), true); + } + + /** + * Add an "or where" clause to the query. + * + * @param \Closure|string|array $column + * @param mixed $operator + * @param mixed $value + * @return $this + */ + public function orWhere($column, $operator = null, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->where($column, $operator, $value, 'or'); + } + + /** + * Add a "where" clause comparing two columns to the query. + * + * @param string|array $first + * @param string|null $operator + * @param string|null $second + * @param string|null $boolean + * @return $this + */ + public function whereColumn($first, $operator = null, $second = null, $boolean = 'and') + { + // If the column is an array, we will assume it is an array of key-value pairs + // and can add them each as a where clause. We will maintain the boolean we + // received when the method was called and pass it into the nested where. + if (is_array($first)) { + return $this->addArrayOfWheres($first, $boolean, 'whereColumn'); + } + + // If the given operator is not found in the list of valid operators we will + // assume that the developer is just short-cutting the '=' operators and + // we will set the operators to '=' and set the values appropriately. + if ($this->invalidOperator($operator)) { + [$second, $operator] = [$operator, '=']; + } + + // Finally, we will add this where clause into this array of clauses that we + // are building for the query. All of them will be compiled via a grammar + // once the query is about to be executed and run against the database. + $type = 'Column'; + + $this->wheres[] = compact( + 'type', 'first', 'operator', 'second', 'boolean' + ); + + return $this; + } + + /** + * Add an "or where" clause comparing two columns to the query. + * + * @param string|array $first + * @param string|null $operator + * @param string|null $second + * @return $this + */ + public function orWhereColumn($first, $operator = null, $second = null) + { + return $this->whereColumn($first, $operator, $second, 'or'); + } + + /** + * Add a raw where clause to the query. + * + * @param string $sql + * @param mixed $bindings + * @param string $boolean + * @return $this + */ + public function whereRaw($sql, $bindings = [], $boolean = 'and') + { + $this->wheres[] = ['type' => 'raw', 'sql' => $sql, 'boolean' => $boolean]; + + $this->addBinding((array) $bindings, 'where'); + + return $this; + } + + /** + * Add a raw or where clause to the query. + * + * @param string $sql + * @param mixed $bindings + * @return $this + */ + public function orWhereRaw($sql, $bindings = []) + { + return $this->whereRaw($sql, $bindings, 'or'); + } + + /** + * Add a "where in" clause to the query. + * + * @param string $column + * @param mixed $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereIn($column, $values, $boolean = 'and', $not = false) + { + $type = $not ? 'NotIn' : 'In'; + + // If the value is a query builder instance we will assume the developer wants to + // look for any values that exists within this given query. So we will add the + // query accordingly so that this query is properly executed when it is run. + if ($this->isQueryable($values)) { + [$query, $bindings] = $this->createSub($values); + + $values = [new Expression($query)]; + + $this->addBinding($bindings, 'where'); + } + + // Next, if the value is Arrayable we need to cast it to its raw array form so we + // have the underlying array value instead of an Arrayable object which is not + // able to be added as a binding, etc. We will then add to the wheres array. + if ($values instanceof Arrayable) { + $values = $values->toArray(); + } + + $this->wheres[] = compact('type', 'column', 'values', 'boolean'); + + // Finally we'll add a binding for each values unless that value is an expression + // in which case we will just skip over it since it will be the query as a raw + // string and not as a parameterized place-holder to be replaced by the PDO. + $this->addBinding($this->cleanBindings($values), 'where'); + + return $this; + } + + /** + * Add an "or where in" clause to the query. + * + * @param string $column + * @param mixed $values + * @return $this + */ + public function orWhereIn($column, $values) + { + return $this->whereIn($column, $values, 'or'); + } + + /** + * Add a "where not in" clause to the query. + * + * @param string $column + * @param mixed $values + * @param string $boolean + * @return $this + */ + public function whereNotIn($column, $values, $boolean = 'and') + { + return $this->whereIn($column, $values, $boolean, true); + } + + /** + * Add an "or where not in" clause to the query. + * + * @param string $column + * @param mixed $values + * @return $this + */ + public function orWhereNotIn($column, $values) + { + return $this->whereNotIn($column, $values, 'or'); + } + + /** + * Add a "where in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = false) + { + $type = $not ? 'NotInRaw' : 'InRaw'; + + if ($values instanceof Arrayable) { + $values = $values->toArray(); + } + + foreach ($values as &$value) { + $value = (int) $value; + } + + $this->wheres[] = compact('type', 'column', 'values', 'boolean'); + + return $this; + } + + /** + * Add an "or where in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @return $this + */ + public function orWhereIntegerInRaw($column, $values) + { + return $this->whereIntegerInRaw($column, $values, 'or'); + } + + /** + * Add a "where not in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @param string $boolean + * @return $this + */ + public function whereIntegerNotInRaw($column, $values, $boolean = 'and') + { + return $this->whereIntegerInRaw($column, $values, $boolean, true); + } + + /** + * Add an "or where not in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @return $this + */ + public function orWhereIntegerNotInRaw($column, $values) + { + return $this->whereIntegerNotInRaw($column, $values, 'or'); + } + + /** + * Add a "where null" clause to the query. + * + * @param string|array $columns + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereNull($columns, $boolean = 'and', $not = false) + { + $type = $not ? 'NotNull' : 'Null'; + + foreach (Arr::wrap($columns) as $column) { + $this->wheres[] = compact('type', 'column', 'boolean'); + } + + return $this; + } + + /** + * Add an "or where null" clause to the query. + * + * @param string|array $column + * @return $this + */ + public function orWhereNull($column) + { + return $this->whereNull($column, 'or'); + } + + /** + * Add a "where not null" clause to the query. + * + * @param string|array $columns + * @param string $boolean + * @return $this + */ + public function whereNotNull($columns, $boolean = 'and') + { + return $this->whereNull($columns, $boolean, true); + } + + /** + * Add a where between statement to the query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @param array $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereBetween($column, array $values, $boolean = 'and', $not = false) + { + $type = 'between'; + + $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not'); + + $this->addBinding(array_slice($this->cleanBindings(Arr::flatten($values)), 0, 2), 'where'); + + return $this; + } + + /** + * Add a where between statement using columns to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereBetweenColumns($column, array $values, $boolean = 'and', $not = false) + { + $type = 'betweenColumns'; + + $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not'); + + return $this; + } + + /** + * Add an or where between statement to the query. + * + * @param string $column + * @param array $values + * @return $this + */ + public function orWhereBetween($column, array $values) + { + return $this->whereBetween($column, $values, 'or'); + } + + /** + * Add an or where between statement using columns to the query. + * + * @param string $column + * @param array $values + * @return $this + */ + public function orWhereBetweenColumns($column, array $values) + { + return $this->whereBetweenColumns($column, $values, 'or'); + } + + /** + * Add a where not between statement to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @return $this + */ + public function whereNotBetween($column, array $values, $boolean = 'and') + { + return $this->whereBetween($column, $values, $boolean, true); + } + + /** + * Add a where not between statement using columns to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @return $this + */ + public function whereNotBetweenColumns($column, array $values, $boolean = 'and') + { + return $this->whereBetweenColumns($column, $values, $boolean, true); + } + + /** + * Add an or where not between statement to the query. + * + * @param string $column + * @param array $values + * @return $this + */ + public function orWhereNotBetween($column, array $values) + { + return $this->whereNotBetween($column, $values, 'or'); + } + + /** + * Add an or where not between statement using columns to the query. + * + * @param string $column + * @param array $values + * @return $this + */ + public function orWhereNotBetweenColumns($column, array $values) + { + return $this->whereNotBetweenColumns($column, $values, 'or'); + } + + /** + * Add an "or where not null" clause to the query. + * + * @param string $column + * @return $this + */ + public function orWhereNotNull($column) + { + return $this->whereNotNull($column, 'or'); + } + + /** + * Add a "where date" statement to the query. + * + * @param \Illuminate\Database\Query\Expression|string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @param string $boolean + * @return $this + */ + public function whereDate($column, $operator, $value = null, $boolean = 'and') + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + $value = $this->flattenValue($value); + + if ($value instanceof DateTimeInterface) { + $value = $value->format('Y-m-d'); + } + + return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean); + } + + /** + * Add an "or where date" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @return $this + */ + public function orWhereDate($column, $operator, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->whereDate($column, $operator, $value, 'or'); + } + + /** + * Add a "where time" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @param string $boolean + * @return $this + */ + public function whereTime($column, $operator, $value = null, $boolean = 'and') + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + $value = $this->flattenValue($value); + + if ($value instanceof DateTimeInterface) { + $value = $value->format('H:i:s'); + } + + return $this->addDateBasedWhere('Time', $column, $operator, $value, $boolean); + } + + /** + * Add an "or where time" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @return $this + */ + public function orWhereTime($column, $operator, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->whereTime($column, $operator, $value, 'or'); + } + + /** + * Add a "where day" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @param string $boolean + * @return $this + */ + public function whereDay($column, $operator, $value = null, $boolean = 'and') + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + $value = $this->flattenValue($value); + + if ($value instanceof DateTimeInterface) { + $value = $value->format('d'); + } + + if (! $value instanceof Expression) { + $value = str_pad($value, 2, '0', STR_PAD_LEFT); + } + + return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean); + } + + /** + * Add an "or where day" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @return $this + */ + public function orWhereDay($column, $operator, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->whereDay($column, $operator, $value, 'or'); + } + + /** + * Add a "where month" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @param string $boolean + * @return $this + */ + public function whereMonth($column, $operator, $value = null, $boolean = 'and') + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + $value = $this->flattenValue($value); + + if ($value instanceof DateTimeInterface) { + $value = $value->format('m'); + } + + if (! $value instanceof Expression) { + $value = str_pad($value, 2, '0', STR_PAD_LEFT); + } + + return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean); + } + + /** + * Add an "or where month" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @return $this + */ + public function orWhereMonth($column, $operator, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->whereMonth($column, $operator, $value, 'or'); + } + + /** + * Add a "where year" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @param string $boolean + * @return $this + */ + public function whereYear($column, $operator, $value = null, $boolean = 'and') + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + $value = $this->flattenValue($value); + + if ($value instanceof DateTimeInterface) { + $value = $value->format('Y'); + } + + return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean); + } + + /** + * Add an "or where year" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @return $this + */ + public function orWhereYear($column, $operator, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->whereYear($column, $operator, $value, 'or'); + } + + /** + * Add a date based (year, month, day, time) statement to the query. + * + * @param string $type + * @param string $column + * @param string $operator + * @param mixed $value + * @param string $boolean + * @return $this + */ + protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and') + { + $this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value'); + + if (! $value instanceof Expression) { + $this->addBinding($value, 'where'); + } + + return $this; + } + + /** + * Add a nested where statement to the query. + * + * @param \Closure $callback + * @param string $boolean + * @return $this + */ + public function whereNested(Closure $callback, $boolean = 'and') + { + call_user_func($callback, $query = $this->forNestedWhere()); + + return $this->addNestedWhereQuery($query, $boolean); + } + + /** + * Create a new query instance for nested where condition. + * + * @return \Illuminate\Database\Query\Builder + */ + public function forNestedWhere() + { + return $this->newQuery()->from($this->from); + } + + /** + * Add another query builder as a nested where to the query builder. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $boolean + * @return $this + */ + public function addNestedWhereQuery($query, $boolean = 'and') + { + if (count($query->wheres)) { + $type = 'Nested'; + + $this->wheres[] = compact('type', 'query', 'boolean'); + + $this->addBinding($query->getRawBindings()['where'], 'where'); + } + + return $this; + } + + /** + * Add a full sub-select to the query. + * + * @param string $column + * @param string $operator + * @param \Closure $callback + * @param string $boolean + * @return $this + */ + protected function whereSub($column, $operator, Closure $callback, $boolean) + { + $type = 'Sub'; + + // Once we have the query instance we can simply execute it so it can add all + // of the sub-select's conditions to itself, and then we can cache it off + // in the array of where clauses for the "main" parent query instance. + call_user_func($callback, $query = $this->forSubQuery()); + + $this->wheres[] = compact( + 'type', 'column', 'operator', 'query', 'boolean' + ); + + $this->addBinding($query->getBindings(), 'where'); + + return $this; + } + + /** + * Add an exists clause to the query. + * + * @param \Closure $callback + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereExists(Closure $callback, $boolean = 'and', $not = false) + { + $query = $this->forSubQuery(); + + // Similar to the sub-select clause, we will create a new query instance so + // the developer may cleanly specify the entire exists query and we will + // compile the whole thing in the grammar and insert it into the SQL. + call_user_func($callback, $query); + + return $this->addWhereExistsQuery($query, $boolean, $not); + } + + /** + * Add an or exists clause to the query. + * + * @param \Closure $callback + * @param bool $not + * @return $this + */ + public function orWhereExists(Closure $callback, $not = false) + { + return $this->whereExists($callback, 'or', $not); + } + + /** + * Add a where not exists clause to the query. + * + * @param \Closure $callback + * @param string $boolean + * @return $this + */ + public function whereNotExists(Closure $callback, $boolean = 'and') + { + return $this->whereExists($callback, $boolean, true); + } + + /** + * Add a where not exists clause to the query. + * + * @param \Closure $callback + * @return $this + */ + public function orWhereNotExists(Closure $callback) + { + return $this->orWhereExists($callback, true); + } + + /** + * Add an exists clause to the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $boolean + * @param bool $not + * @return $this + */ + public function addWhereExistsQuery(self $query, $boolean = 'and', $not = false) + { + $type = $not ? 'NotExists' : 'Exists'; + + $this->wheres[] = compact('type', 'query', 'boolean'); + + $this->addBinding($query->getBindings(), 'where'); + + return $this; + } + + /** + * Adds a where condition using row values. + * + * @param array $columns + * @param string $operator + * @param array $values + * @param string $boolean + * @return $this + * + * @throws \InvalidArgumentException + */ + public function whereRowValues($columns, $operator, $values, $boolean = 'and') + { + if (count($columns) !== count($values)) { + throw new InvalidArgumentException('The number of columns must match the number of values'); + } + + $type = 'RowValues'; + + $this->wheres[] = compact('type', 'columns', 'operator', 'values', 'boolean'); + + $this->addBinding($this->cleanBindings($values)); + + return $this; + } + + /** + * Adds an or where condition using row values. + * + * @param array $columns + * @param string $operator + * @param array $values + * @return $this + */ + public function orWhereRowValues($columns, $operator, $values) + { + return $this->whereRowValues($columns, $operator, $values, 'or'); + } + + /** + * Add a "where JSON contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @param string $boolean + * @param bool $not + * @return $this + */ + public function whereJsonContains($column, $value, $boolean = 'and', $not = false) + { + $type = 'JsonContains'; + + $this->wheres[] = compact('type', 'column', 'value', 'boolean', 'not'); + + if (! $value instanceof Expression) { + $this->addBinding($this->grammar->prepareBindingForJsonContains($value)); + } + + return $this; + } + + /** + * Add an "or where JSON contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @return $this + */ + public function orWhereJsonContains($column, $value) + { + return $this->whereJsonContains($column, $value, 'or'); + } + + /** + * Add a "where JSON not contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @param string $boolean + * @return $this + */ + public function whereJsonDoesntContain($column, $value, $boolean = 'and') + { + return $this->whereJsonContains($column, $value, $boolean, true); + } + + /** + * Add an "or where JSON not contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @return $this + */ + public function orWhereJsonDoesntContain($column, $value) + { + return $this->whereJsonDoesntContain($column, $value, 'or'); + } + + /** + * Add a "where JSON length" clause to the query. + * + * @param string $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return $this + */ + public function whereJsonLength($column, $operator, $value = null, $boolean = 'and') + { + $type = 'JsonLength'; + + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + $this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean'); + + if (! $value instanceof Expression) { + $this->addBinding((int) $this->flattenValue($value)); + } + + return $this; + } + + /** + * Add an "or where JSON length" clause to the query. + * + * @param string $column + * @param mixed $operator + * @param mixed $value + * @return $this + */ + public function orWhereJsonLength($column, $operator, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->whereJsonLength($column, $operator, $value, 'or'); + } + + /** + * Handles dynamic "where" clauses to the query. + * + * @param string $method + * @param array $parameters + * @return $this + */ + public function dynamicWhere($method, $parameters) + { + $finder = substr($method, 5); + + $segments = preg_split( + '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE + ); + + // The connector variable will determine which connector will be used for the + // query condition. We will change it as we come across new boolean values + // in the dynamic method strings, which could contain a number of these. + $connector = 'and'; + + $index = 0; + + foreach ($segments as $segment) { + // If the segment is not a boolean connector, we can assume it is a column's name + // and we will add it to the query as a new constraint as a where clause, then + // we can keep iterating through the dynamic method string's segments again. + if ($segment !== 'And' && $segment !== 'Or') { + $this->addDynamic($segment, $connector, $parameters, $index); + + $index++; + } + + // Otherwise, we will store the connector so we know how the next where clause we + // find in the query should be connected to the previous ones, meaning we will + // have the proper boolean connector to connect the next where clause found. + else { + $connector = $segment; + } + } + + return $this; + } + + /** + * Add a single dynamic where clause statement to the query. + * + * @param string $segment + * @param string $connector + * @param array $parameters + * @param int $index + * @return void + */ + protected function addDynamic($segment, $connector, $parameters, $index) + { + // Once we have parsed out the columns and formatted the boolean operators we + // are ready to add it to this query as a where clause just like any other + // clause on the query. Then we'll increment the parameter index values. + $bool = strtolower($connector); + + $this->where(Str::snake($segment), '=', $parameters[$index], $bool); + } + + /** + * Add a "where fulltext" clause to the query. + * + * @param string|string[] $columns + * @param string $value + * @param string $boolean + * @return $this + */ + public function whereFullText($columns, $value, array $options = [], $boolean = 'and') + { + $type = 'Fulltext'; + + $columns = (array) $columns; + + $this->wheres[] = compact('type', 'columns', 'value', 'options', 'boolean'); + + $this->addBinding($value); + + return $this; + } + + /** + * Add a "or where fulltext" clause to the query. + * + * @param string|string[] $columns + * @param string $value + * @return $this + */ + public function orWhereFullText($columns, $value, array $options = []) + { + return $this->whereFulltext($columns, $value, $options, 'or'); + } + + /** + * Add a "group by" clause to the query. + * + * @param array|string ...$groups + * @return $this + */ + public function groupBy(...$groups) + { + foreach ($groups as $group) { + $this->groups = array_merge( + (array) $this->groups, + Arr::wrap($group) + ); + } + + return $this; + } + + /** + * Add a raw groupBy clause to the query. + * + * @param string $sql + * @param array $bindings + * @return $this + */ + public function groupByRaw($sql, array $bindings = []) + { + $this->groups[] = new Expression($sql); + + $this->addBinding($bindings, 'groupBy'); + + return $this; + } + + /** + * Add a "having" clause to the query. + * + * @param string $column + * @param string|null $operator + * @param string|null $value + * @param string $boolean + * @return $this + */ + public function having($column, $operator = null, $value = null, $boolean = 'and') + { + $type = 'Basic'; + + // Here we will make some assumptions about the operator. If only 2 values are + // passed to the method, we will assume that the operator is an equals sign + // and keep going. Otherwise, we'll require the operator to be passed in. + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + // If the given operator is not found in the list of valid operators we will + // assume that the developer is just short-cutting the '=' operators and + // we will set the operators to '=' and set the values appropriately. + if ($this->invalidOperator($operator)) { + [$value, $operator] = [$operator, '=']; + } + + if ($this->isBitwiseOperator($operator)) { + $type = 'Bitwise'; + } + + $this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean'); + + if (! $value instanceof Expression) { + $this->addBinding($this->flattenValue($value), 'having'); + } + + return $this; + } + + /** + * Add an "or having" clause to the query. + * + * @param string $column + * @param string|null $operator + * @param string|null $value + * @return $this + */ + public function orHaving($column, $operator = null, $value = null) + { + [$value, $operator] = $this->prepareValueAndOperator( + $value, $operator, func_num_args() === 2 + ); + + return $this->having($column, $operator, $value, 'or'); + } + + /** + * Add a "having between " clause to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not + * @return $this + */ + public function havingBetween($column, array $values, $boolean = 'and', $not = false) + { + $type = 'between'; + + $this->havings[] = compact('type', 'column', 'values', 'boolean', 'not'); + + $this->addBinding(array_slice($this->cleanBindings(Arr::flatten($values)), 0, 2), 'having'); + + return $this; + } + + /** + * Add a raw having clause to the query. + * + * @param string $sql + * @param array $bindings + * @param string $boolean + * @return $this + */ + public function havingRaw($sql, array $bindings = [], $boolean = 'and') + { + $type = 'Raw'; + + $this->havings[] = compact('type', 'sql', 'boolean'); + + $this->addBinding($bindings, 'having'); + + return $this; + } + + /** + * Add a raw or having clause to the query. + * + * @param string $sql + * @param array $bindings + * @return $this + */ + public function orHavingRaw($sql, array $bindings = []) + { + return $this->havingRaw($sql, $bindings, 'or'); + } + + /** + * Add an "order by" clause to the query. + * + * @param \Closure|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Database\Query\Expression|string $column + * @param string $direction + * @return $this + * + * @throws \InvalidArgumentException + */ + public function orderBy($column, $direction = 'asc') + { + if ($this->isQueryable($column)) { + [$query, $bindings] = $this->createSub($column); + + $column = new Expression('('.$query.')'); + + $this->addBinding($bindings, $this->unions ? 'unionOrder' : 'order'); + } + + $direction = strtolower($direction); + + if (! in_array($direction, ['asc', 'desc'], true)) { + throw new InvalidArgumentException('Order direction must be "asc" or "desc".'); + } + + $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [ + 'column' => $column, + 'direction' => $direction, + ]; + + return $this; + } + + /** + * Add a descending "order by" clause to the query. + * + * @param \Closure|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Database\Query\Expression|string $column + * @return $this + */ + public function orderByDesc($column) + { + return $this->orderBy($column, 'desc'); + } + + /** + * Add an "order by" clause for a timestamp to the query. + * + * @param \Closure|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Database\Query\Expression|string $column + * @return $this + */ + public function latest($column = 'created_at') + { + return $this->orderBy($column, 'desc'); + } + + /** + * Add an "order by" clause for a timestamp to the query. + * + * @param \Closure|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Database\Query\Expression|string $column + * @return $this + */ + public function oldest($column = 'created_at') + { + return $this->orderBy($column, 'asc'); + } + + /** + * Put the query's results in random order. + * + * @param string $seed + * @return $this + */ + public function inRandomOrder($seed = '') + { + return $this->orderByRaw($this->grammar->compileRandom($seed)); + } + + /** + * Add a raw "order by" clause to the query. + * + * @param string $sql + * @param array $bindings + * @return $this + */ + public function orderByRaw($sql, $bindings = []) + { + $type = 'Raw'; + + $this->{$this->unions ? 'unionOrders' : 'orders'}[] = compact('type', 'sql'); + + $this->addBinding($bindings, $this->unions ? 'unionOrder' : 'order'); + + return $this; + } + + /** + * Alias to set the "offset" value of the query. + * + * @param int $value + * @return $this + */ + public function skip($value) + { + return $this->offset($value); + } + + /** + * Set the "offset" value of the query. + * + * @param int $value + * @return $this + */ + public function offset($value) + { + $property = $this->unions ? 'unionOffset' : 'offset'; + + $this->$property = max(0, (int) $value); + + return $this; + } + + /** + * Alias to set the "limit" value of the query. + * + * @param int $value + * @return $this + */ + public function take($value) + { + return $this->limit($value); + } + + /** + * Set the "limit" value of the query. + * + * @param int $value + * @return $this + */ + public function limit($value) + { + $property = $this->unions ? 'unionLimit' : 'limit'; + + if ($value >= 0) { + $this->$property = ! is_null($value) ? (int) $value : null; + } + + return $this; + } + + /** + * Set the limit and offset for a given page. + * + * @param int $page + * @param int $perPage + * @return $this + */ + public function forPage($page, $perPage = 15) + { + return $this->offset(($page - 1) * $perPage)->limit($perPage); + } + + /** + * Constrain the query to the previous "page" of results before a given ID. + * + * @param int $perPage + * @param int|null $lastId + * @param string $column + * @return $this + */ + public function forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id') + { + $this->orders = $this->removeExistingOrdersFor($column); + + if (! is_null($lastId)) { + $this->where($column, '<', $lastId); + } + + return $this->orderBy($column, 'desc') + ->limit($perPage); + } + + /** + * Constrain the query to the next "page" of results after a given ID. + * + * @param int $perPage + * @param int|null $lastId + * @param string $column + * @return $this + */ + public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') + { + $this->orders = $this->removeExistingOrdersFor($column); + + if (! is_null($lastId)) { + $this->where($column, '>', $lastId); + } + + return $this->orderBy($column, 'asc') + ->limit($perPage); + } + + /** + * Remove all existing orders and optionally add a new order. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Query\Expression|string|null $column + * @param string $direction + * @return $this + */ + public function reorder($column = null, $direction = 'asc') + { + $this->orders = null; + $this->unionOrders = null; + $this->bindings['order'] = []; + $this->bindings['unionOrder'] = []; + + if ($column) { + return $this->orderBy($column, $direction); + } + + return $this; + } + + /** + * Get an array with all orders with a given column removed. + * + * @param string $column + * @return array + */ + protected function removeExistingOrdersFor($column) + { + return Collection::make($this->orders) + ->reject(function ($order) use ($column) { + return isset($order['column']) + ? $order['column'] === $column : false; + })->values()->all(); + } + + /** + * Add a union statement to the query. + * + * @param \Illuminate\Database\Query\Builder|\Closure $query + * @param bool $all + * @return $this + */ + public function union($query, $all = false) + { + if ($query instanceof Closure) { + call_user_func($query, $query = $this->newQuery()); + } + + $this->unions[] = compact('query', 'all'); + + $this->addBinding($query->getBindings(), 'union'); + + return $this; + } + + /** + * Add a union all statement to the query. + * + * @param \Illuminate\Database\Query\Builder|\Closure $query + * @return $this + */ + public function unionAll($query) + { + return $this->union($query, true); + } + + /** + * Lock the selected rows in the table. + * + * @param string|bool $value + * @return $this + */ + public function lock($value = true) + { + $this->lock = $value; + + if (! is_null($this->lock)) { + $this->useWritePdo(); + } + + return $this; + } + + /** + * Lock the selected rows in the table for updating. + * + * @return \Illuminate\Database\Query\Builder + */ + public function lockForUpdate() + { + return $this->lock(true); + } + + /** + * Share lock the selected rows in the table. + * + * @return \Illuminate\Database\Query\Builder + */ + public function sharedLock() + { + return $this->lock(false); + } + + /** + * Register a closure to be invoked before the query is executed. + * + * @param callable $callback + * @return $this + */ + public function beforeQuery(callable $callback) + { + $this->beforeQueryCallbacks[] = $callback; + + return $this; + } + + /** + * Invoke the "before query" modification callbacks. + * + * @return void + */ + public function applyBeforeQueryCallbacks() + { + foreach ($this->beforeQueryCallbacks as $callback) { + $callback($this); + } + + $this->beforeQueryCallbacks = []; + } + + /** + * Get the SQL representation of the query. + * + * @return string + */ + public function toSql() + { + $this->applyBeforeQueryCallbacks(); + + return $this->grammar->compileSelect($this); + } + + /** + * Execute a query for a single record by ID. + * + * @param int|string $id + * @param array $columns + * @return mixed|static + */ + public function find($id, $columns = ['*']) + { + return $this->where('id', '=', $id)->first($columns); + } + + /** + * Get a single column's value from the first result of a query. + * + * @param string $column + * @return mixed + */ + public function value($column) + { + $result = (array) $this->first([$column]); + + return count($result) > 0 ? reset($result) : null; + } + + /** + * Execute the query as a "select" statement. + * + * @param array|string $columns + * @return \Illuminate\Support\Collection + */ + public function get($columns = ['*']) + { + return collect($this->onceWithColumns(Arr::wrap($columns), function () { + return $this->processor->processSelect($this, $this->runSelect()); + })); + } + + /** + * Run the query as a "select" statement against the connection. + * + * @return array + */ + protected function runSelect() + { + return $this->connection->select( + $this->toSql(), $this->getBindings(), ! $this->useWritePdo + ); + } + + /** + * Paginate the given query into a simple paginator. + * + * @param int $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + */ + public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null) + { + $page = $page ?: Paginator::resolveCurrentPage($pageName); + + $total = $this->getCountForPagination(); + + $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect(); + + return $this->paginator($results, $total, $perPage, $page, [ + 'path' => Paginator::resolveCurrentPath(), + 'pageName' => $pageName, + ]); + } + + /** + * Get a paginator only supporting simple next and previous links. + * + * This is more efficient on larger data-sets, etc. + * + * @param int $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\Paginator + */ + public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null) + { + $page = $page ?: Paginator::resolveCurrentPage($pageName); + + $this->offset(($page - 1) * $perPage)->limit($perPage + 1); + + return $this->simplePaginator($this->get($columns), $perPage, $page, [ + 'path' => Paginator::resolveCurrentPath(), + 'pageName' => $pageName, + ]); + } + + /** + * Get a paginator only supporting simple next and previous links. + * + * This is more efficient on larger data-sets, etc. + * + * @param int|null $perPage + * @param array $columns + * @param string $cursorName + * @param \Illuminate\Pagination\Cursor|string|null $cursor + * @return \Illuminate\Contracts\Pagination\CursorPaginator + */ + public function cursorPaginate($perPage = 15, $columns = ['*'], $cursorName = 'cursor', $cursor = null) + { + return $this->paginateUsingCursor($perPage, $columns, $cursorName, $cursor); + } + + /** + * Ensure the proper order by required for cursor pagination. + * + * @param bool $shouldReverse + * @return \Illuminate\Support\Collection + */ + protected function ensureOrderForCursorPagination($shouldReverse = false) + { + $this->enforceOrderBy(); + + return collect($this->orders ?? $this->unionOrders ?? [])->filter(function ($order) { + return Arr::has($order, 'direction'); + })->when($shouldReverse, function (Collection $orders) { + return $orders->map(function ($order) { + $order['direction'] = $order['direction'] === 'asc' ? 'desc' : 'asc'; + + return $order; + }); + })->values(); + } + + /** + * Get the count of the total records for the paginator. + * + * @param array $columns + * @return int + */ + public function getCountForPagination($columns = ['*']) + { + $results = $this->runPaginationCountQuery($columns); + + // Once we have run the pagination count query, we will get the resulting count and + // take into account what type of query it was. When there is a group by we will + // just return the count of the entire results set since that will be correct. + if (! isset($results[0])) { + return 0; + } elseif (is_object($results[0])) { + return (int) $results[0]->aggregate; + } + + return (int) array_change_key_case((array) $results[0])['aggregate']; + } + + /** + * Run a pagination count query. + * + * @param array $columns + * @return array + */ + protected function runPaginationCountQuery($columns = ['*']) + { + if ($this->groups || $this->havings) { + $clone = $this->cloneForPaginationCount(); + + if (is_null($clone->columns) && ! empty($this->joins)) { + $clone->select($this->from.'.*'); + } + + return $this->newQuery() + ->from(new Expression('('.$clone->toSql().') as '.$this->grammar->wrap('aggregate_table'))) + ->mergeBindings($clone) + ->setAggregate('count', $this->withoutSelectAliases($columns)) + ->get()->all(); + } + + $without = $this->unions ? ['orders', 'limit', 'offset'] : ['columns', 'orders', 'limit', 'offset']; + + return $this->cloneWithout($without) + ->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order']) + ->setAggregate('count', $this->withoutSelectAliases($columns)) + ->get()->all(); + } + + /** + * Clone the existing query instance for usage in a pagination subquery. + * + * @return self + */ + protected function cloneForPaginationCount() + { + return $this->cloneWithout(['orders', 'limit', 'offset']) + ->cloneWithoutBindings(['order']); + } + + /** + * Remove the column aliases since they will break count queries. + * + * @param array $columns + * @return array + */ + protected function withoutSelectAliases(array $columns) + { + return array_map(function ($column) { + return is_string($column) && ($aliasPosition = stripos($column, ' as ')) !== false + ? substr($column, 0, $aliasPosition) : $column; + }, $columns); + } + + /** + * Get a lazy collection for the given query. + * + * @return \Illuminate\Support\LazyCollection + */ + public function cursor() + { + if (is_null($this->columns)) { + $this->columns = ['*']; + } + + return new LazyCollection(function () { + yield from $this->connection->cursor( + $this->toSql(), $this->getBindings(), ! $this->useWritePdo + ); + }); + } + + /** + * Throw an exception if the query doesn't have an orderBy clause. + * + * @return void + * + * @throws \RuntimeException + */ + protected function enforceOrderBy() + { + if (empty($this->orders) && empty($this->unionOrders)) { + throw new RuntimeException('You must specify an orderBy clause when using this function.'); + } + } + + /** + * Get a collection instance containing the values of a given column. + * + * @param string $column + * @param string|null $key + * @return \Illuminate\Support\Collection + */ + public function pluck($column, $key = null) + { + // First, we will need to select the results of the query accounting for the + // given columns / key. Once we have the results, we will be able to take + // the results and get the exact data that was requested for the query. + $queryResult = $this->onceWithColumns( + is_null($key) ? [$column] : [$column, $key], + function () { + return $this->processor->processSelect( + $this, $this->runSelect() + ); + } + ); + + if (empty($queryResult)) { + return collect(); + } + + // If the columns are qualified with a table or have an alias, we cannot use + // those directly in the "pluck" operations since the results from the DB + // are only keyed by the column itself. We'll strip the table out here. + $column = $this->stripTableForPluck($column); + + $key = $this->stripTableForPluck($key); + + return is_array($queryResult[0]) + ? $this->pluckFromArrayColumn($queryResult, $column, $key) + : $this->pluckFromObjectColumn($queryResult, $column, $key); + } + + /** + * Strip off the table name or alias from a column identifier. + * + * @param string $column + * @return string|null + */ + protected function stripTableForPluck($column) + { + if (is_null($column)) { + return $column; + } + + $separator = strpos(strtolower($column), ' as ') !== false ? ' as ' : '\.'; + + return last(preg_split('~'.$separator.'~i', $column)); + } + + /** + * Retrieve column values from rows represented as objects. + * + * @param array $queryResult + * @param string $column + * @param string $key + * @return \Illuminate\Support\Collection + */ + protected function pluckFromObjectColumn($queryResult, $column, $key) + { + $results = []; + + if (is_null($key)) { + foreach ($queryResult as $row) { + $results[] = $row->$column; + } + } else { + foreach ($queryResult as $row) { + $results[$row->$key] = $row->$column; + } + } + + return collect($results); + } + + /** + * Retrieve column values from rows represented as arrays. + * + * @param array $queryResult + * @param string $column + * @param string $key + * @return \Illuminate\Support\Collection + */ + protected function pluckFromArrayColumn($queryResult, $column, $key) + { + $results = []; + + if (is_null($key)) { + foreach ($queryResult as $row) { + $results[] = $row[$column]; + } + } else { + foreach ($queryResult as $row) { + $results[$row[$key]] = $row[$column]; + } + } + + return collect($results); + } + + /** + * Concatenate values of a given column as a string. + * + * @param string $column + * @param string $glue + * @return string + */ + public function implode($column, $glue = '') + { + return $this->pluck($column)->implode($glue); + } + + /** + * Determine if any rows exist for the current query. + * + * @return bool + */ + public function exists() + { + $this->applyBeforeQueryCallbacks(); + + $results = $this->connection->select( + $this->grammar->compileExists($this), $this->getBindings(), ! $this->useWritePdo + ); + + // If the results has rows, we will get the row and see if the exists column is a + // boolean true. If there is no results for this query we will return false as + // there are no rows for this query at all and we can return that info here. + if (isset($results[0])) { + $results = (array) $results[0]; + + return (bool) $results['exists']; + } + + return false; + } + + /** + * Determine if no rows exist for the current query. + * + * @return bool + */ + public function doesntExist() + { + return ! $this->exists(); + } + + /** + * Execute the given callback if no rows exist for the current query. + * + * @param \Closure $callback + * @return mixed + */ + public function existsOr(Closure $callback) + { + return $this->exists() ? true : $callback(); + } + + /** + * Execute the given callback if rows exist for the current query. + * + * @param \Closure $callback + * @return mixed + */ + public function doesntExistOr(Closure $callback) + { + return $this->doesntExist() ? true : $callback(); + } + + /** + * Retrieve the "count" result of the query. + * + * @param string $columns + * @return int + */ + public function count($columns = '*') + { + return (int) $this->aggregate(__FUNCTION__, Arr::wrap($columns)); + } + + /** + * Retrieve the minimum value of a given column. + * + * @param string $column + * @return mixed + */ + public function min($column) + { + return $this->aggregate(__FUNCTION__, [$column]); + } + + /** + * Retrieve the maximum value of a given column. + * + * @param string $column + * @return mixed + */ + public function max($column) + { + return $this->aggregate(__FUNCTION__, [$column]); + } + + /** + * Retrieve the sum of the values of a given column. + * + * @param string $column + * @return mixed + */ + public function sum($column) + { + $result = $this->aggregate(__FUNCTION__, [$column]); + + return $result ?: 0; + } + + /** + * Retrieve the average of the values of a given column. + * + * @param string $column + * @return mixed + */ + public function avg($column) + { + return $this->aggregate(__FUNCTION__, [$column]); + } + + /** + * Alias for the "avg" method. + * + * @param string $column + * @return mixed + */ + public function average($column) + { + return $this->avg($column); + } + + /** + * Execute an aggregate function on the database. + * + * @param string $function + * @param array $columns + * @return mixed + */ + public function aggregate($function, $columns = ['*']) + { + $results = $this->cloneWithout($this->unions || $this->havings ? [] : ['columns']) + ->cloneWithoutBindings($this->unions || $this->havings ? [] : ['select']) + ->setAggregate($function, $columns) + ->get($columns); + + if (! $results->isEmpty()) { + return array_change_key_case((array) $results[0])['aggregate']; + } + } + + /** + * Execute a numeric aggregate function on the database. + * + * @param string $function + * @param array $columns + * @return float|int + */ + public function numericAggregate($function, $columns = ['*']) + { + $result = $this->aggregate($function, $columns); + + // If there is no result, we can obviously just return 0 here. Next, we will check + // if the result is an integer or float. If it is already one of these two data + // types we can just return the result as-is, otherwise we will convert this. + if (! $result) { + return 0; + } + + if (is_int($result) || is_float($result)) { + return $result; + } + + // If the result doesn't contain a decimal place, we will assume it is an int then + // cast it to one. When it does we will cast it to a float since it needs to be + // cast to the expected data type for the developers out of pure convenience. + return strpos((string) $result, '.') === false + ? (int) $result : (float) $result; + } + + /** + * Set the aggregate property without running the query. + * + * @param string $function + * @param array $columns + * @return $this + */ + protected function setAggregate($function, $columns) + { + $this->aggregate = compact('function', 'columns'); + + if (empty($this->groups)) { + $this->orders = null; + + $this->bindings['order'] = []; + } + + return $this; + } + + /** + * Execute the given callback while selecting the given columns. + * + * After running the callback, the columns are reset to the original value. + * + * @param array $columns + * @param callable $callback + * @return mixed + */ + protected function onceWithColumns($columns, $callback) + { + $original = $this->columns; + + if (is_null($original)) { + $this->columns = $columns; + } + + $result = $callback(); + + $this->columns = $original; + + return $result; + } + + /** + * Insert new records into the database. + * + * @param array $values + * @return bool + */ + public function insert(array $values) + { + // Since every insert gets treated like a batch insert, we will make sure the + // bindings are structured in a way that is convenient when building these + // inserts statements by verifying these elements are actually an array. + if (empty($values)) { + return true; + } + + if (! is_array(reset($values))) { + $values = [$values]; + } + + // Here, we will sort the insert keys for every record so that each insert is + // in the same order for the record. We need to make sure this is the case + // so there are not any errors or problems when inserting these records. + else { + foreach ($values as $key => $value) { + ksort($value); + + $values[$key] = $value; + } + } + + $this->applyBeforeQueryCallbacks(); + + // Finally, we will run this query against the database connection and return + // the results. We will need to also flatten these bindings before running + // the query so they are all in one huge, flattened array for execution. + return $this->connection->insert( + $this->grammar->compileInsert($this, $values), + $this->cleanBindings(Arr::flatten($values, 1)) + ); + } + + /** + * Insert new records into the database while ignoring errors. + * + * @param array $values + * @return int + */ + public function insertOrIgnore(array $values) + { + if (empty($values)) { + return 0; + } + + if (! is_array(reset($values))) { + $values = [$values]; + } else { + foreach ($values as $key => $value) { + ksort($value); + $values[$key] = $value; + } + } + + $this->applyBeforeQueryCallbacks(); + + return $this->connection->affectingStatement( + $this->grammar->compileInsertOrIgnore($this, $values), + $this->cleanBindings(Arr::flatten($values, 1)) + ); + } + + /** + * Insert a new record and get the value of the primary key. + * + * @param array $values + * @param string|null $sequence + * @return int + */ + public function insertGetId(array $values, $sequence = null) + { + $this->applyBeforeQueryCallbacks(); + + $sql = $this->grammar->compileInsertGetId($this, $values, $sequence); + + $values = $this->cleanBindings($values); + + return $this->processor->processInsertGetId($this, $sql, $values, $sequence); + } + + /** + * Insert new records into the table using a subquery. + * + * @param array $columns + * @param \Closure|\Illuminate\Database\Query\Builder|string $query + * @return int + */ + public function insertUsing(array $columns, $query) + { + $this->applyBeforeQueryCallbacks(); + + [$sql, $bindings] = $this->createSub($query); + + return $this->connection->affectingStatement( + $this->grammar->compileInsertUsing($this, $columns, $sql), + $this->cleanBindings($bindings) + ); + } + + /** + * Update records in the database. + * + * @param array $values + * @return int + */ + public function update(array $values) + { + $this->applyBeforeQueryCallbacks(); + + $sql = $this->grammar->compileUpdate($this, $values); + + return $this->connection->update($sql, $this->cleanBindings( + $this->grammar->prepareBindingsForUpdate($this->bindings, $values) + )); + } + + /** + * Update records in a PostgreSQL database using the update from syntax. + * + * @param array $values + * @return int + */ + public function updateFrom(array $values) + { + if (! method_exists($this->grammar, 'compileUpdateFrom')) { + throw new LogicException('This database engine does not support the updateFrom method.'); + } + + $this->applyBeforeQueryCallbacks(); + + $sql = $this->grammar->compileUpdateFrom($this, $values); + + return $this->connection->update($sql, $this->cleanBindings( + $this->grammar->prepareBindingsForUpdateFrom($this->bindings, $values) + )); + } + + /** + * Insert or update a record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @return bool + */ + public function updateOrInsert(array $attributes, array $values = []) + { + if (! $this->where($attributes)->exists()) { + return $this->insert(array_merge($attributes, $values)); + } + + if (empty($values)) { + return true; + } + + return (bool) $this->limit(1)->update($values); + } + + /** + * Insert new records or update the existing ones. + * + * @param array $values + * @param array|string $uniqueBy + * @param array|null $update + * @return int + */ + public function upsert(array $values, $uniqueBy, $update = null) + { + if (empty($values)) { + return 0; + } elseif ($update === []) { + return (int) $this->insert($values); + } + + if (! is_array(reset($values))) { + $values = [$values]; + } else { + foreach ($values as $key => $value) { + ksort($value); + + $values[$key] = $value; + } + } + + if (is_null($update)) { + $update = array_keys(reset($values)); + } + + $this->applyBeforeQueryCallbacks(); + + $bindings = $this->cleanBindings(array_merge( + Arr::flatten($values, 1), + collect($update)->reject(function ($value, $key) { + return is_int($key); + })->all() + )); + + return $this->connection->affectingStatement( + $this->grammar->compileUpsert($this, $values, (array) $uniqueBy, $update), + $bindings + ); + } + + /** + * Increment a column's value by a given amount. + * + * @param string $column + * @param float|int $amount + * @param array $extra + * @return int + * + * @throws \InvalidArgumentException + */ + public function increment($column, $amount = 1, array $extra = []) + { + if (! is_numeric($amount)) { + throw new InvalidArgumentException('Non-numeric value passed to increment method.'); + } + + $wrapped = $this->grammar->wrap($column); + + $columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra); + + return $this->update($columns); + } + + /** + * Decrement a column's value by a given amount. + * + * @param string $column + * @param float|int $amount + * @param array $extra + * @return int + * + * @throws \InvalidArgumentException + */ + public function decrement($column, $amount = 1, array $extra = []) + { + if (! is_numeric($amount)) { + throw new InvalidArgumentException('Non-numeric value passed to decrement method.'); + } + + $wrapped = $this->grammar->wrap($column); + + $columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra); + + return $this->update($columns); + } + + /** + * Delete records from the database. + * + * @param mixed $id + * @return int + */ + public function delete($id = null) + { + // If an ID is passed to the method, we will set the where clause to check the + // ID to let developers to simply and quickly remove a single row from this + // database without manually specifying the "where" clauses on the query. + if (! is_null($id)) { + $this->where($this->from.'.id', '=', $id); + } + + $this->applyBeforeQueryCallbacks(); + + return $this->connection->delete( + $this->grammar->compileDelete($this), $this->cleanBindings( + $this->grammar->prepareBindingsForDelete($this->bindings) + ) + ); + } + + /** + * Run a truncate statement on the table. + * + * @return void + */ + public function truncate() + { + $this->applyBeforeQueryCallbacks(); + + foreach ($this->grammar->compileTruncate($this) as $sql => $bindings) { + $this->connection->statement($sql, $bindings); + } + } + + /** + * Get a new instance of the query builder. + * + * @return \Illuminate\Database\Query\Builder + */ + public function newQuery() + { + return new static($this->connection, $this->grammar, $this->processor); + } + + /** + * Create a new query instance for a sub-query. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function forSubQuery() + { + return $this->newQuery(); + } + + /** + * Create a raw database expression. + * + * @param mixed $value + * @return \Illuminate\Database\Query\Expression + */ + public function raw($value) + { + return $this->connection->raw($value); + } + + /** + * Get the current query value bindings in a flattened array. + * + * @return array + */ + public function getBindings() + { + return Arr::flatten($this->bindings); + } + + /** + * Get the raw array of bindings. + * + * @return array + */ + public function getRawBindings() + { + return $this->bindings; + } + + /** + * Set the bindings on the query builder. + * + * @param array $bindings + * @param string $type + * @return $this + * + * @throws \InvalidArgumentException + */ + public function setBindings(array $bindings, $type = 'where') + { + if (! array_key_exists($type, $this->bindings)) { + throw new InvalidArgumentException("Invalid binding type: {$type}."); + } + + $this->bindings[$type] = $bindings; + + return $this; + } + + /** + * Add a binding to the query. + * + * @param mixed $value + * @param string $type + * @return $this + * + * @throws \InvalidArgumentException + */ + public function addBinding($value, $type = 'where') + { + if (! array_key_exists($type, $this->bindings)) { + throw new InvalidArgumentException("Invalid binding type: {$type}."); + } + + if (is_array($value)) { + $this->bindings[$type] = array_values(array_map( + [$this, 'castBinding'], + array_merge($this->bindings[$type], $value), + )); + } else { + $this->bindings[$type][] = $this->castBinding($value); + } + + return $this; + } + + /** + * Cast the given binding value. + * + * @param mixed $value + * @return mixed + */ + public function castBinding($value) + { + if (function_exists('enum_exists') && $value instanceof BackedEnum) { + return $value->value; + } + + return $value; + } + + /** + * Merge an array of bindings into our bindings. + * + * @param \Illuminate\Database\Query\Builder $query + * @return $this + */ + public function mergeBindings(self $query) + { + $this->bindings = array_merge_recursive($this->bindings, $query->bindings); + + return $this; + } + + /** + * Remove all of the expressions from a list of bindings. + * + * @param array $bindings + * @return array + */ + public function cleanBindings(array $bindings) + { + return collect($bindings) + ->reject(function ($binding) { + return $binding instanceof Expression; + }) + ->map([$this, 'castBinding']) + ->values() + ->all(); + } + + /** + * Get a scalar type value from an unknown type of input. + * + * @param mixed $value + * @return mixed + */ + protected function flattenValue($value) + { + return is_array($value) ? head(Arr::flatten($value)) : $value; + } + + /** + * Get the default key name of the table. + * + * @return string + */ + protected function defaultKeyName() + { + return 'id'; + } + + /** + * Get the database connection instance. + * + * @return \Illuminate\Database\ConnectionInterface + */ + public function getConnection() + { + return $this->connection; + } + + /** + * Get the database query processor instance. + * + * @return \Illuminate\Database\Query\Processors\Processor + */ + public function getProcessor() + { + return $this->processor; + } + + /** + * Get the query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\Grammar + */ + public function getGrammar() + { + return $this->grammar; + } + + /** + * Use the write pdo for query. + * + * @return $this + */ + public function useWritePdo() + { + $this->useWritePdo = true; + + return $this; + } + + /** + * Determine if the value is a query builder instance or a Closure. + * + * @param mixed $value + * @return bool + */ + protected function isQueryable($value) + { + return $value instanceof self || + $value instanceof EloquentBuilder || + $value instanceof Relation || + $value instanceof Closure; + } + + /** + * Clone the query. + * + * @return static + */ + public function clone() + { + return clone $this; + } + + /** + * Clone the query without the given properties. + * + * @param array $properties + * @return static + */ + public function cloneWithout(array $properties) + { + return tap($this->clone(), function ($clone) use ($properties) { + foreach ($properties as $property) { + $clone->{$property} = null; + } + }); + } + + /** + * Clone the query without the given bindings. + * + * @param array $except + * @return static + */ + public function cloneWithoutBindings(array $except) + { + return tap($this->clone(), function ($clone) use ($except) { + foreach ($except as $type) { + $clone->bindings[$type] = []; + } + }); + } + + /** + * Dump the current SQL and bindings. + * + * @return $this + */ + public function dump() + { + dump($this->toSql(), $this->getBindings()); + + return $this; + } + + /** + * Die and dump the current SQL and bindings. + * + * @return never + */ + public function dd() + { + dd($this->toSql(), $this->getBindings()); + } + + /** + * Handle dynamic method calls into the method. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + if (Str::startsWith($method, 'where')) { + return $this->dynamicWhere($method, $parameters); + } + + static::throwBadMethodCallException($method); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Expression.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Expression.php new file mode 100755 index 0000000..de69029 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Expression.php @@ -0,0 +1,44 @@ +value = $value; + } + + /** + * Get the value of the expression. + * + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * Get the value of the expression. + * + * @return string + */ + public function __toString() + { + return (string) $this->getValue(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php new file mode 100755 index 0000000..0dbdb1e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php @@ -0,0 +1,1331 @@ +unions || $query->havings) && $query->aggregate) { + return $this->compileUnionAggregate($query); + } + + // If the query does not have any columns set, we'll set the columns to the + // * character to just get all of the columns from the database. Then we + // can build the query and concatenate all the pieces together as one. + $original = $query->columns; + + if (is_null($query->columns)) { + $query->columns = ['*']; + } + + // To compile the query, we'll spin through each component of the query and + // see if that component exists. If it does we'll just call the compiler + // function for the component which is responsible for making the SQL. + $sql = trim($this->concatenate( + $this->compileComponents($query)) + ); + + if ($query->unions) { + $sql = $this->wrapUnion($sql).' '.$this->compileUnions($query); + } + + $query->columns = $original; + + return $sql; + } + + /** + * Compile the components necessary for a select clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @return array + */ + protected function compileComponents(Builder $query) + { + $sql = []; + + foreach ($this->selectComponents as $component) { + if (isset($query->$component)) { + $method = 'compile'.ucfirst($component); + + $sql[$component] = $this->$method($query, $query->$component); + } + } + + return $sql; + } + + /** + * Compile an aggregated select clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $aggregate + * @return string + */ + protected function compileAggregate(Builder $query, $aggregate) + { + $column = $this->columnize($aggregate['columns']); + + // If the query has a "distinct" constraint and we're not asking for all columns + // we need to prepend "distinct" onto the column name so that the query takes + // it into account when it performs the aggregating operations on the data. + if (is_array($query->distinct)) { + $column = 'distinct '.$this->columnize($query->distinct); + } elseif ($query->distinct && $column !== '*') { + $column = 'distinct '.$column; + } + + return 'select '.$aggregate['function'].'('.$column.') as aggregate'; + } + + /** + * Compile the "select *" portion of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $columns + * @return string|null + */ + protected function compileColumns(Builder $query, $columns) + { + // If the query is actually performing an aggregating select, we will let that + // compiler handle the building of the select clauses, as it will need some + // more syntax that is best handled by that function to keep things neat. + if (! is_null($query->aggregate)) { + return; + } + + if ($query->distinct) { + $select = 'select distinct '; + } else { + $select = 'select '; + } + + return $select.$this->columnize($columns); + } + + /** + * Compile the "from" portion of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @return string + */ + protected function compileFrom(Builder $query, $table) + { + return 'from '.$this->wrapTable($table); + } + + /** + * Compile the "join" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $joins + * @return string + */ + protected function compileJoins(Builder $query, $joins) + { + return collect($joins)->map(function ($join) use ($query) { + $table = $this->wrapTable($join->table); + + $nestedJoins = is_null($join->joins) ? '' : ' '.$this->compileJoins($query, $join->joins); + + $tableAndNestedJoins = is_null($join->joins) ? $table : '('.$table.$nestedJoins.')'; + + return trim("{$join->type} join {$tableAndNestedJoins} {$this->compileWheres($join)}"); + })->implode(' '); + } + + /** + * Compile the "where" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileWheres(Builder $query) + { + // Each type of where clauses has its own compiler function which is responsible + // for actually creating the where clauses SQL. This helps keep the code nice + // and maintainable since each clause has a very small method that it uses. + if (is_null($query->wheres)) { + return ''; + } + + // If we actually have some where clauses, we will strip off the first boolean + // operator, which is added by the query builders for convenience so we can + // avoid checking for the first clauses in each of the compilers methods. + if (count($sql = $this->compileWheresToArray($query)) > 0) { + return $this->concatenateWhereClauses($query, $sql); + } + + return ''; + } + + /** + * Get an array of all the where clauses for the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @return array + */ + protected function compileWheresToArray($query) + { + return collect($query->wheres)->map(function ($where) use ($query) { + return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where); + })->all(); + } + + /** + * Format the where clause statements into one string. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $sql + * @return string + */ + protected function concatenateWhereClauses($query, $sql) + { + $conjunction = $query instanceof JoinClause ? 'on' : 'where'; + + return $conjunction.' '.$this->removeLeadingBoolean(implode(' ', $sql)); + } + + /** + * Compile a raw where clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereRaw(Builder $query, $where) + { + return $where['sql']; + } + + /** + * Compile a basic where clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBasic(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + $operator = str_replace('?', '??', $where['operator']); + + return $this->wrap($where['column']).' '.$operator.' '.$value; + } + + /** + * Compile a bitwise operator where clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBitwise(Builder $query, $where) + { + return $this->whereBasic($query, $where); + } + + /** + * Compile a "where in" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereIn(Builder $query, $where) + { + if (! empty($where['values'])) { + return $this->wrap($where['column']).' in ('.$this->parameterize($where['values']).')'; + } + + return '0 = 1'; + } + + /** + * Compile a "where not in" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNotIn(Builder $query, $where) + { + if (! empty($where['values'])) { + return $this->wrap($where['column']).' not in ('.$this->parameterize($where['values']).')'; + } + + return '1 = 1'; + } + + /** + * Compile a "where not in raw" clause. + * + * For safety, whereIntegerInRaw ensures this method is only used with integer values. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNotInRaw(Builder $query, $where) + { + if (! empty($where['values'])) { + return $this->wrap($where['column']).' not in ('.implode(', ', $where['values']).')'; + } + + return '1 = 1'; + } + + /** + * Compile a "where in raw" clause. + * + * For safety, whereIntegerInRaw ensures this method is only used with integer values. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereInRaw(Builder $query, $where) + { + if (! empty($where['values'])) { + return $this->wrap($where['column']).' in ('.implode(', ', $where['values']).')'; + } + + return '0 = 1'; + } + + /** + * Compile a "where null" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNull(Builder $query, $where) + { + return $this->wrap($where['column']).' is null'; + } + + /** + * Compile a "where not null" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNotNull(Builder $query, $where) + { + return $this->wrap($where['column']).' is not null'; + } + + /** + * Compile a "between" where clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBetween(Builder $query, $where) + { + $between = $where['not'] ? 'not between' : 'between'; + + $min = $this->parameter(reset($where['values'])); + + $max = $this->parameter(end($where['values'])); + + return $this->wrap($where['column']).' '.$between.' '.$min.' and '.$max; + } + + /** + * Compile a "between" where clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBetweenColumns(Builder $query, $where) + { + $between = $where['not'] ? 'not between' : 'between'; + + $min = $this->wrap(reset($where['values'])); + + $max = $this->wrap(end($where['values'])); + + return $this->wrap($where['column']).' '.$between.' '.$min.' and '.$max; + } + + /** + * Compile a "where date" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereDate(Builder $query, $where) + { + return $this->dateBasedWhere('date', $query, $where); + } + + /** + * Compile a "where time" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereTime(Builder $query, $where) + { + return $this->dateBasedWhere('time', $query, $where); + } + + /** + * Compile a "where day" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereDay(Builder $query, $where) + { + return $this->dateBasedWhere('day', $query, $where); + } + + /** + * Compile a "where month" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereMonth(Builder $query, $where) + { + return $this->dateBasedWhere('month', $query, $where); + } + + /** + * Compile a "where year" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereYear(Builder $query, $where) + { + return $this->dateBasedWhere('year', $query, $where); + } + + /** + * Compile a date based where clause. + * + * @param string $type + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function dateBasedWhere($type, Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return $type.'('.$this->wrap($where['column']).') '.$where['operator'].' '.$value; + } + + /** + * Compile a where clause comparing two columns. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereColumn(Builder $query, $where) + { + return $this->wrap($where['first']).' '.$where['operator'].' '.$this->wrap($where['second']); + } + + /** + * Compile a nested where clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNested(Builder $query, $where) + { + // Here we will calculate what portion of the string we need to remove. If this + // is a join clause query, we need to remove the "on" portion of the SQL and + // if it is a normal query we need to take the leading "where" of queries. + $offset = $query instanceof JoinClause ? 3 : 6; + + return '('.substr($this->compileWheres($where['query']), $offset).')'; + } + + /** + * Compile a where condition with a sub-select. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereSub(Builder $query, $where) + { + $select = $this->compileSelect($where['query']); + + return $this->wrap($where['column']).' '.$where['operator']." ($select)"; + } + + /** + * Compile a where exists clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereExists(Builder $query, $where) + { + return 'exists ('.$this->compileSelect($where['query']).')'; + } + + /** + * Compile a where exists clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNotExists(Builder $query, $where) + { + return 'not exists ('.$this->compileSelect($where['query']).')'; + } + + /** + * Compile a where row values condition. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereRowValues(Builder $query, $where) + { + $columns = $this->columnize($where['columns']); + + $values = $this->parameterize($where['values']); + + return '('.$columns.') '.$where['operator'].' ('.$values.')'; + } + + /** + * Compile a "where JSON boolean" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereJsonBoolean(Builder $query, $where) + { + $column = $this->wrapJsonBooleanSelector($where['column']); + + $value = $this->wrapJsonBooleanValue( + $this->parameter($where['value']) + ); + + return $column.' '.$where['operator'].' '.$value; + } + + /** + * Compile a "where JSON contains" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereJsonContains(Builder $query, $where) + { + $not = $where['not'] ? 'not ' : ''; + + return $not.$this->compileJsonContains( + $where['column'], + $this->parameter($where['value']) + ); + } + + /** + * Compile a "JSON contains" statement into SQL. + * + * @param string $column + * @param string $value + * @return string + * + * @throws \RuntimeException + */ + protected function compileJsonContains($column, $value) + { + throw new RuntimeException('This database engine does not support JSON contains operations.'); + } + + /** + * Prepare the binding for a "JSON contains" statement. + * + * @param mixed $binding + * @return string + */ + public function prepareBindingForJsonContains($binding) + { + return json_encode($binding); + } + + /** + * Compile a "where JSON length" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereJsonLength(Builder $query, $where) + { + return $this->compileJsonLength( + $where['column'], + $where['operator'], + $this->parameter($where['value']) + ); + } + + /** + * Compile a "JSON length" statement into SQL. + * + * @param string $column + * @param string $operator + * @param string $value + * @return string + * + * @throws \RuntimeException + */ + protected function compileJsonLength($column, $operator, $value) + { + throw new RuntimeException('This database engine does not support JSON length operations.'); + } + + /** + * Compile a "where fulltext" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + public function whereFullText(Builder $query, $where) + { + throw new RuntimeException('This database engine does not support fulltext search operations.'); + } + + /** + * Compile the "group by" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $groups + * @return string + */ + protected function compileGroups(Builder $query, $groups) + { + return 'group by '.$this->columnize($groups); + } + + /** + * Compile the "having" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $havings + * @return string + */ + protected function compileHavings(Builder $query, $havings) + { + $sql = implode(' ', array_map([$this, 'compileHaving'], $havings)); + + return 'having '.$this->removeLeadingBoolean($sql); + } + + /** + * Compile a single having clause. + * + * @param array $having + * @return string + */ + protected function compileHaving(array $having) + { + // If the having clause is "raw", we can just return the clause straight away + // without doing any more processing on it. Otherwise, we will compile the + // clause into SQL based on the components that make it up from builder. + if ($having['type'] === 'Raw') { + return $having['boolean'].' '.$having['sql']; + } elseif ($having['type'] === 'between') { + return $this->compileHavingBetween($having); + } + + return $this->compileBasicHaving($having); + } + + /** + * Compile a basic having clause. + * + * @param array $having + * @return string + */ + protected function compileBasicHaving($having) + { + $column = $this->wrap($having['column']); + + $parameter = $this->parameter($having['value']); + + return $having['boolean'].' '.$column.' '.$having['operator'].' '.$parameter; + } + + /** + * Compile a "between" having clause. + * + * @param array $having + * @return string + */ + protected function compileHavingBetween($having) + { + $between = $having['not'] ? 'not between' : 'between'; + + $column = $this->wrap($having['column']); + + $min = $this->parameter(head($having['values'])); + + $max = $this->parameter(last($having['values'])); + + return $having['boolean'].' '.$column.' '.$between.' '.$min.' and '.$max; + } + + /** + * Compile the "order by" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $orders + * @return string + */ + protected function compileOrders(Builder $query, $orders) + { + if (! empty($orders)) { + return 'order by '.implode(', ', $this->compileOrdersToArray($query, $orders)); + } + + return ''; + } + + /** + * Compile the query orders to an array. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $orders + * @return array + */ + protected function compileOrdersToArray(Builder $query, $orders) + { + return array_map(function ($order) { + return $order['sql'] ?? $this->wrap($order['column']).' '.$order['direction']; + }, $orders); + } + + /** + * Compile the random statement into SQL. + * + * @param string $seed + * @return string + */ + public function compileRandom($seed) + { + return 'RANDOM()'; + } + + /** + * Compile the "limit" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param int $limit + * @return string + */ + protected function compileLimit(Builder $query, $limit) + { + return 'limit '.(int) $limit; + } + + /** + * Compile the "offset" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param int $offset + * @return string + */ + protected function compileOffset(Builder $query, $offset) + { + return 'offset '.(int) $offset; + } + + /** + * Compile the "union" queries attached to the main query. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileUnions(Builder $query) + { + $sql = ''; + + foreach ($query->unions as $union) { + $sql .= $this->compileUnion($union); + } + + if (! empty($query->unionOrders)) { + $sql .= ' '.$this->compileOrders($query, $query->unionOrders); + } + + if (isset($query->unionLimit)) { + $sql .= ' '.$this->compileLimit($query, $query->unionLimit); + } + + if (isset($query->unionOffset)) { + $sql .= ' '.$this->compileOffset($query, $query->unionOffset); + } + + return ltrim($sql); + } + + /** + * Compile a single union statement. + * + * @param array $union + * @return string + */ + protected function compileUnion(array $union) + { + $conjunction = $union['all'] ? ' union all ' : ' union '; + + return $conjunction.$this->wrapUnion($union['query']->toSql()); + } + + /** + * Wrap a union subquery in parentheses. + * + * @param string $sql + * @return string + */ + protected function wrapUnion($sql) + { + return '('.$sql.')'; + } + + /** + * Compile a union aggregate query into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileUnionAggregate(Builder $query) + { + $sql = $this->compileAggregate($query, $query->aggregate); + + $query->aggregate = null; + + return $sql.' from ('.$this->compileSelect($query).') as '.$this->wrapTable('temp_table'); + } + + /** + * Compile an exists statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileExists(Builder $query) + { + $select = $this->compileSelect($query); + + return "select exists({$select}) as {$this->wrap('exists')}"; + } + + /** + * Compile an insert statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileInsert(Builder $query, array $values) + { + // Essentially we will force every insert to be treated as a batch insert which + // simply makes creating the SQL easier for us since we can utilize the same + // basic routine regardless of an amount of records given to us to insert. + $table = $this->wrapTable($query->from); + + if (empty($values)) { + return "insert into {$table} default values"; + } + + if (! is_array(reset($values))) { + $values = [$values]; + } + + $columns = $this->columnize(array_keys(reset($values))); + + // We need to build a list of parameter place-holders of values that are bound + // to the query. Each insert should have the exact same amount of parameter + // bindings so we will loop through the record and parameterize them all. + $parameters = collect($values)->map(function ($record) { + return '('.$this->parameterize($record).')'; + })->implode(', '); + + return "insert into $table ($columns) values $parameters"; + } + + /** + * Compile an insert ignore statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + * + * @throws \RuntimeException + */ + public function compileInsertOrIgnore(Builder $query, array $values) + { + throw new RuntimeException('This database engine does not support inserting while ignoring errors.'); + } + + /** + * Compile an insert and get ID statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param string $sequence + * @return string + */ + public function compileInsertGetId(Builder $query, $values, $sequence) + { + return $this->compileInsert($query, $values); + } + + /** + * Compile an insert statement using a subquery into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $columns + * @param string $sql + * @return string + */ + public function compileInsertUsing(Builder $query, array $columns, string $sql) + { + return "insert into {$this->wrapTable($query->from)} ({$this->columnize($columns)}) $sql"; + } + + /** + * Compile an update statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileUpdate(Builder $query, array $values) + { + $table = $this->wrapTable($query->from); + + $columns = $this->compileUpdateColumns($query, $values); + + $where = $this->compileWheres($query); + + return trim( + isset($query->joins) + ? $this->compileUpdateWithJoins($query, $table, $columns, $where) + : $this->compileUpdateWithoutJoins($query, $table, $columns, $where) + ); + } + + /** + * Compile the columns for an update statement. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + protected function compileUpdateColumns(Builder $query, array $values) + { + return collect($values)->map(function ($value, $key) { + return $this->wrap($key).' = '.$this->parameter($value); + })->implode(', '); + } + + /** + * Compile an update statement without joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $columns + * @param string $where + * @return string + */ + protected function compileUpdateWithoutJoins(Builder $query, $table, $columns, $where) + { + return "update {$table} set {$columns} {$where}"; + } + + /** + * Compile an update statement with joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $columns + * @param string $where + * @return string + */ + protected function compileUpdateWithJoins(Builder $query, $table, $columns, $where) + { + $joins = $this->compileJoins($query, $query->joins); + + return "update {$table} {$joins} set {$columns} {$where}"; + } + + /** + * Compile an "upsert" statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param array $uniqueBy + * @param array $update + * @return string + * + * @throws \RuntimeException + */ + public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update) + { + throw new RuntimeException('This database engine does not support upserts.'); + } + + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + $cleanBindings = Arr::except($bindings, ['select', 'join']); + + return array_values( + array_merge($bindings['join'], $values, Arr::flatten($cleanBindings)) + ); + } + + /** + * Compile a delete statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileDelete(Builder $query) + { + $table = $this->wrapTable($query->from); + + $where = $this->compileWheres($query); + + return trim( + isset($query->joins) + ? $this->compileDeleteWithJoins($query, $table, $where) + : $this->compileDeleteWithoutJoins($query, $table, $where) + ); + } + + /** + * Compile a delete statement without joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $where + * @return string + */ + protected function compileDeleteWithoutJoins(Builder $query, $table, $where) + { + return "delete from {$table} {$where}"; + } + + /** + * Compile a delete statement with joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $where + * @return string + */ + protected function compileDeleteWithJoins(Builder $query, $table, $where) + { + $alias = last(explode(' as ', $table)); + + $joins = $this->compileJoins($query, $query->joins); + + return "delete {$alias} from {$table} {$joins} {$where}"; + } + + /** + * Prepare the bindings for a delete statement. + * + * @param array $bindings + * @return array + */ + public function prepareBindingsForDelete(array $bindings) + { + return Arr::flatten( + Arr::except($bindings, 'select') + ); + } + + /** + * Compile a truncate table statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return array + */ + public function compileTruncate(Builder $query) + { + return ['truncate table '.$this->wrapTable($query->from) => []]; + } + + /** + * Compile the lock into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param bool|string $value + * @return string + */ + protected function compileLock(Builder $query, $value) + { + return is_string($value) ? $value : ''; + } + + /** + * Determine if the grammar supports savepoints. + * + * @return bool + */ + public function supportsSavepoints() + { + return true; + } + + /** + * Compile the SQL statement to define a savepoint. + * + * @param string $name + * @return string + */ + public function compileSavepoint($name) + { + return 'SAVEPOINT '.$name; + } + + /** + * Compile the SQL statement to execute a savepoint rollback. + * + * @param string $name + * @return string + */ + public function compileSavepointRollBack($name) + { + return 'ROLLBACK TO SAVEPOINT '.$name; + } + + /** + * Wrap a value in keyword identifiers. + * + * @param \Illuminate\Database\Query\Expression|string $value + * @param bool $prefixAlias + * @return string + */ + public function wrap($value, $prefixAlias = false) + { + if ($this->isExpression($value)) { + return $this->getValue($value); + } + + // If the value being wrapped has a column alias we will need to separate out + // the pieces so we can wrap each of the segments of the expression on its + // own, and then join these both back together using the "as" connector. + if (stripos($value, ' as ') !== false) { + return $this->wrapAliasedValue($value, $prefixAlias); + } + + // If the given value is a JSON selector we will wrap it differently than a + // traditional value. We will need to split this path and wrap each part + // wrapped, etc. Otherwise, we will simply wrap the value as a string. + if ($this->isJsonSelector($value)) { + return $this->wrapJsonSelector($value); + } + + return $this->wrapSegments(explode('.', $value)); + } + + /** + * Wrap the given JSON selector. + * + * @param string $value + * @return string + * + * @throws \RuntimeException + */ + protected function wrapJsonSelector($value) + { + throw new RuntimeException('This database engine does not support JSON operations.'); + } + + /** + * Wrap the given JSON selector for boolean values. + * + * @param string $value + * @return string + */ + protected function wrapJsonBooleanSelector($value) + { + return $this->wrapJsonSelector($value); + } + + /** + * Wrap the given JSON boolean value. + * + * @param string $value + * @return string + */ + protected function wrapJsonBooleanValue($value) + { + return $value; + } + + /** + * Split the given JSON selector into the field and the optional path and wrap them separately. + * + * @param string $column + * @return array + */ + protected function wrapJsonFieldAndPath($column) + { + $parts = explode('->', $column, 2); + + $field = $this->wrap($parts[0]); + + $path = count($parts) > 1 ? ', '.$this->wrapJsonPath($parts[1], '->') : ''; + + return [$field, $path]; + } + + /** + * Wrap the given JSON path. + * + * @param string $value + * @param string $delimiter + * @return string + */ + protected function wrapJsonPath($value, $delimiter = '->') + { + $value = preg_replace("/([\\\\]+)?\\'/", "''", $value); + + return '\'$."'.str_replace($delimiter, '"."', $value).'"\''; + } + + /** + * Determine if the given string is a JSON selector. + * + * @param string $value + * @return bool + */ + protected function isJsonSelector($value) + { + return Str::contains($value, '->'); + } + + /** + * Concatenate an array of segments, removing empties. + * + * @param array $segments + * @return string + */ + protected function concatenate($segments) + { + return implode(' ', array_filter($segments, function ($value) { + return (string) $value !== ''; + })); + } + + /** + * Remove the leading boolean from a statement. + * + * @param string $value + * @return string + */ + protected function removeLeadingBoolean($value) + { + return preg_replace('/and |or /i', '', $value, 1); + } + + /** + * Get the grammar specific operators. + * + * @return array + */ + public function getOperators() + { + return $this->operators; + } + + /** + * Get the grammar specific bitwise operators. + * + * @return array + */ + public function getBitwiseOperators() + { + return $this->bitwiseOperators; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php new file mode 100755 index 0000000..404b3d5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php @@ -0,0 +1,329 @@ +isJsonSelector($where['column'])) { + [$field, $path] = $this->wrapJsonFieldAndPath($where['column']); + + return '(json_extract('.$field.$path.') is null OR json_type(json_extract('.$field.$path.')) = \'NULL\')'; + } + + return parent::whereNull($query, $where); + } + + /** + * Add a "where not null" clause to the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereNotNull(Builder $query, $where) + { + if ($this->isJsonSelector($where['column'])) { + [$field, $path] = $this->wrapJsonFieldAndPath($where['column']); + + return '(json_extract('.$field.$path.') is not null AND json_type(json_extract('.$field.$path.')) != \'NULL\')'; + } + + return parent::whereNotNull($query, $where); + } + + /** + * Compile a "where fulltext" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + public function whereFullText(Builder $query, $where) + { + $columns = $this->columnize($where['columns']); + + $value = $this->parameter($where['value']); + + $mode = ($where['options']['mode'] ?? []) === 'boolean' + ? ' in boolean mode' + : ' in natural language mode'; + + $expanded = ($where['options']['expanded'] ?? []) && ($where['options']['mode'] ?? []) !== 'boolean' + ? ' with query expansion' + : ''; + + return "match ({$columns}) against (".$value."{$mode}{$expanded})"; + } + + /** + * Compile an insert ignore statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileInsertOrIgnore(Builder $query, array $values) + { + return Str::replaceFirst('insert', 'insert ignore', $this->compileInsert($query, $values)); + } + + /** + * Compile a "JSON contains" statement into SQL. + * + * @param string $column + * @param string $value + * @return string + */ + protected function compileJsonContains($column, $value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($column); + + return 'json_contains('.$field.', '.$value.$path.')'; + } + + /** + * Compile a "JSON length" statement into SQL. + * + * @param string $column + * @param string $operator + * @param string $value + * @return string + */ + protected function compileJsonLength($column, $operator, $value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($column); + + return 'json_length('.$field.$path.') '.$operator.' '.$value; + } + + /** + * Compile the random statement into SQL. + * + * @param string $seed + * @return string + */ + public function compileRandom($seed) + { + return 'RAND('.$seed.')'; + } + + /** + * Compile the lock into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param bool|string $value + * @return string + */ + protected function compileLock(Builder $query, $value) + { + if (! is_string($value)) { + return $value ? 'for update' : 'lock in share mode'; + } + + return $value; + } + + /** + * Compile an insert statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileInsert(Builder $query, array $values) + { + if (empty($values)) { + $values = [[]]; + } + + return parent::compileInsert($query, $values); + } + + /** + * Compile the columns for an update statement. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + protected function compileUpdateColumns(Builder $query, array $values) + { + return collect($values)->map(function ($value, $key) { + if ($this->isJsonSelector($key)) { + return $this->compileJsonUpdateColumn($key, $value); + } + + return $this->wrap($key).' = '.$this->parameter($value); + })->implode(', '); + } + + /** + * Compile an "upsert" statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param array $uniqueBy + * @param array $update + * @return string + */ + public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update) + { + $sql = $this->compileInsert($query, $values).' on duplicate key update '; + + $columns = collect($update)->map(function ($value, $key) { + return is_numeric($key) + ? $this->wrap($value).' = values('.$this->wrap($value).')' + : $this->wrap($key).' = '.$this->parameter($value); + })->implode(', '); + + return $sql.$columns; + } + + /** + * Prepare a JSON column being updated using the JSON_SET function. + * + * @param string $key + * @param mixed $value + * @return string + */ + protected function compileJsonUpdateColumn($key, $value) + { + if (is_bool($value)) { + $value = $value ? 'true' : 'false'; + } elseif (is_array($value)) { + $value = 'cast(? as json)'; + } else { + $value = $this->parameter($value); + } + + [$field, $path] = $this->wrapJsonFieldAndPath($key); + + return "{$field} = json_set({$field}{$path}, {$value})"; + } + + /** + * Compile an update statement without joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $columns + * @param string $where + * @return string + */ + protected function compileUpdateWithoutJoins(Builder $query, $table, $columns, $where) + { + $sql = parent::compileUpdateWithoutJoins($query, $table, $columns, $where); + + if (! empty($query->orders)) { + $sql .= ' '.$this->compileOrders($query, $query->orders); + } + + if (isset($query->limit)) { + $sql .= ' '.$this->compileLimit($query, $query->limit); + } + + return $sql; + } + + /** + * Prepare the bindings for an update statement. + * + * Booleans, integers, and doubles are inserted into JSON updates as raw values. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + $values = collect($values)->reject(function ($value, $column) { + return $this->isJsonSelector($column) && is_bool($value); + })->map(function ($value) { + return is_array($value) ? json_encode($value) : $value; + })->all(); + + return parent::prepareBindingsForUpdate($bindings, $values); + } + + /** + * Compile a delete query that does not use joins. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $where + * @return string + */ + protected function compileDeleteWithoutJoins(Builder $query, $table, $where) + { + $sql = parent::compileDeleteWithoutJoins($query, $table, $where); + + // When using MySQL, delete statements may contain order by statements and limits + // so we will compile both of those here. Once we have finished compiling this + // we will return the completed SQL statement so it will be executed for us. + if (! empty($query->orders)) { + $sql .= ' '.$this->compileOrders($query, $query->orders); + } + + if (isset($query->limit)) { + $sql .= ' '.$this->compileLimit($query, $query->limit); + } + + return $sql; + } + + /** + * Wrap a single string in keyword identifiers. + * + * @param string $value + * @return string + */ + protected function wrapValue($value) + { + return $value === '*' ? $value : '`'.str_replace('`', '``', $value).'`'; + } + + /** + * Wrap the given JSON selector. + * + * @param string $value + * @return string + */ + protected function wrapJsonSelector($value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($value); + + return 'json_unquote(json_extract('.$field.$path.'))'; + } + + /** + * Wrap the given JSON selector for boolean values. + * + * @param string $value + * @return string + */ + protected function wrapJsonBooleanSelector($value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($value); + + return 'json_extract('.$field.$path.')'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/PostgresGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/PostgresGrammar.php new file mode 100755 index 0000000..1b49bf1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/PostgresGrammar.php @@ -0,0 +1,640 @@ +', '<=', '>=', '<>', '!=', + 'like', 'not like', 'between', 'ilike', 'not ilike', + '~', '&', '|', '#', '<<', '>>', '<<=', '>>=', + '&&', '@>', '<@', '?', '?|', '?&', '||', '-', '@?', '@@', '#-', + 'is distinct from', 'is not distinct from', + ]; + + /** + * The grammar specific bitwise operators. + * + * @var array + */ + protected $bitwiseOperators = [ + '~', '&', '|', '#', '<<', '>>', '<<=', '>>=', + ]; + + /** + * {@inheritdoc} + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBasic(Builder $query, $where) + { + if (Str::contains(strtolower($where['operator']), 'like')) { + return sprintf( + '%s::text %s %s', + $this->wrap($where['column']), + $where['operator'], + $this->parameter($where['value']) + ); + } + + return parent::whereBasic($query, $where); + } + + /** + * {@inheritdoc} + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBitwise(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + $operator = str_replace('?', '??', $where['operator']); + + return '('.$this->wrap($where['column']).' '.$operator.' '.$value.')::bool'; + } + + /** + * Compile a "where date" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereDate(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return $this->wrap($where['column']).'::date '.$where['operator'].' '.$value; + } + + /** + * Compile a "where time" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereTime(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return $this->wrap($where['column']).'::time '.$where['operator'].' '.$value; + } + + /** + * Compile a date based where clause. + * + * @param string $type + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function dateBasedWhere($type, Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return 'extract('.$type.' from '.$this->wrap($where['column']).') '.$where['operator'].' '.$value; + } + + /** + * Compile a "where fulltext" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + public function whereFullText(Builder $query, $where) + { + $language = $where['options']['language'] ?? 'english'; + + if (! in_array($language, $this->validFullTextLanguages())) { + $language = 'english'; + } + + $columns = collect($where['columns'])->map(function ($column) use ($language) { + return "to_tsvector('{$language}', {$this->wrap($column)})"; + })->implode(' || '); + + $mode = 'plainto_tsquery'; + + if (($where['options']['mode'] ?? []) === 'phrase') { + $mode = 'phraseto_tsquery'; + } + + if (($where['options']['mode'] ?? []) === 'websearch') { + $mode = 'websearch_to_tsquery'; + } + + return "({$columns}) @@ {$mode}('{$language}', {$this->parameter($where['value'])})"; + } + + /** + * Get an array of valid full text languages. + * + * @return array + */ + protected function validFullTextLanguages() + { + return [ + 'simple', + 'arabic', + 'danish', + 'dutch', + 'english', + 'finnish', + 'french', + 'german', + 'hungarian', + 'indonesian', + 'irish', + 'italian', + 'lithuanian', + 'nepali', + 'norwegian', + 'portuguese', + 'romanian', + 'russian', + 'spanish', + 'swedish', + 'tamil', + 'turkish', + ]; + } + + /** + * Compile the "select *" portion of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $columns + * @return string|null + */ + protected function compileColumns(Builder $query, $columns) + { + // If the query is actually performing an aggregating select, we will let that + // compiler handle the building of the select clauses, as it will need some + // more syntax that is best handled by that function to keep things neat. + if (! is_null($query->aggregate)) { + return; + } + + if (is_array($query->distinct)) { + $select = 'select distinct on ('.$this->columnize($query->distinct).') '; + } elseif ($query->distinct) { + $select = 'select distinct '; + } else { + $select = 'select '; + } + + return $select.$this->columnize($columns); + } + + /** + * Compile a "JSON contains" statement into SQL. + * + * @param string $column + * @param string $value + * @return string + */ + protected function compileJsonContains($column, $value) + { + $column = str_replace('->>', '->', $this->wrap($column)); + + return '('.$column.')::jsonb @> '.$value; + } + + /** + * Compile a "JSON length" statement into SQL. + * + * @param string $column + * @param string $operator + * @param string $value + * @return string + */ + protected function compileJsonLength($column, $operator, $value) + { + $column = str_replace('->>', '->', $this->wrap($column)); + + return 'json_array_length(('.$column.')::json) '.$operator.' '.$value; + } + + /** + * {@inheritdoc} + * + * @param array $having + * @return string + */ + protected function compileHaving(array $having) + { + if ($having['type'] === 'Bitwise') { + return $this->compileHavingBitwise($having); + } + + return parent::compileHaving($having); + } + + /** + * Compile a having clause involving a bitwise operator. + * + * @param array $having + * @return string + */ + protected function compileHavingBitwise($having) + { + $column = $this->wrap($having['column']); + + $parameter = $this->parameter($having['value']); + + return $having['boolean'].' ('.$column.' '.$having['operator'].' '.$parameter.')::bool'; + } + + /** + * Compile the lock into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param bool|string $value + * @return string + */ + protected function compileLock(Builder $query, $value) + { + if (! is_string($value)) { + return $value ? 'for update' : 'for share'; + } + + return $value; + } + + /** + * Compile an insert ignore statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileInsertOrIgnore(Builder $query, array $values) + { + return $this->compileInsert($query, $values).' on conflict do nothing'; + } + + /** + * Compile an insert and get ID statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param string $sequence + * @return string + */ + public function compileInsertGetId(Builder $query, $values, $sequence) + { + return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id'); + } + + /** + * Compile an update statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileUpdate(Builder $query, array $values) + { + if (isset($query->joins) || isset($query->limit)) { + return $this->compileUpdateWithJoinsOrLimit($query, $values); + } + + return parent::compileUpdate($query, $values); + } + + /** + * Compile the columns for an update statement. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + protected function compileUpdateColumns(Builder $query, array $values) + { + return collect($values)->map(function ($value, $key) { + $column = last(explode('.', $key)); + + if ($this->isJsonSelector($key)) { + return $this->compileJsonUpdateColumn($column, $value); + } + + return $this->wrap($column).' = '.$this->parameter($value); + })->implode(', '); + } + + /** + * Compile an "upsert" statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param array $uniqueBy + * @param array $update + * @return string + */ + public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update) + { + $sql = $this->compileInsert($query, $values); + + $sql .= ' on conflict ('.$this->columnize($uniqueBy).') do update set '; + + $columns = collect($update)->map(function ($value, $key) { + return is_numeric($key) + ? $this->wrap($value).' = '.$this->wrapValue('excluded').'.'.$this->wrap($value) + : $this->wrap($key).' = '.$this->parameter($value); + })->implode(', '); + + return $sql.$columns; + } + + /** + * Prepares a JSON column being updated using the JSONB_SET function. + * + * @param string $key + * @param mixed $value + * @return string + */ + protected function compileJsonUpdateColumn($key, $value) + { + $segments = explode('->', $key); + + $field = $this->wrap(array_shift($segments)); + + $path = '\'{"'.implode('","', $segments).'"}\''; + + return "{$field} = jsonb_set({$field}::jsonb, {$path}, {$this->parameter($value)})"; + } + + /** + * Compile an update from statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileUpdateFrom(Builder $query, $values) + { + $table = $this->wrapTable($query->from); + + // Each one of the columns in the update statements needs to be wrapped in the + // keyword identifiers, also a place-holder needs to be created for each of + // the values in the list of bindings so we can make the sets statements. + $columns = $this->compileUpdateColumns($query, $values); + + $from = ''; + + if (isset($query->joins)) { + // When using Postgres, updates with joins list the joined tables in the from + // clause, which is different than other systems like MySQL. Here, we will + // compile out the tables that are joined and add them to a from clause. + $froms = collect($query->joins)->map(function ($join) { + return $this->wrapTable($join->table); + })->all(); + + if (count($froms) > 0) { + $from = ' from '.implode(', ', $froms); + } + } + + $where = $this->compileUpdateWheres($query); + + return trim("update {$table} set {$columns}{$from} {$where}"); + } + + /** + * Compile the additional where clauses for updates with joins. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileUpdateWheres(Builder $query) + { + $baseWheres = $this->compileWheres($query); + + if (! isset($query->joins)) { + return $baseWheres; + } + + // Once we compile the join constraints, we will either use them as the where + // clause or append them to the existing base where clauses. If we need to + // strip the leading boolean we will do so when using as the only where. + $joinWheres = $this->compileUpdateJoinWheres($query); + + if (trim($baseWheres) == '') { + return 'where '.$this->removeLeadingBoolean($joinWheres); + } + + return $baseWheres.' '.$joinWheres; + } + + /** + * Compile the "join" clause where clauses for an update. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileUpdateJoinWheres(Builder $query) + { + $joinWheres = []; + + // Here we will just loop through all of the join constraints and compile them + // all out then implode them. This should give us "where" like syntax after + // everything has been built and then we will join it to the real wheres. + foreach ($query->joins as $join) { + foreach ($join->wheres as $where) { + $method = "where{$where['type']}"; + + $joinWheres[] = $where['boolean'].' '.$this->$method($query, $where); + } + } + + return implode(' ', $joinWheres); + } + + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdateFrom(array $bindings, array $values) + { + $values = collect($values)->map(function ($value, $column) { + return is_array($value) || ($this->isJsonSelector($column) && ! $this->isExpression($value)) + ? json_encode($value) + : $value; + })->all(); + + $bindingsWithoutWhere = Arr::except($bindings, ['select', 'where']); + + return array_values( + array_merge($values, $bindings['where'], Arr::flatten($bindingsWithoutWhere)) + ); + } + + /** + * Compile an update statement with joins or limit into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + protected function compileUpdateWithJoinsOrLimit(Builder $query, array $values) + { + $table = $this->wrapTable($query->from); + + $columns = $this->compileUpdateColumns($query, $values); + + $alias = last(preg_split('/\s+as\s+/i', $query->from)); + + $selectSql = $this->compileSelect($query->select($alias.'.ctid')); + + return "update {$table} set {$columns} where {$this->wrap('ctid')} in ({$selectSql})"; + } + + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + $values = collect($values)->map(function ($value, $column) { + return is_array($value) || ($this->isJsonSelector($column) && ! $this->isExpression($value)) + ? json_encode($value) + : $value; + })->all(); + + $cleanBindings = Arr::except($bindings, 'select'); + + return array_values( + array_merge($values, Arr::flatten($cleanBindings)) + ); + } + + /** + * Compile a delete statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileDelete(Builder $query) + { + if (isset($query->joins) || isset($query->limit)) { + return $this->compileDeleteWithJoinsOrLimit($query); + } + + return parent::compileDelete($query); + } + + /** + * Compile a delete statement with joins or limit into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileDeleteWithJoinsOrLimit(Builder $query) + { + $table = $this->wrapTable($query->from); + + $alias = last(preg_split('/\s+as\s+/i', $query->from)); + + $selectSql = $this->compileSelect($query->select($alias.'.ctid')); + + return "delete from {$table} where {$this->wrap('ctid')} in ({$selectSql})"; + } + + /** + * Compile a truncate table statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return array + */ + public function compileTruncate(Builder $query) + { + return ['truncate '.$this->wrapTable($query->from).' restart identity cascade' => []]; + } + + /** + * Wrap the given JSON selector. + * + * @param string $value + * @return string + */ + protected function wrapJsonSelector($value) + { + $path = explode('->', $value); + + $field = $this->wrapSegments(explode('.', array_shift($path))); + + $wrappedPath = $this->wrapJsonPathAttributes($path); + + $attribute = array_pop($wrappedPath); + + if (! empty($wrappedPath)) { + return $field.'->'.implode('->', $wrappedPath).'->>'.$attribute; + } + + return $field.'->>'.$attribute; + } + + /** + * Wrap the given JSON selector for boolean values. + * + * @param string $value + * @return string + */ + protected function wrapJsonBooleanSelector($value) + { + $selector = str_replace( + '->>', '->', + $this->wrapJsonSelector($value) + ); + + return '('.$selector.')::jsonb'; + } + + /** + * Wrap the given JSON boolean value. + * + * @param string $value + * @return string + */ + protected function wrapJsonBooleanValue($value) + { + return "'".$value."'::jsonb"; + } + + /** + * Wrap the attributes of the give JSON path. + * + * @param array $path + * @return array + */ + protected function wrapJsonPathAttributes($path) + { + return array_map(function ($attribute) { + return filter_var($attribute, FILTER_VALIDATE_INT) !== false + ? $attribute + : "'$attribute'"; + }, $path); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php new file mode 100755 index 0000000..29a3796 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php @@ -0,0 +1,342 @@ +', '<=', '>=', '<>', '!=', + 'like', 'not like', 'ilike', + '&', '|', '<<', '>>', + ]; + + /** + * Compile the lock into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param bool|string $value + * @return string + */ + protected function compileLock(Builder $query, $value) + { + return ''; + } + + /** + * Wrap a union subquery in parentheses. + * + * @param string $sql + * @return string + */ + protected function wrapUnion($sql) + { + return 'select * from ('.$sql.')'; + } + + /** + * Compile a "where date" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereDate(Builder $query, $where) + { + return $this->dateBasedWhere('%Y-%m-%d', $query, $where); + } + + /** + * Compile a "where day" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereDay(Builder $query, $where) + { + return $this->dateBasedWhere('%d', $query, $where); + } + + /** + * Compile a "where month" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereMonth(Builder $query, $where) + { + return $this->dateBasedWhere('%m', $query, $where); + } + + /** + * Compile a "where year" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereYear(Builder $query, $where) + { + return $this->dateBasedWhere('%Y', $query, $where); + } + + /** + * Compile a "where time" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereTime(Builder $query, $where) + { + return $this->dateBasedWhere('%H:%M:%S', $query, $where); + } + + /** + * Compile a date based where clause. + * + * @param string $type + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function dateBasedWhere($type, Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return "strftime('{$type}', {$this->wrap($where['column'])}) {$where['operator']} cast({$value} as text)"; + } + + /** + * Compile a "JSON length" statement into SQL. + * + * @param string $column + * @param string $operator + * @param string $value + * @return string + */ + protected function compileJsonLength($column, $operator, $value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($column); + + return 'json_array_length('.$field.$path.') '.$operator.' '.$value; + } + + /** + * Compile an update statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileUpdate(Builder $query, array $values) + { + if (isset($query->joins) || isset($query->limit)) { + return $this->compileUpdateWithJoinsOrLimit($query, $values); + } + + return parent::compileUpdate($query, $values); + } + + /** + * Compile an insert ignore statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + public function compileInsertOrIgnore(Builder $query, array $values) + { + return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsert($query, $values)); + } + + /** + * Compile the columns for an update statement. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + protected function compileUpdateColumns(Builder $query, array $values) + { + $jsonGroups = $this->groupJsonColumnsForUpdate($values); + + return collect($values)->reject(function ($value, $key) { + return $this->isJsonSelector($key); + })->merge($jsonGroups)->map(function ($value, $key) use ($jsonGroups) { + $column = last(explode('.', $key)); + + $value = isset($jsonGroups[$key]) ? $this->compileJsonPatch($column, $value) : $this->parameter($value); + + return $this->wrap($column).' = '.$value; + })->implode(', '); + } + + /** + * Compile an "upsert" statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param array $uniqueBy + * @param array $update + * @return string + */ + public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update) + { + $sql = $this->compileInsert($query, $values); + + $sql .= ' on conflict ('.$this->columnize($uniqueBy).') do update set '; + + $columns = collect($update)->map(function ($value, $key) { + return is_numeric($key) + ? $this->wrap($value).' = '.$this->wrapValue('excluded').'.'.$this->wrap($value) + : $this->wrap($key).' = '.$this->parameter($value); + })->implode(', '); + + return $sql.$columns; + } + + /** + * Group the nested JSON columns. + * + * @param array $values + * @return array + */ + protected function groupJsonColumnsForUpdate(array $values) + { + $groups = []; + + foreach ($values as $key => $value) { + if ($this->isJsonSelector($key)) { + Arr::set($groups, str_replace('->', '.', Str::after($key, '.')), $value); + } + } + + return $groups; + } + + /** + * Compile a "JSON" patch statement into SQL. + * + * @param string $column + * @param mixed $value + * @return string + */ + protected function compileJsonPatch($column, $value) + { + return "json_patch(ifnull({$this->wrap($column)}, json('{}')), json({$this->parameter($value)}))"; + } + + /** + * Compile an update statement with joins or limit into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @return string + */ + protected function compileUpdateWithJoinsOrLimit(Builder $query, array $values) + { + $table = $this->wrapTable($query->from); + + $columns = $this->compileUpdateColumns($query, $values); + + $alias = last(preg_split('/\s+as\s+/i', $query->from)); + + $selectSql = $this->compileSelect($query->select($alias.'.rowid')); + + return "update {$table} set {$columns} where {$this->wrap('rowid')} in ({$selectSql})"; + } + + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + $groups = $this->groupJsonColumnsForUpdate($values); + + $values = collect($values)->reject(function ($value, $key) { + return $this->isJsonSelector($key); + })->merge($groups)->map(function ($value) { + return is_array($value) ? json_encode($value) : $value; + })->all(); + + $cleanBindings = Arr::except($bindings, 'select'); + + return array_values( + array_merge($values, Arr::flatten($cleanBindings)) + ); + } + + /** + * Compile a delete statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileDelete(Builder $query) + { + if (isset($query->joins) || isset($query->limit)) { + return $this->compileDeleteWithJoinsOrLimit($query); + } + + return parent::compileDelete($query); + } + + /** + * Compile a delete statement with joins or limit into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileDeleteWithJoinsOrLimit(Builder $query) + { + $table = $this->wrapTable($query->from); + + $alias = last(preg_split('/\s+as\s+/i', $query->from)); + + $selectSql = $this->compileSelect($query->select($alias.'.rowid')); + + return "delete from {$table} where {$this->wrap('rowid')} in ({$selectSql})"; + } + + /** + * Compile a truncate table statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return array + */ + public function compileTruncate(Builder $query) + { + return [ + 'delete from sqlite_sequence where name = ?' => [$query->from], + 'delete from '.$this->wrapTable($query->from) => [], + ]; + } + + /** + * Wrap the given JSON selector. + * + * @param string $value + * @return string + */ + protected function wrapJsonSelector($value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($value); + + return 'json_extract('.$field.$path.')'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php new file mode 100755 index 0000000..417b63e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php @@ -0,0 +1,584 @@ +', '<=', '>=', '!<', '!>', '<>', '!=', + 'like', 'not like', 'ilike', + '&', '&=', '|', '|=', '^', '^=', + ]; + + /** + * Compile a select query into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileSelect(Builder $query) + { + if (! $query->offset) { + return parent::compileSelect($query); + } + + if (is_null($query->columns)) { + $query->columns = ['*']; + } + + $components = $this->compileComponents($query); + + if (! empty($components['orders'])) { + return parent::compileSelect($query)." offset {$query->offset} rows fetch next {$query->limit} rows only"; + } + + // If an offset is present on the query, we will need to wrap the query in + // a big "ANSI" offset syntax block. This is very nasty compared to the + // other database systems but is necessary for implementing features. + return $this->compileAnsiOffset( + $query, $components + ); + } + + /** + * Compile the "select *" portion of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $columns + * @return string|null + */ + protected function compileColumns(Builder $query, $columns) + { + if (! is_null($query->aggregate)) { + return; + } + + $select = $query->distinct ? 'select distinct ' : 'select '; + + // If there is a limit on the query, but not an offset, we will add the top + // clause to the query, which serves as a "limit" type clause within the + // SQL Server system similar to the limit keywords available in MySQL. + if (is_numeric($query->limit) && $query->limit > 0 && $query->offset <= 0) { + $select .= 'top '.((int) $query->limit).' '; + } + + return $select.$this->columnize($columns); + } + + /** + * Compile the "from" portion of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @return string + */ + protected function compileFrom(Builder $query, $table) + { + $from = parent::compileFrom($query, $table); + + if (is_string($query->lock)) { + return $from.' '.$query->lock; + } + + if (! is_null($query->lock)) { + return $from.' with(rowlock,'.($query->lock ? 'updlock,' : '').'holdlock)'; + } + + return $from; + } + + /** + * {@inheritdoc} + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereBitwise(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + $operator = str_replace('?', '??', $where['operator']); + + return '('.$this->wrap($where['column']).' '.$operator.' '.$value.') != 0'; + } + + /** + * Compile a "where date" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereDate(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return 'cast('.$this->wrap($where['column']).' as date) '.$where['operator'].' '.$value; + } + + /** + * Compile a "where time" clause. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereTime(Builder $query, $where) + { + $value = $this->parameter($where['value']); + + return 'cast('.$this->wrap($where['column']).' as time) '.$where['operator'].' '.$value; + } + + /** + * Compile a "JSON contains" statement into SQL. + * + * @param string $column + * @param string $value + * @return string + */ + protected function compileJsonContains($column, $value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($column); + + return $value.' in (select [value] from openjson('.$field.$path.'))'; + } + + /** + * Prepare the binding for a "JSON contains" statement. + * + * @param mixed $binding + * @return string + */ + public function prepareBindingForJsonContains($binding) + { + return is_bool($binding) ? json_encode($binding) : $binding; + } + + /** + * Compile a "JSON length" statement into SQL. + * + * @param string $column + * @param string $operator + * @param string $value + * @return string + */ + protected function compileJsonLength($column, $operator, $value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($column); + + return '(select count(*) from openjson('.$field.$path.')) '.$operator.' '.$value; + } + + /** + * {@inheritdoc} + * + * @param array $having + * @return string + */ + protected function compileHaving(array $having) + { + if ($having['type'] === 'Bitwise') { + return $this->compileHavingBitwise($having); + } + + return parent::compileHaving($having); + } + + /** + * Compile a having clause involving a bitwise operator. + * + * @param array $having + * @return string + */ + protected function compileHavingBitwise($having) + { + $column = $this->wrap($having['column']); + + $parameter = $this->parameter($having['value']); + + return $having['boolean'].' ('.$column.' '.$having['operator'].' '.$parameter.') != 0'; + } + + /** + * Create a full ANSI offset clause for the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $components + * @return string + */ + protected function compileAnsiOffset(Builder $query, $components) + { + // An ORDER BY clause is required to make this offset query work, so if one does + // not exist we'll just create a dummy clause to trick the database and so it + // does not complain about the queries for not having an "order by" clause. + if (empty($components['orders'])) { + $components['orders'] = 'order by (select 0)'; + } + + // We need to add the row number to the query so we can compare it to the offset + // and limit values given for the statements. So we will add an expression to + // the "select" that will give back the row numbers on each of the records. + $components['columns'] .= $this->compileOver($components['orders']); + + unset($components['orders']); + + if ($this->queryOrderContainsSubquery($query)) { + $query->bindings = $this->sortBindingsForSubqueryOrderBy($query); + } + + // Next we need to calculate the constraints that should be placed on the query + // to get the right offset and limit from our query but if there is no limit + // set we will just handle the offset only since that is all that matters. + $sql = $this->concatenate($components); + + return $this->compileTableExpression($sql, $query); + } + + /** + * Compile the over statement for a table expression. + * + * @param string $orderings + * @return string + */ + protected function compileOver($orderings) + { + return ", row_number() over ({$orderings}) as row_num"; + } + + /** + * Determine if the query's order by clauses contain a subquery. + * + * @param \Illuminate\Database\Query\Builder $query + * @return bool + */ + protected function queryOrderContainsSubquery($query) + { + if (! is_array($query->orders)) { + return false; + } + + return Arr::first($query->orders, function ($value) { + return $this->isExpression($value['column'] ?? null); + }, false) !== false; + } + + /** + * Move the order bindings to be after the "select" statement to account for an order by subquery. + * + * @param \Illuminate\Database\Query\Builder $query + * @return array + */ + protected function sortBindingsForSubqueryOrderBy($query) + { + return Arr::sort($query->bindings, function ($bindings, $key) { + return array_search($key, ['select', 'order', 'from', 'join', 'where', 'groupBy', 'having', 'union', 'unionOrder']); + }); + } + + /** + * Compile a common table expression for a query. + * + * @param string $sql + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileTableExpression($sql, $query) + { + $constraint = $this->compileRowConstraint($query); + + return "select * from ({$sql}) as temp_table where row_num {$constraint} order by row_num"; + } + + /** + * Compile the limit / offset row constraint for a query. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + protected function compileRowConstraint($query) + { + $start = (int) $query->offset + 1; + + if ($query->limit > 0) { + $finish = (int) $query->offset + (int) $query->limit; + + return "between {$start} and {$finish}"; + } + + return ">= {$start}"; + } + + /** + * Compile a delete statement without joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $where + * @return string + */ + protected function compileDeleteWithoutJoins(Builder $query, $table, $where) + { + $sql = parent::compileDeleteWithoutJoins($query, $table, $where); + + return ! is_null($query->limit) && $query->limit > 0 && $query->offset <= 0 + ? Str::replaceFirst('delete', 'delete top ('.$query->limit.')', $sql) + : $sql; + } + + /** + * Compile the random statement into SQL. + * + * @param string $seed + * @return string + */ + public function compileRandom($seed) + { + return 'NEWID()'; + } + + /** + * Compile the "limit" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param int $limit + * @return string + */ + protected function compileLimit(Builder $query, $limit) + { + return ''; + } + + /** + * Compile the "offset" portions of the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param int $offset + * @return string + */ + protected function compileOffset(Builder $query, $offset) + { + return ''; + } + + /** + * Compile the lock into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param bool|string $value + * @return string + */ + protected function compileLock(Builder $query, $value) + { + return ''; + } + + /** + * Wrap a union subquery in parentheses. + * + * @param string $sql + * @return string + */ + protected function wrapUnion($sql) + { + return 'select * from ('.$sql.') as '.$this->wrapTable('temp_table'); + } + + /** + * Compile an exists statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @return string + */ + public function compileExists(Builder $query) + { + $existsQuery = clone $query; + + $existsQuery->columns = []; + + return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1)); + } + + /** + * Compile an update statement with joins into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $table + * @param string $columns + * @param string $where + * @return string + */ + protected function compileUpdateWithJoins(Builder $query, $table, $columns, $where) + { + $alias = last(explode(' as ', $table)); + + $joins = $this->compileJoins($query, $query->joins); + + return "update {$alias} set {$columns} from {$table} {$joins} {$where}"; + } + + /** + * Compile an "upsert" statement into SQL. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $values + * @param array $uniqueBy + * @param array $update + * @return string + */ + public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update) + { + $columns = $this->columnize(array_keys(reset($values))); + + $sql = 'merge '.$this->wrapTable($query->from).' '; + + $parameters = collect($values)->map(function ($record) { + return '('.$this->parameterize($record).')'; + })->implode(', '); + + $sql .= 'using (values '.$parameters.') '.$this->wrapTable('laravel_source').' ('.$columns.') '; + + $on = collect($uniqueBy)->map(function ($column) use ($query) { + return $this->wrap('laravel_source.'.$column).' = '.$this->wrap($query->from.'.'.$column); + })->implode(' and '); + + $sql .= 'on '.$on.' '; + + if ($update) { + $update = collect($update)->map(function ($value, $key) { + return is_numeric($key) + ? $this->wrap($value).' = '.$this->wrap('laravel_source.'.$value) + : $this->wrap($key).' = '.$this->parameter($value); + })->implode(', '); + + $sql .= 'when matched then update set '.$update.' '; + } + + $sql .= 'when not matched then insert ('.$columns.') values ('.$columns.');'; + + return $sql; + } + + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + $cleanBindings = Arr::except($bindings, 'select'); + + return array_values( + array_merge($values, Arr::flatten($cleanBindings)) + ); + } + + /** + * Compile the SQL statement to define a savepoint. + * + * @param string $name + * @return string + */ + public function compileSavepoint($name) + { + return 'SAVE TRANSACTION '.$name; + } + + /** + * Compile the SQL statement to execute a savepoint rollback. + * + * @param string $name + * @return string + */ + public function compileSavepointRollBack($name) + { + return 'ROLLBACK TRANSACTION '.$name; + } + + /** + * Get the format for database stored dates. + * + * @return string + */ + public function getDateFormat() + { + return 'Y-m-d H:i:s.v'; + } + + /** + * Wrap a single string in keyword identifiers. + * + * @param string $value + * @return string + */ + protected function wrapValue($value) + { + return $value === '*' ? $value : '['.str_replace(']', ']]', $value).']'; + } + + /** + * Wrap the given JSON selector. + * + * @param string $value + * @return string + */ + protected function wrapJsonSelector($value) + { + [$field, $path] = $this->wrapJsonFieldAndPath($value); + + return 'json_value('.$field.$path.')'; + } + + /** + * Wrap the given JSON boolean value. + * + * @param string $value + * @return string + */ + protected function wrapJsonBooleanValue($value) + { + return "'".$value."'"; + } + + /** + * Wrap a table in keyword identifiers. + * + * @param \Illuminate\Database\Query\Expression|string $table + * @return string + */ + public function wrapTable($table) + { + if (! $this->isExpression($table)) { + return $this->wrapTableValuedFunction(parent::wrapTable($table)); + } + + return $this->getValue($table); + } + + /** + * Wrap a table in keyword identifiers. + * + * @param string $table + * @return string + */ + protected function wrapTableValuedFunction($table) + { + if (preg_match('/^(.+?)(\(.*?\))]$/', $table, $matches) === 1) { + $table = $matches[1].']'.$matches[2]; + } + + return $table; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/JoinClause.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/JoinClause.php new file mode 100755 index 0000000..57d650a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/JoinClause.php @@ -0,0 +1,146 @@ +type = $type; + $this->table = $table; + $this->parentClass = get_class($parentQuery); + $this->parentGrammar = $parentQuery->getGrammar(); + $this->parentProcessor = $parentQuery->getProcessor(); + $this->parentConnection = $parentQuery->getConnection(); + + parent::__construct( + $this->parentConnection, $this->parentGrammar, $this->parentProcessor + ); + } + + /** + * Add an "on" clause to the join. + * + * On clauses can be chained, e.g. + * + * $join->on('contacts.user_id', '=', 'users.id') + * ->on('contacts.info_id', '=', 'info.id') + * + * will produce the following SQL: + * + * on `contacts`.`user_id` = `users`.`id` and `contacts`.`info_id` = `info`.`id` + * + * @param \Closure|string $first + * @param string|null $operator + * @param \Illuminate\Database\Query\Expression|string|null $second + * @param string $boolean + * @return $this + * + * @throws \InvalidArgumentException + */ + public function on($first, $operator = null, $second = null, $boolean = 'and') + { + if ($first instanceof Closure) { + return $this->whereNested($first, $boolean); + } + + return $this->whereColumn($first, $operator, $second, $boolean); + } + + /** + * Add an "or on" clause to the join. + * + * @param \Closure|string $first + * @param string|null $operator + * @param \Illuminate\Database\Query\Expression|string|null $second + * @return \Illuminate\Database\Query\JoinClause + */ + public function orOn($first, $operator = null, $second = null) + { + return $this->on($first, $operator, $second, 'or'); + } + + /** + * Get a new instance of the join clause builder. + * + * @return \Illuminate\Database\Query\JoinClause + */ + public function newQuery() + { + return new static($this->newParentQuery(), $this->type, $this->table); + } + + /** + * Create a new query instance for sub-query. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function forSubQuery() + { + return $this->newParentQuery()->newQuery(); + } + + /** + * Create a new parent query instance. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function newParentQuery() + { + $class = $this->parentClass; + + return new $class($this->parentConnection, $this->parentGrammar, $this->parentProcessor); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/MySqlProcessor.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/MySqlProcessor.php new file mode 100644 index 0000000..ce91838 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/MySqlProcessor.php @@ -0,0 +1,19 @@ +column_name; + }, $results); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/PostgresProcessor.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/PostgresProcessor.php new file mode 100755 index 0000000..5956a8f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/PostgresProcessor.php @@ -0,0 +1,45 @@ +getConnection(); + + $connection->recordsHaveBeenModified(); + + $result = $connection->selectFromWriteConnection($sql, $values)[0]; + + $sequence = $sequence ?: 'id'; + + $id = is_object($result) ? $result->{$sequence} : $result[$sequence]; + + return is_numeric($id) ? (int) $id : $id; + } + + /** + * Process the results of a column listing query. + * + * @param array $results + * @return array + */ + public function processColumnListing($results) + { + return array_map(function ($result) { + return ((object) $result)->column_name; + }, $results); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php new file mode 100755 index 0000000..0069b43 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php @@ -0,0 +1,49 @@ +getConnection()->insert($sql, $values); + + $id = $query->getConnection()->getPdo()->lastInsertId($sequence); + + return is_numeric($id) ? (int) $id : $id; + } + + /** + * Process the results of a column listing query. + * + * @param array $results + * @return array + */ + public function processColumnListing($results) + { + return $results; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SQLiteProcessor.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SQLiteProcessor.php new file mode 100644 index 0000000..65da1df --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SQLiteProcessor.php @@ -0,0 +1,19 @@ +name; + }, $results); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php new file mode 100755 index 0000000..49476f0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php @@ -0,0 +1,70 @@ +getConnection(); + + $connection->insert($sql, $values); + + if ($connection->getConfig('odbc') === true) { + $id = $this->processInsertGetIdForOdbc($connection); + } else { + $id = $connection->getPdo()->lastInsertId(); + } + + return is_numeric($id) ? (int) $id : $id; + } + + /** + * Process an "insert get ID" query for ODBC. + * + * @param \Illuminate\Database\Connection $connection + * @return int + * + * @throws \Exception + */ + protected function processInsertGetIdForOdbc(Connection $connection) + { + $result = $connection->selectFromWriteConnection( + 'SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid' + ); + + if (! $result) { + throw new Exception('Unable to retrieve lastInsertID for ODBC.'); + } + + $row = $result[0]; + + return is_object($row) ? $row->insertid : $row['insertid']; + } + + /** + * Process the results of a column listing query. + * + * @param array $results + * @return array + */ + public function processColumnListing($results) + { + return array_map(function ($result) { + return ((object) $result)->name; + }, $results); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/QueryException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/QueryException.php new file mode 100644 index 0000000..74e5a31 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/QueryException.php @@ -0,0 +1,79 @@ +sql = $sql; + $this->bindings = $bindings; + $this->code = $previous->getCode(); + $this->message = $this->formatMessage($sql, $bindings, $previous); + + if ($previous instanceof PDOException) { + $this->errorInfo = $previous->errorInfo; + } + } + + /** + * Format the SQL error message. + * + * @param string $sql + * @param array $bindings + * @param \Throwable $previous + * @return string + */ + protected function formatMessage($sql, $bindings, Throwable $previous) + { + return $previous->getMessage().' (SQL: '.Str::replaceArray('?', $bindings, $sql).')'; + } + + /** + * Get the SQL for the query. + * + * @return string + */ + public function getSql() + { + return $this->sql; + } + + /** + * Get the bindings for the query. + * + * @return array + */ + public function getBindings() + { + return $this->bindings; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/README.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/README.md new file mode 100755 index 0000000..9019936 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/README.md @@ -0,0 +1,69 @@ +## Illuminate Database + +The Illuminate Database component is a full database toolkit for PHP, providing an expressive query builder, ActiveRecord style ORM, and schema builder. It currently supports MySQL, Postgres, SQL Server, and SQLite. It also serves as the database layer of the Laravel PHP framework. + +### Usage Instructions + +First, create a new "Capsule" manager instance. Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible. + +```PHP +use Illuminate\Database\Capsule\Manager as Capsule; + +$capsule = new Capsule; + +$capsule->addConnection([ + 'driver' => 'mysql', + 'host' => 'localhost', + 'database' => 'database', + 'username' => 'root', + 'password' => 'password', + 'charset' => 'utf8', + 'collation' => 'utf8_unicode_ci', + 'prefix' => '', +]); + +// Set the event dispatcher used by Eloquent models... (optional) +use Illuminate\Events\Dispatcher; +use Illuminate\Container\Container; +$capsule->setEventDispatcher(new Dispatcher(new Container)); + +// Make this Capsule instance available globally via static methods... (optional) +$capsule->setAsGlobal(); + +// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher()) +$capsule->bootEloquent(); +``` + +> `composer require "illuminate/events"` required when you need to use observers with Eloquent. + +Once the Capsule instance has been registered. You may use it like so: + +**Using The Query Builder** + +```PHP +$users = Capsule::table('users')->where('votes', '>', 100)->get(); +``` +Other core methods may be accessed directly from the Capsule in the same manner as from the DB facade: +```PHP +$results = Capsule::select('select * from users where id = ?', [1]); +``` + +**Using The Schema Builder** + +```PHP +Capsule::schema()->create('users', function ($table) { + $table->increments('id'); + $table->string('email')->unique(); + $table->timestamps(); +}); +``` + +**Using The Eloquent ORM** + +```PHP +class User extends Illuminate\Database\Eloquent\Model {} + +$users = User::where('votes', '>', 1)->get(); +``` + +For further documentation on using the various database facilities this library provides, consult the [Laravel framework documentation](https://laravel.com/docs). diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/RecordsNotFoundException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/RecordsNotFoundException.php new file mode 100755 index 0000000..3e0d955 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/RecordsNotFoundException.php @@ -0,0 +1,10 @@ +getForeignKeyConstraintsConfigurationValue(); + + if ($enableForeignKeyConstraints === null) { + return; + } + + $enableForeignKeyConstraints + ? $this->getSchemaBuilder()->enableForeignKeyConstraints() + : $this->getSchemaBuilder()->disableForeignKeyConstraints(); + } + + /** + * Get the default query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\SQLiteGrammar + */ + protected function getDefaultQueryGrammar() + { + return $this->withTablePrefix(new QueryGrammar); + } + + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\SQLiteBuilder + */ + public function getSchemaBuilder() + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new SQLiteBuilder($this); + } + + /** + * Get the default schema grammar instance. + * + * @return \Illuminate\Database\Schema\Grammars\SQLiteGrammar + */ + protected function getDefaultSchemaGrammar() + { + return $this->withTablePrefix(new SchemaGrammar); + } + + /** + * Get the schema state for the connection. + * + * @param \Illuminate\Filesystem\Filesystem|null $files + * @param callable|null $processFactory + * + * @throws \RuntimeException + */ + public function getSchemaState(Filesystem $files = null, callable $processFactory = null) + { + return new SqliteSchemaState($this, $files, $processFactory); + } + + /** + * Get the default post processor instance. + * + * @return \Illuminate\Database\Query\Processors\SQLiteProcessor + */ + protected function getDefaultPostProcessor() + { + return new SQLiteProcessor; + } + + /** + * Get the Doctrine DBAL driver. + * + * @return \Doctrine\DBAL\Driver\PDOSqlite\Driver|\Illuminate\Database\PDO\SQLiteDriver + */ + protected function getDoctrineDriver() + { + return class_exists(Version::class) ? new DoctrineDriver : new SQLiteDriver; + } + + /** + * Get the database connection foreign key constraints configuration option. + * + * @return bool|null + */ + protected function getForeignKeyConstraintsConfigurationValue() + { + return $this->getConfig('foreign_key_constraints'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php new file mode 100755 index 0000000..dfe53ee --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php @@ -0,0 +1,1711 @@ +table = $table; + $this->prefix = $prefix; + + if (! is_null($callback)) { + $callback($this); + } + } + + /** + * Execute the blueprint against the database. + * + * @param \Illuminate\Database\Connection $connection + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @return void + */ + public function build(Connection $connection, Grammar $grammar) + { + foreach ($this->toSql($connection, $grammar) as $statement) { + $connection->statement($statement); + } + } + + /** + * Get the raw SQL statements for the blueprint. + * + * @param \Illuminate\Database\Connection $connection + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @return array + */ + public function toSql(Connection $connection, Grammar $grammar) + { + $this->addImpliedCommands($grammar); + + $statements = []; + + // Each type of command has a corresponding compiler function on the schema + // grammar which is used to build the necessary SQL statements to build + // the blueprint element, so we'll just call that compilers function. + $this->ensureCommandsAreValid($connection); + + foreach ($this->commands as $command) { + $method = 'compile'.ucfirst($command->name); + + if (method_exists($grammar, $method) || $grammar::hasMacro($method)) { + if (! is_null($sql = $grammar->$method($this, $command, $connection))) { + $statements = array_merge($statements, (array) $sql); + } + } + } + + return $statements; + } + + /** + * Ensure the commands on the blueprint are valid for the connection type. + * + * @param \Illuminate\Database\Connection $connection + * @return void + * + * @throws \BadMethodCallException + */ + protected function ensureCommandsAreValid(Connection $connection) + { + if ($connection instanceof SQLiteConnection) { + if ($this->commandsNamed(['dropColumn', 'renameColumn'])->count() > 1) { + throw new BadMethodCallException( + "SQLite doesn't support multiple calls to dropColumn / renameColumn in a single modification." + ); + } + + if ($this->commandsNamed(['dropForeign'])->count() > 0) { + throw new BadMethodCallException( + "SQLite doesn't support dropping foreign keys (you would need to re-create the table)." + ); + } + } + } + + /** + * Get all of the commands matching the given names. + * + * @param array $names + * @return \Illuminate\Support\Collection + */ + protected function commandsNamed(array $names) + { + return collect($this->commands)->filter(function ($command) use ($names) { + return in_array($command->name, $names); + }); + } + + /** + * Add the commands that are implied by the blueprint's state. + * + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @return void + */ + protected function addImpliedCommands(Grammar $grammar) + { + if (count($this->getAddedColumns()) > 0 && ! $this->creating()) { + array_unshift($this->commands, $this->createCommand('add')); + } + + if (count($this->getChangedColumns()) > 0 && ! $this->creating()) { + array_unshift($this->commands, $this->createCommand('change')); + } + + $this->addFluentIndexes(); + + $this->addFluentCommands($grammar); + } + + /** + * Add the index commands fluently specified on columns. + * + * @return void + */ + protected function addFluentIndexes() + { + foreach ($this->columns as $column) { + foreach (['primary', 'unique', 'index', 'fulltext', 'fullText', 'spatialIndex'] as $index) { + // If the index has been specified on the given column, but is simply equal + // to "true" (boolean), no name has been specified for this index so the + // index method can be called without a name and it will generate one. + if ($column->{$index} === true) { + $this->{$index}($column->name); + $column->{$index} = false; + + continue 2; + } + + // If the index has been specified on the given column, and it has a string + // value, we'll go ahead and call the index method and pass the name for + // the index since the developer specified the explicit name for this. + elseif (isset($column->{$index})) { + $this->{$index}($column->name, $column->{$index}); + $column->{$index} = false; + + continue 2; + } + } + } + } + + /** + * Add the fluent commands specified on any columns. + * + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @return void + */ + public function addFluentCommands(Grammar $grammar) + { + foreach ($this->columns as $column) { + foreach ($grammar->getFluentCommands() as $commandName) { + $attributeName = lcfirst($commandName); + + if (! isset($column->{$attributeName})) { + continue; + } + + $value = $column->{$attributeName}; + + $this->addCommand( + $commandName, compact('value', 'column') + ); + } + } + } + + /** + * Determine if the blueprint has a create command. + * + * @return bool + */ + public function creating() + { + return collect($this->commands)->contains(function ($command) { + return $command->name === 'create'; + }); + } + + /** + * Indicate that the table needs to be created. + * + * @return \Illuminate\Support\Fluent + */ + public function create() + { + return $this->addCommand('create'); + } + + /** + * Indicate that the table needs to be temporary. + * + * @return void + */ + public function temporary() + { + $this->temporary = true; + } + + /** + * Indicate that the table should be dropped. + * + * @return \Illuminate\Support\Fluent + */ + public function drop() + { + return $this->addCommand('drop'); + } + + /** + * Indicate that the table should be dropped if it exists. + * + * @return \Illuminate\Support\Fluent + */ + public function dropIfExists() + { + return $this->addCommand('dropIfExists'); + } + + /** + * Indicate that the given columns should be dropped. + * + * @param array|mixed $columns + * @return \Illuminate\Support\Fluent + */ + public function dropColumn($columns) + { + $columns = is_array($columns) ? $columns : func_get_args(); + + return $this->addCommand('dropColumn', compact('columns')); + } + + /** + * Indicate that the given columns should be renamed. + * + * @param string $from + * @param string $to + * @return \Illuminate\Support\Fluent + */ + public function renameColumn($from, $to) + { + return $this->addCommand('renameColumn', compact('from', 'to')); + } + + /** + * Indicate that the given primary key should be dropped. + * + * @param string|array|null $index + * @return \Illuminate\Support\Fluent + */ + public function dropPrimary($index = null) + { + return $this->dropIndexCommand('dropPrimary', 'primary', $index); + } + + /** + * Indicate that the given unique key should be dropped. + * + * @param string|array $index + * @return \Illuminate\Support\Fluent + */ + public function dropUnique($index) + { + return $this->dropIndexCommand('dropUnique', 'unique', $index); + } + + /** + * Indicate that the given index should be dropped. + * + * @param string|array $index + * @return \Illuminate\Support\Fluent + */ + public function dropIndex($index) + { + return $this->dropIndexCommand('dropIndex', 'index', $index); + } + + /** + * Indicate that the given fulltext index should be dropped. + * + * @param string|array $index + * @return \Illuminate\Support\Fluent + */ + public function dropFullText($index) + { + return $this->dropIndexCommand('dropFullText', 'fulltext', $index); + } + + /** + * Indicate that the given spatial index should be dropped. + * + * @param string|array $index + * @return \Illuminate\Support\Fluent + */ + public function dropSpatialIndex($index) + { + return $this->dropIndexCommand('dropSpatialIndex', 'spatialIndex', $index); + } + + /** + * Indicate that the given foreign key should be dropped. + * + * @param string|array $index + * @return \Illuminate\Support\Fluent + */ + public function dropForeign($index) + { + return $this->dropIndexCommand('dropForeign', 'foreign', $index); + } + + /** + * Indicate that the given column and foreign key should be dropped. + * + * @param string $column + * @return \Illuminate\Support\Fluent + */ + public function dropConstrainedForeignId($column) + { + $this->dropForeign([$column]); + + return $this->dropColumn($column); + } + + /** + * Indicate that the given indexes should be renamed. + * + * @param string $from + * @param string $to + * @return \Illuminate\Support\Fluent + */ + public function renameIndex($from, $to) + { + return $this->addCommand('renameIndex', compact('from', 'to')); + } + + /** + * Indicate that the timestamp columns should be dropped. + * + * @return void + */ + public function dropTimestamps() + { + $this->dropColumn('created_at', 'updated_at'); + } + + /** + * Indicate that the timestamp columns should be dropped. + * + * @return void + */ + public function dropTimestampsTz() + { + $this->dropTimestamps(); + } + + /** + * Indicate that the soft delete column should be dropped. + * + * @param string $column + * @return void + */ + public function dropSoftDeletes($column = 'deleted_at') + { + $this->dropColumn($column); + } + + /** + * Indicate that the soft delete column should be dropped. + * + * @param string $column + * @return void + */ + public function dropSoftDeletesTz($column = 'deleted_at') + { + $this->dropSoftDeletes($column); + } + + /** + * Indicate that the remember token column should be dropped. + * + * @return void + */ + public function dropRememberToken() + { + $this->dropColumn('remember_token'); + } + + /** + * Indicate that the polymorphic columns should be dropped. + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function dropMorphs($name, $indexName = null) + { + $this->dropIndex($indexName ?: $this->createIndexName('index', ["{$name}_type", "{$name}_id"])); + + $this->dropColumn("{$name}_type", "{$name}_id"); + } + + /** + * Rename the table to a given name. + * + * @param string $to + * @return \Illuminate\Support\Fluent + */ + public function rename($to) + { + return $this->addCommand('rename', compact('to')); + } + + /** + * Specify the primary key(s) for the table. + * + * @param string|array $columns + * @param string|null $name + * @param string|null $algorithm + * @return \Illuminate\Support\Fluent + */ + public function primary($columns, $name = null, $algorithm = null) + { + return $this->indexCommand('primary', $columns, $name, $algorithm); + } + + /** + * Specify a unique index for the table. + * + * @param string|array $columns + * @param string|null $name + * @param string|null $algorithm + * @return \Illuminate\Support\Fluent + */ + public function unique($columns, $name = null, $algorithm = null) + { + return $this->indexCommand('unique', $columns, $name, $algorithm); + } + + /** + * Specify an index for the table. + * + * @param string|array $columns + * @param string|null $name + * @param string|null $algorithm + * @return \Illuminate\Support\Fluent + */ + public function index($columns, $name = null, $algorithm = null) + { + return $this->indexCommand('index', $columns, $name, $algorithm); + } + + /** + * Specify an fulltext for the table. + * + * @param string|array $columns + * @param string|null $name + * @param string|null $algorithm + * @return \Illuminate\Support\Fluent + */ + public function fullText($columns, $name = null, $algorithm = null) + { + return $this->indexCommand('fulltext', $columns, $name, $algorithm); + } + + /** + * Specify a spatial index for the table. + * + * @param string|array $columns + * @param string|null $name + * @return \Illuminate\Support\Fluent + */ + public function spatialIndex($columns, $name = null) + { + return $this->indexCommand('spatialIndex', $columns, $name); + } + + /** + * Specify a raw index for the table. + * + * @param string $expression + * @param string $name + * @return \Illuminate\Support\Fluent + */ + public function rawIndex($expression, $name) + { + return $this->index([new Expression($expression)], $name); + } + + /** + * Specify a foreign key for the table. + * + * @param string|array $columns + * @param string|null $name + * @return \Illuminate\Database\Schema\ForeignKeyDefinition + */ + public function foreign($columns, $name = null) + { + $command = new ForeignKeyDefinition( + $this->indexCommand('foreign', $columns, $name)->getAttributes() + ); + + $this->commands[count($this->commands) - 1] = $command; + + return $command; + } + + /** + * Create a new auto-incrementing big integer (8-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function id($column = 'id') + { + return $this->bigIncrements($column); + } + + /** + * Create a new auto-incrementing integer (4-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function increments($column) + { + return $this->unsignedInteger($column, true); + } + + /** + * Create a new auto-incrementing integer (4-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function integerIncrements($column) + { + return $this->unsignedInteger($column, true); + } + + /** + * Create a new auto-incrementing tiny integer (1-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function tinyIncrements($column) + { + return $this->unsignedTinyInteger($column, true); + } + + /** + * Create a new auto-incrementing small integer (2-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function smallIncrements($column) + { + return $this->unsignedSmallInteger($column, true); + } + + /** + * Create a new auto-incrementing medium integer (3-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function mediumIncrements($column) + { + return $this->unsignedMediumInteger($column, true); + } + + /** + * Create a new auto-incrementing big integer (8-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function bigIncrements($column) + { + return $this->unsignedBigInteger($column, true); + } + + /** + * Create a new char column on the table. + * + * @param string $column + * @param int|null $length + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function char($column, $length = null) + { + $length = $length ?: Builder::$defaultStringLength; + + return $this->addColumn('char', $column, compact('length')); + } + + /** + * Create a new string column on the table. + * + * @param string $column + * @param int|null $length + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function string($column, $length = null) + { + $length = $length ?: Builder::$defaultStringLength; + + return $this->addColumn('string', $column, compact('length')); + } + + /** + * Create a new tiny text column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function tinyText($column) + { + return $this->addColumn('tinyText', $column); + } + + /** + * Create a new text column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function text($column) + { + return $this->addColumn('text', $column); + } + + /** + * Create a new medium text column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function mediumText($column) + { + return $this->addColumn('mediumText', $column); + } + + /** + * Create a new long text column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function longText($column) + { + return $this->addColumn('longText', $column); + } + + /** + * Create a new integer (4-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function integer($column, $autoIncrement = false, $unsigned = false) + { + return $this->addColumn('integer', $column, compact('autoIncrement', 'unsigned')); + } + + /** + * Create a new tiny integer (1-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function tinyInteger($column, $autoIncrement = false, $unsigned = false) + { + return $this->addColumn('tinyInteger', $column, compact('autoIncrement', 'unsigned')); + } + + /** + * Create a new small integer (2-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function smallInteger($column, $autoIncrement = false, $unsigned = false) + { + return $this->addColumn('smallInteger', $column, compact('autoIncrement', 'unsigned')); + } + + /** + * Create a new medium integer (3-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function mediumInteger($column, $autoIncrement = false, $unsigned = false) + { + return $this->addColumn('mediumInteger', $column, compact('autoIncrement', 'unsigned')); + } + + /** + * Create a new big integer (8-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function bigInteger($column, $autoIncrement = false, $unsigned = false) + { + return $this->addColumn('bigInteger', $column, compact('autoIncrement', 'unsigned')); + } + + /** + * Create a new unsigned integer (4-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedInteger($column, $autoIncrement = false) + { + return $this->integer($column, $autoIncrement, true); + } + + /** + * Create a new unsigned tiny integer (1-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedTinyInteger($column, $autoIncrement = false) + { + return $this->tinyInteger($column, $autoIncrement, true); + } + + /** + * Create a new unsigned small integer (2-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedSmallInteger($column, $autoIncrement = false) + { + return $this->smallInteger($column, $autoIncrement, true); + } + + /** + * Create a new unsigned medium integer (3-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedMediumInteger($column, $autoIncrement = false) + { + return $this->mediumInteger($column, $autoIncrement, true); + } + + /** + * Create a new unsigned big integer (8-byte) column on the table. + * + * @param string $column + * @param bool $autoIncrement + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedBigInteger($column, $autoIncrement = false) + { + return $this->bigInteger($column, $autoIncrement, true); + } + + /** + * Create a new unsigned big integer (8-byte) column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition + */ + public function foreignId($column) + { + return $this->addColumnDefinition(new ForeignIdColumnDefinition($this, [ + 'type' => 'bigInteger', + 'name' => $column, + 'autoIncrement' => false, + 'unsigned' => true, + ])); + } + + /** + * Create a foreign ID column for the given model. + * + * @param \Illuminate\Database\Eloquent\Model|string $model + * @param string|null $column + * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition + */ + public function foreignIdFor($model, $column = null) + { + if (is_string($model)) { + $model = new $model; + } + + return $model->getKeyType() === 'int' && $model->getIncrementing() + ? $this->foreignId($column ?: $model->getForeignKey()) + : $this->foreignUuid($column ?: $model->getForeignKey()); + } + + /** + * Create a new float column on the table. + * + * @param string $column + * @param int $total + * @param int $places + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function float($column, $total = 8, $places = 2, $unsigned = false) + { + return $this->addColumn('float', $column, compact('total', 'places', 'unsigned')); + } + + /** + * Create a new double column on the table. + * + * @param string $column + * @param int|null $total + * @param int|null $places + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function double($column, $total = null, $places = null, $unsigned = false) + { + return $this->addColumn('double', $column, compact('total', 'places', 'unsigned')); + } + + /** + * Create a new decimal column on the table. + * + * @param string $column + * @param int $total + * @param int $places + * @param bool $unsigned + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function decimal($column, $total = 8, $places = 2, $unsigned = false) + { + return $this->addColumn('decimal', $column, compact('total', 'places', 'unsigned')); + } + + /** + * Create a new unsigned float column on the table. + * + * @param string $column + * @param int $total + * @param int $places + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedFloat($column, $total = 8, $places = 2) + { + return $this->float($column, $total, $places, true); + } + + /** + * Create a new unsigned double column on the table. + * + * @param string $column + * @param int $total + * @param int $places + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedDouble($column, $total = null, $places = null) + { + return $this->double($column, $total, $places, true); + } + + /** + * Create a new unsigned decimal column on the table. + * + * @param string $column + * @param int $total + * @param int $places + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function unsignedDecimal($column, $total = 8, $places = 2) + { + return $this->decimal($column, $total, $places, true); + } + + /** + * Create a new boolean column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function boolean($column) + { + return $this->addColumn('boolean', $column); + } + + /** + * Create a new enum column on the table. + * + * @param string $column + * @param array $allowed + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function enum($column, array $allowed) + { + return $this->addColumn('enum', $column, compact('allowed')); + } + + /** + * Create a new set column on the table. + * + * @param string $column + * @param array $allowed + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function set($column, array $allowed) + { + return $this->addColumn('set', $column, compact('allowed')); + } + + /** + * Create a new json column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function json($column) + { + return $this->addColumn('json', $column); + } + + /** + * Create a new jsonb column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function jsonb($column) + { + return $this->addColumn('jsonb', $column); + } + + /** + * Create a new date column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function date($column) + { + return $this->addColumn('date', $column); + } + + /** + * Create a new date-time column on the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function dateTime($column, $precision = 0) + { + return $this->addColumn('dateTime', $column, compact('precision')); + } + + /** + * Create a new date-time column (with time zone) on the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function dateTimeTz($column, $precision = 0) + { + return $this->addColumn('dateTimeTz', $column, compact('precision')); + } + + /** + * Create a new time column on the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function time($column, $precision = 0) + { + return $this->addColumn('time', $column, compact('precision')); + } + + /** + * Create a new time column (with time zone) on the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function timeTz($column, $precision = 0) + { + return $this->addColumn('timeTz', $column, compact('precision')); + } + + /** + * Create a new timestamp column on the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function timestamp($column, $precision = 0) + { + return $this->addColumn('timestamp', $column, compact('precision')); + } + + /** + * Create a new timestamp (with time zone) column on the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function timestampTz($column, $precision = 0) + { + return $this->addColumn('timestampTz', $column, compact('precision')); + } + + /** + * Add nullable creation and update timestamps to the table. + * + * @param int $precision + * @return void + */ + public function timestamps($precision = 0) + { + $this->timestamp('created_at', $precision)->nullable(); + + $this->timestamp('updated_at', $precision)->nullable(); + } + + /** + * Add nullable creation and update timestamps to the table. + * + * Alias for self::timestamps(). + * + * @param int $precision + * @return void + */ + public function nullableTimestamps($precision = 0) + { + $this->timestamps($precision); + } + + /** + * Add creation and update timestampTz columns to the table. + * + * @param int $precision + * @return void + */ + public function timestampsTz($precision = 0) + { + $this->timestampTz('created_at', $precision)->nullable(); + + $this->timestampTz('updated_at', $precision)->nullable(); + } + + /** + * Add a "deleted at" timestamp for the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function softDeletes($column = 'deleted_at', $precision = 0) + { + return $this->timestamp($column, $precision)->nullable(); + } + + /** + * Add a "deleted at" timestampTz for the table. + * + * @param string $column + * @param int $precision + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function softDeletesTz($column = 'deleted_at', $precision = 0) + { + return $this->timestampTz($column, $precision)->nullable(); + } + + /** + * Create a new year column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function year($column) + { + return $this->addColumn('year', $column); + } + + /** + * Create a new binary column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function binary($column) + { + return $this->addColumn('binary', $column); + } + + /** + * Create a new uuid column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function uuid($column) + { + return $this->addColumn('uuid', $column); + } + + /** + * Create a new UUID column on the table with a foreign key constraint. + * + * @param string $column + * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition + */ + public function foreignUuid($column) + { + return $this->addColumnDefinition(new ForeignIdColumnDefinition($this, [ + 'type' => 'uuid', + 'name' => $column, + ])); + } + + /** + * Create a new IP address column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function ipAddress($column) + { + return $this->addColumn('ipAddress', $column); + } + + /** + * Create a new MAC address column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function macAddress($column) + { + return $this->addColumn('macAddress', $column); + } + + /** + * Create a new geometry column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function geometry($column) + { + return $this->addColumn('geometry', $column); + } + + /** + * Create a new point column on the table. + * + * @param string $column + * @param int|null $srid + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function point($column, $srid = null) + { + return $this->addColumn('point', $column, compact('srid')); + } + + /** + * Create a new linestring column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function lineString($column) + { + return $this->addColumn('linestring', $column); + } + + /** + * Create a new polygon column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function polygon($column) + { + return $this->addColumn('polygon', $column); + } + + /** + * Create a new geometrycollection column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function geometryCollection($column) + { + return $this->addColumn('geometrycollection', $column); + } + + /** + * Create a new multipoint column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function multiPoint($column) + { + return $this->addColumn('multipoint', $column); + } + + /** + * Create a new multilinestring column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function multiLineString($column) + { + return $this->addColumn('multilinestring', $column); + } + + /** + * Create a new multipolygon column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function multiPolygon($column) + { + return $this->addColumn('multipolygon', $column); + } + + /** + * Create a new multipolygon column on the table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function multiPolygonZ($column) + { + return $this->addColumn('multipolygonz', $column); + } + + /** + * Create a new generated, computed column on the table. + * + * @param string $column + * @param string $expression + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function computed($column, $expression) + { + return $this->addColumn('computed', $column, compact('expression')); + } + + /** + * Add the proper columns for a polymorphic table. + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function morphs($name, $indexName = null) + { + if (Builder::$defaultMorphKeyType === 'uuid') { + $this->uuidMorphs($name, $indexName); + } else { + $this->numericMorphs($name, $indexName); + } + } + + /** + * Add nullable columns for a polymorphic table. + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function nullableMorphs($name, $indexName = null) + { + if (Builder::$defaultMorphKeyType === 'uuid') { + $this->nullableUuidMorphs($name, $indexName); + } else { + $this->nullableNumericMorphs($name, $indexName); + } + } + + /** + * Add the proper columns for a polymorphic table using numeric IDs (incremental). + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function numericMorphs($name, $indexName = null) + { + $this->string("{$name}_type"); + + $this->unsignedBigInteger("{$name}_id"); + + $this->index(["{$name}_type", "{$name}_id"], $indexName); + } + + /** + * Add nullable columns for a polymorphic table using numeric IDs (incremental). + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function nullableNumericMorphs($name, $indexName = null) + { + $this->string("{$name}_type")->nullable(); + + $this->unsignedBigInteger("{$name}_id")->nullable(); + + $this->index(["{$name}_type", "{$name}_id"], $indexName); + } + + /** + * Add the proper columns for a polymorphic table using UUIDs. + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function uuidMorphs($name, $indexName = null) + { + $this->string("{$name}_type"); + + $this->uuid("{$name}_id"); + + $this->index(["{$name}_type", "{$name}_id"], $indexName); + } + + /** + * Add nullable columns for a polymorphic table using UUIDs. + * + * @param string $name + * @param string|null $indexName + * @return void + */ + public function nullableUuidMorphs($name, $indexName = null) + { + $this->string("{$name}_type")->nullable(); + + $this->uuid("{$name}_id")->nullable(); + + $this->index(["{$name}_type", "{$name}_id"], $indexName); + } + + /** + * Adds the `remember_token` column to the table. + * + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function rememberToken() + { + return $this->string('remember_token', 100)->nullable(); + } + + /** + * Add a new index command to the blueprint. + * + * @param string $type + * @param string|array $columns + * @param string $index + * @param string|null $algorithm + * @return \Illuminate\Support\Fluent + */ + protected function indexCommand($type, $columns, $index, $algorithm = null) + { + $columns = (array) $columns; + + // If no name was specified for this index, we will create one using a basic + // convention of the table name, followed by the columns, followed by an + // index type, such as primary or index, which makes the index unique. + $index = $index ?: $this->createIndexName($type, $columns); + + return $this->addCommand( + $type, compact('index', 'columns', 'algorithm') + ); + } + + /** + * Create a new drop index command on the blueprint. + * + * @param string $command + * @param string $type + * @param string|array $index + * @return \Illuminate\Support\Fluent + */ + protected function dropIndexCommand($command, $type, $index) + { + $columns = []; + + // If the given "index" is actually an array of columns, the developer means + // to drop an index merely by specifying the columns involved without the + // conventional name, so we will build the index name from the columns. + if (is_array($index)) { + $index = $this->createIndexName($type, $columns = $index); + } + + return $this->indexCommand($command, $columns, $index); + } + + /** + * Create a default index name for the table. + * + * @param string $type + * @param array $columns + * @return string + */ + protected function createIndexName($type, array $columns) + { + $index = strtolower($this->prefix.$this->table.'_'.implode('_', $columns).'_'.$type); + + return str_replace(['-', '.'], '_', $index); + } + + /** + * Add a new column to the blueprint. + * + * @param string $type + * @param string $name + * @param array $parameters + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + public function addColumn($type, $name, array $parameters = []) + { + return $this->addColumnDefinition(new ColumnDefinition( + array_merge(compact('type', 'name'), $parameters) + )); + } + + /** + * Add a new column definition to the blueprint. + * + * @param \Illuminate\Database\Schema\ColumnDefinition $definition + * @return \Illuminate\Database\Schema\ColumnDefinition + */ + protected function addColumnDefinition($definition) + { + $this->columns[] = $definition; + + if ($this->after) { + $definition->after($this->after); + + $this->after = $definition->name; + } + + return $definition; + } + + /** + * Add the columns from the callback after the given column. + * + * @param string $column + * @param \Closure $callback + * @return void + */ + public function after($column, Closure $callback) + { + $this->after = $column; + + $callback($this); + + $this->after = null; + } + + /** + * Remove a column from the schema blueprint. + * + * @param string $name + * @return $this + */ + public function removeColumn($name) + { + $this->columns = array_values(array_filter($this->columns, function ($c) use ($name) { + return $c['name'] != $name; + })); + + return $this; + } + + /** + * Add a new command to the blueprint. + * + * @param string $name + * @param array $parameters + * @return \Illuminate\Support\Fluent + */ + protected function addCommand($name, array $parameters = []) + { + $this->commands[] = $command = $this->createCommand($name, $parameters); + + return $command; + } + + /** + * Create a new Fluent command. + * + * @param string $name + * @param array $parameters + * @return \Illuminate\Support\Fluent + */ + protected function createCommand($name, array $parameters = []) + { + return new Fluent(array_merge(compact('name'), $parameters)); + } + + /** + * Get the table the blueprint describes. + * + * @return string + */ + public function getTable() + { + return $this->table; + } + + /** + * Get the columns on the blueprint. + * + * @return \Illuminate\Database\Schema\ColumnDefinition[] + */ + public function getColumns() + { + return $this->columns; + } + + /** + * Get the commands on the blueprint. + * + * @return \Illuminate\Support\Fluent[] + */ + public function getCommands() + { + return $this->commands; + } + + /** + * Get the columns on the blueprint that should be added. + * + * @return \Illuminate\Database\Schema\ColumnDefinition[] + */ + public function getAddedColumns() + { + return array_filter($this->columns, function ($column) { + return ! $column->change; + }); + } + + /** + * Get the columns on the blueprint that should be changed. + * + * @return \Illuminate\Database\Schema\ColumnDefinition[] + */ + public function getChangedColumns() + { + return array_filter($this->columns, function ($column) { + return (bool) $column->change; + }); + } + + /** + * Determine if the blueprint has auto-increment columns. + * + * @return bool + */ + public function hasAutoIncrementColumn() + { + return ! is_null(collect($this->getAddedColumns())->first(function ($column) { + return $column->autoIncrement === true; + })); + } + + /** + * Get the auto-increment column starting values. + * + * @return array + */ + public function autoIncrementingStartingValues() + { + if (! $this->hasAutoIncrementColumn()) { + return []; + } + + return collect($this->getAddedColumns())->mapWithKeys(function ($column) { + return $column->autoIncrement === true + ? [$column->name => $column->get('startingValue', $column->get('from'))] + : [$column->name => null]; + })->filter()->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php new file mode 100755 index 0000000..40f7888 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php @@ -0,0 +1,433 @@ +connection = $connection; + $this->grammar = $connection->getSchemaGrammar(); + } + + /** + * Set the default string length for migrations. + * + * @param int $length + * @return void + */ + public static function defaultStringLength($length) + { + static::$defaultStringLength = $length; + } + + /** + * Set the default morph key type for migrations. + * + * @param string $type + * @return void + * + * @throws \InvalidArgumentException + */ + public static function defaultMorphKeyType(string $type) + { + if (! in_array($type, ['int', 'uuid'])) { + throw new InvalidArgumentException("Morph key type must be 'int' or 'uuid'."); + } + + static::$defaultMorphKeyType = $type; + } + + /** + * Set the default morph key type for migrations to UUIDs. + * + * @return void + */ + public static function morphUsingUuids() + { + return static::defaultMorphKeyType('uuid'); + } + + /** + * Create a database in the schema. + * + * @param string $name + * @return bool + * + * @throws \LogicException + */ + public function createDatabase($name) + { + throw new LogicException('This database driver does not support creating databases.'); + } + + /** + * Drop a database from the schema if the database exists. + * + * @param string $name + * @return bool + * + * @throws \LogicException + */ + public function dropDatabaseIfExists($name) + { + throw new LogicException('This database driver does not support dropping databases.'); + } + + /** + * Determine if the given table exists. + * + * @param string $table + * @return bool + */ + public function hasTable($table) + { + $table = $this->connection->getTablePrefix().$table; + + return count($this->connection->selectFromWriteConnection( + $this->grammar->compileTableExists(), [$table] + )) > 0; + } + + /** + * Determine if the given table has a given column. + * + * @param string $table + * @param string $column + * @return bool + */ + public function hasColumn($table, $column) + { + return in_array( + strtolower($column), array_map('strtolower', $this->getColumnListing($table)) + ); + } + + /** + * Determine if the given table has given columns. + * + * @param string $table + * @param array $columns + * @return bool + */ + public function hasColumns($table, array $columns) + { + $tableColumns = array_map('strtolower', $this->getColumnListing($table)); + + foreach ($columns as $column) { + if (! in_array(strtolower($column), $tableColumns)) { + return false; + } + } + + return true; + } + + /** + * Get the data type for the given column name. + * + * @param string $table + * @param string $column + * @return string + */ + public function getColumnType($table, $column) + { + $table = $this->connection->getTablePrefix().$table; + + return $this->connection->getDoctrineColumn($table, $column)->getType()->getName(); + } + + /** + * Get the column listing for a given table. + * + * @param string $table + * @return array + */ + public function getColumnListing($table) + { + $results = $this->connection->selectFromWriteConnection($this->grammar->compileColumnListing( + $this->connection->getTablePrefix().$table + )); + + return $this->connection->getPostProcessor()->processColumnListing($results); + } + + /** + * Modify a table on the schema. + * + * @param string $table + * @param \Closure $callback + * @return void + */ + public function table($table, Closure $callback) + { + $this->build($this->createBlueprint($table, $callback)); + } + + /** + * Create a new table on the schema. + * + * @param string $table + * @param \Closure $callback + * @return void + */ + public function create($table, Closure $callback) + { + $this->build(tap($this->createBlueprint($table), function ($blueprint) use ($callback) { + $blueprint->create(); + + $callback($blueprint); + })); + } + + /** + * Drop a table from the schema. + * + * @param string $table + * @return void + */ + public function drop($table) + { + $this->build(tap($this->createBlueprint($table), function ($blueprint) { + $blueprint->drop(); + })); + } + + /** + * Drop a table from the schema if it exists. + * + * @param string $table + * @return void + */ + public function dropIfExists($table) + { + $this->build(tap($this->createBlueprint($table), function ($blueprint) { + $blueprint->dropIfExists(); + })); + } + + /** + * Drop columns from a table schema. + * + * @param string $table + * @param string|array $columns + * @return void + */ + public function dropColumns($table, $columns) + { + $this->table($table, function (Blueprint $blueprint) use ($columns) { + $blueprint->dropColumn($columns); + }); + } + + /** + * Drop all tables from the database. + * + * @return void + * + * @throws \LogicException + */ + public function dropAllTables() + { + throw new LogicException('This database driver does not support dropping all tables.'); + } + + /** + * Drop all views from the database. + * + * @return void + * + * @throws \LogicException + */ + public function dropAllViews() + { + throw new LogicException('This database driver does not support dropping all views.'); + } + + /** + * Drop all types from the database. + * + * @return void + * + * @throws \LogicException + */ + public function dropAllTypes() + { + throw new LogicException('This database driver does not support dropping all types.'); + } + + /** + * Get all of the table names for the database. + * + * @return void + * + * @throws \LogicException + */ + public function getAllTables() + { + throw new LogicException('This database driver does not support getting all tables.'); + } + + /** + * Rename a table on the schema. + * + * @param string $from + * @param string $to + * @return void + */ + public function rename($from, $to) + { + $this->build(tap($this->createBlueprint($from), function ($blueprint) use ($to) { + $blueprint->rename($to); + })); + } + + /** + * Enable foreign key constraints. + * + * @return bool + */ + public function enableForeignKeyConstraints() + { + return $this->connection->statement( + $this->grammar->compileEnableForeignKeyConstraints() + ); + } + + /** + * Disable foreign key constraints. + * + * @return bool + */ + public function disableForeignKeyConstraints() + { + return $this->connection->statement( + $this->grammar->compileDisableForeignKeyConstraints() + ); + } + + /** + * Execute the blueprint to build / modify the table. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return void + */ + protected function build(Blueprint $blueprint) + { + $blueprint->build($this->connection, $this->grammar); + } + + /** + * Create a new command set with a Closure. + * + * @param string $table + * @param \Closure|null $callback + * @return \Illuminate\Database\Schema\Blueprint + */ + protected function createBlueprint($table, Closure $callback = null) + { + $prefix = $this->connection->getConfig('prefix_indexes') + ? $this->connection->getConfig('prefix') + : ''; + + if (isset($this->resolver)) { + return call_user_func($this->resolver, $table, $callback, $prefix); + } + + return Container::getInstance()->make(Blueprint::class, compact('table', 'callback', 'prefix')); + } + + /** + * Register a custom Doctrine mapping type. + * + * @param string $class + * @param string $name + * @param string $type + * @return void + */ + public function registerCustomDoctrineType($class, $name, $type) + { + $this->connection->registerDoctrineType($class, $name, $type); + } + + /** + * Get the database connection instance. + * + * @return \Illuminate\Database\Connection + */ + public function getConnection() + { + return $this->connection; + } + + /** + * Set the database connection instance. + * + * @param \Illuminate\Database\Connection $connection + * @return $this + */ + public function setConnection(Connection $connection) + { + $this->connection = $connection; + + return $this; + } + + /** + * Set the Schema Blueprint resolver callback. + * + * @param \Closure $resolver + * @return void + */ + public function blueprintResolver(Closure $resolver) + { + $this->resolver = $resolver; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/ColumnDefinition.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/ColumnDefinition.php new file mode 100644 index 0000000..85f8ba3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/ColumnDefinition.php @@ -0,0 +1,38 @@ +blueprint = $blueprint; + } + + /** + * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table. + * + * @param string|null $table + * @param string $column + * @return \Illuminate\Database\Schema\ForeignKeyDefinition + */ + public function constrained($table = null, $column = 'id') + { + return $this->references($column)->on($table ?? Str::plural(Str::beforeLast($this->name, '_'.$column))); + } + + /** + * Specify which column this foreign ID references on another table. + * + * @param string $column + * @return \Illuminate\Database\Schema\ForeignKeyDefinition + */ + public function references($column) + { + return $this->blueprint->foreign($this->name)->references($column); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/ForeignKeyDefinition.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/ForeignKeyDefinition.php new file mode 100644 index 0000000..a03fcff --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/ForeignKeyDefinition.php @@ -0,0 +1,66 @@ +onUpdate('cascade'); + } + + /** + * Indicate that updates should be restricted. + * + * @return $this + */ + public function restrictOnUpdate() + { + return $this->onUpdate('restrict'); + } + + /** + * Indicate that deletes should cascade. + * + * @return $this + */ + public function cascadeOnDelete() + { + return $this->onDelete('cascade'); + } + + /** + * Indicate that deletes should be restricted. + * + * @return $this + */ + public function restrictOnDelete() + { + return $this->onDelete('restrict'); + } + + /** + * Indicate that deletes should set the foreign key value to null. + * + * @return $this + */ + public function nullOnDelete() + { + return $this->onDelete('set null'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php new file mode 100644 index 0000000..260935f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php @@ -0,0 +1,248 @@ +isDoctrineAvailable()) { + throw new RuntimeException(sprintf( + 'Changing columns for table "%s" requires Doctrine DBAL. Please install the doctrine/dbal package.', + $blueprint->getTable() + )); + } + + $schema = $connection->getDoctrineSchemaManager(); + $databasePlatform = $schema->getDatabasePlatform(); + $databasePlatform->registerDoctrineTypeMapping('enum', 'string'); + + $tableDiff = static::getChangedDiff( + $grammar, $blueprint, $schema + ); + + if ($tableDiff !== false) { + return (array) $databasePlatform->getAlterTableSQL($tableDiff); + } + + return []; + } + + /** + * Get the Doctrine table difference for the given changes. + * + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema + * @return \Doctrine\DBAL\Schema\TableDiff|bool + */ + protected static function getChangedDiff($grammar, Blueprint $blueprint, SchemaManager $schema) + { + $current = $schema->listTableDetails($grammar->getTablePrefix().$blueprint->getTable()); + + return (new Comparator)->diffTable( + $current, static::getTableWithColumnChanges($blueprint, $current) + ); + } + + /** + * Get a copy of the given Doctrine table after making the column changes. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Doctrine\DBAL\Schema\Table $table + * @return \Doctrine\DBAL\Schema\Table + */ + protected static function getTableWithColumnChanges(Blueprint $blueprint, Table $table) + { + $table = clone $table; + + foreach ($blueprint->getChangedColumns() as $fluent) { + $column = static::getDoctrineColumn($table, $fluent); + + // Here we will spin through each fluent column definition and map it to the proper + // Doctrine column definitions - which is necessary because Laravel and Doctrine + // use some different terminology for various column attributes on the tables. + foreach ($fluent->getAttributes() as $key => $value) { + if (! is_null($option = static::mapFluentOptionToDoctrine($key))) { + if (method_exists($column, $method = 'set'.ucfirst($option))) { + $column->{$method}(static::mapFluentValueToDoctrine($option, $value)); + continue; + } + + $column->setCustomSchemaOption($option, static::mapFluentValueToDoctrine($option, $value)); + } + } + } + + return $table; + } + + /** + * Get the Doctrine column instance for a column change. + * + * @param \Doctrine\DBAL\Schema\Table $table + * @param \Illuminate\Support\Fluent $fluent + * @return \Doctrine\DBAL\Schema\Column + */ + protected static function getDoctrineColumn(Table $table, Fluent $fluent) + { + return $table->changeColumn( + $fluent['name'], static::getDoctrineColumnChangeOptions($fluent) + )->getColumn($fluent['name']); + } + + /** + * Get the Doctrine column change options. + * + * @param \Illuminate\Support\Fluent $fluent + * @return array + */ + protected static function getDoctrineColumnChangeOptions(Fluent $fluent) + { + $options = ['type' => static::getDoctrineColumnType($fluent['type'])]; + + if (in_array($fluent['type'], ['text', 'mediumText', 'longText'])) { + $options['length'] = static::calculateDoctrineTextLength($fluent['type']); + } + + if (static::doesntNeedCharacterOptions($fluent['type'])) { + $options['customSchemaOptions'] = [ + 'collation' => '', + 'charset' => '', + ]; + } + + return $options; + } + + /** + * Get the doctrine column type. + * + * @param string $type + * @return \Doctrine\DBAL\Types\Type + */ + protected static function getDoctrineColumnType($type) + { + $type = strtolower($type); + + switch ($type) { + case 'biginteger': + $type = 'bigint'; + break; + case 'smallinteger': + $type = 'smallint'; + break; + case 'mediumtext': + case 'longtext': + $type = 'text'; + break; + case 'binary': + $type = 'blob'; + break; + case 'uuid': + $type = 'guid'; + break; + } + + return Type::getType($type); + } + + /** + * Calculate the proper column length to force the Doctrine text type. + * + * @param string $type + * @return int + */ + protected static function calculateDoctrineTextLength($type) + { + switch ($type) { + case 'mediumText': + return 65535 + 1; + case 'longText': + return 16777215 + 1; + default: + return 255 + 1; + } + } + + /** + * Determine if the given type does not need character / collation options. + * + * @param string $type + * @return bool + */ + protected static function doesntNeedCharacterOptions($type) + { + return in_array($type, [ + 'bigInteger', + 'binary', + 'boolean', + 'date', + 'dateTime', + 'decimal', + 'double', + 'float', + 'integer', + 'json', + 'mediumInteger', + 'smallInteger', + 'time', + 'tinyInteger', + ]); + } + + /** + * Get the matching Doctrine option for a given Fluent attribute name. + * + * @param string $attribute + * @return string|null + */ + protected static function mapFluentOptionToDoctrine($attribute) + { + switch ($attribute) { + case 'type': + case 'name': + return; + case 'nullable': + return 'notnull'; + case 'total': + return 'precision'; + case 'places': + return 'scale'; + default: + return $attribute; + } + } + + /** + * Get the matching Doctrine value for a given Fluent attribute. + * + * @param string $option + * @param mixed $value + * @return mixed + */ + protected static function mapFluentValueToDoctrine($option, $value) + { + return $option === 'notnull' ? ! $value : $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php new file mode 100755 index 0000000..7313576 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php @@ -0,0 +1,340 @@ +wrapTable($blueprint), + $this->wrap($command->index) + ); + + // Once we have the initial portion of the SQL statement we will add on the + // key name, table name, and referenced columns. These will complete the + // main portion of the SQL statement and this SQL will almost be done. + $sql .= sprintf('foreign key (%s) references %s (%s)', + $this->columnize($command->columns), + $this->wrapTable($command->on), + $this->columnize((array) $command->references) + ); + + // Once we have the basic foreign key creation statement constructed we can + // build out the syntax for what should happen on an update or delete of + // the affected columns, which will get something like "cascade", etc. + if (! is_null($command->onDelete)) { + $sql .= " on delete {$command->onDelete}"; + } + + if (! is_null($command->onUpdate)) { + $sql .= " on update {$command->onUpdate}"; + } + + return $sql; + } + + /** + * Compile the blueprint's column definitions. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return array + */ + protected function getColumns(Blueprint $blueprint) + { + $columns = []; + + foreach ($blueprint->getAddedColumns() as $column) { + // Each of the column types have their own compiler functions which are tasked + // with turning the column definition into its SQL format for this platform + // used by the connection. The column's modifiers are compiled and added. + $sql = $this->wrap($column).' '.$this->getType($column); + + $columns[] = $this->addModifiers($sql, $blueprint, $column); + } + + return $columns; + } + + /** + * Get the SQL for the column data type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function getType(Fluent $column) + { + return $this->{'type'.ucfirst($column->type)}($column); + } + + /** + * Create the column definition for a generated, computed column type. + * + * @param \Illuminate\Support\Fluent $column + * @return void + * + * @throws \RuntimeException + */ + protected function typeComputed(Fluent $column) + { + throw new RuntimeException('This database driver does not support the computed type.'); + } + + /** + * Add the column modifiers to the definition. + * + * @param string $sql + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function addModifiers($sql, Blueprint $blueprint, Fluent $column) + { + foreach ($this->modifiers as $modifier) { + if (method_exists($this, $method = "modify{$modifier}")) { + $sql .= $this->{$method}($blueprint, $column); + } + } + + return $sql; + } + + /** + * Get the primary key command if it exists on the blueprint. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param string $name + * @return \Illuminate\Support\Fluent|null + */ + protected function getCommandByName(Blueprint $blueprint, $name) + { + $commands = $this->getCommandsByName($blueprint, $name); + + if (count($commands) > 0) { + return reset($commands); + } + } + + /** + * Get all of the commands with a given name. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param string $name + * @return array + */ + protected function getCommandsByName(Blueprint $blueprint, $name) + { + return array_filter($blueprint->getCommands(), function ($value) use ($name) { + return $value->name == $name; + }); + } + + /** + * Add a prefix to an array of values. + * + * @param string $prefix + * @param array $values + * @return array + */ + public function prefixArray($prefix, array $values) + { + return array_map(function ($value) use ($prefix) { + return $prefix.' '.$value; + }, $values); + } + + /** + * Wrap a table in keyword identifiers. + * + * @param mixed $table + * @return string + */ + public function wrapTable($table) + { + return parent::wrapTable( + $table instanceof Blueprint ? $table->getTable() : $table + ); + } + + /** + * Wrap a value in keyword identifiers. + * + * @param \Illuminate\Database\Query\Expression|string $value + * @param bool $prefixAlias + * @return string + */ + public function wrap($value, $prefixAlias = false) + { + return parent::wrap( + $value instanceof Fluent ? $value->name : $value, $prefixAlias + ); + } + + /** + * Format a value so that it can be used in "default" clauses. + * + * @param mixed $value + * @return string + */ + protected function getDefaultValue($value) + { + if ($value instanceof Expression) { + return $value; + } + + return is_bool($value) + ? "'".(int) $value."'" + : "'".(string) $value."'"; + } + + /** + * Create an empty Doctrine DBAL TableDiff from the Blueprint. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema + * @return \Doctrine\DBAL\Schema\TableDiff + */ + public function getDoctrineTableDiff(Blueprint $blueprint, SchemaManager $schema) + { + $table = $this->getTablePrefix().$blueprint->getTable(); + + return tap(new TableDiff($table), function ($tableDiff) use ($schema, $table) { + $tableDiff->fromTable = $schema->listTableDetails($table); + }); + } + + /** + * Get the fluent commands for the grammar. + * + * @return array + */ + public function getFluentCommands() + { + return $this->fluentCommands; + } + + /** + * Check if this Grammar supports schema changes wrapped in a transaction. + * + * @return bool + */ + public function supportsSchemaTransactions() + { + return $this->transactions; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php new file mode 100755 index 0000000..1f64cf3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php @@ -0,0 +1,1153 @@ +wrapValue($name), + $this->wrapValue($connection->getConfig('charset')), + $this->wrapValue($connection->getConfig('collation')), + ); + } + + /** + * Compile a drop database if exists command. + * + * @param string $name + * @return string + */ + public function compileDropDatabaseIfExists($name) + { + return sprintf( + 'drop database if exists %s', + $this->wrapValue($name) + ); + } + + /** + * Compile the query to determine the list of tables. + * + * @return string + */ + public function compileTableExists() + { + return "select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'"; + } + + /** + * Compile the query to determine the list of columns. + * + * @return string + */ + public function compileColumnListing() + { + return 'select column_name as `column_name` from information_schema.columns where table_schema = ? and table_name = ?'; + } + + /** + * Compile a create table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @param \Illuminate\Database\Connection $connection + * @return array + */ + public function compileCreate(Blueprint $blueprint, Fluent $command, Connection $connection) + { + $sql = $this->compileCreateTable( + $blueprint, $command, $connection + ); + + // Once we have the primary SQL, we can add the encoding option to the SQL for + // the table. Then, we can check if a storage engine has been supplied for + // the table. If so, we will add the engine declaration to the SQL query. + $sql = $this->compileCreateEncoding( + $sql, $connection, $blueprint + ); + + // Finally, we will append the engine configuration onto this SQL statement as + // the final thing we do before returning this finished SQL. Once this gets + // added the query will be ready to execute against the real connections. + return array_values(array_filter(array_merge([$this->compileCreateEngine( + $sql, $connection, $blueprint + )], $this->compileAutoIncrementStartingValues($blueprint)))); + } + + /** + * Create the main create table clause. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @param \Illuminate\Database\Connection $connection + * @return array + */ + protected function compileCreateTable($blueprint, $command, $connection) + { + return trim(sprintf('%s table %s (%s)', + $blueprint->temporary ? 'create temporary' : 'create', + $this->wrapTable($blueprint), + implode(', ', $this->getColumns($blueprint)) + )); + } + + /** + * Append the character set specifications to a command. + * + * @param string $sql + * @param \Illuminate\Database\Connection $connection + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return string + */ + protected function compileCreateEncoding($sql, Connection $connection, Blueprint $blueprint) + { + // First we will set the character set if one has been set on either the create + // blueprint itself or on the root configuration for the connection that the + // table is being created on. We will add these to the create table query. + if (isset($blueprint->charset)) { + $sql .= ' default character set '.$blueprint->charset; + } elseif (! is_null($charset = $connection->getConfig('charset'))) { + $sql .= ' default character set '.$charset; + } + + // Next we will add the collation to the create table statement if one has been + // added to either this create table blueprint or the configuration for this + // connection that the query is targeting. We'll add it to this SQL query. + if (isset($blueprint->collation)) { + $sql .= " collate '{$blueprint->collation}'"; + } elseif (! is_null($collation = $connection->getConfig('collation'))) { + $sql .= " collate '{$collation}'"; + } + + return $sql; + } + + /** + * Append the engine specifications to a command. + * + * @param string $sql + * @param \Illuminate\Database\Connection $connection + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return string + */ + protected function compileCreateEngine($sql, Connection $connection, Blueprint $blueprint) + { + if (isset($blueprint->engine)) { + return $sql.' engine = '.$blueprint->engine; + } elseif (! is_null($engine = $connection->getConfig('engine'))) { + return $sql.' engine = '.$engine; + } + + return $sql; + } + + /** + * Compile an add column command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return array + */ + public function compileAdd(Blueprint $blueprint, Fluent $command) + { + $columns = $this->prefixArray('add', $this->getColumns($blueprint)); + + return array_values(array_merge( + ['alter table '.$this->wrapTable($blueprint).' '.implode(', ', $columns)], + $this->compileAutoIncrementStartingValues($blueprint) + )); + } + + /** + * Compile the auto-incrementing column starting values. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return array + */ + public function compileAutoIncrementStartingValues(Blueprint $blueprint) + { + return collect($blueprint->autoIncrementingStartingValues())->map(function ($value, $column) use ($blueprint) { + return 'alter table '.$this->wrapTable($blueprint->getTable()).' auto_increment = '.$value; + })->all(); + } + + /** + * Compile a primary key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compilePrimary(Blueprint $blueprint, Fluent $command) + { + $command->name(null); + + return $this->compileKey($blueprint, $command, 'primary key'); + } + + /** + * Compile a unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileUnique(Blueprint $blueprint, Fluent $command) + { + return $this->compileKey($blueprint, $command, 'unique'); + } + + /** + * Compile a plain index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileIndex(Blueprint $blueprint, Fluent $command) + { + return $this->compileKey($blueprint, $command, 'index'); + } + + /** + * Compile a fulltext index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileFullText(Blueprint $blueprint, Fluent $command) + { + return $this->compileKey($blueprint, $command, 'fulltext'); + } + + /** + * Compile a spatial index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileSpatialIndex(Blueprint $blueprint, Fluent $command) + { + return $this->compileKey($blueprint, $command, 'spatial index'); + } + + /** + * Compile an index creation command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @param string $type + * @return string + */ + protected function compileKey(Blueprint $blueprint, Fluent $command, $type) + { + return sprintf('alter table %s add %s %s%s(%s)', + $this->wrapTable($blueprint), + $type, + $this->wrap($command->index), + $command->algorithm ? ' using '.$command->algorithm : '', + $this->columnize($command->columns) + ); + } + + /** + * Compile a drop table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDrop(Blueprint $blueprint, Fluent $command) + { + return 'drop table '.$this->wrapTable($blueprint); + } + + /** + * Compile a drop table (if exists) command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIfExists(Blueprint $blueprint, Fluent $command) + { + return 'drop table if exists '.$this->wrapTable($blueprint); + } + + /** + * Compile a drop column command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropColumn(Blueprint $blueprint, Fluent $command) + { + $columns = $this->prefixArray('drop', $this->wrapArray($command->columns)); + + return 'alter table '.$this->wrapTable($blueprint).' '.implode(', ', $columns); + } + + /** + * Compile a drop primary key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropPrimary(Blueprint $blueprint, Fluent $command) + { + return 'alter table '.$this->wrapTable($blueprint).' drop primary key'; + } + + /** + * Compile a drop unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropUnique(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop index {$index}"; + } + + /** + * Compile a drop index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIndex(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop index {$index}"; + } + + /** + * Compile a drop fulltext index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropFullText(Blueprint $blueprint, Fluent $command) + { + return $this->compileDropIndex($blueprint, $command); + } + + /** + * Compile a drop spatial index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropSpatialIndex(Blueprint $blueprint, Fluent $command) + { + return $this->compileDropIndex($blueprint, $command); + } + + /** + * Compile a drop foreign key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropForeign(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop foreign key {$index}"; + } + + /** + * Compile a rename table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRename(Blueprint $blueprint, Fluent $command) + { + $from = $this->wrapTable($blueprint); + + return "rename table {$from} to ".$this->wrapTable($command->to); + } + + /** + * Compile a rename index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRenameIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf('alter table %s rename index %s to %s', + $this->wrapTable($blueprint), + $this->wrap($command->from), + $this->wrap($command->to) + ); + } + + /** + * Compile the SQL needed to drop all tables. + * + * @param array $tables + * @return string + */ + public function compileDropAllTables($tables) + { + return 'drop table '.implode(',', $this->wrapArray($tables)); + } + + /** + * Compile the SQL needed to drop all views. + * + * @param array $views + * @return string + */ + public function compileDropAllViews($views) + { + return 'drop view '.implode(',', $this->wrapArray($views)); + } + + /** + * Compile the SQL needed to retrieve all table names. + * + * @return string + */ + public function compileGetAllTables() + { + return 'SHOW FULL TABLES WHERE table_type = \'BASE TABLE\''; + } + + /** + * Compile the SQL needed to retrieve all view names. + * + * @return string + */ + public function compileGetAllViews() + { + return 'SHOW FULL TABLES WHERE table_type = \'VIEW\''; + } + + /** + * Compile the command to enable foreign key constraints. + * + * @return string + */ + public function compileEnableForeignKeyConstraints() + { + return 'SET FOREIGN_KEY_CHECKS=1;'; + } + + /** + * Compile the command to disable foreign key constraints. + * + * @return string + */ + public function compileDisableForeignKeyConstraints() + { + return 'SET FOREIGN_KEY_CHECKS=0;'; + } + + /** + * Create the column definition for a char type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeChar(Fluent $column) + { + return "char({$column->length})"; + } + + /** + * Create the column definition for a string type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeString(Fluent $column) + { + return "varchar({$column->length})"; + } + + /** + * Create the column definition for a tiny text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyText(Fluent $column) + { + return 'tinytext'; + } + + /** + * Create the column definition for a text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a medium text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumText(Fluent $column) + { + return 'mediumtext'; + } + + /** + * Create the column definition for a long text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeLongText(Fluent $column) + { + return 'longtext'; + } + + /** + * Create the column definition for a big integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBigInteger(Fluent $column) + { + return 'bigint'; + } + + /** + * Create the column definition for an integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeInteger(Fluent $column) + { + return 'int'; + } + + /** + * Create the column definition for a medium integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumInteger(Fluent $column) + { + return 'mediumint'; + } + + /** + * Create the column definition for a tiny integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyInteger(Fluent $column) + { + return 'tinyint'; + } + + /** + * Create the column definition for a small integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeSmallInteger(Fluent $column) + { + return 'smallint'; + } + + /** + * Create the column definition for a float type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeFloat(Fluent $column) + { + return $this->typeDouble($column); + } + + /** + * Create the column definition for a double type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDouble(Fluent $column) + { + if ($column->total && $column->places) { + return "double({$column->total}, {$column->places})"; + } + + return 'double'; + } + + /** + * Create the column definition for a decimal type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDecimal(Fluent $column) + { + return "decimal({$column->total}, {$column->places})"; + } + + /** + * Create the column definition for a boolean type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBoolean(Fluent $column) + { + return 'tinyint(1)'; + } + + /** + * Create the column definition for an enumeration type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeEnum(Fluent $column) + { + return sprintf('enum(%s)', $this->quoteString($column->allowed)); + } + + /** + * Create the column definition for a set enumeration type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeSet(Fluent $column) + { + return sprintf('set(%s)', $this->quoteString($column->allowed)); + } + + /** + * Create the column definition for a json type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJson(Fluent $column) + { + return 'json'; + } + + /** + * Create the column definition for a jsonb type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJsonb(Fluent $column) + { + return 'json'; + } + + /** + * Create the column definition for a date type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDate(Fluent $column) + { + return 'date'; + } + + /** + * Create the column definition for a date-time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTime(Fluent $column) + { + $columnType = $column->precision ? "datetime($column->precision)" : 'datetime'; + + $current = $column->precision ? "CURRENT_TIMESTAMP($column->precision)" : 'CURRENT_TIMESTAMP'; + + $columnType = $column->useCurrent ? "$columnType default $current" : $columnType; + + return $column->useCurrentOnUpdate ? "$columnType on update $current" : $columnType; + } + + /** + * Create the column definition for a date-time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTimeTz(Fluent $column) + { + return $this->typeDateTime($column); + } + + /** + * Create the column definition for a time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTime(Fluent $column) + { + return $column->precision ? "time($column->precision)" : 'time'; + } + + /** + * Create the column definition for a time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimeTz(Fluent $column) + { + return $this->typeTime($column); + } + + /** + * Create the column definition for a timestamp type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestamp(Fluent $column) + { + $columnType = $column->precision ? "timestamp($column->precision)" : 'timestamp'; + + $current = $column->precision ? "CURRENT_TIMESTAMP($column->precision)" : 'CURRENT_TIMESTAMP'; + + $columnType = $column->useCurrent ? "$columnType default $current" : $columnType; + + return $column->useCurrentOnUpdate ? "$columnType on update $current" : $columnType; + } + + /** + * Create the column definition for a timestamp (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestampTz(Fluent $column) + { + return $this->typeTimestamp($column); + } + + /** + * Create the column definition for a year type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeYear(Fluent $column) + { + return 'year'; + } + + /** + * Create the column definition for a binary type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBinary(Fluent $column) + { + return 'blob'; + } + + /** + * Create the column definition for a uuid type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeUuid(Fluent $column) + { + return 'char(36)'; + } + + /** + * Create the column definition for an IP address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeIpAddress(Fluent $column) + { + return 'varchar(45)'; + } + + /** + * Create the column definition for a MAC address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMacAddress(Fluent $column) + { + return 'varchar(17)'; + } + + /** + * Create the column definition for a spatial Geometry type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeGeometry(Fluent $column) + { + return 'geometry'; + } + + /** + * Create the column definition for a spatial Point type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typePoint(Fluent $column) + { + return 'point'; + } + + /** + * Create the column definition for a spatial LineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeLineString(Fluent $column) + { + return 'linestring'; + } + + /** + * Create the column definition for a spatial Polygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typePolygon(Fluent $column) + { + return 'polygon'; + } + + /** + * Create the column definition for a spatial GeometryCollection type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeGeometryCollection(Fluent $column) + { + return 'geometrycollection'; + } + + /** + * Create the column definition for a spatial MultiPoint type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiPoint(Fluent $column) + { + return 'multipoint'; + } + + /** + * Create the column definition for a spatial MultiLineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiLineString(Fluent $column) + { + return 'multilinestring'; + } + + /** + * Create the column definition for a spatial MultiPolygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiPolygon(Fluent $column) + { + return 'multipolygon'; + } + + /** + * Create the column definition for a generated, computed column type. + * + * @param \Illuminate\Support\Fluent $column + * @return void + * + * @throws \RuntimeException + */ + protected function typeComputed(Fluent $column) + { + throw new RuntimeException('This database driver requires a type, see the virtualAs / storedAs modifiers.'); + } + + /** + * Get the SQL for a generated virtual column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->virtualAs)) { + return " as ({$column->virtualAs})"; + } + } + + /** + * Get the SQL for a generated stored column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyStoredAs(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->storedAs)) { + return " as ({$column->storedAs}) stored"; + } + } + + /** + * Get the SQL for an unsigned column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyUnsigned(Blueprint $blueprint, Fluent $column) + { + if ($column->unsigned) { + return ' unsigned'; + } + } + + /** + * Get the SQL for a character set column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyCharset(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->charset)) { + return ' character set '.$column->charset; + } + } + + /** + * Get the SQL for a collation column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyCollate(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->collation)) { + return " collate '{$column->collation}'"; + } + } + + /** + * Get the SQL for a nullable column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyNullable(Blueprint $blueprint, Fluent $column) + { + if (is_null($column->virtualAs) && is_null($column->storedAs)) { + return $column->nullable ? ' null' : ' not null'; + } + + if ($column->nullable === false) { + return ' not null'; + } + } + + /** + * Get the SQL for an invisible column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyInvisible(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->invisible)) { + return ' invisible'; + } + } + + /** + * Get the SQL for a default column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyDefault(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->default)) { + return ' default '.$this->getDefaultValue($column->default); + } + } + + /** + * Get the SQL for an auto-increment column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyIncrement(Blueprint $blueprint, Fluent $column) + { + if (in_array($column->type, $this->serials) && $column->autoIncrement) { + return ' auto_increment primary key'; + } + } + + /** + * Get the SQL for a "first" column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyFirst(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->first)) { + return ' first'; + } + } + + /** + * Get the SQL for an "after" column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyAfter(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->after)) { + return ' after '.$this->wrap($column->after); + } + } + + /** + * Get the SQL for a "comment" column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyComment(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->comment)) { + return " comment '".addslashes($column->comment)."'"; + } + } + + /** + * Get the SQL for a SRID column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifySrid(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->srid) && is_int($column->srid) && $column->srid > 0) { + return ' srid '.$column->srid; + } + } + + /** + * Wrap a single string in keyword identifiers. + * + * @param string $value + * @return string + */ + protected function wrapValue($value) + { + if ($value !== '*') { + return '`'.str_replace('`', '``', $value).'`'; + } + + return $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php new file mode 100755 index 0000000..27490bc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php @@ -0,0 +1,1073 @@ +wrapValue($name), + $this->wrapValue($connection->getConfig('charset')), + ); + } + + /** + * Compile a drop database if exists command. + * + * @param string $name + * @return string + */ + public function compileDropDatabaseIfExists($name) + { + return sprintf( + 'drop database if exists %s', + $this->wrapValue($name) + ); + } + + /** + * Compile the query to determine if a table exists. + * + * @return string + */ + public function compileTableExists() + { + return "select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'"; + } + + /** + * Compile the query to determine the list of columns. + * + * @return string + */ + public function compileColumnListing() + { + return 'select column_name from information_schema.columns where table_schema = ? and table_name = ?'; + } + + /** + * Compile a create table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return array + */ + public function compileCreate(Blueprint $blueprint, Fluent $command) + { + return array_values(array_filter(array_merge([sprintf('%s table %s (%s)', + $blueprint->temporary ? 'create temporary' : 'create', + $this->wrapTable($blueprint), + implode(', ', $this->getColumns($blueprint)) + )], $this->compileAutoIncrementStartingValues($blueprint)))); + } + + /** + * Compile a column addition command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileAdd(Blueprint $blueprint, Fluent $command) + { + return array_values(array_filter(array_merge([sprintf('alter table %s %s', + $this->wrapTable($blueprint), + implode(', ', $this->prefixArray('add column', $this->getColumns($blueprint))) + )], $this->compileAutoIncrementStartingValues($blueprint)))); + } + + /** + * Compile the auto-incrementing column starting values. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return array + */ + public function compileAutoIncrementStartingValues(Blueprint $blueprint) + { + return collect($blueprint->autoIncrementingStartingValues())->map(function ($value, $column) use ($blueprint) { + return 'alter sequence '.$blueprint->getTable().'_'.$column.'_seq restart with '.$value; + })->all(); + } + + /** + * Compile a primary key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compilePrimary(Blueprint $blueprint, Fluent $command) + { + $columns = $this->columnize($command->columns); + + return 'alter table '.$this->wrapTable($blueprint)." add primary key ({$columns})"; + } + + /** + * Compile a unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileUnique(Blueprint $blueprint, Fluent $command) + { + return sprintf('alter table %s add constraint %s unique (%s)', + $this->wrapTable($blueprint), + $this->wrap($command->index), + $this->columnize($command->columns) + ); + } + + /** + * Compile a plain index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf('create index %s on %s%s (%s)', + $this->wrap($command->index), + $this->wrapTable($blueprint), + $command->algorithm ? ' using '.$command->algorithm : '', + $this->columnize($command->columns) + ); + } + + /** + * Compile a fulltext index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + * + * @throws \RuntimeException + */ + public function compileFulltext(Blueprint $blueprint, Fluent $command) + { + $language = $command->language ?: 'english'; + + $columns = array_map(function ($column) use ($language) { + return "to_tsvector({$this->quoteString($language)}, {$this->wrap($column)})"; + }, $command->columns); + + return sprintf('create index %s on %s using gin ((%s))', + $this->wrap($command->index), + $this->wrapTable($blueprint), + implode(' || ', $columns) + ); + } + + /** + * Compile a spatial index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileSpatialIndex(Blueprint $blueprint, Fluent $command) + { + $command->algorithm = 'gist'; + + return $this->compileIndex($blueprint, $command); + } + + /** + * Compile a foreign key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileForeign(Blueprint $blueprint, Fluent $command) + { + $sql = parent::compileForeign($blueprint, $command); + + if (! is_null($command->deferrable)) { + $sql .= $command->deferrable ? ' deferrable' : ' not deferrable'; + } + + if ($command->deferrable && ! is_null($command->initiallyImmediate)) { + $sql .= $command->initiallyImmediate ? ' initially immediate' : ' initially deferred'; + } + + if (! is_null($command->notValid)) { + $sql .= ' not valid'; + } + + return $sql; + } + + /** + * Compile a drop table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDrop(Blueprint $blueprint, Fluent $command) + { + return 'drop table '.$this->wrapTable($blueprint); + } + + /** + * Compile a drop table (if exists) command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIfExists(Blueprint $blueprint, Fluent $command) + { + return 'drop table if exists '.$this->wrapTable($blueprint); + } + + /** + * Compile the SQL needed to drop all tables. + * + * @param array $tables + * @return string + */ + public function compileDropAllTables($tables) + { + return 'drop table "'.implode('","', $tables).'" cascade'; + } + + /** + * Compile the SQL needed to drop all views. + * + * @param array $views + * @return string + */ + public function compileDropAllViews($views) + { + return 'drop view "'.implode('","', $views).'" cascade'; + } + + /** + * Compile the SQL needed to drop all types. + * + * @param array $types + * @return string + */ + public function compileDropAllTypes($types) + { + return 'drop type "'.implode('","', $types).'" cascade'; + } + + /** + * Compile the SQL needed to retrieve all table names. + * + * @param string|array $schema + * @return string + */ + public function compileGetAllTables($schema) + { + return "select tablename from pg_catalog.pg_tables where schemaname in ('".implode("','", (array) $schema)."')"; + } + + /** + * Compile the SQL needed to retrieve all view names. + * + * @param string|array $schema + * @return string + */ + public function compileGetAllViews($schema) + { + return "select viewname from pg_catalog.pg_views where schemaname in ('".implode("','", (array) $schema)."')"; + } + + /** + * Compile the SQL needed to retrieve all type names. + * + * @return string + */ + public function compileGetAllTypes() + { + return 'select distinct pg_type.typname from pg_type inner join pg_enum on pg_enum.enumtypid = pg_type.oid'; + } + + /** + * Compile a drop column command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropColumn(Blueprint $blueprint, Fluent $command) + { + $columns = $this->prefixArray('drop column', $this->wrapArray($command->columns)); + + return 'alter table '.$this->wrapTable($blueprint).' '.implode(', ', $columns); + } + + /** + * Compile a drop primary key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropPrimary(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap("{$blueprint->getTable()}_pkey"); + + return 'alter table '.$this->wrapTable($blueprint)." drop constraint {$index}"; + } + + /** + * Compile a drop unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropUnique(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop constraint {$index}"; + } + + /** + * Compile a drop index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIndex(Blueprint $blueprint, Fluent $command) + { + return "drop index {$this->wrap($command->index)}"; + } + + /** + * Compile a drop fulltext index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropFullText(Blueprint $blueprint, Fluent $command) + { + return $this->compileDropIndex($blueprint, $command); + } + + /** + * Compile a drop spatial index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropSpatialIndex(Blueprint $blueprint, Fluent $command) + { + return $this->compileDropIndex($blueprint, $command); + } + + /** + * Compile a drop foreign key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropForeign(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop constraint {$index}"; + } + + /** + * Compile a rename table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRename(Blueprint $blueprint, Fluent $command) + { + $from = $this->wrapTable($blueprint); + + return "alter table {$from} rename to ".$this->wrapTable($command->to); + } + + /** + * Compile a rename index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRenameIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf('alter index %s rename to %s', + $this->wrap($command->from), + $this->wrap($command->to) + ); + } + + /** + * Compile the command to enable foreign key constraints. + * + * @return string + */ + public function compileEnableForeignKeyConstraints() + { + return 'SET CONSTRAINTS ALL IMMEDIATE;'; + } + + /** + * Compile the command to disable foreign key constraints. + * + * @return string + */ + public function compileDisableForeignKeyConstraints() + { + return 'SET CONSTRAINTS ALL DEFERRED;'; + } + + /** + * Compile a comment command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileComment(Blueprint $blueprint, Fluent $command) + { + return sprintf('comment on column %s.%s is %s', + $this->wrapTable($blueprint), + $this->wrap($command->column->name), + "'".str_replace("'", "''", $command->value)."'" + ); + } + + /** + * Create the column definition for a char type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeChar(Fluent $column) + { + return "char({$column->length})"; + } + + /** + * Create the column definition for a string type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeString(Fluent $column) + { + return "varchar({$column->length})"; + } + + /** + * Create the column definition for a tiny text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyText(Fluent $column) + { + return 'varchar(255)'; + } + + /** + * Create the column definition for a text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a medium text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a long text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeLongText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for an integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeInteger(Fluent $column) + { + return $this->generatableColumn('integer', $column); + } + + /** + * Create the column definition for a big integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBigInteger(Fluent $column) + { + return $this->generatableColumn('bigint', $column); + } + + /** + * Create the column definition for a medium integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumInteger(Fluent $column) + { + return $this->generatableColumn('integer', $column); + } + + /** + * Create the column definition for a tiny integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyInteger(Fluent $column) + { + return $this->generatableColumn('smallint', $column); + } + + /** + * Create the column definition for a small integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeSmallInteger(Fluent $column) + { + return $this->generatableColumn('smallint', $column); + } + + /** + * Create the column definition for a generatable column. + * + * @param string $type + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function generatableColumn($type, Fluent $column) + { + if (! $column->autoIncrement && is_null($column->generatedAs)) { + return $type; + } + + if ($column->autoIncrement && is_null($column->generatedAs)) { + return with([ + 'integer' => 'serial', + 'bigint' => 'bigserial', + 'smallint' => 'smallserial', + ])[$type]; + } + + $options = ''; + + if (! is_bool($column->generatedAs) && ! empty($column->generatedAs)) { + $options = sprintf(' (%s)', $column->generatedAs); + } + + return sprintf( + '%s generated %s as identity%s', + $type, + $column->always ? 'always' : 'by default', + $options + ); + } + + /** + * Create the column definition for a float type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeFloat(Fluent $column) + { + return $this->typeDouble($column); + } + + /** + * Create the column definition for a double type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDouble(Fluent $column) + { + return 'double precision'; + } + + /** + * Create the column definition for a real type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeReal(Fluent $column) + { + return 'real'; + } + + /** + * Create the column definition for a decimal type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDecimal(Fluent $column) + { + return "decimal({$column->total}, {$column->places})"; + } + + /** + * Create the column definition for a boolean type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBoolean(Fluent $column) + { + return 'boolean'; + } + + /** + * Create the column definition for an enumeration type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeEnum(Fluent $column) + { + return sprintf( + 'varchar(255) check ("%s" in (%s))', + $column->name, + $this->quoteString($column->allowed) + ); + } + + /** + * Create the column definition for a json type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJson(Fluent $column) + { + return 'json'; + } + + /** + * Create the column definition for a jsonb type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJsonb(Fluent $column) + { + return 'jsonb'; + } + + /** + * Create the column definition for a date type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDate(Fluent $column) + { + return 'date'; + } + + /** + * Create the column definition for a date-time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTime(Fluent $column) + { + return $this->typeTimestamp($column); + } + + /** + * Create the column definition for a date-time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTimeTz(Fluent $column) + { + return $this->typeTimestampTz($column); + } + + /** + * Create the column definition for a time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTime(Fluent $column) + { + return 'time'.(is_null($column->precision) ? '' : "($column->precision)").' without time zone'; + } + + /** + * Create the column definition for a time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimeTz(Fluent $column) + { + return 'time'.(is_null($column->precision) ? '' : "($column->precision)").' with time zone'; + } + + /** + * Create the column definition for a timestamp type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestamp(Fluent $column) + { + $columnType = 'timestamp'.(is_null($column->precision) ? '' : "($column->precision)").' without time zone'; + + return $column->useCurrent ? "$columnType default CURRENT_TIMESTAMP" : $columnType; + } + + /** + * Create the column definition for a timestamp (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestampTz(Fluent $column) + { + $columnType = 'timestamp'.(is_null($column->precision) ? '' : "($column->precision)").' with time zone'; + + return $column->useCurrent ? "$columnType default CURRENT_TIMESTAMP" : $columnType; + } + + /** + * Create the column definition for a year type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeYear(Fluent $column) + { + return $this->typeInteger($column); + } + + /** + * Create the column definition for a binary type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBinary(Fluent $column) + { + return 'bytea'; + } + + /** + * Create the column definition for a uuid type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeUuid(Fluent $column) + { + return 'uuid'; + } + + /** + * Create the column definition for an IP address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeIpAddress(Fluent $column) + { + return 'inet'; + } + + /** + * Create the column definition for a MAC address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMacAddress(Fluent $column) + { + return 'macaddr'; + } + + /** + * Create the column definition for a spatial Geometry type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeGeometry(Fluent $column) + { + return $this->formatPostGisType('geometry', $column); + } + + /** + * Create the column definition for a spatial Point type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typePoint(Fluent $column) + { + return $this->formatPostGisType('point', $column); + } + + /** + * Create the column definition for a spatial LineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeLineString(Fluent $column) + { + return $this->formatPostGisType('linestring', $column); + } + + /** + * Create the column definition for a spatial Polygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typePolygon(Fluent $column) + { + return $this->formatPostGisType('polygon', $column); + } + + /** + * Create the column definition for a spatial GeometryCollection type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeGeometryCollection(Fluent $column) + { + return $this->formatPostGisType('geometrycollection', $column); + } + + /** + * Create the column definition for a spatial MultiPoint type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMultiPoint(Fluent $column) + { + return $this->formatPostGisType('multipoint', $column); + } + + /** + * Create the column definition for a spatial MultiLineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiLineString(Fluent $column) + { + return $this->formatPostGisType('multilinestring', $column); + } + + /** + * Create the column definition for a spatial MultiPolygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMultiPolygon(Fluent $column) + { + return $this->formatPostGisType('multipolygon', $column); + } + + /** + * Create the column definition for a spatial MultiPolygonZ type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMultiPolygonZ(Fluent $column) + { + return $this->formatPostGisType('multipolygonz', $column); + } + + /** + * Format the column definition for a PostGIS spatial type. + * + * @param string $type + * @param \Illuminate\Support\Fluent $column + * @return string + */ + private function formatPostGisType($type, Fluent $column) + { + if ($column->isGeometry === null) { + return sprintf('geography(%s, %s)', $type, $column->projection ?? '4326'); + } + + if ($column->projection !== null) { + return sprintf('geometry(%s, %s)', $type, $column->projection); + } + + return "geometry({$type})"; + } + + /** + * Get the SQL for a collation column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyCollate(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->collation)) { + return ' collate '.$this->wrapValue($column->collation); + } + } + + /** + * Get the SQL for a nullable column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyNullable(Blueprint $blueprint, Fluent $column) + { + return $column->nullable ? ' null' : ' not null'; + } + + /** + * Get the SQL for a default column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyDefault(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->default)) { + return ' default '.$this->getDefaultValue($column->default); + } + } + + /** + * Get the SQL for an auto-increment column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyIncrement(Blueprint $blueprint, Fluent $column) + { + if ((in_array($column->type, $this->serials) || ($column->generatedAs !== null)) && $column->autoIncrement) { + return ' primary key'; + } + } + + /** + * Get the SQL for a generated virtual column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column) + { + if ($column->virtualAs !== null) { + return " generated always as ({$column->virtualAs})"; + } + } + + /** + * Get the SQL for a generated stored column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyStoredAs(Blueprint $blueprint, Fluent $column) + { + if ($column->storedAs !== null) { + return " generated always as ({$column->storedAs}) stored"; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/RenameColumn.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/RenameColumn.php new file mode 100644 index 0000000..0db0c50 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/RenameColumn.php @@ -0,0 +1,84 @@ +getDoctrineSchemaManager(); + $databasePlatform = $schema->getDatabasePlatform(); + $databasePlatform->registerDoctrineTypeMapping('enum', 'string'); + + $column = $connection->getDoctrineColumn( + $grammar->getTablePrefix().$blueprint->getTable(), $command->from + ); + + return (array) $databasePlatform->getAlterTableSQL(static::getRenamedDiff( + $grammar, $blueprint, $command, $column, $schema + )); + } + + /** + * Get a new column instance with the new column name. + * + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @param \Doctrine\DBAL\Schema\Column $column + * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema + * @return \Doctrine\DBAL\Schema\TableDiff + */ + protected static function getRenamedDiff(Grammar $grammar, Blueprint $blueprint, Fluent $command, Column $column, SchemaManager $schema) + { + return static::setRenamedColumns( + $grammar->getDoctrineTableDiff($blueprint, $schema), $command, $column + ); + } + + /** + * Set the renamed columns on the table diff. + * + * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff + * @param \Illuminate\Support\Fluent $command + * @param \Doctrine\DBAL\Schema\Column $column + * @return \Doctrine\DBAL\Schema\TableDiff + */ + protected static function setRenamedColumns(TableDiff $tableDiff, Fluent $command, Column $column) + { + $tableDiff->renamedColumns = [ + $command->from => new Column($command->to, $column->getType(), self::getWritableColumnOptions($column)), + ]; + + return $tableDiff; + } + + /** + * Get the writable column options. + * + * @param \Doctrine\DBAL\Schema\Column $column + * @return array + */ + private static function getWritableColumnOptions(Column $column) + { + return array_filter($column->toArray(), function (string $name) use ($column) { + return method_exists($column, 'set'.$name); + }, ARRAY_FILTER_USE_KEY); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php new file mode 100755 index 0000000..e699ee6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php @@ -0,0 +1,925 @@ +wrap(str_replace('.', '__', $table)).')'; + } + + /** + * Compile a create table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileCreate(Blueprint $blueprint, Fluent $command) + { + return sprintf('%s table %s (%s%s%s)', + $blueprint->temporary ? 'create temporary' : 'create', + $this->wrapTable($blueprint), + implode(', ', $this->getColumns($blueprint)), + (string) $this->addForeignKeys($blueprint), + (string) $this->addPrimaryKeys($blueprint) + ); + } + + /** + * Get the foreign key syntax for a table creation statement. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return string|null + */ + protected function addForeignKeys(Blueprint $blueprint) + { + $foreigns = $this->getCommandsByName($blueprint, 'foreign'); + + return collect($foreigns)->reduce(function ($sql, $foreign) { + // Once we have all the foreign key commands for the table creation statement + // we'll loop through each of them and add them to the create table SQL we + // are building, since SQLite needs foreign keys on the tables creation. + $sql .= $this->getForeignKey($foreign); + + if (! is_null($foreign->onDelete)) { + $sql .= " on delete {$foreign->onDelete}"; + } + + // If this foreign key specifies the action to be taken on update we will add + // that to the statement here. We'll append it to this SQL and then return + // the SQL so we can keep adding any other foreign constraints onto this. + if (! is_null($foreign->onUpdate)) { + $sql .= " on update {$foreign->onUpdate}"; + } + + return $sql; + }, ''); + } + + /** + * Get the SQL for the foreign key. + * + * @param \Illuminate\Support\Fluent $foreign + * @return string + */ + protected function getForeignKey($foreign) + { + // We need to columnize the columns that the foreign key is being defined for + // so that it is a properly formatted list. Once we have done this, we can + // return the foreign key SQL declaration to the calling method for use. + return sprintf(', foreign key(%s) references %s(%s)', + $this->columnize($foreign->columns), + $this->wrapTable($foreign->on), + $this->columnize((array) $foreign->references) + ); + } + + /** + * Get the primary key syntax for a table creation statement. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @return string|null + */ + protected function addPrimaryKeys(Blueprint $blueprint) + { + if (! is_null($primary = $this->getCommandByName($blueprint, 'primary'))) { + return ", primary key ({$this->columnize($primary->columns)})"; + } + } + + /** + * Compile alter table commands for adding columns. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return array + */ + public function compileAdd(Blueprint $blueprint, Fluent $command) + { + $columns = $this->prefixArray('add column', $this->getColumns($blueprint)); + + return collect($columns)->reject(function ($column) { + return preg_match('/as \(.*\) stored/', $column) > 0; + })->map(function ($column) use ($blueprint) { + return 'alter table '.$this->wrapTable($blueprint).' '.$column; + })->all(); + } + + /** + * Compile a unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileUnique(Blueprint $blueprint, Fluent $command) + { + return sprintf('create unique index %s on %s (%s)', + $this->wrap($command->index), + $this->wrapTable($blueprint), + $this->columnize($command->columns) + ); + } + + /** + * Compile a plain index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf('create index %s on %s (%s)', + $this->wrap($command->index), + $this->wrapTable($blueprint), + $this->columnize($command->columns) + ); + } + + /** + * Compile a spatial index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return void + * + * @throws \RuntimeException + */ + public function compileSpatialIndex(Blueprint $blueprint, Fluent $command) + { + throw new RuntimeException('The database driver in use does not support spatial indexes.'); + } + + /** + * Compile a foreign key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileForeign(Blueprint $blueprint, Fluent $command) + { + // Handled on table creation... + } + + /** + * Compile a drop table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDrop(Blueprint $blueprint, Fluent $command) + { + return 'drop table '.$this->wrapTable($blueprint); + } + + /** + * Compile a drop table (if exists) command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIfExists(Blueprint $blueprint, Fluent $command) + { + return 'drop table if exists '.$this->wrapTable($blueprint); + } + + /** + * Compile the SQL needed to drop all tables. + * + * @return string + */ + public function compileDropAllTables() + { + return "delete from sqlite_master where type in ('table', 'index', 'trigger')"; + } + + /** + * Compile the SQL needed to drop all views. + * + * @return string + */ + public function compileDropAllViews() + { + return "delete from sqlite_master where type in ('view')"; + } + + /** + * Compile the SQL needed to rebuild the database. + * + * @return string + */ + public function compileRebuild() + { + return 'vacuum'; + } + + /** + * Compile a drop column command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @param \Illuminate\Database\Connection $connection + * @return array + */ + public function compileDropColumn(Blueprint $blueprint, Fluent $command, Connection $connection) + { + $tableDiff = $this->getDoctrineTableDiff( + $blueprint, $schema = $connection->getDoctrineSchemaManager() + ); + + foreach ($command->columns as $name) { + $tableDiff->removedColumns[$name] = $connection->getDoctrineColumn( + $this->getTablePrefix().$blueprint->getTable(), $name + ); + } + + return (array) $schema->getDatabasePlatform()->getAlterTableSQL($tableDiff); + } + + /** + * Compile a drop unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropUnique(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "drop index {$index}"; + } + + /** + * Compile a drop index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIndex(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "drop index {$index}"; + } + + /** + * Compile a drop spatial index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return void + * + * @throws \RuntimeException + */ + public function compileDropSpatialIndex(Blueprint $blueprint, Fluent $command) + { + throw new RuntimeException('The database driver in use does not support spatial indexes.'); + } + + /** + * Compile a rename table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRename(Blueprint $blueprint, Fluent $command) + { + $from = $this->wrapTable($blueprint); + + return "alter table {$from} rename to ".$this->wrapTable($command->to); + } + + /** + * Compile a rename index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @param \Illuminate\Database\Connection $connection + * @return array + * + * @throws \RuntimeException + */ + public function compileRenameIndex(Blueprint $blueprint, Fluent $command, Connection $connection) + { + $schemaManager = $connection->getDoctrineSchemaManager(); + + $indexes = $schemaManager->listTableIndexes($this->getTablePrefix().$blueprint->getTable()); + + $index = Arr::get($indexes, $command->from); + + if (! $index) { + throw new RuntimeException("Index [{$command->from}] does not exist."); + } + + $newIndex = new Index( + $command->to, $index->getColumns(), $index->isUnique(), + $index->isPrimary(), $index->getFlags(), $index->getOptions() + ); + + $platform = $schemaManager->getDatabasePlatform(); + + return [ + $platform->getDropIndexSQL($command->from, $this->getTablePrefix().$blueprint->getTable()), + $platform->getCreateIndexSQL($newIndex, $this->getTablePrefix().$blueprint->getTable()), + ]; + } + + /** + * Compile the command to enable foreign key constraints. + * + * @return string + */ + public function compileEnableForeignKeyConstraints() + { + return 'PRAGMA foreign_keys = ON;'; + } + + /** + * Compile the command to disable foreign key constraints. + * + * @return string + */ + public function compileDisableForeignKeyConstraints() + { + return 'PRAGMA foreign_keys = OFF;'; + } + + /** + * Compile the SQL needed to enable a writable schema. + * + * @return string + */ + public function compileEnableWriteableSchema() + { + return 'PRAGMA writable_schema = 1;'; + } + + /** + * Compile the SQL needed to disable a writable schema. + * + * @return string + */ + public function compileDisableWriteableSchema() + { + return 'PRAGMA writable_schema = 0;'; + } + + /** + * Create the column definition for a char type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeChar(Fluent $column) + { + return 'varchar'; + } + + /** + * Create the column definition for a string type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeString(Fluent $column) + { + return 'varchar'; + } + + /** + * Create the column definition for a tiny text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a medium text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a long text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeLongText(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for an integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeInteger(Fluent $column) + { + return 'integer'; + } + + /** + * Create the column definition for a big integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBigInteger(Fluent $column) + { + return 'integer'; + } + + /** + * Create the column definition for a medium integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumInteger(Fluent $column) + { + return 'integer'; + } + + /** + * Create the column definition for a tiny integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyInteger(Fluent $column) + { + return 'integer'; + } + + /** + * Create the column definition for a small integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeSmallInteger(Fluent $column) + { + return 'integer'; + } + + /** + * Create the column definition for a float type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeFloat(Fluent $column) + { + return 'float'; + } + + /** + * Create the column definition for a double type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDouble(Fluent $column) + { + return 'float'; + } + + /** + * Create the column definition for a decimal type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDecimal(Fluent $column) + { + return 'numeric'; + } + + /** + * Create the column definition for a boolean type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBoolean(Fluent $column) + { + return 'tinyint(1)'; + } + + /** + * Create the column definition for an enumeration type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeEnum(Fluent $column) + { + return sprintf( + 'varchar check ("%s" in (%s))', + $column->name, + $this->quoteString($column->allowed) + ); + } + + /** + * Create the column definition for a json type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJson(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a jsonb type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJsonb(Fluent $column) + { + return 'text'; + } + + /** + * Create the column definition for a date type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDate(Fluent $column) + { + return 'date'; + } + + /** + * Create the column definition for a date-time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTime(Fluent $column) + { + return $this->typeTimestamp($column); + } + + /** + * Create the column definition for a date-time (with time zone) type. + * + * Note: "SQLite does not have a storage class set aside for storing dates and/or times." + * + * @link https://www.sqlite.org/datatype3.html + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTimeTz(Fluent $column) + { + return $this->typeDateTime($column); + } + + /** + * Create the column definition for a time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTime(Fluent $column) + { + return 'time'; + } + + /** + * Create the column definition for a time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimeTz(Fluent $column) + { + return $this->typeTime($column); + } + + /** + * Create the column definition for a timestamp type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestamp(Fluent $column) + { + return $column->useCurrent ? 'datetime default CURRENT_TIMESTAMP' : 'datetime'; + } + + /** + * Create the column definition for a timestamp (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestampTz(Fluent $column) + { + return $this->typeTimestamp($column); + } + + /** + * Create the column definition for a year type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeYear(Fluent $column) + { + return $this->typeInteger($column); + } + + /** + * Create the column definition for a binary type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBinary(Fluent $column) + { + return 'blob'; + } + + /** + * Create the column definition for a uuid type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeUuid(Fluent $column) + { + return 'varchar'; + } + + /** + * Create the column definition for an IP address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeIpAddress(Fluent $column) + { + return 'varchar'; + } + + /** + * Create the column definition for a MAC address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMacAddress(Fluent $column) + { + return 'varchar'; + } + + /** + * Create the column definition for a spatial Geometry type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeGeometry(Fluent $column) + { + return 'geometry'; + } + + /** + * Create the column definition for a spatial Point type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typePoint(Fluent $column) + { + return 'point'; + } + + /** + * Create the column definition for a spatial LineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeLineString(Fluent $column) + { + return 'linestring'; + } + + /** + * Create the column definition for a spatial Polygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typePolygon(Fluent $column) + { + return 'polygon'; + } + + /** + * Create the column definition for a spatial GeometryCollection type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeGeometryCollection(Fluent $column) + { + return 'geometrycollection'; + } + + /** + * Create the column definition for a spatial MultiPoint type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiPoint(Fluent $column) + { + return 'multipoint'; + } + + /** + * Create the column definition for a spatial MultiLineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiLineString(Fluent $column) + { + return 'multilinestring'; + } + + /** + * Create the column definition for a spatial MultiPolygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiPolygon(Fluent $column) + { + return 'multipolygon'; + } + + /** + * Create the column definition for a generated, computed column type. + * + * @param \Illuminate\Support\Fluent $column + * @return void + * + * @throws \RuntimeException + */ + protected function typeComputed(Fluent $column) + { + throw new RuntimeException('This database driver requires a type, see the virtualAs / storedAs modifiers.'); + } + + /** + * Get the SQL for a generated virtual column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->virtualAs)) { + return " as ({$column->virtualAs})"; + } + } + + /** + * Get the SQL for a generated stored column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyStoredAs(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->storedAs)) { + return " as ({$column->storedAs}) stored"; + } + } + + /** + * Get the SQL for a nullable column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyNullable(Blueprint $blueprint, Fluent $column) + { + if (is_null($column->virtualAs) && is_null($column->storedAs)) { + return $column->nullable ? '' : ' not null'; + } + + if ($column->nullable === false) { + return ' not null'; + } + } + + /** + * Get the SQL for a default column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyDefault(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->default) && is_null($column->virtualAs) && is_null($column->storedAs)) { + return ' default '.$this->getDefaultValue($column->default); + } + } + + /** + * Get the SQL for an auto-increment column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyIncrement(Blueprint $blueprint, Fluent $column) + { + if (in_array($column->type, $this->serials) && $column->autoIncrement) { + return ' primary key autoincrement'; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php new file mode 100755 index 0000000..e594cfd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php @@ -0,0 +1,934 @@ +wrapValue($name), + ); + } + + /** + * Compile a drop database if exists command. + * + * @param string $name + * @return string + */ + public function compileDropDatabaseIfExists($name) + { + return sprintf( + 'drop database if exists %s', + $this->wrapValue($name) + ); + } + + /** + * Compile the query to determine if a table exists. + * + * @return string + */ + public function compileTableExists() + { + return "select * from sys.sysobjects where id = object_id(?) and xtype in ('U', 'V')"; + } + + /** + * Compile the query to determine the list of columns. + * + * @param string $table + * @return string + */ + public function compileColumnListing($table) + { + return "select name from sys.columns where object_id = object_id('$table')"; + } + + /** + * Compile a create table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileCreate(Blueprint $blueprint, Fluent $command) + { + $columns = implode(', ', $this->getColumns($blueprint)); + + return 'create table '.$this->wrapTable($blueprint)." ($columns)"; + } + + /** + * Compile a column addition table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileAdd(Blueprint $blueprint, Fluent $command) + { + return sprintf('alter table %s add %s', + $this->wrapTable($blueprint), + implode(', ', $this->getColumns($blueprint)) + ); + } + + /** + * Compile a primary key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compilePrimary(Blueprint $blueprint, Fluent $command) + { + return sprintf('alter table %s add constraint %s primary key (%s)', + $this->wrapTable($blueprint), + $this->wrap($command->index), + $this->columnize($command->columns) + ); + } + + /** + * Compile a unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileUnique(Blueprint $blueprint, Fluent $command) + { + return sprintf('create unique index %s on %s (%s)', + $this->wrap($command->index), + $this->wrapTable($blueprint), + $this->columnize($command->columns) + ); + } + + /** + * Compile a plain index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf('create index %s on %s (%s)', + $this->wrap($command->index), + $this->wrapTable($blueprint), + $this->columnize($command->columns) + ); + } + + /** + * Compile a spatial index key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileSpatialIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf('create spatial index %s on %s (%s)', + $this->wrap($command->index), + $this->wrapTable($blueprint), + $this->columnize($command->columns) + ); + } + + /** + * Compile a drop table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDrop(Blueprint $blueprint, Fluent $command) + { + return 'drop table '.$this->wrapTable($blueprint); + } + + /** + * Compile a drop table (if exists) command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIfExists(Blueprint $blueprint, Fluent $command) + { + return sprintf('if exists (select * from sys.sysobjects where id = object_id(%s, \'U\')) drop table %s', + "'".str_replace("'", "''", $this->getTablePrefix().$blueprint->getTable())."'", + $this->wrapTable($blueprint) + ); + } + + /** + * Compile the SQL needed to drop all tables. + * + * @return string + */ + public function compileDropAllTables() + { + return "EXEC sp_msforeachtable 'DROP TABLE ?'"; + } + + /** + * Compile a drop column command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropColumn(Blueprint $blueprint, Fluent $command) + { + $columns = $this->wrapArray($command->columns); + + $dropExistingConstraintsSql = $this->compileDropDefaultConstraint($blueprint, $command).';'; + + return $dropExistingConstraintsSql.'alter table '.$this->wrapTable($blueprint).' drop column '.implode(', ', $columns); + } + + /** + * Compile a drop default constraint command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropDefaultConstraint(Blueprint $blueprint, Fluent $command) + { + $columns = "'".implode("','", $command->columns)."'"; + + $tableName = $this->getTablePrefix().$blueprint->getTable(); + + $sql = "DECLARE @sql NVARCHAR(MAX) = '';"; + $sql .= "SELECT @sql += 'ALTER TABLE [dbo].[{$tableName}] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' "; + $sql .= 'FROM sys.columns '; + $sql .= "WHERE [object_id] = OBJECT_ID('[dbo].[{$tableName}]') AND [name] in ({$columns}) AND [default_object_id] <> 0;"; + $sql .= 'EXEC(@sql)'; + + return $sql; + } + + /** + * Compile a drop primary key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropPrimary(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop constraint {$index}"; + } + + /** + * Compile a drop unique key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropUnique(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "drop index {$index} on {$this->wrapTable($blueprint)}"; + } + + /** + * Compile a drop index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropIndex(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "drop index {$index} on {$this->wrapTable($blueprint)}"; + } + + /** + * Compile a drop spatial index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropSpatialIndex(Blueprint $blueprint, Fluent $command) + { + return $this->compileDropIndex($blueprint, $command); + } + + /** + * Compile a drop foreign key command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileDropForeign(Blueprint $blueprint, Fluent $command) + { + $index = $this->wrap($command->index); + + return "alter table {$this->wrapTable($blueprint)} drop constraint {$index}"; + } + + /** + * Compile a rename table command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRename(Blueprint $blueprint, Fluent $command) + { + $from = $this->wrapTable($blueprint); + + return "sp_rename {$from}, ".$this->wrapTable($command->to); + } + + /** + * Compile a rename index command. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $command + * @return string + */ + public function compileRenameIndex(Blueprint $blueprint, Fluent $command) + { + return sprintf("sp_rename N'%s', %s, N'INDEX'", + $this->wrap($blueprint->getTable().'.'.$command->from), + $this->wrap($command->to) + ); + } + + /** + * Compile the command to enable foreign key constraints. + * + * @return string + */ + public function compileEnableForeignKeyConstraints() + { + return 'EXEC sp_msforeachtable @command1="print \'?\'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all";'; + } + + /** + * Compile the command to disable foreign key constraints. + * + * @return string + */ + public function compileDisableForeignKeyConstraints() + { + return 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";'; + } + + /** + * Compile the command to drop all foreign keys. + * + * @return string + */ + public function compileDropAllForeignKeys() + { + return "DECLARE @sql NVARCHAR(MAX) = N''; + SELECT @sql += 'ALTER TABLE ' + + QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' + + QUOTENAME(OBJECT_NAME(parent_object_id)) + + ' DROP CONSTRAINT ' + QUOTENAME(name) + ';' + FROM sys.foreign_keys; + + EXEC sp_executesql @sql;"; + } + + /** + * Compile the command to drop all views. + * + * @return string + */ + public function compileDropAllViews() + { + return "DECLARE @sql NVARCHAR(MAX) = N''; + SELECT @sql += 'DROP VIEW ' + QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + '.' + QUOTENAME(name) + ';' + FROM sys.views; + + EXEC sp_executesql @sql;"; + } + + /** + * Create the column definition for a char type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeChar(Fluent $column) + { + return "nchar({$column->length})"; + } + + /** + * Create the column definition for a string type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeString(Fluent $column) + { + return "nvarchar({$column->length})"; + } + + /** + * Create the column definition for a tiny text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyText(Fluent $column) + { + return 'nvarchar(255)'; + } + + /** + * Create the column definition for a text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeText(Fluent $column) + { + return 'nvarchar(max)'; + } + + /** + * Create the column definition for a medium text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumText(Fluent $column) + { + return 'nvarchar(max)'; + } + + /** + * Create the column definition for a long text type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeLongText(Fluent $column) + { + return 'nvarchar(max)'; + } + + /** + * Create the column definition for an integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeInteger(Fluent $column) + { + return 'int'; + } + + /** + * Create the column definition for a big integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBigInteger(Fluent $column) + { + return 'bigint'; + } + + /** + * Create the column definition for a medium integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMediumInteger(Fluent $column) + { + return 'int'; + } + + /** + * Create the column definition for a tiny integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTinyInteger(Fluent $column) + { + return 'tinyint'; + } + + /** + * Create the column definition for a small integer type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeSmallInteger(Fluent $column) + { + return 'smallint'; + } + + /** + * Create the column definition for a float type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeFloat(Fluent $column) + { + return 'float'; + } + + /** + * Create the column definition for a double type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDouble(Fluent $column) + { + return 'float'; + } + + /** + * Create the column definition for a decimal type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDecimal(Fluent $column) + { + return "decimal({$column->total}, {$column->places})"; + } + + /** + * Create the column definition for a boolean type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBoolean(Fluent $column) + { + return 'bit'; + } + + /** + * Create the column definition for an enumeration type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeEnum(Fluent $column) + { + return sprintf( + 'nvarchar(255) check ("%s" in (%s))', + $column->name, + $this->quoteString($column->allowed) + ); + } + + /** + * Create the column definition for a json type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJson(Fluent $column) + { + return 'nvarchar(max)'; + } + + /** + * Create the column definition for a jsonb type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeJsonb(Fluent $column) + { + return 'nvarchar(max)'; + } + + /** + * Create the column definition for a date type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDate(Fluent $column) + { + return 'date'; + } + + /** + * Create the column definition for a date-time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTime(Fluent $column) + { + return $this->typeTimestamp($column); + } + + /** + * Create the column definition for a date-time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeDateTimeTz(Fluent $column) + { + return $this->typeTimestampTz($column); + } + + /** + * Create the column definition for a time type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTime(Fluent $column) + { + return $column->precision ? "time($column->precision)" : 'time'; + } + + /** + * Create the column definition for a time (with time zone) type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimeTz(Fluent $column) + { + return $this->typeTime($column); + } + + /** + * Create the column definition for a timestamp type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestamp(Fluent $column) + { + $columnType = $column->precision ? "datetime2($column->precision)" : 'datetime'; + + return $column->useCurrent ? "$columnType default CURRENT_TIMESTAMP" : $columnType; + } + + /** + * Create the column definition for a timestamp (with time zone) type. + * + * @link https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetimeoffset-transact-sql?view=sql-server-ver15 + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeTimestampTz(Fluent $column) + { + $columnType = $column->precision ? "datetimeoffset($column->precision)" : 'datetimeoffset'; + + return $column->useCurrent ? "$columnType default CURRENT_TIMESTAMP" : $columnType; + } + + /** + * Create the column definition for a year type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeYear(Fluent $column) + { + return $this->typeInteger($column); + } + + /** + * Create the column definition for a binary type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeBinary(Fluent $column) + { + return 'varbinary(max)'; + } + + /** + * Create the column definition for a uuid type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeUuid(Fluent $column) + { + return 'uniqueidentifier'; + } + + /** + * Create the column definition for an IP address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeIpAddress(Fluent $column) + { + return 'nvarchar(45)'; + } + + /** + * Create the column definition for a MAC address type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + protected function typeMacAddress(Fluent $column) + { + return 'nvarchar(17)'; + } + + /** + * Create the column definition for a spatial Geometry type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeGeometry(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial Point type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typePoint(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial LineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeLineString(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial Polygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typePolygon(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial GeometryCollection type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeGeometryCollection(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial MultiPoint type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiPoint(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial MultiLineString type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiLineString(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a spatial MultiPolygon type. + * + * @param \Illuminate\Support\Fluent $column + * @return string + */ + public function typeMultiPolygon(Fluent $column) + { + return 'geography'; + } + + /** + * Create the column definition for a generated, computed column type. + * + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function typeComputed(Fluent $column) + { + return "as ({$column->expression})"; + } + + /** + * Get the SQL for a collation column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyCollate(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->collation)) { + return ' collate '.$column->collation; + } + } + + /** + * Get the SQL for a nullable column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyNullable(Blueprint $blueprint, Fluent $column) + { + if ($column->type !== 'computed') { + return $column->nullable ? ' null' : ' not null'; + } + } + + /** + * Get the SQL for a default column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyDefault(Blueprint $blueprint, Fluent $column) + { + if (! is_null($column->default)) { + return ' default '.$this->getDefaultValue($column->default); + } + } + + /** + * Get the SQL for an auto-increment column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyIncrement(Blueprint $blueprint, Fluent $column) + { + if (in_array($column->type, $this->serials) && $column->autoIncrement) { + return ' identity primary key'; + } + } + + /** + * Get the SQL for a generated stored column modifier. + * + * @param \Illuminate\Database\Schema\Blueprint $blueprint + * @param \Illuminate\Support\Fluent $column + * @return string|null + */ + protected function modifyPersisted(Blueprint $blueprint, Fluent $column) + { + if ($column->persisted) { + return ' persisted'; + } + } + + /** + * Wrap a table in keyword identifiers. + * + * @param \Illuminate\Database\Query\Expression|string $table + * @return string + */ + public function wrapTable($table) + { + if ($table instanceof Blueprint && $table->temporary) { + $this->setTablePrefix('#'); + } + + return parent::wrapTable($table); + } + + /** + * Quote the given string literal. + * + * @param string|array $value + * @return string + */ + public function quoteString($value) + { + if (is_array($value)) { + return implode(', ', array_map([$this, __FUNCTION__], $value)); + } + + return "N'$value'"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlBuilder.php new file mode 100755 index 0000000..699b41d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlBuilder.php @@ -0,0 +1,140 @@ +connection->statement( + $this->grammar->compileCreateDatabase($name, $this->connection) + ); + } + + /** + * Drop a database from the schema if the database exists. + * + * @param string $name + * @return bool + */ + public function dropDatabaseIfExists($name) + { + return $this->connection->statement( + $this->grammar->compileDropDatabaseIfExists($name) + ); + } + + /** + * Determine if the given table exists. + * + * @param string $table + * @return bool + */ + public function hasTable($table) + { + $table = $this->connection->getTablePrefix().$table; + + return count($this->connection->select( + $this->grammar->compileTableExists(), [$this->connection->getDatabaseName(), $table] + )) > 0; + } + + /** + * Get the column listing for a given table. + * + * @param string $table + * @return array + */ + public function getColumnListing($table) + { + $table = $this->connection->getTablePrefix().$table; + + $results = $this->connection->select( + $this->grammar->compileColumnListing(), [$this->connection->getDatabaseName(), $table] + ); + + return $this->connection->getPostProcessor()->processColumnListing($results); + } + + /** + * Drop all tables from the database. + * + * @return void + */ + public function dropAllTables() + { + $tables = []; + + foreach ($this->getAllTables() as $row) { + $row = (array) $row; + + $tables[] = reset($row); + } + + if (empty($tables)) { + return; + } + + $this->disableForeignKeyConstraints(); + + $this->connection->statement( + $this->grammar->compileDropAllTables($tables) + ); + + $this->enableForeignKeyConstraints(); + } + + /** + * Drop all views from the database. + * + * @return void + */ + public function dropAllViews() + { + $views = []; + + foreach ($this->getAllViews() as $row) { + $row = (array) $row; + + $views[] = reset($row); + } + + if (empty($views)) { + return; + } + + $this->connection->statement( + $this->grammar->compileDropAllViews($views) + ); + } + + /** + * Get all of the table names for the database. + * + * @return array + */ + public function getAllTables() + { + return $this->connection->select( + $this->grammar->compileGetAllTables() + ); + } + + /** + * Get all of the view names for the database. + * + * @return array + */ + public function getAllViews() + { + return $this->connection->select( + $this->grammar->compileGetAllViews() + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlSchemaState.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlSchemaState.php new file mode 100644 index 0000000..e0b0103 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlSchemaState.php @@ -0,0 +1,163 @@ +executeDumpProcess($this->makeProcess( + $this->baseDumpCommand().' --routines --result-file="${:LARAVEL_LOAD_PATH}" --no-data' + ), $this->output, array_merge($this->baseVariables($this->connection->getConfig()), [ + 'LARAVEL_LOAD_PATH' => $path, + ])); + + $this->removeAutoIncrementingState($path); + + $this->appendMigrationData($path); + } + + /** + * Remove the auto-incrementing state from the given schema dump. + * + * @param string $path + * @return void + */ + protected function removeAutoIncrementingState(string $path) + { + $this->files->put($path, preg_replace( + '/\s+AUTO_INCREMENT=[0-9]+/iu', + '', + $this->files->get($path) + )); + } + + /** + * Append the migration data to the schema dump. + * + * @param string $path + * @return void + */ + protected function appendMigrationData(string $path) + { + $process = $this->executeDumpProcess($this->makeProcess( + $this->baseDumpCommand().' '.$this->migrationTable.' --no-create-info --skip-extended-insert --skip-routines --compact' + ), null, array_merge($this->baseVariables($this->connection->getConfig()), [ + // + ])); + + $this->files->append($path, $process->getOutput()); + } + + /** + * Load the given schema file into the database. + * + * @param string $path + * @return void + */ + public function load($path) + { + $command = 'mysql '.$this->connectionString().' --database="${:LARAVEL_LOAD_DATABASE}" < "${:LARAVEL_LOAD_PATH}"'; + + $process = $this->makeProcess($command)->setTimeout(null); + + $process->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [ + 'LARAVEL_LOAD_PATH' => $path, + ])); + } + + /** + * Get the base dump command arguments for MySQL as a string. + * + * @return string + */ + protected function baseDumpCommand() + { + $command = 'mysqldump '.$this->connectionString().' --no-tablespaces --skip-add-locks --skip-comments --skip-set-charset --tz-utc --column-statistics=0'; + + if (! $this->connection->isMaria()) { + $command .= ' --set-gtid-purged=OFF'; + } + + return $command.' "${:LARAVEL_LOAD_DATABASE}"'; + } + + /** + * Generate a basic connection string (--socket, --host, --port, --user, --password) for the database. + * + * @return string + */ + protected function connectionString() + { + $value = ' --user="${:LARAVEL_LOAD_USER}" --password="${:LARAVEL_LOAD_PASSWORD}"'; + + $value .= $this->connection->getConfig()['unix_socket'] ?? false + ? ' --socket="${:LARAVEL_LOAD_SOCKET}"' + : ' --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}"'; + + return $value; + } + + /** + * Get the base variables for a dump / load command. + * + * @param array $config + * @return array + */ + protected function baseVariables(array $config) + { + $config['host'] = $config['host'] ?? ''; + + return [ + 'LARAVEL_LOAD_SOCKET' => $config['unix_socket'] ?? '', + 'LARAVEL_LOAD_HOST' => is_array($config['host']) ? $config['host'][0] : $config['host'], + 'LARAVEL_LOAD_PORT' => $config['port'] ?? '', + 'LARAVEL_LOAD_USER' => $config['username'], + 'LARAVEL_LOAD_PASSWORD' => $config['password'] ?? '', + 'LARAVEL_LOAD_DATABASE' => $config['database'], + ]; + } + + /** + * Execute the given dump process. + * + * @param \Symfony\Component\Process\Process $process + * @param callable $output + * @param array $variables + * @return \Symfony\Component\Process\Process + */ + protected function executeDumpProcess(Process $process, $output, array $variables) + { + try { + $process->setTimeout(null)->mustRun($output, $variables); + } catch (Exception $e) { + if (Str::contains($e->getMessage(), ['column-statistics', 'column_statistics'])) { + return $this->executeDumpProcess(Process::fromShellCommandLine( + str_replace(' --column-statistics=0', '', $process->getCommandLine()) + ), $output, $variables); + } + + if (Str::contains($e->getMessage(), ['set-gtid-purged'])) { + return $this->executeDumpProcess(Process::fromShellCommandLine( + str_replace(' --set-gtid-purged=OFF', '', $process->getCommandLine()) + ), $output, $variables); + } + + throw $e; + } + + return $process; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/PostgresBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/PostgresBuilder.php new file mode 100755 index 0000000..ce1b577 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/PostgresBuilder.php @@ -0,0 +1,203 @@ +connection->statement( + $this->grammar->compileCreateDatabase($name, $this->connection) + ); + } + + /** + * Drop a database from the schema if the database exists. + * + * @param string $name + * @return bool + */ + public function dropDatabaseIfExists($name) + { + return $this->connection->statement( + $this->grammar->compileDropDatabaseIfExists($name) + ); + } + + /** + * Determine if the given table exists. + * + * @param string $table + * @return bool + */ + public function hasTable($table) + { + [$schema, $table] = $this->parseSchemaAndTable($table); + + $table = $this->connection->getTablePrefix().$table; + + return count($this->connection->select( + $this->grammar->compileTableExists(), [$schema, $table] + )) > 0; + } + + /** + * Drop all tables from the database. + * + * @return void + */ + public function dropAllTables() + { + $tables = []; + + $excludedTables = $this->connection->getConfig('dont_drop') ?? ['spatial_ref_sys']; + + foreach ($this->getAllTables() as $row) { + $row = (array) $row; + + $table = reset($row); + + if (! in_array($table, $excludedTables)) { + $tables[] = $table; + } + } + + if (empty($tables)) { + return; + } + + $this->connection->statement( + $this->grammar->compileDropAllTables($tables) + ); + } + + /** + * Drop all views from the database. + * + * @return void + */ + public function dropAllViews() + { + $views = []; + + foreach ($this->getAllViews() as $row) { + $row = (array) $row; + + $views[] = reset($row); + } + + if (empty($views)) { + return; + } + + $this->connection->statement( + $this->grammar->compileDropAllViews($views) + ); + } + + /** + * Drop all types from the database. + * + * @return void + */ + public function dropAllTypes() + { + $types = []; + + foreach ($this->getAllTypes() as $row) { + $row = (array) $row; + + $types[] = reset($row); + } + + if (empty($types)) { + return; + } + + $this->connection->statement( + $this->grammar->compileDropAllTypes($types) + ); + } + + /** + * Get all of the table names for the database. + * + * @return array + */ + public function getAllTables() + { + return $this->connection->select( + $this->grammar->compileGetAllTables((array) $this->connection->getConfig('schema')) + ); + } + + /** + * Get all of the view names for the database. + * + * @return array + */ + public function getAllViews() + { + return $this->connection->select( + $this->grammar->compileGetAllViews((array) $this->connection->getConfig('schema')) + ); + } + + /** + * Get all of the type names for the database. + * + * @return array + */ + public function getAllTypes() + { + return $this->connection->select( + $this->grammar->compileGetAllTypes() + ); + } + + /** + * Get the column listing for a given table. + * + * @param string $table + * @return array + */ + public function getColumnListing($table) + { + [$schema, $table] = $this->parseSchemaAndTable($table); + + $table = $this->connection->getTablePrefix().$table; + + $results = $this->connection->select( + $this->grammar->compileColumnListing(), [$schema, $table] + ); + + return $this->connection->getPostProcessor()->processColumnListing($results); + } + + /** + * Parse the table name and extract the schema and table. + * + * @param string $table + * @return array + */ + protected function parseSchemaAndTable($table) + { + $table = explode('.', $table); + + if (is_array($schema = $this->connection->getConfig('schema'))) { + if (in_array($table[0], $schema)) { + return [array_shift($table), implode('.', $table)]; + } + + $schema = head($schema); + } + + return [$schema ?: 'public', implode('.', $table)]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/PostgresSchemaState.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/PostgresSchemaState.php new file mode 100644 index 0000000..3e2f566 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/PostgresSchemaState.php @@ -0,0 +1,83 @@ +getSchemaBuilder()->getAllTables()) + ->map->tablename + ->reject(function ($table) { + return $table === $this->migrationTable; + })->map(function ($table) { + return '--exclude-table-data="*.'.$table.'"'; + })->implode(' '); + + $this->makeProcess( + $this->baseDumpCommand().' --file="${:LARAVEL_LOAD_PATH}" '.$excludedTables + )->mustRun($this->output, array_merge($this->baseVariables($this->connection->getConfig()), [ + 'LARAVEL_LOAD_PATH' => $path, + ])); + } + + /** + * Load the given schema file into the database. + * + * @param string $path + * @return void + */ + public function load($path) + { + $command = 'pg_restore --no-owner --no-acl --clean --if-exists --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}" "${:LARAVEL_LOAD_PATH}"'; + + if (Str::endsWith($path, '.sql')) { + $command = 'psql --file="${:LARAVEL_LOAD_PATH}" --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}"'; + } + + $process = $this->makeProcess($command); + + $process->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [ + 'LARAVEL_LOAD_PATH' => $path, + ])); + } + + /** + * Get the base dump command arguments for PostgreSQL as a string. + * + * @return string + */ + protected function baseDumpCommand() + { + return 'pg_dump --no-owner --no-acl -Fc --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}"'; + } + + /** + * Get the base variables for a dump / load command. + * + * @param array $config + * @return array + */ + protected function baseVariables(array $config) + { + $config['host'] = $config['host'] ?? ''; + + return [ + 'LARAVEL_LOAD_HOST' => is_array($config['host']) ? $config['host'][0] : $config['host'], + 'LARAVEL_LOAD_PORT' => $config['port'], + 'LARAVEL_LOAD_USER' => $config['username'], + 'PGPASSWORD' => $config['password'], + 'LARAVEL_LOAD_DATABASE' => $config['database'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SQLiteBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SQLiteBuilder.php new file mode 100644 index 0000000..3bc1275 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SQLiteBuilder.php @@ -0,0 +1,78 @@ +connection->getDatabaseName() !== ':memory:') { + return $this->refreshDatabaseFile(); + } + + $this->connection->select($this->grammar->compileEnableWriteableSchema()); + + $this->connection->select($this->grammar->compileDropAllTables()); + + $this->connection->select($this->grammar->compileDisableWriteableSchema()); + + $this->connection->select($this->grammar->compileRebuild()); + } + + /** + * Drop all views from the database. + * + * @return void + */ + public function dropAllViews() + { + $this->connection->select($this->grammar->compileEnableWriteableSchema()); + + $this->connection->select($this->grammar->compileDropAllViews()); + + $this->connection->select($this->grammar->compileDisableWriteableSchema()); + + $this->connection->select($this->grammar->compileRebuild()); + } + + /** + * Empty the database file. + * + * @return void + */ + public function refreshDatabaseFile() + { + file_put_contents($this->connection->getDatabaseName(), ''); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SchemaState.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SchemaState.php new file mode 100644 index 0000000..e6f35ab --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SchemaState.php @@ -0,0 +1,122 @@ +connection = $connection; + + $this->files = $files ?: new Filesystem; + + $this->processFactory = $processFactory ?: function (...$arguments) { + return Process::fromShellCommandline(...$arguments)->setTimeout(null); + }; + + $this->handleOutputUsing(function () { + // + }); + } + + /** + * Dump the database's schema into a file. + * + * @param \Illuminate\Database\Connection $connection + * @param string $path + * @return void + */ + abstract public function dump(Connection $connection, $path); + + /** + * Load the given schema file into the database. + * + * @param string $path + * @return void + */ + abstract public function load($path); + + /** + * Create a new process instance. + * + * @param array $arguments + * @return \Symfony\Component\Process\Process + */ + public function makeProcess(...$arguments) + { + return call_user_func($this->processFactory, ...$arguments); + } + + /** + * Specify the name of the application's migration table. + * + * @param string $table + * @return $this + */ + public function withMigrationTable(string $table) + { + $this->migrationTable = $table; + + return $this; + } + + /** + * Specify the callback that should be used to handle process output. + * + * @param callable $output + * @return $this + */ + public function handleOutputUsing(callable $output) + { + $this->output = $output; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SqlServerBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SqlServerBuilder.php new file mode 100644 index 0000000..93da1cb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SqlServerBuilder.php @@ -0,0 +1,54 @@ +connection->statement( + $this->grammar->compileCreateDatabase($name, $this->connection) + ); + } + + /** + * Drop a database from the schema if the database exists. + * + * @param string $name + * @return bool + */ + public function dropDatabaseIfExists($name) + { + return $this->connection->statement( + $this->grammar->compileDropDatabaseIfExists($name) + ); + } + + /** + * Drop all tables from the database. + * + * @return void + */ + public function dropAllTables() + { + $this->connection->statement($this->grammar->compileDropAllForeignKeys()); + + $this->connection->statement($this->grammar->compileDropAllTables()); + } + + /** + * Drop all views from the database. + * + * @return void + */ + public function dropAllViews() + { + $this->connection->statement($this->grammar->compileDropAllViews()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SqliteSchemaState.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SqliteSchemaState.php new file mode 100644 index 0000000..9a98b63 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Schema/SqliteSchemaState.php @@ -0,0 +1,93 @@ +makeProcess( + $this->baseCommand().' .schema' + ))->setTimeout(null)->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [ + // + ])); + + $migrations = collect(preg_split("/\r\n|\n|\r/", $process->getOutput()))->filter(function ($line) { + return stripos($line, 'sqlite_sequence') === false && + strlen($line) > 0; + })->all(); + + $this->files->put($path, implode(PHP_EOL, $migrations).PHP_EOL); + + $this->appendMigrationData($path); + } + + /** + * Append the migration data to the schema dump. + * + * @param string $path + * @return void + */ + protected function appendMigrationData(string $path) + { + with($process = $this->makeProcess( + $this->baseCommand().' ".dump \''.$this->migrationTable.'\'"' + ))->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [ + // + ])); + + $migrations = collect(preg_split("/\r\n|\n|\r/", $process->getOutput()))->filter(function ($line) { + return preg_match('/^\s*(--|INSERT\s)/iu', $line) === 1 && + strlen($line) > 0; + })->all(); + + $this->files->append($path, implode(PHP_EOL, $migrations).PHP_EOL); + } + + /** + * Load the given schema file into the database. + * + * @param string $path + * @return void + */ + public function load($path) + { + $process = $this->makeProcess($this->baseCommand().' < "${:LARAVEL_LOAD_PATH}"'); + + $process->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [ + 'LARAVEL_LOAD_PATH' => $path, + ])); + } + + /** + * Get the base sqlite command arguments as a string. + * + * @return string + */ + protected function baseCommand() + { + return 'sqlite3 "${:LARAVEL_LOAD_DATABASE}"'; + } + + /** + * Get the base variables for a dump / load command. + * + * @param array $config + * @return array + */ + protected function baseVariables(array $config) + { + return [ + 'LARAVEL_LOAD_DATABASE' => $config['database'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Seeder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Seeder.php new file mode 100755 index 0000000..441fa27 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/Seeder.php @@ -0,0 +1,152 @@ +resolve($class); + + $name = get_class($seeder); + + if ($silent === false && isset($this->command)) { + $this->command->getOutput()->writeln("Seeding: {$name}"); + } + + $startTime = microtime(true); + + $seeder->__invoke($parameters); + + $runTime = number_format((microtime(true) - $startTime) * 1000, 2); + + if ($silent === false && isset($this->command)) { + $this->command->getOutput()->writeln("Seeded: {$name} ({$runTime}ms)"); + } + } + + return $this; + } + + /** + * Run the given seeder class. + * + * @param array|string $class + * @param array $parameters + * @return void + */ + public function callWith($class, array $parameters = []) + { + $this->call($class, false, $parameters); + } + + /** + * Silently run the given seeder class. + * + * @param array|string $class + * @param array $parameters + * @return void + */ + public function callSilent($class, array $parameters = []) + { + $this->call($class, true, $parameters); + } + + /** + * Resolve an instance of the given seeder class. + * + * @param string $class + * @return \Illuminate\Database\Seeder + */ + protected function resolve($class) + { + if (isset($this->container)) { + $instance = $this->container->make($class); + + $instance->setContainer($this->container); + } else { + $instance = new $class; + } + + if (isset($this->command)) { + $instance->setCommand($this->command); + } + + return $instance; + } + + /** + * Set the IoC container instance. + * + * @param \Illuminate\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } + + /** + * Set the console command instance. + * + * @param \Illuminate\Console\Command $command + * @return $this + */ + public function setCommand(Command $command) + { + $this->command = $command; + + return $this; + } + + /** + * Run the database seeds. + * + * @param array $parameters + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function __invoke(array $parameters = []) + { + if (! method_exists($this, 'run')) { + throw new InvalidArgumentException('Method [run] missing from '.get_class($this)); + } + + return isset($this->container) + ? $this->container->call([$this, 'run'], $parameters) + : $this->run(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/SqlServerConnection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/SqlServerConnection.php new file mode 100755 index 0000000..d6a2b7a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/SqlServerConnection.php @@ -0,0 +1,125 @@ +getDriverName() === 'sqlsrv') { + return parent::transaction($callback, $attempts); + } + + $this->getPdo()->exec('BEGIN TRAN'); + + // We'll simply execute the given callback within a try / catch block + // and if we catch any exception we can rollback the transaction + // so that none of the changes are persisted to the database. + try { + $result = $callback($this); + + $this->getPdo()->exec('COMMIT TRAN'); + } + + // If we catch an exception, we will rollback so nothing gets messed + // up in the database. Then we'll re-throw the exception so it can + // be handled how the developer sees fit for their applications. + catch (Throwable $e) { + $this->getPdo()->exec('ROLLBACK TRAN'); + + throw $e; + } + + return $result; + } + } + + /** + * Get the default query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\SqlServerGrammar + */ + protected function getDefaultQueryGrammar() + { + return $this->withTablePrefix(new QueryGrammar); + } + + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\SqlServerBuilder + */ + public function getSchemaBuilder() + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new SqlServerBuilder($this); + } + + /** + * Get the default schema grammar instance. + * + * @return \Illuminate\Database\Schema\Grammars\SqlServerGrammar + */ + protected function getDefaultSchemaGrammar() + { + return $this->withTablePrefix(new SchemaGrammar); + } + + /** + * Get the schema state for the connection. + * + * @param \Illuminate\Filesystem\Filesystem|null $files + * @param callable|null $processFactory + * + * @throws \RuntimeException + */ + public function getSchemaState(Filesystem $files = null, callable $processFactory = null) + { + throw new RuntimeException('Schema dumping is not supported when using SQL Server.'); + } + + /** + * Get the default post processor instance. + * + * @return \Illuminate\Database\Query\Processors\SqlServerProcessor + */ + protected function getDefaultPostProcessor() + { + return new SqlServerProcessor; + } + + /** + * Get the Doctrine DBAL driver. + * + * @return \Doctrine\DBAL\Driver\PDOSqlsrv\Driver|\Illuminate\Database\PDO\SqlServerDriver + */ + protected function getDoctrineDriver() + { + return class_exists(Version::class) ? new DoctrineDriver : new SqlServerDriver; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/composer.json new file mode 100644 index 0000000..12738d4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Database/composer.json @@ -0,0 +1,50 @@ +{ + "name": "illuminate/database", + "description": "The Illuminate Database package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "keywords": ["laravel", "database", "sql", "orm"], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "symfony/console": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Database\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.13.3|^3.1.4).", + "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", + "illuminate/console": "Required to use the database commands (^8.0).", + "illuminate/events": "Required to use the observers with Eloquent (^8.0).", + "illuminate/filesystem": "Required to use the migrations (^8.0).", + "illuminate/pagination": "Required to paginate the result set (^8.0).", + "symfony/finder": "Required to use Eloquent model factories (^5.4)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php new file mode 100755 index 0000000..9c2a714 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php @@ -0,0 +1,282 @@ + ['size' => 16, 'aead' => false], + 'aes-256-cbc' => ['size' => 32, 'aead' => false], + 'aes-128-gcm' => ['size' => 16, 'aead' => true], + 'aes-256-gcm' => ['size' => 32, 'aead' => true], + ]; + + /** + * Create a new encrypter instance. + * + * @param string $key + * @param string $cipher + * @return void + * + * @throws \RuntimeException + */ + public function __construct($key, $cipher = 'aes-128-cbc') + { + $key = (string) $key; + + if (! static::supported($key, $cipher)) { + $ciphers = implode(', ', array_keys(self::$supportedCiphers)); + + throw new RuntimeException("Unsupported cipher or incorrect key length. Supported ciphers are: {$ciphers}."); + } + + $this->key = $key; + $this->cipher = $cipher; + } + + /** + * Determine if the given key and cipher combination is valid. + * + * @param string $key + * @param string $cipher + * @return bool + */ + public static function supported($key, $cipher) + { + if (! isset(self::$supportedCiphers[strtolower($cipher)])) { + return false; + } + + return mb_strlen($key, '8bit') === self::$supportedCiphers[strtolower($cipher)]['size']; + } + + /** + * Create a new encryption key for the given cipher. + * + * @param string $cipher + * @return string + */ + public static function generateKey($cipher) + { + return random_bytes(self::$supportedCiphers[strtolower($cipher)]['size'] ?? 32); + } + + /** + * Encrypt the given value. + * + * @param mixed $value + * @param bool $serialize + * @return string + * + * @throws \Illuminate\Contracts\Encryption\EncryptException + */ + public function encrypt($value, $serialize = true) + { + $iv = random_bytes(openssl_cipher_iv_length(strtolower($this->cipher))); + + $tag = ''; + + $value = self::$supportedCiphers[strtolower($this->cipher)]['aead'] + ? \openssl_encrypt( + $serialize ? serialize($value) : $value, + strtolower($this->cipher), $this->key, 0, $iv, $tag + ) + : \openssl_encrypt( + $serialize ? serialize($value) : $value, + strtolower($this->cipher), $this->key, 0, $iv + ); + + if ($value === false) { + throw new EncryptException('Could not encrypt the data.'); + } + + $iv = base64_encode($iv); + $tag = base64_encode($tag); + + $mac = self::$supportedCiphers[strtolower($this->cipher)]['aead'] + ? '' // For AEAD-algoritms, the tag / MAC is returned by openssl_encrypt... + : $this->hash($iv, $value); + + $json = json_encode(compact('iv', 'value', 'mac', 'tag'), JSON_UNESCAPED_SLASHES); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new EncryptException('Could not encrypt the data.'); + } + + return base64_encode($json); + } + + /** + * Encrypt a string without serialization. + * + * @param string $value + * @return string + * + * @throws \Illuminate\Contracts\Encryption\EncryptException + */ + public function encryptString($value) + { + return $this->encrypt($value, false); + } + + /** + * Decrypt the given value. + * + * @param string $payload + * @param bool $unserialize + * @return mixed + * + * @throws \Illuminate\Contracts\Encryption\DecryptException + */ + public function decrypt($payload, $unserialize = true) + { + $payload = $this->getJsonPayload($payload); + + $iv = base64_decode($payload['iv']); + + $this->ensureTagIsValid( + $tag = empty($payload['tag']) ? null : base64_decode($payload['tag']) + ); + + // Here we will decrypt the value. If we are able to successfully decrypt it + // we will then unserialize it and return it out to the caller. If we are + // unable to decrypt this value we will throw out an exception message. + $decrypted = \openssl_decrypt( + $payload['value'], strtolower($this->cipher), $this->key, 0, $iv, $tag ?? '' + ); + + if ($decrypted === false) { + throw new DecryptException('Could not decrypt the data.'); + } + + return $unserialize ? unserialize($decrypted) : $decrypted; + } + + /** + * Decrypt the given string without unserialization. + * + * @param string $payload + * @return string + * + * @throws \Illuminate\Contracts\Encryption\DecryptException + */ + public function decryptString($payload) + { + return $this->decrypt($payload, false); + } + + /** + * Create a MAC for the given value. + * + * @param string $iv + * @param mixed $value + * @return string + */ + protected function hash($iv, $value) + { + return hash_hmac('sha256', $iv.$value, $this->key); + } + + /** + * Get the JSON array from the given payload. + * + * @param string $payload + * @return array + * + * @throws \Illuminate\Contracts\Encryption\DecryptException + */ + protected function getJsonPayload($payload) + { + $payload = json_decode(base64_decode($payload), true); + + // If the payload is not valid JSON or does not have the proper keys set we will + // assume it is invalid and bail out of the routine since we will not be able + // to decrypt the given value. We'll also check the MAC for this encryption. + if (! $this->validPayload($payload)) { + throw new DecryptException('The payload is invalid.'); + } + + if (! self::$supportedCiphers[strtolower($this->cipher)]['aead'] && ! $this->validMac($payload)) { + throw new DecryptException('The MAC is invalid.'); + } + + return $payload; + } + + /** + * Verify that the encryption payload is valid. + * + * @param mixed $payload + * @return bool + */ + protected function validPayload($payload) + { + return is_array($payload) && isset($payload['iv'], $payload['value'], $payload['mac']) && + strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length(strtolower($this->cipher)); + } + + /** + * Determine if the MAC for the given payload is valid. + * + * @param array $payload + * @return bool + */ + protected function validMac(array $payload) + { + return hash_equals( + $this->hash($payload['iv'], $payload['value']), $payload['mac'] + ); + } + + /** + * Ensure the given tag is a valid tag given the selected cipher. + * + * @param string $tag + * @return void + */ + protected function ensureTagIsValid($tag) + { + if (self::$supportedCiphers[strtolower($this->cipher)]['aead'] && strlen($tag) !== 16) { + throw new DecryptException('Could not decrypt the data.'); + } + + if (! self::$supportedCiphers[strtolower($this->cipher)]['aead'] && is_string($tag)) { + throw new DecryptException('Unable to use tag because the cipher algorithm does not support AEAD.'); + } + } + + /** + * Get the encryption key. + * + * @return string + */ + public function getKey() + { + return $this->key; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/EncryptionServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/EncryptionServiceProvider.php new file mode 100755 index 0000000..4ef42ba --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/EncryptionServiceProvider.php @@ -0,0 +1,105 @@ +registerEncrypter(); + $this->registerOpisSecurityKey(); + $this->registerSerializableClosureSecurityKey(); + } + + /** + * Register the encrypter. + * + * @return void + */ + protected function registerEncrypter() + { + $this->app->singleton('encrypter', function ($app) { + $config = $app->make('config')->get('app'); + + return new Encrypter($this->parseKey($config), $config['cipher']); + }); + } + + /** + * Configure Opis Closure signing for security. + * + * @return void + * + * @deprecated Will be removed in a future Laravel version. + */ + protected function registerOpisSecurityKey() + { + if (\PHP_VERSION_ID < 80100) { + $config = $this->app->make('config')->get('app'); + + if (! class_exists(OpisSerializableClosure::class) || empty($config['key'])) { + return; + } + + OpisSerializableClosure::setSecretKey($this->parseKey($config)); + } + } + + /** + * Configure Serializable Closure signing for security. + * + * @return void + */ + protected function registerSerializableClosureSecurityKey() + { + $config = $this->app->make('config')->get('app'); + + if (! class_exists(SerializableClosure::class) || empty($config['key'])) { + return; + } + + SerializableClosure::setSecretKey($this->parseKey($config)); + } + + /** + * Parse the encryption key. + * + * @param array $config + * @return string + */ + protected function parseKey(array $config) + { + if (Str::startsWith($key = $this->key($config), $prefix = 'base64:')) { + $key = base64_decode(Str::after($key, $prefix)); + } + + return $key; + } + + /** + * Extract the encryption key from the given configuration. + * + * @param array $config + * @return string + * + * @throws \Illuminate\Encryption\MissingAppKeyException + */ + protected function key(array $config) + { + return tap($config['key'], function ($key) { + if (empty($key)) { + throw new MissingAppKeyException; + } + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/MissingAppKeyException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/MissingAppKeyException.php new file mode 100644 index 0000000..d8ffcd1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Encryption/MissingAppKeyException.php @@ -0,0 +1,19 @@ +data = $data; + $this->class = $class; + $this->method = $method; + } + + /** + * Handle the queued job. + * + * @param \Illuminate\Container\Container $container + * @return void + */ + public function handle(Container $container) + { + $this->prepareData(); + + $handler = $this->setJobInstanceIfNecessary( + $this->job, $container->make($this->class) + ); + + $handler->{$this->method}(...array_values($this->data)); + } + + /** + * Set the job instance of the given class if necessary. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param object $instance + * @return object + */ + protected function setJobInstanceIfNecessary(Job $job, $instance) + { + if (in_array(InteractsWithQueue::class, class_uses_recursive($instance))) { + $instance->setJob($job); + } + + return $instance; + } + + /** + * Call the failed method on the job instance. + * + * The event instance and the exception will be passed. + * + * @param \Throwable $e + * @return void + */ + public function failed($e) + { + $this->prepareData(); + + $handler = Container::getInstance()->make($this->class); + + $parameters = array_merge(array_values($this->data), [$e]); + + if (method_exists($handler, 'failed')) { + $handler->failed(...$parameters); + } + } + + /** + * Unserialize the data if needed. + * + * @return void + */ + protected function prepareData() + { + if (is_string($this->data)) { + $this->data = unserialize($this->data); + } + } + + /** + * Get the display name for the queued job. + * + * @return string + */ + public function displayName() + { + return $this->class; + } + + /** + * Prepare the instance for cloning. + * + * @return void + */ + public function __clone() + { + $this->data = array_map(function ($data) { + return is_object($data) ? clone $data : $data; + }, $this->data); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php new file mode 100755 index 0000000..5972a83 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php @@ -0,0 +1,676 @@ +container = $container ?: new Container; + } + + /** + * Register an event listener with the dispatcher. + * + * @param \Closure|string|array $events + * @param \Closure|string|array|null $listener + * @return void + */ + public function listen($events, $listener = null) + { + if ($events instanceof Closure) { + return collect($this->firstClosureParameterTypes($events)) + ->each(function ($event) use ($events) { + $this->listen($event, $events); + }); + } elseif ($events instanceof QueuedClosure) { + return collect($this->firstClosureParameterTypes($events->closure)) + ->each(function ($event) use ($events) { + $this->listen($event, $events->resolve()); + }); + } elseif ($listener instanceof QueuedClosure) { + $listener = $listener->resolve(); + } + + foreach ((array) $events as $event) { + if (Str::contains($event, '*')) { + $this->setupWildcardListen($event, $listener); + } else { + $this->listeners[$event][] = $this->makeListener($listener); + } + } + } + + /** + * Setup a wildcard listener callback. + * + * @param string $event + * @param \Closure|string $listener + * @return void + */ + protected function setupWildcardListen($event, $listener) + { + $this->wildcards[$event][] = $this->makeListener($listener, true); + + $this->wildcardsCache = []; + } + + /** + * Determine if a given event has listeners. + * + * @param string $eventName + * @return bool + */ + public function hasListeners($eventName) + { + return isset($this->listeners[$eventName]) || + isset($this->wildcards[$eventName]) || + $this->hasWildcardListeners($eventName); + } + + /** + * Determine if the given event has any wildcard listeners. + * + * @param string $eventName + * @return bool + */ + public function hasWildcardListeners($eventName) + { + foreach ($this->wildcards as $key => $listeners) { + if (Str::is($key, $eventName)) { + return true; + } + } + + return false; + } + + /** + * Register an event and payload to be fired later. + * + * @param string $event + * @param array $payload + * @return void + */ + public function push($event, $payload = []) + { + $this->listen($event.'_pushed', function () use ($event, $payload) { + $this->dispatch($event, $payload); + }); + } + + /** + * Flush a set of pushed events. + * + * @param string $event + * @return void + */ + public function flush($event) + { + $this->dispatch($event.'_pushed'); + } + + /** + * Register an event subscriber with the dispatcher. + * + * @param object|string $subscriber + * @return void + */ + public function subscribe($subscriber) + { + $subscriber = $this->resolveSubscriber($subscriber); + + $events = $subscriber->subscribe($this); + + if (is_array($events)) { + foreach ($events as $event => $listeners) { + foreach (Arr::wrap($listeners) as $listener) { + if (is_string($listener) && method_exists($subscriber, $listener)) { + $this->listen($event, [get_class($subscriber), $listener]); + + continue; + } + + $this->listen($event, $listener); + } + } + } + } + + /** + * Resolve the subscriber instance. + * + * @param object|string $subscriber + * @return mixed + */ + protected function resolveSubscriber($subscriber) + { + if (is_string($subscriber)) { + return $this->container->make($subscriber); + } + + return $subscriber; + } + + /** + * Fire an event until the first non-null response is returned. + * + * @param string|object $event + * @param mixed $payload + * @return array|null + */ + public function until($event, $payload = []) + { + return $this->dispatch($event, $payload, true); + } + + /** + * Fire an event and call the listeners. + * + * @param string|object $event + * @param mixed $payload + * @param bool $halt + * @return array|null + */ + public function dispatch($event, $payload = [], $halt = false) + { + // When the given "event" is actually an object we will assume it is an event + // object and use the class as the event name and this event itself as the + // payload to the handler, which makes object based events quite simple. + [$event, $payload] = $this->parseEventAndPayload( + $event, $payload + ); + + if ($this->shouldBroadcast($payload)) { + $this->broadcastEvent($payload[0]); + } + + $responses = []; + + foreach ($this->getListeners($event) as $listener) { + $response = $listener($event, $payload); + + // If a response is returned from the listener and event halting is enabled + // we will just return this response, and not call the rest of the event + // listeners. Otherwise we will add the response on the response list. + if ($halt && ! is_null($response)) { + return $response; + } + + // If a boolean false is returned from a listener, we will stop propagating + // the event to any further listeners down in the chain, else we keep on + // looping through the listeners and firing every one in our sequence. + if ($response === false) { + break; + } + + $responses[] = $response; + } + + return $halt ? null : $responses; + } + + /** + * Parse the given event and payload and prepare them for dispatching. + * + * @param mixed $event + * @param mixed $payload + * @return array + */ + protected function parseEventAndPayload($event, $payload) + { + if (is_object($event)) { + [$payload, $event] = [[$event], get_class($event)]; + } + + return [$event, Arr::wrap($payload)]; + } + + /** + * Determine if the payload has a broadcastable event. + * + * @param array $payload + * @return bool + */ + protected function shouldBroadcast(array $payload) + { + return isset($payload[0]) && + $payload[0] instanceof ShouldBroadcast && + $this->broadcastWhen($payload[0]); + } + + /** + * Check if the event should be broadcasted by the condition. + * + * @param mixed $event + * @return bool + */ + protected function broadcastWhen($event) + { + return method_exists($event, 'broadcastWhen') + ? $event->broadcastWhen() : true; + } + + /** + * Broadcast the given event class. + * + * @param \Illuminate\Contracts\Broadcasting\ShouldBroadcast $event + * @return void + */ + protected function broadcastEvent($event) + { + $this->container->make(BroadcastFactory::class)->queue($event); + } + + /** + * Get all of the listeners for a given event name. + * + * @param string $eventName + * @return array + */ + public function getListeners($eventName) + { + $listeners = $this->listeners[$eventName] ?? []; + + $listeners = array_merge( + $listeners, + $this->wildcardsCache[$eventName] ?? $this->getWildcardListeners($eventName) + ); + + return class_exists($eventName, false) + ? $this->addInterfaceListeners($eventName, $listeners) + : $listeners; + } + + /** + * Get the wildcard listeners for the event. + * + * @param string $eventName + * @return array + */ + protected function getWildcardListeners($eventName) + { + $wildcards = []; + + foreach ($this->wildcards as $key => $listeners) { + if (Str::is($key, $eventName)) { + $wildcards = array_merge($wildcards, $listeners); + } + } + + return $this->wildcardsCache[$eventName] = $wildcards; + } + + /** + * Add the listeners for the event's interfaces to the given array. + * + * @param string $eventName + * @param array $listeners + * @return array + */ + protected function addInterfaceListeners($eventName, array $listeners = []) + { + foreach (class_implements($eventName) as $interface) { + if (isset($this->listeners[$interface])) { + foreach ($this->listeners[$interface] as $names) { + $listeners = array_merge($listeners, (array) $names); + } + } + } + + return $listeners; + } + + /** + * Register an event listener with the dispatcher. + * + * @param \Closure|string|array $listener + * @param bool $wildcard + * @return \Closure + */ + public function makeListener($listener, $wildcard = false) + { + if (is_string($listener)) { + return $this->createClassListener($listener, $wildcard); + } + + if (is_array($listener) && isset($listener[0]) && is_string($listener[0])) { + return $this->createClassListener($listener, $wildcard); + } + + return function ($event, $payload) use ($listener, $wildcard) { + if ($wildcard) { + return $listener($event, $payload); + } + + return $listener(...array_values($payload)); + }; + } + + /** + * Create a class based listener using the IoC container. + * + * @param string $listener + * @param bool $wildcard + * @return \Closure + */ + public function createClassListener($listener, $wildcard = false) + { + return function ($event, $payload) use ($listener, $wildcard) { + if ($wildcard) { + return call_user_func($this->createClassCallable($listener), $event, $payload); + } + + $callable = $this->createClassCallable($listener); + + return $callable(...array_values($payload)); + }; + } + + /** + * Create the class based event callable. + * + * @param array|string $listener + * @return callable + */ + protected function createClassCallable($listener) + { + [$class, $method] = is_array($listener) + ? $listener + : $this->parseClassCallable($listener); + + if (! method_exists($class, $method)) { + $method = '__invoke'; + } + + if ($this->handlerShouldBeQueued($class)) { + return $this->createQueuedHandlerCallable($class, $method); + } + + $listener = $this->container->make($class); + + return $this->handlerShouldBeDispatchedAfterDatabaseTransactions($listener) + ? $this->createCallbackForListenerRunningAfterCommits($listener, $method) + : [$listener, $method]; + } + + /** + * Parse the class listener into class and method. + * + * @param string $listener + * @return array + */ + protected function parseClassCallable($listener) + { + return Str::parseCallback($listener, 'handle'); + } + + /** + * Determine if the event handler class should be queued. + * + * @param string $class + * @return bool + */ + protected function handlerShouldBeQueued($class) + { + try { + return (new ReflectionClass($class))->implementsInterface( + ShouldQueue::class + ); + } catch (Exception $e) { + return false; + } + } + + /** + * Create a callable for putting an event handler on the queue. + * + * @param string $class + * @param string $method + * @return \Closure + */ + protected function createQueuedHandlerCallable($class, $method) + { + return function () use ($class, $method) { + $arguments = array_map(function ($a) { + return is_object($a) ? clone $a : $a; + }, func_get_args()); + + if ($this->handlerWantsToBeQueued($class, $arguments)) { + $this->queueHandler($class, $method, $arguments); + } + }; + } + + /** + * Determine if the given event handler should be dispatched after all database transactions have committed. + * + * @param object|mixed $listener + * @return bool + */ + protected function handlerShouldBeDispatchedAfterDatabaseTransactions($listener) + { + return ($listener->afterCommit ?? null) && $this->container->bound('db.transactions'); + } + + /** + * Create a callable for dispatching a listener after database transactions. + * + * @param mixed $listener + * @param string $method + * @return \Closure + */ + protected function createCallbackForListenerRunningAfterCommits($listener, $method) + { + return function () use ($method, $listener) { + $payload = func_get_args(); + + $this->container->make('db.transactions')->addCallback( + function () use ($listener, $method, $payload) { + $listener->$method(...$payload); + } + ); + }; + } + + /** + * Determine if the event handler wants to be queued. + * + * @param string $class + * @param array $arguments + * @return bool + */ + protected function handlerWantsToBeQueued($class, $arguments) + { + $instance = $this->container->make($class); + + if (method_exists($instance, 'shouldQueue')) { + return $instance->shouldQueue($arguments[0]); + } + + return true; + } + + /** + * Queue the handler class. + * + * @param string $class + * @param string $method + * @param array $arguments + * @return void + */ + protected function queueHandler($class, $method, $arguments) + { + [$listener, $job] = $this->createListenerAndJob($class, $method, $arguments); + + $connection = $this->resolveQueue()->connection(method_exists($listener, 'viaConnection') + ? $listener->viaConnection() + : $listener->connection ?? null); + + $queue = method_exists($listener, 'viaQueue') + ? $listener->viaQueue() + : $listener->queue ?? null; + + isset($listener->delay) + ? $connection->laterOn($queue, $listener->delay, $job) + : $connection->pushOn($queue, $job); + } + + /** + * Create the listener and job for a queued listener. + * + * @param string $class + * @param string $method + * @param array $arguments + * @return array + */ + protected function createListenerAndJob($class, $method, $arguments) + { + $listener = (new ReflectionClass($class))->newInstanceWithoutConstructor(); + + return [$listener, $this->propagateListenerOptions( + $listener, new CallQueuedListener($class, $method, $arguments) + )]; + } + + /** + * Propagate listener options to the job. + * + * @param mixed $listener + * @param mixed $job + * @return mixed + */ + protected function propagateListenerOptions($listener, $job) + { + return tap($job, function ($job) use ($listener) { + $job->afterCommit = property_exists($listener, 'afterCommit') ? $listener->afterCommit : null; + $job->backoff = method_exists($listener, 'backoff') ? $listener->backoff() : ($listener->backoff ?? null); + $job->maxExceptions = $listener->maxExceptions ?? null; + $job->retryUntil = method_exists($listener, 'retryUntil') ? $listener->retryUntil() : null; + $job->shouldBeEncrypted = $listener instanceof ShouldBeEncrypted; + $job->timeout = $listener->timeout ?? null; + $job->tries = $listener->tries ?? null; + + $job->through(array_merge( + method_exists($listener, 'middleware') ? $listener->middleware() : [], + $listener->middleware ?? [] + )); + }); + } + + /** + * Remove a set of listeners from the dispatcher. + * + * @param string $event + * @return void + */ + public function forget($event) + { + if (Str::contains($event, '*')) { + unset($this->wildcards[$event]); + } else { + unset($this->listeners[$event]); + } + + foreach ($this->wildcardsCache as $key => $listeners) { + if (Str::is($event, $key)) { + unset($this->wildcardsCache[$key]); + } + } + } + + /** + * Forget all of the pushed listeners. + * + * @return void + */ + public function forgetPushed() + { + foreach ($this->listeners as $key => $value) { + if (Str::endsWith($key, '_pushed')) { + $this->forget($key); + } + } + } + + /** + * Get the queue implementation from the resolver. + * + * @return \Illuminate\Contracts\Queue\Queue + */ + protected function resolveQueue() + { + return call_user_func($this->queueResolver); + } + + /** + * Set the queue resolver implementation. + * + * @param callable $resolver + * @return $this + */ + public function setQueueResolver(callable $resolver) + { + $this->queueResolver = $resolver; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/EventServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/EventServiceProvider.php new file mode 100755 index 0000000..15fb60b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/EventServiceProvider.php @@ -0,0 +1,23 @@ +app->singleton('events', function ($app) { + return (new Dispatcher($app))->setQueueResolver(function () use ($app) { + return $app->make(QueueFactoryContract::class); + }); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/InvokeQueuedClosure.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/InvokeQueuedClosure.php new file mode 100644 index 0000000..bc68b19 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/InvokeQueuedClosure.php @@ -0,0 +1,34 @@ +getClosure(), ...$arguments); + } + + /** + * Handle a job failure. + * + * @param \Laravel\SerializableClosure\SerializableClosure $closure + * @param array $arguments + * @param array $catchCallbacks + * @param \Throwable $exception + * @return void + */ + public function failed($closure, array $arguments, array $catchCallbacks, $exception) + { + $arguments[] = $exception; + + collect($catchCallbacks)->each->__invoke(...$arguments); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/NullDispatcher.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/NullDispatcher.php new file mode 100644 index 0000000..5c539d5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/NullDispatcher.php @@ -0,0 +1,144 @@ +dispatcher = $dispatcher; + } + + /** + * Don't fire an event. + * + * @param string|object $event + * @param mixed $payload + * @param bool $halt + * @return void + */ + public function dispatch($event, $payload = [], $halt = false) + { + // + } + + /** + * Don't register an event and payload to be fired later. + * + * @param string $event + * @param array $payload + * @return void + */ + public function push($event, $payload = []) + { + // + } + + /** + * Don't dispatch an event. + * + * @param string|object $event + * @param mixed $payload + * @return array|null + */ + public function until($event, $payload = []) + { + // + } + + /** + * Register an event listener with the dispatcher. + * + * @param \Closure|string|array $events + * @param \Closure|string|array|null $listener + * @return void + */ + public function listen($events, $listener = null) + { + $this->dispatcher->listen($events, $listener); + } + + /** + * Determine if a given event has listeners. + * + * @param string $eventName + * @return bool + */ + public function hasListeners($eventName) + { + return $this->dispatcher->hasListeners($eventName); + } + + /** + * Register an event subscriber with the dispatcher. + * + * @param object|string $subscriber + * @return void + */ + public function subscribe($subscriber) + { + $this->dispatcher->subscribe($subscriber); + } + + /** + * Flush a set of pushed events. + * + * @param string $event + * @return void + */ + public function flush($event) + { + $this->dispatcher->flush($event); + } + + /** + * Remove a set of listeners from the dispatcher. + * + * @param string $event + * @return void + */ + public function forget($event) + { + $this->dispatcher->forget($event); + } + + /** + * Forget all of the queued listeners. + * + * @return void + */ + public function forgetPushed() + { + $this->dispatcher->forgetPushed(); + } + + /** + * Dynamically pass method calls to the underlying dispatcher. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->forwardCallTo($this->dispatcher, $method, $parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/QueuedClosure.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/QueuedClosure.php new file mode 100644 index 0000000..8259059 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/QueuedClosure.php @@ -0,0 +1,125 @@ +closure = $closure; + } + + /** + * Set the desired connection for the job. + * + * @param string|null $connection + * @return $this + */ + public function onConnection($connection) + { + $this->connection = $connection; + + return $this; + } + + /** + * Set the desired queue for the job. + * + * @param string|null $queue + * @return $this + */ + public function onQueue($queue) + { + $this->queue = $queue; + + return $this; + } + + /** + * Set the desired delay for the job. + * + * @param \DateTimeInterface|\DateInterval|int|null $delay + * @return $this + */ + public function delay($delay) + { + $this->delay = $delay; + + return $this; + } + + /** + * Specify a callback that should be invoked if the queued listener job fails. + * + * @param \Closure $closure + * @return $this + */ + public function catch(Closure $closure) + { + $this->catchCallbacks[] = $closure; + + return $this; + } + + /** + * Resolve the actual event listener callback. + * + * @return \Closure + */ + public function resolve() + { + return function (...$arguments) { + dispatch(new CallQueuedListener(InvokeQueuedClosure::class, 'handle', [ + 'closure' => SerializableClosureFactory::make($this->closure), + 'arguments' => $arguments, + 'catch' => collect($this->catchCallbacks)->map(function ($callback) { + return SerializableClosureFactory::make($callback); + })->all(), + ]))->onConnection($this->connection)->onQueue($this->queue)->delay($this->delay); + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/composer.json new file mode 100755 index 0000000..b77ba2c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/composer.json @@ -0,0 +1,42 @@ +{ + "name": "illuminate/events", + "description": "The Illuminate Events package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/bus": "^8.0", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Events\\": "" + }, + "files": [ + "functions.php" + ] + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/functions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/functions.php new file mode 100644 index 0000000..df1b0fe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Events/functions.php @@ -0,0 +1,18 @@ +key = $key; + $this->expire = $expire; + $this->repository = $repository; + } + + /** + * Load the cache. + * + * @return void + */ + public function load() + { + $contents = $this->repository->get($this->key); + + if (! is_null($contents)) { + $this->setFromStorage($contents); + } + } + + /** + * Persist the cache. + * + * @return void + */ + public function save() + { + $contents = $this->getForStorage(); + + $this->repository->put($this->key, $contents, $this->expire); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php new file mode 100644 index 0000000..8b98ae8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php @@ -0,0 +1,743 @@ +exists($path); + } + + /** + * Get the contents of a file. + * + * @param string $path + * @param bool $lock + * @return string + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function get($path, $lock = false) + { + if ($this->isFile($path)) { + return $lock ? $this->sharedGet($path) : file_get_contents($path); + } + + throw new FileNotFoundException("File does not exist at path {$path}."); + } + + /** + * Get contents of a file with shared access. + * + * @param string $path + * @return string + */ + public function sharedGet($path) + { + $contents = ''; + + $handle = fopen($path, 'rb'); + + if ($handle) { + try { + if (flock($handle, LOCK_SH)) { + clearstatcache(true, $path); + + $contents = fread($handle, $this->size($path) ?: 1); + + flock($handle, LOCK_UN); + } + } finally { + fclose($handle); + } + } + + return $contents; + } + + /** + * Get the returned value of a file. + * + * @param string $path + * @param array $data + * @return mixed + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function getRequire($path, array $data = []) + { + if ($this->isFile($path)) { + $__path = $path; + $__data = $data; + + return (static function () use ($__path, $__data) { + extract($__data, EXTR_SKIP); + + return require $__path; + })(); + } + + throw new FileNotFoundException("File does not exist at path {$path}."); + } + + /** + * Require the given file once. + * + * @param string $path + * @param array $data + * @return mixed + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function requireOnce($path, array $data = []) + { + if ($this->isFile($path)) { + $__path = $path; + $__data = $data; + + return (static function () use ($__path, $__data) { + extract($__data, EXTR_SKIP); + + return require_once $__path; + })(); + } + + throw new FileNotFoundException("File does not exist at path {$path}."); + } + + /** + * Get the contents of a file one line at a time. + * + * @param string $path + * @return \Illuminate\Support\LazyCollection + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function lines($path) + { + if (! $this->isFile($path)) { + throw new FileNotFoundException( + "File does not exist at path {$path}." + ); + } + + return LazyCollection::make(function () use ($path) { + $file = new SplFileObject($path); + + $file->setFlags(SplFileObject::DROP_NEW_LINE); + + while (! $file->eof()) { + yield $file->fgets(); + } + }); + } + + /** + * Get the MD5 hash of the file at the given path. + * + * @param string $path + * @return string + */ + public function hash($path) + { + return md5_file($path); + } + + /** + * Write the contents of a file. + * + * @param string $path + * @param string $contents + * @param bool $lock + * @return int|bool + */ + public function put($path, $contents, $lock = false) + { + return file_put_contents($path, $contents, $lock ? LOCK_EX : 0); + } + + /** + * Write the contents of a file, replacing it atomically if it already exists. + * + * @param string $path + * @param string $content + * @return void + */ + public function replace($path, $content) + { + // If the path already exists and is a symlink, get the real path... + clearstatcache(true, $path); + + $path = realpath($path) ?: $path; + + $tempPath = tempnam(dirname($path), basename($path)); + + // Fix permissions of tempPath because `tempnam()` creates it with permissions set to 0600... + chmod($tempPath, 0777 - umask()); + + file_put_contents($tempPath, $content); + + rename($tempPath, $path); + } + + /** + * Replace a given string within a given file. + * + * @param array|string $search + * @param array|string $replace + * @param string $path + * @return void + */ + public function replaceInFile($search, $replace, $path) + { + file_put_contents($path, str_replace($search, $replace, file_get_contents($path))); + } + + /** + * Prepend to a file. + * + * @param string $path + * @param string $data + * @return int + */ + public function prepend($path, $data) + { + if ($this->exists($path)) { + return $this->put($path, $data.$this->get($path)); + } + + return $this->put($path, $data); + } + + /** + * Append to a file. + * + * @param string $path + * @param string $data + * @return int + */ + public function append($path, $data) + { + return file_put_contents($path, $data, FILE_APPEND); + } + + /** + * Get or set UNIX mode of a file or directory. + * + * @param string $path + * @param int|null $mode + * @return mixed + */ + public function chmod($path, $mode = null) + { + if ($mode) { + return chmod($path, $mode); + } + + return substr(sprintf('%o', fileperms($path)), -4); + } + + /** + * Delete the file at a given path. + * + * @param string|array $paths + * @return bool + */ + public function delete($paths) + { + $paths = is_array($paths) ? $paths : func_get_args(); + + $success = true; + + foreach ($paths as $path) { + try { + if (@unlink($path)) { + clearstatcache(false, $path); + } else { + $success = false; + } + } catch (ErrorException $e) { + $success = false; + } + } + + return $success; + } + + /** + * Move a file to a new location. + * + * @param string $path + * @param string $target + * @return bool + */ + public function move($path, $target) + { + return rename($path, $target); + } + + /** + * Copy a file to a new location. + * + * @param string $path + * @param string $target + * @return bool + */ + public function copy($path, $target) + { + return copy($path, $target); + } + + /** + * Create a symlink to the target file or directory. On Windows, a hard link is created if the target is a file. + * + * @param string $target + * @param string $link + * @return void + */ + public function link($target, $link) + { + if (! windows_os()) { + return symlink($target, $link); + } + + $mode = $this->isDirectory($target) ? 'J' : 'H'; + + exec("mklink /{$mode} ".escapeshellarg($link).' '.escapeshellarg($target)); + } + + /** + * Create a relative symlink to the target file or directory. + * + * @param string $target + * @param string $link + * @return void + * + * @throws \RuntimeException + */ + public function relativeLink($target, $link) + { + if (! class_exists(SymfonyFilesystem::class)) { + throw new RuntimeException( + 'To enable support for relative links, please install the symfony/filesystem package.' + ); + } + + $relativeTarget = (new SymfonyFilesystem)->makePathRelative($target, dirname($link)); + + $this->link($relativeTarget, $link); + } + + /** + * Extract the file name from a file path. + * + * @param string $path + * @return string + */ + public function name($path) + { + return pathinfo($path, PATHINFO_FILENAME); + } + + /** + * Extract the trailing name component from a file path. + * + * @param string $path + * @return string + */ + public function basename($path) + { + return pathinfo($path, PATHINFO_BASENAME); + } + + /** + * Extract the parent directory from a file path. + * + * @param string $path + * @return string + */ + public function dirname($path) + { + return pathinfo($path, PATHINFO_DIRNAME); + } + + /** + * Extract the file extension from a file path. + * + * @param string $path + * @return string + */ + public function extension($path) + { + return pathinfo($path, PATHINFO_EXTENSION); + } + + /** + * Guess the file extension from the mime-type of a given file. + * + * @param string $path + * @return string|null + * + * @throws \RuntimeException + */ + public function guessExtension($path) + { + if (! class_exists(MimeTypes::class)) { + throw new RuntimeException( + 'To enable support for guessing extensions, please install the symfony/mime package.' + ); + } + + return (new MimeTypes)->getExtensions($this->mimeType($path))[0] ?? null; + } + + /** + * Get the file type of a given file. + * + * @param string $path + * @return string + */ + public function type($path) + { + return filetype($path); + } + + /** + * Get the mime-type of a given file. + * + * @param string $path + * @return string|false + */ + public function mimeType($path) + { + return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path); + } + + /** + * Get the file size of a given file. + * + * @param string $path + * @return int + */ + public function size($path) + { + return filesize($path); + } + + /** + * Get the file's last modification time. + * + * @param string $path + * @return int + */ + public function lastModified($path) + { + return filemtime($path); + } + + /** + * Determine if the given path is a directory. + * + * @param string $directory + * @return bool + */ + public function isDirectory($directory) + { + return is_dir($directory); + } + + /** + * Determine if the given path is readable. + * + * @param string $path + * @return bool + */ + public function isReadable($path) + { + return is_readable($path); + } + + /** + * Determine if the given path is writable. + * + * @param string $path + * @return bool + */ + public function isWritable($path) + { + return is_writable($path); + } + + /** + * Determine if the given path is a file. + * + * @param string $file + * @return bool + */ + public function isFile($file) + { + return is_file($file); + } + + /** + * Find path names matching a given pattern. + * + * @param string $pattern + * @param int $flags + * @return array + */ + public function glob($pattern, $flags = 0) + { + return glob($pattern, $flags); + } + + /** + * Get an array of all files in a directory. + * + * @param string $directory + * @param bool $hidden + * @return \Symfony\Component\Finder\SplFileInfo[] + */ + public function files($directory, $hidden = false) + { + return iterator_to_array( + Finder::create()->files()->ignoreDotFiles(! $hidden)->in($directory)->depth(0)->sortByName(), + false + ); + } + + /** + * Get all of the files from the given directory (recursive). + * + * @param string $directory + * @param bool $hidden + * @return \Symfony\Component\Finder\SplFileInfo[] + */ + public function allFiles($directory, $hidden = false) + { + return iterator_to_array( + Finder::create()->files()->ignoreDotFiles(! $hidden)->in($directory)->sortByName(), + false + ); + } + + /** + * Get all of the directories within a given directory. + * + * @param string $directory + * @return array + */ + public function directories($directory) + { + $directories = []; + + foreach (Finder::create()->in($directory)->directories()->depth(0)->sortByName() as $dir) { + $directories[] = $dir->getPathname(); + } + + return $directories; + } + + /** + * Ensure a directory exists. + * + * @param string $path + * @param int $mode + * @param bool $recursive + * @return void + */ + public function ensureDirectoryExists($path, $mode = 0755, $recursive = true) + { + if (! $this->isDirectory($path)) { + $this->makeDirectory($path, $mode, $recursive); + } + } + + /** + * Create a directory. + * + * @param string $path + * @param int $mode + * @param bool $recursive + * @param bool $force + * @return bool + */ + public function makeDirectory($path, $mode = 0755, $recursive = false, $force = false) + { + if ($force) { + return @mkdir($path, $mode, $recursive); + } + + return mkdir($path, $mode, $recursive); + } + + /** + * Move a directory. + * + * @param string $from + * @param string $to + * @param bool $overwrite + * @return bool + */ + public function moveDirectory($from, $to, $overwrite = false) + { + if ($overwrite && $this->isDirectory($to) && ! $this->deleteDirectory($to)) { + return false; + } + + return @rename($from, $to) === true; + } + + /** + * Copy a directory from one location to another. + * + * @param string $directory + * @param string $destination + * @param int|null $options + * @return bool + */ + public function copyDirectory($directory, $destination, $options = null) + { + if (! $this->isDirectory($directory)) { + return false; + } + + $options = $options ?: FilesystemIterator::SKIP_DOTS; + + // If the destination directory does not actually exist, we will go ahead and + // create it recursively, which just gets the destination prepared to copy + // the files over. Once we make the directory we'll proceed the copying. + $this->ensureDirectoryExists($destination, 0777); + + $items = new FilesystemIterator($directory, $options); + + foreach ($items as $item) { + // As we spin through items, we will check to see if the current file is actually + // a directory or a file. When it is actually a directory we will need to call + // back into this function recursively to keep copying these nested folders. + $target = $destination.'/'.$item->getBasename(); + + if ($item->isDir()) { + $path = $item->getPathname(); + + if (! $this->copyDirectory($path, $target, $options)) { + return false; + } + } + + // If the current items is just a regular file, we will just copy this to the new + // location and keep looping. If for some reason the copy fails we'll bail out + // and return false, so the developer is aware that the copy process failed. + else { + if (! $this->copy($item->getPathname(), $target)) { + return false; + } + } + } + + return true; + } + + /** + * Recursively delete a directory. + * + * The directory itself may be optionally preserved. + * + * @param string $directory + * @param bool $preserve + * @return bool + */ + public function deleteDirectory($directory, $preserve = false) + { + if (! $this->isDirectory($directory)) { + return false; + } + + $items = new FilesystemIterator($directory); + + foreach ($items as $item) { + // If the item is a directory, we can just recurse into the function and + // delete that sub-directory otherwise we'll just delete the file and + // keep iterating through each file until the directory is cleaned. + if ($item->isDir() && ! $item->isLink()) { + $this->deleteDirectory($item->getPathname()); + } + + // If the item is just a file, we can go ahead and delete it since we're + // just looping through and waxing all of the files in this directory + // and calling directories recursively, so we delete the real path. + else { + $this->delete($item->getPathname()); + } + } + + if (! $preserve) { + @rmdir($directory); + } + + return true; + } + + /** + * Remove all of the directories within a given directory. + * + * @param string $directory + * @return bool + */ + public function deleteDirectories($directory) + { + $allDirectories = $this->directories($directory); + + if (! empty($allDirectories)) { + foreach ($allDirectories as $directoryName) { + $this->deleteDirectory($directoryName); + } + + return true; + } + + return false; + } + + /** + * Empty the specified directory of all files and folders. + * + * @param string $directory + * @return bool + */ + public function cleanDirectory($directory) + { + return $this->deleteDirectory($directory, true); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php new file mode 100644 index 0000000..a9fd524 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php @@ -0,0 +1,829 @@ +driver = $driver; + } + + /** + * Assert that the given file exists. + * + * @param string|array $path + * @param string|null $content + * @return $this + */ + public function assertExists($path, $content = null) + { + clearstatcache(); + + $paths = Arr::wrap($path); + + foreach ($paths as $path) { + PHPUnit::assertTrue( + $this->exists($path), "Unable to find a file at path [{$path}]." + ); + + if (! is_null($content)) { + $actual = $this->get($path); + + PHPUnit::assertSame( + $content, + $actual, + "File [{$path}] was found, but content [{$actual}] does not match [{$content}]." + ); + } + } + + return $this; + } + + /** + * Assert that the given file does not exist. + * + * @param string|array $path + * @return $this + */ + public function assertMissing($path) + { + clearstatcache(); + + $paths = Arr::wrap($path); + + foreach ($paths as $path) { + PHPUnit::assertFalse( + $this->exists($path), "Found unexpected file at path [{$path}]." + ); + } + + return $this; + } + + /** + * Determine if a file exists. + * + * @param string $path + * @return bool + */ + public function exists($path) + { + return $this->driver->has($path); + } + + /** + * Determine if a file or directory is missing. + * + * @param string $path + * @return bool + */ + public function missing($path) + { + return ! $this->exists($path); + } + + /** + * Get the full path for the file at the given "short" path. + * + * @param string $path + * @return string + */ + public function path($path) + { + $adapter = $this->driver->getAdapter(); + + if ($adapter instanceof CachedAdapter) { + $adapter = $adapter->getAdapter(); + } + + return $adapter->getPathPrefix().$path; + } + + /** + * Get the contents of a file. + * + * @param string $path + * @return string + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function get($path) + { + try { + return $this->driver->read($path); + } catch (FileNotFoundException $e) { + throw new ContractFileNotFoundException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * Create a streamed response for a given file. + * + * @param string $path + * @param string|null $name + * @param array|null $headers + * @param string|null $disposition + * @return \Symfony\Component\HttpFoundation\StreamedResponse + */ + public function response($path, $name = null, array $headers = [], $disposition = 'inline') + { + $response = new StreamedResponse; + + $filename = $name ?? basename($path); + + $disposition = $response->headers->makeDisposition( + $disposition, $filename, $this->fallbackName($filename) + ); + + $response->headers->replace($headers + [ + 'Content-Type' => $this->mimeType($path), + 'Content-Length' => $this->size($path), + 'Content-Disposition' => $disposition, + ]); + + $response->setCallback(function () use ($path) { + $stream = $this->readStream($path); + fpassthru($stream); + fclose($stream); + }); + + return $response; + } + + /** + * Create a streamed download response for a given file. + * + * @param string $path + * @param string|null $name + * @param array|null $headers + * @return \Symfony\Component\HttpFoundation\StreamedResponse + */ + public function download($path, $name = null, array $headers = []) + { + return $this->response($path, $name, $headers, 'attachment'); + } + + /** + * Convert the string to ASCII characters that are equivalent to the given name. + * + * @param string $name + * @return string + */ + protected function fallbackName($name) + { + return str_replace('%', '', Str::ascii($name)); + } + + /** + * Write the contents of a file. + * + * @param string $path + * @param \Psr\Http\Message\StreamInterface|\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|resource $contents + * @param mixed $options + * @return bool + */ + public function put($path, $contents, $options = []) + { + $options = is_string($options) + ? ['visibility' => $options] + : (array) $options; + + // If the given contents is actually a file or uploaded file instance than we will + // automatically store the file using a stream. This provides a convenient path + // for the developer to store streams without managing them manually in code. + if ($contents instanceof File || + $contents instanceof UploadedFile) { + return $this->putFile($path, $contents, $options); + } + + if ($contents instanceof StreamInterface) { + return $this->driver->putStream($path, $contents->detach(), $options); + } + + return is_resource($contents) + ? $this->driver->putStream($path, $contents, $options) + : $this->driver->put($path, $contents, $options); + } + + /** + * Store the uploaded file on the disk. + * + * @param string $path + * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $file + * @param mixed $options + * @return string|false + */ + public function putFile($path, $file, $options = []) + { + $file = is_string($file) ? new File($file) : $file; + + return $this->putFileAs($path, $file, $file->hashName(), $options); + } + + /** + * Store the uploaded file on the disk with a given name. + * + * @param string $path + * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $file + * @param string $name + * @param mixed $options + * @return string|false + */ + public function putFileAs($path, $file, $name, $options = []) + { + $stream = fopen(is_string($file) ? $file : $file->getRealPath(), 'r'); + + // Next, we will format the path of the file and store the file using a stream since + // they provide better performance than alternatives. Once we write the file this + // stream will get closed automatically by us so the developer doesn't have to. + $result = $this->put( + $path = trim($path.'/'.$name, '/'), $stream, $options + ); + + if (is_resource($stream)) { + fclose($stream); + } + + return $result ? $path : false; + } + + /** + * Get the visibility for the given path. + * + * @param string $path + * @return string + */ + public function getVisibility($path) + { + if ($this->driver->getVisibility($path) == AdapterInterface::VISIBILITY_PUBLIC) { + return FilesystemContract::VISIBILITY_PUBLIC; + } + + return FilesystemContract::VISIBILITY_PRIVATE; + } + + /** + * Set the visibility for the given path. + * + * @param string $path + * @param string $visibility + * @return bool + */ + public function setVisibility($path, $visibility) + { + return $this->driver->setVisibility($path, $this->parseVisibility($visibility)); + } + + /** + * Prepend to a file. + * + * @param string $path + * @param string $data + * @param string $separator + * @return bool + */ + public function prepend($path, $data, $separator = PHP_EOL) + { + if ($this->exists($path)) { + return $this->put($path, $data.$separator.$this->get($path)); + } + + return $this->put($path, $data); + } + + /** + * Append to a file. + * + * @param string $path + * @param string $data + * @param string $separator + * @return bool + */ + public function append($path, $data, $separator = PHP_EOL) + { + if ($this->exists($path)) { + return $this->put($path, $this->get($path).$separator.$data); + } + + return $this->put($path, $data); + } + + /** + * Delete the file at a given path. + * + * @param string|array $paths + * @return bool + */ + public function delete($paths) + { + $paths = is_array($paths) ? $paths : func_get_args(); + + $success = true; + + foreach ($paths as $path) { + try { + if (! $this->driver->delete($path)) { + $success = false; + } + } catch (FileNotFoundException $e) { + $success = false; + } + } + + return $success; + } + + /** + * Copy a file to a new location. + * + * @param string $from + * @param string $to + * @return bool + */ + public function copy($from, $to) + { + return $this->driver->copy($from, $to); + } + + /** + * Move a file to a new location. + * + * @param string $from + * @param string $to + * @return bool + */ + public function move($from, $to) + { + return $this->driver->rename($from, $to); + } + + /** + * Get the file size of a given file. + * + * @param string $path + * @return int + */ + public function size($path) + { + return $this->driver->getSize($path); + } + + /** + * Get the mime-type of a given file. + * + * @param string $path + * @return string|false + */ + public function mimeType($path) + { + return $this->driver->getMimetype($path); + } + + /** + * Get the file's last modification time. + * + * @param string $path + * @return int + */ + public function lastModified($path) + { + return $this->driver->getTimestamp($path); + } + + /** + * Get the URL for the file at the given path. + * + * @param string $path + * @return string + * + * @throws \RuntimeException + */ + public function url($path) + { + $adapter = $this->driver->getAdapter(); + + if ($adapter instanceof CachedAdapter) { + $adapter = $adapter->getAdapter(); + } + + if (method_exists($adapter, 'getUrl')) { + return $adapter->getUrl($path); + } elseif (method_exists($this->driver, 'getUrl')) { + return $this->driver->getUrl($path); + } elseif ($adapter instanceof AwsS3Adapter) { + return $this->getAwsUrl($adapter, $path); + } elseif ($adapter instanceof Ftp || $adapter instanceof Sftp) { + return $this->getFtpUrl($path); + } elseif ($adapter instanceof LocalAdapter) { + return $this->getLocalUrl($path); + } else { + throw new RuntimeException('This driver does not support retrieving URLs.'); + } + } + + /** + * {@inheritdoc} + */ + public function readStream($path) + { + try { + return $this->driver->readStream($path) ?: null; + } catch (FileNotFoundException $e) { + throw new ContractFileNotFoundException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * {@inheritdoc} + */ + public function writeStream($path, $resource, array $options = []) + { + try { + return $this->driver->writeStream($path, $resource, $options); + } catch (FileExistsException $e) { + throw new ContractFileExistsException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * Get the URL for the file at the given path. + * + * @param \League\Flysystem\AwsS3v3\AwsS3Adapter $adapter + * @param string $path + * @return string + */ + protected function getAwsUrl($adapter, $path) + { + // If an explicit base URL has been set on the disk configuration then we will use + // it as the base URL instead of the default path. This allows the developer to + // have full control over the base path for this filesystem's generated URLs. + if (! is_null($url = $this->driver->getConfig()->get('url'))) { + return $this->concatPathToUrl($url, $adapter->getPathPrefix().$path); + } + + return $adapter->getClient()->getObjectUrl( + $adapter->getBucket(), $adapter->getPathPrefix().$path + ); + } + + /** + * Get the URL for the file at the given path. + * + * @param string $path + * @return string + */ + protected function getFtpUrl($path) + { + $config = $this->driver->getConfig(); + + return $config->has('url') + ? $this->concatPathToUrl($config->get('url'), $path) + : $path; + } + + /** + * Get the URL for the file at the given path. + * + * @param string $path + * @return string + */ + protected function getLocalUrl($path) + { + $config = $this->driver->getConfig(); + + // If an explicit base URL has been set on the disk configuration then we will use + // it as the base URL instead of the default path. This allows the developer to + // have full control over the base path for this filesystem's generated URLs. + if ($config->has('url')) { + return $this->concatPathToUrl($config->get('url'), $path); + } + + $path = '/storage/'.$path; + + // If the path contains "storage/public", it probably means the developer is using + // the default disk to generate the path instead of the "public" disk like they + // are really supposed to use. We will remove the public from this path here. + if (Str::contains($path, '/storage/public/')) { + return Str::replaceFirst('/public/', '/', $path); + } + + return $path; + } + + /** + * Get a temporary URL for the file at the given path. + * + * @param string $path + * @param \DateTimeInterface $expiration + * @param array $options + * @return string + * + * @throws \RuntimeException + */ + public function temporaryUrl($path, $expiration, array $options = []) + { + $adapter = $this->driver->getAdapter(); + + if ($adapter instanceof CachedAdapter) { + $adapter = $adapter->getAdapter(); + } + + if (method_exists($adapter, 'getTemporaryUrl')) { + return $adapter->getTemporaryUrl($path, $expiration, $options); + } + + if ($this->temporaryUrlCallback) { + return $this->temporaryUrlCallback->bindTo($this, static::class)( + $path, $expiration, $options + ); + } + + if ($adapter instanceof AwsS3Adapter) { + return $this->getAwsTemporaryUrl($adapter, $path, $expiration, $options); + } + + throw new RuntimeException('This driver does not support creating temporary URLs.'); + } + + /** + * Get a temporary URL for the file at the given path. + * + * @param \League\Flysystem\AwsS3v3\AwsS3Adapter $adapter + * @param string $path + * @param \DateTimeInterface $expiration + * @param array $options + * @return string + */ + public function getAwsTemporaryUrl($adapter, $path, $expiration, $options) + { + $client = $adapter->getClient(); + + $command = $client->getCommand('GetObject', array_merge([ + 'Bucket' => $adapter->getBucket(), + 'Key' => $adapter->getPathPrefix().$path, + ], $options)); + + $uri = $client->createPresignedRequest( + $command, $expiration + )->getUri(); + + // If an explicit base URL has been set on the disk configuration then we will use + // it as the base URL instead of the default path. This allows the developer to + // have full control over the base path for this filesystem's generated URLs. + if (! is_null($url = $this->driver->getConfig()->get('temporary_url'))) { + $uri = $this->replaceBaseUrl($uri, $url); + } + + return (string) $uri; + } + + /** + * Concatenate a path to a URL. + * + * @param string $url + * @param string $path + * @return string + */ + protected function concatPathToUrl($url, $path) + { + return rtrim($url, '/').'/'.ltrim($path, '/'); + } + + /** + * Replace the scheme, host and port of the given UriInterface with values from the given URL. + * + * @param \Psr\Http\Message\UriInterface $uri + * @param string $url + * @return \Psr\Http\Message\UriInterface + */ + protected function replaceBaseUrl($uri, $url) + { + $parsed = parse_url($url); + + return $uri + ->withScheme($parsed['scheme']) + ->withHost($parsed['host']) + ->withPort($parsed['port'] ?? null); + } + + /** + * Get an array of all files in a directory. + * + * @param string|null $directory + * @param bool $recursive + * @return array + */ + public function files($directory = null, $recursive = false) + { + $contents = $this->driver->listContents($directory ?? '', $recursive); + + return $this->filterContentsByType($contents, 'file'); + } + + /** + * Get all of the files from the given directory (recursive). + * + * @param string|null $directory + * @return array + */ + public function allFiles($directory = null) + { + return $this->files($directory, true); + } + + /** + * Get all of the directories within a given directory. + * + * @param string|null $directory + * @param bool $recursive + * @return array + */ + public function directories($directory = null, $recursive = false) + { + $contents = $this->driver->listContents($directory ?? '', $recursive); + + return $this->filterContentsByType($contents, 'dir'); + } + + /** + * Get all (recursive) of the directories within a given directory. + * + * @param string|null $directory + * @return array + */ + public function allDirectories($directory = null) + { + return $this->directories($directory, true); + } + + /** + * Create a directory. + * + * @param string $path + * @return bool + */ + public function makeDirectory($path) + { + return $this->driver->createDir($path); + } + + /** + * Recursively delete a directory. + * + * @param string $directory + * @return bool + */ + public function deleteDirectory($directory) + { + return $this->driver->deleteDir($directory); + } + + /** + * Flush the Flysystem cache. + * + * @return void + */ + public function flushCache() + { + $adapter = $this->driver->getAdapter(); + + if ($adapter instanceof CachedAdapter) { + $adapter->getCache()->flush(); + } + } + + /** + * Get the Flysystem driver. + * + * @return \League\Flysystem\FilesystemInterface + */ + public function getDriver() + { + return $this->driver; + } + + /** + * Filter directory contents by type. + * + * @param array $contents + * @param string $type + * @return array + */ + protected function filterContentsByType($contents, $type) + { + return Collection::make($contents) + ->where('type', $type) + ->pluck('path') + ->values() + ->all(); + } + + /** + * Parse the given visibility value. + * + * @param string|null $visibility + * @return string|null + * + * @throws \InvalidArgumentException + */ + protected function parseVisibility($visibility) + { + if (is_null($visibility)) { + return; + } + + switch ($visibility) { + case FilesystemContract::VISIBILITY_PUBLIC: + return AdapterInterface::VISIBILITY_PUBLIC; + case FilesystemContract::VISIBILITY_PRIVATE: + return AdapterInterface::VISIBILITY_PRIVATE; + } + + throw new InvalidArgumentException("Unknown visibility: {$visibility}."); + } + + /** + * Define a custom temporary URL builder callback. + * + * @param \Closure $callback + * @return void + */ + public function buildTemporaryUrlsUsing(Closure $callback) + { + $this->temporaryUrlCallback = $callback; + } + + /** + * Pass dynamic methods call onto Flysystem. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, array $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + return $this->driver->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemManager.php new file mode 100644 index 0000000..684c487 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemManager.php @@ -0,0 +1,413 @@ +app = $app; + } + + /** + * Get a filesystem instance. + * + * @param string|null $name + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function drive($name = null) + { + return $this->disk($name); + } + + /** + * Get a filesystem instance. + * + * @param string|null $name + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function disk($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + return $this->disks[$name] = $this->get($name); + } + + /** + * Get a default cloud filesystem instance. + * + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function cloud() + { + $name = $this->getDefaultCloudDriver(); + + return $this->disks[$name] = $this->get($name); + } + + /** + * Build an on-demand disk. + * + * @param string|array $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function build($config) + { + return $this->resolve('ondemand', is_array($config) ? $config : [ + 'driver' => 'local', + 'root' => $config, + ]); + } + + /** + * Attempt to get the disk from the local cache. + * + * @param string $name + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + protected function get($name) + { + return $this->disks[$name] ?? $this->resolve($name); + } + + /** + * Resolve the given disk. + * + * @param string $name + * @param array|null $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + * + * @throws \InvalidArgumentException + */ + protected function resolve($name, $config = null) + { + $config = $config ?? $this->getConfig($name); + + if (empty($config['driver'])) { + throw new InvalidArgumentException("Disk [{$name}] does not have a configured driver."); + } + + $name = $config['driver']; + + if (isset($this->customCreators[$name])) { + return $this->callCustomCreator($config); + } + + $driverMethod = 'create'.ucfirst($name).'Driver'; + + if (! method_exists($this, $driverMethod)) { + throw new InvalidArgumentException("Driver [{$name}] is not supported."); + } + + return $this->{$driverMethod}($config); + } + + /** + * Call a custom driver creator. + * + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + protected function callCustomCreator(array $config) + { + $driver = $this->customCreators[$config['driver']]($this->app, $config); + + if ($driver instanceof FilesystemInterface) { + return $this->adapt($driver); + } + + return $driver; + } + + /** + * Create an instance of the local driver. + * + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function createLocalDriver(array $config) + { + $permissions = $config['permissions'] ?? []; + + $links = ($config['links'] ?? null) === 'skip' + ? LocalAdapter::SKIP_LINKS + : LocalAdapter::DISALLOW_LINKS; + + return $this->adapt($this->createFlysystem(new LocalAdapter( + $config['root'], $config['lock'] ?? LOCK_EX, $links, $permissions + ), $config)); + } + + /** + * Create an instance of the ftp driver. + * + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function createFtpDriver(array $config) + { + return $this->adapt($this->createFlysystem( + new FtpAdapter($config), $config + )); + } + + /** + * Create an instance of the sftp driver. + * + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public function createSftpDriver(array $config) + { + return $this->adapt($this->createFlysystem( + new SftpAdapter($config), $config + )); + } + + /** + * Create an instance of the Amazon S3 driver. + * + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Cloud + */ + public function createS3Driver(array $config) + { + $s3Config = $this->formatS3Config($config); + + $root = $s3Config['root'] ?? null; + + $options = $config['options'] ?? []; + + $streamReads = $config['stream_reads'] ?? false; + + return $this->adapt($this->createFlysystem( + new S3Adapter(new S3Client($s3Config), $s3Config['bucket'], $root, $options, $streamReads), $config + )); + } + + /** + * Format the given S3 configuration with the default options. + * + * @param array $config + * @return array + */ + protected function formatS3Config(array $config) + { + $config += ['version' => 'latest']; + + if (! empty($config['key']) && ! empty($config['secret'])) { + $config['credentials'] = Arr::only($config, ['key', 'secret', 'token']); + } + + return $config; + } + + /** + * Create a Flysystem instance with the given adapter. + * + * @param \League\Flysystem\AdapterInterface $adapter + * @param array $config + * @return \League\Flysystem\FilesystemInterface + */ + protected function createFlysystem(AdapterInterface $adapter, array $config) + { + $cache = Arr::pull($config, 'cache'); + + $config = Arr::only($config, ['visibility', 'disable_asserts', 'url', 'temporary_url']); + + if ($cache) { + $adapter = new CachedAdapter($adapter, $this->createCacheStore($cache)); + } + + return new Flysystem($adapter, count($config) > 0 ? $config : null); + } + + /** + * Create a cache store instance. + * + * @param mixed $config + * @return \League\Flysystem\Cached\CacheInterface + * + * @throws \InvalidArgumentException + */ + protected function createCacheStore($config) + { + if ($config === true) { + return new MemoryStore; + } + + return new Cache( + $this->app['cache']->store($config['store']), + $config['prefix'] ?? 'flysystem', + $config['expire'] ?? null + ); + } + + /** + * Adapt the filesystem implementation. + * + * @param \League\Flysystem\FilesystemInterface $filesystem + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + protected function adapt(FilesystemInterface $filesystem) + { + return new FilesystemAdapter($filesystem); + } + + /** + * Set the given disk instance. + * + * @param string $name + * @param mixed $disk + * @return $this + */ + public function set($name, $disk) + { + $this->disks[$name] = $disk; + + return $this; + } + + /** + * Get the filesystem connection configuration. + * + * @param string $name + * @return array + */ + protected function getConfig($name) + { + return $this->app['config']["filesystems.disks.{$name}"] ?: []; + } + + /** + * Get the default driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->app['config']['filesystems.default']; + } + + /** + * Get the default cloud driver name. + * + * @return string + */ + public function getDefaultCloudDriver() + { + return $this->app['config']['filesystems.cloud'] ?? 's3'; + } + + /** + * Unset the given disk instances. + * + * @param array|string $disk + * @return $this + */ + public function forgetDisk($disk) + { + foreach ((array) $disk as $diskName) { + unset($this->disks[$diskName]); + } + + return $this; + } + + /** + * Disconnect the given disk and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?? $this->getDefaultDriver(); + + unset($this->disks[$name]); + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback; + + return $this; + } + + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication($app) + { + $this->app = $app; + + return $this; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->disk()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemServiceProvider.php new file mode 100644 index 0000000..ff348a2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemServiceProvider.php @@ -0,0 +1,82 @@ +registerNativeFilesystem(); + + $this->registerFlysystem(); + } + + /** + * Register the native filesystem implementation. + * + * @return void + */ + protected function registerNativeFilesystem() + { + $this->app->singleton('files', function () { + return new Filesystem; + }); + } + + /** + * Register the driver based filesystem. + * + * @return void + */ + protected function registerFlysystem() + { + $this->registerManager(); + + $this->app->singleton('filesystem.disk', function ($app) { + return $app['filesystem']->disk($this->getDefaultDriver()); + }); + + $this->app->singleton('filesystem.cloud', function ($app) { + return $app['filesystem']->disk($this->getCloudDriver()); + }); + } + + /** + * Register the filesystem manager. + * + * @return void + */ + protected function registerManager() + { + $this->app->singleton('filesystem', function ($app) { + return new FilesystemManager($app); + }); + } + + /** + * Get the default file driver. + * + * @return string + */ + protected function getDefaultDriver() + { + return $this->app['config']['filesystems.default']; + } + + /** + * Get the default cloud based file driver. + * + * @return string + */ + protected function getCloudDriver() + { + return $this->app['config']['filesystems.cloud']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/LockableFile.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/LockableFile.php new file mode 100644 index 0000000..58bd934 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/LockableFile.php @@ -0,0 +1,194 @@ +path = $path; + + $this->ensureDirectoryExists($path); + $this->createResource($path, $mode); + } + + /** + * Create the file's directory if necessary. + * + * @param string $path + * @return void + */ + protected function ensureDirectoryExists($path) + { + if (! file_exists(dirname($path))) { + @mkdir(dirname($path), 0777, true); + } + } + + /** + * Create the file resource. + * + * @param string $path + * @param string $mode + * @return void + * + * @throws \Exception + */ + protected function createResource($path, $mode) + { + $this->handle = @fopen($path, $mode); + + if (! $this->handle) { + throw new Exception('Unable to create lockable file: '.$path.'. Please ensure you have permission to create files in this location.'); + } + } + + /** + * Read the file contents. + * + * @param int|null $length + * @return string + */ + public function read($length = null) + { + clearstatcache(true, $this->path); + + return fread($this->handle, $length ?? ($this->size() ?: 1)); + } + + /** + * Get the file size. + * + * @return int + */ + public function size() + { + return filesize($this->path); + } + + /** + * Write to the file. + * + * @param string $contents + * @return string + */ + public function write($contents) + { + fwrite($this->handle, $contents); + + fflush($this->handle); + + return $this; + } + + /** + * Truncate the file. + * + * @return $this + */ + public function truncate() + { + rewind($this->handle); + + ftruncate($this->handle, 0); + + return $this; + } + + /** + * Get a shared lock on the file. + * + * @param bool $block + * @return $this + * + * @throws \Illuminate\Contracts\Filesystem\LockTimeoutException + */ + public function getSharedLock($block = false) + { + if (! flock($this->handle, LOCK_SH | ($block ? 0 : LOCK_NB))) { + throw new LockTimeoutException("Unable to acquire file lock at path [{$this->path}]."); + } + + $this->isLocked = true; + + return $this; + } + + /** + * Get an exclusive lock on the file. + * + * @param bool $block + * @return bool + * + * @throws \Illuminate\Contracts\Filesystem\LockTimeoutException + */ + public function getExclusiveLock($block = false) + { + if (! flock($this->handle, LOCK_EX | ($block ? 0 : LOCK_NB))) { + throw new LockTimeoutException("Unable to acquire file lock at path [{$this->path}]."); + } + + $this->isLocked = true; + + return $this; + } + + /** + * Release the lock on the file. + * + * @return $this + */ + public function releaseLock() + { + flock($this->handle, LOCK_UN); + + $this->isLocked = false; + + return $this; + } + + /** + * Close the file. + * + * @return bool + */ + public function close() + { + if ($this->isLocked) { + $this->releaseLock(); + } + + return fclose($this->handle); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/composer.json new file mode 100644 index 0000000..ca82b7a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Filesystem/composer.json @@ -0,0 +1,49 @@ +{ + "name": "illuminate/filesystem", + "description": "The Illuminate Filesystem package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "symfony/finder": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Filesystem\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "ext-ftp": "Required to use the Flysystem FTP driver.", + "illuminate/http": "Required for handling uploaded files (^7.0).", + "league/flysystem": "Required to use the Flysystem local and FTP drivers (^1.1).", + "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", + "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", + "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", + "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^5.4).", + "symfony/mime": "Required to enable support for guessing extensions (^5.4)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/AliasLoader.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/AliasLoader.php new file mode 100755 index 0000000..0f12b6c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/AliasLoader.php @@ -0,0 +1,243 @@ +aliases = $aliases; + } + + /** + * Get or create the singleton alias loader instance. + * + * @param array $aliases + * @return \Illuminate\Foundation\AliasLoader + */ + public static function getInstance(array $aliases = []) + { + if (is_null(static::$instance)) { + return static::$instance = new static($aliases); + } + + $aliases = array_merge(static::$instance->getAliases(), $aliases); + + static::$instance->setAliases($aliases); + + return static::$instance; + } + + /** + * Load a class alias if it is registered. + * + * @param string $alias + * @return bool|null + */ + public function load($alias) + { + if (static::$facadeNamespace && strpos($alias, static::$facadeNamespace) === 0) { + $this->loadFacade($alias); + + return true; + } + + if (isset($this->aliases[$alias])) { + return class_alias($this->aliases[$alias], $alias); + } + } + + /** + * Load a real-time facade for the given alias. + * + * @param string $alias + * @return void + */ + protected function loadFacade($alias) + { + require $this->ensureFacadeExists($alias); + } + + /** + * Ensure that the given alias has an existing real-time facade class. + * + * @param string $alias + * @return string + */ + protected function ensureFacadeExists($alias) + { + if (is_file($path = storage_path('framework/cache/facade-'.sha1($alias).'.php'))) { + return $path; + } + + file_put_contents($path, $this->formatFacadeStub( + $alias, file_get_contents(__DIR__.'/stubs/facade.stub') + )); + + return $path; + } + + /** + * Format the facade stub with the proper namespace and class. + * + * @param string $alias + * @param string $stub + * @return string + */ + protected function formatFacadeStub($alias, $stub) + { + $replacements = [ + str_replace('/', '\\', dirname(str_replace('\\', '/', $alias))), + class_basename($alias), + substr($alias, strlen(static::$facadeNamespace)), + ]; + + return str_replace( + ['DummyNamespace', 'DummyClass', 'DummyTarget'], $replacements, $stub + ); + } + + /** + * Add an alias to the loader. + * + * @param string $alias + * @param string $class + * @return void + */ + public function alias($alias, $class) + { + $this->aliases[$alias] = $class; + } + + /** + * Register the loader on the auto-loader stack. + * + * @return void + */ + public function register() + { + if (! $this->registered) { + $this->prependToLoaderStack(); + + $this->registered = true; + } + } + + /** + * Prepend the load method to the auto-loader stack. + * + * @return void + */ + protected function prependToLoaderStack() + { + spl_autoload_register([$this, 'load'], true, true); + } + + /** + * Get the registered aliases. + * + * @return array + */ + public function getAliases() + { + return $this->aliases; + } + + /** + * Set the registered aliases. + * + * @param array $aliases + * @return void + */ + public function setAliases(array $aliases) + { + $this->aliases = $aliases; + } + + /** + * Indicates if the loader has been registered. + * + * @return bool + */ + public function isRegistered() + { + return $this->registered; + } + + /** + * Set the "registered" state of the loader. + * + * @param bool $value + * @return void + */ + public function setRegistered($value) + { + $this->registered = $value; + } + + /** + * Set the real-time facade namespace. + * + * @param string $namespace + * @return void + */ + public static function setFacadeNamespace($namespace) + { + static::$facadeNamespace = rtrim($namespace, '\\').'\\'; + } + + /** + * Set the value of the singleton alias loader. + * + * @param \Illuminate\Foundation\AliasLoader $loader + * @return void + */ + public static function setInstance($loader) + { + static::$instance = $loader; + } + + /** + * Clone method. + * + * @return void + */ + private function __clone() + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Application.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Application.php new file mode 100755 index 0000000..0aa6a98 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Application.php @@ -0,0 +1,1411 @@ +setBasePath($basePath); + } + + $this->registerBaseBindings(); + $this->registerBaseServiceProviders(); + $this->registerCoreContainerAliases(); + } + + /** + * Get the version number of the application. + * + * @return string + */ + public function version() + { + return static::VERSION; + } + + /** + * Register the basic bindings into the container. + * + * @return void + */ + protected function registerBaseBindings() + { + static::setInstance($this); + + $this->instance('app', $this); + + $this->instance(Container::class, $this); + $this->singleton(Mix::class); + + $this->singleton(PackageManifest::class, function () { + return new PackageManifest( + new Filesystem, $this->basePath(), $this->getCachedPackagesPath() + ); + }); + } + + /** + * Register all of the base service providers. + * + * @return void + */ + protected function registerBaseServiceProviders() + { + $this->register(new EventServiceProvider($this)); + $this->register(new LogServiceProvider($this)); + $this->register(new RoutingServiceProvider($this)); + } + + /** + * Run the given array of bootstrap classes. + * + * @param string[] $bootstrappers + * @return void + */ + public function bootstrapWith(array $bootstrappers) + { + $this->hasBeenBootstrapped = true; + + foreach ($bootstrappers as $bootstrapper) { + $this['events']->dispatch('bootstrapping: '.$bootstrapper, [$this]); + + $this->make($bootstrapper)->bootstrap($this); + + $this['events']->dispatch('bootstrapped: '.$bootstrapper, [$this]); + } + } + + /** + * Register a callback to run after loading the environment. + * + * @param \Closure $callback + * @return void + */ + public function afterLoadingEnvironment(Closure $callback) + { + $this->afterBootstrapping( + LoadEnvironmentVariables::class, $callback + ); + } + + /** + * Register a callback to run before a bootstrapper. + * + * @param string $bootstrapper + * @param \Closure $callback + * @return void + */ + public function beforeBootstrapping($bootstrapper, Closure $callback) + { + $this['events']->listen('bootstrapping: '.$bootstrapper, $callback); + } + + /** + * Register a callback to run after a bootstrapper. + * + * @param string $bootstrapper + * @param \Closure $callback + * @return void + */ + public function afterBootstrapping($bootstrapper, Closure $callback) + { + $this['events']->listen('bootstrapped: '.$bootstrapper, $callback); + } + + /** + * Determine if the application has been bootstrapped before. + * + * @return bool + */ + public function hasBeenBootstrapped() + { + return $this->hasBeenBootstrapped; + } + + /** + * Set the base path for the application. + * + * @param string $basePath + * @return $this + */ + public function setBasePath($basePath) + { + $this->basePath = rtrim($basePath, '\/'); + + $this->bindPathsInContainer(); + + return $this; + } + + /** + * Bind all of the application paths in the container. + * + * @return void + */ + protected function bindPathsInContainer() + { + $this->instance('path', $this->path()); + $this->instance('path.base', $this->basePath()); + $this->instance('path.lang', $this->langPath()); + $this->instance('path.config', $this->configPath()); + $this->instance('path.public', $this->publicPath()); + $this->instance('path.storage', $this->storagePath()); + $this->instance('path.database', $this->databasePath()); + $this->instance('path.resources', $this->resourcePath()); + $this->instance('path.bootstrap', $this->bootstrapPath()); + } + + /** + * Get the path to the application "app" directory. + * + * @param string $path + * @return string + */ + public function path($path = '') + { + $appPath = $this->appPath ?: $this->basePath.DIRECTORY_SEPARATOR.'app'; + + return $appPath.($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Set the application directory. + * + * @param string $path + * @return $this + */ + public function useAppPath($path) + { + $this->appPath = $path; + + $this->instance('path', $path); + + return $this; + } + + /** + * Get the base path of the Laravel installation. + * + * @param string $path + * @return string + */ + public function basePath($path = '') + { + return $this->basePath.($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Get the path to the bootstrap directory. + * + * @param string $path + * @return string + */ + public function bootstrapPath($path = '') + { + return $this->basePath.DIRECTORY_SEPARATOR.'bootstrap'.($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Get the path to the application configuration files. + * + * @param string $path + * @return string + */ + public function configPath($path = '') + { + return $this->basePath.DIRECTORY_SEPARATOR.'config'.($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Get the path to the database directory. + * + * @param string $path + * @return string + */ + public function databasePath($path = '') + { + return ($this->databasePath ?: $this->basePath.DIRECTORY_SEPARATOR.'database').($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Set the database directory. + * + * @param string $path + * @return $this + */ + public function useDatabasePath($path) + { + $this->databasePath = $path; + + $this->instance('path.database', $path); + + return $this; + } + + /** + * Get the path to the language files. + * + * @return string + */ + public function langPath() + { + if ($this->langPath) { + return $this->langPath; + } + + if (is_dir($path = $this->resourcePath().DIRECTORY_SEPARATOR.'lang')) { + return $path; + } + + return $this->basePath().DIRECTORY_SEPARATOR.'lang'; + } + + /** + * Set the language file directory. + * + * @param string $path + * @return $this + */ + public function useLangPath($path) + { + $this->langPath = $path; + + $this->instance('path.lang', $path); + + return $this; + } + + /** + * Get the path to the public / web directory. + * + * @return string + */ + public function publicPath() + { + return $this->basePath.DIRECTORY_SEPARATOR.'public'; + } + + /** + * Get the path to the storage directory. + * + * @return string + */ + public function storagePath() + { + return $this->storagePath ?: $this->basePath.DIRECTORY_SEPARATOR.'storage'; + } + + /** + * Set the storage directory. + * + * @param string $path + * @return $this + */ + public function useStoragePath($path) + { + $this->storagePath = $path; + + $this->instance('path.storage', $path); + + return $this; + } + + /** + * Get the path to the resources directory. + * + * @param string $path + * @return string + */ + public function resourcePath($path = '') + { + return $this->basePath.DIRECTORY_SEPARATOR.'resources'.($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Get the path to the views directory. + * + * This method returns the first configured path in the array of view paths. + * + * @param string $path + * @return string + */ + public function viewPath($path = '') + { + $basePath = $this['config']->get('view.paths')[0]; + + return rtrim($basePath, DIRECTORY_SEPARATOR).($path ? DIRECTORY_SEPARATOR.$path : $path); + } + + /** + * Get the path to the environment file directory. + * + * @return string + */ + public function environmentPath() + { + return $this->environmentPath ?: $this->basePath; + } + + /** + * Set the directory for the environment file. + * + * @param string $path + * @return $this + */ + public function useEnvironmentPath($path) + { + $this->environmentPath = $path; + + return $this; + } + + /** + * Set the environment file to be loaded during bootstrapping. + * + * @param string $file + * @return $this + */ + public function loadEnvironmentFrom($file) + { + $this->environmentFile = $file; + + return $this; + } + + /** + * Get the environment file the application is using. + * + * @return string + */ + public function environmentFile() + { + return $this->environmentFile ?: '.env'; + } + + /** + * Get the fully qualified path to the environment file. + * + * @return string + */ + public function environmentFilePath() + { + return $this->environmentPath().DIRECTORY_SEPARATOR.$this->environmentFile(); + } + + /** + * Get or check the current application environment. + * + * @param string|array $environments + * @return string|bool + */ + public function environment(...$environments) + { + if (count($environments) > 0) { + $patterns = is_array($environments[0]) ? $environments[0] : $environments; + + return Str::is($patterns, $this['env']); + } + + return $this['env']; + } + + /** + * Determine if the application is in the local environment. + * + * @return bool + */ + public function isLocal() + { + return $this['env'] === 'local'; + } + + /** + * Determine if the application is in the production environment. + * + * @return bool + */ + public function isProduction() + { + return $this['env'] === 'production'; + } + + /** + * Detect the application's current environment. + * + * @param \Closure $callback + * @return string + */ + public function detectEnvironment(Closure $callback) + { + $args = $_SERVER['argv'] ?? null; + + return $this['env'] = (new EnvironmentDetector)->detect($callback, $args); + } + + /** + * Determine if the application is running in the console. + * + * @return bool + */ + public function runningInConsole() + { + if ($this->isRunningInConsole === null) { + $this->isRunningInConsole = Env::get('APP_RUNNING_IN_CONSOLE') ?? (\PHP_SAPI === 'cli' || \PHP_SAPI === 'phpdbg'); + } + + return $this->isRunningInConsole; + } + + /** + * Determine if the application is running unit tests. + * + * @return bool + */ + public function runningUnitTests() + { + return $this->bound('env') && $this['env'] === 'testing'; + } + + /** + * Determine if the application is running with debug mode enabled. + * + * @return bool + */ + public function hasDebugModeEnabled() + { + return (bool) $this['config']->get('app.debug'); + } + + /** + * Register all of the configured providers. + * + * @return void + */ + public function registerConfiguredProviders() + { + $providers = Collection::make($this->make('config')->get('app.providers')) + ->partition(function ($provider) { + return strpos($provider, 'Illuminate\\') === 0; + }); + + $providers->splice(1, 0, [$this->make(PackageManifest::class)->providers()]); + + (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath())) + ->load($providers->collapse()->toArray()); + } + + /** + * Register a service provider with the application. + * + * @param \Illuminate\Support\ServiceProvider|string $provider + * @param bool $force + * @return \Illuminate\Support\ServiceProvider + */ + public function register($provider, $force = false) + { + if (($registered = $this->getProvider($provider)) && ! $force) { + return $registered; + } + + // If the given "provider" is a string, we will resolve it, passing in the + // application instance automatically for the developer. This is simply + // a more convenient way of specifying your service provider classes. + if (is_string($provider)) { + $provider = $this->resolveProvider($provider); + } + + $provider->register(); + + // If there are bindings / singletons set as properties on the provider we + // will spin through them and register them with the application, which + // serves as a convenience layer while registering a lot of bindings. + if (property_exists($provider, 'bindings')) { + foreach ($provider->bindings as $key => $value) { + $this->bind($key, $value); + } + } + + if (property_exists($provider, 'singletons')) { + foreach ($provider->singletons as $key => $value) { + $this->singleton($key, $value); + } + } + + $this->markAsRegistered($provider); + + // If the application has already booted, we will call this boot method on + // the provider class so it has an opportunity to do its boot logic and + // will be ready for any usage by this developer's application logic. + if ($this->isBooted()) { + $this->bootProvider($provider); + } + + return $provider; + } + + /** + * Get the registered service provider instance if it exists. + * + * @param \Illuminate\Support\ServiceProvider|string $provider + * @return \Illuminate\Support\ServiceProvider|null + */ + public function getProvider($provider) + { + return array_values($this->getProviders($provider))[0] ?? null; + } + + /** + * Get the registered service provider instances if any exist. + * + * @param \Illuminate\Support\ServiceProvider|string $provider + * @return array + */ + public function getProviders($provider) + { + $name = is_string($provider) ? $provider : get_class($provider); + + return Arr::where($this->serviceProviders, function ($value) use ($name) { + return $value instanceof $name; + }); + } + + /** + * Resolve a service provider instance from the class name. + * + * @param string $provider + * @return \Illuminate\Support\ServiceProvider + */ + public function resolveProvider($provider) + { + return new $provider($this); + } + + /** + * Mark the given provider as registered. + * + * @param \Illuminate\Support\ServiceProvider $provider + * @return void + */ + protected function markAsRegistered($provider) + { + $this->serviceProviders[] = $provider; + + $this->loadedProviders[get_class($provider)] = true; + } + + /** + * Load and boot all of the remaining deferred providers. + * + * @return void + */ + public function loadDeferredProviders() + { + // We will simply spin through each of the deferred providers and register each + // one and boot them if the application has booted. This should make each of + // the remaining services available to this application for immediate use. + foreach ($this->deferredServices as $service => $provider) { + $this->loadDeferredProvider($service); + } + + $this->deferredServices = []; + } + + /** + * Load the provider for a deferred service. + * + * @param string $service + * @return void + */ + public function loadDeferredProvider($service) + { + if (! $this->isDeferredService($service)) { + return; + } + + $provider = $this->deferredServices[$service]; + + // If the service provider has not already been loaded and registered we can + // register it with the application and remove the service from this list + // of deferred services, since it will already be loaded on subsequent. + if (! isset($this->loadedProviders[$provider])) { + $this->registerDeferredProvider($provider, $service); + } + } + + /** + * Register a deferred provider and service. + * + * @param string $provider + * @param string|null $service + * @return void + */ + public function registerDeferredProvider($provider, $service = null) + { + // Once the provider that provides the deferred service has been registered we + // will remove it from our local list of the deferred services with related + // providers so that this container does not try to resolve it out again. + if ($service) { + unset($this->deferredServices[$service]); + } + + $this->register($instance = new $provider($this)); + + if (! $this->isBooted()) { + $this->booting(function () use ($instance) { + $this->bootProvider($instance); + }); + } + } + + /** + * Resolve the given type from the container. + * + * @param string $abstract + * @param array $parameters + * @return mixed + */ + public function make($abstract, array $parameters = []) + { + $this->loadDeferredProviderIfNeeded($abstract = $this->getAlias($abstract)); + + return parent::make($abstract, $parameters); + } + + /** + * Resolve the given type from the container. + * + * @param string $abstract + * @param array $parameters + * @param bool $raiseEvents + * @return mixed + */ + protected function resolve($abstract, $parameters = [], $raiseEvents = true) + { + $this->loadDeferredProviderIfNeeded($abstract = $this->getAlias($abstract)); + + return parent::resolve($abstract, $parameters, $raiseEvents); + } + + /** + * Load the deferred provider if the given type is a deferred service and the instance has not been loaded. + * + * @param string $abstract + * @return void + */ + protected function loadDeferredProviderIfNeeded($abstract) + { + if ($this->isDeferredService($abstract) && ! isset($this->instances[$abstract])) { + $this->loadDeferredProvider($abstract); + } + } + + /** + * Determine if the given abstract type has been bound. + * + * @param string $abstract + * @return bool + */ + public function bound($abstract) + { + return $this->isDeferredService($abstract) || parent::bound($abstract); + } + + /** + * Determine if the application has booted. + * + * @return bool + */ + public function isBooted() + { + return $this->booted; + } + + /** + * Boot the application's service providers. + * + * @return void + */ + public function boot() + { + if ($this->isBooted()) { + return; + } + + // Once the application has booted we will also fire some "booted" callbacks + // for any listeners that need to do work after this initial booting gets + // finished. This is useful when ordering the boot-up processes we run. + $this->fireAppCallbacks($this->bootingCallbacks); + + array_walk($this->serviceProviders, function ($p) { + $this->bootProvider($p); + }); + + $this->booted = true; + + $this->fireAppCallbacks($this->bootedCallbacks); + } + + /** + * Boot the given service provider. + * + * @param \Illuminate\Support\ServiceProvider $provider + * @return void + */ + protected function bootProvider(ServiceProvider $provider) + { + $provider->callBootingCallbacks(); + + if (method_exists($provider, 'boot')) { + $this->call([$provider, 'boot']); + } + + $provider->callBootedCallbacks(); + } + + /** + * Register a new boot listener. + * + * @param callable $callback + * @return void + */ + public function booting($callback) + { + $this->bootingCallbacks[] = $callback; + } + + /** + * Register a new "booted" listener. + * + * @param callable $callback + * @return void + */ + public function booted($callback) + { + $this->bootedCallbacks[] = $callback; + + if ($this->isBooted()) { + $callback($this); + } + } + + /** + * Call the booting callbacks for the application. + * + * @param callable[] $callbacks + * @return void + */ + protected function fireAppCallbacks(array &$callbacks) + { + $index = 0; + + while ($index < count($callbacks)) { + $callbacks[$index]($this); + + $index++; + } + } + + /** + * {@inheritdoc} + * + * @return \Symfony\Component\HttpFoundation\Response + */ + public function handle(SymfonyRequest $request, int $type = self::MASTER_REQUEST, bool $catch = true) + { + return $this[HttpKernelContract::class]->handle(Request::createFromBase($request)); + } + + /** + * Determine if middleware has been disabled for the application. + * + * @return bool + */ + public function shouldSkipMiddleware() + { + return $this->bound('middleware.disable') && + $this->make('middleware.disable') === true; + } + + /** + * Get the path to the cached services.php file. + * + * @return string + */ + public function getCachedServicesPath() + { + return $this->normalizeCachePath('APP_SERVICES_CACHE', 'cache/services.php'); + } + + /** + * Get the path to the cached packages.php file. + * + * @return string + */ + public function getCachedPackagesPath() + { + return $this->normalizeCachePath('APP_PACKAGES_CACHE', 'cache/packages.php'); + } + + /** + * Determine if the application configuration is cached. + * + * @return bool + */ + public function configurationIsCached() + { + return is_file($this->getCachedConfigPath()); + } + + /** + * Get the path to the configuration cache file. + * + * @return string + */ + public function getCachedConfigPath() + { + return $this->normalizeCachePath('APP_CONFIG_CACHE', 'cache/config.php'); + } + + /** + * Determine if the application routes are cached. + * + * @return bool + */ + public function routesAreCached() + { + return $this['files']->exists($this->getCachedRoutesPath()); + } + + /** + * Get the path to the routes cache file. + * + * @return string + */ + public function getCachedRoutesPath() + { + return $this->normalizeCachePath('APP_ROUTES_CACHE', 'cache/routes-v7.php'); + } + + /** + * Determine if the application events are cached. + * + * @return bool + */ + public function eventsAreCached() + { + return $this['files']->exists($this->getCachedEventsPath()); + } + + /** + * Get the path to the events cache file. + * + * @return string + */ + public function getCachedEventsPath() + { + return $this->normalizeCachePath('APP_EVENTS_CACHE', 'cache/events.php'); + } + + /** + * Normalize a relative or absolute path to a cache file. + * + * @param string $key + * @param string $default + * @return string + */ + protected function normalizeCachePath($key, $default) + { + if (is_null($env = Env::get($key))) { + return $this->bootstrapPath($default); + } + + return Str::startsWith($env, $this->absoluteCachePathPrefixes) + ? $env + : $this->basePath($env); + } + + /** + * Add new prefix to list of absolute path prefixes. + * + * @param string $prefix + * @return $this + */ + public function addAbsoluteCachePathPrefix($prefix) + { + $this->absoluteCachePathPrefixes[] = $prefix; + + return $this; + } + + /** + * Determine if the application is currently down for maintenance. + * + * @return bool + */ + public function isDownForMaintenance() + { + return file_exists($this->storagePath().'/framework/down'); + } + + /** + * Throw an HttpException with the given data. + * + * @param int $code + * @param string $message + * @param array $headers + * @return never + * + * @throws \Symfony\Component\HttpKernel\Exception\HttpException + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + */ + public function abort($code, $message = '', array $headers = []) + { + if ($code == 404) { + throw new NotFoundHttpException($message); + } + + throw new HttpException($code, $message, null, $headers); + } + + /** + * Register a terminating callback with the application. + * + * @param callable|string $callback + * @return $this + */ + public function terminating($callback) + { + $this->terminatingCallbacks[] = $callback; + + return $this; + } + + /** + * Terminate the application. + * + * @return void + */ + public function terminate() + { + $index = 0; + + while ($index < count($this->terminatingCallbacks)) { + $this->call($this->terminatingCallbacks[$index]); + + $index++; + } + } + + /** + * Get the service providers that have been loaded. + * + * @return array + */ + public function getLoadedProviders() + { + return $this->loadedProviders; + } + + /** + * Determine if the given service provider is loaded. + * + * @param string $provider + * @return bool + */ + public function providerIsLoaded(string $provider) + { + return isset($this->loadedProviders[$provider]); + } + + /** + * Get the application's deferred services. + * + * @return array + */ + public function getDeferredServices() + { + return $this->deferredServices; + } + + /** + * Set the application's deferred services. + * + * @param array $services + * @return void + */ + public function setDeferredServices(array $services) + { + $this->deferredServices = $services; + } + + /** + * Add an array of services to the application's deferred services. + * + * @param array $services + * @return void + */ + public function addDeferredServices(array $services) + { + $this->deferredServices = array_merge($this->deferredServices, $services); + } + + /** + * Determine if the given service is a deferred service. + * + * @param string $service + * @return bool + */ + public function isDeferredService($service) + { + return isset($this->deferredServices[$service]); + } + + /** + * Configure the real-time facade namespace. + * + * @param string $namespace + * @return void + */ + public function provideFacades($namespace) + { + AliasLoader::setFacadeNamespace($namespace); + } + + /** + * Get the current application locale. + * + * @return string + */ + public function getLocale() + { + return $this['config']->get('app.locale'); + } + + /** + * Get the current application locale. + * + * @return string + */ + public function currentLocale() + { + return $this->getLocale(); + } + + /** + * Get the current application fallback locale. + * + * @return string + */ + public function getFallbackLocale() + { + return $this['config']->get('app.fallback_locale'); + } + + /** + * Set the current application locale. + * + * @param string $locale + * @return void + */ + public function setLocale($locale) + { + $this['config']->set('app.locale', $locale); + + $this['translator']->setLocale($locale); + + $this['events']->dispatch(new LocaleUpdated($locale)); + } + + /** + * Set the current application fallback locale. + * + * @param string $fallbackLocale + * @return void + */ + public function setFallbackLocale($fallbackLocale) + { + $this['config']->set('app.fallback_locale', $fallbackLocale); + + $this['translator']->setFallback($fallbackLocale); + } + + /** + * Determine if the application locale is the given locale. + * + * @param string $locale + * @return bool + */ + public function isLocale($locale) + { + return $this->getLocale() == $locale; + } + + /** + * Register the core class aliases in the container. + * + * @return void + */ + public function registerCoreContainerAliases() + { + foreach ([ + 'app' => [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class], + 'auth' => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class], + 'auth.driver' => [\Illuminate\Contracts\Auth\Guard::class], + 'blade.compiler' => [\Illuminate\View\Compilers\BladeCompiler::class], + 'cache' => [\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class], + 'cache.store' => [\Illuminate\Cache\Repository::class, \Illuminate\Contracts\Cache\Repository::class, \Psr\SimpleCache\CacheInterface::class], + 'cache.psr6' => [\Symfony\Component\Cache\Adapter\Psr16Adapter::class, \Symfony\Component\Cache\Adapter\AdapterInterface::class, \Psr\Cache\CacheItemPoolInterface::class], + 'config' => [\Illuminate\Config\Repository::class, \Illuminate\Contracts\Config\Repository::class], + 'cookie' => [\Illuminate\Cookie\CookieJar::class, \Illuminate\Contracts\Cookie\Factory::class, \Illuminate\Contracts\Cookie\QueueingFactory::class], + 'db' => [\Illuminate\Database\DatabaseManager::class, \Illuminate\Database\ConnectionResolverInterface::class], + 'db.connection' => [\Illuminate\Database\Connection::class, \Illuminate\Database\ConnectionInterface::class], + 'encrypter' => [\Illuminate\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\StringEncrypter::class], + 'events' => [\Illuminate\Events\Dispatcher::class, \Illuminate\Contracts\Events\Dispatcher::class], + 'files' => [\Illuminate\Filesystem\Filesystem::class], + 'filesystem' => [\Illuminate\Filesystem\FilesystemManager::class, \Illuminate\Contracts\Filesystem\Factory::class], + 'filesystem.disk' => [\Illuminate\Contracts\Filesystem\Filesystem::class], + 'filesystem.cloud' => [\Illuminate\Contracts\Filesystem\Cloud::class], + 'hash' => [\Illuminate\Hashing\HashManager::class], + 'hash.driver' => [\Illuminate\Contracts\Hashing\Hasher::class], + 'translator' => [\Illuminate\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class], + 'log' => [\Illuminate\Log\LogManager::class, \Psr\Log\LoggerInterface::class], + 'mail.manager' => [\Illuminate\Mail\MailManager::class, \Illuminate\Contracts\Mail\Factory::class], + 'mailer' => [\Illuminate\Mail\Mailer::class, \Illuminate\Contracts\Mail\Mailer::class, \Illuminate\Contracts\Mail\MailQueue::class], + 'auth.password' => [\Illuminate\Auth\Passwords\PasswordBrokerManager::class, \Illuminate\Contracts\Auth\PasswordBrokerFactory::class], + 'auth.password.broker' => [\Illuminate\Auth\Passwords\PasswordBroker::class, \Illuminate\Contracts\Auth\PasswordBroker::class], + 'queue' => [\Illuminate\Queue\QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class], + 'queue.connection' => [\Illuminate\Contracts\Queue\Queue::class], + 'queue.failer' => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class], + 'redirect' => [\Illuminate\Routing\Redirector::class], + 'redis' => [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class], + 'redis.connection' => [\Illuminate\Redis\Connections\Connection::class, \Illuminate\Contracts\Redis\Connection::class], + 'request' => [\Illuminate\Http\Request::class, \Symfony\Component\HttpFoundation\Request::class], + 'router' => [\Illuminate\Routing\Router::class, \Illuminate\Contracts\Routing\Registrar::class, \Illuminate\Contracts\Routing\BindingRegistrar::class], + 'session' => [\Illuminate\Session\SessionManager::class], + 'session.store' => [\Illuminate\Session\Store::class, \Illuminate\Contracts\Session\Session::class], + 'url' => [\Illuminate\Routing\UrlGenerator::class, \Illuminate\Contracts\Routing\UrlGenerator::class], + 'validator' => [\Illuminate\Validation\Factory::class, \Illuminate\Contracts\Validation\Factory::class], + 'view' => [\Illuminate\View\Factory::class, \Illuminate\Contracts\View\Factory::class], + ] as $key => $aliases) { + foreach ($aliases as $alias) { + $this->alias($key, $alias); + } + } + } + + /** + * Flush the container of all bindings and resolved instances. + * + * @return void + */ + public function flush() + { + parent::flush(); + + $this->buildStack = []; + $this->loadedProviders = []; + $this->bootedCallbacks = []; + $this->bootingCallbacks = []; + $this->deferredServices = []; + $this->reboundCallbacks = []; + $this->serviceProviders = []; + $this->resolvingCallbacks = []; + $this->terminatingCallbacks = []; + $this->beforeResolvingCallbacks = []; + $this->afterResolvingCallbacks = []; + $this->globalBeforeResolvingCallbacks = []; + $this->globalResolvingCallbacks = []; + $this->globalAfterResolvingCallbacks = []; + } + + /** + * Get the application namespace. + * + * @return string + * + * @throws \RuntimeException + */ + public function getNamespace() + { + if (! is_null($this->namespace)) { + return $this->namespace; + } + + $composer = json_decode(file_get_contents($this->basePath('composer.json')), true); + + foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) { + foreach ((array) $path as $pathChoice) { + if (realpath($this->path()) === realpath($this->basePath($pathChoice))) { + return $this->namespace = $namespace; + } + } + } + + throw new RuntimeException('Unable to detect application namespace.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/Access/Authorizable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/Access/Authorizable.php new file mode 100644 index 0000000..d8cf50d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/Access/Authorizable.php @@ -0,0 +1,56 @@ +forUser($this)->check($abilities, $arguments); + } + + /** + * Determine if the entity has any of the given abilities. + * + * @param iterable|string $abilities + * @param array|mixed $arguments + * @return bool + */ + public function canAny($abilities, $arguments = []) + { + return app(Gate::class)->forUser($this)->any($abilities, $arguments); + } + + /** + * Determine if the entity does not have the given abilities. + * + * @param iterable|string $abilities + * @param array|mixed $arguments + * @return bool + */ + public function cant($abilities, $arguments = []) + { + return ! $this->can($abilities, $arguments); + } + + /** + * Determine if the entity does not have the given abilities. + * + * @param iterable|string $abilities + * @param array|mixed $arguments + * @return bool + */ + public function cannot($abilities, $arguments = []) + { + return $this->cant($abilities, $arguments); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php new file mode 100644 index 0000000..fe0ba0c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php @@ -0,0 +1,131 @@ +parseAbilityAndArguments($ability, $arguments); + + return app(Gate::class)->authorize($ability, $arguments); + } + + /** + * Authorize a given action for a user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user + * @param mixed $ability + * @param mixed|array $arguments + * @return \Illuminate\Auth\Access\Response + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function authorizeForUser($user, $ability, $arguments = []) + { + [$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments); + + return app(Gate::class)->forUser($user)->authorize($ability, $arguments); + } + + /** + * Guesses the ability's name if it wasn't provided. + * + * @param mixed $ability + * @param mixed|array $arguments + * @return array + */ + protected function parseAbilityAndArguments($ability, $arguments) + { + if (is_string($ability) && strpos($ability, '\\') === false) { + return [$ability, $arguments]; + } + + $method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function']; + + return [$this->normalizeGuessedAbilityName($method), $ability]; + } + + /** + * Normalize the ability name that has been guessed from the method name. + * + * @param string $ability + * @return string + */ + protected function normalizeGuessedAbilityName($ability) + { + $map = $this->resourceAbilityMap(); + + return $map[$ability] ?? $ability; + } + + /** + * Authorize a resource action based on the incoming request. + * + * @param string|array $model + * @param string|array|null $parameter + * @param array $options + * @param \Illuminate\Http\Request|null $request + * @return void + */ + public function authorizeResource($model, $parameter = null, array $options = [], $request = null) + { + $model = is_array($model) ? implode(',', $model) : $model; + + $parameter = is_array($parameter) ? implode(',', $parameter) : $parameter; + + $parameter = $parameter ?: Str::snake(class_basename($model)); + + $middleware = []; + + foreach ($this->resourceAbilityMap() as $method => $ability) { + $modelName = in_array($method, $this->resourceMethodsWithoutModels()) ? $model : $parameter; + + $middleware["can:{$ability},{$modelName}"][] = $method; + } + + foreach ($middleware as $middlewareName => $methods) { + $this->middleware($middlewareName, $options)->only($methods); + } + } + + /** + * Get the map of resource methods to ability names. + * + * @return array + */ + protected function resourceAbilityMap() + { + return [ + 'index' => 'viewAny', + 'show' => 'view', + 'create' => 'create', + 'store' => 'create', + 'edit' => 'update', + 'update' => 'update', + 'destroy' => 'delete', + ]; + } + + /** + * Get the list of resource methods which do not have model parameters. + * + * @return array + */ + protected function resourceMethodsWithoutModels() + { + return ['index', 'create', 'store']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/EmailVerificationRequest.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/EmailVerificationRequest.php new file mode 100644 index 0000000..081d66b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/EmailVerificationRequest.php @@ -0,0 +1,66 @@ +user()->getKey(), + (string) $this->route('id'))) { + return false; + } + + if (! hash_equals(sha1($this->user()->getEmailForVerification()), + (string) $this->route('hash'))) { + return false; + } + + return true; + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + // + ]; + } + + /** + * Fulfill the email verification request. + * + * @return void + */ + public function fulfill() + { + if (! $this->user()->hasVerifiedEmail()) { + $this->user()->markEmailAsVerified(); + + event(new Verified($this->user())); + } + } + + /** + * Configure the validator instance. + * + * @param \Illuminate\Validation\Validator $validator + * @return void + */ + public function withValidator($validator) + { + return $validator; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/User.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/User.php new file mode 100644 index 0000000..be1dff5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Auth/User.php @@ -0,0 +1,20 @@ +boot(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php new file mode 100644 index 0000000..286c2fe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php @@ -0,0 +1,256 @@ +app = $app; + + error_reporting(-1); + + set_error_handler([$this, 'handleError']); + + set_exception_handler([$this, 'handleException']); + + register_shutdown_function([$this, 'handleShutdown']); + + if (! $app->environment('testing')) { + ini_set('display_errors', 'Off'); + } + } + + /** + * Report PHP deprecations, or convert PHP errors to ErrorException instances. + * + * @param int $level + * @param string $message + * @param string $file + * @param int $line + * @param array $context + * @return void + * + * @throws \ErrorException + */ + public function handleError($level, $message, $file = '', $line = 0, $context = []) + { + if ($this->isDeprecation($level)) { + return $this->handleDeprecation($message, $file, $line); + } + + if (error_reporting() & $level) { + throw new ErrorException($message, 0, $level, $file, $line); + } + } + + /** + * Reports a deprecation to the "deprecations" logger. + * + * @param string $message + * @param string $file + * @param int $line + * @return void + */ + public function handleDeprecation($message, $file, $line) + { + if (! class_exists(LogManager::class) + || ! $this->app->hasBeenBootstrapped() + || $this->app->runningUnitTests() + ) { + return; + } + + try { + $logger = $this->app->make(LogManager::class); + } catch (Exception $e) { + return; + } + + $this->ensureDeprecationLoggerIsConfigured(); + + with($logger->channel('deprecations'), function ($log) use ($message, $file, $line) { + $log->warning(sprintf('%s in %s on line %s', + $message, $file, $line + )); + }); + } + + /** + * Ensure the "deprecations" logger is configured. + * + * @return void + */ + protected function ensureDeprecationLoggerIsConfigured() + { + with($this->app['config'], function ($config) { + if ($config->get('logging.channels.deprecations')) { + return; + } + + $this->ensureNullLogDriverIsConfigured(); + + $driver = $config->get('logging.deprecations') ?? 'null'; + + $config->set('logging.channels.deprecations', $config->get("logging.channels.{$driver}")); + }); + } + + /** + * Ensure the "null" log driver is configured. + * + * @return void + */ + protected function ensureNullLogDriverIsConfigured() + { + with($this->app['config'], function ($config) { + if ($config->get('logging.channels.null')) { + return; + } + + $config->set('logging.channels.null', [ + 'driver' => 'monolog', + 'handler' => NullHandler::class, + ]); + }); + } + + /** + * Handle an uncaught exception from the application. + * + * Note: Most exceptions can be handled via the try / catch block in + * the HTTP and Console kernels. But, fatal error exceptions must + * be handled differently since they are not normal exceptions. + * + * @param \Throwable $e + * @return void + */ + public function handleException(Throwable $e) + { + self::$reservedMemory = null; + + try { + $this->getExceptionHandler()->report($e); + } catch (Exception $e) { + // + } + + if ($this->app->runningInConsole()) { + $this->renderForConsole($e); + } else { + $this->renderHttpResponse($e); + } + } + + /** + * Render an exception to the console. + * + * @param \Throwable $e + * @return void + */ + protected function renderForConsole(Throwable $e) + { + $this->getExceptionHandler()->renderForConsole(new ConsoleOutput, $e); + } + + /** + * Render an exception as an HTTP response and send it. + * + * @param \Throwable $e + * @return void + */ + protected function renderHttpResponse(Throwable $e) + { + $this->getExceptionHandler()->render($this->app['request'], $e)->send(); + } + + /** + * Handle the PHP shutdown event. + * + * @return void + */ + public function handleShutdown() + { + self::$reservedMemory = null; + + if (! is_null($error = error_get_last()) && $this->isFatal($error['type'])) { + $this->handleException($this->fatalErrorFromPhpError($error, 0)); + } + } + + /** + * Create a new fatal error instance from an error array. + * + * @param array $error + * @param int|null $traceOffset + * @return \Symfony\Component\ErrorHandler\Error\FatalError + */ + protected function fatalErrorFromPhpError(array $error, $traceOffset = null) + { + return new FatalError($error['message'], 0, $error, $traceOffset); + } + + /** + * Determine if the error level is a deprecation. + * + * @param int $level + * @return bool + */ + protected function isDeprecation($level) + { + return in_array($level, [E_DEPRECATED, E_USER_DEPRECATED]); + } + + /** + * Determine if the error type is fatal. + * + * @param int $type + * @return bool + */ + protected function isFatal($type) + { + return in_array($type, [E_COMPILE_ERROR, E_CORE_ERROR, E_ERROR, E_PARSE]); + } + + /** + * Get an instance of the exception handler. + * + * @return \Illuminate\Contracts\Debug\ExceptionHandler + */ + protected function getExceptionHandler() + { + return $this->app->make(ExceptionHandler::class); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php new file mode 100644 index 0000000..501a1ee --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php @@ -0,0 +1,116 @@ +getCachedConfigPath())) { + $items = require $cached; + + $loadedFromCache = true; + } + + // Next we will spin through all of the configuration files in the configuration + // directory and load each one into the repository. This will make all of the + // options available to the developer for use in various parts of this app. + $app->instance('config', $config = new Repository($items)); + + if (! isset($loadedFromCache)) { + $this->loadConfigurationFiles($app, $config); + } + + // Finally, we will set the application's environment based on the configuration + // values that were loaded. We will pass a callback which will be used to get + // the environment in a web context where an "--env" switch is not present. + $app->detectEnvironment(function () use ($config) { + return $config->get('app.env', 'production'); + }); + + date_default_timezone_set($config->get('app.timezone', 'UTC')); + + mb_internal_encoding('UTF-8'); + } + + /** + * Load the configuration items from all of the files. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @param \Illuminate\Contracts\Config\Repository $repository + * @return void + * + * @throws \Exception + */ + protected function loadConfigurationFiles(Application $app, RepositoryContract $repository) + { + $files = $this->getConfigurationFiles($app); + + if (! isset($files['app'])) { + throw new Exception('Unable to load the "app" configuration file.'); + } + + foreach ($files as $key => $path) { + $repository->set($key, require $path); + } + } + + /** + * Get all of the configuration files for the application. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return array + */ + protected function getConfigurationFiles(Application $app) + { + $files = []; + + $configPath = realpath($app->configPath()); + + foreach (Finder::create()->files()->name('*.php')->in($configPath) as $file) { + $directory = $this->getNestedDirectory($file, $configPath); + + $files[$directory.basename($file->getRealPath(), '.php')] = $file->getRealPath(); + } + + ksort($files, SORT_NATURAL); + + return $files; + } + + /** + * Get the configuration file nesting path. + * + * @param \SplFileInfo $file + * @param string $configPath + * @return string + */ + protected function getNestedDirectory(SplFileInfo $file, $configPath) + { + $directory = $file->getPath(); + + if ($nested = trim(str_replace($configPath, '', $directory), DIRECTORY_SEPARATOR)) { + $nested = str_replace(DIRECTORY_SEPARATOR, '.', $nested).'.'; + } + + return $nested; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php new file mode 100644 index 0000000..5549a50 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php @@ -0,0 +1,110 @@ +configurationIsCached()) { + return; + } + + $this->checkForSpecificEnvironmentFile($app); + + try { + $this->createDotenv($app)->safeLoad(); + } catch (InvalidFileException $e) { + $this->writeErrorAndDie($e); + } + } + + /** + * Detect if a custom environment file matching the APP_ENV exists. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return void + */ + protected function checkForSpecificEnvironmentFile($app) + { + if ($app->runningInConsole() && ($input = new ArgvInput)->hasParameterOption('--env')) { + if ($this->setEnvironmentFilePath( + $app, $app->environmentFile().'.'.$input->getParameterOption('--env') + )) { + return; + } + } + + $environment = Env::get('APP_ENV'); + + if (! $environment) { + return; + } + + $this->setEnvironmentFilePath( + $app, $app->environmentFile().'.'.$environment + ); + } + + /** + * Load a custom environment file. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @param string $file + * @return bool + */ + protected function setEnvironmentFilePath($app, $file) + { + if (is_file($app->environmentPath().'/'.$file)) { + $app->loadEnvironmentFrom($file); + + return true; + } + + return false; + } + + /** + * Create a Dotenv instance. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Dotenv\Dotenv + */ + protected function createDotenv($app) + { + return Dotenv::create( + Env::getRepository(), + $app->environmentPath(), + $app->environmentFile() + ); + } + + /** + * Write the error information to the screen and exit. + * + * @param \Dotenv\Exception\InvalidFileException $e + * @return void + */ + protected function writeErrorAndDie(InvalidFileException $e) + { + $output = (new ConsoleOutput)->getErrorOutput(); + + $output->writeln('The environment file is invalid!'); + $output->writeln($e->getMessage()); + + exit(1); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php new file mode 100644 index 0000000..2a4c6b4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php @@ -0,0 +1,29 @@ +make('config')->get('app.aliases', []), + $app->make(PackageManifest::class)->aliases() + ))->register(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php new file mode 100644 index 0000000..f18375c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php @@ -0,0 +1,19 @@ +registerConfiguredProviders(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php new file mode 100644 index 0000000..613fa85 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php @@ -0,0 +1,35 @@ +make('config')->get('app.url', 'http://localhost'); + + $components = parse_url($uri); + + $server = $_SERVER; + + if (isset($components['path'])) { + $server = array_merge($server, [ + 'SCRIPT_FILENAME' => $components['path'], + 'SCRIPT_NAME' => $components['path'], + ]); + } + + $app->instance('request', Request::create( + $uri, 'GET', [], [], [], $server + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/Dispatchable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/Dispatchable.php new file mode 100644 index 0000000..3e90e41 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/Dispatchable.php @@ -0,0 +1,92 @@ +dispatchSync(new static(...$arguments)); + } + + /** + * Dispatch a command to its appropriate handler in the current process. + * + * @return mixed + * + * @deprecated Will be removed in a future Laravel version. + */ + public static function dispatchNow(...$arguments) + { + return app(Dispatcher::class)->dispatchNow(new static(...$arguments)); + } + + /** + * Dispatch a command to its appropriate handler after the current process. + * + * @return mixed + */ + public static function dispatchAfterResponse(...$arguments) + { + return app(Dispatcher::class)->dispatchAfterResponse(new static(...$arguments)); + } + + /** + * Set the jobs that should run if this job is successful. + * + * @param array $chain + * @return \Illuminate\Foundation\Bus\PendingChain + */ + public static function withChain($chain) + { + return new PendingChain(static::class, $chain); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/DispatchesJobs.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/DispatchesJobs.php new file mode 100644 index 0000000..d521158 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/DispatchesJobs.php @@ -0,0 +1,45 @@ +dispatch($job); + } + + /** + * Dispatch a job to its appropriate handler in the current process. + * + * @param mixed $job + * @return mixed + * + * @deprecated Will be removed in a future Laravel version. + */ + public function dispatchNow($job) + { + return app(Dispatcher::class)->dispatchNow($job); + } + + /** + * Dispatch a job to its appropriate handler in the current process. + * + * Queueable jobs will be dispatched to the "sync" queue. + * + * @param mixed $job + * @return mixed + */ + public function dispatchSync($job) + { + return app(Dispatcher::class)->dispatchSync($job); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingChain.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingChain.php new file mode 100644 index 0000000..73ae364 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingChain.php @@ -0,0 +1,165 @@ +job = $job; + $this->chain = $chain; + } + + /** + * Set the desired connection for the job. + * + * @param string|null $connection + * @return $this + */ + public function onConnection($connection) + { + $this->connection = $connection; + + return $this; + } + + /** + * Set the desired queue for the job. + * + * @param string|null $queue + * @return $this + */ + public function onQueue($queue) + { + $this->queue = $queue; + + return $this; + } + + /** + * Set the desired delay for the chain. + * + * @param \DateTimeInterface|\DateInterval|int|null $delay + * @return $this + */ + public function delay($delay) + { + $this->delay = $delay; + + return $this; + } + + /** + * Add a callback to be executed on job failure. + * + * @param callable $callback + * @return $this + */ + public function catch($callback) + { + $this->catchCallbacks[] = $callback instanceof Closure + ? SerializableClosureFactory::make($callback) + : $callback; + + return $this; + } + + /** + * Get the "catch" callbacks that have been registered. + * + * @return array + */ + public function catchCallbacks() + { + return $this->catchCallbacks ?? []; + } + + /** + * Dispatch the job with the given arguments. + * + * @return \Illuminate\Foundation\Bus\PendingDispatch + */ + public function dispatch() + { + if (is_string($this->job)) { + $firstJob = new $this->job(...func_get_args()); + } elseif ($this->job instanceof Closure) { + $firstJob = CallQueuedClosure::create($this->job); + } else { + $firstJob = $this->job; + } + + if ($this->connection) { + $firstJob->chainConnection = $this->connection; + $firstJob->connection = $firstJob->connection ?: $this->connection; + } + + if ($this->queue) { + $firstJob->chainQueue = $this->queue; + $firstJob->queue = $firstJob->queue ?: $this->queue; + } + + if ($this->delay) { + $firstJob->delay = ! is_null($firstJob->delay) ? $firstJob->delay : $this->delay; + } + + $firstJob->chain($this->chain); + $firstJob->chainCatchCallbacks = $this->catchCallbacks(); + + return app(Dispatcher::class)->dispatch($firstJob); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingClosureDispatch.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingClosureDispatch.php new file mode 100644 index 0000000..84cc14a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingClosureDispatch.php @@ -0,0 +1,21 @@ +job->onFailure($callback); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingDispatch.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingDispatch.php new file mode 100644 index 0000000..76c16db --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingDispatch.php @@ -0,0 +1,196 @@ +job = $job; + } + + /** + * Set the desired connection for the job. + * + * @param string|null $connection + * @return $this + */ + public function onConnection($connection) + { + $this->job->onConnection($connection); + + return $this; + } + + /** + * Set the desired queue for the job. + * + * @param string|null $queue + * @return $this + */ + public function onQueue($queue) + { + $this->job->onQueue($queue); + + return $this; + } + + /** + * Set the desired connection for the chain. + * + * @param string|null $connection + * @return $this + */ + public function allOnConnection($connection) + { + $this->job->allOnConnection($connection); + + return $this; + } + + /** + * Set the desired queue for the chain. + * + * @param string|null $queue + * @return $this + */ + public function allOnQueue($queue) + { + $this->job->allOnQueue($queue); + + return $this; + } + + /** + * Set the desired delay for the job. + * + * @param \DateTimeInterface|\DateInterval|int|null $delay + * @return $this + */ + public function delay($delay) + { + $this->job->delay($delay); + + return $this; + } + + /** + * Indicate that the job should be dispatched after all database transactions have committed. + * + * @return $this + */ + public function afterCommit() + { + $this->job->afterCommit(); + + return $this; + } + + /** + * Indicate that the job should not wait until database transactions have been committed before dispatching. + * + * @return $this + */ + public function beforeCommit() + { + $this->job->beforeCommit(); + + return $this; + } + + /** + * Set the jobs that should run if this job is successful. + * + * @param array $chain + * @return $this + */ + public function chain($chain) + { + $this->job->chain($chain); + + return $this; + } + + /** + * Indicate that the job should be dispatched after the response is sent to the browser. + * + * @return $this + */ + public function afterResponse() + { + $this->afterResponse = true; + + return $this; + } + + /** + * Determine if the job should be dispatched. + * + * @return bool + */ + protected function shouldDispatch() + { + if (! $this->job instanceof ShouldBeUnique) { + return true; + } + + return (new UniqueLock(Container::getInstance()->make(Cache::class))) + ->acquire($this->job); + } + + /** + * Dynamically proxy methods to the underlying job. + * + * @param string $method + * @param array $parameters + * @return $this + */ + public function __call($method, $parameters) + { + $this->job->{$method}(...$parameters); + + return $this; + } + + /** + * Handle the object's destruction. + * + * @return void + */ + public function __destruct() + { + if (! $this->shouldDispatch()) { + return; + } elseif ($this->afterResponse) { + app(Dispatcher::class)->dispatchAfterResponse($this->job); + } else { + app(Dispatcher::class)->dispatch($this->job); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php new file mode 100644 index 0000000..8cf5684 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php @@ -0,0 +1,69 @@ +getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; + + static::clearCompiled(); + } + + /** + * Handle the post-update Composer event. + * + * @param \Composer\Script\Event $event + * @return void + */ + public static function postUpdate(Event $event) + { + require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; + + static::clearCompiled(); + } + + /** + * Handle the post-autoload-dump Composer event. + * + * @param \Composer\Script\Event $event + * @return void + */ + public static function postAutoloadDump(Event $event) + { + require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; + + static::clearCompiled(); + } + + /** + * Clear the cached Laravel bootstrapping files. + * + * @return void + */ + protected static function clearCompiled() + { + $laravel = new Application(getcwd()); + + if (is_file($configPath = $laravel->getCachedConfigPath())) { + @unlink($configPath); + } + + if (is_file($servicesPath = $laravel->getCachedServicesPath())) { + @unlink($servicesPath); + } + + if (is_file($packagesPath = $laravel->getCachedPackagesPath())) { + @unlink($packagesPath); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/CastMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/CastMakeCommand.php new file mode 100644 index 0000000..3fa3a66 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/CastMakeCommand.php @@ -0,0 +1,63 @@ +resolveStubPath('/stubs/cast.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Casts'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ChannelMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ChannelMakeCommand.php new file mode 100644 index 0000000..756fce6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ChannelMakeCommand.php @@ -0,0 +1,65 @@ +userProviderModel()), + parent::buildClass($name) + ); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return __DIR__.'/stubs/channel.stub'; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Broadcasting'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClearCompiledCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClearCompiledCommand.php new file mode 100644 index 0000000..87ea044 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClearCompiledCommand.php @@ -0,0 +1,40 @@ +laravel->getCachedServicesPath())) { + @unlink($servicesPath); + } + + if (is_file($packagesPath = $this->laravel->getCachedPackagesPath())) { + @unlink($packagesPath); + } + + $this->info('Compiled services and packages files removed!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClosureCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClosureCommand.php new file mode 100644 index 0000000..4cd54e8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ClosureCommand.php @@ -0,0 +1,82 @@ +callback = $callback; + $this->signature = $signature; + + parent::__construct(); + } + + /** + * Execute the console command. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @return int + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $inputs = array_merge($input->getArguments(), $input->getOptions()); + + $parameters = []; + + foreach ((new ReflectionFunction($this->callback))->getParameters() as $parameter) { + if (isset($inputs[$parameter->getName()])) { + $parameters[$parameter->getName()] = $inputs[$parameter->getName()]; + } + } + + return (int) $this->laravel->call( + $this->callback->bindTo($this, $this), $parameters + ); + } + + /** + * Set the description for the command. + * + * @param string $description + * @return $this + */ + public function purpose($description) + { + return $this->describe($description); + } + + /** + * Set the description for the command. + * + * @param string $description + * @return $this + */ + public function describe($description) + { + $this->setDescription($description); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ComponentMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ComponentMakeCommand.php new file mode 100644 index 0000000..b0a3344 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ComponentMakeCommand.php @@ -0,0 +1,163 @@ +option('force')) { + return false; + } + + if (! $this->option('inline')) { + $this->writeView(); + } + } + + /** + * Write the view for the component. + * + * @return void + */ + protected function writeView() + { + $path = $this->viewPath( + str_replace('.', '/', 'components.'.$this->getView()).'.blade.php' + ); + + if (! $this->files->isDirectory(dirname($path))) { + $this->files->makeDirectory(dirname($path), 0777, true, true); + } + + if ($this->files->exists($path) && ! $this->option('force')) { + $this->error('View already exists!'); + + return; + } + + file_put_contents( + $path, + '
+ +
' + ); + } + + /** + * Build the class with the given name. + * + * @param string $name + * @return string + */ + protected function buildClass($name) + { + if ($this->option('inline')) { + return str_replace( + ['DummyView', '{{ view }}'], + "<<<'blade'\n
\n \n
\nblade", + parent::buildClass($name) + ); + } + + return str_replace( + ['DummyView', '{{ view }}'], + 'view(\'components.'.$this->getView().'\')', + parent::buildClass($name) + ); + } + + /** + * Get the view name relative to the components directory. + * + * @return string view + */ + protected function getView() + { + $name = str_replace('\\', '/', $this->argument('name')); + + return collect(explode('/', $name)) + ->map(function ($part) { + return Str::kebab($part); + }) + ->implode('.'); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->resolveStubPath('/stubs/view-component.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\View\Components'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['force', null, InputOption::VALUE_NONE, 'Create the class even if the component already exists'], + ['inline', null, InputOption::VALUE_NONE, 'Create a component that renders an inline view'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigCacheCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigCacheCommand.php new file mode 100644 index 0000000..2703ec7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigCacheCommand.php @@ -0,0 +1,92 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + * + * @throws \LogicException + */ + public function handle() + { + $this->call('config:clear'); + + $config = $this->getFreshConfiguration(); + + $configPath = $this->laravel->getCachedConfigPath(); + + $this->files->put( + $configPath, 'files->delete($configPath); + + throw new LogicException('Your configuration files are not serializable.', 0, $e); + } + + $this->info('Configuration cached successfully!'); + } + + /** + * Boot a fresh copy of the application configuration. + * + * @return array + */ + protected function getFreshConfiguration() + { + $app = require $this->laravel->bootstrapPath().'/app.php'; + + $app->useStoragePath($this->laravel->storagePath()); + + $app->make(ConsoleKernelContract::class)->bootstrap(); + + return $app['config']->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigClearCommand.php new file mode 100644 index 0000000..d20e2d8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigClearCommand.php @@ -0,0 +1,55 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->files->delete($this->laravel->getCachedConfigPath()); + + $this->info('Configuration cache cleared!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConsoleMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConsoleMakeCommand.php new file mode 100644 index 0000000..90607c7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ConsoleMakeCommand.php @@ -0,0 +1,97 @@ +option('command'), $stub); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + $relativePath = '/stubs/console.stub'; + + return file_exists($customPath = $this->laravel->basePath(trim($relativePath, '/'))) + ? $customPath + : __DIR__.$relativePath; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Console\Commands'; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the command'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['command', null, InputOption::VALUE_OPTIONAL, 'The terminal command that should be assigned', 'command:name'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/DownCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/DownCommand.php new file mode 100644 index 0000000..676715a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/DownCommand.php @@ -0,0 +1,140 @@ +comment('Application is already down.'); + + return 0; + } + + file_put_contents( + storage_path('framework/down'), + json_encode($this->getDownFilePayload(), JSON_PRETTY_PRINT) + ); + + file_put_contents( + storage_path('framework/maintenance.php'), + file_get_contents(__DIR__.'/stubs/maintenance-mode.stub') + ); + + $this->laravel->get('events')->dispatch(MaintenanceModeEnabled::class); + + $this->comment('Application is now in maintenance mode.'); + } catch (Exception $e) { + $this->error('Failed to enter maintenance mode.'); + + $this->error($e->getMessage()); + + return 1; + } + } + + /** + * Get the payload to be placed in the "down" file. + * + * @return array + */ + protected function getDownFilePayload() + { + return [ + 'except' => $this->excludedPaths(), + 'redirect' => $this->redirectPath(), + 'retry' => $this->getRetryTime(), + 'refresh' => $this->option('refresh'), + 'secret' => $this->option('secret'), + 'status' => (int) $this->option('status', 503), + 'template' => $this->option('render') ? $this->prerenderView() : null, + ]; + } + + /** + * Get the paths that should be excluded from maintenance mode. + * + * @return array + */ + protected function excludedPaths() + { + try { + return $this->laravel->make(PreventRequestsDuringMaintenance::class)->getExcludedPaths(); + } catch (Throwable $e) { + return []; + } + } + + /** + * Get the path that users should be redirected to. + * + * @return string + */ + protected function redirectPath() + { + if ($this->option('redirect') && $this->option('redirect') !== '/') { + return '/'.trim($this->option('redirect'), '/'); + } + + return $this->option('redirect'); + } + + /** + * Prerender the specified view so that it can be rendered even before loading Composer. + * + * @return string + */ + protected function prerenderView() + { + (new RegisterErrorViewPaths)(); + + return view($this->option('render'), [ + 'retryAfter' => $this->option('retry'), + ])->render(); + } + + /** + * Get the number of seconds the client should wait before retrying their request. + * + * @return int|null + */ + protected function getRetryTime() + { + $retry = $this->option('retry'); + + return is_numeric($retry) && $retry > 0 ? (int) $retry : null; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EnvironmentCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EnvironmentCommand.php new file mode 100644 index 0000000..ab3bb32 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EnvironmentCommand.php @@ -0,0 +1,32 @@ +line('Current application environment: '.$this->laravel['env'].''); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventCacheCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventCacheCommand.php new file mode 100644 index 0000000..310b40a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventCacheCommand.php @@ -0,0 +1,58 @@ +call('event:clear'); + + file_put_contents( + $this->laravel->getCachedEventsPath(), + 'getEvents(), true).';' + ); + + $this->info('Events cached successfully!'); + } + + /** + * Get all of the events and listeners configured for the application. + * + * @return array + */ + protected function getEvents() + { + $events = []; + + foreach ($this->laravel->getProviders(EventServiceProvider::class) as $provider) { + $providerEvents = array_merge_recursive($provider->shouldDiscoverEvents() ? $provider->discoverEvents() : [], $provider->listens()); + + $events[get_class($provider)] = $providerEvents; + } + + return $events; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventClearCommand.php new file mode 100644 index 0000000..a5fe4e6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventClearCommand.php @@ -0,0 +1,57 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + * + * @throws \RuntimeException + */ + public function handle() + { + $this->files->delete($this->laravel->getCachedEventsPath()); + + $this->info('Cached events cleared!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventGenerateCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventGenerateCommand.php new file mode 100644 index 0000000..529b198 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventGenerateCommand.php @@ -0,0 +1,78 @@ +laravel->getProviders(EventServiceProvider::class); + + foreach ($providers as $provider) { + foreach ($provider->listens() as $event => $listeners) { + $this->makeEventAndListeners($event, $listeners); + } + } + + $this->info('Events and listeners generated successfully!'); + } + + /** + * Make the event and listeners for the given event. + * + * @param string $event + * @param array $listeners + * @return void + */ + protected function makeEventAndListeners($event, $listeners) + { + if (! Str::contains($event, '\\')) { + return; + } + + $this->callSilent('make:event', ['name' => $event]); + + $this->makeListeners($event, $listeners); + } + + /** + * Make the listeners for the given event. + * + * @param string $event + * @param array $listeners + * @return void + */ + protected function makeListeners($event, $listeners) + { + foreach ($listeners as $listener) { + $listener = preg_replace('/@.+$/', '', $listener); + + $this->callSilent('make:listener', array_filter( + ['name' => $listener, '--event' => $event] + )); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventListCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventListCommand.php new file mode 100644 index 0000000..4b11ebb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventListCommand.php @@ -0,0 +1,91 @@ +getEvents(); + + if (empty($events)) { + return $this->error("Your application doesn't have any events matching the given criteria."); + } + + $this->table(['Event', 'Listeners'], $events); + } + + /** + * Get all of the events and listeners configured for the application. + * + * @return array + */ + protected function getEvents() + { + $events = []; + + foreach ($this->laravel->getProviders(EventServiceProvider::class) as $provider) { + $providerEvents = array_merge_recursive($provider->shouldDiscoverEvents() ? $provider->discoverEvents() : [], $provider->listens()); + + $events = array_merge_recursive($events, $providerEvents); + } + + if ($this->filteringByEvent()) { + $events = $this->filterEvents($events); + } + + return collect($events)->map(function ($listeners, $event) { + return ['Event' => $event, 'Listeners' => implode(PHP_EOL, $listeners)]; + })->sortBy('Event')->values()->toArray(); + } + + /** + * Filter the given events using the provided event name filter. + * + * @param array $events + * @return array + */ + protected function filterEvents(array $events) + { + if (! $eventName = $this->option('event')) { + return $events; + } + + return collect($events)->filter(function ($listeners, $event) use ($eventName) { + return Str::contains($event, $eventName); + })->toArray(); + } + + /** + * Determine whether the user is filtering by an event name. + * + * @return bool + */ + protected function filteringByEvent() + { + return ! empty($this->option('event')); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventMakeCommand.php new file mode 100644 index 0000000..632be4b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/EventMakeCommand.php @@ -0,0 +1,75 @@ +files->exists($this->getPath($this->qualifyClass($rawName))); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->resolveStubPath('/stubs/event.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Events'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ExceptionMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ExceptionMakeCommand.php new file mode 100644 index 0000000..2bc0e6c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ExceptionMakeCommand.php @@ -0,0 +1,84 @@ +option('render')) { + return $this->option('report') + ? __DIR__.'/stubs/exception-render-report.stub' + : __DIR__.'/stubs/exception-render.stub'; + } + + return $this->option('report') + ? __DIR__.'/stubs/exception-report.stub' + : __DIR__.'/stubs/exception.stub'; + } + + /** + * Determine if the class already exists. + * + * @param string $rawName + * @return bool + */ + protected function alreadyExists($rawName) + { + return class_exists($this->rootNamespace().'Exceptions\\'.$rawName); + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Exceptions'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['render', null, InputOption::VALUE_NONE, 'Create the exception with an empty render method'], + + ['report', null, InputOption::VALUE_NONE, 'Create the exception with an empty report method'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/JobMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/JobMakeCommand.php new file mode 100644 index 0000000..bec3d9d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/JobMakeCommand.php @@ -0,0 +1,81 @@ +option('sync') + ? $this->resolveStubPath('/stubs/job.stub') + : $this->resolveStubPath('/stubs/job.queued.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Jobs'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['sync', null, InputOption::VALUE_NONE, 'Indicates that job should be synchronous'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php new file mode 100644 index 0000000..cdfaeaf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php @@ -0,0 +1,380 @@ +app = $app; + $this->events = $events; + + $this->app->booted(function () { + $this->defineConsoleSchedule(); + }); + } + + /** + * Define the application's command schedule. + * + * @return void + */ + protected function defineConsoleSchedule() + { + $this->app->singleton(Schedule::class, function ($app) { + return tap(new Schedule($this->scheduleTimezone()), function ($schedule) { + $this->schedule($schedule->useCache($this->scheduleCache())); + }); + }); + } + + /** + * Get the name of the cache store that should manage scheduling mutexes. + * + * @return string + */ + protected function scheduleCache() + { + return $this->app['config']->get('cache.schedule_store', Env::get('SCHEDULE_CACHE_DRIVER')); + } + + /** + * Run the console application. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param \Symfony\Component\Console\Output\OutputInterface|null $output + * @return int + */ + public function handle($input, $output = null) + { + try { + $this->bootstrap(); + + return $this->getArtisan()->run($input, $output); + } catch (Throwable $e) { + $this->reportException($e); + + $this->renderException($output, $e); + + return 1; + } + } + + /** + * Terminate the application. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param int $status + * @return void + */ + public function terminate($input, $status) + { + $this->app->terminate(); + } + + /** + * Define the application's command schedule. + * + * @param \Illuminate\Console\Scheduling\Schedule $schedule + * @return void + */ + protected function schedule(Schedule $schedule) + { + // + } + + /** + * Get the timezone that should be used by default for scheduled events. + * + * @return \DateTimeZone|string|null + */ + protected function scheduleTimezone() + { + $config = $this->app['config']; + + return $config->get('app.schedule_timezone', $config->get('app.timezone')); + } + + /** + * Register the commands for the application. + * + * @return void + */ + protected function commands() + { + // + } + + /** + * Register a Closure based command with the application. + * + * @param string $signature + * @param \Closure $callback + * @return \Illuminate\Foundation\Console\ClosureCommand + */ + public function command($signature, Closure $callback) + { + $command = new ClosureCommand($signature, $callback); + + Artisan::starting(function ($artisan) use ($command) { + $artisan->add($command); + }); + + return $command; + } + + /** + * Register all of the commands in the given directory. + * + * @param array|string $paths + * @return void + */ + protected function load($paths) + { + $paths = array_unique(Arr::wrap($paths)); + + $paths = array_filter($paths, function ($path) { + return is_dir($path); + }); + + if (empty($paths)) { + return; + } + + $namespace = $this->app->getNamespace(); + + foreach ((new Finder)->in($paths)->files() as $command) { + $command = $namespace.str_replace( + ['/', '.php'], + ['\\', ''], + Str::after($command->getRealPath(), realpath(app_path()).DIRECTORY_SEPARATOR) + ); + + if (is_subclass_of($command, Command::class) && + ! (new ReflectionClass($command))->isAbstract()) { + Artisan::starting(function ($artisan) use ($command) { + $artisan->resolve($command); + }); + } + } + } + + /** + * Register the given command with the console application. + * + * @param \Symfony\Component\Console\Command\Command $command + * @return void + */ + public function registerCommand($command) + { + $this->getArtisan()->add($command); + } + + /** + * Run an Artisan console command by name. + * + * @param string $command + * @param array $parameters + * @param \Symfony\Component\Console\Output\OutputInterface|null $outputBuffer + * @return int + * + * @throws \Symfony\Component\Console\Exception\CommandNotFoundException + */ + public function call($command, array $parameters = [], $outputBuffer = null) + { + $this->bootstrap(); + + return $this->getArtisan()->call($command, $parameters, $outputBuffer); + } + + /** + * Queue the given console command. + * + * @param string $command + * @param array $parameters + * @return \Illuminate\Foundation\Bus\PendingDispatch + */ + public function queue($command, array $parameters = []) + { + return QueuedCommand::dispatch(func_get_args()); + } + + /** + * Get all of the commands registered with the console. + * + * @return array + */ + public function all() + { + $this->bootstrap(); + + return $this->getArtisan()->all(); + } + + /** + * Get the output for the last run command. + * + * @return string + */ + public function output() + { + $this->bootstrap(); + + return $this->getArtisan()->output(); + } + + /** + * Bootstrap the application for artisan commands. + * + * @return void + */ + public function bootstrap() + { + if (! $this->app->hasBeenBootstrapped()) { + $this->app->bootstrapWith($this->bootstrappers()); + } + + $this->app->loadDeferredProviders(); + + if (! $this->commandsLoaded) { + $this->commands(); + + $this->commandsLoaded = true; + } + } + + /** + * Get the Artisan application instance. + * + * @return \Illuminate\Console\Application + */ + protected function getArtisan() + { + if (is_null($this->artisan)) { + return $this->artisan = (new Artisan($this->app, $this->events, $this->app->version())) + ->resolveCommands($this->commands); + } + + return $this->artisan; + } + + /** + * Set the Artisan application instance. + * + * @param \Illuminate\Console\Application $artisan + * @return void + */ + public function setArtisan($artisan) + { + $this->artisan = $artisan; + } + + /** + * Get the bootstrap classes for the application. + * + * @return array + */ + protected function bootstrappers() + { + return $this->bootstrappers; + } + + /** + * Report the exception to the exception handler. + * + * @param \Throwable $e + * @return void + */ + protected function reportException(Throwable $e) + { + $this->app[ExceptionHandler::class]->report($e); + } + + /** + * Render the given exception. + * + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @param \Throwable $e + * @return void + */ + protected function renderException($output, Throwable $e) + { + $this->app[ExceptionHandler::class]->renderForConsole($output, $e); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php new file mode 100644 index 0000000..030ca21 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php @@ -0,0 +1,111 @@ +generateRandomKey(); + + if ($this->option('show')) { + return $this->line(''.$key.''); + } + + // Next, we will replace the application key in the environment file so it is + // automatically setup for this developer. This key gets generated using a + // secure random byte generator and is later base64 encoded for storage. + if (! $this->setKeyInEnvironmentFile($key)) { + return; + } + + $this->laravel['config']['app.key'] = $key; + + $this->info('Application key set successfully.'); + } + + /** + * Generate a random key for the application. + * + * @return string + */ + protected function generateRandomKey() + { + return 'base64:'.base64_encode( + Encrypter::generateKey($this->laravel['config']['app.cipher']) + ); + } + + /** + * Set the application key in the environment file. + * + * @param string $key + * @return bool + */ + protected function setKeyInEnvironmentFile($key) + { + $currentKey = $this->laravel['config']['app.key']; + + if (strlen($currentKey) !== 0 && (! $this->confirmToProceed())) { + return false; + } + + $this->writeNewEnvironmentFileWith($key); + + return true; + } + + /** + * Write a new environment file with the given key. + * + * @param string $key + * @return void + */ + protected function writeNewEnvironmentFileWith($key) + { + file_put_contents($this->laravel->environmentFilePath(), preg_replace( + $this->keyReplacementPattern(), + 'APP_KEY='.$key, + file_get_contents($this->laravel->environmentFilePath()) + )); + } + + /** + * Get a regex pattern that will match env APP_KEY with any random key. + * + * @return string + */ + protected function keyReplacementPattern() + { + $escaped = preg_quote('='.$this->laravel['config']['app.key'], '/'); + + return "/^APP_KEY{$escaped}/m"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ListenerMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ListenerMakeCommand.php new file mode 100644 index 0000000..b27e798 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ListenerMakeCommand.php @@ -0,0 +1,115 @@ +option('event'); + + if (! Str::startsWith($event, [ + $this->laravel->getNamespace(), + 'Illuminate', + '\\', + ])) { + $event = $this->laravel->getNamespace().'Events\\'.str_replace('/', '\\', $event); + } + + $stub = str_replace( + ['DummyEvent', '{{ event }}'], class_basename($event), parent::buildClass($name) + ); + + return str_replace( + ['DummyFullEvent', '{{ eventNamespace }}'], trim($event, '\\'), $stub + ); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + if ($this->option('queued')) { + return $this->option('event') + ? __DIR__.'/stubs/listener-queued.stub' + : __DIR__.'/stubs/listener-queued-duck.stub'; + } + + return $this->option('event') + ? __DIR__.'/stubs/listener.stub' + : __DIR__.'/stubs/listener-duck.stub'; + } + + /** + * Determine if the class already exists. + * + * @param string $rawName + * @return bool + */ + protected function alreadyExists($rawName) + { + return class_exists($rawName); + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Listeners'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['event', 'e', InputOption::VALUE_OPTIONAL, 'The event class being listened for'], + + ['queued', null, InputOption::VALUE_NONE, 'Indicates the event listener should be queued'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/MailMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/MailMakeCommand.php new file mode 100644 index 0000000..e32e2e2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/MailMakeCommand.php @@ -0,0 +1,152 @@ +option('force')) { + return; + } + + if ($this->option('markdown') !== false) { + $this->writeMarkdownTemplate(); + } + } + + /** + * Write the Markdown template for the mailable. + * + * @return void + */ + protected function writeMarkdownTemplate() + { + $path = $this->viewPath( + str_replace('.', '/', $this->getView()).'.blade.php' + ); + + if (! $this->files->isDirectory(dirname($path))) { + $this->files->makeDirectory(dirname($path), 0755, true); + } + + $this->files->put($path, file_get_contents(__DIR__.'/stubs/markdown.stub')); + } + + /** + * Build the class with the given name. + * + * @param string $name + * @return string + */ + protected function buildClass($name) + { + $class = parent::buildClass($name); + + if ($this->option('markdown') !== false) { + $class = str_replace(['DummyView', '{{ view }}'], $this->getView(), $class); + } + + return $class; + } + + /** + * Get the view name. + * + * @return string + */ + protected function getView() + { + $view = $this->option('markdown'); + + if (! $view) { + $view = 'mail.'.Str::kebab(class_basename($this->argument('name'))); + } + + return $view; + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->resolveStubPath( + $this->option('markdown') !== false + ? '/stubs/markdown-mail.stub' + : '/stubs/mail.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Mail'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the mailable already exists'], + + ['markdown', 'm', InputOption::VALUE_OPTIONAL, 'Create a new Markdown template for the mailable', false], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ModelMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ModelMakeCommand.php new file mode 100644 index 0000000..4f03aae --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ModelMakeCommand.php @@ -0,0 +1,215 @@ +option('force')) { + return false; + } + + if ($this->option('all')) { + $this->input->setOption('factory', true); + $this->input->setOption('seed', true); + $this->input->setOption('migration', true); + $this->input->setOption('controller', true); + $this->input->setOption('policy', true); + $this->input->setOption('resource', true); + } + + if ($this->option('factory')) { + $this->createFactory(); + } + + if ($this->option('migration')) { + $this->createMigration(); + } + + if ($this->option('seed')) { + $this->createSeeder(); + } + + if ($this->option('controller') || $this->option('resource') || $this->option('api')) { + $this->createController(); + } + + if ($this->option('policy')) { + $this->createPolicy(); + } + } + + /** + * Create a model factory for the model. + * + * @return void + */ + protected function createFactory() + { + $factory = Str::studly($this->argument('name')); + + $this->call('make:factory', [ + 'name' => "{$factory}Factory", + '--model' => $this->qualifyClass($this->getNameInput()), + ]); + } + + /** + * Create a migration file for the model. + * + * @return void + */ + protected function createMigration() + { + $table = Str::snake(Str::pluralStudly(class_basename($this->argument('name')))); + + if ($this->option('pivot')) { + $table = Str::singular($table); + } + + $this->call('make:migration', [ + 'name' => "create_{$table}_table", + '--create' => $table, + ]); + } + + /** + * Create a seeder file for the model. + * + * @return void + */ + protected function createSeeder() + { + $seeder = Str::studly(class_basename($this->argument('name'))); + + $this->call('make:seeder', [ + 'name' => "{$seeder}Seeder", + ]); + } + + /** + * Create a controller for the model. + * + * @return void + */ + protected function createController() + { + $controller = Str::studly(class_basename($this->argument('name'))); + + $modelName = $this->qualifyClass($this->getNameInput()); + + $this->call('make:controller', array_filter([ + 'name' => "{$controller}Controller", + '--model' => $this->option('resource') || $this->option('api') ? $modelName : null, + '--api' => $this->option('api'), + '--requests' => $this->option('requests') || $this->option('all'), + ])); + } + + /** + * Create a policy file for the model. + * + * @return void + */ + protected function createPolicy() + { + $policy = Str::studly(class_basename($this->argument('name'))); + + $this->call('make:policy', [ + 'name' => "{$policy}Policy", + '--model' => $this->qualifyClass($this->getNameInput()), + ]); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->option('pivot') + ? $this->resolveStubPath('/stubs/model.pivot.stub') + : $this->resolveStubPath('/stubs/model.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return is_dir(app_path('Models')) ? $rootNamespace.'\\Models' : $rootNamespace; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['all', 'a', InputOption::VALUE_NONE, 'Generate a migration, seeder, factory, policy, and resource controller for the model'], + ['controller', 'c', InputOption::VALUE_NONE, 'Create a new controller for the model'], + ['factory', 'f', InputOption::VALUE_NONE, 'Create a new factory for the model'], + ['force', null, InputOption::VALUE_NONE, 'Create the class even if the model already exists'], + ['migration', 'm', InputOption::VALUE_NONE, 'Create a new migration file for the model'], + ['policy', null, InputOption::VALUE_NONE, 'Create a new policy for the model'], + ['seed', 's', InputOption::VALUE_NONE, 'Create a new seeder for the model'], + ['pivot', 'p', InputOption::VALUE_NONE, 'Indicates if the generated model should be a custom intermediate table model'], + ['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller'], + ['api', null, InputOption::VALUE_NONE, 'Indicates if the generated controller should be an API controller'], + ['requests', 'R', InputOption::VALUE_NONE, 'Create new form request classes and use them in the resource controller'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/NotificationMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/NotificationMakeCommand.php new file mode 100644 index 0000000..f8a5bf8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/NotificationMakeCommand.php @@ -0,0 +1,134 @@ +option('force')) { + return; + } + + if ($this->option('markdown')) { + $this->writeMarkdownTemplate(); + } + } + + /** + * Write the Markdown template for the mailable. + * + * @return void + */ + protected function writeMarkdownTemplate() + { + $path = $this->viewPath( + str_replace('.', '/', $this->option('markdown')).'.blade.php' + ); + + if (! $this->files->isDirectory(dirname($path))) { + $this->files->makeDirectory(dirname($path), 0755, true); + } + + $this->files->put($path, file_get_contents(__DIR__.'/stubs/markdown.stub')); + } + + /** + * Build the class with the given name. + * + * @param string $name + * @return string + */ + protected function buildClass($name) + { + $class = parent::buildClass($name); + + if ($this->option('markdown')) { + $class = str_replace(['DummyView', '{{ view }}'], $this->option('markdown'), $class); + } + + return $class; + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->option('markdown') + ? $this->resolveStubPath('/stubs/markdown-notification.stub') + : $this->resolveStubPath('/stubs/notification.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Notifications'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the notification already exists'], + + ['markdown', 'm', InputOption::VALUE_OPTIONAL, 'Create a new Markdown template for the notification'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ObserverMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ObserverMakeCommand.php new file mode 100644 index 0000000..a2661f3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ObserverMakeCommand.php @@ -0,0 +1,139 @@ +option('model'); + + return $model ? $this->replaceModel($stub, $model) : $stub; + } + + /** + * Replace the model for the given stub. + * + * @param string $stub + * @param string $model + * @return string + */ + protected function replaceModel($stub, $model) + { + $modelClass = $this->parseModel($model); + + $replace = [ + 'DummyFullModelClass' => $modelClass, + '{{ namespacedModel }}' => $modelClass, + '{{namespacedModel}}' => $modelClass, + 'DummyModelClass' => class_basename($modelClass), + '{{ model }}' => class_basename($modelClass), + '{{model}}' => class_basename($modelClass), + 'DummyModelVariable' => lcfirst(class_basename($modelClass)), + '{{ modelVariable }}' => lcfirst(class_basename($modelClass)), + '{{modelVariable}}' => lcfirst(class_basename($modelClass)), + ]; + + return str_replace( + array_keys($replace), array_values($replace), $stub + ); + } + + /** + * Get the fully-qualified model class name. + * + * @param string $model + * @return string + * + * @throws \InvalidArgumentException + */ + protected function parseModel($model) + { + if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) { + throw new InvalidArgumentException('Model name contains invalid characters.'); + } + + return $this->qualifyModel($model); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->option('model') + ? $this->resolveStubPath('/stubs/observer.stub') + : $this->resolveStubPath('/stubs/observer.plain.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Observers'; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getOptions() + { + return [ + ['model', 'm', InputOption::VALUE_OPTIONAL, 'The model that the observer applies to.'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/OptimizeClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/OptimizeClearCommand.php new file mode 100644 index 0000000..7506cc2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/OptimizeClearCommand.php @@ -0,0 +1,39 @@ +call('event:clear'); + $this->call('view:clear'); + $this->call('cache:clear'); + $this->call('route:clear'); + $this->call('config:clear'); + $this->call('clear-compiled'); + + $this->info('Caches cleared successfully!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/OptimizeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/OptimizeCommand.php new file mode 100644 index 0000000..af5d731 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/OptimizeCommand.php @@ -0,0 +1,35 @@ +call('config:cache'); + $this->call('route:cache'); + + $this->info('Files cached successfully!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/PackageDiscoverCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/PackageDiscoverCommand.php new file mode 100644 index 0000000..3ef8f01 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/PackageDiscoverCommand.php @@ -0,0 +1,40 @@ +build(); + + foreach (array_keys($manifest->manifest) as $package) { + $this->line("Discovered Package: {$package}"); + } + + $this->info('Package manifest generated successfully.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/PolicyMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/PolicyMakeCommand.php new file mode 100644 index 0000000..aeb9590 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/PolicyMakeCommand.php @@ -0,0 +1,198 @@ +replaceUserNamespace( + parent::buildClass($name) + ); + + $model = $this->option('model'); + + return $model ? $this->replaceModel($stub, $model) : $stub; + } + + /** + * Replace the User model namespace. + * + * @param string $stub + * @return string + */ + protected function replaceUserNamespace($stub) + { + $model = $this->userProviderModel(); + + if (! $model) { + return $stub; + } + + return str_replace( + $this->rootNamespace().'User', + $model, + $stub + ); + } + + /** + * Get the model for the guard's user provider. + * + * @return string|null + * + * @throws \LogicException + */ + protected function userProviderModel() + { + $config = $this->laravel['config']; + + $guard = $this->option('guard') ?: $config->get('auth.defaults.guard'); + + if (is_null($guardProvider = $config->get('auth.guards.'.$guard.'.provider'))) { + throw new LogicException('The ['.$guard.'] guard is not defined in your "auth" configuration file.'); + } + + if (! $config->get('auth.providers.'.$guardProvider.'.model')) { + return 'App\\Models\\User'; + } + + return $config->get( + 'auth.providers.'.$guardProvider.'.model' + ); + } + + /** + * Replace the model for the given stub. + * + * @param string $stub + * @param string $model + * @return string + */ + protected function replaceModel($stub, $model) + { + $model = str_replace('/', '\\', $model); + + if (Str::startsWith($model, '\\')) { + $namespacedModel = trim($model, '\\'); + } else { + $namespacedModel = $this->qualifyModel($model); + } + + $model = class_basename(trim($model, '\\')); + + $dummyUser = class_basename($this->userProviderModel()); + + $dummyModel = Str::camel($model) === 'user' ? 'model' : $model; + + $replace = [ + 'NamespacedDummyModel' => $namespacedModel, + '{{ namespacedModel }}' => $namespacedModel, + '{{namespacedModel}}' => $namespacedModel, + 'DummyModel' => $model, + '{{ model }}' => $model, + '{{model}}' => $model, + 'dummyModel' => Str::camel($dummyModel), + '{{ modelVariable }}' => Str::camel($dummyModel), + '{{modelVariable}}' => Str::camel($dummyModel), + 'DummyUser' => $dummyUser, + '{{ user }}' => $dummyUser, + '{{user}}' => $dummyUser, + '$user' => '$'.Str::camel($dummyUser), + ]; + + $stub = str_replace( + array_keys($replace), array_values($replace), $stub + ); + + return preg_replace( + vsprintf('/use %s;[\r\n]+use %s;/', [ + preg_quote($namespacedModel, '/'), + preg_quote($namespacedModel, '/'), + ]), + "use {$namespacedModel};", + $stub + ); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->option('model') + ? $this->resolveStubPath('/stubs/policy.stub') + : $this->resolveStubPath('/stubs/policy.plain.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Policies'; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getOptions() + { + return [ + ['model', 'm', InputOption::VALUE_OPTIONAL, 'The model that the policy applies to'], + ['guard', 'g', InputOption::VALUE_OPTIONAL, 'The guard that the policy relies on'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ProviderMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ProviderMakeCommand.php new file mode 100644 index 0000000..ffe6499 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ProviderMakeCommand.php @@ -0,0 +1,63 @@ +resolveStubPath('/stubs/provider.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Providers'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/QueuedCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/QueuedCommand.php new file mode 100644 index 0000000..fb3d027 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/QueuedCommand.php @@ -0,0 +1,42 @@ +data = $data; + } + + /** + * Handle the job. + * + * @param \Illuminate\Contracts\Console\Kernel $kernel + * @return void + */ + public function handle(KernelContract $kernel) + { + $kernel->call(...array_values($this->data)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RequestMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RequestMakeCommand.php new file mode 100644 index 0000000..4605c81 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RequestMakeCommand.php @@ -0,0 +1,63 @@ +resolveStubPath('/stubs/request.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Http\Requests'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ResourceMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ResourceMakeCommand.php new file mode 100644 index 0000000..abaf6f0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ResourceMakeCommand.php @@ -0,0 +1,104 @@ +collection()) { + $this->type = 'Resource collection'; + } + + parent::handle(); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + return $this->collection() + ? $this->resolveStubPath('/stubs/resource-collection.stub') + : $this->resolveStubPath('/stubs/resource.stub'); + } + + /** + * Determine if the command is generating a resource collection. + * + * @return bool + */ + protected function collection() + { + return $this->option('collection') || + Str::endsWith($this->argument('name'), 'Collection'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Http\Resources'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['collection', 'c', InputOption::VALUE_NONE, 'Create a resource collection'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteCacheCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteCacheCommand.php new file mode 100644 index 0000000..05e5267 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteCacheCommand.php @@ -0,0 +1,109 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->call('route:clear'); + + $routes = $this->getFreshApplicationRoutes(); + + if (count($routes) === 0) { + return $this->error("Your application doesn't have any routes."); + } + + foreach ($routes as $route) { + $route->prepareForSerialization(); + } + + $this->files->put( + $this->laravel->getCachedRoutesPath(), $this->buildRouteCacheFile($routes) + ); + + $this->info('Routes cached successfully!'); + } + + /** + * Boot a fresh copy of the application and get the routes. + * + * @return \Illuminate\Routing\RouteCollection + */ + protected function getFreshApplicationRoutes() + { + return tap($this->getFreshApplication()['router']->getRoutes(), function ($routes) { + $routes->refreshNameLookups(); + $routes->refreshActionLookups(); + }); + } + + /** + * Get a fresh application instance. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + protected function getFreshApplication() + { + return tap(require $this->laravel->bootstrapPath().'/app.php', function ($app) { + $app->make(ConsoleKernelContract::class)->bootstrap(); + }); + } + + /** + * Build the route cache file. + * + * @param \Illuminate\Routing\RouteCollection $routes + * @return string + */ + protected function buildRouteCacheFile(RouteCollection $routes) + { + $stub = $this->files->get(__DIR__.'/stubs/routes.stub'); + + return str_replace('{{routes}}', var_export($routes->compile(), true), $stub); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteClearCommand.php new file mode 100644 index 0000000..03fab1d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteClearCommand.php @@ -0,0 +1,55 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->files->delete($this->laravel->getCachedRoutesPath()); + + $this->info('Route cache cleared!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteListCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteListCommand.php new file mode 100644 index 0000000..956a651 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteListCommand.php @@ -0,0 +1,293 @@ +router = $router; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->router->flushMiddlewareGroups(); + + if (empty($this->router->getRoutes())) { + return $this->error("Your application doesn't have any routes."); + } + + if (empty($routes = $this->getRoutes())) { + return $this->error("Your application doesn't have any routes matching the given criteria."); + } + + $this->displayRoutes($routes); + } + + /** + * Compile the routes into a displayable format. + * + * @return array + */ + protected function getRoutes() + { + $routes = collect($this->router->getRoutes())->map(function ($route) { + return $this->getRouteInformation($route); + })->filter()->all(); + + if (($sort = $this->option('sort')) !== 'precedence') { + $routes = $this->sortRoutes($sort, $routes); + } + + if ($this->option('reverse')) { + $routes = array_reverse($routes); + } + + return $this->pluckColumns($routes); + } + + /** + * Get the route information for a given route. + * + * @param \Illuminate\Routing\Route $route + * @return array + */ + protected function getRouteInformation(Route $route) + { + return $this->filterRoute([ + 'domain' => $route->domain(), + 'method' => implode('|', $route->methods()), + 'uri' => $route->uri(), + 'name' => $route->getName(), + 'action' => ltrim($route->getActionName(), '\\'), + 'middleware' => $this->getMiddleware($route), + ]); + } + + /** + * Sort the routes by a given element. + * + * @param string $sort + * @param array $routes + * @return array + */ + protected function sortRoutes($sort, array $routes) + { + return Arr::sort($routes, function ($route) use ($sort) { + return $route[$sort]; + }); + } + + /** + * Remove unnecessary columns from the routes. + * + * @param array $routes + * @return array + */ + protected function pluckColumns(array $routes) + { + return array_map(function ($route) { + return Arr::only($route, $this->getColumns()); + }, $routes); + } + + /** + * Display the route information on the console. + * + * @param array $routes + * @return void + */ + protected function displayRoutes(array $routes) + { + if ($this->option('json')) { + $this->line($this->asJson($routes)); + + return; + } + + $this->table($this->getHeaders(), $routes); + } + + /** + * Get the middleware for the route. + * + * @param \Illuminate\Routing\Route $route + * @return string + */ + protected function getMiddleware($route) + { + return collect($this->router->gatherRouteMiddleware($route))->map(function ($middleware) { + return $middleware instanceof Closure ? 'Closure' : $middleware; + })->implode("\n"); + } + + /** + * Filter the route by URI and / or name. + * + * @param array $route + * @return array|null + */ + protected function filterRoute(array $route) + { + if (($this->option('name') && ! Str::contains($route['name'], $this->option('name'))) || + $this->option('path') && ! Str::contains($route['uri'], $this->option('path')) || + $this->option('method') && ! Str::contains($route['method'], strtoupper($this->option('method')))) { + return; + } + + if ($this->option('except-path')) { + foreach (explode(',', $this->option('except-path')) as $path) { + if (Str::contains($route['uri'], $path)) { + return; + } + } + } + + return $route; + } + + /** + * Get the table headers for the visible columns. + * + * @return array + */ + protected function getHeaders() + { + return Arr::only($this->headers, array_keys($this->getColumns())); + } + + /** + * Get the column names to show (lowercase table headers). + * + * @return array + */ + protected function getColumns() + { + $availableColumns = array_map('strtolower', $this->headers); + + if ($this->option('compact')) { + return array_intersect($availableColumns, $this->compactColumns); + } + + if ($columns = $this->option('columns')) { + return array_intersect($availableColumns, $this->parseColumns($columns)); + } + + return $availableColumns; + } + + /** + * Parse the column list. + * + * @param array $columns + * @return array + */ + protected function parseColumns(array $columns) + { + $results = []; + + foreach ($columns as $i => $column) { + if (Str::contains($column, ',')) { + $results = array_merge($results, explode(',', $column)); + } else { + $results[] = $column; + } + } + + return array_map('strtolower', $results); + } + + /** + * Convert the given routes to JSON. + * + * @param array $routes + * @return string + */ + protected function asJson(array $routes) + { + return collect($routes) + ->map(function ($route) { + $route['middleware'] = empty($route['middleware']) ? [] : explode("\n", $route['middleware']); + + return $route; + }) + ->values() + ->toJson(); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['columns', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Columns to include in the route table'], + ['compact', 'c', InputOption::VALUE_NONE, 'Only show method, URI and action columns'], + ['json', null, InputOption::VALUE_NONE, 'Output the route list as JSON'], + ['method', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by method'], + ['name', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by name'], + ['path', null, InputOption::VALUE_OPTIONAL, 'Only show routes matching the given path pattern'], + ['except-path', null, InputOption::VALUE_OPTIONAL, 'Do not display the routes matching the given path pattern'], + ['reverse', 'r', InputOption::VALUE_NONE, 'Reverse the ordering of the routes'], + ['sort', null, InputOption::VALUE_OPTIONAL, 'The column (precedence, domain, method, uri, name, action, middleware) to sort by', 'uri'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RuleMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RuleMakeCommand.php new file mode 100644 index 0000000..b6f2a1d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/RuleMakeCommand.php @@ -0,0 +1,84 @@ +option('implicit') ? 'ImplicitRule' : 'Rule', + parent::buildClass($name) + ); + } + + /** + * Get the stub file for the generator. + * + * @return string + */ + protected function getStub() + { + $relativePath = '/stubs/rule.stub'; + + return file_exists($customPath = $this->laravel->basePath(trim($relativePath, '/'))) + ? $customPath + : __DIR__.$relativePath; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Rules'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['implicit', 'i', InputOption::VALUE_NONE, 'Generate an implicit rule.'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php new file mode 100644 index 0000000..ddb07e8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php @@ -0,0 +1,207 @@ +line("Starting Laravel development server: http://{$this->host()}:{$this->port()}"); + + $environmentFile = $this->option('env') + ? base_path('.env').'.'.$this->option('env') + : base_path('.env'); + + $hasEnvironment = file_exists($environmentFile); + + $environmentLastModified = $hasEnvironment + ? filemtime($environmentFile) + : now()->addDays(30)->getTimestamp(); + + $process = $this->startProcess($hasEnvironment); + + while ($process->isRunning()) { + if ($hasEnvironment) { + clearstatcache(false, $environmentFile); + } + + if (! $this->option('no-reload') && + $hasEnvironment && + filemtime($environmentFile) > $environmentLastModified) { + $environmentLastModified = filemtime($environmentFile); + + $this->comment('Environment modified. Restarting server...'); + + $process->stop(5); + + $process = $this->startProcess($hasEnvironment); + } + + usleep(500 * 1000); + } + + $status = $process->getExitCode(); + + if ($status && $this->canTryAnotherPort()) { + $this->portOffset += 1; + + return $this->handle(); + } + + return $status; + } + + /** + * Start a new server process. + * + * @param bool $hasEnvironment + * @return \Symfony\Component\Process\Process + */ + protected function startProcess($hasEnvironment) + { + $process = new Process($this->serverCommand(), null, collect($_ENV)->mapWithKeys(function ($value, $key) use ($hasEnvironment) { + if ($this->option('no-reload') || ! $hasEnvironment) { + return [$key => $value]; + } + + return in_array($key, [ + 'APP_ENV', + 'LARAVEL_SAIL', + 'PHP_CLI_SERVER_WORKERS', + 'PHP_IDE_CONFIG', + 'SYSTEMROOT', + 'XDEBUG_CONFIG', + 'XDEBUG_MODE', + 'XDEBUG_SESSION', + ]) ? [$key => $value] : [$key => false]; + })->all()); + + $process->start(function ($type, $buffer) { + $this->output->write($buffer); + }); + + return $process; + } + + /** + * Get the full server command. + * + * @return array + */ + protected function serverCommand() + { + return [ + (new PhpExecutableFinder)->find(false), + '-S', + $this->host().':'.$this->port(), + base_path('server.php'), + ]; + } + + /** + * Get the host for the command. + * + * @return string + */ + protected function host() + { + [$host, ] = $this->getHostAndPort(); + + return $host; + } + + /** + * Get the port for the command. + * + * @return string + */ + protected function port() + { + $port = $this->input->getOption('port'); + + if (is_null($port)) { + [, $port] = $this->getHostAndPort(); + } + + $port = $port ?: 8000; + + return $port + $this->portOffset; + } + + /** + * Get the host and port from the host option string. + * + * @return array + */ + protected function getHostAndPort() + { + $hostParts = explode(':', $this->input->getOption('host')); + + return [ + $hostParts[0], + $hostParts[1] ?? null, + ]; + } + + /** + * Check if the command has reached its max amount of port tries. + * + * @return bool + */ + protected function canTryAnotherPort() + { + return is_null($this->input->getOption('port')) && + ($this->input->getOption('tries') > $this->portOffset); + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on', '127.0.0.1'], + ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on', Env::get('SERVER_PORT')], + ['tries', null, InputOption::VALUE_OPTIONAL, 'The max number of ports to attempt to serve from', 10], + ['no-reload', null, InputOption::VALUE_NONE, 'Do not reload the development server on .env file changes'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/StorageLinkCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/StorageLinkCommand.php new file mode 100644 index 0000000..7926d80 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/StorageLinkCommand.php @@ -0,0 +1,78 @@ +option('relative'); + + foreach ($this->links() as $link => $target) { + if (file_exists($link) && ! $this->isRemovableSymlink($link, $this->option('force'))) { + $this->error("The [$link] link already exists."); + continue; + } + + if (is_link($link)) { + $this->laravel->make('files')->delete($link); + } + + if ($relative) { + $this->laravel->make('files')->relativeLink($target, $link); + } else { + $this->laravel->make('files')->link($target, $link); + } + + $this->info("The [$link] link has been connected to [$target]."); + } + + $this->info('The links have been created.'); + } + + /** + * Get the symbolic links that are configured for the application. + * + * @return array + */ + protected function links() + { + return $this->laravel['config']['filesystems.links'] ?? + [public_path('storage') => storage_path('app/public')]; + } + + /** + * Determine if the provided path is a symlink that can be removed. + * + * @param string $link + * @param bool $force + * @return bool + */ + protected function isRemovableSymlink(string $link, bool $force): bool + { + return is_link($link) && $force; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/StubPublishCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/StubPublishCommand.php new file mode 100644 index 0000000..4594f07 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/StubPublishCommand.php @@ -0,0 +1,83 @@ +laravel->basePath('stubs'))) { + (new Filesystem)->makeDirectory($stubsPath); + } + + $files = [ + __DIR__.'/stubs/cast.stub' => $stubsPath.'/cast.stub', + __DIR__.'/stubs/console.stub' => $stubsPath.'/console.stub', + __DIR__.'/stubs/event.stub' => $stubsPath.'/event.stub', + __DIR__.'/stubs/job.queued.stub' => $stubsPath.'/job.queued.stub', + __DIR__.'/stubs/job.stub' => $stubsPath.'/job.stub', + __DIR__.'/stubs/mail.stub' => $stubsPath.'/mail.stub', + __DIR__.'/stubs/markdown-mail.stub' => $stubsPath.'/markdown-mail.stub', + __DIR__.'/stubs/markdown-notification.stub' => $stubsPath.'/markdown-notification.stub', + __DIR__.'/stubs/model.pivot.stub' => $stubsPath.'/model.pivot.stub', + __DIR__.'/stubs/model.stub' => $stubsPath.'/model.stub', + __DIR__.'/stubs/notification.stub' => $stubsPath.'/notification.stub', + __DIR__.'/stubs/observer.plain.stub' => $stubsPath.'/observer.plain.stub', + __DIR__.'/stubs/observer.stub' => $stubsPath.'/observer.stub', + __DIR__.'/stubs/policy.plain.stub' => $stubsPath.'/policy.plain.stub', + __DIR__.'/stubs/policy.stub' => $stubsPath.'/policy.stub', + __DIR__.'/stubs/provider.stub' => $stubsPath.'/provider.stub', + __DIR__.'/stubs/request.stub' => $stubsPath.'/request.stub', + __DIR__.'/stubs/resource-collection.stub' => $stubsPath.'/resource-collection.stub', + __DIR__.'/stubs/resource.stub' => $stubsPath.'/resource.stub', + __DIR__.'/stubs/rule.stub' => $stubsPath.'/rule.stub', + __DIR__.'/stubs/test.stub' => $stubsPath.'/test.stub', + __DIR__.'/stubs/test.unit.stub' => $stubsPath.'/test.unit.stub', + __DIR__.'/stubs/view-component.stub' => $stubsPath.'/view-component.stub', + realpath(__DIR__.'/../../Database/Console/Factories/stubs/factory.stub') => $stubsPath.'/factory.stub', + realpath(__DIR__.'/../../Database/Console/Seeds/stubs/seeder.stub') => $stubsPath.'/seeder.stub', + realpath(__DIR__.'/../../Database/Migrations/stubs/migration.create.stub') => $stubsPath.'/migration.create.stub', + realpath(__DIR__.'/../../Database/Migrations/stubs/migration.stub') => $stubsPath.'/migration.stub', + realpath(__DIR__.'/../../Database/Migrations/stubs/migration.update.stub') => $stubsPath.'/migration.update.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.api.stub') => $stubsPath.'/controller.api.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.invokable.stub') => $stubsPath.'/controller.invokable.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.model.api.stub') => $stubsPath.'/controller.model.api.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.model.stub') => $stubsPath.'/controller.model.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.nested.api.stub') => $stubsPath.'/controller.nested.api.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.nested.stub') => $stubsPath.'/controller.nested.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.plain.stub') => $stubsPath.'/controller.plain.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/controller.stub') => $stubsPath.'/controller.stub', + realpath(__DIR__.'/../../Routing/Console/stubs/middleware.stub') => $stubsPath.'/middleware.stub', + ]; + + foreach ($files as $from => $to) { + if (! file_exists($to) || $this->option('force')) { + file_put_contents($to, file_get_contents($from)); + } + } + + $this->info('Stubs published successfully.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/TestMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/TestMakeCommand.php new file mode 100644 index 0000000..eced47b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/TestMakeCommand.php @@ -0,0 +1,109 @@ +option('unit') ? '.unit.stub' : '.stub'; + + return $this->option('pest') + ? $this->resolveStubPath('/stubs/pest'.$suffix) + : $this->resolveStubPath('/stubs/test'.$suffix); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the destination class path. + * + * @param string $name + * @return string + */ + protected function getPath($name) + { + $name = Str::replaceFirst($this->rootNamespace(), '', $name); + + return base_path('tests').str_replace('\\', '/', $name).'.php'; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + if ($this->option('unit')) { + return $rootNamespace.'\Unit'; + } else { + return $rootNamespace.'\Feature'; + } + } + + /** + * Get the root namespace for the class. + * + * @return string + */ + protected function rootNamespace() + { + return 'Tests'; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['unit', 'u', InputOption::VALUE_NONE, 'Create a unit test.'], + ['pest', 'p', InputOption::VALUE_NONE, 'Create a Pest test.'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/UpCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/UpCommand.php new file mode 100644 index 0000000..b651247 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/UpCommand.php @@ -0,0 +1,56 @@ +comment('Application is already up.'); + + return 0; + } + + unlink(storage_path('framework/down')); + + if (is_file(storage_path('framework/maintenance.php'))) { + unlink(storage_path('framework/maintenance.php')); + } + + $this->laravel->get('events')->dispatch(MaintenanceModeDisabled::class); + + $this->info('Application is now live.'); + } catch (Exception $e) { + $this->error('Failed to disable maintenance mode.'); + + $this->error($e->getMessage()); + + return 1; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php new file mode 100644 index 0000000..db28b9e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php @@ -0,0 +1,288 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->determineWhatShouldBePublished(); + + foreach ($this->tags ?: [null] as $tag) { + $this->publishTag($tag); + } + + $this->info('Publishing complete.'); + } + + /** + * Determine the provider or tag(s) to publish. + * + * @return void + */ + protected function determineWhatShouldBePublished() + { + if ($this->option('all')) { + return; + } + + [$this->provider, $this->tags] = [ + $this->option('provider'), (array) $this->option('tag'), + ]; + + if (! $this->provider && ! $this->tags) { + $this->promptForProviderOrTag(); + } + } + + /** + * Prompt for which provider or tag to publish. + * + * @return void + */ + protected function promptForProviderOrTag() + { + $choice = $this->choice( + "Which provider or tag's files would you like to publish?", + $choices = $this->publishableChoices() + ); + + if ($choice == $choices[0] || is_null($choice)) { + return; + } + + $this->parseChoice($choice); + } + + /** + * The choices available via the prompt. + * + * @return array + */ + protected function publishableChoices() + { + return array_merge( + ['Publish files from all providers and tags listed below'], + preg_filter('/^/', 'Provider: ', Arr::sort(ServiceProvider::publishableProviders())), + preg_filter('/^/', 'Tag: ', Arr::sort(ServiceProvider::publishableGroups())) + ); + } + + /** + * Parse the answer that was given via the prompt. + * + * @param string $choice + * @return void + */ + protected function parseChoice($choice) + { + [$type, $value] = explode(': ', strip_tags($choice)); + + if ($type === 'Provider') { + $this->provider = $value; + } elseif ($type === 'Tag') { + $this->tags = [$value]; + } + } + + /** + * Publishes the assets for a tag. + * + * @param string $tag + * @return mixed + */ + protected function publishTag($tag) + { + $published = false; + + $pathsToPublish = $this->pathsToPublish($tag); + + foreach ($pathsToPublish as $from => $to) { + $this->publishItem($from, $to); + + $published = true; + } + + if ($published === false) { + $this->comment('No publishable resources for tag ['.$tag.'].'); + } else { + $this->laravel['events']->dispatch(new VendorTagPublished($tag, $pathsToPublish)); + } + } + + /** + * Get all of the paths to publish. + * + * @param string $tag + * @return array + */ + protected function pathsToPublish($tag) + { + return ServiceProvider::pathsToPublish( + $this->provider, $tag + ); + } + + /** + * Publish the given item from and to the given location. + * + * @param string $from + * @param string $to + * @return void + */ + protected function publishItem($from, $to) + { + if ($this->files->isFile($from)) { + return $this->publishFile($from, $to); + } elseif ($this->files->isDirectory($from)) { + return $this->publishDirectory($from, $to); + } + + $this->error("Can't locate path: <{$from}>"); + } + + /** + * Publish the file to the given path. + * + * @param string $from + * @param string $to + * @return void + */ + protected function publishFile($from, $to) + { + if (! $this->files->exists($to) || $this->option('force')) { + $this->createParentDirectory(dirname($to)); + + $this->files->copy($from, $to); + + $this->status($from, $to, 'File'); + } + } + + /** + * Publish the directory to the given directory. + * + * @param string $from + * @param string $to + * @return void + */ + protected function publishDirectory($from, $to) + { + $this->moveManagedFiles(new MountManager([ + 'from' => new Flysystem(new LocalAdapter($from)), + 'to' => new Flysystem(new LocalAdapter($to)), + ])); + + $this->status($from, $to, 'Directory'); + } + + /** + * Move all the files in the given MountManager. + * + * @param \League\Flysystem\MountManager $manager + * @return void + */ + protected function moveManagedFiles($manager) + { + foreach ($manager->listContents('from://', true) as $file) { + if ($file['type'] === 'file' && (! $manager->has('to://'.$file['path']) || $this->option('force'))) { + $manager->put('to://'.$file['path'], $manager->read('from://'.$file['path'])); + } + } + } + + /** + * Create the directory to house the published files if needed. + * + * @param string $directory + * @return void + */ + protected function createParentDirectory($directory) + { + if (! $this->files->isDirectory($directory)) { + $this->files->makeDirectory($directory, 0755, true); + } + } + + /** + * Write a status message to the console. + * + * @param string $from + * @param string $to + * @param string $type + * @return void + */ + protected function status($from, $to, $type) + { + $from = str_replace(base_path(), '', realpath($from)); + + $to = str_replace(base_path(), '', realpath($to)); + + $this->line('Copied '.$type.' ['.$from.'] To ['.$to.']'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ViewCacheCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ViewCacheCommand.php new file mode 100644 index 0000000..19e0ab5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ViewCacheCommand.php @@ -0,0 +1,87 @@ +call('view:clear'); + + $this->paths()->each(function ($path) { + $this->compileViews($this->bladeFilesIn([$path])); + }); + + $this->info('Blade templates cached successfully!'); + } + + /** + * Compile the given view files. + * + * @param \Illuminate\Support\Collection $views + * @return void + */ + protected function compileViews(Collection $views) + { + $compiler = $this->laravel['view']->getEngineResolver()->resolve('blade')->getCompiler(); + + $views->map(function (SplFileInfo $file) use ($compiler) { + $compiler->compile($file->getRealPath()); + }); + } + + /** + * Get the Blade files in the given path. + * + * @param array $paths + * @return \Illuminate\Support\Collection + */ + protected function bladeFilesIn(array $paths) + { + return collect( + Finder::create() + ->in($paths) + ->exclude('vendor') + ->name('*.blade.php') + ->files() + ); + } + + /** + * Get all of the possible view paths. + * + * @return \Illuminate\Support\Collection + */ + protected function paths() + { + $finder = $this->laravel['view']->getFinder(); + + return collect($finder->getPaths())->merge( + collect($finder->getHints())->flatten() + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ViewClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ViewClearCommand.php new file mode 100644 index 0000000..449ebe4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/ViewClearCommand.php @@ -0,0 +1,66 @@ +files = $files; + } + + /** + * Execute the console command. + * + * @return void + * + * @throws \RuntimeException + */ + public function handle() + { + $path = $this->laravel['config']['view.compiled']; + + if (! $path) { + throw new RuntimeException('View path not found.'); + } + + foreach ($this->files->glob("{$path}/*") as $view) { + $this->files->delete($view); + } + + $this->info('Compiled views cleared!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/cast.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/cast.stub new file mode 100644 index 0000000..25d35b6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/cast.stub @@ -0,0 +1,36 @@ +view('view.name'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/maintenance-mode.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/maintenance-mode.stub new file mode 100644 index 0000000..a90b8cd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/maintenance-mode.stub @@ -0,0 +1,78 @@ += time()) { + return; + } +} + +// Redirect to the proper path if necessary... +if (isset($data['redirect']) && $_SERVER['REQUEST_URI'] !== $data['redirect']) { + http_response_code(302); + header('Location: '.$data['redirect']); + + exit; +} + +// Output the prerendered template... +http_response_code($data['status'] ?? 503); + +if (isset($data['retry'])) { + header('Retry-After: '.$data['retry']); +} + +if (isset($data['refresh'])) { + header('Refresh: '.$data['refresh']); +} + +echo $data['template']; + +exit; diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown-mail.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown-mail.stub new file mode 100644 index 0000000..e4c7cd4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown-mail.stub @@ -0,0 +1,33 @@ +markdown('{{ view }}'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown-notification.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown-notification.stub new file mode 100644 index 0000000..5438f04 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown-notification.stub @@ -0,0 +1,58 @@ +markdown('{{ view }}'); + } + + /** + * Get the array representation of the notification. + * + * @param mixed $notifiable + * @return array + */ + public function toArray($notifiable) + { + return [ + // + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown.stub new file mode 100644 index 0000000..bc41428 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/markdown.stub @@ -0,0 +1,12 @@ +@component('mail::message') +# Introduction + +The body of your message. + +@component('mail::button', ['url' => '']) +Button Text +@endcomponent + +Thanks,
+{{ config('app.name') }} +@endcomponent diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/model.pivot.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/model.pivot.stub new file mode 100644 index 0000000..35a674a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/model.pivot.stub @@ -0,0 +1,10 @@ +line('The introduction to the notification.') + ->action('Notification Action', url('/')) + ->line('Thank you for using our application!'); + } + + /** + * Get the array representation of the notification. + * + * @param mixed $notifiable + * @return array + */ + public function toArray($notifiable) + { + return [ + // + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/observer.plain.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/observer.plain.stub new file mode 100644 index 0000000..e2506b7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/observer.plain.stub @@ -0,0 +1,8 @@ +get('/'); + + $response->assertStatus(200); +}); diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/pest.unit.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/pest.unit.stub new file mode 100644 index 0000000..61cd84c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/pest.unit.stub @@ -0,0 +1,5 @@ +toBeTrue(); +}); diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/policy.plain.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/policy.plain.stub new file mode 100644 index 0000000..b014d85 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/policy.plain.stub @@ -0,0 +1,21 @@ +setCompiledRoutes( + {{routes}} +); diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/rule.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/rule.stub new file mode 100644 index 0000000..587ec32 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/rule.stub @@ -0,0 +1,40 @@ +get('/'); + + $response->assertStatus(200); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/test.unit.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/test.unit.stub new file mode 100644 index 0000000..b6816aa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/test.unit.stub @@ -0,0 +1,18 @@ +assertTrue(true); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/view-component.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/view-component.stub new file mode 100644 index 0000000..eab8fd3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/view-component.stub @@ -0,0 +1,28 @@ +detectConsoleEnvironment($callback, $consoleArgs); + } + + return $this->detectWebEnvironment($callback); + } + + /** + * Set the application environment for a web request. + * + * @param \Closure $callback + * @return string + */ + protected function detectWebEnvironment(Closure $callback) + { + return $callback(); + } + + /** + * Set the application environment from command-line arguments. + * + * @param \Closure $callback + * @param array $args + * @return string + */ + protected function detectConsoleEnvironment(Closure $callback, array $args) + { + // First we will check if an environment argument was passed via console arguments + // and if it was that automatically overrides as the environment. Otherwise, we + // will check the environment as a "web" request like a typical HTTP request. + if (! is_null($value = $this->getEnvironmentArgument($args))) { + return $value; + } + + return $this->detectWebEnvironment($callback); + } + + /** + * Get the environment argument from the console. + * + * @param array $args + * @return string|null + */ + protected function getEnvironmentArgument(array $args) + { + foreach ($args as $i => $value) { + if ($value === '--env') { + return $args[$i + 1] ?? null; + } + + if (Str::startsWith($value, '--env')) { + return head(array_slice(explode('=', $value), 1)); + } + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/DiscoverEvents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/DiscoverEvents.php new file mode 100644 index 0000000..6d07df0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/DiscoverEvents.php @@ -0,0 +1,98 @@ +files()->in($listenerPath), $basePath + )); + + $discoveredEvents = []; + + foreach ($listeners as $listener => $events) { + foreach ($events as $event) { + if (! isset($discoveredEvents[$event])) { + $discoveredEvents[$event] = []; + } + + $discoveredEvents[$event][] = $listener; + } + } + + return $discoveredEvents; + } + + /** + * Get all of the listeners and their corresponding events. + * + * @param iterable $listeners + * @param string $basePath + * @return array + */ + protected static function getListenerEvents($listeners, $basePath) + { + $listenerEvents = []; + + foreach ($listeners as $listener) { + try { + $listener = new ReflectionClass( + static::classFromFile($listener, $basePath) + ); + } catch (ReflectionException $e) { + continue; + } + + if (! $listener->isInstantiable()) { + continue; + } + + foreach ($listener->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if (! Str::is('handle*', $method->name) || + ! isset($method->getParameters()[0])) { + continue; + } + + $listenerEvents[$listener->name.'@'.$method->name] = + Reflector::getParameterClassNames($method->getParameters()[0]); + } + } + + return array_filter($listenerEvents); + } + + /** + * Extract the class name from the given file path. + * + * @param \SplFileInfo $file + * @param string $basePath + * @return string + */ + protected static function classFromFile(SplFileInfo $file, $basePath) + { + $class = trim(Str::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); + + return str_replace( + [DIRECTORY_SEPARATOR, ucfirst(basename(app()->path())).'\\'], + ['\\', app()->getNamespace()], + ucfirst(Str::replaceLast('.php', '', $class)) + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/Dispatchable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/Dispatchable.php new file mode 100644 index 0000000..ff63315 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/Dispatchable.php @@ -0,0 +1,54 @@ +locale = $locale; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/MaintenanceModeDisabled.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/MaintenanceModeDisabled.php new file mode 100644 index 0000000..f8edf47 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Events/MaintenanceModeDisabled.php @@ -0,0 +1,8 @@ +tag = $tag; + $this->paths = $paths; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php new file mode 100644 index 0000000..444caf7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php @@ -0,0 +1,694 @@ + + */ + protected $exceptionMap = []; + + /** + * A list of the internal exception types that should not be reported. + * + * @var string[] + */ + protected $internalDontReport = [ + AuthenticationException::class, + AuthorizationException::class, + HttpException::class, + HttpResponseException::class, + ModelNotFoundException::class, + MultipleRecordsFoundException::class, + RecordsNotFoundException::class, + SuspiciousOperationException::class, + TokenMismatchException::class, + ValidationException::class, + ]; + + /** + * A list of the inputs that are never flashed for validation exceptions. + * + * @var string[] + */ + protected $dontFlash = [ + 'current_password', + 'password', + 'password_confirmation', + ]; + + /** + * Create a new exception handler instance. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function __construct(Container $container) + { + $this->container = $container; + + $this->register(); + } + + /** + * Register the exception handling callbacks for the application. + * + * @return void + */ + public function register() + { + // + } + + /** + * Register a reportable callback. + * + * @param callable $reportUsing + * @return \Illuminate\Foundation\Exceptions\ReportableHandler + */ + public function reportable(callable $reportUsing) + { + if (! $reportUsing instanceof Closure) { + $reportUsing = Closure::fromCallable($reportUsing); + } + + return tap(new ReportableHandler($reportUsing), function ($callback) { + $this->reportCallbacks[] = $callback; + }); + } + + /** + * Register a renderable callback. + * + * @param callable $renderUsing + * @return $this + */ + public function renderable(callable $renderUsing) + { + if (! $renderUsing instanceof Closure) { + $renderUsing = Closure::fromCallable($renderUsing); + } + + $this->renderCallbacks[] = $renderUsing; + + return $this; + } + + /** + * Register a new exception mapping. + * + * @param \Closure|string $from + * @param \Closure|string|null $to + * @return $this + * + * @throws \InvalidArgumentException + */ + public function map($from, $to = null) + { + if (is_string($to)) { + $to = function ($exception) use ($to) { + return new $to('', 0, $exception); + }; + } + + if (is_callable($from) && is_null($to)) { + $from = $this->firstClosureParameterType($to = $from); + } + + if (! is_string($from) || ! $to instanceof Closure) { + throw new InvalidArgumentException('Invalid exception mapping.'); + } + + $this->exceptionMap[$from] = $to; + + return $this; + } + + /** + * Indicate that the given exception type should not be reported. + * + * @param string $class + * @return $this + */ + protected function ignore(string $class) + { + $this->dontReport[] = $class; + + return $this; + } + + /** + * Report or log an exception. + * + * @param \Throwable $e + * @return void + * + * @throws \Throwable + */ + public function report(Throwable $e) + { + $e = $this->mapException($e); + + if ($this->shouldntReport($e)) { + return; + } + + if (Reflector::isCallable($reportCallable = [$e, 'report'])) { + if ($this->container->call($reportCallable) !== false) { + return; + } + } + + foreach ($this->reportCallbacks as $reportCallback) { + if ($reportCallback->handles($e)) { + if ($reportCallback($e) === false) { + return; + } + } + } + + try { + $logger = $this->container->make(LoggerInterface::class); + } catch (Exception $ex) { + throw $e; + } + + $logger->error( + $e->getMessage(), + array_merge( + $this->exceptionContext($e), + $this->context(), + ['exception' => $e] + ) + ); + } + + /** + * Determine if the exception should be reported. + * + * @param \Throwable $e + * @return bool + */ + public function shouldReport(Throwable $e) + { + return ! $this->shouldntReport($e); + } + + /** + * Determine if the exception is in the "do not report" list. + * + * @param \Throwable $e + * @return bool + */ + protected function shouldntReport(Throwable $e) + { + $dontReport = array_merge($this->dontReport, $this->internalDontReport); + + return ! is_null(Arr::first($dontReport, function ($type) use ($e) { + return $e instanceof $type; + })); + } + + /** + * Get the default exception context variables for logging. + * + * @param \Throwable $e + * @return array + */ + protected function exceptionContext(Throwable $e) + { + if (method_exists($e, 'context')) { + return $e->context(); + } + + return []; + } + + /** + * Get the default context variables for logging. + * + * @return array + */ + protected function context() + { + try { + return array_filter([ + 'userId' => Auth::id(), + // 'email' => optional(Auth::user())->email, + ]); + } catch (Throwable $e) { + return []; + } + } + + /** + * Render an exception into an HTTP response. + * + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return \Symfony\Component\HttpFoundation\Response + * + * @throws \Throwable + */ + public function render($request, Throwable $e) + { + if (method_exists($e, 'render') && $response = $e->render($request)) { + return Router::toResponse($request, $response); + } elseif ($e instanceof Responsable) { + return $e->toResponse($request); + } + + $e = $this->prepareException($this->mapException($e)); + + foreach ($this->renderCallbacks as $renderCallback) { + foreach ($this->firstClosureParameterTypes($renderCallback) as $type) { + if (is_a($e, $type)) { + $response = $renderCallback($e, $request); + + if (! is_null($response)) { + return $response; + } + } + } + } + + if ($e instanceof HttpResponseException) { + return $e->getResponse(); + } elseif ($e instanceof AuthenticationException) { + return $this->unauthenticated($request, $e); + } elseif ($e instanceof ValidationException) { + return $this->convertValidationExceptionToResponse($e, $request); + } + + return $this->shouldReturnJson($request, $e) + ? $this->prepareJsonResponse($request, $e) + : $this->prepareResponse($request, $e); + } + + /** + * Map the exception using a registered mapper if possible. + * + * @param \Throwable $e + * @return \Throwable + */ + protected function mapException(Throwable $e) + { + foreach ($this->exceptionMap as $class => $mapper) { + if (is_a($e, $class)) { + return $mapper($e); + } + } + + return $e; + } + + /** + * Prepare exception for rendering. + * + * @param \Throwable $e + * @return \Throwable + */ + protected function prepareException(Throwable $e) + { + if ($e instanceof ModelNotFoundException) { + $e = new NotFoundHttpException($e->getMessage(), $e); + } elseif ($e instanceof AuthorizationException) { + $e = new AccessDeniedHttpException($e->getMessage(), $e); + } elseif ($e instanceof TokenMismatchException) { + $e = new HttpException(419, $e->getMessage(), $e); + } elseif ($e instanceof SuspiciousOperationException) { + $e = new NotFoundHttpException('Bad hostname provided.', $e); + } elseif ($e instanceof RecordsNotFoundException) { + $e = new NotFoundHttpException('Not found.', $e); + } + + return $e; + } + + /** + * Convert an authentication exception into a response. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Auth\AuthenticationException $exception + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function unauthenticated($request, AuthenticationException $exception) + { + return $this->shouldReturnJson($request, $exception) + ? response()->json(['message' => $exception->getMessage()], 401) + : redirect()->guest($exception->redirectTo() ?? route('login')); + } + + /** + * Create a response object from the given validation exception. + * + * @param \Illuminate\Validation\ValidationException $e + * @param \Illuminate\Http\Request $request + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function convertValidationExceptionToResponse(ValidationException $e, $request) + { + if ($e->response) { + return $e->response; + } + + return $this->shouldReturnJson($request, $e) + ? $this->invalidJson($request, $e) + : $this->invalid($request, $e); + } + + /** + * Convert a validation exception into a response. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Validation\ValidationException $exception + * @return \Illuminate\Http\Response + */ + protected function invalid($request, ValidationException $exception) + { + return redirect($exception->redirectTo ?? url()->previous()) + ->withInput(Arr::except($request->input(), $this->dontFlash)) + ->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag)); + } + + /** + * Convert a validation exception into a JSON response. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Validation\ValidationException $exception + * @return \Illuminate\Http\JsonResponse + */ + protected function invalidJson($request, ValidationException $exception) + { + return response()->json([ + 'message' => $exception->getMessage(), + 'errors' => $exception->errors(), + ], $exception->status); + } + + /** + * Determine if the exception handler response should be JSON. + * + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return bool + */ + protected function shouldReturnJson($request, Throwable $e) + { + return $request->expectsJson(); + } + + /** + * Prepare a response for the given exception. + * + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function prepareResponse($request, Throwable $e) + { + if (! $this->isHttpException($e) && config('app.debug')) { + return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e); + } + + if (! $this->isHttpException($e)) { + $e = new HttpException(500, $e->getMessage()); + } + + return $this->toIlluminateResponse( + $this->renderHttpException($e), $e + ); + } + + /** + * Create a Symfony response for the given exception. + * + * @param \Throwable $e + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function convertExceptionToResponse(Throwable $e) + { + return new SymfonyResponse( + $this->renderExceptionContent($e), + $this->isHttpException($e) ? $e->getStatusCode() : 500, + $this->isHttpException($e) ? $e->getHeaders() : [] + ); + } + + /** + * Get the response content for the given exception. + * + * @param \Throwable $e + * @return string + */ + protected function renderExceptionContent(Throwable $e) + { + try { + return config('app.debug') && class_exists(Whoops::class) + ? $this->renderExceptionWithWhoops($e) + : $this->renderExceptionWithSymfony($e, config('app.debug')); + } catch (Exception $e) { + return $this->renderExceptionWithSymfony($e, config('app.debug')); + } + } + + /** + * Render an exception to a string using "Whoops". + * + * @param \Throwable $e + * @return string + */ + protected function renderExceptionWithWhoops(Throwable $e) + { + return tap(new Whoops, function ($whoops) { + $whoops->appendHandler($this->whoopsHandler()); + + $whoops->writeToOutput(false); + + $whoops->allowQuit(false); + })->handleException($e); + } + + /** + * Get the Whoops handler for the application. + * + * @return \Whoops\Handler\Handler + */ + protected function whoopsHandler() + { + try { + return app(HandlerInterface::class); + } catch (BindingResolutionException $e) { + return (new WhoopsHandler)->forDebug(); + } + } + + /** + * Render an exception to a string using Symfony. + * + * @param \Throwable $e + * @param bool $debug + * @return string + */ + protected function renderExceptionWithSymfony(Throwable $e, $debug) + { + $renderer = new HtmlErrorRenderer($debug); + + return $renderer->render($e)->getAsString(); + } + + /** + * Render the given HttpException. + * + * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function renderHttpException(HttpExceptionInterface $e) + { + $this->registerErrorViewPaths(); + + if (view()->exists($view = $this->getHttpExceptionView($e))) { + return response()->view($view, [ + 'errors' => new ViewErrorBag, + 'exception' => $e, + ], $e->getStatusCode(), $e->getHeaders()); + } + + return $this->convertExceptionToResponse($e); + } + + /** + * Register the error template hint paths. + * + * @return void + */ + protected function registerErrorViewPaths() + { + (new RegisterErrorViewPaths)(); + } + + /** + * Get the view used to render HTTP exceptions. + * + * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e + * @return string + */ + protected function getHttpExceptionView(HttpExceptionInterface $e) + { + return "errors::{$e->getStatusCode()}"; + } + + /** + * Map the given exception into an Illuminate response. + * + * @param \Symfony\Component\HttpFoundation\Response $response + * @param \Throwable $e + * @return \Illuminate\Http\Response + */ + protected function toIlluminateResponse($response, Throwable $e) + { + if ($response instanceof SymfonyRedirectResponse) { + $response = new RedirectResponse( + $response->getTargetUrl(), $response->getStatusCode(), $response->headers->all() + ); + } else { + $response = new Response( + $response->getContent(), $response->getStatusCode(), $response->headers->all() + ); + } + + return $response->withException($e); + } + + /** + * Prepare a JSON response for the given exception. + * + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return \Illuminate\Http\JsonResponse + */ + protected function prepareJsonResponse($request, Throwable $e) + { + return new JsonResponse( + $this->convertExceptionToArray($e), + $this->isHttpException($e) ? $e->getStatusCode() : 500, + $this->isHttpException($e) ? $e->getHeaders() : [], + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES + ); + } + + /** + * Convert the given exception to an array. + * + * @param \Throwable $e + * @return array + */ + protected function convertExceptionToArray(Throwable $e) + { + return config('app.debug') ? [ + 'message' => $e->getMessage(), + 'exception' => get_class($e), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'trace' => collect($e->getTrace())->map(function ($trace) { + return Arr::except($trace, ['args']); + })->all(), + ] : [ + 'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error', + ]; + } + + /** + * Render an exception to the console. + * + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @param \Throwable $e + * @return void + */ + public function renderForConsole($output, Throwable $e) + { + (new ConsoleApplication)->renderThrowable($e, $output); + } + + /** + * Determine if the given exception is an HTTP exception. + * + * @param \Throwable $e + * @return bool + */ + protected function isHttpException(Throwable $e) + { + return $e instanceof HttpExceptionInterface; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php new file mode 100644 index 0000000..c88f326 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php @@ -0,0 +1,20 @@ +map(function ($path) { + return "{$path}/errors"; + })->push(__DIR__.'/views')->all()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/ReportableHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/ReportableHandler.php new file mode 100644 index 0000000..06a6172 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/ReportableHandler.php @@ -0,0 +1,82 @@ +callback = $callback; + } + + /** + * Invoke the handler. + * + * @param \Throwable $e + * @return bool + */ + public function __invoke(Throwable $e) + { + $result = call_user_func($this->callback, $e); + + if ($result === false) { + return false; + } + + return ! $this->shouldStop; + } + + /** + * Determine if the callback handles the given exception. + * + * @param \Throwable $e + * @return bool + */ + public function handles(Throwable $e) + { + foreach ($this->firstClosureParameterTypes($this->callback) as $type) { + if (is_a($e, $type)) { + return true; + } + } + + return false; + } + + /** + * Indicate that report handling should stop after invoking this callback. + * + * @return $this + */ + public function stop() + { + $this->shouldStop = true; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/WhoopsHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/WhoopsHandler.php new file mode 100644 index 0000000..c91d1ac --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/WhoopsHandler.php @@ -0,0 +1,86 @@ +handleUnconditionally(true); + + $this->registerApplicationPaths($handler) + ->registerBlacklist($handler) + ->registerEditor($handler); + }); + } + + /** + * Register the application paths with the handler. + * + * @param \Whoops\Handler\PrettyPageHandler $handler + * @return $this + */ + protected function registerApplicationPaths($handler) + { + $handler->setApplicationPaths( + array_flip($this->directoriesExceptVendor()) + ); + + return $this; + } + + /** + * Get the application paths except for the "vendor" directory. + * + * @return array + */ + protected function directoriesExceptVendor() + { + return Arr::except( + array_flip((new Filesystem)->directories(base_path())), + [base_path('vendor')] + ); + } + + /** + * Register the blacklist with the handler. + * + * @param \Whoops\Handler\PrettyPageHandler $handler + * @return $this + */ + protected function registerBlacklist($handler) + { + foreach (config('app.debug_blacklist', config('app.debug_hide', [])) as $key => $secrets) { + foreach ($secrets as $secret) { + $handler->blacklist($key, $secret); + } + } + + return $this; + } + + /** + * Register the editor with the handler. + * + * @param \Whoops\Handler\PrettyPageHandler $handler + * @return $this + */ + protected function registerEditor($handler) + { + if (config('app.editor', false)) { + $handler->setEditor(config('app.editor')); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/401.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/401.blade.php new file mode 100644 index 0000000..5c586db --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/401.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Unauthorized')) +@section('code', '401') +@section('message', __('Unauthorized')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/403.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/403.blade.php new file mode 100644 index 0000000..a5506f0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/403.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Forbidden')) +@section('code', '403') +@section('message', __($exception->getMessage() ?: 'Forbidden')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/404.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/404.blade.php new file mode 100644 index 0000000..7549540 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/404.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Not Found')) +@section('code', '404') +@section('message', __('Not Found')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/419.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/419.blade.php new file mode 100644 index 0000000..c09216e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/419.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Page Expired')) +@section('code', '419') +@section('message', __('Page Expired')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/429.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/429.blade.php new file mode 100644 index 0000000..f01b07b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/429.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Too Many Requests')) +@section('code', '429') +@section('message', __('Too Many Requests')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/500.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/500.blade.php new file mode 100644 index 0000000..d9e95d9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/500.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Server Error')) +@section('code', '500') +@section('message', __('Server Error')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/503.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/503.blade.php new file mode 100644 index 0000000..c5a9dde --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/503.blade.php @@ -0,0 +1,5 @@ +@extends('errors::minimal') + +@section('title', __('Service Unavailable')) +@section('code', '503') +@section('message', __('Service Unavailable')) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/illustrated-layout.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/illustrated-layout.blade.php new file mode 100644 index 0000000..2e5b824 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/illustrated-layout.blade.php @@ -0,0 +1,486 @@ + + + + + + + @yield('title') + + + + + + + + + +
+
+
+
+ @yield('code', __('Oh no')) +
+ +
+ +

+ @yield('message') +

+ + + + +
+
+ +
+ @yield('image') +
+
+ + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/layout.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/layout.blade.php new file mode 100644 index 0000000..4f2318f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/layout.blade.php @@ -0,0 +1,57 @@ + + + + + + + @yield('title') + + + + + + + + + +
+
+
+ @yield('message') +
+
+
+ + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/minimal.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/minimal.blade.php new file mode 100644 index 0000000..ee16d44 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/minimal.blade.php @@ -0,0 +1,38 @@ + + + + + + + @yield('title') + + + + + + + + + + +
+
+
+
+ @yield('code') +
+ +
+ @yield('message') +
+
+
+
+ + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Events/RequestHandled.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Events/RequestHandled.php new file mode 100644 index 0000000..d6f71e0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Events/RequestHandled.php @@ -0,0 +1,33 @@ +request = $request; + $this->response = $response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Exceptions/MaintenanceModeException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Exceptions/MaintenanceModeException.php new file mode 100644 index 0000000..5553fde --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Exceptions/MaintenanceModeException.php @@ -0,0 +1,58 @@ +wentDownAt = Date::createFromTimestamp($time); + + if ($retryAfter) { + $this->retryAfter = $retryAfter; + + $this->willBeAvailableAt = Date::instance(Carbon::createFromTimestamp($time)->addRealSeconds($this->retryAfter)); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php new file mode 100644 index 0000000..a20dffe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php @@ -0,0 +1,274 @@ +validator) { + return $this->validator; + } + + $factory = $this->container->make(ValidationFactory::class); + + if (method_exists($this, 'validator')) { + $validator = $this->container->call([$this, 'validator'], compact('factory')); + } else { + $validator = $this->createDefaultValidator($factory); + } + + if (method_exists($this, 'withValidator')) { + $this->withValidator($validator); + } + + $this->setValidator($validator); + + return $this->validator; + } + + /** + * Create the default validator instance. + * + * @param \Illuminate\Contracts\Validation\Factory $factory + * @return \Illuminate\Contracts\Validation\Validator + */ + protected function createDefaultValidator(ValidationFactory $factory) + { + return $factory->make( + $this->validationData(), $this->container->call([$this, 'rules']), + $this->messages(), $this->attributes() + )->stopOnFirstFailure($this->stopOnFirstFailure); + } + + /** + * Get data to be validated from the request. + * + * @return array + */ + public function validationData() + { + return $this->all(); + } + + /** + * Handle a failed validation attempt. + * + * @param \Illuminate\Contracts\Validation\Validator $validator + * @return void + * + * @throws \Illuminate\Validation\ValidationException + */ + protected function failedValidation(Validator $validator) + { + throw (new ValidationException($validator)) + ->errorBag($this->errorBag) + ->redirectTo($this->getRedirectUrl()); + } + + /** + * Get the URL to redirect to on a validation error. + * + * @return string + */ + protected function getRedirectUrl() + { + $url = $this->redirector->getUrlGenerator(); + + if ($this->redirect) { + return $url->to($this->redirect); + } elseif ($this->redirectRoute) { + return $url->route($this->redirectRoute); + } elseif ($this->redirectAction) { + return $url->action($this->redirectAction); + } + + return $url->previous(); + } + + /** + * Determine if the request passes the authorization check. + * + * @return bool + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + protected function passesAuthorization() + { + if (method_exists($this, 'authorize')) { + $result = $this->container->call([$this, 'authorize']); + + return $result instanceof Response ? $result->authorize() : $result; + } + + return true; + } + + /** + * Handle a failed authorization attempt. + * + * @return void + * + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + protected function failedAuthorization() + { + throw new AuthorizationException; + } + + /** + * Get a validated input container for the validated input. + * + * @param array|null $keys + * @return \Illuminate\Support\ValidatedInput|array + */ + public function safe(array $keys = null) + { + return is_array($keys) + ? $this->validator->safe()->only($keys) + : $this->validator->safe(); + } + + /** + * Get the validated data from the request. + * + * @return array + */ + public function validated() + { + return $this->validator->validated(); + } + + /** + * Get custom messages for validator errors. + * + * @return array + */ + public function messages() + { + return []; + } + + /** + * Get custom attributes for validator errors. + * + * @return array + */ + public function attributes() + { + return []; + } + + /** + * Set the Validator instance. + * + * @param \Illuminate\Contracts\Validation\Validator $validator + * @return $this + */ + public function setValidator(Validator $validator) + { + $this->validator = $validator; + + return $this; + } + + /** + * Set the Redirector instance. + * + * @param \Illuminate\Routing\Redirector $redirector + * @return $this + */ + public function setRedirector(Redirector $redirector) + { + $this->redirector = $redirector; + + return $this; + } + + /** + * Set the container implementation. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php new file mode 100644 index 0000000..fa8d9aa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php @@ -0,0 +1,472 @@ +app = $app; + $this->router = $router; + + $this->syncMiddlewareToRouter(); + } + + /** + * Handle an incoming HTTP request. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\Response + */ + public function handle($request) + { + try { + $request->enableHttpMethodParameterOverride(); + + $response = $this->sendRequestThroughRouter($request); + } catch (Throwable $e) { + $this->reportException($e); + + $response = $this->renderException($request, $e); + } + + $this->app['events']->dispatch( + new RequestHandled($request, $response) + ); + + return $response; + } + + /** + * Send the given request through the middleware / router. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\Response + */ + protected function sendRequestThroughRouter($request) + { + $this->app->instance('request', $request); + + Facade::clearResolvedInstance('request'); + + $this->bootstrap(); + + return (new Pipeline($this->app)) + ->send($request) + ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware) + ->then($this->dispatchToRouter()); + } + + /** + * Bootstrap the application for HTTP requests. + * + * @return void + */ + public function bootstrap() + { + if (! $this->app->hasBeenBootstrapped()) { + $this->app->bootstrapWith($this->bootstrappers()); + } + } + + /** + * Get the route dispatcher callback. + * + * @return \Closure + */ + protected function dispatchToRouter() + { + return function ($request) { + $this->app->instance('request', $request); + + return $this->router->dispatch($request); + }; + } + + /** + * Call the terminate method on any terminable middleware. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Response $response + * @return void + */ + public function terminate($request, $response) + { + $this->terminateMiddleware($request, $response); + + $this->app->terminate(); + } + + /** + * Call the terminate method on any terminable middleware. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Response $response + * @return void + */ + protected function terminateMiddleware($request, $response) + { + $middlewares = $this->app->shouldSkipMiddleware() ? [] : array_merge( + $this->gatherRouteMiddleware($request), + $this->middleware + ); + + foreach ($middlewares as $middleware) { + if (! is_string($middleware)) { + continue; + } + + [$name] = $this->parseMiddleware($middleware); + + $instance = $this->app->make($name); + + if (method_exists($instance, 'terminate')) { + $instance->terminate($request, $response); + } + } + } + + /** + * Gather the route middleware for the given request. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + protected function gatherRouteMiddleware($request) + { + if ($route = $request->route()) { + return $this->router->gatherRouteMiddleware($route); + } + + return []; + } + + /** + * Parse a middleware string to get the name and parameters. + * + * @param string $middleware + * @return array + */ + protected function parseMiddleware($middleware) + { + [$name, $parameters] = array_pad(explode(':', $middleware, 2), 2, []); + + if (is_string($parameters)) { + $parameters = explode(',', $parameters); + } + + return [$name, $parameters]; + } + + /** + * Determine if the kernel has a given middleware. + * + * @param string $middleware + * @return bool + */ + public function hasMiddleware($middleware) + { + return in_array($middleware, $this->middleware); + } + + /** + * Add a new middleware to the beginning of the stack if it does not already exist. + * + * @param string $middleware + * @return $this + */ + public function prependMiddleware($middleware) + { + if (array_search($middleware, $this->middleware) === false) { + array_unshift($this->middleware, $middleware); + } + + return $this; + } + + /** + * Add a new middleware to end of the stack if it does not already exist. + * + * @param string $middleware + * @return $this + */ + public function pushMiddleware($middleware) + { + if (array_search($middleware, $this->middleware) === false) { + $this->middleware[] = $middleware; + } + + return $this; + } + + /** + * Prepend the given middleware to the given middleware group. + * + * @param string $group + * @param string $middleware + * @return $this + * + * @throws \InvalidArgumentException + */ + public function prependMiddlewareToGroup($group, $middleware) + { + if (! isset($this->middlewareGroups[$group])) { + throw new InvalidArgumentException("The [{$group}] middleware group has not been defined."); + } + + if (array_search($middleware, $this->middlewareGroups[$group]) === false) { + array_unshift($this->middlewareGroups[$group], $middleware); + } + + $this->syncMiddlewareToRouter(); + + return $this; + } + + /** + * Append the given middleware to the given middleware group. + * + * @param string $group + * @param string $middleware + * @return $this + * + * @throws \InvalidArgumentException + */ + public function appendMiddlewareToGroup($group, $middleware) + { + if (! isset($this->middlewareGroups[$group])) { + throw new InvalidArgumentException("The [{$group}] middleware group has not been defined."); + } + + if (array_search($middleware, $this->middlewareGroups[$group]) === false) { + $this->middlewareGroups[$group][] = $middleware; + } + + $this->syncMiddlewareToRouter(); + + return $this; + } + + /** + * Prepend the given middleware to the middleware priority list. + * + * @param string $middleware + * @return $this + */ + public function prependToMiddlewarePriority($middleware) + { + if (! in_array($middleware, $this->middlewarePriority)) { + array_unshift($this->middlewarePriority, $middleware); + } + + $this->syncMiddlewareToRouter(); + + return $this; + } + + /** + * Append the given middleware to the middleware priority list. + * + * @param string $middleware + * @return $this + */ + public function appendToMiddlewarePriority($middleware) + { + if (! in_array($middleware, $this->middlewarePriority)) { + $this->middlewarePriority[] = $middleware; + } + + $this->syncMiddlewareToRouter(); + + return $this; + } + + /** + * Sync the current state of the middleware to the router. + * + * @return void + */ + protected function syncMiddlewareToRouter() + { + $this->router->middlewarePriority = $this->middlewarePriority; + + foreach ($this->middlewareGroups as $key => $middleware) { + $this->router->middlewareGroup($key, $middleware); + } + + foreach ($this->routeMiddleware as $key => $middleware) { + $this->router->aliasMiddleware($key, $middleware); + } + } + + /** + * Get the priority-sorted list of middleware. + * + * @return array + */ + public function getMiddlewarePriority() + { + return $this->middlewarePriority; + } + + /** + * Get the bootstrap classes for the application. + * + * @return array + */ + protected function bootstrappers() + { + return $this->bootstrappers; + } + + /** + * Report the exception to the exception handler. + * + * @param \Throwable $e + * @return void + */ + protected function reportException(Throwable $e) + { + $this->app[ExceptionHandler::class]->report($e); + } + + /** + * Render the exception to a response. + * + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function renderException($request, Throwable $e) + { + return $this->app[ExceptionHandler::class]->render($request, $e); + } + + /** + * Get the application's route middleware groups. + * + * @return array + */ + public function getMiddlewareGroups() + { + return $this->middlewareGroups; + } + + /** + * Get the application's route middleware. + * + * @return array + */ + public function getRouteMiddleware() + { + return $this->routeMiddleware; + } + + /** + * Get the Laravel application instance. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public function getApplication() + { + return $this->app; + } + + /** + * Set the Laravel application instance. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication(Application $app) + { + $this->app = $app; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/MaintenanceModeBypassCookie.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/MaintenanceModeBypassCookie.php new file mode 100644 index 0000000..ecb6fb9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/MaintenanceModeBypassCookie.php @@ -0,0 +1,43 @@ +addHours(12); + + return new Cookie('laravel_maintenance', base64_encode(json_encode([ + 'expires_at' => $expiresAt->getTimestamp(), + 'mac' => hash_hmac('sha256', $expiresAt->getTimestamp(), $key), + ])), $expiresAt); + } + + /** + * Determine if the given maintenance mode bypass cookie is valid. + * + * @param string $cookie + * @param string $key + * @return bool + */ + public static function isValid(string $cookie, string $key) + { + $payload = json_decode(base64_decode($cookie), true); + + return is_array($payload) && + is_numeric($payload['expires_at'] ?? null) && + isset($payload['mac']) && + hash_equals(hash_hmac('sha256', $payload['expires_at'], $key), $payload['mac']) && + (int) $payload['expires_at'] >= Carbon::now()->getTimestamp(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php new file mode 100644 index 0000000..01a14b4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php @@ -0,0 +1,8 @@ +app = $app; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\HttpException + */ + public function handle($request, Closure $next) + { + if ($this->app->isDownForMaintenance()) { + $data = json_decode(file_get_contents($this->app->storagePath().'/framework/down'), true); + + if (isset($data['secret']) && $request->path() === $data['secret']) { + return $this->bypassResponse($data['secret']); + } + + if ($this->hasValidBypassCookie($request, $data) || + $this->inExceptArray($request)) { + return $next($request); + } + + if (isset($data['redirect'])) { + $path = $data['redirect'] === '/' + ? $data['redirect'] + : trim($data['redirect'], '/'); + + if ($request->path() !== $path) { + return redirect($path); + } + } + + if (isset($data['template'])) { + return response( + $data['template'], + $data['status'] ?? 503, + $this->getHeaders($data) + ); + } + + throw new HttpException( + $data['status'] ?? 503, + 'Service Unavailable', + null, + $this->getHeaders($data) + ); + } + + return $next($request); + } + + /** + * Determine if the incoming request has a maintenance mode bypass cookie. + * + * @param \Illuminate\Http\Request $request + * @param array $data + * @return bool + */ + protected function hasValidBypassCookie($request, array $data) + { + return isset($data['secret']) && + $request->cookie('laravel_maintenance') && + MaintenanceModeBypassCookie::isValid( + $request->cookie('laravel_maintenance'), + $data['secret'] + ); + } + + /** + * Determine if the request has a URI that should be accessible in maintenance mode. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function inExceptArray($request) + { + foreach ($this->except as $except) { + if ($except !== '/') { + $except = trim($except, '/'); + } + + if ($request->fullUrlIs($except) || $request->is($except)) { + return true; + } + } + + return false; + } + + /** + * Redirect the user back to the root of the application with a maintenance mode bypass cookie. + * + * @param string $secret + * @return \Illuminate\Http\RedirectResponse + */ + protected function bypassResponse(string $secret) + { + return redirect('/')->withCookie( + MaintenanceModeBypassCookie::create($secret) + ); + } + + /** + * Get the headers that should be sent with the response. + * + * @param array $data + * @return array + */ + protected function getHeaders($data) + { + $headers = isset($data['retry']) ? ['Retry-After' => $data['retry']] : []; + + if (isset($data['refresh'])) { + $headers['Refresh'] = $data['refresh']; + } + + return $headers; + } + + /** + * Get the URIs that should be accessible even when maintenance mode is enabled. + * + * @return array + */ + public function getExcludedPaths() + { + return $this->except; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php new file mode 100644 index 0000000..fca34f8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php @@ -0,0 +1,95 @@ +clean($request); + + return $next($request); + } + + /** + * Clean the request's data. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + protected function clean($request) + { + $this->cleanParameterBag($request->query); + + if ($request->isJson()) { + $this->cleanParameterBag($request->json()); + } elseif ($request->request !== $request->query) { + $this->cleanParameterBag($request->request); + } + } + + /** + * Clean the data in the parameter bag. + * + * @param \Symfony\Component\HttpFoundation\ParameterBag $bag + * @return void + */ + protected function cleanParameterBag(ParameterBag $bag) + { + $bag->replace($this->cleanArray($bag->all())); + } + + /** + * Clean the data in the given array. + * + * @param array $data + * @param string $keyPrefix + * @return array + */ + protected function cleanArray(array $data, $keyPrefix = '') + { + foreach ($data as $key => $value) { + $data[$key] = $this->cleanValue($keyPrefix.$key, $value); + } + + return collect($data)->all(); + } + + /** + * Clean the given value. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function cleanValue($key, $value) + { + if (is_array($value)) { + return $this->cleanArray($value, $key.'.'); + } + + return $this->transform($key, $value); + } + + /** + * Transform the given value. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function transform($key, $value) + { + return $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php new file mode 100644 index 0000000..fe8f8f8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php @@ -0,0 +1,69 @@ +except, true)) { + return $value; + } + + return is_string($value) ? trim($value) : $value; + } + + /** + * Register a callback that instructs the middleware to be skipped. + * + * @param \Closure $callback + * @return void + */ + public static function skipWhen(Closure $callback) + { + static::$skipCallbacks[] = $callback; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php new file mode 100644 index 0000000..adc5f5a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php @@ -0,0 +1,55 @@ +getPostMaxSize(); + + if ($max > 0 && $request->server('CONTENT_LENGTH') > $max) { + throw new PostTooLargeException; + } + + return $next($request); + } + + /** + * Determine the server 'post_max_size' as bytes. + * + * @return int + */ + protected function getPostMaxSize() + { + if (is_numeric($postMaxSize = ini_get('post_max_size'))) { + return (int) $postMaxSize; + } + + $metric = strtoupper(substr($postMaxSize, -1)); + $postMaxSize = (int) $postMaxSize; + + switch ($metric) { + case 'K': + return $postMaxSize * 1024; + case 'M': + return $postMaxSize * 1048576; + case 'G': + return $postMaxSize * 1073741824; + default: + return $postMaxSize; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php new file mode 100644 index 0000000..5948320 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php @@ -0,0 +1,210 @@ +app = $app; + $this->encrypter = $encrypter; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + * + * @throws \Illuminate\Session\TokenMismatchException + */ + public function handle($request, Closure $next) + { + if ( + $this->isReading($request) || + $this->runningUnitTests() || + $this->inExceptArray($request) || + $this->tokensMatch($request) + ) { + return tap($next($request), function ($response) use ($request) { + if ($this->shouldAddXsrfTokenCookie()) { + $this->addCookieToResponse($request, $response); + } + }); + } + + throw new TokenMismatchException('CSRF token mismatch.'); + } + + /** + * Determine if the HTTP request uses a ‘read’ verb. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function isReading($request) + { + return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']); + } + + /** + * Determine if the application is running unit tests. + * + * @return bool + */ + protected function runningUnitTests() + { + return $this->app->runningInConsole() && $this->app->runningUnitTests(); + } + + /** + * Determine if the request has a URI that should pass through CSRF verification. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function inExceptArray($request) + { + foreach ($this->except as $except) { + if ($except !== '/') { + $except = trim($except, '/'); + } + + if ($request->fullUrlIs($except) || $request->is($except)) { + return true; + } + } + + return false; + } + + /** + * Determine if the session and input CSRF tokens match. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + protected function tokensMatch($request) + { + $token = $this->getTokenFromRequest($request); + + return is_string($request->session()->token()) && + is_string($token) && + hash_equals($request->session()->token(), $token); + } + + /** + * Get the CSRF token from the request. + * + * @param \Illuminate\Http\Request $request + * @return string + */ + protected function getTokenFromRequest($request) + { + $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); + + if (! $token && $header = $request->header('X-XSRF-TOKEN')) { + try { + $token = CookieValuePrefix::remove($this->encrypter->decrypt($header, static::serialized())); + } catch (DecryptException $e) { + $token = ''; + } + } + + return $token; + } + + /** + * Determine if the cookie should be added to the response. + * + * @return bool + */ + public function shouldAddXsrfTokenCookie() + { + return $this->addHttpCookie; + } + + /** + * Add the CSRF token to the response cookies. + * + * @param \Illuminate\Http\Request $request + * @param \Symfony\Component\HttpFoundation\Response $response + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function addCookieToResponse($request, $response) + { + $config = config('session'); + + if ($response instanceof Responsable) { + $response = $response->toResponse($request); + } + + $response->headers->setCookie( + new Cookie( + 'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']), + $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null + ) + ); + + return $response; + } + + /** + * Determine if the cookie contents should be serialized. + * + * @return bool + */ + public static function serialized() + { + return EncryptCookies::serialized('XSRF-TOKEN'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Inspiring.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Inspiring.php new file mode 100644 index 0000000..0ca44fd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Inspiring.php @@ -0,0 +1,61 @@ +random(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Mix.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Mix.php new file mode 100644 index 0000000..edd4817 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Mix.php @@ -0,0 +1,74 @@ +get('app.mix_hot_proxy_url'); + + if (! empty($customUrl)) { + return new HtmlString("{$customUrl}{$path}"); + } + + if (Str::startsWith($url, ['http://', 'https://'])) { + return new HtmlString(Str::after($url, ':').$path); + } + + return new HtmlString("//localhost:8080{$path}"); + } + + $manifestPath = public_path($manifestDirectory.'/mix-manifest.json'); + + if (! isset($manifests[$manifestPath])) { + if (! is_file($manifestPath)) { + throw new Exception('The Mix manifest does not exist.'); + } + + $manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true); + } + + $manifest = $manifests[$manifestPath]; + + if (! isset($manifest[$path])) { + $exception = new Exception("Unable to locate Mix file: {$path}."); + + if (! app('config')->get('app.debug')) { + report($exception); + + return $path; + } else { + throw $exception; + } + } + + return new HtmlString(app('config')->get('app.mix_url').$manifestDirectory.$manifest[$path]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php new file mode 100644 index 0000000..202a8be --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php @@ -0,0 +1,184 @@ +files = $files; + $this->basePath = $basePath; + $this->manifestPath = $manifestPath; + $this->vendorPath = $basePath.'/vendor'; + } + + /** + * Get all of the service provider class names for all packages. + * + * @return array + */ + public function providers() + { + return $this->config('providers'); + } + + /** + * Get all of the aliases for all packages. + * + * @return array + */ + public function aliases() + { + return $this->config('aliases'); + } + + /** + * Get all of the values for all packages for the given configuration name. + * + * @param string $key + * @return array + */ + public function config($key) + { + return collect($this->getManifest())->flatMap(function ($configuration) use ($key) { + return (array) ($configuration[$key] ?? []); + })->filter()->all(); + } + + /** + * Get the current package manifest. + * + * @return array + */ + protected function getManifest() + { + if (! is_null($this->manifest)) { + return $this->manifest; + } + + if (! is_file($this->manifestPath)) { + $this->build(); + } + + return $this->manifest = is_file($this->manifestPath) ? + $this->files->getRequire($this->manifestPath) : []; + } + + /** + * Build the manifest and write it to disk. + * + * @return void + */ + public function build() + { + $packages = []; + + if ($this->files->exists($path = $this->vendorPath.'/composer/installed.json')) { + $installed = json_decode($this->files->get($path), true); + + $packages = $installed['packages'] ?? $installed; + } + + $ignoreAll = in_array('*', $ignore = $this->packagesToIgnore()); + + $this->write(collect($packages)->mapWithKeys(function ($package) { + return [$this->format($package['name']) => $package['extra']['laravel'] ?? []]; + })->each(function ($configuration) use (&$ignore) { + $ignore = array_merge($ignore, $configuration['dont-discover'] ?? []); + })->reject(function ($configuration, $package) use ($ignore, $ignoreAll) { + return $ignoreAll || in_array($package, $ignore); + })->filter()->all()); + } + + /** + * Format the given package name. + * + * @param string $package + * @return string + */ + protected function format($package) + { + return str_replace($this->vendorPath.'/', '', $package); + } + + /** + * Get all of the package names that should be ignored. + * + * @return array + */ + protected function packagesToIgnore() + { + if (! is_file($this->basePath.'/composer.json')) { + return []; + } + + return json_decode(file_get_contents( + $this->basePath.'/composer.json' + ), true)['extra']['laravel']['dont-discover'] ?? []; + } + + /** + * Write the given manifest array to disk. + * + * @param array $manifest + * @return void + * + * @throws \Exception + */ + protected function write(array $manifest) + { + if (! is_writable($dirname = dirname($this->manifestPath))) { + throw new Exception("The {$dirname} directory must be present and writable."); + } + + $this->files->replace( + $this->manifestPath, 'app = $app; + $this->files = $files; + $this->manifestPath = $manifestPath; + } + + /** + * Register the application service providers. + * + * @param array $providers + * @return void + */ + public function load(array $providers) + { + $manifest = $this->loadManifest(); + + // First we will load the service manifest, which contains information on all + // service providers registered with the application and which services it + // provides. This is used to know which services are "deferred" loaders. + if ($this->shouldRecompile($manifest, $providers)) { + $manifest = $this->compileManifest($providers); + } + + // Next, we will register events to load the providers for each of the events + // that it has requested. This allows the service provider to defer itself + // while still getting automatically loaded when a certain event occurs. + foreach ($manifest['when'] as $provider => $events) { + $this->registerLoadEvents($provider, $events); + } + + // We will go ahead and register all of the eagerly loaded providers with the + // application so their services can be registered with the application as + // a provided service. Then we will set the deferred service list on it. + foreach ($manifest['eager'] as $provider) { + $this->app->register($provider); + } + + $this->app->addDeferredServices($manifest['deferred']); + } + + /** + * Load the service provider manifest JSON file. + * + * @return array|null + */ + public function loadManifest() + { + // The service manifest is a file containing a JSON representation of every + // service provided by the application and whether its provider is using + // deferred loading or should be eagerly loaded on each request to us. + if ($this->files->exists($this->manifestPath)) { + $manifest = $this->files->getRequire($this->manifestPath); + + if ($manifest) { + return array_merge(['when' => []], $manifest); + } + } + } + + /** + * Determine if the manifest should be compiled. + * + * @param array $manifest + * @param array $providers + * @return bool + */ + public function shouldRecompile($manifest, $providers) + { + return is_null($manifest) || $manifest['providers'] != $providers; + } + + /** + * Register the load events for the given provider. + * + * @param string $provider + * @param array $events + * @return void + */ + protected function registerLoadEvents($provider, array $events) + { + if (count($events) < 1) { + return; + } + + $this->app->make('events')->listen($events, function () use ($provider) { + $this->app->register($provider); + }); + } + + /** + * Compile the application service manifest file. + * + * @param array $providers + * @return array + */ + protected function compileManifest($providers) + { + // The service manifest should contain a list of all of the providers for + // the application so we can compare it on each request to the service + // and determine if the manifest should be recompiled or is current. + $manifest = $this->freshManifest($providers); + + foreach ($providers as $provider) { + $instance = $this->createProvider($provider); + + // When recompiling the service manifest, we will spin through each of the + // providers and check if it's a deferred provider or not. If so we'll + // add it's provided services to the manifest and note the provider. + if ($instance->isDeferred()) { + foreach ($instance->provides() as $service) { + $manifest['deferred'][$service] = $provider; + } + + $manifest['when'][$provider] = $instance->when(); + } + + // If the service providers are not deferred, we will simply add it to an + // array of eagerly loaded providers that will get registered on every + // request to this application instead of "lazy" loading every time. + else { + $manifest['eager'][] = $provider; + } + } + + return $this->writeManifest($manifest); + } + + /** + * Create a fresh service manifest data structure. + * + * @param array $providers + * @return array + */ + protected function freshManifest(array $providers) + { + return ['providers' => $providers, 'eager' => [], 'deferred' => []]; + } + + /** + * Write the service manifest file to disk. + * + * @param array $manifest + * @return array + * + * @throws \Exception + */ + public function writeManifest($manifest) + { + if (! is_writable($dirname = dirname($this->manifestPath))) { + throw new Exception("The {$dirname} directory must be present and writable."); + } + + $this->files->replace( + $this->manifestPath, ' []], $manifest); + } + + /** + * Create a new provider instance. + * + * @param string $provider + * @return \Illuminate\Support\ServiceProvider + */ + public function createProvider($provider) + { + return new $provider($this->app); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php new file mode 100755 index 0000000..e003ab1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php @@ -0,0 +1,1126 @@ + 'command.cache.clear', + 'CacheForget' => 'command.cache.forget', + 'ClearCompiled' => 'command.clear-compiled', + 'ClearResets' => 'command.auth.resets.clear', + 'ConfigCache' => 'command.config.cache', + 'ConfigClear' => 'command.config.clear', + 'Db' => DbCommand::class, + 'DbPrune' => 'command.db.prune', + 'DbWipe' => 'command.db.wipe', + 'Down' => 'command.down', + 'Environment' => 'command.environment', + 'EventCache' => 'command.event.cache', + 'EventClear' => 'command.event.clear', + 'EventList' => 'command.event.list', + 'KeyGenerate' => 'command.key.generate', + 'Optimize' => 'command.optimize', + 'OptimizeClear' => 'command.optimize.clear', + 'PackageDiscover' => 'command.package.discover', + 'QueueClear' => 'command.queue.clear', + 'QueueFailed' => 'command.queue.failed', + 'QueueFlush' => 'command.queue.flush', + 'QueueForget' => 'command.queue.forget', + 'QueueListen' => 'command.queue.listen', + 'QueueMonitor' => 'command.queue.monitor', + 'QueuePruneBatches' => 'command.queue.prune-batches', + 'QueuePruneFailedJobs' => 'command.queue.prune-failed-jobs', + 'QueueRestart' => 'command.queue.restart', + 'QueueRetry' => 'command.queue.retry', + 'QueueRetryBatch' => 'command.queue.retry-batch', + 'QueueWork' => 'command.queue.work', + 'RouteCache' => 'command.route.cache', + 'RouteClear' => 'command.route.clear', + 'RouteList' => 'command.route.list', + 'SchemaDump' => 'command.schema.dump', + 'Seed' => 'command.seed', + 'ScheduleFinish' => ScheduleFinishCommand::class, + 'ScheduleList' => ScheduleListCommand::class, + 'ScheduleRun' => ScheduleRunCommand::class, + 'ScheduleClearCache' => ScheduleClearCacheCommand::class, + 'ScheduleTest' => ScheduleTestCommand::class, + 'ScheduleWork' => ScheduleWorkCommand::class, + 'StorageLink' => 'command.storage.link', + 'Up' => 'command.up', + 'ViewCache' => 'command.view.cache', + 'ViewClear' => 'command.view.clear', + ]; + + /** + * The commands to be registered. + * + * @var array + */ + protected $devCommands = [ + 'CacheTable' => 'command.cache.table', + 'CastMake' => 'command.cast.make', + 'ChannelMake' => 'command.channel.make', + 'ComponentMake' => 'command.component.make', + 'ConsoleMake' => 'command.console.make', + 'ControllerMake' => 'command.controller.make', + 'EventGenerate' => 'command.event.generate', + 'EventMake' => 'command.event.make', + 'ExceptionMake' => 'command.exception.make', + 'FactoryMake' => 'command.factory.make', + 'JobMake' => 'command.job.make', + 'ListenerMake' => 'command.listener.make', + 'MailMake' => 'command.mail.make', + 'MiddlewareMake' => 'command.middleware.make', + 'ModelMake' => 'command.model.make', + 'NotificationMake' => 'command.notification.make', + 'NotificationTable' => 'command.notification.table', + 'ObserverMake' => 'command.observer.make', + 'PolicyMake' => 'command.policy.make', + 'ProviderMake' => 'command.provider.make', + 'QueueFailedTable' => 'command.queue.failed-table', + 'QueueTable' => 'command.queue.table', + 'QueueBatchesTable' => 'command.queue.batches-table', + 'RequestMake' => 'command.request.make', + 'ResourceMake' => 'command.resource.make', + 'RuleMake' => 'command.rule.make', + 'SeederMake' => 'command.seeder.make', + 'SessionTable' => 'command.session.table', + 'Serve' => 'command.serve', + 'StubPublish' => 'command.stub.publish', + 'TestMake' => 'command.test.make', + 'VendorPublish' => 'command.vendor.publish', + ]; + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $this->registerCommands(array_merge( + $this->commands, $this->devCommands + )); + } + + /** + * Register the given commands. + * + * @param array $commands + * @return void + */ + protected function registerCommands(array $commands) + { + foreach (array_keys($commands) as $command) { + $this->{"register{$command}Command"}(); + } + + $this->commands(array_values($commands)); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerCacheClearCommand() + { + $this->app->singleton('command.cache.clear', function ($app) { + return new CacheClearCommand($app['cache'], $app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerCacheForgetCommand() + { + $this->app->singleton('command.cache.forget', function ($app) { + return new CacheForgetCommand($app['cache']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerCacheTableCommand() + { + $this->app->singleton('command.cache.table', function ($app) { + return new CacheTableCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerCastMakeCommand() + { + $this->app->singleton('command.cast.make', function ($app) { + return new CastMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerChannelMakeCommand() + { + $this->app->singleton('command.channel.make', function ($app) { + return new ChannelMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerClearCompiledCommand() + { + $this->app->singleton('command.clear-compiled', function () { + return new ClearCompiledCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerClearResetsCommand() + { + $this->app->singleton('command.auth.resets.clear', function () { + return new ClearResetsCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerComponentMakeCommand() + { + $this->app->singleton('command.component.make', function ($app) { + return new ComponentMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerConfigCacheCommand() + { + $this->app->singleton('command.config.cache', function ($app) { + return new ConfigCacheCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerConfigClearCommand() + { + $this->app->singleton('command.config.clear', function ($app) { + return new ConfigClearCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerConsoleMakeCommand() + { + $this->app->singleton('command.console.make', function ($app) { + return new ConsoleMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerControllerMakeCommand() + { + $this->app->singleton('command.controller.make', function ($app) { + return new ControllerMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerDbCommand() + { + $this->app->singleton(DbCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerDbPruneCommand() + { + $this->app->singleton('command.db.prune', function ($app) { + return new PruneCommand($app['events']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerDbWipeCommand() + { + $this->app->singleton('command.db.wipe', function () { + return new WipeCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerEventGenerateCommand() + { + $this->app->singleton('command.event.generate', function () { + return new EventGenerateCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerEventMakeCommand() + { + $this->app->singleton('command.event.make', function ($app) { + return new EventMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerExceptionMakeCommand() + { + $this->app->singleton('command.exception.make', function ($app) { + return new ExceptionMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerFactoryMakeCommand() + { + $this->app->singleton('command.factory.make', function ($app) { + return new FactoryMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerDownCommand() + { + $this->app->singleton('command.down', function () { + return new DownCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerEnvironmentCommand() + { + $this->app->singleton('command.environment', function () { + return new EnvironmentCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerEventCacheCommand() + { + $this->app->singleton('command.event.cache', function () { + return new EventCacheCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerEventClearCommand() + { + $this->app->singleton('command.event.clear', function ($app) { + return new EventClearCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerEventListCommand() + { + $this->app->singleton('command.event.list', function () { + return new EventListCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerJobMakeCommand() + { + $this->app->singleton('command.job.make', function ($app) { + return new JobMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerKeyGenerateCommand() + { + $this->app->singleton('command.key.generate', function () { + return new KeyGenerateCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerListenerMakeCommand() + { + $this->app->singleton('command.listener.make', function ($app) { + return new ListenerMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMailMakeCommand() + { + $this->app->singleton('command.mail.make', function ($app) { + return new MailMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerMiddlewareMakeCommand() + { + $this->app->singleton('command.middleware.make', function ($app) { + return new MiddlewareMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerModelMakeCommand() + { + $this->app->singleton('command.model.make', function ($app) { + return new ModelMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerNotificationMakeCommand() + { + $this->app->singleton('command.notification.make', function ($app) { + return new NotificationMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerNotificationTableCommand() + { + $this->app->singleton('command.notification.table', function ($app) { + return new NotificationTableCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerOptimizeCommand() + { + $this->app->singleton('command.optimize', function () { + return new OptimizeCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerObserverMakeCommand() + { + $this->app->singleton('command.observer.make', function ($app) { + return new ObserverMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerOptimizeClearCommand() + { + $this->app->singleton('command.optimize.clear', function () { + return new OptimizeClearCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerPackageDiscoverCommand() + { + $this->app->singleton('command.package.discover', function () { + return new PackageDiscoverCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerPolicyMakeCommand() + { + $this->app->singleton('command.policy.make', function ($app) { + return new PolicyMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerProviderMakeCommand() + { + $this->app->singleton('command.provider.make', function ($app) { + return new ProviderMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueFailedCommand() + { + $this->app->singleton('command.queue.failed', function () { + return new ListFailedQueueCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueForgetCommand() + { + $this->app->singleton('command.queue.forget', function () { + return new ForgetFailedQueueCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueFlushCommand() + { + $this->app->singleton('command.queue.flush', function () { + return new FlushFailedQueueCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueListenCommand() + { + $this->app->singleton('command.queue.listen', function ($app) { + return new QueueListenCommand($app['queue.listener']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueMonitorCommand() + { + $this->app->singleton('command.queue.monitor', function ($app) { + return new QueueMonitorCommand($app['queue'], $app['events']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueuePruneBatchesCommand() + { + $this->app->singleton('command.queue.prune-batches', function () { + return new PruneBatchesQueueCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueuePruneFailedJobsCommand() + { + $this->app->singleton('command.queue.prune-failed-jobs', function () { + return new PruneFailedJobsCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueRestartCommand() + { + $this->app->singleton('command.queue.restart', function ($app) { + return new QueueRestartCommand($app['cache.store']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueRetryCommand() + { + $this->app->singleton('command.queue.retry', function () { + return new QueueRetryCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueRetryBatchCommand() + { + $this->app->singleton('command.queue.retry-batch', function () { + return new QueueRetryBatchCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueWorkCommand() + { + $this->app->singleton('command.queue.work', function ($app) { + return new QueueWorkCommand($app['queue.worker'], $app['cache.store']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueClearCommand() + { + $this->app->singleton('command.queue.clear', function () { + return new QueueClearCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueFailedTableCommand() + { + $this->app->singleton('command.queue.failed-table', function ($app) { + return new FailedTableCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueTableCommand() + { + $this->app->singleton('command.queue.table', function ($app) { + return new TableCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerQueueBatchesTableCommand() + { + $this->app->singleton('command.queue.batches-table', function ($app) { + return new BatchesTableCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerRequestMakeCommand() + { + $this->app->singleton('command.request.make', function ($app) { + return new RequestMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerResourceMakeCommand() + { + $this->app->singleton('command.resource.make', function ($app) { + return new ResourceMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerRuleMakeCommand() + { + $this->app->singleton('command.rule.make', function ($app) { + return new RuleMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerSeederMakeCommand() + { + $this->app->singleton('command.seeder.make', function ($app) { + return new SeederMakeCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerSessionTableCommand() + { + $this->app->singleton('command.session.table', function ($app) { + return new SessionTableCommand($app['files'], $app['composer']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerStorageLinkCommand() + { + $this->app->singleton('command.storage.link', function () { + return new StorageLinkCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerRouteCacheCommand() + { + $this->app->singleton('command.route.cache', function ($app) { + return new RouteCacheCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerRouteClearCommand() + { + $this->app->singleton('command.route.clear', function ($app) { + return new RouteClearCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerRouteListCommand() + { + $this->app->singleton('command.route.list', function ($app) { + return new RouteListCommand($app['router']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerSchemaDumpCommand() + { + $this->app->singleton('command.schema.dump', function () { + return new DumpCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerSeedCommand() + { + $this->app->singleton('command.seed', function ($app) { + return new SeedCommand($app['db']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerScheduleClearCacheCommand() + { + $this->app->singleton(ScheduleClearCacheCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerScheduleFinishCommand() + { + $this->app->singleton(ScheduleFinishCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerScheduleListCommand() + { + $this->app->singleton(ScheduleListCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerScheduleRunCommand() + { + $this->app->singleton(ScheduleRunCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerScheduleTestCommand() + { + $this->app->singleton(ScheduleTestCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerScheduleWorkCommand() + { + $this->app->singleton(ScheduleWorkCommand::class); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerServeCommand() + { + $this->app->singleton('command.serve', function () { + return new ServeCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerStubPublishCommand() + { + $this->app->singleton('command.stub.publish', function () { + return new StubPublishCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerTestMakeCommand() + { + $this->app->singleton('command.test.make', function ($app) { + return new TestMakeCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerUpCommand() + { + $this->app->singleton('command.up', function () { + return new UpCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerVendorPublishCommand() + { + $this->app->singleton('command.vendor.publish', function ($app) { + return new VendorPublishCommand($app['files']); + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerViewCacheCommand() + { + $this->app->singleton('command.view.cache', function () { + return new ViewCacheCommand; + }); + } + + /** + * Register the command. + * + * @return void + */ + protected function registerViewClearCommand() + { + $this->app->singleton('command.view.clear', function ($app) { + return new ViewClearCommand($app['files']); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return array_merge(array_values($this->commands), array_values($this->devCommands)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ComposerServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ComposerServiceProvider.php new file mode 100755 index 0000000..8fe428b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ComposerServiceProvider.php @@ -0,0 +1,32 @@ +app->singleton('composer', function ($app) { + return new Composer($app['files'], $app->basePath()); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['composer']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ConsoleSupportServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ConsoleSupportServiceProvider.php new file mode 100644 index 0000000..f6131ca --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ConsoleSupportServiceProvider.php @@ -0,0 +1,21 @@ +app->afterResolving(ValidatesWhenResolved::class, function ($resolved) { + $resolved->validateResolved(); + }); + + $this->app->resolving(FormRequest::class, function ($request, $app) { + $request = FormRequest::createFrom($app['request'], $request); + + $request->setContainer($app)->setRedirector($app->make(Redirector::class)); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FoundationServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FoundationServiceProvider.php new file mode 100644 index 0000000..bb69c88 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FoundationServiceProvider.php @@ -0,0 +1,116 @@ +app->runningInConsole()) { + $this->publishes([ + __DIR__.'/../Exceptions/views' => $this->app->resourcePath('views/errors/'), + ], 'laravel-errors'); + } + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + parent::register(); + + $this->registerRequestValidation(); + $this->registerRequestSignatureValidation(); + $this->registerExceptionTracking(); + } + + /** + * Register the "validate" macro on the request. + * + * @return void + * + * @throws \Illuminate\Validation\ValidationException + */ + public function registerRequestValidation() + { + Request::macro('validate', function (array $rules, ...$params) { + return validator()->validate($this->all(), $rules, ...$params); + }); + + Request::macro('validateWithBag', function (string $errorBag, array $rules, ...$params) { + try { + return $this->validate($rules, ...$params); + } catch (ValidationException $e) { + $e->errorBag = $errorBag; + + throw $e; + } + }); + } + + /** + * Register the "hasValidSignature" macro on the request. + * + * @return void + */ + public function registerRequestSignatureValidation() + { + Request::macro('hasValidSignature', function ($absolute = true) { + return URL::hasValidSignature($this, $absolute); + }); + + Request::macro('hasValidRelativeSignature', function () { + return URL::hasValidSignature($this, $absolute = false); + }); + } + + /** + * Register an event listener to track logged exceptions. + * + * @return void + */ + protected function registerExceptionTracking() + { + if (! $this->app->runningUnitTests()) { + return; + } + + $this->app->instance( + LoggedExceptionCollection::class, + new LoggedExceptionCollection + ); + + $this->app->make('events')->listen(MessageLogged::class, function ($event) { + if (isset($event->context['exception'])) { + $this->app->make(LoggedExceptionCollection::class) + ->push($event->context['exception']); + } + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/AuthServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/AuthServiceProvider.php new file mode 100644 index 0000000..7ccd2d4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/AuthServiceProvider.php @@ -0,0 +1,38 @@ +policies() as $key => $value) { + Gate::policy($key, $value); + } + } + + /** + * Get the policies defined on the provider. + * + * @return array + */ + public function policies() + { + return $this->policies; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php new file mode 100644 index 0000000..70ea308 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php @@ -0,0 +1,148 @@ +booting(function () { + $events = $this->getEvents(); + + foreach ($events as $event => $listeners) { + foreach (array_unique($listeners) as $listener) { + Event::listen($event, $listener); + } + } + + foreach ($this->subscribe as $subscriber) { + Event::subscribe($subscriber); + } + }); + } + + /** + * Boot any application services. + * + * @return void + */ + public function boot() + { + // + } + + /** + * Get the events and handlers. + * + * @return array + */ + public function listens() + { + return $this->listen; + } + + /** + * Get the discovered events and listeners for the application. + * + * @return array + */ + public function getEvents() + { + if ($this->app->eventsAreCached()) { + $cache = require $this->app->getCachedEventsPath(); + + return $cache[get_class($this)] ?? []; + } else { + return array_merge_recursive( + $this->discoveredEvents(), + $this->listens() + ); + } + } + + /** + * Get the discovered events for the application. + * + * @return array + */ + protected function discoveredEvents() + { + return $this->shouldDiscoverEvents() + ? $this->discoverEvents() + : []; + } + + /** + * Determine if events and listeners should be automatically discovered. + * + * @return bool + */ + public function shouldDiscoverEvents() + { + return false; + } + + /** + * Discover the events and listeners for the application. + * + * @return array + */ + public function discoverEvents() + { + return collect($this->discoverEventsWithin()) + ->reject(function ($directory) { + return ! is_dir($directory); + }) + ->reduce(function ($discovered, $directory) { + return array_merge_recursive( + $discovered, + DiscoverEvents::within($directory, $this->eventDiscoveryBasePath()) + ); + }, []); + } + + /** + * Get the listener directories that should be used to discover events. + * + * @return array + */ + protected function discoverEventsWithin() + { + return [ + $this->app->path('Listeners'), + ]; + } + + /** + * Get the base path to be used during event discovery. + * + * @return string + */ + protected function eventDiscoveryBasePath() + { + return base_path(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php new file mode 100644 index 0000000..c8679e5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php @@ -0,0 +1,139 @@ +booted(function () { + $this->setRootControllerNamespace(); + + if ($this->routesAreCached()) { + $this->loadCachedRoutes(); + } else { + $this->loadRoutes(); + + $this->app->booted(function () { + $this->app['router']->getRoutes()->refreshNameLookups(); + $this->app['router']->getRoutes()->refreshActionLookups(); + }); + } + }); + } + + /** + * Bootstrap any application services. + * + * @return void + */ + public function boot() + { + // + } + + /** + * Register the callback that will be used to load the application's routes. + * + * @param \Closure $routesCallback + * @return $this + */ + protected function routes(Closure $routesCallback) + { + $this->loadRoutesUsing = $routesCallback; + + return $this; + } + + /** + * Set the root controller namespace for the application. + * + * @return void + */ + protected function setRootControllerNamespace() + { + if (! is_null($this->namespace)) { + $this->app[UrlGenerator::class]->setRootControllerNamespace($this->namespace); + } + } + + /** + * Determine if the application routes are cached. + * + * @return bool + */ + protected function routesAreCached() + { + return $this->app->routesAreCached(); + } + + /** + * Load the cached routes for the application. + * + * @return void + */ + protected function loadCachedRoutes() + { + $this->app->booted(function () { + require $this->app->getCachedRoutesPath(); + }); + } + + /** + * Load the application routes. + * + * @return void + */ + protected function loadRoutes() + { + if (! is_null($this->loadRoutesUsing)) { + $this->app->call($this->loadRoutesUsing); + } elseif (method_exists($this, 'map')) { + $this->app->call([$this, 'map']); + } + } + + /** + * Pass dynamic methods onto the router instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->forwardCallTo( + $this->app->make(Router::class), $method, $parameters + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php new file mode 100644 index 0000000..9e8c0f5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php @@ -0,0 +1,151 @@ +be($user, $guard); + } + + /** + * Set the currently logged in user for the application. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string|null $guard + * @return $this + */ + public function be(UserContract $user, $guard = null) + { + if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) { + $user->wasRecentlyCreated = false; + } + + $this->app['auth']->guard($guard)->setUser($user); + + $this->app['auth']->shouldUse($guard); + + return $this; + } + + /** + * Assert that the user is authenticated. + * + * @param string|null $guard + * @return $this + */ + public function assertAuthenticated($guard = null) + { + $this->assertTrue($this->isAuthenticated($guard), 'The user is not authenticated'); + + return $this; + } + + /** + * Assert that the user is not authenticated. + * + * @param string|null $guard + * @return $this + */ + public function assertGuest($guard = null) + { + $this->assertFalse($this->isAuthenticated($guard), 'The user is authenticated'); + + return $this; + } + + /** + * Return true if the user is authenticated, false otherwise. + * + * @param string|null $guard + * @return bool + */ + protected function isAuthenticated($guard = null) + { + return $this->app->make('auth')->guard($guard)->check(); + } + + /** + * Assert that the user is authenticated as the given user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string|null $guard + * @return $this + */ + public function assertAuthenticatedAs($user, $guard = null) + { + $expected = $this->app->make('auth')->guard($guard)->user(); + + $this->assertNotNull($expected, 'The current user is not authenticated.'); + + $this->assertInstanceOf( + get_class($expected), $user, + 'The currently authenticated user is not who was expected' + ); + + $this->assertSame( + $expected->getAuthIdentifier(), $user->getAuthIdentifier(), + 'The currently authenticated user is not who was expected' + ); + + return $this; + } + + /** + * Assert that the given credentials are valid. + * + * @param array $credentials + * @param string|null $guard + * @return $this + */ + public function assertCredentials(array $credentials, $guard = null) + { + $this->assertTrue( + $this->hasCredentials($credentials, $guard), 'The given credentials are invalid.' + ); + + return $this; + } + + /** + * Assert that the given credentials are invalid. + * + * @param array $credentials + * @param string|null $guard + * @return $this + */ + public function assertInvalidCredentials(array $credentials, $guard = null) + { + $this->assertFalse( + $this->hasCredentials($credentials, $guard), 'The given credentials are valid.' + ); + + return $this; + } + + /** + * Return true if the credentials are valid, false otherwise. + * + * @param array $credentials + * @param string|null $guard + * @return bool + */ + protected function hasCredentials(array $credentials, $guard = null) + { + $provider = $this->app->make('auth')->guard($guard)->getProvider(); + + $user = $provider->retrieveByCredentials($credentials); + + return $user && $provider->validateCredentials($user, $credentials); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php new file mode 100644 index 0000000..38409d3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php @@ -0,0 +1,82 @@ +mockConsoleOutput) { + return $this->app[Kernel::class]->call($command, $parameters); + } + + return new PendingCommand($this, $this->app, $command, $parameters); + } + + /** + * Disable mocking the console output. + * + * @return $this + */ + protected function withoutMockingConsoleOutput() + { + $this->mockConsoleOutput = false; + + $this->app->offsetUnset(OutputStyle::class); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php new file mode 100644 index 0000000..6949f6f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php @@ -0,0 +1,124 @@ +instance($abstract, $instance); + } + + /** + * Register an instance of an object in the container. + * + * @param string $abstract + * @param object $instance + * @return object + */ + protected function instance($abstract, $instance) + { + $this->app->instance($abstract, $instance); + + return $instance; + } + + /** + * Mock an instance of an object in the container. + * + * @param string $abstract + * @param \Closure|null $mock + * @return \Mockery\MockInterface + */ + protected function mock($abstract, Closure $mock = null) + { + return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))); + } + + /** + * Mock a partial instance of an object in the container. + * + * @param string $abstract + * @param \Closure|null $mock + * @return \Mockery\MockInterface + */ + protected function partialMock($abstract, Closure $mock = null) + { + return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))->makePartial()); + } + + /** + * Spy an instance of an object in the container. + * + * @param string $abstract + * @param \Closure|null $mock + * @return \Mockery\MockInterface + */ + protected function spy($abstract, Closure $mock = null) + { + return $this->instance($abstract, Mockery::spy(...array_filter(func_get_args()))); + } + + /** + * Instruct the container to forget a previously mocked / spied instance of an object. + * + * @param string $abstract + * @return $this + */ + protected function forgetMock($abstract) + { + $this->app->forgetInstance($abstract); + + return $this; + } + + /** + * Register an empty handler for Laravel Mix in the container. + * + * @return $this + */ + protected function withoutMix() + { + if ($this->originalMix == null) { + $this->originalMix = app(Mix::class); + } + + $this->swap(Mix::class, function () { + return ''; + }); + + return $this; + } + + /** + * Register an empty handler for Laravel Mix in the container. + * + * @return $this + */ + protected function withMix() + { + if ($this->originalMix) { + $this->app->instance(Mix::class, $this->originalMix); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php new file mode 100644 index 0000000..8ccd7e2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php @@ -0,0 +1,245 @@ +assertThat( + $this->getTable($table), new HasInDatabase($this->getConnection($connection), $data) + ); + + return $this; + } + + /** + * Assert that a given where condition does not exist in the database. + * + * @param \Illuminate\Database\Eloquent\Model|string $table + * @param array $data + * @param string|null $connection + * @return $this + */ + protected function assertDatabaseMissing($table, array $data, $connection = null) + { + $constraint = new ReverseConstraint( + new HasInDatabase($this->getConnection($connection), $data) + ); + + $this->assertThat($this->getTable($table), $constraint); + + return $this; + } + + /** + * Assert the count of table entries. + * + * @param \Illuminate\Database\Eloquent\Model|string $table + * @param int $count + * @param string|null $connection + * @return $this + */ + protected function assertDatabaseCount($table, int $count, $connection = null) + { + $this->assertThat( + $this->getTable($table), new CountInDatabase($this->getConnection($connection), $count) + ); + + return $this; + } + + /** + * Assert the given record has been deleted. + * + * @param \Illuminate\Database\Eloquent\Model|string $table + * @param array $data + * @param string|null $connection + * @return $this + */ + protected function assertDeleted($table, array $data = [], $connection = null) + { + if ($table instanceof Model) { + return $this->assertDatabaseMissing($table->getTable(), [$table->getKeyName() => $table->getKey()], $table->getConnectionName()); + } + + $this->assertDatabaseMissing($this->getTable($table), $data, $connection); + + return $this; + } + + /** + * Assert the given record has been "soft deleted". + * + * @param \Illuminate\Database\Eloquent\Model|string $table + * @param array $data + * @param string|null $connection + * @param string|null $deletedAtColumn + * @return $this + */ + protected function assertSoftDeleted($table, array $data = [], $connection = null, $deletedAtColumn = 'deleted_at') + { + if ($this->isSoftDeletableModel($table)) { + return $this->assertSoftDeleted( + $table->getTable(), + array_merge($data, [$table->getKeyName() => $table->getKey()]), + $table->getConnectionName(), + $table->getDeletedAtColumn() + ); + } + + $this->assertThat( + $this->getTable($table), new SoftDeletedInDatabase($this->getConnection($connection), $data, $deletedAtColumn) + ); + + return $this; + } + + /** + * Assert the given record has not been "soft deleted". + * + * @param \Illuminate\Database\Eloquent\Model|string $table + * @param array $data + * @param string|null $connection + * @param string|null $deletedAtColumn + * @return $this + */ + protected function assertNotSoftDeleted($table, array $data = [], $connection = null, $deletedAtColumn = 'deleted_at') + { + if ($this->isSoftDeletableModel($table)) { + return $this->assertNotSoftDeleted( + $table->getTable(), + array_merge($data, [$table->getKeyName() => $table->getKey()]), + $table->getConnectionName(), + $table->getDeletedAtColumn() + ); + } + + $this->assertThat( + $this->getTable($table), new NotSoftDeletedInDatabase($this->getConnection($connection), $data, $deletedAtColumn) + ); + + return $this; + } + + /** + * Assert the given model exists in the database. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return $this + */ + protected function assertModelExists($model) + { + return $this->assertDatabaseHas( + $model->getTable(), + [$model->getKeyName() => $model->getKey()], + $model->getConnectionName() + ); + } + + /** + * Assert the given model does not exist in the database. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return $this + */ + protected function assertModelMissing($model) + { + return $this->assertDatabaseMissing( + $model->getTable(), + [$model->getKeyName() => $model->getKey()], + $model->getConnectionName() + ); + } + + /** + * Determine if the argument is a soft deletable model. + * + * @param mixed $model + * @return bool + */ + protected function isSoftDeletableModel($model) + { + return $model instanceof Model + && in_array(SoftDeletes::class, class_uses_recursive($model)); + } + + /** + * Cast a JSON string to a database compatible type. + * + * @param array|string $value + * @return \Illuminate\Database\Query\Expression + */ + public function castAsJson($value) + { + if ($value instanceof Jsonable) { + $value = $value->toJson(); + } elseif (is_array($value) || is_object($value)) { + $value = json_encode($value); + } + + $value = DB::connection()->getPdo()->quote($value); + + return DB::raw("CAST($value AS JSON)"); + } + + /** + * Get the database connection. + * + * @param string|null $connection + * @return \Illuminate\Database\Connection + */ + protected function getConnection($connection = null) + { + $database = $this->app->make('db'); + + $connection = $connection ?: $database->getDefaultConnection(); + + return $database->connection($connection); + } + + /** + * Get the table name from the given model or string. + * + * @param \Illuminate\Database\Eloquent\Model|string $table + * @return string + */ + protected function getTable($table) + { + return is_subclass_of($table, Model::class) ? (new $table)->getTable() : $table; + } + + /** + * Seed a given database connection. + * + * @param array|string $class + * @return $this + */ + public function seed($class = 'Database\\Seeders\\DatabaseSeeder') + { + foreach (Arr::wrap($class) as $class) { + $this->artisan('db:seed', ['--class' => $class, '--no-interaction' => true]); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDeprecationHandling.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDeprecationHandling.php new file mode 100644 index 0000000..7a914f7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDeprecationHandling.php @@ -0,0 +1,49 @@ +originalDeprecationHandler) { + set_error_handler(tap($this->originalDeprecationHandler, function () { + $this->originalDeprecationHandler = null; + })); + } + + return $this; + } + + /** + * Disable deprecation handling for the test. + * + * @return $this + */ + protected function withoutDeprecationHandling() + { + if ($this->originalDeprecationHandler == null) { + $this->originalDeprecationHandler = set_error_handler(function ($level, $message, $file = '', $line = 0) { + if (in_array($level, [E_DEPRECATED, E_USER_DEPRECATED]) || (error_reporting() & $level)) { + throw new ErrorException($message, 0, $level, $file, $line); + } + }); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php new file mode 100644 index 0000000..5ce5686 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php @@ -0,0 +1,150 @@ +originalExceptionHandler) { + $this->app->instance(ExceptionHandler::class, $this->originalExceptionHandler); + } + + return $this; + } + + /** + * Only handle the given exceptions via the exception handler. + * + * @param array $exceptions + * @return $this + */ + protected function handleExceptions(array $exceptions) + { + return $this->withoutExceptionHandling($exceptions); + } + + /** + * Only handle validation exceptions via the exception handler. + * + * @return $this + */ + protected function handleValidationExceptions() + { + return $this->handleExceptions([ValidationException::class]); + } + + /** + * Disable exception handling for the test. + * + * @param array $except + * @return $this + */ + protected function withoutExceptionHandling(array $except = []) + { + if ($this->originalExceptionHandler == null) { + $this->originalExceptionHandler = app(ExceptionHandler::class); + } + + $this->app->instance(ExceptionHandler::class, new class($this->originalExceptionHandler, $except) implements ExceptionHandler + { + protected $except; + protected $originalHandler; + + /** + * Create a new class instance. + * + * @param \Illuminate\Contracts\Debug\ExceptionHandler $originalHandler + * @param array $except + * @return void + */ + public function __construct($originalHandler, $except = []) + { + $this->except = $except; + $this->originalHandler = $originalHandler; + } + + /** + * Report or log an exception. + * + * @param \Throwable $e + * @return void + * + * @throws \Exception + */ + public function report(Throwable $e) + { + // + } + + /** + * Determine if the exception should be reported. + * + * @param \Throwable $e + * @return bool + */ + public function shouldReport(Throwable $e) + { + return false; + } + + /** + * Render an exception into an HTTP response. + * + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return \Symfony\Component\HttpFoundation\Response + * + * @throws \Throwable + */ + public function render($request, Throwable $e) + { + foreach ($this->except as $class) { + if ($e instanceof $class) { + return $this->originalHandler->render($request, $e); + } + } + + if ($e instanceof NotFoundHttpException) { + throw new NotFoundHttpException( + "{$request->method()} {$request->url()}", $e, $e->getCode() + ); + } + + throw $e; + } + + /** + * Render an exception to the console. + * + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @param \Throwable $e + * @return void + */ + public function renderForConsole($output, Throwable $e) + { + (new ConsoleApplication)->renderThrowable($e, $output); + } + }); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithRedis.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithRedis.php new file mode 100644 index 0000000..5c8d904 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithRedis.php @@ -0,0 +1,113 @@ +markTestSkipped('The redis extension is not installed. Please install the extension to enable '.__CLASS__); + } + + if (static::$connectionFailedOnceWithDefaultsSkip) { + $this->markTestSkipped('Trying default host/port failed, please set environment variable REDIS_HOST & REDIS_PORT to enable '.__CLASS__); + } + + $app = $this->app ?? new Application; + $host = Env::get('REDIS_HOST', '127.0.0.1'); + $port = Env::get('REDIS_PORT', 6379); + + foreach ($this->redisDriverProvider() as $driver) { + $this->redis[$driver[0]] = new RedisManager($app, $driver[0], [ + 'cluster' => false, + 'options' => [ + 'prefix' => 'test_', + ], + 'default' => [ + 'host' => $host, + 'port' => $port, + 'database' => 5, + 'timeout' => 0.5, + 'name' => 'default', + ], + ]); + } + + try { + $this->redis['phpredis']->connection()->flushdb(); + } catch (Exception $e) { + if ($host === '127.0.0.1' && $port === 6379 && Env::get('REDIS_HOST') === null) { + static::$connectionFailedOnceWithDefaultsSkip = true; + + $this->markTestSkipped('Trying default host/port failed, please set environment variable REDIS_HOST & REDIS_PORT to enable '.__CLASS__); + } + } + } + + /** + * Teardown redis connection. + * + * @return void + */ + public function tearDownRedis() + { + $this->redis['phpredis']->connection()->flushdb(); + + foreach ($this->redisDriverProvider() as $driver) { + $this->redis[$driver[0]]->connection()->disconnect(); + } + } + + /** + * Get redis driver provider. + * + * @return array + */ + public function redisDriverProvider() + { + return [ + ['predis'], + ['phpredis'], + ]; + } + + /** + * Run test if redis is available. + * + * @param callable $callback + * @return void + */ + public function ifRedisAvailable($callback) + { + $this->setUpRedis(); + + $callback(); + + $this->tearDownRedis(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithSession.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithSession.php new file mode 100644 index 0000000..9d72e7c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithSession.php @@ -0,0 +1,64 @@ +session($data); + + return $this; + } + + /** + * Set the session to the given array. + * + * @param array $data + * @return $this + */ + public function session(array $data) + { + $this->startSession(); + + foreach ($data as $key => $value) { + $this->app['session']->put($key, $value); + } + + return $this; + } + + /** + * Start the session for the application. + * + * @return $this + */ + protected function startSession() + { + if (! $this->app['session']->isStarted()) { + $this->app['session']->start(); + } + + return $this; + } + + /** + * Flush all of the current session data. + * + * @return $this + */ + public function flushSession() + { + $this->startSession(); + + $this->app['session']->flush(); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php new file mode 100644 index 0000000..184a244 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php @@ -0,0 +1,49 @@ +getPaths())) { + ViewFacade::addLocation(sys_get_temp_dir()); + } + + $tempFileInfo = pathinfo(tempnam($tempDirectory, 'laravel-blade')); + + $tempFile = $tempFileInfo['dirname'].'/'.$tempFileInfo['filename'].'.blade.php'; + + file_put_contents($tempFile, $template); + + return new TestView(view($tempFileInfo['filename'], $data)); + } + + /** + * Render the given view component. + * + * @param string $componentClass + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @return \Illuminate\Testing\TestComponent + */ + protected function component(string $componentClass, array $data = []) + { + $component = $this->app->make($componentClass, $data); + + $view = value($component->resolveView(), $data); + + $view = $view instanceof View + ? $view->with($component->data()) + : view($view, $component->data()); + + return new TestComponent($component, $view); + } + + /** + * Populate the shared view error bag with the given errors. + * + * @param array $errors + * @param string $key + * @return $this + */ + protected function withViewErrors(array $errors, $key = 'default') + { + ViewFacade::share('errors', (new ViewErrorBag)->put($key, new MessageBag($errors))); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php new file mode 100644 index 0000000..36e6734 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php @@ -0,0 +1,653 @@ +defaultHeaders = array_merge($this->defaultHeaders, $headers); + + return $this; + } + + /** + * Add a header to be sent with the request. + * + * @param string $name + * @param string $value + * @return $this + */ + public function withHeader(string $name, string $value) + { + $this->defaultHeaders[$name] = $value; + + return $this; + } + + /** + * Add an authorization token for the request. + * + * @param string $token + * @param string $type + * @return $this + */ + public function withToken(string $token, string $type = 'Bearer') + { + return $this->withHeader('Authorization', $type.' '.$token); + } + + /** + * Flush all the configured headers. + * + * @return $this + */ + public function flushHeaders() + { + $this->defaultHeaders = []; + + return $this; + } + + /** + * Define a set of server variables to be sent with the requests. + * + * @param array $server + * @return $this + */ + public function withServerVariables(array $server) + { + $this->serverVariables = $server; + + return $this; + } + + /** + * Disable middleware for the test. + * + * @param string|array|null $middleware + * @return $this + */ + public function withoutMiddleware($middleware = null) + { + if (is_null($middleware)) { + $this->app->instance('middleware.disable', true); + + return $this; + } + + foreach ((array) $middleware as $abstract) { + $this->app->instance($abstract, new class + { + public function handle($request, $next) + { + return $next($request); + } + }); + } + + return $this; + } + + /** + * Enable the given middleware for the test. + * + * @param string|array|null $middleware + * @return $this + */ + public function withMiddleware($middleware = null) + { + if (is_null($middleware)) { + unset($this->app['middleware.disable']); + + return $this; + } + + foreach ((array) $middleware as $abstract) { + unset($this->app[$abstract]); + } + + return $this; + } + + /** + * Define additional cookies to be sent with the request. + * + * @param array $cookies + * @return $this + */ + public function withCookies(array $cookies) + { + $this->defaultCookies = array_merge($this->defaultCookies, $cookies); + + return $this; + } + + /** + * Add a cookie to be sent with the request. + * + * @param string $name + * @param string $value + * @return $this + */ + public function withCookie(string $name, string $value) + { + $this->defaultCookies[$name] = $value; + + return $this; + } + + /** + * Define additional cookies will not be encrypted before sending with the request. + * + * @param array $cookies + * @return $this + */ + public function withUnencryptedCookies(array $cookies) + { + $this->unencryptedCookies = array_merge($this->unencryptedCookies, $cookies); + + return $this; + } + + /** + * Add a cookie will not be encrypted before sending with the request. + * + * @param string $name + * @param string $value + * @return $this + */ + public function withUnencryptedCookie(string $name, string $value) + { + $this->unencryptedCookies[$name] = $value; + + return $this; + } + + /** + * Automatically follow any redirects returned from the response. + * + * @return $this + */ + public function followingRedirects() + { + $this->followRedirects = true; + + return $this; + } + + /** + * Include cookies and authorization headers for JSON requests. + * + * @return $this + */ + public function withCredentials() + { + $this->withCredentials = true; + + return $this; + } + + /** + * Disable automatic encryption of cookie values. + * + * @return $this + */ + public function disableCookieEncryption() + { + $this->encryptCookies = false; + + return $this; + } + + /** + * Set the referer header and previous URL session value in order to simulate a previous request. + * + * @param string $url + * @return $this + */ + public function from(string $url) + { + $this->app['session']->setPreviousUrl($url); + + return $this->withHeader('referer', $url); + } + + /** + * Visit the given URI with a GET request. + * + * @param string $uri + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function get($uri, array $headers = []) + { + $server = $this->transformHeadersToServerVars($headers); + $cookies = $this->prepareCookiesForRequest(); + + return $this->call('GET', $uri, [], $cookies, [], $server); + } + + /** + * Visit the given URI with a GET request, expecting a JSON response. + * + * @param string $uri + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function getJson($uri, array $headers = []) + { + return $this->json('GET', $uri, [], $headers); + } + + /** + * Visit the given URI with a POST request. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function post($uri, array $data = [], array $headers = []) + { + $server = $this->transformHeadersToServerVars($headers); + $cookies = $this->prepareCookiesForRequest(); + + return $this->call('POST', $uri, $data, $cookies, [], $server); + } + + /** + * Visit the given URI with a POST request, expecting a JSON response. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function postJson($uri, array $data = [], array $headers = []) + { + return $this->json('POST', $uri, $data, $headers); + } + + /** + * Visit the given URI with a PUT request. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function put($uri, array $data = [], array $headers = []) + { + $server = $this->transformHeadersToServerVars($headers); + $cookies = $this->prepareCookiesForRequest(); + + return $this->call('PUT', $uri, $data, $cookies, [], $server); + } + + /** + * Visit the given URI with a PUT request, expecting a JSON response. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function putJson($uri, array $data = [], array $headers = []) + { + return $this->json('PUT', $uri, $data, $headers); + } + + /** + * Visit the given URI with a PATCH request. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function patch($uri, array $data = [], array $headers = []) + { + $server = $this->transformHeadersToServerVars($headers); + $cookies = $this->prepareCookiesForRequest(); + + return $this->call('PATCH', $uri, $data, $cookies, [], $server); + } + + /** + * Visit the given URI with a PATCH request, expecting a JSON response. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function patchJson($uri, array $data = [], array $headers = []) + { + return $this->json('PATCH', $uri, $data, $headers); + } + + /** + * Visit the given URI with a DELETE request. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function delete($uri, array $data = [], array $headers = []) + { + $server = $this->transformHeadersToServerVars($headers); + $cookies = $this->prepareCookiesForRequest(); + + return $this->call('DELETE', $uri, $data, $cookies, [], $server); + } + + /** + * Visit the given URI with a DELETE request, expecting a JSON response. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function deleteJson($uri, array $data = [], array $headers = []) + { + return $this->json('DELETE', $uri, $data, $headers); + } + + /** + * Visit the given URI with an OPTIONS request. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function options($uri, array $data = [], array $headers = []) + { + $server = $this->transformHeadersToServerVars($headers); + $cookies = $this->prepareCookiesForRequest(); + + return $this->call('OPTIONS', $uri, $data, $cookies, [], $server); + } + + /** + * Visit the given URI with an OPTIONS request, expecting a JSON response. + * + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function optionsJson($uri, array $data = [], array $headers = []) + { + return $this->json('OPTIONS', $uri, $data, $headers); + } + + /** + * Call the given URI with a JSON request. + * + * @param string $method + * @param string $uri + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse + */ + public function json($method, $uri, array $data = [], array $headers = []) + { + $files = $this->extractFilesFromDataArray($data); + + $content = json_encode($data); + + $headers = array_merge([ + 'CONTENT_LENGTH' => mb_strlen($content, '8bit'), + 'CONTENT_TYPE' => 'application/json', + 'Accept' => 'application/json', + ], $headers); + + return $this->call( + $method, + $uri, + [], + $this->prepareCookiesForJsonRequest(), + $files, + $this->transformHeadersToServerVars($headers), + $content + ); + } + + /** + * Call the given URI and return the Response. + * + * @param string $method + * @param string $uri + * @param array $parameters + * @param array $cookies + * @param array $files + * @param array $server + * @param string|null $content + * @return \Illuminate\Testing\TestResponse + */ + public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null) + { + $kernel = $this->app->make(HttpKernel::class); + + $files = array_merge($files, $this->extractFilesFromDataArray($parameters)); + + $symfonyRequest = SymfonyRequest::create( + $this->prepareUrlForRequest($uri), $method, $parameters, + $cookies, $files, array_replace($this->serverVariables, $server), $content + ); + + $response = $kernel->handle( + $request = Request::createFromBase($symfonyRequest) + ); + + $kernel->terminate($request, $response); + + if ($this->followRedirects) { + $response = $this->followRedirects($response); + } + + return $this->createTestResponse($response); + } + + /** + * Turn the given URI into a fully qualified URL. + * + * @param string $uri + * @return string + */ + protected function prepareUrlForRequest($uri) + { + if (Str::startsWith($uri, '/')) { + $uri = substr($uri, 1); + } + + return trim(url($uri), '/'); + } + + /** + * Transform headers array to array of $_SERVER vars with HTTP_* format. + * + * @param array $headers + * @return array + */ + protected function transformHeadersToServerVars(array $headers) + { + return collect(array_merge($this->defaultHeaders, $headers))->mapWithKeys(function ($value, $name) { + $name = strtr(strtoupper($name), '-', '_'); + + return [$this->formatServerHeaderKey($name) => $value]; + })->all(); + } + + /** + * Format the header name for the server array. + * + * @param string $name + * @return string + */ + protected function formatServerHeaderKey($name) + { + if (! Str::startsWith($name, 'HTTP_') && $name !== 'CONTENT_TYPE' && $name !== 'REMOTE_ADDR') { + return 'HTTP_'.$name; + } + + return $name; + } + + /** + * Extract the file uploads from the given data array. + * + * @param array $data + * @return array + */ + protected function extractFilesFromDataArray(&$data) + { + $files = []; + + foreach ($data as $key => $value) { + if ($value instanceof SymfonyUploadedFile) { + $files[$key] = $value; + + unset($data[$key]); + } + + if (is_array($value)) { + $files[$key] = $this->extractFilesFromDataArray($value); + + $data[$key] = $value; + } + } + + return $files; + } + + /** + * If enabled, encrypt cookie values for request. + * + * @return array + */ + protected function prepareCookiesForRequest() + { + if (! $this->encryptCookies) { + return array_merge($this->defaultCookies, $this->unencryptedCookies); + } + + return collect($this->defaultCookies)->map(function ($value, $key) { + return encrypt(CookieValuePrefix::create($key, app('encrypter')->getKey()).$value, false); + })->merge($this->unencryptedCookies)->all(); + } + + /** + * If enabled, add cookies for JSON requests. + * + * @return array + */ + protected function prepareCookiesForJsonRequest() + { + return $this->withCredentials ? $this->prepareCookiesForRequest() : []; + } + + /** + * Follow a redirect chain until a non-redirect is received. + * + * @param \Illuminate\Http\Response $response + * @return \Illuminate\Http\Response|\Illuminate\Testing\TestResponse + */ + protected function followRedirects($response) + { + $this->followRedirects = false; + + while ($response->isRedirect()) { + $response = $this->get($response->headers->get('Location')); + } + + return $response; + } + + /** + * Create the test response instance from the given response. + * + * @param \Illuminate\Http\Response $response + * @return \Illuminate\Testing\TestResponse + */ + protected function createTestResponse($response) + { + return tap(TestResponse::fromBaseResponse($response), function ($response) { + $response->withExceptions( + $this->app->bound(LoggedExceptionCollection::class) + ? $this->app->make(LoggedExceptionCollection::class) + : new LoggedExceptionCollection + ); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php new file mode 100644 index 0000000..6662295 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php @@ -0,0 +1,289 @@ +withoutEvents(); + + $this->beforeApplicationDestroyed(function () use ($events) { + $fired = $this->getFiredEvents($events); + + $this->assertEmpty( + $eventsNotFired = array_diff($events, $fired), + 'These expected events were not fired: ['.implode(', ', $eventsNotFired).']' + ); + }); + + return $this; + } + + /** + * Specify a list of events that should not be fired for the given operation. + * + * These events will be mocked, so that handlers will not actually be executed. + * + * @param array|string $events + * @return $this + */ + public function doesntExpectEvents($events) + { + $events = is_array($events) ? $events : func_get_args(); + + $this->withoutEvents(); + + $this->beforeApplicationDestroyed(function () use ($events) { + $this->assertEmpty( + $fired = $this->getFiredEvents($events), + 'These unexpected events were fired: ['.implode(', ', $fired).']' + ); + }); + + return $this; + } + + /** + * Mock the event dispatcher so all events are silenced and collected. + * + * @return $this + */ + protected function withoutEvents() + { + $mock = Mockery::mock(EventsDispatcherContract::class)->shouldIgnoreMissing(); + + $mock->shouldReceive('dispatch', 'until')->andReturnUsing(function ($called) { + $this->firedEvents[] = $called; + }); + + Event::clearResolvedInstances(); + + $this->app->instance('events', $mock); + + return $this; + } + + /** + * Filter the given events against the fired events. + * + * @param array $events + * @return array + */ + protected function getFiredEvents(array $events) + { + return $this->getDispatched($events, $this->firedEvents); + } + + /** + * Specify a list of jobs that should be dispatched for the given operation. + * + * These jobs will be mocked, so that handlers will not actually be executed. + * + * @param array|string $jobs + * @return $this + */ + protected function expectsJobs($jobs) + { + $jobs = is_array($jobs) ? $jobs : func_get_args(); + + $this->withoutJobs(); + + $this->beforeApplicationDestroyed(function () use ($jobs) { + $dispatched = $this->getDispatchedJobs($jobs); + + $this->assertEmpty( + $jobsNotDispatched = array_diff($jobs, $dispatched), + 'These expected jobs were not dispatched: ['.implode(', ', $jobsNotDispatched).']' + ); + }); + + return $this; + } + + /** + * Specify a list of jobs that should not be dispatched for the given operation. + * + * These jobs will be mocked, so that handlers will not actually be executed. + * + * @param array|string $jobs + * @return $this + */ + protected function doesntExpectJobs($jobs) + { + $jobs = is_array($jobs) ? $jobs : func_get_args(); + + $this->withoutJobs(); + + $this->beforeApplicationDestroyed(function () use ($jobs) { + $this->assertEmpty( + $dispatched = $this->getDispatchedJobs($jobs), + 'These unexpected jobs were dispatched: ['.implode(', ', $dispatched).']' + ); + }); + + return $this; + } + + /** + * Mock the job dispatcher so all jobs are silenced and collected. + * + * @return $this + */ + protected function withoutJobs() + { + $mock = Mockery::mock(BusDispatcherContract::class)->shouldIgnoreMissing(); + + $mock->shouldReceive('dispatch', 'dispatchNow')->andReturnUsing(function ($dispatched) { + $this->dispatchedJobs[] = $dispatched; + }); + + $this->app->instance( + BusDispatcherContract::class, $mock + ); + + return $this; + } + + /** + * Filter the given jobs against the dispatched jobs. + * + * @param array $jobs + * @return array + */ + protected function getDispatchedJobs(array $jobs) + { + return $this->getDispatched($jobs, $this->dispatchedJobs); + } + + /** + * Filter the given classes against an array of dispatched classes. + * + * @param array $classes + * @param array $dispatched + * @return array + */ + protected function getDispatched(array $classes, array $dispatched) + { + return array_filter($classes, function ($class) use ($dispatched) { + return $this->wasDispatched($class, $dispatched); + }); + } + + /** + * Check if the given class exists in an array of dispatched classes. + * + * @param string $needle + * @param array $haystack + * @return bool + */ + protected function wasDispatched($needle, array $haystack) + { + foreach ($haystack as $dispatched) { + if ((is_string($dispatched) && ($dispatched === $needle || is_subclass_of($dispatched, $needle))) || + $dispatched instanceof $needle) { + return true; + } + } + + return false; + } + + /** + * Mock the notification dispatcher so all notifications are silenced. + * + * @return $this + */ + protected function withoutNotifications() + { + $mock = Mockery::mock(NotificationDispatcher::class); + + $mock->shouldReceive('send')->andReturnUsing(function ($notifiable, $instance, $channels = []) { + $this->dispatchedNotifications[] = compact( + 'notifiable', 'instance', 'channels' + ); + }); + + $this->app->instance(NotificationDispatcher::class, $mock); + + return $this; + } + + /** + * Specify a notification that is expected to be dispatched. + * + * @param mixed $notifiable + * @param string $notification + * @return $this + */ + protected function expectsNotification($notifiable, $notification) + { + $this->withoutNotifications(); + + $this->beforeApplicationDestroyed(function () use ($notifiable, $notification) { + foreach ($this->dispatchedNotifications as $dispatched) { + $notified = $dispatched['notifiable']; + + if (($notified === $notifiable || + $notified->getKey() == $notifiable->getKey()) && + get_class($dispatched['instance']) === $notification + ) { + return $this; + } + } + + $this->fail('The following expected notification were not dispatched: ['.$notification.']'); + }); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseMigrations.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseMigrations.php new file mode 100644 index 0000000..10a3a73 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseMigrations.php @@ -0,0 +1,29 @@ +artisan('migrate:fresh', $this->migrateFreshUsing()); + + $this->app[Kernel::class]->setArtisan(null); + + $this->beforeApplicationDestroyed(function () { + $this->artisan('migrate:rollback'); + + RefreshDatabaseState::$migrated = false; + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseTransactions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseTransactions.php new file mode 100644 index 0000000..e162e18 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseTransactions.php @@ -0,0 +1,48 @@ +app->make('db'); + + foreach ($this->connectionsToTransact() as $name) { + $connection = $database->connection($name); + $dispatcher = $connection->getEventDispatcher(); + + $connection->unsetEventDispatcher(); + $connection->beginTransaction(); + $connection->setEventDispatcher($dispatcher); + } + + $this->beforeApplicationDestroyed(function () use ($database) { + foreach ($this->connectionsToTransact() as $name) { + $connection = $database->connection($name); + $dispatcher = $connection->getEventDispatcher(); + + $connection->unsetEventDispatcher(); + $connection->rollBack(); + $connection->setEventDispatcher($dispatcher); + $connection->disconnect(); + } + }); + } + + /** + * The database connections that should have transactions. + * + * @return array + */ + protected function connectionsToTransact() + { + return property_exists($this, 'connectionsToTransact') + ? $this->connectionsToTransact : [null]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/LazilyRefreshDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/LazilyRefreshDatabase.php new file mode 100644 index 0000000..98204cc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/LazilyRefreshDatabase.php @@ -0,0 +1,34 @@ +app->make('db'); + + $database->beforeExecuting(function () { + if (RefreshDatabaseState::$lazilyRefreshed) { + return; + } + + RefreshDatabaseState::$lazilyRefreshed = true; + + $this->baseRefreshDatabase(); + }); + + $this->beforeApplicationDestroyed(function () { + RefreshDatabaseState::$lazilyRefreshed = false; + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php new file mode 100644 index 0000000..4839003 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php @@ -0,0 +1,132 @@ +usingInMemoryDatabase() + ? $this->refreshInMemoryDatabase() + : $this->refreshTestDatabase(); + + $this->afterRefreshingDatabase(); + } + + /** + * Determine if an in-memory database is being used. + * + * @return bool + */ + protected function usingInMemoryDatabase() + { + $default = config('database.default'); + + return config("database.connections.$default.database") === ':memory:'; + } + + /** + * Refresh the in-memory database. + * + * @return void + */ + protected function refreshInMemoryDatabase() + { + $this->artisan('migrate', $this->migrateUsing()); + + $this->app[Kernel::class]->setArtisan(null); + } + + /** + * The parameters that should be used when running "migrate". + * + * @return array + */ + protected function migrateUsing() + { + return [ + '--seed' => $this->shouldSeed(), + '--seeder' => $this->seeder(), + ]; + } + + /** + * Refresh a conventional test database. + * + * @return void + */ + protected function refreshTestDatabase() + { + if (! RefreshDatabaseState::$migrated) { + $this->artisan('migrate:fresh', $this->migrateFreshUsing()); + + $this->app[Kernel::class]->setArtisan(null); + + RefreshDatabaseState::$migrated = true; + } + + $this->beginDatabaseTransaction(); + } + + /** + * Begin a database transaction on the testing database. + * + * @return void + */ + public function beginDatabaseTransaction() + { + $database = $this->app->make('db'); + + foreach ($this->connectionsToTransact() as $name) { + $connection = $database->connection($name); + $dispatcher = $connection->getEventDispatcher(); + + $connection->unsetEventDispatcher(); + $connection->beginTransaction(); + $connection->setEventDispatcher($dispatcher); + } + + $this->beforeApplicationDestroyed(function () use ($database) { + foreach ($this->connectionsToTransact() as $name) { + $connection = $database->connection($name); + $dispatcher = $connection->getEventDispatcher(); + + $connection->unsetEventDispatcher(); + $connection->rollBack(); + $connection->setEventDispatcher($dispatcher); + $connection->disconnect(); + } + }); + } + + /** + * The database connections that should have transactions. + * + * @return array + */ + protected function connectionsToTransact() + { + return property_exists($this, 'connectionsToTransact') + ? $this->connectionsToTransact : [null]; + } + + /** + * Perform any work that should take place once the database has finished refreshing. + * + * @return void + */ + protected function afterRefreshingDatabase() + { + // ... + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabaseState.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabaseState.php new file mode 100644 index 0000000..a42d3d0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabaseState.php @@ -0,0 +1,20 @@ +app) { + $this->refreshApplication(); + + ParallelTesting::callSetUpTestCaseCallbacks($this); + } + + $this->setUpTraits(); + + foreach ($this->afterApplicationCreatedCallbacks as $callback) { + $callback(); + } + + Model::setEventDispatcher($this->app['events']); + + $this->setUpHasRun = true; + } + + /** + * Refresh the application instance. + * + * @return void + */ + protected function refreshApplication() + { + $this->app = $this->createApplication(); + } + + /** + * Boot the testing helper traits. + * + * @return array + */ + protected function setUpTraits() + { + $uses = array_flip(class_uses_recursive(static::class)); + + if (isset($uses[RefreshDatabase::class])) { + $this->refreshDatabase(); + } + + if (isset($uses[DatabaseMigrations::class])) { + $this->runDatabaseMigrations(); + } + + if (isset($uses[DatabaseTransactions::class])) { + $this->beginDatabaseTransaction(); + } + + if (isset($uses[WithoutMiddleware::class])) { + $this->disableMiddlewareForAllTests(); + } + + if (isset($uses[WithoutEvents::class])) { + $this->disableEventsForAllTests(); + } + + if (isset($uses[WithFaker::class])) { + $this->setUpFaker(); + } + + return $uses; + } + + /** + * Clean up the testing environment before the next test. + * + * @return void + * + * @throws \Mockery\Exception\InvalidCountException + */ + protected function tearDown(): void + { + if ($this->app) { + $this->callBeforeApplicationDestroyedCallbacks(); + + ParallelTesting::callTearDownTestCaseCallbacks($this); + + $this->app->flush(); + + $this->app = null; + } + + $this->setUpHasRun = false; + + if (property_exists($this, 'serverVariables')) { + $this->serverVariables = []; + } + + if (property_exists($this, 'defaultHeaders')) { + $this->defaultHeaders = []; + } + + if (class_exists('Mockery')) { + if ($container = Mockery::getContainer()) { + $this->addToAssertionCount($container->mockery_getExpectationCount()); + } + + try { + Mockery::close(); + } catch (InvalidCountException $e) { + if (! Str::contains($e->getMethodName(), ['doWrite', 'askQuestion'])) { + throw $e; + } + } + } + + if (class_exists(Carbon::class)) { + Carbon::setTestNow(); + } + + if (class_exists(CarbonImmutable::class)) { + CarbonImmutable::setTestNow(); + } + + $this->afterApplicationCreatedCallbacks = []; + $this->beforeApplicationDestroyedCallbacks = []; + + Artisan::forgetBootstrappers(); + + Queue::createPayloadUsing(null); + + if ($this->callbackException) { + throw $this->callbackException; + } + } + + /** + * Register a callback to be run after the application is created. + * + * @param callable $callback + * @return void + */ + public function afterApplicationCreated(callable $callback) + { + $this->afterApplicationCreatedCallbacks[] = $callback; + + if ($this->setUpHasRun) { + $callback(); + } + } + + /** + * Register a callback to be run before the application is destroyed. + * + * @param callable $callback + * @return void + */ + protected function beforeApplicationDestroyed(callable $callback) + { + $this->beforeApplicationDestroyedCallbacks[] = $callback; + } + + /** + * Execute the application's pre-destruction callbacks. + * + * @return void + */ + protected function callBeforeApplicationDestroyedCallbacks() + { + foreach ($this->beforeApplicationDestroyedCallbacks as $callback) { + try { + $callback(); + } catch (Throwable $e) { + if (! $this->callbackException) { + $this->callbackException = $e; + } + } + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Traits/CanConfigureMigrationCommands.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Traits/CanConfigureMigrationCommands.php new file mode 100644 index 0000000..aafca6f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Traits/CanConfigureMigrationCommands.php @@ -0,0 +1,64 @@ +seeder(); + + return array_merge( + [ + '--drop-views' => $this->shouldDropViews(), + '--drop-types' => $this->shouldDropTypes(), + ], + $seeder ? ['--seeder' => $seeder] : ['--seed' => $this->shouldSeed()] + ); + } + + /** + * Determine if views should be dropped when refreshing the database. + * + * @return bool + */ + protected function shouldDropViews() + { + return property_exists($this, 'dropViews') ? $this->dropViews : false; + } + + /** + * Determine if types should be dropped when refreshing the database. + * + * @return bool + */ + protected function shouldDropTypes() + { + return property_exists($this, 'dropTypes') ? $this->dropTypes : false; + } + + /** + * Determine if the seed task should be run when refreshing the database. + * + * @return bool + */ + protected function shouldSeed() + { + return property_exists($this, 'seed') ? $this->seed : false; + } + + /** + * Determine the specific seeder class that should be used when refreshing the database. + * + * @return mixed + */ + protected function seeder() + { + return property_exists($this, 'seeder') ? $this->seeder : false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithFaker.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithFaker.php new file mode 100644 index 0000000..cd276fb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithFaker.php @@ -0,0 +1,54 @@ +faker = $this->makeFaker(); + } + + /** + * Get the default Faker instance for a given locale. + * + * @param string|null $locale + * @return \Faker\Generator + */ + protected function faker($locale = null) + { + return is_null($locale) ? $this->faker : $this->makeFaker($locale); + } + + /** + * Create a Faker instance for the given locale. + * + * @param string|null $locale + * @return \Faker\Generator + */ + protected function makeFaker($locale = null) + { + $locale = $locale ?? config('app.faker_locale', Factory::DEFAULT_LOCALE); + + if (isset($this->app) && $this->app->bound(Generator::class)) { + return $this->app->make(Generator::class, ['locale' => $locale]); + } + + return Factory::create($locale); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithoutEvents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithoutEvents.php new file mode 100644 index 0000000..fa5df3c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithoutEvents.php @@ -0,0 +1,22 @@ +withoutEvents(); + } else { + throw new Exception('Unable to disable events. ApplicationTrait not used.'); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithoutMiddleware.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithoutMiddleware.php new file mode 100644 index 0000000..269b532 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/WithoutMiddleware.php @@ -0,0 +1,22 @@ +withoutMiddleware(); + } else { + throw new Exception('Unable to disable middleware. MakesHttpRequests trait not used.'); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Wormhole.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Wormhole.php new file mode 100644 index 0000000..54fe0fa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Wormhole.php @@ -0,0 +1,245 @@ +value = $value; + } + + /** + * Travel forward the given number of milliseconds. + * + * @param callable|null $callback + * @return mixed + */ + public function millisecond($callback = null) + { + return $this->milliseconds($callback); + } + + /** + * Travel forward the given number of milliseconds. + * + * @param callable|null $callback + * @return mixed + */ + public function milliseconds($callback = null) + { + Carbon::setTestNow(Carbon::now()->addMilliseconds($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of seconds. + * + * @param callable|null $callback + * @return mixed + */ + public function second($callback = null) + { + return $this->seconds($callback); + } + + /** + * Travel forward the given number of seconds. + * + * @param callable|null $callback + * @return mixed + */ + public function seconds($callback = null) + { + Carbon::setTestNow(Carbon::now()->addSeconds($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of minutes. + * + * @param callable|null $callback + * @return mixed + */ + public function minute($callback = null) + { + return $this->minutes($callback); + } + + /** + * Travel forward the given number of minutes. + * + * @param callable|null $callback + * @return mixed + */ + public function minutes($callback = null) + { + Carbon::setTestNow(Carbon::now()->addMinutes($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of hours. + * + * @param callable|null $callback + * @return mixed + */ + public function hour($callback = null) + { + return $this->hours($callback); + } + + /** + * Travel forward the given number of hours. + * + * @param callable|null $callback + * @return mixed + */ + public function hours($callback = null) + { + Carbon::setTestNow(Carbon::now()->addHours($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of days. + * + * @param callable|null $callback + * @return mixed + */ + public function day($callback = null) + { + return $this->days($callback); + } + + /** + * Travel forward the given number of days. + * + * @param callable|null $callback + * @return mixed + */ + public function days($callback = null) + { + Carbon::setTestNow(Carbon::now()->addDays($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of weeks. + * + * @param callable|null $callback + * @return mixed + */ + public function week($callback = null) + { + return $this->weeks($callback); + } + + /** + * Travel forward the given number of weeks. + * + * @param callable|null $callback + * @return mixed + */ + public function weeks($callback = null) + { + Carbon::setTestNow(Carbon::now()->addWeeks($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of months. + * + * @param callable|null $callback + * @return mixed + */ + public function month($callback = null) + { + return $this->months($callback); + } + + /** + * Travel forward the given number of months. + * + * @param callable|null $callback + * @return mixed + */ + public function months($callback = null) + { + Carbon::setTestNow(Carbon::now()->addMonths($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel forward the given number of years. + * + * @param callable|null $callback + * @return mixed + */ + public function year($callback = null) + { + return $this->years($callback); + } + + /** + * Travel forward the given number of years. + * + * @param callable|null $callback + * @return mixed + */ + public function years($callback = null) + { + Carbon::setTestNow(Carbon::now()->addYears($this->value)); + + return $this->handleCallback($callback); + } + + /** + * Travel back to the current time. + * + * @return \DateTimeInterface + */ + public static function back() + { + Carbon::setTestNow(); + + return Carbon::now(); + } + + /** + * Handle the given optional execution callback. + * + * @param callable|null $callback + * @return mixed + */ + protected function handleCallback($callback) + { + if ($callback) { + return tap($callback(), function () { + Carbon::setTestNow(); + }); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php new file mode 100644 index 0000000..2a1593a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php @@ -0,0 +1,83 @@ +getValidationFactory()->make($request->all(), $validator); + } + + return $validator->validate(); + } + + /** + * Validate the given request with the given rules. + * + * @param \Illuminate\Http\Request $request + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return array + * + * @throws \Illuminate\Validation\ValidationException + */ + public function validate(Request $request, array $rules, + array $messages = [], array $customAttributes = []) + { + return $this->getValidationFactory()->make( + $request->all(), $rules, $messages, $customAttributes + )->validate(); + } + + /** + * Validate the given request with the given rules. + * + * @param string $errorBag + * @param \Illuminate\Http\Request $request + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return array + * + * @throws \Illuminate\Validation\ValidationException + */ + public function validateWithBag($errorBag, Request $request, array $rules, + array $messages = [], array $customAttributes = []) + { + try { + return $this->validate($request, $rules, $messages, $customAttributes); + } catch (ValidationException $e) { + $e->errorBag = $errorBag; + + throw $e; + } + } + + /** + * Get a validation factory instance. + * + * @return \Illuminate\Contracts\Validation\Factory + */ + protected function getValidationFactory() + { + return app(Factory::class); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php new file mode 100644 index 0000000..bd879a8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php @@ -0,0 +1,934 @@ +toResponse(request())); + } + + app()->abort($code, $message, $headers); + } +} + +if (! function_exists('abort_if')) { + /** + * Throw an HttpException with the given data if the given condition is true. + * + * @param bool $boolean + * @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Support\Responsable|int $code + * @param string $message + * @param array $headers + * @return void + * + * @throws \Symfony\Component\HttpKernel\Exception\HttpException + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + */ + function abort_if($boolean, $code, $message = '', array $headers = []) + { + if ($boolean) { + abort($code, $message, $headers); + } + } +} + +if (! function_exists('abort_unless')) { + /** + * Throw an HttpException with the given data unless the given condition is true. + * + * @param bool $boolean + * @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Support\Responsable|int $code + * @param string $message + * @param array $headers + * @return void + * + * @throws \Symfony\Component\HttpKernel\Exception\HttpException + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + */ + function abort_unless($boolean, $code, $message = '', array $headers = []) + { + if (! $boolean) { + abort($code, $message, $headers); + } + } +} + +if (! function_exists('action')) { + /** + * Generate the URL to a controller action. + * + * @param string|array $name + * @param mixed $parameters + * @param bool $absolute + * @return string + */ + function action($name, $parameters = [], $absolute = true) + { + return app('url')->action($name, $parameters, $absolute); + } +} + +if (! function_exists('app')) { + /** + * Get the available container instance. + * + * @param string|null $abstract + * @param array $parameters + * @return mixed|\Illuminate\Contracts\Foundation\Application + */ + function app($abstract = null, array $parameters = []) + { + if (is_null($abstract)) { + return Container::getInstance(); + } + + return Container::getInstance()->make($abstract, $parameters); + } +} + +if (! function_exists('app_path')) { + /** + * Get the path to the application folder. + * + * @param string $path + * @return string + */ + function app_path($path = '') + { + return app()->path($path); + } +} + +if (! function_exists('asset')) { + /** + * Generate an asset path for the application. + * + * @param string $path + * @param bool|null $secure + * @return string + */ + function asset($path, $secure = null) + { + return app('url')->asset($path, $secure); + } +} + +if (! function_exists('auth')) { + /** + * Get the available auth instance. + * + * @param string|null $guard + * @return \Illuminate\Contracts\Auth\Factory|\Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard + */ + function auth($guard = null) + { + if (is_null($guard)) { + return app(AuthFactory::class); + } + + return app(AuthFactory::class)->guard($guard); + } +} + +if (! function_exists('back')) { + /** + * Create a new redirect response to the previous location. + * + * @param int $status + * @param array $headers + * @param mixed $fallback + * @return \Illuminate\Http\RedirectResponse + */ + function back($status = 302, $headers = [], $fallback = false) + { + return app('redirect')->back($status, $headers, $fallback); + } +} + +if (! function_exists('base_path')) { + /** + * Get the path to the base of the install. + * + * @param string $path + * @return string + */ + function base_path($path = '') + { + return app()->basePath($path); + } +} + +if (! function_exists('bcrypt')) { + /** + * Hash the given value against the bcrypt algorithm. + * + * @param string $value + * @param array $options + * @return string + */ + function bcrypt($value, $options = []) + { + return app('hash')->driver('bcrypt')->make($value, $options); + } +} + +if (! function_exists('broadcast')) { + /** + * Begin broadcasting an event. + * + * @param mixed|null $event + * @return \Illuminate\Broadcasting\PendingBroadcast + */ + function broadcast($event = null) + { + return app(BroadcastFactory::class)->event($event); + } +} + +if (! function_exists('cache')) { + /** + * Get / set the specified cache value. + * + * If an array is passed, we'll assume you want to put to the cache. + * + * @param dynamic key|key,default|data,expiration|null + * @return mixed|\Illuminate\Cache\CacheManager + * + * @throws \Exception + */ + function cache() + { + $arguments = func_get_args(); + + if (empty($arguments)) { + return app('cache'); + } + + if (is_string($arguments[0])) { + return app('cache')->get(...$arguments); + } + + if (! is_array($arguments[0])) { + throw new Exception( + 'When setting a value in the cache, you must pass an array of key / value pairs.' + ); + } + + return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1] ?? null); + } +} + +if (! function_exists('config')) { + /** + * Get / set the specified configuration value. + * + * If an array is passed as the key, we will assume you want to set an array of values. + * + * @param array|string|null $key + * @param mixed $default + * @return mixed|\Illuminate\Config\Repository + */ + function config($key = null, $default = null) + { + if (is_null($key)) { + return app('config'); + } + + if (is_array($key)) { + return app('config')->set($key); + } + + return app('config')->get($key, $default); + } +} + +if (! function_exists('config_path')) { + /** + * Get the configuration path. + * + * @param string $path + * @return string + */ + function config_path($path = '') + { + return app()->configPath($path); + } +} + +if (! function_exists('cookie')) { + /** + * Create a new cookie instance. + * + * @param string|null $name + * @param string|null $value + * @param int $minutes + * @param string|null $path + * @param string|null $domain + * @param bool|null $secure + * @param bool $httpOnly + * @param bool $raw + * @param string|null $sameSite + * @return \Illuminate\Cookie\CookieJar|\Symfony\Component\HttpFoundation\Cookie + */ + function cookie($name = null, $value = null, $minutes = 0, $path = null, $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = null) + { + $cookie = app(CookieFactory::class); + + if (is_null($name)) { + return $cookie; + } + + return $cookie->make($name, $value, $minutes, $path, $domain, $secure, $httpOnly, $raw, $sameSite); + } +} + +if (! function_exists('csrf_field')) { + /** + * Generate a CSRF token form field. + * + * @return \Illuminate\Support\HtmlString + */ + function csrf_field() + { + return new HtmlString(''); + } +} + +if (! function_exists('csrf_token')) { + /** + * Get the CSRF token value. + * + * @return string + * + * @throws \RuntimeException + */ + function csrf_token() + { + $session = app('session'); + + if (isset($session)) { + return $session->token(); + } + + throw new RuntimeException('Application session store not set.'); + } +} + +if (! function_exists('database_path')) { + /** + * Get the database path. + * + * @param string $path + * @return string + */ + function database_path($path = '') + { + return app()->databasePath($path); + } +} + +if (! function_exists('decrypt')) { + /** + * Decrypt the given value. + * + * @param string $value + * @param bool $unserialize + * @return mixed + */ + function decrypt($value, $unserialize = true) + { + return app('encrypter')->decrypt($value, $unserialize); + } +} + +if (! function_exists('dispatch')) { + /** + * Dispatch a job to its appropriate handler. + * + * @param mixed $job + * @return \Illuminate\Foundation\Bus\PendingDispatch + */ + function dispatch($job) + { + return $job instanceof Closure + ? new PendingClosureDispatch(CallQueuedClosure::create($job)) + : new PendingDispatch($job); + } +} + +if (! function_exists('dispatch_sync')) { + /** + * Dispatch a command to its appropriate handler in the current process. + * + * Queueable jobs will be dispatched to the "sync" queue. + * + * @param mixed $job + * @param mixed $handler + * @return mixed + */ + function dispatch_sync($job, $handler = null) + { + return app(Dispatcher::class)->dispatchSync($job, $handler); + } +} + +if (! function_exists('dispatch_now')) { + /** + * Dispatch a command to its appropriate handler in the current process. + * + * @param mixed $job + * @param mixed $handler + * @return mixed + * + * @deprecated Will be removed in a future Laravel version. + */ + function dispatch_now($job, $handler = null) + { + return app(Dispatcher::class)->dispatchNow($job, $handler); + } +} + +if (! function_exists('encrypt')) { + /** + * Encrypt the given value. + * + * @param mixed $value + * @param bool $serialize + * @return string + */ + function encrypt($value, $serialize = true) + { + return app('encrypter')->encrypt($value, $serialize); + } +} + +if (! function_exists('event')) { + /** + * Dispatch an event and call the listeners. + * + * @param string|object $event + * @param mixed $payload + * @param bool $halt + * @return array|null + */ + function event(...$args) + { + return app('events')->dispatch(...$args); + } +} + +if (! function_exists('info')) { + /** + * Write some information to the log. + * + * @param string $message + * @param array $context + * @return void + */ + function info($message, $context = []) + { + app('log')->info($message, $context); + } +} + +if (! function_exists('logger')) { + /** + * Log a debug message to the logs. + * + * @param string|null $message + * @param array $context + * @return \Illuminate\Log\LogManager|null + */ + function logger($message = null, array $context = []) + { + if (is_null($message)) { + return app('log'); + } + + return app('log')->debug($message, $context); + } +} + +if (! function_exists('lang_path')) { + /** + * Get the path to the language folder. + * + * @param string $path + * @return string + */ + function lang_path($path = '') + { + return app('path.lang').($path ? DIRECTORY_SEPARATOR.$path : $path); + } +} + +if (! function_exists('logs')) { + /** + * Get a log driver instance. + * + * @param string|null $driver + * @return \Illuminate\Log\LogManager|\Psr\Log\LoggerInterface + */ + function logs($driver = null) + { + return $driver ? app('log')->driver($driver) : app('log'); + } +} + +if (! function_exists('method_field')) { + /** + * Generate a form field to spoof the HTTP verb used by forms. + * + * @param string $method + * @return \Illuminate\Support\HtmlString + */ + function method_field($method) + { + return new HtmlString(''); + } +} + +if (! function_exists('mix')) { + /** + * Get the path to a versioned Mix file. + * + * @param string $path + * @param string $manifestDirectory + * @return \Illuminate\Support\HtmlString|string + * + * @throws \Exception + */ + function mix($path, $manifestDirectory = '') + { + return app(Mix::class)(...func_get_args()); + } +} + +if (! function_exists('now')) { + /** + * Create a new Carbon instance for the current time. + * + * @param \DateTimeZone|string|null $tz + * @return \Illuminate\Support\Carbon + */ + function now($tz = null) + { + return Date::now($tz); + } +} + +if (! function_exists('old')) { + /** + * Retrieve an old input item. + * + * @param string|null $key + * @param mixed $default + * @return mixed + */ + function old($key = null, $default = null) + { + return app('request')->old($key, $default); + } +} + +if (! function_exists('policy')) { + /** + * Get a policy instance for a given class. + * + * @param object|string $class + * @return mixed + * + * @throws \InvalidArgumentException + */ + function policy($class) + { + return app(Gate::class)->getPolicyFor($class); + } +} + +if (! function_exists('public_path')) { + /** + * Get the path to the public folder. + * + * @param string $path + * @return string + */ + function public_path($path = '') + { + return app()->make('path.public').($path ? DIRECTORY_SEPARATOR.ltrim($path, DIRECTORY_SEPARATOR) : $path); + } +} + +if (! function_exists('redirect')) { + /** + * Get an instance of the redirector. + * + * @param string|null $to + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse + */ + function redirect($to = null, $status = 302, $headers = [], $secure = null) + { + if (is_null($to)) { + return app('redirect'); + } + + return app('redirect')->to($to, $status, $headers, $secure); + } +} + +if (! function_exists('report')) { + /** + * Report an exception. + * + * @param \Throwable|string $exception + * @return void + */ + function report($exception) + { + if (is_string($exception)) { + $exception = new Exception($exception); + } + + app(ExceptionHandler::class)->report($exception); + } +} + +if (! function_exists('request')) { + /** + * Get an instance of the current request or an input item from the request. + * + * @param array|string|null $key + * @param mixed $default + * @return \Illuminate\Http\Request|string|array|null + */ + function request($key = null, $default = null) + { + if (is_null($key)) { + return app('request'); + } + + if (is_array($key)) { + return app('request')->only($key); + } + + $value = app('request')->__get($key); + + return is_null($value) ? value($default) : $value; + } +} + +if (! function_exists('rescue')) { + /** + * Catch a potential exception and return a default value. + * + * @param callable $callback + * @param mixed $rescue + * @param bool $report + * @return mixed + */ + function rescue(callable $callback, $rescue = null, $report = true) + { + try { + return $callback(); + } catch (Throwable $e) { + if ($report) { + report($e); + } + + return value($rescue, $e); + } + } +} + +if (! function_exists('resolve')) { + /** + * Resolve a service from the container. + * + * @param string $name + * @param array $parameters + * @return mixed + */ + function resolve($name, array $parameters = []) + { + return app($name, $parameters); + } +} + +if (! function_exists('resource_path')) { + /** + * Get the path to the resources folder. + * + * @param string $path + * @return string + */ + function resource_path($path = '') + { + return app()->resourcePath($path); + } +} + +if (! function_exists('response')) { + /** + * Return a new response from the application. + * + * @param \Illuminate\Contracts\View\View|string|array|null $content + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory + */ + function response($content = '', $status = 200, array $headers = []) + { + $factory = app(ResponseFactory::class); + + if (func_num_args() === 0) { + return $factory; + } + + return $factory->make($content, $status, $headers); + } +} + +if (! function_exists('route')) { + /** + * Generate the URL to a named route. + * + * @param array|string $name + * @param mixed $parameters + * @param bool $absolute + * @return string + */ + function route($name, $parameters = [], $absolute = true) + { + return app('url')->route($name, $parameters, $absolute); + } +} + +if (! function_exists('secure_asset')) { + /** + * Generate an asset path for the application. + * + * @param string $path + * @return string + */ + function secure_asset($path) + { + return asset($path, true); + } +} + +if (! function_exists('secure_url')) { + /** + * Generate a HTTPS url for the application. + * + * @param string $path + * @param mixed $parameters + * @return string + */ + function secure_url($path, $parameters = []) + { + return url($path, $parameters, true); + } +} + +if (! function_exists('session')) { + /** + * Get / set the specified session value. + * + * If an array is passed as the key, we will assume you want to set an array of values. + * + * @param array|string|null $key + * @param mixed $default + * @return mixed|\Illuminate\Session\Store|\Illuminate\Session\SessionManager + */ + function session($key = null, $default = null) + { + if (is_null($key)) { + return app('session'); + } + + if (is_array($key)) { + return app('session')->put($key); + } + + return app('session')->get($key, $default); + } +} + +if (! function_exists('storage_path')) { + /** + * Get the path to the storage folder. + * + * @param string $path + * @return string + */ + function storage_path($path = '') + { + return app('path.storage').($path ? DIRECTORY_SEPARATOR.$path : $path); + } +} + +if (! function_exists('today')) { + /** + * Create a new Carbon instance for the current date. + * + * @param \DateTimeZone|string|null $tz + * @return \Illuminate\Support\Carbon + */ + function today($tz = null) + { + return Date::today($tz); + } +} + +if (! function_exists('trans')) { + /** + * Translate the given message. + * + * @param string|null $key + * @param array $replace + * @param string|null $locale + * @return \Illuminate\Contracts\Translation\Translator|string|array|null + */ + function trans($key = null, $replace = [], $locale = null) + { + if (is_null($key)) { + return app('translator'); + } + + return app('translator')->get($key, $replace, $locale); + } +} + +if (! function_exists('trans_choice')) { + /** + * Translates the given message based on a count. + * + * @param string $key + * @param \Countable|int|array $number + * @param array $replace + * @param string|null $locale + * @return string + */ + function trans_choice($key, $number, array $replace = [], $locale = null) + { + return app('translator')->choice($key, $number, $replace, $locale); + } +} + +if (! function_exists('__')) { + /** + * Translate the given message. + * + * @param string|null $key + * @param array $replace + * @param string|null $locale + * @return string|array|null + */ + function __($key = null, $replace = [], $locale = null) + { + if (is_null($key)) { + return $key; + } + + return trans($key, $replace, $locale); + } +} + +if (! function_exists('url')) { + /** + * Generate a url for the application. + * + * @param string|null $path + * @param mixed $parameters + * @param bool|null $secure + * @return \Illuminate\Contracts\Routing\UrlGenerator|string + */ + function url($path = null, $parameters = [], $secure = null) + { + if (is_null($path)) { + return app(UrlGenerator::class); + } + + return app(UrlGenerator::class)->to($path, $parameters, $secure); + } +} + +if (! function_exists('validator')) { + /** + * Create a new Validator instance. + * + * @param array $data + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return \Illuminate\Contracts\Validation\Validator|\Illuminate\Contracts\Validation\Factory + */ + function validator(array $data = [], array $rules = [], array $messages = [], array $customAttributes = []) + { + $factory = app(ValidationFactory::class); + + if (func_num_args() === 0) { + return $factory; + } + + return $factory->make($data, $rules, $messages, $customAttributes); + } +} + +if (! function_exists('view')) { + /** + * Get the evaluated view contents for the given view. + * + * @param string|null $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory + */ + function view($view = null, $data = [], $mergeData = []) + { + $factory = app(ViewFactory::class); + + if (func_num_args() === 0) { + return $factory; + } + + return $factory->make($view, $data, $mergeData); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/stubs/facade.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/stubs/facade.stub new file mode 100644 index 0000000..aadbe74 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Foundation/stubs/facade.stub @@ -0,0 +1,21 @@ +verifyAlgorithm && $this->info($hashedValue)['algoName'] !== 'argon2id') { + throw new RuntimeException('This password does not use the Argon2id algorithm.'); + } + + if (strlen($hashedValue) === 0) { + return false; + } + + return password_verify($value, $hashedValue); + } + + /** + * Get the algorithm that should be used for hashing. + * + * @return int + */ + protected function algorithm() + { + return PASSWORD_ARGON2ID; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/ArgonHasher.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/ArgonHasher.php new file mode 100644 index 0000000..b999257 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/ArgonHasher.php @@ -0,0 +1,196 @@ +time = $options['time'] ?? $this->time; + $this->memory = $options['memory'] ?? $this->memory; + $this->threads = $this->threads($options); + $this->verifyAlgorithm = $options['verify'] ?? $this->verifyAlgorithm; + } + + /** + * Hash the given value. + * + * @param string $value + * @param array $options + * @return string + * + * @throws \RuntimeException + */ + public function make($value, array $options = []) + { + $hash = @password_hash($value, $this->algorithm(), [ + 'memory_cost' => $this->memory($options), + 'time_cost' => $this->time($options), + 'threads' => $this->threads($options), + ]); + + if (! is_string($hash)) { + throw new RuntimeException('Argon2 hashing not supported.'); + } + + return $hash; + } + + /** + * Get the algorithm that should be used for hashing. + * + * @return int + */ + protected function algorithm() + { + return PASSWORD_ARGON2I; + } + + /** + * Check the given plain value against a hash. + * + * @param string $value + * @param string $hashedValue + * @param array $options + * @return bool + * + * @throws \RuntimeException + */ + public function check($value, $hashedValue, array $options = []) + { + if ($this->verifyAlgorithm && $this->info($hashedValue)['algoName'] !== 'argon2i') { + throw new RuntimeException('This password does not use the Argon2i algorithm.'); + } + + return parent::check($value, $hashedValue, $options); + } + + /** + * Check if the given hash has been hashed using the given options. + * + * @param string $hashedValue + * @param array $options + * @return bool + */ + public function needsRehash($hashedValue, array $options = []) + { + return password_needs_rehash($hashedValue, $this->algorithm(), [ + 'memory_cost' => $this->memory($options), + 'time_cost' => $this->time($options), + 'threads' => $this->threads($options), + ]); + } + + /** + * Set the default password memory factor. + * + * @param int $memory + * @return $this + */ + public function setMemory(int $memory) + { + $this->memory = $memory; + + return $this; + } + + /** + * Set the default password timing factor. + * + * @param int $time + * @return $this + */ + public function setTime(int $time) + { + $this->time = $time; + + return $this; + } + + /** + * Set the default password threads factor. + * + * @param int $threads + * @return $this + */ + public function setThreads(int $threads) + { + $this->threads = $threads; + + return $this; + } + + /** + * Extract the memory cost value from the options array. + * + * @param array $options + * @return int + */ + protected function memory(array $options) + { + return $options['memory'] ?? $this->memory; + } + + /** + * Extract the time cost value from the options array. + * + * @param array $options + * @return int + */ + protected function time(array $options) + { + return $options['time'] ?? $this->time; + } + + /** + * Extract the thread's value from the options array. + * + * @param array $options + * @return int + */ + protected function threads(array $options) + { + if (defined('PASSWORD_ARGON2_PROVIDER') && PASSWORD_ARGON2_PROVIDER === 'sodium') { + return 1; + } + + return $options['threads'] ?? $this->threads; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/BcryptHasher.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/BcryptHasher.php new file mode 100755 index 0000000..26f928c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/BcryptHasher.php @@ -0,0 +1,114 @@ +rounds = $options['rounds'] ?? $this->rounds; + $this->verifyAlgorithm = $options['verify'] ?? $this->verifyAlgorithm; + } + + /** + * Hash the given value. + * + * @param string $value + * @param array $options + * @return string + * + * @throws \RuntimeException + */ + public function make($value, array $options = []) + { + $hash = password_hash($value, PASSWORD_BCRYPT, [ + 'cost' => $this->cost($options), + ]); + + if ($hash === false) { + throw new RuntimeException('Bcrypt hashing not supported.'); + } + + return $hash; + } + + /** + * Check the given plain value against a hash. + * + * @param string $value + * @param string $hashedValue + * @param array $options + * @return bool + * + * @throws \RuntimeException + */ + public function check($value, $hashedValue, array $options = []) + { + if ($this->verifyAlgorithm && $this->info($hashedValue)['algoName'] !== 'bcrypt') { + throw new RuntimeException('This password does not use the Bcrypt algorithm.'); + } + + return parent::check($value, $hashedValue, $options); + } + + /** + * Check if the given hash has been hashed using the given options. + * + * @param string $hashedValue + * @param array $options + * @return bool + */ + public function needsRehash($hashedValue, array $options = []) + { + return password_needs_rehash($hashedValue, PASSWORD_BCRYPT, [ + 'cost' => $this->cost($options), + ]); + } + + /** + * Set the default password work factor. + * + * @param int $rounds + * @return $this + */ + public function setRounds($rounds) + { + $this->rounds = (int) $rounds; + + return $this; + } + + /** + * Extract the cost value from the options array. + * + * @param array $options + * @return int + */ + protected function cost(array $options = []) + { + return $options['rounds'] ?? $this->rounds; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/HashManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/HashManager.php new file mode 100644 index 0000000..977ef22 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/HashManager.php @@ -0,0 +1,97 @@ +config->get('hashing.bcrypt') ?? []); + } + + /** + * Create an instance of the Argon2i hash Driver. + * + * @return \Illuminate\Hashing\ArgonHasher + */ + public function createArgonDriver() + { + return new ArgonHasher($this->config->get('hashing.argon') ?? []); + } + + /** + * Create an instance of the Argon2id hash Driver. + * + * @return \Illuminate\Hashing\Argon2IdHasher + */ + public function createArgon2idDriver() + { + return new Argon2IdHasher($this->config->get('hashing.argon') ?? []); + } + + /** + * Get information about the given hashed value. + * + * @param string $hashedValue + * @return array + */ + public function info($hashedValue) + { + return $this->driver()->info($hashedValue); + } + + /** + * Hash the given value. + * + * @param string $value + * @param array $options + * @return string + */ + public function make($value, array $options = []) + { + return $this->driver()->make($value, $options); + } + + /** + * Check the given plain value against a hash. + * + * @param string $value + * @param string $hashedValue + * @param array $options + * @return bool + */ + public function check($value, $hashedValue, array $options = []) + { + return $this->driver()->check($value, $hashedValue, $options); + } + + /** + * Check if the given hash has been hashed using the given options. + * + * @param string $hashedValue + * @param array $options + * @return bool + */ + public function needsRehash($hashedValue, array $options = []) + { + return $this->driver()->needsRehash($hashedValue, $options); + } + + /** + * Get the default driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->config->get('hashing.driver', 'bcrypt'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/HashServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/HashServiceProvider.php new file mode 100755 index 0000000..2ed56a4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/HashServiceProvider.php @@ -0,0 +1,35 @@ +app->singleton('hash', function ($app) { + return new HashManager($app); + }); + + $this->app->singleton('hash.driver', function ($app) { + return $app['hash']->driver(); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['hash', 'hash.driver']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/composer.json new file mode 100755 index 0000000..6ad3411 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Hashing/composer.json @@ -0,0 +1,35 @@ +{ + "name": "illuminate/hashing", + "description": "The Illuminate Hashing package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/contracts": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Hashing\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/ConnectionException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/ConnectionException.php new file mode 100644 index 0000000..eac85dc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/ConnectionException.php @@ -0,0 +1,8 @@ +request = $request; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Events/RequestSending.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Events/RequestSending.php new file mode 100644 index 0000000..1b363fb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Events/RequestSending.php @@ -0,0 +1,26 @@ +request = $request; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Events/ResponseReceived.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Events/ResponseReceived.php new file mode 100644 index 0000000..77be7ab --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Events/ResponseReceived.php @@ -0,0 +1,36 @@ +request = $request; + $this->response = $response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Factory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Factory.php new file mode 100644 index 0000000..131e669 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Factory.php @@ -0,0 +1,394 @@ +dispatcher = $dispatcher; + + $this->stubCallbacks = collect(); + } + + /** + * Create a new response instance for use during stubbing. + * + * @param array|string $body + * @param int $status + * @param array $headers + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public static function response($body = null, $status = 200, $headers = []) + { + if (is_array($body)) { + $body = json_encode($body); + + $headers['Content-Type'] = 'application/json'; + } + + $response = new Psr7Response($status, $headers, $body); + + return class_exists(\GuzzleHttp\Promise\Create::class) + ? \GuzzleHttp\Promise\Create::promiseFor($response) + : \GuzzleHttp\Promise\promise_for($response); + } + + /** + * Get an invokable object that returns a sequence of responses in order for use during stubbing. + * + * @param array $responses + * @return \Illuminate\Http\Client\ResponseSequence + */ + public function sequence(array $responses = []) + { + return $this->responseSequences[] = new ResponseSequence($responses); + } + + /** + * Register a stub callable that will intercept requests and be able to return stub responses. + * + * @param callable|array $callback + * @return $this + */ + public function fake($callback = null) + { + $this->record(); + + $this->recorded = []; + + if (is_null($callback)) { + $callback = function () { + return static::response(); + }; + } + + if (is_array($callback)) { + foreach ($callback as $url => $callable) { + $this->stubUrl($url, $callable); + } + + return $this; + } + + $this->stubCallbacks = $this->stubCallbacks->merge(collect([ + function ($request, $options) use ($callback) { + $response = $callback instanceof Closure + ? $callback($request, $options) + : $callback; + + if ($response instanceof PromiseInterface) { + $options['on_stats'](new TransferStats( + $request->toPsrRequest(), + $response->wait(), + )); + } + + return $response; + }, + ])); + + return $this; + } + + /** + * Register a response sequence for the given URL pattern. + * + * @param string $url + * @return \Illuminate\Http\Client\ResponseSequence + */ + public function fakeSequence($url = '*') + { + return tap($this->sequence(), function ($sequence) use ($url) { + $this->fake([$url => $sequence]); + }); + } + + /** + * Stub the given URL using the given callback. + * + * @param string $url + * @param \Illuminate\Http\Client\Response|\GuzzleHttp\Promise\PromiseInterface|callable $callback + * @return $this + */ + public function stubUrl($url, $callback) + { + return $this->fake(function ($request, $options) use ($url, $callback) { + if (! Str::is(Str::start($url, '*'), $request->url())) { + return; + } + + return $callback instanceof Closure || $callback instanceof ResponseSequence + ? $callback($request, $options) + : $callback; + }); + } + + /** + * Begin recording request / response pairs. + * + * @return $this + */ + protected function record() + { + $this->recording = true; + + return $this; + } + + /** + * Record a request response pair. + * + * @param \Illuminate\Http\Client\Request $request + * @param \Illuminate\Http\Client\Response $response + * @return void + */ + public function recordRequestResponsePair($request, $response) + { + if ($this->recording) { + $this->recorded[] = [$request, $response]; + } + } + + /** + * Assert that a request / response pair was recorded matching a given truth test. + * + * @param callable $callback + * @return void + */ + public function assertSent($callback) + { + PHPUnit::assertTrue( + $this->recorded($callback)->count() > 0, + 'An expected request was not recorded.' + ); + } + + /** + * Assert that the given request was sent in the given order. + * + * @param array $callbacks + * @return void + */ + public function assertSentInOrder($callbacks) + { + $this->assertSentCount(count($callbacks)); + + foreach ($callbacks as $index => $url) { + $callback = is_callable($url) ? $url : function ($request) use ($url) { + return $request->url() == $url; + }; + + PHPUnit::assertTrue($callback( + $this->recorded[$index][0], + $this->recorded[$index][1] + ), 'An expected request (#'.($index + 1).') was not recorded.'); + } + } + + /** + * Assert that a request / response pair was not recorded matching a given truth test. + * + * @param callable $callback + * @return void + */ + public function assertNotSent($callback) + { + PHPUnit::assertFalse( + $this->recorded($callback)->count() > 0, + 'Unexpected request was recorded.' + ); + } + + /** + * Assert that no request / response pair was recorded. + * + * @return void + */ + public function assertNothingSent() + { + PHPUnit::assertEmpty( + $this->recorded, + 'Requests were recorded.' + ); + } + + /** + * Assert how many requests have been recorded. + * + * @param int $count + * @return void + */ + public function assertSentCount($count) + { + PHPUnit::assertCount($count, $this->recorded); + } + + /** + * Assert that every created response sequence is empty. + * + * @return void + */ + public function assertSequencesAreEmpty() + { + foreach ($this->responseSequences as $responseSequence) { + PHPUnit::assertTrue( + $responseSequence->isEmpty(), + 'Not all response sequences are empty.' + ); + } + } + + /** + * Get a collection of the request / response pairs matching the given truth test. + * + * @param callable $callback + * @return \Illuminate\Support\Collection + */ + public function recorded($callback = null) + { + if (empty($this->recorded)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return collect($this->recorded)->filter(function ($pair) use ($callback) { + return $callback($pair[0], $pair[1]); + }); + } + + /** + * Create a new pending request instance for this factory. + * + * @return \Illuminate\Http\Client\PendingRequest + */ + protected function newPendingRequest() + { + return new PendingRequest($this); + } + + /** + * Get the current event dispatcher implementation. + * + * @return \Illuminate\Contracts\Events\Dispatcher|null + */ + public function getDispatcher() + { + return $this->dispatcher; + } + + /** + * Execute a method against a new pending request instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + return tap($this->newPendingRequest(), function ($request) { + $request->stub($this->stubCallbacks); + })->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/HttpClientException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/HttpClientException.php new file mode 100644 index 0000000..b15b8d3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/HttpClientException.php @@ -0,0 +1,10 @@ +factory = $factory; + $this->middleware = new Collection; + + $this->asJson(); + + $this->options = [ + 'http_errors' => false, + ]; + + $this->beforeSendingCallbacks = collect([function (Request $request, array $options, PendingRequest $pendingRequest) { + $pendingRequest->request = $request; + $pendingRequest->cookies = $options['cookies']; + + $pendingRequest->dispatchRequestSendingEvent(); + }]); + } + + /** + * Set the base URL for the pending request. + * + * @param string $url + * @return $this + */ + public function baseUrl(string $url) + { + $this->baseUrl = $url; + + return $this; + } + + /** + * Attach a raw body to the request. + * + * @param string $content + * @param string $contentType + * @return $this + */ + public function withBody($content, $contentType) + { + $this->bodyFormat('body'); + + $this->pendingBody = $content; + + $this->contentType($contentType); + + return $this; + } + + /** + * Indicate the request contains JSON. + * + * @return $this + */ + public function asJson() + { + return $this->bodyFormat('json')->contentType('application/json'); + } + + /** + * Indicate the request contains form parameters. + * + * @return $this + */ + public function asForm() + { + return $this->bodyFormat('form_params')->contentType('application/x-www-form-urlencoded'); + } + + /** + * Attach a file to the request. + * + * @param string|array $name + * @param string|resource $contents + * @param string|null $filename + * @param array $headers + * @return $this + */ + public function attach($name, $contents = '', $filename = null, array $headers = []) + { + if (is_array($name)) { + foreach ($name as $file) { + $this->attach(...$file); + } + + return $this; + } + + $this->asMultipart(); + + $this->pendingFiles[] = array_filter([ + 'name' => $name, + 'contents' => $contents, + 'headers' => $headers, + 'filename' => $filename, + ]); + + return $this; + } + + /** + * Indicate the request is a multi-part form request. + * + * @return $this + */ + public function asMultipart() + { + return $this->bodyFormat('multipart'); + } + + /** + * Specify the body format of the request. + * + * @param string $format + * @return $this + */ + public function bodyFormat(string $format) + { + return tap($this, function ($request) use ($format) { + $this->bodyFormat = $format; + }); + } + + /** + * Specify the request's content type. + * + * @param string $contentType + * @return $this + */ + public function contentType(string $contentType) + { + return $this->withHeaders(['Content-Type' => $contentType]); + } + + /** + * Indicate that JSON should be returned by the server. + * + * @return $this + */ + public function acceptJson() + { + return $this->accept('application/json'); + } + + /** + * Indicate the type of content that should be returned by the server. + * + * @param string $contentType + * @return $this + */ + public function accept($contentType) + { + return $this->withHeaders(['Accept' => $contentType]); + } + + /** + * Add the given headers to the request. + * + * @param array $headers + * @return $this + */ + public function withHeaders(array $headers) + { + return tap($this, function ($request) use ($headers) { + return $this->options = array_merge_recursive($this->options, [ + 'headers' => $headers, + ]); + }); + } + + /** + * Specify the basic authentication username and password for the request. + * + * @param string $username + * @param string $password + * @return $this + */ + public function withBasicAuth(string $username, string $password) + { + return tap($this, function ($request) use ($username, $password) { + return $this->options['auth'] = [$username, $password]; + }); + } + + /** + * Specify the digest authentication username and password for the request. + * + * @param string $username + * @param string $password + * @return $this + */ + public function withDigestAuth($username, $password) + { + return tap($this, function ($request) use ($username, $password) { + return $this->options['auth'] = [$username, $password, 'digest']; + }); + } + + /** + * Specify an authorization token for the request. + * + * @param string $token + * @param string $type + * @return $this + */ + public function withToken($token, $type = 'Bearer') + { + return tap($this, function ($request) use ($token, $type) { + return $this->options['headers']['Authorization'] = trim($type.' '.$token); + }); + } + + /** + * Specify the user agent for the request. + * + * @param string $userAgent + * @return $this + */ + public function withUserAgent($userAgent) + { + return tap($this, function ($request) use ($userAgent) { + return $this->options['headers']['User-Agent'] = trim($userAgent); + }); + } + + /** + * Specify the cookies that should be included with the request. + * + * @param array $cookies + * @param string $domain + * @return $this + */ + public function withCookies(array $cookies, string $domain) + { + return tap($this, function ($request) use ($cookies, $domain) { + return $this->options = array_merge_recursive($this->options, [ + 'cookies' => CookieJar::fromArray($cookies, $domain), + ]); + }); + } + + /** + * Indicate that redirects should not be followed. + * + * @return $this + */ + public function withoutRedirecting() + { + return tap($this, function ($request) { + return $this->options['allow_redirects'] = false; + }); + } + + /** + * Indicate that TLS certificates should not be verified. + * + * @return $this + */ + public function withoutVerifying() + { + return tap($this, function ($request) { + return $this->options['verify'] = false; + }); + } + + /** + * Specify the path where the body of the response should be stored. + * + * @param string|resource $to + * @return $this + */ + public function sink($to) + { + return tap($this, function ($request) use ($to) { + return $this->options['sink'] = $to; + }); + } + + /** + * Specify the timeout (in seconds) for the request. + * + * @param int $seconds + * @return $this + */ + public function timeout(int $seconds) + { + return tap($this, function () use ($seconds) { + $this->options['timeout'] = $seconds; + }); + } + + /** + * Specify the number of times the request should be attempted. + * + * @param int $times + * @param int $sleep + * @param callable|null $when + * @return $this + */ + public function retry(int $times, int $sleep = 0, ?callable $when = null) + { + $this->tries = $times; + $this->retryDelay = $sleep; + $this->retryWhenCallback = $when; + + return $this; + } + + /** + * Replace the specified options on the request. + * + * @param array $options + * @return $this + */ + public function withOptions(array $options) + { + return tap($this, function ($request) use ($options) { + return $this->options = array_replace_recursive( + array_merge_recursive($this->options, Arr::only($options, $this->mergableOptions)), + $options + ); + }); + } + + /** + * Add new middleware the client handler stack. + * + * @param callable $middleware + * @return $this + */ + public function withMiddleware(callable $middleware) + { + $this->middleware->push($middleware); + + return $this; + } + + /** + * Add a new "before sending" callback to the request. + * + * @param callable $callback + * @return $this + */ + public function beforeSending($callback) + { + return tap($this, function () use ($callback) { + $this->beforeSendingCallbacks[] = $callback; + }); + } + + /** + * Dump the request before sending. + * + * @return $this + */ + public function dump() + { + $values = func_get_args(); + + return $this->beforeSending(function (Request $request, array $options) use ($values) { + foreach (array_merge($values, [$request, $options]) as $value) { + VarDumper::dump($value); + } + }); + } + + /** + * Dump the request before sending and end the script. + * + * @return $this + */ + public function dd() + { + $values = func_get_args(); + + return $this->beforeSending(function (Request $request, array $options) use ($values) { + foreach (array_merge($values, [$request, $options]) as $value) { + VarDumper::dump($value); + } + + exit(1); + }); + } + + /** + * Issue a GET request to the given URL. + * + * @param string $url + * @param array|string|null $query + * @return \Illuminate\Http\Client\Response + */ + public function get(string $url, $query = null) + { + return $this->send('GET', $url, func_num_args() === 1 ? [] : [ + 'query' => $query, + ]); + } + + /** + * Issue a HEAD request to the given URL. + * + * @param string $url + * @param array|string|null $query + * @return \Illuminate\Http\Client\Response + */ + public function head(string $url, $query = null) + { + return $this->send('HEAD', $url, func_num_args() === 1 ? [] : [ + 'query' => $query, + ]); + } + + /** + * Issue a POST request to the given URL. + * + * @param string $url + * @param array $data + * @return \Illuminate\Http\Client\Response + */ + public function post(string $url, array $data = []) + { + return $this->send('POST', $url, [ + $this->bodyFormat => $data, + ]); + } + + /** + * Issue a PATCH request to the given URL. + * + * @param string $url + * @param array $data + * @return \Illuminate\Http\Client\Response + */ + public function patch($url, $data = []) + { + return $this->send('PATCH', $url, [ + $this->bodyFormat => $data, + ]); + } + + /** + * Issue a PUT request to the given URL. + * + * @param string $url + * @param array $data + * @return \Illuminate\Http\Client\Response + */ + public function put($url, $data = []) + { + return $this->send('PUT', $url, [ + $this->bodyFormat => $data, + ]); + } + + /** + * Issue a DELETE request to the given URL. + * + * @param string $url + * @param array $data + * @return \Illuminate\Http\Client\Response + */ + public function delete($url, $data = []) + { + return $this->send('DELETE', $url, empty($data) ? [] : [ + $this->bodyFormat => $data, + ]); + } + + /** + * Send a pool of asynchronous requests concurrently. + * + * @param callable $callback + * @return array + */ + public function pool(callable $callback) + { + $results = []; + + $requests = tap(new Pool($this->factory), $callback)->getRequests(); + + foreach ($requests as $key => $item) { + $results[$key] = $item instanceof static ? $item->getPromise()->wait() : $item->wait(); + } + + return $results; + } + + /** + * Send the request to the given URL. + * + * @param string $method + * @param string $url + * @param array $options + * @return \Illuminate\Http\Client\Response + * + * @throws \Exception + */ + public function send(string $method, string $url, array $options = []) + { + $url = ltrim(rtrim($this->baseUrl, '/').'/'.ltrim($url, '/'), '/'); + + if (isset($options[$this->bodyFormat])) { + if ($this->bodyFormat === 'multipart') { + $options[$this->bodyFormat] = $this->parseMultipartBodyFormat($options[$this->bodyFormat]); + } elseif ($this->bodyFormat === 'body') { + $options[$this->bodyFormat] = $this->pendingBody; + } + + if (is_array($options[$this->bodyFormat])) { + $options[$this->bodyFormat] = array_merge( + $options[$this->bodyFormat], $this->pendingFiles + ); + } + } else { + $options[$this->bodyFormat] = $this->pendingBody; + } + + [$this->pendingBody, $this->pendingFiles] = [null, []]; + + if ($this->async) { + return $this->makePromise($method, $url, $options); + } + + return retry($this->tries ?? 1, function () use ($method, $url, $options) { + try { + return tap(new Response($this->sendRequest($method, $url, $options)), function ($response) { + $this->populateResponse($response); + + if ($this->tries > 1 && ! $response->successful()) { + $response->throw(); + } + + $this->dispatchResponseReceivedEvent($response); + }); + } catch (ConnectException $e) { + $this->dispatchConnectionFailedEvent(); + + throw new ConnectionException($e->getMessage(), 0, $e); + } + }, $this->retryDelay ?? 100, $this->retryWhenCallback); + } + + /** + * Parse multi-part form data. + * + * @param array $data + * @return array|array[] + */ + protected function parseMultipartBodyFormat(array $data) + { + return collect($data)->map(function ($value, $key) { + return is_array($value) ? $value : ['name' => $key, 'contents' => $value]; + })->values()->all(); + } + + /** + * Send an asynchronous request to the given URL. + * + * @param string $method + * @param string $url + * @param array $options + * @return \GuzzleHttp\Promise\PromiseInterface + */ + protected function makePromise(string $method, string $url, array $options = []) + { + return $this->promise = $this->sendRequest($method, $url, $options) + ->then(function (MessageInterface $message) { + return tap(new Response($message), function ($response) { + $this->populateResponse($response); + $this->dispatchResponseReceivedEvent($response); + }); + }) + ->otherwise(function (TransferException $e) { + return $e instanceof RequestException ? $this->populateResponse(new Response($e->getResponse())) : $e; + }); + } + + /** + * Send a request either synchronously or asynchronously. + * + * @param string $method + * @param string $url + * @param array $options + * @return \Psr\Http\Message\MessageInterface|\GuzzleHttp\Promise\PromiseInterface + * + * @throws \Exception + */ + protected function sendRequest(string $method, string $url, array $options = []) + { + $clientMethod = $this->async ? 'requestAsync' : 'request'; + + $laravelData = $this->parseRequestData($method, $url, $options); + + return $this->buildClient()->$clientMethod($method, $url, $this->mergeOptions([ + 'laravel_data' => $laravelData, + 'on_stats' => function ($transferStats) { + $this->transferStats = $transferStats; + }, + ], $options)); + } + + /** + * Get the request data as an array so that we can attach it to the request for convenient assertions. + * + * @param string $method + * @param string $url + * @param array $options + * @return array + */ + protected function parseRequestData($method, $url, array $options) + { + $laravelData = $options[$this->bodyFormat] ?? $options['query'] ?? []; + + $urlString = Str::of($url); + + if (empty($laravelData) && $method === 'GET' && $urlString->contains('?')) { + $laravelData = (string) $urlString->after('?'); + } + + if (is_string($laravelData)) { + parse_str($laravelData, $parsedData); + + $laravelData = is_array($parsedData) ? $parsedData : []; + } + + return $laravelData; + } + + /** + * Populate the given response with additional data. + * + * @param \Illuminate\Http\Client\Response $response + * @return \Illuminate\Http\Client\Response + */ + protected function populateResponse(Response $response) + { + $response->cookies = $this->cookies; + + $response->transferStats = $this->transferStats; + + return $response; + } + + /** + * Build the Guzzle client. + * + * @return \GuzzleHttp\Client + */ + public function buildClient() + { + return $this->requestsReusableClient() + ? $this->getReusableClient() + : $this->createClient($this->buildHandlerStack()); + } + + /** + * Determine if a reusable client is required. + * + * @return bool + */ + protected function requestsReusableClient() + { + return ! is_null($this->client) || $this->async; + } + + /** + * Retrieve a reusable Guzzle client. + * + * @return \GuzzleHttp\Client + */ + protected function getReusableClient() + { + return $this->client = $this->client ?: $this->createClient($this->buildHandlerStack()); + } + + /** + * Create new Guzzle client. + * + * @param \GuzzleHttp\HandlerStack $handlerStack + * @return \GuzzleHttp\Client + */ + public function createClient($handlerStack) + { + return new Client([ + 'handler' => $handlerStack, + 'cookies' => true, + ]); + } + + /** + * Build the Guzzle client handler stack. + * + * @return \GuzzleHttp\HandlerStack + */ + public function buildHandlerStack() + { + return $this->pushHandlers(HandlerStack::create()); + } + + /** + * Add the necessary handlers to the given handler stack. + * + * @param \GuzzleHttp\HandlerStack $handlerStack + * @return \GuzzleHttp\HandlerStack + */ + public function pushHandlers($handlerStack) + { + return tap($handlerStack, function ($stack) { + $stack->push($this->buildBeforeSendingHandler()); + $stack->push($this->buildRecorderHandler()); + $stack->push($this->buildStubHandler()); + + $this->middleware->each(function ($middleware) use ($stack) { + $stack->push($middleware); + }); + }); + } + + /** + * Build the before sending handler. + * + * @return \Closure + */ + public function buildBeforeSendingHandler() + { + return function ($handler) { + return function ($request, $options) use ($handler) { + return $handler($this->runBeforeSendingCallbacks($request, $options), $options); + }; + }; + } + + /** + * Build the recorder handler. + * + * @return \Closure + */ + public function buildRecorderHandler() + { + return function ($handler) { + return function ($request, $options) use ($handler) { + $promise = $handler($request, $options); + + return $promise->then(function ($response) use ($request, $options) { + optional($this->factory)->recordRequestResponsePair( + (new Request($request))->withData($options['laravel_data']), + new Response($response) + ); + + return $response; + }); + }; + }; + } + + /** + * Build the stub handler. + * + * @return \Closure + */ + public function buildStubHandler() + { + return function ($handler) { + return function ($request, $options) use ($handler) { + $response = ($this->stubCallbacks ?? collect()) + ->map + ->__invoke((new Request($request))->withData($options['laravel_data']), $options) + ->filter() + ->first(); + + if (is_null($response)) { + return $handler($request, $options); + } + + $response = is_array($response) ? Factory::response($response) : $response; + + $sink = $options['sink'] ?? null; + + if ($sink) { + $response->then($this->sinkStubHandler($sink)); + } + + return $response; + }; + }; + } + + /** + * Get the sink stub handler callback. + * + * @param string $sink + * @return \Closure + */ + protected function sinkStubHandler($sink) + { + return function ($response) use ($sink) { + $body = $response->getBody()->getContents(); + + if (is_string($sink)) { + file_put_contents($sink, $body); + + return; + } + + fwrite($sink, $body); + rewind($sink); + }; + } + + /** + * Execute the "before sending" callbacks. + * + * @param \GuzzleHttp\Psr7\RequestInterface $request + * @param array $options + * @return \GuzzleHttp\Psr7\RequestInterface + */ + public function runBeforeSendingCallbacks($request, array $options) + { + return tap($request, function (&$request) use ($options) { + $this->beforeSendingCallbacks->each(function ($callback) use (&$request, $options) { + $callbackResult = call_user_func( + $callback, (new Request($request))->withData($options['laravel_data']), $options, $this + ); + + if ($callbackResult instanceof RequestInterface) { + $request = $callbackResult; + } elseif ($callbackResult instanceof Request) { + $request = $callbackResult->toPsrRequest(); + } + }); + }); + } + + /** + * Replace the given options with the current request options. + * + * @param array $options + * @return array + */ + public function mergeOptions(...$options) + { + return array_replace_recursive( + array_merge_recursive($this->options, Arr::only($options, $this->mergableOptions)), + ...$options + ); + } + + /** + * Register a stub callable that will intercept requests and be able to return stub responses. + * + * @param callable $callback + * @return $this + */ + public function stub($callback) + { + $this->stubCallbacks = collect($callback); + + return $this; + } + + /** + * Toggle asynchronicity in requests. + * + * @param bool $async + * @return $this + */ + public function async(bool $async = true) + { + $this->async = $async; + + return $this; + } + + /** + * Retrieve the pending request promise. + * + * @return \GuzzleHttp\Promise\PromiseInterface|null + */ + public function getPromise() + { + return $this->promise; + } + + /** + * Dispatch the RequestSending event if a dispatcher is available. + * + * @return void + */ + protected function dispatchRequestSendingEvent() + { + if ($dispatcher = optional($this->factory)->getDispatcher()) { + $dispatcher->dispatch(new RequestSending($this->request)); + } + } + + /** + * Dispatch the ResponseReceived event if a dispatcher is available. + * + * @param \Illuminate\Http\Client\Response $response + * @return void + */ + protected function dispatchResponseReceivedEvent(Response $response) + { + if (! ($dispatcher = optional($this->factory)->getDispatcher()) || + ! $this->request) { + return; + } + + $dispatcher->dispatch(new ResponseReceived($this->request, $response)); + } + + /** + * Dispatch the ConnectionFailed event if a dispatcher is available. + * + * @return void + */ + protected function dispatchConnectionFailedEvent() + { + if ($dispatcher = optional($this->factory)->getDispatcher()) { + $dispatcher->dispatch(new ConnectionFailed($this->request)); + } + } + + /** + * Set the client instance. + * + * @param \GuzzleHttp\Client $client + * @return $this + */ + public function setClient(Client $client) + { + $this->client = $client; + + return $this; + } + + /** + * Create a new client instance using the given handler. + * + * @param callable $handler + * @return $this + */ + public function setHandler($handler) + { + $this->client = $this->createClient( + $this->pushHandlers(HandlerStack::create($handler)) + ); + + return $this; + } + + /** + * Get the pending request options. + * + * @return array + */ + public function getOptions() + { + return $this->options; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Pool.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Pool.php new file mode 100644 index 0000000..bedffcb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Pool.php @@ -0,0 +1,92 @@ +factory = $factory ?: new Factory(); + + if (method_exists(Utils::class, 'chooseHandler')) { + $this->handler = Utils::chooseHandler(); + } else { + $this->handler = \GuzzleHttp\choose_handler(); + } + } + + /** + * Add a request to the pool with a key. + * + * @param string $key + * @return \Illuminate\Http\Client\PendingRequest + */ + public function as(string $key) + { + return $this->pool[$key] = $this->asyncRequest(); + } + + /** + * Retrieve a new async pending request. + * + * @return \Illuminate\Http\Client\PendingRequest + */ + protected function asyncRequest() + { + return $this->factory->setHandler($this->handler)->async(); + } + + /** + * Retrieve the requests in the pool. + * + * @return array + */ + public function getRequests() + { + return $this->pool; + } + + /** + * Add a request to the pool with a numeric index. + * + * @param string $method + * @param array $parameters + * @return \Illuminate\Http\Client\PendingRequest + */ + public function __call($method, $parameters) + { + return $this->pool[] = $this->asyncRequest()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Request.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Request.php new file mode 100644 index 0000000..0e493f1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Request.php @@ -0,0 +1,310 @@ +request = $request; + } + + /** + * Get the request method. + * + * @return string + */ + public function method() + { + return $this->request->getMethod(); + } + + /** + * Get the URL of the request. + * + * @return string + */ + public function url() + { + return (string) $this->request->getUri(); + } + + /** + * Determine if the request has a given header. + * + * @param string $key + * @param mixed $value + * @return bool + */ + public function hasHeader($key, $value = null) + { + if (is_null($value)) { + return ! empty($this->request->getHeaders()[$key]); + } + + $headers = $this->headers(); + + if (! Arr::has($headers, $key)) { + return false; + } + + $value = is_array($value) ? $value : [$value]; + + return empty(array_diff($value, $headers[$key])); + } + + /** + * Determine if the request has the given headers. + * + * @param array|string $headers + * @return bool + */ + public function hasHeaders($headers) + { + if (is_string($headers)) { + $headers = [$headers => null]; + } + + foreach ($headers as $key => $value) { + if (! $this->hasHeader($key, $value)) { + return false; + } + } + + return true; + } + + /** + * Get the values for the header with the given name. + * + * @param string $key + * @return array + */ + public function header($key) + { + return Arr::get($this->headers(), $key, []); + } + + /** + * Get the request headers. + * + * @return array + */ + public function headers() + { + return $this->request->getHeaders(); + } + + /** + * Get the body of the request. + * + * @return string + */ + public function body() + { + return (string) $this->request->getBody(); + } + + /** + * Determine if the request contains the given file. + * + * @param string $name + * @param string|null $value + * @param string|null $filename + * @return bool + */ + public function hasFile($name, $value = null, $filename = null) + { + if (! $this->isMultipart()) { + return false; + } + + return collect($this->data)->reject(function ($file) use ($name, $value, $filename) { + return $file['name'] != $name || + ($value && $file['contents'] != $value) || + ($filename && $file['filename'] != $filename); + })->count() > 0; + } + + /** + * Get the request's data (form parameters or JSON). + * + * @return array + */ + public function data() + { + if ($this->isForm()) { + return $this->parameters(); + } elseif ($this->isJson()) { + return $this->json(); + } + + return $this->data ?? []; + } + + /** + * Get the request's form parameters. + * + * @return array + */ + protected function parameters() + { + if (! $this->data) { + parse_str($this->body(), $parameters); + + $this->data = $parameters; + } + + return $this->data; + } + + /** + * Get the JSON decoded body of the request. + * + * @return array + */ + protected function json() + { + if (! $this->data) { + $this->data = json_decode($this->body(), true); + } + + return $this->data; + } + + /** + * Determine if the request is simple form data. + * + * @return bool + */ + public function isForm() + { + return $this->hasHeader('Content-Type', 'application/x-www-form-urlencoded'); + } + + /** + * Determine if the request is JSON. + * + * @return bool + */ + public function isJson() + { + return $this->hasHeader('Content-Type') && + Str::contains($this->header('Content-Type')[0], 'json'); + } + + /** + * Determine if the request is multipart. + * + * @return bool + */ + public function isMultipart() + { + return $this->hasHeader('Content-Type') && + Str::contains($this->header('Content-Type')[0], 'multipart'); + } + + /** + * Set the decoded data on the request. + * + * @param array $data + * @return $this + */ + public function withData(array $data) + { + $this->data = $data; + + return $this; + } + + /** + * Get the underlying PSR compliant request instance. + * + * @return \Psr\Http\Message\RequestInterface + */ + public function toPsrRequest() + { + return $this->request; + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return isset($this->data()[$offset]); + } + + /** + * Get the value for a given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->data()[$offset]; + } + + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + * + * @throws \LogicException + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + throw new LogicException('Request data may not be mutated using array access.'); + } + + /** + * Unset the value at the given offset. + * + * @param string $offset + * @return void + * + * @throws \LogicException + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + throw new LogicException('Request data may not be mutated using array access.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/RequestException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/RequestException.php new file mode 100644 index 0000000..fa4f418 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/RequestException.php @@ -0,0 +1,43 @@ +prepareMessage($response), $response->status()); + + $this->response = $response; + } + + /** + * Prepare the exception message. + * + * @param \Illuminate\Http\Client\Response $response + * @return string + */ + protected function prepareMessage(Response $response) + { + $message = "HTTP request returned status code {$response->status()}"; + + $summary = class_exists(\GuzzleHttp\Psr7\Message::class) + ? \GuzzleHttp\Psr7\Message::bodySummary($response->toPsrResponse()) + : \GuzzleHttp\Psr7\get_message_body_summary($response->toPsrResponse()); + + return is_null($summary) ? $message : $message .= ":\n{$summary}\n"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Response.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Response.php new file mode 100644 index 0000000..703b357 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/Response.php @@ -0,0 +1,404 @@ +response = $response; + } + + /** + * Get the body of the response. + * + * @return string + */ + public function body() + { + return (string) $this->response->getBody(); + } + + /** + * Get the JSON decoded body of the response as an array or scalar value. + * + * @param string|null $key + * @param mixed $default + * @return mixed + */ + public function json($key = null, $default = null) + { + if (! $this->decoded) { + $this->decoded = json_decode($this->body(), true); + } + + if (is_null($key)) { + return $this->decoded; + } + + return data_get($this->decoded, $key, $default); + } + + /** + * Get the JSON decoded body of the response as an object. + * + * @return object + */ + public function object() + { + return json_decode($this->body(), false); + } + + /** + * Get the JSON decoded body of the response as a collection. + * + * @param string|null $key + * @return \Illuminate\Support\Collection + */ + public function collect($key = null) + { + return Collection::make($this->json($key)); + } + + /** + * Get a header from the response. + * + * @param string $header + * @return string + */ + public function header(string $header) + { + return $this->response->getHeaderLine($header); + } + + /** + * Get the headers from the response. + * + * @return array + */ + public function headers() + { + return $this->response->getHeaders(); + } + + /** + * Get the status code of the response. + * + * @return int + */ + public function status() + { + return (int) $this->response->getStatusCode(); + } + + /** + * Get the reason phrase of the response. + * + * @return string + */ + public function reason() + { + return $this->response->getReasonPhrase(); + } + + /** + * Get the effective URI of the response. + * + * @return \Psr\Http\Message\UriInterface|null + */ + public function effectiveUri() + { + return optional($this->transferStats)->getEffectiveUri(); + } + + /** + * Determine if the request was successful. + * + * @return bool + */ + public function successful() + { + return $this->status() >= 200 && $this->status() < 300; + } + + /** + * Determine if the response code was "OK". + * + * @return bool + */ + public function ok() + { + return $this->status() === 200; + } + + /** + * Determine if the response was a redirect. + * + * @return bool + */ + public function redirect() + { + return $this->status() >= 300 && $this->status() < 400; + } + + /** + * Determine if the response was a 401 "Unauthorized" response. + * + * @return bool + */ + public function unauthorized() + { + return $this->status() === 401; + } + + /** + * Determine if the response was a 403 "Forbidden" response. + * + * @return bool + */ + public function forbidden() + { + return $this->status() === 403; + } + + /** + * Determine if the response indicates a client or server error occurred. + * + * @return bool + */ + public function failed() + { + return $this->serverError() || $this->clientError(); + } + + /** + * Determine if the response indicates a client error occurred. + * + * @return bool + */ + public function clientError() + { + return $this->status() >= 400 && $this->status() < 500; + } + + /** + * Determine if the response indicates a server error occurred. + * + * @return bool + */ + public function serverError() + { + return $this->status() >= 500; + } + + /** + * Execute the given callback if there was a server or client error. + * + * @param callable $callback + * @return $this + */ + public function onError(callable $callback) + { + if ($this->failed()) { + $callback($this); + } + + return $this; + } + + /** + * Get the response cookies. + * + * @return \GuzzleHttp\Cookie\CookieJar + */ + public function cookies() + { + return $this->cookies; + } + + /** + * Get the handler stats of the response. + * + * @return array + */ + public function handlerStats() + { + return optional($this->transferStats)->getHandlerStats() ?? []; + } + + /** + * Close the stream and any underlying resources. + * + * @return $this + */ + public function close() + { + $this->response->getBody()->close(); + + return $this; + } + + /** + * Get the underlying PSR response for the response. + * + * @return \Psr\Http\Message\ResponseInterface + */ + public function toPsrResponse() + { + return $this->response; + } + + /** + * Create an exception if a server or client error occurred. + * + * @return \Illuminate\Http\Client\RequestException|null + */ + public function toException() + { + if ($this->failed()) { + return new RequestException($this); + } + } + + /** + * Throw an exception if a server or client error occurred. + * + * @param \Closure|null $callback + * @return $this + * + * @throws \Illuminate\Http\Client\RequestException + */ + public function throw() + { + $callback = func_get_args()[0] ?? null; + + if ($this->failed()) { + throw tap($this->toException(), function ($exception) use ($callback) { + if ($callback && is_callable($callback)) { + $callback($this, $exception); + } + }); + } + + return $this; + } + + /** + * Throw an exception if a server or client error occurred and the given condition evaluates to true. + * + * @param bool $condition + * @return $this + * + * @throws \Illuminate\Http\Client\RequestException + */ + public function throwIf($condition) + { + return $condition ? $this->throw() : $this; + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return isset($this->json()[$offset]); + } + + /** + * Get the value for a given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->json()[$offset]; + } + + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + * + * @throws \LogicException + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + throw new LogicException('Response data may not be mutated using array access.'); + } + + /** + * Unset the value at the given offset. + * + * @param string $offset + * @return void + * + * @throws \LogicException + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + throw new LogicException('Response data may not be mutated using array access.'); + } + + /** + * Get the body of the response. + * + * @return string + */ + public function __toString() + { + return $this->body(); + } + + /** + * Dynamically proxy other methods to the underlying response. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return static::hasMacro($method) + ? $this->macroCall($method, $parameters) + : $this->response->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/ResponseSequence.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/ResponseSequence.php new file mode 100644 index 0000000..dcf8633 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Client/ResponseSequence.php @@ -0,0 +1,158 @@ +responses = $responses; + } + + /** + * Push a response to the sequence. + * + * @param string|array $body + * @param int $status + * @param array $headers + * @return $this + */ + public function push($body = '', int $status = 200, array $headers = []) + { + $body = is_array($body) ? json_encode($body) : $body; + + return $this->pushResponse( + Factory::response($body, $status, $headers) + ); + } + + /** + * Push a response with the given status code to the sequence. + * + * @param int $status + * @param array $headers + * @return $this + */ + public function pushStatus(int $status, array $headers = []) + { + return $this->pushResponse( + Factory::response('', $status, $headers) + ); + } + + /** + * Push response with the contents of a file as the body to the sequence. + * + * @param string $filePath + * @param int $status + * @param array $headers + * @return $this + */ + public function pushFile(string $filePath, int $status = 200, array $headers = []) + { + $string = file_get_contents($filePath); + + return $this->pushResponse( + Factory::response($string, $status, $headers) + ); + } + + /** + * Push a response to the sequence. + * + * @param mixed $response + * @return $this + */ + public function pushResponse($response) + { + $this->responses[] = $response; + + return $this; + } + + /** + * Make the sequence return a default response when it is empty. + * + * @param \GuzzleHttp\Promise\PromiseInterface|\Closure $response + * @return $this + */ + public function whenEmpty($response) + { + $this->failWhenEmpty = false; + $this->emptyResponse = $response; + + return $this; + } + + /** + * Make the sequence return a default response when it is empty. + * + * @return $this + */ + public function dontFailWhenEmpty() + { + return $this->whenEmpty(Factory::response()); + } + + /** + * Indicate that this sequence has depleted all of its responses. + * + * @return bool + */ + public function isEmpty() + { + return count($this->responses) === 0; + } + + /** + * Get the next response in the sequence. + * + * @return mixed + * + * @throws \OutOfBoundsException + */ + public function __invoke() + { + if ($this->failWhenEmpty && count($this->responses) === 0) { + throw new OutOfBoundsException('A request was made, but the response sequence is empty.'); + } + + if (! $this->failWhenEmpty && count($this->responses) === 0) { + return value($this->emptyResponse ?? Factory::response()); + } + + return array_shift($this->responses); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithContentTypes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithContentTypes.php new file mode 100644 index 0000000..0d5f62f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithContentTypes.php @@ -0,0 +1,179 @@ +header('CONTENT_TYPE') ?? '', ['/json', '+json']); + } + + /** + * Determine if the current request probably expects a JSON response. + * + * @return bool + */ + public function expectsJson() + { + return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || $this->wantsJson(); + } + + /** + * Determine if the current request is asking for JSON. + * + * @return bool + */ + public function wantsJson() + { + $acceptable = $this->getAcceptableContentTypes(); + + return isset($acceptable[0]) && Str::contains(strtolower($acceptable[0]), ['/json', '+json']); + } + + /** + * Determines whether the current requests accepts a given content type. + * + * @param string|array $contentTypes + * @return bool + */ + public function accepts($contentTypes) + { + $accepts = $this->getAcceptableContentTypes(); + + if (count($accepts) === 0) { + return true; + } + + $types = (array) $contentTypes; + + foreach ($accepts as $accept) { + if ($accept === '*/*' || $accept === '*') { + return true; + } + + foreach ($types as $type) { + $accept = strtolower($accept); + + $type = strtolower($type); + + if ($this->matchesType($accept, $type) || $accept === strtok($type, '/').'/*') { + return true; + } + } + } + + return false; + } + + /** + * Return the most suitable content type from the given array based on content negotiation. + * + * @param string|array $contentTypes + * @return string|null + */ + public function prefers($contentTypes) + { + $accepts = $this->getAcceptableContentTypes(); + + $contentTypes = (array) $contentTypes; + + foreach ($accepts as $accept) { + if (in_array($accept, ['*/*', '*'])) { + return $contentTypes[0]; + } + + foreach ($contentTypes as $contentType) { + $type = $contentType; + + if (! is_null($mimeType = $this->getMimeType($contentType))) { + $type = $mimeType; + } + + $accept = strtolower($accept); + + $type = strtolower($type); + + if ($this->matchesType($type, $accept) || $accept === strtok($type, '/').'/*') { + return $contentType; + } + } + } + } + + /** + * Determine if the current request accepts any content type. + * + * @return bool + */ + public function acceptsAnyContentType() + { + $acceptable = $this->getAcceptableContentTypes(); + + return count($acceptable) === 0 || ( + isset($acceptable[0]) && ($acceptable[0] === '*/*' || $acceptable[0] === '*') + ); + } + + /** + * Determines whether a request accepts JSON. + * + * @return bool + */ + public function acceptsJson() + { + return $this->accepts('application/json'); + } + + /** + * Determines whether a request accepts HTML. + * + * @return bool + */ + public function acceptsHtml() + { + return $this->accepts('text/html'); + } + + /** + * Determine if the given content types match. + * + * @param string $actual + * @param string $type + * @return bool + */ + public static function matchesType($actual, $type) + { + if ($actual === $type) { + return true; + } + + $split = explode('/', $actual); + + return isset($split[1]) && preg_match('#'.preg_quote($split[0], '#').'/.+\+'.preg_quote($split[1], '#').'#', $type); + } + + /** + * Get the data format expected in the response. + * + * @param string $default + * @return string + */ + public function format($default = 'html') + { + foreach ($this->getAcceptableContentTypes() as $type) { + if ($format = $this->getFormat($type)) { + return $format; + } + } + + return $default; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithFlashData.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithFlashData.php new file mode 100644 index 0000000..6682e54 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithFlashData.php @@ -0,0 +1,64 @@ +hasSession() ? $this->session()->getOldInput($key, $default) : $default; + } + + /** + * Flash the input for the current request to the session. + * + * @return void + */ + public function flash() + { + $this->session()->flashInput($this->input()); + } + + /** + * Flash only some of the input to the session. + * + * @param array|mixed $keys + * @return void + */ + public function flashOnly($keys) + { + $this->session()->flashInput( + $this->only(is_array($keys) ? $keys : func_get_args()) + ); + } + + /** + * Flash only some of the input to the session. + * + * @param array|mixed $keys + * @return void + */ + public function flashExcept($keys) + { + $this->session()->flashInput( + $this->except(is_array($keys) ? $keys : func_get_args()) + ); + } + + /** + * Flush all of the old input from the session. + * + * @return void + */ + public function flush() + { + $this->session()->flashInput([]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithInput.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithInput.php new file mode 100644 index 0000000..ae8b6fe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithInput.php @@ -0,0 +1,540 @@ +retrieveItem('server', $key, $default); + } + + /** + * Determine if a header is set on the request. + * + * @param string $key + * @return bool + */ + public function hasHeader($key) + { + return ! is_null($this->header($key)); + } + + /** + * Retrieve a header from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + */ + public function header($key = null, $default = null) + { + return $this->retrieveItem('headers', $key, $default); + } + + /** + * Get the bearer token from the request headers. + * + * @return string|null + */ + public function bearerToken() + { + $header = $this->header('Authorization', ''); + + $position = strrpos($header, 'Bearer '); + + if ($position !== false) { + $header = substr($header, $position + 7); + + return strpos($header, ',') !== false ? strstr($header, ',', true) : $header; + } + } + + /** + * Determine if the request contains a given input item key. + * + * @param string|array $key + * @return bool + */ + public function exists($key) + { + return $this->has($key); + } + + /** + * Determine if the request contains a given input item key. + * + * @param string|array $key + * @return bool + */ + public function has($key) + { + $keys = is_array($key) ? $key : func_get_args(); + + $input = $this->all(); + + foreach ($keys as $value) { + if (! Arr::has($input, $value)) { + return false; + } + } + + return true; + } + + /** + * Determine if the request contains any of the given inputs. + * + * @param string|array $keys + * @return bool + */ + public function hasAny($keys) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + $input = $this->all(); + + return Arr::hasAny($input, $keys); + } + + /** + * Apply the callback if the request contains the given input item key. + * + * @param string $key + * @param callable $callback + * @param callable|null $default + * @return $this|mixed + */ + public function whenHas($key, callable $callback, callable $default = null) + { + if ($this->has($key)) { + return $callback(data_get($this->all(), $key)) ?: $this; + } + + if ($default) { + return $default(); + } + + return $this; + } + + /** + * Determine if the request contains a non-empty value for an input item. + * + * @param string|array $key + * @return bool + */ + public function filled($key) + { + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $value) { + if ($this->isEmptyString($value)) { + return false; + } + } + + return true; + } + + /** + * Determine if the request contains an empty value for an input item. + * + * @param string|array $key + * @return bool + */ + public function isNotFilled($key) + { + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $value) { + if (! $this->isEmptyString($value)) { + return false; + } + } + + return true; + } + + /** + * Determine if the request contains a non-empty value for any of the given inputs. + * + * @param string|array $keys + * @return bool + */ + public function anyFilled($keys) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + foreach ($keys as $key) { + if ($this->filled($key)) { + return true; + } + } + + return false; + } + + /** + * Apply the callback if the request contains a non-empty value for the given input item key. + * + * @param string $key + * @param callable $callback + * @param callable|null $default + * @return $this|mixed + */ + public function whenFilled($key, callable $callback, callable $default = null) + { + if ($this->filled($key)) { + return $callback(data_get($this->all(), $key)) ?: $this; + } + + if ($default) { + return $default(); + } + + return $this; + } + + /** + * Determine if the request is missing a given input item key. + * + * @param string|array $key + * @return bool + */ + public function missing($key) + { + $keys = is_array($key) ? $key : func_get_args(); + + return ! $this->has($keys); + } + + /** + * Determine if the given input key is an empty string for "has". + * + * @param string $key + * @return bool + */ + protected function isEmptyString($key) + { + $value = $this->input($key); + + return ! is_bool($value) && ! is_array($value) && trim((string) $value) === ''; + } + + /** + * Get the keys for all of the input and files. + * + * @return array + */ + public function keys() + { + return array_merge(array_keys($this->input()), $this->files->keys()); + } + + /** + * Get all of the input and files for the request. + * + * @param array|mixed|null $keys + * @return array + */ + public function all($keys = null) + { + $input = array_replace_recursive($this->input(), $this->allFiles()); + + if (! $keys) { + return $input; + } + + $results = []; + + foreach (is_array($keys) ? $keys : func_get_args() as $key) { + Arr::set($results, $key, Arr::get($input, $key)); + } + + return $results; + } + + /** + * Retrieve an input item from the request. + * + * @param string|null $key + * @param mixed $default + * @return mixed + */ + public function input($key = null, $default = null) + { + return data_get( + $this->getInputSource()->all() + $this->query->all(), $key, $default + ); + } + + /** + * Retrieve input as a boolean value. + * + * Returns true when value is "1", "true", "on", and "yes". Otherwise, returns false. + * + * @param string|null $key + * @param bool $default + * @return bool + */ + public function boolean($key = null, $default = false) + { + return filter_var($this->input($key, $default), FILTER_VALIDATE_BOOLEAN); + } + + /** + * Retrieve input from the request as a Carbon instance. + * + * @param string $key + * @param string|null $format + * @param string|null $tz + * @return \Illuminate\Support\Carbon|null + */ + public function date($key, $format = null, $tz = null) + { + if ($this->isNotFilled($key)) { + return null; + } + + if (is_null($format)) { + return Date::parse($this->input($key), $tz); + } + + return Date::createFromFormat($format, $this->input($key), $tz); + } + + /** + * Retrieve input from the request as a collection. + * + * @param array|string|null $key + * @return \Illuminate\Support\Collection + */ + public function collect($key = null) + { + return collect(is_array($key) ? $this->only($key) : $this->input($key)); + } + + /** + * Get a subset containing the provided keys with values from the input data. + * + * @param array|mixed $keys + * @return array + */ + public function only($keys) + { + $results = []; + + $input = $this->all(); + + $placeholder = new stdClass; + + foreach (is_array($keys) ? $keys : func_get_args() as $key) { + $value = data_get($input, $key, $placeholder); + + if ($value !== $placeholder) { + Arr::set($results, $key, $value); + } + } + + return $results; + } + + /** + * Get all of the input except for a specified array of items. + * + * @param array|mixed $keys + * @return array + */ + public function except($keys) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + $results = $this->all(); + + Arr::forget($results, $keys); + + return $results; + } + + /** + * Retrieve a query string item from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + */ + public function query($key = null, $default = null) + { + return $this->retrieveItem('query', $key, $default); + } + + /** + * Retrieve a request payload item from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + */ + public function post($key = null, $default = null) + { + return $this->retrieveItem('request', $key, $default); + } + + /** + * Determine if a cookie is set on the request. + * + * @param string $key + * @return bool + */ + public function hasCookie($key) + { + return ! is_null($this->cookie($key)); + } + + /** + * Retrieve a cookie from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + */ + public function cookie($key = null, $default = null) + { + return $this->retrieveItem('cookies', $key, $default); + } + + /** + * Get an array of all of the files on the request. + * + * @return array + */ + public function allFiles() + { + $files = $this->files->all(); + + return $this->convertedFiles = $this->convertedFiles ?? $this->convertUploadedFiles($files); + } + + /** + * Convert the given array of Symfony UploadedFiles to custom Laravel UploadedFiles. + * + * @param array $files + * @return array + */ + protected function convertUploadedFiles(array $files) + { + return array_map(function ($file) { + if (is_null($file) || (is_array($file) && empty(array_filter($file)))) { + return $file; + } + + return is_array($file) + ? $this->convertUploadedFiles($file) + : UploadedFile::createFromBase($file); + }, $files); + } + + /** + * Determine if the uploaded data contains a file. + * + * @param string $key + * @return bool + */ + public function hasFile($key) + { + if (! is_array($files = $this->file($key))) { + $files = [$files]; + } + + foreach ($files as $file) { + if ($this->isValidFile($file)) { + return true; + } + } + + return false; + } + + /** + * Check that the given file is a valid file instance. + * + * @param mixed $file + * @return bool + */ + protected function isValidFile($file) + { + return $file instanceof SplFileInfo && $file->getPath() !== ''; + } + + /** + * Retrieve a file from the request. + * + * @param string|null $key + * @param mixed $default + * @return \Illuminate\Http\UploadedFile|\Illuminate\Http\UploadedFile[]|array|null + */ + public function file($key = null, $default = null) + { + return data_get($this->allFiles(), $key, $default); + } + + /** + * Retrieve a parameter item from a given source. + * + * @param string $source + * @param string $key + * @param string|array|null $default + * @return string|array|null + */ + protected function retrieveItem($source, $key, $default) + { + if (is_null($key)) { + return $this->$source->all(); + } + + return $this->$source->get($key, $default); + } + + /** + * Dump the request items and end the script. + * + * @param mixed $keys + * @return void + */ + public function dd(...$keys) + { + $this->dump(...$keys); + + exit(1); + } + + /** + * Dump the items. + * + * @param mixed $keys + * @return $this + */ + public function dump($keys = []) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + VarDumper::dump(count($keys) > 0 ? $this->only($keys) : $this->all()); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Exceptions/HttpResponseException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Exceptions/HttpResponseException.php new file mode 100644 index 0000000..b27052f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Exceptions/HttpResponseException.php @@ -0,0 +1,37 @@ +response = $response; + } + + /** + * Get the underlying response instance. + * + * @return \Symfony\Component\HttpFoundation\Response + */ + public function getResponse() + { + return $this->response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Exceptions/PostTooLargeException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Exceptions/PostTooLargeException.php new file mode 100644 index 0000000..75f6cdd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Exceptions/PostTooLargeException.php @@ -0,0 +1,23 @@ +getRealPath(); + } + + /** + * Get the file's extension. + * + * @return string + */ + public function extension() + { + return $this->guessExtension(); + } + + /** + * Get a filename for the file. + * + * @param string|null $path + * @return string + */ + public function hashName($path = null) + { + if ($path) { + $path = rtrim($path, '/').'/'; + } + + $hash = $this->hashName ?: $this->hashName = Str::random(40); + + if ($extension = $this->guessExtension()) { + $extension = '.'.$extension; + } + + return $path.$hash.$extension; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php new file mode 100755 index 0000000..84a68f9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php @@ -0,0 +1,139 @@ +encodingOptions = $options; + + parent::__construct($data, $status, $headers, $json); + } + + /** + * {@inheritdoc} + * + * @return static + */ + public static function fromJsonString(?string $data = null, int $status = 200, array $headers = []) + { + return new static($data, $status, $headers, 0, true); + } + + /** + * Sets the JSONP callback. + * + * @param string|null $callback + * @return $this + */ + public function withCallback($callback = null) + { + return $this->setCallback($callback); + } + + /** + * Get the json_decoded data from the response. + * + * @param bool $assoc + * @param int $depth + * @return mixed + */ + public function getData($assoc = false, $depth = 512) + { + return json_decode($this->data, $assoc, $depth); + } + + /** + * {@inheritdoc} + * + * @return static + */ + public function setData($data = []) + { + $this->original = $data; + + // Ensure json_last_error() is cleared... + json_decode('[]'); + + if ($data instanceof Jsonable) { + $this->data = $data->toJson($this->encodingOptions); + } elseif ($data instanceof JsonSerializable) { + $this->data = json_encode($data->jsonSerialize(), $this->encodingOptions); + } elseif ($data instanceof Arrayable) { + $this->data = json_encode($data->toArray(), $this->encodingOptions); + } else { + $this->data = json_encode($data, $this->encodingOptions); + } + + if (! $this->hasValidJson(json_last_error())) { + throw new InvalidArgumentException(json_last_error_msg()); + } + + return $this->update(); + } + + /** + * Determine if an error occurred during JSON encoding. + * + * @param int $jsonError + * @return bool + */ + protected function hasValidJson($jsonError) + { + if ($jsonError === JSON_ERROR_NONE) { + return true; + } + + return $this->hasEncodingOption(JSON_PARTIAL_OUTPUT_ON_ERROR) && + in_array($jsonError, [ + JSON_ERROR_RECURSION, + JSON_ERROR_INF_OR_NAN, + JSON_ERROR_UNSUPPORTED_TYPE, + ]); + } + + /** + * {@inheritdoc} + * + * @return static + */ + public function setEncodingOptions($options) + { + $this->encodingOptions = (int) $options; + + return $this->setData($this->getData()); + } + + /** + * Determine if a JSON encoding option is set. + * + * @param int $option + * @return bool + */ + public function hasEncodingOption($option) + { + return (bool) ($this->encodingOptions & $option); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/CheckResponseForModifications.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/CheckResponseForModifications.php new file mode 100644 index 0000000..2a93e21 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/CheckResponseForModifications.php @@ -0,0 +1,27 @@ +isNotModified($request); + } + + return $response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/FrameGuard.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/FrameGuard.php new file mode 100644 index 0000000..66edce4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/FrameGuard.php @@ -0,0 +1,24 @@ +headers->set('X-Frame-Options', 'SAMEORIGIN', false); + + return $response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/SetCacheHeaders.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/SetCacheHeaders.php new file mode 100644 index 0000000..b42dc2f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/SetCacheHeaders.php @@ -0,0 +1,64 @@ +isMethodCacheable() || ! $response->getContent()) { + return $response; + } + + if (is_string($options)) { + $options = $this->parseOptions($options); + } + + if (isset($options['etag']) && $options['etag'] === true) { + $options['etag'] = md5($response->getContent()); + } + + if (isset($options['last_modified'])) { + if (is_numeric($options['last_modified'])) { + $options['last_modified'] = Carbon::createFromTimestamp($options['last_modified']); + } else { + $options['last_modified'] = Carbon::parse($options['last_modified']); + } + } + + $response->setCache($options); + $response->isNotModified($request); + + return $response; + } + + /** + * Parse the given header options. + * + * @param string $options + * @return array + */ + protected function parseOptions($options) + { + return collect(explode(';', rtrim($options, ';')))->mapWithKeys(function ($option) { + $data = explode('=', $option, 2); + + return [$data[0] => $data[1] ?? true]; + })->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustHosts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustHosts.php new file mode 100644 index 0000000..8b56315 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustHosts.php @@ -0,0 +1,73 @@ +app = $app; + } + + /** + * Get the host patterns that should be trusted. + * + * @return array + */ + abstract public function hosts(); + + /** + * Handle the incoming request. + * + * @param \Illuminate\Http\Request $request + * @param callable $next + * @return \Illuminate\Http\Response + */ + public function handle(Request $request, $next) + { + if ($this->shouldSpecifyTrustedHosts()) { + Request::setTrustedHosts(array_filter($this->hosts())); + } + + return $next($request); + } + + /** + * Determine if the application should specify trusted hosts. + * + * @return bool + */ + protected function shouldSpecifyTrustedHosts() + { + return config('app.env') !== 'local' && + ! $this->app->runningUnitTests(); + } + + /** + * Get a regular expression matching the application URL and all of its subdomains. + * + * @return string|null + */ + protected function allSubdomainsOfApplicationUrl() + { + if ($host = parse_url($this->app['config']->get('app.url'), PHP_URL_HOST)) { + return '^(.+\.)?'.preg_quote($host).'$'; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php new file mode 100644 index 0000000..872fd3c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php @@ -0,0 +1,136 @@ +getTrustedHeaderNames()); + + $this->setTrustedProxyIpAddresses($request); + + return $next($request); + } + + /** + * Sets the trusted proxies on the request. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + protected function setTrustedProxyIpAddresses(Request $request) + { + $trustedIps = $this->proxies() ?: config('trustedproxy.proxies'); + + if ($trustedIps === '*' || $trustedIps === '**') { + return $this->setTrustedProxyIpAddressesToTheCallingIp($request); + } + + $trustedIps = is_string($trustedIps) + ? array_map('trim', explode(',', $trustedIps)) + : $trustedIps; + + if (is_array($trustedIps)) { + return $this->setTrustedProxyIpAddressesToSpecificIps($request, $trustedIps); + } + } + + /** + * Specify the IP addresses to trust explicitly. + * + * @param \Illuminate\Http\Request $request + * @param array $trustedIps + * @return void + */ + protected function setTrustedProxyIpAddressesToSpecificIps(Request $request, array $trustedIps) + { + $request->setTrustedProxies($trustedIps, $this->getTrustedHeaderNames()); + } + + /** + * Set the trusted proxy to be the IP address calling this servers. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + protected function setTrustedProxyIpAddressesToTheCallingIp(Request $request) + { + $request->setTrustedProxies([$request->server->get('REMOTE_ADDR')], $this->getTrustedHeaderNames()); + } + + /** + * Retrieve trusted header name(s), falling back to defaults if config not set. + * + * @return int A bit field of Request::HEADER_*, to set which headers to trust from your proxies. + */ + protected function getTrustedHeaderNames() + { + switch ($this->headers) { + case 'HEADER_X_FORWARDED_AWS_ELB': + case Request::HEADER_X_FORWARDED_AWS_ELB: + return Request::HEADER_X_FORWARDED_AWS_ELB; + + case 'HEADER_FORWARDED': + case Request::HEADER_FORWARDED: + return Request::HEADER_FORWARDED; + + case 'HEADER_X_FORWARDED_FOR': + case Request::HEADER_X_FORWARDED_FOR: + return Request::HEADER_X_FORWARDED_FOR; + + case 'HEADER_X_FORWARDED_HOST': + case Request::HEADER_X_FORWARDED_HOST: + return Request::HEADER_X_FORWARDED_HOST; + + case 'HEADER_X_FORWARDED_PORT': + case Request::HEADER_X_FORWARDED_PORT: + return Request::HEADER_X_FORWARDED_PORT; + + case 'HEADER_X_FORWARDED_PROTO': + case Request::HEADER_X_FORWARDED_PROTO: + return Request::HEADER_X_FORWARDED_PROTO; + + default: + return Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB; + } + + return $this->headers; + } + + /** + * Get the trusted proxies. + * + * @return array|string|null + */ + protected function proxies() + { + return $this->proxies; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/RedirectResponse.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/RedirectResponse.php new file mode 100755 index 0000000..32bb5fc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/RedirectResponse.php @@ -0,0 +1,258 @@ + $value]; + + foreach ($key as $k => $v) { + $this->session->flash($k, $v); + } + + return $this; + } + + /** + * Add multiple cookies to the response. + * + * @param array $cookies + * @return $this + */ + public function withCookies(array $cookies) + { + foreach ($cookies as $cookie) { + $this->headers->setCookie($cookie); + } + + return $this; + } + + /** + * Flash an array of input to the session. + * + * @param array|null $input + * @return $this + */ + public function withInput(array $input = null) + { + $this->session->flashInput($this->removeFilesFromInput( + ! is_null($input) ? $input : $this->request->input() + )); + + return $this; + } + + /** + * Remove all uploaded files form the given input array. + * + * @param array $input + * @return array + */ + protected function removeFilesFromInput(array $input) + { + foreach ($input as $key => $value) { + if (is_array($value)) { + $input[$key] = $this->removeFilesFromInput($value); + } + + if ($value instanceof SymfonyUploadedFile) { + unset($input[$key]); + } + } + + return $input; + } + + /** + * Flash an array of input to the session. + * + * @return $this + */ + public function onlyInput() + { + return $this->withInput($this->request->only(func_get_args())); + } + + /** + * Flash an array of input to the session. + * + * @return $this + */ + public function exceptInput() + { + return $this->withInput($this->request->except(func_get_args())); + } + + /** + * Flash a container of errors to the session. + * + * @param \Illuminate\Contracts\Support\MessageProvider|array|string $provider + * @param string $key + * @return $this + */ + public function withErrors($provider, $key = 'default') + { + $value = $this->parseErrors($provider); + + $errors = $this->session->get('errors', new ViewErrorBag); + + if (! $errors instanceof ViewErrorBag) { + $errors = new ViewErrorBag; + } + + $this->session->flash( + 'errors', $errors->put($key, $value) + ); + + return $this; + } + + /** + * Parse the given errors into an appropriate value. + * + * @param \Illuminate\Contracts\Support\MessageProvider|array|string $provider + * @return \Illuminate\Support\MessageBag + */ + protected function parseErrors($provider) + { + if ($provider instanceof MessageProvider) { + return $provider->getMessageBag(); + } + + return new MessageBag((array) $provider); + } + + /** + * Add a fragment identifier to the URL. + * + * @param string $fragment + * @return $this + */ + public function withFragment($fragment) + { + return $this->withoutFragment() + ->setTargetUrl($this->getTargetUrl().'#'.Str::after($fragment, '#')); + } + + /** + * Remove any fragment identifier from the response URL. + * + * @return $this + */ + public function withoutFragment() + { + return $this->setTargetUrl(Str::before($this->getTargetUrl(), '#')); + } + + /** + * Get the original response content. + * + * @return null + */ + public function getOriginalContent() + { + // + } + + /** + * Get the request instance. + * + * @return \Illuminate\Http\Request|null + */ + public function getRequest() + { + return $this->request; + } + + /** + * Set the request instance. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + public function setRequest(Request $request) + { + $this->request = $request; + } + + /** + * Get the session store instance. + * + * @return \Illuminate\Session\Store|null + */ + public function getSession() + { + return $this->session; + } + + /** + * Set the session store instance. + * + * @param \Illuminate\Session\Store $session + * @return void + */ + public function setSession(SessionStore $session) + { + $this->session = $session; + } + + /** + * Dynamically bind flash data in the session. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + if (Str::startsWith($method, 'with')) { + return $this->with(Str::snake(substr($method, 4)), $parameters[0]); + } + + static::throwBadMethodCallException($method); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Request.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Request.php new file mode 100644 index 0000000..79175ac --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Request.php @@ -0,0 +1,740 @@ +getMethod(); + } + + /** + * Get the root URL for the application. + * + * @return string + */ + public function root() + { + return rtrim($this->getSchemeAndHttpHost().$this->getBaseUrl(), '/'); + } + + /** + * Get the URL (no query string) for the request. + * + * @return string + */ + public function url() + { + return rtrim(preg_replace('/\?.*/', '', $this->getUri()), '/'); + } + + /** + * Get the full URL for the request. + * + * @return string + */ + public function fullUrl() + { + $query = $this->getQueryString(); + + $question = $this->getBaseUrl().$this->getPathInfo() === '/' ? '/?' : '?'; + + return $query ? $this->url().$question.$query : $this->url(); + } + + /** + * Get the full URL for the request with the added query string parameters. + * + * @param array $query + * @return string + */ + public function fullUrlWithQuery(array $query) + { + $question = $this->getBaseUrl().$this->getPathInfo() === '/' ? '/?' : '?'; + + return count($this->query()) > 0 + ? $this->url().$question.Arr::query(array_merge($this->query(), $query)) + : $this->fullUrl().$question.Arr::query($query); + } + + /** + * Get the full URL for the request without the given query string parameters. + * + * @param array|string $query + * @return string + */ + public function fullUrlWithoutQuery($keys) + { + $query = Arr::except($this->query(), $keys); + + $question = $this->getBaseUrl().$this->getPathInfo() === '/' ? '/?' : '?'; + + return count($query) > 0 + ? $this->url().$question.Arr::query($query) + : $this->url(); + } + + /** + * Get the current path info for the request. + * + * @return string + */ + public function path() + { + $pattern = trim($this->getPathInfo(), '/'); + + return $pattern === '' ? '/' : $pattern; + } + + /** + * Get the current decoded path info for the request. + * + * @return string + */ + public function decodedPath() + { + return rawurldecode($this->path()); + } + + /** + * Get a segment from the URI (1 based index). + * + * @param int $index + * @param string|null $default + * @return string|null + */ + public function segment($index, $default = null) + { + return Arr::get($this->segments(), $index - 1, $default); + } + + /** + * Get all of the segments for the request path. + * + * @return array + */ + public function segments() + { + $segments = explode('/', $this->decodedPath()); + + return array_values(array_filter($segments, function ($value) { + return $value !== ''; + })); + } + + /** + * Determine if the current request URI matches a pattern. + * + * @param mixed ...$patterns + * @return bool + */ + public function is(...$patterns) + { + $path = $this->decodedPath(); + + foreach ($patterns as $pattern) { + if (Str::is($pattern, $path)) { + return true; + } + } + + return false; + } + + /** + * Determine if the route name matches a given pattern. + * + * @param mixed ...$patterns + * @return bool + */ + public function routeIs(...$patterns) + { + return $this->route() && $this->route()->named(...$patterns); + } + + /** + * Determine if the current request URL and query string match a pattern. + * + * @param mixed ...$patterns + * @return bool + */ + public function fullUrlIs(...$patterns) + { + $url = $this->fullUrl(); + + foreach ($patterns as $pattern) { + if (Str::is($pattern, $url)) { + return true; + } + } + + return false; + } + + /** + * Determine if the request is the result of an AJAX call. + * + * @return bool + */ + public function ajax() + { + return $this->isXmlHttpRequest(); + } + + /** + * Determine if the request is the result of a PJAX call. + * + * @return bool + */ + public function pjax() + { + return $this->headers->get('X-PJAX') == true; + } + + /** + * Determine if the request is the result of a prefetch call. + * + * @return bool + */ + public function prefetch() + { + return strcasecmp($this->server->get('HTTP_X_MOZ') ?? '', 'prefetch') === 0 || + strcasecmp($this->headers->get('Purpose') ?? '', 'prefetch') === 0; + } + + /** + * Determine if the request is over HTTPS. + * + * @return bool + */ + public function secure() + { + return $this->isSecure(); + } + + /** + * Get the client IP address. + * + * @return string|null + */ + public function ip() + { + return $this->getClientIp(); + } + + /** + * Get the client IP addresses. + * + * @return array + */ + public function ips() + { + return $this->getClientIps(); + } + + /** + * Get the client user agent. + * + * @return string|null + */ + public function userAgent() + { + return $this->headers->get('User-Agent'); + } + + /** + * Merge new input into the current request's input array. + * + * @param array $input + * @return $this + */ + public function merge(array $input) + { + $this->getInputSource()->add($input); + + return $this; + } + + /** + * Merge new input into the request's input, but only when that key is missing from the request. + * + * @param array $input + * @return $this + */ + public function mergeIfMissing(array $input) + { + return $this->merge(collect($input)->filter(function ($value, $key) { + return $this->missing($key); + })->toArray()); + } + + /** + * Replace the input for the current request. + * + * @param array $input + * @return $this + */ + public function replace(array $input) + { + $this->getInputSource()->replace($input); + + return $this; + } + + /** + * This method belongs to Symfony HttpFoundation and is not usually needed when using Laravel. + * + * Instead, you may use the "input" method. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get(string $key, $default = null) + { + return parent::get($key, $default); + } + + /** + * Get the JSON payload for the request. + * + * @param string|null $key + * @param mixed $default + * @return \Symfony\Component\HttpFoundation\ParameterBag|mixed + */ + public function json($key = null, $default = null) + { + if (! isset($this->json)) { + $this->json = new ParameterBag((array) json_decode($this->getContent(), true)); + } + + if (is_null($key)) { + return $this->json; + } + + return data_get($this->json->all(), $key, $default); + } + + /** + * Get the input source for the request. + * + * @return \Symfony\Component\HttpFoundation\ParameterBag + */ + protected function getInputSource() + { + if ($this->isJson()) { + return $this->json(); + } + + return in_array($this->getRealMethod(), ['GET', 'HEAD']) ? $this->query : $this->request; + } + + /** + * Create a new request instance from the given Laravel request. + * + * @param \Illuminate\Http\Request $from + * @param \Illuminate\Http\Request|null $to + * @return static + */ + public static function createFrom(self $from, $to = null) + { + $request = $to ?: new static; + + $files = $from->files->all(); + + $files = is_array($files) ? array_filter($files) : $files; + + $request->initialize( + $from->query->all(), + $from->request->all(), + $from->attributes->all(), + $from->cookies->all(), + $files, + $from->server->all(), + $from->getContent() + ); + + $request->headers->replace($from->headers->all()); + + $request->setJson($from->json()); + + if ($session = $from->getSession()) { + $request->setLaravelSession($session); + } + + $request->setUserResolver($from->getUserResolver()); + + $request->setRouteResolver($from->getRouteResolver()); + + return $request; + } + + /** + * Create an Illuminate request from a Symfony instance. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @return static + */ + public static function createFromBase(SymfonyRequest $request) + { + $newRequest = (new static)->duplicate( + $request->query->all(), $request->request->all(), $request->attributes->all(), + $request->cookies->all(), $request->files->all(), $request->server->all() + ); + + $newRequest->headers->replace($request->headers->all()); + + $newRequest->content = $request->content; + + $newRequest->request = $newRequest->getInputSource(); + + return $newRequest; + } + + /** + * {@inheritdoc} + * + * @return static + */ + public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null) + { + return parent::duplicate($query, $request, $attributes, $cookies, $this->filterFiles($files), $server); + } + + /** + * Filter the given array of files, removing any empty values. + * + * @param mixed $files + * @return mixed + */ + protected function filterFiles($files) + { + if (! $files) { + return; + } + + foreach ($files as $key => $file) { + if (is_array($file)) { + $files[$key] = $this->filterFiles($files[$key]); + } + + if (empty($files[$key])) { + unset($files[$key]); + } + } + + return $files; + } + + /** + * Get the session associated with the request. + * + * @return \Illuminate\Session\Store + * + * @throws \RuntimeException + */ + public function session() + { + if (! $this->hasSession()) { + throw new RuntimeException('Session store not set on request.'); + } + + return $this->session; + } + + /** + * Get the session associated with the request. + * + * @return \Illuminate\Session\Store|null + */ + public function getSession() + { + return $this->session; + } + + /** + * Set the session instance on the request. + * + * @param \Illuminate\Contracts\Session\Session $session + * @return void + */ + public function setLaravelSession($session) + { + $this->session = $session; + } + + /** + * Get the user making the request. + * + * @param string|null $guard + * @return mixed + */ + public function user($guard = null) + { + return call_user_func($this->getUserResolver(), $guard); + } + + /** + * Get the route handling the request. + * + * @param string|null $param + * @param mixed $default + * @return \Illuminate\Routing\Route|object|string|null + */ + public function route($param = null, $default = null) + { + $route = call_user_func($this->getRouteResolver()); + + if (is_null($route) || is_null($param)) { + return $route; + } + + return $route->parameter($param, $default); + } + + /** + * Get a unique fingerprint for the request / route / IP address. + * + * @return string + * + * @throws \RuntimeException + */ + public function fingerprint() + { + if (! $route = $this->route()) { + throw new RuntimeException('Unable to generate fingerprint. Route unavailable.'); + } + + return sha1(implode('|', array_merge( + $route->methods(), + [$route->getDomain(), $route->uri(), $this->ip()] + ))); + } + + /** + * Set the JSON payload for the request. + * + * @param \Symfony\Component\HttpFoundation\ParameterBag $json + * @return $this + */ + public function setJson($json) + { + $this->json = $json; + + return $this; + } + + /** + * Get the user resolver callback. + * + * @return \Closure + */ + public function getUserResolver() + { + return $this->userResolver ?: function () { + // + }; + } + + /** + * Set the user resolver callback. + * + * @param \Closure $callback + * @return $this + */ + public function setUserResolver(Closure $callback) + { + $this->userResolver = $callback; + + return $this; + } + + /** + * Get the route resolver callback. + * + * @return \Closure + */ + public function getRouteResolver() + { + return $this->routeResolver ?: function () { + // + }; + } + + /** + * Set the route resolver callback. + * + * @param \Closure $callback + * @return $this + */ + public function setRouteResolver(Closure $callback) + { + $this->routeResolver = $callback; + + return $this; + } + + /** + * Get all of the input and files for the request. + * + * @return array + */ + public function toArray() + { + return $this->all(); + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + $route = $this->route(); + + return Arr::has( + $this->all() + ($route ? $route->parameters() : []), + $offset + ); + } + + /** + * Get the value at the given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->__get($offset); + } + + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + $this->getInputSource()->set($offset, $value); + } + + /** + * Remove the value at the given offset. + * + * @param string $offset + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + $this->getInputSource()->remove($offset); + } + + /** + * Check if an input element is set on the request. + * + * @param string $key + * @return bool + */ + public function __isset($key) + { + return ! is_null($this->__get($key)); + } + + /** + * Get an input element from the request. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return Arr::get($this->all(), $key, function () use ($key) { + return $this->route($key); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php new file mode 100644 index 0000000..a4d4fab --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php @@ -0,0 +1,86 @@ +collects(); + + $this->collection = $collects && ! $resource->first() instanceof $collects + ? $resource->mapInto($collects) + : $resource->toBase(); + + return ($resource instanceof AbstractPaginator || $resource instanceof AbstractCursorPaginator) + ? $resource->setCollection($this->collection) + : $this->collection; + } + + /** + * Get the resource that this resource collects. + * + * @return string|null + */ + protected function collects() + { + if ($this->collects) { + return $this->collects; + } + + if (Str::endsWith(class_basename($this), 'Collection') && + (class_exists($class = Str::replaceLast('Collection', '', get_class($this))) || + class_exists($class = Str::replaceLast('Collection', 'Resource', get_class($this))))) { + return $class; + } + } + + /** + * Get the JSON serialization options that should be applied to the resource response. + * + * @return int + */ + public function jsonOptions() + { + $collects = $this->collects(); + + if (! $collects) { + return 0; + } + + return (new ReflectionClass($collects)) + ->newInstanceWithoutConstructor() + ->jsonOptions(); + } + + /** + * Get an iterator for the resource collection. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return $this->collection->getIterator(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php new file mode 100644 index 0000000..5b8c8d0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php @@ -0,0 +1,243 @@ + $value) { + $index++; + + if (is_array($value)) { + $data[$key] = $this->filter($value); + + continue; + } + + if (is_numeric($key) && $value instanceof MergeValue) { + return $this->mergeData( + $data, $index, $this->filter($value->data), + array_values($value->data) === $value->data + ); + } + + if ($value instanceof self && is_null($value->resource)) { + $data[$key] = null; + } + } + + return $this->removeMissingValues($data); + } + + /** + * Merge the given data in at the given index. + * + * @param array $data + * @param int $index + * @param array $merge + * @param bool $numericKeys + * @return array + */ + protected function mergeData($data, $index, $merge, $numericKeys) + { + if ($numericKeys) { + return $this->removeMissingValues(array_merge( + array_merge(array_slice($data, 0, $index, true), $merge), + $this->filter(array_values(array_slice($data, $index + 1, null, true))) + )); + } + + return $this->removeMissingValues(array_slice($data, 0, $index, true) + + $merge + + $this->filter(array_slice($data, $index + 1, null, true))); + } + + /** + * Remove the missing values from the filtered data. + * + * @param array $data + * @return array + */ + protected function removeMissingValues($data) + { + $numericKeys = true; + + foreach ($data as $key => $value) { + if (($value instanceof PotentiallyMissing && $value->isMissing()) || + ($value instanceof self && + $value->resource instanceof PotentiallyMissing && + $value->isMissing())) { + unset($data[$key]); + } else { + $numericKeys = $numericKeys && is_numeric($key); + } + } + + if (property_exists($this, 'preserveKeys') && $this->preserveKeys === true) { + return $data; + } + + return $numericKeys ? array_values($data) : $data; + } + + /** + * Retrieve a value based on a given condition. + * + * @param bool $condition + * @param mixed $value + * @param mixed $default + * @return \Illuminate\Http\Resources\MissingValue|mixed + */ + protected function when($condition, $value, $default = null) + { + if ($condition) { + return value($value); + } + + return func_num_args() === 3 ? value($default) : new MissingValue; + } + + /** + * Merge a value into the array. + * + * @param mixed $value + * @return \Illuminate\Http\Resources\MergeValue|mixed + */ + protected function merge($value) + { + return $this->mergeWhen(true, $value); + } + + /** + * Merge a value based on a given condition. + * + * @param bool $condition + * @param mixed $value + * @return \Illuminate\Http\Resources\MergeValue|mixed + */ + protected function mergeWhen($condition, $value) + { + return $condition ? new MergeValue(value($value)) : new MissingValue; + } + + /** + * Merge the given attributes. + * + * @param array $attributes + * @return \Illuminate\Http\Resources\MergeValue + */ + protected function attributes($attributes) + { + return new MergeValue( + Arr::only($this->resource->toArray(), $attributes) + ); + } + + /** + * Retrieve an accessor when it has been appended. + * + * @param string $attribute + * @param mixed $value + * @param mixed $default + * @return \Illuminate\Http\Resources\MissingValue|mixed + */ + protected function whenAppended($attribute, $value = null, $default = null) + { + if ($this->resource->hasAppended($attribute)) { + return func_num_args() >= 2 ? value($value) : $this->resource->$attribute; + } + + return func_num_args() === 3 ? value($default) : new MissingValue; + } + + /** + * Retrieve a relationship if it has been loaded. + * + * @param string $relationship + * @param mixed $value + * @param mixed $default + * @return \Illuminate\Http\Resources\MissingValue|mixed + */ + protected function whenLoaded($relationship, $value = null, $default = null) + { + if (func_num_args() < 3) { + $default = new MissingValue; + } + + if (! $this->resource->relationLoaded($relationship)) { + return value($default); + } + + if (func_num_args() === 1) { + return $this->resource->{$relationship}; + } + + if ($this->resource->{$relationship} === null) { + return; + } + + return value($value); + } + + /** + * Execute a callback if the given pivot table has been loaded. + * + * @param string $table + * @param mixed $value + * @param mixed $default + * @return \Illuminate\Http\Resources\MissingValue|mixed + */ + protected function whenPivotLoaded($table, $value, $default = null) + { + return $this->whenPivotLoadedAs('pivot', ...func_get_args()); + } + + /** + * Execute a callback if the given pivot table with a custom accessor has been loaded. + * + * @param string $accessor + * @param string $table + * @param mixed $value + * @param mixed $default + * @return \Illuminate\Http\Resources\MissingValue|mixed + */ + protected function whenPivotLoadedAs($accessor, $table, $value, $default = null) + { + if (func_num_args() === 3) { + $default = new MissingValue; + } + + return $this->when( + $this->resource->$accessor && + ($this->resource->$accessor instanceof $table || + $this->resource->$accessor->getTable() === $table), + ...[$value, $default] + ); + } + + /** + * Transform the given value if it is present. + * + * @param mixed $value + * @param callable $callback + * @param mixed $default + * @return mixed + */ + protected function transform($value, callable $callback, $default = null) + { + return transform( + $value, $callback, func_num_args() === 3 ? $default : new MissingValue + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/DelegatesToResource.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/DelegatesToResource.php new file mode 100644 index 0000000..48f455f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/DelegatesToResource.php @@ -0,0 +1,154 @@ +resource->getRouteKey(); + } + + /** + * Get the route key for the resource. + * + * @return string + */ + public function getRouteKeyName() + { + return $this->resource->getRouteKeyName(); + } + + /** + * Retrieve the model for a bound value. + * + * @param mixed $value + * @param string|null $field + * @return void + * + * @throws \Exception + */ + public function resolveRouteBinding($value, $field = null) + { + throw new Exception('Resources may not be implicitly resolved from route bindings.'); + } + + /** + * Retrieve the model for a bound value. + * + * @param string $childType + * @param mixed $value + * @param string|null $field + * @return void + * + * @throws \Exception + */ + public function resolveChildRouteBinding($childType, $value, $field = null) + { + throw new Exception('Resources may not be implicitly resolved from route bindings.'); + } + + /** + * Determine if the given attribute exists. + * + * @param mixed $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return isset($this->resource[$offset]); + } + + /** + * Get the value for a given offset. + * + * @param mixed $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->resource[$offset]; + } + + /** + * Set the value for a given offset. + * + * @param mixed $offset + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + $this->resource[$offset] = $value; + } + + /** + * Unset the value for a given offset. + * + * @param mixed $offset + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + unset($this->resource[$offset]); + } + + /** + * Determine if an attribute exists on the resource. + * + * @param string $key + * @return bool + */ + public function __isset($key) + { + return isset($this->resource->{$key}); + } + + /** + * Unset an attribute on the resource. + * + * @param string $key + * @return void + */ + public function __unset($key) + { + unset($this->resource->{$key}); + } + + /** + * Dynamically get properties from the underlying resource. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->resource->{$key}; + } + + /** + * Dynamically pass method calls to the underlying resource. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->forwardCallTo($this->resource, $method, $parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/AnonymousResourceCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/AnonymousResourceCollection.php new file mode 100644 index 0000000..a583136 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/AnonymousResourceCollection.php @@ -0,0 +1,27 @@ +collects = $collects; + + parent::__construct($resource); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/JsonResource.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/JsonResource.php new file mode 100644 index 0000000..8c8bf00 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/JsonResource.php @@ -0,0 +1,244 @@ +resource = $resource; + } + + /** + * Create a new resource instance. + * + * @param mixed ...$parameters + * @return static + */ + public static function make(...$parameters) + { + return new static(...$parameters); + } + + /** + * Create a new anonymous resource collection. + * + * @param mixed $resource + * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection + */ + public static function collection($resource) + { + return tap(new AnonymousResourceCollection($resource, static::class), function ($collection) { + if (property_exists(static::class, 'preserveKeys')) { + $collection->preserveKeys = (new static([]))->preserveKeys === true; + } + }); + } + + /** + * Resolve the resource to an array. + * + * @param \Illuminate\Http\Request|null $request + * @return array + */ + public function resolve($request = null) + { + $data = $this->toArray( + $request = $request ?: Container::getInstance()->make('request') + ); + + if ($data instanceof Arrayable) { + $data = $data->toArray(); + } elseif ($data instanceof JsonSerializable) { + $data = $data->jsonSerialize(); + } + + return $this->filter((array) $data); + } + + /** + * Transform the resource into an array. + * + * @param \Illuminate\Http\Request $request + * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable + */ + public function toArray($request) + { + if (is_null($this->resource)) { + return []; + } + + return is_array($this->resource) + ? $this->resource + : $this->resource->toArray(); + } + + /** + * Convert the model instance to JSON. + * + * @param int $options + * @return string + * + * @throws \Illuminate\Database\Eloquent\JsonEncodingException + */ + public function toJson($options = 0) + { + $json = json_encode($this->jsonSerialize(), $options); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw JsonEncodingException::forResource($this, json_last_error_msg()); + } + + return $json; + } + + /** + * Get any additional data that should be returned with the resource array. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + public function with($request) + { + return $this->with; + } + + /** + * Add additional meta data to the resource response. + * + * @param array $data + * @return $this + */ + public function additional(array $data) + { + $this->additional = $data; + + return $this; + } + + /** + * Get the JSON serialization options that should be applied to the resource response. + * + * @return int + */ + public function jsonOptions() + { + return 0; + } + + /** + * Customize the response for a request. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\JsonResponse $response + * @return void + */ + public function withResponse($request, $response) + { + // + } + + /** + * Set the string that should wrap the outer-most resource array. + * + * @param string $value + * @return void + */ + public static function wrap($value) + { + static::$wrap = $value; + } + + /** + * Disable wrapping of the outer-most resource array. + * + * @return void + */ + public static function withoutWrapping() + { + static::$wrap = null; + } + + /** + * Transform the resource into an HTTP response. + * + * @param \Illuminate\Http\Request|null $request + * @return \Illuminate\Http\JsonResponse + */ + public function response($request = null) + { + return $this->toResponse( + $request ?: Container::getInstance()->make('request') + ); + } + + /** + * Create an HTTP response that represents the object. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function toResponse($request) + { + return (new ResourceResponse($this))->toResponse($request); + } + + /** + * Prepare the resource for JSON serialization. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->resolve(Container::getInstance()->make('request')); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php new file mode 100644 index 0000000..bd3e8f9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php @@ -0,0 +1,92 @@ +json( + $this->wrap( + $this->resource->resolve($request), + array_merge_recursive( + $this->paginationInformation($request), + $this->resource->with($request), + $this->resource->additional + ) + ), + $this->calculateStatus(), + [], + $this->resource->jsonOptions() + ), function ($response) use ($request) { + $response->original = $this->resource->resource->map(function ($item) { + return is_array($item) ? Arr::get($item, 'resource') : $item->resource; + }); + + $this->resource->withResponse($request, $response); + }); + } + + /** + * Add the pagination information to the response. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + protected function paginationInformation($request) + { + $paginated = $this->resource->resource->toArray(); + + $default = [ + 'links' => $this->paginationLinks($paginated), + 'meta' => $this->meta($paginated), + ]; + + if (method_exists($this->resource, 'paginationInformation')) { + return $this->resource->paginationInformation($request, $paginated, $default); + } + + return $default; + } + + /** + * Get the pagination links for the response. + * + * @param array $paginated + * @return array + */ + protected function paginationLinks($paginated) + { + return [ + 'first' => $paginated['first_page_url'] ?? null, + 'last' => $paginated['last_page_url'] ?? null, + 'prev' => $paginated['prev_page_url'] ?? null, + 'next' => $paginated['next_page_url'] ?? null, + ]; + } + + /** + * Gather the meta data for the response. + * + * @param array $paginated + * @return array + */ + protected function meta($paginated) + { + return Arr::except($paginated, [ + 'data', + 'first_page_url', + 'last_page_url', + 'prev_page_url', + 'next_page_url', + ]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceCollection.php new file mode 100644 index 0000000..65710aa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceCollection.php @@ -0,0 +1,136 @@ +resource = $this->collectResource($resource); + } + + /** + * Indicate that all current query parameters should be appended to pagination links. + * + * @return $this + */ + public function preserveQuery() + { + $this->preserveAllQueryParameters = true; + + return $this; + } + + /** + * Specify the query string parameters that should be present on pagination links. + * + * @param array $query + * @return $this + */ + public function withQuery(array $query) + { + $this->preserveAllQueryParameters = false; + + $this->queryParameters = $query; + + return $this; + } + + /** + * Return the count of items in the resource collection. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return $this->collection->count(); + } + + /** + * Transform the resource into a JSON array. + * + * @param \Illuminate\Http\Request $request + * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable + */ + public function toArray($request) + { + return $this->collection->map->toArray($request)->all(); + } + + /** + * Create an HTTP response that represents the object. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function toResponse($request) + { + if ($this->resource instanceof AbstractPaginator || $this->resource instanceof AbstractCursorPaginator) { + return $this->preparePaginatedResponse($request); + } + + return parent::toResponse($request); + } + + /** + * Create a paginate-aware HTTP response. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\JsonResponse + */ + protected function preparePaginatedResponse($request) + { + if ($this->preserveAllQueryParameters) { + $this->resource->appends($request->query()); + } elseif (! is_null($this->queryParameters)) { + $this->resource->appends($this->queryParameters); + } + + return (new PaginatedResourceResponse($this))->toResponse($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceResponse.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceResponse.php new file mode 100644 index 0000000..51f3657 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceResponse.php @@ -0,0 +1,122 @@ +resource = $resource; + } + + /** + * Create an HTTP response that represents the object. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function toResponse($request) + { + return tap(response()->json( + $this->wrap( + $this->resource->resolve($request), + $this->resource->with($request), + $this->resource->additional + ), + $this->calculateStatus(), + [], + $this->resource->jsonOptions() + ), function ($response) use ($request) { + $response->original = $this->resource->resource; + + $this->resource->withResponse($request, $response); + }); + } + + /** + * Wrap the given data if necessary. + * + * @param array $data + * @param array $with + * @param array $additional + * @return array + */ + protected function wrap($data, $with = [], $additional = []) + { + if ($data instanceof Collection) { + $data = $data->all(); + } + + if ($this->haveDefaultWrapperAndDataIsUnwrapped($data)) { + $data = [$this->wrapper() => $data]; + } elseif ($this->haveAdditionalInformationAndDataIsUnwrapped($data, $with, $additional)) { + $data = [($this->wrapper() ?? 'data') => $data]; + } + + return array_merge_recursive($data, $with, $additional); + } + + /** + * Determine if we have a default wrapper and the given data is unwrapped. + * + * @param array $data + * @return bool + */ + protected function haveDefaultWrapperAndDataIsUnwrapped($data) + { + return $this->wrapper() && ! array_key_exists($this->wrapper(), $data); + } + + /** + * Determine if "with" data has been added and our data is unwrapped. + * + * @param array $data + * @param array $with + * @param array $additional + * @return bool + */ + protected function haveAdditionalInformationAndDataIsUnwrapped($data, $with, $additional) + { + return (! empty($with) || ! empty($additional)) && + (! $this->wrapper() || + ! array_key_exists($this->wrapper(), $data)); + } + + /** + * Get the default data wrapper for the resource. + * + * @return string + */ + protected function wrapper() + { + return get_class($this->resource)::$wrap; + } + + /** + * Calculate the appropriate status code for the response. + * + * @return int + */ + protected function calculateStatus() + { + return $this->resource->resource instanceof Model && + $this->resource->resource->wasRecentlyCreated ? 201 : 200; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/MergeValue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/MergeValue.php new file mode 100644 index 0000000..fb6880f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/MergeValue.php @@ -0,0 +1,33 @@ +data = $data->all(); + } elseif ($data instanceof JsonSerializable) { + $this->data = $data->jsonSerialize(); + } else { + $this->data = $data; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/MissingValue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/MissingValue.php new file mode 100644 index 0000000..d0d8dfa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Resources/MissingValue.php @@ -0,0 +1,16 @@ +headers = new ResponseHeaderBag($headers); + + $this->setContent($content); + $this->setStatusCode($status); + $this->setProtocolVersion('1.0'); + } + + /** + * Set the content on the response. + * + * @param mixed $content + * @return $this + * + * @throws \InvalidArgumentException + */ + public function setContent($content) + { + $this->original = $content; + + // If the content is "JSONable" we will set the appropriate header and convert + // the content to JSON. This is useful when returning something like models + // from routes that will be automatically transformed to their JSON form. + if ($this->shouldBeJson($content)) { + $this->header('Content-Type', 'application/json'); + + $content = $this->morphToJson($content); + + if ($content === false) { + throw new InvalidArgumentException(json_last_error_msg()); + } + } + + // If this content implements the "Renderable" interface then we will call the + // render method on the object so we will avoid any "__toString" exceptions + // that might be thrown and have their errors obscured by PHP's handling. + elseif ($content instanceof Renderable) { + $content = $content->render(); + } + + parent::setContent($content); + + return $this; + } + + /** + * Determine if the given content should be turned into JSON. + * + * @param mixed $content + * @return bool + */ + protected function shouldBeJson($content) + { + return $content instanceof Arrayable || + $content instanceof Jsonable || + $content instanceof ArrayObject || + $content instanceof JsonSerializable || + is_array($content); + } + + /** + * Morph the given content into JSON. + * + * @param mixed $content + * @return string + */ + protected function morphToJson($content) + { + if ($content instanceof Jsonable) { + return $content->toJson(); + } elseif ($content instanceof Arrayable) { + return json_encode($content->toArray()); + } + + return json_encode($content); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/ResponseTrait.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/ResponseTrait.php new file mode 100644 index 0000000..cbe29dc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/ResponseTrait.php @@ -0,0 +1,182 @@ +getStatusCode(); + } + + /** + * Get the status text for the response. + * + * @return string + */ + public function statusText() + { + return $this->statusText; + } + + /** + * Get the content of the response. + * + * @return string + */ + public function content() + { + return $this->getContent(); + } + + /** + * Get the original response content. + * + * @return mixed + */ + public function getOriginalContent() + { + $original = $this->original; + + return $original instanceof self ? $original->{__FUNCTION__}() : $original; + } + + /** + * Set a header on the Response. + * + * @param string $key + * @param array|string $values + * @param bool $replace + * @return $this + */ + public function header($key, $values, $replace = true) + { + $this->headers->set($key, $values, $replace); + + return $this; + } + + /** + * Add an array of headers to the response. + * + * @param \Symfony\Component\HttpFoundation\HeaderBag|array $headers + * @return $this + */ + public function withHeaders($headers) + { + if ($headers instanceof HeaderBag) { + $headers = $headers->all(); + } + + foreach ($headers as $key => $value) { + $this->headers->set($key, $value); + } + + return $this; + } + + /** + * Add a cookie to the response. + * + * @param \Symfony\Component\HttpFoundation\Cookie|mixed $cookie + * @return $this + */ + public function cookie($cookie) + { + return $this->withCookie(...func_get_args()); + } + + /** + * Add a cookie to the response. + * + * @param \Symfony\Component\HttpFoundation\Cookie|mixed $cookie + * @return $this + */ + public function withCookie($cookie) + { + if (is_string($cookie) && function_exists('cookie')) { + $cookie = cookie(...func_get_args()); + } + + $this->headers->setCookie($cookie); + + return $this; + } + + /** + * Expire a cookie when sending the response. + * + * @param \Symfony\Component\HttpFoundation\Cookie|mixed $cookie + * @param string|null $path + * @param string|null $domain + * @return $this + */ + public function withoutCookie($cookie, $path = null, $domain = null) + { + if (is_string($cookie) && function_exists('cookie')) { + $cookie = cookie($cookie, null, -2628000, $path, $domain); + } + + $this->headers->setCookie($cookie); + + return $this; + } + + /** + * Get the callback of the response. + * + * @return string|null + */ + public function getCallback() + { + return $this->callback ?? null; + } + + /** + * Set the exception to attach to the response. + * + * @param \Throwable $e + * @return $this + */ + public function withException(Throwable $e) + { + $this->exception = $e; + + return $this; + } + + /** + * Throws the response in a HttpResponseException instance. + * + * @return void + * + * @throws \Illuminate\Http\Exceptions\HttpResponseException + */ + public function throwResponse() + { + throw new HttpResponseException($this); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/File.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/File.php new file mode 100644 index 0000000..c714529 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/File.php @@ -0,0 +1,148 @@ +name = $name; + $this->tempFile = $tempFile; + + parent::__construct( + $this->tempFilePath(), $name, $this->getMimeType(), + null, true + ); + } + + /** + * Create a new fake file. + * + * @param string $name + * @param string|int $kilobytes + * @return \Illuminate\Http\Testing\File + */ + public static function create($name, $kilobytes = 0) + { + return (new FileFactory)->create($name, $kilobytes); + } + + /** + * Create a new fake file with content. + * + * @param string $name + * @param string $content + * @return \Illuminate\Http\Testing\File + */ + public static function createWithContent($name, $content) + { + return (new FileFactory)->createWithContent($name, $content); + } + + /** + * Create a new fake image. + * + * @param string $name + * @param int $width + * @param int $height + * @return \Illuminate\Http\Testing\File + */ + public static function image($name, $width = 10, $height = 10) + { + return (new FileFactory)->image($name, $width, $height); + } + + /** + * Set the "size" of the file in kilobytes. + * + * @param int $kilobytes + * @return $this + */ + public function size($kilobytes) + { + $this->sizeToReport = $kilobytes * 1024; + + return $this; + } + + /** + * Get the size of the file. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function getSize() + { + return $this->sizeToReport ?: parent::getSize(); + } + + /** + * Set the "MIME type" for the file. + * + * @param string $mimeType + * @return $this + */ + public function mimeType($mimeType) + { + $this->mimeTypeToReport = $mimeType; + + return $this; + } + + /** + * Get the MIME type of the file. + * + * @return string + */ + public function getMimeType() + { + return $this->mimeTypeToReport ?: MimeType::from($this->name); + } + + /** + * Get the path to the temporary file. + * + * @return string + */ + protected function tempFilePath() + { + return stream_get_meta_data($this->tempFile)['uri']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/FileFactory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/FileFactory.php new file mode 100644 index 0000000..9e25d72 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/FileFactory.php @@ -0,0 +1,84 @@ +createWithContent($name, $kilobytes); + } + + return tap(new File($name, tmpfile()), function ($file) use ($kilobytes, $mimeType) { + $file->sizeToReport = $kilobytes * 1024; + $file->mimeTypeToReport = $mimeType; + }); + } + + /** + * Create a new fake file with content. + * + * @param string $name + * @param string $content + * @return \Illuminate\Http\Testing\File + */ + public function createWithContent($name, $content) + { + $tmpfile = tmpfile(); + + fwrite($tmpfile, $content); + + return tap(new File($name, $tmpfile), function ($file) use ($tmpfile) { + $file->sizeToReport = fstat($tmpfile)['size']; + }); + } + + /** + * Create a new fake image. + * + * @param string $name + * @param int $width + * @param int $height + * @return \Illuminate\Http\Testing\File + */ + public function image($name, $width = 10, $height = 10) + { + return new File($name, $this->generateImage( + $width, $height, pathinfo($name, PATHINFO_EXTENSION) + )); + } + + /** + * Generate a dummy image of the given width and height. + * + * @param int $width + * @param int $height + * @param string $extension + * @return resource + */ + protected function generateImage($width, $height, $extension) + { + return tap(tmpfile(), function ($temp) use ($width, $height, $extension) { + ob_start(); + + $extension = in_array($extension, ['jpeg', 'png', 'gif', 'webp', 'wbmp', 'bmp']) + ? strtolower($extension) + : 'jpeg'; + + $image = imagecreatetruecolor($width, $height); + + call_user_func("image{$extension}", $image); + + fwrite($temp, ob_get_clean()); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/MimeType.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/MimeType.php new file mode 100644 index 0000000..d188a4b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/Testing/MimeType.php @@ -0,0 +1,65 @@ +getMimeTypes($extension)) ?? 'application/octet-stream'; + } + + /** + * Search for the extension of a given MIME type. + * + * @param string $mimeType + * @return string|null + */ + public static function search($mimeType) + { + return Arr::first(self::getMimeTypes()->getExtensions($mimeType)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/UploadedFile.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/UploadedFile.php new file mode 100644 index 0000000..7779683 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/UploadedFile.php @@ -0,0 +1,149 @@ +storeAs($path, $this->hashName(), $this->parseOptions($options)); + } + + /** + * Store the uploaded file on a filesystem disk with public visibility. + * + * @param string $path + * @param array|string $options + * @return string|false + */ + public function storePublicly($path, $options = []) + { + $options = $this->parseOptions($options); + + $options['visibility'] = 'public'; + + return $this->storeAs($path, $this->hashName(), $options); + } + + /** + * Store the uploaded file on a filesystem disk with public visibility. + * + * @param string $path + * @param string $name + * @param array|string $options + * @return string|false + */ + public function storePubliclyAs($path, $name, $options = []) + { + $options = $this->parseOptions($options); + + $options['visibility'] = 'public'; + + return $this->storeAs($path, $name, $options); + } + + /** + * Store the uploaded file on a filesystem disk. + * + * @param string $path + * @param string $name + * @param array|string $options + * @return string|false + */ + public function storeAs($path, $name, $options = []) + { + $options = $this->parseOptions($options); + + $disk = Arr::pull($options, 'disk'); + + return Container::getInstance()->make(FilesystemFactory::class)->disk($disk)->putFileAs( + $path, $this, $name, $options + ); + } + + /** + * Get the contents of the uploaded file. + * + * @return false|string + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function get() + { + if (! $this->isValid()) { + throw new FileNotFoundException("File does not exist at path {$this->getPathname()}."); + } + + return file_get_contents($this->getPathname()); + } + + /** + * Get the file's extension supplied by the client. + * + * @return string + */ + public function clientExtension() + { + return $this->guessClientExtension(); + } + + /** + * Create a new file instance from a base instance. + * + * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file + * @param bool $test + * @return static + */ + public static function createFromBase(SymfonyUploadedFile $file, $test = false) + { + return $file instanceof static ? $file : new static( + $file->getPathname(), + $file->getClientOriginalName(), + $file->getClientMimeType(), + $file->getError(), + $test + ); + } + + /** + * Parse and format the given options. + * + * @param array|string $options + * @return array + */ + protected function parseOptions($options) + { + if (is_string($options)) { + $options = ['disk' => $options]; + } + + return $options; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/composer.json new file mode 100755 index 0000000..564c398 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Http/composer.json @@ -0,0 +1,45 @@ +{ + "name": "illuminate/http", + "description": "The Illuminate Http package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/session": "^8.0", + "illuminate/support": "^8.0", + "symfony/http-foundation": "^5.4", + "symfony/http-kernel": "^5.4", + "symfony/mime": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Http\\": "" + } + }, + "suggest": { + "ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().", + "guzzlehttp/guzzle": "Required to use the HTTP Client (^6.5.5|^7.0.1)." + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/Events/MessageLogged.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/Events/MessageLogged.php new file mode 100644 index 0000000..312b343 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/Events/MessageLogged.php @@ -0,0 +1,42 @@ +level = $level; + $this->message = $message; + $this->context = $context; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LogManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LogManager.php new file mode 100644 index 0000000..44601a7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LogManager.php @@ -0,0 +1,670 @@ +app = $app; + } + + /** + * Build an on-demand log channel. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + public function build(array $config) + { + unset($this->channels['ondemand']); + + return $this->get('ondemand', $config); + } + + /** + * Create a new, on-demand aggregate logger instance. + * + * @param array $channels + * @param string|null $channel + * @return \Psr\Log\LoggerInterface + */ + public function stack(array $channels, $channel = null) + { + return new Logger( + $this->createStackDriver(compact('channels', 'channel')), + $this->app['events'] + ); + } + + /** + * Get a log channel instance. + * + * @param string|null $channel + * @return \Psr\Log\LoggerInterface + */ + public function channel($channel = null) + { + return $this->driver($channel); + } + + /** + * Get a log driver instance. + * + * @param string|null $driver + * @return \Psr\Log\LoggerInterface + */ + public function driver($driver = null) + { + return $this->get($this->parseDriver($driver)); + } + + /** + * Attempt to get the log from the local cache. + * + * @param string $name + * @param array|null $config + * @return \Psr\Log\LoggerInterface + */ + protected function get($name, ?array $config = null) + { + try { + return $this->channels[$name] ?? with($this->resolve($name, $config), function ($logger) use ($name) { + return $this->channels[$name] = $this->tap($name, new Logger($logger, $this->app['events'])); + }); + } catch (Throwable $e) { + return tap($this->createEmergencyLogger(), function ($logger) use ($e) { + $logger->emergency('Unable to create configured logger. Using emergency logger.', [ + 'exception' => $e, + ]); + }); + } + } + + /** + * Apply the configured taps for the logger. + * + * @param string $name + * @param \Illuminate\Log\Logger $logger + * @return \Illuminate\Log\Logger + */ + protected function tap($name, Logger $logger) + { + foreach ($this->configurationFor($name)['tap'] ?? [] as $tap) { + [$class, $arguments] = $this->parseTap($tap); + + $this->app->make($class)->__invoke($logger, ...explode(',', $arguments)); + } + + return $logger; + } + + /** + * Parse the given tap class string into a class name and arguments string. + * + * @param string $tap + * @return array + */ + protected function parseTap($tap) + { + return Str::contains($tap, ':') ? explode(':', $tap, 2) : [$tap, '']; + } + + /** + * Create an emergency log handler to avoid white screens of death. + * + * @return \Psr\Log\LoggerInterface + */ + protected function createEmergencyLogger() + { + $config = $this->configurationFor('emergency'); + + $handler = new StreamHandler( + $config['path'] ?? $this->app->storagePath().'/logs/laravel.log', + $this->level(['level' => 'debug']) + ); + + return new Logger( + new Monolog('laravel', $this->prepareHandlers([$handler])), + $this->app['events'] + ); + } + + /** + * Resolve the given log instance by name. + * + * @param string $name + * @param array|null $config + * @return \Psr\Log\LoggerInterface + * + * @throws \InvalidArgumentException + */ + protected function resolve($name, ?array $config = null) + { + $config = $config ?? $this->configurationFor($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Log [{$name}] is not defined."); + } + + if (isset($this->customCreators[$config['driver']])) { + return $this->callCustomCreator($config); + } + + $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; + + if (method_exists($this, $driverMethod)) { + return $this->{$driverMethod}($config); + } + + throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported."); + } + + /** + * Call a custom driver creator. + * + * @param array $config + * @return mixed + */ + protected function callCustomCreator(array $config) + { + return $this->customCreators[$config['driver']]($this->app, $config); + } + + /** + * Create a custom log driver instance. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createCustomDriver(array $config) + { + $factory = is_callable($via = $config['via']) ? $via : $this->app->make($via); + + return $factory($config); + } + + /** + * Create an aggregate log driver instance. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createStackDriver(array $config) + { + if (is_string($config['channels'])) { + $config['channels'] = explode(',', $config['channels']); + } + + $handlers = collect($config['channels'])->flatMap(function ($channel) { + return $channel instanceof LoggerInterface + ? $channel->getHandlers() + : $this->channel($channel)->getHandlers(); + })->all(); + + $processors = collect($config['channels'])->flatMap(function ($channel) { + return $channel instanceof LoggerInterface + ? $channel->getProcessors() + : $this->channel($channel)->getProcessors(); + })->all(); + + if ($config['ignore_exceptions'] ?? false) { + $handlers = [new WhatFailureGroupHandler($handlers)]; + } + + return new Monolog($this->parseChannel($config), $handlers, $processors); + } + + /** + * Create an instance of the single file log driver. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createSingleDriver(array $config) + { + return new Monolog($this->parseChannel($config), [ + $this->prepareHandler( + new StreamHandler( + $config['path'], $this->level($config), + $config['bubble'] ?? true, $config['permission'] ?? null, $config['locking'] ?? false + ), $config + ), + ]); + } + + /** + * Create an instance of the daily file log driver. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createDailyDriver(array $config) + { + return new Monolog($this->parseChannel($config), [ + $this->prepareHandler(new RotatingFileHandler( + $config['path'], $config['days'] ?? 7, $this->level($config), + $config['bubble'] ?? true, $config['permission'] ?? null, $config['locking'] ?? false + ), $config), + ]); + } + + /** + * Create an instance of the Slack log driver. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createSlackDriver(array $config) + { + return new Monolog($this->parseChannel($config), [ + $this->prepareHandler(new SlackWebhookHandler( + $config['url'], + $config['channel'] ?? null, + $config['username'] ?? 'Laravel', + $config['attachment'] ?? true, + $config['emoji'] ?? ':boom:', + $config['short'] ?? false, + $config['context'] ?? true, + $this->level($config), + $config['bubble'] ?? true, + $config['exclude_fields'] ?? [] + ), $config), + ]); + } + + /** + * Create an instance of the syslog log driver. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createSyslogDriver(array $config) + { + return new Monolog($this->parseChannel($config), [ + $this->prepareHandler(new SyslogHandler( + Str::snake($this->app['config']['app.name'], '-'), + $config['facility'] ?? LOG_USER, $this->level($config) + ), $config), + ]); + } + + /** + * Create an instance of the "error log" log driver. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + */ + protected function createErrorlogDriver(array $config) + { + return new Monolog($this->parseChannel($config), [ + $this->prepareHandler(new ErrorLogHandler( + $config['type'] ?? ErrorLogHandler::OPERATING_SYSTEM, $this->level($config) + )), + ]); + } + + /** + * Create an instance of any handler available in Monolog. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + * + * @throws \InvalidArgumentException + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function createMonologDriver(array $config) + { + if (! is_a($config['handler'], HandlerInterface::class, true)) { + throw new InvalidArgumentException( + $config['handler'].' must be an instance of '.HandlerInterface::class + ); + } + + $with = array_merge( + ['level' => $this->level($config)], + $config['with'] ?? [], + $config['handler_with'] ?? [] + ); + + return new Monolog($this->parseChannel($config), [$this->prepareHandler( + $this->app->make($config['handler'], $with), $config + )]); + } + + /** + * Prepare the handlers for usage by Monolog. + * + * @param array $handlers + * @return array + */ + protected function prepareHandlers(array $handlers) + { + foreach ($handlers as $key => $handler) { + $handlers[$key] = $this->prepareHandler($handler); + } + + return $handlers; + } + + /** + * Prepare the handler for usage by Monolog. + * + * @param \Monolog\Handler\HandlerInterface $handler + * @param array $config + * @return \Monolog\Handler\HandlerInterface + */ + protected function prepareHandler(HandlerInterface $handler, array $config = []) + { + if (isset($config['action_level'])) { + $handler = new FingersCrossedHandler($handler, $this->actionLevel($config)); + } + + if (Monolog::API !== 1 && (Monolog::API !== 2 || ! $handler instanceof FormattableHandlerInterface)) { + return $handler; + } + + if (! isset($config['formatter'])) { + $handler->setFormatter($this->formatter()); + } elseif ($config['formatter'] !== 'default') { + $handler->setFormatter($this->app->make($config['formatter'], $config['formatter_with'] ?? [])); + } + + return $handler; + } + + /** + * Get a Monolog formatter instance. + * + * @return \Monolog\Formatter\FormatterInterface + */ + protected function formatter() + { + return tap(new LineFormatter(null, $this->dateFormat, true, true), function ($formatter) { + $formatter->includeStacktraces(); + }); + } + + /** + * Get fallback log channel name. + * + * @return string + */ + protected function getFallbackChannelName() + { + return $this->app->bound('env') ? $this->app->environment() : 'production'; + } + + /** + * Get the log connection configuration. + * + * @param string $name + * @return array + */ + protected function configurationFor($name) + { + return $this->app['config']["logging.channels.{$name}"]; + } + + /** + * Get the default log driver name. + * + * @return string|null + */ + public function getDefaultDriver() + { + return $this->app['config']['logging.default']; + } + + /** + * Set the default log driver name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->app['config']['logging.default'] = $name; + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback->bindTo($this, $this); + + return $this; + } + + /** + * Unset the given channel instance. + * + * @param string|null $driver + * @return $this + */ + public function forgetChannel($driver = null) + { + $driver = $this->parseDriver($driver); + + if (isset($this->channels[$driver])) { + unset($this->channels[$driver]); + } + } + + /** + * Parse the driver name. + * + * @param string|null $driver + * @return string|null + */ + protected function parseDriver($driver) + { + $driver = $driver ?? $this->getDefaultDriver(); + + if ($this->app->runningUnitTests()) { + $driver = $driver ?? 'null'; + } + + return $driver; + } + + /** + * Get all of the resolved log channels. + * + * @return array + */ + public function getChannels() + { + return $this->channels; + } + + /** + * System is unusable. + * + * @param string $message + * @param array $context + * @return void + */ + public function emergency($message, array $context = []) + { + $this->driver()->emergency($message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string $message + * @param array $context + * @return void + */ + public function alert($message, array $context = []) + { + $this->driver()->alert($message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string $message + * @param array $context + * @return void + */ + public function critical($message, array $context = []) + { + $this->driver()->critical($message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string $message + * @param array $context + * @return void + */ + public function error($message, array $context = []) + { + $this->driver()->error($message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string $message + * @param array $context + * @return void + */ + public function warning($message, array $context = []) + { + $this->driver()->warning($message, $context); + } + + /** + * Normal but significant events. + * + * @param string $message + * @param array $context + * @return void + */ + public function notice($message, array $context = []) + { + $this->driver()->notice($message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function info($message, array $context = []) + { + $this->driver()->info($message, $context); + } + + /** + * Detailed debug information. + * + * @param string $message + * @param array $context + * @return void + */ + public function debug($message, array $context = []) + { + $this->driver()->debug($message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + * @return void + */ + public function log($level, $message, array $context = []) + { + $this->driver()->log($level, $message, $context); + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->driver()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LogServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LogServiceProvider.php new file mode 100644 index 0000000..ebe5453 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/LogServiceProvider.php @@ -0,0 +1,20 @@ +app->singleton('log', function ($app) { + return new LogManager($app); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/Logger.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/Logger.php new file mode 100755 index 0000000..382b77c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/Logger.php @@ -0,0 +1,310 @@ +logger = $logger; + $this->dispatcher = $dispatcher; + } + + /** + * Log an emergency message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function emergency($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log an alert message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function alert($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log a critical message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function critical($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log an error message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function error($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log a warning message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function warning($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log a notice to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function notice($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log an informational message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function info($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log a debug message to the logs. + * + * @param string $message + * @param array $context + * @return void + */ + public function debug($message, array $context = []) + { + $this->writeLog(__FUNCTION__, $message, $context); + } + + /** + * Log a message to the logs. + * + * @param string $level + * @param string $message + * @param array $context + * @return void + */ + public function log($level, $message, array $context = []) + { + $this->writeLog($level, $message, $context); + } + + /** + * Dynamically pass log calls into the writer. + * + * @param string $level + * @param string $message + * @param array $context + * @return void + */ + public function write($level, $message, array $context = []) + { + $this->writeLog($level, $message, $context); + } + + /** + * Write a message to the log. + * + * @param string $level + * @param string $message + * @param array $context + * @return void + */ + protected function writeLog($level, $message, $context) + { + $this->logger->{$level}( + $message = $this->formatMessage($message), + $context = array_merge($this->context, $context) + ); + + $this->fireLogEvent($level, $message, $context); + } + + /** + * Add context to all future logs. + * + * @param array $context + * @return $this + */ + public function withContext(array $context = []) + { + $this->context = array_merge($this->context, $context); + + return $this; + } + + /** + * Flush the existing context array. + * + * @return $this + */ + public function withoutContext() + { + $this->context = []; + + return $this; + } + + /** + * Register a new callback handler for when a log event is triggered. + * + * @param \Closure $callback + * @return void + * + * @throws \RuntimeException + */ + public function listen(Closure $callback) + { + if (! isset($this->dispatcher)) { + throw new RuntimeException('Events dispatcher has not been set.'); + } + + $this->dispatcher->listen(MessageLogged::class, $callback); + } + + /** + * Fires a log event. + * + * @param string $level + * @param string $message + * @param array $context + * @return void + */ + protected function fireLogEvent($level, $message, array $context = []) + { + // If the event dispatcher is set, we will pass along the parameters to the + // log listeners. These are useful for building profilers or other tools + // that aggregate all of the log messages for a given "request" cycle. + if (isset($this->dispatcher)) { + $this->dispatcher->dispatch(new MessageLogged($level, $message, $context)); + } + } + + /** + * Format the parameters for the logger. + * + * @param mixed $message + * @return mixed + */ + protected function formatMessage($message) + { + if (is_array($message)) { + return var_export($message, true); + } elseif ($message instanceof Jsonable) { + return $message->toJson(); + } elseif ($message instanceof Arrayable) { + return var_export($message->toArray(), true); + } + + return $message; + } + + /** + * Get the underlying logger implementation. + * + * @return \Psr\Log\LoggerInterface + */ + public function getLogger() + { + return $this->logger; + } + + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public function getEventDispatcher() + { + return $this->dispatcher; + } + + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher + * @return void + */ + public function setEventDispatcher(Dispatcher $dispatcher) + { + $this->dispatcher = $dispatcher; + } + + /** + * Dynamically proxy method calls to the underlying logger. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->logger->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/ParsesLogConfiguration.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/ParsesLogConfiguration.php new file mode 100644 index 0000000..fd0d5ed --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/ParsesLogConfiguration.php @@ -0,0 +1,79 @@ + Monolog::DEBUG, + 'info' => Monolog::INFO, + 'notice' => Monolog::NOTICE, + 'warning' => Monolog::WARNING, + 'error' => Monolog::ERROR, + 'critical' => Monolog::CRITICAL, + 'alert' => Monolog::ALERT, + 'emergency' => Monolog::EMERGENCY, + ]; + + /** + * Get fallback log channel name. + * + * @return string + */ + abstract protected function getFallbackChannelName(); + + /** + * Parse the string level into a Monolog constant. + * + * @param array $config + * @return int + * + * @throws \InvalidArgumentException + */ + protected function level(array $config) + { + $level = $config['level'] ?? 'debug'; + + if (isset($this->levels[$level])) { + return $this->levels[$level]; + } + + throw new InvalidArgumentException('Invalid log level.'); + } + + /** + * Parse the action level from the given configuration. + * + * @param array $config + * @return int + */ + protected function actionLevel(array $config) + { + $level = $config['action_level'] ?? 'debug'; + + if (isset($this->levels[$level])) { + return $this->levels[$level]; + } + + throw new InvalidArgumentException('Invalid log action level.'); + } + + /** + * Extract the log channel from the given configuration. + * + * @param array $config + * @return string + */ + protected function parseChannel(array $config) + { + return $config['name'] ?? $this->getFallbackChannelName(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/composer.json new file mode 100755 index 0000000..1fd148d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Log/composer.json @@ -0,0 +1,36 @@ +{ + "name": "illuminate/log", + "description": "The Illuminate Log package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/contracts": "^8.0", + "illuminate/support": "^8.0", + "monolog/monolog": "^2.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Log\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php new file mode 100644 index 0000000..2269142 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php @@ -0,0 +1,126 @@ +getMethods( + ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED + ); + + foreach ($methods as $method) { + if ($replace || ! static::hasMacro($method->name)) { + $method->setAccessible(true); + static::macro($method->name, $method->invoke($mixin)); + } + } + } + + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + */ + public static function hasMacro($name) + { + return isset(static::$macros[$name]); + } + + /** + * Flush the existing macros. + * + * @return void + */ + public static function flushMacros() + { + static::$macros = []; + } + + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public static function __callStatic($method, $parameters) + { + if (! static::hasMacro($method)) { + throw new BadMethodCallException(sprintf( + 'Method %s::%s does not exist.', static::class, $method + )); + } + + $macro = static::$macros[$method]; + + if ($macro instanceof Closure) { + $macro = $macro->bindTo(null, static::class); + } + + return $macro(...$parameters); + } + + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + if (! static::hasMacro($method)) { + throw new BadMethodCallException(sprintf( + 'Method %s::%s does not exist.', static::class, $method + )); + } + + $macro = static::$macros[$method]; + + if ($macro instanceof Closure) { + $macro = $macro->bindTo($this, static::class); + } + + return $macro(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/composer.json new file mode 100644 index 0000000..dfa5c62 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Macroable/composer.json @@ -0,0 +1,33 @@ +{ + "name": "illuminate/macroable", + "description": "The Illuminate Macroable package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Support\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Events/MessageSending.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Events/MessageSending.php new file mode 100644 index 0000000..bf5bccf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Events/MessageSending.php @@ -0,0 +1,33 @@ +data = $data; + $this->message = $message; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Events/MessageSent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Events/MessageSent.php new file mode 100644 index 0000000..64aef94 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Events/MessageSent.php @@ -0,0 +1,74 @@ +data = $data; + $this->message = $message; + } + + /** + * Get the serializable representation of the object. + * + * @return array + */ + public function __serialize() + { + $hasAttachments = collect($this->message->getChildren()) + ->whereInstanceOf(Swift_Attachment::class) + ->isNotEmpty(); + + return $hasAttachments ? [ + 'message' => base64_encode(serialize($this->message)), + 'data' => base64_encode(serialize($this->data)), + 'hasAttachments' => true, + ] : [ + 'message' => $this->message, + 'data' => $this->data, + 'hasAttachments' => false, + ]; + } + + /** + * Marshal the object from its serialized data. + * + * @param array $data + * @return void + */ + public function __unserialize(array $data) + { + if (isset($data['hasAttachments']) && $data['hasAttachments'] === true) { + $this->message = unserialize(base64_decode($data['message'])); + $this->data = unserialize(base64_decode($data['data'])); + } else { + $this->message = $data['message']; + $this->data = $data['data']; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php new file mode 100644 index 0000000..05d6d8e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php @@ -0,0 +1,552 @@ +app = $app; + } + + /** + * Get a mailer instance by name. + * + * @param string|null $name + * @return \Illuminate\Contracts\Mail\Mailer + */ + public function mailer($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + return $this->mailers[$name] = $this->get($name); + } + + /** + * Get a mailer driver instance. + * + * @param string|null $driver + * @return \Illuminate\Mail\Mailer + */ + public function driver($driver = null) + { + return $this->mailer($driver); + } + + /** + * Attempt to get the mailer from the local cache. + * + * @param string $name + * @return \Illuminate\Mail\Mailer + */ + protected function get($name) + { + return $this->mailers[$name] ?? $this->resolve($name); + } + + /** + * Resolve the given mailer. + * + * @param string $name + * @return \Illuminate\Mail\Mailer + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Mailer [{$name}] is not defined."); + } + + // Once we have created the mailer instance we will set a container instance + // on the mailer. This allows us to resolve mailer classes via containers + // for maximum testability on said classes instead of passing Closures. + $mailer = new Mailer( + $name, + $this->app['view'], + $this->createSwiftMailer($config), + $this->app['events'] + ); + + if ($this->app->bound('queue')) { + $mailer->setQueue($this->app['queue']); + } + + // Next we will set all of the global addresses on this mailer, which allows + // for easy unification of all "from" addresses as well as easy debugging + // of sent messages since these will be sent to a single email address. + foreach (['from', 'reply_to', 'to', 'return_path'] as $type) { + $this->setGlobalAddress($mailer, $config, $type); + } + + return $mailer; + } + + /** + * Create the SwiftMailer instance for the given configuration. + * + * @param array $config + * @return \Swift_Mailer + */ + protected function createSwiftMailer(array $config) + { + if ($config['domain'] ?? false) { + Swift_DependencyContainer::getInstance() + ->register('mime.idgenerator.idright') + ->asValue($config['domain']); + } + + return new Swift_Mailer($this->createTransport($config)); + } + + /** + * Create a new transport instance. + * + * @param array $config + * @return \Swift_Transport + * + * @throws \InvalidArgumentException + */ + public function createTransport(array $config) + { + // Here we will check if the "transport" key exists and if it doesn't we will + // assume an application is still using the legacy mail configuration file + // format and use the "mail.driver" configuration option instead for BC. + $transport = $config['transport'] ?? $this->app['config']['mail.driver']; + + if (isset($this->customCreators[$transport])) { + return call_user_func($this->customCreators[$transport], $config); + } + + if (trim($transport ?? '') === '' || ! method_exists($this, $method = 'create'.ucfirst($transport).'Transport')) { + throw new InvalidArgumentException("Unsupported mail transport [{$transport}]."); + } + + return $this->{$method}($config); + } + + /** + * Create an instance of the SMTP Swift Transport driver. + * + * @param array $config + * @return \Swift_SmtpTransport + */ + protected function createSmtpTransport(array $config) + { + // The Swift SMTP transport instance will allow us to use any SMTP backend + // for delivering mail such as Sendgrid, Amazon SES, or a custom server + // a developer has available. We will just pass this configured host. + $transport = new SmtpTransport( + $config['host'], + $config['port'] + ); + + if (! empty($config['encryption'])) { + $transport->setEncryption($config['encryption']); + } + + // Once we have the transport we will check for the presence of a username + // and password. If we have it we will set the credentials on the Swift + // transporter instance so that we'll properly authenticate delivery. + if (isset($config['username'])) { + $transport->setUsername($config['username']); + + $transport->setPassword($config['password']); + } + + return $this->configureSmtpTransport($transport, $config); + } + + /** + * Configure the additional SMTP driver options. + * + * @param \Swift_SmtpTransport $transport + * @param array $config + * @return \Swift_SmtpTransport + */ + protected function configureSmtpTransport($transport, array $config) + { + if (isset($config['stream'])) { + $transport->setStreamOptions($config['stream']); + } + + if (isset($config['source_ip'])) { + $transport->setSourceIp($config['source_ip']); + } + + if (isset($config['local_domain'])) { + $transport->setLocalDomain($config['local_domain']); + } + + if (isset($config['timeout'])) { + $transport->setTimeout($config['timeout']); + } + + if (isset($config['auth_mode'])) { + $transport->setAuthMode($config['auth_mode']); + } + + return $transport; + } + + /** + * Create an instance of the Sendmail Swift Transport driver. + * + * @param array $config + * @return \Swift_SendmailTransport + */ + protected function createSendmailTransport(array $config) + { + return new SendmailTransport( + $config['path'] ?? $this->app['config']->get('mail.sendmail') + ); + } + + /** + * Create an instance of the Amazon SES Swift Transport driver. + * + * @param array $config + * @return \Illuminate\Mail\Transport\SesTransport + */ + protected function createSesTransport(array $config) + { + $config = array_merge( + $this->app['config']->get('services.ses', []), + ['version' => 'latest', 'service' => 'email'], + $config + ); + + $config = Arr::except($config, ['transport']); + + return new SesTransport( + new SesClient($this->addSesCredentials($config)), + $config['options'] ?? [] + ); + } + + /** + * Add the SES credentials to the configuration array. + * + * @param array $config + * @return array + */ + protected function addSesCredentials(array $config) + { + if (! empty($config['key']) && ! empty($config['secret'])) { + $config['credentials'] = Arr::only($config, ['key', 'secret', 'token']); + } + + return $config; + } + + /** + * Create an instance of the Mail Swift Transport driver. + * + * @return \Swift_SendmailTransport + */ + protected function createMailTransport() + { + return new SendmailTransport; + } + + /** + * Create an instance of the Mailgun Swift Transport driver. + * + * @param array $config + * @return \Illuminate\Mail\Transport\MailgunTransport + */ + protected function createMailgunTransport(array $config) + { + if (! isset($config['secret'])) { + $config = $this->app['config']->get('services.mailgun', []); + } + + return new MailgunTransport( + $this->guzzle($config), + $config['secret'], + $config['domain'], + $config['endpoint'] ?? null + ); + } + + /** + * Create an instance of the Postmark Swift Transport driver. + * + * @param array $config + * @return \Swift_Transport + */ + protected function createPostmarkTransport(array $config) + { + $headers = isset($config['message_stream_id']) ? [ + 'X-PM-Message-Stream' => $config['message_stream_id'], + ] : []; + + return tap(new PostmarkTransport( + $config['token'] ?? $this->app['config']->get('services.postmark.token'), + $headers + ), function ($transport) { + $transport->registerPlugin(new ThrowExceptionOnFailurePlugin); + }); + } + + /** + * Create an instance of the Failover Swift Transport driver. + * + * @param array $config + * @return \Swift_FailoverTransport + */ + protected function createFailoverTransport(array $config) + { + $transports = []; + + foreach ($config['mailers'] as $name) { + $config = $this->getConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Mailer [{$name}] is not defined."); + } + + // Now, we will check if the "driver" key exists and if it does we will set + // the transport configuration parameter in order to offer compatibility + // with any Laravel <= 6.x application style mail configuration files. + $transports[] = $this->app['config']['mail.driver'] + ? $this->createTransport(array_merge($config, ['transport' => $name])) + : $this->createTransport($config); + } + + return new FailoverTransport($transports); + } + + /** + * Create an instance of the Log Swift Transport driver. + * + * @param array $config + * @return \Illuminate\Mail\Transport\LogTransport + */ + protected function createLogTransport(array $config) + { + $logger = $this->app->make(LoggerInterface::class); + + if ($logger instanceof LogManager) { + $logger = $logger->channel( + $config['channel'] ?? $this->app['config']->get('mail.log_channel') + ); + } + + return new LogTransport($logger); + } + + /** + * Create an instance of the Array Swift Transport Driver. + * + * @return \Illuminate\Mail\Transport\ArrayTransport + */ + protected function createArrayTransport() + { + return new ArrayTransport; + } + + /** + * Get a fresh Guzzle HTTP client instance. + * + * @param array $config + * @return \GuzzleHttp\Client + */ + protected function guzzle(array $config) + { + return new HttpClient(Arr::add( + $config['guzzle'] ?? [], + 'connect_timeout', + 60 + )); + } + + /** + * Set a global address on the mailer by type. + * + * @param \Illuminate\Mail\Mailer $mailer + * @param array $config + * @param string $type + * @return void + */ + protected function setGlobalAddress($mailer, array $config, string $type) + { + $address = Arr::get($config, $type, $this->app['config']['mail.'.$type]); + + if (is_array($address) && isset($address['address'])) { + $mailer->{'always'.Str::studly($type)}($address['address'], $address['name']); + } + } + + /** + * Get the mail connection configuration. + * + * @param string $name + * @return array + */ + protected function getConfig(string $name) + { + // Here we will check if the "driver" key exists and if it does we will use + // the entire mail configuration file as the "driver" config in order to + // provide "BC" for any Laravel <= 6.x style mail configuration files. + return $this->app['config']['mail.driver'] + ? $this->app['config']['mail'] + : $this->app['config']["mail.mailers.{$name}"]; + } + + /** + * Get the default mail driver name. + * + * @return string + */ + public function getDefaultDriver() + { + // Here we will check if the "driver" key exists and if it does we will use + // that as the default driver in order to provide support for old styles + // of the Laravel mail configuration file for backwards compatibility. + return $this->app['config']['mail.driver'] ?? + $this->app['config']['mail.default']; + } + + /** + * Set the default mail driver name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver(string $name) + { + if ($this->app['config']['mail.driver']) { + $this->app['config']['mail.driver'] = $name; + } + + $this->app['config']['mail.default'] = $name; + } + + /** + * Disconnect the given mailer and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + unset($this->mailers[$name]); + } + + /** + * Register a custom transport creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback; + + return $this; + } + + /** + * Get the application instance used by the manager. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public function getApplication() + { + return $this->app; + } + + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication($app) + { + $this->app = $app; + + return $this; + } + + /** + * Forget all of the resolved mailer instances. + * + * @return $this + */ + public function forgetMailers() + { + $this->mailers = []; + + return $this; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->mailer()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/MailServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/MailServiceProvider.php new file mode 100755 index 0000000..d4f4682 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/MailServiceProvider.php @@ -0,0 +1,73 @@ +registerIlluminateMailer(); + $this->registerMarkdownRenderer(); + } + + /** + * Register the Illuminate mailer instance. + * + * @return void + */ + protected function registerIlluminateMailer() + { + $this->app->singleton('mail.manager', function ($app) { + return new MailManager($app); + }); + + $this->app->bind('mailer', function ($app) { + return $app->make('mail.manager')->mailer(); + }); + } + + /** + * Register the Markdown renderer instance. + * + * @return void + */ + protected function registerMarkdownRenderer() + { + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__.'/resources/views' => $this->app->resourcePath('views/vendor/mail'), + ], 'laravel-mail'); + } + + $this->app->singleton(Markdown::class, function ($app) { + $config = $app->make('config'); + + return new Markdown($app->make('view'), [ + 'theme' => $config->get('mail.markdown.theme', 'default'), + 'paths' => $config->get('mail.markdown.paths', []), + ]); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + 'mail.manager', + 'mailer', + Markdown::class, + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php new file mode 100644 index 0000000..3df0074 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php @@ -0,0 +1,1031 @@ +withLocale($this->locale, function () use ($mailer) { + Container::getInstance()->call([$this, 'build']); + + $mailer = $mailer instanceof MailFactory + ? $mailer->mailer($this->mailer) + : $mailer; + + return $mailer->send($this->buildView(), $this->buildViewData(), function ($message) { + $this->buildFrom($message) + ->buildRecipients($message) + ->buildSubject($message) + ->runCallbacks($message) + ->buildAttachments($message); + }); + }); + } + + /** + * Queue the message for sending. + * + * @param \Illuminate\Contracts\Queue\Factory $queue + * @return mixed + */ + public function queue(Queue $queue) + { + if (isset($this->delay)) { + return $this->later($this->delay, $queue); + } + + $connection = property_exists($this, 'connection') ? $this->connection : null; + + $queueName = property_exists($this, 'queue') ? $this->queue : null; + + return $queue->connection($connection)->pushOn( + $queueName ?: null, $this->newQueuedJob() + ); + } + + /** + * Deliver the queued message after the given delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param \Illuminate\Contracts\Queue\Factory $queue + * @return mixed + */ + public function later($delay, Queue $queue) + { + $connection = property_exists($this, 'connection') ? $this->connection : null; + + $queueName = property_exists($this, 'queue') ? $this->queue : null; + + return $queue->connection($connection)->laterOn( + $queueName ?: null, $delay, $this->newQueuedJob() + ); + } + + /** + * Make the queued mailable job instance. + * + * @return mixed + */ + protected function newQueuedJob() + { + return (new SendQueuedMailable($this)) + ->through(array_merge( + method_exists($this, 'middleware') ? $this->middleware() : [], + $this->middleware ?? [] + )); + } + + /** + * Render the mailable into a view. + * + * @return string + * + * @throws \ReflectionException + */ + public function render() + { + return $this->withLocale($this->locale, function () { + Container::getInstance()->call([$this, 'build']); + + return Container::getInstance()->make('mailer')->render( + $this->buildView(), $this->buildViewData() + ); + }); + } + + /** + * Build the view for the message. + * + * @return array|string + * + * @throws \ReflectionException + */ + protected function buildView() + { + if (isset($this->html)) { + return array_filter([ + 'html' => new HtmlString($this->html), + 'text' => $this->textView ?? null, + ]); + } + + if (isset($this->markdown)) { + return $this->buildMarkdownView(); + } + + if (isset($this->view, $this->textView)) { + return [$this->view, $this->textView]; + } elseif (isset($this->textView)) { + return ['text' => $this->textView]; + } + + return $this->view; + } + + /** + * Build the Markdown view for the message. + * + * @return array + * + * @throws \ReflectionException + */ + protected function buildMarkdownView() + { + $markdown = Container::getInstance()->make(Markdown::class); + + if (isset($this->theme)) { + $markdown->theme($this->theme); + } + + $data = $this->buildViewData(); + + return [ + 'html' => $markdown->render($this->markdown, $data), + 'text' => $this->buildMarkdownText($markdown, $data), + ]; + } + + /** + * Build the view data for the message. + * + * @return array + * + * @throws \ReflectionException + */ + public function buildViewData() + { + $data = $this->viewData; + + if (static::$viewDataCallback) { + $data = array_merge($data, call_user_func(static::$viewDataCallback, $this)); + } + + foreach ((new ReflectionClass($this))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + if ($property->getDeclaringClass()->getName() !== self::class) { + $data[$property->getName()] = $property->getValue($this); + } + } + + return $data; + } + + /** + * Build the text view for a Markdown message. + * + * @param \Illuminate\Mail\Markdown $markdown + * @param array $data + * @return string + */ + protected function buildMarkdownText($markdown, $data) + { + return $this->textView + ?? $markdown->renderText($this->markdown, $data); + } + + /** + * Add the sender to the message. + * + * @param \Illuminate\Mail\Message $message + * @return $this + */ + protected function buildFrom($message) + { + if (! empty($this->from)) { + $message->from($this->from[0]['address'], $this->from[0]['name']); + } + + return $this; + } + + /** + * Add all of the recipients to the message. + * + * @param \Illuminate\Mail\Message $message + * @return $this + */ + protected function buildRecipients($message) + { + foreach (['to', 'cc', 'bcc', 'replyTo'] as $type) { + foreach ($this->{$type} as $recipient) { + $message->{$type}($recipient['address'], $recipient['name']); + } + } + + return $this; + } + + /** + * Set the subject for the message. + * + * @param \Illuminate\Mail\Message $message + * @return $this + */ + protected function buildSubject($message) + { + if ($this->subject) { + $message->subject($this->subject); + } else { + $message->subject(Str::title(Str::snake(class_basename($this), ' '))); + } + + return $this; + } + + /** + * Add all of the attachments to the message. + * + * @param \Illuminate\Mail\Message $message + * @return $this + */ + protected function buildAttachments($message) + { + foreach ($this->attachments as $attachment) { + $message->attach($attachment['file'], $attachment['options']); + } + + foreach ($this->rawAttachments as $attachment) { + $message->attachData( + $attachment['data'], $attachment['name'], $attachment['options'] + ); + } + + $this->buildDiskAttachments($message); + + return $this; + } + + /** + * Add all of the disk attachments to the message. + * + * @param \Illuminate\Mail\Message $message + * @return void + */ + protected function buildDiskAttachments($message) + { + foreach ($this->diskAttachments as $attachment) { + $storage = Container::getInstance()->make( + FilesystemFactory::class + )->disk($attachment['disk']); + + $message->attachData( + $storage->get($attachment['path']), + $attachment['name'] ?? basename($attachment['path']), + array_merge(['mime' => $storage->mimeType($attachment['path'])], $attachment['options']) + ); + } + } + + /** + * Run the callbacks for the message. + * + * @param \Illuminate\Mail\Message $message + * @return $this + */ + protected function runCallbacks($message) + { + foreach ($this->callbacks as $callback) { + $callback($message->getSwiftMessage()); + } + + return $this; + } + + /** + * Set the locale of the message. + * + * @param string $locale + * @return $this + */ + public function locale($locale) + { + $this->locale = $locale; + + return $this; + } + + /** + * Set the priority of this message. + * + * The value is an integer where 1 is the highest priority and 5 is the lowest. + * + * @param int $level + * @return $this + */ + public function priority($level = 3) + { + $this->callbacks[] = function ($message) use ($level) { + $message->setPriority($level); + }; + + return $this; + } + + /** + * Set the sender of the message. + * + * @param object|array|string $address + * @param string|null $name + * @return $this + */ + public function from($address, $name = null) + { + return $this->setAddress($address, $name, 'from'); + } + + /** + * Determine if the given recipient is set on the mailable. + * + * @param object|array|string $address + * @param string|null $name + * @return bool + */ + public function hasFrom($address, $name = null) + { + return $this->hasRecipient($address, $name, 'from'); + } + + /** + * Set the recipients of the message. + * + * @param object|array|string $address + * @param string|null $name + * @return $this + */ + public function to($address, $name = null) + { + return $this->setAddress($address, $name, 'to'); + } + + /** + * Determine if the given recipient is set on the mailable. + * + * @param object|array|string $address + * @param string|null $name + * @return bool + */ + public function hasTo($address, $name = null) + { + return $this->hasRecipient($address, $name, 'to'); + } + + /** + * Set the recipients of the message. + * + * @param object|array|string $address + * @param string|null $name + * @return $this + */ + public function cc($address, $name = null) + { + return $this->setAddress($address, $name, 'cc'); + } + + /** + * Determine if the given recipient is set on the mailable. + * + * @param object|array|string $address + * @param string|null $name + * @return bool + */ + public function hasCc($address, $name = null) + { + return $this->hasRecipient($address, $name, 'cc'); + } + + /** + * Set the recipients of the message. + * + * @param object|array|string $address + * @param string|null $name + * @return $this + */ + public function bcc($address, $name = null) + { + return $this->setAddress($address, $name, 'bcc'); + } + + /** + * Determine if the given recipient is set on the mailable. + * + * @param object|array|string $address + * @param string|null $name + * @return bool + */ + public function hasBcc($address, $name = null) + { + return $this->hasRecipient($address, $name, 'bcc'); + } + + /** + * Set the "reply to" address of the message. + * + * @param object|array|string $address + * @param string|null $name + * @return $this + */ + public function replyTo($address, $name = null) + { + return $this->setAddress($address, $name, 'replyTo'); + } + + /** + * Determine if the given replyTo is set on the mailable. + * + * @param object|array|string $address + * @param string|null $name + * @return bool + */ + public function hasReplyTo($address, $name = null) + { + return $this->hasRecipient($address, $name, 'replyTo'); + } + + /** + * Set the recipients of the message. + * + * All recipients are stored internally as [['name' => ?, 'address' => ?]] + * + * @param object|array|string $address + * @param string|null $name + * @param string $property + * @return $this + */ + protected function setAddress($address, $name = null, $property = 'to') + { + if (empty($address)) { + return $this; + } + + foreach ($this->addressesToArray($address, $name) as $recipient) { + $recipient = $this->normalizeRecipient($recipient); + + $this->{$property}[] = [ + 'name' => $recipient->name ?? null, + 'address' => $recipient->email, + ]; + } + + return $this; + } + + /** + * Convert the given recipient arguments to an array. + * + * @param object|array|string $address + * @param string|null $name + * @return array + */ + protected function addressesToArray($address, $name) + { + if (! is_array($address) && ! $address instanceof Collection) { + $address = is_string($name) ? [['name' => $name, 'email' => $address]] : [$address]; + } + + return $address; + } + + /** + * Convert the given recipient into an object. + * + * @param mixed $recipient + * @return object + */ + protected function normalizeRecipient($recipient) + { + if (is_array($recipient)) { + if (array_values($recipient) === $recipient) { + return (object) array_map(function ($email) { + return compact('email'); + }, $recipient); + } + + return (object) $recipient; + } elseif (is_string($recipient)) { + return (object) ['email' => $recipient]; + } + + return $recipient; + } + + /** + * Determine if the given recipient is set on the mailable. + * + * @param object|array|string $address + * @param string|null $name + * @param string $property + * @return bool + */ + protected function hasRecipient($address, $name = null, $property = 'to') + { + if (empty($address)) { + return false; + } + + $expected = $this->normalizeRecipient( + $this->addressesToArray($address, $name)[0] + ); + + $expected = [ + 'name' => $expected->name ?? null, + 'address' => $expected->email, + ]; + + return collect($this->{$property})->contains(function ($actual) use ($expected) { + if (! isset($expected['name'])) { + return $actual['address'] == $expected['address']; + } + + return $actual == $expected; + }); + } + + /** + * Set the subject of the message. + * + * @param string $subject + * @return $this + */ + public function subject($subject) + { + $this->subject = $subject; + + return $this; + } + + /** + * Set the Markdown template for the message. + * + * @param string $view + * @param array $data + * @return $this + */ + public function markdown($view, array $data = []) + { + $this->markdown = $view; + $this->viewData = array_merge($this->viewData, $data); + + return $this; + } + + /** + * Set the view and view data for the message. + * + * @param string $view + * @param array $data + * @return $this + */ + public function view($view, array $data = []) + { + $this->view = $view; + $this->viewData = array_merge($this->viewData, $data); + + return $this; + } + + /** + * Set the rendered HTML content for the message. + * + * @param string $html + * @return $this + */ + public function html($html) + { + $this->html = $html; + + return $this; + } + + /** + * Set the plain text view for the message. + * + * @param string $textView + * @param array $data + * @return $this + */ + public function text($textView, array $data = []) + { + $this->textView = $textView; + $this->viewData = array_merge($this->viewData, $data); + + return $this; + } + + /** + * Set the view data for the message. + * + * @param string|array $key + * @param mixed $value + * @return $this + */ + public function with($key, $value = null) + { + if (is_array($key)) { + $this->viewData = array_merge($this->viewData, $key); + } else { + $this->viewData[$key] = $value; + } + + return $this; + } + + /** + * Attach a file to the message. + * + * @param string $file + * @param array $options + * @return $this + */ + public function attach($file, array $options = []) + { + $this->attachments = collect($this->attachments) + ->push(compact('file', 'options')) + ->unique('file') + ->all(); + + return $this; + } + + /** + * Attach a file to the message from storage. + * + * @param string $path + * @param string|null $name + * @param array $options + * @return $this + */ + public function attachFromStorage($path, $name = null, array $options = []) + { + return $this->attachFromStorageDisk(null, $path, $name, $options); + } + + /** + * Attach a file to the message from storage. + * + * @param string $disk + * @param string $path + * @param string|null $name + * @param array $options + * @return $this + */ + public function attachFromStorageDisk($disk, $path, $name = null, array $options = []) + { + $this->diskAttachments = collect($this->diskAttachments)->push([ + 'disk' => $disk, + 'path' => $path, + 'name' => $name ?? basename($path), + 'options' => $options, + ])->unique(function ($file) { + return $file['name'].$file['disk'].$file['path']; + })->all(); + + return $this; + } + + /** + * Attach in-memory data as an attachment. + * + * @param string $data + * @param string $name + * @param array $options + * @return $this + */ + public function attachData($data, $name, array $options = []) + { + $this->rawAttachments = collect($this->rawAttachments) + ->push(compact('data', 'name', 'options')) + ->unique(function ($file) { + return $file['name'].$file['data']; + })->all(); + + return $this; + } + + /** + * Assert that the given text is present in the HTML email body. + * + * @param string $string + * @return $this + */ + public function assertSeeInHtml($string) + { + [$html, $text] = $this->renderForAssertions(); + + PHPUnit::assertTrue( + Str::contains($html, $string), + "Did not see expected text [{$string}] within email body." + ); + + return $this; + } + + /** + * Assert that the given text is not present in the HTML email body. + * + * @param string $string + * @return $this + */ + public function assertDontSeeInHtml($string) + { + [$html, $text] = $this->renderForAssertions(); + + PHPUnit::assertFalse( + Str::contains($html, $string), + "Saw unexpected text [{$string}] within email body." + ); + + return $this; + } + + /** + * Assert that the given text is present in the plain-text email body. + * + * @param string $string + * @return $this + */ + public function assertSeeInText($string) + { + [$html, $text] = $this->renderForAssertions(); + + PHPUnit::assertTrue( + Str::contains($text, $string), + "Did not see expected text [{$string}] within text email body." + ); + + return $this; + } + + /** + * Assert that the given text is not present in the plain-text email body. + * + * @param string $string + * @return $this + */ + public function assertDontSeeInText($string) + { + [$html, $text] = $this->renderForAssertions(); + + PHPUnit::assertFalse( + Str::contains($text, $string), + "Saw unexpected text [{$string}] within text email body." + ); + + return $this; + } + + /** + * Render the HTML and plain-text version of the mailable into views for assertions. + * + * @return array + * + * @throws \ReflectionException + */ + protected function renderForAssertions() + { + if ($this->assertionableRenderStrings) { + return $this->assertionableRenderStrings; + } + + return $this->assertionableRenderStrings = $this->withLocale($this->locale, function () { + Container::getInstance()->call([$this, 'build']); + + $html = Container::getInstance()->make('mailer')->render( + $view = $this->buildView(), $this->buildViewData() + ); + + if (is_array($view) && isset($view[1])) { + $text = $view[1]; + } + + $text = $text ?? $view['text'] ?? ''; + + if (! empty($text) && ! $text instanceof Htmlable) { + $text = Container::getInstance()->make('mailer')->render( + $text, $this->buildViewData() + ); + } + + return [(string) $html, (string) $text]; + }); + } + + /** + * Set the name of the mailer that should send the message. + * + * @param string $mailer + * @return $this + */ + public function mailer($mailer) + { + $this->mailer = $mailer; + + return $this; + } + + /** + * Register a callback to be called with the Swift message instance. + * + * @param callable $callback + * @return $this + */ + public function withSwiftMessage($callback) + { + $this->callbacks[] = $callback; + + return $this; + } + + /** + * Register a callback to be called while building the view data. + * + * @param callable $callback + * @return void + */ + public static function buildViewDataUsing(callable $callback) + { + static::$viewDataCallback = $callback; + } + + /** + * Dynamically bind parameters to the message. + * + * @param string $method + * @param array $parameters + * @return $this + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + if (Str::startsWith($method, 'with')) { + return $this->with(Str::camel(substr($method, 4)), $parameters[0]); + } + + static::throwBadMethodCallException($method); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php new file mode 100755 index 0000000..128f211 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php @@ -0,0 +1,626 @@ +name = $name; + $this->views = $views; + $this->swift = $swift; + $this->events = $events; + } + + /** + * Set the global from address and name. + * + * @param string $address + * @param string|null $name + * @return void + */ + public function alwaysFrom($address, $name = null) + { + $this->from = compact('address', 'name'); + } + + /** + * Set the global reply-to address and name. + * + * @param string $address + * @param string|null $name + * @return void + */ + public function alwaysReplyTo($address, $name = null) + { + $this->replyTo = compact('address', 'name'); + } + + /** + * Set the global return path address. + * + * @param string $address + * @return void + */ + public function alwaysReturnPath($address) + { + $this->returnPath = compact('address'); + } + + /** + * Set the global to address and name. + * + * @param string $address + * @param string|null $name + * @return void + */ + public function alwaysTo($address, $name = null) + { + $this->to = compact('address', 'name'); + } + + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + */ + public function to($users) + { + return (new PendingMail($this))->to($users); + } + + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + */ + public function cc($users) + { + return (new PendingMail($this))->cc($users); + } + + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + */ + public function bcc($users) + { + return (new PendingMail($this))->bcc($users); + } + + /** + * Send a new message with only an HTML part. + * + * @param string $html + * @param mixed $callback + * @return void + */ + public function html($html, $callback) + { + $this->send(['html' => new HtmlString($html)], [], $callback); + } + + /** + * Send a new message with only a raw text part. + * + * @param string $text + * @param mixed $callback + * @return void + */ + public function raw($text, $callback) + { + $this->send(['raw' => $text], [], $callback); + } + + /** + * Send a new message with only a plain part. + * + * @param string $view + * @param array $data + * @param mixed $callback + * @return void + */ + public function plain($view, array $data, $callback) + { + $this->send(['text' => $view], $data, $callback); + } + + /** + * Render the given message as a view. + * + * @param string|array $view + * @param array $data + * @return string + */ + public function render($view, array $data = []) + { + // First we need to parse the view, which could either be a string or an array + // containing both an HTML and plain text versions of the view which should + // be used when sending an e-mail. We will extract both of them out here. + [$view, $plain, $raw] = $this->parseView($view); + + $data['message'] = $this->createMessage(); + + return $this->renderView($view ?: $plain, $data); + } + + /** + * Send a new message using a view. + * + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param array $data + * @param \Closure|string|null $callback + * @return void + */ + public function send($view, array $data = [], $callback = null) + { + if ($view instanceof MailableContract) { + return $this->sendMailable($view); + } + + // First we need to parse the view, which could either be a string or an array + // containing both an HTML and plain text versions of the view which should + // be used when sending an e-mail. We will extract both of them out here. + [$view, $plain, $raw] = $this->parseView($view); + + $data['message'] = $message = $this->createMessage(); + + // Once we have retrieved the view content for the e-mail we will set the body + // of this message using the HTML type, which will provide a simple wrapper + // to creating view based emails that are able to receive arrays of data. + $callback($message); + + $this->addContent($message, $view, $plain, $raw, $data); + + // If a global "to" address has been set, we will set that address on the mail + // message. This is primarily useful during local development in which each + // message should be delivered into a single mail address for inspection. + if (isset($this->to['address'])) { + $this->setGlobalToAndRemoveCcAndBcc($message); + } + + // Next we will determine if the message should be sent. We give the developer + // one final chance to stop this message and then we will send it to all of + // its recipients. We will then fire the sent event for the sent message. + $swiftMessage = $message->getSwiftMessage(); + + if ($this->shouldSendMessage($swiftMessage, $data)) { + $this->sendSwiftMessage($swiftMessage); + + $this->dispatchSentEvent($message, $data); + } + } + + /** + * Send the given mailable. + * + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return mixed + */ + protected function sendMailable(MailableContract $mailable) + { + return $mailable instanceof ShouldQueue + ? $mailable->mailer($this->name)->queue($this->queue) + : $mailable->mailer($this->name)->send($this); + } + + /** + * Parse the given view name or array. + * + * @param string|array $view + * @return array + * + * @throws \InvalidArgumentException + */ + protected function parseView($view) + { + if (is_string($view)) { + return [$view, null, null]; + } + + // If the given view is an array with numeric keys, we will just assume that + // both a "pretty" and "plain" view were provided, so we will return this + // array as is, since it should contain both views with numerical keys. + if (is_array($view) && isset($view[0])) { + return [$view[0], $view[1], null]; + } + + // If this view is an array but doesn't contain numeric keys, we will assume + // the views are being explicitly specified and will extract them via the + // named keys instead, allowing the developers to use one or the other. + if (is_array($view)) { + return [ + $view['html'] ?? null, + $view['text'] ?? null, + $view['raw'] ?? null, + ]; + } + + throw new InvalidArgumentException('Invalid view.'); + } + + /** + * Add the content to a given message. + * + * @param \Illuminate\Mail\Message $message + * @param string $view + * @param string $plain + * @param string $raw + * @param array $data + * @return void + */ + protected function addContent($message, $view, $plain, $raw, $data) + { + if (isset($view)) { + $message->setBody($this->renderView($view, $data) ?: ' ', 'text/html'); + } + + if (isset($plain)) { + $method = isset($view) ? 'addPart' : 'setBody'; + + $message->$method($this->renderView($plain, $data) ?: ' ', 'text/plain'); + } + + if (isset($raw)) { + $method = (isset($view) || isset($plain)) ? 'addPart' : 'setBody'; + + $message->$method($raw, 'text/plain'); + } + } + + /** + * Render the given view. + * + * @param string $view + * @param array $data + * @return string + */ + protected function renderView($view, $data) + { + return $view instanceof Htmlable + ? $view->toHtml() + : $this->views->make($view, $data)->render(); + } + + /** + * Set the global "to" address on the given message. + * + * @param \Illuminate\Mail\Message $message + * @return void + */ + protected function setGlobalToAndRemoveCcAndBcc($message) + { + $message->to($this->to['address'], $this->to['name'], true); + $message->cc(null, null, true); + $message->bcc(null, null, true); + } + + /** + * Queue a new e-mail message for sending. + * + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param string|null $queue + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function queue($view, $queue = null) + { + if (! $view instanceof MailableContract) { + throw new InvalidArgumentException('Only mailables may be queued.'); + } + + if (is_string($queue)) { + $view->onQueue($queue); + } + + return $view->mailer($this->name)->queue($this->queue); + } + + /** + * Queue a new e-mail message for sending on the given queue. + * + * @param string $queue + * @param \Illuminate\Contracts\Mail\Mailable $view + * @return mixed + */ + public function onQueue($queue, $view) + { + return $this->queue($view, $queue); + } + + /** + * Queue a new e-mail message for sending on the given queue. + * + * This method didn't match rest of framework's "onQueue" phrasing. Added "onQueue". + * + * @param string $queue + * @param \Illuminate\Contracts\Mail\Mailable $view + * @return mixed + */ + public function queueOn($queue, $view) + { + return $this->onQueue($queue, $view); + } + + /** + * Queue a new e-mail message for sending after (n) seconds. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param \Illuminate\Contracts\Mail\Mailable $view + * @param string|null $queue + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function later($delay, $view, $queue = null) + { + if (! $view instanceof MailableContract) { + throw new InvalidArgumentException('Only mailables may be queued.'); + } + + return $view->mailer($this->name)->later( + $delay, is_null($queue) ? $this->queue : $queue + ); + } + + /** + * Queue a new e-mail message for sending after (n) seconds on the given queue. + * + * @param string $queue + * @param \DateTimeInterface|\DateInterval|int $delay + * @param \Illuminate\Contracts\Mail\Mailable $view + * @return mixed + */ + public function laterOn($queue, $delay, $view) + { + return $this->later($delay, $view, $queue); + } + + /** + * Create a new message instance. + * + * @return \Illuminate\Mail\Message + */ + protected function createMessage() + { + $message = new Message($this->swift->createMessage('message')); + + // If a global from address has been specified we will set it on every message + // instance so the developer does not have to repeat themselves every time + // they create a new message. We'll just go ahead and push this address. + if (! empty($this->from['address'])) { + $message->from($this->from['address'], $this->from['name']); + } + + // When a global reply address was specified we will set this on every message + // instance so the developer does not have to repeat themselves every time + // they create a new message. We will just go ahead and push this address. + if (! empty($this->replyTo['address'])) { + $message->replyTo($this->replyTo['address'], $this->replyTo['name']); + } + + if (! empty($this->returnPath['address'])) { + $message->returnPath($this->returnPath['address']); + } + + return $message; + } + + /** + * Send a Swift Message instance. + * + * @param \Swift_Message $message + * @return int|null + */ + protected function sendSwiftMessage($message) + { + $this->failedRecipients = []; + + try { + return $this->swift->send($message, $this->failedRecipients); + } finally { + $this->forceReconnection(); + } + } + + /** + * Determines if the message can be sent. + * + * @param \Swift_Message $message + * @param array $data + * @return bool + */ + protected function shouldSendMessage($message, $data = []) + { + if (! $this->events) { + return true; + } + + return $this->events->until( + new MessageSending($message, $data) + ) !== false; + } + + /** + * Dispatch the message sent event. + * + * @param \Illuminate\Mail\Message $message + * @param array $data + * @return void + */ + protected function dispatchSentEvent($message, $data = []) + { + if ($this->events) { + $this->events->dispatch( + new MessageSent($message->getSwiftMessage(), $data) + ); + } + } + + /** + * Force the transport to re-connect. + * + * This will prevent errors in daemon queue situations. + * + * @return void + */ + protected function forceReconnection() + { + $this->getSwiftMailer()->getTransport()->stop(); + } + + /** + * Get the array of failed recipients. + * + * @return array + */ + public function failures() + { + return $this->failedRecipients; + } + + /** + * Get the Swift Mailer instance. + * + * @return \Swift_Mailer + */ + public function getSwiftMailer() + { + return $this->swift; + } + + /** + * Get the view factory instance. + * + * @return \Illuminate\Contracts\View\Factory + */ + public function getViewFactory() + { + return $this->views; + } + + /** + * Set the Swift Mailer instance. + * + * @param \Swift_Mailer $swift + * @return void + */ + public function setSwiftMailer($swift) + { + $this->swift = $swift; + } + + /** + * Set the queue manager instance. + * + * @param \Illuminate\Contracts\Queue\Factory $queue + * @return $this + */ + public function setQueue(QueueContract $queue) + { + $this->queue = $queue; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Markdown.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Markdown.php new file mode 100644 index 0000000..9bd0836 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Markdown.php @@ -0,0 +1,184 @@ +view = $view; + $this->theme = $options['theme'] ?? 'default'; + $this->loadComponentsFrom($options['paths'] ?? []); + } + + /** + * Render the Markdown template into HTML. + * + * @param string $view + * @param array $data + * @param \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles|null $inliner + * @return \Illuminate\Support\HtmlString + */ + public function render($view, array $data = [], $inliner = null) + { + $this->view->flushFinderCache(); + + $contents = $this->view->replaceNamespace( + 'mail', $this->htmlComponentPaths() + )->make($view, $data)->render(); + + if ($this->view->exists($customTheme = Str::start($this->theme, 'mail.'))) { + $theme = $customTheme; + } else { + $theme = Str::contains($this->theme, '::') + ? $this->theme + : 'mail::themes.'.$this->theme; + } + + return new HtmlString(($inliner ?: new CssToInlineStyles)->convert( + $contents, $this->view->make($theme, $data)->render() + )); + } + + /** + * Render the Markdown template into text. + * + * @param string $view + * @param array $data + * @return \Illuminate\Support\HtmlString + */ + public function renderText($view, array $data = []) + { + $this->view->flushFinderCache(); + + $contents = $this->view->replaceNamespace( + 'mail', $this->textComponentPaths() + )->make($view, $data)->render(); + + return new HtmlString( + html_entity_decode(preg_replace("/[\r\n]{2,}/", "\n\n", $contents), ENT_QUOTES, 'UTF-8') + ); + } + + /** + * Parse the given Markdown text into HTML. + * + * @param string $text + * @return \Illuminate\Support\HtmlString + */ + public static function parse($text) + { + $converter = new CommonMarkConverter([ + 'allow_unsafe_links' => false, + ]); + + $converter->getEnvironment()->addExtension(new TableExtension()); + + return new HtmlString((string) $converter->convertToHtml($text)); + } + + /** + * Get the HTML component paths. + * + * @return array + */ + public function htmlComponentPaths() + { + return array_map(function ($path) { + return $path.'/html'; + }, $this->componentPaths()); + } + + /** + * Get the text component paths. + * + * @return array + */ + public function textComponentPaths() + { + return array_map(function ($path) { + return $path.'/text'; + }, $this->componentPaths()); + } + + /** + * Get the component paths. + * + * @return array + */ + protected function componentPaths() + { + return array_unique(array_merge($this->componentPaths, [ + __DIR__.'/resources/views', + ])); + } + + /** + * Register new mail component paths. + * + * @param array $paths + * @return void + */ + public function loadComponentsFrom(array $paths = []) + { + $this->componentPaths = $paths; + } + + /** + * Set the default theme to be used. + * + * @param string $theme + * @return $this + */ + public function theme($theme) + { + $this->theme = $theme; + + return $this; + } + + /** + * Get the theme currently being used by the renderer. + * + * @return string + */ + public function getTheme() + { + return $this->theme; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Message.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Message.php new file mode 100755 index 0000000..cab6c02 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Message.php @@ -0,0 +1,329 @@ +swift = $swift; + } + + /** + * Add a "from" address to the message. + * + * @param string|array $address + * @param string|null $name + * @return $this + */ + public function from($address, $name = null) + { + $this->swift->setFrom($address, $name); + + return $this; + } + + /** + * Set the "sender" of the message. + * + * @param string|array $address + * @param string|null $name + * @return $this + */ + public function sender($address, $name = null) + { + $this->swift->setSender($address, $name); + + return $this; + } + + /** + * Set the "return path" of the message. + * + * @param string $address + * @return $this + */ + public function returnPath($address) + { + $this->swift->setReturnPath($address); + + return $this; + } + + /** + * Add a recipient to the message. + * + * @param string|array $address + * @param string|null $name + * @param bool $override + * @return $this + */ + public function to($address, $name = null, $override = false) + { + if ($override) { + $this->swift->setTo($address, $name); + + return $this; + } + + return $this->addAddresses($address, $name, 'To'); + } + + /** + * Add a carbon copy to the message. + * + * @param string|array $address + * @param string|null $name + * @param bool $override + * @return $this + */ + public function cc($address, $name = null, $override = false) + { + if ($override) { + $this->swift->setCc($address, $name); + + return $this; + } + + return $this->addAddresses($address, $name, 'Cc'); + } + + /** + * Add a blind carbon copy to the message. + * + * @param string|array $address + * @param string|null $name + * @param bool $override + * @return $this + */ + public function bcc($address, $name = null, $override = false) + { + if ($override) { + $this->swift->setBcc($address, $name); + + return $this; + } + + return $this->addAddresses($address, $name, 'Bcc'); + } + + /** + * Add a "reply to" address to the message. + * + * @param string|array $address + * @param string|null $name + * @return $this + */ + public function replyTo($address, $name = null) + { + return $this->addAddresses($address, $name, 'ReplyTo'); + } + + /** + * Add a recipient to the message. + * + * @param string|array $address + * @param string $name + * @param string $type + * @return $this + */ + protected function addAddresses($address, $name, $type) + { + if (is_array($address)) { + $this->swift->{"set{$type}"}($address, $name); + } else { + $this->swift->{"add{$type}"}($address, $name); + } + + return $this; + } + + /** + * Set the subject of the message. + * + * @param string $subject + * @return $this + */ + public function subject($subject) + { + $this->swift->setSubject($subject); + + return $this; + } + + /** + * Set the message priority level. + * + * @param int $level + * @return $this + */ + public function priority($level) + { + $this->swift->setPriority($level); + + return $this; + } + + /** + * Attach a file to the message. + * + * @param string $file + * @param array $options + * @return $this + */ + public function attach($file, array $options = []) + { + $attachment = $this->createAttachmentFromPath($file); + + return $this->prepAttachment($attachment, $options); + } + + /** + * Create a Swift Attachment instance. + * + * @param string $file + * @return \Swift_Mime_Attachment + */ + protected function createAttachmentFromPath($file) + { + return Swift_Attachment::fromPath($file); + } + + /** + * Attach in-memory data as an attachment. + * + * @param string $data + * @param string $name + * @param array $options + * @return $this + */ + public function attachData($data, $name, array $options = []) + { + $attachment = $this->createAttachmentFromData($data, $name); + + return $this->prepAttachment($attachment, $options); + } + + /** + * Create a Swift Attachment instance from data. + * + * @param string $data + * @param string $name + * @return \Swift_Attachment + */ + protected function createAttachmentFromData($data, $name) + { + return new Swift_Attachment($data, $name); + } + + /** + * Embed a file in the message and get the CID. + * + * @param string $file + * @return string + */ + public function embed($file) + { + if (isset($this->embeddedFiles[$file])) { + return $this->embeddedFiles[$file]; + } + + return $this->embeddedFiles[$file] = $this->swift->embed( + Swift_Image::fromPath($file) + ); + } + + /** + * Embed in-memory data in the message and get the CID. + * + * @param string $data + * @param string $name + * @param string|null $contentType + * @return string + */ + public function embedData($data, $name, $contentType = null) + { + $image = new Swift_Image($data, $name, $contentType); + + return $this->swift->embed($image); + } + + /** + * Prepare and attach the given attachment. + * + * @param \Swift_Attachment $attachment + * @param array $options + * @return $this + */ + protected function prepAttachment($attachment, $options = []) + { + // First we will check for a MIME type on the message, which instructs the + // mail client on what type of attachment the file is so that it may be + // downloaded correctly by the user. The MIME option is not required. + if (isset($options['mime'])) { + $attachment->setContentType($options['mime']); + } + + // If an alternative name was given as an option, we will set that on this + // attachment so that it will be downloaded with the desired names from + // the developer, otherwise the default file names will get assigned. + if (isset($options['as'])) { + $attachment->setFilename($options['as']); + } + + $this->swift->attach($attachment); + + return $this; + } + + /** + * Get the underlying Swift Message instance. + * + * @return \Swift_Message + */ + public function getSwiftMessage() + { + return $this->swift; + } + + /** + * Dynamically pass missing methods to the Swift instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->forwardCallTo($this->swift, $method, $parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/PendingMail.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/PendingMail.php new file mode 100644 index 0000000..8fbabc4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/PendingMail.php @@ -0,0 +1,166 @@ +mailer = $mailer; + } + + /** + * Set the locale of the message. + * + * @param string $locale + * @return $this + */ + public function locale($locale) + { + $this->locale = $locale; + + return $this; + } + + /** + * Set the recipients of the message. + * + * @param mixed $users + * @return $this + */ + public function to($users) + { + $this->to = $users; + + if (! $this->locale && $users instanceof HasLocalePreference) { + $this->locale($users->preferredLocale()); + } + + return $this; + } + + /** + * Set the recipients of the message. + * + * @param mixed $users + * @return $this + */ + public function cc($users) + { + $this->cc = $users; + + return $this; + } + + /** + * Set the recipients of the message. + * + * @param mixed $users + * @return $this + */ + public function bcc($users) + { + $this->bcc = $users; + + return $this; + } + + /** + * Send a new mailable message instance. + * + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return void + */ + public function send(MailableContract $mailable) + { + $this->mailer->send($this->fill($mailable)); + } + + /** + * Push the given mailable onto the queue. + * + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return mixed + */ + public function queue(MailableContract $mailable) + { + return $this->mailer->queue($this->fill($mailable)); + } + + /** + * Deliver the queued message after the given delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return mixed + */ + public function later($delay, MailableContract $mailable) + { + return $this->mailer->later($delay, $this->fill($mailable)); + } + + /** + * Populate the mailable with the addresses. + * + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return \Illuminate\Mail\Mailable + */ + protected function fill(MailableContract $mailable) + { + return tap($mailable->to($this->to) + ->cc($this->cc) + ->bcc($this->bcc), function (MailableContract $mailable) { + if ($this->locale) { + $mailable->locale($this->locale); + } + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/SendQueuedMailable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/SendQueuedMailable.php new file mode 100644 index 0000000..1009789 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/SendQueuedMailable.php @@ -0,0 +1,114 @@ +mailable = $mailable; + $this->tries = property_exists($mailable, 'tries') ? $mailable->tries : null; + $this->timeout = property_exists($mailable, 'timeout') ? $mailable->timeout : null; + $this->afterCommit = property_exists($mailable, 'afterCommit') ? $mailable->afterCommit : null; + $this->shouldBeEncrypted = $mailable instanceof ShouldBeEncrypted; + } + + /** + * Handle the queued job. + * + * @param \Illuminate\Contracts\Mail\Factory $factory + * @return void + */ + public function handle(MailFactory $factory) + { + $this->mailable->send($factory); + } + + /** + * Get the display name for the queued job. + * + * @return string + */ + public function displayName() + { + return get_class($this->mailable); + } + + /** + * Call the failed method on the mailable instance. + * + * @param \Throwable $e + * @return void + */ + public function failed($e) + { + if (method_exists($this->mailable, 'failed')) { + $this->mailable->failed($e); + } + } + + /** + * Get the number of seconds before a released mailable will be available. + * + * @return mixed + */ + public function backoff() + { + if (! method_exists($this->mailable, 'backoff') && ! isset($this->mailable->backoff)) { + return; + } + + return $this->mailable->backoff ?? $this->mailable->backoff(); + } + + /** + * Prepare the instance for cloning. + * + * @return void + */ + public function __clone() + { + $this->mailable = clone $this->mailable; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/ArrayTransport.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/ArrayTransport.php new file mode 100644 index 0000000..fe6fdf7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/ArrayTransport.php @@ -0,0 +1,60 @@ +messages = new Collection; + } + + /** + * {@inheritdoc} + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $this->beforeSendPerformed($message); + + $this->messages[] = $message; + + return $this->numberOfRecipients($message); + } + + /** + * Retrieve the collection of messages. + * + * @return \Illuminate\Support\Collection + */ + public function messages() + { + return $this->messages; + } + + /** + * Clear all of the messages from the local collection. + * + * @return \Illuminate\Support\Collection + */ + public function flush() + { + return $this->messages = new Collection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/LogTransport.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/LogTransport.php new file mode 100644 index 0000000..21f1aae --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/LogTransport.php @@ -0,0 +1,71 @@ +logger = $logger; + } + + /** + * {@inheritdoc} + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $this->beforeSendPerformed($message); + + $this->logger->debug($this->getMimeEntityString($message)); + + $this->sendPerformed($message); + + return $this->numberOfRecipients($message); + } + + /** + * Get a loggable string out of a Swiftmailer entity. + * + * @param \Swift_Mime_SimpleMimeEntity $entity + * @return string + */ + protected function getMimeEntityString(Swift_Mime_SimpleMimeEntity $entity) + { + $string = (string) $entity->getHeaders().PHP_EOL.$entity->getBody(); + + foreach ($entity->getChildren() as $children) { + $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($children); + } + + return $string; + } + + /** + * Get the logger for the LogTransport instance. + * + * @return \Psr\Log\LoggerInterface + */ + public function logger() + { + return $this->logger; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/MailgunTransport.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/MailgunTransport.php new file mode 100644 index 0000000..71ceccf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/MailgunTransport.php @@ -0,0 +1,224 @@ +key = $key; + $this->client = $client; + $this->endpoint = $endpoint ?? 'api.mailgun.net'; + + $this->setDomain($domain); + } + + /** + * {@inheritdoc} + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $this->beforeSendPerformed($message); + + $to = $this->getTo($message); + + $bcc = $message->getBcc(); + + $message->setBcc([]); + + try { + $response = $this->client->request( + 'POST', + "https://{$this->endpoint}/v3/{$this->domain}/messages.mime", + $this->payload($message, $to) + ); + } catch (GuzzleException $e) { + throw new Swift_TransportException('Request to Mailgun API failed.', $e->getCode(), $e); + } + + $messageId = $this->getMessageId($response); + + $message->getHeaders()->addTextHeader('X-Message-ID', $messageId); + $message->getHeaders()->addTextHeader('X-Mailgun-Message-ID', $messageId); + + $message->setBcc($bcc); + + $this->sendPerformed($message); + + return $this->numberOfRecipients($message); + } + + /** + * Get the HTTP payload for sending the Mailgun message. + * + * @param \Swift_Mime_SimpleMessage $message + * @param string $to + * @return array + */ + protected function payload(Swift_Mime_SimpleMessage $message, $to) + { + return [ + 'auth' => [ + 'api', + $this->key, + ], + 'multipart' => [ + [ + 'name' => 'to', + 'contents' => $to, + ], + [ + 'name' => 'message', + 'contents' => $message->toString(), + 'filename' => 'message.mime', + ], + ], + ]; + } + + /** + * Get the "to" payload field for the API request. + * + * @param \Swift_Mime_SimpleMessage $message + * @return string + */ + protected function getTo(Swift_Mime_SimpleMessage $message) + { + return collect($this->allContacts($message))->map(function ($display, $address) { + return $display ? $display." <{$address}>" : $address; + })->values()->implode(','); + } + + /** + * Get all of the contacts for the message. + * + * @param \Swift_Mime_SimpleMessage $message + * @return array + */ + protected function allContacts(Swift_Mime_SimpleMessage $message) + { + return array_merge( + (array) $message->getTo(), (array) $message->getCc(), (array) $message->getBcc() + ); + } + + /** + * Get the message ID from the response. + * + * @param \Psr\Http\Message\ResponseInterface $response + * @return string + */ + protected function getMessageId($response) + { + return object_get( + json_decode($response->getBody()->getContents()), 'id' + ); + } + + /** + * Get the API key being used by the transport. + * + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * Set the API key being used by the transport. + * + * @param string $key + * @return string + */ + public function setKey($key) + { + return $this->key = $key; + } + + /** + * Get the domain being used by the transport. + * + * @return string + */ + public function getDomain() + { + return $this->domain; + } + + /** + * Set the domain being used by the transport. + * + * @param string $domain + * @return string + */ + public function setDomain($domain) + { + return $this->domain = $domain; + } + + /** + * Get the API endpoint being used by the transport. + * + * @return string + */ + public function getEndpoint() + { + return $this->endpoint; + } + + /** + * Set the API endpoint being used by the transport. + * + * @param string $endpoint + * @return string + */ + public function setEndpoint($endpoint) + { + return $this->endpoint = $endpoint; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/SesTransport.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/SesTransport.php new file mode 100644 index 0000000..7dd81a2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/SesTransport.php @@ -0,0 +1,103 @@ +ses = $ses; + $this->options = $options; + } + + /** + * {@inheritdoc} + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $this->beforeSendPerformed($message); + + try { + $result = $this->ses->sendRawEmail( + array_merge( + $this->options, [ + 'Source' => key($message->getSender() ?: $message->getFrom()), + 'RawMessage' => [ + 'Data' => $message->toString(), + ], + ] + ) + ); + } catch (AwsException $e) { + throw new Swift_TransportException('Request to AWS SES API failed.', $e->getCode(), $e); + } + + $messageId = $result->get('MessageId'); + + $message->getHeaders()->addTextHeader('X-Message-ID', $messageId); + $message->getHeaders()->addTextHeader('X-SES-Message-ID', $messageId); + + $this->sendPerformed($message); + + return $this->numberOfRecipients($message); + } + + /** + * Get the Amazon SES client for the SesTransport instance. + * + * @return \Aws\Ses\SesClient + */ + public function ses() + { + return $this->ses; + } + + /** + * Get the transmission options being used by the transport. + * + * @return array + */ + public function getOptions() + { + return $this->options; + } + + /** + * Set the transmission options being used by the transport. + * + * @param array $options + * @return array + */ + public function setOptions(array $options) + { + return $this->options = $options; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/Transport.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/Transport.php new file mode 100644 index 0000000..62b4495 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/Transport/Transport.php @@ -0,0 +1,112 @@ +plugins, $plugin); + } + + /** + * Iterate through registered plugins and execute plugins' methods. + * + * @param \Swift_Mime_SimpleMessage $message + * @return void + */ + protected function beforeSendPerformed(Swift_Mime_SimpleMessage $message) + { + $event = new Swift_Events_SendEvent($this, $message); + + foreach ($this->plugins as $plugin) { + if (method_exists($plugin, 'beforeSendPerformed')) { + $plugin->beforeSendPerformed($event); + } + } + } + + /** + * Iterate through registered plugins and execute plugins' methods. + * + * @param \Swift_Mime_SimpleMessage $message + * @return void + */ + protected function sendPerformed(Swift_Mime_SimpleMessage $message) + { + $event = new Swift_Events_SendEvent($this, $message); + + foreach ($this->plugins as $plugin) { + if (method_exists($plugin, 'sendPerformed')) { + $plugin->sendPerformed($event); + } + } + } + + /** + * Get the number of recipients. + * + * @param \Swift_Mime_SimpleMessage $message + * @return int + */ + protected function numberOfRecipients(Swift_Mime_SimpleMessage $message) + { + return count(array_merge( + (array) $message->getTo(), (array) $message->getCc(), (array) $message->getBcc() + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/composer.json new file mode 100755 index 0000000..cfddcb3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/composer.json @@ -0,0 +1,48 @@ +{ + "name": "illuminate/mail", + "description": "The Illuminate Mail package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "league/commonmark": "^1.3|^2.0.2", + "psr/log": "^1.0|^2.0", + "swiftmailer/swiftmailer": "^6.3", + "tijsverkoyen/css-to-inline-styles": "^2.2.2" + }, + "autoload": { + "psr-4": { + "Illuminate\\Mail\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "aws/aws-sdk-php": "Required to use the SES mail driver (^3.198.1).", + "guzzlehttp/guzzle": "Required to use the Mailgun mail driver (^6.5.5|^7.0.1).", + "wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/button.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/button.blade.php new file mode 100644 index 0000000..e74fe55 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/button.blade.php @@ -0,0 +1,19 @@ + + + + + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/footer.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/footer.blade.php new file mode 100644 index 0000000..3ff41f8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/footer.blade.php @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/header.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/header.blade.php new file mode 100644 index 0000000..fa1875c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/header.blade.php @@ -0,0 +1,11 @@ + + + +@if (trim($slot) === 'Laravel') + +@else +{{ $slot }} +@endif + + + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/layout.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/layout.blade.php new file mode 100644 index 0000000..21d349b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/layout.blade.php @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/message.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/message.blade.php new file mode 100644 index 0000000..deec4a1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/message.blade.php @@ -0,0 +1,27 @@ +@component('mail::layout') +{{-- Header --}} +@slot('header') +@component('mail::header', ['url' => config('app.url')]) +{{ config('app.name') }} +@endcomponent +@endslot + +{{-- Body --}} +{{ $slot }} + +{{-- Subcopy --}} +@isset($subcopy) +@slot('subcopy') +@component('mail::subcopy') +{{ $subcopy }} +@endcomponent +@endslot +@endisset + +{{-- Footer --}} +@slot('footer') +@component('mail::footer') +© {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.') +@endcomponent +@endslot +@endcomponent diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/panel.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/panel.blade.php new file mode 100644 index 0000000..2975a60 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -0,0 +1,14 @@ + + + + + + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/subcopy.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/subcopy.blade.php new file mode 100644 index 0000000..790ce6c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/subcopy.blade.php @@ -0,0 +1,7 @@ + + + + + diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/table.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/table.blade.php new file mode 100644 index 0000000..a5f3348 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/table.blade.php @@ -0,0 +1,3 @@ +
+{{ Illuminate\Mail\Markdown::parse($slot) }} +
diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/themes/default.css b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/themes/default.css new file mode 100644 index 0000000..2483b11 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/themes/default.css @@ -0,0 +1,290 @@ +/* Base */ + +body, +body *:not(html):not(style):not(br):not(tr):not(code) { + box-sizing: border-box; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, + 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; + position: relative; +} + +body { + -webkit-text-size-adjust: none; + background-color: #ffffff; + color: #718096; + height: 100%; + line-height: 1.4; + margin: 0; + padding: 0; + width: 100% !important; +} + +p, +ul, +ol, +blockquote { + line-height: 1.4; + text-align: left; +} + +a { + color: #3869d4; +} + +a img { + border: none; +} + +/* Typography */ + +h1 { + color: #3d4852; + font-size: 18px; + font-weight: bold; + margin-top: 0; + text-align: left; +} + +h2 { + font-size: 16px; + font-weight: bold; + margin-top: 0; + text-align: left; +} + +h3 { + font-size: 14px; + font-weight: bold; + margin-top: 0; + text-align: left; +} + +p { + font-size: 16px; + line-height: 1.5em; + margin-top: 0; + text-align: left; +} + +p.sub { + font-size: 12px; +} + +img { + max-width: 100%; +} + +/* Layout */ + +.wrapper { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 100%; + background-color: #edf2f7; + margin: 0; + padding: 0; + width: 100%; +} + +.content { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 100%; + margin: 0; + padding: 0; + width: 100%; +} + +/* Header */ + +.header { + padding: 25px 0; + text-align: center; +} + +.header a { + color: #3d4852; + font-size: 19px; + font-weight: bold; + text-decoration: none; +} + +/* Logo */ + +.logo { + height: 75px; + max-height: 75px; + width: 75px; +} + +/* Body */ + +.body { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 100%; + background-color: #edf2f7; + border-bottom: 1px solid #edf2f7; + border-top: 1px solid #edf2f7; + margin: 0; + padding: 0; + width: 100%; +} + +.inner-body { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 570px; + background-color: #ffffff; + border-color: #e8e5ef; + border-radius: 2px; + border-width: 1px; + box-shadow: 0 2px 0 rgba(0, 0, 150, 0.025), 2px 4px 0 rgba(0, 0, 150, 0.015); + margin: 0 auto; + padding: 0; + width: 570px; +} + +/* Subcopy */ + +.subcopy { + border-top: 1px solid #e8e5ef; + margin-top: 25px; + padding-top: 25px; +} + +.subcopy p { + font-size: 14px; +} + +/* Footer */ + +.footer { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 570px; + margin: 0 auto; + padding: 0; + text-align: center; + width: 570px; +} + +.footer p { + color: #b0adc5; + font-size: 12px; + text-align: center; +} + +.footer a { + color: #b0adc5; + text-decoration: underline; +} + +/* Tables */ + +.table table { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 100%; + margin: 30px auto; + width: 100%; +} + +.table th { + border-bottom: 1px solid #edeff2; + margin: 0; + padding-bottom: 8px; +} + +.table td { + color: #74787e; + font-size: 15px; + line-height: 18px; + margin: 0; + padding: 10px 0; +} + +.content-cell { + max-width: 100vw; + padding: 32px; +} + +/* Buttons */ + +.action { + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + -premailer-width: 100%; + margin: 30px auto; + padding: 0; + text-align: center; + width: 100%; +} + +.button { + -webkit-text-size-adjust: none; + border-radius: 4px; + color: #fff; + display: inline-block; + overflow: hidden; + text-decoration: none; +} + +.button-blue, +.button-primary { + background-color: #2d3748; + border-bottom: 8px solid #2d3748; + border-left: 18px solid #2d3748; + border-right: 18px solid #2d3748; + border-top: 8px solid #2d3748; +} + +.button-green, +.button-success { + background-color: #48bb78; + border-bottom: 8px solid #48bb78; + border-left: 18px solid #48bb78; + border-right: 18px solid #48bb78; + border-top: 8px solid #48bb78; +} + +.button-red, +.button-error { + background-color: #e53e3e; + border-bottom: 8px solid #e53e3e; + border-left: 18px solid #e53e3e; + border-right: 18px solid #e53e3e; + border-top: 8px solid #e53e3e; +} + +/* Panels */ + +.panel { + border-left: #2d3748 solid 4px; + margin: 21px 0; +} + +.panel-content { + background-color: #edf2f7; + color: #718096; + padding: 16px; +} + +.panel-content p { + color: #718096; +} + +.panel-item { + padding: 0; +} + +.panel-item p:last-of-type { + margin-bottom: 0; + padding-bottom: 0; +} + +/* Utilities */ + +.break-all { + word-break: break-all; +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/button.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/button.blade.php new file mode 100644 index 0000000..97444eb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/button.blade.php @@ -0,0 +1 @@ +{{ $slot }}: {{ $url }} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/footer.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/footer.blade.php new file mode 100644 index 0000000..3338f62 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/footer.blade.php @@ -0,0 +1 @@ +{{ $slot }} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/header.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/header.blade.php new file mode 100644 index 0000000..aaa3e57 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/header.blade.php @@ -0,0 +1 @@ +[{{ $slot }}]({{ $url }}) diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/layout.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/layout.blade.php new file mode 100644 index 0000000..9378baa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/layout.blade.php @@ -0,0 +1,9 @@ +{!! strip_tags($header) !!} + +{!! strip_tags($slot) !!} +@isset($subcopy) + +{!! strip_tags($subcopy) !!} +@endisset + +{!! strip_tags($footer) !!} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/message.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/message.blade.php new file mode 100644 index 0000000..1ae9ed8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/message.blade.php @@ -0,0 +1,27 @@ +@component('mail::layout') + {{-- Header --}} + @slot('header') + @component('mail::header', ['url' => config('app.url')]) + {{ config('app.name') }} + @endcomponent + @endslot + + {{-- Body --}} + {{ $slot }} + + {{-- Subcopy --}} + @isset($subcopy) + @slot('subcopy') + @component('mail::subcopy') + {{ $subcopy }} + @endcomponent + @endslot + @endisset + + {{-- Footer --}} + @slot('footer') + @component('mail::footer') + © {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.') + @endcomponent + @endslot +@endcomponent diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/panel.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/panel.blade.php new file mode 100644 index 0000000..3338f62 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/panel.blade.php @@ -0,0 +1 @@ +{{ $slot }} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/subcopy.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/subcopy.blade.php new file mode 100644 index 0000000..3338f62 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/subcopy.blade.php @@ -0,0 +1 @@ +{{ $slot }} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/table.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/table.blade.php new file mode 100644 index 0000000..3338f62 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Mail/resources/views/text/table.blade.php @@ -0,0 +1 @@ +{{ $slot }} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Action.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Action.php new file mode 100644 index 0000000..071db2d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Action.php @@ -0,0 +1,33 @@ +url = $url; + $this->text = $text; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/AnonymousNotifiable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/AnonymousNotifiable.php new file mode 100644 index 0000000..aa4d7bb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/AnonymousNotifiable.php @@ -0,0 +1,79 @@ +routes[$channel] = $route; + + return $this; + } + + /** + * Send the given notification. + * + * @param mixed $notification + * @return void + */ + public function notify($notification) + { + app(Dispatcher::class)->send($this, $notification); + } + + /** + * Send the given notification immediately. + * + * @param mixed $notification + * @return void + */ + public function notifyNow($notification) + { + app(Dispatcher::class)->sendNow($this, $notification); + } + + /** + * Get the notification routing information for the given driver. + * + * @param string $driver + * @return mixed + */ + public function routeNotificationFor($driver) + { + return $this->routes[$driver] ?? null; + } + + /** + * Get the value of the notifiable's primary key. + * + * @return mixed + */ + public function getKey() + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php new file mode 100644 index 0000000..8eb9c25 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php @@ -0,0 +1,162 @@ +container->make(Bus::class), $this->container->make(Dispatcher::class), $this->locale) + )->send($notifiables, $notification); + } + + /** + * Send the given notification immediately. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @param array|null $channels + * @return void + */ + public function sendNow($notifiables, $notification, array $channels = null) + { + (new NotificationSender( + $this, $this->container->make(Bus::class), $this->container->make(Dispatcher::class), $this->locale) + )->sendNow($notifiables, $notification, $channels); + } + + /** + * Get a channel instance. + * + * @param string|null $name + * @return mixed + */ + public function channel($name = null) + { + return $this->driver($name); + } + + /** + * Create an instance of the database driver. + * + * @return \Illuminate\Notifications\Channels\DatabaseChannel + */ + protected function createDatabaseDriver() + { + return $this->container->make(Channels\DatabaseChannel::class); + } + + /** + * Create an instance of the broadcast driver. + * + * @return \Illuminate\Notifications\Channels\BroadcastChannel + */ + protected function createBroadcastDriver() + { + return $this->container->make(Channels\BroadcastChannel::class); + } + + /** + * Create an instance of the mail driver. + * + * @return \Illuminate\Notifications\Channels\MailChannel + */ + protected function createMailDriver() + { + return $this->container->make(Channels\MailChannel::class); + } + + /** + * Create a new driver instance. + * + * @param string $driver + * @return mixed + * + * @throws \InvalidArgumentException + */ + protected function createDriver($driver) + { + try { + return parent::createDriver($driver); + } catch (InvalidArgumentException $e) { + if (class_exists($driver)) { + return $this->container->make($driver); + } + + throw $e; + } + } + + /** + * Get the default channel driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->defaultChannel; + } + + /** + * Get the default channel driver name. + * + * @return string + */ + public function deliversVia() + { + return $this->getDefaultDriver(); + } + + /** + * Set the default channel driver name. + * + * @param string $channel + * @return void + */ + public function deliverVia($channel) + { + $this->defaultChannel = $channel; + } + + /** + * Set the locale of notifications. + * + * @param string $locale + * @return $this + */ + public function locale($locale) + { + $this->locale = $locale; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/BroadcastChannel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/BroadcastChannel.php new file mode 100644 index 0000000..1389f49 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/BroadcastChannel.php @@ -0,0 +1,75 @@ +events = $events; + } + + /** + * Send the given notification. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @return array|null + */ + public function send($notifiable, Notification $notification) + { + $message = $this->getData($notifiable, $notification); + + $event = new BroadcastNotificationCreated( + $notifiable, $notification, is_array($message) ? $message : $message->data + ); + + if ($message instanceof BroadcastMessage) { + $event->onConnection($message->connection) + ->onQueue($message->queue); + } + + return $this->events->dispatch($event); + } + + /** + * Get the data for the notification. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @return mixed + * + * @throws \RuntimeException + */ + protected function getData($notifiable, Notification $notification) + { + if (method_exists($notification, 'toBroadcast')) { + return $notification->toBroadcast($notifiable); + } + + if (method_exists($notification, 'toArray')) { + return $notification->toArray($notifiable); + } + + throw new RuntimeException('Notification is missing toArray method.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/DatabaseChannel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/DatabaseChannel.php new file mode 100644 index 0000000..8b3167b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/DatabaseChannel.php @@ -0,0 +1,65 @@ +routeNotificationFor('database', $notification)->create( + $this->buildPayload($notifiable, $notification) + ); + } + + /** + * Build an array payload for the DatabaseNotification Model. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @return array + */ + protected function buildPayload($notifiable, Notification $notification) + { + return [ + 'id' => $notification->id, + 'type' => method_exists($notification, 'databaseType') + ? $notification->databaseType($notifiable) + : get_class($notification), + 'data' => $this->getData($notifiable, $notification), + 'read_at' => null, + ]; + } + + /** + * Get the data for the notification. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @return array + * + * @throws \RuntimeException + */ + protected function getData($notifiable, Notification $notification) + { + if (method_exists($notification, 'toDatabase')) { + return is_array($data = $notification->toDatabase($notifiable)) + ? $data : $data->data; + } + + if (method_exists($notification, 'toArray')) { + return $notification->toArray($notifiable); + } + + throw new RuntimeException('Notification is missing toDatabase / toArray method.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php new file mode 100644 index 0000000..2a30bcd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php @@ -0,0 +1,252 @@ +mailer = $mailer; + $this->markdown = $markdown; + } + + /** + * Send the given notification. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @return void + */ + public function send($notifiable, Notification $notification) + { + $message = $notification->toMail($notifiable); + + if (! $notifiable->routeNotificationFor('mail', $notification) && + ! $message instanceof Mailable) { + return; + } + + if ($message instanceof Mailable) { + return $message->send($this->mailer); + } + + $this->mailer->mailer($message->mailer ?? null)->send( + $this->buildView($message), + array_merge($message->data(), $this->additionalMessageData($notification)), + $this->messageBuilder($notifiable, $notification, $message) + ); + } + + /** + * Get the mailer Closure for the message. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return \Closure + */ + protected function messageBuilder($notifiable, $notification, $message) + { + return function ($mailMessage) use ($notifiable, $notification, $message) { + $this->buildMessage($mailMessage, $notifiable, $notification, $message); + }; + } + + /** + * Build the notification's view. + * + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return string|array + */ + protected function buildView($message) + { + if ($message->view) { + return $message->view; + } + + if (property_exists($message, 'theme') && ! is_null($message->theme)) { + $this->markdown->theme($message->theme); + } + + return [ + 'html' => $this->markdown->render($message->markdown, $message->data()), + 'text' => $this->markdown->renderText($message->markdown, $message->data()), + ]; + } + + /** + * Get additional meta-data to pass along with the view data. + * + * @param \Illuminate\Notifications\Notification $notification + * @return array + */ + protected function additionalMessageData($notification) + { + return [ + '__laravel_notification_id' => $notification->id, + '__laravel_notification' => get_class($notification), + '__laravel_notification_queued' => in_array( + ShouldQueue::class, + class_implements($notification) + ), + ]; + } + + /** + * Build the mail message. + * + * @param \Illuminate\Mail\Message $mailMessage + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return void + */ + protected function buildMessage($mailMessage, $notifiable, $notification, $message) + { + $this->addressMessage($mailMessage, $notifiable, $notification, $message); + + $mailMessage->subject($message->subject ?: Str::title( + Str::snake(class_basename($notification), ' ') + )); + + $this->addAttachments($mailMessage, $message); + + if (! is_null($message->priority)) { + $mailMessage->setPriority($message->priority); + } + + $this->runCallbacks($mailMessage, $message); + } + + /** + * Address the mail message. + * + * @param \Illuminate\Mail\Message $mailMessage + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return void + */ + protected function addressMessage($mailMessage, $notifiable, $notification, $message) + { + $this->addSender($mailMessage, $message); + + $mailMessage->to($this->getRecipients($notifiable, $notification, $message)); + + if (! empty($message->cc)) { + foreach ($message->cc as $cc) { + $mailMessage->cc($cc[0], Arr::get($cc, 1)); + } + } + + if (! empty($message->bcc)) { + foreach ($message->bcc as $bcc) { + $mailMessage->bcc($bcc[0], Arr::get($bcc, 1)); + } + } + } + + /** + * Add the "from" and "reply to" addresses to the message. + * + * @param \Illuminate\Mail\Message $mailMessage + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return void + */ + protected function addSender($mailMessage, $message) + { + if (! empty($message->from)) { + $mailMessage->from($message->from[0], Arr::get($message->from, 1)); + } + + if (! empty($message->replyTo)) { + foreach ($message->replyTo as $replyTo) { + $mailMessage->replyTo($replyTo[0], Arr::get($replyTo, 1)); + } + } + } + + /** + * Get the recipients of the given message. + * + * @param mixed $notifiable + * @param \Illuminate\Notifications\Notification $notification + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return mixed + */ + protected function getRecipients($notifiable, $notification, $message) + { + if (is_string($recipients = $notifiable->routeNotificationFor('mail', $notification))) { + $recipients = [$recipients]; + } + + return collect($recipients)->mapWithKeys(function ($recipient, $email) { + return is_numeric($email) + ? [$email => (is_string($recipient) ? $recipient : $recipient->email)] + : [$email => $recipient]; + })->all(); + } + + /** + * Add the attachments to the message. + * + * @param \Illuminate\Mail\Message $mailMessage + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return void + */ + protected function addAttachments($mailMessage, $message) + { + foreach ($message->attachments as $attachment) { + $mailMessage->attach($attachment['file'], $attachment['options']); + } + + foreach ($message->rawAttachments as $attachment) { + $mailMessage->attachData($attachment['data'], $attachment['name'], $attachment['options']); + } + } + + /** + * Run the callbacks for the message. + * + * @param \Illuminate\Mail\Message $mailMessage + * @param \Illuminate\Notifications\Messages\MailMessage $message + * @return $this + */ + protected function runCallbacks($mailMessage, $message) + { + foreach ($message->callbacks as $callback) { + $callback($mailMessage->getSwiftMessage()); + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Console/NotificationTableCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Console/NotificationTableCommand.php new file mode 100644 index 0000000..f447fc1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Console/NotificationTableCommand.php @@ -0,0 +1,81 @@ +files = $files; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $fullPath = $this->createBaseMigration(); + + $this->files->put($fullPath, $this->files->get(__DIR__.'/stubs/notifications.stub')); + + $this->info('Migration created successfully!'); + + $this->composer->dumpAutoloads(); + } + + /** + * Create a base migration file for the notifications. + * + * @return string + */ + protected function createBaseMigration() + { + $name = 'create_notifications_table'; + + $path = $this->laravel->databasePath().'/migrations'; + + return $this->laravel['migration.creator']->create($name, $path); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Console/stubs/notifications.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Console/stubs/notifications.stub new file mode 100644 index 0000000..9797596 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Console/stubs/notifications.stub @@ -0,0 +1,35 @@ +uuid('id')->primary(); + $table->string('type'); + $table->morphs('notifiable'); + $table->text('data'); + $table->timestamp('read_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('notifications'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotification.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotification.php new file mode 100644 index 0000000..14bc9d6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotification.php @@ -0,0 +1,134 @@ + 'array', + 'read_at' => 'datetime', + ]; + + /** + * Get the notifiable entity that the notification belongs to. + * + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function notifiable() + { + return $this->morphTo(); + } + + /** + * Mark the notification as read. + * + * @return void + */ + public function markAsRead() + { + if (is_null($this->read_at)) { + $this->forceFill(['read_at' => $this->freshTimestamp()])->save(); + } + } + + /** + * Mark the notification as unread. + * + * @return void + */ + public function markAsUnread() + { + if (! is_null($this->read_at)) { + $this->forceFill(['read_at' => null])->save(); + } + } + + /** + * Determine if a notification has been read. + * + * @return bool + */ + public function read() + { + return $this->read_at !== null; + } + + /** + * Determine if a notification has not been read. + * + * @return bool + */ + public function unread() + { + return $this->read_at === null; + } + + /** + * Scope a query to only include read notifications. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + public function scopeRead(Builder $query) + { + return $query->whereNotNull('read_at'); + } + + /** + * Scope a query to only include unread notifications. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + public function scopeUnread(Builder $query) + { + return $query->whereNull('read_at'); + } + + /** + * Create a new database notification collection instance. + * + * @param array $models + * @return \Illuminate\Notifications\DatabaseNotificationCollection + */ + public function newCollection(array $models = []) + { + return new DatabaseNotificationCollection($models); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotificationCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotificationCollection.php new file mode 100644 index 0000000..05924ec --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotificationCollection.php @@ -0,0 +1,28 @@ +each->markAsRead(); + } + + /** + * Mark all notifications as unread. + * + * @return void + */ + public function markAsUnread() + { + $this->each->markAsUnread(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/BroadcastNotificationCreated.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/BroadcastNotificationCreated.php new file mode 100644 index 0000000..2495885 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/BroadcastNotificationCreated.php @@ -0,0 +1,116 @@ +data = $data; + $this->notifiable = $notifiable; + $this->notification = $notification; + } + + /** + * Get the channels the event should broadcast on. + * + * @return array + */ + public function broadcastOn() + { + $channels = $this->notification->broadcastOn(); + + if (! empty($channels)) { + return $channels; + } + + if (is_string($channels = $this->channelName())) { + return [new PrivateChannel($channels)]; + } + + return collect($channels)->map(function ($channel) { + return new PrivateChannel($channel); + })->all(); + } + + /** + * Get the broadcast channel name for the event. + * + * @return array|string + */ + protected function channelName() + { + if (method_exists($this->notifiable, 'receivesBroadcastNotificationsOn')) { + return $this->notifiable->receivesBroadcastNotificationsOn($this->notification); + } + + $class = str_replace('\\', '.', get_class($this->notifiable)); + + return $class.'.'.$this->notifiable->getKey(); + } + + /** + * Get the data that should be sent with the broadcasted event. + * + * @return array + */ + public function broadcastWith() + { + if (method_exists($this->notification, 'broadcastWith')) { + return $this->notification->broadcastWith(); + } + + return array_merge($this->data, [ + 'id' => $this->notification->id, + 'type' => $this->broadcastType(), + ]); + } + + /** + * Get the type of the notification being broadcast. + * + * @return string + */ + public function broadcastType() + { + return method_exists($this->notification, 'broadcastType') + ? $this->notification->broadcastType() + : get_class($this->notification); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationFailed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationFailed.php new file mode 100644 index 0000000..b69e1c5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationFailed.php @@ -0,0 +1,56 @@ +data = $data; + $this->channel = $channel; + $this->notifiable = $notifiable; + $this->notification = $notification; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationSending.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationSending.php new file mode 100644 index 0000000..6efd1d0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationSending.php @@ -0,0 +1,47 @@ +channel = $channel; + $this->notifiable = $notifiable; + $this->notification = $notification; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationSent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationSent.php new file mode 100644 index 0000000..4f09069 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Events/NotificationSent.php @@ -0,0 +1,56 @@ +channel = $channel; + $this->response = $response; + $this->notifiable = $notifiable; + $this->notification = $notification; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/HasDatabaseNotifications.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/HasDatabaseNotifications.php new file mode 100644 index 0000000..5f999da --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/HasDatabaseNotifications.php @@ -0,0 +1,36 @@ +morphMany(DatabaseNotification::class, 'notifiable')->orderBy('created_at', 'desc'); + } + + /** + * Get the entity's read notifications. + * + * @return \Illuminate\Database\Query\Builder + */ + public function readNotifications() + { + return $this->notifications()->read(); + } + + /** + * Get the entity's unread notifications. + * + * @return \Illuminate\Database\Query\Builder + */ + public function unreadNotifications() + { + return $this->notifications()->unread(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/BroadcastMessage.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/BroadcastMessage.php new file mode 100644 index 0000000..9884a8f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/BroadcastMessage.php @@ -0,0 +1,41 @@ +data = $data; + } + + /** + * Set the message data. + * + * @param array $data + * @return $this + */ + public function data($data) + { + $this->data = $data; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/DatabaseMessage.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/DatabaseMessage.php new file mode 100644 index 0000000..55707a7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/DatabaseMessage.php @@ -0,0 +1,24 @@ +data = $data; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/MailMessage.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/MailMessage.php new file mode 100644 index 0000000..94342f3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/MailMessage.php @@ -0,0 +1,336 @@ +view = $view; + $this->viewData = $data; + + $this->markdown = null; + + return $this; + } + + /** + * Set the Markdown template for the notification. + * + * @param string $view + * @param array $data + * @return $this + */ + public function markdown($view, array $data = []) + { + $this->markdown = $view; + $this->viewData = $data; + + $this->view = null; + + return $this; + } + + /** + * Set the default markdown template. + * + * @param string $template + * @return $this + */ + public function template($template) + { + $this->markdown = $template; + + return $this; + } + + /** + * Set the theme to use with the Markdown template. + * + * @param string $theme + * @return $this + */ + public function theme($theme) + { + $this->theme = $theme; + + return $this; + } + + /** + * Set the from address for the mail message. + * + * @param string $address + * @param string|null $name + * @return $this + */ + public function from($address, $name = null) + { + $this->from = [$address, $name]; + + return $this; + } + + /** + * Set the "reply to" address of the message. + * + * @param array|string $address + * @param string|null $name + * @return $this + */ + public function replyTo($address, $name = null) + { + if ($this->arrayOfAddresses($address)) { + $this->replyTo += $this->parseAddresses($address); + } else { + $this->replyTo[] = [$address, $name]; + } + + return $this; + } + + /** + * Set the cc address for the mail message. + * + * @param array|string $address + * @param string|null $name + * @return $this + */ + public function cc($address, $name = null) + { + if ($this->arrayOfAddresses($address)) { + $this->cc += $this->parseAddresses($address); + } else { + $this->cc[] = [$address, $name]; + } + + return $this; + } + + /** + * Set the bcc address for the mail message. + * + * @param array|string $address + * @param string|null $name + * @return $this + */ + public function bcc($address, $name = null) + { + if ($this->arrayOfAddresses($address)) { + $this->bcc += $this->parseAddresses($address); + } else { + $this->bcc[] = [$address, $name]; + } + + return $this; + } + + /** + * Attach a file to the message. + * + * @param string $file + * @param array $options + * @return $this + */ + public function attach($file, array $options = []) + { + $this->attachments[] = compact('file', 'options'); + + return $this; + } + + /** + * Attach in-memory data as an attachment. + * + * @param string $data + * @param string $name + * @param array $options + * @return $this + */ + public function attachData($data, $name, array $options = []) + { + $this->rawAttachments[] = compact('data', 'name', 'options'); + + return $this; + } + + /** + * Set the priority of this message. + * + * The value is an integer where 1 is the highest priority and 5 is the lowest. + * + * @param int $level + * @return $this + */ + public function priority($level) + { + $this->priority = $level; + + return $this; + } + + /** + * Get the data array for the mail message. + * + * @return array + */ + public function data() + { + return array_merge($this->toArray(), $this->viewData); + } + + /** + * Parse the multi-address array into the necessary format. + * + * @param array $value + * @return array + */ + protected function parseAddresses($value) + { + return collect($value)->map(function ($address, $name) { + return [$address, is_numeric($name) ? null : $name]; + })->values()->all(); + } + + /** + * Determine if the given "address" is actually an array of addresses. + * + * @param mixed $address + * @return bool + */ + protected function arrayOfAddresses($address) + { + return is_iterable($address) || $address instanceof Arrayable; + } + + /** + * Render the mail notification message into an HTML string. + * + * @return string + */ + public function render() + { + if (isset($this->view)) { + return Container::getInstance()->make('mailer')->render( + $this->view, $this->data() + ); + } + + $markdown = Container::getInstance()->make(Markdown::class); + + return $markdown->theme($this->theme ?: $markdown->getTheme()) + ->render($this->markdown, $this->data()); + } + + /** + * Register a callback to be called with the Swift message instance. + * + * @param callable $callback + * @return $this + */ + public function withSwiftMessage($callback) + { + $this->callbacks[] = $callback; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/SimpleMessage.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/SimpleMessage.php new file mode 100644 index 0000000..7dab7e4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Messages/SimpleMessage.php @@ -0,0 +1,260 @@ +level = 'success'; + + return $this; + } + + /** + * Indicate that the notification gives information about an error. + * + * @return $this + */ + public function error() + { + $this->level = 'error'; + + return $this; + } + + /** + * Set the "level" of the notification (success, error, etc.). + * + * @param string $level + * @return $this + */ + public function level($level) + { + $this->level = $level; + + return $this; + } + + /** + * Set the subject of the notification. + * + * @param string $subject + * @return $this + */ + public function subject($subject) + { + $this->subject = $subject; + + return $this; + } + + /** + * Set the greeting of the notification. + * + * @param string $greeting + * @return $this + */ + public function greeting($greeting) + { + $this->greeting = $greeting; + + return $this; + } + + /** + * Set the salutation of the notification. + * + * @param string $salutation + * @return $this + */ + public function salutation($salutation) + { + $this->salutation = $salutation; + + return $this; + } + + /** + * Add a line of text to the notification. + * + * @param mixed $line + * @return $this + */ + public function line($line) + { + return $this->with($line); + } + + /** + * Add lines of text to the notification. + * + * @param iterable $lines + * @return $this + */ + public function lines($lines) + { + foreach ($lines as $line) { + $this->line($line); + } + + return $this; + } + + /** + * Add a line of text to the notification. + * + * @param mixed $line + * @return $this + */ + public function with($line) + { + if ($line instanceof Action) { + $this->action($line->text, $line->url); + } elseif (! $this->actionText) { + $this->introLines[] = $this->formatLine($line); + } else { + $this->outroLines[] = $this->formatLine($line); + } + + return $this; + } + + /** + * Format the given line of text. + * + * @param \Illuminate\Contracts\Support\Htmlable|string|array $line + * @return \Illuminate\Contracts\Support\Htmlable|string + */ + protected function formatLine($line) + { + if ($line instanceof Htmlable) { + return $line; + } + + if (is_array($line)) { + return implode(' ', array_map('trim', $line)); + } + + return trim(implode(' ', array_map('trim', preg_split('/\\r\\n|\\r|\\n/', $line ?? '')))); + } + + /** + * Configure the "call to action" button. + * + * @param string $text + * @param string $url + * @return $this + */ + public function action($text, $url) + { + $this->actionText = $text; + $this->actionUrl = $url; + + return $this; + } + + /** + * Set the name of the mailer that should send the notification. + * + * @param string $mailer + * @return $this + */ + public function mailer($mailer) + { + $this->mailer = $mailer; + + return $this; + } + + /** + * Get an array representation of the message. + * + * @return array + */ + public function toArray() + { + return [ + 'level' => $this->level, + 'subject' => $this->subject, + 'greeting' => $this->greeting, + 'salutation' => $this->salutation, + 'introLines' => $this->introLines, + 'outroLines' => $this->outroLines, + 'actionText' => $this->actionText, + 'actionUrl' => $this->actionUrl, + 'displayableActionUrl' => str_replace(['mailto:', 'tel:'], '', $this->actionUrl ?? ''), + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Notifiable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Notifiable.php new file mode 100644 index 0000000..82381e1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/Notifiable.php @@ -0,0 +1,8 @@ +locale = $locale; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php new file mode 100644 index 0000000..c7b67ec --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php @@ -0,0 +1,240 @@ +bus = $bus; + $this->events = $events; + $this->locale = $locale; + $this->manager = $manager; + } + + /** + * Send the given notification to the given notifiable entities. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @return void + */ + public function send($notifiables, $notification) + { + $notifiables = $this->formatNotifiables($notifiables); + + if ($notification instanceof ShouldQueue) { + return $this->queueNotification($notifiables, $notification); + } + + $this->sendNow($notifiables, $notification); + } + + /** + * Send the given notification immediately. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @param array|null $channels + * @return void + */ + public function sendNow($notifiables, $notification, array $channels = null) + { + $notifiables = $this->formatNotifiables($notifiables); + + $original = clone $notification; + + foreach ($notifiables as $notifiable) { + if (empty($viaChannels = $channels ?: $notification->via($notifiable))) { + continue; + } + + $this->withLocale($this->preferredLocale($notifiable, $notification), function () use ($viaChannels, $notifiable, $original) { + $notificationId = Str::uuid()->toString(); + + foreach ((array) $viaChannels as $channel) { + if (! ($notifiable instanceof AnonymousNotifiable && $channel === 'database')) { + $this->sendToNotifiable($notifiable, $notificationId, clone $original, $channel); + } + } + }); + } + } + + /** + * Get the notifiable's preferred locale for the notification. + * + * @param mixed $notifiable + * @param mixed $notification + * @return string|null + */ + protected function preferredLocale($notifiable, $notification) + { + return $notification->locale ?? $this->locale ?? value(function () use ($notifiable) { + if ($notifiable instanceof HasLocalePreference) { + return $notifiable->preferredLocale(); + } + }); + } + + /** + * Send the given notification to the given notifiable via a channel. + * + * @param mixed $notifiable + * @param string $id + * @param mixed $notification + * @param string $channel + * @return void + */ + protected function sendToNotifiable($notifiable, $id, $notification, $channel) + { + if (! $notification->id) { + $notification->id = $id; + } + + if (! $this->shouldSendNotification($notifiable, $notification, $channel)) { + return; + } + + $response = $this->manager->driver($channel)->send($notifiable, $notification); + + $this->events->dispatch( + new NotificationSent($notifiable, $notification, $channel, $response) + ); + } + + /** + * Determines if the notification can be sent. + * + * @param mixed $notifiable + * @param mixed $notification + * @param string $channel + * @return bool + */ + protected function shouldSendNotification($notifiable, $notification, $channel) + { + if (method_exists($notification, 'shouldSend') && + $notification->shouldSend($notifiable, $channel) === false) { + return false; + } + + return $this->events->until( + new NotificationSending($notifiable, $notification, $channel) + ) !== false; + } + + /** + * Queue the given notification instances. + * + * @param mixed $notifiables + * @param \Illuminate\Notifications\Notification $notification + * @return void + */ + protected function queueNotification($notifiables, $notification) + { + $notifiables = $this->formatNotifiables($notifiables); + + $original = clone $notification; + + foreach ($notifiables as $notifiable) { + $notificationId = Str::uuid()->toString(); + + foreach ((array) $original->via($notifiable) as $channel) { + $notification = clone $original; + + $notification->id = $notificationId; + + if (! is_null($this->locale)) { + $notification->locale = $this->locale; + } + + $queue = $notification->queue; + + if (method_exists($notification, 'viaQueues')) { + $queue = $notification->viaQueues()[$channel] ?? null; + } + + $this->bus->dispatch( + (new SendQueuedNotifications($notifiable, $notification, [$channel])) + ->onConnection($notification->connection) + ->onQueue($queue) + ->delay(is_array($notification->delay) ? + ($notification->delay[$channel] ?? null) + : $notification->delay + ) + ->through( + array_merge( + method_exists($notification, 'middleware') ? $notification->middleware() : [], + $notification->middleware ?? [] + ) + ) + ); + } + } + } + + /** + * Format the notifiables into a Collection / array if necessary. + * + * @param mixed $notifiables + * @return \Illuminate\Database\Eloquent\Collection|array + */ + protected function formatNotifiables($notifiables) + { + if (! $notifiables instanceof Collection && ! is_array($notifiables)) { + return $notifiables instanceof Model + ? new ModelCollection([$notifiables]) : [$notifiables]; + } + + return $notifiables; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/NotificationServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/NotificationServiceProvider.php new file mode 100644 index 0000000..fb202ed --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/NotificationServiceProvider.php @@ -0,0 +1,46 @@ +loadViewsFrom(__DIR__.'/resources/views', 'notifications'); + + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__.'/resources/views' => $this->app->resourcePath('views/vendor/notifications'), + ], 'laravel-notifications'); + } + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $this->app->singleton(ChannelManager::class, function ($app) { + return new ChannelManager($app); + }); + + $this->app->alias( + ChannelManager::class, DispatcherContract::class + ); + + $this->app->alias( + ChannelManager::class, FactoryContract::class + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php new file mode 100644 index 0000000..799845a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php @@ -0,0 +1,53 @@ +send($this, $instance); + } + + /** + * Send the given notification immediately. + * + * @param mixed $instance + * @param array|null $channels + * @return void + */ + public function notifyNow($instance, array $channels = null) + { + app(Dispatcher::class)->sendNow($this, $instance, $channels); + } + + /** + * Get the notification routing information for the given driver. + * + * @param string $driver + * @param \Illuminate\Notifications\Notification|null $notification + * @return mixed + */ + public function routeNotificationFor($driver, $notification = null) + { + if (method_exists($this, $method = 'routeNotificationFor'.Str::studly($driver))) { + return $this->{$method}($notification); + } + + switch ($driver) { + case 'database': + return $this->notifications(); + case 'mail': + return $this->email; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/SendQueuedNotifications.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/SendQueuedNotifications.php new file mode 100644 index 0000000..d83c890 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/SendQueuedNotifications.php @@ -0,0 +1,168 @@ +channels = $channels; + $this->notification = $notification; + $this->notifiables = $this->wrapNotifiables($notifiables); + $this->tries = property_exists($notification, 'tries') ? $notification->tries : null; + $this->timeout = property_exists($notification, 'timeout') ? $notification->timeout : null; + $this->afterCommit = property_exists($notification, 'afterCommit') ? $notification->afterCommit : null; + $this->shouldBeEncrypted = $notification instanceof ShouldBeEncrypted; + } + + /** + * Wrap the notifiable(s) in a collection. + * + * @param \Illuminate\Notifications\Notifiable|\Illuminate\Support\Collection $notifiables + * @return \Illuminate\Support\Collection + */ + protected function wrapNotifiables($notifiables) + { + if ($notifiables instanceof Collection) { + return $notifiables; + } elseif ($notifiables instanceof Model) { + return EloquentCollection::wrap($notifiables); + } + + return Collection::wrap($notifiables); + } + + /** + * Send the notifications. + * + * @param \Illuminate\Notifications\ChannelManager $manager + * @return void + */ + public function handle(ChannelManager $manager) + { + $manager->sendNow($this->notifiables, $this->notification, $this->channels); + } + + /** + * Get the display name for the queued job. + * + * @return string + */ + public function displayName() + { + return get_class($this->notification); + } + + /** + * Call the failed method on the notification instance. + * + * @param \Throwable $e + * @return void + */ + public function failed($e) + { + if (method_exists($this->notification, 'failed')) { + $this->notification->failed($e); + } + } + + /** + * Get the number of seconds before a released notification will be available. + * + * @return mixed + */ + public function backoff() + { + if (! method_exists($this->notification, 'backoff') && ! isset($this->notification->backoff)) { + return; + } + + return $this->notification->backoff ?? $this->notification->backoff(); + } + + /** + * Get the expiration for the notification. + * + * @return mixed + */ + public function retryUntil() + { + if (! method_exists($this->notification, 'retryUntil') && ! isset($this->notification->retryUntil)) { + return; + } + + return $this->notification->retryUntil ?? $this->notification->retryUntil(); + } + + /** + * Prepare the instance for cloning. + * + * @return void + */ + public function __clone() + { + $this->notifiables = clone $this->notifiables; + $this->notification = clone $this->notification; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/composer.json new file mode 100644 index 0000000..1bc673a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/composer.json @@ -0,0 +1,45 @@ +{ + "name": "illuminate/notifications", + "description": "The Illuminate Notifications package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/broadcasting": "^8.0", + "illuminate/bus": "^8.0", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/mail": "^8.0", + "illuminate/queue": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Notifications\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "illuminate/database": "Required to use the database transport (^8.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php new file mode 100644 index 0000000..bcf39f0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php @@ -0,0 +1,62 @@ +@component('mail::message') +{{-- Greeting --}} +@if (! empty($greeting)) +# {{ $greeting }} +@else +@if ($level === 'error') +# @lang('Whoops!') +@else +# @lang('Hello!') +@endif +@endif + +{{-- Intro Lines --}} +@foreach ($introLines as $line) +{{ $line }} + +@endforeach + +{{-- Action Button --}} +@isset($actionText) + +@component('mail::button', ['url' => $actionUrl, 'color' => $color]) +{{ $actionText }} +@endcomponent +@endisset + +{{-- Outro Lines --}} +@foreach ($outroLines as $line) +{{ $line }} + +@endforeach + +{{-- Salutation --}} +@if (! empty($salutation)) +{{ $salutation }} +@else +@lang('Regards'),
+{{ config('app.name') }} +@endif + +{{-- Subcopy --}} +@isset($actionText) +@slot('subcopy') +@lang( + "If you're having trouble clicking the \":actionText\" button, copy and paste the URL below\n". + 'into your web browser:', + [ + 'actionText' => $actionText, + ] +) [{{ $displayableActionUrl }}]({{ $actionUrl }}) +@endslot +@endisset +@endcomponent diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/AbstractCursorPaginator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/AbstractCursorPaginator.php new file mode 100644 index 0000000..1234485 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/AbstractCursorPaginator.php @@ -0,0 +1,676 @@ +cursorName => $cursor->encode()]; + + if (count($this->query) > 0) { + $parameters = array_merge($this->query, $parameters); + } + + return $this->path() + .(Str::contains($this->path(), '?') ? '&' : '?') + .Arr::query($parameters) + .$this->buildFragment(); + } + + /** + * Get the URL for the previous page. + * + * @return string|null + */ + public function previousPageUrl() + { + if (is_null($previousCursor = $this->previousCursor())) { + return null; + } + + return $this->url($previousCursor); + } + + /** + * The URL for the next page, or null. + * + * @return string|null + */ + public function nextPageUrl() + { + if (is_null($nextCursor = $this->nextCursor())) { + return null; + } + + return $this->url($nextCursor); + } + + /** + * Get the "cursor" that points to the previous set of items. + * + * @return \Illuminate\Pagination\Cursor|null + */ + public function previousCursor() + { + if (is_null($this->cursor) || + ($this->cursor->pointsToPreviousItems() && ! $this->hasMore)) { + return null; + } + + if ($this->items->isEmpty()) { + return null; + } + + return $this->getCursorForItem($this->items->first(), false); + } + + /** + * Get the "cursor" that points to the next set of items. + * + * @return \Illuminate\Pagination\Cursor|null + */ + public function nextCursor() + { + if ((is_null($this->cursor) && ! $this->hasMore) || + (! is_null($this->cursor) && $this->cursor->pointsToNextItems() && ! $this->hasMore)) { + return null; + } + + if ($this->items->isEmpty()) { + return null; + } + + return $this->getCursorForItem($this->items->last(), true); + } + + /** + * Get a cursor instance for the given item. + * + * @param \ArrayAccess|\stdClass $item + * @param bool $isNext + * @return \Illuminate\Pagination\Cursor + */ + public function getCursorForItem($item, $isNext = true) + { + return new Cursor($this->getParametersForItem($item), $isNext); + } + + /** + * Get the cursor parameters for a given object. + * + * @param \ArrayAccess|\stdClass $item + * @return array + * + * @throws \Exception + */ + public function getParametersForItem($item) + { + return collect($this->parameters) + ->flip() + ->map(function ($_, $parameterName) use ($item) { + if ($item instanceof JsonResource) { + $item = $item->resource; + } + + if ($item instanceof Model && + ! is_null($parameter = $this->getPivotParameterForItem($item, $parameterName))) { + return $parameter; + } elseif ($item instanceof ArrayAccess || is_array($item)) { + return $this->ensureParameterIsPrimitive( + $item[$parameterName] ?? $item[Str::afterLast($parameterName, '.')] + ); + } elseif (is_object($item)) { + return $this->ensureParameterIsPrimitive( + $item->{$parameterName} ?? $item->{Str::afterLast($parameterName, '.')} + ); + } + + throw new Exception('Only arrays and objects are supported when cursor paginating items.'); + })->toArray(); + } + + /** + * Get the cursor parameter value from a pivot model if applicable. + * + * @param \ArrayAccess|\stdClass $item + * @param string $parameterName + * @return string|null + */ + protected function getPivotParameterForItem($item, $parameterName) + { + $table = Str::beforeLast($parameterName, '.'); + + foreach ($item->getRelations() as $relation) { + if ($relation instanceof Pivot && $relation->getTable() === $table) { + return $this->ensureParameterIsPrimitive( + $relation->getAttribute(Str::afterLast($parameterName, '.')) + ); + } + } + } + + /** + * Ensure the parameter is a primitive type. + * + * This can resolve issues that arise the developer uses a value object for an attribute. + * + * @param mixed $parameter + * @return mixed + */ + protected function ensureParameterIsPrimitive($parameter) + { + return is_object($parameter) && method_exists($parameter, '__toString') + ? (string) $parameter + : $parameter; + } + + /** + * Get / set the URL fragment to be appended to URLs. + * + * @param string|null $fragment + * @return $this|string|null + */ + public function fragment($fragment = null) + { + if (is_null($fragment)) { + return $this->fragment; + } + + $this->fragment = $fragment; + + return $this; + } + + /** + * Add a set of query string values to the paginator. + * + * @param array|string|null $key + * @param string|null $value + * @return $this + */ + public function appends($key, $value = null) + { + if (is_null($key)) { + return $this; + } + + if (is_array($key)) { + return $this->appendArray($key); + } + + return $this->addQuery($key, $value); + } + + /** + * Add an array of query string values. + * + * @param array $keys + * @return $this + */ + protected function appendArray(array $keys) + { + foreach ($keys as $key => $value) { + $this->addQuery($key, $value); + } + + return $this; + } + + /** + * Add all current query string values to the paginator. + * + * @return $this + */ + public function withQueryString() + { + if (! is_null($query = Paginator::resolveQueryString())) { + return $this->appends($query); + } + + return $this; + } + + /** + * Add a query string value to the paginator. + * + * @param string $key + * @param string $value + * @return $this + */ + protected function addQuery($key, $value) + { + if ($key !== $this->cursorName) { + $this->query[$key] = $value; + } + + return $this; + } + + /** + * Build the full fragment portion of a URL. + * + * @return string + */ + protected function buildFragment() + { + return $this->fragment ? '#'.$this->fragment : ''; + } + + /** + * Load a set of relationships onto the mixed relationship collection. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorph($relation, $relations) + { + $this->getCollection()->loadMorph($relation, $relations); + + return $this; + } + + /** + * Load a set of relationship counts onto the mixed relationship collection. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorphCount($relation, $relations) + { + $this->getCollection()->loadMorphCount($relation, $relations); + + return $this; + } + + /** + * Get the slice of items being paginated. + * + * @return array + */ + public function items() + { + return $this->items->all(); + } + + /** + * Transform each item in the slice of items using a callback. + * + * @param callable $callback + * @return $this + */ + public function through(callable $callback) + { + $this->items->transform($callback); + + return $this; + } + + /** + * Get the number of items shown per page. + * + * @return int + */ + public function perPage() + { + return $this->perPage; + } + + /** + * Get the current cursor being paginated. + * + * @return \Illuminate\Pagination\Cursor|null + */ + public function cursor() + { + return $this->cursor; + } + + /** + * Get the query string variable used to store the cursor. + * + * @return string + */ + public function getCursorName() + { + return $this->cursorName; + } + + /** + * Set the query string variable used to store the cursor. + * + * @param string $name + * @return $this + */ + public function setCursorName($name) + { + $this->cursorName = $name; + + return $this; + } + + /** + * Set the base path to assign to all URLs. + * + * @param string $path + * @return $this + */ + public function withPath($path) + { + return $this->setPath($path); + } + + /** + * Set the base path to assign to all URLs. + * + * @param string $path + * @return $this + */ + public function setPath($path) + { + $this->path = $path; + + return $this; + } + + /** + * Get the base path for paginator generated URLs. + * + * @return string|null + */ + public function path() + { + return $this->path; + } + + /** + * Resolve the current cursor or return the default value. + * + * @param string $cursorName + * @return \Illuminate\Pagination\Cursor|null + */ + public static function resolveCurrentCursor($cursorName = 'cursor', $default = null) + { + if (isset(static::$currentCursorResolver)) { + return call_user_func(static::$currentCursorResolver, $cursorName); + } + + return $default; + } + + /** + * Set the current cursor resolver callback. + * + * @param \Closure $resolver + * @return void + */ + public static function currentCursorResolver(Closure $resolver) + { + static::$currentCursorResolver = $resolver; + } + + /** + * Get an instance of the view factory from the resolver. + * + * @return \Illuminate\Contracts\View\Factory + */ + public static function viewFactory() + { + return Paginator::viewFactory(); + } + + /** + * Get an iterator for the items. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return $this->items->getIterator(); + } + + /** + * Determine if the list of items is empty. + * + * @return bool + */ + public function isEmpty() + { + return $this->items->isEmpty(); + } + + /** + * Determine if the list of items is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return $this->items->isNotEmpty(); + } + + /** + * Get the number of items for the current page. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return $this->items->count(); + } + + /** + * Get the paginator's underlying collection. + * + * @return \Illuminate\Support\Collection + */ + public function getCollection() + { + return $this->items; + } + + /** + * Set the paginator's underlying collection. + * + * @param \Illuminate\Support\Collection $collection + * @return $this + */ + public function setCollection(Collection $collection) + { + $this->items = $collection; + + return $this; + } + + /** + * Get the paginator options. + * + * @return array + */ + public function getOptions() + { + return $this->options; + } + + /** + * Determine if the given item exists. + * + * @param mixed $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->items->has($key); + } + + /** + * Get the item at the given offset. + * + * @param mixed $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->items->get($key); + } + + /** + * Set the item at the given offset. + * + * @param mixed $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->items->put($key, $value); + } + + /** + * Unset the item at the given key. + * + * @param mixed $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + $this->items->forget($key); + } + + /** + * Render the contents of the paginator to HTML. + * + * @return string + */ + public function toHtml() + { + return (string) $this->render(); + } + + /** + * Make dynamic calls into the collection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->forwardCallTo($this->getCollection(), $method, $parameters); + } + + /** + * Render the contents of the paginator when casting to a string. + * + * @return string + */ + public function __toString() + { + return (string) $this->render(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/AbstractPaginator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/AbstractPaginator.php new file mode 100644 index 0000000..ac9ef40 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/AbstractPaginator.php @@ -0,0 +1,782 @@ += 1 && filter_var($page, FILTER_VALIDATE_INT) !== false; + } + + /** + * Get the URL for the previous page. + * + * @return string|null + */ + public function previousPageUrl() + { + if ($this->currentPage() > 1) { + return $this->url($this->currentPage() - 1); + } + } + + /** + * Create a range of pagination URLs. + * + * @param int $start + * @param int $end + * @return array + */ + public function getUrlRange($start, $end) + { + return collect(range($start, $end))->mapWithKeys(function ($page) { + return [$page => $this->url($page)]; + })->all(); + } + + /** + * Get the URL for a given page number. + * + * @param int $page + * @return string + */ + public function url($page) + { + if ($page <= 0) { + $page = 1; + } + + // If we have any extra query string key / value pairs that need to be added + // onto the URL, we will put them in query string form and then attach it + // to the URL. This allows for extra information like sortings storage. + $parameters = [$this->pageName => $page]; + + if (count($this->query) > 0) { + $parameters = array_merge($this->query, $parameters); + } + + return $this->path() + .(Str::contains($this->path(), '?') ? '&' : '?') + .Arr::query($parameters) + .$this->buildFragment(); + } + + /** + * Get / set the URL fragment to be appended to URLs. + * + * @param string|null $fragment + * @return $this|string|null + */ + public function fragment($fragment = null) + { + if (is_null($fragment)) { + return $this->fragment; + } + + $this->fragment = $fragment; + + return $this; + } + + /** + * Add a set of query string values to the paginator. + * + * @param array|string|null $key + * @param string|null $value + * @return $this + */ + public function appends($key, $value = null) + { + if (is_null($key)) { + return $this; + } + + if (is_array($key)) { + return $this->appendArray($key); + } + + return $this->addQuery($key, $value); + } + + /** + * Add an array of query string values. + * + * @param array $keys + * @return $this + */ + protected function appendArray(array $keys) + { + foreach ($keys as $key => $value) { + $this->addQuery($key, $value); + } + + return $this; + } + + /** + * Add all current query string values to the paginator. + * + * @return $this + */ + public function withQueryString() + { + if (isset(static::$queryStringResolver)) { + return $this->appends(call_user_func(static::$queryStringResolver)); + } + + return $this; + } + + /** + * Add a query string value to the paginator. + * + * @param string $key + * @param string $value + * @return $this + */ + protected function addQuery($key, $value) + { + if ($key !== $this->pageName) { + $this->query[$key] = $value; + } + + return $this; + } + + /** + * Build the full fragment portion of a URL. + * + * @return string + */ + protected function buildFragment() + { + return $this->fragment ? '#'.$this->fragment : ''; + } + + /** + * Load a set of relationships onto the mixed relationship collection. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorph($relation, $relations) + { + $this->getCollection()->loadMorph($relation, $relations); + + return $this; + } + + /** + * Load a set of relationship counts onto the mixed relationship collection. + * + * @param string $relation + * @param array $relations + * @return $this + */ + public function loadMorphCount($relation, $relations) + { + $this->getCollection()->loadMorphCount($relation, $relations); + + return $this; + } + + /** + * Get the slice of items being paginated. + * + * @return array + */ + public function items() + { + return $this->items->all(); + } + + /** + * Get the number of the first item in the slice. + * + * @return int + */ + public function firstItem() + { + return count($this->items) > 0 ? ($this->currentPage - 1) * $this->perPage + 1 : null; + } + + /** + * Get the number of the last item in the slice. + * + * @return int + */ + public function lastItem() + { + return count($this->items) > 0 ? $this->firstItem() + $this->count() - 1 : null; + } + + /** + * Transform each item in the slice of items using a callback. + * + * @param callable $callback + * @return $this + */ + public function through(callable $callback) + { + $this->items->transform($callback); + + return $this; + } + + /** + * Get the number of items shown per page. + * + * @return int + */ + public function perPage() + { + return $this->perPage; + } + + /** + * Determine if there are enough items to split into multiple pages. + * + * @return bool + */ + public function hasPages() + { + return $this->currentPage() != 1 || $this->hasMorePages(); + } + + /** + * Determine if the paginator is on the first page. + * + * @return bool + */ + public function onFirstPage() + { + return $this->currentPage() <= 1; + } + + /** + * Determine if the paginator is on the last page. + * + * @return bool + */ + public function onLastPage() + { + return ! $this->hasMorePages(); + } + + /** + * Get the current page. + * + * @return int + */ + public function currentPage() + { + return $this->currentPage; + } + + /** + * Get the query string variable used to store the page. + * + * @return string + */ + public function getPageName() + { + return $this->pageName; + } + + /** + * Set the query string variable used to store the page. + * + * @param string $name + * @return $this + */ + public function setPageName($name) + { + $this->pageName = $name; + + return $this; + } + + /** + * Set the base path to assign to all URLs. + * + * @param string $path + * @return $this + */ + public function withPath($path) + { + return $this->setPath($path); + } + + /** + * Set the base path to assign to all URLs. + * + * @param string $path + * @return $this + */ + public function setPath($path) + { + $this->path = $path; + + return $this; + } + + /** + * Set the number of links to display on each side of current page link. + * + * @param int $count + * @return $this + */ + public function onEachSide($count) + { + $this->onEachSide = $count; + + return $this; + } + + /** + * Get the base path for paginator generated URLs. + * + * @return string|null + */ + public function path() + { + return $this->path; + } + + /** + * Resolve the current request path or return the default value. + * + * @param string $default + * @return string + */ + public static function resolveCurrentPath($default = '/') + { + if (isset(static::$currentPathResolver)) { + return call_user_func(static::$currentPathResolver); + } + + return $default; + } + + /** + * Set the current request path resolver callback. + * + * @param \Closure $resolver + * @return void + */ + public static function currentPathResolver(Closure $resolver) + { + static::$currentPathResolver = $resolver; + } + + /** + * Resolve the current page or return the default value. + * + * @param string $pageName + * @param int $default + * @return int + */ + public static function resolveCurrentPage($pageName = 'page', $default = 1) + { + if (isset(static::$currentPageResolver)) { + return (int) call_user_func(static::$currentPageResolver, $pageName); + } + + return $default; + } + + /** + * Set the current page resolver callback. + * + * @param \Closure $resolver + * @return void + */ + public static function currentPageResolver(Closure $resolver) + { + static::$currentPageResolver = $resolver; + } + + /** + * Resolve the query string or return the default value. + * + * @param string|array|null $default + * @return string + */ + public static function resolveQueryString($default = null) + { + if (isset(static::$queryStringResolver)) { + return (static::$queryStringResolver)(); + } + + return $default; + } + + /** + * Set with query string resolver callback. + * + * @param \Closure $resolver + * @return void + */ + public static function queryStringResolver(Closure $resolver) + { + static::$queryStringResolver = $resolver; + } + + /** + * Get an instance of the view factory from the resolver. + * + * @return \Illuminate\Contracts\View\Factory + */ + public static function viewFactory() + { + return call_user_func(static::$viewFactoryResolver); + } + + /** + * Set the view factory resolver callback. + * + * @param \Closure $resolver + * @return void + */ + public static function viewFactoryResolver(Closure $resolver) + { + static::$viewFactoryResolver = $resolver; + } + + /** + * Set the default pagination view. + * + * @param string $view + * @return void + */ + public static function defaultView($view) + { + static::$defaultView = $view; + } + + /** + * Set the default "simple" pagination view. + * + * @param string $view + * @return void + */ + public static function defaultSimpleView($view) + { + static::$defaultSimpleView = $view; + } + + /** + * Indicate that Tailwind styling should be used for generated links. + * + * @return void + */ + public static function useTailwind() + { + static::defaultView('pagination::tailwind'); + static::defaultSimpleView('pagination::simple-tailwind'); + } + + /** + * Indicate that Bootstrap 4 styling should be used for generated links. + * + * @return void + */ + public static function useBootstrap() + { + static::defaultView('pagination::bootstrap-4'); + static::defaultSimpleView('pagination::simple-bootstrap-4'); + } + + /** + * Indicate that Bootstrap 3 styling should be used for generated links. + * + * @return void + */ + public static function useBootstrapThree() + { + static::defaultView('pagination::default'); + static::defaultSimpleView('pagination::simple-default'); + } + + /** + * Get an iterator for the items. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return $this->items->getIterator(); + } + + /** + * Determine if the list of items is empty. + * + * @return bool + */ + public function isEmpty() + { + return $this->items->isEmpty(); + } + + /** + * Determine if the list of items is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return $this->items->isNotEmpty(); + } + + /** + * Get the number of items for the current page. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return $this->items->count(); + } + + /** + * Get the paginator's underlying collection. + * + * @return \Illuminate\Support\Collection + */ + public function getCollection() + { + return $this->items; + } + + /** + * Set the paginator's underlying collection. + * + * @param \Illuminate\Support\Collection $collection + * @return $this + */ + public function setCollection(Collection $collection) + { + $this->items = $collection; + + return $this; + } + + /** + * Get the paginator options. + * + * @return array + */ + public function getOptions() + { + return $this->options; + } + + /** + * Determine if the given item exists. + * + * @param mixed $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->items->has($key); + } + + /** + * Get the item at the given offset. + * + * @param mixed $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->items->get($key); + } + + /** + * Set the item at the given offset. + * + * @param mixed $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->items->put($key, $value); + } + + /** + * Unset the item at the given key. + * + * @param mixed $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + $this->items->forget($key); + } + + /** + * Render the contents of the paginator to HTML. + * + * @return string + */ + public function toHtml() + { + return (string) $this->render(); + } + + /** + * Make dynamic calls into the collection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->forwardCallTo($this->getCollection(), $method, $parameters); + } + + /** + * Render the contents of the paginator when casting to a string. + * + * @return string + */ + public function __toString() + { + return (string) $this->render(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/Cursor.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/Cursor.php new file mode 100644 index 0000000..e8edf65 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/Cursor.php @@ -0,0 +1,132 @@ +parameters = $parameters; + $this->pointsToNextItems = $pointsToNextItems; + } + + /** + * Get the given parameter from the cursor. + * + * @param string $parameterName + * @return string|null + * + * @throws \UnexpectedValueException + */ + public function parameter(string $parameterName) + { + if (! array_key_exists($parameterName, $this->parameters)) { + throw new UnexpectedValueException("Unable to find parameter [{$parameterName}] in pagination item."); + } + + return $this->parameters[$parameterName]; + } + + /** + * Get the given parameters from the cursor. + * + * @param array $parameterNames + * @return array + */ + public function parameters(array $parameterNames) + { + return collect($parameterNames)->map(function ($parameterName) { + return $this->parameter($parameterName); + })->toArray(); + } + + /** + * Determine whether the cursor points to the next set of items. + * + * @return bool + */ + public function pointsToNextItems() + { + return $this->pointsToNextItems; + } + + /** + * Determine whether the cursor points to the previous set of items. + * + * @return bool + */ + public function pointsToPreviousItems() + { + return ! $this->pointsToNextItems; + } + + /** + * Get the array representation of the cursor. + * + * @return array + */ + public function toArray() + { + return array_merge($this->parameters, [ + '_pointsToNextItems' => $this->pointsToNextItems, + ]); + } + + /** + * Get the encoded string representation of the cursor to construct a URL. + * + * @return string + */ + public function encode() + { + return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode($this->toArray()))); + } + + /** + * Get a cursor instance from the encoded string representation. + * + * @param string|null $encodedString + * @return static|null + */ + public static function fromEncoded($encodedString) + { + if (is_null($encodedString) || ! is_string($encodedString)) { + return null; + } + + $parameters = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $encodedString)), true); + + if (json_last_error() !== JSON_ERROR_NONE) { + return null; + } + + $pointsToNextItems = $parameters['_pointsToNextItems']; + + unset($parameters['_pointsToNextItems']); + + return new static($parameters, $pointsToNextItems); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/CursorPaginationException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/CursorPaginationException.php new file mode 100644 index 0000000..b12ca60 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/CursorPaginationException.php @@ -0,0 +1,13 @@ +options = $options; + + foreach ($options as $key => $value) { + $this->{$key} = $value; + } + + $this->perPage = $perPage; + $this->cursor = $cursor; + $this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path; + + $this->setItems($items); + } + + /** + * Set the items for the paginator. + * + * @param mixed $items + * @return void + */ + protected function setItems($items) + { + $this->items = $items instanceof Collection ? $items : Collection::make($items); + + $this->hasMore = $this->items->count() > $this->perPage; + + $this->items = $this->items->slice(0, $this->perPage); + + if (! is_null($this->cursor) && $this->cursor->pointsToPreviousItems()) { + $this->items = $this->items->reverse()->values(); + } + } + + /** + * Render the paginator using the given view. + * + * @param string|null $view + * @param array $data + * @return \Illuminate\Contracts\Support\Htmlable + */ + public function links($view = null, $data = []) + { + return $this->render($view, $data); + } + + /** + * Render the paginator using the given view. + * + * @param string|null $view + * @param array $data + * @return \Illuminate\Contracts\Support\Htmlable + */ + public function render($view = null, $data = []) + { + return static::viewFactory()->make($view ?: Paginator::$defaultSimpleView, array_merge($data, [ + 'paginator' => $this, + ])); + } + + /** + * Determine if there are more items in the data source. + * + * @return bool + */ + public function hasMorePages() + { + return (is_null($this->cursor) && $this->hasMore) || + (! is_null($this->cursor) && $this->cursor->pointsToNextItems() && $this->hasMore) || + (! is_null($this->cursor) && $this->cursor->pointsToPreviousItems()); + } + + /** + * Determine if there are enough items to split into multiple pages. + * + * @return bool + */ + public function hasPages() + { + return ! $this->onFirstPage() || $this->hasMorePages(); + } + + /** + * Determine if the paginator is on the first page. + * + * @return bool + */ + public function onFirstPage() + { + return is_null($this->cursor) || ($this->cursor->pointsToPreviousItems() && ! $this->hasMore); + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return [ + 'data' => $this->items->toArray(), + 'path' => $this->path(), + 'per_page' => $this->perPage(), + 'next_page_url' => $this->nextPageUrl(), + 'prev_page_url' => $this->previousPageUrl(), + ]; + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/LengthAwarePaginator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/LengthAwarePaginator.php new file mode 100644 index 0000000..24f68b1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/LengthAwarePaginator.php @@ -0,0 +1,232 @@ +options = $options; + + foreach ($options as $key => $value) { + $this->{$key} = $value; + } + + $this->total = $total; + $this->perPage = $perPage; + $this->lastPage = max((int) ceil($total / $perPage), 1); + $this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path; + $this->currentPage = $this->setCurrentPage($currentPage, $this->pageName); + $this->items = $items instanceof Collection ? $items : Collection::make($items); + } + + /** + * Get the current page for the request. + * + * @param int $currentPage + * @param string $pageName + * @return int + */ + protected function setCurrentPage($currentPage, $pageName) + { + $currentPage = $currentPage ?: static::resolveCurrentPage($pageName); + + return $this->isValidPageNumber($currentPage) ? (int) $currentPage : 1; + } + + /** + * Render the paginator using the given view. + * + * @param string|null $view + * @param array $data + * @return \Illuminate\Contracts\Support\Htmlable + */ + public function links($view = null, $data = []) + { + return $this->render($view, $data); + } + + /** + * Render the paginator using the given view. + * + * @param string|null $view + * @param array $data + * @return \Illuminate\Contracts\Support\Htmlable + */ + public function render($view = null, $data = []) + { + return static::viewFactory()->make($view ?: static::$defaultView, array_merge($data, [ + 'paginator' => $this, + 'elements' => $this->elements(), + ])); + } + + /** + * Get the paginator links as a collection (for JSON responses). + * + * @return \Illuminate\Support\Collection + */ + public function linkCollection() + { + return collect($this->elements())->flatMap(function ($item) { + if (! is_array($item)) { + return [['url' => null, 'label' => '...', 'active' => false]]; + } + + return collect($item)->map(function ($url, $page) { + return [ + 'url' => $url, + 'label' => (string) $page, + 'active' => $this->currentPage() === $page, + ]; + }); + })->prepend([ + 'url' => $this->previousPageUrl(), + 'label' => function_exists('__') ? __('pagination.previous') : 'Previous', + 'active' => false, + ])->push([ + 'url' => $this->nextPageUrl(), + 'label' => function_exists('__') ? __('pagination.next') : 'Next', + 'active' => false, + ]); + } + + /** + * Get the array of elements to pass to the view. + * + * @return array + */ + protected function elements() + { + $window = UrlWindow::make($this); + + return array_filter([ + $window['first'], + is_array($window['slider']) ? '...' : null, + $window['slider'], + is_array($window['last']) ? '...' : null, + $window['last'], + ]); + } + + /** + * Get the total number of items being paginated. + * + * @return int + */ + public function total() + { + return $this->total; + } + + /** + * Determine if there are more items in the data source. + * + * @return bool + */ + public function hasMorePages() + { + return $this->currentPage() < $this->lastPage(); + } + + /** + * Get the URL for the next page. + * + * @return string|null + */ + public function nextPageUrl() + { + if ($this->hasMorePages()) { + return $this->url($this->currentPage() + 1); + } + } + + /** + * Get the last page. + * + * @return int + */ + public function lastPage() + { + return $this->lastPage; + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return [ + 'current_page' => $this->currentPage(), + 'data' => $this->items->toArray(), + 'first_page_url' => $this->url(1), + 'from' => $this->firstItem(), + 'last_page' => $this->lastPage(), + 'last_page_url' => $this->url($this->lastPage()), + 'links' => $this->linkCollection()->toArray(), + 'next_page_url' => $this->nextPageUrl(), + 'path' => $this->path(), + 'per_page' => $this->perPage(), + 'prev_page_url' => $this->previousPageUrl(), + 'to' => $this->lastItem(), + 'total' => $this->total(), + ]; + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/PaginationServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/PaginationServiceProvider.php new file mode 100755 index 0000000..e94cebd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/PaginationServiceProvider.php @@ -0,0 +1,34 @@ +loadViewsFrom(__DIR__.'/resources/views', 'pagination'); + + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__.'/resources/views' => $this->app->resourcePath('views/vendor/pagination'), + ], 'laravel-pagination'); + } + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + PaginationState::resolveUsing($this->app); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/PaginationState.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/PaginationState.php new file mode 100644 index 0000000..ff8150f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/PaginationState.php @@ -0,0 +1,41 @@ +url(); + }); + + Paginator::currentPageResolver(function ($pageName = 'page') use ($app) { + $page = $app['request']->input($pageName); + + if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) { + return (int) $page; + } + + return 1; + }); + + Paginator::queryStringResolver(function () use ($app) { + return $app['request']->query(); + }); + + CursorPaginator::currentCursorResolver(function ($cursorName = 'cursor') use ($app) { + return Cursor::fromEncoded($app['request']->input($cursorName)); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/Paginator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/Paginator.php new file mode 100644 index 0000000..733edb8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/Paginator.php @@ -0,0 +1,177 @@ +options = $options; + + foreach ($options as $key => $value) { + $this->{$key} = $value; + } + + $this->perPage = $perPage; + $this->currentPage = $this->setCurrentPage($currentPage); + $this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path; + + $this->setItems($items); + } + + /** + * Get the current page for the request. + * + * @param int $currentPage + * @return int + */ + protected function setCurrentPage($currentPage) + { + $currentPage = $currentPage ?: static::resolveCurrentPage(); + + return $this->isValidPageNumber($currentPage) ? (int) $currentPage : 1; + } + + /** + * Set the items for the paginator. + * + * @param mixed $items + * @return void + */ + protected function setItems($items) + { + $this->items = $items instanceof Collection ? $items : Collection::make($items); + + $this->hasMore = $this->items->count() > $this->perPage; + + $this->items = $this->items->slice(0, $this->perPage); + } + + /** + * Get the URL for the next page. + * + * @return string|null + */ + public function nextPageUrl() + { + if ($this->hasMorePages()) { + return $this->url($this->currentPage() + 1); + } + } + + /** + * Render the paginator using the given view. + * + * @param string|null $view + * @param array $data + * @return string + */ + public function links($view = null, $data = []) + { + return $this->render($view, $data); + } + + /** + * Render the paginator using the given view. + * + * @param string|null $view + * @param array $data + * @return \Illuminate\Contracts\Support\Htmlable + */ + public function render($view = null, $data = []) + { + return static::viewFactory()->make($view ?: static::$defaultSimpleView, array_merge($data, [ + 'paginator' => $this, + ])); + } + + /** + * Manually indicate that the paginator does have more pages. + * + * @param bool $hasMore + * @return $this + */ + public function hasMorePagesWhen($hasMore = true) + { + $this->hasMore = $hasMore; + + return $this; + } + + /** + * Determine if there are more items in the data source. + * + * @return bool + */ + public function hasMorePages() + { + return $this->hasMore; + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return [ + 'current_page' => $this->currentPage(), + 'data' => $this->items->toArray(), + 'first_page_url' => $this->url(1), + 'from' => $this->firstItem(), + 'next_page_url' => $this->nextPageUrl(), + 'path' => $this->path(), + 'per_page' => $this->perPage(), + 'prev_page_url' => $this->previousPageUrl(), + 'to' => $this->lastItem(), + ]; + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/UrlWindow.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/UrlWindow.php new file mode 100644 index 0000000..31c7cc2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/UrlWindow.php @@ -0,0 +1,220 @@ +paginator = $paginator; + } + + /** + * Create a new URL window instance. + * + * @param \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginator + * @return array + */ + public static function make(PaginatorContract $paginator) + { + return (new static($paginator))->get(); + } + + /** + * Get the window of URLs to be shown. + * + * @return array + */ + public function get() + { + $onEachSide = $this->paginator->onEachSide; + + if ($this->paginator->lastPage() < ($onEachSide * 2) + 8) { + return $this->getSmallSlider(); + } + + return $this->getUrlSlider($onEachSide); + } + + /** + * Get the slider of URLs there are not enough pages to slide. + * + * @return array + */ + protected function getSmallSlider() + { + return [ + 'first' => $this->paginator->getUrlRange(1, $this->lastPage()), + 'slider' => null, + 'last' => null, + ]; + } + + /** + * Create a URL slider links. + * + * @param int $onEachSide + * @return array + */ + protected function getUrlSlider($onEachSide) + { + $window = $onEachSide + 4; + + if (! $this->hasPages()) { + return ['first' => null, 'slider' => null, 'last' => null]; + } + + // If the current page is very close to the beginning of the page range, we will + // just render the beginning of the page range, followed by the last 2 of the + // links in this list, since we will not have room to create a full slider. + if ($this->currentPage() <= $window) { + return $this->getSliderTooCloseToBeginning($window, $onEachSide); + } + + // If the current page is close to the ending of the page range we will just get + // this first couple pages, followed by a larger window of these ending pages + // since we're too close to the end of the list to create a full on slider. + elseif ($this->currentPage() > ($this->lastPage() - $window)) { + return $this->getSliderTooCloseToEnding($window, $onEachSide); + } + + // If we have enough room on both sides of the current page to build a slider we + // will surround it with both the beginning and ending caps, with this window + // of pages in the middle providing a Google style sliding paginator setup. + return $this->getFullSlider($onEachSide); + } + + /** + * Get the slider of URLs when too close to beginning of window. + * + * @param int $window + * @param int $onEachSide + * @return array + */ + protected function getSliderTooCloseToBeginning($window, $onEachSide) + { + return [ + 'first' => $this->paginator->getUrlRange(1, $window + $onEachSide), + 'slider' => null, + 'last' => $this->getFinish(), + ]; + } + + /** + * Get the slider of URLs when too close to ending of window. + * + * @param int $window + * @param int $onEachSide + * @return array + */ + protected function getSliderTooCloseToEnding($window, $onEachSide) + { + $last = $this->paginator->getUrlRange( + $this->lastPage() - ($window + ($onEachSide - 1)), + $this->lastPage() + ); + + return [ + 'first' => $this->getStart(), + 'slider' => null, + 'last' => $last, + ]; + } + + /** + * Get the slider of URLs when a full slider can be made. + * + * @param int $onEachSide + * @return array + */ + protected function getFullSlider($onEachSide) + { + return [ + 'first' => $this->getStart(), + 'slider' => $this->getAdjacentUrlRange($onEachSide), + 'last' => $this->getFinish(), + ]; + } + + /** + * Get the page range for the current page window. + * + * @param int $onEachSide + * @return array + */ + public function getAdjacentUrlRange($onEachSide) + { + return $this->paginator->getUrlRange( + $this->currentPage() - $onEachSide, + $this->currentPage() + $onEachSide + ); + } + + /** + * Get the starting URLs of a pagination slider. + * + * @return array + */ + public function getStart() + { + return $this->paginator->getUrlRange(1, 2); + } + + /** + * Get the ending URLs of a pagination slider. + * + * @return array + */ + public function getFinish() + { + return $this->paginator->getUrlRange( + $this->lastPage() - 1, + $this->lastPage() + ); + } + + /** + * Determine if the underlying paginator being presented has pages to show. + * + * @return bool + */ + public function hasPages() + { + return $this->paginator->lastPage() > 1; + } + + /** + * Get the current page from the paginator. + * + * @return int + */ + protected function currentPage() + { + return $this->paginator->currentPage(); + } + + /** + * Get the last page from the paginator. + * + * @return int + */ + protected function lastPage() + { + return $this->paginator->lastPage(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/composer.json new file mode 100755 index 0000000..5c8a380 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/composer.json @@ -0,0 +1,37 @@ +{ + "name": "illuminate/pagination", + "description": "The Illuminate Pagination package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Pagination\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/bootstrap-4.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/bootstrap-4.blade.php new file mode 100644 index 0000000..63c6f56 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/bootstrap-4.blade.php @@ -0,0 +1,46 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/default.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/default.blade.php new file mode 100644 index 0000000..0db70b5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/default.blade.php @@ -0,0 +1,46 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/semantic-ui.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/semantic-ui.blade.php new file mode 100644 index 0000000..ef0dbb1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/semantic-ui.blade.php @@ -0,0 +1,36 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-bootstrap-4.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-bootstrap-4.blade.php new file mode 100644 index 0000000..4bb4917 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-bootstrap-4.blade.php @@ -0,0 +1,27 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-default.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-default.blade.php new file mode 100644 index 0000000..36bdbc1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-default.blade.php @@ -0,0 +1,19 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-tailwind.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-tailwind.blade.php new file mode 100644 index 0000000..6872cca --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/simple-tailwind.blade.php @@ -0,0 +1,25 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/tailwind.blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/tailwind.blade.php new file mode 100644 index 0000000..5bf323b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pagination/resources/views/tailwind.blade.php @@ -0,0 +1,106 @@ +@if ($paginator->hasPages()) + +@endif diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/Hub.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/Hub.php new file mode 100644 index 0000000..91e9b3f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/Hub.php @@ -0,0 +1,97 @@ +container = $container; + } + + /** + * Define the default named pipeline. + * + * @param \Closure $callback + * @return void + */ + public function defaults(Closure $callback) + { + return $this->pipeline('default', $callback); + } + + /** + * Define a new named pipeline. + * + * @param string $name + * @param \Closure $callback + * @return void + */ + public function pipeline($name, Closure $callback) + { + $this->pipelines[$name] = $callback; + } + + /** + * Send an object through one of the available pipelines. + * + * @param mixed $object + * @param string|null $pipeline + * @return mixed + */ + public function pipe($object, $pipeline = null) + { + $pipeline = $pipeline ?: 'default'; + + return call_user_func( + $this->pipelines[$pipeline], new Pipeline($this->container), $object + ); + } + + /** + * Get the container instance used by the hub. + * + * @return \Illuminate\Contracts\Container\Container + */ + public function getContainer() + { + return $this->container; + } + + /** + * Set the container instance used by the hub. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php new file mode 100644 index 0000000..d2924e5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php @@ -0,0 +1,258 @@ +container = $container; + } + + /** + * Set the object being sent through the pipeline. + * + * @param mixed $passable + * @return $this + */ + public function send($passable) + { + $this->passable = $passable; + + return $this; + } + + /** + * Set the array of pipes. + * + * @param array|mixed $pipes + * @return $this + */ + public function through($pipes) + { + $this->pipes = is_array($pipes) ? $pipes : func_get_args(); + + return $this; + } + + /** + * Set the method to call on the pipes. + * + * @param string $method + * @return $this + */ + public function via($method) + { + $this->method = $method; + + return $this; + } + + /** + * Run the pipeline with a final destination callback. + * + * @param \Closure $destination + * @return mixed + */ + public function then(Closure $destination) + { + $pipeline = array_reduce( + array_reverse($this->pipes()), $this->carry(), $this->prepareDestination($destination) + ); + + return $pipeline($this->passable); + } + + /** + * Run the pipeline and return the result. + * + * @return mixed + */ + public function thenReturn() + { + return $this->then(function ($passable) { + return $passable; + }); + } + + /** + * Get the final piece of the Closure onion. + * + * @param \Closure $destination + * @return \Closure + */ + protected function prepareDestination(Closure $destination) + { + return function ($passable) use ($destination) { + try { + return $destination($passable); + } catch (Throwable $e) { + return $this->handleException($passable, $e); + } + }; + } + + /** + * Get a Closure that represents a slice of the application onion. + * + * @return \Closure + */ + protected function carry() + { + return function ($stack, $pipe) { + return function ($passable) use ($stack, $pipe) { + try { + if (is_callable($pipe)) { + // If the pipe is a callable, then we will call it directly, but otherwise we + // will resolve the pipes out of the dependency container and call it with + // the appropriate method and arguments, returning the results back out. + return $pipe($passable, $stack); + } elseif (! is_object($pipe)) { + [$name, $parameters] = $this->parsePipeString($pipe); + + // If the pipe is a string we will parse the string and resolve the class out + // of the dependency injection container. We can then build a callable and + // execute the pipe function giving in the parameters that are required. + $pipe = $this->getContainer()->make($name); + + $parameters = array_merge([$passable, $stack], $parameters); + } else { + // If the pipe is already an object we'll just make a callable and pass it to + // the pipe as-is. There is no need to do any extra parsing and formatting + // since the object we're given was already a fully instantiated object. + $parameters = [$passable, $stack]; + } + + $carry = method_exists($pipe, $this->method) + ? $pipe->{$this->method}(...$parameters) + : $pipe(...$parameters); + + return $this->handleCarry($carry); + } catch (Throwable $e) { + return $this->handleException($passable, $e); + } + }; + }; + } + + /** + * Parse full pipe string to get name and parameters. + * + * @param string $pipe + * @return array + */ + protected function parsePipeString($pipe) + { + [$name, $parameters] = array_pad(explode(':', $pipe, 2), 2, []); + + if (is_string($parameters)) { + $parameters = explode(',', $parameters); + } + + return [$name, $parameters]; + } + + /** + * Get the array of configured pipes. + * + * @return array + */ + protected function pipes() + { + return $this->pipes; + } + + /** + * Get the container instance. + * + * @return \Illuminate\Contracts\Container\Container + * + * @throws \RuntimeException + */ + protected function getContainer() + { + if (! $this->container) { + throw new RuntimeException('A container instance has not been passed to the Pipeline.'); + } + + return $this->container; + } + + /** + * Set the container instance. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } + + /** + * Handle the value returned from each pipe before passing it to the next. + * + * @param mixed $carry + * @return mixed + */ + protected function handleCarry($carry) + { + return $carry; + } + + /** + * Handle the given exception. + * + * @param mixed $passable + * @param \Throwable $e + * @return mixed + * + * @throws \Throwable + */ + protected function handleException($passable, Throwable $e) + { + throw $e; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/PipelineServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/PipelineServiceProvider.php new file mode 100644 index 0000000..982608b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/PipelineServiceProvider.php @@ -0,0 +1,34 @@ +app->singleton( + PipelineHubContract::class, Hub::class + ); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + PipelineHubContract::class, + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/composer.json new file mode 100644 index 0000000..ef6805b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Pipeline/composer.json @@ -0,0 +1,35 @@ +{ + "name": "illuminate/pipeline", + "description": "The Illuminate Pipeline package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/contracts": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Pipeline\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/BeanstalkdQueue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/BeanstalkdQueue.php new file mode 100755 index 0000000..b258c49 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/BeanstalkdQueue.php @@ -0,0 +1,192 @@ +default = $default; + $this->blockFor = $blockFor; + $this->timeToRun = $timeToRun; + $this->pheanstalk = $pheanstalk; + $this->dispatchAfterCommit = $dispatchAfterCommit; + } + + /** + * Get the size of the queue. + * + * @param string|null $queue + * @return int + */ + public function size($queue = null) + { + $queue = $this->getQueue($queue); + + return (int) $this->pheanstalk->statsTube($queue)->current_jobs_ready; + } + + /** + * Push a new job onto the queue. + * + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function push($job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $this->getQueue($queue), $data), + $queue, + null, + function ($payload, $queue) { + return $this->pushRaw($payload, $queue); + } + ); + } + + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + */ + public function pushRaw($payload, $queue = null, array $options = []) + { + return $this->pheanstalk->useTube($this->getQueue($queue))->put( + $payload, Pheanstalk::DEFAULT_PRIORITY, Pheanstalk::DEFAULT_DELAY, $this->timeToRun + ); + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function later($delay, $job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $this->getQueue($queue), $data), + $queue, + $delay, + function ($payload, $queue, $delay) { + return $this->pheanstalk->useTube($this->getQueue($queue))->put( + $payload, + Pheanstalk::DEFAULT_PRIORITY, + $this->secondsUntil($delay), + $this->timeToRun + ); + } + ); + } + + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + */ + public function pop($queue = null) + { + $queue = $this->getQueue($queue); + + $job = $this->pheanstalk->watchOnly($queue)->reserveWithTimeout($this->blockFor); + + if ($job instanceof PheanstalkJob) { + return new BeanstalkdJob( + $this->container, $this->pheanstalk, $job, $this->connectionName, $queue + ); + } + } + + /** + * Delete a message from the Beanstalk queue. + * + * @param string $queue + * @param string|int $id + * @return void + */ + public function deleteMessage($queue, $id) + { + $queue = $this->getQueue($queue); + + $this->pheanstalk->useTube($queue)->delete(new PheanstalkJob($id, '')); + } + + /** + * Get the queue or return the default. + * + * @param string|null $queue + * @return string + */ + public function getQueue($queue) + { + return $queue ?: $this->default; + } + + /** + * Get the underlying Pheanstalk instance. + * + * @return \Pheanstalk\Pheanstalk + */ + public function getPheanstalk() + { + return $this->pheanstalk; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedClosure.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedClosure.php new file mode 100644 index 0000000..24a72d9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedClosure.php @@ -0,0 +1,110 @@ +closure = $closure; + } + + /** + * Create a new job instance. + * + * @param \Closure $job + * @return self + */ + public static function create(Closure $job) + { + return new self(SerializableClosureFactory::make($job)); + } + + /** + * Execute the job. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function handle(Container $container) + { + $container->call($this->closure->getClosure(), ['job' => $this]); + } + + /** + * Add a callback to be executed if the job fails. + * + * @param callable $callback + * @return $this + */ + public function onFailure($callback) + { + $this->failureCallbacks[] = $callback instanceof Closure + ? SerializableClosureFactory::make($callback) + : $callback; + + return $this; + } + + /** + * Handle a job failure. + * + * @param \Throwable $e + * @return void + */ + public function failed($e) + { + foreach ($this->failureCallbacks as $callback) { + $callback($e); + } + } + + /** + * Get the display name for the queued job. + * + * @return string + */ + public function displayName() + { + $reflection = new ReflectionFunction($this->closure->getClosure()); + + return 'Closure ('.basename($reflection->getFileName()).':'.$reflection->getStartLine().')'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php new file mode 100644 index 0000000..dcd8210 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php @@ -0,0 +1,299 @@ +container = $container; + $this->dispatcher = $dispatcher; + } + + /** + * Handle the queued job. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param array $data + * @return void + */ + public function call(Job $job, array $data) + { + try { + $command = $this->setJobInstanceIfNecessary( + $job, $this->getCommand($data) + ); + } catch (ModelNotFoundException $e) { + return $this->handleModelNotFound($job, $e); + } + + if ($command instanceof ShouldBeUniqueUntilProcessing) { + $this->ensureUniqueJobLockIsReleased($command); + } + + $this->dispatchThroughMiddleware($job, $command); + + if (! $job->isReleased() && ! $command instanceof ShouldBeUniqueUntilProcessing) { + $this->ensureUniqueJobLockIsReleased($command); + } + + if (! $job->hasFailed() && ! $job->isReleased()) { + $this->ensureNextJobInChainIsDispatched($command); + $this->ensureSuccessfulBatchJobIsRecorded($command); + } + + if (! $job->isDeletedOrReleased()) { + $job->delete(); + } + } + + /** + * Get the command from the given payload. + * + * @param array $data + * @return mixed + * + * @throws \RuntimeException + */ + protected function getCommand(array $data) + { + if (Str::startsWith($data['command'], 'O:')) { + return unserialize($data['command']); + } + + if ($this->container->bound(Encrypter::class)) { + return unserialize($this->container[Encrypter::class]->decrypt($data['command'])); + } + + throw new RuntimeException('Unable to extract job payload.'); + } + + /** + * Dispatch the given job / command through its specified middleware. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param mixed $command + * @return mixed + */ + protected function dispatchThroughMiddleware(Job $job, $command) + { + return (new Pipeline($this->container))->send($command) + ->through(array_merge(method_exists($command, 'middleware') ? $command->middleware() : [], $command->middleware ?? [])) + ->then(function ($command) use ($job) { + return $this->dispatcher->dispatchNow( + $command, $this->resolveHandler($job, $command) + ); + }); + } + + /** + * Resolve the handler for the given command. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param mixed $command + * @return mixed + */ + protected function resolveHandler($job, $command) + { + $handler = $this->dispatcher->getCommandHandler($command) ?: null; + + if ($handler) { + $this->setJobInstanceIfNecessary($job, $handler); + } + + return $handler; + } + + /** + * Set the job instance of the given class if necessary. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param mixed $instance + * @return mixed + */ + protected function setJobInstanceIfNecessary(Job $job, $instance) + { + if (in_array(InteractsWithQueue::class, class_uses_recursive($instance))) { + $instance->setJob($job); + } + + return $instance; + } + + /** + * Ensure the next job in the chain is dispatched if applicable. + * + * @param mixed $command + * @return void + */ + protected function ensureNextJobInChainIsDispatched($command) + { + if (method_exists($command, 'dispatchNextJobInChain')) { + $command->dispatchNextJobInChain(); + } + } + + /** + * Ensure the batch is notified of the successful job completion. + * + * @param mixed $command + * @return void + */ + protected function ensureSuccessfulBatchJobIsRecorded($command) + { + $uses = class_uses_recursive($command); + + if (! in_array(Batchable::class, $uses) || + ! in_array(InteractsWithQueue::class, $uses) || + is_null($command->batch())) { + return; + } + + $command->batch()->recordSuccessfulJob($command->job->uuid()); + } + + /** + * Ensure the lock for a unique job is released. + * + * @param mixed $command + * @return void + */ + protected function ensureUniqueJobLockIsReleased($command) + { + if (! $command instanceof ShouldBeUnique) { + return; + } + + $uniqueId = method_exists($command, 'uniqueId') + ? $command->uniqueId() + : ($command->uniqueId ?? ''); + + $cache = method_exists($command, 'uniqueVia') + ? $command->uniqueVia() + : $this->container->make(Cache::class); + + $cache->lock( + 'laravel_unique_job:'.get_class($command).$uniqueId + )->forceRelease(); + } + + /** + * Handle a model not found exception. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Throwable $e + * @return void + */ + protected function handleModelNotFound(Job $job, $e) + { + $class = $job->resolveName(); + + try { + $shouldDelete = (new ReflectionClass($class)) + ->getDefaultProperties()['deleteWhenMissingModels'] ?? false; + } catch (Exception $e) { + $shouldDelete = false; + } + + if ($shouldDelete) { + return $job->delete(); + } + + return $job->fail($e); + } + + /** + * Call the failed method on the job instance. + * + * The exception that caused the failure will be passed. + * + * @param array $data + * @param \Throwable|null $e + * @param string $uuid + * @return void + */ + public function failed(array $data, $e, string $uuid) + { + $command = $this->getCommand($data); + + if (! $command instanceof ShouldBeUniqueUntilProcessing) { + $this->ensureUniqueJobLockIsReleased($command); + } + + $this->ensureFailedBatchJobIsRecorded($uuid, $command, $e); + $this->ensureChainCatchCallbacksAreInvoked($uuid, $command, $e); + + if (method_exists($command, 'failed')) { + $command->failed($e); + } + } + + /** + * Ensure the batch is notified of the failed job. + * + * @param string $uuid + * @param mixed $command + * @param \Throwable $e + * @return void + */ + protected function ensureFailedBatchJobIsRecorded(string $uuid, $command, $e) + { + if (! in_array(Batchable::class, class_uses_recursive($command)) || + is_null($command->batch())) { + return; + } + + $command->batch()->recordFailedJob($uuid, $e); + } + + /** + * Ensure the chained job catch callbacks are invoked. + * + * @param string $uuid + * @param mixed $command + * @param \Throwable $e + * @return void + */ + protected function ensureChainCatchCallbacksAreInvoked(string $uuid, $command, $e) + { + if (method_exists($command, 'invokeChainCatchCallbacks')) { + $command->invokeChainCatchCallbacks($e); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Capsule/Manager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Capsule/Manager.php new file mode 100644 index 0000000..046555a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Capsule/Manager.php @@ -0,0 +1,187 @@ +setupContainer($container ?: new Container); + + // Once we have the container setup, we will setup the default configuration + // options in the container "config" bindings. This just makes this queue + // manager behave correctly since all the correct binding are in place. + $this->setupDefaultConfiguration(); + + $this->setupManager(); + + $this->registerConnectors(); + } + + /** + * Setup the default queue configuration options. + * + * @return void + */ + protected function setupDefaultConfiguration() + { + $this->container['config']['queue.default'] = 'default'; + } + + /** + * Build the queue manager instance. + * + * @return void + */ + protected function setupManager() + { + $this->manager = new QueueManager($this->container); + } + + /** + * Register the default connectors that the component ships with. + * + * @return void + */ + protected function registerConnectors() + { + $provider = new QueueServiceProvider($this->container); + + $provider->registerConnectors($this->manager); + } + + /** + * Get a connection instance from the global manager. + * + * @param string|null $connection + * @return \Illuminate\Contracts\Queue\Queue + */ + public static function connection($connection = null) + { + return static::$instance->getConnection($connection); + } + + /** + * Push a new job onto the queue. + * + * @param string $job + * @param mixed $data + * @param string|null $queue + * @param string|null $connection + * @return mixed + */ + public static function push($job, $data = '', $queue = null, $connection = null) + { + return static::$instance->connection($connection)->push($job, $data, $queue); + } + + /** + * Push a new an array of jobs onto the queue. + * + * @param array $jobs + * @param mixed $data + * @param string|null $queue + * @param string|null $connection + * @return mixed + */ + public static function bulk($jobs, $data = '', $queue = null, $connection = null) + { + return static::$instance->connection($connection)->bulk($jobs, $data, $queue); + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $job + * @param mixed $data + * @param string|null $queue + * @param string|null $connection + * @return mixed + */ + public static function later($delay, $job, $data = '', $queue = null, $connection = null) + { + return static::$instance->connection($connection)->later($delay, $job, $data, $queue); + } + + /** + * Get a registered connection instance. + * + * @param string|null $name + * @return \Illuminate\Contracts\Queue\Queue + */ + public function getConnection($name = null) + { + return $this->manager->connection($name); + } + + /** + * Register a connection with the manager. + * + * @param array $config + * @param string $name + * @return void + */ + public function addConnection(array $config, $name = 'default') + { + $this->container['config']["queue.connections.{$name}"] = $config; + } + + /** + * Get the queue manager instance. + * + * @return \Illuminate\Queue\QueueManager + */ + public function getQueueManager() + { + return $this->manager; + } + + /** + * Pass dynamic instance methods to the manager. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->manager->$method(...$parameters); + } + + /** + * Dynamically pass methods to the default connection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public static function __callStatic($method, $parameters) + { + return static::connection()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/BeanstalkdConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/BeanstalkdConnector.php new file mode 100755 index 0000000..fdcdb35 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/BeanstalkdConnector.php @@ -0,0 +1,42 @@ +pheanstalk($config), + $config['queue'], + $config['retry_after'] ?? Pheanstalk::DEFAULT_TTR, + $config['block_for'] ?? 0, + $config['after_commit'] ?? null + ); + } + + /** + * Create a Pheanstalk instance. + * + * @param array $config + * @return \Pheanstalk\Pheanstalk + */ + protected function pheanstalk(array $config) + { + return Pheanstalk::create( + $config['host'], + $config['port'] ?? Pheanstalk::DEFAULT_PORT, + $config['timeout'] ?? Connection::DEFAULT_CONNECT_TIMEOUT + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/ConnectorInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/ConnectorInterface.php new file mode 100755 index 0000000..617bf09 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/ConnectorInterface.php @@ -0,0 +1,14 @@ +connections = $connections; + } + + /** + * Establish a queue connection. + * + * @param array $config + * @return \Illuminate\Contracts\Queue\Queue + */ + public function connect(array $config) + { + return new DatabaseQueue( + $this->connections->connection($config['connection'] ?? null), + $config['table'], + $config['queue'], + $config['retry_after'] ?? 60, + $config['after_commit'] ?? null + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/NullConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/NullConnector.php new file mode 100644 index 0000000..39de480 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/NullConnector.php @@ -0,0 +1,19 @@ +redis = $redis; + $this->connection = $connection; + } + + /** + * Establish a queue connection. + * + * @param array $config + * @return \Illuminate\Contracts\Queue\Queue + */ + public function connect(array $config) + { + return new RedisQueue( + $this->redis, $config['queue'], + $config['connection'] ?? $this->connection, + $config['retry_after'] ?? 60, + $config['block_for'] ?? null, + $config['after_commit'] ?? null + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SqsConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SqsConnector.php new file mode 100755 index 0000000..029c607 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SqsConnector.php @@ -0,0 +1,50 @@ +getDefaultConfiguration($config); + + if (! empty($config['key']) && ! empty($config['secret'])) { + $config['credentials'] = Arr::only($config, ['key', 'secret', 'token']); + } + + return new SqsQueue( + new SqsClient($config), + $config['queue'], + $config['prefix'] ?? '', + $config['suffix'] ?? '', + $config['after_commit'] ?? null + ); + } + + /** + * Get the default configuration for SQS. + * + * @param array $config + * @return array + */ + protected function getDefaultConfiguration(array $config) + { + return array_merge([ + 'version' => 'latest', + 'http' => [ + 'timeout' => 60, + 'connect_timeout' => 60, + ], + ], $config); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SyncConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SyncConnector.php new file mode 100755 index 0000000..4269b80 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Connectors/SyncConnector.php @@ -0,0 +1,19 @@ +files = $files; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $table = $this->laravel['config']['queue.batching.table'] ?? 'job_batches'; + + $this->replaceMigration( + $this->createBaseMigration($table), $table, Str::studly($table) + ); + + $this->info('Migration created successfully!'); + + $this->composer->dumpAutoloads(); + } + + /** + * Create a base migration file for the table. + * + * @param string $table + * @return string + */ + protected function createBaseMigration($table = 'job_batches') + { + return $this->laravel['migration.creator']->create( + 'create_'.$table.'_table', $this->laravel->databasePath().'/migrations' + ); + } + + /** + * Replace the generated migration with the batches job table stub. + * + * @param string $path + * @param string $table + * @param string $tableClassName + * @return void + */ + protected function replaceMigration($path, $table, $tableClassName) + { + $stub = str_replace( + ['{{table}}', '{{tableClassName}}'], + [$table, $tableClassName], + $this->files->get(__DIR__.'/stubs/batches.stub') + ); + + $this->files->put($path, $stub); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ClearCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ClearCommand.php new file mode 100644 index 0000000..ff9f936 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ClearCommand.php @@ -0,0 +1,100 @@ +confirmToProceed()) { + return 1; + } + + $connection = $this->argument('connection') + ?: $this->laravel['config']['queue.default']; + + // We need to get the right queue for the connection which is set in the queue + // configuration file for the application. We will pull it based on the set + // connection being run for the queue operation currently being executed. + $queueName = $this->getQueue($connection); + + $queue = ($this->laravel['queue'])->connection($connection); + + if ($queue instanceof ClearableQueue) { + $count = $queue->clear($queueName); + + $this->line('Cleared '.$count.' jobs from the ['.$queueName.'] queue '); + } else { + $this->line('Clearing queues is not supported on ['.(new ReflectionClass($queue))->getShortName().'] '); + } + + return 0; + } + + /** + * Get the queue name to clear. + * + * @param string $connection + * @return string + */ + protected function getQueue($connection) + { + return $this->option('queue') ?: $this->laravel['config']->get( + "queue.connections.{$connection}.queue", 'default' + ); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['connection', InputArgument::OPTIONAL, 'The name of the queue connection to clear'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['queue', null, InputOption::VALUE_OPTIONAL, 'The name of the queue to clear'], + + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/FailedTableCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/FailedTableCommand.php new file mode 100644 index 0000000..09d3986 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/FailedTableCommand.php @@ -0,0 +1,102 @@ +files = $files; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $table = $this->laravel['config']['queue.failed.table']; + + $this->replaceMigration( + $this->createBaseMigration($table), $table, Str::studly($table) + ); + + $this->info('Migration created successfully!'); + + $this->composer->dumpAutoloads(); + } + + /** + * Create a base migration file for the table. + * + * @param string $table + * @return string + */ + protected function createBaseMigration($table = 'failed_jobs') + { + return $this->laravel['migration.creator']->create( + 'create_'.$table.'_table', $this->laravel->databasePath().'/migrations' + ); + } + + /** + * Replace the generated migration with the failed job table stub. + * + * @param string $path + * @param string $table + * @param string $tableClassName + * @return void + */ + protected function replaceMigration($path, $table, $tableClassName) + { + $stub = str_replace( + ['{{table}}', '{{tableClassName}}'], + [$table, $tableClassName], + $this->files->get(__DIR__.'/stubs/failed_jobs.stub') + ); + + $this->files->put($path, $stub); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/FlushFailedCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/FlushFailedCommand.php new file mode 100644 index 0000000..550b860 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/FlushFailedCommand.php @@ -0,0 +1,34 @@ +laravel['queue.failer']->flush(); + + $this->info('All failed jobs deleted successfully!'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ForgetFailedCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ForgetFailedCommand.php new file mode 100644 index 0000000..b8eecb9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ForgetFailedCommand.php @@ -0,0 +1,36 @@ +laravel['queue.failer']->forget($this->argument('id'))) { + $this->info('Failed job deleted successfully!'); + } else { + $this->error('No failed job matches the given ID.'); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ListFailedCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ListFailedCommand.php new file mode 100644 index 0000000..66b5ddd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ListFailedCommand.php @@ -0,0 +1,114 @@ +getFailedJobs()) === 0) { + return $this->info('No failed jobs!'); + } + + $this->displayFailedJobs($jobs); + } + + /** + * Compile the failed jobs into a displayable format. + * + * @return array + */ + protected function getFailedJobs() + { + $failed = $this->laravel['queue.failer']->all(); + + return collect($failed)->map(function ($failed) { + return $this->parseFailedJob((array) $failed); + })->filter()->all(); + } + + /** + * Parse the failed job row. + * + * @param array $failed + * @return array + */ + protected function parseFailedJob(array $failed) + { + $row = array_values(Arr::except($failed, ['payload', 'exception'])); + + array_splice($row, 3, 0, $this->extractJobName($failed['payload']) ?: ''); + + return $row; + } + + /** + * Extract the failed job name from payload. + * + * @param string $payload + * @return string|null + */ + private function extractJobName($payload) + { + $payload = json_decode($payload, true); + + if ($payload && (! isset($payload['data']['command']))) { + return $payload['job'] ?? null; + } elseif ($payload && isset($payload['data']['command'])) { + return $this->matchJobName($payload); + } + } + + /** + * Match the job name from the payload. + * + * @param array $payload + * @return string|null + */ + protected function matchJobName($payload) + { + preg_match('/"([^"]+)"/', $payload['data']['command'], $matches); + + return $matches[1] ?? $payload['job'] ?? null; + } + + /** + * Display the failed jobs in the console. + * + * @param array $jobs + * @return void + */ + protected function displayFailedJobs(array $jobs) + { + $this->table($this->headers, $jobs); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ListenCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ListenCommand.php new file mode 100755 index 0000000..f650e43 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/ListenCommand.php @@ -0,0 +1,124 @@ +setOutputHandler($this->listener = $listener); + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + // We need to get the right queue for the connection which is set in the queue + // configuration file for the application. We will pull it based on the set + // connection being run for the queue operation currently being executed. + $queue = $this->getQueue( + $connection = $this->input->getArgument('connection') + ); + + $this->listener->listen( + $connection, $queue, $this->gatherOptions() + ); + } + + /** + * Get the name of the queue connection to listen on. + * + * @param string $connection + * @return string + */ + protected function getQueue($connection) + { + $connection = $connection ?: $this->laravel['config']['queue.default']; + + return $this->input->getOption('queue') ?: $this->laravel['config']->get( + "queue.connections.{$connection}.queue", 'default' + ); + } + + /** + * Get the listener options for the command. + * + * @return \Illuminate\Queue\ListenerOptions + */ + protected function gatherOptions() + { + $backoff = $this->hasOption('backoff') + ? $this->option('backoff') + : $this->option('delay'); + + return new ListenerOptions( + $this->option('name'), + $this->option('env'), + $backoff, + $this->option('memory'), + $this->option('timeout'), + $this->option('sleep'), + $this->option('tries'), + $this->option('force') + ); + } + + /** + * Set the options on the queue listener. + * + * @param \Illuminate\Queue\Listener $listener + * @return void + */ + protected function setOutputHandler(Listener $listener) + { + $listener->setOutputHandler(function ($type, $line) { + $this->output->write($line); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/MonitorCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/MonitorCommand.php new file mode 100644 index 0000000..1deb479 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/MonitorCommand.php @@ -0,0 +1,137 @@ +manager = $manager; + $this->events = $events; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $queues = $this->parseQueues($this->argument('queues')); + + $this->displaySizes($queues); + + $this->dispatchEvents($queues); + } + + /** + * Parse the queues into an array of the connections and queues. + * + * @param string $queues + * @return \Illuminate\Support\Collection + */ + protected function parseQueues($queues) + { + return collect(explode(',', $queues))->map(function ($queue) { + [$connection, $queue] = array_pad(explode(':', $queue, 2), 2, null); + + if (! isset($queue)) { + $queue = $connection; + $connection = $this->laravel['config']['queue.default']; + } + + return [ + 'connection' => $connection, + 'queue' => $queue, + 'size' => $size = $this->manager->connection($connection)->size($queue), + 'status' => $size >= $this->option('max') ? 'ALERT' : 'OK', + ]; + }); + } + + /** + * Display the failed jobs in the console. + * + * @param \Illuminate\Support\Collection $queues + * @return void + */ + protected function displaySizes(Collection $queues) + { + $this->table($this->headers, $queues); + } + + /** + * Fire the monitoring events. + * + * @param \Illuminate\Support\Collection $queues + * @return void + */ + protected function dispatchEvents(Collection $queues) + { + foreach ($queues as $queue) { + if ($queue['status'] == 'OK') { + continue; + } + + $this->events->dispatch( + new QueueBusy( + $queue['connection'], + $queue['queue'], + $queue['size'], + ) + ); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/PruneBatchesCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/PruneBatchesCommand.php new file mode 100644 index 0000000..59ea388 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/PruneBatchesCommand.php @@ -0,0 +1,56 @@ +laravel[BatchRepository::class]; + + $count = 0; + + if ($repository instanceof PrunableBatchRepository) { + $count = $repository->prune(Carbon::now()->subHours($this->option('hours'))); + } + + $this->info("{$count} entries deleted!"); + + if ($unfinished = $this->option('unfinished')) { + $count = 0; + + if ($repository instanceof DatabaseBatchRepository) { + $count = $repository->pruneUnfinished(Carbon::now()->subHours($this->option('unfinished'))); + } + + $this->info("{$count} unfinished entries deleted!"); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/PruneFailedJobsCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/PruneFailedJobsCommand.php new file mode 100644 index 0000000..f82d9be --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/PruneFailedJobsCommand.php @@ -0,0 +1,47 @@ +laravel['queue.failer']; + + $count = 0; + + if ($failer instanceof PrunableFailedJobProvider) { + $count = $failer->prune(Carbon::now()->subHours($this->option('hours'))); + } else { + $this->error('The ['.class_basename($failer).'] failed job storage driver does not support pruning.'); + + return 1; + } + + $this->info("{$count} entries deleted!"); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RestartCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RestartCommand.php new file mode 100644 index 0000000..9c610d9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RestartCommand.php @@ -0,0 +1,58 @@ +cache = $cache; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $this->cache->forever('illuminate:queue:restart', $this->currentTime()); + + $this->info('Broadcasting queue restart signal.'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RetryBatchCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RetryBatchCommand.php new file mode 100644 index 0000000..828278a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RetryBatchCommand.php @@ -0,0 +1,47 @@ +laravel[BatchRepository::class]->find($id = $this->argument('id')); + + if (! $batch) { + $this->error("Unable to find a batch with ID [{$id}]."); + + return 1; + } elseif (empty($batch->failedJobIds)) { + $this->error('The given batch does not contain any failed jobs.'); + + return 1; + } + + foreach ($batch->failedJobIds as $failedJobId) { + $this->call('queue:retry', ['id' => $failedJobId]); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RetryCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RetryCommand.php new file mode 100644 index 0000000..dbd2e7a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/RetryCommand.php @@ -0,0 +1,187 @@ +getJobIds() as $id) { + $job = $this->laravel['queue.failer']->find($id); + + if (is_null($job)) { + $this->error("Unable to find failed job with ID [{$id}]."); + } else { + $this->laravel['events']->dispatch(new JobRetryRequested($job)); + + $this->retryJob($job); + + $this->info("The failed job [{$id}] has been pushed back onto the queue!"); + + $this->laravel['queue.failer']->forget($id); + } + } + } + + /** + * Get the job IDs to be retried. + * + * @return array + */ + protected function getJobIds() + { + $ids = (array) $this->argument('id'); + + if (count($ids) === 1 && $ids[0] === 'all') { + return Arr::pluck($this->laravel['queue.failer']->all(), 'id'); + } + + if ($queue = $this->option('queue')) { + return $this->getJobIdsByQueue($queue); + } + + if ($ranges = (array) $this->option('range')) { + $ids = array_merge($ids, $this->getJobIdsByRanges($ranges)); + } + + return array_values(array_filter(array_unique($ids))); + } + + /** + * Get the job IDs by queue, if applicable. + * + * @param string $queue + * @return array + */ + protected function getJobIdsByQueue($queue) + { + $ids = collect($this->laravel['queue.failer']->all()) + ->where('queue', $queue) + ->pluck('id') + ->toArray(); + + if (count($ids) === 0) { + $this->error("Unable to find failed jobs for queue [{$queue}]."); + } + + return $ids; + } + + /** + * Get the job IDs ranges, if applicable. + * + * @param array $ranges + * @return array + */ + protected function getJobIdsByRanges(array $ranges) + { + $ids = []; + + foreach ($ranges as $range) { + if (preg_match('/^[0-9]+\-[0-9]+$/', $range)) { + $ids = array_merge($ids, range(...explode('-', $range))); + } + } + + return $ids; + } + + /** + * Retry the queue job. + * + * @param \stdClass $job + * @return void + */ + protected function retryJob($job) + { + $this->laravel['queue']->connection($job->connection)->pushRaw( + $this->refreshRetryUntil($this->resetAttempts($job->payload)), $job->queue + ); + } + + /** + * Reset the payload attempts. + * + * Applicable to Redis and other jobs which store attempts in their payload. + * + * @param string $payload + * @return string + */ + protected function resetAttempts($payload) + { + $payload = json_decode($payload, true); + + if (isset($payload['attempts'])) { + $payload['attempts'] = 0; + } + + return json_encode($payload); + } + + /** + * Refresh the "retry until" timestamp for the job. + * + * @param string $payload + * @return string + * + * @throws \RuntimeException + */ + protected function refreshRetryUntil($payload) + { + $payload = json_decode($payload, true); + + if (! isset($payload['data']['command'])) { + return json_encode($payload); + } + + if (Str::startsWith($payload['data']['command'], 'O:')) { + $instance = unserialize($payload['data']['command']); + } elseif ($this->laravel->bound(Encrypter::class)) { + $instance = unserialize($this->laravel->make(Encrypter::class)->decrypt($payload['data']['command'])); + } + + if (! isset($instance)) { + throw new RuntimeException('Unable to extract job payload.'); + } + + if (is_object($instance) && ! $instance instanceof \__PHP_Incomplete_Class && method_exists($instance, 'retryUntil')) { + $retryUntil = $instance->retryUntil(); + + $payload['retryUntil'] = $retryUntil instanceof DateTimeInterface + ? $retryUntil->getTimestamp() + : $retryUntil; + } + + return json_encode($payload); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/TableCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/TableCommand.php new file mode 100644 index 0000000..cc949d4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/TableCommand.php @@ -0,0 +1,102 @@ +files = $files; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $table = $this->laravel['config']['queue.connections.database.table']; + + $this->replaceMigration( + $this->createBaseMigration($table), $table, Str::studly($table) + ); + + $this->info('Migration created successfully!'); + + $this->composer->dumpAutoloads(); + } + + /** + * Create a base migration file for the table. + * + * @param string $table + * @return string + */ + protected function createBaseMigration($table = 'jobs') + { + return $this->laravel['migration.creator']->create( + 'create_'.$table.'_table', $this->laravel->databasePath().'/migrations' + ); + } + + /** + * Replace the generated migration with the job table stub. + * + * @param string $path + * @param string $table + * @param string $tableClassName + * @return void + */ + protected function replaceMigration($path, $table, $tableClassName) + { + $stub = str_replace( + ['{{table}}', '{{tableClassName}}'], + [$table, $tableClassName], + $this->files->get(__DIR__.'/stubs/jobs.stub') + ); + + $this->files->put($path, $stub); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php new file mode 100644 index 0000000..da9176b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php @@ -0,0 +1,240 @@ +cache = $cache; + $this->worker = $worker; + } + + /** + * Execute the console command. + * + * @return int|null + */ + public function handle() + { + if ($this->downForMaintenance() && $this->option('once')) { + return $this->worker->sleep($this->option('sleep')); + } + + // We'll listen to the processed and failed events so we can write information + // to the console as jobs are processed, which will let the developer watch + // which jobs are coming through a queue and be informed on its progress. + $this->listenForEvents(); + + $connection = $this->argument('connection') + ?: $this->laravel['config']['queue.default']; + + // We need to get the right queue for the connection which is set in the queue + // configuration file for the application. We will pull it based on the set + // connection being run for the queue operation currently being executed. + $queue = $this->getQueue($connection); + + return $this->runWorker( + $connection, $queue + ); + } + + /** + * Run the worker instance. + * + * @param string $connection + * @param string $queue + * @return int|null + */ + protected function runWorker($connection, $queue) + { + return $this->worker->setName($this->option('name')) + ->setCache($this->cache) + ->{$this->option('once') ? 'runNextJob' : 'daemon'}( + $connection, $queue, $this->gatherWorkerOptions() + ); + } + + /** + * Gather all of the queue worker options as a single object. + * + * @return \Illuminate\Queue\WorkerOptions + */ + protected function gatherWorkerOptions() + { + return new WorkerOptions( + $this->option('name'), + max($this->option('backoff'), $this->option('delay')), + $this->option('memory'), + $this->option('timeout'), + $this->option('sleep'), + $this->option('tries'), + $this->option('force'), + $this->option('stop-when-empty'), + $this->option('max-jobs'), + $this->option('max-time'), + $this->option('rest') + ); + } + + /** + * Listen for the queue events in order to update the console output. + * + * @return void + */ + protected function listenForEvents() + { + $this->laravel['events']->listen(JobProcessing::class, function ($event) { + $this->writeOutput($event->job, 'starting'); + }); + + $this->laravel['events']->listen(JobProcessed::class, function ($event) { + $this->writeOutput($event->job, 'success'); + }); + + $this->laravel['events']->listen(JobFailed::class, function ($event) { + $this->writeOutput($event->job, 'failed'); + + $this->logFailedJob($event); + }); + } + + /** + * Write the status output for the queue worker. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param string $status + * @return void + */ + protected function writeOutput(Job $job, $status) + { + switch ($status) { + case 'starting': + return $this->writeStatus($job, 'Processing', 'comment'); + case 'success': + return $this->writeStatus($job, 'Processed', 'info'); + case 'failed': + return $this->writeStatus($job, 'Failed', 'error'); + } + } + + /** + * Format the status output for the queue worker. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param string $status + * @param string $type + * @return void + */ + protected function writeStatus(Job $job, $status, $type) + { + $this->output->writeln(sprintf( + "<{$type}>[%s][%s] %s %s", + Carbon::now()->format('Y-m-d H:i:s'), + $job->getJobId(), + str_pad("{$status}:", 11), $job->resolveName() + )); + } + + /** + * Store a failed job event. + * + * @param \Illuminate\Queue\Events\JobFailed $event + * @return void + */ + protected function logFailedJob(JobFailed $event) + { + $this->laravel['queue.failer']->log( + $event->connectionName, + $event->job->getQueue(), + $event->job->getRawBody(), + $event->exception + ); + } + + /** + * Get the queue name for the worker. + * + * @param string $connection + * @return string + */ + protected function getQueue($connection) + { + return $this->option('queue') ?: $this->laravel['config']->get( + "queue.connections.{$connection}.queue", 'default' + ); + } + + /** + * Determine if the worker should run in maintenance mode. + * + * @return bool + */ + protected function downForMaintenance() + { + return $this->option('force') ? false : $this->laravel->isDownForMaintenance(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/batches.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/batches.stub new file mode 100644 index 0000000..d4fa380 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/batches.stub @@ -0,0 +1,39 @@ +string('id')->primary(); + $table->string('name'); + $table->integer('total_jobs'); + $table->integer('pending_jobs'); + $table->integer('failed_jobs'); + $table->text('failed_job_ids'); + $table->mediumText('options')->nullable(); + $table->integer('cancelled_at')->nullable(); + $table->integer('created_at'); + $table->integer('finished_at')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('{{table}}'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/failed_jobs.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/failed_jobs.stub new file mode 100644 index 0000000..6179e7f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/failed_jobs.stub @@ -0,0 +1,36 @@ +id(); + $table->string('uuid')->unique(); + $table->text('connection'); + $table->text('queue'); + $table->longText('payload'); + $table->longText('exception'); + $table->timestamp('failed_at')->useCurrent(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('{{table}}'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/jobs.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/jobs.stub new file mode 100644 index 0000000..45d6031 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Console/stubs/jobs.stub @@ -0,0 +1,36 @@ +bigIncrements('id'); + $table->string('queue')->index(); + $table->longText('payload'); + $table->unsignedTinyInteger('attempts'); + $table->unsignedInteger('reserved_at')->nullable(); + $table->unsignedInteger('available_at'); + $table->unsignedInteger('created_at'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('{{table}}'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php new file mode 100644 index 0000000..a1d3f08 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php @@ -0,0 +1,402 @@ +table = $table; + $this->default = $default; + $this->database = $database; + $this->retryAfter = $retryAfter; + $this->dispatchAfterCommit = $dispatchAfterCommit; + } + + /** + * Get the size of the queue. + * + * @param string|null $queue + * @return int + */ + public function size($queue = null) + { + return $this->database->table($this->table) + ->where('queue', $this->getQueue($queue)) + ->count(); + } + + /** + * Push a new job onto the queue. + * + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function push($job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $this->getQueue($queue), $data), + $queue, + null, + function ($payload, $queue) { + return $this->pushToDatabase($queue, $payload); + } + ); + } + + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + */ + public function pushRaw($payload, $queue = null, array $options = []) + { + return $this->pushToDatabase($queue, $payload); + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return void + */ + public function later($delay, $job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $this->getQueue($queue), $data), + $queue, + $delay, + function ($payload, $queue, $delay) { + return $this->pushToDatabase($queue, $payload, $delay); + } + ); + } + + /** + * Push an array of jobs onto the queue. + * + * @param array $jobs + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function bulk($jobs, $data = '', $queue = null) + { + $queue = $this->getQueue($queue); + + $availableAt = $this->availableAt(); + + return $this->database->table($this->table)->insert(collect((array) $jobs)->map( + function ($job) use ($queue, $data, $availableAt) { + return $this->buildDatabaseRecord($queue, $this->createPayload($job, $this->getQueue($queue), $data), $availableAt); + } + )->all()); + } + + /** + * Release a reserved job back onto the queue. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job + * @param int $delay + * @return mixed + */ + public function release($queue, $job, $delay) + { + return $this->pushToDatabase($queue, $job->payload, $delay, $job->attempts); + } + + /** + * Push a raw payload to the database with a given delay. + * + * @param string|null $queue + * @param string $payload + * @param \DateTimeInterface|\DateInterval|int $delay + * @param int $attempts + * @return mixed + */ + protected function pushToDatabase($queue, $payload, $delay = 0, $attempts = 0) + { + return $this->database->table($this->table)->insertGetId($this->buildDatabaseRecord( + $this->getQueue($queue), $payload, $this->availableAt($delay), $attempts + )); + } + + /** + * Create an array to insert for the given job. + * + * @param string|null $queue + * @param string $payload + * @param int $availableAt + * @param int $attempts + * @return array + */ + protected function buildDatabaseRecord($queue, $payload, $availableAt, $attempts = 0) + { + return [ + 'queue' => $queue, + 'attempts' => $attempts, + 'reserved_at' => null, + 'available_at' => $availableAt, + 'created_at' => $this->currentTime(), + 'payload' => $payload, + ]; + } + + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + * + * @throws \Throwable + */ + public function pop($queue = null) + { + $queue = $this->getQueue($queue); + + return $this->database->transaction(function () use ($queue) { + if ($job = $this->getNextAvailableJob($queue)) { + return $this->marshalJob($queue, $job); + } + }); + } + + /** + * Get the next available job for the queue. + * + * @param string|null $queue + * @return \Illuminate\Queue\Jobs\DatabaseJobRecord|null + */ + protected function getNextAvailableJob($queue) + { + $job = $this->database->table($this->table) + ->lock($this->getLockForPopping()) + ->where('queue', $this->getQueue($queue)) + ->where(function ($query) { + $this->isAvailable($query); + $this->isReservedButExpired($query); + }) + ->orderBy('id', 'asc') + ->first(); + + return $job ? new DatabaseJobRecord((object) $job) : null; + } + + /** + * Get the lock required for popping the next job. + * + * @return string|bool + */ + protected function getLockForPopping() + { + $databaseEngine = $this->database->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME); + $databaseVersion = $this->database->getConfig('version') ?? $this->database->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION); + + if (Str::of($databaseVersion)->contains('MariaDB')) { + $databaseEngine = 'mariadb'; + $databaseVersion = Str::before(Str::after($databaseVersion, '5.5.5-'), '-'); + } + + if (($databaseEngine === 'mysql' && version_compare($databaseVersion, '8.0.1', '>=')) || + ($databaseEngine === 'mariadb' && version_compare($databaseVersion, '10.6.0', '>=')) || + ($databaseEngine === 'pgsql' && version_compare($databaseVersion, '9.5', '>='))) { + return 'FOR UPDATE SKIP LOCKED'; + } + + return true; + } + + /** + * Modify the query to check for available jobs. + * + * @param \Illuminate\Database\Query\Builder $query + * @return void + */ + protected function isAvailable($query) + { + $query->where(function ($query) { + $query->whereNull('reserved_at') + ->where('available_at', '<=', $this->currentTime()); + }); + } + + /** + * Modify the query to check for jobs that are reserved but have expired. + * + * @param \Illuminate\Database\Query\Builder $query + * @return void + */ + protected function isReservedButExpired($query) + { + $expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp(); + + $query->orWhere(function ($query) use ($expiration) { + $query->where('reserved_at', '<=', $expiration); + }); + } + + /** + * Marshal the reserved job into a DatabaseJob instance. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job + * @return \Illuminate\Queue\Jobs\DatabaseJob + */ + protected function marshalJob($queue, $job) + { + $job = $this->markJobAsReserved($job); + + return new DatabaseJob( + $this->container, $this, $job, $this->connectionName, $queue + ); + } + + /** + * Mark the given job ID as reserved. + * + * @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job + * @return \Illuminate\Queue\Jobs\DatabaseJobRecord + */ + protected function markJobAsReserved($job) + { + $this->database->table($this->table)->where('id', $job->id)->update([ + 'reserved_at' => $job->touch(), + 'attempts' => $job->increment(), + ]); + + return $job; + } + + /** + * Delete a reserved job from the queue. + * + * @param string $queue + * @param string $id + * @return void + * + * @throws \Throwable + */ + public function deleteReserved($queue, $id) + { + $this->database->transaction(function () use ($id) { + if ($this->database->table($this->table)->lockForUpdate()->find($id)) { + $this->database->table($this->table)->where('id', $id)->delete(); + } + }); + } + + /** + * Delete a reserved job from the reserved queue and release it. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\DatabaseJob $job + * @param int $delay + * @return void + */ + public function deleteAndRelease($queue, $job, $delay) + { + $this->database->transaction(function () use ($queue, $job, $delay) { + if ($this->database->table($this->table)->lockForUpdate()->find($job->getJobId())) { + $this->database->table($this->table)->where('id', $job->getJobId())->delete(); + } + + $this->release($queue, $job->getJobRecord(), $delay); + }); + } + + /** + * Delete all of the jobs from the queue. + * + * @param string $queue + * @return int + */ + public function clear($queue) + { + return $this->database->table($this->table) + ->where('queue', $this->getQueue($queue)) + ->delete(); + } + + /** + * Get the queue or return the default. + * + * @param string|null $queue + * @return string + */ + public function getQueue($queue) + { + return $queue ?: $this->default; + } + + /** + * Get the underlying database instance. + * + * @return \Illuminate\Database\Connection + */ + public function getDatabase() + { + return $this->database; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobExceptionOccurred.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobExceptionOccurred.php new file mode 100644 index 0000000..4bdf392 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobExceptionOccurred.php @@ -0,0 +1,42 @@ +job = $job; + $this->exception = $exception; + $this->connectionName = $connectionName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobFailed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobFailed.php new file mode 100644 index 0000000..d973a50 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobFailed.php @@ -0,0 +1,42 @@ +job = $job; + $this->exception = $exception; + $this->connectionName = $connectionName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobProcessed.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobProcessed.php new file mode 100644 index 0000000..f8abefb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobProcessed.php @@ -0,0 +1,33 @@ +job = $job; + $this->connectionName = $connectionName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobProcessing.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobProcessing.php new file mode 100644 index 0000000..3dd9724 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobProcessing.php @@ -0,0 +1,33 @@ +job = $job; + $this->connectionName = $connectionName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobQueued.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobQueued.php new file mode 100644 index 0000000..c91d140 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobQueued.php @@ -0,0 +1,42 @@ +connectionName = $connectionName; + $this->id = $id; + $this->job = $job; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobRetryRequested.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobRetryRequested.php new file mode 100644 index 0000000..9b9809f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/JobRetryRequested.php @@ -0,0 +1,45 @@ +job = $job; + } + + /** + * The job payload. + * + * @return array + */ + public function payload() + { + if (is_null($this->payload)) { + $this->payload = json_decode($this->job->payload, true); + } + + return $this->payload; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/Looping.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/Looping.php new file mode 100644 index 0000000..f9538e4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/Looping.php @@ -0,0 +1,33 @@ +queue = $queue; + $this->connectionName = $connectionName; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/QueueBusy.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/QueueBusy.php new file mode 100644 index 0000000..684dec4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/QueueBusy.php @@ -0,0 +1,42 @@ +connection = $connection; + $this->queue = $queue; + $this->size = $size; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/WorkerStopping.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/WorkerStopping.php new file mode 100644 index 0000000..6d49bb2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Events/WorkerStopping.php @@ -0,0 +1,24 @@ +status = $status; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DatabaseFailedJobProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DatabaseFailedJobProvider.php new file mode 100644 index 0000000..a4d98e0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DatabaseFailedJobProvider.php @@ -0,0 +1,139 @@ +table = $table; + $this->resolver = $resolver; + $this->database = $database; + } + + /** + * Log a failed job into storage. + * + * @param string $connection + * @param string $queue + * @param string $payload + * @param \Throwable $exception + * @return int|null + */ + public function log($connection, $queue, $payload, $exception) + { + $failed_at = Date::now(); + + $exception = (string) $exception; + + return $this->getTable()->insertGetId(compact( + 'connection', 'queue', 'payload', 'exception', 'failed_at' + )); + } + + /** + * Get a list of all of the failed jobs. + * + * @return array + */ + public function all() + { + return $this->getTable()->orderBy('id', 'desc')->get()->all(); + } + + /** + * Get a single failed job. + * + * @param mixed $id + * @return object|null + */ + public function find($id) + { + return $this->getTable()->find($id); + } + + /** + * Delete a single failed job from storage. + * + * @param mixed $id + * @return bool + */ + public function forget($id) + { + return $this->getTable()->where('id', $id)->delete() > 0; + } + + /** + * Flush all of the failed jobs from storage. + * + * @return void + */ + public function flush() + { + $this->getTable()->delete(); + } + + /** + * Prune all of the entries older than the given date. + * + * @param \DateTimeInterface $before + * @return int + */ + public function prune(DateTimeInterface $before) + { + $query = $this->getTable()->where('failed_at', '<', $before); + + $totalDeleted = 0; + + do { + $deleted = $query->take(1000)->delete(); + + $totalDeleted += $deleted; + } while ($deleted !== 0); + + return $totalDeleted; + } + + /** + * Get a new query builder instance for the table. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function getTable() + { + return $this->resolver->connection($this->database)->table($this->table); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DatabaseUuidFailedJobProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DatabaseUuidFailedJobProvider.php new file mode 100644 index 0000000..e952052 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DatabaseUuidFailedJobProvider.php @@ -0,0 +1,152 @@ +table = $table; + $this->resolver = $resolver; + $this->database = $database; + } + + /** + * Log a failed job into storage. + * + * @param string $connection + * @param string $queue + * @param string $payload + * @param \Throwable $exception + * @return string|null + */ + public function log($connection, $queue, $payload, $exception) + { + $this->getTable()->insert([ + 'uuid' => $uuid = json_decode($payload, true)['uuid'], + 'connection' => $connection, + 'queue' => $queue, + 'payload' => $payload, + 'exception' => (string) $exception, + 'failed_at' => Date::now(), + ]); + + return $uuid; + } + + /** + * Get a list of all of the failed jobs. + * + * @return array + */ + public function all() + { + return $this->getTable()->orderBy('id', 'desc')->get()->map(function ($record) { + $record->id = $record->uuid; + unset($record->uuid); + + return $record; + })->all(); + } + + /** + * Get a single failed job. + * + * @param mixed $id + * @return object|null + */ + public function find($id) + { + if ($record = $this->getTable()->where('uuid', $id)->first()) { + $record->id = $record->uuid; + unset($record->uuid); + } + + return $record; + } + + /** + * Delete a single failed job from storage. + * + * @param mixed $id + * @return bool + */ + public function forget($id) + { + return $this->getTable()->where('uuid', $id)->delete() > 0; + } + + /** + * Flush all of the failed jobs from storage. + * + * @return void + */ + public function flush() + { + $this->getTable()->delete(); + } + + /** + * Prune all of the entries older than the given date. + * + * @param \DateTimeInterface $before + * @return int + */ + public function prune(DateTimeInterface $before) + { + $query = $this->getTable()->where('failed_at', '<', $before); + + $totalDeleted = 0; + + do { + $deleted = $query->take(1000)->delete(); + + $totalDeleted += $deleted; + } while ($deleted !== 0); + + return $totalDeleted; + } + + /** + * Get a new query builder instance for the table. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function getTable() + { + return $this->resolver->connection($this->database)->table($this->table); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DynamoDbFailedJobProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DynamoDbFailedJobProvider.php new file mode 100644 index 0000000..7b88b23 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/DynamoDbFailedJobProvider.php @@ -0,0 +1,176 @@ +table = $table; + $this->dynamo = $dynamo; + $this->applicationName = $applicationName; + } + + /** + * Log a failed job into storage. + * + * @param string $connection + * @param string $queue + * @param string $payload + * @param \Throwable $exception + * @return string|int|null + */ + public function log($connection, $queue, $payload, $exception) + { + $id = json_decode($payload, true)['uuid']; + + $failedAt = Date::now(); + + $this->dynamo->putItem([ + 'TableName' => $this->table, + 'Item' => [ + 'application' => ['S' => $this->applicationName], + 'uuid' => ['S' => $id], + 'connection' => ['S' => $connection], + 'queue' => ['S' => $queue], + 'payload' => ['S' => $payload], + 'exception' => ['S' => (string) $exception], + 'failed_at' => ['N' => (string) $failedAt->getTimestamp()], + 'expires_at' => ['N' => (string) $failedAt->addDays(3)->getTimestamp()], + ], + ]); + + return $id; + } + + /** + * Get a list of all of the failed jobs. + * + * @return array + */ + public function all() + { + $results = $this->dynamo->query([ + 'TableName' => $this->table, + 'Select' => 'ALL_ATTRIBUTES', + 'KeyConditionExpression' => 'application = :application', + 'ExpressionAttributeValues' => [ + ':application' => ['S' => $this->applicationName], + ], + 'ScanIndexForward' => false, + ]); + + return collect($results['Items'])->sortByDesc(function ($result) { + return (int) $result['failed_at']['N']; + })->map(function ($result) { + return (object) [ + 'id' => $result['uuid']['S'], + 'connection' => $result['connection']['S'], + 'queue' => $result['queue']['S'], + 'payload' => $result['payload']['S'], + 'exception' => $result['exception']['S'], + 'failed_at' => Carbon::createFromTimestamp( + (int) $result['failed_at']['N'] + )->format(DateTimeInterface::ISO8601), + ]; + })->all(); + } + + /** + * Get a single failed job. + * + * @param mixed $id + * @return object|null + */ + public function find($id) + { + $result = $this->dynamo->getItem([ + 'TableName' => $this->table, + 'Key' => [ + 'application' => ['S' => $this->applicationName], + 'uuid' => ['S' => $id], + ], + ]); + + if (! isset($result['Item'])) { + return; + } + + return (object) [ + 'id' => $result['Item']['uuid']['S'], + 'connection' => $result['Item']['connection']['S'], + 'queue' => $result['Item']['queue']['S'], + 'payload' => $result['Item']['payload']['S'], + 'exception' => $result['Item']['exception']['S'], + 'failed_at' => Carbon::createFromTimestamp( + (int) $result['Item']['failed_at']['N'] + )->format(DateTimeInterface::ISO8601), + ]; + } + + /** + * Delete a single failed job from storage. + * + * @param mixed $id + * @return bool + */ + public function forget($id) + { + $this->dynamo->deleteItem([ + 'TableName' => $this->table, + 'Key' => [ + 'application' => ['S' => $this->applicationName], + 'uuid' => ['S' => $id], + ], + ]); + + return true; + } + + /** + * Flush all of the failed jobs from storage. + * + * @return void + * + * @throws \Exception + */ + public function flush() + { + throw new Exception("DynamoDb failed job storage may not be flushed. Please use DynamoDb's TTL features on your expires_at attribute."); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/FailedJobProviderInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/FailedJobProviderInterface.php new file mode 100644 index 0000000..1a11fc0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Failed/FailedJobProviderInterface.php @@ -0,0 +1,47 @@ +job ? $this->job->attempts() : 1; + } + + /** + * Delete the job from the queue. + * + * @return void + */ + public function delete() + { + if ($this->job) { + return $this->job->delete(); + } + } + + /** + * Fail the job from the queue. + * + * @param \Throwable|null $exception + * @return void + */ + public function fail($exception = null) + { + if ($this->job) { + $this->job->fail($exception); + } + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + if ($this->job) { + return $this->job->release($delay); + } + } + + /** + * Set the base queue job instance. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @return $this + */ + public function setJob(JobContract $job) + { + $this->job = $job; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/InvalidPayloadException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/InvalidPayloadException.php new file mode 100644 index 0000000..788fa66 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/InvalidPayloadException.php @@ -0,0 +1,19 @@ +job = $job; + $this->queue = $queue; + $this->container = $container; + $this->pheanstalk = $pheanstalk; + $this->connectionName = $connectionName; + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + parent::release($delay); + + $priority = Pheanstalk::DEFAULT_PRIORITY; + + $this->pheanstalk->release($this->job, $priority, $delay); + } + + /** + * Bury the job in the queue. + * + * @return void + */ + public function bury() + { + parent::release(); + + $this->pheanstalk->bury($this->job); + } + + /** + * Delete the job from the queue. + * + * @return void + */ + public function delete() + { + parent::delete(); + + $this->pheanstalk->delete($this->job); + } + + /** + * Get the number of times the job has been attempted. + * + * @return int + */ + public function attempts() + { + $stats = $this->pheanstalk->statsJob($this->job); + + return (int) $stats->reserves; + } + + /** + * Get the job identifier. + * + * @return int + */ + public function getJobId() + { + return $this->job->getId(); + } + + /** + * Get the raw body string for the job. + * + * @return string + */ + public function getRawBody() + { + return $this->job->getData(); + } + + /** + * Get the underlying Pheanstalk instance. + * + * @return \Pheanstalk\Pheanstalk + */ + public function getPheanstalk() + { + return $this->pheanstalk; + } + + /** + * Get the underlying Pheanstalk job. + * + * @return \Pheanstalk\Job + */ + public function getPheanstalkJob() + { + return $this->job; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJob.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJob.php new file mode 100644 index 0000000..66332e2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJob.php @@ -0,0 +1,108 @@ +job = $job; + $this->queue = $queue; + $this->database = $database; + $this->container = $container; + $this->connectionName = $connectionName; + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + parent::release($delay); + + $this->database->deleteAndRelease($this->queue, $this, $delay); + } + + /** + * Delete the job from the queue. + * + * @return void + */ + public function delete() + { + parent::delete(); + + $this->database->deleteReserved($this->queue, $this->job->id); + } + + /** + * Get the number of times the job has been attempted. + * + * @return int + */ + public function attempts() + { + return (int) $this->job->attempts; + } + + /** + * Get the job identifier. + * + * @return string + */ + public function getJobId() + { + return $this->job->id; + } + + /** + * Get the raw body string for the job. + * + * @return string + */ + public function getRawBody() + { + return $this->job->payload; + } + + /** + * Get the database job record. + * + * @return \Illuminate\Queue\Jobs\DatabaseJobRecord + */ + public function getJobRecord() + { + return $this->job; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJobRecord.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJobRecord.php new file mode 100644 index 0000000..b4b5725 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJobRecord.php @@ -0,0 +1,63 @@ +record = $record; + } + + /** + * Increment the number of times the job has been attempted. + * + * @return int + */ + public function increment() + { + $this->record->attempts++; + + return $this->record->attempts; + } + + /** + * Update the "reserved at" timestamp of the job. + * + * @return int + */ + public function touch() + { + $this->record->reserved_at = $this->currentTime(); + + return $this->record->reserved_at; + } + + /** + * Dynamically access the underlying job information. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->record->{$key}; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php new file mode 100755 index 0000000..28cd103 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php @@ -0,0 +1,359 @@ +payload()['uuid'] ?? null; + } + + /** + * Fire the job. + * + * @return void + */ + public function fire() + { + $payload = $this->payload(); + + [$class, $method] = JobName::parse($payload['job']); + + ($this->instance = $this->resolve($class))->{$method}($this, $payload['data']); + } + + /** + * Delete the job from the queue. + * + * @return void + */ + public function delete() + { + $this->deleted = true; + } + + /** + * Determine if the job has been deleted. + * + * @return bool + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + $this->released = true; + } + + /** + * Determine if the job was released back into the queue. + * + * @return bool + */ + public function isReleased() + { + return $this->released; + } + + /** + * Determine if the job has been deleted or released. + * + * @return bool + */ + public function isDeletedOrReleased() + { + return $this->isDeleted() || $this->isReleased(); + } + + /** + * Determine if the job has been marked as a failure. + * + * @return bool + */ + public function hasFailed() + { + return $this->failed; + } + + /** + * Mark the job as "failed". + * + * @return void + */ + public function markAsFailed() + { + $this->failed = true; + } + + /** + * Delete the job, call the "failed" method, and raise the failed job event. + * + * @param \Throwable|null $e + * @return void + */ + public function fail($e = null) + { + $this->markAsFailed(); + + if ($this->isDeleted()) { + return; + } + + try { + // If the job has failed, we will delete it, call the "failed" method and then call + // an event indicating the job has failed so it can be logged if needed. This is + // to allow every developer to better keep monitor of their failed queue jobs. + $this->delete(); + + $this->failed($e); + } finally { + $this->resolve(Dispatcher::class)->dispatch(new JobFailed( + $this->connectionName, $this, $e ?: new ManuallyFailedException + )); + } + } + + /** + * Process an exception that caused the job to fail. + * + * @param \Throwable|null $e + * @return void + */ + protected function failed($e) + { + $payload = $this->payload(); + + [$class, $method] = JobName::parse($payload['job']); + + if (method_exists($this->instance = $this->resolve($class), 'failed')) { + $this->instance->failed($payload['data'], $e, $payload['uuid'] ?? ''); + } + } + + /** + * Resolve the given class. + * + * @param string $class + * @return mixed + */ + protected function resolve($class) + { + return $this->container->make($class); + } + + /** + * Get the resolved job handler instance. + * + * @return mixed + */ + public function getResolvedJob() + { + return $this->instance; + } + + /** + * Get the decoded body of the job. + * + * @return array + */ + public function payload() + { + return json_decode($this->getRawBody(), true); + } + + /** + * Get the number of times to attempt a job. + * + * @return int|null + */ + public function maxTries() + { + return $this->payload()['maxTries'] ?? null; + } + + /** + * Get the number of times to attempt a job after an exception. + * + * @return int|null + */ + public function maxExceptions() + { + return $this->payload()['maxExceptions'] ?? null; + } + + /** + * Determine if the job should fail when it timeouts. + * + * @return bool + */ + public function shouldFailOnTimeout() + { + return $this->payload()['failOnTimeout'] ?? false; + } + + /** + * The number of seconds to wait before retrying a job that encountered an uncaught exception. + * + * @return int|null + */ + public function backoff() + { + return $this->payload()['backoff'] ?? $this->payload()['delay'] ?? null; + } + + /** + * Get the number of seconds the job can run. + * + * @return int|null + */ + public function timeout() + { + return $this->payload()['timeout'] ?? null; + } + + /** + * Get the timestamp indicating when the job should timeout. + * + * @return int|null + */ + public function retryUntil() + { + return $this->payload()['retryUntil'] ?? $this->payload()['timeoutAt'] ?? null; + } + + /** + * Get the name of the queued job class. + * + * @return string + */ + public function getName() + { + return $this->payload()['job']; + } + + /** + * Get the resolved name of the queued job class. + * + * Resolves the name of "wrapped" jobs such as class-based handlers. + * + * @return string + */ + public function resolveName() + { + return JobName::resolve($this->getName(), $this->payload()); + } + + /** + * Get the name of the connection the job belongs to. + * + * @return string + */ + public function getConnectionName() + { + return $this->connectionName; + } + + /** + * Get the name of the queue the job belongs to. + * + * @return string + */ + public function getQueue() + { + return $this->queue; + } + + /** + * Get the service container instance. + * + * @return \Illuminate\Container\Container + */ + public function getContainer() + { + return $this->container; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/JobName.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/JobName.php new file mode 100644 index 0000000..0db53bb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/JobName.php @@ -0,0 +1,35 @@ +job = $job; + $this->redis = $redis; + $this->queue = $queue; + $this->reserved = $reserved; + $this->container = $container; + $this->connectionName = $connectionName; + + $this->decoded = $this->payload(); + } + + /** + * Get the raw body string for the job. + * + * @return string + */ + public function getRawBody() + { + return $this->job; + } + + /** + * Delete the job from the queue. + * + * @return void + */ + public function delete() + { + parent::delete(); + + $this->redis->deleteReserved($this->queue, $this); + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + parent::release($delay); + + $this->redis->deleteAndRelease($this->queue, $this, $delay); + } + + /** + * Get the number of times the job has been attempted. + * + * @return int + */ + public function attempts() + { + return ($this->decoded['attempts'] ?? null) + 1; + } + + /** + * Get the job identifier. + * + * @return string|null + */ + public function getJobId() + { + return $this->decoded['id'] ?? null; + } + + /** + * Get the underlying Redis factory implementation. + * + * @return \Illuminate\Queue\RedisQueue + */ + public function getRedisQueue() + { + return $this->redis; + } + + /** + * Get the underlying reserved Redis job. + * + * @return string + */ + public function getReservedJob() + { + return $this->reserved; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SqsJob.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SqsJob.php new file mode 100755 index 0000000..5253850 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SqsJob.php @@ -0,0 +1,124 @@ +sqs = $sqs; + $this->job = $job; + $this->queue = $queue; + $this->container = $container; + $this->connectionName = $connectionName; + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + parent::release($delay); + + $this->sqs->changeMessageVisibility([ + 'QueueUrl' => $this->queue, + 'ReceiptHandle' => $this->job['ReceiptHandle'], + 'VisibilityTimeout' => $delay, + ]); + } + + /** + * Delete the job from the queue. + * + * @return void + */ + public function delete() + { + parent::delete(); + + $this->sqs->deleteMessage([ + 'QueueUrl' => $this->queue, 'ReceiptHandle' => $this->job['ReceiptHandle'], + ]); + } + + /** + * Get the number of times the job has been attempted. + * + * @return int + */ + public function attempts() + { + return (int) $this->job['Attributes']['ApproximateReceiveCount']; + } + + /** + * Get the job identifier. + * + * @return string + */ + public function getJobId() + { + return $this->job['MessageId']; + } + + /** + * Get the raw body string for the job. + * + * @return string + */ + public function getRawBody() + { + return $this->job['Body']; + } + + /** + * Get the underlying SQS client instance. + * + * @return \Aws\Sqs\SqsClient + */ + public function getSqs() + { + return $this->sqs; + } + + /** + * Get the underlying raw SQS job. + * + * @return array + */ + public function getSqsJob() + { + return $this->job; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SyncJob.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SyncJob.php new file mode 100755 index 0000000..de6e5c6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SyncJob.php @@ -0,0 +1,91 @@ +queue = $queue; + $this->payload = $payload; + $this->container = $container; + $this->connectionName = $connectionName; + } + + /** + * Release the job back into the queue. + * + * @param int $delay + * @return void + */ + public function release($delay = 0) + { + parent::release($delay); + } + + /** + * Get the number of times the job has been attempted. + * + * @return int + */ + public function attempts() + { + return 1; + } + + /** + * Get the job identifier. + * + * @return string + */ + public function getJobId() + { + return ''; + } + + /** + * Get the raw body string for the job. + * + * @return string + */ + public function getRawBody() + { + return $this->payload; + } + + /** + * Get the name of the queue the job belongs to. + * + * @return string + */ + public function getQueue() + { + return 'sync'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Listener.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Listener.php new file mode 100755 index 0000000..cbead01 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Listener.php @@ -0,0 +1,231 @@ +commandPath = $commandPath; + } + + /** + * Get the PHP binary. + * + * @return string + */ + protected function phpBinary() + { + return (new PhpExecutableFinder)->find(false); + } + + /** + * Get the Artisan binary. + * + * @return string + */ + protected function artisanBinary() + { + return defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan'; + } + + /** + * Listen to the given queue connection. + * + * @param string $connection + * @param string $queue + * @param \Illuminate\Queue\ListenerOptions $options + * @return void + */ + public function listen($connection, $queue, ListenerOptions $options) + { + $process = $this->makeProcess($connection, $queue, $options); + + while (true) { + $this->runProcess($process, $options->memory); + } + } + + /** + * Create a new Symfony process for the worker. + * + * @param string $connection + * @param string $queue + * @param \Illuminate\Queue\ListenerOptions $options + * @return \Symfony\Component\Process\Process + */ + public function makeProcess($connection, $queue, ListenerOptions $options) + { + $command = $this->createCommand( + $connection, + $queue, + $options + ); + + // If the environment is set, we will append it to the command array so the + // workers will run under the specified environment. Otherwise, they will + // just run under the production environment which is not always right. + if (isset($options->environment)) { + $command = $this->addEnvironment($command, $options); + } + + return new Process( + $command, + $this->commandPath, + null, + null, + $options->timeout + ); + } + + /** + * Add the environment option to the given command. + * + * @param array $command + * @param \Illuminate\Queue\ListenerOptions $options + * @return array + */ + protected function addEnvironment($command, ListenerOptions $options) + { + return array_merge($command, ["--env={$options->environment}"]); + } + + /** + * Create the command with the listener options. + * + * @param string $connection + * @param string $queue + * @param \Illuminate\Queue\ListenerOptions $options + * @return array + */ + protected function createCommand($connection, $queue, ListenerOptions $options) + { + return array_filter([ + $this->phpBinary(), + $this->artisanBinary(), + 'queue:work', + $connection, + '--once', + "--name={$options->name}", + "--queue={$queue}", + "--backoff={$options->backoff}", + "--memory={$options->memory}", + "--sleep={$options->sleep}", + "--tries={$options->maxTries}", + ], function ($value) { + return ! is_null($value); + }); + } + + /** + * Run the given process. + * + * @param \Symfony\Component\Process\Process $process + * @param int $memory + * @return void + */ + public function runProcess(Process $process, $memory) + { + $process->run(function ($type, $line) { + $this->handleWorkerOutput($type, $line); + }); + + // Once we have run the job we'll go check if the memory limit has been exceeded + // for the script. If it has, we will kill this script so the process manager + // will restart this with a clean slate of memory automatically on exiting. + if ($this->memoryExceeded($memory)) { + $this->stop(); + } + } + + /** + * Handle output from the worker process. + * + * @param int $type + * @param string $line + * @return void + */ + protected function handleWorkerOutput($type, $line) + { + if (isset($this->outputHandler)) { + call_user_func($this->outputHandler, $type, $line); + } + } + + /** + * Determine if the memory limit has been exceeded. + * + * @param int $memoryLimit + * @return bool + */ + public function memoryExceeded($memoryLimit) + { + return (memory_get_usage(true) / 1024 / 1024) >= $memoryLimit; + } + + /** + * Stop listening and bail out of the script. + * + * @return void + */ + public function stop() + { + exit; + } + + /** + * Set the output handler callback. + * + * @param \Closure $outputHandler + * @return void + */ + public function setOutputHandler(Closure $outputHandler) + { + $this->outputHandler = $outputHandler; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/ListenerOptions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/ListenerOptions.php new file mode 100644 index 0000000..c147f7a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/ListenerOptions.php @@ -0,0 +1,33 @@ +environment = $environment; + + parent::__construct($name, $backoff, $memory, $timeout, $sleep, $maxTries, $force); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/LuaScripts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/LuaScripts.php new file mode 100644 index 0000000..fa27842 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/LuaScripts.php @@ -0,0 +1,148 @@ +limiter = Container::getInstance()->make(RateLimiter::class); + + $this->limiterName = $limiterName; + } + + /** + * Process the job. + * + * @param mixed $job + * @param callable $next + * @return mixed + */ + public function handle($job, $next) + { + if (is_null($limiter = $this->limiter->limiter($this->limiterName))) { + return $next($job); + } + + $limiterResponse = call_user_func($limiter, $job); + + if ($limiterResponse instanceof Unlimited) { + return $next($job); + } + + return $this->handleJob( + $job, + $next, + collect(Arr::wrap($limiterResponse))->map(function ($limit) { + return (object) [ + 'key' => md5($this->limiterName.$limit->key), + 'maxAttempts' => $limit->maxAttempts, + 'decayMinutes' => $limit->decayMinutes, + ]; + })->all() + ); + } + + /** + * Handle a rate limited job. + * + * @param mixed $job + * @param callable $next + * @param array $limits + * @return mixed + */ + protected function handleJob($job, $next, array $limits) + { + foreach ($limits as $limit) { + if ($this->limiter->tooManyAttempts($limit->key, $limit->maxAttempts)) { + return $this->shouldRelease + ? $job->release($this->getTimeUntilNextRetry($limit->key)) + : false; + } + + $this->limiter->hit($limit->key, $limit->decayMinutes * 60); + } + + return $next($job); + } + + /** + * Do not release the job back to the queue if the limit is exceeded. + * + * @return $this + */ + public function dontRelease() + { + $this->shouldRelease = false; + + return $this; + } + + /** + * Get the number of seconds that should elapse before the job is retried. + * + * @param string $key + * @return int + */ + protected function getTimeUntilNextRetry($key) + { + return $this->limiter->availableIn($key) + 3; + } + + /** + * Prepare the object for serialization. + * + * @return array + */ + public function __sleep() + { + return [ + 'limiterName', + 'shouldRelease', + ]; + } + + /** + * Prepare the object after unserialization. + * + * @return void + */ + public function __wakeup() + { + $this->limiter = Container::getInstance()->make(RateLimiter::class); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/RateLimitedWithRedis.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/RateLimitedWithRedis.php new file mode 100644 index 0000000..e919786 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/RateLimitedWithRedis.php @@ -0,0 +1,103 @@ +redis = Container::getInstance()->make(Redis::class); + } + + /** + * Handle a rate limited job. + * + * @param mixed $job + * @param callable $next + * @param array $limits + * @return mixed + */ + protected function handleJob($job, $next, array $limits) + { + foreach ($limits as $limit) { + if ($this->tooManyAttempts($limit->key, $limit->maxAttempts, $limit->decayMinutes)) { + return $this->shouldRelease + ? $job->release($this->getTimeUntilNextRetry($limit->key)) + : false; + } + } + + return $next($job); + } + + /** + * Determine if the given key has been "accessed" too many times. + * + * @param string $key + * @param int $maxAttempts + * @param int $decayMinutes + * @return bool + */ + protected function tooManyAttempts($key, $maxAttempts, $decayMinutes) + { + $limiter = new DurationLimiter( + $this->redis, $key, $maxAttempts, $decayMinutes * 60 + ); + + return tap(! $limiter->acquire(), function () use ($key, $limiter) { + $this->decaysAt[$key] = $limiter->decaysAt; + }); + } + + /** + * Get the number of seconds that should elapse before the job is retried. + * + * @param string $key + * @return int + */ + protected function getTimeUntilNextRetry($key) + { + return ($this->decaysAt[$key] - $this->currentTime()) + 3; + } + + /** + * Prepare the object after unserialization. + * + * @return void + */ + public function __wakeup() + { + parent::__wakeup(); + + $this->redis = Container::getInstance()->make(Redis::class); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/ThrottlesExceptions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/ThrottlesExceptions.php new file mode 100644 index 0000000..d289989 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/ThrottlesExceptions.php @@ -0,0 +1,202 @@ +maxAttempts = $maxAttempts; + $this->decayMinutes = $decayMinutes; + } + + /** + * Process the job. + * + * @param mixed $job + * @param callable $next + * @return mixed + */ + public function handle($job, $next) + { + $this->limiter = Container::getInstance()->make(RateLimiter::class); + + if ($this->limiter->tooManyAttempts($jobKey = $this->getKey($job), $this->maxAttempts)) { + return $job->release($this->getTimeUntilNextRetry($jobKey)); + } + + try { + $next($job); + + $this->limiter->clear($jobKey); + } catch (Throwable $throwable) { + if ($this->whenCallback && ! call_user_func($this->whenCallback, $throwable)) { + throw $throwable; + } + + $this->limiter->hit($jobKey, $this->decayMinutes * 60); + + return $job->release($this->retryAfterMinutes * 60); + } + } + + /** + * Specify a callback that should determine if rate limiting behavior should apply. + * + * @param callable $callback + * @return $this + */ + public function when(callable $callback) + { + $this->whenCallback = $callback; + + return $this; + } + + /** + * Set the prefix of the rate limiter key. + * + * @param string $prefix + * @return $this + */ + public function withPrefix(string $prefix) + { + $this->prefix = $prefix; + + return $this; + } + + /** + * Specify the number of minutes a job should be delayed when it is released (before it has reached its max exceptions). + * + * @param int $backoff + * @return $this + */ + public function backoff($backoff) + { + $this->retryAfterMinutes = $backoff; + + return $this; + } + + /** + * Get the cache key associated for the rate limiter. + * + * @param mixed $job + * @return string + */ + protected function getKey($job) + { + if ($this->key) { + return $this->prefix.$this->key; + } elseif ($this->byJob) { + return $this->prefix.$job->job->uuid(); + } + + return $this->prefix.md5(get_class($job)); + } + + /** + * Set the value that the rate limiter should be keyed by. + * + * @param string $key + * @return $this + */ + public function by($key) + { + $this->key = $key; + + return $this; + } + + /** + * Indicate that the throttle key should use the job's UUID. + * + * @return $this + */ + public function byJob() + { + $this->byJob = true; + + return $this; + } + + /** + * Get the number of seconds that should elapse before the job is retried. + * + * @param string $key + * @return int + */ + protected function getTimeUntilNextRetry($key) + { + return $this->limiter->availableIn($key) + 3; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/ThrottlesExceptionsWithRedis.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/ThrottlesExceptionsWithRedis.php new file mode 100644 index 0000000..38790e3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/ThrottlesExceptionsWithRedis.php @@ -0,0 +1,62 @@ +redis = Container::getInstance()->make(Redis::class); + + $this->limiter = new DurationLimiter( + $this->redis, $this->getKey($job), $this->maxAttempts, $this->decayMinutes * 60 + ); + + if ($this->limiter->tooManyAttempts()) { + return $job->release($this->limiter->decaysAt - $this->currentTime()); + } + + try { + $next($job); + + $this->limiter->clear(); + } catch (Throwable $throwable) { + if ($this->whenCallback && ! call_user_func($this->whenCallback, $throwable)) { + throw $throwable; + } + + $this->limiter->acquire(); + + return $job->release($this->retryAfterMinutes * 60); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/WithoutOverlapping.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/WithoutOverlapping.php new file mode 100644 index 0000000..c7989e6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Middleware/WithoutOverlapping.php @@ -0,0 +1,141 @@ +key = $key; + $this->releaseAfter = $releaseAfter; + $this->expiresAfter = $this->secondsUntil($expiresAfter); + } + + /** + * Process the job. + * + * @param mixed $job + * @param callable $next + * @return mixed + */ + public function handle($job, $next) + { + $lock = Container::getInstance()->make(Cache::class)->lock( + $this->getLockKey($job), $this->expiresAfter + ); + + if ($lock->get()) { + try { + $next($job); + } finally { + $lock->release(); + } + } elseif (! is_null($this->releaseAfter)) { + $job->release($this->releaseAfter); + } + } + + /** + * Set the delay (in seconds) to release the job back to the queue. + * + * @param \DateTimeInterface|int $releaseAfter + * @return $this + */ + public function releaseAfter($releaseAfter) + { + $this->releaseAfter = $releaseAfter; + + return $this; + } + + /** + * Do not release the job back to the queue if no lock can be acquired. + * + * @return $this + */ + public function dontRelease() + { + $this->releaseAfter = null; + + return $this; + } + + /** + * Set the maximum number of seconds that can elapse before the lock is released. + * + * @param \DateTimeInterface|int $expiresAfter + * @return $this + */ + public function expireAfter($expiresAfter) + { + $this->expiresAfter = $this->secondsUntil($expiresAfter); + + return $this; + } + + /** + * Set the prefix of the lock key. + * + * @param string $prefix + * @return $this + */ + public function withPrefix(string $prefix) + { + $this->prefix = $prefix; + + return $this; + } + + /** + * Get the lock key for the given job. + * + * @param mixed $job + * @return string + */ + public function getLockKey($job) + { + return $this->prefix.get_class($job).':'.$this->key; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/NullQueue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/NullQueue.php new file mode 100644 index 0000000..f8ff093 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/NullQueue.php @@ -0,0 +1,70 @@ +push($job, $data, $queue); + } + + /** + * Push a new job onto the queue after a delay. + * + * @param string $queue + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $job + * @param mixed $data + * @return mixed + */ + public function laterOn($queue, $delay, $job, $data = '') + { + return $this->later($delay, $job, $data, $queue); + } + + /** + * Push an array of jobs onto the queue. + * + * @param array $jobs + * @param mixed $data + * @param string|null $queue + * @return void + */ + public function bulk($jobs, $data = '', $queue = null) + { + foreach ((array) $jobs as $job) { + $this->push($job, $data, $queue); + } + } + + /** + * Create a payload string from the given job and data. + * + * @param \Closure|string|object $job + * @param string $queue + * @param mixed $data + * @return string + * + * @throws \Illuminate\Queue\InvalidPayloadException + */ + protected function createPayload($job, $queue, $data = '') + { + if ($job instanceof Closure) { + $job = CallQueuedClosure::create($job); + } + + $payload = json_encode($this->createPayloadArray($job, $queue, $data), \JSON_UNESCAPED_UNICODE); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw new InvalidPayloadException( + 'Unable to JSON encode payload. Error code: '.json_last_error() + ); + } + + return $payload; + } + + /** + * Create a payload array from the given job and data. + * + * @param string|object $job + * @param string $queue + * @param mixed $data + * @return array + */ + protected function createPayloadArray($job, $queue, $data = '') + { + return is_object($job) + ? $this->createObjectPayload($job, $queue) + : $this->createStringPayload($job, $queue, $data); + } + + /** + * Create a payload for an object-based queue handler. + * + * @param object $job + * @param string $queue + * @return array + */ + protected function createObjectPayload($job, $queue) + { + $payload = $this->withCreatePayloadHooks($queue, [ + 'uuid' => (string) Str::uuid(), + 'displayName' => $this->getDisplayName($job), + 'job' => 'Illuminate\Queue\CallQueuedHandler@call', + 'maxTries' => $job->tries ?? null, + 'maxExceptions' => $job->maxExceptions ?? null, + 'failOnTimeout' => $job->failOnTimeout ?? false, + 'backoff' => $this->getJobBackoff($job), + 'timeout' => $job->timeout ?? null, + 'retryUntil' => $this->getJobExpiration($job), + 'data' => [ + 'commandName' => $job, + 'command' => $job, + ], + ]); + + $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class) + ? $this->container[Encrypter::class]->encrypt(serialize(clone $job)) + : serialize(clone $job); + + return array_merge($payload, [ + 'data' => array_merge($payload['data'], [ + 'commandName' => get_class($job), + 'command' => $command, + ]), + ]); + } + + /** + * Get the display name for the given job. + * + * @param object $job + * @return string + */ + protected function getDisplayName($job) + { + return method_exists($job, 'displayName') + ? $job->displayName() : get_class($job); + } + + /** + * Get the backoff for an object-based queue handler. + * + * @param mixed $job + * @return mixed + */ + public function getJobBackoff($job) + { + if (! method_exists($job, 'backoff') && ! isset($job->backoff)) { + return; + } + + if (is_null($backoff = $job->backoff ?? $job->backoff())) { + return; + } + + return collect(Arr::wrap($backoff)) + ->map(function ($backoff) { + return $backoff instanceof DateTimeInterface + ? $this->secondsUntil($backoff) : $backoff; + })->implode(','); + } + + /** + * Get the expiration timestamp for an object-based queue handler. + * + * @param mixed $job + * @return mixed + */ + public function getJobExpiration($job) + { + if (! method_exists($job, 'retryUntil') && ! isset($job->retryUntil)) { + return; + } + + $expiration = $job->retryUntil ?? $job->retryUntil(); + + return $expiration instanceof DateTimeInterface + ? $expiration->getTimestamp() : $expiration; + } + + /** + * Determine if the job should be encrypted. + * + * @param object $job + * @return bool + */ + protected function jobShouldBeEncrypted($job) + { + if ($job instanceof ShouldBeEncrypted) { + return true; + } + + return isset($job->shouldBeEncrypted) && $job->shouldBeEncrypted; + } + + /** + * Create a typical, string based queue payload array. + * + * @param string $job + * @param string $queue + * @param mixed $data + * @return array + */ + protected function createStringPayload($job, $queue, $data) + { + return $this->withCreatePayloadHooks($queue, [ + 'uuid' => (string) Str::uuid(), + 'displayName' => is_string($job) ? explode('@', $job)[0] : null, + 'job' => $job, + 'maxTries' => null, + 'maxExceptions' => null, + 'failOnTimeout' => false, + 'backoff' => null, + 'timeout' => null, + 'data' => $data, + ]); + } + + /** + * Register a callback to be executed when creating job payloads. + * + * @param callable|null $callback + * @return void + */ + public static function createPayloadUsing($callback) + { + if (is_null($callback)) { + static::$createPayloadCallbacks = []; + } else { + static::$createPayloadCallbacks[] = $callback; + } + } + + /** + * Create the given payload using any registered payload hooks. + * + * @param string $queue + * @param array $payload + * @return array + */ + protected function withCreatePayloadHooks($queue, array $payload) + { + if (! empty(static::$createPayloadCallbacks)) { + foreach (static::$createPayloadCallbacks as $callback) { + $payload = array_merge($payload, call_user_func( + $callback, $this->getConnectionName(), $queue, $payload + )); + } + } + + return $payload; + } + + /** + * Enqueue a job using the given callback. + * + * @param \Closure|string|object $job + * @param string $payload + * @param string $queue + * @param \DateTimeInterface|\DateInterval|int|null $delay + * @param callable $callback + * @return mixed + */ + protected function enqueueUsing($job, $payload, $queue, $delay, $callback) + { + if ($this->shouldDispatchAfterCommit($job) && + $this->container->bound('db.transactions')) { + return $this->container->make('db.transactions')->addCallback( + function () use ($payload, $queue, $delay, $callback, $job) { + return tap($callback($payload, $queue, $delay), function ($jobId) use ($job) { + $this->raiseJobQueuedEvent($jobId, $job); + }); + } + ); + } + + return tap($callback($payload, $queue, $delay), function ($jobId) use ($job) { + $this->raiseJobQueuedEvent($jobId, $job); + }); + } + + /** + * Determine if the job should be dispatched after all database transactions have committed. + * + * @param \Closure|string|object $job + * @return bool + */ + protected function shouldDispatchAfterCommit($job) + { + if (is_object($job) && isset($job->afterCommit)) { + return $job->afterCommit; + } + + if (isset($this->dispatchAfterCommit)) { + return $this->dispatchAfterCommit; + } + + return false; + } + + /** + * Raise the job queued event. + * + * @param string|int|null $jobId + * @param \Closure|string|object $job + * @return void + */ + protected function raiseJobQueuedEvent($jobId, $job) + { + if ($this->container->bound('events')) { + $this->container['events']->dispatch(new JobQueued($this->connectionName, $jobId, $job)); + } + } + + /** + * Get the connection name for the queue. + * + * @return string + */ + public function getConnectionName() + { + return $this->connectionName; + } + + /** + * Set the connection name for the queue. + * + * @param string $name + * @return $this + */ + public function setConnectionName($name) + { + $this->connectionName = $name; + + return $this; + } + + /** + * Get the container instance being used by the connection. + * + * @return \Illuminate\Container\Container + */ + public function getContainer() + { + return $this->container; + } + + /** + * Set the IoC container instance. + * + * @param \Illuminate\Container\Container $container + * @return void + */ + public function setContainer(Container $container) + { + $this->container = $container; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/QueueManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/QueueManager.php new file mode 100755 index 0000000..33f1cd1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/QueueManager.php @@ -0,0 +1,293 @@ +app = $app; + } + + /** + * Register an event listener for the before job event. + * + * @param mixed $callback + * @return void + */ + public function before($callback) + { + $this->app['events']->listen(Events\JobProcessing::class, $callback); + } + + /** + * Register an event listener for the after job event. + * + * @param mixed $callback + * @return void + */ + public function after($callback) + { + $this->app['events']->listen(Events\JobProcessed::class, $callback); + } + + /** + * Register an event listener for the exception occurred job event. + * + * @param mixed $callback + * @return void + */ + public function exceptionOccurred($callback) + { + $this->app['events']->listen(Events\JobExceptionOccurred::class, $callback); + } + + /** + * Register an event listener for the daemon queue loop. + * + * @param mixed $callback + * @return void + */ + public function looping($callback) + { + $this->app['events']->listen(Events\Looping::class, $callback); + } + + /** + * Register an event listener for the failed job event. + * + * @param mixed $callback + * @return void + */ + public function failing($callback) + { + $this->app['events']->listen(Events\JobFailed::class, $callback); + } + + /** + * Register an event listener for the daemon queue stopping. + * + * @param mixed $callback + * @return void + */ + public function stopping($callback) + { + $this->app['events']->listen(Events\WorkerStopping::class, $callback); + } + + /** + * Determine if the driver is connected. + * + * @param string|null $name + * @return bool + */ + public function connected($name = null) + { + return isset($this->connections[$name ?: $this->getDefaultDriver()]); + } + + /** + * Resolve a queue connection instance. + * + * @param string|null $name + * @return \Illuminate\Contracts\Queue\Queue + */ + public function connection($name = null) + { + $name = $name ?: $this->getDefaultDriver(); + + // If the connection has not been resolved yet we will resolve it now as all + // of the connections are resolved when they are actually needed so we do + // not make any unnecessary connection to the various queue end-points. + if (! isset($this->connections[$name])) { + $this->connections[$name] = $this->resolve($name); + + $this->connections[$name]->setContainer($this->app); + } + + return $this->connections[$name]; + } + + /** + * Resolve a queue connection. + * + * @param string $name + * @return \Illuminate\Contracts\Queue\Queue + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("The [{$name}] queue connection has not been configured."); + } + + return $this->getConnector($config['driver']) + ->connect($config) + ->setConnectionName($name); + } + + /** + * Get the connector for a given driver. + * + * @param string $driver + * @return \Illuminate\Queue\Connectors\ConnectorInterface + * + * @throws \InvalidArgumentException + */ + protected function getConnector($driver) + { + if (! isset($this->connectors[$driver])) { + throw new InvalidArgumentException("No connector for [$driver]."); + } + + return call_user_func($this->connectors[$driver]); + } + + /** + * Add a queue connection resolver. + * + * @param string $driver + * @param \Closure $resolver + * @return void + */ + public function extend($driver, Closure $resolver) + { + return $this->addConnector($driver, $resolver); + } + + /** + * Add a queue connection resolver. + * + * @param string $driver + * @param \Closure $resolver + * @return void + */ + public function addConnector($driver, Closure $resolver) + { + $this->connectors[$driver] = $resolver; + } + + /** + * Get the queue connection configuration. + * + * @param string $name + * @return array|null + */ + protected function getConfig($name) + { + if (! is_null($name) && $name !== 'null') { + return $this->app['config']["queue.connections.{$name}"]; + } + + return ['driver' => 'null']; + } + + /** + * Get the name of the default queue connection. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->app['config']['queue.default']; + } + + /** + * Set the name of the default queue connection. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->app['config']['queue.default'] = $name; + } + + /** + * Get the full name for the given connection. + * + * @param string|null $connection + * @return string + */ + public function getName($connection = null) + { + return $connection ?: $this->getDefaultDriver(); + } + + /** + * Get the application instance used by the manager. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public function getApplication() + { + return $this->app; + } + + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return $this + */ + public function setApplication($app) + { + $this->app = $app; + + foreach ($this->connections as $connection) { + $connection->setContainer($app); + } + + return $this; + } + + /** + * Dynamically pass calls to the default connection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->connection()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/QueueServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/QueueServiceProvider.php new file mode 100755 index 0000000..97ac37e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/QueueServiceProvider.php @@ -0,0 +1,326 @@ +configureSerializableClosureUses(); + + $this->registerManager(); + $this->registerConnection(); + $this->registerWorker(); + $this->registerListener(); + $this->registerFailedJobServices(); + } + + /** + * Configure serializable closures uses. + * + * @return void + */ + protected function configureSerializableClosureUses() + { + SerializableClosure::transformUseVariablesUsing(function ($data) { + foreach ($data as $key => $value) { + $data[$key] = $this->getSerializedPropertyValue($value); + } + + return $data; + }); + + SerializableClosure::resolveUseVariablesUsing(function ($data) { + foreach ($data as $key => $value) { + $data[$key] = $this->getRestoredPropertyValue($value); + } + + return $data; + }); + } + + /** + * Register the queue manager. + * + * @return void + */ + protected function registerManager() + { + $this->app->singleton('queue', function ($app) { + // Once we have an instance of the queue manager, we will register the various + // resolvers for the queue connectors. These connectors are responsible for + // creating the classes that accept queue configs and instantiate queues. + return tap(new QueueManager($app), function ($manager) { + $this->registerConnectors($manager); + }); + }); + } + + /** + * Register the default queue connection binding. + * + * @return void + */ + protected function registerConnection() + { + $this->app->singleton('queue.connection', function ($app) { + return $app['queue']->connection(); + }); + } + + /** + * Register the connectors on the queue manager. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + public function registerConnectors($manager) + { + foreach (['Null', 'Sync', 'Database', 'Redis', 'Beanstalkd', 'Sqs'] as $connector) { + $this->{"register{$connector}Connector"}($manager); + } + } + + /** + * Register the Null queue connector. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + protected function registerNullConnector($manager) + { + $manager->addConnector('null', function () { + return new NullConnector; + }); + } + + /** + * Register the Sync queue connector. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + protected function registerSyncConnector($manager) + { + $manager->addConnector('sync', function () { + return new SyncConnector; + }); + } + + /** + * Register the database queue connector. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + protected function registerDatabaseConnector($manager) + { + $manager->addConnector('database', function () { + return new DatabaseConnector($this->app['db']); + }); + } + + /** + * Register the Redis queue connector. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + protected function registerRedisConnector($manager) + { + $manager->addConnector('redis', function () { + return new RedisConnector($this->app['redis']); + }); + } + + /** + * Register the Beanstalkd queue connector. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + protected function registerBeanstalkdConnector($manager) + { + $manager->addConnector('beanstalkd', function () { + return new BeanstalkdConnector; + }); + } + + /** + * Register the Amazon SQS queue connector. + * + * @param \Illuminate\Queue\QueueManager $manager + * @return void + */ + protected function registerSqsConnector($manager) + { + $manager->addConnector('sqs', function () { + return new SqsConnector; + }); + } + + /** + * Register the queue worker. + * + * @return void + */ + protected function registerWorker() + { + $this->app->singleton('queue.worker', function ($app) { + $isDownForMaintenance = function () { + return $this->app->isDownForMaintenance(); + }; + + $resetScope = function () use ($app) { + if (method_exists($app['log']->driver(), 'withoutContext')) { + $app['log']->withoutContext(); + } + + $app->forgetScopedInstances(); + + return Facade::clearResolvedInstances(); + }; + + return new Worker( + $app['queue'], + $app['events'], + $app[ExceptionHandler::class], + $isDownForMaintenance, + $resetScope + ); + }); + } + + /** + * Register the queue listener. + * + * @return void + */ + protected function registerListener() + { + $this->app->singleton('queue.listener', function ($app) { + return new Listener($app->basePath()); + }); + } + + /** + * Register the failed job services. + * + * @return void + */ + protected function registerFailedJobServices() + { + $this->app->singleton('queue.failer', function ($app) { + $config = $app['config']['queue.failed']; + + if (array_key_exists('driver', $config) && + (is_null($config['driver']) || $config['driver'] === 'null')) { + return new NullFailedJobProvider; + } + + if (isset($config['driver']) && $config['driver'] === 'dynamodb') { + return $this->dynamoFailedJobProvider($config); + } elseif (isset($config['driver']) && $config['driver'] === 'database-uuids') { + return $this->databaseUuidFailedJobProvider($config); + } elseif (isset($config['table'])) { + return $this->databaseFailedJobProvider($config); + } else { + return new NullFailedJobProvider; + } + }); + } + + /** + * Create a new database failed job provider. + * + * @param array $config + * @return \Illuminate\Queue\Failed\DatabaseFailedJobProvider + */ + protected function databaseFailedJobProvider($config) + { + return new DatabaseFailedJobProvider( + $this->app['db'], $config['database'], $config['table'] + ); + } + + /** + * Create a new database failed job provider that uses UUIDs as IDs. + * + * @param array $config + * @return \Illuminate\Queue\Failed\DatabaseUuidFailedJobProvider + */ + protected function databaseUuidFailedJobProvider($config) + { + return new DatabaseUuidFailedJobProvider( + $this->app['db'], $config['database'], $config['table'] + ); + } + + /** + * Create a new DynamoDb failed job provider. + * + * @param array $config + * @return \Illuminate\Queue\Failed\DynamoDbFailedJobProvider + */ + protected function dynamoFailedJobProvider($config) + { + $dynamoConfig = [ + 'region' => $config['region'], + 'version' => 'latest', + 'endpoint' => $config['endpoint'] ?? null, + ]; + + if (! empty($config['key']) && ! empty($config['secret'])) { + $dynamoConfig['credentials'] = Arr::only( + $config, ['key', 'secret', 'token'] + ); + } + + return new DynamoDbFailedJobProvider( + new DynamoDbClient($dynamoConfig), + $this->app['config']['app.name'], + $config['table'] + ); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + 'queue', + 'queue.connection', + 'queue.failer', + 'queue.listener', + 'queue.worker', + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/README.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/README.md new file mode 100644 index 0000000..1999dd7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/README.md @@ -0,0 +1,34 @@ +## Illuminate Queue + +The Laravel Queue component provides a unified API across a variety of different queue services. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time, thus drastically speeding up the web requests to your application. + +### Usage Instructions + +First, create a new Queue `Capsule` manager instance. Similar to the "Capsule" provided for the Eloquent ORM, the queue Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible. + +```PHP +use Illuminate\Queue\Capsule\Manager as Queue; + +$queue = new Queue; + +$queue->addConnection([ + 'driver' => 'beanstalkd', + 'host' => 'localhost', + 'queue' => 'default', +]); + +// Make this Capsule instance available globally via static methods... (optional) +$queue->setAsGlobal(); +``` + +Once the Capsule instance has been registered. You may use it like so: + +```PHP +// As an instance... +$queue->push('SendEmail', ['message' => $message]); + +// If setAsGlobal has been called... +Queue::push('SendEmail', ['message' => $message]); +``` + +For further documentation on using the queue, consult the [Laravel framework documentation](https://laravel.com/docs). diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/RedisQueue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/RedisQueue.php new file mode 100644 index 0000000..79efc05 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/RedisQueue.php @@ -0,0 +1,365 @@ +redis = $redis; + $this->default = $default; + $this->blockFor = $blockFor; + $this->connection = $connection; + $this->retryAfter = $retryAfter; + $this->dispatchAfterCommit = $dispatchAfterCommit; + } + + /** + * Get the size of the queue. + * + * @param string|null $queue + * @return int + */ + public function size($queue = null) + { + $queue = $this->getQueue($queue); + + return $this->getConnection()->eval( + LuaScripts::size(), 3, $queue, $queue.':delayed', $queue.':reserved' + ); + } + + /** + * Push an array of jobs onto the queue. + * + * @param array $jobs + * @param mixed $data + * @param string|null $queue + * @return void + */ + public function bulk($jobs, $data = '', $queue = null) + { + $this->getConnection()->pipeline(function () use ($jobs, $data, $queue) { + $this->getConnection()->transaction(function () use ($jobs, $data, $queue) { + foreach ((array) $jobs as $job) { + $this->push($job, $data, $queue); + } + }); + }); + } + + /** + * Push a new job onto the queue. + * + * @param object|string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function push($job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $this->getQueue($queue), $data), + $queue, + null, + function ($payload, $queue) { + return $this->pushRaw($payload, $queue); + } + ); + } + + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + */ + public function pushRaw($payload, $queue = null, array $options = []) + { + $this->getConnection()->eval( + LuaScripts::push(), 2, $this->getQueue($queue), + $this->getQueue($queue).':notify', $payload + ); + + return json_decode($payload, true)['id'] ?? null; + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param object|string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function later($delay, $job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $this->getQueue($queue), $data), + $queue, + $delay, + function ($payload, $queue, $delay) { + return $this->laterRaw($delay, $payload, $queue); + } + ); + } + + /** + * Push a raw job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $payload + * @param string|null $queue + * @return mixed + */ + protected function laterRaw($delay, $payload, $queue = null) + { + $this->getConnection()->zadd( + $this->getQueue($queue).':delayed', $this->availableAt($delay), $payload + ); + + return json_decode($payload, true)['id'] ?? null; + } + + /** + * Create a payload string from the given job and data. + * + * @param string $job + * @param string $queue + * @param mixed $data + * @return array + */ + protected function createPayloadArray($job, $queue, $data = '') + { + return array_merge(parent::createPayloadArray($job, $queue, $data), [ + 'id' => $this->getRandomId(), + 'attempts' => 0, + ]); + } + + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + */ + public function pop($queue = null) + { + $this->migrate($prefixed = $this->getQueue($queue)); + + [$job, $reserved] = $this->retrieveNextJob($prefixed); + + if ($reserved) { + return new RedisJob( + $this->container, $this, $job, + $reserved, $this->connectionName, $queue ?: $this->default + ); + } + } + + /** + * Migrate any delayed or expired jobs onto the primary queue. + * + * @param string $queue + * @return void + */ + protected function migrate($queue) + { + $this->migrateExpiredJobs($queue.':delayed', $queue); + + if (! is_null($this->retryAfter)) { + $this->migrateExpiredJobs($queue.':reserved', $queue); + } + } + + /** + * Migrate the delayed jobs that are ready to the regular queue. + * + * @param string $from + * @param string $to + * @return array + */ + public function migrateExpiredJobs($from, $to) + { + return $this->getConnection()->eval( + LuaScripts::migrateExpiredJobs(), 3, $from, $to, $to.':notify', $this->currentTime() + ); + } + + /** + * Retrieve the next job from the queue. + * + * @param string $queue + * @param bool $block + * @return array + */ + protected function retrieveNextJob($queue, $block = true) + { + $nextJob = $this->getConnection()->eval( + LuaScripts::pop(), 3, $queue, $queue.':reserved', $queue.':notify', + $this->availableAt($this->retryAfter) + ); + + if (empty($nextJob)) { + return [null, null]; + } + + [$job, $reserved] = $nextJob; + + if (! $job && ! is_null($this->blockFor) && $block && + $this->getConnection()->blpop([$queue.':notify'], $this->blockFor)) { + return $this->retrieveNextJob($queue, false); + } + + return [$job, $reserved]; + } + + /** + * Delete a reserved job from the queue. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\RedisJob $job + * @return void + */ + public function deleteReserved($queue, $job) + { + $this->getConnection()->zrem($this->getQueue($queue).':reserved', $job->getReservedJob()); + } + + /** + * Delete a reserved job from the reserved queue and release it. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\RedisJob $job + * @param int $delay + * @return void + */ + public function deleteAndRelease($queue, $job, $delay) + { + $queue = $this->getQueue($queue); + + $this->getConnection()->eval( + LuaScripts::release(), 2, $queue.':delayed', $queue.':reserved', + $job->getReservedJob(), $this->availableAt($delay) + ); + } + + /** + * Delete all of the jobs from the queue. + * + * @param string $queue + * @return int + */ + public function clear($queue) + { + $queue = $this->getQueue($queue); + + return $this->getConnection()->eval( + LuaScripts::clear(), 4, $queue, $queue.':delayed', + $queue.':reserved', $queue.':notify' + ); + } + + /** + * Get a random ID string. + * + * @return string + */ + protected function getRandomId() + { + return Str::random(32); + } + + /** + * Get the queue or return the default. + * + * @param string|null $queue + * @return string + */ + public function getQueue($queue) + { + return 'queues:'.($queue ?: $this->default); + } + + /** + * Get the connection for the queue. + * + * @return \Illuminate\Redis\Connections\Connection + */ + public function getConnection() + { + return $this->redis->connection($this->connection); + } + + /** + * Get the underlying Redis instance. + * + * @return \Illuminate\Contracts\Redis\Factory + */ + public function getRedis() + { + return $this->redis; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializableClosure.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializableClosure.php new file mode 100644 index 0000000..cb0a587 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializableClosure.php @@ -0,0 +1,43 @@ + $value) { + $data[$key] = $this->getSerializedPropertyValue($value); + } + + return $data; + } + + /** + * Resolve the use variables after unserialization. + * + * @param array $data + * @return array + */ + protected function resolveUseVariables($data) + { + foreach ($data as $key => $value) { + $data[$key] = $this->getRestoredPropertyValue($value); + } + + return $data; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializableClosureFactory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializableClosureFactory.php new file mode 100644 index 0000000..42aa3f6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializableClosureFactory.php @@ -0,0 +1,28 @@ +getQueueableClass(), + $value->getQueueableIds(), + $value->getQueueableRelations(), + $value->getQueueableConnection() + ); + } + + if ($value instanceof QueueableEntity) { + return new ModelIdentifier( + get_class($value), + $value->getQueueableId(), + $value->getQueueableRelations(), + $value->getQueueableConnection() + ); + } + + return $value; + } + + /** + * Get the restored property value after deserialization. + * + * @param mixed $value + * @return mixed + */ + protected function getRestoredPropertyValue($value) + { + if (! $value instanceof ModelIdentifier) { + return $value; + } + + return is_array($value->id) + ? $this->restoreCollection($value) + : $this->restoreModel($value); + } + + /** + * Restore a queueable collection instance. + * + * @param \Illuminate\Contracts\Database\ModelIdentifier $value + * @return \Illuminate\Database\Eloquent\Collection + */ + protected function restoreCollection($value) + { + if (! $value->class || count($value->id) === 0) { + return new EloquentCollection; + } + + $collection = $this->getQueryForModelRestoration( + (new $value->class)->setConnection($value->connection), $value->id + )->useWritePdo()->get(); + + if (is_a($value->class, Pivot::class, true) || + in_array(AsPivot::class, class_uses($value->class))) { + return $collection; + } + + $collection = $collection->keyBy->getKey(); + + $collectionClass = get_class($collection); + + return new $collectionClass( + collect($value->id)->map(function ($id) use ($collection) { + return $collection[$id] ?? null; + })->filter() + ); + } + + /** + * Restore the model from the model identifier instance. + * + * @param \Illuminate\Contracts\Database\ModelIdentifier $value + * @return \Illuminate\Database\Eloquent\Model + */ + public function restoreModel($value) + { + return $this->getQueryForModelRestoration( + (new $value->class)->setConnection($value->connection), $value->id + )->useWritePdo()->firstOrFail()->load($value->relations ?? []); + } + + /** + * Get the query for model restoration. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param array|int $ids + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function getQueryForModelRestoration($model, $ids) + { + return $model->newQueryForRestoration($ids); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php new file mode 100644 index 0000000..d60479d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php @@ -0,0 +1,139 @@ +getProperties(); + + foreach ($properties as $property) { + $property->setValue($this, $this->getSerializedPropertyValue( + $this->getPropertyValue($property) + )); + } + + return array_values(array_filter(array_map(function ($p) { + return $p->isStatic() ? null : $p->getName(); + }, $properties))); + } + + /** + * Restore the model after serialization. + * + * @return void + */ + public function __wakeup() + { + foreach ((new ReflectionClass($this))->getProperties() as $property) { + if ($property->isStatic()) { + continue; + } + + $property->setValue($this, $this->getRestoredPropertyValue( + $this->getPropertyValue($property) + )); + } + } + + /** + * Prepare the instance values for serialization. + * + * @return array + */ + public function __serialize() + { + $values = []; + + $properties = (new ReflectionClass($this))->getProperties(); + + $class = get_class($this); + + foreach ($properties as $property) { + if ($property->isStatic()) { + continue; + } + + $property->setAccessible(true); + + if (! $property->isInitialized($this)) { + continue; + } + + $name = $property->getName(); + + if ($property->isPrivate()) { + $name = "\0{$class}\0{$name}"; + } elseif ($property->isProtected()) { + $name = "\0*\0{$name}"; + } + + $values[$name] = $this->getSerializedPropertyValue( + $this->getPropertyValue($property) + ); + } + + return $values; + } + + /** + * Restore the model after serialization. + * + * @param array $values + * @return void + */ + public function __unserialize(array $values) + { + $properties = (new ReflectionClass($this))->getProperties(); + + $class = get_class($this); + + foreach ($properties as $property) { + if ($property->isStatic()) { + continue; + } + + $name = $property->getName(); + + if ($property->isPrivate()) { + $name = "\0{$class}\0{$name}"; + } elseif ($property->isProtected()) { + $name = "\0*\0{$name}"; + } + + if (! array_key_exists($name, $values)) { + continue; + } + + $property->setAccessible(true); + + $property->setValue( + $this, $this->getRestoredPropertyValue($values[$name]) + ); + } + } + + /** + * Get the property value for the given property. + * + * @param \ReflectionProperty $property + * @return mixed + */ + protected function getPropertyValue(ReflectionProperty $property) + { + $property->setAccessible(true); + + return $property->getValue($this); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SqsQueue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SqsQueue.php new file mode 100755 index 0000000..dab07b7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SqsQueue.php @@ -0,0 +1,222 @@ +sqs = $sqs; + $this->prefix = $prefix; + $this->default = $default; + $this->suffix = $suffix; + $this->dispatchAfterCommit = $dispatchAfterCommit; + } + + /** + * Get the size of the queue. + * + * @param string|null $queue + * @return int + */ + public function size($queue = null) + { + $response = $this->sqs->getQueueAttributes([ + 'QueueUrl' => $this->getQueue($queue), + 'AttributeNames' => ['ApproximateNumberOfMessages'], + ]); + + $attributes = $response->get('Attributes'); + + return (int) $attributes['ApproximateNumberOfMessages']; + } + + /** + * Push a new job onto the queue. + * + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function push($job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $queue ?: $this->default, $data), + $queue, + null, + function ($payload, $queue) { + return $this->pushRaw($payload, $queue); + } + ); + } + + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + */ + public function pushRaw($payload, $queue = null, array $options = []) + { + return $this->sqs->sendMessage([ + 'QueueUrl' => $this->getQueue($queue), 'MessageBody' => $payload, + ])->get('MessageId'); + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function later($delay, $job, $data = '', $queue = null) + { + return $this->enqueueUsing( + $job, + $this->createPayload($job, $queue ?: $this->default, $data), + $queue, + $delay, + function ($payload, $queue, $delay) { + return $this->sqs->sendMessage([ + 'QueueUrl' => $this->getQueue($queue), + 'MessageBody' => $payload, + 'DelaySeconds' => $this->secondsUntil($delay), + ])->get('MessageId'); + } + ); + } + + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + */ + public function pop($queue = null) + { + $response = $this->sqs->receiveMessage([ + 'QueueUrl' => $queue = $this->getQueue($queue), + 'AttributeNames' => ['ApproximateReceiveCount'], + ]); + + if (! is_null($response['Messages']) && count($response['Messages']) > 0) { + return new SqsJob( + $this->container, $this->sqs, $response['Messages'][0], + $this->connectionName, $queue + ); + } + } + + /** + * Delete all of the jobs from the queue. + * + * @param string $queue + * @return int + */ + public function clear($queue) + { + return tap($this->size($queue), function () use ($queue) { + $this->sqs->purgeQueue([ + 'QueueUrl' => $this->getQueue($queue), + ]); + }); + } + + /** + * Get the queue or return the default. + * + * @param string|null $queue + * @return string + */ + public function getQueue($queue) + { + $queue = $queue ?: $this->default; + + return filter_var($queue, FILTER_VALIDATE_URL) === false + ? $this->suffixQueue($queue, $this->suffix) + : $queue; + } + + /** + * Add the given suffix to the given queue name. + * + * @param string $queue + * @param string $suffix + * @return string + */ + protected function suffixQueue($queue, $suffix = '') + { + if (Str::endsWith($queue, '.fifo')) { + $queue = Str::beforeLast($queue, '.fifo'); + + return rtrim($this->prefix, '/').'/'.Str::finish($queue, $suffix).'.fifo'; + } + + return rtrim($this->prefix, '/').'/'.Str::finish($queue, $this->suffix); + } + + /** + * Get the underlying SQS instance. + * + * @return \Aws\Sqs\SqsClient + */ + public function getSqs() + { + return $this->sqs; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SyncQueue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SyncQueue.php new file mode 100755 index 0000000..33638c2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/SyncQueue.php @@ -0,0 +1,160 @@ +resolveJob($this->createPayload($job, $queue, $data), $queue); + + try { + $this->raiseBeforeJobEvent($queueJob); + + $queueJob->fire(); + + $this->raiseAfterJobEvent($queueJob); + } catch (Throwable $e) { + $this->handleException($queueJob, $e); + } + + return 0; + } + + /** + * Resolve a Sync job instance. + * + * @param string $payload + * @param string $queue + * @return \Illuminate\Queue\Jobs\SyncJob + */ + protected function resolveJob($payload, $queue) + { + return new SyncJob($this->container, $payload, $this->connectionName, $queue); + } + + /** + * Raise the before queue job event. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @return void + */ + protected function raiseBeforeJobEvent(Job $job) + { + if ($this->container->bound('events')) { + $this->container['events']->dispatch(new JobProcessing($this->connectionName, $job)); + } + } + + /** + * Raise the after queue job event. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @return void + */ + protected function raiseAfterJobEvent(Job $job) + { + if ($this->container->bound('events')) { + $this->container['events']->dispatch(new JobProcessed($this->connectionName, $job)); + } + } + + /** + * Raise the exception occurred queue job event. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Throwable $e + * @return void + */ + protected function raiseExceptionOccurredJobEvent(Job $job, Throwable $e) + { + if ($this->container->bound('events')) { + $this->container['events']->dispatch(new JobExceptionOccurred($this->connectionName, $job, $e)); + } + } + + /** + * Handle an exception that occurred while processing a job. + * + * @param \Illuminate\Contracts\Queue\Job $queueJob + * @param \Throwable $e + * @return void + * + * @throws \Throwable + */ + protected function handleException(Job $queueJob, Throwable $e) + { + $this->raiseExceptionOccurredJobEvent($queueJob, $e); + + $queueJob->fail($e); + + throw $e; + } + + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + */ + public function pushRaw($payload, $queue = null, array $options = []) + { + // + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function later($delay, $job, $data = '', $queue = null) + { + return $this->push($job, $data, $queue); + } + + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + */ + public function pop($queue = null) + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Worker.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Worker.php new file mode 100644 index 0000000..a46a6f7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/Worker.php @@ -0,0 +1,832 @@ +events = $events; + $this->manager = $manager; + $this->exceptions = $exceptions; + $this->isDownForMaintenance = $isDownForMaintenance; + $this->resetScope = $resetScope; + } + + /** + * Listen to the given queue in a loop. + * + * @param string $connectionName + * @param string $queue + * @param \Illuminate\Queue\WorkerOptions $options + * @return int + */ + public function daemon($connectionName, $queue, WorkerOptions $options) + { + if ($supportsAsyncSignals = $this->supportsAsyncSignals()) { + $this->listenForSignals(); + } + + $lastRestart = $this->getTimestampOfLastQueueRestart(); + + [$startTime, $jobsProcessed] = [hrtime(true) / 1e9, 0]; + + while (true) { + // Before reserving any jobs, we will make sure this queue is not paused and + // if it is we will just pause this worker for a given amount of time and + // make sure we do not need to kill this worker process off completely. + if (! $this->daemonShouldRun($options, $connectionName, $queue)) { + $status = $this->pauseWorker($options, $lastRestart); + + if (! is_null($status)) { + return $this->stop($status); + } + + continue; + } + + if (isset($this->resetScope)) { + ($this->resetScope)(); + } + + // First, we will attempt to get the next job off of the queue. We will also + // register the timeout handler and reset the alarm for this job so it is + // not stuck in a frozen state forever. Then, we can fire off this job. + $job = $this->getNextJob( + $this->manager->connection($connectionName), $queue + ); + + if ($supportsAsyncSignals) { + $this->registerTimeoutHandler($job, $options); + } + + // If the daemon should run (not in maintenance mode, etc.), then we can run + // fire off this job for processing. Otherwise, we will need to sleep the + // worker so no more jobs are processed until they should be processed. + if ($job) { + $jobsProcessed++; + + $this->runJob($job, $connectionName, $options); + + if ($options->rest > 0) { + $this->sleep($options->rest); + } + } else { + $this->sleep($options->sleep); + } + + if ($supportsAsyncSignals) { + $this->resetTimeoutHandler(); + } + + // Finally, we will check to see if we have exceeded our memory limits or if + // the queue should restart based on other indications. If so, we'll stop + // this worker and let whatever is "monitoring" it restart the process. + $status = $this->stopIfNecessary( + $options, $lastRestart, $startTime, $jobsProcessed, $job + ); + + if (! is_null($status)) { + return $this->stop($status); + } + } + } + + /** + * Register the worker timeout handler. + * + * @param \Illuminate\Contracts\Queue\Job|null $job + * @param \Illuminate\Queue\WorkerOptions $options + * @return void + */ + protected function registerTimeoutHandler($job, WorkerOptions $options) + { + // We will register a signal handler for the alarm signal so that we can kill this + // process if it is running too long because it has frozen. This uses the async + // signals supported in recent versions of PHP to accomplish it conveniently. + pcntl_signal(SIGALRM, function () use ($job, $options) { + if ($job) { + $this->markJobAsFailedIfWillExceedMaxAttempts( + $job->getConnectionName(), $job, (int) $options->maxTries, $e = $this->maxAttemptsExceededException($job) + ); + + $this->markJobAsFailedIfWillExceedMaxExceptions( + $job->getConnectionName(), $job, $e + ); + + $this->markJobAsFailedIfItShouldFailOnTimeout( + $job->getConnectionName(), $job, $e + ); + } + + $this->kill(static::EXIT_ERROR); + }); + + pcntl_alarm( + max($this->timeoutForJob($job, $options), 0) + ); + } + + /** + * Reset the worker timeout handler. + * + * @return void + */ + protected function resetTimeoutHandler() + { + pcntl_alarm(0); + } + + /** + * Get the appropriate timeout for the given job. + * + * @param \Illuminate\Contracts\Queue\Job|null $job + * @param \Illuminate\Queue\WorkerOptions $options + * @return int + */ + protected function timeoutForJob($job, WorkerOptions $options) + { + return $job && ! is_null($job->timeout()) ? $job->timeout() : $options->timeout; + } + + /** + * Determine if the daemon should process on this iteration. + * + * @param \Illuminate\Queue\WorkerOptions $options + * @param string $connectionName + * @param string $queue + * @return bool + */ + protected function daemonShouldRun(WorkerOptions $options, $connectionName, $queue) + { + return ! ((($this->isDownForMaintenance)() && ! $options->force) || + $this->paused || + $this->events->until(new Looping($connectionName, $queue)) === false); + } + + /** + * Pause the worker for the current loop. + * + * @param \Illuminate\Queue\WorkerOptions $options + * @param int $lastRestart + * @return int|null + */ + protected function pauseWorker(WorkerOptions $options, $lastRestart) + { + $this->sleep($options->sleep > 0 ? $options->sleep : 1); + + return $this->stopIfNecessary($options, $lastRestart); + } + + /** + * Determine the exit code to stop the process if necessary. + * + * @param \Illuminate\Queue\WorkerOptions $options + * @param int $lastRestart + * @param int $startTime + * @param int $jobsProcessed + * @param mixed $job + * @return int|null + */ + protected function stopIfNecessary(WorkerOptions $options, $lastRestart, $startTime = 0, $jobsProcessed = 0, $job = null) + { + if ($this->shouldQuit) { + return static::EXIT_SUCCESS; + } elseif ($this->memoryExceeded($options->memory)) { + return static::EXIT_MEMORY_LIMIT; + } elseif ($this->queueShouldRestart($lastRestart)) { + return static::EXIT_SUCCESS; + } elseif ($options->stopWhenEmpty && is_null($job)) { + return static::EXIT_SUCCESS; + } elseif ($options->maxTime && hrtime(true) / 1e9 - $startTime >= $options->maxTime) { + return static::EXIT_SUCCESS; + } elseif ($options->maxJobs && $jobsProcessed >= $options->maxJobs) { + return static::EXIT_SUCCESS; + } + } + + /** + * Process the next job on the queue. + * + * @param string $connectionName + * @param string $queue + * @param \Illuminate\Queue\WorkerOptions $options + * @return void + */ + public function runNextJob($connectionName, $queue, WorkerOptions $options) + { + $job = $this->getNextJob( + $this->manager->connection($connectionName), $queue + ); + + // If we're able to pull a job off of the stack, we will process it and then return + // from this method. If there is no job on the queue, we will "sleep" the worker + // for the specified number of seconds, then keep processing jobs after sleep. + if ($job) { + return $this->runJob($job, $connectionName, $options); + } + + $this->sleep($options->sleep); + } + + /** + * Get the next job from the queue connection. + * + * @param \Illuminate\Contracts\Queue\Queue $connection + * @param string $queue + * @return \Illuminate\Contracts\Queue\Job|null + */ + protected function getNextJob($connection, $queue) + { + $popJobCallback = function ($queue) use ($connection) { + return $connection->pop($queue); + }; + + try { + if (isset(static::$popCallbacks[$this->name])) { + return (static::$popCallbacks[$this->name])($popJobCallback, $queue); + } + + foreach (explode(',', $queue) as $queue) { + if (! is_null($job = $popJobCallback($queue))) { + return $job; + } + } + } catch (Throwable $e) { + $this->exceptions->report($e); + + $this->stopWorkerIfLostConnection($e); + + $this->sleep(1); + } + } + + /** + * Process the given job. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param string $connectionName + * @param \Illuminate\Queue\WorkerOptions $options + * @return void + */ + protected function runJob($job, $connectionName, WorkerOptions $options) + { + try { + return $this->process($connectionName, $job, $options); + } catch (Throwable $e) { + $this->exceptions->report($e); + + $this->stopWorkerIfLostConnection($e); + } + } + + /** + * Stop the worker if we have lost connection to a database. + * + * @param \Throwable $e + * @return void + */ + protected function stopWorkerIfLostConnection($e) + { + if ($this->causedByLostConnection($e)) { + $this->shouldQuit = true; + } + } + + /** + * Process the given job from the queue. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Illuminate\Queue\WorkerOptions $options + * @return void + * + * @throws \Throwable + */ + public function process($connectionName, $job, WorkerOptions $options) + { + try { + // First we will raise the before job event and determine if the job has already ran + // over its maximum attempt limits, which could primarily happen when this job is + // continually timing out and not actually throwing any exceptions from itself. + $this->raiseBeforeJobEvent($connectionName, $job); + + $this->markJobAsFailedIfAlreadyExceedsMaxAttempts( + $connectionName, $job, (int) $options->maxTries + ); + + if ($job->isDeleted()) { + return $this->raiseAfterJobEvent($connectionName, $job); + } + + // Here we will fire off the job and let it process. We will catch any exceptions so + // they can be reported to the developers logs, etc. Once the job is finished the + // proper events will be fired to let any listeners know this job has finished. + $job->fire(); + + $this->raiseAfterJobEvent($connectionName, $job); + } catch (Throwable $e) { + $this->handleJobException($connectionName, $job, $options, $e); + } + } + + /** + * Handle an exception that occurred while the job was running. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Illuminate\Queue\WorkerOptions $options + * @param \Throwable $e + * @return void + * + * @throws \Throwable + */ + protected function handleJobException($connectionName, $job, WorkerOptions $options, Throwable $e) + { + try { + // First, we will go ahead and mark the job as failed if it will exceed the maximum + // attempts it is allowed to run the next time we process it. If so we will just + // go ahead and mark it as failed now so we do not have to release this again. + if (! $job->hasFailed()) { + $this->markJobAsFailedIfWillExceedMaxAttempts( + $connectionName, $job, (int) $options->maxTries, $e + ); + + $this->markJobAsFailedIfWillExceedMaxExceptions( + $connectionName, $job, $e + ); + } + + $this->raiseExceptionOccurredJobEvent( + $connectionName, $job, $e + ); + } finally { + // If we catch an exception, we will attempt to release the job back onto the queue + // so it is not lost entirely. This'll let the job be retried at a later time by + // another listener (or this same one). We will re-throw this exception after. + if (! $job->isDeleted() && ! $job->isReleased() && ! $job->hasFailed()) { + $job->release($this->calculateBackoff($job, $options)); + } + } + + throw $e; + } + + /** + * Mark the given job as failed if it has exceeded the maximum allowed attempts. + * + * This will likely be because the job previously exceeded a timeout. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param int $maxTries + * @return void + * + * @throws \Throwable + */ + protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $job, $maxTries) + { + $maxTries = ! is_null($job->maxTries()) ? $job->maxTries() : $maxTries; + + $retryUntil = $job->retryUntil(); + + if ($retryUntil && Carbon::now()->getTimestamp() <= $retryUntil) { + return; + } + + if (! $retryUntil && ($maxTries === 0 || $job->attempts() <= $maxTries)) { + return; + } + + $this->failJob($job, $e = $this->maxAttemptsExceededException($job)); + + throw $e; + } + + /** + * Mark the given job as failed if it has exceeded the maximum allowed attempts. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param int $maxTries + * @param \Throwable $e + * @return void + */ + protected function markJobAsFailedIfWillExceedMaxAttempts($connectionName, $job, $maxTries, Throwable $e) + { + $maxTries = ! is_null($job->maxTries()) ? $job->maxTries() : $maxTries; + + if ($job->retryUntil() && $job->retryUntil() <= Carbon::now()->getTimestamp()) { + $this->failJob($job, $e); + } + + if (! $job->retryUntil() && $maxTries > 0 && $job->attempts() >= $maxTries) { + $this->failJob($job, $e); + } + } + + /** + * Mark the given job as failed if it has exceeded the maximum allowed attempts. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Throwable $e + * @return void + */ + protected function markJobAsFailedIfWillExceedMaxExceptions($connectionName, $job, Throwable $e) + { + if (! $this->cache || is_null($uuid = $job->uuid()) || + is_null($maxExceptions = $job->maxExceptions())) { + return; + } + + if (! $this->cache->get('job-exceptions:'.$uuid)) { + $this->cache->put('job-exceptions:'.$uuid, 0, Carbon::now()->addDay()); + } + + if ($maxExceptions <= $this->cache->increment('job-exceptions:'.$uuid)) { + $this->cache->forget('job-exceptions:'.$uuid); + + $this->failJob($job, $e); + } + } + + /** + * Mark the given job as failed if it should fail on timeouts. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Throwable $e + * @return void + */ + protected function markJobAsFailedIfItShouldFailOnTimeout($connectionName, $job, Throwable $e) + { + if (method_exists($job, 'shouldFailOnTimeout') ? $job->shouldFailOnTimeout() : false) { + $this->failJob($job, $e); + } + } + + /** + * Mark the given job as failed and raise the relevant event. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Throwable $e + * @return void + */ + protected function failJob($job, Throwable $e) + { + return $job->fail($e); + } + + /** + * Calculate the backoff for the given job. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Illuminate\Queue\WorkerOptions $options + * @return int + */ + protected function calculateBackoff($job, WorkerOptions $options) + { + $backoff = explode( + ',', + method_exists($job, 'backoff') && ! is_null($job->backoff()) + ? $job->backoff() + : $options->backoff + ); + + return (int) ($backoff[$job->attempts() - 1] ?? last($backoff)); + } + + /** + * Raise the before queue job event. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @return void + */ + protected function raiseBeforeJobEvent($connectionName, $job) + { + $this->events->dispatch(new JobProcessing( + $connectionName, $job + )); + } + + /** + * Raise the after queue job event. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @return void + */ + protected function raiseAfterJobEvent($connectionName, $job) + { + $this->events->dispatch(new JobProcessed( + $connectionName, $job + )); + } + + /** + * Raise the exception occurred queue job event. + * + * @param string $connectionName + * @param \Illuminate\Contracts\Queue\Job $job + * @param \Throwable $e + * @return void + */ + protected function raiseExceptionOccurredJobEvent($connectionName, $job, Throwable $e) + { + $this->events->dispatch(new JobExceptionOccurred( + $connectionName, $job, $e + )); + } + + /** + * Determine if the queue worker should restart. + * + * @param int|null $lastRestart + * @return bool + */ + protected function queueShouldRestart($lastRestart) + { + return $this->getTimestampOfLastQueueRestart() != $lastRestart; + } + + /** + * Get the last queue restart timestamp, or null. + * + * @return int|null + */ + protected function getTimestampOfLastQueueRestart() + { + if ($this->cache) { + return $this->cache->get('illuminate:queue:restart'); + } + } + + /** + * Enable async signals for the process. + * + * @return void + */ + protected function listenForSignals() + { + pcntl_async_signals(true); + + pcntl_signal(SIGTERM, function () { + $this->shouldQuit = true; + }); + + pcntl_signal(SIGUSR2, function () { + $this->paused = true; + }); + + pcntl_signal(SIGCONT, function () { + $this->paused = false; + }); + } + + /** + * Determine if "async" signals are supported. + * + * @return bool + */ + protected function supportsAsyncSignals() + { + return extension_loaded('pcntl'); + } + + /** + * Determine if the memory limit has been exceeded. + * + * @param int $memoryLimit + * @return bool + */ + public function memoryExceeded($memoryLimit) + { + return (memory_get_usage(true) / 1024 / 1024) >= $memoryLimit; + } + + /** + * Stop listening and bail out of the script. + * + * @param int $status + * @return int + */ + public function stop($status = 0) + { + $this->events->dispatch(new WorkerStopping($status)); + + return $status; + } + + /** + * Kill the process. + * + * @param int $status + * @return never + */ + public function kill($status = 0) + { + $this->events->dispatch(new WorkerStopping($status)); + + if (extension_loaded('posix')) { + posix_kill(getmypid(), SIGKILL); + } + + exit($status); + } + + /** + * Create an instance of MaxAttemptsExceededException. + * + * @param \Illuminate\Contracts\Queue\Job $job + * @return \Illuminate\Queue\MaxAttemptsExceededException + */ + protected function maxAttemptsExceededException($job) + { + return new MaxAttemptsExceededException( + $job->resolveName().' has been attempted too many times or run too long. The job may have previously timed out.' + ); + } + + /** + * Sleep the script for a given number of seconds. + * + * @param int|float $seconds + * @return void + */ + public function sleep($seconds) + { + if ($seconds < 1) { + usleep($seconds * 1000000); + } else { + sleep($seconds); + } + } + + /** + * Set the cache repository implementation. + * + * @param \Illuminate\Contracts\Cache\Repository $cache + * @return $this + */ + public function setCache(CacheContract $cache) + { + $this->cache = $cache; + + return $this; + } + + /** + * Set the name of the worker. + * + * @param string $name + * @return $this + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Register a callback to be executed to pick jobs. + * + * @param string $workerName + * @param callable $callback + * @return void + */ + public static function popUsing($workerName, $callback) + { + if (is_null($callback)) { + unset(static::$popCallbacks[$workerName]); + } else { + static::$popCallbacks[$workerName] = $callback; + } + } + + /** + * Get the queue manager instance. + * + * @return \Illuminate\Queue\QueueManager + */ + public function getManager() + { + return $this->manager; + } + + /** + * Set the queue manager instance. + * + * @param \Illuminate\Contracts\Queue\Factory $manager + * @return void + */ + public function setManager(QueueManager $manager) + { + $this->manager = $manager; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/WorkerOptions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/WorkerOptions.php new file mode 100644 index 0000000..7b8d8df --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/WorkerOptions.php @@ -0,0 +1,115 @@ +name = $name; + $this->backoff = $backoff; + $this->sleep = $sleep; + $this->rest = $rest; + $this->force = $force; + $this->memory = $memory; + $this->timeout = $timeout; + $this->maxTries = $maxTries; + $this->stopWhenEmpty = $stopWhenEmpty; + $this->maxJobs = $maxJobs; + $this->maxTime = $maxTime; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/composer.json new file mode 100644 index 0000000..6c43b18 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Queue/composer.json @@ -0,0 +1,53 @@ +{ + "name": "illuminate/queue", + "description": "The Illuminate Queue package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/console": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/database": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/pipeline": "^8.0", + "illuminate/support": "^8.0", + "laravel/serializable-closure": "^1.0", + "opis/closure": "^3.6", + "ramsey/uuid": "^4.2.2", + "symfony/process": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Queue\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "ext-pcntl": "Required to use all features of the queue worker.", + "ext-posix": "Required to use all features of the queue worker.", + "aws/aws-sdk-php": "Required to use the SQS queue driver and DynamoDb failed job storage (^3.198.1).", + "illuminate/redis": "Required to use the Redis queue driver (^8.0).", + "pda/pheanstalk": "Required to use the Beanstalk queue driver (^4.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php new file mode 100644 index 0000000..95af91e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php @@ -0,0 +1,222 @@ +client; + } + + /** + * Subscribe to a set of given channels for messages. + * + * @param array|string $channels + * @param \Closure $callback + * @return void + */ + public function subscribe($channels, Closure $callback) + { + return $this->createSubscription($channels, $callback, __FUNCTION__); + } + + /** + * Subscribe to a set of given channels with wildcards. + * + * @param array|string $channels + * @param \Closure $callback + * @return void + */ + public function psubscribe($channels, Closure $callback) + { + return $this->createSubscription($channels, $callback, __FUNCTION__); + } + + /** + * Run a command against the Redis database. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function command($method, array $parameters = []) + { + $start = microtime(true); + + $result = $this->client->{$method}(...$parameters); + + $time = round((microtime(true) - $start) * 1000, 2); + + if (isset($this->events)) { + $this->event(new CommandExecuted($method, $parameters, $time, $this)); + } + + return $result; + } + + /** + * Fire the given event if possible. + * + * @param mixed $event + * @return void + */ + protected function event($event) + { + if (isset($this->events)) { + $this->events->dispatch($event); + } + } + + /** + * Register a Redis command listener with the connection. + * + * @param \Closure $callback + * @return void + */ + public function listen(Closure $callback) + { + if (isset($this->events)) { + $this->events->listen(CommandExecuted::class, $callback); + } + } + + /** + * Get the connection name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Set the connections name. + * + * @param string $name + * @return $this + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Get the event dispatcher used by the connection. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public function getEventDispatcher() + { + return $this->events; + } + + /** + * Set the event dispatcher instance on the connection. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + */ + public function setEventDispatcher(Dispatcher $events) + { + $this->events = $events; + } + + /** + * Unset the event dispatcher instance on the connection. + * + * @return void + */ + public function unsetEventDispatcher() + { + $this->events = null; + } + + /** + * Pass other method calls down to the underlying client. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + return $this->command($method, $parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PacksPhpRedisValues.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PacksPhpRedisValues.php new file mode 100644 index 0000000..4d27ff5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PacksPhpRedisValues.php @@ -0,0 +1,183 @@ + $values + * @return array + */ + public function pack(array $values): array + { + if (empty($values)) { + return $values; + } + + if ($this->supportsPacking()) { + return array_map([$this->client, '_pack'], $values); + } + + if ($this->compressed()) { + if ($this->supportsLzf() && $this->lzfCompressed()) { + if (! function_exists('lzf_compress')) { + throw new RuntimeException("'lzf' extension required to call 'lzf_compress'."); + } + + $processor = function ($value) { + return \lzf_compress($this->client->_serialize($value)); + }; + } elseif ($this->supportsZstd() && $this->zstdCompressed()) { + if (! function_exists('zstd_compress')) { + throw new RuntimeException("'zstd' extension required to call 'zstd_compress'."); + } + + $compressionLevel = $this->client->getOption(Redis::OPT_COMPRESSION_LEVEL); + + $processor = function ($value) use ($compressionLevel) { + return \zstd_compress( + $this->client->_serialize($value), + $compressionLevel === 0 ? Redis::COMPRESSION_ZSTD_DEFAULT : $compressionLevel + ); + }; + } else { + throw new UnexpectedValueException(sprintf( + 'Unsupported phpredis compression in use [%d].', + $this->client->getOption(Redis::OPT_COMPRESSION) + )); + } + } else { + $processor = function ($value) { + return $this->client->_serialize($value); + }; + } + + return array_map($processor, $values); + } + + /** + * Determine if compression is enabled. + * + * @return bool + */ + public function compressed(): bool + { + return defined('Redis::OPT_COMPRESSION') && + $this->client->getOption(Redis::OPT_COMPRESSION) !== Redis::COMPRESSION_NONE; + } + + /** + * Determine if LZF compression is enabled. + * + * @return bool + */ + public function lzfCompressed(): bool + { + return defined('Redis::COMPRESSION_LZF') && + $this->client->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_LZF; + } + + /** + * Determine if ZSTD compression is enabled. + * + * @return bool + */ + public function zstdCompressed(): bool + { + return defined('Redis::COMPRESSION_ZSTD') && + $this->client->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_ZSTD; + } + + /** + * Determine if LZ4 compression is enabled. + * + * @return bool + */ + public function lz4Compressed(): bool + { + return defined('Redis::COMPRESSION_LZ4') && + $this->client->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_LZ4; + } + + /** + * Determine if the current PhpRedis extension version supports packing. + * + * @return bool + */ + protected function supportsPacking(): bool + { + if ($this->supportsPacking === null) { + $this->supportsPacking = $this->phpRedisVersionAtLeast('5.3.5'); + } + + return $this->supportsPacking; + } + + /** + * Determine if the current PhpRedis extension version supports LZF compression. + * + * @return bool + */ + protected function supportsLzf(): bool + { + if ($this->supportsLzf === null) { + $this->supportsLzf = $this->phpRedisVersionAtLeast('4.3.0'); + } + + return $this->supportsLzf; + } + + /** + * Determine if the current PhpRedis extension version supports Zstd compression. + * + * @return bool + */ + protected function supportsZstd(): bool + { + if ($this->supportsZstd === null) { + $this->supportsZstd = $this->phpRedisVersionAtLeast('5.1.0'); + } + + return $this->supportsZstd; + } + + /** + * Determine if the PhpRedis extension version is at least the given version. + * + * @param string $version + * @return bool + */ + protected function phpRedisVersionAtLeast(string $version): bool + { + $phpredisVersion = phpversion('redis'); + + return $phpredisVersion !== false && version_compare($phpredisVersion, $version, '>='); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisClusterConnection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisClusterConnection.php new file mode 100644 index 0000000..bf4816a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisClusterConnection.php @@ -0,0 +1,24 @@ +client->_masters() as $master) { + $async + ? $this->command('rawCommand', [$master, 'flushdb', 'async']) + : $this->command('flushdb', [$master]); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisConnection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisConnection.php new file mode 100644 index 0000000..4e68547 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisConnection.php @@ -0,0 +1,577 @@ +client = $client; + $this->config = $config; + $this->connector = $connector; + } + + /** + * Returns the value of the given key. + * + * @param string $key + * @return string|null + */ + public function get($key) + { + $result = $this->command('get', [$key]); + + return $result !== false ? $result : null; + } + + /** + * Get the values of all the given keys. + * + * @param array $keys + * @return array + */ + public function mget(array $keys) + { + return array_map(function ($value) { + return $value !== false ? $value : null; + }, $this->command('mget', [$keys])); + } + + /** + * Set the string value in the argument as the value of the key. + * + * @param string $key + * @param mixed $value + * @param string|null $expireResolution + * @param int|null $expireTTL + * @param string|null $flag + * @return bool + */ + public function set($key, $value, $expireResolution = null, $expireTTL = null, $flag = null) + { + return $this->command('set', [ + $key, + $value, + $expireResolution ? [$flag, $expireResolution => $expireTTL] : null, + ]); + } + + /** + * Set the given key if it doesn't exist. + * + * @param string $key + * @param string $value + * @return int + */ + public function setnx($key, $value) + { + return (int) $this->command('setnx', [$key, $value]); + } + + /** + * Get the value of the given hash fields. + * + * @param string $key + * @param mixed $dictionary + * @return array + */ + public function hmget($key, ...$dictionary) + { + if (count($dictionary) === 1) { + $dictionary = $dictionary[0]; + } + + return array_values($this->command('hmget', [$key, $dictionary])); + } + + /** + * Set the given hash fields to their respective values. + * + * @param string $key + * @param mixed $dictionary + * @return int + */ + public function hmset($key, ...$dictionary) + { + if (count($dictionary) === 1) { + $dictionary = $dictionary[0]; + } else { + $input = collect($dictionary); + + $dictionary = $input->nth(2)->combine($input->nth(2, 1))->toArray(); + } + + return $this->command('hmset', [$key, $dictionary]); + } + + /** + * Set the given hash field if it doesn't exist. + * + * @param string $hash + * @param string $key + * @param string $value + * @return int + */ + public function hsetnx($hash, $key, $value) + { + return (int) $this->command('hsetnx', [$hash, $key, $value]); + } + + /** + * Removes the first count occurrences of the value element from the list. + * + * @param string $key + * @param int $count + * @param mixed $value + * @return int|false + */ + public function lrem($key, $count, $value) + { + return $this->command('lrem', [$key, $value, $count]); + } + + /** + * Removes and returns the first element of the list stored at key. + * + * @param mixed $arguments + * @return array|null + */ + public function blpop(...$arguments) + { + $result = $this->command('blpop', $arguments); + + return empty($result) ? null : $result; + } + + /** + * Removes and returns the last element of the list stored at key. + * + * @param mixed $arguments + * @return array|null + */ + public function brpop(...$arguments) + { + $result = $this->command('brpop', $arguments); + + return empty($result) ? null : $result; + } + + /** + * Removes and returns a random element from the set value at key. + * + * @param string $key + * @param int|null $count + * @return mixed|false + */ + public function spop($key, $count = 1) + { + return $this->command('spop', func_get_args()); + } + + /** + * Add one or more members to a sorted set or update its score if it already exists. + * + * @param string $key + * @param mixed $dictionary + * @return int + */ + public function zadd($key, ...$dictionary) + { + if (is_array(end($dictionary))) { + foreach (array_pop($dictionary) as $member => $score) { + $dictionary[] = $score; + $dictionary[] = $member; + } + } + + $options = []; + + foreach (array_slice($dictionary, 0, 3) as $i => $value) { + if (in_array($value, ['nx', 'xx', 'ch', 'incr', 'gt', 'lt', 'NX', 'XX', 'CH', 'INCR', 'GT', 'LT'], true)) { + $options[] = $value; + + unset($dictionary[$i]); + } + } + + return $this->command('zadd', array_merge([$key], [$options], array_values($dictionary))); + } + + /** + * Return elements with score between $min and $max. + * + * @param string $key + * @param mixed $min + * @param mixed $max + * @param array $options + * @return array + */ + public function zrangebyscore($key, $min, $max, $options = []) + { + if (isset($options['limit']) && Arr::isAssoc($options['limit'])) { + $options['limit'] = [ + $options['limit']['offset'], + $options['limit']['count'], + ]; + } + + return $this->command('zRangeByScore', [$key, $min, $max, $options]); + } + + /** + * Return elements with score between $min and $max. + * + * @param string $key + * @param mixed $min + * @param mixed $max + * @param array $options + * @return array + */ + public function zrevrangebyscore($key, $min, $max, $options = []) + { + if (isset($options['limit']) && Arr::isAssoc($options['limit'])) { + $options['limit'] = [ + $options['limit']['offset'], + $options['limit']['count'], + ]; + } + + return $this->command('zRevRangeByScore', [$key, $min, $max, $options]); + } + + /** + * Find the intersection between sets and store in a new set. + * + * @param string $output + * @param array $keys + * @param array $options + * @return int + */ + public function zinterstore($output, $keys, $options = []) + { + return $this->command('zinterstore', [$output, $keys, + $options['weights'] ?? null, + $options['aggregate'] ?? 'sum', + ]); + } + + /** + * Find the union between sets and store in a new set. + * + * @param string $output + * @param array $keys + * @param array $options + * @return int + */ + public function zunionstore($output, $keys, $options = []) + { + return $this->command('zunionstore', [$output, $keys, + $options['weights'] ?? null, + $options['aggregate'] ?? 'sum', + ]); + } + + /** + * Scans all keys based on options. + * + * @param mixed $cursor + * @param array $options + * @return mixed + */ + public function scan($cursor, $options = []) + { + $result = $this->client->scan($cursor, + $options['match'] ?? '*', + $options['count'] ?? 10 + ); + + if ($result === false) { + $result = []; + } + + return $cursor === 0 && empty($result) ? false : [$cursor, $result]; + } + + /** + * Scans the given set for all values based on options. + * + * @param string $key + * @param mixed $cursor + * @param array $options + * @return mixed + */ + public function zscan($key, $cursor, $options = []) + { + $result = $this->client->zscan($key, $cursor, + $options['match'] ?? '*', + $options['count'] ?? 10 + ); + + if ($result === false) { + $result = []; + } + + return $cursor === 0 && empty($result) ? false : [$cursor, $result]; + } + + /** + * Scans the given hash for all values based on options. + * + * @param string $key + * @param mixed $cursor + * @param array $options + * @return mixed + */ + public function hscan($key, $cursor, $options = []) + { + $result = $this->client->hscan($key, $cursor, + $options['match'] ?? '*', + $options['count'] ?? 10 + ); + + if ($result === false) { + $result = []; + } + + return $cursor === 0 && empty($result) ? false : [$cursor, $result]; + } + + /** + * Scans the given set for all values based on options. + * + * @param string $key + * @param mixed $cursor + * @param array $options + * @return mixed + */ + public function sscan($key, $cursor, $options = []) + { + $result = $this->client->sscan($key, $cursor, + $options['match'] ?? '*', + $options['count'] ?? 10 + ); + + if ($result === false) { + $result = []; + } + + return $cursor === 0 && empty($result) ? false : [$cursor, $result]; + } + + /** + * Execute commands in a pipeline. + * + * @param callable|null $callback + * @return \Redis|array + */ + public function pipeline(callable $callback = null) + { + $pipeline = $this->client()->pipeline(); + + return is_null($callback) + ? $pipeline + : tap($pipeline, $callback)->exec(); + } + + /** + * Execute commands in a transaction. + * + * @param callable|null $callback + * @return \Redis|array + */ + public function transaction(callable $callback = null) + { + $transaction = $this->client()->multi(); + + return is_null($callback) + ? $transaction + : tap($transaction, $callback)->exec(); + } + + /** + * Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself. + * + * @param string $script + * @param int $numkeys + * @param mixed $arguments + * @return mixed + */ + public function evalsha($script, $numkeys, ...$arguments) + { + return $this->command('evalsha', [ + $this->script('load', $script), $arguments, $numkeys, + ]); + } + + /** + * Evaluate a script and return its result. + * + * @param string $script + * @param int $numberOfKeys + * @param dynamic $arguments + * @return mixed + */ + public function eval($script, $numberOfKeys, ...$arguments) + { + return $this->command('eval', [$script, $arguments, $numberOfKeys]); + } + + /** + * Subscribe to a set of given channels for messages. + * + * @param array|string $channels + * @param \Closure $callback + * @return void + */ + public function subscribe($channels, Closure $callback) + { + $this->client->subscribe((array) $channels, function ($redis, $channel, $message) use ($callback) { + $callback($message, $channel); + }); + } + + /** + * Subscribe to a set of given channels with wildcards. + * + * @param array|string $channels + * @param \Closure $callback + * @return void + */ + public function psubscribe($channels, Closure $callback) + { + $this->client->psubscribe((array) $channels, function ($redis, $pattern, $channel, $message) use ($callback) { + $callback($message, $channel); + }); + } + + /** + * Subscribe to a set of given channels for messages. + * + * @param array|string $channels + * @param \Closure $callback + * @param string $method + * @return void + */ + public function createSubscription($channels, Closure $callback, $method = 'subscribe') + { + // + } + + /** + * Flush the selected Redis database. + * + * @return mixed + */ + public function flushdb() + { + $arguments = func_get_args(); + + if (strtoupper((string) ($arguments[0] ?? null)) === 'ASYNC') { + return $this->command('flushdb', [true]); + } + + return $this->command('flushdb'); + } + + /** + * Execute a raw command. + * + * @param array $parameters + * @return mixed + */ + public function executeRaw(array $parameters) + { + return $this->command('rawCommand', $parameters); + } + + /** + * Run a command against the Redis database. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \RedisException + */ + public function command($method, array $parameters = []) + { + try { + return parent::command($method, $parameters); + } catch (RedisException $e) { + if (Str::contains($e->getMessage(), 'went away')) { + $this->client = $this->connector ? call_user_func($this->connector) : $this->client; + } + + throw $e; + } + } + + /** + * Disconnects from the Redis instance. + * + * @return void + */ + public function disconnect() + { + $this->client->close(); + } + + /** + * Apply a prefix to the given key if necessary. + * + * @param string $key + * @return string + */ + private function applyPrefix($key) + { + $prefix = (string) $this->client->getOption(Redis::OPT_PREFIX); + + return $prefix.$key; + } + + /** + * Pass other method calls down to the underlying client. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return parent::__call(strtolower($method), $parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PredisClusterConnection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PredisClusterConnection.php new file mode 100644 index 0000000..6d07de1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PredisClusterConnection.php @@ -0,0 +1,20 @@ +client->executeCommandOnNodes( + tap(new ServerFlushDatabase)->setArguments(func_get_args()) + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PredisConnection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PredisConnection.php new file mode 100644 index 0000000..e0a8be0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connections/PredisConnection.php @@ -0,0 +1,53 @@ +client = $client; + } + + /** + * Subscribe to a set of given channels for messages. + * + * @param array|string $channels + * @param \Closure $callback + * @param string $method + * @return void + */ + public function createSubscription($channels, Closure $callback, $method = 'subscribe') + { + $loop = $this->pubSubLoop(); + + $loop->{$method}(...array_values((array) $channels)); + + foreach ($loop as $message) { + if ($message->kind === 'message' || $message->kind === 'pmessage') { + call_user_func($callback, $message->payload, $message->channel); + } + } + + unset($loop); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php new file mode 100644 index 0000000..1c48bdf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php @@ -0,0 +1,228 @@ +createClient(array_merge( + $config, $options, Arr::pull($config, 'options', []) + )); + }; + + return new PhpRedisConnection($connector(), $connector, $config); + } + + /** + * Create a new clustered PhpRedis connection. + * + * @param array $config + * @param array $clusterOptions + * @param array $options + * @return \Illuminate\Redis\Connections\PhpRedisClusterConnection + */ + public function connectToCluster(array $config, array $clusterOptions, array $options) + { + $options = array_merge($options, $clusterOptions, Arr::pull($config, 'options', [])); + + return new PhpRedisClusterConnection($this->createRedisClusterInstance( + array_map([$this, 'buildClusterConnectionString'], $config), $options + )); + } + + /** + * Build a single cluster seed string from an array. + * + * @param array $server + * @return string + */ + protected function buildClusterConnectionString(array $server) + { + return $this->formatHost($server).':'.$server['port'].'?'.Arr::query(Arr::only($server, [ + 'database', 'password', 'prefix', 'read_timeout', + ])); + } + + /** + * Create the Redis client instance. + * + * @param array $config + * @return \Redis + * + * @throws \LogicException + */ + protected function createClient(array $config) + { + return tap(new Redis, function ($client) use ($config) { + if ($client instanceof RedisFacade) { + throw new LogicException( + extension_loaded('redis') + ? 'Please remove or rename the Redis facade alias in your "app" configuration file in order to avoid collision with the PHP Redis extension.' + : 'Please make sure the PHP Redis extension is installed and enabled.' + ); + } + + $this->establishConnection($client, $config); + + if (! empty($config['password'])) { + $client->auth($config['password']); + } + + if (isset($config['database'])) { + $client->select((int) $config['database']); + } + + if (! empty($config['prefix'])) { + $client->setOption(Redis::OPT_PREFIX, $config['prefix']); + } + + if (! empty($config['read_timeout'])) { + $client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']); + } + + if (! empty($config['scan'])) { + $client->setOption(Redis::OPT_SCAN, $config['scan']); + } + + if (! empty($config['name'])) { + $client->client('SETNAME', $config['name']); + } + + if (array_key_exists('serializer', $config)) { + $client->setOption(Redis::OPT_SERIALIZER, $config['serializer']); + } + + if (array_key_exists('compression', $config)) { + $client->setOption(Redis::OPT_COMPRESSION, $config['compression']); + } + + if (array_key_exists('compression_level', $config)) { + $client->setOption(Redis::OPT_COMPRESSION_LEVEL, $config['compression_level']); + } + }); + } + + /** + * Establish a connection with the Redis host. + * + * @param \Redis $client + * @param array $config + * @return void + */ + protected function establishConnection($client, array $config) + { + $persistent = $config['persistent'] ?? false; + + $parameters = [ + $this->formatHost($config), + $config['port'], + Arr::get($config, 'timeout', 0.0), + $persistent ? Arr::get($config, 'persistent_id', null) : null, + Arr::get($config, 'retry_interval', 0), + ]; + + if (version_compare(phpversion('redis'), '3.1.3', '>=')) { + $parameters[] = Arr::get($config, 'read_timeout', 0.0); + } + + if (version_compare(phpversion('redis'), '5.3.0', '>=')) { + if (! is_null($context = Arr::get($config, 'context'))) { + $parameters[] = $context; + } + } + + $client->{($persistent ? 'pconnect' : 'connect')}(...$parameters); + } + + /** + * Create a new redis cluster instance. + * + * @param array $servers + * @param array $options + * @return \RedisCluster + */ + protected function createRedisClusterInstance(array $servers, array $options) + { + $parameters = [ + null, + array_values($servers), + $options['timeout'] ?? 0, + $options['read_timeout'] ?? 0, + isset($options['persistent']) && $options['persistent'], + ]; + + if (version_compare(phpversion('redis'), '4.3.0', '>=')) { + $parameters[] = $options['password'] ?? null; + } + + if (version_compare(phpversion('redis'), '5.3.2', '>=')) { + if (! is_null($context = Arr::get($options, 'context'))) { + $parameters[] = $context; + } + } + + return tap(new RedisCluster(...$parameters), function ($client) use ($options) { + if (! empty($options['prefix'])) { + $client->setOption(RedisCluster::OPT_PREFIX, $options['prefix']); + } + + if (! empty($options['scan'])) { + $client->setOption(RedisCluster::OPT_SCAN, $options['scan']); + } + + if (! empty($options['failover'])) { + $client->setOption(RedisCluster::OPT_SLAVE_FAILOVER, $options['failover']); + } + + if (! empty($options['name'])) { + $client->client('SETNAME', $options['name']); + } + + if (array_key_exists('serializer', $options)) { + $client->setOption(RedisCluster::OPT_SERIALIZER, $options['serializer']); + } + + if (array_key_exists('compression', $options)) { + $client->setOption(RedisCluster::OPT_COMPRESSION, $options['compression']); + } + + if (array_key_exists('compression_level', $options)) { + $client->setOption(RedisCluster::OPT_COMPRESSION_LEVEL, $options['compression_level']); + } + }); + } + + /** + * Format the host using the scheme if available. + * + * @param array $options + * @return string + */ + protected function formatHost(array $options) + { + if (isset($options['scheme'])) { + return Str::start($options['host'], "{$options['scheme']}://"); + } + + return $options['host']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PredisConnector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PredisConnector.php new file mode 100644 index 0000000..6222a4b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PredisConnector.php @@ -0,0 +1,53 @@ + 10.0], $options, Arr::pull($config, 'options', []) + ); + + if (isset($config['prefix'])) { + $formattedOptions['prefix'] = $config['prefix']; + } + + return new PredisConnection(new Client($config, $formattedOptions)); + } + + /** + * Create a new clustered Predis connection. + * + * @param array $config + * @param array $clusterOptions + * @param array $options + * @return \Illuminate\Redis\Connections\PredisClusterConnection + */ + public function connectToCluster(array $config, array $clusterOptions, array $options) + { + $clusterSpecificOptions = Arr::pull($config, 'options', []); + + if (isset($config['prefix'])) { + $clusterSpecificOptions['prefix'] = $config['prefix']; + } + + return new PredisClusterConnection(new Client(array_values($config), array_merge( + $options, $clusterOptions, $clusterSpecificOptions + ))); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Events/CommandExecuted.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Events/CommandExecuted.php new file mode 100644 index 0000000..fa65719 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Events/CommandExecuted.php @@ -0,0 +1,59 @@ +time = $time; + $this->command = $command; + $this->parameters = $parameters; + $this->connection = $connection; + $this->connectionName = $connection->getName(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php new file mode 100644 index 0000000..5fcc921 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php @@ -0,0 +1,166 @@ +name = $name; + $this->redis = $redis; + $this->maxLocks = $maxLocks; + $this->releaseAfter = $releaseAfter; + } + + /** + * Attempt to acquire the lock for the given number of seconds. + * + * @param int $timeout + * @param callable|null $callback + * @return bool + * + * @throws \Illuminate\Contracts\Redis\LimiterTimeoutException + * @throws \Throwable + */ + public function block($timeout, $callback = null) + { + $starting = time(); + + $id = Str::random(20); + + while (! $slot = $this->acquire($id)) { + if (time() - $timeout >= $starting) { + throw new LimiterTimeoutException; + } + + usleep(250 * 1000); + } + + if (is_callable($callback)) { + try { + return tap($callback(), function () use ($slot, $id) { + $this->release($slot, $id); + }); + } catch (Throwable $exception) { + $this->release($slot, $id); + + throw $exception; + } + } + + return true; + } + + /** + * Attempt to acquire the lock. + * + * @param string $id A unique identifier for this lock + * @return mixed + */ + protected function acquire($id) + { + $slots = array_map(function ($i) { + return $this->name.$i; + }, range(1, $this->maxLocks)); + + return $this->redis->eval(...array_merge( + [$this->lockScript(), count($slots)], + array_merge($slots, [$this->name, $this->releaseAfter, $id]) + )); + } + + /** + * Get the Lua script for acquiring a lock. + * + * KEYS - The keys that represent available slots + * ARGV[1] - The limiter name + * ARGV[2] - The number of seconds the slot should be reserved + * ARGV[3] - The unique identifier for this lock + * + * @return string + */ + protected function lockScript() + { + return <<<'LUA' +for index, value in pairs(redis.call('mget', unpack(KEYS))) do + if not value then + redis.call('set', KEYS[index], ARGV[3], "EX", ARGV[2]) + return ARGV[1]..index + end +end +LUA; + } + + /** + * Release the lock. + * + * @param string $key + * @param string $id + * @return void + */ + protected function release($key, $id) + { + $this->redis->eval($this->releaseScript(), 1, $key, $id); + } + + /** + * Get the Lua script to atomically release a lock. + * + * KEYS[1] - The name of the lock + * ARGV[1] - The unique identifier for this lock + * + * @return string + */ + protected function releaseScript() + { + return <<<'LUA' +if redis.call('get', KEYS[1]) == ARGV[1] +then + return redis.call('del', KEYS[1]) +else + return 0 +end +LUA; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/ConcurrencyLimiterBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/ConcurrencyLimiterBuilder.php new file mode 100644 index 0000000..e66259f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/ConcurrencyLimiterBuilder.php @@ -0,0 +1,122 @@ +name = $name; + $this->connection = $connection; + } + + /** + * Set the maximum number of locks that can be obtained per time window. + * + * @param int $maxLocks + * @return $this + */ + public function limit($maxLocks) + { + $this->maxLocks = $maxLocks; + + return $this; + } + + /** + * Set the number of seconds until the lock will be released. + * + * @param int $releaseAfter + * @return $this + */ + public function releaseAfter($releaseAfter) + { + $this->releaseAfter = $this->secondsUntil($releaseAfter); + + return $this; + } + + /** + * Set the amount of time to block until a lock is available. + * + * @param int $timeout + * @return $this + */ + public function block($timeout) + { + $this->timeout = $timeout; + + return $this; + } + + /** + * Execute the given callback if a lock is obtained, otherwise call the failure callback. + * + * @param callable $callback + * @param callable|null $failure + * @return mixed + * + * @throws \Illuminate\Contracts\Redis\LimiterTimeoutException + */ + public function then(callable $callback, callable $failure = null) + { + try { + return (new ConcurrencyLimiter( + $this->connection, $this->name, $this->maxLocks, $this->releaseAfter + ))->block($this->timeout, $callback); + } catch (LimiterTimeoutException $e) { + if ($failure) { + return $failure($e); + } + + throw $e; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiter.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiter.php new file mode 100644 index 0000000..56dbba5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiter.php @@ -0,0 +1,202 @@ +name = $name; + $this->decay = $decay; + $this->redis = $redis; + $this->maxLocks = $maxLocks; + } + + /** + * Attempt to acquire the lock for the given number of seconds. + * + * @param int $timeout + * @param callable|null $callback + * @return mixed + * + * @throws \Illuminate\Contracts\Redis\LimiterTimeoutException + */ + public function block($timeout, $callback = null) + { + $starting = time(); + + while (! $this->acquire()) { + if (time() - $timeout >= $starting) { + throw new LimiterTimeoutException; + } + + usleep(750 * 1000); + } + + if (is_callable($callback)) { + return $callback(); + } + + return true; + } + + /** + * Attempt to acquire the lock. + * + * @return bool + */ + public function acquire() + { + $results = $this->redis->eval( + $this->luaScript(), 1, $this->name, microtime(true), time(), $this->decay, $this->maxLocks + ); + + $this->decaysAt = $results[1]; + + $this->remaining = max(0, $results[2]); + + return (bool) $results[0]; + } + + /** + * Determine if the key has been "accessed" too many times. + * + * @return bool + */ + public function tooManyAttempts() + { + [$this->decaysAt, $this->remaining] = $this->redis->eval( + $this->tooManyAttemptsLuaScript(), 1, $this->name, microtime(true), time(), $this->decay, $this->maxLocks + ); + + return $this->remaining <= 0; + } + + /** + * Clear the limiter. + * + * @return void + */ + public function clear() + { + $this->redis->del($this->name); + } + + /** + * Get the Lua script for acquiring a lock. + * + * KEYS[1] - The limiter name + * ARGV[1] - Current time in microseconds + * ARGV[2] - Current time in seconds + * ARGV[3] - Duration of the bucket + * ARGV[4] - Allowed number of tasks + * + * @return string + */ + protected function luaScript() + { + return <<<'LUA' +local function reset() + redis.call('HMSET', KEYS[1], 'start', ARGV[2], 'end', ARGV[2] + ARGV[3], 'count', 1) + return redis.call('EXPIRE', KEYS[1], ARGV[3] * 2) +end + +if redis.call('EXISTS', KEYS[1]) == 0 then + return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1} +end + +if ARGV[1] >= redis.call('HGET', KEYS[1], 'start') and ARGV[1] <= redis.call('HGET', KEYS[1], 'end') then + return { + tonumber(redis.call('HINCRBY', KEYS[1], 'count', 1)) <= tonumber(ARGV[4]), + redis.call('HGET', KEYS[1], 'end'), + ARGV[4] - redis.call('HGET', KEYS[1], 'count') + } +end + +return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1} +LUA; + } + + /** + * Get the Lua script to determine if the key has been "accessed" too many times. + * + * KEYS[1] - The limiter name + * ARGV[1] - Current time in microseconds + * ARGV[2] - Current time in seconds + * ARGV[3] - Duration of the bucket + * ARGV[4] - Allowed number of tasks + * + * @return string + */ + protected function tooManyAttemptsLuaScript() + { + return <<<'LUA' + +if redis.call('EXISTS', KEYS[1]) == 0 then + return {0, ARGV[2] + ARGV[3]} +end + +if ARGV[1] >= redis.call('HGET', KEYS[1], 'start') and ARGV[1] <= redis.call('HGET', KEYS[1], 'end') then + return { + redis.call('HGET', KEYS[1], 'end'), + ARGV[4] - redis.call('HGET', KEYS[1], 'count') + } +end + +return {0, ARGV[2] + ARGV[3]} +LUA; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php new file mode 100644 index 0000000..c32cb50 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php @@ -0,0 +1,122 @@ +name = $name; + $this->connection = $connection; + } + + /** + * Set the maximum number of locks that can be obtained per time window. + * + * @param int $maxLocks + * @return $this + */ + public function allow($maxLocks) + { + $this->maxLocks = $maxLocks; + + return $this; + } + + /** + * Set the amount of time the lock window is maintained. + * + * @param \DateTimeInterface|\DateInterval|int $decay + * @return $this + */ + public function every($decay) + { + $this->decay = $this->secondsUntil($decay); + + return $this; + } + + /** + * Set the amount of time to block until a lock is available. + * + * @param int $timeout + * @return $this + */ + public function block($timeout) + { + $this->timeout = $timeout; + + return $this; + } + + /** + * Execute the given callback if a lock is obtained, otherwise call the failure callback. + * + * @param callable $callback + * @param callable|null $failure + * @return mixed + * + * @throws \Illuminate\Contracts\Redis\LimiterTimeoutException + */ + public function then(callable $callback, callable $failure = null) + { + try { + return (new DurationLimiter( + $this->connection, $this->name, $this->maxLocks, $this->decay + ))->block($this->timeout, $callback); + } catch (LimiterTimeoutException $e) { + if ($failure) { + return $failure($e); + } + + throw $e; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php new file mode 100644 index 0000000..d69f211 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php @@ -0,0 +1,279 @@ +app = $app; + $this->driver = $driver; + $this->config = $config; + } + + /** + * Get a Redis connection by name. + * + * @param string|null $name + * @return \Illuminate\Redis\Connections\Connection + */ + public function connection($name = null) + { + $name = $name ?: 'default'; + + if (isset($this->connections[$name])) { + return $this->connections[$name]; + } + + return $this->connections[$name] = $this->configure( + $this->resolve($name), $name + ); + } + + /** + * Resolve the given connection by name. + * + * @param string|null $name + * @return \Illuminate\Redis\Connections\Connection + * + * @throws \InvalidArgumentException + */ + public function resolve($name = null) + { + $name = $name ?: 'default'; + + $options = $this->config['options'] ?? []; + + if (isset($this->config[$name])) { + return $this->connector()->connect( + $this->parseConnectionConfiguration($this->config[$name]), + array_merge(Arr::except($options, 'parameters'), ['parameters' => Arr::get($options, 'parameters.'.$name, Arr::get($options, 'parameters', []))]) + ); + } + + if (isset($this->config['clusters'][$name])) { + return $this->resolveCluster($name); + } + + throw new InvalidArgumentException("Redis connection [{$name}] not configured."); + } + + /** + * Resolve the given cluster connection by name. + * + * @param string $name + * @return \Illuminate\Redis\Connections\Connection + */ + protected function resolveCluster($name) + { + return $this->connector()->connectToCluster( + array_map(function ($config) { + return $this->parseConnectionConfiguration($config); + }, $this->config['clusters'][$name]), + $this->config['clusters']['options'] ?? [], + $this->config['options'] ?? [] + ); + } + + /** + * Configure the given connection to prepare it for commands. + * + * @param \Illuminate\Redis\Connections\Connection $connection + * @param string $name + * @return \Illuminate\Redis\Connections\Connection + */ + protected function configure(Connection $connection, $name) + { + $connection->setName($name); + + if ($this->events && $this->app->bound('events')) { + $connection->setEventDispatcher($this->app->make('events')); + } + + return $connection; + } + + /** + * Get the connector instance for the current driver. + * + * @return \Illuminate\Contracts\Redis\Connector + */ + protected function connector() + { + $customCreator = $this->customCreators[$this->driver] ?? null; + + if ($customCreator) { + return $customCreator(); + } + + switch ($this->driver) { + case 'predis': + return new PredisConnector; + case 'phpredis': + return new PhpRedisConnector; + } + } + + /** + * Parse the Redis connection configuration. + * + * @param mixed $config + * @return array + */ + protected function parseConnectionConfiguration($config) + { + $parsed = (new ConfigurationUrlParser)->parseConfiguration($config); + + $driver = strtolower($parsed['driver'] ?? ''); + + if (in_array($driver, ['tcp', 'tls'])) { + $parsed['scheme'] = $driver; + } + + return array_filter($parsed, function ($key) { + return ! in_array($key, ['driver'], true); + }, ARRAY_FILTER_USE_KEY); + } + + /** + * Return all of the created connections. + * + * @return array + */ + public function connections() + { + return $this->connections; + } + + /** + * Enable the firing of Redis command events. + * + * @return void + */ + public function enableEvents() + { + $this->events = true; + } + + /** + * Disable the firing of Redis command events. + * + * @return void + */ + public function disableEvents() + { + $this->events = false; + } + + /** + * Set the default driver. + * + * @param string $driver + * @return void + */ + public function setDriver($driver) + { + $this->driver = $driver; + } + + /** + * Disconnect the given connection and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?: 'default'; + + unset($this->connections[$name]); + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback->bindTo($this, $this); + + return $this; + } + + /** + * Pass methods onto the default Redis connection. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->connection()->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/RedisServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/RedisServiceProvider.php new file mode 100755 index 0000000..66282e5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/RedisServiceProvider.php @@ -0,0 +1,38 @@ +app->singleton('redis', function ($app) { + $config = $app->make('config')->get('database.redis', []); + + return new RedisManager($app, Arr::pull($config, 'client', 'phpredis'), $config); + }); + + $this->app->bind('redis.connection', function ($app) { + return $app['redis']->connection(); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['redis', 'redis.connection']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/composer.json new file mode 100755 index 0000000..52cd8c9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Redis/composer.json @@ -0,0 +1,41 @@ +{ + "name": "illuminate/redis", + "description": "The Illuminate Redis package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Redis\\": "" + } + }, + "suggest": { + "ext-redis": "Required to use the phpredis connector (^4.0|^5.0).", + "predis/predis": "Required to use the predis connector (^1.1.9)." + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php new file mode 100644 index 0000000..9599d0e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php @@ -0,0 +1,257 @@ +bind($request); + } + + // If no route was found we will now check if a matching route is specified by + // another HTTP verb. If it is we will need to throw a MethodNotAllowed and + // inform the user agent of which HTTP verb it should use for this route. + $others = $this->checkForAlternateVerbs($request); + + if (count($others) > 0) { + return $this->getRouteForMethods($request, $others); + } + + throw new NotFoundHttpException; + } + + /** + * Determine if any routes match on another HTTP verb. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + protected function checkForAlternateVerbs($request) + { + $methods = array_diff(Router::$verbs, [$request->getMethod()]); + + // Here we will spin through all verbs except for the current request verb and + // check to see if any routes respond to them. If they do, we will return a + // proper error response with the correct headers on the response string. + return array_values(array_filter( + $methods, + function ($method) use ($request) { + return ! is_null($this->matchAgainstRoutes($this->get($method), $request, false)); + } + )); + } + + /** + * Determine if a route in the array matches the request. + * + * @param \Illuminate\Routing\Route[] $routes + * @param \Illuminate\Http\Request $request + * @param bool $includingMethod + * @return \Illuminate\Routing\Route|null + */ + protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true) + { + [$fallbacks, $routes] = collect($routes)->partition(function ($route) { + return $route->isFallback; + }); + + return $routes->merge($fallbacks)->first(function (Route $route) use ($request, $includingMethod) { + return $route->matches($request, $includingMethod); + }); + } + + /** + * Get a route (if necessary) that responds when other available methods are present. + * + * @param \Illuminate\Http\Request $request + * @param string[] $methods + * @return \Illuminate\Routing\Route + * + * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + protected function getRouteForMethods($request, array $methods) + { + if ($request->method() === 'OPTIONS') { + return (new Route('OPTIONS', $request->path(), function () use ($methods) { + return new Response('', 200, ['Allow' => implode(',', $methods)]); + }))->bind($request); + } + + $this->methodNotAllowed($methods, $request->method()); + } + + /** + * Throw a method not allowed HTTP exception. + * + * @param array $others + * @param string $method + * @return void + * + * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + protected function methodNotAllowed(array $others, $method) + { + throw new MethodNotAllowedHttpException( + $others, + sprintf( + 'The %s method is not supported for this route. Supported methods: %s.', + $method, + implode(', ', $others) + ) + ); + } + + /** + * Compile the routes for caching. + * + * @return array + */ + public function compile() + { + $compiled = $this->dumper()->getCompiledRoutes(); + + $attributes = []; + + foreach ($this->getRoutes() as $route) { + $attributes[$route->getName()] = [ + 'methods' => $route->methods(), + 'uri' => $route->uri(), + 'action' => $route->getAction(), + 'fallback' => $route->isFallback, + 'defaults' => $route->defaults, + 'wheres' => $route->wheres, + 'bindingFields' => $route->bindingFields(), + 'lockSeconds' => $route->locksFor(), + 'waitSeconds' => $route->waitsFor(), + 'withTrashed' => $route->allowsTrashedBindings(), + ]; + } + + return compact('compiled', 'attributes'); + } + + /** + * Return the CompiledUrlMatcherDumper instance for the route collection. + * + * @return \Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper + */ + public function dumper() + { + return new CompiledUrlMatcherDumper($this->toSymfonyRouteCollection()); + } + + /** + * Convert the collection to a Symfony RouteCollection instance. + * + * @return \Symfony\Component\Routing\RouteCollection + */ + public function toSymfonyRouteCollection() + { + $symfonyRoutes = new SymfonyRouteCollection; + + $routes = $this->getRoutes(); + + foreach ($routes as $route) { + if (! $route->isFallback) { + $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route); + } + } + + foreach ($routes as $route) { + if ($route->isFallback) { + $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route); + } + } + + return $symfonyRoutes; + } + + /** + * Add a route to the SymfonyRouteCollection instance. + * + * @param \Symfony\Component\Routing\RouteCollection $symfonyRoutes + * @param \Illuminate\Routing\Route $route + * @return \Symfony\Component\Routing\RouteCollection + * + * @throws \LogicException + */ + protected function addToSymfonyRoutesCollection(SymfonyRouteCollection $symfonyRoutes, Route $route) + { + $name = $route->getName(); + + if ( + ! is_null($name) + && Str::endsWith($name, '.') + && ! is_null($symfonyRoutes->get($name)) + ) { + $name = null; + } + + if (! $name) { + $route->name($name = $this->generateRouteName()); + + $this->add($route); + } elseif (! is_null($symfonyRoutes->get($name))) { + throw new LogicException("Unable to prepare route [{$route->uri}] for serialization. Another route has already been assigned name [{$name}]."); + } + + $symfonyRoutes->add($route->getName(), $route->toSymfonyRoute()); + + return $symfonyRoutes; + } + + /** + * Get a randomly generated route name. + * + * @return string + */ + protected function generateRouteName() + { + return 'generated::'.Str::random(); + } + + /** + * Get an iterator for the items. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new ArrayIterator($this->getRoutes()); + } + + /** + * Count the number of items in the collection. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return count($this->getRoutes()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/CompiledRouteCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/CompiledRouteCollection.php new file mode 100644 index 0000000..2b693f8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/CompiledRouteCollection.php @@ -0,0 +1,330 @@ +compiled = $compiled; + $this->attributes = $attributes; + $this->routes = new RouteCollection; + } + + /** + * Add a Route instance to the collection. + * + * @param \Illuminate\Routing\Route $route + * @return \Illuminate\Routing\Route + */ + public function add(Route $route) + { + return $this->routes->add($route); + } + + /** + * Refresh the name look-up table. + * + * This is done in case any names are fluently defined or if routes are overwritten. + * + * @return void + */ + public function refreshNameLookups() + { + // + } + + /** + * Refresh the action look-up table. + * + * This is done in case any actions are overwritten with new controllers. + * + * @return void + */ + public function refreshActionLookups() + { + // + } + + /** + * Find the first route matching a given request. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Routing\Route + * + * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + */ + public function match(Request $request) + { + $matcher = new CompiledUrlMatcher( + $this->compiled, (new RequestContext)->fromRequest( + $trimmedRequest = $this->requestWithoutTrailingSlash($request) + ) + ); + + $route = null; + + try { + if ($result = $matcher->matchRequest($trimmedRequest)) { + $route = $this->getByName($result['_route']); + } + } catch (ResourceNotFoundException|MethodNotAllowedException $e) { + try { + return $this->routes->match($request); + } catch (NotFoundHttpException $e) { + // + } + } + + if ($route && $route->isFallback) { + try { + $dynamicRoute = $this->routes->match($request); + + if (! $dynamicRoute->isFallback) { + $route = $dynamicRoute; + } + } catch (NotFoundHttpException|MethodNotAllowedHttpException $e) { + // + } + } + + return $this->handleMatchedRoute($request, $route); + } + + /** + * Get a cloned instance of the given request without any trailing slash on the URI. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\Request + */ + protected function requestWithoutTrailingSlash(Request $request) + { + $trimmedRequest = $request->duplicate(); + + $parts = explode('?', $request->server->get('REQUEST_URI'), 2); + + $trimmedRequest->server->set( + 'REQUEST_URI', rtrim($parts[0], '/').(isset($parts[1]) ? '?'.$parts[1] : '') + ); + + return $trimmedRequest; + } + + /** + * Get routes from the collection by method. + * + * @param string|null $method + * @return \Illuminate\Routing\Route[] + */ + public function get($method = null) + { + return $this->getRoutesByMethod()[$method] ?? []; + } + + /** + * Determine if the route collection contains a given named route. + * + * @param string $name + * @return bool + */ + public function hasNamedRoute($name) + { + return isset($this->attributes[$name]) || $this->routes->hasNamedRoute($name); + } + + /** + * Get a route instance by its name. + * + * @param string $name + * @return \Illuminate\Routing\Route|null + */ + public function getByName($name) + { + if (isset($this->attributes[$name])) { + return $this->newRoute($this->attributes[$name]); + } + + return $this->routes->getByName($name); + } + + /** + * Get a route instance by its controller action. + * + * @param string $action + * @return \Illuminate\Routing\Route|null + */ + public function getByAction($action) + { + $attributes = collect($this->attributes)->first(function (array $attributes) use ($action) { + if (isset($attributes['action']['controller'])) { + return trim($attributes['action']['controller'], '\\') === $action; + } + + return $attributes['action']['uses'] === $action; + }); + + if ($attributes) { + return $this->newRoute($attributes); + } + + return $this->routes->getByAction($action); + } + + /** + * Get all of the routes in the collection. + * + * @return \Illuminate\Routing\Route[] + */ + public function getRoutes() + { + return collect($this->attributes) + ->map(function (array $attributes) { + return $this->newRoute($attributes); + }) + ->merge($this->routes->getRoutes()) + ->values() + ->all(); + } + + /** + * Get all of the routes keyed by their HTTP verb / method. + * + * @return array + */ + public function getRoutesByMethod() + { + return collect($this->getRoutes()) + ->groupBy(function (Route $route) { + return $route->methods(); + }) + ->map(function (Collection $routes) { + return $routes->mapWithKeys(function (Route $route) { + return [$route->getDomain().$route->uri => $route]; + })->all(); + }) + ->all(); + } + + /** + * Get all of the routes keyed by their name. + * + * @return \Illuminate\Routing\Route[] + */ + public function getRoutesByName() + { + return collect($this->getRoutes()) + ->keyBy(function (Route $route) { + return $route->getName(); + }) + ->all(); + } + + /** + * Resolve an array of attributes to a Route instance. + * + * @param array $attributes + * @return \Illuminate\Routing\Route + */ + protected function newRoute(array $attributes) + { + if (empty($attributes['action']['prefix'] ?? '')) { + $baseUri = $attributes['uri']; + } else { + $prefix = trim($attributes['action']['prefix'], '/'); + + $baseUri = trim(implode( + '/', array_slice( + explode('/', trim($attributes['uri'], '/')), + count($prefix !== '' ? explode('/', $prefix) : []) + ) + ), '/'); + } + + return $this->router->newRoute($attributes['methods'], $baseUri === '' ? '/' : $baseUri, $attributes['action']) + ->setFallback($attributes['fallback']) + ->setDefaults($attributes['defaults']) + ->setWheres($attributes['wheres']) + ->setBindingFields($attributes['bindingFields']) + ->block($attributes['lockSeconds'] ?? null, $attributes['waitSeconds'] ?? null) + ->withTrashed($attributes['withTrashed'] ?? false); + } + + /** + * Set the router instance on the route. + * + * @param \Illuminate\Routing\Router $router + * @return $this + */ + public function setRouter(Router $router) + { + $this->router = $router; + + return $this; + } + + /** + * Set the container instance on the route. + * + * @param \Illuminate\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/ControllerMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/ControllerMakeCommand.php new file mode 100755 index 0000000..fe31bea --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/ControllerMakeCommand.php @@ -0,0 +1,280 @@ +option('type')) { + $stub = "/stubs/controller.{$type}.stub"; + } elseif ($this->option('parent')) { + $stub = '/stubs/controller.nested.stub'; + } elseif ($this->option('model')) { + $stub = '/stubs/controller.model.stub'; + } elseif ($this->option('invokable')) { + $stub = '/stubs/controller.invokable.stub'; + } elseif ($this->option('resource')) { + $stub = '/stubs/controller.stub'; + } + + if ($this->option('api') && is_null($stub)) { + $stub = '/stubs/controller.api.stub'; + } elseif ($this->option('api') && ! is_null($stub) && ! $this->option('invokable')) { + $stub = str_replace('.stub', '.api.stub', $stub); + } + + $stub = $stub ?? '/stubs/controller.plain.stub'; + + return $this->resolveStubPath($stub); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Http\Controllers'; + } + + /** + * Build the class with the given name. + * + * Remove the base controller import if we are already in the base namespace. + * + * @param string $name + * @return string + */ + protected function buildClass($name) + { + $controllerNamespace = $this->getNamespace($name); + + $replace = []; + + if ($this->option('parent')) { + $replace = $this->buildParentReplacements(); + } + + if ($this->option('model')) { + $replace = $this->buildModelReplacements($replace); + } + + $replace["use {$controllerNamespace}\Controller;\n"] = ''; + + return str_replace( + array_keys($replace), array_values($replace), parent::buildClass($name) + ); + } + + /** + * Build the replacements for a parent controller. + * + * @return array + */ + protected function buildParentReplacements() + { + $parentModelClass = $this->parseModel($this->option('parent')); + + if (! class_exists($parentModelClass)) { + if ($this->confirm("A {$parentModelClass} model does not exist. Do you want to generate it?", true)) { + $this->call('make:model', ['name' => $parentModelClass]); + } + } + + return [ + 'ParentDummyFullModelClass' => $parentModelClass, + '{{ namespacedParentModel }}' => $parentModelClass, + '{{namespacedParentModel}}' => $parentModelClass, + 'ParentDummyModelClass' => class_basename($parentModelClass), + '{{ parentModel }}' => class_basename($parentModelClass), + '{{parentModel}}' => class_basename($parentModelClass), + 'ParentDummyModelVariable' => lcfirst(class_basename($parentModelClass)), + '{{ parentModelVariable }}' => lcfirst(class_basename($parentModelClass)), + '{{parentModelVariable}}' => lcfirst(class_basename($parentModelClass)), + ]; + } + + /** + * Build the model replacement values. + * + * @param array $replace + * @return array + */ + protected function buildModelReplacements(array $replace) + { + $modelClass = $this->parseModel($this->option('model')); + + if (! class_exists($modelClass)) { + if ($this->confirm("A {$modelClass} model does not exist. Do you want to generate it?", true)) { + $this->call('make:model', ['name' => $modelClass]); + } + } + + $replace = $this->buildFormRequestReplacements($replace, $modelClass); + + return array_merge($replace, [ + 'DummyFullModelClass' => $modelClass, + '{{ namespacedModel }}' => $modelClass, + '{{namespacedModel}}' => $modelClass, + 'DummyModelClass' => class_basename($modelClass), + '{{ model }}' => class_basename($modelClass), + '{{model}}' => class_basename($modelClass), + 'DummyModelVariable' => lcfirst(class_basename($modelClass)), + '{{ modelVariable }}' => lcfirst(class_basename($modelClass)), + '{{modelVariable}}' => lcfirst(class_basename($modelClass)), + ]); + } + + /** + * Get the fully-qualified model class name. + * + * @param string $model + * @return string + * + * @throws \InvalidArgumentException + */ + protected function parseModel($model) + { + if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) { + throw new InvalidArgumentException('Model name contains invalid characters.'); + } + + return $this->qualifyModel($model); + } + + /** + * Build the model replacement values. + * + * @param array $replace + * @param string $modelClass + * @return array + */ + protected function buildFormRequestReplacements(array $replace, $modelClass) + { + [$namespace, $storeRequestClass, $updateRequestClass] = [ + 'Illuminate\\Http', 'Request', 'Request', + ]; + + if ($this->option('requests')) { + $namespace = 'App\\Http\\Requests'; + + [$storeRequestClass, $updateRequestClass] = $this->generateFormRequests( + $modelClass, $storeRequestClass, $updateRequestClass + ); + } + + $namespacedRequests = $namespace.'\\'.$storeRequestClass.';'; + + if ($storeRequestClass !== $updateRequestClass) { + $namespacedRequests .= PHP_EOL.'use '.$namespace.'\\'.$updateRequestClass.';'; + } + + return array_merge($replace, [ + '{{ storeRequest }}' => $storeRequestClass, + '{{storeRequest}}' => $storeRequestClass, + '{{ updateRequest }}' => $updateRequestClass, + '{{updateRequest}}' => $updateRequestClass, + '{{ namespacedStoreRequest }}' => $namespace.'\\'.$storeRequestClass, + '{{namespacedStoreRequest}}' => $namespace.'\\'.$storeRequestClass, + '{{ namespacedUpdateRequest }}' => $namespace.'\\'.$updateRequestClass, + '{{namespacedUpdateRequest}}' => $namespace.'\\'.$updateRequestClass, + '{{ namespacedRequests }}' => $namespacedRequests, + '{{namespacedRequests}}' => $namespacedRequests, + ]); + } + + /** + * Generate the form requests for the given model and classes. + * + * @param string $modelName + * @param string $storeRequestClass + * @param string $updateRequestClass + * @return array + */ + protected function generateFormRequests($modelClass, $storeRequestClass, $updateRequestClass) + { + $storeRequestClass = 'Store'.class_basename($modelClass).'Request'; + + $this->call('make:request', [ + 'name' => $storeRequestClass, + ]); + + $updateRequestClass = 'Update'.class_basename($modelClass).'Request'; + + $this->call('make:request', [ + 'name' => $updateRequestClass, + ]); + + return [$storeRequestClass, $updateRequestClass]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['api', null, InputOption::VALUE_NONE, 'Exclude the create and edit methods from the controller.'], + ['type', null, InputOption::VALUE_REQUIRED, 'Manually specify the controller stub file to use.'], + ['force', null, InputOption::VALUE_NONE, 'Create the class even if the controller already exists'], + ['invokable', 'i', InputOption::VALUE_NONE, 'Generate a single method, invokable controller class.'], + ['model', 'm', InputOption::VALUE_OPTIONAL, 'Generate a resource controller for the given model.'], + ['parent', 'p', InputOption::VALUE_OPTIONAL, 'Generate a nested resource controller class.'], + ['resource', 'r', InputOption::VALUE_NONE, 'Generate a resource controller class.'], + ['requests', 'R', InputOption::VALUE_NONE, 'Generate FormRequest classes for store and update.'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/MiddlewareMakeCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/MiddlewareMakeCommand.php new file mode 100644 index 0000000..ddd591c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/MiddlewareMakeCommand.php @@ -0,0 +1,66 @@ +resolveStubPath('/stubs/middleware.stub'); + } + + /** + * Resolve the fully-qualified path to the stub. + * + * @param string $stub + * @return string + */ + protected function resolveStubPath($stub) + { + return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) + ? $customPath + : __DIR__.$stub; + } + + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace.'\Http\Middleware'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/stubs/controller.api.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/stubs/controller.api.stub new file mode 100644 index 0000000..381a9c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Console/stubs/controller.api.stub @@ -0,0 +1,64 @@ +middleware[] = [ + 'middleware' => $m, + 'options' => &$options, + ]; + } + + return new ControllerMiddlewareOptions($options); + } + + /** + * Get the middleware assigned to the controller. + * + * @return array + */ + public function getMiddleware() + { + return $this->middleware; + } + + /** + * Execute an action on the controller. + * + * @param string $method + * @param array $parameters + * @return \Symfony\Component\HttpFoundation\Response + */ + public function callAction($method, $parameters) + { + return $this->{$method}(...array_values($parameters)); + } + + /** + * Handle calls to missing methods on the controller. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + throw new BadMethodCallException(sprintf( + 'Method %s::%s does not exist.', static::class, $method + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php new file mode 100644 index 0000000..673a333 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php @@ -0,0 +1,81 @@ +container = $container; + } + + /** + * Dispatch a request to a given controller and method. + * + * @param \Illuminate\Routing\Route $route + * @param mixed $controller + * @param string $method + * @return mixed + */ + public function dispatch(Route $route, $controller, $method) + { + $parameters = $this->resolveClassMethodDependencies( + $route->parametersWithoutNulls(), $controller, $method + ); + + if (method_exists($controller, 'callAction')) { + return $controller->callAction($method, $parameters); + } + + return $controller->{$method}(...array_values($parameters)); + } + + /** + * Get the middleware for the controller instance. + * + * @param \Illuminate\Routing\Controller $controller + * @param string $method + * @return array + */ + public function getMiddleware($controller, $method) + { + if (! method_exists($controller, 'getMiddleware')) { + return []; + } + + return collect($controller->getMiddleware())->reject(function ($data) use ($method) { + return static::methodExcludedByOptions($method, $data['options']); + })->pluck('middleware')->all(); + } + + /** + * Determine if the given options exclude a particular method. + * + * @param string $method + * @param array $options + * @return bool + */ + protected static function methodExcludedByOptions($method, array $options) + { + return (isset($options['only']) && ! in_array($method, (array) $options['only'])) || + (! empty($options['except']) && in_array($method, (array) $options['except'])); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ControllerMiddlewareOptions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ControllerMiddlewareOptions.php new file mode 100644 index 0000000..13ef189 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ControllerMiddlewareOptions.php @@ -0,0 +1,50 @@ +options = &$options; + } + + /** + * Set the controller methods the middleware should apply to. + * + * @param array|string|dynamic $methods + * @return $this + */ + public function only($methods) + { + $this->options['only'] = is_array($methods) ? $methods : func_get_args(); + + return $this; + } + + /** + * Set the controller methods the middleware should exclude. + * + * @param array|string|dynamic $methods + * @return $this + */ + public function except($methods) + { + $this->options['except'] = is_array($methods) ? $methods : func_get_args(); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/CreatesRegularExpressionRouteConstraints.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/CreatesRegularExpressionRouteConstraints.php new file mode 100644 index 0000000..31b0f71 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/CreatesRegularExpressionRouteConstraints.php @@ -0,0 +1,67 @@ +assignExpressionToParameters($parameters, '[a-zA-Z]+'); + } + + /** + * Specify that the given route parameters must be alphanumeric. + * + * @param array|string $parameters + * @return $this + */ + public function whereAlphaNumeric($parameters) + { + return $this->assignExpressionToParameters($parameters, '[a-zA-Z0-9]+'); + } + + /** + * Specify that the given route parameters must be numeric. + * + * @param array|string $parameters + * @return $this + */ + public function whereNumber($parameters) + { + return $this->assignExpressionToParameters($parameters, '[0-9]+'); + } + + /** + * Specify that the given route parameters must be UUIDs. + * + * @param array|string $parameters + * @return $this + */ + public function whereUuid($parameters) + { + return $this->assignExpressionToParameters($parameters, '[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}'); + } + + /** + * Apply the given regular expression to the given parameters. + * + * @param array|string $parameters + * @param string $expression + * @return $this + */ + protected function assignExpressionToParameters($parameters, $expression) + { + return $this->where(collect(Arr::wrap($parameters)) + ->mapWithKeys(function ($parameter) use ($expression) { + return [$parameter => $expression]; + })->all()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Events/RouteMatched.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Events/RouteMatched.php new file mode 100644 index 0000000..c848607 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Events/RouteMatched.php @@ -0,0 +1,33 @@ +route = $route; + $this->request = $request; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Exceptions/InvalidSignatureException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Exceptions/InvalidSignatureException.php new file mode 100644 index 0000000..06a35c5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Exceptions/InvalidSignatureException.php @@ -0,0 +1,18 @@ +getName(), + $route->uri() + ); + + if (count($parameters) > 0) { + $message .= sprintf(' [Missing %s: %s]', $parameterLabel, implode(', ', $parameters)); + } + + $message .= '.'; + + return new static($message); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ImplicitRouteBinding.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ImplicitRouteBinding.php new file mode 100644 index 0000000..1dbc572 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ImplicitRouteBinding.php @@ -0,0 +1,80 @@ +parameters(); + + foreach ($route->signatureParameters(UrlRoutable::class) as $parameter) { + if (! $parameterName = static::getParameterName($parameter->getName(), $parameters)) { + continue; + } + + $parameterValue = $parameters[$parameterName]; + + if ($parameterValue instanceof UrlRoutable) { + continue; + } + + $instance = $container->make(Reflector::getParameterClassName($parameter)); + + $parent = $route->parentOfParameter($parameterName); + + $routeBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance)) + ? 'resolveSoftDeletableRouteBinding' + : 'resolveRouteBinding'; + + if ($parent instanceof UrlRoutable && ($route->enforcesScopedBindings() || array_key_exists($parameterName, $route->bindingFields()))) { + $childRouteBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance)) + ? 'resolveSoftDeletableChildRouteBinding' + : 'resolveChildRouteBinding'; + + if (! $model = $parent->{$childRouteBindingMethod}( + $parameterName, $parameterValue, $route->bindingFieldFor($parameterName) + )) { + throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]); + } + } elseif (! $model = $instance->{$routeBindingMethod}($parameterValue, $route->bindingFieldFor($parameterName))) { + throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]); + } + + $route->setParameter($parameterName, $model); + } + } + + /** + * Return the parameter name if it exists in the given parameters. + * + * @param string $name + * @param array $parameters + * @return string|null + */ + protected static function getParameterName($name, $parameters) + { + if (array_key_exists($name, $parameters)) { + return $name; + } + + if (array_key_exists($snakedName = Str::snake($name), $parameters)) { + return $snakedName; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/HostValidator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/HostValidator.php new file mode 100644 index 0000000..a0ea721 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/HostValidator.php @@ -0,0 +1,27 @@ +getCompiled()->getHostRegex(); + + if (is_null($hostRegex)) { + return true; + } + + return preg_match($hostRegex, $request->getHost()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/MethodValidator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/MethodValidator.php new file mode 100644 index 0000000..f9cf155 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/MethodValidator.php @@ -0,0 +1,21 @@ +getMethod(), $route->methods()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/SchemeValidator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/SchemeValidator.php new file mode 100644 index 0000000..fd5d5af --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/SchemeValidator.php @@ -0,0 +1,27 @@ +httpOnly()) { + return ! $request->secure(); + } elseif ($route->secure()) { + return $request->secure(); + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/UriValidator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/UriValidator.php new file mode 100644 index 0000000..4dcc2cf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/UriValidator.php @@ -0,0 +1,23 @@ +getPathInfo(), '/') ?: '/'; + + return preg_match($route->getCompiled()->getRegex(), rawurldecode($path)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/ValidatorInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/ValidatorInterface.php new file mode 100644 index 0000000..0f178f1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Matching/ValidatorInterface.php @@ -0,0 +1,18 @@ +router = $router; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + try { + $this->router->substituteBindings($route = $request->route()); + + $this->router->substituteImplicitBindings($route); + } catch (ModelNotFoundException $exception) { + if ($route->getMissing()) { + return $route->getMissing()($request, $exception); + } + + throw $exception; + } + + return $next($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php new file mode 100644 index 0000000..d570da4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php @@ -0,0 +1,277 @@ +limiter = $limiter; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param int|string $maxAttempts + * @param float|int $decayMinutes + * @param string $prefix + * @return \Symfony\Component\HttpFoundation\Response + * + * @throws \Illuminate\Http\Exceptions\ThrottleRequestsException + */ + public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '') + { + if (is_string($maxAttempts) + && func_num_args() === 3 + && ! is_null($limiter = $this->limiter->limiter($maxAttempts))) { + return $this->handleRequestUsingNamedLimiter($request, $next, $maxAttempts, $limiter); + } + + return $this->handleRequest( + $request, + $next, + [ + (object) [ + 'key' => $prefix.$this->resolveRequestSignature($request), + 'maxAttempts' => $this->resolveMaxAttempts($request, $maxAttempts), + 'decayMinutes' => $decayMinutes, + 'responseCallback' => null, + ], + ] + ); + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string $limiterName + * @param \Closure $limiter + * @return \Symfony\Component\HttpFoundation\Response + * + * @throws \Illuminate\Http\Exceptions\ThrottleRequestsException + */ + protected function handleRequestUsingNamedLimiter($request, Closure $next, $limiterName, Closure $limiter) + { + $limiterResponse = call_user_func($limiter, $request); + + if ($limiterResponse instanceof Response) { + return $limiterResponse; + } elseif ($limiterResponse instanceof Unlimited) { + return $next($request); + } + + return $this->handleRequest( + $request, + $next, + collect(Arr::wrap($limiterResponse))->map(function ($limit) use ($limiterName) { + return (object) [ + 'key' => md5($limiterName.$limit->key), + 'maxAttempts' => $limit->maxAttempts, + 'decayMinutes' => $limit->decayMinutes, + 'responseCallback' => $limit->responseCallback, + ]; + })->all() + ); + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param array $limits + * @return \Symfony\Component\HttpFoundation\Response + * + * @throws \Illuminate\Http\Exceptions\ThrottleRequestsException + */ + protected function handleRequest($request, Closure $next, array $limits) + { + foreach ($limits as $limit) { + if ($this->limiter->tooManyAttempts($limit->key, $limit->maxAttempts)) { + throw $this->buildException($request, $limit->key, $limit->maxAttempts, $limit->responseCallback); + } + + $this->limiter->hit($limit->key, $limit->decayMinutes * 60); + } + + $response = $next($request); + + foreach ($limits as $limit) { + $response = $this->addHeaders( + $response, + $limit->maxAttempts, + $this->calculateRemainingAttempts($limit->key, $limit->maxAttempts) + ); + } + + return $response; + } + + /** + * Resolve the number of attempts if the user is authenticated or not. + * + * @param \Illuminate\Http\Request $request + * @param int|string $maxAttempts + * @return int + */ + protected function resolveMaxAttempts($request, $maxAttempts) + { + if (Str::contains($maxAttempts, '|')) { + $maxAttempts = explode('|', $maxAttempts, 2)[$request->user() ? 1 : 0]; + } + + if (! is_numeric($maxAttempts) && $request->user()) { + $maxAttempts = $request->user()->{$maxAttempts}; + } + + return (int) $maxAttempts; + } + + /** + * Resolve request signature. + * + * @param \Illuminate\Http\Request $request + * @return string + * + * @throws \RuntimeException + */ + protected function resolveRequestSignature($request) + { + if ($user = $request->user()) { + return sha1($user->getAuthIdentifier()); + } elseif ($route = $request->route()) { + return sha1($route->getDomain().'|'.$request->ip()); + } + + throw new RuntimeException('Unable to generate the request signature. Route unavailable.'); + } + + /** + * Create a 'too many attempts' exception. + * + * @param \Illuminate\Http\Request $request + * @param string $key + * @param int $maxAttempts + * @param callable|null $responseCallback + * @return \Illuminate\Http\Exceptions\ThrottleRequestsException + */ + protected function buildException($request, $key, $maxAttempts, $responseCallback = null) + { + $retryAfter = $this->getTimeUntilNextRetry($key); + + $headers = $this->getHeaders( + $maxAttempts, + $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter), + $retryAfter + ); + + return is_callable($responseCallback) + ? new HttpResponseException($responseCallback($request, $headers)) + : new ThrottleRequestsException('Too Many Attempts.', null, $headers); + } + + /** + * Get the number of seconds until the next retry. + * + * @param string $key + * @return int + */ + protected function getTimeUntilNextRetry($key) + { + return $this->limiter->availableIn($key); + } + + /** + * Add the limit header information to the given response. + * + * @param \Symfony\Component\HttpFoundation\Response $response + * @param int $maxAttempts + * @param int $remainingAttempts + * @param int|null $retryAfter + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null) + { + $response->headers->add( + $this->getHeaders($maxAttempts, $remainingAttempts, $retryAfter, $response) + ); + + return $response; + } + + /** + * Get the limit headers information. + * + * @param int $maxAttempts + * @param int $remainingAttempts + * @param int|null $retryAfter + * @param \Symfony\Component\HttpFoundation\Response|null $response + * @return array + */ + protected function getHeaders($maxAttempts, + $remainingAttempts, + $retryAfter = null, + ?Response $response = null) + { + if ($response && + ! is_null($response->headers->get('X-RateLimit-Remaining')) && + (int) $response->headers->get('X-RateLimit-Remaining') <= (int) $remainingAttempts) { + return []; + } + + $headers = [ + 'X-RateLimit-Limit' => $maxAttempts, + 'X-RateLimit-Remaining' => $remainingAttempts, + ]; + + if (! is_null($retryAfter)) { + $headers['Retry-After'] = $retryAfter; + $headers['X-RateLimit-Reset'] = $this->availableAt($retryAfter); + } + + return $headers; + } + + /** + * Calculate the number of remaining attempts. + * + * @param string $key + * @param int $maxAttempts + * @param int|null $retryAfter + * @return int + */ + protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null) + { + return is_null($retryAfter) ? $this->limiter->retriesLeft($key, $maxAttempts) : 0; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequestsWithRedis.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequestsWithRedis.php new file mode 100644 index 0000000..777f30c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequestsWithRedis.php @@ -0,0 +1,122 @@ +redis = $redis; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param array $limits + * @return \Symfony\Component\HttpFoundation\Response + * + * @throws \Illuminate\Http\Exceptions\ThrottleRequestsException + */ + protected function handleRequest($request, Closure $next, array $limits) + { + foreach ($limits as $limit) { + if ($this->tooManyAttempts($limit->key, $limit->maxAttempts, $limit->decayMinutes)) { + throw $this->buildException($request, $limit->key, $limit->maxAttempts, $limit->responseCallback); + } + } + + $response = $next($request); + + foreach ($limits as $limit) { + $response = $this->addHeaders( + $response, + $limit->maxAttempts, + $this->calculateRemainingAttempts($limit->key, $limit->maxAttempts) + ); + } + + return $response; + } + + /** + * Determine if the given key has been "accessed" too many times. + * + * @param string $key + * @param int $maxAttempts + * @param int $decayMinutes + * @return mixed + */ + protected function tooManyAttempts($key, $maxAttempts, $decayMinutes) + { + $limiter = new DurationLimiter( + $this->redis, $key, $maxAttempts, $decayMinutes * 60 + ); + + return tap(! $limiter->acquire(), function () use ($key, $limiter) { + [$this->decaysAt[$key], $this->remaining[$key]] = [ + $limiter->decaysAt, $limiter->remaining, + ]; + }); + } + + /** + * Calculate the number of remaining attempts. + * + * @param string $key + * @param int $maxAttempts + * @param int|null $retryAfter + * @return int + */ + protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null) + { + return is_null($retryAfter) ? $this->remaining[$key] : 0; + } + + /** + * Get the number of seconds until the lock is released. + * + * @param string $key + * @return int + */ + protected function getTimeUntilNextRetry($key) + { + return $this->decaysAt[$key] - $this->currentTime(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ValidateSignature.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ValidateSignature.php new file mode 100644 index 0000000..59fd368 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ValidateSignature.php @@ -0,0 +1,28 @@ +hasValidSignature($relative !== 'relative')) { + return $next($request); + } + + throw new InvalidSignatureException; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/MiddlewareNameResolver.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/MiddlewareNameResolver.php new file mode 100644 index 0000000..87ab42d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/MiddlewareNameResolver.php @@ -0,0 +1,85 @@ +name = $name; + $this->options = $options; + $this->registrar = $registrar; + $this->controller = $controller; + } + + /** + * Set the methods the controller should apply to. + * + * @param array|string|dynamic $methods + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function only($methods) + { + $this->options['only'] = is_array($methods) ? $methods : func_get_args(); + + return $this; + } + + /** + * Set the methods the controller should exclude. + * + * @param array|string|dynamic $methods + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function except($methods) + { + $this->options['except'] = is_array($methods) ? $methods : func_get_args(); + + return $this; + } + + /** + * Set the route names for controller actions. + * + * @param array|string $names + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function names($names) + { + $this->options['names'] = $names; + + return $this; + } + + /** + * Set the route name for a controller action. + * + * @param string $method + * @param string $name + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function name($method, $name) + { + $this->options['names'][$method] = $name; + + return $this; + } + + /** + * Override the route parameter names. + * + * @param array|string $parameters + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function parameters($parameters) + { + $this->options['parameters'] = $parameters; + + return $this; + } + + /** + * Override a route parameter's name. + * + * @param string $previous + * @param string $new + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function parameter($previous, $new) + { + $this->options['parameters'][$previous] = $new; + + return $this; + } + + /** + * Add middleware to the resource routes. + * + * @param mixed $middleware + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function middleware($middleware) + { + $middleware = Arr::wrap($middleware); + + foreach ($middleware as $key => $value) { + $middleware[$key] = (string) $value; + } + + $this->options['middleware'] = $middleware; + + return $this; + } + + /** + * Specify middleware that should be removed from the resource routes. + * + * @param array|string $middleware + * @return $this|array + */ + public function withoutMiddleware($middleware) + { + $this->options['excluded_middleware'] = array_merge( + (array) ($this->options['excluded_middleware'] ?? []), Arr::wrap($middleware) + ); + + return $this; + } + + /** + * Add "where" constraints to the resource routes. + * + * @param mixed $wheres + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function where($wheres) + { + $this->options['wheres'] = $wheres; + + return $this; + } + + /** + * Indicate that the resource routes should have "shallow" nesting. + * + * @param bool $shallow + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function shallow($shallow = true) + { + $this->options['shallow'] = $shallow; + + return $this; + } + + /** + * Define the callable that should be invoked on a missing model exception. + * + * @param callable $callback + * @return $this + */ + public function missing($callback) + { + $this->options['missing'] = $callback; + + return $this; + } + + /** + * Indicate that the resource routes should be scoped using the given binding fields. + * + * @param array $fields + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function scoped(array $fields = []) + { + $this->options['bindingFields'] = $fields; + + return $this; + } + + /** + * Register the resource route. + * + * @return \Illuminate\Routing\RouteCollection + */ + public function register() + { + $this->registered = true; + + return $this->registrar->register( + $this->name, $this->controller, $this->options + ); + } + + /** + * Handle the object's destruction. + * + * @return void + */ + public function __destruct() + { + if (! $this->registered) { + $this->register(); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php new file mode 100644 index 0000000..e43d591 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php @@ -0,0 +1,59 @@ +toResponse($this->getContainer()->make(Request::class)) + : $carry; + } + + /** + * Handle the given exception. + * + * @param mixed $passable + * @param \Throwable $e + * @return mixed + * + * @throws \Throwable + */ + protected function handleException($passable, Throwable $e) + { + if (! $this->container->bound(ExceptionHandler::class) || + ! $passable instanceof Request) { + throw $e; + } + + $handler = $this->container->make(ExceptionHandler::class); + + $handler->report($e); + + $response = $handler->render($passable, $e); + + if (is_object($response) && method_exists($response, 'withException')) { + $response->withException($e); + } + + return $response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RedirectController.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RedirectController.php new file mode 100644 index 0000000..e98414b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RedirectController.php @@ -0,0 +1,44 @@ +route()->parameters()); + + $status = $parameters->get('status'); + + $destination = $parameters->get('destination'); + + $parameters->forget('status')->forget('destination'); + + $route = (new Route('GET', $destination, [ + 'as' => 'laravel_route_redirect_destination', + ]))->bind($request); + + $parameters = $parameters->only( + $route->getCompiled()->getPathVariables() + )->toArray(); + + $url = $url->toRoute($route, $parameters, false); + + if (! Str::startsWith($destination, '/') && Str::startsWith($url, '/')) { + $url = Str::after($url, '/'); + } + + return new RedirectResponse($url, $status); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Redirector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Redirector.php new file mode 100755 index 0000000..99e7c22 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Redirector.php @@ -0,0 +1,262 @@ +generator = $generator; + } + + /** + * Create a new redirect response to the "home" route. + * + * @param int $status + * @return \Illuminate\Http\RedirectResponse + */ + public function home($status = 302) + { + return $this->to($this->generator->route('home'), $status); + } + + /** + * Create a new redirect response to the previous location. + * + * @param int $status + * @param array $headers + * @param mixed $fallback + * @return \Illuminate\Http\RedirectResponse + */ + public function back($status = 302, $headers = [], $fallback = false) + { + return $this->createRedirect($this->generator->previous($fallback), $status, $headers); + } + + /** + * Create a new redirect response to the current URI. + * + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function refresh($status = 302, $headers = []) + { + return $this->to($this->generator->getRequest()->path(), $status, $headers); + } + + /** + * Create a new redirect response, while putting the current URL in the session. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + */ + public function guest($path, $status = 302, $headers = [], $secure = null) + { + $request = $this->generator->getRequest(); + + $intended = $request->method() === 'GET' && $request->route() && ! $request->expectsJson() + ? $this->generator->full() + : $this->generator->previous(); + + if ($intended) { + $this->setIntendedUrl($intended); + } + + return $this->to($path, $status, $headers, $secure); + } + + /** + * Create a new redirect response to the previously intended location. + * + * @param string $default + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + */ + public function intended($default = '/', $status = 302, $headers = [], $secure = null) + { + $path = $this->session->pull('url.intended', $default); + + return $this->to($path, $status, $headers, $secure); + } + + /** + * Set the intended url. + * + * @param string $url + * @return void + */ + public function setIntendedUrl($url) + { + $this->session->put('url.intended', $url); + } + + /** + * Create a new redirect response to the given path. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + */ + public function to($path, $status = 302, $headers = [], $secure = null) + { + return $this->createRedirect($this->generator->to($path, [], $secure), $status, $headers); + } + + /** + * Create a new redirect response to an external URL (no validation). + * + * @param string $path + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function away($path, $status = 302, $headers = []) + { + return $this->createRedirect($path, $status, $headers); + } + + /** + * Create a new redirect response to the given HTTPS path. + * + * @param string $path + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function secure($path, $status = 302, $headers = []) + { + return $this->to($path, $status, $headers, true); + } + + /** + * Create a new redirect response to a named route. + * + * @param string $route + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function route($route, $parameters = [], $status = 302, $headers = []) + { + return $this->to($this->generator->route($route, $parameters), $status, $headers); + } + + /** + * Create a new redirect response to a signed named route. + * + * @param string $route + * @param mixed $parameters + * @param \DateTimeInterface|\DateInterval|int|null $expiration + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function signedRoute($route, $parameters = [], $expiration = null, $status = 302, $headers = []) + { + return $this->to($this->generator->signedRoute($route, $parameters, $expiration), $status, $headers); + } + + /** + * Create a new redirect response to a signed named route. + * + * @param string $route + * @param \DateTimeInterface|\DateInterval|int|null $expiration + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function temporarySignedRoute($route, $expiration, $parameters = [], $status = 302, $headers = []) + { + return $this->to($this->generator->temporarySignedRoute($route, $expiration, $parameters), $status, $headers); + } + + /** + * Create a new redirect response to a controller action. + * + * @param string|array $action + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function action($action, $parameters = [], $status = 302, $headers = []) + { + return $this->to($this->generator->action($action, $parameters), $status, $headers); + } + + /** + * Create a new redirect response. + * + * @param string $path + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + protected function createRedirect($path, $status, $headers) + { + return tap(new RedirectResponse($path, $status, $headers), function ($redirect) { + if (isset($this->session)) { + $redirect->setSession($this->session); + } + + $redirect->setRequest($this->generator->getRequest()); + }); + } + + /** + * Get the URL generator instance. + * + * @return \Illuminate\Routing\UrlGenerator + */ + public function getUrlGenerator() + { + return $this->generator; + } + + /** + * Set the active session store. + * + * @param \Illuminate\Session\Store $session + * @return void + */ + public function setSession(SessionStore $session) + { + $this->session = $session; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ResourceRegistrar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ResourceRegistrar.php new file mode 100644 index 0000000..c32de58 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ResourceRegistrar.php @@ -0,0 +1,514 @@ + 'create', + 'edit' => 'edit', + ]; + + /** + * Create a new resource registrar instance. + * + * @param \Illuminate\Routing\Router $router + * @return void + */ + public function __construct(Router $router) + { + $this->router = $router; + } + + /** + * Route a resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\RouteCollection + */ + public function register($name, $controller, array $options = []) + { + if (isset($options['parameters']) && ! isset($this->parameters)) { + $this->parameters = $options['parameters']; + } + + // If the resource name contains a slash, we will assume the developer wishes to + // register these resource routes with a prefix so we will set that up out of + // the box so they don't have to mess with it. Otherwise, we will continue. + if (Str::contains($name, '/')) { + $this->prefixedResource($name, $controller, $options); + + return; + } + + // We need to extract the base resource from the resource name. Nested resources + // are supported in the framework, but we need to know what name to use for a + // place-holder on the route parameters, which should be the base resources. + $base = $this->getResourceWildcard(last(explode('.', $name))); + + $defaults = $this->resourceDefaults; + + $collection = new RouteCollection; + + foreach ($this->getResourceMethods($defaults, $options) as $m) { + $route = $this->{'addResource'.ucfirst($m)}( + $name, $base, $controller, $options + ); + + if (isset($options['bindingFields'])) { + $this->setResourceBindingFields($route, $options['bindingFields']); + } + + $collection->add($route); + } + + return $collection; + } + + /** + * Build a set of prefixed resource routes. + * + * @param string $name + * @param string $controller + * @param array $options + * @return void + */ + protected function prefixedResource($name, $controller, array $options) + { + [$name, $prefix] = $this->getResourcePrefix($name); + + // We need to extract the base resource from the resource name. Nested resources + // are supported in the framework, but we need to know what name to use for a + // place-holder on the route parameters, which should be the base resources. + $callback = function ($me) use ($name, $controller, $options) { + $me->resource($name, $controller, $options); + }; + + return $this->router->group(compact('prefix'), $callback); + } + + /** + * Extract the resource and prefix from a resource name. + * + * @param string $name + * @return array + */ + protected function getResourcePrefix($name) + { + $segments = explode('/', $name); + + // To get the prefix, we will take all of the name segments and implode them on + // a slash. This will generate a proper URI prefix for us. Then we take this + // last segment, which will be considered the final resources name we use. + $prefix = implode('/', array_slice($segments, 0, -1)); + + return [end($segments), $prefix]; + } + + /** + * Get the applicable resource methods. + * + * @param array $defaults + * @param array $options + * @return array + */ + protected function getResourceMethods($defaults, $options) + { + $methods = $defaults; + + if (isset($options['only'])) { + $methods = array_intersect($methods, (array) $options['only']); + } + + if (isset($options['except'])) { + $methods = array_diff($methods, (array) $options['except']); + } + + return $methods; + } + + /** + * Add the index method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceIndex($name, $base, $controller, $options) + { + $uri = $this->getResourceUri($name); + + unset($options['missing']); + + $action = $this->getResourceAction($name, $controller, 'index', $options); + + return $this->router->get($uri, $action); + } + + /** + * Add the create method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceCreate($name, $base, $controller, $options) + { + $uri = $this->getResourceUri($name).'/'.static::$verbs['create']; + + unset($options['missing']); + + $action = $this->getResourceAction($name, $controller, 'create', $options); + + return $this->router->get($uri, $action); + } + + /** + * Add the store method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceStore($name, $base, $controller, $options) + { + $uri = $this->getResourceUri($name); + + unset($options['missing']); + + $action = $this->getResourceAction($name, $controller, 'store', $options); + + return $this->router->post($uri, $action); + } + + /** + * Add the show method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceShow($name, $base, $controller, $options) + { + $name = $this->getShallowName($name, $options); + + $uri = $this->getResourceUri($name).'/{'.$base.'}'; + + $action = $this->getResourceAction($name, $controller, 'show', $options); + + return $this->router->get($uri, $action); + } + + /** + * Add the edit method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceEdit($name, $base, $controller, $options) + { + $name = $this->getShallowName($name, $options); + + $uri = $this->getResourceUri($name).'/{'.$base.'}/'.static::$verbs['edit']; + + $action = $this->getResourceAction($name, $controller, 'edit', $options); + + return $this->router->get($uri, $action); + } + + /** + * Add the update method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceUpdate($name, $base, $controller, $options) + { + $name = $this->getShallowName($name, $options); + + $uri = $this->getResourceUri($name).'/{'.$base.'}'; + + $action = $this->getResourceAction($name, $controller, 'update', $options); + + return $this->router->match(['PUT', 'PATCH'], $uri, $action); + } + + /** + * Add the destroy method for a resourceful route. + * + * @param string $name + * @param string $base + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\Route + */ + protected function addResourceDestroy($name, $base, $controller, $options) + { + $name = $this->getShallowName($name, $options); + + $uri = $this->getResourceUri($name).'/{'.$base.'}'; + + $action = $this->getResourceAction($name, $controller, 'destroy', $options); + + return $this->router->delete($uri, $action); + } + + /** + * Get the name for a given resource with shallowness applied when applicable. + * + * @param string $name + * @param array $options + * @return string + */ + protected function getShallowName($name, $options) + { + return isset($options['shallow']) && $options['shallow'] + ? last(explode('.', $name)) + : $name; + } + + /** + * Set the route's binding fields if the resource is scoped. + * + * @param \Illuminate\Routing\Route $route + * @param array $bindingFields + * @return void + */ + protected function setResourceBindingFields($route, $bindingFields) + { + preg_match_all('/(?<={).*?(?=})/', $route->uri, $matches); + + $fields = array_fill_keys($matches[0], null); + + $route->setBindingFields(array_replace( + $fields, array_intersect_key($bindingFields, $fields) + )); + } + + /** + * Get the base resource URI for a given resource. + * + * @param string $resource + * @return string + */ + public function getResourceUri($resource) + { + if (! Str::contains($resource, '.')) { + return $resource; + } + + // Once we have built the base URI, we'll remove the parameter holder for this + // base resource name so that the individual route adders can suffix these + // paths however they need to, as some do not have any parameters at all. + $segments = explode('.', $resource); + + $uri = $this->getNestedResourceUri($segments); + + return str_replace('/{'.$this->getResourceWildcard(end($segments)).'}', '', $uri); + } + + /** + * Get the URI for a nested resource segment array. + * + * @param array $segments + * @return string + */ + protected function getNestedResourceUri(array $segments) + { + // We will spin through the segments and create a place-holder for each of the + // resource segments, as well as the resource itself. Then we should get an + // entire string for the resource URI that contains all nested resources. + return implode('/', array_map(function ($s) { + return $s.'/{'.$this->getResourceWildcard($s).'}'; + }, $segments)); + } + + /** + * Format a resource parameter for usage. + * + * @param string $value + * @return string + */ + public function getResourceWildcard($value) + { + if (isset($this->parameters[$value])) { + $value = $this->parameters[$value]; + } elseif (isset(static::$parameterMap[$value])) { + $value = static::$parameterMap[$value]; + } elseif ($this->parameters === 'singular' || static::$singularParameters) { + $value = Str::singular($value); + } + + return str_replace('-', '_', $value); + } + + /** + * Get the action array for a resource route. + * + * @param string $resource + * @param string $controller + * @param string $method + * @param array $options + * @return array + */ + protected function getResourceAction($resource, $controller, $method, $options) + { + $name = $this->getResourceRouteName($resource, $method, $options); + + $action = ['as' => $name, 'uses' => $controller.'@'.$method]; + + if (isset($options['middleware'])) { + $action['middleware'] = $options['middleware']; + } + + if (isset($options['excluded_middleware'])) { + $action['excluded_middleware'] = $options['excluded_middleware']; + } + + if (isset($options['wheres'])) { + $action['where'] = $options['wheres']; + } + + if (isset($options['missing'])) { + $action['missing'] = $options['missing']; + } + + return $action; + } + + /** + * Get the name for a given resource. + * + * @param string $resource + * @param string $method + * @param array $options + * @return string + */ + protected function getResourceRouteName($resource, $method, $options) + { + $name = $resource; + + // If the names array has been provided to us we will check for an entry in the + // array first. We will also check for the specific method within this array + // so the names may be specified on a more "granular" level using methods. + if (isset($options['names'])) { + if (is_string($options['names'])) { + $name = $options['names']; + } elseif (isset($options['names'][$method])) { + return $options['names'][$method]; + } + } + + // If a global prefix has been assigned to all names for this resource, we will + // grab that so we can prepend it onto the name when we create this name for + // the resource action. Otherwise we'll just use an empty string for here. + $prefix = isset($options['as']) ? $options['as'].'.' : ''; + + return trim(sprintf('%s%s.%s', $prefix, $name, $method), '.'); + } + + /** + * Set or unset the unmapped global parameters to singular. + * + * @param bool $singular + * @return void + */ + public static function singularParameters($singular = true) + { + static::$singularParameters = (bool) $singular; + } + + /** + * Get the global parameter map. + * + * @return array + */ + public static function getParameters() + { + return static::$parameterMap; + } + + /** + * Set the global parameter mapping. + * + * @param array $parameters + * @return void + */ + public static function setParameters(array $parameters = []) + { + static::$parameterMap = $parameters; + } + + /** + * Get or set the action verbs used in the resource URIs. + * + * @param array $verbs + * @return array + */ + public static function verbs(array $verbs = []) + { + if (empty($verbs)) { + return static::$verbs; + } else { + static::$verbs = array_merge(static::$verbs, $verbs); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php new file mode 100644 index 0000000..8a914f8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php @@ -0,0 +1,266 @@ +view = $view; + $this->redirector = $redirector; + } + + /** + * Create a new response instance. + * + * @param mixed $content + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response + */ + public function make($content = '', $status = 200, array $headers = []) + { + return new Response($content, $status, $headers); + } + + /** + * Create a new "no content" response. + * + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response + */ + public function noContent($status = 204, array $headers = []) + { + return $this->make('', $status, $headers); + } + + /** + * Create a new response for a given view. + * + * @param string|array $view + * @param array $data + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response + */ + public function view($view, $data = [], $status = 200, array $headers = []) + { + if (is_array($view)) { + return $this->make($this->view->first($view, $data), $status, $headers); + } + + return $this->make($this->view->make($view, $data), $status, $headers); + } + + /** + * Create a new JSON response instance. + * + * @param mixed $data + * @param int $status + * @param array $headers + * @param int $options + * @return \Illuminate\Http\JsonResponse + */ + public function json($data = [], $status = 200, array $headers = [], $options = 0) + { + return new JsonResponse($data, $status, $headers, $options); + } + + /** + * Create a new JSONP response instance. + * + * @param string $callback + * @param mixed $data + * @param int $status + * @param array $headers + * @param int $options + * @return \Illuminate\Http\JsonResponse + */ + public function jsonp($callback, $data = [], $status = 200, array $headers = [], $options = 0) + { + return $this->json($data, $status, $headers, $options)->setCallback($callback); + } + + /** + * Create a new streamed response instance. + * + * @param \Closure $callback + * @param int $status + * @param array $headers + * @return \Symfony\Component\HttpFoundation\StreamedResponse + */ + public function stream($callback, $status = 200, array $headers = []) + { + return new StreamedResponse($callback, $status, $headers); + } + + /** + * Create a new streamed response instance as a file download. + * + * @param \Closure $callback + * @param string|null $name + * @param array $headers + * @param string|null $disposition + * @return \Symfony\Component\HttpFoundation\StreamedResponse + */ + public function streamDownload($callback, $name = null, array $headers = [], $disposition = 'attachment') + { + $response = new StreamedResponse($callback, 200, $headers); + + if (! is_null($name)) { + $response->headers->set('Content-Disposition', $response->headers->makeDisposition( + $disposition, + $name, + $this->fallbackName($name) + )); + } + + return $response; + } + + /** + * Create a new file download response. + * + * @param \SplFileInfo|string $file + * @param string|null $name + * @param array $headers + * @param string|null $disposition + * @return \Symfony\Component\HttpFoundation\BinaryFileResponse + */ + public function download($file, $name = null, array $headers = [], $disposition = 'attachment') + { + $response = new BinaryFileResponse($file, 200, $headers, true, $disposition); + + if (! is_null($name)) { + return $response->setContentDisposition($disposition, $name, $this->fallbackName($name)); + } + + return $response; + } + + /** + * Convert the string to ASCII characters that are equivalent to the given name. + * + * @param string $name + * @return string + */ + protected function fallbackName($name) + { + return str_replace('%', '', Str::ascii($name)); + } + + /** + * Return the raw contents of a binary file. + * + * @param \SplFileInfo|string $file + * @param array $headers + * @return \Symfony\Component\HttpFoundation\BinaryFileResponse + */ + public function file($file, array $headers = []) + { + return new BinaryFileResponse($file, 200, $headers); + } + + /** + * Create a new redirect response to the given path. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + */ + public function redirectTo($path, $status = 302, $headers = [], $secure = null) + { + return $this->redirector->to($path, $status, $headers, $secure); + } + + /** + * Create a new redirect response to a named route. + * + * @param string $route + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function redirectToRoute($route, $parameters = [], $status = 302, $headers = []) + { + return $this->redirector->route($route, $parameters, $status, $headers); + } + + /** + * Create a new redirect response to a controller action. + * + * @param string $action + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + */ + public function redirectToAction($action, $parameters = [], $status = 302, $headers = []) + { + return $this->redirector->action($action, $parameters, $status, $headers); + } + + /** + * Create a new redirect response, while putting the current URL in the session. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + */ + public function redirectGuest($path, $status = 302, $headers = [], $secure = null) + { + return $this->redirector->guest($path, $status, $headers, $secure); + } + + /** + * Create a new redirect response to the previously intended location. + * + * @param string $default + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + */ + public function redirectToIntended($default = '/', $status = 302, $headers = [], $secure = null) + { + return $this->redirector->intended($default, $status, $headers, $secure); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Route.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Route.php new file mode 100755 index 0000000..95e3cd3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Route.php @@ -0,0 +1,1310 @@ +uri = $uri; + $this->methods = (array) $methods; + $this->action = Arr::except($this->parseAction($action), ['prefix']); + + if (in_array('GET', $this->methods) && ! in_array('HEAD', $this->methods)) { + $this->methods[] = 'HEAD'; + } + + $this->prefix(is_array($action) ? Arr::get($action, 'prefix') : ''); + } + + /** + * Parse the route action into a standard array. + * + * @param callable|array|null $action + * @return array + * + * @throws \UnexpectedValueException + */ + protected function parseAction($action) + { + return RouteAction::parse($this->uri, $action); + } + + /** + * Run the route action and return the response. + * + * @return mixed + */ + public function run() + { + $this->container = $this->container ?: new Container; + + try { + if ($this->isControllerAction()) { + return $this->runController(); + } + + return $this->runCallable(); + } catch (HttpResponseException $e) { + return $e->getResponse(); + } + } + + /** + * Checks whether the route's action is a controller. + * + * @return bool + */ + protected function isControllerAction() + { + return is_string($this->action['uses']) && ! $this->isSerializedClosure(); + } + + /** + * Run the route action and return the response. + * + * @return mixed + */ + protected function runCallable() + { + $callable = $this->action['uses']; + + if ($this->isSerializedClosure()) { + $callable = unserialize($this->action['uses'])->getClosure(); + } + + return $callable(...array_values($this->resolveMethodDependencies( + $this->parametersWithoutNulls(), new ReflectionFunction($callable) + ))); + } + + /** + * Determine if the route action is a serialized Closure. + * + * @return bool + */ + protected function isSerializedClosure() + { + return RouteAction::containsSerializedClosure($this->action); + } + + /** + * Run the route action and return the response. + * + * @return mixed + * + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + */ + protected function runController() + { + return $this->controllerDispatcher()->dispatch( + $this, $this->getController(), $this->getControllerMethod() + ); + } + + /** + * Get the controller instance for the route. + * + * @return mixed + */ + public function getController() + { + if (! $this->controller) { + $class = $this->parseControllerCallback()[0]; + + $this->controller = $this->container->make(ltrim($class, '\\')); + } + + return $this->controller; + } + + /** + * Get the controller method used for the route. + * + * @return string + */ + protected function getControllerMethod() + { + return $this->parseControllerCallback()[1]; + } + + /** + * Parse the controller. + * + * @return array + */ + protected function parseControllerCallback() + { + return Str::parseCallback($this->action['uses']); + } + + /** + * Flush the cached container instance on the route. + * + * @return void + */ + public function flushController() + { + $this->computedMiddleware = null; + $this->controller = null; + } + + /** + * Determine if the route matches a given request. + * + * @param \Illuminate\Http\Request $request + * @param bool $includingMethod + * @return bool + */ + public function matches(Request $request, $includingMethod = true) + { + $this->compileRoute(); + + foreach (self::getValidators() as $validator) { + if (! $includingMethod && $validator instanceof MethodValidator) { + continue; + } + + if (! $validator->matches($this, $request)) { + return false; + } + } + + return true; + } + + /** + * Compile the route into a Symfony CompiledRoute instance. + * + * @return \Symfony\Component\Routing\CompiledRoute + */ + protected function compileRoute() + { + if (! $this->compiled) { + $this->compiled = $this->toSymfonyRoute()->compile(); + } + + return $this->compiled; + } + + /** + * Bind the route to a given request for execution. + * + * @param \Illuminate\Http\Request $request + * @return $this + */ + public function bind(Request $request) + { + $this->compileRoute(); + + $this->parameters = (new RouteParameterBinder($this)) + ->parameters($request); + + $this->originalParameters = $this->parameters; + + return $this; + } + + /** + * Determine if the route has parameters. + * + * @return bool + */ + public function hasParameters() + { + return isset($this->parameters); + } + + /** + * Determine a given parameter exists from the route. + * + * @param string $name + * @return bool + */ + public function hasParameter($name) + { + if ($this->hasParameters()) { + return array_key_exists($name, $this->parameters()); + } + + return false; + } + + /** + * Get a given parameter from the route. + * + * @param string $name + * @param string|object|null $default + * @return string|object|null + */ + public function parameter($name, $default = null) + { + return Arr::get($this->parameters(), $name, $default); + } + + /** + * Get original value of a given parameter from the route. + * + * @param string $name + * @param string|null $default + * @return string|null + */ + public function originalParameter($name, $default = null) + { + return Arr::get($this->originalParameters(), $name, $default); + } + + /** + * Set a parameter to the given value. + * + * @param string $name + * @param string|object|null $value + * @return void + */ + public function setParameter($name, $value) + { + $this->parameters(); + + $this->parameters[$name] = $value; + } + + /** + * Unset a parameter on the route if it is set. + * + * @param string $name + * @return void + */ + public function forgetParameter($name) + { + $this->parameters(); + + unset($this->parameters[$name]); + } + + /** + * Get the key / value list of parameters for the route. + * + * @return array + * + * @throws \LogicException + */ + public function parameters() + { + if (isset($this->parameters)) { + return $this->parameters; + } + + throw new LogicException('Route is not bound.'); + } + + /** + * Get the key / value list of original parameters for the route. + * + * @return array + * + * @throws \LogicException + */ + public function originalParameters() + { + if (isset($this->originalParameters)) { + return $this->originalParameters; + } + + throw new LogicException('Route is not bound.'); + } + + /** + * Get the key / value list of parameters without null values. + * + * @return array + */ + public function parametersWithoutNulls() + { + return array_filter($this->parameters(), function ($p) { + return ! is_null($p); + }); + } + + /** + * Get all of the parameter names for the route. + * + * @return array + */ + public function parameterNames() + { + if (isset($this->parameterNames)) { + return $this->parameterNames; + } + + return $this->parameterNames = $this->compileParameterNames(); + } + + /** + * Get the parameter names for the route. + * + * @return array + */ + protected function compileParameterNames() + { + preg_match_all('/\{(.*?)\}/', $this->getDomain().$this->uri, $matches); + + return array_map(function ($m) { + return trim($m, '?'); + }, $matches[1]); + } + + /** + * Get the parameters that are listed in the route / controller signature. + * + * @param string|null $subClass + * @return array + */ + public function signatureParameters($subClass = null) + { + return RouteSignatureParameters::fromAction($this->action, $subClass); + } + + /** + * Get the binding field for the given parameter. + * + * @param string|int $parameter + * @return string|null + */ + public function bindingFieldFor($parameter) + { + $fields = is_int($parameter) ? array_values($this->bindingFields) : $this->bindingFields; + + return $fields[$parameter] ?? null; + } + + /** + * Get the binding fields for the route. + * + * @return array + */ + public function bindingFields() + { + return $this->bindingFields ?? []; + } + + /** + * Set the binding fields for the route. + * + * @param array $bindingFields + * @return $this + */ + public function setBindingFields(array $bindingFields) + { + $this->bindingFields = $bindingFields; + + return $this; + } + + /** + * Get the parent parameter of the given parameter. + * + * @param string $parameter + * @return string + */ + public function parentOfParameter($parameter) + { + $key = array_search($parameter, array_keys($this->parameters)); + + if ($key === 0) { + return; + } + + return array_values($this->parameters)[$key - 1]; + } + + /** + * Allow "trashed" models to be retrieved when resolving implicit model bindings for this route. + * + * @param bool $withTrashed + * @return $this + */ + public function withTrashed($withTrashed = true) + { + $this->withTrashedBindings = $withTrashed; + + return $this; + } + + /** + * Determines if the route allows "trashed" models to be retrieved when resolving implicit model bindings. + * + * @return bool + */ + public function allowsTrashedBindings() + { + return $this->withTrashedBindings; + } + + /** + * Set a default value for the route. + * + * @param string $key + * @param mixed $value + * @return $this + */ + public function defaults($key, $value) + { + $this->defaults[$key] = $value; + + return $this; + } + + /** + * Set the default values for the route. + * + * @param array $defaults + * @return $this + */ + public function setDefaults(array $defaults) + { + $this->defaults = $defaults; + + return $this; + } + + /** + * Set a regular expression requirement on the route. + * + * @param array|string $name + * @param string|null $expression + * @return $this + */ + public function where($name, $expression = null) + { + foreach ($this->parseWhere($name, $expression) as $name => $expression) { + $this->wheres[$name] = $expression; + } + + return $this; + } + + /** + * Parse arguments to the where method into an array. + * + * @param array|string $name + * @param string $expression + * @return array + */ + protected function parseWhere($name, $expression) + { + return is_array($name) ? $name : [$name => $expression]; + } + + /** + * Set a list of regular expression requirements on the route. + * + * @param array $wheres + * @return $this + */ + public function setWheres(array $wheres) + { + foreach ($wheres as $name => $expression) { + $this->where($name, $expression); + } + + return $this; + } + + /** + * Mark this route as a fallback route. + * + * @return $this + */ + public function fallback() + { + $this->isFallback = true; + + return $this; + } + + /** + * Set the fallback value. + * + * @param bool $isFallback + * @return $this + */ + public function setFallback($isFallback) + { + $this->isFallback = $isFallback; + + return $this; + } + + /** + * Get the HTTP verbs the route responds to. + * + * @return array + */ + public function methods() + { + return $this->methods; + } + + /** + * Determine if the route only responds to HTTP requests. + * + * @return bool + */ + public function httpOnly() + { + return in_array('http', $this->action, true); + } + + /** + * Determine if the route only responds to HTTPS requests. + * + * @return bool + */ + public function httpsOnly() + { + return $this->secure(); + } + + /** + * Determine if the route only responds to HTTPS requests. + * + * @return bool + */ + public function secure() + { + return in_array('https', $this->action, true); + } + + /** + * Get or set the domain for the route. + * + * @param string|null $domain + * @return $this|string|null + */ + public function domain($domain = null) + { + if (is_null($domain)) { + return $this->getDomain(); + } + + $parsed = RouteUri::parse($domain); + + $this->action['domain'] = $parsed->uri; + + $this->bindingFields = array_merge( + $this->bindingFields, $parsed->bindingFields + ); + + return $this; + } + + /** + * Get the domain defined for the route. + * + * @return string|null + */ + public function getDomain() + { + return isset($this->action['domain']) + ? str_replace(['http://', 'https://'], '', $this->action['domain']) : null; + } + + /** + * Get the prefix of the route instance. + * + * @return string|null + */ + public function getPrefix() + { + return $this->action['prefix'] ?? null; + } + + /** + * Add a prefix to the route URI. + * + * @param string $prefix + * @return $this + */ + public function prefix($prefix) + { + $prefix = $prefix ?? ''; + + $this->updatePrefixOnAction($prefix); + + $uri = rtrim($prefix, '/').'/'.ltrim($this->uri, '/'); + + return $this->setUri($uri !== '/' ? trim($uri, '/') : $uri); + } + + /** + * Update the "prefix" attribute on the action array. + * + * @param string $prefix + * @return void + */ + protected function updatePrefixOnAction($prefix) + { + if (! empty($newPrefix = trim(rtrim($prefix, '/').'/'.ltrim($this->action['prefix'] ?? '', '/'), '/'))) { + $this->action['prefix'] = $newPrefix; + } + } + + /** + * Get the URI associated with the route. + * + * @return string + */ + public function uri() + { + return $this->uri; + } + + /** + * Set the URI that the route responds to. + * + * @param string $uri + * @return $this + */ + public function setUri($uri) + { + $this->uri = $this->parseUri($uri); + + return $this; + } + + /** + * Parse the route URI and normalize / store any implicit binding fields. + * + * @param string $uri + * @return string + */ + protected function parseUri($uri) + { + $this->bindingFields = []; + + return tap(RouteUri::parse($uri), function ($uri) { + $this->bindingFields = $uri->bindingFields; + })->uri; + } + + /** + * Get the name of the route instance. + * + * @return string|null + */ + public function getName() + { + return $this->action['as'] ?? null; + } + + /** + * Add or change the route name. + * + * @param string $name + * @return $this + */ + public function name($name) + { + $this->action['as'] = isset($this->action['as']) ? $this->action['as'].$name : $name; + + return $this; + } + + /** + * Determine whether the route's name matches the given patterns. + * + * @param mixed ...$patterns + * @return bool + */ + public function named(...$patterns) + { + if (is_null($routeName = $this->getName())) { + return false; + } + + foreach ($patterns as $pattern) { + if (Str::is($pattern, $routeName)) { + return true; + } + } + + return false; + } + + /** + * Set the handler for the route. + * + * @param \Closure|array|string $action + * @return $this + */ + public function uses($action) + { + if (is_array($action)) { + $action = $action[0].'@'.$action[1]; + } + + $action = is_string($action) ? $this->addGroupNamespaceToStringUses($action) : $action; + + return $this->setAction(array_merge($this->action, $this->parseAction([ + 'uses' => $action, + 'controller' => $action, + ]))); + } + + /** + * Parse a string based action for the "uses" fluent method. + * + * @param string $action + * @return string + */ + protected function addGroupNamespaceToStringUses($action) + { + $groupStack = last($this->router->getGroupStack()); + + if (isset($groupStack['namespace']) && strpos($action, '\\') !== 0) { + return $groupStack['namespace'].'\\'.$action; + } + + return $action; + } + + /** + * Get the action name for the route. + * + * @return string + */ + public function getActionName() + { + return $this->action['controller'] ?? 'Closure'; + } + + /** + * Get the method name of the route action. + * + * @return string + */ + public function getActionMethod() + { + return Arr::last(explode('@', $this->getActionName())); + } + + /** + * Get the action array or one of its properties for the route. + * + * @param string|null $key + * @return mixed + */ + public function getAction($key = null) + { + return Arr::get($this->action, $key); + } + + /** + * Set the action array for the route. + * + * @param array $action + * @return $this + */ + public function setAction(array $action) + { + $this->action = $action; + + if (isset($this->action['domain'])) { + $this->domain($this->action['domain']); + } + + return $this; + } + + /** + * Get the value of the action that should be taken on a missing model exception. + * + * @return \Closure|null + */ + public function getMissing() + { + $missing = $this->action['missing'] ?? null; + + return is_string($missing) && + Str::startsWith($missing, [ + 'C:32:"Opis\\Closure\\SerializableClosure', + 'O:47:"Laravel\\SerializableClosure\\SerializableClosure', + ]) ? unserialize($missing) : $missing; + } + + /** + * Define the callable that should be invoked on a missing model exception. + * + * @param \Closure $missing + * @return $this + */ + public function missing($missing) + { + $this->action['missing'] = $missing; + + return $this; + } + + /** + * Get all middleware, including the ones from the controller. + * + * @return array + */ + public function gatherMiddleware() + { + if (! is_null($this->computedMiddleware)) { + return $this->computedMiddleware; + } + + $this->computedMiddleware = []; + + return $this->computedMiddleware = Router::uniqueMiddleware(array_merge( + $this->middleware(), $this->controllerMiddleware() + )); + } + + /** + * Get or set the middlewares attached to the route. + * + * @param array|string|null $middleware + * @return $this|array + */ + public function middleware($middleware = null) + { + if (is_null($middleware)) { + return (array) ($this->action['middleware'] ?? []); + } + + if (! is_array($middleware)) { + $middleware = func_get_args(); + } + + foreach ($middleware as $index => $value) { + $middleware[$index] = (string) $value; + } + + $this->action['middleware'] = array_merge( + (array) ($this->action['middleware'] ?? []), $middleware + ); + + return $this; + } + + /** + * Specify that the "Authorize" / "can" middleware should be applied to the route with the given options. + * + * @param string $ability + * @param array|string $models + * @return $this + */ + public function can($ability, $models = []) + { + return empty($models) + ? $this->middleware(['can:'.$ability]) + : $this->middleware(['can:'.$ability.','.implode(',', Arr::wrap($models))]); + } + + /** + * Get the middleware for the route's controller. + * + * @return array + */ + public function controllerMiddleware() + { + if (! $this->isControllerAction()) { + return []; + } + + return $this->controllerDispatcher()->getMiddleware( + $this->getController(), $this->getControllerMethod() + ); + } + + /** + * Specify middleware that should be removed from the given route. + * + * @param array|string $middleware + * @return $this|array + */ + public function withoutMiddleware($middleware) + { + $this->action['excluded_middleware'] = array_merge( + (array) ($this->action['excluded_middleware'] ?? []), Arr::wrap($middleware) + ); + + return $this; + } + + /** + * Get the middleware should be removed from the route. + * + * @return array + */ + public function excludedMiddleware() + { + return (array) ($this->action['excluded_middleware'] ?? []); + } + + /** + * Indicate that the route should enforce scoping of multiple implicit Eloquent bindings. + * + * @return bool + */ + public function scopeBindings() + { + $this->action['scope_bindings'] = true; + + return $this; + } + + /** + * Determine if the route should enforce scoping of multiple implicit Eloquent bindings. + * + * @return bool + */ + public function enforcesScopedBindings() + { + return (bool) ($this->action['scope_bindings'] ?? false); + } + + /** + * Specify that the route should not allow concurrent requests from the same session. + * + * @param int|null $lockSeconds + * @param int|null $waitSeconds + * @return $this + */ + public function block($lockSeconds = 10, $waitSeconds = 10) + { + $this->lockSeconds = $lockSeconds; + $this->waitSeconds = $waitSeconds; + + return $this; + } + + /** + * Specify that the route should allow concurrent requests from the same session. + * + * @return $this + */ + public function withoutBlocking() + { + return $this->block(null, null); + } + + /** + * Get the maximum number of seconds the route's session lock should be held for. + * + * @return int|null + */ + public function locksFor() + { + return $this->lockSeconds; + } + + /** + * Get the maximum number of seconds to wait while attempting to acquire a session lock. + * + * @return int|null + */ + public function waitsFor() + { + return $this->waitSeconds; + } + + /** + * Get the dispatcher for the route's controller. + * + * @return \Illuminate\Routing\Contracts\ControllerDispatcher + */ + public function controllerDispatcher() + { + if ($this->container->bound(ControllerDispatcherContract::class)) { + return $this->container->make(ControllerDispatcherContract::class); + } + + return new ControllerDispatcher($this->container); + } + + /** + * Get the route validators for the instance. + * + * @return array + */ + public static function getValidators() + { + if (isset(static::$validators)) { + return static::$validators; + } + + // To match the route, we will use a chain of responsibility pattern with the + // validator implementations. We will spin through each one making sure it + // passes and then we will know if the route as a whole matches request. + return static::$validators = [ + new UriValidator, new MethodValidator, + new SchemeValidator, new HostValidator, + ]; + } + + /** + * Convert the route to a Symfony route. + * + * @return \Symfony\Component\Routing\Route + */ + public function toSymfonyRoute() + { + return new SymfonyRoute( + preg_replace('/\{(\w+?)\?\}/', '{$1}', $this->uri()), $this->getOptionalParameterNames(), + $this->wheres, ['utf8' => true, 'action' => $this->action], + $this->getDomain() ?: '', [], $this->methods + ); + } + + /** + * Get the optional parameter names for the route. + * + * @return array + */ + protected function getOptionalParameterNames() + { + preg_match_all('/\{(\w+?)\?\}/', $this->uri(), $matches); + + return isset($matches[1]) ? array_fill_keys($matches[1], null) : []; + } + + /** + * Get the compiled version of the route. + * + * @return \Symfony\Component\Routing\CompiledRoute + */ + public function getCompiled() + { + return $this->compiled; + } + + /** + * Set the router instance on the route. + * + * @param \Illuminate\Routing\Router $router + * @return $this + */ + public function setRouter(Router $router) + { + $this->router = $router; + + return $this; + } + + /** + * Set the container instance on the route. + * + * @param \Illuminate\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } + + /** + * Prepare the route instance for serialization. + * + * @return void + * + * @throws \LogicException + */ + public function prepareForSerialization() + { + if ($this->action['uses'] instanceof Closure) { + $this->action['uses'] = serialize(\PHP_VERSION_ID < 70400 + ? new OpisSerializableClosure($this->action['uses']) + : new SerializableClosure($this->action['uses']) + ); + } + + if (isset($this->action['missing']) && $this->action['missing'] instanceof Closure) { + $this->action['missing'] = serialize(\PHP_VERSION_ID < 70400 + ? new OpisSerializableClosure($this->action['missing']) + : new SerializableClosure($this->action['missing']) + ); + } + + $this->compileRoute(); + + unset($this->router, $this->container); + } + + /** + * Dynamically access route parameters. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->parameter($key); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteAction.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteAction.php new file mode 100644 index 0000000..b356f97 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteAction.php @@ -0,0 +1,111 @@ + $action] : [ + 'uses' => $action[0].'@'.$action[1], + 'controller' => $action[0].'@'.$action[1], + ]; + } + + // If no "uses" property has been set, we will dig through the array to find a + // Closure instance within this list. We will set the first Closure we come + // across into the "uses" property that will get fired off by this route. + elseif (! isset($action['uses'])) { + $action['uses'] = static::findCallable($action); + } + + if (! static::containsSerializedClosure($action) && is_string($action['uses']) && ! Str::contains($action['uses'], '@')) { + $action['uses'] = static::makeInvokable($action['uses']); + } + + return $action; + } + + /** + * Get an action for a route that has no action. + * + * @param string $uri + * @return array + * + * @throws \LogicException + */ + protected static function missingAction($uri) + { + return ['uses' => function () use ($uri) { + throw new LogicException("Route for [{$uri}] has no action."); + }]; + } + + /** + * Find the callable in an action array. + * + * @param array $action + * @return callable + */ + protected static function findCallable(array $action) + { + return Arr::first($action, function ($value, $key) { + return Reflector::isCallable($value) && is_numeric($key); + }); + } + + /** + * Make an action for an invokable controller. + * + * @param string $action + * @return string + * + * @throws \UnexpectedValueException + */ + protected static function makeInvokable($action) + { + if (! method_exists($action, '__invoke')) { + throw new UnexpectedValueException("Invalid route action: [{$action}]."); + } + + return $action.'@__invoke'; + } + + /** + * Determine if the given array actions contain a serialized Closure. + * + * @param array $action + * @return bool + */ + public static function containsSerializedClosure(array $action) + { + return is_string($action['uses']) && Str::startsWith($action['uses'], [ + 'C:32:"Opis\\Closure\\SerializableClosure', + 'O:47:"Laravel\\SerializableClosure\\SerializableClosure', + ]) !== false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteBinding.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteBinding.php new file mode 100644 index 0000000..133a84a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteBinding.php @@ -0,0 +1,84 @@ +make($class), $method]; + + return $callable($value, $route); + }; + } + + /** + * Create a Route model binding for a model. + * + * @param \Illuminate\Container\Container $container + * @param string $class + * @param \Closure|null $callback + * @return \Closure + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public static function forModel($container, $class, $callback = null) + { + return function ($value) use ($container, $class, $callback) { + if (is_null($value)) { + return; + } + + // For model binders, we will attempt to retrieve the models using the first + // method on the model instance. If we cannot retrieve the models we'll + // throw a not found exception otherwise we will return the instance. + $instance = $container->make($class); + + if ($model = $instance->resolveRouteBinding($value)) { + return $model; + } + + // If a callback was supplied to the method we will call that to determine + // what we should do when the model is not found. This just gives these + // developer a little greater flexibility to decide what will happen. + if ($callback instanceof Closure) { + return $callback($value); + } + + throw (new ModelNotFoundException)->setModel($class); + }; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php new file mode 100644 index 0000000..7e6f98b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php @@ -0,0 +1,268 @@ +addToCollections($route); + + $this->addLookups($route); + + return $route; + } + + /** + * Add the given route to the arrays of routes. + * + * @param \Illuminate\Routing\Route $route + * @return void + */ + protected function addToCollections($route) + { + $domainAndUri = $route->getDomain().$route->uri(); + + foreach ($route->methods() as $method) { + $this->routes[$method][$domainAndUri] = $route; + } + + $this->allRoutes[$method.$domainAndUri] = $route; + } + + /** + * Add the route to any look-up tables if necessary. + * + * @param \Illuminate\Routing\Route $route + * @return void + */ + protected function addLookups($route) + { + // If the route has a name, we will add it to the name look-up table so that we + // will quickly be able to find any route associate with a name and not have + // to iterate through every route every time we need to perform a look-up. + if ($name = $route->getName()) { + $this->nameList[$name] = $route; + } + + // When the route is routing to a controller we will also store the action that + // is used by the route. This will let us reverse route to controllers while + // processing a request and easily generate URLs to the given controllers. + $action = $route->getAction(); + + if (isset($action['controller'])) { + $this->addToActionList($action, $route); + } + } + + /** + * Add a route to the controller action dictionary. + * + * @param array $action + * @param \Illuminate\Routing\Route $route + * @return void + */ + protected function addToActionList($action, $route) + { + $this->actionList[trim($action['controller'], '\\')] = $route; + } + + /** + * Refresh the name look-up table. + * + * This is done in case any names are fluently defined or if routes are overwritten. + * + * @return void + */ + public function refreshNameLookups() + { + $this->nameList = []; + + foreach ($this->allRoutes as $route) { + if ($route->getName()) { + $this->nameList[$route->getName()] = $route; + } + } + } + + /** + * Refresh the action look-up table. + * + * This is done in case any actions are overwritten with new controllers. + * + * @return void + */ + public function refreshActionLookups() + { + $this->actionList = []; + + foreach ($this->allRoutes as $route) { + if (isset($route->getAction()['controller'])) { + $this->addToActionList($route->getAction(), $route); + } + } + } + + /** + * Find the first route matching a given request. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Routing\Route + * + * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + */ + public function match(Request $request) + { + $routes = $this->get($request->getMethod()); + + // First, we will see if we can find a matching route for this current request + // method. If we can, great, we can just return it so that it can be called + // by the consumer. Otherwise we will check for routes with another verb. + $route = $this->matchAgainstRoutes($routes, $request); + + return $this->handleMatchedRoute($request, $route); + } + + /** + * Get routes from the collection by method. + * + * @param string|null $method + * @return \Illuminate\Routing\Route[] + */ + public function get($method = null) + { + return is_null($method) ? $this->getRoutes() : Arr::get($this->routes, $method, []); + } + + /** + * Determine if the route collection contains a given named route. + * + * @param string $name + * @return bool + */ + public function hasNamedRoute($name) + { + return ! is_null($this->getByName($name)); + } + + /** + * Get a route instance by its name. + * + * @param string $name + * @return \Illuminate\Routing\Route|null + */ + public function getByName($name) + { + return $this->nameList[$name] ?? null; + } + + /** + * Get a route instance by its controller action. + * + * @param string $action + * @return \Illuminate\Routing\Route|null + */ + public function getByAction($action) + { + return $this->actionList[$action] ?? null; + } + + /** + * Get all of the routes in the collection. + * + * @return \Illuminate\Routing\Route[] + */ + public function getRoutes() + { + return array_values($this->allRoutes); + } + + /** + * Get all of the routes keyed by their HTTP verb / method. + * + * @return array + */ + public function getRoutesByMethod() + { + return $this->routes; + } + + /** + * Get all of the routes keyed by their name. + * + * @return \Illuminate\Routing\Route[] + */ + public function getRoutesByName() + { + return $this->nameList; + } + + /** + * Convert the collection to a Symfony RouteCollection instance. + * + * @return \Symfony\Component\Routing\RouteCollection + */ + public function toSymfonyRouteCollection() + { + $symfonyRoutes = parent::toSymfonyRouteCollection(); + + $this->refreshNameLookups(); + + return $symfonyRoutes; + } + + /** + * Convert the collection to a CompiledRouteCollection instance. + * + * @param \Illuminate\Routing\Router $router + * @param \Illuminate\Container\Container $container + * @return \Illuminate\Routing\CompiledRouteCollection + */ + public function toCompiledRouteCollection(Router $router, Container $container) + { + ['compiled' => $compiled, 'attributes' => $attributes] = $this->compile(); + + return (new CompiledRouteCollection($compiled, $attributes)) + ->setRouter($router) + ->setContainer($container); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollectionInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollectionInterface.php new file mode 100644 index 0000000..8e25d0f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollectionInterface.php @@ -0,0 +1,98 @@ +resolveMethodDependencies( + $parameters, new ReflectionMethod($instance, $method) + ); + } + + /** + * Resolve the given method's type-hinted dependencies. + * + * @param array $parameters + * @param \ReflectionFunctionAbstract $reflector + * @return array + */ + public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector) + { + $instanceCount = 0; + + $values = array_values($parameters); + + $skippableValue = new \stdClass; + + foreach ($reflector->getParameters() as $key => $parameter) { + $instance = $this->transformDependency($parameter, $parameters, $skippableValue); + + if ($instance !== $skippableValue) { + $instanceCount++; + + $this->spliceIntoParameters($parameters, $key, $instance); + } elseif (! isset($values[$key - $instanceCount]) && + $parameter->isDefaultValueAvailable()) { + $this->spliceIntoParameters($parameters, $key, $parameter->getDefaultValue()); + } + } + + return $parameters; + } + + /** + * Attempt to transform the given parameter into a class instance. + * + * @param \ReflectionParameter $parameter + * @param array $parameters + * @param object $skippableValue + * @return mixed + */ + protected function transformDependency(ReflectionParameter $parameter, $parameters, $skippableValue) + { + $className = Reflector::getParameterClassName($parameter); + + // If the parameter has a type-hinted class, we will check to see if it is already in + // the list of parameters. If it is we will just skip it as it is probably a model + // binding and we do not want to mess with those; otherwise, we resolve it here. + if ($className && ! $this->alreadyInParameters($className, $parameters)) { + return $parameter->isDefaultValueAvailable() ? null : $this->container->make($className); + } + + return $skippableValue; + } + + /** + * Determine if an object of the given class is in a list of parameters. + * + * @param string $class + * @param array $parameters + * @return bool + */ + protected function alreadyInParameters($class, array $parameters) + { + return ! is_null(Arr::first($parameters, function ($value) use ($class) { + return $value instanceof $class; + })); + } + + /** + * Splice the given value into the parameter list. + * + * @param array $parameters + * @param string $offset + * @param mixed $value + * @return void + */ + protected function spliceIntoParameters(array &$parameters, $offset, $value) + { + array_splice( + $parameters, $offset, 0, [$value] + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteFileRegistrar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteFileRegistrar.php new file mode 100644 index 0000000..7670b10 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteFileRegistrar.php @@ -0,0 +1,37 @@ +router = $router; + } + + /** + * Require the given routes file. + * + * @param string $routes + * @return void + */ + public function register($routes) + { + $router = $this->router; + + require $routes; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteGroup.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteGroup.php new file mode 100644 index 0000000..18dbb52 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteGroup.php @@ -0,0 +1,105 @@ + static::formatNamespace($new, $old), + 'prefix' => static::formatPrefix($new, $old, $prependExistingPrefix), + 'where' => static::formatWhere($new, $old), + ]); + + return array_merge_recursive(Arr::except( + $old, ['namespace', 'prefix', 'where', 'as'] + ), $new); + } + + /** + * Format the namespace for the new group attributes. + * + * @param array $new + * @param array $old + * @return string|null + */ + protected static function formatNamespace($new, $old) + { + if (isset($new['namespace'])) { + return isset($old['namespace']) && strpos($new['namespace'], '\\') !== 0 + ? trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\') + : trim($new['namespace'], '\\'); + } + + return $old['namespace'] ?? null; + } + + /** + * Format the prefix for the new group attributes. + * + * @param array $new + * @param array $old + * @param bool $prependExistingPrefix + * @return string|null + */ + protected static function formatPrefix($new, $old, $prependExistingPrefix = true) + { + $old = $old['prefix'] ?? ''; + + if ($prependExistingPrefix) { + return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old; + } else { + return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old; + } + } + + /** + * Format the "wheres" for the new group attributes. + * + * @param array $new + * @param array $old + * @return array + */ + protected static function formatWhere($new, $old) + { + return array_merge( + $old['where'] ?? [], + $new['where'] ?? [] + ); + } + + /** + * Format the "as" clause of the new group attributes. + * + * @param array $new + * @param array $old + * @return array + */ + protected static function formatAs($new, $old) + { + if (isset($old['as'])) { + $new['as'] = $old['as'].($new['as'] ?? ''); + } + + return $new; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteParameterBinder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteParameterBinder.php new file mode 100644 index 0000000..8c3968e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteParameterBinder.php @@ -0,0 +1,117 @@ +route = $route; + } + + /** + * Get the parameters for the route. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + public function parameters($request) + { + $parameters = $this->bindPathParameters($request); + + // If the route has a regular expression for the host part of the URI, we will + // compile that and get the parameter matches for this domain. We will then + // merge them into this parameters array so that this array is completed. + if (! is_null($this->route->compiled->getHostRegex())) { + $parameters = $this->bindHostParameters( + $request, $parameters + ); + } + + return $this->replaceDefaults($parameters); + } + + /** + * Get the parameter matches for the path portion of the URI. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + protected function bindPathParameters($request) + { + $path = '/'.ltrim($request->decodedPath(), '/'); + + preg_match($this->route->compiled->getRegex(), $path, $matches); + + return $this->matchToKeys(array_slice($matches, 1)); + } + + /** + * Extract the parameter list from the host part of the request. + * + * @param \Illuminate\Http\Request $request + * @param array $parameters + * @return array + */ + protected function bindHostParameters($request, $parameters) + { + preg_match($this->route->compiled->getHostRegex(), $request->getHost(), $matches); + + return array_merge($this->matchToKeys(array_slice($matches, 1)), $parameters); + } + + /** + * Combine a set of parameter matches with the route's keys. + * + * @param array $matches + * @return array + */ + protected function matchToKeys(array $matches) + { + if (empty($parameterNames = $this->route->parameterNames())) { + return []; + } + + $parameters = array_intersect_key($matches, array_flip($parameterNames)); + + return array_filter($parameters, function ($value) { + return is_string($value) && strlen($value) > 0; + }); + } + + /** + * Replace null parameters with their defaults. + * + * @param array $parameters + * @return array + */ + protected function replaceDefaults(array $parameters) + { + foreach ($parameters as $key => $value) { + $parameters[$key] = $value ?? Arr::get($this->route->defaults, $key); + } + + foreach ($this->route->defaults as $key => $value) { + if (! isset($parameters[$key])) { + $parameters[$key] = $value; + } + } + + return $parameters; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteRegistrar.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteRegistrar.php new file mode 100644 index 0000000..64c1359 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteRegistrar.php @@ -0,0 +1,254 @@ + 'as', + 'scopeBindings' => 'scope_bindings', + 'withoutMiddleware' => 'excluded_middleware', + ]; + + /** + * Create a new route registrar instance. + * + * @param \Illuminate\Routing\Router $router + * @return void + */ + public function __construct(Router $router) + { + $this->router = $router; + } + + /** + * Set the value for a given attribute. + * + * @param string $key + * @param mixed $value + * @return $this + * + * @throws \InvalidArgumentException + */ + public function attribute($key, $value) + { + if (! in_array($key, $this->allowedAttributes)) { + throw new InvalidArgumentException("Attribute [{$key}] does not exist."); + } + + if ($key === 'middleware') { + foreach ($value as $index => $middleware) { + $value[$index] = (string) $middleware; + } + } + + $attributeKey = Arr::get($this->aliases, $key, $key); + + if ($key === 'withoutMiddleware') { + $value = array_merge( + (array) ($this->attributes[$attributeKey] ?? []), Arr::wrap($value) + ); + } + + $this->attributes[$attributeKey] = $value; + + return $this; + } + + /** + * Route a resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function resource($name, $controller, array $options = []) + { + return $this->router->resource($name, $controller, $this->attributes + $options); + } + + /** + * Route an API resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function apiResource($name, $controller, array $options = []) + { + return $this->router->apiResource($name, $controller, $this->attributes + $options); + } + + /** + * Create a route group with shared attributes. + * + * @param \Closure|string $callback + * @return void + */ + public function group($callback) + { + $this->router->group($this->attributes, $callback); + } + + /** + * Register a new route with the given verbs. + * + * @param array|string $methods + * @param string $uri + * @param \Closure|array|string|null $action + * @return \Illuminate\Routing\Route + */ + public function match($methods, $uri, $action = null) + { + return $this->router->match($methods, $uri, $this->compileAction($action)); + } + + /** + * Register a new route with the router. + * + * @param string $method + * @param string $uri + * @param \Closure|array|string|null $action + * @return \Illuminate\Routing\Route + */ + protected function registerRoute($method, $uri, $action = null) + { + if (! is_array($action)) { + $action = array_merge($this->attributes, $action ? ['uses' => $action] : []); + } + + return $this->router->{$method}($uri, $this->compileAction($action)); + } + + /** + * Compile the action into an array including the attributes. + * + * @param \Closure|array|string|null $action + * @return array + */ + protected function compileAction($action) + { + if (is_null($action)) { + return $this->attributes; + } + + if (is_string($action) || $action instanceof Closure) { + $action = ['uses' => $action]; + } + + if (is_array($action) && + ! Arr::isAssoc($action) && + Reflector::isCallable($action)) { + if (strncmp($action[0], '\\', 1)) { + $action[0] = '\\'.$action[0]; + } + $action = [ + 'uses' => $action[0].'@'.$action[1], + 'controller' => $action[0].'@'.$action[1], + ]; + } + + return array_merge($this->attributes, $action); + } + + /** + * Dynamically handle calls into the route registrar. + * + * @param string $method + * @param array $parameters + * @return \Illuminate\Routing\Route|$this + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + if (in_array($method, $this->passthru)) { + return $this->registerRoute($method, ...$parameters); + } + + if (in_array($method, $this->allowedAttributes)) { + if ($method === 'middleware') { + return $this->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); + } + + return $this->attribute($method, array_key_exists(0, $parameters) ? $parameters[0] : true); + } + + throw new BadMethodCallException(sprintf( + 'Method %s::%s does not exist.', static::class, $method + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php new file mode 100644 index 0000000..03d3137 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php @@ -0,0 +1,50 @@ +getClosure() + : $action['uses']; + + $parameters = is_string($callback) + ? static::fromClassMethodString($callback) + : (new ReflectionFunction($callback))->getParameters(); + + return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) { + return Reflector::isParameterSubclassOf($p, $subClass); + }); + } + + /** + * Get the parameters for the given class / method by string. + * + * @param string $uses + * @return array + */ + protected static function fromClassMethodString($uses) + { + [$class, $method] = Str::parseCallback($uses); + + if (! method_exists($class, $method) && Reflector::isCallable($class, $method)) { + return []; + } + + return (new ReflectionMethod($class, $method))->getParameters(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteUri.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteUri.php new file mode 100644 index 0000000..ad69527 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteUri.php @@ -0,0 +1,62 @@ +uri = $uri; + $this->bindingFields = $bindingFields; + } + + /** + * Parse the given URI. + * + * @param string $uri + * @return static + */ + public static function parse($uri) + { + preg_match_all('/\{([\w\:]+?)\??\}/', $uri, $matches); + + $bindingFields = []; + + foreach ($matches[0] as $match) { + if (strpos($match, ':') === false) { + continue; + } + + $segments = explode(':', trim($match, '{}?')); + + $bindingFields[$segments[0]] = $segments[1]; + + $uri = strpos($match, '?') !== false + ? str_replace($match, '{'.$segments[0].'?}', $uri) + : str_replace($match, '{'.$segments[0].'}', $uri); + } + + return new static($uri, $bindingFields); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteUrlGenerator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteUrlGenerator.php new file mode 100644 index 0000000..5f12489 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RouteUrlGenerator.php @@ -0,0 +1,321 @@ + '/', + '%40' => '@', + '%3A' => ':', + '%3B' => ';', + '%2C' => ',', + '%3D' => '=', + '%2B' => '+', + '%21' => '!', + '%2A' => '*', + '%7C' => '|', + '%3F' => '?', + '%26' => '&', + '%23' => '#', + '%25' => '%', + ]; + + /** + * Create a new Route URL generator. + * + * @param \Illuminate\Routing\UrlGenerator $url + * @param \Illuminate\Http\Request $request + * @return void + */ + public function __construct($url, $request) + { + $this->url = $url; + $this->request = $request; + } + + /** + * Generate a URL for the given route. + * + * @param \Illuminate\Routing\Route $route + * @param array $parameters + * @param bool $absolute + * @return string + * + * @throws \Illuminate\Routing\Exceptions\UrlGenerationException + */ + public function to($route, $parameters = [], $absolute = false) + { + $domain = $this->getRouteDomain($route, $parameters); + + // First we will construct the entire URI including the root and query string. Once it + // has been constructed, we'll make sure we don't have any missing parameters or we + // will need to throw the exception to let the developers know one was not given. + $uri = $this->addQueryString($this->url->format( + $root = $this->replaceRootParameters($route, $domain, $parameters), + $this->replaceRouteParameters($route->uri(), $parameters), + $route + ), $parameters); + + if (preg_match_all('/{(.*?)}/', $uri, $matchedMissingParameters)) { + throw UrlGenerationException::forMissingParameters($route, $matchedMissingParameters[1]); + } + + // Once we have ensured that there are no missing parameters in the URI we will encode + // the URI and prepare it for returning to the developer. If the URI is supposed to + // be absolute, we will return it as-is. Otherwise we will remove the URL's root. + $uri = strtr(rawurlencode($uri), $this->dontEncode); + + if (! $absolute) { + $uri = preg_replace('#^(//|[^/?])+#', '', $uri); + + if ($base = $this->request->getBaseUrl()) { + $uri = preg_replace('#^'.$base.'#i', '', $uri); + } + + return '/'.ltrim($uri, '/'); + } + + return $uri; + } + + /** + * Get the formatted domain for a given route. + * + * @param \Illuminate\Routing\Route $route + * @param array $parameters + * @return string + */ + protected function getRouteDomain($route, &$parameters) + { + return $route->getDomain() ? $this->formatDomain($route, $parameters) : null; + } + + /** + * Format the domain and port for the route and request. + * + * @param \Illuminate\Routing\Route $route + * @param array $parameters + * @return string + */ + protected function formatDomain($route, &$parameters) + { + return $this->addPortToDomain( + $this->getRouteScheme($route).$route->getDomain() + ); + } + + /** + * Get the scheme for the given route. + * + * @param \Illuminate\Routing\Route $route + * @return string + */ + protected function getRouteScheme($route) + { + if ($route->httpOnly()) { + return 'http://'; + } elseif ($route->httpsOnly()) { + return 'https://'; + } + + return $this->url->formatScheme(); + } + + /** + * Add the port to the domain if necessary. + * + * @param string $domain + * @return string + */ + protected function addPortToDomain($domain) + { + $secure = $this->request->isSecure(); + + $port = (int) $this->request->getPort(); + + return ($secure && $port === 443) || (! $secure && $port === 80) + ? $domain : $domain.':'.$port; + } + + /** + * Replace the parameters on the root path. + * + * @param \Illuminate\Routing\Route $route + * @param string $domain + * @param array $parameters + * @return string + */ + protected function replaceRootParameters($route, $domain, &$parameters) + { + $scheme = $this->getRouteScheme($route); + + return $this->replaceRouteParameters( + $this->url->formatRoot($scheme, $domain), $parameters + ); + } + + /** + * Replace all of the wildcard parameters for a route path. + * + * @param string $path + * @param array $parameters + * @return string + */ + protected function replaceRouteParameters($path, array &$parameters) + { + $path = $this->replaceNamedParameters($path, $parameters); + + $path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) { + // Reset only the numeric keys... + $parameters = array_merge($parameters); + + return (! isset($parameters[0]) && ! Str::endsWith($match[0], '?}')) + ? $match[0] + : Arr::pull($parameters, 0); + }, $path); + + return trim(preg_replace('/\{.*?\?\}/', '', $path), '/'); + } + + /** + * Replace all of the named parameters in the path. + * + * @param string $path + * @param array $parameters + * @return string + */ + protected function replaceNamedParameters($path, &$parameters) + { + return preg_replace_callback('/\{(.*?)(\?)?\}/', function ($m) use (&$parameters) { + if (isset($parameters[$m[1]]) && $parameters[$m[1]] !== '') { + return Arr::pull($parameters, $m[1]); + } elseif (isset($this->defaultParameters[$m[1]])) { + return $this->defaultParameters[$m[1]]; + } elseif (isset($parameters[$m[1]])) { + Arr::pull($parameters, $m[1]); + } + + return $m[0]; + }, $path); + } + + /** + * Add a query string to the URI. + * + * @param string $uri + * @param array $parameters + * @return mixed|string + */ + protected function addQueryString($uri, array $parameters) + { + // If the URI has a fragment we will move it to the end of this URI since it will + // need to come after any query string that may be added to the URL else it is + // not going to be available. We will remove it then append it back on here. + if (! is_null($fragment = parse_url($uri, PHP_URL_FRAGMENT))) { + $uri = preg_replace('/#.*/', '', $uri); + } + + $uri .= $this->getRouteQueryString($parameters); + + return is_null($fragment) ? $uri : $uri."#{$fragment}"; + } + + /** + * Get the query string for a given route. + * + * @param array $parameters + * @return string + */ + protected function getRouteQueryString(array $parameters) + { + // First we will get all of the string parameters that are remaining after we + // have replaced the route wildcards. We'll then build a query string from + // these string parameters then use it as a starting point for the rest. + if (count($parameters) === 0) { + return ''; + } + + $query = Arr::query( + $keyed = $this->getStringParameters($parameters) + ); + + // Lastly, if there are still parameters remaining, we will fetch the numeric + // parameters that are in the array and add them to the query string or we + // will make the initial query string if it wasn't started with strings. + if (count($keyed) < count($parameters)) { + $query .= '&'.implode( + '&', $this->getNumericParameters($parameters) + ); + } + + $query = trim($query, '&'); + + return $query === '' ? '' : "?{$query}"; + } + + /** + * Get the string parameters from a given list. + * + * @param array $parameters + * @return array + */ + protected function getStringParameters(array $parameters) + { + return array_filter($parameters, 'is_string', ARRAY_FILTER_USE_KEY); + } + + /** + * Get the numeric parameters from a given list. + * + * @param array $parameters + * @return array + */ + protected function getNumericParameters(array $parameters) + { + return array_filter($parameters, 'is_numeric', ARRAY_FILTER_USE_KEY); + } + + /** + * Set the default named parameters used by the URL generator. + * + * @param array $defaults + * @return void + */ + public function defaults(array $defaults) + { + $this->defaultParameters = array_merge( + $this->defaultParameters, $defaults + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Router.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Router.php new file mode 100644 index 0000000..26f6ec9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/Router.php @@ -0,0 +1,1357 @@ +events = $events; + $this->routes = new RouteCollection; + $this->container = $container ?: new Container; + } + + /** + * Register a new GET route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function get($uri, $action = null) + { + return $this->addRoute(['GET', 'HEAD'], $uri, $action); + } + + /** + * Register a new POST route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function post($uri, $action = null) + { + return $this->addRoute('POST', $uri, $action); + } + + /** + * Register a new PUT route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function put($uri, $action = null) + { + return $this->addRoute('PUT', $uri, $action); + } + + /** + * Register a new PATCH route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function patch($uri, $action = null) + { + return $this->addRoute('PATCH', $uri, $action); + } + + /** + * Register a new DELETE route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function delete($uri, $action = null) + { + return $this->addRoute('DELETE', $uri, $action); + } + + /** + * Register a new OPTIONS route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function options($uri, $action = null) + { + return $this->addRoute('OPTIONS', $uri, $action); + } + + /** + * Register a new route responding to all verbs. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function any($uri, $action = null) + { + return $this->addRoute(self::$verbs, $uri, $action); + } + + /** + * Register a new Fallback route with the router. + * + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function fallback($action) + { + $placeholder = 'fallbackPlaceholder'; + + return $this->addRoute( + 'GET', "{{$placeholder}}", $action + )->where($placeholder, '.*')->fallback(); + } + + /** + * Create a redirect from one URI to another. + * + * @param string $uri + * @param string $destination + * @param int $status + * @return \Illuminate\Routing\Route + */ + public function redirect($uri, $destination, $status = 302) + { + return $this->any($uri, '\Illuminate\Routing\RedirectController') + ->defaults('destination', $destination) + ->defaults('status', $status); + } + + /** + * Create a permanent redirect from one URI to another. + * + * @param string $uri + * @param string $destination + * @return \Illuminate\Routing\Route + */ + public function permanentRedirect($uri, $destination) + { + return $this->redirect($uri, $destination, 301); + } + + /** + * Register a new route that returns a view. + * + * @param string $uri + * @param string $view + * @param array $data + * @param int|array $status + * @param array $headers + * @return \Illuminate\Routing\Route + */ + public function view($uri, $view, $data = [], $status = 200, array $headers = []) + { + return $this->match(['GET', 'HEAD'], $uri, '\Illuminate\Routing\ViewController') + ->setDefaults([ + 'view' => $view, + 'data' => $data, + 'status' => is_array($status) ? 200 : $status, + 'headers' => is_array($status) ? $status : $headers, + ]); + } + + /** + * Register a new route with the given verbs. + * + * @param array|string $methods + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function match($methods, $uri, $action = null) + { + return $this->addRoute(array_map('strtoupper', (array) $methods), $uri, $action); + } + + /** + * Register an array of resource controllers. + * + * @param array $resources + * @param array $options + * @return void + */ + public function resources(array $resources, array $options = []) + { + foreach ($resources as $name => $controller) { + $this->resource($name, $controller, $options); + } + } + + /** + * Route a resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function resource($name, $controller, array $options = []) + { + if ($this->container && $this->container->bound(ResourceRegistrar::class)) { + $registrar = $this->container->make(ResourceRegistrar::class); + } else { + $registrar = new ResourceRegistrar($this); + } + + return new PendingResourceRegistration( + $registrar, $name, $controller, $options + ); + } + + /** + * Register an array of API resource controllers. + * + * @param array $resources + * @param array $options + * @return void + */ + public function apiResources(array $resources, array $options = []) + { + foreach ($resources as $name => $controller) { + $this->apiResource($name, $controller, $options); + } + } + + /** + * Route an API resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingResourceRegistration + */ + public function apiResource($name, $controller, array $options = []) + { + $only = ['index', 'show', 'store', 'update', 'destroy']; + + if (isset($options['except'])) { + $only = array_diff($only, (array) $options['except']); + } + + return $this->resource($name, $controller, array_merge([ + 'only' => $only, + ], $options)); + } + + /** + * Create a route group with shared attributes. + * + * @param array $attributes + * @param \Closure|string $routes + * @return void + */ + public function group(array $attributes, $routes) + { + $this->updateGroupStack($attributes); + + // Once we have updated the group stack, we'll load the provided routes and + // merge in the group's attributes when the routes are created. After we + // have created the routes, we will pop the attributes off the stack. + $this->loadRoutes($routes); + + array_pop($this->groupStack); + } + + /** + * Update the group stack with the given attributes. + * + * @param array $attributes + * @return void + */ + protected function updateGroupStack(array $attributes) + { + if ($this->hasGroupStack()) { + $attributes = $this->mergeWithLastGroup($attributes); + } + + $this->groupStack[] = $attributes; + } + + /** + * Merge the given array with the last group stack. + * + * @param array $new + * @param bool $prependExistingPrefix + * @return array + */ + public function mergeWithLastGroup($new, $prependExistingPrefix = true) + { + return RouteGroup::merge($new, end($this->groupStack), $prependExistingPrefix); + } + + /** + * Load the provided routes. + * + * @param \Closure|string $routes + * @return void + */ + protected function loadRoutes($routes) + { + if ($routes instanceof Closure) { + $routes($this); + } else { + (new RouteFileRegistrar($this))->register($routes); + } + } + + /** + * Get the prefix from the last group on the stack. + * + * @return string + */ + public function getLastGroupPrefix() + { + if ($this->hasGroupStack()) { + $last = end($this->groupStack); + + return $last['prefix'] ?? ''; + } + + return ''; + } + + /** + * Add a route to the underlying route collection. + * + * @param array|string $methods + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + */ + public function addRoute($methods, $uri, $action) + { + return $this->routes->add($this->createRoute($methods, $uri, $action)); + } + + /** + * Create a new route instance. + * + * @param array|string $methods + * @param string $uri + * @param mixed $action + * @return \Illuminate\Routing\Route + */ + protected function createRoute($methods, $uri, $action) + { + // If the route is routing to a controller we will parse the route action into + // an acceptable array format before registering it and creating this route + // instance itself. We need to build the Closure that will call this out. + if ($this->actionReferencesController($action)) { + $action = $this->convertToControllerAction($action); + } + + $route = $this->newRoute( + $methods, $this->prefix($uri), $action + ); + + // If we have groups that need to be merged, we will merge them now after this + // route has already been created and is ready to go. After we're done with + // the merge we will be ready to return the route back out to the caller. + if ($this->hasGroupStack()) { + $this->mergeGroupAttributesIntoRoute($route); + } + + $this->addWhereClausesToRoute($route); + + return $route; + } + + /** + * Determine if the action is routing to a controller. + * + * @param mixed $action + * @return bool + */ + protected function actionReferencesController($action) + { + if (! $action instanceof Closure) { + return is_string($action) || (isset($action['uses']) && is_string($action['uses'])); + } + + return false; + } + + /** + * Add a controller based route action to the action array. + * + * @param array|string $action + * @return array + */ + protected function convertToControllerAction($action) + { + if (is_string($action)) { + $action = ['uses' => $action]; + } + + // Here we'll merge any group "controller" and "uses" statements if necessary so that + // the action has the proper clause for this property. Then, we can simply set the + // name of this controller on the action plus return the action array for usage. + if ($this->hasGroupStack()) { + $action['uses'] = $this->prependGroupController($action['uses']); + $action['uses'] = $this->prependGroupNamespace($action['uses']); + } + + // Here we will set this controller name on the action array just so we always + // have a copy of it for reference if we need it. This can be used while we + // search for a controller name or do some other type of fetch operation. + $action['controller'] = $action['uses']; + + return $action; + } + + /** + * Prepend the last group namespace onto the use clause. + * + * @param string $class + * @return string + */ + protected function prependGroupNamespace($class) + { + $group = end($this->groupStack); + + return isset($group['namespace']) && strpos($class, '\\') !== 0 + ? $group['namespace'].'\\'.$class : $class; + } + + /** + * Prepend the last group controller onto the use clause. + * + * @param string $class + * @return string + */ + protected function prependGroupController($class) + { + $group = end($this->groupStack); + + if (! isset($group['controller'])) { + return $class; + } + + if (class_exists($class)) { + return $class; + } + + if (strpos($class, '@') !== false) { + return $class; + } + + return $group['controller'].'@'.$class; + } + + /** + * Create a new Route object. + * + * @param array|string $methods + * @param string $uri + * @param mixed $action + * @return \Illuminate\Routing\Route + */ + public function newRoute($methods, $uri, $action) + { + return (new Route($methods, $uri, $action)) + ->setRouter($this) + ->setContainer($this->container); + } + + /** + * Prefix the given URI with the last prefix. + * + * @param string $uri + * @return string + */ + protected function prefix($uri) + { + return trim(trim($this->getLastGroupPrefix(), '/').'/'.trim($uri, '/'), '/') ?: '/'; + } + + /** + * Add the necessary where clauses to the route based on its initial registration. + * + * @param \Illuminate\Routing\Route $route + * @return \Illuminate\Routing\Route + */ + protected function addWhereClausesToRoute($route) + { + $route->where(array_merge( + $this->patterns, $route->getAction()['where'] ?? [] + )); + + return $route; + } + + /** + * Merge the group stack with the controller action. + * + * @param \Illuminate\Routing\Route $route + * @return void + */ + protected function mergeGroupAttributesIntoRoute($route) + { + $route->setAction($this->mergeWithLastGroup( + $route->getAction(), + $prependExistingPrefix = false + )); + } + + /** + * Return the response returned by the given route. + * + * @param string $name + * @return \Symfony\Component\HttpFoundation\Response + */ + public function respondWithRoute($name) + { + $route = tap($this->routes->getByName($name))->bind($this->currentRequest); + + return $this->runRoute($this->currentRequest, $route); + } + + /** + * Dispatch the request to the application. + * + * @param \Illuminate\Http\Request $request + * @return \Symfony\Component\HttpFoundation\Response + */ + public function dispatch(Request $request) + { + $this->currentRequest = $request; + + return $this->dispatchToRoute($request); + } + + /** + * Dispatch the request to a route and return the response. + * + * @param \Illuminate\Http\Request $request + * @return \Symfony\Component\HttpFoundation\Response + */ + public function dispatchToRoute(Request $request) + { + return $this->runRoute($request, $this->findRoute($request)); + } + + /** + * Find the route matching a given request. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Routing\Route + */ + protected function findRoute($request) + { + $this->current = $route = $this->routes->match($request); + + $route->setContainer($this->container); + + $this->container->instance(Route::class, $route); + + return $route; + } + + /** + * Return the response for the given route. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Routing\Route $route + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function runRoute(Request $request, Route $route) + { + $request->setRouteResolver(function () use ($route) { + return $route; + }); + + $this->events->dispatch(new RouteMatched($route, $request)); + + return $this->prepareResponse($request, + $this->runRouteWithinStack($route, $request) + ); + } + + /** + * Run the given route within a Stack "onion" instance. + * + * @param \Illuminate\Routing\Route $route + * @param \Illuminate\Http\Request $request + * @return mixed + */ + protected function runRouteWithinStack(Route $route, Request $request) + { + $shouldSkipMiddleware = $this->container->bound('middleware.disable') && + $this->container->make('middleware.disable') === true; + + $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route); + + return (new Pipeline($this->container)) + ->send($request) + ->through($middleware) + ->then(function ($request) use ($route) { + return $this->prepareResponse( + $request, $route->run() + ); + }); + } + + /** + * Gather the middleware for the given route with resolved class names. + * + * @param \Illuminate\Routing\Route $route + * @return array + */ + public function gatherRouteMiddleware(Route $route) + { + $computedMiddleware = $route->gatherMiddleware(); + + $excluded = collect($route->excludedMiddleware())->map(function ($name) { + return (array) MiddlewareNameResolver::resolve($name, $this->middleware, $this->middlewareGroups); + })->flatten()->values()->all(); + + $middleware = collect($computedMiddleware)->map(function ($name) { + return (array) MiddlewareNameResolver::resolve($name, $this->middleware, $this->middlewareGroups); + })->flatten()->reject(function ($name) use ($excluded) { + if (empty($excluded)) { + return false; + } + + if ($name instanceof Closure) { + return false; + } + + if (in_array($name, $excluded, true)) { + return true; + } + + if (! class_exists($name)) { + return false; + } + + $reflection = new ReflectionClass($name); + + return collect($excluded)->contains(function ($exclude) use ($reflection) { + return class_exists($exclude) && $reflection->isSubclassOf($exclude); + }); + })->values(); + + return $this->sortMiddleware($middleware); + } + + /** + * Sort the given middleware by priority. + * + * @param \Illuminate\Support\Collection $middlewares + * @return array + */ + protected function sortMiddleware(Collection $middlewares) + { + return (new SortedMiddleware($this->middlewarePriority, $middlewares))->all(); + } + + /** + * Create a response instance from the given value. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param mixed $response + * @return \Symfony\Component\HttpFoundation\Response + */ + public function prepareResponse($request, $response) + { + return static::toResponse($request, $response); + } + + /** + * Static version of prepareResponse. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param mixed $response + * @return \Symfony\Component\HttpFoundation\Response + */ + public static function toResponse($request, $response) + { + if ($response instanceof Responsable) { + $response = $response->toResponse($request); + } + + if ($response instanceof PsrResponseInterface) { + $response = (new HttpFoundationFactory)->createResponse($response); + } elseif ($response instanceof Model && $response->wasRecentlyCreated) { + $response = new JsonResponse($response, 201); + } elseif ($response instanceof Stringable) { + $response = new Response($response->__toString(), 200, ['Content-Type' => 'text/html']); + } elseif (! $response instanceof SymfonyResponse && + ($response instanceof Arrayable || + $response instanceof Jsonable || + $response instanceof ArrayObject || + $response instanceof JsonSerializable || + $response instanceof \stdClass || + is_array($response))) { + $response = new JsonResponse($response); + } elseif (! $response instanceof SymfonyResponse) { + $response = new Response($response, 200, ['Content-Type' => 'text/html']); + } + + if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) { + $response->setNotModified(); + } + + return $response->prepare($request); + } + + /** + * Substitute the route bindings onto the route. + * + * @param \Illuminate\Routing\Route $route + * @return \Illuminate\Routing\Route + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function substituteBindings($route) + { + foreach ($route->parameters() as $key => $value) { + if (isset($this->binders[$key])) { + $route->setParameter($key, $this->performBinding($key, $value, $route)); + } + } + + return $route; + } + + /** + * Substitute the implicit Eloquent model bindings for the route. + * + * @param \Illuminate\Routing\Route $route + * @return void + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function substituteImplicitBindings($route) + { + ImplicitRouteBinding::resolveForRoute($this->container, $route); + } + + /** + * Call the binding callback for the given key. + * + * @param string $key + * @param string $value + * @param \Illuminate\Routing\Route $route + * @return mixed + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + protected function performBinding($key, $value, $route) + { + return call_user_func($this->binders[$key], $value, $route); + } + + /** + * Register a route matched event listener. + * + * @param string|callable $callback + * @return void + */ + public function matched($callback) + { + $this->events->listen(Events\RouteMatched::class, $callback); + } + + /** + * Get all of the defined middleware short-hand names. + * + * @return array + */ + public function getMiddleware() + { + return $this->middleware; + } + + /** + * Register a short-hand name for a middleware. + * + * @param string $name + * @param string $class + * @return $this + */ + public function aliasMiddleware($name, $class) + { + $this->middleware[$name] = $class; + + return $this; + } + + /** + * Check if a middlewareGroup with the given name exists. + * + * @param string $name + * @return bool + */ + public function hasMiddlewareGroup($name) + { + return array_key_exists($name, $this->middlewareGroups); + } + + /** + * Get all of the defined middleware groups. + * + * @return array + */ + public function getMiddlewareGroups() + { + return $this->middlewareGroups; + } + + /** + * Register a group of middleware. + * + * @param string $name + * @param array $middleware + * @return $this + */ + public function middlewareGroup($name, array $middleware) + { + $this->middlewareGroups[$name] = $middleware; + + return $this; + } + + /** + * Add a middleware to the beginning of a middleware group. + * + * If the middleware is already in the group, it will not be added again. + * + * @param string $group + * @param string $middleware + * @return $this + */ + public function prependMiddlewareToGroup($group, $middleware) + { + if (isset($this->middlewareGroups[$group]) && ! in_array($middleware, $this->middlewareGroups[$group])) { + array_unshift($this->middlewareGroups[$group], $middleware); + } + + return $this; + } + + /** + * Add a middleware to the end of a middleware group. + * + * If the middleware is already in the group, it will not be added again. + * + * @param string $group + * @param string $middleware + * @return $this + */ + public function pushMiddlewareToGroup($group, $middleware) + { + if (! array_key_exists($group, $this->middlewareGroups)) { + $this->middlewareGroups[$group] = []; + } + + if (! in_array($middleware, $this->middlewareGroups[$group])) { + $this->middlewareGroups[$group][] = $middleware; + } + + return $this; + } + + /** + * Flush the router's middleware groups. + * + * @return $this + */ + public function flushMiddlewareGroups() + { + $this->middlewareGroups = []; + + return $this; + } + + /** + * Add a new route parameter binder. + * + * @param string $key + * @param string|callable $binder + * @return void + */ + public function bind($key, $binder) + { + $this->binders[str_replace('-', '_', $key)] = RouteBinding::forCallback( + $this->container, $binder + ); + } + + /** + * Register a model binder for a wildcard. + * + * @param string $key + * @param string $class + * @param \Closure|null $callback + * @return void + */ + public function model($key, $class, Closure $callback = null) + { + $this->bind($key, RouteBinding::forModel($this->container, $class, $callback)); + } + + /** + * Get the binding callback for a given binding. + * + * @param string $key + * @return \Closure|null + */ + public function getBindingCallback($key) + { + if (isset($this->binders[$key = str_replace('-', '_', $key)])) { + return $this->binders[$key]; + } + } + + /** + * Get the global "where" patterns. + * + * @return array + */ + public function getPatterns() + { + return $this->patterns; + } + + /** + * Set a global where pattern on all routes. + * + * @param string $key + * @param string $pattern + * @return void + */ + public function pattern($key, $pattern) + { + $this->patterns[$key] = $pattern; + } + + /** + * Set a group of global where patterns on all routes. + * + * @param array $patterns + * @return void + */ + public function patterns($patterns) + { + foreach ($patterns as $key => $pattern) { + $this->pattern($key, $pattern); + } + } + + /** + * Determine if the router currently has a group stack. + * + * @return bool + */ + public function hasGroupStack() + { + return ! empty($this->groupStack); + } + + /** + * Get the current group stack for the router. + * + * @return array + */ + public function getGroupStack() + { + return $this->groupStack; + } + + /** + * Get a route parameter for the current route. + * + * @param string $key + * @param string|null $default + * @return mixed + */ + public function input($key, $default = null) + { + return $this->current()->parameter($key, $default); + } + + /** + * Get the request currently being dispatched. + * + * @return \Illuminate\Http\Request + */ + public function getCurrentRequest() + { + return $this->currentRequest; + } + + /** + * Get the currently dispatched route instance. + * + * @return \Illuminate\Routing\Route|null + */ + public function getCurrentRoute() + { + return $this->current(); + } + + /** + * Get the currently dispatched route instance. + * + * @return \Illuminate\Routing\Route|null + */ + public function current() + { + return $this->current; + } + + /** + * Check if a route with the given name exists. + * + * @param string $name + * @return bool + */ + public function has($name) + { + $names = is_array($name) ? $name : func_get_args(); + + foreach ($names as $value) { + if (! $this->routes->hasNamedRoute($value)) { + return false; + } + } + + return true; + } + + /** + * Get the current route name. + * + * @return string|null + */ + public function currentRouteName() + { + return $this->current() ? $this->current()->getName() : null; + } + + /** + * Alias for the "currentRouteNamed" method. + * + * @param mixed ...$patterns + * @return bool + */ + public function is(...$patterns) + { + return $this->currentRouteNamed(...$patterns); + } + + /** + * Determine if the current route matches a pattern. + * + * @param mixed ...$patterns + * @return bool + */ + public function currentRouteNamed(...$patterns) + { + return $this->current() && $this->current()->named(...$patterns); + } + + /** + * Get the current route action. + * + * @return string|null + */ + public function currentRouteAction() + { + if ($this->current()) { + return $this->current()->getAction()['controller'] ?? null; + } + } + + /** + * Alias for the "currentRouteUses" method. + * + * @param array ...$patterns + * @return bool + */ + public function uses(...$patterns) + { + foreach ($patterns as $pattern) { + if (Str::is($pattern, $this->currentRouteAction())) { + return true; + } + } + + return false; + } + + /** + * Determine if the current route action matches a given action. + * + * @param string $action + * @return bool + */ + public function currentRouteUses($action) + { + return $this->currentRouteAction() == $action; + } + + /** + * Set the unmapped global resource parameters to singular. + * + * @param bool $singular + * @return void + */ + public function singularResourceParameters($singular = true) + { + ResourceRegistrar::singularParameters($singular); + } + + /** + * Set the global resource parameter mapping. + * + * @param array $parameters + * @return void + */ + public function resourceParameters(array $parameters = []) + { + ResourceRegistrar::setParameters($parameters); + } + + /** + * Get or set the verbs used in the resource URIs. + * + * @param array $verbs + * @return array|null + */ + public function resourceVerbs(array $verbs = []) + { + return ResourceRegistrar::verbs($verbs); + } + + /** + * Get the underlying route collection. + * + * @return \Illuminate\Routing\RouteCollectionInterface + */ + public function getRoutes() + { + return $this->routes; + } + + /** + * Set the route collection instance. + * + * @param \Illuminate\Routing\RouteCollection $routes + * @return void + */ + public function setRoutes(RouteCollection $routes) + { + foreach ($routes as $route) { + $route->setRouter($this)->setContainer($this->container); + } + + $this->routes = $routes; + + $this->container->instance('routes', $this->routes); + } + + /** + * Set the compiled route collection instance. + * + * @param array $routes + * @return void + */ + public function setCompiledRoutes(array $routes) + { + $this->routes = (new CompiledRouteCollection($routes['compiled'], $routes['attributes'])) + ->setRouter($this) + ->setContainer($this->container); + + $this->container->instance('routes', $this->routes); + } + + /** + * Remove any duplicate middleware from the given array. + * + * @param array $middleware + * @return array + */ + public static function uniqueMiddleware(array $middleware) + { + $seen = []; + $result = []; + + foreach ($middleware as $value) { + $key = \is_object($value) ? \spl_object_id($value) : $value; + + if (! isset($seen[$key])) { + $seen[$key] = true; + $result[] = $value; + } + } + + return $result; + } + + /** + * Set the container instance used by the router. + * + * @param \Illuminate\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } + + /** + * Dynamically handle calls into the router instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + if ($method === 'middleware') { + return (new RouteRegistrar($this))->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); + } + + return (new RouteRegistrar($this))->attribute($method, array_key_exists(0, $parameters) ? $parameters[0] : true); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php new file mode 100755 index 0000000..ee09863 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php @@ -0,0 +1,187 @@ +registerRouter(); + $this->registerUrlGenerator(); + $this->registerRedirector(); + $this->registerPsrRequest(); + $this->registerPsrResponse(); + $this->registerResponseFactory(); + $this->registerControllerDispatcher(); + } + + /** + * Register the router instance. + * + * @return void + */ + protected function registerRouter() + { + $this->app->singleton('router', function ($app) { + return new Router($app['events'], $app); + }); + } + + /** + * Register the URL generator service. + * + * @return void + */ + protected function registerUrlGenerator() + { + $this->app->singleton('url', function ($app) { + $routes = $app['router']->getRoutes(); + + // The URL generator needs the route collection that exists on the router. + // Keep in mind this is an object, so we're passing by references here + // and all the registered routes will be available to the generator. + $app->instance('routes', $routes); + + return new UrlGenerator( + $routes, $app->rebinding( + 'request', $this->requestRebinder() + ), $app['config']['app.asset_url'] + ); + }); + + $this->app->extend('url', function (UrlGeneratorContract $url, $app) { + // Next we will set a few service resolvers on the URL generator so it can + // get the information it needs to function. This just provides some of + // the convenience features to this URL generator like "signed" URLs. + $url->setSessionResolver(function () { + return $this->app['session'] ?? null; + }); + + $url->setKeyResolver(function () { + return $this->app->make('config')->get('app.key'); + }); + + // If the route collection is "rebound", for example, when the routes stay + // cached for the application, we will need to rebind the routes on the + // URL generator instance so it has the latest version of the routes. + $app->rebinding('routes', function ($app, $routes) { + $app['url']->setRoutes($routes); + }); + + return $url; + }); + } + + /** + * Get the URL generator request rebinder. + * + * @return \Closure + */ + protected function requestRebinder() + { + return function ($app, $request) { + $app['url']->setRequest($request); + }; + } + + /** + * Register the Redirector service. + * + * @return void + */ + protected function registerRedirector() + { + $this->app->singleton('redirect', function ($app) { + $redirector = new Redirector($app['url']); + + // If the session is set on the application instance, we'll inject it into + // the redirector instance. This allows the redirect responses to allow + // for the quite convenient "with" methods that flash to the session. + if (isset($app['session.store'])) { + $redirector->setSession($app['session.store']); + } + + return $redirector; + }); + } + + /** + * Register a binding for the PSR-7 request implementation. + * + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function registerPsrRequest() + { + $this->app->bind(ServerRequestInterface::class, function ($app) { + if (class_exists(Psr17Factory::class) && class_exists(PsrHttpFactory::class)) { + $psr17Factory = new Psr17Factory; + + return (new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory)) + ->createRequest($app->make('request')); + } + + throw new BindingResolutionException('Unable to resolve PSR request. Please install the symfony/psr-http-message-bridge and nyholm/psr7 packages.'); + }); + } + + /** + * Register a binding for the PSR-7 response implementation. + * + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function registerPsrResponse() + { + $this->app->bind(ResponseInterface::class, function () { + if (class_exists(PsrResponse::class)) { + return new PsrResponse; + } + + throw new BindingResolutionException('Unable to resolve PSR response. Please install the nyholm/psr7 package.'); + }); + } + + /** + * Register the response factory implementation. + * + * @return void + */ + protected function registerResponseFactory() + { + $this->app->singleton(ResponseFactoryContract::class, function ($app) { + return new ResponseFactory($app[ViewFactoryContract::class], $app['redirect']); + }); + } + + /** + * Register the controller dispatcher. + * + * @return void + */ + protected function registerControllerDispatcher() + { + $this->app->singleton(ControllerDispatcherContract::class, function ($app) { + return new ControllerDispatcher($app); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/SortedMiddleware.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/SortedMiddleware.php new file mode 100644 index 0000000..853378c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/SortedMiddleware.php @@ -0,0 +1,122 @@ +all(); + } + + $this->items = $this->sortMiddleware($priorityMap, $middlewares); + } + + /** + * Sort the middlewares by the given priority map. + * + * Each call to this method makes one discrete middleware movement if necessary. + * + * @param array $priorityMap + * @param array $middlewares + * @return array + */ + protected function sortMiddleware($priorityMap, $middlewares) + { + $lastIndex = 0; + + foreach ($middlewares as $index => $middleware) { + if (! is_string($middleware)) { + continue; + } + + $priorityIndex = $this->priorityMapIndex($priorityMap, $middleware); + + if (! is_null($priorityIndex)) { + // This middleware is in the priority map. If we have encountered another middleware + // that was also in the priority map and was at a lower priority than the current + // middleware, we will move this middleware to be above the previous encounter. + if (isset($lastPriorityIndex) && $priorityIndex < $lastPriorityIndex) { + return $this->sortMiddleware( + $priorityMap, array_values($this->moveMiddleware($middlewares, $index, $lastIndex)) + ); + } + + // This middleware is in the priority map; but, this is the first middleware we have + // encountered from the map thus far. We'll save its current index plus its index + // from the priority map so we can compare against them on the next iterations. + $lastIndex = $index; + + $lastPriorityIndex = $priorityIndex; + } + } + + return Router::uniqueMiddleware($middlewares); + } + + /** + * Calculate the priority map index of the middleware. + * + * @param array $priorityMap + * @param string $middleware + * @return int|null + */ + protected function priorityMapIndex($priorityMap, $middleware) + { + foreach ($this->middlewareNames($middleware) as $name) { + $priorityIndex = array_search($name, $priorityMap); + + if ($priorityIndex !== false) { + return $priorityIndex; + } + } + } + + /** + * Resolve the middleware names to look for in the priority array. + * + * @param string $middleware + * @return \Generator + */ + protected function middlewareNames($middleware) + { + $stripped = head(explode(':', $middleware)); + + yield $stripped; + + $interfaces = @class_implements($stripped); + + if ($interfaces !== false) { + foreach ($interfaces as $interface) { + yield $interface; + } + } + } + + /** + * Splice a middleware into a new position and remove the old entry. + * + * @param array $middlewares + * @param int $from + * @param int $to + * @return array + */ + protected function moveMiddleware($middlewares, $from, $to) + { + array_splice($middlewares, $to, 0, $middlewares[$from]); + + unset($middlewares[$from + 1]); + + return $middlewares; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php new file mode 100755 index 0000000..f40491d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php @@ -0,0 +1,799 @@ +routes = $routes; + $this->assetRoot = $assetRoot; + + $this->setRequest($request); + } + + /** + * Get the full URL for the current request. + * + * @return string + */ + public function full() + { + return $this->request->fullUrl(); + } + + /** + * Get the current URL for the request. + * + * @return string + */ + public function current() + { + return $this->to($this->request->getPathInfo()); + } + + /** + * Get the URL for the previous request. + * + * @param mixed $fallback + * @return string + */ + public function previous($fallback = false) + { + $referrer = $this->request->headers->get('referer'); + + $url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession(); + + if ($url) { + return $url; + } elseif ($fallback) { + return $this->to($fallback); + } + + return $this->to('/'); + } + + /** + * Get the previous URL from the session if possible. + * + * @return string|null + */ + protected function getPreviousUrlFromSession() + { + $session = $this->getSession(); + + return $session ? $session->previousUrl() : null; + } + + /** + * Generate an absolute URL to the given path. + * + * @param string $path + * @param mixed $extra + * @param bool|null $secure + * @return string + */ + public function to($path, $extra = [], $secure = null) + { + // First we will check if the URL is already a valid URL. If it is we will not + // try to generate a new one but will simply return the URL as is, which is + // convenient since developers do not always have to check if it's valid. + if ($this->isValidUrl($path)) { + return $path; + } + + $tail = implode('/', array_map( + 'rawurlencode', (array) $this->formatParameters($extra)) + ); + + // Once we have the scheme we will compile the "tail" by collapsing the values + // into a single string delimited by slashes. This just makes it convenient + // for passing the array of parameters to this URL as a list of segments. + $root = $this->formatRoot($this->formatScheme($secure)); + + [$path, $query] = $this->extractQueryString($path); + + return $this->format( + $root, '/'.trim($path.'/'.$tail, '/') + ).$query; + } + + /** + * Generate a secure, absolute URL to the given path. + * + * @param string $path + * @param array $parameters + * @return string + */ + public function secure($path, $parameters = []) + { + return $this->to($path, $parameters, true); + } + + /** + * Generate the URL to an application asset. + * + * @param string $path + * @param bool|null $secure + * @return string + */ + public function asset($path, $secure = null) + { + if ($this->isValidUrl($path)) { + return $path; + } + + // Once we get the root URL, we will check to see if it contains an index.php + // file in the paths. If it does, we will remove it since it is not needed + // for asset paths, but only for routes to endpoints in the application. + $root = $this->assetRoot ?: $this->formatRoot($this->formatScheme($secure)); + + return $this->removeIndex($root).'/'.trim($path, '/'); + } + + /** + * Generate the URL to a secure asset. + * + * @param string $path + * @return string + */ + public function secureAsset($path) + { + return $this->asset($path, true); + } + + /** + * Generate the URL to an asset from a custom root domain such as CDN, etc. + * + * @param string $root + * @param string $path + * @param bool|null $secure + * @return string + */ + public function assetFrom($root, $path, $secure = null) + { + // Once we get the root URL, we will check to see if it contains an index.php + // file in the paths. If it does, we will remove it since it is not needed + // for asset paths, but only for routes to endpoints in the application. + $root = $this->formatRoot($this->formatScheme($secure), $root); + + return $this->removeIndex($root).'/'.trim($path, '/'); + } + + /** + * Remove the index.php file from a path. + * + * @param string $root + * @return string + */ + protected function removeIndex($root) + { + $i = 'index.php'; + + return Str::contains($root, $i) ? str_replace('/'.$i, '', $root) : $root; + } + + /** + * Get the default scheme for a raw URL. + * + * @param bool|null $secure + * @return string + */ + public function formatScheme($secure = null) + { + if (! is_null($secure)) { + return $secure ? 'https://' : 'http://'; + } + + if (is_null($this->cachedScheme)) { + $this->cachedScheme = $this->forceScheme ?: $this->request->getScheme().'://'; + } + + return $this->cachedScheme; + } + + /** + * Create a signed route URL for a named route. + * + * @param string $name + * @param mixed $parameters + * @param \DateTimeInterface|\DateInterval|int|null $expiration + * @param bool $absolute + * @return string + * + * @throws \InvalidArgumentException + */ + public function signedRoute($name, $parameters = [], $expiration = null, $absolute = true) + { + $this->ensureSignedRouteParametersAreNotReserved( + $parameters = Arr::wrap($parameters) + ); + + if ($expiration) { + $parameters = $parameters + ['expires' => $this->availableAt($expiration)]; + } + + ksort($parameters); + + $key = call_user_func($this->keyResolver); + + return $this->route($name, $parameters + [ + 'signature' => hash_hmac('sha256', $this->route($name, $parameters, $absolute), $key), + ], $absolute); + } + + /** + * Ensure the given signed route parameters are not reserved. + * + * @param mixed $parameters + * @return void + */ + protected function ensureSignedRouteParametersAreNotReserved($parameters) + { + if (array_key_exists('signature', $parameters)) { + throw new InvalidArgumentException( + '"Signature" is a reserved parameter when generating signed routes. Please rename your route parameter.' + ); + } + + if (array_key_exists('expires', $parameters)) { + throw new InvalidArgumentException( + '"Expires" is a reserved parameter when generating signed routes. Please rename your route parameter.' + ); + } + } + + /** + * Create a temporary signed route URL for a named route. + * + * @param string $name + * @param \DateTimeInterface|\DateInterval|int $expiration + * @param array $parameters + * @param bool $absolute + * @return string + */ + public function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true) + { + return $this->signedRoute($name, $parameters, $expiration, $absolute); + } + + /** + * Determine if the given request has a valid signature. + * + * @param \Illuminate\Http\Request $request + * @param bool $absolute + * @return bool + */ + public function hasValidSignature(Request $request, $absolute = true) + { + return $this->hasCorrectSignature($request, $absolute) + && $this->signatureHasNotExpired($request); + } + + /** + * Determine if the given request has a valid signature for a relative URL. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + public function hasValidRelativeSignature(Request $request) + { + return $this->hasValidSignature($request, false); + } + + /** + * Determine if the signature from the given request matches the URL. + * + * @param \Illuminate\Http\Request $request + * @param bool $absolute + * @return bool + */ + public function hasCorrectSignature(Request $request, $absolute = true) + { + $url = $absolute ? $request->url() : '/'.$request->path(); + + $queryString = ltrim(preg_replace('/(^|&)signature=[^&]+/', '', $request->server->get('QUERY_STRING')), '&'); + + $signature = hash_hmac('sha256', rtrim($url.'?'.$queryString, '?'), call_user_func($this->keyResolver)); + + return hash_equals($signature, (string) $request->query('signature', '')); + } + + /** + * Determine if the expires timestamp from the given request is not from the past. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + public function signatureHasNotExpired(Request $request) + { + $expires = $request->query('expires'); + + return ! ($expires && Carbon::now()->getTimestamp() > $expires); + } + + /** + * Get the URL to a named route. + * + * @param string $name + * @param mixed $parameters + * @param bool $absolute + * @return string + * + * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException + */ + public function route($name, $parameters = [], $absolute = true) + { + if (! is_null($route = $this->routes->getByName($name))) { + return $this->toRoute($route, $parameters, $absolute); + } + + throw new RouteNotFoundException("Route [{$name}] not defined."); + } + + /** + * Get the URL for a given route instance. + * + * @param \Illuminate\Routing\Route $route + * @param mixed $parameters + * @param bool $absolute + * @return string + * + * @throws \Illuminate\Routing\Exceptions\UrlGenerationException + */ + public function toRoute($route, $parameters, $absolute) + { + $parameters = collect(Arr::wrap($parameters))->map(function ($value, $key) use ($route) { + return $value instanceof UrlRoutable && $route->bindingFieldFor($key) + ? $value->{$route->bindingFieldFor($key)} + : $value; + })->all(); + + return $this->routeUrl()->to( + $route, $this->formatParameters($parameters), $absolute + ); + } + + /** + * Get the URL to a controller action. + * + * @param string|array $action + * @param mixed $parameters + * @param bool $absolute + * @return string + * + * @throws \InvalidArgumentException + */ + public function action($action, $parameters = [], $absolute = true) + { + if (is_null($route = $this->routes->getByAction($action = $this->formatAction($action)))) { + throw new InvalidArgumentException("Action {$action} not defined."); + } + + return $this->toRoute($route, $parameters, $absolute); + } + + /** + * Format the given controller action. + * + * @param string|array $action + * @return string + */ + protected function formatAction($action) + { + if (is_array($action)) { + $action = '\\'.implode('@', $action); + } + + if ($this->rootNamespace && strpos($action, '\\') !== 0) { + return $this->rootNamespace.'\\'.$action; + } else { + return trim($action, '\\'); + } + } + + /** + * Format the array of URL parameters. + * + * @param mixed|array $parameters + * @return array + */ + public function formatParameters($parameters) + { + $parameters = Arr::wrap($parameters); + + foreach ($parameters as $key => $parameter) { + if ($parameter instanceof UrlRoutable) { + $parameters[$key] = $parameter->getRouteKey(); + } + } + + return $parameters; + } + + /** + * Extract the query string from the given path. + * + * @param string $path + * @return array + */ + protected function extractQueryString($path) + { + if (($queryPosition = strpos($path, '?')) !== false) { + return [ + substr($path, 0, $queryPosition), + substr($path, $queryPosition), + ]; + } + + return [$path, '']; + } + + /** + * Get the base URL for the request. + * + * @param string $scheme + * @param string|null $root + * @return string + */ + public function formatRoot($scheme, $root = null) + { + if (is_null($root)) { + if (is_null($this->cachedRoot)) { + $this->cachedRoot = $this->forcedRoot ?: $this->request->root(); + } + + $root = $this->cachedRoot; + } + + $start = Str::startsWith($root, 'http://') ? 'http://' : 'https://'; + + return preg_replace('~'.$start.'~', $scheme, $root, 1); + } + + /** + * Format the given URL segments into a single URL. + * + * @param string $root + * @param string $path + * @param \Illuminate\Routing\Route|null $route + * @return string + */ + public function format($root, $path, $route = null) + { + $path = '/'.trim($path, '/'); + + if ($this->formatHostUsing) { + $root = call_user_func($this->formatHostUsing, $root, $route); + } + + if ($this->formatPathUsing) { + $path = call_user_func($this->formatPathUsing, $path, $route); + } + + return trim($root.$path, '/'); + } + + /** + * Determine if the given path is a valid URL. + * + * @param string $path + * @return bool + */ + public function isValidUrl($path) + { + if (! preg_match('~^(#|//|https?://|(mailto|tel|sms):)~', $path)) { + return filter_var($path, FILTER_VALIDATE_URL) !== false; + } + + return true; + } + + /** + * Get the Route URL generator instance. + * + * @return \Illuminate\Routing\RouteUrlGenerator + */ + protected function routeUrl() + { + if (! $this->routeGenerator) { + $this->routeGenerator = new RouteUrlGenerator($this, $this->request); + } + + return $this->routeGenerator; + } + + /** + * Set the default named parameters used by the URL generator. + * + * @param array $defaults + * @return void + */ + public function defaults(array $defaults) + { + $this->routeUrl()->defaults($defaults); + } + + /** + * Get the default named parameters used by the URL generator. + * + * @return array + */ + public function getDefaultParameters() + { + return $this->routeUrl()->defaultParameters; + } + + /** + * Force the scheme for URLs. + * + * @param string|null $scheme + * @return void + */ + public function forceScheme($scheme) + { + $this->cachedScheme = null; + + $this->forceScheme = $scheme ? $scheme.'://' : null; + } + + /** + * Set the forced root URL. + * + * @param string|null $root + * @return void + */ + public function forceRootUrl($root) + { + $this->forcedRoot = $root ? rtrim($root, '/') : null; + + $this->cachedRoot = null; + } + + /** + * Set a callback to be used to format the host of generated URLs. + * + * @param \Closure $callback + * @return $this + */ + public function formatHostUsing(Closure $callback) + { + $this->formatHostUsing = $callback; + + return $this; + } + + /** + * Set a callback to be used to format the path of generated URLs. + * + * @param \Closure $callback + * @return $this + */ + public function formatPathUsing(Closure $callback) + { + $this->formatPathUsing = $callback; + + return $this; + } + + /** + * Get the path formatter being used by the URL generator. + * + * @return \Closure + */ + public function pathFormatter() + { + return $this->formatPathUsing ?: function ($path) { + return $path; + }; + } + + /** + * Get the request instance. + * + * @return \Illuminate\Http\Request + */ + public function getRequest() + { + return $this->request; + } + + /** + * Set the current request instance. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + public function setRequest(Request $request) + { + $this->request = $request; + + $this->cachedRoot = null; + $this->cachedScheme = null; + + tap(optional($this->routeGenerator)->defaultParameters ?: [], function ($defaults) { + $this->routeGenerator = null; + + if (! empty($defaults)) { + $this->defaults($defaults); + } + }); + } + + /** + * Set the route collection. + * + * @param \Illuminate\Routing\RouteCollectionInterface $routes + * @return $this + */ + public function setRoutes(RouteCollectionInterface $routes) + { + $this->routes = $routes; + + return $this; + } + + /** + * Get the session implementation from the resolver. + * + * @return \Illuminate\Session\Store|null + */ + protected function getSession() + { + if ($this->sessionResolver) { + return call_user_func($this->sessionResolver); + } + } + + /** + * Set the session resolver for the generator. + * + * @param callable $sessionResolver + * @return $this + */ + public function setSessionResolver(callable $sessionResolver) + { + $this->sessionResolver = $sessionResolver; + + return $this; + } + + /** + * Set the encryption key resolver. + * + * @param callable $keyResolver + * @return $this + */ + public function setKeyResolver(callable $keyResolver) + { + $this->keyResolver = $keyResolver; + + return $this; + } + + /** + * Set the root controller namespace. + * + * @param string $rootNamespace + * @return $this + */ + public function setRootControllerNamespace($rootNamespace) + { + $this->rootNamespace = $rootNamespace; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ViewController.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ViewController.php new file mode 100644 index 0000000..7829cca --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/ViewController.php @@ -0,0 +1,39 @@ +response = $response; + } + + /** + * Invoke the controller method. + * + * @param array $args + * @return \Illuminate\Http\Response + */ + public function __invoke(...$args) + { + [$view, $data, $status, $headers] = array_slice($args, -4); + + return $this->response->view($view, $data, $status, $headers); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/composer.json new file mode 100644 index 0000000..96c3488 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Routing/composer.json @@ -0,0 +1,50 @@ +{ + "name": "illuminate/routing", + "description": "The Illuminate Routing package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/http": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/pipeline": "^8.0", + "illuminate/session": "^8.0", + "illuminate/support": "^8.0", + "symfony/http-foundation": "^5.4", + "symfony/http-kernel": "^5.4", + "symfony/routing": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Routing\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "illuminate/console": "Required to use the make commands (^8.0).", + "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", + "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/ArraySessionHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/ArraySessionHandler.php new file mode 100644 index 0000000..9a0dff1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/ArraySessionHandler.php @@ -0,0 +1,142 @@ +minutes = $minutes; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * {@inheritdoc} + * + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + if (! isset($this->storage[$sessionId])) { + return ''; + } + + $session = $this->storage[$sessionId]; + + $expiration = $this->calculateExpiration($this->minutes * 60); + + if (isset($session['time']) && $session['time'] >= $expiration) { + return $session['data']; + } + + return ''; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + $this->storage[$sessionId] = [ + 'data' => $data, + 'time' => $this->currentTime(), + ]; + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + if (isset($this->storage[$sessionId])) { + unset($this->storage[$sessionId]); + } + + return true; + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($lifetime) + { + $expiration = $this->calculateExpiration($lifetime); + + foreach ($this->storage as $sessionId => $session) { + if ($session['time'] < $expiration) { + unset($this->storage[$sessionId]); + } + } + + return true; + } + + /** + * Get the expiration time of the session. + * + * @param int $seconds + * @return int + */ + protected function calculateExpiration($seconds) + { + return $this->currentTime() - $seconds; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/CacheBasedSessionHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/CacheBasedSessionHandler.php new file mode 100755 index 0000000..5db2ac5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/CacheBasedSessionHandler.php @@ -0,0 +1,112 @@ +cache = $cache; + $this->minutes = $minutes; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * {@inheritdoc} + * + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + return $this->cache->get($sessionId, ''); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + return $this->cache->put($sessionId, $data, $this->minutes * 60); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + return $this->cache->forget($sessionId); + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($lifetime) + { + return true; + } + + /** + * Get the underlying cache repository. + * + * @return \Illuminate\Contracts\Cache\Repository + */ + public function getCache() + { + return $this->cache; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Console/SessionTableCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Console/SessionTableCommand.php new file mode 100644 index 0000000..1675c19 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Console/SessionTableCommand.php @@ -0,0 +1,81 @@ +files = $files; + $this->composer = $composer; + } + + /** + * Execute the console command. + * + * @return void + */ + public function handle() + { + $fullPath = $this->createBaseMigration(); + + $this->files->put($fullPath, $this->files->get(__DIR__.'/stubs/database.stub')); + + $this->info('Migration created successfully!'); + + $this->composer->dumpAutoloads(); + } + + /** + * Create a base migration file for the session. + * + * @return string + */ + protected function createBaseMigration() + { + $name = 'create_sessions_table'; + + $path = $this->laravel->databasePath().'/migrations'; + + return $this->laravel['migration.creator']->create($name, $path); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Console/stubs/database.stub b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Console/stubs/database.stub new file mode 100755 index 0000000..88b4a31 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Console/stubs/database.stub @@ -0,0 +1,35 @@ +string('id')->primary(); + $table->foreignId('user_id')->nullable()->index(); + $table->string('ip_address', 45)->nullable(); + $table->text('user_agent')->nullable(); + $table->text('payload'); + $table->integer('last_activity')->index(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('sessions'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/CookieSessionHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/CookieSessionHandler.php new file mode 100755 index 0000000..0a1d9cd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/CookieSessionHandler.php @@ -0,0 +1,139 @@ +cookie = $cookie; + $this->minutes = $minutes; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * {@inheritdoc} + * + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + $value = $this->request->cookies->get($sessionId) ?: ''; + + if (! is_null($decoded = json_decode($value, true)) && is_array($decoded)) { + if (isset($decoded['expires']) && $this->currentTime() <= $decoded['expires']) { + return $decoded['data']; + } + } + + return ''; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + $this->cookie->queue($sessionId, json_encode([ + 'data' => $data, + 'expires' => $this->availableAt($this->minutes * 60), + ]), $this->minutes); + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + $this->cookie->queue($this->cookie->forget($sessionId)); + + return true; + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($lifetime) + { + return true; + } + + /** + * Set the request instance. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @return void + */ + public function setRequest(Request $request) + { + $this->request = $request; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php new file mode 100644 index 0000000..18846ad --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php @@ -0,0 +1,325 @@ +table = $table; + $this->minutes = $minutes; + $this->container = $container; + $this->connection = $connection; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * {@inheritdoc} + * + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + $session = (object) $this->getQuery()->find($sessionId); + + if ($this->expired($session)) { + $this->exists = true; + + return ''; + } + + if (isset($session->payload)) { + $this->exists = true; + + return base64_decode($session->payload); + } + + return ''; + } + + /** + * Determine if the session is expired. + * + * @param \stdClass $session + * @return bool + */ + protected function expired($session) + { + return isset($session->last_activity) && + $session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp(); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + $payload = $this->getDefaultPayload($data); + + if (! $this->exists) { + $this->read($sessionId); + } + + if ($this->exists) { + $this->performUpdate($sessionId, $payload); + } else { + $this->performInsert($sessionId, $payload); + } + + return $this->exists = true; + } + + /** + * Perform an insert operation on the session ID. + * + * @param string $sessionId + * @param array $payload + * @return bool|null + */ + protected function performInsert($sessionId, $payload) + { + try { + return $this->getQuery()->insert(Arr::set($payload, 'id', $sessionId)); + } catch (QueryException $e) { + $this->performUpdate($sessionId, $payload); + } + } + + /** + * Perform an update operation on the session ID. + * + * @param string $sessionId + * @param array $payload + * @return int + */ + protected function performUpdate($sessionId, $payload) + { + return $this->getQuery()->where('id', $sessionId)->update($payload); + } + + /** + * Get the default payload for the session. + * + * @param string $data + * @return array + */ + protected function getDefaultPayload($data) + { + $payload = [ + 'payload' => base64_encode($data), + 'last_activity' => $this->currentTime(), + ]; + + if (! $this->container) { + return $payload; + } + + return tap($payload, function (&$payload) { + $this->addUserInformation($payload) + ->addRequestInformation($payload); + }); + } + + /** + * Add the user information to the session payload. + * + * @param array $payload + * @return $this + */ + protected function addUserInformation(&$payload) + { + if ($this->container->bound(Guard::class)) { + $payload['user_id'] = $this->userId(); + } + + return $this; + } + + /** + * Get the currently authenticated user's ID. + * + * @return mixed + */ + protected function userId() + { + return $this->container->make(Guard::class)->id(); + } + + /** + * Add the request information to the session payload. + * + * @param array $payload + * @return $this + */ + protected function addRequestInformation(&$payload) + { + if ($this->container->bound('request')) { + $payload = array_merge($payload, [ + 'ip_address' => $this->ipAddress(), + 'user_agent' => $this->userAgent(), + ]); + } + + return $this; + } + + /** + * Get the IP address for the current request. + * + * @return string + */ + protected function ipAddress() + { + return $this->container->make('request')->ip(); + } + + /** + * Get the user agent for the current request. + * + * @return string + */ + protected function userAgent() + { + return substr((string) $this->container->make('request')->header('User-Agent'), 0, 500); + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + $this->getQuery()->where('id', $sessionId)->delete(); + + return true; + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($lifetime) + { + $this->getQuery()->where('last_activity', '<=', $this->currentTime() - $lifetime)->delete(); + } + + /** + * Get a fresh query builder instance for the table. + * + * @return \Illuminate\Database\Query\Builder + */ + protected function getQuery() + { + return $this->connection->table($this->table); + } + + /** + * Set the application instance used by the handler. + * + * @param \Illuminate\Contracts\Foundation\Application $container + * @return $this + */ + public function setContainer($container) + { + $this->container = $container; + + return $this; + } + + /** + * Set the existence state for the session. + * + * @param bool $value + * @return $this + */ + public function setExists($value) + { + $this->exists = $value; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/EncryptedStore.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/EncryptedStore.php new file mode 100644 index 0000000..106fe13 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/EncryptedStore.php @@ -0,0 +1,69 @@ +encrypter = $encrypter; + + parent::__construct($name, $handler, $id); + } + + /** + * Prepare the raw string data from the session for unserialization. + * + * @param string $data + * @return string + */ + protected function prepareForUnserialize($data) + { + try { + return $this->encrypter->decrypt($data); + } catch (DecryptException $e) { + return serialize([]); + } + } + + /** + * Prepare the serialized session data for storage. + * + * @param string $data + * @return string + */ + protected function prepareForStorage($data) + { + return $this->encrypter->encrypt($data); + } + + /** + * Get the encrypter instance. + * + * @return \Illuminate\Contracts\Encryption\Encrypter + */ + public function getEncrypter() + { + return $this->encrypter; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/ExistenceAwareInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/ExistenceAwareInterface.php new file mode 100644 index 0000000..4a6bd98 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/ExistenceAwareInterface.php @@ -0,0 +1,14 @@ +path = $path; + $this->files = $files; + $this->minutes = $minutes; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * {@inheritdoc} + * + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + if ($this->files->isFile($path = $this->path.'/'.$sessionId)) { + if ($this->files->lastModified($path) >= Carbon::now()->subMinutes($this->minutes)->getTimestamp()) { + return $this->files->sharedGet($path); + } + } + + return ''; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + $this->files->put($this->path.'/'.$sessionId, $data, true); + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + $this->files->delete($this->path.'/'.$sessionId); + + return true; + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($lifetime) + { + $files = Finder::create() + ->in($this->path) + ->files() + ->ignoreDotFiles(true) + ->date('<= now - '.$lifetime.' seconds'); + + foreach ($files as $file) { + $this->files->delete($file->getRealPath()); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php new file mode 100644 index 0000000..42f3a4f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php @@ -0,0 +1,108 @@ +auth = $auth; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + if (! $request->hasSession() || ! $request->user()) { + return $next($request); + } + + if ($this->guard()->viaRemember()) { + $passwordHash = explode('|', $request->cookies->get($this->auth->getRecallerName()))[2] ?? null; + + if (! $passwordHash || $passwordHash != $request->user()->getAuthPassword()) { + $this->logout($request); + } + } + + if (! $request->session()->has('password_hash_'.$this->auth->getDefaultDriver())) { + $this->storePasswordHashInSession($request); + } + + if ($request->session()->get('password_hash_'.$this->auth->getDefaultDriver()) !== $request->user()->getAuthPassword()) { + $this->logout($request); + } + + return tap($next($request), function () use ($request) { + if (! is_null($this->guard()->user())) { + $this->storePasswordHashInSession($request); + } + }); + } + + /** + * Store the user's current password hash in the session. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + protected function storePasswordHashInSession($request) + { + if (! $request->user()) { + return; + } + + $request->session()->put([ + 'password_hash_'.$this->auth->getDefaultDriver() => $request->user()->getAuthPassword(), + ]); + } + + /** + * Log the user out of the application. + * + * @param \Illuminate\Http\Request $request + * @return void + * + * @throws \Illuminate\Auth\AuthenticationException + */ + protected function logout($request) + { + $this->guard()->logoutCurrentDevice(); + + $request->session()->flush(); + + throw new AuthenticationException('Unauthenticated.', [$this->auth->getDefaultDriver()]); + } + + /** + * Get the guard instance that should be used by the middleware. + * + * @return \Illuminate\Contracts\Auth\Factory|\Illuminate\Contracts\Auth\Guard + */ + protected function guard() + { + return $this->auth; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php new file mode 100644 index 0000000..e7d2daa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php @@ -0,0 +1,296 @@ +manager = $manager; + $this->cacheFactoryResolver = $cacheFactoryResolver; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + if (! $this->sessionConfigured()) { + return $next($request); + } + + $session = $this->getSession($request); + + if ($this->manager->shouldBlock() || + ($request->route() instanceof Route && $request->route()->locksFor())) { + return $this->handleRequestWhileBlocking($request, $session, $next); + } + + return $this->handleStatefulRequest($request, $session, $next); + } + + /** + * Handle the given request within session state. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Contracts\Session\Session $session + * @param \Closure $next + * @return mixed + */ + protected function handleRequestWhileBlocking(Request $request, $session, Closure $next) + { + if (! $request->route() instanceof Route) { + return; + } + + $lockFor = $request->route() && $request->route()->locksFor() + ? $request->route()->locksFor() + : 10; + + $lock = $this->cache($this->manager->blockDriver()) + ->lock('session:'.$session->getId(), $lockFor) + ->betweenBlockedAttemptsSleepFor(50); + + try { + $lock->block( + ! is_null($request->route()->waitsFor()) + ? $request->route()->waitsFor() + : 10 + ); + + return $this->handleStatefulRequest($request, $session, $next); + } finally { + optional($lock)->release(); + } + } + + /** + * Handle the given request within session state. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Contracts\Session\Session $session + * @param \Closure $next + * @return mixed + */ + protected function handleStatefulRequest(Request $request, $session, Closure $next) + { + // If a session driver has been configured, we will need to start the session here + // so that the data is ready for an application. Note that the Laravel sessions + // do not make use of PHP "native" sessions in any way since they are crappy. + $request->setLaravelSession( + $this->startSession($request, $session) + ); + + $this->collectGarbage($session); + + $response = $next($request); + + $this->storeCurrentUrl($request, $session); + + $this->addCookieToResponse($response, $session); + + // Again, if the session has been configured we will need to close out the session + // so that the attributes may be persisted to some storage medium. We will also + // add the session identifier cookie to the application response headers now. + $this->saveSession($request); + + return $response; + } + + /** + * Start the session for the given request. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Contracts\Session\Session $session + * @return \Illuminate\Contracts\Session\Session + */ + protected function startSession(Request $request, $session) + { + return tap($session, function ($session) use ($request) { + $session->setRequestOnHandler($request); + + $session->start(); + }); + } + + /** + * Get the session implementation from the manager. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Contracts\Session\Session + */ + public function getSession(Request $request) + { + return tap($this->manager->driver(), function ($session) use ($request) { + $session->setId($request->cookies->get($session->getName())); + }); + } + + /** + * Remove the garbage from the session if necessary. + * + * @param \Illuminate\Contracts\Session\Session $session + * @return void + */ + protected function collectGarbage(Session $session) + { + $config = $this->manager->getSessionConfig(); + + // Here we will see if this request hits the garbage collection lottery by hitting + // the odds needed to perform garbage collection on any given request. If we do + // hit it, we'll call this handler to let it delete all the expired sessions. + if ($this->configHitsLottery($config)) { + $session->getHandler()->gc($this->getSessionLifetimeInSeconds()); + } + } + + /** + * Determine if the configuration odds hit the lottery. + * + * @param array $config + * @return bool + */ + protected function configHitsLottery(array $config) + { + return random_int(1, $config['lottery'][1]) <= $config['lottery'][0]; + } + + /** + * Store the current URL for the request if necessary. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Contracts\Session\Session $session + * @return void + */ + protected function storeCurrentUrl(Request $request, $session) + { + if ($request->method() === 'GET' && + $request->route() instanceof Route && + ! $request->ajax() && + ! $request->prefetch()) { + $session->setPreviousUrl($request->fullUrl()); + } + } + + /** + * Add the session cookie to the application response. + * + * @param \Symfony\Component\HttpFoundation\Response $response + * @param \Illuminate\Contracts\Session\Session $session + * @return void + */ + protected function addCookieToResponse(Response $response, Session $session) + { + if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) { + $response->headers->setCookie(new Cookie( + $session->getName(), $session->getId(), $this->getCookieExpirationDate(), + $config['path'], $config['domain'], $config['secure'] ?? false, + $config['http_only'] ?? true, false, $config['same_site'] ?? null + )); + } + } + + /** + * Save the session data to storage. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + protected function saveSession($request) + { + $this->manager->driver()->save(); + } + + /** + * Get the session lifetime in seconds. + * + * @return int + */ + protected function getSessionLifetimeInSeconds() + { + return ($this->manager->getSessionConfig()['lifetime'] ?? null) * 60; + } + + /** + * Get the cookie lifetime in seconds. + * + * @return \DateTimeInterface|int + */ + protected function getCookieExpirationDate() + { + $config = $this->manager->getSessionConfig(); + + return $config['expire_on_close'] ? 0 : Date::instance( + Carbon::now()->addRealMinutes($config['lifetime']) + ); + } + + /** + * Determine if a session driver has been configured. + * + * @return bool + */ + protected function sessionConfigured() + { + return ! is_null($this->manager->getSessionConfig()['driver'] ?? null); + } + + /** + * Determine if the configured session driver is persistent. + * + * @param array|null $config + * @return bool + */ + protected function sessionIsPersistent(array $config = null) + { + $config = $config ?: $this->manager->getSessionConfig(); + + return ! is_null($config['driver'] ?? null); + } + + /** + * Resolve the given cache driver. + * + * @param string $driver + * @return \Illuminate\Cache\Store + */ + protected function cache($driver) + { + return call_user_func($this->cacheFactoryResolver)->driver($driver); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/NullSessionHandler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/NullSessionHandler.php new file mode 100644 index 0000000..b9af93a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/NullSessionHandler.php @@ -0,0 +1,74 @@ +buildSession(parent::callCustomCreator($driver)); + } + + /** + * Create an instance of the "null" session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createNullDriver() + { + return $this->buildSession(new NullSessionHandler); + } + + /** + * Create an instance of the "array" session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createArrayDriver() + { + return $this->buildSession(new ArraySessionHandler( + $this->config->get('session.lifetime') + )); + } + + /** + * Create an instance of the "cookie" session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createCookieDriver() + { + return $this->buildSession(new CookieSessionHandler( + $this->container->make('cookie'), $this->config->get('session.lifetime') + )); + } + + /** + * Create an instance of the file session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createFileDriver() + { + return $this->createNativeDriver(); + } + + /** + * Create an instance of the file session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createNativeDriver() + { + $lifetime = $this->config->get('session.lifetime'); + + return $this->buildSession(new FileSessionHandler( + $this->container->make('files'), $this->config->get('session.files'), $lifetime + )); + } + + /** + * Create an instance of the database session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createDatabaseDriver() + { + $table = $this->config->get('session.table'); + + $lifetime = $this->config->get('session.lifetime'); + + return $this->buildSession(new DatabaseSessionHandler( + $this->getDatabaseConnection(), $table, $lifetime, $this->container + )); + } + + /** + * Get the database connection for the database driver. + * + * @return \Illuminate\Database\Connection + */ + protected function getDatabaseConnection() + { + $connection = $this->config->get('session.connection'); + + return $this->container->make('db')->connection($connection); + } + + /** + * Create an instance of the APC session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createApcDriver() + { + return $this->createCacheBased('apc'); + } + + /** + * Create an instance of the Memcached session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createMemcachedDriver() + { + return $this->createCacheBased('memcached'); + } + + /** + * Create an instance of the Redis session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createRedisDriver() + { + $handler = $this->createCacheHandler('redis'); + + $handler->getCache()->getStore()->setConnection( + $this->config->get('session.connection') + ); + + return $this->buildSession($handler); + } + + /** + * Create an instance of the DynamoDB session driver. + * + * @return \Illuminate\Session\Store + */ + protected function createDynamodbDriver() + { + return $this->createCacheBased('dynamodb'); + } + + /** + * Create an instance of a cache driven driver. + * + * @param string $driver + * @return \Illuminate\Session\Store + */ + protected function createCacheBased($driver) + { + return $this->buildSession($this->createCacheHandler($driver)); + } + + /** + * Create the cache based session handler instance. + * + * @param string $driver + * @return \Illuminate\Session\CacheBasedSessionHandler + */ + protected function createCacheHandler($driver) + { + $store = $this->config->get('session.store') ?: $driver; + + return new CacheBasedSessionHandler( + clone $this->container->make('cache')->store($store), + $this->config->get('session.lifetime') + ); + } + + /** + * Build the session instance. + * + * @param \SessionHandlerInterface $handler + * @return \Illuminate\Session\Store + */ + protected function buildSession($handler) + { + return $this->config->get('session.encrypt') + ? $this->buildEncryptedSession($handler) + : new Store($this->config->get('session.cookie'), $handler); + } + + /** + * Build the encrypted session instance. + * + * @param \SessionHandlerInterface $handler + * @return \Illuminate\Session\EncryptedStore + */ + protected function buildEncryptedSession($handler) + { + return new EncryptedStore( + $this->config->get('session.cookie'), $handler, $this->container['encrypter'] + ); + } + + /** + * Determine if requests for the same session should wait for each to finish before executing. + * + * @return bool + */ + public function shouldBlock() + { + return $this->config->get('session.block', false); + } + + /** + * Get the name of the cache store / driver that should be used to acquire session locks. + * + * @return string|null + */ + public function blockDriver() + { + return $this->config->get('session.block_store'); + } + + /** + * Get the session configuration. + * + * @return array + */ + public function getSessionConfig() + { + return $this->config->get('session'); + } + + /** + * Get the default session driver name. + * + * @return string + */ + public function getDefaultDriver() + { + return $this->config->get('session.driver'); + } + + /** + * Set the default session driver name. + * + * @param string $name + * @return void + */ + public function setDefaultDriver($name) + { + $this->config->set('session.driver', $name); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/SessionServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/SessionServiceProvider.php new file mode 100755 index 0000000..d1108e3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/SessionServiceProvider.php @@ -0,0 +1,55 @@ +registerSessionManager(); + + $this->registerSessionDriver(); + + $this->app->singleton(StartSession::class, function ($app) { + return new StartSession($app->make(SessionManager::class), function () use ($app) { + return $app->make(CacheFactory::class); + }); + }); + } + + /** + * Register the session manager instance. + * + * @return void + */ + protected function registerSessionManager() + { + $this->app->singleton('session', function ($app) { + return new SessionManager($app); + }); + } + + /** + * Register the session driver instance. + * + * @return void + */ + protected function registerSessionDriver() + { + $this->app->singleton('session.store', function ($app) { + // First, we will create the session manager which is responsible for the + // creation of the various session drivers when they are needed by the + // application instance, and will resolve them on a lazy load basis. + return $app->make('session')->driver(); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Store.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Store.php new file mode 100755 index 0000000..151e8b6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/Store.php @@ -0,0 +1,693 @@ +setId($id); + $this->name = $name; + $this->handler = $handler; + } + + /** + * Start the session, reading the data from a handler. + * + * @return bool + */ + public function start() + { + $this->loadSession(); + + if (! $this->has('_token')) { + $this->regenerateToken(); + } + + return $this->started = true; + } + + /** + * Load the session data from the handler. + * + * @return void + */ + protected function loadSession() + { + $this->attributes = array_merge($this->attributes, $this->readFromHandler()); + } + + /** + * Read the session data from the handler. + * + * @return array + */ + protected function readFromHandler() + { + if ($data = $this->handler->read($this->getId())) { + $data = @unserialize($this->prepareForUnserialize($data)); + + if ($data !== false && ! is_null($data) && is_array($data)) { + return $data; + } + } + + return []; + } + + /** + * Prepare the raw string data from the session for unserialization. + * + * @param string $data + * @return string + */ + protected function prepareForUnserialize($data) + { + return $data; + } + + /** + * Save the session data to storage. + * + * @return void + */ + public function save() + { + $this->ageFlashData(); + + $this->handler->write($this->getId(), $this->prepareForStorage( + serialize($this->attributes) + )); + + $this->started = false; + } + + /** + * Prepare the serialized session data for storage. + * + * @param string $data + * @return string + */ + protected function prepareForStorage($data) + { + return $data; + } + + /** + * Age the flash data for the session. + * + * @return void + */ + public function ageFlashData() + { + $this->forget($this->get('_flash.old', [])); + + $this->put('_flash.old', $this->get('_flash.new', [])); + + $this->put('_flash.new', []); + } + + /** + * Get all of the session data. + * + * @return array + */ + public function all() + { + return $this->attributes; + } + + /** + * Get a subset of the session data. + * + * @param array $keys + * @return array + */ + public function only(array $keys) + { + return Arr::only($this->attributes, $keys); + } + + /** + * Checks if a key exists. + * + * @param string|array $key + * @return bool + */ + public function exists($key) + { + $placeholder = new stdClass; + + return ! collect(is_array($key) ? $key : func_get_args())->contains(function ($key) use ($placeholder) { + return $this->get($key, $placeholder) === $placeholder; + }); + } + + /** + * Determine if the given key is missing from the session data. + * + * @param string|array $key + * @return bool + */ + public function missing($key) + { + return ! $this->exists($key); + } + + /** + * Checks if a key is present and not null. + * + * @param string|array $key + * @return bool + */ + public function has($key) + { + return ! collect(is_array($key) ? $key : func_get_args())->contains(function ($key) { + return is_null($this->get($key)); + }); + } + + /** + * Get an item from the session. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + return Arr::get($this->attributes, $key, $default); + } + + /** + * Get the value of a given key and then forget it. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function pull($key, $default = null) + { + return Arr::pull($this->attributes, $key, $default); + } + + /** + * Determine if the session contains old input. + * + * @param string|null $key + * @return bool + */ + public function hasOldInput($key = null) + { + $old = $this->getOldInput($key); + + return is_null($key) ? count($old) > 0 : ! is_null($old); + } + + /** + * Get the requested item from the flashed input array. + * + * @param string|null $key + * @param mixed $default + * @return mixed + */ + public function getOldInput($key = null, $default = null) + { + return Arr::get($this->get('_old_input', []), $key, $default); + } + + /** + * Replace the given session attributes entirely. + * + * @param array $attributes + * @return void + */ + public function replace(array $attributes) + { + $this->put($attributes); + } + + /** + * Put a key / value pair or array of key / value pairs in the session. + * + * @param string|array $key + * @param mixed $value + * @return void + */ + public function put($key, $value = null) + { + if (! is_array($key)) { + $key = [$key => $value]; + } + + foreach ($key as $arrayKey => $arrayValue) { + Arr::set($this->attributes, $arrayKey, $arrayValue); + } + } + + /** + * Get an item from the session, or store the default value. + * + * @param string $key + * @param \Closure $callback + * @return mixed + */ + public function remember($key, Closure $callback) + { + if (! is_null($value = $this->get($key))) { + return $value; + } + + return tap($callback(), function ($value) use ($key) { + $this->put($key, $value); + }); + } + + /** + * Push a value onto a session array. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function push($key, $value) + { + $array = $this->get($key, []); + + $array[] = $value; + + $this->put($key, $array); + } + + /** + * Increment the value of an item in the session. + * + * @param string $key + * @param int $amount + * @return mixed + */ + public function increment($key, $amount = 1) + { + $this->put($key, $value = $this->get($key, 0) + $amount); + + return $value; + } + + /** + * Decrement the value of an item in the session. + * + * @param string $key + * @param int $amount + * @return int + */ + public function decrement($key, $amount = 1) + { + return $this->increment($key, $amount * -1); + } + + /** + * Flash a key / value pair to the session. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function flash(string $key, $value = true) + { + $this->put($key, $value); + + $this->push('_flash.new', $key); + + $this->removeFromOldFlashData([$key]); + } + + /** + * Flash a key / value pair to the session for immediate use. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function now($key, $value) + { + $this->put($key, $value); + + $this->push('_flash.old', $key); + } + + /** + * Reflash all of the session flash data. + * + * @return void + */ + public function reflash() + { + $this->mergeNewFlashes($this->get('_flash.old', [])); + + $this->put('_flash.old', []); + } + + /** + * Reflash a subset of the current flash data. + * + * @param array|mixed $keys + * @return void + */ + public function keep($keys = null) + { + $this->mergeNewFlashes($keys = is_array($keys) ? $keys : func_get_args()); + + $this->removeFromOldFlashData($keys); + } + + /** + * Merge new flash keys into the new flash array. + * + * @param array $keys + * @return void + */ + protected function mergeNewFlashes(array $keys) + { + $values = array_unique(array_merge($this->get('_flash.new', []), $keys)); + + $this->put('_flash.new', $values); + } + + /** + * Remove the given keys from the old flash data. + * + * @param array $keys + * @return void + */ + protected function removeFromOldFlashData(array $keys) + { + $this->put('_flash.old', array_diff($this->get('_flash.old', []), $keys)); + } + + /** + * Flash an input array to the session. + * + * @param array $value + * @return void + */ + public function flashInput(array $value) + { + $this->flash('_old_input', $value); + } + + /** + * Remove an item from the session, returning its value. + * + * @param string $key + * @return mixed + */ + public function remove($key) + { + return Arr::pull($this->attributes, $key); + } + + /** + * Remove one or many items from the session. + * + * @param string|array $keys + * @return void + */ + public function forget($keys) + { + Arr::forget($this->attributes, $keys); + } + + /** + * Remove all of the items from the session. + * + * @return void + */ + public function flush() + { + $this->attributes = []; + } + + /** + * Flush the session data and regenerate the ID. + * + * @return bool + */ + public function invalidate() + { + $this->flush(); + + return $this->migrate(true); + } + + /** + * Generate a new session identifier. + * + * @param bool $destroy + * @return bool + */ + public function regenerate($destroy = false) + { + return tap($this->migrate($destroy), function () { + $this->regenerateToken(); + }); + } + + /** + * Generate a new session ID for the session. + * + * @param bool $destroy + * @return bool + */ + public function migrate($destroy = false) + { + if ($destroy) { + $this->handler->destroy($this->getId()); + } + + $this->setExists(false); + + $this->setId($this->generateSessionId()); + + return true; + } + + /** + * Determine if the session has been started. + * + * @return bool + */ + public function isStarted() + { + return $this->started; + } + + /** + * Get the name of the session. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set the name of the session. + * + * @param string $name + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * Get the current session ID. + * + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * Set the session ID. + * + * @param string $id + * @return void + */ + public function setId($id) + { + $this->id = $this->isValidId($id) ? $id : $this->generateSessionId(); + } + + /** + * Determine if this is a valid session ID. + * + * @param string $id + * @return bool + */ + public function isValidId($id) + { + return is_string($id) && ctype_alnum($id) && strlen($id) === 40; + } + + /** + * Get a new, random session ID. + * + * @return string + */ + protected function generateSessionId() + { + return Str::random(40); + } + + /** + * Set the existence of the session on the handler if applicable. + * + * @param bool $value + * @return void + */ + public function setExists($value) + { + if ($this->handler instanceof ExistenceAwareInterface) { + $this->handler->setExists($value); + } + } + + /** + * Get the CSRF token value. + * + * @return string + */ + public function token() + { + return $this->get('_token'); + } + + /** + * Regenerate the CSRF token value. + * + * @return void + */ + public function regenerateToken() + { + $this->put('_token', Str::random(40)); + } + + /** + * Get the previous URL from the session. + * + * @return string|null + */ + public function previousUrl() + { + return $this->get('_previous.url'); + } + + /** + * Set the "previous" URL in the session. + * + * @param string $url + * @return void + */ + public function setPreviousUrl($url) + { + $this->put('_previous.url', $url); + } + + /** + * Specify that the user has confirmed their password. + * + * @return void + */ + public function passwordConfirmed() + { + $this->put('auth.password_confirmed_at', time()); + } + + /** + * Get the underlying session handler implementation. + * + * @return \SessionHandlerInterface + */ + public function getHandler() + { + return $this->handler; + } + + /** + * Determine if the session handler needs a request. + * + * @return bool + */ + public function handlerNeedsRequest() + { + return $this->handler instanceof CookieSessionHandler; + } + + /** + * Set the request on the handler instance. + * + * @param \Illuminate\Http\Request $request + * @return void + */ + public function setRequestOnHandler($request) + { + if ($this->handlerNeedsRequest()) { + $this->handler->setRequest($request); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/TokenMismatchException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/TokenMismatchException.php new file mode 100755 index 0000000..98d99a1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Session/TokenMismatchException.php @@ -0,0 +1,10 @@ +instances = []; + + foreach ($this->providers as $provider) { + $this->instances[] = $this->app->register($provider); + } + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + $provides = []; + + foreach ($this->providers as $provider) { + $instance = $this->app->resolveProvider($provider); + + $provides = array_merge($provides, $instance->provides()); + } + + return $provides; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Carbon.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Carbon.php new file mode 100644 index 0000000..004b27b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Carbon.php @@ -0,0 +1,18 @@ +files = $files; + $this->workingPath = $workingPath; + } + + /** + * Regenerate the Composer autoloader files. + * + * @param string|array $extra + * @return int + */ + public function dumpAutoloads($extra = '') + { + $extra = $extra ? (array) $extra : []; + + $command = array_merge($this->findComposer(), ['dump-autoload'], $extra); + + return $this->getProcess($command)->run(); + } + + /** + * Regenerate the optimized Composer autoloader files. + * + * @return int + */ + public function dumpOptimized() + { + return $this->dumpAutoloads('--optimize'); + } + + /** + * Get the composer command for the environment. + * + * @return array + */ + protected function findComposer() + { + if ($this->files->exists($this->workingPath.'/composer.phar')) { + return [$this->phpBinary(), 'composer.phar']; + } + + return ['composer']; + } + + /** + * Get the PHP binary. + * + * @return string + */ + protected function phpBinary() + { + return ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)); + } + + /** + * Get a new Symfony process instance. + * + * @param array $command + * @return \Symfony\Component\Process\Process + */ + protected function getProcess(array $command) + { + return (new Process($command, $this->workingPath))->setTimeout(null); + } + + /** + * Set the working path used by the class. + * + * @param string $path + * @return $this + */ + public function setWorkingPath($path) + { + $this->workingPath = realpath($path); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ConfigurationUrlParser.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ConfigurationUrlParser.php new file mode 100644 index 0000000..be54b9a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ConfigurationUrlParser.php @@ -0,0 +1,193 @@ + 'sqlsrv', + 'mysql2' => 'mysql', // RDS + 'postgres' => 'pgsql', + 'postgresql' => 'pgsql', + 'sqlite3' => 'sqlite', + 'redis' => 'tcp', + 'rediss' => 'tls', + ]; + + /** + * Parse the database configuration, hydrating options using a database configuration URL if possible. + * + * @param array|string $config + * @return array + */ + public function parseConfiguration($config) + { + if (is_string($config)) { + $config = ['url' => $config]; + } + + $url = Arr::pull($config, 'url'); + + if (! $url) { + return $config; + } + + $rawComponents = $this->parseUrl($url); + + $decodedComponents = $this->parseStringsToNativeTypes( + array_map('rawurldecode', $rawComponents) + ); + + return array_merge( + $config, + $this->getPrimaryOptions($decodedComponents), + $this->getQueryOptions($rawComponents) + ); + } + + /** + * Get the primary database connection options. + * + * @param array $url + * @return array + */ + protected function getPrimaryOptions($url) + { + return array_filter([ + 'driver' => $this->getDriver($url), + 'database' => $this->getDatabase($url), + 'host' => $url['host'] ?? null, + 'port' => $url['port'] ?? null, + 'username' => $url['user'] ?? null, + 'password' => $url['pass'] ?? null, + ], function ($value) { + return ! is_null($value); + }); + } + + /** + * Get the database driver from the URL. + * + * @param array $url + * @return string|null + */ + protected function getDriver($url) + { + $alias = $url['scheme'] ?? null; + + if (! $alias) { + return; + } + + return static::$driverAliases[$alias] ?? $alias; + } + + /** + * Get the database name from the URL. + * + * @param array $url + * @return string|null + */ + protected function getDatabase($url) + { + $path = $url['path'] ?? null; + + return $path && $path !== '/' ? substr($path, 1) : null; + } + + /** + * Get all of the additional database options from the query string. + * + * @param array $url + * @return array + */ + protected function getQueryOptions($url) + { + $queryString = $url['query'] ?? null; + + if (! $queryString) { + return []; + } + + $query = []; + + parse_str($queryString, $query); + + return $this->parseStringsToNativeTypes($query); + } + + /** + * Parse the string URL to an array of components. + * + * @param string $url + * @return array + * + * @throws \InvalidArgumentException + */ + protected function parseUrl($url) + { + $url = preg_replace('#^(sqlite3?):///#', '$1://null/', $url); + + $parsedUrl = parse_url($url); + + if ($parsedUrl === false) { + throw new InvalidArgumentException('The database configuration URL is malformed.'); + } + + return $parsedUrl; + } + + /** + * Convert string casted values to their native types. + * + * @param mixed $value + * @return mixed + */ + protected function parseStringsToNativeTypes($value) + { + if (is_array($value)) { + return array_map([$this, 'parseStringsToNativeTypes'], $value); + } + + if (! is_string($value)) { + return $value; + } + + $parsedValue = json_decode($value, true); + + if (json_last_error() === JSON_ERROR_NONE) { + return $parsedValue; + } + + return $value; + } + + /** + * Get all of the current drivers' aliases. + * + * @return array + */ + public static function getDriverAliases() + { + return static::$driverAliases; + } + + /** + * Add the given driver alias to the driver aliases array. + * + * @param string $alias + * @param string $driver + * @return void + */ + public static function addDriverAlias($alias, $driver) + { + static::$driverAliases[$alias] = $driver; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/DateFactory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/DateFactory.php new file mode 100644 index 0000000..f36cb46 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/DateFactory.php @@ -0,0 +1,231 @@ +$method(...$parameters); + } + + $dateClass = static::$dateClass ?: $defaultClassName; + + // Check if date can be created using public class method... + if (method_exists($dateClass, $method) || + method_exists($dateClass, 'hasMacro') && $dateClass::hasMacro($method)) { + return $dateClass::$method(...$parameters); + } + + // If that fails, create the date with the default class... + $date = $defaultClassName::$method(...$parameters); + + // If the configured class has an "instance" method, we'll try to pass our date into there... + if (method_exists($dateClass, 'instance')) { + return $dateClass::instance($date); + } + + // Otherwise, assume the configured class has a DateTime compatible constructor... + return new $dateClass($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Env.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Env.php new file mode 100644 index 0000000..b310073 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Env.php @@ -0,0 +1,103 @@ +addAdapter(PutenvAdapter::class); + } + + static::$repository = $builder->immutable()->make(); + } + + return static::$repository; + } + + /** + * Gets the value of an environment variable. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public static function get($key, $default = null) + { + return Option::fromValue(static::getRepository()->get($key)) + ->map(function ($value) { + switch (strtolower($value)) { + case 'true': + case '(true)': + return true; + case 'false': + case '(false)': + return false; + case 'empty': + case '(empty)': + return ''; + case 'null': + case '(null)': + return; + } + + if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) { + return $matches[2]; + } + + return $value; + }) + ->getOrCall(function () use ($default) { + return value($default); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/App.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/App.php new file mode 100755 index 0000000..8fbec3d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/App.php @@ -0,0 +1,64 @@ +providerIsLoaded(UiServiceProvider::class)) { + throw new RuntimeException('In order to use the Auth::routes() method, please install the laravel/ui package.'); + } + + static::$app->make('router')->auth($options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Blade.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Blade.php new file mode 100755 index 0000000..81019e2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Blade.php @@ -0,0 +1,46 @@ +dispatch(); + } + + /** + * Get the registered name of the component. + * + * @return string + */ + protected static function getFacadeAccessor() + { + return BusDispatcherContract::class; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Cache.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Cache.php new file mode 100755 index 0000000..70aa1dc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Cache.php @@ -0,0 +1,40 @@ +cookie($key, null)); + } + + /** + * Retrieve a cookie from the request. + * + * @param string|null $key + * @param mixed $default + * @return string|array|null + */ + public static function get($key = null, $default = null) + { + return static::$app['request']->cookie($key, $default); + } + + /** + * Get the registered name of the component. + * + * @return string + */ + protected static function getFacadeAccessor() + { + return 'cookie'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Crypt.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Crypt.php new file mode 100755 index 0000000..61eaaa8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Crypt.php @@ -0,0 +1,27 @@ +resolved($accessor) === true) { + $callback(static::getFacadeRoot()); + } + + static::$app->afterResolving($accessor, function ($service) use ($callback) { + $callback($service); + }); + } + + /** + * Convert the facade into a Mockery spy. + * + * @return \Mockery\MockInterface + */ + public static function spy() + { + if (! static::isMock()) { + $class = static::getMockableClass(); + + return tap($class ? Mockery::spy($class) : Mockery::spy(), function ($spy) { + static::swap($spy); + }); + } + } + + /** + * Initiate a partial mock on the facade. + * + * @return \Mockery\MockInterface + */ + public static function partialMock() + { + $name = static::getFacadeAccessor(); + + $mock = static::isMock() + ? static::$resolvedInstance[$name] + : static::createFreshMockInstance(); + + return $mock->makePartial(); + } + + /** + * Initiate a mock expectation on the facade. + * + * @return \Mockery\Expectation + */ + public static function shouldReceive() + { + $name = static::getFacadeAccessor(); + + $mock = static::isMock() + ? static::$resolvedInstance[$name] + : static::createFreshMockInstance(); + + return $mock->shouldReceive(...func_get_args()); + } + + /** + * Create a fresh mock instance for the given class. + * + * @return \Mockery\MockInterface + */ + protected static function createFreshMockInstance() + { + return tap(static::createMock(), function ($mock) { + static::swap($mock); + + $mock->shouldAllowMockingProtectedMethods(); + }); + } + + /** + * Create a fresh mock instance for the given class. + * + * @return \Mockery\MockInterface + */ + protected static function createMock() + { + $class = static::getMockableClass(); + + return $class ? Mockery::mock($class) : Mockery::mock(); + } + + /** + * Determines whether a mock is set as the instance of the facade. + * + * @return bool + */ + protected static function isMock() + { + $name = static::getFacadeAccessor(); + + return isset(static::$resolvedInstance[$name]) && + static::$resolvedInstance[$name] instanceof LegacyMockInterface; + } + + /** + * Get the mockable class for the bound instance. + * + * @return string|null + */ + protected static function getMockableClass() + { + if ($root = static::getFacadeRoot()) { + return get_class($root); + } + } + + /** + * Hotswap the underlying instance behind the facade. + * + * @param mixed $instance + * @return void + */ + public static function swap($instance) + { + static::$resolvedInstance[static::getFacadeAccessor()] = $instance; + + if (isset(static::$app)) { + static::$app->instance(static::getFacadeAccessor(), $instance); + } + } + + /** + * Get the root object behind the facade. + * + * @return mixed + */ + public static function getFacadeRoot() + { + return static::resolveFacadeInstance(static::getFacadeAccessor()); + } + + /** + * Get the registered name of the component. + * + * @return string + * + * @throws \RuntimeException + */ + protected static function getFacadeAccessor() + { + throw new RuntimeException('Facade does not implement getFacadeAccessor method.'); + } + + /** + * Resolve the facade root instance from the container. + * + * @param object|string $name + * @return mixed + */ + protected static function resolveFacadeInstance($name) + { + if (is_object($name)) { + return $name; + } + + if (isset(static::$resolvedInstance[$name])) { + return static::$resolvedInstance[$name]; + } + + if (static::$app) { + return static::$resolvedInstance[$name] = static::$app[$name]; + } + } + + /** + * Clear a resolved facade instance. + * + * @param string $name + * @return void + */ + public static function clearResolvedInstance($name) + { + unset(static::$resolvedInstance[$name]); + } + + /** + * Clear all of the resolved instances. + * + * @return void + */ + public static function clearResolvedInstances() + { + static::$resolvedInstance = []; + } + + /** + * Get the application instance behind the facade. + * + * @return \Illuminate\Contracts\Foundation\Application + */ + public static function getFacadeApplication() + { + return static::$app; + } + + /** + * Set the application instance. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return void + */ + public static function setFacadeApplication($app) + { + static::$app = $app; + } + + /** + * Handle dynamic, static calls to the object. + * + * @param string $method + * @param array $args + * @return mixed + * + * @throws \RuntimeException + */ + public static function __callStatic($method, $args) + { + $instance = static::getFacadeRoot(); + + if (! $instance) { + throw new RuntimeException('A facade root has not been set.'); + } + + return $instance->$method(...$args); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/File.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/File.php new file mode 100755 index 0000000..c22d363 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/File.php @@ -0,0 +1,62 @@ +route($channel, $route); + } + + /** + * Get the registered name of the component. + * + * @return string + */ + protected static function getFacadeAccessor() + { + return ChannelManager::class; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/ParallelTesting.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/ParallelTesting.php new file mode 100644 index 0000000..c397611 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/ParallelTesting.php @@ -0,0 +1,26 @@ +connection($name)->getSchemaBuilder(); + } + + /** + * Get a schema builder instance for the default connection. + * + * @return \Illuminate\Database\Schema\Builder + */ + protected static function getFacadeAccessor() + { + return static::$app['db']->connection()->getSchemaBuilder(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Session.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Session.php new file mode 100755 index 0000000..a072321 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/Session.php @@ -0,0 +1,45 @@ +get('filesystems.default'); + + $root = storage_path('framework/testing/disks/'.$disk); + + if ($token = ParallelTesting::token()) { + $root = "{$root}_test_{$token}"; + } + + (new Filesystem)->cleanDirectory($root); + + static::set($disk, $fake = static::createLocalDriver(array_merge($config, [ + 'root' => $root, + ]))); + + return $fake; + } + + /** + * Replace the given disk with a persistent local testing disk. + * + * @param string|null $disk + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Filesystem + */ + public static function persistentFake($disk = null, array $config = []) + { + $disk = $disk ?: static::$app['config']->get('filesystems.default'); + + static::set($disk, $fake = static::createLocalDriver(array_merge($config, [ + 'root' => storage_path('framework/testing/disks/'.$disk), + ]))); + + return $fake; + } + + /** + * Get the registered name of the component. + * + * @return string + */ + protected static function getFacadeAccessor() + { + return 'filesystem'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/URL.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/URL.php new file mode 100755 index 0000000..7d9941d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Facades/URL.php @@ -0,0 +1,38 @@ + $value) { + $this->attributes[$key] = $value; + } + } + + /** + * Get an attribute from the fluent instance. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + if (array_key_exists($key, $this->attributes)) { + return $this->attributes[$key]; + } + + return value($default); + } + + /** + * Get the attributes from the fluent instance. + * + * @return array + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Convert the fluent instance to an array. + * + * @return array + */ + public function toArray() + { + return $this->attributes; + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Convert the fluent instance to JSON. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return isset($this->attributes[$offset]); + } + + /** + * Get the value for a given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->get($offset); + } + + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + $this->attributes[$offset] = $value; + } + + /** + * Unset the value at the given offset. + * + * @param string $offset + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + unset($this->attributes[$offset]); + } + + /** + * Handle dynamic calls to the fluent instance to set attributes. + * + * @param string $method + * @param array $parameters + * @return $this + */ + public function __call($method, $parameters) + { + $this->attributes[$method] = count($parameters) > 0 ? $parameters[0] : true; + + return $this; + } + + /** + * Dynamically retrieve the value of an attribute. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->get($key); + } + + /** + * Dynamically set the value of an attribute. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function __set($key, $value) + { + $this->offsetSet($key, $value); + } + + /** + * Dynamically check if an attribute is set. + * + * @param string $key + * @return bool + */ + public function __isset($key) + { + return $this->offsetExists($key); + } + + /** + * Dynamically unset an attribute. + * + * @param string $key + * @return void + */ + public function __unset($key) + { + $this->offsetUnset($key); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/HigherOrderTapProxy.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/HigherOrderTapProxy.php new file mode 100644 index 0000000..bbf9b2e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/HigherOrderTapProxy.php @@ -0,0 +1,38 @@ +target = $target; + } + + /** + * Dynamically pass method calls to the target. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + $this->target->{$method}(...$parameters); + + return $this->target; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/HtmlString.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/HtmlString.php new file mode 100644 index 0000000..d6b71d4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/HtmlString.php @@ -0,0 +1,66 @@ +html = $html; + } + + /** + * Get the HTML string. + * + * @return string + */ + public function toHtml() + { + return $this->html; + } + + /** + * Determine if the given HTML string is empty. + * + * @return bool + */ + public function isEmpty() + { + return $this->html === ''; + } + + /** + * Determine if the given HTML string is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return ! $this->isEmpty(); + } + + /** + * Get the HTML string. + * + * @return string + */ + public function __toString() + { + return $this->toHtml(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/InteractsWithTime.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/InteractsWithTime.php new file mode 100644 index 0000000..2b617c3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/InteractsWithTime.php @@ -0,0 +1,64 @@ +parseDateInterval($delay); + + return $delay instanceof DateTimeInterface + ? max(0, $delay->getTimestamp() - $this->currentTime()) + : (int) $delay; + } + + /** + * Get the "available at" UNIX timestamp. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @return int + */ + protected function availableAt($delay = 0) + { + $delay = $this->parseDateInterval($delay); + + return $delay instanceof DateTimeInterface + ? $delay->getTimestamp() + : Carbon::now()->addRealSeconds($delay)->getTimestamp(); + } + + /** + * If the given value is an interval, convert it to a DateTime instance. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @return \DateTimeInterface|int + */ + protected function parseDateInterval($delay) + { + if ($delay instanceof DateInterval) { + $delay = Carbon::now()->add($delay); + } + + return $delay; + } + + /** + * Get the current system time as a UNIX timestamp. + * + * @return int + */ + protected function currentTime() + { + return Carbon::now()->getTimestamp(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Js.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Js.php new file mode 100644 index 0000000..6d6de34 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Js.php @@ -0,0 +1,145 @@ +js = $this->convertDataToJavaScriptExpression($data, $flags, $depth); + } + + /** + * Create a new JavaScript string from the given data. + * + * @param mixed $data + * @param int $flags + * @param int $depth + * @return static + * + * @throws \JsonException + */ + public static function from($data, $flags = 0, $depth = 512) + { + return new static($data, $flags, $depth); + } + + /** + * Convert the given data to a JavaScript expression. + * + * @param mixed $data + * @param int $flags + * @param int $depth + * @return string + * + * @throws \JsonException + */ + protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth = 512) + { + if ($data instanceof self) { + return $data->toHtml(); + } + + $json = $this->jsonEncode($data, $flags, $depth); + + if (is_string($data)) { + return "'".substr($json, 1, -1)."'"; + } + + return $this->convertJsonToJavaScriptExpression($json, $flags); + } + + /** + * Encode the given data as JSON. + * + * @param mixed $data + * @param int $flags + * @param int $depth + * @return string + * + * @throws \JsonException + */ + protected function jsonEncode($data, $flags = 0, $depth = 512) + { + if ($data instanceof Jsonable) { + return $data->toJson($flags | static::REQUIRED_FLAGS); + } + + if ($data instanceof Arrayable && ! ($data instanceof JsonSerializable)) { + $data = $data->toArray(); + } + + return json_encode($data, $flags | static::REQUIRED_FLAGS, $depth); + } + + /** + * Convert the given JSON to a JavaScript expression. + * + * @param string $json + * @param int $flags + * @return string + * + * @throws \JsonException + */ + protected function convertJsonToJavaScriptExpression($json, $flags = 0) + { + if ('[]' === $json || '{}' === $json) { + return $json; + } + + if (Str::startsWith($json, ['"', '{', '['])) { + return "JSON.parse('".substr(json_encode($json, $flags | static::REQUIRED_FLAGS), 1, -1)."')"; + } + + return $json; + } + + /** + * Get the string representation of the data for use in HTML. + * + * @return string + */ + public function toHtml() + { + return $this->js; + } + + /** + * Get the string representation of the data for use in HTML. + * + * @return string + */ + public function __toString() + { + return $this->toHtml(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Manager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Manager.php new file mode 100755 index 0000000..f8ae072 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Manager.php @@ -0,0 +1,193 @@ +container = $container; + $this->config = $container->make('config'); + } + + /** + * Get the default driver name. + * + * @return string + */ + abstract public function getDefaultDriver(); + + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function driver($driver = null) + { + $driver = $driver ?: $this->getDefaultDriver(); + + if (is_null($driver)) { + throw new InvalidArgumentException(sprintf( + 'Unable to resolve NULL driver for [%s].', static::class + )); + } + + // If the given driver has not been created before, we will create the instances + // here and cache it so we can return it next time very quickly. If there is + // already a driver created by this name, we'll just return that instance. + if (! isset($this->drivers[$driver])) { + $this->drivers[$driver] = $this->createDriver($driver); + } + + return $this->drivers[$driver]; + } + + /** + * Create a new driver instance. + * + * @param string $driver + * @return mixed + * + * @throws \InvalidArgumentException + */ + protected function createDriver($driver) + { + // First, we will determine if a custom driver creator exists for the given driver and + // if it does not we will check for a creator method for the driver. Custom creator + // callbacks allow developers to build their own "drivers" easily using Closures. + if (isset($this->customCreators[$driver])) { + return $this->callCustomCreator($driver); + } else { + $method = 'create'.Str::studly($driver).'Driver'; + + if (method_exists($this, $method)) { + return $this->$method(); + } + } + + throw new InvalidArgumentException("Driver [$driver] not supported."); + } + + /** + * Call a custom driver creator. + * + * @param string $driver + * @return mixed + */ + protected function callCustomCreator($driver) + { + return $this->customCreators[$driver]($this->container); + } + + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return $this + */ + public function extend($driver, Closure $callback) + { + $this->customCreators[$driver] = $callback; + + return $this; + } + + /** + * Get all of the created "drivers". + * + * @return array + */ + public function getDrivers() + { + return $this->drivers; + } + + /** + * Get the container instance used by the manager. + * + * @return \Illuminate\Contracts\Container\Container + */ + public function getContainer() + { + return $this->container; + } + + /** + * Set the container instance used by the manager. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } + + /** + * Forget all of the resolved driver instances. + * + * @return $this + */ + public function forgetDrivers() + { + $this->drivers = []; + + return $this; + } + + /** + * Dynamically call the default driver instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->driver()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/MessageBag.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/MessageBag.php new file mode 100755 index 0000000..e53d509 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/MessageBag.php @@ -0,0 +1,418 @@ + $value) { + $value = $value instanceof Arrayable ? $value->toArray() : (array) $value; + + $this->messages[$key] = array_unique($value); + } + } + + /** + * Get the keys present in the message bag. + * + * @return array + */ + public function keys() + { + return array_keys($this->messages); + } + + /** + * Add a message to the message bag. + * + * @param string $key + * @param string $message + * @return $this + */ + public function add($key, $message) + { + if ($this->isUnique($key, $message)) { + $this->messages[$key][] = $message; + } + + return $this; + } + + /** + * Add a message to the message bag if the given conditional is "true". + * + * @param bool $boolean + * @param string $key + * @param string $message + * @return $this + */ + public function addIf($boolean, $key, $message) + { + return $boolean ? $this->add($key, $message) : $this; + } + + /** + * Determine if a key and message combination already exists. + * + * @param string $key + * @param string $message + * @return bool + */ + protected function isUnique($key, $message) + { + $messages = (array) $this->messages; + + return ! isset($messages[$key]) || ! in_array($message, $messages[$key]); + } + + /** + * Merge a new array of messages into the message bag. + * + * @param \Illuminate\Contracts\Support\MessageProvider|array $messages + * @return $this + */ + public function merge($messages) + { + if ($messages instanceof MessageProvider) { + $messages = $messages->getMessageBag()->getMessages(); + } + + $this->messages = array_merge_recursive($this->messages, $messages); + + return $this; + } + + /** + * Determine if messages exist for all of the given keys. + * + * @param array|string|null $key + * @return bool + */ + public function has($key) + { + if ($this->isEmpty()) { + return false; + } + + if (is_null($key)) { + return $this->any(); + } + + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $key) { + if ($this->first($key) === '') { + return false; + } + } + + return true; + } + + /** + * Determine if messages exist for any of the given keys. + * + * @param array|string $keys + * @return bool + */ + public function hasAny($keys = []) + { + if ($this->isEmpty()) { + return false; + } + + $keys = is_array($keys) ? $keys : func_get_args(); + + foreach ($keys as $key) { + if ($this->has($key)) { + return true; + } + } + + return false; + } + + /** + * Get the first message from the message bag for a given key. + * + * @param string|null $key + * @param string|null $format + * @return string + */ + public function first($key = null, $format = null) + { + $messages = is_null($key) ? $this->all($format) : $this->get($key, $format); + + $firstMessage = Arr::first($messages, null, ''); + + return is_array($firstMessage) ? Arr::first($firstMessage) : $firstMessage; + } + + /** + * Get all of the messages from the message bag for a given key. + * + * @param string $key + * @param string|null $format + * @return array + */ + public function get($key, $format = null) + { + // If the message exists in the message bag, we will transform it and return + // the message. Otherwise, we will check if the key is implicit & collect + // all the messages that match the given key and output it as an array. + if (array_key_exists($key, $this->messages)) { + return $this->transform( + $this->messages[$key], $this->checkFormat($format), $key + ); + } + + if (Str::contains($key, '*')) { + return $this->getMessagesForWildcardKey($key, $format); + } + + return []; + } + + /** + * Get the messages for a wildcard key. + * + * @param string $key + * @param string|null $format + * @return array + */ + protected function getMessagesForWildcardKey($key, $format) + { + return collect($this->messages) + ->filter(function ($messages, $messageKey) use ($key) { + return Str::is($key, $messageKey); + }) + ->map(function ($messages, $messageKey) use ($format) { + return $this->transform( + $messages, $this->checkFormat($format), $messageKey + ); + })->all(); + } + + /** + * Get all of the messages for every key in the message bag. + * + * @param string|null $format + * @return array + */ + public function all($format = null) + { + $format = $this->checkFormat($format); + + $all = []; + + foreach ($this->messages as $key => $messages) { + $all = array_merge($all, $this->transform($messages, $format, $key)); + } + + return $all; + } + + /** + * Get all of the unique messages for every key in the message bag. + * + * @param string|null $format + * @return array + */ + public function unique($format = null) + { + return array_unique($this->all($format)); + } + + /** + * Format an array of messages. + * + * @param array $messages + * @param string $format + * @param string $messageKey + * @return array + */ + protected function transform($messages, $format, $messageKey) + { + return collect((array) $messages) + ->map(function ($message) use ($format, $messageKey) { + // We will simply spin through the given messages and transform each one + // replacing the :message place holder with the real message allowing + // the messages to be easily formatted to each developer's desires. + return str_replace([':message', ':key'], [$message, $messageKey], $format); + })->all(); + } + + /** + * Get the appropriate format based on the given format. + * + * @param string $format + * @return string + */ + protected function checkFormat($format) + { + return $format ?: $this->format; + } + + /** + * Get the raw messages in the message bag. + * + * @return array + */ + public function messages() + { + return $this->messages; + } + + /** + * Get the raw messages in the message bag. + * + * @return array + */ + public function getMessages() + { + return $this->messages(); + } + + /** + * Get the messages for the instance. + * + * @return \Illuminate\Support\MessageBag + */ + public function getMessageBag() + { + return $this; + } + + /** + * Get the default message format. + * + * @return string + */ + public function getFormat() + { + return $this->format; + } + + /** + * Set the default message format. + * + * @param string $format + * @return \Illuminate\Support\MessageBag + */ + public function setFormat($format = ':message') + { + $this->format = $format; + + return $this; + } + + /** + * Determine if the message bag has any messages. + * + * @return bool + */ + public function isEmpty() + { + return ! $this->any(); + } + + /** + * Determine if the message bag has any messages. + * + * @return bool + */ + public function isNotEmpty() + { + return $this->any(); + } + + /** + * Determine if the message bag has any messages. + * + * @return bool + */ + public function any() + { + return $this->count() > 0; + } + + /** + * Get the number of messages in the message bag. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return count($this->messages, COUNT_RECURSIVE) - count($this->messages); + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return $this->getMessages(); + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } + + /** + * Convert the message bag to its string representation. + * + * @return string + */ + public function __toString() + { + return $this->toJson(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/MultipleInstanceManager.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/MultipleInstanceManager.php new file mode 100644 index 0000000..97cee33 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/MultipleInstanceManager.php @@ -0,0 +1,191 @@ +app = $app; + } + + /** + * Get the default instance name. + * + * @return string + */ + abstract public function getDefaultInstance(); + + /** + * Set the default instance name. + * + * @param string $name + * @return void + */ + abstract public function setDefaultInstance($name); + + /** + * Get the instance specific configuration. + * + * @param string $name + * @return array + */ + abstract public function getInstanceConfig($name); + + /** + * Get an instance instance by name. + * + * @param string|null $name + * @return mixed + */ + public function instance($name = null) + { + $name = $name ?: $this->getDefaultInstance(); + + return $this->instances[$name] = $this->get($name); + } + + /** + * Attempt to get an instance from the local cache. + * + * @param string $name + * @return mixed + */ + protected function get($name) + { + return $this->instances[$name] ?? $this->resolve($name); + } + + /** + * Resolve the given instance. + * + * @param string $name + * @return mixed + * + * @throws \InvalidArgumentException + */ + protected function resolve($name) + { + $config = $this->getInstanceConfig($name); + + if (is_null($config)) { + throw new InvalidArgumentException("Instance [{$name}] is not defined."); + } + + if (! array_key_exists('driver', $config)) { + throw new RuntimeException("Instance [{$name}] does not specify a driver."); + } + + if (isset($this->customCreators[$config['driver']])) { + return $this->callCustomCreator($config); + } else { + $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; + + if (method_exists($this, $driverMethod)) { + return $this->{$driverMethod}($config); + } else { + throw new InvalidArgumentException("Instance driver [{$config['driver']}] is not supported."); + } + } + } + + /** + * Call a custom instance creator. + * + * @param array $config + * @return mixed + */ + protected function callCustomCreator(array $config) + { + return $this->customCreators[$config['driver']]($this->app, $config); + } + + /** + * Unset the given instances. + * + * @param array|string|null $name + * @return $this + */ + public function forgetInstance($name = null) + { + $name = $name ?? $this->getDefaultInstance(); + + foreach ((array) $name as $instanceName) { + if (isset($this->instances[$instanceName])) { + unset($this->instances[$instanceName]); + } + } + + return $this; + } + + /** + * Disconnect the given instance and remove from local cache. + * + * @param string|null $name + * @return void + */ + public function purge($name = null) + { + $name = $name ?? $this->getDefaultInstance(); + + unset($this->instances[$name]); + } + + /** + * Register a custom instance creator Closure. + * + * @param string $name + * @param \Closure $callback + * @return $this + */ + public function extend($name, Closure $callback) + { + $this->customCreators[$name] = $callback->bindTo($this, $this); + + return $this; + } + + /** + * Dynamically call the default instance. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->instance()->$method(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/NamespacedItemResolver.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/NamespacedItemResolver.php new file mode 100755 index 0000000..a0d8508 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/NamespacedItemResolver.php @@ -0,0 +1,112 @@ +parsed[$key])) { + return $this->parsed[$key]; + } + + // If the key does not contain a double colon, it means the key is not in a + // namespace, and is just a regular configuration item. Namespaces are a + // tool for organizing configuration items for things such as modules. + if (strpos($key, '::') === false) { + $segments = explode('.', $key); + + $parsed = $this->parseBasicSegments($segments); + } else { + $parsed = $this->parseNamespacedSegments($key); + } + + // Once we have the parsed array of this key's elements, such as its groups + // and namespace, we will cache each array inside a simple list that has + // the key and the parsed array for quick look-ups for later requests. + return $this->parsed[$key] = $parsed; + } + + /** + * Parse an array of basic segments. + * + * @param array $segments + * @return array + */ + protected function parseBasicSegments(array $segments) + { + // The first segment in a basic array will always be the group, so we can go + // ahead and grab that segment. If there is only one total segment we are + // just pulling an entire group out of the array and not a single item. + $group = $segments[0]; + + // If there is more than one segment in this group, it means we are pulling + // a specific item out of a group and will need to return this item name + // as well as the group so we know which item to pull from the arrays. + $item = count($segments) === 1 + ? null + : implode('.', array_slice($segments, 1)); + + return [null, $group, $item]; + } + + /** + * Parse an array of namespaced segments. + * + * @param string $key + * @return array + */ + protected function parseNamespacedSegments($key) + { + [$namespace, $item] = explode('::', $key); + + // First we'll just explode the first segment to get the namespace and group + // since the item should be in the remaining segments. Once we have these + // two pieces of data we can proceed with parsing out the item's value. + $itemSegments = explode('.', $item); + + $groupAndItem = array_slice( + $this->parseBasicSegments($itemSegments), 1 + ); + + return array_merge([$namespace], $groupAndItem); + } + + /** + * Set the parsed value of a key. + * + * @param string $key + * @param array $parsed + * @return void + */ + public function setParsedKey($key, $parsed) + { + $this->parsed[$key] = $parsed; + } + + /** + * Flush the cache of parsed keys. + * + * @return void + */ + public function flushParsedKeys() + { + $this->parsed = []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Optional.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Optional.php new file mode 100644 index 0000000..816190d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Optional.php @@ -0,0 +1,135 @@ +value = $value; + } + + /** + * Dynamically access a property on the underlying object. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + if (is_object($this->value)) { + return $this->value->{$key} ?? null; + } + } + + /** + * Dynamically check a property exists on the underlying object. + * + * @param mixed $name + * @return bool + */ + public function __isset($name) + { + if (is_object($this->value)) { + return isset($this->value->{$name}); + } + + if (is_array($this->value) || $this->value instanceof ArrayObject) { + return isset($this->value[$name]); + } + + return false; + } + + /** + * Determine if an item exists at an offset. + * + * @param mixed $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return Arr::accessible($this->value) && Arr::exists($this->value, $key); + } + + /** + * Get an item at a given offset. + * + * @param mixed $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return Arr::get($this->value, $key); + } + + /** + * Set the item at a given offset. + * + * @param mixed $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + if (Arr::accessible($this->value)) { + $this->value[$key] = $value; + } + } + + /** + * Unset the item at a given offset. + * + * @param string $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + if (Arr::accessible($this->value)) { + unset($this->value[$key]); + } + } + + /** + * Dynamically pass a method to the underlying object. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + if (is_object($this->value)) { + return $this->value->{$method}(...$parameters); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Pluralizer.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Pluralizer.php new file mode 100755 index 0000000..109a108 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Pluralizer.php @@ -0,0 +1,142 @@ +pluralize($value); + + return static::matchCase($plural, $value); + } + + /** + * Get the singular form of an English word. + * + * @param string $value + * @return string + */ + public static function singular($value) + { + $singular = static::inflector()->singularize($value); + + return static::matchCase($singular, $value); + } + + /** + * Determine if the given value is uncountable. + * + * @param string $value + * @return bool + */ + protected static function uncountable($value) + { + return in_array(strtolower($value), static::$uncountable); + } + + /** + * Attempt to match the case on two strings. + * + * @param string $value + * @param string $comparison + * @return string + */ + protected static function matchCase($value, $comparison) + { + $functions = ['mb_strtolower', 'mb_strtoupper', 'ucfirst', 'ucwords']; + + foreach ($functions as $function) { + if ($function($comparison) === $comparison) { + return $function($value); + } + } + + return $value; + } + + /** + * Get the inflector instance. + * + * @return \Doctrine\Inflector\Inflector + */ + public static function inflector() + { + static $inflector; + + if (is_null($inflector)) { + $inflector = InflectorFactory::createForLanguage('english')->build(); + } + + return $inflector; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ProcessUtils.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ProcessUtils.php new file mode 100644 index 0000000..1caa9e1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ProcessUtils.php @@ -0,0 +1,69 @@ +isPublic(); + } + + if (is_object($var[0]) && method_exists($class, '__call')) { + return (new ReflectionMethod($class, '__call'))->isPublic(); + } + + if (! is_object($var[0]) && method_exists($class, '__callStatic')) { + return (new ReflectionMethod($class, '__callStatic'))->isPublic(); + } + + return false; + } + + /** + * Get the class name of the given parameter's type, if possible. + * + * @param \ReflectionParameter $parameter + * @return string|null + */ + public static function getParameterClassName($parameter) + { + $type = $parameter->getType(); + + if (! $type instanceof ReflectionNamedType || $type->isBuiltin()) { + return; + } + + return static::getTypeName($parameter, $type); + } + + /** + * Get the class names of the given parameter's type, including union types. + * + * @param \ReflectionParameter $parameter + * @return array + */ + public static function getParameterClassNames($parameter) + { + $type = $parameter->getType(); + + if (! $type instanceof ReflectionUnionType) { + return array_filter([static::getParameterClassName($parameter)]); + } + + $unionTypes = []; + + foreach ($type->getTypes() as $listedType) { + if (! $listedType instanceof ReflectionNamedType || $listedType->isBuiltin()) { + continue; + } + + $unionTypes[] = static::getTypeName($parameter, $listedType); + } + + return array_filter($unionTypes); + } + + /** + * Get the given type's class name. + * + * @param \ReflectionParameter $parameter + * @param \ReflectionNamedType $type + * @return string + */ + protected static function getTypeName($parameter, $type) + { + $name = $type->getName(); + + if (! is_null($class = $parameter->getDeclaringClass())) { + if ($name === 'self') { + return $class->getName(); + } + + if ($name === 'parent' && $parent = $class->getParentClass()) { + return $parent->getName(); + } + } + + return $name; + } + + /** + * Determine if the parameter's type is a subclass of the given type. + * + * @param \ReflectionParameter $parameter + * @param string $className + * @return bool + */ + public static function isParameterSubclassOf($parameter, $className) + { + $paramClassName = static::getParameterClassName($parameter); + + return $paramClassName + && (class_exists($paramClassName) || interface_exists($paramClassName)) + && (new ReflectionClass($paramClassName))->isSubclassOf($className); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php new file mode 100755 index 0000000..6c530c1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php @@ -0,0 +1,437 @@ +app = $app; + } + + /** + * Register any application services. + * + * @return void + */ + public function register() + { + // + } + + /** + * Register a booting callback to be run before the "boot" method is called. + * + * @param \Closure $callback + * @return void + */ + public function booting(Closure $callback) + { + $this->bootingCallbacks[] = $callback; + } + + /** + * Register a booted callback to be run after the "boot" method is called. + * + * @param \Closure $callback + * @return void + */ + public function booted(Closure $callback) + { + $this->bootedCallbacks[] = $callback; + } + + /** + * Call the registered booting callbacks. + * + * @return void + */ + public function callBootingCallbacks() + { + $index = 0; + + while ($index < count($this->bootingCallbacks)) { + $this->app->call($this->bootingCallbacks[$index]); + + $index++; + } + } + + /** + * Call the registered booted callbacks. + * + * @return void + */ + public function callBootedCallbacks() + { + $index = 0; + + while ($index < count($this->bootedCallbacks)) { + $this->app->call($this->bootedCallbacks[$index]); + + $index++; + } + } + + /** + * Merge the given configuration with the existing configuration. + * + * @param string $path + * @param string $key + * @return void + */ + protected function mergeConfigFrom($path, $key) + { + if (! ($this->app instanceof CachesConfiguration && $this->app->configurationIsCached())) { + $config = $this->app->make('config'); + + $config->set($key, array_merge( + require $path, $config->get($key, []) + )); + } + } + + /** + * Load the given routes file if routes are not already cached. + * + * @param string $path + * @return void + */ + protected function loadRoutesFrom($path) + { + if (! ($this->app instanceof CachesRoutes && $this->app->routesAreCached())) { + require $path; + } + } + + /** + * Register a view file namespace. + * + * @param string|array $path + * @param string $namespace + * @return void + */ + protected function loadViewsFrom($path, $namespace) + { + $this->callAfterResolving('view', function ($view) use ($path, $namespace) { + if (isset($this->app->config['view']['paths']) && + is_array($this->app->config['view']['paths'])) { + foreach ($this->app->config['view']['paths'] as $viewPath) { + if (is_dir($appPath = $viewPath.'/vendor/'.$namespace)) { + $view->addNamespace($namespace, $appPath); + } + } + } + + $view->addNamespace($namespace, $path); + }); + } + + /** + * Register the given view components with a custom prefix. + * + * @param string $prefix + * @param array $components + * @return void + */ + protected function loadViewComponentsAs($prefix, array $components) + { + $this->callAfterResolving(BladeCompiler::class, function ($blade) use ($prefix, $components) { + foreach ($components as $alias => $component) { + $blade->component($component, is_string($alias) ? $alias : null, $prefix); + } + }); + } + + /** + * Register a translation file namespace. + * + * @param string $path + * @param string $namespace + * @return void + */ + protected function loadTranslationsFrom($path, $namespace) + { + $this->callAfterResolving('translator', function ($translator) use ($path, $namespace) { + $translator->addNamespace($namespace, $path); + }); + } + + /** + * Register a JSON translation file path. + * + * @param string $path + * @return void + */ + protected function loadJsonTranslationsFrom($path) + { + $this->callAfterResolving('translator', function ($translator) use ($path) { + $translator->addJsonPath($path); + }); + } + + /** + * Register database migration paths. + * + * @param array|string $paths + * @return void + */ + protected function loadMigrationsFrom($paths) + { + $this->callAfterResolving('migrator', function ($migrator) use ($paths) { + foreach ((array) $paths as $path) { + $migrator->path($path); + } + }); + } + + /** + * Register Eloquent model factory paths. + * + * @deprecated Will be removed in a future Laravel version. + * + * @param array|string $paths + * @return void + */ + protected function loadFactoriesFrom($paths) + { + $this->callAfterResolving(ModelFactory::class, function ($factory) use ($paths) { + foreach ((array) $paths as $path) { + $factory->load($path); + } + }); + } + + /** + * Setup an after resolving listener, or fire immediately if already resolved. + * + * @param string $name + * @param callable $callback + * @return void + */ + protected function callAfterResolving($name, $callback) + { + $this->app->afterResolving($name, $callback); + + if ($this->app->resolved($name)) { + $callback($this->app->make($name), $this->app); + } + } + + /** + * Register paths to be published by the publish command. + * + * @param array $paths + * @param mixed $groups + * @return void + */ + protected function publishes(array $paths, $groups = null) + { + $this->ensurePublishArrayInitialized($class = static::class); + + static::$publishes[$class] = array_merge(static::$publishes[$class], $paths); + + foreach ((array) $groups as $group) { + $this->addPublishGroup($group, $paths); + } + } + + /** + * Ensure the publish array for the service provider is initialized. + * + * @param string $class + * @return void + */ + protected function ensurePublishArrayInitialized($class) + { + if (! array_key_exists($class, static::$publishes)) { + static::$publishes[$class] = []; + } + } + + /** + * Add a publish group / tag to the service provider. + * + * @param string $group + * @param array $paths + * @return void + */ + protected function addPublishGroup($group, $paths) + { + if (! array_key_exists($group, static::$publishGroups)) { + static::$publishGroups[$group] = []; + } + + static::$publishGroups[$group] = array_merge( + static::$publishGroups[$group], $paths + ); + } + + /** + * Get the paths to publish. + * + * @param string|null $provider + * @param string|null $group + * @return array + */ + public static function pathsToPublish($provider = null, $group = null) + { + if (! is_null($paths = static::pathsForProviderOrGroup($provider, $group))) { + return $paths; + } + + return collect(static::$publishes)->reduce(function ($paths, $p) { + return array_merge($paths, $p); + }, []); + } + + /** + * Get the paths for the provider or group (or both). + * + * @param string|null $provider + * @param string|null $group + * @return array + */ + protected static function pathsForProviderOrGroup($provider, $group) + { + if ($provider && $group) { + return static::pathsForProviderAndGroup($provider, $group); + } elseif ($group && array_key_exists($group, static::$publishGroups)) { + return static::$publishGroups[$group]; + } elseif ($provider && array_key_exists($provider, static::$publishes)) { + return static::$publishes[$provider]; + } elseif ($group || $provider) { + return []; + } + } + + /** + * Get the paths for the provider and group. + * + * @param string $provider + * @param string $group + * @return array + */ + protected static function pathsForProviderAndGroup($provider, $group) + { + if (! empty(static::$publishes[$provider]) && ! empty(static::$publishGroups[$group])) { + return array_intersect_key(static::$publishes[$provider], static::$publishGroups[$group]); + } + + return []; + } + + /** + * Get the service providers available for publishing. + * + * @return array + */ + public static function publishableProviders() + { + return array_keys(static::$publishes); + } + + /** + * Get the groups available for publishing. + * + * @return array + */ + public static function publishableGroups() + { + return array_keys(static::$publishGroups); + } + + /** + * Register the package's custom Artisan commands. + * + * @param array|mixed $commands + * @return void + */ + public function commands($commands) + { + $commands = is_array($commands) ? $commands : func_get_args(); + + Artisan::starting(function ($artisan) use ($commands) { + $artisan->resolveCommands($commands); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return []; + } + + /** + * Get the events that trigger this service provider to register. + * + * @return array + */ + public function when() + { + return []; + } + + /** + * Determine if the provider is deferred. + * + * @return bool + */ + public function isDeferred() + { + return $this instanceof DeferrableProvider; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Str.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Str.php new file mode 100644 index 0000000..21e1904 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Str.php @@ -0,0 +1,1033 @@ + 0; + } + + /** + * Convert a string to kebab case. + * + * @param string $value + * @return string + */ + public static function kebab($value) + { + return static::snake($value, '-'); + } + + /** + * Return the length of the given string. + * + * @param string $value + * @param string|null $encoding + * @return int + */ + public static function length($value, $encoding = null) + { + if ($encoding) { + return mb_strlen($value, $encoding); + } + + return mb_strlen($value); + } + + /** + * Limit the number of characters in a string. + * + * @param string $value + * @param int $limit + * @param string $end + * @return string + */ + public static function limit($value, $limit = 100, $end = '...') + { + if (mb_strwidth($value, 'UTF-8') <= $limit) { + return $value; + } + + return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end; + } + + /** + * Convert the given string to lower-case. + * + * @param string $value + * @return string + */ + public static function lower($value) + { + return mb_strtolower($value, 'UTF-8'); + } + + /** + * Limit the number of words in a string. + * + * @param string $value + * @param int $words + * @param string $end + * @return string + */ + public static function words($value, $words = 100, $end = '...') + { + preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches); + + if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) { + return $value; + } + + return rtrim($matches[0]).$end; + } + + /** + * Converts GitHub flavored Markdown into HTML. + * + * @param string $string + * @param array $options + * @return string + */ + public static function markdown($string, array $options = []) + { + $converter = new GithubFlavoredMarkdownConverter($options); + + return (string) $converter->convertToHtml($string); + } + + /** + * Masks a portion of a string with a repeated character. + * + * @param string $string + * @param string $character + * @param int $index + * @param int|null $length + * @param string $encoding + * @return string + */ + public static function mask($string, $character, $index, $length = null, $encoding = 'UTF-8') + { + if ($character === '') { + return $string; + } + + if (is_null($length) && PHP_MAJOR_VERSION < 8) { + $length = mb_strlen($string, $encoding); + } + + $segment = mb_substr($string, $index, $length, $encoding); + + if ($segment === '') { + return $string; + } + + $strlen = mb_strlen($string, $encoding); + $startIndex = $index; + + if ($index < 0) { + $startIndex = $index < -$strlen ? 0 : $strlen + $index; + } + + $start = mb_substr($string, 0, $startIndex, $encoding); + $segmentLen = mb_strlen($segment, $encoding); + $end = mb_substr($string, $startIndex + $segmentLen); + + return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end; + } + + /** + * Get the string matching the given pattern. + * + * @param string $pattern + * @param string $subject + * @return string + */ + public static function match($pattern, $subject) + { + preg_match($pattern, $subject, $matches); + + if (! $matches) { + return ''; + } + + return $matches[1] ?? $matches[0]; + } + + /** + * Get the string matching the given pattern. + * + * @param string $pattern + * @param string $subject + * @return \Illuminate\Support\Collection + */ + public static function matchAll($pattern, $subject) + { + preg_match_all($pattern, $subject, $matches); + + if (empty($matches[0])) { + return collect(); + } + + return collect($matches[1] ?? $matches[0]); + } + + /** + * Pad both sides of a string with another. + * + * @param string $value + * @param int $length + * @param string $pad + * @return string + */ + public static function padBoth($value, $length, $pad = ' ') + { + return str_pad($value, strlen($value) - mb_strlen($value) + $length, $pad, STR_PAD_BOTH); + } + + /** + * Pad the left side of a string with another. + * + * @param string $value + * @param int $length + * @param string $pad + * @return string + */ + public static function padLeft($value, $length, $pad = ' ') + { + return str_pad($value, strlen($value) - mb_strlen($value) + $length, $pad, STR_PAD_LEFT); + } + + /** + * Pad the right side of a string with another. + * + * @param string $value + * @param int $length + * @param string $pad + * @return string + */ + public static function padRight($value, $length, $pad = ' ') + { + return str_pad($value, strlen($value) - mb_strlen($value) + $length, $pad, STR_PAD_RIGHT); + } + + /** + * Parse a Class[@]method style callback into class and method. + * + * @param string $callback + * @param string|null $default + * @return array + */ + public static function parseCallback($callback, $default = null) + { + return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default]; + } + + /** + * Get the plural form of an English word. + * + * @param string $value + * @param int|array|\Countable $count + * @return string + */ + public static function plural($value, $count = 2) + { + return Pluralizer::plural($value, $count); + } + + /** + * Pluralize the last word of an English, studly caps case string. + * + * @param string $value + * @param int|array|\Countable $count + * @return string + */ + public static function pluralStudly($value, $count = 2) + { + $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE); + + $lastWord = array_pop($parts); + + return implode('', $parts).self::plural($lastWord, $count); + } + + /** + * Generate a more truly "random" alpha-numeric string. + * + * @param int $length + * @return string + */ + public static function random($length = 16) + { + $string = ''; + + while (($len = strlen($string)) < $length) { + $size = $length - $len; + + $bytes = random_bytes($size); + + $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size); + } + + return $string; + } + + /** + * Repeat the given string. + * + * @param string $string + * @param int $times + * @return string + */ + public static function repeat(string $string, int $times) + { + return str_repeat($string, $times); + } + + /** + * Replace a given value in the string sequentially with an array. + * + * @param string $search + * @param array $replace + * @param string $subject + * @return string + */ + public static function replaceArray($search, array $replace, $subject) + { + $segments = explode($search, $subject); + + $result = array_shift($segments); + + foreach ($segments as $segment) { + $result .= (array_shift($replace) ?? $search).$segment; + } + + return $result; + } + + /** + * Replace the given value in the given string. + * + * @param string|string[] $search + * @param string|string[] $replace + * @param string|string[] $subject + * @return string + */ + public static function replace($search, $replace, $subject) + { + return str_replace($search, $replace, $subject); + } + + /** + * Replace the first occurrence of a given value in the string. + * + * @param string $search + * @param string $replace + * @param string $subject + * @return string + */ + public static function replaceFirst($search, $replace, $subject) + { + if ($search === '') { + return $subject; + } + + $position = strpos($subject, $search); + + if ($position !== false) { + return substr_replace($subject, $replace, $position, strlen($search)); + } + + return $subject; + } + + /** + * Replace the last occurrence of a given value in the string. + * + * @param string $search + * @param string $replace + * @param string $subject + * @return string + */ + public static function replaceLast($search, $replace, $subject) + { + if ($search === '') { + return $subject; + } + + $position = strrpos($subject, $search); + + if ($position !== false) { + return substr_replace($subject, $replace, $position, strlen($search)); + } + + return $subject; + } + + /** + * Remove any occurrence of the given string in the subject. + * + * @param string|array $search + * @param string $subject + * @param bool $caseSensitive + * @return string + */ + public static function remove($search, $subject, $caseSensitive = true) + { + $subject = $caseSensitive + ? str_replace($search, '', $subject) + : str_ireplace($search, '', $subject); + + return $subject; + } + + /** + * Reverse the given string. + * + * @param string $value + * @return string + */ + public static function reverse(string $value) + { + return implode(array_reverse(mb_str_split($value))); + } + + /** + * Begin a string with a single instance of a given value. + * + * @param string $value + * @param string $prefix + * @return string + */ + public static function start($value, $prefix) + { + $quoted = preg_quote($prefix, '/'); + + return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value); + } + + /** + * Convert the given string to upper-case. + * + * @param string $value + * @return string + */ + public static function upper($value) + { + return mb_strtoupper($value, 'UTF-8'); + } + + /** + * Convert the given string to title case. + * + * @param string $value + * @return string + */ + public static function title($value) + { + return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8'); + } + + /** + * Convert the given string to title case for each word. + * + * @param string $value + * @return string + */ + public static function headline($value) + { + $parts = explode(' ', $value); + + $parts = count($parts) > 1 + ? $parts = array_map([static::class, 'title'], $parts) + : $parts = array_map([static::class, 'title'], static::ucsplit(implode('_', $parts))); + + $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts)); + + return implode(' ', array_filter(explode('_', $collapsed))); + } + + /** + * Get the singular form of an English word. + * + * @param string $value + * @return string + */ + public static function singular($value) + { + return Pluralizer::singular($value); + } + + /** + * Generate a URL friendly "slug" from a given string. + * + * @param string $title + * @param string $separator + * @param string|null $language + * @return string + */ + public static function slug($title, $separator = '-', $language = 'en') + { + $title = $language ? static::ascii($title, $language) : $title; + + // Convert all dashes/underscores into separator + $flip = $separator === '-' ? '_' : '-'; + + $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title); + + // Replace @ with the word 'at' + $title = str_replace('@', $separator.'at'.$separator, $title); + + // Remove all characters that are not the separator, letters, numbers, or whitespace. + $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title)); + + // Replace all separator characters and whitespace by a single separator + $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); + + return trim($title, $separator); + } + + /** + * Convert a string to snake case. + * + * @param string $value + * @param string $delimiter + * @return string + */ + public static function snake($value, $delimiter = '_') + { + $key = $value; + + if (isset(static::$snakeCache[$key][$delimiter])) { + return static::$snakeCache[$key][$delimiter]; + } + + if (! ctype_lower($value)) { + $value = preg_replace('/\s+/u', '', ucwords($value)); + + $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value)); + } + + return static::$snakeCache[$key][$delimiter] = $value; + } + + /** + * Determine if a given string starts with a given substring. + * + * @param string $haystack + * @param string|string[] $needles + * @return bool + */ + public static function startsWith($haystack, $needles) + { + foreach ((array) $needles as $needle) { + if ((string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0) { + return true; + } + } + + return false; + } + + /** + * Convert a value to studly caps case. + * + * @param string $value + * @return string + */ + public static function studly($value) + { + $key = $value; + + if (isset(static::$studlyCache[$key])) { + return static::$studlyCache[$key]; + } + + $words = explode(' ', static::replace(['-', '_'], ' ', $value)); + + $studlyWords = array_map(function ($word) { + return static::ucfirst($word); + }, $words); + + return static::$studlyCache[$key] = implode($studlyWords); + } + + /** + * Returns the portion of the string specified by the start and length parameters. + * + * @param string $string + * @param int $start + * @param int|null $length + * @return string + */ + public static function substr($string, $start, $length = null) + { + return mb_substr($string, $start, $length, 'UTF-8'); + } + + /** + * Returns the number of substring occurrences. + * + * @param string $haystack + * @param string $needle + * @param int $offset + * @param int|null $length + * @return int + */ + public static function substrCount($haystack, $needle, $offset = 0, $length = null) + { + if (! is_null($length)) { + return substr_count($haystack, $needle, $offset, $length); + } else { + return substr_count($haystack, $needle, $offset); + } + } + + /** + * Replace text within a portion of a string. + * + * @param string|array $string + * @param string|array $replace + * @param array|int $offset + * @param array|int|null $length + * @return string|array + */ + public static function substrReplace($string, $replace, $offset = 0, $length = null) + { + if ($length === null) { + $length = strlen($string); + } + + return substr_replace($string, $replace, $offset, $length); + } + + /** + * Swap multiple keywords in a string with other keywords. + * + * @param array $map + * @param string $subject + * @return string + */ + public static function swap(array $map, $subject) + { + return strtr($subject, $map); + } + + /** + * Make a string's first character uppercase. + * + * @param string $string + * @return string + */ + public static function ucfirst($string) + { + return static::upper(static::substr($string, 0, 1)).static::substr($string, 1); + } + + /** + * Split a string into pieces by uppercase characters. + * + * @param string $string + * @return array + */ + public static function ucsplit($string) + { + return preg_split('/(?=\p{Lu})/u', $string, -1, PREG_SPLIT_NO_EMPTY); + } + + /** + * Get the number of words a string contains. + * + * @param string $string + * @return int + */ + public static function wordCount($string) + { + return str_word_count($string); + } + + /** + * Generate a UUID (version 4). + * + * @return \Ramsey\Uuid\UuidInterface + */ + public static function uuid() + { + return static::$uuidFactory + ? call_user_func(static::$uuidFactory) + : Uuid::uuid4(); + } + + /** + * Generate a time-ordered UUID (version 4). + * + * @return \Ramsey\Uuid\UuidInterface + */ + public static function orderedUuid() + { + if (static::$uuidFactory) { + return call_user_func(static::$uuidFactory); + } + + $factory = new UuidFactory; + + $factory->setRandomGenerator(new CombGenerator( + $factory->getRandomGenerator(), + $factory->getNumberConverter() + )); + + $factory->setCodec(new TimestampFirstCombCodec( + $factory->getUuidBuilder() + )); + + return $factory->uuid4(); + } + + /** + * Set the callable that will be used to generate UUIDs. + * + * @param callable|null $factory + * @return void + */ + public static function createUuidsUsing(callable $factory = null) + { + static::$uuidFactory = $factory; + } + + /** + * Indicate that UUIDs should be created normally and not using a custom factory. + * + * @return void + */ + public static function createUuidsNormally() + { + static::$uuidFactory = null; + } + + /** + * Remove all strings from the casing caches. + * + * @return void + */ + public static function flushCache() + { + static::$snakeCache = []; + static::$camelCache = []; + static::$studlyCache = []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Stringable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Stringable.php new file mode 100644 index 0000000..414be0c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Stringable.php @@ -0,0 +1,1026 @@ +value = (string) $value; + } + + /** + * Return the remainder of a string after the first occurrence of a given value. + * + * @param string $search + * @return static + */ + public function after($search) + { + return new static(Str::after($this->value, $search)); + } + + /** + * Return the remainder of a string after the last occurrence of a given value. + * + * @param string $search + * @return static + */ + public function afterLast($search) + { + return new static(Str::afterLast($this->value, $search)); + } + + /** + * Append the given values to the string. + * + * @param array $values + * @return static + */ + public function append(...$values) + { + return new static($this->value.implode('', $values)); + } + + /** + * Transliterate a UTF-8 value to ASCII. + * + * @param string $language + * @return static + */ + public function ascii($language = 'en') + { + return new static(Str::ascii($this->value, $language)); + } + + /** + * Get the trailing name component of the path. + * + * @param string $suffix + * @return static + */ + public function basename($suffix = '') + { + return new static(basename($this->value, $suffix)); + } + + /** + * Get the basename of the class path. + * + * @return static + */ + public function classBasename() + { + return new static(class_basename($this->value)); + } + + /** + * Get the portion of a string before the first occurrence of a given value. + * + * @param string $search + * @return static + */ + public function before($search) + { + return new static(Str::before($this->value, $search)); + } + + /** + * Get the portion of a string before the last occurrence of a given value. + * + * @param string $search + * @return static + */ + public function beforeLast($search) + { + return new static(Str::beforeLast($this->value, $search)); + } + + /** + * Get the portion of a string between two given values. + * + * @param string $from + * @param string $to + * @return static + */ + public function between($from, $to) + { + return new static(Str::between($this->value, $from, $to)); + } + + /** + * Convert a value to camel case. + * + * @return static + */ + public function camel() + { + return new static(Str::camel($this->value)); + } + + /** + * Determine if a given string contains a given substring. + * + * @param string|array $needles + * @return bool + */ + public function contains($needles) + { + return Str::contains($this->value, $needles); + } + + /** + * Determine if a given string contains all array values. + * + * @param array $needles + * @return bool + */ + public function containsAll(array $needles) + { + return Str::containsAll($this->value, $needles); + } + + /** + * Get the parent directory's path. + * + * @param int $levels + * @return static + */ + public function dirname($levels = 1) + { + return new static(dirname($this->value, $levels)); + } + + /** + * Determine if a given string ends with a given substring. + * + * @param string|array $needles + * @return bool + */ + public function endsWith($needles) + { + return Str::endsWith($this->value, $needles); + } + + /** + * Determine if the string is an exact match with the given value. + * + * @param string $value + * @return bool + */ + public function exactly($value) + { + return $this->value === $value; + } + + /** + * Explode the string into an array. + * + * @param string $delimiter + * @param int $limit + * @return \Illuminate\Support\Collection + */ + public function explode($delimiter, $limit = PHP_INT_MAX) + { + return collect(explode($delimiter, $this->value, $limit)); + } + + /** + * Split a string using a regular expression or by length. + * + * @param string|int $pattern + * @param int $limit + * @param int $flags + * @return \Illuminate\Support\Collection + */ + public function split($pattern, $limit = -1, $flags = 0) + { + if (filter_var($pattern, FILTER_VALIDATE_INT) !== false) { + return collect(mb_str_split($this->value, $pattern)); + } + + $segments = preg_split($pattern, $this->value, $limit, $flags); + + return ! empty($segments) ? collect($segments) : collect(); + } + + /** + * Cap a string with a single instance of a given value. + * + * @param string $cap + * @return static + */ + public function finish($cap) + { + return new static(Str::finish($this->value, $cap)); + } + + /** + * Determine if a given string matches a given pattern. + * + * @param string|array $pattern + * @return bool + */ + public function is($pattern) + { + return Str::is($pattern, $this->value); + } + + /** + * Determine if a given string is 7 bit ASCII. + * + * @return bool + */ + public function isAscii() + { + return Str::isAscii($this->value); + } + + /** + * Determine if a given string is a valid UUID. + * + * @return bool + */ + public function isUuid() + { + return Str::isUuid($this->value); + } + + /** + * Determine if the given string is empty. + * + * @return bool + */ + public function isEmpty() + { + return $this->value === ''; + } + + /** + * Determine if the given string is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return ! $this->isEmpty(); + } + + /** + * Convert a string to kebab case. + * + * @return static + */ + public function kebab() + { + return new static(Str::kebab($this->value)); + } + + /** + * Return the length of the given string. + * + * @param string $encoding + * @return int + */ + public function length($encoding = null) + { + return Str::length($this->value, $encoding); + } + + /** + * Limit the number of characters in a string. + * + * @param int $limit + * @param string $end + * @return static + */ + public function limit($limit = 100, $end = '...') + { + return new static(Str::limit($this->value, $limit, $end)); + } + + /** + * Convert the given string to lower-case. + * + * @return static + */ + public function lower() + { + return new static(Str::lower($this->value)); + } + + /** + * Convert GitHub flavored Markdown into HTML. + * + * @param array $options + * @return static + */ + public function markdown(array $options = []) + { + return new static(Str::markdown($this->value, $options)); + } + + /** + * Masks a portion of a string with a repeated character. + * + * @param string $character + * @param int $index + * @param int|null $length + * @param string $encoding + * @return static + */ + public function mask($character, $index, $length = null, $encoding = 'UTF-8') + { + return new static(Str::mask($this->value, $character, $index, $length, $encoding)); + } + + /** + * Get the string matching the given pattern. + * + * @param string $pattern + * @return static + */ + public function match($pattern) + { + return new static(Str::match($pattern, $this->value)); + } + + /** + * Get the string matching the given pattern. + * + * @param string $pattern + * @return \Illuminate\Support\Collection + */ + public function matchAll($pattern) + { + return Str::matchAll($pattern, $this->value); + } + + /** + * Determine if the string matches the given pattern. + * + * @param string $pattern + * @return bool + */ + public function test($pattern) + { + return $this->match($pattern)->isNotEmpty(); + } + + /** + * Pad both sides of the string with another. + * + * @param int $length + * @param string $pad + * @return static + */ + public function padBoth($length, $pad = ' ') + { + return new static(Str::padBoth($this->value, $length, $pad)); + } + + /** + * Pad the left side of the string with another. + * + * @param int $length + * @param string $pad + * @return static + */ + public function padLeft($length, $pad = ' ') + { + return new static(Str::padLeft($this->value, $length, $pad)); + } + + /** + * Pad the right side of the string with another. + * + * @param int $length + * @param string $pad + * @return static + */ + public function padRight($length, $pad = ' ') + { + return new static(Str::padRight($this->value, $length, $pad)); + } + + /** + * Parse a Class@method style callback into class and method. + * + * @param string|null $default + * @return array + */ + public function parseCallback($default = null) + { + return Str::parseCallback($this->value, $default); + } + + /** + * Call the given callback and return a new string. + * + * @param callable $callback + * @return static + */ + public function pipe(callable $callback) + { + return new static(call_user_func($callback, $this)); + } + + /** + * Get the plural form of an English word. + * + * @param int $count + * @return static + */ + public function plural($count = 2) + { + return new static(Str::plural($this->value, $count)); + } + + /** + * Pluralize the last word of an English, studly caps case string. + * + * @param int $count + * @return static + */ + public function pluralStudly($count = 2) + { + return new static(Str::pluralStudly($this->value, $count)); + } + + /** + * Prepend the given values to the string. + * + * @param array $values + * @return static + */ + public function prepend(...$values) + { + return new static(implode('', $values).$this->value); + } + + /** + * Remove any occurrence of the given string in the subject. + * + * @param string|array $search + * @param bool $caseSensitive + * @return static + */ + public function remove($search, $caseSensitive = true) + { + return new static(Str::remove($search, $this->value, $caseSensitive)); + } + + /** + * Reverse the string. + * + * @return static + */ + public function reverse() + { + return new static(Str::reverse($this->value)); + } + + /** + * Repeat the string. + * + * @param int $times + * @return static + */ + public function repeat(int $times) + { + return new static(Str::repeat($this->value, $times)); + } + + /** + * Replace the given value in the given string. + * + * @param string|string[] $search + * @param string|string[] $replace + * @return static + */ + public function replace($search, $replace) + { + return new static(Str::replace($search, $replace, $this->value)); + } + + /** + * Replace a given value in the string sequentially with an array. + * + * @param string $search + * @param array $replace + * @return static + */ + public function replaceArray($search, array $replace) + { + return new static(Str::replaceArray($search, $replace, $this->value)); + } + + /** + * Replace the first occurrence of a given value in the string. + * + * @param string $search + * @param string $replace + * @return static + */ + public function replaceFirst($search, $replace) + { + return new static(Str::replaceFirst($search, $replace, $this->value)); + } + + /** + * Replace the last occurrence of a given value in the string. + * + * @param string $search + * @param string $replace + * @return static + */ + public function replaceLast($search, $replace) + { + return new static(Str::replaceLast($search, $replace, $this->value)); + } + + /** + * Replace the patterns matching the given regular expression. + * + * @param string $pattern + * @param \Closure|string $replace + * @param int $limit + * @return static + */ + public function replaceMatches($pattern, $replace, $limit = -1) + { + if ($replace instanceof Closure) { + return new static(preg_replace_callback($pattern, $replace, $this->value, $limit)); + } + + return new static(preg_replace($pattern, $replace, $this->value, $limit)); + } + + /** + * Parse input from a string to a collection, according to a format. + * + * @param string $format + * @return \Illuminate\Support\Collection + */ + public function scan($format) + { + return collect(sscanf($this->value, $format)); + } + + /** + * Begin a string with a single instance of a given value. + * + * @param string $prefix + * @return static + */ + public function start($prefix) + { + return new static(Str::start($this->value, $prefix)); + } + + /** + * Strip HTML and PHP tags from the given string. + * + * @param string $allowedTags + * @return static + */ + public function stripTags($allowedTags = null) + { + return new static(strip_tags($this->value, $allowedTags)); + } + + /** + * Convert the given string to upper-case. + * + * @return static + */ + public function upper() + { + return new static(Str::upper($this->value)); + } + + /** + * Convert the given string to title case. + * + * @return static + */ + public function title() + { + return new static(Str::title($this->value)); + } + + /** + * Convert the given string to title case for each word. + * + * @return static + */ + public function headline() + { + return new static(Str::headline($this->value)); + } + + /** + * Get the singular form of an English word. + * + * @return static + */ + public function singular() + { + return new static(Str::singular($this->value)); + } + + /** + * Generate a URL friendly "slug" from a given string. + * + * @param string $separator + * @param string|null $language + * @return static + */ + public function slug($separator = '-', $language = 'en') + { + return new static(Str::slug($this->value, $separator, $language)); + } + + /** + * Convert a string to snake case. + * + * @param string $delimiter + * @return static + */ + public function snake($delimiter = '_') + { + return new static(Str::snake($this->value, $delimiter)); + } + + /** + * Determine if a given string starts with a given substring. + * + * @param string|array $needles + * @return bool + */ + public function startsWith($needles) + { + return Str::startsWith($this->value, $needles); + } + + /** + * Convert a value to studly caps case. + * + * @return static + */ + public function studly() + { + return new static(Str::studly($this->value)); + } + + /** + * Returns the portion of the string specified by the start and length parameters. + * + * @param int $start + * @param int|null $length + * @return static + */ + public function substr($start, $length = null) + { + return new static(Str::substr($this->value, $start, $length)); + } + + /** + * Returns the number of substring occurrences. + * + * @param string $needle + * @param int|null $offset + * @param int|null $length + * @return int + */ + public function substrCount($needle, $offset = null, $length = null) + { + return Str::substrCount($this->value, $needle, $offset ?? 0, $length); + } + + /** + * Replace text within a portion of a string. + * + * @param string|array $replace + * @param array|int $offset + * @param array|int|null $length + * @return static + */ + public function substrReplace($replace, $offset = 0, $length = null) + { + return new static(Str::substrReplace($this->value, $replace, $offset, $length)); + } + + /** + * Swap multiple keywords in a string with other keywords. + * + * @param array $map + * @return static + */ + public function swap(array $map) + { + return new static(strtr($this->value, $map)); + } + + /** + * Trim the string of the given characters. + * + * @param string $characters + * @return static + */ + public function trim($characters = null) + { + return new static(trim(...array_merge([$this->value], func_get_args()))); + } + + /** + * Left trim the string of the given characters. + * + * @param string $characters + * @return static + */ + public function ltrim($characters = null) + { + return new static(ltrim(...array_merge([$this->value], func_get_args()))); + } + + /** + * Right trim the string of the given characters. + * + * @param string $characters + * @return static + */ + public function rtrim($characters = null) + { + return new static(rtrim(...array_merge([$this->value], func_get_args()))); + } + + /** + * Make a string's first character uppercase. + * + * @return static + */ + public function ucfirst() + { + return new static(Str::ucfirst($this->value)); + } + + /** + * Split a string by uppercase characters. + * + * @return \Illuminate\Support\Collection + */ + public function ucsplit() + { + return collect(Str::ucsplit($this->value)); + } + + /** + * Execute the given callback if the string contains a given substring. + * + * @param string|array $needles + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenContains($needles, $callback, $default = null) + { + return $this->when($this->contains($needles), $callback, $default); + } + + /** + * Execute the given callback if the string contains all array values. + * + * @param array $needles + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenContainsAll(array $needles, $callback, $default = null) + { + return $this->when($this->containsAll($needles), $callback, $default); + } + + /** + * Execute the given callback if the string is empty. + * + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenEmpty($callback, $default = null) + { + return $this->when($this->isEmpty(), $callback, $default); + } + + /** + * Execute the given callback if the string is not empty. + * + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenNotEmpty($callback, $default = null) + { + return $this->when($this->isNotEmpty(), $callback, $default); + } + + /** + * Execute the given callback if the string ends with a given substring. + * + * @param string|array $needles + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenEndsWith($needles, $callback, $default = null) + { + return $this->when($this->endsWith($needles), $callback, $default); + } + + /** + * Execute the given callback if the string is an exact match with the given value. + * + * @param string $value + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenExactly($value, $callback, $default = null) + { + return $this->when($this->exactly($value), $callback, $default); + } + + /** + * Execute the given callback if the string matches a given pattern. + * + * @param string|array $pattern + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenIs($pattern, $callback, $default = null) + { + return $this->when($this->is($pattern), $callback, $default); + } + + /** + * Execute the given callback if the string is 7 bit ASCII. + * + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenIsAscii($callback, $default = null) + { + return $this->when($this->isAscii(), $callback, $default); + } + + /** + * Execute the given callback if the string is a valid UUID. + * + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenIsUuid($callback, $default = null) + { + return $this->when($this->isUuid(), $callback, $default); + } + + /** + * Execute the given callback if the string starts with a given substring. + * + * @param string|array $needles + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenStartsWith($needles, $callback, $default = null) + { + return $this->when($this->startsWith($needles), $callback, $default); + } + + /** + * Execute the given callback if the string matches the given pattern. + * + * @param string $pattern + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenTest($pattern, $callback, $default = null) + { + return $this->when($this->test($pattern), $callback, $default); + } + + /** + * Limit the number of words in a string. + * + * @param int $words + * @param string $end + * @return static + */ + public function words($words = 100, $end = '...') + { + return new static(Str::words($this->value, $words, $end)); + } + + /** + * Get the number of words a string contains. + * + * @return int + */ + public function wordCount() + { + return str_word_count($this->value); + } + + /** + * Convert the string into a `HtmlString` instance. + * + * @return \Illuminate\Support\HtmlString + */ + public function toHtmlString() + { + return new HtmlString($this->value); + } + + /** + * Dump the string. + * + * @return $this + */ + public function dump() + { + VarDumper::dump($this->value); + + return $this; + } + + /** + * Dump the string and end the script. + * + * @return never + */ + public function dd() + { + $this->dump(); + + exit(1); + } + + /** + * Convert the object to a string when JSON encoded. + * + * @return string + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->__toString(); + } + + /** + * Proxy dynamic properties onto methods. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->{$key}(); + } + + /** + * Get the raw string value. + * + * @return string + */ + public function __toString() + { + return (string) $this->value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php new file mode 100644 index 0000000..d966133 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php @@ -0,0 +1,142 @@ +name, + count($batch->jobs), + count($batch->jobs), + 0, + [], + $batch->options, + CarbonImmutable::now(), + null, + null + ); + } + + /** + * Increment the total number of jobs within the batch. + * + * @param string $batchId + * @param int $amount + * @return void + */ + public function incrementTotalJobs(string $batchId, int $amount) + { + // + } + + /** + * Decrement the total number of pending jobs for the batch. + * + * @param string $batchId + * @param string $jobId + * @return \Illuminate\Bus\UpdatedBatchJobCounts + */ + public function decrementPendingJobs(string $batchId, string $jobId) + { + return new UpdatedBatchJobCounts; + } + + /** + * Increment the total number of failed jobs for the batch. + * + * @param string $batchId + * @param string $jobId + * @return \Illuminate\Bus\UpdatedBatchJobCounts + */ + public function incrementFailedJobs(string $batchId, string $jobId) + { + return new UpdatedBatchJobCounts; + } + + /** + * Mark the batch that has the given ID as finished. + * + * @param string $batchId + * @return void + */ + public function markAsFinished(string $batchId) + { + // + } + + /** + * Cancel the batch that has the given ID. + * + * @param string $batchId + * @return void + */ + public function cancel(string $batchId) + { + // + } + + /** + * Delete the batch that has the given ID. + * + * @param string $batchId + * @return void + */ + public function delete(string $batchId) + { + // + } + + /** + * Execute the given Closure within a storage specific transaction. + * + * @param \Closure $callback + * @return mixed + */ + public function transaction(Closure $callback) + { + return $callback(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php new file mode 100644 index 0000000..122252d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php @@ -0,0 +1,739 @@ +dispatcher = $dispatcher; + + $this->jobsToFake = Arr::wrap($jobsToFake); + } + + /** + * Assert if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|int|null $callback + * @return void + */ + public function assertDispatched($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + if (is_numeric($callback)) { + return $this->assertDispatchedTimes($command, $callback); + } + + PHPUnit::assertTrue( + $this->dispatched($command, $callback)->count() > 0 || + $this->dispatchedAfterResponse($command, $callback)->count() > 0 || + $this->dispatchedSync($command, $callback)->count() > 0, + "The expected [{$command}] job was not dispatched." + ); + } + + /** + * Assert if a job was pushed a number of times. + * + * @param string $command + * @param int $times + * @return void + */ + public function assertDispatchedTimes($command, $times = 1) + { + $count = $this->dispatched($command)->count() + + $this->dispatchedAfterResponse($command)->count() + + $this->dispatchedSync($command)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$command}] job was pushed {$count} times instead of {$times} times." + ); + } + + /** + * Determine if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + */ + public function assertNotDispatched($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + PHPUnit::assertTrue( + $this->dispatched($command, $callback)->count() === 0 && + $this->dispatchedAfterResponse($command, $callback)->count() === 0 && + $this->dispatchedSync($command, $callback)->count() === 0, + "The unexpected [{$command}] job was dispatched." + ); + } + + /** + * Assert that no jobs were dispatched. + * + * @return void + */ + public function assertNothingDispatched() + { + PHPUnit::assertEmpty($this->commands, 'Jobs were dispatched unexpectedly.'); + } + + /** + * Assert if a job was explicitly dispatched synchronously based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|int|null $callback + * @return void + */ + public function assertDispatchedSync($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + if (is_numeric($callback)) { + return $this->assertDispatchedSyncTimes($command, $callback); + } + + PHPUnit::assertTrue( + $this->dispatchedSync($command, $callback)->count() > 0, + "The expected [{$command}] job was not dispatched synchronously." + ); + } + + /** + * Assert if a job was pushed synchronously a number of times. + * + * @param string $command + * @param int $times + * @return void + */ + public function assertDispatchedSyncTimes($command, $times = 1) + { + $count = $this->dispatchedSync($command)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$command}] job was synchronously pushed {$count} times instead of {$times} times." + ); + } + + /** + * Determine if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + */ + public function assertNotDispatchedSync($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + PHPUnit::assertCount( + 0, $this->dispatchedSync($command, $callback), + "The unexpected [{$command}] job was dispatched synchronously." + ); + } + + /** + * Assert if a job was dispatched after the response was sent based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|int|null $callback + * @return void + */ + public function assertDispatchedAfterResponse($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + if (is_numeric($callback)) { + return $this->assertDispatchedAfterResponseTimes($command, $callback); + } + + PHPUnit::assertTrue( + $this->dispatchedAfterResponse($command, $callback)->count() > 0, + "The expected [{$command}] job was not dispatched after sending the response." + ); + } + + /** + * Assert if a job was pushed after the response was sent a number of times. + * + * @param string $command + * @param int $times + * @return void + */ + public function assertDispatchedAfterResponseTimes($command, $times = 1) + { + $count = $this->dispatchedAfterResponse($command)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$command}] job was pushed {$count} times instead of {$times} times." + ); + } + + /** + * Determine if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + */ + public function assertNotDispatchedAfterResponse($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + PHPUnit::assertCount( + 0, $this->dispatchedAfterResponse($command, $callback), + "The unexpected [{$command}] job was dispatched after sending the response." + ); + } + + /** + * Assert if a chain of jobs was dispatched. + * + * @param array $expectedChain + * @return void + */ + public function assertChained(array $expectedChain) + { + $command = $expectedChain[0]; + + $expectedChain = array_slice($expectedChain, 1); + + $callback = null; + + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } elseif (! is_string($command)) { + $instance = $command; + + $command = get_class($instance); + + $callback = function ($job) use ($instance) { + return serialize($this->resetChainPropertiesToDefaults($job)) === serialize($instance); + }; + } + + PHPUnit::assertTrue( + $this->dispatched($command, $callback)->isNotEmpty(), + "The expected [{$command}] job was not dispatched." + ); + + PHPUnit::assertTrue( + collect($expectedChain)->isNotEmpty(), + 'The expected chain can not be empty.' + ); + + $this->isChainOfObjects($expectedChain) + ? $this->assertDispatchedWithChainOfObjects($command, $expectedChain, $callback) + : $this->assertDispatchedWithChainOfClasses($command, $expectedChain, $callback); + } + + /** + * Reset the chain properties to their default values on the job. + * + * @param mixed $job + * @return mixed + */ + protected function resetChainPropertiesToDefaults($job) + { + return tap(clone $job, function ($job) { + $job->chainConnection = null; + $job->chainQueue = null; + $job->chainCatchCallbacks = null; + $job->chained = []; + }); + } + + /** + * Assert if a job was dispatched with an empty chain based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + */ + public function assertDispatchedWithoutChain($command, $callback = null) + { + if ($command instanceof Closure) { + [$command, $callback] = [$this->firstClosureParameterType($command), $command]; + } + + PHPUnit::assertTrue( + $this->dispatched($command, $callback)->isNotEmpty(), + "The expected [{$command}] job was not dispatched." + ); + + $this->assertDispatchedWithChainOfClasses($command, [], $callback); + } + + /** + * Assert if a job was dispatched with chained jobs based on a truth-test callback. + * + * @param string $command + * @param array $expectedChain + * @param callable|null $callback + * @return void + */ + protected function assertDispatchedWithChainOfObjects($command, $expectedChain, $callback) + { + $chain = collect($expectedChain)->map(function ($job) { + return serialize($job); + })->all(); + + PHPUnit::assertTrue( + $this->dispatched($command, $callback)->filter(function ($job) use ($chain) { + return $job->chained == $chain; + })->isNotEmpty(), + 'The expected chain was not dispatched.' + ); + } + + /** + * Assert if a job was dispatched with chained jobs based on a truth-test callback. + * + * @param string $command + * @param array $expectedChain + * @param callable|null $callback + * @return void + */ + protected function assertDispatchedWithChainOfClasses($command, $expectedChain, $callback) + { + $matching = $this->dispatched($command, $callback)->map->chained->map(function ($chain) { + return collect($chain)->map(function ($job) { + return get_class(unserialize($job)); + }); + })->filter(function ($chain) use ($expectedChain) { + return $chain->all() === $expectedChain; + }); + + PHPUnit::assertTrue( + $matching->isNotEmpty(), 'The expected chain was not dispatched.' + ); + } + + /** + * Determine if the given chain is entirely composed of objects. + * + * @param array $chain + * @return bool + */ + protected function isChainOfObjects($chain) + { + return ! collect($chain)->contains(function ($job) { + return ! is_object($job); + }); + } + + /** + * Assert if a batch was dispatched based on a truth-test callback. + * + * @param callable $callback + * @return void + */ + public function assertBatched(callable $callback) + { + PHPUnit::assertTrue( + $this->batched($callback)->count() > 0, + 'The expected batch was not dispatched.' + ); + } + + /** + * Assert the number of batches that have been dispatched. + * + * @param int $count + * @return void + */ + public function assertBatchCount($count) + { + PHPUnit::assertCount( + $count, $this->batches, + ); + } + + /** + * Get all of the jobs matching a truth-test callback. + * + * @param string $command + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function dispatched($command, $callback = null) + { + if (! $this->hasDispatched($command)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return collect($this->commands[$command])->filter(function ($command) use ($callback) { + return $callback($command); + }); + } + + /** + * Get all of the jobs dispatched synchronously matching a truth-test callback. + * + * @param string $command + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function dispatchedSync(string $command, $callback = null) + { + if (! $this->hasDispatchedSync($command)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return collect($this->commandsSync[$command])->filter(function ($command) use ($callback) { + return $callback($command); + }); + } + + /** + * Get all of the jobs dispatched after the response was sent matching a truth-test callback. + * + * @param string $command + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function dispatchedAfterResponse(string $command, $callback = null) + { + if (! $this->hasDispatchedAfterResponse($command)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return collect($this->commandsAfterResponse[$command])->filter(function ($command) use ($callback) { + return $callback($command); + }); + } + + /** + * Get all of the pending batches matching a truth-test callback. + * + * @param callable $callback + * @return \Illuminate\Support\Collection + */ + public function batched(callable $callback) + { + if (empty($this->batches)) { + return collect(); + } + + return collect($this->batches)->filter(function ($batch) use ($callback) { + return $callback($batch); + }); + } + + /** + * Determine if there are any stored commands for a given class. + * + * @param string $command + * @return bool + */ + public function hasDispatched($command) + { + return isset($this->commands[$command]) && ! empty($this->commands[$command]); + } + + /** + * Determine if there are any stored commands for a given class. + * + * @param string $command + * @return bool + */ + public function hasDispatchedSync($command) + { + return isset($this->commandsSync[$command]) && ! empty($this->commandsSync[$command]); + } + + /** + * Determine if there are any stored commands for a given class. + * + * @param string $command + * @return bool + */ + public function hasDispatchedAfterResponse($command) + { + return isset($this->commandsAfterResponse[$command]) && ! empty($this->commandsAfterResponse[$command]); + } + + /** + * Dispatch a command to its appropriate handler. + * + * @param mixed $command + * @return mixed + */ + public function dispatch($command) + { + if ($this->shouldFakeJob($command)) { + $this->commands[get_class($command)][] = $command; + } else { + return $this->dispatcher->dispatch($command); + } + } + + /** + * Dispatch a command to its appropriate handler in the current process. + * + * Queueable jobs will be dispatched to the "sync" queue. + * + * @param mixed $command + * @param mixed $handler + * @return mixed + */ + public function dispatchSync($command, $handler = null) + { + if ($this->shouldFakeJob($command)) { + $this->commandsSync[get_class($command)][] = $command; + } else { + return $this->dispatcher->dispatchSync($command, $handler); + } + } + + /** + * Dispatch a command to its appropriate handler in the current process. + * + * @param mixed $command + * @param mixed $handler + * @return mixed + */ + public function dispatchNow($command, $handler = null) + { + if ($this->shouldFakeJob($command)) { + $this->commands[get_class($command)][] = $command; + } else { + return $this->dispatcher->dispatchNow($command, $handler); + } + } + + /** + * Dispatch a command to its appropriate handler behind a queue. + * + * @param mixed $command + * @return mixed + */ + public function dispatchToQueue($command) + { + if ($this->shouldFakeJob($command)) { + $this->commands[get_class($command)][] = $command; + } else { + return $this->dispatcher->dispatchToQueue($command); + } + } + + /** + * Dispatch a command to its appropriate handler. + * + * @param mixed $command + * @return mixed + */ + public function dispatchAfterResponse($command) + { + if ($this->shouldFakeJob($command)) { + $this->commandsAfterResponse[get_class($command)][] = $command; + } else { + return $this->dispatcher->dispatch($command); + } + } + + /** + * Create a new chain of queueable jobs. + * + * @param \Illuminate\Support\Collection|array $jobs + * @return \Illuminate\Foundation\Bus\PendingChain + */ + public function chain($jobs) + { + $jobs = Collection::wrap($jobs); + + return new PendingChainFake($this, $jobs->shift(), $jobs->toArray()); + } + + /** + * Attempt to find the batch with the given ID. + * + * @param string $batchId + * @return \Illuminate\Bus\Batch|null + */ + public function findBatch(string $batchId) + { + // + } + + /** + * Create a new batch of queueable jobs. + * + * @param \Illuminate\Support\Collection|array $jobs + * @return \Illuminate\Bus\PendingBatch + */ + public function batch($jobs) + { + return new PendingBatchFake($this, Collection::wrap($jobs)); + } + + /** + * Record the fake pending batch dispatch. + * + * @param \Illuminate\Bus\PendingBatch $pendingBatch + * @return \Illuminate\Bus\Batch + */ + public function recordPendingBatch(PendingBatch $pendingBatch) + { + $this->batches[] = $pendingBatch; + + return (new BatchRepositoryFake)->store($pendingBatch); + } + + /** + * Determine if a command should be faked or actually dispatched. + * + * @param mixed $command + * @return bool + */ + protected function shouldFakeJob($command) + { + if (empty($this->jobsToFake)) { + return true; + } + + return collect($this->jobsToFake) + ->filter(function ($job) use ($command) { + return $job instanceof Closure + ? $job($command) + : $job === get_class($command); + })->isNotEmpty(); + } + + /** + * Set the pipes commands should be piped through before dispatching. + * + * @param array $pipes + * @return $this + */ + public function pipeThrough(array $pipes) + { + $this->dispatcher->pipeThrough($pipes); + + return $this; + } + + /** + * Determine if the given command has a handler. + * + * @param mixed $command + * @return bool + */ + public function hasCommandHandler($command) + { + return $this->dispatcher->hasCommandHandler($command); + } + + /** + * Retrieve the handler for a command. + * + * @param mixed $command + * @return mixed + */ + public function getCommandHandler($command) + { + return $this->dispatcher->getCommandHandler($command); + } + + /** + * Map a command to a handler. + * + * @param array $map + * @return $this + */ + public function map(array $map) + { + $this->dispatcher->map($map); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/EventFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/EventFake.php new file mode 100644 index 0000000..436173e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/EventFake.php @@ -0,0 +1,325 @@ +dispatcher = $dispatcher; + + $this->eventsToFake = Arr::wrap($eventsToFake); + } + + /** + * Assert if an event has a listener attached to it. + * + * @param string $expectedEvent + * @param string $expectedListener + * @return void + */ + public function assertListening($expectedEvent, $expectedListener) + { + foreach ($this->dispatcher->getListeners($expectedEvent) as $listenerClosure) { + $actualListener = (new ReflectionFunction($listenerClosure)) + ->getStaticVariables()['listener']; + + if (is_string($actualListener) && Str::endsWith($actualListener, '@handle')) { + $actualListener = Str::parseCallback($actualListener)[0]; + } + + if ($actualListener === $expectedListener || + ($actualListener instanceof Closure && + $expectedListener === Closure::class)) { + PHPUnit::assertTrue(true); + + return; + } + } + + PHPUnit::assertTrue( + false, + sprintf( + 'Event [%s] does not have the [%s] listener attached to it', + $expectedEvent, + print_r($expectedListener, true) + ) + ); + } + + /** + * Assert if an event was dispatched based on a truth-test callback. + * + * @param string|\Closure $event + * @param callable|int|null $callback + * @return void + */ + public function assertDispatched($event, $callback = null) + { + if ($event instanceof Closure) { + [$event, $callback] = [$this->firstClosureParameterType($event), $event]; + } + + if (is_int($callback)) { + return $this->assertDispatchedTimes($event, $callback); + } + + PHPUnit::assertTrue( + $this->dispatched($event, $callback)->count() > 0, + "The expected [{$event}] event was not dispatched." + ); + } + + /** + * Assert if an event was dispatched a number of times. + * + * @param string $event + * @param int $times + * @return void + */ + public function assertDispatchedTimes($event, $times = 1) + { + $count = $this->dispatched($event)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$event}] event was dispatched {$count} times instead of {$times} times." + ); + } + + /** + * Determine if an event was dispatched based on a truth-test callback. + * + * @param string|\Closure $event + * @param callable|null $callback + * @return void + */ + public function assertNotDispatched($event, $callback = null) + { + if ($event instanceof Closure) { + [$event, $callback] = [$this->firstClosureParameterType($event), $event]; + } + + PHPUnit::assertCount( + 0, $this->dispatched($event, $callback), + "The unexpected [{$event}] event was dispatched." + ); + } + + /** + * Assert that no events were dispatched. + * + * @return void + */ + public function assertNothingDispatched() + { + $count = count(Arr::flatten($this->events)); + + PHPUnit::assertSame( + 0, $count, + "{$count} unexpected events were dispatched." + ); + } + + /** + * Get all of the events matching a truth-test callback. + * + * @param string $event + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function dispatched($event, $callback = null) + { + if (! $this->hasDispatched($event)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return collect($this->events[$event])->filter(function ($arguments) use ($callback) { + return $callback(...$arguments); + }); + } + + /** + * Determine if the given event has been dispatched. + * + * @param string $event + * @return bool + */ + public function hasDispatched($event) + { + return isset($this->events[$event]) && ! empty($this->events[$event]); + } + + /** + * Register an event listener with the dispatcher. + * + * @param \Closure|string|array $events + * @param mixed $listener + * @return void + */ + public function listen($events, $listener = null) + { + $this->dispatcher->listen($events, $listener); + } + + /** + * Determine if a given event has listeners. + * + * @param string $eventName + * @return bool + */ + public function hasListeners($eventName) + { + return $this->dispatcher->hasListeners($eventName); + } + + /** + * Register an event and payload to be dispatched later. + * + * @param string $event + * @param array $payload + * @return void + */ + public function push($event, $payload = []) + { + // + } + + /** + * Register an event subscriber with the dispatcher. + * + * @param object|string $subscriber + * @return void + */ + public function subscribe($subscriber) + { + $this->dispatcher->subscribe($subscriber); + } + + /** + * Flush a set of pushed events. + * + * @param string $event + * @return void + */ + public function flush($event) + { + // + } + + /** + * Fire an event and call the listeners. + * + * @param string|object $event + * @param mixed $payload + * @param bool $halt + * @return array|null + */ + public function dispatch($event, $payload = [], $halt = false) + { + $name = is_object($event) ? get_class($event) : (string) $event; + + if ($this->shouldFakeEvent($name, $payload)) { + $this->events[$name][] = func_get_args(); + } else { + return $this->dispatcher->dispatch($event, $payload, $halt); + } + } + + /** + * Determine if an event should be faked or actually dispatched. + * + * @param string $eventName + * @param mixed $payload + * @return bool + */ + protected function shouldFakeEvent($eventName, $payload) + { + if (empty($this->eventsToFake)) { + return true; + } + + return collect($this->eventsToFake) + ->filter(function ($event) use ($eventName, $payload) { + return $event instanceof Closure + ? $event($eventName, $payload) + : $event === $eventName; + }) + ->isNotEmpty(); + } + + /** + * Remove a set of listeners from the dispatcher. + * + * @param string $event + * @return void + */ + public function forget($event) + { + // + } + + /** + * Forget all of the queued listeners. + * + * @return void + */ + public function forgetPushed() + { + // + } + + /** + * Dispatch an event and call the listeners. + * + * @param string|object $event + * @param mixed $payload + * @return array|null + */ + public function until($event, $payload = []) + { + return $this->dispatch($event, $payload, true); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php new file mode 100644 index 0000000..fff5f8f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/MailFake.php @@ -0,0 +1,445 @@ +prepareMailableAndCallback($mailable, $callback); + + if (is_numeric($callback)) { + return $this->assertSentTimes($mailable, $callback); + } + + $message = "The expected [{$mailable}] mailable was not sent."; + + if (count($this->queuedMailables) > 0) { + $message .= ' Did you mean to use assertQueued() instead?'; + } + + PHPUnit::assertTrue( + $this->sent($mailable, $callback)->count() > 0, + $message + ); + } + + /** + * Assert if a mailable was sent a number of times. + * + * @param string $mailable + * @param int $times + * @return void + */ + protected function assertSentTimes($mailable, $times = 1) + { + $count = $this->sent($mailable)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$mailable}] mailable was sent {$count} times instead of {$times} times." + ); + } + + /** + * Determine if a mailable was not sent or queued to be sent based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return void + */ + public function assertNotOutgoing($mailable, $callback = null) + { + $this->assertNotSent($mailable, $callback); + $this->assertNotQueued($mailable, $callback); + } + + /** + * Determine if a mailable was not sent based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return void + */ + public function assertNotSent($mailable, $callback = null) + { + [$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback); + + PHPUnit::assertCount( + 0, $this->sent($mailable, $callback), + "The unexpected [{$mailable}] mailable was sent." + ); + } + + /** + * Assert that no mailables were sent or queued to be sent. + * + * @return void + */ + public function assertNothingOutgoing() + { + $this->assertNothingSent(); + $this->assertNothingQueued(); + } + + /** + * Assert that no mailables were sent. + * + * @return void + */ + public function assertNothingSent() + { + $mailableNames = collect($this->mailables)->map(function ($mailable) { + return get_class($mailable); + })->join(', '); + + PHPUnit::assertEmpty($this->mailables, 'The following mailables were sent unexpectedly: '.$mailableNames); + } + + /** + * Assert if a mailable was queued based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|int|null $callback + * @return void + */ + public function assertQueued($mailable, $callback = null) + { + [$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback); + + if (is_numeric($callback)) { + return $this->assertQueuedTimes($mailable, $callback); + } + + PHPUnit::assertTrue( + $this->queued($mailable, $callback)->count() > 0, + "The expected [{$mailable}] mailable was not queued." + ); + } + + /** + * Assert if a mailable was queued a number of times. + * + * @param string $mailable + * @param int $times + * @return void + */ + protected function assertQueuedTimes($mailable, $times = 1) + { + $count = $this->queued($mailable)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$mailable}] mailable was queued {$count} times instead of {$times} times." + ); + } + + /** + * Determine if a mailable was not queued based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return void + */ + public function assertNotQueued($mailable, $callback = null) + { + [$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback); + + PHPUnit::assertCount( + 0, $this->queued($mailable, $callback), + "The unexpected [{$mailable}] mailable was queued." + ); + } + + /** + * Assert that no mailables were queued. + * + * @return void + */ + public function assertNothingQueued() + { + $mailableNames = collect($this->queuedMailables)->map(function ($mailable) { + return get_class($mailable); + })->join(', '); + + PHPUnit::assertEmpty($this->queuedMailables, 'The following mailables were queued unexpectedly: '.$mailableNames); + } + + /** + * Get all of the mailables matching a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function sent($mailable, $callback = null) + { + [$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback); + + if (! $this->hasSent($mailable)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return $this->mailablesOf($mailable)->filter(function ($mailable) use ($callback) { + return $callback($mailable); + }); + } + + /** + * Determine if the given mailable has been sent. + * + * @param string $mailable + * @return bool + */ + public function hasSent($mailable) + { + return $this->mailablesOf($mailable)->count() > 0; + } + + /** + * Get all of the queued mailables matching a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function queued($mailable, $callback = null) + { + [$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback); + + if (! $this->hasQueued($mailable)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return $this->queuedMailablesOf($mailable)->filter(function ($mailable) use ($callback) { + return $callback($mailable); + }); + } + + /** + * Determine if the given mailable has been queued. + * + * @param string $mailable + * @return bool + */ + public function hasQueued($mailable) + { + return $this->queuedMailablesOf($mailable)->count() > 0; + } + + /** + * Get all of the mailed mailables for a given type. + * + * @param string $type + * @return \Illuminate\Support\Collection + */ + protected function mailablesOf($type) + { + return collect($this->mailables)->filter(function ($mailable) use ($type) { + return $mailable instanceof $type; + }); + } + + /** + * Get all of the mailed mailables for a given type. + * + * @param string $type + * @return \Illuminate\Support\Collection + */ + protected function queuedMailablesOf($type) + { + return collect($this->queuedMailables)->filter(function ($mailable) use ($type) { + return $mailable instanceof $type; + }); + } + + /** + * Get a mailer instance by name. + * + * @param string|null $name + * @return \Illuminate\Contracts\Mail\Mailer + */ + public function mailer($name = null) + { + $this->currentMailer = $name; + + return $this; + } + + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + */ + public function to($users) + { + return (new PendingMailFake($this))->to($users); + } + + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + */ + public function bcc($users) + { + return (new PendingMailFake($this))->bcc($users); + } + + /** + * Send a new message with only a raw text part. + * + * @param string $text + * @param \Closure|string $callback + * @return void + */ + public function raw($text, $callback) + { + // + } + + /** + * Send a new message using a view. + * + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param array $data + * @param \Closure|string|null $callback + * @return void + */ + public function send($view, array $data = [], $callback = null) + { + if (! $view instanceof Mailable) { + return; + } + + $view->mailer($this->currentMailer); + + if ($view instanceof ShouldQueue) { + return $this->queue($view, $data); + } + + $this->currentMailer = null; + + $this->mailables[] = $view; + } + + /** + * Queue a new e-mail message for sending. + * + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param string|null $queue + * @return mixed + */ + public function queue($view, $queue = null) + { + if (! $view instanceof Mailable) { + return; + } + + $view->mailer($this->currentMailer); + + $this->currentMailer = null; + + $this->queuedMailables[] = $view; + } + + /** + * Queue a new e-mail message for sending after (n) seconds. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param string|null $queue + * @return mixed + */ + public function later($delay, $view, $queue = null) + { + $this->queue($view, $queue); + } + + /** + * Get the array of failed recipients. + * + * @return array + */ + public function failures() + { + return []; + } + + /** + * Infer mailable class using reflection if a typehinted closure is passed to assertion. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return array + */ + protected function prepareMailableAndCallback($mailable, $callback) + { + if ($mailable instanceof Closure) { + return [$this->firstClosureParameterType($mailable), $mailable]; + } + + return [$mailable, $callback]; + } + + /** + * Forget all of the resolved mailer instances. + * + * @return $this + */ + public function forgetMailers() + { + $this->currentMailer = null; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php new file mode 100644 index 0000000..c7b12f4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php @@ -0,0 +1,327 @@ +assertSentTo(new AnonymousNotifiable, $notification, $callback); + } + + /** + * Assert if a notification was sent based on a truth-test callback. + * + * @param mixed $notifiable + * @param string|\Closure $notification + * @param callable|null $callback + * @return void + * + * @throws \Exception + */ + public function assertSentTo($notifiable, $notification, $callback = null) + { + if (is_array($notifiable) || $notifiable instanceof Collection) { + if (count($notifiable) === 0) { + throw new Exception('No notifiable given.'); + } + + foreach ($notifiable as $singleNotifiable) { + $this->assertSentTo($singleNotifiable, $notification, $callback); + } + + return; + } + + if ($notification instanceof Closure) { + [$notification, $callback] = [$this->firstClosureParameterType($notification), $notification]; + } + + if (is_numeric($callback)) { + return $this->assertSentToTimes($notifiable, $notification, $callback); + } + + PHPUnit::assertTrue( + $this->sent($notifiable, $notification, $callback)->count() > 0, + "The expected [{$notification}] notification was not sent." + ); + } + + /** + * Assert if a notification was sent on-demand a number of times. + * + * @param string $notification + * @param int $times + * @return void + */ + public function assertSentOnDemandTimes($notification, $times = 1) + { + return $this->assertSentToTimes(new AnonymousNotifiable, $notification, $times); + } + + /** + * Assert if a notification was sent a number of times. + * + * @param mixed $notifiable + * @param string $notification + * @param int $times + * @return void + */ + public function assertSentToTimes($notifiable, $notification, $times = 1) + { + $count = $this->sent($notifiable, $notification)->count(); + + PHPUnit::assertSame( + $times, $count, + "Expected [{$notification}] to be sent {$times} times, but was sent {$count} times." + ); + } + + /** + * Determine if a notification was sent based on a truth-test callback. + * + * @param mixed $notifiable + * @param string|\Closure $notification + * @param callable|null $callback + * @return void + * + * @throws \Exception + */ + public function assertNotSentTo($notifiable, $notification, $callback = null) + { + if (is_array($notifiable) || $notifiable instanceof Collection) { + if (count($notifiable) === 0) { + throw new Exception('No notifiable given.'); + } + + foreach ($notifiable as $singleNotifiable) { + $this->assertNotSentTo($singleNotifiable, $notification, $callback); + } + + return; + } + + if ($notification instanceof Closure) { + [$notification, $callback] = [$this->firstClosureParameterType($notification), $notification]; + } + + PHPUnit::assertCount( + 0, $this->sent($notifiable, $notification, $callback), + "The unexpected [{$notification}] notification was sent." + ); + } + + /** + * Assert that no notifications were sent. + * + * @return void + */ + public function assertNothingSent() + { + PHPUnit::assertEmpty($this->notifications, 'Notifications were sent unexpectedly.'); + } + + /** + * Assert the total amount of times a notification was sent. + * + * @param string $notification + * @param int $expectedCount + * @return void + */ + public function assertSentTimes($notification, $expectedCount) + { + $actualCount = collect($this->notifications) + ->flatten(1) + ->reduce(function ($count, $sent) use ($notification) { + return $count + count($sent[$notification] ?? []); + }, 0); + + PHPUnit::assertSame( + $expectedCount, $actualCount, + "Expected [{$notification}] to be sent {$expectedCount} times, but was sent {$actualCount} times." + ); + } + + /** + * Assert the total amount of times a notification was sent. + * + * @param int $expectedCount + * @param string $notification + * @return void + * + * @deprecated Use the assertSentTimes method instead + */ + public function assertTimesSent($expectedCount, $notification) + { + $this->assertSentTimes($notification, $expectedCount); + } + + /** + * Get all of the notifications matching a truth-test callback. + * + * @param mixed $notifiable + * @param string $notification + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function sent($notifiable, $notification, $callback = null) + { + if (! $this->hasSent($notifiable, $notification)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + $notifications = collect($this->notificationsFor($notifiable, $notification)); + + return $notifications->filter(function ($arguments) use ($callback) { + return $callback(...array_values($arguments)); + })->pluck('notification'); + } + + /** + * Determine if there are more notifications left to inspect. + * + * @param mixed $notifiable + * @param string $notification + * @return bool + */ + public function hasSent($notifiable, $notification) + { + return ! empty($this->notificationsFor($notifiable, $notification)); + } + + /** + * Get all of the notifications for a notifiable entity by type. + * + * @param mixed $notifiable + * @param string $notification + * @return array + */ + protected function notificationsFor($notifiable, $notification) + { + return $this->notifications[get_class($notifiable)][$notifiable->getKey()][$notification] ?? []; + } + + /** + * Send the given notification to the given notifiable entities. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @return void + */ + public function send($notifiables, $notification) + { + $this->sendNow($notifiables, $notification); + } + + /** + * Send the given notification immediately. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @param array|null $channels + * @return void + */ + public function sendNow($notifiables, $notification, array $channels = null) + { + if (! $notifiables instanceof Collection && ! is_array($notifiables)) { + $notifiables = [$notifiables]; + } + + foreach ($notifiables as $notifiable) { + if (! $notification->id) { + $notification->id = Str::uuid()->toString(); + } + + $notifiableChannels = $channels ?: $notification->via($notifiable); + + if (method_exists($notification, 'shouldSend')) { + $notifiableChannels = array_filter( + $notifiableChannels, + function ($channel) use ($notification, $notifiable) { + return $notification->shouldSend($notifiable, $channel) !== false; + } + ); + + if (empty($notifiableChannels)) { + continue; + } + } + + $this->notifications[get_class($notifiable)][$notifiable->getKey()][get_class($notification)][] = [ + 'notification' => $notification, + 'channels' => $notifiableChannels, + 'notifiable' => $notifiable, + 'locale' => $notification->locale ?? $this->locale ?? value(function () use ($notifiable) { + if ($notifiable instanceof HasLocalePreference) { + return $notifiable->preferredLocale(); + } + }), + ]; + } + } + + /** + * Get a channel instance by name. + * + * @param string|null $name + * @return mixed + */ + public function channel($name = null) + { + // + } + + /** + * Set the locale of notifications. + * + * @param string $locale + * @return $this + */ + public function locale($locale) + { + $this->locale = $locale; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingBatchFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingBatchFake.php new file mode 100644 index 0000000..c60b4b5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingBatchFake.php @@ -0,0 +1,39 @@ +bus = $bus; + $this->jobs = $jobs; + } + + /** + * Dispatch the batch. + * + * @return \Illuminate\Bus\Batch + */ + public function dispatch() + { + return $this->bus->recordPendingBatch($this); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingChainFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingChainFake.php new file mode 100644 index 0000000..533c649 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingChainFake.php @@ -0,0 +1,56 @@ +bus = $bus; + $this->job = $job; + $this->chain = $chain; + } + + /** + * Dispatch the job with the given arguments. + * + * @return \Illuminate\Foundation\Bus\PendingDispatch + */ + public function dispatch() + { + if (is_string($this->job)) { + $firstJob = new $this->job(...func_get_args()); + } elseif ($this->job instanceof Closure) { + $firstJob = CallQueuedClosure::create($this->job); + } else { + $firstJob = $this->job; + } + + $firstJob->allOnConnection($this->connection); + $firstJob->allOnQueue($this->queue); + $firstJob->chain($this->chain); + $firstJob->delay($this->delay); + $firstJob->chainCatchCallbacks = $this->catchCallbacks(); + + return $this->bus->dispatch($firstJob); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingMailFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingMailFake.php new file mode 100644 index 0000000..5225130 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/PendingMailFake.php @@ -0,0 +1,42 @@ +mailer = $mailer; + } + + /** + * Send a new mailable message instance. + * + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return void + */ + public function send(Mailable $mailable) + { + $this->mailer->send($this->fill($mailable)); + } + + /** + * Push the given mailable onto the queue. + * + * @param \Illuminate\Contracts\Mail\Mailable $mailable + * @return mixed + */ + public function queue(Mailable $mailable) + { + return $this->mailer->queue($this->fill($mailable)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/QueueFake.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/QueueFake.php new file mode 100644 index 0000000..d37cd67 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/QueueFake.php @@ -0,0 +1,414 @@ +firstClosureParameterType($job), $job]; + } + + if (is_numeric($callback)) { + return $this->assertPushedTimes($job, $callback); + } + + PHPUnit::assertTrue( + $this->pushed($job, $callback)->count() > 0, + "The expected [{$job}] job was not pushed." + ); + } + + /** + * Assert if a job was pushed a number of times. + * + * @param string $job + * @param int $times + * @return void + */ + protected function assertPushedTimes($job, $times = 1) + { + $count = $this->pushed($job)->count(); + + PHPUnit::assertSame( + $times, $count, + "The expected [{$job}] job was pushed {$count} times instead of {$times} times." + ); + } + + /** + * Assert if a job was pushed based on a truth-test callback. + * + * @param string $queue + * @param string|\Closure $job + * @param callable|null $callback + * @return void + */ + public function assertPushedOn($queue, $job, $callback = null) + { + if ($job instanceof Closure) { + [$job, $callback] = [$this->firstClosureParameterType($job), $job]; + } + + $this->assertPushed($job, function ($job, $pushedQueue) use ($callback, $queue) { + if ($pushedQueue !== $queue) { + return false; + } + + return $callback ? $callback(...func_get_args()) : true; + }); + } + + /** + * Assert if a job was pushed with chained jobs based on a truth-test callback. + * + * @param string $job + * @param array $expectedChain + * @param callable|null $callback + * @return void + */ + public function assertPushedWithChain($job, $expectedChain = [], $callback = null) + { + PHPUnit::assertTrue( + $this->pushed($job, $callback)->isNotEmpty(), + "The expected [{$job}] job was not pushed." + ); + + PHPUnit::assertTrue( + collect($expectedChain)->isNotEmpty(), + 'The expected chain can not be empty.' + ); + + $this->isChainOfObjects($expectedChain) + ? $this->assertPushedWithChainOfObjects($job, $expectedChain, $callback) + : $this->assertPushedWithChainOfClasses($job, $expectedChain, $callback); + } + + /** + * Assert if a job was pushed with an empty chain based on a truth-test callback. + * + * @param string $job + * @param callable|null $callback + * @return void + */ + public function assertPushedWithoutChain($job, $callback = null) + { + PHPUnit::assertTrue( + $this->pushed($job, $callback)->isNotEmpty(), + "The expected [{$job}] job was not pushed." + ); + + $this->assertPushedWithChainOfClasses($job, [], $callback); + } + + /** + * Assert if a job was pushed with chained jobs based on a truth-test callback. + * + * @param string $job + * @param array $expectedChain + * @param callable|null $callback + * @return void + */ + protected function assertPushedWithChainOfObjects($job, $expectedChain, $callback) + { + $chain = collect($expectedChain)->map(function ($job) { + return serialize($job); + })->all(); + + PHPUnit::assertTrue( + $this->pushed($job, $callback)->filter(function ($job) use ($chain) { + return $job->chained == $chain; + })->isNotEmpty(), + 'The expected chain was not pushed.' + ); + } + + /** + * Assert if a job was pushed with chained jobs based on a truth-test callback. + * + * @param string $job + * @param array $expectedChain + * @param callable|null $callback + * @return void + */ + protected function assertPushedWithChainOfClasses($job, $expectedChain, $callback) + { + $matching = $this->pushed($job, $callback)->map->chained->map(function ($chain) { + return collect($chain)->map(function ($job) { + return get_class(unserialize($job)); + }); + })->filter(function ($chain) use ($expectedChain) { + return $chain->all() === $expectedChain; + }); + + PHPUnit::assertTrue( + $matching->isNotEmpty(), 'The expected chain was not pushed.' + ); + } + + /** + * Determine if the given chain is entirely composed of objects. + * + * @param array $chain + * @return bool + */ + protected function isChainOfObjects($chain) + { + return ! collect($chain)->contains(function ($job) { + return ! is_object($job); + }); + } + + /** + * Determine if a job was pushed based on a truth-test callback. + * + * @param string|\Closure $job + * @param callable|null $callback + * @return void + */ + public function assertNotPushed($job, $callback = null) + { + if ($job instanceof Closure) { + [$job, $callback] = [$this->firstClosureParameterType($job), $job]; + } + + PHPUnit::assertCount( + 0, $this->pushed($job, $callback), + "The unexpected [{$job}] job was pushed." + ); + } + + /** + * Assert that no jobs were pushed. + * + * @return void + */ + public function assertNothingPushed() + { + PHPUnit::assertEmpty($this->jobs, 'Jobs were pushed unexpectedly.'); + } + + /** + * Get all of the jobs matching a truth-test callback. + * + * @param string $job + * @param callable|null $callback + * @return \Illuminate\Support\Collection + */ + public function pushed($job, $callback = null) + { + if (! $this->hasPushed($job)) { + return collect(); + } + + $callback = $callback ?: function () { + return true; + }; + + return collect($this->jobs[$job])->filter(function ($data) use ($callback) { + return $callback($data['job'], $data['queue']); + })->pluck('job'); + } + + /** + * Determine if there are any stored jobs for a given class. + * + * @param string $job + * @return bool + */ + public function hasPushed($job) + { + return isset($this->jobs[$job]) && ! empty($this->jobs[$job]); + } + + /** + * Resolve a queue connection instance. + * + * @param mixed $value + * @return \Illuminate\Contracts\Queue\Queue + */ + public function connection($value = null) + { + return $this; + } + + /** + * Get the size of the queue. + * + * @param string|null $queue + * @return int + */ + public function size($queue = null) + { + return collect($this->jobs)->flatten(1)->filter(function ($job) use ($queue) { + return $job['queue'] === $queue; + })->count(); + } + + /** + * Push a new job onto the queue. + * + * @param string|object $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function push($job, $data = '', $queue = null) + { + $this->jobs[is_object($job) ? get_class($job) : $job][] = [ + 'job' => $job, + 'queue' => $queue, + ]; + } + + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + */ + public function pushRaw($payload, $queue = null, array $options = []) + { + // + } + + /** + * Push a new job onto the queue after a delay. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string|object $job + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function later($delay, $job, $data = '', $queue = null) + { + return $this->push($job, $data, $queue); + } + + /** + * Push a new job onto the queue. + * + * @param string $queue + * @param string|object $job + * @param mixed $data + * @return mixed + */ + public function pushOn($queue, $job, $data = '') + { + return $this->push($job, $data, $queue); + } + + /** + * Push a new job onto the queue after a delay. + * + * @param string $queue + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string|object $job + * @param mixed $data + * @return mixed + */ + public function laterOn($queue, $delay, $job, $data = '') + { + return $this->push($job, $data, $queue); + } + + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + */ + public function pop($queue = null) + { + // + } + + /** + * Push an array of jobs onto the queue. + * + * @param array $jobs + * @param mixed $data + * @param string|null $queue + * @return mixed + */ + public function bulk($jobs, $data = '', $queue = null) + { + foreach ($jobs as $job) { + $this->push($job, $data, $queue); + } + } + + /** + * Get the jobs that have been pushed. + * + * @return array + */ + public function pushedJobs() + { + return $this->jobs; + } + + /** + * Get the connection name for the queue. + * + * @return string + */ + public function getConnectionName() + { + // + } + + /** + * Set the connection name for the queue. + * + * @param string $name + * @return $this + */ + public function setConnectionName($name) + { + return $this; + } + + /** + * Override the QueueManager to prevent circular dependency. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + throw new BadMethodCallException(sprintf( + 'Call to undefined method %s::%s()', static::class, $method + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Timebox.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Timebox.php new file mode 100644 index 0000000..32fd607 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Timebox.php @@ -0,0 +1,70 @@ +earlyReturn && $remainder > 0) { + $this->usleep($remainder); + } + + return $result; + } + + /** + * Indicate that the timebox can return early. + * + * @return $this + */ + public function returnEarly() + { + $this->earlyReturn = true; + + return $this; + } + + /** + * Indicate that the timebox cannot return early. + * + * @return $this + */ + public function dontReturnEarly() + { + $this->earlyReturn = false; + + return $this; + } + + /** + * Sleep for the specified number of microseconds. + * + * @param $microseconds + * @return void + */ + protected function usleep($microseconds) + { + usleep($microseconds); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/CapsuleManagerTrait.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/CapsuleManagerTrait.php new file mode 100644 index 0000000..0532755 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/CapsuleManagerTrait.php @@ -0,0 +1,69 @@ +container = $container; + + if (! $this->container->bound('config')) { + $this->container->instance('config', new Fluent); + } + } + + /** + * Make this capsule instance available globally. + * + * @return void + */ + public function setAsGlobal() + { + static::$instance = $this; + } + + /** + * Get the IoC container instance. + * + * @return \Illuminate\Contracts\Container\Container + */ + public function getContainer() + { + return $this->container; + } + + /** + * Set the IoC container instance. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function setContainer(Container $container) + { + $this->container = $container; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Conditionable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Conditionable.php new file mode 100644 index 0000000..7980827 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Conditionable.php @@ -0,0 +1,44 @@ +{$method}(...$parameters); + } catch (Error|BadMethodCallException $e) { + $pattern = '~^Call to undefined method (?P[^:]+)::(?P[^\(]+)\(\)$~'; + + if (! preg_match($pattern, $e->getMessage(), $matches)) { + throw $e; + } + + if ($matches['class'] != get_class($object) || + $matches['method'] != $method) { + throw $e; + } + + static::throwBadMethodCallException($method); + } + } + + /** + * Forward a method call to the given object, returning $this if the forwarded call returned itself. + * + * @param mixed $object + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + protected function forwardDecoratedCallTo($object, $method, $parameters) + { + $result = $this->forwardCallTo($object, $method, $parameters); + + if ($result === $object) { + return $this; + } + + return $result; + } + + /** + * Throw a bad method call exception for the given method. + * + * @param string $method + * @return void + * + * @throws \BadMethodCallException + */ + protected static function throwBadMethodCallException($method) + { + throw new BadMethodCallException(sprintf( + 'Call to undefined method %s::%s()', static::class, $method + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php new file mode 100644 index 0000000..1e9fa58 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php @@ -0,0 +1,34 @@ +getLocale(); + + try { + $app->setLocale($locale); + + return $callback(); + } finally { + $app->setLocale($original); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/ReflectsClosures.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/ReflectsClosures.php new file mode 100644 index 0000000..bf47d7e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/ReflectsClosures.php @@ -0,0 +1,88 @@ +closureParameterTypes($closure)); + + if (! $types) { + throw new RuntimeException('The given Closure has no parameters.'); + } + + if ($types[0] === null) { + throw new RuntimeException('The first parameter of the given Closure is missing a type hint.'); + } + + return $types[0]; + } + + /** + * Get the class names of the first parameter of the given Closure, including union types. + * + * @param \Closure $closure + * @return array + * + * @throws \ReflectionException + * @throws \RuntimeException + */ + protected function firstClosureParameterTypes(Closure $closure) + { + $reflection = new ReflectionFunction($closure); + + $types = collect($reflection->getParameters())->mapWithKeys(function ($parameter) { + if ($parameter->isVariadic()) { + return [$parameter->getName() => null]; + } + + return [$parameter->getName() => Reflector::getParameterClassNames($parameter)]; + })->filter()->values()->all(); + + if (empty($types)) { + throw new RuntimeException('The given Closure has no parameters.'); + } + + if (isset($types[0]) && empty($types[0])) { + throw new RuntimeException('The first parameter of the given Closure is missing a type hint.'); + } + + return $types[0]; + } + + /** + * Get the class names / types of the parameters of the given Closure. + * + * @param \Closure $closure + * @return array + * + * @throws \ReflectionException + */ + protected function closureParameterTypes(Closure $closure) + { + $reflection = new ReflectionFunction($closure); + + return collect($reflection->getParameters())->mapWithKeys(function ($parameter) { + if ($parameter->isVariadic()) { + return [$parameter->getName() => null]; + } + + return [$parameter->getName() => Reflector::getParameterClassName($parameter)]; + })->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Tappable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Tappable.php new file mode 100644 index 0000000..9353451 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/Traits/Tappable.php @@ -0,0 +1,17 @@ +input = $input; + } + + /** + * Get a subset containing the provided keys with values from the input data. + * + * @param array|mixed $keys + * @return array + */ + public function only($keys) + { + $results = []; + + $input = $this->input; + + $placeholder = new stdClass; + + foreach (is_array($keys) ? $keys : func_get_args() as $key) { + $value = data_get($input, $key, $placeholder); + + if ($value !== $placeholder) { + Arr::set($results, $key, $value); + } + } + + return $results; + } + + /** + * Get all of the input except for a specified array of items. + * + * @param array|mixed $keys + * @return array + */ + public function except($keys) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + $results = $this->input; + + Arr::forget($results, $keys); + + return $results; + } + + /** + * Merge the validated input with the given array of additional data. + * + * @param array $items + * @return static + */ + public function merge(array $items) + { + return new static(array_merge($this->input, $items)); + } + + /** + * Get the input as a collection. + * + * @return \Illuminate\Support\Collection + */ + public function collect() + { + return new Collection($this->input); + } + + /** + * Get the raw, underlying input array. + * + * @return array + */ + public function all() + { + return $this->input; + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return $this->all(); + } + + /** + * Dynamically access input data. + * + * @param string $name + * @return mixed + */ + public function __get($name) + { + return $this->input[$name]; + } + + /** + * Dynamically set input data. + * + * @param string $name + * @param mixed $value + * @return mixed + */ + public function __set($name, $value) + { + $this->input[$name] = $value; + } + + /** + * Determine if an input key is set. + * + * @return bool + */ + public function __isset($name) + { + return isset($this->input[$name]); + } + + /** + * Remove an input key. + * + * @param string $name + * @return void + */ + public function __unset($name) + { + unset($this->input[$name]); + } + + /** + * Determine if an item exists at an offset. + * + * @param mixed $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return isset($this->input[$key]); + } + + /** + * Get an item at a given offset. + * + * @param mixed $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->input[$key]; + } + + /** + * Set the item at a given offset. + * + * @param mixed $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + if (is_null($key)) { + $this->input[] = $value; + } else { + $this->input[$key] = $value; + } + } + + /** + * Unset the item at a given offset. + * + * @param string $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + unset($this->input[$key]); + } + + /** + * Get an iterator for the input. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new ArrayIterator($this->input); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ViewErrorBag.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ViewErrorBag.php new file mode 100644 index 0000000..d51bb53 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/ViewErrorBag.php @@ -0,0 +1,131 @@ +bags[$key]); + } + + /** + * Get a MessageBag instance from the bags. + * + * @param string $key + * @return \Illuminate\Contracts\Support\MessageBag + */ + public function getBag($key) + { + return Arr::get($this->bags, $key) ?: new MessageBag; + } + + /** + * Get all the bags. + * + * @return array + */ + public function getBags() + { + return $this->bags; + } + + /** + * Add a new MessageBag instance to the bags. + * + * @param string $key + * @param \Illuminate\Contracts\Support\MessageBag $bag + * @return $this + */ + public function put($key, MessageBagContract $bag) + { + $this->bags[$key] = $bag; + + return $this; + } + + /** + * Determine if the default message bag has any messages. + * + * @return bool + */ + public function any() + { + return $this->count() > 0; + } + + /** + * Get the number of messages in the default bag. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return $this->getBag('default')->count(); + } + + /** + * Dynamically call methods on the default bag. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->getBag('default')->$method(...$parameters); + } + + /** + * Dynamically access a view error bag. + * + * @param string $key + * @return \Illuminate\Contracts\Support\MessageBag + */ + public function __get($key) + { + return $this->getBag($key); + } + + /** + * Dynamically set a view error bag. + * + * @param string $key + * @param \Illuminate\Contracts\Support\MessageBag $value + * @return void + */ + public function __set($key, $value) + { + $this->put($key, $value); + } + + /** + * Convert the default bag to its string representation. + * + * @return string + */ + public function __toString() + { + return (string) $this->getBag('default'); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/composer.json new file mode 100644 index 0000000..527bdcb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/composer.json @@ -0,0 +1,55 @@ +{ + "name": "illuminate/support", + "description": "The Illuminate Support package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "ext-mbstring": "*", + "doctrine/inflector": "^1.4|^2.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "nesbot/carbon": "^2.53.1", + "voku/portable-ascii": "^1.6.1" + }, + "conflict": { + "tightenco/collect": "<5.5.33" + }, + "autoload": { + "psr-4": { + "Illuminate\\Support\\": "" + }, + "files": [ + "helpers.php" + ] + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "illuminate/filesystem": "Required to use the composer class (^8.0).", + "league/commonmark": "Required to use Str::markdown() and Stringable::markdown() (^1.3|^2.0.2).", + "ramsey/uuid": "Required to use Str::uuid() (^4.2.2).", + "symfony/process": "Required to use the composer class (^5.4).", + "symfony/var-dumper": "Required to use the dd function (^5.4).", + "vlucas/phpdotenv": "Required to use the Env class and env helper (^5.4.1)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/helpers.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/helpers.php new file mode 100755 index 0000000..0b82fe7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Support/helpers.php @@ -0,0 +1,379 @@ + $value) { + if (is_numeric($key)) { + $start++; + + $array[$start] = Arr::pull($array, $key); + } + } + + return $array; + } +} + +if (! function_exists('blank')) { + /** + * Determine if the given value is "blank". + * + * @param mixed $value + * @return bool + */ + function blank($value) + { + if (is_null($value)) { + return true; + } + + if (is_string($value)) { + return trim($value) === ''; + } + + if (is_numeric($value) || is_bool($value)) { + return false; + } + + if ($value instanceof Countable) { + return count($value) === 0; + } + + return empty($value); + } +} + +if (! function_exists('class_basename')) { + /** + * Get the class "basename" of the given object / class. + * + * @param string|object $class + * @return string + */ + function class_basename($class) + { + $class = is_object($class) ? get_class($class) : $class; + + return basename(str_replace('\\', '/', $class)); + } +} + +if (! function_exists('class_uses_recursive')) { + /** + * Returns all traits used by a class, its parent classes and trait of their traits. + * + * @param object|string $class + * @return array + */ + function class_uses_recursive($class) + { + if (is_object($class)) { + $class = get_class($class); + } + + $results = []; + + foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) { + $results += trait_uses_recursive($class); + } + + return array_unique($results); + } +} + +if (! function_exists('e')) { + /** + * Encode HTML special characters in a string. + * + * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|string|null $value + * @param bool $doubleEncode + * @return string + */ + function e($value, $doubleEncode = true) + { + if ($value instanceof DeferringDisplayableValue) { + $value = $value->resolveDisplayableValue(); + } + + if ($value instanceof Htmlable) { + return $value->toHtml(); + } + + return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8', $doubleEncode); + } +} + +if (! function_exists('env')) { + /** + * Gets the value of an environment variable. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + function env($key, $default = null) + { + return Env::get($key, $default); + } +} + +if (! function_exists('filled')) { + /** + * Determine if a value is "filled". + * + * @param mixed $value + * @return bool + */ + function filled($value) + { + return ! blank($value); + } +} + +if (! function_exists('object_get')) { + /** + * Get an item from an object using "dot" notation. + * + * @param object $object + * @param string|null $key + * @param mixed $default + * @return mixed + */ + function object_get($object, $key, $default = null) + { + if (is_null($key) || trim($key) === '') { + return $object; + } + + foreach (explode('.', $key) as $segment) { + if (! is_object($object) || ! isset($object->{$segment})) { + return value($default); + } + + $object = $object->{$segment}; + } + + return $object; + } +} + +if (! function_exists('optional')) { + /** + * Provide access to optional objects. + * + * @param mixed $value + * @param callable|null $callback + * @return mixed + */ + function optional($value = null, callable $callback = null) + { + if (is_null($callback)) { + return new Optional($value); + } elseif (! is_null($value)) { + return $callback($value); + } + } +} + +if (! function_exists('preg_replace_array')) { + /** + * Replace a given pattern with each value in the array in sequentially. + * + * @param string $pattern + * @param array $replacements + * @param string $subject + * @return string + */ + function preg_replace_array($pattern, array $replacements, $subject) + { + return preg_replace_callback($pattern, function () use (&$replacements) { + foreach ($replacements as $key => $value) { + return array_shift($replacements); + } + }, $subject); + } +} + +if (! function_exists('retry')) { + /** + * Retry an operation a given number of times. + * + * @param int $times + * @param callable $callback + * @param int|\Closure $sleepMilliseconds + * @param callable|null $when + * @return mixed + * + * @throws \Exception + */ + function retry($times, callable $callback, $sleepMilliseconds = 0, $when = null) + { + $attempts = 0; + + beginning: + $attempts++; + $times--; + + try { + return $callback($attempts); + } catch (Exception $e) { + if ($times < 1 || ($when && ! $when($e))) { + throw $e; + } + + if ($sleepMilliseconds) { + usleep(value($sleepMilliseconds, $attempts) * 1000); + } + + goto beginning; + } + } +} + +if (! function_exists('tap')) { + /** + * Call the given Closure with the given value then return the value. + * + * @param mixed $value + * @param callable|null $callback + * @return mixed + */ + function tap($value, $callback = null) + { + if (is_null($callback)) { + return new HigherOrderTapProxy($value); + } + + $callback($value); + + return $value; + } +} + +if (! function_exists('throw_if')) { + /** + * Throw the given exception if the given condition is true. + * + * @param mixed $condition + * @param \Throwable|string $exception + * @param mixed ...$parameters + * @return mixed + * + * @throws \Throwable + */ + function throw_if($condition, $exception = 'RuntimeException', ...$parameters) + { + if ($condition) { + if (is_string($exception) && class_exists($exception)) { + $exception = new $exception(...$parameters); + } + + throw is_string($exception) ? new RuntimeException($exception) : $exception; + } + + return $condition; + } +} + +if (! function_exists('throw_unless')) { + /** + * Throw the given exception unless the given condition is true. + * + * @param mixed $condition + * @param \Throwable|string $exception + * @param mixed ...$parameters + * @return mixed + * + * @throws \Throwable + */ + function throw_unless($condition, $exception = 'RuntimeException', ...$parameters) + { + throw_if(! $condition, $exception, ...$parameters); + + return $condition; + } +} + +if (! function_exists('trait_uses_recursive')) { + /** + * Returns all traits used by a trait and its traits. + * + * @param string $trait + * @return array + */ + function trait_uses_recursive($trait) + { + $traits = class_uses($trait) ?: []; + + foreach ($traits as $trait) { + $traits += trait_uses_recursive($trait); + } + + return $traits; + } +} + +if (! function_exists('transform')) { + /** + * Transform the given value if it is present. + * + * @param mixed $value + * @param callable $callback + * @param mixed $default + * @return mixed|null + */ + function transform($value, callable $callback, $default = null) + { + if (filled($value)) { + return $callback($value); + } + + if (is_callable($default)) { + return $default($value); + } + + return $default; + } +} + +if (! function_exists('windows_os')) { + /** + * Determine whether the current environment is Windows based. + * + * @return bool + */ + function windows_os() + { + return PHP_OS_FAMILY === 'Windows'; + } +} + +if (! function_exists('with')) { + /** + * Return the given value, optionally passed through the given callback. + * + * @param mixed $value + * @param callable|null $callback + * @return mixed + */ + function with($value, callable $callback = null) + { + return is_null($callback) ? $value : $callback($value); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Assert.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Assert.php new file mode 100644 index 0000000..c0184b7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Assert.php @@ -0,0 +1,79 @@ +json = $jsonable; + + if ($jsonable instanceof JsonSerializable) { + $this->decoded = $jsonable->jsonSerialize(); + } elseif ($jsonable instanceof Jsonable) { + $this->decoded = json_decode($jsonable->toJson(), true); + } elseif (is_array($jsonable)) { + $this->decoded = $jsonable; + } else { + $this->decoded = json_decode($jsonable, true); + } + } + + /** + * Validate and return the decoded response JSON. + * + * @param string|null $key + * @return mixed + */ + public function json($key = null) + { + return data_get($this->decoded, $key); + } + + /** + * Assert that the response JSON has the expected count of items at the given key. + * + * @param int $count + * @param string|null $key + * @return $this + */ + public function assertCount(int $count, $key = null) + { + if (! is_null($key)) { + PHPUnit::assertCount( + $count, data_get($this->decoded, $key), + "Failed to assert that the response count matched the expected {$count}" + ); + + return $this; + } + + PHPUnit::assertCount($count, + $this->decoded, + "Failed to assert that the response count matched the expected {$count}" + ); + + return $this; + } + + /** + * Assert that the response has the exact given JSON. + * + * @param array $data + * @return $this + */ + public function assertExact(array $data) + { + $actual = $this->reorderAssocKeys((array) $this->decoded); + + $expected = $this->reorderAssocKeys($data); + + PHPUnit::assertEquals( + json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), + json_encode($actual, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) + ); + + return $this; + } + + /** + * Assert that the response has the similar JSON as given. + * + * @param array $data + * @return $this + */ + public function assertSimilar(array $data) + { + $actual = json_encode(Arr::sortRecursive( + (array) $this->decoded + )); + + PHPUnit::assertEquals(json_encode(Arr::sortRecursive($data)), $actual); + + return $this; + } + + /** + * Assert that the response contains the given JSON fragment. + * + * @param array $data + * @return $this + */ + public function assertFragment(array $data) + { + $actual = json_encode(Arr::sortRecursive( + (array) $this->decoded + )); + + foreach (Arr::sortRecursive($data) as $key => $value) { + $expected = $this->jsonSearchStrings($key, $value); + + PHPUnit::assertTrue( + Str::contains($actual, $expected), + 'Unable to find JSON fragment: '.PHP_EOL.PHP_EOL. + '['.json_encode([$key => $value]).']'.PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. + "[{$actual}]." + ); + } + + return $this; + } + + /** + * Assert that the response does not contain the given JSON fragment. + * + * @param array $data + * @param bool $exact + * @return $this + */ + public function assertMissing(array $data, $exact = false) + { + if ($exact) { + return $this->assertMissingExact($data); + } + + $actual = json_encode(Arr::sortRecursive( + (array) $this->decoded + )); + + foreach (Arr::sortRecursive($data) as $key => $value) { + $unexpected = $this->jsonSearchStrings($key, $value); + + PHPUnit::assertFalse( + Str::contains($actual, $unexpected), + 'Found unexpected JSON fragment: '.PHP_EOL.PHP_EOL. + '['.json_encode([$key => $value]).']'.PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. + "[{$actual}]." + ); + } + + return $this; + } + + /** + * Assert that the response does not contain the exact JSON fragment. + * + * @param array $data + * @return $this + */ + public function assertMissingExact(array $data) + { + $actual = json_encode(Arr::sortRecursive( + (array) $this->decoded + )); + + foreach (Arr::sortRecursive($data) as $key => $value) { + $unexpected = $this->jsonSearchStrings($key, $value); + + if (! Str::contains($actual, $unexpected)) { + return $this; + } + } + + PHPUnit::fail( + 'Found unexpected JSON fragment: '.PHP_EOL.PHP_EOL. + '['.json_encode($data).']'.PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. + "[{$actual}]." + ); + + return $this; + } + + /** + * Assert that the expected value and type exists at the given path in the response. + * + * @param string $path + * @param mixed $expect + * @return $this + */ + public function assertPath($path, $expect) + { + PHPUnit::assertSame($expect, $this->json($path)); + + return $this; + } + + /** + * Assert that the response has a given JSON structure. + * + * @param array|null $structure + * @param array|null $responseData + * @return $this + */ + public function assertStructure(array $structure = null, $responseData = null) + { + if (is_null($structure)) { + return $this->assertSimilar($this->decoded); + } + + if (! is_null($responseData)) { + return (new static($responseData))->assertStructure($structure); + } + + foreach ($structure as $key => $value) { + if (is_array($value) && $key === '*') { + PHPUnit::assertIsArray($this->decoded); + + foreach ($this->decoded as $responseDataItem) { + $this->assertStructure($structure['*'], $responseDataItem); + } + } elseif (is_array($value)) { + PHPUnit::assertArrayHasKey($key, $this->decoded); + + $this->assertStructure($structure[$key], $this->decoded[$key]); + } else { + PHPUnit::assertArrayHasKey($value, $this->decoded); + } + } + + return $this; + } + + /** + * Assert that the response is a superset of the given JSON. + * + * @param array $data + * @param bool $strict + * @return $this + */ + public function assertSubset(array $data, $strict = false) + { + PHPUnit::assertArraySubset( + $data, $this->decoded, $strict, $this->assertJsonMessage($data) + ); + + return $this; + } + + /** + * Reorder associative array keys to make it easy to compare arrays. + * + * @param array $data + * @return array + */ + protected function reorderAssocKeys(array $data) + { + $data = Arr::dot($data); + ksort($data); + + $result = []; + + foreach ($data as $key => $value) { + Arr::set($result, $key, $value); + } + + return $result; + } + + /** + * Get the assertion message for assertJson. + * + * @param array $data + * @return string + */ + protected function assertJsonMessage(array $data) + { + $expected = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + + $actual = json_encode($this->decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + + return 'Unable to find JSON: '.PHP_EOL.PHP_EOL. + "[{$expected}]".PHP_EOL.PHP_EOL. + 'within response JSON:'.PHP_EOL.PHP_EOL. + "[{$actual}].".PHP_EOL.PHP_EOL; + } + + /** + * Get the strings we need to search for when examining the JSON. + * + * @param string $key + * @param string $value + * @return array + */ + protected function jsonSearchStrings($key, $value) + { + $needle = substr(json_encode([$key => $value]), 1, -1); + + return [ + $needle.']', + $needle.'}', + $needle.',', + ]; + } + + /** + * Get the total number of items in the underlying JSON array. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return count($this->decoded); + } + + /** + * Determine whether an offset exists. + * + * @param mixed $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return isset($this->decoded[$offset]); + } + + /** + * Get the value at the given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->decoded[$offset]; + } + + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + $this->decoded[$offset] = $value; + } + + /** + * Unset the value at the given offset. + * + * @param string $offset + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + unset($this->decoded[$offset]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Concerns/TestDatabases.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Concerns/TestDatabases.php new file mode 100644 index 0000000..c27c2d3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Concerns/TestDatabases.php @@ -0,0 +1,180 @@ +whenNotUsingInMemoryDatabase(function ($database) { + if (ParallelTesting::option('recreate_databases')) { + Schema::dropDatabaseIfExists( + $this->testDatabase($database) + ); + } + }); + }); + + ParallelTesting::setUpTestCase(function ($testCase) { + $uses = array_flip(class_uses_recursive(get_class($testCase))); + + $databaseTraits = [ + Testing\DatabaseMigrations::class, + Testing\DatabaseTransactions::class, + Testing\RefreshDatabase::class, + ]; + + if (Arr::hasAny($uses, $databaseTraits)) { + if (! ParallelTesting::option('without_databases')) { + $this->whenNotUsingInMemoryDatabase(function ($database) use ($uses) { + [$testDatabase, $created] = $this->ensureTestDatabaseExists($database); + + $this->switchToDatabase($testDatabase); + + if (isset($uses[Testing\DatabaseTransactions::class])) { + $this->ensureSchemaIsUpToDate(); + } + + if ($created) { + ParallelTesting::callSetUpTestDatabaseCallbacks($testDatabase); + } + }); + } + } + }); + } + + /** + * Ensure a test database exists and returns its name. + * + * @param string $database + * @return array + */ + protected function ensureTestDatabaseExists($database) + { + $testDatabase = $this->testDatabase($database); + + try { + $this->usingDatabase($testDatabase, function () { + Schema::hasTable('dummy'); + }); + } catch (QueryException $e) { + $this->usingDatabase($database, function () use ($testDatabase) { + Schema::dropDatabaseIfExists($testDatabase); + Schema::createDatabase($testDatabase); + }); + + return [$testDatabase, true]; + } + + return [$testDatabase, false]; + } + + /** + * Ensure the current database test schema is up to date. + * + * @return void + */ + protected function ensureSchemaIsUpToDate() + { + if (! static::$schemaIsUpToDate) { + Artisan::call('migrate'); + + static::$schemaIsUpToDate = true; + } + } + + /** + * Runs the given callable using the given database. + * + * @param string $database + * @param callable $callable + * @return void + */ + protected function usingDatabase($database, $callable) + { + $original = DB::getConfig('database'); + + try { + $this->switchToDatabase($database); + $callable(); + } finally { + $this->switchToDatabase($original); + } + } + + /** + * Apply the given callback when tests are not using in memory database. + * + * @param callable $callback + * @return void + */ + protected function whenNotUsingInMemoryDatabase($callback) + { + $database = DB::getConfig('database'); + + if ($database !== ':memory:') { + $callback($database); + } + } + + /** + * Switch to the given database. + * + * @param string $database + * @return void + */ + protected function switchToDatabase($database) + { + DB::purge(); + + $default = config('database.default'); + + $url = config("database.connections.{$default}.url"); + + if ($url) { + config()->set( + "database.connections.{$default}.url", + preg_replace('/^(.*)(\/[\w-]*)(\??.*)$/', "$1/{$database}$3", $url), + ); + } else { + config()->set( + "database.connections.{$default}.database", + $database, + ); + } + } + + /** + * Returns the test database name. + * + * @return string + */ + protected function testDatabase($database) + { + $token = ParallelTesting::token(); + + return "{$database}_test_{$token}"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/ArraySubset.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/ArraySubset.php new file mode 100644 index 0000000..c455bdd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/ArraySubset.php @@ -0,0 +1,279 @@ += 9) { + /** + * @internal This class is not meant to be used or overwritten outside the framework itself. + */ + final class ArraySubset extends Constraint + { + /** + * @var iterable + */ + private $subset; + + /** + * @var bool + */ + private $strict; + + /** + * Create a new array subset constraint instance. + * + * @param iterable $subset + * @param bool $strict + * @return void + */ + public function __construct(iterable $subset, bool $strict = false) + { + $this->strict = $strict; + $this->subset = $subset; + } + + /** + * Evaluates the constraint for parameter $other. + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param mixed $other + * @param string $description + * @param bool $returnResult + * @return bool|null + * + * @throws \PHPUnit\Framework\ExpectationFailedException + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function evaluate($other, string $description = '', bool $returnResult = false): ?bool + { + // type cast $other & $this->subset as an array to allow + // support in standard array functions. + $other = $this->toArray($other); + $this->subset = $this->toArray($this->subset); + + $patched = array_replace_recursive($other, $this->subset); + + if ($this->strict) { + $result = $other === $patched; + } else { + $result = $other == $patched; + } + + if ($returnResult) { + return $result; + } + + if (! $result) { + $f = new ComparisonFailure( + $patched, + $other, + var_export($patched, true), + var_export($other, true) + ); + + $this->fail($other, $description, $f); + } + + return null; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function toString(): string + { + return 'has the subset '.$this->exporter()->export($this->subset); + } + + /** + * Returns the description of the failure. + * + * The beginning of failure messages is "Failed asserting that" in most + * cases. This method should return the second part of that sentence. + * + * @param mixed $other + * @return string + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + protected function failureDescription($other): string + { + return 'an array '.$this->toString(); + } + + /** + * Returns the description of the failure. + * + * The beginning of failure messages is "Failed asserting that" in most + * cases. This method should return the second part of that sentence. + * + * @param iterable $other + * @return array + */ + private function toArray(iterable $other): array + { + if (is_array($other)) { + return $other; + } + + if ($other instanceof ArrayObject) { + return $other->getArrayCopy(); + } + + if ($other instanceof Traversable) { + return iterator_to_array($other); + } + + // Keep BC even if we know that array would not be the expected one + return (array) $other; + } + } +} else { + /** + * @internal This class is not meant to be used or overwritten outside the framework itself. + */ + final class ArraySubset extends Constraint + { + /** + * @var iterable + */ + private $subset; + + /** + * @var bool + */ + private $strict; + + /** + * Create a new array subset constraint instance. + * + * @param iterable $subset + * @param bool $strict + * @return void + */ + public function __construct(iterable $subset, bool $strict = false) + { + $this->strict = $strict; + $this->subset = $subset; + } + + /** + * Evaluates the constraint for parameter $other. + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param mixed $other + * @param string $description + * @param bool $returnResult + * @return bool|null + * + * @throws \PHPUnit\Framework\ExpectationFailedException + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function evaluate($other, string $description = '', bool $returnResult = false) + { + // type cast $other & $this->subset as an array to allow + // support in standard array functions. + $other = $this->toArray($other); + $this->subset = $this->toArray($this->subset); + + $patched = array_replace_recursive($other, $this->subset); + + if ($this->strict) { + $result = $other === $patched; + } else { + $result = $other == $patched; + } + + if ($returnResult) { + return $result; + } + + if (! $result) { + $f = new ComparisonFailure( + $patched, + $other, + var_export($patched, true), + var_export($other, true) + ); + + $this->fail($other, $description, $f); + } + } + + /** + * Returns a string representation of the constraint. + * + * @return string + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function toString(): string + { + return 'has the subset '.$this->exporter()->export($this->subset); + } + + /** + * Returns the description of the failure. + * + * The beginning of failure messages is "Failed asserting that" in most + * cases. This method should return the second part of that sentence. + * + * @param mixed $other + * @return string + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + protected function failureDescription($other): string + { + return 'an array '.$this->toString(); + } + + /** + * Returns the description of the failure. + * + * The beginning of failure messages is "Failed asserting that" in most + * cases. This method should return the second part of that sentence. + * + * @param iterable $other + * @return array + */ + private function toArray(iterable $other): array + { + if (is_array($other)) { + return $other; + } + + if ($other instanceof ArrayObject) { + return $other->getArrayCopy(); + } + + if ($other instanceof Traversable) { + return iterator_to_array($other); + } + + // Keep BC even if we know that array would not be the expected one + return (array) $other; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/CountInDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/CountInDatabase.php new file mode 100644 index 0000000..3ed6826 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/CountInDatabase.php @@ -0,0 +1,83 @@ +expectedCount = $expectedCount; + + $this->database = $database; + } + + /** + * Check if the expected and actual count are equal. + * + * @param string $table + * @return bool + */ + public function matches($table): bool + { + $this->actualCount = $this->database->table($table)->count(); + + return $this->actualCount === $this->expectedCount; + } + + /** + * Get the description of the failure. + * + * @param string $table + * @return string + */ + public function failureDescription($table): string + { + return sprintf( + "table [%s] matches expected entries count of %s. Entries found: %s.\n", + $table, $this->expectedCount, $this->actualCount + ); + } + + /** + * Get a string representation of the object. + * + * @param int $options + * @return string + */ + public function toString($options = 0): string + { + return (new ReflectionClass($this))->name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/HasInDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/HasInDatabase.php new file mode 100644 index 0000000..039ee44 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/HasInDatabase.php @@ -0,0 +1,121 @@ +data = $data; + + $this->database = $database; + } + + /** + * Check if the data is found in the given table. + * + * @param string $table + * @return bool + */ + public function matches($table): bool + { + return $this->database->table($table)->where($this->data)->count() > 0; + } + + /** + * Get the description of the failure. + * + * @param string $table + * @return string + */ + public function failureDescription($table): string + { + return sprintf( + "a row in the table [%s] matches the attributes %s.\n\n%s", + $table, $this->toString(JSON_PRETTY_PRINT), $this->getAdditionalInfo($table) + ); + } + + /** + * Get additional info about the records found in the database table. + * + * @param string $table + * @return string + */ + protected function getAdditionalInfo($table) + { + $query = $this->database->table($table); + + $similarResults = $query->where( + array_key_first($this->data), + $this->data[array_key_first($this->data)] + )->limit($this->show)->get(); + + if ($similarResults->isNotEmpty()) { + $description = 'Found similar results: '.json_encode($similarResults, JSON_PRETTY_PRINT); + } else { + $query = $this->database->table($table); + + $results = $query->limit($this->show)->get(); + + if ($results->isEmpty()) { + return 'The table is empty.'; + } + + $description = 'Found: '.json_encode($results, JSON_PRETTY_PRINT); + } + + if ($query->count() > $this->show) { + $description .= sprintf(' and %s others', $query->count() - $this->show); + } + + return $description; + } + + /** + * Get a string representation of the object. + * + * @param int $options + * @return string + */ + public function toString($options = 0): string + { + foreach ($this->data as $key => $data) { + $output[$key] = $data instanceof Expression ? (string) $data : $data; + } + + return json_encode($output ?? [], $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/NotSoftDeletedInDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/NotSoftDeletedInDatabase.php new file mode 100644 index 0000000..ff81958 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/NotSoftDeletedInDatabase.php @@ -0,0 +1,115 @@ +database = $database; + $this->data = $data; + $this->deletedAtColumn = $deletedAtColumn; + } + + /** + * Check if the data is found in the given table. + * + * @param string $table + * @return bool + */ + public function matches($table): bool + { + return $this->database->table($table) + ->where($this->data) + ->whereNull($this->deletedAtColumn) + ->count() > 0; + } + + /** + * Get the description of the failure. + * + * @param string $table + * @return string + */ + public function failureDescription($table): string + { + return sprintf( + "any existing row in the table [%s] matches the attributes %s.\n\n%s", + $table, $this->toString(), $this->getAdditionalInfo($table) + ); + } + + /** + * Get additional info about the records found in the database table. + * + * @param string $table + * @return string + */ + protected function getAdditionalInfo($table) + { + $query = $this->database->table($table); + + $results = $query->limit($this->show)->get(); + + if ($results->isEmpty()) { + return 'The table is empty'; + } + + $description = 'Found: '.json_encode($results, JSON_PRETTY_PRINT); + + if ($query->count() > $this->show) { + $description .= sprintf(' and %s others', $query->count() - $this->show); + } + + return $description; + } + + /** + * Get a string representation of the object. + * + * @return string + */ + public function toString(): string + { + return json_encode($this->data); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/SeeInOrder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/SeeInOrder.php new file mode 100644 index 0000000..609f32d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/SeeInOrder.php @@ -0,0 +1,88 @@ +content = $content; + } + + /** + * Determine if the rule passes validation. + * + * @param array $values + * @return bool + */ + public function matches($values): bool + { + $position = 0; + + foreach ($values as $value) { + if (empty($value)) { + continue; + } + + $valuePosition = mb_strpos($this->content, $value, $position); + + if ($valuePosition === false || $valuePosition < $position) { + $this->failedValue = $value; + + return false; + } + + $position = $valuePosition + mb_strlen($value); + } + + return true; + } + + /** + * Get the description of the failure. + * + * @param array $values + * @return string + */ + public function failureDescription($values): string + { + return sprintf( + 'Failed asserting that \'%s\' contains "%s" in specified order.', + $this->content, + $this->failedValue + ); + } + + /** + * Get a string representation of the object. + * + * @return string + */ + public function toString(): string + { + return (new ReflectionClass($this))->name; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/SoftDeletedInDatabase.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/SoftDeletedInDatabase.php new file mode 100644 index 0000000..baaeee2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Constraints/SoftDeletedInDatabase.php @@ -0,0 +1,117 @@ +data = $data; + + $this->database = $database; + + $this->deletedAtColumn = $deletedAtColumn; + } + + /** + * Check if the data is found in the given table. + * + * @param string $table + * @return bool + */ + public function matches($table): bool + { + return $this->database->table($table) + ->where($this->data) + ->whereNotNull($this->deletedAtColumn) + ->count() > 0; + } + + /** + * Get the description of the failure. + * + * @param string $table + * @return string + */ + public function failureDescription($table): string + { + return sprintf( + "any soft deleted row in the table [%s] matches the attributes %s.\n\n%s", + $table, $this->toString(), $this->getAdditionalInfo($table) + ); + } + + /** + * Get additional info about the records found in the database table. + * + * @param string $table + * @return string + */ + protected function getAdditionalInfo($table) + { + $query = $this->database->table($table); + + $results = $query->limit($this->show)->get(); + + if ($results->isEmpty()) { + return 'The table is empty'; + } + + $description = 'Found: '.json_encode($results, JSON_PRETTY_PRINT); + + if ($query->count() > $this->show) { + $description .= sprintf(' and %s others', $query->count() - $this->show); + } + + return $description; + } + + /** + * Get a string representation of the object. + * + * @return string + */ + public function toString(): string + { + return json_encode($this->data); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/AssertableJson.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/AssertableJson.php new file mode 100644 index 0000000..d548e28 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/AssertableJson.php @@ -0,0 +1,177 @@ +path = $path; + $this->props = $props; + } + + /** + * Compose the absolute "dot" path to the given key. + * + * @param string $key + * @return string + */ + protected function dotPath(string $key = ''): string + { + if (is_null($this->path)) { + return $key; + } + + return rtrim(implode('.', [$this->path, $key]), '.'); + } + + /** + * Retrieve a prop within the current scope using "dot" notation. + * + * @param string|null $key + * @return mixed + */ + protected function prop(string $key = null) + { + return Arr::get($this->props, $key); + } + + /** + * Instantiate a new "scope" at the path of the given key. + * + * @param string $key + * @param \Closure $callback + * @return $this + */ + protected function scope(string $key, Closure $callback): self + { + $props = $this->prop($key); + $path = $this->dotPath($key); + + PHPUnit::assertIsArray($props, sprintf('Property [%s] is not scopeable.', $path)); + + $scope = new static($props, $path); + $callback($scope); + $scope->interacted(); + + return $this; + } + + /** + * Instantiate a new "scope" on the first child element. + * + * @param \Closure $callback + * @return $this + */ + public function first(Closure $callback): self + { + $props = $this->prop(); + + $path = $this->dotPath(); + + PHPUnit::assertNotEmpty($props, $path === '' + ? 'Cannot scope directly onto the first element of the root level because it is empty.' + : sprintf('Cannot scope directly onto the first element of property [%s] because it is empty.', $path) + ); + + $key = array_keys($props)[0]; + + $this->interactsWith($key); + + return $this->scope($key, $callback); + } + + /** + * Instantiate a new "scope" on each child element. + * + * @param \Closure $callback + * @return $this + */ + public function each(Closure $callback): self + { + $props = $this->prop(); + + $path = $this->dotPath(); + + PHPUnit::assertNotEmpty($props, $path === '' + ? 'Cannot scope directly onto each element of the root level because it is empty.' + : sprintf('Cannot scope directly onto each element of property [%s] because it is empty.', $path) + ); + + foreach (array_keys($props) as $key) { + $this->interactsWith($key); + + $this->scope($key, $callback); + } + + return $this; + } + + /** + * Create a new instance from an array. + * + * @param array $data + * @return static + */ + public static function fromArray(array $data): self + { + return new static($data); + } + + /** + * Create a new instance from a AssertableJsonString. + * + * @param \Illuminate\Testing\AssertableJsonString $json + * @return static + */ + public static function fromAssertableJsonString(AssertableJsonString $json): self + { + return static::fromArray($json->json()); + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return $this->props; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Debugging.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Debugging.php new file mode 100644 index 0000000..f51d119 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Debugging.php @@ -0,0 +1,38 @@ +prop($prop)); + + return $this; + } + + /** + * Dumps the given props and exits. + * + * @param string|null $prop + * @return void + */ + public function dd(string $prop = null): void + { + dd($this->prop($prop)); + } + + /** + * Retrieve a prop within the current scope using "dot" notation. + * + * @param string|null $key + * @return mixed + */ + abstract protected function prop(string $key = null); +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Has.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Has.php new file mode 100644 index 0000000..7765f4a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Has.php @@ -0,0 +1,213 @@ +dotPath(); + + PHPUnit::assertCount( + $key, + $this->prop(), + $path + ? sprintf('Property [%s] does not have the expected size.', $path) + : sprintf('Root level does not have the expected size.') + ); + + return $this; + } + + PHPUnit::assertCount( + $length, + $this->prop($key), + sprintf('Property [%s] does not have the expected size.', $this->dotPath($key)) + ); + + return $this; + } + + /** + * Ensure that the given prop exists. + * + * @param string|int $key + * @param int|\Closure|null $length + * @param \Closure|null $callback + * @return $this + */ + public function has($key, $length = null, Closure $callback = null): self + { + $prop = $this->prop(); + + if (is_int($key) && is_null($length)) { + return $this->count($key); + } + + PHPUnit::assertTrue( + Arr::has($prop, $key), + sprintf('Property [%s] does not exist.', $this->dotPath($key)) + ); + + $this->interactsWith($key); + + if (! is_null($callback)) { + return $this->has($key, function (self $scope) use ($length, $callback) { + return $scope + ->tap(function (self $scope) use ($length) { + if (! is_null($length)) { + $scope->count($length); + } + }) + ->first($callback) + ->etc(); + }); + } + + if (is_callable($length)) { + return $this->scope($key, $length); + } + + if (! is_null($length)) { + return $this->count($key, $length); + } + + return $this; + } + + /** + * Assert that all of the given props exist. + * + * @param array|string $key + * @return $this + */ + public function hasAll($key): self + { + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $prop => $count) { + if (is_int($prop)) { + $this->has($count); + } else { + $this->has($prop, $count); + } + } + + return $this; + } + + /** + * Assert that at least one of the given props exists. + * + * @param array|string $key + * @return $this + */ + public function hasAny($key): self + { + $keys = is_array($key) ? $key : func_get_args(); + + PHPUnit::assertTrue( + Arr::hasAny($this->prop(), $keys), + sprintf('None of properties [%s] exist.', implode(', ', $keys)) + ); + + foreach ($keys as $key) { + $this->interactsWith($key); + } + + return $this; + } + + /** + * Assert that none of the given props exist. + * + * @param array|string $key + * @return $this + */ + public function missingAll($key): self + { + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $prop) { + $this->missing($prop); + } + + return $this; + } + + /** + * Assert that the given prop does not exist. + * + * @param string $key + * @return $this + */ + public function missing(string $key): self + { + PHPUnit::assertNotTrue( + Arr::has($this->prop(), $key), + sprintf('Property [%s] was found while it was expected to be missing.', $this->dotPath($key)) + ); + + return $this; + } + + /** + * Compose the absolute "dot" path to the given key. + * + * @param string $key + * @return string + */ + abstract protected function dotPath(string $key = ''): string; + + /** + * Marks the property as interacted. + * + * @param string $key + * @return void + */ + abstract protected function interactsWith(string $key): void; + + /** + * Retrieve a prop within the current scope using "dot" notation. + * + * @param string|null $key + * @return mixed + */ + abstract protected function prop(string $key = null); + + /** + * Instantiate a new "scope" at the path of the given key. + * + * @param string $key + * @param \Closure $callback + * @return $this + */ + abstract protected function scope(string $key, Closure $callback); + + /** + * Disables the interaction check. + * + * @return $this + */ + abstract public function etc(); + + /** + * Instantiate a new "scope" on the first element. + * + * @param \Closure $callback + * @return $this + */ + abstract public function first(Closure $callback); +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Interaction.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Interaction.php new file mode 100644 index 0000000..15e7e95 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Interaction.php @@ -0,0 +1,67 @@ +interacted, true)) { + $this->interacted[] = $prop; + } + } + + /** + * Asserts that all properties have been interacted with. + * + * @return void + */ + public function interacted(): void + { + PHPUnit::assertSame( + [], + array_diff(array_keys($this->prop()), $this->interacted), + $this->path + ? sprintf('Unexpected properties were found in scope [%s].', $this->path) + : 'Unexpected properties were found on the root level.' + ); + } + + /** + * Disables the interaction check. + * + * @return $this + */ + public function etc(): self + { + $this->interacted = array_keys($this->prop()); + + return $this; + } + + /** + * Retrieve a prop within the current scope using "dot" notation. + * + * @param string|null $key + * @return mixed + */ + abstract protected function prop(string $key = null); +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Matching.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Matching.php new file mode 100644 index 0000000..949047b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/Fluent/Concerns/Matching.php @@ -0,0 +1,193 @@ +has($key); + + $actual = $this->prop($key); + + if ($expected instanceof Closure) { + PHPUnit::assertTrue( + $expected(is_array($actual) ? Collection::make($actual) : $actual), + sprintf('Property [%s] was marked as invalid using a closure.', $this->dotPath($key)) + ); + + return $this; + } + + if ($expected instanceof Arrayable) { + $expected = $expected->toArray(); + } + + $this->ensureSorted($expected); + $this->ensureSorted($actual); + + PHPUnit::assertSame( + $expected, + $actual, + sprintf('Property [%s] does not match the expected value.', $this->dotPath($key)) + ); + + return $this; + } + + /** + * Asserts that all properties match their expected values. + * + * @param array $bindings + * @return $this + */ + public function whereAll(array $bindings): self + { + foreach ($bindings as $key => $value) { + $this->where($key, $value); + } + + return $this; + } + + /** + * Asserts that the property is of the expected type. + * + * @param string $key + * @param string|array $expected + * @return $this + */ + public function whereType(string $key, $expected): self + { + $this->has($key); + + $actual = $this->prop($key); + + if (! is_array($expected)) { + $expected = explode('|', $expected); + } + + PHPUnit::assertContains( + strtolower(gettype($actual)), + $expected, + sprintf('Property [%s] is not of expected type [%s].', $this->dotPath($key), implode('|', $expected)) + ); + + return $this; + } + + /** + * Asserts that all properties are of their expected types. + * + * @param array $bindings + * @return $this + */ + public function whereAllType(array $bindings): self + { + foreach ($bindings as $key => $value) { + $this->whereType($key, $value); + } + + return $this; + } + + /** + * Asserts that the property contains the expected values. + * + * @param string $key + * @param mixed $expected + * @return $this + */ + public function whereContains(string $key, $expected) + { + $actual = Collection::make( + $this->prop($key) ?? $this->prop() + ); + + $missing = Collection::make($expected)->reject(function ($search) use ($key, $actual) { + if ($actual->containsStrict($key, $search)) { + return true; + } + + return $actual->containsStrict($search); + }); + + if ($missing->whereInstanceOf('Closure')->isNotEmpty()) { + PHPUnit::assertEmpty( + $missing->toArray(), + sprintf( + 'Property [%s] does not contain a value that passes the truth test within the given closure.', + $key, + ) + ); + } else { + PHPUnit::assertEmpty( + $missing->toArray(), + sprintf( + 'Property [%s] does not contain [%s].', + $key, + implode(', ', array_values($missing->toArray())) + ) + ); + } + + return $this; + } + + /** + * Ensures that all properties are sorted the same way, recursively. + * + * @param mixed $value + * @return void + */ + protected function ensureSorted(&$value): void + { + if (! is_array($value)) { + return; + } + + foreach ($value as &$arg) { + $this->ensureSorted($arg); + } + + ksort($value); + } + + /** + * Compose the absolute "dot" path to the given key. + * + * @param string $key + * @return string + */ + abstract protected function dotPath(string $key = ''): string; + + /** + * Ensure that the given prop exists. + * + * @param string $key + * @param null $value + * @param \Closure|null $scope + * @return $this + */ + abstract public function has(string $key, $value = null, Closure $scope = null); + + /** + * Retrieve a prop within the current scope using "dot" notation. + * + * @param string|null $key + * @return mixed + */ + abstract protected function prop(string $key = null); +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/LoggedExceptionCollection.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/LoggedExceptionCollection.php new file mode 100644 index 0000000..907b061 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/LoggedExceptionCollection.php @@ -0,0 +1,10 @@ +getVerbosity(), + $output->isDecorated(), + $output->getFormatter(), + ); + + $this->output = $output; + } + + /** + * Writes a message to the output. + * + * @param string|iterable $messages + * @param bool $newline + * @param int $options + * @return void + */ + public function write($messages, bool $newline = false, int $options = 0) + { + $messages = collect($messages)->filter(function ($message) { + return ! Str::contains($message, $this->ignore); + }); + + $this->output->write($messages->toArray(), $newline, $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelRunner.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelRunner.php new file mode 100644 index 0000000..fd3b7dc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelRunner.php @@ -0,0 +1,177 @@ +options = $options; + + if ($output instanceof ConsoleOutput) { + $output = new ParallelConsoleOutput($output); + } + + $runnerResolver = static::$runnerResolver ?: function (Options $options, OutputInterface $output) { + return new WrapperRunner($options, $output); + }; + + $this->runner = call_user_func($runnerResolver, $options, $output); + } + + /** + * Set the application resolver callback. + * + * @param \Closure|null $resolver + * @return void + */ + public static function resolveApplicationUsing($resolver) + { + static::$applicationResolver = $resolver; + } + + /** + * Set the runner resolver callback. + * + * @param \Closure|null $resolver + * @return void + */ + public static function resolveRunnerUsing($resolver) + { + static::$runnerResolver = $resolver; + } + + /** + * Runs the test suite. + * + * @return void + */ + public function run(): void + { + (new PhpHandler)->handle($this->options->configuration()->php()); + + $this->forEachProcess(function () { + ParallelTesting::callSetUpProcessCallbacks(); + }); + + try { + $this->runner->run(); + } finally { + $this->forEachProcess(function () { + ParallelTesting::callTearDownProcessCallbacks(); + }); + } + } + + /** + * Returns the highest exit code encountered throughout the course of test execution. + * + * @return int + */ + public function getExitCode(): int + { + return $this->runner->getExitCode(); + } + + /** + * Apply the given callback for each process. + * + * @param callable $callback + * @return void + */ + protected function forEachProcess($callback) + { + collect(range(1, $this->options->processes()))->each(function ($token) use ($callback) { + tap($this->createApplication(), function ($app) use ($callback, $token) { + ParallelTesting::resolveTokenUsing(function () use ($token) { + return $token; + }); + + $callback($app); + })->flush(); + }); + } + + /** + * Creates the application. + * + * @return \Illuminate\Contracts\Foundation\Application + * + * @throws \RuntimeException + */ + protected function createApplication() + { + $applicationResolver = static::$applicationResolver ?: function () { + if (trait_exists(\Tests\CreatesApplication::class)) { + $applicationCreator = new class + { + use \Tests\CreatesApplication; + }; + + return $applicationCreator->createApplication(); + } elseif (file_exists(getcwd().'/bootstrap/app.php')) { + $app = require getcwd().'/bootstrap/app.php'; + + $app->make(Kernel::class)->bootstrap(); + + return $app; + } + + throw new RuntimeException('Parallel Runner unable to resolve application.'); + }; + + return call_user_func($applicationResolver); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelTesting.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelTesting.php new file mode 100644 index 0000000..f8bf993 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelTesting.php @@ -0,0 +1,291 @@ +container = $container; + } + + /** + * Set a callback that should be used when resolving options. + * + * @param \Closure|null $callback + * @return void + */ + public function resolveOptionsUsing($resolver) + { + $this->optionsResolver = $resolver; + } + + /** + * Set a callback that should be used when resolving the unique process token. + * + * @param \Closure|null $callback + * @return void + */ + public function resolveTokenUsing($resolver) + { + $this->tokenResolver = $resolver; + } + + /** + * Register a "setUp" process callback. + * + * @param callable $callback + * @return void + */ + public function setUpProcess($callback) + { + $this->setUpProcessCallbacks[] = $callback; + } + + /** + * Register a "setUp" test case callback. + * + * @param callable $callback + * @return void + */ + public function setUpTestCase($callback) + { + $this->setUpTestCaseCallbacks[] = $callback; + } + + /** + * Register a "setUp" test database callback. + * + * @param callable $callback + * @return void + */ + public function setUpTestDatabase($callback) + { + $this->setUpTestDatabaseCallbacks[] = $callback; + } + + /** + * Register a "tearDown" process callback. + * + * @param callable $callback + * @return void + */ + public function tearDownProcess($callback) + { + $this->tearDownProcessCallbacks[] = $callback; + } + + /** + * Register a "tearDown" test case callback. + * + * @param callable $callback + * @return void + */ + public function tearDownTestCase($callback) + { + $this->tearDownTestCaseCallbacks[] = $callback; + } + + /** + * Call all of the "setUp" process callbacks. + * + * @return void + */ + public function callSetUpProcessCallbacks() + { + $this->whenRunningInParallel(function () { + foreach ($this->setUpProcessCallbacks as $callback) { + $this->container->call($callback, [ + 'token' => $this->token(), + ]); + } + }); + } + + /** + * Call all of the "setUp" test case callbacks. + * + * @param \Illuminate\Foundation\Testing\TestCase $testCase + * @return void + */ + public function callSetUpTestCaseCallbacks($testCase) + { + $this->whenRunningInParallel(function () use ($testCase) { + foreach ($this->setUpTestCaseCallbacks as $callback) { + $this->container->call($callback, [ + 'testCase' => $testCase, + 'token' => $this->token(), + ]); + } + }); + } + + /** + * Call all of the "setUp" test database callbacks. + * + * @param string $database + * @return void + */ + public function callSetUpTestDatabaseCallbacks($database) + { + $this->whenRunningInParallel(function () use ($database) { + foreach ($this->setUpTestDatabaseCallbacks as $callback) { + $this->container->call($callback, [ + 'database' => $database, + 'token' => $this->token(), + ]); + } + }); + } + + /** + * Call all of the "tearDown" process callbacks. + * + * @return void + */ + public function callTearDownProcessCallbacks() + { + $this->whenRunningInParallel(function () { + foreach ($this->tearDownProcessCallbacks as $callback) { + $this->container->call($callback, [ + 'token' => $this->token(), + ]); + } + }); + } + + /** + * Call all of the "tearDown" test case callbacks. + * + * @param \Illuminate\Foundation\Testing\TestCase $testCase + * @return void + */ + public function callTearDownTestCaseCallbacks($testCase) + { + $this->whenRunningInParallel(function () use ($testCase) { + foreach ($this->tearDownTestCaseCallbacks as $callback) { + $this->container->call($callback, [ + 'testCase' => $testCase, + 'token' => $this->token(), + ]); + } + }); + } + + /** + * Get a parallel testing option. + * + * @param string $option + * @return mixed + */ + public function option($option) + { + $optionsResolver = $this->optionsResolver ?: function ($option) { + $option = 'LARAVEL_PARALLEL_TESTING_'.Str::upper($option); + + return $_SERVER[$option] ?? false; + }; + + return call_user_func($optionsResolver, $option); + } + + /** + * Gets a unique test token. + * + * @return string|false + */ + public function token() + { + return $token = $this->tokenResolver + ? call_user_func($this->tokenResolver) + : ($_SERVER['TEST_TOKEN'] ?? false); + } + + /** + * Apply the callback if tests are running in parallel. + * + * @param callable $callback + * @return void + */ + protected function whenRunningInParallel($callback) + { + if ($this->inParallel()) { + $callback(); + } + } + + /** + * Indicates if the current tests are been run in parallel. + * + * @return bool + */ + protected function inParallel() + { + return ! empty($_SERVER['LARAVEL_PARALLEL_TESTING']) && $this->token(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelTestingServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelTestingServiceProvider.php new file mode 100644 index 0000000..20b900d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/ParallelTestingServiceProvider.php @@ -0,0 +1,38 @@ +app->runningInConsole()) { + $this->bootTestDatabase(); + } + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + if ($this->app->runningInConsole()) { + $this->app->singleton(ParallelTesting::class, function () { + return new ParallelTesting($this->app); + }); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/PendingCommand.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/PendingCommand.php new file mode 100644 index 0000000..8701086 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/PendingCommand.php @@ -0,0 +1,415 @@ +app = $app; + $this->test = $test; + $this->command = $command; + $this->parameters = $parameters; + } + + /** + * Specify an expected question that will be asked when the command runs. + * + * @param string $question + * @param string|bool $answer + * @return $this + */ + public function expectsQuestion($question, $answer) + { + $this->test->expectedQuestions[] = [$question, $answer]; + + return $this; + } + + /** + * Specify an expected confirmation question that will be asked when the command runs. + * + * @param string $question + * @param string $answer + * @return $this + */ + public function expectsConfirmation($question, $answer = 'no') + { + return $this->expectsQuestion($question, strtolower($answer) === 'yes'); + } + + /** + * Specify an expected choice question with expected answers that will be asked/shown when the command runs. + * + * @param string $question + * @param string|array $answer + * @param array $answers + * @param bool $strict + * @return $this + */ + public function expectsChoice($question, $answer, $answers, $strict = false) + { + $this->test->expectedChoices[$question] = [ + 'expected' => $answers, + 'strict' => $strict, + ]; + + return $this->expectsQuestion($question, $answer); + } + + /** + * Specify output that should be printed when the command runs. + * + * @param string $output + * @return $this + */ + public function expectsOutput($output) + { + $this->test->expectedOutput[] = $output; + + return $this; + } + + /** + * Specify output that should never be printed when the command runs. + * + * @param string $output + * @return $this + */ + public function doesntExpectOutput($output) + { + $this->test->unexpectedOutput[$output] = false; + + return $this; + } + + /** + * Specify a table that should be printed when the command runs. + * + * @param array $headers + * @param \Illuminate\Contracts\Support\Arrayable|array $rows + * @param string $tableStyle + * @param array $columnStyles + * @return $this + */ + public function expectsTable($headers, $rows, $tableStyle = 'default', array $columnStyles = []) + { + $table = (new Table($output = new BufferedOutput)) + ->setHeaders((array) $headers) + ->setRows($rows instanceof Arrayable ? $rows->toArray() : $rows) + ->setStyle($tableStyle); + + foreach ($columnStyles as $columnIndex => $columnStyle) { + $table->setColumnStyle($columnIndex, $columnStyle); + } + + $table->render(); + + $lines = array_filter( + explode(PHP_EOL, $output->fetch()) + ); + + foreach ($lines as $line) { + $this->expectsOutput($line); + } + + return $this; + } + + /** + * Assert that the command has the given exit code. + * + * @param int $exitCode + * @return $this + */ + public function assertExitCode($exitCode) + { + $this->expectedExitCode = $exitCode; + + return $this; + } + + /** + * Assert that the command does not have the given exit code. + * + * @param int $exitCode + * @return $this + */ + public function assertNotExitCode($exitCode) + { + $this->unexpectedExitCode = $exitCode; + + return $this; + } + + /** + * Assert that the command has the success exit code. + * + * @return $this + */ + public function assertSuccessful() + { + return $this->assertExitCode(Command::SUCCESS); + } + + /** + * Assert that the command does not have the success exit code. + * + * @return $this + */ + public function assertFailed() + { + return $this->assertNotExitCode(Command::SUCCESS); + } + + /** + * Execute the command. + * + * @return int + */ + public function execute() + { + return $this->run(); + } + + /** + * Execute the command. + * + * @return int + * + * @throws \Mockery\Exception\NoMatchingExpectationException + */ + public function run() + { + $this->hasExecuted = true; + + $mock = $this->mockConsoleOutput(); + + try { + $exitCode = $this->app->make(Kernel::class)->call($this->command, $this->parameters, $mock); + } catch (NoMatchingExpectationException $e) { + if ($e->getMethodName() === 'askQuestion') { + $this->test->fail('Unexpected question "'.$e->getActualArguments()[0]->getQuestion().'" was asked.'); + } + + throw $e; + } + + if ($this->expectedExitCode !== null) { + $this->test->assertEquals( + $this->expectedExitCode, $exitCode, + "Expected status code {$this->expectedExitCode} but received {$exitCode}." + ); + } elseif (! is_null($this->unexpectedExitCode)) { + $this->test->assertNotEquals( + $this->unexpectedExitCode, $exitCode, + "Unexpected status code {$this->unexpectedExitCode} was received." + ); + } + + $this->verifyExpectations(); + $this->flushExpectations(); + + return $exitCode; + } + + /** + * Determine if expected questions / choices / outputs are fulfilled. + * + * @return void + */ + protected function verifyExpectations() + { + if (count($this->test->expectedQuestions)) { + $this->test->fail('Question "'.Arr::first($this->test->expectedQuestions)[0].'" was not asked.'); + } + + if (count($this->test->expectedChoices) > 0) { + foreach ($this->test->expectedChoices as $question => $answers) { + $assertion = $answers['strict'] ? 'assertEquals' : 'assertEqualsCanonicalizing'; + + $this->test->{$assertion}( + $answers['expected'], + $answers['actual'], + 'Question "'.$question.'" has different options.' + ); + } + } + + if (count($this->test->expectedOutput)) { + $this->test->fail('Output "'.Arr::first($this->test->expectedOutput).'" was not printed.'); + } + + if ($output = array_search(true, $this->test->unexpectedOutput)) { + $this->test->fail('Output "'.$output.'" was printed.'); + } + } + + /** + * Mock the application's console output. + * + * @return \Mockery\MockInterface + */ + protected function mockConsoleOutput() + { + $mock = Mockery::mock(OutputStyle::class.'[askQuestion]', [ + (new ArrayInput($this->parameters)), $this->createABufferedOutputMock(), + ]); + + foreach ($this->test->expectedQuestions as $i => $question) { + $mock->shouldReceive('askQuestion') + ->once() + ->ordered() + ->with(Mockery::on(function ($argument) use ($question) { + if (isset($this->test->expectedChoices[$question[0]])) { + $this->test->expectedChoices[$question[0]]['actual'] = $argument->getAutocompleterValues(); + } + + return $argument->getQuestion() == $question[0]; + })) + ->andReturnUsing(function () use ($question, $i) { + unset($this->test->expectedQuestions[$i]); + + return $question[1]; + }); + } + + $this->app->bind(OutputStyle::class, function () use ($mock) { + return $mock; + }); + + return $mock; + } + + /** + * Create a mock for the buffered output. + * + * @return \Mockery\MockInterface + */ + private function createABufferedOutputMock() + { + $mock = Mockery::mock(BufferedOutput::class.'[doWrite]') + ->shouldAllowMockingProtectedMethods() + ->shouldIgnoreMissing(); + + foreach ($this->test->expectedOutput as $i => $output) { + $mock->shouldReceive('doWrite') + ->once() + ->ordered() + ->with($output, Mockery::any()) + ->andReturnUsing(function () use ($i) { + unset($this->test->expectedOutput[$i]); + }); + } + + foreach ($this->test->unexpectedOutput as $output => $displayed) { + $mock->shouldReceive('doWrite') + ->ordered() + ->with($output, Mockery::any()) + ->andReturnUsing(function () use ($output) { + $this->test->unexpectedOutput[$output] = true; + }); + } + + return $mock; + } + + /** + * Flush the expectations from the test case. + * + * @return void + */ + protected function flushExpectations() + { + $this->test->expectedOutput = []; + $this->test->unexpectedOutput = []; + $this->test->expectedTables = []; + $this->test->expectedQuestions = []; + $this->test->expectedChoices = []; + } + + /** + * Handle the object's destruction. + * + * @return void + */ + public function __destruct() + { + if ($this->hasExecuted) { + return; + } + + $this->run(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestComponent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestComponent.php new file mode 100644 index 0000000..21663aa --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestComponent.php @@ -0,0 +1,167 @@ +component = $component; + + $this->rendered = $view->render(); + } + + /** + * Assert that the given string is contained within the rendered component. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertSee($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringContainsString((string) $value, $this->rendered); + + return $this; + } + + /** + * Assert that the given strings are contained in order within the rendered component. + * + * @param array $values + * @param bool $escape + * @return $this + */ + public function assertSeeInOrder(array $values, $escape = true) + { + $values = $escape ? array_map('e', ($values)) : $values; + + PHPUnit::assertThat($values, new SeeInOrder($this->rendered)); + + return $this; + } + + /** + * Assert that the given string is contained within the rendered component text. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertSeeText($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringContainsString((string) $value, strip_tags($this->rendered)); + + return $this; + } + + /** + * Assert that the given strings are contained in order within the rendered component text. + * + * @param array $values + * @param bool $escape + * @return $this + */ + public function assertSeeTextInOrder(array $values, $escape = true) + { + $values = $escape ? array_map('e', ($values)) : $values; + + PHPUnit::assertThat($values, new SeeInOrder(strip_tags($this->rendered))); + + return $this; + } + + /** + * Assert that the given string is not contained within the rendered component. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertDontSee($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringNotContainsString((string) $value, $this->rendered); + + return $this; + } + + /** + * Assert that the given string is not contained within the rendered component text. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertDontSeeText($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringNotContainsString((string) $value, strip_tags($this->rendered)); + + return $this; + } + + /** + * Get the string contents of the rendered component. + * + * @return string + */ + public function __toString() + { + return $this->rendered; + } + + /** + * Dynamically access properties on the underlying component. + * + * @param string $attribute + * @return mixed + */ + public function __get($attribute) + { + return $this->component->{$attribute}; + } + + /** + * Dynamically call methods on the underlying component. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->component->{$method}(...$parameters); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php new file mode 100644 index 0000000..b89af26 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php @@ -0,0 +1,1614 @@ +baseResponse = $response; + $this->exceptions = new Collection; + } + + /** + * Create a new TestResponse from another response. + * + * @param \Illuminate\Http\Response $response + * @return static + */ + public static function fromBaseResponse($response) + { + return new static($response); + } + + /** + * Assert that the response has a successful status code. + * + * @return $this + */ + public function assertSuccessful() + { + PHPUnit::assertTrue( + $this->isSuccessful(), + $this->statusMessageWithDetails('>=200, <300', $this->getStatusCode()) + ); + + return $this; + } + + /** + * Assert that the response has a 200 status code. + * + * @return $this + */ + public function assertOk() + { + return $this->assertStatus(200); + } + + /** + * Assert that the response has a 201 status code. + * + * @return $this + */ + public function assertCreated() + { + return $this->assertStatus(201); + } + + /** + * Assert that the response has the given status code and no content. + * + * @param int $status + * @return $this + */ + public function assertNoContent($status = 204) + { + $this->assertStatus($status); + + PHPUnit::assertEmpty($this->getContent(), 'Response content is not empty.'); + + return $this; + } + + /** + * Assert that the response has a not found status code. + * + * @return $this + */ + public function assertNotFound() + { + return $this->assertStatus(404); + } + + /** + * Assert that the response has a forbidden status code. + * + * @return $this + */ + public function assertForbidden() + { + return $this->assertStatus(403); + } + + /** + * Assert that the response has an unauthorized status code. + * + * @return $this + */ + public function assertUnauthorized() + { + return $this->assertStatus(401); + } + + /** + * Assert that the response has a 422 status code. + * + * @return $this + */ + public function assertUnprocessable() + { + return $this->assertStatus(422); + } + + /** + * Assert that the response has the given status code. + * + * @param int $status + * @return $this + */ + public function assertStatus($status) + { + $message = $this->statusMessageWithDetails($status, $actual = $this->getStatusCode()); + + PHPUnit::assertSame($actual, $status, $message); + + return $this; + } + + /** + * Get an assertion message for a status assertion containing extra details when available. + * + * @param string|int $expected + * @param string|int $actual + * @return string + */ + protected function statusMessageWithDetails($expected, $actual) + { + $lastException = $this->exceptions->last(); + + if ($lastException) { + return $this->statusMessageWithException($expected, $actual, $lastException); + } + + if ($this->baseResponse instanceof RedirectResponse) { + $session = $this->baseResponse->getSession(); + + if (! is_null($session) && $session->has('errors')) { + return $this->statusMessageWithErrors($expected, $actual, $session->get('errors')->all()); + } + } + + if ($this->baseResponse->headers->get('Content-Type') === 'application/json') { + $testJson = new AssertableJsonString($this->getContent()); + + if (isset($testJson['errors'])) { + return $this->statusMessageWithErrors($expected, $actual, $testJson->json()); + } + } + + return "Expected response status code [{$expected}] but received {$actual}."; + } + + /** + * Get an assertion message for a status assertion that has an unexpected exception. + * + * @param string|int $expected + * @param string|int $actual + * @param \Throwable $exception + * @return string + */ + protected function statusMessageWithException($expected, $actual, $exception) + { + $exception = (string) $exception; + + return <<baseResponse->headers->get('Content-Type') === 'application/json' + ? json_encode($errors, JSON_PRETTY_PRINT) + : implode(PHP_EOL, Arr::flatten($errors)); + + return <<isRedirect(), + $this->statusMessageWithDetails('201, 301, 302, 303, 307, 308', $this->getStatusCode()), + ); + + if (! is_null($uri)) { + $this->assertLocation($uri); + } + + return $this; + } + + /** + * Assert whether the response is redirecting to a URI that contains the given URI. + * + * @param string $uri + * @return $this + */ + public function assertRedirectContains($uri) + { + PHPUnit::assertTrue( + $this->isRedirect(), + $this->statusMessageWithDetails('201, 301, 302, 303, 307, 308', $this->getStatusCode()), + ); + + PHPUnit::assertTrue( + Str::contains($this->headers->get('Location'), $uri), 'Redirect location ['.$this->headers->get('Location').'] does not contain ['.$uri.'].' + ); + + return $this; + } + + /** + * Assert whether the response is redirecting to a given signed route. + * + * @param string|null $name + * @param mixed $parameters + * @return $this + */ + public function assertRedirectToSignedRoute($name = null, $parameters = []) + { + if (! is_null($name)) { + $uri = route($name, $parameters); + } + + PHPUnit::assertTrue( + $this->isRedirect(), + $this->statusMessageWithDetails('201, 301, 302, 303, 307, 308', $this->getStatusCode()), + ); + + $request = Request::create($this->headers->get('Location')); + + PHPUnit::assertTrue( + $request->hasValidSignature(), 'The response is not a redirect to a signed route.' + ); + + if (! is_null($name)) { + $expectedUri = rtrim($request->fullUrlWithQuery([ + 'signature' => null, + 'expires' => null, + ]), '?'); + + PHPUnit::assertEquals( + app('url')->to($uri), $expectedUri + ); + } + + return $this; + } + + /** + * Asserts that the response contains the given header and equals the optional value. + * + * @param string $headerName + * @param mixed $value + * @return $this + */ + public function assertHeader($headerName, $value = null) + { + PHPUnit::assertTrue( + $this->headers->has($headerName), "Header [{$headerName}] not present on response." + ); + + $actual = $this->headers->get($headerName); + + if (! is_null($value)) { + PHPUnit::assertEquals( + $value, $this->headers->get($headerName), + "Header [{$headerName}] was found, but value [{$actual}] does not match [{$value}]." + ); + } + + return $this; + } + + /** + * Asserts that the response does not contain the given header. + * + * @param string $headerName + * @return $this + */ + public function assertHeaderMissing($headerName) + { + PHPUnit::assertFalse( + $this->headers->has($headerName), "Unexpected header [{$headerName}] is present on response." + ); + + return $this; + } + + /** + * Assert that the current location header matches the given URI. + * + * @param string $uri + * @return $this + */ + public function assertLocation($uri) + { + PHPUnit::assertEquals( + app('url')->to($uri), app('url')->to($this->headers->get('Location')) + ); + + return $this; + } + + /** + * Assert that the response offers a file download. + * + * @param string|null $filename + * @return $this + */ + public function assertDownload($filename = null) + { + $contentDisposition = explode(';', $this->headers->get('content-disposition')); + + if (trim($contentDisposition[0]) !== 'attachment') { + PHPUnit::fail( + 'Response does not offer a file download.'.PHP_EOL. + 'Disposition ['.trim($contentDisposition[0]).'] found in header, [attachment] expected.' + ); + } + + if (! is_null($filename)) { + if (isset($contentDisposition[1]) && + trim(explode('=', $contentDisposition[1])[0]) !== 'filename') { + PHPUnit::fail( + 'Unsupported Content-Disposition header provided.'.PHP_EOL. + 'Disposition ['.trim(explode('=', $contentDisposition[1])[0]).'] found in header, [filename] expected.' + ); + } + + $message = "Expected file [{$filename}] is not present in Content-Disposition header."; + + if (! isset($contentDisposition[1])) { + PHPUnit::fail($message); + } else { + PHPUnit::assertSame( + $filename, + isset(explode('=', $contentDisposition[1])[1]) + ? trim(explode('=', $contentDisposition[1])[1], " \"'") + : '', + $message + ); + + return $this; + } + } else { + PHPUnit::assertTrue(true); + + return $this; + } + } + + /** + * Asserts that the response contains the given cookie and equals the optional value. + * + * @param string $cookieName + * @param mixed $value + * @return $this + */ + public function assertPlainCookie($cookieName, $value = null) + { + $this->assertCookie($cookieName, $value, false); + + return $this; + } + + /** + * Asserts that the response contains the given cookie and equals the optional value. + * + * @param string $cookieName + * @param mixed $value + * @param bool $encrypted + * @param bool $unserialize + * @return $this + */ + public function assertCookie($cookieName, $value = null, $encrypted = true, $unserialize = false) + { + PHPUnit::assertNotNull( + $cookie = $this->getCookie($cookieName), + "Cookie [{$cookieName}] not present on response." + ); + + if (! $cookie || is_null($value)) { + return $this; + } + + $cookieValue = $cookie->getValue(); + + $actual = $encrypted + ? CookieValuePrefix::remove(app('encrypter')->decrypt($cookieValue, $unserialize)) + : $cookieValue; + + PHPUnit::assertEquals( + $value, $actual, + "Cookie [{$cookieName}] was found, but value [{$actual}] does not match [{$value}]." + ); + + return $this; + } + + /** + * Asserts that the response contains the given cookie and is expired. + * + * @param string $cookieName + * @return $this + */ + public function assertCookieExpired($cookieName) + { + PHPUnit::assertNotNull( + $cookie = $this->getCookie($cookieName), + "Cookie [{$cookieName}] not present on response." + ); + + $expiresAt = Carbon::createFromTimestamp($cookie->getExpiresTime()); + + PHPUnit::assertTrue( + 0 !== $cookie->getExpiresTime() && $expiresAt->lessThan(Carbon::now()), + "Cookie [{$cookieName}] is not expired, it expires at [{$expiresAt}]." + ); + + return $this; + } + + /** + * Asserts that the response contains the given cookie and is not expired. + * + * @param string $cookieName + * @return $this + */ + public function assertCookieNotExpired($cookieName) + { + PHPUnit::assertNotNull( + $cookie = $this->getCookie($cookieName), + "Cookie [{$cookieName}] not present on response." + ); + + $expiresAt = Carbon::createFromTimestamp($cookie->getExpiresTime()); + + PHPUnit::assertTrue( + 0 === $cookie->getExpiresTime() || $expiresAt->greaterThan(Carbon::now()), + "Cookie [{$cookieName}] is expired, it expired at [{$expiresAt}]." + ); + + return $this; + } + + /** + * Asserts that the response does not contain the given cookie. + * + * @param string $cookieName + * @return $this + */ + public function assertCookieMissing($cookieName) + { + PHPUnit::assertNull( + $this->getCookie($cookieName), + "Cookie [{$cookieName}] is present on response." + ); + + return $this; + } + + /** + * Get the given cookie from the response. + * + * @param string $cookieName + * @return \Symfony\Component\HttpFoundation\Cookie|null + */ + public function getCookie($cookieName) + { + foreach ($this->headers->getCookies() as $cookie) { + if ($cookie->getName() === $cookieName) { + return $cookie; + } + } + } + + /** + * Assert that the given string or array of strings are contained within the response. + * + * @param string|array $value + * @param bool $escape + * @return $this + */ + public function assertSee($value, $escape = true) + { + $value = Arr::wrap($value); + + $values = $escape ? array_map('e', ($value)) : $value; + + foreach ($values as $value) { + PHPUnit::assertStringContainsString((string) $value, $this->getContent()); + } + + return $this; + } + + /** + * Assert that the given strings are contained in order within the response. + * + * @param array $values + * @param bool $escape + * @return $this + */ + public function assertSeeInOrder(array $values, $escape = true) + { + $values = $escape ? array_map('e', ($values)) : $values; + + PHPUnit::assertThat($values, new SeeInOrder($this->getContent())); + + return $this; + } + + /** + * Assert that the given string or array of strings are contained within the response text. + * + * @param string|array $value + * @param bool $escape + * @return $this + */ + public function assertSeeText($value, $escape = true) + { + $value = Arr::wrap($value); + + $values = $escape ? array_map('e', ($value)) : $value; + + tap(strip_tags($this->getContent()), function ($content) use ($values) { + foreach ($values as $value) { + PHPUnit::assertStringContainsString((string) $value, $content); + } + }); + + return $this; + } + + /** + * Assert that the given strings are contained in order within the response text. + * + * @param array $values + * @param bool $escape + * @return $this + */ + public function assertSeeTextInOrder(array $values, $escape = true) + { + $values = $escape ? array_map('e', ($values)) : $values; + + PHPUnit::assertThat($values, new SeeInOrder(strip_tags($this->getContent()))); + + return $this; + } + + /** + * Assert that the given string or array of strings are not contained within the response. + * + * @param string|array $value + * @param bool $escape + * @return $this + */ + public function assertDontSee($value, $escape = true) + { + $value = Arr::wrap($value); + + $values = $escape ? array_map('e', ($value)) : $value; + + foreach ($values as $value) { + PHPUnit::assertStringNotContainsString((string) $value, $this->getContent()); + } + + return $this; + } + + /** + * Assert that the given string or array of strings are not contained within the response text. + * + * @param string|array $value + * @param bool $escape + * @return $this + */ + public function assertDontSeeText($value, $escape = true) + { + $value = Arr::wrap($value); + + $values = $escape ? array_map('e', ($value)) : $value; + + tap(strip_tags($this->getContent()), function ($content) use ($values) { + foreach ($values as $value) { + PHPUnit::assertStringNotContainsString((string) $value, $content); + } + }); + + return $this; + } + + /** + * Assert that the response is a superset of the given JSON. + * + * @param array|callable $value + * @param bool $strict + * @return $this + */ + public function assertJson($value, $strict = false) + { + $json = $this->decodeResponseJson(); + + if (is_array($value)) { + $json->assertSubset($value, $strict); + } else { + $assert = AssertableJson::fromAssertableJsonString($json); + + $value($assert); + + if (Arr::isAssoc($assert->toArray())) { + $assert->interacted(); + } + } + + return $this; + } + + /** + * Assert that the expected value and type exists at the given path in the response. + * + * @param string $path + * @param mixed $expect + * @return $this + */ + public function assertJsonPath($path, $expect) + { + $this->decodeResponseJson()->assertPath($path, $expect); + + return $this; + } + + /** + * Assert that the response has the exact given JSON. + * + * @param array $data + * @return $this + */ + public function assertExactJson(array $data) + { + $this->decodeResponseJson()->assertExact($data); + + return $this; + } + + /** + * Assert that the response has the similar JSON as given. + * + * @param array $data + * @return $this + */ + public function assertSimilarJson(array $data) + { + $this->decodeResponseJson()->assertSimilar($data); + + return $this; + } + + /** + * Assert that the response contains the given JSON fragment. + * + * @param array $data + * @return $this + */ + public function assertJsonFragment(array $data) + { + $this->decodeResponseJson()->assertFragment($data); + + return $this; + } + + /** + * Assert that the response does not contain the given JSON fragment. + * + * @param array $data + * @param bool $exact + * @return $this + */ + public function assertJsonMissing(array $data, $exact = false) + { + $this->decodeResponseJson()->assertMissing($data, $exact); + + return $this; + } + + /** + * Assert that the response does not contain the exact JSON fragment. + * + * @param array $data + * @return $this + */ + public function assertJsonMissingExact(array $data) + { + $this->decodeResponseJson()->assertMissingExact($data); + + return $this; + } + + /** + * Assert that the response has a given JSON structure. + * + * @param array|null $structure + * @param array|null $responseData + * @return $this + */ + public function assertJsonStructure(array $structure = null, $responseData = null) + { + $this->decodeResponseJson()->assertStructure($structure, $responseData); + + return $this; + } + + /** + * Assert that the response JSON has the expected count of items at the given key. + * + * @param int $count + * @param string|null $key + * @return $this + */ + public function assertJsonCount(int $count, $key = null) + { + $this->decodeResponseJson()->assertCount($count, $key); + + return $this; + } + + /** + * Assert that the response has the given JSON validation errors. + * + * @param string|array $errors + * @param string $responseKey + * @return $this + */ + public function assertJsonValidationErrors($errors, $responseKey = 'errors') + { + $errors = Arr::wrap($errors); + + PHPUnit::assertNotEmpty($errors, 'No validation errors were provided.'); + + $jsonErrors = Arr::get($this->json(), $responseKey) ?? []; + + $errorMessage = $jsonErrors + ? 'Response has the following JSON validation errors:'. + PHP_EOL.PHP_EOL.json_encode($jsonErrors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).PHP_EOL + : 'Response does not have JSON validation errors.'; + + foreach ($errors as $key => $value) { + if (is_int($key)) { + $this->assertJsonValidationErrorFor($value, $responseKey); + + continue; + } + + $this->assertJsonValidationErrorFor($key, $responseKey); + + foreach (Arr::wrap($value) as $expectedMessage) { + $errorMissing = true; + + foreach (Arr::wrap($jsonErrors[$key]) as $jsonErrorMessage) { + if (Str::contains($jsonErrorMessage, $expectedMessage)) { + $errorMissing = false; + + break; + } + } + } + + if ($errorMissing) { + PHPUnit::fail( + "Failed to find a validation error in the response for key and message: '$key' => '$expectedMessage'".PHP_EOL.PHP_EOL.$errorMessage + ); + } + } + + return $this; + } + + /** + * Assert the response has any JSON validation errors for the given key. + * + * @param string $key + * @param string $responseKey + * @return $this + */ + public function assertJsonValidationErrorFor($key, $responseKey = 'errors') + { + $jsonErrors = Arr::get($this->json(), $responseKey) ?? []; + + $errorMessage = $jsonErrors + ? 'Response has the following JSON validation errors:'. + PHP_EOL.PHP_EOL.json_encode($jsonErrors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).PHP_EOL + : 'Response does not have JSON validation errors.'; + + PHPUnit::assertArrayHasKey( + $key, + $jsonErrors, + "Failed to find a validation error in the response for key: '{$key}'".PHP_EOL.PHP_EOL.$errorMessage + ); + + return $this; + } + + /** + * Assert that the response has no JSON validation errors for the given keys. + * + * @param string|array|null $keys + * @param string $responseKey + * @return $this + */ + public function assertJsonMissingValidationErrors($keys = null, $responseKey = 'errors') + { + if ($this->getContent() === '') { + PHPUnit::assertTrue(true); + + return $this; + } + + $json = $this->json(); + + if (! Arr::has($json, $responseKey)) { + PHPUnit::assertTrue(true); + + return $this; + } + + $errors = Arr::get($json, $responseKey, []); + + if (is_null($keys) && count($errors) > 0) { + PHPUnit::fail( + 'Response has unexpected validation errors: '.PHP_EOL.PHP_EOL. + json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) + ); + } + + foreach (Arr::wrap($keys) as $key) { + PHPUnit::assertFalse( + isset($errors[$key]), + "Found unexpected validation error for key: '{$key}'" + ); + } + + return $this; + } + + /** + * Validate and return the decoded response JSON. + * + * @return \Illuminate\Testing\AssertableJsonString + * + * @throws \Throwable + */ + public function decodeResponseJson() + { + $testJson = new AssertableJsonString($this->getContent()); + + $decodedResponse = $testJson->json(); + + if (is_null($decodedResponse) || $decodedResponse === false) { + if ($this->exception) { + throw $this->exception; + } else { + PHPUnit::fail('Invalid JSON was returned from the route.'); + } + } + + return $testJson; + } + + /** + * Validate and return the decoded response JSON. + * + * @param string|null $key + * @return mixed + */ + public function json($key = null) + { + return $this->decodeResponseJson()->json($key); + } + + /** + * Assert that the response view equals the given value. + * + * @param string $value + * @return $this + */ + public function assertViewIs($value) + { + $this->ensureResponseHasView(); + + PHPUnit::assertEquals($value, $this->original->name()); + + return $this; + } + + /** + * Assert that the response view has a given piece of bound data. + * + * @param string|array $key + * @param mixed $value + * @return $this + */ + public function assertViewHas($key, $value = null) + { + if (is_array($key)) { + return $this->assertViewHasAll($key); + } + + $this->ensureResponseHasView(); + + if (is_null($value)) { + PHPUnit::assertTrue(Arr::has($this->original->gatherData(), $key)); + } elseif ($value instanceof Closure) { + PHPUnit::assertTrue($value(Arr::get($this->original->gatherData(), $key))); + } elseif ($value instanceof Model) { + PHPUnit::assertTrue($value->is(Arr::get($this->original->gatherData(), $key))); + } else { + PHPUnit::assertEquals($value, Arr::get($this->original->gatherData(), $key)); + } + + return $this; + } + + /** + * Assert that the response view has a given list of bound data. + * + * @param array $bindings + * @return $this + */ + public function assertViewHasAll(array $bindings) + { + foreach ($bindings as $key => $value) { + if (is_int($key)) { + $this->assertViewHas($value); + } else { + $this->assertViewHas($key, $value); + } + } + + return $this; + } + + /** + * Get a piece of data from the original view. + * + * @param string $key + * @return mixed + */ + public function viewData($key) + { + $this->ensureResponseHasView(); + + return $this->original->gatherData()[$key]; + } + + /** + * Assert that the response view is missing a piece of bound data. + * + * @param string $key + * @return $this + */ + public function assertViewMissing($key) + { + $this->ensureResponseHasView(); + + PHPUnit::assertFalse(Arr::has($this->original->gatherData(), $key)); + + return $this; + } + + /** + * Ensure that the response has a view as its original content. + * + * @return $this + */ + protected function ensureResponseHasView() + { + if (! $this->responseHasView()) { + return PHPUnit::fail('The response is not a view.'); + } + + return $this; + } + + /** + * Determine if the original response is a view. + * + * @return bool + */ + protected function responseHasView() + { + return isset($this->original) && $this->original instanceof View; + } + + /** + * Assert that the given keys do not have validation errors. + * + * @param string|array|null $keys + * @param string $errorBag + * @param string $responseKey + * @return $this + */ + public function assertValid($keys = null, $errorBag = 'default', $responseKey = 'errors') + { + if ($this->baseResponse->headers->get('Content-Type') === 'application/json') { + return $this->assertJsonMissingValidationErrors($keys, $responseKey); + } + + if ($this->session()->get('errors')) { + $errors = $this->session()->get('errors')->getBag($errorBag)->getMessages(); + } else { + $errors = []; + } + + if (empty($errors)) { + PHPUnit::assertTrue(true); + + return $this; + } + + if (is_null($keys) && count($errors) > 0) { + PHPUnit::fail( + 'Response has unexpected validation errors: '.PHP_EOL.PHP_EOL. + json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) + ); + } + + foreach (Arr::wrap($keys) as $key) { + PHPUnit::assertFalse( + isset($errors[$key]), + "Found unexpected validation error for key: '{$key}'" + ); + } + + return $this; + } + + /** + * Assert that the response has the given validation errors. + * + * @param string|array|null $errors + * @param string $errorBag + * @param string $responseKey + * @return $this + */ + public function assertInvalid($errors = null, + $errorBag = 'default', + $responseKey = 'errors') + { + if ($this->baseResponse->headers->get('Content-Type') === 'application/json') { + return $this->assertJsonValidationErrors($errors, $responseKey); + } + + $this->assertSessionHas('errors'); + + $keys = (array) $errors; + + $sessionErrors = $this->session()->get('errors')->getBag($errorBag)->getMessages(); + + $errorMessage = $sessionErrors + ? 'Response has the following validation errors in the session:'. + PHP_EOL.PHP_EOL.json_encode($sessionErrors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).PHP_EOL + : 'Response does not have validation errors in the session.'; + + foreach (Arr::wrap($errors) as $key => $value) { + PHPUnit::assertArrayHasKey( + (is_int($key)) ? $value : $key, + $sessionErrors, + "Failed to find a validation error in session for key: '{$value}'".PHP_EOL.PHP_EOL.$errorMessage + ); + + if (! is_int($key)) { + $hasError = false; + + foreach (Arr::wrap($sessionErrors[$key]) as $sessionErrorMessage) { + if (Str::contains($sessionErrorMessage, $value)) { + $hasError = true; + + break; + } + } + + if (! $hasError) { + PHPUnit::fail( + "Failed to find a validation error for key and message: '$key' => '$value'".PHP_EOL.PHP_EOL.$errorMessage + ); + } + } + } + + return $this; + } + + /** + * Assert that the session has a given value. + * + * @param string|array $key + * @param mixed $value + * @return $this + */ + public function assertSessionHas($key, $value = null) + { + if (is_array($key)) { + return $this->assertSessionHasAll($key); + } + + if (is_null($value)) { + PHPUnit::assertTrue( + $this->session()->has($key), + "Session is missing expected key [{$key}]." + ); + } elseif ($value instanceof Closure) { + PHPUnit::assertTrue($value($this->session()->get($key))); + } else { + PHPUnit::assertEquals($value, $this->session()->get($key)); + } + + return $this; + } + + /** + * Assert that the session has a given list of values. + * + * @param array $bindings + * @return $this + */ + public function assertSessionHasAll(array $bindings) + { + foreach ($bindings as $key => $value) { + if (is_int($key)) { + $this->assertSessionHas($value); + } else { + $this->assertSessionHas($key, $value); + } + } + + return $this; + } + + /** + * Assert that the session has a given value in the flashed input array. + * + * @param string|array $key + * @param mixed $value + * @return $this + */ + public function assertSessionHasInput($key, $value = null) + { + if (is_array($key)) { + foreach ($key as $k => $v) { + if (is_int($k)) { + $this->assertSessionHasInput($v); + } else { + $this->assertSessionHasInput($k, $v); + } + } + + return $this; + } + + if (is_null($value)) { + PHPUnit::assertTrue( + $this->session()->hasOldInput($key), + "Session is missing expected key [{$key}]." + ); + } elseif ($value instanceof Closure) { + PHPUnit::assertTrue($value($this->session()->getOldInput($key))); + } else { + PHPUnit::assertEquals($value, $this->session()->getOldInput($key)); + } + + return $this; + } + + /** + * Assert that the session has the given errors. + * + * @param string|array $keys + * @param mixed $format + * @param string $errorBag + * @return $this + */ + public function assertSessionHasErrors($keys = [], $format = null, $errorBag = 'default') + { + $this->assertSessionHas('errors'); + + $keys = (array) $keys; + + $errors = $this->session()->get('errors')->getBag($errorBag); + + foreach ($keys as $key => $value) { + if (is_int($key)) { + PHPUnit::assertTrue($errors->has($value), "Session missing error: $value"); + } else { + PHPUnit::assertContains(is_bool($value) ? (string) $value : $value, $errors->get($key, $format)); + } + } + + return $this; + } + + /** + * Assert that the session is missing the given errors. + * + * @param string|array $keys + * @param string|null $format + * @param string $errorBag + * @return $this + */ + public function assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default') + { + $keys = (array) $keys; + + if (empty($keys)) { + return $this->assertSessionHasNoErrors(); + } + + if (is_null($this->session()->get('errors'))) { + PHPUnit::assertTrue(true); + + return $this; + } + + $errors = $this->session()->get('errors')->getBag($errorBag); + + foreach ($keys as $key => $value) { + if (is_int($key)) { + PHPUnit::assertFalse($errors->has($value), "Session has unexpected error: $value"); + } else { + PHPUnit::assertNotContains($value, $errors->get($key, $format)); + } + } + + return $this; + } + + /** + * Assert that the session has no errors. + * + * @return $this + */ + public function assertSessionHasNoErrors() + { + $hasErrors = $this->session()->has('errors'); + + $errors = $hasErrors ? $this->session()->get('errors')->all() : []; + + PHPUnit::assertFalse( + $hasErrors, + 'Session has unexpected errors: '.PHP_EOL.PHP_EOL. + json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) + ); + + return $this; + } + + /** + * Assert that the session has the given errors. + * + * @param string $errorBag + * @param string|array $keys + * @param mixed $format + * @return $this + */ + public function assertSessionHasErrorsIn($errorBag, $keys = [], $format = null) + { + return $this->assertSessionHasErrors($keys, $format, $errorBag); + } + + /** + * Assert that the session does not have a given key. + * + * @param string|array $key + * @return $this + */ + public function assertSessionMissing($key) + { + if (is_array($key)) { + foreach ($key as $value) { + $this->assertSessionMissing($value); + } + } else { + PHPUnit::assertFalse( + $this->session()->has($key), + "Session has unexpected key [{$key}]." + ); + } + + return $this; + } + + /** + * Get the current session store. + * + * @return \Illuminate\Session\Store + */ + protected function session() + { + return app('session.store'); + } + + /** + * Dump the content from the response and end the script. + * + * @return never + */ + public function dd() + { + $this->dump(); + + exit(1); + } + + /** + * Dump the headers from the response and end the script. + * + * @return never + */ + public function ddHeaders() + { + $this->dumpHeaders(); + + exit(1); + } + + /** + * Dump the session from the response and end the script. + * + * @param string|array $keys + * @return never + */ + public function ddSession($keys = []) + { + $this->dumpSession($keys); + + exit(1); + } + + /** + * Dump the content from the response. + * + * @return $this + */ + public function dump() + { + $content = $this->getContent(); + + $json = json_decode($content); + + if (json_last_error() === JSON_ERROR_NONE) { + $content = $json; + } + + dump($content); + + return $this; + } + + /** + * Dump the headers from the response. + * + * @return $this + */ + public function dumpHeaders() + { + dump($this->headers->all()); + + return $this; + } + + /** + * Dump the session from the response. + * + * @param string|array $keys + * @return $this + */ + public function dumpSession($keys = []) + { + $keys = (array) $keys; + + if (empty($keys)) { + dump($this->session()->all()); + } else { + dump($this->session()->only($keys)); + } + + return $this; + } + + /** + * Get the streamed content from the response. + * + * @return string + */ + public function streamedContent() + { + if (! is_null($this->streamedContent)) { + return $this->streamedContent; + } + + if (! $this->baseResponse instanceof StreamedResponse) { + PHPUnit::fail('The response is not a streamed response.'); + } + + ob_start(function (string $buffer): string { + $this->streamedContent .= $buffer; + + return ''; + }); + + $this->sendContent(); + + ob_end_clean(); + + return $this->streamedContent; + } + + /** + * Set the previous exceptions on the response. + * + * @param \Illuminate\Support\Collection $exceptions + * @return $this + */ + public function withExceptions(Collection $exceptions) + { + $this->exceptions = $exceptions; + + return $this; + } + + /** + * Dynamically access base response parameters. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->baseResponse->{$key}; + } + + /** + * Proxy isset() checks to the underlying base response. + * + * @param string $key + * @return mixed + */ + public function __isset($key) + { + return isset($this->baseResponse->{$key}); + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return $this->responseHasView() + ? isset($this->original->gatherData()[$offset]) + : isset($this->json()[$offset]); + } + + /** + * Get the value for a given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->responseHasView() + ? $this->viewData($offset) + : $this->json()[$offset]; + } + + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + * + * @throws \LogicException + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + throw new LogicException('Response data may not be mutated using array access.'); + } + + /** + * Unset the value at the given offset. + * + * @param string $offset + * @return void + * + * @throws \LogicException + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + throw new LogicException('Response data may not be mutated using array access.'); + } + + /** + * Handle dynamic calls into macros or pass missing methods to the base response. + * + * @param string $method + * @param array $args + * @return mixed + */ + public function __call($method, $args) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $args); + } + + return $this->baseResponse->{$method}(...$args); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestView.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestView.php new file mode 100644 index 0000000..3642c3f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/TestView.php @@ -0,0 +1,145 @@ +view = $view; + $this->rendered = $view->render(); + } + + /** + * Assert that the given string is contained within the view. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertSee($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringContainsString((string) $value, $this->rendered); + + return $this; + } + + /** + * Assert that the given strings are contained in order within the view. + * + * @param array $values + * @param bool $escape + * @return $this + */ + public function assertSeeInOrder(array $values, $escape = true) + { + $values = $escape ? array_map('e', ($values)) : $values; + + PHPUnit::assertThat($values, new SeeInOrder($this->rendered)); + + return $this; + } + + /** + * Assert that the given string is contained within the view text. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertSeeText($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringContainsString((string) $value, strip_tags($this->rendered)); + + return $this; + } + + /** + * Assert that the given strings are contained in order within the view text. + * + * @param array $values + * @param bool $escape + * @return $this + */ + public function assertSeeTextInOrder(array $values, $escape = true) + { + $values = $escape ? array_map('e', ($values)) : $values; + + PHPUnit::assertThat($values, new SeeInOrder(strip_tags($this->rendered))); + + return $this; + } + + /** + * Assert that the given string is not contained within the view. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertDontSee($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringNotContainsString((string) $value, $this->rendered); + + return $this; + } + + /** + * Assert that the given string is not contained within the view text. + * + * @param string $value + * @param bool $escape + * @return $this + */ + public function assertDontSeeText($value, $escape = true) + { + $value = $escape ? e($value) : $value; + + PHPUnit::assertStringNotContainsString((string) $value, strip_tags($this->rendered)); + + return $this; + } + + /** + * Get the string contents of the rendered view. + * + * @return string + */ + public function __toString() + { + return $this->rendered; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/composer.json new file mode 100644 index 0000000..41771b3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Testing/composer.json @@ -0,0 +1,45 @@ +{ + "name": "illuminate/testing", + "description": "The Illuminate Testing package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Testing\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "brianium/paratest": "Required to run tests in parallel (^6.0).", + "illuminate/console": "Required to assert console commands (^8.0).", + "illuminate/database": "Required to assert databases (^8.0).", + "illuminate/http": "Required to assert responses (^8.0).", + "mockery/mockery": "Required to use mocking (^1.4.4).", + "phpunit/phpunit": "Required to use assertions and run tests (^8.5.19|^9.5.8)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/ArrayLoader.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/ArrayLoader.php new file mode 100644 index 0000000..117e044 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/ArrayLoader.php @@ -0,0 +1,81 @@ +messages[$namespace][$locale][$group] ?? []; + } + + /** + * Add a new namespace to the loader. + * + * @param string $namespace + * @param string $hint + * @return void + */ + public function addNamespace($namespace, $hint) + { + // + } + + /** + * Add a new JSON path to the loader. + * + * @param string $path + * @return void + */ + public function addJsonPath($path) + { + // + } + + /** + * Add messages to the loader. + * + * @param string $locale + * @param string $group + * @param array $messages + * @param string|null $namespace + * @return $this + */ + public function addMessages($locale, $group, array $messages, $namespace = null) + { + $namespace = $namespace ?: '*'; + + $this->messages[$namespace][$locale][$group] = $messages; + + return $this; + } + + /** + * Get an array of all the registered namespaces. + * + * @return array + */ + public function namespaces() + { + return []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/FileLoader.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/FileLoader.php new file mode 100755 index 0000000..f359a8e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/FileLoader.php @@ -0,0 +1,197 @@ +path = $path; + $this->files = $files; + } + + /** + * Load the messages for the given locale. + * + * @param string $locale + * @param string $group + * @param string|null $namespace + * @return array + */ + public function load($locale, $group, $namespace = null) + { + if ($group === '*' && $namespace === '*') { + return $this->loadJsonPaths($locale); + } + + if (is_null($namespace) || $namespace === '*') { + return $this->loadPath($this->path, $locale, $group); + } + + return $this->loadNamespaced($locale, $group, $namespace); + } + + /** + * Load a namespaced translation group. + * + * @param string $locale + * @param string $group + * @param string $namespace + * @return array + */ + protected function loadNamespaced($locale, $group, $namespace) + { + if (isset($this->hints[$namespace])) { + $lines = $this->loadPath($this->hints[$namespace], $locale, $group); + + return $this->loadNamespaceOverrides($lines, $locale, $group, $namespace); + } + + return []; + } + + /** + * Load a local namespaced translation group for overrides. + * + * @param array $lines + * @param string $locale + * @param string $group + * @param string $namespace + * @return array + */ + protected function loadNamespaceOverrides(array $lines, $locale, $group, $namespace) + { + $file = "{$this->path}/vendor/{$namespace}/{$locale}/{$group}.php"; + + if ($this->files->exists($file)) { + return array_replace_recursive($lines, $this->files->getRequire($file)); + } + + return $lines; + } + + /** + * Load a locale from a given path. + * + * @param string $path + * @param string $locale + * @param string $group + * @return array + */ + protected function loadPath($path, $locale, $group) + { + if ($this->files->exists($full = "{$path}/{$locale}/{$group}.php")) { + return $this->files->getRequire($full); + } + + return []; + } + + /** + * Load a locale from the given JSON file path. + * + * @param string $locale + * @return array + * + * @throws \RuntimeException + */ + protected function loadJsonPaths($locale) + { + return collect(array_merge($this->jsonPaths, [$this->path])) + ->reduce(function ($output, $path) use ($locale) { + if ($this->files->exists($full = "{$path}/{$locale}.json")) { + $decoded = json_decode($this->files->get($full), true); + + if (is_null($decoded) || json_last_error() !== JSON_ERROR_NONE) { + throw new RuntimeException("Translation file [{$full}] contains an invalid JSON structure."); + } + + $output = array_merge($output, $decoded); + } + + return $output; + }, []); + } + + /** + * Add a new namespace to the loader. + * + * @param string $namespace + * @param string $hint + * @return void + */ + public function addNamespace($namespace, $hint) + { + $this->hints[$namespace] = $hint; + } + + /** + * Get an array of all the registered namespaces. + * + * @return array + */ + public function namespaces() + { + return $this->hints; + } + + /** + * Add a new JSON path to the loader. + * + * @param string $path + * @return void + */ + public function addJsonPath($path) + { + $this->jsonPaths[] = $path; + } + + /** + * Get an array of all the registered paths to JSON translation files. + * + * @return array + */ + public function jsonPaths() + { + return $this->jsonPaths; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/MessageSelector.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/MessageSelector.php new file mode 100755 index 0000000..177fa12 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/MessageSelector.php @@ -0,0 +1,412 @@ +extract($segments, $number)) !== null) { + return trim($value); + } + + $segments = $this->stripConditions($segments); + + $pluralIndex = $this->getPluralIndex($locale, $number); + + if (count($segments) === 1 || ! isset($segments[$pluralIndex])) { + return $segments[0]; + } + + return $segments[$pluralIndex]; + } + + /** + * Extract a translation string using inline conditions. + * + * @param array $segments + * @param int $number + * @return mixed + */ + private function extract($segments, $number) + { + foreach ($segments as $part) { + if (! is_null($line = $this->extractFromString($part, $number))) { + return $line; + } + } + } + + /** + * Get the translation string if the condition matches. + * + * @param string $part + * @param int $number + * @return mixed + */ + private function extractFromString($part, $number) + { + preg_match('/^[\{\[]([^\[\]\{\}]*)[\}\]](.*)/s', $part, $matches); + + if (count($matches) !== 3) { + return null; + } + + $condition = $matches[1]; + + $value = $matches[2]; + + if (Str::contains($condition, ',')) { + [$from, $to] = explode(',', $condition, 2); + + if ($to === '*' && $number >= $from) { + return $value; + } elseif ($from === '*' && $number <= $to) { + return $value; + } elseif ($number >= $from && $number <= $to) { + return $value; + } + } + + return $condition == $number ? $value : null; + } + + /** + * Strip the inline conditions from each segment, just leaving the text. + * + * @param array $segments + * @return array + */ + private function stripConditions($segments) + { + return collect($segments)->map(function ($part) { + return preg_replace('/^[\{\[]([^\[\]\{\}]*)[\}\]]/', '', $part); + })->all(); + } + + /** + * Get the index to use for pluralization. + * + * The plural rules are derived from code of the Zend Framework (2010-09-25), which + * is subject to the new BSD license (https://framework.zend.com/license) + * Copyright (c) 2005-2010 - Zend Technologies USA Inc. (http://www.zend.com) + * + * @param string $locale + * @param int $number + * @return int + */ + public function getPluralIndex($locale, $number) + { + switch ($locale) { + case 'az': + case 'az_AZ': + case 'bo': + case 'bo_CN': + case 'bo_IN': + case 'dz': + case 'dz_BT': + case 'id': + case 'id_ID': + case 'ja': + case 'ja_JP': + case 'jv': + case 'ka': + case 'ka_GE': + case 'km': + case 'km_KH': + case 'kn': + case 'kn_IN': + case 'ko': + case 'ko_KR': + case 'ms': + case 'ms_MY': + case 'th': + case 'th_TH': + case 'tr': + case 'tr_CY': + case 'tr_TR': + case 'vi': + case 'vi_VN': + case 'zh': + case 'zh_CN': + case 'zh_HK': + case 'zh_SG': + case 'zh_TW': + return 0; + case 'af': + case 'af_ZA': + case 'bn': + case 'bn_BD': + case 'bn_IN': + case 'bg': + case 'bg_BG': + case 'ca': + case 'ca_AD': + case 'ca_ES': + case 'ca_FR': + case 'ca_IT': + case 'da': + case 'da_DK': + case 'de': + case 'de_AT': + case 'de_BE': + case 'de_CH': + case 'de_DE': + case 'de_LI': + case 'de_LU': + case 'el': + case 'el_CY': + case 'el_GR': + case 'en': + case 'en_AG': + case 'en_AU': + case 'en_BW': + case 'en_CA': + case 'en_DK': + case 'en_GB': + case 'en_HK': + case 'en_IE': + case 'en_IN': + case 'en_NG': + case 'en_NZ': + case 'en_PH': + case 'en_SG': + case 'en_US': + case 'en_ZA': + case 'en_ZM': + case 'en_ZW': + case 'eo': + case 'eo_US': + case 'es': + case 'es_AR': + case 'es_BO': + case 'es_CL': + case 'es_CO': + case 'es_CR': + case 'es_CU': + case 'es_DO': + case 'es_EC': + case 'es_ES': + case 'es_GT': + case 'es_HN': + case 'es_MX': + case 'es_NI': + case 'es_PA': + case 'es_PE': + case 'es_PR': + case 'es_PY': + case 'es_SV': + case 'es_US': + case 'es_UY': + case 'es_VE': + case 'et': + case 'et_EE': + case 'eu': + case 'eu_ES': + case 'eu_FR': + case 'fa': + case 'fa_IR': + case 'fi': + case 'fi_FI': + case 'fo': + case 'fo_FO': + case 'fur': + case 'fur_IT': + case 'fy': + case 'fy_DE': + case 'fy_NL': + case 'gl': + case 'gl_ES': + case 'gu': + case 'gu_IN': + case 'ha': + case 'ha_NG': + case 'he': + case 'he_IL': + case 'hu': + case 'hu_HU': + case 'is': + case 'is_IS': + case 'it': + case 'it_CH': + case 'it_IT': + case 'ku': + case 'ku_TR': + case 'lb': + case 'lb_LU': + case 'ml': + case 'ml_IN': + case 'mn': + case 'mn_MN': + case 'mr': + case 'mr_IN': + case 'nah': + case 'nb': + case 'nb_NO': + case 'ne': + case 'ne_NP': + case 'nl': + case 'nl_AW': + case 'nl_BE': + case 'nl_NL': + case 'nn': + case 'nn_NO': + case 'no': + case 'om': + case 'om_ET': + case 'om_KE': + case 'or': + case 'or_IN': + case 'pa': + case 'pa_IN': + case 'pa_PK': + case 'pap': + case 'pap_AN': + case 'pap_AW': + case 'pap_CW': + case 'ps': + case 'ps_AF': + case 'pt': + case 'pt_BR': + case 'pt_PT': + case 'so': + case 'so_DJ': + case 'so_ET': + case 'so_KE': + case 'so_SO': + case 'sq': + case 'sq_AL': + case 'sq_MK': + case 'sv': + case 'sv_FI': + case 'sv_SE': + case 'sw': + case 'sw_KE': + case 'sw_TZ': + case 'ta': + case 'ta_IN': + case 'ta_LK': + case 'te': + case 'te_IN': + case 'tk': + case 'tk_TM': + case 'ur': + case 'ur_IN': + case 'ur_PK': + case 'zu': + case 'zu_ZA': + return ($number == 1) ? 0 : 1; + case 'am': + case 'am_ET': + case 'bh': + case 'fil': + case 'fil_PH': + case 'fr': + case 'fr_BE': + case 'fr_CA': + case 'fr_CH': + case 'fr_FR': + case 'fr_LU': + case 'gun': + case 'hi': + case 'hi_IN': + case 'hy': + case 'hy_AM': + case 'ln': + case 'ln_CD': + case 'mg': + case 'mg_MG': + case 'nso': + case 'nso_ZA': + case 'ti': + case 'ti_ER': + case 'ti_ET': + case 'wa': + case 'wa_BE': + case 'xbr': + return (($number == 0) || ($number == 1)) ? 0 : 1; + case 'be': + case 'be_BY': + case 'bs': + case 'bs_BA': + case 'hr': + case 'hr_HR': + case 'ru': + case 'ru_RU': + case 'ru_UA': + case 'sr': + case 'sr_ME': + case 'sr_RS': + case 'uk': + case 'uk_UA': + return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); + case 'cs': + case 'cs_CZ': + case 'sk': + case 'sk_SK': + return ($number == 1) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2); + case 'ga': + case 'ga_IE': + return ($number == 1) ? 0 : (($number == 2) ? 1 : 2); + case 'lt': + case 'lt_LT': + return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); + case 'sl': + case 'sl_SI': + return ($number % 100 == 1) ? 0 : (($number % 100 == 2) ? 1 : ((($number % 100 == 3) || ($number % 100 == 4)) ? 2 : 3)); + case 'mk': + case 'mk_MK': + return ($number % 10 == 1) ? 0 : 1; + case 'mt': + case 'mt_MT': + return ($number == 1) ? 0 : ((($number == 0) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3)); + case 'lv': + case 'lv_LV': + return ($number == 0) ? 0 : ((($number % 10 == 1) && ($number % 100 != 11)) ? 1 : 2); + case 'pl': + case 'pl_PL': + return ($number == 1) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2); + case 'cy': + case 'cy_GB': + return ($number == 1) ? 0 : (($number == 2) ? 1 : ((($number == 8) || ($number == 11)) ? 2 : 3)); + case 'ro': + case 'ro_RO': + return ($number == 1) ? 0 : ((($number == 0) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2); + case 'ar': + case 'ar_AE': + case 'ar_BH': + case 'ar_DZ': + case 'ar_EG': + case 'ar_IN': + case 'ar_IQ': + case 'ar_JO': + case 'ar_KW': + case 'ar_LB': + case 'ar_LY': + case 'ar_MA': + case 'ar_OM': + case 'ar_QA': + case 'ar_SA': + case 'ar_SD': + case 'ar_SS': + case 'ar_SY': + case 'ar_TN': + case 'ar_YE': + return ($number == 0) ? 0 : (($number == 1) ? 1 : (($number == 2) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5)))); + default: + return 0; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/TranslationServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/TranslationServiceProvider.php new file mode 100755 index 0000000..7455b52 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/TranslationServiceProvider.php @@ -0,0 +1,56 @@ +registerLoader(); + + $this->app->singleton('translator', function ($app) { + $loader = $app['translation.loader']; + + // When registering the translator component, we'll need to set the default + // locale as well as the fallback locale. So, we'll grab the application + // configuration so we can easily get both of these values from there. + $locale = $app['config']['app.locale']; + + $trans = new Translator($loader, $locale); + + $trans->setFallback($app['config']['app.fallback_locale']); + + return $trans; + }); + } + + /** + * Register the translation line loader. + * + * @return void + */ + protected function registerLoader() + { + $this->app->singleton('translation.loader', function ($app) { + return new FileLoader($app['files'], $app['path.lang']); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['translator', 'translation.loader']; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/Translator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/Translator.php new file mode 100755 index 0000000..cc36dbe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/Translator.php @@ -0,0 +1,435 @@ +loader = $loader; + + $this->setLocale($locale); + } + + /** + * Determine if a translation exists for a given locale. + * + * @param string $key + * @param string|null $locale + * @return bool + */ + public function hasForLocale($key, $locale = null) + { + return $this->has($key, $locale, false); + } + + /** + * Determine if a translation exists. + * + * @param string $key + * @param string|null $locale + * @param bool $fallback + * @return bool + */ + public function has($key, $locale = null, $fallback = true) + { + return $this->get($key, [], $locale, $fallback) !== $key; + } + + /** + * Get the translation for the given key. + * + * @param string $key + * @param array $replace + * @param string|null $locale + * @param bool $fallback + * @return string|array + */ + public function get($key, array $replace = [], $locale = null, $fallback = true) + { + $locale = $locale ?: $this->locale; + + // For JSON translations, there is only one file per locale, so we will simply load + // that file and then we will be ready to check the array for the key. These are + // only one level deep so we do not need to do any fancy searching through it. + $this->load('*', '*', $locale); + + $line = $this->loaded['*']['*'][$locale][$key] ?? null; + + // If we can't find a translation for the JSON key, we will attempt to translate it + // using the typical translation file. This way developers can always just use a + // helper such as __ instead of having to pick between trans or __ with views. + if (! isset($line)) { + [$namespace, $group, $item] = $this->parseKey($key); + + // Here we will get the locale that should be used for the language line. If one + // was not passed, we will use the default locales which was given to us when + // the translator was instantiated. Then, we can load the lines and return. + $locales = $fallback ? $this->localeArray($locale) : [$locale]; + + foreach ($locales as $locale) { + if (! is_null($line = $this->getLine( + $namespace, $group, $locale, $item, $replace + ))) { + return $line; + } + } + } + + // If the line doesn't exist, we will return back the key which was requested as + // that will be quick to spot in the UI if language keys are wrong or missing + // from the application's language files. Otherwise we can return the line. + return $this->makeReplacements($line ?: $key, $replace); + } + + /** + * Get a translation according to an integer value. + * + * @param string $key + * @param \Countable|int|array $number + * @param array $replace + * @param string|null $locale + * @return string + */ + public function choice($key, $number, array $replace = [], $locale = null) + { + $line = $this->get( + $key, $replace, $locale = $this->localeForChoice($locale) + ); + + // If the given "number" is actually an array or countable we will simply count the + // number of elements in an instance. This allows developers to pass an array of + // items without having to count it on their end first which gives bad syntax. + if (is_array($number) || $number instanceof Countable) { + $number = count($number); + } + + $replace['count'] = $number; + + return $this->makeReplacements( + $this->getSelector()->choose($line, $number, $locale), $replace + ); + } + + /** + * Get the proper locale for a choice operation. + * + * @param string|null $locale + * @return string + */ + protected function localeForChoice($locale) + { + return $locale ?: $this->locale ?: $this->fallback; + } + + /** + * Retrieve a language line out the loaded array. + * + * @param string $namespace + * @param string $group + * @param string $locale + * @param string $item + * @param array $replace + * @return string|array|null + */ + protected function getLine($namespace, $group, $locale, $item, array $replace) + { + $this->load($namespace, $group, $locale); + + $line = Arr::get($this->loaded[$namespace][$group][$locale], $item); + + if (is_string($line)) { + return $this->makeReplacements($line, $replace); + } elseif (is_array($line) && count($line) > 0) { + foreach ($line as $key => $value) { + $line[$key] = $this->makeReplacements($value, $replace); + } + + return $line; + } + } + + /** + * Make the place-holder replacements on a line. + * + * @param string $line + * @param array $replace + * @return string + */ + protected function makeReplacements($line, array $replace) + { + if (empty($replace)) { + return $line; + } + + $shouldReplace = []; + + foreach ($replace as $key => $value) { + $shouldReplace[':'.Str::ucfirst($key ?? '')] = Str::ucfirst($value ?? ''); + $shouldReplace[':'.Str::upper($key ?? '')] = Str::upper($value ?? ''); + $shouldReplace[':'.$key] = $value; + } + + return strtr($line, $shouldReplace); + } + + /** + * Add translation lines to the given locale. + * + * @param array $lines + * @param string $locale + * @param string $namespace + * @return void + */ + public function addLines(array $lines, $locale, $namespace = '*') + { + foreach ($lines as $key => $value) { + [$group, $item] = explode('.', $key, 2); + + Arr::set($this->loaded, "$namespace.$group.$locale.$item", $value); + } + } + + /** + * Load the specified language group. + * + * @param string $namespace + * @param string $group + * @param string $locale + * @return void + */ + public function load($namespace, $group, $locale) + { + if ($this->isLoaded($namespace, $group, $locale)) { + return; + } + + // The loader is responsible for returning the array of language lines for the + // given namespace, group, and locale. We'll set the lines in this array of + // lines that have already been loaded so that we can easily access them. + $lines = $this->loader->load($locale, $group, $namespace); + + $this->loaded[$namespace][$group][$locale] = $lines; + } + + /** + * Determine if the given group has been loaded. + * + * @param string $namespace + * @param string $group + * @param string $locale + * @return bool + */ + protected function isLoaded($namespace, $group, $locale) + { + return isset($this->loaded[$namespace][$group][$locale]); + } + + /** + * Add a new namespace to the loader. + * + * @param string $namespace + * @param string $hint + * @return void + */ + public function addNamespace($namespace, $hint) + { + $this->loader->addNamespace($namespace, $hint); + } + + /** + * Add a new JSON path to the loader. + * + * @param string $path + * @return void + */ + public function addJsonPath($path) + { + $this->loader->addJsonPath($path); + } + + /** + * Parse a key into namespace, group, and item. + * + * @param string $key + * @return array + */ + public function parseKey($key) + { + $segments = parent::parseKey($key); + + if (is_null($segments[0])) { + $segments[0] = '*'; + } + + return $segments; + } + + /** + * Get the array of locales to be checked. + * + * @param string|null $locale + * @return array + */ + protected function localeArray($locale) + { + return array_filter([$locale ?: $this->locale, $this->fallback]); + } + + /** + * Get the message selector instance. + * + * @return \Illuminate\Translation\MessageSelector + */ + public function getSelector() + { + if (! isset($this->selector)) { + $this->selector = new MessageSelector; + } + + return $this->selector; + } + + /** + * Set the message selector instance. + * + * @param \Illuminate\Translation\MessageSelector $selector + * @return void + */ + public function setSelector(MessageSelector $selector) + { + $this->selector = $selector; + } + + /** + * Get the language line loader implementation. + * + * @return \Illuminate\Contracts\Translation\Loader + */ + public function getLoader() + { + return $this->loader; + } + + /** + * Get the default locale being used. + * + * @return string + */ + public function locale() + { + return $this->getLocale(); + } + + /** + * Get the default locale being used. + * + * @return string + */ + public function getLocale() + { + return $this->locale; + } + + /** + * Set the default locale. + * + * @param string $locale + * @return void + * + * @throws \InvalidArgumentException + */ + public function setLocale($locale) + { + if (Str::contains($locale, ['/', '\\'])) { + throw new InvalidArgumentException('Invalid characters present in locale.'); + } + + $this->locale = $locale; + } + + /** + * Get the fallback locale being used. + * + * @return string + */ + public function getFallback() + { + return $this->fallback; + } + + /** + * Set the fallback locale being used. + * + * @param string $fallback + * @return void + */ + public function setFallback($fallback) + { + $this->fallback = $fallback; + } + + /** + * Set the loaded translation groups. + * + * @param array $loaded + * @return void + */ + public function setLoaded(array $loaded) + { + $this->loaded = $loaded; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/composer.json new file mode 100755 index 0000000..ccd7142 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Translation/composer.json @@ -0,0 +1,39 @@ +{ + "name": "illuminate/translation", + "description": "The Illuminate Translation package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\Translation\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ClosureValidationRule.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ClosureValidationRule.php new file mode 100644 index 0000000..8f247fc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ClosureValidationRule.php @@ -0,0 +1,70 @@ +callback = $callback; + } + + /** + * Determine if the validation rule passes. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function passes($attribute, $value) + { + $this->failed = false; + + $this->callback->__invoke($attribute, $value, function ($message) { + $this->failed = true; + + $this->message = $message; + }); + + return ! $this->failed; + } + + /** + * Get the validation error message. + * + * @return string + */ + public function message() + { + return $this->message; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/FilterEmailValidation.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/FilterEmailValidation.php new file mode 100644 index 0000000..2d21b6c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/FilterEmailValidation.php @@ -0,0 +1,71 @@ +flags = $flags; + } + + /** + * Create a new instance which allows any unicode characters in local-part. + * + * @return static + */ + public static function unicode() + { + return new static(FILTER_FLAG_EMAIL_UNICODE); + } + + /** + * Returns true if the given email is valid. + * + * @param string $email + * @param \Egulias\EmailValidator\EmailLexer $emailLexer + * @return bool + */ + public function isValid($email, EmailLexer $emailLexer) + { + return is_null($this->flags) + ? filter_var($email, FILTER_VALIDATE_EMAIL) !== false + : filter_var($email, FILTER_VALIDATE_EMAIL, $this->flags) !== false; + } + + /** + * Returns the validation error. + * + * @return \Egulias\EmailValidator\Exception\InvalidEmail|null + */ + public function getError() + { + // + } + + /** + * Returns the validation warnings. + * + * @return \Egulias\EmailValidator\Warning\Warning[] + */ + public function getWarnings() + { + return []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php new file mode 100644 index 0000000..c7c9a1d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php @@ -0,0 +1,408 @@ +replacePlaceholderInString($attribute); + + $inlineMessage = $this->getInlineMessage($attribute, $rule); + + // First we will retrieve the custom message for the validation rule if one + // exists. If a custom validation message is being used we'll return the + // custom message, otherwise we'll keep searching for a valid message. + if (! is_null($inlineMessage)) { + return $inlineMessage; + } + + $lowerRule = Str::snake($rule); + + $customMessage = $this->getCustomMessageFromTranslator( + $customKey = "validation.custom.{$attribute}.{$lowerRule}" + ); + + // First we check for a custom defined validation message for the attribute + // and rule. This allows the developer to specify specific messages for + // only some attributes and rules that need to get specially formed. + if ($customMessage !== $customKey) { + return $customMessage; + } + + // If the rule being validated is a "size" rule, we will need to gather the + // specific error message for the type of attribute being validated such + // as a number, file or string which all have different message types. + elseif (in_array($rule, $this->sizeRules)) { + return $this->getSizeMessage($attributeWithPlaceholders, $rule); + } + + // Finally, if no developer specified messages have been set, and no other + // special messages apply for this rule, we will just pull the default + // messages out of the translator service for this validation rule. + $key = "validation.{$lowerRule}"; + + if ($key !== ($value = $this->translator->get($key))) { + return $value; + } + + return $this->getFromLocalArray( + $attribute, $lowerRule, $this->fallbackMessages + ) ?: $key; + } + + /** + * Get the proper inline error message for standard and size rules. + * + * @param string $attribute + * @param string $rule + * @return string|null + */ + protected function getInlineMessage($attribute, $rule) + { + $inlineEntry = $this->getFromLocalArray($attribute, Str::snake($rule)); + + return is_array($inlineEntry) && in_array($rule, $this->sizeRules) + ? $inlineEntry[$this->getAttributeType($attribute)] + : $inlineEntry; + } + + /** + * Get the inline message for a rule if it exists. + * + * @param string $attribute + * @param string $lowerRule + * @param array|null $source + * @return string|null + */ + protected function getFromLocalArray($attribute, $lowerRule, $source = null) + { + $source = $source ?: $this->customMessages; + + $keys = ["{$attribute}.{$lowerRule}", $lowerRule]; + + // First we will check for a custom message for an attribute specific rule + // message for the fields, then we will check for a general custom line + // that is not attribute specific. If we find either we'll return it. + foreach ($keys as $key) { + foreach (array_keys($source) as $sourceKey) { + if (strpos($sourceKey, '*') !== false) { + $pattern = str_replace('\*', '([^.]*)', preg_quote($sourceKey, '#')); + + if (preg_match('#^'.$pattern.'\z#u', $key) === 1) { + return $source[$sourceKey]; + } + + continue; + } + + if (Str::is($sourceKey, $key)) { + return $source[$sourceKey]; + } + } + } + } + + /** + * Get the custom error message from the translator. + * + * @param string $key + * @return string + */ + protected function getCustomMessageFromTranslator($key) + { + if (($message = $this->translator->get($key)) !== $key) { + return $message; + } + + // If an exact match was not found for the key, we will collapse all of these + // messages and loop through them and try to find a wildcard match for the + // given key. Otherwise, we will simply return the key's value back out. + $shortKey = preg_replace( + '/^validation\.custom\./', '', $key + ); + + return $this->getWildcardCustomMessages(Arr::dot( + (array) $this->translator->get('validation.custom') + ), $shortKey, $key); + } + + /** + * Check the given messages for a wildcard key. + * + * @param array $messages + * @param string $search + * @param string $default + * @return string + */ + protected function getWildcardCustomMessages($messages, $search, $default) + { + foreach ($messages as $key => $message) { + if ($search === $key || (Str::contains($key, ['*']) && Str::is($key, $search))) { + return $message; + } + } + + return $default; + } + + /** + * Get the proper error message for an attribute and size rule. + * + * @param string $attribute + * @param string $rule + * @return string + */ + protected function getSizeMessage($attribute, $rule) + { + $lowerRule = Str::snake($rule); + + // There are three different types of size validations. The attribute may be + // either a number, file, or string so we will check a few things to know + // which type of value it is and return the correct line for that type. + $type = $this->getAttributeType($attribute); + + $key = "validation.{$lowerRule}.{$type}"; + + return $this->translator->get($key); + } + + /** + * Get the data type of the given attribute. + * + * @param string $attribute + * @return string + */ + protected function getAttributeType($attribute) + { + // We assume that the attributes present in the file array are files so that + // means that if the attribute does not have a numeric rule and the files + // list doesn't have it we'll just consider it a string by elimination. + if ($this->hasRule($attribute, $this->numericRules)) { + return 'numeric'; + } elseif ($this->hasRule($attribute, ['Array'])) { + return 'array'; + } elseif ($this->getValue($attribute) instanceof UploadedFile) { + return 'file'; + } + + return 'string'; + } + + /** + * Replace all error message place-holders with actual values. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + public function makeReplacements($message, $attribute, $rule, $parameters) + { + $message = $this->replaceAttributePlaceholder( + $message, $this->getDisplayableAttribute($attribute) + ); + + $message = $this->replaceInputPlaceholder($message, $attribute); + + if (isset($this->replacers[Str::snake($rule)])) { + return $this->callReplacer($message, $attribute, Str::snake($rule), $parameters, $this); + } elseif (method_exists($this, $replacer = "replace{$rule}")) { + return $this->$replacer($message, $attribute, $rule, $parameters); + } + + return $message; + } + + /** + * Get the displayable name of the attribute. + * + * @param string $attribute + * @return string + */ + public function getDisplayableAttribute($attribute) + { + $primaryAttribute = $this->getPrimaryAttribute($attribute); + + $expectedAttributes = $attribute != $primaryAttribute + ? [$attribute, $primaryAttribute] : [$attribute]; + + foreach ($expectedAttributes as $name) { + // The developer may dynamically specify the array of custom attributes on this + // validator instance. If the attribute exists in this array it is used over + // the other ways of pulling the attribute name for this given attributes. + if (isset($this->customAttributes[$name])) { + return $this->customAttributes[$name]; + } + + // We allow for a developer to specify language lines for any attribute in this + // application, which allows flexibility for displaying a unique displayable + // version of the attribute name instead of the name used in an HTTP POST. + if ($line = $this->getAttributeFromTranslations($name)) { + return $line; + } + } + + // When no language line has been specified for the attribute and it is also + // an implicit attribute we will display the raw attribute's name and not + // modify it with any of these replacements before we display the name. + if (isset($this->implicitAttributes[$primaryAttribute])) { + return ($formatter = $this->implicitAttributesFormatter) + ? $formatter($attribute) + : $attribute; + } + + return str_replace('_', ' ', Str::snake($attribute)); + } + + /** + * Get the given attribute from the attribute translations. + * + * @param string $name + * @return string + */ + protected function getAttributeFromTranslations($name) + { + return Arr::get($this->translator->get('validation.attributes'), $name); + } + + /** + * Replace the :attribute placeholder in the given message. + * + * @param string $message + * @param string $value + * @return string + */ + protected function replaceAttributePlaceholder($message, $value) + { + return str_replace( + [':attribute', ':ATTRIBUTE', ':Attribute'], + [$value, Str::upper($value), Str::ucfirst($value)], + $message + ); + } + + /** + * Replace the :input placeholder in the given message. + * + * @param string $message + * @param string $attribute + * @return string + */ + protected function replaceInputPlaceholder($message, $attribute) + { + $actualValue = $this->getValue($attribute); + + if (is_scalar($actualValue) || is_null($actualValue)) { + $message = str_replace(':input', $this->getDisplayableValue($attribute, $actualValue), $message); + } + + return $message; + } + + /** + * Get the displayable name of the value. + * + * @param string $attribute + * @param mixed $value + * @return string + */ + public function getDisplayableValue($attribute, $value) + { + if (isset($this->customValues[$attribute][$value])) { + return $this->customValues[$attribute][$value]; + } + + $key = "validation.values.{$attribute}.{$value}"; + + if (($line = $this->translator->get($key)) !== $key) { + return $line; + } + + if (is_bool($value)) { + return $value ? 'true' : 'false'; + } + + if (is_null($value)) { + return 'empty'; + } + + return (string) $value; + } + + /** + * Transform an array of attributes to their displayable form. + * + * @param array $values + * @return array + */ + protected function getAttributeList(array $values) + { + $attributes = []; + + // For each attribute in the list we will simply get its displayable form as + // this is convenient when replacing lists of parameters like some of the + // replacement functions do when formatting out the validation message. + foreach ($values as $key => $value) { + $attributes[$key] = $this->getDisplayableAttribute($value); + } + + return $attributes; + } + + /** + * Call a custom validator message replacer. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @param \Illuminate\Validation\Validator $validator + * @return string|null + */ + protected function callReplacer($message, $attribute, $rule, $parameters, $validator) + { + $callback = $this->replacers[$rule]; + + if ($callback instanceof Closure) { + return $callback(...func_get_args()); + } elseif (is_string($callback)) { + return $this->callClassBasedReplacer($callback, $message, $attribute, $rule, $parameters, $validator); + } + } + + /** + * Call a class based validator message replacer. + * + * @param string $callback + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @param \Illuminate\Validation\Validator $validator + * @return string + */ + protected function callClassBasedReplacer($callback, $message, $attribute, $rule, $parameters, $validator) + { + [$class, $method] = Str::parseCallback($callback, 'replace'); + + return $this->container->make($class)->{$method}(...array_slice(func_get_args(), 1)); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ReplacesAttributes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ReplacesAttributes.php new file mode 100644 index 0000000..e973274 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ReplacesAttributes.php @@ -0,0 +1,630 @@ +getDisplayableValue($parameters[0], Arr::get($this->data, $parameters[0])); + + $parameters[0] = $this->getDisplayableAttribute($parameters[0]); + + return str_replace([':other', ':value'], $parameters, $message); + } + + /** + * Replace all place-holders for the declined_if rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDeclinedIf($message, $attribute, $rule, $parameters) + { + $parameters[1] = $this->getDisplayableValue($parameters[0], Arr::get($this->data, $parameters[0])); + + $parameters[0] = $this->getDisplayableAttribute($parameters[0]); + + return str_replace([':other', ':value'], $parameters, $message); + } + + /** + * Replace all place-holders for the between rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceBetween($message, $attribute, $rule, $parameters) + { + return str_replace([':min', ':max'], $parameters, $message); + } + + /** + * Replace all place-holders for the date_format rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDateFormat($message, $attribute, $rule, $parameters) + { + return str_replace(':format', $parameters[0], $message); + } + + /** + * Replace all place-holders for the different rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDifferent($message, $attribute, $rule, $parameters) + { + return $this->replaceSame($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the digits rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDigits($message, $attribute, $rule, $parameters) + { + return str_replace(':digits', $parameters[0], $message); + } + + /** + * Replace all place-holders for the digits (between) rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDigitsBetween($message, $attribute, $rule, $parameters) + { + return $this->replaceBetween($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the min rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceMin($message, $attribute, $rule, $parameters) + { + return str_replace(':min', $parameters[0], $message); + } + + /** + * Replace all place-holders for the max rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceMax($message, $attribute, $rule, $parameters) + { + return str_replace(':max', $parameters[0], $message); + } + + /** + * Replace all place-holders for the multiple_of rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceMultipleOf($message, $attribute, $rule, $parameters) + { + return str_replace(':value', $parameters[0] ?? '', $message); + } + + /** + * Replace all place-holders for the in rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceIn($message, $attribute, $rule, $parameters) + { + foreach ($parameters as &$parameter) { + $parameter = $this->getDisplayableValue($attribute, $parameter); + } + + return str_replace(':values', implode(', ', $parameters), $message); + } + + /** + * Replace all place-holders for the not_in rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceNotIn($message, $attribute, $rule, $parameters) + { + return $this->replaceIn($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the in_array rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceInArray($message, $attribute, $rule, $parameters) + { + return str_replace(':other', $this->getDisplayableAttribute($parameters[0]), $message); + } + + /** + * Replace all place-holders for the required_array_keys rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredArrayKeys($message, $attribute, $rule, $parameters) + { + foreach ($parameters as &$parameter) { + $parameter = $this->getDisplayableValue($attribute, $parameter); + } + + return str_replace(':values', implode(', ', $parameters), $message); + } + + /** + * Replace all place-holders for the mimetypes rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceMimetypes($message, $attribute, $rule, $parameters) + { + return str_replace(':values', implode(', ', $parameters), $message); + } + + /** + * Replace all place-holders for the mimes rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceMimes($message, $attribute, $rule, $parameters) + { + return str_replace(':values', implode(', ', $parameters), $message); + } + + /** + * Replace all place-holders for the required_with rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredWith($message, $attribute, $rule, $parameters) + { + return str_replace(':values', implode(' / ', $this->getAttributeList($parameters)), $message); + } + + /** + * Replace all place-holders for the required_with_all rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredWithAll($message, $attribute, $rule, $parameters) + { + return $this->replaceRequiredWith($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the required_without rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredWithout($message, $attribute, $rule, $parameters) + { + return $this->replaceRequiredWith($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the required_without_all rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredWithoutAll($message, $attribute, $rule, $parameters) + { + return $this->replaceRequiredWith($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the size rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceSize($message, $attribute, $rule, $parameters) + { + return str_replace(':size', $parameters[0], $message); + } + + /** + * Replace all place-holders for the gt rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceGt($message, $attribute, $rule, $parameters) + { + if (is_null($value = $this->getValue($parameters[0]))) { + return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message); + } + + return str_replace(':value', $this->getSize($attribute, $value), $message); + } + + /** + * Replace all place-holders for the lt rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceLt($message, $attribute, $rule, $parameters) + { + if (is_null($value = $this->getValue($parameters[0]))) { + return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message); + } + + return str_replace(':value', $this->getSize($attribute, $value), $message); + } + + /** + * Replace all place-holders for the gte rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceGte($message, $attribute, $rule, $parameters) + { + if (is_null($value = $this->getValue($parameters[0]))) { + return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message); + } + + return str_replace(':value', $this->getSize($attribute, $value), $message); + } + + /** + * Replace all place-holders for the lte rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceLte($message, $attribute, $rule, $parameters) + { + if (is_null($value = $this->getValue($parameters[0]))) { + return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message); + } + + return str_replace(':value', $this->getSize($attribute, $value), $message); + } + + /** + * Replace all place-holders for the required_if rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredIf($message, $attribute, $rule, $parameters) + { + $parameters[1] = $this->getDisplayableValue($parameters[0], Arr::get($this->data, $parameters[0])); + + $parameters[0] = $this->getDisplayableAttribute($parameters[0]); + + return str_replace([':other', ':value'], $parameters, $message); + } + + /** + * Replace all place-holders for the required_unless rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceRequiredUnless($message, $attribute, $rule, $parameters) + { + $other = $this->getDisplayableAttribute($parameters[0]); + + $values = []; + + foreach (array_slice($parameters, 1) as $value) { + $values[] = $this->getDisplayableValue($parameters[0], $value); + } + + return str_replace([':other', ':values'], [$other, implode(', ', $values)], $message); + } + + /** + * Replace all place-holders for the prohibited_if rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceProhibitedIf($message, $attribute, $rule, $parameters) + { + $parameters[1] = $this->getDisplayableValue($parameters[0], Arr::get($this->data, $parameters[0])); + + $parameters[0] = $this->getDisplayableAttribute($parameters[0]); + + return str_replace([':other', ':value'], $parameters, $message); + } + + /** + * Replace all place-holders for the prohibited_unless rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceProhibitedUnless($message, $attribute, $rule, $parameters) + { + $other = $this->getDisplayableAttribute($parameters[0]); + + $values = []; + + foreach (array_slice($parameters, 1) as $value) { + $values[] = $this->getDisplayableValue($parameters[0], $value); + } + + return str_replace([':other', ':values'], [$other, implode(', ', $values)], $message); + } + + /** + * Replace all place-holders for the prohibited_with rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceProhibits($message, $attribute, $rule, $parameters) + { + return str_replace(':other', implode(' / ', $this->getAttributeList($parameters)), $message); + } + + /** + * Replace all place-holders for the same rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceSame($message, $attribute, $rule, $parameters) + { + return str_replace(':other', $this->getDisplayableAttribute($parameters[0]), $message); + } + + /** + * Replace all place-holders for the before rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceBefore($message, $attribute, $rule, $parameters) + { + if (! strtotime($parameters[0])) { + return str_replace(':date', $this->getDisplayableAttribute($parameters[0]), $message); + } + + return str_replace(':date', $this->getDisplayableValue($attribute, $parameters[0]), $message); + } + + /** + * Replace all place-holders for the before_or_equal rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceBeforeOrEqual($message, $attribute, $rule, $parameters) + { + return $this->replaceBefore($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the after rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceAfter($message, $attribute, $rule, $parameters) + { + return $this->replaceBefore($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the after_or_equal rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceAfterOrEqual($message, $attribute, $rule, $parameters) + { + return $this->replaceBefore($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the date_equals rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDateEquals($message, $attribute, $rule, $parameters) + { + return $this->replaceBefore($message, $attribute, $rule, $parameters); + } + + /** + * Replace all place-holders for the dimensions rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceDimensions($message, $attribute, $rule, $parameters) + { + $parameters = $this->parseNamedParameters($parameters); + + if (is_array($parameters)) { + foreach ($parameters as $key => $value) { + $message = str_replace(':'.$key, $value, $message); + } + } + + return $message; + } + + /** + * Replace all place-holders for the ends_with rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceEndsWith($message, $attribute, $rule, $parameters) + { + foreach ($parameters as &$parameter) { + $parameter = $this->getDisplayableValue($attribute, $parameter); + } + + return str_replace(':values', implode(', ', $parameters), $message); + } + + /** + * Replace all place-holders for the starts_with rule. + * + * @param string $message + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return string + */ + protected function replaceStartsWith($message, $attribute, $rule, $parameters) + { + foreach ($parameters as &$parameter) { + $parameter = $this->getDisplayableValue($attribute, $parameter); + } + + return str_replace(':values', implode(', ', $parameters), $message); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php new file mode 100644 index 0000000..2974174 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php @@ -0,0 +1,2165 @@ +validateRequired($attribute, $value) && in_array($value, $acceptable, true); + } + + /** + * Validate that an attribute was "accepted" when another attribute has a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateAcceptedIf($attribute, $value, $parameters) + { + $acceptable = ['yes', 'on', '1', 1, true, 'true']; + + $this->requireParameterCount(2, $parameters, 'accepted_if'); + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + if (in_array($other, $values, is_bool($other) || is_null($other))) { + return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); + } + + return true; + } + + /** + * Validate that an attribute was "declined". + * + * This validation rule implies the attribute is "required". + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateDeclined($attribute, $value) + { + $acceptable = ['no', 'off', '0', 0, false, 'false']; + + return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); + } + + /** + * Validate that an attribute was "declined" when another attribute has a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateDeclinedIf($attribute, $value, $parameters) + { + $acceptable = ['no', 'off', '0', 0, false, 'false']; + + $this->requireParameterCount(2, $parameters, 'declined_if'); + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + if (in_array($other, $values, is_bool($other) || is_null($other))) { + return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); + } + + return true; + } + + /** + * Validate that an attribute is an active URL. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateActiveUrl($attribute, $value) + { + if (! is_string($value)) { + return false; + } + + if ($url = parse_url($value, PHP_URL_HOST)) { + try { + return count(dns_get_record($url.'.', DNS_A | DNS_AAAA)) > 0; + } catch (Exception $e) { + return false; + } + } + + return false; + } + + /** + * "Break" on first validation fail. + * + * Always returns true, just lets us put "bail" in rules. + * + * @return bool + */ + public function validateBail() + { + return true; + } + + /** + * Validate the date is before a given date. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateBefore($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'before'); + + return $this->compareDates($attribute, $value, $parameters, '<'); + } + + /** + * Validate the date is before or equal a given date. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateBeforeOrEqual($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'before_or_equal'); + + return $this->compareDates($attribute, $value, $parameters, '<='); + } + + /** + * Validate the date is after a given date. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateAfter($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'after'); + + return $this->compareDates($attribute, $value, $parameters, '>'); + } + + /** + * Validate the date is equal or after a given date. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateAfterOrEqual($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'after_or_equal'); + + return $this->compareDates($attribute, $value, $parameters, '>='); + } + + /** + * Compare a given date against another using an operator. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @param string $operator + * @return bool + */ + protected function compareDates($attribute, $value, $parameters, $operator) + { + if (! is_string($value) && ! is_numeric($value) && ! $value instanceof DateTimeInterface) { + return false; + } + + if ($format = $this->getDateFormat($attribute)) { + return $this->checkDateTimeOrder($format, $value, $parameters[0], $operator); + } + + if (! $date = $this->getDateTimestamp($parameters[0])) { + $date = $this->getDateTimestamp($this->getValue($parameters[0])); + } + + return $this->compare($this->getDateTimestamp($value), $date, $operator); + } + + /** + * Get the date format for an attribute if it has one. + * + * @param string $attribute + * @return string|null + */ + protected function getDateFormat($attribute) + { + if ($result = $this->getRule($attribute, 'DateFormat')) { + return $result[1][0]; + } + } + + /** + * Get the date timestamp. + * + * @param mixed $value + * @return int + */ + protected function getDateTimestamp($value) + { + $date = is_null($value) ? null : $this->getDateTime($value); + + return $date ? $date->getTimestamp() : null; + } + + /** + * Given two date/time strings, check that one is after the other. + * + * @param string $format + * @param string $first + * @param string $second + * @param string $operator + * @return bool + */ + protected function checkDateTimeOrder($format, $first, $second, $operator) + { + $firstDate = $this->getDateTimeWithOptionalFormat($format, $first); + + if (! $secondDate = $this->getDateTimeWithOptionalFormat($format, $second)) { + if (is_null($second = $this->getValue($second))) { + return true; + } + + $secondDate = $this->getDateTimeWithOptionalFormat($format, $second); + } + + return ($firstDate && $secondDate) && ($this->compare($firstDate, $secondDate, $operator)); + } + + /** + * Get a DateTime instance from a string. + * + * @param string $format + * @param string $value + * @return \DateTime|null + */ + protected function getDateTimeWithOptionalFormat($format, $value) + { + if ($date = DateTime::createFromFormat('!'.$format, $value)) { + return $date; + } + + return $this->getDateTime($value); + } + + /** + * Get a DateTime instance from a string with no format. + * + * @param string $value + * @return \DateTime|null + */ + protected function getDateTime($value) + { + try { + return @Date::parse($value) ?: null; + } catch (Exception $e) { + // + } + } + + /** + * Validate that an attribute contains only alphabetic characters. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateAlpha($attribute, $value) + { + return is_string($value) && preg_match('/^[\pL\pM]+$/u', $value); + } + + /** + * Validate that an attribute contains only alpha-numeric characters, dashes, and underscores. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateAlphaDash($attribute, $value) + { + if (! is_string($value) && ! is_numeric($value)) { + return false; + } + + return preg_match('/^[\pL\pM\pN_-]+$/u', $value) > 0; + } + + /** + * Validate that an attribute contains only alpha-numeric characters. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateAlphaNum($attribute, $value) + { + if (! is_string($value) && ! is_numeric($value)) { + return false; + } + + return preg_match('/^[\pL\pM\pN]+$/u', $value) > 0; + } + + /** + * Validate that an attribute is an array. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateArray($attribute, $value, $parameters = []) + { + if (! is_array($value)) { + return false; + } + + if (empty($parameters)) { + return true; + } + + return empty(array_diff_key($value, array_fill_keys($parameters, ''))); + } + + /** + * Validate that an array has all of the given keys. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateRequiredArrayKeys($attribute, $value, $parameters) + { + if (! is_array($value)) { + return false; + } + + foreach ($parameters as $param) { + if (! Arr::exists($value, $param)) { + return false; + } + } + + return true; + } + + /** + * Validate the size of an attribute is between a set of values. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateBetween($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'between'); + + $size = $this->getSize($attribute, $value); + + return $size >= $parameters[0] && $size <= $parameters[1]; + } + + /** + * Validate that an attribute is a boolean. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateBoolean($attribute, $value) + { + $acceptable = [true, false, 0, 1, '0', '1']; + + return in_array($value, $acceptable, true); + } + + /** + * Validate that an attribute has a matching confirmation. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateConfirmed($attribute, $value) + { + return $this->validateSame($attribute, $value, [$attribute.'_confirmation']); + } + + /** + * Validate that the password of the currently authenticated user matches the given value. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + protected function validateCurrentPassword($attribute, $value, $parameters) + { + $auth = $this->container->make('auth'); + $hasher = $this->container->make('hash'); + + $guard = $auth->guard(Arr::first($parameters)); + + if ($guard->guest()) { + return false; + } + + return $hasher->check($value, $guard->user()->getAuthPassword()); + } + + /** + * Validate that an attribute is a valid date. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateDate($attribute, $value) + { + if ($value instanceof DateTimeInterface) { + return true; + } + + try { + if ((! is_string($value) && ! is_numeric($value)) || strtotime($value) === false) { + return false; + } + } catch (Exception $e) { + return false; + } + + $date = date_parse($value); + + return checkdate($date['month'], $date['day'], $date['year']); + } + + /** + * Validate that an attribute matches a date format. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDateFormat($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'date_format'); + + if (! is_string($value) && ! is_numeric($value)) { + return false; + } + + foreach ($parameters as $format) { + $date = DateTime::createFromFormat('!'.$format, $value); + + if ($date && $date->format($format) == $value) { + return true; + } + } + + return false; + } + + /** + * Validate that an attribute is equal to another date. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDateEquals($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'date_equals'); + + return $this->compareDates($attribute, $value, $parameters, '='); + } + + /** + * Validate that an attribute is different from another attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDifferent($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'different'); + + foreach ($parameters as $parameter) { + if (Arr::has($this->data, $parameter)) { + $other = Arr::get($this->data, $parameter); + + if ($value === $other) { + return false; + } + } + } + + return true; + } + + /** + * Validate that an attribute has a given number of digits. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDigits($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'digits'); + + return ! preg_match('/[^0-9]/', $value) + && strlen((string) $value) == $parameters[0]; + } + + /** + * Validate that an attribute is between a given number of digits. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDigitsBetween($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'digits_between'); + + $length = strlen((string) $value); + + return ! preg_match('/[^0-9]/', $value) + && $length >= $parameters[0] && $length <= $parameters[1]; + } + + /** + * Validate the dimensions of an image matches the given values. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDimensions($attribute, $value, $parameters) + { + if ($this->isValidFileInstance($value) && in_array($value->getMimeType(), ['image/svg+xml', 'image/svg'])) { + return true; + } + + if (! $this->isValidFileInstance($value) || ! $sizeDetails = @getimagesize($value->getRealPath())) { + return false; + } + + $this->requireParameterCount(1, $parameters, 'dimensions'); + + [$width, $height] = $sizeDetails; + + $parameters = $this->parseNamedParameters($parameters); + + if ($this->failsBasicDimensionChecks($parameters, $width, $height) || + $this->failsRatioCheck($parameters, $width, $height)) { + return false; + } + + return true; + } + + /** + * Test if the given width and height fail any conditions. + * + * @param array $parameters + * @param int $width + * @param int $height + * @return bool + */ + protected function failsBasicDimensionChecks($parameters, $width, $height) + { + return (isset($parameters['width']) && $parameters['width'] != $width) || + (isset($parameters['min_width']) && $parameters['min_width'] > $width) || + (isset($parameters['max_width']) && $parameters['max_width'] < $width) || + (isset($parameters['height']) && $parameters['height'] != $height) || + (isset($parameters['min_height']) && $parameters['min_height'] > $height) || + (isset($parameters['max_height']) && $parameters['max_height'] < $height); + } + + /** + * Determine if the given parameters fail a dimension ratio check. + * + * @param array $parameters + * @param int $width + * @param int $height + * @return bool + */ + protected function failsRatioCheck($parameters, $width, $height) + { + if (! isset($parameters['ratio'])) { + return false; + } + + [$numerator, $denominator] = array_replace( + [1, 1], array_filter(sscanf($parameters['ratio'], '%f/%d')) + ); + + $precision = 1 / (max($width, $height) + 1); + + return abs($numerator / $denominator - $width / $height) > $precision; + } + + /** + * Validate an attribute is unique among other values. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateDistinct($attribute, $value, $parameters) + { + $data = Arr::except($this->getDistinctValues($attribute), $attribute); + + if (in_array('ignore_case', $parameters)) { + return empty(preg_grep('/^'.preg_quote($value, '/').'$/iu', $data)); + } + + return ! in_array($value, array_values($data), in_array('strict', $parameters)); + } + + /** + * Get the values to distinct between. + * + * @param string $attribute + * @return array + */ + protected function getDistinctValues($attribute) + { + $attributeName = $this->getPrimaryAttribute($attribute); + + if (! property_exists($this, 'distinctValues')) { + return $this->extractDistinctValues($attributeName); + } + + if (! array_key_exists($attributeName, $this->distinctValues)) { + $this->distinctValues[$attributeName] = $this->extractDistinctValues($attributeName); + } + + return $this->distinctValues[$attributeName]; + } + + /** + * Extract the distinct values from the data. + * + * @param string $attribute + * @return array + */ + protected function extractDistinctValues($attribute) + { + $attributeData = ValidationData::extractDataFromPath( + ValidationData::getLeadingExplicitAttributePath($attribute), $this->data + ); + + $pattern = str_replace('\*', '[^.]+', preg_quote($attribute, '#')); + + return Arr::where(Arr::dot($attributeData), function ($value, $key) use ($pattern) { + return (bool) preg_match('#^'.$pattern.'\z#u', $key); + }); + } + + /** + * Validate that an attribute is a valid e-mail address. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateEmail($attribute, $value, $parameters) + { + if (! is_string($value) && ! (is_object($value) && method_exists($value, '__toString'))) { + return false; + } + + $validations = collect($parameters) + ->unique() + ->map(function ($validation) { + if ($validation === 'rfc') { + return new RFCValidation; + } elseif ($validation === 'strict') { + return new NoRFCWarningsValidation; + } elseif ($validation === 'dns') { + return new DNSCheckValidation; + } elseif ($validation === 'spoof') { + return new SpoofCheckValidation; + } elseif ($validation === 'filter') { + return new FilterEmailValidation; + } elseif ($validation === 'filter_unicode') { + return FilterEmailValidation::unicode(); + } elseif (is_string($validation) && class_exists($validation)) { + return $this->container->make($validation); + } + }) + ->values() + ->all() ?: [new RFCValidation]; + + return (new EmailValidator)->isValid($value, new MultipleValidationWithAnd($validations)); + } + + /** + * Validate the existence of an attribute value in a database table. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateExists($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'exists'); + + [$connection, $table] = $this->parseTable($parameters[0]); + + // The second parameter position holds the name of the column that should be + // verified as existing. If this parameter is not specified we will guess + // that the columns being "verified" shares the given attribute's name. + $column = $this->getQueryColumn($parameters, $attribute); + + $expected = is_array($value) ? count(array_unique($value)) : 1; + + return $this->getExistCount( + $connection, $table, $column, $value, $parameters + ) >= $expected; + } + + /** + * Get the number of records that exist in storage. + * + * @param mixed $connection + * @param string $table + * @param string $column + * @param mixed $value + * @param array $parameters + * @return int + */ + protected function getExistCount($connection, $table, $column, $value, $parameters) + { + $verifier = $this->getPresenceVerifier($connection); + + $extra = $this->getExtraConditions( + array_values(array_slice($parameters, 2)) + ); + + if ($this->currentRule instanceof Exists) { + $extra = array_merge($extra, $this->currentRule->queryCallbacks()); + } + + return is_array($value) + ? $verifier->getMultiCount($table, $column, $value, $extra) + : $verifier->getCount($table, $column, $value, null, null, $extra); + } + + /** + * Validate the uniqueness of an attribute value on a given database table. + * + * If a database column is not specified, the attribute will be used. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateUnique($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'unique'); + + [$connection, $table, $idColumn] = $this->parseTable($parameters[0]); + + // The second parameter position holds the name of the column that needs to + // be verified as unique. If this parameter isn't specified we will just + // assume that this column to be verified shares the attribute's name. + $column = $this->getQueryColumn($parameters, $attribute); + + $id = null; + + if (isset($parameters[2])) { + [$idColumn, $id] = $this->getUniqueIds($idColumn, $parameters); + + if (! is_null($id)) { + $id = stripslashes($id); + } + } + + // The presence verifier is responsible for counting rows within this store + // mechanism which might be a relational database or any other permanent + // data store like Redis, etc. We will use it to determine uniqueness. + $verifier = $this->getPresenceVerifier($connection); + + $extra = $this->getUniqueExtra($parameters); + + if ($this->currentRule instanceof Unique) { + $extra = array_merge($extra, $this->currentRule->queryCallbacks()); + } + + return $verifier->getCount( + $table, $column, $value, $id, $idColumn, $extra + ) == 0; + } + + /** + * Get the excluded ID column and value for the unique rule. + * + * @param string|null $idColumn + * @param array $parameters + * @return array + */ + protected function getUniqueIds($idColumn, $parameters) + { + $idColumn = $idColumn ?? $parameters[3] ?? 'id'; + + return [$idColumn, $this->prepareUniqueId($parameters[2])]; + } + + /** + * Prepare the given ID for querying. + * + * @param mixed $id + * @return int + */ + protected function prepareUniqueId($id) + { + if (preg_match('/\[(.*)\]/', $id, $matches)) { + $id = $this->getValue($matches[1]); + } + + if (strtolower($id) === 'null') { + $id = null; + } + + if (filter_var($id, FILTER_VALIDATE_INT) !== false) { + $id = (int) $id; + } + + return $id; + } + + /** + * Get the extra conditions for a unique rule. + * + * @param array $parameters + * @return array + */ + protected function getUniqueExtra($parameters) + { + if (isset($parameters[4])) { + return $this->getExtraConditions(array_slice($parameters, 4)); + } + + return []; + } + + /** + * Parse the connection / table for the unique / exists rules. + * + * @param string $table + * @return array + */ + public function parseTable($table) + { + [$connection, $table] = Str::contains($table, '.') ? explode('.', $table, 2) : [null, $table]; + + if (Str::contains($table, '\\') && class_exists($table) && is_a($table, Model::class, true)) { + $model = new $table; + + $table = $model->getTable(); + $connection = $connection ?? $model->getConnectionName(); + + if (Str::contains($table, '.') && Str::startsWith($table, $connection)) { + $connection = null; + } + + $idColumn = $model->getKeyName(); + } + + return [$connection, $table, $idColumn ?? null]; + } + + /** + * Get the column name for an exists / unique query. + * + * @param array $parameters + * @param string $attribute + * @return bool + */ + public function getQueryColumn($parameters, $attribute) + { + return isset($parameters[1]) && $parameters[1] !== 'NULL' + ? $parameters[1] : $this->guessColumnForQuery($attribute); + } + + /** + * Guess the database column from the given attribute name. + * + * @param string $attribute + * @return string + */ + public function guessColumnForQuery($attribute) + { + if (in_array($attribute, Arr::collapse($this->implicitAttributes)) + && ! is_numeric($last = last(explode('.', $attribute)))) { + return $last; + } + + return $attribute; + } + + /** + * Get the extra conditions for a unique / exists rule. + * + * @param array $segments + * @return array + */ + protected function getExtraConditions(array $segments) + { + $extra = []; + + $count = count($segments); + + for ($i = 0; $i < $count; $i += 2) { + $extra[$segments[$i]] = $segments[$i + 1]; + } + + return $extra; + } + + /** + * Validate the given value is a valid file. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateFile($attribute, $value) + { + return $this->isValidFileInstance($value); + } + + /** + * Validate the given attribute is filled if it is present. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateFilled($attribute, $value) + { + if (Arr::has($this->data, $attribute)) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that an attribute is greater than another attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateGt($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'gt'); + + $comparedToValue = $this->getValue($parameters[0]); + + $this->shouldBeNumeric($attribute, 'Gt'); + + if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) { + return $this->getSize($attribute, $value) > $parameters[0]; + } + + if (is_numeric($parameters[0])) { + return false; + } + + if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) { + return $value > $comparedToValue; + } + + if (! $this->isSameType($value, $comparedToValue)) { + return false; + } + + return $this->getSize($attribute, $value) > $this->getSize($attribute, $comparedToValue); + } + + /** + * Validate that an attribute is less than another attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateLt($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'lt'); + + $comparedToValue = $this->getValue($parameters[0]); + + $this->shouldBeNumeric($attribute, 'Lt'); + + if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) { + return $this->getSize($attribute, $value) < $parameters[0]; + } + + if (is_numeric($parameters[0])) { + return false; + } + + if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) { + return $value < $comparedToValue; + } + + if (! $this->isSameType($value, $comparedToValue)) { + return false; + } + + return $this->getSize($attribute, $value) < $this->getSize($attribute, $comparedToValue); + } + + /** + * Validate that an attribute is greater than or equal another attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateGte($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'gte'); + + $comparedToValue = $this->getValue($parameters[0]); + + $this->shouldBeNumeric($attribute, 'Gte'); + + if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) { + return $this->getSize($attribute, $value) >= $parameters[0]; + } + + if (is_numeric($parameters[0])) { + return false; + } + + if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) { + return $value >= $comparedToValue; + } + + if (! $this->isSameType($value, $comparedToValue)) { + return false; + } + + return $this->getSize($attribute, $value) >= $this->getSize($attribute, $comparedToValue); + } + + /** + * Validate that an attribute is less than or equal another attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateLte($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'lte'); + + $comparedToValue = $this->getValue($parameters[0]); + + $this->shouldBeNumeric($attribute, 'Lte'); + + if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) { + return $this->getSize($attribute, $value) <= $parameters[0]; + } + + if (is_numeric($parameters[0])) { + return false; + } + + if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) { + return $value <= $comparedToValue; + } + + if (! $this->isSameType($value, $comparedToValue)) { + return false; + } + + return $this->getSize($attribute, $value) <= $this->getSize($attribute, $comparedToValue); + } + + /** + * Validate the MIME type of a file is an image MIME type. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateImage($attribute, $value) + { + return $this->validateMimes($attribute, $value, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp']); + } + + /** + * Validate an attribute is contained within a list of values. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateIn($attribute, $value, $parameters) + { + if (is_array($value) && $this->hasRule($attribute, 'Array')) { + foreach ($value as $element) { + if (is_array($element)) { + return false; + } + } + + return count(array_diff($value, $parameters)) === 0; + } + + return ! is_array($value) && in_array((string) $value, $parameters); + } + + /** + * Validate that the values of an attribute are in another attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateInArray($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'in_array'); + + $explicitPath = ValidationData::getLeadingExplicitAttributePath($parameters[0]); + + $attributeData = ValidationData::extractDataFromPath($explicitPath, $this->data); + + $otherValues = Arr::where(Arr::dot($attributeData), function ($value, $key) use ($parameters) { + return Str::is($parameters[0], $key); + }); + + return in_array($value, $otherValues); + } + + /** + * Validate that an attribute is an integer. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateInteger($attribute, $value) + { + return filter_var($value, FILTER_VALIDATE_INT) !== false; + } + + /** + * Validate that an attribute is a valid IP. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateIp($attribute, $value) + { + return filter_var($value, FILTER_VALIDATE_IP) !== false; + } + + /** + * Validate that an attribute is a valid IPv4. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateIpv4($attribute, $value) + { + return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; + } + + /** + * Validate that an attribute is a valid IPv6. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateIpv6($attribute, $value) + { + return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + } + + /** + * Validate that an attribute is a valid MAC address. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateMacAddress($attribute, $value) + { + return filter_var($value, FILTER_VALIDATE_MAC) !== false; + } + + /** + * Validate the attribute is a valid JSON string. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateJson($attribute, $value) + { + if (is_array($value)) { + return false; + } + + if (! is_scalar($value) && ! is_null($value) && ! method_exists($value, '__toString')) { + return false; + } + + json_decode($value); + + return json_last_error() === JSON_ERROR_NONE; + } + + /** + * Validate the size of an attribute is less than a maximum value. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateMax($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'max'); + + if ($value instanceof UploadedFile && ! $value->isValid()) { + return false; + } + + return $this->getSize($attribute, $value) <= $parameters[0]; + } + + /** + * Validate the guessed extension of a file upload is in a set of file extensions. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateMimes($attribute, $value, $parameters) + { + if (! $this->isValidFileInstance($value)) { + return false; + } + + if ($this->shouldBlockPhpUpload($value, $parameters)) { + return false; + } + + if (in_array('jpg', $parameters) || in_array('jpeg', $parameters)) { + $parameters = array_unique(array_merge($parameters, ['jpg', 'jpeg'])); + } + + return $value->getPath() !== '' && in_array($value->guessExtension(), $parameters); + } + + /** + * Validate the MIME type of a file upload attribute is in a set of MIME types. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateMimetypes($attribute, $value, $parameters) + { + if (! $this->isValidFileInstance($value)) { + return false; + } + + if ($this->shouldBlockPhpUpload($value, $parameters)) { + return false; + } + + return $value->getPath() !== '' && + (in_array($value->getMimeType(), $parameters) || + in_array(explode('/', $value->getMimeType())[0].'/*', $parameters)); + } + + /** + * Check if PHP uploads are explicitly allowed. + * + * @param mixed $value + * @param array $parameters + * @return bool + */ + protected function shouldBlockPhpUpload($value, $parameters) + { + if (in_array('php', $parameters)) { + return false; + } + + $phpExtensions = [ + 'php', 'php3', 'php4', 'php5', 'phtml', 'phar', + ]; + + return ($value instanceof UploadedFile) + ? in_array(trim(strtolower($value->getClientOriginalExtension())), $phpExtensions) + : in_array(trim(strtolower($value->getExtension())), $phpExtensions); + } + + /** + * Validate the size of an attribute is greater than a minimum value. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateMin($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'min'); + + return $this->getSize($attribute, $value) >= $parameters[0]; + } + + /** + * Validate the value of an attribute is a multiple of a given value. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateMultipleOf($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'multiple_of'); + + if (! $this->validateNumeric($attribute, $value) || ! $this->validateNumeric($attribute, $parameters[0])) { + return false; + } + + if ((float) $parameters[0] === 0.0) { + return false; + } + + return bcmod($value, $parameters[0], 16) === '0.0000000000000000'; + } + + /** + * "Indicate" validation should pass if value is null. + * + * Always returns true, just lets us put "nullable" in rules. + * + * @return bool + */ + public function validateNullable() + { + return true; + } + + /** + * Validate an attribute is not contained within a list of values. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateNotIn($attribute, $value, $parameters) + { + return ! $this->validateIn($attribute, $value, $parameters); + } + + /** + * Validate that an attribute is numeric. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateNumeric($attribute, $value) + { + return is_numeric($value); + } + + /** + * Validate that the password of the currently authenticated user matches the given value. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + protected function validatePassword($attribute, $value, $parameters) + { + return $this->validateCurrentPassword($attribute, $value, $parameters); + } + + /** + * Validate that an attribute exists even if not filled. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validatePresent($attribute, $value) + { + return Arr::has($this->data, $attribute); + } + + /** + * Validate that an attribute passes a regular expression check. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateRegex($attribute, $value, $parameters) + { + if (! is_string($value) && ! is_numeric($value)) { + return false; + } + + $this->requireParameterCount(1, $parameters, 'regex'); + + return preg_match($parameters[0], $value) > 0; + } + + /** + * Validate that an attribute does not pass a regular expression check. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateNotRegex($attribute, $value, $parameters) + { + if (! is_string($value) && ! is_numeric($value)) { + return false; + } + + $this->requireParameterCount(1, $parameters, 'not_regex'); + + return preg_match($parameters[0], $value) < 1; + } + + /** + * Validate that a required attribute exists. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateRequired($attribute, $value) + { + if (is_null($value)) { + return false; + } elseif (is_string($value) && trim($value) === '') { + return false; + } elseif ((is_array($value) || $value instanceof Countable) && count($value) < 1) { + return false; + } elseif ($value instanceof File) { + return (string) $value->getPath() !== ''; + } + + return true; + } + + /** + * Validate that an attribute exists when another attribute has a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateRequiredIf($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'required_if'); + + if (! Arr::has($this->data, $parameters[0])) { + return true; + } + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + if (in_array($other, $values, is_bool($other) || is_null($other))) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that an attribute does not exist. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateProhibited($attribute, $value) + { + return false; + } + + /** + * Validate that an attribute does not exist when another attribute has a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateProhibitedIf($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'prohibited_if'); + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + if (in_array($other, $values, is_bool($other) || is_null($other))) { + return ! $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that an attribute does not exist unless another attribute has a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateProhibitedUnless($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'prohibited_unless'); + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + if (! in_array($other, $values, is_bool($other) || is_null($other))) { + return ! $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that other attributes do not exist when this attribute exists. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateProhibits($attribute, $value, $parameters) + { + return ! Arr::hasAny($this->data, $parameters); + } + + /** + * Indicate that an attribute is excluded. + * + * @return bool + */ + public function validateExclude() + { + return false; + } + + /** + * Indicate that an attribute should be excluded when another attribute has a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateExcludeIf($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'exclude_if'); + + if (! Arr::has($this->data, $parameters[0])) { + return true; + } + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + return ! in_array($other, $values, is_bool($other) || is_null($other)); + } + + /** + * Indicate that an attribute should be excluded when another attribute does not have a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateExcludeUnless($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'exclude_unless'); + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + return in_array($other, $values, is_bool($other) || is_null($other)); + } + + /** + * Validate that an attribute exists when another attribute does not have a given value. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateRequiredUnless($attribute, $value, $parameters) + { + $this->requireParameterCount(2, $parameters, 'required_unless'); + + [$values, $other] = $this->parseDependentRuleParameters($parameters); + + if (! in_array($other, $values, is_bool($other) || is_null($other))) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Indicate that an attribute should be excluded when another attribute is missing. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateExcludeWithout($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'exclude_without'); + + if ($this->anyFailingRequired($parameters)) { + return false; + } + + return true; + } + + /** + * Prepare the values and the other value for validation. + * + * @param array $parameters + * @return array + */ + public function parseDependentRuleParameters($parameters) + { + $other = Arr::get($this->data, $parameters[0]); + + $values = array_slice($parameters, 1); + + if ($this->shouldConvertToBoolean($parameters[0]) || is_bool($other)) { + $values = $this->convertValuesToBoolean($values); + } + + if (is_null($other)) { + $values = $this->convertValuesToNull($values); + } + + return [$values, $other]; + } + + /** + * Check if parameter should be converted to boolean. + * + * @param string $parameter + * @return bool + */ + protected function shouldConvertToBoolean($parameter) + { + return in_array('boolean', Arr::get($this->rules, $parameter, [])); + } + + /** + * Convert the given values to boolean if they are string "true" / "false". + * + * @param array $values + * @return array + */ + protected function convertValuesToBoolean($values) + { + return array_map(function ($value) { + if ($value === 'true') { + return true; + } elseif ($value === 'false') { + return false; + } + + return $value; + }, $values); + } + + /** + * Convert the given values to null if they are string "null". + * + * @param array $values + * @return array + */ + protected function convertValuesToNull($values) + { + return array_map(function ($value) { + return Str::lower($value) === 'null' ? null : $value; + }, $values); + } + + /** + * Validate that an attribute exists when any other attribute exists. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateRequiredWith($attribute, $value, $parameters) + { + if (! $this->allFailingRequired($parameters)) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that an attribute exists when all other attributes exist. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateRequiredWithAll($attribute, $value, $parameters) + { + if (! $this->anyFailingRequired($parameters)) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that an attribute exists when another attribute does not. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateRequiredWithout($attribute, $value, $parameters) + { + if ($this->anyFailingRequired($parameters)) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Validate that an attribute exists when all other attributes do not. + * + * @param string $attribute + * @param mixed $value + * @param mixed $parameters + * @return bool + */ + public function validateRequiredWithoutAll($attribute, $value, $parameters) + { + if ($this->allFailingRequired($parameters)) { + return $this->validateRequired($attribute, $value); + } + + return true; + } + + /** + * Determine if any of the given attributes fail the required test. + * + * @param array $attributes + * @return bool + */ + protected function anyFailingRequired(array $attributes) + { + foreach ($attributes as $key) { + if (! $this->validateRequired($key, $this->getValue($key))) { + return true; + } + } + + return false; + } + + /** + * Determine if all of the given attributes fail the required test. + * + * @param array $attributes + * @return bool + */ + protected function allFailingRequired(array $attributes) + { + foreach ($attributes as $key) { + if ($this->validateRequired($key, $this->getValue($key))) { + return false; + } + } + + return true; + } + + /** + * Validate that two attributes match. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateSame($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'same'); + + $other = Arr::get($this->data, $parameters[0]); + + return $value === $other; + } + + /** + * Validate the size of an attribute. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateSize($attribute, $value, $parameters) + { + $this->requireParameterCount(1, $parameters, 'size'); + + return $this->getSize($attribute, $value) == $parameters[0]; + } + + /** + * "Validate" optional attributes. + * + * Always returns true, just lets us put sometimes in rules. + * + * @return bool + */ + public function validateSometimes() + { + return true; + } + + /** + * Validate the attribute starts with a given substring. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateStartsWith($attribute, $value, $parameters) + { + return Str::startsWith($value, $parameters); + } + + /** + * Validate the attribute ends with a given substring. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + public function validateEndsWith($attribute, $value, $parameters) + { + return Str::endsWith($value, $parameters); + } + + /** + * Validate that an attribute is a string. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateString($attribute, $value) + { + return is_string($value); + } + + /** + * Validate that an attribute is a valid timezone. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateTimezone($attribute, $value) + { + return in_array($value, timezone_identifiers_list(), true); + } + + /** + * Validate that an attribute is a valid URL. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateUrl($attribute, $value) + { + if (! is_string($value)) { + return false; + } + + /* + * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7). + * + * (c) Fabien Potencier http://symfony.com + */ + $pattern = '~^ + (aaa|aaas|about|acap|acct|acd|acr|adiumxtra|adt|afp|afs|aim|amss|android|appdata|apt|ark|attachment|aw|barion|beshare|bitcoin|bitcoincash|blob|bolo|browserext|calculator|callto|cap|cast|casts|chrome|chrome-extension|cid|coap|coap\+tcp|coap\+ws|coaps|coaps\+tcp|coaps\+ws|com-eventbrite-attendee|content|conti|crid|cvs|dab|data|dav|diaspora|dict|did|dis|dlna-playcontainer|dlna-playsingle|dns|dntp|dpp|drm|drop|dtn|dvb|ed2k|elsi|example|facetime|fax|feed|feedready|file|filesystem|finger|first-run-pen-experience|fish|fm|ftp|fuchsia-pkg|geo|gg|git|gizmoproject|go|gopher|graph|gtalk|h323|ham|hcap|hcp|http|https|hxxp|hxxps|hydrazone|iax|icap|icon|im|imap|info|iotdisco|ipn|ipp|ipps|irc|irc6|ircs|iris|iris\.beep|iris\.lwz|iris\.xpc|iris\.xpcs|isostore|itms|jabber|jar|jms|keyparc|lastfm|ldap|ldaps|leaptofrogans|lorawan|lvlt|magnet|mailserver|mailto|maps|market|message|mid|mms|modem|mongodb|moz|ms-access|ms-browser-extension|ms-calculator|ms-drive-to|ms-enrollment|ms-excel|ms-eyecontrolspeech|ms-gamebarservices|ms-gamingoverlay|ms-getoffice|ms-help|ms-infopath|ms-inputapp|ms-lockscreencomponent-config|ms-media-stream-id|ms-mixedrealitycapture|ms-mobileplans|ms-officeapp|ms-people|ms-project|ms-powerpoint|ms-publisher|ms-restoretabcompanion|ms-screenclip|ms-screensketch|ms-search|ms-search-repair|ms-secondary-screen-controller|ms-secondary-screen-setup|ms-settings|ms-settings-airplanemode|ms-settings-bluetooth|ms-settings-camera|ms-settings-cellular|ms-settings-cloudstorage|ms-settings-connectabledevices|ms-settings-displays-topology|ms-settings-emailandaccounts|ms-settings-language|ms-settings-location|ms-settings-lock|ms-settings-nfctransactions|ms-settings-notifications|ms-settings-power|ms-settings-privacy|ms-settings-proximity|ms-settings-screenrotation|ms-settings-wifi|ms-settings-workplace|ms-spd|ms-sttoverlay|ms-transit-to|ms-useractivityset|ms-virtualtouchpad|ms-visio|ms-walk-to|ms-whiteboard|ms-whiteboard-cmd|ms-word|msnim|msrp|msrps|mss|mtqp|mumble|mupdate|mvn|news|nfs|ni|nih|nntp|notes|ocf|oid|onenote|onenote-cmd|opaquelocktoken|openpgp4fpr|pack|palm|paparazzi|payto|pkcs11|platform|pop|pres|prospero|proxy|pwid|psyc|pttp|qb|query|redis|rediss|reload|res|resource|rmi|rsync|rtmfp|rtmp|rtsp|rtsps|rtspu|s3|secondlife|service|session|sftp|sgn|shttp|sieve|simpleledger|sip|sips|skype|smb|sms|smtp|snews|snmp|soap\.beep|soap\.beeps|soldat|spiffe|spotify|ssh|steam|stun|stuns|submit|svn|tag|teamspeak|tel|teliaeid|telnet|tftp|tg|things|thismessage|tip|tn3270|tool|ts3server|turn|turns|tv|udp|unreal|urn|ut2004|v-event|vemmi|ventrilo|videotex|vnc|view-source|wais|webcal|wpid|ws|wss|wtai|wyciwyg|xcon|xcon-userid|xfire|xmlrpc\.beep|xmlrpc\.beeps|xmpp|xri|ymsgr|z39\.50|z39\.50r|z39\.50s):// # protocol + (((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth + ( + ([\pL\pN\pS\-\_\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name + | # or + \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address + | # or + \[ + (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) + \] # an IPv6 address + ) + (:[0-9]+)? # a port (optional) + (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path + (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional) + (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional) + $~ixu'; + + return preg_match($pattern, $value) > 0; + } + + /** + * Validate that an attribute is a valid UUID. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function validateUuid($attribute, $value) + { + return Str::isUuid($value); + } + + /** + * Get the size of an attribute. + * + * @param string $attribute + * @param mixed $value + * @return mixed + */ + protected function getSize($attribute, $value) + { + $hasNumeric = $this->hasRule($attribute, $this->numericRules); + + // This method will determine if the attribute is a number, string, or file and + // return the proper size accordingly. If it is a number, then number itself + // is the size. If it is a file, we take kilobytes, and for a string the + // entire length of the string will be considered the attribute size. + if (is_numeric($value) && $hasNumeric) { + return $value; + } elseif (is_array($value)) { + return count($value); + } elseif ($value instanceof File) { + return $value->getSize() / 1024; + } + + return mb_strlen($value ?? ''); + } + + /** + * Check that the given value is a valid file instance. + * + * @param mixed $value + * @return bool + */ + public function isValidFileInstance($value) + { + if ($value instanceof UploadedFile && ! $value->isValid()) { + return false; + } + + return $value instanceof File; + } + + /** + * Determine if a comparison passes between the given values. + * + * @param mixed $first + * @param mixed $second + * @param string $operator + * @return bool + * + * @throws \InvalidArgumentException + */ + protected function compare($first, $second, $operator) + { + switch ($operator) { + case '<': + return $first < $second; + case '>': + return $first > $second; + case '<=': + return $first <= $second; + case '>=': + return $first >= $second; + case '=': + return $first == $second; + default: + throw new InvalidArgumentException; + } + } + + /** + * Parse named parameters to $key => $value items. + * + * @param array $parameters + * @return array + */ + public function parseNamedParameters($parameters) + { + return array_reduce($parameters, function ($result, $item) { + [$key, $value] = array_pad(explode('=', $item, 2), 2, null); + + $result[$key] = $value; + + return $result; + }); + } + + /** + * Require a certain number of parameters to be present. + * + * @param int $count + * @param array $parameters + * @param string $rule + * @return void + * + * @throws \InvalidArgumentException + */ + public function requireParameterCount($count, $parameters, $rule) + { + if (count($parameters) < $count) { + throw new InvalidArgumentException("Validation rule $rule requires at least $count parameters."); + } + } + + /** + * Check if the parameters are of the same type. + * + * @param mixed $first + * @param mixed $second + * @return bool + */ + protected function isSameType($first, $second) + { + return gettype($first) == gettype($second); + } + + /** + * Adds the existing rule to the numericRules array if the attribute's value is numeric. + * + * @param string $attribute + * @param string $rule + * @return void + */ + protected function shouldBeNumeric($attribute, $rule) + { + if (is_numeric($this->getValue($attribute))) { + $this->numericRules[] = $rule; + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ConditionalRules.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ConditionalRules.php new file mode 100644 index 0000000..d52455a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ConditionalRules.php @@ -0,0 +1,77 @@ +condition = $condition; + $this->rules = $rules; + $this->defaultRules = $defaultRules; + } + + /** + * Determine if the conditional rules should be added. + * + * @param array $data + * @return bool + */ + public function passes(array $data = []) + { + return is_callable($this->condition) + ? call_user_func($this->condition, new Fluent($data)) + : $this->condition; + } + + /** + * Get the rules. + * + * @return array + */ + public function rules() + { + return is_string($this->rules) ? explode('|', $this->rules) : $this->rules; + } + + /** + * Get the default rules. + * + * @return array + */ + public function defaultRules() + { + return is_string($this->defaultRules) ? explode('|', $this->defaultRules) : $this->defaultRules; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifier.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifier.php new file mode 100755 index 0000000..b5255e3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifier.php @@ -0,0 +1,138 @@ +db = $db; + } + + /** + * Count the number of objects in a collection having the given value. + * + * @param string $collection + * @param string $column + * @param string $value + * @param int|null $excludeId + * @param string|null $idColumn + * @param array $extra + * @return int + */ + public function getCount($collection, $column, $value, $excludeId = null, $idColumn = null, array $extra = []) + { + $query = $this->table($collection)->where($column, '=', $value); + + if (! is_null($excludeId) && $excludeId !== 'NULL') { + $query->where($idColumn ?: 'id', '<>', $excludeId); + } + + return $this->addConditions($query, $extra)->count(); + } + + /** + * Count the number of objects in a collection with the given values. + * + * @param string $collection + * @param string $column + * @param array $values + * @param array $extra + * @return int + */ + public function getMultiCount($collection, $column, array $values, array $extra = []) + { + $query = $this->table($collection)->whereIn($column, $values); + + return $this->addConditions($query, $extra)->distinct()->count($column); + } + + /** + * Add the given conditions to the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $conditions + * @return \Illuminate\Database\Query\Builder + */ + protected function addConditions($query, $conditions) + { + foreach ($conditions as $key => $value) { + if ($value instanceof Closure) { + $query->where(function ($query) use ($value) { + $value($query); + }); + } else { + $this->addWhere($query, $key, $value); + } + } + + return $query; + } + + /** + * Add a "where" clause to the given query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $key + * @param string $extraValue + * @return void + */ + protected function addWhere($query, $key, $extraValue) + { + if ($extraValue === 'NULL') { + $query->whereNull($key); + } elseif ($extraValue === 'NOT_NULL') { + $query->whereNotNull($key); + } elseif (Str::startsWith($extraValue, '!')) { + $query->where($key, '!=', mb_substr($extraValue, 1)); + } else { + $query->where($key, $extraValue); + } + } + + /** + * Get a query builder for the given table. + * + * @param string $table + * @return \Illuminate\Database\Query\Builder + */ + protected function table($table) + { + return $this->db->connection($this->connection)->table($table)->useWritePdo(); + } + + /** + * Set the connection to be used. + * + * @param string $connection + * @return void + */ + public function setConnection($connection) + { + $this->connection = $connection; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifierInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifierInterface.php new file mode 100755 index 0000000..4b70ee0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifierInterface.php @@ -0,0 +1,14 @@ +container = $container; + $this->translator = $translator; + } + + /** + * Create a new Validator instance. + * + * @param array $data + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return \Illuminate\Validation\Validator + */ + public function make(array $data, array $rules, array $messages = [], array $customAttributes = []) + { + $validator = $this->resolve( + $data, $rules, $messages, $customAttributes + ); + + // The presence verifier is responsible for checking the unique and exists data + // for the validator. It is behind an interface so that multiple versions of + // it may be written besides database. We'll inject it into the validator. + if (! is_null($this->verifier)) { + $validator->setPresenceVerifier($this->verifier); + } + + // Next we'll set the IoC container instance of the validator, which is used to + // resolve out class based validator extensions. If it is not set then these + // types of extensions will not be possible on these validation instances. + if (! is_null($this->container)) { + $validator->setContainer($this->container); + } + + $validator->excludeUnvalidatedArrayKeys = $this->excludeUnvalidatedArrayKeys; + + $this->addExtensions($validator); + + return $validator; + } + + /** + * Validate the given data against the provided rules. + * + * @param array $data + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return array + * + * @throws \Illuminate\Validation\ValidationException + */ + public function validate(array $data, array $rules, array $messages = [], array $customAttributes = []) + { + return $this->make($data, $rules, $messages, $customAttributes)->validate(); + } + + /** + * Resolve a new Validator instance. + * + * @param array $data + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return \Illuminate\Validation\Validator + */ + protected function resolve(array $data, array $rules, array $messages, array $customAttributes) + { + if (is_null($this->resolver)) { + return new Validator($this->translator, $data, $rules, $messages, $customAttributes); + } + + return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes); + } + + /** + * Add the extensions to a validator instance. + * + * @param \Illuminate\Validation\Validator $validator + * @return void + */ + protected function addExtensions(Validator $validator) + { + $validator->addExtensions($this->extensions); + + // Next, we will add the implicit extensions, which are similar to the required + // and accepted rule in that they are run even if the attributes is not in a + // array of data that is given to a validator instances via instantiation. + $validator->addImplicitExtensions($this->implicitExtensions); + + $validator->addDependentExtensions($this->dependentExtensions); + + $validator->addReplacers($this->replacers); + + $validator->setFallbackMessages($this->fallbackMessages); + } + + /** + * Register a custom validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @param string|null $message + * @return void + */ + public function extend($rule, $extension, $message = null) + { + $this->extensions[$rule] = $extension; + + if ($message) { + $this->fallbackMessages[Str::snake($rule)] = $message; + } + } + + /** + * Register a custom implicit validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @param string|null $message + * @return void + */ + public function extendImplicit($rule, $extension, $message = null) + { + $this->implicitExtensions[$rule] = $extension; + + if ($message) { + $this->fallbackMessages[Str::snake($rule)] = $message; + } + } + + /** + * Register a custom dependent validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @param string|null $message + * @return void + */ + public function extendDependent($rule, $extension, $message = null) + { + $this->dependentExtensions[$rule] = $extension; + + if ($message) { + $this->fallbackMessages[Str::snake($rule)] = $message; + } + } + + /** + * Register a custom validator message replacer. + * + * @param string $rule + * @param \Closure|string $replacer + * @return void + */ + public function replacer($rule, $replacer) + { + $this->replacers[$rule] = $replacer; + } + + /** + * Indicate that unvalidated array keys should be excluded, even if the parent array was validated. + * + * @return void + */ + public function excludeUnvalidatedArrayKeys() + { + $this->excludeUnvalidatedArrayKeys = true; + } + + /** + * Set the Validator instance resolver. + * + * @param \Closure $resolver + * @return void + */ + public function resolver(Closure $resolver) + { + $this->resolver = $resolver; + } + + /** + * Get the Translator implementation. + * + * @return \Illuminate\Contracts\Translation\Translator + */ + public function getTranslator() + { + return $this->translator; + } + + /** + * Get the Presence Verifier implementation. + * + * @return \Illuminate\Validation\PresenceVerifierInterface + */ + public function getPresenceVerifier() + { + return $this->verifier; + } + + /** + * Set the Presence Verifier implementation. + * + * @param \Illuminate\Validation\PresenceVerifierInterface $presenceVerifier + * @return void + */ + public function setPresenceVerifier(PresenceVerifierInterface $presenceVerifier) + { + $this->verifier = $presenceVerifier; + } + + /** + * Get the container instance used by the validation factory. + * + * @return \Illuminate\Contracts\Container\Container + */ + public function getContainer() + { + return $this->container; + } + + /** + * Set the container instance used by the validation factory. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return $this + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/NotPwnedVerifier.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/NotPwnedVerifier.php new file mode 100644 index 0000000..f1c2f1d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/NotPwnedVerifier.php @@ -0,0 +1,104 @@ +factory = $factory; + $this->timeout = $timeout ?? 30; + } + + /** + * Verify that the given data has not been compromised in public breaches. + * + * @param array $data + * @return bool + */ + public function verify($data) + { + $value = $data['value']; + $threshold = $data['threshold']; + + if (empty($value = (string) $value)) { + return false; + } + + [$hash, $hashPrefix] = $this->getHash($value); + + return ! $this->search($hashPrefix) + ->contains(function ($line) use ($hash, $hashPrefix, $threshold) { + [$hashSuffix, $count] = explode(':', $line); + + return $hashPrefix.$hashSuffix == $hash && $count > $threshold; + }); + } + + /** + * Get the hash and its first 5 chars. + * + * @param string $value + * @return array + */ + protected function getHash($value) + { + $hash = strtoupper(sha1((string) $value)); + + $hashPrefix = substr($hash, 0, 5); + + return [$hash, $hashPrefix]; + } + + /** + * Search by the given hash prefix and returns all occurrences of leaked passwords. + * + * @param string $hashPrefix + * @return \Illuminate\Support\Collection + */ + protected function search($hashPrefix) + { + try { + $response = $this->factory->withHeaders([ + 'Add-Padding' => true, + ])->timeout($this->timeout)->get( + 'https://api.pwnedpasswords.com/range/'.$hashPrefix + ); + } catch (Exception $e) { + report($e); + } + + $body = (isset($response) && $response->successful()) + ? $response->body() + : ''; + + return Str::of($body)->trim()->explode("\n")->filter(function ($line) { + return Str::contains($line, ':'); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/PresenceVerifierInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/PresenceVerifierInterface.php new file mode 100755 index 0000000..da58a12 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/PresenceVerifierInterface.php @@ -0,0 +1,30 @@ +toArray(); + } + + return new In(is_array($values) ? $values : func_get_args()); + } + + /** + * Get a not_in constraint builder instance. + * + * @param \Illuminate\Contracts\Support\Arrayable|array|string $values + * @return \Illuminate\Validation\Rules\NotIn + */ + public static function notIn($values) + { + if ($values instanceof Arrayable) { + $values = $values->toArray(); + } + + return new NotIn(is_array($values) ? $values : func_get_args()); + } + + /** + * Get a required_if constraint builder instance. + * + * @param callable|bool $callback + * @return \Illuminate\Validation\Rules\RequiredIf + */ + public static function requiredIf($callback) + { + return new RequiredIf($callback); + } + + /** + * Get a unique constraint builder instance. + * + * @param string $table + * @param string $column + * @return \Illuminate\Validation\Rules\Unique + */ + public static function unique($table, $column = 'NULL') + { + return new Unique($table, $column); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/DatabaseRule.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/DatabaseRule.php new file mode 100644 index 0000000..7789008 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/DatabaseRule.php @@ -0,0 +1,206 @@ +column = $column; + + $this->table = $this->resolveTableName($table); + } + + /** + * Resolves the name of the table from the given string. + * + * @param string $table + * @return string + */ + public function resolveTableName($table) + { + if (! Str::contains($table, '\\') || ! class_exists($table)) { + return $table; + } + + if (is_subclass_of($table, Model::class)) { + $model = new $table; + + if (Str::contains($model->getTable(), '.')) { + return $table; + } + + return implode('.', array_map(function (string $part) { + return trim($part, '.'); + }, array_filter([$model->getConnectionName(), $model->getTable()]))); + } + + return $table; + } + + /** + * Set a "where" constraint on the query. + * + * @param \Closure|string $column + * @param array|string|int|null $value + * @return $this + */ + public function where($column, $value = null) + { + if (is_array($value)) { + return $this->whereIn($column, $value); + } + + if ($column instanceof Closure) { + return $this->using($column); + } + + if (is_null($value)) { + return $this->whereNull($column); + } + + $this->wheres[] = compact('column', 'value'); + + return $this; + } + + /** + * Set a "where not" constraint on the query. + * + * @param string $column + * @param array|string $value + * @return $this + */ + public function whereNot($column, $value) + { + if (is_array($value)) { + return $this->whereNotIn($column, $value); + } + + return $this->where($column, '!'.$value); + } + + /** + * Set a "where null" constraint on the query. + * + * @param string $column + * @return $this + */ + public function whereNull($column) + { + return $this->where($column, 'NULL'); + } + + /** + * Set a "where not null" constraint on the query. + * + * @param string $column + * @return $this + */ + public function whereNotNull($column) + { + return $this->where($column, 'NOT_NULL'); + } + + /** + * Set a "where in" constraint on the query. + * + * @param string $column + * @param array $values + * @return $this + */ + public function whereIn($column, array $values) + { + return $this->where(function ($query) use ($column, $values) { + $query->whereIn($column, $values); + }); + } + + /** + * Set a "where not in" constraint on the query. + * + * @param string $column + * @param array $values + * @return $this + */ + public function whereNotIn($column, array $values) + { + return $this->where(function ($query) use ($column, $values) { + $query->whereNotIn($column, $values); + }); + } + + /** + * Register a custom query callback. + * + * @param \Closure $callback + * @return $this + */ + public function using(Closure $callback) + { + $this->using[] = $callback; + + return $this; + } + + /** + * Get the custom query callbacks for the rule. + * + * @return array + */ + public function queryCallbacks() + { + return $this->using; + } + + /** + * Format the where clauses. + * + * @return string + */ + protected function formatWheres() + { + return collect($this->wheres)->map(function ($where) { + return $where['column'].','.'"'.str_replace('"', '""', $where['value']).'"'; + })->implode(','); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Dimensions.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Dimensions.php new file mode 100644 index 0000000..624cbcb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Dimensions.php @@ -0,0 +1,135 @@ +constraints = $constraints; + } + + /** + * Set the "width" constraint. + * + * @param int $value + * @return $this + */ + public function width($value) + { + $this->constraints['width'] = $value; + + return $this; + } + + /** + * Set the "height" constraint. + * + * @param int $value + * @return $this + */ + public function height($value) + { + $this->constraints['height'] = $value; + + return $this; + } + + /** + * Set the "min width" constraint. + * + * @param int $value + * @return $this + */ + public function minWidth($value) + { + $this->constraints['min_width'] = $value; + + return $this; + } + + /** + * Set the "min height" constraint. + * + * @param int $value + * @return $this + */ + public function minHeight($value) + { + $this->constraints['min_height'] = $value; + + return $this; + } + + /** + * Set the "max width" constraint. + * + * @param int $value + * @return $this + */ + public function maxWidth($value) + { + $this->constraints['max_width'] = $value; + + return $this; + } + + /** + * Set the "max height" constraint. + * + * @param int $value + * @return $this + */ + public function maxHeight($value) + { + $this->constraints['max_height'] = $value; + + return $this; + } + + /** + * Set the "ratio" constraint. + * + * @param float $value + * @return $this + */ + public function ratio($value) + { + $this->constraints['ratio'] = $value; + + return $this; + } + + /** + * Convert the rule to a validation string. + * + * @return string + */ + public function __toString() + { + $result = ''; + + foreach ($this->constraints as $key => $value) { + $result .= "$key=$value,"; + } + + return 'dimensions:'.substr($result, 0, -1); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Enum.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Enum.php new file mode 100644 index 0000000..df8f982 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Enum.php @@ -0,0 +1,61 @@ +type = $type; + } + + /** + * Determine if the validation rule passes. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function passes($attribute, $value) + { + if (is_null($value) || ! function_exists('enum_exists') || ! enum_exists($this->type) || ! method_exists($this->type, 'tryFrom')) { + return false; + } + + try { + return ! is_null($this->type::tryFrom($value)); + } catch (TypeError $e) { + return false; + } + } + + /** + * Get the validation error message. + * + * @return array + */ + public function message() + { + $message = trans('validation.enum'); + + return $message === 'validation.enum' + ? ['The selected :attribute is invalid.'] + : $message; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Exists.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Exists.php new file mode 100644 index 0000000..374dcf3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Exists.php @@ -0,0 +1,37 @@ +whereNull($deletedAtColumn); + + return $this; + } + + /** + * Convert the rule to a validation string. + * + * @return string + */ + public function __toString() + { + return rtrim(sprintf('exists:%s,%s,%s', + $this->table, + $this->column, + $this->formatWheres() + ), ','); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/In.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/In.php new file mode 100644 index 0000000..58086bf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/In.php @@ -0,0 +1,45 @@ +values = $values; + } + + /** + * Convert the rule to a validation string. + * + * @return string + * + * @see \Illuminate\Validation\ValidationRuleParser::parseParameters + */ + public function __toString() + { + $values = array_map(function ($value) { + return '"'.str_replace('"', '""', $value).'"'; + }, $this->values); + + return $this->rule.':'.implode(',', $values); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/NotIn.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/NotIn.php new file mode 100644 index 0000000..edd1013 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/NotIn.php @@ -0,0 +1,43 @@ +values = $values; + } + + /** + * Convert the rule to a validation string. + * + * @return string + */ + public function __toString() + { + $values = array_map(function ($value) { + return '"'.str_replace('"', '""', $value).'"'; + }, $this->values); + + return $this->rule.':'.implode(',', $values); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Password.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Password.php new file mode 100644 index 0000000..676dda6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Password.php @@ -0,0 +1,364 @@ +min = max((int) $min, 1); + } + + /** + * Set the default callback to be used for determining a password's default rules. + * + * If no arguments are passed, the default password rule configuration will be returned. + * + * @param static|callable|null $callback + * @return static|null + */ + public static function defaults($callback = null) + { + if (is_null($callback)) { + return static::default(); + } + + if (! is_callable($callback) && ! $callback instanceof static) { + throw new InvalidArgumentException('The given callback should be callable or an instance of '.static::class); + } + + static::$defaultCallback = $callback; + } + + /** + * Get the default configuration of the password rule. + * + * @return static + */ + public static function default() + { + $password = is_callable(static::$defaultCallback) + ? call_user_func(static::$defaultCallback) + : static::$defaultCallback; + + return $password instanceof Rule ? $password : static::min(8); + } + + /** + * Get the default configuration of the password rule and mark the field as required. + * + * @return array + */ + public static function required() + { + return ['required', static::default()]; + } + + /** + * Get the default configuration of the password rule and mark the field as sometimes being required. + * + * @return array + */ + public static function sometimes() + { + return ['sometimes', static::default()]; + } + + /** + * Set the performing validator. + * + * @param \Illuminate\Contracts\Validation\Validator $validator + * @return $this + */ + public function setValidator($validator) + { + $this->validator = $validator; + + return $this; + } + + /** + * Set the data under validation. + * + * @param array $data + * @return $this + */ + public function setData($data) + { + $this->data = $data; + + return $this; + } + + /** + * Sets the minimum size of the password. + * + * @param int $size + * @return $this + */ + public static function min($size) + { + return new static($size); + } + + /** + * Ensures the password has not been compromised in data leaks. + * + * @param int $threshold + * @return $this + */ + public function uncompromised($threshold = 0) + { + $this->uncompromised = true; + + $this->compromisedThreshold = $threshold; + + return $this; + } + + /** + * Makes the password require at least one uppercase and one lowercase letter. + * + * @return $this + */ + public function mixedCase() + { + $this->mixedCase = true; + + return $this; + } + + /** + * Makes the password require at least one letter. + * + * @return $this + */ + public function letters() + { + $this->letters = true; + + return $this; + } + + /** + * Makes the password require at least one number. + * + * @return $this + */ + public function numbers() + { + $this->numbers = true; + + return $this; + } + + /** + * Makes the password require at least one symbol. + * + * @return $this + */ + public function symbols() + { + $this->symbols = true; + + return $this; + } + + /** + * Specify additional validation rules that should be merged with the default rules during validation. + * + * @param string|array $rules + * @return $this + */ + public function rules($rules) + { + $this->customRules = Arr::wrap($rules); + + return $this; + } + + /** + * Determine if the validation rule passes. + * + * @param string $attribute + * @param mixed $value + * @return bool + */ + public function passes($attribute, $value) + { + $this->messages = []; + + $validator = Validator::make( + $this->data, + [$attribute => array_merge(['string', 'min:'.$this->min], $this->customRules)], + $this->validator->customMessages, + $this->validator->customAttributes + )->after(function ($validator) use ($attribute, $value) { + if (! is_string($value)) { + return; + } + + $value = (string) $value; + + if ($this->mixedCase && ! preg_match('/(\p{Ll}+.*\p{Lu})|(\p{Lu}+.*\p{Ll})/u', $value)) { + $validator->errors()->add($attribute, 'The :attribute must contain at least one uppercase and one lowercase letter.'); + } + + if ($this->letters && ! preg_match('/\pL/u', $value)) { + $validator->errors()->add($attribute, 'The :attribute must contain at least one letter.'); + } + + if ($this->symbols && ! preg_match('/\p{Z}|\p{S}|\p{P}/u', $value)) { + $validator->errors()->add($attribute, 'The :attribute must contain at least one symbol.'); + } + + if ($this->numbers && ! preg_match('/\pN/u', $value)) { + $validator->errors()->add($attribute, 'The :attribute must contain at least one number.'); + } + }); + + if ($validator->fails()) { + return $this->fail($validator->messages()->all()); + } + + if ($this->uncompromised && ! Container::getInstance()->make(UncompromisedVerifier::class)->verify([ + 'value' => $value, + 'threshold' => $this->compromisedThreshold, + ])) { + return $this->fail( + 'The given :attribute has appeared in a data leak. Please choose a different :attribute.' + ); + } + + return true; + } + + /** + * Get the validation error message. + * + * @return array + */ + public function message() + { + return $this->messages; + } + + /** + * Adds the given failures, and return false. + * + * @param array|string $messages + * @return bool + */ + protected function fail($messages) + { + $messages = collect(Arr::wrap($messages))->map(function ($message) { + return $this->validator->getTranslator()->get($message); + })->all(); + + $this->messages = array_merge($this->messages, $messages); + + return false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/RequiredIf.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/RequiredIf.php new file mode 100644 index 0000000..a1ab749 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/RequiredIf.php @@ -0,0 +1,44 @@ +condition = $condition; + } else { + throw new InvalidArgumentException('The provided condition must be a callable or boolean.'); + } + } + + /** + * Convert the rule to a validation string. + * + * @return string + */ + public function __toString() + { + if (is_callable($this->condition)) { + return call_user_func($this->condition) ? 'required' : ''; + } + + return $this->condition ? 'required' : ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Unique.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Unique.php new file mode 100644 index 0000000..02f3d14 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Rules/Unique.php @@ -0,0 +1,88 @@ +ignoreModel($id, $idColumn); + } + + $this->ignore = $id; + $this->idColumn = $idColumn ?? 'id'; + + return $this; + } + + /** + * Ignore the given model during the unique check. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string|null $idColumn + * @return $this + */ + public function ignoreModel($model, $idColumn = null) + { + $this->idColumn = $idColumn ?? $model->getKeyName(); + $this->ignore = $model->{$this->idColumn}; + + return $this; + } + + /** + * Ignore soft deleted models during the unique check. + * + * @param string $deletedAtColumn + * @return $this + */ + public function withoutTrashed($deletedAtColumn = 'deleted_at') + { + $this->whereNull($deletedAtColumn); + + return $this; + } + + /** + * Convert the rule to a validation string. + * + * @return string + */ + public function __toString() + { + return rtrim(sprintf('unique:%s,%s,%s,%s,%s', + $this->table, + $this->column, + $this->ignore ? '"'.addslashes($this->ignore).'"' : 'NULL', + $this->idColumn, + $this->formatWheres() + ), ','); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/UnauthorizedException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/UnauthorizedException.php new file mode 100644 index 0000000..ea8a6ec --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/UnauthorizedException.php @@ -0,0 +1,10 @@ +prepareForValidation(); + + if (! $this->passesAuthorization()) { + $this->failedAuthorization(); + } + + $instance = $this->getValidatorInstance(); + + if ($instance->fails()) { + $this->failedValidation($instance); + } + + $this->passedValidation(); + } + + /** + * Prepare the data for validation. + * + * @return void + */ + protected function prepareForValidation() + { + // + } + + /** + * Get the validator instance for the request. + * + * @return \Illuminate\Validation\Validator + */ + protected function getValidatorInstance() + { + return $this->validator(); + } + + /** + * Handle a passed validation attempt. + * + * @return void + */ + protected function passedValidation() + { + // + } + + /** + * Handle a failed validation attempt. + * + * @param \Illuminate\Validation\Validator $validator + * @return void + * + * @throws \Illuminate\Validation\ValidationException + */ + protected function failedValidation(Validator $validator) + { + throw new ValidationException($validator); + } + + /** + * Determine if the request passes the authorization check. + * + * @return bool + */ + protected function passesAuthorization() + { + if (method_exists($this, 'authorize')) { + return $this->authorize(); + } + + return true; + } + + /** + * Handle a failed authorization attempt. + * + * @return void + * + * @throws \Illuminate\Validation\UnauthorizedException + */ + protected function failedAuthorization() + { + throw new UnauthorizedException; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationData.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationData.php new file mode 100644 index 0000000..86da0fd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationData.php @@ -0,0 +1,113 @@ + $value) { + if ((bool) preg_match('/^'.$pattern.'/', $key, $matches)) { + $keys[] = $matches[0]; + } + } + + $keys = array_unique($keys); + + $data = []; + + foreach ($keys as $key) { + $data[$key] = Arr::get($masterData, $key); + } + + return $data; + } + + /** + * Extract data based on the given dot-notated path. + * + * Used to extract a sub-section of the data for faster iteration. + * + * @param string $attribute + * @param array $masterData + * @return array + */ + public static function extractDataFromPath($attribute, $masterData) + { + $results = []; + + $value = Arr::get($masterData, $attribute, '__missing__'); + + if ($value !== '__missing__') { + Arr::set($results, $attribute, $value); + } + + return $results; + } + + /** + * Get the explicit part of the attribute name. + * + * E.g. 'foo.bar.*.baz' -> 'foo.bar' + * + * Allows us to not spin through all of the flattened data for some operations. + * + * @param string $attribute + * @return string + */ + public static function getLeadingExplicitAttributePath($attribute) + { + return rtrim(explode('*', $attribute)[0], '.') ?: null; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php new file mode 100644 index 0000000..460f959 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php @@ -0,0 +1,138 @@ +response = $response; + $this->errorBag = $errorBag; + $this->validator = $validator; + } + + /** + * Create a new validation exception from a plain array of messages. + * + * @param array $messages + * @return static + */ + public static function withMessages(array $messages) + { + return new static(tap(ValidatorFacade::make([], []), function ($validator) use ($messages) { + foreach ($messages as $key => $value) { + foreach (Arr::wrap($value) as $message) { + $validator->errors()->add($key, $message); + } + } + })); + } + + /** + * Get all of the validation error messages. + * + * @return array + */ + public function errors() + { + return $this->validator->errors()->messages(); + } + + /** + * Set the HTTP status code to be used for the response. + * + * @param int $status + * @return $this + */ + public function status($status) + { + $this->status = $status; + + return $this; + } + + /** + * Set the error bag on the exception. + * + * @param string $errorBag + * @return $this + */ + public function errorBag($errorBag) + { + $this->errorBag = $errorBag; + + return $this; + } + + /** + * Set the URL to redirect to on a validation error. + * + * @param string $url + * @return $this + */ + public function redirectTo($url) + { + $this->redirectTo = $url; + + return $this; + } + + /** + * Get the underlying response instance. + * + * @return \Symfony\Component\HttpFoundation\Response|null + */ + public function getResponse() + { + return $this->response; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationRuleParser.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationRuleParser.php new file mode 100644 index 0000000..ce499a5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationRuleParser.php @@ -0,0 +1,308 @@ +data = $data; + } + + /** + * Parse the human-friendly rules into a full rules array for the validator. + * + * @param array $rules + * @return \stdClass + */ + public function explode($rules) + { + $this->implicitAttributes = []; + + $rules = $this->explodeRules($rules); + + return (object) [ + 'rules' => $rules, + 'implicitAttributes' => $this->implicitAttributes, + ]; + } + + /** + * Explode the rules into an array of explicit rules. + * + * @param array $rules + * @return array + */ + protected function explodeRules($rules) + { + foreach ($rules as $key => $rule) { + if (Str::contains($key, '*')) { + $rules = $this->explodeWildcardRules($rules, $key, [$rule]); + + unset($rules[$key]); + } else { + $rules[$key] = $this->explodeExplicitRule($rule); + } + } + + return $rules; + } + + /** + * Explode the explicit rule into an array if necessary. + * + * @param mixed $rule + * @return array + */ + protected function explodeExplicitRule($rule) + { + if (is_string($rule)) { + return explode('|', $rule); + } elseif (is_object($rule)) { + return [$this->prepareRule($rule)]; + } + + return array_map([$this, 'prepareRule'], $rule); + } + + /** + * Prepare the given rule for the Validator. + * + * @param mixed $rule + * @return mixed + */ + protected function prepareRule($rule) + { + if ($rule instanceof Closure) { + $rule = new ClosureValidationRule($rule); + } + + if (! is_object($rule) || + $rule instanceof RuleContract || + ($rule instanceof Exists && $rule->queryCallbacks()) || + ($rule instanceof Unique && $rule->queryCallbacks())) { + return $rule; + } + + return (string) $rule; + } + + /** + * Define a set of rules that apply to each element in an array attribute. + * + * @param array $results + * @param string $attribute + * @param string|array $rules + * @return array + */ + protected function explodeWildcardRules($results, $attribute, $rules) + { + $pattern = str_replace('\*', '[^\.]*', preg_quote($attribute)); + + $data = ValidationData::initializeAndGatherData($attribute, $this->data); + + foreach ($data as $key => $value) { + if (Str::startsWith($key, $attribute) || (bool) preg_match('/^'.$pattern.'\z/', $key)) { + foreach ((array) $rules as $rule) { + $this->implicitAttributes[$attribute][] = $key; + + $results = $this->mergeRules($results, $key, $rule); + } + } + } + + return $results; + } + + /** + * Merge additional rules into a given attribute(s). + * + * @param array $results + * @param string|array $attribute + * @param string|array $rules + * @return array + */ + public function mergeRules($results, $attribute, $rules = []) + { + if (is_array($attribute)) { + foreach ((array) $attribute as $innerAttribute => $innerRules) { + $results = $this->mergeRulesForAttribute($results, $innerAttribute, $innerRules); + } + + return $results; + } + + return $this->mergeRulesForAttribute( + $results, $attribute, $rules + ); + } + + /** + * Merge additional rules into a given attribute. + * + * @param array $results + * @param string $attribute + * @param string|array $rules + * @return array + */ + protected function mergeRulesForAttribute($results, $attribute, $rules) + { + $merge = head($this->explodeRules([$rules])); + + $results[$attribute] = array_merge( + isset($results[$attribute]) ? $this->explodeExplicitRule($results[$attribute]) : [], $merge + ); + + return $results; + } + + /** + * Extract the rule name and parameters from a rule. + * + * @param array|string $rule + * @return array + */ + public static function parse($rule) + { + if ($rule instanceof RuleContract) { + return [$rule, []]; + } + + if (is_array($rule)) { + $rule = static::parseArrayRule($rule); + } else { + $rule = static::parseStringRule($rule); + } + + $rule[0] = static::normalizeRule($rule[0]); + + return $rule; + } + + /** + * Parse an array based rule. + * + * @param array $rule + * @return array + */ + protected static function parseArrayRule(array $rule) + { + return [Str::studly(trim(Arr::get($rule, 0, ''))), array_slice($rule, 1)]; + } + + /** + * Parse a string based rule. + * + * @param string $rule + * @return array + */ + protected static function parseStringRule($rule) + { + $parameters = []; + + // The format for specifying validation rules and parameters follows an + // easy {rule}:{parameters} formatting convention. For instance the + // rule "Max:3" states that the value may only be three letters. + if (strpos($rule, ':') !== false) { + [$rule, $parameter] = explode(':', $rule, 2); + + $parameters = static::parseParameters($rule, $parameter); + } + + return [Str::studly(trim($rule)), $parameters]; + } + + /** + * Parse a parameter list. + * + * @param string $rule + * @param string $parameter + * @return array + */ + protected static function parseParameters($rule, $parameter) + { + $rule = strtolower($rule); + + if (in_array($rule, ['regex', 'not_regex', 'notregex'], true)) { + return [$parameter]; + } + + return str_getcsv($parameter); + } + + /** + * Normalizes a rule so that we can accept short types. + * + * @param string $rule + * @return string + */ + protected static function normalizeRule($rule) + { + switch ($rule) { + case 'Int': + return 'Integer'; + case 'Bool': + return 'Boolean'; + default: + return $rule; + } + } + + /** + * Expand and conditional rules in the given array of rules. + * + * @param array $rules + * @param array $data + * @return array + */ + public static function filterConditionalRules($rules, array $data = []) + { + return collect($rules)->mapWithKeys(function ($attributeRules, $attribute) use ($data) { + if (! is_array($attributeRules) && + ! $attributeRules instanceof ConditionalRules) { + return [$attribute => $attributeRules]; + } + + if ($attributeRules instanceof ConditionalRules) { + return [$attribute => $attributeRules->passes($data) + ? array_filter($attributeRules->rules()) + : array_filter($attributeRules->defaultRules()), ]; + } + + return [$attribute => collect($attributeRules)->map(function ($rule) use ($data) { + if (! $rule instanceof ConditionalRules) { + return [$rule]; + } + + return $rule->passes($data) ? $rule->rules() : $rule->defaultRules(); + })->filter()->flatten(1)->values()->all()]; + })->all(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationServiceProvider.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationServiceProvider.php new file mode 100755 index 0000000..936235f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/ValidationServiceProvider.php @@ -0,0 +1,80 @@ +registerPresenceVerifier(); + $this->registerUncompromisedVerifier(); + $this->registerValidationFactory(); + } + + /** + * Register the validation factory. + * + * @return void + */ + protected function registerValidationFactory() + { + $this->app->singleton('validator', function ($app) { + $validator = new Factory($app['translator'], $app); + + // The validation presence verifier is responsible for determining the existence of + // values in a given data collection which is typically a relational database or + // other persistent data stores. It is used to check for "uniqueness" as well. + if (isset($app['db'], $app['validation.presence'])) { + $validator->setPresenceVerifier($app['validation.presence']); + } + + return $validator; + }); + } + + /** + * Register the database presence verifier. + * + * @return void + */ + protected function registerPresenceVerifier() + { + $this->app->singleton('validation.presence', function ($app) { + return new DatabasePresenceVerifier($app['db']); + }); + } + + /** + * Register the uncompromised password verifier. + * + * @return void + */ + protected function registerUncompromisedVerifier() + { + $this->app->singleton(UncompromisedVerifier::class, function ($app) { + return new NotPwnedVerifier($app[HttpFactory::class]); + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + 'validator', 'validation.presence', + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Validator.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Validator.php new file mode 100755 index 0000000..9cbc91b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/Validator.php @@ -0,0 +1,1538 @@ +dotPlaceholder = Str::random(); + + $this->initialRules = $rules; + $this->translator = $translator; + $this->customMessages = $messages; + $this->data = $this->parseData($data); + $this->customAttributes = $customAttributes; + + $this->setRules($rules); + } + + /** + * Parse the data array, converting dots and asterisks. + * + * @param array $data + * @return array + */ + public function parseData(array $data) + { + $newData = []; + + foreach ($data as $key => $value) { + if (is_array($value)) { + $value = $this->parseData($value); + } + + $key = str_replace( + ['.', '*'], + [$this->dotPlaceholder, '__asterisk__'], + $key + ); + + $newData[$key] = $value; + } + + return $newData; + } + + /** + * Replace the placeholders used in data keys. + * + * @param array $data + * @return array + */ + protected function replacePlaceholders($data) + { + $originalData = []; + + foreach ($data as $key => $value) { + $originalData[$this->replacePlaceholderInString($key)] = is_array($value) + ? $this->replacePlaceholders($value) + : $value; + } + + return $originalData; + } + + /** + * Replace the placeholders in the given string. + * + * @param string $value + * @return string + */ + protected function replacePlaceholderInString(string $value) + { + return str_replace( + [$this->dotPlaceholder, '__asterisk__'], + ['.', '*'], + $value + ); + } + + /** + * Add an after validation callback. + * + * @param callable|string $callback + * @return $this + */ + public function after($callback) + { + $this->after[] = function () use ($callback) { + return $callback($this); + }; + + return $this; + } + + /** + * Determine if the data passes the validation rules. + * + * @return bool + */ + public function passes() + { + $this->messages = new MessageBag; + + [$this->distinctValues, $this->failedRules] = [[], []]; + + // We'll spin through each rule, validating the attributes attached to that + // rule. Any error messages will be added to the containers with each of + // the other error messages, returning true if we don't have messages. + foreach ($this->rules as $attribute => $rules) { + if ($this->shouldBeExcluded($attribute)) { + $this->removeAttribute($attribute); + + continue; + } + + if ($this->stopOnFirstFailure && $this->messages->isNotEmpty()) { + break; + } + + foreach ($rules as $rule) { + $this->validateAttribute($attribute, $rule); + + if ($this->shouldBeExcluded($attribute)) { + $this->removeAttribute($attribute); + + break; + } + + if ($this->shouldStopValidating($attribute)) { + break; + } + } + } + + // Here we will spin through all of the "after" hooks on this validator and + // fire them off. This gives the callbacks a chance to perform all kinds + // of other validation that needs to get wrapped up in this operation. + foreach ($this->after as $after) { + $after(); + } + + return $this->messages->isEmpty(); + } + + /** + * Determine if the data fails the validation rules. + * + * @return bool + */ + public function fails() + { + return ! $this->passes(); + } + + /** + * Determine if the attribute should be excluded. + * + * @param string $attribute + * @return bool + */ + protected function shouldBeExcluded($attribute) + { + foreach ($this->excludeAttributes as $excludeAttribute) { + if ($attribute === $excludeAttribute || + Str::startsWith($attribute, $excludeAttribute.'.')) { + return true; + } + } + + return false; + } + + /** + * Remove the given attribute. + * + * @param string $attribute + * @return void + */ + protected function removeAttribute($attribute) + { + Arr::forget($this->data, $attribute); + Arr::forget($this->rules, $attribute); + } + + /** + * Run the validator's rules against its data. + * + * @return array + * + * @throws \Illuminate\Validation\ValidationException + */ + public function validate() + { + throw_if($this->fails(), $this->exception, $this); + + return $this->validated(); + } + + /** + * Run the validator's rules against its data. + * + * @param string $errorBag + * @return array + * + * @throws \Illuminate\Validation\ValidationException + */ + public function validateWithBag(string $errorBag) + { + try { + return $this->validate(); + } catch (ValidationException $e) { + $e->errorBag = $errorBag; + + throw $e; + } + } + + /** + * Get a validated input container for the validated input. + * + * @param array|null $keys + * @return \Illuminate\Support\ValidatedInput|array + */ + public function safe(array $keys = null) + { + return is_array($keys) + ? (new ValidatedInput($this->validated()))->only($keys) + : new ValidatedInput($this->validated()); + } + + /** + * Get the attributes and values that were validated. + * + * @return array + * + * @throws \Illuminate\Validation\ValidationException + */ + public function validated() + { + throw_if($this->invalid(), $this->exception, $this); + + $results = []; + + $missingValue = new stdClass; + + foreach ($this->getRules() as $key => $rules) { + if ($this->excludeUnvalidatedArrayKeys && + in_array('array', $rules) && + ! empty(preg_grep('/^'.preg_quote($key, '/').'\.+/', array_keys($this->getRules())))) { + continue; + } + + $value = data_get($this->getData(), $key, $missingValue); + + if ($value !== $missingValue) { + Arr::set($results, $key, $value); + } + } + + return $this->replacePlaceholders($results); + } + + /** + * Validate a given attribute against a rule. + * + * @param string $attribute + * @param string $rule + * @return void + */ + protected function validateAttribute($attribute, $rule) + { + $this->currentRule = $rule; + + [$rule, $parameters] = ValidationRuleParser::parse($rule); + + if ($rule === '') { + return; + } + + // First we will get the correct keys for the given attribute in case the field is nested in + // an array. Then we determine if the given rule accepts other field names as parameters. + // If so, we will replace any asterisks found in the parameters with the correct keys. + if ($this->dependsOnOtherFields($rule)) { + $parameters = $this->replaceDotInParameters($parameters); + + if ($keys = $this->getExplicitKeys($attribute)) { + $parameters = $this->replaceAsterisksInParameters($parameters, $keys); + } + } + + $value = $this->getValue($attribute); + + // If the attribute is a file, we will verify that the file upload was actually successful + // and if it wasn't we will add a failure for the attribute. Files may not successfully + // upload if they are too large based on PHP's settings so we will bail in this case. + if ($value instanceof UploadedFile && ! $value->isValid() && + $this->hasRule($attribute, array_merge($this->fileRules, $this->implicitRules)) + ) { + return $this->addFailure($attribute, 'uploaded', []); + } + + // If we have made it this far we will make sure the attribute is validatable and if it is + // we will call the validation method with the attribute. If a method returns false the + // attribute is invalid and we will add a failure message for this failing attribute. + $validatable = $this->isValidatable($rule, $attribute, $value); + + if ($rule instanceof RuleContract) { + return $validatable + ? $this->validateUsingCustomRule($attribute, $value, $rule) + : null; + } + + $method = "validate{$rule}"; + + if ($validatable && ! $this->$method($attribute, $value, $parameters, $this)) { + $this->addFailure($attribute, $rule, $parameters); + } + } + + /** + * Determine if the given rule depends on other fields. + * + * @param string $rule + * @return bool + */ + protected function dependsOnOtherFields($rule) + { + return in_array($rule, $this->dependentRules); + } + + /** + * Get the explicit keys from an attribute flattened with dot notation. + * + * E.g. 'foo.1.bar.spark.baz' -> [1, 'spark'] for 'foo.*.bar.*.baz' + * + * @param string $attribute + * @return array + */ + protected function getExplicitKeys($attribute) + { + $pattern = str_replace('\*', '([^\.]+)', preg_quote($this->getPrimaryAttribute($attribute), '/')); + + if (preg_match('/^'.$pattern.'/', $attribute, $keys)) { + array_shift($keys); + + return $keys; + } + + return []; + } + + /** + * Get the primary attribute name. + * + * For example, if "name.0" is given, "name.*" will be returned. + * + * @param string $attribute + * @return string + */ + protected function getPrimaryAttribute($attribute) + { + foreach ($this->implicitAttributes as $unparsed => $parsed) { + if (in_array($attribute, $parsed, true)) { + return $unparsed; + } + } + + return $attribute; + } + + /** + * Replace each field parameter which has an escaped dot with the dot placeholder. + * + * @param array $parameters + * @param array $keys + * @return array + */ + protected function replaceDotInParameters(array $parameters) + { + return array_map(function ($field) { + return str_replace('\.', $this->dotPlaceholder, $field); + }, $parameters); + } + + /** + * Replace each field parameter which has asterisks with the given keys. + * + * @param array $parameters + * @param array $keys + * @return array + */ + protected function replaceAsterisksInParameters(array $parameters, array $keys) + { + return array_map(function ($field) use ($keys) { + return vsprintf(str_replace('*', '%s', $field), $keys); + }, $parameters); + } + + /** + * Determine if the attribute is validatable. + * + * @param object|string $rule + * @param string $attribute + * @param mixed $value + * @return bool + */ + protected function isValidatable($rule, $attribute, $value) + { + if (in_array($rule, $this->excludeRules)) { + return true; + } + + return $this->presentOrRuleIsImplicit($rule, $attribute, $value) && + $this->passesOptionalCheck($attribute) && + $this->isNotNullIfMarkedAsNullable($rule, $attribute) && + $this->hasNotFailedPreviousRuleIfPresenceRule($rule, $attribute); + } + + /** + * Determine if the field is present, or the rule implies required. + * + * @param object|string $rule + * @param string $attribute + * @param mixed $value + * @return bool + */ + protected function presentOrRuleIsImplicit($rule, $attribute, $value) + { + if (is_string($value) && trim($value) === '') { + return $this->isImplicit($rule); + } + + return $this->validatePresent($attribute, $value) || + $this->isImplicit($rule); + } + + /** + * Determine if a given rule implies the attribute is required. + * + * @param object|string $rule + * @return bool + */ + protected function isImplicit($rule) + { + return $rule instanceof ImplicitRule || + in_array($rule, $this->implicitRules); + } + + /** + * Determine if the attribute passes any optional check. + * + * @param string $attribute + * @return bool + */ + protected function passesOptionalCheck($attribute) + { + if (! $this->hasRule($attribute, ['Sometimes'])) { + return true; + } + + $data = ValidationData::initializeAndGatherData($attribute, $this->data); + + return array_key_exists($attribute, $data) + || array_key_exists($attribute, $this->data); + } + + /** + * Determine if the attribute fails the nullable check. + * + * @param string $rule + * @param string $attribute + * @return bool + */ + protected function isNotNullIfMarkedAsNullable($rule, $attribute) + { + if ($this->isImplicit($rule) || ! $this->hasRule($attribute, ['Nullable'])) { + return true; + } + + return ! is_null(Arr::get($this->data, $attribute, 0)); + } + + /** + * Determine if it's a necessary presence validation. + * + * This is to avoid possible database type comparison errors. + * + * @param string $rule + * @param string $attribute + * @return bool + */ + protected function hasNotFailedPreviousRuleIfPresenceRule($rule, $attribute) + { + return in_array($rule, ['Unique', 'Exists']) ? ! $this->messages->has($attribute) : true; + } + + /** + * Validate an attribute using a custom rule object. + * + * @param string $attribute + * @param mixed $value + * @param \Illuminate\Contracts\Validation\Rule $rule + * @return void + */ + protected function validateUsingCustomRule($attribute, $value, $rule) + { + $attribute = $this->replacePlaceholderInString($attribute); + + $value = is_array($value) ? $this->replacePlaceholders($value) : $value; + + if ($rule instanceof ValidatorAwareRule) { + $rule->setValidator($this); + } + + if ($rule instanceof DataAwareRule) { + $rule->setData($this->data); + } + + if (! $rule->passes($attribute, $value)) { + $this->failedRules[$attribute][get_class($rule)] = []; + + $messages = $rule->message(); + + $messages = $messages ? (array) $messages : [get_class($rule)]; + + foreach ($messages as $message) { + $this->messages->add($attribute, $this->makeReplacements( + $message, $attribute, get_class($rule), [] + )); + } + } + } + + /** + * Check if we should stop further validations on a given attribute. + * + * @param string $attribute + * @return bool + */ + protected function shouldStopValidating($attribute) + { + $cleanedAttribute = $this->replacePlaceholderInString($attribute); + + if ($this->hasRule($attribute, ['Bail'])) { + return $this->messages->has($cleanedAttribute); + } + + if (isset($this->failedRules[$cleanedAttribute]) && + array_key_exists('uploaded', $this->failedRules[$cleanedAttribute])) { + return true; + } + + // In case the attribute has any rule that indicates that the field is required + // and that rule already failed then we should stop validation at this point + // as now there is no point in calling other rules with this field empty. + return $this->hasRule($attribute, $this->implicitRules) && + isset($this->failedRules[$cleanedAttribute]) && + array_intersect(array_keys($this->failedRules[$cleanedAttribute]), $this->implicitRules); + } + + /** + * Add a failed rule and error message to the collection. + * + * @param string $attribute + * @param string $rule + * @param array $parameters + * @return void + */ + public function addFailure($attribute, $rule, $parameters = []) + { + if (! $this->messages) { + $this->passes(); + } + + $attributeWithPlaceholders = $attribute; + + $attribute = str_replace( + [$this->dotPlaceholder, '__asterisk__'], + ['.', '*'], + $attribute + ); + + if (in_array($rule, $this->excludeRules)) { + return $this->excludeAttribute($attribute); + } + + $this->messages->add($attribute, $this->makeReplacements( + $this->getMessage($attributeWithPlaceholders, $rule), $attribute, $rule, $parameters + )); + + $this->failedRules[$attribute][$rule] = $parameters; + } + + /** + * Add the given attribute to the list of excluded attributes. + * + * @param string $attribute + * @return void + */ + protected function excludeAttribute(string $attribute) + { + $this->excludeAttributes[] = $attribute; + + $this->excludeAttributes = array_unique($this->excludeAttributes); + } + + /** + * Returns the data which was valid. + * + * @return array + */ + public function valid() + { + if (! $this->messages) { + $this->passes(); + } + + return array_diff_key( + $this->data, $this->attributesThatHaveMessages() + ); + } + + /** + * Returns the data which was invalid. + * + * @return array + */ + public function invalid() + { + if (! $this->messages) { + $this->passes(); + } + + $invalid = array_intersect_key( + $this->data, $this->attributesThatHaveMessages() + ); + + $result = []; + + $failed = Arr::only(Arr::dot($invalid), array_keys($this->failed())); + + foreach ($failed as $key => $failure) { + Arr::set($result, $key, $failure); + } + + return $result; + } + + /** + * Generate an array of all attributes that have messages. + * + * @return array + */ + protected function attributesThatHaveMessages() + { + return collect($this->messages()->toArray())->map(function ($message, $key) { + return explode('.', $key)[0]; + })->unique()->flip()->all(); + } + + /** + * Get the failed validation rules. + * + * @return array + */ + public function failed() + { + return $this->failedRules; + } + + /** + * Get the message container for the validator. + * + * @return \Illuminate\Support\MessageBag + */ + public function messages() + { + if (! $this->messages) { + $this->passes(); + } + + return $this->messages; + } + + /** + * An alternative more semantic shortcut to the message container. + * + * @return \Illuminate\Support\MessageBag + */ + public function errors() + { + return $this->messages(); + } + + /** + * Get the messages for the instance. + * + * @return \Illuminate\Support\MessageBag + */ + public function getMessageBag() + { + return $this->messages(); + } + + /** + * Determine if the given attribute has a rule in the given set. + * + * @param string $attribute + * @param string|array $rules + * @return bool + */ + public function hasRule($attribute, $rules) + { + return ! is_null($this->getRule($attribute, $rules)); + } + + /** + * Get a rule and its parameters for a given attribute. + * + * @param string $attribute + * @param string|array $rules + * @return array|null + */ + protected function getRule($attribute, $rules) + { + if (! array_key_exists($attribute, $this->rules)) { + return; + } + + $rules = (array) $rules; + + foreach ($this->rules[$attribute] as $rule) { + [$rule, $parameters] = ValidationRuleParser::parse($rule); + + if (in_array($rule, $rules)) { + return [$rule, $parameters]; + } + } + } + + /** + * Get the data under validation. + * + * @return array + */ + public function attributes() + { + return $this->getData(); + } + + /** + * Get the data under validation. + * + * @return array + */ + public function getData() + { + return $this->data; + } + + /** + * Set the data under validation. + * + * @param array $data + * @return $this + */ + public function setData(array $data) + { + $this->data = $this->parseData($data); + + $this->setRules($this->initialRules); + + return $this; + } + + /** + * Get the value of a given attribute. + * + * @param string $attribute + * @return mixed + */ + protected function getValue($attribute) + { + return Arr::get($this->data, $attribute); + } + + /** + * Get the validation rules. + * + * @return array + */ + public function getRules() + { + return $this->rules; + } + + /** + * Set the validation rules. + * + * @param array $rules + * @return $this + */ + public function setRules(array $rules) + { + $rules = collect($rules)->mapWithKeys(function ($value, $key) { + return [str_replace('\.', $this->dotPlaceholder, $key) => $value]; + })->toArray(); + + $this->initialRules = $rules; + + $this->rules = []; + + $this->addRules($rules); + + return $this; + } + + /** + * Parse the given rules and merge them into current rules. + * + * @param array $rules + * @return void + */ + public function addRules($rules) + { + // The primary purpose of this parser is to expand any "*" rules to the all + // of the explicit rules needed for the given data. For example the rule + // names.* would get expanded to names.0, names.1, etc. for this data. + $response = (new ValidationRuleParser($this->data)) + ->explode(ValidationRuleParser::filterConditionalRules($rules, $this->data)); + + $this->rules = array_merge_recursive( + $this->rules, $response->rules + ); + + $this->implicitAttributes = array_merge( + $this->implicitAttributes, $response->implicitAttributes + ); + } + + /** + * Add conditions to a given field based on a Closure. + * + * @param string|array $attribute + * @param string|array $rules + * @param callable $callback + * @return $this + */ + public function sometimes($attribute, $rules, callable $callback) + { + $payload = new Fluent($this->data); + + foreach ((array) $attribute as $key) { + $response = (new ValidationRuleParser($this->data))->explode([$key => $rules]); + + $this->implicitAttributes = array_merge($response->implicitAttributes, $this->implicitAttributes); + + foreach ($response->rules as $ruleKey => $ruleValue) { + if ($callback($payload, $this->dataForSometimesIteration($ruleKey, ! Str::endsWith($key, '.*')))) { + $this->addRules([$ruleKey => $ruleValue]); + } + } + } + + return $this; + } + + /** + * Get the data that should be injected into the iteration of a wildcard "sometimes" callback. + * + * @param string $attribute + * @return \Illuminate\Support\Fluent|array|mixed + */ + private function dataForSometimesIteration(string $attribute, $removeLastSegmentOfAttribute) + { + $lastSegmentOfAttribute = strrchr($attribute, '.'); + + $attribute = $lastSegmentOfAttribute && $removeLastSegmentOfAttribute + ? Str::replaceLast($lastSegmentOfAttribute, '', $attribute) + : $attribute; + + return is_array($data = data_get($this->data, $attribute)) + ? new Fluent($data) + : $data; + } + + /** + * Instruct the validator to stop validating after the first rule failure. + * + * @param bool $stopOnFirstFailure + * @return $this + */ + public function stopOnFirstFailure($stopOnFirstFailure = true) + { + $this->stopOnFirstFailure = $stopOnFirstFailure; + + return $this; + } + + /** + * Register an array of custom validator extensions. + * + * @param array $extensions + * @return void + */ + public function addExtensions(array $extensions) + { + if ($extensions) { + $keys = array_map([Str::class, 'snake'], array_keys($extensions)); + + $extensions = array_combine($keys, array_values($extensions)); + } + + $this->extensions = array_merge($this->extensions, $extensions); + } + + /** + * Register an array of custom implicit validator extensions. + * + * @param array $extensions + * @return void + */ + public function addImplicitExtensions(array $extensions) + { + $this->addExtensions($extensions); + + foreach ($extensions as $rule => $extension) { + $this->implicitRules[] = Str::studly($rule); + } + } + + /** + * Register an array of custom dependent validator extensions. + * + * @param array $extensions + * @return void + */ + public function addDependentExtensions(array $extensions) + { + $this->addExtensions($extensions); + + foreach ($extensions as $rule => $extension) { + $this->dependentRules[] = Str::studly($rule); + } + } + + /** + * Register a custom validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @return void + */ + public function addExtension($rule, $extension) + { + $this->extensions[Str::snake($rule)] = $extension; + } + + /** + * Register a custom implicit validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @return void + */ + public function addImplicitExtension($rule, $extension) + { + $this->addExtension($rule, $extension); + + $this->implicitRules[] = Str::studly($rule); + } + + /** + * Register a custom dependent validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @return void + */ + public function addDependentExtension($rule, $extension) + { + $this->addExtension($rule, $extension); + + $this->dependentRules[] = Str::studly($rule); + } + + /** + * Register an array of custom validator message replacers. + * + * @param array $replacers + * @return void + */ + public function addReplacers(array $replacers) + { + if ($replacers) { + $keys = array_map([Str::class, 'snake'], array_keys($replacers)); + + $replacers = array_combine($keys, array_values($replacers)); + } + + $this->replacers = array_merge($this->replacers, $replacers); + } + + /** + * Register a custom validator message replacer. + * + * @param string $rule + * @param \Closure|string $replacer + * @return void + */ + public function addReplacer($rule, $replacer) + { + $this->replacers[Str::snake($rule)] = $replacer; + } + + /** + * Set the custom messages for the validator. + * + * @param array $messages + * @return $this + */ + public function setCustomMessages(array $messages) + { + $this->customMessages = array_merge($this->customMessages, $messages); + + return $this; + } + + /** + * Set the custom attributes on the validator. + * + * @param array $attributes + * @return $this + */ + public function setAttributeNames(array $attributes) + { + $this->customAttributes = $attributes; + + return $this; + } + + /** + * Add custom attributes to the validator. + * + * @param array $customAttributes + * @return $this + */ + public function addCustomAttributes(array $customAttributes) + { + $this->customAttributes = array_merge($this->customAttributes, $customAttributes); + + return $this; + } + + /** + * Set the callback that used to format an implicit attribute. + * + * @param callable|null $formatter + * @return $this + */ + public function setImplicitAttributesFormatter(callable $formatter = null) + { + $this->implicitAttributesFormatter = $formatter; + + return $this; + } + + /** + * Set the custom values on the validator. + * + * @param array $values + * @return $this + */ + public function setValueNames(array $values) + { + $this->customValues = $values; + + return $this; + } + + /** + * Add the custom values for the validator. + * + * @param array $customValues + * @return $this + */ + public function addCustomValues(array $customValues) + { + $this->customValues = array_merge($this->customValues, $customValues); + + return $this; + } + + /** + * Set the fallback messages for the validator. + * + * @param array $messages + * @return void + */ + public function setFallbackMessages(array $messages) + { + $this->fallbackMessages = $messages; + } + + /** + * Get the Presence Verifier implementation. + * + * @param string|null $connection + * @return \Illuminate\Validation\PresenceVerifierInterface + * + * @throws \RuntimeException + */ + public function getPresenceVerifier($connection = null) + { + if (! isset($this->presenceVerifier)) { + throw new RuntimeException('Presence verifier has not been set.'); + } + + if ($this->presenceVerifier instanceof DatabasePresenceVerifierInterface) { + $this->presenceVerifier->setConnection($connection); + } + + return $this->presenceVerifier; + } + + /** + * Set the Presence Verifier implementation. + * + * @param \Illuminate\Validation\PresenceVerifierInterface $presenceVerifier + * @return void + */ + public function setPresenceVerifier(PresenceVerifierInterface $presenceVerifier) + { + $this->presenceVerifier = $presenceVerifier; + } + + /** + * Set the exception to throw upon failed validation. + * + * @param string $exception + * @return $this + * + * @throws \InvalidArgumentException + */ + public function setException($exception) + { + if (! is_a($exception, ValidationException::class, true)) { + throw new InvalidArgumentException( + sprintf('Exception [%s] is invalid. It must extend [%s].', $exception, ValidationException::class) + ); + } + + $this->exception = $exception; + + return $this; + } + + /** + * Get the Translator implementation. + * + * @return \Illuminate\Contracts\Translation\Translator + */ + public function getTranslator() + { + return $this->translator; + } + + /** + * Set the Translator implementation. + * + * @param \Illuminate\Contracts\Translation\Translator $translator + * @return void + */ + public function setTranslator(Translator $translator) + { + $this->translator = $translator; + } + + /** + * Set the IoC container instance. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function setContainer(Container $container) + { + $this->container = $container; + } + + /** + * Call a custom validator extension. + * + * @param string $rule + * @param array $parameters + * @return bool|null + */ + protected function callExtension($rule, $parameters) + { + $callback = $this->extensions[$rule]; + + if (is_callable($callback)) { + return $callback(...array_values($parameters)); + } elseif (is_string($callback)) { + return $this->callClassBasedExtension($callback, $parameters); + } + } + + /** + * Call a class based validator extension. + * + * @param string $callback + * @param array $parameters + * @return bool + */ + protected function callClassBasedExtension($callback, $parameters) + { + [$class, $method] = Str::parseCallback($callback, 'validate'); + + return $this->container->make($class)->{$method}(...array_values($parameters)); + } + + /** + * Handle dynamic calls to class methods. + * + * @param string $method + * @param array $parameters + * @return mixed + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + $rule = Str::snake(substr($method, 8)); + + if (isset($this->extensions[$rule])) { + return $this->callExtension($rule, $parameters); + } + + throw new BadMethodCallException(sprintf( + 'Method %s::%s does not exist.', static::class, $method + )); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/composer.json new file mode 100755 index 0000000..f4a0bab --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/Validation/composer.json @@ -0,0 +1,47 @@ +{ + "name": "illuminate/validation", + "description": "The Illuminate Validation package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "egulias/email-validator": "^2.1.10", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "illuminate/translation": "^8.0", + "symfony/http-foundation": "^5.4", + "symfony/mime": "^5.4" + }, + "autoload": { + "psr-4": { + "Illuminate\\Validation\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "suggest": { + "ext-bcmath": "Required to use the multiple_of validation rule.", + "illuminate/database": "Required to use the database presence verifier (^8.0)." + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/AnonymousComponent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/AnonymousComponent.php new file mode 100644 index 0000000..2fb21e1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/AnonymousComponent.php @@ -0,0 +1,60 @@ +view = $view; + $this->data = $data; + } + + /** + * Get the view / view contents that represent the component. + * + * @return string + */ + public function render() + { + return $this->view; + } + + /** + * Get the data that should be supplied to the view. + * + * @return array + */ + public function data() + { + $this->attributes = $this->attributes ?: $this->newAttributeBag(); + + return array_merge( + optional($this->data['attributes'] ?? null)->getAttributes() ?: [], + $this->attributes->getAttributes(), + $this->data, + ['attributes' => $this->attributes] + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/AppendableAttributeValue.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/AppendableAttributeValue.php new file mode 100644 index 0000000..f275801 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/AppendableAttributeValue.php @@ -0,0 +1,34 @@ +value = $value; + } + + /** + * Get the string value. + * + * @return string + */ + public function __toString() + { + return (string) $this->value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php new file mode 100644 index 0000000..fd3f91a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php @@ -0,0 +1,828 @@ +setPath($path); + } + + if (! is_null($this->cachePath)) { + $contents = $this->compileString($this->files->get($this->getPath())); + + if (! empty($this->getPath())) { + $contents = $this->appendFilePath($contents); + } + + $this->ensureCompiledDirectoryExists( + $compiledPath = $this->getCompiledPath($this->getPath()) + ); + + $this->files->put($compiledPath, $contents); + } + } + + /** + * Append the file path to the compiled string. + * + * @param string $contents + * @return string + */ + protected function appendFilePath($contents) + { + $tokens = $this->getOpenAndClosingPhpTokens($contents); + + if ($tokens->isNotEmpty() && $tokens->last() !== T_CLOSE_TAG) { + $contents .= ' ?>'; + } + + return $contents."getPath()} ENDPATH**/ ?>"; + } + + /** + * Get the open and closing PHP tag tokens from the given string. + * + * @param string $contents + * @return \Illuminate\Support\Collection + */ + protected function getOpenAndClosingPhpTokens($contents) + { + return collect(token_get_all($contents)) + ->pluck(0) + ->filter(function ($token) { + return in_array($token, [T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_CLOSE_TAG]); + }); + } + + /** + * Get the path currently being compiled. + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Set the path currently being compiled. + * + * @param string $path + * @return void + */ + public function setPath($path) + { + $this->path = $path; + } + + /** + * Compile the given Blade template contents. + * + * @param string $value + * @return string + */ + public function compileString($value) + { + [$this->footer, $result] = [[], '']; + + // First we will compile the Blade component tags. This is a precompile style + // step which compiles the component Blade tags into @component directives + // that may be used by Blade. Then we should call any other precompilers. + $value = $this->compileComponentTags( + $this->compileComments($this->storeUncompiledBlocks($value)) + ); + + foreach ($this->precompilers as $precompiler) { + $value = call_user_func($precompiler, $value); + } + + // Here we will loop through all of the tokens returned by the Zend lexer and + // parse each one into the corresponding valid PHP. We will then have this + // template as the correctly rendered PHP that can be rendered natively. + foreach (token_get_all($value) as $token) { + $result .= is_array($token) ? $this->parseToken($token) : $token; + } + + if (! empty($this->rawBlocks)) { + $result = $this->restoreRawContent($result); + } + + // If there are any footer lines that need to get added to a template we will + // add them here at the end of the template. This gets used mainly for the + // template inheritance via the extends keyword that should be appended. + if (count($this->footer) > 0) { + $result = $this->addFooters($result); + } + + if (! empty($this->echoHandlers)) { + $result = $this->addBladeCompilerVariable($result); + } + + return str_replace( + ['##BEGIN-COMPONENT-CLASS##', '##END-COMPONENT-CLASS##'], + '', + $result); + } + + /** + * Evaluate and render a Blade string to HTML. + * + * @param string $string + * @param array $data + * @param bool $deleteCachedView + * @return string + */ + public static function render($string, $data = [], $deleteCachedView = false) + { + $component = new class($string) extends Component + { + protected $template; + + public function __construct($template) + { + $this->template = $template; + } + + public function render() + { + return $this->template; + } + }; + + $view = Container::getInstance() + ->make(ViewFactory::class) + ->make($component->resolveView(), $data); + + return tap($view->render(), function () use ($view, $deleteCachedView) { + if ($deleteCachedView) { + unlink($view->getPath()); + } + }); + } + + /** + * Render a component instance to HTML. + * + * @param \Illuminate\View\Component $component + * @return string + */ + public static function renderComponent(Component $component) + { + $data = $component->data(); + + $view = value($component->resolveView(), $data); + + if ($view instanceof View) { + return $view->with($data)->render(); + } elseif ($view instanceof Htmlable) { + return $view->toHtml(); + } else { + return Container::getInstance() + ->make(ViewFactory::class) + ->make($view, $data) + ->render(); + } + } + + /** + * Store the blocks that do not receive compilation. + * + * @param string $value + * @return string + */ + protected function storeUncompiledBlocks($value) + { + if (strpos($value, '@verbatim') !== false) { + $value = $this->storeVerbatimBlocks($value); + } + + if (strpos($value, '@php') !== false) { + $value = $this->storePhpBlocks($value); + } + + return $value; + } + + /** + * Store the verbatim blocks and replace them with a temporary placeholder. + * + * @param string $value + * @return string + */ + protected function storeVerbatimBlocks($value) + { + return preg_replace_callback('/(?storeRawBlock($matches[1]); + }, $value); + } + + /** + * Store the PHP blocks and replace them with a temporary placeholder. + * + * @param string $value + * @return string + */ + protected function storePhpBlocks($value) + { + return preg_replace_callback('/(?storeRawBlock(""); + }, $value); + } + + /** + * Store a raw block and return a unique raw placeholder. + * + * @param string $value + * @return string + */ + protected function storeRawBlock($value) + { + return $this->getRawPlaceholder( + array_push($this->rawBlocks, $value) - 1 + ); + } + + /** + * Compile the component tags. + * + * @param string $value + * @return string + */ + protected function compileComponentTags($value) + { + if (! $this->compilesComponentTags) { + return $value; + } + + return (new ComponentTagCompiler( + $this->classComponentAliases, $this->classComponentNamespaces, $this + ))->compile($value); + } + + /** + * Replace the raw placeholders with the original code stored in the raw blocks. + * + * @param string $result + * @return string + */ + protected function restoreRawContent($result) + { + $result = preg_replace_callback('/'.$this->getRawPlaceholder('(\d+)').'/', function ($matches) { + return $this->rawBlocks[$matches[1]]; + }, $result); + + $this->rawBlocks = []; + + return $result; + } + + /** + * Get a placeholder to temporarily mark the position of raw blocks. + * + * @param int|string $replace + * @return string + */ + protected function getRawPlaceholder($replace) + { + return str_replace('#', $replace, '@__raw_block_#__@'); + } + + /** + * Add the stored footers onto the given content. + * + * @param string $result + * @return string + */ + protected function addFooters($result) + { + return ltrim($result, "\n") + ."\n".implode("\n", array_reverse($this->footer)); + } + + /** + * Parse the tokens from the template. + * + * @param array $token + * @return string + */ + protected function parseToken($token) + { + [$id, $content] = $token; + + if ($id == T_INLINE_HTML) { + foreach ($this->compilers as $type) { + $content = $this->{"compile{$type}"}($content); + } + } + + return $content; + } + + /** + * Execute the user defined extensions. + * + * @param string $value + * @return string + */ + protected function compileExtensions($value) + { + foreach ($this->extensions as $compiler) { + $value = $compiler($value, $this); + } + + return $value; + } + + /** + * Compile Blade statements that start with "@". + * + * @param string $value + * @return string + */ + protected function compileStatements($value) + { + return preg_replace_callback( + '/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?/x', function ($match) { + return $this->compileStatement($match); + }, $value + ); + } + + /** + * Compile a single Blade @ statement. + * + * @param array $match + * @return string + */ + protected function compileStatement($match) + { + if (Str::contains($match[1], '@')) { + $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1]; + } elseif (isset($this->customDirectives[$match[1]])) { + $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3)); + } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) { + $match[0] = $this->$method(Arr::get($match, 3)); + } + + return isset($match[3]) ? $match[0] : $match[0].$match[2]; + } + + /** + * Call the given directive with the given value. + * + * @param string $name + * @param string|null $value + * @return string + */ + protected function callCustomDirective($name, $value) + { + $value = $value ?? ''; + + if (Str::startsWith($value, '(') && Str::endsWith($value, ')')) { + $value = Str::substr($value, 1, -1); + } + + return call_user_func($this->customDirectives[$name], trim($value)); + } + + /** + * Strip the parentheses from the given expression. + * + * @param string $expression + * @return string + */ + public function stripParentheses($expression) + { + if (Str::startsWith($expression, '(')) { + $expression = substr($expression, 1, -1); + } + + return $expression; + } + + /** + * Register a custom Blade compiler. + * + * @param callable $compiler + * @return void + */ + public function extend(callable $compiler) + { + $this->extensions[] = $compiler; + } + + /** + * Get the extensions used by the compiler. + * + * @return array + */ + public function getExtensions() + { + return $this->extensions; + } + + /** + * Register an "if" statement directive. + * + * @param string $name + * @param callable $callback + * @return void + */ + public function if($name, callable $callback) + { + $this->conditions[$name] = $callback; + + $this->directive($name, function ($expression) use ($name) { + return $expression !== '' + ? "" + : ""; + }); + + $this->directive('unless'.$name, function ($expression) use ($name) { + return $expression !== '' + ? "" + : ""; + }); + + $this->directive('else'.$name, function ($expression) use ($name) { + return $expression !== '' + ? "" + : ""; + }); + + $this->directive('end'.$name, function () { + return ''; + }); + } + + /** + * Check the result of a condition. + * + * @param string $name + * @param array $parameters + * @return bool + */ + public function check($name, ...$parameters) + { + return call_user_func($this->conditions[$name], ...$parameters); + } + + /** + * Register a class-based component alias directive. + * + * @param string $class + * @param string|null $alias + * @param string $prefix + * @return void + */ + public function component($class, $alias = null, $prefix = '') + { + if (! is_null($alias) && Str::contains($alias, '\\')) { + [$class, $alias] = [$alias, $class]; + } + + if (is_null($alias)) { + $alias = Str::contains($class, '\\View\\Components\\') + ? collect(explode('\\', Str::after($class, '\\View\\Components\\')))->map(function ($segment) { + return Str::kebab($segment); + })->implode(':') + : Str::kebab(class_basename($class)); + } + + if (! empty($prefix)) { + $alias = $prefix.'-'.$alias; + } + + $this->classComponentAliases[$alias] = $class; + } + + /** + * Register an array of class-based components. + * + * @param array $components + * @param string $prefix + * @return void + */ + public function components(array $components, $prefix = '') + { + foreach ($components as $key => $value) { + if (is_numeric($key)) { + $this->component($value, null, $prefix); + } else { + $this->component($key, $value, $prefix); + } + } + } + + /** + * Get the registered class component aliases. + * + * @return array + */ + public function getClassComponentAliases() + { + return $this->classComponentAliases; + } + + /** + * Register a class-based component namespace. + * + * @param string $namespace + * @param string $prefix + * @return void + */ + public function componentNamespace($namespace, $prefix) + { + $this->classComponentNamespaces[$prefix] = $namespace; + } + + /** + * Get the registered class component namespaces. + * + * @return array + */ + public function getClassComponentNamespaces() + { + return $this->classComponentNamespaces; + } + + /** + * Register a component alias directive. + * + * @param string $path + * @param string|null $alias + * @return void + */ + public function aliasComponent($path, $alias = null) + { + $alias = $alias ?: Arr::last(explode('.', $path)); + + $this->directive($alias, function ($expression) use ($path) { + return $expression + ? "startComponent('{$path}', {$expression}); ?>" + : "startComponent('{$path}'); ?>"; + }); + + $this->directive('end'.$alias, function ($expression) { + return 'renderComponent(); ?>'; + }); + } + + /** + * Register an include alias directive. + * + * @param string $path + * @param string|null $alias + * @return void + */ + public function include($path, $alias = null) + { + $this->aliasInclude($path, $alias); + } + + /** + * Register an include alias directive. + * + * @param string $path + * @param string|null $alias + * @return void + */ + public function aliasInclude($path, $alias = null) + { + $alias = $alias ?: Arr::last(explode('.', $path)); + + $this->directive($alias, function ($expression) use ($path) { + $expression = $this->stripParentheses($expression) ?: '[]'; + + return "make('{$path}', {$expression}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>"; + }); + } + + /** + * Register a handler for custom directives. + * + * @param string $name + * @param callable $handler + * @return void + * + * @throws \InvalidArgumentException + */ + public function directive($name, callable $handler) + { + if (! preg_match('/^\w+(?:::\w+)?$/x', $name)) { + throw new InvalidArgumentException("The directive name [{$name}] is not valid. Directive names must only contain alphanumeric characters and underscores."); + } + + $this->customDirectives[$name] = $handler; + } + + /** + * Get the list of custom directives. + * + * @return array + */ + public function getCustomDirectives() + { + return $this->customDirectives; + } + + /** + * Register a new precompiler. + * + * @param callable $precompiler + * @return void + */ + public function precompiler(callable $precompiler) + { + $this->precompilers[] = $precompiler; + } + + /** + * Set the echo format to be used by the compiler. + * + * @param string $format + * @return void + */ + public function setEchoFormat($format) + { + $this->echoFormat = $format; + } + + /** + * Set the "echo" format to double encode entities. + * + * @return void + */ + public function withDoubleEncoding() + { + $this->setEchoFormat('e(%s, true)'); + } + + /** + * Set the "echo" format to not double encode entities. + * + * @return void + */ + public function withoutDoubleEncoding() + { + $this->setEchoFormat('e(%s, false)'); + } + + /** + * Indicate that component tags should not be compiled. + * + * @return void + */ + public function withoutComponentTags() + { + $this->compilesComponentTags = false; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Compiler.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Compiler.php new file mode 100755 index 0000000..e14c852 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Compiler.php @@ -0,0 +1,87 @@ +files = $files; + $this->cachePath = $cachePath; + } + + /** + * Get the path to the compiled version of a view. + * + * @param string $path + * @return string + */ + public function getCompiledPath($path) + { + return $this->cachePath.'/'.sha1('v2'.$path).'.php'; + } + + /** + * Determine if the view at the given path is expired. + * + * @param string $path + * @return bool + */ + public function isExpired($path) + { + $compiled = $this->getCompiledPath($path); + + // If the compiled file doesn't exist we will indicate that the view is expired + // so that it can be re-compiled. Else, we will verify the last modification + // of the views is less than the modification times of the compiled views. + if (! $this->files->exists($compiled)) { + return true; + } + + return $this->files->lastModified($path) >= + $this->files->lastModified($compiled); + } + + /** + * Create the compiled file directory if necessary. + * + * @param string $path + * @return void + */ + protected function ensureCompiledDirectoryExists($path) + { + if (! $this->files->exists(dirname($path))) { + $this->files->makeDirectory(dirname($path), 0777, true, true); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/CompilerInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/CompilerInterface.php new file mode 100755 index 0000000..dfcb023 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/CompilerInterface.php @@ -0,0 +1,30 @@ + + * @author Taylor Otwell + */ +class ComponentTagCompiler +{ + /** + * The Blade compiler instance. + * + * @var \Illuminate\View\Compilers\BladeCompiler + */ + protected $blade; + + /** + * The component class aliases. + * + * @var array + */ + protected $aliases = []; + + /** + * The component class namespaces. + * + * @var array + */ + protected $namespaces = []; + + /** + * The "bind:" attributes that have been compiled for the current component. + * + * @var array + */ + protected $boundAttributes = []; + + /** + * Create a new component tag compiler. + * + * @param array $aliases + * @param array $namespaces + * @param \Illuminate\View\Compilers\BladeCompiler|null $blade + * @return void + */ + public function __construct(array $aliases = [], array $namespaces = [], ?BladeCompiler $blade = null) + { + $this->aliases = $aliases; + $this->namespaces = $namespaces; + + $this->blade = $blade ?: new BladeCompiler(new Filesystem, sys_get_temp_dir()); + } + + /** + * Compile the component and slot tags within the given string. + * + * @param string $value + * @return string + */ + public function compile(string $value) + { + $value = $this->compileSlots($value); + + return $this->compileTags($value); + } + + /** + * Compile the tags within the given string. + * + * @param string $value + * @return string + * + * @throws \InvalidArgumentException + */ + public function compileTags(string $value) + { + $value = $this->compileSelfClosingTags($value); + $value = $this->compileOpeningTags($value); + $value = $this->compileClosingTags($value); + + return $value; + } + + /** + * Compile the opening tags within the given string. + * + * @param string $value + * @return string + * + * @throws \InvalidArgumentException + */ + protected function compileOpeningTags(string $value) + { + $pattern = "/ + < + \s* + x[-\:]([\w\-\:\.]*) + (? + (?: + \s+ + (?: + (?: + \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} + ) + | + (?: + [\w\-:.@]+ + ( + = + (?: + \\\"[^\\\"]*\\\" + | + \'[^\']*\' + | + [^\'\\\"=<>]+ + ) + )? + ) + ) + )* + \s* + ) + (? + /x"; + + return preg_replace_callback($pattern, function (array $matches) { + $this->boundAttributes = []; + + $attributes = $this->getAttributesFromAttributeString($matches['attributes']); + + return $this->componentString($matches[1], $attributes); + }, $value); + } + + /** + * Compile the self-closing tags within the given string. + * + * @param string $value + * @return string + * + * @throws \InvalidArgumentException + */ + protected function compileSelfClosingTags(string $value) + { + $pattern = "/ + < + \s* + x[-\:]([\w\-\:\.]*) + \s* + (? + (?: + \s+ + (?: + (?: + \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} + ) + | + (?: + [\w\-:.@]+ + ( + = + (?: + \\\"[^\\\"]*\\\" + | + \'[^\']*\' + | + [^\'\\\"=<>]+ + ) + )? + ) + ) + )* + \s* + ) + \/> + /x"; + + return preg_replace_callback($pattern, function (array $matches) { + $this->boundAttributes = []; + + $attributes = $this->getAttributesFromAttributeString($matches['attributes']); + + return $this->componentString($matches[1], $attributes)."\n@endComponentClass##END-COMPONENT-CLASS##"; + }, $value); + } + + /** + * Compile the Blade component string for the given component and attributes. + * + * @param string $component + * @param array $attributes + * @return string + * + * @throws \InvalidArgumentException + */ + protected function componentString(string $component, array $attributes) + { + $class = $this->componentClass($component); + + [$data, $attributes] = $this->partitionDataAndAttributes($class, $attributes); + + $data = $data->mapWithKeys(function ($value, $key) { + return [Str::camel($key) => $value]; + }); + + // If the component doesn't exists as a class we'll assume it's a class-less + // component and pass the component as a view parameter to the data so it + // can be accessed within the component and we can render out the view. + if (! class_exists($class)) { + $parameters = [ + 'view' => "'$class'", + 'data' => '['.$this->attributesToString($data->all(), $escapeBound = false).']', + ]; + + $class = AnonymousComponent::class; + } else { + $parameters = $data->all(); + } + + return "##BEGIN-COMPONENT-CLASS##@component('{$class}', '{$component}', [".$this->attributesToString($parameters, $escapeBound = false).']) +withAttributes(['.$this->attributesToString($attributes->all(), $escapeAttributes = $class !== DynamicComponent::class).']); ?>'; + } + + /** + * Get the component class for a given component alias. + * + * @param string $component + * @return string + * + * @throws \InvalidArgumentException + */ + public function componentClass(string $component) + { + $viewFactory = Container::getInstance()->make(Factory::class); + + if (isset($this->aliases[$component])) { + if (class_exists($alias = $this->aliases[$component])) { + return $alias; + } + + if ($viewFactory->exists($alias)) { + return $alias; + } + + throw new InvalidArgumentException( + "Unable to locate class or view [{$alias}] for component [{$component}]." + ); + } + + if ($class = $this->findClassByComponent($component)) { + return $class; + } + + if (class_exists($class = $this->guessClassName($component))) { + return $class; + } + + if ($viewFactory->exists($view = $this->guessViewName($component))) { + return $view; + } + + if ($viewFactory->exists($view = $this->guessViewName($component).'.index')) { + return $view; + } + + throw new InvalidArgumentException( + "Unable to locate a class or view for component [{$component}]." + ); + } + + /** + * Find the class for the given component using the registered namespaces. + * + * @param string $component + * @return string|null + */ + public function findClassByComponent(string $component) + { + $segments = explode('::', $component); + + $prefix = $segments[0]; + + if (! isset($this->namespaces[$prefix]) || ! isset($segments[1])) { + return; + } + + if (class_exists($class = $this->namespaces[$prefix].'\\'.$this->formatClassName($segments[1]))) { + return $class; + } + } + + /** + * Guess the class name for the given component. + * + * @param string $component + * @return string + */ + public function guessClassName(string $component) + { + $namespace = Container::getInstance() + ->make(Application::class) + ->getNamespace(); + + $class = $this->formatClassName($component); + + return $namespace.'View\\Components\\'.$class; + } + + /** + * Format the class name for the given component. + * + * @param string $component + * @return string + */ + public function formatClassName(string $component) + { + $componentPieces = array_map(function ($componentPiece) { + return ucfirst(Str::camel($componentPiece)); + }, explode('.', $component)); + + return implode('\\', $componentPieces); + } + + /** + * Guess the view name for the given component. + * + * @param string $name + * @return string + */ + public function guessViewName($name) + { + $prefix = 'components.'; + + $delimiter = ViewFinderInterface::HINT_PATH_DELIMITER; + + if (Str::contains($name, $delimiter)) { + return Str::replaceFirst($delimiter, $delimiter.$prefix, $name); + } + + return $prefix.$name; + } + + /** + * Partition the data and extra attributes from the given array of attributes. + * + * @param string $class + * @param array $attributes + * @return array + */ + public function partitionDataAndAttributes($class, array $attributes) + { + // If the class doesn't exists, we'll assume it's a class-less component and + // return all of the attributes as both data and attributes since we have + // now way to partition them. The user can exclude attributes manually. + if (! class_exists($class)) { + return [collect($attributes), collect($attributes)]; + } + + $constructor = (new ReflectionClass($class))->getConstructor(); + + $parameterNames = $constructor + ? collect($constructor->getParameters())->map->getName()->all() + : []; + + return collect($attributes)->partition(function ($value, $key) use ($parameterNames) { + return in_array(Str::camel($key), $parameterNames); + })->all(); + } + + /** + * Compile the closing tags within the given string. + * + * @param string $value + * @return string + */ + protected function compileClosingTags(string $value) + { + return preg_replace("/<\/\s*x[-\:][\w\-\:\.]*\s*>/", ' @endComponentClass##END-COMPONENT-CLASS##', $value); + } + + /** + * Compile the slot tags within the given string. + * + * @param string $value + * @return string + */ + public function compileSlots(string $value) + { + $pattern = "/ + < + \s* + x[\-\:]slot + \s+ + (:?)name=(?(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+)) + (? + (?: + \s+ + (?: + (?: + \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} + ) + | + (?: + [\w\-:.@]+ + ( + = + (?: + \\\"[^\\\"]*\\\" + | + \'[^\']*\' + | + [^\'\\\"=<>]+ + ) + )? + ) + ) + )* + \s* + ) + (? + /x"; + + $value = preg_replace_callback($pattern, function ($matches) { + $name = $this->stripQuotes($matches['name']); + + if ($matches[1] !== ':') { + $name = "'{$name}'"; + } + + $this->boundAttributes = []; + + $attributes = $this->getAttributesFromAttributeString($matches['attributes']); + + return " @slot({$name}, null, [".$this->attributesToString($attributes).']) '; + }, $value); + + return preg_replace('/<\/\s*x[\-\:]slot[^>]*>/', ' @endslot', $value); + } + + /** + * Get an array of attributes from the given attribute string. + * + * @param string $attributeString + * @return array + */ + protected function getAttributesFromAttributeString(string $attributeString) + { + $attributeString = $this->parseAttributeBag($attributeString); + + $attributeString = $this->parseBindAttributes($attributeString); + + $pattern = '/ + (?[\w\-:.@]+) + ( + = + (? + ( + \"[^\"]+\" + | + \\\'[^\\\']+\\\' + | + [^\s>]+ + ) + ) + )? + /x'; + + if (! preg_match_all($pattern, $attributeString, $matches, PREG_SET_ORDER)) { + return []; + } + + return collect($matches)->mapWithKeys(function ($match) { + $attribute = $match['attribute']; + $value = $match['value'] ?? null; + + if (is_null($value)) { + $value = 'true'; + + $attribute = Str::start($attribute, 'bind:'); + } + + $value = $this->stripQuotes($value); + + if (Str::startsWith($attribute, 'bind:')) { + $attribute = Str::after($attribute, 'bind:'); + + $this->boundAttributes[$attribute] = true; + } else { + $value = "'".$this->compileAttributeEchos($value)."'"; + } + + if (Str::startsWith($attribute, '::')) { + $attribute = substr($attribute, 1); + } + + return [$attribute => $value]; + })->toArray(); + } + + /** + * Parse the attribute bag in a given attribute string into its fully-qualified syntax. + * + * @param string $attributeString + * @return string + */ + protected function parseAttributeBag(string $attributeString) + { + $pattern = "/ + (?:^|\s+) # start of the string or whitespace between attributes + \{\{\s*(\\\$attributes(?:[^}]+?(?blade->compileEchos($attributeString); + + $value = $this->escapeSingleQuotesOutsideOfPhpBlocks($value); + + $value = str_replace('', '.\'', $value); + + return $value; + } + + /** + * Escape the single quotes in the given string that are outside of PHP blocks. + * + * @param string $value + * @return string + */ + protected function escapeSingleQuotesOutsideOfPhpBlocks(string $value) + { + return collect(token_get_all($value))->map(function ($token) { + if (! is_array($token)) { + return $token; + } + + return $token[0] === T_INLINE_HTML + ? str_replace("'", "\\'", $token[1]) + : $token[1]; + })->implode(''); + } + + /** + * Convert an array of attributes to a string. + * + * @param array $attributes + * @param bool $escapeBound + * @return string + */ + protected function attributesToString(array $attributes, $escapeBound = true) + { + return collect($attributes) + ->map(function (string $value, string $attribute) use ($escapeBound) { + return $escapeBound && isset($this->boundAttributes[$attribute]) && $value !== 'true' && ! is_numeric($value) + ? "'{$attribute}' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute({$value})" + : "'{$attribute}' => {$value}"; + }) + ->implode(','); + } + + /** + * Strip any quotes from the given string. + * + * @param string $value + * @return string + */ + public function stripQuotes(string $value) + { + return Str::startsWith($value, ['"', '\'']) + ? substr($value, 1, -1) + : $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesAuthorizations.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesAuthorizations.php new file mode 100644 index 0000000..4f96998 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesAuthorizations.php @@ -0,0 +1,102 @@ +check{$expression}): ?>"; + } + + /** + * Compile the cannot statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileCannot($expression) + { + return "denies{$expression}): ?>"; + } + + /** + * Compile the canany statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileCanany($expression) + { + return "any{$expression}): ?>"; + } + + /** + * Compile the else-can statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileElsecan($expression) + { + return "check{$expression}): ?>"; + } + + /** + * Compile the else-cannot statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileElsecannot($expression) + { + return "denies{$expression}): ?>"; + } + + /** + * Compile the else-canany statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileElsecanany($expression) + { + return "any{$expression}): ?>"; + } + + /** + * Compile the end-can statements into valid PHP. + * + * @return string + */ + protected function compileEndcan() + { + return ''; + } + + /** + * Compile the end-cannot statements into valid PHP. + * + * @return string + */ + protected function compileEndcannot() + { + return ''; + } + + /** + * Compile the end-canany statements into valid PHP. + * + * @return string + */ + protected function compileEndcanany() + { + return ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesClasses.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesClasses.php new file mode 100644 index 0000000..b3dbbcd --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesClasses.php @@ -0,0 +1,19 @@ +\""; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesComments.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesComments.php new file mode 100644 index 0000000..104a9c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesComments.php @@ -0,0 +1,19 @@ +contentTags[0], $this->contentTags[1]); + + return preg_replace($pattern, '', $value); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesComponents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesComponents.php new file mode 100644 index 0000000..db4f0e8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesComponents.php @@ -0,0 +1,194 @@ +startComponent{$expression}; ?>"; + } + + /** + * Get a new component hash for a component name. + * + * @param string $component + * @return string + */ + public static function newComponentHash(string $component) + { + static::$componentHashStack[] = $hash = sha1($component); + + return $hash; + } + + /** + * Compile a class component opening. + * + * @param string $component + * @param string $alias + * @param string $data + * @param string $hash + * @return string + */ + public static function compileClassComponentOpening(string $component, string $alias, string $data, string $hash) + { + return implode("\n", [ + '', + 'getContainer()->make('.Str::finish($component, '::class').', '.($data ?: '[]').'); ?>', + 'withName('.$alias.'); ?>', + 'shouldRender()): ?>', + 'startComponent($component->resolveView(), $component->data()); ?>', + ]); + } + + /** + * Compile the end-component statements into valid PHP. + * + * @return string + */ + protected function compileEndComponent() + { + return 'renderComponent(); ?>'; + } + + /** + * Compile the end-component statements into valid PHP. + * + * @return string + */ + public function compileEndComponentClass() + { + $hash = array_pop(static::$componentHashStack); + + return $this->compileEndComponent()."\n".implode("\n", [ + '', + '', + '', + '', + '', + ]); + } + + /** + * Compile the slot statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileSlot($expression) + { + return "slot{$expression}; ?>"; + } + + /** + * Compile the end-slot statements into valid PHP. + * + * @return string + */ + protected function compileEndSlot() + { + return 'endSlot(); ?>'; + } + + /** + * Compile the component-first statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileComponentFirst($expression) + { + return "startComponentFirst{$expression}; ?>"; + } + + /** + * Compile the end-component-first statements into valid PHP. + * + * @return string + */ + protected function compileEndComponentFirst() + { + return $this->compileEndComponent(); + } + + /** + * Compile the prop statement into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileProps($expression) + { + return "exceptProps{$expression}; ?> + \$__value) { + \$\$__key = \$\$__key ?? \$__value; +} ?> + + \$__value) { + if (array_key_exists(\$__key, \$__defined_vars)) unset(\$\$__key); +} ?> +"; + } + + /** + * Compile the aware statement into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileAware($expression) + { + return " \$__value) { + \$__consumeVariable = is_string(\$__key) ? \$__key : \$__value; + \$\$__consumeVariable = is_string(\$__key) ? \$__env->getConsumableComponentData(\$__key, \$__value) : \$__env->getConsumableComponentData(\$__value); +} ?>"; + } + + /** + * Sanitize the given component attribute value. + * + * @param mixed $value + * @return mixed + */ + public static function sanitizeComponentAttribute($value) + { + if (is_object($value) && $value instanceof CanBeEscapedWhenCastToString) { + return $value->escapeWhenCastingToString(); + } + + return is_string($value) || + (is_object($value) && ! $value instanceof ComponentAttributeBag && method_exists($value, '__toString')) + ? e($value) + : $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php new file mode 100644 index 0000000..6bae1e1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php @@ -0,0 +1,307 @@ +guard{$guard}->check()): ?>"; + } + + /** + * Compile the else-auth statements into valid PHP. + * + * @param string|null $guard + * @return string + */ + protected function compileElseAuth($guard = null) + { + $guard = is_null($guard) ? '()' : $guard; + + return "guard{$guard}->check()): ?>"; + } + + /** + * Compile the end-auth statements into valid PHP. + * + * @return string + */ + protected function compileEndAuth() + { + return ''; + } + + /** + * Compile the env statements into valid PHP. + * + * @param string $environments + * @return string + */ + protected function compileEnv($environments) + { + return "environment{$environments}): ?>"; + } + + /** + * Compile the end-env statements into valid PHP. + * + * @return string + */ + protected function compileEndEnv() + { + return ''; + } + + /** + * Compile the production statements into valid PHP. + * + * @return string + */ + protected function compileProduction() + { + return "environment('production')): ?>"; + } + + /** + * Compile the end-production statements into valid PHP. + * + * @return string + */ + protected function compileEndProduction() + { + return ''; + } + + /** + * Compile the if-guest statements into valid PHP. + * + * @param string|null $guard + * @return string + */ + protected function compileGuest($guard = null) + { + $guard = is_null($guard) ? '()' : $guard; + + return "guard{$guard}->guest()): ?>"; + } + + /** + * Compile the else-guest statements into valid PHP. + * + * @param string|null $guard + * @return string + */ + protected function compileElseGuest($guard = null) + { + $guard = is_null($guard) ? '()' : $guard; + + return "guard{$guard}->guest()): ?>"; + } + + /** + * Compile the end-guest statements into valid PHP. + * + * @return string + */ + protected function compileEndGuest() + { + return ''; + } + + /** + * Compile the has-section statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileHasSection($expression) + { + return "yieldContent{$expression}))): ?>"; + } + + /** + * Compile the section-missing statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileSectionMissing($expression) + { + return "yieldContent{$expression}))): ?>"; + } + + /** + * Compile the if statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileIf($expression) + { + return ""; + } + + /** + * Compile the unless statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileUnless($expression) + { + return ""; + } + + /** + * Compile the else-if statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileElseif($expression) + { + return ""; + } + + /** + * Compile the else statements into valid PHP. + * + * @return string + */ + protected function compileElse() + { + return ''; + } + + /** + * Compile the end-if statements into valid PHP. + * + * @return string + */ + protected function compileEndif() + { + return ''; + } + + /** + * Compile the end-unless statements into valid PHP. + * + * @return string + */ + protected function compileEndunless() + { + return ''; + } + + /** + * Compile the if-isset statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileIsset($expression) + { + return ""; + } + + /** + * Compile the end-isset statements into valid PHP. + * + * @return string + */ + protected function compileEndIsset() + { + return ''; + } + + /** + * Compile the switch statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileSwitch($expression) + { + $this->firstCaseInSwitch = true; + + return "firstCaseInSwitch) { + $this->firstCaseInSwitch = false; + + return "case {$expression}: ?>"; + } + + return ""; + } + + /** + * Compile the default statements in switch case into valid PHP. + * + * @return string + */ + protected function compileDefault() + { + return ''; + } + + /** + * Compile the end switch statements into valid PHP. + * + * @return string + */ + protected function compileEndSwitch() + { + return ''; + } + + /** + * Compile a once block into valid PHP. + * + * @param string|null $id + * @return string + */ + protected function compileOnce($id = null) + { + $id = $id ? $this->stripParentheses($id) : "'".(string) Str::uuid()."'"; + + return 'hasRenderedOnce('.$id.')): $__env->markAsRenderedOnce('.$id.'); ?>'; + } + + /** + * Compile an end-once block into valid PHP. + * + * @return string + */ + public function compileEndOnce() + { + return ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesEchos.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesEchos.php new file mode 100644 index 0000000..5924a0a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesEchos.php @@ -0,0 +1,167 @@ +firstClosureParameterType($class), $class]; + } + + $this->echoHandlers[$class] = $handler; + } + + /** + * Compile Blade echos into valid PHP. + * + * @param string $value + * @return string + */ + public function compileEchos($value) + { + foreach ($this->getEchoMethods() as $method) { + $value = $this->$method($value); + } + + return $value; + } + + /** + * Get the echo methods in the proper order for compilation. + * + * @return array + */ + protected function getEchoMethods() + { + return [ + 'compileRawEchos', + 'compileEscapedEchos', + 'compileRegularEchos', + ]; + } + + /** + * Compile the "raw" echo statements. + * + * @param string $value + * @return string + */ + protected function compileRawEchos($value) + { + $pattern = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', $this->rawTags[0], $this->rawTags[1]); + + $callback = function ($matches) { + $whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3]; + + return $matches[1] + ? substr($matches[0], 1) + : "wrapInEchoHandler($matches[2])}; ?>{$whitespace}"; + }; + + return preg_replace_callback($pattern, $callback, $value); + } + + /** + * Compile the "regular" echo statements. + * + * @param string $value + * @return string + */ + protected function compileRegularEchos($value) + { + $pattern = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', $this->contentTags[0], $this->contentTags[1]); + + $callback = function ($matches) { + $whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3]; + + $wrapped = sprintf($this->echoFormat, $this->wrapInEchoHandler($matches[2])); + + return $matches[1] ? substr($matches[0], 1) : "{$whitespace}"; + }; + + return preg_replace_callback($pattern, $callback, $value); + } + + /** + * Compile the escaped echo statements. + * + * @param string $value + * @return string + */ + protected function compileEscapedEchos($value) + { + $pattern = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', $this->escapedTags[0], $this->escapedTags[1]); + + $callback = function ($matches) { + $whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3]; + + return $matches[1] + ? $matches[0] + : "wrapInEchoHandler($matches[2])}); ?>{$whitespace}"; + }; + + return preg_replace_callback($pattern, $callback, $value); + } + + /** + * Add an instance of the blade echo handler to the start of the compiled string. + * + * @param string $result + * @return string + */ + protected function addBladeCompilerVariable($result) + { + return "".$result; + } + + /** + * Wrap the echoable value in an echo handler if applicable. + * + * @param string $value + * @return string + */ + protected function wrapInEchoHandler($value) + { + $value = Str::of($value) + ->trim() + ->when(Str::endsWith($value, ';'), function ($str) { + return $str->beforeLast(';'); + }); + + return empty($this->echoHandlers) ? $value : '$__bladeCompiler->applyEchoHandler('.$value.')'; + } + + /** + * Apply the echo handler for the value if it exists. + * + * @param string $value + * @return string + */ + public function applyEchoHandler($value) + { + if (is_object($value) && isset($this->echoHandlers[get_class($value)])) { + return call_user_func($this->echoHandlers[get_class($value)], $value); + } + + return $value; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesErrors.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesErrors.php new file mode 100644 index 0000000..77edc4b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesErrors.php @@ -0,0 +1,37 @@ +stripParentheses($expression); + + return 'getBag($__errorArgs[1] ?? \'default\'); +if ($__bag->has($__errorArgs[0])) : +if (isset($message)) { $__messageOriginal = $message; } +$message = $__bag->first($__errorArgs[0]); ?>'; + } + + /** + * Compile the enderror statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileEnderror($expression) + { + return ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php new file mode 100644 index 0000000..979cadc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php @@ -0,0 +1,49 @@ +'; + } + + /** + * Compile the "dd" statements into valid PHP. + * + * @param string $arguments + * @return string + */ + protected function compileDd($arguments) + { + return ""; + } + + /** + * Compile the "dump" statements into valid PHP. + * + * @param string $arguments + * @return string + */ + protected function compileDump($arguments) + { + return ""; + } + + /** + * Compile the method statements into valid PHP. + * + * @param string $method + * @return string + */ + protected function compileMethod($method) + { + return ""; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesIncludes.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesIncludes.php new file mode 100644 index 0000000..aa3d4a6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesIncludes.php @@ -0,0 +1,82 @@ +renderEach{$expression}; ?>"; + } + + /** + * Compile the include statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileInclude($expression) + { + $expression = $this->stripParentheses($expression); + + return "make({$expression}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>"; + } + + /** + * Compile the include-if statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileIncludeIf($expression) + { + $expression = $this->stripParentheses($expression); + + return "exists({$expression})) echo \$__env->make({$expression}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>"; + } + + /** + * Compile the include-when statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileIncludeWhen($expression) + { + $expression = $this->stripParentheses($expression); + + return "renderWhen($expression, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path'])); ?>"; + } + + /** + * Compile the include-unless statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileIncludeUnless($expression) + { + $expression = $this->stripParentheses($expression); + + return "renderUnless($expression, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path'])); ?>"; + } + + /** + * Compile the include-first statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileIncludeFirst($expression) + { + $expression = $this->stripParentheses($expression); + + return "first({$expression}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesInjections.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesInjections.php new file mode 100644 index 0000000..a0d1ccf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesInjections.php @@ -0,0 +1,23 @@ +"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesJs.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesJs.php new file mode 100644 index 0000000..3104057 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesJs.php @@ -0,0 +1,22 @@ +toHtml() ?>", + Js::class, $this->stripParentheses($expression) + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesJson.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesJson.php new file mode 100644 index 0000000..cf343e9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesJson.php @@ -0,0 +1,30 @@ +stripParentheses($expression)); + + $options = isset($parts[1]) ? trim($parts[1]) : $this->encodingOptions; + + $depth = isset($parts[2]) ? trim($parts[2]) : 512; + + return ""; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesLayouts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesLayouts.php new file mode 100644 index 0000000..6540603 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesLayouts.php @@ -0,0 +1,133 @@ +stripParentheses($expression); + + $echo = "make({$expression}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>"; + + $this->footer[] = $echo; + + return ''; + } + + /** + * Compile the extends-first statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileExtendsFirst($expression) + { + $expression = $this->stripParentheses($expression); + + $echo = "first({$expression}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>"; + + $this->footer[] = $echo; + + return ''; + } + + /** + * Compile the section statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileSection($expression) + { + $this->lastSection = trim($expression, "()'\" "); + + return "startSection{$expression}; ?>"; + } + + /** + * Replace the @parent directive to a placeholder. + * + * @return string + */ + protected function compileParent() + { + $escapedLastSection = strtr($this->lastSection, ['\\' => '\\\\', "'" => "\\'"]); + + return ""; + } + + /** + * Compile the yield statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileYield($expression) + { + return "yieldContent{$expression}; ?>"; + } + + /** + * Compile the show statements into valid PHP. + * + * @return string + */ + protected function compileShow() + { + return 'yieldSection(); ?>'; + } + + /** + * Compile the append statements into valid PHP. + * + * @return string + */ + protected function compileAppend() + { + return 'appendSection(); ?>'; + } + + /** + * Compile the overwrite statements into valid PHP. + * + * @return string + */ + protected function compileOverwrite() + { + return 'stopSection(true); ?>'; + } + + /** + * Compile the stop statements into valid PHP. + * + * @return string + */ + protected function compileStop() + { + return 'stopSection(); ?>'; + } + + /** + * Compile the end-section statements into valid PHP. + * + * @return string + */ + protected function compileEndsection() + { + return 'stopSection(); ?>'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesLoops.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesLoops.php new file mode 100644 index 0000000..9f64c4f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesLoops.php @@ -0,0 +1,180 @@ +forElseCounter; + + preg_match('/\( *(.*) +as *(.*)\)$/is', $expression, $matches); + + $iteratee = trim($matches[1]); + + $iteration = trim($matches[2]); + + $initLoop = "\$__currentLoopData = {$iteratee}; \$__env->addLoop(\$__currentLoopData);"; + + $iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();'; + + return ""; + } + + /** + * Compile the for-else-empty and empty statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileEmpty($expression) + { + if ($expression) { + return ""; + } + + $empty = '$__empty_'.$this->forElseCounter--; + + return "popLoop(); \$loop = \$__env->getLastLoop(); if ({$empty}): ?>"; + } + + /** + * Compile the end-for-else statements into valid PHP. + * + * @return string + */ + protected function compileEndforelse() + { + return ''; + } + + /** + * Compile the end-empty statements into valid PHP. + * + * @return string + */ + protected function compileEndEmpty() + { + return ''; + } + + /** + * Compile the for statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileFor($expression) + { + return ""; + } + + /** + * Compile the for-each statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileForeach($expression) + { + preg_match('/\( *(.*) +as *(.*)\)$/is', $expression, $matches); + + $iteratee = trim($matches[1]); + + $iteration = trim($matches[2]); + + $initLoop = "\$__currentLoopData = {$iteratee}; \$__env->addLoop(\$__currentLoopData);"; + + $iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();'; + + return ""; + } + + /** + * Compile the break statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileBreak($expression) + { + if ($expression) { + preg_match('/\(\s*(-?\d+)\s*\)$/', $expression, $matches); + + return $matches ? '' : ""; + } + + return ''; + } + + /** + * Compile the continue statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileContinue($expression) + { + if ($expression) { + preg_match('/\(\s*(-?\d+)\s*\)$/', $expression, $matches); + + return $matches ? '' : ""; + } + + return ''; + } + + /** + * Compile the end-for statements into valid PHP. + * + * @return string + */ + protected function compileEndfor() + { + return ''; + } + + /** + * Compile the end-for-each statements into valid PHP. + * + * @return string + */ + protected function compileEndforeach() + { + return 'popLoop(); $loop = $__env->getLastLoop(); ?>'; + } + + /** + * Compile the while statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileWhile($expression) + { + return ""; + } + + /** + * Compile the end-while statements into valid PHP. + * + * @return string + */ + protected function compileEndwhile() + { + return ''; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesRawPhp.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesRawPhp.php new file mode 100644 index 0000000..41c7edf --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesRawPhp.php @@ -0,0 +1,32 @@ +"; + } + + return '@php'; + } + + /** + * Compile the unset statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileUnset($expression) + { + return ""; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php new file mode 100644 index 0000000..79a380e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php @@ -0,0 +1,59 @@ +yieldPushContent{$expression}; ?>"; + } + + /** + * Compile the push statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compilePush($expression) + { + return "startPush{$expression}; ?>"; + } + + /** + * Compile the end-push statements into valid PHP. + * + * @return string + */ + protected function compileEndpush() + { + return 'stopPush(); ?>'; + } + + /** + * Compile the prepend statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compilePrepend($expression) + { + return "startPrepend{$expression}; ?>"; + } + + /** + * Compile the end-prepend statements into valid PHP. + * + * @return string + */ + protected function compileEndprepend() + { + return 'stopPrepend(); ?>'; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesTranslations.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesTranslations.php new file mode 100644 index 0000000..7cbafdb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesTranslations.php @@ -0,0 +1,44 @@ +startTranslation(); ?>'; + } elseif ($expression[1] === '[') { + return "startTranslation{$expression}; ?>"; + } + + return "get{$expression}; ?>"; + } + + /** + * Compile the end-lang statements into valid PHP. + * + * @return string + */ + protected function compileEndlang() + { + return 'renderTranslation(); ?>'; + } + + /** + * Compile the choice statements into valid PHP. + * + * @param string $expression + * @return string + */ + protected function compileChoice($expression) + { + return "choice{$expression}; ?>"; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Component.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Component.php new file mode 100644 index 0000000..8acf9a7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Component.php @@ -0,0 +1,296 @@ +render(); + + if ($view instanceof ViewContract) { + return $view; + } + + if ($view instanceof Htmlable) { + return $view; + } + + $resolver = function ($view) { + $factory = Container::getInstance()->make('view'); + + return strlen($view) <= PHP_MAXPATHLEN && $factory->exists($view) + ? $view + : $this->createBladeViewFromString($factory, $view); + }; + + return $view instanceof Closure ? function (array $data = []) use ($view, $resolver) { + return $resolver($view($data)); + } + : $resolver($view); + } + + /** + * Create a Blade view with the raw component string content. + * + * @param \Illuminate\Contracts\View\Factory $factory + * @param string $contents + * @return string + */ + protected function createBladeViewFromString($factory, $contents) + { + $factory->addNamespace( + '__components', + $directory = Container::getInstance()['config']->get('view.compiled') + ); + + if (! is_file($viewFile = $directory.'/'.sha1($contents).'.blade.php')) { + if (! is_dir($directory)) { + mkdir($directory, 0755, true); + } + + file_put_contents($viewFile, $contents); + } + + return '__components::'.basename($viewFile, '.blade.php'); + } + + /** + * Get the data that should be supplied to the view. + * + * @author Freek Van der Herten + * @author Brent Roose + * + * @return array + */ + public function data() + { + $this->attributes = $this->attributes ?: $this->newAttributeBag(); + + return array_merge($this->extractPublicProperties(), $this->extractPublicMethods()); + } + + /** + * Extract the public properties for the component. + * + * @return array + */ + protected function extractPublicProperties() + { + $class = get_class($this); + + if (! isset(static::$propertyCache[$class])) { + $reflection = new ReflectionClass($this); + + static::$propertyCache[$class] = collect($reflection->getProperties(ReflectionProperty::IS_PUBLIC)) + ->reject(function (ReflectionProperty $property) { + return $property->isStatic(); + }) + ->reject(function (ReflectionProperty $property) { + return $this->shouldIgnore($property->getName()); + }) + ->map(function (ReflectionProperty $property) { + return $property->getName(); + })->all(); + } + + $values = []; + + foreach (static::$propertyCache[$class] as $property) { + $values[$property] = $this->{$property}; + } + + return $values; + } + + /** + * Extract the public methods for the component. + * + * @return array + */ + protected function extractPublicMethods() + { + $class = get_class($this); + + if (! isset(static::$methodCache[$class])) { + $reflection = new ReflectionClass($this); + + static::$methodCache[$class] = collect($reflection->getMethods(ReflectionMethod::IS_PUBLIC)) + ->reject(function (ReflectionMethod $method) { + return $this->shouldIgnore($method->getName()); + }) + ->map(function (ReflectionMethod $method) { + return $method->getName(); + }); + } + + $values = []; + + foreach (static::$methodCache[$class] as $method) { + $values[$method] = $this->createVariableFromMethod(new ReflectionMethod($this, $method)); + } + + return $values; + } + + /** + * Create a callable variable from the given method. + * + * @param \ReflectionMethod $method + * @return mixed + */ + protected function createVariableFromMethod(ReflectionMethod $method) + { + return $method->getNumberOfParameters() === 0 + ? $this->createInvokableVariable($method->getName()) + : Closure::fromCallable([$this, $method->getName()]); + } + + /** + * Create an invokable, toStringable variable for the given component method. + * + * @param string $method + * @return \Illuminate\View\InvokableComponentVariable + */ + protected function createInvokableVariable(string $method) + { + return new InvokableComponentVariable(function () use ($method) { + return $this->{$method}(); + }); + } + + /** + * Determine if the given property / method should be ignored. + * + * @param string $name + * @return bool + */ + protected function shouldIgnore($name) + { + return Str::startsWith($name, '__') || + in_array($name, $this->ignoredMethods()); + } + + /** + * Get the methods that should be ignored. + * + * @return array + */ + protected function ignoredMethods() + { + return array_merge([ + 'data', + 'render', + 'resolveView', + 'shouldRender', + 'view', + 'withName', + 'withAttributes', + ], $this->except); + } + + /** + * Set the component alias name. + * + * @param string $name + * @return $this + */ + public function withName($name) + { + $this->componentName = $name; + + return $this; + } + + /** + * Set the extra attributes that the component should make available. + * + * @param array $attributes + * @return $this + */ + public function withAttributes(array $attributes) + { + $this->attributes = $this->attributes ?: $this->newAttributeBag(); + + $this->attributes->setAttributes($attributes); + + return $this; + } + + /** + * Get a new attribute bag instance. + * + * @param array $attributes + * @return \Illuminate\View\ComponentAttributeBag + */ + protected function newAttributeBag(array $attributes = []) + { + return new ComponentAttributeBag($attributes); + } + + /** + * Determine if the component should be rendered. + * + * @return bool + */ + public function shouldRender() + { + return true; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ComponentAttributeBag.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ComponentAttributeBag.php new file mode 100644 index 0000000..255d164 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ComponentAttributeBag.php @@ -0,0 +1,403 @@ +attributes = $attributes; + } + + /** + * Get the first attribute's value. + * + * @param mixed $default + * @return mixed + */ + public function first($default = null) + { + return $this->getIterator()->current() ?? value($default); + } + + /** + * Get a given attribute from the attribute array. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + return $this->attributes[$key] ?? value($default); + } + + /** + * Determine if a given attribute exists in the attribute array. + * + * @param string $key + * @return bool + */ + public function has($key) + { + return array_key_exists($key, $this->attributes); + } + + /** + * Only include the given attribute from the attribute array. + * + * @param mixed $keys + * @return static + */ + public function only($keys) + { + if (is_null($keys)) { + $values = $this->attributes; + } else { + $keys = Arr::wrap($keys); + + $values = Arr::only($this->attributes, $keys); + } + + return new static($values); + } + + /** + * Exclude the given attribute from the attribute array. + * + * @param mixed|array $keys + * @return static + */ + public function except($keys) + { + if (is_null($keys)) { + $values = $this->attributes; + } else { + $keys = Arr::wrap($keys); + + $values = Arr::except($this->attributes, $keys); + } + + return new static($values); + } + + /** + * Filter the attributes, returning a bag of attributes that pass the filter. + * + * @param callable $callback + * @return static + */ + public function filter($callback) + { + return new static(collect($this->attributes)->filter($callback)->all()); + } + + /** + * Return a bag of attributes that have keys starting with the given value / pattern. + * + * @param string|string[] $needles + * @return static + */ + public function whereStartsWith($needles) + { + return $this->filter(function ($value, $key) use ($needles) { + return Str::startsWith($key, $needles); + }); + } + + /** + * Return a bag of attributes with keys that do not start with the given value / pattern. + * + * @param string|string[] $needles + * @return static + */ + public function whereDoesntStartWith($needles) + { + return $this->filter(function ($value, $key) use ($needles) { + return ! Str::startsWith($key, $needles); + }); + } + + /** + * Return a bag of attributes that have keys starting with the given value / pattern. + * + * @param string|string[] $needles + * @return static + */ + public function thatStartWith($needles) + { + return $this->whereStartsWith($needles); + } + + /** + * Exclude the given attribute from the attribute array. + * + * @param mixed|array $keys + * @return static + */ + public function exceptProps($keys) + { + $props = []; + + foreach ($keys as $key => $defaultValue) { + $key = is_numeric($key) ? $defaultValue : $key; + + $props[] = $key; + $props[] = Str::kebab($key); + } + + return $this->except($props); + } + + /** + * Conditionally merge classes into the attribute bag. + * + * @param mixed|array $classList + * @return static + */ + public function class($classList) + { + $classList = Arr::wrap($classList); + + return $this->merge(['class' => Arr::toCssClasses($classList)]); + } + + /** + * Merge additional attributes / values into the attribute bag. + * + * @param array $attributeDefaults + * @param bool $escape + * @return static + */ + public function merge(array $attributeDefaults = [], $escape = true) + { + $attributeDefaults = array_map(function ($value) use ($escape) { + return $this->shouldEscapeAttributeValue($escape, $value) + ? e($value) + : $value; + }, $attributeDefaults); + + [$appendableAttributes, $nonAppendableAttributes] = collect($this->attributes) + ->partition(function ($value, $key) use ($attributeDefaults) { + return $key === 'class' || + (isset($attributeDefaults[$key]) && + $attributeDefaults[$key] instanceof AppendableAttributeValue); + }); + + $attributes = $appendableAttributes->mapWithKeys(function ($value, $key) use ($attributeDefaults, $escape) { + $defaultsValue = isset($attributeDefaults[$key]) && $attributeDefaults[$key] instanceof AppendableAttributeValue + ? $this->resolveAppendableAttributeDefault($attributeDefaults, $key, $escape) + : ($attributeDefaults[$key] ?? ''); + + return [$key => implode(' ', array_unique(array_filter([$defaultsValue, $value])))]; + })->merge($nonAppendableAttributes)->all(); + + return new static(array_merge($attributeDefaults, $attributes)); + } + + /** + * Determine if the specific attribute value should be escaped. + * + * @param bool $escape + * @param mixed $value + * @return bool + */ + protected function shouldEscapeAttributeValue($escape, $value) + { + if (! $escape) { + return false; + } + + return ! is_object($value) && + ! is_null($value) && + ! is_bool($value); + } + + /** + * Create a new appendable attribute value. + * + * @param mixed $value + * @return \Illuminate\View\AppendableAttributeValue + */ + public function prepends($value) + { + return new AppendableAttributeValue($value); + } + + /** + * Resolve an appendable attribute value default value. + * + * @param array $attributeDefaults + * @param string $key + * @param bool $escape + * @return mixed + */ + protected function resolveAppendableAttributeDefault($attributeDefaults, $key, $escape) + { + if ($this->shouldEscapeAttributeValue($escape, $value = $attributeDefaults[$key]->value)) { + $value = e($value); + } + + return $value; + } + + /** + * Get all of the raw attributes. + * + * @return array + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Set the underlying attributes. + * + * @param array $attributes + * @return void + */ + public function setAttributes(array $attributes) + { + if (isset($attributes['attributes']) && + $attributes['attributes'] instanceof self) { + $parentBag = $attributes['attributes']; + + unset($attributes['attributes']); + + $attributes = $parentBag->merge($attributes, $escape = false)->getAttributes(); + } + + $this->attributes = $attributes; + } + + /** + * Get content as a string of HTML. + * + * @return string + */ + public function toHtml() + { + return (string) $this; + } + + /** + * Merge additional attributes / values into the attribute bag. + * + * @param array $attributeDefaults + * @return \Illuminate\Support\HtmlString + */ + public function __invoke(array $attributeDefaults = []) + { + return new HtmlString((string) $this->merge($attributeDefaults)); + } + + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($offset) + { + return isset($this->attributes[$offset]); + } + + /** + * Get the value at the given offset. + * + * @param string $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->get($offset); + } + + /** + * Set the value at a given offset. + * + * @param string $offset + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value) + { + $this->attributes[$offset] = $value; + } + + /** + * Remove the value at the given offset. + * + * @param string $offset + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset) + { + unset($this->attributes[$offset]); + } + + /** + * Get an iterator for the items. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new ArrayIterator($this->attributes); + } + + /** + * Implode the attributes into a single HTML ready string. + * + * @return string + */ + public function __toString() + { + $string = ''; + + foreach ($this->attributes as $key => $value) { + if ($value === false || is_null($value)) { + continue; + } + + if ($value === true) { + $value = $key; + } + + $string .= ' '.$key.'="'.str_replace('"', '\\"', trim($value)).'"'; + } + + return trim($string); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ComponentSlot.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ComponentSlot.php new file mode 100644 index 0000000..85665ad --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ComponentSlot.php @@ -0,0 +1,89 @@ +contents = $contents; + + $this->withAttributes($attributes); + } + + /** + * Set the extra attributes that the slot should make available. + * + * @param array $attributes + * @return $this + */ + public function withAttributes(array $attributes) + { + $this->attributes = new ComponentAttributeBag($attributes); + + return $this; + } + + /** + * Get the slot's HTML string. + * + * @return string + */ + public function toHtml() + { + return $this->contents; + } + + /** + * Determine if the slot is empty. + * + * @return bool + */ + public function isEmpty() + { + return $this->contents === ''; + } + + /** + * Determine if the slot is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return ! $this->isEmpty(); + } + + /** + * Get the slot's HTML string. + * + * @return string + */ + public function __toString() + { + return $this->toHtml(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesComponents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesComponents.php new file mode 100644 index 0000000..f24908f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesComponents.php @@ -0,0 +1,222 @@ +componentStack[] = $view; + + $this->componentData[$this->currentComponent()] = $data; + + $this->slots[$this->currentComponent()] = []; + } + } + + /** + * Get the first view that actually exists from the given list, and start a component. + * + * @param array $names + * @param array $data + * @return void + */ + public function startComponentFirst(array $names, array $data = []) + { + $name = Arr::first($names, function ($item) { + return $this->exists($item); + }); + + $this->startComponent($name, $data); + } + + /** + * Render the current component. + * + * @return string + */ + public function renderComponent() + { + $view = array_pop($this->componentStack); + + $this->currentComponentData = array_merge( + $previousComponentData = $this->currentComponentData, + $data = $this->componentData() + ); + + try { + $view = value($view, $data); + + if ($view instanceof View) { + return $view->with($data)->render(); + } elseif ($view instanceof Htmlable) { + return $view->toHtml(); + } else { + return $this->make($view, $data)->render(); + } + } finally { + $this->currentComponentData = $previousComponentData; + } + } + + /** + * Get the data for the given component. + * + * @return array + */ + protected function componentData() + { + $defaultSlot = new HtmlString(trim(ob_get_clean())); + + $slots = array_merge([ + '__default' => $defaultSlot, + ], $this->slots[count($this->componentStack)]); + + return array_merge( + $this->componentData[count($this->componentStack)], + ['slot' => $defaultSlot], + $this->slots[count($this->componentStack)], + ['__laravel_slots' => $slots] + ); + } + + /** + * Get an item from the component data that exists above the current component. + * + * @param string $key + * @param mixed $default + * @return mixed|null + */ + public function getConsumableComponentData($key, $default = null) + { + if (array_key_exists($key, $this->currentComponentData)) { + return $this->currentComponentData[$key]; + } + + $currentComponent = count($this->componentStack); + + if ($currentComponent === 0) { + return value($default); + } + + for ($i = $currentComponent - 1; $i >= 0; $i--) { + $data = $this->componentData[$i] ?? []; + + if (array_key_exists($key, $data)) { + return $data[$key]; + } + } + + return value($default); + } + + /** + * Start the slot rendering process. + * + * @param string $name + * @param string|null $content + * @param array $attributes + * @return void + */ + public function slot($name, $content = null, $attributes = []) + { + if (func_num_args() === 2 || $content !== null) { + $this->slots[$this->currentComponent()][$name] = $content; + } elseif (ob_start()) { + $this->slots[$this->currentComponent()][$name] = ''; + + $this->slotStack[$this->currentComponent()][] = [$name, $attributes]; + } + } + + /** + * Save the slot content for rendering. + * + * @return void + */ + public function endSlot() + { + last($this->componentStack); + + $currentSlot = array_pop( + $this->slotStack[$this->currentComponent()] + ); + + [$currentName, $currentAttributes] = $currentSlot; + + $this->slots[$this->currentComponent()][$currentName] = new ComponentSlot( + trim(ob_get_clean()), $currentAttributes + ); + } + + /** + * Get the index for the current component. + * + * @return int + */ + protected function currentComponent() + { + return count($this->componentStack) - 1; + } + + /** + * Flush all of the component state. + * + * @return void + */ + protected function flushComponents() + { + $this->componentStack = []; + $this->componentData = []; + $this->currentComponentData = []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesEvents.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesEvents.php new file mode 100644 index 0000000..3990290 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesEvents.php @@ -0,0 +1,190 @@ +addViewEvent($view, $callback, 'creating: '); + } + + return $creators; + } + + /** + * Register multiple view composers via an array. + * + * @param array $composers + * @return array + */ + public function composers(array $composers) + { + $registered = []; + + foreach ($composers as $callback => $views) { + $registered = array_merge($registered, $this->composer($views, $callback)); + } + + return $registered; + } + + /** + * Register a view composer event. + * + * @param array|string $views + * @param \Closure|string $callback + * @return array + */ + public function composer($views, $callback) + { + $composers = []; + + foreach ((array) $views as $view) { + $composers[] = $this->addViewEvent($view, $callback, 'composing: '); + } + + return $composers; + } + + /** + * Add an event for a given view. + * + * @param string $view + * @param \Closure|string $callback + * @param string $prefix + * @return \Closure|null + */ + protected function addViewEvent($view, $callback, $prefix = 'composing: ') + { + $view = $this->normalizeName($view); + + if ($callback instanceof Closure) { + $this->addEventListener($prefix.$view, $callback); + + return $callback; + } elseif (is_string($callback)) { + return $this->addClassEvent($view, $callback, $prefix); + } + } + + /** + * Register a class based view composer. + * + * @param string $view + * @param string $class + * @param string $prefix + * @return \Closure + */ + protected function addClassEvent($view, $class, $prefix) + { + $name = $prefix.$view; + + // When registering a class based view "composer", we will simply resolve the + // classes from the application IoC container then call the compose method + // on the instance. This allows for convenient, testable view composers. + $callback = $this->buildClassEventCallback( + $class, $prefix + ); + + $this->addEventListener($name, $callback); + + return $callback; + } + + /** + * Build a class based container callback Closure. + * + * @param string $class + * @param string $prefix + * @return \Closure + */ + protected function buildClassEventCallback($class, $prefix) + { + [$class, $method] = $this->parseClassEvent($class, $prefix); + + // Once we have the class and method name, we can build the Closure to resolve + // the instance out of the IoC container and call the method on it with the + // given arguments that are passed to the Closure as the composer's data. + return function () use ($class, $method) { + return $this->container->make($class)->{$method}(...func_get_args()); + }; + } + + /** + * Parse a class based composer name. + * + * @param string $class + * @param string $prefix + * @return array + */ + protected function parseClassEvent($class, $prefix) + { + return Str::parseCallback($class, $this->classEventMethodForPrefix($prefix)); + } + + /** + * Determine the class event method based on the given prefix. + * + * @param string $prefix + * @return string + */ + protected function classEventMethodForPrefix($prefix) + { + return Str::contains($prefix, 'composing') ? 'compose' : 'create'; + } + + /** + * Add a listener to the event dispatcher. + * + * @param string $name + * @param \Closure $callback + * @return void + */ + protected function addEventListener($name, $callback) + { + if (Str::contains($name, '*')) { + $callback = function ($name, array $data) use ($callback) { + return $callback($data[0]); + }; + } + + $this->events->listen($name, $callback); + } + + /** + * Call the composer for a given view. + * + * @param \Illuminate\Contracts\View\View $view + * @return void + */ + public function callComposer(ViewContract $view) + { + $this->events->dispatch('composing: '.$view->name(), [$view]); + } + + /** + * Call the creator for a given view. + * + * @param \Illuminate\Contracts\View\View $view + * @return void + */ + public function callCreator(ViewContract $view) + { + $this->events->dispatch('creating: '.$view->name(), [$view]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesLayouts.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesLayouts.php new file mode 100644 index 0000000..f045126 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesLayouts.php @@ -0,0 +1,255 @@ +sectionStack[] = $section; + } + } else { + $this->extendSection($section, $content instanceof View ? $content : e($content)); + } + } + + /** + * Inject inline content into a section. + * + * @param string $section + * @param string $content + * @return void + */ + public function inject($section, $content) + { + $this->startSection($section, $content); + } + + /** + * Stop injecting content into a section and return its contents. + * + * @return string + */ + public function yieldSection() + { + if (empty($this->sectionStack)) { + return ''; + } + + return $this->yieldContent($this->stopSection()); + } + + /** + * Stop injecting content into a section. + * + * @param bool $overwrite + * @return string + * + * @throws \InvalidArgumentException + */ + public function stopSection($overwrite = false) + { + if (empty($this->sectionStack)) { + throw new InvalidArgumentException('Cannot end a section without first starting one.'); + } + + $last = array_pop($this->sectionStack); + + if ($overwrite) { + $this->sections[$last] = ob_get_clean(); + } else { + $this->extendSection($last, ob_get_clean()); + } + + return $last; + } + + /** + * Stop injecting content into a section and append it. + * + * @return string + * + * @throws \InvalidArgumentException + */ + public function appendSection() + { + if (empty($this->sectionStack)) { + throw new InvalidArgumentException('Cannot end a section without first starting one.'); + } + + $last = array_pop($this->sectionStack); + + if (isset($this->sections[$last])) { + $this->sections[$last] .= ob_get_clean(); + } else { + $this->sections[$last] = ob_get_clean(); + } + + return $last; + } + + /** + * Append content to a given section. + * + * @param string $section + * @param string $content + * @return void + */ + protected function extendSection($section, $content) + { + if (isset($this->sections[$section])) { + $content = str_replace(static::parentPlaceholder($section), $content, $this->sections[$section]); + } + + $this->sections[$section] = $content; + } + + /** + * Get the string contents of a section. + * + * @param string $section + * @param string $default + * @return string + */ + public function yieldContent($section, $default = '') + { + $sectionContent = $default instanceof View ? $default : e($default); + + if (isset($this->sections[$section])) { + $sectionContent = $this->sections[$section]; + } + + $sectionContent = str_replace('@@parent', '--parent--holder--', $sectionContent); + + return str_replace( + '--parent--holder--', '@parent', str_replace(static::parentPlaceholder($section), '', $sectionContent) + ); + } + + /** + * Get the parent placeholder for the current request. + * + * @param string $section + * @return string + */ + public static function parentPlaceholder($section = '') + { + if (! isset(static::$parentPlaceholder[$section])) { + $salt = static::parentPlaceholderSalt(); + + static::$parentPlaceholder[$section] = '##parent-placeholder-'.sha1($salt.$section).'##'; + } + + return static::$parentPlaceholder[$section]; + } + + /** + * Get the parent placeholder salt. + * + * @return string + */ + protected static function parentPlaceholderSalt() + { + if (! static::$parentPlaceholderSalt) { + return static::$parentPlaceholderSalt = Str::random(40); + } + + return static::$parentPlaceholderSalt; + } + + /** + * Check if section exists. + * + * @param string $name + * @return bool + */ + public function hasSection($name) + { + return array_key_exists($name, $this->sections); + } + + /** + * Check if section does not exist. + * + * @param string $name + * @return bool + */ + public function sectionMissing($name) + { + return ! $this->hasSection($name); + } + + /** + * Get the contents of a section. + * + * @param string $name + * @param string|null $default + * @return mixed + */ + public function getSection($name, $default = null) + { + return $this->getSections()[$name] ?? $default; + } + + /** + * Get the entire array of sections. + * + * @return array + */ + public function getSections() + { + return $this->sections; + } + + /** + * Flush all of the sections. + * + * @return void + */ + public function flushSections() + { + $this->sections = []; + $this->sectionStack = []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesLoops.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesLoops.php new file mode 100644 index 0000000..edd6363 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesLoops.php @@ -0,0 +1,94 @@ +loopsStack); + + $this->loopsStack[] = [ + 'iteration' => 0, + 'index' => 0, + 'remaining' => $length ?? null, + 'count' => $length, + 'first' => true, + 'last' => isset($length) ? $length == 1 : null, + 'odd' => false, + 'even' => true, + 'depth' => count($this->loopsStack) + 1, + 'parent' => $parent ? (object) $parent : null, + ]; + } + + /** + * Increment the top loop's indices. + * + * @return void + */ + public function incrementLoopIndices() + { + $loop = $this->loopsStack[$index = count($this->loopsStack) - 1]; + + $this->loopsStack[$index] = array_merge($this->loopsStack[$index], [ + 'iteration' => $loop['iteration'] + 1, + 'index' => $loop['iteration'], + 'first' => $loop['iteration'] == 0, + 'odd' => ! $loop['odd'], + 'even' => ! $loop['even'], + 'remaining' => isset($loop['count']) ? $loop['remaining'] - 1 : null, + 'last' => isset($loop['count']) ? $loop['iteration'] == $loop['count'] - 1 : null, + ]); + } + + /** + * Pop a loop from the top of the loop stack. + * + * @return void + */ + public function popLoop() + { + array_pop($this->loopsStack); + } + + /** + * Get an instance of the last loop in the stack. + * + * @return \stdClass|null + */ + public function getLastLoop() + { + if ($last = Arr::last($this->loopsStack)) { + return (object) $last; + } + } + + /** + * Get the entire loop stack. + * + * @return array + */ + public function getLoopStack() + { + return $this->loopsStack; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesStacks.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesStacks.php new file mode 100644 index 0000000..4e063af --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesStacks.php @@ -0,0 +1,179 @@ +pushStack[] = $section; + } + } else { + $this->extendPush($section, $content); + } + } + + /** + * Stop injecting content into a push section. + * + * @return string + * + * @throws \InvalidArgumentException + */ + public function stopPush() + { + if (empty($this->pushStack)) { + throw new InvalidArgumentException('Cannot end a push stack without first starting one.'); + } + + return tap(array_pop($this->pushStack), function ($last) { + $this->extendPush($last, ob_get_clean()); + }); + } + + /** + * Append content to a given push section. + * + * @param string $section + * @param string $content + * @return void + */ + protected function extendPush($section, $content) + { + if (! isset($this->pushes[$section])) { + $this->pushes[$section] = []; + } + + if (! isset($this->pushes[$section][$this->renderCount])) { + $this->pushes[$section][$this->renderCount] = $content; + } else { + $this->pushes[$section][$this->renderCount] .= $content; + } + } + + /** + * Start prepending content into a push section. + * + * @param string $section + * @param string $content + * @return void + */ + public function startPrepend($section, $content = '') + { + if ($content === '') { + if (ob_start()) { + $this->pushStack[] = $section; + } + } else { + $this->extendPrepend($section, $content); + } + } + + /** + * Stop prepending content into a push section. + * + * @return string + * + * @throws \InvalidArgumentException + */ + public function stopPrepend() + { + if (empty($this->pushStack)) { + throw new InvalidArgumentException('Cannot end a prepend operation without first starting one.'); + } + + return tap(array_pop($this->pushStack), function ($last) { + $this->extendPrepend($last, ob_get_clean()); + }); + } + + /** + * Prepend content to a given stack. + * + * @param string $section + * @param string $content + * @return void + */ + protected function extendPrepend($section, $content) + { + if (! isset($this->prepends[$section])) { + $this->prepends[$section] = []; + } + + if (! isset($this->prepends[$section][$this->renderCount])) { + $this->prepends[$section][$this->renderCount] = $content; + } else { + $this->prepends[$section][$this->renderCount] = $content.$this->prepends[$section][$this->renderCount]; + } + } + + /** + * Get the string contents of a push section. + * + * @param string $section + * @param string $default + * @return string + */ + public function yieldPushContent($section, $default = '') + { + if (! isset($this->pushes[$section]) && ! isset($this->prepends[$section])) { + return $default; + } + + $output = ''; + + if (isset($this->prepends[$section])) { + $output .= implode(array_reverse($this->prepends[$section])); + } + + if (isset($this->pushes[$section])) { + $output .= implode($this->pushes[$section]); + } + + return $output; + } + + /** + * Flush all of the stacks. + * + * @return void + */ + public function flushStacks() + { + $this->pushes = []; + $this->prepends = []; + $this->pushStack = []; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesTranslations.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesTranslations.php new file mode 100644 index 0000000..a77fc26 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Concerns/ManagesTranslations.php @@ -0,0 +1,38 @@ +translationReplacements = $replacements; + } + + /** + * Render the current translation. + * + * @return string + */ + public function renderTranslation() + { + return $this->container->make('translator')->get( + trim(ob_get_clean()), $this->translationReplacements + ); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/DynamicComponent.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/DynamicComponent.php new file mode 100644 index 0000000..cea66e7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/DynamicComponent.php @@ -0,0 +1,172 @@ +component = $component; + } + + /** + * Get the view / contents that represent the component. + * + * @return \Illuminate\Contracts\View\View|string + */ + public function render() + { + $template = <<<'EOF' +getAttributes())->mapWithKeys(function ($value, $key) { return [Illuminate\Support\Str::camel(str_replace([':', '.'], ' ', $key)) => $value]; })->all(), EXTR_SKIP); ?> +{{ props }} + +{{ slots }} +{{ defaultSlot }} + +EOF; + + return function ($data) use ($template) { + $bindings = $this->bindings($class = $this->classForComponent()); + + return str_replace( + [ + '{{ component }}', + '{{ props }}', + '{{ bindings }}', + '{{ attributes }}', + '{{ slots }}', + '{{ defaultSlot }}', + ], + [ + $this->component, + $this->compileProps($bindings), + $this->compileBindings($bindings), + class_exists($class) ? '{{ $attributes }}' : '', + $this->compileSlots($data['__laravel_slots']), + '{{ $slot ?? "" }}', + ], + $template + ); + }; + } + + /** + * Compile the @props directive for the component. + * + * @param array $bindings + * @return string + */ + protected function compileProps(array $bindings) + { + if (empty($bindings)) { + return ''; + } + + return '@props('.'[\''.implode('\',\'', collect($bindings)->map(function ($dataKey) { + return Str::camel($dataKey); + })->all()).'\']'.')'; + } + + /** + * Compile the bindings for the component. + * + * @param array $bindings + * @return string + */ + protected function compileBindings(array $bindings) + { + return collect($bindings)->map(function ($key) { + return ':'.$key.'="$'.Str::camel(str_replace([':', '.'], ' ', $key)).'"'; + })->implode(' '); + } + + /** + * Compile the slots for the component. + * + * @param array $slots + * @return string + */ + protected function compileSlots(array $slots) + { + return collect($slots)->map(function ($slot, $name) { + return $name === '__default' ? null : 'attributes).'>{{ $'.$name.' }}'; + })->filter()->implode(PHP_EOL); + } + + /** + * Get the class for the current component. + * + * @return string + */ + protected function classForComponent() + { + if (isset(static::$componentClasses[$this->component])) { + return static::$componentClasses[$this->component]; + } + + return static::$componentClasses[$this->component] = + $this->compiler()->componentClass($this->component); + } + + /** + * Get the names of the variables that should be bound to the component. + * + * @param string $class + * @return array + */ + protected function bindings(string $class) + { + [$data, $attributes] = $this->compiler()->partitionDataAndAttributes($class, $this->attributes->getAttributes()); + + return array_keys($data->all()); + } + + /** + * Get an instance of the Blade tag compiler. + * + * @return \Illuminate\View\Compilers\ComponentTagCompiler + */ + protected function compiler() + { + if (! static::$compiler) { + static::$compiler = new ComponentTagCompiler( + Container::getInstance()->make('blade.compiler')->getClassComponentAliases(), + Container::getInstance()->make('blade.compiler')->getClassComponentNamespaces(), + Container::getInstance()->make('blade.compiler') + ); + } + + return static::$compiler; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php new file mode 100755 index 0000000..dca6a87 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php @@ -0,0 +1,104 @@ +compiler = $compiler; + } + + /** + * Get the evaluated contents of the view. + * + * @param string $path + * @param array $data + * @return string + */ + public function get($path, array $data = []) + { + $this->lastCompiled[] = $path; + + // If this given view has expired, which means it has simply been edited since + // it was last compiled, we will re-compile the views so we can evaluate a + // fresh copy of the view. We'll pass the compiler the path of the view. + if ($this->compiler->isExpired($path)) { + $this->compiler->compile($path); + } + + // Once we have the path to the compiled file, we will evaluate the paths with + // typical PHP just like any other templates. We also keep a stack of views + // which have been rendered for right exception messages to be generated. + $results = $this->evaluatePath($this->compiler->getCompiledPath($path), $data); + + array_pop($this->lastCompiled); + + return $results; + } + + /** + * Handle a view exception. + * + * @param \Throwable $e + * @param int $obLevel + * @return void + * + * @throws \Throwable + */ + protected function handleViewException(Throwable $e, $obLevel) + { + $e = new ViewException($this->getMessage($e), 0, 1, $e->getFile(), $e->getLine(), $e); + + parent::handleViewException($e, $obLevel); + } + + /** + * Get the exception message for an exception. + * + * @param \Throwable $e + * @return string + */ + protected function getMessage(Throwable $e) + { + return $e->getMessage().' (View: '.realpath(last($this->lastCompiled)).')'; + } + + /** + * Get the compiler implementation. + * + * @return \Illuminate\View\Compilers\CompilerInterface + */ + public function getCompiler() + { + return $this->compiler; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/Engine.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/Engine.php new file mode 100755 index 0000000..bf5c748 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/Engine.php @@ -0,0 +1,23 @@ +lastRendered; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/EngineResolver.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/EngineResolver.php new file mode 100755 index 0000000..6740407 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/EngineResolver.php @@ -0,0 +1,71 @@ +forget($engine); + + $this->resolvers[$engine] = $resolver; + } + + /** + * Resolve an engine instance by name. + * + * @param string $engine + * @return \Illuminate\Contracts\View\Engine + * + * @throws \InvalidArgumentException + */ + public function resolve($engine) + { + if (isset($this->resolved[$engine])) { + return $this->resolved[$engine]; + } + + if (isset($this->resolvers[$engine])) { + return $this->resolved[$engine] = call_user_func($this->resolvers[$engine]); + } + + throw new InvalidArgumentException("Engine [{$engine}] not found."); + } + + /** + * Remove a resolved engine. + * + * @param string $engine + * @return void + */ + public function forget($engine) + { + unset($this->resolved[$engine]); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/FileEngine.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/FileEngine.php new file mode 100644 index 0000000..992f675 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/FileEngine.php @@ -0,0 +1,39 @@ +files = $files; + } + + /** + * Get the evaluated contents of the view. + * + * @param string $path + * @param array $data + * @return string + */ + public function get($path, array $data = []) + { + return $this->files->get($path); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php new file mode 100755 index 0000000..13525ae --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php @@ -0,0 +1,83 @@ +files = $files; + } + + /** + * Get the evaluated contents of the view. + * + * @param string $path + * @param array $data + * @return string + */ + public function get($path, array $data = []) + { + return $this->evaluatePath($path, $data); + } + + /** + * Get the evaluated contents of the view at the given path. + * + * @param string $path + * @param array $data + * @return string + */ + protected function evaluatePath($path, $data) + { + $obLevel = ob_get_level(); + + ob_start(); + + // We'll evaluate the contents of the view inside a try/catch block so we can + // flush out any stray output that might get out before an error occurs or + // an exception is thrown. This prevents any partial views from leaking. + try { + $this->files->getRequire($path, $data); + } catch (Throwable $e) { + $this->handleViewException($e, $obLevel); + } + + return ltrim(ob_get_clean()); + } + + /** + * Handle a view exception. + * + * @param \Throwable $e + * @param int $obLevel + * @return void + * + * @throws \Throwable + */ + protected function handleViewException(Throwable $e, $obLevel) + { + while (ob_get_level() > $obLevel) { + ob_end_clean(); + } + + throw $e; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Factory.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Factory.php new file mode 100755 index 0000000..de431f7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Factory.php @@ -0,0 +1,613 @@ + 'blade', + 'php' => 'php', + 'css' => 'file', + 'html' => 'file', + ]; + + /** + * The view composer events. + * + * @var array + */ + protected $composers = []; + + /** + * The number of active rendering operations. + * + * @var int + */ + protected $renderCount = 0; + + /** + * The "once" block IDs that have been rendered. + * + * @var array + */ + protected $renderedOnce = []; + + /** + * Create a new view factory instance. + * + * @param \Illuminate\View\Engines\EngineResolver $engines + * @param \Illuminate\View\ViewFinderInterface $finder + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + */ + public function __construct(EngineResolver $engines, ViewFinderInterface $finder, Dispatcher $events) + { + $this->finder = $finder; + $this->events = $events; + $this->engines = $engines; + + $this->share('__env', $this); + } + + /** + * Get the evaluated view contents for the given view. + * + * @param string $path + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View + */ + public function file($path, $data = [], $mergeData = []) + { + $data = array_merge($mergeData, $this->parseData($data)); + + return tap($this->viewInstance($path, $path, $data), function ($view) { + $this->callCreator($view); + }); + } + + /** + * Get the evaluated view contents for the given view. + * + * @param string $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View + */ + public function make($view, $data = [], $mergeData = []) + { + $path = $this->finder->find( + $view = $this->normalizeName($view) + ); + + // Next, we will create the view instance and call the view creator for the view + // which can set any data, etc. Then we will return the view instance back to + // the caller for rendering or performing other view manipulations on this. + $data = array_merge($mergeData, $this->parseData($data)); + + return tap($this->viewInstance($view, $path, $data), function ($view) { + $this->callCreator($view); + }); + } + + /** + * Get the first view that actually exists from the given list. + * + * @param array $views + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View + * + * @throws \InvalidArgumentException + */ + public function first(array $views, $data = [], $mergeData = []) + { + $view = Arr::first($views, function ($view) { + return $this->exists($view); + }); + + if (! $view) { + throw new InvalidArgumentException('None of the views in the given array exist.'); + } + + return $this->make($view, $data, $mergeData); + } + + /** + * Get the rendered content of the view based on a given condition. + * + * @param bool $condition + * @param string $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return string + */ + public function renderWhen($condition, $view, $data = [], $mergeData = []) + { + if (! $condition) { + return ''; + } + + return $this->make($view, $this->parseData($data), $mergeData)->render(); + } + + /** + * Get the rendered content of the view based on the negation of a given condition. + * + * @param bool $condition + * @param string $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return string + */ + public function renderUnless($condition, $view, $data = [], $mergeData = []) + { + return $this->renderWhen(! $condition, $view, $data, $mergeData); + } + + /** + * Get the rendered contents of a partial from a loop. + * + * @param string $view + * @param array $data + * @param string $iterator + * @param string $empty + * @return string + */ + public function renderEach($view, $data, $iterator, $empty = 'raw|') + { + $result = ''; + + // If is actually data in the array, we will loop through the data and append + // an instance of the partial view to the final result HTML passing in the + // iterated value of this data array, allowing the views to access them. + if (count($data) > 0) { + foreach ($data as $key => $value) { + $result .= $this->make( + $view, ['key' => $key, $iterator => $value] + )->render(); + } + } + + // If there is no data in the array, we will render the contents of the empty + // view. Alternatively, the "empty view" could be a raw string that begins + // with "raw|" for convenience and to let this know that it is a string. + else { + $result = Str::startsWith($empty, 'raw|') + ? substr($empty, 4) + : $this->make($empty)->render(); + } + + return $result; + } + + /** + * Normalize a view name. + * + * @param string $name + * @return string + */ + protected function normalizeName($name) + { + return ViewName::normalize($name); + } + + /** + * Parse the given data into a raw array. + * + * @param mixed $data + * @return array + */ + protected function parseData($data) + { + return $data instanceof Arrayable ? $data->toArray() : $data; + } + + /** + * Create a new view instance from the given arguments. + * + * @param string $view + * @param string $path + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @return \Illuminate\Contracts\View\View + */ + protected function viewInstance($view, $path, $data) + { + return new View($this, $this->getEngineFromPath($path), $view, $path, $data); + } + + /** + * Determine if a given view exists. + * + * @param string $view + * @return bool + */ + public function exists($view) + { + try { + $this->finder->find($view); + } catch (InvalidArgumentException $e) { + return false; + } + + return true; + } + + /** + * Get the appropriate view engine for the given path. + * + * @param string $path + * @return \Illuminate\Contracts\View\Engine + * + * @throws \InvalidArgumentException + */ + public function getEngineFromPath($path) + { + if (! $extension = $this->getExtension($path)) { + throw new InvalidArgumentException("Unrecognized extension in file: {$path}."); + } + + $engine = $this->extensions[$extension]; + + return $this->engines->resolve($engine); + } + + /** + * Get the extension used by the view file. + * + * @param string $path + * @return string|null + */ + protected function getExtension($path) + { + $extensions = array_keys($this->extensions); + + return Arr::first($extensions, function ($value) use ($path) { + return Str::endsWith($path, '.'.$value); + }); + } + + /** + * Add a piece of shared data to the environment. + * + * @param array|string $key + * @param mixed|null $value + * @return mixed + */ + public function share($key, $value = null) + { + $keys = is_array($key) ? $key : [$key => $value]; + + foreach ($keys as $key => $value) { + $this->shared[$key] = $value; + } + + return $value; + } + + /** + * Increment the rendering counter. + * + * @return void + */ + public function incrementRender() + { + $this->renderCount++; + } + + /** + * Decrement the rendering counter. + * + * @return void + */ + public function decrementRender() + { + $this->renderCount--; + } + + /** + * Check if there are no active render operations. + * + * @return bool + */ + public function doneRendering() + { + return $this->renderCount == 0; + } + + /** + * Determine if the given once token has been rendered. + * + * @param string $id + * @return bool + */ + public function hasRenderedOnce(string $id) + { + return isset($this->renderedOnce[$id]); + } + + /** + * Mark the given once token as having been rendered. + * + * @param string $id + * @return void + */ + public function markAsRenderedOnce(string $id) + { + $this->renderedOnce[$id] = true; + } + + /** + * Add a location to the array of view locations. + * + * @param string $location + * @return void + */ + public function addLocation($location) + { + $this->finder->addLocation($location); + } + + /** + * Add a new namespace to the loader. + * + * @param string $namespace + * @param string|array $hints + * @return $this + */ + public function addNamespace($namespace, $hints) + { + $this->finder->addNamespace($namespace, $hints); + + return $this; + } + + /** + * Prepend a new namespace to the loader. + * + * @param string $namespace + * @param string|array $hints + * @return $this + */ + public function prependNamespace($namespace, $hints) + { + $this->finder->prependNamespace($namespace, $hints); + + return $this; + } + + /** + * Replace the namespace hints for the given namespace. + * + * @param string $namespace + * @param string|array $hints + * @return $this + */ + public function replaceNamespace($namespace, $hints) + { + $this->finder->replaceNamespace($namespace, $hints); + + return $this; + } + + /** + * Register a valid view extension and its engine. + * + * @param string $extension + * @param string $engine + * @param \Closure|null $resolver + * @return void + */ + public function addExtension($extension, $engine, $resolver = null) + { + $this->finder->addExtension($extension); + + if (isset($resolver)) { + $this->engines->register($engine, $resolver); + } + + unset($this->extensions[$extension]); + + $this->extensions = array_merge([$extension => $engine], $this->extensions); + } + + /** + * Flush all of the factory state like sections and stacks. + * + * @return void + */ + public function flushState() + { + $this->renderCount = 0; + $this->renderedOnce = []; + + $this->flushSections(); + $this->flushStacks(); + $this->flushComponents(); + } + + /** + * Flush all of the section contents if done rendering. + * + * @return void + */ + public function flushStateIfDoneRendering() + { + if ($this->doneRendering()) { + $this->flushState(); + } + } + + /** + * Get the extension to engine bindings. + * + * @return array + */ + public function getExtensions() + { + return $this->extensions; + } + + /** + * Get the engine resolver instance. + * + * @return \Illuminate\View\Engines\EngineResolver + */ + public function getEngineResolver() + { + return $this->engines; + } + + /** + * Get the view finder instance. + * + * @return \Illuminate\View\ViewFinderInterface + */ + public function getFinder() + { + return $this->finder; + } + + /** + * Set the view finder instance. + * + * @param \Illuminate\View\ViewFinderInterface $finder + * @return void + */ + public function setFinder(ViewFinderInterface $finder) + { + $this->finder = $finder; + } + + /** + * Flush the cache of views located by the finder. + * + * @return void + */ + public function flushFinderCache() + { + $this->getFinder()->flush(); + } + + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + */ + public function getDispatcher() + { + return $this->events; + } + + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + */ + public function setDispatcher(Dispatcher $events) + { + $this->events = $events; + } + + /** + * Get the IoC container instance. + * + * @return \Illuminate\Contracts\Container\Container + */ + public function getContainer() + { + return $this->container; + } + + /** + * Set the IoC container instance. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + */ + public function setContainer(Container $container) + { + $this->container = $container; + } + + /** + * Get an item from the shared data. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function shared($key, $default = null) + { + return Arr::get($this->shared, $key, $default); + } + + /** + * Get all of the shared data for the environment. + * + * @return array + */ + public function getShared() + { + return $this->shared; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/FileViewFinder.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/FileViewFinder.php new file mode 100755 index 0000000..a488a9d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/FileViewFinder.php @@ -0,0 +1,332 @@ +files = $files; + $this->paths = array_map([$this, 'resolvePath'], $paths); + + if (isset($extensions)) { + $this->extensions = $extensions; + } + } + + /** + * Get the fully qualified location of the view. + * + * @param string $name + * @return string + */ + public function find($name) + { + if (isset($this->views[$name])) { + return $this->views[$name]; + } + + if ($this->hasHintInformation($name = trim($name))) { + return $this->views[$name] = $this->findNamespacedView($name); + } + + return $this->views[$name] = $this->findInPaths($name, $this->paths); + } + + /** + * Get the path to a template with a named path. + * + * @param string $name + * @return string + */ + protected function findNamespacedView($name) + { + [$namespace, $view] = $this->parseNamespaceSegments($name); + + return $this->findInPaths($view, $this->hints[$namespace]); + } + + /** + * Get the segments of a template with a named path. + * + * @param string $name + * @return array + * + * @throws \InvalidArgumentException + */ + protected function parseNamespaceSegments($name) + { + $segments = explode(static::HINT_PATH_DELIMITER, $name); + + if (count($segments) !== 2) { + throw new InvalidArgumentException("View [{$name}] has an invalid name."); + } + + if (! isset($this->hints[$segments[0]])) { + throw new InvalidArgumentException("No hint path defined for [{$segments[0]}]."); + } + + return $segments; + } + + /** + * Find the given view in the list of paths. + * + * @param string $name + * @param array $paths + * @return string + * + * @throws \InvalidArgumentException + */ + protected function findInPaths($name, $paths) + { + foreach ((array) $paths as $path) { + foreach ($this->getPossibleViewFiles($name) as $file) { + if ($this->files->exists($viewPath = $path.'/'.$file)) { + return $viewPath; + } + } + } + + throw new InvalidArgumentException("View [{$name}] not found."); + } + + /** + * Get an array of possible view files. + * + * @param string $name + * @return array + */ + protected function getPossibleViewFiles($name) + { + return array_map(function ($extension) use ($name) { + return str_replace('.', '/', $name).'.'.$extension; + }, $this->extensions); + } + + /** + * Add a location to the finder. + * + * @param string $location + * @return void + */ + public function addLocation($location) + { + $this->paths[] = $this->resolvePath($location); + } + + /** + * Prepend a location to the finder. + * + * @param string $location + * @return void + */ + public function prependLocation($location) + { + array_unshift($this->paths, $this->resolvePath($location)); + } + + /** + * Resolve the path. + * + * @param string $path + * @return string + */ + protected function resolvePath($path) + { + return realpath($path) ?: $path; + } + + /** + * Add a namespace hint to the finder. + * + * @param string $namespace + * @param string|array $hints + * @return void + */ + public function addNamespace($namespace, $hints) + { + $hints = (array) $hints; + + if (isset($this->hints[$namespace])) { + $hints = array_merge($this->hints[$namespace], $hints); + } + + $this->hints[$namespace] = $hints; + } + + /** + * Prepend a namespace hint to the finder. + * + * @param string $namespace + * @param string|array $hints + * @return void + */ + public function prependNamespace($namespace, $hints) + { + $hints = (array) $hints; + + if (isset($this->hints[$namespace])) { + $hints = array_merge($hints, $this->hints[$namespace]); + } + + $this->hints[$namespace] = $hints; + } + + /** + * Replace the namespace hints for the given namespace. + * + * @param string $namespace + * @param string|array $hints + * @return void + */ + public function replaceNamespace($namespace, $hints) + { + $this->hints[$namespace] = (array) $hints; + } + + /** + * Register an extension with the view finder. + * + * @param string $extension + * @return void + */ + public function addExtension($extension) + { + if (($index = array_search($extension, $this->extensions)) !== false) { + unset($this->extensions[$index]); + } + + array_unshift($this->extensions, $extension); + } + + /** + * Returns whether or not the view name has any hint information. + * + * @param string $name + * @return bool + */ + public function hasHintInformation($name) + { + return strpos($name, static::HINT_PATH_DELIMITER) > 0; + } + + /** + * Flush the cache of located views. + * + * @return void + */ + public function flush() + { + $this->views = []; + } + + /** + * Get the filesystem instance. + * + * @return \Illuminate\Filesystem\Filesystem + */ + public function getFilesystem() + { + return $this->files; + } + + /** + * Set the active view paths. + * + * @param array $paths + * @return $this + */ + public function setPaths($paths) + { + $this->paths = $paths; + + return $this; + } + + /** + * Get the active view paths. + * + * @return array + */ + public function getPaths() + { + return $this->paths; + } + + /** + * Get the views that have been located. + * + * @return array + */ + public function getViews() + { + return $this->views; + } + + /** + * Get the namespace to file path hints. + * + * @return array + */ + public function getHints() + { + return $this->hints; + } + + /** + * Get registered extensions. + * + * @return array + */ + public function getExtensions() + { + return $this->extensions; + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/InvokableComponentVariable.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/InvokableComponentVariable.php new file mode 100644 index 0000000..b9db657 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/InvokableComponentVariable.php @@ -0,0 +1,96 @@ +callable = $callable; + } + + /** + * Resolve the displayable value that the class is deferring. + * + * @return \Illuminate\Contracts\Support\Htmlable|string + */ + public function resolveDisplayableValue() + { + return $this->__invoke(); + } + + /** + * Get an interator instance for the variable. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + $result = $this->__invoke(); + + return new ArrayIterator($result instanceof Enumerable ? $result->all() : $result); + } + + /** + * Dynamically proxy attribute access to the variable. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->__invoke()->{$key}; + } + + /** + * Dynamically proxy method access to the variable. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + return $this->__invoke()->{$method}(...$parameters); + } + + /** + * Resolve the variable. + * + * @return mixed + */ + public function __invoke() + { + return call_user_func($this->callable); + } + + /** + * Resolve the variable as a string. + * + * @return mixed + */ + public function __toString() + { + return (string) $this->__invoke(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/LICENSE.md b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php new file mode 100644 index 0000000..64015d5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php @@ -0,0 +1,51 @@ +view = $view; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + // If the current session has an "errors" variable bound to it, we will share + // its value with all view instances so the views can easily access errors + // without having to bind. An empty bag is set when there aren't errors. + $this->view->share( + 'errors', $request->session()->get('errors') ?: new ViewErrorBag + ); + + // Putting the errors in the view for every view allows the developer to just + // assume that some errors are always available, which is convenient since + // they don't have to continually run checks for the presence of errors. + + return $next($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/View.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/View.php new file mode 100755 index 0000000..a196935 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/View.php @@ -0,0 +1,442 @@ +view = $view; + $this->path = $path; + $this->engine = $engine; + $this->factory = $factory; + + $this->data = $data instanceof Arrayable ? $data->toArray() : (array) $data; + } + + /** + * Get the string contents of the view. + * + * @param callable|null $callback + * @return string + * + * @throws \Throwable + */ + public function render(callable $callback = null) + { + try { + $contents = $this->renderContents(); + + $response = isset($callback) ? $callback($this, $contents) : null; + + // Once we have the contents of the view, we will flush the sections if we are + // done rendering all views so that there is nothing left hanging over when + // another view gets rendered in the future by the application developer. + $this->factory->flushStateIfDoneRendering(); + + return ! is_null($response) ? $response : $contents; + } catch (Throwable $e) { + $this->factory->flushState(); + + throw $e; + } + } + + /** + * Get the contents of the view instance. + * + * @return string + */ + protected function renderContents() + { + // We will keep track of the amount of views being rendered so we can flush + // the section after the complete rendering operation is done. This will + // clear out the sections for any separate views that may be rendered. + $this->factory->incrementRender(); + + $this->factory->callComposer($this); + + $contents = $this->getContents(); + + // Once we've finished rendering the view, we'll decrement the render count + // so that each sections get flushed out next time a view is created and + // no old sections are staying around in the memory of an environment. + $this->factory->decrementRender(); + + return $contents; + } + + /** + * Get the evaluated contents of the view. + * + * @return string + */ + protected function getContents() + { + return $this->engine->get($this->path, $this->gatherData()); + } + + /** + * Get the data bound to the view instance. + * + * @return array + */ + public function gatherData() + { + $data = array_merge($this->factory->getShared(), $this->data); + + foreach ($data as $key => $value) { + if ($value instanceof Renderable) { + $data[$key] = $value->render(); + } + } + + return $data; + } + + /** + * Get the sections of the rendered view. + * + * @return array + * + * @throws \Throwable + */ + public function renderSections() + { + return $this->render(function () { + return $this->factory->getSections(); + }); + } + + /** + * Add a piece of data to the view. + * + * @param string|array $key + * @param mixed $value + * @return $this + */ + public function with($key, $value = null) + { + if (is_array($key)) { + $this->data = array_merge($this->data, $key); + } else { + $this->data[$key] = $value; + } + + return $this; + } + + /** + * Add a view instance to the view data. + * + * @param string $key + * @param string $view + * @param array $data + * @return $this + */ + public function nest($key, $view, array $data = []) + { + return $this->with($key, $this->factory->make($view, $data)); + } + + /** + * Add validation errors to the view. + * + * @param \Illuminate\Contracts\Support\MessageProvider|array $provider + * @param string $bag + * @return $this + */ + public function withErrors($provider, $bag = 'default') + { + return $this->with('errors', (new ViewErrorBag)->put( + $bag, $this->formatErrors($provider) + )); + } + + /** + * Parse the given errors into an appropriate value. + * + * @param \Illuminate\Contracts\Support\MessageProvider|array|string $provider + * @return \Illuminate\Support\MessageBag + */ + protected function formatErrors($provider) + { + return $provider instanceof MessageProvider + ? $provider->getMessageBag() + : new MessageBag((array) $provider); + } + + /** + * Get the name of the view. + * + * @return string + */ + public function name() + { + return $this->getName(); + } + + /** + * Get the name of the view. + * + * @return string + */ + public function getName() + { + return $this->view; + } + + /** + * Get the array of view data. + * + * @return array + */ + public function getData() + { + return $this->data; + } + + /** + * Get the path to the view file. + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Set the path to the view. + * + * @param string $path + * @return void + */ + public function setPath($path) + { + $this->path = $path; + } + + /** + * Get the view factory instance. + * + * @return \Illuminate\View\Factory + */ + public function getFactory() + { + return $this->factory; + } + + /** + * Get the view's rendering engine. + * + * @return \Illuminate\Contracts\View\Engine + */ + public function getEngine() + { + return $this->engine; + } + + /** + * Determine if a piece of data is bound. + * + * @param string $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return array_key_exists($key, $this->data); + } + + /** + * Get a piece of bound data to the view. + * + * @param string $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->data[$key]; + } + + /** + * Set a piece of data on the view. + * + * @param string $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->with($key, $value); + } + + /** + * Unset a piece of data from the view. + * + * @param string $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + unset($this->data[$key]); + } + + /** + * Get a piece of data from the view. + * + * @param string $key + * @return mixed + */ + public function &__get($key) + { + return $this->data[$key]; + } + + /** + * Set a piece of data on the view. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function __set($key, $value) + { + $this->with($key, $value); + } + + /** + * Check if a piece of data is bound to the view. + * + * @param string $key + * @return bool + */ + public function __isset($key) + { + return isset($this->data[$key]); + } + + /** + * Remove a piece of bound data from the view. + * + * @param string $key + * @return void + */ + public function __unset($key) + { + unset($this->data[$key]); + } + + /** + * Dynamically bind parameters to the view. + * + * @param string $method + * @param array $parameters + * @return \Illuminate\View\View + * + * @throws \BadMethodCallException + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + + if (! Str::startsWith($method, 'with')) { + throw new BadMethodCallException(sprintf( + 'Method %s::%s does not exist.', static::class, $method + )); + } + + return $this->with(Str::camel(substr($method, 4)), $parameters[0]); + } + + /** + * Get content as a string of HTML. + * + * @return string + */ + public function toHtml() + { + return $this->render(); + } + + /** + * Get the string contents of the view. + * + * @return string + * + * @throws \Throwable + */ + public function __toString() + { + return $this->render(); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ViewException.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ViewException.php new file mode 100644 index 0000000..e6797a2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ViewException.php @@ -0,0 +1,41 @@ +getPrevious(); + + if (Reflector::isCallable($reportCallable = [$exception, 'report'])) { + return Container::getInstance()->call($reportCallable); + } + + return false; + } + + /** + * Render the exception into an HTTP response. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\Response + */ + public function render($request) + { + $exception = $this->getPrevious(); + + if ($exception && method_exists($exception, 'render')) { + return $exception->render($request); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ViewFinderInterface.php b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ViewFinderInterface.php new file mode 100755 index 0000000..7b8a849 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/ViewFinderInterface.php @@ -0,0 +1,71 @@ +registerFactory(); + $this->registerViewFinder(); + $this->registerBladeCompiler(); + $this->registerEngineResolver(); + } + + /** + * Register the view environment. + * + * @return void + */ + public function registerFactory() + { + $this->app->singleton('view', function ($app) { + // Next we need to grab the engine resolver instance that will be used by the + // environment. The resolver will be used by an environment to get each of + // the various engine implementations such as plain PHP or Blade engine. + $resolver = $app['view.engine.resolver']; + + $finder = $app['view.finder']; + + $factory = $this->createFactory($resolver, $finder, $app['events']); + + // We will also set the container instance on this view environment since the + // view composers may be classes registered in the container, which allows + // for great testable, flexible composers for the application developer. + $factory->setContainer($app); + + $factory->share('app', $app); + + return $factory; + }); + } + + /** + * Create a new Factory Instance. + * + * @param \Illuminate\View\Engines\EngineResolver $resolver + * @param \Illuminate\View\ViewFinderInterface $finder + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return \Illuminate\View\Factory + */ + protected function createFactory($resolver, $finder, $events) + { + return new Factory($resolver, $finder, $events); + } + + /** + * Register the view finder implementation. + * + * @return void + */ + public function registerViewFinder() + { + $this->app->bind('view.finder', function ($app) { + return new FileViewFinder($app['files'], $app['config']['view.paths']); + }); + } + + /** + * Register the Blade compiler implementation. + * + * @return void + */ + public function registerBladeCompiler() + { + $this->app->singleton('blade.compiler', function ($app) { + return tap(new BladeCompiler($app['files'], $app['config']['view.compiled']), function ($blade) { + $blade->component('dynamic-component', DynamicComponent::class); + }); + }); + } + + /** + * Register the engine resolver instance. + * + * @return void + */ + public function registerEngineResolver() + { + $this->app->singleton('view.engine.resolver', function () { + $resolver = new EngineResolver; + + // Next, we will register the various view engines with the resolver so that the + // environment will resolve the engines needed for various views based on the + // extension of view file. We call a method for each of the view's engines. + foreach (['file', 'php', 'blade'] as $engine) { + $this->{'register'.ucfirst($engine).'Engine'}($resolver); + } + + return $resolver; + }); + } + + /** + * Register the file engine implementation. + * + * @param \Illuminate\View\Engines\EngineResolver $resolver + * @return void + */ + public function registerFileEngine($resolver) + { + $resolver->register('file', function () { + return new FileEngine($this->app['files']); + }); + } + + /** + * Register the PHP engine implementation. + * + * @param \Illuminate\View\Engines\EngineResolver $resolver + * @return void + */ + public function registerPhpEngine($resolver) + { + $resolver->register('php', function () { + return new PhpEngine($this->app['files']); + }); + } + + /** + * Register the Blade engine implementation. + * + * @param \Illuminate\View\Engines\EngineResolver $resolver + * @return void + */ + public function registerBladeEngine($resolver) + { + $resolver->register('blade', function () { + return new CompilerEngine($this->app['blade.compiler'], $this->app['files']); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/composer.json b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/composer.json new file mode 100644 index 0000000..942435b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/framework/src/Illuminate/View/composer.json @@ -0,0 +1,41 @@ +{ + "name": "illuminate/view", + "description": "The Illuminate View package.", + "license": "MIT", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/events": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0" + }, + "autoload": { + "psr-4": { + "Illuminate\\View\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/laravel/laravel/.editorconfig b/php/libraries/composer/vendor/laravel/laravel/.editorconfig new file mode 100644 index 0000000..1671c9b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 + +[docker-compose.yml] +indent_size = 4 diff --git a/php/libraries/composer/vendor/laravel/laravel/.env.example b/php/libraries/composer/vendor/laravel/laravel/.env.example new file mode 100644 index 0000000..b7becba --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/.env.example @@ -0,0 +1,52 @@ +APP_NAME=Laravel +APP_ENV=local +APP_KEY= +APP_DEBUG=true +APP_URL=http://localhost + +LOG_CHANNEL=stack +LOG_DEPRECATIONS_CHANNEL=null +LOG_LEVEL=debug + +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE=laravel +DB_USERNAME=root +DB_PASSWORD= + +BROADCAST_DRIVER=log +CACHE_DRIVER=file +FILESYSTEM_DRIVER=local +QUEUE_CONNECTION=sync +SESSION_DRIVER=file +SESSION_LIFETIME=120 + +MEMCACHED_HOST=127.0.0.1 + +REDIS_HOST=127.0.0.1 +REDIS_PASSWORD=null +REDIS_PORT=6379 + +MAIL_MAILER=smtp +MAIL_HOST=mailhog +MAIL_PORT=1025 +MAIL_USERNAME=null +MAIL_PASSWORD=null +MAIL_ENCRYPTION=null +MAIL_FROM_ADDRESS=null +MAIL_FROM_NAME="${APP_NAME}" + +AWS_ACCESS_KEY_ID= +AWS_SECRET_ACCESS_KEY= +AWS_DEFAULT_REGION=us-east-1 +AWS_BUCKET= +AWS_USE_PATH_STYLE_ENDPOINT=false + +PUSHER_APP_ID= +PUSHER_APP_KEY= +PUSHER_APP_SECRET= +PUSHER_APP_CLUSTER=mt1 + +MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" +MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" diff --git a/php/libraries/composer/vendor/laravel/laravel/.gitattributes b/php/libraries/composer/vendor/laravel/laravel/.gitattributes new file mode 100644 index 0000000..967315d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/.gitattributes @@ -0,0 +1,5 @@ +* text=auto +*.css linguist-vendored +*.scss linguist-vendored +*.js linguist-vendored +CHANGELOG.md export-ignore diff --git a/php/libraries/composer/vendor/laravel/laravel/.gitignore b/php/libraries/composer/vendor/laravel/laravel/.gitignore new file mode 100644 index 0000000..eb003b0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/.gitignore @@ -0,0 +1,15 @@ +/node_modules +/public/hot +/public/storage +/storage/*.key +/vendor +.env +.env.backup +.phpunit.result.cache +docker-compose.override.yml +Homestead.json +Homestead.yaml +npm-debug.log +yarn-error.log +/.idea +/.vscode diff --git a/php/libraries/composer/vendor/laravel/laravel/.styleci.yml b/php/libraries/composer/vendor/laravel/laravel/.styleci.yml new file mode 100644 index 0000000..877ea70 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/.styleci.yml @@ -0,0 +1,14 @@ +php: + preset: laravel + version: 8 + disabled: + - no_unused_imports + finder: + not-name: + - index.php + - server.php +js: + finder: + not-name: + - webpack.mix.js +css: true diff --git a/php/libraries/composer/vendor/laravel/laravel/README.md b/php/libraries/composer/vendor/laravel/laravel/README.md new file mode 100644 index 0000000..8878ec1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/README.md @@ -0,0 +1,66 @@ +

+ +

+Build Status +Total Downloads +Latest Stable Version +License +

+ +## About Laravel + +Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as: + +- [Simple, fast routing engine](https://laravel.com/docs/routing). +- [Powerful dependency injection container](https://laravel.com/docs/container). +- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage. +- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent). +- Database agnostic [schema migrations](https://laravel.com/docs/migrations). +- [Robust background job processing](https://laravel.com/docs/queues). +- [Real-time event broadcasting](https://laravel.com/docs/broadcasting). + +Laravel is accessible, powerful, and provides tools required for large, robust applications. + +## Learning Laravel + +Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. + +If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library. + +## Laravel Sponsors + +We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell). + +### Premium Partners + +- **[Vehikl](https://vehikl.com/)** +- **[Tighten Co.](https://tighten.co)** +- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)** +- **[64 Robots](https://64robots.com)** +- **[Cubet Techno Labs](https://cubettech.com)** +- **[Cyber-Duck](https://cyber-duck.co.uk)** +- **[Many](https://www.many.co.uk)** +- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)** +- **[DevSquad](https://devsquad.com)** +- **[Curotec](https://www.curotec.com/services/technologies/laravel/)** +- **[OP.GG](https://op.gg)** +- **[CMS Max](https://www.cmsmax.com/)** +- **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)** +- **[Lendio](https://lendio.com)** +- **[Romega Software](https://romegasoftware.com)** + +## Contributing + +Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed. + +## License + +The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Console/Kernel.php b/php/libraries/composer/vendor/laravel/laravel/app/Console/Kernel.php new file mode 100644 index 0000000..d8bc1d2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Console/Kernel.php @@ -0,0 +1,32 @@ +command('inspire')->hourly(); + } + + /** + * Register the commands for the application. + * + * @return void + */ + protected function commands() + { + $this->load(__DIR__.'/Commands'); + + require base_path('routes/console.php'); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Exceptions/Handler.php b/php/libraries/composer/vendor/laravel/laravel/app/Exceptions/Handler.php new file mode 100644 index 0000000..8e7fbd1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Exceptions/Handler.php @@ -0,0 +1,41 @@ +> + */ + protected $dontReport = [ + // + ]; + + /** + * A list of the inputs that are never flashed for validation exceptions. + * + * @var array + */ + protected $dontFlash = [ + 'current_password', + 'password', + 'password_confirmation', + ]; + + /** + * Register the exception handling callbacks for the application. + * + * @return void + */ + public function register() + { + $this->reportable(function (Throwable $e) { + // + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Controllers/Controller.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Controllers/Controller.php new file mode 100644 index 0000000..a0a2a8a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Controllers/Controller.php @@ -0,0 +1,13 @@ + + */ + protected $middleware = [ + // \App\Http\Middleware\TrustHosts::class, + \App\Http\Middleware\TrustProxies::class, + \Fruitcake\Cors\HandleCors::class, + \App\Http\Middleware\PreventRequestsDuringMaintenance::class, + \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, + \App\Http\Middleware\TrimStrings::class, + \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, + ]; + + /** + * The application's route middleware groups. + * + * @var array> + */ + protected $middlewareGroups = [ + 'web' => [ + \App\Http\Middleware\EncryptCookies::class, + \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, + \Illuminate\Session\Middleware\StartSession::class, + // \Illuminate\Session\Middleware\AuthenticateSession::class, + \Illuminate\View\Middleware\ShareErrorsFromSession::class, + \App\Http\Middleware\VerifyCsrfToken::class, + \Illuminate\Routing\Middleware\SubstituteBindings::class, + ], + + 'api' => [ + // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, + 'throttle:api', + \Illuminate\Routing\Middleware\SubstituteBindings::class, + ], + ]; + + /** + * The application's route middleware. + * + * These middleware may be assigned to groups or used individually. + * + * @var array + */ + protected $routeMiddleware = [ + 'auth' => \App\Http\Middleware\Authenticate::class, + 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, + 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, + 'can' => \Illuminate\Auth\Middleware\Authorize::class, + 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, + 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, + 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, + 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, + 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, + ]; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/Authenticate.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/Authenticate.php new file mode 100644 index 0000000..704089a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/Authenticate.php @@ -0,0 +1,21 @@ +expectsJson()) { + return route('login'); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/EncryptCookies.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/EncryptCookies.php new file mode 100644 index 0000000..867695b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/EncryptCookies.php @@ -0,0 +1,17 @@ + + */ + protected $except = [ + // + ]; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/PreventRequestsDuringMaintenance.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/PreventRequestsDuringMaintenance.php new file mode 100644 index 0000000..74cbd9a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/PreventRequestsDuringMaintenance.php @@ -0,0 +1,17 @@ + + */ + protected $except = [ + // + ]; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/RedirectIfAuthenticated.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/RedirectIfAuthenticated.php new file mode 100644 index 0000000..a2813a0 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/RedirectIfAuthenticated.php @@ -0,0 +1,32 @@ +check()) { + return redirect(RouteServiceProvider::HOME); + } + } + + return $next($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrimStrings.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrimStrings.php new file mode 100644 index 0000000..88cadca --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrimStrings.php @@ -0,0 +1,19 @@ + + */ + protected $except = [ + 'current_password', + 'password', + 'password_confirmation', + ]; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrustHosts.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrustHosts.php new file mode 100644 index 0000000..7186414 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrustHosts.php @@ -0,0 +1,20 @@ + + */ + public function hosts() + { + return [ + $this->allSubdomainsOfApplicationUrl(), + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrustProxies.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrustProxies.php new file mode 100644 index 0000000..3391630 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/TrustProxies.php @@ -0,0 +1,28 @@ +|string|null + */ + protected $proxies; + + /** + * The headers that should be used to detect proxies. + * + * @var int + */ + protected $headers = + Request::HEADER_X_FORWARDED_FOR | + Request::HEADER_X_FORWARDED_HOST | + Request::HEADER_X_FORWARDED_PORT | + Request::HEADER_X_FORWARDED_PROTO | + Request::HEADER_X_FORWARDED_AWS_ELB; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/VerifyCsrfToken.php b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/VerifyCsrfToken.php new file mode 100644 index 0000000..9e86521 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Http/Middleware/VerifyCsrfToken.php @@ -0,0 +1,17 @@ + + */ + protected $except = [ + // + ]; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Models/User.php b/php/libraries/composer/vendor/laravel/laravel/app/Models/User.php new file mode 100644 index 0000000..8996368 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Models/User.php @@ -0,0 +1,44 @@ + + */ + protected $fillable = [ + 'name', + 'email', + 'password', + ]; + + /** + * The attributes that should be hidden for serialization. + * + * @var array + */ + protected $hidden = [ + 'password', + 'remember_token', + ]; + + /** + * The attributes that should be cast. + * + * @var array + */ + protected $casts = [ + 'email_verified_at' => 'datetime', + ]; +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Providers/AppServiceProvider.php b/php/libraries/composer/vendor/laravel/laravel/app/Providers/AppServiceProvider.php new file mode 100644 index 0000000..ee8ca5b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Providers/AppServiceProvider.php @@ -0,0 +1,28 @@ + + */ + protected $policies = [ + // 'App\Models\Model' => 'App\Policies\ModelPolicy', + ]; + + /** + * Register any authentication / authorization services. + * + * @return void + */ + public function boot() + { + $this->registerPolicies(); + + // + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Providers/BroadcastServiceProvider.php b/php/libraries/composer/vendor/laravel/laravel/app/Providers/BroadcastServiceProvider.php new file mode 100644 index 0000000..395c518 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Providers/BroadcastServiceProvider.php @@ -0,0 +1,21 @@ +> + */ + protected $listen = [ + Registered::class => [ + SendEmailVerificationNotification::class, + ], + ]; + + /** + * Register any events for your application. + * + * @return void + */ + public function boot() + { + // + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/app/Providers/RouteServiceProvider.php b/php/libraries/composer/vendor/laravel/laravel/app/Providers/RouteServiceProvider.php new file mode 100644 index 0000000..3bd3c81 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/app/Providers/RouteServiceProvider.php @@ -0,0 +1,63 @@ +configureRateLimiting(); + + $this->routes(function () { + Route::prefix('api') + ->middleware('api') + ->namespace($this->namespace) + ->group(base_path('routes/api.php')); + + Route::middleware('web') + ->namespace($this->namespace) + ->group(base_path('routes/web.php')); + }); + } + + /** + * Configure the rate limiters for the application. + * + * @return void + */ + protected function configureRateLimiting() + { + RateLimiter::for('api', function (Request $request) { + return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip()); + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/artisan b/php/libraries/composer/vendor/laravel/laravel/artisan new file mode 100755 index 0000000..67a3329 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/artisan @@ -0,0 +1,53 @@ +#!/usr/bin/env php +make(Illuminate\Contracts\Console\Kernel::class); + +$status = $kernel->handle( + $input = new Symfony\Component\Console\Input\ArgvInput, + new Symfony\Component\Console\Output\ConsoleOutput +); + +/* +|-------------------------------------------------------------------------- +| Shutdown The Application +|-------------------------------------------------------------------------- +| +| Once Artisan has finished running, we will fire off the shutdown events +| so that any final work may be done by the application before we shut +| down the process. This is the last thing to happen to the request. +| +*/ + +$kernel->terminate($input, $status); + +exit($status); diff --git a/php/libraries/composer/vendor/laravel/laravel/bootstrap/app.php b/php/libraries/composer/vendor/laravel/laravel/bootstrap/app.php new file mode 100644 index 0000000..037e17d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/bootstrap/app.php @@ -0,0 +1,55 @@ +singleton( + Illuminate\Contracts\Http\Kernel::class, + App\Http\Kernel::class +); + +$app->singleton( + Illuminate\Contracts\Console\Kernel::class, + App\Console\Kernel::class +); + +$app->singleton( + Illuminate\Contracts\Debug\ExceptionHandler::class, + App\Exceptions\Handler::class +); + +/* +|-------------------------------------------------------------------------- +| Return The Application +|-------------------------------------------------------------------------- +| +| This script returns the application instance. The instance is given to +| the calling script so we can separate the building of the instances +| from the actual running of the application and sending responses. +| +*/ + +return $app; diff --git a/php/libraries/composer/vendor/laravel/laravel/bootstrap/cache/.gitignore b/php/libraries/composer/vendor/laravel/laravel/bootstrap/cache/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/bootstrap/cache/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/composer.json b/php/libraries/composer/vendor/laravel/laravel/composer.json new file mode 100644 index 0000000..2b0c115 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/composer.json @@ -0,0 +1,62 @@ +{ + "name": "laravel/laravel", + "type": "project", + "description": "The Laravel Framework.", + "keywords": ["framework", "laravel"], + "license": "MIT", + "require": { + "php": "^7.3|^8.0", + "fruitcake/laravel-cors": "^2.0", + "guzzlehttp/guzzle": "^7.0.1", + "laravel/framework": "^8.75", + "laravel/sanctum": "^2.11", + "laravel/tinker": "^2.5" + }, + "require-dev": { + "facade/ignition": "^2.5", + "fakerphp/faker": "^1.9.1", + "laravel/sail": "^1.0.1", + "mockery/mockery": "^1.4.4", + "nunomaduro/collision": "^5.10", + "phpunit/phpunit": "^9.5.10" + }, + "autoload": { + "psr-4": { + "App\\": "app/", + "Database\\Factories\\": "database/factories/", + "Database\\Seeders\\": "database/seeders/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + } + }, + "scripts": { + "post-autoload-dump": [ + "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", + "@php artisan package:discover --ansi" + ], + "post-update-cmd": [ + "@php artisan vendor:publish --tag=laravel-assets --ansi --force" + ], + "post-root-package-install": [ + "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" + ], + "post-create-project-cmd": [ + "@php artisan key:generate --ansi" + ] + }, + "extra": { + "laravel": { + "dont-discover": [] + } + }, + "config": { + "optimize-autoloader": true, + "preferred-install": "dist", + "sort-packages": true + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/laravel/laravel/config/app.php b/php/libraries/composer/vendor/laravel/laravel/config/app.php new file mode 100644 index 0000000..a8d1a82 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/app.php @@ -0,0 +1,235 @@ + env('APP_NAME', 'Laravel'), + + /* + |-------------------------------------------------------------------------- + | Application Environment + |-------------------------------------------------------------------------- + | + | This value determines the "environment" your application is currently + | running in. This may determine how you prefer to configure various + | services the application utilizes. Set this in your ".env" file. + | + */ + + 'env' => env('APP_ENV', 'production'), + + /* + |-------------------------------------------------------------------------- + | Application Debug Mode + |-------------------------------------------------------------------------- + | + | When your application is in debug mode, detailed error messages with + | stack traces will be shown on every error that occurs within your + | application. If disabled, a simple generic error page is shown. + | + */ + + 'debug' => (bool) env('APP_DEBUG', false), + + /* + |-------------------------------------------------------------------------- + | Application URL + |-------------------------------------------------------------------------- + | + | This URL is used by the console to properly generate URLs when using + | the Artisan command line tool. You should set this to the root of + | your application so that it is used when running Artisan tasks. + | + */ + + 'url' => env('APP_URL', 'http://localhost'), + + 'asset_url' => env('ASSET_URL', null), + + /* + |-------------------------------------------------------------------------- + | Application Timezone + |-------------------------------------------------------------------------- + | + | Here you may specify the default timezone for your application, which + | will be used by the PHP date and date-time functions. We have gone + | ahead and set this to a sensible default for you out of the box. + | + */ + + 'timezone' => 'UTC', + + /* + |-------------------------------------------------------------------------- + | Application Locale Configuration + |-------------------------------------------------------------------------- + | + | The application locale determines the default locale that will be used + | by the translation service provider. You are free to set this value + | to any of the locales which will be supported by the application. + | + */ + + 'locale' => 'en', + + /* + |-------------------------------------------------------------------------- + | Application Fallback Locale + |-------------------------------------------------------------------------- + | + | The fallback locale determines the locale to use when the current one + | is not available. You may change the value to correspond to any of + | the language folders that are provided through your application. + | + */ + + 'fallback_locale' => 'en', + + /* + |-------------------------------------------------------------------------- + | Faker Locale + |-------------------------------------------------------------------------- + | + | This locale will be used by the Faker PHP library when generating fake + | data for your database seeds. For example, this will be used to get + | localized telephone numbers, street address information and more. + | + */ + + 'faker_locale' => 'en_US', + + /* + |-------------------------------------------------------------------------- + | Encryption Key + |-------------------------------------------------------------------------- + | + | This key is used by the Illuminate encrypter service and should be set + | to a random, 32 character string, otherwise these encrypted strings + | will not be safe. Please do this before deploying an application! + | + */ + + 'key' => env('APP_KEY'), + + 'cipher' => 'AES-256-CBC', + + /* + |-------------------------------------------------------------------------- + | Autoloaded Service Providers + |-------------------------------------------------------------------------- + | + | The service providers listed here will be automatically loaded on the + | request to your application. Feel free to add your own services to + | this array to grant expanded functionality to your applications. + | + */ + + 'providers' => [ + + /* + * Laravel Framework Service Providers... + */ + Illuminate\Auth\AuthServiceProvider::class, + Illuminate\Broadcasting\BroadcastServiceProvider::class, + Illuminate\Bus\BusServiceProvider::class, + Illuminate\Cache\CacheServiceProvider::class, + Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, + Illuminate\Cookie\CookieServiceProvider::class, + Illuminate\Database\DatabaseServiceProvider::class, + Illuminate\Encryption\EncryptionServiceProvider::class, + Illuminate\Filesystem\FilesystemServiceProvider::class, + Illuminate\Foundation\Providers\FoundationServiceProvider::class, + Illuminate\Hashing\HashServiceProvider::class, + Illuminate\Mail\MailServiceProvider::class, + Illuminate\Notifications\NotificationServiceProvider::class, + Illuminate\Pagination\PaginationServiceProvider::class, + Illuminate\Pipeline\PipelineServiceProvider::class, + Illuminate\Queue\QueueServiceProvider::class, + Illuminate\Redis\RedisServiceProvider::class, + Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, + Illuminate\Session\SessionServiceProvider::class, + Illuminate\Translation\TranslationServiceProvider::class, + Illuminate\Validation\ValidationServiceProvider::class, + Illuminate\View\ViewServiceProvider::class, + + /* + * Package Service Providers... + */ + + /* + * Application Service Providers... + */ + App\Providers\AppServiceProvider::class, + App\Providers\AuthServiceProvider::class, + // App\Providers\BroadcastServiceProvider::class, + App\Providers\EventServiceProvider::class, + App\Providers\RouteServiceProvider::class, + + ], + + /* + |-------------------------------------------------------------------------- + | Class Aliases + |-------------------------------------------------------------------------- + | + | This array of class aliases will be registered when this application + | is started. However, feel free to register as many as you wish as + | the aliases are "lazy" loaded so they don't hinder performance. + | + */ + + 'aliases' => [ + + 'App' => Illuminate\Support\Facades\App::class, + 'Arr' => Illuminate\Support\Arr::class, + 'Artisan' => Illuminate\Support\Facades\Artisan::class, + 'Auth' => Illuminate\Support\Facades\Auth::class, + 'Blade' => Illuminate\Support\Facades\Blade::class, + 'Broadcast' => Illuminate\Support\Facades\Broadcast::class, + 'Bus' => Illuminate\Support\Facades\Bus::class, + 'Cache' => Illuminate\Support\Facades\Cache::class, + 'Config' => Illuminate\Support\Facades\Config::class, + 'Cookie' => Illuminate\Support\Facades\Cookie::class, + 'Crypt' => Illuminate\Support\Facades\Crypt::class, + 'Date' => Illuminate\Support\Facades\Date::class, + 'DB' => Illuminate\Support\Facades\DB::class, + 'Eloquent' => Illuminate\Database\Eloquent\Model::class, + 'Event' => Illuminate\Support\Facades\Event::class, + 'File' => Illuminate\Support\Facades\File::class, + 'Gate' => Illuminate\Support\Facades\Gate::class, + 'Hash' => Illuminate\Support\Facades\Hash::class, + 'Http' => Illuminate\Support\Facades\Http::class, + 'Js' => Illuminate\Support\Js::class, + 'Lang' => Illuminate\Support\Facades\Lang::class, + 'Log' => Illuminate\Support\Facades\Log::class, + 'Mail' => Illuminate\Support\Facades\Mail::class, + 'Notification' => Illuminate\Support\Facades\Notification::class, + 'Password' => Illuminate\Support\Facades\Password::class, + 'Queue' => Illuminate\Support\Facades\Queue::class, + 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class, + 'Redirect' => Illuminate\Support\Facades\Redirect::class, + // 'Redis' => Illuminate\Support\Facades\Redis::class, + 'Request' => Illuminate\Support\Facades\Request::class, + 'Response' => Illuminate\Support\Facades\Response::class, + 'Route' => Illuminate\Support\Facades\Route::class, + 'Schema' => Illuminate\Support\Facades\Schema::class, + 'Session' => Illuminate\Support\Facades\Session::class, + 'Storage' => Illuminate\Support\Facades\Storage::class, + 'Str' => Illuminate\Support\Str::class, + 'URL' => Illuminate\Support\Facades\URL::class, + 'Validator' => Illuminate\Support\Facades\Validator::class, + 'View' => Illuminate\Support\Facades\View::class, + + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/auth.php b/php/libraries/composer/vendor/laravel/laravel/config/auth.php new file mode 100644 index 0000000..e29a3f7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/auth.php @@ -0,0 +1,111 @@ + [ + 'guard' => 'web', + 'passwords' => 'users', + ], + + /* + |-------------------------------------------------------------------------- + | Authentication Guards + |-------------------------------------------------------------------------- + | + | Next, you may define every authentication guard for your application. + | Of course, a great default configuration has been defined for you + | here which uses session storage and the Eloquent user provider. + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | Supported: "session" + | + */ + + 'guards' => [ + 'web' => [ + 'driver' => 'session', + 'provider' => 'users', + ], + ], + + /* + |-------------------------------------------------------------------------- + | User Providers + |-------------------------------------------------------------------------- + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | If you have multiple user tables or models you may configure multiple + | sources which represent each model / table. These sources may then + | be assigned to any extra authentication guards you have defined. + | + | Supported: "database", "eloquent" + | + */ + + 'providers' => [ + 'users' => [ + 'driver' => 'eloquent', + 'model' => App\Models\User::class, + ], + + // 'users' => [ + // 'driver' => 'database', + // 'table' => 'users', + // ], + ], + + /* + |-------------------------------------------------------------------------- + | Resetting Passwords + |-------------------------------------------------------------------------- + | + | You may specify multiple password reset configurations if you have more + | than one user table or model in the application and you want to have + | separate password reset settings based on the specific user types. + | + | The expire time is the number of minutes that the reset token should be + | considered valid. This security feature keeps tokens short-lived so + | they have less time to be guessed. You may change this as needed. + | + */ + + 'passwords' => [ + 'users' => [ + 'provider' => 'users', + 'table' => 'password_resets', + 'expire' => 60, + 'throttle' => 60, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Password Confirmation Timeout + |-------------------------------------------------------------------------- + | + | Here you may define the amount of seconds before a password confirmation + | times out and the user is prompted to re-enter their password via the + | confirmation screen. By default, the timeout lasts for three hours. + | + */ + + 'password_timeout' => 10800, + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/broadcasting.php b/php/libraries/composer/vendor/laravel/laravel/config/broadcasting.php new file mode 100644 index 0000000..2d52982 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/broadcasting.php @@ -0,0 +1,64 @@ + env('BROADCAST_DRIVER', 'null'), + + /* + |-------------------------------------------------------------------------- + | Broadcast Connections + |-------------------------------------------------------------------------- + | + | Here you may define all of the broadcast connections that will be used + | to broadcast events to other systems or over websockets. Samples of + | each available type of connection are provided inside this array. + | + */ + + 'connections' => [ + + 'pusher' => [ + 'driver' => 'pusher', + 'key' => env('PUSHER_APP_KEY'), + 'secret' => env('PUSHER_APP_SECRET'), + 'app_id' => env('PUSHER_APP_ID'), + 'options' => [ + 'cluster' => env('PUSHER_APP_CLUSTER'), + 'useTLS' => true, + ], + ], + + 'ably' => [ + 'driver' => 'ably', + 'key' => env('ABLY_KEY'), + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'default', + ], + + 'log' => [ + 'driver' => 'log', + ], + + 'null' => [ + 'driver' => 'null', + ], + + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/cache.php b/php/libraries/composer/vendor/laravel/laravel/config/cache.php new file mode 100644 index 0000000..8736c7a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/cache.php @@ -0,0 +1,110 @@ + env('CACHE_DRIVER', 'file'), + + /* + |-------------------------------------------------------------------------- + | Cache Stores + |-------------------------------------------------------------------------- + | + | Here you may define all of the cache "stores" for your application as + | well as their drivers. You may even define multiple stores for the + | same cache driver to group types of items stored in your caches. + | + | Supported drivers: "apc", "array", "database", "file", + | "memcached", "redis", "dynamodb", "octane", "null" + | + */ + + 'stores' => [ + + 'apc' => [ + 'driver' => 'apc', + ], + + 'array' => [ + 'driver' => 'array', + 'serialize' => false, + ], + + 'database' => [ + 'driver' => 'database', + 'table' => 'cache', + 'connection' => null, + 'lock_connection' => null, + ], + + 'file' => [ + 'driver' => 'file', + 'path' => storage_path('framework/cache/data'), + ], + + 'memcached' => [ + 'driver' => 'memcached', + 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), + 'sasl' => [ + env('MEMCACHED_USERNAME'), + env('MEMCACHED_PASSWORD'), + ], + 'options' => [ + // Memcached::OPT_CONNECT_TIMEOUT => 2000, + ], + 'servers' => [ + [ + 'host' => env('MEMCACHED_HOST', '127.0.0.1'), + 'port' => env('MEMCACHED_PORT', 11211), + 'weight' => 100, + ], + ], + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'cache', + 'lock_connection' => 'default', + ], + + 'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), + ], + + 'octane' => [ + 'driver' => 'octane', + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Cache Key Prefix + |-------------------------------------------------------------------------- + | + | When utilizing a RAM based store such as APC or Memcached, there might + | be other applications utilizing the same cache. So, we'll specify a + | value to get prefixed to all our keys so we can avoid collisions. + | + */ + + 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'), + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/cors.php b/php/libraries/composer/vendor/laravel/laravel/config/cors.php new file mode 100644 index 0000000..8a39e6d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/cors.php @@ -0,0 +1,34 @@ + ['api/*', 'sanctum/csrf-cookie'], + + 'allowed_methods' => ['*'], + + 'allowed_origins' => ['*'], + + 'allowed_origins_patterns' => [], + + 'allowed_headers' => ['*'], + + 'exposed_headers' => [], + + 'max_age' => 0, + + 'supports_credentials' => false, + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/database.php b/php/libraries/composer/vendor/laravel/laravel/config/database.php new file mode 100644 index 0000000..b42d9b3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/database.php @@ -0,0 +1,147 @@ + env('DB_CONNECTION', 'mysql'), + + /* + |-------------------------------------------------------------------------- + | Database Connections + |-------------------------------------------------------------------------- + | + | Here are each of the database connections setup for your application. + | Of course, examples of configuring each database platform that is + | supported by Laravel is shown below to make development simple. + | + | + | All database work in Laravel is done through the PHP PDO facilities + | so make sure you have the driver for your particular database of + | choice installed on your machine before you begin development. + | + */ + + 'connections' => [ + + 'sqlite' => [ + 'driver' => 'sqlite', + 'url' => env('DATABASE_URL'), + 'database' => env('DB_DATABASE', database_path('database.sqlite')), + 'prefix' => '', + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), + ], + + 'mysql' => [ + 'driver' => 'mysql', + 'url' => env('DATABASE_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'forge'), + 'username' => env('DB_USERNAME', 'forge'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'pgsql' => [ + 'driver' => 'pgsql', + 'url' => env('DATABASE_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '5432'), + 'database' => env('DB_DATABASE', 'forge'), + 'username' => env('DB_USERNAME', 'forge'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => 'utf8', + 'prefix' => '', + 'prefix_indexes' => true, + 'schema' => 'public', + 'sslmode' => 'prefer', + ], + + 'sqlsrv' => [ + 'driver' => 'sqlsrv', + 'url' => env('DATABASE_URL'), + 'host' => env('DB_HOST', 'localhost'), + 'port' => env('DB_PORT', '1433'), + 'database' => env('DB_DATABASE', 'forge'), + 'username' => env('DB_USERNAME', 'forge'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => 'utf8', + 'prefix' => '', + 'prefix_indexes' => true, + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Migration Repository Table + |-------------------------------------------------------------------------- + | + | This table keeps track of all the migrations that have already run for + | your application. Using this information, we can determine which of + | the migrations on disk haven't actually been run in the database. + | + */ + + 'migrations' => 'migrations', + + /* + |-------------------------------------------------------------------------- + | Redis Databases + |-------------------------------------------------------------------------- + | + | Redis is an open source, fast, and advanced key-value store that also + | provides a richer body of commands than a typical key-value system + | such as APC or Memcached. Laravel makes it easy to dig right in. + | + */ + + 'redis' => [ + + 'client' => env('REDIS_CLIENT', 'phpredis'), + + 'options' => [ + 'cluster' => env('REDIS_CLUSTER', 'redis'), + 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), + ], + + 'default' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'password' => env('REDIS_PASSWORD', null), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_DB', '0'), + ], + + 'cache' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'password' => env('REDIS_PASSWORD', null), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_CACHE_DB', '1'), + ], + + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/filesystems.php b/php/libraries/composer/vendor/laravel/laravel/config/filesystems.php new file mode 100644 index 0000000..760ef97 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/filesystems.php @@ -0,0 +1,73 @@ + env('FILESYSTEM_DRIVER', 'local'), + + /* + |-------------------------------------------------------------------------- + | Filesystem Disks + |-------------------------------------------------------------------------- + | + | Here you may configure as many filesystem "disks" as you wish, and you + | may even configure multiple disks of the same driver. Defaults have + | been setup for each driver as an example of the required options. + | + | Supported Drivers: "local", "ftp", "sftp", "s3" + | + */ + + 'disks' => [ + + 'local' => [ + 'driver' => 'local', + 'root' => storage_path('app'), + ], + + 'public' => [ + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => env('APP_URL').'/storage', + 'visibility' => 'public', + ], + + 's3' => [ + 'driver' => 's3', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION'), + 'bucket' => env('AWS_BUCKET'), + 'url' => env('AWS_URL'), + 'endpoint' => env('AWS_ENDPOINT'), + 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Symbolic Links + |-------------------------------------------------------------------------- + | + | Here you may configure the symbolic links that will be created when the + | `storage:link` Artisan command is executed. The array keys should be + | the locations of the links and the values should be their targets. + | + */ + + 'links' => [ + public_path('storage') => storage_path('app/public'), + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/hashing.php b/php/libraries/composer/vendor/laravel/laravel/config/hashing.php new file mode 100644 index 0000000..8425770 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/hashing.php @@ -0,0 +1,52 @@ + 'bcrypt', + + /* + |-------------------------------------------------------------------------- + | Bcrypt Options + |-------------------------------------------------------------------------- + | + | Here you may specify the configuration options that should be used when + | passwords are hashed using the Bcrypt algorithm. This will allow you + | to control the amount of time it takes to hash the given password. + | + */ + + 'bcrypt' => [ + 'rounds' => env('BCRYPT_ROUNDS', 10), + ], + + /* + |-------------------------------------------------------------------------- + | Argon Options + |-------------------------------------------------------------------------- + | + | Here you may specify the configuration options that should be used when + | passwords are hashed using the Argon algorithm. These will allow you + | to control the amount of time it takes to hash the given password. + | + */ + + 'argon' => [ + 'memory' => 1024, + 'threads' => 2, + 'time' => 2, + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/logging.php b/php/libraries/composer/vendor/laravel/laravel/config/logging.php new file mode 100644 index 0000000..880cd92 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/logging.php @@ -0,0 +1,118 @@ + env('LOG_CHANNEL', 'stack'), + + /* + |-------------------------------------------------------------------------- + | Deprecations Log Channel + |-------------------------------------------------------------------------- + | + | This option controls the log channel that should be used to log warnings + | regarding deprecated PHP and library features. This allows you to get + | your application ready for upcoming major versions of dependencies. + | + */ + + 'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), + + /* + |-------------------------------------------------------------------------- + | Log Channels + |-------------------------------------------------------------------------- + | + | Here you may configure the log channels for your application. Out of + | the box, Laravel uses the Monolog PHP logging library. This gives + | you a variety of powerful log handlers / formatters to utilize. + | + | Available Drivers: "single", "daily", "slack", "syslog", + | "errorlog", "monolog", + | "custom", "stack" + | + */ + + 'channels' => [ + 'stack' => [ + 'driver' => 'stack', + 'channels' => ['single'], + 'ignore_exceptions' => false, + ], + + 'single' => [ + 'driver' => 'single', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + ], + + 'daily' => [ + 'driver' => 'daily', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'days' => 14, + ], + + 'slack' => [ + 'driver' => 'slack', + 'url' => env('LOG_SLACK_WEBHOOK_URL'), + 'username' => 'Laravel Log', + 'emoji' => ':boom:', + 'level' => env('LOG_LEVEL', 'critical'), + ], + + 'papertrail' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => SyslogUdpHandler::class, + 'handler_with' => [ + 'host' => env('PAPERTRAIL_URL'), + 'port' => env('PAPERTRAIL_PORT'), + ], + ], + + 'stderr' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => StreamHandler::class, + 'formatter' => env('LOG_STDERR_FORMATTER'), + 'with' => [ + 'stream' => 'php://stderr', + ], + ], + + 'syslog' => [ + 'driver' => 'syslog', + 'level' => env('LOG_LEVEL', 'debug'), + ], + + 'errorlog' => [ + 'driver' => 'errorlog', + 'level' => env('LOG_LEVEL', 'debug'), + ], + + 'null' => [ + 'driver' => 'monolog', + 'handler' => NullHandler::class, + ], + + 'emergency' => [ + 'path' => storage_path('logs/laravel.log'), + ], + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/mail.php b/php/libraries/composer/vendor/laravel/laravel/config/mail.php new file mode 100644 index 0000000..f96c6c7 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/mail.php @@ -0,0 +1,118 @@ + env('MAIL_MAILER', 'smtp'), + + /* + |-------------------------------------------------------------------------- + | Mailer Configurations + |-------------------------------------------------------------------------- + | + | Here you may configure all of the mailers used by your application plus + | their respective settings. Several examples have been configured for + | you and you are free to add your own as your application requires. + | + | Laravel supports a variety of mail "transport" drivers to be used while + | sending an e-mail. You will specify which one you are using for your + | mailers below. You are free to add additional mailers as required. + | + | Supported: "smtp", "sendmail", "mailgun", "ses", + | "postmark", "log", "array", "failover" + | + */ + + 'mailers' => [ + 'smtp' => [ + 'transport' => 'smtp', + 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), + 'port' => env('MAIL_PORT', 587), + 'encryption' => env('MAIL_ENCRYPTION', 'tls'), + 'username' => env('MAIL_USERNAME'), + 'password' => env('MAIL_PASSWORD'), + 'timeout' => null, + 'auth_mode' => null, + ], + + 'ses' => [ + 'transport' => 'ses', + ], + + 'mailgun' => [ + 'transport' => 'mailgun', + ], + + 'postmark' => [ + 'transport' => 'postmark', + ], + + 'sendmail' => [ + 'transport' => 'sendmail', + 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -t -i'), + ], + + 'log' => [ + 'transport' => 'log', + 'channel' => env('MAIL_LOG_CHANNEL'), + ], + + 'array' => [ + 'transport' => 'array', + ], + + 'failover' => [ + 'transport' => 'failover', + 'mailers' => [ + 'smtp', + 'log', + ], + ], + ], + + /* + |-------------------------------------------------------------------------- + | Global "From" Address + |-------------------------------------------------------------------------- + | + | You may wish for all e-mails sent by your application to be sent from + | the same address. Here, you may specify a name and address that is + | used globally for all e-mails that are sent by your application. + | + */ + + 'from' => [ + 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), + 'name' => env('MAIL_FROM_NAME', 'Example'), + ], + + /* + |-------------------------------------------------------------------------- + | Markdown Mail Settings + |-------------------------------------------------------------------------- + | + | If you are using Markdown based email rendering, you may configure your + | theme and component paths here, allowing you to customize the design + | of the emails. Or, you may simply stick with the Laravel defaults! + | + */ + + 'markdown' => [ + 'theme' => 'default', + + 'paths' => [ + resource_path('views/vendor/mail'), + ], + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/queue.php b/php/libraries/composer/vendor/laravel/laravel/config/queue.php new file mode 100644 index 0000000..25ea5a8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/queue.php @@ -0,0 +1,93 @@ + env('QUEUE_CONNECTION', 'sync'), + + /* + |-------------------------------------------------------------------------- + | Queue Connections + |-------------------------------------------------------------------------- + | + | Here you may configure the connection information for each server that + | is used by your application. A default configuration has been added + | for each back-end shipped with Laravel. You are free to add more. + | + | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" + | + */ + + 'connections' => [ + + 'sync' => [ + 'driver' => 'sync', + ], + + 'database' => [ + 'driver' => 'database', + 'table' => 'jobs', + 'queue' => 'default', + 'retry_after' => 90, + 'after_commit' => false, + ], + + 'beanstalkd' => [ + 'driver' => 'beanstalkd', + 'host' => 'localhost', + 'queue' => 'default', + 'retry_after' => 90, + 'block_for' => 0, + 'after_commit' => false, + ], + + 'sqs' => [ + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'after_commit' => false, + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'default', + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => 90, + 'block_for' => null, + 'after_commit' => false, + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Failed Queue Jobs + |-------------------------------------------------------------------------- + | + | These options configure the behavior of failed queue job logging so you + | can control which database and table are used to store the jobs that + | have failed. You may change them to any database / table you wish. + | + */ + + 'failed' => [ + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'database' => env('DB_CONNECTION', 'mysql'), + 'table' => 'failed_jobs', + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/sanctum.php b/php/libraries/composer/vendor/laravel/laravel/config/sanctum.php new file mode 100644 index 0000000..9281c92 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/sanctum.php @@ -0,0 +1,65 @@ + explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( + '%s%s', + 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', + env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : '' + ))), + + /* + |-------------------------------------------------------------------------- + | Sanctum Guards + |-------------------------------------------------------------------------- + | + | This array contains the authentication guards that will be checked when + | Sanctum is trying to authenticate a request. If none of these guards + | are able to authenticate the request, Sanctum will use the bearer + | token that's present on an incoming request for authentication. + | + */ + + 'guard' => ['web'], + + /* + |-------------------------------------------------------------------------- + | Expiration Minutes + |-------------------------------------------------------------------------- + | + | This value controls the number of minutes until an issued token will be + | considered expired. If this value is null, personal access tokens do + | not expire. This won't tweak the lifetime of first-party sessions. + | + */ + + 'expiration' => null, + + /* + |-------------------------------------------------------------------------- + | Sanctum Middleware + |-------------------------------------------------------------------------- + | + | When authenticating your first-party SPA with Sanctum you may need to + | customize some of the middleware Sanctum uses while processing the + | request. You may change the middleware listed below as required. + | + */ + + 'middleware' => [ + 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class, + 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class, + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/services.php b/php/libraries/composer/vendor/laravel/laravel/config/services.php new file mode 100644 index 0000000..2a1d616 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/services.php @@ -0,0 +1,33 @@ + [ + 'domain' => env('MAILGUN_DOMAIN'), + 'secret' => env('MAILGUN_SECRET'), + 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), + ], + + 'postmark' => [ + 'token' => env('POSTMARK_TOKEN'), + ], + + 'ses' => [ + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/session.php b/php/libraries/composer/vendor/laravel/laravel/config/session.php new file mode 100644 index 0000000..ac0802b --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/session.php @@ -0,0 +1,201 @@ + env('SESSION_DRIVER', 'file'), + + /* + |-------------------------------------------------------------------------- + | Session Lifetime + |-------------------------------------------------------------------------- + | + | Here you may specify the number of minutes that you wish the session + | to be allowed to remain idle before it expires. If you want them + | to immediately expire on the browser closing, set that option. + | + */ + + 'lifetime' => env('SESSION_LIFETIME', 120), + + 'expire_on_close' => false, + + /* + |-------------------------------------------------------------------------- + | Session Encryption + |-------------------------------------------------------------------------- + | + | This option allows you to easily specify that all of your session data + | should be encrypted before it is stored. All encryption will be run + | automatically by Laravel and you can use the Session like normal. + | + */ + + 'encrypt' => false, + + /* + |-------------------------------------------------------------------------- + | Session File Location + |-------------------------------------------------------------------------- + | + | When using the native session driver, we need a location where session + | files may be stored. A default has been set for you but a different + | location may be specified. This is only needed for file sessions. + | + */ + + 'files' => storage_path('framework/sessions'), + + /* + |-------------------------------------------------------------------------- + | Session Database Connection + |-------------------------------------------------------------------------- + | + | When using the "database" or "redis" session drivers, you may specify a + | connection that should be used to manage these sessions. This should + | correspond to a connection in your database configuration options. + | + */ + + 'connection' => env('SESSION_CONNECTION', null), + + /* + |-------------------------------------------------------------------------- + | Session Database Table + |-------------------------------------------------------------------------- + | + | When using the "database" session driver, you may specify the table we + | should use to manage the sessions. Of course, a sensible default is + | provided for you; however, you are free to change this as needed. + | + */ + + 'table' => 'sessions', + + /* + |-------------------------------------------------------------------------- + | Session Cache Store + |-------------------------------------------------------------------------- + | + | While using one of the framework's cache driven session backends you may + | list a cache store that should be used for these sessions. This value + | must match with one of the application's configured cache "stores". + | + | Affects: "apc", "dynamodb", "memcached", "redis" + | + */ + + 'store' => env('SESSION_STORE', null), + + /* + |-------------------------------------------------------------------------- + | Session Sweeping Lottery + |-------------------------------------------------------------------------- + | + | Some session drivers must manually sweep their storage location to get + | rid of old sessions from storage. Here are the chances that it will + | happen on a given request. By default, the odds are 2 out of 100. + | + */ + + 'lottery' => [2, 100], + + /* + |-------------------------------------------------------------------------- + | Session Cookie Name + |-------------------------------------------------------------------------- + | + | Here you may change the name of the cookie used to identify a session + | instance by ID. The name specified here will get used every time a + | new session cookie is created by the framework for every driver. + | + */ + + 'cookie' => env( + 'SESSION_COOKIE', + Str::slug(env('APP_NAME', 'laravel'), '_').'_session' + ), + + /* + |-------------------------------------------------------------------------- + | Session Cookie Path + |-------------------------------------------------------------------------- + | + | The session cookie path determines the path for which the cookie will + | be regarded as available. Typically, this will be the root path of + | your application but you are free to change this when necessary. + | + */ + + 'path' => '/', + + /* + |-------------------------------------------------------------------------- + | Session Cookie Domain + |-------------------------------------------------------------------------- + | + | Here you may change the domain of the cookie used to identify a session + | in your application. This will determine which domains the cookie is + | available to in your application. A sensible default has been set. + | + */ + + 'domain' => env('SESSION_DOMAIN', null), + + /* + |-------------------------------------------------------------------------- + | HTTPS Only Cookies + |-------------------------------------------------------------------------- + | + | By setting this option to true, session cookies will only be sent back + | to the server if the browser has a HTTPS connection. This will keep + | the cookie from being sent to you when it can't be done securely. + | + */ + + 'secure' => env('SESSION_SECURE_COOKIE'), + + /* + |-------------------------------------------------------------------------- + | HTTP Access Only + |-------------------------------------------------------------------------- + | + | Setting this value to true will prevent JavaScript from accessing the + | value of the cookie and the cookie will only be accessible through + | the HTTP protocol. You are free to modify this option if needed. + | + */ + + 'http_only' => true, + + /* + |-------------------------------------------------------------------------- + | Same-Site Cookies + |-------------------------------------------------------------------------- + | + | This option determines how your cookies behave when cross-site requests + | take place, and can be used to mitigate CSRF attacks. By default, we + | will set this value to "lax" since this is a secure default value. + | + | Supported: "lax", "strict", "none", null + | + */ + + 'same_site' => 'lax', + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/config/view.php b/php/libraries/composer/vendor/laravel/laravel/config/view.php new file mode 100644 index 0000000..22b8a18 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/config/view.php @@ -0,0 +1,36 @@ + [ + resource_path('views'), + ], + + /* + |-------------------------------------------------------------------------- + | Compiled View Path + |-------------------------------------------------------------------------- + | + | This option determines where all the compiled Blade templates will be + | stored for your application. Typically, this is within the storage + | directory. However, as usual, you are free to change this value. + | + */ + + 'compiled' => env( + 'VIEW_COMPILED_PATH', + realpath(storage_path('framework/views')) + ), + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/database/.gitignore b/php/libraries/composer/vendor/laravel/laravel/database/.gitignore new file mode 100644 index 0000000..9b19b93 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/.gitignore @@ -0,0 +1 @@ +*.sqlite* diff --git a/php/libraries/composer/vendor/laravel/laravel/database/factories/UserFactory.php b/php/libraries/composer/vendor/laravel/laravel/database/factories/UserFactory.php new file mode 100644 index 0000000..a3eb239 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/factories/UserFactory.php @@ -0,0 +1,39 @@ + $this->faker->name(), + 'email' => $this->faker->unique()->safeEmail(), + 'email_verified_at' => now(), + 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password + 'remember_token' => Str::random(10), + ]; + } + + /** + * Indicate that the model's email address should be unverified. + * + * @return \Illuminate\Database\Eloquent\Factories\Factory + */ + public function unverified() + { + return $this->state(function (array $attributes) { + return [ + 'email_verified_at' => null, + ]; + }); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/database/migrations/2014_10_12_000000_create_users_table.php b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2014_10_12_000000_create_users_table.php new file mode 100644 index 0000000..621a24e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2014_10_12_000000_create_users_table.php @@ -0,0 +1,36 @@ +id(); + $table->string('name'); + $table->string('email')->unique(); + $table->timestamp('email_verified_at')->nullable(); + $table->string('password'); + $table->rememberToken(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('users'); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/database/migrations/2014_10_12_100000_create_password_resets_table.php b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2014_10_12_100000_create_password_resets_table.php new file mode 100644 index 0000000..0ee0a36 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2014_10_12_100000_create_password_resets_table.php @@ -0,0 +1,32 @@ +string('email')->index(); + $table->string('token'); + $table->timestamp('created_at')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('password_resets'); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/database/migrations/2019_08_19_000000_create_failed_jobs_table.php b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2019_08_19_000000_create_failed_jobs_table.php new file mode 100644 index 0000000..6aa6d74 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2019_08_19_000000_create_failed_jobs_table.php @@ -0,0 +1,36 @@ +id(); + $table->string('uuid')->unique(); + $table->text('connection'); + $table->text('queue'); + $table->longText('payload'); + $table->longText('exception'); + $table->timestamp('failed_at')->useCurrent(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('failed_jobs'); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php new file mode 100644 index 0000000..4315e16 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php @@ -0,0 +1,36 @@ +id(); + $table->morphs('tokenable'); + $table->string('name'); + $table->string('token', 64)->unique(); + $table->text('abilities')->nullable(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('personal_access_tokens'); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/database/seeders/DatabaseSeeder.php b/php/libraries/composer/vendor/laravel/laravel/database/seeders/DatabaseSeeder.php new file mode 100644 index 0000000..57b73b5 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/database/seeders/DatabaseSeeder.php @@ -0,0 +1,18 @@ +create(); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/package.json b/php/libraries/composer/vendor/laravel/laravel/package.json new file mode 100644 index 0000000..00c6506 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/package.json @@ -0,0 +1,18 @@ +{ + "private": true, + "scripts": { + "dev": "npm run development", + "development": "mix", + "watch": "mix watch", + "watch-poll": "mix watch -- --watch-options-poll=1000", + "hot": "mix watch --hot", + "prod": "npm run production", + "production": "mix --production" + }, + "devDependencies": { + "axios": "^0.21", + "laravel-mix": "^6.0.6", + "lodash": "^4.17.19", + "postcss": "^8.1.14" + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/phpunit.xml b/php/libraries/composer/vendor/laravel/laravel/phpunit.xml new file mode 100644 index 0000000..4ae4d97 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/phpunit.xml @@ -0,0 +1,31 @@ + + + + + ./tests/Unit + + + ./tests/Feature + + + + + ./app + + + + + + + + + + + + + + diff --git a/php/libraries/composer/vendor/laravel/laravel/public/.htaccess b/php/libraries/composer/vendor/laravel/laravel/public/.htaccess new file mode 100644 index 0000000..3aec5e2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/public/.htaccess @@ -0,0 +1,21 @@ + + + Options -MultiViews -Indexes + + + RewriteEngine On + + # Handle Authorization Header + RewriteCond %{HTTP:Authorization} . + RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] + + # Redirect Trailing Slashes If Not A Folder... + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_URI} (.+)/$ + RewriteRule ^ %1 [L,R=301] + + # Send Requests To Front Controller... + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^ index.php [L] + diff --git a/php/libraries/composer/vendor/laravel/laravel/public/favicon.ico b/php/libraries/composer/vendor/laravel/laravel/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/php/libraries/composer/vendor/laravel/laravel/public/index.php b/php/libraries/composer/vendor/laravel/laravel/public/index.php new file mode 100644 index 0000000..1d69f3a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/public/index.php @@ -0,0 +1,55 @@ +make(Kernel::class); + +$response = $kernel->handle( + $request = Request::capture() +)->send(); + +$kernel->terminate($request, $response); diff --git a/php/libraries/composer/vendor/laravel/laravel/public/robots.txt b/php/libraries/composer/vendor/laravel/laravel/public/robots.txt new file mode 100644 index 0000000..eb05362 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/css/app.css b/php/libraries/composer/vendor/laravel/laravel/resources/css/app.css new file mode 100644 index 0000000..e69de29 diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/js/app.js b/php/libraries/composer/vendor/laravel/laravel/resources/js/app.js new file mode 100644 index 0000000..40c55f6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/js/app.js @@ -0,0 +1 @@ +require('./bootstrap'); diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/js/bootstrap.js b/php/libraries/composer/vendor/laravel/laravel/resources/js/bootstrap.js new file mode 100644 index 0000000..6922577 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/js/bootstrap.js @@ -0,0 +1,28 @@ +window._ = require('lodash'); + +/** + * We'll load the axios HTTP library which allows us to easily issue requests + * to our Laravel back-end. This library automatically handles sending the + * CSRF token as a header based on the value of the "XSRF" token cookie. + */ + +window.axios = require('axios'); + +window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; + +/** + * Echo exposes an expressive API for subscribing to channels and listening + * for events that are broadcast by Laravel. Echo and event broadcasting + * allows your team to easily build robust real-time web applications. + */ + +// import Echo from 'laravel-echo'; + +// window.Pusher = require('pusher-js'); + +// window.Echo = new Echo({ +// broadcaster: 'pusher', +// key: process.env.MIX_PUSHER_APP_KEY, +// cluster: process.env.MIX_PUSHER_APP_CLUSTER, +// forceTLS: true +// }); diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/auth.php b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/auth.php new file mode 100644 index 0000000..6598e2c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/auth.php @@ -0,0 +1,20 @@ + 'These credentials do not match our records.', + 'password' => 'The provided password is incorrect.', + 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/pagination.php b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/pagination.php new file mode 100644 index 0000000..d481411 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/pagination.php @@ -0,0 +1,19 @@ + '« Previous', + 'next' => 'Next »', + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/passwords.php b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/passwords.php new file mode 100644 index 0000000..2345a56 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/passwords.php @@ -0,0 +1,22 @@ + 'Your password has been reset!', + 'sent' => 'We have emailed your password reset link!', + 'throttled' => 'Please wait before retrying.', + 'token' => 'This password reset token is invalid.', + 'user' => "We can't find a user with that email address.", + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/validation.php b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/validation.php new file mode 100644 index 0000000..87fb437 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/lang/en/validation.php @@ -0,0 +1,162 @@ + 'The :attribute must be accepted.', + 'accepted_if' => 'The :attribute must be accepted when :other is :value.', + 'active_url' => 'The :attribute is not a valid URL.', + 'after' => 'The :attribute must be a date after :date.', + 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', + 'alpha' => 'The :attribute must only contain letters.', + 'alpha_dash' => 'The :attribute must only contain letters, numbers, dashes and underscores.', + 'alpha_num' => 'The :attribute must only contain letters and numbers.', + 'array' => 'The :attribute must be an array.', + 'before' => 'The :attribute must be a date before :date.', + 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', + 'between' => [ + 'numeric' => 'The :attribute must be between :min and :max.', + 'file' => 'The :attribute must be between :min and :max kilobytes.', + 'string' => 'The :attribute must be between :min and :max characters.', + 'array' => 'The :attribute must have between :min and :max items.', + ], + 'boolean' => 'The :attribute field must be true or false.', + 'confirmed' => 'The :attribute confirmation does not match.', + 'current_password' => 'The password is incorrect.', + 'date' => 'The :attribute is not a valid date.', + 'date_equals' => 'The :attribute must be a date equal to :date.', + 'date_format' => 'The :attribute does not match the format :format.', + 'declined' => 'The :attribute must be declined.', + 'declined_if' => 'The :attribute must be declined when :other is :value.', + 'different' => 'The :attribute and :other must be different.', + 'digits' => 'The :attribute must be :digits digits.', + 'digits_between' => 'The :attribute must be between :min and :max digits.', + 'dimensions' => 'The :attribute has invalid image dimensions.', + 'distinct' => 'The :attribute field has a duplicate value.', + 'email' => 'The :attribute must be a valid email address.', + 'ends_with' => 'The :attribute must end with one of the following: :values.', + 'enum' => 'The selected :attribute is invalid.', + 'exists' => 'The selected :attribute is invalid.', + 'file' => 'The :attribute must be a file.', + 'filled' => 'The :attribute field must have a value.', + 'gt' => [ + 'numeric' => 'The :attribute must be greater than :value.', + 'file' => 'The :attribute must be greater than :value kilobytes.', + 'string' => 'The :attribute must be greater than :value characters.', + 'array' => 'The :attribute must have more than :value items.', + ], + 'gte' => [ + 'numeric' => 'The :attribute must be greater than or equal to :value.', + 'file' => 'The :attribute must be greater than or equal to :value kilobytes.', + 'string' => 'The :attribute must be greater than or equal to :value characters.', + 'array' => 'The :attribute must have :value items or more.', + ], + 'image' => 'The :attribute must be an image.', + 'in' => 'The selected :attribute is invalid.', + 'in_array' => 'The :attribute field does not exist in :other.', + 'integer' => 'The :attribute must be an integer.', + 'ip' => 'The :attribute must be a valid IP address.', + 'ipv4' => 'The :attribute must be a valid IPv4 address.', + 'ipv6' => 'The :attribute must be a valid IPv6 address.', + 'mac_address' => 'The :attribute must be a valid MAC address.', + 'json' => 'The :attribute must be a valid JSON string.', + 'lt' => [ + 'numeric' => 'The :attribute must be less than :value.', + 'file' => 'The :attribute must be less than :value kilobytes.', + 'string' => 'The :attribute must be less than :value characters.', + 'array' => 'The :attribute must have less than :value items.', + ], + 'lte' => [ + 'numeric' => 'The :attribute must be less than or equal to :value.', + 'file' => 'The :attribute must be less than or equal to :value kilobytes.', + 'string' => 'The :attribute must be less than or equal to :value characters.', + 'array' => 'The :attribute must not have more than :value items.', + ], + 'max' => [ + 'numeric' => 'The :attribute must not be greater than :max.', + 'file' => 'The :attribute must not be greater than :max kilobytes.', + 'string' => 'The :attribute must not be greater than :max characters.', + 'array' => 'The :attribute must not have more than :max items.', + ], + 'mimes' => 'The :attribute must be a file of type: :values.', + 'mimetypes' => 'The :attribute must be a file of type: :values.', + 'min' => [ + 'numeric' => 'The :attribute must be at least :min.', + 'file' => 'The :attribute must be at least :min kilobytes.', + 'string' => 'The :attribute must be at least :min characters.', + 'array' => 'The :attribute must have at least :min items.', + ], + 'multiple_of' => 'The :attribute must be a multiple of :value.', + 'not_in' => 'The selected :attribute is invalid.', + 'not_regex' => 'The :attribute format is invalid.', + 'numeric' => 'The :attribute must be a number.', + 'password' => 'The password is incorrect.', + 'present' => 'The :attribute field must be present.', + 'prohibited' => 'The :attribute field is prohibited.', + 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.', + 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.', + 'prohibits' => 'The :attribute field prohibits :other from being present.', + 'regex' => 'The :attribute format is invalid.', + 'required' => 'The :attribute field is required.', + 'required_if' => 'The :attribute field is required when :other is :value.', + 'required_unless' => 'The :attribute field is required unless :other is in :values.', + 'required_with' => 'The :attribute field is required when :values is present.', + 'required_with_all' => 'The :attribute field is required when :values are present.', + 'required_without' => 'The :attribute field is required when :values is not present.', + 'required_without_all' => 'The :attribute field is required when none of :values are present.', + 'same' => 'The :attribute and :other must match.', + 'size' => [ + 'numeric' => 'The :attribute must be :size.', + 'file' => 'The :attribute must be :size kilobytes.', + 'string' => 'The :attribute must be :size characters.', + 'array' => 'The :attribute must contain :size items.', + ], + 'starts_with' => 'The :attribute must start with one of the following: :values.', + 'string' => 'The :attribute must be a string.', + 'timezone' => 'The :attribute must be a valid timezone.', + 'unique' => 'The :attribute has already been taken.', + 'uploaded' => 'The :attribute failed to upload.', + 'url' => 'The :attribute must be a valid URL.', + 'uuid' => 'The :attribute must be a valid UUID.', + + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap our attribute placeholder + | with something more reader friendly such as "E-Mail Address" instead + | of "email". This simply helps us make our message more expressive. + | + */ + + 'attributes' => [], + +]; diff --git a/php/libraries/composer/vendor/laravel/laravel/resources/views/welcome.blade.php b/php/libraries/composer/vendor/laravel/laravel/resources/views/welcome.blade.php new file mode 100644 index 0000000..dd6a45d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/resources/views/welcome.blade.php @@ -0,0 +1,132 @@ + + + + + + + Laravel + + + + + + + + + + +
+ @if (Route::has('login')) + + @endif + +
+
+ + + + + +
+ +
+
+
+ + +
+
+ Laravel has wonderful, thorough documentation covering every aspect of the framework. Whether you are new to the framework or have previous experience with Laravel, we recommend reading all of the documentation from beginning to end. +
+
+
+ +
+
+ + +
+ +
+
+ Laracasts offers thousands of video tutorials on Laravel, PHP, and JavaScript development. Check them out, see for yourself, and massively level up your development skills in the process. +
+
+
+ +
+
+ + +
+ +
+
+ Laravel News is a community driven portal and newsletter aggregating all of the latest and most important news in the Laravel ecosystem, including new package releases and tutorials. +
+
+
+ +
+
+ +
Vibrant Ecosystem
+
+ +
+
+ Laravel's robust library of first-party tools and libraries, such as Forge, Vapor, Nova, and Envoyer help you take your projects to the next level. Pair them with powerful open source libraries like Cashier, Dusk, Echo, Horizon, Sanctum, Telescope, and more. +
+
+
+
+
+ +
+
+
+ + + + + + Shop + + + + + + + + Sponsor + +
+
+ +
+ Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}) +
+
+
+
+ + diff --git a/php/libraries/composer/vendor/laravel/laravel/routes/api.php b/php/libraries/composer/vendor/laravel/laravel/routes/api.php new file mode 100644 index 0000000..eb6fa48 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/routes/api.php @@ -0,0 +1,19 @@ +get('/user', function (Request $request) { + return $request->user(); +}); diff --git a/php/libraries/composer/vendor/laravel/laravel/routes/channels.php b/php/libraries/composer/vendor/laravel/laravel/routes/channels.php new file mode 100644 index 0000000..5d451e1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/routes/channels.php @@ -0,0 +1,18 @@ +id === (int) $id; +}); diff --git a/php/libraries/composer/vendor/laravel/laravel/routes/console.php b/php/libraries/composer/vendor/laravel/laravel/routes/console.php new file mode 100644 index 0000000..e05f4c9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/routes/console.php @@ -0,0 +1,19 @@ +comment(Inspiring::quote()); +})->purpose('Display an inspiring quote'); diff --git a/php/libraries/composer/vendor/laravel/laravel/routes/web.php b/php/libraries/composer/vendor/laravel/laravel/routes/web.php new file mode 100644 index 0000000..b130397 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/routes/web.php @@ -0,0 +1,18 @@ + + */ + +$uri = urldecode( + parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) +); + +// This file allows us to emulate Apache's "mod_rewrite" functionality from the +// built-in PHP web server. This provides a convenient way to test a Laravel +// application without having installed a "real" web server software here. +if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { + return false; +} + +require_once __DIR__.'/public/index.php'; diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/app/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/app/.gitignore new file mode 100644 index 0000000..8f4803c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/app/.gitignore @@ -0,0 +1,3 @@ +* +!public/ +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/app/public/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/app/public/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/app/public/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/framework/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/framework/.gitignore new file mode 100644 index 0000000..05c4471 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/framework/.gitignore @@ -0,0 +1,9 @@ +compiled.php +config.php +down +events.scanned.php +maintenance.php +routes.php +routes.scanned.php +schedule-* +services.json diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/framework/cache/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/framework/cache/.gitignore new file mode 100644 index 0000000..01e4a6c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/framework/cache/.gitignore @@ -0,0 +1,3 @@ +* +!data/ +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/framework/cache/data/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/framework/cache/data/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/framework/cache/data/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/framework/sessions/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/framework/sessions/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/framework/sessions/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/framework/testing/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/framework/testing/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/framework/testing/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/framework/views/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/framework/views/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/framework/views/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/storage/logs/.gitignore b/php/libraries/composer/vendor/laravel/laravel/storage/logs/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/storage/logs/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/php/libraries/composer/vendor/laravel/laravel/tests/CreatesApplication.php b/php/libraries/composer/vendor/laravel/laravel/tests/CreatesApplication.php new file mode 100644 index 0000000..547152f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/tests/CreatesApplication.php @@ -0,0 +1,22 @@ +make(Kernel::class)->bootstrap(); + + return $app; + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/tests/Feature/ExampleTest.php b/php/libraries/composer/vendor/laravel/laravel/tests/Feature/ExampleTest.php new file mode 100644 index 0000000..4ae02bc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/tests/Feature/ExampleTest.php @@ -0,0 +1,21 @@ +get('/'); + + $response->assertStatus(200); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/tests/TestCase.php b/php/libraries/composer/vendor/laravel/laravel/tests/TestCase.php new file mode 100644 index 0000000..2932d4a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/tests/TestCase.php @@ -0,0 +1,10 @@ +assertTrue(true); + } +} diff --git a/php/libraries/composer/vendor/laravel/laravel/webpack.mix.js b/php/libraries/composer/vendor/laravel/laravel/webpack.mix.js new file mode 100644 index 0000000..2a22dc1 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/laravel/webpack.mix.js @@ -0,0 +1,17 @@ +const mix = require('laravel-mix'); + +/* + |-------------------------------------------------------------------------- + | Mix Asset Management + |-------------------------------------------------------------------------- + | + | Mix provides a clean, fluent API for defining some Webpack build steps + | for your Laravel applications. By default, we are compiling the CSS + | file for the application as well as bundling up all the JS files. + | + */ + +mix.js('resources/js/app.js', 'public/js') + .postCss('resources/css/app.css', 'public/css', [ + // + ]); diff --git a/php/libraries/composer/vendor/laravel/sanctum/LICENSE.md b/php/libraries/composer/vendor/laravel/sanctum/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/sanctum/README.md b/php/libraries/composer/vendor/laravel/sanctum/README.md new file mode 100644 index 0000000..263eb5e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/README.md @@ -0,0 +1,32 @@ +

Logo Laravel Sanctum

+ +

+Build Status +Total Downloads +Latest Stable Version +License +

+ +## Introduction + +Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs. + +## Official Documentation + +Documentation for Sanctum can be found on the [Laravel website](https://laravel.com/docs/sanctum). + +## Contributing + +Thank you for considering contributing to Sanctum! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +Please review [our security policy](https://github.com/laravel/sanctum/security/policy) on how to report security vulnerabilities. + +## License + +Laravel Sanctum is open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/php/libraries/composer/vendor/laravel/sanctum/composer.json b/php/libraries/composer/vendor/laravel/sanctum/composer.json new file mode 100644 index 0000000..1c27485 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/composer.json @@ -0,0 +1,54 @@ +{ + "name": "laravel/sanctum", + "description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.", + "keywords": ["laravel", "sanctum", "auth"], + "license": "MIT", + "support": { + "issues": "https://github.com/laravel/sanctum/issues", + "source": "https://github.com/laravel/sanctum" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.2|^8.0", + "ext-json": "*", + "illuminate/console": "^6.9|^7.0|^8.0|^9.0", + "illuminate/contracts": "^6.9|^7.0|^8.0|^9.0", + "illuminate/database": "^6.9|^7.0|^8.0|^9.0", + "illuminate/support": "^6.9|^7.0|^8.0|^9.0" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0", + "phpunit/phpunit": "^8.0|^9.3" + }, + "autoload": { + "psr-4": { + "Laravel\\Sanctum\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Laravel\\Sanctum\\Tests\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + }, + "laravel": { + "providers": [ + "Laravel\\Sanctum\\SanctumServiceProvider" + ] + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/config/sanctum.php b/php/libraries/composer/vendor/laravel/sanctum/config/sanctum.php new file mode 100644 index 0000000..529cfdc --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/config/sanctum.php @@ -0,0 +1,67 @@ + explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( + '%s%s', + 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', + Sanctum::currentApplicationUrlWithPort() + ))), + + /* + |-------------------------------------------------------------------------- + | Sanctum Guards + |-------------------------------------------------------------------------- + | + | This array contains the authentication guards that will be checked when + | Sanctum is trying to authenticate a request. If none of these guards + | are able to authenticate the request, Sanctum will use the bearer + | token that's present on an incoming request for authentication. + | + */ + + 'guard' => ['web'], + + /* + |-------------------------------------------------------------------------- + | Expiration Minutes + |-------------------------------------------------------------------------- + | + | This value controls the number of minutes until an issued token will be + | considered expired. If this value is null, personal access tokens do + | not expire. This won't tweak the lifetime of first-party sessions. + | + */ + + 'expiration' => null, + + /* + |-------------------------------------------------------------------------- + | Sanctum Middleware + |-------------------------------------------------------------------------- + | + | When authenticating your first-party SPA with Sanctum you may need to + | customize some of the middleware Sanctum uses while processing the + | request. You may change the middleware listed below as required. + | + */ + + 'middleware' => [ + 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class, + 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class, + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/sanctum/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php b/php/libraries/composer/vendor/laravel/sanctum/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php new file mode 100644 index 0000000..3ce0002 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php @@ -0,0 +1,36 @@ +bigIncrements('id'); + $table->morphs('tokenable'); + $table->string('name'); + $table->string('token', 64)->unique(); + $table->text('abilities')->nullable(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('personal_access_tokens'); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Console/Commands/PruneExpired.php b/php/libraries/composer/vendor/laravel/sanctum/src/Console/Commands/PruneExpired.php new file mode 100644 index 0000000..0e07bfb --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Console/Commands/PruneExpired.php @@ -0,0 +1,47 @@ +option('hours'); + + $model::where('created_at', '<', now()->subMinutes($expiration + ($hours * 60)))->delete(); + + $this->info("Tokens expired for more than {$hours} hours pruned successfully."); + + return 0; + } + + $this->warn('Expiration value not specified in configuration file.'); + + return 1; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Contracts/HasAbilities.php b/php/libraries/composer/vendor/laravel/sanctum/src/Contracts/HasAbilities.php new file mode 100644 index 0000000..6012e2e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Contracts/HasAbilities.php @@ -0,0 +1,22 @@ +token = $token; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Exceptions/MissingAbilityException.php b/php/libraries/composer/vendor/laravel/sanctum/src/Exceptions/MissingAbilityException.php new file mode 100644 index 0000000..287fafe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Exceptions/MissingAbilityException.php @@ -0,0 +1,40 @@ +abilities = Arr::wrap($abilities); + } + + /** + * Get the abilities that the user did not have. + * + * @return array + */ + public function abilities() + { + return $this->abilities; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Exceptions/MissingScopeException.php b/php/libraries/composer/vendor/laravel/sanctum/src/Exceptions/MissingScopeException.php new file mode 100644 index 0000000..de9bcd9 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Exceptions/MissingScopeException.php @@ -0,0 +1,40 @@ +scopes = Arr::wrap($scopes); + } + + /** + * Get the scopes that the user did not have. + * + * @return array + */ + public function scopes() + { + return $this->scopes; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Guard.php b/php/libraries/composer/vendor/laravel/sanctum/src/Guard.php new file mode 100644 index 0000000..5dde429 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Guard.php @@ -0,0 +1,162 @@ +auth = $auth; + $this->expiration = $expiration; + $this->provider = $provider; + } + + /** + * Retrieve the authenticated user for the incoming request. + * + * @param \Illuminate\Http\Request $request + * @return mixed + */ + public function __invoke(Request $request) + { + foreach (Arr::wrap(config('sanctum.guard', 'web')) as $guard) { + if ($user = $this->auth->guard($guard)->user()) { + return $this->supportsTokens($user) + ? $user->withAccessToken(new TransientToken) + : $user; + } + } + + if ($token = $this->getTokenFromRequest($request)) { + $model = Sanctum::$personalAccessTokenModel; + + $accessToken = $model::findToken($token); + + if (! $this->isValidAccessToken($accessToken) || + ! $this->supportsTokens($accessToken->tokenable)) { + return; + } + + $tokenable = $accessToken->tokenable->withAccessToken( + $accessToken + ); + + event(new TokenAuthenticated($accessToken)); + + if (method_exists($accessToken->getConnection(), 'hasModifiedRecords') && + method_exists($accessToken->getConnection(), 'setRecordModificationState')) { + tap($accessToken->getConnection()->hasModifiedRecords(), function ($hasModifiedRecords) use ($accessToken) { + $accessToken->forceFill(['last_used_at' => now()])->save(); + + $accessToken->getConnection()->setRecordModificationState($hasModifiedRecords); + }); + } else { + $accessToken->forceFill(['last_used_at' => now()])->save(); + } + + return $tokenable; + } + } + + /** + * Determine if the tokenable model supports API tokens. + * + * @param mixed $tokenable + * @return bool + */ + protected function supportsTokens($tokenable = null) + { + return $tokenable && in_array(HasApiTokens::class, class_uses_recursive( + get_class($tokenable) + )); + } + + /** + * Get the token from the request. + * + * @param \Illuminate\Http\Request $request + * @return string|null + */ + protected function getTokenFromRequest(Request $request) + { + if (is_callable(Sanctum::$accessTokenRetrievalCallback)) { + return (string) (Sanctum::$accessTokenRetrievalCallback)($request); + } + + return $request->bearerToken(); + } + + /** + * Determine if the provided access token is valid. + * + * @param mixed $accessToken + * @return bool + */ + protected function isValidAccessToken($accessToken): bool + { + if (! $accessToken) { + return false; + } + + $isValid = + (! $this->expiration || $accessToken->created_at->gt(now()->subMinutes($this->expiration))) + && $this->hasValidProvider($accessToken->tokenable); + + if (is_callable(Sanctum::$accessTokenAuthenticationCallback)) { + $isValid = (bool) (Sanctum::$accessTokenAuthenticationCallback)($accessToken, $isValid); + } + + return $isValid; + } + + /** + * Determine if the tokenable model matches the provider's model type. + * + * @param \Illuminate\Database\Eloquent\Model $tokenable + * @return bool + */ + protected function hasValidProvider($tokenable) + { + if (is_null($this->provider)) { + return true; + } + + $model = config("auth.providers.{$this->provider}.model"); + + return $tokenable instanceof $model; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/HasApiTokens.php b/php/libraries/composer/vendor/laravel/sanctum/src/HasApiTokens.php new file mode 100644 index 0000000..c3d5c80 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/HasApiTokens.php @@ -0,0 +1,77 @@ +morphMany(Sanctum::$personalAccessTokenModel, 'tokenable'); + } + + /** + * Determine if the current API token has a given scope. + * + * @param string $ability + * @return bool + */ + public function tokenCan(string $ability) + { + return $this->accessToken && $this->accessToken->can($ability); + } + + /** + * Create a new personal access token for the user. + * + * @param string $name + * @param array $abilities + * @return \Laravel\Sanctum\NewAccessToken + */ + public function createToken(string $name, array $abilities = ['*']) + { + $token = $this->tokens()->create([ + 'name' => $name, + 'token' => hash('sha256', $plainTextToken = Str::random(40)), + 'abilities' => $abilities, + ]); + + return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken); + } + + /** + * Get the access token currently associated with the user. + * + * @return \Laravel\Sanctum\Contracts\HasAbilities + */ + public function currentAccessToken() + { + return $this->accessToken; + } + + /** + * Set the current access token for the user. + * + * @param \Laravel\Sanctum\Contracts\HasAbilities $accessToken + * @return $this + */ + public function withAccessToken($accessToken) + { + $this->accessToken = $accessToken; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Http/Controllers/CsrfCookieController.php b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Controllers/CsrfCookieController.php new file mode 100644 index 0000000..2cb9dfe --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Controllers/CsrfCookieController.php @@ -0,0 +1,25 @@ +expectsJson()) { + return new JsonResponse(null, 204); + } + + return new Response('', 204); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckAbilities.php b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckAbilities.php new file mode 100644 index 0000000..2a4d157 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckAbilities.php @@ -0,0 +1,34 @@ +user() || ! $request->user()->currentAccessToken()) { + throw new AuthenticationException; + } + + foreach ($abilities as $ability) { + if (! $request->user()->tokenCan($ability)) { + throw new MissingAbilityException($ability); + } + } + + return $next($request); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckForAnyAbility.php b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckForAnyAbility.php new file mode 100644 index 0000000..b7d7d31 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckForAnyAbility.php @@ -0,0 +1,34 @@ +user() || ! $request->user()->currentAccessToken()) { + throw new AuthenticationException; + } + + foreach ($abilities as $ability) { + if ($request->user()->tokenCan($ability)) { + return $next($request); + } + } + + throw new MissingAbilityException($abilities); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckForAnyScope.php b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckForAnyScope.php new file mode 100644 index 0000000..5f4ec8f --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckForAnyScope.php @@ -0,0 +1,31 @@ +handle($request, $next, ...$scopes); + } catch (\Laravel\Sanctum\Exceptions\MissingAbilityException $e) { + throw new MissingScopeException($e->abilities()); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckScopes.php b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckScopes.php new file mode 100644 index 0000000..aa5786c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/CheckScopes.php @@ -0,0 +1,31 @@ +handle($request, $next, ...$scopes); + } catch (\Laravel\Sanctum\Exceptions\MissingAbilityException $e) { + throw new MissingScopeException($e->abilities()); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php new file mode 100644 index 0000000..f1e3423 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php @@ -0,0 +1,74 @@ +configureSecureCookieSessions(); + + return (new Pipeline(app()))->send($request)->through(static::fromFrontend($request) ? [ + function ($request, $next) { + $request->attributes->set('sanctum', true); + + return $next($request); + }, + config('sanctum.middleware.encrypt_cookies', \Illuminate\Cookie\Middleware\EncryptCookies::class), + \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, + \Illuminate\Session\Middleware\StartSession::class, + config('sanctum.middleware.verify_csrf_token', \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class), + ] : [])->then(function ($request) use ($next) { + return $next($request); + }); + } + + /** + * Configure secure cookie sessions. + * + * @return void + */ + protected function configureSecureCookieSessions() + { + config([ + 'session.http_only' => true, + 'session.same_site' => 'lax', + ]); + } + + /** + * Determine if the given request is from the first-party application frontend. + * + * @param \Illuminate\Http\Request $request + * @return bool + */ + public static function fromFrontend($request) + { + $domain = $request->headers->get('referer') ?: $request->headers->get('origin'); + + if (is_null($domain)) { + return false; + } + + $domain = Str::replaceFirst('https://', '', $domain); + $domain = Str::replaceFirst('http://', '', $domain); + $domain = Str::endsWith($domain, '/') ? $domain : "{$domain}/"; + + $stateful = array_filter(config('sanctum.stateful', [])); + + return Str::is(Collection::make($stateful)->map(function ($uri) { + return trim($uri).'/*'; + })->all(), $domain); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/NewAccessToken.php b/php/libraries/composer/vendor/laravel/sanctum/src/NewAccessToken.php new file mode 100644 index 0000000..489fae6 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/NewAccessToken.php @@ -0,0 +1,60 @@ +accessToken = $accessToken; + $this->plainTextToken = $plainTextToken; + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return [ + 'accessToken' => $this->accessToken, + 'plainTextToken' => $this->plainTextToken, + ]; + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->toArray(), $options); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/PersonalAccessToken.php b/php/libraries/composer/vendor/laravel/sanctum/src/PersonalAccessToken.php new file mode 100644 index 0000000..0d5df21 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/PersonalAccessToken.php @@ -0,0 +1,91 @@ + 'json', + 'last_used_at' => 'datetime', + ]; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', + 'token', + 'abilities', + ]; + + /** + * The attributes that should be hidden for serialization. + * + * @var array + */ + protected $hidden = [ + 'token', + ]; + + /** + * Get the tokenable model that the access token belongs to. + * + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function tokenable() + { + return $this->morphTo('tokenable'); + } + + /** + * Find the token instance matching the given token. + * + * @param string $token + * @return static|null + */ + public static function findToken($token) + { + if (strpos($token, '|') === false) { + return static::where('token', hash('sha256', $token))->first(); + } + + [$id, $token] = explode('|', $token, 2); + + if ($instance = static::find($id)) { + return hash_equals($instance->token, hash('sha256', $token)) ? $instance : null; + } + } + + /** + * Determine if the token has a given ability. + * + * @param string $ability + * @return bool + */ + public function can($ability) + { + return in_array('*', $this->abilities) || + array_key_exists($ability, array_flip($this->abilities)); + } + + /** + * Determine if the token is missing a given ability. + * + * @param string $ability + * @return bool + */ + public function cant($ability) + { + return ! $this->can($ability); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/Sanctum.php b/php/libraries/composer/vendor/laravel/sanctum/src/Sanctum.php new file mode 100644 index 0000000..09063e4 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/Sanctum.php @@ -0,0 +1,146 @@ +shouldIgnoreMissing(false); + + if (in_array('*', $abilities)) { + $token->shouldReceive('can')->withAnyArgs()->andReturn(true); + } else { + foreach ($abilities as $ability) { + $token->shouldReceive('can')->with($ability)->andReturn(true); + } + } + + $user->withAccessToken($token); + + if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) { + $user->wasRecentlyCreated = false; + } + + app('auth')->guard($guard)->setUser($user); + + app('auth')->shouldUse($guard); + + return $user; + } + + /** + * Set the personal access token model name. + * + * @param string $model + * @return void + */ + public static function usePersonalAccessTokenModel($model) + { + static::$personalAccessTokenModel = $model; + } + + /** + * Specify a callback that should be used to fetch the access token from the request. + * + * @param callable $callback + * @return void + */ + public static function getAccessTokenFromRequestUsing(callable $callback) + { + static::$accessTokenRetrievalCallback = $callback; + } + + /** + * Specify a callback that should be used to authenticate access tokens. + * + * @param callable $callback + * @return void + */ + public static function authenticateAccessTokensUsing(callable $callback) + { + static::$accessTokenAuthenticationCallback = $callback; + } + + /** + * Determine if Sanctum's migrations should be run. + * + * @return bool + */ + public static function shouldRunMigrations() + { + return static::$runsMigrations; + } + + /** + * Configure Sanctum to not register its migrations. + * + * @return static + */ + public static function ignoreMigrations() + { + static::$runsMigrations = false; + + return new static; + } + + /** + * Get the token model class name. + * + * @return string + */ + public static function personalAccessTokenModel() + { + return static::$personalAccessTokenModel; + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/SanctumServiceProvider.php b/php/libraries/composer/vendor/laravel/sanctum/src/SanctumServiceProvider.php new file mode 100644 index 0000000..27c0072 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/SanctumServiceProvider.php @@ -0,0 +1,137 @@ + array_merge([ + 'driver' => 'sanctum', + 'provider' => null, + ], config('auth.guards.sanctum', [])), + ]); + + if (! app()->configurationIsCached()) { + $this->mergeConfigFrom(__DIR__.'/../config/sanctum.php', 'sanctum'); + } + } + + /** + * Bootstrap any application services. + * + * @return void + */ + public function boot() + { + if (app()->runningInConsole()) { + $this->registerMigrations(); + + $this->publishes([ + __DIR__.'/../database/migrations' => database_path('migrations'), + ], 'sanctum-migrations'); + + $this->publishes([ + __DIR__.'/../config/sanctum.php' => config_path('sanctum.php'), + ], 'sanctum-config'); + + $this->commands([ + PruneExpired::class, + ]); + } + + $this->defineRoutes(); + $this->configureGuard(); + $this->configureMiddleware(); + } + + /** + * Register Sanctum's migration files. + * + * @return void + */ + protected function registerMigrations() + { + if (Sanctum::shouldRunMigrations()) { + return $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); + } + } + + /** + * Define the Sanctum routes. + * + * @return void + */ + protected function defineRoutes() + { + if (app()->routesAreCached() || config('sanctum.routes') === false) { + return; + } + + Route::group(['prefix' => config('sanctum.prefix', 'sanctum')], function () { + Route::get( + '/csrf-cookie', + CsrfCookieController::class.'@show' + )->middleware('web'); + }); + } + + /** + * Configure the Sanctum authentication guard. + * + * @return void + */ + protected function configureGuard() + { + Auth::resolved(function ($auth) { + $auth->extend('sanctum', function ($app, $name, array $config) use ($auth) { + return tap($this->createGuard($auth, $config), function ($guard) { + app()->refresh('request', $guard, 'setRequest'); + }); + }); + }); + } + + /** + * Register the guard. + * + * @param \Illuminate\Contracts\Auth\Factory $auth + * @param array $config + * @return RequestGuard + */ + protected function createGuard($auth, $config) + { + return new RequestGuard( + new Guard($auth, config('sanctum.expiration'), $config['provider']), + request(), + $auth->createUserProvider($config['provider'] ?? null) + ); + } + + /** + * Configure the Sanctum middleware and priority. + * + * @return void + */ + protected function configureMiddleware() + { + $kernel = app()->make(Kernel::class); + + $kernel->prependToMiddlewarePriority(EnsureFrontendRequestsAreStateful::class); + } +} diff --git a/php/libraries/composer/vendor/laravel/sanctum/src/TransientToken.php b/php/libraries/composer/vendor/laravel/sanctum/src/TransientToken.php new file mode 100644 index 0000000..6987b5d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/sanctum/src/TransientToken.php @@ -0,0 +1,30 @@ + + Build Status + + + Total Downloads + + + Latest Stable Version + + + License + + +## Introduction + +> This project is a fork of the excellent [opis/closure: 3.x](https://github.com/opis/closure) package. At Laravel, we decided to fork this package as the upcoming version [4.x](https://github.com/opis/closure) is a complete rewrite on top of the [FFI extension](https://www.php.net/manual/en/book.ffi.php). As Laravel is a web framework, and FFI is not enabled by default in web requests, this fork allows us to keep using the `3.x` series while adding support for new PHP versions. + +Laravel Serializable Closure provides an easy and secure way to **serialize closures in PHP**. + +## Official Documentation + +### Installation + +> **Requires [PHP 7.4+](https://php.net/releases/)** + +First, install Laravel Serializable Closure via the [Composer](https://getcomposer.org/) package manager: + +```bash +composer require laravel/serializable-closure +``` + +### Usage + +You may serialize a closure this way: + +```php +use Laravel\SerializableClosure\SerializableClosure; + +$closure = fn () => 'james'; + +// Recommended +SerializableClosure::setSecretKey('secret'); + +$serialized = serialize(new SerializableClosure($closure)); +$closure = unserialize($serialized)->getClosure(); + +echo $closure(); // james; +``` + +### Caveats + +* Anonymous classes cannot be created within closures. +* Attributes cannot be used within closures. +* Serializing closures on REPL environments like Laravel Tinker is not supported. +* Serializing closures that reference objects with readonly properties is not supported. + +## Contributing + +Thank you for considering contributing to Serializable Closure! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +Please review [our security policy](https://github.com/laravel/serializable-closure/security/policy) on how to report security vulnerabilities. + +## License + +Serializable Closure is open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/composer.json b/php/libraries/composer/vendor/laravel/serializable-closure/composer.json new file mode 100644 index 0000000..7142366 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/composer.json @@ -0,0 +1,52 @@ +{ + "name": "laravel/serializable-closure", + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": ["laravel", "Serializable", "closure"], + "license": "MIT", + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "nesbot/carbon": "^2.61", + "pestphp/pest": "^1.21.3", + "phpstan/phpstan": "^1.8.2", + "symfony/var-dumper": "^5.4.11" + }, + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Contracts/Serializable.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Contracts/Serializable.php new file mode 100644 index 0000000..1a62922 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Contracts/Serializable.php @@ -0,0 +1,20 @@ +serializable = Serializers\Signed::$signer + ? new Serializers\Signed($closure) + : new Serializers\Native($closure); + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return call_user_func_array($this->serializable, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return $this->serializable->getClosure(); + } + + /** + * Create a new unsigned serializable closure instance. + * + * @param Closure $closure + * @return \Laravel\SerializableClosure\UnsignedSerializableClosure + */ + public static function unsigned(Closure $closure) + { + return new UnsignedSerializableClosure($closure); + } + + /** + * Sets the serializable closure secret key. + * + * @param string|null $secret + * @return void + */ + public static function setSecretKey($secret) + { + Serializers\Signed::$signer = $secret + ? new Hmac($secret) + : null; + } + + /** + * Sets the serializable closure secret key. + * + * @param \Closure|null $transformer + * @return void + */ + public static function transformUseVariablesUsing($transformer) + { + Serializers\Native::$transformUseVariables = $transformer; + } + + /** + * Sets the serializable closure secret key. + * + * @param \Closure|null $resolver + * @return void + */ + public static function resolveUseVariablesUsing($resolver) + { + Serializers\Native::$resolveUseVariables = $resolver; + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + return [ + 'serializable' => $this->serializable, + ]; + } + + /** + * Restore the closure after serialization. + * + * @param array $data + * @return void + * + * @throws \Laravel\SerializableClosure\Exceptions\InvalidSignatureException + */ + public function __unserialize($data) + { + if (Signed::$signer && ! $data['serializable'] instanceof Signed) { + throw new InvalidSignatureException(); + } + + $this->serializable = $data['serializable']; + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Serializers/Native.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Serializers/Native.php new file mode 100644 index 0000000..4a04b98 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Serializers/Native.php @@ -0,0 +1,514 @@ +closure = $closure; + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + return call_user_func_array($this->closure, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + return $this->closure; + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + if ($this->scope === null) { + $this->scope = new ClosureScope(); + $this->scope->toSerialize++; + } + + $this->scope->serializations++; + + $scope = $object = null; + $reflector = $this->getReflector(); + + if ($reflector->isBindingRequired()) { + $object = $reflector->getClosureThis(); + + static::wrapClosures($object, $this->scope); + } + + if ($scope = $reflector->getClosureScopeClass()) { + $scope = $scope->name; + } + + $this->reference = spl_object_hash($this->closure); + + $this->scope[$this->closure] = $this; + + $use = $reflector->getUseVariables(); + + if (static::$transformUseVariables) { + $use = call_user_func(static::$transformUseVariables, $reflector->getUseVariables()); + } + + $code = $reflector->getCode(); + + $this->mapByReference($use); + + $data = [ + 'use' => $use, + 'function' => $code, + 'scope' => $scope, + 'this' => $object, + 'self' => $this->reference, + ]; + + if (! --$this->scope->serializations && ! --$this->scope->toSerialize) { + $this->scope = null; + } + + return $data; + } + + /** + * Restore the closure after serialization. + * + * @param array $data + * @return void + */ + public function __unserialize($data) + { + ClosureStream::register(); + + $this->code = $data; + unset($data); + + $this->code['objects'] = []; + + if ($this->code['use']) { + $this->scope = new ClosureScope(); + + if (static::$resolveUseVariables) { + $this->code['use'] = call_user_func(static::$resolveUseVariables, $this->code['use']); + } + + $this->mapPointers($this->code['use']); + + extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS); + + $this->scope = null; + } + + $this->closure = include ClosureStream::STREAM_PROTO.'://'.$this->code['function']; + + if ($this->code['this'] === $this) { + $this->code['this'] = null; + } + + $this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']); + + if (! empty($this->code['objects'])) { + foreach ($this->code['objects'] as $item) { + $item['property']->setValue($item['instance'], $item['object']->getClosure()); + } + } + + $this->code = $this->code['function']; + } + + /** + * Ensures the given closures are serializable. + * + * @param mixed $data + * @param \Laravel\SerializableClosure\Support\ClosureScope $storage + * @return void + */ + public static function wrapClosures(&$data, $storage) + { + if ($data instanceof Closure) { + $data = new static($data); + } elseif (is_array($data)) { + if (isset($data[self::ARRAY_RECURSIVE_KEY])) { + return; + } + + $data[self::ARRAY_RECURSIVE_KEY] = true; + + foreach ($data as $key => &$value) { + if ($key === self::ARRAY_RECURSIVE_KEY) { + continue; + } + static::wrapClosures($value, $storage); + } + + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if (isset($storage[$data])) { + $data = $storage[$data]; + + return; + } + + $data = $storage[$data] = clone $data; + + foreach ($data as &$value) { + static::wrapClosures($value, $storage); + } + + unset($value); + } elseif (is_object($data) && ! $data instanceof static && ! $data instanceof UnitEnum) { + if (isset($storage[$data])) { + $data = $storage[$data]; + + return; + } + + $instance = $data; + $reflection = new ReflectionObject($instance); + + if (! $reflection->isUserDefined()) { + $storage[$instance] = $data; + + return; + } + + $storage[$instance] = $data = $reflection->newInstanceWithoutConstructor(); + + do { + if (! $reflection->isUserDefined()) { + break; + } + + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) { + continue; + } + + $property->setAccessible(true); + + if (PHP_VERSION >= 7.4 && ! $property->isInitialized($instance)) { + continue; + } + + $value = $property->getValue($instance); + + if (is_array($value) || is_object($value)) { + static::wrapClosures($value, $storage); + } + + $property->setValue($data, $value); + } + } while ($reflection = $reflection->getParentClass()); + } + } + + /** + * Gets the closure's reflector. + * + * @return \Laravel\SerializableClosure\Support\ReflectionClosure + */ + public function getReflector() + { + if ($this->reflector === null) { + $this->code = null; + $this->reflector = new ReflectionClosure($this->closure); + } + + return $this->reflector; + } + + /** + * Internal method used to map closure pointers. + * + * @param mixed $data + * @return void + */ + protected function mapPointers(&$data) + { + $scope = $this->scope; + + if ($data instanceof static) { + $data = &$data->closure; + } elseif (is_array($data)) { + if (isset($data[self::ARRAY_RECURSIVE_KEY])) { + return; + } + + $data[self::ARRAY_RECURSIVE_KEY] = true; + + foreach ($data as $key => &$value) { + if ($key === self::ARRAY_RECURSIVE_KEY) { + continue; + } elseif ($value instanceof static) { + $data[$key] = &$value->closure; + } elseif ($value instanceof SelfReference && $value->hash === $this->code['self']) { + $data[$key] = &$this->closure; + } else { + $this->mapPointers($value); + } + } + + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if (isset($scope[$data])) { + return; + } + + $scope[$data] = true; + + foreach ($data as $key => &$value) { + if ($value instanceof SelfReference && $value->hash === $this->code['self']) { + $data->{$key} = &$this->closure; + } elseif (is_array($value) || is_object($value)) { + $this->mapPointers($value); + } + } + + unset($value); + } elseif (is_object($data) && ! ($data instanceof Closure)) { + if (isset($scope[$data])) { + return; + } + + $scope[$data] = true; + $reflection = new ReflectionObject($data); + + do { + if (! $reflection->isUserDefined()) { + break; + } + + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) { + continue; + } + + $property->setAccessible(true); + + if (PHP_VERSION >= 7.4 && ! $property->isInitialized($data)) { + continue; + } + + $item = $property->getValue($data); + + if ($item instanceof SerializableClosure || $item instanceof UnsignedSerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) { + $this->code['objects'][] = [ + 'instance' => $data, + 'property' => $property, + 'object' => $item instanceof SelfReference ? $this : $item, + ]; + } elseif (is_array($item) || is_object($item)) { + $this->mapPointers($item); + $property->setValue($data, $item); + } + } + } while ($reflection = $reflection->getParentClass()); + } + } + + /** + * Internal method used to map closures by reference. + * + * @param mixed $data + * @return void + */ + protected function mapByReference(&$data) + { + if ($data instanceof Closure) { + if ($data === $this->closure) { + $data = new SelfReference($this->reference); + + return; + } + + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + + return; + } + + $instance = new static($data); + + $instance->scope = $this->scope; + + $data = $this->scope[$data] = $instance; + } elseif (is_array($data)) { + if (isset($data[self::ARRAY_RECURSIVE_KEY])) { + return; + } + + $data[self::ARRAY_RECURSIVE_KEY] = true; + + foreach ($data as $key => &$value) { + if ($key === self::ARRAY_RECURSIVE_KEY) { + continue; + } + + $this->mapByReference($value); + } + + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + + return; + } + + $instance = $data; + $this->scope[$instance] = $data = clone $data; + + foreach ($data as &$value) { + $this->mapByReference($value); + } + + unset($value); + } elseif (is_object($data) && ! $data instanceof SerializableClosure && ! $data instanceof UnsignedSerializableClosure) { + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + + return; + } + + $instance = $data; + + if ($data instanceof DateTimeInterface) { + $this->scope[$instance] = $data; + + return; + } + + if ($data instanceof UnitEnum) { + $this->scope[$instance] = $data; + + return; + } + + $reflection = new ReflectionObject($data); + + if (! $reflection->isUserDefined()) { + $this->scope[$instance] = $data; + + return; + } + + $this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor(); + + do { + if (! $reflection->isUserDefined()) { + break; + } + + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) { + continue; + } + + $property->setAccessible(true); + + if (PHP_VERSION >= 7.4 && ! $property->isInitialized($instance)) { + continue; + } + + $value = $property->getValue($instance); + + if (is_array($value) || is_object($value)) { + $this->mapByReference($value); + } + + $property->setValue($data, $value); + } + } while ($reflection = $reflection->getParentClass()); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Serializers/Signed.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Serializers/Signed.php new file mode 100644 index 0000000..391d20d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Serializers/Signed.php @@ -0,0 +1,91 @@ +closure = $closure; + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + return call_user_func_array($this->closure, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + return $this->closure; + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + if (! static::$signer) { + throw new MissingSecretKeyException(); + } + + return static::$signer->sign( + serialize(new Native($this->closure)) + ); + } + + /** + * Restore the closure after serialization. + * + * @param array $signature + * @return void + * + * @throws \Laravel\SerializableClosure\Exceptions\InvalidSignatureException + */ + public function __unserialize($signature) + { + if (static::$signer && ! static::$signer->verify($signature)) { + throw new InvalidSignatureException(); + } + + /** @var \Laravel\SerializableClosure\Contracts\Serializable $serializable */ + $serializable = unserialize($signature['serializable']); + + $this->closure = $serializable->getClosure(); + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Signers/Hmac.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Signers/Hmac.php new file mode 100644 index 0000000..d94b0a2 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Signers/Hmac.php @@ -0,0 +1,53 @@ +secret = $secret; + } + + /** + * Sign the given serializable. + * + * @param string $serialized + * @return array + */ + public function sign($serialized) + { + return [ + 'serializable' => $serialized, + 'hash' => base64_encode(hash_hmac('sha256', $serialized, $this->secret, true)), + ]; + } + + /** + * Verify the given signature. + * + * @param array $signature + * @return bool + */ + public function verify($signature) + { + return hash_equals(base64_encode( + hash_hmac('sha256', $signature['serializable'], $this->secret, true) + ), $signature['hash']); + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/ClosureScope.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/ClosureScope.php new file mode 100644 index 0000000..64ca19a --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/ClosureScope.php @@ -0,0 +1,22 @@ +content = "length = strlen($this->content); + + return true; + } + + /** + * Read from stream. + * + * @param int $count + * @return string + */ + public function stream_read($count) + { + $value = substr($this->content, $this->pointer, $count); + + $this->pointer += $count; + + return $value; + } + + /** + * Tests for end-of-file on a file pointer. + * + * @return bool + */ + public function stream_eof() + { + return $this->pointer >= $this->length; + } + + /** + * Change stream options. + * + * @param int $option + * @param int $arg1 + * @param int $arg2 + * @return bool + */ + public function stream_set_option($option, $arg1, $arg2) + { + return false; + } + + /** + * Retrieve information about a file resource. + * + * @return array|bool + */ + public function stream_stat() + { + $stat = stat(__FILE__); + // @phpstan-ignore-next-line + $stat[7] = $stat['size'] = $this->length; + + return $stat; + } + + /** + * Retrieve information about a file. + * + * @param string $path + * @param int $flags + * @return array|bool + */ + public function url_stat($path, $flags) + { + $stat = stat(__FILE__); + // @phpstan-ignore-next-line + $stat[7] = $stat['size'] = $this->length; + + return $stat; + } + + /** + * Seeks to specific location in a stream. + * + * @param int $offset + * @param int $whence + * @return bool + */ + public function stream_seek($offset, $whence = SEEK_SET) + { + $crt = $this->pointer; + + switch ($whence) { + case SEEK_SET: + $this->pointer = $offset; + break; + case SEEK_CUR: + $this->pointer += $offset; + break; + case SEEK_END: + $this->pointer = $this->length + $offset; + break; + } + + if ($this->pointer < 0 || $this->pointer >= $this->length) { + $this->pointer = $crt; + + return false; + } + + return true; + } + + /** + * Retrieve the current position of a stream. + * + * @return int + */ + public function stream_tell() + { + return $this->pointer; + } + + /** + * Registers the stream. + * + * @return void + */ + public static function register() + { + if (! static::$isRegistered) { + static::$isRegistered = stream_wrapper_register(static::STREAM_PROTO, __CLASS__); + } + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/ReflectionClosure.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/ReflectionClosure.php new file mode 100644 index 0000000..0544004 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/ReflectionClosure.php @@ -0,0 +1,1198 @@ +isStaticClosure === null) { + $this->isStaticClosure = strtolower(substr($this->getCode(), 0, 6)) === 'static'; + } + + return $this->isStaticClosure; + } + + /** + * Checks if the closure is a "short closure". + * + * @return bool + */ + public function isShortClosure() + { + if ($this->isShortClosure === null) { + $code = $this->getCode(); + + if ($this->isStatic()) { + $code = substr($code, 6); + } + + $this->isShortClosure = strtolower(substr(trim($code), 0, 2)) === 'fn'; + } + + return $this->isShortClosure; + } + + /** + * Get the closure's code. + * + * @return string + */ + public function getCode() + { + if ($this->code !== null) { + return $this->code; + } + + $fileName = $this->getFileName(); + $line = $this->getStartLine() - 1; + + $className = null; + + if (null !== $className = $this->getClosureScopeClass()) { + $className = '\\'.trim($className->getName(), '\\'); + } + + $builtin_types = self::getBuiltinTypes(); + $class_keywords = ['self', 'static', 'parent']; + + $ns = $this->getClosureNamespaceName(); + $nsf = $ns == '' ? '' : ($ns[0] == '\\' ? $ns : '\\'.$ns); + + $_file = var_export($fileName, true); + $_dir = var_export(dirname($fileName), true); + $_namespace = var_export($ns, true); + $_class = var_export(trim($className ?: '', '\\'), true); + $_function = $ns.($ns == '' ? '' : '\\').'{closure}'; + $_method = ($className == '' ? '' : trim($className, '\\').'::').$_function; + $_function = var_export($_function, true); + $_method = var_export($_method, true); + $_trait = null; + + $tokens = $this->getTokens(); + $state = $lastState = 'start'; + $inside_structure = false; + $isFirstClassCallable = false; + $isShortClosure = false; + + $inside_structure_mark = 0; + $open = 0; + $code = ''; + $id_start = $id_start_ci = $id_name = $context = ''; + $classes = $functions = $constants = null; + $use = []; + $lineAdd = 0; + $isUsingScope = false; + $isUsingThisObject = false; + + for ($i = 0, $l = count($tokens); $i < $l; $i++) { + $token = $tokens[$i]; + + switch ($state) { + case 'start': + if ($token[0] === T_FUNCTION || $token[0] === T_STATIC) { + $code .= $token[1]; + + $state = $token[0] === T_FUNCTION ? 'function' : 'static'; + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } elseif ($token[0] === T_PUBLIC || $token[0] === T_PROTECTED || $token[0] === T_PRIVATE) { + $code = ''; + $isFirstClassCallable = true; + } + break; + case 'static': + if ($token[0] === T_WHITESPACE || $token[0] === T_COMMENT || $token[0] === T_FUNCTION) { + $code .= $token[1]; + if ($token[0] === T_FUNCTION) { + $state = 'function'; + } + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } else { + $code = ''; + $state = 'start'; + } + break; + case 'function': + switch ($token[0]) { + case T_STRING: + if ($isFirstClassCallable) { + $state = 'closure_args'; + break; + } + + $code = ''; + $state = 'named_function'; + break; + case '(': + $code .= '('; + $state = 'closure_args'; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'named_function': + if ($token[0] === T_FUNCTION || $token[0] === T_STATIC) { + $code = $token[1]; + $state = $token[0] === T_FUNCTION ? 'function' : 'static'; + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } + break; + case 'closure_args': + switch ($token[0]) { + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $context = 'args'; + $state = 'id_name'; + $lastState = 'closure_args'; + break; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'args'; + $state = 'id_name'; + $lastState = 'closure_args'; + break; + case T_USE: + $code .= $token[1]; + $state = 'use'; + break; + case T_DOUBLE_ARROW: + $code .= $token[1]; + if ($isShortClosure) { + $state = 'closure'; + } + break; + case ':': + $code .= ':'; + $state = 'return'; + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'use': + switch ($token[0]) { + case T_VARIABLE: + $use[] = substr($token[1], 1); + $code .= $token[1]; + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + case ':': + $code .= ':'; + $state = 'return'; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + break; + } + break; + case 'return': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'return_type'; + $state = 'id_name'; + $lastState = 'return'; + break 2; + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $context = 'return_type'; + $state = 'id_name'; + $lastState = 'return'; + break 2; + case T_DOUBLE_ARROW: + $code .= $token[1]; + if ($isShortClosure) { + $state = 'closure'; + } + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + break; + } + break; + case 'closure': + switch ($token[0]) { + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + case '{': + $code .= is_array($token) ? $token[1] : $token; + $open++; + break; + case '}': + $code .= '}'; + if (--$open === 0 && ! $isShortClosure) { + break 3; + } elseif ($inside_structure) { + $inside_structure = ! ($open === $inside_structure_mark); + } + break; + case '(': + case '[': + $code .= $token[0]; + if ($isShortClosure) { + $open++; + } + break; + case ')': + case ']': + if ($isShortClosure) { + if ($open === 0) { + break 3; + } + $open--; + } + $code .= $token[0]; + break; + case ',': + case ';': + if ($isShortClosure && $open === 0) { + break 3; + } + $code .= $token[0]; + break; + case T_LINE: + $code .= $token[2] - $line + $lineAdd; + break; + case T_FILE: + $code .= $_file; + break; + case T_DIR: + $code .= $_dir; + break; + case T_NS_C: + $code .= $_namespace; + break; + case T_CLASS_C: + $code .= $inside_structure ? $token[1] : $_class; + break; + case T_FUNC_C: + $code .= $inside_structure ? $token[1] : $_function; + break; + case T_METHOD_C: + $code .= $inside_structure ? $token[1] : $_method; + break; + case T_COMMENT: + if (substr($token[1], 0, 8) === '#trackme') { + $timestamp = time(); + $code .= '/**'.PHP_EOL; + $code .= '* Date : '.date(DATE_W3C, $timestamp).PHP_EOL; + $code .= '* Timestamp : '.$timestamp.PHP_EOL; + $code .= '* Line : '.($line + 1).PHP_EOL; + $code .= '* File : '.$_file.PHP_EOL.'*/'.PHP_EOL; + $lineAdd += 5; + } else { + $code .= $token[1]; + } + break; + case T_VARIABLE: + if ($token[1] == '$this' && ! $inside_structure) { + $isUsingThisObject = true; + } + $code .= $token[1]; + break; + case T_STATIC: + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'root'; + $state = 'id_name'; + $lastState = 'closure'; + break 2; + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $context = 'root'; + $state = 'id_name'; + $lastState = 'closure'; + break 2; + case T_NEW: + $code .= $token[1]; + $context = 'new'; + $state = 'id_start'; + $lastState = 'closure'; + break 2; + case T_USE: + $code .= $token[1]; + $context = 'use'; + $state = 'id_start'; + $lastState = 'closure'; + break; + case T_INSTANCEOF: + case T_INSTEADOF: + $code .= $token[1]; + $context = 'instanceof'; + $state = 'id_start'; + $lastState = 'closure'; + break; + case T_OBJECT_OPERATOR: + case T_NULLSAFE_OBJECT_OPERATOR: + case T_DOUBLE_COLON: + $code .= $token[1]; + $lastState = 'closure'; + $state = 'ignore_next'; + break; + case T_FUNCTION: + $code .= $token[1]; + $state = 'closure_args'; + if (! $inside_structure) { + $inside_structure = true; + $inside_structure_mark = $open; + } + break; + case T_TRAIT_C: + if ($_trait === null) { + $startLine = $this->getStartLine(); + $endLine = $this->getEndLine(); + $structures = $this->getStructures(); + + $_trait = ''; + + foreach ($structures as &$struct) { + if ($struct['type'] === 'trait' && + $struct['start'] <= $startLine && + $struct['end'] >= $endLine + ) { + $_trait = ($ns == '' ? '' : $ns.'\\').$struct['name']; + break; + } + } + + $_trait = var_export($_trait, true); + } + + $code .= $_trait; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'ignore_next': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_CLASS: + case T_NEW: + case T_STATIC: + case T_VARIABLE: + case T_STRING: + case T_CLASS_C: + case T_FILE: + case T_DIR: + case T_METHOD_C: + case T_FUNC_C: + case T_FUNCTION: + case T_INSTANCEOF: + case T_LINE: + case T_NS_C: + case T_TRAIT_C: + case T_USE: + $code .= $token[1]; + $state = $lastState; + break; + default: + $state = $lastState; + $i--; + } + break; + case 'id_start': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_NS_SEPARATOR: + case T_NAME_FULLY_QUALIFIED: + case T_STRING: + case T_STATIC: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $state = 'id_name'; + break 2; + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $state = 'id_name'; + break 2; + case T_VARIABLE: + $code .= $token[1]; + $state = $lastState; + break; + case T_CLASS: + $code .= $token[1]; + $state = 'anonymous'; + break; + default: + $i--; //reprocess last + $state = 'id_name'; + } + break; + case 'id_name': + switch ($token[0]) { + case $token[0] === ':' && $context !== 'instanceof': + if ($lastState === 'closure' && $context === 'root') { + $state = 'closure'; + $code .= $id_start.$token; + } + + break; + case T_NAME_QUALIFIED: + case T_NS_SEPARATOR: + case T_STRING: + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $id_name .= $token[1]; + break; + case '(': + if ($isShortClosure) { + $open++; + } + if ($context === 'new' || false !== strpos($id_name, '\\')) { + if ($id_start_ci === 'self' || $id_start_ci === 'static') { + if (! $inside_structure) { + $isUsingScope = true; + } + } elseif ($id_start !== '\\' && ! in_array($id_start_ci, $class_keywords)) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } else { + if ($id_start !== '\\') { + if ($functions === null) { + $functions = $this->getFunctions(); + } + if (isset($functions[$id_start_ci])) { + $id_start = $functions[$id_start_ci]; + } elseif ($nsf !== '\\' && function_exists($nsf.'\\'.$id_start)) { + $id_start = $nsf.'\\'.$id_start; + // Cache it to functions array + $functions[$id_start_ci] = $id_start; + } + } + } + $code .= $id_start.$id_name.'('; + $state = $lastState; + break; + case T_VARIABLE: + case T_DOUBLE_COLON: + if ($id_start !== '\\') { + if ($id_start_ci === 'self' || $id_start_ci === 'parent') { + if (! $inside_structure) { + $isUsingScope = true; + } + } elseif ($id_start_ci === 'static') { + if (! $inside_structure) { + $isUsingScope = $token[0] === T_DOUBLE_COLON; + } + } elseif (! (\PHP_MAJOR_VERSION >= 7 && in_array($id_start_ci, $builtin_types))) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } + + $code .= $id_start.$id_name.$token[1]; + $state = $token[0] === T_DOUBLE_COLON ? 'ignore_next' : $lastState; + break; + default: + if ($id_start !== '\\' && ! defined($id_start)) { + if ($constants === null) { + $constants = $this->getConstants(); + } + if (isset($constants[$id_start])) { + $id_start = $constants[$id_start]; + } elseif ($context === 'new') { + if (in_array($id_start_ci, $class_keywords)) { + if (! $inside_structure) { + $isUsingScope = true; + } + } else { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } elseif ($context === 'use' || + $context === 'instanceof' || + $context === 'args' || + $context === 'return_type' || + $context === 'extends' || + $context === 'root' + ) { + if (in_array($id_start_ci, $class_keywords)) { + if (! $inside_structure && ! $id_start_ci === 'static') { + $isUsingScope = true; + } + } elseif (! (\PHP_MAJOR_VERSION >= 7 && in_array($id_start_ci, $builtin_types))) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } + } + $code .= $id_start.$id_name; + $state = $lastState; + $i--; //reprocess last token + } + break; + case 'anonymous': + switch ($token[0]) { + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $state = 'id_name'; + $lastState = 'anonymous'; + break 2; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $state = 'id_name'; + $context = 'extends'; + $lastState = 'anonymous'; + break; + case '{': + $state = 'closure'; + if (! $inside_structure) { + $inside_structure = true; + $inside_structure_mark = $open; + } + $i--; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + } + } + + if ($isShortClosure) { + $this->useVariables = $this->getStaticVariables(); + } else { + $this->useVariables = empty($use) ? $use : array_intersect_key($this->getStaticVariables(), array_flip($use)); + } + + $this->isShortClosure = $isShortClosure; + $this->isBindingRequired = $isUsingThisObject; + $this->isScopeRequired = $isUsingScope; + + if (PHP_VERSION_ID >= 80100) { + $attributesCode = array_map(function ($attribute) { + $arguments = $attribute->getArguments(); + + $name = $attribute->getName(); + $arguments = implode(', ', array_map(function ($argument, $key) { + $argument = sprintf("'%s'", str_replace("'", "\\'", $argument)); + + if (is_string($key)) { + $argument = sprintf('%s: %s', $key, $argument); + } + + return $argument; + }, $arguments, array_keys($arguments))); + + return "#[$name($arguments)]"; + }, $this->getAttributes()); + + if (! empty($attributesCode)) { + $code = implode("\n", array_merge($attributesCode, [$code])); + } + } + + $this->code = $code; + + return $this->code; + } + + /** + * Get PHP native built in types. + * + * @return array + */ + protected static function getBuiltinTypes() + { + // PHP 8.1 + if (PHP_VERSION_ID >= 80100) { + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object', 'mixed', 'false', 'null', 'never']; + } + + // PHP 8 + if (\PHP_MAJOR_VERSION === 8) { + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object', 'mixed', 'false', 'null']; + } + + // PHP 7 + switch (\PHP_MINOR_VERSION) { + case 0: + return ['array', 'callable', 'string', 'int', 'bool', 'float']; + case 1: + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void']; + default: + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object']; + } + } + + /** + * Gets the use variables by the closure. + * + * @return array + */ + public function getUseVariables() + { + if ($this->useVariables !== null) { + return $this->useVariables; + } + + $tokens = $this->getTokens(); + $use = []; + $state = 'start'; + + foreach ($tokens as &$token) { + $is_array = is_array($token); + + switch ($state) { + case 'start': + if ($is_array && $token[0] === T_USE) { + $state = 'use'; + } + break; + case 'use': + if ($is_array) { + if ($token[0] === T_VARIABLE) { + $use[] = substr($token[1], 1); + } + } elseif ($token == ')') { + break 2; + } + break; + } + } + + $this->useVariables = empty($use) ? $use : array_intersect_key($this->getStaticVariables(), array_flip($use)); + + return $this->useVariables; + } + + /** + * Checks if binding is required. + * + * @return bool + */ + public function isBindingRequired() + { + if ($this->isBindingRequired === null) { + $this->getCode(); + } + + return $this->isBindingRequired; + } + + /** + * Checks if access to the scope is required. + * + * @return bool + */ + public function isScopeRequired() + { + if ($this->isScopeRequired === null) { + $this->getCode(); + } + + return $this->isScopeRequired; + } + + /** + * The the hash of the current file name. + * + * @return string + */ + protected function getHashedFileName() + { + if ($this->hashedName === null) { + $this->hashedName = sha1($this->getFileName()); + } + + return $this->hashedName; + } + + /** + * Get the file tokens. + * + * @return array + */ + protected function getFileTokens() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$files[$key])) { + static::$files[$key] = token_get_all(file_get_contents($this->getFileName())); + } + + return static::$files[$key]; + } + + /** + * Get the tokens. + * + * @return array + */ + protected function getTokens() + { + if ($this->tokens === null) { + $tokens = $this->getFileTokens(); + $startLine = $this->getStartLine(); + $endLine = $this->getEndLine(); + $results = []; + $start = false; + + foreach ($tokens as &$token) { + if (! is_array($token)) { + if ($start) { + $results[] = $token; + } + + continue; + } + + $line = $token[2]; + + if ($line <= $endLine) { + if ($line >= $startLine) { + $start = true; + $results[] = $token; + } + + continue; + } + + break; + } + + $this->tokens = $results; + } + + return $this->tokens; + } + + /** + * Get the classes. + * + * @return array + */ + protected function getClasses() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$classes[$key])) { + $this->fetchItems(); + } + + return static::$classes[$key]; + } + + /** + * Get the functions. + * + * @return array + */ + protected function getFunctions() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$functions[$key])) { + $this->fetchItems(); + } + + return static::$functions[$key]; + } + + /** + * Gets the constants. + * + * @return array + */ + protected function getConstants() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$constants[$key])) { + $this->fetchItems(); + } + + return static::$constants[$key]; + } + + /** + * Get the structures. + * + * @return array + */ + protected function getStructures() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$structures[$key])) { + $this->fetchItems(); + } + + return static::$structures[$key]; + } + + /** + * Fetch the items. + * + * @return void. + */ + protected function fetchItems() + { + $key = $this->getHashedFileName(); + + $classes = []; + $functions = []; + $constants = []; + $structures = []; + $tokens = $this->getFileTokens(); + + $open = 0; + $state = 'start'; + $lastState = ''; + $prefix = ''; + $name = ''; + $alias = ''; + $isFunc = $isConst = false; + + $startLine = $endLine = 0; + $structType = $structName = ''; + $structIgnore = false; + + foreach ($tokens as $token) { + switch ($state) { + case 'start': + switch ($token[0]) { + case T_CLASS: + case T_INTERFACE: + case T_TRAIT: + $state = 'before_structure'; + $startLine = $token[2]; + $structType = $token[0] == T_CLASS + ? 'class' + : ($token[0] == T_INTERFACE ? 'interface' : 'trait'); + break; + case T_USE: + $state = 'use'; + $prefix = $name = $alias = ''; + $isFunc = $isConst = false; + break; + case T_FUNCTION: + $state = 'structure'; + $structIgnore = true; + break; + case T_NEW: + $state = 'new'; + break; + case T_OBJECT_OPERATOR: + case T_DOUBLE_COLON: + $state = 'invoke'; + break; + } + break; + case 'use': + switch ($token[0]) { + case T_FUNCTION: + $isFunc = true; + break; + case T_CONST: + $isConst = true; + break; + case T_NS_SEPARATOR: + $name .= $token[1]; + break; + case T_STRING: + $name .= $token[1]; + $alias = $token[1]; + break; + case T_NAME_QUALIFIED: + $name .= $token[1]; + $pieces = explode('\\', $token[1]); + $alias = end($pieces); + break; + case T_AS: + $lastState = 'use'; + $state = 'alias'; + break; + case '{': + $prefix = $name; + $name = $alias = ''; + $state = 'use-group'; + break; + case ',': + case ';': + if ($name === '' || $name[0] !== '\\') { + $name = '\\'.$name; + } + + if ($alias !== '') { + if ($isFunc) { + $functions[strtolower($alias)] = $name; + } elseif ($isConst) { + $constants[$alias] = $name; + } else { + $classes[strtolower($alias)] = $name; + } + } + $name = $alias = ''; + $state = $token === ';' ? 'start' : 'use'; + break; + } + break; + case 'use-group': + switch ($token[0]) { + case T_NS_SEPARATOR: + $name .= $token[1]; + break; + case T_NAME_QUALIFIED: + $name .= $token[1]; + $pieces = explode('\\', $token[1]); + $alias = end($pieces); + break; + case T_STRING: + $name .= $token[1]; + $alias = $token[1]; + break; + case T_AS: + $lastState = 'use-group'; + $state = 'alias'; + break; + case ',': + case '}': + + if ($prefix === '' || $prefix[0] !== '\\') { + $prefix = '\\'.$prefix; + } + + if ($alias !== '') { + if ($isFunc) { + $functions[strtolower($alias)] = $prefix.$name; + } elseif ($isConst) { + $constants[$alias] = $prefix.$name; + } else { + $classes[strtolower($alias)] = $prefix.$name; + } + } + $name = $alias = ''; + $state = $token === '}' ? 'use' : 'use-group'; + break; + } + break; + case 'alias': + if ($token[0] === T_STRING) { + $alias = $token[1]; + $state = $lastState; + } + break; + case 'new': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + break 2; + case T_CLASS: + $state = 'structure'; + $structIgnore = true; + break; + default: + $state = 'start'; + } + break; + case 'invoke': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + break 2; + default: + $state = 'start'; + } + break; + case 'before_structure': + if ($token[0] == T_STRING) { + $structName = $token[1]; + $state = 'structure'; + } + break; + case 'structure': + switch ($token[0]) { + case '{': + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + $open++; + break; + case '}': + if (--$open == 0) { + if (! $structIgnore) { + $structures[] = [ + 'type' => $structType, + 'name' => $structName, + 'start' => $startLine, + 'end' => $endLine, + ]; + } + $structIgnore = false; + $state = 'start'; + } + break; + default: + if (is_array($token)) { + $endLine = $token[2]; + } + } + break; + } + } + + static::$classes[$key] = $classes; + static::$functions[$key] = $functions; + static::$constants[$key] = $constants; + static::$structures[$key] = $structures; + } + + /** + * Returns the namespace associated to the closure. + * + * @return string + */ + protected function getClosureNamespaceName() + { + $ns = $this->getNamespaceName(); + + // First class callables... + if ($this->getName() !== '{closure}' && empty($ns) && ! is_null($this->getClosureScopeClass())) { + $ns = $this->getClosureScopeClass()->getNamespaceName(); + } + + return $ns; + } + + /** + * Parse the given token. + * + * @param string $token + * @return array + */ + protected function parseNameQualified($token) + { + $pieces = explode('\\', $token); + + $id_start = array_shift($pieces); + + $id_start_ci = strtolower($id_start); + + $id_name = '\\'.implode('\\', $pieces); + + return [$id_start, $id_start_ci, $id_name]; + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/SelfReference.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/SelfReference.php new file mode 100644 index 0000000..5831950 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/Support/SelfReference.php @@ -0,0 +1,24 @@ +hash = $hash; + } +} diff --git a/php/libraries/composer/vendor/laravel/serializable-closure/src/UnsignedSerializableClosure.php b/php/libraries/composer/vendor/laravel/serializable-closure/src/UnsignedSerializableClosure.php new file mode 100644 index 0000000..1588e7c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/serializable-closure/src/UnsignedSerializableClosure.php @@ -0,0 +1,82 @@ +serializable = new Serializers\Native($closure); + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return call_user_func_array($this->serializable, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return $this->serializable->getClosure(); + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + return [ + 'serializable' => $this->serializable, + ]; + } + + /** + * Restore the closure after serialization. + * + * @param array $data + * @return void + */ + public function __unserialize($data) + { + $this->serializable = $data['serializable']; + } +} diff --git a/php/libraries/composer/vendor/laravel/tinker/LICENSE.md b/php/libraries/composer/vendor/laravel/tinker/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +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/php/libraries/composer/vendor/laravel/tinker/README.md b/php/libraries/composer/vendor/laravel/tinker/README.md new file mode 100644 index 0000000..40284ac --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/README.md @@ -0,0 +1,32 @@ +

Logo Laravel Tinker

+ +

+Build Status +Total Downloads +Latest Stable Version +License +

+ +## Introduction + +Laravel Tinker is a powerful REPL for the Laravel framework. + +## Official Documentation + +Documentation for Tinker can be found on the [Laravel website](https://laravel.com/docs/artisan#tinker). + +## Contributing + +Thank you for considering contributing to Tinker! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +Please review [our security policy](https://github.com/laravel/tinker/security/policy) on how to report security vulnerabilities. + +## License + +Laravel Tinker is open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/php/libraries/composer/vendor/laravel/tinker/composer.json b/php/libraries/composer/vendor/laravel/tinker/composer.json new file mode 100644 index 0000000..827dd1d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/composer.json @@ -0,0 +1,52 @@ +{ + "name": "laravel/tinker", + "description": "Powerful REPL for the Laravel framework.", + "keywords": ["tinker", "repl", "psysh", "laravel"], + "license": "MIT", + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^7.2.5|^8.0", + "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/contracts": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "psy/psysh": "^0.11.1|^0.12.0", + "symfony/var-dumper": "^4.3.4|^5.0|^6.0|^7.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.3|^1.4.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^8.5.8|^9.3.3" + }, + "suggest": { + "illuminate/database": "The Illuminate Database package (^6.0|^7.0|^8.0|^9.0|^10.0|^11.0)." + }, + "autoload": { + "psr-4": { + "Laravel\\Tinker\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Laravel\\Tinker\\Tests\\": "tests/", + "App\\": "tests/fixtures/app", + "One\\Two\\": "tests/fixtures/vendor/one/two" + } + }, + "extra": { + "laravel": { + "providers": [ + "Laravel\\Tinker\\TinkerServiceProvider" + ] + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/laravel/tinker/config/tinker.php b/php/libraries/composer/vendor/laravel/tinker/config/tinker.php new file mode 100644 index 0000000..c187942 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/config/tinker.php @@ -0,0 +1,50 @@ + [ + // App\Console\Commands\ExampleCommand::class, + ], + + /* + |-------------------------------------------------------------------------- + | Auto Aliased Classes + |-------------------------------------------------------------------------- + | + | Tinker will not automatically alias classes in your vendor namespaces + | but you may explicitly allow a subset of classes to get aliased by + | adding the names of each of those classes to the following list. + | + */ + + 'alias' => [ + // + ], + + /* + |-------------------------------------------------------------------------- + | Classes That Should Not Be Aliased + |-------------------------------------------------------------------------- + | + | Typically, Tinker automatically aliases classes as you require them in + | Tinker. However, you may wish to never alias certain classes, which + | you may accomplish by listing the classes in the following array. + | + */ + + 'dont_alias' => [ + 'App\Nova', + ], + +]; diff --git a/php/libraries/composer/vendor/laravel/tinker/src/ClassAliasAutoloader.php b/php/libraries/composer/vendor/laravel/tinker/src/ClassAliasAutoloader.php new file mode 100644 index 0000000..994d75c --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/src/ClassAliasAutoloader.php @@ -0,0 +1,163 @@ +shell = $shell; + $this->vendorPath = dirname(dirname($classMapPath)); + $this->includedAliases = collect($includedAliases); + $this->excludedAliases = collect($excludedAliases); + + $classes = require $classMapPath; + + foreach ($classes as $class => $path) { + if (! $this->isAliasable($class, $path)) { + continue; + } + + $name = class_basename($class); + + if (! isset($this->classes[$name])) { + $this->classes[$name] = $class; + } + } + } + + /** + * Find the closest class by name. + * + * @param string $class + * @return void + */ + public function aliasClass($class) + { + if (Str::contains($class, '\\')) { + return; + } + + $fullName = $this->classes[$class] ?? false; + + if ($fullName) { + $this->shell->writeStdout("[!] Aliasing '{$class}' to '{$fullName}' for this Tinker session.\n"); + + class_alias($fullName, $class); + } + } + + /** + * Unregister the alias loader instance. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister([$this, 'aliasClass']); + } + + /** + * Handle the destruction of the instance. + * + * @return void + */ + public function __destruct() + { + $this->unregister(); + } + + /** + * Whether a class may be aliased. + * + * @param string $class + * @param string $path + */ + public function isAliasable($class, $path) + { + if (! Str::contains($class, '\\')) { + return false; + } + + if (! $this->includedAliases->filter(function ($alias) use ($class) { + return Str::startsWith($class, $alias); + })->isEmpty()) { + return true; + } + + if (Str::startsWith($path, $this->vendorPath)) { + return false; + } + + if (! $this->excludedAliases->filter(function ($alias) use ($class) { + return Str::startsWith($class, $alias); + })->isEmpty()) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/laravel/tinker/src/Console/TinkerCommand.php b/php/libraries/composer/vendor/laravel/tinker/src/Console/TinkerCommand.php new file mode 100644 index 0000000..07ad30d --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/src/Console/TinkerCommand.php @@ -0,0 +1,170 @@ +getApplication()->setCatchExceptions(false); + + $config = Configuration::fromInput($this->input); + $config->setUpdateCheck(Checker::NEVER); + + $config->getPresenter()->addCasters( + $this->getCasters() + ); + + if ($this->option('execute')) { + $config->setRawOutput(true); + } + + $shell = new Shell($config); + $shell->addCommands($this->getCommands()); + $shell->setIncludes($this->argument('include')); + + $path = Env::get('COMPOSER_VENDOR_DIR', $this->getLaravel()->basePath().DIRECTORY_SEPARATOR.'vendor'); + + $path .= '/composer/autoload_classmap.php'; + + $config = $this->getLaravel()->make('config'); + + $loader = ClassAliasAutoloader::register( + $shell, $path, $config->get('tinker.alias', []), $config->get('tinker.dont_alias', []) + ); + + if ($code = $this->option('execute')) { + try { + $shell->setOutput($this->output); + $shell->execute($code); + } finally { + $loader->unregister(); + } + + return 0; + } + + try { + return $shell->run(); + } finally { + $loader->unregister(); + } + } + + /** + * Get artisan commands to pass through to PsySH. + * + * @return array + */ + protected function getCommands() + { + $commands = []; + + foreach ($this->getApplication()->all() as $name => $command) { + if (in_array($name, $this->commandWhitelist)) { + $commands[] = $command; + } + } + + $config = $this->getLaravel()->make('config'); + + foreach ($config->get('tinker.commands', []) as $command) { + $commands[] = $this->getApplication()->add( + $this->getLaravel()->make($command) + ); + } + + return $commands; + } + + /** + * Get an array of Laravel tailored casters. + * + * @return array + */ + protected function getCasters() + { + $casters = [ + 'Illuminate\Support\Collection' => 'Laravel\Tinker\TinkerCaster::castCollection', + 'Illuminate\Support\HtmlString' => 'Laravel\Tinker\TinkerCaster::castHtmlString', + 'Illuminate\Support\Stringable' => 'Laravel\Tinker\TinkerCaster::castStringable', + ]; + + if (class_exists('Illuminate\Database\Eloquent\Model')) { + $casters['Illuminate\Database\Eloquent\Model'] = 'Laravel\Tinker\TinkerCaster::castModel'; + } + + if (class_exists('Illuminate\Process\ProcessResult')) { + $casters['Illuminate\Process\ProcessResult'] = 'Laravel\Tinker\TinkerCaster::castProcessResult'; + } + + if (class_exists('Illuminate\Foundation\Application')) { + $casters['Illuminate\Foundation\Application'] = 'Laravel\Tinker\TinkerCaster::castApplication'; + } + + $config = $this->getLaravel()->make('config'); + + return array_merge($casters, (array) $config->get('tinker.casters', [])); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['include', InputArgument::IS_ARRAY, 'Include file(s) before starting tinker'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['execute', null, InputOption::VALUE_OPTIONAL, 'Execute the given code using Tinker'], + ]; + } +} diff --git a/php/libraries/composer/vendor/laravel/tinker/src/TinkerCaster.php b/php/libraries/composer/vendor/laravel/tinker/src/TinkerCaster.php new file mode 100644 index 0000000..be3544e --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/src/TinkerCaster.php @@ -0,0 +1,157 @@ +$property(); + + if (! is_null($val)) { + $results[Caster::PREFIX_VIRTUAL.$property] = $val; + } + } catch (Exception $e) { + // + } + } + + return $results; + } + + /** + * Get an array representing the properties of a collection. + * + * @param \Illuminate\Support\Collection $collection + * @return array + */ + public static function castCollection($collection) + { + return [ + Caster::PREFIX_VIRTUAL.'all' => $collection->all(), + ]; + } + + /** + * Get an array representing the properties of an html string. + * + * @param \Illuminate\Support\HtmlString $htmlString + * @return array + */ + public static function castHtmlString($htmlString) + { + return [ + Caster::PREFIX_VIRTUAL.'html' => $htmlString->toHtml(), + ]; + } + + /** + * Get an array representing the properties of a fluent string. + * + * @param \Illuminate\Support\Stringable $stringable + * @return array + */ + public static function castStringable($stringable) + { + return [ + Caster::PREFIX_VIRTUAL.'value' => (string) $stringable, + ]; + } + + /** + * Get an array representing the properties of a process result. + * + * @param \Illuminate\Process\ProcessResult $result + * @return array + */ + public static function castProcessResult($result) + { + return [ + Caster::PREFIX_VIRTUAL.'output' => $result->output(), + Caster::PREFIX_VIRTUAL.'errorOutput' => $result->errorOutput(), + Caster::PREFIX_VIRTUAL.'exitCode' => $result->exitCode(), + Caster::PREFIX_VIRTUAL.'successful' => $result->successful(), + ]; + } + + /** + * Get an array representing the properties of a model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return array + */ + public static function castModel($model) + { + $attributes = array_merge( + $model->getAttributes(), $model->getRelations() + ); + + $visible = array_flip( + $model->getVisible() ?: array_diff(array_keys($attributes), $model->getHidden()) + ); + + $hidden = array_flip($model->getHidden()); + + $appends = (function () { + return array_combine($this->appends, $this->appends); // @phpstan-ignore-line + })->bindTo($model, $model)(); + + foreach ($appends as $appended) { + $attributes[$appended] = $model->{$appended}; + } + + $results = []; + + foreach ($attributes as $key => $value) { + $prefix = ''; + + if (isset($visible[$key])) { + $prefix = Caster::PREFIX_VIRTUAL; + } + + if (isset($hidden[$key])) { + $prefix = Caster::PREFIX_PROTECTED; + } + + $results[$prefix.$key] = $value; + } + + return $results; + } +} diff --git a/php/libraries/composer/vendor/laravel/tinker/src/TinkerServiceProvider.php b/php/libraries/composer/vendor/laravel/tinker/src/TinkerServiceProvider.php new file mode 100644 index 0000000..0da82b8 --- /dev/null +++ b/php/libraries/composer/vendor/laravel/tinker/src/TinkerServiceProvider.php @@ -0,0 +1,54 @@ +app instanceof LaravelApplication && $this->app->runningInConsole()) { + $this->publishes([$source => $this->app->configPath('tinker.php')]); + } elseif ($this->app instanceof LumenApplication) { + $this->app->configure('tinker'); + } + + $this->mergeConfigFrom($source, 'tinker'); + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $this->app->singleton('command.tinker', function () { + return new TinkerCommand; + }); + + $this->commands(['command.tinker']); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['command.tinker']; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/.phpstorm.meta.php b/php/libraries/composer/vendor/league/commonmark/.phpstorm.meta.php new file mode 100644 index 0000000..ca1bec7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/.phpstorm.meta.php @@ -0,0 +1,104 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace PHPSTORM_META +{ + expectedArguments(\League\CommonMark\Util\HtmlElement::__construct(), 0, 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kdb', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr'); + + expectedArguments(\League\CommonMark\Extension\CommonMark\Node\Block\Heading::__construct(), 0, 1, 2, 3, 4, 5, 6); + expectedReturnValues(\League\CommonMark\Extension\CommonMark\Node\Block\Heading::getLevel(), 1, 2, 3, 4, 5, 6); + + registerArgumentsSet('league_commonmark_htmlblock_types', \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_1_CODE_CONTAINER, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_2_COMMENT, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_3, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_4, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_5_CDATA, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_6_BLOCK_ELEMENT, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_7_MISC_ELEMENT); + expectedArguments(\League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::__construct(), 0, argumentsSet('league_commonmark_htmlblock_types')); + expectedArguments(\League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::setType(), 0, argumentsSet('league_commonmark_htmlblock_types')); + expectedReturnValues(\League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::getType(), argumentsSet('league_commonmark_htmlblock_types')); + expectedArguments(\League\CommonMark\Util\RegexHelper::getHtmlBlockOpenRegex(), 0, argumentsSet('league_commonmark_htmlblock_types')); + expectedArguments(\League\CommonMark\Util\RegexHelper::getHtmlBlockCloseRegex(), 0, argumentsSet('league_commonmark_htmlblock_types')); + + registerArgumentsSet('league_commonmark_newline_types', \League\CommonMark\Node\Inline\Newline::HARDBREAK, \League\CommonMark\Node\Inline\Newline::SOFTBREAK); + expectedArguments(\League\CommonMark\Node\Inline\Newline::__construct(), 0, argumentsSet('league_commonmark_newline_types')); + expectedReturnValues(\League\CommonMark\Node\Inline\Newline::getType(), argumentsSet('league_commonmark_newline_types')); + + registerArgumentsSet('league_commonmark_options', + 'html_input', + 'allow_unsafe_links', + 'max_nesting_level', + 'renderer', + 'renderer/block_separator', + 'renderer/inner_separator', + 'renderer/soft_break', + 'commonmark', + 'commonmark/enable_em', + 'commonmark/enable_strong', + 'commonmark/use_asterisk', + 'commonmark/use_underscore', + 'commonmark/unordered_list_markers', + 'disallowed_raw_html', + 'disallowed_raw_html/disallowed_tags', + 'external_link', + 'external_link/html_class', + 'external_link/internal_hosts', + 'external_link/nofollow', + 'external_link/noopener', + 'external_link/noreferrer', + 'external_link/open_in_new_window', + 'footnote', + 'footnote/backref_class', + 'footnote/backref_symbol', + 'footnote/container_add_hr', + 'footnote/container_class', + 'footnote/ref_class', + 'footnote/ref_id_prefix', + 'footnote/footnote_class', + 'footnote/footnote_id_prefix', + 'heading_permalink', + 'heading_permalink/apply_id_to_heading', + 'heading_permalink/heading_class', + 'heading_permalink/html_class', + 'heading_permalink/fragment_prefix', + 'heading_permalink/id_prefix', + 'heading_permalink/inner_contents', + 'heading_permalink/insert', + 'heading_permalink/max_heading_level', + 'heading_permalink/min_heading_level', + 'heading_permalink/symbol', + 'heading_permalink/title', + 'mentions', + 'smartpunct/double_quote_closer', + 'smartpunct/double_quote_opener', + 'smartpunct/single_quote_closer', + 'smartpunct/single_quote_opener', + 'slug_normalizer', + 'slug_normalizer/instance', + 'slug_normalizer/max_length', + 'slug_normalizer/unique', + 'table', + 'table/wrap', + 'table/wrap/attributes', + 'table/wrap/enabled', + 'table/wrap/tag', + 'table/alignment_attributes', + 'table/alignment_attributes/left', + 'table/alignment_attributes/center', + 'table/alignment_attributes/right', + 'table_of_contents', + 'table_of_contents/html_class', + 'table_of_contents/max_heading_level', + 'table_of_contents/min_heading_level', + 'table_of_contents/normalize', + 'table_of_contents/placeholder', + 'table_of_contents/position', + 'table_of_contents/style', + ); + expectedArguments(\League\Config\ConfigurationInterface::get(), 0, argumentsSet('league_commonmark_options')); + expectedArguments(\League\Config\ConfigurationInterface::exists(), 0, argumentsSet('league_commonmark_options')); + expectedArguments(\League\Config\MutableConfigurationInterface::set(), 0, argumentsSet('league_commonmark_options')); +} diff --git a/php/libraries/composer/vendor/league/commonmark/CHANGELOG.md b/php/libraries/composer/vendor/league/commonmark/CHANGELOG.md new file mode 100644 index 0000000..481fb22 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/CHANGELOG.md @@ -0,0 +1,603 @@ +# Change Log +All notable changes to this project will be documented in this file. +Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) principles. + +**Upgrading from 1.x?** See for additional information. + +## [Unreleased][unreleased] + +## [2.4.2] - 2024-02-02 + +### Fixed + +- Fixed declaration parser being too strict +- `FencedCodeRenderer`: don't add `language-` to class if already prefixed + +## [2.4.1] - 2023-08-30 + +### Fixed + +- Fixed `ExternalLinkProcessor` not fully disabling the `rel` attribute when configured to do so (#992) + +## [2.4.0] - 2023-03-24 + +### Added + +- Added generic `CommonMarkException` marker interface for all exceptions thrown by the library +- Added several new specific exception types implementing that marker interface: + - `AlreadyInitializedException` + - `InvalidArgumentException` + - `IOException` + - `LogicException` + - `MissingDependencyException` + - `NoMatchingRendererException` + - `ParserLogicException` +- Added more configuration options to the Heading Permalinks extension (#939): + - `heading_permalink/apply_id_to_heading` - When `true`, the `id` attribute will be applied to the heading element itself instead of the `` tag + - `heading_permalink/heading_class` - class to apply to the heading element + - `heading_permalink/insert` - now accepts `none` to prevent the creation of the `` link +- Added new `table/alignment_attributes` configuration option to control how table cell alignment is rendered (#959) + +### Changed + +- Change several thrown exceptions from `RuntimeException` to `LogicException` (or something extending it), including: + - `CallbackGenerator`s that fail to set a URL or return an expected value + - `MarkdownParser` when deactivating the last block parser or attempting to get an active block parser when they've all been closed + - Adding items to an already-initialized `Environment` + - Rendering a `Node` when no renderer has been registered for it +- `HeadingPermalinkProcessor` now throws `InvalidConfigurationException` instead of `RuntimeException` when invalid config values are given. +- `HtmlElement::setAttribute()` no longer requires the second parameter for boolean attributes +- Several small micro-optimizations +- Changed Strikethrough to only allow 1 or 2 tildes per the updated GFM spec + +### Fixed + +- Fixed inaccurate `@throws` docblocks throughout the codebase, including `ConverterInterface`, `MarkdownConverter`, and `MarkdownConverterInterface`. + - These previously suggested that only `\RuntimeException`s were thrown, which was inaccurate as `\LogicException`s were also possible. + +## [2.3.9] - 2023-02-15 + +### Fixed + +- Fixed autolink extension not detecting some URIs with underscores (#956) + +## [2.3.8] - 2022-12-10 + +### Fixed + +- Fixed parsing issues when `mb_internal_encoding()` is set to something other than `UTF-8` (#951) + +## [2.3.7] - 2022-11-03 + +### Fixed + +- Fixed `TaskListItemMarkerRenderer` not including HTML attributes set on the node by other extensions (#947) + +## [2.3.6] - 2022-10-30 + +### Fixed + +- Fixed unquoted attribute parsing when closing curly brace is followed by certain characters (like a `.`) (#943) + +## [2.3.5] - 2022-07-29 + +### Fixed + +- Fixed error using `InlineParserEngine` when no inline parsers are registered in the `Environment` (#908) + +## [2.3.4] - 2022-07-17 + +### Changed + +- Made a number of small tweaks to the embed extension's parsing behavior to fix #898: + - Changed `EmbedStartParser` to always capture embed-like lines in container blocks, regardless of parent block type + - Changed `EmbedProcessor` to also remove `Embed` blocks that aren't direct children of the `Document` + - Increased the priority of `EmbedProcessor` to `1010` + +### Fixed + +- Fixed `EmbedExtension` not parsing embeds following a list block (#898) + +## [2.3.3] - 2022-06-07 + +### Fixed + +- Fixed `DomainFilteringAdapter` not reindexing the embed list (#884, #885) + +## [2.3.2] - 2022-06-03 + +### Fixed + +- Fixed FootnoteExtension stripping extra characters from tab-indented footnotes (#881) + +## [2.2.5] - 2022-06-03 + +### Fixed + +- Fixed FootnoteExtension stripping extra characters from tab-indented footnotes (#881) + +## [2.3.1] - 2022-05-14 + +### Fixed + +- Fixed AutolinkExtension not ignoring trailing strikethrough syntax (#867) + +## [2.2.4] - 2022-05-14 + +### Fixed + +- Fixed AutolinkExtension not ignoring trailing strikethrough syntax (#867) + +## [2.3.0] - 2022-04-07 + +### Added + +- Added new `EmbedExtension` (#805) +- Added `DocumentRendererInterface` as a replacement for the now-deprecated `MarkdownRendererInterface` + +### Deprecated + +- Deprecated `MarkdownRendererInterface`; use `DocumentRendererInterface` instead + +## [2.2.3] - 2022-02-26 + +### Fixed + +- Fixed front matter parsing with Windows line endings (#821) + +## [2.1.3] - 2022-02-26 + +### Fixed + +- Fixed front matter parsing with Windows line endings (#821) + +## [2.0.4] - 2022-02-26 + +### Fixed + +- Fixed front matter parsing with Windows line endings (#821) + +## [2.2.2] - 2022-02-13 + +### Fixed + +- Fixed double-escaping of image alt text (#806, #810) +- Fixed Psalm typehints for event class names + +## [2.2.1] - 2022-01-25 + +### Fixed + + - Fixed `symfony/deprecation-contracts` constraint + +### Removed + + - Removed deprecation trigger from `MarkdownConverterInterface` to reduce noise + +## [2.2.0] - 2022-01-22 + +### Added + + - Added new `ConverterInterface` + - Added new `MarkdownToXmlConverter` class + - Added new `HtmlDecorator` class which can wrap existing renderers with additional HTML tags + - Added new `table/wrap` config to apply an optional wrapping/container element around a table (#780) + +### Changed + + - `HtmlElement` contents can now consist of any `Stringable`, not just `HtmlElement` and `string` + +### Deprecated + + - Deprecated `MarkdownConverterInterface` and its `convertToHtml()` method; use `ConverterInterface` and `convert()` instead + +## [2.1.2] - 2022-02-13 + +### Fixed + +- Fixed double-escaping of image alt text (#806, #810) +- Fixed Psalm typehints for event class names + +## [2.1.1] - 2022-01-02 + +### Added + + - Added missing return type to `Environment::dispatch()` to fix deprecation warning (#778) + +## [2.1.0] - 2021-12-05 + +### Added + +- Added support for ext-yaml in FrontMatterExtension (#715) +- Added support for symfony/yaml v6.0 in FrontMatterExtension (#739) +- Added new `heading_permalink/aria_hidden` config option (#741) + +### Fixed + + - Fixed PHP 8.1 deprecation warning (#759, #762) + +## [2.0.3] - 2022-02-13 + +### Fixed + +- Fixed double-escaping of image alt text (#806, #810) +- Fixed Psalm typehints for event class names + +## [2.0.2] - 2021-08-14 + +### Changed + +- Bumped minimum version of league/config to support PHP 8.1 + +### Fixed + +- Fixed ability to register block parsers that identify lines starting with letters (#706) + +## [2.0.1] - 2021-07-31 + +### Fixed + +- Fixed nested autolinks (#689) +- Fixed description lists being parsed incorrectly (#692) +- Fixed Table of Contents not respecting Heading Permalink prefixes (#690) + +## [2.0.0] - 2021-07-24 + +No changes were introduced since the previous RC2 release. +See all entries below for a list of changes between 1.x and 2.0. + +## [2.0.0-rc2] - 2021-07-17 + +### Fixed + +- Fixed Mentions inside of links creating nested links against the spec's rules (#688) + +## [2.0.0-rc1] - 2021-07-10 + +No changes were introduced since the previous release. + +## [2.0.0-beta3] - 2021-07-03 + +### Changed + + - Any leading UTF-8 BOM will be stripped from the input + - The `getEnvironment()` method of `CommonMarkConverter` and `GithubFlavoredMarkdownConverter` will always return the concrete, configurable `Environment` for upgrading convenience + - Optimized AST iteration + - Lots of small micro-optimizations + +## [2.0.0-beta2] - 2021-06-27 + +### Added + +- Added new `Node::iterator()` method and `NodeIterator` class for faster AST iteration (#683, #684) + +### Changed + +- Made compatible with CommonMark spec 0.30.0 +- Optimized link label parsing +- Optimized AST iteration for a 50% performance boost in some event listeners (#683, #684) + +### Fixed + +- Fixed processing instructions with EOLs +- Fixed case-insensitive matching for HTML tag types +- Fixed type 7 HTML blocks incorrectly interrupting lazy paragraphs +- Fixed newlines in reference labels not collapsing into spaces +- Fixed link label normalization with escaped newlines +- Fixed unnecessary AST iteration when no default attributes are configured + +## [2.0.0-beta1] - 2021-06-20 + +### Added + + - **Added three new extensions:** + - `FrontMatterExtension` ([see documentation](https://commonmark.thephpleague.com/extensions/front-matter/)) + - `DescriptionListExtension` ([see documentation](https://commonmark.thephpleague.com/extensions/description-lists/)) + - `DefaultAttributesExtension` ([see documentation](https://commonmark.thephpleague.com/extensions/default-attributes/)) + - **Added new `XmlRenderer` to simplify AST debugging** ([see documentation](https://commonmark.thephpleague.com/xml/)) (#431) + - **Added the ability to configure disallowed raw HTML tags** (#507) + - **Added the ability for Mentions to use multiple characters for their symbol** (#514, #550) + - **Added the ability to delegate event dispatching to PSR-14 compliant event dispatcher libraries** + - **Added new configuration options:** + - Added `heading_permalink/min_heading_level` and `heading_permalink/max_heading_level` options to control which headings get permalinks (#519) + - Added `heading_permalink/fragment_prefix` to allow customizing the URL fragment prefix (#602) + - Added `footnote/backref_symbol` option for customizing backreference link appearance (#522) + - Added `slug_normalizer/max_length` option to control the maximum length of generated URL slugs + - Added `slug_normalizer/unique` option to control whether unique slugs should be generated per-document or per-environment + - **Added purity markers throughout the codebase** (verified with Psalm) + - Added `Query` class to simplify Node traversal when looking to take action on certain Nodes + - Added new `HtmlFilter` and `StringContainerHelper` utility classes + - Added new `AbstractBlockContinueParser` class to simplify the creation of custom block parsers + - Added several new classes and interfaces: + - `BlockContinue` + - `BlockContinueParserInterface` + - `BlockContinueParserWithInlinesInterface` + - `BlockStart` + - `BlockStartParserInterface` + - `ChildNodeRendererInterface` + - `ConfigurableExtensionInterface` + - `CursorState` + - `DashParser` (extracted from `PunctuationParser`) + - `DelimiterParser` + - `DocumentBlockParser` + - `DocumentPreRenderEvent` + - `DocumentRenderedEvent` + - `EllipsesParser` (extracted from `PunctuationParser`) + - `ExpressionInterface` + - `FallbackNodeXmlRenderer` + - `InlineParserEngineInterface` + - `InlineParserMatch` + - `MarkdownParserState` + - `MarkdownParserStateInterface` + - `MarkdownRendererInterface` + - `Query` + - `RawMarkupContainerInterface` + - `ReferenceableInterface` + - `RenderedContent` + - `RenderedContentInterface` + - `ReplaceUnpairedQuotesListener` + - `SpecReader` + - `TableOfContentsRenderer` + - `UniqueSlugNormalizer` + - `UniqueSlugNormalizerInterface` + - `XmlRenderer` + - `XmlNodeRendererInterface` + - Added several new methods: + - `Cursor::getCurrentCharacter()` + - `Environment::createDefaultConfiguration()` + - `Environment::setEventDispatcher()` + - `EnvironmentInterface::getExtensions()` + - `EnvironmentInterface::getInlineParsers()` + - `EnvironmentInterface::getSlugNormalizer()` + - `FencedCode::setInfo()` + - `Heading::setLevel()` + - `HtmlRenderer::renderDocument()` + - `InlineParserContext::getFullMatch()` + - `InlineParserContext::getFullMatchLength()` + - `InlineParserContext::getMatches()` + - `InlineParserContext::getSubMatches()` + - `LinkParserHelper::parsePartialLinkLabel()` + - `LinkParserHelper::parsePartialLinkTitle()` + - `Node::assertInstanceOf()` + - `RegexHelper::isLetter()` + - `StringContainerInterface::setLiteral()` + - `TableCell::getType()` + - `TableCell::setType()` + - `TableCell::getAlign()` + - `TableCell::setAlign()` + +### Changed + + - **Changed the converter return type** + - `CommonMarkConverter::convertToHtml()` now returns an instance of `RenderedContentInterface`. This can be cast to a string for backward compatibility with 1.x. + - **Table of Contents items are no longer wrapped with `

` tags** (#613) + - **Heading Permalinks now link to element IDs instead of using `name` attributes** (#602) + - **Heading Permalink IDs and URL fragments now have a `content` prefix by default** (#602) + - **Changes to configuration options:** + - `enable_em` has been renamed to `commonmark/enable_em` + - `enable_strong` has been renamed to `commonmark/enable_strong` + - `use_asterisk` has been renamed to `commonmark/use_asterisk` + - `use_underscore` has been renamed to `commonmark/use_underscore` + - `unordered_list_markers` has been renamed to `commonmark/unordered_list_markers` + - `mentions/*/symbol` has been renamed to `mentions/*/prefix` + - `mentions/*/regex` has been renamed to `mentions/*/pattern` and requires partial regular expressions (without delimiters or flags) + - `max_nesting_level` now defaults to `PHP_INT_MAX` and no longer supports floats + - `heading_permalink/slug_normalizer` has been renamed to `slug_normalizer/instance` + - **Event dispatching is now fully PSR-14 compliant** + - **Moved and renamed several classes** - [see the full list here](https://commonmark.thephpleague.com/2.0/upgrading/#classesnamespaces-renamed) + - The `HeadingPermalinkExtension` and `FootnoteExtension` were modified to ensure they never produce a slug which conflicts with slugs created by the other extension + - `SlugNormalizer::normalizer()` now supports optional prefixes and max length options passed in via the `$context` argument + - The `AbstractBlock::$data` and `AbstractInline::$data` arrays were replaced with a `Data` array-like object on the base `Node` class + - **Implemented a new approach to block parsing.** This was a massive change, so here are the highlights: + - Functionality previously found in block parsers and node elements has moved to block parser factories and block parsers, respectively ([more details](https://commonmark.thephpleague.com/2.0/upgrading/#new-block-parsing-approach)) + - `ConfigurableEnvironmentInterface::addBlockParser()` is now `EnvironmentBuilderInterface::addBlockParserFactory()` + - `ReferenceParser` was re-implemented and works completely different than before + - The paragraph parser no longer needs to be added manually to the environment + - **Implemented a new approach to inline parsing** where parsers can now specify longer strings or regular expressions they want to parse (instead of just single characters): + - `InlineParserInterface::getCharacters()` is now `getMatchDefinition()` and returns an instance of `InlineParserMatch` + - `InlineParserContext::__construct()` now requires the contents to be provided as a `Cursor` instead of a `string` + - **Implemented delimiter parsing as a special type of inline parser** (via the new `DelimiterParser` class) + - **Changed block and inline rendering to use common methods and interfaces** + - `BlockRendererInterface` and `InlineRendererInterface` were replaced by `NodeRendererInterface` with slightly different parameters. All core renderers now implement this interface. + - `ConfigurableEnvironmentInterface::addBlockRenderer()` and `addInlineRenderer()` were combined into `EnvironmentBuilderInterface::addRenderer()` + - `EnvironmentInterface::getBlockRenderersForClass()` and `getInlineRenderersForClass()` are now just `getRenderersForClass()` + - **Completely refactored the Configuration implementation** + - All configuration-specific classes have been moved into a new `league/config` package with a new namespace + - `Configuration` objects must now be configured with a schema and all options must match that schema - arbitrary keys are no longer permitted + - `Configuration::__construct()` no longer accepts the default configuration values - use `Configuration::merge()` instead + - `ConfigurationInterface` now only contains a `get(string $key)`; this method no longer allows arbitrary default values to be returned if the option is missing + - `ConfigurableEnvironmentInterface` was renamed to `EnvironmentBuilderInterface` + - `ExtensionInterface::register()` now requires an `EnvironmentBuilderInterface` param instead of `ConfigurableEnvironmentInterface` + - **Added missing return types to virtually every class and interface method** + - Re-implemented the GFM Autolink extension using the new inline parser approach instead of document processors + - `EmailAutolinkProcessor` is now `EmailAutolinkParser` + - `UrlAutolinkProcessor` is now `UrlAutolinkParser` + - `HtmlElement` can now properly handle array (i.e. `class`) and boolean (i.e. `checked`) attribute values + - `HtmlElement` automatically flattens any attributes with array values into space-separated strings, removing duplicate entries + - Combined separate classes/interfaces into one: + - `DisallowedRawHtmlRenderer` replaces `DisallowedRawHtmlBlockRenderer` and `DisallowedRawHtmlInlineRenderer` + - `NodeRendererInterface` replaces `BlockRendererInterface` and `InlineRendererInterface` + - Renamed the following methods: + - `Environment` and `ConfigurableEnvironmentInterface`: + - `addBlockParser()` is now `addBlockStartParser()` + - `ReferenceMap` and `ReferenceMapInterface`: + - `addReference()` is now `add()` + - `getReference()` is now `get()` + - `listReferences()` is now `getIterator()` + - Various node (block/inline) classes: + - `getContent()` is now `getLiteral()` + - `setContent()` is now `setLiteral()` + - Moved and renamed the following constants: + - `EnvironmentInterface::HTML_INPUT_ALLOW` is now `HtmlFilter::ALLOW` + - `EnvironmentInterface::HTML_INPUT_ESCAPE` is now `HtmlFilter::ESCAPE` + - `EnvironmentInterface::HTML_INPUT_STRIP` is now `HtmlFilter::STRIP` + - `TableCell::TYPE_HEAD` is now `TableCell::TYPE_HEADER` + - `TableCell::TYPE_BODY` is now `TableCell::TYPE_DATA` + - Changed the visibility of the following properties: + - `AttributesInline::$attributes` is now `private` + - `AttributesInline::$block` is now `private` + - `TableCell::$align` is now `private` + - `TableCell::$type` is now `private` + - `TableSection::$type` is now `private` + - Several methods which previously returned `$this` now return `void` + - `Delimiter::setPrevious()` + - `Node::replaceChildren()` + - `Context::setTip()` + - `Context::setContainer()` + - `Context::setBlocksParsed()` + - `AbstractStringContainer::setContent()` + - `AbstractWebResource::setUrl()` + - Several classes are now marked `final`: + - `ArrayCollection` + - `Emphasis` + - `FencedCode` + - `Heading` + - `HtmlBlock` + - `HtmlElement` + - `HtmlInline` + - `IndentedCode` + - `Newline` + - `Strikethrough` + - `Strong` + - `Text` + - `Heading` nodes no longer directly contain a copy of their inner text + - `StringContainerInterface` can now be used for inlines, not just blocks + - `ArrayCollection` only supports integer keys + - `HtmlElement` now implements `Stringable` + - `Cursor::saveState()` and `Cursor::restoreState()` now use `CursorState` objects instead of arrays + - `NodeWalker::next()` now enters, traverses any children, and leaves all elements which may have children (basically all blocks plus any inlines with children). Previously, it only did this for elements explicitly marked as "containers". + - `InvalidOptionException` was removed + - Anything with a `getReference(): ReferenceInterface` method now implements `ReferencableInterface` + - The `SmartPunct` extension now replaces all unpaired `Quote` elements with `Text` elements towards the end of parsing, making the `QuoteRenderer` unnecessary + - Several changes made to the Footnote extension: + - Footnote identifiers can no longer contain spaces + - Anonymous footnotes can now span subsequent lines + - Footnotes can now contain multiple lines of content, including sub-blocks, by indenting them + - Footnote event listeners now have numbered priorities (but still execute in the same order) + - Footnotes must now be separated from previous content by a blank line + - The line numbers (keys) returned via `MarkdownInput::getLines()` now start at 1 instead of 0 + - `DelimiterProcessorCollectionInterface` now extends `Countable` + - `RegexHelper::PARTIAL_` constants must always be used in case-insensitive contexts + - `HeadingPermalinkProcessor` no longer accepts text normalizers via the constructor - these must be provided via configuration instead + - Blocks which can't contain inlines will no longer be asked to render inlines + - `AnonymousFootnoteRefParser` and `HeadingPermalinkProcessor` now implement `EnvironmentAwareInterface` instead of `ConfigurationAwareInterface` + - The second argument to `TextNormalizerInterface::normalize()` must now be an array + - The `title` attribute for `Link` and `Image` nodes is now stored using a dedicated property instead of stashing it in `$data` + - `ListData::$delimiter` now returns either `ListBlock::DELIM_PERIOD` or `ListBlock::DELIM_PAREN` instead of the literal delimiter + +### Fixed + + - **Fixed parsing of footnotes without content** + - **Fixed rendering of orphaned footnotes and footnote refs** + - **Fixed some URL autolinks breaking too early** (#492) + - Fixed `AbstractStringContainer` not actually being `abstract` + +### Removed + + - **Removed support for PHP 7.1, 7.2, and 7.3** (#625, #671) + - **Removed all previously-deprecated functionality:** + - Removed the ability to pass custom `Environment` instances into the `CommonMarkConverter` and `GithubFlavoredMarkdownConverter` constructors + - Removed the `Converter` class and `ConverterInterface` + - Removed the `bin/commonmark` script + - Removed the `Html5Entities` utility class + - Removed the `InlineMentionParser` (use `MentionParser` instead) + - Removed `DefaultSlugGenerator` and `SlugGeneratorInterface` from the `Extension/HeadingPermalink/Slug` sub-namespace (use the new ones under `./SlugGenerator` instead) + - Removed the following `ArrayCollection` methods: + - `add()` + - `set()` + - `get()` + - `remove()` + - `isEmpty()` + - `contains()` + - `indexOf()` + - `containsKey()` + - `replaceWith()` + - `removeGaps()` + - Removed the `ConfigurableEnvironmentInterface::setConfig()` method + - Removed the `ListBlock::TYPE_UNORDERED` constant + - Removed the `CommonMarkConverter::VERSION` constant + - Removed the `HeadingPermalinkRenderer::DEFAULT_INNER_CONTENTS` constant + - Removed the `heading_permalink/inner_contents` configuration option + - **Removed now-unused classes:** + - `AbstractStringContainerBlock` + - `BlockRendererInterface` + - `Context` + - `ContextInterface` + - `Converter` + - `ConverterInterface` + - `InlineRendererInterface` + - `PunctuationParser` (was split into two classes: `DashParser` and `EllipsesParser`) + - `QuoteRenderer` + - `UnmatchedBlockCloser` + - Removed the following methods, properties, and constants: + - `AbstractBlock::$open` + - `AbstractBlock::$lastLineBlank` + - `AbstractBlock::isContainer()` + - `AbstractBlock::canContain()` + - `AbstractBlock::isCode()` + - `AbstractBlock::matchesNextLine()` + - `AbstractBlock::endsWithBlankLine()` + - `AbstractBlock::setLastLineBlank()` + - `AbstractBlock::shouldLastLineBeBlank()` + - `AbstractBlock::isOpen()` + - `AbstractBlock::finalize()` + - `AbstractBlock::getData()` + - `AbstractInline::getData()` + - `ConfigurableEnvironmentInterface::addBlockParser()` + - `ConfigurableEnvironmentInterface::mergeConfig()` + - `Delimiter::setCanClose()` + - `EnvironmentInterface::getConfig()` + - `EnvironmentInterface::getInlineParsersForCharacter()` + - `EnvironmentInterface::getInlineParserCharacterRegex()` + - `HtmlRenderer::renderBlock()` + - `HtmlRenderer::renderBlocks()` + - `HtmlRenderer::renderInline()` + - `HtmlRenderer::renderInlines()` + - `Node::isContainer()` + - `RegexHelper::matchAll()` (use the new `matchFirst()` method instead) + - `RegexHelper::REGEX_WHITESPACE` + - Removed the second `$contents` argument from the `Heading` constructor + +### Deprecated + +**The following things have been deprecated and will not be supported in v3.0:** + + - `Environment::mergeConfig()` (set configuration before instantiation instead) + - `Environment::createCommonMarkEnvironment()` and `Environment::createGFMEnvironment()` + - Alternative 1: Use `CommonMarkConverter` or `GithubFlavoredMarkdownConverter` if you don't need to customize the environment + - Alternative 2: Instantiate a new `Environment` and add the necessary extensions yourself + +[unreleased]: https://github.com/thephpleague/commonmark/compare/2.4.2...main +[2.4.2]: https://github.com/thephpleague/commonmark/compare/2.4.1...2.4.2 +[2.4.1]: https://github.com/thephpleague/commonmark/compare/2.4.0...2.4.1 +[2.4.0]: https://github.com/thephpleague/commonmark/compare/2.3.9...2.4.0 +[2.3.9]: https://github.com/thephpleague/commonmark/compare/2.3.8...2.3.9 +[2.3.8]: https://github.com/thephpleague/commonmark/compare/2.3.7...2.3.8 +[2.3.7]: https://github.com/thephpleague/commonmark/compare/2.3.6...2.3.7 +[2.3.6]: https://github.com/thephpleague/commonmark/compare/2.3.5...2.3.6 +[2.3.5]: https://github.com/thephpleague/commonmark/compare/2.3.4...2.3.5 +[2.3.4]: https://github.com/thephpleague/commonmark/compare/2.3.3...2.3.4 +[2.3.3]: https://github.com/thephpleague/commonmark/compare/2.3.2...2.3.3 +[2.3.2]: https://github.com/thephpleague/commonmark/compare/2.3.2...main +[2.3.1]: https://github.com/thephpleague/commonmark/compare/2.3.0...2.3.1 +[2.3.0]: https://github.com/thephpleague/commonmark/compare/2.2.3...2.3.0 +[2.2.5]: https://github.com/thephpleague/commonmark/compare/2.2.4...2.2.5 +[2.2.4]: https://github.com/thephpleague/commonmark/compare/2.2.3...2.2.4 +[2.2.3]: https://github.com/thephpleague/commonmark/compare/2.2.2...2.2.3 +[2.2.2]: https://github.com/thephpleague/commonmark/compare/2.2.1...2.2.2 +[2.2.1]: https://github.com/thephpleague/commonmark/compare/2.2.0...2.2.1 +[2.2.0]: https://github.com/thephpleague/commonmark/compare/2.1.1...2.2.0 +[2.1.3]: https://github.com/thephpleague/commonmark/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/thephpleague/commonmark/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/thephpleague/commonmark/compare/2.0.2...2.1.1 +[2.1.0]: https://github.com/thephpleague/commonmark/compare/2.0.2...2.1.0 +[2.0.4]: https://github.com/thephpleague/commonmark/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/thephpleague/commonmark/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/thephpleague/commonmark/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/thephpleague/commonmark/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/thephpleague/commonmark/compare/2.0.0-rc2...2.0.0 +[2.0.0-rc2]: https://github.com/thephpleague/commonmark/compare/2.0.0-rc1...2.0.0-rc2 +[2.0.0-rc1]: https://github.com/thephpleague/commonmark/compare/2.0.0-beta3...2.0.0-rc1 +[2.0.0-beta3]: https://github.com/thephpleague/commonmark/compare/2.0.0-beta2...2.0.0-beta3 +[2.0.0-beta2]: https://github.com/thephpleague/commonmark/compare/2.0.0-beta1...2.0.0-beta2 +[2.0.0-beta1]: https://github.com/thephpleague/commonmark/compare/1.6...2.0.0-beta1 diff --git a/php/libraries/composer/vendor/league/commonmark/LICENSE b/php/libraries/composer/vendor/league/commonmark/LICENSE new file mode 100644 index 0000000..5f04fad --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2014-2022, Colin O'Dell. All rights reserved. Some code based on commonmark.js (copyright 2014-2018, John MacFarlane) and commonmark-java (copyright 2015-2016, Atlassian Pty Ltd) + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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/php/libraries/composer/vendor/league/commonmark/README.md b/php/libraries/composer/vendor/league/commonmark/README.md new file mode 100644 index 0000000..36a337b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/README.md @@ -0,0 +1,221 @@ +# league/commonmark + +[![Latest Version](https://img.shields.io/packagist/v/league/commonmark.svg?style=flat-square)](https://packagist.org/packages/league/commonmark) +[![Total Downloads](https://img.shields.io/packagist/dt/league/commonmark.svg?style=flat-square)](https://packagist.org/packages/league/commonmark) +[![Software License](https://img.shields.io/badge/License-BSD--3-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/github/actions/workflow/status/thephpleague/commonmark/tests.yml?branch=main&style=flat-square)](https://github.com/thephpleague/commonmark/actions?query=workflow%3ATests+branch%3Amain) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/commonmark.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/commonmark/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/commonmark.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/commonmark) +[![Psalm Type Coverage](https://shepherd.dev/github/thephpleague/commonmark/coverage.svg)](https://shepherd.dev/github/thephpleague/commonmark) +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/126/badge)](https://bestpractices.coreinfrastructure.org/projects/126) +[![Sponsor development of this project](https://img.shields.io/badge/sponsor%20this%20package-%E2%9D%A4-ff69b4.svg?style=flat-square)](https://www.colinodell.com/sponsor) + +![league/commonmark](commonmark-banner.png) + +**league/commonmark** is a highly-extensible PHP Markdown parser created by [Colin O'Dell][@colinodell] which supports the full [CommonMark] spec and [GitHub-Flavored Markdown]. It is based on the [CommonMark JS reference implementation][commonmark.js] by [John MacFarlane] \([@jgm]\). + +## 📦 Installation & Basic Usage + +This project requires PHP 7.4 or higher with the `mbstring` extension. To install it via [Composer] simply run: + +``` bash +$ composer require league/commonmark +``` + +The `CommonMarkConverter` class provides a simple wrapper for converting CommonMark to HTML: + +```php +use League\CommonMark\CommonMarkConverter; + +$converter = new CommonMarkConverter([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +echo $converter->convert('# Hello World!'); + +//

Hello World!

+``` + +Or if you want GitHub-Flavored Markdown, use the `GithubFlavoredMarkdownConverter` class instead: + +```php +use League\CommonMark\GithubFlavoredMarkdownConverter; + +$converter = new GithubFlavoredMarkdownConverter([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +echo $converter->convert('# Hello World!'); + +//

Hello World!

+``` + +Please note that only UTF-8 and ASCII encodings are supported. If your Markdown uses a different encoding please convert it to UTF-8 before running it through this library. + +🔒 If you will be parsing untrusted input from users, please consider setting the `html_input` and `allow_unsafe_links` options per the example above. See for more details. If you also do choose to allow raw HTML input from untrusted users, consider using a library (like [HTML Purifier](https://github.com/ezyang/htmlpurifier)) to provide additional HTML filtering. + +## 📓 Documentation + +Full documentation on advanced usage, configuration, and customization can be found at [commonmark.thephpleague.com][docs]. + +## ⏫ Upgrading + +Information on how to upgrade to newer versions of this library can be found at . + +## 💻 GitHub-Flavored Markdown + +The `GithubFlavoredMarkdownConverter` shown earlier is a drop-in replacement for the `CommonMarkConverter` which adds additional features found in the GFM spec: + + - Autolinks + - Disallowed raw HTML + - Strikethrough + - Tables + - Task Lists + +See the [Extensions documentation](https://commonmark.thephpleague.com/customization/extensions/) for more details on how to include only certain GFM features if you don't want them all. + +## 🗃️ Related Packages + +### Integrations + +- [CakePHP 3](https://github.com/gourmet/common-mark) +- [Drupal](https://www.drupal.org/project/markdown) +- [Laravel 4+](https://github.com/GrahamCampbell/Laravel-Markdown) +- [Sculpin](https://github.com/bcremer/sculpin-commonmark-bundle) +- [Symfony 2 & 3](https://github.com/webuni/commonmark-bundle) +- [Symfony 4](https://github.com/avensome/commonmark-bundle) +- [Twig Markdown extension](https://github.com/twigphp/markdown-extension) +- [Twig filter and tag](https://github.com/aptoma/twig-markdown) +- [Laravel CommonMark Blog](https://github.com/spekulatius/laravel-commonmark-blog) + +### Included Extensions + +See [our extension documentation](https://commonmark.thephpleague.com/extensions/overview) for a full list of extensions bundled with this library. + +### Community Extensions + +Custom parsers/renderers can be bundled into extensions which extend CommonMark. Here are some that you may find interesting: + + - [Emoji extension](https://github.com/ElGigi/CommonMarkEmoji) - UTF-8 emoji extension with Github tag. + - [Sup Sub extensions](https://github.com/OWS/commonmark-sup-sub-extensions) - Adds support of superscript and subscript (`` and `` HTML tags) + - [YouTube iframe extension](https://github.com/zoonru/commonmark-ext-youtube-iframe) - Replaces youtube link with iframe. + - [Lazy Image extension](https://github.com/simonvomeyser/commonmark-ext-lazy-image) - Adds various options for lazy loading of images. + - [Marker Extension](https://github.com/noah1400/commonmark-marker-extension) - Adds support of highlighted text (`` HTML tag) + +Others can be found on [Packagist under the `commonmark-extension` package type](https://packagist.org/packages/league/commonmark?type=commonmark-extension). + +If you build your own, feel free to submit a PR to add it to this list! + +### Others + +Check out the other cool things people are doing with `league/commonmark`: + +## 🏷️ Versioning + +[SemVer](http://semver.org/) is followed closely. Minor and patch releases should not introduce breaking changes to the codebase; however, they might change the resulting AST or HTML output of parsed Markdown (due to bug fixes, spec changes, etc.) As a result, you might get slightly different HTML, but any custom code built onto this library should still function correctly. + +Any classes or methods marked `@internal` are not intended for use outside of this library and are subject to breaking changes at any time, so please avoid using them. + +## 🛠️ Maintenance & Support + +When a new **minor** version (e.g. `2.0` -> `2.1`) is released, the previous one (`2.0`) will continue to receive security and critical bug fixes for *at least* 3 months. + +When a new **major** version is released (e.g. `1.6` -> `2.0`), the previous one (`1.6`) will receive critical bug fixes for *at least* 3 months and security updates for 6 months after that new release comes out. + +(This policy may change in the future and exceptions may be made on a case-by-case basis.) + +**Professional support, including notification of new releases and security updates, is available through a [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-league-commonmark?utm_source=packagist-league-commonmark&utm_medium=referral&utm_campaign=readme).** + +## 👷‍♀️ Contributing + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure with us. + +If you encounter a bug in the spec, please report it to the [CommonMark] project. Any resulting fix will eventually be implemented in this project as well. + +Contributions to this library are **welcome**, especially ones that: + + * Improve usability or flexibility without compromising our ability to adhere to the [CommonMark spec] + * Mirror fixes made to the [reference implementation][commonmark.js] + * Optimize performance + * Fix issues with adhering to the [CommonMark spec] + +Major refactoring to core parsing logic should be avoided if possible so that we can easily follow updates made to [the reference implementation][commonmark.js]. That being said, we will absolutely consider changes which don't deviate too far from the reference spec or which are favored by other popular CommonMark implementations. + +Please see [CONTRIBUTING](https://github.com/thephpleague/commonmark/blob/main/.github/CONTRIBUTING.md) for additional details. + +## 🧪 Testing + +``` bash +$ composer test +``` + +This will also test league/commonmark against the latest supported spec. + +## 🚀 Performance Benchmarks + +You can compare the performance of **league/commonmark** to other popular parsers by running the included benchmark tool: + +``` bash +$ ./tests/benchmark/benchmark.php +``` + +## 👥 Credits & Acknowledgements + +- [Colin O'Dell][@colinodell] +- [John MacFarlane][@jgm] +- [All Contributors] + +This code is partially based on the [CommonMark JS reference implementation][commonmark.js] which is written, maintained and copyrighted by [John MacFarlane]. This project simply wouldn't exist without his work. + +### Sponsors + +We'd also like to extend our sincere thanks the following sponsors who support ongoing development of this project: + + - [Tidelift](https://tidelift.com/subscription/pkg/packagist-league-commonmark?utm_source=packagist-league-commonmark&utm_medium=referral&utm_campaign=readme) for offering support to both the maintainers and end-users through their [professional support](https://tidelift.com/subscription/pkg/packagist-league-commonmark?utm_source=packagist-league-commonmark&utm_medium=referral&utm_campaign=readme) program + - [Blackfire](https://www.blackfire.io/) for providing an Open-Source Profiler subscription + - [JetBrains](https://www.jetbrains.com/) for supporting this project with complimentary [PhpStorm](https://www.jetbrains.com/phpstorm/) licenses + - [Taylor Otwell](https://twitter.com/taylorotwell) for sponsoring this project through GitHub sponsors + +Are you interested in sponsoring development of this project? See for a list of ways to contribute. + +## 📄 License + +**league/commonmark** is licensed under the BSD-3 license. See the [`LICENSE`](LICENSE) file for more details. + +## 🏛️ Governance + +This project is primarily maintained by [Colin O'Dell][@colinodell]. Members of the [PHP League] Leadership Team may occasionally assist with some of these duties. + +## 🗺️ Who Uses It? + +This project is used by [Drupal](https://www.drupal.org/project/markdown), [Laravel Framework](https://laravel.com/), [Cachet](https://cachethq.io/), [Firefly III](https://firefly-iii.org/), [Neos](https://www.neos.io/), [Daux.io](https://daux.io/), and [more](https://packagist.org/packages/league/commonmark/dependents)! + +--- + +
+ + Get professional support for league/commonmark with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +[CommonMark]: http://commonmark.org/ +[CommonMark spec]: http://spec.commonmark.org/ +[commonmark.js]: https://github.com/jgm/commonmark.js +[GitHub-Flavored Markdown]: https://github.github.com/gfm/ +[John MacFarlane]: http://johnmacfarlane.net +[docs]: https://commonmark.thephpleague.com/ +[docs-examples]: https://commonmark.thephpleague.com/customization/overview/#examples +[docs-example-twitter]: https://commonmark.thephpleague.com/customization/inline-parsing#example-1---twitter-handles +[docs-example-smilies]: https://commonmark.thephpleague.com/customization/inline-parsing#example-2---emoticons +[All Contributors]: https://github.com/thephpleague/commonmark/contributors +[@colinodell]: https://www.twitter.com/colinodell +[@jgm]: https://github.com/jgm +[jgm/stmd]: https://github.com/jgm/stmd +[Composer]: https://getcomposer.org/ +[PHP League]: https://thephpleague.com diff --git a/php/libraries/composer/vendor/league/commonmark/composer.json b/php/libraries/composer/vendor/league/commonmark/composer.json new file mode 100644 index 0000000..53901eb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/composer.json @@ -0,0 +1,125 @@ +{ + "name": "league/commonmark", + "type": "library", + "description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)", + "keywords": ["markdown","parser","commonmark","gfm","github","flavored","github-flavored","md"], + "homepage": "https://commonmark.thephpleague.com", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "support": { + "docs": "https://commonmark.thephpleague.com/", + "forum": "https://github.com/thephpleague/commonmark/discussions", + "issues": "https://github.com/thephpleague/commonmark/issues", + "rss": "https://github.com/thephpleague/commonmark/releases.atom", + "source": "https://github.com/thephpleague/commonmark" + }, + "require": { + "php": "^7.4 || ^8.0", + "ext-mbstring": "*", + "league/config": "^1.1.1", + "psr/event-dispatcher": "^1.0", + "symfony/deprecation-contracts": "^2.1 || ^3.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "ext-json": "*", + "cebe/markdown": "^1.0", + "commonmark/cmark": "0.30.3", + "commonmark/commonmark.js": "0.30.0", + "composer/package-versions-deprecated": "^1.8", + "embed/embed": "^4.4", + "erusev/parsedown": "^1.0", + "github/gfm": "0.29.0", + "michelf/php-markdown": "^1.4 || ^2.0", + "nyholm/psr7": "^1.5", + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.21 || ^10.5.9 || ^11.0.0", + "scrutinizer/ocular": "^1.8.1", + "symfony/finder": "^5.3 | ^6.0 || ^7.0", + "symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0 || ^7.0", + "unleashedtech/php-coding-standard": "^3.1.1", + "vimeo/psalm": "^4.24.0 || ^5.0.0" + }, + "minimum-stability": "beta", + "suggest": { + "symfony/yaml": "v2.3+ required if using the Front Matter extension" + }, + "repositories": [ + { + "type": "package", + "package": { + "name": "commonmark/commonmark.js", + "version": "0.30.0", + "dist": { + "url": "https://github.com/commonmark/commonmark.js/archive/0.30.0.zip", + "type": "zip" + } + } + }, + { + "type": "package", + "package": { + "name": "commonmark/cmark", + "version": "0.30.3", + "dist": { + "url": "https://github.com/commonmark/cmark/archive/0.30.3.zip", + "type": "zip" + } + } + }, + { + "type": "package", + "package": { + "name": "github/gfm", + "version": "0.29.0", + "dist": { + "url": "https://github.com/github/cmark-gfm/archive/0.29.0.gfm.13.zip", + "type": "zip" + } + } + } + ], + "autoload": { + "psr-4": { + "League\\CommonMark\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "League\\CommonMark\\Tests\\Unit\\": "tests/unit", + "League\\CommonMark\\Tests\\Functional\\": "tests/functional", + "League\\CommonMark\\Tests\\PHPStan\\": "tests/phpstan" + } + }, + "scripts": { + "phpcs": "phpcs", + "phpstan": "phpstan analyse", + "phpunit": "phpunit --no-coverage", + "psalm": "psalm --stats", + "test": [ + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + } + }, + "config": { + "allow-plugins": { + "composer/package-versions-deprecated": true, + "dealerdirect/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/CommonMarkConverter.php b/php/libraries/composer/vendor/league/commonmark/src/CommonMarkConverter.php new file mode 100644 index 0000000..4d70053 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/CommonMarkConverter.php @@ -0,0 +1,46 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Environment\Environment; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; + +/** + * Converts CommonMark-compatible Markdown to HTML. + */ +final class CommonMarkConverter extends MarkdownConverter +{ + /** + * Create a new Markdown converter pre-configured for CommonMark + * + * @param array $config + */ + public function __construct(array $config = []) + { + $environment = new Environment($config); + $environment->addExtension(new CommonMarkCoreExtension()); + + parent::__construct($environment); + } + + public function getEnvironment(): Environment + { + \assert($this->environment instanceof Environment); + + return $this->environment; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/ConverterInterface.php b/php/libraries/composer/vendor/league/commonmark/src/ConverterInterface.php new file mode 100644 index 0000000..8192b0f --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/ConverterInterface.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 League\CommonMark; + +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; +use League\Config\Exception\ConfigurationExceptionInterface; + +/** + * Interface for a service which converts content from one format (like Markdown) to another (like HTML). + */ +interface ConverterInterface +{ + /** + * @throws CommonMarkException + * @throws ConfigurationExceptionInterface + */ + public function convert(string $input): RenderedContentInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Delimiter.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Delimiter.php new file mode 100644 index 0000000..2f04f24 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Delimiter.php @@ -0,0 +1,134 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class Delimiter implements DelimiterInterface +{ + /** @psalm-readonly */ + private string $char; + + /** @psalm-readonly-allow-private-mutation */ + private int $length; + + /** @psalm-readonly */ + private int $originalLength; + + /** @psalm-readonly */ + private AbstractStringContainer $inlineNode; + + /** @psalm-readonly-allow-private-mutation */ + private ?DelimiterInterface $previous = null; + + /** @psalm-readonly-allow-private-mutation */ + private ?DelimiterInterface $next = null; + + /** @psalm-readonly */ + private bool $canOpen; + + /** @psalm-readonly */ + private bool $canClose; + + /** @psalm-readonly-allow-private-mutation */ + private bool $active; + + /** @psalm-readonly */ + private ?int $index = null; + + public function __construct(string $char, int $numDelims, AbstractStringContainer $node, bool $canOpen, bool $canClose, ?int $index = null) + { + $this->char = $char; + $this->length = $numDelims; + $this->originalLength = $numDelims; + $this->inlineNode = $node; + $this->canOpen = $canOpen; + $this->canClose = $canClose; + $this->active = true; + $this->index = $index; + } + + public function canClose(): bool + { + return $this->canClose; + } + + public function canOpen(): bool + { + return $this->canOpen; + } + + public function isActive(): bool + { + return $this->active; + } + + public function setActive(bool $active): void + { + $this->active = $active; + } + + public function getChar(): string + { + return $this->char; + } + + public function getIndex(): ?int + { + return $this->index; + } + + public function getNext(): ?DelimiterInterface + { + return $this->next; + } + + public function setNext(?DelimiterInterface $next): void + { + $this->next = $next; + } + + public function getLength(): int + { + return $this->length; + } + + public function setLength(int $length): void + { + $this->length = $length; + } + + public function getOriginalLength(): int + { + return $this->originalLength; + } + + public function getInlineNode(): AbstractStringContainer + { + return $this->inlineNode; + } + + public function getPrevious(): ?DelimiterInterface + { + return $this->previous; + } + + public function setPrevious(?DelimiterInterface $previous): void + { + $this->previous = $previous; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterInterface.php new file mode 100644 index 0000000..6bfa32e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterInterface.php @@ -0,0 +1,50 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +interface DelimiterInterface +{ + public function canClose(): bool; + + public function canOpen(): bool; + + public function isActive(): bool; + + public function setActive(bool $active): void; + + public function getChar(): string; + + public function getIndex(): ?int; + + public function getNext(): ?DelimiterInterface; + + public function setNext(?DelimiterInterface $next): void; + + public function getLength(): int; + + public function setLength(int $length): void; + + public function getOriginalLength(): int; + + public function getInlineNode(): AbstractStringContainer; + + public function getPrevious(): ?DelimiterInterface; + + public function setPrevious(?DelimiterInterface $previous): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterParser.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterParser.php new file mode 100644 index 0000000..3f96add --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterParser.php @@ -0,0 +1,102 @@ +collection = $collection; + } + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf(...$this->collection->getDelimiterCharacters()); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $character = $inlineContext->getFullMatch(); + $numDelims = 0; + $cursor = $inlineContext->getCursor(); + $processor = $this->collection->getDelimiterProcessor($character); + + \assert($processor !== null); // Delimiter processor should never be null here + + $charBefore = $cursor->peek(-1); + if ($charBefore === null) { + $charBefore = "\n"; + } + + while ($cursor->peek($numDelims) === $character) { + ++$numDelims; + } + + if ($numDelims < $processor->getMinLength()) { + return false; + } + + $cursor->advanceBy($numDelims); + + $charAfter = $cursor->getCurrentCharacter(); + if ($charAfter === null) { + $charAfter = "\n"; + } + + [$canOpen, $canClose] = self::determineCanOpenOrClose($charBefore, $charAfter, $character, $processor); + + $node = new Text(\str_repeat($character, $numDelims), [ + 'delim' => true, + ]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack to this opener + if ($canOpen || $canClose) { + $delimiter = new Delimiter($character, $numDelims, $node, $canOpen, $canClose); + $inlineContext->getDelimiterStack()->push($delimiter); + } + + return true; + } + + /** + * @return bool[] + */ + private static function determineCanOpenOrClose(string $charBefore, string $charAfter, string $character, DelimiterProcessorInterface $delimiterProcessor): array + { + $afterIsWhitespace = \preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $charAfter); + $afterIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charAfter); + $beforeIsWhitespace = \preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $charBefore); + $beforeIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charBefore); + + $leftFlanking = ! $afterIsWhitespace && (! $afterIsPunctuation || $beforeIsWhitespace || $beforeIsPunctuation); + $rightFlanking = ! $beforeIsWhitespace && (! $beforeIsPunctuation || $afterIsWhitespace || $afterIsPunctuation); + + if ($character === '_') { + $canOpen = $leftFlanking && (! $rightFlanking || $beforeIsPunctuation); + $canClose = $rightFlanking && (! $leftFlanking || $afterIsPunctuation); + } else { + $canOpen = $leftFlanking && $character === $delimiterProcessor->getOpeningCharacter(); + $canClose = $rightFlanking && $character === $delimiterProcessor->getClosingCharacter(); + } + + return [$canOpen, $canClose]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterStack.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterStack.php new file mode 100644 index 0000000..fb95b90 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/DelimiterStack.php @@ -0,0 +1,214 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection; +use League\CommonMark\Node\Inline\AdjacentTextMerger; + +final class DelimiterStack +{ + /** @psalm-readonly-allow-private-mutation */ + private ?DelimiterInterface $top = null; + + public function push(DelimiterInterface $newDelimiter): void + { + $newDelimiter->setPrevious($this->top); + + if ($this->top !== null) { + $this->top->setNext($newDelimiter); + } + + $this->top = $newDelimiter; + } + + private function findEarliest(?DelimiterInterface $stackBottom = null): ?DelimiterInterface + { + $delimiter = $this->top; + while ($delimiter !== null && $delimiter->getPrevious() !== $stackBottom) { + $delimiter = $delimiter->getPrevious(); + } + + return $delimiter; + } + + public function removeDelimiter(DelimiterInterface $delimiter): void + { + if ($delimiter->getPrevious() !== null) { + /** @psalm-suppress PossiblyNullReference */ + $delimiter->getPrevious()->setNext($delimiter->getNext()); + } + + if ($delimiter->getNext() === null) { + // top of stack + $this->top = $delimiter->getPrevious(); + } else { + /** @psalm-suppress PossiblyNullReference */ + $delimiter->getNext()->setPrevious($delimiter->getPrevious()); + } + } + + private function removeDelimiterAndNode(DelimiterInterface $delimiter): void + { + $delimiter->getInlineNode()->detach(); + $this->removeDelimiter($delimiter); + } + + private function removeDelimitersBetween(DelimiterInterface $opener, DelimiterInterface $closer): void + { + $delimiter = $closer->getPrevious(); + while ($delimiter !== null && $delimiter !== $opener) { + $previous = $delimiter->getPrevious(); + $this->removeDelimiter($delimiter); + $delimiter = $previous; + } + } + + public function removeAll(?DelimiterInterface $stackBottom = null): void + { + while ($this->top && $this->top !== $stackBottom) { + $this->removeDelimiter($this->top); + } + } + + public function removeEarlierMatches(string $character): void + { + $opener = $this->top; + while ($opener !== null) { + if ($opener->getChar() === $character) { + $opener->setActive(false); + } + + $opener = $opener->getPrevious(); + } + } + + /** + * @param string|string[] $characters + */ + public function searchByCharacter($characters): ?DelimiterInterface + { + if (! \is_array($characters)) { + $characters = [$characters]; + } + + $opener = $this->top; + while ($opener !== null) { + if (\in_array($opener->getChar(), $characters, true)) { + break; + } + + $opener = $opener->getPrevious(); + } + + return $opener; + } + + public function processDelimiters(?DelimiterInterface $stackBottom, DelimiterProcessorCollection $processors): void + { + $openersBottom = []; + + // Find first closer above stackBottom + $closer = $this->findEarliest($stackBottom); + + // Move forward, looking for closers, and handling each + while ($closer !== null) { + $delimiterChar = $closer->getChar(); + + $delimiterProcessor = $processors->getDelimiterProcessor($delimiterChar); + if (! $closer->canClose() || $delimiterProcessor === null) { + $closer = $closer->getNext(); + continue; + } + + $openingDelimiterChar = $delimiterProcessor->getOpeningCharacter(); + + $useDelims = 0; + $openerFound = false; + $potentialOpenerFound = false; + $opener = $closer->getPrevious(); + while ($opener !== null && $opener !== $stackBottom && $opener !== ($openersBottom[$delimiterChar] ?? null)) { + if ($opener->canOpen() && $opener->getChar() === $openingDelimiterChar) { + $potentialOpenerFound = true; + $useDelims = $delimiterProcessor->getDelimiterUse($opener, $closer); + if ($useDelims > 0) { + $openerFound = true; + break; + } + } + + $opener = $opener->getPrevious(); + } + + if (! $openerFound) { + if (! $potentialOpenerFound) { + // Only do this when we didn't even have a potential + // opener (one that matches the character and can open). + // If an opener was rejected because of the number of + // delimiters (e.g. because of the "multiple of 3" + // Set lower bound for future searches for openersrule), + // we want to consider it next time because the number + // of delimiters can change as we continue processing. + $openersBottom[$delimiterChar] = $closer->getPrevious(); + if (! $closer->canOpen()) { + // We can remove a closer that can't be an opener, + // once we've seen there's no matching opener. + $this->removeDelimiter($closer); + } + } + + $closer = $closer->getNext(); + continue; + } + + \assert($opener !== null); + + $openerNode = $opener->getInlineNode(); + $closerNode = $closer->getInlineNode(); + + // Remove number of used delimiters from stack and inline nodes. + $opener->setLength($opener->getLength() - $useDelims); + $closer->setLength($closer->getLength() - $useDelims); + + $openerNode->setLiteral(\substr($openerNode->getLiteral(), 0, -$useDelims)); + $closerNode->setLiteral(\substr($closerNode->getLiteral(), 0, -$useDelims)); + + $this->removeDelimitersBetween($opener, $closer); + // The delimiter processor can re-parent the nodes between opener and closer, + // so make sure they're contiguous already. Exclusive because we want to keep opener/closer themselves. + AdjacentTextMerger::mergeTextNodesBetweenExclusive($openerNode, $closerNode); + $delimiterProcessor->process($openerNode, $closerNode, $useDelims); + + // No delimiter characters left to process, so we can remove delimiter and the now empty node. + if ($opener->getLength() === 0) { + $this->removeDelimiterAndNode($opener); + } + + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($closer->getLength() === 0) { + $next = $closer->getNext(); + $this->removeDelimiterAndNode($closer); + $closer = $next; + } + } + + // Remove all delimiters + $this->removeAll($stackBottom); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php new file mode 100644 index 0000000..6e9f336 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php @@ -0,0 +1,89 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Exception\InvalidArgumentException; + +final class DelimiterProcessorCollection implements DelimiterProcessorCollectionInterface +{ + /** + * @var array|DelimiterProcessorInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $processorsByChar = []; + + public function add(DelimiterProcessorInterface $processor): void + { + $opening = $processor->getOpeningCharacter(); + $closing = $processor->getClosingCharacter(); + + if ($opening === $closing) { + $old = $this->processorsByChar[$opening] ?? null; + if ($old !== null && $old->getOpeningCharacter() === $old->getClosingCharacter()) { + $this->addStaggeredDelimiterProcessorForChar($opening, $old, $processor); + } else { + $this->addDelimiterProcessorForChar($opening, $processor); + } + } else { + $this->addDelimiterProcessorForChar($opening, $processor); + $this->addDelimiterProcessorForChar($closing, $processor); + } + } + + public function getDelimiterProcessor(string $char): ?DelimiterProcessorInterface + { + return $this->processorsByChar[$char] ?? null; + } + + /** + * @return string[] + */ + public function getDelimiterCharacters(): array + { + return \array_keys($this->processorsByChar); + } + + private function addDelimiterProcessorForChar(string $delimiterChar, DelimiterProcessorInterface $processor): void + { + if (isset($this->processorsByChar[$delimiterChar])) { + throw new InvalidArgumentException(\sprintf('Delim processor for character "%s" already exists', $processor->getOpeningCharacter())); + } + + $this->processorsByChar[$delimiterChar] = $processor; + } + + private function addStaggeredDelimiterProcessorForChar(string $opening, DelimiterProcessorInterface $old, DelimiterProcessorInterface $new): void + { + if ($old instanceof StaggeredDelimiterProcessor) { + $s = $old; + } else { + $s = new StaggeredDelimiterProcessor($opening, $old); + } + + $s->add($new); + $this->processorsByChar[$opening] = $s; + } + + public function count(): int + { + return \count($this->processorsByChar); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php new file mode 100644 index 0000000..fea3ddb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php @@ -0,0 +1,46 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Exception\InvalidArgumentException; + +interface DelimiterProcessorCollectionInterface extends \Countable +{ + /** + * Add the given delim processor to the collection + * + * @param DelimiterProcessorInterface $processor The delim processor to add + * + * @throws InvalidArgumentException Exception will be thrown if attempting to add multiple processors for the same character + */ + public function add(DelimiterProcessorInterface $processor): void; + + /** + * Returns the delim processor which handles the given character if one exists + */ + public function getDelimiterProcessor(string $char): ?DelimiterProcessorInterface; + + /** + * Returns an array of delimiter characters who have associated processors + * + * @return string[] + */ + public function getDelimiterCharacters(): array; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php new file mode 100644 index 0000000..465378c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php @@ -0,0 +1,78 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +/** + * Interface for a delimiter processor + */ +interface DelimiterProcessorInterface +{ + /** + * Returns the character that marks the beginning of a delimited node. + * + * This must not clash with any other processors being added to the environment. + */ + public function getOpeningCharacter(): string; + + /** + * Returns the character that marks the ending of a delimited node. + * + * This must not clash with any other processors being added to the environment. + * + * Note that for a symmetric delimiter such as "*", this is the same as the opening. + */ + public function getClosingCharacter(): string; + + /** + * Minimum number of delimiter characters that are needed to active this. + * + * Must be at least 1. + */ + public function getMinLength(): int; + + /** + * Determine how many (if any) of the delimiter characters should be used. + * + * This allows implementations to decide how many characters to be used + * based on the properties of the delimiter runs. An implementation can also + * return 0 when it doesn't want to allow this particular combination of + * delimiter runs. + * + * @param DelimiterInterface $opener The opening delimiter run + * @param DelimiterInterface $closer The closing delimiter run + */ + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int; + + /** + * Process the matched delimiters, e.g. by wrapping the nodes between opener + * and closer in a new node, or appending a new node after the opener. + * + * Note that removal of the delimiter from the delimiter nodes and detaching + * them is done by the caller. + * + * @param AbstractStringContainer $opener The node that contained the opening delimiter + * @param AbstractStringContainer $closer The node that contained the closing delimiter + * @param int $delimiterUse The number of delimiters that were used + */ + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php new file mode 100644 index 0000000..7d33e83 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php @@ -0,0 +1,111 @@ + + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +/** + * An implementation of DelimiterProcessorInterface that dispatches all calls to two or more other DelimiterProcessors + * depending on the length of the delimiter run. All child DelimiterProcessors must have different minimum + * lengths. A given delimiter run is dispatched to the child with the largest acceptable minimum length. If no + * child is applicable, the one with the largest minimum length is chosen. + * + * @internal + */ +final class StaggeredDelimiterProcessor implements DelimiterProcessorInterface +{ + /** @psalm-readonly */ + private string $delimiterChar; + + /** @psalm-readonly-allow-private-mutation */ + private int $minLength = 0; + + /** + * @var array|DelimiterProcessorInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $processors = []; // keyed by minLength in reverse order + + public function __construct(string $char, DelimiterProcessorInterface $processor) + { + $this->delimiterChar = $char; + $this->add($processor); + } + + public function getOpeningCharacter(): string + { + return $this->delimiterChar; + } + + public function getClosingCharacter(): string + { + return $this->delimiterChar; + } + + public function getMinLength(): int + { + return $this->minLength; + } + + /** + * Adds the given processor to this staggered delimiter processor + * + * @throws InvalidArgumentException if attempting to add another processors for the same character and minimum length + */ + public function add(DelimiterProcessorInterface $processor): void + { + $len = $processor->getMinLength(); + + if (isset($this->processors[$len])) { + throw new InvalidArgumentException(\sprintf('Cannot add two delimiter processors for char "%s" and minimum length %d', $this->delimiterChar, $len)); + } + + $this->processors[$len] = $processor; + \krsort($this->processors); + + $this->minLength = \min($this->minLength, $len); + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + return $this->findProcessor($opener->getLength())->getDelimiterUse($opener, $closer); + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $this->findProcessor($delimiterUse)->process($opener, $closer, $delimiterUse); + } + + private function findProcessor(int $len): DelimiterProcessorInterface + { + // Find the "longest" processor which can handle this length + foreach ($this->processors as $processor) { + if ($processor->getMinLength() <= $len) { + return $processor; + } + } + + // Just use the first one in our list + $first = \reset($this->processors); + \assert($first instanceof DelimiterProcessorInterface); + + return $first; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Environment/Environment.php b/php/libraries/composer/vendor/league/commonmark/src/Environment/Environment.php new file mode 100644 index 0000000..3c24749 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Environment/Environment.php @@ -0,0 +1,447 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +use League\CommonMark\Delimiter\DelimiterParser; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Event\ListenerData; +use League\CommonMark\Exception\AlreadyInitializedException; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Extension\GithubFlavoredMarkdownExtension; +use League\CommonMark\Normalizer\SlugNormalizer; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\CommonMark\Normalizer\UniqueSlugNormalizer; +use League\CommonMark\Normalizer\UniqueSlugNormalizerInterface; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Block\SkipLinesStartingWithLettersParser; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlFilter; +use League\CommonMark\Util\PrioritizedList; +use League\Config\Configuration; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; +use Nette\Schema\Expect; +use Psr\EventDispatcher\EventDispatcherInterface; +use Psr\EventDispatcher\ListenerProviderInterface; +use Psr\EventDispatcher\StoppableEventInterface; + +final class Environment implements EnvironmentInterface, EnvironmentBuilderInterface, ListenerProviderInterface +{ + /** + * @var ExtensionInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $extensions = []; + + /** + * @var ExtensionInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $uninitializedExtensions = []; + + /** @psalm-readonly-allow-private-mutation */ + private bool $extensionsInitialized = false; + + /** + * @var PrioritizedList + * + * @psalm-readonly + */ + private PrioritizedList $blockStartParsers; + + /** + * @var PrioritizedList + * + * @psalm-readonly + */ + private PrioritizedList $inlineParsers; + + /** @psalm-readonly */ + private DelimiterProcessorCollection $delimiterProcessors; + + /** + * @var array> + * + * @psalm-readonly-allow-private-mutation + */ + private array $renderersByClass = []; + + /** + * @var PrioritizedList + * + * @psalm-readonly-allow-private-mutation + */ + private PrioritizedList $listenerData; + + private ?EventDispatcherInterface $eventDispatcher = null; + + /** @psalm-readonly */ + private Configuration $config; + + private ?TextNormalizerInterface $slugNormalizer = null; + + /** + * @param array $config + */ + public function __construct(array $config = []) + { + $this->config = self::createDefaultConfiguration(); + $this->config->merge($config); + + $this->blockStartParsers = new PrioritizedList(); + $this->inlineParsers = new PrioritizedList(); + $this->listenerData = new PrioritizedList(); + $this->delimiterProcessors = new DelimiterProcessorCollection(); + + // Performance optimization: always include a block "parser" that aborts parsing if a line starts with a letter + // and is therefore unlikely to match any lines as a block start. + $this->addBlockStartParser(new SkipLinesStartingWithLettersParser(), 249); + } + + public function getConfiguration(): ConfigurationInterface + { + return $this->config->reader(); + } + + /** + * @deprecated Environment::mergeConfig() is deprecated since league/commonmark v2.0 and will be removed in v3.0. Configuration should be set when instantiating the environment instead. + * + * @param array $config + */ + public function mergeConfig(array $config): void + { + @\trigger_error('Environment::mergeConfig() is deprecated since league/commonmark v2.0 and will be removed in v3.0. Configuration should be set when instantiating the environment instead.', \E_USER_DEPRECATED); + + $this->assertUninitialized('Failed to modify configuration.'); + + $this->config->merge($config); + } + + public function addBlockStartParser(BlockStartParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add block start parser.'); + + $this->blockStartParsers->add($parser, $priority); + $this->injectEnvironmentAndConfigurationIfNeeded($parser); + + return $this; + } + + public function addInlineParser(InlineParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add inline parser.'); + + $this->inlineParsers->add($parser, $priority); + $this->injectEnvironmentAndConfigurationIfNeeded($parser); + + return $this; + } + + public function addDelimiterProcessor(DelimiterProcessorInterface $processor): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add delimiter processor.'); + $this->delimiterProcessors->add($processor); + $this->injectEnvironmentAndConfigurationIfNeeded($processor); + + return $this; + } + + public function addRenderer(string $nodeClass, NodeRendererInterface $renderer, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add renderer.'); + + if (! isset($this->renderersByClass[$nodeClass])) { + $this->renderersByClass[$nodeClass] = new PrioritizedList(); + } + + $this->renderersByClass[$nodeClass]->add($renderer, $priority); + $this->injectEnvironmentAndConfigurationIfNeeded($renderer); + + return $this; + } + + /** + * {@inheritDoc} + */ + public function getBlockStartParsers(): iterable + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return $this->blockStartParsers->getIterator(); + } + + public function getDelimiterProcessors(): DelimiterProcessorCollection + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return $this->delimiterProcessors; + } + + /** + * {@inheritDoc} + */ + public function getRenderersForClass(string $nodeClass): iterable + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + // If renderers are defined for this specific class, return them immediately + if (isset($this->renderersByClass[$nodeClass])) { + return $this->renderersByClass[$nodeClass]; + } + + /** @psalm-suppress TypeDoesNotContainType -- Bug: https://github.com/vimeo/psalm/issues/3332 */ + while (\class_exists($parent ??= $nodeClass) && $parent = \get_parent_class($parent)) { + if (! isset($this->renderersByClass[$parent])) { + continue; + } + + // "Cache" this result to avoid future loops + return $this->renderersByClass[$nodeClass] = $this->renderersByClass[$parent]; + } + + return []; + } + + /** + * {@inheritDoc} + */ + public function getExtensions(): iterable + { + return $this->extensions; + } + + /** + * Add a single extension + * + * @return $this + */ + public function addExtension(ExtensionInterface $extension): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add extension.'); + + $this->extensions[] = $extension; + $this->uninitializedExtensions[] = $extension; + + if ($extension instanceof ConfigurableExtensionInterface) { + $extension->configureSchema($this->config); + } + + return $this; + } + + private function initializeExtensions(): void + { + // Initialize the slug normalizer + $this->getSlugNormalizer(); + + // Ask all extensions to register their components + while (\count($this->uninitializedExtensions) > 0) { + foreach ($this->uninitializedExtensions as $i => $extension) { + $extension->register($this); + unset($this->uninitializedExtensions[$i]); + } + } + + $this->extensionsInitialized = true; + + // Create the special delimiter parser if any processors were registered + if ($this->delimiterProcessors->count() > 0) { + $this->inlineParsers->add(new DelimiterParser($this->delimiterProcessors), PHP_INT_MIN); + } + } + + private function injectEnvironmentAndConfigurationIfNeeded(object $object): void + { + if ($object instanceof EnvironmentAwareInterface) { + $object->setEnvironment($this); + } + + if ($object instanceof ConfigurationAwareInterface) { + $object->setConfiguration($this->config->reader()); + } + } + + /** + * @deprecated Instantiate the environment and add the extension yourself + * + * @param array $config + */ + public static function createCommonMarkEnvironment(array $config = []): Environment + { + $environment = new self($config); + $environment->addExtension(new CommonMarkCoreExtension()); + + return $environment; + } + + /** + * @deprecated Instantiate the environment and add the extension yourself + * + * @param array $config + */ + public static function createGFMEnvironment(array $config = []): Environment + { + $environment = new self($config); + $environment->addExtension(new CommonMarkCoreExtension()); + $environment->addExtension(new GithubFlavoredMarkdownExtension()); + + return $environment; + } + + public function addEventListener(string $eventClass, callable $listener, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add event listener.'); + + $this->listenerData->add(new ListenerData($eventClass, $listener), $priority); + + if (\is_object($listener)) { + $this->injectEnvironmentAndConfigurationIfNeeded($listener); + } elseif (\is_array($listener) && \is_object($listener[0])) { + $this->injectEnvironmentAndConfigurationIfNeeded($listener[0]); + } + + return $this; + } + + public function dispatch(object $event): object + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + if ($this->eventDispatcher !== null) { + return $this->eventDispatcher->dispatch($event); + } + + foreach ($this->getListenersForEvent($event) as $listener) { + if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + return $event; + } + + $listener($event); + } + + return $event; + } + + public function setEventDispatcher(EventDispatcherInterface $dispatcher): void + { + $this->eventDispatcher = $dispatcher; + } + + /** + * {@inheritDoc} + * + * @return iterable + */ + public function getListenersForEvent(object $event): iterable + { + foreach ($this->listenerData as $listenerData) { + \assert($listenerData instanceof ListenerData); + + /** @psalm-suppress ArgumentTypeCoercion */ + if (! \is_a($event, $listenerData->getEvent())) { + continue; + } + + yield function (object $event) use ($listenerData) { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return \call_user_func($listenerData->getListener(), $event); + }; + } + } + + /** + * @return iterable + */ + public function getInlineParsers(): iterable + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return $this->inlineParsers->getIterator(); + } + + public function getSlugNormalizer(): TextNormalizerInterface + { + if ($this->slugNormalizer === null) { + $normalizer = $this->config->get('slug_normalizer/instance'); + \assert($normalizer instanceof TextNormalizerInterface); + $this->injectEnvironmentAndConfigurationIfNeeded($normalizer); + + if ($this->config->get('slug_normalizer/unique') !== UniqueSlugNormalizerInterface::DISABLED && ! $normalizer instanceof UniqueSlugNormalizer) { + $normalizer = new UniqueSlugNormalizer($normalizer); + } + + if ($normalizer instanceof UniqueSlugNormalizer) { + if ($this->config->get('slug_normalizer/unique') === UniqueSlugNormalizerInterface::PER_DOCUMENT) { + $this->addEventListener(DocumentParsedEvent::class, [$normalizer, 'clearHistory'], -1000); + } + } + + $this->slugNormalizer = $normalizer; + } + + return $this->slugNormalizer; + } + + /** + * @throws AlreadyInitializedException + */ + private function assertUninitialized(string $message): void + { + if ($this->extensionsInitialized) { + throw new AlreadyInitializedException($message . ' Extensions have already been initialized.'); + } + } + + public static function createDefaultConfiguration(): Configuration + { + return new Configuration([ + 'html_input' => Expect::anyOf(HtmlFilter::STRIP, HtmlFilter::ALLOW, HtmlFilter::ESCAPE)->default(HtmlFilter::ALLOW), + 'allow_unsafe_links' => Expect::bool(true), + 'max_nesting_level' => Expect::type('int')->default(PHP_INT_MAX), + 'renderer' => Expect::structure([ + 'block_separator' => Expect::string("\n"), + 'inner_separator' => Expect::string("\n"), + 'soft_break' => Expect::string("\n"), + ]), + 'slug_normalizer' => Expect::structure([ + 'instance' => Expect::type(TextNormalizerInterface::class)->default(new SlugNormalizer()), + 'max_length' => Expect::int()->min(0)->default(255), + 'unique' => Expect::anyOf(UniqueSlugNormalizerInterface::DISABLED, UniqueSlugNormalizerInterface::PER_ENVIRONMENT, UniqueSlugNormalizerInterface::PER_DOCUMENT)->default(UniqueSlugNormalizerInterface::PER_DOCUMENT), + ]), + ]); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php new file mode 100644 index 0000000..44b9d3e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +interface EnvironmentAwareInterface +{ + public function setEnvironment(EnvironmentInterface $environment): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php new file mode 100644 index 0000000..4df9761 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Exception\AlreadyInitializedException; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\Config\ConfigurationProviderInterface; + +/** + * Interface for building the Environment with any extensions, parsers, listeners, etc. that it may need + */ +interface EnvironmentBuilderInterface extends ConfigurationProviderInterface +{ + /** + * Registers the given extension with the Environment + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addExtension(ExtensionInterface $extension): EnvironmentBuilderInterface; + + /** + * Registers the given block start parser with the Environment + * + * @param BlockStartParserInterface $parser Block parser instance + * @param int $priority Priority (a higher number will be executed earlier) + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addBlockStartParser(BlockStartParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface; + + /** + * Registers the given inline parser with the Environment + * + * @param InlineParserInterface $parser Inline parser instance + * @param int $priority Priority (a higher number will be executed earlier) + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addInlineParser(InlineParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface; + + /** + * Registers the given delimiter processor with the Environment + * + * @param DelimiterProcessorInterface $processor Delimiter processors instance + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addDelimiterProcessor(DelimiterProcessorInterface $processor): EnvironmentBuilderInterface; + + /** + * Registers the given node renderer with the Environment + * + * @param string $nodeClass The fully-qualified node element class name the renderer below should handle + * @param NodeRendererInterface $renderer The renderer responsible for rendering the type of element given above + * @param int $priority Priority (a higher number will be executed earlier) + * + * @psalm-param class-string $nodeClass + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addRenderer(string $nodeClass, NodeRendererInterface $renderer, int $priority = 0): EnvironmentBuilderInterface; + + /** + * Registers the given event listener + * + * @param class-string $eventClass Fully-qualified class name of the event this listener should respond to + * @param callable $listener Listener to be executed + * @param int $priority Priority (a higher number will be executed earlier) + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addEventListener(string $eventClass, callable $listener, int $priority = 0): EnvironmentBuilderInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentInterface.php new file mode 100644 index 0000000..8e19a52 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Environment/EnvironmentInterface.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 League\CommonMark\Environment; + +use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\Config\ConfigurationProviderInterface; +use Psr\EventDispatcher\EventDispatcherInterface; + +interface EnvironmentInterface extends ConfigurationProviderInterface, EventDispatcherInterface +{ + /** + * Get all registered extensions + * + * @return ExtensionInterface[] + */ + public function getExtensions(): iterable; + + /** + * @return iterable + */ + public function getBlockStartParsers(): iterable; + + /** + * @return iterable + */ + public function getInlineParsers(): iterable; + + public function getDelimiterProcessors(): DelimiterProcessorCollection; + + /** + * @psalm-param class-string $nodeClass + * + * @return iterable + */ + public function getRenderersForClass(string $nodeClass): iterable; + + public function getSlugNormalizer(): TextNormalizerInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Event/AbstractEvent.php b/php/libraries/composer/vendor/league/commonmark/src/Event/AbstractEvent.php new file mode 100644 index 0000000..8c83f92 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Event/AbstractEvent.php @@ -0,0 +1,54 @@ + + * + * Original code based on the Symfony EventDispatcher "Event" contract + * - (c) 2018-2019 Fabien Potencier + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use Psr\EventDispatcher\StoppableEventInterface; + +/** + * Base class for classes containing event data. + * + * This class contains no event data. It is used by events that do not pass + * state information to an event handler when an event is raised. + * + * You can call the method stopPropagation() to abort the execution of + * further listeners in your event listener. + */ +abstract class AbstractEvent implements StoppableEventInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private bool $propagationStopped = false; + + /** + * Returns whether further event listeners should be triggered. + */ + final public function isPropagationStopped(): bool + { + return $this->propagationStopped; + } + + /** + * Stops the propagation of the event to further event listeners. + * + * If multiple event listeners are connected to the same event, no + * further event listener will be triggered once any trigger calls + * stopPropagation(). + */ + final public function stopPropagation(): void + { + $this->propagationStopped = true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentParsedEvent.php b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentParsedEvent.php new file mode 100644 index 0000000..04664c5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentParsedEvent.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use League\CommonMark\Node\Block\Document; + +/** + * Event dispatched when the document has been fully parsed + */ +final class DocumentParsedEvent extends AbstractEvent +{ + /** @psalm-readonly */ + private Document $document; + + public function __construct(Document $document) + { + $this->document = $document; + } + + public function getDocument(): Document + { + return $this->document; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentPreParsedEvent.php b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentPreParsedEvent.php new file mode 100644 index 0000000..ad72512 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentPreParsedEvent.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 League\CommonMark\Event; + +use League\CommonMark\Input\MarkdownInputInterface; +use League\CommonMark\Node\Block\Document; + +/** + * Event dispatched when the document is about to be parsed + */ +final class DocumentPreParsedEvent extends AbstractEvent +{ + /** @psalm-readonly */ + private Document $document; + + private MarkdownInputInterface $markdown; + + public function __construct(Document $document, MarkdownInputInterface $markdown) + { + $this->document = $document; + $this->markdown = $markdown; + } + + public function getDocument(): Document + { + return $this->document; + } + + public function getMarkdown(): MarkdownInputInterface + { + return $this->markdown; + } + + public function replaceMarkdown(MarkdownInputInterface $markdownInput): void + { + $this->markdown = $markdownInput; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php new file mode 100644 index 0000000..c569ca3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use League\CommonMark\Node\Block\Document; + +/** + * Event dispatched just before rendering begins + */ +final class DocumentPreRenderEvent extends AbstractEvent +{ + /** @psalm-readonly */ + private Document $document; + + /** @psalm-readonly */ + private string $format; + + public function __construct(Document $document, string $format) + { + $this->document = $document; + $this->format = $format; + } + + public function getDocument(): Document + { + return $this->document; + } + + public function getFormat(): string + { + return $this->format; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentRenderedEvent.php b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentRenderedEvent.php new file mode 100644 index 0000000..7e49d01 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Event/DocumentRenderedEvent.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Event; + +use League\CommonMark\Output\RenderedContentInterface; + +final class DocumentRenderedEvent extends AbstractEvent +{ + private RenderedContentInterface $output; + + public function __construct(RenderedContentInterface $output) + { + $this->output = $output; + } + + /** + * @psalm-mutation-free + */ + public function getOutput(): RenderedContentInterface + { + return $this->output; + } + + /** + * @psalm-external-mutation-free + */ + public function replaceOutput(RenderedContentInterface $output): void + { + $this->output = $output; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Event/ListenerData.php b/php/libraries/composer/vendor/league/commonmark/src/Event/ListenerData.php new file mode 100644 index 0000000..4cf3b3a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Event/ListenerData.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 League\CommonMark\Event; + +/** + * @internal + * + * @psalm-immutable + */ +final class ListenerData +{ + /** @var class-string */ + private string $event; + + /** @var callable */ + private $listener; + + /** + * @param class-string $event + */ + public function __construct(string $event, callable $listener) + { + $this->event = $event; + $this->listener = $listener; + } + + /** + * @return class-string + */ + public function getEvent(): string + { + return $this->event; + } + + public function getListener(): callable + { + return $this->listener; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/AlreadyInitializedException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/AlreadyInitializedException.php new file mode 100644 index 0000000..5faa6f8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/AlreadyInitializedException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class AlreadyInitializedException extends LogicException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/CommonMarkException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/CommonMarkException.php new file mode 100644 index 0000000..9fb349e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/CommonMarkException.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 League\CommonMark\Exception; + +/** + * Marker interface for all exceptions thrown by this library. + */ +interface CommonMarkException extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/IOException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/IOException.php new file mode 100644 index 0000000..09a5578 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/IOException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class IOException extends \RuntimeException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..fc67ac4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/InvalidArgumentException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class InvalidArgumentException extends \InvalidArgumentException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/LogicException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/LogicException.php new file mode 100644 index 0000000..c1d00df --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/LogicException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class LogicException extends \LogicException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/MissingDependencyException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/MissingDependencyException.php new file mode 100644 index 0000000..b8eb841 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/MissingDependencyException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class MissingDependencyException extends \RuntimeException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php b/php/libraries/composer/vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php new file mode 100644 index 0000000..0f4e399 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +final class UnexpectedEncodingException extends \RuntimeException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php new file mode 100644 index 0000000..2ef3d85 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php @@ -0,0 +1,32 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Attributes\Event\AttributesListener; +use League\CommonMark\Extension\Attributes\Parser\AttributesBlockStartParser; +use League\CommonMark\Extension\Attributes\Parser\AttributesInlineParser; +use League\CommonMark\Extension\ExtensionInterface; + +final class AttributesExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addBlockStartParser(new AttributesBlockStartParser()); + $environment->addInlineParser(new AttributesInlineParser()); + $environment->addEventListener(DocumentParsedEvent::class, [new AttributesListener(), 'processDocument']); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php new file mode 100644 index 0000000..feec8cc --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php @@ -0,0 +1,139 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Attributes\Node\Attributes; +use League\CommonMark\Extension\Attributes\Node\AttributesInline; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Node; + +final class AttributesListener +{ + private const DIRECTION_PREFIX = 'prefix'; + private const DIRECTION_SUFFIX = 'suffix'; + + public function processDocument(DocumentParsedEvent $event): void + { + foreach ($event->getDocument()->iterator() as $node) { + if (! ($node instanceof Attributes || $node instanceof AttributesInline)) { + continue; + } + + [$target, $direction] = self::findTargetAndDirection($node); + + if ($target instanceof Node) { + $parent = $target->parent(); + if ($parent instanceof ListItem && $parent->parent() instanceof ListBlock && $parent->parent()->isTight()) { + $target = $parent; + } + + if ($direction === self::DIRECTION_SUFFIX) { + $attributes = AttributesHelper::mergeAttributes($target, $node->getAttributes()); + } else { + $attributes = AttributesHelper::mergeAttributes($node->getAttributes(), $target); + } + + $target->data->set('attributes', $attributes); + } + + $node->detach(); + } + } + + /** + * @param Attributes|AttributesInline $node + * + * @return array + */ + private static function findTargetAndDirection($node): array + { + $target = null; + $direction = null; + $previous = $next = $node; + while (true) { + $previous = self::getPrevious($previous); + $next = self::getNext($next); + + if ($previous === null && $next === null) { + if (! $node->parent() instanceof FencedCode) { + $target = $node->parent(); + $direction = self::DIRECTION_SUFFIX; + } + + break; + } + + if ($node instanceof AttributesInline && ($previous === null || ($previous instanceof AbstractInline && $node->isBlock()))) { + continue; + } + + if ($previous !== null && ! self::isAttributesNode($previous)) { + $target = $previous; + $direction = self::DIRECTION_SUFFIX; + + break; + } + + if ($next !== null && ! self::isAttributesNode($next)) { + $target = $next; + $direction = self::DIRECTION_PREFIX; + + break; + } + } + + return [$target, $direction]; + } + + /** + * Get any previous block (sibling or parent) this might apply to + */ + private static function getPrevious(?Node $node = null): ?Node + { + if ($node instanceof Attributes) { + if ($node->getTarget() === Attributes::TARGET_NEXT) { + return null; + } + + if ($node->getTarget() === Attributes::TARGET_PARENT) { + return $node->parent(); + } + } + + return $node instanceof Node ? $node->previous() : null; + } + + /** + * Get any previous block (sibling or parent) this might apply to + */ + private static function getNext(?Node $node = null): ?Node + { + if ($node instanceof Attributes && $node->getTarget() !== Attributes::TARGET_NEXT) { + return null; + } + + return $node instanceof Node ? $node->next() : null; + } + + private static function isAttributesNode(Node $node): bool + { + return $node instanceof Attributes || $node instanceof AttributesInline; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php new file mode 100644 index 0000000..096f04a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php @@ -0,0 +1,65 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Attributes extends AbstractBlock +{ + public const TARGET_PARENT = 0; + public const TARGET_PREVIOUS = 1; + public const TARGET_NEXT = 2; + + /** @var array */ + private array $attributes; + + private int $target = self::TARGET_NEXT; + + /** + * @param array $attributes + */ + public function __construct(array $attributes) + { + parent::__construct(); + + $this->attributes = $attributes; + } + + /** + * @return array + */ + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @param array $attributes + */ + public function setAttributes(array $attributes): void + { + $this->attributes = $attributes; + } + + public function getTarget(): int + { + return $this->target; + } + + public function setTarget(int $target): void + { + $this->target = $target; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php new file mode 100644 index 0000000..d8b0d08 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php @@ -0,0 +1,57 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Node; + +use League\CommonMark\Node\Inline\AbstractInline; + +final class AttributesInline extends AbstractInline +{ + /** @var array */ + private array $attributes; + + private bool $block; + + /** + * @param array $attributes + */ + public function __construct(array $attributes, bool $block) + { + parent::__construct(); + + $this->attributes = $attributes; + $this->block = $block; + } + + /** + * @return array + */ + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @param array $attributes + */ + public function setAttributes(array $attributes): void + { + $this->attributes = $attributes; + } + + public function isBlock(): bool + { + return $this->block; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php new file mode 100644 index 0000000..6e0cdc6 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php @@ -0,0 +1,92 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Parser; + +use League\CommonMark\Extension\Attributes\Node\Attributes; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class AttributesBlockContinueParser extends AbstractBlockContinueParser +{ + private Attributes $block; + + private AbstractBlock $container; + + private bool $hasSubsequentLine = false; + + /** + * @param array $attributes The attributes identified by the block start parser + * @param AbstractBlock $container The node we were in when these attributes were discovered + */ + public function __construct(array $attributes, AbstractBlock $container) + { + $this->block = new Attributes($attributes); + + $this->container = $container; + } + + public function getBlock(): AbstractBlock + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + $this->hasSubsequentLine = true; + + $cursor->advanceToNextNonSpaceOrTab(); + + // Does this next line also have attributes? + $attributes = AttributesHelper::parseAttributes($cursor); + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd() && $attributes !== []) { + // It does! Merge them into what we parsed previously + $this->block->setAttributes(AttributesHelper::mergeAttributes( + $this->block->getAttributes(), + $attributes + )); + + // Tell the core parser we've consumed everything + return BlockContinue::at($cursor); + } + + // Okay, so there are no attributes on the next line + // If this next line is blank we know we can't target the next node, it must be a previous one + if ($cursor->isBlank()) { + $this->block->setTarget(Attributes::TARGET_PREVIOUS); + } + + return BlockContinue::none(); + } + + public function closeBlock(): void + { + // Attributes appearing at the very end of the document won't have any last lines to check + // so we can make that determination here + if (! $this->hasSubsequentLine) { + $this->block->setTarget(Attributes::TARGET_PREVIOUS); + } + + // We know this block must apply to the "previous" block, but that could be a sibling or parent, + // so we check the containing block to see which one it might be. + if ($this->block->getTarget() === Attributes::TARGET_PREVIOUS && $this->block->parent() === $this->container) { + $this->block->setTarget(Attributes::TARGET_PARENT); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php new file mode 100644 index 0000000..299ccd4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php @@ -0,0 +1,40 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Parser; + +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class AttributesBlockStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + $originalPosition = $cursor->getPosition(); + $attributes = AttributesHelper::parseAttributes($cursor); + + if ($attributes === [] && $originalPosition === $cursor->getPosition()) { + return BlockStart::none(); + } + + if ($cursor->getNextNonSpaceCharacter() !== null) { + return BlockStart::none(); + } + + return BlockStart::of(new AttributesBlockContinueParser($attributes, $parserState->getActiveBlockParser()->getBlock()))->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php new file mode 100644 index 0000000..26af3ca --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php @@ -0,0 +1,54 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Parser; + +use League\CommonMark\Extension\Attributes\Node\AttributesInline; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\StringContainerInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class AttributesInlineParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('{'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + $char = (string) $cursor->peek(-1); + + $attributes = AttributesHelper::parseAttributes($cursor); + if ($attributes === []) { + return false; + } + + if ($char === ' ' && ($prev = $inlineContext->getContainer()->lastChild()) instanceof StringContainerInterface) { + $prev->setLiteral(\rtrim($prev->getLiteral(), ' ')); + } + + if ($char === '') { + $cursor->advanceToNextNonSpaceOrNewline(); + } + + $node = new AttributesInline($attributes, $char === ' ' || $char === ''); + $inlineContext->getContainer()->appendChild($node); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php new file mode 100644 index 0000000..de5c111 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php @@ -0,0 +1,137 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Util; + +use League\CommonMark\Node\Node; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\RegexHelper; + +/** + * @internal + */ +final class AttributesHelper +{ + private const SINGLE_ATTRIBUTE = '\s*([.#][_a-z0-9-]+|' . RegexHelper::PARTIAL_ATTRIBUTENAME . RegexHelper::PARTIAL_ATTRIBUTEVALUESPEC . ')\s*'; + private const ATTRIBUTE_LIST = '/^{:?(' . self::SINGLE_ATTRIBUTE . ')+}/i'; + + /** + * @return array + */ + public static function parseAttributes(Cursor $cursor): array + { + $state = $cursor->saveState(); + $cursor->advanceToNextNonSpaceOrNewline(); + + // Quick check to see if we might have attributes + if ($cursor->getCharacter() !== '{') { + $cursor->restoreState($state); + + return []; + } + + // Attempt to match the entire attribute list expression + // While this is less performant than checking for '{' now and '}' later, it simplifies + // matching individual attributes since they won't need to look ahead for the closing '}' + // while dealing with the fact that attributes can technically contain curly braces. + // So we'll just match the start and end braces up front. + $attributeExpression = $cursor->match(self::ATTRIBUTE_LIST); + if ($attributeExpression === null) { + $cursor->restoreState($state); + + return []; + } + + // Trim the leading '{' or '{:' and the trailing '}' + $attributeExpression = \ltrim(\substr($attributeExpression, 1, -1), ':'); + $attributeCursor = new Cursor($attributeExpression); + + /** @var array $attributes */ + $attributes = []; + while ($attribute = \trim((string) $attributeCursor->match('/^' . self::SINGLE_ATTRIBUTE . '/i'))) { + if ($attribute[0] === '#') { + $attributes['id'] = \substr($attribute, 1); + + continue; + } + + if ($attribute[0] === '.') { + $attributes['class'][] = \substr($attribute, 1); + + continue; + } + + /** @psalm-suppress PossiblyUndefinedArrayOffset */ + [$name, $value] = \explode('=', $attribute, 2); + + $first = $value[0]; + $last = \substr($value, -1); + if (($first === '"' && $last === '"') || ($first === "'" && $last === "'") && \strlen($value) > 1) { + $value = \substr($value, 1, -1); + } + + if (\strtolower(\trim($name)) === 'class') { + foreach (\array_filter(\explode(' ', \trim($value))) as $class) { + $attributes['class'][] = $class; + } + } else { + $attributes[\trim($name)] = \trim($value); + } + } + + if (isset($attributes['class'])) { + $attributes['class'] = \implode(' ', (array) $attributes['class']); + } + + return $attributes; + } + + /** + * @param Node|array $attributes1 + * @param Node|array $attributes2 + * + * @return array + */ + public static function mergeAttributes($attributes1, $attributes2): array + { + $attributes = []; + foreach ([$attributes1, $attributes2] as $arg) { + if ($arg instanceof Node) { + $arg = $arg->data->get('attributes'); + } + + /** @var array $arg */ + $arg = (array) $arg; + if (isset($arg['class'])) { + if (\is_string($arg['class'])) { + $arg['class'] = \array_filter(\explode(' ', \trim($arg['class']))); + } + + foreach ($arg['class'] as $class) { + $attributes['class'][] = $class; + } + + unset($arg['class']); + } + + $attributes = \array_merge($attributes, $arg); + } + + if (isset($attributes['class'])) { + $attributes['class'] = \implode(' ', $attributes['class']); + } + + return $attributes; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.php new file mode 100644 index 0000000..3516ebb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.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 League\CommonMark\Extension\Autolink; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ExtensionInterface; + +final class AutolinkExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addInlineParser(new EmailAutolinkParser()); + $environment->addInlineParser(new UrlAutolinkParser()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.php new file mode 100644 index 0000000..15a7d34 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.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 League\CommonMark\Extension\Autolink; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class EmailAutolinkParser implements InlineParserInterface +{ + private const REGEX = '[A-Za-z0-9.\-_+]+@[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_.]+'; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(self::REGEX); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $email = $inlineContext->getFullMatch(); + // The last character cannot be - or _ + if (\in_array(\substr($email, -1), ['-', '_'], true)) { + return false; + } + + // Does the URL end with punctuation that should be stripped? + if (\substr($email, -1) === '.') { + $email = \substr($email, 0, -1); + } + + $inlineContext->getCursor()->advanceBy(\strlen($email)); + $inlineContext->getContainer()->appendChild(new Link('mailto:' . $email, $email)); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php new file mode 100644 index 0000000..f44da33 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php @@ -0,0 +1,153 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Autolink; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class UrlAutolinkParser implements InlineParserInterface +{ + private const ALLOWED_AFTER = [null, ' ', "\t", "\n", "\x0b", "\x0c", "\x0d", '*', '_', '~', '(']; + + // RegEx adapted from https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Validator/Constraints/UrlValidator.php + private const REGEX = '~ + ( + # Must start with a supported scheme + auth, or "www" + (?: + (?:%s):// # protocol + (?:(?:(?:[\_\.\pL\pN-]|%%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%%[0-9A-Fa-f]{2})+)@)? # basic auth + |www\.) + (?: + (?: + (?:xn--[a-z0-9-]++\.)*+xn--[a-z0-9-]++ # a domain name using punycode + | + (?:[\pL\pN\pS\pM\-\_]++\.)+[\pL\pN\pM]++ # a multi-level domain name + | + [a-z0-9\-\_]++ # a single-level domain name + )\.? + | # or + \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address + | # or + \[ + (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) + \] # an IPv6 address + ) + (?::[0-9]+)? # a port (optional) + (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%%[0-9A-Fa-f]{2})* )* # a path + (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a query (optional) + (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a fragment (optional) + )~ixu'; + + /** + * @var string[] + * + * @psalm-readonly + */ + private array $prefixes = ['www']; + + /** + * @psalm-var non-empty-string + * + * @psalm-readonly + */ + private string $finalRegex; + + /** + * @param array $allowedProtocols + */ + public function __construct(array $allowedProtocols = ['http', 'https', 'ftp']) + { + /** + * @psalm-suppress PropertyTypeCoercion + */ + $this->finalRegex = \sprintf(self::REGEX, \implode('|', $allowedProtocols)); + + foreach ($allowedProtocols as $protocol) { + $this->prefixes[] = $protocol . '://'; + } + } + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf(...$this->prefixes); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + + // Autolinks can only come at the beginning of a line, after whitespace, or certain delimiting characters + $previousChar = $cursor->peek(-1); + if (! \in_array($previousChar, self::ALLOWED_AFTER, true)) { + return false; + } + + // Check if we have a valid URL + if (! \preg_match($this->finalRegex, $cursor->getRemainder(), $matches)) { + return false; + } + + $url = $matches[0]; + + // Does the URL end with punctuation that should be stripped? + if (\preg_match('/(.+?)([?!.,:*_~]+)$/', $url, $matches)) { + // Add the punctuation later + $url = $matches[1]; + } + + // Does the URL end with something that looks like an entity reference? + if (\preg_match('/(.+)(&[A-Za-z0-9]+;)$/', $url, $matches)) { + $url = $matches[1]; + } + + // Does the URL need unmatched parens chopped off? + if (\substr($url, -1) === ')' && ($diff = self::diffParens($url)) > 0) { + $url = \substr($url, 0, -$diff); + } + + $cursor->advanceBy(\mb_strlen($url, 'UTF-8')); + + // Auto-prefix 'http://' onto 'www' URLs + if (\substr($url, 0, 4) === 'www.') { + $inlineContext->getContainer()->appendChild(new Link('http://' . $url, $url)); + + return true; + } + + $inlineContext->getContainer()->appendChild(new Link($url, $url)); + + return true; + } + + /** + * @psalm-pure + */ + private static function diffParens(string $content): int + { + // Scan the entire autolink for the total number of parentheses. + // If there is a greater number of closing parentheses than opening ones, + // we don’t consider ANY of the last characters as part of the autolink, + // in order to facilitate including an autolink inside a parenthesis. + \preg_match_all('/[()]/', $content, $matches); + + $charCount = ['(' => 0, ')' => 0]; + foreach ($matches[0] as $char) { + $charCount[$char]++; + } + + return $charCount[')'] - $charCount['(']; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php new file mode 100644 index 0000000..91f7a22 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php @@ -0,0 +1,92 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\CommonMark\Delimiter\Processor\EmphasisDelimiterProcessor; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Node as CoreNode; +use League\CommonMark\Parser as CoreParser; +use League\CommonMark\Renderer as CoreRenderer; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class CommonMarkCoreExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('commonmark', Expect::structure([ + 'use_asterisk' => Expect::bool(true), + 'use_underscore' => Expect::bool(true), + 'enable_strong' => Expect::bool(true), + 'enable_em' => Expect::bool(true), + 'unordered_list_markers' => Expect::listOf('string')->min(1)->default(['*', '+', '-'])->mergeDefaults(false), + ])); + } + + // phpcs:disable Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma,Squiz.WhiteSpace.SemicolonSpacing.Incorrect + public function register(EnvironmentBuilderInterface $environment): void + { + $environment + ->addBlockStartParser(new Parser\Block\BlockQuoteStartParser(), 70) + ->addBlockStartParser(new Parser\Block\HeadingStartParser(), 60) + ->addBlockStartParser(new Parser\Block\FencedCodeStartParser(), 50) + ->addBlockStartParser(new Parser\Block\HtmlBlockStartParser(), 40) + ->addBlockStartParser(new Parser\Block\ThematicBreakStartParser(), 20) + ->addBlockStartParser(new Parser\Block\ListBlockStartParser(), 10) + ->addBlockStartParser(new Parser\Block\IndentedCodeStartParser(), -100) + + ->addInlineParser(new CoreParser\Inline\NewlineParser(), 200) + ->addInlineParser(new Parser\Inline\BacktickParser(), 150) + ->addInlineParser(new Parser\Inline\EscapableParser(), 80) + ->addInlineParser(new Parser\Inline\EntityParser(), 70) + ->addInlineParser(new Parser\Inline\AutolinkParser(), 50) + ->addInlineParser(new Parser\Inline\HtmlInlineParser(), 40) + ->addInlineParser(new Parser\Inline\CloseBracketParser(), 30) + ->addInlineParser(new Parser\Inline\OpenBracketParser(), 20) + ->addInlineParser(new Parser\Inline\BangParser(), 10) + + ->addRenderer(Node\Block\BlockQuote::class, new Renderer\Block\BlockQuoteRenderer(), 0) + ->addRenderer(CoreNode\Block\Document::class, new CoreRenderer\Block\DocumentRenderer(), 0) + ->addRenderer(Node\Block\FencedCode::class, new Renderer\Block\FencedCodeRenderer(), 0) + ->addRenderer(Node\Block\Heading::class, new Renderer\Block\HeadingRenderer(), 0) + ->addRenderer(Node\Block\HtmlBlock::class, new Renderer\Block\HtmlBlockRenderer(), 0) + ->addRenderer(Node\Block\IndentedCode::class, new Renderer\Block\IndentedCodeRenderer(), 0) + ->addRenderer(Node\Block\ListBlock::class, new Renderer\Block\ListBlockRenderer(), 0) + ->addRenderer(Node\Block\ListItem::class, new Renderer\Block\ListItemRenderer(), 0) + ->addRenderer(CoreNode\Block\Paragraph::class, new CoreRenderer\Block\ParagraphRenderer(), 0) + ->addRenderer(Node\Block\ThematicBreak::class, new Renderer\Block\ThematicBreakRenderer(), 0) + + ->addRenderer(Node\Inline\Code::class, new Renderer\Inline\CodeRenderer(), 0) + ->addRenderer(Node\Inline\Emphasis::class, new Renderer\Inline\EmphasisRenderer(), 0) + ->addRenderer(Node\Inline\HtmlInline::class, new Renderer\Inline\HtmlInlineRenderer(), 0) + ->addRenderer(Node\Inline\Image::class, new Renderer\Inline\ImageRenderer(), 0) + ->addRenderer(Node\Inline\Link::class, new Renderer\Inline\LinkRenderer(), 0) + ->addRenderer(CoreNode\Inline\Newline::class, new CoreRenderer\Inline\NewlineRenderer(), 0) + ->addRenderer(Node\Inline\Strong::class, new Renderer\Inline\StrongRenderer(), 0) + ->addRenderer(CoreNode\Inline\Text::class, new CoreRenderer\Inline\TextRenderer(), 0) + ; + + if ($environment->getConfiguration()->get('commonmark/use_asterisk')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('*')); + } + + if ($environment->getConfiguration()->get('commonmark/use_underscore')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('_')); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php new file mode 100644 index 0000000..84b46ee --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php @@ -0,0 +1,108 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Extension\CommonMark\Node\Inline\Emphasis; +use League\CommonMark\Extension\CommonMark\Node\Inline\Strong; +use League\CommonMark\Node\Inline\AbstractStringContainer; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class EmphasisDelimiterProcessor implements DelimiterProcessorInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly */ + private string $char; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param string $char The emphasis character to use (typically '*' or '_') + */ + public function __construct(string $char) + { + $this->char = $char; + } + + public function getOpeningCharacter(): string + { + return $this->char; + } + + public function getClosingCharacter(): string + { + return $this->char; + } + + public function getMinLength(): int + { + return 1; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + // "Multiple of 3" rule for internal delimiter runs + if (($opener->canClose() || $closer->canOpen()) && $closer->getOriginalLength() % 3 !== 0 && ($opener->getOriginalLength() + $closer->getOriginalLength()) % 3 === 0) { + return 0; + } + + // Calculate actual number of delimiters used from this closer + if ($opener->getLength() >= 2 && $closer->getLength() >= 2) { + if ($this->config->get('commonmark/enable_strong')) { + return 2; + } + + return 0; + } + + if ($this->config->get('commonmark/enable_em')) { + return 1; + } + + return 0; + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + if ($delimiterUse === 1) { + $emphasis = new Emphasis($this->char); + } elseif ($delimiterUse === 2) { + $emphasis = new Strong($this->char . $this->char); + } else { + return; + } + + $next = $opener->next(); + while ($next !== null && $next !== $closer) { + $tmp = $next->next(); + $emphasis->appendChild($next); + $next = $tmp; + } + + $opener->insertAfter($emphasis); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.php new file mode 100644 index 0000000..11094b9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.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 League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +class BlockQuote extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php new file mode 100644 index 0000000..b50b407 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php @@ -0,0 +1,100 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\StringContainerInterface; + +final class FencedCode extends AbstractBlock implements StringContainerInterface +{ + private ?string $info = null; + + private string $literal = ''; + + private int $length; + + private string $char; + + private int $offset; + + public function __construct(int $length, string $char, int $offset) + { + parent::__construct(); + + $this->length = $length; + $this->char = $char; + $this->offset = $offset; + } + + public function getInfo(): ?string + { + return $this->info; + } + + /** + * @return string[] + */ + public function getInfoWords(): array + { + return \preg_split('/\s+/', $this->info ?? '') ?: []; + } + + public function setInfo(string $info): void + { + $this->info = $info; + } + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } + + public function getChar(): string + { + return $this->char; + } + + public function setChar(string $char): void + { + $this->char = $char; + } + + public function getLength(): int + { + return $this->length; + } + + public function setLength(int $length): void + { + $this->length = $length; + } + + public function getOffset(): int + { + return $this->offset; + } + + public function setOffset(int $offset): void + { + $this->offset = $offset; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php new file mode 100644 index 0000000..1cf1184 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php @@ -0,0 +1,41 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Heading extends AbstractBlock +{ + private int $level; + + public function __construct(int $level) + { + parent::__construct(); + + $this->level = $level; + } + + public function getLevel(): int + { + return $this->level; + } + + public function setLevel(int $level): void + { + $this->level = $level; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php new file mode 100644 index 0000000..9879a89 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\RawMarkupContainerInterface; + +final class HtmlBlock extends AbstractBlock implements RawMarkupContainerInterface +{ + // Any changes to these constants should be reflected in .phpstorm.meta.php + public const TYPE_1_CODE_CONTAINER = 1; + public const TYPE_2_COMMENT = 2; + public const TYPE_3 = 3; + public const TYPE_4 = 4; + public const TYPE_5_CDATA = 5; + public const TYPE_6_BLOCK_ELEMENT = 6; + public const TYPE_7_MISC_ELEMENT = 7; + + /** + * @psalm-var self::TYPE_* $type + * @phpstan-var self::TYPE_* $type + */ + private int $type; + + private string $literal = ''; + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function __construct(int $type) + { + parent::__construct(); + + $this->type = $type; + } + + /** + * @psalm-return self::TYPE_* + * + * @phpstan-return self::TYPE_* + */ + public function getType(): int + { + return $this->type; + } + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function setType(int $type): void + { + $this->type = $type; + } + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php new file mode 100644 index 0000000..d18be15 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\StringContainerInterface; + +final class IndentedCode extends AbstractBlock implements StringContainerInterface +{ + private string $literal = ''; + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php new file mode 100644 index 0000000..74f9ca8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\TightBlockInterface; + +class ListBlock extends AbstractBlock implements TightBlockInterface +{ + public const TYPE_BULLET = 'bullet'; + public const TYPE_ORDERED = 'ordered'; + + public const DELIM_PERIOD = 'period'; + public const DELIM_PAREN = 'paren'; + + protected bool $tight = false; + + /** @psalm-readonly */ + protected ListData $listData; + + public function __construct(ListData $listData) + { + parent::__construct(); + + $this->listData = $listData; + } + + public function getListData(): ListData + { + return $this->listData; + } + + public function isTight(): bool + { + return $this->tight; + } + + public function setTight(bool $tight): void + { + $this->tight = $tight; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php new file mode 100644 index 0000000..7108a93 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php @@ -0,0 +1,47 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +class ListData +{ + public ?int $start = null; + + public int $padding = 0; + + /** + * @psalm-var ListBlock::TYPE_* + * @phpstan-var ListBlock::TYPE_* + */ + public string $type; + + /** + * @psalm-var ListBlock::DELIM_*|null + * @phpstan-var ListBlock::DELIM_*|null + */ + public ?string $delimiter = null; + + public ?string $bulletChar = null; + + public int $markerOffset; + + public function equals(ListData $data): bool + { + return $this->type === $data->type && + $this->delimiter === $data->delimiter && + $this->bulletChar === $data->bulletChar; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php new file mode 100644 index 0000000..f136b7e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php @@ -0,0 +1,37 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +class ListItem extends AbstractBlock +{ + /** @psalm-readonly */ + protected ListData $listData; + + public function __construct(ListData $listData) + { + parent::__construct(); + + $this->listData = $listData; + } + + public function getListData(): ListData + { + return $this->listData; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.php new file mode 100644 index 0000000..bb6cea0 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.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 League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +class ThematicBreak extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php new file mode 100644 index 0000000..dc0ed0a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php @@ -0,0 +1,41 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractInline; + +abstract class AbstractWebResource extends AbstractInline +{ + protected string $url; + + public function __construct(string $url) + { + parent::__construct(); + + $this->url = $url; + } + + public function getUrl(): string + { + return $this->url; + } + + public function setUrl(string $url): void + { + $this->url = $url; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php new file mode 100644 index 0000000..3a6aca2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php @@ -0,0 +1,23 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +class Code extends AbstractStringContainer +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php new file mode 100644 index 0000000..fab6869 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Emphasis extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '_') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php new file mode 100644 index 0000000..8594a06 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php @@ -0,0 +1,24 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractStringContainer; +use League\CommonMark\Node\RawMarkupContainerInterface; + +final class HtmlInline extends AbstractStringContainer implements RawMarkupContainerInterface +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php new file mode 100644 index 0000000..20e3f87 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php @@ -0,0 +1,49 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\Text; + +class Image extends AbstractWebResource +{ + protected ?string $title = null; + + public function __construct(string $url, ?string $label = null, ?string $title = null) + { + parent::__construct($url); + + if ($label !== null && $label !== '') { + $this->appendChild(new Text($label)); + } + + $this->title = $title; + } + + public function getTitle(): ?string + { + if ($this->title === '') { + return null; + } + + return $this->title; + } + + public function setTitle(?string $title): void + { + $this->title = $title; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php new file mode 100644 index 0000000..76d5609 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php @@ -0,0 +1,49 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\Text; + +class Link extends AbstractWebResource +{ + protected ?string $title = null; + + public function __construct(string $url, ?string $label = null, ?string $title = null) + { + parent::__construct($url); + + if ($label !== null && $label !== '') { + $this->appendChild(new Text($label)); + } + + $this->title = $title; + } + + public function getTitle(): ?string + { + if ($this->title === '') { + return null; + } + + return $this->title; + } + + public function setTitle(?string $title): void + { + $this->title = $title; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php new file mode 100644 index 0000000..827960f --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Strong extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '**') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.php new file mode 100644 index 0000000..78db6c5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\BlockQuote; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class BlockQuoteParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private BlockQuote $block; + + public function __construct() + { + $this->block = new BlockQuote(); + } + + public function getBlock(): BlockQuote + { + return $this->block; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if (! $cursor->isIndented() && $cursor->getNextNonSpaceCharacter() === '>') { + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(1); + $cursor->advanceBySpaceOrTab(); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.php new file mode 100644 index 0000000..de9a6bc --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class BlockQuoteStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + if ($cursor->getNextNonSpaceCharacter() !== '>') { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(1); + $cursor->advanceBySpaceOrTab(); + + return BlockStart::of(new BlockQuoteParser())->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.php new file mode 100644 index 0000000..88572c7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\ArrayCollection; +use League\CommonMark\Util\RegexHelper; + +final class FencedCodeParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private FencedCode $block; + + /** @var ArrayCollection */ + private ArrayCollection $strings; + + public function __construct(int $fenceLength, string $fenceChar, int $fenceOffset) + { + $this->block = new FencedCode($fenceLength, $fenceChar, $fenceOffset); + $this->strings = new ArrayCollection(); + } + + public function getBlock(): FencedCode + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + // Check for closing code fence + if (! $cursor->isIndented() && $cursor->getNextNonSpaceCharacter() === $this->block->getChar()) { + $match = RegexHelper::matchFirst('/^(?:`{3,}|~{3,})(?= *$)/', $cursor->getLine(), $cursor->getNextNonSpacePosition()); + if ($match !== null && \strlen($match[0]) >= $this->block->getLength()) { + // closing fence - we're at end of line, so we can finalize now + return BlockContinue::finished(); + } + } + + // Skip optional spaces of fence offset + // Optimization: don't attempt to match if we're at a non-space position + if ($cursor->getNextNonSpacePosition() > $cursor->getPosition()) { + $cursor->match('/^ {0,' . $this->block->getOffset() . '}/'); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + $this->strings[] = $line; + } + + public function closeBlock(): void + { + // first line becomes info string + $firstLine = $this->strings->first(); + if ($firstLine === false) { + $firstLine = ''; + } + + $this->block->setInfo(RegexHelper::unescape(\trim($firstLine))); + + if ($this->strings->count() === 1) { + $this->block->setLiteral(''); + } else { + $this->block->setLiteral(\implode("\n", $this->strings->slice(1)) . "\n"); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.php new file mode 100644 index 0000000..be1b1dc --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class FencedCodeStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || ! \in_array($cursor->getNextNonSpaceCharacter(), ['`', '~'], true)) { + return BlockStart::none(); + } + + $indent = $cursor->getIndent(); + $fence = $cursor->match('/^[ \t]*(?:`{3,}(?!.*`)|~{3,})/'); + if ($fence === null) { + return BlockStart::none(); + } + + // fenced code block + $fence = \ltrim($fence, " \t"); + + return BlockStart::of(new FencedCodeParser(\strlen($fence), $fence[0], $indent))->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.php new file mode 100644 index 0000000..c3e3108 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; + +final class HeadingParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + /** @psalm-readonly */ + private Heading $block; + + private string $content; + + public function __construct(int $level, string $content) + { + $this->block = new Heading($level); + $this->content = $content; + } + + public function getBlock(): Heading + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::none(); + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + $inlineParser->parse($this->content, $this->block); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php new file mode 100644 index 0000000..404f403 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +class HeadingStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || ! \in_array($cursor->getNextNonSpaceCharacter(), ['#', '-', '='], true)) { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + + if ($atxHeading = self::getAtxHeader($cursor)) { + return BlockStart::of($atxHeading)->at($cursor); + } + + $setextHeadingLevel = self::getSetextHeadingLevel($cursor); + if ($setextHeadingLevel > 0) { + $content = $parserState->getParagraphContent(); + if ($content !== null) { + $cursor->advanceToEnd(); + + return BlockStart::of(new HeadingParser($setextHeadingLevel, $content)) + ->at($cursor) + ->replaceActiveBlockParser(); + } + } + + return BlockStart::none(); + } + + private static function getAtxHeader(Cursor $cursor): ?HeadingParser + { + $match = RegexHelper::matchFirst('/^#{1,6}(?:[ \t]+|$)/', $cursor->getRemainder()); + if (! $match) { + return null; + } + + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(\strlen($match[0])); + + $level = \strlen(\trim($match[0])); + $str = $cursor->getRemainder(); + $str = \preg_replace('/^[ \t]*#+[ \t]*$/', '', $str); + \assert(\is_string($str)); + $str = \preg_replace('/[ \t]+#+[ \t]*$/', '', $str); + \assert(\is_string($str)); + + return new HeadingParser($level, $str); + } + + private static function getSetextHeadingLevel(Cursor $cursor): int + { + $match = RegexHelper::matchFirst('/^(?:=+|-+)[ \t]*$/', $cursor->getRemainder()); + if ($match === null) { + return 0; + } + + return $match[0][0] === '=' ? 1 : 2; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php new file mode 100644 index 0000000..6778676 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\RegexHelper; + +final class HtmlBlockParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private HtmlBlock $block; + + private string $content = ''; + + private bool $finished = false; + + /** + * @psalm-param HtmlBlock::TYPE_* $blockType + * + * @phpstan-param HtmlBlock::TYPE_* $blockType + */ + public function __construct(int $blockType) + { + $this->block = new HtmlBlock($blockType); + } + + public function getBlock(): HtmlBlock + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($this->finished) { + return BlockContinue::none(); + } + + if ($cursor->isBlank() && \in_array($this->block->getType(), [HtmlBlock::TYPE_6_BLOCK_ELEMENT, HtmlBlock::TYPE_7_MISC_ELEMENT], true)) { + return BlockContinue::none(); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + if ($this->content !== '') { + $this->content .= "\n"; + } + + $this->content .= $line; + + // Check for end condition + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($this->block->getType() <= HtmlBlock::TYPE_5_CDATA) { + if (\preg_match(RegexHelper::getHtmlBlockCloseRegex($this->block->getType()), $line) === 1) { + $this->finished = true; + } + } + } + + public function closeBlock(): void + { + $this->block->setLiteral($this->content); + $this->content = ''; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php new file mode 100644 index 0000000..bcef0af --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +final class HtmlBlockStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || $cursor->getNextNonSpaceCharacter() !== '<') { + return BlockStart::none(); + } + + $tmpCursor = clone $cursor; + $tmpCursor->advanceToNextNonSpaceOrTab(); + $line = $tmpCursor->getRemainder(); + + for ($blockType = 1; $blockType <= 7; $blockType++) { + /** @psalm-var HtmlBlock::TYPE_* $blockType */ + /** @phpstan-var HtmlBlock::TYPE_* $blockType */ + $match = RegexHelper::matchAt( + RegexHelper::getHtmlBlockOpenRegex($blockType), + $line + ); + + if ($match !== null && ($blockType < 7 || $this->isType7BlockAllowed($cursor, $parserState))) { + return BlockStart::of(new HtmlBlockParser($blockType))->at($cursor); + } + } + + return BlockStart::none(); + } + + private function isType7BlockAllowed(Cursor $cursor, MarkdownParserStateInterface $parserState): bool + { + // Type 7 blocks can't interrupt paragraphs + if ($parserState->getLastMatchedBlockParser()->getBlock() instanceof Paragraph) { + return false; + } + + // Even lazy ones + return ! $parserState->getActiveBlockParser()->canHaveLazyContinuationLines(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.php new file mode 100644 index 0000000..b7c425a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\ArrayCollection; + +final class IndentedCodeParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private IndentedCode $block; + + /** @var ArrayCollection */ + private ArrayCollection $strings; + + public function __construct() + { + $this->block = new IndentedCode(); + $this->strings = new ArrayCollection(); + } + + public function getBlock(): IndentedCode + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isIndented()) { + $cursor->advanceBy(Cursor::INDENT_LEVEL, true); + + return BlockContinue::at($cursor); + } + + if ($cursor->isBlank()) { + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } + + public function addLine(string $line): void + { + $this->strings[] = $line; + } + + public function closeBlock(): void + { + $reversed = \array_reverse($this->strings->toArray(), true); + foreach ($reversed as $index => $line) { + if ($line !== '' && $line !== "\n" && ! \preg_match('/^(\n *)$/', $line)) { + break; + } + + unset($reversed[$index]); + } + + $fixed = \array_reverse($reversed); + $tmp = \implode("\n", $fixed); + if (\substr($tmp, -1) !== "\n") { + $tmp .= "\n"; + } + + $this->block->setLiteral($tmp); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php new file mode 100644 index 0000000..bea4bde --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class IndentedCodeStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if (! $cursor->isIndented()) { + return BlockStart::none(); + } + + if ($parserState->getActiveBlockParser()->getBlock() instanceof Paragraph) { + return BlockStart::none(); + } + + if ($cursor->isBlank()) { + return BlockStart::none(); + } + + $cursor->advanceBy(Cursor::INDENT_LEVEL, true); + + return BlockStart::of(new IndentedCodeParser())->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php new file mode 100644 index 0000000..4dffb7a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class ListBlockParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private ListBlock $block; + + private bool $hadBlankLine = false; + + private int $linesAfterBlank = 0; + + public function __construct(ListData $listData) + { + $this->block = new ListBlock($listData); + } + + public function getBlock(): ListBlock + { + return $this->block; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + if (! $childBlock instanceof ListItem) { + return false; + } + + // Another list item is being added to this list block. + // If the previous line was blank, that means this list + // block is "loose" (not tight). + if ($this->hadBlankLine && $this->linesAfterBlank === 1) { + $this->block->setTight(false); + $this->hadBlankLine = false; + } + + return true; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + $this->hadBlankLine = true; + $this->linesAfterBlank = 0; + } elseif ($this->hadBlankLine) { + $this->linesAfterBlank++; + } + + // List blocks themselves don't have any markers, only list items. So try to stay in the list. + // If there is a block start other than list item, canContain makes sure that this list is closed. + return BlockContinue::at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php new file mode 100644 index 0000000..65b4535 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php @@ -0,0 +1,153 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class ListBlockStartParser implements BlockStartParserInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ?ConfigurationInterface $config = null; + + /** + * @psalm-var non-empty-string|null + * + * @psalm-readonly-allow-private-mutation + */ + private ?string $listMarkerRegex = null; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + $listData = $this->parseList($cursor, $parserState->getParagraphContent() !== null); + if ($listData === null) { + return BlockStart::none(); + } + + $listItemParser = new ListItemParser($listData); + + // prepend the list block if needed + $matched = $parserState->getLastMatchedBlockParser(); + if (! ($matched instanceof ListBlockParser) || ! $listData->equals($matched->getBlock()->getListData())) { + $listBlockParser = new ListBlockParser($listData); + // We start out with assuming a list is tight. If we find a blank line, we set it to loose later. + $listBlockParser->getBlock()->setTight(true); + + return BlockStart::of($listBlockParser, $listItemParser)->at($cursor); + } + + return BlockStart::of($listItemParser)->at($cursor); + } + + private function parseList(Cursor $cursor, bool $inParagraph): ?ListData + { + $indent = $cursor->getIndent(); + + $tmpCursor = clone $cursor; + $tmpCursor->advanceToNextNonSpaceOrTab(); + $rest = $tmpCursor->getRemainder(); + + if (\preg_match($this->listMarkerRegex ?? $this->generateListMarkerRegex(), $rest) === 1) { + $data = new ListData(); + $data->markerOffset = $indent; + $data->type = ListBlock::TYPE_BULLET; + $data->delimiter = null; + $data->bulletChar = $rest[0]; + $markerLength = 1; + } elseif (($matches = RegexHelper::matchFirst('/^(\d{1,9})([.)])/', $rest)) && (! $inParagraph || $matches[1] === '1')) { + $data = new ListData(); + $data->markerOffset = $indent; + $data->type = ListBlock::TYPE_ORDERED; + $data->start = (int) $matches[1]; + $data->delimiter = $matches[2] === '.' ? ListBlock::DELIM_PERIOD : ListBlock::DELIM_PAREN; + $data->bulletChar = null; + $markerLength = \strlen($matches[0]); + } else { + return null; + } + + // Make sure we have spaces after + $nextChar = $tmpCursor->peek($markerLength); + if (! ($nextChar === null || $nextChar === "\t" || $nextChar === ' ')) { + return null; + } + + // If it interrupts paragraph, make sure first line isn't blank + if ($inParagraph && ! RegexHelper::matchAt(RegexHelper::REGEX_NON_SPACE, $rest, $markerLength)) { + return null; + } + + $cursor->advanceToNextNonSpaceOrTab(); // to start of marker + $cursor->advanceBy($markerLength, true); // to end of marker + $data->padding = self::calculateListMarkerPadding($cursor, $markerLength); + + return $data; + } + + private static function calculateListMarkerPadding(Cursor $cursor, int $markerLength): int + { + $start = $cursor->saveState(); + $spacesStartCol = $cursor->getColumn(); + + while ($cursor->getColumn() - $spacesStartCol < 5) { + if (! $cursor->advanceBySpaceOrTab()) { + break; + } + } + + $blankItem = $cursor->peek() === null; + $spacesAfterMarker = $cursor->getColumn() - $spacesStartCol; + + if ($spacesAfterMarker >= 5 || $spacesAfterMarker < 1 || $blankItem) { + $cursor->restoreState($start); + $cursor->advanceBySpaceOrTab(); + + return $markerLength + 1; + } + + return $markerLength + $spacesAfterMarker; + } + + /** + * @psalm-return non-empty-string + */ + private function generateListMarkerRegex(): string + { + // No configuration given - use the defaults + if ($this->config === null) { + return $this->listMarkerRegex = '/^[*+-]/'; + } + + $markers = $this->config->get('commonmark/unordered_list_markers'); + \assert(\is_array($markers)); + + return $this->listMarkerRegex = '/^[' . \preg_quote(\implode('', $markers), '/') . ']/'; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.php new file mode 100644 index 0000000..73b98be --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class ListItemParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private ListItem $block; + + private bool $hadBlankLine = false; + + public function __construct(ListData $listData) + { + $this->block = new ListItem($listData); + } + + public function getBlock(): ListItem + { + return $this->block; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + if ($this->hadBlankLine) { + // We saw a blank line in this list item, that means the list block is loose. + // + // spec: if any of its constituent list items directly contain two block-level elements with a blank line + // between them + $parent = $this->block->parent(); + if ($parent instanceof ListBlock) { + $parent->setTight(false); + } + } + + return true; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + if ($this->block->firstChild() === null) { + // Blank line after empty list item + return BlockContinue::none(); + } + + $activeBlock = $activeBlockParser->getBlock(); + // If the active block is a code block, blank lines in it should not affect if the list is tight. + $this->hadBlankLine = $activeBlock instanceof Paragraph || $activeBlock instanceof ListItem; + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockContinue::at($cursor); + } + + $contentIndent = $this->block->getListData()->markerOffset + $this->getBlock()->getListData()->padding; + if ($cursor->getIndent() >= $contentIndent) { + $cursor->advanceBy($contentIndent, true); + + return BlockContinue::at($cursor); + } + + // Note: We'll hit this case for lazy continuation lines, they will get added later. + return BlockContinue::none(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php new file mode 100644 index 0000000..fb46637 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ThematicBreak; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class ThematicBreakParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private ThematicBreak $block; + + public function __construct() + { + $this->block = new ThematicBreak(); + } + + public function getBlock(): ThematicBreak + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + // a horizontal rule can never container > 1 line, so fail to match + return BlockContinue::none(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.php new file mode 100644 index 0000000..ba7ddf3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.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 League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +final class ThematicBreakStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + $match = RegexHelper::matchAt(RegexHelper::REGEX_THEMATIC_BREAK, $cursor->getLine(), $cursor->getNextNonSpacePosition()); + if ($match === null) { + return BlockStart::none(); + } + + // Advance to the end of the string, consuming the entire line (of the thematic break) + $cursor->advanceToEnd(); + + return BlockStart::of(new ThematicBreakParser())->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php new file mode 100644 index 0000000..810769d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php @@ -0,0 +1,54 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\UrlEncoder; + +final class AutolinkParser implements InlineParserInterface +{ + private const EMAIL_REGEX = '<([a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>'; + private const OTHER_LINK_REGEX = '<([A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*)>'; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(self::EMAIL_REGEX . '|' . self::OTHER_LINK_REGEX); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $matches = $inlineContext->getMatches(); + + if ($matches[1] !== '') { + $inlineContext->getContainer()->appendChild(new Link('mailto:' . UrlEncoder::unescapeAndEncode($matches[1]), $matches[1])); + + return true; + } + + if ($matches[2] !== '') { + $inlineContext->getContainer()->appendChild(new Link(UrlEncoder::unescapeAndEncode($matches[2]), $matches[2])); + + return true; + } + + return false; // This should never happen + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php new file mode 100644 index 0000000..9618f2e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php @@ -0,0 +1,70 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Code; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class BacktickParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('`+'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $ticks = $inlineContext->getFullMatch(); + $cursor = $inlineContext->getCursor(); + $cursor->advanceBy($inlineContext->getFullMatchLength()); + + $currentPosition = $cursor->getPosition(); + $previousState = $cursor->saveState(); + + while ($matchingTicks = $cursor->match('/`+/m')) { + if ($matchingTicks !== $ticks) { + continue; + } + + $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks)); + + $c = \preg_replace('/\n/m', ' ', $code) ?? ''; + + if ( + $c !== '' && + $c[0] === ' ' && + \substr($c, -1, 1) === ' ' && + \preg_match('/[^ ]/', $c) + ) { + $c = \substr($c, 1, -1); + } + + $inlineContext->getContainer()->appendChild(new Code($c)); + + return true; + } + + // If we got here, we didn't match a closing backtick sequence + $cursor->restoreState($previousState); + $inlineContext->getContainer()->appendChild(new Text($ticks)); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php new file mode 100644 index 0000000..8a9e1bd --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php @@ -0,0 +1,46 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Delimiter\Delimiter; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class BangParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('!['); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + $cursor->advanceBy(2); + + $node = new Text('![', ['delim' => true]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack for this opener + $delimiter = new Delimiter('!', 1, $node, true, false, $cursor->getPosition()); + $inlineContext->getDelimiterStack()->push($delimiter); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php new file mode 100644 index 0000000..16f24dc --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php @@ -0,0 +1,212 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Extension\CommonMark\Node\Inline\AbstractWebResource; +use League\CommonMark\Extension\CommonMark\Node\Inline\Image; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceMapInterface; +use League\CommonMark\Util\LinkParserHelper; +use League\CommonMark\Util\RegexHelper; + +final class CloseBracketParser implements InlineParserInterface, EnvironmentAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private EnvironmentInterface $environment; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string(']'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + // Look through stack of delimiters for a [ or ! + $opener = $inlineContext->getDelimiterStack()->searchByCharacter(['[', '!']); + if ($opener === null) { + return false; + } + + if (! $opener->isActive()) { + // no matched opener; remove from emphasis stack + $inlineContext->getDelimiterStack()->removeDelimiter($opener); + + return false; + } + + $cursor = $inlineContext->getCursor(); + + $startPos = $cursor->getPosition(); + $previousState = $cursor->saveState(); + + $cursor->advanceBy(1); + + // Check to see if we have a link/image + + // Inline link? + if ($result = $this->tryParseInlineLinkAndTitle($cursor)) { + $link = $result; + } elseif ($link = $this->tryParseReference($cursor, $inlineContext->getReferenceMap(), $opener->getIndex(), $startPos)) { + $reference = $link; + $link = ['url' => $link->getDestination(), 'title' => $link->getTitle()]; + } else { + // No match + $inlineContext->getDelimiterStack()->removeDelimiter($opener); // Remove this opener from stack + $cursor->restoreState($previousState); + + return false; + } + + $isImage = $opener->getChar() === '!'; + + $inline = $this->createInline($link['url'], $link['title'], $isImage, $reference ?? null); + $opener->getInlineNode()->replaceWith($inline); + while (($label = $inline->next()) !== null) { + // Is there a Mention or Link contained within this link? + // CommonMark does not allow nested links, so we'll restore the original text. + if ($label instanceof Mention) { + $label->replaceWith($replacement = new Text($label->getPrefix() . $label->getIdentifier())); + $inline->appendChild($replacement); + } elseif ($label instanceof Link) { + foreach ($label->children() as $child) { + $label->insertBefore($child); + } + + $label->detach(); + } else { + $inline->appendChild($label); + } + } + + // Process delimiters such as emphasis inside link/image + $delimiterStack = $inlineContext->getDelimiterStack(); + $stackBottom = $opener->getPrevious(); + $delimiterStack->processDelimiters($stackBottom, $this->environment->getDelimiterProcessors()); + $delimiterStack->removeAll($stackBottom); + + // Merge any adjacent Text nodes together + AdjacentTextMerger::mergeChildNodes($inline); + + // processEmphasis will remove this and later delimiters. + // Now, for a link, we also remove earlier link openers (no links in links) + if (! $isImage) { + $inlineContext->getDelimiterStack()->removeEarlierMatches('['); + } + + return true; + } + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->environment = $environment; + } + + /** + * @return array|null + */ + private function tryParseInlineLinkAndTitle(Cursor $cursor): ?array + { + if ($cursor->getCurrentCharacter() !== '(') { + return null; + } + + $previousState = $cursor->saveState(); + + $cursor->advanceBy(1); + $cursor->advanceToNextNonSpaceOrNewline(); + if (($dest = LinkParserHelper::parseLinkDestination($cursor)) === null) { + $cursor->restoreState($previousState); + + return null; + } + + $cursor->advanceToNextNonSpaceOrNewline(); + $previousCharacter = $cursor->peek(-1); + // We know from previous lines that we've advanced at least one space so far, so this next call should never be null + \assert(\is_string($previousCharacter)); + + $title = ''; + // make sure there's a space before the title: + if (\preg_match(RegexHelper::REGEX_WHITESPACE_CHAR, $previousCharacter)) { + $title = LinkParserHelper::parseLinkTitle($cursor) ?? ''; + } + + $cursor->advanceToNextNonSpaceOrNewline(); + + if ($cursor->getCurrentCharacter() !== ')') { + $cursor->restoreState($previousState); + + return null; + } + + $cursor->advanceBy(1); + + return ['url' => $dest, 'title' => $title]; + } + + private function tryParseReference(Cursor $cursor, ReferenceMapInterface $referenceMap, ?int $openerIndex, int $startPos): ?ReferenceInterface + { + if ($openerIndex === null) { + return null; + } + + $savePos = $cursor->saveState(); + $beforeLabel = $cursor->getPosition(); + $n = LinkParserHelper::parseLinkLabel($cursor); + if ($n === 0 || $n === 2) { + $start = $openerIndex; + $length = $startPos - $openerIndex; + } else { + $start = $beforeLabel + 1; + $length = $n - 2; + } + + $referenceLabel = $cursor->getSubstring($start, $length); + + if ($n === 0) { + // If shortcut reference link, rewind before spaces we skipped + $cursor->restoreState($savePos); + } + + return $referenceMap->get($referenceLabel); + } + + private function createInline(string $url, string $title, bool $isImage, ?ReferenceInterface $reference = null): AbstractWebResource + { + if ($isImage) { + $inline = new Image($url, null, $title); + } else { + $inline = new Link($url, null, $title); + } + + if ($reference) { + $inline->data->set('reference', $reference); + } + + return $inline; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php new file mode 100644 index 0000000..4122ff7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\Html5EntityDecoder; +use League\CommonMark\Util\RegexHelper; + +final class EntityParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(RegexHelper::PARTIAL_ENTITY); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $entity = $inlineContext->getFullMatch(); + + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild(new Text(Html5EntityDecoder::decode($entity))); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php new file mode 100644 index 0000000..64e6fab --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php @@ -0,0 +1,57 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; + +final class EscapableParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('\\'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + $nextChar = $cursor->peek(); + + if ($nextChar === "\n") { + $cursor->advanceBy(2); + $inlineContext->getContainer()->appendChild(new Newline(Newline::HARDBREAK)); + + return true; + } + + if ($nextChar !== null && RegexHelper::isEscapable($nextChar)) { + $cursor->advanceBy(2); + $inlineContext->getContainer()->appendChild(new Text($nextChar)); + + return true; + } + + $cursor->advanceBy(1); + $inlineContext->getContainer()->appendChild(new Text('\\')); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php new file mode 100644 index 0000000..f38db13 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php @@ -0,0 +1,41 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; + +final class HtmlInlineParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(RegexHelper::PARTIAL_HTMLTAG)->caseSensitive(); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inline = $inlineContext->getFullMatch(); + + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild(new HtmlInline($inline)); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php new file mode 100644 index 0000000..2b52d1c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php @@ -0,0 +1,44 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Delimiter\Delimiter; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class OpenBracketParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('['); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy(1); + $node = new Text('[', ['delim' => true]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack for this opener + $delimiter = new Delimiter('[', 1, $node, true, false, $inlineContext->getCursor()->getPosition()); + $inlineContext->getDelimiterStack()->push($delimiter); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php new file mode 100644 index 0000000..4a59bd3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php @@ -0,0 +1,70 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\BlockQuote; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class BlockQuoteRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param BlockQuote $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + BlockQuote::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $filling = $childRenderer->renderNodes($node->children()); + $innerSeparator = $childRenderer->getInnerSeparator(); + if ($filling === '') { + return new HtmlElement('blockquote', $attrs, $innerSeparator); + } + + return new HtmlElement( + 'blockquote', + $attrs, + $innerSeparator . $filling . $innerSeparator + ); + } + + public function getXmlTagName(Node $node): string + { + return 'block_quote'; + } + + /** + * @param BlockQuote $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php new file mode 100644 index 0000000..8df9a40 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php @@ -0,0 +1,81 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class FencedCodeRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param FencedCode $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + FencedCode::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $infoWords = $node->getInfoWords(); + if (\count($infoWords) !== 0 && $infoWords[0] !== '') { + $class = $infoWords[0]; + if (! \str_starts_with($class, 'language-')) { + $class = 'language-' . $class; + } + + $attrs->append('class', $class); + } + + return new HtmlElement( + 'pre', + [], + new HtmlElement('code', $attrs->export(), Xml::escape($node->getLiteral())) + ); + } + + public function getXmlTagName(Node $node): string + { + return 'code_block'; + } + + /** + * @param FencedCode $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + FencedCode::assertInstanceOf($node); + + if (($info = $node->getInfo()) === null || $info === '') { + return []; + } + + return ['info' => $info]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php new file mode 100644 index 0000000..8718b8c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php @@ -0,0 +1,64 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class HeadingRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Heading $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Heading::assertInstanceOf($node); + + $tag = 'h' . $node->getLevel(); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement($tag, $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'heading'; + } + + /** + * @param Heading $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Heading::assertInstanceOf($node); + + return ['level' => $node->getLevel()]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php new file mode 100644 index 0000000..63a1907 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php @@ -0,0 +1,66 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlFilter; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class HtmlBlockRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param HtmlBlock $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + HtmlBlock::assertInstanceOf($node); + + $htmlInput = $this->config->get('html_input'); + + return HtmlFilter::filter($node->getLiteral(), $htmlInput); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'html_block'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php new file mode 100644 index 0000000..c4bd4eb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php @@ -0,0 +1,61 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class IndentedCodeRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param IndentedCode $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + IndentedCode::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement( + 'pre', + [], + new HtmlElement('code', $attrs, Xml::escape($node->getLiteral())) + ); + } + + public function getXmlTagName(Node $node): string + { + return 'code_block'; + } + + /** + * @return array + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php new file mode 100644 index 0000000..f79b44d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php @@ -0,0 +1,86 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ListBlockRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param ListBlock $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + ListBlock::assertInstanceOf($node); + + $listData = $node->getListData(); + + $tag = $listData->type === ListBlock::TYPE_BULLET ? 'ul' : 'ol'; + + $attrs = $node->data->get('attributes'); + + if ($listData->start !== null && $listData->start !== 1) { + $attrs['start'] = (string) $listData->start; + } + + $innerSeparator = $childRenderer->getInnerSeparator(); + + return new HtmlElement($tag, $attrs, $innerSeparator . $childRenderer->renderNodes($node->children()) . $innerSeparator); + } + + public function getXmlTagName(Node $node): string + { + return 'list'; + } + + /** + * @param ListBlock $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + ListBlock::assertInstanceOf($node); + + $data = $node->getListData(); + + if ($data->type === ListBlock::TYPE_BULLET) { + return [ + 'type' => $data->type, + 'tight' => $node->isTight() ? 'true' : 'false', + ]; + } + + return [ + 'type' => $data->type, + 'start' => $data->start ?? 1, + 'tight' => $node->isTight(), + 'delimiter' => $data->delimiter ?? ListBlock::DELIM_PERIOD, + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php new file mode 100644 index 0000000..570f5a7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php @@ -0,0 +1,74 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TaskList\TaskListItemMarker; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ListItemRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param ListItem $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + ListItem::assertInstanceOf($node); + + $contents = $childRenderer->renderNodes($node->children()); + if (\substr($contents, 0, 1) === '<' && ! $this->startsTaskListItem($node)) { + $contents = "\n" . $contents; + } + + if (\substr($contents, -1, 1) === '>') { + $contents .= "\n"; + } + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('li', $attrs, $contents); + } + + public function getXmlTagName(Node $node): string + { + return 'item'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } + + private function startsTaskListItem(ListItem $block): bool + { + $firstChild = $block->firstChild(); + + return $firstChild instanceof Paragraph && $firstChild->firstChild() instanceof TaskListItemMarker; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php new file mode 100644 index 0000000..392bfee --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ThematicBreak; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ThematicBreakRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param ThematicBreak $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + ThematicBreak::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('hr', $attrs, '', true); + } + + public function getXmlTagName(Node $node): string + { + return 'thematic_break'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php new file mode 100644 index 0000000..de030e8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php @@ -0,0 +1,57 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Code; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class CodeRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Code $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Code::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('code', $attrs, Xml::escape($node->getLiteral())); + } + + public function getXmlTagName(Node $node): string + { + return 'code'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php new file mode 100644 index 0000000..41169c4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Emphasis; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class EmphasisRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Emphasis $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Emphasis::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('em', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'emph'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php new file mode 100644 index 0000000..69f0fd5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php @@ -0,0 +1,66 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlFilter; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class HtmlInlineRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param HtmlInline $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + HtmlInline::assertInstanceOf($node); + + $htmlInput = $this->config->get('html_input'); + + return HtmlFilter::filter($node->getLiteral(), $htmlInput); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'html_inline'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php new file mode 100644 index 0000000..7bf09ac --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php @@ -0,0 +1,107 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Image; +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Node; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Node\StringContainerInterface; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\RegexHelper; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class ImageRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param Image $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Image::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $forbidUnsafeLinks = ! $this->config->get('allow_unsafe_links'); + if ($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($node->getUrl())) { + $attrs['src'] = ''; + } else { + $attrs['src'] = $node->getUrl(); + } + + $attrs['alt'] = $this->getAltText($node); + + if (($title = $node->getTitle()) !== null) { + $attrs['title'] = $title; + } + + return new HtmlElement('img', $attrs, '', true); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'image'; + } + + /** + * @param Image $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Image::assertInstanceOf($node); + + return [ + 'destination' => $node->getUrl(), + 'title' => $node->getTitle() ?? '', + ]; + } + + private function getAltText(Image $node): string + { + $altText = ''; + + foreach ((new NodeIterator($node)) as $n) { + if ($n instanceof StringContainerInterface) { + $altText .= $n->getLiteral(); + } elseif ($n instanceof Newline) { + $altText .= "\n"; + } + } + + return $altText; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php new file mode 100644 index 0000000..4ef9645 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php @@ -0,0 +1,89 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\RegexHelper; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class LinkRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param Link $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Link::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $forbidUnsafeLinks = ! $this->config->get('allow_unsafe_links'); + if (! ($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($node->getUrl()))) { + $attrs['href'] = $node->getUrl(); + } + + if (($title = $node->getTitle()) !== null) { + $attrs['title'] = $title; + } + + if (isset($attrs['target']) && $attrs['target'] === '_blank' && ! isset($attrs['rel'])) { + $attrs['rel'] = 'noopener noreferrer'; + } + + return new HtmlElement('a', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'link'; + } + + /** + * @param Link $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Link::assertInstanceOf($node); + + return [ + 'destination' => $node->getUrl(), + 'title' => $node->getTitle() ?? '', + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php new file mode 100644 index 0000000..f0bb8f9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Strong; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class StrongRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Strong $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Strong::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('strong', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'strong'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.php new file mode 100644 index 0000000..63e467c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.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 League\CommonMark\Extension; + +use League\Config\ConfigurationBuilderInterface; + +interface ConfigurableExtensionInterface extends ExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php new file mode 100644 index 0000000..6b519f8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DefaultAttributes; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + /** @var array> $map */ + $map = $this->config->get('default_attributes'); + + // Don't bother iterating if no default attributes are configured + if (! $map) { + return; + } + + foreach ($event->getDocument()->iterator() as $node) { + // Check to see if any default attributes were defined + if (($attributesToApply = $map[\get_class($node)] ?? []) === []) { + continue; + } + + $newAttributes = []; + foreach ($attributesToApply as $name => $value) { + if (\is_callable($value)) { + $value = $value($node); + // Callables are allowed to return `null` indicating that no changes should be made + if ($value !== null) { + $newAttributes[$name] = $value; + } + } else { + $newAttributes[$name] = $value; + } + } + + // Merge these attributes into the node + if (\count($newAttributes) > 0) { + $node->data->set('attributes', AttributesHelper::mergeAttributes($node, $newAttributes)); + } + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.php new file mode 100644 index 0000000..152c29a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.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 League\CommonMark\Extension\DefaultAttributes; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class DefaultAttributesExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('default_attributes', Expect::arrayOf( + Expect::arrayOf( + Expect::type('string|string[]|bool|callable'), // attribute value(s) + 'string' // attribute name + ), + 'string' // node FQCN + )->default([])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, [new ApplyDefaultAttributesProcessor(), 'onDocumentParsed']); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php new file mode 100644 index 0000000..9ddd2a8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\DescriptionList\Event\ConsecutiveDescriptionListMerger; +use League\CommonMark\Extension\DescriptionList\Event\LooseDescriptionHandler; +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Extension\DescriptionList\Parser\DescriptionStartParser; +use League\CommonMark\Extension\DescriptionList\Renderer\DescriptionListRenderer; +use League\CommonMark\Extension\DescriptionList\Renderer\DescriptionRenderer; +use League\CommonMark\Extension\DescriptionList\Renderer\DescriptionTermRenderer; +use League\CommonMark\Extension\ExtensionInterface; + +final class DescriptionListExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addBlockStartParser(new DescriptionStartParser()); + + $environment->addEventListener(DocumentParsedEvent::class, new LooseDescriptionHandler(), 1001); + $environment->addEventListener(DocumentParsedEvent::class, new ConsecutiveDescriptionListMerger(), 1000); + + $environment->addRenderer(DescriptionList::class, new DescriptionListRenderer()); + $environment->addRenderer(DescriptionTerm::class, new DescriptionTermRenderer()); + $environment->addRenderer(Description::class, new DescriptionRenderer()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.php new file mode 100644 index 0000000..15210e7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.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 League\CommonMark\Extension\DescriptionList\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Node\NodeIterator; + +final class ConsecutiveDescriptionListMerger +{ + public function __invoke(DocumentParsedEvent $event): void + { + foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof DescriptionList) { + continue; + } + + if (! ($prev = $node->previous()) instanceof DescriptionList) { + continue; + } + + // There's another description list behind this one; merge the current one into that + foreach ($node->children() as $child) { + $prev->appendChild($child); + } + + $node->detach(); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php new file mode 100644 index 0000000..a8823fa --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\NodeIterator; + +final class LooseDescriptionHandler +{ + public function __invoke(DocumentParsedEvent $event): void + { + foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $description) { + if (! $description instanceof Description) { + continue; + } + + // Does this description need to be added to a list? + if (! $description->parent() instanceof DescriptionList) { + $list = new DescriptionList(); + // Taking any preceding paragraphs with it + if (($paragraph = $description->previous()) instanceof Paragraph) { + $list->appendChild($paragraph); + } + + $description->replaceWith($list); + $list->appendChild($description); + } + + // Is this description preceded by a paragraph that should really be a term? + if (! (($paragraph = $description->previous()) instanceof Paragraph)) { + continue; + } + + // Convert the paragraph into one or more terms + $term = new DescriptionTerm(); + $paragraph->replaceWith($term); + + foreach ($paragraph->children() as $child) { + if ($child instanceof Newline) { + $newTerm = new DescriptionTerm(); + $term->insertAfter($newTerm); + $term = $newTerm; + continue; + } + + $term->appendChild($child); + } + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.php new file mode 100644 index 0000000..ccef962 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.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 League\CommonMark\Extension\DescriptionList\Node; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\TightBlockInterface; + +class Description extends AbstractBlock implements TightBlockInterface +{ + private bool $tight; + + public function __construct(bool $tight = false) + { + parent::__construct(); + + $this->tight = $tight; + } + + public function isTight(): bool + { + return $this->tight; + } + + public function setTight(bool $tight): void + { + $this->tight = $tight; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.php new file mode 100644 index 0000000..90d026c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.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 League\CommonMark\Extension\DescriptionList\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +class DescriptionList extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.php new file mode 100644 index 0000000..b13ec75 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.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 League\CommonMark\Extension\DescriptionList\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +class DescriptionTerm extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php new file mode 100644 index 0000000..0cdd9d5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class DescriptionContinueParser extends AbstractBlockContinueParser +{ + private Description $block; + + private int $indentation; + + public function __construct(bool $tight, int $indentation) + { + $this->block = new Description($tight); + $this->indentation = $indentation; + } + + public function getBlock(): Description + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + if ($this->block->firstChild() === null) { + // Blank line after empty item + return BlockContinue::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockContinue::at($cursor); + } + + if ($cursor->getIndent() >= $this->indentation) { + $cursor->advanceBy($this->indentation, true); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php new file mode 100644 index 0000000..1d446a7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class DescriptionListContinueParser extends AbstractBlockContinueParser +{ + private DescriptionList $block; + + public function __construct() + { + $this->block = new DescriptionList(); + } + + public function getBlock(): DescriptionList + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::at($cursor); + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return $childBlock instanceof DescriptionTerm || $childBlock instanceof Description; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php new file mode 100644 index 0000000..b4e8c98 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class DescriptionStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->match('/^:[ \t]+/') === null) { + return BlockStart::none(); + } + + $terms = $parserState->getParagraphContent(); + + $activeBlock = $parserState->getActiveBlockParser()->getBlock(); + + if ($terms !== null && $terms !== '') { + // New description; tight; term(s) sitting in pending block that we will replace + return BlockStart::of(...[new DescriptionListContinueParser()], ...self::splitTerms($terms), ...[new DescriptionContinueParser(true, $cursor->getPosition())]) + ->at($cursor) + ->replaceActiveBlockParser(); + } + + if ($activeBlock instanceof Paragraph && $activeBlock->parent() instanceof Description) { + // Additional description in the same list as the parent description + return BlockStart::of(new DescriptionContinueParser(true, $cursor->getPosition()))->at($cursor); + } + + if ($activeBlock->lastChild() instanceof Paragraph) { + // New description; loose; term(s) sitting in previous closed paragraph block + return BlockStart::of(new DescriptionContinueParser(false, $cursor->getPosition()))->at($cursor); + } + + // No preceding terms + return BlockStart::none(); + } + + /** + * @return array + */ + private static function splitTerms(string $terms): array + { + $ret = []; + foreach (\explode("\n", $terms) as $term) { + $ret[] = new DescriptionTermContinueParser($term); + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php new file mode 100644 index 0000000..7b43882 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; + +final class DescriptionTermContinueParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + private DescriptionTerm $block; + + private string $term; + + public function __construct(string $term) + { + $this->block = new DescriptionTerm(); + $this->term = $term; + } + + public function getBlock(): DescriptionTerm + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::finished(); + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + if ($this->term !== '') { + $inlineParser->parse($this->term, $this->block); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.php new file mode 100644 index 0000000..7723038 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.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 League\CommonMark\Extension\DescriptionList\Renderer; + +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; + +final class DescriptionListRenderer implements NodeRendererInterface +{ + /** + * @param DescriptionList $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): HtmlElement + { + DescriptionList::assertInstanceOf($node); + + $separator = $childRenderer->getBlockSeparator(); + + return new HtmlElement('dl', [], $separator . $childRenderer->renderNodes($node->children()) . $separator); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.php new file mode 100644 index 0000000..5fcffd6 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.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 League\CommonMark\Extension\DescriptionList\Renderer; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; + +final class DescriptionRenderer implements NodeRendererInterface +{ + /** + * @param Description $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Description::assertInstanceOf($node); + + return new HtmlElement('dd', [], $childRenderer->renderNodes($node->children())); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.php new file mode 100644 index 0000000..ce8a1c4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.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 League\CommonMark\Extension\DescriptionList\Renderer; + +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; + +final class DescriptionTermRenderer implements NodeRendererInterface +{ + /** + * @param DescriptionTerm $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + DescriptionTerm::assertInstanceOf($node); + + return new HtmlElement('dt', [], $childRenderer->renderNodes($node->children())); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.php new file mode 100644 index 0000000..0ece0c2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.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 League\CommonMark\Extension\DisallowedRawHtml; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; +use League\CommonMark\Extension\CommonMark\Renderer\Block\HtmlBlockRenderer; +use League\CommonMark\Extension\CommonMark\Renderer\Inline\HtmlInlineRenderer; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class DisallowedRawHtmlExtension implements ConfigurableExtensionInterface +{ + private const DEFAULT_DISALLOWED_TAGS = [ + 'title', + 'textarea', + 'style', + 'xmp', + 'iframe', + 'noembed', + 'noframes', + 'script', + 'plaintext', + ]; + + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('disallowed_raw_html', Expect::structure([ + 'disallowed_tags' => Expect::listOf('string')->default(self::DEFAULT_DISALLOWED_TAGS)->mergeDefaults(false), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addRenderer(HtmlBlock::class, new DisallowedRawHtmlRenderer(new HtmlBlockRenderer()), 50); + $environment->addRenderer(HtmlInline::class, new DisallowedRawHtmlRenderer(new HtmlInlineRenderer()), 50); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php new file mode 100644 index 0000000..06252a3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DisallowedRawHtml; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class DisallowedRawHtmlRenderer implements NodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly */ + private NodeRendererInterface $innerRenderer; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function __construct(NodeRendererInterface $innerRenderer) + { + $this->innerRenderer = $innerRenderer; + } + + public function render(Node $node, ChildNodeRendererInterface $childRenderer): ?string + { + $rendered = (string) $this->innerRenderer->render($node, $childRenderer); + + if ($rendered === '') { + return ''; + } + + $tags = (array) $this->config->get('disallowed_raw_html/disallowed_tags'); + if (\count($tags) === 0) { + return $rendered; + } + + $regex = \sprintf('/<(\/?(?:%s)[ \/>])/i', \implode('|', \array_map('preg_quote', $tags))); + + // Match these types of tags: <title/> <title /> + return \preg_replace($regex, '<$1', $rendered); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + + if ($this->innerRenderer instanceof ConfigurationAwareInterface) { + $this->innerRenderer->setConfiguration($configuration); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php new file mode 100644 index 0000000..06b8190 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed\Bridge; + +use Embed\Embed as EmbedLib; +use League\CommonMark\Exception\MissingDependencyException; +use League\CommonMark\Extension\Embed\Embed; +use League\CommonMark\Extension\Embed\EmbedAdapterInterface; + +final class OscaroteroEmbedAdapter implements EmbedAdapterInterface +{ + private EmbedLib $embedLib; + + public function __construct(?EmbedLib $embed = null) + { + if ($embed === null) { + if (! \class_exists(EmbedLib::class)) { + throw new MissingDependencyException('The embed/embed package is not installed. Please install it with Composer to use this adapter.'); + } + + $embed = new EmbedLib(); + } + + $this->embedLib = $embed; + } + + /** + * {@inheritDoc} + */ + public function updateEmbeds(array $embeds): void + { + $extractors = $this->embedLib->getMulti(...\array_map(static fn (Embed $embed) => $embed->getUrl(), $embeds)); + foreach ($extractors as $i => $extractor) { + if ($extractor->code !== null) { + $embeds[$i]->setEmbedCode($extractor->code->html); + } + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php new file mode 100644 index 0000000..d150764 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +class DomainFilteringAdapter implements EmbedAdapterInterface +{ + private EmbedAdapterInterface $decorated; + + /** @psalm-var non-empty-string */ + private string $regex; + + /** + * @param string[] $allowedDomains + */ + public function __construct(EmbedAdapterInterface $decorated, array $allowedDomains) + { + $this->decorated = $decorated; + $this->regex = self::createRegex($allowedDomains); + } + + /** + * {@inheritDoc} + */ + public function updateEmbeds(array $embeds): void + { + $this->decorated->updateEmbeds(\array_values(\array_filter($embeds, function (Embed $embed): bool { + return \preg_match($this->regex, $embed->getUrl()) === 1; + }))); + } + + /** + * @param string[] $allowedDomains + * + * @psalm-return non-empty-string + */ + private static function createRegex(array $allowedDomains): string + { + $allowedDomains = \array_map('preg_quote', $allowedDomains); + + return '/^(?:https?:\/\/)?(?:[^.]+\.)*(' . \implode('|', $allowedDomains) . ')/'; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/Embed.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/Embed.php new file mode 100644 index 0000000..94c1980 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/Embed.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Embed extends AbstractBlock +{ + private string $url; + private ?string $embedCode; + + public function __construct(string $url, ?string $embedCode = null) + { + parent::__construct(); + + $this->url = $url; + $this->embedCode = $embedCode; + } + + public function getUrl(): string + { + return $this->url; + } + + public function setUrl(string $url): void + { + $this->url = $url; + } + + public function getEmbedCode(): ?string + { + return $this->embedCode; + } + + public function setEmbedCode(?string $embedCode): void + { + $this->embedCode = $embedCode; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php new file mode 100644 index 0000000..9880a43 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php @@ -0,0 +1,25 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +/** + * Interface for a service which updates the embed code(s) for the given array of embeds + */ +interface EmbedAdapterInterface +{ + /** + * @param Embed[] $embeds + */ + public function updateEmbeds(array $embeds): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php new file mode 100644 index 0000000..babf048 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php @@ -0,0 +1,48 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class EmbedExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('embed', Expect::structure([ + 'adapter' => Expect::type(EmbedAdapterInterface::class), + 'allowed_domains' => Expect::arrayOf('string')->default([]), + 'fallback' => Expect::anyOf('link', 'remove')->default('link'), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $adapter = $environment->getConfiguration()->get('embed.adapter'); + \assert($adapter instanceof EmbedAdapterInterface); + + $allowedDomains = $environment->getConfiguration()->get('embed.allowed_domains'); + if ($allowedDomains !== []) { + $adapter = new DomainFilteringAdapter($adapter, $allowedDomains); + } + + $environment + ->addBlockStartParser(new EmbedStartParser(), 300) + ->addEventListener(DocumentParsedEvent::class, new EmbedProcessor($adapter, $environment->getConfiguration()->get('embed.fallback')), 1010) + ->addRenderer(Embed::class, new EmbedRenderer()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedParser.php new file mode 100644 index 0000000..e957caf --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedParser.php @@ -0,0 +1,62 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +class EmbedParser implements BlockContinueParserInterface +{ + private Embed $embed; + + public function __construct(string $url) + { + $this->embed = new Embed($url); + } + + public function getBlock(): AbstractBlock + { + return $this->embed; + } + + public function isContainer(): bool + { + return false; + } + + public function canHaveLazyContinuationLines(): bool + { + return false; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return false; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::none(); + } + + public function addLine(string $line): void + { + } + + public function closeBlock(): void + { + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php new file mode 100644 index 0000000..68fb9ee --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php @@ -0,0 +1,70 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\NodeIterator; + +final class EmbedProcessor +{ + public const FALLBACK_REMOVE = 'remove'; + public const FALLBACK_LINK = 'link'; + + private EmbedAdapterInterface $adapter; + private string $fallback; + + public function __construct(EmbedAdapterInterface $adapter, string $fallback = self::FALLBACK_REMOVE) + { + $this->adapter = $adapter; + $this->fallback = $fallback; + } + + public function __invoke(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $embeds = []; + foreach (new NodeIterator($document) as $node) { + if (! ($node instanceof Embed)) { + continue; + } + + if ($node->parent() !== $document) { + $replacement = new Paragraph(); + $replacement->appendChild(new Text($node->getUrl())); + $node->replaceWith($replacement); + } else { + $embeds[] = $node; + } + } + + $this->adapter->updateEmbeds($embeds); + + foreach ($embeds as $embed) { + if ($embed->getEmbedCode() !== null) { + continue; + } + + if ($this->fallback === self::FALLBACK_REMOVE) { + $embed->detach(); + } elseif ($this->fallback === self::FALLBACK_LINK) { + $paragraph = new Paragraph(); + $paragraph->appendChild(new Link($embed->getUrl(), $embed->getUrl())); + $embed->replaceWith($paragraph); + } + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php new file mode 100644 index 0000000..91655d8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php @@ -0,0 +1,35 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; + +class EmbedRenderer implements NodeRendererInterface +{ + /** + * @param Embed $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + Embed::assertInstanceOf($node); + + return $node->getEmbedCode() ?? ''; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php new file mode 100644 index 0000000..5ff3808 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\LinkParserHelper; + +class EmbedStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || $parserState->getParagraphContent() !== null || ! ($parserState->getActiveBlockParser()->isContainer())) { + return BlockStart::none(); + } + + // 0-3 leading spaces are okay + $cursor->advanceToNextNonSpaceOrTab(); + + // The line must begin with "https://" + if (! str_starts_with($cursor->getRemainder(), 'https://')) { + return BlockStart::none(); + } + + // A valid link must be found next + if (($dest = LinkParserHelper::parseLinkDestination($cursor)) === null) { + return BlockStart::none(); + } + + // Skip any trailing whitespace + $cursor->advanceToNextNonSpaceOrTab(); + + // We must be at the end of the line; otherwise, this link was not by itself + if (! $cursor->isAtEnd()) { + return BlockStart::none(); + } + + return BlockStart::of(new EmbedParser($dest))->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/ExtensionInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/ExtensionInterface.php new file mode 100644 index 0000000..01a9f2e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/ExtensionInterface.php @@ -0,0 +1,24 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; + +interface ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php new file mode 100644 index 0000000..df0079c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\ExternalLink; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class ExternalLinkExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $applyOptions = [ + ExternalLinkProcessor::APPLY_NONE, + ExternalLinkProcessor::APPLY_ALL, + ExternalLinkProcessor::APPLY_INTERNAL, + ExternalLinkProcessor::APPLY_EXTERNAL, + ]; + + $builder->addSchema('external_link', Expect::structure([ + 'internal_hosts' => Expect::type('string|string[]'), + 'open_in_new_window' => Expect::bool(false), + 'html_class' => Expect::string()->default(''), + 'nofollow' => Expect::anyOf(...$applyOptions)->default(ExternalLinkProcessor::APPLY_NONE), + 'noopener' => Expect::anyOf(...$applyOptions)->default(ExternalLinkProcessor::APPLY_EXTERNAL), + 'noreferrer' => Expect::anyOf(...$applyOptions)->default(ExternalLinkProcessor::APPLY_EXTERNAL), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, new ExternalLinkProcessor($environment->getConfiguration()), -50); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php new file mode 100644 index 0000000..4a0aa89 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php @@ -0,0 +1,119 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\ExternalLink; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\Config\ConfigurationInterface; + +final class ExternalLinkProcessor +{ + public const APPLY_NONE = ''; + public const APPLY_ALL = 'all'; + public const APPLY_EXTERNAL = 'external'; + public const APPLY_INTERNAL = 'internal'; + + /** @psalm-readonly */ + private ConfigurationInterface $config; + + public function __construct(ConfigurationInterface $config) + { + $this->config = $config; + } + + public function __invoke(DocumentParsedEvent $e): void + { + $internalHosts = $this->config->get('external_link/internal_hosts'); + $openInNewWindow = $this->config->get('external_link/open_in_new_window'); + $classes = $this->config->get('external_link/html_class'); + + foreach ($e->getDocument()->iterator() as $link) { + if (! ($link instanceof Link)) { + continue; + } + + $host = \parse_url($link->getUrl(), PHP_URL_HOST); + if (! \is_string($host)) { + // Something is terribly wrong with this URL + continue; + } + + if (self::hostMatches($host, $internalHosts)) { + $link->data->set('external', false); + $this->applyRelAttribute($link, false); + continue; + } + + // Host does not match our list + $this->markLinkAsExternal($link, $openInNewWindow, $classes); + } + } + + private function markLinkAsExternal(Link $link, bool $openInNewWindow, string $classes): void + { + $link->data->set('external', true); + $this->applyRelAttribute($link, true); + + if ($openInNewWindow) { + $link->data->set('attributes/target', '_blank'); + } + + if ($classes !== '') { + $link->data->append('attributes/class', $classes); + } + } + + private function applyRelAttribute(Link $link, bool $isExternal): void + { + $options = [ + 'nofollow' => $this->config->get('external_link/nofollow'), + 'noopener' => $this->config->get('external_link/noopener'), + 'noreferrer' => $this->config->get('external_link/noreferrer'), + ]; + + foreach ($options as $type => $option) { + switch (true) { + case $option === self::APPLY_ALL: + case $isExternal && $option === self::APPLY_EXTERNAL: + case ! $isExternal && $option === self::APPLY_INTERNAL: + $link->data->append('attributes/rel', $type); + } + } + + // No rel attributes? Mark the attribute as 'false' so LinkRenderer doesn't add defaults + if (! $link->data->has('attributes/rel')) { + $link->data->set('attributes/rel', false); + } + } + + /** + * @internal This method is only public so we can easily test it. DO NOT USE THIS OUTSIDE OF THIS EXTENSION! + * + * @param non-empty-string|list<non-empty-string> $compareTo + */ + public static function hostMatches(string $host, $compareTo): bool + { + foreach ((array) $compareTo as $c) { + if (\strpos($c, '/') === 0) { + if (\preg_match($c, $host)) { + return true; + } + } elseif ($c === $host) { + return true; + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php new file mode 100644 index 0000000..401613a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php @@ -0,0 +1,62 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class AnonymousFootnotesListener implements ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + foreach ($document->iterator() as $node) { + if (! $node instanceof FootnoteRef || ($text = $node->getContent()) === null) { + continue; + } + + // Anonymous footnote needs to create a footnote from its content + $existingReference = $node->getReference(); + $newReference = new Reference( + $existingReference->getLabel(), + '#' . $this->config->get('footnote/ref_id_prefix') . $existingReference->getLabel(), + $existingReference->getTitle() + ); + + $paragraph = new Paragraph(); + $paragraph->appendChild(new Text($text)); + $paragraph->appendChild(new FootnoteBackref($newReference)); + + $footnote = new Footnote($newReference); + $footnote->appendChild($paragraph); + + $document->appendChild($footnote); + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php new file mode 100644 index 0000000..a0295b5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php @@ -0,0 +1,68 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Inline\Text; + +final class FixOrphanedFootnotesAndRefsListener +{ + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $map = $this->buildMapOfKnownFootnotesAndRefs($document); + + foreach ($map['_flat'] as $node) { + if ($node instanceof FootnoteRef && ! isset($map[Footnote::class][$node->getReference()->getLabel()])) { + // Found an orphaned FootnoteRef without a corresponding Footnote + // Restore the original footnote ref text + $node->replaceWith(new Text(\sprintf('[^%s]', $node->getReference()->getLabel()))); + } + + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($node instanceof Footnote && ! isset($map[FootnoteRef::class][$node->getReference()->getLabel()])) { + // Found an orphaned Footnote without a corresponding FootnoteRef + // Remove the footnote + $node->detach(); + } + } + } + + /** @phpstan-ignore-next-line */ + private function buildMapOfKnownFootnotesAndRefs(Document $document): array // @phpcs:ignore + { + $map = [ + Footnote::class => [], + FootnoteRef::class => [], + '_flat' => [], + ]; + + foreach ($document->iterator() as $node) { + if ($node instanceof Footnote) { + $map[Footnote::class][$node->getReference()->getLabel()] = true; + + $map['_flat'][] = $node; + } elseif ($node instanceof FootnoteRef) { + $map[FootnoteRef::class][$node->getReference()->getLabel()] = true; + + $map['_flat'][] = $node; + } + } + + return $map; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php new file mode 100644 index 0000000..ae8d00b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php @@ -0,0 +1,106 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Extension\Footnote\Node\FootnoteContainer; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class GatherFootnotesListener implements ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $footnotes = []; + + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Footnote) { + continue; + } + + // Look for existing reference with footnote label + $ref = $document->getReferenceMap()->get($node->getReference()->getLabel()); + if ($ref !== null) { + // Use numeric title to get footnotes order + $footnotes[(int) $ref->getTitle()] = $node; + } else { + // Footnote call is missing, append footnote at the end + $footnotes[\PHP_INT_MAX] = $node; + } + + $key = '#' . $this->config->get('footnote/footnote_id_prefix') . $node->getReference()->getDestination(); + if ($document->data->has($key)) { + $this->createBackrefs($node, $document->data->get($key)); + } + } + + // Only add a footnote container if there are any + if (\count($footnotes) === 0) { + return; + } + + $container = $this->getFootnotesContainer($document); + + \ksort($footnotes); + foreach ($footnotes as $footnote) { + $container->appendChild($footnote); + } + } + + private function getFootnotesContainer(Document $document): FootnoteContainer + { + $footnoteContainer = new FootnoteContainer(); + $document->appendChild($footnoteContainer); + + return $footnoteContainer; + } + + /** + * Look for all footnote refs pointing to this footnote and create each footnote backrefs. + * + * @param Footnote $node The target footnote + * @param Reference[] $backrefs References to create backrefs for + */ + private function createBackrefs(Footnote $node, array $backrefs): void + { + // Backrefs should be added to the child paragraph + $target = $node->lastChild(); + if ($target === null) { + // This should never happen, but you never know + $target = $node; + } + + foreach ($backrefs as $backref) { + $target->appendChild(new FootnoteBackref(new Reference( + $backref->getLabel(), + '#' . $this->config->get('footnote/ref_id_prefix') . $backref->getLabel(), + $backref->getTitle() + ))); + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php new file mode 100644 index 0000000..65600fa --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php @@ -0,0 +1,75 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Reference\Reference; + +final class NumberFootnotesListener +{ + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $nextCounter = 1; + $usedLabels = []; + $usedCounters = []; + + foreach ($document->iterator() as $node) { + if (! $node instanceof FootnoteRef) { + continue; + } + + $existingReference = $node->getReference(); + $label = $existingReference->getLabel(); + $counter = $nextCounter; + $canIncrementCounter = true; + + if (\array_key_exists($label, $usedLabels)) { + /* + * Reference is used again, we need to point + * to the same footnote. But with a different ID + */ + $counter = $usedCounters[$label]; + $label .= '__' . ++$usedLabels[$label]; + $canIncrementCounter = false; + } + + // rewrite reference title to use a numeric link + $newReference = new Reference( + $label, + $existingReference->getDestination(), + (string) $counter + ); + + // Override reference with numeric link + $node->setReference($newReference); + $document->getReferenceMap()->add($newReference); + + /* + * Store created references in document for + * creating FootnoteBackrefs + */ + $document->data->append($existingReference->getDestination(), $newReference); + + $usedLabels[$label] = 1; + $usedCounters[$label] = $nextCounter; + + if ($canIncrementCounter) { + $nextCounter++; + } + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php new file mode 100644 index 0000000..0fa8038 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php @@ -0,0 +1,70 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\Footnote\Event\AnonymousFootnotesListener; +use League\CommonMark\Extension\Footnote\Event\FixOrphanedFootnotesAndRefsListener; +use League\CommonMark\Extension\Footnote\Event\GatherFootnotesListener; +use League\CommonMark\Extension\Footnote\Event\NumberFootnotesListener; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Extension\Footnote\Node\FootnoteContainer; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Extension\Footnote\Parser\AnonymousFootnoteRefParser; +use League\CommonMark\Extension\Footnote\Parser\FootnoteRefParser; +use League\CommonMark\Extension\Footnote\Parser\FootnoteStartParser; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteBackrefRenderer; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteContainerRenderer; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteRefRenderer; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteRenderer; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class FootnoteExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('footnote', Expect::structure([ + 'backref_class' => Expect::string('footnote-backref'), + 'backref_symbol' => Expect::string('↩'), + 'container_add_hr' => Expect::bool(true), + 'container_class' => Expect::string('footnotes'), + 'ref_class' => Expect::string('footnote-ref'), + 'ref_id_prefix' => Expect::string('fnref:'), + 'footnote_class' => Expect::string('footnote'), + 'footnote_id_prefix' => Expect::string('fn:'), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addBlockStartParser(new FootnoteStartParser(), 51); + $environment->addInlineParser(new AnonymousFootnoteRefParser(), 35); + $environment->addInlineParser(new FootnoteRefParser(), 51); + + $environment->addRenderer(FootnoteContainer::class, new FootnoteContainerRenderer()); + $environment->addRenderer(Footnote::class, new FootnoteRenderer()); + $environment->addRenderer(FootnoteRef::class, new FootnoteRefRenderer()); + $environment->addRenderer(FootnoteBackref::class, new FootnoteBackrefRenderer()); + + $environment->addEventListener(DocumentParsedEvent::class, [new AnonymousFootnotesListener(), 'onDocumentParsed'], 40); + $environment->addEventListener(DocumentParsedEvent::class, [new FixOrphanedFootnotesAndRefsListener(), 'onDocumentParsed'], 30); + $environment->addEventListener(DocumentParsedEvent::class, [new NumberFootnotesListener(), 'onDocumentParsed'], 20); + $environment->addEventListener(DocumentParsedEvent::class, [new GatherFootnotesListener(), 'onDocumentParsed'], 10); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php new file mode 100644 index 0000000..c3f77ca --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceableInterface; + +final class Footnote extends AbstractBlock implements ReferenceableInterface +{ + /** @psalm-readonly */ + private ReferenceInterface $reference; + + public function __construct(ReferenceInterface $reference) + { + parent::__construct(); + + $this->reference = $reference; + } + + public function getReference(): ReferenceInterface + { + return $this->reference; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php new file mode 100644 index 0000000..f56daa5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php @@ -0,0 +1,40 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceableInterface; + +/** + * Link from the footnote on the bottom of the document back to the reference + */ +final class FootnoteBackref extends AbstractInline implements ReferenceableInterface +{ + /** @psalm-readonly */ + private ReferenceInterface $reference; + + public function __construct(ReferenceInterface $reference) + { + parent::__construct(); + + $this->reference = $reference; + } + + public function getReference(): ReferenceInterface + { + return $this->reference; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php new file mode 100644 index 0000000..af4ee35 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class FootnoteContainer extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php new file mode 100644 index 0000000..429a1dc --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceableInterface; + +final class FootnoteRef extends AbstractInline implements ReferenceableInterface +{ + private ReferenceInterface $reference; + + /** @psalm-readonly */ + private ?string $content = null; + + /** + * @param array<mixed> $data + */ + public function __construct(ReferenceInterface $reference, ?string $content = null, array $data = []) + { + parent::__construct(); + + $this->reference = $reference; + $this->content = $content; + + if (\count($data) > 0) { + $this->data->import($data); + } + } + + public function getReference(): ReferenceInterface + { + return $this->reference; + } + + public function setReference(ReferenceInterface $reference): void + { + $this->reference = $reference; + } + + public function getContent(): ?string + { + return $this->content; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php new file mode 100644 index 0000000..4ed93da --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php @@ -0,0 +1,66 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationInterface; + +final class AnonymousFootnoteRefParser implements InlineParserInterface, EnvironmentAwareInterface +{ + private ConfigurationInterface $config; + + /** @psalm-readonly-allow-private-mutation */ + private TextNormalizerInterface $slugNormalizer; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('\^\[([^\]]+)\]'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + + [$label] = $inlineContext->getSubMatches(); + $reference = $this->createReference($label); + $inlineContext->getContainer()->appendChild(new FootnoteRef($reference, $label)); + + return true; + } + + private function createReference(string $label): Reference + { + $refLabel = $this->slugNormalizer->normalize($label, ['length' => 20]); + + return new Reference( + $refLabel, + '#' . $this->config->get('footnote/footnote_id_prefix') . $refLabel, + $label + ); + } + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->config = $environment->getConfiguration(); + $this->slugNormalizer = $environment->getSlugNormalizer(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php new file mode 100644 index 0000000..2192546 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php @@ -0,0 +1,68 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Reference\ReferenceInterface; + +final class FootnoteParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private Footnote $block; + + /** @psalm-readonly-allow-private-mutation */ + private ?int $indentation = null; + + public function __construct(ReferenceInterface $reference) + { + $this->block = new Footnote($reference); + } + + public function getBlock(): Footnote + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + return BlockContinue::at($cursor); + } + + if ($cursor->isIndented()) { + $this->indentation ??= $cursor->getIndent(); + $cursor->advanceBy($this->indentation, true); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php new file mode 100644 index 0000000..4032abd --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteRefParser implements InlineParserInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('\[\^([^\s\]]+)\]'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + + [$label] = $inlineContext->getSubMatches(); + $inlineContext->getContainer()->appendChild(new FootnoteRef($this->createReference($label))); + + return true; + } + + private function createReference(string $label): Reference + { + return new Reference( + $label, + '#' . $this->config->get('footnote/footnote_id_prefix') . $label, + $label + ); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php new file mode 100644 index 0000000..734e678 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php @@ -0,0 +1,56 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Reference\Reference; +use League\CommonMark\Util\RegexHelper; + +final class FootnoteStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || $parserState->getLastMatchedBlockParser()->canHaveLazyContinuationLines()) { + return BlockStart::none(); + } + + $match = RegexHelper::matchFirst( + '/^\[\^([^\s^\]]+)\]\:(?:\s|$)/', + $cursor->getLine(), + $cursor->getNextNonSpacePosition() + ); + + if (! $match) { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(\strlen($match[0])); + $str = $cursor->getRemainder(); + \preg_replace('/^\[\^([^\s^\]]+)\]\:(?:\s|$)/', '', $str); + + if (\preg_match('/^\[\^([^\s^\]]+)\]\:(?:\s|$)/', $match[0], $matches) !== 1) { + return BlockStart::none(); + } + + $reference = new Reference($matches[1], $matches[1], $matches[1]); + $footnoteParser = new FootnoteParser($reference); + + return BlockStart::of($footnoteParser)->at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php new file mode 100644 index 0000000..3b7bc3c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php @@ -0,0 +1,81 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteBackrefRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + public const DEFAULT_SYMBOL = '↩'; + + private ConfigurationInterface $config; + + /** + * @param FootnoteBackref $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + FootnoteBackref::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $attrs->append('class', $this->config->get('footnote/backref_class')); + $attrs->set('rev', 'footnote'); + $attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8')); + $attrs->set('role', 'doc-backlink'); + + $symbol = $this->config->get('footnote/backref_symbol'); + \assert(\is_string($symbol)); + + return ' ' . new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), true); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote_backref'; + } + + /** + * @param FootnoteBackref $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + FootnoteBackref::assertInstanceOf($node); + + return [ + 'reference' => $node->getReference()->getLabel(), + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php new file mode 100644 index 0000000..74d35ef --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php @@ -0,0 +1,71 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\FootnoteContainer; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteContainerRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * @param FootnoteContainer $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + FootnoteContainer::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $attrs->append('class', $this->config->get('footnote/container_class')); + $attrs->set('role', 'doc-endnotes'); + + $contents = new HtmlElement('ol', [], $childRenderer->renderNodes($node->children())); + if ($this->config->get('footnote/container_add_hr')) { + $contents = [new HtmlElement('hr', [], null, true), $contents]; + } + + return new HtmlElement('div', $attrs->export(), $contents); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote_container'; + } + + /** + * @return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php new file mode 100644 index 0000000..c0c07d7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteRefRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * @param FootnoteRef $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + FootnoteRef::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + $attrs->append('class', $this->config->get('footnote/ref_class')); + $attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8')); + $attrs->set('role', 'doc-noteref'); + + $idPrefix = $this->config->get('footnote/ref_id_prefix'); + + return new HtmlElement( + 'sup', + [ + 'id' => $idPrefix . \mb_strtolower($node->getReference()->getLabel(), 'UTF-8'), + ], + new HtmlElement( + 'a', + $attrs->export(), + $node->getReference()->getTitle() + ), + true + ); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote_ref'; + } + + /** + * @param FootnoteRef $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + FootnoteRef::assertInstanceOf($node); + + return [ + 'reference' => $node->getReference()->getLabel(), + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php new file mode 100644 index 0000000..cdd027e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php @@ -0,0 +1,80 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * @param Footnote $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Footnote::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $attrs->append('class', $this->config->get('footnote/footnote_class')); + $attrs->set('id', $this->config->get('footnote/footnote_id_prefix') . \mb_strtolower($node->getReference()->getLabel(), 'UTF-8')); + $attrs->set('role', 'doc-endnote'); + + return new HtmlElement( + 'li', + $attrs->export(), + $childRenderer->renderNodes($node->children()), + true + ); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote'; + } + + /** + * @param Footnote $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Footnote::assertInstanceOf($node); + + return [ + 'reference' => $node->getReference()->getLabel(), + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php new file mode 100644 index 0000000..6e9db40 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter\Data; + +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; + +interface FrontMatterDataParserInterface +{ + /** + * @return mixed|null The parsed data (which may be null, if the input represents a null value) + * + * @throws InvalidFrontMatterException if parsing fails + */ + public function parse(string $frontMatter); +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php new file mode 100644 index 0000000..b7194f4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter\Data; + +use League\CommonMark\Exception\MissingDependencyException; +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; + +final class LibYamlFrontMatterParser implements FrontMatterDataParserInterface +{ + public static function capable(): ?LibYamlFrontMatterParser + { + if (! \extension_loaded('yaml')) { + return null; + } + + return new LibYamlFrontMatterParser(); + } + + /** + * {@inheritDoc} + */ + public function parse(string $frontMatter) + { + if (! \extension_loaded('yaml')) { + throw new MissingDependencyException('Failed to parse yaml: "ext-yaml" extension is missing'); + } + + $result = @\yaml_parse($frontMatter); + + if ($result === false) { + throw new InvalidFrontMatterException('Failed to parse front matter'); + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php new file mode 100644 index 0000000..8d99d33 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter\Data; + +use League\CommonMark\Exception\MissingDependencyException; +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Yaml; + +final class SymfonyYamlFrontMatterParser implements FrontMatterDataParserInterface +{ + /** + * {@inheritDoc} + */ + public function parse(string $frontMatter) + { + if (! \class_exists(Yaml::class)) { + throw new MissingDependencyException('Failed to parse yaml: "symfony/yaml" library is missing'); + } + + try { + /** @psalm-suppress ReservedWord */ + return Yaml::parse($frontMatter); + } catch (ParseException $ex) { + throw InvalidFrontMatterException::wrap($ex); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php new file mode 100644 index 0000000..ffe0c28 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Exception; + +use League\CommonMark\Exception\CommonMarkException; + +class InvalidFrontMatterException extends \RuntimeException implements CommonMarkException +{ + public static function wrap(\Throwable $t): self + { + return new InvalidFrontMatterException('Failed to parse front matter: ' . $t->getMessage(), 0, $t); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php new file mode 100644 index 0000000..019ecb4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php @@ -0,0 +1,46 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentPreParsedEvent; +use League\CommonMark\Event\DocumentRenderedEvent; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; +use League\CommonMark\Extension\FrontMatter\Data\LibYamlFrontMatterParser; +use League\CommonMark\Extension\FrontMatter\Data\SymfonyYamlFrontMatterParser; +use League\CommonMark\Extension\FrontMatter\Listener\FrontMatterPostRenderListener; +use League\CommonMark\Extension\FrontMatter\Listener\FrontMatterPreParser; + +final class FrontMatterExtension implements ExtensionInterface +{ + /** @psalm-readonly */ + private FrontMatterParserInterface $frontMatterParser; + + public function __construct(?FrontMatterDataParserInterface $dataParser = null) + { + $this->frontMatterParser = new FrontMatterParser($dataParser ?? LibYamlFrontMatterParser::capable() ?? new SymfonyYamlFrontMatterParser()); + } + + public function getFrontMatterParser(): FrontMatterParserInterface + { + return $this->frontMatterParser; + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentPreParsedEvent::class, new FrontMatterPreParser($this->frontMatterParser)); + $environment->addEventListener(DocumentRenderedEvent::class, new FrontMatterPostRenderListener(), -500); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php new file mode 100644 index 0000000..69c41d1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter; + +use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; +use League\CommonMark\Extension\FrontMatter\Input\MarkdownInputWithFrontMatter; +use League\CommonMark\Parser\Cursor; + +final class FrontMatterParser implements FrontMatterParserInterface +{ + /** @psalm-readonly */ + private FrontMatterDataParserInterface $frontMatterParser; + + private const REGEX_FRONT_MATTER = '/^---\\R.*?\\R---\\R/s'; + + public function __construct(FrontMatterDataParserInterface $frontMatterParser) + { + $this->frontMatterParser = $frontMatterParser; + } + + /** + * @throws InvalidFrontMatterException if the front matter cannot be parsed + */ + public function parse(string $markdownContent): MarkdownInputWithFrontMatter + { + $cursor = new Cursor($markdownContent); + + // Locate the front matter + $frontMatter = $cursor->match(self::REGEX_FRONT_MATTER); + if ($frontMatter === null) { + return new MarkdownInputWithFrontMatter($markdownContent); + } + + // Trim the last line (ending ---s and newline) + $frontMatter = \preg_replace('/---\R$/', '', $frontMatter); + if ($frontMatter === null) { + return new MarkdownInputWithFrontMatter($markdownContent); + } + + // Parse the resulting YAML data + $data = $this->frontMatterParser->parse($frontMatter); + + // Advance through any remaining newlines which separated the front matter from the Markdown text + $trailingNewlines = $cursor->match('/^\R+/'); + + // Calculate how many lines the Markdown is offset from the front matter by counting the number of newlines + // Don't forget to add 1 because we stripped one out when trimming the trailing delims + $lineOffset = \preg_match_all('/\R/', $frontMatter . $trailingNewlines) + 1; + + return new MarkdownInputWithFrontMatter($cursor->getRemainder(), $lineOffset, $data); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php new file mode 100644 index 0000000..197a33b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter; + +use League\CommonMark\Extension\FrontMatter\Input\MarkdownInputWithFrontMatter; + +interface FrontMatterParserInterface +{ + public function parse(string $markdownContent): MarkdownInputWithFrontMatter; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php new file mode 100644 index 0000000..b5a7278 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter; + +interface FrontMatterProviderInterface +{ + /** + * @return mixed|null + */ + public function getFrontMatter(); +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php new file mode 100644 index 0000000..86c982b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Input; + +use League\CommonMark\Extension\FrontMatter\FrontMatterProviderInterface; +use League\CommonMark\Input\MarkdownInput; + +final class MarkdownInputWithFrontMatter extends MarkdownInput implements FrontMatterProviderInterface +{ + /** @var mixed|null */ + private $frontMatter; + + /** + * @param string $content Markdown content without the raw front matter + * @param int $lineOffset Line offset (based on number of front matter lines removed) + * @param mixed|null $frontMatter Parsed front matter + */ + public function __construct(string $content, int $lineOffset = 0, $frontMatter = null) + { + parent::__construct($content, $lineOffset); + + $this->frontMatter = $frontMatter; + } + + /** + * {@inheritDoc} + */ + public function getFrontMatter() + { + return $this->frontMatter; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php new file mode 100644 index 0000000..14b7191 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Listener; + +use League\CommonMark\Event\DocumentRenderedEvent; +use League\CommonMark\Extension\FrontMatter\Output\RenderedContentWithFrontMatter; + +final class FrontMatterPostRenderListener +{ + public function __invoke(DocumentRenderedEvent $event): void + { + if ($event->getOutput()->getDocument()->data->get('front_matter', null) === null) { + return; + } + + $frontMatter = $event->getOutput()->getDocument()->data->get('front_matter'); + + $event->replaceOutput(new RenderedContentWithFrontMatter( + $event->getOutput()->getDocument(), + $event->getOutput()->getContent(), + $frontMatter + )); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php new file mode 100644 index 0000000..b0afbee --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Listener; + +use League\CommonMark\Event\DocumentPreParsedEvent; +use League\CommonMark\Extension\FrontMatter\FrontMatterParserInterface; + +final class FrontMatterPreParser +{ + private FrontMatterParserInterface $parser; + + public function __construct(FrontMatterParserInterface $parser) + { + $this->parser = $parser; + } + + public function __invoke(DocumentPreParsedEvent $event): void + { + $content = $event->getMarkdown()->getContent(); + + $parsed = $this->parser->parse($content); + + $event->getDocument()->data->set('front_matter', $parsed->getFrontMatter()); + $event->replaceMarkdown($parsed); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php new file mode 100644 index 0000000..efaa342 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php @@ -0,0 +1,51 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Output; + +use League\CommonMark\Extension\FrontMatter\FrontMatterProviderInterface; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Output\RenderedContent; + +/** + * @psalm-immutable + */ +final class RenderedContentWithFrontMatter extends RenderedContent implements FrontMatterProviderInterface +{ + /** + * @var mixed + * + * @psalm-readonly + */ + private $frontMatter; + + /** + * @param Document $document The parsed Document object + * @param string $content The final HTML + * @param mixed|null $frontMatter Any parsed front matter + */ + public function __construct(Document $document, string $content, $frontMatter) + { + parent::__construct($document, $content); + + $this->frontMatter = $frontMatter; + } + + /** + * {@inheritDoc} + */ + public function getFrontMatter() + { + return $this->frontMatter; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php new file mode 100644 index 0000000..b3920aa --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\Autolink\AutolinkExtension; +use League\CommonMark\Extension\DisallowedRawHtml\DisallowedRawHtmlExtension; +use League\CommonMark\Extension\Strikethrough\StrikethroughExtension; +use League\CommonMark\Extension\Table\TableExtension; +use League\CommonMark\Extension\TaskList\TaskListExtension; + +final class GithubFlavoredMarkdownExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addExtension(new AutolinkExtension()); + $environment->addExtension(new DisallowedRawHtmlExtension()); + $environment->addExtension(new StrikethroughExtension()); + $environment->addExtension(new TableExtension()); + $environment->addExtension(new TaskListExtension()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php new file mode 100644 index 0000000..df9bded --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php @@ -0,0 +1,37 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Node\Inline\AbstractInline; + +/** + * Represents an anchor link within a heading + */ +final class HeadingPermalink extends AbstractInline +{ + /** @psalm-readonly */ + private string $slug; + + public function __construct(string $slug) + { + parent::__construct(); + + $this->slug = $slug; + } + + public function getSlug(): string + { + return $this->slug; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php new file mode 100644 index 0000000..96473a2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php @@ -0,0 +1,49 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +/** + * Extension which automatically anchor links to heading elements + */ +final class HeadingPermalinkExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('heading_permalink', Expect::structure([ + 'min_heading_level' => Expect::int()->min(1)->max(6)->default(1), + 'max_heading_level' => Expect::int()->min(1)->max(6)->default(6), + 'insert' => Expect::anyOf(HeadingPermalinkProcessor::INSERT_BEFORE, HeadingPermalinkProcessor::INSERT_AFTER, HeadingPermalinkProcessor::INSERT_NONE)->default(HeadingPermalinkProcessor::INSERT_BEFORE), + 'id_prefix' => Expect::string()->default('content'), + 'apply_id_to_heading' => Expect::bool()->default(false), + 'heading_class' => Expect::string()->default(''), + 'fragment_prefix' => Expect::string()->default('content'), + 'html_class' => Expect::string()->default('heading-permalink'), + 'title' => Expect::string()->default('Permalink'), + 'symbol' => Expect::string()->default(HeadingPermalinkRenderer::DEFAULT_SYMBOL), + 'aria_hidden' => Expect::bool()->default(true), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, new HeadingPermalinkProcessor(), -100); + $environment->addRenderer(HeadingPermalink::class, new HeadingPermalinkRenderer()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php new file mode 100644 index 0000000..871aa21 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php @@ -0,0 +1,101 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Node\RawMarkupContainerInterface; +use League\CommonMark\Node\StringContainerHelper; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\Config\ConfigurationInterface; +use League\Config\Exception\InvalidConfigurationException; + +/** + * Searches the Document for Heading elements and adds HeadingPermalinks to each one + */ +final class HeadingPermalinkProcessor implements EnvironmentAwareInterface +{ + public const INSERT_BEFORE = 'before'; + public const INSERT_AFTER = 'after'; + public const INSERT_NONE = 'none'; + + /** @psalm-readonly-allow-private-mutation */ + private TextNormalizerInterface $slugNormalizer; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->config = $environment->getConfiguration(); + $this->slugNormalizer = $environment->getSlugNormalizer(); + } + + public function __invoke(DocumentParsedEvent $e): void + { + $min = (int) $this->config->get('heading_permalink/min_heading_level'); + $max = (int) $this->config->get('heading_permalink/max_heading_level'); + $applyToHeading = (bool) $this->config->get('heading_permalink/apply_id_to_heading'); + $idPrefix = (string) $this->config->get('heading_permalink/id_prefix'); + $slugLength = (int) $this->config->get('slug_normalizer/max_length'); + $headingClass = (string) $this->config->get('heading_permalink/heading_class'); + + if ($idPrefix !== '') { + $idPrefix .= '-'; + } + + foreach ($e->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if ($node instanceof Heading && $node->getLevel() >= $min && $node->getLevel() <= $max) { + $this->addHeadingLink($node, $slugLength, $idPrefix, $applyToHeading, $headingClass); + } + } + } + + private function addHeadingLink(Heading $heading, int $slugLength, string $idPrefix, bool $applyToHeading, string $headingClass): void + { + $text = StringContainerHelper::getChildText($heading, [RawMarkupContainerInterface::class]); + $slug = $this->slugNormalizer->normalize($text, [ + 'node' => $heading, + 'length' => $slugLength, + ]); + + if ($applyToHeading) { + $heading->data->set('attributes/id', $idPrefix . $slug); + } + + if ($headingClass !== '') { + $heading->data->append('attributes/class', $headingClass); + } + + $headingLinkAnchor = new HeadingPermalink($slug); + + switch ($this->config->get('heading_permalink/insert')) { + case self::INSERT_BEFORE: + $heading->prependChild($headingLinkAnchor); + + return; + case self::INSERT_AFTER: + $heading->appendChild($headingLinkAnchor); + + return; + case self::INSERT_NONE: + return; + default: + throw new InvalidConfigurationException("Invalid configuration value for heading_permalink/insert; expected 'before', 'after', or 'none'"); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php new file mode 100644 index 0000000..59a86a1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php @@ -0,0 +1,106 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +/** + * Renders the HeadingPermalink elements + */ +final class HeadingPermalinkRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + public const DEFAULT_SYMBOL = '¶'; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + /** + * @param HeadingPermalink $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + HeadingPermalink::assertInstanceOf($node); + + $slug = $node->getSlug(); + + $fragmentPrefix = (string) $this->config->get('heading_permalink/fragment_prefix'); + if ($fragmentPrefix !== '') { + $fragmentPrefix .= '-'; + } + + $attrs = $node->data->getData('attributes'); + $appendId = ! $this->config->get('heading_permalink/apply_id_to_heading'); + + if ($appendId) { + $idPrefix = (string) $this->config->get('heading_permalink/id_prefix'); + + if ($idPrefix !== '') { + $idPrefix .= '-'; + } + + $attrs->set('id', $idPrefix . $slug); + } + + $attrs->set('href', '#' . $fragmentPrefix . $slug); + $attrs->append('class', $this->config->get('heading_permalink/html_class')); + + $hidden = $this->config->get('heading_permalink/aria_hidden'); + if ($hidden) { + $attrs->set('aria-hidden', 'true'); + } + + $attrs->set('title', $this->config->get('heading_permalink/title')); + + $symbol = $this->config->get('heading_permalink/symbol'); + \assert(\is_string($symbol)); + + return new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), false); + } + + public function getXmlTagName(Node $node): string + { + return 'heading_permalink'; + } + + /** + * @param HeadingPermalink $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + HeadingPermalink::assertInstanceOf($node); + + return [ + 'slug' => $node->getSlug(), + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php new file mode 100644 index 0000000..403e948 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php @@ -0,0 +1,35 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\InlinesOnly; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; + +/** + * Simply renders child elements as-is, adding newlines as needed. + */ +final class ChildRenderer implements NodeRendererInterface +{ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + $out = $childRenderer->renderNodes($node->children()); + if (! $node instanceof Document) { + $out .= $childRenderer->getBlockSeparator(); + } + + return $out; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php new file mode 100644 index 0000000..7777510 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\InlinesOnly; + +use League\CommonMark as Core; +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\CommonMark; +use League\CommonMark\Extension\CommonMark\Delimiter\Processor\EmphasisDelimiterProcessor; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class InlinesOnlyExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('commonmark', Expect::structure([ + 'use_asterisk' => Expect::bool(true), + 'use_underscore' => Expect::bool(true), + 'enable_strong' => Expect::bool(true), + 'enable_em' => Expect::bool(true), + ])); + } + + // phpcs:disable Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma,Squiz.WhiteSpace.SemicolonSpacing.Incorrect + public function register(EnvironmentBuilderInterface $environment): void + { + $childRenderer = new ChildRenderer(); + + $environment + ->addInlineParser(new Core\Parser\Inline\NewlineParser(), 200) + ->addInlineParser(new CommonMark\Parser\Inline\BacktickParser(), 150) + ->addInlineParser(new CommonMark\Parser\Inline\EscapableParser(), 80) + ->addInlineParser(new CommonMark\Parser\Inline\EntityParser(), 70) + ->addInlineParser(new CommonMark\Parser\Inline\AutolinkParser(), 50) + ->addInlineParser(new CommonMark\Parser\Inline\HtmlInlineParser(), 40) + ->addInlineParser(new CommonMark\Parser\Inline\CloseBracketParser(), 30) + ->addInlineParser(new CommonMark\Parser\Inline\OpenBracketParser(), 20) + ->addInlineParser(new CommonMark\Parser\Inline\BangParser(), 10) + + ->addRenderer(Core\Node\Block\Document::class, $childRenderer, 0) + ->addRenderer(Core\Node\Block\Paragraph::class, $childRenderer, 0) + + ->addRenderer(CommonMark\Node\Inline\Code::class, new CommonMark\Renderer\Inline\CodeRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Emphasis::class, new CommonMark\Renderer\Inline\EmphasisRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\HtmlInline::class, new CommonMark\Renderer\Inline\HtmlInlineRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Image::class, new CommonMark\Renderer\Inline\ImageRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Link::class, new CommonMark\Renderer\Inline\LinkRenderer(), 0) + ->addRenderer(Core\Node\Inline\Newline::class, new Core\Renderer\Inline\NewlineRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Strong::class, new CommonMark\Renderer\Inline\StrongRenderer(), 0) + ->addRenderer(Core\Node\Inline\Text::class, new Core\Renderer\Inline\TextRenderer(), 0) + ; + + if ($environment->getConfiguration()->get('commonmark/use_asterisk')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('*')); + } + + if ($environment->getConfiguration()->get('commonmark/use_underscore')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('_')); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php new file mode 100644 index 0000000..d0b6292 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention\Generator; + +use League\CommonMark\Exception\LogicException; +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AbstractInline; + +final class CallbackGenerator implements MentionGeneratorInterface +{ + /** + * A callback function which sets the URL on the passed mention and returns the mention, return a new AbstractInline based object or null if the mention is not a match + * + * @var callable(Mention): ?AbstractInline + */ + private $callback; + + public function __construct(callable $callback) + { + $this->callback = $callback; + } + + /** + * @throws LogicException + */ + public function generateMention(Mention $mention): ?AbstractInline + { + $result = \call_user_func($this->callback, $mention); + if ($result === null) { + return null; + } + + if ($result instanceof AbstractInline && ! ($result instanceof Mention)) { + return $result; + } + + if ($result instanceof Mention && $result->hasUrl()) { + return $mention; + } + + throw new LogicException('CallbackGenerator callable must set the URL on the passed mention and return the mention, return a new AbstractInline based object or null if the mention is not a match'); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php new file mode 100644 index 0000000..30d4a51 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention\Generator; + +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AbstractInline; + +interface MentionGeneratorInterface +{ + public function generateMention(Mention $mention): ?AbstractInline; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php new file mode 100644 index 0000000..5d92897 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention\Generator; + +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AbstractInline; + +final class StringTemplateLinkGenerator implements MentionGeneratorInterface +{ + private string $urlTemplate; + + public function __construct(string $urlTemplate) + { + $this->urlTemplate = $urlTemplate; + } + + public function generateMention(Mention $mention): ?AbstractInline + { + $mention->setUrl(\sprintf($this->urlTemplate, $mention->getIdentifier())); + + return $mention; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Mention.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Mention.php new file mode 100644 index 0000000..74eaee4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/Mention.php @@ -0,0 +1,93 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Node\Inline\Text; + +class Mention extends Link +{ + private string $name; + + private string $prefix; + + private string $identifier; + + public function __construct(string $name, string $prefix, string $identifier, ?string $label = null) + { + $this->name = $name; + $this->prefix = $prefix; + $this->identifier = $identifier; + + parent::__construct('', $label ?? \sprintf('%s%s', $prefix, $identifier)); + } + + public function getLabel(): ?string + { + if (($labelNode = $this->findLabelNode()) === null) { + return null; + } + + return $labelNode->getLiteral(); + } + + public function getIdentifier(): string + { + return $this->identifier; + } + + public function getName(): ?string + { + return $this->name; + } + + public function getPrefix(): string + { + return $this->prefix; + } + + public function hasUrl(): bool + { + return $this->url !== ''; + } + + /** + * @return $this + */ + public function setLabel(string $label): self + { + if (($labelNode = $this->findLabelNode()) === null) { + $labelNode = new Text(); + $this->prependChild($labelNode); + } + + $labelNode->setLiteral($label); + + return $this; + } + + private function findLabelNode(): ?Text + { + foreach ($this->children() as $child) { + if ($child instanceof Text) { + return $child; + } + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/MentionExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/MentionExtension.php new file mode 100644 index 0000000..c848c26 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/MentionExtension.php @@ -0,0 +1,61 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface; +use League\Config\ConfigurationBuilderInterface; +use League\Config\Exception\InvalidConfigurationException; +use Nette\Schema\Expect; + +final class MentionExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $isAValidPartialRegex = static function (string $regex): bool { + $regex = '/' . $regex . '/i'; + + return @\preg_match($regex, '') !== false; + }; + + $builder->addSchema('mentions', Expect::arrayOf( + Expect::structure([ + 'prefix' => Expect::string()->required(), + 'pattern' => Expect::string()->assert($isAValidPartialRegex, 'Pattern must not include starting/ending delimiters (like "/")')->required(), + 'generator' => Expect::anyOf( + Expect::type(MentionGeneratorInterface::class), + Expect::string(), + Expect::type('callable') + )->required(), + ]) + )); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $mentions = $environment->getConfiguration()->get('mentions'); + foreach ($mentions as $name => $mention) { + if ($mention['generator'] instanceof MentionGeneratorInterface) { + $environment->addInlineParser(new MentionParser($name, $mention['prefix'], $mention['pattern'], $mention['generator'])); + } elseif (\is_string($mention['generator'])) { + $environment->addInlineParser(MentionParser::createWithStringTemplate($name, $mention['prefix'], $mention['pattern'], $mention['generator'])); + } elseif (\is_callable($mention['generator'])) { + $environment->addInlineParser(MentionParser::createWithCallback($name, $mention['prefix'], $mention['pattern'], $mention['generator'])); + } else { + throw new InvalidConfigurationException(\sprintf('The "generator" provided for the "%s" MentionParser configuration must be a string template, callable, or an object that implements %s.', $name, MentionGeneratorInterface::class)); + } + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/MentionParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/MentionParser.php new file mode 100644 index 0000000..a81c787 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Mention/MentionParser.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention; + +use League\CommonMark\Extension\Mention\Generator\CallbackGenerator; +use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface; +use League\CommonMark\Extension\Mention\Generator\StringTemplateLinkGenerator; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class MentionParser implements InlineParserInterface +{ + /** @psalm-readonly */ + private string $name; + + /** @psalm-readonly */ + private string $prefix; + + /** @psalm-readonly */ + private string $identifierPattern; + + /** @psalm-readonly */ + private MentionGeneratorInterface $mentionGenerator; + + public function __construct(string $name, string $prefix, string $identifierPattern, MentionGeneratorInterface $mentionGenerator) + { + $this->name = $name; + $this->prefix = $prefix; + $this->identifierPattern = $identifierPattern; + $this->mentionGenerator = $mentionGenerator; + } + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::join( + InlineParserMatch::string($this->prefix), + InlineParserMatch::regex($this->identifierPattern) + ); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + + // The prefix must not have any other characters immediately prior + $previousChar = $cursor->peek(-1); + if ($previousChar !== null && \preg_match('/\w/', $previousChar)) { + // peek() doesn't modify the cursor, so no need to restore state first + return false; + } + + [$prefix, $identifier] = $inlineContext->getSubMatches(); + + $mention = $this->mentionGenerator->generateMention(new Mention($this->name, $prefix, $identifier)); + + if ($mention === null) { + return false; + } + + $cursor->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild($mention); + + return true; + } + + public static function createWithStringTemplate(string $name, string $prefix, string $mentionRegex, string $urlTemplate): MentionParser + { + return new self($name, $prefix, $mentionRegex, new StringTemplateLinkGenerator($urlTemplate)); + } + + public static function createWithCallback(string $name, string $prefix, string $mentionRegex, callable $callback): MentionParser + { + return new self($name, $prefix, $mentionRegex, new CallbackGenerator($callback)); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php new file mode 100644 index 0000000..cf0e1af --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php @@ -0,0 +1,59 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class DashParser implements InlineParserInterface +{ + private const EN_DASH = '–'; + private const EM_DASH = '—'; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('(?<!-)(-{2,})'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $count = $inlineContext->getFullMatchLength(); + $inlineContext->getCursor()->advanceBy($count); + + $enCount = 0; + $emCount = 0; + if ($count % 3 === 0) { // If divisible by 3, use all em dashes + $emCount = (int) ($count / 3); + } elseif ($count % 2 === 0) { // If divisible by 2, use all en dashes + $enCount = (int) ($count / 2); + } elseif ($count % 3 === 2) { // If 2 extra dashes, use en dash for last 2; em dashes for rest + $emCount = (int) (($count - 2) / 3); + $enCount = 1; + } else { // Use en dashes for last 4 hyphens; em dashes for rest + $emCount = (int) (($count - 4) / 3); + $enCount = 2; + } + + $inlineContext->getContainer()->appendChild(new Text( + \str_repeat(self::EM_DASH, $emCount) . \str_repeat(self::EN_DASH, $enCount) + )); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php new file mode 100644 index 0000000..9f5b3bd --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php @@ -0,0 +1,38 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class EllipsesParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf('...', '. . .'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild(new Text('…')); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/Quote.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/Quote.php new file mode 100644 index 0000000..dee9759 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/Quote.php @@ -0,0 +1,30 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class Quote extends AbstractStringContainer +{ + public const DOUBLE_QUOTE = '"'; + public const DOUBLE_QUOTE_OPENER = '“'; + public const DOUBLE_QUOTE_CLOSER = '”'; + + public const SINGLE_QUOTE = "'"; + public const SINGLE_QUOTE_OPENER = '‘'; + public const SINGLE_QUOTE_CLOSER = '’'; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php new file mode 100644 index 0000000..b77d085 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php @@ -0,0 +1,105 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Delimiter\Delimiter; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; + +final class QuoteParser implements InlineParserInterface +{ + public const DOUBLE_QUOTES = [Quote::DOUBLE_QUOTE, Quote::DOUBLE_QUOTE_OPENER, Quote::DOUBLE_QUOTE_CLOSER]; + public const SINGLE_QUOTES = [Quote::SINGLE_QUOTE, Quote::SINGLE_QUOTE_OPENER, Quote::SINGLE_QUOTE_CLOSER]; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf(...[...self::DOUBLE_QUOTES, ...self::SINGLE_QUOTES]); + } + + /** + * Normalizes any quote characters found and manually adds them to the delimiter stack + */ + public function parse(InlineParserContext $inlineContext): bool + { + $char = $inlineContext->getFullMatch(); + $cursor = $inlineContext->getCursor(); + + $normalizedCharacter = $this->getNormalizedQuoteCharacter($char); + + $charBefore = $cursor->peek(-1); + if ($charBefore === null) { + $charBefore = "\n"; + } + + $cursor->advance(); + + $charAfter = $cursor->getCurrentCharacter(); + if ($charAfter === null) { + $charAfter = "\n"; + } + + [$leftFlanking, $rightFlanking] = $this->determineFlanking($charBefore, $charAfter); + $canOpen = $leftFlanking && ! $rightFlanking; + $canClose = $rightFlanking; + + $node = new Quote($normalizedCharacter, ['delim' => true]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack to this opener + $inlineContext->getDelimiterStack()->push(new Delimiter($normalizedCharacter, 1, $node, $canOpen, $canClose)); + + return true; + } + + private function getNormalizedQuoteCharacter(string $character): string + { + if (\in_array($character, self::DOUBLE_QUOTES, true)) { + return Quote::DOUBLE_QUOTE; + } + + if (\in_array($character, self::SINGLE_QUOTES, true)) { + return Quote::SINGLE_QUOTE; + } + + return $character; + } + + /** + * @return bool[] + */ + private function determineFlanking(string $charBefore, string $charAfter): array + { + $afterIsWhitespace = \preg_match('/\pZ|\s/u', $charAfter); + $afterIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charAfter); + $beforeIsWhitespace = \preg_match('/\pZ|\s/u', $charBefore); + $beforeIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charBefore); + + $leftFlanking = ! $afterIsWhitespace && + ! ($afterIsPunctuation && + ! $beforeIsWhitespace && + ! $beforeIsPunctuation); + + $rightFlanking = ! $beforeIsWhitespace && + ! ($beforeIsPunctuation && + ! $afterIsWhitespace && + ! $afterIsPunctuation); + + return [$leftFlanking, $rightFlanking]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php new file mode 100644 index 0000000..1fc30d4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php @@ -0,0 +1,82 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class QuoteProcessor implements DelimiterProcessorInterface +{ + /** @psalm-readonly */ + private string $normalizedCharacter; + + /** @psalm-readonly */ + private string $openerCharacter; + + /** @psalm-readonly */ + private string $closerCharacter; + + private function __construct(string $char, string $opener, string $closer) + { + $this->normalizedCharacter = $char; + $this->openerCharacter = $opener; + $this->closerCharacter = $closer; + } + + public function getOpeningCharacter(): string + { + return $this->normalizedCharacter; + } + + public function getClosingCharacter(): string + { + return $this->normalizedCharacter; + } + + public function getMinLength(): int + { + return 1; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + return 1; + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $opener->insertAfter(new Quote($this->openerCharacter)); + $closer->insertBefore(new Quote($this->closerCharacter)); + } + + /** + * Create a double-quote processor + */ + public static function createDoubleQuoteProcessor(string $opener = Quote::DOUBLE_QUOTE_OPENER, string $closer = Quote::DOUBLE_QUOTE_CLOSER): self + { + return new self(Quote::DOUBLE_QUOTE, $opener, $closer); + } + + /** + * Create a single-quote processor + */ + public static function createSingleQuoteProcessor(string $opener = Quote::SINGLE_QUOTE_OPENER, string $closer = Quote::SINGLE_QUOTE_CLOSER): self + { + return new self(Quote::SINGLE_QUOTE, $opener, $closer); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php new file mode 100644 index 0000000..3536452 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\Query; + +/** + * Identifies any lingering Quote nodes that were missing pairs and converts them into Text nodes + */ +final class ReplaceUnpairedQuotesListener +{ + public function __invoke(DocumentParsedEvent $event): void + { + $query = (new Query())->where(Query::type(Quote::class)); + foreach ($query->findAll($event->getDocument()) as $quote) { + \assert($quote instanceof Quote); + + $literal = $quote->getLiteral(); + if ($literal === Quote::SINGLE_QUOTE) { + $literal = Quote::SINGLE_QUOTE_CLOSER; + } elseif ($literal === Quote::DOUBLE_QUOTE) { + $literal = Quote::DOUBLE_QUOTE_OPENER; + } + + $quote->replaceWith($new = new Text($literal)); + AdjacentTextMerger::mergeWithDirectlyAdjacentNodes($new); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php new file mode 100644 index 0000000..8524ca1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Renderer\Block as CoreBlockRenderer; +use League\CommonMark\Renderer\Inline as CoreInlineRenderer; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class SmartPunctExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('smartpunct', Expect::structure([ + 'double_quote_opener' => Expect::string(Quote::DOUBLE_QUOTE_OPENER), + 'double_quote_closer' => Expect::string(Quote::DOUBLE_QUOTE_CLOSER), + 'single_quote_opener' => Expect::string(Quote::SINGLE_QUOTE_OPENER), + 'single_quote_closer' => Expect::string(Quote::SINGLE_QUOTE_CLOSER), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment + ->addInlineParser(new QuoteParser(), 10) + ->addInlineParser(new DashParser(), 0) + ->addInlineParser(new EllipsesParser(), 0) + + ->addDelimiterProcessor(QuoteProcessor::createDoubleQuoteProcessor( + $environment->getConfiguration()->get('smartpunct/double_quote_opener'), + $environment->getConfiguration()->get('smartpunct/double_quote_closer') + )) + ->addDelimiterProcessor(QuoteProcessor::createSingleQuoteProcessor( + $environment->getConfiguration()->get('smartpunct/single_quote_opener'), + $environment->getConfiguration()->get('smartpunct/single_quote_closer') + )) + + ->addEventListener(DocumentParsedEvent::class, new ReplaceUnpairedQuotesListener()) + + ->addRenderer(Document::class, new CoreBlockRenderer\DocumentRenderer(), 0) + ->addRenderer(Paragraph::class, new CoreBlockRenderer\ParagraphRenderer(), 0) + ->addRenderer(Text::class, new CoreInlineRenderer\TextRenderer(), 0); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php new file mode 100644 index 0000000..20ad161 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Strikethrough extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '~~') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php new file mode 100644 index 0000000..af0fdb1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php @@ -0,0 +1,63 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class StrikethroughDelimiterProcessor implements DelimiterProcessorInterface +{ + public function getOpeningCharacter(): string + { + return '~'; + } + + public function getClosingCharacter(): string + { + return '~'; + } + + public function getMinLength(): int + { + return 1; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + if ($opener->getLength() > 2 && $closer->getLength() > 2) { + return 0; + } + + if ($opener->getLength() !== $closer->getLength()) { + return 0; + } + + return \min($opener->getLength(), $closer->getLength()); + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $strikethrough = new Strikethrough(\str_repeat('~', $delimiterUse)); + + $tmp = $opener->next(); + while ($tmp !== null && $tmp !== $closer) { + $next = $tmp->next(); + $strikethrough->appendChild($tmp); + $tmp = $next; + } + + $opener->insertAfter($strikethrough); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php new file mode 100644 index 0000000..96ffe7a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ExtensionInterface; + +final class StrikethroughExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addDelimiterProcessor(new StrikethroughDelimiterProcessor()); + $environment->addRenderer(Strikethrough::class, new StrikethroughRenderer()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php new file mode 100644 index 0000000..a50b895 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class StrikethroughRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Strikethrough $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Strikethrough::assertInstanceOf($node); + + return new HtmlElement('del', $node->data->get('attributes'), $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'strikethrough'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/Table.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/Table.php new file mode 100644 index 0000000..2fe441d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/Table.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Table extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableCell.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableCell.php new file mode 100644 index 0000000..6ed359a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableCell.php @@ -0,0 +1,99 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableCell extends AbstractBlock +{ + public const TYPE_HEADER = 'header'; + public const TYPE_DATA = 'data'; + + public const ALIGN_LEFT = 'left'; + public const ALIGN_RIGHT = 'right'; + public const ALIGN_CENTER = 'center'; + + /** + * @psalm-var self::TYPE_* + * @phpstan-var self::TYPE_* + * + * @psalm-readonly-allow-private-mutation + */ + private string $type = self::TYPE_DATA; + + /** + * @psalm-var self::ALIGN_*|null + * @phpstan-var self::ALIGN_*|null + * + * @psalm-readonly-allow-private-mutation + */ + private ?string $align = null; + + /** + * @psalm-param self::TYPE_* $type + * @psalm-param self::ALIGN_*|null $align + * + * @phpstan-param self::TYPE_* $type + * @phpstan-param self::ALIGN_*|null $align + */ + public function __construct(string $type = self::TYPE_DATA, ?string $align = null) + { + parent::__construct(); + + $this->type = $type; + $this->align = $align; + } + + /** + * @psalm-return self::TYPE_* + * + * @phpstan-return self::TYPE_* + */ + public function getType(): string + { + return $this->type; + } + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function setType(string $type): void + { + $this->type = $type; + } + + /** + * @psalm-return self::ALIGN_*|null + * + * @phpstan-return self::ALIGN_*|null + */ + public function getAlign(): ?string + { + return $this->align; + } + + /** + * @psalm-param self::ALIGN_*|null $align + * + * @phpstan-param self::ALIGN_*|null $align + */ + public function setAlign(?string $align): void + { + $this->align = $align; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php new file mode 100644 index 0000000..99512c3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php @@ -0,0 +1,89 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableCellRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + private const DEFAULT_ATTRIBUTES = [ + TableCell::ALIGN_LEFT => ['align' => 'left'], + TableCell::ALIGN_CENTER => ['align' => 'center'], + TableCell::ALIGN_RIGHT => ['align' => 'right'], + ]; + + /** @var array<TableCell::ALIGN_*, array<string, string|string[]|bool>> */ + private array $alignmentAttributes; + + /** + * @param array<TableCell::ALIGN_*, array<string, string|string[]|bool>> $alignmentAttributes + */ + public function __construct(array $alignmentAttributes = self::DEFAULT_ATTRIBUTES) + { + $this->alignmentAttributes = $alignmentAttributes; + } + + /** + * @param TableCell $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + TableCell::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + if (($alignment = $node->getAlign()) !== null) { + $attrs = AttributesHelper::mergeAttributes($attrs, $this->alignmentAttributes[$alignment]); + } + + $tag = $node->getType() === TableCell::TYPE_HEADER ? 'th' : 'td'; + + return new HtmlElement($tag, $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'table_cell'; + } + + /** + * @param TableCell $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + TableCell::assertInstanceOf($node); + + $ret = ['type' => $node->getType()]; + + if (($align = $node->getAlign()) !== null) { + $ret['align'] = $align; + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableExtension.php new file mode 100644 index 0000000..27a58bb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableExtension.php @@ -0,0 +1,62 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Renderer\HtmlDecorator; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class TableExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $attributeArraySchema = Expect::arrayOf( + Expect::type('string|string[]|bool'), // attribute value(s) + 'string' // attribute name + )->mergeDefaults(false); + + $builder->addSchema('table', Expect::structure([ + 'wrap' => Expect::structure([ + 'enabled' => Expect::bool()->default(false), + 'tag' => Expect::string()->default('div'), + 'attributes' => Expect::arrayOf(Expect::string()), + ]), + 'alignment_attributes' => Expect::structure([ + 'left' => (clone $attributeArraySchema)->default(['align' => 'left']), + 'center' => (clone $attributeArraySchema)->default(['align' => 'center']), + 'right' => (clone $attributeArraySchema)->default(['align' => 'right']), + ]), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $tableRenderer = new TableRenderer(); + if ($environment->getConfiguration()->get('table/wrap/enabled')) { + $tableRenderer = new HtmlDecorator($tableRenderer, $environment->getConfiguration()->get('table/wrap/tag'), $environment->getConfiguration()->get('table/wrap/attributes')); + } + + $environment + ->addBlockStartParser(new TableStartParser()) + + ->addRenderer(Table::class, $tableRenderer) + ->addRenderer(TableSection::class, new TableSectionRenderer()) + ->addRenderer(TableRow::class, new TableRowRenderer()) + ->addRenderer(TableCell::class, new TableCellRenderer($environment->getConfiguration()->get('table/alignment_attributes'))); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableParser.php new file mode 100644 index 0000000..ca340a3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableParser.php @@ -0,0 +1,200 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; +use League\CommonMark\Util\ArrayCollection; + +final class TableParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + /** @psalm-readonly */ + private Table $block; + + /** + * @var ArrayCollection<string> + * + * @psalm-readonly-allow-private-mutation + */ + private ArrayCollection $bodyLines; + + /** + * @var array<int, string|null> + * @psalm-var array<int, TableCell::ALIGN_*|null> + * @phpstan-var array<int, TableCell::ALIGN_*|null> + * + * @psalm-readonly + */ + private array $columns; + + /** + * @var array<int, string> + * + * @psalm-readonly-allow-private-mutation + */ + private array $headerCells; + + /** @psalm-readonly-allow-private-mutation */ + private bool $nextIsSeparatorLine = true; + + /** + * @param array<int, string|null> $columns + * @param array<int, string> $headerCells + * + * @psalm-param array<int, TableCell::ALIGN_*|null> $columns + * + * @phpstan-param array<int, TableCell::ALIGN_*|null> $columns + */ + public function __construct(array $columns, array $headerCells) + { + $this->block = new Table(); + $this->bodyLines = new ArrayCollection(); + $this->columns = $columns; + $this->headerCells = $headerCells; + } + + public function canHaveLazyContinuationLines(): bool + { + return true; + } + + public function getBlock(): Table + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if (\strpos($cursor->getLine(), '|') === false) { + return BlockContinue::none(); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + if ($this->nextIsSeparatorLine) { + $this->nextIsSeparatorLine = false; + } else { + $this->bodyLines[] = $line; + } + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + $headerColumns = \count($this->headerCells); + + $head = new TableSection(TableSection::TYPE_HEAD); + $this->block->appendChild($head); + + $headerRow = new TableRow(); + $head->appendChild($headerRow); + for ($i = 0; $i < $headerColumns; $i++) { + $cell = $this->headerCells[$i]; + $tableCell = $this->parseCell($cell, $i, $inlineParser); + $tableCell->setType(TableCell::TYPE_HEADER); + $headerRow->appendChild($tableCell); + } + + $body = null; + foreach ($this->bodyLines as $rowLine) { + $cells = self::split($rowLine); + $row = new TableRow(); + + // Body can not have more columns than head + for ($i = 0; $i < $headerColumns; $i++) { + $cell = $cells[$i] ?? ''; + $tableCell = $this->parseCell($cell, $i, $inlineParser); + $row->appendChild($tableCell); + } + + if ($body === null) { + // It's valid to have a table without body. In that case, don't add an empty TableBody node. + $body = new TableSection(); + $this->block->appendChild($body); + } + + $body->appendChild($row); + } + } + + private function parseCell(string $cell, int $column, InlineParserEngineInterface $inlineParser): TableCell + { + $tableCell = new TableCell(); + + if ($column < \count($this->columns)) { + $tableCell->setAlign($this->columns[$column]); + } + + $inlineParser->parse(\trim($cell), $tableCell); + + return $tableCell; + } + + /** + * @internal + * + * @return array<int, string> + */ + public static function split(string $line): array + { + $cursor = new Cursor(\trim($line)); + + if ($cursor->getCurrentCharacter() === '|') { + $cursor->advanceBy(1); + } + + $cells = []; + $sb = ''; + + while (! $cursor->isAtEnd()) { + switch ($c = $cursor->getCurrentCharacter()) { + case '\\': + if ($cursor->peek() === '|') { + // Pipe is special for table parsing. An escaped pipe doesn't result in a new cell, but is + // passed down to inline parsing as an unescaped pipe. Note that that applies even for the `\|` + // in an input like `\\|` - in other words, table parsing doesn't support escaping backslashes. + $sb .= '|'; + $cursor->advanceBy(1); + } else { + // Preserve backslash before other characters or at end of line. + $sb .= '\\'; + } + + break; + case '|': + $cells[] = $sb; + $sb = ''; + break; + default: + $sb .= $c; + } + + $cursor->advanceBy(1); + } + + if ($sb !== '') { + $cells[] = $sb; + } + + return $cells; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRenderer.php new file mode 100644 index 0000000..7799e22 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRenderer.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Table $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Table::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $separator = $childRenderer->getInnerSeparator(); + + $children = $childRenderer->renderNodes($node->children()); + + return new HtmlElement('table', $attrs, $separator . \trim($children) . $separator); + } + + public function getXmlTagName(Node $node): string + { + return 'table'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRow.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRow.php new file mode 100644 index 0000000..cd6ac99 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRow.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableRow extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php new file mode 100644 index 0000000..dee72d2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableRowRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param TableRow $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + TableRow::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $separator = $childRenderer->getInnerSeparator(); + + return new HtmlElement('tr', $attrs, $separator . $childRenderer->renderNodes($node->children()) . $separator); + } + + public function getXmlTagName(Node $node): string + { + return 'table_row'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableSection.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableSection.php new file mode 100644 index 0000000..9edd63b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableSection.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableSection extends AbstractBlock +{ + public const TYPE_HEAD = 'head'; + public const TYPE_BODY = 'body'; + + /** + * @psalm-var self::TYPE_* + * @phpstan-var self::TYPE_* + * + * @psalm-readonly + */ + private string $type; + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function __construct(string $type = self::TYPE_BODY) + { + parent::__construct(); + + $this->type = $type; + } + + /** + * @psalm-return self::TYPE_* + * + * @phpstan-return self::TYPE_* + */ + public function getType(): string + { + return $this->type; + } + + public function isHead(): bool + { + return $this->type === self::TYPE_HEAD; + } + + public function isBody(): bool + { + return $this->type === self::TYPE_BODY; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php new file mode 100644 index 0000000..cccf06c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php @@ -0,0 +1,70 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableSectionRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param TableSection $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + TableSection::assertInstanceOf($node); + + if (! $node->hasChildren()) { + return ''; + } + + $attrs = $node->data->get('attributes'); + + $separator = $childRenderer->getInnerSeparator(); + + $tag = $node->getType() === TableSection::TYPE_HEAD ? 'thead' : 'tbody'; + + return new HtmlElement($tag, $attrs, $separator . $childRenderer->renderNodes($node->children()) . $separator); + } + + public function getXmlTagName(Node $node): string + { + return 'table_section'; + } + + /** + * @param TableSection $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + TableSection::assertInstanceOf($node); + + return [ + 'type' => $node->getType(), + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableStartParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableStartParser.php new file mode 100644 index 0000000..12206d2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/Table/TableStartParser.php @@ -0,0 +1,158 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Block\ParagraphParser; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class TableStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + $paragraph = $parserState->getParagraphContent(); + if ($paragraph === null || \strpos($paragraph, '|') === false) { + return BlockStart::none(); + } + + $columns = self::parseSeparator($cursor); + if (\count($columns) === 0) { + return BlockStart::none(); + } + + $lines = \explode("\n", $paragraph); + $lastLine = \array_pop($lines); + + $headerCells = TableParser::split($lastLine); + if (\count($headerCells) > \count($columns)) { + return BlockStart::none(); + } + + $cursor->advanceToEnd(); + + $parsers = []; + + if (\count($lines) > 0) { + $p = new ParagraphParser(); + $p->addLine(\implode("\n", $lines)); + $parsers[] = $p; + } + + $parsers[] = new TableParser($columns, $headerCells); + + return BlockStart::of(...$parsers) + ->at($cursor) + ->replaceActiveBlockParser(); + } + + /** + * @return array<int, string|null> + * + * @psalm-return array<int, TableCell::ALIGN_*|null> + * + * @phpstan-return array<int, TableCell::ALIGN_*|null> + */ + private static function parseSeparator(Cursor $cursor): array + { + $columns = []; + $pipes = 0; + $valid = false; + + while (! $cursor->isAtEnd()) { + switch ($c = $cursor->getCurrentCharacter()) { + case '|': + $cursor->advanceBy(1); + $pipes++; + if ($pipes > 1) { + // More than one adjacent pipe not allowed + return []; + } + + // Need at least one pipe, even for a one-column table + $valid = true; + break; + case '-': + case ':': + if ($pipes === 0 && \count($columns) > 0) { + // Need a pipe after the first column (first column doesn't need to start with one) + return []; + } + + $left = false; + $right = false; + if ($c === ':') { + $left = true; + $cursor->advanceBy(1); + } + + if ($cursor->match('/^-+/') === null) { + // Need at least one dash + return []; + } + + if ($cursor->getCurrentCharacter() === ':') { + $right = true; + $cursor->advanceBy(1); + } + + $columns[] = self::getAlignment($left, $right); + // Next, need another pipe + $pipes = 0; + break; + case ' ': + case "\t": + // White space is allowed between pipes and columns + $cursor->advanceToNextNonSpaceOrTab(); + break; + default: + // Any other character is invalid + return []; + } + } + + if (! $valid) { + return []; + } + + return $columns; + } + + /** + * @psalm-return TableCell::ALIGN_*|null + * + * @phpstan-return TableCell::ALIGN_*|null + * + * @psalm-pure + */ + private static function getAlignment(bool $left, bool $right): ?string + { + if ($left && $right) { + return TableCell::ALIGN_CENTER; + } + + if ($left) { + return TableCell::ALIGN_LEFT; + } + + if ($right) { + return TableCell::ALIGN_RIGHT; + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php new file mode 100644 index 0000000..e040d86 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Node; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; + +final class TableOfContents extends ListBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php new file mode 100644 index 0000000..6d6db10 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableOfContentsPlaceholder extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php new file mode 100644 index 0000000..f5bb9a4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php @@ -0,0 +1,72 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; + +final class AsIsNormalizerStrategy implements NormalizerStrategyInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ListBlock $parentListBlock; + + /** @psalm-readonly-allow-private-mutation */ + private int $parentLevel = 1; + + /** @psalm-readonly-allow-private-mutation */ + private ?ListItem $lastListItem = null; + + public function __construct(TableOfContents $toc) + { + $this->parentListBlock = $toc; + } + + public function addItem(int $level, ListItem $listItemToAdd): void + { + while ($level > $this->parentLevel) { + // Descend downwards, creating new ListBlocks if needed, until we reach the correct depth + if ($this->lastListItem === null) { + $this->lastListItem = new ListItem($this->parentListBlock->getListData()); + $this->parentListBlock->appendChild($this->lastListItem); + } + + $newListBlock = new ListBlock($this->parentListBlock->getListData()); + $newListBlock->setStartLine($listItemToAdd->getStartLine()); + $newListBlock->setEndLine($listItemToAdd->getEndLine()); + $this->lastListItem->appendChild($newListBlock); + $this->parentListBlock = $newListBlock; + $this->lastListItem = null; + + $this->parentLevel++; + } + + while ($level < $this->parentLevel) { + // Search upwards for the previous parent list block + $search = $this->parentListBlock; + while ($search = $search->parent()) { + if ($search instanceof ListBlock) { + $this->parentListBlock = $search; + break; + } + } + + $this->parentLevel--; + } + + $this->parentListBlock->appendChild($listItemToAdd); + + $this->lastListItem = $listItemToAdd; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php new file mode 100644 index 0000000..8e805ae --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; + +final class FlatNormalizerStrategy implements NormalizerStrategyInterface +{ + /** @psalm-readonly */ + private TableOfContents $toc; + + public function __construct(TableOfContents $toc) + { + $this->toc = $toc; + } + + public function addItem(int $level, ListItem $listItemToAdd): void + { + $this->toc->appendChild($listItemToAdd); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php new file mode 100644 index 0000000..f30afb1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; + +interface NormalizerStrategyInterface +{ + public function addItem(int $level, ListItem $listItemToAdd): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php new file mode 100644 index 0000000..1b2197f --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php @@ -0,0 +1,67 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; + +final class RelativeNormalizerStrategy implements NormalizerStrategyInterface +{ + /** @psalm-readonly */ + private TableOfContents $toc; + + /** + * @var array<int, ListItem> + * + * @psalm-readonly-allow-private-mutation + */ + private array $listItemStack = []; + + public function __construct(TableOfContents $toc) + { + $this->toc = $toc; + } + + public function addItem(int $level, ListItem $listItemToAdd): void + { + $previousLevel = \array_key_last($this->listItemStack); + + // Pop the stack if we're too deep + while ($previousLevel !== null && $level < $previousLevel) { + \array_pop($this->listItemStack); + $previousLevel = \array_key_last($this->listItemStack); + } + + $lastListItem = \end($this->listItemStack); + + // Need to go one level deeper? Add that level + if ($lastListItem !== false && $level > $previousLevel) { + $targetListBlock = new ListBlock($lastListItem->getListData()); + $targetListBlock->setStartLine($listItemToAdd->getStartLine()); + $targetListBlock->setEndLine($listItemToAdd->getEndLine()); + $lastListItem->appendChild($targetListBlock); + // Otherwise we're at the right level + // If there's no stack we're adding this item directly to the TOC element + } elseif ($lastListItem === false) { + $targetListBlock = $this->toc; + // Otherwise add it to the last list item + } else { + $targetListBlock = $lastListItem->parent(); + } + + $targetListBlock->appendChild($listItemToAdd); + $this->listItemStack[$level] = $listItemToAdd; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php new file mode 100644 index 0000000..7fe2b09 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php @@ -0,0 +1,106 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\NodeIterator; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; +use League\Config\Exception\InvalidConfigurationException; + +final class TableOfContentsBuilder implements ConfigurationAwareInterface +{ + public const POSITION_TOP = 'top'; + public const POSITION_BEFORE_HEADINGS = 'before-headings'; + public const POSITION_PLACEHOLDER = 'placeholder'; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + + $generator = new TableOfContentsGenerator( + (string) $this->config->get('table_of_contents/style'), + (string) $this->config->get('table_of_contents/normalize'), + (int) $this->config->get('table_of_contents/min_heading_level'), + (int) $this->config->get('table_of_contents/max_heading_level'), + (string) $this->config->get('heading_permalink/fragment_prefix'), + ); + + $toc = $generator->generate($document); + if ($toc === null) { + // No linkable headers exist, so no TOC could be generated + return; + } + + // Add custom CSS class(es), if defined + $class = $this->config->get('table_of_contents/html_class'); + if ($class !== null) { + $toc->data->append('attributes/class', $class); + } + + // Add the TOC to the Document + $position = $this->config->get('table_of_contents/position'); + if ($position === self::POSITION_TOP) { + $document->prependChild($toc); + } elseif ($position === self::POSITION_BEFORE_HEADINGS) { + $this->insertBeforeFirstLinkedHeading($document, $toc); + } elseif ($position === self::POSITION_PLACEHOLDER) { + $this->replacePlaceholders($document, $toc); + } else { + throw InvalidConfigurationException::forConfigOption('table_of_contents/position', $position); + } + } + + private function insertBeforeFirstLinkedHeading(Document $document, TableOfContents $toc): void + { + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Heading) { + continue; + } + + foreach ($node->children() as $child) { + if ($child instanceof HeadingPermalink) { + $node->insertBefore($toc); + + return; + } + } + } + } + + private function replacePlaceholders(Document $document, TableOfContents $toc): void + { + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + // Add the block once we find a placeholder + if (! $node instanceof TableOfContentsPlaceholder) { + continue; + } + + $node->replaceWith(clone $toc); + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php new file mode 100644 index 0000000..9c8223b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Renderer\Block\ListBlockRenderer; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class TableOfContentsExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('table_of_contents', Expect::structure([ + 'position' => Expect::anyOf(TableOfContentsBuilder::POSITION_BEFORE_HEADINGS, TableOfContentsBuilder::POSITION_PLACEHOLDER, TableOfContentsBuilder::POSITION_TOP)->default(TableOfContentsBuilder::POSITION_TOP), + 'style' => Expect::anyOf(ListBlock::TYPE_BULLET, ListBlock::TYPE_ORDERED)->default(ListBlock::TYPE_BULLET), + 'normalize' => Expect::anyOf(TableOfContentsGenerator::NORMALIZE_RELATIVE, TableOfContentsGenerator::NORMALIZE_FLAT, TableOfContentsGenerator::NORMALIZE_DISABLED)->default(TableOfContentsGenerator::NORMALIZE_RELATIVE), + 'min_heading_level' => Expect::int()->min(1)->max(6)->default(1), + 'max_heading_level' => Expect::int()->min(1)->max(6)->default(6), + 'html_class' => Expect::string()->default('table-of-contents'), + 'placeholder' => Expect::anyOf(Expect::string(), Expect::null())->default(null), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addRenderer(TableOfContents::class, new TableOfContentsRenderer(new ListBlockRenderer())); + $environment->addEventListener(DocumentParsedEvent::class, [new TableOfContentsBuilder(), 'onDocumentParsed'], -150); + + // phpcs:ignore SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($environment->getConfiguration()->get('table_of_contents/position') === TableOfContentsBuilder::POSITION_PLACEHOLDER) { + $environment->addBlockStartParser(TableOfContentsPlaceholderParser::blockStartParser(), 200); + // If a placeholder cannot be replaced with a TOC element this renderer will ensure the parser won't error out + $environment->addRenderer(TableOfContentsPlaceholder::class, new TableOfContentsPlaceholderRenderer()); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php new file mode 100644 index 0000000..f0df96b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php @@ -0,0 +1,168 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Extension\TableOfContents\Normalizer\AsIsNormalizerStrategy; +use League\CommonMark\Extension\TableOfContents\Normalizer\FlatNormalizerStrategy; +use League\CommonMark\Extension\TableOfContents\Normalizer\NormalizerStrategyInterface; +use League\CommonMark\Extension\TableOfContents\Normalizer\RelativeNormalizerStrategy; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Node\RawMarkupContainerInterface; +use League\CommonMark\Node\StringContainerHelper; +use League\Config\Exception\InvalidConfigurationException; + +final class TableOfContentsGenerator implements TableOfContentsGeneratorInterface +{ + public const STYLE_BULLET = ListBlock::TYPE_BULLET; + public const STYLE_ORDERED = ListBlock::TYPE_ORDERED; + + public const NORMALIZE_DISABLED = 'as-is'; + public const NORMALIZE_RELATIVE = 'relative'; + public const NORMALIZE_FLAT = 'flat'; + + /** @psalm-readonly */ + private string $style; + + /** @psalm-readonly */ + private string $normalizationStrategy; + + /** @psalm-readonly */ + private int $minHeadingLevel; + + /** @psalm-readonly */ + private int $maxHeadingLevel; + + /** @psalm-readonly */ + private string $fragmentPrefix; + + public function __construct(string $style, string $normalizationStrategy, int $minHeadingLevel, int $maxHeadingLevel, string $fragmentPrefix) + { + $this->style = $style; + $this->normalizationStrategy = $normalizationStrategy; + $this->minHeadingLevel = $minHeadingLevel; + $this->maxHeadingLevel = $maxHeadingLevel; + $this->fragmentPrefix = $fragmentPrefix; + + if ($fragmentPrefix !== '') { + $this->fragmentPrefix .= '-'; + } + } + + public function generate(Document $document): ?TableOfContents + { + $toc = $this->createToc($document); + + $normalizer = $this->getNormalizer($toc); + + $firstHeading = null; + + foreach ($this->getHeadingLinks($document) as $headingLink) { + $heading = $headingLink->parent(); + // Make sure this is actually tied to a heading + if (! $heading instanceof Heading) { + continue; + } + + // Skip any headings outside the configured min/max levels + if ($heading->getLevel() < $this->minHeadingLevel || $heading->getLevel() > $this->maxHeadingLevel) { + continue; + } + + // Keep track of the first heading we see - we might need this later + $firstHeading ??= $heading; + + // Keep track of the start and end lines + $toc->setStartLine($firstHeading->getStartLine()); + $toc->setEndLine($heading->getEndLine()); + + // Create the new link + $link = new Link('#' . $this->fragmentPrefix . $headingLink->getSlug(), StringContainerHelper::getChildText($heading, [RawMarkupContainerInterface::class])); + + $listItem = new ListItem($toc->getListData()); + $listItem->setStartLine($heading->getStartLine()); + $listItem->setEndLine($heading->getEndLine()); + $listItem->appendChild($link); + + // Add it to the correct place + $normalizer->addItem($heading->getLevel(), $listItem); + } + + // Don't add the TOC if no headings were present + if (! $toc->hasChildren() || $firstHeading === null) { + return null; + } + + return $toc; + } + + private function createToc(Document $document): TableOfContents + { + $listData = new ListData(); + + if ($this->style === self::STYLE_BULLET) { + $listData->type = ListBlock::TYPE_BULLET; + } elseif ($this->style === self::STYLE_ORDERED) { + $listData->type = ListBlock::TYPE_ORDERED; + } else { + throw new InvalidConfigurationException(\sprintf('Invalid table of contents list style: "%s"', $this->style)); + } + + $toc = new TableOfContents($listData); + + $toc->setStartLine($document->getStartLine()); + $toc->setEndLine($document->getEndLine()); + + return $toc; + } + + /** + * @return iterable<HeadingPermalink> + */ + private function getHeadingLinks(Document $document): iterable + { + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Heading) { + continue; + } + + foreach ($node->children() as $child) { + if ($child instanceof HeadingPermalink) { + yield $child; + } + } + } + } + + private function getNormalizer(TableOfContents $toc): NormalizerStrategyInterface + { + switch ($this->normalizationStrategy) { + case self::NORMALIZE_DISABLED: + return new AsIsNormalizerStrategy($toc); + case self::NORMALIZE_RELATIVE: + return new RelativeNormalizerStrategy($toc); + case self::NORMALIZE_FLAT: + return new FlatNormalizerStrategy($toc); + default: + throw new InvalidConfigurationException(\sprintf('Invalid table of contents normalization strategy: "%s"', $this->normalizationStrategy)); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php new file mode 100644 index 0000000..64ecb8e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Node\Block\Document; + +interface TableOfContentsGeneratorInterface +{ + public function generate(Document $document): ?TableOfContents; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php new file mode 100644 index 0000000..b27ddee --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php @@ -0,0 +1,74 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class TableOfContentsPlaceholderParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private TableOfContentsPlaceholder $block; + + public function __construct() + { + $this->block = new TableOfContentsPlaceholder(); + } + + public function getBlock(): TableOfContentsPlaceholder + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::none(); + } + + public static function blockStartParser(): BlockStartParserInterface + { + return new class () implements BlockStartParserInterface, ConfigurationAwareInterface { + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + $placeholder = $this->config->get('table_of_contents/placeholder'); + if ($placeholder === null) { + return BlockStart::none(); + } + + // The placeholder must be the only thing on the line + if ($cursor->match('/^' . \preg_quote($placeholder, '/') . '$/') === null) { + return BlockStart::none(); + } + + return BlockStart::of(new TableOfContentsPlaceholderParser())->at($cursor); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + }; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php new file mode 100644 index 0000000..0366cb9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php @@ -0,0 +1,40 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableOfContentsPlaceholderRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + return '<!-- table of contents -->'; + } + + public function getXmlTagName(Node $node): string + { + return 'table_of_contents_placeholder'; + } + + /** + * @return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php new file mode 100644 index 0000000..da1b698 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableOfContentsRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** @var NodeRendererInterface&XmlNodeRendererInterface */ + private $innerRenderer; + + /** + * @psalm-param NodeRendererInterface&XmlNodeRendererInterface $innerRenderer + * + * @phpstan-param NodeRendererInterface&XmlNodeRendererInterface $innerRenderer + */ + public function __construct(NodeRendererInterface $innerRenderer) + { + $this->innerRenderer = $innerRenderer; + } + + /** + * {@inheritDoc} + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + return $this->innerRenderer->render($node, $childRenderer); + } + + public function getXmlTagName(Node $node): string + { + return 'table_of_contents'; + } + + /** + * @return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array + { + return $this->innerRenderer->getXmlAttributes($node); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php new file mode 100644 index 0000000..bf4b0d2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ExtensionInterface; + +final class TaskListExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addInlineParser(new TaskListItemMarkerParser(), 35); + $environment->addRenderer(TaskListItemMarker::class, new TaskListItemMarkerRenderer()); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php new file mode 100644 index 0000000..125ae40 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Node\Inline\AbstractInline; + +final class TaskListItemMarker extends AbstractInline +{ + /** @psalm-readonly-allow-private-mutation */ + private bool $checked; + + public function __construct(bool $isCompleted) + { + parent::__construct(); + + $this->checked = $isCompleted; + } + + public function isChecked(): bool + { + return $this->checked; + } + + public function setChecked(bool $checked): void + { + $this->checked = $checked; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php new file mode 100644 index 0000000..30e2731 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class TaskListItemMarkerParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf('[ ]', '[x]'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $container = $inlineContext->getContainer(); + + // Checkbox must come at the beginning of the first paragraph of the list item + if ($container->hasChildren() || ! ($container instanceof Paragraph && $container->parent() && $container->parent() instanceof ListItem)) { + return false; + } + + $cursor = $inlineContext->getCursor(); + $oldState = $cursor->saveState(); + + $cursor->advanceBy(3); + + if ($cursor->getNextNonSpaceCharacter() === null) { + $cursor->restoreState($oldState); + + return false; + } + + $isChecked = $inlineContext->getFullMatch() !== '[ ]'; + + $container->appendChild(new TaskListItemMarker($isChecked)); + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php new file mode 100644 index 0000000..a1eb745 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php @@ -0,0 +1,70 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TaskListItemMarkerRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param TaskListItemMarker $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + TaskListItemMarker::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + $checkbox = new HtmlElement('input', $attrs, '', true); + + if ($node->isChecked()) { + $checkbox->setAttribute('checked', ''); + } + + $checkbox->setAttribute('disabled', ''); + $checkbox->setAttribute('type', 'checkbox'); + + return $checkbox; + } + + public function getXmlTagName(Node $node): string + { + return 'task_list_item_marker'; + } + + /** + * @param TaskListItemMarker $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + TaskListItemMarker::assertInstanceOf($node); + + if ($node->isChecked()) { + return ['checked' => 'checked']; + } + + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php b/php/libraries/composer/vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php new file mode 100644 index 0000000..f2524b2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Environment\Environment; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; +use League\CommonMark\Extension\GithubFlavoredMarkdownExtension; + +/** + * Converts GitHub Flavored Markdown to HTML. + */ +final class GithubFlavoredMarkdownConverter extends MarkdownConverter +{ + /** + * Create a new Markdown converter pre-configured for GFM + * + * @param array<string, mixed> $config + */ + public function __construct(array $config = []) + { + $environment = new Environment($config); + $environment->addExtension(new CommonMarkCoreExtension()); + $environment->addExtension(new GithubFlavoredMarkdownExtension()); + + parent::__construct($environment); + } + + public function getEnvironment(): Environment + { + \assert($this->environment instanceof Environment); + + return $this->environment; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Input/MarkdownInput.php b/php/libraries/composer/vendor/league/commonmark/src/Input/MarkdownInput.php new file mode 100644 index 0000000..bbe1618 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Input/MarkdownInput.php @@ -0,0 +1,102 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Input; + +use League\CommonMark\Exception\UnexpectedEncodingException; + +class MarkdownInput implements MarkdownInputInterface +{ + /** + * @var array<int, string>|null + * + * @psalm-readonly-allow-private-mutation + */ + private ?array $lines = null; + + /** @psalm-readonly-allow-private-mutation */ + private string $content; + + /** @psalm-readonly-allow-private-mutation */ + private ?int $lineCount = null; + + /** @psalm-readonly */ + private int $lineOffset; + + public function __construct(string $content, int $lineOffset = 0) + { + if (! \mb_check_encoding($content, 'UTF-8')) { + throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected'); + } + + // Strip any leading UTF-8 BOM + if (\substr($content, 0, 3) === "\xEF\xBB\xBF") { + $content = \substr($content, 3); + } + + $this->content = $content; + $this->lineOffset = $lineOffset; + } + + public function getContent(): string + { + return $this->content; + } + + /** + * {@inheritDoc} + */ + public function getLines(): iterable + { + $this->splitLinesIfNeeded(); + + \assert($this->lines !== null); + + /** @psalm-suppress PossiblyNullIterator */ + foreach ($this->lines as $i => $line) { + yield $this->lineOffset + $i + 1 => $line; + } + } + + public function getLineCount(): int + { + $this->splitLinesIfNeeded(); + + \assert($this->lineCount !== null); + + return $this->lineCount; + } + + private function splitLinesIfNeeded(): void + { + if ($this->lines !== null) { + return; + } + + $lines = \preg_split('/\r\n|\n|\r/', $this->content); + if ($lines === false) { + throw new UnexpectedEncodingException('Failed to split Markdown content by line'); + } + + $this->lines = $lines; + + // Remove any newline which appears at the very end of the string. + // We've already split the document by newlines, so we can simply drop + // any empty element which appears on the end. + if (\end($this->lines) === '') { + \array_pop($this->lines); + } + + $this->lineCount = \count($this->lines); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Input/MarkdownInputInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Input/MarkdownInputInterface.php new file mode 100644 index 0000000..bb8d6f1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Input/MarkdownInputInterface.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Input; + +interface MarkdownInputInterface +{ + public function getContent(): string; + + /** + * @return iterable<int, string> + */ + public function getLines(): iterable; + + public function getLineCount(): int; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/MarkdownConverter.php b/php/libraries/composer/vendor/league/commonmark/src/MarkdownConverter.php new file mode 100644 index 0000000..037ecff --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/MarkdownConverter.php @@ -0,0 +1,93 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; +use League\CommonMark\Parser\MarkdownParser; +use League\CommonMark\Parser\MarkdownParserInterface; +use League\CommonMark\Renderer\HtmlRenderer; +use League\CommonMark\Renderer\MarkdownRendererInterface; + +class MarkdownConverter implements ConverterInterface, MarkdownConverterInterface +{ + /** @psalm-readonly */ + protected EnvironmentInterface $environment; + + /** @psalm-readonly */ + protected MarkdownParserInterface $markdownParser; + + /** @psalm-readonly */ + protected MarkdownRendererInterface $htmlRenderer; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + + $this->markdownParser = new MarkdownParser($environment); + $this->htmlRenderer = new HtmlRenderer($environment); + } + + public function getEnvironment(): EnvironmentInterface + { + return $this->environment; + } + + /** + * Converts Markdown to HTML. + * + * @param string $input The Markdown to convert + * + * @return RenderedContentInterface Rendered HTML + * + * @throws CommonMarkException + */ + public function convert(string $input): RenderedContentInterface + { + $documentAST = $this->markdownParser->parse($input); + + return $this->htmlRenderer->renderDocument($documentAST); + } + + /** + * Converts Markdown to HTML. + * + * @deprecated since 2.2; use {@link convert()} instead + * + * @param string $markdown The Markdown to convert + * + * @return RenderedContentInterface Rendered HTML + * + * @throws CommonMarkException + */ + public function convertToHtml(string $markdown): RenderedContentInterface + { + \trigger_deprecation('league/commonmark', '2.2.0', 'Calling "convertToHtml()" on a %s class is deprecated, use "convert()" instead.', self::class); + + return $this->convert($markdown); + } + + /** + * Converts CommonMark to HTML. + * + * @see MarkdownConverter::convert() + * + * @throws CommonMarkException + */ + public function __invoke(string $markdown): RenderedContentInterface + { + return $this->convert($markdown); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/MarkdownConverterInterface.php b/php/libraries/composer/vendor/league/commonmark/src/MarkdownConverterInterface.php new file mode 100644 index 0000000..a52a286 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/MarkdownConverterInterface.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; + +/** + * Interface for a service which converts Markdown to HTML. + * + * @deprecated since 2.2; use {@link ConverterInterface} instead + */ +interface MarkdownConverterInterface +{ + /** + * Converts Markdown to HTML. + * + * @deprecated since 2.2; use {@link ConverterInterface::convert()} instead + * + * @throws CommonMarkException + */ + public function convertToHtml(string $markdown): RenderedContentInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Block/AbstractBlock.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/AbstractBlock.php new file mode 100644 index 0000000..417f89b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/AbstractBlock.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Node; + +/** + * Block-level element + * + * @method parent() ?AbstractBlock + */ +abstract class AbstractBlock extends Node +{ + protected ?int $startLine = null; + + protected ?int $endLine = null; + + protected function setParent(?Node $node = null): void + { + if ($node && ! $node instanceof self) { + throw new InvalidArgumentException('Parent of block must also be block (cannot be inline)'); + } + + parent::setParent($node); + } + + public function setStartLine(?int $startLine): void + { + $this->startLine = $startLine; + if ($this->endLine === null) { + $this->endLine = $startLine; + } + } + + public function getStartLine(): ?int + { + return $this->startLine; + } + + public function setEndLine(?int $endLine): void + { + $this->endLine = $endLine; + } + + public function getEndLine(): ?int + { + return $this->endLine; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Block/Document.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/Document.php new file mode 100644 index 0000000..ee7ee44 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/Document.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Reference\ReferenceMap; +use League\CommonMark\Reference\ReferenceMapInterface; + +class Document extends AbstractBlock +{ + /** @psalm-readonly */ + protected ReferenceMapInterface $referenceMap; + + public function __construct(?ReferenceMapInterface $referenceMap = null) + { + parent::__construct(); + + $this->setStartLine(1); + + $this->referenceMap = $referenceMap ?? new ReferenceMap(); + } + + public function getReferenceMap(): ReferenceMapInterface + { + return $this->referenceMap; + } + + public function canContain(AbstractBlock $block): bool + { + return true; + } + + public function isCode(): bool + { + return false; + } + + public function matchesNextLine(Cursor $cursor): bool + { + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Block/Paragraph.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/Paragraph.php new file mode 100644 index 0000000..5b7d17c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/Paragraph.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +class Paragraph extends AbstractBlock +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Block/TightBlockInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/TightBlockInterface.php new file mode 100644 index 0000000..21a5868 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Block/TightBlockInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +interface TightBlockInterface +{ + public function isTight(): bool; + + public function setTight(bool $tight): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AbstractInline.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AbstractInline.php new file mode 100644 index 0000000..d3705b4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AbstractInline.php @@ -0,0 +1,23 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +use League\CommonMark\Node\Node; + +abstract class AbstractInline extends Node +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php new file mode 100644 index 0000000..f0aab84 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +use League\CommonMark\Node\StringContainerInterface; + +abstract class AbstractStringContainer extends AbstractInline implements StringContainerInterface +{ + protected string $literal = ''; + + /** + * @param array<string, mixed> $data + */ + public function __construct(string $contents = '', array $data = []) + { + parent::__construct(); + + $this->literal = $contents; + if (\count($data) > 0) { + $this->data->import($data); + } + } + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php new file mode 100644 index 0000000..43922d4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php @@ -0,0 +1,105 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class AdjacentTextMerger +{ + public static function mergeChildNodes(Node $node): void + { + // No children or just one child node, no need for merging + if ($node->firstChild() === $node->lastChild() || $node->firstChild() === null || $node->lastChild() === null) { + return; + } + + /** @psalm-suppress PossiblyNullArgument */ + self::mergeTextNodesInclusive($node->firstChild(), $node->lastChild()); + } + + public static function mergeTextNodesBetweenExclusive(Node $fromNode, Node $toNode): void + { + // No nodes between them + if ($fromNode === $toNode || $fromNode->next() === $toNode || $fromNode->next() === null || $toNode->previous() === null) { + return; + } + + /** @psalm-suppress PossiblyNullArgument */ + self::mergeTextNodesInclusive($fromNode->next(), $toNode->previous()); + } + + public static function mergeWithDirectlyAdjacentNodes(Text $node): void + { + $start = ($previous = $node->previous()) instanceof Text ? $previous : $node; + $end = ($next = $node->next()) instanceof Text ? $next : $node; + + self::mergeIfNeeded($start, $end); + } + + private static function mergeTextNodesInclusive(Node $fromNode, Node $toNode): void + { + $first = null; + $last = null; + + $node = $fromNode; + while ($node !== null) { + if ($node instanceof Text) { + if ($first === null) { + $first = $node; + } + + $last = $node; + } else { + self::mergeIfNeeded($first, $last); + $first = null; + $last = null; + } + + if ($node === $toNode) { + break; + } + + $node = $node->next(); + } + + self::mergeIfNeeded($first, $last); + } + + private static function mergeIfNeeded(?Text $first, ?Text $last): void + { + if ($first === null || $last === null || $first === $last) { + // No merging needed + return; + } + + $s = $first->getLiteral(); + + $node = $first->next(); + $stop = $last->next(); + while ($node !== $stop && $node instanceof Text) { + $s .= $node->getLiteral(); + $unlink = $node; + $node = $node->next(); + $unlink->detach(); + } + + $first->setLiteral($s); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php new file mode 100644 index 0000000..89773fa --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +interface DelimitedInterface +{ + public function getOpeningDelimiter(): string; + + public function getClosingDelimiter(): string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/Newline.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/Newline.php new file mode 100644 index 0000000..68790de --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/Newline.php @@ -0,0 +1,40 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +final class Newline extends AbstractInline +{ + // Any changes to these constants should be reflected in .phpstorm.meta.php + public const HARDBREAK = 0; + public const SOFTBREAK = 1; + + /** @psalm-readonly */ + private int $type; + + public function __construct(int $breakType = self::HARDBREAK) + { + parent::__construct(); + + $this->type = $breakType; + } + + /** @psalm-immutable */ + public function getType(): int + { + return $this->type; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/Text.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/Text.php new file mode 100644 index 0000000..31387f9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Inline/Text.php @@ -0,0 +1,25 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +final class Text extends AbstractStringContainer +{ + public function append(string $literal): void + { + $this->literal .= $literal; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Node.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Node.php new file mode 100644 index 0000000..484b39c --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Node.php @@ -0,0 +1,262 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use Dflydev\DotAccessData\Data; +use League\CommonMark\Exception\InvalidArgumentException; + +abstract class Node +{ + /** @psalm-readonly */ + public Data $data; + + /** @psalm-readonly-allow-private-mutation */ + protected int $depth = 0; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $parent = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $previous = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $next = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $firstChild = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $lastChild = null; + + public function __construct() + { + $this->data = new Data([ + 'attributes' => [], + ]); + } + + public function previous(): ?Node + { + return $this->previous; + } + + public function next(): ?Node + { + return $this->next; + } + + public function parent(): ?Node + { + return $this->parent; + } + + protected function setParent(?Node $node = null): void + { + $this->parent = $node; + $this->depth = $node === null ? 0 : $node->depth + 1; + } + + /** + * Inserts the $sibling node after $this + */ + public function insertAfter(Node $sibling): void + { + $sibling->detach(); + $sibling->next = $this->next; + + if ($sibling->next) { + $sibling->next->previous = $sibling; + } + + $sibling->previous = $this; + $this->next = $sibling; + $sibling->setParent($this->parent); + + if (! $sibling->next && $sibling->parent) { + $sibling->parent->lastChild = $sibling; + } + } + + /** + * Inserts the $sibling node before $this + */ + public function insertBefore(Node $sibling): void + { + $sibling->detach(); + $sibling->previous = $this->previous; + + if ($sibling->previous) { + $sibling->previous->next = $sibling; + } + + $sibling->next = $this; + $this->previous = $sibling; + $sibling->setParent($this->parent); + + if (! $sibling->previous && $sibling->parent) { + $sibling->parent->firstChild = $sibling; + } + } + + public function replaceWith(Node $replacement): void + { + $replacement->detach(); + $this->insertAfter($replacement); + $this->detach(); + } + + public function detach(): void + { + if ($this->previous) { + $this->previous->next = $this->next; + } elseif ($this->parent) { + $this->parent->firstChild = $this->next; + } + + if ($this->next) { + $this->next->previous = $this->previous; + } elseif ($this->parent) { + $this->parent->lastChild = $this->previous; + } + + $this->parent = null; + $this->next = null; + $this->previous = null; + $this->depth = 0; + } + + public function hasChildren(): bool + { + return $this->firstChild !== null; + } + + public function firstChild(): ?Node + { + return $this->firstChild; + } + + public function lastChild(): ?Node + { + return $this->lastChild; + } + + /** + * @return Node[] + */ + public function children(): iterable + { + $children = []; + for ($current = $this->firstChild; $current !== null; $current = $current->next) { + $children[] = $current; + } + + return $children; + } + + public function appendChild(Node $child): void + { + if ($this->lastChild) { + $this->lastChild->insertAfter($child); + } else { + $child->detach(); + $child->setParent($this); + $this->lastChild = $this->firstChild = $child; + } + } + + /** + * Adds $child as the very first child of $this + */ + public function prependChild(Node $child): void + { + if ($this->firstChild) { + $this->firstChild->insertBefore($child); + } else { + $child->detach(); + $child->setParent($this); + $this->lastChild = $this->firstChild = $child; + } + } + + /** + * Detaches all child nodes of given node + */ + public function detachChildren(): void + { + foreach ($this->children() as $children) { + $children->setParent(null); + } + + $this->firstChild = $this->lastChild = null; + } + + /** + * Replace all children of given node with collection of another + * + * @param iterable<Node> $children + */ + public function replaceChildren(iterable $children): void + { + $this->detachChildren(); + foreach ($children as $item) { + $this->appendChild($item); + } + } + + public function getDepth(): int + { + return $this->depth; + } + + public function walker(): NodeWalker + { + return new NodeWalker($this); + } + + public function iterator(int $flags = 0): NodeIterator + { + return new NodeIterator($this, $flags); + } + + /** + * Clone the current node and its children + * + * WARNING: This is a recursive function and should not be called on deeply-nested node trees! + */ + public function __clone() + { + // Cloned nodes are detached from their parents, siblings, and children + $this->parent = null; + $this->previous = null; + $this->next = null; + // But save a copy of the children since we'll need that in a moment + $children = $this->children(); + $this->detachChildren(); + + // The original children get cloned and re-added + foreach ($children as $child) { + $this->appendChild(clone $child); + } + } + + public static function assertInstanceOf(Node $node): void + { + if (! $node instanceof static) { + throw new InvalidArgumentException(\sprintf('Incompatible node type: expected %s, got %s', static::class, \get_class($node))); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/NodeIterator.php b/php/libraries/composer/vendor/league/commonmark/src/Node/NodeIterator.php new file mode 100644 index 0000000..3d295ef --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/NodeIterator.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * @implements \IteratorAggregate<int, Node> + */ +final class NodeIterator implements \IteratorAggregate +{ + public const FLAG_BLOCKS_ONLY = 1; + + private Node $node; + private bool $blocksOnly; + + public function __construct(Node $node, int $flags = 0) + { + $this->node = $node; + $this->blocksOnly = ($flags & self::FLAG_BLOCKS_ONLY) === self::FLAG_BLOCKS_ONLY; + } + + /** + * @return \Generator<int, Node> + */ + public function getIterator(): \Generator + { + $stack = [$this->node]; + $index = 0; + + while ($stack) { + $node = \array_pop($stack); + + yield $index++ => $node; + + // Push all children onto the stack in reverse order + $child = $node->lastChild(); + while ($child !== null) { + if (! $this->blocksOnly || $child instanceof AbstractBlock) { + $stack[] = $child; + } + + $child = $child->previous(); + } + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/NodeWalker.php b/php/libraries/composer/vendor/league/commonmark/src/Node/NodeWalker.php new file mode 100644 index 0000000..6f922e8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/NodeWalker.php @@ -0,0 +1,80 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class NodeWalker +{ + /** @psalm-readonly */ + private Node $root; + + /** @psalm-readonly-allow-private-mutation */ + private ?Node $current = null; + + /** @psalm-readonly-allow-private-mutation */ + private bool $entering; + + public function __construct(Node $root) + { + $this->root = $root; + $this->current = $this->root; + $this->entering = true; + } + + /** + * Returns an event which contains node and entering flag + * (entering is true when we enter a Node from a parent or sibling, + * and false when we reenter it from child) + */ + public function next(): ?NodeWalkerEvent + { + $current = $this->current; + $entering = $this->entering; + if ($current === null) { + return null; + } + + if ($entering && ($current instanceof AbstractBlock || $current->hasChildren())) { + if ($current->firstChild()) { + $this->current = $current->firstChild(); + $this->entering = true; + } else { + $this->entering = false; + } + } elseif ($current === $this->root) { + $this->current = null; + } elseif ($current->next() === null) { + $this->current = $current->parent(); + $this->entering = false; + } else { + $this->current = $current->next(); + $this->entering = true; + } + + return new NodeWalkerEvent($current, $entering); + } + + /** + * Resets the iterator to resume at the specified node + */ + public function resumeAt(Node $node, bool $entering = true): void + { + $this->current = $node; + $this->entering = $entering; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/NodeWalkerEvent.php b/php/libraries/composer/vendor/league/commonmark/src/Node/NodeWalkerEvent.php new file mode 100644 index 0000000..773ec3a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/NodeWalkerEvent.php @@ -0,0 +1,42 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +final class NodeWalkerEvent +{ + /** @psalm-readonly */ + private Node $node; + + /** @psalm-readonly */ + private bool $isEntering; + + public function __construct(Node $node, bool $isEntering = true) + { + $this->node = $node; + $this->isEntering = $isEntering; + } + + public function getNode(): Node + { + return $this->node; + } + + public function isEntering(): bool + { + return $this->isEntering; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Query.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Query.php new file mode 100644 index 0000000..7e76fe3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Query.php @@ -0,0 +1,139 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use League\CommonMark\Node\Query\AndExpr; +use League\CommonMark\Node\Query\OrExpr; + +final class Query +{ + /** @var callable(Node): bool $condition */ + private $condition; + + public function __construct() + { + $this->condition = new AndExpr(); + } + + public function where(callable ...$conditions): self + { + return $this->andWhere(...$conditions); + } + + public function andWhere(callable ...$conditions): self + { + if ($this->condition instanceof AndExpr) { + foreach ($conditions as $condition) { + $this->condition->add($condition); + } + } else { + $this->condition = new AndExpr($this->condition, ...$conditions); + } + + return $this; + } + + public function orWhere(callable ...$conditions): self + { + if ($this->condition instanceof OrExpr) { + foreach ($conditions as $condition) { + $this->condition->add($condition); + } + } else { + $this->condition = new OrExpr($this->condition, ...$conditions); + } + + return $this; + } + + public function findOne(Node $node): ?Node + { + foreach ($node->iterator() as $n) { + if (\call_user_func($this->condition, $n)) { + return $n; + } + } + + return null; + } + + /** + * @return iterable<Node> + */ + public function findAll(Node $node, ?int $limit = PHP_INT_MAX): iterable + { + $resultCount = 0; + + foreach ($node->iterator() as $n) { + if ($resultCount >= $limit) { + break; + } + + if (! \call_user_func($this->condition, $n)) { + continue; + } + + ++$resultCount; + + yield $n; + } + } + + /** + * @return callable(Node): bool + */ + public static function type(string $class): callable + { + return static fn (Node $node): bool => $node instanceof $class; + } + + /** + * @psalm-param ?callable(Node): bool $condition + * + * @return callable(Node): bool + */ + public static function hasChild(?callable $condition = null): callable + { + return static function (Node $node) use ($condition): bool { + foreach ($node->children() as $child) { + if ($condition === null || $condition($child)) { + return true; + } + } + + return false; + }; + } + + /** + * @psalm-param ?callable(Node): bool $condition + * + * @return callable(Node): bool + */ + public static function hasParent(?callable $condition = null): callable + { + return static function (Node $node) use ($condition): bool { + $parent = $node->parent(); + if ($parent === null) { + return false; + } + + if ($condition === null) { + return true; + } + + return $condition($parent); + }; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Query/AndExpr.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Query/AndExpr.php new file mode 100644 index 0000000..d2cd615 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Query/AndExpr.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Query; + +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class AndExpr implements ExpressionInterface +{ + /** + * @var callable[] + * @psalm-var list<callable(Node): bool> + */ + private array $conditions; + + /** + * @psalm-param callable(Node): bool $expressions + */ + public function __construct(callable ...$expressions) + { + $this->conditions = \array_values($expressions); + } + + /** + * @param callable(Node): bool $expression + */ + public function add(callable $expression): void + { + $this->conditions[] = $expression; + } + + public function __invoke(Node $node): bool + { + foreach ($this->conditions as $condition) { + if (! $condition($node)) { + return false; + } + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Query/ExpressionInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Query/ExpressionInterface.php new file mode 100644 index 0000000..2bbbc7f --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Query/ExpressionInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Query; + +use League\CommonMark\Node\Node; + +interface ExpressionInterface +{ + public function __invoke(Node $node): bool; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/Query/OrExpr.php b/php/libraries/composer/vendor/league/commonmark/src/Node/Query/OrExpr.php new file mode 100644 index 0000000..b0baad8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/Query/OrExpr.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Query; + +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class OrExpr implements ExpressionInterface +{ + /** + * @var callable[] + * @psalm-var list<callable(Node): bool> + */ + private array $conditions; + + /** + * @psalm-param callable(Node): bool $expressions + */ + public function __construct(callable ...$expressions) + { + $this->conditions = \array_values($expressions); + } + + /** + * @param callable(Node): bool $expression + */ + public function add(callable $expression): void + { + $this->conditions[] = $expression; + } + + public function __invoke(Node $node): bool + { + foreach ($this->conditions as $condition) { + if ($condition($node)) { + return true; + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php new file mode 100644 index 0000000..1545285 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +/** + * Interface for a node which contains raw, unprocessed markup (like HTML) + */ +interface RawMarkupContainerInterface extends StringContainerInterface +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/StringContainerHelper.php b/php/libraries/composer/vendor/league/commonmark/src/Node/StringContainerHelper.php new file mode 100644 index 0000000..8e1ec34 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/StringContainerHelper.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +final class StringContainerHelper +{ + /** + * Extract text literals from all descendant nodes + * + * @param Node $node Parent node + * @param array<string> $excludeTypes Optional list of node class types to exclude + * + * @return string Concatenated literals + */ + public static function getChildText(Node $node, array $excludeTypes = []): string + { + $text = ''; + + foreach ($node->iterator() as $child) { + if ($child instanceof StringContainerInterface && ! self::isOneOf($child, $excludeTypes)) { + $text .= $child->getLiteral(); + } + } + + return $text; + } + + /** + * @param string[] $classesOrInterfacesToCheck + * + * @psalm-pure + */ + private static function isOneOf(object $object, array $classesOrInterfacesToCheck): bool + { + foreach ($classesOrInterfacesToCheck as $type) { + if ($object instanceof $type) { + return true; + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Node/StringContainerInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Node/StringContainerInterface.php new file mode 100644 index 0000000..23564ae --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Node/StringContainerInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +/** + * Interface for a node which directly contains line(s) of text + */ +interface StringContainerInterface +{ + public function setLiteral(string $literal): void; + + public function getLiteral(): string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Normalizer/SlugNormalizer.php b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/SlugNormalizer.php new file mode 100644 index 0000000..d41ea24 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/SlugNormalizer.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +/** + * Creates URL-friendly strings based on the given string input + */ +final class SlugNormalizer implements TextNormalizerInterface, ConfigurationAwareInterface +{ + /** @psalm-allow-private-mutation */ + private int $defaultMaxLength = 255; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->defaultMaxLength = $configuration->get('slug_normalizer/max_length'); + } + + /** + * {@inheritDoc} + * + * @psalm-immutable + */ + public function normalize(string $text, array $context = []): string + { + // Add any requested prefix + $slug = ($context['prefix'] ?? '') . $text; + // Trim whitespace + $slug = \trim($slug); + // Convert to lowercase + $slug = \mb_strtolower($slug, 'UTF-8'); + // Try replacing whitespace with a dash + $slug = \preg_replace('/\s+/u', '-', $slug) ?? $slug; + // Try removing characters other than letters, numbers, and marks. + $slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug) ?? $slug; + // Trim to requested length if given + if ($length = $context['length'] ?? $this->defaultMaxLength) { + $slug = \mb_substr($slug, 0, $length, 'UTF-8'); + } + + return $slug; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Normalizer/TextNormalizer.php b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/TextNormalizer.php new file mode 100644 index 0000000..7860f1b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/TextNormalizer.php @@ -0,0 +1,39 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Normalizer; + +/*** + * Normalize text input using the steps given by the CommonMark spec to normalize labels + * + * @see https://spec.commonmark.org/0.29/#matches + * + * @psalm-immutable + */ +final class TextNormalizer implements TextNormalizerInterface +{ + /** + * {@inheritDoc} + * + * @psalm-pure + */ + public function normalize(string $text, array $context = []): string + { + // Collapse internal whitespace to single space and remove + // leading/trailing whitespace + $text = \preg_replace('/[ \t\r\n]+/', ' ', \trim($text)); + \assert(\is_string($text)); + + return \mb_convert_case($text, \MB_CASE_FOLD, 'UTF-8'); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php new file mode 100644 index 0000000..f476234 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +/** + * Creates a normalized version of the given input text + */ +interface TextNormalizerInterface +{ + /** + * @param string $text The text to normalize + * @param array<string, mixed> $context Additional context about the text being normalized (optional) + * + * $context may include (but is not required to include) the following: + * - `prefix` - A string prefix to prepend to each normalized result + * - `length` - The requested maximum length + * - `node` - The node we're normalizing text for + * + * Implementations do not have to use or respect any information within that $context + */ + public function normalize(string $text, array $context = []): string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php new file mode 100644 index 0000000..591f19f --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +// phpcs:disable Squiz.Strings.DoubleQuoteUsage.ContainsVar +final class UniqueSlugNormalizer implements UniqueSlugNormalizerInterface +{ + private TextNormalizerInterface $innerNormalizer; + /** @var array<string, bool> */ + private array $alreadyUsed = []; + + public function __construct(TextNormalizerInterface $innerNormalizer) + { + $this->innerNormalizer = $innerNormalizer; + } + + public function clearHistory(): void + { + $this->alreadyUsed = []; + } + + /** + * {@inheritDoc} + * + * @psalm-allow-private-mutation + */ + public function normalize(string $text, array $context = []): string + { + $normalized = $this->innerNormalizer->normalize($text, $context); + + // If it's not unique, add an incremental number to the end until we get a unique version + if (\array_key_exists($normalized, $this->alreadyUsed)) { + $suffix = 0; + do { + ++$suffix; + } while (\array_key_exists("$normalized-$suffix", $this->alreadyUsed)); + + $normalized = "$normalized-$suffix"; + } + + $this->alreadyUsed[$normalized] = true; + + return $normalized; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php new file mode 100644 index 0000000..642edeb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php @@ -0,0 +1,28 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +interface UniqueSlugNormalizerInterface extends TextNormalizerInterface +{ + public const DISABLED = false; + public const PER_ENVIRONMENT = 'environment'; + public const PER_DOCUMENT = 'document'; + + /** + * Called by the Environment whenever the configured scope changes + * + * Currently, this will only be called PER_DOCUMENT. + */ + public function clearHistory(): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Output/RenderedContent.php b/php/libraries/composer/vendor/league/commonmark/src/Output/RenderedContent.php new file mode 100644 index 0000000..4bf612d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Output/RenderedContent.php @@ -0,0 +1,49 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Output; + +use League\CommonMark\Node\Block\Document; + +class RenderedContent implements RenderedContentInterface, \Stringable +{ + /** @psalm-readonly */ + private Document $document; + + /** @psalm-readonly */ + private string $content; + + public function __construct(Document $document, string $content) + { + $this->document = $document; + $this->content = $content; + } + + public function getDocument(): Document + { + return $this->document; + } + + public function getContent(): string + { + return $this->content; + } + + /** + * @psalm-mutation-free + */ + public function __toString(): string + { + return $this->content; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Output/RenderedContentInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Output/RenderedContentInterface.php new file mode 100644 index 0000000..2179b1b --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Output/RenderedContentInterface.php @@ -0,0 +1,29 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Output; + +use League\CommonMark\Node\Block\Document; + +interface RenderedContentInterface extends \Stringable +{ + /** + * @psalm-mutation-free + */ + public function getDocument(): Document; + + /** + * @psalm-mutation-free + */ + public function getContent(): string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php new file mode 100644 index 0000000..889532e --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * Base class for a block parser + * + * Slightly more convenient to extend from vs. implementing the interface + */ +abstract class AbstractBlockContinueParser implements BlockContinueParserInterface +{ + public function isContainer(): bool + { + return false; + } + + public function canHaveLazyContinuationLines(): bool + { + return false; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return false; + } + + public function addLine(string $line): void + { + } + + public function closeBlock(): void + { + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinue.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinue.php new file mode 100644 index 0000000..4b5f37d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinue.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\CursorState; + +/** + * Result object for continuing parsing of a block; see static methods for constructors. + * + * @psalm-immutable + */ +final class BlockContinue +{ + /** @psalm-readonly */ + private ?CursorState $cursorState = null; + + /** @psalm-readonly */ + private bool $finalize; + + private function __construct(?CursorState $cursorState = null, bool $finalize = false) + { + $this->cursorState = $cursorState; + $this->finalize = $finalize; + } + + public function getCursorState(): ?CursorState + { + return $this->cursorState; + } + + public function isFinalize(): bool + { + return $this->finalize; + } + + /** + * Signal that we cannot continue here + * + * @return null + */ + public static function none(): ?self + { + return null; + } + + /** + * Signal that we're continuing at the given position + */ + public static function at(Cursor $cursor): self + { + return new self($cursor->saveState(), false); + } + + /** + * Signal that we want to finalize and close the block + */ + public static function finished(): self + { + return new self(null, true); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php new file mode 100644 index 0000000..b6e5472 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Cursor; + +/** + * Interface for a block continuation parser + * + * A block continue parser can only handle a single block instance. The current block being parsed is stored within this parser and + * can be returned once parsing has completed. If you need to parse multiple block continuations, instantiate a new parser for each one. + */ +interface BlockContinueParserInterface +{ + /** + * Return the current block being parsed by this parser + */ + public function getBlock(): AbstractBlock; + + /** + * Return whether we are parsing a container block + */ + public function isContainer(): bool; + + /** + * Return whether we are interested in possibly lazily parsing any subsequent lines + */ + public function canHaveLazyContinuationLines(): bool; + + /** + * Determine whether the current block being parsed can contain the given child block + */ + public function canContain(AbstractBlock $childBlock): bool; + + /** + * Attempt to parse the given line + */ + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue; + + /** + * Add the given line of text to the current block + */ + public function addLine(string $line): void; + + /** + * Close and finalize the current block + */ + public function closeBlock(): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php new file mode 100644 index 0000000..6f826c9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php @@ -0,0 +1,24 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\InlineParserEngineInterface; + +interface BlockContinueParserWithInlinesInterface extends BlockContinueParserInterface +{ + /** + * Parse any inlines inside of the current block + */ + public function parseInlines(InlineParserEngineInterface $inlineParser): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockStart.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockStart.php new file mode 100644 index 0000000..5576622 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockStart.php @@ -0,0 +1,124 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\CursorState; + +/** + * Result object for starting parsing of a block; see static methods for constructors + */ +final class BlockStart +{ + /** + * @var BlockContinueParserInterface[] + * + * @psalm-readonly + */ + private array $blockParsers; + + /** @psalm-readonly-allow-private-mutation */ + private ?CursorState $cursorState = null; + + /** @psalm-readonly-allow-private-mutation */ + private bool $replaceActiveBlockParser = false; + + private bool $isAborting = false; + + private function __construct(BlockContinueParserInterface ...$blockParsers) + { + $this->blockParsers = $blockParsers; + } + + /** + * @return BlockContinueParserInterface[] + */ + public function getBlockParsers(): iterable + { + return $this->blockParsers; + } + + public function getCursorState(): ?CursorState + { + return $this->cursorState; + } + + public function isReplaceActiveBlockParser(): bool + { + return $this->replaceActiveBlockParser; + } + + /** + * @internal + */ + public function isAborting(): bool + { + return $this->isAborting; + } + + /** + * Signal that we want to parse at the given cursor position + * + * @return $this + */ + public function at(Cursor $cursor): self + { + $this->cursorState = $cursor->saveState(); + + return $this; + } + + /** + * Signal that we want to replace the active block parser with this one + * + * @return $this + */ + public function replaceActiveBlockParser(): self + { + $this->replaceActiveBlockParser = true; + + return $this; + } + + /** + * Signal that we cannot parse whatever is here + * + * @return null + */ + public static function none(): ?self + { + return null; + } + + /** + * Signal that we'd like to register the given parser(s) so they can parse the current block + */ + public static function of(BlockContinueParserInterface ...$blockParsers): self + { + return new self(...$blockParsers); + } + + /** + * Signal that the block parsing process should be aborted (no other block starts should be checked) + * + * @internal + */ + public static function abort(): self + { + $ret = new self(); + $ret->isAborting = true; + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php new file mode 100644 index 0000000..90ed781 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +/** + * Interface for a block parser which identifies block starts. + */ +interface BlockStartParserInterface +{ + /** + * Check whether we should handle the block at the current position + * + * @param Cursor $cursor A cloned copy of the cursor at the current parsing location + * @param MarkdownParserStateInterface $parserState Additional information about the state of the Markdown parser + * + * @return BlockStart|null The BlockStart that has been identified, or null if the block doesn't match here + */ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php new file mode 100644 index 0000000..bacb512 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Reference\ReferenceMapInterface; + +/** + * Parser implementation which ensures everything is added to the root-level Document + */ +final class DocumentBlockParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private Document $document; + + public function __construct(ReferenceMapInterface $referenceMap) + { + $this->document = new Document($referenceMap); + } + + public function getBlock(): Document + { + return $this->document; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::at($cursor); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/ParagraphParser.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/ParagraphParser.php new file mode 100644 index 0000000..1573429 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/ParagraphParser.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceParser; + +final class ParagraphParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + /** @psalm-readonly */ + private Paragraph $block; + + /** @psalm-readonly */ + private ReferenceParser $referenceParser; + + public function __construct() + { + $this->block = new Paragraph(); + $this->referenceParser = new ReferenceParser(); + } + + public function canHaveLazyContinuationLines(): bool + { + return true; + } + + public function getBlock(): Paragraph + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + return BlockContinue::none(); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + $this->referenceParser->parse($line); + } + + public function closeBlock(): void + { + if ($this->referenceParser->hasReferences() && $this->referenceParser->getParagraphContent() === '') { + $this->block->detach(); + } + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + $content = $this->getContentString(); + if ($content !== '') { + $inlineParser->parse($content, $this->block); + } + } + + public function getContentString(): string + { + return $this->referenceParser->getParagraphContent(); + } + + /** + * @return ReferenceInterface[] + */ + public function getReferences(): iterable + { + return $this->referenceParser->getReferences(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php new file mode 100644 index 0000000..95d8bd2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +/** + * @internal + * + * This "parser" is actually a performance optimization. + * + * Most lines in a typical Markdown document probably won't match a block start. This is especially true for lines starting + * with letters - nothing in the core CommonMark spec or our supported extensions will match those lines as blocks. Therefore, + * if we can identify those lines and skip block start parsing, we can optimize performance by ~10%. + * + * Previously this optimization was hard-coded in the MarkdownParser but did not allow users to override this behavior. + * By implementing this optimization as a block parser instead, users wanting custom blocks starting with letters + * can instead register their block parser with a higher priority to ensure their parser is always called first. + */ +final class SkipLinesStartingWithLettersParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if (! $cursor->isIndented() && RegexHelper::isLetter($cursor->getNextNonSpaceCharacter())) { + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockStart::abort(); + } + + return BlockStart::none(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Cursor.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Cursor.php new file mode 100644 index 0000000..d6d76b3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Cursor.php @@ -0,0 +1,493 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Exception\UnexpectedEncodingException; + +class Cursor +{ + public const INDENT_LEVEL = 4; + + /** @psalm-readonly */ + private string $line; + + /** @psalm-readonly */ + private int $length; + + /** + * @var int + * + * It's possible for this to be 1 char past the end, meaning we've parsed all chars and have + * reached the end. In this state, any character-returning method MUST return null. + */ + private int $currentPosition = 0; + + private int $column = 0; + + private int $indent = 0; + + private int $previousPosition = 0; + + private ?int $nextNonSpaceCache = null; + + private bool $partiallyConsumedTab = false; + + /** + * @var int|false + * + * @psalm-readonly + */ + private $lastTabPosition; + + /** @psalm-readonly */ + private bool $isMultibyte; + + /** @var array<int, string> */ + private array $charCache = []; + + /** + * @param string $line The line being parsed (ASCII or UTF-8) + */ + public function __construct(string $line) + { + if (! \mb_check_encoding($line, 'UTF-8')) { + throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected'); + } + + $this->line = $line; + $this->length = \mb_strlen($line, 'UTF-8') ?: 0; + $this->isMultibyte = $this->length !== \strlen($line); + $this->lastTabPosition = $this->isMultibyte ? \mb_strrpos($line, "\t", 0, 'UTF-8') : \strrpos($line, "\t"); + } + + /** + * Returns the position of the next character which is not a space (or tab) + */ + public function getNextNonSpacePosition(): int + { + if ($this->nextNonSpaceCache !== null) { + return $this->nextNonSpaceCache; + } + + if ($this->currentPosition >= $this->length) { + return $this->length; + } + + $cols = $this->column; + + for ($i = $this->currentPosition; $i < $this->length; $i++) { + // This if-else was copied out of getCharacter() for performance reasons + if ($this->isMultibyte) { + $c = $this->charCache[$i] ??= \mb_substr($this->line, $i, 1, 'UTF-8'); + } else { + $c = $this->line[$i]; + } + + if ($c === ' ') { + $cols++; + } elseif ($c === "\t") { + $cols += 4 - ($cols % 4); + } else { + break; + } + } + + $this->indent = $cols - $this->column; + + return $this->nextNonSpaceCache = $i; + } + + /** + * Returns the next character which isn't a space (or tab) + */ + public function getNextNonSpaceCharacter(): ?string + { + $index = $this->getNextNonSpacePosition(); + if ($index >= $this->length) { + return null; + } + + if ($this->isMultibyte) { + return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8'); + } + + return $this->line[$index]; + } + + /** + * Calculates the current indent (number of spaces after current position) + */ + public function getIndent(): int + { + if ($this->nextNonSpaceCache === null) { + $this->getNextNonSpacePosition(); + } + + return $this->indent; + } + + /** + * Whether the cursor is indented to INDENT_LEVEL + */ + public function isIndented(): bool + { + if ($this->nextNonSpaceCache === null) { + $this->getNextNonSpacePosition(); + } + + return $this->indent >= self::INDENT_LEVEL; + } + + public function getCharacter(?int $index = null): ?string + { + if ($index === null) { + $index = $this->currentPosition; + } + + // Index out-of-bounds, or we're at the end + if ($index < 0 || $index >= $this->length) { + return null; + } + + if ($this->isMultibyte) { + return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8'); + } + + return $this->line[$index]; + } + + /** + * Slightly-optimized version of getCurrent(null) + */ + public function getCurrentCharacter(): ?string + { + if ($this->currentPosition >= $this->length) { + return null; + } + + if ($this->isMultibyte) { + return $this->charCache[$this->currentPosition] ??= \mb_substr($this->line, $this->currentPosition, 1, 'UTF-8'); + } + + return $this->line[$this->currentPosition]; + } + + /** + * Returns the next character (or null, if none) without advancing forwards + */ + public function peek(int $offset = 1): ?string + { + return $this->getCharacter($this->currentPosition + $offset); + } + + /** + * Whether the remainder is blank + */ + public function isBlank(): bool + { + return $this->nextNonSpaceCache === $this->length || $this->getNextNonSpacePosition() === $this->length; + } + + /** + * Move the cursor forwards + */ + public function advance(): void + { + $this->advanceBy(1); + } + + /** + * Move the cursor forwards + * + * @param int $characters Number of characters to advance by + * @param bool $advanceByColumns Whether to advance by columns instead of spaces + */ + public function advanceBy(int $characters, bool $advanceByColumns = false): void + { + $this->previousPosition = $this->currentPosition; + $this->nextNonSpaceCache = null; + + if ($this->currentPosition >= $this->length || $characters === 0) { + return; + } + + // Optimization to avoid tab handling logic if we have no tabs + if ($this->lastTabPosition === false || $this->currentPosition > $this->lastTabPosition) { + $length = \min($characters, $this->length - $this->currentPosition); + $this->partiallyConsumedTab = false; + $this->currentPosition += $length; + $this->column += $length; + + return; + } + + $nextFewChars = $this->isMultibyte ? + \mb_substr($this->line, $this->currentPosition, $characters, 'UTF-8') : + \substr($this->line, $this->currentPosition, $characters); + + if ($characters === 1) { + $asArray = [$nextFewChars]; + } elseif ($this->isMultibyte) { + /** @var string[] $asArray */ + $asArray = \mb_str_split($nextFewChars, 1, 'UTF-8'); + } else { + $asArray = \str_split($nextFewChars); + } + + foreach ($asArray as $c) { + if ($c === "\t") { + $charsToTab = 4 - ($this->column % 4); + if ($advanceByColumns) { + $this->partiallyConsumedTab = $charsToTab > $characters; + $charsToAdvance = $charsToTab > $characters ? $characters : $charsToTab; + $this->column += $charsToAdvance; + $this->currentPosition += $this->partiallyConsumedTab ? 0 : 1; + $characters -= $charsToAdvance; + } else { + $this->partiallyConsumedTab = false; + $this->column += $charsToTab; + $this->currentPosition++; + $characters--; + } + } else { + $this->partiallyConsumedTab = false; + $this->currentPosition++; + $this->column++; + $characters--; + } + + if ($characters <= 0) { + break; + } + } + } + + /** + * Advances the cursor by a single space or tab, if present + */ + public function advanceBySpaceOrTab(): bool + { + $character = $this->getCurrentCharacter(); + + if ($character === ' ' || $character === "\t") { + $this->advanceBy(1, true); + + return true; + } + + return false; + } + + /** + * Parse zero or more space/tab characters + * + * @return int Number of positions moved + */ + public function advanceToNextNonSpaceOrTab(): int + { + $newPosition = $this->nextNonSpaceCache ?? $this->getNextNonSpacePosition(); + if ($newPosition === $this->currentPosition) { + return 0; + } + + $this->advanceBy($newPosition - $this->currentPosition); + $this->partiallyConsumedTab = false; + + // We've just advanced to where that non-space is, + // so any subsequent calls to find the next one will + // always return the current position. + $this->nextNonSpaceCache = $this->currentPosition; + $this->indent = 0; + + return $this->currentPosition - $this->previousPosition; + } + + /** + * Parse zero or more space characters, including at most one newline. + * + * Tab characters are not parsed with this function. + * + * @return int Number of positions moved + */ + public function advanceToNextNonSpaceOrNewline(): int + { + $remainder = $this->getRemainder(); + + // Optimization: Avoid the regex if we know there are no spaces or newlines + if ($remainder === '' || ($remainder[0] !== ' ' && $remainder[0] !== "\n")) { + $this->previousPosition = $this->currentPosition; + + return 0; + } + + $matches = []; + \preg_match('/^ *(?:\n *)?/', $remainder, $matches, \PREG_OFFSET_CAPTURE); + + // [0][0] contains the matched text + // [0][1] contains the index of that match + $increment = $matches[0][1] + \strlen($matches[0][0]); + + $this->advanceBy($increment); + + return $this->currentPosition - $this->previousPosition; + } + + /** + * Move the position to the very end of the line + * + * @return int The number of characters moved + */ + public function advanceToEnd(): int + { + $this->previousPosition = $this->currentPosition; + $this->nextNonSpaceCache = null; + + $this->currentPosition = $this->length; + + return $this->currentPosition - $this->previousPosition; + } + + public function getRemainder(): string + { + if ($this->currentPosition >= $this->length) { + return ''; + } + + $prefix = ''; + $position = $this->currentPosition; + if ($this->partiallyConsumedTab) { + $position++; + $charsToTab = 4 - ($this->column % 4); + $prefix = \str_repeat(' ', $charsToTab); + } + + $subString = $this->isMultibyte ? + \mb_substr($this->line, $position, null, 'UTF-8') : + \substr($this->line, $position); + + return $prefix . $subString; + } + + public function getLine(): string + { + return $this->line; + } + + public function isAtEnd(): bool + { + return $this->currentPosition >= $this->length; + } + + /** + * Try to match a regular expression + * + * Returns the matching text and advances to the end of that match + * + * @psalm-param non-empty-string $regex + */ + public function match(string $regex): ?string + { + $subject = $this->getRemainder(); + + if (! \preg_match($regex, $subject, $matches, \PREG_OFFSET_CAPTURE)) { + return null; + } + + // $matches[0][0] contains the matched text + // $matches[0][1] contains the index of that match + + if ($this->isMultibyte) { + // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying + $offset = \mb_strlen(\substr($subject, 0, $matches[0][1]), 'UTF-8'); + $matchLength = \mb_strlen($matches[0][0], 'UTF-8'); + } else { + $offset = $matches[0][1]; + $matchLength = \strlen($matches[0][0]); + } + + // [0][0] contains the matched text + // [0][1] contains the index of that match + $this->advanceBy($offset + $matchLength); + + return $matches[0][0]; + } + + /** + * Encapsulates the current state of this cursor in case you need to rollback later. + * + * WARNING: Do not parse or use the return value for ANYTHING except for + * passing it back into restoreState(), as the number of values and their + * contents may change in any future release without warning. + */ + public function saveState(): CursorState + { + return new CursorState([ + $this->currentPosition, + $this->previousPosition, + $this->nextNonSpaceCache, + $this->indent, + $this->column, + $this->partiallyConsumedTab, + ]); + } + + /** + * Restore the cursor to a previous state. + * + * Pass in the value previously obtained by calling saveState(). + */ + public function restoreState(CursorState $state): void + { + [ + $this->currentPosition, + $this->previousPosition, + $this->nextNonSpaceCache, + $this->indent, + $this->column, + $this->partiallyConsumedTab, + ] = $state->toArray(); + } + + public function getPosition(): int + { + return $this->currentPosition; + } + + public function getPreviousText(): string + { + if ($this->isMultibyte) { + return \mb_substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition, 'UTF-8'); + } + + return \substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition); + } + + public function getSubstring(int $start, ?int $length = null): string + { + if ($this->isMultibyte) { + return \mb_substr($this->line, $start, $length, 'UTF-8'); + } + + if ($length !== null) { + return \substr($this->line, $start, $length); + } + + return \substr($this->line, $start); + } + + public function getColumn(): int + { + return $this->column; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/CursorState.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/CursorState.php new file mode 100644 index 0000000..4a6c2d9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/CursorState.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +/** + * Encapsulates the current state of a cursor in case you need to rollback later. + * + * WARNING: Do not attempt to use this class for ANYTHING except for + * type hinting and passing this object back into restoreState(). + * The constructor, methods, and inner contents may change in any + * future release without warning! + * + * @internal + * + * @psalm-immutable + */ +final class CursorState +{ + /** + * @var array<int, mixed> + * + * @psalm-readonly + */ + private array $state; + + /** + * @internal + * + * @param array<int, mixed> $state + */ + public function __construct(array $state) + { + $this->state = $state; + } + + /** + * @internal + * + * @return array<int, mixed> + */ + public function toArray(): array + { + return $this->state; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php new file mode 100644 index 0000000..fd13435 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php @@ -0,0 +1,23 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Inline; + +use League\CommonMark\Parser\InlineParserContext; + +interface InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch; + + public function parse(InlineParserContext $inlineContext): bool; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php new file mode 100644 index 0000000..e433ed2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Inline; + +use League\CommonMark\Exception\InvalidArgumentException; + +final class InlineParserMatch +{ + private string $regex; + + private bool $caseSensitive; + + private function __construct(string $regex, bool $caseSensitive = false) + { + $this->regex = $regex; + $this->caseSensitive = $caseSensitive; + } + + public function caseSensitive(): self + { + $this->caseSensitive = true; + + return $this; + } + + /** + * @internal + * + * @psalm-return non-empty-string + */ + public function getRegex(): string + { + return '/' . $this->regex . '/' . ($this->caseSensitive ? '' : 'i'); + } + + /** + * Match the given string (case-insensitive) + */ + public static function string(string $str): self + { + return new self(\preg_quote($str, '/')); + } + + /** + * Match any of the given strings (case-insensitive) + */ + public static function oneOf(string ...$str): self + { + return new self(\implode('|', \array_map(static fn (string $str): string => \preg_quote($str, '/'), $str))); + } + + /** + * Match a partial regular expression without starting/ending delimiters, anchors, or flags + */ + public static function regex(string $regex): self + { + return new self($regex); + } + + public static function join(self ...$definitions): self + { + $regex = ''; + $caseSensitive = null; + foreach ($definitions as $definition) { + $regex .= '(' . $definition->regex . ')'; + + if ($caseSensitive === null) { + $caseSensitive = $definition->caseSensitive; + } elseif ($caseSensitive !== $definition->caseSensitive) { + throw new InvalidArgumentException('Case-sensitive and case-insensitive definitions cannot be combined'); + } + } + + return new self($regex, $caseSensitive ?? false); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/NewlineParser.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/NewlineParser.php new file mode 100644 index 0000000..eb10d91 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/Inline/NewlineParser.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\InlineParserContext; + +final class NewlineParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('\\n'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy(1); + + // Check previous inline for trailing spaces + $spaces = 0; + $lastInline = $inlineContext->getContainer()->lastChild(); + if ($lastInline instanceof Text) { + $trimmed = \rtrim($lastInline->getLiteral(), ' '); + $spaces = \strlen($lastInline->getLiteral()) - \strlen($trimmed); + if ($spaces) { + $lastInline->setLiteral($trimmed); + } + } + + if ($spaces >= 2) { + $inlineContext->getContainer()->appendChild(new Newline(Newline::HARDBREAK)); + } else { + $inlineContext->getContainer()->appendChild(new Newline(Newline::SOFTBREAK)); + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserContext.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserContext.php new file mode 100644 index 0000000..796f2f3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserContext.php @@ -0,0 +1,120 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Delimiter\DelimiterStack; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Reference\ReferenceMapInterface; + +final class InlineParserContext +{ + /** @psalm-readonly */ + private AbstractBlock $container; + + /** @psalm-readonly */ + private ReferenceMapInterface $referenceMap; + + /** @psalm-readonly */ + private Cursor $cursor; + + /** @psalm-readonly */ + private DelimiterStack $delimiterStack; + + /** + * @var string[] + * @psalm-var non-empty-array<string> + * + * @psalm-readonly-allow-private-mutation + */ + private array $matches; + + public function __construct(Cursor $contents, AbstractBlock $container, ReferenceMapInterface $referenceMap) + { + $this->referenceMap = $referenceMap; + $this->container = $container; + $this->cursor = $contents; + $this->delimiterStack = new DelimiterStack(); + } + + public function getContainer(): AbstractBlock + { + return $this->container; + } + + public function getReferenceMap(): ReferenceMapInterface + { + return $this->referenceMap; + } + + public function getCursor(): Cursor + { + return $this->cursor; + } + + public function getDelimiterStack(): DelimiterStack + { + return $this->delimiterStack; + } + + /** + * @return string The full text that matched the InlineParserMatch definition + */ + public function getFullMatch(): string + { + return $this->matches[0]; + } + + /** + * @return int The length of the full match (in characters, not bytes) + */ + public function getFullMatchLength(): int + { + return \mb_strlen($this->matches[0], 'UTF-8'); + } + + /** + * @return string[] Similar to preg_match(), index 0 will contain the full match, and any other array elements will be captured sub-matches + * + * @psalm-return non-empty-array<string> + */ + public function getMatches(): array + { + return $this->matches; + } + + /** + * @return string[] + */ + public function getSubMatches(): array + { + return \array_slice($this->matches, 1); + } + + /** + * @param string[] $matches + * + * @psalm-param non-empty-array<string> $matches + */ + public function withMatches(array $matches): InlineParserContext + { + $ctx = clone $this; + + $ctx->matches = $matches; + + return $ctx; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserEngine.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserEngine.php new file mode 100644 index 0000000..b91a63f --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserEngine.php @@ -0,0 +1,177 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Reference\ReferenceMapInterface; + +/** + * @internal + */ +final class InlineParserEngine implements InlineParserEngineInterface +{ + /** @psalm-readonly */ + private EnvironmentInterface $environment; + + /** @psalm-readonly */ + private ReferenceMapInterface $referenceMap; + + /** + * @var array<int, InlineParserInterface|string|bool> + * @psalm-var list<array{0: InlineParserInterface, 1: non-empty-string, 2: bool}> + * @phpstan-var array<int, array{0: InlineParserInterface, 1: non-empty-string, 2: bool}> + */ + private array $parsers = []; + + public function __construct(EnvironmentInterface $environment, ReferenceMapInterface $referenceMap) + { + $this->environment = $environment; + $this->referenceMap = $referenceMap; + + foreach ($environment->getInlineParsers() as $parser) { + \assert($parser instanceof InlineParserInterface); + $regex = $parser->getMatchDefinition()->getRegex(); + + $this->parsers[] = [$parser, $regex, \strlen($regex) !== \mb_strlen($regex, 'UTF-8')]; + } + } + + public function parse(string $contents, AbstractBlock $block): void + { + $contents = \trim($contents); + $cursor = new Cursor($contents); + + $inlineParserContext = new InlineParserContext($cursor, $block, $this->referenceMap); + + // Have all parsers look at the line to determine what they might want to parse and what positions they exist at + foreach ($this->matchParsers($contents) as $matchPosition => $parsers) { + $currentPosition = $cursor->getPosition(); + // We've already gone past this point + if ($currentPosition > $matchPosition) { + continue; + } + + // We've skipped over some uninteresting text that should be added as a plain text node + if ($currentPosition < $matchPosition) { + $cursor->advanceBy($matchPosition - $currentPosition); + $this->addPlainText($cursor->getPreviousText(), $block); + } + + // We're now at a potential start - see which of the current parsers can handle it + $parsed = false; + foreach ($parsers as [$parser, $matches]) { + \assert($parser instanceof InlineParserInterface); + if ($parser->parse($inlineParserContext->withMatches($matches))) { + // A parser has successfully handled the text at the given position; don't consider any others at this position + $parsed = true; + break; + } + } + + if ($parsed) { + continue; + } + + // Despite potentially being interested, nothing actually parsed text here, so add the current character and continue onwards + $this->addPlainText((string) $cursor->getCurrentCharacter(), $block); + $cursor->advance(); + } + + // Add any remaining text that wasn't parsed + if (! $cursor->isAtEnd()) { + $this->addPlainText($cursor->getRemainder(), $block); + } + + // Process any delimiters that were found + $delimiterStack = $inlineParserContext->getDelimiterStack(); + $delimiterStack->processDelimiters(null, $this->environment->getDelimiterProcessors()); + $delimiterStack->removeAll(); + + // Combine adjacent text notes into one + AdjacentTextMerger::mergeChildNodes($block); + } + + private function addPlainText(string $text, AbstractBlock $container): void + { + $lastInline = $container->lastChild(); + if ($lastInline instanceof Text && ! $lastInline->data->has('delim')) { + $lastInline->append($text); + } else { + $container->appendChild(new Text($text)); + } + } + + /** + * Given the current line, ask all the parsers which parts of the text they would be interested in parsing. + * + * The resulting array provides a list of character positions, which parsers are interested in trying to parse + * the text at those points, and (for convenience/optimization) what the matching text happened to be. + * + * @return array<array<int, InlineParserInterface|string>> + * + * @psalm-return array<int, list<array{0: InlineParserInterface, 1: non-empty-array<string>}>> + * + * @phpstan-return array<int, array<int, array{0: InlineParserInterface, 1: non-empty-array<string>}>> + */ + private function matchParsers(string $contents): array + { + $contents = \trim($contents); + $isMultibyte = ! \mb_check_encoding($contents, 'ASCII'); + + $ret = []; + + foreach ($this->parsers as [$parser, $regex, $isRegexMultibyte]) { + if ($isMultibyte || $isRegexMultibyte) { + $regex .= 'u'; + } + + // See if the parser's InlineParserMatch regex matched against any part of the string + if (! \preg_match_all($regex, $contents, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER)) { + continue; + } + + // For each part that matched... + foreach ($matches as $match) { + if ($isMultibyte) { + // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying + $offset = \mb_strlen(\substr($contents, 0, $match[0][1]), 'UTF-8'); + } else { + $offset = \intval($match[0][1]); + } + + // Remove the offsets, keeping only the matched text + $m = \array_column($match, 0); + + if ($m === []) { + continue; + } + + // Add this match to the list of character positions to stop at + $ret[$offset][] = [$parser, $m]; + } + } + + // Sort matches by position so we visit them in order + \ksort($ret); + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php new file mode 100644 index 0000000..8a0986d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * Parser for inline content (text, links, emphasized text, etc). + */ +interface InlineParserEngineInterface +{ + /** + * Parse the given contents as inlines and insert them into the given block + */ + public function parse(string $contents, AbstractBlock $block): void; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParser.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParser.php new file mode 100644 index 0000000..dcf9a42 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParser.php @@ -0,0 +1,346 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional code based on commonmark-java (https://github.com/commonmark/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Event\DocumentPreParsedEvent; +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Input\MarkdownInput; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Block\DocumentBlockParser; +use League\CommonMark\Parser\Block\ParagraphParser; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceMap; + +final class MarkdownParser implements MarkdownParserInterface +{ + /** @psalm-readonly */ + private EnvironmentInterface $environment; + + /** @psalm-readonly-allow-private-mutation */ + private int $maxNestingLevel; + + /** @psalm-readonly-allow-private-mutation */ + private ReferenceMap $referenceMap; + + /** @psalm-readonly-allow-private-mutation */ + private int $lineNumber = 0; + + /** @psalm-readonly-allow-private-mutation */ + private Cursor $cursor; + + /** + * @var array<int, BlockContinueParserInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $activeBlockParsers = []; + + /** + * @var array<int, BlockContinueParserWithInlinesInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $closedBlockParsers = []; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + } + + private function initialize(): void + { + $this->referenceMap = new ReferenceMap(); + $this->lineNumber = 0; + $this->activeBlockParsers = []; + $this->closedBlockParsers = []; + + $this->maxNestingLevel = $this->environment->getConfiguration()->get('max_nesting_level'); + } + + /** + * @throws CommonMarkException + */ + public function parse(string $input): Document + { + $this->initialize(); + + $documentParser = new DocumentBlockParser($this->referenceMap); + $this->activateBlockParser($documentParser); + + $preParsedEvent = new DocumentPreParsedEvent($documentParser->getBlock(), new MarkdownInput($input)); + $this->environment->dispatch($preParsedEvent); + $markdownInput = $preParsedEvent->getMarkdown(); + + foreach ($markdownInput->getLines() as $lineNumber => $line) { + $this->lineNumber = $lineNumber; + $this->parseLine($line); + } + + // finalizeAndProcess + $this->closeBlockParsers(\count($this->activeBlockParsers), $this->lineNumber); + $this->processInlines(); + + $this->environment->dispatch(new DocumentParsedEvent($documentParser->getBlock())); + + return $documentParser->getBlock(); + } + + /** + * Analyze a line of text and update the document appropriately. We parse markdown text by calling this on each + * line of input, then finalizing the document. + */ + private function parseLine(string $line): void + { + $this->cursor = new Cursor($line); + + $matches = $this->parseBlockContinuation(); + if ($matches === null) { + return; + } + + $unmatchedBlocks = \count($this->activeBlockParsers) - $matches; + $blockParser = $this->activeBlockParsers[$matches - 1]; + $startedNewBlock = false; + + // Unless last matched container is a code block, try new container starts, + // adding children to the last matched container: + $tryBlockStarts = $blockParser->getBlock() instanceof Paragraph || $blockParser->isContainer(); + while ($tryBlockStarts) { + // this is a little performance optimization + if ($this->cursor->isBlank()) { + $this->cursor->advanceToEnd(); + break; + } + + if ($blockParser->getBlock()->getDepth() >= $this->maxNestingLevel) { + break; + } + + $blockStart = $this->findBlockStart($blockParser); + if ($blockStart === null || $blockStart->isAborting()) { + $this->cursor->advanceToNextNonSpaceOrTab(); + break; + } + + if (($state = $blockStart->getCursorState()) !== null) { + $this->cursor->restoreState($state); + } + + $startedNewBlock = true; + + // We're starting a new block. If we have any previous blocks that need to be closed, we need to do it now. + if ($unmatchedBlocks > 0) { + $this->closeBlockParsers($unmatchedBlocks, $this->lineNumber - 1); + $unmatchedBlocks = 0; + } + + if ($blockStart->isReplaceActiveBlockParser()) { + $this->prepareActiveBlockParserForReplacement(); + } + + foreach ($blockStart->getBlockParsers() as $newBlockParser) { + $blockParser = $this->addChild($newBlockParser); + $tryBlockStarts = $newBlockParser->isContainer(); + } + } + + // What remains at the offset is a text line. Add the text to the appropriate block. + + // First check for a lazy paragraph continuation: + if (! $startedNewBlock && ! $this->cursor->isBlank() && $this->getActiveBlockParser()->canHaveLazyContinuationLines()) { + $this->getActiveBlockParser()->addLine($this->cursor->getRemainder()); + } else { + // finalize any blocks not matched + if ($unmatchedBlocks > 0) { + $this->closeBlockParsers($unmatchedBlocks, $this->lineNumber); + } + + if (! $blockParser->isContainer()) { + $this->getActiveBlockParser()->addLine($this->cursor->getRemainder()); + } elseif (! $this->cursor->isBlank()) { + $this->addChild(new ParagraphParser()); + $this->getActiveBlockParser()->addLine($this->cursor->getRemainder()); + } + } + } + + private function parseBlockContinuation(): ?int + { + // For each containing block, try to parse the associated line start. + // The document will always match, so we can skip the first block parser and start at 1 matches + $matches = 1; + for ($i = 1; $i < \count($this->activeBlockParsers); $i++) { + $blockParser = $this->activeBlockParsers[$i]; + $blockContinue = $blockParser->tryContinue(clone $this->cursor, $this->getActiveBlockParser()); + if ($blockContinue === null) { + break; + } + + if ($blockContinue->isFinalize()) { + $this->closeBlockParsers(\count($this->activeBlockParsers) - $i, $this->lineNumber); + + return null; + } + + if (($state = $blockContinue->getCursorState()) !== null) { + $this->cursor->restoreState($state); + } + + $matches++; + } + + return $matches; + } + + private function findBlockStart(BlockContinueParserInterface $lastMatchedBlockParser): ?BlockStart + { + $matchedBlockParser = new MarkdownParserState($this->getActiveBlockParser(), $lastMatchedBlockParser); + + foreach ($this->environment->getBlockStartParsers() as $blockStartParser) { + \assert($blockStartParser instanceof BlockStartParserInterface); + if (($result = $blockStartParser->tryStart(clone $this->cursor, $matchedBlockParser)) !== null) { + return $result; + } + } + + return null; + } + + private function closeBlockParsers(int $count, int $endLineNumber): void + { + for ($i = 0; $i < $count; $i++) { + $blockParser = $this->deactivateBlockParser(); + $this->finalize($blockParser, $endLineNumber); + + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($blockParser instanceof BlockContinueParserWithInlinesInterface) { + // Remember for inline parsing + $this->closedBlockParsers[] = $blockParser; + } + } + } + + /** + * Finalize a block. Close it and do any necessary postprocessing, e.g. creating string_content from strings, + * setting the 'tight' or 'loose' status of a list, and parsing the beginnings of paragraphs for reference + * definitions. + */ + private function finalize(BlockContinueParserInterface $blockParser, int $endLineNumber): void + { + if ($blockParser instanceof ParagraphParser) { + $this->updateReferenceMap($blockParser->getReferences()); + } + + $blockParser->getBlock()->setEndLine($endLineNumber); + $blockParser->closeBlock(); + } + + /** + * Walk through a block & children recursively, parsing string content into inline content where appropriate. + */ + private function processInlines(): void + { + $p = new InlineParserEngine($this->environment, $this->referenceMap); + + foreach ($this->closedBlockParsers as $blockParser) { + $blockParser->parseInlines($p); + } + } + + /** + * Add block of type tag as a child of the tip. If the tip can't accept children, close and finalize it and try + * its parent, and so on til we find a block that can accept children. + */ + private function addChild(BlockContinueParserInterface $blockParser): BlockContinueParserInterface + { + $blockParser->getBlock()->setStartLine($this->lineNumber); + + while (! $this->getActiveBlockParser()->canContain($blockParser->getBlock())) { + $this->closeBlockParsers(1, $this->lineNumber - 1); + } + + $this->getActiveBlockParser()->getBlock()->appendChild($blockParser->getBlock()); + $this->activateBlockParser($blockParser); + + return $blockParser; + } + + private function activateBlockParser(BlockContinueParserInterface $blockParser): void + { + $this->activeBlockParsers[] = $blockParser; + } + + /** + * @throws ParserLogicException + */ + private function deactivateBlockParser(): BlockContinueParserInterface + { + $popped = \array_pop($this->activeBlockParsers); + if ($popped === null) { + throw new ParserLogicException('The last block parser should not be deactivated'); + } + + return $popped; + } + + private function prepareActiveBlockParserForReplacement(): void + { + // Note that we don't want to parse inlines or finalize this block, as it's getting replaced. + $old = $this->deactivateBlockParser(); + + if ($old instanceof ParagraphParser) { + $this->updateReferenceMap($old->getReferences()); + } + + $old->getBlock()->detach(); + } + + /** + * @param ReferenceInterface[] $references + */ + private function updateReferenceMap(iterable $references): void + { + foreach ($references as $reference) { + if (! $this->referenceMap->contains($reference->getLabel())) { + $this->referenceMap->add($reference); + } + } + } + + /** + * @throws ParserLogicException + */ + public function getActiveBlockParser(): BlockContinueParserInterface + { + $active = \end($this->activeBlockParsers); + if ($active === false) { + throw new ParserLogicException('No active block parsers are available'); + } + + return $active; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserInterface.php new file mode 100644 index 0000000..e0a6be4 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserInterface.php @@ -0,0 +1,25 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Node\Block\Document; + +interface MarkdownParserInterface +{ + /** + * @throws CommonMarkException + */ + public function parse(string $input): Document; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserState.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserState.php new file mode 100644 index 0000000..79abd42 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserState.php @@ -0,0 +1,57 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\ParagraphParser; + +/** + * @internal You should rely on the interface instead + */ +final class MarkdownParserState implements MarkdownParserStateInterface +{ + /** @psalm-readonly */ + private BlockContinueParserInterface $activeBlockParser; + + /** @psalm-readonly */ + private BlockContinueParserInterface $lastMatchedBlockParser; + + public function __construct(BlockContinueParserInterface $activeBlockParser, BlockContinueParserInterface $lastMatchedBlockParser) + { + $this->activeBlockParser = $activeBlockParser; + $this->lastMatchedBlockParser = $lastMatchedBlockParser; + } + + public function getActiveBlockParser(): BlockContinueParserInterface + { + return $this->activeBlockParser; + } + + public function getLastMatchedBlockParser(): BlockContinueParserInterface + { + return $this->lastMatchedBlockParser; + } + + public function getParagraphContent(): ?string + { + if (! $this->lastMatchedBlockParser instanceof ParagraphParser) { + return null; + } + + $paragraphParser = $this->lastMatchedBlockParser; + $content = $paragraphParser->getContentString(); + + return $content === '' ? null : $content; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php new file mode 100644 index 0000000..21a9d3a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php @@ -0,0 +1,36 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Parser\Block\BlockContinueParserInterface; + +interface MarkdownParserStateInterface +{ + /** + * Returns the deepest open block parser + */ + public function getActiveBlockParser(): BlockContinueParserInterface; + + /** + * Open block parser that was last matched during the continue phase. This is different from the currently active + * block parser, as an unmatched block is only closed when a new block is started. + */ + public function getLastMatchedBlockParser(): BlockContinueParserInterface; + + /** + * Returns the current content of the paragraph if the matched block is a paragraph. The content can be multiple + * lines separated by newlines. + */ + public function getParagraphContent(): ?string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Parser/ParserLogicException.php b/php/libraries/composer/vendor/league/commonmark/src/Parser/ParserLogicException.php new file mode 100644 index 0000000..592b1a2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Parser/ParserLogicException.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Exception\CommonMarkException; + +class ParserLogicException extends \LogicException implements CommonMarkException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Reference/Reference.php b/php/libraries/composer/vendor/league/commonmark/src/Reference/Reference.php new file mode 100644 index 0000000..a0d571d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Reference/Reference.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +/** + * @psalm-immutable + */ +final class Reference implements ReferenceInterface +{ + /** @psalm-readonly */ + private string $label; + + /** @psalm-readonly */ + private string $destination; + + /** @psalm-readonly */ + private string $title; + + public function __construct(string $label, string $destination, string $title) + { + $this->label = $label; + $this->destination = $destination; + $this->title = $title; + } + + public function getLabel(): string + { + return $this->label; + } + + public function getDestination(): string + { + return $this->destination; + } + + public function getTitle(): string + { + return $this->title; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceInterface.php new file mode 100644 index 0000000..244b354 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceInterface.php @@ -0,0 +1,29 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +/** + * Link reference + */ +interface ReferenceInterface +{ + public function getLabel(): string; + + public function getDestination(): string; + + public function getTitle(): string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceMap.php b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceMap.php new file mode 100644 index 0000000..982cb12 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceMap.php @@ -0,0 +1,77 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +use League\CommonMark\Normalizer\TextNormalizer; + +/** + * A collection of references, indexed by label + */ +final class ReferenceMap implements ReferenceMapInterface +{ + /** @psalm-readonly */ + private TextNormalizer $normalizer; + + /** + * @var array<string, ReferenceInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $references = []; + + public function __construct() + { + $this->normalizer = new TextNormalizer(); + } + + public function add(ReferenceInterface $reference): void + { + // Normalize the key + $key = $this->normalizer->normalize($reference->getLabel()); + // Store the reference + $this->references[$key] = $reference; + } + + public function contains(string $label): bool + { + $label = $this->normalizer->normalize($label); + + return isset($this->references[$label]); + } + + public function get(string $label): ?ReferenceInterface + { + $label = $this->normalizer->normalize($label); + + return $this->references[$label] ?? null; + } + + /** + * @return \Traversable<string, ReferenceInterface> + */ + public function getIterator(): \Traversable + { + foreach ($this->references as $normalizedLabel => $reference) { + yield $normalizedLabel => $reference; + } + } + + public function count(): int + { + return \count($this->references); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceMapInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceMapInterface.php new file mode 100644 index 0000000..71daa19 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceMapInterface.php @@ -0,0 +1,31 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +/** + * A collection of references + * + * @phpstan-extends \IteratorAggregate<ReferenceInterface> + */ +interface ReferenceMapInterface extends \IteratorAggregate, \Countable +{ + public function add(ReferenceInterface $reference): void; + + public function contains(string $label): bool; + + public function get(string $label): ?ReferenceInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceParser.php b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceParser.php new file mode 100644 index 0000000..c01dd21 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceParser.php @@ -0,0 +1,324 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\LinkParserHelper; + +final class ReferenceParser +{ + // Looking for the start of a definition, i.e. `[` + private const START_DEFINITION = 0; + // Looking for and parsing the label, i.e. `[foo]` within `[foo]` + private const LABEL = 1; + // Parsing the destination, i.e. `/url` in `[foo]: /url` + private const DESTINATION = 2; + // Looking for the start of a title, i.e. the first `"` in `[foo]: /url "title"` + private const START_TITLE = 3; + // Parsing the content of the title, i.e. `title` in `[foo]: /url "title"` + private const TITLE = 4; + // End state, no matter what kind of lines we add, they won't be references + private const PARAGRAPH = 5; + + /** @psalm-readonly-allow-private-mutation */ + private string $paragraph = ''; + + /** + * @var array<int, ReferenceInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $references = []; + + /** @psalm-readonly-allow-private-mutation */ + private int $state = self::START_DEFINITION; + + /** @psalm-readonly-allow-private-mutation */ + private ?string $label = null; + + /** @psalm-readonly-allow-private-mutation */ + private ?string $destination = null; + + /** + * @var string string + * + * @psalm-readonly-allow-private-mutation + */ + private string $title = ''; + + /** @psalm-readonly-allow-private-mutation */ + private ?string $titleDelimiter = null; + + /** @psalm-readonly-allow-private-mutation */ + private bool $referenceValid = false; + + public function getParagraphContent(): string + { + return $this->paragraph; + } + + /** + * @return ReferenceInterface[] + */ + public function getReferences(): iterable + { + $this->finishReference(); + + return $this->references; + } + + public function hasReferences(): bool + { + return $this->references !== []; + } + + public function parse(string $line): void + { + if ($this->paragraph !== '') { + $this->paragraph .= "\n"; + } + + $this->paragraph .= $line; + + $cursor = new Cursor($line); + while (! $cursor->isAtEnd()) { + $result = false; + switch ($this->state) { + case self::PARAGRAPH: + // We're in a paragraph now. Link reference definitions can only appear at the beginning, so once + // we're in a paragraph, there's no going back. + return; + case self::START_DEFINITION: + $result = $this->parseStartDefinition($cursor); + break; + case self::LABEL: + $result = $this->parseLabel($cursor); + break; + case self::DESTINATION: + $result = $this->parseDestination($cursor); + break; + case self::START_TITLE: + $result = $this->parseStartTitle($cursor); + break; + case self::TITLE: + $result = $this->parseTitle($cursor); + break; + default: + // this should never happen + break; + } + + if (! $result) { + $this->state = self::PARAGRAPH; + + return; + } + } + } + + private function parseStartDefinition(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd() || $cursor->getCurrentCharacter() !== '[') { + return false; + } + + $this->state = self::LABEL; + $this->label = ''; + + $cursor->advance(); + if ($cursor->isAtEnd()) { + $this->label .= "\n"; + } + + return true; + } + + private function parseLabel(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + + $partialLabel = LinkParserHelper::parsePartialLinkLabel($cursor); + if ($partialLabel === null) { + return false; + } + + \assert($this->label !== null); + $this->label .= $partialLabel; + + if ($cursor->isAtEnd()) { + // label might continue on next line + $this->label .= "\n"; + + return true; + } + + if ($cursor->getCurrentCharacter() !== ']') { + return false; + } + + $cursor->advance(); + + // end of label + if ($cursor->getCurrentCharacter() !== ':') { + return false; + } + + $cursor->advance(); + + // spec: A link label can have at most 999 characters inside the square brackets + if (\mb_strlen($this->label, 'UTF-8') > 999) { + return false; + } + + // spec: A link label must contain at least one non-whitespace character + if (\trim($this->label) === '') { + return false; + } + + $cursor->advanceToNextNonSpaceOrTab(); + + $this->state = self::DESTINATION; + + return true; + } + + private function parseDestination(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + + $destination = LinkParserHelper::parseLinkDestination($cursor); + if ($destination === null) { + return false; + } + + $this->destination = $destination; + + $advanced = $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd()) { + // Destination was at end of line, so this is a valid reference for sure (and maybe a title). + // If not at end of line, wait for title to be valid first. + $this->referenceValid = true; + $this->paragraph = ''; + } elseif ($advanced === 0) { + // spec: The title must be separated from the link destination by whitespace + return false; + } + + $this->state = self::START_TITLE; + + return true; + } + + private function parseStartTitle(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd()) { + $this->state = self::START_DEFINITION; + + return true; + } + + $this->titleDelimiter = null; + switch ($c = $cursor->getCurrentCharacter()) { + case '"': + case "'": + $this->titleDelimiter = $c; + break; + case '(': + $this->titleDelimiter = ')'; + break; + default: + // no title delimter found + break; + } + + if ($this->titleDelimiter !== null) { + $this->state = self::TITLE; + $cursor->advance(); + if ($cursor->isAtEnd()) { + $this->title .= "\n"; + } + } else { + $this->finishReference(); + // There might be another reference instead, try that for the same character. + $this->state = self::START_DEFINITION; + } + + return true; + } + + private function parseTitle(Cursor $cursor): bool + { + \assert($this->titleDelimiter !== null); + $title = LinkParserHelper::parsePartialLinkTitle($cursor, $this->titleDelimiter); + + if ($title === null) { + // Invalid title, stop + return false; + } + + // Did we find the end delimiter? + $endDelimiterFound = false; + if (\substr($title, -1) === $this->titleDelimiter) { + $endDelimiterFound = true; + // Chop it off + $title = \substr($title, 0, -1); + } + + $this->title .= $title; + + if (! $endDelimiterFound && $cursor->isAtEnd()) { + // Title still going, continue on next line + $this->title .= "\n"; + + return true; + } + + // We either hit the end delimiter or some extra whitespace + $cursor->advanceToNextNonSpaceOrTab(); + if (! $cursor->isAtEnd()) { + // spec: No further non-whitespace characters may occur on the line. + return false; + } + + $this->referenceValid = true; + $this->finishReference(); + $this->paragraph = ''; + + // See if there's another definition + $this->state = self::START_DEFINITION; + + return true; + } + + private function finishReference(): void + { + if (! $this->referenceValid) { + return; + } + + /** @psalm-suppress PossiblyNullArgument -- these can't possibly be null if we're in this state */ + $this->references[] = new Reference($this->label, $this->destination, $this->title); + + $this->label = null; + $this->referenceValid = false; + $this->destination = null; + $this->title = ''; + $this->titleDelimiter = null; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceableInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceableInterface.php new file mode 100644 index 0000000..b45f379 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Reference/ReferenceableInterface.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Reference; + +interface ReferenceableInterface +{ + public function getReference(): ReferenceInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php new file mode 100644 index 0000000..3262691 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php @@ -0,0 +1,57 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Block; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class DocumentRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Document $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + Document::assertInstanceOf($node); + + $wholeDoc = $childRenderer->renderNodes($node->children()); + + return $wholeDoc === '' ? '' : $wholeDoc . "\n"; + } + + public function getXmlTagName(Node $node): string + { + return 'document'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return [ + 'xmlns' => 'http://commonmark.org/xml/1.0', + ]; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php new file mode 100644 index 0000000..934eac2 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php @@ -0,0 +1,74 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Block; + +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Block\TightBlockInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ParagraphRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Paragraph $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + Paragraph::assertInstanceOf($node); + + if ($this->inTightList($node)) { + return $childRenderer->renderNodes($node->children()); + } + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('p', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'paragraph'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } + + private function inTightList(Paragraph $node): bool + { + // Only check up to two (2) levels above this for tightness + $i = 2; + while (($node = $node->parent()) && $i--) { + if ($node instanceof TightBlockInterface) { + return $node->isTight(); + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php new file mode 100644 index 0000000..8e866b5 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php @@ -0,0 +1,31 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Node; + +/** + * Renders multiple nodes by delegating to the individual node renderers and adding spacing where needed + */ +interface ChildNodeRendererInterface +{ + /** + * @param Node[] $nodes + */ + public function renderNodes(iterable $nodes): string; + + public function getBlockSeparator(): string; + + public function getInnerSeparator(): string; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php new file mode 100644 index 0000000..dd34dd6 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php @@ -0,0 +1,28 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Output\RenderedContentInterface; + +/** + * Renders a parsed Document AST + */ +interface DocumentRendererInterface extends MarkdownRendererInterface +{ + /** + * Render the given Document node (and all of its children) + */ + public function renderDocument(Document $document): RenderedContentInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/HtmlDecorator.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/HtmlDecorator.php new file mode 100644 index 0000000..46a38d9 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/HtmlDecorator.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Node; +use League\CommonMark\Util\HtmlElement; + +final class HtmlDecorator implements NodeRendererInterface +{ + private NodeRendererInterface $inner; + private string $tag; + /** @var array<string, string|string[]|bool> */ + private array $attributes; + private bool $selfClosing; + + /** + * @param array<string, string|string[]|bool> $attributes + */ + public function __construct(NodeRendererInterface $inner, string $tag, array $attributes = [], bool $selfClosing = false) + { + $this->inner = $inner; + $this->tag = $tag; + $this->attributes = $attributes; + $this->selfClosing = $selfClosing; + } + + /** + * {@inheritDoc} + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + return new HtmlElement($this->tag, $this->attributes, $this->inner->render($node, $childRenderer), $this->selfClosing); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/HtmlRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/HtmlRenderer.php new file mode 100644 index 0000000..2e05cfb --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/HtmlRenderer.php @@ -0,0 +1,100 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Event\DocumentRenderedEvent; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Output\RenderedContent; +use League\CommonMark\Output\RenderedContentInterface; + +final class HtmlRenderer implements DocumentRendererInterface, ChildNodeRendererInterface +{ + /** @psalm-readonly */ + private EnvironmentInterface $environment; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + } + + public function renderDocument(Document $document): RenderedContentInterface + { + $this->environment->dispatch(new DocumentPreRenderEvent($document, 'html')); + + $output = new RenderedContent($document, (string) $this->renderNode($document)); + + $event = new DocumentRenderedEvent($output); + $this->environment->dispatch($event); + + return $event->getOutput(); + } + + /** + * {@inheritDoc} + */ + public function renderNodes(iterable $nodes): string + { + $output = ''; + + $isFirstItem = true; + + foreach ($nodes as $node) { + if (! $isFirstItem && $node instanceof AbstractBlock) { + $output .= $this->getBlockSeparator(); + } + + $output .= $this->renderNode($node); + + $isFirstItem = false; + } + + return $output; + } + + /** + * @return \Stringable|string + * + * @throws NoMatchingRendererException + */ + private function renderNode(Node $node) + { + $renderers = $this->environment->getRenderersForClass(\get_class($node)); + + foreach ($renderers as $renderer) { + \assert($renderer instanceof NodeRendererInterface); + if (($result = $renderer->render($node, $this)) !== null) { + return $result; + } + } + + throw new NoMatchingRendererException('Unable to find corresponding renderer for node type ' . \get_class($node)); + } + + public function getBlockSeparator(): string + { + return $this->environment->getConfiguration()->get('renderer/block_separator'); + } + + public function getInnerSeparator(): string + { + return $this->environment->getConfiguration()->get('renderer/inner_separator'); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php new file mode 100644 index 0000000..f64cc58 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php @@ -0,0 +1,76 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Inline; + +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class NewlineRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + /** + * @param Newline $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + Newline::assertInstanceOf($node); + + if ($node->getType() === Newline::HARDBREAK) { + return "<br />\n"; + } + + return $this->config->get('renderer/soft_break'); + } + + /** + * @param Newline $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlTagName(Node $node): string + { + Newline::assertInstanceOf($node); + + return $node->getType() === Newline::SOFTBREAK ? 'softbreak' : 'linebreak'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php new file mode 100644 index 0000000..40ad02a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Inline; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TextRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Text $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + Text::assertInstanceOf($node); + + return Xml::escape($node->getLiteral()); + } + + public function getXmlTagName(Node $node): string + { + return 'text'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php new file mode 100644 index 0000000..83af8cd --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php @@ -0,0 +1,30 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Output\RenderedContentInterface; + +/** + * Renders a parsed Document AST + * + * @deprecated since 2.3; use {@link DocumentRendererInterface} instead + */ +interface MarkdownRendererInterface +{ + /** + * Render the given Document node (and all of its children) + */ + public function renderDocument(Document $document): RenderedContentInterface; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php new file mode 100644 index 0000000..14fe493 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Exception\LogicException; + +class NoMatchingRendererException extends LogicException +{ +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Renderer/NodeRendererInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Renderer/NodeRendererInterface.php new file mode 100644 index 0000000..5d40582 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Renderer/NodeRendererInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Node; + +interface NodeRendererInterface +{ + /** + * @return \Stringable|string|null + * + * @throws InvalidArgumentException if the wrong type of Node is provided + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer); +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/ArrayCollection.php b/php/libraries/composer/vendor/league/commonmark/src/Util/ArrayCollection.php new file mode 100644 index 0000000..7210770 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/ArrayCollection.php @@ -0,0 +1,173 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * Array collection + * + * Provides a wrapper around a standard PHP array. + * + * @internal + * + * @phpstan-template T + * @phpstan-implements \IteratorAggregate<int, T> + * @phpstan-implements \ArrayAccess<int, T> + */ +final class ArrayCollection implements \IteratorAggregate, \Countable, \ArrayAccess +{ + /** + * @var array<int, mixed> + * @phpstan-var array<int, T> + */ + private array $elements; + + /** + * Constructor + * + * @param array<int|string, mixed> $elements + * + * @phpstan-param array<int, T> $elements + */ + public function __construct(array $elements = []) + { + $this->elements = $elements; + } + + /** + * @return mixed|false + * + * @phpstan-return T|false + */ + public function first() + { + return \reset($this->elements); + } + + /** + * @return mixed|false + * + * @phpstan-return T|false + */ + public function last() + { + return \end($this->elements); + } + + /** + * Retrieve an external iterator + * + * @return \ArrayIterator<int, mixed> + * + * @phpstan-return \ArrayIterator<int, T> + */ + #[\ReturnTypeWillChange] + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->elements); + } + + /** + * Count elements of an object + * + * @return int The count as an integer. + */ + public function count(): int + { + return \count($this->elements); + } + + /** + * Whether an offset exists + * + * {@inheritDoc} + * + * @phpstan-param int $offset + */ + public function offsetExists($offset): bool + { + return \array_key_exists($offset, $this->elements); + } + + /** + * Offset to retrieve + * + * {@inheritDoc} + * + * @phpstan-param int $offset + * + * @phpstan-return T|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->elements[$offset] ?? null; + } + + /** + * Offset to set + * + * {@inheritDoc} + * + * @phpstan-param int|null $offset + * @phpstan-param T $value + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value): void + { + if ($offset === null) { + $this->elements[] = $value; + } else { + $this->elements[$offset] = $value; + } + } + + /** + * Offset to unset + * + * {@inheritDoc} + * + * @phpstan-param int $offset + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset): void + { + if (! \array_key_exists($offset, $this->elements)) { + return; + } + + unset($this->elements[$offset]); + } + + /** + * Returns a subset of the array + * + * @return array<int, mixed> + * + * @phpstan-return array<int, T> + */ + public function slice(int $offset, ?int $length = null): array + { + return \array_slice($this->elements, $offset, $length, true); + } + + /** + * @return array<int, mixed> + * + * @phpstan-return array<int, T> + */ + public function toArray(): array + { + return $this->elements; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/Html5EntityDecoder.php b/php/libraries/composer/vendor/league/commonmark/src/Util/Html5EntityDecoder.php new file mode 100644 index 0000000..52550a0 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/Html5EntityDecoder.php @@ -0,0 +1,75 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * @psalm-immutable + */ +final class Html5EntityDecoder +{ + /** + * @psalm-pure + */ + public static function decode(string $entity): string + { + if (\substr($entity, -1) !== ';') { + return $entity; + } + + if (\substr($entity, 0, 2) === '&#') { + if (\strtolower(\substr($entity, 2, 1)) === 'x') { + return self::fromHex(\substr($entity, 3, -1)); + } + + return self::fromDecimal(\substr($entity, 2, -1)); + } + + return \html_entity_decode($entity, \ENT_QUOTES | \ENT_HTML5, 'UTF-8'); + } + + /** + * @param mixed $number + * + * @psalm-pure + */ + private static function fromDecimal($number): string + { + // Only convert code points within planes 0-2, excluding NULL + // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found + if (empty($number) || $number > 0x2FFFF) { + return self::fromHex('fffd'); + } + + $entity = '&#' . $number . ';'; + + $converted = \mb_decode_numericentity($entity, [0x0, 0x2FFFF, 0, 0xFFFF], 'UTF-8'); + + if ($converted === $entity) { + return self::fromHex('fffd'); + } + + return $converted; + } + + /** + * @psalm-pure + */ + private static function fromHex(string $hexChars): string + { + return self::fromDecimal(\hexdec($hexChars)); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/HtmlElement.php b/php/libraries/composer/vendor/league/commonmark/src/Util/HtmlElement.php new file mode 100644 index 0000000..51fa6de --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/HtmlElement.php @@ -0,0 +1,160 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +final class HtmlElement implements \Stringable +{ + /** @psalm-readonly */ + private string $tagName; + + /** @var array<string, string|bool> */ + private array $attributes = []; + + /** @var \Stringable|\Stringable[]|string */ + private $contents; + + /** @psalm-readonly */ + private bool $selfClosing; + + /** + * @param string $tagName Name of the HTML tag + * @param array<string, string|string[]|bool> $attributes Array of attributes (values should be unescaped) + * @param \Stringable|\Stringable[]|string|null $contents Inner contents, pre-escaped if needed + * @param bool $selfClosing Whether the tag is self-closing + */ + public function __construct(string $tagName, array $attributes = [], $contents = '', bool $selfClosing = false) + { + $this->tagName = $tagName; + $this->selfClosing = $selfClosing; + + foreach ($attributes as $name => $value) { + $this->setAttribute($name, $value); + } + + $this->setContents($contents ?? ''); + } + + /** @psalm-immutable */ + public function getTagName(): string + { + return $this->tagName; + } + + /** + * @return array<string, string|bool> + * + * @psalm-immutable + */ + public function getAllAttributes(): array + { + return $this->attributes; + } + + /** + * @return string|bool|null + * + * @psalm-immutable + */ + public function getAttribute(string $key) + { + return $this->attributes[$key] ?? null; + } + + /** + * @param string|string[]|bool $value + */ + public function setAttribute(string $key, $value = true): self + { + if (\is_array($value)) { + $this->attributes[$key] = \implode(' ', \array_unique($value)); + } else { + $this->attributes[$key] = $value; + } + + return $this; + } + + /** + * @return \Stringable|\Stringable[]|string + * + * @psalm-immutable + */ + public function getContents(bool $asString = true) + { + if (! $asString) { + return $this->contents; + } + + return $this->getContentsAsString(); + } + + /** + * Sets the inner contents of the tag (must be pre-escaped if needed) + * + * @param \Stringable|\Stringable[]|string $contents + * + * @return $this + */ + public function setContents($contents): self + { + $this->contents = $contents ?? ''; // @phpstan-ignore-line + + return $this; + } + + /** @psalm-immutable */ + public function __toString(): string + { + $result = '<' . $this->tagName; + + foreach ($this->attributes as $key => $value) { + if ($value === true) { + $result .= ' ' . $key; + } elseif ($value === false) { + continue; + } else { + $result .= ' ' . $key . '="' . Xml::escape($value) . '"'; + } + } + + if ($this->contents !== '') { + $result .= '>' . $this->getContentsAsString() . '</' . $this->tagName . '>'; + } elseif ($this->selfClosing && $this->tagName === 'input') { + $result .= '>'; + } elseif ($this->selfClosing) { + $result .= ' />'; + } else { + $result .= '></' . $this->tagName . '>'; + } + + return $result; + } + + /** @psalm-immutable */ + private function getContentsAsString(): string + { + if (\is_string($this->contents)) { + return $this->contents; + } + + if (\is_array($this->contents)) { + return \implode('', $this->contents); + } + + return (string) $this->contents; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/HtmlFilter.php b/php/libraries/composer/vendor/league/commonmark/src/Util/HtmlFilter.php new file mode 100644 index 0000000..b1e0555 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/HtmlFilter.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\InvalidArgumentException; + +/** + * @psalm-immutable + */ +final class HtmlFilter +{ + // Return the entire string as-is + public const ALLOW = 'allow'; + // Escape the entire string so any HTML/JS won't be interpreted as such + public const ESCAPE = 'escape'; + // Return an empty string + public const STRIP = 'strip'; + + /** + * Runs the given HTML through the given filter + * + * @param string $html HTML input to be filtered + * @param string $filter One of the HtmlFilter constants + * + * @return string Filtered HTML + * + * @throws InvalidArgumentException when an invalid $filter is given + * + * @psalm-pure + */ + public static function filter(string $html, string $filter): string + { + switch ($filter) { + case self::STRIP: + return ''; + case self::ESCAPE: + return \htmlspecialchars($html, \ENT_NOQUOTES); + case self::ALLOW: + return $html; + default: + throw new InvalidArgumentException(\sprintf('Invalid filter provided: "%s"', $filter)); + } + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/LinkParserHelper.php b/php/libraries/composer/vendor/league/commonmark/src/Util/LinkParserHelper.php new file mode 100644 index 0000000..e329669 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/LinkParserHelper.php @@ -0,0 +1,142 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Parser\Cursor; + +/** + * @psalm-immutable + */ +final class LinkParserHelper +{ + /** + * Attempt to parse link destination + * + * @return string|null The string, or null if no match + */ + public static function parseLinkDestination(Cursor $cursor): ?string + { + if ($res = $cursor->match(RegexHelper::REGEX_LINK_DESTINATION_BRACES)) { + // Chop off surrounding <..>: + return UrlEncoder::unescapeAndEncode( + RegexHelper::unescape(\substr($res, 1, -1)) + ); + } + + if ($cursor->getCurrentCharacter() === '<') { + return null; + } + + $destination = self::manuallyParseLinkDestination($cursor); + if ($destination === null) { + return null; + } + + return UrlEncoder::unescapeAndEncode( + RegexHelper::unescape($destination) + ); + } + + public static function parseLinkLabel(Cursor $cursor): int + { + $match = $cursor->match('/^\[(?:[^\\\\\[\]]|\\\\.){0,1000}\]/'); + if ($match === null) { + return 0; + } + + $length = \mb_strlen($match, 'UTF-8'); + + if ($length > 1001) { + return 0; + } + + return $length; + } + + public static function parsePartialLinkLabel(Cursor $cursor): ?string + { + return $cursor->match('/^(?:[^\\\\\[\]]+|\\\\.?)*/'); + } + + /** + * Attempt to parse link title (sans quotes) + * + * @return string|null The string, or null if no match + */ + public static function parseLinkTitle(Cursor $cursor): ?string + { + if ($title = $cursor->match('/' . RegexHelper::PARTIAL_LINK_TITLE . '/')) { + // Chop off quotes from title and unescape + return RegexHelper::unescape(\substr($title, 1, -1)); + } + + return null; + } + + public static function parsePartialLinkTitle(Cursor $cursor, string $endDelimiter): ?string + { + $endDelimiter = \preg_quote($endDelimiter, '/'); + $regex = \sprintf('/(%s|[^%s\x00])*(?:%s)?/', RegexHelper::PARTIAL_ESCAPED_CHAR, $endDelimiter, $endDelimiter); + if (($partialTitle = $cursor->match($regex)) === null) { + return null; + } + + return RegexHelper::unescape($partialTitle); + } + + private static function manuallyParseLinkDestination(Cursor $cursor): ?string + { + $oldPosition = $cursor->getPosition(); + $oldState = $cursor->saveState(); + + $openParens = 0; + while (($c = $cursor->getCurrentCharacter()) !== null) { + if ($c === '\\' && ($peek = $cursor->peek()) !== null && RegexHelper::isEscapable($peek)) { + $cursor->advanceBy(2); + } elseif ($c === '(') { + $cursor->advanceBy(1); + $openParens++; + } elseif ($c === ')') { + if ($openParens < 1) { + break; + } + + $cursor->advanceBy(1); + $openParens--; + } elseif (\preg_match(RegexHelper::REGEX_WHITESPACE_CHAR, $c)) { + break; + } else { + $cursor->advanceBy(1); + } + } + + if ($openParens !== 0) { + return null; + } + + if ($cursor->getPosition() === $oldPosition && (! isset($c) || $c !== ')')) { + return null; + } + + $newPos = $cursor->getPosition(); + $cursor->restoreState($oldState); + + $cursor->advanceBy($newPos - $cursor->getPosition()); + + return $cursor->getPreviousText(); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/PrioritizedList.php b/php/libraries/composer/vendor/league/commonmark/src/Util/PrioritizedList.php new file mode 100644 index 0000000..77ec24a --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/PrioritizedList.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * @internal + * + * @phpstan-template T + * @phpstan-implements \IteratorAggregate<T> + */ +final class PrioritizedList implements \IteratorAggregate +{ + /** + * @var array<int, array<mixed>> + * @phpstan-var array<int, array<T>> + */ + private array $list = []; + + /** + * @var \Traversable<mixed>|null + * @phpstan-var \Traversable<T>|null + */ + private ?\Traversable $optimized = null; + + /** + * @param mixed $item + * + * @phpstan-param T $item + */ + public function add($item, int $priority): void + { + $this->list[$priority][] = $item; + $this->optimized = null; + } + + /** + * @return \Traversable<int, mixed> + * + * @phpstan-return \Traversable<int, T> + */ + #[\ReturnTypeWillChange] + public function getIterator(): \Traversable + { + if ($this->optimized === null) { + \krsort($this->list); + + $sorted = []; + foreach ($this->list as $group) { + foreach ($group as $item) { + $sorted[] = $item; + } + } + + $this->optimized = new \ArrayIterator($sorted); + } + + return $this->optimized; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/RegexHelper.php b/php/libraries/composer/vendor/league/commonmark/src/Util/RegexHelper.php new file mode 100644 index 0000000..7144332 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/RegexHelper.php @@ -0,0 +1,237 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; + +/** + * Provides regular expressions and utilities for parsing Markdown + * + * All of the PARTIAL_ regex constants assume that they'll be used in case-insensitive searches + * All other complete regexes provided by this class (either via constants or methods) will have case-insensitivity enabled. + * + * @phpcs:disable Generic.Strings.UnnecessaryStringConcat.Found + * + * @psalm-immutable + */ +final class RegexHelper +{ + // Partial regular expressions (wrap with `/` on each side and add the case-insensitive `i` flag before use) + public const PARTIAL_ENTITY = '&(?:#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});'; + public const PARTIAL_ESCAPABLE = '[!"#$%&\'()*+,.\/:;<=>?@[\\\\\]^_`{|}~-]'; + public const PARTIAL_ESCAPED_CHAR = '\\\\' . self::PARTIAL_ESCAPABLE; + public const PARTIAL_IN_DOUBLE_QUOTES = '"(' . self::PARTIAL_ESCAPED_CHAR . '|[^"\x00])*"'; + public const PARTIAL_IN_SINGLE_QUOTES = '\'(' . self::PARTIAL_ESCAPED_CHAR . '|[^\'\x00])*\''; + public const PARTIAL_IN_PARENS = '\\((' . self::PARTIAL_ESCAPED_CHAR . '|[^)\x00])*\\)'; + public const PARTIAL_REG_CHAR = '[^\\\\()\x00-\x20]'; + public const PARTIAL_IN_PARENS_NOSP = '\((' . self::PARTIAL_REG_CHAR . '|' . self::PARTIAL_ESCAPED_CHAR . '|\\\\)*\)'; + public const PARTIAL_TAGNAME = '[a-z][a-z0-9-]*'; + public const PARTIAL_BLOCKTAGNAME = '(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)'; + public const PARTIAL_ATTRIBUTENAME = '[a-z_:][a-z0-9:._-]*'; + public const PARTIAL_UNQUOTEDVALUE = '[^"\'=<>`\x00-\x20]+'; + public const PARTIAL_SINGLEQUOTEDVALUE = '\'[^\']*\''; + public const PARTIAL_DOUBLEQUOTEDVALUE = '"[^"]*"'; + public const PARTIAL_ATTRIBUTEVALUE = '(?:' . self::PARTIAL_UNQUOTEDVALUE . '|' . self::PARTIAL_SINGLEQUOTEDVALUE . '|' . self::PARTIAL_DOUBLEQUOTEDVALUE . ')'; + public const PARTIAL_ATTRIBUTEVALUESPEC = '(?:' . '\s*=' . '\s*' . self::PARTIAL_ATTRIBUTEVALUE . ')'; + public const PARTIAL_ATTRIBUTE = '(?:' . '\s+' . self::PARTIAL_ATTRIBUTENAME . self::PARTIAL_ATTRIBUTEVALUESPEC . '?)'; + public const PARTIAL_OPENTAG = '<' . self::PARTIAL_TAGNAME . self::PARTIAL_ATTRIBUTE . '*' . '\s*\/?>'; + public const PARTIAL_CLOSETAG = '<\/' . self::PARTIAL_TAGNAME . '\s*[>]'; + public const PARTIAL_OPENBLOCKTAG = '<' . self::PARTIAL_BLOCKTAGNAME . self::PARTIAL_ATTRIBUTE . '*' . '\s*\/?>'; + public const PARTIAL_CLOSEBLOCKTAG = '<\/' . self::PARTIAL_BLOCKTAGNAME . '\s*[>]'; + public const PARTIAL_HTMLCOMMENT = '<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->'; + public const PARTIAL_PROCESSINGINSTRUCTION = '[<][?][\s\S]*?[?][>]'; + public const PARTIAL_DECLARATION = '<![A-Z]+' . '[^>]*>'; + public const PARTIAL_CDATA = '<!\[CDATA\[[\s\S]*?]\]>'; + public const PARTIAL_HTMLTAG = '(?:' . self::PARTIAL_OPENTAG . '|' . self::PARTIAL_CLOSETAG . '|' . self::PARTIAL_HTMLCOMMENT . '|' . + self::PARTIAL_PROCESSINGINSTRUCTION . '|' . self::PARTIAL_DECLARATION . '|' . self::PARTIAL_CDATA . ')'; + public const PARTIAL_HTMLBLOCKOPEN = '<(?:' . self::PARTIAL_BLOCKTAGNAME . '(?:[\s\/>]|$)' . '|' . + '\/' . self::PARTIAL_BLOCKTAGNAME . '(?:[\s>]|$)' . '|' . '[?!])'; + public const PARTIAL_LINK_TITLE = '^(?:"(' . self::PARTIAL_ESCAPED_CHAR . '|[^"\x00])*"' . + '|' . '\'(' . self::PARTIAL_ESCAPED_CHAR . '|[^\'\x00])*\'' . + '|' . '\((' . self::PARTIAL_ESCAPED_CHAR . '|[^()\x00])*\))'; + + public const REGEX_PUNCTUATION = '/^[\x{2000}-\x{206F}\x{2E00}-\x{2E7F}\p{Pc}\p{Pd}\p{Pe}\p{Pf}\p{Pi}\p{Po}\p{Ps}\\\\\'!"#\$%&\(\)\*\+,\-\.\\/:;<=>\?@\[\]\^_`\{\|\}~]/u'; + public const REGEX_UNSAFE_PROTOCOL = '/^javascript:|vbscript:|file:|data:/i'; + public const REGEX_SAFE_DATA_PROTOCOL = '/^data:image\/(?:png|gif|jpeg|webp)/i'; + public const REGEX_NON_SPACE = '/[^ \t\f\v\r\n]/'; + + public const REGEX_WHITESPACE_CHAR = '/^[ \t\n\x0b\x0c\x0d]/'; + public const REGEX_UNICODE_WHITESPACE_CHAR = '/^\pZ|\s/u'; + public const REGEX_THEMATIC_BREAK = '/^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$|^(?:-[ \t]*){3,}$/'; + public const REGEX_LINK_DESTINATION_BRACES = '/^(?:<(?:[^<>\\n\\\\\\x00]|\\\\.)*>)/'; + + /** + * @psalm-pure + */ + public static function isEscapable(string $character): bool + { + return \preg_match('/' . self::PARTIAL_ESCAPABLE . '/', $character) === 1; + } + + /** + * @psalm-pure + */ + public static function isLetter(?string $character): bool + { + if ($character === null) { + return false; + } + + return \preg_match('/[\pL]/u', $character) === 1; + } + + /** + * Attempt to match a regex in string s at offset offset + * + * @psalm-param non-empty-string $regex + * + * @return int|null Index of match, or null + * + * @psalm-pure + */ + public static function matchAt(string $regex, string $string, int $offset = 0): ?int + { + $matches = []; + $string = \mb_substr($string, $offset, null, 'UTF-8'); + if (! \preg_match($regex, $string, $matches, \PREG_OFFSET_CAPTURE)) { + return null; + } + + // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying + $charPos = \mb_strlen(\mb_strcut($string, 0, $matches[0][1], 'UTF-8'), 'UTF-8'); + + return $offset + $charPos; + } + + /** + * Functional wrapper around preg_match_all which only returns the first set of matches + * + * @psalm-param non-empty-string $pattern + * + * @return string[]|null + * + * @psalm-pure + */ + public static function matchFirst(string $pattern, string $subject, int $offset = 0): ?array + { + if ($offset !== 0) { + $subject = \substr($subject, $offset); + } + + \preg_match_all($pattern, $subject, $matches, \PREG_SET_ORDER); + + if ($matches === []) { + return null; + } + + return $matches[0] ?: null; + } + + /** + * Replace backslash escapes with literal characters + * + * @psalm-pure + */ + public static function unescape(string $string): string + { + $allEscapedChar = '/\\\\(' . self::PARTIAL_ESCAPABLE . ')/'; + + $escaped = \preg_replace($allEscapedChar, '$1', $string); + \assert(\is_string($escaped)); + + return \preg_replace_callback('/' . self::PARTIAL_ENTITY . '/i', static fn ($e) => Html5EntityDecoder::decode($e[0]), $escaped); + } + + /** + * @internal + * + * @param int $type HTML block type + * + * @psalm-param HtmlBlock::TYPE_* $type + * + * @phpstan-param HtmlBlock::TYPE_* $type + * + * @psalm-return non-empty-string + * + * @throws InvalidArgumentException if an invalid type is given + * + * @psalm-pure + */ + public static function getHtmlBlockOpenRegex(int $type): string + { + switch ($type) { + case HtmlBlock::TYPE_1_CODE_CONTAINER: + return '/^<(?:script|pre|textarea|style)(?:\s|>|$)/i'; + case HtmlBlock::TYPE_2_COMMENT: + return '/^<!--/'; + case HtmlBlock::TYPE_3: + return '/^<[?]/'; + case HtmlBlock::TYPE_4: + return '/^<![A-Z]/i'; + case HtmlBlock::TYPE_5_CDATA: + return '/^<!\[CDATA\[/i'; + case HtmlBlock::TYPE_6_BLOCK_ELEMENT: + return '%^<[/]?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|[/]?[>]|$)%i'; + case HtmlBlock::TYPE_7_MISC_ELEMENT: + return '/^(?:' . self::PARTIAL_OPENTAG . '|' . self::PARTIAL_CLOSETAG . ')\\s*$/i'; + default: + throw new InvalidArgumentException('Invalid HTML block type'); + } + } + + /** + * @internal + * + * @param int $type HTML block type + * + * @psalm-param HtmlBlock::TYPE_* $type + * + * @phpstan-param HtmlBlock::TYPE_* $type + * + * @psalm-return non-empty-string + * + * @throws InvalidArgumentException if an invalid type is given + * + * @psalm-pure + */ + public static function getHtmlBlockCloseRegex(int $type): string + { + switch ($type) { + case HtmlBlock::TYPE_1_CODE_CONTAINER: + return '%<\/(?:script|pre|textarea|style)>%i'; + case HtmlBlock::TYPE_2_COMMENT: + return '/-->/'; + case HtmlBlock::TYPE_3: + return '/\?>/'; + case HtmlBlock::TYPE_4: + return '/>/'; + case HtmlBlock::TYPE_5_CDATA: + return '/\]\]>/'; + default: + throw new InvalidArgumentException('Invalid HTML block type'); + } + } + + /** + * @psalm-pure + */ + public static function isLinkPotentiallyUnsafe(string $url): bool + { + return \preg_match(self::REGEX_UNSAFE_PROTOCOL, $url) !== 0 && \preg_match(self::REGEX_SAFE_DATA_PROTOCOL, $url) === 0; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/SpecReader.php b/php/libraries/composer/vendor/league/commonmark/src/Util/SpecReader.php new file mode 100644 index 0000000..7523304 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/SpecReader.php @@ -0,0 +1,71 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\IOException; + +/** + * Reads in a CommonMark spec document and extracts the input/output examples for testing against them + */ +final class SpecReader +{ + private function __construct() + { + } + + /** + * @return iterable<string, array{input: string, output: string, type: string, section: string, number: int}> + */ + public static function read(string $data): iterable + { + // Normalize newlines for platform independence + $data = \preg_replace('/\r\n?/', "\n", $data); + \assert($data !== null); + $data = \preg_replace('/<!-- END TESTS -->.*$/', '', $data); + \assert($data !== null); + \preg_match_all('/^`{32} (example ?\w*)\n([\s\S]*?)^\.\n([\s\S]*?)^`{32}$|^#{1,6} *(.*)$/m', $data, $matches, PREG_SET_ORDER); + + $currentSection = 'Example'; + $exampleNumber = 0; + + foreach ($matches as $match) { + if (isset($match[4])) { + $currentSection = $match[4]; + continue; + } + + yield \trim($currentSection . ' #' . $exampleNumber) => [ + 'input' => \str_replace('→', "\t", $match[2]), + 'output' => \str_replace('→', "\t", $match[3]), + 'type' => $match[1], + 'section' => $currentSection, + 'number' => $exampleNumber++, + ]; + } + } + + /** + * @return iterable<string, array{input: string, output: string, type: string, section: string, number: int}> + * + * @throws IOException if the file cannot be loaded + */ + public static function readFile(string $filename): iterable + { + if (($data = \file_get_contents($filename)) === false) { + throw new IOException(\sprintf('Failed to load spec from %s', $filename)); + } + + return self::read($data); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/UrlEncoder.php b/php/libraries/composer/vendor/league/commonmark/src/Util/UrlEncoder.php new file mode 100644 index 0000000..bba1af3 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/UrlEncoder.php @@ -0,0 +1,69 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\UnexpectedEncodingException; + +/** + * @psalm-immutable + */ +final class UrlEncoder +{ + private const ENCODE_CACHE = ['%00', '%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08', '%09', '%0A', '%0B', '%0C', '%0D', '%0E', '%0F', '%10', '%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18', '%19', '%1A', '%1B', '%1C', '%1D', '%1E', '%1F', '%20', '!', '%22', '#', '$', '%25', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '%3C', '=', '%3E', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '%5B', '%5C', '%5D', '%5E', '_', '%60', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '%7B', '%7C', '%7D', '~', '%7F']; + + /** + * @throws UnexpectedEncodingException if a non-UTF-8-compatible encoding is used + * + * @psalm-pure + */ + public static function unescapeAndEncode(string $uri): string + { + // Optimization: if the URL only includes characters we know will be kept as-is, then just return the URL as-is. + if (\preg_match('/^[A-Za-z0-9~!@#$&*()\-_=+;:,.\/?]+$/', $uri)) { + return $uri; + } + + if (! \mb_check_encoding($uri, 'UTF-8')) { + throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected'); + } + + $result = ''; + + $chars = \mb_str_split($uri, 1, 'UTF-8'); + + $l = \count($chars); + for ($i = 0; $i < $l; $i++) { + $code = $chars[$i]; + if ($code === '%' && $i + 2 < $l) { + if (\preg_match('/^[0-9a-f]{2}$/i', $chars[$i + 1] . $chars[$i + 2]) === 1) { + $result .= '%' . $chars[$i + 1] . $chars[$i + 2]; + $i += 2; + continue; + } + } + + if (\ord($code) < 128) { + $result .= self::ENCODE_CACHE[\ord($code)]; + continue; + } + + $result .= \rawurlencode($code); + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Util/Xml.php b/php/libraries/composer/vendor/league/commonmark/src/Util/Xml.php new file mode 100644 index 0000000..8f9e84d --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Util/Xml.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * Utility class for handling/generating XML and HTML + * + * @psalm-immutable + */ +final class Xml +{ + /** + * @psalm-pure + */ + public static function escape(string $string): string + { + return \str_replace(['&', '<', '>', '"'], ['&', '<', '>', '"'], $string); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php new file mode 100644 index 0000000..48aa3c8 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php @@ -0,0 +1,85 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Xml; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class FallbackNodeXmlRenderer implements XmlNodeRendererInterface +{ + /** + * @var array<string, string> + * + * @psalm-allow-private-mutation + */ + private array $classCache = []; + + /** + * @psalm-allow-private-mutation + */ + public function getXmlTagName(Node $node): string + { + $className = \get_class($node); + if (isset($this->classCache[$className])) { + return $this->classCache[$className]; + } + + $type = $node instanceof AbstractBlock ? 'block' : 'inline'; + $shortName = \strtolower((new \ReflectionClass($node))->getShortName()); + + return $this->classCache[$className] = \sprintf('custom_%s_%s', $type, $shortName); + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + $attrs = []; + foreach ($node->data->export() as $k => $v) { + if (self::isValueUsable($v)) { + $attrs[$k] = $v; + } + } + + $reflClass = new \ReflectionClass($node); + foreach ($reflClass->getProperties() as $property) { + if (\in_array($property->getDeclaringClass()->getName(), [Node::class, AbstractBlock::class, AbstractInline::class], true)) { + continue; + } + + $property->setAccessible(true); + $value = $property->getValue($node); + if (self::isValueUsable($value)) { + $attrs[$property->getName()] = $value; + } + } + + return $attrs; + } + + /** + * @param mixed $var + * + * @psalm-pure + */ + private static function isValueUsable($var): bool + { + return \is_string($var) || \is_int($var) || \is_float($var) || \is_bool($var); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php b/php/libraries/composer/vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php new file mode 100644 index 0000000..538ad98 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php @@ -0,0 +1,59 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Xml; + +use League\CommonMark\ConverterInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; +use League\CommonMark\Parser\MarkdownParser; +use League\CommonMark\Parser\MarkdownParserInterface; +use League\CommonMark\Renderer\DocumentRendererInterface; + +final class MarkdownToXmlConverter implements ConverterInterface +{ + /** @psalm-readonly */ + private MarkdownParserInterface $parser; + + /** @psalm-readonly */ + private DocumentRendererInterface $renderer; + + public function __construct(EnvironmentInterface $environment) + { + $this->parser = new MarkdownParser($environment); + $this->renderer = new XmlRenderer($environment); + } + + /** + * Converts Markdown to XML + * + * @throws CommonMarkException + */ + public function convert(string $input): RenderedContentInterface + { + return $this->renderer->renderDocument($this->parser->parse($input)); + } + + /** + * Converts CommonMark to HTML. + * + * @see MarkdownToXmlConverter::convert() + * + * @throws CommonMarkException + */ + public function __invoke(string $input): RenderedContentInterface + { + return $this->convert($input); + } +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php b/php/libraries/composer/vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php new file mode 100644 index 0000000..aafc9f1 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php @@ -0,0 +1,28 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Xml; + +use League\CommonMark\Node\Node; + +interface XmlNodeRendererInterface +{ + public function getXmlTagName(Node $node): string; + + /** + * @return array<string, string|int|float|bool> + * + * @psalm-return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array; +} diff --git a/php/libraries/composer/vendor/league/commonmark/src/Xml/XmlRenderer.php b/php/libraries/composer/vendor/league/commonmark/src/Xml/XmlRenderer.php new file mode 100644 index 0000000..2973dd7 --- /dev/null +++ b/php/libraries/composer/vendor/league/commonmark/src/Xml/XmlRenderer.php @@ -0,0 +1,135 @@ +<?php + +declare(strict_types=1); + +namespace League\CommonMark\Xml; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Node\StringContainerInterface; +use League\CommonMark\Output\RenderedContent; +use League\CommonMark\Output\RenderedContentInterface; +use League\CommonMark\Renderer\DocumentRendererInterface; +use League\CommonMark\Util\Xml; + +final class XmlRenderer implements DocumentRendererInterface +{ + private const INDENTATION = ' '; + + private EnvironmentInterface $environment; + + private XmlNodeRendererInterface $fallbackRenderer; + + /** @var array<class-string, XmlNodeRendererInterface> */ + private array $rendererCache = []; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + $this->fallbackRenderer = new FallbackNodeXmlRenderer(); + } + + public function renderDocument(Document $document): RenderedContentInterface + { + $this->environment->dispatch(new DocumentPreRenderEvent($document, 'xml')); + + $xml = '<?xml version="1.0" encoding="UTF-8"?>'; + + $indent = 0; + $walker = $document->walker(); + while ($event = $walker->next()) { + $node = $event->getNode(); + + $closeImmediately = ! $node->hasChildren(); + $selfClosing = $closeImmediately && ! $node instanceof StringContainerInterface; + + $renderer = $this->findXmlRenderer($node); + $tagName = $renderer->getXmlTagName($node); + + if ($event->isEntering()) { + $attrs = $renderer->getXmlAttributes($node); + + $xml .= "\n" . \str_repeat(self::INDENTATION, $indent); + $xml .= self::tag($tagName, $attrs, $selfClosing); + + if ($node instanceof StringContainerInterface) { + $xml .= Xml::escape($node->getLiteral()); + } + + if ($closeImmediately && ! $selfClosing) { + $xml .= self::tag('/' . $tagName); + } + + if (! $closeImmediately) { + $indent++; + } + } elseif (! $closeImmediately) { + $indent--; + $xml .= "\n" . \str_repeat(self::INDENTATION, $indent); + $xml .= self::tag('/' . $tagName); + } + } + + return new RenderedContent($document, $xml . "\n"); + } + + /** + * @param array<string, string|int|float|bool> $attrs + */ + private static function tag(string $name, array $attrs = [], bool $selfClosing = \false): string + { + $result = '<' . $name; + foreach ($attrs as $key => $value) { + $result .= \sprintf(' %s="%s"', $key, self::convertAndEscape($value)); + } + + if ($selfClosing) { + $result .= ' /'; + } + + $result .= '>'; + + return $result; + } + + /** + * @param string|int|float|bool $value + */ + private static function convertAndEscape($value): string + { + if (\is_string($value)) { + return Xml::escape($value); + } + + if (\is_int($value) || \is_float($value)) { + return (string) $value; + } + + if (\is_bool($value)) { + return $value ? 'true' : 'false'; + } + + // @phpstan-ignore-next-line + throw new InvalidArgumentException('$value must be a string, int, float, or bool'); + } + + private function findXmlRenderer(Node $node): XmlNodeRendererInterface + { + $class = \get_class($node); + + if (\array_key_exists($class, $this->rendererCache)) { + return $this->rendererCache[$class]; + } + + foreach ($this->environment->getRenderersForClass($class) as $renderer) { + if ($renderer instanceof XmlNodeRendererInterface) { + return $this->rendererCache[$class] = $renderer; + } + } + + return $this->rendererCache[$class] = $this->fallbackRenderer; + } +} diff --git a/php/libraries/composer/vendor/league/config/CHANGELOG.md b/php/libraries/composer/vendor/league/config/CHANGELOG.md new file mode 100644 index 0000000..9a7813a --- /dev/null +++ b/php/libraries/composer/vendor/league/config/CHANGELOG.md @@ -0,0 +1,42 @@ +# Change Log +All notable changes to this project will be documented in this file. +Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) principles. + +## [Unreleased][unreleased] + +## [1.2.0] - 2022-12-11 + +### Changed + +- Values can now be set prior to the corresponding schema being registered. +- `exists()` and `get()` now only trigger validation for the relevant schema, not the entire config at once. + +## [1.1.1] - 2021-08-14 + +### Changed + + - Bumped the minimum version of dflydev/dot-access-data for PHP 8.1 support + +## [1.1.0] - 2021-06-19 + +### Changed + +- Bumped the minimum PHP version to 7.4+ +- Bumped the minimum version of nette/schema to 1.2.0 + +## [1.0.1] - 2021-05-31 + +### Fixed + +- Fixed the `ConfigurationExceptionInterface` marker interface not extending `Throwable` (#2) + +## [1.0.0] - 2021-05-31 + +Initial release! 🎉 + +[unreleased]: https://github.com/thephpleague/config/compare/v1.2.0...main +[1.2.0]: https://github.com/thephpleague/config/compare/v1.1.1...v.1.2.0 +[1.1.1]: https://github.com/thephpleague/config/compare/v1.1.0...v1.1.1 +[1.1.0]: https://github.com/thephpleague/config/compare/v1.0.1...v1.1.0 +[1.0.1]: https://github.com/thephpleague/config/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/thephpleague/config/releases/tag/v1.0.0 diff --git a/php/libraries/composer/vendor/league/config/LICENSE.md b/php/libraries/composer/vendor/league/config/LICENSE.md new file mode 100644 index 0000000..1a444a1 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/LICENSE.md @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2022, Colin O'Dell. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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/php/libraries/composer/vendor/league/config/README.md b/php/libraries/composer/vendor/league/config/README.md new file mode 100644 index 0000000..2304746 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/README.md @@ -0,0 +1,153 @@ +# league/config + +[![Latest Version](https://img.shields.io/packagist/v/league/config.svg?style=flat-square)](https://packagist.org/packages/league/config) +[![Total Downloads](https://img.shields.io/packagist/dt/league/config.svg?style=flat-square)](https://packagist.org/packages/league/config) +[![Software License](https://img.shields.io/badge/License-BSD--3-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/github/workflow/status/thephpleague/config/Tests/main.svg?style=flat-square)](https://github.com/thephpleague/config/actions?query=workflow%3ATests+branch%3Amain) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/config.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/config/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/config.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/config) +[![Sponsor development of this project](https://img.shields.io/badge/sponsor%20this%20package-%E2%9D%A4-ff69b4.svg?style=flat-square)](https://www.colinodell.com/sponsor) + +**league/config** helps you define nested configuration arrays with strict schemas and access configuration values with dot notation. It was created by [Colin O'Dell][@colinodell]. + +## 📦 Installation + +This project requires PHP 7.4 or higher. To install it via [Composer] simply run: + +```bash +composer require league/config +``` + +## 🧰️ Basic Usage + +The `Configuration` class provides everything you need to define the configuration structure and fetch values: + +```php +use League\Config\Configuration; +use Nette\Schema\Expect; + +// Define your configuration schema +$config = new Configuration([ + 'database' => Expect::structure([ + 'driver' => Expect::anyOf('mysql', 'postgresql', 'sqlite')->required(), + 'host' => Expect::string()->default('localhost'), + 'port' => Expect::int()->min(1)->max(65535), + 'ssl' => Expect::bool(), + 'database' => Expect::string()->required(), + 'username' => Expect::string()->required(), + 'password' => Expect::string()->nullable(), + ]), + 'logging' => Expect::structure([ + 'enabled' => Expect::bool()->default($_ENV['DEBUG'] == true), + 'file' => Expect::string()->deprecated("use logging.path instead"), + 'path' => Expect::string()->assert(function ($path) { return \is_writeable($path); })->required(), + ]), +]); + +// Set the values, either all at once with `merge()`: +$config->merge([ + 'database' => [ + 'driver' => 'mysql', + 'port' => 3306, + 'database' => 'mydb', + 'username' => 'user', + 'password' => 'secret', + ], +]); + +// Or one-at-a-time with `set()`: +$config->set('logging.path', '/var/log/myapp.log'); + +// You can now retrieve those values with `get()`. +// Validation and defaults will be applied for you automatically +$config->get('database'); // Fetches the entire "database" section as an array +$config->get('database.driver'); // Fetch a specific nested value with dot notation +$config->get('database/driver'); // Fetch a specific nested value with slash notation +$config->get('database.host'); // Returns the default value "localhost" +$config->get('logging.path'); // Guaranteed to be writeable thanks to the assertion in the schema + +// If validation fails an `InvalidConfigurationException` will be thrown: +$config->set('database.driver', 'mongodb'); +$config->get('database.driver'); // InvalidConfigurationException + +// Attempting to fetch a non-existent key will result in an `InvalidConfigurationException` +$config->get('foo.bar'); + +// You could avoid this by checking whether that item exists: +$config->exists('foo.bar'); // Returns `false` +``` + +## 📓 Documentation + +Full documentation can be found at [config.thephpleague.com][docs]. + +## 💭 Philosophy + +This library aims to provide a **simple yet opinionated** approach to configuration with the following goals: + +- The configuration should operate on **arrays with nested values** which are easily accessible +- The configuration structure should be **defined with strict schemas** defining the overall structure, allowed types, and allowed values +- Schemas should be defined using a **simple, fluent interface** +- You should be able to **add and combine schemas but never modify existing ones** +- Both the configuration values and the schema should be **defined and managed with PHP code** +- Schemas should be **immutable**; they should never change once they are set +- Configuration values should never define or influence the schemas + +As a result, this library will likely **never** support features like: + +- Loading and/or exporting configuration values or schemas using YAML, XML, or other files +- Parsing configuration values from a command line or other user interface +- Dynamically changing the schema, allowed values, or default values based on other configuration values + +If you need that functionality you should check out other libraries like: + +- [symfony/config] +- [symfony/options-resolver] +- [hassankhan/config] +- [consolidation/config] +- [laminas/laminas-config] + +## 🏷️ Versioning + +[SemVer](http://semver.org/) is followed closely. Minor and patch releases should not introduce breaking changes to the codebase. + +Any classes or methods marked `@internal` are not intended for use outside this library and are subject to breaking changes at any time, so please avoid using them. + +## 🛠️ Maintenance & Support + +When a new **minor** version (e.g. `1.0` -> `1.1`) is released, the previous one (`1.0`) will continue to receive security and critical bug fixes for *at least* 3 months. + +When a new **major** version is released (e.g. `1.1` -> `2.0`), the previous one (`1.1`) will receive critical bug fixes for *at least* 3 months and security updates for 6 months after that new release comes out. + +(This policy may change in the future and exceptions may be made on a case-by-case basis.) + +## 👷‍️ Contributing + +Contributions to this library are **welcome**! We only ask that you adhere to our [contributor guidelines] and avoid making changes that conflict with our Philosophy above. + +## 🧪 Testing + +```bash +composer test +``` + +## 📄 License + +**league/config** is licensed under the BSD-3 license. See the [`LICENSE.md`][license] file for more details. + +## 🗺️ Who Uses It? + +This project is used by [league/commonmark][league-commonmark]. + +[docs]: https://config.thephpleague.com/ +[@colinodell]: https://www.twitter.com/colinodell +[Composer]: https://getcomposer.org/ +[PHP League]: https://thephpleague.com +[symfony/config]: https://symfony.com/doc/current/components/config.html +[symfony/options-resolver]: https://symfony.com/doc/current/components/options_resolver.html +[hassankhan/config]: https://github.com/hassankhan/config +[consolidation/config]: https://github.com/consolidation/config +[laminas/laminas-config]: https://docs.laminas.dev/laminas-config/ +[contributor guidelines]: https://github.com/thephpleague/config/blob/main/.github/CONTRIBUTING.md +[license]: https://github.com/thephpleague/config/blob/main/LICENSE.md +[league-commonmark]: https://commonmark.thephpleague.com diff --git a/php/libraries/composer/vendor/league/config/composer.json b/php/libraries/composer/vendor/league/config/composer.json new file mode 100644 index 0000000..3cd8d87 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/composer.json @@ -0,0 +1,69 @@ +{ + "name": "league/config", + "type": "library", + "description": "Define configuration arrays with strict schemas and access values with dot notation", + "keywords": ["configuration","config","schema","array","nested","dot","dot-access"], + "homepage": "https://config.thephpleague.com", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "support": { + "docs": "https://config.thephpleague.com/", + "issues": "https://github.com/thephpleague/config/issues", + "rss": "https://github.com/thephpleague/config/releases.atom", + "source": "https://github.com/thephpleague/config" + }, + "require": { + "php": "^7.4 || ^8.0", + "dflydev/dot-access-data": "^3.0.1", + "nette/schema": "^1.2" + }, + "require-dev": { + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "minimum-stability": "dev", + "prefer-stable": true, + "autoload": { + "psr-4": { + "League\\Config\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "League\\Config\\Tests\\": "tests" + } + }, + "scripts": { + "phpcs": "phpcs", + "phpstan": "phpstan analyse", + "phpunit": "phpunit --no-coverage", + "psalm": "psalm", + "test": [ + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + } + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/php/libraries/composer/vendor/league/config/src/Configuration.php b/php/libraries/composer/vendor/league/config/src/Configuration.php new file mode 100644 index 0000000..6294367 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/Configuration.php @@ -0,0 +1,255 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use Dflydev\DotAccessData\Data; +use Dflydev\DotAccessData\DataInterface; +use Dflydev\DotAccessData\Exception\DataException; +use Dflydev\DotAccessData\Exception\InvalidPathException; +use Dflydev\DotAccessData\Exception\MissingPathException; +use League\Config\Exception\UnknownOptionException; +use League\Config\Exception\ValidationException; +use Nette\Schema\Expect; +use Nette\Schema\Processor; +use Nette\Schema\Schema; +use Nette\Schema\ValidationException as NetteValidationException; + +final class Configuration implements ConfigurationBuilderInterface, ConfigurationInterface +{ + /** @psalm-readonly */ + private Data $userConfig; + + /** + * @var array<string, Schema> + * + * @psalm-allow-private-mutation + */ + private array $configSchemas = []; + + /** @psalm-allow-private-mutation */ + private Data $finalConfig; + + /** + * @var array<string, mixed> + * + * @psalm-allow-private-mutation + */ + private array $cache = []; + + /** @psalm-readonly */ + private ConfigurationInterface $reader; + + /** + * @param array<string, Schema> $baseSchemas + */ + public function __construct(array $baseSchemas = []) + { + $this->configSchemas = $baseSchemas; + $this->userConfig = new Data(); + $this->finalConfig = new Data(); + + $this->reader = new ReadOnlyConfiguration($this); + } + + /** + * Registers a new configuration schema at the given top-level key + * + * @psalm-allow-private-mutation + */ + public function addSchema(string $key, Schema $schema): void + { + $this->invalidate(); + + $this->configSchemas[$key] = $schema; + } + + /** + * {@inheritDoc} + * + * @psalm-allow-private-mutation + */ + public function merge(array $config = []): void + { + $this->invalidate(); + + $this->userConfig->import($config, DataInterface::REPLACE); + } + + /** + * {@inheritDoc} + * + * @psalm-allow-private-mutation + */ + public function set(string $key, $value): void + { + $this->invalidate(); + + try { + $this->userConfig->set($key, $value); + } catch (DataException $ex) { + throw new UnknownOptionException($ex->getMessage(), $key, (int) $ex->getCode(), $ex); + } + } + + /** + * {@inheritDoc} + * + * @psalm-external-mutation-free + */ + public function get(string $key) + { + if (\array_key_exists($key, $this->cache)) { + return $this->cache[$key]; + } + + try { + $this->build(self::getTopLevelKey($key)); + + return $this->cache[$key] = $this->finalConfig->get($key); + } catch (InvalidPathException | MissingPathException $ex) { + throw new UnknownOptionException($ex->getMessage(), $key, (int) $ex->getCode(), $ex); + } + } + + /** + * {@inheritDoc} + * + * @psalm-external-mutation-free + */ + public function exists(string $key): bool + { + if (\array_key_exists($key, $this->cache)) { + return true; + } + + try { + $this->build(self::getTopLevelKey($key)); + + return $this->finalConfig->has($key); + } catch (InvalidPathException | UnknownOptionException $ex) { + return false; + } + } + + /** + * @psalm-mutation-free + */ + public function reader(): ConfigurationInterface + { + return $this->reader; + } + + /** + * @psalm-external-mutation-free + */ + private function invalidate(): void + { + $this->cache = []; + $this->finalConfig = new Data(); + } + + /** + * Applies the schema against the configuration to return the final configuration + * + * @throws ValidationException|UnknownOptionException|InvalidPathException + * + * @psalm-allow-private-mutation + */ + private function build(string $topLevelKey): void + { + if ($this->finalConfig->has($topLevelKey)) { + return; + } + + if (! isset($this->configSchemas[$topLevelKey])) { + throw new UnknownOptionException(\sprintf('Missing config schema for "%s"', $topLevelKey), $topLevelKey); + } + + try { + $userData = [$topLevelKey => $this->userConfig->get($topLevelKey)]; + } catch (DataException $ex) { + $userData = []; + } + + try { + $schema = $this->configSchemas[$topLevelKey]; + $processor = new Processor(); + + $processed = $processor->process(Expect::structure([$topLevelKey => $schema]), $userData); + + $this->raiseAnyDeprecationNotices($processor->getWarnings()); + + $this->finalConfig->import((array) self::convertStdClassesToArrays($processed)); + } catch (NetteValidationException $ex) { + throw new ValidationException($ex); + } + } + + /** + * Recursively converts stdClass instances to arrays + * + * @phpstan-template T + * + * @param T $data + * + * @return mixed + * + * @phpstan-return ($data is \stdClass ? array<string, mixed> : T) + * + * @psalm-pure + */ + private static function convertStdClassesToArrays($data) + { + if ($data instanceof \stdClass) { + $data = (array) $data; + } + + if (\is_array($data)) { + foreach ($data as $k => $v) { + $data[$k] = self::convertStdClassesToArrays($v); + } + } + + return $data; + } + + /** + * @param string[] $warnings + */ + private function raiseAnyDeprecationNotices(array $warnings): void + { + foreach ($warnings as $warning) { + @\trigger_error($warning, \E_USER_DEPRECATED); + } + } + + /** + * @throws InvalidPathException + */ + private static function getTopLevelKey(string $path): string + { + if (\strlen($path) === 0) { + throw new InvalidPathException('Path cannot be an empty string'); + } + + $path = \str_replace(['.', '/'], '.', $path); + + $firstDelimiter = \strpos($path, '.'); + if ($firstDelimiter === false) { + return $path; + } + + return \substr($path, 0, $firstDelimiter); + } +} diff --git a/php/libraries/composer/vendor/league/config/src/ConfigurationAwareInterface.php b/php/libraries/composer/vendor/league/config/src/ConfigurationAwareInterface.php new file mode 100644 index 0000000..ec5d7b3 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/ConfigurationAwareInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * Implement this class to facilitate setter injection of the configuration where needed + */ +interface ConfigurationAwareInterface +{ + public function setConfiguration(ConfigurationInterface $configuration): void; +} diff --git a/php/libraries/composer/vendor/league/config/src/ConfigurationBuilderInterface.php b/php/libraries/composer/vendor/league/config/src/ConfigurationBuilderInterface.php new file mode 100644 index 0000000..e9c5ed6 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/ConfigurationBuilderInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * An interface that provides the ability to set both the schema and configuration values + */ +interface ConfigurationBuilderInterface extends MutableConfigurationInterface, SchemaBuilderInterface +{ +} diff --git a/php/libraries/composer/vendor/league/config/src/ConfigurationInterface.php b/php/libraries/composer/vendor/league/config/src/ConfigurationInterface.php new file mode 100644 index 0000000..534bd9f --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/ConfigurationInterface.php @@ -0,0 +1,46 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use League\Config\Exception\UnknownOptionException; +use League\Config\Exception\ValidationException; + +/** + * Interface for reading configuration values + */ +interface ConfigurationInterface +{ + /** + * @param string $key Configuration option path/key + * + * @psalm-param non-empty-string $key + * + * @return mixed + * + * @throws ValidationException if the schema failed to validate the given input + * @throws UnknownOptionException if the requested key does not exist or is malformed + */ + public function get(string $key); + + /** + * @param string $key Configuration option path/key + * + * @psalm-param non-empty-string $key + * + * @return bool Whether the given option exists + * + * @throws ValidationException if the schema failed to validate the given input + */ + public function exists(string $key): bool; +} diff --git a/php/libraries/composer/vendor/league/config/src/ConfigurationProviderInterface.php b/php/libraries/composer/vendor/league/config/src/ConfigurationProviderInterface.php new file mode 100644 index 0000000..7af6148 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/ConfigurationProviderInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * Interface for a service which provides a readable configuration object + */ +interface ConfigurationProviderInterface +{ + public function getConfiguration(): ConfigurationInterface; +} diff --git a/php/libraries/composer/vendor/league/config/src/Exception/ConfigurationExceptionInterface.php b/php/libraries/composer/vendor/league/config/src/Exception/ConfigurationExceptionInterface.php new file mode 100644 index 0000000..db9ee78 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/Exception/ConfigurationExceptionInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +/** + * Marker interface for any/all exceptions thrown by this library + */ +interface ConfigurationExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/league/config/src/Exception/InvalidConfigurationException.php b/php/libraries/composer/vendor/league/config/src/Exception/InvalidConfigurationException.php new file mode 100644 index 0000000..f2a6b69 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/Exception/InvalidConfigurationException.php @@ -0,0 +1,46 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +class InvalidConfigurationException extends \UnexpectedValueException implements ConfigurationExceptionInterface +{ + /** + * @param string $option Name/path of the option + * @param mixed $valueGiven The invalid option that was provided + * @param ?string $description Additional text describing the issue (optional) + */ + public static function forConfigOption(string $option, $valueGiven, ?string $description = null): self + { + $message = \sprintf('Invalid config option for "%s": %s', $option, self::getDebugValue($valueGiven)); + if ($description !== null) { + $message .= \sprintf(' (%s)', $description); + } + + return new self($message); + } + + /** + * @param mixed $value + * + * @psalm-pure + */ + private static function getDebugValue($value): string + { + if (\is_object($value)) { + return \get_class($value); + } + + return \print_r($value, true); + } +} diff --git a/php/libraries/composer/vendor/league/config/src/Exception/UnknownOptionException.php b/php/libraries/composer/vendor/league/config/src/Exception/UnknownOptionException.php new file mode 100644 index 0000000..5afba12 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/Exception/UnknownOptionException.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +use Throwable; + +final class UnknownOptionException extends \InvalidArgumentException implements ConfigurationExceptionInterface +{ + private string $path; + + public function __construct(string $message, string $path, int $code = 0, ?Throwable $previous = null) + { + parent::__construct($message, $code, $previous); + + $this->path = $path; + } + + public function getPath(): string + { + return $this->path; + } +} diff --git a/php/libraries/composer/vendor/league/config/src/Exception/ValidationException.php b/php/libraries/composer/vendor/league/config/src/Exception/ValidationException.php new file mode 100644 index 0000000..b43e2f5 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/Exception/ValidationException.php @@ -0,0 +1,37 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +use Nette\Schema\ValidationException as NetteException; + +final class ValidationException extends InvalidConfigurationException +{ + /** @var string[] */ + private array $messages; + + public function __construct(NetteException $innerException) + { + parent::__construct($innerException->getMessage(), (int) $innerException->getCode(), $innerException); + + $this->messages = $innerException->getMessages(); + } + + /** + * @return string[] + */ + public function getMessages(): array + { + return $this->messages; + } +} diff --git a/php/libraries/composer/vendor/league/config/src/MutableConfigurationInterface.php b/php/libraries/composer/vendor/league/config/src/MutableConfigurationInterface.php new file mode 100644 index 0000000..2d4b2ee --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/MutableConfigurationInterface.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use League\Config\Exception\UnknownOptionException; + +/** + * Interface for setting/merging user-defined configuration values into the configuration object + */ +interface MutableConfigurationInterface +{ + /** + * @param mixed $value + * + * @throws UnknownOptionException if $key contains a nested path which doesn't point to an array value + */ + public function set(string $key, $value): void; + + /** + * @param array<string, mixed> $config + */ + public function merge(array $config = []): void; +} diff --git a/php/libraries/composer/vendor/league/config/src/ReadOnlyConfiguration.php b/php/libraries/composer/vendor/league/config/src/ReadOnlyConfiguration.php new file mode 100644 index 0000000..58e6171 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/ReadOnlyConfiguration.php @@ -0,0 +1,40 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * Provides read-only access to a given Configuration object + */ +final class ReadOnlyConfiguration implements ConfigurationInterface +{ + private Configuration $config; + + public function __construct(Configuration $config) + { + $this->config = $config; + } + + /** + * {@inheritDoc} + */ + public function get(string $key) + { + return $this->config->get($key); + } + + public function exists(string $key): bool + { + return $this->config->exists($key); + } +} diff --git a/php/libraries/composer/vendor/league/config/src/SchemaBuilderInterface.php b/php/libraries/composer/vendor/league/config/src/SchemaBuilderInterface.php new file mode 100644 index 0000000..3a19807 --- /dev/null +++ b/php/libraries/composer/vendor/league/config/src/SchemaBuilderInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use Nette\Schema\Schema; + +/** + * Interface that allows new schemas to be added to a configuration + */ +interface SchemaBuilderInterface +{ + /** + * Registers a new configuration schema at the given top-level key + */ + public function addSchema(string $key, Schema $schema): void; +} diff --git a/php/libraries/composer/vendor/league/flysystem/CODE_OF_CONDUCT.md b/php/libraries/composer/vendor/league/flysystem/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..89569c0 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at info+flysystem@frankdejonge.nl. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/php/libraries/composer/vendor/league/flysystem/LICENSE b/php/libraries/composer/vendor/league/flysystem/LICENSE new file mode 100644 index 0000000..f2684c8 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2019 Frank de Jonge + +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/php/libraries/composer/vendor/league/flysystem/SECURITY.md b/php/libraries/composer/vendor/league/flysystem/SECURITY.md new file mode 100644 index 0000000..f5b205e --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/SECURITY.md @@ -0,0 +1,16 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 1.0.x | :white_check_mark: | +| 2.0.x | :x: | + +## Reporting a Vulnerability + +When you've encountered a security vulnerability, please disclose it securely. + +The security process is described at: +[https://flysystem.thephpleague.com/docs/security/](https://flysystem.thephpleague.com/docs/security/) + diff --git a/php/libraries/composer/vendor/league/flysystem/composer.json b/php/libraries/composer/vendor/league/flysystem/composer.json new file mode 100644 index 0000000..bd7434a --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/composer.json @@ -0,0 +1,69 @@ +{ + "name": "league/flysystem", + "type": "library", + "description": "Filesystem abstraction: Many filesystems, one API.", + "keywords": [ + "filesystem", "filesystems", "files", "storage", "dropbox", "aws", + "abstraction", "s3", "ftp", "sftp", "remote", "webdav", + "file systems", "cloud", "cloud files", "rackspace", "copy.com" + ], + "funding": [ + { + "type": "other", + "url": "https://offset.earth/frankdejonge" + } + ], + "license": "MIT", + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frenky.net" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-fileinfo": "*", + "league/mime-type-detection": "^1.3" + }, + "require-dev": { + "phpspec/prophecy": "^1.11.1", + "phpunit/phpunit": "^8.5.8" + }, + "autoload": { + "psr-4": { + "League\\Flysystem\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\Flysystem\\Stub\\": "stub/" + } + }, + "suggest": { + "ext-fileinfo": "Required for MimeType", + "league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem", + "league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files", + "league/flysystem-azure": "Allows you to use Windows Azure Blob storage", + "league/flysystem-webdav": "Allows you to use WebDAV storage", + "league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2", + "league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3", + "spatie/flysystem-dropbox": "Allows you to use Dropbox storage", + "srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications", + "league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching", + "ext-ftp": "Allows you to use FTP server storage", + "ext-openssl": "Allows you to use FTPS server storage", + "league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib", + "league/flysystem-ziparchive": "Allows you to use ZipArchive adapter" + }, + "conflict": { + "league/flysystem-sftp": "<1.0.6" + }, + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "scripts": { + "phpstan": "php phpstan.php" + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/deprecations.md b/php/libraries/composer/vendor/league/flysystem/deprecations.md new file mode 100644 index 0000000..c336a42 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/deprecations.md @@ -0,0 +1,19 @@ +# Deprecations + +This document lists all the planned deprecations. + +## Handlers will be removed in 2.0 + +The `Handler` type and associated calls will be removed in version 2.0. + +### Upgrade path + +You should create your own implementation for handling OOP usage, +but it's recommended to move away from using an OOP-style wrapper entirely. + +The reason for this is that it's too easy for implementation details (for +your application this is Flysystem) to leak into the application. The most +important part for Flysystem is that it improves portability and creates a +solid boundary between your application core and the infrastructure you use. +The OOP-style handling breaks this principle, therefore I want to stop +promoting it. diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/AbstractAdapter.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/AbstractAdapter.php new file mode 100644 index 0000000..e577ac4 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/AbstractAdapter.php @@ -0,0 +1,72 @@ +<?php + +namespace League\Flysystem\Adapter; + +use League\Flysystem\AdapterInterface; + +abstract class AbstractAdapter implements AdapterInterface +{ + /** + * @var string|null path prefix + */ + protected $pathPrefix; + + /** + * @var string + */ + protected $pathSeparator = '/'; + + /** + * Set the path prefix. + * + * @param string $prefix + * + * @return void + */ + public function setPathPrefix($prefix) + { + $prefix = (string) $prefix; + + if ($prefix === '') { + $this->pathPrefix = null; + + return; + } + + $this->pathPrefix = rtrim($prefix, '\\/') . $this->pathSeparator; + } + + /** + * Get the path prefix. + * + * @return string|null path prefix or null if pathPrefix is empty + */ + public function getPathPrefix() + { + return $this->pathPrefix; + } + + /** + * Prefix a path. + * + * @param string $path + * + * @return string prefixed path + */ + public function applyPathPrefix($path) + { + return $this->getPathPrefix() . ltrim($path, '\\/'); + } + + /** + * Remove a path prefix. + * + * @param string $path + * + * @return string path without the prefix + */ + public function removePathPrefix($path) + { + return substr($path, strlen($this->getPathPrefix())); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/AbstractFtpAdapter.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/AbstractFtpAdapter.php new file mode 100644 index 0000000..b232cdc --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/AbstractFtpAdapter.php @@ -0,0 +1,705 @@ +<?php + +namespace League\Flysystem\Adapter; + +use DateTime; +use League\Flysystem\AdapterInterface; +use League\Flysystem\Config; +use League\Flysystem\NotSupportedException; +use League\Flysystem\SafeStorage; +use RuntimeException; + +abstract class AbstractFtpAdapter extends AbstractAdapter +{ + /** + * @var mixed + */ + protected $connection; + + /** + * @var string + */ + protected $host; + + /** + * @var int + */ + protected $port = 21; + + /** + * @var bool + */ + protected $ssl = false; + + /** + * @var int + */ + protected $timeout = 90; + + /** + * @var bool + */ + protected $passive = true; + + /** + * @var string + */ + protected $separator = '/'; + + /** + * @var string|null + */ + protected $root; + + /** + * @var int + */ + protected $permPublic = 0744; + + /** + * @var int + */ + protected $permPrivate = 0700; + + /** + * @var array + */ + protected $configurable = []; + + /** + * @var string + */ + protected $systemType; + + /** + * @var SafeStorage + */ + protected $safeStorage; + + /** + * True to enable timestamps for FTP servers that return unix-style listings. + * + * @var bool + */ + protected $enableTimestampsOnUnixListings = false; + + /** + * Constructor. + * + * @param array $config + */ + public function __construct(array $config) + { + $this->safeStorage = new SafeStorage(); + $this->setConfig($config); + } + + /** + * Set the config. + * + * @param array $config + * + * @return $this + */ + public function setConfig(array $config) + { + foreach ($this->configurable as $setting) { + if ( ! isset($config[$setting])) { + continue; + } + + $method = 'set' . ucfirst($setting); + + if (method_exists($this, $method)) { + $this->$method($config[$setting]); + } + } + + return $this; + } + + /** + * Returns the host. + * + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * Set the host. + * + * @param string $host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + + return $this; + } + + /** + * Set the public permission value. + * + * @param int $permPublic + * + * @return $this + */ + public function setPermPublic($permPublic) + { + $this->permPublic = $permPublic; + + return $this; + } + + /** + * Set the private permission value. + * + * @param int $permPrivate + * + * @return $this + */ + public function setPermPrivate($permPrivate) + { + $this->permPrivate = $permPrivate; + + return $this; + } + + /** + * Returns the ftp port. + * + * @return int + */ + public function getPort() + { + return $this->port; + } + + /** + * Returns the root folder to work from. + * + * @return string + */ + public function getRoot() + { + return $this->root; + } + + /** + * Set the ftp port. + * + * @param int|string $port + * + * @return $this + */ + public function setPort($port) + { + $this->port = (int) $port; + + return $this; + } + + /** + * Set the root folder to work from. + * + * @param string $root + * + * @return $this + */ + public function setRoot($root) + { + $this->root = rtrim($root, '\\/') . $this->separator; + + return $this; + } + + /** + * Returns the ftp username. + * + * @return string username + */ + public function getUsername() + { + $username = $this->safeStorage->retrieveSafely('username'); + + return $username !== null ? $username : 'anonymous'; + } + + /** + * Set ftp username. + * + * @param string $username + * + * @return $this + */ + public function setUsername($username) + { + $this->safeStorage->storeSafely('username', $username); + + return $this; + } + + /** + * Returns the password. + * + * @return string password + */ + public function getPassword() + { + return $this->safeStorage->retrieveSafely('password'); + } + + /** + * Set the ftp password. + * + * @param string $password + * + * @return $this + */ + public function setPassword($password) + { + $this->safeStorage->storeSafely('password', $password); + + return $this; + } + + /** + * Returns the amount of seconds before the connection will timeout. + * + * @return int + */ + public function getTimeout() + { + return $this->timeout; + } + + /** + * Set the amount of seconds before the connection should timeout. + * + * @param int $timeout + * + * @return $this + */ + public function setTimeout($timeout) + { + $this->timeout = (int) $timeout; + + return $this; + } + + /** + * Return the FTP system type. + * + * @return string + */ + public function getSystemType() + { + return $this->systemType; + } + + /** + * Set the FTP system type (windows or unix). + * + * @param string $systemType + * + * @return $this + */ + public function setSystemType($systemType) + { + $this->systemType = strtolower($systemType); + + return $this; + } + + /** + * True to enable timestamps for FTP servers that return unix-style listings. + * + * @param bool $bool + * + * @return $this + */ + public function setEnableTimestampsOnUnixListings($bool = false) + { + $this->enableTimestampsOnUnixListings = $bool; + + return $this; + } + + /** + * @inheritdoc + */ + public function listContents($directory = '', $recursive = false) + { + return $this->listDirectoryContents($directory, $recursive); + } + + abstract protected function listDirectoryContents($directory, $recursive = false); + + /** + * Normalize a directory listing. + * + * @param array $listing + * @param string $prefix + * + * @return array directory listing + */ + protected function normalizeListing(array $listing, $prefix = '') + { + $base = $prefix; + $result = []; + $listing = $this->removeDotDirectories($listing); + + while ($item = array_shift($listing)) { + if (preg_match('#^.*:$#', $item)) { + $base = preg_replace('~^\./*|:$~', '', $item); + continue; + } + + $result[] = $this->normalizeObject($item, $base); + } + + return $this->sortListing($result); + } + + /** + * Sort a directory listing. + * + * @param array $result + * + * @return array sorted listing + */ + protected function sortListing(array $result) + { + $compare = function ($one, $two) { + return strnatcmp($one['path'], $two['path']); + }; + + usort($result, $compare); + + return $result; + } + + /** + * Normalize a file entry. + * + * @param string $item + * @param string $base + * + * @return array normalized file array + * + * @throws NotSupportedException + */ + protected function normalizeObject($item, $base) + { + $systemType = $this->systemType ?: $this->detectSystemType($item); + + if ($systemType === 'unix') { + return $this->normalizeUnixObject($item, $base); + } elseif ($systemType === 'windows') { + return $this->normalizeWindowsObject($item, $base); + } + + throw NotSupportedException::forFtpSystemType($systemType); + } + + /** + * Normalize a Unix file entry. + * + * Given $item contains: + * '-rw-r--r-- 1 ftp ftp 409 Aug 19 09:01 file1.txt' + * + * This function will return: + * [ + * 'type' => 'file', + * 'path' => 'file1.txt', + * 'visibility' => 'public', + * 'size' => 409, + * 'timestamp' => 1566205260 + * ] + * + * @param string $item + * @param string $base + * + * @return array normalized file array + */ + protected function normalizeUnixObject($item, $base) + { + $item = preg_replace('#\s+#', ' ', trim($item), 7); + + if (count(explode(' ', $item, 9)) !== 9) { + throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts."); + } + + list($permissions, /* $number */, /* $owner */, /* $group */, $size, $month, $day, $timeOrYear, $name) = explode(' ', $item, 9); + $type = $this->detectType($permissions); + $path = $base === '' ? $name : $base . $this->separator . $name; + + if ($type === 'dir') { + $result = compact('type', 'path'); + if ($this->enableTimestampsOnUnixListings) { + $timestamp = $this->normalizeUnixTimestamp($month, $day, $timeOrYear); + $result += compact('timestamp'); + } + + return $result; + } + + $permissions = $this->normalizePermissions($permissions); + $visibility = $permissions & 0044 ? AdapterInterface::VISIBILITY_PUBLIC : AdapterInterface::VISIBILITY_PRIVATE; + $size = (int) $size; + + $result = compact('type', 'path', 'visibility', 'size'); + if ($this->enableTimestampsOnUnixListings) { + $timestamp = $this->normalizeUnixTimestamp($month, $day, $timeOrYear); + $result += compact('timestamp'); + } + + return $result; + } + + /** + * Only accurate to the minute (current year), or to the day. + * + * Inadequacies in timestamp accuracy are due to limitations of the FTP 'LIST' command + * + * Note: The 'MLSD' command is a machine-readable replacement for 'LIST' + * but many FTP servers do not support it :( + * + * @param string $month e.g. 'Aug' + * @param string $day e.g. '19' + * @param string $timeOrYear e.g. '09:01' OR '2015' + * + * @return int + */ + protected function normalizeUnixTimestamp($month, $day, $timeOrYear) + { + if (is_numeric($timeOrYear)) { + $year = $timeOrYear; + $hour = '00'; + $minute = '00'; + $seconds = '00'; + } else { + $year = date('Y'); + list($hour, $minute) = explode(':', $timeOrYear); + $seconds = '00'; + } + $dateTime = DateTime::createFromFormat('Y-M-j-G:i:s', "{$year}-{$month}-{$day}-{$hour}:{$minute}:{$seconds}"); + + return $dateTime->getTimestamp(); + } + + /** + * Normalize a Windows/DOS file entry. + * + * @param string $item + * @param string $base + * + * @return array normalized file array + */ + protected function normalizeWindowsObject($item, $base) + { + $item = preg_replace('#\s+#', ' ', trim($item), 3); + + if (count(explode(' ', $item, 4)) !== 4) { + throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts."); + } + + list($date, $time, $size, $name) = explode(' ', $item, 4); + $path = $base === '' ? $name : $base . $this->separator . $name; + + // Check for the correct date/time format + $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i'; + $dt = DateTime::createFromFormat($format, $date . $time); + $timestamp = $dt ? $dt->getTimestamp() : (int) strtotime("$date $time"); + + if ($size === '<DIR>') { + $type = 'dir'; + + return compact('type', 'path', 'timestamp'); + } + + $type = 'file'; + $visibility = AdapterInterface::VISIBILITY_PUBLIC; + $size = (int) $size; + + return compact('type', 'path', 'visibility', 'size', 'timestamp'); + } + + /** + * Get the system type from a listing item. + * + * @param string $item + * + * @return string the system type + */ + protected function detectSystemType($item) + { + return preg_match('/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item) ? 'windows' : 'unix'; + } + + /** + * Get the file type from the permissions. + * + * @param string $permissions + * + * @return string file type + */ + protected function detectType($permissions) + { + return substr($permissions, 0, 1) === 'd' ? 'dir' : 'file'; + } + + /** + * Normalize a permissions string. + * + * @param string $permissions + * + * @return int + */ + protected function normalizePermissions($permissions) + { + if (is_numeric($permissions)) { + return ((int) $permissions) & 0777; + } + + // remove the type identifier + $permissions = substr($permissions, 1); + + // map the string rights to the numeric counterparts + $map = ['-' => '0', 'r' => '4', 'w' => '2', 'x' => '1']; + $permissions = strtr($permissions, $map); + + // split up the permission groups + $parts = str_split($permissions, 3); + + // convert the groups + $mapper = function ($part) { + return array_sum(str_split($part)); + }; + + // converts to decimal number + return octdec(implode('', array_map($mapper, $parts))); + } + + /** + * Filter out dot-directories. + * + * @param array $list + * + * @return array + */ + public function removeDotDirectories(array $list) + { + $filter = function ($line) { + return $line !== '' && ! preg_match('#.* \.(\.)?$|^total#', $line); + }; + + return array_filter($list, $filter); + } + + /** + * @inheritdoc + */ + public function has($path) + { + return $this->getMetadata($path); + } + + /** + * @inheritdoc + */ + public function getSize($path) + { + return $this->getMetadata($path); + } + + /** + * @inheritdoc + */ + public function getVisibility($path) + { + return $this->getMetadata($path); + } + + /** + * Ensure a directory exists. + * + * @param string $dirname + */ + public function ensureDirectory($dirname) + { + $dirname = (string) $dirname; + + if ($dirname !== '' && ! $this->has($dirname)) { + $this->createDir($dirname, new Config()); + } + } + + /** + * @return mixed + */ + public function getConnection() + { + if ( ! $this->isConnected()) { + $this->disconnect(); + $this->connect(); + } + + return $this->connection; + } + + /** + * Get the public permission value. + * + * @return int + */ + public function getPermPublic() + { + return $this->permPublic; + } + + /** + * Get the private permission value. + * + * @return int + */ + public function getPermPrivate() + { + return $this->permPrivate; + } + + /** + * Disconnect on destruction. + */ + public function __destruct() + { + $this->disconnect(); + } + + /** + * Establish a connection. + */ + abstract public function connect(); + + /** + * Close the connection. + */ + abstract public function disconnect(); + + /** + * Check if a connection is active. + * + * @return bool + */ + abstract public function isConnected(); + + protected function escapePath($path) + { + return str_replace(['*', '[', ']'], ['\\*', '\\[', '\\]'], $path); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/CanOverwriteFiles.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/CanOverwriteFiles.php new file mode 100644 index 0000000..fd8d216 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/CanOverwriteFiles.php @@ -0,0 +1,12 @@ +<?php + + +namespace League\Flysystem\Adapter; + +/** + * Adapters that implement this interface let the Filesystem know that files can be overwritten using the write + * functions and don't need the update function to be called. This can help improve performance when asserts are disabled. + */ +interface CanOverwriteFiles +{ +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Ftp.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Ftp.php new file mode 100644 index 0000000..b009210 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Ftp.php @@ -0,0 +1,579 @@ +<?php + +namespace League\Flysystem\Adapter; + +use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait; +use League\Flysystem\AdapterInterface; +use League\Flysystem\Config; +use League\Flysystem\ConnectionErrorException; +use League\Flysystem\ConnectionRuntimeException; +use League\Flysystem\InvalidRootException; +use League\Flysystem\Util; +use League\Flysystem\Util\MimeType; + +class Ftp extends AbstractFtpAdapter +{ + use StreamedCopyTrait; + + /** + * @var int + */ + protected $transferMode = FTP_BINARY; + + /** + * @var null|bool + */ + protected $ignorePassiveAddress = null; + + /** + * @var bool + */ + protected $recurseManually = false; + + /** + * @var bool + */ + protected $utf8 = false; + + /** + * @var array + */ + protected $configurable = [ + 'host', + 'port', + 'username', + 'password', + 'ssl', + 'timeout', + 'root', + 'permPrivate', + 'permPublic', + 'passive', + 'transferMode', + 'systemType', + 'ignorePassiveAddress', + 'recurseManually', + 'utf8', + 'enableTimestampsOnUnixListings', + ]; + + /** + * @var bool + */ + protected $isPureFtpd; + + /** + * Set the transfer mode. + * + * @param int $mode + * + * @return $this + */ + public function setTransferMode($mode) + { + $this->transferMode = $mode; + + return $this; + } + + /** + * Set if Ssl is enabled. + * + * @param bool $ssl + * + * @return $this + */ + public function setSsl($ssl) + { + $this->ssl = (bool) $ssl; + + return $this; + } + + /** + * Set if passive mode should be used. + * + * @param bool $passive + */ + public function setPassive($passive = true) + { + $this->passive = $passive; + } + + /** + * @param bool $ignorePassiveAddress + */ + public function setIgnorePassiveAddress($ignorePassiveAddress) + { + $this->ignorePassiveAddress = $ignorePassiveAddress; + } + + /** + * @param bool $recurseManually + */ + public function setRecurseManually($recurseManually) + { + $this->recurseManually = $recurseManually; + } + + /** + * @param bool $utf8 + */ + public function setUtf8($utf8) + { + $this->utf8 = (bool) $utf8; + } + + /** + * Connect to the FTP server. + */ + public function connect() + { + $tries = 3; + start_connecting: + + if ($this->ssl) { + $this->connection = @ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout()); + } else { + $this->connection = @ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout()); + } + + if ( ! $this->connection) { + $tries--; + + if ($tries > 0) goto start_connecting; + + throw new ConnectionRuntimeException('Could not connect to host: ' . $this->getHost() . ', port:' . $this->getPort()); + } + + $this->login(); + $this->setUtf8Mode(); + $this->setConnectionPassiveMode(); + $this->setConnectionRoot(); + $this->isPureFtpd = $this->isPureFtpdServer(); + } + + /** + * Set the connection to UTF-8 mode. + */ + protected function setUtf8Mode() + { + if ($this->utf8) { + $response = ftp_raw($this->connection, "OPTS UTF8 ON"); + if (substr($response[0], 0, 3) !== '200') { + throw new ConnectionRuntimeException( + 'Could not set UTF-8 mode for connection: ' . $this->getHost() . '::' . $this->getPort() + ); + } + } + } + + /** + * Set the connections to passive mode. + * + * @throws ConnectionRuntimeException + */ + protected function setConnectionPassiveMode() + { + if (is_bool($this->ignorePassiveAddress) && defined('FTP_USEPASVADDRESS')) { + ftp_set_option($this->connection, FTP_USEPASVADDRESS, ! $this->ignorePassiveAddress); + } + + if ( ! ftp_pasv($this->connection, $this->passive)) { + throw new ConnectionRuntimeException( + 'Could not set passive mode for connection: ' . $this->getHost() . '::' . $this->getPort() + ); + } + } + + /** + * Set the connection root. + */ + protected function setConnectionRoot() + { + $root = $this->getRoot(); + $connection = $this->connection; + + if ($root && ! ftp_chdir($connection, $root)) { + throw new InvalidRootException('Root is invalid or does not exist: ' . $this->getRoot()); + } + + // Store absolute path for further reference. + // This is needed when creating directories and + // initial root was a relative path, else the root + // would be relative to the chdir'd path. + $this->root = ftp_pwd($connection); + } + + /** + * Login. + * + * @throws ConnectionRuntimeException + */ + protected function login() + { + set_error_handler(function () { + }); + $isLoggedIn = ftp_login( + $this->connection, + $this->getUsername(), + $this->getPassword() + ); + restore_error_handler(); + + if ( ! $isLoggedIn) { + $this->disconnect(); + throw new ConnectionRuntimeException( + 'Could not login with connection: ' . $this->getHost() . '::' . $this->getPort( + ) . ', username: ' . $this->getUsername() + ); + } + } + + /** + * Disconnect from the FTP server. + */ + public function disconnect() + { + if (is_resource($this->connection)) { + @ftp_close($this->connection); + } + + $this->connection = null; + } + + /** + * @inheritdoc + */ + public function write($path, $contents, Config $config) + { + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, $contents); + rewind($stream); + $result = $this->writeStream($path, $stream, $config); + fclose($stream); + + if ($result === false) { + return false; + } + + $result['contents'] = $contents; + $result['mimetype'] = $config->get('mimetype') ?: Util::guessMimeType($path, $contents); + + return $result; + } + + /** + * @inheritdoc + */ + public function writeStream($path, $resource, Config $config) + { + $this->ensureDirectory(Util::dirname($path)); + + if ( ! ftp_fput($this->getConnection(), $path, $resource, $this->transferMode)) { + return false; + } + + if ($visibility = $config->get('visibility')) { + $this->setVisibility($path, $visibility); + } + + $type = 'file'; + + return compact('type', 'path', 'visibility'); + } + + /** + * @inheritdoc + */ + public function update($path, $contents, Config $config) + { + return $this->write($path, $contents, $config); + } + + /** + * @inheritdoc + */ + public function updateStream($path, $resource, Config $config) + { + return $this->writeStream($path, $resource, $config); + } + + /** + * @inheritdoc + */ + public function rename($path, $newpath) + { + return ftp_rename($this->getConnection(), $path, $newpath); + } + + /** + * @inheritdoc + */ + public function delete($path) + { + return ftp_delete($this->getConnection(), $path); + } + + /** + * @inheritdoc + */ + public function deleteDir($dirname) + { + $connection = $this->getConnection(); + $contents = array_reverse($this->listDirectoryContents($dirname, false)); + + foreach ($contents as $object) { + if ($object['type'] === 'file') { + if ( ! ftp_delete($connection, $object['path'])) { + return false; + } + } elseif ( ! $this->deleteDir($object['path'])) { + return false; + } + } + + return ftp_rmdir($connection, $dirname); + } + + /** + * @inheritdoc + */ + public function createDir($dirname, Config $config) + { + $connection = $this->getConnection(); + $directories = explode('/', $dirname); + + foreach ($directories as $directory) { + if (false === $this->createActualDirectory($directory, $connection)) { + $this->setConnectionRoot(); + + return false; + } + + ftp_chdir($connection, $directory); + } + + $this->setConnectionRoot(); + + return ['type' => 'dir', 'path' => $dirname]; + } + + /** + * Create a directory. + * + * @param string $directory + * @param resource $connection + * + * @return bool + */ + protected function createActualDirectory($directory, $connection) + { + // List the current directory + $listing = ftp_nlist($connection, '.') ?: []; + + foreach ($listing as $key => $item) { + if (preg_match('~^\./.*~', $item)) { + $listing[$key] = substr($item, 2); + } + } + + if (in_array($directory, $listing, true)) { + return true; + } + + return (boolean) ftp_mkdir($connection, $directory); + } + + /** + * @inheritdoc + */ + public function getMetadata($path) + { + if ($path === '') { + return ['type' => 'dir', 'path' => '']; + } + + if (@ftp_chdir($this->getConnection(), $path) === true) { + $this->setConnectionRoot(); + + return ['type' => 'dir', 'path' => $path]; + } + + $listing = $this->ftpRawlist('-A', $path); + + if (empty($listing) || in_array('total 0', $listing, true)) { + return false; + } + + if (preg_match('/.* not found/', $listing[0])) { + return false; + } + + if (preg_match('/^total [0-9]*$/', $listing[0])) { + array_shift($listing); + } + + return $this->normalizeObject($listing[0], ''); + } + + /** + * @inheritdoc + */ + public function getMimetype($path) + { + if ( ! $metadata = $this->getMetadata($path)) { + return false; + } + + $metadata['mimetype'] = MimeType::detectByFilename($path); + + return $metadata; + } + + /** + * @inheritdoc + */ + public function getTimestamp($path) + { + $timestamp = ftp_mdtm($this->getConnection(), $path); + + return ($timestamp !== -1) ? ['path' => $path, 'timestamp' => $timestamp] : false; + } + + /** + * @inheritdoc + */ + public function read($path) + { + if ( ! $object = $this->readStream($path)) { + return false; + } + + $object['contents'] = stream_get_contents($object['stream']); + fclose($object['stream']); + unset($object['stream']); + + return $object; + } + + /** + * @inheritdoc + */ + public function readStream($path) + { + $stream = fopen('php://temp', 'w+b'); + $result = ftp_fget($this->getConnection(), $stream, $path, $this->transferMode); + rewind($stream); + + if ( ! $result) { + fclose($stream); + + return false; + } + + return ['type' => 'file', 'path' => $path, 'stream' => $stream]; + } + + /** + * @inheritdoc + */ + public function setVisibility($path, $visibility) + { + $mode = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? $this->getPermPublic() : $this->getPermPrivate(); + + if ( ! ftp_chmod($this->getConnection(), $mode, $path)) { + return false; + } + + return compact('path', 'visibility'); + } + + /** + * @inheritdoc + * + * @param string $directory + */ + protected function listDirectoryContents($directory, $recursive = true) + { + if ($recursive && $this->recurseManually) { + return $this->listDirectoryContentsRecursive($directory); + } + + $options = $recursive ? '-alnR' : '-aln'; + $listing = $this->ftpRawlist($options, $directory); + + return $listing ? $this->normalizeListing($listing, $directory) : []; + } + + /** + * @inheritdoc + * + * @param string $directory + */ + protected function listDirectoryContentsRecursive($directory) + { + $listing = $this->normalizeListing($this->ftpRawlist('-aln', $directory) ?: [], $directory); + $output = []; + + foreach ($listing as $item) { + $output[] = $item; + if ($item['type'] !== 'dir') { + continue; + } + $output = array_merge($output, $this->listDirectoryContentsRecursive($item['path'])); + } + + return $output; + } + + /** + * Check if the connection is open. + * + * @return bool + * + * @throws ConnectionErrorException + */ + public function isConnected() + { + return is_resource($this->connection) + && $this->getRawExecResponseCode('NOOP') === 200; + } + + /** + * @return bool + */ + protected function isPureFtpdServer() + { + $response = ftp_raw($this->connection, 'HELP'); + + return stripos(implode(' ', $response), 'Pure-FTPd') !== false; + } + + /** + * The ftp_rawlist function with optional escaping. + * + * @param string $options + * @param string $path + * + * @return array + */ + protected function ftpRawlist($options, $path) + { + $connection = $this->getConnection(); + + if ($this->isPureFtpd) { + $path = str_replace(' ', '\ ', $path); + $this->escapePath($path); + } + + return ftp_rawlist($connection, $options . ' ' . $path); + } + + private function getRawExecResponseCode($command) + { + $response = @ftp_raw($this->connection, trim($command)); + + return (int) preg_replace('/\D/', '', implode(' ', $response)); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Ftpd.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Ftpd.php new file mode 100644 index 0000000..7e71d19 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Ftpd.php @@ -0,0 +1,48 @@ +<?php + +namespace League\Flysystem\Adapter; + +class Ftpd extends Ftp +{ + /** + * @inheritdoc + */ + public function getMetadata($path) + { + if ($path === '') { + return ['type' => 'dir', 'path' => '']; + } + + if (@ftp_chdir($this->getConnection(), $path) === true) { + $this->setConnectionRoot(); + + return ['type' => 'dir', 'path' => $path]; + } + + $object = ftp_raw($this->getConnection(), 'STAT ' . $this->escapePath($path)); + + if ( ! $object || count($object) < 3) { + return false; + } + + if (substr($object[1], 0, 5) === "ftpd:") { + return false; + } + + return $this->normalizeObject($object[1], ''); + } + + /** + * @inheritdoc + */ + protected function listDirectoryContents($directory, $recursive = true) + { + $listing = ftp_rawlist($this->getConnection(), $this->escapePath($directory), $recursive); + + if ($listing === false || ( ! empty($listing) && substr($listing[0], 0, 5) === "ftpd:")) { + return []; + } + + return $this->normalizeListing($listing, $directory); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Local.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Local.php new file mode 100644 index 0000000..747c463 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Local.php @@ -0,0 +1,533 @@ +<?php + +namespace League\Flysystem\Adapter; + +use DirectoryIterator; +use FilesystemIterator; +use finfo as Finfo; +use League\Flysystem\Config; +use League\Flysystem\Exception; +use League\Flysystem\NotSupportedException; +use League\Flysystem\UnreadableFileException; +use League\Flysystem\Util; +use LogicException; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; +use SplFileInfo; + +class Local extends AbstractAdapter +{ + /** + * @var int + */ + const SKIP_LINKS = 0001; + + /** + * @var int + */ + const DISALLOW_LINKS = 0002; + + /** + * @var array + */ + protected static $permissions = [ + 'file' => [ + 'public' => 0644, + 'private' => 0600, + ], + 'dir' => [ + 'public' => 0755, + 'private' => 0700, + ], + ]; + + /** + * @var string + */ + protected $pathSeparator = DIRECTORY_SEPARATOR; + + /** + * @var array + */ + protected $permissionMap; + + /** + * @var int + */ + protected $writeFlags; + + /** + * @var int + */ + private $linkHandling; + + /** + * Constructor. + * + * @param string $root + * @param int $writeFlags + * @param int $linkHandling + * @param array $permissions + * + * @throws LogicException + */ + public function __construct($root, $writeFlags = LOCK_EX, $linkHandling = self::DISALLOW_LINKS, array $permissions = []) + { + $root = is_link($root) ? realpath($root) : $root; + $this->permissionMap = array_replace_recursive(static::$permissions, $permissions); + $this->ensureDirectory($root); + + if ( ! is_dir($root) || ! is_readable($root)) { + throw new LogicException('The root path ' . $root . ' is not readable.'); + } + + $this->setPathPrefix($root); + $this->writeFlags = $writeFlags; + $this->linkHandling = $linkHandling; + } + + /** + * Ensure the root directory exists. + * + * @param string $root root directory path + * + * @return void + * + * @throws Exception in case the root directory can not be created + */ + protected function ensureDirectory($root) + { + if ( ! is_dir($root)) { + $umask = umask(0); + + if ( ! @mkdir($root, $this->permissionMap['dir']['public'], true)) { + $mkdirError = error_get_last(); + } + + umask($umask); + clearstatcache(false, $root); + + if ( ! is_dir($root)) { + $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : ''; + throw new Exception(sprintf('Impossible to create the root directory "%s". %s', $root, $errorMessage)); + } + } + } + + /** + * @inheritdoc + */ + public function has($path) + { + $location = $this->applyPathPrefix($path); + + return file_exists($location); + } + + /** + * @inheritdoc + */ + public function write($path, $contents, Config $config) + { + $location = $this->applyPathPrefix($path); + $this->ensureDirectory(dirname($location)); + + if (($size = file_put_contents($location, $contents, $this->writeFlags)) === false) { + return false; + } + + $type = 'file'; + $result = compact('contents', 'type', 'size', 'path'); + + if ($visibility = $config->get('visibility')) { + $result['visibility'] = $visibility; + $this->setVisibility($path, $visibility); + } + + return $result; + } + + /** + * @inheritdoc + */ + public function writeStream($path, $resource, Config $config) + { + $location = $this->applyPathPrefix($path); + $this->ensureDirectory(dirname($location)); + $stream = fopen($location, 'w+b'); + + if ( ! $stream || stream_copy_to_stream($resource, $stream) === false || ! fclose($stream)) { + return false; + } + + $type = 'file'; + $result = compact('type', 'path'); + + if ($visibility = $config->get('visibility')) { + $this->setVisibility($path, $visibility); + $result['visibility'] = $visibility; + } + + return $result; + } + + /** + * @inheritdoc + */ + public function readStream($path) + { + $location = $this->applyPathPrefix($path); + $stream = fopen($location, 'rb'); + + return ['type' => 'file', 'path' => $path, 'stream' => $stream]; + } + + /** + * @inheritdoc + */ + public function updateStream($path, $resource, Config $config) + { + return $this->writeStream($path, $resource, $config); + } + + /** + * @inheritdoc + */ + public function update($path, $contents, Config $config) + { + $location = $this->applyPathPrefix($path); + $size = file_put_contents($location, $contents, $this->writeFlags); + + if ($size === false) { + return false; + } + + $type = 'file'; + + $result = compact('type', 'path', 'size', 'contents'); + + if ($visibility = $config->get('visibility')) { + $this->setVisibility($path, $visibility); + $result['visibility'] = $visibility; + } + + return $result; + } + + /** + * @inheritdoc + */ + public function read($path) + { + $location = $this->applyPathPrefix($path); + $contents = @file_get_contents($location); + + if ($contents === false) { + return false; + } + + return ['type' => 'file', 'path' => $path, 'contents' => $contents]; + } + + /** + * @inheritdoc + */ + public function rename($path, $newpath) + { + $location = $this->applyPathPrefix($path); + $destination = $this->applyPathPrefix($newpath); + $parentDirectory = $this->applyPathPrefix(Util::dirname($newpath)); + $this->ensureDirectory($parentDirectory); + + return rename($location, $destination); + } + + /** + * @inheritdoc + */ + public function copy($path, $newpath) + { + $location = $this->applyPathPrefix($path); + $destination = $this->applyPathPrefix($newpath); + $this->ensureDirectory(dirname($destination)); + + return copy($location, $destination); + } + + /** + * @inheritdoc + */ + public function delete($path) + { + $location = $this->applyPathPrefix($path); + + return @unlink($location); + } + + /** + * @inheritdoc + */ + public function listContents($directory = '', $recursive = false) + { + $result = []; + $location = $this->applyPathPrefix($directory); + + if ( ! is_dir($location)) { + return []; + } + + $iterator = $recursive ? $this->getRecursiveDirectoryIterator($location) : $this->getDirectoryIterator($location); + + foreach ($iterator as $file) { + $path = $this->getFilePath($file); + + if (preg_match('#(^|/|\\\\)\.{1,2}$#', $path)) { + continue; + } + + $result[] = $this->normalizeFileInfo($file); + } + + unset($iterator); + + return array_filter($result); + } + + /** + * @inheritdoc + */ + public function getMetadata($path) + { + $location = $this->applyPathPrefix($path); + clearstatcache(false, $location); + $info = new SplFileInfo($location); + + return $this->normalizeFileInfo($info); + } + + /** + * @inheritdoc + */ + public function getSize($path) + { + return $this->getMetadata($path); + } + + /** + * @inheritdoc + */ + public function getMimetype($path) + { + $location = $this->applyPathPrefix($path); + $finfo = new Finfo(FILEINFO_MIME_TYPE); + $mimetype = $finfo->file($location); + + if (in_array($mimetype, ['application/octet-stream', 'inode/x-empty', 'application/x-empty'])) { + $mimetype = Util\MimeType::detectByFilename($location); + } + + return ['path' => $path, 'type' => 'file', 'mimetype' => $mimetype]; + } + + /** + * @inheritdoc + */ + public function getTimestamp($path) + { + return $this->getMetadata($path); + } + + /** + * @inheritdoc + */ + public function getVisibility($path) + { + $location = $this->applyPathPrefix($path); + clearstatcache(false, $location); + $permissions = octdec(substr(sprintf('%o', fileperms($location)), -4)); + $type = is_dir($location) ? 'dir' : 'file'; + + foreach ($this->permissionMap[$type] as $visibility => $visibilityPermissions) { + if ($visibilityPermissions == $permissions) { + return compact('path', 'visibility'); + } + } + + $visibility = substr(sprintf('%o', fileperms($location)), -4); + + return compact('path', 'visibility'); + } + + /** + * @inheritdoc + */ + public function setVisibility($path, $visibility) + { + $location = $this->applyPathPrefix($path); + $type = is_dir($location) ? 'dir' : 'file'; + $success = chmod($location, $this->permissionMap[$type][$visibility]); + + if ($success === false) { + return false; + } + + return compact('path', 'visibility'); + } + + /** + * @inheritdoc + */ + public function createDir($dirname, Config $config) + { + $location = $this->applyPathPrefix($dirname); + $umask = umask(0); + $visibility = $config->get('visibility', 'public'); + $return = ['path' => $dirname, 'type' => 'dir']; + + if ( ! is_dir($location)) { + if (false === @mkdir($location, $this->permissionMap['dir'][$visibility], true) + || false === is_dir($location)) { + $return = false; + } + } + + umask($umask); + + return $return; + } + + /** + * @inheritdoc + */ + public function deleteDir($dirname) + { + $location = $this->applyPathPrefix($dirname); + + if ( ! is_dir($location)) { + return false; + } + + $contents = $this->getRecursiveDirectoryIterator($location, RecursiveIteratorIterator::CHILD_FIRST); + + /** @var SplFileInfo $file */ + foreach ($contents as $file) { + $this->guardAgainstUnreadableFileInfo($file); + $this->deleteFileInfoObject($file); + } + + unset($contents); + + return rmdir($location); + } + + /** + * @param SplFileInfo $file + */ + protected function deleteFileInfoObject(SplFileInfo $file) + { + switch ($file->getType()) { + case 'dir': + rmdir($file->getRealPath()); + break; + case 'link': + unlink($file->getPathname()); + break; + default: + unlink($file->getRealPath()); + } + } + + /** + * Normalize the file info. + * + * @param SplFileInfo $file + * + * @return array|void + * + * @throws NotSupportedException + */ + protected function normalizeFileInfo(SplFileInfo $file) + { + if ( ! $file->isLink()) { + return $this->mapFileInfo($file); + } + + if ($this->linkHandling & self::DISALLOW_LINKS) { + throw NotSupportedException::forLink($file); + } + } + + /** + * Get the normalized path from a SplFileInfo object. + * + * @param SplFileInfo $file + * + * @return string + */ + protected function getFilePath(SplFileInfo $file) + { + $location = $file->getPathname(); + $path = $this->removePathPrefix($location); + + return trim(str_replace('\\', '/', $path), '/'); + } + + /** + * @param string $path + * @param int $mode + * + * @return RecursiveIteratorIterator + */ + protected function getRecursiveDirectoryIterator($path, $mode = RecursiveIteratorIterator::SELF_FIRST) + { + return new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), + $mode + ); + } + + /** + * @param string $path + * + * @return DirectoryIterator + */ + protected function getDirectoryIterator($path) + { + $iterator = new DirectoryIterator($path); + + return $iterator; + } + + /** + * @param SplFileInfo $file + * + * @return array + */ + protected function mapFileInfo(SplFileInfo $file) + { + $normalized = [ + 'type' => $file->getType(), + 'path' => $this->getFilePath($file), + ]; + + $normalized['timestamp'] = $file->getMTime(); + + if ($normalized['type'] === 'file') { + $normalized['size'] = $file->getSize(); + } + + return $normalized; + } + + /** + * @param SplFileInfo $file + * + * @throws UnreadableFileException + */ + protected function guardAgainstUnreadableFileInfo(SplFileInfo $file) + { + if ( ! $file->isReadable()) { + throw UnreadableFileException::forFileInfo($file); + } + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/NullAdapter.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/NullAdapter.php new file mode 100644 index 0000000..2527087 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/NullAdapter.php @@ -0,0 +1,144 @@ +<?php + +namespace League\Flysystem\Adapter; + +use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait; +use League\Flysystem\Adapter\Polyfill\StreamedTrait; +use League\Flysystem\Config; + +class NullAdapter extends AbstractAdapter +{ + use StreamedTrait; + use StreamedCopyTrait; + + /** + * Check whether a file is present. + * + * @param string $path + * + * @return bool + */ + public function has($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function write($path, $contents, Config $config) + { + $type = 'file'; + $result = compact('contents', 'type', 'path'); + + if ($visibility = $config->get('visibility')) { + $result['visibility'] = $visibility; + } + + return $result; + } + + /** + * @inheritdoc + */ + public function update($path, $contents, Config $config) + { + return false; + } + + /** + * @inheritdoc + */ + public function read($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function rename($path, $newpath) + { + return false; + } + + /** + * @inheritdoc + */ + public function delete($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function listContents($directory = '', $recursive = false) + { + return []; + } + + /** + * @inheritdoc + */ + public function getMetadata($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function getSize($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function getMimetype($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function getTimestamp($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function getVisibility($path) + { + return false; + } + + /** + * @inheritdoc + */ + public function setVisibility($path, $visibility) + { + return compact('visibility'); + } + + /** + * @inheritdoc + */ + public function createDir($dirname, Config $config) + { + return ['path' => $dirname, 'type' => 'dir']; + } + + /** + * @inheritdoc + */ + public function deleteDir($dirname) + { + return false; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/NotSupportingVisibilityTrait.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/NotSupportingVisibilityTrait.php new file mode 100644 index 0000000..fc0a747 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/NotSupportingVisibilityTrait.php @@ -0,0 +1,33 @@ +<?php + +namespace League\Flysystem\Adapter\Polyfill; + +use LogicException; + +trait NotSupportingVisibilityTrait +{ + /** + * Get the visibility of a file. + * + * @param string $path + * + * @throws LogicException + */ + public function getVisibility($path) + { + throw new LogicException(get_class($this) . ' does not support visibility. Path: ' . $path); + } + + /** + * Set the visibility for a file. + * + * @param string $path + * @param string $visibility + * + * @throws LogicException + */ + public function setVisibility($path, $visibility) + { + throw new LogicException(get_class($this) . ' does not support visibility. Path: ' . $path . ', visibility: ' . $visibility); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedCopyTrait.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedCopyTrait.php new file mode 100644 index 0000000..1b491a4 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedCopyTrait.php @@ -0,0 +1,51 @@ +<?php + +namespace League\Flysystem\Adapter\Polyfill; + +use League\Flysystem\Config; + +trait StreamedCopyTrait +{ + /** + * Copy a file. + * + * @param string $path + * @param string $newpath + * + * @return bool + */ + public function copy($path, $newpath) + { + $response = $this->readStream($path); + + if ($response === false || ! is_resource($response['stream'])) { + return false; + } + + $result = $this->writeStream($newpath, $response['stream'], new Config()); + + if ($result !== false && is_resource($response['stream'])) { + fclose($response['stream']); + } + + return $result !== false; + } + + // Required abstract method + + /** + * @param string $path + * + * @return resource + */ + abstract public function readStream($path); + + /** + * @param string $path + * @param resource $resource + * @param Config $config + * + * @return resource + */ + abstract public function writeStream($path, $resource, Config $config); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedReadingTrait.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedReadingTrait.php new file mode 100644 index 0000000..2b31c01 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedReadingTrait.php @@ -0,0 +1,44 @@ +<?php + +namespace League\Flysystem\Adapter\Polyfill; + +/** + * A helper for adapters that only handle strings to provide read streams. + */ +trait StreamedReadingTrait +{ + /** + * Reads a file as a stream. + * + * @param string $path + * + * @return array|false + * + * @see League\Flysystem\ReadInterface::readStream() + */ + public function readStream($path) + { + if ( ! $data = $this->read($path)) { + return false; + } + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, $data['contents']); + rewind($stream); + $data['stream'] = $stream; + unset($data['contents']); + + return $data; + } + + /** + * Reads a file. + * + * @param string $path + * + * @return array|false + * + * @see League\Flysystem\ReadInterface::read() + */ + abstract public function read($path); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedTrait.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedTrait.php new file mode 100644 index 0000000..8042496 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedTrait.php @@ -0,0 +1,9 @@ +<?php + +namespace League\Flysystem\Adapter\Polyfill; + +trait StreamedTrait +{ + use StreamedReadingTrait; + use StreamedWritingTrait; +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedWritingTrait.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedWritingTrait.php new file mode 100644 index 0000000..8c91e83 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/Polyfill/StreamedWritingTrait.php @@ -0,0 +1,60 @@ +<?php + +namespace League\Flysystem\Adapter\Polyfill; + +use League\Flysystem\Config; +use League\Flysystem\Util; + +trait StreamedWritingTrait +{ + /** + * Stream fallback delegator. + * + * @param string $path + * @param resource $resource + * @param Config $config + * @param string $fallback + * + * @return mixed fallback result + */ + protected function stream($path, $resource, Config $config, $fallback) + { + Util::rewindStream($resource); + $contents = stream_get_contents($resource); + $fallbackCall = [$this, $fallback]; + + return call_user_func($fallbackCall, $path, $contents, $config); + } + + /** + * Write using a stream. + * + * @param string $path + * @param resource $resource + * @param Config $config + * + * @return mixed false or file metadata + */ + public function writeStream($path, $resource, Config $config) + { + return $this->stream($path, $resource, $config, 'write'); + } + + /** + * Update a file using a stream. + * + * @param string $path + * @param resource $resource + * @param Config $config Config object or visibility setting + * + * @return mixed false of file metadata + */ + public function updateStream($path, $resource, Config $config) + { + return $this->stream($path, $resource, $config, 'update'); + } + + // Required abstract methods + abstract public function write($pash, $contents, Config $config); + abstract public function update($pash, $contents, Config $config); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Adapter/SynologyFtp.php b/php/libraries/composer/vendor/league/flysystem/src/Adapter/SynologyFtp.php new file mode 100644 index 0000000..fe0d344 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Adapter/SynologyFtp.php @@ -0,0 +1,8 @@ +<?php + +namespace League\Flysystem\Adapter; + +class SynologyFtp extends Ftpd +{ + // This class merely exists because of BC. +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/AdapterInterface.php b/php/libraries/composer/vendor/league/flysystem/src/AdapterInterface.php new file mode 100644 index 0000000..567fc5a --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/AdapterInterface.php @@ -0,0 +1,118 @@ +<?php + +namespace League\Flysystem; + +interface AdapterInterface extends ReadInterface +{ + /** + * @const VISIBILITY_PUBLIC public visibility + */ + const VISIBILITY_PUBLIC = 'public'; + + /** + * @const VISIBILITY_PRIVATE private visibility + */ + const VISIBILITY_PRIVATE = 'private'; + + /** + * Write a new file. + * + * @param string $path + * @param string $contents + * @param Config $config Config object + * + * @return array|false false on failure file meta data on success + */ + public function write($path, $contents, Config $config); + + /** + * Write a new file using a stream. + * + * @param string $path + * @param resource $resource + * @param Config $config Config object + * + * @return array|false false on failure file meta data on success + */ + public function writeStream($path, $resource, Config $config); + + /** + * Update a file. + * + * @param string $path + * @param string $contents + * @param Config $config Config object + * + * @return array|false false on failure file meta data on success + */ + public function update($path, $contents, Config $config); + + /** + * Update a file using a stream. + * + * @param string $path + * @param resource $resource + * @param Config $config Config object + * + * @return array|false false on failure file meta data on success + */ + public function updateStream($path, $resource, Config $config); + + /** + * Rename a file. + * + * @param string $path + * @param string $newpath + * + * @return bool + */ + public function rename($path, $newpath); + + /** + * Copy a file. + * + * @param string $path + * @param string $newpath + * + * @return bool + */ + public function copy($path, $newpath); + + /** + * Delete a file. + * + * @param string $path + * + * @return bool + */ + public function delete($path); + + /** + * Delete a directory. + * + * @param string $dirname + * + * @return bool + */ + public function deleteDir($dirname); + + /** + * Create a directory. + * + * @param string $dirname directory name + * @param Config $config + * + * @return array|false + */ + public function createDir($dirname, Config $config); + + /** + * Set the visibility for a file. + * + * @param string $path + * @param string $visibility + * + * @return array|false file meta data + */ + public function setVisibility($path, $visibility); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Config.php b/php/libraries/composer/vendor/league/flysystem/src/Config.php new file mode 100644 index 0000000..639f43d --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Config.php @@ -0,0 +1,107 @@ +<?php + +namespace League\Flysystem; + +class Config +{ + /** + * @var array + */ + protected $settings = []; + + /** + * @var Config|null + */ + protected $fallback; + + /** + * Constructor. + * + * @param array $settings + */ + public function __construct(array $settings = []) + { + $this->settings = $settings; + } + + /** + * Get a setting. + * + * @param string $key + * @param mixed $default + * + * @return mixed config setting or default when not found + */ + public function get($key, $default = null) + { + if ( ! array_key_exists($key, $this->settings)) { + return $this->getDefault($key, $default); + } + + return $this->settings[$key]; + } + + /** + * Check if an item exists by key. + * + * @param string $key + * + * @return bool + */ + public function has($key) + { + if (array_key_exists($key, $this->settings)) { + return true; + } + + return $this->fallback instanceof Config + ? $this->fallback->has($key) + : false; + } + + /** + * Try to retrieve a default setting from a config fallback. + * + * @param string $key + * @param mixed $default + * + * @return mixed config setting or default when not found + */ + protected function getDefault($key, $default) + { + if ( ! $this->fallback) { + return $default; + } + + return $this->fallback->get($key, $default); + } + + /** + * Set a setting. + * + * @param string $key + * @param mixed $value + * + * @return $this + */ + public function set($key, $value) + { + $this->settings[$key] = $value; + + return $this; + } + + /** + * Set the fallback. + * + * @param Config $fallback + * + * @return $this + */ + public function setFallback(Config $fallback) + { + $this->fallback = $fallback; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/ConfigAwareTrait.php b/php/libraries/composer/vendor/league/flysystem/src/ConfigAwareTrait.php new file mode 100644 index 0000000..202d605 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/ConfigAwareTrait.php @@ -0,0 +1,49 @@ +<?php + +namespace League\Flysystem; + +/** + * @internal + */ +trait ConfigAwareTrait +{ + /** + * @var Config + */ + protected $config; + + /** + * Set the config. + * + * @param Config|array|null $config + */ + protected function setConfig($config) + { + $this->config = $config ? Util::ensureConfig($config) : new Config; + } + + /** + * Get the Config. + * + * @return Config config object + */ + public function getConfig() + { + return $this->config; + } + + /** + * Convert a config array to a Config object with the correct fallback. + * + * @param array $config + * + * @return Config + */ + protected function prepareConfig(array $config) + { + $config = new Config($config); + $config->setFallback($this->getConfig()); + + return $config; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/ConnectionErrorException.php b/php/libraries/composer/vendor/league/flysystem/src/ConnectionErrorException.php new file mode 100644 index 0000000..adb651d --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/ConnectionErrorException.php @@ -0,0 +1,9 @@ +<?php + +namespace League\Flysystem; + +use ErrorException; + +class ConnectionErrorException extends ErrorException implements FilesystemException +{ +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/ConnectionRuntimeException.php b/php/libraries/composer/vendor/league/flysystem/src/ConnectionRuntimeException.php new file mode 100644 index 0000000..8b893ef --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/ConnectionRuntimeException.php @@ -0,0 +1,9 @@ +<?php + +namespace League\Flysystem; + +use RuntimeException; + +class ConnectionRuntimeException extends RuntimeException implements FilesystemException +{ +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Directory.php b/php/libraries/composer/vendor/league/flysystem/src/Directory.php new file mode 100644 index 0000000..d4f90a8 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Directory.php @@ -0,0 +1,31 @@ +<?php + +namespace League\Flysystem; + +/** + * @deprecated + */ +class Directory extends Handler +{ + /** + * Delete the directory. + * + * @return bool + */ + public function delete() + { + return $this->filesystem->deleteDir($this->path); + } + + /** + * List the directory contents. + * + * @param bool $recursive + * + * @return array|bool directory contents or false + */ + public function getContents($recursive = false) + { + return $this->filesystem->listContents($this->path, $recursive); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Exception.php b/php/libraries/composer/vendor/league/flysystem/src/Exception.php new file mode 100644 index 0000000..4596c0a --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Exception.php @@ -0,0 +1,8 @@ +<?php + +namespace League\Flysystem; + +class Exception extends \Exception implements FilesystemException +{ + // +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/File.php b/php/libraries/composer/vendor/league/flysystem/src/File.php new file mode 100644 index 0000000..4a4b7a0 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/File.php @@ -0,0 +1,205 @@ +<?php + +namespace League\Flysystem; + +/** + * @deprecated + */ +class File extends Handler +{ + /** + * Check whether the file exists. + * + * @return bool + */ + public function exists() + { + return $this->filesystem->has($this->path); + } + + /** + * Read the file. + * + * @return string|false file contents + */ + public function read() + { + return $this->filesystem->read($this->path); + } + + /** + * Read the file as a stream. + * + * @return resource|false file stream + */ + public function readStream() + { + return $this->filesystem->readStream($this->path); + } + + /** + * Write the new file. + * + * @param string $content + * + * @return bool success boolean + */ + public function write($content) + { + return $this->filesystem->write($this->path, $content); + } + + /** + * Write the new file using a stream. + * + * @param resource $resource + * + * @return bool success boolean + */ + public function writeStream($resource) + { + return $this->filesystem->writeStream($this->path, $resource); + } + + /** + * Update the file contents. + * + * @param string $content + * + * @return bool success boolean + */ + public function update($content) + { + return $this->filesystem->update($this->path, $content); + } + + /** + * Update the file contents with a stream. + * + * @param resource $resource + * + * @return bool success boolean + */ + public function updateStream($resource) + { + return $this->filesystem->updateStream($this->path, $resource); + } + + /** + * Create the file or update if exists. + * + * @param string $content + * + * @return bool success boolean + */ + public function put($content) + { + return $this->filesystem->put($this->path, $content); + } + + /** + * Create the file or update if exists using a stream. + * + * @param resource $resource + * + * @return bool success boolean + */ + public function putStream($resource) + { + return $this->filesystem->putStream($this->path, $resource); + } + + /** + * Rename the file. + * + * @param string $newpath + * + * @return bool success boolean + */ + public function rename($newpath) + { + if ($this->filesystem->rename($this->path, $newpath)) { + $this->path = $newpath; + + return true; + } + + return false; + } + + /** + * Copy the file. + * + * @param string $newpath + * + * @return File|false new file or false + */ + public function copy($newpath) + { + if ($this->filesystem->copy($this->path, $newpath)) { + return new File($this->filesystem, $newpath); + } + + return false; + } + + /** + * Get the file's timestamp. + * + * @return string|false The timestamp or false on failure. + */ + public function getTimestamp() + { + return $this->filesystem->getTimestamp($this->path); + } + + /** + * Get the file's mimetype. + * + * @return string|false The file mime-type or false on failure. + */ + public function getMimetype() + { + return $this->filesystem->getMimetype($this->path); + } + + /** + * Get the file's visibility. + * + * @return string|false The visibility (public|private) or false on failure. + */ + public function getVisibility() + { + return $this->filesystem->getVisibility($this->path); + } + + /** + * Get the file's metadata. + * + * @return array|false The file metadata or false on failure. + */ + public function getMetadata() + { + return $this->filesystem->getMetadata($this->path); + } + + /** + * Get the file size. + * + * @return int|false The file size or false on failure. + */ + public function getSize() + { + return $this->filesystem->getSize($this->path); + } + + /** + * Delete the file. + * + * @return bool success boolean + */ + public function delete() + { + return $this->filesystem->delete($this->path); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/FileExistsException.php b/php/libraries/composer/vendor/league/flysystem/src/FileExistsException.php new file mode 100644 index 0000000..c82e20c --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/FileExistsException.php @@ -0,0 +1,37 @@ +<?php + +namespace League\Flysystem; + +use Exception as BaseException; + +class FileExistsException extends Exception +{ + /** + * @var string + */ + protected $path; + + /** + * Constructor. + * + * @param string $path + * @param int $code + * @param BaseException $previous + */ + public function __construct($path, $code = 0, BaseException $previous = null) + { + $this->path = $path; + + parent::__construct('File already exists at path: ' . $this->getPath(), $code, $previous); + } + + /** + * Get the path which was found. + * + * @return string + */ + public function getPath() + { + return $this->path; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/FileNotFoundException.php b/php/libraries/composer/vendor/league/flysystem/src/FileNotFoundException.php new file mode 100644 index 0000000..989df69 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/FileNotFoundException.php @@ -0,0 +1,37 @@ +<?php + +namespace League\Flysystem; + +use Exception as BaseException; + +class FileNotFoundException extends Exception +{ + /** + * @var string + */ + protected $path; + + /** + * Constructor. + * + * @param string $path + * @param int $code + * @param \Exception $previous + */ + public function __construct($path, $code = 0, BaseException $previous = null) + { + $this->path = $path; + + parent::__construct('File not found at path: ' . $this->getPath(), $code, $previous); + } + + /** + * Get the path which was not found. + * + * @return string + */ + public function getPath() + { + return $this->path; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Filesystem.php b/php/libraries/composer/vendor/league/flysystem/src/Filesystem.php new file mode 100644 index 0000000..59cc82e --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Filesystem.php @@ -0,0 +1,408 @@ +<?php + +namespace League\Flysystem; + +use InvalidArgumentException; +use League\Flysystem\Adapter\CanOverwriteFiles; +use League\Flysystem\Plugin\PluggableTrait; +use League\Flysystem\Util\ContentListingFormatter; + +/** + * @method array getWithMetadata(string $path, array $metadata) + * @method bool forceCopy(string $path, string $newpath) + * @method bool forceRename(string $path, string $newpath) + * @method array listFiles(string $path = '', boolean $recursive = false) + * @method array listPaths(string $path = '', boolean $recursive = false) + * @method array listWith(array $keys = [], $directory = '', $recursive = false) + */ +class Filesystem implements FilesystemInterface +{ + use PluggableTrait; + use ConfigAwareTrait; + + /** + * @var AdapterInterface + */ + protected $adapter; + + /** + * Constructor. + * + * @param AdapterInterface $adapter + * @param Config|array $config + */ + public function __construct(AdapterInterface $adapter, $config = null) + { + $this->adapter = $adapter; + $this->setConfig($config); + } + + /** + * Get the Adapter. + * + * @return AdapterInterface adapter + */ + public function getAdapter() + { + return $this->adapter; + } + + /** + * @inheritdoc + */ + public function has($path) + { + $path = Util::normalizePath($path); + + return strlen($path) === 0 ? false : (bool) $this->getAdapter()->has($path); + } + + /** + * @inheritdoc + */ + public function write($path, $contents, array $config = []) + { + $path = Util::normalizePath($path); + $this->assertAbsent($path); + $config = $this->prepareConfig($config); + + return (bool) $this->getAdapter()->write($path, $contents, $config); + } + + /** + * @inheritdoc + */ + public function writeStream($path, $resource, array $config = []) + { + if ( ! is_resource($resource) || get_resource_type($resource) !== 'stream') { + throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.'); + } + + $path = Util::normalizePath($path); + $this->assertAbsent($path); + $config = $this->prepareConfig($config); + + Util::rewindStream($resource); + + return (bool) $this->getAdapter()->writeStream($path, $resource, $config); + } + + /** + * @inheritdoc + */ + public function put($path, $contents, array $config = []) + { + $path = Util::normalizePath($path); + $config = $this->prepareConfig($config); + + if ( ! $this->getAdapter() instanceof CanOverwriteFiles && $this->has($path)) { + return (bool) $this->getAdapter()->update($path, $contents, $config); + } + + return (bool) $this->getAdapter()->write($path, $contents, $config); + } + + /** + * @inheritdoc + */ + public function putStream($path, $resource, array $config = []) + { + if ( ! is_resource($resource) || get_resource_type($resource) !== 'stream') { + throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.'); + } + + $path = Util::normalizePath($path); + $config = $this->prepareConfig($config); + Util::rewindStream($resource); + + if ( ! $this->getAdapter() instanceof CanOverwriteFiles && $this->has($path)) { + return (bool) $this->getAdapter()->updateStream($path, $resource, $config); + } + + return (bool) $this->getAdapter()->writeStream($path, $resource, $config); + } + + /** + * @inheritdoc + */ + public function readAndDelete($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + $contents = $this->read($path); + + if ($contents === false) { + return false; + } + + $this->delete($path); + + return $contents; + } + + /** + * @inheritdoc + */ + public function update($path, $contents, array $config = []) + { + $path = Util::normalizePath($path); + $config = $this->prepareConfig($config); + + $this->assertPresent($path); + + return (bool) $this->getAdapter()->update($path, $contents, $config); + } + + /** + * @inheritdoc + */ + public function updateStream($path, $resource, array $config = []) + { + if ( ! is_resource($resource) || get_resource_type($resource) !== 'stream') { + throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.'); + } + + $path = Util::normalizePath($path); + $config = $this->prepareConfig($config); + $this->assertPresent($path); + Util::rewindStream($resource); + + return (bool) $this->getAdapter()->updateStream($path, $resource, $config); + } + + /** + * @inheritdoc + */ + public function read($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + if ( ! ($object = $this->getAdapter()->read($path))) { + return false; + } + + return $object['contents']; + } + + /** + * @inheritdoc + */ + public function readStream($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + if ( ! $object = $this->getAdapter()->readStream($path)) { + return false; + } + + return $object['stream']; + } + + /** + * @inheritdoc + */ + public function rename($path, $newpath) + { + $path = Util::normalizePath($path); + $newpath = Util::normalizePath($newpath); + $this->assertPresent($path); + $this->assertAbsent($newpath); + + return (bool) $this->getAdapter()->rename($path, $newpath); + } + + /** + * @inheritdoc + */ + public function copy($path, $newpath) + { + $path = Util::normalizePath($path); + $newpath = Util::normalizePath($newpath); + $this->assertPresent($path); + $this->assertAbsent($newpath); + + return $this->getAdapter()->copy($path, $newpath); + } + + /** + * @inheritdoc + */ + public function delete($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + return $this->getAdapter()->delete($path); + } + + /** + * @inheritdoc + */ + public function deleteDir($dirname) + { + $dirname = Util::normalizePath($dirname); + + if ($dirname === '') { + throw new RootViolationException('Root directories can not be deleted.'); + } + + return (bool) $this->getAdapter()->deleteDir($dirname); + } + + /** + * @inheritdoc + */ + public function createDir($dirname, array $config = []) + { + $dirname = Util::normalizePath($dirname); + $config = $this->prepareConfig($config); + + return (bool) $this->getAdapter()->createDir($dirname, $config); + } + + /** + * @inheritdoc + */ + public function listContents($directory = '', $recursive = false) + { + $directory = Util::normalizePath($directory); + $contents = $this->getAdapter()->listContents($directory, $recursive); + + return (new ContentListingFormatter($directory, $recursive, $this->config->get('case_sensitive', true))) + ->formatListing($contents); + } + + /** + * @inheritdoc + */ + public function getMimetype($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + if (( ! $object = $this->getAdapter()->getMimetype($path)) || ! array_key_exists('mimetype', $object)) { + return false; + } + + return $object['mimetype']; + } + + /** + * @inheritdoc + */ + public function getTimestamp($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + if (( ! $object = $this->getAdapter()->getTimestamp($path)) || ! array_key_exists('timestamp', $object)) { + return false; + } + + return (int) $object['timestamp']; + } + + /** + * @inheritdoc + */ + public function getVisibility($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + if (( ! $object = $this->getAdapter()->getVisibility($path)) || ! array_key_exists('visibility', $object)) { + return false; + } + + return $object['visibility']; + } + + /** + * @inheritdoc + */ + public function getSize($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + if (( ! $object = $this->getAdapter()->getSize($path)) || ! array_key_exists('size', $object)) { + return false; + } + + return (int) $object['size']; + } + + /** + * @inheritdoc + */ + public function setVisibility($path, $visibility) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + return (bool) $this->getAdapter()->setVisibility($path, $visibility); + } + + /** + * @inheritdoc + */ + public function getMetadata($path) + { + $path = Util::normalizePath($path); + $this->assertPresent($path); + + return $this->getAdapter()->getMetadata($path); + } + + /** + * @inheritdoc + */ + public function get($path, Handler $handler = null) + { + $path = Util::normalizePath($path); + + if ( ! $handler) { + $metadata = $this->getMetadata($path); + $handler = ($metadata && $metadata['type'] === 'file') ? new File($this, $path) : new Directory($this, $path); + } + + $handler->setPath($path); + $handler->setFilesystem($this); + + return $handler; + } + + /** + * Assert a file is present. + * + * @param string $path path to file + * + * @throws FileNotFoundException + * + * @return void + */ + public function assertPresent($path) + { + if ($this->config->get('disable_asserts', false) === false && ! $this->has($path)) { + throw new FileNotFoundException($path); + } + } + + /** + * Assert a file is absent. + * + * @param string $path path to file + * + * @throws FileExistsException + * + * @return void + */ + public function assertAbsent($path) + { + if ($this->config->get('disable_asserts', false) === false && $this->has($path)) { + throw new FileExistsException($path); + } + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/FilesystemException.php b/php/libraries/composer/vendor/league/flysystem/src/FilesystemException.php new file mode 100644 index 0000000..3121e53 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/FilesystemException.php @@ -0,0 +1,7 @@ +<?php + +namespace League\Flysystem; + +interface FilesystemException +{ +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/FilesystemInterface.php b/php/libraries/composer/vendor/league/flysystem/src/FilesystemInterface.php new file mode 100644 index 0000000..a6b99ba --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/FilesystemInterface.php @@ -0,0 +1,284 @@ +<?php + +namespace League\Flysystem; + +use InvalidArgumentException; + +interface FilesystemInterface +{ + /** + * Check whether a file exists. + * + * @param string $path + * + * @return bool + */ + public function has($path); + + /** + * Read a file. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The file contents or false on failure. + */ + public function read($path); + + /** + * Retrieves a read-stream for a path. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return resource|false The path resource or false on failure. + */ + public function readStream($path); + + /** + * List contents of a directory. + * + * @param string $directory The directory to list. + * @param bool $recursive Whether to list recursively. + * + * @return array A list of file metadata. + */ + public function listContents($directory = '', $recursive = false); + + /** + * Get a file's metadata. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return array|false The file metadata or false on failure. + */ + public function getMetadata($path); + + /** + * Get a file's size. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return int|false The file size or false on failure. + */ + public function getSize($path); + + /** + * Get a file's mime-type. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The file mime-type or false on failure. + */ + public function getMimetype($path); + + /** + * Get a file's timestamp. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return int|false The timestamp or false on failure. + */ + public function getTimestamp($path); + + /** + * Get a file's visibility. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The visibility (public|private) or false on failure. + */ + public function getVisibility($path); + + /** + * Write a new file. + * + * @param string $path The path of the new file. + * @param string $contents The file contents. + * @param array $config An optional configuration array. + * + * @throws FileExistsException + * + * @return bool True on success, false on failure. + */ + public function write($path, $contents, array $config = []); + + /** + * Write a new file using a stream. + * + * @param string $path The path of the new file. + * @param resource $resource The file handle. + * @param array $config An optional configuration array. + * + * @throws InvalidArgumentException If $resource is not a file handle. + * @throws FileExistsException + * + * @return bool True on success, false on failure. + */ + public function writeStream($path, $resource, array $config = []); + + /** + * Update an existing file. + * + * @param string $path The path of the existing file. + * @param string $contents The file contents. + * @param array $config An optional configuration array. + * + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function update($path, $contents, array $config = []); + + /** + * Update an existing file using a stream. + * + * @param string $path The path of the existing file. + * @param resource $resource The file handle. + * @param array $config An optional configuration array. + * + * @throws InvalidArgumentException If $resource is not a file handle. + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function updateStream($path, $resource, array $config = []); + + /** + * Rename a file. + * + * @param string $path Path to the existing file. + * @param string $newpath The new path of the file. + * + * @throws FileExistsException Thrown if $newpath exists. + * @throws FileNotFoundException Thrown if $path does not exist. + * + * @return bool True on success, false on failure. + */ + public function rename($path, $newpath); + + /** + * Copy a file. + * + * @param string $path Path to the existing file. + * @param string $newpath The new path of the file. + * + * @throws FileExistsException Thrown if $newpath exists. + * @throws FileNotFoundException Thrown if $path does not exist. + * + * @return bool True on success, false on failure. + */ + public function copy($path, $newpath); + + /** + * Delete a file. + * + * @param string $path + * + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function delete($path); + + /** + * Delete a directory. + * + * @param string $dirname + * + * @throws RootViolationException Thrown if $dirname is empty. + * + * @return bool True on success, false on failure. + */ + public function deleteDir($dirname); + + /** + * Create a directory. + * + * @param string $dirname The name of the new directory. + * @param array $config An optional configuration array. + * + * @return bool True on success, false on failure. + */ + public function createDir($dirname, array $config = []); + + /** + * Set the visibility for a file. + * + * @param string $path The path to the file. + * @param string $visibility One of 'public' or 'private'. + * + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function setVisibility($path, $visibility); + + /** + * Create a file or update if exists. + * + * @param string $path The path to the file. + * @param string $contents The file contents. + * @param array $config An optional configuration array. + * + * @return bool True on success, false on failure. + */ + public function put($path, $contents, array $config = []); + + /** + * Create a file or update if exists. + * + * @param string $path The path to the file. + * @param resource $resource The file handle. + * @param array $config An optional configuration array. + * + * @throws InvalidArgumentException Thrown if $resource is not a resource. + * + * @return bool True on success, false on failure. + */ + public function putStream($path, $resource, array $config = []); + + /** + * Read and delete a file. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The file contents, or false on failure. + */ + public function readAndDelete($path); + + /** + * Get a file/directory handler. + * + * @deprecated + * + * @param string $path The path to the file. + * @param Handler $handler An optional existing handler to populate. + * + * @return Handler Either a file or directory handler. + */ + public function get($path, Handler $handler = null); + + /** + * Register a plugin. + * + * @param PluginInterface $plugin The plugin to register. + * + * @return $this + */ + public function addPlugin(PluginInterface $plugin); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/FilesystemNotFoundException.php b/php/libraries/composer/vendor/league/flysystem/src/FilesystemNotFoundException.php new file mode 100644 index 0000000..f928fa1 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/FilesystemNotFoundException.php @@ -0,0 +1,12 @@ +<?php + +namespace League\Flysystem; + +use LogicException; + +/** + * Thrown when the MountManager cannot find a filesystem. + */ +class FilesystemNotFoundException extends LogicException implements FilesystemException +{ +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Handler.php b/php/libraries/composer/vendor/league/flysystem/src/Handler.php new file mode 100644 index 0000000..098bb85 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Handler.php @@ -0,0 +1,137 @@ +<?php + +namespace League\Flysystem; + +use BadMethodCallException; + +/** + * @deprecated + */ +abstract class Handler +{ + /** + * @var string + */ + protected $path; + + /** + * @var FilesystemInterface + */ + protected $filesystem; + + /** + * Constructor. + * + * @param FilesystemInterface $filesystem + * @param string $path + */ + public function __construct(FilesystemInterface $filesystem = null, $path = null) + { + $this->path = $path; + $this->filesystem = $filesystem; + } + + /** + * Check whether the entree is a directory. + * + * @return bool + */ + public function isDir() + { + return $this->getType() === 'dir'; + } + + /** + * Check whether the entree is a file. + * + * @return bool + */ + public function isFile() + { + return $this->getType() === 'file'; + } + + /** + * Retrieve the entree type (file|dir). + * + * @return string file or dir + */ + public function getType() + { + $metadata = $this->filesystem->getMetadata($this->path); + + return $metadata ? $metadata['type'] : 'dir'; + } + + /** + * Set the Filesystem object. + * + * @param FilesystemInterface $filesystem + * + * @return $this + */ + public function setFilesystem(FilesystemInterface $filesystem) + { + $this->filesystem = $filesystem; + + return $this; + } + + /** + * Retrieve the Filesystem object. + * + * @return FilesystemInterface + */ + public function getFilesystem() + { + return $this->filesystem; + } + + /** + * Set the entree path. + * + * @param string $path + * + * @return $this + */ + public function setPath($path) + { + $this->path = $path; + + return $this; + } + + /** + * Retrieve the entree path. + * + * @return string path + */ + public function getPath() + { + return $this->path; + } + + /** + * Plugins pass-through. + * + * @param string $method + * @param array $arguments + * + * @return mixed + */ + public function __call($method, array $arguments) + { + array_unshift($arguments, $this->path); + $callback = [$this->filesystem, $method]; + + try { + return call_user_func_array($callback, $arguments); + } catch (BadMethodCallException $e) { + throw new BadMethodCallException( + 'Call to undefined method ' + . get_called_class() + . '::' . $method + ); + } + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/InvalidRootException.php b/php/libraries/composer/vendor/league/flysystem/src/InvalidRootException.php new file mode 100644 index 0000000..468d1d5 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/InvalidRootException.php @@ -0,0 +1,9 @@ +<?php + +namespace League\Flysystem; + +use RuntimeException; + +class InvalidRootException extends RuntimeException implements FilesystemException +{ +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/MountManager.php b/php/libraries/composer/vendor/league/flysystem/src/MountManager.php new file mode 100644 index 0000000..150aee3 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/MountManager.php @@ -0,0 +1,650 @@ +<?php + +namespace League\Flysystem; + +use InvalidArgumentException; +use League\Flysystem\Plugin\PluggableTrait; +use League\Flysystem\Plugin\PluginNotFoundException; + +/** + * Class MountManager. + * + * Proxies methods to Filesystem (@see __call): + * + * @method AdapterInterface getAdapter($prefix) + * @method Config getConfig($prefix) + * @method array listFiles($directory = '', $recursive = false) + * @method array listPaths($directory = '', $recursive = false) + * @method array getWithMetadata($path, array $metadata) + * @method Filesystem flushCache() + * @method void assertPresent($path) + * @method void assertAbsent($path) + * @method Filesystem addPlugin(PluginInterface $plugin) + * + * @deprecated This functionality will be removed in 2.0 + */ +class MountManager implements FilesystemInterface +{ + use PluggableTrait; + + /** + * @var FilesystemInterface[] + */ + protected $filesystems = []; + + /** + * Constructor. + * + * @param FilesystemInterface[] $filesystems [:prefix => Filesystem,] + * + * @throws InvalidArgumentException + */ + public function __construct(array $filesystems = []) + { + $this->mountFilesystems($filesystems); + } + + /** + * Mount filesystems. + * + * @param FilesystemInterface[] $filesystems [:prefix => Filesystem,] + * + * @throws InvalidArgumentException + * + * @return $this + */ + public function mountFilesystems(array $filesystems) + { + foreach ($filesystems as $prefix => $filesystem) { + $this->mountFilesystem($prefix, $filesystem); + } + + return $this; + } + + /** + * Mount filesystems. + * + * @param string $prefix + * @param FilesystemInterface $filesystem + * + * @throws InvalidArgumentException + * + * @return $this + */ + public function mountFilesystem($prefix, FilesystemInterface $filesystem) + { + if ( ! is_string($prefix)) { + throw new InvalidArgumentException(__METHOD__ . ' expects argument #1 to be a string.'); + } + + $this->filesystems[$prefix] = $filesystem; + + return $this; + } + + /** + * Get the filesystem with the corresponding prefix. + * + * @param string $prefix + * + * @throws FilesystemNotFoundException + * + * @return FilesystemInterface + */ + public function getFilesystem($prefix) + { + if ( ! isset($this->filesystems[$prefix])) { + throw new FilesystemNotFoundException('No filesystem mounted with prefix ' . $prefix); + } + + return $this->filesystems[$prefix]; + } + + /** + * Retrieve the prefix from an arguments array. + * + * @param array $arguments + * + * @throws InvalidArgumentException + * + * @return array [:prefix, :arguments] + */ + public function filterPrefix(array $arguments) + { + if (empty($arguments)) { + throw new InvalidArgumentException('At least one argument needed'); + } + + $path = array_shift($arguments); + + if ( ! is_string($path)) { + throw new InvalidArgumentException('First argument should be a string'); + } + + list($prefix, $path) = $this->getPrefixAndPath($path); + array_unshift($arguments, $path); + + return [$prefix, $arguments]; + } + + /** + * @param string $directory + * @param bool $recursive + * + * @throws InvalidArgumentException + * @throws FilesystemNotFoundException + * + * @return array + */ + public function listContents($directory = '', $recursive = false) + { + list($prefix, $directory) = $this->getPrefixAndPath($directory); + $filesystem = $this->getFilesystem($prefix); + $result = $filesystem->listContents($directory, $recursive); + + foreach ($result as &$file) { + $file['filesystem'] = $prefix; + } + + return $result; + } + + /** + * Call forwarder. + * + * @param string $method + * @param array $arguments + * + * @throws InvalidArgumentException + * @throws FilesystemNotFoundException + * + * @return mixed + */ + public function __call($method, $arguments) + { + list($prefix, $arguments) = $this->filterPrefix($arguments); + + return $this->invokePluginOnFilesystem($method, $arguments, $prefix); + } + + /** + * @param string $from + * @param string $to + * @param array $config + * + * @throws InvalidArgumentException + * @throws FilesystemNotFoundException + * @throws FileExistsException + * + * @return bool + */ + public function copy($from, $to, array $config = []) + { + list($prefixFrom, $from) = $this->getPrefixAndPath($from); + + $buffer = $this->getFilesystem($prefixFrom)->readStream($from); + + if ($buffer === false) { + return false; + } + + list($prefixTo, $to) = $this->getPrefixAndPath($to); + + $result = $this->getFilesystem($prefixTo)->writeStream($to, $buffer, $config); + + if (is_resource($buffer)) { + fclose($buffer); + } + + return $result; + } + + /** + * List with plugin adapter. + * + * @param array $keys + * @param string $directory + * @param bool $recursive + * + * @throws InvalidArgumentException + * @throws FilesystemNotFoundException + * + * @return array + */ + public function listWith(array $keys = [], $directory = '', $recursive = false) + { + list($prefix, $directory) = $this->getPrefixAndPath($directory); + $arguments = [$keys, $directory, $recursive]; + + return $this->invokePluginOnFilesystem('listWith', $arguments, $prefix); + } + + /** + * Move a file. + * + * @param string $from + * @param string $to + * @param array $config + * + * @throws InvalidArgumentException + * @throws FilesystemNotFoundException + * + * @return bool + */ + public function move($from, $to, array $config = []) + { + list($prefixFrom, $pathFrom) = $this->getPrefixAndPath($from); + list($prefixTo, $pathTo) = $this->getPrefixAndPath($to); + + if ($prefixFrom === $prefixTo) { + $filesystem = $this->getFilesystem($prefixFrom); + $renamed = $filesystem->rename($pathFrom, $pathTo); + + if ($renamed && isset($config['visibility'])) { + return $filesystem->setVisibility($pathTo, $config['visibility']); + } + + return $renamed; + } + + $copied = $this->copy($from, $to, $config); + + if ($copied) { + return $this->delete($from); + } + + return false; + } + + /** + * Invoke a plugin on a filesystem mounted on a given prefix. + * + * @param string $method + * @param array $arguments + * @param string $prefix + * + * @throws FilesystemNotFoundException + * + * @return mixed + */ + public function invokePluginOnFilesystem($method, $arguments, $prefix) + { + $filesystem = $this->getFilesystem($prefix); + + try { + return $this->invokePlugin($method, $arguments, $filesystem); + } catch (PluginNotFoundException $e) { + // Let it pass, it's ok, don't panic. + } + + $callback = [$filesystem, $method]; + + return call_user_func_array($callback, $arguments); + } + + /** + * @param string $path + * + * @throws InvalidArgumentException + * + * @return string[] [:prefix, :path] + */ + protected function getPrefixAndPath($path) + { + if (strpos($path, '://') < 1) { + throw new InvalidArgumentException('No prefix detected in path: ' . $path); + } + + return explode('://', $path, 2); + } + + /** + * Check whether a file exists. + * + * @param string $path + * + * @return bool + */ + public function has($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->has($path); + } + + /** + * Read a file. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The file contents or false on failure. + */ + public function read($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->read($path); + } + + /** + * Retrieves a read-stream for a path. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return resource|false The path resource or false on failure. + */ + public function readStream($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->readStream($path); + } + + /** + * Get a file's metadata. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return array|false The file metadata or false on failure. + */ + public function getMetadata($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->getMetadata($path); + } + + /** + * Get a file's size. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return int|false The file size or false on failure. + */ + public function getSize($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->getSize($path); + } + + /** + * Get a file's mime-type. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The file mime-type or false on failure. + */ + public function getMimetype($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->getMimetype($path); + } + + /** + * Get a file's timestamp. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The timestamp or false on failure. + */ + public function getTimestamp($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->getTimestamp($path); + } + + /** + * Get a file's visibility. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The visibility (public|private) or false on failure. + */ + public function getVisibility($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->getVisibility($path); + } + + /** + * Write a new file. + * + * @param string $path The path of the new file. + * @param string $contents The file contents. + * @param array $config An optional configuration array. + * + * @throws FileExistsException + * + * @return bool True on success, false on failure. + */ + public function write($path, $contents, array $config = []) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->write($path, $contents, $config); + } + + /** + * Write a new file using a stream. + * + * @param string $path The path of the new file. + * @param resource $resource The file handle. + * @param array $config An optional configuration array. + * + * @throws InvalidArgumentException If $resource is not a file handle. + * @throws FileExistsException + * + * @return bool True on success, false on failure. + */ + public function writeStream($path, $resource, array $config = []) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->writeStream($path, $resource, $config); + } + + /** + * Update an existing file. + * + * @param string $path The path of the existing file. + * @param string $contents The file contents. + * @param array $config An optional configuration array. + * + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function update($path, $contents, array $config = []) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->update($path, $contents, $config); + } + + /** + * Update an existing file using a stream. + * + * @param string $path The path of the existing file. + * @param resource $resource The file handle. + * @param array $config An optional configuration array. + * + * @throws InvalidArgumentException If $resource is not a file handle. + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function updateStream($path, $resource, array $config = []) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->updateStream($path, $resource, $config); + } + + /** + * Rename a file. + * + * @param string $path Path to the existing file. + * @param string $newpath The new path of the file. + * + * @throws FileExistsException Thrown if $newpath exists. + * @throws FileNotFoundException Thrown if $path does not exist. + * + * @return bool True on success, false on failure. + */ + public function rename($path, $newpath) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->rename($path, $newpath); + } + + /** + * Delete a file. + * + * @param string $path + * + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function delete($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->delete($path); + } + + /** + * Delete a directory. + * + * @param string $dirname + * + * @throws RootViolationException Thrown if $dirname is empty. + * + * @return bool True on success, false on failure. + */ + public function deleteDir($dirname) + { + list($prefix, $dirname) = $this->getPrefixAndPath($dirname); + + return $this->getFilesystem($prefix)->deleteDir($dirname); + } + + /** + * Create a directory. + * + * @param string $dirname The name of the new directory. + * @param array $config An optional configuration array. + * + * @return bool True on success, false on failure. + */ + public function createDir($dirname, array $config = []) + { + list($prefix, $dirname) = $this->getPrefixAndPath($dirname); + + return $this->getFilesystem($prefix)->createDir($dirname); + } + + /** + * Set the visibility for a file. + * + * @param string $path The path to the file. + * @param string $visibility One of 'public' or 'private'. + * + * @throws FileNotFoundException + * + * @return bool True on success, false on failure. + */ + public function setVisibility($path, $visibility) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->setVisibility($path, $visibility); + } + + /** + * Create a file or update if exists. + * + * @param string $path The path to the file. + * @param string $contents The file contents. + * @param array $config An optional configuration array. + * + * @return bool True on success, false on failure. + */ + public function put($path, $contents, array $config = []) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->put($path, $contents, $config); + } + + /** + * Create a file or update if exists. + * + * @param string $path The path to the file. + * @param resource $resource The file handle. + * @param array $config An optional configuration array. + * + * @throws InvalidArgumentException Thrown if $resource is not a resource. + * + * @return bool True on success, false on failure. + */ + public function putStream($path, $resource, array $config = []) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->putStream($path, $resource, $config); + } + + /** + * Read and delete a file. + * + * @param string $path The path to the file. + * + * @throws FileNotFoundException + * + * @return string|false The file contents, or false on failure. + */ + public function readAndDelete($path) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->readAndDelete($path); + } + + /** + * Get a file/directory handler. + * + * @deprecated + * + * @param string $path The path to the file. + * @param Handler $handler An optional existing handler to populate. + * + * @return Handler Either a file or directory handler. + */ + public function get($path, Handler $handler = null) + { + list($prefix, $path) = $this->getPrefixAndPath($path); + + return $this->getFilesystem($prefix)->get($path); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/NotSupportedException.php b/php/libraries/composer/vendor/league/flysystem/src/NotSupportedException.php new file mode 100644 index 0000000..e0a989b --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/NotSupportedException.php @@ -0,0 +1,37 @@ +<?php + +namespace League\Flysystem; + +use RuntimeException; +use SplFileInfo; + +class NotSupportedException extends RuntimeException implements FilesystemException +{ + /** + * Create a new exception for a link. + * + * @param SplFileInfo $file + * + * @return static + */ + public static function forLink(SplFileInfo $file) + { + $message = 'Links are not supported, encountered link at '; + + return new static($message . $file->getPathname()); + } + + /** + * Create a new exception for a link. + * + * @param string $systemType + * + * @return static + */ + public static function forFtpSystemType($systemType) + { + $message = "The FTP system type '$systemType' is currently not supported."; + + return new static($message); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/AbstractPlugin.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/AbstractPlugin.php new file mode 100644 index 0000000..0d56789 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/AbstractPlugin.php @@ -0,0 +1,24 @@ +<?php + +namespace League\Flysystem\Plugin; + +use League\Flysystem\FilesystemInterface; +use League\Flysystem\PluginInterface; + +abstract class AbstractPlugin implements PluginInterface +{ + /** + * @var FilesystemInterface + */ + protected $filesystem; + + /** + * Set the Filesystem object. + * + * @param FilesystemInterface $filesystem + */ + public function setFilesystem(FilesystemInterface $filesystem) + { + $this->filesystem = $filesystem; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/EmptyDir.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/EmptyDir.php new file mode 100644 index 0000000..b5ae7f5 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/EmptyDir.php @@ -0,0 +1,34 @@ +<?php + +namespace League\Flysystem\Plugin; + +class EmptyDir extends AbstractPlugin +{ + /** + * Get the method name. + * + * @return string + */ + public function getMethod() + { + return 'emptyDir'; + } + + /** + * Empty a directory's contents. + * + * @param string $dirname + */ + public function handle($dirname) + { + $listing = $this->filesystem->listContents($dirname, false); + + foreach ($listing as $item) { + if ($item['type'] === 'dir') { + $this->filesystem->deleteDir($item['path']); + } else { + $this->filesystem->delete($item['path']); + } + } + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/ForcedCopy.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ForcedCopy.php new file mode 100644 index 0000000..a41e9f3 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ForcedCopy.php @@ -0,0 +1,44 @@ +<?php + +namespace League\Flysystem\Plugin; + +use League\Flysystem\FileExistsException; +use League\Flysystem\FileNotFoundException; + +class ForcedCopy extends AbstractPlugin +{ + /** + * @inheritdoc + */ + public function getMethod() + { + return 'forceCopy'; + } + + /** + * Copies a file, overwriting any existing files. + * + * @param string $path Path to the existing file. + * @param string $newpath The new path of the file. + * + * @throws FileExistsException + * @throws FileNotFoundException Thrown if $path does not exist. + * + * @return bool True on success, false on failure. + */ + public function handle($path, $newpath) + { + try { + $deleted = $this->filesystem->delete($newpath); + } catch (FileNotFoundException $e) { + // The destination path does not exist. That's ok. + $deleted = true; + } + + if ($deleted) { + return $this->filesystem->copy($path, $newpath); + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/ForcedRename.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ForcedRename.php new file mode 100644 index 0000000..3f51cd6 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ForcedRename.php @@ -0,0 +1,44 @@ +<?php + +namespace League\Flysystem\Plugin; + +use League\Flysystem\FileExistsException; +use League\Flysystem\FileNotFoundException; + +class ForcedRename extends AbstractPlugin +{ + /** + * @inheritdoc + */ + public function getMethod() + { + return 'forceRename'; + } + + /** + * Renames a file, overwriting the destination if it exists. + * + * @param string $path Path to the existing file. + * @param string $newpath The new path of the file. + * + * @throws FileNotFoundException Thrown if $path does not exist. + * @throws FileExistsException + * + * @return bool True on success, false on failure. + */ + public function handle($path, $newpath) + { + try { + $deleted = $this->filesystem->delete($newpath); + } catch (FileNotFoundException $e) { + // The destination path does not exist. That's ok. + $deleted = true; + } + + if ($deleted) { + return $this->filesystem->rename($path, $newpath); + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/GetWithMetadata.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/GetWithMetadata.php new file mode 100644 index 0000000..6fe4f05 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/GetWithMetadata.php @@ -0,0 +1,51 @@ +<?php + +namespace League\Flysystem\Plugin; + +use InvalidArgumentException; +use League\Flysystem\FileNotFoundException; + +class GetWithMetadata extends AbstractPlugin +{ + /** + * Get the method name. + * + * @return string + */ + public function getMethod() + { + return 'getWithMetadata'; + } + + /** + * Get metadata for an object with required metadata. + * + * @param string $path path to file + * @param array $metadata metadata keys + * + * @throws InvalidArgumentException + * @throws FileNotFoundException + * + * @return array|false metadata + */ + public function handle($path, array $metadata) + { + $object = $this->filesystem->getMetadata($path); + + if ( ! $object) { + return false; + } + + $keys = array_diff($metadata, array_keys($object)); + + foreach ($keys as $key) { + if ( ! method_exists($this->filesystem, $method = 'get' . ucfirst($key))) { + throw new InvalidArgumentException('Could not fetch metadata: ' . $key); + } + + $object[$key] = $this->filesystem->{$method}($path); + } + + return $object; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListFiles.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListFiles.php new file mode 100644 index 0000000..9669fe7 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListFiles.php @@ -0,0 +1,35 @@ +<?php + +namespace League\Flysystem\Plugin; + +class ListFiles extends AbstractPlugin +{ + /** + * Get the method name. + * + * @return string + */ + public function getMethod() + { + return 'listFiles'; + } + + /** + * List all files in the directory. + * + * @param string $directory + * @param bool $recursive + * + * @return array + */ + public function handle($directory = '', $recursive = false) + { + $contents = $this->filesystem->listContents($directory, $recursive); + + $filter = function ($object) { + return $object['type'] === 'file'; + }; + + return array_values(array_filter($contents, $filter)); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListPaths.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListPaths.php new file mode 100644 index 0000000..514bdf0 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListPaths.php @@ -0,0 +1,36 @@ +<?php + +namespace League\Flysystem\Plugin; + +class ListPaths extends AbstractPlugin +{ + /** + * Get the method name. + * + * @return string + */ + public function getMethod() + { + return 'listPaths'; + } + + /** + * List all paths. + * + * @param string $directory + * @param bool $recursive + * + * @return array paths + */ + public function handle($directory = '', $recursive = false) + { + $result = []; + $contents = $this->filesystem->listContents($directory, $recursive); + + foreach ($contents as $object) { + $result[] = $object['path']; + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListWith.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListWith.php new file mode 100644 index 0000000..d90464e --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/ListWith.php @@ -0,0 +1,60 @@ +<?php + +namespace League\Flysystem\Plugin; + +class ListWith extends AbstractPlugin +{ + /** + * Get the method name. + * + * @return string + */ + public function getMethod() + { + return 'listWith'; + } + + /** + * List contents with metadata. + * + * @param array $keys + * @param string $directory + * @param bool $recursive + * + * @return array listing with metadata + */ + public function handle(array $keys = [], $directory = '', $recursive = false) + { + $contents = $this->filesystem->listContents($directory, $recursive); + + foreach ($contents as $index => $object) { + if ($object['type'] === 'file') { + $missingKeys = array_diff($keys, array_keys($object)); + $contents[$index] = array_reduce($missingKeys, [$this, 'getMetadataByName'], $object); + } + } + + return $contents; + } + + /** + * Get a meta-data value by key name. + * + * @param array $object + * @param string $key + * + * @return array + */ + protected function getMetadataByName(array $object, $key) + { + $method = 'get' . ucfirst($key); + + if ( ! method_exists($this->filesystem, $method)) { + throw new \InvalidArgumentException('Could not get meta-data for key: ' . $key); + } + + $object[$key] = $this->filesystem->{$method}($object['path']); + + return $object; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/PluggableTrait.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/PluggableTrait.php new file mode 100644 index 0000000..922edfe --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/PluggableTrait.php @@ -0,0 +1,97 @@ +<?php + +namespace League\Flysystem\Plugin; + +use BadMethodCallException; +use League\Flysystem\FilesystemInterface; +use League\Flysystem\PluginInterface; +use LogicException; + +trait PluggableTrait +{ + /** + * @var array + */ + protected $plugins = []; + + /** + * Register a plugin. + * + * @param PluginInterface $plugin + * + * @throws LogicException + * + * @return $this + */ + public function addPlugin(PluginInterface $plugin) + { + if ( ! method_exists($plugin, 'handle')) { + throw new LogicException(get_class($plugin) . ' does not have a handle method.'); + } + + $this->plugins[$plugin->getMethod()] = $plugin; + + return $this; + } + + /** + * Find a specific plugin. + * + * @param string $method + * + * @throws PluginNotFoundException + * + * @return PluginInterface + */ + protected function findPlugin($method) + { + if ( ! isset($this->plugins[$method])) { + throw new PluginNotFoundException('Plugin not found for method: ' . $method); + } + + return $this->plugins[$method]; + } + + /** + * Invoke a plugin by method name. + * + * @param string $method + * @param array $arguments + * @param FilesystemInterface $filesystem + * + * @throws PluginNotFoundException + * + * @return mixed + */ + protected function invokePlugin($method, array $arguments, FilesystemInterface $filesystem) + { + $plugin = $this->findPlugin($method); + $plugin->setFilesystem($filesystem); + $callback = [$plugin, 'handle']; + + return call_user_func_array($callback, $arguments); + } + + /** + * Plugins pass-through. + * + * @param string $method + * @param array $arguments + * + * @throws BadMethodCallException + * + * @return mixed + */ + public function __call($method, array $arguments) + { + try { + return $this->invokePlugin($method, $arguments, $this); + } catch (PluginNotFoundException $e) { + throw new BadMethodCallException( + 'Call to undefined method ' + . get_class($this) + . '::' . $method + ); + } + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Plugin/PluginNotFoundException.php b/php/libraries/composer/vendor/league/flysystem/src/Plugin/PluginNotFoundException.php new file mode 100644 index 0000000..fd1d7e7 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Plugin/PluginNotFoundException.php @@ -0,0 +1,10 @@ +<?php + +namespace League\Flysystem\Plugin; + +use LogicException; + +class PluginNotFoundException extends LogicException +{ + // This exception doesn't require additional information. +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/PluginInterface.php b/php/libraries/composer/vendor/league/flysystem/src/PluginInterface.php new file mode 100644 index 0000000..7010a35 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/PluginInterface.php @@ -0,0 +1,20 @@ +<?php + +namespace League\Flysystem; + +interface PluginInterface +{ + /** + * Get the method name. + * + * @return string + */ + public function getMethod(); + + /** + * Set the Filesystem object. + * + * @param FilesystemInterface $filesystem + */ + public function setFilesystem(FilesystemInterface $filesystem); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/ReadInterface.php b/php/libraries/composer/vendor/league/flysystem/src/ReadInterface.php new file mode 100644 index 0000000..898a8d5 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/ReadInterface.php @@ -0,0 +1,88 @@ +<?php + +namespace League\Flysystem; + +interface ReadInterface +{ + /** + * Check whether a file exists. + * + * @param string $path + * + * @return array|bool|null + */ + public function has($path); + + /** + * Read a file. + * + * @param string $path + * + * @return array|false + */ + public function read($path); + + /** + * Read a file as a stream. + * + * @param string $path + * + * @return array|false + */ + public function readStream($path); + + /** + * List contents of a directory. + * + * @param string $directory + * @param bool $recursive + * + * @return array + */ + public function listContents($directory = '', $recursive = false); + + /** + * Get all the meta data of a file or directory. + * + * @param string $path + * + * @return array|false + */ + public function getMetadata($path); + + /** + * Get the size of a file. + * + * @param string $path + * + * @return array|false + */ + public function getSize($path); + + /** + * Get the mimetype of a file. + * + * @param string $path + * + * @return array|false + */ + public function getMimetype($path); + + /** + * Get the last modified time of a file as a timestamp. + * + * @param string $path + * + * @return array|false + */ + public function getTimestamp($path); + + /** + * Get the visibility of a file. + * + * @param string $path + * + * @return array|false + */ + public function getVisibility($path); +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/RootViolationException.php b/php/libraries/composer/vendor/league/flysystem/src/RootViolationException.php new file mode 100644 index 0000000..073fc92 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/RootViolationException.php @@ -0,0 +1,10 @@ +<?php + +namespace League\Flysystem; + +use LogicException; + +class RootViolationException extends LogicException implements FilesystemException +{ + // +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/SafeStorage.php b/php/libraries/composer/vendor/league/flysystem/src/SafeStorage.php new file mode 100644 index 0000000..5397f58 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/SafeStorage.php @@ -0,0 +1,39 @@ +<?php + +namespace League\Flysystem; + +final class SafeStorage +{ + /** + * @var string + */ + private $hash; + + /** + * @var array + */ + protected static $safeStorage = []; + + public function __construct() + { + $this->hash = spl_object_hash($this); + static::$safeStorage[$this->hash] = []; + } + + public function storeSafely($key, $value) + { + static::$safeStorage[$this->hash][$key] = $value; + } + + public function retrieveSafely($key) + { + if (array_key_exists($key, static::$safeStorage[$this->hash])) { + return static::$safeStorage[$this->hash][$key]; + } + } + + public function __destruct() + { + unset(static::$safeStorage[$this->hash]); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/UnreadableFileException.php b/php/libraries/composer/vendor/league/flysystem/src/UnreadableFileException.php new file mode 100644 index 0000000..e668033 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/UnreadableFileException.php @@ -0,0 +1,18 @@ +<?php + +namespace League\Flysystem; + +use SplFileInfo; + +class UnreadableFileException extends Exception +{ + public static function forFileInfo(SplFileInfo $fileInfo) + { + return new static( + sprintf( + 'Unreadable file encountered: %s', + $fileInfo->getRealPath() + ) + ); + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Util.php b/php/libraries/composer/vendor/league/flysystem/src/Util.php new file mode 100644 index 0000000..76454a0 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Util.php @@ -0,0 +1,353 @@ +<?php + +namespace League\Flysystem; + +use League\Flysystem\Util\MimeType; +use LogicException; + +class Util +{ + /** + * Get normalized pathinfo. + * + * @param string $path + * + * @return array pathinfo + */ + public static function pathinfo($path) + { + $pathinfo = compact('path'); + + if ('' !== $dirname = dirname($path)) { + $pathinfo['dirname'] = static::normalizeDirname($dirname); + } + + $pathinfo['basename'] = static::basename($path); + + $pathinfo += pathinfo($pathinfo['basename']); + + return $pathinfo + ['dirname' => '']; + } + + /** + * Normalize a dirname return value. + * + * @param string $dirname + * + * @return string normalized dirname + */ + public static function normalizeDirname($dirname) + { + return $dirname === '.' ? '' : $dirname; + } + + /** + * Get a normalized dirname from a path. + * + * @param string $path + * + * @return string dirname + */ + public static function dirname($path) + { + return static::normalizeDirname(dirname($path)); + } + + /** + * Map result arrays. + * + * @param array $object + * @param array $map + * + * @return array mapped result + */ + public static function map(array $object, array $map) + { + $result = []; + + foreach ($map as $from => $to) { + if ( ! isset($object[$from])) { + continue; + } + + $result[$to] = $object[$from]; + } + + return $result; + } + + /** + * Normalize path. + * + * @param string $path + * + * @throws LogicException + * + * @return string + */ + public static function normalizePath($path) + { + return static::normalizeRelativePath($path); + } + + /** + * Normalize relative directories in a path. + * + * @param string $path + * + * @throws LogicException + * + * @return string + */ + public static function normalizeRelativePath($path) + { + $path = str_replace('\\', '/', $path); + $path = static::removeFunkyWhiteSpace($path); + + $parts = []; + + foreach (explode('/', $path) as $part) { + switch ($part) { + case '': + case '.': + break; + + case '..': + if (empty($parts)) { + throw new LogicException( + 'Path is outside of the defined root, path: [' . $path . ']' + ); + } + array_pop($parts); + break; + + default: + $parts[] = $part; + break; + } + } + + return implode('/', $parts); + } + + /** + * Removes unprintable characters and invalid unicode characters. + * + * @param string $path + * + * @return string $path + */ + protected static function removeFunkyWhiteSpace($path) + { + // We do this check in a loop, since removing invalid unicode characters + // can lead to new characters being created. + while (preg_match('#\p{C}+|^\./#u', $path)) { + $path = preg_replace('#\p{C}+|^\./#u', '', $path); + } + + return $path; + } + + /** + * Normalize prefix. + * + * @param string $prefix + * @param string $separator + * + * @return string normalized path + */ + public static function normalizePrefix($prefix, $separator) + { + return rtrim($prefix, $separator) . $separator; + } + + /** + * Get content size. + * + * @param string $contents + * + * @return int content size + */ + public static function contentSize($contents) + { + return defined('MB_OVERLOAD_STRING') ? mb_strlen($contents, '8bit') : strlen($contents); + } + + /** + * Guess MIME Type based on the path of the file and it's content. + * + * @param string $path + * @param string|resource $content + * + * @return string|null MIME Type or NULL if no extension detected + */ + public static function guessMimeType($path, $content) + { + $mimeType = MimeType::detectByContent($content); + + if ( ! (empty($mimeType) || in_array($mimeType, ['application/x-empty', 'text/plain', 'text/x-asm']))) { + return $mimeType; + } + + return MimeType::detectByFilename($path); + } + + /** + * Emulate directories. + * + * @param array $listing + * + * @return array listing with emulated directories + */ + public static function emulateDirectories(array $listing) + { + $directories = []; + $listedDirectories = []; + + foreach ($listing as $object) { + list($directories, $listedDirectories) = static::emulateObjectDirectories($object, $directories, $listedDirectories); + } + + $directories = array_diff(array_unique($directories), array_unique($listedDirectories)); + + foreach ($directories as $directory) { + $listing[] = static::pathinfo($directory) + ['type' => 'dir']; + } + + return $listing; + } + + /** + * Ensure a Config instance. + * + * @param null|array|Config $config + * + * @return Config config instance + * + * @throw LogicException + */ + public static function ensureConfig($config) + { + if ($config === null) { + return new Config(); + } + + if ($config instanceof Config) { + return $config; + } + + if (is_array($config)) { + return new Config($config); + } + + throw new LogicException('A config should either be an array or a Flysystem\Config object.'); + } + + /** + * Rewind a stream. + * + * @param resource $resource + */ + public static function rewindStream($resource) + { + if (ftell($resource) !== 0 && static::isSeekableStream($resource)) { + rewind($resource); + } + } + + public static function isSeekableStream($resource) + { + $metadata = stream_get_meta_data($resource); + + return $metadata['seekable']; + } + + /** + * Get the size of a stream. + * + * @param resource $resource + * + * @return int|null stream size + */ + public static function getStreamSize($resource) + { + $stat = fstat($resource); + + if ( ! is_array($stat) || ! isset($stat['size'])) { + return null; + } + + return $stat['size']; + } + + /** + * Emulate the directories of a single object. + * + * @param array $object + * @param array $directories + * @param array $listedDirectories + * + * @return array + */ + protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories) + { + if ($object['type'] === 'dir') { + $listedDirectories[] = $object['path']; + } + + if ( ! isset($object['dirname']) || trim($object['dirname']) === '') { + return [$directories, $listedDirectories]; + } + + $parent = $object['dirname']; + + while (isset($parent) && trim($parent) !== '' && ! in_array($parent, $directories)) { + $directories[] = $parent; + $parent = static::dirname($parent); + } + + if (isset($object['type']) && $object['type'] === 'dir') { + $listedDirectories[] = $object['path']; + + return [$directories, $listedDirectories]; + } + + return [$directories, $listedDirectories]; + } + + /** + * Returns the trailing name component of the path. + * + * @param string $path + * + * @return string + */ + private static function basename($path) + { + $separators = DIRECTORY_SEPARATOR === '/' ? '/' : '\/'; + + $path = rtrim($path, $separators); + + $basename = preg_replace('#.*?([^' . preg_quote($separators, '#') . ']+$)#', '$1', $path); + + if (DIRECTORY_SEPARATOR === '/') { + return $basename; + } + // @codeCoverageIgnoreStart + // Extra Windows path munging. This is tested via AppVeyor, but code + // coverage is not reported. + + // Handle relative paths with drive letters. c:file.txt. + while (preg_match('#^[a-zA-Z]{1}:[^\\\/]#', $basename)) { + $basename = substr($basename, 2); + } + + // Remove colon for standalone drive letter names. + if (preg_match('#^[a-zA-Z]{1}:$#', $basename)) { + $basename = rtrim($basename, ':'); + } + + return $basename; + // @codeCoverageIgnoreEnd + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Util/ContentListingFormatter.php b/php/libraries/composer/vendor/league/flysystem/src/Util/ContentListingFormatter.php new file mode 100644 index 0000000..ae0d3b9 --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Util/ContentListingFormatter.php @@ -0,0 +1,122 @@ +<?php + +namespace League\Flysystem\Util; + +use League\Flysystem\Util; + +/** + * @internal + */ +class ContentListingFormatter +{ + /** + * @var string + */ + private $directory; + + /** + * @var bool + */ + private $recursive; + + /** + * @var bool + */ + private $caseSensitive; + + /** + * @param string $directory + * @param bool $recursive + */ + public function __construct($directory, $recursive, $caseSensitive = true) + { + $this->directory = rtrim($directory, '/'); + $this->recursive = $recursive; + $this->caseSensitive = $caseSensitive; + } + + /** + * Format contents listing. + * + * @param array $listing + * + * @return array + */ + public function formatListing(array $listing) + { + $listing = array_filter(array_map([$this, 'addPathInfo'], $listing), [$this, 'isEntryOutOfScope']); + + return $this->sortListing(array_values($listing)); + } + + private function addPathInfo(array $entry) + { + return $entry + Util::pathinfo($entry['path']); + } + + /** + * Determine if the entry is out of scope. + * + * @param array $entry + * + * @return bool + */ + private function isEntryOutOfScope(array $entry) + { + if (empty($entry['path']) && $entry['path'] !== '0') { + return false; + } + + if ($this->recursive) { + return $this->residesInDirectory($entry); + } + + return $this->isDirectChild($entry); + } + + /** + * Check if the entry resides within the parent directory. + * + * @param array $entry + * + * @return bool + */ + private function residesInDirectory(array $entry) + { + if ($this->directory === '') { + return true; + } + + return $this->caseSensitive + ? strpos($entry['path'], $this->directory . '/') === 0 + : stripos($entry['path'], $this->directory . '/') === 0; + } + + /** + * Check if the entry is a direct child of the directory. + * + * @param array $entry + * + * @return bool + */ + private function isDirectChild(array $entry) + { + return $this->caseSensitive + ? $entry['dirname'] === $this->directory + : strcasecmp($this->directory, $entry['dirname']) === 0; + } + + /** + * @param array $listing + * + * @return array + */ + private function sortListing(array $listing) + { + usort($listing, function ($a, $b) { + return strcasecmp($a['path'], $b['path']); + }); + + return $listing; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Util/MimeType.php b/php/libraries/composer/vendor/league/flysystem/src/Util/MimeType.php new file mode 100644 index 0000000..35cba3f --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Util/MimeType.php @@ -0,0 +1,80 @@ +<?php + +namespace League\Flysystem\Util; + +use League\MimeTypeDetection\FinfoMimeTypeDetector; +use League\MimeTypeDetection\GeneratedExtensionToMimeTypeMap; +use League\MimeTypeDetection\MimeTypeDetector; + +/** + * @internal + */ +class MimeType +{ + protected static $extensionToMimeTypeMap = GeneratedExtensionToMimeTypeMap::MIME_TYPES_FOR_EXTENSIONS; + protected static $detector; + + public static function useDetector(MimeTypeDetector $detector) + { + static::$detector = $detector; + } + + /** + * @return MimeTypeDetector + */ + protected static function detector() + { + if ( ! static::$detector instanceof MimeTypeDetector) { + static::$detector = new FinfoMimeTypeDetector(); + } + + return static::$detector; + } + + + /** + * Detects MIME Type based on given content. + * + * @param mixed $content + * + * @return string MIME Type + */ + public static function detectByContent($content) + { + if (is_string($content)) { + return static::detector()->detectMimeTypeFromBuffer($content); + } + + return 'text/plain'; + } + + /** + * Detects MIME Type based on file extension. + * + * @param string $extension + * + * @return string MIME Type + */ + public static function detectByFileExtension($extension) + { + return static::detector()->detectMimeTypeFromPath('artificial.' . $extension) ?: 'text/plain'; + } + + /** + * @param string $filename + * + * @return string MIME Type + */ + public static function detectByFilename($filename) + { + return static::detector()->detectMimeTypeFromPath($filename) ?: 'text/plain'; + } + + /** + * @return array Map of file extension to MIME Type + */ + public static function getExtensionToMimeTypeMap() + { + return static::$extensionToMimeTypeMap; + } +} diff --git a/php/libraries/composer/vendor/league/flysystem/src/Util/StreamHasher.php b/php/libraries/composer/vendor/league/flysystem/src/Util/StreamHasher.php new file mode 100644 index 0000000..938ec5d --- /dev/null +++ b/php/libraries/composer/vendor/league/flysystem/src/Util/StreamHasher.php @@ -0,0 +1,36 @@ +<?php + +namespace League\Flysystem\Util; + +class StreamHasher +{ + /** + * @var string + */ + private $algo; + + /** + * StreamHasher constructor. + * + * @param string $algo + */ + public function __construct($algo) + { + $this->algo = $algo; + } + + /** + * @param resource $resource + * + * @return string + */ + public function hash($resource) + { + rewind($resource); + $context = hash_init($this->algo); + hash_update_stream($context, $resource); + fclose($resource); + + return hash_final($context); + } +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/CHANGELOG.md b/php/libraries/composer/vendor/league/mime-type-detection/CHANGELOG.md new file mode 100644 index 0000000..a45872a --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/CHANGELOG.md @@ -0,0 +1,59 @@ +# Changelog + +## 1.15.0 - 2024-01-28 + +- Updated lookup + +## 1.14.0 - 2022-10-17 + +### Updated + +- Updated lookup + +## 1.13.0 - 2023-08-05 + +### Added + +- A reverse lookup mechanism to fetch one or all extensions for a given mimetype + +## 1.12.0 - 2023-08-03 + +### Updated + +- Updated lookup + +## 1.11.0 - 2023-04-17 + +### Updated + +- Updated lookup + +## 1.10.0 - 2022-04-11 + +### Fixed + +- Added Flysystem v1 inconclusive mime-types and made it configurable as a constructor parameter. + +## 1.9.0 - 2021-11-21 + +### Updated + +- Updated lookup + +## 1.8.0 - 2021-09-25 + +### Added + +- Added the decorator `OverridingExtensionToMimeTypeMap` which allows you to override values. + +## 1.7.0 - 2021-01-18 + +### Added + +- Added a `bufferSampleSize` parameter to the `FinfoMimeTypeDetector` class that allows you to send a reduced content sample which costs less memory. + +## 1.6.0 - 2021-01-18 + +### Changes + +- Updated generated mime-type map diff --git a/php/libraries/composer/vendor/league/mime-type-detection/LICENSE b/php/libraries/composer/vendor/league/mime-type-detection/LICENSE new file mode 100644 index 0000000..39d50b5 --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2023 Frank de Jonge + +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/php/libraries/composer/vendor/league/mime-type-detection/composer.json b/php/libraries/composer/vendor/league/mime-type-detection/composer.json new file mode 100644 index 0000000..cd75bee --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/composer.json @@ -0,0 +1,34 @@ +{ + "name": "league/mime-type-detection", + "description": "Mime-type detection for Flysystem", + "license": "MIT", + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "scripts": { + "test": "vendor/bin/phpunit", + "phpstan": "vendor/bin/phpstan analyse -l 6 src" + }, + "require": { + "php": "^7.4 || ^8.0", + "ext-fileinfo": "*" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.8 || ^9.3 || ^10.0", + "phpstan/phpstan": "^0.12.68", + "friendsofphp/php-cs-fixer": "^3.2" + }, + "autoload": { + "psr-4": { + "League\\MimeTypeDetection\\": "src" + } + }, + "config": { + "platform": { + "php": "7.4.0" + } + } +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/EmptyExtensionToMimeTypeMap.php b/php/libraries/composer/vendor/league/mime-type-detection/src/EmptyExtensionToMimeTypeMap.php new file mode 100644 index 0000000..fc04241 --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/EmptyExtensionToMimeTypeMap.php @@ -0,0 +1,13 @@ +<?php + +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +class EmptyExtensionToMimeTypeMap implements ExtensionToMimeTypeMap +{ + public function lookupMimeType(string $extension): ?string + { + return null; + } +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionLookup.php b/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionLookup.php new file mode 100644 index 0000000..14b89df --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionLookup.php @@ -0,0 +1,14 @@ +<?php +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +interface ExtensionLookup +{ + public function lookupExtension(string $mimetype): ?string; + + /** + * @return string[] + */ + public function lookupAllExtensions(string $mimetype): array; +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionMimeTypeDetector.php b/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionMimeTypeDetector.php new file mode 100644 index 0000000..cd34462 --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionMimeTypeDetector.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +use const PATHINFO_EXTENSION; + +class ExtensionMimeTypeDetector implements MimeTypeDetector, ExtensionLookup +{ + /** + * @var ExtensionToMimeTypeMap + */ + private $extensions; + + public function __construct(ExtensionToMimeTypeMap $extensions = null) + { + $this->extensions = $extensions ?: new GeneratedExtensionToMimeTypeMap(); + } + + public function detectMimeType(string $path, $contents): ?string + { + return $this->detectMimeTypeFromPath($path); + } + + public function detectMimeTypeFromPath(string $path): ?string + { + $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + + return $this->extensions->lookupMimeType($extension); + } + + public function detectMimeTypeFromFile(string $path): ?string + { + return $this->detectMimeTypeFromPath($path); + } + + public function detectMimeTypeFromBuffer(string $contents): ?string + { + return null; + } + + public function lookupExtension(string $mimetype): ?string + { + return $this->extensions instanceof ExtensionLookup + ? $this->extensions->lookupExtension($mimetype) + : null; + } + + public function lookupAllExtensions(string $mimetype): array + { + return $this->extensions instanceof ExtensionLookup + ? $this->extensions->lookupAllExtensions($mimetype) + : []; + } +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionToMimeTypeMap.php b/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionToMimeTypeMap.php new file mode 100644 index 0000000..1dad7bc --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/ExtensionToMimeTypeMap.php @@ -0,0 +1,10 @@ +<?php + +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +interface ExtensionToMimeTypeMap +{ + public function lookupMimeType(string $extension): ?string; +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/FinfoMimeTypeDetector.php b/php/libraries/composer/vendor/league/mime-type-detection/src/FinfoMimeTypeDetector.php new file mode 100644 index 0000000..8084f92 --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/FinfoMimeTypeDetector.php @@ -0,0 +1,106 @@ +<?php + +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +use const FILEINFO_MIME_TYPE; + +use const PATHINFO_EXTENSION; +use finfo; + +class FinfoMimeTypeDetector implements MimeTypeDetector, ExtensionLookup +{ + private const INCONCLUSIVE_MIME_TYPES = [ + 'application/x-empty', + 'text/plain', + 'text/x-asm', + 'application/octet-stream', + 'inode/x-empty', + ]; + + /** + * @var finfo + */ + private $finfo; + + /** + * @var ExtensionToMimeTypeMap + */ + private $extensionMap; + + /** + * @var int|null + */ + private $bufferSampleSize; + + /** + * @var array<string> + */ + private $inconclusiveMimetypes; + + public function __construct( + string $magicFile = '', + ExtensionToMimeTypeMap $extensionMap = null, + ?int $bufferSampleSize = null, + array $inconclusiveMimetypes = self::INCONCLUSIVE_MIME_TYPES + ) { + $this->finfo = new finfo(FILEINFO_MIME_TYPE, $magicFile); + $this->extensionMap = $extensionMap ?: new GeneratedExtensionToMimeTypeMap(); + $this->bufferSampleSize = $bufferSampleSize; + $this->inconclusiveMimetypes = $inconclusiveMimetypes; + } + + public function detectMimeType(string $path, $contents): ?string + { + $mimeType = is_string($contents) + ? (@$this->finfo->buffer($this->takeSample($contents)) ?: null) + : null; + + if ($mimeType !== null && ! in_array($mimeType, $this->inconclusiveMimetypes)) { + return $mimeType; + } + + return $this->detectMimeTypeFromPath($path); + } + + public function detectMimeTypeFromPath(string $path): ?string + { + $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + + return $this->extensionMap->lookupMimeType($extension); + } + + public function detectMimeTypeFromFile(string $path): ?string + { + return @$this->finfo->file($path) ?: null; + } + + public function detectMimeTypeFromBuffer(string $contents): ?string + { + return @$this->finfo->buffer($this->takeSample($contents)) ?: null; + } + + private function takeSample(string $contents): string + { + if ($this->bufferSampleSize === null) { + return $contents; + } + + return (string) substr($contents, 0, $this->bufferSampleSize); + } + + public function lookupExtension(string $mimetype): ?string + { + return $this->extensionMap instanceof ExtensionLookup + ? $this->extensionMap->lookupExtension($mimetype) + : null; + } + + public function lookupAllExtensions(string $mimetype): array + { + return $this->extensionMap instanceof ExtensionLookup + ? $this->extensionMap->lookupAllExtensions($mimetype) + : []; + } +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/GeneratedExtensionToMimeTypeMap.php b/php/libraries/composer/vendor/league/mime-type-detection/src/GeneratedExtensionToMimeTypeMap.php new file mode 100644 index 0000000..1ce1791 --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/GeneratedExtensionToMimeTypeMap.php @@ -0,0 +1,2298 @@ +<?php + +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +class GeneratedExtensionToMimeTypeMap implements ExtensionToMimeTypeMap, ExtensionLookup +{ + /** + * @var array<string, string> + * + * @internal + */ + public const MIME_TYPES_FOR_EXTENSIONS = [ + '1km' => 'application/vnd.1000minds.decision-model+xml', + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gp', + '3gpp' => 'video/3gpp', + '3mf' => 'model/3mf', + '7z' => 'application/x-7z-compressed', + '7zip' => 'application/x-7z-compressed', + '123' => 'application/vnd.lotus-1-2-3', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/acc', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/vnd.nokia.n-gage.ac+xml', + 'ac3' => 'audio/ac3', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'adts' => 'audio/aac', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'age' => 'application/vnd.age', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/pdf', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'aml' => 'application/automationml-aml+xml', + 'amlx' => 'application/automationml-amlx+zip', + 'amr' => 'audio/amr', + 'apk' => 'application/vnd.android.package-archive', + 'apng' => 'image/apng', + 'appcache' => 'text/cache-manifest', + 'appinstaller' => 'application/appinstaller', + 'application' => 'application/x-ms-application', + 'appx' => 'application/appx', + 'appxbundle' => 'application/appxbundle', + 'apr' => 'application/vnd.lotus-approach', + 'arc' => 'application/x-freearc', + 'arj' => 'application/x-arj', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomdeleted' => 'application/atomdeleted+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/x-au', + 'avci' => 'image/avci', + 'avcs' => 'image/avcs', + 'avi' => 'video/x-msvideo', + 'avif' => 'image/avif', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azv' => 'image/vnd.airzip.accelerator.azv', + 'azw' => 'application/vnd.amazon.ebook', + 'b16' => 'image/vnd.pco.b16', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bdoc' => 'application/x-bdoc', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmml' => 'application/vnd.balsamiq.bmml+xml', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'bpmn' => 'application/octet-stream', + 'brf' => 'application/braille', + 'bsp' => 'model/vnd.valve.source.compiled-map', + 'btf' => 'image/prs.btif', + 'btif' => 'image/prs.btif', + 'buffer' => 'application/octet-stream', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cco' => 'application/x-cocoa', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdfx' => 'application/cdfx+xml', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdr' => 'application/cdr', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cjs' => 'application/node', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/octet-stream', + 'cld' => 'model/vnd.cld', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'coffee' => 'text/coffeescript', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpl' => 'application/cpl+xml', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'crx' => 'application/x-chrome-extension', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'csh' => 'application/x-csh', + 'csl' => 'application/vnd.citationstyles.style+xml', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'csr' => 'application/octet-stream', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cwl' => 'application/cwl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbf' => 'application/vnd.dbf', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'ddf' => 'application/vnd.syncml.dmddf+xml', + 'dds' => 'image/vnd.ms-dds', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dib' => 'image/bmp', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'disposition-notification' => 'message/disposition-notification', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/x-apple-diskimage', + 'dmn' => 'application/octet-stream', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dpx' => 'image/dpx', + 'dra' => 'audio/vnd.dra', + 'drle' => 'image/dicom-rle', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dst' => 'application/octet-stream', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwd' => 'application/atsc-dwd+xml', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ear' => 'application/java-archive', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'image/emf', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emotionml' => 'application/emotionml+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'exi' => 'application/exi', + 'exp' => 'application/express', + 'exr' => 'image/aces', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/mp4', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fdt' => 'application/fdt+xml', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fits' => 'image/fits', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'fo' => 'application/vnd.software602.filler.form+xml', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'gdoc' => 'application/vnd.google-apps.document', + 'ged' => 'text/vnd.familysearch.gedcom', + 'geo' => 'application/vnd.dynageo', + 'geojson' => 'application/geo+json', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'glb' => 'model/gltf-binary', + 'gltf' => 'model/gltf+json', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gpg' => 'application/gpg-keys', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gsheet' => 'application/vnd.google-apps.spreadsheet', + 'gslides' => 'application/vnd.google-apps.presentation', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/gzip', + 'gzip' => 'application/gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hbs' => 'text/x-handlebars-template', + 'hdd' => 'application/x-virtualbox-hdd', + 'hdf' => 'application/x-hdf', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'hej2' => 'image/hej2k', + 'held' => 'application/atsc-held+xml', + 'hh' => 'text/x-c', + 'hjson' => 'application/hjson', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'hsj2' => 'image/hsj2', + 'htc' => 'text/x-component', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'img' => 'application/octet-stream', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ini' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'its' => 'application/its+xml', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jade' => 'text/jade', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'jardiff' => 'application/x-java-archive-diff', + 'java' => 'text/x-java-source', + 'jhc' => 'image/jphc', + 'jisp' => 'application/vnd.jisp', + 'jls' => 'image/jls', + 'jlt' => 'application/vnd.hp-jlyt', + 'jng' => 'image/x-jng', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpf' => 'image/jpx', + 'jpg' => 'image/jpeg', + 'jpg2' => 'image/jp2', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jph' => 'image/jph', + 'jpm' => 'video/jpm', + 'jpx' => 'image/jpx', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'json5' => 'application/json5', + 'jsonld' => 'application/ld+json', + 'jsonml' => 'application/jsonml+json', + 'jsx' => 'text/jsx', + 'jt' => 'model/jt', + 'jxr' => 'image/jxr', + 'jxra' => 'image/jxra', + 'jxrs' => 'image/jxrs', + 'jxs' => 'image/jxs', + 'jxsc' => 'image/jxsc', + 'jxsi' => 'image/jxsi', + 'jxss' => 'image/jxss', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kdb' => 'application/octet-stream', + 'kdbx' => 'application/x-keepass2', + 'key' => 'application/x-iwork-keynote-sffkey', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktx2' => 'image/ktx2', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'less' => 'text/less', + 'lgr' => 'application/lgr+xml', + 'lha' => 'application/octet-stream', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'litcoffee' => 'text/coffeescript', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lua' => 'text/x-lua', + 'luac' => 'application/x-lua-bytecode', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/octet-stream', + 'm1v' => 'video/mpeg', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'text/plain', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/x-m4a', + 'm4p' => 'application/mp4', + 'm4s' => 'video/iso.segment', + 'm4u' => 'application/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm21' => 'application/mp21', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'maei' => 'application/mmt-aei+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'manifest' => 'text/cache-manifest', + 'map' => 'application/json', + 'mar' => 'application/octet-stream', + 'markdown' => 'text/markdown', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'md' => 'text/markdown', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'mdx' => 'text/mdx', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mjs' => 'text/javascript', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mkd' => 'text/x-markdown', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mml' => 'text/mathml', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mp21' => 'application/mp21', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpd' => 'application/dash+xml', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpf' => 'application/media-policy-dataset+xml', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msg' => 'application/vnd.ms-outlook', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msix' => 'application/msix', + 'msixbundle' => 'application/msixbundle', + 'msl' => 'application/vnd.mobius.msl', + 'msm' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msty' => 'application/vnd.muvee.style', + 'mtl' => 'model/mtl', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musd' => 'application/mmt-usd+xml', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mvt' => 'application/vnd.mapbox-vector-tile', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxmf' => 'audio/mobile-xmf', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'ndjson' => 'application/x-ndjson', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nq' => 'application/n-quads', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'nt' => 'application/n-triples', + 'ntf' => 'application/vnd.nitf', + 'numbers' => 'application/x-iwork-numbers-sffnumbers', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obgx' => 'application/vnd.openblox.game+xml', + 'obj' => 'model/obj', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogex' => 'model/vnd.opengex', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'opus' => 'audio/ogg', + 'org' => 'text/x-org', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'osm' => 'application/vnd.openstreetmap.data+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'font/otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'ova' => 'application/x-virtualbox-ova', + 'ovf' => 'application/x-virtualbox-ovf', + 'owl' => 'application/rdf+xml', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p7a' => 'application/x-pkcs7-signature', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'p10' => 'application/x-pkcs10', + 'p12' => 'application/x-pkcs12', + 'pac' => 'application/x-ns-proxy-autoconfig', + 'pages' => 'application/x-iwork-pages-sffpages', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/x-pilot', + 'pde' => 'text/x-processing', + 'pdf' => 'application/pdf', + 'pem' => 'application/x-x509-user-cert', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp', + 'phar' => 'application/octet-stream', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'pkpass' => 'application/vnd.apple.pkpass', + 'pl' => 'application/x-perl', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pm' => 'application/x-perl', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'model/prc', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'provx' => 'application/provenance+xml', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'application/x-photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'pti' => 'image/prs.pti', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pv' => 'application/octet-stream', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pxf' => 'application/octet-stream', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyo' => 'model/vnd.pytha.pyox', + 'pyox' => 'model/vnd.pytha.pyox', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'raml' => 'application/raml+yaml', + 'rapd' => 'application/route-apd+xml', + 'rar' => 'application/x-rar', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'relo' => 'application/p2p-overlay+xml', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'audio/x-pn-realaudio', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'rng' => 'application/xml', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsa' => 'application/x-pkcs7', + 'rsat' => 'application/atsc-rsat+xml', + 'rsd' => 'application/rsd+xml', + 'rsheet' => 'application/urc-ressheet+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'run' => 'application/x-makeself', + 'rusd' => 'application/route-usd+xml', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sass' => 'text/x-sass', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scss' => 'text/x-scss', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'sea' => 'application/octet-stream', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'senmlx' => 'application/senml+xml', + 'sensmlx' => 'application/sensml+xml', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shex' => 'text/shex', + 'shf' => 'application/shf+xml', + 'shtml' => 'text/html', + 'sid' => 'image/x-mrsid-image', + 'sieve' => 'application/sieve', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'siv' => 'application/sieve', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slim' => 'text/slim', + 'slm' => 'text/slim', + 'sls' => 'application/route-s-tsid+xml', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spdx' => 'text/spdx', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'sst' => 'application/octet-stream', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'step' => 'application/STEP', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'model/stl', + 'stp' => 'application/STEP', + 'stpx' => 'model/step+xml', + 'stpxz' => 'model/step-xml+zip', + 'stpz' => 'model/step+zip', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'styl' => 'text/stylus', + 'stylus' => 'text/stylus', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'swidtag' => 'application/swid+xml', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 't38' => 'image/t38', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tap' => 'image/vnd.tencent.tap', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'td' => 'application/urc-targetdesc+xml', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tfx' => 'image/tiff-fx', + 'tga' => 'image/x-tga', + 'tgz' => 'application/x-tar', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tk' => 'application/x-tcl', + 'tmo' => 'application/vnd.tmobile-livetv', + 'toml' => 'application/toml', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trig' => 'application/trig', + 'trm' => 'application/x-msterminal', + 'ts' => 'video/mp2t', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'font/collection', + 'ttf' => 'font/ttf', + 'ttl' => 'text/turtle', + 'ttml' => 'application/ttml+xml', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u3d' => 'model/u3d', + 'u8dsn' => 'message/global-delivery-status', + 'u8hdr' => 'message/global-headers', + 'u8mdn' => 'message/global-disposition-notification', + 'u8msg' => 'message/global', + 'u32' => 'application/x-authorware-bin', + 'ubj' => 'application/ubjson', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uo' => 'application/vnd.uoml+xml', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'usda' => 'model/vnd.usda', + 'usdz' => 'model/vnd.usdz+zip', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vbox' => 'application/x-virtualbox-vbox', + 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vdi' => 'application/x-virtualbox-vdi', + 'vds' => 'model/vnd.sap.vds', + 'vhd' => 'application/x-virtualbox-vhd', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vlc' => 'application/videolan', + 'vmdk' => 'application/x-virtualbox-vmdk', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtf' => 'image/vnd.valve.source.texture', + 'vtt' => 'text/vtt', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wadl' => 'application/vnd.sun.wadl+xml', + 'war' => 'application/java-archive', + 'wasm' => 'application/wasm', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webapp' => 'application/x-web-app-manifest+json', + 'webm' => 'video/webm', + 'webmanifest' => 'application/manifest+json', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgsl' => 'text/wgsl', + 'wgt' => 'application/widget', + 'wif' => 'application/watcherinfo+xml', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'image/wmf', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + 'word' => 'application/msword', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsc' => 'message/vnd.wfa.wsc', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+fastinfoset', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d-vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'x32' => 'application/x-authorware-bin', + 'x_b' => 'model/vnd.parasolid.transmit.binary', + 'x_t' => 'model/vnd.parasolid.transmit.text', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xav' => 'application/xcap-att+xml', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xca' => 'application/xcap-caps+xml', + 'xcs' => 'application/calendar+xml', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xel' => 'application/xcap-el+xml', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtm' => 'application/vnd.pwg-xhtml-print+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/excel', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xns' => 'application/xcap-ns+xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsd' => 'application/xml', + 'xsf' => 'application/prs.xsf+xml', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'ymp' => 'text/x-suse-ymp', + 'z' => 'application/x-compress', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + 'zsh' => 'text/x-scriptzsh', + ]; + + /** + * @var array<string, string> + * + * @internal + */ + public const EXTENSIONS_FOR_MIME_TIMES = [ + 'application/andrew-inset' => ['ez'], + 'application/appinstaller' => ['appinstaller'], + 'application/applixware' => ['aw'], + 'application/appx' => ['appx'], + 'application/appxbundle' => ['appxbundle'], + 'application/atom+xml' => ['atom'], + 'application/atomcat+xml' => ['atomcat'], + 'application/atomdeleted+xml' => ['atomdeleted'], + 'application/atomsvc+xml' => ['atomsvc'], + 'application/atsc-dwd+xml' => ['dwd'], + 'application/atsc-held+xml' => ['held'], + 'application/atsc-rsat+xml' => ['rsat'], + 'application/automationml-aml+xml' => ['aml'], + 'application/automationml-amlx+zip' => ['amlx'], + 'application/bdoc' => ['bdoc'], + 'application/calendar+xml' => ['xcs'], + 'application/ccxml+xml' => ['ccxml'], + 'application/cdfx+xml' => ['cdfx'], + 'application/cdmi-capability' => ['cdmia'], + 'application/cdmi-container' => ['cdmic'], + 'application/cdmi-domain' => ['cdmid'], + 'application/cdmi-object' => ['cdmio'], + 'application/cdmi-queue' => ['cdmiq'], + 'application/cpl+xml' => ['cpl'], + 'application/cu-seeme' => ['cu'], + 'application/cwl' => ['cwl'], + 'application/dash+xml' => ['mpd'], + 'application/dash-patch+xml' => ['mpp'], + 'application/davmount+xml' => ['davmount'], + 'application/docbook+xml' => ['dbk'], + 'application/dssc+der' => ['dssc'], + 'application/dssc+xml' => ['xdssc'], + 'application/ecmascript' => ['ecma'], + 'application/emma+xml' => ['emma'], + 'application/emotionml+xml' => ['emotionml'], + 'application/epub+zip' => ['epub'], + 'application/exi' => ['exi'], + 'application/express' => ['exp'], + 'application/fdf' => ['fdf'], + 'application/fdt+xml' => ['fdt'], + 'application/font-tdpfr' => ['pfr'], + 'application/geo+json' => ['geojson'], + 'application/gml+xml' => ['gml'], + 'application/gpx+xml' => ['gpx'], + 'application/gxf' => ['gxf'], + 'application/gzip' => ['gz', 'gzip'], + 'application/hjson' => ['hjson'], + 'application/hyperstudio' => ['stk'], + 'application/inkml+xml' => ['ink', 'inkml'], + 'application/ipfix' => ['ipfix'], + 'application/its+xml' => ['its'], + 'application/java-archive' => ['jar', 'war', 'ear'], + 'application/java-serialized-object' => ['ser'], + 'application/java-vm' => ['class'], + 'application/javascript' => ['js'], + 'application/json' => ['json', 'map'], + 'application/json5' => ['json5'], + 'application/jsonml+json' => ['jsonml'], + 'application/ld+json' => ['jsonld'], + 'application/lgr+xml' => ['lgr'], + 'application/lost+xml' => ['lostxml'], + 'application/mac-binhex40' => ['hqx'], + 'application/mac-compactpro' => ['cpt'], + 'application/mads+xml' => ['mads'], + 'application/manifest+json' => ['webmanifest'], + 'application/marc' => ['mrc'], + 'application/marcxml+xml' => ['mrcx'], + 'application/mathematica' => ['ma', 'nb', 'mb'], + 'application/mathml+xml' => ['mathml'], + 'application/mbox' => ['mbox'], + 'application/media-policy-dataset+xml' => ['mpf'], + 'application/mediaservercontrol+xml' => ['mscml'], + 'application/metalink+xml' => ['metalink'], + 'application/metalink4+xml' => ['meta4'], + 'application/mets+xml' => ['mets'], + 'application/mmt-aei+xml' => ['maei'], + 'application/mmt-usd+xml' => ['musd'], + 'application/mods+xml' => ['mods'], + 'application/mp21' => ['m21', 'mp21'], + 'application/mp4' => ['mp4', 'mpg4', 'mp4s', 'm4p'], + 'application/msix' => ['msix'], + 'application/msixbundle' => ['msixbundle'], + 'application/msword' => ['doc', 'dot', 'word'], + 'application/mxf' => ['mxf'], + 'application/n-quads' => ['nq'], + 'application/n-triples' => ['nt'], + 'application/node' => ['cjs'], + 'application/octet-stream' => ['bin', 'dms', 'lrf', 'mar', 'so', 'dist', 'distz', 'pkg', 'bpk', 'dump', 'elc', 'deploy', 'exe', 'dll', 'deb', 'dmg', 'iso', 'img', 'msi', 'msp', 'msm', 'buffer', 'phar', 'lha', 'lzh', 'class', 'sea', 'dmn', 'bpmn', 'kdb', 'sst', 'csr', 'dst', 'pv', 'pxf'], + 'application/oda' => ['oda'], + 'application/oebps-package+xml' => ['opf'], + 'application/ogg' => ['ogx'], + 'application/omdoc+xml' => ['omdoc'], + 'application/onenote' => ['onetoc', 'onetoc2', 'onetmp', 'onepkg'], + 'application/oxps' => ['oxps'], + 'application/p2p-overlay+xml' => ['relo'], + 'application/patch-ops-error+xml' => ['xer'], + 'application/pdf' => ['pdf', 'ai'], + 'application/pgp-encrypted' => ['pgp'], + 'application/pgp-keys' => ['asc'], + 'application/pgp-signature' => ['sig', 'asc'], + 'application/pics-rules' => ['prf'], + 'application/pkcs10' => ['p10'], + 'application/pkcs7-mime' => ['p7m', 'p7c'], + 'application/pkcs7-signature' => ['p7s'], + 'application/pkcs8' => ['p8'], + 'application/pkix-attr-cert' => ['ac'], + 'application/pkix-cert' => ['cer'], + 'application/pkix-crl' => ['crl'], + 'application/pkix-pkipath' => ['pkipath'], + 'application/pkixcmp' => ['pki'], + 'application/pls+xml' => ['pls'], + 'application/postscript' => ['ai', 'eps', 'ps'], + 'application/provenance+xml' => ['provx'], + 'application/prs.cww' => ['cww'], + 'application/prs.xsf+xml' => ['xsf'], + 'application/pskc+xml' => ['pskcxml'], + 'application/raml+yaml' => ['raml'], + 'application/rdf+xml' => ['rdf', 'owl'], + 'application/reginfo+xml' => ['rif'], + 'application/relax-ng-compact-syntax' => ['rnc'], + 'application/resource-lists+xml' => ['rl'], + 'application/resource-lists-diff+xml' => ['rld'], + 'application/rls-services+xml' => ['rs'], + 'application/route-apd+xml' => ['rapd'], + 'application/route-s-tsid+xml' => ['sls'], + 'application/route-usd+xml' => ['rusd'], + 'application/rpki-ghostbusters' => ['gbr'], + 'application/rpki-manifest' => ['mft'], + 'application/rpki-roa' => ['roa'], + 'application/rsd+xml' => ['rsd'], + 'application/rss+xml' => ['rss'], + 'application/rtf' => ['rtf'], + 'application/sbml+xml' => ['sbml'], + 'application/scvp-cv-request' => ['scq'], + 'application/scvp-cv-response' => ['scs'], + 'application/scvp-vp-request' => ['spq'], + 'application/scvp-vp-response' => ['spp'], + 'application/sdp' => ['sdp'], + 'application/senml+xml' => ['senmlx'], + 'application/sensml+xml' => ['sensmlx'], + 'application/set-payment-initiation' => ['setpay'], + 'application/set-registration-initiation' => ['setreg'], + 'application/shf+xml' => ['shf'], + 'application/sieve' => ['siv', 'sieve'], + 'application/smil+xml' => ['smi', 'smil'], + 'application/sparql-query' => ['rq'], + 'application/sparql-results+xml' => ['srx'], + 'application/sql' => ['sql'], + 'application/srgs' => ['gram'], + 'application/srgs+xml' => ['grxml'], + 'application/sru+xml' => ['sru'], + 'application/ssdl+xml' => ['ssdl'], + 'application/ssml+xml' => ['ssml'], + 'application/swid+xml' => ['swidtag'], + 'application/tei+xml' => ['tei', 'teicorpus'], + 'application/thraud+xml' => ['tfi'], + 'application/timestamped-data' => ['tsd'], + 'application/toml' => ['toml'], + 'application/trig' => ['trig'], + 'application/ttml+xml' => ['ttml'], + 'application/ubjson' => ['ubj'], + 'application/urc-ressheet+xml' => ['rsheet'], + 'application/urc-targetdesc+xml' => ['td'], + 'application/vnd.1000minds.decision-model+xml' => ['1km'], + 'application/vnd.3gpp.pic-bw-large' => ['plb'], + 'application/vnd.3gpp.pic-bw-small' => ['psb'], + 'application/vnd.3gpp.pic-bw-var' => ['pvb'], + 'application/vnd.3gpp2.tcap' => ['tcap'], + 'application/vnd.3m.post-it-notes' => ['pwn'], + 'application/vnd.accpac.simply.aso' => ['aso'], + 'application/vnd.accpac.simply.imp' => ['imp'], + 'application/vnd.acucobol' => ['acu'], + 'application/vnd.acucorp' => ['atc', 'acutc'], + 'application/vnd.adobe.air-application-installer-package+zip' => ['air'], + 'application/vnd.adobe.formscentral.fcdt' => ['fcdt'], + 'application/vnd.adobe.fxp' => ['fxp', 'fxpl'], + 'application/vnd.adobe.xdp+xml' => ['xdp'], + 'application/vnd.adobe.xfdf' => ['xfdf'], + 'application/vnd.age' => ['age'], + 'application/vnd.ahead.space' => ['ahead'], + 'application/vnd.airzip.filesecure.azf' => ['azf'], + 'application/vnd.airzip.filesecure.azs' => ['azs'], + 'application/vnd.amazon.ebook' => ['azw'], + 'application/vnd.americandynamics.acc' => ['acc'], + 'application/vnd.amiga.ami' => ['ami'], + 'application/vnd.android.package-archive' => ['apk'], + 'application/vnd.anser-web-certificate-issue-initiation' => ['cii'], + 'application/vnd.anser-web-funds-transfer-initiation' => ['fti'], + 'application/vnd.antix.game-component' => ['atx'], + 'application/vnd.apple.installer+xml' => ['mpkg'], + 'application/vnd.apple.keynote' => ['key'], + 'application/vnd.apple.mpegurl' => ['m3u8'], + 'application/vnd.apple.numbers' => ['numbers'], + 'application/vnd.apple.pages' => ['pages'], + 'application/vnd.apple.pkpass' => ['pkpass'], + 'application/vnd.aristanetworks.swi' => ['swi'], + 'application/vnd.astraea-software.iota' => ['iota'], + 'application/vnd.audiograph' => ['aep'], + 'application/vnd.balsamiq.bmml+xml' => ['bmml'], + 'application/vnd.blueice.multipass' => ['mpm'], + 'application/vnd.bmi' => ['bmi'], + 'application/vnd.businessobjects' => ['rep'], + 'application/vnd.chemdraw+xml' => ['cdxml'], + 'application/vnd.chipnuts.karaoke-mmd' => ['mmd'], + 'application/vnd.cinderella' => ['cdy'], + 'application/vnd.citationstyles.style+xml' => ['csl'], + 'application/vnd.claymore' => ['cla'], + 'application/vnd.cloanto.rp9' => ['rp9'], + 'application/vnd.clonk.c4group' => ['c4g', 'c4d', 'c4f', 'c4p', 'c4u'], + 'application/vnd.cluetrust.cartomobile-config' => ['c11amc'], + 'application/vnd.cluetrust.cartomobile-config-pkg' => ['c11amz'], + 'application/vnd.commonspace' => ['csp'], + 'application/vnd.contact.cmsg' => ['cdbcmsg'], + 'application/vnd.cosmocaller' => ['cmc'], + 'application/vnd.crick.clicker' => ['clkx'], + 'application/vnd.crick.clicker.keyboard' => ['clkk'], + 'application/vnd.crick.clicker.palette' => ['clkp'], + 'application/vnd.crick.clicker.template' => ['clkt'], + 'application/vnd.crick.clicker.wordbank' => ['clkw'], + 'application/vnd.criticaltools.wbs+xml' => ['wbs'], + 'application/vnd.ctc-posml' => ['pml'], + 'application/vnd.cups-ppd' => ['ppd'], + 'application/vnd.curl.car' => ['car'], + 'application/vnd.curl.pcurl' => ['pcurl'], + 'application/vnd.dart' => ['dart'], + 'application/vnd.data-vision.rdz' => ['rdz'], + 'application/vnd.dbf' => ['dbf'], + 'application/vnd.dece.data' => ['uvf', 'uvvf', 'uvd', 'uvvd'], + 'application/vnd.dece.ttml+xml' => ['uvt', 'uvvt'], + 'application/vnd.dece.unspecified' => ['uvx', 'uvvx'], + 'application/vnd.dece.zip' => ['uvz', 'uvvz'], + 'application/vnd.denovo.fcselayout-link' => ['fe_launch'], + 'application/vnd.dna' => ['dna'], + 'application/vnd.dolby.mlp' => ['mlp'], + 'application/vnd.dpgraph' => ['dpg'], + 'application/vnd.dreamfactory' => ['dfac'], + 'application/vnd.ds-keypoint' => ['kpxx'], + 'application/vnd.dvb.ait' => ['ait'], + 'application/vnd.dvb.service' => ['svc'], + 'application/vnd.dynageo' => ['geo'], + 'application/vnd.ecowin.chart' => ['mag'], + 'application/vnd.enliven' => ['nml'], + 'application/vnd.epson.esf' => ['esf'], + 'application/vnd.epson.msf' => ['msf'], + 'application/vnd.epson.quickanime' => ['qam'], + 'application/vnd.epson.salt' => ['slt'], + 'application/vnd.epson.ssf' => ['ssf'], + 'application/vnd.eszigno3+xml' => ['es3', 'et3'], + 'application/vnd.ezpix-album' => ['ez2'], + 'application/vnd.ezpix-package' => ['ez3'], + 'application/vnd.fdf' => ['fdf'], + 'application/vnd.fdsn.mseed' => ['mseed'], + 'application/vnd.fdsn.seed' => ['seed', 'dataless'], + 'application/vnd.flographit' => ['gph'], + 'application/vnd.fluxtime.clip' => ['ftc'], + 'application/vnd.framemaker' => ['fm', 'frame', 'maker', 'book'], + 'application/vnd.frogans.fnc' => ['fnc'], + 'application/vnd.frogans.ltf' => ['ltf'], + 'application/vnd.fsc.weblaunch' => ['fsc'], + 'application/vnd.fujitsu.oasys' => ['oas'], + 'application/vnd.fujitsu.oasys2' => ['oa2'], + 'application/vnd.fujitsu.oasys3' => ['oa3'], + 'application/vnd.fujitsu.oasysgp' => ['fg5'], + 'application/vnd.fujitsu.oasysprs' => ['bh2'], + 'application/vnd.fujixerox.ddd' => ['ddd'], + 'application/vnd.fujixerox.docuworks' => ['xdw'], + 'application/vnd.fujixerox.docuworks.binder' => ['xbd'], + 'application/vnd.fuzzysheet' => ['fzs'], + 'application/vnd.genomatix.tuxedo' => ['txd'], + 'application/vnd.geogebra.file' => ['ggb'], + 'application/vnd.geogebra.tool' => ['ggt'], + 'application/vnd.geometry-explorer' => ['gex', 'gre'], + 'application/vnd.geonext' => ['gxt'], + 'application/vnd.geoplan' => ['g2w'], + 'application/vnd.geospace' => ['g3w'], + 'application/vnd.gmx' => ['gmx'], + 'application/vnd.google-apps.document' => ['gdoc'], + 'application/vnd.google-apps.presentation' => ['gslides'], + 'application/vnd.google-apps.spreadsheet' => ['gsheet'], + 'application/vnd.google-earth.kml+xml' => ['kml'], + 'application/vnd.google-earth.kmz' => ['kmz'], + 'application/vnd.grafeq' => ['gqf', 'gqs'], + 'application/vnd.groove-account' => ['gac'], + 'application/vnd.groove-help' => ['ghf'], + 'application/vnd.groove-identity-message' => ['gim'], + 'application/vnd.groove-injector' => ['grv'], + 'application/vnd.groove-tool-message' => ['gtm'], + 'application/vnd.groove-tool-template' => ['tpl'], + 'application/vnd.groove-vcard' => ['vcg'], + 'application/vnd.hal+xml' => ['hal'], + 'application/vnd.handheld-entertainment+xml' => ['zmm'], + 'application/vnd.hbci' => ['hbci'], + 'application/vnd.hhe.lesson-player' => ['les'], + 'application/vnd.hp-hpgl' => ['hpgl'], + 'application/vnd.hp-hpid' => ['hpid'], + 'application/vnd.hp-hps' => ['hps'], + 'application/vnd.hp-jlyt' => ['jlt'], + 'application/vnd.hp-pcl' => ['pcl'], + 'application/vnd.hp-pclxl' => ['pclxl'], + 'application/vnd.hydrostatix.sof-data' => ['sfd-hdstx'], + 'application/vnd.ibm.minipay' => ['mpy'], + 'application/vnd.ibm.modcap' => ['afp', 'listafp', 'list3820'], + 'application/vnd.ibm.rights-management' => ['irm'], + 'application/vnd.ibm.secure-container' => ['sc'], + 'application/vnd.iccprofile' => ['icc', 'icm'], + 'application/vnd.igloader' => ['igl'], + 'application/vnd.immervision-ivp' => ['ivp'], + 'application/vnd.immervision-ivu' => ['ivu'], + 'application/vnd.insors.igm' => ['igm'], + 'application/vnd.intercon.formnet' => ['xpw', 'xpx'], + 'application/vnd.intergeo' => ['i2g'], + 'application/vnd.intu.qbo' => ['qbo'], + 'application/vnd.intu.qfx' => ['qfx'], + 'application/vnd.ipunplugged.rcprofile' => ['rcprofile'], + 'application/vnd.irepository.package+xml' => ['irp'], + 'application/vnd.is-xpr' => ['xpr'], + 'application/vnd.isac.fcs' => ['fcs'], + 'application/vnd.jam' => ['jam'], + 'application/vnd.jcp.javame.midlet-rms' => ['rms'], + 'application/vnd.jisp' => ['jisp'], + 'application/vnd.joost.joda-archive' => ['joda'], + 'application/vnd.kahootz' => ['ktz', 'ktr'], + 'application/vnd.kde.karbon' => ['karbon'], + 'application/vnd.kde.kchart' => ['chrt'], + 'application/vnd.kde.kformula' => ['kfo'], + 'application/vnd.kde.kivio' => ['flw'], + 'application/vnd.kde.kontour' => ['kon'], + 'application/vnd.kde.kpresenter' => ['kpr', 'kpt'], + 'application/vnd.kde.kspread' => ['ksp'], + 'application/vnd.kde.kword' => ['kwd', 'kwt'], + 'application/vnd.kenameaapp' => ['htke'], + 'application/vnd.kidspiration' => ['kia'], + 'application/vnd.kinar' => ['kne', 'knp'], + 'application/vnd.koan' => ['skp', 'skd', 'skt', 'skm'], + 'application/vnd.kodak-descriptor' => ['sse'], + 'application/vnd.las.las+xml' => ['lasxml'], + 'application/vnd.llamagraphics.life-balance.desktop' => ['lbd'], + 'application/vnd.llamagraphics.life-balance.exchange+xml' => ['lbe'], + 'application/vnd.lotus-1-2-3' => ['123'], + 'application/vnd.lotus-approach' => ['apr'], + 'application/vnd.lotus-freelance' => ['pre'], + 'application/vnd.lotus-notes' => ['nsf'], + 'application/vnd.lotus-organizer' => ['org'], + 'application/vnd.lotus-screencam' => ['scm'], + 'application/vnd.lotus-wordpro' => ['lwp'], + 'application/vnd.macports.portpkg' => ['portpkg'], + 'application/vnd.mapbox-vector-tile' => ['mvt'], + 'application/vnd.mcd' => ['mcd'], + 'application/vnd.medcalcdata' => ['mc1'], + 'application/vnd.mediastation.cdkey' => ['cdkey'], + 'application/vnd.mfer' => ['mwf'], + 'application/vnd.mfmp' => ['mfm'], + 'application/vnd.micrografx.flo' => ['flo'], + 'application/vnd.micrografx.igx' => ['igx'], + 'application/vnd.mif' => ['mif'], + 'application/vnd.mobius.daf' => ['daf'], + 'application/vnd.mobius.dis' => ['dis'], + 'application/vnd.mobius.mbk' => ['mbk'], + 'application/vnd.mobius.mqy' => ['mqy'], + 'application/vnd.mobius.msl' => ['msl'], + 'application/vnd.mobius.plc' => ['plc'], + 'application/vnd.mobius.txf' => ['txf'], + 'application/vnd.mophun.application' => ['mpn'], + 'application/vnd.mophun.certificate' => ['mpc'], + 'application/vnd.mozilla.xul+xml' => ['xul'], + 'application/vnd.ms-artgalry' => ['cil'], + 'application/vnd.ms-cab-compressed' => ['cab'], + 'application/vnd.ms-excel' => ['xls', 'xlm', 'xla', 'xlc', 'xlt', 'xlw'], + 'application/vnd.ms-excel.addin.macroenabled.12' => ['xlam'], + 'application/vnd.ms-excel.sheet.binary.macroenabled.12' => ['xlsb'], + 'application/vnd.ms-excel.sheet.macroenabled.12' => ['xlsm'], + 'application/vnd.ms-excel.template.macroenabled.12' => ['xltm'], + 'application/vnd.ms-fontobject' => ['eot'], + 'application/vnd.ms-htmlhelp' => ['chm'], + 'application/vnd.ms-ims' => ['ims'], + 'application/vnd.ms-lrm' => ['lrm'], + 'application/vnd.ms-officetheme' => ['thmx'], + 'application/vnd.ms-outlook' => ['msg'], + 'application/vnd.ms-pki.seccat' => ['cat'], + 'application/vnd.ms-pki.stl' => ['stl'], + 'application/vnd.ms-powerpoint' => ['ppt', 'pps', 'pot', 'ppa'], + 'application/vnd.ms-powerpoint.addin.macroenabled.12' => ['ppam'], + 'application/vnd.ms-powerpoint.presentation.macroenabled.12' => ['pptm'], + 'application/vnd.ms-powerpoint.slide.macroenabled.12' => ['sldm'], + 'application/vnd.ms-powerpoint.slideshow.macroenabled.12' => ['ppsm'], + 'application/vnd.ms-powerpoint.template.macroenabled.12' => ['potm'], + 'application/vnd.ms-project' => ['mpp', 'mpt'], + 'application/vnd.ms-word.document.macroenabled.12' => ['docm'], + 'application/vnd.ms-word.template.macroenabled.12' => ['dotm'], + 'application/vnd.ms-works' => ['wps', 'wks', 'wcm', 'wdb'], + 'application/vnd.ms-wpl' => ['wpl'], + 'application/vnd.ms-xpsdocument' => ['xps'], + 'application/vnd.mseq' => ['mseq'], + 'application/vnd.musician' => ['mus'], + 'application/vnd.muvee.style' => ['msty'], + 'application/vnd.mynfc' => ['taglet'], + 'application/vnd.neurolanguage.nlu' => ['nlu'], + 'application/vnd.nitf' => ['ntf', 'nitf'], + 'application/vnd.noblenet-directory' => ['nnd'], + 'application/vnd.noblenet-sealer' => ['nns'], + 'application/vnd.noblenet-web' => ['nnw'], + 'application/vnd.nokia.n-gage.ac+xml' => ['ac'], + 'application/vnd.nokia.n-gage.data' => ['ngdat'], + 'application/vnd.nokia.n-gage.symbian.install' => ['n-gage'], + 'application/vnd.nokia.radio-preset' => ['rpst'], + 'application/vnd.nokia.radio-presets' => ['rpss'], + 'application/vnd.novadigm.edm' => ['edm'], + 'application/vnd.novadigm.edx' => ['edx'], + 'application/vnd.novadigm.ext' => ['ext'], + 'application/vnd.oasis.opendocument.chart' => ['odc'], + 'application/vnd.oasis.opendocument.chart-template' => ['otc'], + 'application/vnd.oasis.opendocument.database' => ['odb'], + 'application/vnd.oasis.opendocument.formula' => ['odf'], + 'application/vnd.oasis.opendocument.formula-template' => ['odft'], + 'application/vnd.oasis.opendocument.graphics' => ['odg'], + 'application/vnd.oasis.opendocument.graphics-template' => ['otg'], + 'application/vnd.oasis.opendocument.image' => ['odi'], + 'application/vnd.oasis.opendocument.image-template' => ['oti'], + 'application/vnd.oasis.opendocument.presentation' => ['odp'], + 'application/vnd.oasis.opendocument.presentation-template' => ['otp'], + 'application/vnd.oasis.opendocument.spreadsheet' => ['ods'], + 'application/vnd.oasis.opendocument.spreadsheet-template' => ['ots'], + 'application/vnd.oasis.opendocument.text' => ['odt'], + 'application/vnd.oasis.opendocument.text-master' => ['odm'], + 'application/vnd.oasis.opendocument.text-template' => ['ott'], + 'application/vnd.oasis.opendocument.text-web' => ['oth'], + 'application/vnd.olpc-sugar' => ['xo'], + 'application/vnd.oma.dd2+xml' => ['dd2'], + 'application/vnd.openblox.game+xml' => ['obgx'], + 'application/vnd.openofficeorg.extension' => ['oxt'], + 'application/vnd.openstreetmap.data+xml' => ['osm'], + 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => ['pptx'], + 'application/vnd.openxmlformats-officedocument.presentationml.slide' => ['sldx'], + 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' => ['ppsx'], + 'application/vnd.openxmlformats-officedocument.presentationml.template' => ['potx'], + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx'], + 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' => ['xltx'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => ['dotx'], + 'application/vnd.osgeo.mapguide.package' => ['mgp'], + 'application/vnd.osgi.dp' => ['dp'], + 'application/vnd.osgi.subsystem' => ['esa'], + 'application/vnd.palm' => ['pdb', 'pqa', 'oprc'], + 'application/vnd.pawaafile' => ['paw'], + 'application/vnd.pg.format' => ['str'], + 'application/vnd.pg.osasli' => ['ei6'], + 'application/vnd.picsel' => ['efif'], + 'application/vnd.pmi.widget' => ['wg'], + 'application/vnd.pocketlearn' => ['plf'], + 'application/vnd.powerbuilder6' => ['pbd'], + 'application/vnd.previewsystems.box' => ['box'], + 'application/vnd.proteus.magazine' => ['mgz'], + 'application/vnd.publishare-delta-tree' => ['qps'], + 'application/vnd.pvi.ptid1' => ['ptid'], + 'application/vnd.pwg-xhtml-print+xml' => ['xhtm'], + 'application/vnd.quark.quarkxpress' => ['qxd', 'qxt', 'qwd', 'qwt', 'qxl', 'qxb'], + 'application/vnd.rar' => ['rar'], + 'application/vnd.realvnc.bed' => ['bed'], + 'application/vnd.recordare.musicxml' => ['mxl'], + 'application/vnd.recordare.musicxml+xml' => ['musicxml'], + 'application/vnd.rig.cryptonote' => ['cryptonote'], + 'application/vnd.rim.cod' => ['cod'], + 'application/vnd.rn-realmedia' => ['rm'], + 'application/vnd.rn-realmedia-vbr' => ['rmvb'], + 'application/vnd.route66.link66+xml' => ['link66'], + 'application/vnd.sailingtracker.track' => ['st'], + 'application/vnd.seemail' => ['see'], + 'application/vnd.sema' => ['sema'], + 'application/vnd.semd' => ['semd'], + 'application/vnd.semf' => ['semf'], + 'application/vnd.shana.informed.formdata' => ['ifm'], + 'application/vnd.shana.informed.formtemplate' => ['itp'], + 'application/vnd.shana.informed.interchange' => ['iif'], + 'application/vnd.shana.informed.package' => ['ipk'], + 'application/vnd.simtech-mindmapper' => ['twd', 'twds'], + 'application/vnd.smaf' => ['mmf'], + 'application/vnd.smart.teacher' => ['teacher'], + 'application/vnd.software602.filler.form+xml' => ['fo'], + 'application/vnd.solent.sdkm+xml' => ['sdkm', 'sdkd'], + 'application/vnd.spotfire.dxp' => ['dxp'], + 'application/vnd.spotfire.sfs' => ['sfs'], + 'application/vnd.stardivision.calc' => ['sdc'], + 'application/vnd.stardivision.draw' => ['sda'], + 'application/vnd.stardivision.impress' => ['sdd'], + 'application/vnd.stardivision.math' => ['smf'], + 'application/vnd.stardivision.writer' => ['sdw', 'vor'], + 'application/vnd.stardivision.writer-global' => ['sgl'], + 'application/vnd.stepmania.package' => ['smzip'], + 'application/vnd.stepmania.stepchart' => ['sm'], + 'application/vnd.sun.wadl+xml' => ['wadl'], + 'application/vnd.sun.xml.calc' => ['sxc'], + 'application/vnd.sun.xml.calc.template' => ['stc'], + 'application/vnd.sun.xml.draw' => ['sxd'], + 'application/vnd.sun.xml.draw.template' => ['std'], + 'application/vnd.sun.xml.impress' => ['sxi'], + 'application/vnd.sun.xml.impress.template' => ['sti'], + 'application/vnd.sun.xml.math' => ['sxm'], + 'application/vnd.sun.xml.writer' => ['sxw'], + 'application/vnd.sun.xml.writer.global' => ['sxg'], + 'application/vnd.sun.xml.writer.template' => ['stw'], + 'application/vnd.sus-calendar' => ['sus', 'susp'], + 'application/vnd.svd' => ['svd'], + 'application/vnd.symbian.install' => ['sis', 'sisx'], + 'application/vnd.syncml+xml' => ['xsm'], + 'application/vnd.syncml.dm+wbxml' => ['bdm'], + 'application/vnd.syncml.dm+xml' => ['xdm'], + 'application/vnd.syncml.dmddf+xml' => ['ddf'], + 'application/vnd.tao.intent-module-archive' => ['tao'], + 'application/vnd.tcpdump.pcap' => ['pcap', 'cap', 'dmp'], + 'application/vnd.tmobile-livetv' => ['tmo'], + 'application/vnd.trid.tpt' => ['tpt'], + 'application/vnd.triscape.mxs' => ['mxs'], + 'application/vnd.trueapp' => ['tra'], + 'application/vnd.ufdl' => ['ufd', 'ufdl'], + 'application/vnd.uiq.theme' => ['utz'], + 'application/vnd.umajin' => ['umj'], + 'application/vnd.unity' => ['unityweb'], + 'application/vnd.uoml+xml' => ['uoml', 'uo'], + 'application/vnd.vcx' => ['vcx'], + 'application/vnd.visio' => ['vsd', 'vst', 'vss', 'vsw'], + 'application/vnd.visionary' => ['vis'], + 'application/vnd.vsf' => ['vsf'], + 'application/vnd.wap.wbxml' => ['wbxml'], + 'application/vnd.wap.wmlc' => ['wmlc'], + 'application/vnd.wap.wmlscriptc' => ['wmlsc'], + 'application/vnd.webturbo' => ['wtb'], + 'application/vnd.wolfram.player' => ['nbp'], + 'application/vnd.wordperfect' => ['wpd'], + 'application/vnd.wqd' => ['wqd'], + 'application/vnd.wt.stf' => ['stf'], + 'application/vnd.xara' => ['xar'], + 'application/vnd.xfdl' => ['xfdl'], + 'application/vnd.yamaha.hv-dic' => ['hvd'], + 'application/vnd.yamaha.hv-script' => ['hvs'], + 'application/vnd.yamaha.hv-voice' => ['hvp'], + 'application/vnd.yamaha.openscoreformat' => ['osf'], + 'application/vnd.yamaha.openscoreformat.osfpvg+xml' => ['osfpvg'], + 'application/vnd.yamaha.smaf-audio' => ['saf'], + 'application/vnd.yamaha.smaf-phrase' => ['spf'], + 'application/vnd.yellowriver-custom-menu' => ['cmp'], + 'application/vnd.zul' => ['zir', 'zirz'], + 'application/vnd.zzazz.deck+xml' => ['zaz'], + 'application/voicexml+xml' => ['vxml'], + 'application/wasm' => ['wasm'], + 'application/watcherinfo+xml' => ['wif'], + 'application/widget' => ['wgt'], + 'application/winhlp' => ['hlp'], + 'application/wsdl+xml' => ['wsdl'], + 'application/wspolicy+xml' => ['wspolicy'], + 'application/x-7z-compressed' => ['7z', '7zip'], + 'application/x-abiword' => ['abw'], + 'application/x-ace-compressed' => ['ace'], + 'application/x-apple-diskimage' => ['dmg'], + 'application/x-arj' => ['arj'], + 'application/x-authorware-bin' => ['aab', 'x32', 'u32', 'vox'], + 'application/x-authorware-map' => ['aam'], + 'application/x-authorware-seg' => ['aas'], + 'application/x-bcpio' => ['bcpio'], + 'application/x-bdoc' => ['bdoc'], + 'application/x-bittorrent' => ['torrent'], + 'application/x-blorb' => ['blb', 'blorb'], + 'application/x-bzip' => ['bz'], + 'application/x-bzip2' => ['bz2', 'boz'], + 'application/x-cbr' => ['cbr', 'cba', 'cbt', 'cbz', 'cb7'], + 'application/x-cdlink' => ['vcd'], + 'application/x-cfs-compressed' => ['cfs'], + 'application/x-chat' => ['chat'], + 'application/x-chess-pgn' => ['pgn'], + 'application/x-chrome-extension' => ['crx'], + 'application/x-cocoa' => ['cco'], + 'application/x-conference' => ['nsc'], + 'application/x-cpio' => ['cpio'], + 'application/x-csh' => ['csh'], + 'application/x-debian-package' => ['deb', 'udeb'], + 'application/x-dgc-compressed' => ['dgc'], + 'application/x-director' => ['dir', 'dcr', 'dxr', 'cst', 'cct', 'cxt', 'w3d', 'fgd', 'swa'], + 'application/x-doom' => ['wad'], + 'application/x-dtbncx+xml' => ['ncx'], + 'application/x-dtbook+xml' => ['dtb'], + 'application/x-dtbresource+xml' => ['res'], + 'application/x-dvi' => ['dvi'], + 'application/x-envoy' => ['evy'], + 'application/x-eva' => ['eva'], + 'application/x-font-bdf' => ['bdf'], + 'application/x-font-ghostscript' => ['gsf'], + 'application/x-font-linux-psf' => ['psf'], + 'application/x-font-pcf' => ['pcf'], + 'application/x-font-snf' => ['snf'], + 'application/x-font-type1' => ['pfa', 'pfb', 'pfm', 'afm'], + 'application/x-freearc' => ['arc'], + 'application/x-futuresplash' => ['spl'], + 'application/x-gca-compressed' => ['gca'], + 'application/x-glulx' => ['ulx'], + 'application/x-gnumeric' => ['gnumeric'], + 'application/x-gramps-xml' => ['gramps'], + 'application/x-gtar' => ['gtar'], + 'application/x-hdf' => ['hdf'], + 'application/x-httpd-php' => ['php', 'php4', 'php3', 'phtml'], + 'application/x-install-instructions' => ['install'], + 'application/x-iso9660-image' => ['iso'], + 'application/x-iwork-keynote-sffkey' => ['key'], + 'application/x-iwork-numbers-sffnumbers' => ['numbers'], + 'application/x-iwork-pages-sffpages' => ['pages'], + 'application/x-java-archive-diff' => ['jardiff'], + 'application/x-java-jnlp-file' => ['jnlp'], + 'application/x-keepass2' => ['kdbx'], + 'application/x-latex' => ['latex'], + 'application/x-lua-bytecode' => ['luac'], + 'application/x-lzh-compressed' => ['lzh', 'lha'], + 'application/x-makeself' => ['run'], + 'application/x-mie' => ['mie'], + 'application/x-mobipocket-ebook' => ['prc', 'mobi'], + 'application/x-ms-application' => ['application'], + 'application/x-ms-shortcut' => ['lnk'], + 'application/x-ms-wmd' => ['wmd'], + 'application/x-ms-wmz' => ['wmz'], + 'application/x-ms-xbap' => ['xbap'], + 'application/x-msaccess' => ['mdb'], + 'application/x-msbinder' => ['obd'], + 'application/x-mscardfile' => ['crd'], + 'application/x-msclip' => ['clp'], + 'application/x-msdos-program' => ['exe'], + 'application/x-msdownload' => ['exe', 'dll', 'com', 'bat', 'msi'], + 'application/x-msmediaview' => ['mvb', 'm13', 'm14'], + 'application/x-msmetafile' => ['wmf', 'wmz', 'emf', 'emz'], + 'application/x-msmoney' => ['mny'], + 'application/x-mspublisher' => ['pub'], + 'application/x-msschedule' => ['scd'], + 'application/x-msterminal' => ['trm'], + 'application/x-mswrite' => ['wri'], + 'application/x-netcdf' => ['nc', 'cdf'], + 'application/x-ns-proxy-autoconfig' => ['pac'], + 'application/x-nzb' => ['nzb'], + 'application/x-perl' => ['pl', 'pm'], + 'application/x-pilot' => ['prc', 'pdb'], + 'application/x-pkcs12' => ['p12', 'pfx'], + 'application/x-pkcs7-certificates' => ['p7b', 'spc'], + 'application/x-pkcs7-certreqresp' => ['p7r'], + 'application/x-rar-compressed' => ['rar'], + 'application/x-redhat-package-manager' => ['rpm'], + 'application/x-research-info-systems' => ['ris'], + 'application/x-sea' => ['sea'], + 'application/x-sh' => ['sh'], + 'application/x-shar' => ['shar'], + 'application/x-shockwave-flash' => ['swf'], + 'application/x-silverlight-app' => ['xap'], + 'application/x-sql' => ['sql'], + 'application/x-stuffit' => ['sit'], + 'application/x-stuffitx' => ['sitx'], + 'application/x-subrip' => ['srt'], + 'application/x-sv4cpio' => ['sv4cpio'], + 'application/x-sv4crc' => ['sv4crc'], + 'application/x-t3vm-image' => ['t3'], + 'application/x-tads' => ['gam'], + 'application/x-tar' => ['tar', 'tgz'], + 'application/x-tcl' => ['tcl', 'tk'], + 'application/x-tex' => ['tex'], + 'application/x-tex-tfm' => ['tfm'], + 'application/x-texinfo' => ['texinfo', 'texi'], + 'application/x-tgif' => ['obj'], + 'application/x-ustar' => ['ustar'], + 'application/x-virtualbox-hdd' => ['hdd'], + 'application/x-virtualbox-ova' => ['ova'], + 'application/x-virtualbox-ovf' => ['ovf'], + 'application/x-virtualbox-vbox' => ['vbox'], + 'application/x-virtualbox-vbox-extpack' => ['vbox-extpack'], + 'application/x-virtualbox-vdi' => ['vdi'], + 'application/x-virtualbox-vhd' => ['vhd'], + 'application/x-virtualbox-vmdk' => ['vmdk'], + 'application/x-wais-source' => ['src'], + 'application/x-web-app-manifest+json' => ['webapp'], + 'application/x-x509-ca-cert' => ['der', 'crt', 'pem'], + 'application/x-xfig' => ['fig'], + 'application/x-xliff+xml' => ['xlf'], + 'application/x-xpinstall' => ['xpi'], + 'application/x-xz' => ['xz'], + 'application/x-zmachine' => ['z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7', 'z8'], + 'application/xaml+xml' => ['xaml'], + 'application/xcap-att+xml' => ['xav'], + 'application/xcap-caps+xml' => ['xca'], + 'application/xcap-diff+xml' => ['xdf'], + 'application/xcap-el+xml' => ['xel'], + 'application/xcap-ns+xml' => ['xns'], + 'application/xenc+xml' => ['xenc'], + 'application/xfdf' => ['xfdf'], + 'application/xhtml+xml' => ['xhtml', 'xht'], + 'application/xliff+xml' => ['xlf'], + 'application/xml' => ['xml', 'xsl', 'xsd', 'rng'], + 'application/xml-dtd' => ['dtd'], + 'application/xop+xml' => ['xop'], + 'application/xproc+xml' => ['xpl'], + 'application/xslt+xml' => ['xsl', 'xslt'], + 'application/xspf+xml' => ['xspf'], + 'application/xv+xml' => ['mxml', 'xhvml', 'xvml', 'xvm'], + 'application/yang' => ['yang'], + 'application/yin+xml' => ['yin'], + 'application/zip' => ['zip'], + 'audio/3gpp' => ['3gpp'], + 'audio/aac' => ['adts', 'aac'], + 'audio/adpcm' => ['adp'], + 'audio/amr' => ['amr'], + 'audio/basic' => ['au', 'snd'], + 'audio/midi' => ['mid', 'midi', 'kar', 'rmi'], + 'audio/mobile-xmf' => ['mxmf'], + 'audio/mp3' => ['mp3'], + 'audio/mp4' => ['m4a', 'mp4a'], + 'audio/mpeg' => ['mpga', 'mp2', 'mp2a', 'mp3', 'm2a', 'm3a'], + 'audio/ogg' => ['oga', 'ogg', 'spx', 'opus'], + 'audio/s3m' => ['s3m'], + 'audio/silk' => ['sil'], + 'audio/vnd.dece.audio' => ['uva', 'uvva'], + 'audio/vnd.digital-winds' => ['eol'], + 'audio/vnd.dra' => ['dra'], + 'audio/vnd.dts' => ['dts'], + 'audio/vnd.dts.hd' => ['dtshd'], + 'audio/vnd.lucent.voice' => ['lvp'], + 'audio/vnd.ms-playready.media.pya' => ['pya'], + 'audio/vnd.nuera.ecelp4800' => ['ecelp4800'], + 'audio/vnd.nuera.ecelp7470' => ['ecelp7470'], + 'audio/vnd.nuera.ecelp9600' => ['ecelp9600'], + 'audio/vnd.rip' => ['rip'], + 'audio/wav' => ['wav'], + 'audio/wave' => ['wav'], + 'audio/webm' => ['weba'], + 'audio/x-aac' => ['aac'], + 'audio/x-aiff' => ['aif', 'aiff', 'aifc'], + 'audio/x-caf' => ['caf'], + 'audio/x-flac' => ['flac'], + 'audio/x-m4a' => ['m4a'], + 'audio/x-matroska' => ['mka'], + 'audio/x-mpegurl' => ['m3u'], + 'audio/x-ms-wax' => ['wax'], + 'audio/x-ms-wma' => ['wma'], + 'audio/x-pn-realaudio' => ['ram', 'ra', 'rm'], + 'audio/x-pn-realaudio-plugin' => ['rmp', 'rpm'], + 'audio/x-realaudio' => ['ra'], + 'audio/x-wav' => ['wav'], + 'audio/xm' => ['xm'], + 'chemical/x-cdx' => ['cdx'], + 'chemical/x-cif' => ['cif'], + 'chemical/x-cmdf' => ['cmdf'], + 'chemical/x-cml' => ['cml'], + 'chemical/x-csml' => ['csml'], + 'chemical/x-xyz' => ['xyz'], + 'font/collection' => ['ttc'], + 'font/otf' => ['otf'], + 'font/ttf' => ['ttf'], + 'font/woff' => ['woff'], + 'font/woff2' => ['woff2'], + 'image/aces' => ['exr'], + 'image/apng' => ['apng'], + 'image/avci' => ['avci'], + 'image/avcs' => ['avcs'], + 'image/avif' => ['avif'], + 'image/bmp' => ['bmp', 'dib'], + 'image/cgm' => ['cgm'], + 'image/dicom-rle' => ['drle'], + 'image/dpx' => ['dpx'], + 'image/emf' => ['emf'], + 'image/fits' => ['fits'], + 'image/g3fax' => ['g3'], + 'image/gif' => ['gif'], + 'image/heic' => ['heic'], + 'image/heic-sequence' => ['heics'], + 'image/heif' => ['heif'], + 'image/heif-sequence' => ['heifs'], + 'image/hej2k' => ['hej2'], + 'image/hsj2' => ['hsj2'], + 'image/ief' => ['ief'], + 'image/jls' => ['jls'], + 'image/jp2' => ['jp2', 'jpg2'], + 'image/jpeg' => ['jpeg', 'jpg', 'jpe'], + 'image/jph' => ['jph'], + 'image/jphc' => ['jhc'], + 'image/jpm' => ['jpm', 'jpgm'], + 'image/jpx' => ['jpx', 'jpf'], + 'image/jxr' => ['jxr'], + 'image/jxra' => ['jxra'], + 'image/jxrs' => ['jxrs'], + 'image/jxs' => ['jxs'], + 'image/jxsc' => ['jxsc'], + 'image/jxsi' => ['jxsi'], + 'image/jxss' => ['jxss'], + 'image/ktx' => ['ktx'], + 'image/ktx2' => ['ktx2'], + 'image/png' => ['png'], + 'image/prs.btif' => ['btif', 'btf'], + 'image/prs.pti' => ['pti'], + 'image/sgi' => ['sgi'], + 'image/svg+xml' => ['svg', 'svgz'], + 'image/t38' => ['t38'], + 'image/tiff' => ['tif', 'tiff'], + 'image/tiff-fx' => ['tfx'], + 'image/vnd.adobe.photoshop' => ['psd'], + 'image/vnd.airzip.accelerator.azv' => ['azv'], + 'image/vnd.dece.graphic' => ['uvi', 'uvvi', 'uvg', 'uvvg'], + 'image/vnd.djvu' => ['djvu', 'djv'], + 'image/vnd.dvb.subtitle' => ['sub'], + 'image/vnd.dwg' => ['dwg'], + 'image/vnd.dxf' => ['dxf'], + 'image/vnd.fastbidsheet' => ['fbs'], + 'image/vnd.fpx' => ['fpx'], + 'image/vnd.fst' => ['fst'], + 'image/vnd.fujixerox.edmics-mmr' => ['mmr'], + 'image/vnd.fujixerox.edmics-rlc' => ['rlc'], + 'image/vnd.microsoft.icon' => ['ico'], + 'image/vnd.ms-dds' => ['dds'], + 'image/vnd.ms-modi' => ['mdi'], + 'image/vnd.ms-photo' => ['wdp'], + 'image/vnd.net-fpx' => ['npx'], + 'image/vnd.pco.b16' => ['b16'], + 'image/vnd.tencent.tap' => ['tap'], + 'image/vnd.valve.source.texture' => ['vtf'], + 'image/vnd.wap.wbmp' => ['wbmp'], + 'image/vnd.xiff' => ['xif'], + 'image/vnd.zbrush.pcx' => ['pcx'], + 'image/webp' => ['webp'], + 'image/wmf' => ['wmf'], + 'image/x-3ds' => ['3ds'], + 'image/x-cmu-raster' => ['ras'], + 'image/x-cmx' => ['cmx'], + 'image/x-freehand' => ['fh', 'fhc', 'fh4', 'fh5', 'fh7'], + 'image/x-icon' => ['ico'], + 'image/x-jng' => ['jng'], + 'image/x-mrsid-image' => ['sid'], + 'image/x-ms-bmp' => ['bmp'], + 'image/x-pcx' => ['pcx'], + 'image/x-pict' => ['pic', 'pct'], + 'image/x-portable-anymap' => ['pnm'], + 'image/x-portable-bitmap' => ['pbm'], + 'image/x-portable-graymap' => ['pgm'], + 'image/x-portable-pixmap' => ['ppm'], + 'image/x-rgb' => ['rgb'], + 'image/x-tga' => ['tga'], + 'image/x-xbitmap' => ['xbm'], + 'image/x-xpixmap' => ['xpm'], + 'image/x-xwindowdump' => ['xwd'], + 'message/disposition-notification' => ['disposition-notification'], + 'message/global' => ['u8msg'], + 'message/global-delivery-status' => ['u8dsn'], + 'message/global-disposition-notification' => ['u8mdn'], + 'message/global-headers' => ['u8hdr'], + 'message/rfc822' => ['eml', 'mime'], + 'message/vnd.wfa.wsc' => ['wsc'], + 'model/3mf' => ['3mf'], + 'model/gltf+json' => ['gltf'], + 'model/gltf-binary' => ['glb'], + 'model/iges' => ['igs', 'iges'], + 'model/jt' => ['jt'], + 'model/mesh' => ['msh', 'mesh', 'silo'], + 'model/mtl' => ['mtl'], + 'model/obj' => ['obj'], + 'model/prc' => ['prc'], + 'model/step+xml' => ['stpx'], + 'model/step+zip' => ['stpz'], + 'model/step-xml+zip' => ['stpxz'], + 'model/stl' => ['stl'], + 'model/u3d' => ['u3d'], + 'model/vnd.cld' => ['cld'], + 'model/vnd.collada+xml' => ['dae'], + 'model/vnd.dwf' => ['dwf'], + 'model/vnd.gdl' => ['gdl'], + 'model/vnd.gtw' => ['gtw'], + 'model/vnd.mts' => ['mts'], + 'model/vnd.opengex' => ['ogex'], + 'model/vnd.parasolid.transmit.binary' => ['x_b'], + 'model/vnd.parasolid.transmit.text' => ['x_t'], + 'model/vnd.pytha.pyox' => ['pyo', 'pyox'], + 'model/vnd.sap.vds' => ['vds'], + 'model/vnd.usda' => ['usda'], + 'model/vnd.usdz+zip' => ['usdz'], + 'model/vnd.valve.source.compiled-map' => ['bsp'], + 'model/vnd.vtu' => ['vtu'], + 'model/vrml' => ['wrl', 'vrml'], + 'model/x3d+binary' => ['x3db', 'x3dbz'], + 'model/x3d+fastinfoset' => ['x3db'], + 'model/x3d+vrml' => ['x3dv', 'x3dvz'], + 'model/x3d+xml' => ['x3d', 'x3dz'], + 'model/x3d-vrml' => ['x3dv'], + 'text/cache-manifest' => ['appcache', 'manifest'], + 'text/calendar' => ['ics', 'ifb'], + 'text/coffeescript' => ['coffee', 'litcoffee'], + 'text/css' => ['css'], + 'text/csv' => ['csv'], + 'text/html' => ['html', 'htm', 'shtml'], + 'text/jade' => ['jade'], + 'text/javascript' => ['js', 'mjs'], + 'text/jsx' => ['jsx'], + 'text/less' => ['less'], + 'text/markdown' => ['md', 'markdown'], + 'text/mathml' => ['mml'], + 'text/mdx' => ['mdx'], + 'text/n3' => ['n3'], + 'text/plain' => ['txt', 'text', 'conf', 'def', 'list', 'log', 'in', 'ini', 'm3u'], + 'text/prs.lines.tag' => ['dsc'], + 'text/richtext' => ['rtx'], + 'text/rtf' => ['rtf'], + 'text/sgml' => ['sgml', 'sgm'], + 'text/shex' => ['shex'], + 'text/slim' => ['slim', 'slm'], + 'text/spdx' => ['spdx'], + 'text/stylus' => ['stylus', 'styl'], + 'text/tab-separated-values' => ['tsv'], + 'text/troff' => ['t', 'tr', 'roff', 'man', 'me', 'ms'], + 'text/turtle' => ['ttl'], + 'text/uri-list' => ['uri', 'uris', 'urls'], + 'text/vcard' => ['vcard'], + 'text/vnd.curl' => ['curl'], + 'text/vnd.curl.dcurl' => ['dcurl'], + 'text/vnd.curl.mcurl' => ['mcurl'], + 'text/vnd.curl.scurl' => ['scurl'], + 'text/vnd.dvb.subtitle' => ['sub'], + 'text/vnd.familysearch.gedcom' => ['ged'], + 'text/vnd.fly' => ['fly'], + 'text/vnd.fmi.flexstor' => ['flx'], + 'text/vnd.graphviz' => ['gv'], + 'text/vnd.in3d.3dml' => ['3dml'], + 'text/vnd.in3d.spot' => ['spot'], + 'text/vnd.sun.j2me.app-descriptor' => ['jad'], + 'text/vnd.wap.wml' => ['wml'], + 'text/vnd.wap.wmlscript' => ['wmls'], + 'text/vtt' => ['vtt'], + 'text/wgsl' => ['wgsl'], + 'text/x-asm' => ['s', 'asm'], + 'text/x-c' => ['c', 'cc', 'cxx', 'cpp', 'h', 'hh', 'dic'], + 'text/x-component' => ['htc'], + 'text/x-fortran' => ['f', 'for', 'f77', 'f90'], + 'text/x-handlebars-template' => ['hbs'], + 'text/x-java-source' => ['java'], + 'text/x-lua' => ['lua'], + 'text/x-markdown' => ['mkd'], + 'text/x-nfo' => ['nfo'], + 'text/x-opml' => ['opml'], + 'text/x-org' => ['org'], + 'text/x-pascal' => ['p', 'pas'], + 'text/x-processing' => ['pde'], + 'text/x-sass' => ['sass'], + 'text/x-scss' => ['scss'], + 'text/x-setext' => ['etx'], + 'text/x-sfv' => ['sfv'], + 'text/x-suse-ymp' => ['ymp'], + 'text/x-uuencode' => ['uu'], + 'text/x-vcalendar' => ['vcs'], + 'text/x-vcard' => ['vcf'], + 'text/xml' => ['xml'], + 'text/yaml' => ['yaml', 'yml'], + 'video/3gpp' => ['3gp', '3gpp'], + 'video/3gpp2' => ['3g2'], + 'video/h261' => ['h261'], + 'video/h263' => ['h263'], + 'video/h264' => ['h264'], + 'video/iso.segment' => ['m4s'], + 'video/jpeg' => ['jpgv'], + 'video/jpm' => ['jpm', 'jpgm'], + 'video/mj2' => ['mj2', 'mjp2'], + 'video/mp2t' => ['ts'], + 'video/mp4' => ['mp4', 'mp4v', 'mpg4', 'f4v'], + 'video/mpeg' => ['mpeg', 'mpg', 'mpe', 'm1v', 'm2v'], + 'video/ogg' => ['ogv'], + 'video/quicktime' => ['qt', 'mov'], + 'video/vnd.dece.hd' => ['uvh', 'uvvh'], + 'video/vnd.dece.mobile' => ['uvm', 'uvvm'], + 'video/vnd.dece.pd' => ['uvp', 'uvvp'], + 'video/vnd.dece.sd' => ['uvs', 'uvvs'], + 'video/vnd.dece.video' => ['uvv', 'uvvv'], + 'video/vnd.dvb.file' => ['dvb'], + 'video/vnd.fvt' => ['fvt'], + 'video/vnd.mpegurl' => ['mxu', 'm4u'], + 'video/vnd.ms-playready.media.pyv' => ['pyv'], + 'video/vnd.uvvu.mp4' => ['uvu', 'uvvu'], + 'video/vnd.vivo' => ['viv'], + 'video/webm' => ['webm'], + 'video/x-f4v' => ['f4v'], + 'video/x-fli' => ['fli'], + 'video/x-flv' => ['flv'], + 'video/x-m4v' => ['m4v'], + 'video/x-matroska' => ['mkv', 'mk3d', 'mks'], + 'video/x-mng' => ['mng'], + 'video/x-ms-asf' => ['asf', 'asx'], + 'video/x-ms-vob' => ['vob'], + 'video/x-ms-wm' => ['wm'], + 'video/x-ms-wmv' => ['wmv'], + 'video/x-ms-wmx' => ['wmx'], + 'video/x-ms-wvx' => ['wvx'], + 'video/x-msvideo' => ['avi'], + 'video/x-sgi-movie' => ['movie'], + 'video/x-smv' => ['smv'], + 'x-conference/x-cooltalk' => ['ice'], + 'application/x-photoshop' => ['psd'], + 'application/smil' => ['smi', 'smil'], + 'application/powerpoint' => ['ppt'], + 'application/vnd.ms-powerpoint.addin.macroEnabled.12' => ['ppam'], + 'application/vnd.ms-powerpoint.presentation.macroEnabled.12' => ['pptm', 'potm'], + 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12' => ['ppsm'], + 'application/wbxml' => ['wbxml'], + 'application/wmlc' => ['wmlc'], + 'application/x-httpd-php-source' => ['phps'], + 'application/x-compress' => ['z'], + 'application/x-rar' => ['rar'], + 'video/vnd.rn-realvideo' => ['rv'], + 'application/vnd.ms-word.template.macroEnabled.12' => ['docm', 'dotm'], + 'application/vnd.ms-excel.sheet.macroEnabled.12' => ['xlsm'], + 'application/vnd.ms-excel.template.macroEnabled.12' => ['xltm'], + 'application/vnd.ms-excel.addin.macroEnabled.12' => ['xlam'], + 'application/vnd.ms-excel.sheet.binary.macroEnabled.12' => ['xlsb'], + 'application/excel' => ['xl'], + 'application/x-x509-user-cert' => ['pem'], + 'application/x-pkcs10' => ['p10'], + 'application/x-pkcs7-signature' => ['p7a'], + 'application/pgp' => ['pgp'], + 'application/gpg-keys' => ['gpg'], + 'application/x-pkcs7' => ['rsa'], + 'video/3gp' => ['3gp'], + 'audio/acc' => ['aac'], + 'application/vnd.mpegurl' => ['m4u'], + 'application/videolan' => ['vlc'], + 'audio/x-au' => ['au'], + 'audio/ac3' => ['ac3'], + 'text/x-scriptzsh' => ['zsh'], + 'application/cdr' => ['cdr'], + 'application/STEP' => ['step', 'stp'], + 'application/x-ndjson' => ['ndjson'], + 'application/braille' => ['brf'], + ]; + + public function lookupMimeType(string $extension): ?string + { + return self::MIME_TYPES_FOR_EXTENSIONS[$extension] ?? null; + } + + public function lookupExtension(string $mimetype): ?string + { + return self::EXTENSIONS_FOR_MIME_TIMES[$mimetype][0] ?? null; + } + + /** + * @return string[] + */ + public function lookupAllExtensions(string $mimetype): array + { + return self::EXTENSIONS_FOR_MIME_TIMES[$mimetype] ?? []; + } +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/MimeTypeDetector.php b/php/libraries/composer/vendor/league/mime-type-detection/src/MimeTypeDetector.php new file mode 100644 index 0000000..5d799d2 --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/MimeTypeDetector.php @@ -0,0 +1,19 @@ +<?php + +declare(strict_types=1); + +namespace League\MimeTypeDetection; + +interface MimeTypeDetector +{ + /** + * @param string|resource $contents + */ + public function detectMimeType(string $path, $contents): ?string; + + public function detectMimeTypeFromBuffer(string $contents): ?string; + + public function detectMimeTypeFromPath(string $path): ?string; + + public function detectMimeTypeFromFile(string $path): ?string; +} diff --git a/php/libraries/composer/vendor/league/mime-type-detection/src/OverridingExtensionToMimeTypeMap.php b/php/libraries/composer/vendor/league/mime-type-detection/src/OverridingExtensionToMimeTypeMap.php new file mode 100644 index 0000000..0c71e4d --- /dev/null +++ b/php/libraries/composer/vendor/league/mime-type-detection/src/OverridingExtensionToMimeTypeMap.php @@ -0,0 +1,30 @@ +<?php + +namespace League\MimeTypeDetection; + +class OverridingExtensionToMimeTypeMap implements ExtensionToMimeTypeMap +{ + /** + * @var ExtensionToMimeTypeMap + */ + private $innerMap; + + /** + * @var string[] + */ + private $overrides; + + /** + * @param array<string, string> $overrides + */ + public function __construct(ExtensionToMimeTypeMap $innerMap, array $overrides) + { + $this->innerMap = $innerMap; + $this->overrides = $overrides; + } + + public function lookupMimeType(string $extension): ?string + { + return $this->overrides[$extension] ?? $this->innerMap->lookupMimeType($extension); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/CHANGELOG.md b/php/libraries/composer/vendor/monolog/monolog/CHANGELOG.md new file mode 100644 index 0000000..aca1bdd --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/CHANGELOG.md @@ -0,0 +1,629 @@ +### 2.9.2 (2023-10-27) + + * Fixed display_errors parsing in ErrorHandler which did not support string values (#1804) + * Fixed bug where the previous error handler would not be restored in some cases where StreamHandler fails (#1815) + * Fixed normalization error when normalizing incomplete classes (#1833) + +### 2.9.1 (2023-02-06) + + * Fixed Logger not being serializable anymore (#1792) + +### 2.9.0 (2023-02-05) + + * Deprecated FlowdockHandler & Formatter as the flowdock service was shutdown (#1748) + * Added support for enum context values in PsrLogMessageProcessor (#1773) + * Added graylog2/gelf-php 2.x support (#1747) + * Improved `BrowserConsoleHandler` logging to use more appropriate methods than just console.log in the browser (#1739) + * Fixed `WhatFailureGroupHandler` not catching errors happening inside `close()` (#1791) + * Fixed datetime field in `GoogleCloudLoggingFormatter` (#1758) + * Fixed infinite loop detection within Fibers (#1753) + * Fixed `AmqpHandler->setExtraAttributes` not working with buffering handler wrappers (#1781) + +### 2.8.0 (2022-07-24) + + * Deprecated `CubeHandler` and `PHPConsoleHandler` as both projects are abandoned and those should not be used anymore (#1734) + * Added RFC 5424 level (`7` to `0`) support to `Logger::log` and `Logger::addRecord` to increase interoperability (#1723) + * Added support for `__toString` for objects which are not json serializable in `JsonFormatter` (#1733) + * Added `GoogleCloudLoggingFormatter` (#1719) + * Added support for Predis 2.x (#1732) + * Added `AmqpHandler->setExtraAttributes` to allow configuring attributes when using an AMQPExchange (#1724) + * Fixed serialization/unserialization of handlers to make sure private properties are included (#1727) + * Fixed allowInlineLineBreaks in LineFormatter causing issues with windows paths containing `\n` or `\r` sequences (#1720) + * Fixed max normalization depth not being taken into account when formatting exceptions with a deep chain of previous exceptions (#1726) + * Fixed PHP 8.2 deprecation warnings (#1722) + * Fixed rare race condition or filesystem issue where StreamHandler is unable to create the directory the log should go into yet it exists already (#1678) + +### 2.7.0 (2022-06-09) + + * Added `$datetime` parameter to `Logger::addRecord` as low level API to allow logging into the past or future (#1682) + * Added `Logger::useLoggingLoopDetection` to allow disabling cyclic logging detection in concurrent frameworks (#1681) + * Fixed handling of fatal errors if callPrevious is disabled in ErrorHandler (#1670) + * Marked the reusable `Monolog\Test\TestCase` class as `@internal` to make sure PHPStorm does not show it above PHPUnit, you may still use it to test your own handlers/etc though (#1677) + * Fixed RotatingFileHandler issue when the date format contained slashes (#1671) + +### 2.6.0 (2022-05-10) + + * Deprecated `SwiftMailerHandler`, use `SymfonyMailerHandler` instead + * Added `SymfonyMailerHandler` (#1663) + * Added ElasticSearch 8.x support to the ElasticsearchHandler (#1662) + * Added a way to filter/modify stack traces in LineFormatter (#1665) + * Fixed UdpSocket not being able to reopen/reconnect after close() + * Fixed infinite loops if a Handler is triggering logging while handling log records + +### 2.5.0 (2022-04-08) + + * Added `callType` to IntrospectionProcessor (#1612) + * Fixed AsMonologProcessor syntax to be compatible with PHP 7.2 (#1651) + +### 2.4.0 (2022-03-14) + + * Added [`Monolog\LogRecord`](src/Monolog/LogRecord.php) interface that can be used to type-hint records like `array|\Monolog\LogRecord $record` to be forward compatible with the upcoming Monolog 3 changes + * Added `includeStacktraces` constructor params to LineFormatter & JsonFormatter (#1603) + * Added `persistent`, `timeout`, `writingTimeout`, `connectionTimeout`, `chunkSize` constructor params to SocketHandler and derivatives (#1600) + * Added `AsMonologProcessor` PHP attribute which can help autowiring / autoconfiguration of processors if frameworks / integrations decide to make use of it. This is useless when used purely with Monolog (#1637) + * Added support for keeping native BSON types as is in MongoDBFormatter (#1620) + * Added support for a `user_agent` key in WebProcessor, disabled by default but you can use it by configuring the $extraFields you want (#1613) + * Added support for username/userIcon in SlackWebhookHandler (#1617) + * Added extension points to BrowserConsoleHandler (#1593) + * Added record message/context/extra info to exceptions thrown when a StreamHandler cannot open its stream to avoid completely losing the data logged (#1630) + * Fixed error handler signature to accept a null $context which happens with internal PHP errors (#1614) + * Fixed a few setter methods not returning `self` (#1609) + * Fixed handling of records going over the max Telegram message length (#1616) + +### 2.3.5 (2021-10-01) + + * Fixed regression in StreamHandler since 2.3.3 on systems with the memory_limit set to >=20GB (#1592) + +### 2.3.4 (2021-09-15) + + * Fixed support for psr/log 3.x (#1589) + +### 2.3.3 (2021-09-14) + + * Fixed memory usage when using StreamHandler and calling stream_get_contents on the resource you passed to it (#1578, #1577) + * Fixed support for psr/log 2.x (#1587) + * Fixed some type annotations + +### 2.3.2 (2021-07-23) + + * Fixed compatibility with PHP 7.2 - 7.4 when experiencing PCRE errors (#1568) + +### 2.3.1 (2021-07-14) + + * Fixed Utils::getClass handling of anonymous classes not being fully compatible with PHP 8 (#1563) + * Fixed some `@inheritDoc` annotations having the wrong case + +### 2.3.0 (2021-07-05) + + * Added a ton of PHPStan type annotations as well as type aliases on Monolog\Logger for Record, Level and LevelName that you can import (#1557) + * Added ability to customize date format when using JsonFormatter (#1561) + * Fixed FilterHandler not calling reset on its internal handler when reset() is called on it (#1531) + * Fixed SyslogUdpHandler not setting the timezone correctly on DateTimeImmutable instances (#1540) + * Fixed StreamHandler thread safety - chunk size set to 2GB now to avoid interlacing when doing concurrent writes (#1553) + +### 2.2.0 (2020-12-14) + + * Added JSON_PARTIAL_OUTPUT_ON_ERROR to default json encoding flags, to avoid dropping entire context data or even records due to an invalid subset of it somewhere + * Added setDateFormat to NormalizerFormatter (and Line/Json formatters by extension) to allow changing this after object creation + * Added RedisPubSubHandler to log records to a Redis channel using PUBLISH + * Added support for Elastica 7, and deprecated the $type argument of ElasticaFormatter which is not in use anymore as of Elastica 7 + * Added support for millisecond write timeouts in SocketHandler, you can now pass floats to setWritingTimeout, e.g. 0.2 is 200ms + * Added support for unix sockets in SyslogUdpHandler (set $port to 0 to make the $host a unix socket) + * Added handleBatch support for TelegramBotHandler + * Added RFC5424e extended date format including milliseconds to SyslogUdpHandler + * Added support for configuring handlers with numeric level values in strings (coming from e.g. env vars) + * Fixed Wildfire/FirePHP/ChromePHP handling of unicode characters + * Fixed PHP 8 issues in SyslogUdpHandler + * Fixed internal type error when mbstring is missing + +### 2.1.1 (2020-07-23) + + * Fixed removing of json encoding options + * Fixed type hint of $level not accepting strings in SendGridHandler and OverflowHandler + * Fixed SwiftMailerHandler not accepting email templates with an empty subject + * Fixed array access on null in RavenHandler + * Fixed unique_id in WebProcessor not being disableable + +### 2.1.0 (2020-05-22) + + * Added `JSON_INVALID_UTF8_SUBSTITUTE` to default json flags, so that invalid UTF8 characters now get converted to [�](https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character) instead of being converted from ISO-8859-15 to UTF8 as it was before, which was hardly a comprehensive solution + * Added `$ignoreEmptyContextAndExtra` option to JsonFormatter to skip empty context/extra entirely from the output + * Added `$parseMode`, `$disableWebPagePreview` and `$disableNotification` options to TelegramBotHandler + * Added tentative support for PHP 8 + * NormalizerFormatter::addJsonEncodeOption and removeJsonEncodeOption are now public to allow modifying default json flags + * Fixed GitProcessor type error when there is no git repo present + * Fixed normalization of SoapFault objects containing deeply nested objects as "detail" + * Fixed support for relative paths in RotatingFileHandler + +### 2.0.2 (2019-12-20) + + * Fixed ElasticsearchHandler swallowing exceptions details when failing to index log records + * Fixed normalization of SoapFault objects containing non-strings as "detail" in LineFormatter + * Fixed formatting of resources in JsonFormatter + * Fixed RedisHandler failing to use MULTI properly when passed a proxied Redis instance (e.g. in Symfony with lazy services) + * Fixed FilterHandler triggering a notice when handleBatch was filtering all records passed to it + * Fixed Turkish locale messing up the conversion of level names to their constant values + +### 2.0.1 (2019-11-13) + + * Fixed normalization of Traversables to avoid traversing them as not all of them are rewindable + * Fixed setFormatter/getFormatter to forward to the nested handler in FilterHandler, FingersCrossedHandler, BufferHandler, OverflowHandler and SamplingHandler + * Fixed BrowserConsoleHandler formatting when using multiple styles + * Fixed normalization of exception codes to be always integers even for PDOException which have them as numeric strings + * Fixed normalization of SoapFault objects containing non-strings as "detail" + * Fixed json encoding across all handlers to always attempt recovery of non-UTF-8 strings instead of failing the whole encoding + * Fixed ChromePHPHandler to avoid sending more data than latest Chrome versions allow in headers (4KB down from 256KB). + * Fixed type error in BrowserConsoleHandler when the context array of log records was not associative. + +### 2.0.0 (2019-08-30) + + * BC Break: This is a major release, see [UPGRADE.md](UPGRADE.md) for details if you are coming from a 1.x release + * BC Break: Logger methods log/debug/info/notice/warning/error/critical/alert/emergency now have explicit void return types + * Added FallbackGroupHandler which works like the WhatFailureGroupHandler but stops dispatching log records as soon as one handler accepted it + * Fixed support for UTF-8 when cutting strings to avoid cutting a multibyte-character in half + * Fixed normalizers handling of exception backtraces to avoid serializing arguments in some cases + * Fixed date timezone handling in SyslogUdpHandler + +### 2.0.0-beta2 (2019-07-06) + + * BC Break: This is a major release, see [UPGRADE.md](UPGRADE.md) for details if you are coming from a 1.x release + * BC Break: PHP 7.2 is now the minimum required PHP version. + * BC Break: Removed SlackbotHandler, RavenHandler and HipChatHandler, see [UPGRADE.md](UPGRADE.md) for details + * Added OverflowHandler which will only flush log records to its nested handler when reaching a certain amount of logs (i.e. only pass through when things go really bad) + * Added TelegramBotHandler to log records to a [Telegram](https://core.telegram.org/bots/api) bot account + * Added support for JsonSerializable when normalizing exceptions + * Added support for RFC3164 (outdated BSD syslog protocol) to SyslogUdpHandler + * Added SoapFault details to formatted exceptions + * Fixed DeduplicationHandler silently failing to start when file could not be opened + * Fixed issue in GroupHandler and WhatFailureGroupHandler where setting multiple processors would duplicate records + * Fixed GelfFormatter losing some data when one attachment was too long + * Fixed issue in SignalHandler restarting syscalls functionality + * Improved performance of LogglyHandler when sending multiple logs in a single request + +### 2.0.0-beta1 (2018-12-08) + + * BC Break: This is a major release, see [UPGRADE.md](UPGRADE.md) for details if you are coming from a 1.x release + * BC Break: PHP 7.1 is now the minimum required PHP version. + * BC Break: Quite a few interface changes, only relevant if you implemented your own handlers/processors/formatters + * BC Break: Removed non-PSR-3 methods to add records, all the `add*` (e.g. `addWarning`) methods as well as `emerg`, `crit`, `err` and `warn` + * BC Break: The record timezone is now set per Logger instance and not statically anymore + * BC Break: There is no more default handler configured on empty Logger instances + * BC Break: ElasticSearchHandler renamed to ElasticaHandler + * BC Break: Various handler-specific breaks, see [UPGRADE.md](UPGRADE.md) for details + * Added scalar type hints and return hints in all the places it was possible. Switched strict_types on for more reliability. + * Added DateTimeImmutable support, all record datetime are now immutable, and will toString/json serialize with the correct date format, including microseconds (unless disabled) + * Added timezone and microseconds to the default date format + * Added SendGridHandler to use the SendGrid API to send emails + * Added LogmaticHandler to use the Logmatic.io API to store log records + * Added SqsHandler to send log records to an AWS SQS queue + * Added ElasticsearchHandler to send records via the official ES library. Elastica users should now use ElasticaHandler instead of ElasticSearchHandler + * Added NoopHandler which is similar to the NullHandle but does not prevent the bubbling of log records to handlers further down the configuration, useful for temporarily disabling a handler in configuration files + * Added ProcessHandler to write log output to the STDIN of a given process + * Added HostnameProcessor that adds the machine's hostname to log records + * Added a `$dateFormat` option to the PsrLogMessageProcessor which lets you format DateTime instances nicely + * Added support for the PHP 7.x `mongodb` extension in the MongoDBHandler + * Fixed many minor issues in various handlers, and probably added a few regressions too + +### 1.26.1 (2021-05-28) + + * Fixed PHP 8.1 deprecation warning + +### 1.26.0 (2020-12-14) + + * Added $dateFormat and $removeUsedContextFields arguments to PsrLogMessageProcessor (backport from 2.x) + +### 1.25.5 (2020-07-23) + + * Fixed array access on null in RavenHandler + * Fixed unique_id in WebProcessor not being disableable + +### 1.25.4 (2020-05-22) + + * Fixed GitProcessor type error when there is no git repo present + * Fixed normalization of SoapFault objects containing deeply nested objects as "detail" + * Fixed support for relative paths in RotatingFileHandler + +### 1.25.3 (2019-12-20) + + * Fixed formatting of resources in JsonFormatter + * Fixed RedisHandler failing to use MULTI properly when passed a proxied Redis instance (e.g. in Symfony with lazy services) + * Fixed FilterHandler triggering a notice when handleBatch was filtering all records passed to it + * Fixed Turkish locale messing up the conversion of level names to their constant values + +### 1.25.2 (2019-11-13) + + * Fixed normalization of Traversables to avoid traversing them as not all of them are rewindable + * Fixed setFormatter/getFormatter to forward to the nested handler in FilterHandler, FingersCrossedHandler, BufferHandler and SamplingHandler + * Fixed BrowserConsoleHandler formatting when using multiple styles + * Fixed normalization of exception codes to be always integers even for PDOException which have them as numeric strings + * Fixed normalization of SoapFault objects containing non-strings as "detail" + * Fixed json encoding across all handlers to always attempt recovery of non-UTF-8 strings instead of failing the whole encoding + +### 1.25.1 (2019-09-06) + + * Fixed forward-compatible interfaces to be compatible with Monolog 1.x too. + +### 1.25.0 (2019-09-06) + + * Deprecated SlackbotHandler, use SlackWebhookHandler or SlackHandler instead + * Deprecated RavenHandler, use sentry/sentry 2.x and their Sentry\Monolog\Handler instead + * Deprecated HipChatHandler, migrate to Slack and use SlackWebhookHandler or SlackHandler instead + * Added forward-compatible interfaces and traits FormattableHandlerInterface, FormattableHandlerTrait, ProcessableHandlerInterface, ProcessableHandlerTrait. If you use modern PHP and want to make code compatible with Monolog 1 and 2 this can help. You will have to require at least Monolog 1.25 though. + * Added support for RFC3164 (outdated BSD syslog protocol) to SyslogUdpHandler + * Fixed issue in GroupHandler and WhatFailureGroupHandler where setting multiple processors would duplicate records + * Fixed issue in SignalHandler restarting syscalls functionality + * Fixed normalizers handling of exception backtraces to avoid serializing arguments in some cases + * Fixed ZendMonitorHandler to work with the latest Zend Server versions + * Fixed ChromePHPHandler to avoid sending more data than latest Chrome versions allow in headers (4KB down from 256KB). + +### 1.24.0 (2018-11-05) + + * BC Notice: If you are extending any of the Monolog's Formatters' `normalize` method, make sure you add the new `$depth = 0` argument to your function signature to avoid strict PHP warnings. + * Added a `ResettableInterface` in order to reset/reset/clear/flush handlers and processors + * Added a `ProcessorInterface` as an optional way to label a class as being a processor (mostly useful for autowiring dependency containers) + * Added a way to log signals being received using Monolog\SignalHandler + * Added ability to customize error handling at the Logger level using Logger::setExceptionHandler + * Added InsightOpsHandler to migrate users of the LogEntriesHandler + * Added protection to NormalizerFormatter against circular and very deep structures, it now stops normalizing at a depth of 9 + * Added capture of stack traces to ErrorHandler when logging PHP errors + * Added RavenHandler support for a `contexts` context or extra key to forward that to Sentry's contexts + * Added forwarding of context info to FluentdFormatter + * Added SocketHandler::setChunkSize to override the default chunk size in case you must send large log lines to rsyslog for example + * Added ability to extend/override BrowserConsoleHandler + * Added SlackWebhookHandler::getWebhookUrl and SlackHandler::getToken to enable class extensibility + * Added SwiftMailerHandler::getSubjectFormatter to enable class extensibility + * Dropped official support for HHVM in test builds + * Fixed normalization of exception traces when call_user_func is used to avoid serializing objects and the data they contain + * Fixed naming of fields in Slack handler, all field names are now capitalized in all cases + * Fixed HipChatHandler bug where slack dropped messages randomly + * Fixed normalization of objects in Slack handlers + * Fixed support for PHP7's Throwable in NewRelicHandler + * Fixed race bug when StreamHandler sometimes incorrectly reported it failed to create a directory + * Fixed table row styling issues in HtmlFormatter + * Fixed RavenHandler dropping the message when logging exception + * Fixed WhatFailureGroupHandler skipping processors when using handleBatch + and implement it where possible + * Fixed display of anonymous class names + +### 1.23.0 (2017-06-19) + + * Improved SyslogUdpHandler's support for RFC5424 and added optional `$ident` argument + * Fixed GelfHandler truncation to be per field and not per message + * Fixed compatibility issue with PHP <5.3.6 + * Fixed support for headless Chrome in ChromePHPHandler + * Fixed support for latest Aws SDK in DynamoDbHandler + * Fixed support for SwiftMailer 6.0+ in SwiftMailerHandler + +### 1.22.1 (2017-03-13) + + * Fixed lots of minor issues in the new Slack integrations + * Fixed support for allowInlineLineBreaks in LineFormatter when formatting exception backtraces + +### 1.22.0 (2016-11-26) + + * Added SlackbotHandler and SlackWebhookHandler to set up Slack integration more easily + * Added MercurialProcessor to add mercurial revision and branch names to log records + * Added support for AWS SDK v3 in DynamoDbHandler + * Fixed fatal errors occurring when normalizing generators that have been fully consumed + * Fixed RollbarHandler to include a level (rollbar level), monolog_level (original name), channel and datetime (unix) + * Fixed RollbarHandler not flushing records automatically, calling close() explicitly is not necessary anymore + * Fixed SyslogUdpHandler to avoid sending empty frames + * Fixed a few PHP 7.0 and 7.1 compatibility issues + +### 1.21.0 (2016-07-29) + + * Break: Reverted the addition of $context when the ErrorHandler handles regular php errors from 1.20.0 as it was causing issues + * Added support for more formats in RotatingFileHandler::setFilenameFormat as long as they have Y, m and d in order + * Added ability to format the main line of text the SlackHandler sends by explicitly setting a formatter on the handler + * Added information about SoapFault instances in NormalizerFormatter + * Added $handleOnlyReportedErrors option on ErrorHandler::registerErrorHandler (default true) to allow logging of all errors no matter the error_reporting level + +### 1.20.0 (2016-07-02) + + * Added FingersCrossedHandler::activate() to manually trigger the handler regardless of the activation policy + * Added StreamHandler::getUrl to retrieve the stream's URL + * Added ability to override addRow/addTitle in HtmlFormatter + * Added the $context to context information when the ErrorHandler handles a regular php error + * Deprecated RotatingFileHandler::setFilenameFormat to only support 3 formats: Y, Y-m and Y-m-d + * Fixed WhatFailureGroupHandler to work with PHP7 throwables + * Fixed a few minor bugs + +### 1.19.0 (2016-04-12) + + * Break: StreamHandler will not close streams automatically that it does not own. If you pass in a stream (not a path/url), then it will not close it for you. You can retrieve those using getStream() if needed + * Added DeduplicationHandler to remove duplicate records from notifications across multiple requests, useful for email or other notifications on errors + * Added ability to use `%message%` and other LineFormatter replacements in the subject line of emails sent with NativeMailHandler and SwiftMailerHandler + * Fixed HipChatHandler handling of long messages + +### 1.18.2 (2016-04-02) + + * Fixed ElasticaFormatter to use more precise dates + * Fixed GelfMessageFormatter sending too long messages + +### 1.18.1 (2016-03-13) + + * Fixed SlackHandler bug where slack dropped messages randomly + * Fixed RedisHandler issue when using with the PHPRedis extension + * Fixed AmqpHandler content-type being incorrectly set when using with the AMQP extension + * Fixed BrowserConsoleHandler regression + +### 1.18.0 (2016-03-01) + + * Added optional reduction of timestamp precision via `Logger->useMicrosecondTimestamps(false)`, disabling it gets you a bit of performance boost but reduces the precision to the second instead of microsecond + * Added possibility to skip some extra stack frames in IntrospectionProcessor if you have some library wrapping Monolog that is always adding frames + * Added `Logger->withName` to clone a logger (keeping all handlers) with a new name + * Added FluentdFormatter for the Fluentd unix socket protocol + * Added HandlerWrapper base class to ease the creation of handler wrappers, just extend it and override as needed + * Added support for replacing context sub-keys using `%context.*%` in LineFormatter + * Added support for `payload` context value in RollbarHandler + * Added setRelease to RavenHandler to describe the application version, sent with every log + * Added support for `fingerprint` context value in RavenHandler + * Fixed JSON encoding errors that would gobble up the whole log record, we now handle those more gracefully by dropping chars as needed + * Fixed write timeouts in SocketHandler and derivatives, set to 10sec by default, lower it with `setWritingTimeout()` + * Fixed PHP7 compatibility with regard to Exception/Throwable handling in a few places + +### 1.17.2 (2015-10-14) + + * Fixed ErrorHandler compatibility with non-Monolog PSR-3 loggers + * Fixed SlackHandler handling to use slack functionalities better + * Fixed SwiftMailerHandler bug when sending multiple emails they all had the same id + * Fixed 5.3 compatibility regression + +### 1.17.1 (2015-08-31) + + * Fixed RollbarHandler triggering PHP notices + +### 1.17.0 (2015-08-30) + + * Added support for `checksum` and `release` context/extra values in RavenHandler + * Added better support for exceptions in RollbarHandler + * Added UidProcessor::getUid + * Added support for showing the resource type in NormalizedFormatter + * Fixed IntrospectionProcessor triggering PHP notices + +### 1.16.0 (2015-08-09) + + * Added IFTTTHandler to notify ifttt.com triggers + * Added Logger::setHandlers() to allow setting/replacing all handlers + * Added $capSize in RedisHandler to cap the log size + * Fixed StreamHandler creation of directory to only trigger when the first log write happens + * Fixed bug in the handling of curl failures + * Fixed duplicate logging of fatal errors when both error and fatal error handlers are registered in monolog's ErrorHandler + * Fixed missing fatal errors records with handlers that need to be closed to flush log records + * Fixed TagProcessor::addTags support for associative arrays + +### 1.15.0 (2015-07-12) + + * Added addTags and setTags methods to change a TagProcessor + * Added automatic creation of directories if they are missing for a StreamHandler to open a log file + * Added retry functionality to Loggly, Cube and Mandrill handlers so they retry up to 5 times in case of network failure + * Fixed process exit code being incorrectly reset to 0 if ErrorHandler::registerExceptionHandler was used + * Fixed HTML/JS escaping in BrowserConsoleHandler + * Fixed JSON encoding errors being silently suppressed (PHP 5.5+ only) + +### 1.14.0 (2015-06-19) + + * Added PHPConsoleHandler to send record to Chrome's PHP Console extension and library + * Added support for objects implementing __toString in the NormalizerFormatter + * Added support for HipChat's v2 API in HipChatHandler + * Added Logger::setTimezone() to initialize the timezone monolog should use in case date.timezone isn't correct for your app + * Added an option to send formatted message instead of the raw record on PushoverHandler via ->useFormattedMessage(true) + * Fixed curl errors being silently suppressed + +### 1.13.1 (2015-03-09) + + * Fixed regression in HipChat requiring a new token to be created + +### 1.13.0 (2015-03-05) + + * Added Registry::hasLogger to check for the presence of a logger instance + * Added context.user support to RavenHandler + * Added HipChat API v2 support in the HipChatHandler + * Added NativeMailerHandler::addParameter to pass params to the mail() process + * Added context data to SlackHandler when $includeContextAndExtra is true + * Added ability to customize the Swift_Message per-email in SwiftMailerHandler + * Fixed SwiftMailerHandler to lazily create message instances if a callback is provided + * Fixed serialization of INF and NaN values in Normalizer and LineFormatter + +### 1.12.0 (2014-12-29) + + * Break: HandlerInterface::isHandling now receives a partial record containing only a level key. This was always the intent and does not break any Monolog handler but is strictly speaking a BC break and you should check if you relied on any other field in your own handlers. + * Added PsrHandler to forward records to another PSR-3 logger + * Added SamplingHandler to wrap around a handler and include only every Nth record + * Added MongoDBFormatter to support better storage with MongoDBHandler (it must be enabled manually for now) + * Added exception codes in the output of most formatters + * Added LineFormatter::includeStacktraces to enable exception stack traces in logs (uses more than one line) + * Added $useShortAttachment to SlackHandler to minify attachment size and $includeExtra to append extra data + * Added $host to HipChatHandler for users of private instances + * Added $transactionName to NewRelicHandler and support for a transaction_name context value + * Fixed MandrillHandler to avoid outputting API call responses + * Fixed some non-standard behaviors in SyslogUdpHandler + +### 1.11.0 (2014-09-30) + + * Break: The NewRelicHandler extra and context data are now prefixed with extra_ and context_ to avoid clashes. Watch out if you have scripts reading those from the API and rely on names + * Added WhatFailureGroupHandler to suppress any exception coming from the wrapped handlers and avoid chain failures if a logging service fails + * Added MandrillHandler to send emails via the Mandrillapp.com API + * Added SlackHandler to log records to a Slack.com account + * Added FleepHookHandler to log records to a Fleep.io account + * Added LogglyHandler::addTag to allow adding tags to an existing handler + * Added $ignoreEmptyContextAndExtra to LineFormatter to avoid empty [] at the end + * Added $useLocking to StreamHandler and RotatingFileHandler to enable flock() while writing + * Added support for PhpAmqpLib in the AmqpHandler + * Added FingersCrossedHandler::clear and BufferHandler::clear to reset them between batches in long running jobs + * Added support for adding extra fields from $_SERVER in the WebProcessor + * Fixed support for non-string values in PrsLogMessageProcessor + * Fixed SwiftMailer messages being sent with the wrong date in long running scripts + * Fixed minor PHP 5.6 compatibility issues + * Fixed BufferHandler::close being called twice + +### 1.10.0 (2014-06-04) + + * Added Logger::getHandlers() and Logger::getProcessors() methods + * Added $passthruLevel argument to FingersCrossedHandler to let it always pass some records through even if the trigger level is not reached + * Added support for extra data in NewRelicHandler + * Added $expandNewlines flag to the ErrorLogHandler to create multiple log entries when a message has multiple lines + +### 1.9.1 (2014-04-24) + + * Fixed regression in RotatingFileHandler file permissions + * Fixed initialization of the BufferHandler to make sure it gets flushed after receiving records + * Fixed ChromePHPHandler and FirePHPHandler's activation strategies to be more conservative + +### 1.9.0 (2014-04-20) + + * Added LogEntriesHandler to send logs to a LogEntries account + * Added $filePermissions to tweak file mode on StreamHandler and RotatingFileHandler + * Added $useFormatting flag to MemoryProcessor to make it send raw data in bytes + * Added support for table formatting in FirePHPHandler via the table context key + * Added a TagProcessor to add tags to records, and support for tags in RavenHandler + * Added $appendNewline flag to the JsonFormatter to enable using it when logging to files + * Added sound support to the PushoverHandler + * Fixed multi-threading support in StreamHandler + * Fixed empty headers issue when ChromePHPHandler received no records + * Fixed default format of the ErrorLogHandler + +### 1.8.0 (2014-03-23) + + * Break: the LineFormatter now strips newlines by default because this was a bug, set $allowInlineLineBreaks to true if you need them + * Added BrowserConsoleHandler to send logs to any browser's console via console.log() injection in the output + * Added FilterHandler to filter records and only allow those of a given list of levels through to the wrapped handler + * Added FlowdockHandler to send logs to a Flowdock account + * Added RollbarHandler to send logs to a Rollbar account + * Added HtmlFormatter to send prettier log emails with colors for each log level + * Added GitProcessor to add the current branch/commit to extra record data + * Added a Monolog\Registry class to allow easier global access to pre-configured loggers + * Added support for the new official graylog2/gelf-php lib for GelfHandler, upgrade if you can by replacing the mlehner/gelf-php requirement + * Added support for HHVM + * Added support for Loggly batch uploads + * Added support for tweaking the content type and encoding in NativeMailerHandler + * Added $skipClassesPartials to tweak the ignored classes in the IntrospectionProcessor + * Fixed batch request support in GelfHandler + +### 1.7.0 (2013-11-14) + + * Added ElasticSearchHandler to send logs to an Elastic Search server + * Added DynamoDbHandler and ScalarFormatter to send logs to Amazon's Dynamo DB + * Added SyslogUdpHandler to send logs to a remote syslogd server + * Added LogglyHandler to send logs to a Loggly account + * Added $level to IntrospectionProcessor so it only adds backtraces when needed + * Added $version to LogstashFormatter to allow using the new v1 Logstash format + * Added $appName to NewRelicHandler + * Added configuration of Pushover notification retries/expiry + * Added $maxColumnWidth to NativeMailerHandler to change the 70 chars default + * Added chainability to most setters for all handlers + * Fixed RavenHandler batch processing so it takes the message from the record with highest priority + * Fixed HipChatHandler batch processing so it sends all messages at once + * Fixed issues with eAccelerator + * Fixed and improved many small things + +### 1.6.0 (2013-07-29) + + * Added HipChatHandler to send logs to a HipChat chat room + * Added ErrorLogHandler to send logs to PHP's error_log function + * Added NewRelicHandler to send logs to NewRelic's service + * Added Monolog\ErrorHandler helper class to register a Logger as exception/error/fatal handler + * Added ChannelLevelActivationStrategy for the FingersCrossedHandler to customize levels by channel + * Added stack traces output when normalizing exceptions (json output & co) + * Added Monolog\Logger::API constant (currently 1) + * Added support for ChromePHP's v4.0 extension + * Added support for message priorities in PushoverHandler, see $highPriorityLevel and $emergencyLevel + * Added support for sending messages to multiple users at once with the PushoverHandler + * Fixed RavenHandler's support for batch sending of messages (when behind a Buffer or FingersCrossedHandler) + * Fixed normalization of Traversables with very large data sets, only the first 1000 items are shown now + * Fixed issue in RotatingFileHandler when an open_basedir restriction is active + * Fixed minor issues in RavenHandler and bumped the API to Raven 0.5.0 + * Fixed SyslogHandler issue when many were used concurrently with different facilities + +### 1.5.0 (2013-04-23) + + * Added ProcessIdProcessor to inject the PID in log records + * Added UidProcessor to inject a unique identifier to all log records of one request/run + * Added support for previous exceptions in the LineFormatter exception serialization + * Added Monolog\Logger::getLevels() to get all available levels + * Fixed ChromePHPHandler so it avoids sending headers larger than Chrome can handle + +### 1.4.1 (2013-04-01) + + * Fixed exception formatting in the LineFormatter to be more minimalistic + * Fixed RavenHandler's handling of context/extra data, requires Raven client >0.1.0 + * Fixed log rotation in RotatingFileHandler to work with long running scripts spanning multiple days + * Fixed WebProcessor array access so it checks for data presence + * Fixed Buffer, Group and FingersCrossed handlers to make use of their processors + +### 1.4.0 (2013-02-13) + + * Added RedisHandler to log to Redis via the Predis library or the phpredis extension + * Added ZendMonitorHandler to log to the Zend Server monitor + * Added the possibility to pass arrays of handlers and processors directly in the Logger constructor + * Added `$useSSL` option to the PushoverHandler which is enabled by default + * Fixed ChromePHPHandler and FirePHPHandler issue when multiple instances are used simultaneously + * Fixed header injection capability in the NativeMailHandler + +### 1.3.1 (2013-01-11) + + * Fixed LogstashFormatter to be usable with stream handlers + * Fixed GelfMessageFormatter levels on Windows + +### 1.3.0 (2013-01-08) + + * Added PSR-3 compliance, the `Monolog\Logger` class is now an instance of `Psr\Log\LoggerInterface` + * Added PsrLogMessageProcessor that you can selectively enable for full PSR-3 compliance + * Added LogstashFormatter (combine with SocketHandler or StreamHandler to send logs to Logstash) + * Added PushoverHandler to send mobile notifications + * Added CouchDBHandler and DoctrineCouchDBHandler + * Added RavenHandler to send data to Sentry servers + * Added support for the new MongoClient class in MongoDBHandler + * Added microsecond precision to log records' timestamps + * Added `$flushOnOverflow` param to BufferHandler to flush by batches instead of losing + the oldest entries + * Fixed normalization of objects with cyclic references + +### 1.2.1 (2012-08-29) + + * Added new $logopts arg to SyslogHandler to provide custom openlog options + * Fixed fatal error in SyslogHandler + +### 1.2.0 (2012-08-18) + + * Added AmqpHandler (for use with AMQP servers) + * Added CubeHandler + * Added NativeMailerHandler::addHeader() to send custom headers in mails + * Added the possibility to specify more than one recipient in NativeMailerHandler + * Added the possibility to specify float timeouts in SocketHandler + * Added NOTICE and EMERGENCY levels to conform with RFC 5424 + * Fixed the log records to use the php default timezone instead of UTC + * Fixed BufferHandler not being flushed properly on PHP fatal errors + * Fixed normalization of exotic resource types + * Fixed the default format of the SyslogHandler to avoid duplicating datetimes in syslog + +### 1.1.0 (2012-04-23) + + * Added Monolog\Logger::isHandling() to check if a handler will + handle the given log level + * Added ChromePHPHandler + * Added MongoDBHandler + * Added GelfHandler (for use with Graylog2 servers) + * Added SocketHandler (for use with syslog-ng for example) + * Added NormalizerFormatter + * Added the possibility to change the activation strategy of the FingersCrossedHandler + * Added possibility to show microseconds in logs + * Added `server` and `referer` to WebProcessor output + +### 1.0.2 (2011-10-24) + + * Fixed bug in IE with large response headers and FirePHPHandler + +### 1.0.1 (2011-08-25) + + * Added MemoryPeakUsageProcessor and MemoryUsageProcessor + * Added Monolog\Logger::getName() to get a logger's channel name + +### 1.0.0 (2011-07-06) + + * Added IntrospectionProcessor to get info from where the logger was called + * Fixed WebProcessor in CLI + +### 1.0.0-RC1 (2011-07-01) + + * Initial release diff --git a/php/libraries/composer/vendor/monolog/monolog/LICENSE b/php/libraries/composer/vendor/monolog/monolog/LICENSE new file mode 100644 index 0000000..aa2a042 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2020 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/php/libraries/composer/vendor/monolog/monolog/README.md b/php/libraries/composer/vendor/monolog/monolog/README.md new file mode 100644 index 0000000..bfcae0c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/README.md @@ -0,0 +1,112 @@ +# Monolog - Logging for PHP [![Continuous Integration](https://github.com/Seldaek/monolog/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/Seldaek/monolog/actions) + +[![Total Downloads](https://img.shields.io/packagist/dt/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) +[![Latest Stable Version](https://img.shields.io/packagist/v/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) + + +Monolog sends your logs to files, sockets, inboxes, databases and various +web services. See the complete list of handlers below. Special handlers +allow you to build advanced logging strategies. + +This library implements the [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +interface that you can type-hint against in your own libraries to keep +a maximum of interoperability. You can also use it in your applications to +make sure you can always use another compatible logger at a later time. +As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels. +Internally Monolog still uses its own level scheme since it predates PSR-3. + +## Installation + +Install the latest version with + +```bash +$ composer require monolog/monolog +``` + +## Basic Usage + +```php +<?php + +use Monolog\Logger; +use Monolog\Handler\StreamHandler; + +// create a log channel +$log = new Logger('name'); +$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); + +// add records to the log +$log->warning('Foo'); +$log->error('Bar'); +``` + +## Documentation + +- [Usage Instructions](doc/01-usage.md) +- [Handlers, Formatters and Processors](doc/02-handlers-formatters-processors.md) +- [Utility Classes](doc/03-utilities.md) +- [Extending Monolog](doc/04-extending.md) +- [Log Record Structure](doc/message-structure.md) + +## Support Monolog Financially + +Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek). + +Tidelift delivers commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. + +## Third Party Packages + +Third party handlers, formatters and processors are +[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You +can also add your own there if you publish one. + +## About + +### Requirements + +- Monolog `^2.0` works with PHP 7.2 or above, use Monolog `^1.25` for PHP 5.3+ support. + +### Support + +Monolog 1.x support is somewhat limited at this point and only important fixes will be done. You should migrate to Monolog 2 where possible to benefit from all the latest features and fixes. + +### Submitting bugs and feature requests + +Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/monolog/issues) + +### Framework Integrations + +- Frameworks and libraries using [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) + can be used very easily with Monolog since it implements the interface. +- [Symfony](http://symfony.com) comes out of the box with Monolog. +- [Laravel](http://laravel.com/) comes out of the box with Monolog. +- [Lumen](http://lumen.laravel.com/) comes out of the box with Monolog. +- [PPI](https://github.com/ppi/framework) comes out of the box with Monolog. +- [CakePHP](http://cakephp.org/) is usable with Monolog via the [cakephp-monolog](https://github.com/jadb/cakephp-monolog) plugin. +- [Slim](http://www.slimframework.com/) is usable with Monolog via the [Slim-Monolog](https://github.com/Flynsarmy/Slim-Monolog) log writer. +- [XOOPS 2.6](http://xoops.org/) comes out of the box with Monolog. +- [Aura.Web_Project](https://github.com/auraphp/Aura.Web_Project) comes out of the box with Monolog. +- [Nette Framework](http://nette.org/en/) is usable with Monolog via the [contributte/monolog](https://github.com/contributte/monolog) or [orisai/nette-monolog](https://github.com/orisai/nette-monolog) extensions. +- [Proton Micro Framework](https://github.com/alexbilbie/Proton) comes out of the box with Monolog. +- [FuelPHP](http://fuelphp.com/) comes out of the box with Monolog. +- [Equip Framework](https://github.com/equip/framework) comes out of the box with Monolog. +- [Yii 2](http://www.yiiframework.com/) is usable with Monolog via the [yii2-monolog](https://github.com/merorafael/yii2-monolog) or [yii2-psr-log-target](https://github.com/samdark/yii2-psr-log-target) plugins. +- [Hawkbit Micro Framework](https://github.com/HawkBitPhp/hawkbit) comes out of the box with Monolog. +- [SilverStripe 4](https://www.silverstripe.org/) comes out of the box with Monolog. +- [Drupal](https://www.drupal.org/) is usable with Monolog via the [monolog](https://www.drupal.org/project/monolog) module. +- [Aimeos ecommerce framework](https://aimeos.org/) is usable with Monolog via the [ai-monolog](https://github.com/aimeos/ai-monolog) extension. +- [Magento](https://magento.com/) comes out of the box with Monolog. + +### Author + +Jordi Boggiano - <j.boggiano@seld.be> - <http://twitter.com/seldaek><br /> +See also the list of [contributors](https://github.com/Seldaek/monolog/contributors) who participated in this project. + +### License + +Monolog is licensed under the MIT License - see the [LICENSE](LICENSE) file for details + +### Acknowledgements + +This library is heavily inspired by Python's [Logbook](https://logbook.readthedocs.io/en/stable/) +library, although most concepts have been adjusted to fit to the PHP world. diff --git a/php/libraries/composer/vendor/monolog/monolog/UPGRADE.md b/php/libraries/composer/vendor/monolog/monolog/UPGRADE.md new file mode 100644 index 0000000..84e15e6 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/UPGRADE.md @@ -0,0 +1,72 @@ +### 2.0.0 + +- `Monolog\Logger::API` can be used to distinguish between a Monolog `1` and `2` + install of Monolog when writing integration code. + +- Removed non-PSR-3 methods to add records, all the `add*` (e.g. `addWarning`) + methods as well as `emerg`, `crit`, `err` and `warn`. + +- DateTime are now formatted with a timezone and microseconds (unless disabled). + Various formatters and log output might be affected, which may mess with log parsing + in some cases. + +- The `datetime` in every record array is now a DateTimeImmutable, not that you + should have been modifying these anyway. + +- The timezone is now set per Logger instance and not statically, either + via ->setTimezone or passed in the constructor. Calls to Logger::setTimezone + should be converted. + +- `HandlerInterface` has been split off and two new interfaces now exist for + more granular controls: `ProcessableHandlerInterface` and + `FormattableHandlerInterface`. Handlers not extending `AbstractHandler` + should make sure to implement the relevant interfaces. + +- `HandlerInterface` now requires the `close` method to be implemented. This + only impacts you if you implement the interface yourself, but you can extend + the new `Monolog\Handler\Handler` base class too. + +- There is no more default handler configured on empty Logger instances, if + you were relying on that you will not get any output anymore, make sure to + configure the handler you need. + +#### LogglyFormatter + +- The records' `datetime` is not sent anymore. Only `timestamp` is sent to Loggly. + +#### AmqpHandler + +- Log levels are not shortened to 4 characters anymore. e.g. a warning record + will be sent using the `warning.channel` routing key instead of `warn.channel` + as in 1.x. +- The exchange name does not default to 'log' anymore, and it is completely ignored + now for the AMQP extension users. Only PHPAmqpLib uses it if provided. + +#### RotatingFileHandler + +- The file name format must now contain `{date}` and the date format must be set + to one of the predefined FILE_PER_* constants to avoid issues with file rotation. + See `setFilenameFormat`. + +#### LogstashFormatter + +- Removed Logstash V0 support +- Context/extra prefix has been removed in favor of letting users configure the exact key being sent +- Context/extra data are now sent as an object instead of single keys + +#### HipChatHandler + +- Removed deprecated HipChat handler, migrate to Slack and use SlackWebhookHandler or SlackHandler instead + +#### SlackbotHandler + +- Removed deprecated SlackbotHandler handler, use SlackWebhookHandler or SlackHandler instead + +#### RavenHandler + +- Removed deprecated RavenHandler handler, use sentry/sentry 2.x and their Sentry\Monolog\Handler instead + +#### ElasticSearchHandler + +- As support for the official Elasticsearch library was added, the former ElasticSearchHandler has been + renamed to ElasticaHandler and the new one added as ElasticsearchHandler. diff --git a/php/libraries/composer/vendor/monolog/monolog/composer.json b/php/libraries/composer/vendor/monolog/monolog/composer.json new file mode 100644 index 0000000..b9437d6 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/composer.json @@ -0,0 +1,81 @@ +{ + "name": "monolog/monolog", + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "keywords": ["log", "logging", "psr-3"], + "homepage": "https://github.com/Seldaek/monolog", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "require": { + "php": ">=7.2", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "ext-json": "*", + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "elasticsearch/elasticsearch": "^7 || ^8", + "graylog2/gelf-php": "^1.4.2 || ^2@dev", + "guzzlehttp/guzzle": "^7.4", + "guzzlehttp/psr7": "^2.2", + "mongodb/mongodb": "^1.8", + "php-amqplib/php-amqplib": "~2.4 || ^3", + "phpspec/prophecy": "^1.15", + "phpstan/phpstan": "^0.12.91", + "phpunit/phpunit": "^8.5.14", + "predis/predis": "^1.1 || ^2.0", + "rollbar/rollbar": "^1.3 || ^2 || ^3", + "ruflin/elastica": "^7", + "swiftmailer/swiftmailer": "^5.3|^6.0", + "symfony/mailer": "^5.4 || ^6", + "symfony/mime": "^5.4 || ^6" + }, + "suggest": { + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)", + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ext-mbstring": "Allow to work properly with unicode symbols", + "ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)", + "ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler", + "ext-openssl": "Required to send log messages using SSL" + }, + "autoload": { + "psr-4": {"Monolog\\": "src/Monolog"} + }, + "autoload-dev": { + "psr-4": {"Monolog\\": "tests/Monolog"} + }, + "provide": { + "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + }, + "extra": { + "branch-alias": { + "dev-main": "2.x-dev" + } + }, + "scripts": { + "test": "@php vendor/bin/phpunit", + "phpstan": "@php vendor/bin/phpstan analyse" + }, + "config": { + "lock": false, + "sort-packages": true, + "platform-check": false, + "allow-plugins": { + "composer/package-versions-deprecated": true + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php new file mode 100644 index 0000000..188bbb0 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php @@ -0,0 +1,46 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Attribute; + +/** + * A reusable attribute to help configure a class or a method as a processor. + * + * Using it offers no guarantee: it needs to be leveraged by a Monolog third-party consumer. + * + * Using it with the Monolog library only has no effect at all: processors should still be turned into a callable if + * needed and manually pushed to the loggers and to the processable handlers. + */ +#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +class AsMonologProcessor +{ + /** @var string|null */ + public $channel = null; + /** @var string|null */ + public $handler = null; + /** @var string|null */ + public $method = null; + + /** + * @param string|null $channel The logging channel the processor should be pushed to. + * @param string|null $handler The handler the processor should be pushed to. + * @param string|null $method The method that processes the records (if the attribute is used at the class level). + */ + public function __construct( + ?string $channel = null, + ?string $handler = null, + ?string $method = null + ) { + $this->channel = $channel; + $this->handler = $handler; + $this->method = $method; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php new file mode 100644 index 0000000..6a1ba9b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use DateTimeZone; + +/** + * Overrides default json encoding of date time objects + * + * @author Menno Holtkamp + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable +{ + /** + * @var bool + */ + private $useMicroseconds; + + public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null) + { + $this->useMicroseconds = $useMicroseconds; + + parent::__construct('now', $timezone); + } + + public function jsonSerialize(): string + { + if ($this->useMicroseconds) { + return $this->format('Y-m-d\TH:i:s.uP'); + } + + return $this->format('Y-m-d\TH:i:sP'); + } + + public function __toString(): string + { + return $this->jsonSerialize(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/ErrorHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/ErrorHandler.php new file mode 100644 index 0000000..1406d34 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/ErrorHandler.php @@ -0,0 +1,307 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; + +/** + * Monolog error handler + * + * A facility to enable logging of runtime errors, exceptions and fatal errors. + * + * Quick setup: <code>ErrorHandler::register($logger);</code> + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class ErrorHandler +{ + /** @var LoggerInterface */ + private $logger; + + /** @var ?callable */ + private $previousExceptionHandler = null; + /** @var array<class-string, LogLevel::*> an array of class name to LogLevel::* constant mapping */ + private $uncaughtExceptionLevelMap = []; + + /** @var callable|true|null */ + private $previousErrorHandler = null; + /** @var array<int, LogLevel::*> an array of E_* constant to LogLevel::* constant mapping */ + private $errorLevelMap = []; + /** @var bool */ + private $handleOnlyReportedErrors = true; + + /** @var bool */ + private $hasFatalErrorHandler = false; + /** @var LogLevel::* */ + private $fatalLevel = LogLevel::ALERT; + /** @var ?string */ + private $reservedMemory = null; + /** @var ?array{type: int, message: string, file: string, line: int, trace: mixed} */ + private $lastFatalData = null; + /** @var int[] */ + private static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** + * Registers a new ErrorHandler for a given Logger + * + * By default it will handle errors, exceptions and fatal errors + * + * @param LoggerInterface $logger + * @param array<int, LogLevel::*>|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling + * @param array<class-string, LogLevel::*>|false $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling + * @param LogLevel::*|null|false $fatalLevel a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling + * @return ErrorHandler + */ + public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self + { + /** @phpstan-ignore-next-line */ + $handler = new static($logger); + if ($errorLevelMap !== false) { + $handler->registerErrorHandler($errorLevelMap); + } + if ($exceptionLevelMap !== false) { + $handler->registerExceptionHandler($exceptionLevelMap); + } + if ($fatalLevel !== false) { + $handler->registerFatalHandler($fatalLevel); + } + + return $handler; + } + + /** + * @param array<class-string, LogLevel::*> $levelMap an array of class name to LogLevel::* constant mapping + * @return $this + */ + public function registerExceptionHandler(array $levelMap = [], bool $callPrevious = true): self + { + $prev = set_exception_handler(function (\Throwable $e): void { + $this->handleException($e); + }); + $this->uncaughtExceptionLevelMap = $levelMap; + foreach ($this->defaultExceptionLevelMap() as $class => $level) { + if (!isset($this->uncaughtExceptionLevelMap[$class])) { + $this->uncaughtExceptionLevelMap[$class] = $level; + } + } + if ($callPrevious && $prev) { + $this->previousExceptionHandler = $prev; + } + + return $this; + } + + /** + * @param array<int, LogLevel::*> $levelMap an array of E_* constant to LogLevel::* constant mapping + * @return $this + */ + public function registerErrorHandler(array $levelMap = [], bool $callPrevious = true, int $errorTypes = -1, bool $handleOnlyReportedErrors = true): self + { + $prev = set_error_handler([$this, 'handleError'], $errorTypes); + $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap); + if ($callPrevious) { + $this->previousErrorHandler = $prev ?: true; + } else { + $this->previousErrorHandler = null; + } + + $this->handleOnlyReportedErrors = $handleOnlyReportedErrors; + + return $this; + } + + /** + * @param LogLevel::*|null $level a LogLevel::* constant, null to use the default LogLevel::ALERT + * @param int $reservedMemorySize Amount of KBs to reserve in memory so that it can be freed when handling fatal errors giving Monolog some room in memory to get its job done + */ + public function registerFatalHandler($level = null, int $reservedMemorySize = 20): self + { + register_shutdown_function([$this, 'handleFatalError']); + + $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); + $this->fatalLevel = null === $level ? LogLevel::ALERT : $level; + $this->hasFatalErrorHandler = true; + + return $this; + } + + /** + * @return array<class-string, LogLevel::*> + */ + protected function defaultExceptionLevelMap(): array + { + return [ + 'ParseError' => LogLevel::CRITICAL, + 'Throwable' => LogLevel::ERROR, + ]; + } + + /** + * @return array<int, LogLevel::*> + */ + protected function defaultErrorLevelMap(): array + { + return [ + E_ERROR => LogLevel::CRITICAL, + E_WARNING => LogLevel::WARNING, + E_PARSE => LogLevel::ALERT, + E_NOTICE => LogLevel::NOTICE, + E_CORE_ERROR => LogLevel::CRITICAL, + E_CORE_WARNING => LogLevel::WARNING, + E_COMPILE_ERROR => LogLevel::ALERT, + E_COMPILE_WARNING => LogLevel::WARNING, + E_USER_ERROR => LogLevel::ERROR, + E_USER_WARNING => LogLevel::WARNING, + E_USER_NOTICE => LogLevel::NOTICE, + E_STRICT => LogLevel::NOTICE, + E_RECOVERABLE_ERROR => LogLevel::ERROR, + E_DEPRECATED => LogLevel::NOTICE, + E_USER_DEPRECATED => LogLevel::NOTICE, + ]; + } + + /** + * @phpstan-return never + */ + private function handleException(\Throwable $e): void + { + $level = LogLevel::ERROR; + foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) { + if ($e instanceof $class) { + $level = $candidate; + break; + } + } + + $this->logger->log( + $level, + sprintf('Uncaught Exception %s: "%s" at %s line %s', Utils::getClass($e), $e->getMessage(), $e->getFile(), $e->getLine()), + ['exception' => $e] + ); + + if ($this->previousExceptionHandler) { + ($this->previousExceptionHandler)($e); + } + + if (!headers_sent() && in_array(strtolower((string) ini_get('display_errors')), ['0', '', 'false', 'off', 'none', 'no'], true)) { + http_response_code(500); + } + + exit(255); + } + + /** + * @private + * + * @param mixed[] $context + */ + public function handleError(int $code, string $message, string $file = '', int $line = 0, ?array $context = []): bool + { + if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) { + return false; + } + + // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries + if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) { + $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL; + $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]); + } else { + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + array_shift($trace); // Exclude handleError from trace + $this->lastFatalData = ['type' => $code, 'message' => $message, 'file' => $file, 'line' => $line, 'trace' => $trace]; + } + + if ($this->previousErrorHandler === true) { + return false; + } elseif ($this->previousErrorHandler) { + return (bool) ($this->previousErrorHandler)($code, $message, $file, $line, $context); + } + + return true; + } + + /** + * @private + */ + public function handleFatalError(): void + { + $this->reservedMemory = ''; + + if (is_array($this->lastFatalData)) { + $lastError = $this->lastFatalData; + } else { + $lastError = error_get_last(); + } + + if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) { + $trace = $lastError['trace'] ?? null; + $this->logger->log( + $this->fatalLevel, + 'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'], + ['code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'trace' => $trace] + ); + + if ($this->logger instanceof Logger) { + foreach ($this->logger->getHandlers() as $handler) { + $handler->close(); + } + } + } + } + + /** + * @param int $code + */ + private static function codeToString($code): string + { + switch ($code) { + case E_ERROR: + return 'E_ERROR'; + case E_WARNING: + return 'E_WARNING'; + case E_PARSE: + return 'E_PARSE'; + case E_NOTICE: + return 'E_NOTICE'; + case E_CORE_ERROR: + return 'E_CORE_ERROR'; + case E_CORE_WARNING: + return 'E_CORE_WARNING'; + case E_COMPILE_ERROR: + return 'E_COMPILE_ERROR'; + case E_COMPILE_WARNING: + return 'E_COMPILE_WARNING'; + case E_USER_ERROR: + return 'E_USER_ERROR'; + case E_USER_WARNING: + return 'E_USER_WARNING'; + case E_USER_NOTICE: + return 'E_USER_NOTICE'; + case E_STRICT: + return 'E_STRICT'; + case E_RECOVERABLE_ERROR: + return 'E_RECOVERABLE_ERROR'; + case E_DEPRECATED: + return 'E_DEPRECATED'; + case E_USER_DEPRECATED: + return 'E_USER_DEPRECATED'; + } + + return 'Unknown PHP error'; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php new file mode 100644 index 0000000..aa1884b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php @@ -0,0 +1,83 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +/** + * Formats a log message according to the ChromePHP array format + * + * @author Christophe Coevoet <stof@notk.org> + */ +class ChromePHPFormatter implements FormatterInterface +{ + /** + * Translates Monolog log levels to Wildfire levels. + * + * @var array<int, 'log'|'info'|'warn'|'error'> + */ + private $logLevels = [ + Logger::DEBUG => 'log', + Logger::INFO => 'info', + Logger::NOTICE => 'info', + Logger::WARNING => 'warn', + Logger::ERROR => 'error', + Logger::CRITICAL => 'error', + Logger::ALERT => 'error', + Logger::EMERGENCY => 'error', + ]; + + /** + * {@inheritDoc} + */ + public function format(array $record) + { + // Retrieve the line and file if set and remove them from the formatted extra + $backtrace = 'unknown'; + if (isset($record['extra']['file'], $record['extra']['line'])) { + $backtrace = $record['extra']['file'].' : '.$record['extra']['line']; + unset($record['extra']['file'], $record['extra']['line']); + } + + $message = ['message' => $record['message']]; + if ($record['context']) { + $message['context'] = $record['context']; + } + if ($record['extra']) { + $message['extra'] = $record['extra']; + } + if (count($message) === 1) { + $message = reset($message); + } + + return [ + $record['channel'], + $message, + $backtrace, + $this->logLevels[$record['level']], + ]; + } + + /** + * {@inheritDoc} + */ + public function formatBatch(array $records) + { + $formatted = []; + + foreach ($records as $record) { + $formatted[] = $this->format($record); + } + + return $formatted; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php new file mode 100644 index 0000000..6c8a9ab --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php @@ -0,0 +1,89 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Elastica\Document; + +/** + * Format a log message into an Elastica Document + * + * @author Jelle Vink <jelle.vink@gmail.com> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class ElasticaFormatter extends NormalizerFormatter +{ + /** + * @var string Elastic search index name + */ + protected $index; + + /** + * @var ?string Elastic search document type + */ + protected $type; + + /** + * @param string $index Elastic Search index name + * @param ?string $type Elastic Search document type, deprecated as of Elastica 7 + */ + public function __construct(string $index, ?string $type) + { + // elasticsearch requires a ISO 8601 format date with optional millisecond precision. + parent::__construct('Y-m-d\TH:i:s.uP'); + + $this->index = $index; + $this->type = $type; + } + + /** + * {@inheritDoc} + */ + public function format(array $record) + { + $record = parent::format($record); + + return $this->getDocument($record); + } + + public function getIndex(): string + { + return $this->index; + } + + /** + * @deprecated since Elastica 7 type has no effect + */ + public function getType(): string + { + /** @phpstan-ignore-next-line */ + return $this->type; + } + + /** + * Convert a log message into an Elastica Document + * + * @phpstan-param Record $record + */ + protected function getDocument(array $record): Document + { + $document = new Document(); + $document->setData($record); + if (method_exists($document, 'setType')) { + /** @phpstan-ignore-next-line */ + $document->setType($this->type); + } + $document->setIndex($this->index); + + return $document; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php new file mode 100644 index 0000000..b792b81 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php @@ -0,0 +1,89 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use DateTimeInterface; + +/** + * Format a log message into an Elasticsearch record + * + * @author Avtandil Kikabidze <akalongman@gmail.com> + */ +class ElasticsearchFormatter extends NormalizerFormatter +{ + /** + * @var string Elasticsearch index name + */ + protected $index; + + /** + * @var string Elasticsearch record type + */ + protected $type; + + /** + * @param string $index Elasticsearch index name + * @param string $type Elasticsearch record type + */ + public function __construct(string $index, string $type) + { + // Elasticsearch requires an ISO 8601 format date with optional millisecond precision. + parent::__construct(DateTimeInterface::ISO8601); + + $this->index = $index; + $this->type = $type; + } + + /** + * {@inheritDoc} + */ + public function format(array $record) + { + $record = parent::format($record); + + return $this->getDocument($record); + } + + /** + * Getter index + * + * @return string + */ + public function getIndex(): string + { + return $this->index; + } + + /** + * Getter type + * + * @return string + */ + public function getType(): string + { + return $this->type; + } + + /** + * Convert a log message into an Elasticsearch record + * + * @param mixed[] $record Log message + * @return mixed[] + */ + protected function getDocument(array $record): array + { + $record['_index'] = $this->index; + $record['_type'] = $this->type; + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php new file mode 100644 index 0000000..867ae58 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php @@ -0,0 +1,112 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * formats the record to be used in the FlowdockHandler + * + * @author Dominik Liebler <liebler.dominik@gmail.com> + * @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4 + */ +class FlowdockFormatter implements FormatterInterface +{ + /** + * @var string + */ + private $source; + + /** + * @var string + */ + private $sourceEmail; + + public function __construct(string $source, string $sourceEmail) + { + $this->source = $source; + $this->sourceEmail = $sourceEmail; + } + + /** + * {@inheritDoc} + * + * @return mixed[] + */ + public function format(array $record): array + { + $tags = [ + '#logs', + '#' . strtolower($record['level_name']), + '#' . $record['channel'], + ]; + + foreach ($record['extra'] as $value) { + $tags[] = '#' . $value; + } + + $subject = sprintf( + 'in %s: %s - %s', + $this->source, + $record['level_name'], + $this->getShortMessage($record['message']) + ); + + $record['flowdock'] = [ + 'source' => $this->source, + 'from_address' => $this->sourceEmail, + 'subject' => $subject, + 'content' => $record['message'], + 'tags' => $tags, + 'project' => $this->source, + ]; + + return $record; + } + + /** + * {@inheritDoc} + * + * @return mixed[][] + */ + public function formatBatch(array $records): array + { + $formatted = []; + + foreach ($records as $record) { + $formatted[] = $this->format($record); + } + + return $formatted; + } + + public function getShortMessage(string $message): string + { + static $hasMbString; + + if (null === $hasMbString) { + $hasMbString = function_exists('mb_strlen'); + } + + $maxLength = 45; + + if ($hasMbString) { + if (mb_strlen($message, 'UTF-8') > $maxLength) { + $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...'; + } + } else { + if (strlen($message) > $maxLength) { + $message = substr($message, 0, $maxLength - 4) . ' ...'; + } + } + + return $message; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php new file mode 100644 index 0000000..29b14d3 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php @@ -0,0 +1,88 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Utils; + +/** + * Class FluentdFormatter + * + * Serializes a log message to Fluentd unix socket protocol + * + * Fluentd config: + * + * <source> + * type unix + * path /var/run/td-agent/td-agent.sock + * </source> + * + * Monolog setup: + * + * $logger = new Monolog\Logger('fluent.tag'); + * $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock'); + * $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter()); + * $logger->pushHandler($fluentHandler); + * + * @author Andrius Putna <fordnox@gmail.com> + */ +class FluentdFormatter implements FormatterInterface +{ + /** + * @var bool $levelTag should message level be a part of the fluentd tag + */ + protected $levelTag = false; + + public function __construct(bool $levelTag = false) + { + if (!function_exists('json_encode')) { + throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter'); + } + + $this->levelTag = $levelTag; + } + + public function isUsingLevelsInTag(): bool + { + return $this->levelTag; + } + + public function format(array $record): string + { + $tag = $record['channel']; + if ($this->levelTag) { + $tag .= '.' . strtolower($record['level_name']); + } + + $message = [ + 'message' => $record['message'], + 'context' => $record['context'], + 'extra' => $record['extra'], + ]; + + if (!$this->levelTag) { + $message['level'] = $record['level']; + $message['level_name'] = $record['level_name']; + } + + return Utils::jsonEncode([$tag, $record['datetime']->getTimestamp(), $message]); + } + + public function formatBatch(array $records): string + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php new file mode 100644 index 0000000..19617ec --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php @@ -0,0 +1,42 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Interface for formatters + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +interface FormatterInterface +{ + /** + * Formats a log record. + * + * @param array $record A record to format + * @return mixed The formatted record + * + * @phpstan-param Record $record + */ + public function format(array $record); + + /** + * Formats a set of log records. + * + * @param array $records A set of records to format + * @return mixed The formatted set of records + * + * @phpstan-param Record[] $records + */ + public function formatBatch(array $records); +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php new file mode 100644 index 0000000..3b3e1e7 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php @@ -0,0 +1,175 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; +use Gelf\Message; +use Monolog\Utils; + +/** + * Serializes a log message to GELF + * @see http://docs.graylog.org/en/latest/pages/gelf.html + * + * @author Matt Lehner <mlehner@gmail.com> + * + * @phpstan-import-type Level from \Monolog\Logger + */ +class GelfMessageFormatter extends NormalizerFormatter +{ + protected const DEFAULT_MAX_LENGTH = 32766; + + /** + * @var string the name of the system for the Gelf log message + */ + protected $systemName; + + /** + * @var string a prefix for 'extra' fields from the Monolog record (optional) + */ + protected $extraPrefix; + + /** + * @var string a prefix for 'context' fields from the Monolog record (optional) + */ + protected $contextPrefix; + + /** + * @var int max length per field + */ + protected $maxLength; + + /** + * @var int + */ + private $gelfVersion = 2; + + /** + * Translates Monolog log levels to Graylog2 log priorities. + * + * @var array<int, int> + * + * @phpstan-var array<Level, int> + */ + private $logLevels = [ + Logger::DEBUG => 7, + Logger::INFO => 6, + Logger::NOTICE => 5, + Logger::WARNING => 4, + Logger::ERROR => 3, + Logger::CRITICAL => 2, + Logger::ALERT => 1, + Logger::EMERGENCY => 0, + ]; + + public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null) + { + if (!class_exists(Message::class)) { + throw new \RuntimeException('Composer package graylog2/gelf-php is required to use Monolog\'s GelfMessageFormatter'); + } + + parent::__construct('U.u'); + + $this->systemName = (is_null($systemName) || $systemName === '') ? (string) gethostname() : $systemName; + + $this->extraPrefix = is_null($extraPrefix) ? '' : $extraPrefix; + $this->contextPrefix = $contextPrefix; + $this->maxLength = is_null($maxLength) ? self::DEFAULT_MAX_LENGTH : $maxLength; + + if (method_exists(Message::class, 'setFacility')) { + $this->gelfVersion = 1; + } + } + + /** + * {@inheritDoc} + */ + public function format(array $record): Message + { + $context = $extra = []; + if (isset($record['context'])) { + /** @var mixed[] $context */ + $context = parent::normalize($record['context']); + } + if (isset($record['extra'])) { + /** @var mixed[] $extra */ + $extra = parent::normalize($record['extra']); + } + + if (!isset($record['datetime'], $record['message'], $record['level'])) { + throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, '.var_export($record, true).' given'); + } + + $message = new Message(); + $message + ->setTimestamp($record['datetime']) + ->setShortMessage((string) $record['message']) + ->setHost($this->systemName) + ->setLevel($this->logLevels[$record['level']]); + + // message length + system name length + 200 for padding / metadata + $len = 200 + strlen((string) $record['message']) + strlen($this->systemName); + + if ($len > $this->maxLength) { + $message->setShortMessage(Utils::substr($record['message'], 0, $this->maxLength)); + } + + if ($this->gelfVersion === 1) { + if (isset($record['channel'])) { + $message->setFacility($record['channel']); + } + if (isset($extra['line'])) { + $message->setLine($extra['line']); + unset($extra['line']); + } + if (isset($extra['file'])) { + $message->setFile($extra['file']); + unset($extra['file']); + } + } else { + $message->setAdditional('facility', $record['channel']); + } + + foreach ($extra as $key => $val) { + $val = is_scalar($val) || null === $val ? $val : $this->toJson($val); + $len = strlen($this->extraPrefix . $key . $val); + if ($len > $this->maxLength) { + $message->setAdditional($this->extraPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength)); + + continue; + } + $message->setAdditional($this->extraPrefix . $key, $val); + } + + foreach ($context as $key => $val) { + $val = is_scalar($val) || null === $val ? $val : $this->toJson($val); + $len = strlen($this->contextPrefix . $key . $val); + if ($len > $this->maxLength) { + $message->setAdditional($this->contextPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength)); + + continue; + } + $message->setAdditional($this->contextPrefix . $key, $val); + } + + if ($this->gelfVersion === 1) { + /** @phpstan-ignore-next-line */ + if (null === $message->getFile() && isset($context['exception']['file'])) { + if (preg_match("/^(.+):([0-9]+)$/", $context['exception']['file'], $matches)) { + $message->setFile($matches[1]); + $message->setLine($matches[2]); + } + } + } + + return $message; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php new file mode 100644 index 0000000..ca52ebf --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use DateTimeInterface; +use Monolog\LogRecord; + +/** + * Encodes message information into JSON in a format compatible with Cloud logging. + * + * @see https://cloud.google.com/logging/docs/structured-logging + * @see https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry + * + * @author Luís Cobucci <lcobucci@gmail.com> + */ +final class GoogleCloudLoggingFormatter extends JsonFormatter +{ + /** {@inheritdoc} **/ + public function format(array $record): string + { + // Re-key level for GCP logging + $record['severity'] = $record['level_name']; + $record['time'] = $record['datetime']->format(DateTimeInterface::RFC3339_EXTENDED); + + // Remove keys that are not used by GCP + unset($record['level'], $record['level_name'], $record['datetime']); + + return parent::format($record); + } +} + diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php new file mode 100644 index 0000000..10a4311 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php @@ -0,0 +1,142 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; +use Monolog\Utils; + +/** + * Formats incoming records into an HTML table + * + * This is especially useful for html email logging + * + * @author Tiago Brito <tlfbrito@gmail.com> + */ +class HtmlFormatter extends NormalizerFormatter +{ + /** + * Translates Monolog log levels to html color priorities. + * + * @var array<int, string> + */ + protected $logLevels = [ + Logger::DEBUG => '#CCCCCC', + Logger::INFO => '#28A745', + Logger::NOTICE => '#17A2B8', + Logger::WARNING => '#FFC107', + Logger::ERROR => '#FD7E14', + Logger::CRITICAL => '#DC3545', + Logger::ALERT => '#821722', + Logger::EMERGENCY => '#000000', + ]; + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(?string $dateFormat = null) + { + parent::__construct($dateFormat); + } + + /** + * Creates an HTML table row + * + * @param string $th Row header content + * @param string $td Row standard cell content + * @param bool $escapeTd false if td content must not be html escaped + */ + protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): string + { + $th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8'); + if ($escapeTd) { + $td = '<pre>'.htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8').'</pre>'; + } + + return "<tr style=\"padding: 4px;text-align: left;\">\n<th style=\"vertical-align: top;background: #ccc;color: #000\" width=\"100\">$th:</th>\n<td style=\"padding: 4px;text-align: left;vertical-align: top;background: #eee;color: #000\">".$td."</td>\n</tr>"; + } + + /** + * Create a HTML h1 tag + * + * @param string $title Text to be in the h1 + * @param int $level Error level + * @return string + */ + protected function addTitle(string $title, int $level): string + { + $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); + + return '<h1 style="background: '.$this->logLevels[$level].';color: #ffffff;padding: 5px;" class="monolog-output">'.$title.'</h1>'; + } + + /** + * Formats a log record. + * + * @return string The formatted record + */ + public function format(array $record): string + { + $output = $this->addTitle($record['level_name'], $record['level']); + $output .= '<table cellspacing="1" width="100%" class="monolog-output">'; + + $output .= $this->addRow('Message', (string) $record['message']); + $output .= $this->addRow('Time', $this->formatDate($record['datetime'])); + $output .= $this->addRow('Channel', $record['channel']); + if ($record['context']) { + $embeddedTable = '<table cellspacing="1" width="100%">'; + foreach ($record['context'] as $key => $value) { + $embeddedTable .= $this->addRow((string) $key, $this->convertToString($value)); + } + $embeddedTable .= '</table>'; + $output .= $this->addRow('Context', $embeddedTable, false); + } + if ($record['extra']) { + $embeddedTable = '<table cellspacing="1" width="100%">'; + foreach ($record['extra'] as $key => $value) { + $embeddedTable .= $this->addRow((string) $key, $this->convertToString($value)); + } + $embeddedTable .= '</table>'; + $output .= $this->addRow('Extra', $embeddedTable, false); + } + + return $output.'</table>'; + } + + /** + * Formats a set of log records. + * + * @return string The formatted set of records + */ + public function formatBatch(array $records): string + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } + + /** + * @param mixed $data + */ + protected function convertToString($data): string + { + if (null === $data || is_scalar($data)) { + return (string) $data; + } + + $data = $this->normalize($data); + + return Utils::jsonEncode($data, JSON_PRETTY_PRINT | Utils::DEFAULT_JSON_FLAGS, true); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php new file mode 100644 index 0000000..b737d82 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php @@ -0,0 +1,224 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Throwable; + +/** + * Encodes whatever record data is passed to it as json + * + * This can be useful to log to databases or remote APIs + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class JsonFormatter extends NormalizerFormatter +{ + public const BATCH_MODE_JSON = 1; + public const BATCH_MODE_NEWLINES = 2; + + /** @var self::BATCH_MODE_* */ + protected $batchMode; + /** @var bool */ + protected $appendNewline; + /** @var bool */ + protected $ignoreEmptyContextAndExtra; + /** @var bool */ + protected $includeStacktraces = false; + + /** + * @param self::BATCH_MODE_* $batchMode + */ + public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) + { + $this->batchMode = $batchMode; + $this->appendNewline = $appendNewline; + $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra; + $this->includeStacktraces = $includeStacktraces; + + parent::__construct(); + } + + /** + * The batch mode option configures the formatting style for + * multiple records. By default, multiple records will be + * formatted as a JSON-encoded array. However, for + * compatibility with some API endpoints, alternative styles + * are available. + */ + public function getBatchMode(): int + { + return $this->batchMode; + } + + /** + * True if newlines are appended to every formatted record + */ + public function isAppendingNewlines(): bool + { + return $this->appendNewline; + } + + /** + * {@inheritDoc} + */ + public function format(array $record): string + { + $normalized = $this->normalize($record); + + if (isset($normalized['context']) && $normalized['context'] === []) { + if ($this->ignoreEmptyContextAndExtra) { + unset($normalized['context']); + } else { + $normalized['context'] = new \stdClass; + } + } + if (isset($normalized['extra']) && $normalized['extra'] === []) { + if ($this->ignoreEmptyContextAndExtra) { + unset($normalized['extra']); + } else { + $normalized['extra'] = new \stdClass; + } + } + + return $this->toJson($normalized, true) . ($this->appendNewline ? "\n" : ''); + } + + /** + * {@inheritDoc} + */ + public function formatBatch(array $records): string + { + switch ($this->batchMode) { + case static::BATCH_MODE_NEWLINES: + return $this->formatBatchNewlines($records); + + case static::BATCH_MODE_JSON: + default: + return $this->formatBatchJson($records); + } + } + + /** + * @return self + */ + public function includeStacktraces(bool $include = true): self + { + $this->includeStacktraces = $include; + + return $this; + } + + /** + * Return a JSON-encoded array of records. + * + * @phpstan-param Record[] $records + */ + protected function formatBatchJson(array $records): string + { + return $this->toJson($this->normalize($records), true); + } + + /** + * Use new lines to separate records instead of a + * JSON-encoded array. + * + * @phpstan-param Record[] $records + */ + protected function formatBatchNewlines(array $records): string + { + $instance = $this; + + $oldNewline = $this->appendNewline; + $this->appendNewline = false; + array_walk($records, function (&$value, $key) use ($instance) { + $value = $instance->format($value); + }); + $this->appendNewline = $oldNewline; + + return implode("\n", $records); + } + + /** + * Normalizes given $data. + * + * @param mixed $data + * + * @return mixed + */ + protected function normalize($data, int $depth = 0) + { + if ($depth > $this->maxNormalizeDepth) { + return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization'; + } + + if (is_array($data)) { + $normalized = []; + + $count = 1; + foreach ($data as $key => $value) { + if ($count++ > $this->maxNormalizeItemCount) { + $normalized['...'] = 'Over '.$this->maxNormalizeItemCount.' items ('.count($data).' total), aborting normalization'; + break; + } + + $normalized[$key] = $this->normalize($value, $depth + 1); + } + + return $normalized; + } + + if (is_object($data)) { + if ($data instanceof \DateTimeInterface) { + return $this->formatDate($data); + } + + if ($data instanceof Throwable) { + return $this->normalizeException($data, $depth); + } + + // if the object has specific json serializability we want to make sure we skip the __toString treatment below + if ($data instanceof \JsonSerializable) { + return $data; + } + + if (method_exists($data, '__toString')) { + return $data->__toString(); + } + + return $data; + } + + if (is_resource($data)) { + return parent::normalize($data); + } + + return $data; + } + + /** + * Normalizes given exception with or without its own stack trace based on + * `includeStacktraces` property. + * + * {@inheritDoc} + */ + protected function normalizeException(Throwable $e, int $depth = 0): array + { + $data = parent::normalizeException($e, $depth); + if (!$this->includeStacktraces) { + unset($data['trace']); + } + + return $data; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php new file mode 100644 index 0000000..e6e7898 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php @@ -0,0 +1,246 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Utils; + +/** + * Formats incoming records into a one-line string + * + * This is especially useful for logging to files + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @author Christophe Coevoet <stof@notk.org> + */ +class LineFormatter extends NormalizerFormatter +{ + public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"; + + /** @var string */ + protected $format; + /** @var bool */ + protected $allowInlineLineBreaks; + /** @var bool */ + protected $ignoreEmptyContextAndExtra; + /** @var bool */ + protected $includeStacktraces; + /** @var ?callable */ + protected $stacktracesParser; + + /** + * @param string|null $format The format of the message + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries + * @param bool $ignoreEmptyContextAndExtra + */ + public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) + { + $this->format = $format === null ? static::SIMPLE_FORMAT : $format; + $this->allowInlineLineBreaks = $allowInlineLineBreaks; + $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra; + $this->includeStacktraces($includeStacktraces); + parent::__construct($dateFormat); + } + + public function includeStacktraces(bool $include = true, ?callable $parser = null): self + { + $this->includeStacktraces = $include; + if ($this->includeStacktraces) { + $this->allowInlineLineBreaks = true; + $this->stacktracesParser = $parser; + } + + return $this; + } + + public function allowInlineLineBreaks(bool $allow = true): self + { + $this->allowInlineLineBreaks = $allow; + + return $this; + } + + public function ignoreEmptyContextAndExtra(bool $ignore = true): self + { + $this->ignoreEmptyContextAndExtra = $ignore; + + return $this; + } + + /** + * {@inheritDoc} + */ + public function format(array $record): string + { + $vars = parent::format($record); + + $output = $this->format; + + foreach ($vars['extra'] as $var => $val) { + if (false !== strpos($output, '%extra.'.$var.'%')) { + $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output); + unset($vars['extra'][$var]); + } + } + + foreach ($vars['context'] as $var => $val) { + if (false !== strpos($output, '%context.'.$var.'%')) { + $output = str_replace('%context.'.$var.'%', $this->stringify($val), $output); + unset($vars['context'][$var]); + } + } + + if ($this->ignoreEmptyContextAndExtra) { + if (empty($vars['context'])) { + unset($vars['context']); + $output = str_replace('%context%', '', $output); + } + + if (empty($vars['extra'])) { + unset($vars['extra']); + $output = str_replace('%extra%', '', $output); + } + } + + foreach ($vars as $var => $val) { + if (false !== strpos($output, '%'.$var.'%')) { + $output = str_replace('%'.$var.'%', $this->stringify($val), $output); + } + } + + // remove leftover %extra.xxx% and %context.xxx% if any + if (false !== strpos($output, '%')) { + $output = preg_replace('/%(?:extra|context)\..+?%/', '', $output); + if (null === $output) { + $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + } + } + + return $output; + } + + public function formatBatch(array $records): string + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } + + /** + * @param mixed $value + */ + public function stringify($value): string + { + return $this->replaceNewlines($this->convertToString($value)); + } + + protected function normalizeException(\Throwable $e, int $depth = 0): string + { + $str = $this->formatException($e); + + if ($previous = $e->getPrevious()) { + do { + $depth++; + if ($depth > $this->maxNormalizeDepth) { + $str .= "\n[previous exception] Over " . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; + break; + } + + $str .= "\n[previous exception] " . $this->formatException($previous); + } while ($previous = $previous->getPrevious()); + } + + return $str; + } + + /** + * @param mixed $data + */ + protected function convertToString($data): string + { + if (null === $data || is_bool($data)) { + return var_export($data, true); + } + + if (is_scalar($data)) { + return (string) $data; + } + + return $this->toJson($data, true); + } + + protected function replaceNewlines(string $str): string + { + if ($this->allowInlineLineBreaks) { + if (0 === strpos($str, '{')) { + $str = preg_replace('/(?<!\\\\)\\\\[rn]/', "\n", $str); + if (null === $str) { + $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + } + } + + return $str; + } + + return str_replace(["\r\n", "\r", "\n"], ' ', $str); + } + + private function formatException(\Throwable $e): string + { + $str = '[object] (' . Utils::getClass($e) . '(code: ' . $e->getCode(); + if ($e instanceof \SoapFault) { + if (isset($e->faultcode)) { + $str .= ' faultcode: ' . $e->faultcode; + } + + if (isset($e->faultactor)) { + $str .= ' faultactor: ' . $e->faultactor; + } + + if (isset($e->detail)) { + if (is_string($e->detail)) { + $str .= ' detail: ' . $e->detail; + } elseif (is_object($e->detail) || is_array($e->detail)) { + $str .= ' detail: ' . $this->toJson($e->detail, true); + } + } + } + $str .= '): ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine() . ')'; + + if ($this->includeStacktraces) { + $str .= $this->stacktracesParser($e); + } + + return $str; + } + + private function stacktracesParser(\Throwable $e): string + { + $trace = $e->getTraceAsString(); + + if ($this->stacktracesParser) { + $trace = $this->stacktracesParserCustom($trace); + } + + return "\n[stacktrace]\n" . $trace . "\n"; + } + + private function stacktracesParserCustom(string $trace): string + { + return implode("\n", array_filter(array_map($this->stacktracesParser, explode("\n", $trace)))); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php new file mode 100644 index 0000000..29841aa --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php @@ -0,0 +1,45 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Encodes message information into JSON in a format compatible with Loggly. + * + * @author Adam Pancutt <adam@pancutt.com> + */ +class LogglyFormatter extends JsonFormatter +{ + /** + * Overrides the default batch mode to new lines for compatibility with the + * Loggly bulk API. + */ + public function __construct(int $batchMode = self::BATCH_MODE_NEWLINES, bool $appendNewline = false) + { + parent::__construct($batchMode, $appendNewline); + } + + /** + * Appends the 'timestamp' parameter for indexing by Loggly. + * + * @see https://www.loggly.com/docs/automated-parsing/#json + * @see \Monolog\Formatter\JsonFormatter::format() + */ + public function format(array $record): string + { + if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) { + $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO"); + unset($record["datetime"]); + } + + return parent::format($record); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php new file mode 100644 index 0000000..b0451ab --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php @@ -0,0 +1,66 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Encodes message information into JSON in a format compatible with Logmatic. + * + * @author Julien Breux <julien.breux@gmail.com> + */ +class LogmaticFormatter extends JsonFormatter +{ + protected const MARKERS = ["sourcecode", "php"]; + + /** + * @var string + */ + protected $hostname = ''; + + /** + * @var string + */ + protected $appname = ''; + + public function setHostname(string $hostname): self + { + $this->hostname = $hostname; + + return $this; + } + + public function setAppname(string $appname): self + { + $this->appname = $appname; + + return $this; + } + + /** + * Appends the 'hostname' and 'appname' parameter for indexing by Logmatic. + * + * @see http://doc.logmatic.io/docs/basics-to-send-data + * @see \Monolog\Formatter\JsonFormatter::format() + */ + public function format(array $record): string + { + if (!empty($this->hostname)) { + $record["hostname"] = $this->hostname; + } + if (!empty($this->appname)) { + $record["appname"] = $this->appname; + } + + $record["@marker"] = static::MARKERS; + + return parent::format($record); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php new file mode 100644 index 0000000..f8de0d3 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php @@ -0,0 +1,101 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Serializes a log message to Logstash Event Format + * + * @see https://www.elastic.co/products/logstash + * @see https://github.com/elastic/logstash/blob/master/logstash-core/src/main/java/org/logstash/Event.java + * + * @author Tim Mower <timothy.mower@gmail.com> + */ +class LogstashFormatter extends NormalizerFormatter +{ + /** + * @var string the name of the system for the Logstash log message, used to fill the @source field + */ + protected $systemName; + + /** + * @var string an application name for the Logstash log message, used to fill the @type field + */ + protected $applicationName; + + /** + * @var string the key for 'extra' fields from the Monolog record + */ + protected $extraKey; + + /** + * @var string the key for 'context' fields from the Monolog record + */ + protected $contextKey; + + /** + * @param string $applicationName The application that sends the data, used as the "type" field of logstash + * @param string|null $systemName The system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine + * @param string $extraKey The key for extra keys inside logstash "fields", defaults to extra + * @param string $contextKey The key for context keys inside logstash "fields", defaults to context + */ + public function __construct(string $applicationName, ?string $systemName = null, string $extraKey = 'extra', string $contextKey = 'context') + { + // logstash requires a ISO 8601 format date with optional millisecond precision. + parent::__construct('Y-m-d\TH:i:s.uP'); + + $this->systemName = $systemName === null ? (string) gethostname() : $systemName; + $this->applicationName = $applicationName; + $this->extraKey = $extraKey; + $this->contextKey = $contextKey; + } + + /** + * {@inheritDoc} + */ + public function format(array $record): string + { + $record = parent::format($record); + + if (empty($record['datetime'])) { + $record['datetime'] = gmdate('c'); + } + $message = [ + '@timestamp' => $record['datetime'], + '@version' => 1, + 'host' => $this->systemName, + ]; + if (isset($record['message'])) { + $message['message'] = $record['message']; + } + if (isset($record['channel'])) { + $message['type'] = $record['channel']; + $message['channel'] = $record['channel']; + } + if (isset($record['level_name'])) { + $message['level'] = $record['level_name']; + } + if (isset($record['level'])) { + $message['monolog_level'] = $record['level']; + } + if ($this->applicationName) { + $message['type'] = $this->applicationName; + } + if (!empty($record['extra'])) { + $message[$this->extraKey] = $record['extra']; + } + if (!empty($record['context'])) { + $message[$this->contextKey] = $record['context']; + } + + return $this->toJson($message) . "\n"; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php new file mode 100644 index 0000000..fca69a8 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php @@ -0,0 +1,162 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use MongoDB\BSON\Type; +use MongoDB\BSON\UTCDateTime; +use Monolog\Utils; + +/** + * Formats a record for use with the MongoDBHandler. + * + * @author Florian Plattner <me@florianplattner.de> + */ +class MongoDBFormatter implements FormatterInterface +{ + /** @var bool */ + private $exceptionTraceAsString; + /** @var int */ + private $maxNestingLevel; + /** @var bool */ + private $isLegacyMongoExt; + + /** + * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2 + * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings + */ + public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsString = true) + { + $this->maxNestingLevel = max($maxNestingLevel, 0); + $this->exceptionTraceAsString = $exceptionTraceAsString; + + $this->isLegacyMongoExt = extension_loaded('mongodb') && version_compare((string) phpversion('mongodb'), '1.1.9', '<='); + } + + /** + * {@inheritDoc} + * + * @return mixed[] + */ + public function format(array $record): array + { + /** @var mixed[] $res */ + $res = $this->formatArray($record); + + return $res; + } + + /** + * {@inheritDoc} + * + * @return array<mixed[]> + */ + public function formatBatch(array $records): array + { + $formatted = []; + foreach ($records as $key => $record) { + $formatted[$key] = $this->format($record); + } + + return $formatted; + } + + /** + * @param mixed[] $array + * @return mixed[]|string Array except when max nesting level is reached then a string "[...]" + */ + protected function formatArray(array $array, int $nestingLevel = 0) + { + if ($this->maxNestingLevel > 0 && $nestingLevel > $this->maxNestingLevel) { + return '[...]'; + } + + foreach ($array as $name => $value) { + if ($value instanceof \DateTimeInterface) { + $array[$name] = $this->formatDate($value, $nestingLevel + 1); + } elseif ($value instanceof \Throwable) { + $array[$name] = $this->formatException($value, $nestingLevel + 1); + } elseif (is_array($value)) { + $array[$name] = $this->formatArray($value, $nestingLevel + 1); + } elseif (is_object($value) && !$value instanceof Type) { + $array[$name] = $this->formatObject($value, $nestingLevel + 1); + } + } + + return $array; + } + + /** + * @param mixed $value + * @return mixed[]|string + */ + protected function formatObject($value, int $nestingLevel) + { + $objectVars = get_object_vars($value); + $objectVars['class'] = Utils::getClass($value); + + return $this->formatArray($objectVars, $nestingLevel); + } + + /** + * @return mixed[]|string + */ + protected function formatException(\Throwable $exception, int $nestingLevel) + { + $formattedException = [ + 'class' => Utils::getClass($exception), + 'message' => $exception->getMessage(), + 'code' => (int) $exception->getCode(), + 'file' => $exception->getFile() . ':' . $exception->getLine(), + ]; + + if ($this->exceptionTraceAsString === true) { + $formattedException['trace'] = $exception->getTraceAsString(); + } else { + $formattedException['trace'] = $exception->getTrace(); + } + + return $this->formatArray($formattedException, $nestingLevel); + } + + protected function formatDate(\DateTimeInterface $value, int $nestingLevel): UTCDateTime + { + if ($this->isLegacyMongoExt) { + return $this->legacyGetMongoDbDateTime($value); + } + + return $this->getMongoDbDateTime($value); + } + + private function getMongoDbDateTime(\DateTimeInterface $value): UTCDateTime + { + return new UTCDateTime((int) floor(((float) $value->format('U.u')) * 1000)); + } + + /** + * This is needed to support MongoDB Driver v1.19 and below + * + * See https://github.com/mongodb/mongo-php-driver/issues/426 + * + * It can probably be removed in 2.1 or later once MongoDB's 1.2 is released and widely adopted + */ + private function legacyGetMongoDbDateTime(\DateTimeInterface $value): UTCDateTime + { + $milliseconds = floor(((float) $value->format('U.u')) * 1000); + + $milliseconds = (PHP_INT_SIZE == 8) //64-bit OS? + ? (int) $milliseconds + : (string) $milliseconds; + + // @phpstan-ignore-next-line + return new UTCDateTime($milliseconds); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php new file mode 100644 index 0000000..f926a84 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php @@ -0,0 +1,290 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\DateTimeImmutable; +use Monolog\Utils; +use Throwable; + +/** + * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class NormalizerFormatter implements FormatterInterface +{ + public const SIMPLE_DATE = "Y-m-d\TH:i:sP"; + + /** @var string */ + protected $dateFormat; + /** @var int */ + protected $maxNormalizeDepth = 9; + /** @var int */ + protected $maxNormalizeItemCount = 1000; + + /** @var int */ + private $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS; + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(?string $dateFormat = null) + { + $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat; + if (!function_exists('json_encode')) { + throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter'); + } + } + + /** + * {@inheritDoc} + * + * @param mixed[] $record + */ + public function format(array $record) + { + return $this->normalize($record); + } + + /** + * {@inheritDoc} + */ + public function formatBatch(array $records) + { + foreach ($records as $key => $record) { + $records[$key] = $this->format($record); + } + + return $records; + } + + public function getDateFormat(): string + { + return $this->dateFormat; + } + + public function setDateFormat(string $dateFormat): self + { + $this->dateFormat = $dateFormat; + + return $this; + } + + /** + * The maximum number of normalization levels to go through + */ + public function getMaxNormalizeDepth(): int + { + return $this->maxNormalizeDepth; + } + + public function setMaxNormalizeDepth(int $maxNormalizeDepth): self + { + $this->maxNormalizeDepth = $maxNormalizeDepth; + + return $this; + } + + /** + * The maximum number of items to normalize per level + */ + public function getMaxNormalizeItemCount(): int + { + return $this->maxNormalizeItemCount; + } + + public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self + { + $this->maxNormalizeItemCount = $maxNormalizeItemCount; + + return $this; + } + + /** + * Enables `json_encode` pretty print. + */ + public function setJsonPrettyPrint(bool $enable): self + { + if ($enable) { + $this->jsonEncodeOptions |= JSON_PRETTY_PRINT; + } else { + $this->jsonEncodeOptions &= ~JSON_PRETTY_PRINT; + } + + return $this; + } + + /** + * @param mixed $data + * @return null|scalar|array<array|scalar|null> + */ + protected function normalize($data, int $depth = 0) + { + if ($depth > $this->maxNormalizeDepth) { + return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; + } + + if (null === $data || is_scalar($data)) { + if (is_float($data)) { + if (is_infinite($data)) { + return ($data > 0 ? '' : '-') . 'INF'; + } + if (is_nan($data)) { + return 'NaN'; + } + } + + return $data; + } + + if (is_array($data)) { + $normalized = []; + + $count = 1; + foreach ($data as $key => $value) { + if ($count++ > $this->maxNormalizeItemCount) { + $normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.count($data).' total), aborting normalization'; + break; + } + + $normalized[$key] = $this->normalize($value, $depth + 1); + } + + return $normalized; + } + + if ($data instanceof \DateTimeInterface) { + return $this->formatDate($data); + } + + if (is_object($data)) { + if ($data instanceof Throwable) { + return $this->normalizeException($data, $depth); + } + + if ($data instanceof \JsonSerializable) { + /** @var null|scalar|array<array|scalar|null> $value */ + $value = $data->jsonSerialize(); + } elseif (\get_class($data) === '__PHP_Incomplete_Class') { + $accessor = new \ArrayObject($data); + $value = (string) $accessor['__PHP_Incomplete_Class_Name']; + } elseif (method_exists($data, '__toString')) { + /** @var string $value */ + $value = $data->__toString(); + } else { + // the rest is normalized by json encoding and decoding it + /** @var null|scalar|array<array|scalar|null> $value */ + $value = json_decode($this->toJson($data, true), true); + } + + return [Utils::getClass($data) => $value]; + } + + if (is_resource($data)) { + return sprintf('[resource(%s)]', get_resource_type($data)); + } + + return '[unknown('.gettype($data).')]'; + } + + /** + * @return mixed[] + */ + protected function normalizeException(Throwable $e, int $depth = 0) + { + if ($depth > $this->maxNormalizeDepth) { + return ['Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization']; + } + + if ($e instanceof \JsonSerializable) { + return (array) $e->jsonSerialize(); + } + + $data = [ + 'class' => Utils::getClass($e), + 'message' => $e->getMessage(), + 'code' => (int) $e->getCode(), + 'file' => $e->getFile().':'.$e->getLine(), + ]; + + if ($e instanceof \SoapFault) { + if (isset($e->faultcode)) { + $data['faultcode'] = $e->faultcode; + } + + if (isset($e->faultactor)) { + $data['faultactor'] = $e->faultactor; + } + + if (isset($e->detail)) { + if (is_string($e->detail)) { + $data['detail'] = $e->detail; + } elseif (is_object($e->detail) || is_array($e->detail)) { + $data['detail'] = $this->toJson($e->detail, true); + } + } + } + + $trace = $e->getTrace(); + foreach ($trace as $frame) { + if (isset($frame['file'])) { + $data['trace'][] = $frame['file'].':'.$frame['line']; + } + } + + if ($previous = $e->getPrevious()) { + $data['previous'] = $this->normalizeException($previous, $depth + 1); + } + + return $data; + } + + /** + * Return the JSON representation of a value + * + * @param mixed $data + * @throws \RuntimeException if encoding fails and errors are not ignored + * @return string if encoding fails and ignoreErrors is true 'null' is returned + */ + protected function toJson($data, bool $ignoreErrors = false): string + { + return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors); + } + + /** + * @return string + */ + protected function formatDate(\DateTimeInterface $date) + { + // in case the date format isn't custom then we defer to the custom DateTimeImmutable + // formatting logic, which will pick the right format based on whether useMicroseconds is on + if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof DateTimeImmutable) { + return (string) $date; + } + + return $date->format($this->dateFormat); + } + + public function addJsonEncodeOption(int $option): self + { + $this->jsonEncodeOptions |= $option; + + return $this; + } + + public function removeJsonEncodeOption(int $option): self + { + $this->jsonEncodeOptions &= ~$option; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php new file mode 100644 index 0000000..187bc55 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php @@ -0,0 +1,51 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Formats data into an associative array of scalar values. + * Objects and arrays will be JSON encoded. + * + * @author Andrew Lawson <adlawson@gmail.com> + */ +class ScalarFormatter extends NormalizerFormatter +{ + /** + * {@inheritDoc} + * + * @phpstan-return array<string, scalar|null> $record + */ + public function format(array $record): array + { + $result = []; + foreach ($record as $key => $value) { + $result[$key] = $this->normalizeValue($value); + } + + return $result; + } + + /** + * @param mixed $value + * @return scalar|null + */ + protected function normalizeValue($value) + { + $normalized = $this->normalize($value); + + if (is_array($normalized)) { + return $this->toJson($normalized, true); + } + + return $normalized; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php new file mode 100644 index 0000000..6539b34 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php @@ -0,0 +1,139 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +/** + * Serializes a log message according to Wildfire's header requirements + * + * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com> + * @author Christophe Coevoet <stof@notk.org> + * @author Kirill chEbba Chebunin <iam@chebba.org> + * + * @phpstan-import-type Level from \Monolog\Logger + */ +class WildfireFormatter extends NormalizerFormatter +{ + /** + * Translates Monolog log levels to Wildfire levels. + * + * @var array<Level, string> + */ + private $logLevels = [ + Logger::DEBUG => 'LOG', + Logger::INFO => 'INFO', + Logger::NOTICE => 'INFO', + Logger::WARNING => 'WARN', + Logger::ERROR => 'ERROR', + Logger::CRITICAL => 'ERROR', + Logger::ALERT => 'ERROR', + Logger::EMERGENCY => 'ERROR', + ]; + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(?string $dateFormat = null) + { + parent::__construct($dateFormat); + + // http headers do not like non-ISO-8559-1 characters + $this->removeJsonEncodeOption(JSON_UNESCAPED_UNICODE); + } + + /** + * {@inheritDoc} + * + * @return string + */ + public function format(array $record): string + { + // Retrieve the line and file if set and remove them from the formatted extra + $file = $line = ''; + if (isset($record['extra']['file'])) { + $file = $record['extra']['file']; + unset($record['extra']['file']); + } + if (isset($record['extra']['line'])) { + $line = $record['extra']['line']; + unset($record['extra']['line']); + } + + /** @var mixed[] $record */ + $record = $this->normalize($record); + $message = ['message' => $record['message']]; + $handleError = false; + if ($record['context']) { + $message['context'] = $record['context']; + $handleError = true; + } + if ($record['extra']) { + $message['extra'] = $record['extra']; + $handleError = true; + } + if (count($message) === 1) { + $message = reset($message); + } + + if (isset($record['context']['table'])) { + $type = 'TABLE'; + $label = $record['channel'] .': '. $record['message']; + $message = $record['context']['table']; + } else { + $type = $this->logLevels[$record['level']]; + $label = $record['channel']; + } + + // Create JSON object describing the appearance of the message in the console + $json = $this->toJson([ + [ + 'Type' => $type, + 'File' => $file, + 'Line' => $line, + 'Label' => $label, + ], + $message, + ], $handleError); + + // The message itself is a serialization of the above JSON object + it's length + return sprintf( + '%d|%s|', + strlen($json), + $json + ); + } + + /** + * {@inheritDoc} + * + * @phpstan-return never + */ + public function formatBatch(array $records) + { + throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter'); + } + + /** + * {@inheritDoc} + * + * @return null|scalar|array<array|scalar|null>|object + */ + protected function normalize($data, int $depth = 0) + { + if (is_object($data) && !$data instanceof \DateTimeInterface) { + return $data; + } + + return parent::normalize($data, $depth); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php new file mode 100644 index 0000000..a5cdaa7 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php @@ -0,0 +1,112 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\ResettableInterface; +use Psr\Log\LogLevel; + +/** + * Base Handler class providing basic level/bubble support + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +abstract class AbstractHandler extends Handler implements ResettableInterface +{ + /** + * @var int + * @phpstan-var Level + */ + protected $level = Logger::DEBUG; + /** @var bool */ + protected $bubble = true; + + /** + * @param int|string $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function __construct($level = Logger::DEBUG, bool $bubble = true) + { + $this->setLevel($level); + $this->bubble = $bubble; + } + + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + return $record['level'] >= $this->level; + } + + /** + * Sets minimum logging level at which this handler will be triggered. + * + * @param Level|LevelName|LogLevel::* $level Level or level name + * @return self + */ + public function setLevel($level): self + { + $this->level = Logger::toMonologLevel($level); + + return $this; + } + + /** + * Gets minimum logging level at which this handler will be triggered. + * + * @return int + * + * @phpstan-return Level + */ + public function getLevel(): int + { + return $this->level; + } + + /** + * Sets the bubbling behavior. + * + * @param bool $bubble true means that this handler allows bubbling. + * false means that bubbling is not permitted. + * @return self + */ + public function setBubble(bool $bubble): self + { + $this->bubble = $bubble; + + return $this; + } + + /** + * Gets the bubbling behavior. + * + * @return bool true means that this handler allows bubbling. + * false means that bubbling is not permitted. + */ + public function getBubble(): bool + { + return $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function reset() + { + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php new file mode 100644 index 0000000..77e533f --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php @@ -0,0 +1,69 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Base Handler class providing the Handler structure, including processors and formatters + * + * Classes extending it should (in most cases) only implement write($record) + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @author Christophe Coevoet <stof@notk.org> + * + * @phpstan-import-type LevelName from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-type FormattedRecord array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[], formatted: mixed} + */ +abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + use FormattableHandlerTrait; + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + $record['formatted'] = $this->getFormatter()->format($record); + + $this->write($record); + + return false === $this->bubble; + } + + /** + * Writes the record down to the log of the implementing handler + * + * @phpstan-param FormattedRecord $record + */ + abstract protected function write(array $record): void; + + /** + * @return void + */ + public function reset() + { + parent::reset(); + + $this->resetProcessors(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php new file mode 100644 index 0000000..5e5ad1c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php @@ -0,0 +1,106 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; + +/** + * Common syslog functionality + * + * @phpstan-import-type Level from \Monolog\Logger + */ +abstract class AbstractSyslogHandler extends AbstractProcessingHandler +{ + /** @var int */ + protected $facility; + + /** + * Translates Monolog log levels to syslog log priorities. + * @var array + * @phpstan-var array<Level, int> + */ + protected $logLevels = [ + Logger::DEBUG => LOG_DEBUG, + Logger::INFO => LOG_INFO, + Logger::NOTICE => LOG_NOTICE, + Logger::WARNING => LOG_WARNING, + Logger::ERROR => LOG_ERR, + Logger::CRITICAL => LOG_CRIT, + Logger::ALERT => LOG_ALERT, + Logger::EMERGENCY => LOG_EMERG, + ]; + + /** + * List of valid log facility names. + * @var array<string, int> + */ + protected $facilities = [ + 'auth' => LOG_AUTH, + 'authpriv' => LOG_AUTHPRIV, + 'cron' => LOG_CRON, + 'daemon' => LOG_DAEMON, + 'kern' => LOG_KERN, + 'lpr' => LOG_LPR, + 'mail' => LOG_MAIL, + 'news' => LOG_NEWS, + 'syslog' => LOG_SYSLOG, + 'user' => LOG_USER, + 'uucp' => LOG_UUCP, + ]; + + /** + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + */ + public function __construct($facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true) + { + parent::__construct($level, $bubble); + + if (!defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->facilities['local0'] = LOG_LOCAL0; + $this->facilities['local1'] = LOG_LOCAL1; + $this->facilities['local2'] = LOG_LOCAL2; + $this->facilities['local3'] = LOG_LOCAL3; + $this->facilities['local4'] = LOG_LOCAL4; + $this->facilities['local5'] = LOG_LOCAL5; + $this->facilities['local6'] = LOG_LOCAL6; + $this->facilities['local7'] = LOG_LOCAL7; + } else { + $this->facilities['local0'] = 128; // LOG_LOCAL0 + $this->facilities['local1'] = 136; // LOG_LOCAL1 + $this->facilities['local2'] = 144; // LOG_LOCAL2 + $this->facilities['local3'] = 152; // LOG_LOCAL3 + $this->facilities['local4'] = 160; // LOG_LOCAL4 + $this->facilities['local5'] = 168; // LOG_LOCAL5 + $this->facilities['local6'] = 176; // LOG_LOCAL6 + $this->facilities['local7'] = 184; // LOG_LOCAL7 + } + + // convert textual description of facility to syslog constant + if (is_string($facility) && array_key_exists(strtolower($facility), $this->facilities)) { + $facility = $this->facilities[strtolower($facility)]; + } elseif (!in_array($facility, array_values($this->facilities), true)) { + throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given'); + } + + $this->facility = $facility; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('%channel%.%level_name%: %message% %context% %extra%'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php new file mode 100644 index 0000000..994872c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php @@ -0,0 +1,171 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\JsonFormatter; +use PhpAmqpLib\Message\AMQPMessage; +use PhpAmqpLib\Channel\AMQPChannel; +use AMQPExchange; + +/** + * @phpstan-import-type Record from \Monolog\Logger + */ +class AmqpHandler extends AbstractProcessingHandler +{ + /** + * @var AMQPExchange|AMQPChannel $exchange + */ + protected $exchange; + /** @var array<string, mixed> */ + private $extraAttributes = []; + + /** + * @return array<string, mixed> + */ + public function getExtraAttributes(): array + { + return $this->extraAttributes; + } + + /** + * Configure extra attributes to pass to the AMQPExchange (if you are using the amqp extension) + * + * @param array<string, mixed> $extraAttributes One of content_type, content_encoding, + * message_id, user_id, app_id, delivery_mode, + * priority, timestamp, expiration, type + * or reply_to, headers. + * @return AmqpHandler + */ + public function setExtraAttributes(array $extraAttributes): self + { + $this->extraAttributes = $extraAttributes; + return $this; + } + + /** + * @var string + */ + protected $exchangeName; + + /** + * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use + * @param string|null $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only + */ + public function __construct($exchange, ?string $exchangeName = null, $level = Logger::DEBUG, bool $bubble = true) + { + if ($exchange instanceof AMQPChannel) { + $this->exchangeName = (string) $exchangeName; + } elseif (!$exchange instanceof AMQPExchange) { + throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required'); + } elseif ($exchangeName) { + @trigger_error('The $exchangeName parameter can only be passed when using PhpAmqpLib, if using an AMQPExchange instance configure it beforehand', E_USER_DEPRECATED); + } + $this->exchange = $exchange; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $data = $record["formatted"]; + $routingKey = $this->getRoutingKey($record); + + if ($this->exchange instanceof AMQPExchange) { + $attributes = [ + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ]; + if ($this->extraAttributes) { + $attributes = array_merge($attributes, $this->extraAttributes); + } + $this->exchange->publish( + $data, + $routingKey, + 0, + $attributes + ); + } else { + $this->exchange->basic_publish( + $this->createAmqpMessage($data), + $this->exchangeName, + $routingKey + ); + } + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + if ($this->exchange instanceof AMQPExchange) { + parent::handleBatch($records); + + return; + } + + foreach ($records as $record) { + if (!$this->isHandling($record)) { + continue; + } + + /** @var Record $record */ + $record = $this->processRecord($record); + $data = $this->getFormatter()->format($record); + + $this->exchange->batch_basic_publish( + $this->createAmqpMessage($data), + $this->exchangeName, + $this->getRoutingKey($record) + ); + } + + $this->exchange->publish_batch(); + } + + /** + * Gets the routing key for the AMQP exchange + * + * @phpstan-param Record $record + */ + protected function getRoutingKey(array $record): string + { + $routingKey = sprintf('%s.%s', $record['level_name'], $record['channel']); + + return strtolower($routingKey); + } + + private function createAmqpMessage(string $data): AMQPMessage + { + $attributes = [ + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ]; + if ($this->extraAttributes) { + $attributes = array_merge($attributes, $this->extraAttributes); + } + return new AMQPMessage($data, $attributes); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php new file mode 100644 index 0000000..95bbfed --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php @@ -0,0 +1,308 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Monolog\Utils; +use Monolog\Logger; + +use function count; +use function headers_list; +use function stripos; +use function trigger_error; + +use const E_USER_DEPRECATED; + +/** + * Handler sending logs to browser's javascript console with no browser extension required + * + * @author Olivier Poitrey <rs@dailymotion.com> + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class BrowserConsoleHandler extends AbstractProcessingHandler +{ + /** @var bool */ + protected static $initialized = false; + /** @var FormattedRecord[] */ + protected static $records = []; + + protected const FORMAT_HTML = 'html'; + protected const FORMAT_JS = 'js'; + protected const FORMAT_UNKNOWN = 'unknown'; + + /** + * {@inheritDoc} + * + * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format. + * + * Example of formatted string: + * + * You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%'); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + // Accumulate records + static::$records[] = $record; + + // Register shutdown handler if not already done + if (!static::$initialized) { + static::$initialized = true; + $this->registerShutdownFunction(); + } + } + + /** + * Convert records to javascript console commands and send it to the browser. + * This method is automatically called on PHP shutdown if output is HTML or Javascript. + */ + public static function send(): void + { + $format = static::getResponseFormat(); + if ($format === self::FORMAT_UNKNOWN) { + return; + } + + if (count(static::$records)) { + if ($format === self::FORMAT_HTML) { + static::writeOutput('<script>' . static::generateScript() . '</script>'); + } elseif ($format === self::FORMAT_JS) { + static::writeOutput(static::generateScript()); + } + static::resetStatic(); + } + } + + public function close(): void + { + self::resetStatic(); + } + + public function reset() + { + parent::reset(); + + self::resetStatic(); + } + + /** + * Forget all logged records + */ + public static function resetStatic(): void + { + static::$records = []; + } + + /** + * Wrapper for register_shutdown_function to allow overriding + */ + protected function registerShutdownFunction(): void + { + if (PHP_SAPI !== 'cli') { + register_shutdown_function(['Monolog\Handler\BrowserConsoleHandler', 'send']); + } + } + + /** + * Wrapper for echo to allow overriding + */ + protected static function writeOutput(string $str): void + { + echo $str; + } + + /** + * Checks the format of the response + * + * If Content-Type is set to application/javascript or text/javascript -> js + * If Content-Type is set to text/html, or is unset -> html + * If Content-Type is anything else -> unknown + * + * @return string One of 'js', 'html' or 'unknown' + * @phpstan-return self::FORMAT_* + */ + protected static function getResponseFormat(): string + { + // Check content type + foreach (headers_list() as $header) { + if (stripos($header, 'content-type:') === 0) { + return static::getResponseFormatFromContentType($header); + } + } + + return self::FORMAT_HTML; + } + + /** + * @return string One of 'js', 'html' or 'unknown' + * @phpstan-return self::FORMAT_* + */ + protected static function getResponseFormatFromContentType(string $contentType): string + { + // This handler only works with HTML and javascript outputs + // text/javascript is obsolete in favour of application/javascript, but still used + if (stripos($contentType, 'application/javascript') !== false || stripos($contentType, 'text/javascript') !== false) { + return self::FORMAT_JS; + } + + if (stripos($contentType, 'text/html') !== false) { + return self::FORMAT_HTML; + } + + return self::FORMAT_UNKNOWN; + } + + private static function generateScript(): string + { + $script = []; + foreach (static::$records as $record) { + $context = static::dump('Context', $record['context']); + $extra = static::dump('Extra', $record['extra']); + + if (empty($context) && empty($extra)) { + $script[] = static::call_array(static::getConsoleMethodForLevel($record['level']), static::handleStyles($record['formatted'])); + } else { + $script = array_merge( + $script, + [static::call_array('groupCollapsed', static::handleStyles($record['formatted']))], + $context, + $extra, + [static::call('groupEnd')] + ); + } + } + + return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);"; + } + + private static function getConsoleMethodForLevel(int $level): string + { + return [ + Logger::DEBUG => 'debug', + Logger::INFO => 'info', + Logger::NOTICE => 'info', + Logger::WARNING => 'warn', + Logger::ERROR => 'error', + Logger::CRITICAL => 'error', + Logger::ALERT => 'error', + Logger::EMERGENCY => 'error', + ][$level] ?? 'log'; + } + + /** + * @return string[] + */ + private static function handleStyles(string $formatted): array + { + $args = []; + $format = '%c' . $formatted; + preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); + + foreach (array_reverse($matches) as $match) { + $args[] = '"font-weight: normal"'; + $args[] = static::quote(static::handleCustomStyles($match[2][0], $match[1][0])); + + $pos = $match[0][1]; + $format = Utils::substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . Utils::substr($format, $pos + strlen($match[0][0])); + } + + $args[] = static::quote('font-weight: normal'); + $args[] = static::quote($format); + + return array_reverse($args); + } + + private static function handleCustomStyles(string $style, string $string): string + { + static $colors = ['blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey']; + static $labels = []; + + $style = preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function (array $m) use ($string, &$colors, &$labels) { + if (trim($m[1]) === 'autolabel') { + // Format the string as a label with consistent auto assigned background color + if (!isset($labels[$string])) { + $labels[$string] = $colors[count($labels) % count($colors)]; + } + $color = $labels[$string]; + + return "background-color: $color; color: white; border-radius: 3px; padding: 0 2px 0 2px"; + } + + return $m[1]; + }, $style); + + if (null === $style) { + $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to run preg_replace_callback: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + } + + return $style; + } + + /** + * @param mixed[] $dict + * @return mixed[] + */ + private static function dump(string $title, array $dict): array + { + $script = []; + $dict = array_filter($dict); + if (empty($dict)) { + return $script; + } + $script[] = static::call('log', static::quote('%c%s'), static::quote('font-weight: bold'), static::quote($title)); + foreach ($dict as $key => $value) { + $value = json_encode($value); + if (empty($value)) { + $value = static::quote(''); + } + $script[] = static::call('log', static::quote('%s: %o'), static::quote((string) $key), $value); + } + + return $script; + } + + private static function quote(string $arg): string + { + return '"' . addcslashes($arg, "\"\n\\") . '"'; + } + + /** + * @param mixed $args + */ + private static function call(...$args): string + { + $method = array_shift($args); + if (!is_string($method)) { + throw new \UnexpectedValueException('Expected the first arg to be a string, got: '.var_export($method, true)); + } + + return static::call_array($method, $args); + } + + /** + * @param mixed[] $args + */ + private static function call_array(string $method, array $args): string + { + return 'c.' . $method . '(' . implode(', ', $args) . ');'; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php new file mode 100644 index 0000000..fcce5d6 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php @@ -0,0 +1,167 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; + +/** + * Buffers all records until closing the handler and then pass them as batch. + * + * This is useful for a MailHandler to send only one mail per request instead of + * sending one per log message. + * + * @author Christophe Coevoet <stof@notk.org> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class BufferHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** @var HandlerInterface */ + protected $handler; + /** @var int */ + protected $bufferSize = 0; + /** @var int */ + protected $bufferLimit; + /** @var bool */ + protected $flushOnOverflow; + /** @var Record[] */ + protected $buffer = []; + /** @var bool */ + protected $initialized = false; + + /** + * @param HandlerInterface $handler Handler. + * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded + */ + public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, bool $flushOnOverflow = false) + { + parent::__construct($level, $bubble); + $this->handler = $handler; + $this->bufferLimit = $bufferLimit; + $this->flushOnOverflow = $flushOnOverflow; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if ($record['level'] < $this->level) { + return false; + } + + if (!$this->initialized) { + // __destructor() doesn't get called on Fatal errors + register_shutdown_function([$this, 'close']); + $this->initialized = true; + } + + if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) { + if ($this->flushOnOverflow) { + $this->flush(); + } else { + array_shift($this->buffer); + $this->bufferSize--; + } + } + + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + $this->buffer[] = $record; + $this->bufferSize++; + + return false === $this->bubble; + } + + public function flush(): void + { + if ($this->bufferSize === 0) { + return; + } + + $this->handler->handleBatch($this->buffer); + $this->clear(); + } + + public function __destruct() + { + // suppress the parent behavior since we already have register_shutdown_function() + // to call close(), and the reference contained there will prevent this from being + // GC'd until the end of the request + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + $this->flush(); + + $this->handler->close(); + } + + /** + * Clears the buffer without flushing any messages down to the wrapped handler. + */ + public function clear(): void + { + $this->bufferSize = 0; + $this->buffer = []; + } + + public function reset() + { + $this->flush(); + + parent::reset(); + + $this->resetProcessors(); + + if ($this->handler instanceof ResettableInterface) { + $this->handler->reset(); + } + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + $this->handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + return $this->handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php new file mode 100644 index 0000000..234ecf6 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php @@ -0,0 +1,196 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\ChromePHPFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Utils; + +/** + * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/) + * + * This also works out of the box with Firefox 43+ + * + * @author Christophe Coevoet <stof@notk.org> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class ChromePHPHandler extends AbstractProcessingHandler +{ + use WebRequestRecognizerTrait; + + /** + * Version of the extension + */ + protected const VERSION = '4.0'; + + /** + * Header name + */ + protected const HEADER_NAME = 'X-ChromeLogger-Data'; + + /** + * Regular expression to detect supported browsers (matches any Chrome, or Firefox 43+) + */ + protected const USER_AGENT_REGEX = '{\b(?:Chrome/\d+(?:\.\d+)*|HeadlessChrome|Firefox/(?:4[3-9]|[5-9]\d|\d{3,})(?:\.\d)*)\b}'; + + /** @var bool */ + protected static $initialized = false; + + /** + * Tracks whether we sent too much data + * + * Chrome limits the headers to 4KB, so when we sent 3KB we stop sending + * + * @var bool + */ + protected static $overflowed = false; + + /** @var mixed[] */ + protected static $json = [ + 'version' => self::VERSION, + 'columns' => ['label', 'log', 'backtrace', 'type'], + 'rows' => [], + ]; + + /** @var bool */ + protected static $sendHeaders = true; + + public function __construct($level = Logger::DEBUG, bool $bubble = true) + { + parent::__construct($level, $bubble); + if (!function_exists('json_encode')) { + throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s ChromePHPHandler'); + } + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + if (!$this->isWebRequest()) { + return; + } + + $messages = []; + + foreach ($records as $record) { + if ($record['level'] < $this->level) { + continue; + } + /** @var Record $message */ + $message = $this->processRecord($record); + $messages[] = $message; + } + + if (!empty($messages)) { + $messages = $this->getFormatter()->formatBatch($messages); + self::$json['rows'] = array_merge(self::$json['rows'], $messages); + $this->send(); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ChromePHPFormatter(); + } + + /** + * Creates & sends header for a record + * + * @see sendHeader() + * @see send() + */ + protected function write(array $record): void + { + if (!$this->isWebRequest()) { + return; + } + + self::$json['rows'][] = $record['formatted']; + + $this->send(); + } + + /** + * Sends the log header + * + * @see sendHeader() + */ + protected function send(): void + { + if (self::$overflowed || !self::$sendHeaders) { + return; + } + + if (!self::$initialized) { + self::$initialized = true; + + self::$sendHeaders = $this->headersAccepted(); + if (!self::$sendHeaders) { + return; + } + + self::$json['request_uri'] = $_SERVER['REQUEST_URI'] ?? ''; + } + + $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); + $data = base64_encode($json); + if (strlen($data) > 3 * 1024) { + self::$overflowed = true; + + $record = [ + 'message' => 'Incomplete logs, chrome header size limit reached', + 'context' => [], + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'monolog', + 'datetime' => new \DateTimeImmutable(), + 'extra' => [], + ]; + self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record); + $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); + $data = base64_encode($json); + } + + if (trim($data) !== '') { + $this->sendHeader(static::HEADER_NAME, $data); + } + } + + /** + * Send header string to the client + */ + protected function sendHeader(string $header, string $content): void + { + if (!headers_sent() && self::$sendHeaders) { + header(sprintf('%s: %s', $header, $content)); + } + } + + /** + * Verifies if the headers are accepted by the current user agent + */ + protected function headersAccepted(): bool + { + if (empty($_SERVER['HTTP_USER_AGENT'])) { + return false; + } + + return preg_match(static::USER_AGENT_REGEX, $_SERVER['HTTP_USER_AGENT']) === 1; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php new file mode 100644 index 0000000..5265761 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php @@ -0,0 +1,77 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\JsonFormatter; +use Monolog\Logger; + +/** + * CouchDB handler + * + * @author Markus Bachmann <markus.bachmann@bachi.biz> + */ +class CouchDBHandler extends AbstractProcessingHandler +{ + /** @var mixed[] */ + private $options; + + /** + * @param mixed[] $options + */ + public function __construct(array $options = [], $level = Logger::DEBUG, bool $bubble = true) + { + $this->options = array_merge([ + 'host' => 'localhost', + 'port' => 5984, + 'dbname' => 'logger', + 'username' => null, + 'password' => null, + ], $options); + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $basicAuth = null; + if ($this->options['username']) { + $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']); + } + + $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname']; + $context = stream_context_create([ + 'http' => [ + 'method' => 'POST', + 'content' => $record['formatted'], + 'ignore_errors' => true, + 'max_redirects' => 0, + 'header' => 'Content-type: application/json', + ], + ]); + + if (false === @file_get_contents($url, false, $context)) { + throw new \RuntimeException(sprintf('Could not connect to %s', $url)); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php new file mode 100644 index 0000000..3535a4f --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php @@ -0,0 +1,167 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; + +/** + * Logs to Cube. + * + * @link https://github.com/square/cube/wiki + * @author Wan Chen <kami@kamisama.me> + * @deprecated Since 2.8.0 and 3.2.0, Cube appears abandoned and thus we will drop this handler in Monolog 4 + */ +class CubeHandler extends AbstractProcessingHandler +{ + /** @var resource|\Socket|null */ + private $udpConnection = null; + /** @var resource|\CurlHandle|null */ + private $httpConnection = null; + /** @var string */ + private $scheme; + /** @var string */ + private $host; + /** @var int */ + private $port; + /** @var string[] */ + private $acceptedSchemes = ['http', 'udp']; + + /** + * Create a Cube handler + * + * @throws \UnexpectedValueException when given url is not a valid url. + * A valid url must consist of three parts : protocol://host:port + * Only valid protocols used by Cube are http and udp + */ + public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = true) + { + $urlInfo = parse_url($url); + + if ($urlInfo === false || !isset($urlInfo['scheme'], $urlInfo['host'], $urlInfo['port'])) { + throw new \UnexpectedValueException('URL "'.$url.'" is not valid'); + } + + if (!in_array($urlInfo['scheme'], $this->acceptedSchemes)) { + throw new \UnexpectedValueException( + 'Invalid protocol (' . $urlInfo['scheme'] . ').' + . ' Valid options are ' . implode(', ', $this->acceptedSchemes) + ); + } + + $this->scheme = $urlInfo['scheme']; + $this->host = $urlInfo['host']; + $this->port = (int) $urlInfo['port']; + + parent::__construct($level, $bubble); + } + + /** + * Establish a connection to an UDP socket + * + * @throws \LogicException when unable to connect to the socket + * @throws MissingExtensionException when there is no socket extension + */ + protected function connectUdp(): void + { + if (!extension_loaded('sockets')) { + throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler'); + } + + $udpConnection = socket_create(AF_INET, SOCK_DGRAM, 0); + if (false === $udpConnection) { + throw new \LogicException('Unable to create a socket'); + } + + $this->udpConnection = $udpConnection; + if (!socket_connect($this->udpConnection, $this->host, $this->port)) { + throw new \LogicException('Unable to connect to the socket at ' . $this->host . ':' . $this->port); + } + } + + /** + * Establish a connection to an http server + * + * @throws \LogicException when unable to connect to the socket + * @throws MissingExtensionException when no curl extension + */ + protected function connectHttp(): void + { + if (!extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is required to use http URLs with the CubeHandler'); + } + + $httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put'); + if (false === $httpConnection) { + throw new \LogicException('Unable to connect to ' . $this->host . ':' . $this->port); + } + + $this->httpConnection = $httpConnection; + curl_setopt($this->httpConnection, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($this->httpConnection, CURLOPT_RETURNTRANSFER, true); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $date = $record['datetime']; + + $data = ['time' => $date->format('Y-m-d\TH:i:s.uO')]; + unset($record['datetime']); + + if (isset($record['context']['type'])) { + $data['type'] = $record['context']['type']; + unset($record['context']['type']); + } else { + $data['type'] = $record['channel']; + } + + $data['data'] = $record['context']; + $data['data']['level'] = $record['level']; + + if ($this->scheme === 'http') { + $this->writeHttp(Utils::jsonEncode($data)); + } else { + $this->writeUdp(Utils::jsonEncode($data)); + } + } + + private function writeUdp(string $data): void + { + if (!$this->udpConnection) { + $this->connectUdp(); + } + + socket_send($this->udpConnection, $data, strlen($data), 0); + } + + private function writeHttp(string $data): void + { + if (!$this->httpConnection) { + $this->connectHttp(); + } + + if (null === $this->httpConnection) { + throw new \LogicException('No connection could be established'); + } + + curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']'); + curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json', + 'Content-Length: ' . strlen('['.$data.']'), + ]); + + Curl\Util::execute($this->httpConnection, 5, false); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php new file mode 100644 index 0000000..7213e8e --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php @@ -0,0 +1,71 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Curl; + +use CurlHandle; + +/** + * This class is marked as internal and it is not under the BC promise of the package. + * + * @internal + */ +final class Util +{ + /** @var array<int> */ + private static $retriableErrorCodes = [ + CURLE_COULDNT_RESOLVE_HOST, + CURLE_COULDNT_CONNECT, + CURLE_HTTP_NOT_FOUND, + CURLE_READ_ERROR, + CURLE_OPERATION_TIMEOUTED, + CURLE_HTTP_POST_ERROR, + CURLE_SSL_CONNECT_ERROR, + ]; + + /** + * Executes a CURL request with optional retries and exception on failure + * + * @param resource|CurlHandle $ch curl handler + * @param int $retries + * @param bool $closeAfterDone + * @return bool|string @see curl_exec + */ + public static function execute($ch, int $retries = 5, bool $closeAfterDone = true) + { + while ($retries--) { + $curlResponse = curl_exec($ch); + if ($curlResponse === false) { + $curlErrno = curl_errno($ch); + + if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) { + $curlError = curl_error($ch); + + if ($closeAfterDone) { + curl_close($ch); + } + + throw new \RuntimeException(sprintf('Curl error (code %d): %s', $curlErrno, $curlError)); + } + + continue; + } + + if ($closeAfterDone) { + curl_close($ch); + } + + return $curlResponse; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php new file mode 100644 index 0000000..9b85ae7 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php @@ -0,0 +1,186 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Simple handler wrapper that deduplicates log records across multiple requests + * + * It also includes the BufferHandler functionality and will buffer + * all messages until the end of the request or flush() is called. + * + * This works by storing all log records' messages above $deduplicationLevel + * to the file specified by $deduplicationStore. When further logs come in at the end of the + * request (or when flush() is called), all those above $deduplicationLevel are checked + * against the existing stored logs. If they match and the timestamps in the stored log is + * not older than $time seconds, the new log record is discarded. If no log record is new, the + * whole data set is discarded. + * + * This is mainly useful in combination with Mail handlers or things like Slack or HipChat handlers + * that send messages to people, to avoid spamming with the same message over and over in case of + * a major component failure like a database server being down which makes all requests fail in the + * same way. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + */ +class DeduplicationHandler extends BufferHandler +{ + /** + * @var string + */ + protected $deduplicationStore; + + /** + * @var Level + */ + protected $deduplicationLevel; + + /** + * @var int + */ + protected $time; + + /** + * @var bool + */ + private $gc = false; + + /** + * @param HandlerInterface $handler Handler. + * @param string $deduplicationStore The file/path where the deduplication log should be kept + * @param string|int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes + * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @phpstan-param Level|LevelName|LogLevel::* $deduplicationLevel + */ + public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, int $time = 60, bool $bubble = true) + { + parent::__construct($handler, 0, Logger::DEBUG, $bubble, false); + + $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore; + $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel); + $this->time = $time; + } + + public function flush(): void + { + if ($this->bufferSize === 0) { + return; + } + + $passthru = null; + + foreach ($this->buffer as $record) { + if ($record['level'] >= $this->deduplicationLevel) { + $passthru = $passthru || !$this->isDuplicate($record); + if ($passthru) { + $this->appendRecord($record); + } + } + } + + // default of null is valid as well as if no record matches duplicationLevel we just pass through + if ($passthru === true || $passthru === null) { + $this->handler->handleBatch($this->buffer); + } + + $this->clear(); + + if ($this->gc) { + $this->collectLogs(); + } + } + + /** + * @phpstan-param Record $record + */ + private function isDuplicate(array $record): bool + { + if (!file_exists($this->deduplicationStore)) { + return false; + } + + $store = file($this->deduplicationStore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + if (!is_array($store)) { + return false; + } + + $yesterday = time() - 86400; + $timestampValidity = $record['datetime']->getTimestamp() - $this->time; + $expectedMessage = preg_replace('{[\r\n].*}', '', $record['message']); + + for ($i = count($store) - 1; $i >= 0; $i--) { + list($timestamp, $level, $message) = explode(':', $store[$i], 3); + + if ($level === $record['level_name'] && $message === $expectedMessage && $timestamp > $timestampValidity) { + return true; + } + + if ($timestamp < $yesterday) { + $this->gc = true; + } + } + + return false; + } + + private function collectLogs(): void + { + if (!file_exists($this->deduplicationStore)) { + return; + } + + $handle = fopen($this->deduplicationStore, 'rw+'); + + if (!$handle) { + throw new \RuntimeException('Failed to open file for reading and writing: ' . $this->deduplicationStore); + } + + flock($handle, LOCK_EX); + $validLogs = []; + + $timestampValidity = time() - $this->time; + + while (!feof($handle)) { + $log = fgets($handle); + if ($log && substr($log, 0, 10) >= $timestampValidity) { + $validLogs[] = $log; + } + } + + ftruncate($handle, 0); + rewind($handle); + foreach ($validLogs as $log) { + fwrite($handle, $log); + } + + flock($handle, LOCK_UN); + fclose($handle); + + $this->gc = false; + } + + /** + * @phpstan-param Record $record + */ + private function appendRecord(array $record): void + { + file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php new file mode 100644 index 0000000..ebd52c3 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; +use Doctrine\CouchDB\CouchDBClient; + +/** + * CouchDB handler for Doctrine CouchDB ODM + * + * @author Markus Bachmann <markus.bachmann@bachi.biz> + */ +class DoctrineCouchDBHandler extends AbstractProcessingHandler +{ + /** @var CouchDBClient */ + private $client; + + public function __construct(CouchDBClient $client, $level = Logger::DEBUG, bool $bubble = true) + { + $this->client = $client; + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->client->postDocument($record['formatted']); + } + + protected function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php new file mode 100644 index 0000000..21840bf --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php @@ -0,0 +1,104 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Aws\Sdk; +use Aws\DynamoDb\DynamoDbClient; +use Monolog\Formatter\FormatterInterface; +use Aws\DynamoDb\Marshaler; +use Monolog\Formatter\ScalarFormatter; +use Monolog\Logger; + +/** + * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/) + * + * @link https://github.com/aws/aws-sdk-php/ + * @author Andrew Lawson <adlawson@gmail.com> + */ +class DynamoDbHandler extends AbstractProcessingHandler +{ + public const DATE_FORMAT = 'Y-m-d\TH:i:s.uO'; + + /** + * @var DynamoDbClient + */ + protected $client; + + /** + * @var string + */ + protected $table; + + /** + * @var int + */ + protected $version; + + /** + * @var Marshaler + */ + protected $marshaler; + + public function __construct(DynamoDbClient $client, string $table, $level = Logger::DEBUG, bool $bubble = true) + { + /** @phpstan-ignore-next-line */ + if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) { + $this->version = 3; + $this->marshaler = new Marshaler; + } else { + $this->version = 2; + } + + $this->client = $client; + $this->table = $table; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $filtered = $this->filterEmptyFields($record['formatted']); + if ($this->version === 3) { + $formatted = $this->marshaler->marshalItem($filtered); + } else { + /** @phpstan-ignore-next-line */ + $formatted = $this->client->formatAttributes($filtered); + } + + $this->client->putItem([ + 'TableName' => $this->table, + 'Item' => $formatted, + ]); + } + + /** + * @param mixed[] $record + * @return mixed[] + */ + protected function filterEmptyFields(array $record): array + { + return array_filter($record, function ($value) { + return !empty($value) || false === $value || 0 === $value; + }); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ScalarFormatter(self::DATE_FORMAT); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php new file mode 100644 index 0000000..fc92ca4 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php @@ -0,0 +1,129 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Elastica\Document; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\ElasticaFormatter; +use Monolog\Logger; +use Elastica\Client; +use Elastica\Exception\ExceptionInterface; + +/** + * Elastic Search handler + * + * Usage example: + * + * $client = new \Elastica\Client(); + * $options = array( + * 'index' => 'elastic_index_name', + * 'type' => 'elastic_doc_type', Types have been removed in Elastica 7 + * ); + * $handler = new ElasticaHandler($client, $options); + * $log = new Logger('application'); + * $log->pushHandler($handler); + * + * @author Jelle Vink <jelle.vink@gmail.com> + */ +class ElasticaHandler extends AbstractProcessingHandler +{ + /** + * @var Client + */ + protected $client; + + /** + * @var mixed[] Handler config options + */ + protected $options = []; + + /** + * @param Client $client Elastica Client object + * @param mixed[] $options Handler configuration + */ + public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) + { + parent::__construct($level, $bubble); + $this->client = $client; + $this->options = array_merge( + [ + 'index' => 'monolog', // Elastic index name + 'type' => 'record', // Elastic document type + 'ignore_error' => false, // Suppress Elastica exceptions + ], + $options + ); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->bulkSend([$record['formatted']]); + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($formatter instanceof ElasticaFormatter) { + return parent::setFormatter($formatter); + } + + throw new \InvalidArgumentException('ElasticaHandler is only compatible with ElasticaFormatter'); + } + + /** + * @return mixed[] + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ElasticaFormatter($this->options['index'], $this->options['type']); + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + $documents = $this->getFormatter()->formatBatch($records); + $this->bulkSend($documents); + } + + /** + * Use Elasticsearch bulk API to send list of documents + * + * @param Document[] $documents + * + * @throws \RuntimeException + */ + protected function bulkSend(array $documents): void + { + try { + $this->client->addDocuments($documents); + } catch (ExceptionInterface $e) { + if (!$this->options['ignore_error']) { + throw new \RuntimeException("Error sending messages to Elasticsearch", 0, $e); + } + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php new file mode 100644 index 0000000..e88375c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php @@ -0,0 +1,218 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Elastic\Elasticsearch\Response\Elasticsearch; +use Throwable; +use RuntimeException; +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\ElasticsearchFormatter; +use InvalidArgumentException; +use Elasticsearch\Common\Exceptions\RuntimeException as ElasticsearchRuntimeException; +use Elasticsearch\Client; +use Elastic\Elasticsearch\Exception\InvalidArgumentException as ElasticInvalidArgumentException; +use Elastic\Elasticsearch\Client as Client8; + +/** + * Elasticsearch handler + * + * @link https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html + * + * Simple usage example: + * + * $client = \Elasticsearch\ClientBuilder::create() + * ->setHosts($hosts) + * ->build(); + * + * $options = array( + * 'index' => 'elastic_index_name', + * 'type' => 'elastic_doc_type', + * ); + * $handler = new ElasticsearchHandler($client, $options); + * $log = new Logger('application'); + * $log->pushHandler($handler); + * + * @author Avtandil Kikabidze <akalongman@gmail.com> + */ +class ElasticsearchHandler extends AbstractProcessingHandler +{ + /** + * @var Client|Client8 + */ + protected $client; + + /** + * @var mixed[] Handler config options + */ + protected $options = []; + + /** + * @var bool + */ + private $needsType; + + /** + * @param Client|Client8 $client Elasticsearch Client object + * @param mixed[] $options Handler configuration + */ + public function __construct($client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) + { + if (!$client instanceof Client && !$client instanceof Client8) { + throw new \TypeError('Elasticsearch\Client or Elastic\Elasticsearch\Client instance required'); + } + + parent::__construct($level, $bubble); + $this->client = $client; + $this->options = array_merge( + [ + 'index' => 'monolog', // Elastic index name + 'type' => '_doc', // Elastic document type + 'ignore_error' => false, // Suppress Elasticsearch exceptions + ], + $options + ); + + if ($client instanceof Client8 || $client::VERSION[0] === '7') { + $this->needsType = false; + // force the type to _doc for ES8/ES7 + $this->options['type'] = '_doc'; + } else { + $this->needsType = true; + } + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->bulkSend([$record['formatted']]); + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($formatter instanceof ElasticsearchFormatter) { + return parent::setFormatter($formatter); + } + + throw new InvalidArgumentException('ElasticsearchHandler is only compatible with ElasticsearchFormatter'); + } + + /** + * Getter options + * + * @return mixed[] + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ElasticsearchFormatter($this->options['index'], $this->options['type']); + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + $documents = $this->getFormatter()->formatBatch($records); + $this->bulkSend($documents); + } + + /** + * Use Elasticsearch bulk API to send list of documents + * + * @param array[] $records Records + _index/_type keys + * @throws \RuntimeException + */ + protected function bulkSend(array $records): void + { + try { + $params = [ + 'body' => [], + ]; + + foreach ($records as $record) { + $params['body'][] = [ + 'index' => $this->needsType ? [ + '_index' => $record['_index'], + '_type' => $record['_type'], + ] : [ + '_index' => $record['_index'], + ], + ]; + unset($record['_index'], $record['_type']); + + $params['body'][] = $record; + } + + /** @var Elasticsearch */ + $responses = $this->client->bulk($params); + + if ($responses['errors'] === true) { + throw $this->createExceptionFromResponses($responses); + } + } catch (Throwable $e) { + if (! $this->options['ignore_error']) { + throw new RuntimeException('Error sending messages to Elasticsearch', 0, $e); + } + } + } + + /** + * Creates elasticsearch exception from responses array + * + * Only the first error is converted into an exception. + * + * @param mixed[]|Elasticsearch $responses returned by $this->client->bulk() + */ + protected function createExceptionFromResponses($responses): Throwable + { + foreach ($responses['items'] ?? [] as $item) { + if (isset($item['index']['error'])) { + return $this->createExceptionFromError($item['index']['error']); + } + } + + if (class_exists(ElasticInvalidArgumentException::class)) { + return new ElasticInvalidArgumentException('Elasticsearch failed to index one or more records.'); + } + + return new ElasticsearchRuntimeException('Elasticsearch failed to index one or more records.'); + } + + /** + * Creates elasticsearch exception from error array + * + * @param mixed[] $error + */ + protected function createExceptionFromError(array $error): Throwable + { + $previous = isset($error['caused_by']) ? $this->createExceptionFromError($error['caused_by']) : null; + + if (class_exists(ElasticInvalidArgumentException::class)) { + return new ElasticInvalidArgumentException($error['type'] . ': ' . $error['reason'], 0, $previous); + } + + return new ElasticsearchRuntimeException($error['type'] . ': ' . $error['reason'], 0, $previous); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php new file mode 100644 index 0000000..f2e2203 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php @@ -0,0 +1,91 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Utils; + +/** + * Stores to PHP error_log() handler. + * + * @author Elan Ruusamäe <glen@delfi.ee> + */ +class ErrorLogHandler extends AbstractProcessingHandler +{ + public const OPERATING_SYSTEM = 0; + public const SAPI = 4; + + /** @var int */ + protected $messageType; + /** @var bool */ + protected $expandNewlines; + + /** + * @param int $messageType Says where the error should go. + * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries + */ + public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, bool $expandNewlines = false) + { + parent::__construct($level, $bubble); + + if (false === in_array($messageType, self::getAvailableTypes(), true)) { + $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true)); + + throw new \InvalidArgumentException($message); + } + + $this->messageType = $messageType; + $this->expandNewlines = $expandNewlines; + } + + /** + * @return int[] With all available types + */ + public static function getAvailableTypes(): array + { + return [ + self::OPERATING_SYSTEM, + self::SAPI, + ]; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%'); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if (!$this->expandNewlines) { + error_log((string) $record['formatted'], $this->messageType); + + return; + } + + $lines = preg_split('{[\r\n]+}', (string) $record['formatted']); + if ($lines === false) { + $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to preg_split formatted string: ' . $pcreErrorCode . ' / '. Utils::pcreLastErrorMessage($pcreErrorCode)); + } + foreach ($lines as $line) { + error_log($line, $this->messageType); + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php new file mode 100644 index 0000000..d4e234c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php @@ -0,0 +1,71 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Throwable; + +/** + * Forwards records to at most one handler + * + * If a handler fails, the exception is suppressed and the record is forwarded to the next handler. + * + * As soon as one handler handles a record successfully, the handling stops there. + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class FallbackGroupHandler extends GroupHandler +{ + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + foreach ($this->handlers as $handler) { + try { + $handler->handle($record); + break; + } catch (Throwable $e) { + // What throwable? + } + } + + return false === $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + if ($this->processors) { + $processed = []; + foreach ($records as $record) { + $processed[] = $this->processRecord($record); + } + /** @var Record[] $records */ + $records = $processed; + } + + foreach ($this->handlers as $handler) { + try { + $handler->handleBatch($records); + break; + } catch (Throwable $e) { + // What throwable? + } + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php new file mode 100644 index 0000000..718f17e --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php @@ -0,0 +1,212 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; + +/** + * Simple handler wrapper that filters records based on a list of levels + * + * It can be configured with an exact list of levels to allow, or a min/max level. + * + * @author Hennadiy Verkh + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class FilterHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * Handler or factory callable($record, $this) + * + * @var callable|HandlerInterface + * @phpstan-var callable(?Record, HandlerInterface): HandlerInterface|HandlerInterface + */ + protected $handler; + + /** + * Minimum level for logs that are passed to handler + * + * @var int[] + * @phpstan-var array<Level, int> + */ + protected $acceptedLevels; + + /** + * Whether the messages that are handled can bubble up the stack or not + * + * @var bool + */ + protected $bubble; + + /** + * @psalm-param HandlerInterface|callable(?Record, HandlerInterface): HandlerInterface $handler + * + * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $filterHandler). + * @param int|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided + * @param int|string $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @phpstan-param Level|LevelName|LogLevel::*|array<Level|LevelName|LogLevel::*> $minLevelOrList + * @phpstan-param Level|LevelName|LogLevel::* $maxLevel + */ + public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, bool $bubble = true) + { + $this->handler = $handler; + $this->bubble = $bubble; + $this->setAcceptedLevels($minLevelOrList, $maxLevel); + + if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { + throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); + } + } + + /** + * @phpstan-return array<int, Level> + */ + public function getAcceptedLevels(): array + { + return array_flip($this->acceptedLevels); + } + + /** + * @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided + * @param int|string $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array + * + * @phpstan-param Level|LevelName|LogLevel::*|array<Level|LevelName|LogLevel::*> $minLevelOrList + * @phpstan-param Level|LevelName|LogLevel::* $maxLevel + */ + public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY): self + { + if (is_array($minLevelOrList)) { + $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); + } else { + $minLevelOrList = Logger::toMonologLevel($minLevelOrList); + $maxLevel = Logger::toMonologLevel($maxLevel); + $acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) { + return $level >= $minLevelOrList && $level <= $maxLevel; + })); + } + $this->acceptedLevels = array_flip($acceptedLevels); + + return $this; + } + + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + return isset($this->acceptedLevels[$record['level']]); + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + $this->getHandler($record)->handle($record); + + return false === $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + $filtered = []; + foreach ($records as $record) { + if ($this->isHandling($record)) { + $filtered[] = $record; + } + } + + if (count($filtered) > 0) { + $this->getHandler($filtered[count($filtered) - 1])->handleBatch($filtered); + } + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory callable, this will trigger the handler's instantiation. + * + * @return HandlerInterface + * + * @phpstan-param Record $record + */ + public function getHandler(array $record = null) + { + if (!$this->handler instanceof HandlerInterface) { + $this->handler = ($this->handler)($record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); + } + } + + return $this->handler; + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); + } + + public function reset() + { + $this->resetProcessors(); + + if ($this->getHandler() instanceof ResettableInterface) { + $this->getHandler()->reset(); + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php new file mode 100644 index 0000000..0aa5607 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +/** + * Interface for activation strategies for the FingersCrossedHandler. + * + * @author Johannes M. Schmitt <schmittjoh@gmail.com> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +interface ActivationStrategyInterface +{ + /** + * Returns whether the given record activates the handler. + * + * @phpstan-param Record $record + */ + public function isHandlerActivated(array $record): bool; +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php new file mode 100644 index 0000000..7b9abb5 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php @@ -0,0 +1,77 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Channel and Error level based monolog activation strategy. Allows to trigger activation + * based on level per channel. e.g. trigger activation on level 'ERROR' by default, except + * for records of the 'sql' channel; those should trigger activation on level 'WARN'. + * + * Example: + * + * <code> + * $activationStrategy = new ChannelLevelActivationStrategy( + * Logger::CRITICAL, + * array( + * 'request' => Logger::ALERT, + * 'sensitive' => Logger::ERROR, + * ) + * ); + * $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy); + * </code> + * + * @author Mike Meessen <netmikey@gmail.com> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class ChannelLevelActivationStrategy implements ActivationStrategyInterface +{ + /** + * @var Level + */ + private $defaultActionLevel; + + /** + * @var array<string, Level> + */ + private $channelToActionLevel; + + /** + * @param int|string $defaultActionLevel The default action level to be used if the record's category doesn't match any + * @param array<string, int> $channelToActionLevel An array that maps channel names to action levels. + * + * @phpstan-param array<string, Level> $channelToActionLevel + * @phpstan-param Level|LevelName|LogLevel::* $defaultActionLevel + */ + public function __construct($defaultActionLevel, array $channelToActionLevel = []) + { + $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); + $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel); + } + + /** + * @phpstan-param Record $record + */ + public function isHandlerActivated(array $record): bool + { + if (isset($this->channelToActionLevel[$record['channel']])) { + return $record['level'] >= $this->channelToActionLevel[$record['channel']]; + } + + return $record['level'] >= $this->defaultActionLevel; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php new file mode 100644 index 0000000..5ec88ea --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php @@ -0,0 +1,46 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Error level based activation strategy. + * + * @author Johannes M. Schmitt <schmittjoh@gmail.com> + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class ErrorLevelActivationStrategy implements ActivationStrategyInterface +{ + /** + * @var Level + */ + private $actionLevel; + + /** + * @param int|string $actionLevel Level or name or value + * + * @phpstan-param Level|LevelName|LogLevel::* $actionLevel + */ + public function __construct($actionLevel) + { + $this->actionLevel = Logger::toMonologLevel($actionLevel); + } + + public function isHandlerActivated(array $record): bool + { + return $record['level'] >= $this->actionLevel; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php new file mode 100644 index 0000000..0627b44 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php @@ -0,0 +1,252 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; +use Monolog\Handler\FingersCrossed\ActivationStrategyInterface; +use Monolog\Logger; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; + +/** + * Buffers all records until a certain level is reached + * + * The advantage of this approach is that you don't get any clutter in your log files. + * Only requests which actually trigger an error (or whatever your actionLevel is) will be + * in the logs, but they will contain all records, not only those above the level threshold. + * + * You can then have a passthruLevel as well which means that at the end of the request, + * even if it did not get activated, it will still send through log records of e.g. at least a + * warning level. + * + * You can find the various activation strategies in the + * Monolog\Handler\FingersCrossed\ namespace. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * @var callable|HandlerInterface + * @phpstan-var callable(?Record, HandlerInterface): HandlerInterface|HandlerInterface + */ + protected $handler; + /** @var ActivationStrategyInterface */ + protected $activationStrategy; + /** @var bool */ + protected $buffering = true; + /** @var int */ + protected $bufferSize; + /** @var Record[] */ + protected $buffer = []; + /** @var bool */ + protected $stopBuffering; + /** + * @var ?int + * @phpstan-var ?Level + */ + protected $passthruLevel; + /** @var bool */ + protected $bubble; + + /** + * @psalm-param HandlerInterface|callable(?Record, HandlerInterface): HandlerInterface $handler + * + * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $fingersCrossedHandler). + * @param int|string|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated + * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true) + * @param int|string $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered + * + * @phpstan-param Level|LevelName|LogLevel::* $passthruLevel + * @phpstan-param Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy + */ + public function __construct($handler, $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, $passthruLevel = null) + { + if (null === $activationStrategy) { + $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); + } + + // convert simple int activationStrategy to an object + if (!$activationStrategy instanceof ActivationStrategyInterface) { + $activationStrategy = new ErrorLevelActivationStrategy($activationStrategy); + } + + $this->handler = $handler; + $this->activationStrategy = $activationStrategy; + $this->bufferSize = $bufferSize; + $this->bubble = $bubble; + $this->stopBuffering = $stopBuffering; + + if ($passthruLevel !== null) { + $this->passthruLevel = Logger::toMonologLevel($passthruLevel); + } + + if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { + throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); + } + } + + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + return true; + } + + /** + * Manually activate this logger regardless of the activation strategy + */ + public function activate(): void + { + if ($this->stopBuffering) { + $this->buffering = false; + } + + $this->getHandler(end($this->buffer) ?: null)->handleBatch($this->buffer); + $this->buffer = []; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + if ($this->buffering) { + $this->buffer[] = $record; + if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) { + array_shift($this->buffer); + } + if ($this->activationStrategy->isHandlerActivated($record)) { + $this->activate(); + } + } else { + $this->getHandler($record)->handle($record); + } + + return false === $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + $this->flushBuffer(); + + $this->getHandler()->close(); + } + + public function reset() + { + $this->flushBuffer(); + + $this->resetProcessors(); + + if ($this->getHandler() instanceof ResettableInterface) { + $this->getHandler()->reset(); + } + } + + /** + * Clears the buffer without flushing any messages down to the wrapped handler. + * + * It also resets the handler to its initial buffering state. + */ + public function clear(): void + { + $this->buffer = []; + $this->reset(); + } + + /** + * Resets the state of the handler. Stops forwarding records to the wrapped handler. + */ + private function flushBuffer(): void + { + if (null !== $this->passthruLevel) { + $level = $this->passthruLevel; + $this->buffer = array_filter($this->buffer, function ($record) use ($level) { + return $record['level'] >= $level; + }); + if (count($this->buffer) > 0) { + $this->getHandler(end($this->buffer))->handleBatch($this->buffer); + } + } + + $this->buffer = []; + $this->buffering = true; + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory callable, this will trigger the handler's instantiation. + * + * @return HandlerInterface + * + * @phpstan-param Record $record + */ + public function getHandler(array $record = null) + { + if (!$this->handler instanceof HandlerInterface) { + $this->handler = ($this->handler)($record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); + } + } + + return $this->handler; + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php new file mode 100644 index 0000000..72718de --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php @@ -0,0 +1,180 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\WildfireFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Simple FirePHP Handler (http://www.firephp.org/), which uses the Wildfire protocol. + * + * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com> + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class FirePHPHandler extends AbstractProcessingHandler +{ + use WebRequestRecognizerTrait; + + /** + * WildFire JSON header message format + */ + protected const PROTOCOL_URI = 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2'; + + /** + * FirePHP structure for parsing messages & their presentation + */ + protected const STRUCTURE_URI = 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1'; + + /** + * Must reference a "known" plugin, otherwise headers won't display in FirePHP + */ + protected const PLUGIN_URI = 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3'; + + /** + * Header prefix for Wildfire to recognize & parse headers + */ + protected const HEADER_PREFIX = 'X-Wf'; + + /** + * Whether or not Wildfire vendor-specific headers have been generated & sent yet + * @var bool + */ + protected static $initialized = false; + + /** + * Shared static message index between potentially multiple handlers + * @var int + */ + protected static $messageIndex = 1; + + /** @var bool */ + protected static $sendHeaders = true; + + /** + * Base header creation function used by init headers & record headers + * + * @param array<int|string> $meta Wildfire Plugin, Protocol & Structure Indexes + * @param string $message Log message + * + * @return array<string, string> Complete header string ready for the client as key and message as value + * + * @phpstan-return non-empty-array<string, string> + */ + protected function createHeader(array $meta, string $message): array + { + $header = sprintf('%s-%s', static::HEADER_PREFIX, join('-', $meta)); + + return [$header => $message]; + } + + /** + * Creates message header from record + * + * @return array<string, string> + * + * @phpstan-return non-empty-array<string, string> + * + * @see createHeader() + * + * @phpstan-param FormattedRecord $record + */ + protected function createRecordHeader(array $record): array + { + // Wildfire is extensible to support multiple protocols & plugins in a single request, + // but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake. + return $this->createHeader( + [1, 1, 1, self::$messageIndex++], + $record['formatted'] + ); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new WildfireFormatter(); + } + + /** + * Wildfire initialization headers to enable message parsing + * + * @see createHeader() + * @see sendHeader() + * + * @return array<string, string> + */ + protected function getInitHeaders(): array + { + // Initial payload consists of required headers for Wildfire + return array_merge( + $this->createHeader(['Protocol', 1], static::PROTOCOL_URI), + $this->createHeader([1, 'Structure', 1], static::STRUCTURE_URI), + $this->createHeader([1, 'Plugin', 1], static::PLUGIN_URI) + ); + } + + /** + * Send header string to the client + */ + protected function sendHeader(string $header, string $content): void + { + if (!headers_sent() && self::$sendHeaders) { + header(sprintf('%s: %s', $header, $content)); + } + } + + /** + * Creates & sends header for a record, ensuring init headers have been sent prior + * + * @see sendHeader() + * @see sendInitHeaders() + */ + protected function write(array $record): void + { + if (!self::$sendHeaders || !$this->isWebRequest()) { + return; + } + + // WildFire-specific headers must be sent prior to any messages + if (!self::$initialized) { + self::$initialized = true; + + self::$sendHeaders = $this->headersAccepted(); + if (!self::$sendHeaders) { + return; + } + + foreach ($this->getInitHeaders() as $header => $content) { + $this->sendHeader($header, $content); + } + } + + $header = $this->createRecordHeader($record); + if (trim(current($header)) !== '') { + $this->sendHeader(key($header), current($header)); + } + } + + /** + * Verifies if the headers are accepted by the current user agent + */ + protected function headersAccepted(): bool + { + if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { + return true; + } + + return isset($_SERVER['HTTP_X_FIREPHP_VERSION']); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php new file mode 100644 index 0000000..85c95b9 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php @@ -0,0 +1,135 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Monolog\Logger; + +/** + * Sends logs to Fleep.io using Webhook integrations + * + * You'll need a Fleep.io account to use this handler. + * + * @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation + * @author Ando Roots <ando@sqroot.eu> + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class FleepHookHandler extends SocketHandler +{ + protected const FLEEP_HOST = 'fleep.io'; + + protected const FLEEP_HOOK_URI = '/hook/'; + + /** + * @var string Webhook token (specifies the conversation where logs are sent) + */ + protected $token; + + /** + * Construct a new Fleep.io Handler. + * + * For instructions on how to create a new web hook in your conversations + * see https://fleep.io/integrations/webhooks/ + * + * @param string $token Webhook token + * @throws MissingExtensionException + */ + public function __construct( + string $token, + $level = Logger::DEBUG, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if (!extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler'); + } + + $this->token = $token; + + $connectionString = 'ssl://' . static::FLEEP_HOST . ':443'; + parent::__construct( + $connectionString, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + } + + /** + * Returns the default formatter to use with this handler + * + * Overloaded to remove empty context and extra arrays from the end of the log message. + * + * @return LineFormatter + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(null, null, true, true); + } + + /** + * Handles a log record + */ + public function write(array $record): void + { + parent::write($record); + $this->closeSocket(); + } + + /** + * {@inheritDoc} + */ + protected function generateDataStream(array $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the header of the API Call + */ + private function buildHeader(string $content): string + { + $header = "POST " . static::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n"; + $header .= "Host: " . static::FLEEP_HOST . "\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * Builds the body of API call + * + * @phpstan-param FormattedRecord $record + */ + private function buildContent(array $record): string + { + $dataArray = [ + 'message' => $record['formatted'], + ]; + + return http_build_query($dataArray); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php new file mode 100644 index 0000000..5715d58 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php @@ -0,0 +1,133 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Formatter\FlowdockFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Sends notifications through the Flowdock push API + * + * This must be configured with a FlowdockFormatter instance via setFormatter() + * + * Notes: + * API token - Flowdock API token + * + * @author Dominik Liebler <liebler.dominik@gmail.com> + * @see https://www.flowdock.com/api/push + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + * @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4 + */ +class FlowdockHandler extends SocketHandler +{ + /** + * @var string + */ + protected $apiToken; + + /** + * @throws MissingExtensionException if OpenSSL is missing + */ + public function __construct( + string $apiToken, + $level = Logger::DEBUG, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if (!extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler'); + } + + parent::__construct( + 'ssl://api.flowdock.com:443', + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + $this->apiToken = $apiToken; + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if (!$formatter instanceof FlowdockFormatter) { + throw new \InvalidArgumentException('The FlowdockHandler requires an instance of Monolog\Formatter\FlowdockFormatter to function correctly'); + } + + return parent::setFormatter($formatter); + } + + /** + * Gets the default formatter. + */ + protected function getDefaultFormatter(): FormatterInterface + { + throw new \InvalidArgumentException('The FlowdockHandler must be configured (via setFormatter) with an instance of Monolog\Formatter\FlowdockFormatter to function correctly'); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + parent::write($record); + + $this->closeSocket(); + } + + /** + * {@inheritDoc} + */ + protected function generateDataStream(array $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + * + * @phpstan-param FormattedRecord $record + */ + private function buildContent(array $record): string + { + return Utils::jsonEncode($record['formatted']['flowdock']); + } + + /** + * Builds the header of the API Call + */ + private function buildHeader(string $content): string + { + $header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n"; + $header .= "Host: api.flowdock.com\r\n"; + $header .= "Content-Type: application/json\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php new file mode 100644 index 0000000..fc1693c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; + +/** + * Interface to describe loggers that have a formatter + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +interface FormattableHandlerInterface +{ + /** + * Sets the formatter. + * + * @param FormatterInterface $formatter + * @return HandlerInterface self + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface; + + /** + * Gets the formatter. + * + * @return FormatterInterface + */ + public function getFormatter(): FormatterInterface; +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php new file mode 100644 index 0000000..b60bdce --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php @@ -0,0 +1,60 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; + +/** + * Helper trait for implementing FormattableInterface + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +trait FormattableHandlerTrait +{ + /** + * @var ?FormatterInterface + */ + protected $formatter; + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $this->formatter = $formatter; + + return $this; + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + if (!$this->formatter) { + $this->formatter = $this->getDefaultFormatter(); + } + + return $this->formatter; + } + + /** + * Gets the default formatter. + * + * Overwrite this if the LineFormatter is not a good default for your handler. + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php new file mode 100644 index 0000000..4ff26c4 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php @@ -0,0 +1,57 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\PublisherInterface; +use Monolog\Logger; +use Monolog\Formatter\GelfMessageFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Handler to send messages to a Graylog2 (http://www.graylog2.org) server + * + * @author Matt Lehner <mlehner@gmail.com> + * @author Benjamin Zikarsky <benjamin@zikarsky.de> + */ +class GelfHandler extends AbstractProcessingHandler +{ + /** + * @var PublisherInterface the publisher object that sends the message to the server + */ + protected $publisher; + + /** + * @param PublisherInterface $publisher a gelf publisher object + */ + public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->publisher = $publisher; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->publisher->publish($record['formatted']); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new GelfMessageFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php new file mode 100644 index 0000000..3c9dc4b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php @@ -0,0 +1,132 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\ResettableInterface; + +/** + * Forwards records to multiple handlers + * + * @author Lenar Lõhmus <lenar@city.ee> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class GroupHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface +{ + use ProcessableHandlerTrait; + + /** @var HandlerInterface[] */ + protected $handlers; + /** @var bool */ + protected $bubble; + + /** + * @param HandlerInterface[] $handlers Array of Handlers. + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(array $handlers, bool $bubble = true) + { + foreach ($handlers as $handler) { + if (!$handler instanceof HandlerInterface) { + throw new \InvalidArgumentException('The first argument of the GroupHandler must be an array of HandlerInterface instances.'); + } + } + + $this->handlers = $handlers; + $this->bubble = $bubble; + } + + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + foreach ($this->handlers as $handler) { + if ($handler->isHandling($record)) { + return true; + } + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + foreach ($this->handlers as $handler) { + $handler->handle($record); + } + + return false === $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + if ($this->processors) { + $processed = []; + foreach ($records as $record) { + $processed[] = $this->processRecord($record); + } + /** @var Record[] $records */ + $records = $processed; + } + + foreach ($this->handlers as $handler) { + $handler->handleBatch($records); + } + } + + public function reset() + { + $this->resetProcessors(); + + foreach ($this->handlers as $handler) { + if ($handler instanceof ResettableInterface) { + $handler->reset(); + } + } + } + + public function close(): void + { + parent::close(); + + foreach ($this->handlers as $handler) { + $handler->close(); + } + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + foreach ($this->handlers as $handler) { + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + } + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Handler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Handler.php new file mode 100644 index 0000000..34b4935 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Handler.php @@ -0,0 +1,62 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Base Handler class providing basic close() support as well as handleBatch + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +abstract class Handler implements HandlerInterface +{ + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + foreach ($records as $record) { + $this->handle($record); + } + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + } + + public function __destruct() + { + try { + $this->close(); + } catch (\Throwable $e) { + // do nothing + } + } + + public function __sleep() + { + $this->close(); + + $reflClass = new \ReflectionClass($this); + + $keys = []; + foreach ($reflClass->getProperties() as $reflProp) { + if (!$reflProp->isStatic()) { + $keys[] = $reflProp->getName(); + } + } + + return $keys; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php new file mode 100644 index 0000000..affcc51 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php @@ -0,0 +1,85 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Interface that all Monolog Handlers must implement + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + */ +interface HandlerInterface +{ + /** + * Checks whether the given record will be handled by this handler. + * + * This is mostly done for performance reasons, to avoid calling processors for nothing. + * + * Handlers should still check the record levels within handle(), returning false in isHandling() + * is no guarantee that handle() will not be called, and isHandling() might not be called + * for a given record. + * + * @param array $record Partial log record containing only a level key + * + * @return bool + * + * @phpstan-param array{level: Level} $record + */ + public function isHandling(array $record): bool; + + /** + * Handles a record. + * + * All records may be passed to this method, and the handler should discard + * those that it does not want to handle. + * + * The return value of this function controls the bubbling process of the handler stack. + * Unless the bubbling is interrupted (by returning true), the Logger class will keep on + * calling further handlers in the stack with a given log record. + * + * @param array $record The record to handle + * @return bool true means that this handler handled the record, and that bubbling is not permitted. + * false means the record was either not processed or that this handler allows bubbling. + * + * @phpstan-param Record $record + */ + public function handle(array $record): bool; + + /** + * Handles a set of records at once. + * + * @param array $records The records to handle (an array of record arrays) + * + * @phpstan-param Record[] $records + */ + public function handleBatch(array $records): void; + + /** + * Closes the handler. + * + * Ends a log cycle and frees all resources used by the handler. + * + * Closing a Handler means flushing all buffers and freeing any open resources/handles. + * + * Implementations have to be idempotent (i.e. it should be possible to call close several times without breakage) + * and ideally handlers should be able to reopen themselves on handle() after they have been closed. + * + * This is useful at the end of a request and will be called automatically when the object + * is destroyed if you extend Monolog\Handler\Handler. + * + * If you are thinking of calling this method yourself, most likely you should be + * calling ResettableInterface::reset instead. Have a look. + */ + public function close(): void; +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php new file mode 100644 index 0000000..d4351b9 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php @@ -0,0 +1,136 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; + +/** + * This simple wrapper class can be used to extend handlers functionality. + * + * Example: A custom filtering that can be applied to any handler. + * + * Inherit from this class and override handle() like this: + * + * public function handle(array $record) + * { + * if ($record meets certain conditions) { + * return false; + * } + * return $this->handler->handle($record); + * } + * + * @author Alexey Karapetov <alexey@karapetov.com> + */ +class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, FormattableHandlerInterface, ResettableInterface +{ + /** + * @var HandlerInterface + */ + protected $handler; + + public function __construct(HandlerInterface $handler) + { + $this->handler = $handler; + } + + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + return $this->handler->isHandling($record); + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + return $this->handler->handle($record); + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + $this->handler->handleBatch($records); + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + $this->handler->close(); + } + + /** + * {@inheritDoc} + */ + public function pushProcessor(callable $callback): HandlerInterface + { + if ($this->handler instanceof ProcessableHandlerInterface) { + $this->handler->pushProcessor($callback); + + return $this; + } + + throw new \LogicException('The wrapped handler does not implement ' . ProcessableHandlerInterface::class); + } + + /** + * {@inheritDoc} + */ + public function popProcessor(): callable + { + if ($this->handler instanceof ProcessableHandlerInterface) { + return $this->handler->popProcessor(); + } + + throw new \LogicException('The wrapped handler does not implement ' . ProcessableHandlerInterface::class); + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + $this->handler->setFormatter($formatter); + + return $this; + } + + throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class); + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + return $this->handler->getFormatter(); + } + + throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class); + } + + public function reset() + { + if ($this->handler instanceof ResettableInterface) { + $this->handler->reset(); + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php new file mode 100644 index 0000000..000ccea --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php @@ -0,0 +1,74 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; + +/** + * IFTTTHandler uses cURL to trigger IFTTT Maker actions + * + * Register a secret key and trigger/event name at https://ifttt.com/maker + * + * value1 will be the channel from monolog's Logger constructor, + * value2 will be the level name (ERROR, WARNING, ..) + * value3 will be the log record's message + * + * @author Nehal Patel <nehal@nehalpatel.me> + */ +class IFTTTHandler extends AbstractProcessingHandler +{ + /** @var string */ + private $eventName; + /** @var string */ + private $secretKey; + + /** + * @param string $eventName The name of the IFTTT Maker event that should be triggered + * @param string $secretKey A valid IFTTT secret key + */ + public function __construct(string $eventName, string $secretKey, $level = Logger::ERROR, bool $bubble = true) + { + if (!extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); + } + + $this->eventName = $eventName; + $this->secretKey = $secretKey; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + public function write(array $record): void + { + $postData = [ + "value1" => $record["channel"], + "value2" => $record["level_name"], + "value3" => $record["message"], + ]; + $postString = Utils::jsonEncode($postData); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "https://maker.ifttt.com/trigger/" . $this->eventName . "/with/key/" . $this->secretKey); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + ]); + + Curl\Util::execute($ch); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php new file mode 100644 index 0000000..71f64a2 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php @@ -0,0 +1,76 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Inspired on LogEntriesHandler. + * + * @author Robert Kaufmann III <rok3@rok3.me> + * @author Gabriel Machado <gabriel.ms1@hotmail.com> + */ +class InsightOpsHandler extends SocketHandler +{ + /** + * @var string + */ + protected $logToken; + + /** + * @param string $token Log token supplied by InsightOps + * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'. + * @param bool $useSSL Whether or not SSL encryption should be used + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct( + string $token, + string $region = 'us', + bool $useSSL = true, + $level = Logger::DEBUG, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if ($useSSL && !extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for InsightOpsHandler'); + } + + $endpoint = $useSSL + ? 'ssl://' . $region . '.data.logs.insight.rapid7.com:443' + : $region . '.data.logs.insight.rapid7.com:80'; + + parent::__construct( + $endpoint, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + $this->logToken = $token; + } + + /** + * {@inheritDoc} + */ + protected function generateDataStream(array $record): string + { + return $this->logToken . ' ' . $record['formatted']; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php new file mode 100644 index 0000000..25fcd15 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php @@ -0,0 +1,70 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * @author Robert Kaufmann III <rok3@rok3.me> + */ +class LogEntriesHandler extends SocketHandler +{ + /** + * @var string + */ + protected $logToken; + + /** + * @param string $token Log token supplied by LogEntries + * @param bool $useSSL Whether or not SSL encryption should be used. + * @param string $host Custom hostname to send the data to if needed + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct( + string $token, + bool $useSSL = true, + $level = Logger::DEBUG, + bool $bubble = true, + string $host = 'data.logentries.com', + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if ($useSSL && !extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); + } + + $endpoint = $useSSL ? 'ssl://' . $host . ':443' : $host . ':80'; + parent::__construct( + $endpoint, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + $this->logToken = $token; + } + + /** + * {@inheritDoc} + */ + protected function generateDataStream(array $record): string + { + return $this->logToken . ' ' . $record['formatted']; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php new file mode 100644 index 0000000..6d13db3 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php @@ -0,0 +1,160 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LogglyFormatter; +use function array_key_exists; +use CurlHandle; + +/** + * Sends errors to Loggly. + * + * @author Przemek Sobstel <przemek@sobstel.org> + * @author Adam Pancutt <adam@pancutt.com> + * @author Gregory Barchard <gregory@barchard.net> + */ +class LogglyHandler extends AbstractProcessingHandler +{ + protected const HOST = 'logs-01.loggly.com'; + protected const ENDPOINT_SINGLE = 'inputs'; + protected const ENDPOINT_BATCH = 'bulk'; + + /** + * Caches the curl handlers for every given endpoint. + * + * @var resource[]|CurlHandle[] + */ + protected $curlHandlers = []; + + /** @var string */ + protected $token; + + /** @var string[] */ + protected $tag = []; + + /** + * @param string $token API token supplied by Loggly + * + * @throws MissingExtensionException If the curl extension is missing + */ + public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true) + { + if (!extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); + } + + $this->token = $token; + + parent::__construct($level, $bubble); + } + + /** + * Loads and returns the shared curl handler for the given endpoint. + * + * @param string $endpoint + * + * @return resource|CurlHandle + */ + protected function getCurlHandler(string $endpoint) + { + if (!array_key_exists($endpoint, $this->curlHandlers)) { + $this->curlHandlers[$endpoint] = $this->loadCurlHandle($endpoint); + } + + return $this->curlHandlers[$endpoint]; + } + + /** + * Starts a fresh curl session for the given endpoint and returns its handler. + * + * @param string $endpoint + * + * @return resource|CurlHandle + */ + private function loadCurlHandle(string $endpoint) + { + $url = sprintf("https://%s/%s/%s/", static::HOST, $endpoint, $this->token); + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + return $ch; + } + + /** + * @param string[]|string $tag + */ + public function setTag($tag): self + { + $tag = !empty($tag) ? $tag : []; + $this->tag = is_array($tag) ? $tag : [$tag]; + + return $this; + } + + /** + * @param string[]|string $tag + */ + public function addTag($tag): self + { + if (!empty($tag)) { + $tag = is_array($tag) ? $tag : [$tag]; + $this->tag = array_unique(array_merge($this->tag, $tag)); + } + + return $this; + } + + protected function write(array $record): void + { + $this->send($record["formatted"], static::ENDPOINT_SINGLE); + } + + public function handleBatch(array $records): void + { + $level = $this->level; + + $records = array_filter($records, function ($record) use ($level) { + return ($record['level'] >= $level); + }); + + if ($records) { + $this->send($this->getFormatter()->formatBatch($records), static::ENDPOINT_BATCH); + } + } + + protected function send(string $data, string $endpoint): void + { + $ch = $this->getCurlHandler($endpoint); + + $headers = ['Content-Type: application/json']; + + if (!empty($this->tag)) { + $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag); + } + + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + + Curl\Util::execute($ch, 5, false); + } + + protected function getDefaultFormatter(): FormatterInterface + { + return new LogglyFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php new file mode 100644 index 0000000..859a469 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php @@ -0,0 +1,106 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LogmaticFormatter; + +/** + * @author Julien Breux <julien.breux@gmail.com> + */ +class LogmaticHandler extends SocketHandler +{ + /** + * @var string + */ + private $logToken; + + /** + * @var string + */ + private $hostname; + + /** + * @var string + */ + private $appname; + + /** + * @param string $token Log token supplied by Logmatic. + * @param string $hostname Host name supplied by Logmatic. + * @param string $appname Application name supplied by Logmatic. + * @param bool $useSSL Whether or not SSL encryption should be used. + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct( + string $token, + string $hostname = '', + string $appname = '', + bool $useSSL = true, + $level = Logger::DEBUG, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if ($useSSL && !extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use SSL encrypted connection for LogmaticHandler'); + } + + $endpoint = $useSSL ? 'ssl://api.logmatic.io:10515' : 'api.logmatic.io:10514'; + $endpoint .= '/v1/'; + + parent::__construct( + $endpoint, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + + $this->logToken = $token; + $this->hostname = $hostname; + $this->appname = $appname; + } + + /** + * {@inheritDoc} + */ + protected function generateDataStream(array $record): string + { + return $this->logToken . ' ' . $record['formatted']; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + $formatter = new LogmaticFormatter(); + + if (!empty($this->hostname)) { + $formatter->setHostname($this->hostname); + } + if (!empty($this->appname)) { + $formatter->setAppname($this->appname); + } + + return $formatter; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php new file mode 100644 index 0000000..97f3432 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php @@ -0,0 +1,95 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\HtmlFormatter; + +/** + * Base class for all mail handlers + * + * @author Gyula Sallai + * + * @phpstan-import-type Record from \Monolog\Logger + */ +abstract class MailHandler extends AbstractProcessingHandler +{ + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + $messages = []; + + foreach ($records as $record) { + if ($record['level'] < $this->level) { + continue; + } + /** @var Record $message */ + $message = $this->processRecord($record); + $messages[] = $message; + } + + if (!empty($messages)) { + $this->send((string) $this->getFormatter()->formatBatch($messages), $messages); + } + } + + /** + * Send a mail with the given content + * + * @param string $content formatted email body to be sent + * @param array $records the array of log records that formed this content + * + * @phpstan-param Record[] $records + */ + abstract protected function send(string $content, array $records): void; + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->send((string) $record['formatted'], [$record]); + } + + /** + * @phpstan-param non-empty-array<Record> $records + * @phpstan-return Record + */ + protected function getHighestRecord(array $records): array + { + $highestRecord = null; + foreach ($records as $record) { + if ($highestRecord === null || $highestRecord['level'] < $record['level']) { + $highestRecord = $record; + } + } + + return $highestRecord; + } + + protected function isHtmlBody(string $body): bool + { + return ($body[0] ?? null) === '<'; + } + + /** + * Gets the default formatter. + * + * @return FormatterInterface + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new HtmlFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php new file mode 100644 index 0000000..3003500 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php @@ -0,0 +1,83 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Swift; +use Swift_Message; + +/** + * MandrillHandler uses cURL to send the emails to the Mandrill API + * + * @author Adam Nicholson <adamnicholson10@gmail.com> + */ +class MandrillHandler extends MailHandler +{ + /** @var Swift_Message */ + protected $message; + /** @var string */ + protected $apiKey; + + /** + * @psalm-param Swift_Message|callable(): Swift_Message $message + * + * @param string $apiKey A valid Mandrill API key + * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced + */ + public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true) + { + parent::__construct($level, $bubble); + + if (!$message instanceof Swift_Message && is_callable($message)) { + $message = $message(); + } + if (!$message instanceof Swift_Message) { + throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it'); + } + $this->message = $message; + $this->apiKey = $apiKey; + } + + /** + * {@inheritDoc} + */ + protected function send(string $content, array $records): void + { + $mime = 'text/plain'; + if ($this->isHtmlBody($content)) { + $mime = 'text/html'; + } + + $message = clone $this->message; + $message->setBody($content, $mime); + /** @phpstan-ignore-next-line */ + if (version_compare(Swift::VERSION, '6.0.0', '>=')) { + $message->setDate(new \DateTimeImmutable()); + } else { + /** @phpstan-ignore-next-line */ + $message->setDate(time()); + } + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json'); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ + 'key' => $this->apiKey, + 'raw_message' => (string) $message, + 'async' => false, + ])); + + Curl\Util::execute($ch); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php new file mode 100644 index 0000000..3965aee --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php @@ -0,0 +1,21 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Exception can be thrown if an extension for a handler is missing + * + * @author Christian Bergau <cbergau86@gmail.com> + */ +class MissingExtensionException extends \Exception +{ +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php new file mode 100644 index 0000000..3063091 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php @@ -0,0 +1,86 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use MongoDB\Driver\BulkWrite; +use MongoDB\Driver\Manager; +use MongoDB\Client; +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\MongoDBFormatter; + +/** + * Logs to a MongoDB database. + * + * Usage example: + * + * $log = new \Monolog\Logger('application'); + * $client = new \MongoDB\Client('mongodb://localhost:27017'); + * $mongodb = new \Monolog\Handler\MongoDBHandler($client, 'logs', 'prod'); + * $log->pushHandler($mongodb); + * + * The above examples uses the MongoDB PHP library's client class; however, the + * MongoDB\Driver\Manager class from ext-mongodb is also supported. + */ +class MongoDBHandler extends AbstractProcessingHandler +{ + /** @var \MongoDB\Collection */ + private $collection; + /** @var Client|Manager */ + private $manager; + /** @var string */ + private $namespace; + + /** + * Constructor. + * + * @param Client|Manager $mongodb MongoDB library or driver client + * @param string $database Database name + * @param string $collection Collection name + */ + public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true) + { + if (!($mongodb instanceof Client || $mongodb instanceof Manager)) { + throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required'); + } + + if ($mongodb instanceof Client) { + $this->collection = $mongodb->selectCollection($database, $collection); + } else { + $this->manager = $mongodb; + $this->namespace = $database . '.' . $collection; + } + + parent::__construct($level, $bubble); + } + + protected function write(array $record): void + { + if (isset($this->collection)) { + $this->collection->insertOne($record['formatted']); + } + + if (isset($this->manager, $this->namespace)) { + $bulk = new BulkWrite; + $bulk->insert($record["formatted"]); + $this->manager->executeBulkWrite($this->namespace, $bulk); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new MongoDBFormatter; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php new file mode 100644 index 0000000..0c0a3bd --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php @@ -0,0 +1,174 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; + +/** + * NativeMailerHandler uses the mail() function to send the emails + * + * @author Christophe Coevoet <stof@notk.org> + * @author Mark Garrett <mark@moderndeveloperllc.com> + */ +class NativeMailerHandler extends MailHandler +{ + /** + * The email addresses to which the message will be sent + * @var string[] + */ + protected $to; + + /** + * The subject of the email + * @var string + */ + protected $subject; + + /** + * Optional headers for the message + * @var string[] + */ + protected $headers = []; + + /** + * Optional parameters for the message + * @var string[] + */ + protected $parameters = []; + + /** + * The wordwrap length for the message + * @var int + */ + protected $maxColumnWidth; + + /** + * The Content-type for the message + * @var string|null + */ + protected $contentType; + + /** + * The encoding for the message + * @var string + */ + protected $encoding = 'utf-8'; + + /** + * @param string|string[] $to The receiver of the mail + * @param string $subject The subject of the mail + * @param string $from The sender of the mail + * @param int $maxColumnWidth The maximum column width that the message lines will have + */ + public function __construct($to, string $subject, string $from, $level = Logger::ERROR, bool $bubble = true, int $maxColumnWidth = 70) + { + parent::__construct($level, $bubble); + $this->to = (array) $to; + $this->subject = $subject; + $this->addHeader(sprintf('From: %s', $from)); + $this->maxColumnWidth = $maxColumnWidth; + } + + /** + * Add headers to the message + * + * @param string|string[] $headers Custom added headers + */ + public function addHeader($headers): self + { + foreach ((array) $headers as $header) { + if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) { + throw new \InvalidArgumentException('Headers can not contain newline characters for security reasons'); + } + $this->headers[] = $header; + } + + return $this; + } + + /** + * Add parameters to the message + * + * @param string|string[] $parameters Custom added parameters + */ + public function addParameter($parameters): self + { + $this->parameters = array_merge($this->parameters, (array) $parameters); + + return $this; + } + + /** + * {@inheritDoc} + */ + protected function send(string $content, array $records): void + { + $contentType = $this->getContentType() ?: ($this->isHtmlBody($content) ? 'text/html' : 'text/plain'); + + if ($contentType !== 'text/html') { + $content = wordwrap($content, $this->maxColumnWidth); + } + + $headers = ltrim(implode("\r\n", $this->headers) . "\r\n", "\r\n"); + $headers .= 'Content-type: ' . $contentType . '; charset=' . $this->getEncoding() . "\r\n"; + if ($contentType === 'text/html' && false === strpos($headers, 'MIME-Version:')) { + $headers .= 'MIME-Version: 1.0' . "\r\n"; + } + + $subject = $this->subject; + if ($records) { + $subjectFormatter = new LineFormatter($this->subject); + $subject = $subjectFormatter->format($this->getHighestRecord($records)); + } + + $parameters = implode(' ', $this->parameters); + foreach ($this->to as $to) { + mail($to, $subject, $content, $headers, $parameters); + } + } + + public function getContentType(): ?string + { + return $this->contentType; + } + + public function getEncoding(): string + { + return $this->encoding; + } + + /** + * @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML messages. + */ + public function setContentType(string $contentType): self + { + if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) { + throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection'); + } + + $this->contentType = $contentType; + + return $this; + } + + public function setEncoding(string $encoding): self + { + if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) { + throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection'); + } + + $this->encoding = $encoding; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php new file mode 100644 index 0000000..114d749 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php @@ -0,0 +1,199 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Class to record a log on a NewRelic application. + * Enabling New Relic High Security mode may prevent capture of useful information. + * + * This handler requires a NormalizerFormatter to function and expects an array in $record['formatted'] + * + * @see https://docs.newrelic.com/docs/agents/php-agent + * @see https://docs.newrelic.com/docs/accounts-partnerships/accounts/security/high-security + */ +class NewRelicHandler extends AbstractProcessingHandler +{ + /** + * Name of the New Relic application that will receive logs from this handler. + * + * @var ?string + */ + protected $appName; + + /** + * Name of the current transaction + * + * @var ?string + */ + protected $transactionName; + + /** + * Some context and extra data is passed into the handler as arrays of values. Do we send them as is + * (useful if we are using the API), or explode them for display on the NewRelic RPM website? + * + * @var bool + */ + protected $explodeArrays; + + /** + * {@inheritDoc} + * + * @param string|null $appName + * @param bool $explodeArrays + * @param string|null $transactionName + */ + public function __construct( + $level = Logger::ERROR, + bool $bubble = true, + ?string $appName = null, + bool $explodeArrays = false, + ?string $transactionName = null + ) { + parent::__construct($level, $bubble); + + $this->appName = $appName; + $this->explodeArrays = $explodeArrays; + $this->transactionName = $transactionName; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if (!$this->isNewRelicEnabled()) { + throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler'); + } + + if ($appName = $this->getAppName($record['context'])) { + $this->setNewRelicAppName($appName); + } + + if ($transactionName = $this->getTransactionName($record['context'])) { + $this->setNewRelicTransactionName($transactionName); + unset($record['formatted']['context']['transaction_name']); + } + + if (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) { + newrelic_notice_error($record['message'], $record['context']['exception']); + unset($record['formatted']['context']['exception']); + } else { + newrelic_notice_error($record['message']); + } + + if (isset($record['formatted']['context']) && is_array($record['formatted']['context'])) { + foreach ($record['formatted']['context'] as $key => $parameter) { + if (is_array($parameter) && $this->explodeArrays) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('context_' . $key, $parameter); + } + } + } + + if (isset($record['formatted']['extra']) && is_array($record['formatted']['extra'])) { + foreach ($record['formatted']['extra'] as $key => $parameter) { + if (is_array($parameter) && $this->explodeArrays) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('extra_' . $key, $parameter); + } + } + } + } + + /** + * Checks whether the NewRelic extension is enabled in the system. + * + * @return bool + */ + protected function isNewRelicEnabled(): bool + { + return extension_loaded('newrelic'); + } + + /** + * Returns the appname where this log should be sent. Each log can override the default appname, set in this + * handler's constructor, by providing the appname in it's context. + * + * @param mixed[] $context + */ + protected function getAppName(array $context): ?string + { + if (isset($context['appname'])) { + return $context['appname']; + } + + return $this->appName; + } + + /** + * Returns the name of the current transaction. Each log can override the default transaction name, set in this + * handler's constructor, by providing the transaction_name in it's context + * + * @param mixed[] $context + */ + protected function getTransactionName(array $context): ?string + { + if (isset($context['transaction_name'])) { + return $context['transaction_name']; + } + + return $this->transactionName; + } + + /** + * Sets the NewRelic application that should receive this log. + */ + protected function setNewRelicAppName(string $appName): void + { + newrelic_set_appname($appName); + } + + /** + * Overwrites the name of the current transaction + */ + protected function setNewRelicTransactionName(string $transactionName): void + { + newrelic_name_transaction($transactionName); + } + + /** + * @param string $key + * @param mixed $value + */ + protected function setNewRelicParameter(string $key, $value): void + { + if (null === $value || is_scalar($value)) { + newrelic_add_custom_parameter($key, $value); + } else { + newrelic_add_custom_parameter($key, Utils::jsonEncode($value, null, true)); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php new file mode 100644 index 0000000..1ddf0be --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * No-op + * + * This handler handles anything, but does nothing, and does not stop bubbling to the rest of the stack. + * This can be used for testing, or to disable a handler when overriding a configuration without + * influencing the rest of the stack. + * + * @author Roel Harbers <roelharbers@gmail.com> + */ +class NoopHandler extends Handler +{ + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + return true; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + return false; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php new file mode 100644 index 0000000..e75ee0c --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php @@ -0,0 +1,60 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Blackhole + * + * Any record it can handle will be thrown away. This can be used + * to put on top of an existing stack to override it temporarily. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class NullHandler extends Handler +{ + /** + * @var int + */ + private $level; + + /** + * @param string|int $level The minimum logging level at which this handler will be triggered + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function __construct($level = Logger::DEBUG) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * {@inheritDoc} + */ + public function isHandling(array $record): bool + { + return $record['level'] >= $this->level; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + return $record['level'] >= $this->level; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php new file mode 100644 index 0000000..22068c9 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php @@ -0,0 +1,149 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; + +/** + * Handler to only pass log messages when a certain threshold of number of messages is reached. + * + * This can be useful in cases of processing a batch of data, but you're for example only interested + * in case it fails catastrophically instead of a warning for 1 or 2 events. Worse things can happen, right? + * + * Usage example: + * + * ``` + * $log = new Logger('application'); + * $handler = new SomeHandler(...) + * + * // Pass all warnings to the handler when more than 10 & all error messages when more then 5 + * $overflow = new OverflowHandler($handler, [Logger::WARNING => 10, Logger::ERROR => 5]); + * + * $log->pushHandler($overflow); + *``` + * + * @author Kris Buist <krisbuist@gmail.com> + */ +class OverflowHandler extends AbstractHandler implements FormattableHandlerInterface +{ + /** @var HandlerInterface */ + private $handler; + + /** @var int[] */ + private $thresholdMap = [ + Logger::DEBUG => 0, + Logger::INFO => 0, + Logger::NOTICE => 0, + Logger::WARNING => 0, + Logger::ERROR => 0, + Logger::CRITICAL => 0, + Logger::ALERT => 0, + Logger::EMERGENCY => 0, + ]; + + /** + * Buffer of all messages passed to the handler before the threshold was reached + * + * @var mixed[][] + */ + private $buffer = []; + + /** + * @param HandlerInterface $handler + * @param int[] $thresholdMap Dictionary of logger level => threshold + */ + public function __construct( + HandlerInterface $handler, + array $thresholdMap = [], + $level = Logger::DEBUG, + bool $bubble = true + ) { + $this->handler = $handler; + foreach ($thresholdMap as $thresholdLevel => $threshold) { + $this->thresholdMap[$thresholdLevel] = $threshold; + } + parent::__construct($level, $bubble); + } + + /** + * Handles a record. + * + * All records may be passed to this method, and the handler should discard + * those that it does not want to handle. + * + * The return value of this function controls the bubbling process of the handler stack. + * Unless the bubbling is interrupted (by returning true), the Logger class will keep on + * calling further handlers in the stack with a given log record. + * + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if ($record['level'] < $this->level) { + return false; + } + + $level = $record['level']; + + if (!isset($this->thresholdMap[$level])) { + $this->thresholdMap[$level] = 0; + } + + if ($this->thresholdMap[$level] > 0) { + // The overflow threshold is not yet reached, so we're buffering the record and lowering the threshold by 1 + $this->thresholdMap[$level]--; + $this->buffer[$level][] = $record; + + return false === $this->bubble; + } + + if ($this->thresholdMap[$level] == 0) { + // This current message is breaking the threshold. Flush the buffer and continue handling the current record + foreach ($this->buffer[$level] ?? [] as $buffered) { + $this->handler->handle($buffered); + } + $this->thresholdMap[$level]--; + unset($this->buffer[$level]); + } + + $this->handler->handle($record); + + return false === $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + $this->handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + return $this->handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php new file mode 100644 index 0000000..23a1d11 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php @@ -0,0 +1,263 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Utils; +use PhpConsole\Connector; +use PhpConsole\Handler as VendorPhpConsoleHandler; +use PhpConsole\Helper; + +/** + * Monolog handler for Google Chrome extension "PHP Console" + * + * Display PHP error/debug log messages in Google Chrome console and notification popups, executes PHP code remotely + * + * Usage: + * 1. Install Google Chrome extension [now dead and removed from the chrome store] + * 2. See overview https://github.com/barbushin/php-console#overview + * 3. Install PHP Console library https://github.com/barbushin/php-console#installation + * 4. Example (result will looks like http://i.hizliresim.com/vg3Pz4.png) + * + * $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler())); + * \Monolog\ErrorHandler::register($logger); + * echo $undefinedVar; + * $logger->debug('SELECT * FROM users', array('db', 'time' => 0.012)); + * PC::debug($_SERVER); // PHP Console debugger for any type of vars + * + * @author Sergey Barbushin https://www.linkedin.com/in/barbushin + * + * @phpstan-import-type Record from \Monolog\Logger + * @deprecated Since 2.8.0 and 3.2.0, PHPConsole is abandoned and thus we will drop this handler in Monolog 4 + */ +class PHPConsoleHandler extends AbstractProcessingHandler +{ + /** @var array<string, mixed> */ + private $options = [ + 'enabled' => true, // bool Is PHP Console server enabled + 'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with... + 'debugTagsKeysInContext' => [0, 'tag'], // bool Is PHP Console server enabled + 'useOwnErrorsHandler' => false, // bool Enable errors handling + 'useOwnExceptionsHandler' => false, // bool Enable exceptions handling + 'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths + 'registerHelper' => true, // bool Register PhpConsole\Helper that allows short debug calls like PC::debug($var, 'ta.g.s') + 'serverEncoding' => null, // string|null Server internal encoding + 'headersLimit' => null, // int|null Set headers size limit for your web-server + 'password' => null, // string|null Protect PHP Console connection by password + 'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed + 'ipMasks' => [], // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1') + 'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required) + 'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings + 'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level + 'dumperItemsCountLimit' => 100, // int Maximum dumped var same level array items or object properties number + 'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item + 'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON + 'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug + 'dataStorage' => null, // \PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ) + ]; + + /** @var Connector */ + private $connector; + + /** + * @param array<string, mixed> $options See \Monolog\Handler\PHPConsoleHandler::$options for more details + * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) + * @throws \RuntimeException + */ + public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true) + { + if (!class_exists('PhpConsole\Connector')) { + throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); + } + parent::__construct($level, $bubble); + $this->options = $this->initOptions($options); + $this->connector = $this->initConnector($connector); + } + + /** + * @param array<string, mixed> $options + * + * @return array<string, mixed> + */ + private function initOptions(array $options): array + { + $wrongOptions = array_diff(array_keys($options), array_keys($this->options)); + if ($wrongOptions) { + throw new \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions)); + } + + return array_replace($this->options, $options); + } + + private function initConnector(?Connector $connector = null): Connector + { + if (!$connector) { + if ($this->options['dataStorage']) { + Connector::setPostponeStorage($this->options['dataStorage']); + } + $connector = Connector::getInstance(); + } + + if ($this->options['registerHelper'] && !Helper::isRegistered()) { + Helper::register(); + } + + if ($this->options['enabled'] && $connector->isActiveClient()) { + if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) { + $handler = VendorPhpConsoleHandler::getInstance(); + $handler->setHandleErrors($this->options['useOwnErrorsHandler']); + $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']); + $handler->start(); + } + if ($this->options['sourcesBasePath']) { + $connector->setSourcesBasePath($this->options['sourcesBasePath']); + } + if ($this->options['serverEncoding']) { + $connector->setServerEncoding($this->options['serverEncoding']); + } + if ($this->options['password']) { + $connector->setPassword($this->options['password']); + } + if ($this->options['enableSslOnlyMode']) { + $connector->enableSslOnlyMode(); + } + if ($this->options['ipMasks']) { + $connector->setAllowedIpMasks($this->options['ipMasks']); + } + if ($this->options['headersLimit']) { + $connector->setHeadersLimit($this->options['headersLimit']); + } + if ($this->options['detectDumpTraceAndSource']) { + $connector->getDebugDispatcher()->detectTraceAndSource = true; + } + $dumper = $connector->getDumper(); + $dumper->levelLimit = $this->options['dumperLevelLimit']; + $dumper->itemsCountLimit = $this->options['dumperItemsCountLimit']; + $dumper->itemSizeLimit = $this->options['dumperItemSizeLimit']; + $dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit']; + $dumper->detectCallbacks = $this->options['dumperDetectCallbacks']; + if ($this->options['enableEvalListener']) { + $connector->startEvalRequestsListener(); + } + } + + return $connector; + } + + public function getConnector(): Connector + { + return $this->connector; + } + + /** + * @return array<string, mixed> + */ + public function getOptions(): array + { + return $this->options; + } + + public function handle(array $record): bool + { + if ($this->options['enabled'] && $this->connector->isActiveClient()) { + return parent::handle($record); + } + + return !$this->bubble; + } + + /** + * Writes the record down to the log of the implementing handler + */ + protected function write(array $record): void + { + if ($record['level'] < Logger::NOTICE) { + $this->handleDebugRecord($record); + } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) { + $this->handleExceptionRecord($record); + } else { + $this->handleErrorRecord($record); + } + } + + /** + * @phpstan-param Record $record + */ + private function handleDebugRecord(array $record): void + { + $tags = $this->getRecordTags($record); + $message = $record['message']; + if ($record['context']) { + $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($record['context'])), null, true); + } + $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']); + } + + /** + * @phpstan-param Record $record + */ + private function handleExceptionRecord(array $record): void + { + $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']); + } + + /** + * @phpstan-param Record $record + */ + private function handleErrorRecord(array $record): void + { + $context = $record['context']; + + $this->connector->getErrorsDispatcher()->dispatchError( + $context['code'] ?? null, + $context['message'] ?? $record['message'], + $context['file'] ?? null, + $context['line'] ?? null, + $this->options['classesPartialsTraceIgnore'] + ); + } + + /** + * @phpstan-param Record $record + * @return string + */ + private function getRecordTags(array &$record) + { + $tags = null; + if (!empty($record['context'])) { + $context = & $record['context']; + foreach ($this->options['debugTagsKeysInContext'] as $key) { + if (!empty($context[$key])) { + $tags = $context[$key]; + if ($key === 0) { + array_shift($context); + } else { + unset($context[$key]); + } + break; + } + } + } + + return $tags ?: strtolower($record['level_name']); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('%message%'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php new file mode 100644 index 0000000..8a8cf1b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php @@ -0,0 +1,191 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Stores to STDIN of any process, specified by a command. + * + * Usage example: + * <pre> + * $log = new Logger('myLogger'); + * $log->pushHandler(new ProcessHandler('/usr/bin/php /var/www/monolog/someScript.php')); + * </pre> + * + * @author Kolja Zuelsdorf <koljaz@web.de> + */ +class ProcessHandler extends AbstractProcessingHandler +{ + /** + * Holds the process to receive data on its STDIN. + * + * @var resource|bool|null + */ + private $process; + + /** + * @var string + */ + private $command; + + /** + * @var string|null + */ + private $cwd; + + /** + * @var resource[] + */ + private $pipes = []; + + /** + * @var array<int, string[]> + */ + protected const DESCRIPTOR_SPEC = [ + 0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from + 1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to + 2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors + ]; + + /** + * @param string $command Command for the process to start. Absolute paths are recommended, + * especially if you do not use the $cwd parameter. + * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in. + * @throws \InvalidArgumentException + */ + public function __construct(string $command, $level = Logger::DEBUG, bool $bubble = true, ?string $cwd = null) + { + if ($command === '') { + throw new \InvalidArgumentException('The command argument must be a non-empty string.'); + } + if ($cwd === '') { + throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string or null.'); + } + + parent::__construct($level, $bubble); + + $this->command = $command; + $this->cwd = $cwd; + } + + /** + * Writes the record down to the log of the implementing handler + * + * @throws \UnexpectedValueException + */ + protected function write(array $record): void + { + $this->ensureProcessIsStarted(); + + $this->writeProcessInput($record['formatted']); + + $errors = $this->readProcessErrors(); + if (empty($errors) === false) { + throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors)); + } + } + + /** + * Makes sure that the process is actually started, and if not, starts it, + * assigns the stream pipes, and handles startup errors, if any. + */ + private function ensureProcessIsStarted(): void + { + if (is_resource($this->process) === false) { + $this->startProcess(); + + $this->handleStartupErrors(); + } + } + + /** + * Starts the actual process and sets all streams to non-blocking. + */ + private function startProcess(): void + { + $this->process = proc_open($this->command, static::DESCRIPTOR_SPEC, $this->pipes, $this->cwd); + + foreach ($this->pipes as $pipe) { + stream_set_blocking($pipe, false); + } + } + + /** + * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any. + * + * @throws \UnexpectedValueException + */ + private function handleStartupErrors(): void + { + $selected = $this->selectErrorStream(); + if (false === $selected) { + throw new \UnexpectedValueException('Something went wrong while selecting a stream.'); + } + + $errors = $this->readProcessErrors(); + + if (is_resource($this->process) === false || empty($errors) === false) { + throw new \UnexpectedValueException( + sprintf('The process "%s" could not be opened: ' . $errors, $this->command) + ); + } + } + + /** + * Selects the STDERR stream. + * + * @return int|bool + */ + protected function selectErrorStream() + { + $empty = []; + $errorPipes = [$this->pipes[2]]; + + return stream_select($errorPipes, $empty, $empty, 1); + } + + /** + * Reads the errors of the process, if there are any. + * + * @codeCoverageIgnore + * @return string Empty string if there are no errors. + */ + protected function readProcessErrors(): string + { + return (string) stream_get_contents($this->pipes[2]); + } + + /** + * Writes to the input stream of the opened process. + * + * @codeCoverageIgnore + */ + protected function writeProcessInput(string $string): void + { + fwrite($this->pipes[0], $string); + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + if (is_resource($this->process)) { + foreach ($this->pipes as $pipe) { + fclose($pipe); + } + proc_close($this->process); + $this->process = null; + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php new file mode 100644 index 0000000..3adec7a --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php @@ -0,0 +1,44 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Processor\ProcessorInterface; + +/** + * Interface to describe loggers that have processors + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +interface ProcessableHandlerInterface +{ + /** + * Adds a processor in the stack. + * + * @psalm-param ProcessorInterface|callable(Record): Record $callback + * + * @param ProcessorInterface|callable $callback + * @return HandlerInterface self + */ + public function pushProcessor(callable $callback): HandlerInterface; + + /** + * Removes the processor on top of the stack and returns it. + * + * @psalm-return ProcessorInterface|callable(Record): Record $callback + * + * @throws \LogicException In case the processor stack is empty + * @return callable|ProcessorInterface + */ + public function popProcessor(): callable; +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php new file mode 100644 index 0000000..9ef6e30 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php @@ -0,0 +1,77 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\ResettableInterface; +use Monolog\Processor\ProcessorInterface; + +/** + * Helper trait for implementing ProcessableInterface + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +trait ProcessableHandlerTrait +{ + /** + * @var callable[] + * @phpstan-var array<ProcessorInterface|callable(Record): Record> + */ + protected $processors = []; + + /** + * {@inheritDoc} + */ + public function pushProcessor(callable $callback): HandlerInterface + { + array_unshift($this->processors, $callback); + + return $this; + } + + /** + * {@inheritDoc} + */ + public function popProcessor(): callable + { + if (!$this->processors) { + throw new \LogicException('You tried to pop from an empty processor stack.'); + } + + return array_shift($this->processors); + } + + /** + * Processes a record. + * + * @phpstan-param Record $record + * @phpstan-return Record + */ + protected function processRecord(array $record): array + { + foreach ($this->processors as $processor) { + $record = $processor($record); + } + + return $record; + } + + protected function resetProcessors(): void + { + foreach ($this->processors as $processor) { + if ($processor instanceof ResettableInterface) { + $processor->reset(); + } + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php new file mode 100644 index 0000000..36e19cc --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php @@ -0,0 +1,95 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Psr\Log\LoggerInterface; +use Monolog\Formatter\FormatterInterface; + +/** + * Proxies log messages to an existing PSR-3 compliant logger. + * + * If a formatter is configured, the formatter's output MUST be a string and the + * formatted message will be fed to the wrapped PSR logger instead of the original + * log record's message. + * + * @author Michael Moussa <michael.moussa@gmail.com> + */ +class PsrHandler extends AbstractHandler implements FormattableHandlerInterface +{ + /** + * PSR-3 compliant logger + * + * @var LoggerInterface + */ + protected $logger; + + /** + * @var FormatterInterface|null + */ + protected $formatter; + + /** + * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied + */ + public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->logger = $logger; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + if ($this->formatter) { + $formatted = $this->formatter->format($record); + $this->logger->log(strtolower($record['level_name']), (string) $formatted, $record['context']); + } else { + $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']); + } + + return false === $this->bubble; + } + + /** + * Sets the formatter. + * + * @param FormatterInterface $formatter + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $this->formatter = $formatter; + + return $this; + } + + /** + * Gets the formatter. + * + * @return FormatterInterface + */ + public function getFormatter(): FormatterInterface + { + if (!$this->formatter) { + throw new \LogicException('No formatter has been set and this handler does not have a default formatter'); + } + + return $this->formatter; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php new file mode 100644 index 0000000..fed2303 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php @@ -0,0 +1,246 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; +use Psr\Log\LogLevel; + +/** + * Sends notifications through the pushover api to mobile phones + * + * @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com> + * @see https://www.pushover.net/api + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class PushoverHandler extends SocketHandler +{ + /** @var string */ + private $token; + /** @var array<int|string> */ + private $users; + /** @var string */ + private $title; + /** @var string|int|null */ + private $user = null; + /** @var int */ + private $retry; + /** @var int */ + private $expire; + + /** @var int */ + private $highPriorityLevel; + /** @var int */ + private $emergencyLevel; + /** @var bool */ + private $useFormattedMessage = false; + + /** + * All parameters that can be sent to Pushover + * @see https://pushover.net/api + * @var array<string, bool> + */ + private $parameterNames = [ + 'token' => true, + 'user' => true, + 'message' => true, + 'device' => true, + 'title' => true, + 'url' => true, + 'url_title' => true, + 'priority' => true, + 'timestamp' => true, + 'sound' => true, + 'retry' => true, + 'expire' => true, + 'callback' => true, + ]; + + /** + * Sounds the api supports by default + * @see https://pushover.net/api#sounds + * @var string[] + */ + private $sounds = [ + 'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming', + 'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb', + 'persistent', 'echo', 'updown', 'none', + ]; + + /** + * @param string $token Pushover api token + * @param string|array $users Pushover user id or array of ids the message will be sent to + * @param string|null $title Title sent to the Pushover API + * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not + * the pushover.net app owner. OpenSSL is required for this option. + * @param string|int $highPriorityLevel The minimum logging level at which this handler will start + * sending "high priority" requests to the Pushover API + * @param string|int $emergencyLevel The minimum logging level at which this handler will start + * sending "emergency" requests to the Pushover API + * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will + * send the same notification to the user. + * @param int $expire The expire parameter specifies how many seconds your notification will continue + * to be retried for (every retry seconds). + * + * @phpstan-param string|array<int|string> $users + * @phpstan-param Level|LevelName|LogLevel::* $highPriorityLevel + * @phpstan-param Level|LevelName|LogLevel::* $emergencyLevel + */ + public function __construct( + string $token, + $users, + ?string $title = null, + $level = Logger::CRITICAL, + bool $bubble = true, + bool $useSSL = true, + $highPriorityLevel = Logger::CRITICAL, + $emergencyLevel = Logger::EMERGENCY, + int $retry = 30, + int $expire = 25200, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + $connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80'; + parent::__construct( + $connectionString, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + + $this->token = $token; + $this->users = (array) $users; + $this->title = $title ?: (string) gethostname(); + $this->highPriorityLevel = Logger::toMonologLevel($highPriorityLevel); + $this->emergencyLevel = Logger::toMonologLevel($emergencyLevel); + $this->retry = $retry; + $this->expire = $expire; + } + + protected function generateDataStream(array $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * @phpstan-param FormattedRecord $record + */ + private function buildContent(array $record): string + { + // Pushover has a limit of 512 characters on title and message combined. + $maxMessageLength = 512 - strlen($this->title); + + $message = ($this->useFormattedMessage) ? $record['formatted'] : $record['message']; + $message = Utils::substr($message, 0, $maxMessageLength); + + $timestamp = $record['datetime']->getTimestamp(); + + $dataArray = [ + 'token' => $this->token, + 'user' => $this->user, + 'message' => $message, + 'title' => $this->title, + 'timestamp' => $timestamp, + ]; + + if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) { + $dataArray['priority'] = 2; + $dataArray['retry'] = $this->retry; + $dataArray['expire'] = $this->expire; + } elseif (isset($record['level']) && $record['level'] >= $this->highPriorityLevel) { + $dataArray['priority'] = 1; + } + + // First determine the available parameters + $context = array_intersect_key($record['context'], $this->parameterNames); + $extra = array_intersect_key($record['extra'], $this->parameterNames); + + // Least important info should be merged with subsequent info + $dataArray = array_merge($extra, $context, $dataArray); + + // Only pass sounds that are supported by the API + if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds)) { + unset($dataArray['sound']); + } + + return http_build_query($dataArray); + } + + private function buildHeader(string $content): string + { + $header = "POST /1/messages.json HTTP/1.1\r\n"; + $header .= "Host: api.pushover.net\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + protected function write(array $record): void + { + foreach ($this->users as $user) { + $this->user = $user; + + parent::write($record); + $this->closeSocket(); + } + + $this->user = null; + } + + /** + * @param int|string $value + * + * @phpstan-param Level|LevelName|LogLevel::* $value + */ + public function setHighPriorityLevel($value): self + { + $this->highPriorityLevel = Logger::toMonologLevel($value); + + return $this; + } + + /** + * @param int|string $value + * + * @phpstan-param Level|LevelName|LogLevel::* $value + */ + public function setEmergencyLevel($value): self + { + $this->emergencyLevel = Logger::toMonologLevel($value); + + return $this; + } + + /** + * Use the formatted message? + */ + public function useFormattedMessage(bool $value): self + { + $this->useFormattedMessage = $value; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php new file mode 100644 index 0000000..91d16ea --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php @@ -0,0 +1,101 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; + +/** + * Logs to a Redis key using rpush + * + * usage example: + * + * $log = new Logger('application'); + * $redis = new RedisHandler(new Predis\Client("tcp://localhost:6379"), "logs", "prod"); + * $log->pushHandler($redis); + * + * @author Thomas Tourlourat <thomas@tourlourat.com> + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class RedisHandler extends AbstractProcessingHandler +{ + /** @var \Predis\Client<\Predis\Client>|\Redis */ + private $redisClient; + /** @var string */ + private $redisKey; + /** @var int */ + protected $capSize; + + /** + * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance + * @param string $key The key name to push records to + * @param int $capSize Number of entries to limit list size to, 0 = unlimited + */ + public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true, int $capSize = 0) + { + if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { + throw new \InvalidArgumentException('Predis\Client or Redis instance required'); + } + + $this->redisClient = $redis; + $this->redisKey = $key; + $this->capSize = $capSize; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if ($this->capSize) { + $this->writeCapped($record); + } else { + $this->redisClient->rpush($this->redisKey, $record["formatted"]); + } + } + + /** + * Write and cap the collection + * Writes the record to the redis list and caps its + * + * @phpstan-param FormattedRecord $record + */ + protected function writeCapped(array $record): void + { + if ($this->redisClient instanceof \Redis) { + $mode = defined('\Redis::MULTI') ? \Redis::MULTI : 1; + $this->redisClient->multi($mode) + ->rpush($this->redisKey, $record["formatted"]) + ->ltrim($this->redisKey, -$this->capSize, -1) + ->exec(); + } else { + $redisKey = $this->redisKey; + $capSize = $this->capSize; + $this->redisClient->transaction(function ($tx) use ($record, $redisKey, $capSize) { + $tx->rpush($redisKey, $record["formatted"]); + $tx->ltrim($redisKey, -$capSize, -1); + }); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php new file mode 100644 index 0000000..7789309 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php @@ -0,0 +1,67 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; + +/** + * Sends the message to a Redis Pub/Sub channel using PUBLISH + * + * usage example: + * + * $log = new Logger('application'); + * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Logger::WARNING); + * $log->pushHandler($redis); + * + * @author Gaëtan Faugère <gaetan@fauge.re> + */ +class RedisPubSubHandler extends AbstractProcessingHandler +{ + /** @var \Predis\Client<\Predis\Client>|\Redis */ + private $redisClient; + /** @var string */ + private $channelKey; + + /** + * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance + * @param string $key The channel key to publish records to + */ + public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true) + { + if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { + throw new \InvalidArgumentException('Predis\Client or Redis instance required'); + } + + $this->redisClient = $redis; + $this->channelKey = $key; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->redisClient->publish($this->channelKey, $record["formatted"]); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php new file mode 100644 index 0000000..adcc939 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php @@ -0,0 +1,131 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Rollbar\RollbarLogger; +use Throwable; +use Monolog\Logger; + +/** + * Sends errors to Rollbar + * + * If the context data contains a `payload` key, that is used as an array + * of payload options to RollbarLogger's log method. + * + * Rollbar's context info will contain the context + extra keys from the log record + * merged, and then on top of that a few keys: + * + * - level (rollbar level name) + * - monolog_level (monolog level name, raw level, as rollbar only has 5 but monolog 8) + * - channel + * - datetime (unix timestamp) + * + * @author Paul Statezny <paulstatezny@gmail.com> + */ +class RollbarHandler extends AbstractProcessingHandler +{ + /** + * @var RollbarLogger + */ + protected $rollbarLogger; + + /** @var string[] */ + protected $levelMap = [ + Logger::DEBUG => 'debug', + Logger::INFO => 'info', + Logger::NOTICE => 'info', + Logger::WARNING => 'warning', + Logger::ERROR => 'error', + Logger::CRITICAL => 'critical', + Logger::ALERT => 'critical', + Logger::EMERGENCY => 'critical', + ]; + + /** + * Records whether any log records have been added since the last flush of the rollbar notifier + * + * @var bool + */ + private $hasRecords = false; + + /** @var bool */ + protected $initialized = false; + + /** + * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token + */ + public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true) + { + $this->rollbarLogger = $rollbarLogger; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if (!$this->initialized) { + // __destructor() doesn't get called on Fatal errors + register_shutdown_function(array($this, 'close')); + $this->initialized = true; + } + + $context = $record['context']; + $context = array_merge($context, $record['extra'], [ + 'level' => $this->levelMap[$record['level']], + 'monolog_level' => $record['level_name'], + 'channel' => $record['channel'], + 'datetime' => $record['datetime']->format('U'), + ]); + + if (isset($context['exception']) && $context['exception'] instanceof Throwable) { + $exception = $context['exception']; + unset($context['exception']); + $toLog = $exception; + } else { + $toLog = $record['message']; + } + + // @phpstan-ignore-next-line + $this->rollbarLogger->log($context['level'], $toLog, $context); + + $this->hasRecords = true; + } + + public function flush(): void + { + if ($this->hasRecords) { + $this->rollbarLogger->flush(); + $this->hasRecords = false; + } + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + $this->flush(); + } + + /** + * {@inheritDoc} + */ + public function reset() + { + $this->flush(); + + parent::reset(); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php new file mode 100644 index 0000000..17745d2 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php @@ -0,0 +1,207 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use InvalidArgumentException; +use Monolog\Logger; +use Monolog\Utils; + +/** + * Stores logs to files that are rotated every day and a limited number of files are kept. + * + * This rotation is only intended to be used as a workaround. Using logrotate to + * handle the rotation is strongly encouraged when you can use it. + * + * @author Christophe Coevoet <stof@notk.org> + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class RotatingFileHandler extends StreamHandler +{ + public const FILE_PER_DAY = 'Y-m-d'; + public const FILE_PER_MONTH = 'Y-m'; + public const FILE_PER_YEAR = 'Y'; + + /** @var string */ + protected $filename; + /** @var int */ + protected $maxFiles; + /** @var bool */ + protected $mustRotate; + /** @var \DateTimeImmutable */ + protected $nextRotation; + /** @var string */ + protected $filenameFormat; + /** @var string */ + protected $dateFormat; + + /** + * @param string $filename + * @param int $maxFiles The maximal amount of files to keep (0 means unlimited) + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param bool $useLocking Try to lock log file before doing any writes + */ + public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + { + $this->filename = Utils::canonicalizePath($filename); + $this->maxFiles = $maxFiles; + $this->nextRotation = new \DateTimeImmutable('tomorrow'); + $this->filenameFormat = '{filename}-{date}'; + $this->dateFormat = static::FILE_PER_DAY; + + parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking); + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + parent::close(); + + if (true === $this->mustRotate) { + $this->rotate(); + } + } + + /** + * {@inheritDoc} + */ + public function reset() + { + parent::reset(); + + if (true === $this->mustRotate) { + $this->rotate(); + } + } + + public function setFilenameFormat(string $filenameFormat, string $dateFormat): self + { + if (!preg_match('{^[Yy](([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) { + throw new InvalidArgumentException( + 'Invalid date format - format must be one of '. + 'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '. + 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '. + 'date formats using slashes, underscores and/or dots instead of dashes.' + ); + } + if (substr_count($filenameFormat, '{date}') === 0) { + throw new InvalidArgumentException( + 'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.' + ); + } + $this->filenameFormat = $filenameFormat; + $this->dateFormat = $dateFormat; + $this->url = $this->getTimedFilename(); + $this->close(); + + return $this; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + // on the first record written, if the log is new, we should rotate (once per day) + if (null === $this->mustRotate) { + $this->mustRotate = null === $this->url || !file_exists($this->url); + } + + if ($this->nextRotation <= $record['datetime']) { + $this->mustRotate = true; + $this->close(); + } + + parent::write($record); + } + + /** + * Rotates the files. + */ + protected function rotate(): void + { + // update filename + $this->url = $this->getTimedFilename(); + $this->nextRotation = new \DateTimeImmutable('tomorrow'); + + // skip GC of old logs if files are unlimited + if (0 === $this->maxFiles) { + return; + } + + $logFiles = glob($this->getGlobPattern()); + if (false === $logFiles) { + // failed to glob + return; + } + + if ($this->maxFiles >= count($logFiles)) { + // no files to remove + return; + } + + // Sorting the files by name to remove the older ones + usort($logFiles, function ($a, $b) { + return strcmp($b, $a); + }); + + foreach (array_slice($logFiles, $this->maxFiles) as $file) { + if (is_writable($file)) { + // suppress errors here as unlink() might fail if two processes + // are cleaning up/rotating at the same time + set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool { + return false; + }); + unlink($file); + restore_error_handler(); + } + } + + $this->mustRotate = false; + } + + protected function getTimedFilename(): string + { + $fileInfo = pathinfo($this->filename); + $timedFilename = str_replace( + ['{filename}', '{date}'], + [$fileInfo['filename'], date($this->dateFormat)], + $fileInfo['dirname'] . '/' . $this->filenameFormat + ); + + if (isset($fileInfo['extension'])) { + $timedFilename .= '.'.$fileInfo['extension']; + } + + return $timedFilename; + } + + protected function getGlobPattern(): string + { + $fileInfo = pathinfo($this->filename); + $glob = str_replace( + ['{filename}', '{date}'], + [$fileInfo['filename'], str_replace( + ['Y', 'y', 'm', 'd'], + ['[0-9][0-9][0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]'], + $this->dateFormat) + ], + $fileInfo['dirname'] . '/' . $this->filenameFormat + ); + if (isset($fileInfo['extension'])) { + $glob .= '.'.$fileInfo['extension']; + } + + return $glob; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php new file mode 100644 index 0000000..c128a32 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php @@ -0,0 +1,132 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; + +/** + * Sampling handler + * + * A sampled event stream can be useful for logging high frequency events in + * a production environment where you only need an idea of what is happening + * and are not concerned with capturing every occurrence. Since the decision to + * handle or not handle a particular event is determined randomly, the + * resulting sampled log is not guaranteed to contain 1/N of the events that + * occurred in the application, but based on the Law of large numbers, it will + * tend to be close to this ratio with a large number of attempts. + * + * @author Bryan Davis <bd808@wikimedia.org> + * @author Kunal Mehta <legoktm@gmail.com> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + */ +class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * @var HandlerInterface|callable + * @phpstan-var HandlerInterface|callable(Record|array{level: Level}|null, HandlerInterface): HandlerInterface + */ + protected $handler; + + /** + * @var int $factor + */ + protected $factor; + + /** + * @psalm-param HandlerInterface|callable(Record|array{level: Level}|null, HandlerInterface): HandlerInterface $handler + * + * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $samplingHandler). + * @param int $factor Sample factor (e.g. 10 means every ~10th record is sampled) + */ + public function __construct($handler, int $factor) + { + parent::__construct(); + $this->handler = $handler; + $this->factor = $factor; + + if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { + throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); + } + } + + public function isHandling(array $record): bool + { + return $this->getHandler($record)->isHandling($record); + } + + public function handle(array $record): bool + { + if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) { + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + $this->getHandler($record)->handle($record); + } + + return false === $this->bubble; + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory callable, this will trigger the handler's instantiation. + * + * @phpstan-param Record|array{level: Level}|null $record + * + * @return HandlerInterface + */ + public function getHandler(array $record = null) + { + if (!$this->handler instanceof HandlerInterface) { + $this->handler = ($this->handler)($record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); + } + } + + return $this->handler; + } + + /** + * {@inheritDoc} + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); + } + + /** + * {@inheritDoc} + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php new file mode 100644 index 0000000..1280ee7 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php @@ -0,0 +1,102 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * SendGridrHandler uses the SendGrid API v2 function to send Log emails, more information in https://sendgrid.com/docs/API_Reference/Web_API/mail.html + * + * @author Ricardo Fontanelli <ricardo.fontanelli@hotmail.com> + */ +class SendGridHandler extends MailHandler +{ + /** + * The SendGrid API User + * @var string + */ + protected $apiUser; + + /** + * The SendGrid API Key + * @var string + */ + protected $apiKey; + + /** + * The email addresses to which the message will be sent + * @var string + */ + protected $from; + + /** + * The email addresses to which the message will be sent + * @var string[] + */ + protected $to; + + /** + * The subject of the email + * @var string + */ + protected $subject; + + /** + * @param string $apiUser The SendGrid API User + * @param string $apiKey The SendGrid API Key + * @param string $from The sender of the email + * @param string|string[] $to The recipients of the email + * @param string $subject The subject of the mail + */ + public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, $level = Logger::ERROR, bool $bubble = true) + { + if (!extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); + } + + parent::__construct($level, $bubble); + $this->apiUser = $apiUser; + $this->apiKey = $apiKey; + $this->from = $from; + $this->to = (array) $to; + $this->subject = $subject; + } + + /** + * {@inheritDoc} + */ + protected function send(string $content, array $records): void + { + $message = []; + $message['api_user'] = $this->apiUser; + $message['api_key'] = $this->apiKey; + $message['from'] = $this->from; + foreach ($this->to as $recipient) { + $message['to[]'] = $recipient; + } + $message['subject'] = $this->subject; + $message['date'] = date('r'); + + if ($this->isHtmlBody($content)) { + $message['html'] = $content; + } else { + $message['text'] = $content; + } + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, 'https://api.sendgrid.com/api/mail.send.json'); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($message)); + Curl\Util::execute($ch, 2); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php new file mode 100644 index 0000000..71a4109 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php @@ -0,0 +1,387 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Slack; + +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Slack record utility helping to log to Slack webhooks or API. + * + * @author Greg Kedzierski <greg@gregkedzierski.com> + * @author Haralan Dobrev <hkdobrev@gmail.com> + * @see https://api.slack.com/incoming-webhooks + * @see https://api.slack.com/docs/message-attachments + * + * @phpstan-import-type FormattedRecord from \Monolog\Handler\AbstractProcessingHandler + * @phpstan-import-type Record from \Monolog\Logger + */ +class SlackRecord +{ + public const COLOR_DANGER = 'danger'; + + public const COLOR_WARNING = 'warning'; + + public const COLOR_GOOD = 'good'; + + public const COLOR_DEFAULT = '#e3e4e6'; + + /** + * Slack channel (encoded ID or name) + * @var string|null + */ + private $channel; + + /** + * Name of a bot + * @var string|null + */ + private $username; + + /** + * User icon e.g. 'ghost', 'http://example.com/user.png' + * @var string|null + */ + private $userIcon; + + /** + * Whether the message should be added to Slack as attachment (plain text otherwise) + * @var bool + */ + private $useAttachment; + + /** + * Whether the the context/extra messages added to Slack as attachments are in a short style + * @var bool + */ + private $useShortAttachment; + + /** + * Whether the attachment should include context and extra data + * @var bool + */ + private $includeContextAndExtra; + + /** + * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * @var string[] + */ + private $excludeFields; + + /** + * @var ?FormatterInterface + */ + private $formatter; + + /** + * @var NormalizerFormatter + */ + private $normalizerFormatter; + + /** + * @param string[] $excludeFields + */ + public function __construct( + ?string $channel = null, + ?string $username = null, + bool $useAttachment = true, + ?string $userIcon = null, + bool $useShortAttachment = false, + bool $includeContextAndExtra = false, + array $excludeFields = array(), + FormatterInterface $formatter = null + ) { + $this + ->setChannel($channel) + ->setUsername($username) + ->useAttachment($useAttachment) + ->setUserIcon($userIcon) + ->useShortAttachment($useShortAttachment) + ->includeContextAndExtra($includeContextAndExtra) + ->excludeFields($excludeFields) + ->setFormatter($formatter); + + if ($this->includeContextAndExtra) { + $this->normalizerFormatter = new NormalizerFormatter(); + } + } + + /** + * Returns required data in format that Slack + * is expecting. + * + * @phpstan-param FormattedRecord $record + * @phpstan-return mixed[] + */ + public function getSlackData(array $record): array + { + $dataArray = array(); + $record = $this->removeExcludedFields($record); + + if ($this->username) { + $dataArray['username'] = $this->username; + } + + if ($this->channel) { + $dataArray['channel'] = $this->channel; + } + + if ($this->formatter && !$this->useAttachment) { + /** @phpstan-ignore-next-line */ + $message = $this->formatter->format($record); + } else { + $message = $record['message']; + } + + if ($this->useAttachment) { + $attachment = array( + 'fallback' => $message, + 'text' => $message, + 'color' => $this->getAttachmentColor($record['level']), + 'fields' => array(), + 'mrkdwn_in' => array('fields'), + 'ts' => $record['datetime']->getTimestamp(), + 'footer' => $this->username, + 'footer_icon' => $this->userIcon, + ); + + if ($this->useShortAttachment) { + $attachment['title'] = $record['level_name']; + } else { + $attachment['title'] = 'Message'; + $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']); + } + + if ($this->includeContextAndExtra) { + foreach (array('extra', 'context') as $key) { + if (empty($record[$key])) { + continue; + } + + if ($this->useShortAttachment) { + $attachment['fields'][] = $this->generateAttachmentField( + (string) $key, + $record[$key] + ); + } else { + // Add all extra fields as individual fields in attachment + $attachment['fields'] = array_merge( + $attachment['fields'], + $this->generateAttachmentFields($record[$key]) + ); + } + } + } + + $dataArray['attachments'] = array($attachment); + } else { + $dataArray['text'] = $message; + } + + if ($this->userIcon) { + if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) { + $dataArray['icon_url'] = $this->userIcon; + } else { + $dataArray['icon_emoji'] = ":{$this->userIcon}:"; + } + } + + return $dataArray; + } + + /** + * Returns a Slack message attachment color associated with + * provided level. + */ + public function getAttachmentColor(int $level): string + { + switch (true) { + case $level >= Logger::ERROR: + return static::COLOR_DANGER; + case $level >= Logger::WARNING: + return static::COLOR_WARNING; + case $level >= Logger::INFO: + return static::COLOR_GOOD; + default: + return static::COLOR_DEFAULT; + } + } + + /** + * Stringifies an array of key/value pairs to be used in attachment fields + * + * @param mixed[] $fields + */ + public function stringify(array $fields): string + { + /** @var Record $fields */ + $normalized = $this->normalizerFormatter->format($fields); + + $hasSecondDimension = count(array_filter($normalized, 'is_array')); + $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric')); + + return $hasSecondDimension || $hasNonNumericKeys + ? Utils::jsonEncode($normalized, JSON_PRETTY_PRINT|Utils::DEFAULT_JSON_FLAGS) + : Utils::jsonEncode($normalized, Utils::DEFAULT_JSON_FLAGS); + } + + /** + * Channel used by the bot when posting + * + * @param ?string $channel + * + * @return static + */ + public function setChannel(?string $channel = null): self + { + $this->channel = $channel; + + return $this; + } + + /** + * Username used by the bot when posting + * + * @param ?string $username + * + * @return static + */ + public function setUsername(?string $username = null): self + { + $this->username = $username; + + return $this; + } + + public function useAttachment(bool $useAttachment = true): self + { + $this->useAttachment = $useAttachment; + + return $this; + } + + public function setUserIcon(?string $userIcon = null): self + { + $this->userIcon = $userIcon; + + if (\is_string($userIcon)) { + $this->userIcon = trim($userIcon, ':'); + } + + return $this; + } + + public function useShortAttachment(bool $useShortAttachment = false): self + { + $this->useShortAttachment = $useShortAttachment; + + return $this; + } + + public function includeContextAndExtra(bool $includeContextAndExtra = false): self + { + $this->includeContextAndExtra = $includeContextAndExtra; + + if ($this->includeContextAndExtra) { + $this->normalizerFormatter = new NormalizerFormatter(); + } + + return $this; + } + + /** + * @param string[] $excludeFields + */ + public function excludeFields(array $excludeFields = []): self + { + $this->excludeFields = $excludeFields; + + return $this; + } + + public function setFormatter(?FormatterInterface $formatter = null): self + { + $this->formatter = $formatter; + + return $this; + } + + /** + * Generates attachment field + * + * @param string|mixed[] $value + * + * @return array{title: string, value: string, short: false} + */ + private function generateAttachmentField(string $title, $value): array + { + $value = is_array($value) + ? sprintf('```%s```', substr($this->stringify($value), 0, 1990)) + : $value; + + return array( + 'title' => ucfirst($title), + 'value' => $value, + 'short' => false, + ); + } + + /** + * Generates a collection of attachment fields from array + * + * @param mixed[] $data + * + * @return array<array{title: string, value: string, short: false}> + */ + private function generateAttachmentFields(array $data): array + { + /** @var Record $data */ + $normalized = $this->normalizerFormatter->format($data); + + $fields = array(); + foreach ($normalized as $key => $value) { + $fields[] = $this->generateAttachmentField((string) $key, $value); + } + + return $fields; + } + + /** + * Get a copy of record with fields excluded according to $this->excludeFields + * + * @phpstan-param FormattedRecord $record + * + * @return mixed[] + */ + private function removeExcludedFields(array $record): array + { + foreach ($this->excludeFields as $field) { + $keys = explode('.', $field); + $node = &$record; + $lastKey = end($keys); + foreach ($keys as $key) { + if (!isset($node[$key])) { + break; + } + if ($lastKey === $key) { + unset($node[$key]); + break; + } + $node = &$node[$key]; + } + } + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php new file mode 100644 index 0000000..a648513 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php @@ -0,0 +1,256 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Handler\Slack\SlackRecord; + +/** + * Sends notifications through Slack API + * + * @author Greg Kedzierski <greg@gregkedzierski.com> + * @see https://api.slack.com/ + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class SlackHandler extends SocketHandler +{ + /** + * Slack API token + * @var string + */ + private $token; + + /** + * Instance of the SlackRecord util class preparing data for Slack API. + * @var SlackRecord + */ + private $slackRecord; + + /** + * @param string $token Slack API token + * @param string $channel Slack channel (encoded ID or name) + * @param string|null $username Name of a bot + * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) + * @param string|null $iconEmoji The emoji name to use (or null) + * @param bool $useShortAttachment Whether the context/extra messages added to Slack as attachments are in a short style + * @param bool $includeContextAndExtra Whether the attachment should include context and extra data + * @param string[] $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * @throws MissingExtensionException If no OpenSSL PHP extension configured + */ + public function __construct( + string $token, + string $channel, + ?string $username = null, + bool $useAttachment = true, + ?string $iconEmoji = null, + $level = Logger::CRITICAL, + bool $bubble = true, + bool $useShortAttachment = false, + bool $includeContextAndExtra = false, + array $excludeFields = array(), + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if (!extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler'); + } + + parent::__construct( + 'ssl://slack.com:443', + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + + $this->slackRecord = new SlackRecord( + $channel, + $username, + $useAttachment, + $iconEmoji, + $useShortAttachment, + $includeContextAndExtra, + $excludeFields + ); + + $this->token = $token; + } + + public function getSlackRecord(): SlackRecord + { + return $this->slackRecord; + } + + public function getToken(): string + { + return $this->token; + } + + /** + * {@inheritDoc} + */ + protected function generateDataStream(array $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + * + * @phpstan-param FormattedRecord $record + */ + private function buildContent(array $record): string + { + $dataArray = $this->prepareContentData($record); + + return http_build_query($dataArray); + } + + /** + * @phpstan-param FormattedRecord $record + * @return string[] + */ + protected function prepareContentData(array $record): array + { + $dataArray = $this->slackRecord->getSlackData($record); + $dataArray['token'] = $this->token; + + if (!empty($dataArray['attachments'])) { + $dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']); + } + + return $dataArray; + } + + /** + * Builds the header of the API Call + */ + private function buildHeader(string $content): string + { + $header = "POST /api/chat.postMessage HTTP/1.1\r\n"; + $header .= "Host: slack.com\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + parent::write($record); + $this->finalizeWrite(); + } + + /** + * Finalizes the request by reading some bytes and then closing the socket + * + * If we do not read some but close the socket too early, slack sometimes + * drops the request entirely. + */ + protected function finalizeWrite(): void + { + $res = $this->getResource(); + if (is_resource($res)) { + @fread($res, 2048); + } + $this->closeSocket(); + } + + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + parent::setFormatter($formatter); + $this->slackRecord->setFormatter($formatter); + + return $this; + } + + public function getFormatter(): FormatterInterface + { + $formatter = parent::getFormatter(); + $this->slackRecord->setFormatter($formatter); + + return $formatter; + } + + /** + * Channel used by the bot when posting + */ + public function setChannel(string $channel): self + { + $this->slackRecord->setChannel($channel); + + return $this; + } + + /** + * Username used by the bot when posting + */ + public function setUsername(string $username): self + { + $this->slackRecord->setUsername($username); + + return $this; + } + + public function useAttachment(bool $useAttachment): self + { + $this->slackRecord->useAttachment($useAttachment); + + return $this; + } + + public function setIconEmoji(string $iconEmoji): self + { + $this->slackRecord->setUserIcon($iconEmoji); + + return $this; + } + + public function useShortAttachment(bool $useShortAttachment): self + { + $this->slackRecord->useShortAttachment($useShortAttachment); + + return $this; + } + + public function includeContextAndExtra(bool $includeContextAndExtra): self + { + $this->slackRecord->includeContextAndExtra($includeContextAndExtra); + + return $this; + } + + /** + * @param string[] $excludeFields + */ + public function excludeFields(array $excludeFields): self + { + $this->slackRecord->excludeFields($excludeFields); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php new file mode 100644 index 0000000..8ae3c78 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php @@ -0,0 +1,130 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Handler\Slack\SlackRecord; + +/** + * Sends notifications through Slack Webhooks + * + * @author Haralan Dobrev <hkdobrev@gmail.com> + * @see https://api.slack.com/incoming-webhooks + */ +class SlackWebhookHandler extends AbstractProcessingHandler +{ + /** + * Slack Webhook token + * @var string + */ + private $webhookUrl; + + /** + * Instance of the SlackRecord util class preparing data for Slack API. + * @var SlackRecord + */ + private $slackRecord; + + /** + * @param string $webhookUrl Slack Webhook URL + * @param string|null $channel Slack channel (encoded ID or name) + * @param string|null $username Name of a bot + * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) + * @param string|null $iconEmoji The emoji name to use (or null) + * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style + * @param bool $includeContextAndExtra Whether the attachment should include context and extra data + * @param string[] $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + */ + public function __construct( + string $webhookUrl, + ?string $channel = null, + ?string $username = null, + bool $useAttachment = true, + ?string $iconEmoji = null, + bool $useShortAttachment = false, + bool $includeContextAndExtra = false, + $level = Logger::CRITICAL, + bool $bubble = true, + array $excludeFields = array() + ) { + if (!extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler'); + } + + parent::__construct($level, $bubble); + + $this->webhookUrl = $webhookUrl; + + $this->slackRecord = new SlackRecord( + $channel, + $username, + $useAttachment, + $iconEmoji, + $useShortAttachment, + $includeContextAndExtra, + $excludeFields + ); + } + + public function getSlackRecord(): SlackRecord + { + return $this->slackRecord; + } + + public function getWebhookUrl(): string + { + return $this->webhookUrl; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $postData = $this->slackRecord->getSlackData($record); + $postString = Utils::jsonEncode($postData); + + $ch = curl_init(); + $options = array( + CURLOPT_URL => $this->webhookUrl, + CURLOPT_POST => true, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HTTPHEADER => array('Content-type: application/json'), + CURLOPT_POSTFIELDS => $postString, + ); + if (defined('CURLOPT_SAFE_UPLOAD')) { + $options[CURLOPT_SAFE_UPLOAD] = true; + } + + curl_setopt_array($ch, $options); + + Curl\Util::execute($ch); + } + + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + parent::setFormatter($formatter); + $this->slackRecord->setFormatter($formatter); + + return $this; + } + + public function getFormatter(): FormatterInterface + { + $formatter = parent::getFormatter(); + $this->slackRecord->setFormatter($formatter); + + return $formatter; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php new file mode 100644 index 0000000..21701af --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php @@ -0,0 +1,448 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Stores to any socket - uses fsockopen() or pfsockopen(). + * + * @author Pablo de Leon Belloc <pablolb@gmail.com> + * @see http://php.net/manual/en/function.fsockopen.php + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class SocketHandler extends AbstractProcessingHandler +{ + /** @var string */ + private $connectionString; + /** @var float */ + private $connectionTimeout; + /** @var resource|null */ + private $resource; + /** @var float */ + private $timeout; + /** @var float */ + private $writingTimeout; + /** @var ?int */ + private $lastSentBytes = null; + /** @var ?int */ + private $chunkSize; + /** @var bool */ + private $persistent; + /** @var ?int */ + private $errno = null; + /** @var ?string */ + private $errstr = null; + /** @var ?float */ + private $lastWritingAt = null; + + /** + * @param string $connectionString Socket connection string + * @param bool $persistent Flag to enable/disable persistent connections + * @param float $timeout Socket timeout to wait until the request is being aborted + * @param float $writingTimeout Socket timeout to wait until the request should've been sent/written + * @param float|null $connectionTimeout Socket connect timeout to wait until the connection should've been + * established + * @param int|null $chunkSize Sets the chunk size. Only has effect during connection in the writing cycle + * + * @throws \InvalidArgumentException If an invalid timeout value (less than 0) is passed. + */ + public function __construct( + string $connectionString, + $level = Logger::DEBUG, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + parent::__construct($level, $bubble); + $this->connectionString = $connectionString; + + if ($connectionTimeout !== null) { + $this->validateTimeout($connectionTimeout); + } + + $this->connectionTimeout = $connectionTimeout ?? (float) ini_get('default_socket_timeout'); + $this->persistent = $persistent; + $this->validateTimeout($timeout); + $this->timeout = $timeout; + $this->validateTimeout($writingTimeout); + $this->writingTimeout = $writingTimeout; + $this->chunkSize = $chunkSize; + } + + /** + * Connect (if necessary) and write to the socket + * + * {@inheritDoc} + * + * @throws \UnexpectedValueException + * @throws \RuntimeException + */ + protected function write(array $record): void + { + $this->connectIfNotConnected(); + $data = $this->generateDataStream($record); + $this->writeToSocket($data); + } + + /** + * We will not close a PersistentSocket instance so it can be reused in other requests. + */ + public function close(): void + { + if (!$this->isPersistent()) { + $this->closeSocket(); + } + } + + /** + * Close socket, if open + */ + public function closeSocket(): void + { + if (is_resource($this->resource)) { + fclose($this->resource); + $this->resource = null; + } + } + + /** + * Set socket connection to be persistent. It only has effect before the connection is initiated. + */ + public function setPersistent(bool $persistent): self + { + $this->persistent = $persistent; + + return $this; + } + + /** + * Set connection timeout. Only has effect before we connect. + * + * @see http://php.net/manual/en/function.fsockopen.php + */ + public function setConnectionTimeout(float $seconds): self + { + $this->validateTimeout($seconds); + $this->connectionTimeout = $seconds; + + return $this; + } + + /** + * Set write timeout. Only has effect before we connect. + * + * @see http://php.net/manual/en/function.stream-set-timeout.php + */ + public function setTimeout(float $seconds): self + { + $this->validateTimeout($seconds); + $this->timeout = $seconds; + + return $this; + } + + /** + * Set writing timeout. Only has effect during connection in the writing cycle. + * + * @param float $seconds 0 for no timeout + */ + public function setWritingTimeout(float $seconds): self + { + $this->validateTimeout($seconds); + $this->writingTimeout = $seconds; + + return $this; + } + + /** + * Set chunk size. Only has effect during connection in the writing cycle. + */ + public function setChunkSize(int $bytes): self + { + $this->chunkSize = $bytes; + + return $this; + } + + /** + * Get current connection string + */ + public function getConnectionString(): string + { + return $this->connectionString; + } + + /** + * Get persistent setting + */ + public function isPersistent(): bool + { + return $this->persistent; + } + + /** + * Get current connection timeout setting + */ + public function getConnectionTimeout(): float + { + return $this->connectionTimeout; + } + + /** + * Get current in-transfer timeout + */ + public function getTimeout(): float + { + return $this->timeout; + } + + /** + * Get current local writing timeout + * + * @return float + */ + public function getWritingTimeout(): float + { + return $this->writingTimeout; + } + + /** + * Get current chunk size + */ + public function getChunkSize(): ?int + { + return $this->chunkSize; + } + + /** + * Check to see if the socket is currently available. + * + * UDP might appear to be connected but might fail when writing. See http://php.net/fsockopen for details. + */ + public function isConnected(): bool + { + return is_resource($this->resource) + && !feof($this->resource); // on TCP - other party can close connection. + } + + /** + * Wrapper to allow mocking + * + * @return resource|false + */ + protected function pfsockopen() + { + return @pfsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout); + } + + /** + * Wrapper to allow mocking + * + * @return resource|false + */ + protected function fsockopen() + { + return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout); + } + + /** + * Wrapper to allow mocking + * + * @see http://php.net/manual/en/function.stream-set-timeout.php + * + * @return bool + */ + protected function streamSetTimeout() + { + $seconds = floor($this->timeout); + $microseconds = round(($this->timeout - $seconds) * 1e6); + + if (!is_resource($this->resource)) { + throw new \LogicException('streamSetTimeout called but $this->resource is not a resource'); + } + + return stream_set_timeout($this->resource, (int) $seconds, (int) $microseconds); + } + + /** + * Wrapper to allow mocking + * + * @see http://php.net/manual/en/function.stream-set-chunk-size.php + * + * @return int|bool + */ + protected function streamSetChunkSize() + { + if (!is_resource($this->resource)) { + throw new \LogicException('streamSetChunkSize called but $this->resource is not a resource'); + } + + if (null === $this->chunkSize) { + throw new \LogicException('streamSetChunkSize called but $this->chunkSize is not set'); + } + + return stream_set_chunk_size($this->resource, $this->chunkSize); + } + + /** + * Wrapper to allow mocking + * + * @return int|bool + */ + protected function fwrite(string $data) + { + if (!is_resource($this->resource)) { + throw new \LogicException('fwrite called but $this->resource is not a resource'); + } + + return @fwrite($this->resource, $data); + } + + /** + * Wrapper to allow mocking + * + * @return mixed[]|bool + */ + protected function streamGetMetadata() + { + if (!is_resource($this->resource)) { + throw new \LogicException('streamGetMetadata called but $this->resource is not a resource'); + } + + return stream_get_meta_data($this->resource); + } + + private function validateTimeout(float $value): void + { + if ($value < 0) { + throw new \InvalidArgumentException("Timeout must be 0 or a positive float (got $value)"); + } + } + + private function connectIfNotConnected(): void + { + if ($this->isConnected()) { + return; + } + $this->connect(); + } + + /** + * @phpstan-param FormattedRecord $record + */ + protected function generateDataStream(array $record): string + { + return (string) $record['formatted']; + } + + /** + * @return resource|null + */ + protected function getResource() + { + return $this->resource; + } + + private function connect(): void + { + $this->createSocketResource(); + $this->setSocketTimeout(); + $this->setStreamChunkSize(); + } + + private function createSocketResource(): void + { + if ($this->isPersistent()) { + $resource = $this->pfsockopen(); + } else { + $resource = $this->fsockopen(); + } + if (is_bool($resource)) { + throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)"); + } + $this->resource = $resource; + } + + private function setSocketTimeout(): void + { + if (!$this->streamSetTimeout()) { + throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()"); + } + } + + private function setStreamChunkSize(): void + { + if ($this->chunkSize && !$this->streamSetChunkSize()) { + throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()"); + } + } + + private function writeToSocket(string $data): void + { + $length = strlen($data); + $sent = 0; + $this->lastSentBytes = $sent; + while ($this->isConnected() && $sent < $length) { + if (0 == $sent) { + $chunk = $this->fwrite($data); + } else { + $chunk = $this->fwrite(substr($data, $sent)); + } + if ($chunk === false) { + throw new \RuntimeException("Could not write to socket"); + } + $sent += $chunk; + $socketInfo = $this->streamGetMetadata(); + if (is_array($socketInfo) && $socketInfo['timed_out']) { + throw new \RuntimeException("Write timed-out"); + } + + if ($this->writingIsTimedOut($sent)) { + throw new \RuntimeException("Write timed-out, no data sent for `{$this->writingTimeout}` seconds, probably we got disconnected (sent $sent of $length)"); + } + } + if (!$this->isConnected() && $sent < $length) { + throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)"); + } + } + + private function writingIsTimedOut(int $sent): bool + { + // convert to ms + if (0.0 == $this->writingTimeout) { + return false; + } + + if ($sent !== $this->lastSentBytes) { + $this->lastWritingAt = microtime(true); + $this->lastSentBytes = $sent; + + return false; + } else { + usleep(100); + } + + if ((microtime(true) - $this->lastWritingAt) >= $this->writingTimeout) { + $this->closeSocket(); + + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php new file mode 100644 index 0000000..dcf282b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php @@ -0,0 +1,62 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Aws\Sqs\SqsClient; +use Monolog\Logger; +use Monolog\Utils; + +/** + * Writes to any sqs queue. + * + * @author Martijn van Calker <git@amvc.nl> + */ +class SqsHandler extends AbstractProcessingHandler +{ + /** 256 KB in bytes - maximum message size in SQS */ + protected const MAX_MESSAGE_SIZE = 262144; + /** 100 KB in bytes - head message size for new error log */ + protected const HEAD_MESSAGE_SIZE = 102400; + + /** @var SqsClient */ + private $client; + /** @var string */ + private $queueUrl; + + public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->client = $sqsClient; + $this->queueUrl = $queueUrl; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if (!isset($record['formatted']) || 'string' !== gettype($record['formatted'])) { + throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record)); + } + + $messageBody = $record['formatted']; + if (strlen($messageBody) >= static::MAX_MESSAGE_SIZE) { + $messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE); + } + + $this->client->sendMessage([ + 'QueueUrl' => $this->queueUrl, + 'MessageBody' => $messageBody, + ]); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php new file mode 100644 index 0000000..82c048e --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php @@ -0,0 +1,224 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; + +/** + * Stores to any stream resource + * + * Can be used to store into php://stderr, remote and local files, etc. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class StreamHandler extends AbstractProcessingHandler +{ + /** @const int */ + protected const MAX_CHUNK_SIZE = 2147483647; + /** @const int 10MB */ + protected const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024; + /** @var int */ + protected $streamChunkSize; + /** @var resource|null */ + protected $stream; + /** @var ?string */ + protected $url = null; + /** @var ?string */ + private $errorMessage = null; + /** @var ?int */ + protected $filePermission; + /** @var bool */ + protected $useLocking; + /** @var true|null */ + private $dirCreated = null; + + /** + * @param resource|string $stream If a missing path can't be created, an UnexpectedValueException will be thrown on first write + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param bool $useLocking Try to lock log file before doing any writes + * + * @throws \InvalidArgumentException If stream is not a resource or string + */ + public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + { + parent::__construct($level, $bubble); + + if (($phpMemoryLimit = Utils::expandIniShorthandBytes(ini_get('memory_limit'))) !== false) { + if ($phpMemoryLimit > 0) { + // use max 10% of allowed memory for the chunk size, and at least 100KB + $this->streamChunkSize = min(static::MAX_CHUNK_SIZE, max((int) ($phpMemoryLimit / 10), 100 * 1024)); + } else { + // memory is unlimited, set to the default 10MB + $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE; + } + } else { + // no memory limit information, set to the default 10MB + $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE; + } + + if (is_resource($stream)) { + $this->stream = $stream; + + stream_set_chunk_size($this->stream, $this->streamChunkSize); + } elseif (is_string($stream)) { + $this->url = Utils::canonicalizePath($stream); + } else { + throw new \InvalidArgumentException('A stream must either be a resource or a string.'); + } + + $this->filePermission = $filePermission; + $this->useLocking = $useLocking; + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + if ($this->url && is_resource($this->stream)) { + fclose($this->stream); + } + $this->stream = null; + $this->dirCreated = null; + } + + /** + * Return the currently active stream if it is open + * + * @return resource|null + */ + public function getStream() + { + return $this->stream; + } + + /** + * Return the stream URL if it was configured with a URL and not an active resource + * + * @return string|null + */ + public function getUrl(): ?string + { + return $this->url; + } + + /** + * @return int + */ + public function getStreamChunkSize(): int + { + return $this->streamChunkSize; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if (!is_resource($this->stream)) { + $url = $this->url; + if (null === $url || '' === $url) { + throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().' . Utils::getRecordMessageForException($record)); + } + $this->createDir($url); + $this->errorMessage = null; + set_error_handler([$this, 'customErrorHandler']); + try { + $stream = fopen($url, 'a'); + if ($this->filePermission !== null) { + @chmod($url, $this->filePermission); + } + } finally { + restore_error_handler(); + } + if (!is_resource($stream)) { + $this->stream = null; + + throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url) . Utils::getRecordMessageForException($record)); + } + stream_set_chunk_size($stream, $this->streamChunkSize); + $this->stream = $stream; + } + + $stream = $this->stream; + if (!is_resource($stream)) { + throw new \LogicException('No stream was opened yet' . Utils::getRecordMessageForException($record)); + } + + if ($this->useLocking) { + // ignoring errors here, there's not much we can do about them + flock($stream, LOCK_EX); + } + + $this->streamWrite($stream, $record); + + if ($this->useLocking) { + flock($stream, LOCK_UN); + } + } + + /** + * Write to stream + * @param resource $stream + * @param array $record + * + * @phpstan-param FormattedRecord $record + */ + protected function streamWrite($stream, array $record): void + { + fwrite($stream, (string) $record['formatted']); + } + + private function customErrorHandler(int $code, string $msg): bool + { + $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg); + + return true; + } + + private function getDirFromStream(string $stream): ?string + { + $pos = strpos($stream, '://'); + if ($pos === false) { + return dirname($stream); + } + + if ('file://' === substr($stream, 0, 7)) { + return dirname(substr($stream, 7)); + } + + return null; + } + + private function createDir(string $url): void + { + // Do not try to create dir if it has already been tried. + if ($this->dirCreated) { + return; + } + + $dir = $this->getDirFromStream($url); + if (null !== $dir && !is_dir($dir)) { + $this->errorMessage = null; + set_error_handler([$this, 'customErrorHandler']); + $status = mkdir($dir, 0777, true); + restore_error_handler(); + if (false === $status && !is_dir($dir) && strpos((string) $this->errorMessage, 'File exists') === false) { + throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and it could not be created: '.$this->errorMessage, $dir)); + } + } + $this->dirCreated = true; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php new file mode 100644 index 0000000..fae9251 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php @@ -0,0 +1,115 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Swift_Message; +use Swift; + +/** + * SwiftMailerHandler uses Swift_Mailer to send the emails + * + * @author Gyula Sallai + * + * @phpstan-import-type Record from \Monolog\Logger + * @deprecated Since Monolog 2.6. Use SymfonyMailerHandler instead. + */ +class SwiftMailerHandler extends MailHandler +{ + /** @var \Swift_Mailer */ + protected $mailer; + /** @var Swift_Message|callable(string, Record[]): Swift_Message */ + private $messageTemplate; + + /** + * @psalm-param Swift_Message|callable(string, Record[]): Swift_Message $message + * + * @param \Swift_Mailer $mailer The mailer to use + * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced + */ + public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true) + { + parent::__construct($level, $bubble); + + @trigger_error('The SwiftMailerHandler is deprecated since Monolog 2.6. Use SymfonyMailerHandler instead.', E_USER_DEPRECATED); + + $this->mailer = $mailer; + $this->messageTemplate = $message; + } + + /** + * {@inheritDoc} + */ + protected function send(string $content, array $records): void + { + $this->mailer->send($this->buildMessage($content, $records)); + } + + /** + * Gets the formatter for the Swift_Message subject. + * + * @param string|null $format The format of the subject + */ + protected function getSubjectFormatter(?string $format): FormatterInterface + { + return new LineFormatter($format); + } + + /** + * Creates instance of Swift_Message to be sent + * + * @param string $content formatted email body to be sent + * @param array $records Log records that formed the content + * @return Swift_Message + * + * @phpstan-param Record[] $records + */ + protected function buildMessage(string $content, array $records): Swift_Message + { + $message = null; + if ($this->messageTemplate instanceof Swift_Message) { + $message = clone $this->messageTemplate; + $message->generateId(); + } elseif (is_callable($this->messageTemplate)) { + $message = ($this->messageTemplate)($content, $records); + } + + if (!$message instanceof Swift_Message) { + $record = reset($records); + throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it' . ($record ? Utils::getRecordMessageForException($record) : '')); + } + + if ($records) { + $subjectFormatter = $this->getSubjectFormatter($message->getSubject()); + $message->setSubject($subjectFormatter->format($this->getHighestRecord($records))); + } + + $mime = 'text/plain'; + if ($this->isHtmlBody($content)) { + $mime = 'text/html'; + } + + $message->setBody($content, $mime); + /** @phpstan-ignore-next-line */ + if (version_compare(Swift::VERSION, '6.0.0', '>=')) { + $message->setDate(new \DateTimeImmutable()); + } else { + /** @phpstan-ignore-next-line */ + $message->setDate(time()); + } + + return $message; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php new file mode 100644 index 0000000..130e6f1 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php @@ -0,0 +1,111 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Symfony\Component\Mailer\MailerInterface; +use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Mime\Email; + +/** + * SymfonyMailerHandler uses Symfony's Mailer component to send the emails + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class SymfonyMailerHandler extends MailHandler +{ + /** @var MailerInterface|TransportInterface */ + protected $mailer; + /** @var Email|callable(string, Record[]): Email */ + private $emailTemplate; + + /** + * @psalm-param Email|callable(string, Record[]): Email $email + * + * @param MailerInterface|TransportInterface $mailer The mailer to use + * @param callable|Email $email An email template, the subject/body will be replaced + */ + public function __construct($mailer, $email, $level = Logger::ERROR, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->mailer = $mailer; + $this->emailTemplate = $email; + } + + /** + * {@inheritDoc} + */ + protected function send(string $content, array $records): void + { + $this->mailer->send($this->buildMessage($content, $records)); + } + + /** + * Gets the formatter for the Swift_Message subject. + * + * @param string|null $format The format of the subject + */ + protected function getSubjectFormatter(?string $format): FormatterInterface + { + return new LineFormatter($format); + } + + /** + * Creates instance of Email to be sent + * + * @param string $content formatted email body to be sent + * @param array $records Log records that formed the content + * + * @phpstan-param Record[] $records + */ + protected function buildMessage(string $content, array $records): Email + { + $message = null; + if ($this->emailTemplate instanceof Email) { + $message = clone $this->emailTemplate; + } elseif (is_callable($this->emailTemplate)) { + $message = ($this->emailTemplate)($content, $records); + } + + if (!$message instanceof Email) { + $record = reset($records); + throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it' . ($record ? Utils::getRecordMessageForException($record) : '')); + } + + if ($records) { + $subjectFormatter = $this->getSubjectFormatter($message->getSubject()); + $message->subject($subjectFormatter->format($this->getHighestRecord($records))); + } + + if ($this->isHtmlBody($content)) { + if (null !== ($charset = $message->getHtmlCharset())) { + $message->html($content, $charset); + } else { + $message->html($content); + } + } else { + if (null !== ($charset = $message->getTextCharset())) { + $message->text($content, $charset); + } else { + $message->text($content); + } + } + + return $message->date(new \DateTimeImmutable()); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php new file mode 100644 index 0000000..1d543b7 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php @@ -0,0 +1,68 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Utils; + +/** + * Logs to syslog service. + * + * usage example: + * + * $log = new Logger('application'); + * $syslog = new SyslogHandler('myfacility', 'local6'); + * $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%"); + * $syslog->setFormatter($formatter); + * $log->pushHandler($syslog); + * + * @author Sven Paulus <sven@karlsruhe.org> + */ +class SyslogHandler extends AbstractSyslogHandler +{ + /** @var string */ + protected $ident; + /** @var int */ + protected $logopts; + + /** + * @param string $ident + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID + */ + public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID) + { + parent::__construct($facility, $level, $bubble); + + $this->ident = $ident; + $this->logopts = $logopts; + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + closelog(); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + if (!openlog($this->ident, $this->logopts, $this->facility)) { + throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"' . Utils::getRecordMessageForException($record)); + } + syslog($this->logLevels[$record['level']], (string) $record['formatted']); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php new file mode 100644 index 0000000..dbd8ef6 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php @@ -0,0 +1,88 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\SyslogUdp; + +use Monolog\Utils; +use Socket; + +class UdpSocket +{ + protected const DATAGRAM_MAX_LENGTH = 65023; + + /** @var string */ + protected $ip; + /** @var int */ + protected $port; + /** @var resource|Socket|null */ + protected $socket = null; + + public function __construct(string $ip, int $port = 514) + { + $this->ip = $ip; + $this->port = $port; + } + + /** + * @param string $line + * @param string $header + * @return void + */ + public function write($line, $header = "") + { + $this->send($this->assembleMessage($line, $header)); + } + + public function close(): void + { + if (is_resource($this->socket) || $this->socket instanceof Socket) { + socket_close($this->socket); + $this->socket = null; + } + } + + /** + * @return resource|Socket + */ + protected function getSocket() + { + if (null !== $this->socket) { + return $this->socket; + } + + $domain = AF_INET; + $protocol = SOL_UDP; + // Check if we are using unix sockets. + if ($this->port === 0) { + $domain = AF_UNIX; + $protocol = IPPROTO_IP; + } + + $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null; + if (null === $this->socket) { + throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create'); + } + + return $this->socket; + } + + protected function send(string $chunk): void + { + socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port); + } + + protected function assembleMessage(string $line, string $header): string + { + $chunkSize = static::DATAGRAM_MAX_LENGTH - strlen($header); + + return $header . Utils::substr($line, 0, $chunkSize); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php new file mode 100644 index 0000000..deaa19f --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php @@ -0,0 +1,150 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use DateTimeInterface; +use Monolog\Logger; +use Monolog\Handler\SyslogUdp\UdpSocket; +use Monolog\Utils; + +/** + * A Handler for logging to a remote syslogd server. + * + * @author Jesper Skovgaard Nielsen <nulpunkt@gmail.com> + * @author Dominik Kukacka <dominik.kukacka@gmail.com> + */ +class SyslogUdpHandler extends AbstractSyslogHandler +{ + const RFC3164 = 0; + const RFC5424 = 1; + const RFC5424e = 2; + + /** @var array<self::RFC*, string> */ + private $dateFormats = array( + self::RFC3164 => 'M d H:i:s', + self::RFC5424 => \DateTime::RFC3339, + self::RFC5424e => \DateTime::RFC3339_EXTENDED, + ); + + /** @var UdpSocket */ + protected $socket; + /** @var string */ + protected $ident; + /** @var self::RFC* */ + protected $rfc; + + /** + * @param string $host Either IP/hostname or a path to a unix socket (port must be 0 then) + * @param int $port Port number, or 0 if $host is a unix socket + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param string $ident Program name or tag for each log message. + * @param int $rfc RFC to format the message for. + * @throws MissingExtensionException + * + * @phpstan-param self::RFC* $rfc + */ + public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) + { + if (!extension_loaded('sockets')) { + throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler'); + } + + parent::__construct($facility, $level, $bubble); + + $this->ident = $ident; + $this->rfc = $rfc; + + $this->socket = new UdpSocket($host, $port); + } + + protected function write(array $record): void + { + $lines = $this->splitMessageIntoLines($record['formatted']); + + $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']], $record['datetime']); + + foreach ($lines as $line) { + $this->socket->write($line, $header); + } + } + + public function close(): void + { + $this->socket->close(); + } + + /** + * @param string|string[] $message + * @return string[] + */ + private function splitMessageIntoLines($message): array + { + if (is_array($message)) { + $message = implode("\n", $message); + } + + $lines = preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY); + if (false === $lines) { + $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + } + + return $lines; + } + + /** + * Make common syslog header (see rfc5424 or rfc3164) + */ + protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $datetime): string + { + $priority = $severity + $this->facility; + + if (!$pid = getmypid()) { + $pid = '-'; + } + + if (!$hostname = gethostname()) { + $hostname = '-'; + } + + if ($this->rfc === self::RFC3164) { + // see https://github.com/phpstan/phpstan/issues/5348 + // @phpstan-ignore-next-line + $dateNew = $datetime->setTimezone(new \DateTimeZone('UTC')); + $date = $dateNew->format($this->dateFormats[$this->rfc]); + + return "<$priority>" . + $date . " " . + $hostname . " " . + $this->ident . "[" . $pid . "]: "; + } + + $date = $datetime->format($this->dateFormats[$this->rfc]); + + return "<$priority>1 " . + $date . " " . + $hostname . " " . + $this->ident . " " . + $pid . " - - "; + } + + /** + * Inject your own socket, mainly used for testing + */ + public function setSocket(UdpSocket $socket): self + { + $this->socket = $socket; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php new file mode 100644 index 0000000..8912eba --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php @@ -0,0 +1,274 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use RuntimeException; +use Monolog\Logger; +use Monolog\Utils; + +/** + * Handler send logs to Telegram using Telegram Bot API. + * + * How to use: + * 1) Create telegram bot with https://telegram.me/BotFather + * 2) Create a telegram channel where logs will be recorded. + * 3) Add created bot from step 1 to the created channel from step 2. + * + * Use telegram bot API key from step 1 and channel name with '@' prefix from step 2 to create instance of TelegramBotHandler + * + * @link https://core.telegram.org/bots/api + * + * @author Mazur Alexandr <alexandrmazur96@gmail.com> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class TelegramBotHandler extends AbstractProcessingHandler +{ + private const BOT_API = 'https://api.telegram.org/bot'; + + /** + * The available values of parseMode according to the Telegram api documentation + */ + private const AVAILABLE_PARSE_MODES = [ + 'HTML', + 'MarkdownV2', + 'Markdown', // legacy mode without underline and strikethrough, use MarkdownV2 instead + ]; + + /** + * The maximum number of characters allowed in a message according to the Telegram api documentation + */ + private const MAX_MESSAGE_LENGTH = 4096; + + /** + * Telegram bot access token provided by BotFather. + * Create telegram bot with https://telegram.me/BotFather and use access token from it. + * @var string + */ + private $apiKey; + + /** + * Telegram channel name. + * Since to start with '@' symbol as prefix. + * @var string + */ + private $channel; + + /** + * The kind of formatting that is used for the message. + * See available options at https://core.telegram.org/bots/api#formatting-options + * or in AVAILABLE_PARSE_MODES + * @var ?string + */ + private $parseMode; + + /** + * Disables link previews for links in the message. + * @var ?bool + */ + private $disableWebPagePreview; + + /** + * Sends the message silently. Users will receive a notification with no sound. + * @var ?bool + */ + private $disableNotification; + + /** + * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages. + * False - truncates a message that is too long. + * @var bool + */ + private $splitLongMessages; + + /** + * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). + * @var bool + */ + private $delayBetweenMessages; + + /** + * @param string $apiKey Telegram bot access token provided by BotFather + * @param string $channel Telegram channel name + * @param bool $splitLongMessages Split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages + * @param bool $delayBetweenMessages Adds delay between sending a split message according to Telegram API + * @throws MissingExtensionException + */ + public function __construct( + string $apiKey, + string $channel, + $level = Logger::DEBUG, + bool $bubble = true, + string $parseMode = null, + bool $disableWebPagePreview = null, + bool $disableNotification = null, + bool $splitLongMessages = false, + bool $delayBetweenMessages = false + ) + { + if (!extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler'); + } + + parent::__construct($level, $bubble); + + $this->apiKey = $apiKey; + $this->channel = $channel; + $this->setParseMode($parseMode); + $this->disableWebPagePreview($disableWebPagePreview); + $this->disableNotification($disableNotification); + $this->splitLongMessages($splitLongMessages); + $this->delayBetweenMessages($delayBetweenMessages); + } + + public function setParseMode(string $parseMode = null): self + { + if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES)) { + throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.'); + } + + $this->parseMode = $parseMode; + + return $this; + } + + public function disableWebPagePreview(bool $disableWebPagePreview = null): self + { + $this->disableWebPagePreview = $disableWebPagePreview; + + return $this; + } + + public function disableNotification(bool $disableNotification = null): self + { + $this->disableNotification = $disableNotification; + + return $this; + } + + /** + * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages. + * False - truncates a message that is too long. + * @param bool $splitLongMessages + * @return $this + */ + public function splitLongMessages(bool $splitLongMessages = false): self + { + $this->splitLongMessages = $splitLongMessages; + + return $this; + } + + /** + * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). + * @param bool $delayBetweenMessages + * @return $this + */ + public function delayBetweenMessages(bool $delayBetweenMessages = false): self + { + $this->delayBetweenMessages = $delayBetweenMessages; + + return $this; + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + /** @var Record[] $messages */ + $messages = []; + + foreach ($records as $record) { + if (!$this->isHandling($record)) { + continue; + } + + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + $messages[] = $record; + } + + if (!empty($messages)) { + $this->send((string)$this->getFormatter()->formatBatch($messages)); + } + } + + /** + * @inheritDoc + */ + protected function write(array $record): void + { + $this->send($record['formatted']); + } + + /** + * Send request to @link https://api.telegram.org/bot on SendMessage action. + * @param string $message + */ + protected function send(string $message): void + { + $messages = $this->handleMessageLength($message); + + foreach ($messages as $key => $msg) { + if ($this->delayBetweenMessages && $key > 0) { + sleep(1); + } + + $this->sendCurl($msg); + } + } + + protected function sendCurl(string $message): void + { + $ch = curl_init(); + $url = self::BOT_API . $this->apiKey . '/SendMessage'; + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ + 'text' => $message, + 'chat_id' => $this->channel, + 'parse_mode' => $this->parseMode, + 'disable_web_page_preview' => $this->disableWebPagePreview, + 'disable_notification' => $this->disableNotification, + ])); + + $result = Curl\Util::execute($ch); + if (!is_string($result)) { + throw new RuntimeException('Telegram API error. Description: No response'); + } + $result = json_decode($result, true); + + if ($result['ok'] === false) { + throw new RuntimeException('Telegram API error. Description: ' . $result['description']); + } + } + + /** + * Handle a message that is too long: truncates or splits into several + * @param string $message + * @return string[] + */ + private function handleMessageLength(string $message): array + { + $truncatedMarker = ' (...truncated)'; + if (!$this->splitLongMessages && strlen($message) > self::MAX_MESSAGE_LENGTH) { + return [Utils::substr($message, 0, self::MAX_MESSAGE_LENGTH - strlen($truncatedMarker)) . $truncatedMarker]; + } + + return str_split($message, self::MAX_MESSAGE_LENGTH); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php new file mode 100644 index 0000000..0986da2 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php @@ -0,0 +1,231 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Used for testing purposes. + * + * It records all records and gives you access to them for verification. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @method bool hasEmergency($record) + * @method bool hasAlert($record) + * @method bool hasCritical($record) + * @method bool hasError($record) + * @method bool hasWarning($record) + * @method bool hasNotice($record) + * @method bool hasInfo($record) + * @method bool hasDebug($record) + * + * @method bool hasEmergencyRecords() + * @method bool hasAlertRecords() + * @method bool hasCriticalRecords() + * @method bool hasErrorRecords() + * @method bool hasWarningRecords() + * @method bool hasNoticeRecords() + * @method bool hasInfoRecords() + * @method bool hasDebugRecords() + * + * @method bool hasEmergencyThatContains($message) + * @method bool hasAlertThatContains($message) + * @method bool hasCriticalThatContains($message) + * @method bool hasErrorThatContains($message) + * @method bool hasWarningThatContains($message) + * @method bool hasNoticeThatContains($message) + * @method bool hasInfoThatContains($message) + * @method bool hasDebugThatContains($message) + * + * @method bool hasEmergencyThatMatches($message) + * @method bool hasAlertThatMatches($message) + * @method bool hasCriticalThatMatches($message) + * @method bool hasErrorThatMatches($message) + * @method bool hasWarningThatMatches($message) + * @method bool hasNoticeThatMatches($message) + * @method bool hasInfoThatMatches($message) + * @method bool hasDebugThatMatches($message) + * + * @method bool hasEmergencyThatPasses($message) + * @method bool hasAlertThatPasses($message) + * @method bool hasCriticalThatPasses($message) + * @method bool hasErrorThatPasses($message) + * @method bool hasWarningThatPasses($message) + * @method bool hasNoticeThatPasses($message) + * @method bool hasInfoThatPasses($message) + * @method bool hasDebugThatPasses($message) + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class TestHandler extends AbstractProcessingHandler +{ + /** @var Record[] */ + protected $records = []; + /** @var array<Level, Record[]> */ + protected $recordsByLevel = []; + /** @var bool */ + private $skipReset = false; + + /** + * @return array + * + * @phpstan-return Record[] + */ + public function getRecords() + { + return $this->records; + } + + /** + * @return void + */ + public function clear() + { + $this->records = []; + $this->recordsByLevel = []; + } + + /** + * @return void + */ + public function reset() + { + if (!$this->skipReset) { + $this->clear(); + } + } + + /** + * @return void + */ + public function setSkipReset(bool $skipReset) + { + $this->skipReset = $skipReset; + } + + /** + * @param string|int $level Logging level value or name + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecords($level): bool + { + return isset($this->recordsByLevel[Logger::toMonologLevel($level)]); + } + + /** + * @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records + * @param string|int $level Logging level value or name + * + * @phpstan-param array{message: string, context?: mixed[]}|string $record + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecord($record, $level): bool + { + if (is_string($record)) { + $record = array('message' => $record); + } + + return $this->hasRecordThatPasses(function ($rec) use ($record) { + if ($rec['message'] !== $record['message']) { + return false; + } + if (isset($record['context']) && $rec['context'] !== $record['context']) { + return false; + } + + return true; + }, $level); + } + + /** + * @param string|int $level Logging level value or name + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecordThatContains(string $message, $level): bool + { + return $this->hasRecordThatPasses(function ($rec) use ($message) { + return strpos($rec['message'], $message) !== false; + }, $level); + } + + /** + * @param string|int $level Logging level value or name + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecordThatMatches(string $regex, $level): bool + { + return $this->hasRecordThatPasses(function (array $rec) use ($regex): bool { + return preg_match($regex, $rec['message']) > 0; + }, $level); + } + + /** + * @param string|int $level Logging level value or name + * @return bool + * + * @psalm-param callable(Record, int): mixed $predicate + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecordThatPasses(callable $predicate, $level) + { + $level = Logger::toMonologLevel($level); + + if (!isset($this->recordsByLevel[$level])) { + return false; + } + + foreach ($this->recordsByLevel[$level] as $i => $rec) { + if ($predicate($rec, $i)) { + return true; + } + } + + return false; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->recordsByLevel[$record['level']][] = $record; + $this->records[] = $record; + } + + /** + * @param string $method + * @param mixed[] $args + * @return bool + */ + public function __call($method, $args) + { + if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { + $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; + $level = constant('Monolog\Logger::' . strtoupper($matches[2])); + $callback = [$this, $genericMethod]; + if (is_callable($callback)) { + $args[] = $level; + + return call_user_func_array($callback, $args); + } + } + + throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()'); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php new file mode 100644 index 0000000..c818352 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php @@ -0,0 +1,24 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +trait WebRequestRecognizerTrait +{ + /** + * Checks if PHP's serving a web request + * @return bool + */ + protected function isWebRequest(): bool + { + return 'cli' !== \PHP_SAPI && 'phpdbg' !== \PHP_SAPI; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php new file mode 100644 index 0000000..b6d3d3b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php @@ -0,0 +1,81 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Forwards records to multiple handlers suppressing failures of each handler + * and continuing through to give every handler a chance to succeed. + * + * @author Craig D'Amelio <craig@damelio.ca> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +class WhatFailureGroupHandler extends GroupHandler +{ + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + if ($this->processors) { + /** @var Record $record */ + $record = $this->processRecord($record); + } + + foreach ($this->handlers as $handler) { + try { + $handler->handle($record); + } catch (\Throwable $e) { + // What failure? + } + } + + return false === $this->bubble; + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + if ($this->processors) { + $processed = array(); + foreach ($records as $record) { + $processed[] = $this->processRecord($record); + } + /** @var Record[] $records */ + $records = $processed; + } + + foreach ($this->handlers as $handler) { + try { + $handler->handleBatch($records); + } catch (\Throwable $e) { + // What failure? + } + } + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + foreach ($this->handlers as $handler) { + try { + $handler->close(); + } catch (\Throwable $e) { + // What failure? + } + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php new file mode 100644 index 0000000..ddd46d8 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php @@ -0,0 +1,101 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Logger; + +/** + * Handler sending logs to Zend Monitor + * + * @author Christian Bergau <cbergau86@gmail.com> + * @author Jason Davis <happydude@jasondavis.net> + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler + */ +class ZendMonitorHandler extends AbstractProcessingHandler +{ + /** + * Monolog level / ZendMonitor Custom Event priority map + * + * @var array<int, int> + */ + protected $levelMap = []; + + /** + * @throws MissingExtensionException + */ + public function __construct($level = Logger::DEBUG, bool $bubble = true) + { + if (!function_exists('zend_monitor_custom_event')) { + throw new MissingExtensionException( + 'You must have Zend Server installed with Zend Monitor enabled in order to use this handler' + ); + } + //zend monitor constants are not defined if zend monitor is not enabled. + $this->levelMap = [ + Logger::DEBUG => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Logger::INFO => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Logger::NOTICE => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Logger::WARNING => \ZEND_MONITOR_EVENT_SEVERITY_WARNING, + Logger::ERROR => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Logger::CRITICAL => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Logger::ALERT => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Logger::EMERGENCY => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + ]; + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record): void + { + $this->writeZendMonitorCustomEvent( + Logger::getLevelName($record['level']), + $record['message'], + $record['formatted'], + $this->levelMap[$record['level']] + ); + } + + /** + * Write to Zend Monitor Events + * @param string $type Text displayed in "Class Name (custom)" field + * @param string $message Text displayed in "Error String" + * @param array $formatted Displayed in Custom Variables tab + * @param int $severity Set the event severity level (-1,0,1) + * + * @phpstan-param FormattedRecord $formatted + */ + protected function writeZendMonitorCustomEvent(string $type, string $message, array $formatted, int $severity): void + { + zend_monitor_custom_event($type, $message, $formatted, $severity); + } + + /** + * {@inheritDoc} + */ + public function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter(); + } + + /** + * @return array<int, int> + */ + public function getLevelMap(): array + { + return $this->levelMap; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/LogRecord.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/LogRecord.php new file mode 100644 index 0000000..702807d --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/LogRecord.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use ArrayAccess; + +/** + * Monolog log record interface for forward compatibility with Monolog 3.0 + * + * This is just present in Monolog 2.4+ to allow interoperable code to be written against + * both versions by type-hinting arguments as `array|\Monolog\LogRecord $record` + * + * Do not rely on this interface for other purposes, and do not implement it. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @template-extends \ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra'|'formatted', mixed> + * @phpstan-import-type Record from Logger + */ +interface LogRecord extends \ArrayAccess +{ + /** + * @phpstan-return Record + */ + public function toArray(): array; +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Logger.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Logger.php new file mode 100644 index 0000000..84a2f55 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Logger.php @@ -0,0 +1,761 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use DateTimeZone; +use Monolog\Handler\HandlerInterface; +use Psr\Log\LoggerInterface; +use Psr\Log\InvalidArgumentException; +use Psr\Log\LogLevel; +use Throwable; +use Stringable; + +/** + * Monolog log channel + * + * It contains a stack of Handlers and a stack of Processors, + * and uses them to store records that are added to it. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-type Level Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY + * @phpstan-type LevelName 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY' + * @phpstan-type Record array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} + */ +class Logger implements LoggerInterface, ResettableInterface +{ + /** + * Detailed debug information + */ + public const DEBUG = 100; + + /** + * Interesting events + * + * Examples: User logs in, SQL logs. + */ + public const INFO = 200; + + /** + * Uncommon events + */ + public const NOTICE = 250; + + /** + * Exceptional occurrences that are not errors + * + * Examples: Use of deprecated APIs, poor use of an API, + * undesirable things that are not necessarily wrong. + */ + public const WARNING = 300; + + /** + * Runtime errors + */ + public const ERROR = 400; + + /** + * Critical conditions + * + * Example: Application component unavailable, unexpected exception. + */ + public const CRITICAL = 500; + + /** + * Action must be taken immediately + * + * Example: Entire website down, database unavailable, etc. + * This should trigger the SMS alerts and wake you up. + */ + public const ALERT = 550; + + /** + * Urgent alert. + */ + public const EMERGENCY = 600; + + /** + * Monolog API version + * + * This is only bumped when API breaks are done and should + * follow the major version of the library + * + * @var int + */ + public const API = 2; + + /** + * This is a static variable and not a constant to serve as an extension point for custom levels + * + * @var array<int, string> $levels Logging levels with the levels as key + * + * @phpstan-var array<Level, LevelName> $levels Logging levels with the levels as key + */ + protected static $levels = [ + self::DEBUG => 'DEBUG', + self::INFO => 'INFO', + self::NOTICE => 'NOTICE', + self::WARNING => 'WARNING', + self::ERROR => 'ERROR', + self::CRITICAL => 'CRITICAL', + self::ALERT => 'ALERT', + self::EMERGENCY => 'EMERGENCY', + ]; + + /** + * Mapping between levels numbers defined in RFC 5424 and Monolog ones + * + * @phpstan-var array<int, Level> $rfc_5424_levels + */ + private const RFC_5424_LEVELS = [ + 7 => self::DEBUG, + 6 => self::INFO, + 5 => self::NOTICE, + 4 => self::WARNING, + 3 => self::ERROR, + 2 => self::CRITICAL, + 1 => self::ALERT, + 0 => self::EMERGENCY, + ]; + + /** + * @var string + */ + protected $name; + + /** + * The handler stack + * + * @var HandlerInterface[] + */ + protected $handlers; + + /** + * Processors that will process all log records + * + * To process records of a single handler instead, add the processor on that specific handler + * + * @var callable[] + */ + protected $processors; + + /** + * @var bool + */ + protected $microsecondTimestamps = true; + + /** + * @var DateTimeZone + */ + protected $timezone; + + /** + * @var callable|null + */ + protected $exceptionHandler; + + /** + * @var int Keeps track of depth to prevent infinite logging loops + */ + private $logDepth = 0; + + /** + * @var \WeakMap<\Fiber, int>|null Keeps track of depth inside fibers to prevent infinite logging loops + */ + private $fiberLogDepth; + + /** + * @var bool Whether to detect infinite logging loops + * + * This can be disabled via {@see useLoggingLoopDetection} if you have async handlers that do not play well with this + */ + private $detectCycles = true; + + /** + * @psalm-param array<callable(array): array> $processors + * + * @param string $name The logging channel, a simple descriptive name that is attached to all log records + * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc. + * @param callable[] $processors Optional array of processors + * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used + */ + public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null) + { + $this->name = $name; + $this->setHandlers($handlers); + $this->processors = $processors; + $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC'); + + if (\PHP_VERSION_ID >= 80100) { + // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412 + /** @var \WeakMap<\Fiber, int> $fiberLogDepth */ + $fiberLogDepth = new \WeakMap(); + $this->fiberLogDepth = $fiberLogDepth; + } + } + + public function getName(): string + { + return $this->name; + } + + /** + * Return a new cloned instance with the name changed + */ + public function withName(string $name): self + { + $new = clone $this; + $new->name = $name; + + return $new; + } + + /** + * Pushes a handler on to the stack. + */ + public function pushHandler(HandlerInterface $handler): self + { + array_unshift($this->handlers, $handler); + + return $this; + } + + /** + * Pops a handler from the stack + * + * @throws \LogicException If empty handler stack + */ + public function popHandler(): HandlerInterface + { + if (!$this->handlers) { + throw new \LogicException('You tried to pop from an empty handler stack.'); + } + + return array_shift($this->handlers); + } + + /** + * Set handlers, replacing all existing ones. + * + * If a map is passed, keys will be ignored. + * + * @param HandlerInterface[] $handlers + */ + public function setHandlers(array $handlers): self + { + $this->handlers = []; + foreach (array_reverse($handlers) as $handler) { + $this->pushHandler($handler); + } + + return $this; + } + + /** + * @return HandlerInterface[] + */ + public function getHandlers(): array + { + return $this->handlers; + } + + /** + * Adds a processor on to the stack. + */ + public function pushProcessor(callable $callback): self + { + array_unshift($this->processors, $callback); + + return $this; + } + + /** + * Removes the processor on top of the stack and returns it. + * + * @throws \LogicException If empty processor stack + * @return callable + */ + public function popProcessor(): callable + { + if (!$this->processors) { + throw new \LogicException('You tried to pop from an empty processor stack.'); + } + + return array_shift($this->processors); + } + + /** + * @return callable[] + */ + public function getProcessors(): array + { + return $this->processors; + } + + /** + * Control the use of microsecond resolution timestamps in the 'datetime' + * member of new records. + * + * As of PHP7.1 microseconds are always included by the engine, so + * there is no performance penalty and Monolog 2 enabled microseconds + * by default. This function lets you disable them though in case you want + * to suppress microseconds from the output. + * + * @param bool $micro True to use microtime() to create timestamps + */ + public function useMicrosecondTimestamps(bool $micro): self + { + $this->microsecondTimestamps = $micro; + + return $this; + } + + public function useLoggingLoopDetection(bool $detectCycles): self + { + $this->detectCycles = $detectCycles; + + return $this; + } + + /** + * Adds a log record. + * + * @param int $level The logging level (a Monolog or RFC 5424 level) + * @param string $message The log message + * @param mixed[] $context The log context + * @param DateTimeImmutable $datetime Optional log date to log into the past or future + * @return bool Whether the record has been processed + * + * @phpstan-param Level $level + */ + public function addRecord(int $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool + { + if (isset(self::RFC_5424_LEVELS[$level])) { + $level = self::RFC_5424_LEVELS[$level]; + } + + if ($this->detectCycles) { + if (\PHP_VERSION_ID >= 80100 && $fiber = \Fiber::getCurrent()) { + $this->fiberLogDepth[$fiber] = $this->fiberLogDepth[$fiber] ?? 0; + $logDepth = ++$this->fiberLogDepth[$fiber]; + } else { + $logDepth = ++$this->logDepth; + } + } else { + $logDepth = 0; + } + + if ($logDepth === 3) { + $this->warning('A possible infinite logging loop was detected and aborted. It appears some of your handler code is triggering logging, see the previous log record for a hint as to what may be the cause.'); + return false; + } elseif ($logDepth >= 5) { // log depth 4 is let through, so we can log the warning above + return false; + } + + try { + $record = null; + + foreach ($this->handlers as $handler) { + if (null === $record) { + // skip creating the record as long as no handler is going to handle it + if (!$handler->isHandling(['level' => $level])) { + continue; + } + + $levelName = static::getLevelName($level); + + $record = [ + 'message' => $message, + 'context' => $context, + 'level' => $level, + 'level_name' => $levelName, + 'channel' => $this->name, + 'datetime' => $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), + 'extra' => [], + ]; + + try { + foreach ($this->processors as $processor) { + $record = $processor($record); + } + } catch (Throwable $e) { + $this->handleException($e, $record); + + return true; + } + } + + // once the record exists, send it to all handlers as long as the bubbling chain is not interrupted + try { + if (true === $handler->handle($record)) { + break; + } + } catch (Throwable $e) { + $this->handleException($e, $record); + + return true; + } + } + } finally { + if ($this->detectCycles) { + if (isset($fiber)) { + $this->fiberLogDepth[$fiber]--; + } else { + $this->logDepth--; + } + } + } + + return null !== $record; + } + + /** + * Ends a log cycle and frees all resources used by handlers. + * + * Closing a Handler means flushing all buffers and freeing any open resources/handles. + * Handlers that have been closed should be able to accept log records again and re-open + * themselves on demand, but this may not always be possible depending on implementation. + * + * This is useful at the end of a request and will be called automatically on every handler + * when they get destructed. + */ + public function close(): void + { + foreach ($this->handlers as $handler) { + $handler->close(); + } + } + + /** + * Ends a log cycle and resets all handlers and processors to their initial state. + * + * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal + * state, and getting it back to a state in which it can receive log records again. + * + * This is useful in case you want to avoid logs leaking between two requests or jobs when you + * have a long running process like a worker or an application server serving multiple requests + * in one process. + */ + public function reset(): void + { + foreach ($this->handlers as $handler) { + if ($handler instanceof ResettableInterface) { + $handler->reset(); + } + } + + foreach ($this->processors as $processor) { + if ($processor instanceof ResettableInterface) { + $processor->reset(); + } + } + } + + /** + * Gets all supported logging levels. + * + * @return array<string, int> Assoc array with human-readable level names => level codes. + * @phpstan-return array<LevelName, Level> + */ + public static function getLevels(): array + { + return array_flip(static::$levels); + } + + /** + * Gets the name of the logging level. + * + * @throws \Psr\Log\InvalidArgumentException If level is not defined + * + * @phpstan-param Level $level + * @phpstan-return LevelName + */ + public static function getLevelName(int $level): string + { + if (!isset(static::$levels[$level])) { + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels))); + } + + return static::$levels[$level]; + } + + /** + * Converts PSR-3 levels to Monolog ones if necessary + * + * @param string|int $level Level number (monolog) or name (PSR-3) + * @throws \Psr\Log\InvalidArgumentException If level is not defined + * + * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-return Level + */ + public static function toMonologLevel($level): int + { + if (is_string($level)) { + if (is_numeric($level)) { + /** @phpstan-ignore-next-line */ + return intval($level); + } + + // Contains chars of all log levels and avoids using strtoupper() which may have + // strange results depending on locale (for example, "i" will become "İ" in Turkish locale) + $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY'); + if (defined(__CLASS__.'::'.$upper)) { + return constant(__CLASS__ . '::' . $upper); + } + + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); + } + + if (!is_int($level)) { + throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); + } + + return $level; + } + + /** + * Checks whether the Logger has a handler that listens on the given level + * + * @phpstan-param Level $level + */ + public function isHandling(int $level): bool + { + $record = [ + 'level' => $level, + ]; + + foreach ($this->handlers as $handler) { + if ($handler->isHandling($record)) { + return true; + } + } + + return false; + } + + /** + * Set a custom exception handler that will be called if adding a new record fails + * + * The callable will receive an exception object and the record that failed to be logged + */ + public function setExceptionHandler(?callable $callback): self + { + $this->exceptionHandler = $callback; + + return $this; + } + + public function getExceptionHandler(): ?callable + { + return $this->exceptionHandler; + } + + /** + * Adds a log record at an arbitrary level. + * + * This method allows for compatibility with common interfaces. + * + * @param mixed $level The log level (a Monolog, PSR-3 or RFC 5424 level) + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function log($level, $message, array $context = []): void + { + if (!is_int($level) && !is_string($level)) { + throw new \InvalidArgumentException('$level is expected to be a string or int'); + } + + if (isset(self::RFC_5424_LEVELS[$level])) { + $level = self::RFC_5424_LEVELS[$level]; + } + + $level = static::toMonologLevel($level); + + $this->addRecord($level, (string) $message, $context); + } + + /** + * Adds a log record at the DEBUG level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function debug($message, array $context = []): void + { + $this->addRecord(static::DEBUG, (string) $message, $context); + } + + /** + * Adds a log record at the INFO level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function info($message, array $context = []): void + { + $this->addRecord(static::INFO, (string) $message, $context); + } + + /** + * Adds a log record at the NOTICE level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function notice($message, array $context = []): void + { + $this->addRecord(static::NOTICE, (string) $message, $context); + } + + /** + * Adds a log record at the WARNING level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function warning($message, array $context = []): void + { + $this->addRecord(static::WARNING, (string) $message, $context); + } + + /** + * Adds a log record at the ERROR level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function error($message, array $context = []): void + { + $this->addRecord(static::ERROR, (string) $message, $context); + } + + /** + * Adds a log record at the CRITICAL level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function critical($message, array $context = []): void + { + $this->addRecord(static::CRITICAL, (string) $message, $context); + } + + /** + * Adds a log record at the ALERT level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function alert($message, array $context = []): void + { + $this->addRecord(static::ALERT, (string) $message, $context); + } + + /** + * Adds a log record at the EMERGENCY level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function emergency($message, array $context = []): void + { + $this->addRecord(static::EMERGENCY, (string) $message, $context); + } + + /** + * Sets the timezone to be used for the timestamp of log records. + */ + public function setTimezone(DateTimeZone $tz): self + { + $this->timezone = $tz; + + return $this; + } + + /** + * Returns the timezone to be used for the timestamp of log records. + */ + public function getTimezone(): DateTimeZone + { + return $this->timezone; + } + + /** + * Delegates exception management to the custom exception handler, + * or throws the exception if no custom handler is set. + * + * @param array $record + * @phpstan-param Record $record + */ + protected function handleException(Throwable $e, array $record): void + { + if (!$this->exceptionHandler) { + throw $e; + } + + ($this->exceptionHandler)($e, $record); + } + + /** + * @return array<string, mixed> + */ + public function __serialize(): array + { + return [ + 'name' => $this->name, + 'handlers' => $this->handlers, + 'processors' => $this->processors, + 'microsecondTimestamps' => $this->microsecondTimestamps, + 'timezone' => $this->timezone, + 'exceptionHandler' => $this->exceptionHandler, + 'logDepth' => $this->logDepth, + 'detectCycles' => $this->detectCycles, + ]; + } + + /** + * @param array<string, mixed> $data + */ + public function __unserialize(array $data): void + { + foreach (['name', 'handlers', 'processors', 'microsecondTimestamps', 'timezone', 'exceptionHandler', 'logDepth', 'detectCycles'] as $property) { + if (isset($data[$property])) { + $this->$property = $data[$property]; + } + } + + if (\PHP_VERSION_ID >= 80100) { + // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412 + /** @var \WeakMap<\Fiber, int> $fiberLogDepth */ + $fiberLogDepth = new \WeakMap(); + $this->fiberLogDepth = $fiberLogDepth; + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php new file mode 100644 index 0000000..8166bdc --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php @@ -0,0 +1,77 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Injects Git branch and Git commit SHA in all records + * + * @author Nick Otter + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class GitProcessor implements ProcessorInterface +{ + /** @var int */ + private $level; + /** @var array{branch: string, commit: string}|array<never>|null */ + private static $cache = null; + + /** + * @param string|int $level The minimum logging level at which this Processor will be triggered + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function __construct($level = Logger::DEBUG) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + // return if the level is not high enough + if ($record['level'] < $this->level) { + return $record; + } + + $record['extra']['git'] = self::getGitInfo(); + + return $record; + } + + /** + * @return array{branch: string, commit: string}|array<never> + */ + private static function getGitInfo(): array + { + if (self::$cache) { + return self::$cache; + } + + $branches = `git branch -v --no-abbrev`; + if ($branches && preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { + return self::$cache = [ + 'branch' => $matches[1], + 'commit' => $matches[2], + ]; + } + + return self::$cache = []; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php new file mode 100644 index 0000000..91fda7d --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php @@ -0,0 +1,36 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects value of gethostname in all records + */ +class HostnameProcessor implements ProcessorInterface +{ + /** @var string */ + private static $host; + + public function __construct() + { + self::$host = (string) gethostname(); + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + $record['extra']['hostname'] = self::$host; + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php new file mode 100644 index 0000000..a32e76b --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php @@ -0,0 +1,123 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Injects line/file:class/function where the log message came from + * + * Warning: This only works if the handler processes the logs directly. + * If you put the processor on a handler that is behind a FingersCrossedHandler + * for example, the processor will only be called once the trigger level is reached, + * and all the log records will have the same file/line/.. data from the call that + * triggered the FingersCrossedHandler. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class IntrospectionProcessor implements ProcessorInterface +{ + /** @var int */ + private $level; + /** @var string[] */ + private $skipClassesPartials; + /** @var int */ + private $skipStackFramesCount; + /** @var string[] */ + private $skipFunctions = [ + 'call_user_func', + 'call_user_func_array', + ]; + + /** + * @param string|int $level The minimum logging level at which this Processor will be triggered + * @param string[] $skipClassesPartials + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], int $skipStackFramesCount = 0) + { + $this->level = Logger::toMonologLevel($level); + $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials); + $this->skipStackFramesCount = $skipStackFramesCount; + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + // return if the level is not high enough + if ($record['level'] < $this->level) { + return $record; + } + + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + + // skip first since it's always the current method + array_shift($trace); + // the call_user_func call is also skipped + array_shift($trace); + + $i = 0; + + while ($this->isTraceClassOrSkippedFunction($trace, $i)) { + if (isset($trace[$i]['class'])) { + foreach ($this->skipClassesPartials as $part) { + if (strpos($trace[$i]['class'], $part) !== false) { + $i++; + + continue 2; + } + } + } elseif (in_array($trace[$i]['function'], $this->skipFunctions)) { + $i++; + + continue; + } + + break; + } + + $i += $this->skipStackFramesCount; + + // we should have the call source now + $record['extra'] = array_merge( + $record['extra'], + [ + 'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null, + 'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null, + 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null, + 'callType' => isset($trace[$i]['type']) ? $trace[$i]['type'] : null, + 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null, + ] + ); + + return $record; + } + + /** + * @param array[] $trace + */ + private function isTraceClassOrSkippedFunction(array $trace, int $index): bool + { + if (!isset($trace[$index])) { + return false; + } + + return isset($trace[$index]['class']) || in_array($trace[$index]['function'], $this->skipFunctions); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php new file mode 100644 index 0000000..37c756f --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects memory_get_peak_usage in all records + * + * @see Monolog\Processor\MemoryProcessor::__construct() for options + * @author Rob Jensen + */ +class MemoryPeakUsageProcessor extends MemoryProcessor +{ + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + $usage = memory_get_peak_usage($this->realUsage); + + if ($this->useFormatting) { + $usage = $this->formatBytes($usage); + } + + $record['extra']['memory_peak_usage'] = $usage; + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php new file mode 100644 index 0000000..227deb7 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php @@ -0,0 +1,61 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Some methods that are common for all memory processors + * + * @author Rob Jensen + */ +abstract class MemoryProcessor implements ProcessorInterface +{ + /** + * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported. + */ + protected $realUsage; + + /** + * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size) + */ + protected $useFormatting; + + /** + * @param bool $realUsage Set this to true to get the real size of memory allocated from system. + * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size) + */ + public function __construct(bool $realUsage = true, bool $useFormatting = true) + { + $this->realUsage = $realUsage; + $this->useFormatting = $useFormatting; + } + + /** + * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is + * + * @param int $bytes + * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int + */ + protected function formatBytes(int $bytes) + { + if (!$this->useFormatting) { + return $bytes; + } + + if ($bytes > 1024 * 1024) { + return round($bytes / 1024 / 1024, 2).' MB'; + } elseif ($bytes > 1024) { + return round($bytes / 1024, 2).' KB'; + } + + return $bytes . ' B'; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php new file mode 100644 index 0000000..e141921 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects memory_get_usage in all records + * + * @see Monolog\Processor\MemoryProcessor::__construct() for options + * @author Rob Jensen + */ +class MemoryUsageProcessor extends MemoryProcessor +{ + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + $usage = memory_get_usage($this->realUsage); + + if ($this->useFormatting) { + $usage = $this->formatBytes($usage); + } + + $record['extra']['memory_usage'] = $usage; + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php new file mode 100644 index 0000000..d4a628f --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php @@ -0,0 +1,77 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Injects Hg branch and Hg revision number in all records + * + * @author Jonathan A. Schweder <jonathanschweder@gmail.com> + * + * @phpstan-import-type LevelName from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + */ +class MercurialProcessor implements ProcessorInterface +{ + /** @var Level */ + private $level; + /** @var array{branch: string, revision: string}|array<never>|null */ + private static $cache = null; + + /** + * @param int|string $level The minimum logging level at which this Processor will be triggered + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function __construct($level = Logger::DEBUG) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + // return if the level is not high enough + if ($record['level'] < $this->level) { + return $record; + } + + $record['extra']['hg'] = self::getMercurialInfo(); + + return $record; + } + + /** + * @return array{branch: string, revision: string}|array<never> + */ + private static function getMercurialInfo(): array + { + if (self::$cache) { + return self::$cache; + } + + $result = explode(' ', trim(`hg id -nb`)); + + if (count($result) >= 3) { + return self::$cache = [ + 'branch' => $result[1], + 'revision' => $result[2], + ]; + } + + return self::$cache = []; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php new file mode 100644 index 0000000..3b939a9 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Adds value of getmypid into records + * + * @author Andreas Hörnicke + */ +class ProcessIdProcessor implements ProcessorInterface +{ + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + $record['extra']['process_id'] = getmypid(); + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php new file mode 100644 index 0000000..5defb7e --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * An optional interface to allow labelling Monolog processors. + * + * @author Nicolas Grekas <p@tchwork.com> + * + * @phpstan-import-type Record from \Monolog\Logger + */ +interface ProcessorInterface +{ + /** + * @return array The processed record + * + * @phpstan-param Record $record + * @phpstan-return Record + */ + public function __invoke(array $record); +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php new file mode 100644 index 0000000..e7c1217 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php @@ -0,0 +1,88 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Utils; + +/** + * Processes a record's message according to PSR-3 rules + * + * It replaces {foo} with the value from $context['foo'] + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class PsrLogMessageProcessor implements ProcessorInterface +{ + public const SIMPLE_DATE = "Y-m-d\TH:i:s.uP"; + + /** @var string|null */ + private $dateFormat; + + /** @var bool */ + private $removeUsedContextFields; + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $removeUsedContextFields If set to true the fields interpolated into message gets unset + */ + public function __construct(?string $dateFormat = null, bool $removeUsedContextFields = false) + { + $this->dateFormat = $dateFormat; + $this->removeUsedContextFields = $removeUsedContextFields; + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + if (false === strpos($record['message'], '{')) { + return $record; + } + + $replacements = []; + foreach ($record['context'] as $key => $val) { + $placeholder = '{' . $key . '}'; + if (strpos($record['message'], $placeholder) === false) { + continue; + } + + if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { + $replacements[$placeholder] = $val; + } elseif ($val instanceof \DateTimeInterface) { + if (!$this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) { + // handle monolog dates using __toString if no specific dateFormat was asked for + // so that it follows the useMicroseconds flag + $replacements[$placeholder] = (string) $val; + } else { + $replacements[$placeholder] = $val->format($this->dateFormat ?: static::SIMPLE_DATE); + } + } elseif ($val instanceof \UnitEnum) { + $replacements[$placeholder] = $val instanceof \BackedEnum ? $val->value : $val->name; + } elseif (is_object($val)) { + $replacements[$placeholder] = '[object '.Utils::getClass($val).']'; + } elseif (is_array($val)) { + $replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true); + } else { + $replacements[$placeholder] = '['.gettype($val).']'; + } + + if ($this->removeUsedContextFields) { + unset($record['context'][$key]); + } + } + + $record['message'] = strtr($record['message'], $replacements); + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php new file mode 100644 index 0000000..80f1874 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php @@ -0,0 +1,61 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Adds a tags array into record + * + * @author Martijn Riemers + */ +class TagProcessor implements ProcessorInterface +{ + /** @var string[] */ + private $tags; + + /** + * @param string[] $tags + */ + public function __construct(array $tags = []) + { + $this->setTags($tags); + } + + /** + * @param string[] $tags + */ + public function addTags(array $tags = []): self + { + $this->tags = array_merge($this->tags, $tags); + + return $this; + } + + /** + * @param string[] $tags + */ + public function setTags(array $tags = []): self + { + $this->tags = $tags; + + return $this; + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + $record['extra']['tags'] = $this->tags; + + return $record; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php new file mode 100644 index 0000000..a27b74d --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php @@ -0,0 +1,59 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\ResettableInterface; + +/** + * Adds a unique identifier into records + * + * @author Simon Mönch <sm@webfactory.de> + */ +class UidProcessor implements ProcessorInterface, ResettableInterface +{ + /** @var string */ + private $uid; + + public function __construct(int $length = 7) + { + if ($length > 32 || $length < 1) { + throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32'); + } + + $this->uid = $this->generateUid($length); + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + $record['extra']['uid'] = $this->uid; + + return $record; + } + + public function getUid(): string + { + return $this->uid; + } + + public function reset() + { + $this->uid = $this->generateUid(strlen($this->uid)); + } + + private function generateUid(int $length): string + { + return substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php new file mode 100644 index 0000000..51850e1 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php @@ -0,0 +1,111 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects url/method and remote IP of the current web request in all records + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class WebProcessor implements ProcessorInterface +{ + /** + * @var array<string, mixed>|\ArrayAccess<string, mixed> + */ + protected $serverData; + + /** + * Default fields + * + * Array is structured as [key in record.extra => key in $serverData] + * + * @var array<string, string> + */ + protected $extraFields = [ + 'url' => 'REQUEST_URI', + 'ip' => 'REMOTE_ADDR', + 'http_method' => 'REQUEST_METHOD', + 'server' => 'SERVER_NAME', + 'referrer' => 'HTTP_REFERER', + 'user_agent' => 'HTTP_USER_AGENT', + ]; + + /** + * @param array<string, mixed>|\ArrayAccess<string, mixed>|null $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data + * @param array<string, string>|array<string>|null $extraFields Field names and the related key inside $serverData to be added (or just a list of field names to use the default configured $serverData mapping). If not provided it defaults to: [url, ip, http_method, server, referrer] + unique_id if present in server data + */ + public function __construct($serverData = null, array $extraFields = null) + { + if (null === $serverData) { + $this->serverData = &$_SERVER; + } elseif (is_array($serverData) || $serverData instanceof \ArrayAccess) { + $this->serverData = $serverData; + } else { + throw new \UnexpectedValueException('$serverData must be an array or object implementing ArrayAccess.'); + } + + $defaultEnabled = ['url', 'ip', 'http_method', 'server', 'referrer']; + if (isset($this->serverData['UNIQUE_ID'])) { + $this->extraFields['unique_id'] = 'UNIQUE_ID'; + $defaultEnabled[] = 'unique_id'; + } + + if (null === $extraFields) { + $extraFields = $defaultEnabled; + } + if (isset($extraFields[0])) { + foreach (array_keys($this->extraFields) as $fieldName) { + if (!in_array($fieldName, $extraFields)) { + unset($this->extraFields[$fieldName]); + } + } + } else { + $this->extraFields = $extraFields; + } + } + + /** + * {@inheritDoc} + */ + public function __invoke(array $record): array + { + // skip processing if for some reason request data + // is not present (CLI or wonky SAPIs) + if (!isset($this->serverData['REQUEST_URI'])) { + return $record; + } + + $record['extra'] = $this->appendExtraFields($record['extra']); + + return $record; + } + + public function addExtraField(string $extraName, string $serverName): self + { + $this->extraFields[$extraName] = $serverName; + + return $this; + } + + /** + * @param mixed[] $extra + * @return mixed[] + */ + private function appendExtraFields(array $extra): array + { + foreach ($this->extraFields as $extraName => $serverName) { + $extra[$extraName] = $this->serverData[$serverName] ?? null; + } + + return $extra; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Registry.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Registry.php new file mode 100644 index 0000000..ae94ae6 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Registry.php @@ -0,0 +1,134 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use InvalidArgumentException; + +/** + * Monolog log registry + * + * Allows to get `Logger` instances in the global scope + * via static method calls on this class. + * + * <code> + * $application = new Monolog\Logger('application'); + * $api = new Monolog\Logger('api'); + * + * Monolog\Registry::addLogger($application); + * Monolog\Registry::addLogger($api); + * + * function testLogger() + * { + * Monolog\Registry::api()->error('Sent to $api Logger instance'); + * Monolog\Registry::application()->error('Sent to $application Logger instance'); + * } + * </code> + * + * @author Tomas Tatarko <tomas@tatarko.sk> + */ +class Registry +{ + /** + * List of all loggers in the registry (by named indexes) + * + * @var Logger[] + */ + private static $loggers = []; + + /** + * Adds new logging channel to the registry + * + * @param Logger $logger Instance of the logging channel + * @param string|null $name Name of the logging channel ($logger->getName() by default) + * @param bool $overwrite Overwrite instance in the registry if the given name already exists? + * @throws \InvalidArgumentException If $overwrite set to false and named Logger instance already exists + * @return void + */ + public static function addLogger(Logger $logger, ?string $name = null, bool $overwrite = false) + { + $name = $name ?: $logger->getName(); + + if (isset(self::$loggers[$name]) && !$overwrite) { + throw new InvalidArgumentException('Logger with the given name already exists'); + } + + self::$loggers[$name] = $logger; + } + + /** + * Checks if such logging channel exists by name or instance + * + * @param string|Logger $logger Name or logger instance + */ + public static function hasLogger($logger): bool + { + if ($logger instanceof Logger) { + $index = array_search($logger, self::$loggers, true); + + return false !== $index; + } + + return isset(self::$loggers[$logger]); + } + + /** + * Removes instance from registry by name or instance + * + * @param string|Logger $logger Name or logger instance + */ + public static function removeLogger($logger): void + { + if ($logger instanceof Logger) { + if (false !== ($idx = array_search($logger, self::$loggers, true))) { + unset(self::$loggers[$idx]); + } + } else { + unset(self::$loggers[$logger]); + } + } + + /** + * Clears the registry + */ + public static function clear(): void + { + self::$loggers = []; + } + + /** + * Gets Logger instance from the registry + * + * @param string $name Name of the requested Logger instance + * @throws \InvalidArgumentException If named Logger instance is not in the registry + */ + public static function getInstance($name): Logger + { + if (!isset(self::$loggers[$name])) { + throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name)); + } + + return self::$loggers[$name]; + } + + /** + * Gets Logger instance from the registry via static method call + * + * @param string $name Name of the requested Logger instance + * @param mixed[] $arguments Arguments passed to static method call + * @throws \InvalidArgumentException If named Logger instance is not in the registry + * @return Logger Requested instance of Logger + */ + public static function __callStatic($name, $arguments) + { + return self::getInstance($name); + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/ResettableInterface.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/ResettableInterface.php new file mode 100644 index 0000000..2c5fd78 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/ResettableInterface.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +/** + * Handler or Processor implementing this interface will be reset when Logger::reset() is called. + * + * Resetting ends a log cycle gets them back to their initial state. + * + * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal + * state, and getting it back to a state in which it can receive log records again. + * + * This is useful in case you want to avoid logs leaking between two requests or jobs when you + * have a long running process like a worker or an application server serving multiple requests + * in one process. + * + * @author Grégoire Pineau <lyrixx@lyrixx.info> + */ +interface ResettableInterface +{ + /** + * @return void + */ + public function reset(); +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/SignalHandler.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/SignalHandler.php new file mode 100644 index 0000000..d730eea --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/SignalHandler.php @@ -0,0 +1,120 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; +use ReflectionExtension; + +/** + * Monolog POSIX signal handler + * + * @author Robert Gust-Bardon <robert@gust-bardon.org> + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger + */ +class SignalHandler +{ + /** @var LoggerInterface */ + private $logger; + + /** @var array<int, callable|string|int> SIG_DFL, SIG_IGN or previous callable */ + private $previousSignalHandler = []; + /** @var array<int, int> */ + private $signalLevelMap = []; + /** @var array<int, bool> */ + private $signalRestartSyscalls = []; + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** + * @param int|string $level Level or level name + * @param bool $callPrevious + * @param bool $restartSyscalls + * @param bool|null $async + * @return $this + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function registerSignalHandler(int $signo, $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self + { + if (!extension_loaded('pcntl') || !function_exists('pcntl_signal')) { + return $this; + } + + $level = Logger::toMonologLevel($level); + + if ($callPrevious) { + $handler = pcntl_signal_get_handler($signo); + $this->previousSignalHandler[$signo] = $handler; + } else { + unset($this->previousSignalHandler[$signo]); + } + $this->signalLevelMap[$signo] = $level; + $this->signalRestartSyscalls[$signo] = $restartSyscalls; + + if ($async !== null) { + pcntl_async_signals($async); + } + + pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls); + + return $this; + } + + /** + * @param mixed $siginfo + */ + public function handleSignal(int $signo, $siginfo = null): void + { + static $signals = []; + + if (!$signals && extension_loaded('pcntl')) { + $pcntl = new ReflectionExtension('pcntl'); + // HHVM 3.24.2 returns an empty array. + foreach ($pcntl->getConstants() ?: get_defined_constants(true)['Core'] as $name => $value) { + if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && is_int($value)) { + $signals[$value] = $name; + } + } + } + + $level = $this->signalLevelMap[$signo] ?? LogLevel::CRITICAL; + $signal = $signals[$signo] ?? $signo; + $context = $siginfo ?? []; + $this->logger->log($level, sprintf('Program received signal %s', $signal), $context); + + if (!isset($this->previousSignalHandler[$signo])) { + return; + } + + if ($this->previousSignalHandler[$signo] === SIG_DFL) { + if (extension_loaded('pcntl') && function_exists('pcntl_signal') && function_exists('pcntl_sigprocmask') && function_exists('pcntl_signal_dispatch') + && extension_loaded('posix') && function_exists('posix_getpid') && function_exists('posix_kill') + ) { + $restartSyscalls = $this->signalRestartSyscalls[$signo] ?? true; + pcntl_signal($signo, SIG_DFL, $restartSyscalls); + pcntl_sigprocmask(SIG_UNBLOCK, [$signo], $oldset); + posix_kill(posix_getpid(), $signo); + pcntl_signal_dispatch(); + pcntl_sigprocmask(SIG_SETMASK, $oldset); + pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls); + } + } elseif (is_callable($this->previousSignalHandler[$signo])) { + $this->previousSignalHandler[$signo]($signo, $siginfo); + } + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Test/TestCase.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Test/TestCase.php new file mode 100644 index 0000000..bc0b425 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Test/TestCase.php @@ -0,0 +1,85 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Test; + +use Monolog\Logger; +use Monolog\DateTimeImmutable; +use Monolog\Formatter\FormatterInterface; + +/** + * Lets you easily generate log records and a dummy formatter for testing purposes + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @phpstan-import-type Record from \Monolog\Logger + * @phpstan-import-type Level from \Monolog\Logger + * + * @internal feel free to reuse this to test your own handlers, this is marked internal to avoid issues with PHPStorm https://github.com/Seldaek/monolog/issues/1677 + */ +class TestCase extends \PHPUnit\Framework\TestCase +{ + public function tearDown(): void + { + parent::tearDown(); + + if (isset($this->handler)) { + unset($this->handler); + } + } + + /** + * @param mixed[] $context + * + * @return array Record + * + * @phpstan-param Level $level + * @phpstan-return Record + */ + protected function getRecord(int $level = Logger::WARNING, string $message = 'test', array $context = []): array + { + return [ + 'message' => (string) $message, + 'context' => $context, + 'level' => $level, + 'level_name' => Logger::getLevelName($level), + 'channel' => 'test', + 'datetime' => new DateTimeImmutable(true), + 'extra' => [], + ]; + } + + /** + * @phpstan-return Record[] + */ + protected function getMultipleRecords(): array + { + return [ + $this->getRecord(Logger::DEBUG, 'debug message 1'), + $this->getRecord(Logger::DEBUG, 'debug message 2'), + $this->getRecord(Logger::INFO, 'information'), + $this->getRecord(Logger::WARNING, 'warning'), + $this->getRecord(Logger::ERROR, 'error'), + ]; + } + + protected function getIdentityFormatter(): FormatterInterface + { + $formatter = $this->createMock(FormatterInterface::class); + $formatter->expects($this->any()) + ->method('format') + ->will($this->returnCallback(function ($record) { + return $record['message']; + })); + + return $formatter; + } +} diff --git a/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Utils.php b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Utils.php new file mode 100644 index 0000000..360c421 --- /dev/null +++ b/php/libraries/composer/vendor/monolog/monolog/src/Monolog/Utils.php @@ -0,0 +1,284 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +final class Utils +{ + const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; + + public static function getClass(object $object): string + { + $class = \get_class($object); + + if (false === ($pos = \strpos($class, "@anonymous\0"))) { + return $class; + } + + if (false === ($parent = \get_parent_class($class))) { + return \substr($class, 0, $pos + 10); + } + + return $parent . '@anonymous'; + } + + public static function substr(string $string, int $start, ?int $length = null): string + { + if (extension_loaded('mbstring')) { + return mb_strcut($string, $start, $length); + } + + return substr($string, $start, (null === $length) ? strlen($string) : $length); + } + + /** + * Makes sure if a relative path is passed in it is turned into an absolute path + * + * @param string $streamUrl stream URL or path without protocol + */ + public static function canonicalizePath(string $streamUrl): string + { + $prefix = ''; + if ('file://' === substr($streamUrl, 0, 7)) { + $streamUrl = substr($streamUrl, 7); + $prefix = 'file://'; + } + + // other type of stream, not supported + if (false !== strpos($streamUrl, '://')) { + return $streamUrl; + } + + // already absolute + if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') { + return $prefix.$streamUrl; + } + + $streamUrl = getcwd() . '/' . $streamUrl; + + return $prefix.$streamUrl; + } + + /** + * Return the JSON representation of a value + * + * @param mixed $data + * @param int $encodeFlags flags to pass to json encode, defaults to DEFAULT_JSON_FLAGS + * @param bool $ignoreErrors whether to ignore encoding errors or to throw on error, when ignored and the encoding fails, "null" is returned which is valid json for null + * @throws \RuntimeException if encoding fails and errors are not ignored + * @return string when errors are ignored and the encoding fails, "null" is returned which is valid json for null + */ + public static function jsonEncode($data, ?int $encodeFlags = null, bool $ignoreErrors = false): string + { + if (null === $encodeFlags) { + $encodeFlags = self::DEFAULT_JSON_FLAGS; + } + + if ($ignoreErrors) { + $json = @json_encode($data, $encodeFlags); + if (false === $json) { + return 'null'; + } + + return $json; + } + + $json = json_encode($data, $encodeFlags); + if (false === $json) { + $json = self::handleJsonError(json_last_error(), $data); + } + + return $json; + } + + /** + * Handle a json_encode failure. + * + * If the failure is due to invalid string encoding, try to clean the + * input and encode again. If the second encoding attempt fails, the + * initial error is not encoding related or the input can't be cleaned then + * raise a descriptive exception. + * + * @param int $code return code of json_last_error function + * @param mixed $data data that was meant to be encoded + * @param int $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION + * @throws \RuntimeException if failure can't be corrected + * @return string JSON encoded data after error correction + */ + public static function handleJsonError(int $code, $data, ?int $encodeFlags = null): string + { + if ($code !== JSON_ERROR_UTF8) { + self::throwEncodeError($code, $data); + } + + if (is_string($data)) { + self::detectAndCleanUtf8($data); + } elseif (is_array($data)) { + array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8')); + } else { + self::throwEncodeError($code, $data); + } + + if (null === $encodeFlags) { + $encodeFlags = self::DEFAULT_JSON_FLAGS; + } + + $json = json_encode($data, $encodeFlags); + + if ($json === false) { + self::throwEncodeError(json_last_error(), $data); + } + + return $json; + } + + /** + * @internal + */ + public static function pcreLastErrorMessage(int $code): string + { + if (PHP_VERSION_ID >= 80000) { + return preg_last_error_msg(); + } + + $constants = (get_defined_constants(true))['pcre']; + $constants = array_filter($constants, function ($key) { + return substr($key, -6) == '_ERROR'; + }, ARRAY_FILTER_USE_KEY); + + $constants = array_flip($constants); + + return $constants[$code] ?? 'UNDEFINED_ERROR'; + } + + /** + * Throws an exception according to a given code with a customized message + * + * @param int $code return code of json_last_error function + * @param mixed $data data that was meant to be encoded + * @throws \RuntimeException + * + * @return never + */ + private static function throwEncodeError(int $code, $data): void + { + switch ($code) { + case JSON_ERROR_DEPTH: + $msg = 'Maximum stack depth exceeded'; + break; + case JSON_ERROR_STATE_MISMATCH: + $msg = 'Underflow or the modes mismatch'; + break; + case JSON_ERROR_CTRL_CHAR: + $msg = 'Unexpected control character found'; + break; + case JSON_ERROR_UTF8: + $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; + break; + default: + $msg = 'Unknown error'; + } + + throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true)); + } + + /** + * Detect invalid UTF-8 string characters and convert to valid UTF-8. + * + * Valid UTF-8 input will be left unmodified, but strings containing + * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed + * original encoding of ISO-8859-15. This conversion may result in + * incorrect output if the actual encoding was not ISO-8859-15, but it + * will be clean UTF-8 output and will not rely on expensive and fragile + * detection algorithms. + * + * Function converts the input in place in the passed variable so that it + * can be used as a callback for array_walk_recursive. + * + * @param mixed $data Input to check and convert if needed, passed by ref + */ + private static function detectAndCleanUtf8(&$data): void + { + if (is_string($data) && !preg_match('//u', $data)) { + $data = preg_replace_callback( + '/[\x80-\xFF]+/', + function ($m) { + return function_exists('mb_convert_encoding') ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') : utf8_encode($m[0]); + }, + $data + ); + if (!is_string($data)) { + $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode)); + } + $data = str_replace( + ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'], + ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'], + $data + ); + } + } + + /** + * Converts a string with a valid 'memory_limit' format, to bytes. + * + * @param string|false $val + * @return int|false Returns an integer representing bytes. Returns FALSE in case of error. + */ + public static function expandIniShorthandBytes($val) + { + if (!is_string($val)) { + return false; + } + + // support -1 + if ((int) $val < 0) { + return (int) $val; + } + + if (!preg_match('/^\s*(?<val>\d+)(?:\.\d+)?\s*(?<unit>[gmk]?)\s*$/i', $val, $match)) { + return false; + } + + $val = (int) $match['val']; + switch (strtolower($match['unit'] ?? '')) { + case 'g': + $val *= 1024; + case 'm': + $val *= 1024; + case 'k': + $val *= 1024; + } + + return $val; + } + + /** + * @param array<mixed> $record + */ + public static function getRecordMessageForException(array $record): string + { + $context = ''; + $extra = ''; + try { + if ($record['context']) { + $context = "\nContext: " . json_encode($record['context']); + } + if ($record['extra']) { + $extra = "\nExtra: " . json_encode($record['extra']); + } + } catch (\Throwable $e) { + // noop + } + + return "\nThe exception occurred while attempting to log: " . $record['message'] . $context . $extra; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/.phpstorm.meta.php b/php/libraries/composer/vendor/nesbot/carbon/.phpstorm.meta.php new file mode 100644 index 0000000..bd7c7e0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/.phpstorm.meta.php @@ -0,0 +1,10 @@ +<?php +namespace PHPSTORM_META { + registerArgumentsSet("date_units", "millenania", "millennium", "century", "centuries", "decade", "decades", "year", "years", "y", "yr", "yrs", "quarter", "quarters", "month", "months", "mo", "mos", "week", "weeks", "w", "day", "days", "d", "hour", "hours", "h", "minute", "minutes", "m", "second", "seconds", "s", "millisecond", "milliseconds", "milli", "ms", "microsecond", "microseconds", "micro", "µs"); + expectedArguments(\Carbon\Traits\Units::add(), 0, argumentsSet("date_units")); + expectedArguments(\Carbon\Traits\Units::add(), 1, argumentsSet("date_units")); + expectedArguments(\Carbon\CarbonInterface::add(), 0, argumentsSet("date_units")); + expectedArguments(\Carbon\CarbonInterface::add(), 1, argumentsSet("date_units")); + + expectedArguments(\Carbon\CarbonInterface::getTimeFormatByPrecision(), 0, "minute", "second", "m", "millisecond", "µ", "microsecond", "minutes", "seconds", "ms", "milliseconds", "µs", "microseconds"); +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/LICENSE b/php/libraries/composer/vendor/nesbot/carbon/LICENSE new file mode 100644 index 0000000..6de45eb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) Brian Nesbitt + +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/php/libraries/composer/vendor/nesbot/carbon/bin/carbon b/php/libraries/composer/vendor/nesbot/carbon/bin/carbon new file mode 100755 index 0000000..b53ab73 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/bin/carbon @@ -0,0 +1,23 @@ +#!/usr/bin/env php +<?php + +use Carbon\Cli\Invoker; + +$dir = __DIR__.'/..'; + +if (!file_exists($dir.'/autoload.php')) { + $dir = __DIR__.'/../vendor'; +} + +if (!file_exists($dir.'/autoload.php')) { + $dir = __DIR__.'/../../..'; +} + +if (!file_exists($dir.'/autoload.php')) { + echo 'Autoload not found.'; + exit(1); +} + +require $dir.'/autoload.php'; + +exit((new Invoker())(...$argv) ? 0 : 1); diff --git a/php/libraries/composer/vendor/nesbot/carbon/bin/carbon.bat b/php/libraries/composer/vendor/nesbot/carbon/bin/carbon.bat new file mode 100644 index 0000000..84599d3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/bin/carbon.bat @@ -0,0 +1,4 @@ +@ECHO OFF +setlocal DISABLEDELAYEDEXPANSION +SET BIN_TARGET=%~dp0/carbon +php "%BIN_TARGET%" %* diff --git a/php/libraries/composer/vendor/nesbot/carbon/composer.json b/php/libraries/composer/vendor/nesbot/carbon/composer.json new file mode 100644 index 0000000..48366b5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/composer.json @@ -0,0 +1,127 @@ +{ + "name": "nesbot/carbon", + "description": "An API extension for DateTime that supports 281 different languages.", + "license": "MIT", + "type": "library", + "keywords": [ + "date", + "time", + "DateTime" + ], + "authors": [ + { + "name": "Brian Nesbitt", + "email": "brian@nesbot.com", + "homepage": "https://markido.com" + }, + { + "name": "kylekatarnls", + "homepage": "https://github.com/kylekatarnls" + } + ], + "homepage": "https://carbon.nesbot.com", + "support": { + "issues": "https://github.com/briannesbitt/Carbon/issues", + "source": "https://github.com/briannesbitt/Carbon", + "docs": "https://carbon.nesbot.com/docs" + }, + "funding": [ + { + "url": "https://github.com/sponsors/kylekatarnls", + "type": "github" + }, + { + "url": "https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme", + "type": "tidelift" + }, + { + "url": "https://opencollective.com/Carbon#sponsor", + "type": "opencollective" + } + ], + "require": { + "php": "^7.1.8 || ^8.0", + "ext-json": "*", + "carbonphp/carbon-doctrine-types": "*", + "psr/clock": "^1.0", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.16", + "symfony/translation": "^3.4 || ^4.0 || ^5.0 || ^6.0" + }, + "require-dev": { + "doctrine/dbal": "^2.0 || ^3.1.4 || ^4.0", + "doctrine/orm": "^2.7 || ^3.0", + "friendsofphp/php-cs-fixer": "^3.0", + "kylekatarnls/multi-tester": "^2.0", + "ondrejmirtes/better-reflection": "*", + "phpmd/phpmd": "^2.9", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12.99 || ^1.7.14", + "phpunit/php-file-iterator": "^2.0.5 || ^3.0.6", + "phpunit/phpunit": "^7.5.20 || ^8.5.26 || ^9.5.20", + "squizlabs/php_codesniffer": "^3.4" + }, + "provide": { + "psr/clock-implementation": "1.0" + }, + "minimum-stability": "dev", + "prefer-stable": true, + "autoload": { + "psr-4": { + "Carbon\\": "src/Carbon/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + }, + "files": [ + "tests/Laravel/ServiceProvider.php" + ] + }, + "bin": [ + "bin/carbon" + ], + "config": { + "allow-plugins": { + "phpstan/extension-installer": true, + "composer/package-versions-deprecated": true + }, + "process-timeout": 0, + "sort-packages": true + }, + "extra": { + "branch-alias": { + "dev-3.x": "3.x-dev", + "dev-master": "2.x-dev" + }, + "laravel": { + "providers": [ + "Carbon\\Laravel\\ServiceProvider" + ] + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "scripts": { + "phpcs": "php-cs-fixer fix -v --diff --dry-run", + "phpdoc": "php phpdoc.php", + "phpmd": "phpmd src text /phpmd.xml", + "phpmd-test": "phpmd tests text /tests/phpmd-test.xml", + "phpstan": "phpstan analyse --configuration phpstan.neon", + "phpunit": "phpunit --verbose", + "style-check": [ + "@phpcs", + "@phpstan", + "@phpmd" + ], + "test": [ + "@phpunit", + "@style-check" + ], + "sponsors": "php sponsors.php" + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/extension.neon b/php/libraries/composer/vendor/nesbot/carbon/extension.neon new file mode 100644 index 0000000..33bf794 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/extension.neon @@ -0,0 +1,5 @@ +services: + - + class: Carbon\PHPStan\MacroExtension + tags: + - phpstan.broker.methodsClassReflectionExtension diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php new file mode 100644 index 0000000..c2f4bf0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\MessageFormatter; + +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +if (!class_exists(LazyMessageFormatter::class, false)) { + abstract class LazyMessageFormatter implements MessageFormatterInterface + { + public function format(string $message, string $locale, array $parameters = []): string + { + return $this->formatter->format( + $message, + $this->transformLocale($locale), + $parameters + ); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php new file mode 100644 index 0000000..cbd890d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php @@ -0,0 +1,36 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\MessageFormatter; + +use Symfony\Component\Translation\Formatter\ChoiceMessageFormatterInterface; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +if (!class_exists(LazyMessageFormatter::class, false)) { + abstract class LazyMessageFormatter implements MessageFormatterInterface, ChoiceMessageFormatterInterface + { + abstract protected function transformLocale(?string $locale): ?string; + + public function format($message, $locale, array $parameters = []) + { + return $this->formatter->format( + $message, + $this->transformLocale($locale), + $parameters + ); + } + + public function choiceFormat($message, $number, $locale, array $parameters = []) + { + return $this->formatter->choiceFormat($message, $number, $locale, $parameters); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroBuiltin.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroBuiltin.php new file mode 100644 index 0000000..ba7cf63 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroBuiltin.php @@ -0,0 +1,36 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use PHPStan\BetterReflection\Reflection; +use ReflectionMethod; + +if (!class_exists(AbstractReflectionMacro::class, false)) { + abstract class AbstractReflectionMacro extends AbstractMacro + { + /** + * {@inheritdoc} + */ + public function getReflection(): ?ReflectionMethod + { + if ($this->reflectionFunction instanceof Reflection\ReflectionMethod) { + return new Reflection\Adapter\ReflectionMethod($this->reflectionFunction); + } + + return $this->reflectionFunction instanceof ReflectionMethod + ? $this->reflectionFunction + : null; + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroStatic.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroStatic.php new file mode 100644 index 0000000..bd4c8e8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroStatic.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use PHPStan\BetterReflection\Reflection; +use ReflectionMethod; + +if (!class_exists(AbstractReflectionMacro::class, false)) { + abstract class AbstractReflectionMacro extends AbstractMacro + { + /** + * {@inheritdoc} + */ + public function getReflection(): ?Reflection\Adapter\ReflectionMethod + { + if ($this->reflectionFunction instanceof Reflection\Adapter\ReflectionMethod) { + return $this->reflectionFunction; + } + + if ($this->reflectionFunction instanceof Reflection\ReflectionMethod) { + return new Reflection\Adapter\ReflectionMethod($this->reflectionFunction); + } + + return $this->reflectionFunction instanceof ReflectionMethod + ? new Reflection\Adapter\ReflectionMethod( + Reflection\ReflectionMethod::createFromName( + $this->reflectionFunction->getDeclaringClass()->getName(), + $this->reflectionFunction->getName() + ) + ) + : null; + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php new file mode 100644 index 0000000..f615b3a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +if (!class_exists(LazyMacro::class, false)) { + abstract class LazyMacro extends AbstractReflectionMacro + { + /** + * {@inheritdoc} + */ + public function getFileName(): ?string + { + $file = $this->reflectionFunction->getFileName(); + + return (($file ? realpath($file) : null) ?: $file) ?: null; + } + + /** + * {@inheritdoc} + */ + public function getStartLine(): ?int + { + return $this->reflectionFunction->getStartLine(); + } + + /** + * {@inheritdoc} + */ + public function getEndLine(): ?int + { + return $this->reflectionFunction->getEndLine(); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php new file mode 100644 index 0000000..bf64c1d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php @@ -0,0 +1,51 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +if (!class_exists(LazyMacro::class, false)) { + abstract class LazyMacro extends AbstractReflectionMacro + { + /** + * {@inheritdoc} + * + * @return string|false + */ + public function getFileName() + { + $file = $this->reflectionFunction->getFileName(); + + return (($file ? realpath($file) : null) ?: $file) ?: null; + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + public function getStartLine() + { + return $this->reflectionFunction->getStartLine(); + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + public function getEndLine() + { + return $this->reflectionFunction->getEndLine(); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/TranslatorStrongType.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/TranslatorStrongType.php new file mode 100644 index 0000000..d35308a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/TranslatorStrongType.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Symfony\Component\Translation\MessageCatalogueInterface; + +if (!class_exists(LazyTranslator::class, false)) { + class LazyTranslator extends AbstractTranslator implements TranslatorStrongTypeInterface + { + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + return $this->translate($id, $parameters, $domain, $locale); + } + + public function getFromCatalogue(MessageCatalogueInterface $catalogue, string $id, string $domain = 'messages') + { + $messages = $this->getPrivateProperty($catalogue, 'messages'); + + if (isset($messages[$domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX][$id])) { + return $messages[$domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX][$id]; + } + + if (isset($messages[$domain][$id])) { + return $messages[$domain][$id]; + } + + $fallbackCatalogue = $this->getPrivateProperty($catalogue, 'fallbackCatalogue'); + + if ($fallbackCatalogue !== null) { + return $this->getFromCatalogue($fallbackCatalogue, $id, $domain); + } + + return $id; + } + + private function getPrivateProperty($instance, string $field) + { + return (function (string $field) { + return $this->$field; + })->call($instance, $field); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/TranslatorWeakType.php b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/TranslatorWeakType.php new file mode 100644 index 0000000..94dbdc3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/lazy/Carbon/TranslatorWeakType.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +if (!class_exists(LazyTranslator::class, false)) { + class LazyTranslator extends AbstractTranslator + { + /** + * Returns the translation. + * + * @param string|null $id + * @param array $parameters + * @param string|null $domain + * @param string|null $locale + * + * @return string + */ + public function trans($id, array $parameters = [], $domain = null, $locale = null) + { + return $this->translate($id, $parameters, $domain, $locale); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/readme.md b/php/libraries/composer/vendor/nesbot/carbon/readme.md new file mode 100644 index 0000000..3f41177 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/readme.md @@ -0,0 +1,175 @@ +# Carbon + +[![Latest Stable Version](https://img.shields.io/packagist/v/nesbot/carbon.svg?style=flat-square)](https://packagist.org/packages/nesbot/carbon) +[![Total Downloads](https://img.shields.io/packagist/dt/nesbot/carbon.svg?style=flat-square)](https://packagist.org/packages/nesbot/carbon) +[![GitHub Actions](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fbriannesbitt%2FCarbon%2Fbadge&style=flat-square&label=Build&logo=none)](https://github.com/briannesbitt/Carbon/actions) +[![codecov.io](https://img.shields.io/codecov/c/github/briannesbitt/Carbon.svg?style=flat-square)](https://codecov.io/github/briannesbitt/Carbon?branch=master) +[![Tidelift](https://tidelift.com/badges/github/briannesbitt/Carbon)](https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme) + +An international PHP extension for DateTime. [https://carbon.nesbot.com](https://carbon.nesbot.com) + +```php +<?php + +use Carbon\Carbon; + +printf("Right now is %s", Carbon::now()->toDateTimeString()); +printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); //implicit __toString() +$tomorrow = Carbon::now()->addDay(); +$lastWeek = Carbon::now()->subWeek(); +$nextSummerOlympics = Carbon::createFromDate(2016)->addYears(4); + +$officialDate = Carbon::now()->toRfc2822String(); + +$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age; + +$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London'); + +$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT'); + +// Don't really want this to happen so mock now +Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1)); + +// comparisons are always done in UTC +if (Carbon::now()->gte($internetWillBlowUpOn)) { + die(); +} + +// Phew! Return to normal behaviour +Carbon::setTestNow(); + +if (Carbon::now()->isWeekend()) { + echo 'Party!'; +} +// Over 200 languages (and over 500 regional variants) supported: +echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago' +echo Carbon::now()->subMinutes(2)->locale('zh_CN')->diffForHumans(); // '2分钟前' +echo Carbon::parse('2019-07-23 14:51')->isoFormat('LLLL'); // 'Tuesday, July 23, 2019 2:51 PM' +echo Carbon::parse('2019-07-23 14:51')->locale('fr_FR')->isoFormat('LLLL'); // 'mardi 23 juillet 2019 14:51' + +// ... but also does 'from now', 'after' and 'before' +// rolling up to seconds, minutes, hours, days, months, years + +$daysSinceEpoch = Carbon::createFromTimestamp(0)->diffInDays(); +``` + +[Get supported nesbot/carbon with the Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme) + +## Installation + +### With Composer + +``` +$ composer require nesbot/carbon +``` + +```json +{ + "require": { + "nesbot/carbon": "^2.16" + } +} +``` + +```php +<?php +require 'vendor/autoload.php'; + +use Carbon\Carbon; + +printf("Now: %s", Carbon::now()); +``` + +### Without Composer + +Why are you not using [composer](https://getcomposer.org/)? Download the Carbon [latest release](https://github.com/briannesbitt/Carbon/releases) and put the contents of the ZIP archive into a directory in your project. Then require the file `autoload.php` to get all classes and dependencies loaded on need. + +```php +<?php +require 'path-to-Carbon-directory/autoload.php'; + +use Carbon\Carbon; + +printf("Now: %s", Carbon::now()); +``` + +## Docs + +[https://carbon.nesbot.com/docs](https://carbon.nesbot.com/docs) + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## Credits + +### Contributors + +This project exists thanks to all the people who contribute. + +<a href="https://github.com/briannesbitt/Carbon/graphs/contributors" target="_blank"><img src="https://opencollective.com/Carbon/contributors.svg?width=890&button=false" /></a> + +### Translators + +[Thanks to people helping us to translate Carbon in so many languages](https://carbon.nesbot.com/contribute/translators/) + +### Sponsors + +Support this project by becoming a sponsor. Your logo will show up here with a link to your website. + +<a href="https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme" target="_blank"><img src="https://carbon.nesbot.com/tidelift-brand.png" width="256" height="64"></a><!-- <open-collective-sponsors> --> +<a title="Онлайн казино 777 Україна" href="https://777.ua/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Онлайн казино" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/7e572d50-1ce8-4d69-ae12-86cc80371373/ok-ua-777.png" width="64" height="64"></a> +<a title="#1 Guide To Online Gambling In Canada" href="https://casinohex.org/canada/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="CasinoHex Canada" src="https://opencollective-production.s3.us-west-1.amazonaws.com/79fdbcc0-a997-11eb-abbc-25e48b63c6dc.jpg" width="85" height="64"></a> +<a title="Znajdź najlepsze zakłady bukmacherskie w Polsce w 2023 roku. Probukmacher.pl to Twoje kompendium wiedzy na temat bukmacherów!" href="https://www.probukmacher.pl?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Probukmacher" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/caf50271-4560-4ffe-a434-ea15239168db/Screenshot_1.png" width="89" height="64"></a> +<a title="Gives a fun for our users" href="https://slotoking.ua/games/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Игровые автоматы" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/94601d07-3205-4c60-9c2d-9b8194dbefb7/skg-blue.png" width="64" height="64"></a> +<a title="Casino-portugal.pt" href="https://casino-portugal.pt/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Casino-portugal.pt" src="https://logo.clearbit.com/casino-portugal.pt" width="64" height="64"></a> +<a title="Slots City® ➢ Лучшее лицензионно казино онлайн и оффлайн на гривны в Украине. 【 Более1500 игровых автоматов и слотов】✅ Официально и Безопасно" href="https://slotscity.ua/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Slots City" src="https://opencollective-production.s3.us-west-1.amazonaws.com/d7e298c0-7abe-11ed-8553-230872f5e54d.png" width="90" height="64"></a> +<a title="inkedin" href="https://inkedin.com?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="inkedin" src="https://logo.clearbit.com/inkedin.com" width="64" height="64"></a> +<a title="Актуальний та повносправний рейтинг онлайн казино України, ґрунтований на відгуках реальних гравців." href="https://uk.onlinecasino.in.ua/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Онлайн казино України" src="https://opencollective-production.s3.us-west-1.amazonaws.com/c0b4b090-eef8-11ec-9cb7-0527a205b226.png" width="64" height="64"></a> +<a title="OnlineCasinosSpelen" href="https://onlinecasinosspelen.com?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="OnlineCasinosSpelen" src="https://logo.clearbit.com/onlinecasinosspelen.com" width="64" height="64"></a> +<a title="Best non Gamstop sites in the UK" href="https://nongamstopcasinos.net/gb/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Best non Gamstop sites in the UK" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/34e340b8-e1de-4932-8a76-1b3ce2ec7ee8/logo_white%20bg%20(8).png" width="64" height="64"></a> +<a title="Real Money Pokies" href="https://www.nzfirst.org.nz/real-money-pokies/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Real Money Pokies" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/30d38232-a9d6-4e95-a48c-641fdc4d96fd/NZ_logo%20(6)%20(1)%20(1).jpg" width="64" height="64"></a> +<a title="Non GamStop Bookies UK" href="https://nongamstopbookies.com/uk/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Non GamStop Bookies UK" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/43c5561c-8907-4ef7-a4ee-c6da054788b8/logo-site%20(3).jpg" width="64" height="64"></a> +<a title="Актуальний топ-рейтинг українських онлайн казино на гривні! Щоденне оновлення топу та унікальна система ранжування, основана на відгуках гравців!" href="https://onlinecasino.in.ua/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Онлайн Казино Украины" src="https://opencollective-production.s3.us-west-1.amazonaws.com/8fdd8aa0-e273-11ec-a95e-d38fd331cabf.png" width="64" height="64"></a> +<a title="Twitter Video Downloader HD Tool allows you to store tweets on your device (mobile or PC) for free." href="https://ssstwitter.online/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="SSSTwitter" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/ba0d1daf-a894-4d98-95f7-a44d321364b3/Screenshot%202024-01-16%20at%2011.43.22.png" width="76" height="64"></a> +<a title="Entertainment" href="https://www.nongamstopbets.com/casinos-not-on-gamstop/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Non-GamStop Bets UK" src="https://logo.clearbit.com/nongamstopbets.com" width="64" height="64"></a> +<a title="Chudovo - international software development company with representative offices in Kyiv, Cologne, New York, Tallinn and London. It has been working on the market since 2006. Company has domain expertise in video security, logistics, medicine, finance and" href="https://chudovo.com/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Chudovo" src="https://opencollective-production.s3.us-west-1.amazonaws.com/326c19a0-2e87-11eb-a13a-c99a2a201d11.png" width="84" height="42"></a> +<a title="Entertainment" href="https://casinogap.org/uk/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="UK Casino Gap" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/143f9301-beec-4118-89d5-9a07a01345f3/casinogap-uk.png" width="42" height="42"></a> +<a title="NZ Gaming Portal" href="https://casinodeps.co.nz?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="NZ Casino Deps" src="https://logo.clearbit.com/casinodeps.co.nz" width="42" height="42"></a> +<a title="NonStop Sites" href="https://uk.nonstopcasino.org/non-gamstop-casinos/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="NonStopCasino.org" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/fd7ad905-8752-468f-ad20-582a24cca9d9/non-stop-casino.png" width="42" height="42"></a> +<a title="Siti Non AAMS" href="https://www.outlookindia.com/outlook-spotlight/migliori-siti-non-aams-siti-scommesse-senza-licenza-sicuri-news-294715?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Migliori Siti Non AAMS" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/392810da-6cb6-4938-a3cb-38bd0e1eb7de/migliori-siti-non-aams.png" width="42" height="42"></a> +<a title="List of trusted non GamStop casino reviews" href="https://nongamstopcasinos.org?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="UK NonGamStopCasinos" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/cbda0ee1-26ea-4252-9580-f1f9b317b1f7/nongamstopcasinos-uk.png" width="42" height="42"></a> +<a title="Online TikTok Video Download Tool" href="https://snaptik.pro?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="SnapTik" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/546bcd53-6615-457d-ab21-1db1c52b3af5/logo.jpg" width="42" height="42"></a> +<a title="IG Downloader is an Instagram Downloader service that offers a variety of tools to download Instagram content for free. Listed below are all the tools" href="https://indownloader.app/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="IG Downloader" src="https://logo.clearbit.com/indownloader.app" width="42" height="42"></a> +<a title="Proxidize is a mobile proxy creation and management platform that provides all needed components from hardware to cloud software and SIM cards." href="https://proxidize.com/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Proxidize" src="https://logo.clearbit.com/proxidize.com" width="42" height="42"></a> +<a title="Blastup offers Instagram growth services like buying likes, views, and followers, emphasizing real user engagement and instant delivery." href="https://blastup.com/buy-instagram-likes?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Blastup" src="https://opencollective-production.s3.us-west-1.amazonaws.com/account-avatar/955a0beb-9fe8-4753-ad92-fae8ef5382fc/favicon--dark.jpg" width="42" height="42"></a> +<a title="A self-hosted web radio management suite, including turnkey installer tools and an easy-to-use web app to manage your stations." href="https://azuracast.com?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="AzuraCast" src="https://opencollective-production.s3.us-west-1.amazonaws.com/3c12ea10-cdfb-11eb-9cf4-3760b386b76d.png" width="42" height="42"></a> +<a title="Triplebyte is the first software engineering job platform that is on the developer's side. Take our coding quiz!" href="https://triplebyte.com/os/opencollective?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Triplebyte" src="https://opencollective-production.s3.us-west-1.amazonaws.com/43e4f9d0-30cd-11ea-9c6b-e1142996e8b2.png" width="42" height="42"></a> +<a title="Connect your Collective to GitHub Sponsors: https://docs.opencollective.com/help/collectives/github-sponsors" href="https://github.com/sponsors/?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="GitHub Sponsors" src="https://opencollective-production.s3.us-west-1.amazonaws.com/87b1d240-f617-11ea-9960-fd7e8ab20fe4.png" width="48" height="42"></a> +<a title="Salesforce" href="https://engineering.salesforce.com?utm_source=opencollective&utm_medium=github&utm_campaign=Carbon" target="_blank"><img alt="Salesforce" src="https://opencollective-production.s3.us-west-1.amazonaws.com/24d34880-df8d-11e9-949c-6bc2037b6bd5.png" width="42" height="42"></a> +<!-- </open-collective-sponsors> --> + +[[Become a sponsor via OpenCollective](https://opencollective.com/Carbon#sponsor)] + +<a href="https://github.com/johnrsimeone" target="_blank"><img src="https://avatars.githubusercontent.com/u/22871068?s=70&v=4" width="64" height="64"></a> +<a href="https://github.com/taylorotwell" target="_blank"><img src="https://avatars.githubusercontent.com/u/463230?s=128&v=4" width="64" height="64"></a> +<a href="https://github.com/getsentry" target="_blank"><img src="https://avatars.githubusercontent.com/u/1396951?s=128&v=4" width="64" height="64"></a> +<a href="https://github.com/codecov" target="_blank"><img src="https://avatars.githubusercontent.com/u/8226205?s=128&v=4" width="64" height="64"></a> + +[[Become a sponsor via GitHub](https://github.com/sponsors/kylekatarnls)] + +### Backers + +Thank you to all our backers! 🙏 + +<a href="https://opencollective.com/Carbon#backers" target="_blank"><img src="https://opencollective.com/Carbon/backers.svg?width=890&version=2023-06-08-07-12"></a> + +[[Become a backer](https://opencollective.com/Carbon#backer)] + +## Carbon for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of ``Carbon`` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/php/libraries/composer/vendor/nesbot/carbon/sponsors.php b/php/libraries/composer/vendor/nesbot/carbon/sponsors.php new file mode 100644 index 0000000..67b2171 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/sponsors.php @@ -0,0 +1,129 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Carbon\CarbonImmutable; + +require_once __DIR__.'/vendor/autoload.php'; + +function getMaxHistoryMonthsByAmount($amount): int +{ + if ($amount >= 50) { + return 6; + } + + if ($amount >= 20) { + return 4; + } + + return 2; +} + +function getHtmlAttribute($rawValue): string +{ + return str_replace( + ['​', "\r"], + '', + trim(htmlspecialchars((string) $rawValue), "  \n\r\t\v\0"), + ); +} + +function getOpenCollectiveSponsors(): string +{ + $customSponsorImages = [ + // For consistency and equity among sponsors, as of now, we kindly ask our sponsors + // to provide an image having a width/height ratio between 1/1 and 2/1. + // By default, we'll show the member picture from OpenCollective, and will resize it if bigger + // int(OpenCollective.MemberId) => ImageURL + ]; + + $members = json_decode(file_get_contents('https://opencollective.com/carbon/members/all.json'), true); + + $list = array_filter($members, static function ($member): bool { + return ($member['lastTransactionAmount'] > 3 || $member['isActive']) && + $member['role'] === 'BACKER' && + $member['type'] !== 'USER' && + ( + $member['totalAmountDonated'] > 100 || + $member['lastTransactionAt'] > CarbonImmutable::now() + ->subMonthsNoOverflow(getMaxHistoryMonthsByAmount($member['lastTransactionAmount'])) + ->format('Y-m-d h:i') || + $member['isActive'] && $member['lastTransactionAmount'] >= 30 + ); + }); + + $list = array_map(static function (array $member): array { + $createdAt = CarbonImmutable::parse($member['createdAt']); + $lastTransactionAt = CarbonImmutable::parse($member['lastTransactionAt']); + + if ($createdAt->format('d H:i:s.u') > $lastTransactionAt->format('d H:i:s.u')) { + $createdAt = $createdAt + ->setDay($lastTransactionAt->day) + ->modify($lastTransactionAt->format('H:i:s.u')); + } + + $monthlyContribution = (float) ($member['totalAmountDonated'] / ceil($createdAt->floatDiffInMonths())); + + if ( + $lastTransactionAt->isAfter('last month') && + $member['lastTransactionAmount'] > $monthlyContribution + ) { + $monthlyContribution = (float) $member['lastTransactionAmount']; + } + + $yearlyContribution = (float) ($member['totalAmountDonated'] / max(1, $createdAt->floatDiffInYears())); + $status = null; + + if ($monthlyContribution > 29) { + $status = 'sponsor'; + } elseif ($monthlyContribution > 4.5 || $yearlyContribution > 29) { + $status = 'backer'; + } elseif ($member['totalAmountDonated'] > 0) { + $status = 'helper'; + } + + return array_merge($member, [ + 'star' => ($monthlyContribution > 98 || $yearlyContribution > 500), + 'status' => $status, + 'monthlyContribution' => $monthlyContribution, + 'yearlyContribution' => $yearlyContribution, + ]); + }, $list); + + usort($list, static function (array $a, array $b): int { + return ($b['monthlyContribution'] <=> $a['monthlyContribution']) + ?: ($b['totalAmountDonated'] <=> $a['totalAmountDonated']); + }); + + return implode('', array_map(static function (array $member) use ($customSponsorImages): string { + $href = htmlspecialchars($member['website'] ?? $member['profile']); + $src = $customSponsorImages[$member['MemberId'] ?? ''] ?? $member['image'] ?? (strtr($member['profile'], ['https://opencollective.com/' => 'https://images.opencollective.com/']).'/avatar/256.png'); + [$x, $y] = @getimagesize($src) ?: [0, 0]; + $validImage = ($x && $y); + $src = $validImage ? htmlspecialchars($src) : 'https://opencollective.com/static/images/default-guest-logo.svg'; + $height = $member['status'] === 'sponsor' ? 64 : 42; + $width = min($height * 2, $validImage ? round($x * $height / $y) : $height); + $href .= (strpos($href, '?') === false ? '?' : '&').'utm_source=opencollective&utm_medium=github&utm_campaign=Carbon'; + $title = getHtmlAttribute(($member['description'] ?? null) ?: $member['name']); + $alt = getHtmlAttribute($member['name']); + + return "\n".'<a title="'.$title.'" href="'.$href.'" target="_blank">'. + '<img alt="'.$alt.'" src="'.$src.'" width="'.$width.'" height="'.$height.'">'. + '</a>'; + }, $list))."\n"; +} + +file_put_contents('readme.md', preg_replace_callback( + '/(<!-- <open-collective-sponsors> -->)[\s\S]+(<!-- <\/open-collective-sponsors> -->)/', + static function (array $match): string { + return $match[1].getOpenCollectiveSponsors().$match[2]; + }, + file_get_contents('readme.md') +)); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php new file mode 100644 index 0000000..8b8fe08 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php @@ -0,0 +1,398 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\MessageFormatter\MessageFormatterMapper; +use Closure; +use ReflectionException; +use ReflectionFunction; +use Symfony\Component\Translation; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; +use Symfony\Component\Translation\Loader\ArrayLoader; + +abstract class AbstractTranslator extends Translation\Translator +{ + /** + * Translator singletons for each language. + * + * @var array + */ + protected static $singletons = []; + + /** + * List of custom localized messages. + * + * @var array + */ + protected $messages = []; + + /** + * List of custom directories that contain translation files. + * + * @var string[] + */ + protected $directories = []; + + /** + * Set to true while constructing. + * + * @var bool + */ + protected $initializing = false; + + /** + * List of locales aliases. + * + * @var array<string, string> + */ + protected $aliases = [ + 'me' => 'sr_Latn_ME', + 'scr' => 'sh', + ]; + + /** + * Return a singleton instance of Translator. + * + * @param string|null $locale optional initial locale ("en" - english by default) + * + * @return static + */ + public static function get($locale = null) + { + $locale = $locale ?: 'en'; + $key = static::class === Translator::class ? $locale : static::class.'|'.$locale; + + if (!isset(static::$singletons[$key])) { + static::$singletons[$key] = new static($locale); + } + + return static::$singletons[$key]; + } + + public function __construct($locale, MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false) + { + parent::setLocale($locale); + $this->initializing = true; + $this->directories = [__DIR__.'/Lang']; + $this->addLoader('array', new ArrayLoader()); + parent::__construct($locale, new MessageFormatterMapper($formatter), $cacheDir, $debug); + $this->initializing = false; + } + + /** + * Returns the list of directories translation files are searched in. + * + * @return array + */ + public function getDirectories(): array + { + return $this->directories; + } + + /** + * Set list of directories translation files are searched in. + * + * @param array $directories new directories list + * + * @return $this + */ + public function setDirectories(array $directories) + { + $this->directories = $directories; + + return $this; + } + + /** + * Add a directory to the list translation files are searched in. + * + * @param string $directory new directory + * + * @return $this + */ + public function addDirectory(string $directory) + { + $this->directories[] = $directory; + + return $this; + } + + /** + * Remove a directory from the list translation files are searched in. + * + * @param string $directory directory path + * + * @return $this + */ + public function removeDirectory(string $directory) + { + $search = rtrim(strtr($directory, '\\', '/'), '/'); + + return $this->setDirectories(array_filter($this->getDirectories(), function ($item) use ($search) { + return rtrim(strtr($item, '\\', '/'), '/') !== $search; + })); + } + + /** + * Reset messages of a locale (all locale if no locale passed). + * Remove custom messages and reload initial messages from matching + * file in Lang directory. + * + * @param string|null $locale + * + * @return bool + */ + public function resetMessages($locale = null) + { + if ($locale === null) { + $this->messages = []; + + return true; + } + + foreach ($this->getDirectories() as $directory) { + $data = @include sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale); + + if ($data !== false) { + $this->messages[$locale] = $data; + $this->addResource('array', $this->messages[$locale], $locale); + + return true; + } + } + + return false; + } + + /** + * Returns the list of files matching a given locale prefix (or all if empty). + * + * @param string $prefix prefix required to filter result + * + * @return array + */ + public function getLocalesFiles($prefix = '') + { + $files = []; + + foreach ($this->getDirectories() as $directory) { + $directory = rtrim($directory, '\\/'); + + foreach (glob("$directory/$prefix*.php") as $file) { + $files[] = $file; + } + } + + return array_unique($files); + } + + /** + * Returns the list of internally available locales and already loaded custom locales. + * (It will ignore custom translator dynamic loading.) + * + * @param string $prefix prefix required to filter result + * + * @return array + */ + public function getAvailableLocales($prefix = '') + { + $locales = []; + foreach ($this->getLocalesFiles($prefix) as $file) { + $locales[] = substr($file, strrpos($file, '/') + 1, -4); + } + + return array_unique(array_merge($locales, array_keys($this->messages))); + } + + protected function translate(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + if ($domain === null) { + $domain = 'messages'; + } + + $catalogue = $this->getCatalogue($locale); + $format = $this instanceof TranslatorStrongTypeInterface + ? $this->getFromCatalogue($catalogue, (string) $id, $domain) + : $this->getCatalogue($locale)->get((string) $id, $domain); // @codeCoverageIgnore + + if ($format instanceof Closure) { + // @codeCoverageIgnoreStart + try { + $count = (new ReflectionFunction($format))->getNumberOfRequiredParameters(); + } catch (ReflectionException $exception) { + $count = 0; + } + // @codeCoverageIgnoreEnd + + return $format( + ...array_values($parameters), + ...array_fill(0, max(0, $count - \count($parameters)), null) + ); + } + + return parent::trans($id, $parameters, $domain, $locale); + } + + /** + * Init messages language from matching file in Lang directory. + * + * @param string $locale + * + * @return bool + */ + protected function loadMessagesFromFile($locale) + { + return isset($this->messages[$locale]) || $this->resetMessages($locale); + } + + /** + * Set messages of a locale and take file first if present. + * + * @param string $locale + * @param array $messages + * + * @return $this + */ + public function setMessages($locale, $messages) + { + $this->loadMessagesFromFile($locale); + $this->addResource('array', $messages, $locale); + $this->messages[$locale] = array_merge( + $this->messages[$locale] ?? [], + $messages + ); + + return $this; + } + + /** + * Set messages of the current locale and take file first if present. + * + * @param array $messages + * + * @return $this + */ + public function setTranslations($messages) + { + return $this->setMessages($this->getLocale(), $messages); + } + + /** + * Get messages of a locale, if none given, return all the + * languages. + * + * @param string|null $locale + * + * @return array + */ + public function getMessages($locale = null) + { + return $locale === null ? $this->messages : $this->messages[$locale]; + } + + /** + * Set the current translator locale and indicate if the source locale file exists + * + * @param string $locale locale ex. en + * + * @return bool + */ + public function setLocale($locale) + { + $locale = preg_replace_callback('/[-_]([a-z]{2,}|\d{2,})/', function ($matches) { + // _2-letters or YUE is a region, _3+-letters is a variant + $upper = strtoupper($matches[1]); + + if ($upper === 'YUE' || $upper === 'ISO' || \strlen($upper) < 3) { + return "_$upper"; + } + + return '_'.ucfirst($matches[1]); + }, strtolower($locale)); + + $previousLocale = $this->getLocale(); + + if ($previousLocale === $locale && isset($this->messages[$locale])) { + return true; + } + + unset(static::$singletons[$previousLocale]); + + if ($locale === 'auto') { + $completeLocale = setlocale(LC_TIME, '0'); + $locale = preg_replace('/^([^_.-]+).*$/', '$1', $completeLocale); + $locales = $this->getAvailableLocales($locale); + + $completeLocaleChunks = preg_split('/[_.-]+/', $completeLocale); + + $getScore = function ($language) use ($completeLocaleChunks) { + return self::compareChunkLists($completeLocaleChunks, preg_split('/[_.-]+/', $language)); + }; + + usort($locales, function ($first, $second) use ($getScore) { + return $getScore($second) <=> $getScore($first); + }); + + $locale = $locales[0]; + } + + if (isset($this->aliases[$locale])) { + $locale = $this->aliases[$locale]; + } + + // If subtag (ex: en_CA) first load the macro (ex: en) to have a fallback + if (str_contains($locale, '_') && + $this->loadMessagesFromFile($macroLocale = preg_replace('/^([^_]+).*$/', '$1', $locale)) + ) { + parent::setLocale($macroLocale); + } + + if (!$this->loadMessagesFromFile($locale) && !$this->initializing) { + return false; + } + + parent::setLocale($locale); + + return true; + } + + /** + * Show locale on var_dump(). + * + * @return array + */ + public function __debugInfo() + { + return [ + 'locale' => $this->getLocale(), + ]; + } + + private static function compareChunkLists($referenceChunks, $chunks) + { + $score = 0; + + foreach ($referenceChunks as $index => $chunk) { + if (!isset($chunks[$index])) { + $score++; + + continue; + } + + if (strtolower($chunks[$index]) === strtolower($chunk)) { + $score += 10; + } + } + + return $score; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Carbon.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Carbon.php new file mode 100644 index 0000000..e32569a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Carbon.php @@ -0,0 +1,523 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\Traits\Date; +use Carbon\Traits\DeprecatedProperties; +use DateTime; +use DateTimeInterface; +use DateTimeZone; + +/** + * A simple API extension for DateTime. + * + * @mixin DeprecatedProperties + * + * <autodoc generated by `composer phpdoc`> + * + * @property int $year + * @property int $yearIso + * @property int $month + * @property int $day + * @property int $hour + * @property int $minute + * @property int $second + * @property int $micro + * @property int $microsecond + * @property int|float|string $timestamp seconds since the Unix Epoch + * @property string $englishDayOfWeek the day of week in English + * @property string $shortEnglishDayOfWeek the abbreviated day of week in English + * @property string $englishMonth the month in English + * @property string $shortEnglishMonth the abbreviated month in English + * @property int $milliseconds + * @property int $millisecond + * @property int $milli + * @property int $week 1 through 53 + * @property int $isoWeek 1 through 53 + * @property int $weekYear year according to week format + * @property int $isoWeekYear year according to ISO week format + * @property int $dayOfYear 1 through 366 + * @property int $age does a diffInYears() with default parameters + * @property int $offset the timezone offset in seconds from UTC + * @property int $offsetMinutes the timezone offset in minutes from UTC + * @property int $offsetHours the timezone offset in hours from UTC + * @property CarbonTimeZone $timezone the current timezone + * @property CarbonTimeZone $tz alias of $timezone + * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) + * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) + * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday + * @property-read int $daysInMonth number of days in the given month + * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read int $noZeroHour current hour from 1 to 24 + * @property-read int $weeksInYear 51 through 53 + * @property-read int $isoWeeksInYear 51 through 53 + * @property-read int $weekOfMonth 1 through 5 + * @property-read int $weekNumberInMonth 1 through 5 + * @property-read int $firstWeekDay 0 through 6 + * @property-read int $lastWeekDay 0 through 6 + * @property-read int $daysInYear 365 or 366 + * @property-read int $quarter the quarter of this instance, 1 - 4 + * @property-read int $decade the decade of this instance + * @property-read int $century the century of this instance + * @property-read int $millennium the millennium of this instance + * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise + * @property-read bool $local checks if the timezone is local, true if local, false otherwise + * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise + * @property-read string $timezoneName the current timezone name + * @property-read string $tzName alias of $timezoneName + * @property-read string $locale locale of the current instance + * + * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + * @method bool isLocal() Check if the current instance has non-UTC timezone. + * @method bool isValid() Check if the current instance is a valid date. + * @method bool isDST() Check if the current instance is in a daylight saving time. + * @method bool isSunday() Checks if the instance day is sunday. + * @method bool isMonday() Checks if the instance day is monday. + * @method bool isTuesday() Checks if the instance day is tuesday. + * @method bool isWednesday() Checks if the instance day is wednesday. + * @method bool isThursday() Checks if the instance day is thursday. + * @method bool isFriday() Checks if the instance day is friday. + * @method bool isSaturday() Checks if the instance day is saturday. + * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. + * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. + * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. + * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. + * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. + * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. + * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. + * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. + * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. + * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. + * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. + * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. + * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. + * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. + * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. + * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. + * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. + * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. + * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. + * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. + * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. + * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. + * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. + * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. + * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. + * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. + * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. + * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. + * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. + * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. + * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. + * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. + * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. + * @method $this years(int $value) Set current instance year to the given value. + * @method $this year(int $value) Set current instance year to the given value. + * @method $this setYears(int $value) Set current instance year to the given value. + * @method $this setYear(int $value) Set current instance year to the given value. + * @method $this months(int $value) Set current instance month to the given value. + * @method $this month(int $value) Set current instance month to the given value. + * @method $this setMonths(int $value) Set current instance month to the given value. + * @method $this setMonth(int $value) Set current instance month to the given value. + * @method $this days(int $value) Set current instance day to the given value. + * @method $this day(int $value) Set current instance day to the given value. + * @method $this setDays(int $value) Set current instance day to the given value. + * @method $this setDay(int $value) Set current instance day to the given value. + * @method $this hours(int $value) Set current instance hour to the given value. + * @method $this hour(int $value) Set current instance hour to the given value. + * @method $this setHours(int $value) Set current instance hour to the given value. + * @method $this setHour(int $value) Set current instance hour to the given value. + * @method $this minutes(int $value) Set current instance minute to the given value. + * @method $this minute(int $value) Set current instance minute to the given value. + * @method $this setMinutes(int $value) Set current instance minute to the given value. + * @method $this setMinute(int $value) Set current instance minute to the given value. + * @method $this seconds(int $value) Set current instance second to the given value. + * @method $this second(int $value) Set current instance second to the given value. + * @method $this setSeconds(int $value) Set current instance second to the given value. + * @method $this setSecond(int $value) Set current instance second to the given value. + * @method $this millis(int $value) Set current instance millisecond to the given value. + * @method $this milli(int $value) Set current instance millisecond to the given value. + * @method $this setMillis(int $value) Set current instance millisecond to the given value. + * @method $this setMilli(int $value) Set current instance millisecond to the given value. + * @method $this milliseconds(int $value) Set current instance millisecond to the given value. + * @method $this millisecond(int $value) Set current instance millisecond to the given value. + * @method $this setMilliseconds(int $value) Set current instance millisecond to the given value. + * @method $this setMillisecond(int $value) Set current instance millisecond to the given value. + * @method $this micros(int $value) Set current instance microsecond to the given value. + * @method $this micro(int $value) Set current instance microsecond to the given value. + * @method $this setMicros(int $value) Set current instance microsecond to the given value. + * @method $this setMicro(int $value) Set current instance microsecond to the given value. + * @method $this microseconds(int $value) Set current instance microsecond to the given value. + * @method $this microsecond(int $value) Set current instance microsecond to the given value. + * @method $this setMicroseconds(int $value) Set current instance microsecond to the given value. + * @method $this setMicrosecond(int $value) Set current instance microsecond to the given value. + * @method $this addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). + * @method $this addYear() Add one year to the instance (using date interval). + * @method $this subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). + * @method $this subYear() Sub one year to the instance (using date interval). + * @method $this addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. + * @method $this subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. + * @method $this addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). + * @method $this addMonth() Add one month to the instance (using date interval). + * @method $this subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). + * @method $this subMonth() Sub one month to the instance (using date interval). + * @method $this addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). + * @method $this addDay() Add one day to the instance (using date interval). + * @method $this subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). + * @method $this subDay() Sub one day to the instance (using date interval). + * @method $this addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). + * @method $this addHour() Add one hour to the instance (using date interval). + * @method $this subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). + * @method $this subHour() Sub one hour to the instance (using date interval). + * @method $this addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). + * @method $this addMinute() Add one minute to the instance (using date interval). + * @method $this subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). + * @method $this subMinute() Sub one minute to the instance (using date interval). + * @method $this addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). + * @method $this addSecond() Add one second to the instance (using date interval). + * @method $this subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). + * @method $this subSecond() Sub one second to the instance (using date interval). + * @method $this addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMilli() Add one millisecond to the instance (using date interval). + * @method $this subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMilli() Sub one millisecond to the instance (using date interval). + * @method $this addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMillisecond() Add one millisecond to the instance (using date interval). + * @method $this subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMillisecond() Sub one millisecond to the instance (using date interval). + * @method $this addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMicro() Add one microsecond to the instance (using date interval). + * @method $this subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMicro() Sub one microsecond to the instance (using date interval). + * @method $this addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMicrosecond() Add one microsecond to the instance (using date interval). + * @method $this subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMicrosecond() Sub one microsecond to the instance (using date interval). + * @method $this addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). + * @method $this addMillennium() Add one millennium to the instance (using date interval). + * @method $this subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). + * @method $this subMillennium() Sub one millennium to the instance (using date interval). + * @method $this addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). + * @method $this addCentury() Add one century to the instance (using date interval). + * @method $this subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). + * @method $this subCentury() Sub one century to the instance (using date interval). + * @method $this addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. + * @method $this subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. + * @method $this addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). + * @method $this addDecade() Add one decade to the instance (using date interval). + * @method $this subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). + * @method $this subDecade() Sub one decade to the instance (using date interval). + * @method $this addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. + * @method $this subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. + * @method $this addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). + * @method $this addQuarter() Add one quarter to the instance (using date interval). + * @method $this subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). + * @method $this subQuarter() Sub one quarter to the instance (using date interval). + * @method $this addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method $this subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method $this addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). + * @method $this addWeek() Add one week to the instance (using date interval). + * @method $this subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). + * @method $this subWeek() Sub one week to the instance (using date interval). + * @method $this addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). + * @method $this addWeekday() Add one weekday to the instance (using date interval). + * @method $this subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). + * @method $this subWeekday() Sub one weekday to the instance (using date interval). + * @method $this addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMicro() Add one microsecond to the instance (using timestamp). + * @method $this subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMicro() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method $this addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMicrosecond() Add one microsecond to the instance (using timestamp). + * @method $this subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMicrosecond() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method $this addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMilli() Add one millisecond to the instance (using timestamp). + * @method $this subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMilli() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method $this addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMillisecond() Add one millisecond to the instance (using timestamp). + * @method $this subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMillisecond() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method $this addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealSecond() Add one second to the instance (using timestamp). + * @method $this subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealSecond() Sub one second to the instance (using timestamp). + * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. + * @method $this addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMinute() Add one minute to the instance (using timestamp). + * @method $this subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMinute() Sub one minute to the instance (using timestamp). + * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. + * @method $this addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). + * @method $this addRealHour() Add one hour to the instance (using timestamp). + * @method $this subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). + * @method $this subRealHour() Sub one hour to the instance (using timestamp). + * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. + * @method $this addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). + * @method $this addRealDay() Add one day to the instance (using timestamp). + * @method $this subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). + * @method $this subRealDay() Sub one day to the instance (using timestamp). + * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. + * @method $this addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). + * @method $this addRealWeek() Add one week to the instance (using timestamp). + * @method $this subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). + * @method $this subRealWeek() Sub one week to the instance (using timestamp). + * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. + * @method $this addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMonth() Add one month to the instance (using timestamp). + * @method $this subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMonth() Sub one month to the instance (using timestamp). + * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. + * @method $this addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). + * @method $this addRealQuarter() Add one quarter to the instance (using timestamp). + * @method $this subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). + * @method $this subRealQuarter() Sub one quarter to the instance (using timestamp). + * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. + * @method $this addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). + * @method $this addRealYear() Add one year to the instance (using timestamp). + * @method $this subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). + * @method $this subRealYear() Sub one year to the instance (using timestamp). + * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. + * @method $this addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). + * @method $this addRealDecade() Add one decade to the instance (using timestamp). + * @method $this subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). + * @method $this subRealDecade() Sub one decade to the instance (using timestamp). + * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. + * @method $this addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). + * @method $this addRealCentury() Add one century to the instance (using timestamp). + * @method $this subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). + * @method $this subRealCentury() Sub one century to the instance (using timestamp). + * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. + * @method $this addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMillennium() Add one millennium to the instance (using timestamp). + * @method $this subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMillennium() Sub one millennium to the instance (using timestamp). + * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. + * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method static static|false createFromFormat(string $format, string $time, DateTimeZone|string|false|null $timezone = null) Parse a string into a new Carbon object according to the specified format. + * @method static static __set_state(array $array) https://php.net/manual/en/datetime.set-state.php + * + * </autodoc> + */ +class Carbon extends DateTime implements CarbonInterface +{ + use Date; + + /** + * Returns true if the current class/instance is mutable. + * + * @return bool + */ + public static function isMutable() + { + return true; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonConverterInterface.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonConverterInterface.php new file mode 100644 index 0000000..1ce967b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonConverterInterface.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use DateTimeInterface; + +interface CarbonConverterInterface +{ + public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface; +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php new file mode 100644 index 0000000..4c9c1cf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php @@ -0,0 +1,582 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\Traits\Date; +use Carbon\Traits\DeprecatedProperties; +use DateTimeImmutable; +use DateTimeInterface; +use DateTimeZone; + +/** + * A simple API extension for DateTimeImmutable. + * + * @mixin DeprecatedProperties + * + * <autodoc generated by `composer phpdoc`> + * + * @property int $year + * @property int $yearIso + * @property int $month + * @property int $day + * @property int $hour + * @property int $minute + * @property int $second + * @property int $micro + * @property int $microsecond + * @property int|float|string $timestamp seconds since the Unix Epoch + * @property string $englishDayOfWeek the day of week in English + * @property string $shortEnglishDayOfWeek the abbreviated day of week in English + * @property string $englishMonth the month in English + * @property string $shortEnglishMonth the abbreviated month in English + * @property int $milliseconds + * @property int $millisecond + * @property int $milli + * @property int $week 1 through 53 + * @property int $isoWeek 1 through 53 + * @property int $weekYear year according to week format + * @property int $isoWeekYear year according to ISO week format + * @property int $dayOfYear 1 through 366 + * @property int $age does a diffInYears() with default parameters + * @property int $offset the timezone offset in seconds from UTC + * @property int $offsetMinutes the timezone offset in minutes from UTC + * @property int $offsetHours the timezone offset in hours from UTC + * @property CarbonTimeZone $timezone the current timezone + * @property CarbonTimeZone $tz alias of $timezone + * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) + * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) + * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday + * @property-read int $daysInMonth number of days in the given month + * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read int $noZeroHour current hour from 1 to 24 + * @property-read int $weeksInYear 51 through 53 + * @property-read int $isoWeeksInYear 51 through 53 + * @property-read int $weekOfMonth 1 through 5 + * @property-read int $weekNumberInMonth 1 through 5 + * @property-read int $firstWeekDay 0 through 6 + * @property-read int $lastWeekDay 0 through 6 + * @property-read int $daysInYear 365 or 366 + * @property-read int $quarter the quarter of this instance, 1 - 4 + * @property-read int $decade the decade of this instance + * @property-read int $century the century of this instance + * @property-read int $millennium the millennium of this instance + * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise + * @property-read bool $local checks if the timezone is local, true if local, false otherwise + * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise + * @property-read string $timezoneName the current timezone name + * @property-read string $tzName alias of $timezoneName + * @property-read string $locale locale of the current instance + * + * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + * @method bool isLocal() Check if the current instance has non-UTC timezone. + * @method bool isValid() Check if the current instance is a valid date. + * @method bool isDST() Check if the current instance is in a daylight saving time. + * @method bool isSunday() Checks if the instance day is sunday. + * @method bool isMonday() Checks if the instance day is monday. + * @method bool isTuesday() Checks if the instance day is tuesday. + * @method bool isWednesday() Checks if the instance day is wednesday. + * @method bool isThursday() Checks if the instance day is thursday. + * @method bool isFriday() Checks if the instance day is friday. + * @method bool isSaturday() Checks if the instance day is saturday. + * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. + * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. + * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. + * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. + * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. + * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. + * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. + * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. + * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. + * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. + * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. + * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. + * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. + * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. + * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. + * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. + * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. + * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. + * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. + * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. + * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. + * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. + * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. + * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. + * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. + * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. + * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. + * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. + * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. + * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. + * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. + * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. + * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. + * @method CarbonImmutable years(int $value) Set current instance year to the given value. + * @method CarbonImmutable year(int $value) Set current instance year to the given value. + * @method CarbonImmutable setYears(int $value) Set current instance year to the given value. + * @method CarbonImmutable setYear(int $value) Set current instance year to the given value. + * @method CarbonImmutable months(int $value) Set current instance month to the given value. + * @method CarbonImmutable month(int $value) Set current instance month to the given value. + * @method CarbonImmutable setMonths(int $value) Set current instance month to the given value. + * @method CarbonImmutable setMonth(int $value) Set current instance month to the given value. + * @method CarbonImmutable days(int $value) Set current instance day to the given value. + * @method CarbonImmutable day(int $value) Set current instance day to the given value. + * @method CarbonImmutable setDays(int $value) Set current instance day to the given value. + * @method CarbonImmutable setDay(int $value) Set current instance day to the given value. + * @method CarbonImmutable hours(int $value) Set current instance hour to the given value. + * @method CarbonImmutable hour(int $value) Set current instance hour to the given value. + * @method CarbonImmutable setHours(int $value) Set current instance hour to the given value. + * @method CarbonImmutable setHour(int $value) Set current instance hour to the given value. + * @method CarbonImmutable minutes(int $value) Set current instance minute to the given value. + * @method CarbonImmutable minute(int $value) Set current instance minute to the given value. + * @method CarbonImmutable setMinutes(int $value) Set current instance minute to the given value. + * @method CarbonImmutable setMinute(int $value) Set current instance minute to the given value. + * @method CarbonImmutable seconds(int $value) Set current instance second to the given value. + * @method CarbonImmutable second(int $value) Set current instance second to the given value. + * @method CarbonImmutable setSeconds(int $value) Set current instance second to the given value. + * @method CarbonImmutable setSecond(int $value) Set current instance second to the given value. + * @method CarbonImmutable millis(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable milli(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMillis(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMilli(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable milliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable millisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMilliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMillisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable micros(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable micro(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicros(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicro(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable microseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable microsecond(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicroseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicrosecond(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addYear() Add one year to the instance (using date interval). + * @method CarbonImmutable subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subYear() Sub one year to the instance (using date interval). + * @method CarbonImmutable addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMonth() Add one month to the instance (using date interval). + * @method CarbonImmutable subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMonth() Sub one month to the instance (using date interval). + * @method CarbonImmutable addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addDay() Add one day to the instance (using date interval). + * @method CarbonImmutable subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subDay() Sub one day to the instance (using date interval). + * @method CarbonImmutable addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addHour() Add one hour to the instance (using date interval). + * @method CarbonImmutable subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subHour() Sub one hour to the instance (using date interval). + * @method CarbonImmutable addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMinute() Add one minute to the instance (using date interval). + * @method CarbonImmutable subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMinute() Sub one minute to the instance (using date interval). + * @method CarbonImmutable addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addSecond() Add one second to the instance (using date interval). + * @method CarbonImmutable subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subSecond() Sub one second to the instance (using date interval). + * @method CarbonImmutable addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMilli() Add one millisecond to the instance (using date interval). + * @method CarbonImmutable subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMilli() Sub one millisecond to the instance (using date interval). + * @method CarbonImmutable addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMillisecond() Add one millisecond to the instance (using date interval). + * @method CarbonImmutable subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMillisecond() Sub one millisecond to the instance (using date interval). + * @method CarbonImmutable addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMicro() Add one microsecond to the instance (using date interval). + * @method CarbonImmutable subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMicro() Sub one microsecond to the instance (using date interval). + * @method CarbonImmutable addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMicrosecond() Add one microsecond to the instance (using date interval). + * @method CarbonImmutable subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMicrosecond() Sub one microsecond to the instance (using date interval). + * @method CarbonImmutable addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMillennium() Add one millennium to the instance (using date interval). + * @method CarbonImmutable subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMillennium() Sub one millennium to the instance (using date interval). + * @method CarbonImmutable addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addCentury() Add one century to the instance (using date interval). + * @method CarbonImmutable subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subCentury() Sub one century to the instance (using date interval). + * @method CarbonImmutable addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addDecade() Add one decade to the instance (using date interval). + * @method CarbonImmutable subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subDecade() Sub one decade to the instance (using date interval). + * @method CarbonImmutable addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addQuarter() Add one quarter to the instance (using date interval). + * @method CarbonImmutable subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subQuarter() Sub one quarter to the instance (using date interval). + * @method CarbonImmutable addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addWeek() Add one week to the instance (using date interval). + * @method CarbonImmutable subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subWeek() Sub one week to the instance (using date interval). + * @method CarbonImmutable addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addWeekday() Add one weekday to the instance (using date interval). + * @method CarbonImmutable subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subWeekday() Sub one weekday to the instance (using date interval). + * @method CarbonImmutable addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMicro() Add one microsecond to the instance (using timestamp). + * @method CarbonImmutable subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMicro() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonImmutable addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMicrosecond() Add one microsecond to the instance (using timestamp). + * @method CarbonImmutable subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMicrosecond() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonImmutable addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMilli() Add one millisecond to the instance (using timestamp). + * @method CarbonImmutable subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMilli() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonImmutable addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMillisecond() Add one millisecond to the instance (using timestamp). + * @method CarbonImmutable subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMillisecond() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonImmutable addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealSecond() Add one second to the instance (using timestamp). + * @method CarbonImmutable subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealSecond() Sub one second to the instance (using timestamp). + * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. + * @method CarbonImmutable addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMinute() Add one minute to the instance (using timestamp). + * @method CarbonImmutable subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMinute() Sub one minute to the instance (using timestamp). + * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. + * @method CarbonImmutable addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealHour() Add one hour to the instance (using timestamp). + * @method CarbonImmutable subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealHour() Sub one hour to the instance (using timestamp). + * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. + * @method CarbonImmutable addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealDay() Add one day to the instance (using timestamp). + * @method CarbonImmutable subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealDay() Sub one day to the instance (using timestamp). + * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. + * @method CarbonImmutable addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealWeek() Add one week to the instance (using timestamp). + * @method CarbonImmutable subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealWeek() Sub one week to the instance (using timestamp). + * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. + * @method CarbonImmutable addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMonth() Add one month to the instance (using timestamp). + * @method CarbonImmutable subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMonth() Sub one month to the instance (using timestamp). + * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. + * @method CarbonImmutable addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealQuarter() Add one quarter to the instance (using timestamp). + * @method CarbonImmutable subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealQuarter() Sub one quarter to the instance (using timestamp). + * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. + * @method CarbonImmutable addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealYear() Add one year to the instance (using timestamp). + * @method CarbonImmutable subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealYear() Sub one year to the instance (using timestamp). + * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. + * @method CarbonImmutable addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealDecade() Add one decade to the instance (using timestamp). + * @method CarbonImmutable subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealDecade() Sub one decade to the instance (using timestamp). + * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. + * @method CarbonImmutable addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealCentury() Add one century to the instance (using timestamp). + * @method CarbonImmutable subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealCentury() Sub one century to the instance (using timestamp). + * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. + * @method CarbonImmutable addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMillennium() Add one millennium to the instance (using timestamp). + * @method CarbonImmutable subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMillennium() Sub one millennium to the instance (using timestamp). + * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. + * @method CarbonImmutable roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonImmutable roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonImmutable floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonImmutable floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonImmutable ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonImmutable ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonImmutable roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonImmutable roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonImmutable floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonImmutable floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonImmutable ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonImmutable ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonImmutable roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonImmutable roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonImmutable floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonImmutable floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonImmutable ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonImmutable ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonImmutable roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonImmutable roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonImmutable floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonImmutable floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonImmutable ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonImmutable ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonImmutable roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonImmutable roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonImmutable floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonImmutable floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonImmutable ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonImmutable ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonImmutable roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonImmutable roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonImmutable floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonImmutable floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonImmutable ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonImmutable ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonImmutable roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonImmutable roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonImmutable floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonImmutable floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonImmutable ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonImmutable ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonImmutable roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonImmutable roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonImmutable floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonImmutable floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonImmutable ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonImmutable ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonImmutable roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonImmutable roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonImmutable floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonImmutable floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonImmutable ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonImmutable ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonImmutable roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonImmutable roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonImmutable floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonImmutable floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonImmutable ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonImmutable ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonImmutable roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonImmutable roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonImmutable floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonImmutable floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonImmutable ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonImmutable ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonImmutable roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonImmutable roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonImmutable floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonImmutable floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonImmutable ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method CarbonImmutable ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method static static|false createFromFormat(string $format, string $time, DateTimeZone|string|false|null $timezone = null) Parse a string into a new CarbonImmutable object according to the specified format. + * @method static static __set_state(array $array) https://php.net/manual/en/datetime.set-state.php + * + * </autodoc> + */ +class CarbonImmutable extends DateTimeImmutable implements CarbonInterface +{ + use Date { + __clone as dateTraitClone; + } + + public function __clone() + { + $this->dateTraitClone(); + $this->endOfTime = false; + $this->startOfTime = false; + } + + /** + * Create a very old date representing start of time. + * + * @return static + */ + public static function startOfTime(): self + { + $date = static::parse('0001-01-01')->years(self::getStartOfTimeYear()); + $date->startOfTime = true; + + return $date; + } + + /** + * Create a very far date representing end of time. + * + * @return static + */ + public static function endOfTime(): self + { + $date = static::parse('9999-12-31 23:59:59.999999')->years(self::getEndOfTimeYear()); + $date->endOfTime = true; + + return $date; + } + + /** + * @codeCoverageIgnore + */ + private static function getEndOfTimeYear(): int + { + if (version_compare(PHP_VERSION, '7.3.0-dev', '<')) { + return 145261681241552; + } + + // Remove if https://bugs.php.net/bug.php?id=81107 is fixed + if (version_compare(PHP_VERSION, '8.1.0-dev', '>=')) { + return 1118290769066902787; + } + + return PHP_INT_MAX; + } + + /** + * @codeCoverageIgnore + */ + private static function getStartOfTimeYear(): int + { + if (version_compare(PHP_VERSION, '7.3.0-dev', '<')) { + return -135908816449551; + } + + // Remove if https://bugs.php.net/bug.php?id=81107 is fixed + if (version_compare(PHP_VERSION, '8.1.0-dev', '>=')) { + return -1118290769066898816; + } + + return max(PHP_INT_MIN, -9223372036854773760); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php new file mode 100644 index 0000000..b90e298 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php @@ -0,0 +1,5142 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use BadMethodCallException; +use Carbon\Exceptions\BadComparisonUnitException; +use Carbon\Exceptions\ImmutableException; +use Carbon\Exceptions\InvalidDateException; +use Carbon\Exceptions\InvalidFormatException; +use Carbon\Exceptions\UnknownGetterException; +use Carbon\Exceptions\UnknownMethodException; +use Carbon\Exceptions\UnknownSetterException; +use Closure; +use DateInterval; +use DateTime; +use DateTimeImmutable; +use DateTimeInterface; +use DateTimeZone; +use JsonSerializable; +use ReflectionException; +use ReturnTypeWillChange; +use Symfony\Component\Translation\TranslatorInterface; +use Throwable; + +/** + * Common interface for Carbon and CarbonImmutable. + * + * <autodoc generated by `composer phpdoc`> + * + * @property int $year + * @property int $yearIso + * @property int $month + * @property int $day + * @property int $hour + * @property int $minute + * @property int $second + * @property int $micro + * @property int $microsecond + * @property int|float|string $timestamp seconds since the Unix Epoch + * @property string $englishDayOfWeek the day of week in English + * @property string $shortEnglishDayOfWeek the abbreviated day of week in English + * @property string $englishMonth the month in English + * @property string $shortEnglishMonth the abbreviated month in English + * @property int $milliseconds + * @property int $millisecond + * @property int $milli + * @property int $week 1 through 53 + * @property int $isoWeek 1 through 53 + * @property int $weekYear year according to week format + * @property int $isoWeekYear year according to ISO week format + * @property int $dayOfYear 1 through 366 + * @property int $age does a diffInYears() with default parameters + * @property int $offset the timezone offset in seconds from UTC + * @property int $offsetMinutes the timezone offset in minutes from UTC + * @property int $offsetHours the timezone offset in hours from UTC + * @property CarbonTimeZone $timezone the current timezone + * @property CarbonTimeZone $tz alias of $timezone + * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) + * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) + * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday + * @property-read int $daysInMonth number of days in the given month + * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read int $noZeroHour current hour from 1 to 24 + * @property-read int $weeksInYear 51 through 53 + * @property-read int $isoWeeksInYear 51 through 53 + * @property-read int $weekOfMonth 1 through 5 + * @property-read int $weekNumberInMonth 1 through 5 + * @property-read int $firstWeekDay 0 through 6 + * @property-read int $lastWeekDay 0 through 6 + * @property-read int $daysInYear 365 or 366 + * @property-read int $quarter the quarter of this instance, 1 - 4 + * @property-read int $decade the decade of this instance + * @property-read int $century the century of this instance + * @property-read int $millennium the millennium of this instance + * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise + * @property-read bool $local checks if the timezone is local, true if local, false otherwise + * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise + * @property-read string $timezoneName the current timezone name + * @property-read string $tzName alias of $timezoneName + * @property-read string $locale locale of the current instance + * + * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + * @method bool isLocal() Check if the current instance has non-UTC timezone. + * @method bool isValid() Check if the current instance is a valid date. + * @method bool isDST() Check if the current instance is in a daylight saving time. + * @method bool isSunday() Checks if the instance day is sunday. + * @method bool isMonday() Checks if the instance day is monday. + * @method bool isTuesday() Checks if the instance day is tuesday. + * @method bool isWednesday() Checks if the instance day is wednesday. + * @method bool isThursday() Checks if the instance day is thursday. + * @method bool isFriday() Checks if the instance day is friday. + * @method bool isSaturday() Checks if the instance day is saturday. + * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. + * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. + * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. + * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. + * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. + * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. + * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. + * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. + * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. + * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. + * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. + * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. + * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. + * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. + * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. + * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. + * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. + * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. + * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. + * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. + * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. + * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. + * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. + * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. + * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. + * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. + * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. + * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. + * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. + * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. + * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. + * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. + * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. + * @method CarbonInterface years(int $value) Set current instance year to the given value. + * @method CarbonInterface year(int $value) Set current instance year to the given value. + * @method CarbonInterface setYears(int $value) Set current instance year to the given value. + * @method CarbonInterface setYear(int $value) Set current instance year to the given value. + * @method CarbonInterface months(int $value) Set current instance month to the given value. + * @method CarbonInterface month(int $value) Set current instance month to the given value. + * @method CarbonInterface setMonths(int $value) Set current instance month to the given value. + * @method CarbonInterface setMonth(int $value) Set current instance month to the given value. + * @method CarbonInterface days(int $value) Set current instance day to the given value. + * @method CarbonInterface day(int $value) Set current instance day to the given value. + * @method CarbonInterface setDays(int $value) Set current instance day to the given value. + * @method CarbonInterface setDay(int $value) Set current instance day to the given value. + * @method CarbonInterface hours(int $value) Set current instance hour to the given value. + * @method CarbonInterface hour(int $value) Set current instance hour to the given value. + * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. + * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. + * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. + * @method CarbonInterface minute(int $value) Set current instance minute to the given value. + * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. + * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. + * @method CarbonInterface seconds(int $value) Set current instance second to the given value. + * @method CarbonInterface second(int $value) Set current instance second to the given value. + * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. + * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. + * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicrosecond(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addYear() Add one year to the instance (using date interval). + * @method CarbonInterface subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subYear() Sub one year to the instance (using date interval). + * @method CarbonInterface addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMonth() Add one month to the instance (using date interval). + * @method CarbonInterface subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). + * @method CarbonInterface addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addDay() Add one day to the instance (using date interval). + * @method CarbonInterface subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subDay() Sub one day to the instance (using date interval). + * @method CarbonInterface addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addHour() Add one hour to the instance (using date interval). + * @method CarbonInterface subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). + * @method CarbonInterface addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). + * @method CarbonInterface subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). + * @method CarbonInterface addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addSecond() Add one second to the instance (using date interval). + * @method CarbonInterface subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). + * @method CarbonInterface addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). + * @method CarbonInterface subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). + * @method CarbonInterface addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). + * @method CarbonInterface subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). + * @method CarbonInterface addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). + * @method CarbonInterface subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). + * @method CarbonInterface addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). + * @method CarbonInterface subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). + * @method CarbonInterface addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). + * @method CarbonInterface subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). + * @method CarbonInterface addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addCentury() Add one century to the instance (using date interval). + * @method CarbonInterface subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). + * @method CarbonInterface addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). + * @method CarbonInterface subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). + * @method CarbonInterface addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). + * @method CarbonInterface subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). + * @method CarbonInterface addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addWeek() Add one week to the instance (using date interval). + * @method CarbonInterface subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). + * @method CarbonInterface addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). + * @method CarbonInterface subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). + * @method CarbonInterface addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMicro() Add one microsecond to the instance (using timestamp). + * @method CarbonInterface subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMicro() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonInterface addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMicrosecond() Add one microsecond to the instance (using timestamp). + * @method CarbonInterface subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMicrosecond() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonInterface addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMilli() Add one millisecond to the instance (using timestamp). + * @method CarbonInterface subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMilli() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonInterface addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMillisecond() Add one millisecond to the instance (using timestamp). + * @method CarbonInterface subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMillisecond() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonInterface addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealSecond() Add one second to the instance (using timestamp). + * @method CarbonInterface subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealSecond() Sub one second to the instance (using timestamp). + * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. + * @method CarbonInterface addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMinute() Add one minute to the instance (using timestamp). + * @method CarbonInterface subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMinute() Sub one minute to the instance (using timestamp). + * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. + * @method CarbonInterface addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealHour() Add one hour to the instance (using timestamp). + * @method CarbonInterface subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealHour() Sub one hour to the instance (using timestamp). + * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. + * @method CarbonInterface addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealDay() Add one day to the instance (using timestamp). + * @method CarbonInterface subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealDay() Sub one day to the instance (using timestamp). + * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. + * @method CarbonInterface addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealWeek() Add one week to the instance (using timestamp). + * @method CarbonInterface subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealWeek() Sub one week to the instance (using timestamp). + * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. + * @method CarbonInterface addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMonth() Add one month to the instance (using timestamp). + * @method CarbonInterface subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMonth() Sub one month to the instance (using timestamp). + * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. + * @method CarbonInterface addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealQuarter() Add one quarter to the instance (using timestamp). + * @method CarbonInterface subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealQuarter() Sub one quarter to the instance (using timestamp). + * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. + * @method CarbonInterface addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealYear() Add one year to the instance (using timestamp). + * @method CarbonInterface subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealYear() Sub one year to the instance (using timestamp). + * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. + * @method CarbonInterface addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealDecade() Add one decade to the instance (using timestamp). + * @method CarbonInterface subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealDecade() Sub one decade to the instance (using timestamp). + * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. + * @method CarbonInterface addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealCentury() Add one century to the instance (using timestamp). + * @method CarbonInterface subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealCentury() Sub one century to the instance (using timestamp). + * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. + * @method CarbonInterface addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMillennium() Add one millennium to the instance (using timestamp). + * @method CarbonInterface subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMillennium() Sub one millennium to the instance (using timestamp). + * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. + * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * + * </autodoc> + */ +interface CarbonInterface extends DateTimeInterface, JsonSerializable +{ + /** + * Diff wording options(expressed in octal). + */ + public const NO_ZERO_DIFF = 01; + public const JUST_NOW = 02; + public const ONE_DAY_WORDS = 04; + public const TWO_DAY_WORDS = 010; + public const SEQUENTIAL_PARTS_ONLY = 020; + public const ROUND = 040; + public const FLOOR = 0100; + public const CEIL = 0200; + + /** + * Diff syntax options. + */ + public const DIFF_ABSOLUTE = 1; // backward compatibility with true + public const DIFF_RELATIVE_AUTO = 0; // backward compatibility with false + public const DIFF_RELATIVE_TO_NOW = 2; + public const DIFF_RELATIVE_TO_OTHER = 3; + + /** + * Translate string options. + */ + public const TRANSLATE_MONTHS = 1; + public const TRANSLATE_DAYS = 2; + public const TRANSLATE_UNITS = 4; + public const TRANSLATE_MERIDIEM = 8; + public const TRANSLATE_DIFF = 0x10; + public const TRANSLATE_ALL = self::TRANSLATE_MONTHS | self::TRANSLATE_DAYS | self::TRANSLATE_UNITS | self::TRANSLATE_MERIDIEM | self::TRANSLATE_DIFF; + + /** + * The day constants. + */ + public const SUNDAY = 0; + public const MONDAY = 1; + public const TUESDAY = 2; + public const WEDNESDAY = 3; + public const THURSDAY = 4; + public const FRIDAY = 5; + public const SATURDAY = 6; + + /** + * The month constants. + * These aren't used by Carbon itself but exist for + * convenience sake alone. + */ + public const JANUARY = 1; + public const FEBRUARY = 2; + public const MARCH = 3; + public const APRIL = 4; + public const MAY = 5; + public const JUNE = 6; + public const JULY = 7; + public const AUGUST = 8; + public const SEPTEMBER = 9; + public const OCTOBER = 10; + public const NOVEMBER = 11; + public const DECEMBER = 12; + + /** + * Number of X in Y. + */ + public const YEARS_PER_MILLENNIUM = 1000; + public const YEARS_PER_CENTURY = 100; + public const YEARS_PER_DECADE = 10; + public const MONTHS_PER_YEAR = 12; + public const MONTHS_PER_QUARTER = 3; + public const QUARTERS_PER_YEAR = 4; + public const WEEKS_PER_YEAR = 52; + public const WEEKS_PER_MONTH = 4; + public const DAYS_PER_YEAR = 365; + public const DAYS_PER_WEEK = 7; + public const HOURS_PER_DAY = 24; + public const MINUTES_PER_HOUR = 60; + public const SECONDS_PER_MINUTE = 60; + public const MILLISECONDS_PER_SECOND = 1000; + public const MICROSECONDS_PER_MILLISECOND = 1000; + public const MICROSECONDS_PER_SECOND = 1000000; + + /** + * Special settings to get the start of week from current locale culture. + */ + public const WEEK_DAY_AUTO = 'auto'; + + /** + * RFC7231 DateTime format. + * + * @var string + */ + public const RFC7231_FORMAT = 'D, d M Y H:i:s \G\M\T'; + + /** + * Default format to use for __toString method when type juggling occurs. + * + * @var string + */ + public const DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s'; + + /** + * Format for converting mocked time, includes microseconds. + * + * @var string + */ + public const MOCK_DATETIME_FORMAT = 'Y-m-d H:i:s.u'; + + /** + * Pattern detection for ->isoFormat and ::createFromIsoFormat. + * + * @var string + */ + public const ISO_FORMAT_REGEXP = '(O[YMDHhms]|[Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY?|g{1,5}|G{1,5}|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?)'; + + // <methods> + + /** + * Dynamically handle calls to the class. + * + * @param string $method magic method name called + * @param array $parameters parameters list + * + * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable + * + * @return mixed + */ + public function __call($method, $parameters); + + /** + * Dynamically handle calls to the class. + * + * @param string $method magic method name called + * @param array $parameters parameters list + * + * @throws BadMethodCallException + * + * @return mixed + */ + public static function __callStatic($method, $parameters); + + /** + * Update constructedObjectId on cloned. + */ + public function __clone(); + + /** + * Create a new Carbon instance. + * + * Please see the testing aids section (specifically static::setTestNow()) + * for more on the possibility of this constructor returning a test instance. + * + * @param DateTimeInterface|string|null $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + */ + public function __construct($time = null, $tz = null); + + /** + * Show truthy properties on var_dump(). + * + * @return array + */ + public function __debugInfo(); + + /** + * Get a part of the Carbon object + * + * @param string $name + * + * @throws UnknownGetterException + * + * @return string|int|bool|DateTimeZone|null + */ + public function __get($name); + + /** + * Check if an attribute exists on the object + * + * @param string $name + * + * @return bool + */ + public function __isset($name); + + /** + * Set a part of the Carbon object + * + * @param string $name + * @param string|int|DateTimeZone $value + * + * @throws UnknownSetterException|ReflectionException + * + * @return void + */ + public function __set($name, $value); + + /** + * The __set_state handler. + * + * @param string|array $dump + * + * @return static + */ + #[ReturnTypeWillChange] + public static function __set_state($dump); + + /** + * Returns the list of properties to dump on serialize() called on. + * + * Only used by PHP < 7.4. + * + * @return array + */ + public function __sleep(); + + /** + * Format the instance as a string using the set format + * + * @example + * ``` + * echo Carbon::now(); // Carbon instances can be cast to string + * ``` + * + * @return string + */ + public function __toString(); + + /** + * Add given units or interval to the current instance. + * + * @example $date->add('hour', 3) + * @example $date->add(15, 'days') + * @example $date->add(CarbonInterval::days(4)) + * + * @param string|DateInterval|Closure|CarbonConverterInterface $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + #[ReturnTypeWillChange] + public function add($unit, $value = 1, $overflow = null); + + /** + * Add seconds to the instance using timestamp. Positive $value travels + * forward while negative $value travels into the past. + * + * @param string $unit + * @param int $value + * + * @return static + */ + public function addRealUnit($unit, $value = 1); + + /** + * Add given units to the current instance. + * + * @param string $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + public function addUnit($unit, $value = 1, $overflow = null); + + /** + * Add any unit to a new value without overflowing current other unit given. + * + * @param string $valueUnit unit name to modify + * @param int $value amount to add to the input unit + * @param string $overflowUnit unit name to not overflow + * + * @return static + */ + public function addUnitNoOverflow($valueUnit, $value, $overflowUnit); + + /** + * Get the difference in a human readable format in the current locale from an other + * instance given to now + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single part) + * @param int $options human diff options + * + * @return string + */ + public function ago($syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Modify the current instance to the average of a given instance (default now) and the current instance + * (second-precision). + * + * @param \Carbon\Carbon|\DateTimeInterface|null $date + * + * @return static + */ + public function average($date = null); + + /** + * Clone the current instance if it's mutable. + * + * This method is convenient to ensure you don't mutate the initial object + * but avoid to make a useless copy of it if it's already immutable. + * + * @return static + */ + public function avoidMutation(); + + /** + * Determines if the instance is between two others. + * + * The third argument allow you to specify if bounds are included or not (true by default) + * but for when you including/excluding bounds may produce different results in your application, + * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. + * + * @example + * ``` + * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * @param bool $equal Indicates if an equal to comparison should be done + * + * @return bool + */ + public function between($date1, $date2, $equal = true): bool; + + /** + * Determines if the instance is between two others, bounds excluded. + * + * @example + * ``` + * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return bool + */ + public function betweenExcluded($date1, $date2): bool; + + /** + * Determines if the instance is between two others, bounds included. + * + * @example + * ``` + * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return bool + */ + public function betweenIncluded($date1, $date2): bool; + + /** + * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, + * or a calendar date (e.g. "10/29/2017") otherwise. + * + * Language, date and time formats will change according to the current locale. + * + * @param Carbon|\DateTimeInterface|string|null $referenceTime + * @param array $formats + * + * @return string + */ + public function calendar($referenceTime = null, array $formats = []); + + /** + * Checks if the (date)time string is in a given format and valid to create a + * new instance. + * + * @example + * ``` + * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true + * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false + * ``` + * + * @param string $date + * @param string $format + * + * @return bool + */ + public static function canBeCreatedFromFormat($date, $format); + + /** + * Return the Carbon instance passed through, a now instance in the same timezone + * if null given or parse the input if string given. + * + * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date + * + * @return static + */ + public function carbonize($date = null); + + /** + * Cast the current instance into the given class. + * + * @param string $className The $className::instance() method will be called to cast the current object. + * + * @return DateTimeInterface + */ + public function cast(string $className); + + /** + * Ceil the current instance second with given precision if specified. + * + * @param float|int|string|\DateInterval|null $precision + * + * @return CarbonInterface + */ + public function ceil($precision = 1); + + /** + * Ceil the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int $precision + * + * @return CarbonInterface + */ + public function ceilUnit($unit, $precision = 1); + + /** + * Ceil the current instance week. + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return CarbonInterface + */ + public function ceilWeek($weekStartsAt = null); + + /** + * Similar to native modify() method of DateTime but can handle more grammars. + * + * @example + * ``` + * echo Carbon::now()->change('next 2pm'); + * ``` + * + * @link https://php.net/manual/en/datetime.modify.php + * + * @param string $modifier + * + * @return static|false + */ + public function change($modifier); + + /** + * Cleanup properties attached to the public scope of DateTime when a dump of the date is requested. + * foreach ($date as $_) {} + * serializer($date) + * var_export($date) + * get_object_vars($date) + */ + public function cleanupDumpProperties(); + + /** + * @alias copy + * + * Get a copy of the instance. + * + * @return static + */ + public function clone(); + + /** + * Get the closest date from the instance (second-precision). + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return static + */ + public function closest($date1, $date2); + + /** + * Get a copy of the instance. + * + * @return static + */ + public function copy(); + + /** + * Create a new Carbon instance from a specific date and time. + * + * If any of $year, $month or $day are set to null their now() values will + * be used. + * + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * + * If $hour is not null then the default values for $minute and $second + * will be 0. + * + * @param DateTimeInterface|int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null); + + /** + * Create a Carbon instance from just a date. The time portion is set to now. + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createFromDate($year = null, $month = null, $day = null, $tz = null); + + /** + * Create a Carbon instance from a specific format. + * + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + #[ReturnTypeWillChange] + public static function createFromFormat($format, $time, $tz = null); + + /** + * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). + * + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $tz optional timezone + * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) + * @param \Symfony\Component\Translation\TranslatorInterface $translator optional custom translator to use for macro-formats + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null); + + /** + * Create a Carbon instance from a specific format and a string in a given language. + * + * @param string $format Datetime format + * @param string $locale + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function createFromLocaleFormat($format, $locale, $time, $tz = null); + + /** + * Create a Carbon instance from a specific ISO format and a string in a given language. + * + * @param string $format Datetime ISO format + * @param string $locale + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function createFromLocaleIsoFormat($format, $locale, $time, $tz = null); + + /** + * Create a Carbon instance from just a time. The date portion is set to today. + * + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null); + + /** + * Create a Carbon instance from a time string. The date portion is set to today. + * + * @param string $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createFromTimeString($time, $tz = null); + + /** + * Create a Carbon instance from a timestamp and set the timezone (use default one if not specified). + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * @param \DateTimeZone|string|null $tz + * + * @return static + */ + public static function createFromTimestamp($timestamp, $tz = null); + + /** + * Create a Carbon instance from a timestamp in milliseconds. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * @param \DateTimeZone|string|null $tz + * + * @return static + */ + public static function createFromTimestampMs($timestamp, $tz = null); + + /** + * Create a Carbon instance from a timestamp in milliseconds. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * + * @return static + */ + public static function createFromTimestampMsUTC($timestamp); + + /** + * Create a Carbon instance from an timestamp keeping the timezone to UTC. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * + * @return static + */ + public static function createFromTimestampUTC($timestamp); + + /** + * Create a Carbon instance from just a date. The time portion is set to midnight. + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createMidnightDate($year = null, $month = null, $day = null, $tz = null); + + /** + * Create a new safe Carbon instance from a specific date and time. + * + * If any of $year, $month or $day are set to null their now() values will + * be used. + * + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * + * If $hour is not null then the default values for $minute and $second + * will be 0. + * + * If one of the set values is not valid, an InvalidDateException + * will be thrown. + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidDateException + * + * @return static|false + */ + public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null); + + /** + * Create a new Carbon instance from a specific date and time using strict validation. + * + * @see create() + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $tz = null); + + /** + * Get/set the day of year. + * + * @param int|null $value new value for day of year if using as setter. + * + * @return static|int + */ + public function dayOfYear($value = null); + + /** + * Get the difference as a CarbonInterval instance. + * Return relative interval (negative if $absolute flag is not set to true and the given date is before + * current one). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return CarbonInterval + */ + public function diffAsCarbonInterval($date = null, $absolute = true, array $skip = []); + + /** + * Get the difference by the given interval using a filter closure. + * + * @param CarbonInterval $ci An interval to traverse by + * @param Closure $callback + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, $absolute = true); + + /** + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + * + * @example + * ``` + * echo Carbon::tomorrow()->diffForHumans() . "\n"; + * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; + * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; + * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; + * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; + * ``` + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'skip' entry, list of units to skip (array of strings or a single string, + * ` it can be the unit name (singular or plural) or its shortcut + * ` (y, m, w, d, h, min, s, ms, µs). + * - 'aUnit' entry, prefer "an hour" over "1 hour" if true + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * - 'minimumUnit' entry determines the smallest unit of time to display can be long or + * ` short form of the units, e.g. 'hour' or 'h' (default value: s) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Get the difference in days rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInDays($date = null, $absolute = true); + + /** + * Get the difference in days using a filter closure rounded down. + * + * @param Closure $callback + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInDaysFiltered(Closure $callback, $date = null, $absolute = true); + + /** + * Get the difference in hours rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInHours($date = null, $absolute = true); + + /** + * Get the difference in hours using a filter closure rounded down. + * + * @param Closure $callback + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInHoursFiltered(Closure $callback, $date = null, $absolute = true); + + /** + * Get the difference in microseconds. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMicroseconds($date = null, $absolute = true); + + /** + * Get the difference in milliseconds rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMilliseconds($date = null, $absolute = true); + + /** + * Get the difference in minutes rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMinutes($date = null, $absolute = true); + + /** + * Get the difference in months rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMonths($date = null, $absolute = true); + + /** + * Get the difference in quarters rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInQuarters($date = null, $absolute = true); + + /** + * Get the difference in hours rounded down using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealHours($date = null, $absolute = true); + + /** + * Get the difference in microseconds using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealMicroseconds($date = null, $absolute = true); + + /** + * Get the difference in milliseconds rounded down using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealMilliseconds($date = null, $absolute = true); + + /** + * Get the difference in minutes rounded down using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealMinutes($date = null, $absolute = true); + + /** + * Get the difference in seconds using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealSeconds($date = null, $absolute = true); + + /** + * Get the difference in seconds rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInSeconds($date = null, $absolute = true); + + /** + * Get the difference in weekdays rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInWeekdays($date = null, $absolute = true); + + /** + * Get the difference in weekend days using a filter rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInWeekendDays($date = null, $absolute = true); + + /** + * Get the difference in weeks rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInWeeks($date = null, $absolute = true); + + /** + * Get the difference in years + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInYears($date = null, $absolute = true); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * @param int $humanDiffOption + */ + public static function disableHumanDiffOption($humanDiffOption); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * @param int $humanDiffOption + */ + public static function enableHumanDiffOption($humanDiffOption); + + /** + * Modify to end of current given unit. + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->startOf('month') + * ->endOf('week', Carbon::FRIDAY); + * ``` + * + * @param string $unit + * @param array<int, mixed> $params + * + * @return static + */ + public function endOf($unit, ...$params); + + /** + * Resets the date to end of the century and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfCentury(); + * ``` + * + * @return static + */ + public function endOfCentury(); + + /** + * Resets the time to 23:59:59.999999 end of day + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfDay(); + * ``` + * + * @return static + */ + public function endOfDay(); + + /** + * Resets the date to end of the decade and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfDecade(); + * ``` + * + * @return static + */ + public function endOfDecade(); + + /** + * Modify to end of current hour, minutes and seconds become 59 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfHour(); + * ``` + * + * @return static + */ + public function endOfHour(); + + /** + * Resets the date to end of the millennium and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfMillennium(); + * ``` + * + * @return static + */ + public function endOfMillennium(); + + /** + * Modify to end of current minute, seconds become 59 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfMinute(); + * ``` + * + * @return static + */ + public function endOfMinute(); + + /** + * Resets the date to end of the month and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfMonth(); + * ``` + * + * @return static + */ + public function endOfMonth(); + + /** + * Resets the date to end of the quarter and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfQuarter(); + * ``` + * + * @return static + */ + public function endOfQuarter(); + + /** + * Modify to end of current second, microseconds become 999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->endOfSecond() + * ->format('H:i:s.u'); + * ``` + * + * @return static + */ + public function endOfSecond(); + + /** + * Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->endOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek(Carbon::SATURDAY) . "\n"; + * ``` + * + * @param int $weekEndsAt optional start allow you to specify the day of week to use to end the week + * + * @return static + */ + public function endOfWeek($weekEndsAt = null); + + /** + * Resets the date to end of the year and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfYear(); + * ``` + * + * @return static + */ + public function endOfYear(); + + /** + * Determines if the instance is equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true + * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see equalTo() + * + * @return bool + */ + public function eq($date): bool; + + /** + * Determines if the instance is equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true + * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function equalTo($date): bool; + + /** + * Set the current locale to the given, execute the passed function, reset the locale to previous one, + * then return the result of the closure (or null if the closure was void). + * + * @param string $locale locale ex. en + * @param callable $func + * + * @return mixed + */ + public static function executeWithLocale($locale, $func); + + /** + * Get the farthest date from the instance (second-precision). + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return static + */ + public function farthest($date1, $date2); + + /** + * Modify to the first occurrence of a given day of the week + * in the current month. If no dayOfWeek is provided, modify to the + * first day of the current month. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek + * + * @return static + */ + public function firstOfMonth($dayOfWeek = null); + + /** + * Modify to the first occurrence of a given day of the week + * in the current quarter. If no dayOfWeek is provided, modify to the + * first day of the current quarter. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function firstOfQuarter($dayOfWeek = null); + + /** + * Modify to the first occurrence of a given day of the week + * in the current year. If no dayOfWeek is provided, modify to the + * first day of the current year. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function firstOfYear($dayOfWeek = null); + + /** + * Get the difference in days as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInDays($date = null, $absolute = true); + + /** + * Get the difference in hours as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInHours($date = null, $absolute = true); + + /** + * Get the difference in minutes as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInMinutes($date = null, $absolute = true); + + /** + * Get the difference in months as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInMonths($date = null, $absolute = true); + + /** + * Get the difference in days as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealDays($date = null, $absolute = true); + + /** + * Get the difference in hours as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealHours($date = null, $absolute = true); + + /** + * Get the difference in minutes as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealMinutes($date = null, $absolute = true); + + /** + * Get the difference in months as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealMonths($date = null, $absolute = true); + + /** + * Get the difference in seconds as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealSeconds($date = null, $absolute = true); + + /** + * Get the difference in weeks as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealWeeks($date = null, $absolute = true); + + /** + * Get the difference in year as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealYears($date = null, $absolute = true); + + /** + * Get the difference in seconds as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInSeconds($date = null, $absolute = true); + + /** + * Get the difference in weeks as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInWeeks($date = null, $absolute = true); + + /** + * Get the difference in year as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInYears($date = null, $absolute = true); + + /** + * Round the current instance second with given precision if specified. + * + * @param float|int|string|\DateInterval|null $precision + * + * @return CarbonInterface + */ + public function floor($precision = 1); + + /** + * Truncate the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int $precision + * + * @return CarbonInterface + */ + public function floorUnit($unit, $precision = 1); + + /** + * Truncate the current instance week. + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return CarbonInterface + */ + public function floorWeek($weekStartsAt = null); + + /** + * Format the instance with the current locale. You can set the current + * locale using setlocale() https://php.net/setlocale. + * + * @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1. + * Use ->isoFormat() instead. + * Deprecated since 2.55.0 + * + * @param string $format + * + * @return string + */ + public function formatLocalized($format); + + /** + * @alias diffForHumans + * + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Get the difference in a human readable format in the current locale from current + * instance to now. + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function fromNow($syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Create an instance from a serialized string. + * + * @param string $value + * + * @throws InvalidFormatException + * + * @return static + */ + public static function fromSerialized($value); + + /** + * Register a custom macro. + * + * @param object|callable $macro + * @param int $priority marco with higher priority is tried first + * + * @return void + */ + public static function genericMacro($macro, $priority = 0); + + /** + * Get a part of the Carbon object + * + * @param string $name + * + * @throws UnknownGetterException + * + * @return string|int|bool|DateTimeZone|null + */ + public function get($name); + + /** + * Returns the alternative number for a given date property if available in the current locale. + * + * @param string $key date property + * + * @return string + */ + public function getAltNumber(string $key): string; + + /** + * Returns the list of internally available locales and already loaded custom locales. + * (It will ignore custom translator dynamic loading.) + * + * @return array + */ + public static function getAvailableLocales(); + + /** + * Returns list of Language object for each available locale. This object allow you to get the ISO name, native + * name, region and variant of the locale. + * + * @return Language[] + */ + public static function getAvailableLocalesInfo(); + + /** + * Returns list of calendar formats for ISO formatting. + * + * @param string|null $locale current locale used if null + * + * @return array + */ + public function getCalendarFormats($locale = null); + + /** + * Get the days of the week + * + * @return array + */ + public static function getDays(); + + /** + * Return the number of days since the start of the week (using the current locale or the first parameter + * if explicitly given). + * + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return int + */ + public function getDaysFromStartOfWeek(?int $weekStartsAt = null): int; + + /** + * Get the fallback locale. + * + * @see https://symfony.com/doc/current/components/translation.html#fallback-locales + * + * @return string|null + */ + public static function getFallbackLocale(); + + /** + * List of replacements from date() format to isoFormat(). + * + * @return array + */ + public static function getFormatsToIsoReplacements(); + + /** + * Return default humanDiff() options (merged flags as integer). + * + * @return int + */ + public static function getHumanDiffOptions(); + + /** + * Returns list of locale formats for ISO formatting. + * + * @param string|null $locale current locale used if null + * + * @return array + */ + public function getIsoFormats($locale = null); + + /** + * Returns list of locale units for ISO formatting. + * + * @return array + */ + public static function getIsoUnits(); + + /** + * {@inheritdoc} + * + * @return array + */ + #[ReturnTypeWillChange] + public static function getLastErrors(); + + /** + * Get the raw callable macro registered globally or locally for a given name. + * + * @param string $name + * + * @return callable|null + */ + public function getLocalMacro($name); + + /** + * Get the translator of the current instance or the default if none set. + * + * @return \Symfony\Component\Translation\TranslatorInterface + */ + public function getLocalTranslator(); + + /** + * Get the current translator locale. + * + * @return string + */ + public static function getLocale(); + + /** + * Get the raw callable macro registered globally for a given name. + * + * @param string $name + * + * @return callable|null + */ + public static function getMacro($name); + + /** + * get midday/noon hour + * + * @return int + */ + public static function getMidDayAt(); + + /** + * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). + * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first + * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something + * like "-12:00". + * + * @param string $separator string to place between hours and minutes (":" by default) + * + * @return string + */ + public function getOffsetString($separator = ':'); + + /** + * Returns a unit of the instance padded with 0 by default or any other string if specified. + * + * @param string $unit Carbon unit name + * @param int $length Length of the output (2 by default) + * @param string $padString String to use for padding ("0" by default) + * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) + * + * @return string + */ + public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = 0); + + /** + * Returns a timestamp rounded with the given precision (6 by default). + * + * @example getPreciseTimestamp() 1532087464437474 (microsecond maximum precision) + * @example getPreciseTimestamp(6) 1532087464437474 + * @example getPreciseTimestamp(5) 153208746443747 (1/100000 second precision) + * @example getPreciseTimestamp(4) 15320874644375 (1/10000 second precision) + * @example getPreciseTimestamp(3) 1532087464437 (millisecond precision) + * @example getPreciseTimestamp(2) 153208746444 (1/100 second precision) + * @example getPreciseTimestamp(1) 15320874644 (1/10 second precision) + * @example getPreciseTimestamp(0) 1532087464 (second precision) + * @example getPreciseTimestamp(-1) 153208746 (10 second precision) + * @example getPreciseTimestamp(-2) 15320875 (100 second precision) + * + * @param int $precision + * + * @return float + */ + public function getPreciseTimestamp($precision = 6); + + /** + * Returns current local settings. + * + * @return array + */ + public function getSettings(); + + /** + * Get the Carbon instance (real or mock) to be returned when a "now" + * instance is created. + * + * @return Closure|static the current instance used for testing + */ + public static function getTestNow(); + + /** + * Return a format from H:i to H:i:s.u according to given unit precision. + * + * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" + * + * @return string + */ + public static function getTimeFormatByPrecision($unitPrecision); + + /** + * Returns the timestamp with millisecond precision. + * + * @return int + */ + public function getTimestampMs(); + + /** + * Get the translation of the current week day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * @param string $keySuffix "", "_short" or "_min" + * @param string|null $defaultValue default value if translation missing + * + * @return string + */ + public function getTranslatedDayName($context = null, $keySuffix = '', $defaultValue = null); + + /** + * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * + * @return string + */ + public function getTranslatedMinDayName($context = null); + + /** + * Get the translation of the current month day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * @param string $keySuffix "" or "_short" + * @param string|null $defaultValue default value if translation missing + * + * @return string + */ + public function getTranslatedMonthName($context = null, $keySuffix = '', $defaultValue = null); + + /** + * Get the translation of the current short week day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * + * @return string + */ + public function getTranslatedShortDayName($context = null); + + /** + * Get the translation of the current short month day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * + * @return string + */ + public function getTranslatedShortMonthName($context = null); + + /** + * Returns raw translation message for a given key. + * + * @param string $key key to find + * @param string|null $locale current locale used if null + * @param string|null $default default value if translation returns the key + * @param \Symfony\Component\Translation\TranslatorInterface $translator an optional translator to use + * + * @return string + */ + public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null); + + /** + * Returns raw translation message for a given key. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator the translator to use + * @param string $key key to find + * @param string|null $locale current locale used if null + * @param string|null $default default value if translation returns the key + * + * @return string + */ + public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null); + + /** + * Get the default translator instance in use. + * + * @return \Symfony\Component\Translation\TranslatorInterface + */ + public static function getTranslator(); + + /** + * Get the last day of week + * + * @return int + */ + public static function getWeekEndsAt(); + + /** + * Get the first day of week + * + * @return int + */ + public static function getWeekStartsAt(); + + /** + * Get weekend days + * + * @return array + */ + public static function getWeekendDays(); + + /** + * Determines if the instance is greater (after) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function greaterThan($date): bool; + + /** + * Determines if the instance is greater (after) than or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function greaterThanOrEqualTo($date): bool; + + /** + * Determines if the instance is greater (after) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see greaterThan() + * + * @return bool + */ + public function gt($date): bool; + + /** + * Determines if the instance is greater (after) than or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see greaterThanOrEqualTo() + * + * @return bool + */ + public function gte($date): bool; + + /** + * Checks if the (date)time string is in a given format. + * + * @example + * ``` + * Carbon::hasFormat('11:12:45', 'h:i:s'); // true + * Carbon::hasFormat('13:12:45', 'h:i:s'); // false + * ``` + * + * @param string $date + * @param string $format + * + * @return bool + */ + public static function hasFormat($date, $format); + + /** + * Checks if the (date)time string is in a given format. + * + * @example + * ``` + * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true + * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false + * ``` + * + * @param string $date + * @param string $format + * + * @return bool + */ + public static function hasFormatWithModifiers($date, $format): bool; + + /** + * Checks if macro is registered globally or locally. + * + * @param string $name + * + * @return bool + */ + public function hasLocalMacro($name); + + /** + * Return true if the current instance has its own translator. + * + * @return bool + */ + public function hasLocalTranslator(); + + /** + * Checks if macro is registered globally. + * + * @param string $name + * + * @return bool + */ + public static function hasMacro($name); + + /** + * Determine if a time string will produce a relative date. + * + * @param string $time + * + * @return bool true if time match a relative date, false if absolute or invalid time string + */ + public static function hasRelativeKeywords($time); + + /** + * Determine if there is a valid test instance set. A valid test instance + * is anything that is not null. + * + * @return bool true if there is a test instance, otherwise false + */ + public static function hasTestNow(); + + /** + * Create a Carbon instance from a DateTime one. + * + * @param DateTimeInterface $date + * + * @return static + */ + public static function instance($date); + + /** + * Returns true if the current date matches the given string. + * + * @example + * ``` + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true + * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true + * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false + * ``` + * + * @param string $tester day name, month name, hour, date, etc. as string + * + * @return bool + */ + public function is(string $tester); + + /** + * Determines if the instance is greater (after) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see greaterThan() + * + * @return bool + */ + public function isAfter($date): bool; + + /** + * Determines if the instance is less (before) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see lessThan() + * + * @return bool + */ + public function isBefore($date): bool; + + /** + * Determines if the instance is between two others + * + * @example + * ``` + * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * @param bool $equal Indicates if an equal to comparison should be done + * + * @return bool + */ + public function isBetween($date1, $date2, $equal = true): bool; + + /** + * Check if its the birthday. Compares the date/month values of the two dates. + * + * @example + * ``` + * Carbon::now()->subYears(5)->isBirthday(); // true + * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false + * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true + * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use current day. + * + * @return bool + */ + public function isBirthday($date = null); + + /** + * Determines if the instance is in the current unit given. + * + * @example + * ``` + * Carbon::now()->isCurrentUnit('hour'); // true + * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false + * ``` + * + * @param string $unit The unit to test. + * + * @throws BadMethodCallException + * + * @return bool + */ + public function isCurrentUnit($unit); + + /** + * Checks if this day is a specific day of the week. + * + * @example + * ``` + * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true + * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false + * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true + * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false + * ``` + * + * @param int $dayOfWeek + * + * @return bool + */ + public function isDayOfWeek($dayOfWeek); + + /** + * Check if the instance is end of day. + * + * @example + * ``` + * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true + * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true + * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true + * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false + * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true + * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false + * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false + * ``` + * + * @param bool $checkMicroseconds check time at microseconds precision + * + * @return bool + */ + public function isEndOfDay($checkMicroseconds = false); + + /** + * Returns true if the date was created using CarbonImmutable::endOfTime() + * + * @return bool + */ + public function isEndOfTime(): bool; + + /** + * Determines if the instance is in the future, ie. greater (after) than now. + * + * @example + * ``` + * Carbon::now()->addHours(5)->isFuture(); // true + * Carbon::now()->subHours(5)->isFuture(); // false + * ``` + * + * @return bool + */ + public function isFuture(); + + /** + * Returns true if the current class/instance is immutable. + * + * @return bool + */ + public static function isImmutable(); + + /** + * Check if today is the last day of the Month + * + * @example + * ``` + * Carbon::parse('2019-02-28')->isLastOfMonth(); // true + * Carbon::parse('2019-03-28')->isLastOfMonth(); // false + * Carbon::parse('2019-03-30')->isLastOfMonth(); // false + * Carbon::parse('2019-03-31')->isLastOfMonth(); // true + * Carbon::parse('2019-04-30')->isLastOfMonth(); // true + * ``` + * + * @return bool + */ + public function isLastOfMonth(); + + /** + * Determines if the instance is a leap year. + * + * @example + * ``` + * Carbon::parse('2020-01-01')->isLeapYear(); // true + * Carbon::parse('2019-01-01')->isLeapYear(); // false + * ``` + * + * @return bool + */ + public function isLeapYear(); + + /** + * Determines if the instance is a long year (using ISO 8601 year). + * + * @example + * ``` + * Carbon::parse('2015-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-03')->isLongIsoYear(); // false + * Carbon::parse('2019-12-29')->isLongIsoYear(); // false + * Carbon::parse('2019-12-30')->isLongIsoYear(); // true + * ``` + * + * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * @return bool + */ + public function isLongIsoYear(); + + /** + * Determines if the instance is a long year (using calendar year). + * + * ⚠️ This method completely ignores month and day to use the numeric year number, + * it's not correct if the exact date matters. For instance as `2019-12-30` is already + * in the first week of the 2020 year, if you want to know from this date if ISO week + * year 2020 is a long year, use `isLongIsoYear` instead. + * + * @example + * ``` + * Carbon::create(2015)->isLongYear(); // true + * Carbon::create(2016)->isLongYear(); // false + * ``` + * + * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * @return bool + */ + public function isLongYear(); + + /** + * Check if the instance is midday. + * + * @example + * ``` + * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false + * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true + * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true + * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false + * ``` + * + * @return bool + */ + public function isMidday(); + + /** + * Check if the instance is start of day / midnight. + * + * @example + * ``` + * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true + * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true + * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false + * ``` + * + * @return bool + */ + public function isMidnight(); + + /** + * Returns true if a property can be changed via setter. + * + * @param string $unit + * + * @return bool + */ + public static function isModifiableUnit($unit); + + /** + * Returns true if the current class/instance is mutable. + * + * @return bool + */ + public static function isMutable(); + + /** + * Determines if the instance is in the past, ie. less (before) than now. + * + * @example + * ``` + * Carbon::now()->subHours(5)->isPast(); // true + * Carbon::now()->addHours(5)->isPast(); // false + * ``` + * + * @return bool + */ + public function isPast(); + + /** + * Compares the formatted values of the two dates. + * + * @example + * ``` + * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true + * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false + * ``` + * + * @param string $format date formats to compare. + * @param \Carbon\Carbon|\DateTimeInterface|string|null $date instance to compare with or null to use current day. + * + * @return bool + */ + public function isSameAs($format, $date = null); + + /** + * Checks if the passed in date is in the same month as the instance´s month. + * + * @example + * ``` + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use the current date. + * @param bool $ofSameYear Check if it is the same month in the same year. + * + * @return bool + */ + public function isSameMonth($date = null, $ofSameYear = true); + + /** + * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). + * + * @example + * ``` + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|string|null $date The instance to compare with or null to use current day. + * @param bool $ofSameYear Check if it is the same month in the same year. + * + * @return bool + */ + public function isSameQuarter($date = null, $ofSameYear = true); + + /** + * Determines if the instance is in the current unit given. + * + * @example + * ``` + * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true + * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false + * ``` + * + * @param string $unit singular unit string + * @param \Carbon\Carbon|\DateTimeInterface|null $date instance to compare with or null to use current day. + * + * @throws BadComparisonUnitException + * + * @return bool + */ + public function isSameUnit($unit, $date = null); + + /** + * Check if the instance is start of day / midnight. + * + * @example + * ``` + * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true + * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true + * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false + * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true + * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false + * ``` + * + * @param bool $checkMicroseconds check time at microseconds precision + * + * @return bool + */ + public function isStartOfDay($checkMicroseconds = false); + + /** + * Returns true if the date was created using CarbonImmutable::startOfTime() + * + * @return bool + */ + public function isStartOfTime(): bool; + + /** + * Returns true if the strict mode is globally in use, false else. + * (It can be overridden in specific instances.) + * + * @return bool + */ + public static function isStrictModeEnabled(); + + /** + * Determines if the instance is today. + * + * @example + * ``` + * Carbon::today()->isToday(); // true + * Carbon::tomorrow()->isToday(); // false + * ``` + * + * @return bool + */ + public function isToday(); + + /** + * Determines if the instance is tomorrow. + * + * @example + * ``` + * Carbon::tomorrow()->isTomorrow(); // true + * Carbon::yesterday()->isTomorrow(); // false + * ``` + * + * @return bool + */ + public function isTomorrow(); + + /** + * Determines if the instance is a weekday. + * + * @example + * ``` + * Carbon::parse('2019-07-14')->isWeekday(); // false + * Carbon::parse('2019-07-15')->isWeekday(); // true + * ``` + * + * @return bool + */ + public function isWeekday(); + + /** + * Determines if the instance is a weekend day. + * + * @example + * ``` + * Carbon::parse('2019-07-14')->isWeekend(); // true + * Carbon::parse('2019-07-15')->isWeekend(); // false + * ``` + * + * @return bool + */ + public function isWeekend(); + + /** + * Determines if the instance is yesterday. + * + * @example + * ``` + * Carbon::yesterday()->isYesterday(); // true + * Carbon::tomorrow()->isYesterday(); // false + * ``` + * + * @return bool + */ + public function isYesterday(); + + /** + * Format in the current language using ISO replacement patterns. + * + * @param string $format + * @param string|null $originalFormat provide context if a chunk has been passed alone + * + * @return string + */ + public function isoFormat(string $format, ?string $originalFormat = null): string; + + /** + * Get/set the week number using given first day of week and first + * day of year included in the first week. Or use ISO format if no settings + * given. + * + * @param int|null $week + * @param int|null $dayOfWeek + * @param int|null $dayOfYear + * + * @return int|static + */ + public function isoWeek($week = null, $dayOfWeek = null, $dayOfYear = null); + + /** + * Set/get the week number of year using given first day of week and first + * day of year included in the first week. Or use ISO format if no settings + * given. + * + * @param int|null $year if null, act as a getter, if not null, set the year and return current instance. + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int|static + */ + public function isoWeekYear($year = null, $dayOfWeek = null, $dayOfYear = null); + + /** + * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). + * + * @param int|null $value new value for weekday if using as setter. + * + * @return static|int + */ + public function isoWeekday($value = null); + + /** + * Get the number of weeks of the current week-year using given first day of week and first + * day of year included in the first week. Or use ISO format if no settings + * given. + * + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int + */ + public function isoWeeksInYear($dayOfWeek = null, $dayOfYear = null); + + /** + * Prepare the object for JSON serialization. + * + * @return array|string + */ + #[ReturnTypeWillChange] + public function jsonSerialize(); + + /** + * Modify to the last occurrence of a given day of the week + * in the current month. If no dayOfWeek is provided, modify to the + * last day of the current month. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek + * + * @return static + */ + public function lastOfMonth($dayOfWeek = null); + + /** + * Modify to the last occurrence of a given day of the week + * in the current quarter. If no dayOfWeek is provided, modify to the + * last day of the current quarter. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function lastOfQuarter($dayOfWeek = null); + + /** + * Modify to the last occurrence of a given day of the week + * in the current year. If no dayOfWeek is provided, modify to the + * last day of the current year. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function lastOfYear($dayOfWeek = null); + + /** + * Determines if the instance is less (before) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function lessThan($date): bool; + + /** + * Determines if the instance is less (before) or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function lessThanOrEqualTo($date): bool; + + /** + * Get/set the locale for the current instance. + * + * @param string|null $locale + * @param string ...$fallbackLocales + * + * @return $this|string + */ + public function locale(?string $locale = null, ...$fallbackLocales); + + /** + * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). + * Support is considered enabled if the 3 words are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasDiffOneDayWords($locale); + + /** + * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasDiffSyntax($locale); + + /** + * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). + * Support is considered enabled if the 2 words are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasDiffTwoDayWords($locale); + + /** + * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasPeriodSyntax($locale); + + /** + * Returns true if the given locale is internally supported and has short-units support. + * Support is considered enabled if either year, day or hour has a short variant translated. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasShortUnits($locale); + + /** + * Determines if the instance is less (before) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see lessThan() + * + * @return bool + */ + public function lt($date): bool; + + /** + * Determines if the instance is less (before) or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see lessThanOrEqualTo() + * + * @return bool + */ + public function lte($date): bool; + + /** + * Register a custom macro. + * + * @example + * ``` + * $userSettings = [ + * 'locale' => 'pt', + * 'timezone' => 'America/Sao_Paulo', + * ]; + * Carbon::macro('userFormat', function () use ($userSettings) { + * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar(); + * }); + * echo Carbon::yesterday()->hours(11)->userFormat(); + * ``` + * + * @param string $name + * @param object|callable $macro + * + * @return void + */ + public static function macro($name, $macro); + + /** + * Make a Carbon instance from given variable if possible. + * + * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals + * and recurrences). Throw an exception for invalid format, but otherwise return null. + * + * @param mixed $var + * + * @throws InvalidFormatException + * + * @return static|null + */ + public static function make($var); + + /** + * Get the maximum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return static + */ + public function max($date = null); + + /** + * Create a Carbon instance for the greatest supported date. + * + * @return static + */ + public static function maxValue(); + + /** + * Get the maximum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see max() + * + * @return static + */ + public function maximum($date = null); + + /** + * Return the meridiem of the current time in the current locale. + * + * @param bool $isLower if true, returns lowercase variant if available in the current locale. + * + * @return string + */ + public function meridiem(bool $isLower = false): string; + + /** + * Modify to midday, default to self::$midDayAt + * + * @return static + */ + public function midDay(); + + /** + * Get the minimum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return static + */ + public function min($date = null); + + /** + * Create a Carbon instance for the lowest supported date. + * + * @return static + */ + public static function minValue(); + + /** + * Get the minimum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see min() + * + * @return static + */ + public function minimum($date = null); + + /** + * Mix another object into the class. + * + * @example + * ``` + * Carbon::mixin(new class { + * public function addMoon() { + * return function () { + * return $this->addDays(30); + * }; + * } + * public function subMoon() { + * return function () { + * return $this->subDays(30); + * }; + * } + * }); + * $fullMoon = Carbon::create('2018-12-22'); + * $nextFullMoon = $fullMoon->addMoon(); + * $blackMoon = Carbon::create('2019-01-06'); + * $previousBlackMoon = $blackMoon->subMoon(); + * echo "$nextFullMoon\n"; + * echo "$previousBlackMoon\n"; + * ``` + * + * @param object|string $mixin + * + * @throws ReflectionException + * + * @return void + */ + public static function mixin($mixin); + + /** + * Calls \DateTime::modify if mutable or \DateTimeImmutable::modify else. + * + * @see https://php.net/manual/en/datetime.modify.php + * + * @return static|false + */ + #[ReturnTypeWillChange] + public function modify($modify); + + /** + * Determines if the instance is not equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false + * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see notEqualTo() + * + * @return bool + */ + public function ne($date): bool; + + /** + * Modify to the next occurrence of a given modifier such as a day of + * the week. If no modifier is provided, modify to the next occurrence + * of the current day of the week. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param string|int|null $modifier + * + * @return static|false + */ + public function next($modifier = null); + + /** + * Go forward to the next weekday. + * + * @return static + */ + public function nextWeekday(); + + /** + * Go forward to the next weekend day. + * + * @return static + */ + public function nextWeekendDay(); + + /** + * Determines if the instance is not equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false + * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function notEqualTo($date): bool; + + /** + * Get a Carbon instance for the current date and time. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function now($tz = null); + + /** + * Returns a present instance in the same timezone. + * + * @return static + */ + public function nowWithSameTz(); + + /** + * Modify to the given occurrence of a given day of the week + * in the current month. If the calculated occurrence is outside the scope + * of the current month, then return false and no modifications are made. + * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int $nth + * @param int $dayOfWeek + * + * @return mixed + */ + public function nthOfMonth($nth, $dayOfWeek); + + /** + * Modify to the given occurrence of a given day of the week + * in the current quarter. If the calculated occurrence is outside the scope + * of the current quarter, then return false and no modifications are made. + * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int $nth + * @param int $dayOfWeek + * + * @return mixed + */ + public function nthOfQuarter($nth, $dayOfWeek); + + /** + * Modify to the given occurrence of a given day of the week + * in the current year. If the calculated occurrence is outside the scope + * of the current year, then return false and no modifications are made. + * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int $nth + * @param int $dayOfWeek + * + * @return mixed + */ + public function nthOfYear($nth, $dayOfWeek); + + /** + * Return a property with its ordinal. + * + * @param string $key + * @param string|null $period + * + * @return string + */ + public function ordinal(string $key, ?string $period = null): string; + + /** + * Create a carbon instance from a string. + * + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * + * @param string|DateTimeInterface|null $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function parse($time = null, $tz = null); + + /** + * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). + * + * @param string $time date/time string in the given language (may also contain English). + * @param string|null $locale if locale is null or not specified, current global locale will be + * used instead. + * @param DateTimeZone|string|null $tz optional timezone for the new instance. + * + * @throws InvalidFormatException + * + * @return static + */ + public static function parseFromLocale($time, $locale = null, $tz = null); + + /** + * Returns standardized plural of a given singular/plural unit name (in English). + * + * @param string $unit + * + * @return string + */ + public static function pluralUnit(string $unit): string; + + /** + * Modify to the previous occurrence of a given modifier such as a day of + * the week. If no dayOfWeek is provided, modify to the previous occurrence + * of the current day of the week. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param string|int|null $modifier + * + * @return static|false + */ + public function previous($modifier = null); + + /** + * Go backward to the previous weekday. + * + * @return static + */ + public function previousWeekday(); + + /** + * Go backward to the previous weekend day. + * + * @return static + */ + public function previousWeekendDay(); + + /** + * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). + * + * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date + * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit + * @param string|null $unit if specified, $interval must be an integer + * + * @return CarbonPeriod + */ + public function range($end = null, $interval = null, $unit = null); + + /** + * Call native PHP DateTime/DateTimeImmutable add() method. + * + * @param DateInterval $interval + * + * @return static + */ + public function rawAdd(DateInterval $interval); + + /** + * Create a Carbon instance from a specific format. + * + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function rawCreateFromFormat($format, $time, $tz = null); + + /** + * @see https://php.net/manual/en/datetime.format.php + * + * @param string $format + * + * @return string + */ + public function rawFormat($format); + + /** + * Create a carbon instance from a string. + * + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * + * @param string|DateTimeInterface|null $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function rawParse($time = null, $tz = null); + + /** + * Call native PHP DateTime/DateTimeImmutable sub() method. + * + * @param DateInterval $interval + * + * @return static + */ + public function rawSub(DateInterval $interval); + + /** + * Remove all macros and generic macros. + */ + public static function resetMacros(); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Reset the month overflow behavior. + * + * @return void + */ + public static function resetMonthsOverflow(); + + /** + * Reset the format used to the default when type juggling a Carbon instance to a string + * + * @return void + */ + public static function resetToStringFormat(); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Reset the month overflow behavior. + * + * @return void + */ + public static function resetYearsOverflow(); + + /** + * Round the current instance second with given precision if specified. + * + * @param float|int|string|\DateInterval|null $precision + * @param string $function + * + * @return CarbonInterface + */ + public function round($precision = 1, $function = 'round'); + + /** + * Round the current instance at the given unit with given precision if specified and the given function. + * + * @param string $unit + * @param float|int $precision + * @param string $function + * + * @return CarbonInterface + */ + public function roundUnit($unit, $precision = 1, $function = 'round'); + + /** + * Round the current instance week. + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return CarbonInterface + */ + public function roundWeek($weekStartsAt = null); + + /** + * The number of seconds since midnight. + * + * @return int + */ + public function secondsSinceMidnight(); + + /** + * The number of seconds until 23:59:59. + * + * @return int + */ + public function secondsUntilEndOfDay(); + + /** + * Return a serialized string of the instance. + * + * @return string + */ + public function serialize(); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather transform Carbon object before the serialization. + * + * JSON serialize all Carbon instances using the given callback. + * + * @param callable $callback + * + * @return void + */ + public static function serializeUsing($callback); + + /** + * Set a part of the Carbon object + * + * @param string|array $name + * @param string|int|DateTimeZone $value + * + * @throws ImmutableException|UnknownSetterException + * + * @return $this + */ + public function set($name, $value = null); + + /** + * Set the date with gregorian year, month and day numbers. + * + * @see https://php.net/manual/en/datetime.setdate.php + * + * @param int $year + * @param int $month + * @param int $day + * + * @return static + */ + #[ReturnTypeWillChange] + public function setDate($year, $month, $day); + + /** + * Set the year, month, and date for this instance to that of the passed instance. + * + * @param Carbon|DateTimeInterface $date now if null + * + * @return static + */ + public function setDateFrom($date = null); + + /** + * Set the date and time all together. + * + * @param int $year + * @param int $month + * @param int $day + * @param int $hour + * @param int $minute + * @param int $second + * @param int $microseconds + * + * @return static + */ + public function setDateTime($year, $month, $day, $hour, $minute, $second = 0, $microseconds = 0); + + /** + * Set the date and time for this instance to that of the passed instance. + * + * @param Carbon|DateTimeInterface $date + * + * @return static + */ + public function setDateTimeFrom($date = null); + + /** + * Set the day (keeping the current time) to the start of the week + the number of days passed as the first + * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. + * + * @param int $numberOfDays number of days to add after the start of the current week + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return static + */ + public function setDaysFromStartOfWeek(int $numberOfDays, ?int $weekStartsAt = null); + + /** + * Set the fallback locale. + * + * @see https://symfony.com/doc/current/components/translation.html#fallback-locales + * + * @param string $locale + */ + public static function setFallbackLocale($locale); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * @param int $humanDiffOptions + */ + public static function setHumanDiffOptions($humanDiffOptions); + + /** + * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. + * + * @see https://php.net/manual/en/datetime.setisodate.php + * + * @param int $year + * @param int $week + * @param int $day + * + * @return static + */ + #[ReturnTypeWillChange] + public function setISODate($year, $week, $day = 1); + + /** + * Set the translator for the current instance. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator + * + * @return $this + */ + public function setLocalTranslator(TranslatorInterface $translator); + + /** + * Set the current translator locale and indicate if the source locale file exists. + * Pass 'auto' as locale to use closest language from the current LC_TIME locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function setLocale($locale); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider mid-day is always 12pm, then if you need to test if it's an other + * hour, test it explicitly: + * $date->format('G') == 13 + * or to set explicitly to a given hour: + * $date->setTime(13, 0, 0, 0) + * + * Set midday/noon hour + * + * @param int $hour midday hour + * + * @return void + */ + public static function setMidDayAt($hour); + + /** + * Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * + * Note the timezone parameter was left out of the examples above and + * has no affect as the mock value will be returned regardless of its value. + * + * Only the moment is mocked with setTestNow(), the timezone will still be the one passed + * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()). + * + * To clear the test instance call this method using the default + * parameter of null. + * + * /!\ Use this method for unit tests only. + * + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + */ + public static function setTestNow($testNow = null); + + /** + * Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * + * It will also align default timezone (e.g. call date_default_timezone_set()) with + * the second argument or if null, with the timezone of the given date object. + * + * To clear the test instance call this method using the default + * parameter of null. + * + * /!\ Use this method for unit tests only. + * + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + */ + public static function setTestNowAndTimezone($testNow = null, $tz = null); + + /** + * Resets the current time of the DateTime object to a different time. + * + * @see https://php.net/manual/en/datetime.settime.php + * + * @param int $hour + * @param int $minute + * @param int $second + * @param int $microseconds + * + * @return static + */ + #[ReturnTypeWillChange] + public function setTime($hour, $minute, $second = 0, $microseconds = 0); + + /** + * Set the hour, minute, second and microseconds for this instance to that of the passed instance. + * + * @param Carbon|DateTimeInterface $date now if null + * + * @return static + */ + public function setTimeFrom($date = null); + + /** + * Set the time by time string. + * + * @param string $time + * + * @return static + */ + public function setTimeFromTimeString($time); + + /** + * Set the instance's timestamp. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $unixTimestamp + * + * @return static + */ + #[ReturnTypeWillChange] + public function setTimestamp($unixTimestamp); + + /** + * Set the instance's timezone from a string or object. + * + * @param DateTimeZone|string $value + * + * @return static + */ + #[ReturnTypeWillChange] + public function setTimezone($value); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string + * format. + * + * Set the default format used when type juggling a Carbon instance to a string. + * + * @param string|Closure|null $format + * + * @return void + */ + public static function setToStringFormat($format); + + /** + * Set the default translator instance to use. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator + * + * @return void + */ + public static function setTranslator(TranslatorInterface $translator); + + /** + * Set specified unit to new given value. + * + * @param string $unit year, month, day, hour, minute, second or microsecond + * @param int $value new value for given unit + * + * @return static + */ + public function setUnit($unit, $value = null); + + /** + * Set any unit to a new value without overflowing current other unit given. + * + * @param string $valueUnit unit name to modify + * @param int $value new value for the input unit + * @param string $overflowUnit unit name to not overflow + * + * @return static + */ + public function setUnitNoOverflow($valueUnit, $value, $overflowUnit); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use UTF-8 language packages on every machine. + * + * Set if UTF8 will be used for localized date/time. + * + * @param bool $utf8 + */ + public static function setUtf8($utf8); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek + * or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the + * start of week according to current locale selected and implicitly the end of week. + * + * Set the last day of week + * + * @param int|string $day week end day (or 'auto' to get the day before the first day of week + * from Carbon::getLocale() culture). + * + * @return void + */ + public static function setWeekEndsAt($day); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the + * 'first_day_of_week' locale setting to change the start of week according to current locale + * selected and implicitly the end of week. + * + * Set the first day of week + * + * @param int|string $day week start day (or 'auto' to get the first day of week from Carbon::getLocale() culture). + * + * @return void + */ + public static function setWeekStartsAt($day); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider week-end is always saturday and sunday, and if you have some custom + * week-end days to handle, give to those days an other name and create a macro for them: + * + * ``` + * Carbon::macro('isDayOff', function ($date) { + * return $date->isSunday() || $date->isMonday(); + * }); + * Carbon::macro('isNotDayOff', function ($date) { + * return !$date->isDayOff(); + * }); + * if ($someDate->isDayOff()) ... + * if ($someDate->isNotDayOff()) ... + * // Add 5 not-off days + * $count = 5; + * while ($someDate->isDayOff() || ($count-- > 0)) { + * $someDate->addDay(); + * } + * ``` + * + * Set weekend days + * + * @param array $days + * + * @return void + */ + public static function setWeekendDays($days); + + /** + * Set specific options. + * - strictMode: true|false|null + * - monthOverflow: true|false|null + * - yearOverflow: true|false|null + * - humanDiffOptions: int|null + * - toStringFormat: string|Closure|null + * - toJsonFormat: string|Closure|null + * - locale: string|null + * - timezone: \DateTimeZone|string|int|null + * - macros: array|null + * - genericMacros: array|null + * + * @param array $settings + * + * @return $this|static + */ + public function settings(array $settings); + + /** + * Set the instance's timezone from a string or object and add/subtract the offset difference. + * + * @param DateTimeZone|string $value + * + * @return static + */ + public function shiftTimezone($value); + + /** + * Get the month overflow global behavior (can be overridden in specific instances). + * + * @return bool + */ + public static function shouldOverflowMonths(); + + /** + * Get the month overflow global behavior (can be overridden in specific instances). + * + * @return bool + */ + public static function shouldOverflowYears(); + + /** + * @alias diffForHumans + * + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + */ + public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Returns standardized singular of a given singular/plural unit name (in English). + * + * @param string $unit + * + * @return string + */ + public static function singularUnit(string $unit): string; + + /** + * Modify to start of current given unit. + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->startOf('month') + * ->endOf('week', Carbon::FRIDAY); + * ``` + * + * @param string $unit + * @param array<int, mixed> $params + * + * @return static + */ + public function startOf($unit, ...$params); + + /** + * Resets the date to the first day of the century and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfCentury(); + * ``` + * + * @return static + */ + public function startOfCentury(); + + /** + * Resets the time to 00:00:00 start of day + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfDay(); + * ``` + * + * @return static + */ + public function startOfDay(); + + /** + * Resets the date to the first day of the decade and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfDecade(); + * ``` + * + * @return static + */ + public function startOfDecade(); + + /** + * Modify to start of current hour, minutes and seconds become 0 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfHour(); + * ``` + * + * @return static + */ + public function startOfHour(); + + /** + * Resets the date to the first day of the millennium and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfMillennium(); + * ``` + * + * @return static + */ + public function startOfMillennium(); + + /** + * Modify to start of current minute, seconds become 0 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfMinute(); + * ``` + * + * @return static + */ + public function startOfMinute(); + + /** + * Resets the date to the first day of the month and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfMonth(); + * ``` + * + * @return static + */ + public function startOfMonth(); + + /** + * Resets the date to the first day of the quarter and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfQuarter(); + * ``` + * + * @return static + */ + public function startOfQuarter(); + + /** + * Modify to start of current second, microseconds become 0 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->startOfSecond() + * ->format('H:i:s.u'); + * ``` + * + * @return static + */ + public function startOfSecond(); + + /** + * Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->startOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek(Carbon::SUNDAY) . "\n"; + * ``` + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return static + */ + public function startOfWeek($weekStartsAt = null); + + /** + * Resets the date to the first day of the year and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfYear(); + * ``` + * + * @return static + */ + public function startOfYear(); + + /** + * Subtract given units or interval to the current instance. + * + * @example $date->sub('hour', 3) + * @example $date->sub(15, 'days') + * @example $date->sub(CarbonInterval::days(4)) + * + * @param string|DateInterval|Closure|CarbonConverterInterface $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + #[ReturnTypeWillChange] + public function sub($unit, $value = 1, $overflow = null); + + public function subRealUnit($unit, $value = 1); + + /** + * Subtract given units to the current instance. + * + * @param string $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + public function subUnit($unit, $value = 1, $overflow = null); + + /** + * Subtract any unit to a new value without overflowing current other unit given. + * + * @param string $valueUnit unit name to modify + * @param int $value amount to subtract to the input unit + * @param string $overflowUnit unit name to not overflow + * + * @return static + */ + public function subUnitNoOverflow($valueUnit, $value, $overflowUnit); + + /** + * Subtract given units or interval to the current instance. + * + * @see sub() + * + * @param string|DateInterval $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + public function subtract($unit, $value = 1, $overflow = null); + + /** + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + * + * @return string + */ + public function timespan($other = null, $timezone = null); + + /** + * Set the instance's timestamp. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $unixTimestamp + * + * @return static + */ + public function timestamp($unixTimestamp); + + /** + * @alias setTimezone + * + * @param DateTimeZone|string $value + * + * @return static + */ + public function timezone($value); + + /** + * Get the difference in a human readable format in the current locale from an other + * instance given (or now if null given) to current instance. + * + * When comparing a value in the past to default now: + * 1 hour from now + * 5 months from now + * + * When comparing a value in the future to default now: + * 1 hour ago + * 5 months ago + * + * When comparing a value in the past to another value: + * 1 hour after + * 5 months after + * + * When comparing a value in the future to another value: + * 1 hour before + * 5 months before + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Get default array representation. + * + * @example + * ``` + * var_dump(Carbon::now()->toArray()); + * ``` + * + * @return array + */ + public function toArray(); + + /** + * Format the instance as ATOM + * + * @example + * ``` + * echo Carbon::now()->toAtomString(); + * ``` + * + * @return string + */ + public function toAtomString(); + + /** + * Format the instance as COOKIE + * + * @example + * ``` + * echo Carbon::now()->toCookieString(); + * ``` + * + * @return string + */ + public function toCookieString(); + + /** + * @alias toDateTime + * + * Return native DateTime PHP object matching the current instance. + * + * @example + * ``` + * var_dump(Carbon::now()->toDate()); + * ``` + * + * @return DateTime + */ + public function toDate(); + + /** + * Format the instance as date + * + * @example + * ``` + * echo Carbon::now()->toDateString(); + * ``` + * + * @return string + */ + public function toDateString(); + + /** + * Return native DateTime PHP object matching the current instance. + * + * @example + * ``` + * var_dump(Carbon::now()->toDateTime()); + * ``` + * + * @return DateTime + */ + public function toDateTime(); + + /** + * Return native toDateTimeImmutable PHP object matching the current instance. + * + * @example + * ``` + * var_dump(Carbon::now()->toDateTimeImmutable()); + * ``` + * + * @return DateTimeImmutable + */ + public function toDateTimeImmutable(); + + /** + * Format the instance as date and time T-separated with no timezone + * + * @example + * ``` + * echo Carbon::now()->toDateTimeLocalString(); + * echo "\n"; + * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toDateTimeLocalString($unitPrecision = 'second'); + + /** + * Format the instance as date and time + * + * @example + * ``` + * echo Carbon::now()->toDateTimeString(); + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toDateTimeString($unitPrecision = 'second'); + + /** + * Format the instance with day, date and time + * + * @example + * ``` + * echo Carbon::now()->toDayDateTimeString(); + * ``` + * + * @return string + */ + public function toDayDateTimeString(); + + /** + * Format the instance as a readable date + * + * @example + * ``` + * echo Carbon::now()->toFormattedDateString(); + * ``` + * + * @return string + */ + public function toFormattedDateString(); + + /** + * Format the instance with the day, and a readable date + * + * @example + * ``` + * echo Carbon::now()->toFormattedDayDateString(); + * ``` + * + * @return string + */ + public function toFormattedDayDateString(): string; + + /** + * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: + * 1977-04-22T01:00:00-05:00). + * + * @example + * ``` + * echo Carbon::now('America/Toronto')->toISOString() . "\n"; + * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; + * ``` + * + * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. + * + * @return null|string + */ + public function toISOString($keepOffset = false); + + /** + * Return a immutable copy of the instance. + * + * @return CarbonImmutable + */ + public function toImmutable(); + + /** + * Format the instance as ISO8601 + * + * @example + * ``` + * echo Carbon::now()->toIso8601String(); + * ``` + * + * @return string + */ + public function toIso8601String(); + + /** + * Convert the instance to UTC and return as Zulu ISO8601 + * + * @example + * ``` + * echo Carbon::now()->toIso8601ZuluString(); + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toIso8601ZuluString($unitPrecision = 'second'); + + /** + * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. + * + * @example + * ``` + * echo Carbon::now('America/Toronto')->toJSON(); + * ``` + * + * @return null|string + */ + public function toJSON(); + + /** + * Return a mutable copy of the instance. + * + * @return Carbon + */ + public function toMutable(); + + /** + * Get the difference in a human readable format in the current locale from an other + * instance given to now + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single part) + * @param int $options human diff options + * + * @return string + */ + public function toNow($syntax = null, $short = false, $parts = 1, $options = null); + + /** + * Get default object representation. + * + * @example + * ``` + * var_dump(Carbon::now()->toObject()); + * ``` + * + * @return object + */ + public function toObject(); + + /** + * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). + * + * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int + * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit + * @param string|null $unit if specified, $interval must be an integer + * + * @return CarbonPeriod + */ + public function toPeriod($end = null, $interval = null, $unit = null); + + /** + * Format the instance as RFC1036 + * + * @example + * ``` + * echo Carbon::now()->toRfc1036String(); + * ``` + * + * @return string + */ + public function toRfc1036String(); + + /** + * Format the instance as RFC1123 + * + * @example + * ``` + * echo Carbon::now()->toRfc1123String(); + * ``` + * + * @return string + */ + public function toRfc1123String(); + + /** + * Format the instance as RFC2822 + * + * @example + * ``` + * echo Carbon::now()->toRfc2822String(); + * ``` + * + * @return string + */ + public function toRfc2822String(); + + /** + * Format the instance as RFC3339 + * + * @param bool $extended + * + * @example + * ``` + * echo Carbon::now()->toRfc3339String() . "\n"; + * echo Carbon::now()->toRfc3339String(true) . "\n"; + * ``` + * + * @return string + */ + public function toRfc3339String($extended = false); + + /** + * Format the instance as RFC7231 + * + * @example + * ``` + * echo Carbon::now()->toRfc7231String(); + * ``` + * + * @return string + */ + public function toRfc7231String(); + + /** + * Format the instance as RFC822 + * + * @example + * ``` + * echo Carbon::now()->toRfc822String(); + * ``` + * + * @return string + */ + public function toRfc822String(); + + /** + * Format the instance as RFC850 + * + * @example + * ``` + * echo Carbon::now()->toRfc850String(); + * ``` + * + * @return string + */ + public function toRfc850String(); + + /** + * Format the instance as RSS + * + * @example + * ``` + * echo Carbon::now()->toRssString(); + * ``` + * + * @return string + */ + public function toRssString(); + + /** + * Returns english human readable complete date string. + * + * @example + * ``` + * echo Carbon::now()->toString(); + * ``` + * + * @return string + */ + public function toString(); + + /** + * Format the instance as time + * + * @example + * ``` + * echo Carbon::now()->toTimeString(); + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toTimeString($unitPrecision = 'second'); + + /** + * Format the instance as W3C + * + * @example + * ``` + * echo Carbon::now()->toW3cString(); + * ``` + * + * @return string + */ + public function toW3cString(); + + /** + * Create a Carbon instance for today. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function today($tz = null); + + /** + * Create a Carbon instance for tomorrow. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function tomorrow($tz = null); + + /** + * Translate using translation string or callback available. + * + * @param string $key + * @param array $parameters + * @param string|int|float|null $number + * @param \Symfony\Component\Translation\TranslatorInterface|null $translator + * @param bool $altNumbers + * + * @return string + */ + public function translate(string $key, array $parameters = [], $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false): string; + + /** + * Returns the alternative number for a given integer if available in the current locale. + * + * @param int $number + * + * @return string + */ + public function translateNumber(int $number): string; + + /** + * Translate a time string from a locale to an other. + * + * @param string $timeString date/time/duration string to translate (may also contain English) + * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) + * @param string|null $to output locale of the result returned (`"en"` by default) + * @param int $mode specify what to translate with options: + * - self::TRANSLATE_ALL (default) + * - CarbonInterface::TRANSLATE_MONTHS + * - CarbonInterface::TRANSLATE_DAYS + * - CarbonInterface::TRANSLATE_UNITS + * - CarbonInterface::TRANSLATE_MERIDIEM + * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS + * + * @return string + */ + public static function translateTimeString($timeString, $from = null, $to = null, $mode = self::TRANSLATE_ALL); + + /** + * Translate a time string from the current locale (`$date->locale()`) to an other. + * + * @param string $timeString time string to translate + * @param string|null $to output locale of the result returned ("en" by default) + * + * @return string + */ + public function translateTimeStringTo($timeString, $to = null); + + /** + * Translate using translation string or callback available. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator + * @param string $key + * @param array $parameters + * @param null $number + * + * @return string + */ + public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string; + + /** + * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) + * but translate words whenever possible (months, day names, etc.) using the current locale. + * + * @param string $format + * + * @return string + */ + public function translatedFormat(string $format): string; + + /** + * Set the timezone or returns the timezone name if no arguments passed. + * + * @param DateTimeZone|string $value + * + * @return static|string + */ + public function tz($value = null); + + /** + * @alias getTimestamp + * + * Returns the UNIX timestamp for the current date. + * + * @return int + */ + public function unix(); + + /** + * @alias to + * + * Get the difference in a human readable format in the current locale from an other + * instance given (or now if null given) to current instance. + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Indicates if months should be calculated with overflow. + * + * @param bool $monthsOverflow + * + * @return void + */ + public static function useMonthsOverflow($monthsOverflow = true); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * Enable the strict mode (or disable with passing false). + * + * @param bool $strictModeEnabled + */ + public static function useStrictMode($strictModeEnabled = true); + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Indicates if years should be calculated with overflow. + * + * @param bool $yearsOverflow + * + * @return void + */ + public static function useYearsOverflow($yearsOverflow = true); + + /** + * Set the instance's timezone to UTC. + * + * @return static + */ + public function utc(); + + /** + * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. + * + * @param int|null $minuteOffset + * + * @return int|static + */ + public function utcOffset(?int $minuteOffset = null); + + /** + * Returns the milliseconds timestamps used amongst other by Date javascript objects. + * + * @return float + */ + public function valueOf(); + + /** + * Get/set the week number using given first day of week and first + * day of year included in the first week. Or use US format if no settings + * given (Sunday / Jan 6). + * + * @param int|null $week + * @param int|null $dayOfWeek + * @param int|null $dayOfYear + * + * @return int|static + */ + public function week($week = null, $dayOfWeek = null, $dayOfYear = null); + + /** + * Set/get the week number of year using given first day of week and first + * day of year included in the first week. Or use US format if no settings + * given (Sunday / Jan 6). + * + * @param int|null $year if null, act as a getter, if not null, set the year and return current instance. + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int|static + */ + public function weekYear($year = null, $dayOfWeek = null, $dayOfYear = null); + + /** + * Get/set the weekday from 0 (Sunday) to 6 (Saturday). + * + * @param int|null $value new value for weekday if using as setter. + * + * @return static|int + */ + public function weekday($value = null); + + /** + * Get the number of weeks of the current week-year using given first day of week and first + * day of year included in the first week. Or use US format if no settings + * given (Sunday / Jan 6). + * + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int + */ + public function weeksInYear($dayOfWeek = null, $dayOfYear = null); + + /** + * Temporarily sets a static date to be used within the callback. + * Using setTestNow to set the date, executing the callback, then + * clearing the test instance. + * + * /!\ Use this method for unit tests only. + * + * @template T + * + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + * @param Closure(): T $callback + * + * @return T + */ + public static function withTestNow($testNow, $callback); + + /** + * Create a Carbon instance for yesterday. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function yesterday($tz = null); + + // </methods> +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php new file mode 100644 index 0000000..8437c54 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php @@ -0,0 +1,3054 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\Exceptions\BadFluentConstructorException; +use Carbon\Exceptions\BadFluentSetterException; +use Carbon\Exceptions\InvalidCastException; +use Carbon\Exceptions\InvalidIntervalException; +use Carbon\Exceptions\OutOfRangeException; +use Carbon\Exceptions\ParseErrorException; +use Carbon\Exceptions\UnitNotConfiguredException; +use Carbon\Exceptions\UnknownGetterException; +use Carbon\Exceptions\UnknownSetterException; +use Carbon\Exceptions\UnknownUnitException; +use Carbon\Traits\IntervalRounding; +use Carbon\Traits\IntervalStep; +use Carbon\Traits\MagicParameter; +use Carbon\Traits\Mixin; +use Carbon\Traits\Options; +use Carbon\Traits\ToStringFormat; +use Closure; +use DateInterval; +use DateMalformedIntervalStringException; +use DateTimeInterface; +use DateTimeZone; +use Exception; +use InvalidArgumentException; +use ReflectionException; +use ReturnTypeWillChange; +use RuntimeException; +use Throwable; + +/** + * A simple API extension for DateInterval. + * The implementation provides helpers to handle weeks but only days are saved. + * Weeks are calculated based on the total days of the current instance. + * + * @property int $years Total years of the current interval. + * @property int $months Total months of the current interval. + * @property int $weeks Total weeks of the current interval calculated from the days. + * @property int $dayz Total days of the current interval (weeks * 7 + days). + * @property int $hours Total hours of the current interval. + * @property int $minutes Total minutes of the current interval. + * @property int $seconds Total seconds of the current interval. + * @property int $microseconds Total microseconds of the current interval. + * @property int $milliseconds Total milliseconds of the current interval. + * @property int $microExcludeMilli Remaining microseconds without the milliseconds. + * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). + * @property int $daysExcludeWeeks alias of dayzExcludeWeeks + * @property-read float $totalYears Number of years equivalent to the interval. + * @property-read float $totalMonths Number of months equivalent to the interval. + * @property-read float $totalWeeks Number of weeks equivalent to the interval. + * @property-read float $totalDays Number of days equivalent to the interval. + * @property-read float $totalDayz Alias for totalDays. + * @property-read float $totalHours Number of hours equivalent to the interval. + * @property-read float $totalMinutes Number of minutes equivalent to the interval. + * @property-read float $totalSeconds Number of seconds equivalent to the interval. + * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. + * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. + * @property-read string $locale locale of the current instance + * + * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. + * @method static CarbonInterval year($years = 1) Alias for years() + * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. + * @method static CarbonInterval month($months = 1) Alias for months() + * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. + * @method static CarbonInterval week($weeks = 1) Alias for weeks() + * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. + * @method static CarbonInterval dayz($days = 1) Alias for days() + * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. + * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() + * @method static CarbonInterval day($days = 1) Alias for days() + * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. + * @method static CarbonInterval hour($hours = 1) Alias for hours() + * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. + * @method static CarbonInterval minute($minutes = 1) Alias for minutes() + * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. + * @method static CarbonInterval second($seconds = 1) Alias for seconds() + * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. + * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() + * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. + * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() + * @method $this addYears(int $years) Add given number of years to the current interval + * @method $this subYears(int $years) Subtract given number of years to the current interval + * @method $this addMonths(int $months) Add given number of months to the current interval + * @method $this subMonths(int $months) Subtract given number of months to the current interval + * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval + * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval + * @method $this addDays(int|float $days) Add given number of days to the current interval + * @method $this subDays(int|float $days) Subtract given number of days to the current interval + * @method $this addHours(int|float $hours) Add given number of hours to the current interval + * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval + * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval + * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval + * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval + * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval + * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval + * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval + * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval + * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval + * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. + * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. + * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. + * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. + * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. + * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. + * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. + * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. + * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. + * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. + * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. + * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. + * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. + * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. + * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. + * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. + * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. + * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. + * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. + * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. + * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. + * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. + * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. + * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. + * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. + * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. + * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. + * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. + * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. + * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. + * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. + * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. + * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. + * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. + * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. + * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. + * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. + * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. + */ +class CarbonInterval extends DateInterval implements CarbonConverterInterface +{ + use IntervalRounding; + use IntervalStep; + use MagicParameter; + use Mixin { + Mixin::mixin as baseMixin; + } + use Options; + use ToStringFormat; + + /** + * Interval spec period designators + */ + public const PERIOD_PREFIX = 'P'; + public const PERIOD_YEARS = 'Y'; + public const PERIOD_MONTHS = 'M'; + public const PERIOD_DAYS = 'D'; + public const PERIOD_TIME_PREFIX = 'T'; + public const PERIOD_HOURS = 'H'; + public const PERIOD_MINUTES = 'M'; + public const PERIOD_SECONDS = 'S'; + + /** + * A translator to ... er ... translate stuff + * + * @var \Symfony\Component\Translation\TranslatorInterface + */ + protected static $translator; + + /** + * @var array|null + */ + protected static $cascadeFactors; + + /** + * @var array + */ + protected static $formats = [ + 'y' => 'y', + 'Y' => 'y', + 'o' => 'y', + 'm' => 'm', + 'n' => 'm', + 'W' => 'weeks', + 'd' => 'd', + 'j' => 'd', + 'z' => 'd', + 'h' => 'h', + 'g' => 'h', + 'H' => 'h', + 'G' => 'h', + 'i' => 'i', + 's' => 's', + 'u' => 'micro', + 'v' => 'milli', + ]; + + /** + * @var array|null + */ + private static $flipCascadeFactors; + + /** + * @var bool + */ + private static $floatSettersEnabled = false; + + /** + * The registered macros. + * + * @var array + */ + protected static $macros = []; + + /** + * Timezone handler for settings() method. + * + * @var mixed + */ + protected $tzName; + + /** + * Set the instance's timezone from a string or object. + * + * @param \DateTimeZone|string $tzName + * + * @return static + */ + public function setTimezone($tzName) + { + $this->tzName = $tzName; + + return $this; + } + + /** + * @internal + * + * Set the instance's timezone from a string or object and add/subtract the offset difference. + * + * @param \DateTimeZone|string $tzName + * + * @return static + */ + public function shiftTimezone($tzName) + { + $this->tzName = $tzName; + + return $this; + } + + /** + * Mapping of units and factors for cascading. + * + * Should only be modified by changing the factors or referenced constants. + * + * @return array + */ + public static function getCascadeFactors() + { + return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); + } + + protected static function getDefaultCascadeFactors(): array + { + return [ + 'milliseconds' => [Carbon::MICROSECONDS_PER_MILLISECOND, 'microseconds'], + 'seconds' => [Carbon::MILLISECONDS_PER_SECOND, 'milliseconds'], + 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], + 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], + 'dayz' => [Carbon::HOURS_PER_DAY, 'hours'], + 'weeks' => [Carbon::DAYS_PER_WEEK, 'dayz'], + 'months' => [Carbon::WEEKS_PER_MONTH, 'weeks'], + 'years' => [Carbon::MONTHS_PER_YEAR, 'months'], + ]; + } + + private static function standardizeUnit($unit) + { + $unit = rtrim($unit, 'sz').'s'; + + return $unit === 'days' ? 'dayz' : $unit; + } + + private static function getFlipCascadeFactors() + { + if (!self::$flipCascadeFactors) { + self::$flipCascadeFactors = []; + + foreach (static::getCascadeFactors() as $to => [$factor, $from]) { + self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; + } + } + + return self::$flipCascadeFactors; + } + + /** + * Set default cascading factors for ->cascade() method. + * + * @param array $cascadeFactors + */ + public static function setCascadeFactors(array $cascadeFactors) + { + self::$flipCascadeFactors = null; + static::$cascadeFactors = $cascadeFactors; + } + + /** + * This option allow you to opt-in for the Carbon 3 behavior where float + * values will no longer be cast to integer (so truncated). + * + * ⚠️ This settings will be applied globally, which mean your whole application + * code including the third-party dependencies that also may use Carbon will + * adopt the new behavior. + */ + public static function enableFloatSetters(bool $floatSettersEnabled = true): void + { + self::$floatSettersEnabled = $floatSettersEnabled; + } + + /////////////////////////////////////////////////////////////////// + //////////////////////////// CONSTRUCTORS ///////////////////////// + /////////////////////////////////////////////////////////////////// + + /** + * Create a new CarbonInterval instance. + * + * @param Closure|DateInterval|string|int|null $years + * @param int|float|null $months + * @param int|float|null $weeks + * @param int|float|null $days + * @param int|float|null $hours + * @param int|float|null $minutes + * @param int|float|null $seconds + * @param int|float|null $microseconds + * + * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. + */ + public function __construct($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) + { + if ($years instanceof Closure) { + $this->step = $years; + $years = null; + } + + if ($years instanceof DateInterval) { + parent::__construct(static::getDateIntervalSpec($years)); + $this->f = $years->f; + self::copyNegativeUnits($years, $this); + + return; + } + + $spec = $years; + $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); + + if (!$isStringSpec || (float) $years) { + $spec = static::PERIOD_PREFIX; + + $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; + $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; + + $specDays = 0; + $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; + $specDays += $days > 0 ? $days : 0; + + $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; + + if ($hours > 0 || $minutes > 0 || $seconds > 0) { + $spec .= static::PERIOD_TIME_PREFIX; + $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; + $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; + $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; + } + + if ($spec === static::PERIOD_PREFIX) { + // Allow the zero interval. + $spec .= '0'.static::PERIOD_YEARS; + } + } + + try { + parent::__construct($spec); + } catch (Throwable $exception) { + try { + parent::__construct('PT0S'); + + if ($isStringSpec) { + if (!preg_match('/^P + (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? + (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? + (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? + (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? + (?:T + (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? + (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? + (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? + )? + $/x', $spec, $match)) { + throw new InvalidArgumentException("Invalid duration: $spec"); + } + + $years = (float) ($match['year'] ?? 0); + $this->assertSafeForInteger('year', $years); + $months = (float) ($match['month'] ?? 0); + $this->assertSafeForInteger('month', $months); + $weeks = (float) ($match['week'] ?? 0); + $this->assertSafeForInteger('week', $weeks); + $days = (float) ($match['day'] ?? 0); + $this->assertSafeForInteger('day', $days); + $hours = (float) ($match['hour'] ?? 0); + $this->assertSafeForInteger('hour', $hours); + $minutes = (float) ($match['minute'] ?? 0); + $this->assertSafeForInteger('minute', $minutes); + $seconds = (float) ($match['second'] ?? 0); + $this->assertSafeForInteger('second', $seconds); + } + + $totalDays = (($weeks * static::getDaysPerWeek()) + $days); + $this->assertSafeForInteger('days total (including weeks)', $totalDays); + + $this->y = (int) $years; + $this->m = (int) $months; + $this->d = (int) $totalDays; + $this->h = (int) $hours; + $this->i = (int) $minutes; + $this->s = (int) $seconds; + + if ( + ((float) $this->y) !== $years || + ((float) $this->m) !== $months || + ((float) $this->d) !== $totalDays || + ((float) $this->h) !== $hours || + ((float) $this->i) !== $minutes || + ((float) $this->s) !== $seconds + ) { + $this->add(static::fromString( + ($years - $this->y).' years '. + ($months - $this->m).' months '. + ($totalDays - $this->d).' days '. + ($hours - $this->h).' hours '. + ($minutes - $this->i).' minutes '. + ($seconds - $this->s).' seconds ' + )); + } + } catch (Throwable $secondException) { + throw $secondException instanceof OutOfRangeException ? $secondException : $exception; + } + } + + if ($microseconds !== null) { + $this->f = $microseconds / Carbon::MICROSECONDS_PER_SECOND; + } + } + + /** + * Returns the factor for a given source-to-target couple. + * + * @param string $source + * @param string $target + * + * @return int|float|null + */ + public static function getFactor($source, $target) + { + $source = self::standardizeUnit($source); + $target = self::standardizeUnit($target); + $factors = self::getFlipCascadeFactors(); + + if (isset($factors[$source])) { + [$to, $factor] = $factors[$source]; + + if ($to === $target) { + return $factor; + } + + return $factor * static::getFactor($to, $target); + } + + return null; + } + + /** + * Returns the factor for a given source-to-target couple if set, + * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. + * + * @param string $source + * @param string $target + * + * @return int|float|null + */ + public static function getFactorWithDefault($source, $target) + { + $factor = self::getFactor($source, $target); + + if ($factor) { + return $factor; + } + + static $defaults = [ + 'month' => ['year' => Carbon::MONTHS_PER_YEAR], + 'week' => ['month' => Carbon::WEEKS_PER_MONTH], + 'day' => ['week' => Carbon::DAYS_PER_WEEK], + 'hour' => ['day' => Carbon::HOURS_PER_DAY], + 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], + 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], + 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], + 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], + ]; + + return $defaults[$source][$target] ?? null; + } + + /** + * Returns current config for days per week. + * + * @return int|float + */ + public static function getDaysPerWeek() + { + return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; + } + + /** + * Returns current config for hours per day. + * + * @return int|float + */ + public static function getHoursPerDay() + { + return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; + } + + /** + * Returns current config for minutes per hour. + * + * @return int|float + */ + public static function getMinutesPerHour() + { + return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; + } + + /** + * Returns current config for seconds per minute. + * + * @return int|float + */ + public static function getSecondsPerMinute() + { + return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; + } + + /** + * Returns current config for microseconds per second. + * + * @return int|float + */ + public static function getMillisecondsPerSecond() + { + return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; + } + + /** + * Returns current config for microseconds per second. + * + * @return int|float + */ + public static function getMicrosecondsPerMillisecond() + { + return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; + } + + /** + * Create a new CarbonInterval instance from specific values. + * This is an alias for the constructor that allows better fluent + * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than + * (new CarbonInterval(1))->fn(). + * + * @param int $years + * @param int $months + * @param int $weeks + * @param int $days + * @param int $hours + * @param int $minutes + * @param int $seconds + * @param int $microseconds + * + * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. + * + * @return static + */ + public static function create($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) + { + return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); + } + + /** + * Parse a string into a new CarbonInterval object according to the specified format. + * + * @example + * ``` + * echo Carboninterval::createFromFormat('H:i', '1:30'); + * ``` + * + * @param string $format Format of the $interval input string + * @param string|null $interval Input string to convert into an interval + * + * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. + * + * @return static + */ + public static function createFromFormat(string $format, ?string $interval) + { + $instance = new static(0); + $length = mb_strlen($format); + + if (preg_match('/s([,.])([uv])$/', $format, $match)) { + $interval = explode($match[1], $interval); + $index = \count($interval) - 1; + $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); + $interval = implode($match[1], $interval); + } + + $interval = $interval ?? ''; + + for ($index = 0; $index < $length; $index++) { + $expected = mb_substr($format, $index, 1); + $nextCharacter = mb_substr($interval, 0, 1); + $unit = static::$formats[$expected] ?? null; + + if ($unit) { + if (!preg_match('/^-?\d+/', $interval, $match)) { + throw new ParseErrorException('number', $nextCharacter); + } + + $interval = mb_substr($interval, mb_strlen($match[0])); + $instance->$unit += (int) ($match[0]); + + continue; + } + + if ($nextCharacter !== $expected) { + throw new ParseErrorException( + "'$expected'", + $nextCharacter, + 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". + 'See https://php.net/manual/en/function.date.php for their meaning' + ); + } + + $interval = mb_substr($interval, 1); + } + + if ($interval !== '') { + throw new ParseErrorException( + 'end of string', + $interval + ); + } + + return $instance; + } + + /** + * Get a copy of the instance. + * + * @return static + */ + public function copy() + { + $date = new static(0); + $date->copyProperties($this); + $date->step = $this->step; + + return $date; + } + + /** + * Get a copy of the instance. + * + * @return static + */ + public function clone() + { + return $this->copy(); + } + + /** + * Provide static helpers to create instances. Allows CarbonInterval::years(3). + * + * Note: This is done using the magic method to allow static and instance methods to + * have the same names. + * + * @param string $method magic method name called + * @param array $parameters parameters list + * + * @return static|null + */ + public static function __callStatic($method, $parameters) + { + try { + $interval = new static(0); + $localStrictModeEnabled = $interval->localStrictModeEnabled; + $interval->localStrictModeEnabled = true; + + $result = static::hasMacro($method) + ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { + return $interval->callMacro($method, $parameters); + }) + : $interval->$method(...$parameters); + + $interval->localStrictModeEnabled = $localStrictModeEnabled; + + return $result; + } catch (BadFluentSetterException $exception) { + if (Carbon::isStrictModeEnabled()) { + throw new BadFluentConstructorException($method, 0, $exception); + } + + return null; + } + } + + /** + * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. + * + * @param array $dump data as exported by var_export() + * + * @return static + */ + #[ReturnTypeWillChange] + public static function __set_state($dump) + { + /** @noinspection PhpVoidFunctionResultUsedInspection */ + /** @var DateInterval $dateInterval */ + $dateInterval = parent::__set_state($dump); + + return static::instance($dateInterval); + } + + /** + * Return the current context from inside a macro callee or a new one if static. + * + * @return static + */ + protected static function this() + { + return end(static::$macroContextStack) ?: new static(0); + } + + /** + * Creates a CarbonInterval from string. + * + * Format: + * + * Suffix | Unit | Example | DateInterval expression + * -------|---------|---------|------------------------ + * y | years | 1y | P1Y + * mo | months | 3mo | P3M + * w | weeks | 2w | P2W + * d | days | 28d | P28D + * h | hours | 4h | PT4H + * m | minutes | 12m | PT12M + * s | seconds | 59s | PT59S + * + * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. + * + * Special cases: + * - An empty string will return a zero interval + * - Fractions are allowed for weeks, days, hours and minutes and will be converted + * and rounded to the next smaller value (caution: 0.5w = 4d) + * + * @param string $intervalDefinition + * + * @return static + */ + public static function fromString($intervalDefinition) + { + if (empty($intervalDefinition)) { + return new static(0); + } + + $years = 0; + $months = 0; + $weeks = 0; + $days = 0; + $hours = 0; + $minutes = 0; + $seconds = 0; + $milliseconds = 0; + $microseconds = 0; + + $pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; + preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); + + while ([$part, $value, $unit] = array_shift($parts)) { + $intValue = (int) $value; + $fraction = (float) $value - $intValue; + + // Fix calculation precision + switch (round($fraction, 6)) { + case 1: + $fraction = 0; + $intValue++; + + break; + case 0: + $fraction = 0; + + break; + } + + switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { + case 'millennia': + case 'millennium': + $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; + + break; + + case 'century': + case 'centuries': + $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; + + break; + + case 'decade': + case 'decades': + $years += $intValue * CarbonInterface::YEARS_PER_DECADE; + + break; + + case 'year': + case 'years': + case 'y': + case 'yr': + case 'yrs': + $years += $intValue; + + break; + + case 'quarter': + case 'quarters': + $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; + + break; + + case 'month': + case 'months': + case 'mo': + case 'mos': + $months += $intValue; + + break; + + case 'week': + case 'weeks': + case 'w': + $weeks += $intValue; + + if ($fraction) { + $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; + } + + break; + + case 'day': + case 'days': + case 'd': + $days += $intValue; + + if ($fraction) { + $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; + } + + break; + + case 'hour': + case 'hours': + case 'h': + $hours += $intValue; + + if ($fraction) { + $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; + } + + break; + + case 'minute': + case 'minutes': + case 'm': + $minutes += $intValue; + + if ($fraction) { + $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; + } + + break; + + case 'second': + case 'seconds': + case 's': + $seconds += $intValue; + + if ($fraction) { + $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; + } + + break; + + case 'millisecond': + case 'milliseconds': + case 'milli': + case 'ms': + $milliseconds += $intValue; + + if ($fraction) { + $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); + } + + break; + + case 'microsecond': + case 'microseconds': + case 'micro': + case 'µs': + $microseconds += $intValue; + + break; + + default: + throw new InvalidIntervalException( + sprintf('Invalid part %s in definition %s', $part, $intervalDefinition) + ); + } + } + + return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds); + } + + /** + * Creates a CarbonInterval from string using a different locale. + * + * @param string $interval interval string in the given language (may also contain English). + * @param string|null $locale if locale is null or not specified, current global locale will be used instead. + * + * @return static + */ + public static function parseFromLocale($interval, $locale = null) + { + return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), 'en')); + } + + private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []) + { + $mainClass = DateInterval::class; + + if (!is_a($className, $mainClass, true)) { + throw new InvalidCastException("$className is not a sub-class of $mainClass."); + } + + $microseconds = $interval->f; + $instance = new $className(static::getDateIntervalSpec($interval, false, $skip)); + + if ($microseconds) { + $instance->f = $microseconds; + } + + if ($interval instanceof self && is_a($className, self::class, true)) { + self::copyStep($interval, $instance); + } + + self::copyNegativeUnits($interval, $instance); + + return $instance; + } + + private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void + { + $to->invert = $from->invert; + + foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { + if ($from->$unit < 0) { + $to->$unit *= -1; + } + } + } + + private static function copyStep(self $from, self $to): void + { + $to->setStep($from->getStep()); + } + + /** + * Cast the current instance into the given class. + * + * @param string $className The $className::instance() method will be called to cast the current object. + * + * @return DateInterval + */ + public function cast(string $className) + { + return self::castIntervalToClass($this, $className); + } + + /** + * Create a CarbonInterval instance from a DateInterval one. Can not instance + * DateInterval objects created from DateTime::diff() as you can't externally + * set the $days field. + * + * @param DateInterval $interval + * @param bool $skipCopy set to true to return the passed object + * (without copying it) if it's already of the + * current class + * + * @return static + */ + public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false) + { + if ($skipCopy && $interval instanceof static) { + return $interval; + } + + return self::castIntervalToClass($interval, static::class, $skip); + } + + /** + * Make a CarbonInterval instance from given variable if possible. + * + * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates + * and recurrences). Throw an exception for invalid format, but otherwise return null. + * + * @param mixed|int|DateInterval|string|Closure|null $interval interval or number of the given $unit + * @param string|null $unit if specified, $interval must be an integer + * @param bool $skipCopy set to true to return the passed object + * (without copying it) if it's already of the + * current class + * + * @return static|null + */ + public static function make($interval, $unit = null, bool $skipCopy = false) + { + if ($unit) { + $interval = "$interval ".Carbon::pluralUnit($unit); + } + + if ($interval instanceof DateInterval) { + return static::instance($interval, [], $skipCopy); + } + + if ($interval instanceof Closure) { + return new static($interval); + } + + if (!\is_string($interval)) { + return null; + } + + return static::makeFromString($interval); + } + + protected static function makeFromString(string $interval) + { + $interval = preg_replace('/\s+/', ' ', trim($interval)); + + if (preg_match('/^P[T\d]/', $interval)) { + return new static($interval); + } + + if (preg_match('/^(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { + return static::fromString($interval); + } + + // @codeCoverageIgnoreStart + try { + /** @var static $interval */ + $interval = static::createFromDateString($interval); + } catch (DateMalformedIntervalStringException $e) { + return null; + } + // @codeCoverageIgnoreEnd + + return !$interval || $interval->isEmpty() ? null : $interval; + } + + protected function resolveInterval($interval) + { + if (!($interval instanceof self)) { + return self::make($interval); + } + + return $interval; + } + + /** + * Sets up a DateInterval from the relative parts of the string. + * + * @param string $time + * + * @return static + * + * @link https://php.net/manual/en/dateinterval.createfromdatestring.php + */ + #[ReturnTypeWillChange] + public static function createFromDateString($time) + { + $interval = @parent::createFromDateString(strtr($time, [ + ',' => ' ', + ' and ' => ' ', + ])); + + if ($interval instanceof DateInterval) { + $interval = static::instance($interval); + } + + return $interval; + } + + /////////////////////////////////////////////////////////////////// + ///////////////////////// GETTERS AND SETTERS ///////////////////// + /////////////////////////////////////////////////////////////////// + + /** + * Get a part of the CarbonInterval object. + * + * @param string $name + * + * @throws UnknownGetterException + * + * @return int|float|string + */ + public function get($name) + { + if (str_starts_with($name, 'total')) { + return $this->total(substr($name, 5)); + } + + switch ($name) { + case 'years': + return $this->y; + + case 'months': + return $this->m; + + case 'dayz': + return $this->d; + + case 'hours': + return $this->h; + + case 'minutes': + return $this->i; + + case 'seconds': + return $this->s; + + case 'milli': + case 'milliseconds': + return (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND); + + case 'micro': + case 'microseconds': + return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND); + + case 'microExcludeMilli': + return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND; + + case 'weeks': + return (int) ($this->d / (int) static::getDaysPerWeek()); + + case 'daysExcludeWeeks': + case 'dayzExcludeWeeks': + return $this->d % (int) static::getDaysPerWeek(); + + case 'locale': + return $this->getTranslatorLocale(); + + default: + throw new UnknownGetterException($name); + } + } + + /** + * Get a part of the CarbonInterval object. + * + * @param string $name + * + * @throws UnknownGetterException + * + * @return int|float|string + */ + public function __get($name) + { + return $this->get($name); + } + + /** + * Set a part of the CarbonInterval object. + * + * @param string|array $name + * @param int $value + * + * @throws UnknownSetterException + * + * @return $this + */ + public function set($name, $value = null) + { + $properties = \is_array($name) ? $name : [$name => $value]; + + foreach ($properties as $key => $value) { + switch (Carbon::singularUnit(rtrim($key, 'z'))) { + case 'year': + $this->checkIntegerValue($key, $value); + $this->y = $value; + $this->handleDecimalPart('year', $value, $this->y); + + break; + + case 'month': + $this->checkIntegerValue($key, $value); + $this->m = $value; + $this->handleDecimalPart('month', $value, $this->m); + + break; + + case 'week': + $this->checkIntegerValue($key, $value); + $days = $value * (int) static::getDaysPerWeek(); + $this->assertSafeForInteger('days total (including weeks)', $days); + $this->d = $days; + $this->handleDecimalPart('day', $days, $this->d); + + break; + + case 'day': + $this->checkIntegerValue($key, $value); + $this->d = $value; + $this->handleDecimalPart('day', $value, $this->d); + + break; + + case 'daysexcludeweek': + case 'dayzexcludeweek': + $this->checkIntegerValue($key, $value); + $days = $this->weeks * (int) static::getDaysPerWeek() + $value; + $this->assertSafeForInteger('days total (including weeks)', $days); + $this->d = $days; + $this->handleDecimalPart('day', $days, $this->d); + + break; + + case 'hour': + $this->checkIntegerValue($key, $value); + $this->h = $value; + $this->handleDecimalPart('hour', $value, $this->h); + + break; + + case 'minute': + $this->checkIntegerValue($key, $value); + $this->i = $value; + $this->handleDecimalPart('minute', $value, $this->i); + + break; + + case 'second': + $this->checkIntegerValue($key, $value); + $this->s = $value; + $this->handleDecimalPart('second', $value, $this->s); + + break; + + case 'milli': + case 'millisecond': + $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; + + break; + + case 'micro': + case 'microsecond': + $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; + + break; + + default: + if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { + throw new UnknownSetterException($key); + } + + $this->$key = $value; + } + } + + return $this; + } + + /** + * Set a part of the CarbonInterval object. + * + * @param string $name + * @param int $value + * + * @throws UnknownSetterException + */ + public function __set($name, $value) + { + $this->set($name, $value); + } + + /** + * Allow setting of weeks and days to be cumulative. + * + * @param int $weeks Number of weeks to set + * @param int $days Number of days to set + * + * @return static + */ + public function weeksAndDays($weeks, $days) + { + $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; + + return $this; + } + + /** + * Returns true if the interval is empty for each unit. + * + * @return bool + */ + public function isEmpty() + { + return $this->years === 0 && + $this->months === 0 && + $this->dayz === 0 && + !$this->days && + $this->hours === 0 && + $this->minutes === 0 && + $this->seconds === 0 && + $this->microseconds === 0; + } + + /** + * Register a custom macro. + * + * @example + * ``` + * CarbonInterval::macro('twice', function () { + * return $this->times(2); + * }); + * echo CarbonInterval::hours(2)->twice(); + * ``` + * + * @param string $name + * @param object|callable $macro + * + * @return void + */ + public static function macro($name, $macro) + { + static::$macros[$name] = $macro; + } + + /** + * Register macros from a mixin object. + * + * @example + * ``` + * CarbonInterval::mixin(new class { + * public function daysToHours() { + * return function () { + * $this->hours += $this->days; + * $this->days = 0; + * + * return $this; + * }; + * } + * public function hoursToDays() { + * return function () { + * $this->days += $this->hours; + * $this->hours = 0; + * + * return $this; + * }; + * } + * }); + * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; + * echo CarbonInterval::days(5)->daysToHours() . "\n"; + * ``` + * + * @param object|string $mixin + * + * @throws ReflectionException + * + * @return void + */ + public static function mixin($mixin) + { + static::baseMixin($mixin); + } + + /** + * Check if macro is registered. + * + * @param string $name + * + * @return bool + */ + public static function hasMacro($name) + { + return isset(static::$macros[$name]); + } + + /** + * Call given macro. + * + * @param string $name + * @param array $parameters + * + * @return mixed + */ + protected function callMacro($name, $parameters) + { + $macro = static::$macros[$name]; + + if ($macro instanceof Closure) { + $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); + + return ($boundMacro ?: $macro)(...$parameters); + } + + return $macro(...$parameters); + } + + /** + * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). + * + * Note: This is done using the magic method to allow static and instance methods to + * have the same names. + * + * @param string $method magic method name called + * @param array $parameters parameters list + * + * @throws BadFluentSetterException|Throwable + * + * @return static + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return static::bindMacroContext($this, function () use (&$method, &$parameters) { + return $this->callMacro($method, $parameters); + }); + } + + $roundedValue = $this->callRoundMethod($method, $parameters); + + if ($roundedValue !== null) { + return $roundedValue; + } + + if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { + $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); + + return $this->{$match['method']}($value, $match['unit']); + } + + $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); + + try { + $this->set($method, $value); + } catch (UnknownSetterException $exception) { + if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { + throw new BadFluentSetterException($method, 0, $exception); + } + } + + return $this; + } + + protected function getForHumansInitialVariables($syntax, $short) + { + if (\is_array($syntax)) { + return $syntax; + } + + if (\is_int($short)) { + return [ + 'parts' => $short, + 'short' => false, + ]; + } + + if (\is_bool($syntax)) { + return [ + 'short' => $syntax, + 'syntax' => CarbonInterface::DIFF_ABSOLUTE, + ]; + } + + return []; + } + + /** + * @param mixed $syntax + * @param mixed $short + * @param mixed $parts + * @param mixed $options + * + * @return array + */ + protected function getForHumansParameters($syntax = null, $short = false, $parts = -1, $options = null) + { + $optionalSpace = ' '; + $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; + $join = $default === '' ? '' : ' '; + $altNumbers = false; + $aUnit = false; + $minimumUnit = 's'; + $skip = []; + extract($this->getForHumansInitialVariables($syntax, $short)); + $skip = array_map('strtolower', array_filter((array) $skip, static function ($value) { + return \is_string($value) && $value !== ''; + })); + + if ($syntax === null) { + $syntax = CarbonInterface::DIFF_ABSOLUTE; + } + + if ($parts === -1) { + $parts = INF; + } + + if ($options === null) { + $options = static::getHumanDiffOptions(); + } + + if ($join === false) { + $join = ' '; + } elseif ($join === true) { + $join = [ + $default, + $this->getTranslationMessage('list.1') ?? $default, + ]; + } + + if ($altNumbers && $altNumbers !== true) { + $language = new Language($this->locale); + $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); + } + + if (\is_array($join)) { + [$default, $last] = $join; + + if ($default !== ' ') { + $optionalSpace = ''; + } + + $join = function ($list) use ($default, $last) { + if (\count($list) < 2) { + return implode('', $list); + } + + $end = array_pop($list); + + return implode($default, $list).$last.$end; + }; + } + + if (\is_string($join)) { + if ($join !== ' ') { + $optionalSpace = ''; + } + + $glue = $join; + $join = function ($list) use ($glue) { + return implode($glue, $list); + }; + } + + $interpolations = [ + ':optional-space' => $optionalSpace, + ]; + + return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip]; + } + + protected static function getRoundingMethodFromOptions(int $options): ?string + { + if ($options & CarbonInterface::ROUND) { + return 'round'; + } + + if ($options & CarbonInterface::CEIL) { + return 'ceil'; + } + + if ($options & CarbonInterface::FLOOR) { + return 'floor'; + } + + return null; + } + + /** + * Returns interval values as an array where key are the unit names and values the counts. + * + * @return int[] + */ + public function toArray() + { + return [ + 'years' => $this->years, + 'months' => $this->months, + 'weeks' => $this->weeks, + 'days' => $this->daysExcludeWeeks, + 'hours' => $this->hours, + 'minutes' => $this->minutes, + 'seconds' => $this->seconds, + 'microseconds' => $this->microseconds, + ]; + } + + /** + * Returns interval non-zero values as an array where key are the unit names and values the counts. + * + * @return int[] + */ + public function getNonZeroValues() + { + return array_filter($this->toArray(), 'intval'); + } + + /** + * Returns interval values as an array where key are the unit names and values the counts + * from the biggest non-zero one the the smallest non-zero one. + * + * @return int[] + */ + public function getValuesSequence() + { + $nonZeroValues = $this->getNonZeroValues(); + + if ($nonZeroValues === []) { + return []; + } + + $keys = array_keys($nonZeroValues); + $firstKey = $keys[0]; + $lastKey = $keys[\count($keys) - 1]; + $values = []; + $record = false; + + foreach ($this->toArray() as $unit => $count) { + if ($unit === $firstKey) { + $record = true; + } + + if ($record) { + $values[$unit] = $count; + } + + if ($unit === $lastKey) { + $record = false; + } + } + + return $values; + } + + /** + * Get the current interval in a human readable format in the current locale. + * + * @example + * ``` + * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; + * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; + * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; + * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; + * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; + * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; + * ``` + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'skip' entry, list of units to skip (array of strings or a single string, + * ` it can be the unit name (singular or plural) or its shortcut + * ` (y, m, w, d, h, min, s, ms, µs). + * - 'aUnit' entry, prefer "an hour" over "1 hour" if true + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'minimumUnit' entry determines the smallest unit of time to display can be long or + * ` short form of the units, e.g. 'hour' or 'h' (default value: s) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: -1: no limits) + * @param int $options human diff options + * + * @throws Exception + * + * @return string + */ + public function forHumans($syntax = null, $short = false, $parts = -1, $options = null) + { + [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip] = $this + ->getForHumansParameters($syntax, $short, $parts, $options); + + $interval = []; + + $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); + $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; + $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; + $count = 1; + $unit = $short ? 's' : 'second'; + $isFuture = $this->invert === 1; + $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); + $declensionMode = null; + + /** @var \Symfony\Component\Translation\Translator $translator */ + $translator = $this->getLocalTranslator(); + + $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { + if (!$absolute) { + $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); + + if ($this->needsDeclension($declensionMode, $index, $parts)) { + // Some languages have special pluralization for past and future tense. + $key = $unit.'_'.$transId; + $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); + + if ($result !== $key) { + return $result; + } + } + } + + $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); + + if ($result !== $unit) { + return $result; + } + + return null; + }; + + $intervalValues = $this; + $method = static::getRoundingMethodFromOptions($options); + + if ($method) { + $previousCount = INF; + + while ( + \count($intervalValues->getNonZeroValues()) > $parts && + ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 + ) { + $index = min($count, $previousCount - 1) - 2; + + if ($index < 0) { + break; + } + + $intervalValues = $this->copy()->roundUnit( + $keys[$index], + 1, + $method + ); + $previousCount = $count; + } + } + + $diffIntervalArray = [ + ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], + ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], + ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], + ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], + ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], + ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], + ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], + ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], + ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], + ]; + + if (!empty($skip)) { + foreach ($diffIntervalArray as $index => &$unitData) { + $nextIndex = $index + 1; + + if ($unitData['value'] && + isset($diffIntervalArray[$nextIndex]) && + \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) + ) { + $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * + self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); + $unitData['value'] = 0; + } + } + } + + $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { + $count = $unitData['value']; + + if ($short) { + $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); + + if ($result !== null) { + return $result; + } + } elseif ($aUnit) { + $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); + + if ($result !== null) { + return $result; + } + } + + if (!$absolute) { + return $handleDeclensions($unitData['unit'], $count, $index, $parts); + } + + return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); + }; + + $fallbackUnit = ['second', 's']; + + foreach ($diffIntervalArray as $diffIntervalData) { + if ($diffIntervalData['value'] > 0) { + $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; + $count = $diffIntervalData['value']; + $interval[] = [$short, $diffIntervalData]; + } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { + break; + } + + // break the loop after we get the required number of parts in array + if (\count($interval) >= $parts) { + break; + } + + // break the loop after we have reached the minimum unit + if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { + $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; + + break; + } + } + + $actualParts = \count($interval); + + foreach ($interval as $index => &$item) { + $item = $transChoice($item[0], $item[1], $index, $actualParts); + } + + if (\count($interval) === 0) { + if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { + $key = 'diff_now'; + $translation = $this->translate($key, $interpolations, null, $translator); + + if ($translation !== $key) { + return $translation; + } + } + + $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; + $unit = $fallbackUnit[$short ? 1 : 0]; + $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); + } + + // join the interval parts by a space + $time = $join($interval); + + unset($diffIntervalArray, $interval); + + if ($absolute) { + return $time; + } + + $isFuture = $this->invert === 1; + + $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); + + if ($parts === 1) { + if ($relativeToNow && $unit === 'day') { + if ($count === 1 && $options & CarbonInterface::ONE_DAY_WORDS) { + $key = $isFuture ? 'diff_tomorrow' : 'diff_yesterday'; + $translation = $this->translate($key, $interpolations, null, $translator); + + if ($translation !== $key) { + return $translation; + } + } + + if ($count === 2 && $options & CarbonInterface::TWO_DAY_WORDS) { + $key = $isFuture ? 'diff_after_tomorrow' : 'diff_before_yesterday'; + $translation = $this->translate($key, $interpolations, null, $translator); + + if ($translation !== $key) { + return $translation; + } + } + } + + $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; + + $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; + } + + $time = [':time' => $time]; + + return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); + } + + /** + * Format the instance as a string using the forHumans() function. + * + * @throws Exception + * + * @return string + */ + public function __toString() + { + $format = $this->localToStringFormat ?? static::$toStringFormat; + + if (!$format) { + return $this->forHumans(); + } + + if ($format instanceof Closure) { + return $format($this); + } + + return $this->format($format); + } + + /** + * Return native DateInterval PHP object matching the current instance. + * + * @example + * ``` + * var_dump(CarbonInterval::hours(2)->toDateInterval()); + * ``` + * + * @return DateInterval + */ + public function toDateInterval() + { + return self::castIntervalToClass($this, DateInterval::class); + } + + /** + * Convert the interval to a CarbonPeriod. + * + * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. + * + * @return CarbonPeriod + */ + public function toPeriod(...$params) + { + if ($this->tzName) { + $tz = \is_string($this->tzName) ? new DateTimeZone($this->tzName) : $this->tzName; + + if ($tz instanceof DateTimeZone) { + array_unshift($params, $tz); + } + } + + return CarbonPeriod::create($this, ...$params); + } + + /** + * Invert the interval. + * + * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used + * as the new value of the ->invert property. + * + * @return $this + */ + public function invert($inverted = null) + { + $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; + + return $this; + } + + protected function solveNegativeInterval() + { + if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { + $this->years *= -1; + $this->months *= -1; + $this->dayz *= -1; + $this->hours *= -1; + $this->minutes *= -1; + $this->seconds *= -1; + $this->microseconds *= -1; + $this->invert(); + } + + return $this; + } + + /** + * Add the passed interval to the current instance. + * + * @param string|DateInterval $unit + * @param int|float $value + * + * @return $this + */ + public function add($unit, $value = 1) + { + if (is_numeric($unit)) { + [$value, $unit] = [$unit, $value]; + } + + if (\is_string($unit) && !preg_match('/^\s*\d/', $unit)) { + $unit = "$value $unit"; + $value = 1; + } + + $interval = static::make($unit); + + if (!$interval) { + throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); + } + + if ($value !== 1) { + $interval->times($value); + } + + $sign = ($this->invert === 1) !== ($interval->invert === 1) ? -1 : 1; + $this->years += $interval->y * $sign; + $this->months += $interval->m * $sign; + $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; + $this->hours += $interval->h * $sign; + $this->minutes += $interval->i * $sign; + $this->seconds += $interval->s * $sign; + $this->microseconds += $interval->microseconds * $sign; + + $this->solveNegativeInterval(); + + return $this; + } + + /** + * Subtract the passed interval to the current instance. + * + * @param string|DateInterval $unit + * @param int|float $value + * + * @return $this + */ + public function sub($unit, $value = 1) + { + if (is_numeric($unit)) { + [$value, $unit] = [$unit, $value]; + } + + return $this->add($unit, -(float) $value); + } + + /** + * Subtract the passed interval to the current instance. + * + * @param string|DateInterval $unit + * @param int|float $value + * + * @return $this + */ + public function subtract($unit, $value = 1) + { + return $this->sub($unit, $value); + } + + /** + * Add given parameters to the current interval. + * + * @param int $years + * @param int $months + * @param int|float $weeks + * @param int|float $days + * @param int|float $hours + * @param int|float $minutes + * @param int|float $seconds + * @param int|float $microseconds + * + * @return $this + */ + public function plus( + $years = 0, + $months = 0, + $weeks = 0, + $days = 0, + $hours = 0, + $minutes = 0, + $seconds = 0, + $microseconds = 0 + ): self { + return $this->add(" + $years years $months months $weeks weeks $days days + $hours hours $minutes minutes $seconds seconds $microseconds microseconds + "); + } + + /** + * Add given parameters to the current interval. + * + * @param int $years + * @param int $months + * @param int|float $weeks + * @param int|float $days + * @param int|float $hours + * @param int|float $minutes + * @param int|float $seconds + * @param int|float $microseconds + * + * @return $this + */ + public function minus( + $years = 0, + $months = 0, + $weeks = 0, + $days = 0, + $hours = 0, + $minutes = 0, + $seconds = 0, + $microseconds = 0 + ): self { + return $this->sub(" + $years years $months months $weeks weeks $days days + $hours hours $minutes minutes $seconds seconds $microseconds microseconds + "); + } + + /** + * Multiply current instance given number of times. times() is naive, it multiplies each unit + * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded + * separately for each unit. + * + * Use times() when you want a fast and approximated calculation that does not cascade units. + * + * For a precise and cascaded calculation, + * + * @see multiply() + * + * @param float|int $factor + * + * @return $this + */ + public function times($factor) + { + if ($factor < 0) { + $this->invert = $this->invert ? 0 : 1; + $factor = -$factor; + } + + $this->years = (int) round($this->years * $factor); + $this->months = (int) round($this->months * $factor); + $this->dayz = (int) round($this->dayz * $factor); + $this->hours = (int) round($this->hours * $factor); + $this->minutes = (int) round($this->minutes * $factor); + $this->seconds = (int) round($this->seconds * $factor); + $this->microseconds = (int) round($this->microseconds * $factor); + + return $this; + } + + /** + * Divide current instance by a given divider. shares() is naive, it divides each unit separately + * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours + * and 7 minutes. + * + * Use shares() when you want a fast and approximated calculation that does not cascade units. + * + * For a precise and cascaded calculation, + * + * @see divide() + * + * @param float|int $divider + * + * @return $this + */ + public function shares($divider) + { + return $this->times(1 / $divider); + } + + protected function copyProperties(self $interval, $ignoreSign = false) + { + $this->years = $interval->years; + $this->months = $interval->months; + $this->dayz = $interval->dayz; + $this->hours = $interval->hours; + $this->minutes = $interval->minutes; + $this->seconds = $interval->seconds; + $this->microseconds = $interval->microseconds; + + if (!$ignoreSign) { + $this->invert = $interval->invert; + } + + return $this; + } + + /** + * Multiply and cascade current instance by a given factor. + * + * @param float|int $factor + * + * @return $this + */ + public function multiply($factor) + { + if ($factor < 0) { + $this->invert = $this->invert ? 0 : 1; + $factor = -$factor; + } + + $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision + + if ($yearPart) { + $this->years -= $yearPart / $factor; + } + + return $this->copyProperties( + static::create($yearPart) + ->microseconds(abs($this->totalMicroseconds) * $factor) + ->cascade(), + true + ); + } + + /** + * Divide and cascade current instance by a given divider. + * + * @param float|int $divider + * + * @return $this + */ + public function divide($divider) + { + return $this->multiply(1 / $divider); + } + + /** + * Get the interval_spec string of a date interval. + * + * @param DateInterval $interval + * + * @return string + */ + public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []) + { + $date = array_filter([ + static::PERIOD_YEARS => abs($interval->y), + static::PERIOD_MONTHS => abs($interval->m), + static::PERIOD_DAYS => abs($interval->d), + ]); + + if ( + $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && + (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && + (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) + ) { + $date = [ + static::PERIOD_DAYS => abs($interval->days), + ]; + } + + $seconds = abs($interval->s); + if ($microseconds && $interval->f > 0) { + $seconds = sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); + } + + $time = array_filter([ + static::PERIOD_HOURS => abs($interval->h), + static::PERIOD_MINUTES => abs($interval->i), + static::PERIOD_SECONDS => $seconds, + ]); + + $specString = static::PERIOD_PREFIX; + + foreach ($date as $key => $value) { + $specString .= $value.$key; + } + + if (\count($time) > 0) { + $specString .= static::PERIOD_TIME_PREFIX; + foreach ($time as $key => $value) { + $specString .= $value.$key; + } + } + + return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; + } + + /** + * Get the interval_spec string. + * + * @return string + */ + public function spec(bool $microseconds = false) + { + return static::getDateIntervalSpec($this, $microseconds); + } + + /** + * Comparing 2 date intervals. + * + * @param DateInterval $first + * @param DateInterval $second + * + * @return int + */ + public static function compareDateIntervals(DateInterval $first, DateInterval $second) + { + $current = Carbon::now(); + $passed = $current->avoidMutation()->add($second); + $current->add($first); + + if ($current < $passed) { + return -1; + } + if ($current > $passed) { + return 1; + } + + return 0; + } + + /** + * Comparing with passed interval. + * + * @param DateInterval $interval + * + * @return int + */ + public function compare(DateInterval $interval) + { + return static::compareDateIntervals($this, $interval); + } + + private function invertCascade(array $values) + { + return $this->set(array_map(function ($value) { + return -$value; + }, $values))->doCascade(true)->invert(); + } + + private function doCascade(bool $deep) + { + $originalData = $this->toArray(); + $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); + $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); + $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); + $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); + unset($originalData['days']); + $newData = $originalData; + $previous = []; + + foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { + foreach (['source', 'target'] as $key) { + if ($$key === 'dayz') { + $$key = 'daysExcludeWeeks'; + } + } + + $value = $newData[$source]; + $modulo = fmod($factor + fmod($value, $factor), $factor); + $newData[$source] = $modulo; + $newData[$target] += ($value - $modulo) / $factor; + + $decimalPart = fmod($newData[$source], 1); + + if ($decimalPart !== 0.0) { + $unit = $source; + + foreach ($previous as [$subUnit, $subFactor]) { + $newData[$unit] -= $decimalPart; + $newData[$subUnit] += $decimalPart * $subFactor; + $decimalPart = fmod($newData[$subUnit], 1); + + if ($decimalPart === 0.0) { + break; + } + + $unit = $subUnit; + } + } + + array_unshift($previous, [$source, $factor]); + } + + $positive = null; + + if (!$deep) { + foreach ($newData as $value) { + if ($value) { + if ($positive === null) { + $positive = ($value > 0); + + continue; + } + + if (($value > 0) !== $positive) { + return $this->invertCascade($originalData) + ->solveNegativeInterval(); + } + } + } + } + + return $this->set($newData) + ->solveNegativeInterval(); + } + + /** + * Convert overflowed values into bigger units. + * + * @return $this + */ + public function cascade() + { + return $this->doCascade(false); + } + + public function hasNegativeValues(): bool + { + foreach ($this->toArray() as $value) { + if ($value < 0) { + return true; + } + } + + return false; + } + + public function hasPositiveValues(): bool + { + foreach ($this->toArray() as $value) { + if ($value > 0) { + return true; + } + } + + return false; + } + + /** + * Get amount of given unit equivalent to the interval. + * + * @param string $unit + * + * @throws UnknownUnitException|UnitNotConfiguredException + * + * @return float + */ + public function total($unit) + { + $realUnit = $unit = strtolower($unit); + + if (\in_array($unit, ['days', 'weeks'])) { + $realUnit = 'dayz'; + } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { + throw new UnknownUnitException($unit); + } + + $result = 0; + $cumulativeFactor = 0; + $unitFound = false; + $factors = self::getFlipCascadeFactors(); + $daysPerWeek = (int) static::getDaysPerWeek(); + + $values = [ + 'years' => $this->years, + 'months' => $this->months, + 'weeks' => (int) ($this->d / $daysPerWeek), + 'dayz' => fmod($this->d, $daysPerWeek), + 'hours' => $this->hours, + 'minutes' => $this->minutes, + 'seconds' => $this->seconds, + 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), + 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, + ]; + + if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { + $values['dayz'] += $values['weeks'] * $daysPerWeek; + $values['weeks'] = 0; + } + + foreach ($factors as $source => [$target, $factor]) { + if ($source === $realUnit) { + $unitFound = true; + $value = $values[$source]; + $result += $value; + $cumulativeFactor = 1; + } + + if ($factor === false) { + if ($unitFound) { + break; + } + + $result = 0; + $cumulativeFactor = 0; + + continue; + } + + if ($target === $realUnit) { + $unitFound = true; + } + + if ($cumulativeFactor) { + $cumulativeFactor *= $factor; + $result += $values[$target] * $cumulativeFactor; + + continue; + } + + $value = $values[$source]; + + $result = ($result + $value) / $factor; + } + + if (isset($target) && !$cumulativeFactor) { + $result += $values[$target]; + } + + if (!$unitFound) { + throw new UnitNotConfiguredException($unit); + } + + if ($this->invert) { + $result *= -1; + } + + if ($unit === 'weeks') { + $result /= $daysPerWeek; + } + + // Cast as int numbers with no decimal part + return fmod($result, 1) === 0.0 ? (int) $result : $result; + } + + /** + * Determines if the instance is equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @see equalTo() + * + * @return bool + */ + public function eq($interval): bool + { + return $this->equalTo($interval); + } + + /** + * Determines if the instance is equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @return bool + */ + public function equalTo($interval): bool + { + $interval = $this->resolveInterval($interval); + + return $interval !== null && $this->totalMicroseconds === $interval->totalMicroseconds; + } + + /** + * Determines if the instance is not equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @see notEqualTo() + * + * @return bool + */ + public function ne($interval): bool + { + return $this->notEqualTo($interval); + } + + /** + * Determines if the instance is not equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @return bool + */ + public function notEqualTo($interval): bool + { + return !$this->eq($interval); + } + + /** + * Determines if the instance is greater (longer) than another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @see greaterThan() + * + * @return bool + */ + public function gt($interval): bool + { + return $this->greaterThan($interval); + } + + /** + * Determines if the instance is greater (longer) than another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @return bool + */ + public function greaterThan($interval): bool + { + $interval = $this->resolveInterval($interval); + + return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; + } + + /** + * Determines if the instance is greater (longer) than or equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @see greaterThanOrEqualTo() + * + * @return bool + */ + public function gte($interval): bool + { + return $this->greaterThanOrEqualTo($interval); + } + + /** + * Determines if the instance is greater (longer) than or equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @return bool + */ + public function greaterThanOrEqualTo($interval): bool + { + return $this->greaterThan($interval) || $this->equalTo($interval); + } + + /** + * Determines if the instance is less (shorter) than another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @see lessThan() + * + * @return bool + */ + public function lt($interval): bool + { + return $this->lessThan($interval); + } + + /** + * Determines if the instance is less (shorter) than another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @return bool + */ + public function lessThan($interval): bool + { + $interval = $this->resolveInterval($interval); + + return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; + } + + /** + * Determines if the instance is less (shorter) than or equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @see lessThanOrEqualTo() + * + * @return bool + */ + public function lte($interval): bool + { + return $this->lessThanOrEqualTo($interval); + } + + /** + * Determines if the instance is less (shorter) than or equal to another + * + * @param CarbonInterval|DateInterval|mixed $interval + * + * @return bool + */ + public function lessThanOrEqualTo($interval): bool + { + return $this->lessThan($interval) || $this->equalTo($interval); + } + + /** + * Determines if the instance is between two others. + * + * The third argument allow you to specify if bounds are included or not (true by default) + * but for when you including/excluding bounds may produce different results in your application, + * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. + * + * @example + * ``` + * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true + * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false + * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true + * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false + * ``` + * + * @param CarbonInterval|DateInterval|mixed $interval1 + * @param CarbonInterval|DateInterval|mixed $interval2 + * @param bool $equal Indicates if an equal to comparison should be done + * + * @return bool + */ + public function between($interval1, $interval2, $equal = true): bool + { + return $equal + ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) + : $this->greaterThan($interval1) && $this->lessThan($interval2); + } + + /** + * Determines if the instance is between two others, bounds excluded. + * + * @example + * ``` + * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true + * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false + * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true + * ``` + * + * @param CarbonInterval|DateInterval|mixed $interval1 + * @param CarbonInterval|DateInterval|mixed $interval2 + * + * @return bool + */ + public function betweenIncluded($interval1, $interval2): bool + { + return $this->between($interval1, $interval2, true); + } + + /** + * Determines if the instance is between two others, bounds excluded. + * + * @example + * ``` + * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true + * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false + * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false + * ``` + * + * @param CarbonInterval|DateInterval|mixed $interval1 + * @param CarbonInterval|DateInterval|mixed $interval2 + * + * @return bool + */ + public function betweenExcluded($interval1, $interval2): bool + { + return $this->between($interval1, $interval2, false); + } + + /** + * Determines if the instance is between two others + * + * @example + * ``` + * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true + * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false + * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true + * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false + * ``` + * + * @param CarbonInterval|DateInterval|mixed $interval1 + * @param CarbonInterval|DateInterval|mixed $interval2 + * @param bool $equal Indicates if an equal to comparison should be done + * + * @return bool + */ + public function isBetween($interval1, $interval2, $equal = true): bool + { + return $this->between($interval1, $interval2, $equal); + } + + /** + * Round the current instance at the given unit with given precision if specified and the given function. + * + * @param string $unit + * @param float|int|string|DateInterval|null $precision + * @param string $function + * + * @throws Exception + * + * @return $this + */ + public function roundUnit($unit, $precision = 1, $function = 'round') + { + if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { + $value = $function($this->total($unit) / $precision) * $precision; + $inverted = $value < 0; + + return $this->copyProperties(self::fromString( + number_format(abs($value), 12, '.', '').' '.$unit + )->invert($inverted)->cascade()); + } + + $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') + ->roundUnit($unit, $precision, $function); + $next = $base->add($this); + $inverted = $next < $base; + + if ($inverted) { + $next = $base->sub($this); + } + + $this->copyProperties( + $next + ->roundUnit($unit, $precision, $function) + ->diffAsCarbonInterval($base) + ); + + return $this->invert($inverted); + } + + /** + * Truncate the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int|string|DateInterval|null $precision + * + * @throws Exception + * + * @return $this + */ + public function floorUnit($unit, $precision = 1) + { + return $this->roundUnit($unit, $precision, 'floor'); + } + + /** + * Ceil the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int|string|DateInterval|null $precision + * + * @throws Exception + * + * @return $this + */ + public function ceilUnit($unit, $precision = 1) + { + return $this->roundUnit($unit, $precision, 'ceil'); + } + + /** + * Round the current instance second with given precision if specified. + * + * @param float|int|string|DateInterval|null $precision + * @param string $function + * + * @throws Exception + * + * @return $this + */ + public function round($precision = 1, $function = 'round') + { + return $this->roundWith($precision, $function); + } + + /** + * Round the current instance second with given precision if specified. + * + * @param float|int|string|DateInterval|null $precision + * + * @throws Exception + * + * @return $this + */ + public function floor($precision = 1) + { + return $this->round($precision, 'floor'); + } + + /** + * Ceil the current instance second with given precision if specified. + * + * @param float|int|string|DateInterval|null $precision + * + * @throws Exception + * + * @return $this + */ + public function ceil($precision = 1) + { + return $this->round($precision, 'ceil'); + } + + private function needsDeclension(string $mode, int $index, int $parts): bool + { + switch ($mode) { + case 'last': + return $index === $parts - 1; + default: + return true; + } + } + + private function checkIntegerValue(string $name, $value) + { + if (\is_int($value)) { + return; + } + + $this->assertSafeForInteger($name, $value); + + if (\is_float($value) && (((float) (int) $value) === $value)) { + return; + } + + if (!self::$floatSettersEnabled) { + $type = \gettype($value); + @trigger_error( + "Since 2.70.0, it's deprecated to pass $type value for $name.\n". + "It's truncated when stored as an integer interval unit.\n". + "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". + "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". + "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", + \E_USER_DEPRECATED + ); + } + } + + /** + * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. + */ + private function assertSafeForInteger(string $name, $value) + { + if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { + throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); + } + } + + private function handleDecimalPart(string $unit, $value, $integerValue) + { + if (self::$floatSettersEnabled) { + $floatValue = (float) $value; + $base = (float) $integerValue; + + if ($floatValue === $base) { + return; + } + + $units = [ + 'y' => 'year', + 'm' => 'month', + 'd' => 'day', + 'h' => 'hour', + 'i' => 'minute', + 's' => 'second', + ]; + $upper = true; + + foreach ($units as $property => $name) { + if ($name === $unit) { + $upper = false; + + continue; + } + + if (!$upper && $this->$property !== 0) { + throw new RuntimeException( + "You cannot set $unit to a float value as $name would be overridden, ". + 'set it first to 0 explicitly if you really want to erase its value' + ); + } + } + + $this->add($unit, $floatValue - $base); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php new file mode 100644 index 0000000..d12a986 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php @@ -0,0 +1,2742 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\Exceptions\EndLessPeriodException; +use Carbon\Exceptions\InvalidCastException; +use Carbon\Exceptions\InvalidIntervalException; +use Carbon\Exceptions\InvalidPeriodDateException; +use Carbon\Exceptions\InvalidPeriodParameterException; +use Carbon\Exceptions\NotACarbonClassException; +use Carbon\Exceptions\NotAPeriodException; +use Carbon\Exceptions\UnknownGetterException; +use Carbon\Exceptions\UnknownMethodException; +use Carbon\Exceptions\UnreachableException; +use Carbon\Traits\IntervalRounding; +use Carbon\Traits\Mixin; +use Carbon\Traits\Options; +use Carbon\Traits\ToStringFormat; +use Closure; +use Countable; +use DateInterval; +use DatePeriod; +use DateTime; +use DateTimeImmutable; +use DateTimeInterface; +use DateTimeZone; +use InvalidArgumentException; +use Iterator; +use JsonSerializable; +use ReflectionException; +use ReturnTypeWillChange; +use RuntimeException; + +/** + * Substitution of DatePeriod with some modifications and many more features. + * + * @property-read int|float $recurrences number of recurrences (if end not set). + * @property-read bool $include_start_date rather the start date is included in the iteration. + * @property-read bool $include_end_date rather the end date is included in the iteration (if recurrences not set). + * @property-read CarbonInterface $start Period start date. + * @property-read CarbonInterface $current Current date from the iteration. + * @property-read CarbonInterface $end Period end date. + * @property-read CarbonInterval $interval Underlying date interval instance. Always present, one day by default. + * + * @method static static start($date, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. + * @method static static since($date, $inclusive = null) Alias for start(). + * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. + * @method static static end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. + * @method static static until($date = null, $inclusive = null) Alias for end(). + * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. + * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. + * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. + * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. + * @method static static times($recurrences = null) Alias for recurrences(). + * @method static static options($options = null) Create instance with options or modify the options if called on an instance. + * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. + * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. + * @method static static push($callback, $name = null) Alias for filter(). + * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. + * @method static static filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. + * @method static static interval($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. + * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. + * @method static static year($years = 1) Alias for years(). + * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. + * @method static static month($months = 1) Alias for months(). + * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. + * @method static static week($weeks = 1) Alias for weeks(). + * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. + * @method static static dayz($days = 1) Alias for days(). + * @method static static day($days = 1) Alias for days(). + * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. + * @method static static hour($hours = 1) Alias for hours(). + * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. + * @method static static minute($minutes = 1) Alias for minutes(). + * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. + * @method static static second($seconds = 1) Alias for seconds(). + * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. + * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). + * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. + * @method static static microsecond($microseconds = 1) Alias for microseconds(). + * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. + * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. + * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. + * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. + * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class CarbonPeriod implements Iterator, Countable, JsonSerializable +{ + use IntervalRounding; + use Mixin { + Mixin::mixin as baseMixin; + } + use Options; + use ToStringFormat; + + /** + * Built-in filter for limit by recurrences. + * + * @var callable + */ + public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; + + /** + * Built-in filter for limit to an end. + * + * @var callable + */ + public const END_DATE_FILTER = [self::class, 'filterEndDate']; + + /** + * Special value which can be returned by filters to end iteration. Also a filter. + * + * @var callable + */ + public const END_ITERATION = [self::class, 'endIteration']; + + /** + * Exclude start date from iteration. + * + * @var int + */ + public const EXCLUDE_START_DATE = 1; + + /** + * Exclude end date from iteration. + * + * @var int + */ + public const EXCLUDE_END_DATE = 2; + + /** + * Yield CarbonImmutable instances. + * + * @var int + */ + public const IMMUTABLE = 4; + + /** + * Number of maximum attempts before giving up on finding next valid date. + * + * @var int + */ + public const NEXT_MAX_ATTEMPTS = 1000; + + /** + * Number of maximum attempts before giving up on finding end date. + * + * @var int + */ + public const END_MAX_ATTEMPTS = 10000; + + /** + * Default date class of iteration items. + * + * @var string + */ + protected const DEFAULT_DATE_CLASS = Carbon::class; + + /** + * The registered macros. + * + * @var array + */ + protected static $macros = []; + + /** + * Date class of iteration items. + * + * @var string + */ + protected $dateClass = Carbon::class; + + /** + * Underlying date interval instance. Always present, one day by default. + * + * @var CarbonInterval + */ + protected $dateInterval; + + /** + * True once __construct is finished. + * + * @var bool + */ + protected $constructed = false; + + /** + * Whether current date interval was set by default. + * + * @var bool + */ + protected $isDefaultInterval; + + /** + * The filters stack. + * + * @var array + */ + protected $filters = []; + + /** + * Period start date. Applied on rewind. Always present, now by default. + * + * @var CarbonInterface + */ + protected $startDate; + + /** + * Period end date. For inverted interval should be before the start date. Applied via a filter. + * + * @var CarbonInterface|null + */ + protected $endDate; + + /** + * Limit for number of recurrences. Applied via a filter. + * + * @var int|null + */ + protected $recurrences; + + /** + * Iteration options. + * + * @var int + */ + protected $options; + + /** + * Index of current date. Always sequential, even if some dates are skipped by filters. + * Equal to null only before the first iteration. + * + * @var int + */ + protected $key; + + /** + * Current date. May temporarily hold unaccepted value when looking for a next valid date. + * Equal to null only before the first iteration. + * + * @var CarbonInterface + */ + protected $current; + + /** + * Timezone of current date. Taken from the start date. + * + * @var \DateTimeZone|null + */ + protected $timezone; + + /** + * The cached validation result for current date. + * + * @var bool|string|null + */ + protected $validationResult; + + /** + * Timezone handler for settings() method. + * + * @var mixed + */ + protected $tzName; + + /** + * Make a CarbonPeriod instance from given variable if possible. + * + * @param mixed $var + * + * @return static|null + */ + public static function make($var) + { + try { + return static::instance($var); + } catch (NotAPeriodException $e) { + return static::create($var); + } + } + + /** + * Create a new instance from a DatePeriod or CarbonPeriod object. + * + * @param CarbonPeriod|DatePeriod $period + * + * @return static + */ + public static function instance($period) + { + if ($period instanceof static) { + return $period->copy(); + } + + if ($period instanceof self) { + return new static( + $period->getStartDate(), + $period->getEndDate() ?: $period->getRecurrences(), + $period->getDateInterval(), + $period->getOptions() + ); + } + + if ($period instanceof DatePeriod) { + return new static( + $period->start, + $period->end ?: ($period->recurrences - 1), + $period->interval, + $period->include_start_date ? 0 : static::EXCLUDE_START_DATE + ); + } + + $class = static::class; + $type = \gettype($period); + + throw new NotAPeriodException( + 'Argument 1 passed to '.$class.'::'.__METHOD__.'() '. + 'must be an instance of DatePeriod or '.$class.', '. + ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.' + ); + } + + /** + * Create a new instance. + * + * @return static + */ + public static function create(...$params) + { + return static::createFromArray($params); + } + + /** + * Create a new instance from an array of parameters. + * + * @param array $params + * + * @return static + */ + public static function createFromArray(array $params) + { + return new static(...$params); + } + + /** + * Create CarbonPeriod from ISO 8601 string. + * + * @param string $iso + * @param int|null $options + * + * @return static + */ + public static function createFromIso($iso, $options = null) + { + $params = static::parseIso8601($iso); + + $instance = static::createFromArray($params); + + if ($options !== null) { + $instance->setOptions($options); + } + + return $instance; + } + + /** + * Return whether given interval contains non zero value of any time unit. + * + * @param \DateInterval $interval + * + * @return bool + */ + protected static function intervalHasTime(DateInterval $interval) + { + return $interval->h || $interval->i || $interval->s || $interval->f; + } + + /** + * Return whether given variable is an ISO 8601 specification. + * + * Note: Check is very basic, as actual validation will be done later when parsing. + * We just want to ensure that variable is not any other type of a valid parameter. + * + * @param mixed $var + * + * @return bool + */ + protected static function isIso8601($var) + { + if (!\is_string($var)) { + return false; + } + + // Match slash but not within a timezone name. + $part = '[a-z]+(?:[_-][a-z]+)*'; + + preg_match("#\b$part/$part\b|(/)#i", $var, $match); + + return isset($match[1]); + } + + /** + * Parse given ISO 8601 string into an array of arguments. + * + * @SuppressWarnings(PHPMD.ElseExpression) + * + * @param string $iso + * + * @return array + */ + protected static function parseIso8601($iso) + { + $result = []; + + $interval = null; + $start = null; + $end = null; + $dateClass = static::DEFAULT_DATE_CLASS; + + foreach (explode('/', $iso) as $key => $part) { + if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { + $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; + } elseif ($interval === null && $parsed = CarbonInterval::make($part)) { + $interval = $part; + } elseif ($start === null && $parsed = $dateClass::make($part)) { + $start = $part; + } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { + $end = $part; + } else { + throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); + } + + $result[] = $parsed; + } + + return $result; + } + + /** + * Add missing parts of the target date from the source date. + * + * @param string $source + * @param string $target + * + * @return string + */ + protected static function addMissingParts($source, $target) + { + $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; + + $result = preg_replace($pattern, $target, $source, 1, $count); + + return $count ? $result : $target; + } + + /** + * Register a custom macro. + * + * @example + * ``` + * CarbonPeriod::macro('middle', function () { + * return $this->getStartDate()->average($this->getEndDate()); + * }); + * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); + * ``` + * + * @param string $name + * @param object|callable $macro + * + * @return void + */ + public static function macro($name, $macro) + { + static::$macros[$name] = $macro; + } + + /** + * Register macros from a mixin object. + * + * @example + * ``` + * CarbonPeriod::mixin(new class { + * public function addDays() { + * return function ($count = 1) { + * return $this->setStartDate( + * $this->getStartDate()->addDays($count) + * )->setEndDate( + * $this->getEndDate()->addDays($count) + * ); + * }; + * } + * public function subDays() { + * return function ($count = 1) { + * return $this->setStartDate( + * $this->getStartDate()->subDays($count) + * )->setEndDate( + * $this->getEndDate()->subDays($count) + * ); + * }; + * } + * }); + * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); + * ``` + * + * @param object|string $mixin + * + * @throws ReflectionException + * + * @return void + */ + public static function mixin($mixin) + { + static::baseMixin($mixin); + } + + /** + * Check if macro is registered. + * + * @param string $name + * + * @return bool + */ + public static function hasMacro($name) + { + return isset(static::$macros[$name]); + } + + /** + * Provide static proxy for instance aliases. + * + * @param string $method + * @param array $parameters + * + * @return mixed + */ + public static function __callStatic($method, $parameters) + { + $date = new static(); + + if (static::hasMacro($method)) { + return static::bindMacroContext(null, function () use (&$method, &$parameters, &$date) { + return $date->callMacro($method, $parameters); + }); + } + + return $date->$method(...$parameters); + } + + /** + * CarbonPeriod constructor. + * + * @SuppressWarnings(PHPMD.ElseExpression) + * + * @throws InvalidArgumentException + */ + public function __construct(...$arguments) + { + if (is_a($this->dateClass, DateTimeImmutable::class, true)) { + $this->options = static::IMMUTABLE; + } + + // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, + // which will be first parsed into parts and then processed the same way. + + $argumentsCount = \count($arguments); + + if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { + array_splice($arguments, 0, 1, static::parseIso8601($iso)); + } + + if ($argumentsCount === 1) { + if ($arguments[0] instanceof DatePeriod) { + $arguments = [ + $arguments[0]->start, + $arguments[0]->end ?: ($arguments[0]->recurrences - 1), + $arguments[0]->interval, + $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, + ]; + } elseif ($arguments[0] instanceof self) { + $arguments = [ + $arguments[0]->getStartDate(), + $arguments[0]->getEndDate() ?: $arguments[0]->getRecurrences(), + $arguments[0]->getDateInterval(), + $arguments[0]->getOptions(), + ]; + } + } + + $optionsSet = false; + + foreach ($arguments as $argument) { + $parsedDate = null; + + if ($argument instanceof DateTimeZone) { + $this->setTimezone($argument); + } elseif ($this->dateInterval === null && + ( + (\is_string($argument) && preg_match( + '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', + $argument + )) || + $argument instanceof DateInterval || + $argument instanceof Closure + ) && + $parsedInterval = @CarbonInterval::make($argument) + ) { + $this->setDateInterval($parsedInterval); + } elseif ($this->startDate === null && $parsedDate = $this->makeDateTime($argument)) { + $this->setStartDate($parsedDate); + } elseif ($this->endDate === null && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { + $this->setEndDate($parsedDate); + } elseif ($this->recurrences === null && $this->endDate === null && is_numeric($argument)) { + $this->setRecurrences($argument); + } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { + $optionsSet = true; + $this->setOptions(((int) $this->options) | ((int) $argument)); + } else { + throw new InvalidPeriodParameterException('Invalid constructor parameters.'); + } + } + + if ($this->startDate === null) { + $dateClass = $this->dateClass; + $this->setStartDate($dateClass::now()); + } + + if ($this->dateInterval === null) { + $this->setDateInterval(CarbonInterval::day()); + + $this->isDefaultInterval = true; + } + + if ($this->options === null) { + $this->setOptions(0); + } + + $this->constructed = true; + } + + /** + * Get a copy of the instance. + * + * @return static + */ + public function copy() + { + return clone $this; + } + + /** + * Prepare the instance to be set (self if mutable to be mutated, + * copy if immutable to generate a new instance). + * + * @return static + */ + protected function copyIfImmutable() + { + return $this; + } + + /** + * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. + * + * @param string $name + * + * @return callable|null + */ + protected function getGetter(string $name) + { + switch (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { + case 'start': + case 'start_date': + return [$this, 'getStartDate']; + case 'end': + case 'end_date': + return [$this, 'getEndDate']; + case 'interval': + case 'date_interval': + return [$this, 'getDateInterval']; + case 'recurrences': + return [$this, 'getRecurrences']; + case 'include_start_date': + return [$this, 'isStartIncluded']; + case 'include_end_date': + return [$this, 'isEndIncluded']; + case 'current': + return [$this, 'current']; + default: + return null; + } + } + + /** + * Get a property allowing both `DatePeriod` snakeCase and camelCase names. + * + * @param string $name + * + * @return bool|CarbonInterface|CarbonInterval|int|null + */ + public function get(string $name) + { + $getter = $this->getGetter($name); + + if ($getter) { + return $getter(); + } + + throw new UnknownGetterException($name); + } + + /** + * Get a property allowing both `DatePeriod` snakeCase and camelCase names. + * + * @param string $name + * + * @return bool|CarbonInterface|CarbonInterval|int|null + */ + public function __get(string $name) + { + return $this->get($name); + } + + /** + * Check if an attribute exists on the object + * + * @param string $name + * + * @return bool + */ + public function __isset(string $name): bool + { + return $this->getGetter($name) !== null; + } + + /** + * @alias copy + * + * Get a copy of the instance. + * + * @return static + */ + public function clone() + { + return clone $this; + } + + /** + * Set the iteration item class. + * + * @param string $dateClass + * + * @return static + */ + public function setDateClass(string $dateClass) + { + if (!is_a($dateClass, CarbonInterface::class, true)) { + throw new NotACarbonClassException($dateClass); + } + + $self = $this->copyIfImmutable(); + $self->dateClass = $dateClass; + + if (is_a($dateClass, Carbon::class, true)) { + $self->options = $self->options & ~static::IMMUTABLE; + } elseif (is_a($dateClass, CarbonImmutable::class, true)) { + $self->options = $self->options | static::IMMUTABLE; + } + + return $self; + } + + /** + * Returns iteration item date class. + * + * @return string + */ + public function getDateClass(): string + { + return $this->dateClass; + } + + /** + * Change the period date interval. + * + * @param DateInterval|string $interval + * + * @throws InvalidIntervalException + * + * @return static + */ + public function setDateInterval($interval) + { + if (!$interval = CarbonInterval::make($interval)) { + throw new InvalidIntervalException('Invalid interval.'); + } + + if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { + throw new InvalidIntervalException('Empty interval is not accepted.'); + } + + $self = $this->copyIfImmutable(); + $self->dateInterval = $interval; + + $self->isDefaultInterval = false; + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Invert the period date interval. + * + * @return static + */ + public function invertDateInterval() + { + return $this->setDateInterval($this->dateInterval->invert()); + } + + /** + * Set start and end date. + * + * @param DateTime|DateTimeInterface|string $start + * @param DateTime|DateTimeInterface|string|null $end + * + * @return static + */ + public function setDates($start, $end) + { + return $this->setStartDate($start)->setEndDate($end); + } + + /** + * Change the period options. + * + * @param int|null $options + * + * @throws InvalidArgumentException + * + * @return static + */ + public function setOptions($options) + { + if (!\is_int($options) && $options !== null) { + throw new InvalidPeriodParameterException('Invalid options.'); + } + + $self = $this->copyIfImmutable(); + $self->options = $options ?: 0; + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Get the period options. + * + * @return int + */ + public function getOptions() + { + return $this->options; + } + + /** + * Toggle given options on or off. + * + * @param int $options + * @param bool|null $state + * + * @throws \InvalidArgumentException + * + * @return static + */ + public function toggleOptions($options, $state = null) + { + if ($state === null) { + $state = ($this->options & $options) !== $options; + } + + return $this->setOptions( + $state ? + $this->options | $options : + $this->options & ~$options + ); + } + + /** + * Toggle EXCLUDE_START_DATE option. + * + * @param bool $state + * + * @return static + */ + public function excludeStartDate($state = true) + { + return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); + } + + /** + * Toggle EXCLUDE_END_DATE option. + * + * @param bool $state + * + * @return static + */ + public function excludeEndDate($state = true) + { + return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); + } + + /** + * Get the underlying date interval. + * + * @return CarbonInterval + */ + public function getDateInterval() + { + return $this->dateInterval->copy(); + } + + /** + * Get start date of the period. + * + * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. + * + * @return CarbonInterface + */ + public function getStartDate(string $rounding = null) + { + $date = $this->startDate->avoidMutation(); + + return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; + } + + /** + * Get end date of the period. + * + * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. + * + * @return CarbonInterface|null + */ + public function getEndDate(string $rounding = null) + { + if (!$this->endDate) { + return null; + } + + $date = $this->endDate->avoidMutation(); + + return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; + } + + /** + * Get number of recurrences. + * + * @return int|float|null + */ + public function getRecurrences() + { + return $this->recurrences; + } + + /** + * Returns true if the start date should be excluded. + * + * @return bool + */ + public function isStartExcluded() + { + return ($this->options & static::EXCLUDE_START_DATE) !== 0; + } + + /** + * Returns true if the end date should be excluded. + * + * @return bool + */ + public function isEndExcluded() + { + return ($this->options & static::EXCLUDE_END_DATE) !== 0; + } + + /** + * Returns true if the start date should be included. + * + * @return bool + */ + public function isStartIncluded() + { + return !$this->isStartExcluded(); + } + + /** + * Returns true if the end date should be included. + * + * @return bool + */ + public function isEndIncluded() + { + return !$this->isEndExcluded(); + } + + /** + * Return the start if it's included by option, else return the start + 1 period interval. + * + * @return CarbonInterface + */ + public function getIncludedStartDate() + { + $start = $this->getStartDate(); + + if ($this->isStartExcluded()) { + return $start->add($this->getDateInterval()); + } + + return $start; + } + + /** + * Return the end if it's included by option, else return the end - 1 period interval. + * Warning: if the period has no fixed end, this method will iterate the period to calculate it. + * + * @return CarbonInterface + */ + public function getIncludedEndDate() + { + $end = $this->getEndDate(); + + if (!$end) { + return $this->calculateEnd(); + } + + if ($this->isEndExcluded()) { + return $end->sub($this->getDateInterval()); + } + + return $end; + } + + /** + * Add a filter to the stack. + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * + * @param callable $callback + * @param string $name + * + * @return static + */ + public function addFilter($callback, $name = null) + { + $self = $this->copyIfImmutable(); + $tuple = $self->createFilterTuple(\func_get_args()); + + $self->filters[] = $tuple; + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Prepend a filter to the stack. + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * + * @param callable $callback + * @param string $name + * + * @return static + */ + public function prependFilter($callback, $name = null) + { + $self = $this->copyIfImmutable(); + $tuple = $self->createFilterTuple(\func_get_args()); + + array_unshift($self->filters, $tuple); + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Remove a filter by instance or name. + * + * @param callable|string $filter + * + * @return static + */ + public function removeFilter($filter) + { + $self = $this->copyIfImmutable(); + $key = \is_callable($filter) ? 0 : 1; + + $self->filters = array_values(array_filter( + $this->filters, + function ($tuple) use ($key, $filter) { + return $tuple[$key] !== $filter; + } + )); + + $self->updateInternalState(); + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Return whether given instance or name is in the filter stack. + * + * @param callable|string $filter + * + * @return bool + */ + public function hasFilter($filter) + { + $key = \is_callable($filter) ? 0 : 1; + + foreach ($this->filters as $tuple) { + if ($tuple[$key] === $filter) { + return true; + } + } + + return false; + } + + /** + * Get filters stack. + * + * @return array + */ + public function getFilters() + { + return $this->filters; + } + + /** + * Set filters stack. + * + * @param array $filters + * + * @return static + */ + public function setFilters(array $filters) + { + $self = $this->copyIfImmutable(); + $self->filters = $filters; + + $self->updateInternalState(); + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Reset filters stack. + * + * @return static + */ + public function resetFilters() + { + $self = $this->copyIfImmutable(); + $self->filters = []; + + if ($self->endDate !== null) { + $self->filters[] = [static::END_DATE_FILTER, null]; + } + + if ($self->recurrences !== null) { + $self->filters[] = [static::RECURRENCES_FILTER, null]; + } + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Add a recurrences filter (set maximum number of recurrences). + * + * @param int|float|null $recurrences + * + * @throws InvalidArgumentException + * + * @return static + */ + public function setRecurrences($recurrences) + { + if ((!is_numeric($recurrences) && $recurrences !== null) || $recurrences < 0) { + throw new InvalidPeriodParameterException('Invalid number of recurrences.'); + } + + if ($recurrences === null) { + return $this->removeFilter(static::RECURRENCES_FILTER); + } + + /** @var self $self */ + $self = $this->copyIfImmutable(); + $self->recurrences = $recurrences === INF ? INF : (int) $recurrences; + + if (!$self->hasFilter(static::RECURRENCES_FILTER)) { + return $self->addFilter(static::RECURRENCES_FILTER); + } + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Change the period start date. + * + * @param DateTime|DateTimeInterface|string $date + * @param bool|null $inclusive + * + * @throws InvalidPeriodDateException + * + * @return static + */ + public function setStartDate($date, $inclusive = null) + { + if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date))) { + throw new InvalidPeriodDateException('Invalid start date.'); + } + + $self = $this->copyIfImmutable(); + $self->startDate = $date; + + if ($inclusive !== null) { + $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); + } + + return $self; + } + + /** + * Change the period end date. + * + * @param DateTime|DateTimeInterface|string|null $date + * @param bool|null $inclusive + * + * @throws \InvalidArgumentException + * + * @return static + */ + public function setEndDate($date, $inclusive = null) + { + if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date)) { + throw new InvalidPeriodDateException('Invalid end date.'); + } + + if (!$date) { + return $this->removeFilter(static::END_DATE_FILTER); + } + + $self = $this->copyIfImmutable(); + $self->endDate = $date; + + if ($inclusive !== null) { + $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); + } + + if (!$self->hasFilter(static::END_DATE_FILTER)) { + return $self->addFilter(static::END_DATE_FILTER); + } + + $self->handleChangedParameters(); + + return $self; + } + + /** + * Check if the current position is valid. + * + * @return bool + */ + #[ReturnTypeWillChange] + public function valid() + { + return $this->validateCurrentDate() === true; + } + + /** + * Return the current key. + * + * @return int|null + */ + #[ReturnTypeWillChange] + public function key() + { + return $this->valid() + ? $this->key + : null; + } + + /** + * Return the current date. + * + * @return CarbonInterface|null + */ + #[ReturnTypeWillChange] + public function current() + { + return $this->valid() + ? $this->prepareForReturn($this->current) + : null; + } + + /** + * Move forward to the next date. + * + * @throws RuntimeException + * + * @return void + */ + #[ReturnTypeWillChange] + public function next() + { + if ($this->current === null) { + $this->rewind(); + } + + if ($this->validationResult !== static::END_ITERATION) { + $this->key++; + + $this->incrementCurrentDateUntilValid(); + } + } + + /** + * Rewind to the start date. + * + * Iterating over a date in the UTC timezone avoids bug during backward DST change. + * + * @see https://bugs.php.net/bug.php?id=72255 + * @see https://bugs.php.net/bug.php?id=74274 + * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time + * + * @throws RuntimeException + * + * @return void + */ + #[ReturnTypeWillChange] + public function rewind() + { + $this->key = 0; + $this->current = ([$this->dateClass, 'make'])($this->startDate); + $settings = $this->getSettings(); + + if ($this->hasLocalTranslator()) { + $settings['locale'] = $this->getTranslatorLocale(); + } + + $this->current->settings($settings); + $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->current->getTimezone() : null; + + if ($this->timezone) { + $this->current = $this->current->utc(); + } + + $this->validationResult = null; + + if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { + $this->incrementCurrentDateUntilValid(); + } + } + + /** + * Skip iterations and returns iteration state (false if ended, true if still valid). + * + * @param int $count steps number to skip (1 by default) + * + * @return bool + */ + public function skip($count = 1) + { + for ($i = $count; $this->valid() && $i > 0; $i--) { + $this->next(); + } + + return $this->valid(); + } + + /** + * Format the date period as ISO 8601. + * + * @return string + */ + public function toIso8601String() + { + $parts = []; + + if ($this->recurrences !== null) { + $parts[] = 'R'.$this->recurrences; + } + + $parts[] = $this->startDate->toIso8601String(); + + $parts[] = $this->dateInterval->spec(); + + if ($this->endDate !== null) { + $parts[] = $this->endDate->toIso8601String(); + } + + return implode('/', $parts); + } + + /** + * Convert the date period into a string. + * + * @return string + */ + public function toString() + { + $format = $this->localToStringFormat ?? static::$toStringFormat; + + if ($format instanceof Closure) { + return $format($this); + } + + $translator = ([$this->dateClass, 'getTranslator'])(); + + $parts = []; + + $format = $format ?? ( + !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) + ? 'Y-m-d H:i:s' + : 'Y-m-d' + ); + + if ($this->recurrences !== null) { + $parts[] = $this->translate('period_recurrences', [], $this->recurrences, $translator); + } + + $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ + 'join' => true, + ])], null, $translator); + + $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); + + if ($this->endDate !== null) { + $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); + } + + $result = implode(' ', $parts); + + return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); + } + + /** + * Format the date period as ISO 8601. + * + * @return string + */ + public function spec() + { + return $this->toIso8601String(); + } + + /** + * Cast the current instance into the given class. + * + * @param string $className The $className::instance() method will be called to cast the current object. + * + * @return DatePeriod + */ + public function cast(string $className) + { + if (!method_exists($className, 'instance')) { + if (is_a($className, DatePeriod::class, true)) { + return new $className( + $this->rawDate($this->getStartDate()), + $this->getDateInterval(), + $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), + $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0 + ); + } + + throw new InvalidCastException("$className has not the instance() method needed to cast the date."); + } + + return $className::instance($this); + } + + /** + * Return native DatePeriod PHP object matching the current instance. + * + * @example + * ``` + * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); + * ``` + * + * @return DatePeriod + */ + public function toDatePeriod() + { + return $this->cast(DatePeriod::class); + } + + /** + * Return `true` if the period has no custom filter and is guaranteed to be endless. + * + * Note that we can't check if a period is endless as soon as it has custom filters + * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in + * a way we can't predict without actually iterating the period. + */ + public function isUnfilteredAndEndLess(): bool + { + foreach ($this->filters as $filter) { + switch ($filter) { + case [static::RECURRENCES_FILTER, null]: + if ($this->recurrences !== null && is_finite($this->recurrences)) { + return false; + } + + break; + + case [static::END_DATE_FILTER, null]: + if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { + return false; + } + + break; + + default: + return false; + } + } + + return true; + } + + /** + * Convert the date period into an array without changing current iteration state. + * + * @return CarbonInterface[] + */ + public function toArray() + { + if ($this->isUnfilteredAndEndLess()) { + throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); + } + + $state = [ + $this->key, + $this->current ? $this->current->avoidMutation() : null, + $this->validationResult, + ]; + + $result = iterator_to_array($this); + + [$this->key, $this->current, $this->validationResult] = $state; + + return $result; + } + + /** + * Count dates in the date period. + * + * @return int + */ + #[ReturnTypeWillChange] + public function count() + { + return \count($this->toArray()); + } + + /** + * Return the first date in the date period. + * + * @return CarbonInterface|null + */ + public function first() + { + if ($this->isUnfilteredAndEndLess()) { + foreach ($this as $date) { + $this->rewind(); + + return $date; + } + + return null; + } + + return ($this->toArray() ?: [])[0] ?? null; + } + + /** + * Return the last date in the date period. + * + * @return CarbonInterface|null + */ + public function last() + { + $array = $this->toArray(); + + return $array ? $array[\count($array) - 1] : null; + } + + /** + * Convert the date period into a string. + * + * @return string + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Add aliases for setters. + * + * CarbonPeriod::days(3)->hours(5)->invert() + * ->sinceNow()->until('2010-01-10') + * ->filter(...) + * ->count() + * + * Note: We use magic method to let static and instance aliases with the same names. + * + * @param string $method + * @param array $parameters + * + * @return mixed + */ + public function __call($method, $parameters) + { + if (static::hasMacro($method)) { + return static::bindMacroContext($this, function () use (&$method, &$parameters) { + return $this->callMacro($method, $parameters); + }); + } + + $roundedValue = $this->callRoundMethod($method, $parameters); + + if ($roundedValue !== null) { + return $roundedValue; + } + + switch ($method) { + case 'start': + case 'since': + self::setDefaultParameters($parameters, [ + [0, 'date', null], + ]); + + return $this->setStartDate(...$parameters); + + case 'sinceNow': + return $this->setStartDate(new Carbon(), ...$parameters); + + case 'end': + case 'until': + self::setDefaultParameters($parameters, [ + [0, 'date', null], + ]); + + return $this->setEndDate(...$parameters); + + case 'untilNow': + return $this->setEndDate(new Carbon(), ...$parameters); + + case 'dates': + case 'between': + self::setDefaultParameters($parameters, [ + [0, 'start', null], + [1, 'end', null], + ]); + + return $this->setDates(...$parameters); + + case 'recurrences': + case 'times': + self::setDefaultParameters($parameters, [ + [0, 'recurrences', null], + ]); + + return $this->setRecurrences(...$parameters); + + case 'options': + self::setDefaultParameters($parameters, [ + [0, 'options', null], + ]); + + return $this->setOptions(...$parameters); + + case 'toggle': + self::setDefaultParameters($parameters, [ + [0, 'options', null], + ]); + + return $this->toggleOptions(...$parameters); + + case 'filter': + case 'push': + return $this->addFilter(...$parameters); + + case 'prepend': + return $this->prependFilter(...$parameters); + + case 'filters': + self::setDefaultParameters($parameters, [ + [0, 'filters', []], + ]); + + return $this->setFilters(...$parameters); + + case 'interval': + case 'each': + case 'every': + case 'step': + case 'stepBy': + return $this->setDateInterval(...$parameters); + + case 'invert': + return $this->invertDateInterval(); + + case 'years': + case 'year': + case 'months': + case 'month': + case 'weeks': + case 'week': + case 'days': + case 'dayz': + case 'day': + case 'hours': + case 'hour': + case 'minutes': + case 'minute': + case 'seconds': + case 'second': + case 'milliseconds': + case 'millisecond': + case 'microseconds': + case 'microsecond': + return $this->setDateInterval(( + // Override default P1D when instantiating via fluent setters. + [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] + )(...$parameters)); + } + + $dateClass = $this->dateClass; + + if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { + throw new UnknownMethodException($method); + } + + return $this; + } + + /** + * Set the instance's timezone from a string or object and apply it to start/end. + * + * @param \DateTimeZone|string $timezone + * + * @return static + */ + public function setTimezone($timezone) + { + $self = $this->copyIfImmutable(); + $self->tzName = $timezone; + $self->timezone = $timezone; + + if ($self->startDate) { + $self = $self->setStartDate($self->startDate->setTimezone($timezone)); + } + + if ($self->endDate) { + $self = $self->setEndDate($self->endDate->setTimezone($timezone)); + } + + return $self; + } + + /** + * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. + * + * @param \DateTimeZone|string $timezone + * + * @return static + */ + public function shiftTimezone($timezone) + { + $self = $this->copyIfImmutable(); + $self->tzName = $timezone; + $self->timezone = $timezone; + + if ($self->startDate) { + $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); + } + + if ($self->endDate) { + $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); + } + + return $self; + } + + /** + * Returns the end is set, else calculated from start an recurrences. + * + * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. + * + * @return CarbonInterface + */ + public function calculateEnd(string $rounding = null) + { + if ($end = $this->getEndDate($rounding)) { + return $end; + } + + if ($this->dateInterval->isEmpty()) { + return $this->getStartDate($rounding); + } + + $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); + + if ($date && $rounding) { + $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); + } + + return $date; + } + + /** + * @return CarbonInterface|null + */ + private function getEndFromRecurrences() + { + if ($this->recurrences === null) { + throw new UnreachableException( + "Could not calculate period end without either explicit end or recurrences.\n". + "If you're looking for a forever-period, use ->setRecurrences(INF)." + ); + } + + if ($this->recurrences === INF) { + $start = $this->getStartDate(); + + return $start < $start->avoidMutation()->add($this->getDateInterval()) + ? CarbonImmutable::endOfTime() + : CarbonImmutable::startOfTime(); + } + + if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { + return $this->getStartDate()->avoidMutation()->add( + $this->getDateInterval()->times( + $this->recurrences - ($this->isStartExcluded() ? 0 : 1) + ) + ); + } + + return null; + } + + /** + * @return CarbonInterface|null + */ + private function iterateUntilEnd() + { + $attempts = 0; + $date = null; + + foreach ($this as $date) { + if (++$attempts > static::END_MAX_ATTEMPTS) { + throw new UnreachableException( + 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.' + ); + } + } + + return $date; + } + + /** + * Returns true if the current period overlaps the given one (if 1 parameter passed) + * or the period between 2 dates (if 2 parameters passed). + * + * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart + * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd + * + * @return bool + */ + public function overlaps($rangeOrRangeStart, $rangeEnd = null) + { + $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; + + if (!($range instanceof self)) { + $range = static::create($range); + } + + [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); + [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); + + return $end > $rangeStart && $rangeEnd > $start; + } + + /** + * Execute a given function on each date of the period. + * + * @example + * ``` + * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { + * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; + * }); + * ``` + * + * @param callable $callback + */ + public function forEach(callable $callback) + { + foreach ($this as $date) { + $callback($date); + } + } + + /** + * Execute a given function on each date of the period and yield the result of this function. + * + * @example + * ``` + * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); + * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { + * return $date->diffInDays('2020-12-25').' days before Christmas!'; + * }))); + * ``` + * + * @param callable $callback + * + * @return \Generator + */ + public function map(callable $callback) + { + foreach ($this as $date) { + yield $callback($date); + } + } + + /** + * Determines if the instance is equal to another. + * Warning: if options differ, instances will never be equal. + * + * @param mixed $period + * + * @see equalTo() + * + * @return bool + */ + public function eq($period): bool + { + return $this->equalTo($period); + } + + /** + * Determines if the instance is equal to another. + * Warning: if options differ, instances will never be equal. + * + * @param mixed $period + * + * @return bool + */ + public function equalTo($period): bool + { + if (!($period instanceof self)) { + $period = self::make($period); + } + + $end = $this->getEndDate(); + + return $period !== null + && $this->getDateInterval()->eq($period->getDateInterval()) + && $this->getStartDate()->eq($period->getStartDate()) + && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) + && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); + } + + /** + * Determines if the instance is not equal to another. + * Warning: if options differ, instances will never be equal. + * + * @param mixed $period + * + * @see notEqualTo() + * + * @return bool + */ + public function ne($period): bool + { + return $this->notEqualTo($period); + } + + /** + * Determines if the instance is not equal to another. + * Warning: if options differ, instances will never be equal. + * + * @param mixed $period + * + * @return bool + */ + public function notEqualTo($period): bool + { + return !$this->eq($period); + } + + /** + * Determines if the start date is before an other given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function startsBefore($date = null): bool + { + return $this->getStartDate()->lessThan($this->resolveCarbon($date)); + } + + /** + * Determines if the start date is before or the same as a given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function startsBeforeOrAt($date = null): bool + { + return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); + } + + /** + * Determines if the start date is after an other given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function startsAfter($date = null): bool + { + return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); + } + + /** + * Determines if the start date is after or the same as a given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function startsAfterOrAt($date = null): bool + { + return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); + } + + /** + * Determines if the start date is the same as a given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function startsAt($date = null): bool + { + return $this->getStartDate()->equalTo($this->resolveCarbon($date)); + } + + /** + * Determines if the end date is before an other given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function endsBefore($date = null): bool + { + return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); + } + + /** + * Determines if the end date is before or the same as a given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function endsBeforeOrAt($date = null): bool + { + return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); + } + + /** + * Determines if the end date is after an other given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function endsAfter($date = null): bool + { + return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); + } + + /** + * Determines if the end date is after or the same as a given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function endsAfterOrAt($date = null): bool + { + return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); + } + + /** + * Determines if the end date is the same as a given date. + * (Rather start/end are included by options is ignored.) + * + * @param mixed $date + * + * @return bool + */ + public function endsAt($date = null): bool + { + return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); + } + + /** + * Return true if start date is now or later. + * (Rather start/end are included by options is ignored.) + * + * @return bool + */ + public function isStarted(): bool + { + return $this->startsBeforeOrAt(); + } + + /** + * Return true if end date is now or later. + * (Rather start/end are included by options is ignored.) + * + * @return bool + */ + public function isEnded(): bool + { + return $this->endsBeforeOrAt(); + } + + /** + * Return true if now is between start date (included) and end date (excluded). + * (Rather start/end are included by options is ignored.) + * + * @return bool + */ + public function isInProgress(): bool + { + return $this->isStarted() && !$this->isEnded(); + } + + /** + * Round the current instance at the given unit with given precision if specified and the given function. + * + * @param string $unit + * @param float|int|string|\DateInterval|null $precision + * @param string $function + * + * @return static + */ + public function roundUnit($unit, $precision = 1, $function = 'round') + { + $self = $this->copyIfImmutable(); + $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); + + if ($self->endDate) { + $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); + } + + return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); + } + + /** + * Truncate the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int|string|\DateInterval|null $precision + * + * @return static + */ + public function floorUnit($unit, $precision = 1) + { + return $this->roundUnit($unit, $precision, 'floor'); + } + + /** + * Ceil the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int|string|\DateInterval|null $precision + * + * @return static + */ + public function ceilUnit($unit, $precision = 1) + { + return $this->roundUnit($unit, $precision, 'ceil'); + } + + /** + * Round the current instance second with given precision if specified (else period interval is used). + * + * @param float|int|string|\DateInterval|null $precision + * @param string $function + * + * @return static + */ + public function round($precision = null, $function = 'round') + { + return $this->roundWith( + $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), + $function + ); + } + + /** + * Round the current instance second with given precision if specified (else period interval is used). + * + * @param float|int|string|\DateInterval|null $precision + * + * @return static + */ + public function floor($precision = null) + { + return $this->round($precision, 'floor'); + } + + /** + * Ceil the current instance second with given precision if specified (else period interval is used). + * + * @param float|int|string|\DateInterval|null $precision + * + * @return static + */ + public function ceil($precision = null) + { + return $this->round($precision, 'ceil'); + } + + /** + * Specify data which should be serialized to JSON. + * + * @link https://php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return CarbonInterface[] + */ + #[ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Return true if the given date is between start and end. + * + * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date + * + * @return bool + */ + public function contains($date = null): bool + { + $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); + $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); + + return $this->$startMethod($date) && $this->$endMethod($date); + } + + /** + * Return true if the current period follows a given other period (with no overlap). + * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] + * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. + * + * @param \Carbon\CarbonPeriod|\DatePeriod|string $period + * + * @return bool + */ + public function follows($period, ...$arguments): bool + { + $period = $this->resolveCarbonPeriod($period, ...$arguments); + + return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); + } + + /** + * Return true if the given other period follows the current one (with no overlap). + * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] + * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. + * + * @param \Carbon\CarbonPeriod|\DatePeriod|string $period + * + * @return bool + */ + public function isFollowedBy($period, ...$arguments): bool + { + $period = $this->resolveCarbonPeriod($period, ...$arguments); + + return $period->follows($this); + } + + /** + * Return true if the given period either follows or is followed by the current one. + * + * @see follows() + * @see isFollowedBy() + * + * @param \Carbon\CarbonPeriod|\DatePeriod|string $period + * + * @return bool + */ + public function isConsecutiveWith($period, ...$arguments): bool + { + return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); + } + + /** + * Update properties after removing built-in filters. + * + * @return void + */ + protected function updateInternalState() + { + if (!$this->hasFilter(static::END_DATE_FILTER)) { + $this->endDate = null; + } + + if (!$this->hasFilter(static::RECURRENCES_FILTER)) { + $this->recurrences = null; + } + } + + /** + * Create a filter tuple from raw parameters. + * + * Will create an automatic filter callback for one of Carbon's is* methods. + * + * @param array $parameters + * + * @return array + */ + protected function createFilterTuple(array $parameters) + { + $method = array_shift($parameters); + + if (!$this->isCarbonPredicateMethod($method)) { + return [$method, array_shift($parameters)]; + } + + return [function ($date) use ($method, $parameters) { + return ([$date, $method])(...$parameters); + }, $method]; + } + + /** + * Return whether given callable is a string pointing to one of Carbon's is* methods + * and should be automatically converted to a filter callback. + * + * @param callable $callable + * + * @return bool + */ + protected function isCarbonPredicateMethod($callable) + { + return \is_string($callable) && str_starts_with($callable, 'is') && + (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); + } + + /** + * Recurrences filter callback (limits number of recurrences). + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * + * @param \Carbon\Carbon $current + * @param int $key + * + * @return bool|string + */ + protected function filterRecurrences($current, $key) + { + if ($key < $this->recurrences) { + return true; + } + + return static::END_ITERATION; + } + + /** + * End date filter callback. + * + * @param \Carbon\Carbon $current + * + * @return bool|string + */ + protected function filterEndDate($current) + { + if (!$this->isEndExcluded() && $current == $this->endDate) { + return true; + } + + if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { + return true; + } + + return static::END_ITERATION; + } + + /** + * End iteration filter callback. + * + * @return string + */ + protected function endIteration() + { + return static::END_ITERATION; + } + + /** + * Handle change of the parameters. + */ + protected function handleChangedParameters() + { + if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { + $this->dateClass = CarbonImmutable::class; + } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { + $this->dateClass = Carbon::class; + } + + $this->validationResult = null; + } + + /** + * Validate current date and stop iteration when necessary. + * + * Returns true when current date is valid, false if it is not, or static::END_ITERATION + * when iteration should be stopped. + * + * @return bool|string + */ + protected function validateCurrentDate() + { + if ($this->current === null) { + $this->rewind(); + } + + // Check after the first rewind to avoid repeating the initial validation. + return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); + } + + /** + * Check whether current value and key pass all the filters. + * + * @return bool|string + */ + protected function checkFilters() + { + $current = $this->prepareForReturn($this->current); + + foreach ($this->filters as $tuple) { + $result = \call_user_func( + $tuple[0], + $current->avoidMutation(), + $this->key, + $this + ); + + if ($result === static::END_ITERATION) { + return static::END_ITERATION; + } + + if (!$result) { + return false; + } + } + + return true; + } + + /** + * Prepare given date to be returned to the external logic. + * + * @param CarbonInterface $date + * + * @return CarbonInterface + */ + protected function prepareForReturn(CarbonInterface $date) + { + $date = ([$this->dateClass, 'make'])($date); + + if ($this->timezone) { + $date = $date->setTimezone($this->timezone); + } + + return $date; + } + + /** + * Keep incrementing the current date until a valid date is found or the iteration is ended. + * + * @throws RuntimeException + * + * @return void + */ + protected function incrementCurrentDateUntilValid() + { + $attempts = 0; + + do { + $this->current = $this->current->add($this->dateInterval); + + $this->validationResult = null; + + if (++$attempts > static::NEXT_MAX_ATTEMPTS) { + throw new UnreachableException('Could not find next valid date.'); + } + } while ($this->validateCurrentDate() === false); + } + + /** + * Call given macro. + * + * @param string $name + * @param array $parameters + * + * @return mixed + */ + protected function callMacro($name, $parameters) + { + $macro = static::$macros[$name]; + + if ($macro instanceof Closure) { + $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); + + return ($boundMacro ?: $macro)(...$parameters); + } + + return $macro(...$parameters); + } + + /** + * Return the Carbon instance passed through, a now instance in the same timezone + * if null given or parse the input if string given. + * + * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date + * + * @return \Carbon\CarbonInterface + */ + protected function resolveCarbon($date = null) + { + return $this->getStartDate()->nowWithSameTz()->carbonize($date); + } + + /** + * Resolve passed arguments or DatePeriod to a CarbonPeriod object. + * + * @param mixed $period + * @param mixed ...$arguments + * + * @return static + */ + protected function resolveCarbonPeriod($period, ...$arguments) + { + if ($period instanceof self) { + return $period; + } + + return $period instanceof DatePeriod + ? static::instance($period) + : static::create($period, ...$arguments); + } + + private function orderCouple($first, $second): array + { + return $first > $second ? [$second, $first] : [$first, $second]; + } + + private function makeDateTime($value): ?DateTimeInterface + { + if ($value instanceof DateTimeInterface) { + return $value; + } + + if (\is_string($value)) { + $value = trim($value); + + if (!preg_match('/^P[\dT]/', $value) && + !preg_match('/^R\d/', $value) && + preg_match('/[a-z\d]/i', $value) + ) { + $dateClass = $this->dateClass; + + return $dateClass::parse($value, $this->tzName); + } + } + + return null; + } + + private function isInfiniteDate($date): bool + { + return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); + } + + private function rawDate($date): ?DateTimeInterface + { + if ($date === false || $date === null) { + return null; + } + + if ($date instanceof CarbonInterface) { + return $date->isMutable() + ? $date->toDateTime() + : $date->toDateTimeImmutable(); + } + + if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { + return $date; + } + + $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; + + return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); + } + + private static function setDefaultParameters(array &$parameters, array $defaults): void + { + foreach ($defaults as [$index, $name, $value]) { + if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { + $parameters[$index] = $value; + } + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonPeriodImmutable.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonPeriodImmutable.php new file mode 100644 index 0000000..f0d0ee2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonPeriodImmutable.php @@ -0,0 +1,40 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +class CarbonPeriodImmutable extends CarbonPeriod +{ + /** + * Default date class of iteration items. + * + * @var string + */ + protected const DEFAULT_DATE_CLASS = CarbonImmutable::class; + + /** + * Date class of iteration items. + * + * @var string + */ + protected $dateClass = CarbonImmutable::class; + + /** + * Prepare the instance to be set (self if mutable to be mutated, + * copy if immutable to generate a new instance). + * + * @return static + */ + protected function copyIfImmutable() + { + return $this->constructed ? clone $this : $this; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php new file mode 100644 index 0000000..c81899f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php @@ -0,0 +1,320 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\Exceptions\InvalidCastException; +use Carbon\Exceptions\InvalidTimeZoneException; +use DateTimeInterface; +use DateTimeZone; +use Throwable; + +class CarbonTimeZone extends DateTimeZone +{ + public function __construct($timezone = null) + { + parent::__construct(static::getDateTimeZoneNameFromMixed($timezone)); + } + + protected static function parseNumericTimezone($timezone) + { + if ($timezone <= -100 || $timezone >= 100) { + throw new InvalidTimeZoneException('Absolute timezone offset cannot be greater than 100.'); + } + + return ($timezone >= 0 ? '+' : '').ltrim($timezone, '+').':00'; + } + + protected static function getDateTimeZoneNameFromMixed($timezone) + { + if ($timezone === null) { + return date_default_timezone_get(); + } + + if (\is_string($timezone)) { + $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone); + } + + if (is_numeric($timezone)) { + return static::parseNumericTimezone($timezone); + } + + return $timezone; + } + + protected static function getDateTimeZoneFromName(&$name) + { + return @timezone_open($name = (string) static::getDateTimeZoneNameFromMixed($name)); + } + + /** + * Cast the current instance into the given class. + * + * @param string $className The $className::instance() method will be called to cast the current object. + * + * @return DateTimeZone + */ + public function cast(string $className) + { + if (!method_exists($className, 'instance')) { + if (is_a($className, DateTimeZone::class, true)) { + return new $className($this->getName()); + } + + throw new InvalidCastException("$className has not the instance() method needed to cast the date."); + } + + return $className::instance($this); + } + + /** + * Create a CarbonTimeZone from mixed input. + * + * @param DateTimeZone|string|int|null $object original value to get CarbonTimeZone from it. + * @param DateTimeZone|string|int|null $objectDump dump of the object for error messages. + * + * @throws InvalidTimeZoneException + * + * @return false|static + */ + public static function instance($object = null, $objectDump = null) + { + $tz = $object; + + if ($tz instanceof static) { + return $tz; + } + + if ($tz === null) { + return new static(); + } + + if (!$tz instanceof DateTimeZone) { + $tz = static::getDateTimeZoneFromName($object); + } + + if ($tz !== false) { + return new static($tz->getName()); + } + + if (Carbon::isStrictModeEnabled()) { + throw new InvalidTimeZoneException('Unknown or bad timezone ('.($objectDump ?: $object).')'); + } + + return false; + } + + /** + * Returns abbreviated name of the current timezone according to DST setting. + * + * @param bool $dst + * + * @return string + */ + public function getAbbreviatedName($dst = false) + { + $name = $this->getName(); + + foreach ($this->listAbbreviations() as $abbreviation => $zones) { + foreach ($zones as $zone) { + if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { + return $abbreviation; + } + } + } + + return 'unknown'; + } + + /** + * @alias getAbbreviatedName + * + * Returns abbreviated name of the current timezone according to DST setting. + * + * @param bool $dst + * + * @return string + */ + public function getAbbr($dst = false) + { + return $this->getAbbreviatedName($dst); + } + + /** + * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30"). + * + * @param DateTimeInterface|null $date + * + * @return string + */ + public function toOffsetName(DateTimeInterface $date = null) + { + return static::getOffsetNameFromMinuteOffset( + $this->getOffset($date ?: Carbon::now($this)) / 60 + ); + } + + /** + * Returns a new CarbonTimeZone object using the offset string instead of region string. + * + * @param DateTimeInterface|null $date + * + * @return CarbonTimeZone + */ + public function toOffsetTimeZone(DateTimeInterface $date = null) + { + return new static($this->toOffsetName($date)); + } + + /** + * Returns the first region string (such as "America/Toronto") that matches the current timezone or + * false if no match is found. + * + * @see timezone_name_from_abbr native PHP function. + * + * @param DateTimeInterface|null $date + * @param int $isDst + * + * @return string|false + */ + public function toRegionName(DateTimeInterface $date = null, $isDst = 1) + { + $name = $this->getName(); + $firstChar = substr($name, 0, 1); + + if ($firstChar !== '+' && $firstChar !== '-') { + return $name; + } + + $date = $date ?: Carbon::now($this); + + // Integer construction no longer supported since PHP 8 + // @codeCoverageIgnoreStart + try { + $offset = @$this->getOffset($date) ?: 0; + } catch (Throwable $e) { + $offset = 0; + } + // @codeCoverageIgnoreEnd + + $name = @timezone_name_from_abbr('', $offset, $isDst); + + if ($name) { + return $name; + } + + foreach (timezone_identifiers_list() as $timezone) { + if (Carbon::instance($date)->tz($timezone)->getOffset() === $offset) { + return $timezone; + } + } + + return false; + } + + /** + * Returns a new CarbonTimeZone object using the region string instead of offset string. + * + * @param DateTimeInterface|null $date + * + * @return CarbonTimeZone|false + */ + public function toRegionTimeZone(DateTimeInterface $date = null) + { + $tz = $this->toRegionName($date); + + if ($tz !== false) { + return new static($tz); + } + + if (Carbon::isStrictModeEnabled()) { + throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($date ?: Carbon::now($this)).' seconds.'); + } + + return false; + } + + /** + * Cast to string (get timezone name). + * + * @return string + */ + public function __toString() + { + return $this->getName(); + } + + /** + * Return the type number: + * + * Type 1; A UTC offset, such as -0300 + * Type 2; A timezone abbreviation, such as GMT + * Type 3: A timezone identifier, such as Europe/London + */ + public function getType(): int + { + return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; + } + + /** + * Create a CarbonTimeZone from mixed input. + * + * @param DateTimeZone|string|int|null $object + * + * @return false|static + */ + public static function create($object = null) + { + return static::instance($object); + } + + /** + * Create a CarbonTimeZone from int/float hour offset. + * + * @param float $hourOffset number of hour of the timezone shift (can be decimal). + * + * @return false|static + */ + public static function createFromHourOffset(float $hourOffset) + { + return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR); + } + + /** + * Create a CarbonTimeZone from int/float minute offset. + * + * @param float $minuteOffset number of total minutes of the timezone shift. + * + * @return false|static + */ + public static function createFromMinuteOffset(float $minuteOffset) + { + return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset)); + } + + /** + * Convert a total minutes offset into a standardized timezone offset string. + * + * @param float $minutes number of total minutes of the timezone shift. + * + * @return string + */ + public static function getOffsetNameFromMinuteOffset(float $minutes): string + { + $minutes = round($minutes); + $unsignedMinutes = abs($minutes); + + return ($minutes < 0 ? '-' : '+'). + str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT). + ':'. + str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Cli/Invoker.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Cli/Invoker.php new file mode 100644 index 0000000..4f35d6c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Cli/Invoker.php @@ -0,0 +1,38 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Cli; + +class Invoker +{ + public const CLI_CLASS_NAME = 'Carbon\\Cli'; + + protected function runWithCli(string $className, array $parameters): bool + { + $cli = new $className(); + + return $cli(...$parameters); + } + + public function __invoke(...$parameters): bool + { + if (class_exists(self::CLI_CLASS_NAME)) { + return $this->runWithCli(self::CLI_CLASS_NAME, $parameters); + } + + $function = (($parameters[1] ?? '') === 'install' ? ($parameters[2] ?? null) : null) ?: 'shell_exec'; + $function('composer require carbon-cli/carbon-cli --no-interaction'); + + echo 'Installation succeeded.'; + + return true; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php new file mode 100644 index 0000000..3ca8837 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php @@ -0,0 +1,48 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use Throwable; + +class BadComparisonUnitException extends UnitException +{ + /** + * The unit. + * + * @var string + */ + protected $unit; + + /** + * Constructor. + * + * @param string $unit + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($unit, $code = 0, Throwable $previous = null) + { + $this->unit = $unit; + + parent::__construct("Bad comparison unit: '$unit'", $code, $previous); + } + + /** + * Get the unit. + * + * @return string + */ + public function getUnit(): string + { + return $this->unit; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php new file mode 100644 index 0000000..2e222e5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use BadMethodCallException as BaseBadMethodCallException; +use Throwable; + +class BadFluentConstructorException extends BaseBadMethodCallException implements BadMethodCallException +{ + /** + * The method. + * + * @var string + */ + protected $method; + + /** + * Constructor. + * + * @param string $method + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($method, $code = 0, Throwable $previous = null) + { + $this->method = $method; + + parent::__construct(sprintf("Unknown fluent constructor '%s'.", $method), $code, $previous); + } + + /** + * Get the method. + * + * @return string + */ + public function getMethod(): string + { + return $this->method; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php new file mode 100644 index 0000000..4ceaa2e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use BadMethodCallException as BaseBadMethodCallException; +use Throwable; + +class BadFluentSetterException extends BaseBadMethodCallException implements BadMethodCallException +{ + /** + * The setter. + * + * @var string + */ + protected $setter; + + /** + * Constructor. + * + * @param string $setter + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($setter, $code = 0, Throwable $previous = null) + { + $this->setter = $setter; + + parent::__construct(sprintf("Unknown fluent setter '%s'", $setter), $code, $previous); + } + + /** + * Get the setter. + * + * @return string + */ + public function getSetter(): string + { + return $this->setter; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php new file mode 100644 index 0000000..108206d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +interface BadMethodCallException extends Exception +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/EndLessPeriodException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/EndLessPeriodException.php new file mode 100644 index 0000000..e104926 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/EndLessPeriodException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use RuntimeException as BaseRuntimeException; + +final class EndLessPeriodException extends BaseRuntimeException implements RuntimeException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php new file mode 100644 index 0000000..8ad747e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +interface Exception +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php new file mode 100644 index 0000000..db334c6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php @@ -0,0 +1,48 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use RuntimeException as BaseRuntimeException; +use Throwable; + +class ImmutableException extends BaseRuntimeException implements RuntimeException +{ + /** + * The value. + * + * @var string + */ + protected $value; + + /** + * Constructor. + * + * @param string $value the immutable type/value + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($value, $code = 0, Throwable $previous = null) + { + $this->value = $value; + parent::__construct("$value is immutable.", $code, $previous); + } + + /** + * Get the value. + * + * @return string + */ + public function getValue(): string + { + return $this->value; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php new file mode 100644 index 0000000..5b013cd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +interface InvalidArgumentException extends Exception +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php new file mode 100644 index 0000000..a421401 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidCastException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php new file mode 100644 index 0000000..c9ecb6b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php @@ -0,0 +1,67 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +class InvalidDateException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + /** + * The invalid field. + * + * @var string + */ + private $field; + + /** + * The invalid value. + * + * @var mixed + */ + private $value; + + /** + * Constructor. + * + * @param string $field + * @param mixed $value + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($field, $value, $code = 0, Throwable $previous = null) + { + $this->field = $field; + $this->value = $value; + parent::__construct($field.' : '.$value.' is not a valid value.', $code, $previous); + } + + /** + * Get the invalid field. + * + * @return string + */ + public function getField() + { + return $this->field; + } + + /** + * Get the invalid value. + * + * @return mixed + */ + public function getValue() + { + return $this->value; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php new file mode 100644 index 0000000..92d55fe --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidFormatException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php new file mode 100644 index 0000000..69cf412 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidIntervalException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php new file mode 100644 index 0000000..9bd84a9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidPeriodDateException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php new file mode 100644 index 0000000..cf2c902 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidPeriodParameterException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php new file mode 100644 index 0000000..f725955 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidTimeZoneException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php new file mode 100644 index 0000000..2c8ec9b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class InvalidTypeException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php new file mode 100644 index 0000000..7a87632 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use Carbon\CarbonInterface; +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +class NotACarbonClassException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + /** + * The className. + * + * @var string + */ + protected $className; + + /** + * Constructor. + * + * @param string $className + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($className, $code = 0, Throwable $previous = null) + { + $this->className = $className; + + parent::__construct(sprintf('Given class does not implement %s: %s', CarbonInterface::class, $className), $code, $previous); + } + + /** + * Get the className. + * + * @return string + */ + public function getClassName(): string + { + return $this->className; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php new file mode 100644 index 0000000..4edd7a4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class NotAPeriodException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php new file mode 100644 index 0000000..f2c5468 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +class NotLocaleAwareException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + /** + * Constructor. + * + * @param mixed $object + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($object, $code = 0, Throwable $previous = null) + { + $dump = \is_object($object) ? \get_class($object) : \gettype($object); + + parent::__construct("$dump does neither implements Symfony\Contracts\Translation\LocaleAwareInterface nor getLocale() method.", $code, $previous); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php new file mode 100644 index 0000000..2c586d0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php @@ -0,0 +1,101 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +// This will extends OutOfRangeException instead of InvalidArgumentException since 3.0.0 +// use OutOfRangeException as BaseOutOfRangeException; + +class OutOfRangeException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + /** + * The unit or name of the value. + * + * @var string + */ + private $unit; + + /** + * The range minimum. + * + * @var mixed + */ + private $min; + + /** + * The range maximum. + * + * @var mixed + */ + private $max; + + /** + * The invalid value. + * + * @var mixed + */ + private $value; + + /** + * Constructor. + * + * @param string $unit + * @param mixed $min + * @param mixed $max + * @param mixed $value + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($unit, $min, $max, $value, $code = 0, Throwable $previous = null) + { + $this->unit = $unit; + $this->min = $min; + $this->max = $max; + $this->value = $value; + + parent::__construct("$unit must be between $min and $max, $value given", $code, $previous); + } + + /** + * @return mixed + */ + public function getMax() + { + return $this->max; + } + + /** + * @return mixed + */ + public function getMin() + { + return $this->min; + } + + /** + * @return mixed + */ + public function getUnit() + { + return $this->unit; + } + + /** + * @return mixed + */ + public function getValue() + { + return $this->value; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php new file mode 100644 index 0000000..5416fd1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php @@ -0,0 +1,88 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +class ParseErrorException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + /** + * The expected. + * + * @var string + */ + protected $expected; + + /** + * The actual. + * + * @var string + */ + protected $actual; + + /** + * The help message. + * + * @var string + */ + protected $help; + + /** + * Constructor. + * + * @param string $expected + * @param string $actual + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($expected, $actual, $help = '', $code = 0, Throwable $previous = null) + { + $this->expected = $expected; + $this->actual = $actual; + $this->help = $help; + + $actual = $actual === '' ? 'data is missing' : "get '$actual'"; + + parent::__construct(trim("Format expected $expected but $actual\n$help"), $code, $previous); + } + + /** + * Get the expected. + * + * @return string + */ + public function getExpected(): string + { + return $this->expected; + } + + /** + * Get the actual. + * + * @return string + */ + public function getActual(): string + { + return $this->actual; + } + + /** + * Get the help message. + * + * @return string + */ + public function getHelp(): string + { + return $this->help; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php new file mode 100644 index 0000000..ad196f7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +interface RuntimeException extends Exception +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php new file mode 100644 index 0000000..ee99953 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; + +class UnitException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php new file mode 100644 index 0000000..0e72305 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php @@ -0,0 +1,48 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use Throwable; + +class UnitNotConfiguredException extends UnitException +{ + /** + * The unit. + * + * @var string + */ + protected $unit; + + /** + * Constructor. + * + * @param string $unit + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($unit, $code = 0, Throwable $previous = null) + { + $this->unit = $unit; + + parent::__construct("Unit $unit have no configuration to get total from other units.", $code, $previous); + } + + /** + * Get the unit. + * + * @return string + */ + public function getUnit(): string + { + return $this->unit; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php new file mode 100644 index 0000000..5c50497 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +class UnknownGetterException extends BaseInvalidArgumentException implements InvalidArgumentException +{ + /** + * The getter. + * + * @var string + */ + protected $getter; + + /** + * Constructor. + * + * @param string $getter getter name + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($getter, $code = 0, Throwable $previous = null) + { + $this->getter = $getter; + + parent::__construct("Unknown getter '$getter'", $code, $previous); + } + + /** + * Get the getter. + * + * @return string + */ + public function getGetter(): string + { + return $this->getter; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php new file mode 100644 index 0000000..75273a7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use BadMethodCallException as BaseBadMethodCallException; +use Throwable; + +class UnknownMethodException extends BaseBadMethodCallException implements BadMethodCallException +{ + /** + * The method. + * + * @var string + */ + protected $method; + + /** + * Constructor. + * + * @param string $method + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($method, $code = 0, Throwable $previous = null) + { + $this->method = $method; + + parent::__construct("Method $method does not exist.", $code, $previous); + } + + /** + * Get the method. + * + * @return string + */ + public function getMethod(): string + { + return $this->method; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php new file mode 100644 index 0000000..a795f5d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; + +class UnknownSetterException extends BaseInvalidArgumentException implements BadMethodCallException +{ + /** + * The setter. + * + * @var string + */ + protected $setter; + + /** + * Constructor. + * + * @param string $setter setter name + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($setter, $code = 0, Throwable $previous = null) + { + $this->setter = $setter; + + parent::__construct("Unknown setter '$setter'", $code, $previous); + } + + /** + * Get the setter. + * + * @return string + */ + public function getSetter(): string + { + return $this->setter; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php new file mode 100644 index 0000000..ecd7f7a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php @@ -0,0 +1,48 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use Throwable; + +class UnknownUnitException extends UnitException +{ + /** + * The unit. + * + * @var string + */ + protected $unit; + + /** + * Constructor. + * + * @param string $unit + * @param int $code + * @param Throwable|null $previous + */ + public function __construct($unit, $code = 0, Throwable $previous = null) + { + $this->unit = $unit; + + parent::__construct("Unknown unit '$unit'.", $code, $previous); + } + + /** + * Get the unit. + * + * @return string + */ + public function getUnit(): string + { + return $this->unit; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php new file mode 100644 index 0000000..1654ab1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use RuntimeException as BaseRuntimeException; + +class UnreachableException extends BaseRuntimeException implements RuntimeException +{ + // +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Factory.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Factory.php new file mode 100644 index 0000000..d497535 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Factory.php @@ -0,0 +1,326 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Closure; +use DateTimeInterface; +use ReflectionMethod; + +/** + * A factory to generate Carbon instances with common settings. + * + * <autodoc generated by `composer phpdoc`> + * + * @method bool canBeCreatedFromFormat($date, $format) Checks if the (date)time string is in a given format and valid to create a + * new instance. + * @method Carbon|false create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) Create a new Carbon instance from a specific date and time. + * If any of $year, $month or $day are set to null their now() values will + * be used. + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * If $hour is not null then the default values for $minute and $second + * will be 0. + * @method Carbon createFromDate($year = null, $month = null, $day = null, $tz = null) Create a Carbon instance from just a date. The time portion is set to now. + * @method Carbon|false createFromFormat($format, $time, $tz = null) Create a Carbon instance from a specific format. + * @method Carbon|false createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). + * @method Carbon|false createFromLocaleFormat($format, $locale, $time, $tz = null) Create a Carbon instance from a specific format and a string in a given language. + * @method Carbon|false createFromLocaleIsoFormat($format, $locale, $time, $tz = null) Create a Carbon instance from a specific ISO format and a string in a given language. + * @method Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null) Create a Carbon instance from just a time. The date portion is set to today. + * @method Carbon createFromTimeString($time, $tz = null) Create a Carbon instance from a time string. The date portion is set to today. + * @method Carbon createFromTimestamp($timestamp, $tz = null) Create a Carbon instance from a timestamp and set the timezone (use default one if not specified). + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method Carbon createFromTimestampMs($timestamp, $tz = null) Create a Carbon instance from a timestamp in milliseconds. + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method Carbon createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds. + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method Carbon createFromTimestampUTC($timestamp) Create a Carbon instance from an timestamp keeping the timezone to UTC. + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method Carbon createMidnightDate($year = null, $month = null, $day = null, $tz = null) Create a Carbon instance from just a date. The time portion is set to midnight. + * @method Carbon|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) Create a new safe Carbon instance from a specific date and time. + * If any of $year, $month or $day are set to null their now() values will + * be used. + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * If $hour is not null then the default values for $minute and $second + * will be 0. + * If one of the set values is not valid, an InvalidDateException + * will be thrown. + * @method CarbonInterface createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $tz = null) Create a new Carbon instance from a specific date and time using strict validation. + * @method Carbon disableHumanDiffOption($humanDiffOption) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method Carbon enableHumanDiffOption($humanDiffOption) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method mixed executeWithLocale($locale, $func) Set the current locale to the given, execute the passed function, reset the locale to previous one, + * then return the result of the closure (or null if the closure was void). + * @method Carbon fromSerialized($value) Create an instance from a serialized string. + * @method void genericMacro($macro, $priority = 0) Register a custom macro. + * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales. + * (It will ignore custom translator dynamic loading.) + * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native + * name, region and variant of the locale. + * @method array getDays() Get the days of the week + * @method string|null getFallbackLocale() Get the fallback locale. + * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat(). + * @method int getHumanDiffOptions() Return default humanDiff() options (merged flags as integer). + * @method array getIsoUnits() Returns list of locale units for ISO formatting. + * @method array getLastErrors() {@inheritdoc} + * @method string getLocale() Get the current translator locale. + * @method callable|null getMacro($name) Get the raw callable macro registered globally for a given name. + * @method int getMidDayAt() get midday/noon hour + * @method Closure|Carbon getTestNow() Get the Carbon instance (real or mock) to be returned when a "now" + * instance is created. + * @method string getTimeFormatByPrecision($unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision. + * @method string getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key. + * @method \Symfony\Component\Translation\TranslatorInterface getTranslator() Get the default translator instance in use. + * @method int getWeekEndsAt() Get the last day of week + * @method int getWeekStartsAt() Get the first day of week + * @method array getWeekendDays() Get weekend days + * @method bool hasFormat($date, $format) Checks if the (date)time string is in a given format. + * @method bool hasFormatWithModifiers($date, $format) Checks if the (date)time string is in a given format. + * @method bool hasMacro($name) Checks if macro is registered globally. + * @method bool hasRelativeKeywords($time) Determine if a time string will produce a relative date. + * @method bool hasTestNow() Determine if there is a valid test instance set. A valid test instance + * is anything that is not null. + * @method Carbon instance($date) Create a Carbon instance from a DateTime one. + * @method bool isImmutable() Returns true if the current class/instance is immutable. + * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter. + * @method bool isMutable() Returns true if the current class/instance is mutable. + * @method bool isStrictModeEnabled() Returns true if the strict mode is globally in use, false else. + * (It can be overridden in specific instances.) + * @method bool localeHasDiffOneDayWords($locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). + * Support is considered enabled if the 3 words are translated in the given locale. + * @method bool localeHasDiffSyntax($locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * @method bool localeHasDiffTwoDayWords($locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). + * Support is considered enabled if the 2 words are translated in the given locale. + * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * @method bool localeHasShortUnits($locale) Returns true if the given locale is internally supported and has short-units support. + * Support is considered enabled if either year, day or hour has a short variant translated. + * @method void macro($name, $macro) Register a custom macro. + * @method Carbon|null make($var) Make a Carbon instance from given variable if possible. + * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals + * and recurrences). Throw an exception for invalid format, but otherwise return null. + * @method Carbon maxValue() Create a Carbon instance for the greatest supported date. + * @method Carbon minValue() Create a Carbon instance for the lowest supported date. + * @method void mixin($mixin) Mix another object into the class. + * @method Carbon now($tz = null) Get a Carbon instance for the current date and time. + * @method Carbon parse($time = null, $tz = null) Create a carbon instance from a string. + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * @method Carbon parseFromLocale($time, $locale = null, $tz = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). + * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English). + * @method Carbon|false rawCreateFromFormat($format, $time, $tz = null) Create a Carbon instance from a specific format. + * @method Carbon rawParse($time = null, $tz = null) Create a carbon instance from a string. + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * @method Carbon resetMacros() Remove all macros and generic macros. + * @method void resetMonthsOverflow() @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method void resetToStringFormat() Reset the format used to the default when type juggling a Carbon instance to a string + * @method void resetYearsOverflow() @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method void serializeUsing($callback) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather transform Carbon object before the serialization. + * JSON serialize all Carbon instances using the given callback. + * @method Carbon setFallbackLocale($locale) Set the fallback locale. + * @method Carbon setHumanDiffOptions($humanDiffOptions) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method bool setLocale($locale) Set the current translator locale and indicate if the source locale file exists. + * Pass 'auto' as locale to use closest language from the current LC_TIME locale. + * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider mid-day is always 12pm, then if you need to test if it's an other + * hour, test it explicitly: + * $date->format('G') == 13 + * or to set explicitly to a given hour: + * $date->setTime(13, 0, 0, 0) + * Set midday/noon hour + * @method Carbon setTestNow($testNow = null) Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * Note the timezone parameter was left out of the examples above and + * has no affect as the mock value will be returned regardless of its value. + * Only the moment is mocked with setTestNow(), the timezone will still be the one passed + * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()). + * To clear the test instance call this method using the default + * parameter of null. + * /!\ Use this method for unit tests only. + * @method Carbon setTestNowAndTimezone($testNow = null, $tz = null) Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * It will also align default timezone (e.g. call date_default_timezone_set()) with + * the second argument or if null, with the timezone of the given date object. + * To clear the test instance call this method using the default + * parameter of null. + * /!\ Use this method for unit tests only. + * @method void setToStringFormat($format) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string + * format. + * Set the default format used when type juggling a Carbon instance to a string. + * @method void setTranslator(TranslatorInterface $translator) Set the default translator instance to use. + * @method Carbon setUtf8($utf8) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use UTF-8 language packages on every machine. + * Set if UTF8 will be used for localized date/time. + * @method void setWeekEndsAt($day) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek + * or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the + * start of week according to current locale selected and implicitly the end of week. + * Set the last day of week + * @method void setWeekStartsAt($day) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the + * 'first_day_of_week' locale setting to change the start of week according to current locale + * selected and implicitly the end of week. + * Set the first day of week + * @method void setWeekendDays($days) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider week-end is always saturday and sunday, and if you have some custom + * week-end days to handle, give to those days an other name and create a macro for them: + * ``` + * Carbon::macro('isDayOff', function ($date) { + * return $date->isSunday() || $date->isMonday(); + * }); + * Carbon::macro('isNotDayOff', function ($date) { + * return !$date->isDayOff(); + * }); + * if ($someDate->isDayOff()) ... + * if ($someDate->isNotDayOff()) ... + * // Add 5 not-off days + * $count = 5; + * while ($someDate->isDayOff() || ($count-- > 0)) { + * $someDate->addDay(); + * } + * ``` + * Set weekend days + * @method bool shouldOverflowMonths() Get the month overflow global behavior (can be overridden in specific instances). + * @method bool shouldOverflowYears() Get the month overflow global behavior (can be overridden in specific instances). + * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English). + * @method Carbon today($tz = null) Create a Carbon instance for today. + * @method Carbon tomorrow($tz = null) Create a Carbon instance for tomorrow. + * @method string translateTimeString($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other. + * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available. + * @method void useMonthsOverflow($monthsOverflow = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method Carbon useStrictMode($strictModeEnabled = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method void useYearsOverflow($yearsOverflow = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method mixed withTestNow($testNow, $callback) Temporarily sets a static date to be used within the callback. + * Using setTestNow to set the date, executing the callback, then + * clearing the test instance. + * /!\ Use this method for unit tests only. + * @method Carbon yesterday($tz = null) Create a Carbon instance for yesterday. + * + * </autodoc> + */ +class Factory +{ + protected $className = Carbon::class; + + protected $settings = []; + + public function __construct(array $settings = [], ?string $className = null) + { + if ($className) { + $this->className = $className; + } + + $this->settings = $settings; + } + + public function getClassName() + { + return $this->className; + } + + public function setClassName(string $className) + { + $this->className = $className; + + return $this; + } + + public function className(string $className = null) + { + return $className === null ? $this->getClassName() : $this->setClassName($className); + } + + public function getSettings() + { + return $this->settings; + } + + public function setSettings(array $settings) + { + $this->settings = $settings; + + return $this; + } + + public function settings(array $settings = null) + { + return $settings === null ? $this->getSettings() : $this->setSettings($settings); + } + + public function mergeSettings(array $settings) + { + $this->settings = array_merge($this->settings, $settings); + + return $this; + } + + public function __call($name, $arguments) + { + $method = new ReflectionMethod($this->className, $name); + $settings = $this->settings; + + if ($settings && isset($settings['timezone'])) { + $tzParameters = array_filter($method->getParameters(), function ($parameter) { + return \in_array($parameter->getName(), ['tz', 'timezone'], true); + }); + + if (isset($arguments[0]) && \in_array($name, ['instance', 'make', 'create', 'parse'], true)) { + if ($arguments[0] instanceof DateTimeInterface) { + $settings['innerTimezone'] = $settings['timezone']; + } elseif (\is_string($arguments[0]) && date_parse($arguments[0])['is_localtime']) { + unset($settings['timezone'], $settings['innerTimezone']); + } + } elseif (\count($tzParameters)) { + array_splice($arguments, key($tzParameters), 0, [$settings['timezone']]); + unset($settings['timezone']); + } + } + + $result = $this->className::$name(...$arguments); + + return $result instanceof CarbonInterface && !empty($settings) + ? $result->settings($settings) + : $result; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php new file mode 100644 index 0000000..d88a1cf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php @@ -0,0 +1,259 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Closure; +use DateTimeImmutable; +use DateTimeZone; +use Psr\Clock\ClockInterface; + +/** + * A factory to generate CarbonImmutable instances with common settings. + * + * <autodoc generated by `composer phpdoc`> + * + * @method bool canBeCreatedFromFormat($date, $format) Checks if the (date)time string is in a given format and valid to create a + * new instance. + * @method CarbonImmutable|false create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) Create a new Carbon instance from a specific date and time. + * If any of $year, $month or $day are set to null their now() values will + * be used. + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * If $hour is not null then the default values for $minute and $second + * will be 0. + * @method CarbonImmutable createFromDate($year = null, $month = null, $day = null, $tz = null) Create a Carbon instance from just a date. The time portion is set to now. + * @method CarbonImmutable|false createFromFormat($format, $time, $tz = null) Create a Carbon instance from a specific format. + * @method CarbonImmutable|false createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). + * @method CarbonImmutable|false createFromLocaleFormat($format, $locale, $time, $tz = null) Create a Carbon instance from a specific format and a string in a given language. + * @method CarbonImmutable|false createFromLocaleIsoFormat($format, $locale, $time, $tz = null) Create a Carbon instance from a specific ISO format and a string in a given language. + * @method CarbonImmutable createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null) Create a Carbon instance from just a time. The date portion is set to today. + * @method CarbonImmutable createFromTimeString($time, $tz = null) Create a Carbon instance from a time string. The date portion is set to today. + * @method CarbonImmutable createFromTimestamp($timestamp, $tz = null) Create a Carbon instance from a timestamp and set the timezone (use default one if not specified). + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method CarbonImmutable createFromTimestampMs($timestamp, $tz = null) Create a Carbon instance from a timestamp in milliseconds. + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method CarbonImmutable createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds. + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method CarbonImmutable createFromTimestampUTC($timestamp) Create a Carbon instance from an timestamp keeping the timezone to UTC. + * Timestamp input can be given as int, float or a string containing one or more numbers. + * @method CarbonImmutable createMidnightDate($year = null, $month = null, $day = null, $tz = null) Create a Carbon instance from just a date. The time portion is set to midnight. + * @method CarbonImmutable|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) Create a new safe Carbon instance from a specific date and time. + * If any of $year, $month or $day are set to null their now() values will + * be used. + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * If $hour is not null then the default values for $minute and $second + * will be 0. + * If one of the set values is not valid, an InvalidDateException + * will be thrown. + * @method CarbonInterface createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $tz = null) Create a new Carbon instance from a specific date and time using strict validation. + * @method CarbonImmutable disableHumanDiffOption($humanDiffOption) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method CarbonImmutable enableHumanDiffOption($humanDiffOption) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method mixed executeWithLocale($locale, $func) Set the current locale to the given, execute the passed function, reset the locale to previous one, + * then return the result of the closure (or null if the closure was void). + * @method CarbonImmutable fromSerialized($value) Create an instance from a serialized string. + * @method void genericMacro($macro, $priority = 0) Register a custom macro. + * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales. + * (It will ignore custom translator dynamic loading.) + * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native + * name, region and variant of the locale. + * @method array getDays() Get the days of the week + * @method string|null getFallbackLocale() Get the fallback locale. + * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat(). + * @method int getHumanDiffOptions() Return default humanDiff() options (merged flags as integer). + * @method array getIsoUnits() Returns list of locale units for ISO formatting. + * @method array getLastErrors() {@inheritdoc} + * @method string getLocale() Get the current translator locale. + * @method callable|null getMacro($name) Get the raw callable macro registered globally for a given name. + * @method int getMidDayAt() get midday/noon hour + * @method Closure|CarbonImmutable getTestNow() Get the Carbon instance (real or mock) to be returned when a "now" + * instance is created. + * @method string getTimeFormatByPrecision($unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision. + * @method string getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key. + * @method \Symfony\Component\Translation\TranslatorInterface getTranslator() Get the default translator instance in use. + * @method int getWeekEndsAt() Get the last day of week + * @method int getWeekStartsAt() Get the first day of week + * @method array getWeekendDays() Get weekend days + * @method bool hasFormat($date, $format) Checks if the (date)time string is in a given format. + * @method bool hasFormatWithModifiers($date, $format) Checks if the (date)time string is in a given format. + * @method bool hasMacro($name) Checks if macro is registered globally. + * @method bool hasRelativeKeywords($time) Determine if a time string will produce a relative date. + * @method bool hasTestNow() Determine if there is a valid test instance set. A valid test instance + * is anything that is not null. + * @method CarbonImmutable instance($date) Create a Carbon instance from a DateTime one. + * @method bool isImmutable() Returns true if the current class/instance is immutable. + * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter. + * @method bool isMutable() Returns true if the current class/instance is mutable. + * @method bool isStrictModeEnabled() Returns true if the strict mode is globally in use, false else. + * (It can be overridden in specific instances.) + * @method bool localeHasDiffOneDayWords($locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). + * Support is considered enabled if the 3 words are translated in the given locale. + * @method bool localeHasDiffSyntax($locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * @method bool localeHasDiffTwoDayWords($locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). + * Support is considered enabled if the 2 words are translated in the given locale. + * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * @method bool localeHasShortUnits($locale) Returns true if the given locale is internally supported and has short-units support. + * Support is considered enabled if either year, day or hour has a short variant translated. + * @method void macro($name, $macro) Register a custom macro. + * @method CarbonImmutable|null make($var) Make a Carbon instance from given variable if possible. + * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals + * and recurrences). Throw an exception for invalid format, but otherwise return null. + * @method CarbonImmutable maxValue() Create a Carbon instance for the greatest supported date. + * @method CarbonImmutable minValue() Create a Carbon instance for the lowest supported date. + * @method void mixin($mixin) Mix another object into the class. + * @method CarbonImmutable parse($time = null, $tz = null) Create a carbon instance from a string. + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * @method CarbonImmutable parseFromLocale($time, $locale = null, $tz = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). + * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English). + * @method CarbonImmutable|false rawCreateFromFormat($format, $time, $tz = null) Create a Carbon instance from a specific format. + * @method CarbonImmutable rawParse($time = null, $tz = null) Create a carbon instance from a string. + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * @method CarbonImmutable resetMacros() Remove all macros and generic macros. + * @method void resetMonthsOverflow() @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method void resetToStringFormat() Reset the format used to the default when type juggling a Carbon instance to a string + * @method void resetYearsOverflow() @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method void serializeUsing($callback) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather transform Carbon object before the serialization. + * JSON serialize all Carbon instances using the given callback. + * @method CarbonImmutable setFallbackLocale($locale) Set the fallback locale. + * @method CarbonImmutable setHumanDiffOptions($humanDiffOptions) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method bool setLocale($locale) Set the current translator locale and indicate if the source locale file exists. + * Pass 'auto' as locale to use closest language from the current LC_TIME locale. + * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider mid-day is always 12pm, then if you need to test if it's an other + * hour, test it explicitly: + * $date->format('G') == 13 + * or to set explicitly to a given hour: + * $date->setTime(13, 0, 0, 0) + * Set midday/noon hour + * @method CarbonImmutable setTestNow($testNow = null) Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * Note the timezone parameter was left out of the examples above and + * has no affect as the mock value will be returned regardless of its value. + * Only the moment is mocked with setTestNow(), the timezone will still be the one passed + * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()). + * To clear the test instance call this method using the default + * parameter of null. + * /!\ Use this method for unit tests only. + * @method CarbonImmutable setTestNowAndTimezone($testNow = null, $tz = null) Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * It will also align default timezone (e.g. call date_default_timezone_set()) with + * the second argument or if null, with the timezone of the given date object. + * To clear the test instance call this method using the default + * parameter of null. + * /!\ Use this method for unit tests only. + * @method void setToStringFormat($format) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string + * format. + * Set the default format used when type juggling a Carbon instance to a string. + * @method void setTranslator(TranslatorInterface $translator) Set the default translator instance to use. + * @method CarbonImmutable setUtf8($utf8) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use UTF-8 language packages on every machine. + * Set if UTF8 will be used for localized date/time. + * @method void setWeekEndsAt($day) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek + * or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the + * start of week according to current locale selected and implicitly the end of week. + * Set the last day of week + * @method void setWeekStartsAt($day) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the + * 'first_day_of_week' locale setting to change the start of week according to current locale + * selected and implicitly the end of week. + * Set the first day of week + * @method void setWeekendDays($days) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider week-end is always saturday and sunday, and if you have some custom + * week-end days to handle, give to those days an other name and create a macro for them: + * ``` + * Carbon::macro('isDayOff', function ($date) { + * return $date->isSunday() || $date->isMonday(); + * }); + * Carbon::macro('isNotDayOff', function ($date) { + * return !$date->isDayOff(); + * }); + * if ($someDate->isDayOff()) ... + * if ($someDate->isNotDayOff()) ... + * // Add 5 not-off days + * $count = 5; + * while ($someDate->isDayOff() || ($count-- > 0)) { + * $someDate->addDay(); + * } + * ``` + * Set weekend days + * @method bool shouldOverflowMonths() Get the month overflow global behavior (can be overridden in specific instances). + * @method bool shouldOverflowYears() Get the month overflow global behavior (can be overridden in specific instances). + * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English). + * @method CarbonImmutable today($tz = null) Create a Carbon instance for today. + * @method CarbonImmutable tomorrow($tz = null) Create a Carbon instance for tomorrow. + * @method string translateTimeString($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other. + * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available. + * @method void useMonthsOverflow($monthsOverflow = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method CarbonImmutable useStrictMode($strictModeEnabled = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @method void useYearsOverflow($yearsOverflow = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @method mixed withTestNow($testNow, $callback) Temporarily sets a static date to be used within the callback. + * Using setTestNow to set the date, executing the callback, then + * clearing the test instance. + * /!\ Use this method for unit tests only. + * @method CarbonImmutable yesterday($tz = null) Create a Carbon instance for yesterday. + * + * </autodoc> + */ +class FactoryImmutable extends Factory implements ClockInterface +{ + protected $className = CarbonImmutable::class; + + /** + * Get a Carbon instance for the current date and time. + * + * @param DateTimeZone|string|int|null $tz + * + * @return CarbonImmutable + */ + public function now($tz = null): DateTimeImmutable + { + $className = $this->className; + + return new $className(null, $tz); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa.php new file mode 100644 index 0000000..f3431e4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/aa_DJ.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_DJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_DJ.php new file mode 100644 index 0000000..c6e23c0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_DJ.php @@ -0,0 +1,44 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Qunxa Garablu', 'Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Liiqen', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu'], + 'months_short' => ['qun', 'nah', 'cig', 'agd', 'cax', 'qas', 'qad', 'leq', 'way', 'dit', 'xim', 'kax'], + 'weekdays' => ['Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti'], + 'weekdays_short' => ['aca', 'etl', 'tal', 'arb', 'kam', 'gum', 'sab'], + 'weekdays_min' => ['aca', 'etl', 'tal', 'arb', 'kam', 'gum', 'sab'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['saaku', 'carra'], + + 'year' => ':count gaqambo', // less reliable + 'y' => ':count gaqambo', // less reliable + 'a_year' => ':count gaqambo', // less reliable + + 'month' => ':count àlsa', + 'm' => ':count àlsa', + 'a_month' => ':count àlsa', + + 'day' => ':count saaku', // less reliable + 'd' => ':count saaku', // less reliable + 'a_day' => ':count saaku', // less reliable + + 'hour' => ':count ayti', // less reliable + 'h' => ':count ayti', // less reliable + 'a_hour' => ':count ayti', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ER.php new file mode 100644 index 0000000..f8f395b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ER.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Qunxa Garablu', 'Naharsi Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Leqeeni', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu'], + 'months_short' => ['Qun', 'Nah', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax'], + 'weekdays' => ['Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti'], + 'weekdays_short' => ['Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab'], + 'weekdays_min' => ['Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['saaku', 'carra'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ER@saaho.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ER@saaho.php new file mode 100644 index 0000000..6461225 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ER@saaho.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Qunxa Garablu', 'Naharsi Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Leqeeni', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu'], + 'months_short' => ['Qun', 'Nah', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax'], + 'weekdays' => ['Naba Sambat', 'Sani', 'Salus', 'Rabuq', 'Camus', 'Jumqata', 'Qunxa Sambat'], + 'weekdays_short' => ['Nab', 'San', 'Sal', 'Rab', 'Cam', 'Jum', 'Qun'], + 'weekdays_min' => ['Nab', 'San', 'Sal', 'Rab', 'Cam', 'Jum', 'Qun'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['saaku', 'carra'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ET.php new file mode 100644 index 0000000..e55e591 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/aa_ET.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Qunxa Garablu', 'Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Liiqen', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu'], + 'months_short' => ['Qun', 'Kud', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax'], + 'weekdays' => ['Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti'], + 'weekdays_short' => ['Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab'], + 'weekdays_min' => ['Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['saaku', 'carra'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af.php new file mode 100644 index 0000000..27771d7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af.php @@ -0,0 +1,79 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - JD Isaacks + * - Pierre du Plessis + */ +return [ + 'year' => ':count jaar', + 'a_year' => '\'n jaar|:count jaar', + 'y' => ':count j.', + 'month' => ':count maand|:count maande', + 'a_month' => '\'n maand|:count maande', + 'm' => ':count maa.', + 'week' => ':count week|:count weke', + 'a_week' => '\'n week|:count weke', + 'w' => ':count w.', + 'day' => ':count dag|:count dae', + 'a_day' => '\'n dag|:count dae', + 'd' => ':count d.', + 'hour' => ':count uur', + 'a_hour' => '\'n uur|:count uur', + 'h' => ':count u.', + 'minute' => ':count minuut|:count minute', + 'a_minute' => '\'n minuut|:count minute', + 'min' => ':count min.', + 'second' => ':count sekond|:count sekondes', + 'a_second' => '\'n paar sekondes|:count sekondes', + 's' => ':count s.', + 'ago' => ':time gelede', + 'from_now' => 'oor :time', + 'after' => ':time na', + 'before' => ':time voor', + 'diff_now' => 'Nou', + 'diff_today' => 'Vandag', + 'diff_today_regexp' => 'Vandag(?:\\s+om)?', + 'diff_yesterday' => 'Gister', + 'diff_yesterday_regexp' => 'Gister(?:\\s+om)?', + 'diff_tomorrow' => 'Môre', + 'diff_tomorrow_regexp' => 'Môre(?:\\s+om)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Vandag om] LT', + 'nextDay' => '[Môre om] LT', + 'nextWeek' => 'dddd [om] LT', + 'lastDay' => '[Gister om] LT', + 'lastWeek' => '[Laas] dddd [om] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + return $number.(($number === 1 || $number === 8 || $number >= 20) ? 'ste' : 'de'); + }, + 'meridiem' => ['VM', 'NM'], + 'months' => ['Januarie', 'Februarie', 'Maart', 'April', 'Mei', 'Junie', 'Julie', 'Augustus', 'September', 'Oktober', 'November', 'Desember'], + 'months_short' => ['Jan', 'Feb', 'Mrt', 'Apr', 'Mei', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Sondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrydag', 'Saterdag'], + 'weekdays_short' => ['Son', 'Maa', 'Din', 'Woe', 'Don', 'Vry', 'Sat'], + 'weekdays_min' => ['So', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' en '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af_NA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af_NA.php new file mode 100644 index 0000000..f2fcf05 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af_NA.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/af.php', [ + 'meridiem' => ['v', 'n'], + 'weekdays' => ['Sondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrydag', 'Saterdag'], + 'weekdays_short' => ['So.', 'Ma.', 'Di.', 'Wo.', 'Do.', 'Vr.', 'Sa.'], + 'weekdays_min' => ['So.', 'Ma.', 'Di.', 'Wo.', 'Do.', 'Vr.', 'Sa.'], + 'months' => ['Januarie', 'Februarie', 'Maart', 'April', 'Mei', 'Junie', 'Julie', 'Augustus', 'September', 'Oktober', 'November', 'Desember'], + 'months_short' => ['Jan.', 'Feb.', 'Mrt.', 'Apr.', 'Mei', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Okt.', 'Nov.', 'Des.'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'DD MMM YYYY', + 'LLL' => 'DD MMMM YYYY HH:mm', + 'LLLL' => 'dddd, DD MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af_ZA.php new file mode 100644 index 0000000..27896bd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/af_ZA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/af.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agq.php new file mode 100644 index 0000000..7011464 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agq.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['a.g', 'a.k'], + 'weekdays' => ['tsuʔntsɨ', 'tsuʔukpà', 'tsuʔughɔe', 'tsuʔutɔ̀mlò', 'tsuʔumè', 'tsuʔughɨ̂m', 'tsuʔndzɨkɔʔɔ'], + 'weekdays_short' => ['nts', 'kpa', 'ghɔ', 'tɔm', 'ume', 'ghɨ', 'dzk'], + 'weekdays_min' => ['nts', 'kpa', 'ghɔ', 'tɔm', 'ume', 'ghɨ', 'dzk'], + 'months' => ['ndzɔ̀ŋɔ̀nùm', 'ndzɔ̀ŋɔ̀kƗ̀zùʔ', 'ndzɔ̀ŋɔ̀tƗ̀dʉ̀ghà', 'ndzɔ̀ŋɔ̀tǎafʉ̄ghā', 'ndzɔ̀ŋèsèe', 'ndzɔ̀ŋɔ̀nzùghò', 'ndzɔ̀ŋɔ̀dùmlo', 'ndzɔ̀ŋɔ̀kwîfɔ̀e', 'ndzɔ̀ŋɔ̀tƗ̀fʉ̀ghàdzughù', 'ndzɔ̀ŋɔ̀ghǔuwelɔ̀m', 'ndzɔ̀ŋɔ̀chwaʔàkaa wo', 'ndzɔ̀ŋèfwòo'], + 'months_short' => ['nùm', 'kɨz', 'tɨd', 'taa', 'see', 'nzu', 'dum', 'fɔe', 'dzu', 'lɔm', 'kaa', 'fwo'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agr.php new file mode 100644 index 0000000..8f036ae --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agr.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/agr_PE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agr_PE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agr_PE.php new file mode 100644 index 0000000..54a326a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/agr_PE.php @@ -0,0 +1,44 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - somosazucar.org libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Petsatin', 'Kupitin', 'Uyaitin', 'Tayutin', 'Kegketin', 'Tegmatin', 'Kuntutin', 'Yagkujutin', 'Daiktatin', 'Ipamtatin', 'Shinutin', 'Sakamtin'], + 'months_short' => ['Pet', 'Kup', 'Uya', 'Tay', 'Keg', 'Teg', 'Kun', 'Yag', 'Dait', 'Ipam', 'Shin', 'Sak'], + 'weekdays' => ['Tuntuamtin', 'Achutin', 'Kugkuktin', 'Saketin', 'Shimpitin', 'Imaptin', 'Bataetin'], + 'weekdays_short' => ['Tun', 'Ach', 'Kug', 'Sak', 'Shim', 'Im', 'Bat'], + 'weekdays_min' => ['Tun', 'Ach', 'Kug', 'Sak', 'Shim', 'Im', 'Bat'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 7, + 'meridiem' => ['VM', 'NM'], + + 'year' => ':count yaya', // less reliable + 'y' => ':count yaya', // less reliable + 'a_year' => ':count yaya', // less reliable + + 'month' => ':count nantu', // less reliable + 'm' => ':count nantu', // less reliable + 'a_month' => ':count nantu', // less reliable + + 'day' => ':count nayaim', // less reliable + 'd' => ':count nayaim', // less reliable + 'a_day' => ':count nayaim', // less reliable + + 'hour' => ':count kuwiš', // less reliable + 'h' => ':count kuwiš', // less reliable + 'a_hour' => ':count kuwiš', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ak.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ak.php new file mode 100644 index 0000000..5a64be3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ak.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ak_GH.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ak_GH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ak_GH.php new file mode 100644 index 0000000..1381946 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ak_GH.php @@ -0,0 +1,40 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Sugar Labs // OLPC sugarlabs.org libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY/MM/DD', + ], + 'months' => ['Sanda-Ɔpɛpɔn', 'Kwakwar-Ɔgyefuo', 'Ebɔw-Ɔbenem', 'Ebɔbira-Oforisuo', 'Esusow Aketseaba-Kɔtɔnimba', 'Obirade-Ayɛwohomumu', 'Ayɛwoho-Kitawonsa', 'Difuu-Ɔsandaa', 'Fankwa-Ɛbɔ', 'Ɔbɛsɛ-Ahinime', 'Ɔberɛfɛw-Obubuo', 'Mumu-Ɔpɛnimba'], + 'months_short' => ['S-Ɔ', 'K-Ɔ', 'E-Ɔ', 'E-O', 'E-K', 'O-A', 'A-K', 'D-Ɔ', 'F-Ɛ', 'Ɔ-A', 'Ɔ-O', 'M-Ɔ'], + 'weekdays' => ['Kwesida', 'Dwowda', 'Benada', 'Wukuda', 'Yawda', 'Fida', 'Memeneda'], + 'weekdays_short' => ['Kwe', 'Dwo', 'Ben', 'Wuk', 'Yaw', 'Fia', 'Mem'], + 'weekdays_min' => ['Kwe', 'Dwo', 'Ben', 'Wuk', 'Yaw', 'Fia', 'Mem'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['AN', 'EW'], + + 'year' => ':count afe', + 'y' => ':count afe', + 'a_year' => ':count afe', + + 'month' => ':count bosume', + 'm' => ':count bosume', + 'a_month' => ':count bosume', + + 'day' => ':count ɛda', + 'd' => ':count ɛda', + 'a_day' => ':count ɛda', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/am.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/am.php new file mode 100644 index 0000000..63bf72d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/am.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/am_ET.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/am_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/am_ET.php new file mode 100644 index 0000000..ece8062 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/am_ET.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕሪል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክቶበር', 'ኖቬምበር', 'ዲሴምበር'], + 'months_short' => ['ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም'], + 'weekdays' => ['እሑድ', 'ሰኞ', 'ማክሰኞ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ'], + 'weekdays_short' => ['እሑድ', 'ሰኞ ', 'ማክሰ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ'], + 'weekdays_min' => ['እሑድ', 'ሰኞ ', 'ማክሰ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ጡዋት', 'ከሰዓት'], + + 'year' => ':count አመት', + 'y' => ':count አመት', + 'a_year' => ':count አመት', + + 'month' => ':count ወር', + 'm' => ':count ወር', + 'a_month' => ':count ወር', + + 'week' => ':count ሳምንት', + 'w' => ':count ሳምንት', + 'a_week' => ':count ሳምንት', + + 'day' => ':count ቀን', + 'd' => ':count ቀን', + 'a_day' => ':count ቀን', + + 'hour' => ':count ሰዓት', + 'h' => ':count ሰዓት', + 'a_hour' => ':count ሰዓት', + + 'minute' => ':count ደቂቃ', + 'min' => ':count ደቂቃ', + 'a_minute' => ':count ደቂቃ', + + 'second' => ':count ሴኮንድ', + 's' => ':count ሴኮንድ', + 'a_second' => ':count ሴኮንድ', + + 'ago' => 'ከ:time በፊት', + 'from_now' => 'በ:time ውስጥ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/an.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/an.php new file mode 100644 index 0000000..565abf2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/an.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/an_ES.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/an_ES.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/an_ES.php new file mode 100644 index 0000000..faf8ae0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/an_ES.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Softaragones Jordi Mallach Pérez, Juan Pablo Martínez bug-glibc-locales@gnu.org, softaragones@softaragones.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['chinero', 'febrero', 'marzo', 'abril', 'mayo', 'chunyo', 'chuliol', 'agosto', 'setiembre', 'octubre', 'noviembre', 'aviento'], + 'months_short' => ['chi', 'feb', 'mar', 'abr', 'may', 'chn', 'chl', 'ago', 'set', 'oct', 'nov', 'avi'], + 'weekdays' => ['domingo', 'luns', 'martes', 'mierques', 'chueves', 'viernes', 'sabado'], + 'weekdays_short' => ['dom', 'lun', 'mar', 'mie', 'chu', 'vie', 'sab'], + 'weekdays_min' => ['dom', 'lun', 'mar', 'mie', 'chu', 'vie', 'sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count año', + 'y' => ':count año', + 'a_year' => ':count año', + + 'month' => ':count mes', + 'm' => ':count mes', + 'a_month' => ':count mes', + + 'week' => ':count semana', + 'w' => ':count semana', + 'a_week' => ':count semana', + + 'day' => ':count día', + 'd' => ':count día', + 'a_day' => ':count día', + + 'hour' => ':count reloch', // less reliable + 'h' => ':count reloch', // less reliable + 'a_hour' => ':count reloch', // less reliable + + 'minute' => ':count minuto', + 'min' => ':count minuto', + 'a_minute' => ':count minuto', + + 'second' => ':count segundo', + 's' => ':count segundo', + 'a_second' => ':count segundo', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/anp.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/anp.php new file mode 100644 index 0000000..b56c67b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/anp.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/anp_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/anp_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/anp_IN.php new file mode 100644 index 0000000..11069be --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/anp_IN.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bhashaghar@googlegroups.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर"'], + 'months_short' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर'], + 'weekdays' => ['रविवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'बृहस्पतिवार', 'शुक्रवार', 'शनिवार'], + 'weekdays_short' => ['रवि', 'सोम', 'मंगल', 'बुध', 'बृहस्पति', 'शुक्र', 'शनि'], + 'weekdays_min' => ['रवि', 'सोम', 'मंगल', 'बुध', 'बृहस्पति', 'शुक्र', 'शनि'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar.php new file mode 100644 index 0000000..5f73f63 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar.php @@ -0,0 +1,93 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Atef Ben Ali (atefBB) + * - Ibrahim AshShohail + * - MLTDev + * - Mohamed Sabil (mohamedsabil83) + * - Yazan Alnugnugh (yazan-alnugnugh) + */ +$months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => ':time من الآن', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدًا(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'اث', 'ثل', 'أر', 'خم', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم عند الساعة] LT', + 'nextDay' => '[غدًا عند الساعة] LT', + 'nextWeek' => 'dddd [عند الساعة] LT', + 'lastDay' => '[أمس عند الساعة] LT', + 'lastWeek' => 'dddd [عند الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php new file mode 100644 index 0000000..35a22b1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت '], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php new file mode 100644 index 0000000..3518096 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_DJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_DJ.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_DJ.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_DZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_DZ.php new file mode 100644 index 0000000..aea4eee --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_DZ.php @@ -0,0 +1,92 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Authors: + * - Josh Soref + * - Noureddine LOUAHEDJ + * - JD Isaacks + * - Atef Ben Ali (atefBB) + * - Mohamed Sabil (mohamedsabil83) + */ +$months = [ + 'جانفي', + 'فيفري', + 'مارس', + 'أفريل', + 'ماي', + 'جوان', + 'جويلية', + 'أوت', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => 'في :time', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدا(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['أح', 'إث', 'ثلا', 'أر', 'خم', 'جم', 'سب'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 4, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم على الساعة] LT', + 'nextDay' => '[غدا على الساعة] LT', + 'nextWeek' => 'dddd [على الساعة] LT', + 'lastDay' => '[أمس على الساعة] LT', + 'lastWeek' => 'dddd [على الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php new file mode 100644 index 0000000..3518096 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_EH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_EH.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_EH.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_ER.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_ER.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IL.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IL.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IN.php new file mode 100644 index 0000000..5fecf70 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IN.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php new file mode 100644 index 0000000..2d42008 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'months_short' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php new file mode 100644 index 0000000..2d42008 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'months_short' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_KM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_KM.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_KM.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php new file mode 100644 index 0000000..b3fb1cf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php @@ -0,0 +1,95 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Authors: + * - Josh Soref + * - Nusret Parlak + * - JD Isaacks + * - Atef Ben Ali (atefBB) + * - Mohamed Sabil (mohamedsabil83) + * - Abdullah-Alhariri + */ +$months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'ماي', + 'يونيو', + 'يوليوز', + 'غشت', + 'شتنبر', + 'أكتوبر', + 'نونبر', + 'دجنبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => 'في :time', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدا(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم على الساعة] LT', + 'nextDay' => '[غدا على الساعة] LT', + 'nextWeek' => 'dddd [على الساعة] LT', + 'lastDay' => '[أمس على الساعة] LT', + 'lastWeek' => 'dddd [على الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php new file mode 100644 index 0000000..2792745 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'months_short' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_LY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_LY.php new file mode 100644 index 0000000..1f0af49 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_LY.php @@ -0,0 +1,92 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Atef Ben Ali (atefBB) + * - Ibrahim AshShohail + * - MLTDev + */ + +$months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', +]; + +return [ + 'year' => implode('|', [':count سنة', 'سنة', 'سنتين', ':count سنوات', ':count سنة']), + 'a_year' => implode('|', [':count سنة', 'سنة', 'سنتين', ':count سنوات', ':count سنة']), + 'month' => implode('|', [':count شهر', 'شهر', 'شهرين', ':count أشهر', ':count شهر']), + 'a_month' => implode('|', [':count شهر', 'شهر', 'شهرين', ':count أشهر', ':count شهر']), + 'week' => implode('|', [':count أسبوع', 'أسبوع', 'أسبوعين', ':count أسابيع', ':count أسبوع']), + 'a_week' => implode('|', [':count أسبوع', 'أسبوع', 'أسبوعين', ':count أسابيع', ':count أسبوع']), + 'day' => implode('|', [':count يوم', 'يوم', 'يومين', ':count أيام', ':count يوم']), + 'a_day' => implode('|', [':count يوم', 'يوم', 'يومين', ':count أيام', ':count يوم']), + 'hour' => implode('|', [':count ساعة', 'ساعة', 'ساعتين', ':count ساعات', ':count ساعة']), + 'a_hour' => implode('|', [':count ساعة', 'ساعة', 'ساعتين', ':count ساعات', ':count ساعة']), + 'minute' => implode('|', [':count دقيقة', 'دقيقة', 'دقيقتين', ':count دقائق', ':count دقيقة']), + 'a_minute' => implode('|', [':count دقيقة', 'دقيقة', 'دقيقتين', ':count دقائق', ':count دقيقة']), + 'second' => implode('|', [':count ثانية', 'ثانية', 'ثانيتين', ':count ثواني', ':count ثانية']), + 'a_second' => implode('|', [':count ثانية', 'ثانية', 'ثانيتين', ':count ثواني', ':count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => ':time من الآن', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدًا(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['مرة', 'مرة', ':count مرتين', ':count مرات', ':count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'اث', 'ثل', 'أر', 'خم', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم عند الساعة] LT', + 'nextDay' => '[غدًا عند الساعة] LT', + 'nextWeek' => 'dddd [عند الساعة] LT', + 'lastDay' => '[أمس عند الساعة] LT', + 'lastWeek' => 'dddd [عند الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_MA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_MA.php new file mode 100644 index 0000000..047ae05 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_MA.php @@ -0,0 +1,92 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Authors: + * - Josh Soref + * - JD Isaacks + * - Atef Ben Ali (atefBB) + * - Mohamed Sabil (mohamedsabil83) + */ +$months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'ماي', + 'يونيو', + 'يوليوز', + 'غشت', + 'شتنبر', + 'أكتوبر', + 'نونبر', + 'دجنبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => 'في :time', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدا(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم على الساعة] LT', + 'nextDay' => '[غدا على الساعة] LT', + 'nextWeek' => 'dddd [على الساعة] LT', + 'lastDay' => '[أمس على الساعة] LT', + 'lastWeek' => 'dddd [على الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_MR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_MR.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_MR.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php new file mode 100644 index 0000000..3518096 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php new file mode 100644 index 0000000..503c60d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php new file mode 100644 index 0000000..3518096 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php new file mode 100644 index 0000000..550b0c7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php @@ -0,0 +1,94 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Authors: + * - Josh Soref + * - JD Isaacks + * - Atef Ben Ali (atefBB) + * - Mohamed Sabil (mohamedsabil83) + * - Abdullah-Alhariri + */ +$months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => 'في :time', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدا(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم على الساعة] LT', + 'nextDay' => '[غدا على الساعة] LT', + 'nextWeek' => 'dddd [على الساعة] LT', + 'lastDay' => '[أمس على الساعة] LT', + 'lastWeek' => 'dddd [على الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php new file mode 100644 index 0000000..3518096 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SO.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SO.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SS.php new file mode 100644 index 0000000..32f3282 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SS.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php new file mode 100644 index 0000000..2d42008 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'months_short' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_Shakl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_Shakl.php new file mode 100644 index 0000000..c2d4b43 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_Shakl.php @@ -0,0 +1,95 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Abdellah Chadidi + * - Atef Ben Ali (atefBB) + * - Mohamed Sabil (mohamedsabil83) + */ +// Same for long and short +$months = [ + // @TODO add shakl to months + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سَنَة', '{1}سَنَة', '{2}سَنَتَيْن', ']2,11[:count سَنَوَات', ']10,Inf[:count سَنَة']), + 'a_year' => implode('|', ['{0}:count سَنَة', '{1}سَنَة', '{2}سَنَتَيْن', ']2,11[:count سَنَوَات', ']10,Inf[:count سَنَة']), + 'month' => implode('|', ['{0}:count شَهْرَ', '{1}شَهْرَ', '{2}شَهْرَيْن', ']2,11[:count أَشْهُر', ']10,Inf[:count شَهْرَ']), + 'a_month' => implode('|', ['{0}:count شَهْرَ', '{1}شَهْرَ', '{2}شَهْرَيْن', ']2,11[:count أَشْهُر', ']10,Inf[:count شَهْرَ']), + 'week' => implode('|', ['{0}:count أُسْبُوع', '{1}أُسْبُوع', '{2}أُسْبُوعَيْن', ']2,11[:count أَسَابِيع', ']10,Inf[:count أُسْبُوع']), + 'a_week' => implode('|', ['{0}:count أُسْبُوع', '{1}أُسْبُوع', '{2}أُسْبُوعَيْن', ']2,11[:count أَسَابِيع', ']10,Inf[:count أُسْبُوع']), + 'day' => implode('|', ['{0}:count يَوْم', '{1}يَوْم', '{2}يَوْمَيْن', ']2,11[:count أَيَّام', ']10,Inf[:count يَوْم']), + 'a_day' => implode('|', ['{0}:count يَوْم', '{1}يَوْم', '{2}يَوْمَيْن', ']2,11[:count أَيَّام', ']10,Inf[:count يَوْم']), + 'hour' => implode('|', ['{0}:count سَاعَة', '{1}سَاعَة', '{2}سَاعَتَيْن', ']2,11[:count سَاعَات', ']10,Inf[:count سَاعَة']), + 'a_hour' => implode('|', ['{0}:count سَاعَة', '{1}سَاعَة', '{2}سَاعَتَيْن', ']2,11[:count سَاعَات', ']10,Inf[:count سَاعَة']), + 'minute' => implode('|', ['{0}:count دَقِيقَة', '{1}دَقِيقَة', '{2}دَقِيقَتَيْن', ']2,11[:count دَقَائِق', ']10,Inf[:count دَقِيقَة']), + 'a_minute' => implode('|', ['{0}:count دَقِيقَة', '{1}دَقِيقَة', '{2}دَقِيقَتَيْن', ']2,11[:count دَقَائِق', ']10,Inf[:count دَقِيقَة']), + 'second' => implode('|', ['{0}:count ثَانِيَة', '{1}ثَانِيَة', '{2}ثَانِيَتَيْن', ']2,11[:count ثَوَان', ']10,Inf[:count ثَانِيَة']), + 'a_second' => implode('|', ['{0}:count ثَانِيَة', '{1}ثَانِيَة', '{2}ثَانِيَتَيْن', ']2,11[:count ثَوَان', ']10,Inf[:count ثَانِيَة']), + 'ago' => 'مُنْذُ :time', + 'from_now' => 'مِنَ الْآن :time', + 'after' => 'بَعْدَ :time', + 'before' => 'قَبْلَ :time', + + // @TODO add shakl to translations below + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدًا(?:\\s+عند)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'اث', 'ثل', 'أر', 'خم', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم عند الساعة] LT', + 'nextDay' => '[غدًا عند الساعة] LT', + 'nextWeek' => 'dddd [عند الساعة] LT', + 'lastDay' => '[أمس عند الساعة] LT', + 'lastWeek' => 'dddd [عند الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_TD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_TD.php new file mode 100644 index 0000000..e790b99 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_TD.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ar.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_TN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_TN.php new file mode 100644 index 0000000..f096678 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_TN.php @@ -0,0 +1,91 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Authors: + * - JD Isaacks + * - Atef Ben Ali (atefBB) + * - Mohamed Sabil (mohamedsabil83) + */ +$months = [ + 'جانفي', + 'فيفري', + 'مارس', + 'أفريل', + 'ماي', + 'جوان', + 'جويلية', + 'أوت', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', +]; + +return [ + 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), + 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), + 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), + 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), + 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), + 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), + 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), + 'ago' => 'منذ :time', + 'from_now' => 'في :time', + 'after' => 'بعد :time', + 'before' => 'قبل :time', + 'diff_now' => 'الآن', + 'diff_today' => 'اليوم', + 'diff_today_regexp' => 'اليوم(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_yesterday' => 'أمس', + 'diff_yesterday_regexp' => 'أمس(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_tomorrow' => 'غداً', + 'diff_tomorrow_regexp' => 'غدا(?:\\s+على)?(?:\\s+الساعة)?', + 'diff_before_yesterday' => 'قبل الأمس', + 'diff_after_tomorrow' => 'بعد غد', + 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), + 'period_interval' => 'كل :interval', + 'period_start_date' => 'من :date', + 'period_end_date' => 'إلى :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اليوم على الساعة] LT', + 'nextDay' => '[غدا على الساعة] LT', + 'nextWeek' => 'dddd [على الساعة] LT', + 'lastDay' => '[أمس على الساعة] LT', + 'lastWeek' => 'dddd [على الساعة] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ص', 'م'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php new file mode 100644 index 0000000..169fe88 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri + */ +return array_replace_recursive(require __DIR__.'/ar.php', [ + 'formats' => [ + 'L' => 'DD MMM, YYYY', + ], + 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], + 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], + 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], + 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/as.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/as.php new file mode 100644 index 0000000..04bc3df --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/as.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/as_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/as_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/as_IN.php new file mode 100644 index 0000000..5fbc3db --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/as_IN.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Amitakhya Phukan, Red Hat bug-glibc@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D-MM-YYYY', + ], + 'months' => ['জানুৱাৰী', 'ফেব্ৰুৱাৰী', 'মাৰ্চ', 'এপ্ৰিল', 'মে', 'জুন', 'জুলাই', 'আগষ্ট', 'ছেপ্তেম্বৰ', 'অক্টোবৰ', 'নৱেম্বৰ', 'ডিচেম্বৰ'], + 'months_short' => ['জানু', 'ফেব্ৰু', 'মাৰ্চ', 'এপ্ৰিল', 'মে', 'জুন', 'জুলাই', 'আগ', 'সেপ্ট', 'অক্টো', 'নভে', 'ডিসে'], + 'weekdays' => ['দেওবাৰ', 'সোমবাৰ', 'মঙ্গলবাৰ', 'বুধবাৰ', 'বৃহষ্পতিবাৰ', 'শুক্ৰবাৰ', 'শনিবাৰ'], + 'weekdays_short' => ['দেও', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহষ্পতি', 'শুক্ৰ', 'শনি'], + 'weekdays_min' => ['দেও', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহষ্পতি', 'শুক্ৰ', 'শনি'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['পূৰ্ব্বাহ্ন', 'অপৰাহ্ন'], + + 'year' => ':count বছৰ', + 'y' => ':count বছৰ', + 'a_year' => ':count বছৰ', + + 'month' => ':count মাহ', + 'm' => ':count মাহ', + 'a_month' => ':count মাহ', + + 'week' => ':count সপ্তাহ', + 'w' => ':count সপ্তাহ', + 'a_week' => ':count সপ্তাহ', + + 'day' => ':count বাৰ', + 'd' => ':count বাৰ', + 'a_day' => ':count বাৰ', + + 'hour' => ':count ঘণ্টা', + 'h' => ':count ঘণ্টা', + 'a_hour' => ':count ঘণ্টা', + + 'minute' => ':count মিনিট', + 'min' => ':count মিনিট', + 'a_minute' => ':count মিনিট', + + 'second' => ':count দ্বিতীয়', + 's' => ':count দ্বিতীয়', + 'a_second' => ':count দ্বিতীয়', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/asa.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/asa.php new file mode 100644 index 0000000..03bb483 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/asa.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['icheheavo', 'ichamthi'], + 'weekdays' => ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Ijm', 'Jmo'], + 'weekdays_min' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Ijm', 'Jmo'], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Dec'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ast.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ast.php new file mode 100644 index 0000000..d9bdebe --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ast.php @@ -0,0 +1,59 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Jordi Mallach jordi@gnu.org + * - Adolfo Jayme-Barrientos (fitojb) + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['de xineru', 'de febreru', 'de marzu', 'd’abril', 'de mayu', 'de xunu', 'de xunetu', 'd’agostu', 'de setiembre', 'd’ochobre', 'de payares', 'd’avientu'], + 'months_short' => ['xin', 'feb', 'mar', 'abr', 'may', 'xun', 'xnt', 'ago', 'set', 'och', 'pay', 'avi'], + 'weekdays' => ['domingu', 'llunes', 'martes', 'miércoles', 'xueves', 'vienres', 'sábadu'], + 'weekdays_short' => ['dom', 'llu', 'mar', 'mié', 'xue', 'vie', 'sáb'], + 'weekdays_min' => ['dom', 'llu', 'mar', 'mié', 'xue', 'vie', 'sáb'], + + 'year' => ':count añu|:count años', + 'y' => ':count añu|:count años', + 'a_year' => 'un añu|:count años', + + 'month' => ':count mes', + 'm' => ':count mes', + 'a_month' => 'un mes|:count mes', + + 'week' => ':count selmana|:count selmanes', + 'w' => ':count selmana|:count selmanes', + 'a_week' => 'una selmana|:count selmanes', + + 'day' => ':count día|:count díes', + 'd' => ':count día|:count díes', + 'a_day' => 'un día|:count díes', + + 'hour' => ':count hora|:count hores', + 'h' => ':count hora|:count hores', + 'a_hour' => 'una hora|:count hores', + + 'minute' => ':count minutu|:count minutos', + 'min' => ':count minutu|:count minutos', + 'a_minute' => 'un minutu|:count minutos', + + 'second' => ':count segundu|:count segundos', + 's' => ':count segundu|:count segundos', + 'a_second' => 'un segundu|:count segundos', + + 'ago' => 'hai :time', + 'from_now' => 'en :time', + 'after' => ':time dempués', + 'before' => ':time enantes', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ast_ES.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ast_ES.php new file mode 100644 index 0000000..04d7562 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ast_ES.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ast.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ayc.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ayc.php new file mode 100644 index 0000000..d6a6f63 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ayc.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ayc_PE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ayc_PE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ayc_PE.php new file mode 100644 index 0000000..ff18504 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ayc_PE.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - runasimipi.org libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['inïru', 'phiwriru', 'marsu', 'awrila', 'mayu', 'junyu', 'julyu', 'awustu', 'sitimri', 'uktuwri', 'nuwimri', 'risimri'], + 'months_short' => ['ini', 'phi', 'mar', 'awr', 'may', 'jun', 'jul', 'awu', 'sit', 'ukt', 'nuw', 'ris'], + 'weekdays' => ['tuminku', 'lunisa', 'martisa', 'mirkulisa', 'juywisa', 'wirnisa', 'sawäru'], + 'weekdays_short' => ['tum', 'lun', 'mar', 'mir', 'juy', 'wir', 'saw'], + 'weekdays_min' => ['tum', 'lun', 'mar', 'mir', 'juy', 'wir', 'saw'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['VM', 'NM'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az.php new file mode 100644 index 0000000..1e92106 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az.php @@ -0,0 +1,128 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Kunal Marwaha + * - François B + * - JD Isaacks + * - Orxan + * - Şəhriyar İmanov + * - Baran Şengül + */ +return [ + 'year' => ':count il', + 'a_year' => '{1}bir il|]1,Inf[:count il', + 'y' => ':count il', + 'month' => ':count ay', + 'a_month' => '{1}bir ay|]1,Inf[:count ay', + 'm' => ':count ay', + 'week' => ':count həftə', + 'a_week' => '{1}bir həftə|]1,Inf[:count həftə', + 'w' => ':count h.', + 'day' => ':count gün', + 'a_day' => '{1}bir gün|]1,Inf[:count gün', + 'd' => ':count g.', + 'hour' => ':count saat', + 'a_hour' => '{1}bir saat|]1,Inf[:count saat', + 'h' => ':count saat', + 'minute' => ':count d.', + 'a_minute' => '{1}bir dəqiqə|]1,Inf[:count dəqiqə', + 'min' => ':count dəqiqə', + 'second' => ':count san.', + 'a_second' => '{1}birneçə saniyə|]1,Inf[:count saniyə', + 's' => ':count saniyə', + 'ago' => ':time əvvəl', + 'from_now' => ':time sonra', + 'after' => ':time sonra', + 'before' => ':time əvvəl', + 'diff_now' => 'indi', + 'diff_today' => 'bugün', + 'diff_today_regexp' => 'bugün(?:\\s+saat)?', + 'diff_yesterday' => 'dünən', + 'diff_tomorrow' => 'sabah', + 'diff_tomorrow_regexp' => 'sabah(?:\\s+saat)?', + 'diff_before_yesterday' => 'srağagün', + 'diff_after_tomorrow' => 'birisi gün', + 'period_recurrences' => ':count dəfədən bir', + 'period_interval' => 'hər :interval', + 'period_start_date' => ':date tarixindən başlayaraq', + 'period_end_date' => ':date tarixinədək', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[bugün saat] LT', + 'nextDay' => '[sabah saat] LT', + 'nextWeek' => '[gələn həftə] dddd [saat] LT', + 'lastDay' => '[dünən] LT', + 'lastWeek' => '[keçən həftə] dddd [saat] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + if ($number === 0) { // special case for zero + return "$number-ıncı"; + } + + static $suffixes = [ + 1 => '-inci', + 5 => '-inci', + 8 => '-inci', + 70 => '-inci', + 80 => '-inci', + 2 => '-nci', + 7 => '-nci', + 20 => '-nci', + 50 => '-nci', + 3 => '-üncü', + 4 => '-üncü', + 100 => '-üncü', + 6 => '-ncı', + 9 => '-uncu', + 10 => '-uncu', + 30 => '-uncu', + 60 => '-ıncı', + 90 => '-ıncı', + ]; + + $lastDigit = $number % 10; + + return $number.($suffixes[$lastDigit] ?? $suffixes[$number % 100 - $lastDigit] ?? $suffixes[$number >= 100 ? 100 : -1] ?? ''); + }, + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'gecə'; + } + if ($hour < 12) { + return 'səhər'; + } + if ($hour < 17) { + return 'gündüz'; + } + + return 'axşam'; + }, + 'months' => ['yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr'], + 'months_short' => ['yan', 'fev', 'mar', 'apr', 'may', 'iyn', 'iyl', 'avq', 'sen', 'okt', 'noy', 'dek'], + 'months_standalone' => ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'İyun', 'İyul', 'Avqust', 'Sentyabr', 'Oktyabr', 'Noyabr', 'Dekabr'], + 'weekdays' => ['bazar', 'bazar ertəsi', 'çərşənbə axşamı', 'çərşənbə', 'cümə axşamı', 'cümə', 'şənbə'], + 'weekdays_short' => ['baz', 'bze', 'çax', 'çər', 'cax', 'cüm', 'şən'], + 'weekdays_min' => ['bz', 'be', 'ça', 'çə', 'ca', 'cü', 'şə'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' və '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_AZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_AZ.php new file mode 100644 index 0000000..2acf881 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_AZ.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Pablo Saratxaga pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/az.php', [ + 'months_short' => ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek'], + 'weekdays' => ['bazar günü', 'bazar ertəsi', 'çərşənbə axşamı', 'çərşənbə', 'cümə axşamı', 'cümə', 'şənbə'], + 'weekdays_short' => ['baz', 'ber', 'çax', 'çər', 'cax', 'cüm', 'şnb'], + 'weekdays_min' => ['baz', 'ber', 'çax', 'çər', 'cax', 'cüm', 'şnb'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_Cyrl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_Cyrl.php new file mode 100644 index 0000000..28fc62f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_Cyrl.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/az.php', [ + 'weekdays' => ['базар', 'базар ертәси', 'чәршәнбә ахшамы', 'чәршәнбә', 'ҹүмә ахшамы', 'ҹүмә', 'шәнбә'], + 'weekdays_short' => ['Б.', 'Б.Е.', 'Ч.А.', 'Ч.', 'Ҹ.А.', 'Ҹ.', 'Ш.'], + 'weekdays_min' => ['Б.', 'Б.Е.', 'Ч.А.', 'Ч.', 'Ҹ.А.', 'Ҹ.', 'Ш.'], + 'months' => ['јанвар', 'феврал', 'март', 'апрел', 'май', 'ијун', 'ијул', 'август', 'сентјабр', 'октјабр', 'нојабр', 'декабр'], + 'months_short' => ['јан', 'фев', 'мар', 'апр', 'май', 'ијн', 'ијл', 'авг', 'сен', 'окт', 'ној', 'дек'], + 'months_standalone' => ['Јанвар', 'Феврал', 'Март', 'Апрел', 'Май', 'Ијун', 'Ијул', 'Август', 'Сентјабр', 'Октјабр', 'Нојабр', 'Декабр'], + 'meridiem' => ['а', 'п'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_IR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_IR.php new file mode 100644 index 0000000..991a0ef --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_IR.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Mousa Moradi mousamk@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'OY/OM/OD', + ], + 'months' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مئی', 'ژوئن', 'جولای', 'آقۇست', 'سپتامبر', 'اوْکتوْبر', 'نوْوامبر', 'دسامبر'], + 'months_short' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مئی', 'ژوئن', 'جولای', 'آقۇست', 'سپتامبر', 'اوْکتوْبر', 'نوْوامبر', 'دسامبر'], + 'weekdays' => ['یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چارشنبه', 'جۆمعه آخشامی', 'جۆمعه', 'شنبه'], + 'weekdays_short' => ['یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چارشنبه', 'جۆمعه آخشامی', 'جۆمعه', 'شنبه'], + 'weekdays_min' => ['یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چارشنبه', 'جۆمعه آخشامی', 'جۆمعه', 'شنبه'], + 'first_day_of_week' => 6, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰۴', '۰۵', '۰۶', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱۴', '۱۵', '۱۶', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲۴', '۲۵', '۲۶', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳۴', '۳۵', '۳۶', '۳۷', '۳۸', '۳۹', '۴۰', '۴۱', '۴۲', '۴۳', '۴۴', '۴۵', '۴۶', '۴۷', '۴۸', '۴۹', '۵۰', '۵۱', '۵۲', '۵۳', '۵۴', '۵۵', '۵۶', '۵۷', '۵۸', '۵۹', '۶۰', '۶۱', '۶۲', '۶۳', '۶۴', '۶۵', '۶۶', '۶۷', '۶۸', '۶۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷۴', '۷۵', '۷۶', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸۴', '۸۵', '۸۶', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹۴', '۹۵', '۹۶', '۹۷', '۹۸', '۹۹'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_Latn.php new file mode 100644 index 0000000..0be3391 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/az_Latn.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/az.php', [ + 'meridiem' => ['a', 'p'], + 'weekdays' => ['bazar', 'bazar ertəsi', 'çərşənbə axşamı', 'çərşənbə', 'cümə axşamı', 'cümə', 'şənbə'], + 'weekdays_short' => ['B.', 'B.E.', 'Ç.A.', 'Ç.', 'C.A.', 'C.', 'Ş.'], + 'weekdays_min' => ['B.', 'B.E.', 'Ç.A.', 'Ç.', 'C.A.', 'C.', 'Ş.'], + 'months' => ['yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr'], + 'months_short' => ['yan', 'fev', 'mar', 'apr', 'may', 'iyn', 'iyl', 'avq', 'sen', 'okt', 'noy', 'dek'], + 'months_standalone' => ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'İyun', 'İyul', 'Avqust', 'Sentyabr', 'Oktyabr', 'Noyabr', 'Dekabr'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'D MMMM YYYY, dddd HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bas.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bas.php new file mode 100644 index 0000000..41bfa1d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bas.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['I bikɛ̂glà', 'I ɓugajɔp'], + 'weekdays' => ['ŋgwà nɔ̂y', 'ŋgwà njaŋgumba', 'ŋgwà ûm', 'ŋgwà ŋgê', 'ŋgwà mbɔk', 'ŋgwà kɔɔ', 'ŋgwà jôn'], + 'weekdays_short' => ['nɔy', 'nja', 'uum', 'ŋge', 'mbɔ', 'kɔɔ', 'jon'], + 'weekdays_min' => ['nɔy', 'nja', 'uum', 'ŋge', 'mbɔ', 'kɔɔ', 'jon'], + 'months' => ['Kɔndɔŋ', 'Màcɛ̂l', 'Màtùmb', 'Màtop', 'M̀puyɛ', 'Hìlòndɛ̀', 'Njèbà', 'Hìkaŋ', 'Dìpɔ̀s', 'Bìòôm', 'Màyɛsèp', 'Lìbuy li ńyèe'], + 'months_short' => ['kɔn', 'mac', 'mat', 'mto', 'mpu', 'hil', 'nje', 'hik', 'dip', 'bio', 'may', 'liɓ'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'second' => ':count móndî', // less reliable + 's' => ':count móndî', // less reliable + 'a_second' => ':count móndî', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be.php new file mode 100644 index 0000000..ee73636 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be.php @@ -0,0 +1,172 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Carbon\CarbonInterface; +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); + }, 'be'); +} +// @codeCoverageIgnoreEnd + +/* + * Authors: + * - Josh Soref + * - SobakaSlava + * - François B + * - Serhan Apaydın + * - JD Isaacks + * - AbadonnaAbbys + * - Siomkin Alexander + */ +return [ + 'year' => ':count год|:count гады|:count гадоў', + 'a_year' => '{1}год|:count год|:count гады|:count гадоў', + 'y' => ':count год|:count гады|:count гадоў', + 'month' => ':count месяц|:count месяцы|:count месяцаў', + 'a_month' => '{1}месяц|:count месяц|:count месяцы|:count месяцаў', + 'm' => ':count месяц|:count месяцы|:count месяцаў', + 'week' => ':count тыдзень|:count тыдні|:count тыдняў', + 'a_week' => '{1}тыдзень|:count тыдзень|:count тыдні|:count тыдняў', + 'w' => ':count тыдзень|:count тыдні|:count тыдняў', + 'day' => ':count дзень|:count дні|:count дзён', + 'a_day' => '{1}дзень|:count дзень|:count дні|:count дзён', + 'd' => ':count дн', + 'hour' => ':count гадзіну|:count гадзіны|:count гадзін', + 'a_hour' => '{1}гадзіна|:count гадзіна|:count гадзіны|:count гадзін', + 'h' => ':count гадзіна|:count гадзіны|:count гадзін', + 'minute' => ':count хвіліна|:count хвіліны|:count хвілін', + 'a_minute' => '{1}хвіліна|:count хвіліна|:count хвіліны|:count хвілін', + 'min' => ':count хв', + 'second' => ':count секунда|:count секунды|:count секунд', + 'a_second' => '{1}некалькі секунд|:count секунда|:count секунды|:count секунд', + 's' => ':count сек', + + 'hour_ago' => ':count гадзіну|:count гадзіны|:count гадзін', + 'a_hour_ago' => '{1}гадзіну|:count гадзіну|:count гадзіны|:count гадзін', + 'h_ago' => ':count гадзіну|:count гадзіны|:count гадзін', + 'minute_ago' => ':count хвіліну|:count хвіліны|:count хвілін', + 'a_minute_ago' => '{1}хвіліну|:count хвіліну|:count хвіліны|:count хвілін', + 'min_ago' => ':count хвіліну|:count хвіліны|:count хвілін', + 'second_ago' => ':count секунду|:count секунды|:count секунд', + 'a_second_ago' => '{1}некалькі секунд|:count секунду|:count секунды|:count секунд', + 's_ago' => ':count секунду|:count секунды|:count секунд', + + 'hour_from_now' => ':count гадзіну|:count гадзіны|:count гадзін', + 'a_hour_from_now' => '{1}гадзіну|:count гадзіну|:count гадзіны|:count гадзін', + 'h_from_now' => ':count гадзіну|:count гадзіны|:count гадзін', + 'minute_from_now' => ':count хвіліну|:count хвіліны|:count хвілін', + 'a_minute_from_now' => '{1}хвіліну|:count хвіліну|:count хвіліны|:count хвілін', + 'min_from_now' => ':count хвіліну|:count хвіліны|:count хвілін', + 'second_from_now' => ':count секунду|:count секунды|:count секунд', + 'a_second_from_now' => '{1}некалькі секунд|:count секунду|:count секунды|:count секунд', + 's_from_now' => ':count секунду|:count секунды|:count секунд', + + 'hour_after' => ':count гадзіну|:count гадзіны|:count гадзін', + 'a_hour_after' => '{1}гадзіну|:count гадзіну|:count гадзіны|:count гадзін', + 'h_after' => ':count гадзіну|:count гадзіны|:count гадзін', + 'minute_after' => ':count хвіліну|:count хвіліны|:count хвілін', + 'a_minute_after' => '{1}хвіліну|:count хвіліну|:count хвіліны|:count хвілін', + 'min_after' => ':count хвіліну|:count хвіліны|:count хвілін', + 'second_after' => ':count секунду|:count секунды|:count секунд', + 'a_second_after' => '{1}некалькі секунд|:count секунду|:count секунды|:count секунд', + 's_after' => ':count секунду|:count секунды|:count секунд', + + 'hour_before' => ':count гадзіну|:count гадзіны|:count гадзін', + 'a_hour_before' => '{1}гадзіну|:count гадзіну|:count гадзіны|:count гадзін', + 'h_before' => ':count гадзіну|:count гадзіны|:count гадзін', + 'minute_before' => ':count хвіліну|:count хвіліны|:count хвілін', + 'a_minute_before' => '{1}хвіліну|:count хвіліну|:count хвіліны|:count хвілін', + 'min_before' => ':count хвіліну|:count хвіліны|:count хвілін', + 'second_before' => ':count секунду|:count секунды|:count секунд', + 'a_second_before' => '{1}некалькі секунд|:count секунду|:count секунды|:count секунд', + 's_before' => ':count секунду|:count секунды|:count секунд', + + 'ago' => ':time таму', + 'from_now' => 'праз :time', + 'after' => ':time пасля', + 'before' => ':time да', + 'diff_now' => 'цяпер', + 'diff_today' => 'Сёння', + 'diff_today_regexp' => 'Сёння(?:\\s+ў)?', + 'diff_yesterday' => 'учора', + 'diff_yesterday_regexp' => 'Учора(?:\\s+ў)?', + 'diff_tomorrow' => 'заўтра', + 'diff_tomorrow_regexp' => 'Заўтра(?:\\s+ў)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY г.', + 'LLL' => 'D MMMM YYYY г., HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY г., HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Сёння ў] LT', + 'nextDay' => '[Заўтра ў] LT', + 'nextWeek' => '[У] dddd [ў] LT', + 'lastDay' => '[Учора ў] LT', + 'lastWeek' => function (CarbonInterface $current) { + switch ($current->dayOfWeek) { + case 1: + case 2: + case 4: + return '[У мінулы] dddd [ў] LT'; + default: + return '[У мінулую] dddd [ў] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'M': + case 'd': + case 'DDD': + case 'w': + case 'W': + return ($number % 10 === 2 || $number % 10 === 3) && ($number % 100 !== 12 && $number % 100 !== 13) ? $number.'-і' : $number.'-ы'; + case 'D': + return $number.'-га'; + default: + return $number; + } + }, + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'ночы'; + } + if ($hour < 12) { + return 'раніцы'; + } + if ($hour < 17) { + return 'дня'; + } + + return 'вечара'; + }, + 'months' => ['студзеня', 'лютага', 'сакавіка', 'красавіка', 'траўня', 'чэрвеня', 'ліпеня', 'жніўня', 'верасня', 'кастрычніка', 'лістапада', 'снежня'], + 'months_standalone' => ['студзень', 'люты', 'сакавік', 'красавік', 'травень', 'чэрвень', 'ліпень', 'жнівень', 'верасень', 'кастрычнік', 'лістапад', 'снежань'], + 'months_short' => ['студ', 'лют', 'сак', 'крас', 'трав', 'чэрв', 'ліп', 'жнів', 'вер', 'каст', 'ліст', 'снеж'], + 'months_regexp' => '/(DD?o?\.?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['нядзелю', 'панядзелак', 'аўторак', 'сераду', 'чацвер', 'пятніцу', 'суботу'], + 'weekdays_standalone' => ['нядзеля', 'панядзелак', 'аўторак', 'серада', 'чацвер', 'пятніца', 'субота'], + 'weekdays_short' => ['нд', 'пн', 'ат', 'ср', 'чц', 'пт', 'сб'], + 'weekdays_min' => ['нд', 'пн', 'ат', 'ср', 'чц', 'пт', 'сб'], + 'weekdays_regexp' => '/\[ ?[Ууў] ?(?:мінулую|наступную)? ?\] ?dddd/', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' і '], + 'months_short_standalone' => ['сту', 'лют', 'сак', 'кра', 'май', 'чэр', 'ліп', 'жні', 'вер', 'кас', 'ліс', 'сне'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be_BY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be_BY.php new file mode 100644 index 0000000..26684b4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be_BY.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/be.php', [ + 'months' => ['студзеня', 'лютага', 'сакавіка', 'красавіка', 'мая', 'чэрвеня', 'ліпеня', 'жніўня', 'верасня', 'кастрычніка', 'лістапада', 'снежня'], + 'months_short' => ['сту', 'лют', 'сак', 'кра', 'мая', 'чэр', 'ліп', 'жні', 'вер', 'кас', 'ліс', 'сне'], + 'weekdays' => ['Нядзеля', 'Панядзелак', 'Аўторак', 'Серада', 'Чацвер', 'Пятніца', 'Субота'], + 'weekdays_short' => ['Няд', 'Пан', 'Аўт', 'Срд', 'Чцв', 'Пят', 'Суб'], + 'weekdays_min' => ['Няд', 'Пан', 'Аўт', 'Срд', 'Чцв', 'Пят', 'Суб'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be_BY@latin.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be_BY@latin.php new file mode 100644 index 0000000..517ce83 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/be_BY@latin.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['studzienia', 'lutaha', 'sakavika', 'krasavika', 'maja', 'červienia', 'lipienia', 'žniŭnia', 'vieraśnia', 'kastryčnika', 'listapada', 'śniežnia'], + 'months_short' => ['Stu', 'Lut', 'Sak', 'Kra', 'Maj', 'Čer', 'Lip', 'Žni', 'Vie', 'Kas', 'Lis', 'Śni'], + 'weekdays' => ['Niadziela', 'Paniadziełak', 'Aŭtorak', 'Sierada', 'Čaćvier', 'Piatnica', 'Subota'], + 'weekdays_short' => ['Nia', 'Pan', 'Aŭt', 'Sie', 'Čać', 'Pia', 'Sub'], + 'weekdays_min' => ['Nia', 'Pan', 'Aŭt', 'Sie', 'Čać', 'Pia', 'Sub'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bem.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bem.php new file mode 100644 index 0000000..1c3ef03 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bem.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/bem_ZM.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bem_ZM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bem_ZM.php new file mode 100644 index 0000000..620b579 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bem_ZM.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - ANLoc Martin Benjamin locales@africanlocalization.net + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'MM/DD/YYYY', + ], + 'months' => ['Januari', 'Februari', 'Machi', 'Epreo', 'Mei', 'Juni', 'Julai', 'Ogasti', 'Septemba', 'Oktoba', 'Novemba', 'Disemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Epr', 'Mei', 'Jun', 'Jul', 'Oga', 'Sep', 'Okt', 'Nov', 'Dis'], + 'weekdays' => ['Pa Mulungu', 'Palichimo', 'Palichibuli', 'Palichitatu', 'Palichine', 'Palichisano', 'Pachibelushi'], + 'weekdays_short' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + 'weekdays_min' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['uluchelo', 'akasuba'], + + 'year' => 'myaka :count', + 'y' => 'myaka :count', + 'a_year' => 'myaka :count', + + 'month' => 'myeshi :count', + 'm' => 'myeshi :count', + 'a_month' => 'myeshi :count', + + 'week' => 'umulungu :count', + 'w' => 'umulungu :count', + 'a_week' => 'umulungu :count', + + 'day' => 'inshiku :count', + 'd' => 'inshiku :count', + 'a_day' => 'inshiku :count', + + 'hour' => 'awala :count', + 'h' => 'awala :count', + 'a_hour' => 'awala :count', + + 'minute' => 'miniti :count', + 'min' => 'miniti :count', + 'a_minute' => 'miniti :count', + + 'second' => 'sekondi :count', + 's' => 'sekondi :count', + 'a_second' => 'sekondi :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber.php new file mode 100644 index 0000000..685603c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ber_DZ.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber_DZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber_DZ.php new file mode 100644 index 0000000..38de10a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber_DZ.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Pablo Saratxaga pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr'], + 'months_short' => ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek'], + 'weekdays' => ['bazar günü', 'birinci gün', 'ikinci gün', 'üçüncü gün', 'dördüncü gün', 'beşinci gün', 'altıncı gün'], + 'weekdays_short' => ['baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt'], + 'weekdays_min' => ['baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber_MA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber_MA.php new file mode 100644 index 0000000..38de10a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ber_MA.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Pablo Saratxaga pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr'], + 'months_short' => ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek'], + 'weekdays' => ['bazar günü', 'birinci gün', 'ikinci gün', 'üçüncü gün', 'dördüncü gün', 'beşinci gün', 'altıncı gün'], + 'weekdays_short' => ['baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt'], + 'weekdays_min' => ['baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bez.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bez.php new file mode 100644 index 0000000..d59c5ef --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bez.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['pamilau', 'pamunyi'], + 'weekdays' => ['pa mulungu', 'pa shahuviluha', 'pa hivili', 'pa hidatu', 'pa hitayi', 'pa hihanu', 'pa shahulembela'], + 'weekdays_short' => ['Mul', 'Vil', 'Hiv', 'Hid', 'Hit', 'Hih', 'Lem'], + 'weekdays_min' => ['Mul', 'Vil', 'Hiv', 'Hid', 'Hit', 'Hih', 'Lem'], + 'months' => ['pa mwedzi gwa hutala', 'pa mwedzi gwa wuvili', 'pa mwedzi gwa wudatu', 'pa mwedzi gwa wutai', 'pa mwedzi gwa wuhanu', 'pa mwedzi gwa sita', 'pa mwedzi gwa saba', 'pa mwedzi gwa nane', 'pa mwedzi gwa tisa', 'pa mwedzi gwa kumi', 'pa mwedzi gwa kumi na moja', 'pa mwedzi gwa kumi na mbili'], + 'months_short' => ['Hut', 'Vil', 'Dat', 'Tai', 'Han', 'Sit', 'Sab', 'Nan', 'Tis', 'Kum', 'Kmj', 'Kmb'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bg.php new file mode 100644 index 0000000..f768074 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bg.php @@ -0,0 +1,114 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - Serhan Apaydın + * - JD Isaacks + * - Glavić + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count година|:count години', + 'a_year' => 'година|:count години', + 'y' => ':count година|:count години', + 'month' => ':count месец|:count месеца', + 'a_month' => 'месец|:count месеца', + 'm' => ':count месец|:count месеца', + 'week' => ':count седмица|:count седмици', + 'a_week' => 'седмица|:count седмици', + 'w' => ':count седмица|:count седмици', + 'day' => ':count ден|:count дни', + 'a_day' => 'ден|:count дни', + 'd' => ':count ден|:count дни', + 'hour' => ':count час|:count часа', + 'a_hour' => 'час|:count часа', + 'h' => ':count час|:count часа', + 'minute' => ':count минута|:count минути', + 'a_minute' => 'минута|:count минути', + 'min' => ':count минута|:count минути', + 'second' => ':count секунда|:count секунди', + 'a_second' => 'няколко секунди|:count секунди', + 's' => ':count секунда|:count секунди', + 'ago' => 'преди :time', + 'from_now' => 'след :time', + 'after' => 'след :time', + 'before' => 'преди :time', + 'diff_now' => 'сега', + 'diff_today' => 'Днес', + 'diff_today_regexp' => 'Днес(?:\\s+в)?', + 'diff_yesterday' => 'вчера', + 'diff_yesterday_regexp' => 'Вчера(?:\\s+в)?', + 'diff_tomorrow' => 'утре', + 'diff_tomorrow_regexp' => 'Утре(?:\\s+в)?', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'D.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY H:mm', + 'LLLL' => 'dddd, D MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[Днес в] LT', + 'nextDay' => '[Утре в] LT', + 'nextWeek' => 'dddd [в] LT', + 'lastDay' => '[Вчера в] LT', + 'lastWeek' => function (CarbonInterface $current) { + switch ($current->dayOfWeek) { + case 0: + case 3: + case 6: + return '[В изминалата] dddd [в] LT'; + default: + return '[В изминалия] dddd [в] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + $lastDigit = $number % 10; + $last2Digits = $number % 100; + if ($number === 0) { + return "$number-ев"; + } + if ($last2Digits === 0) { + return "$number-ен"; + } + if ($last2Digits > 10 && $last2Digits < 20) { + return "$number-ти"; + } + if ($lastDigit === 1) { + return "$number-ви"; + } + if ($lastDigit === 2) { + return "$number-ри"; + } + if ($lastDigit === 7 || $lastDigit === 8) { + return "$number-ми"; + } + + return "$number-ти"; + }, + 'months' => ['януари', 'февруари', 'март', 'април', 'май', 'юни', 'юли', 'август', 'септември', 'октомври', 'ноември', 'декември'], + 'months_short' => ['яну', 'фев', 'мар', 'апр', 'май', 'юни', 'юли', 'авг', 'сеп', 'окт', 'ное', 'дек'], + 'weekdays' => ['неделя', 'понеделник', 'вторник', 'сряда', 'четвъртък', 'петък', 'събота'], + 'weekdays_short' => ['нед', 'пон', 'вто', 'сря', 'чет', 'пет', 'съб'], + 'weekdays_min' => ['нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' и '], + 'meridiem' => ['преди обяд', 'следобед'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bg_BG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bg_BG.php new file mode 100644 index 0000000..b53874d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bg_BG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/bg.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bhb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bhb.php new file mode 100644 index 0000000..49f0803 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bhb.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/bhb_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bhb_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bhb_IN.php new file mode 100644 index 0000000..ab557cb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bhb_IN.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Samsung Electronics Co., Ltd. alexey.merzlyakov@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + 'weekdays' => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + 'weekdays_short' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + 'weekdays_min' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bho.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bho.php new file mode 100644 index 0000000..e9ed0b6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bho.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/bho_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bho_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bho_IN.php new file mode 100644 index 0000000..bc54f36 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bho_IN.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bhashaghar@googlegroups.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर"'], + 'months_short' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर"'], + 'weekdays' => ['रविवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'गुरुवार', 'शुक्रवार', 'शनिवार'], + 'weekdays_short' => ['रवि', 'सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र', 'शनि'], + 'weekdays_min' => ['रवि', 'सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र', 'शनि'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], + + 'hour' => ':count मौसम', + 'h' => ':count मौसम', + 'a_hour' => ':count मौसम', + + 'minute' => ':count कला', + 'min' => ':count कला', + 'a_minute' => ':count कला', + + 'second' => ':count सोमार', + 's' => ':count सोमार', + 'a_second' => ':count सोमार', + + 'year' => ':count साल', + 'y' => ':count साल', + 'a_year' => ':count साल', + + 'month' => ':count महिना', + 'm' => ':count महिना', + 'a_month' => ':count महिना', + + 'week' => ':count सप्ताह', + 'w' => ':count सप्ताह', + 'a_week' => ':count सप्ताह', + + 'day' => ':count दिन', + 'd' => ':count दिन', + 'a_day' => ':count दिन', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bi.php new file mode 100644 index 0000000..dd08128 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bi.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/bi_VU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bi_VU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bi_VU.php new file mode 100644 index 0000000..1fe7770 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bi_VU.php @@ -0,0 +1,53 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Samsung Electronics Co., Ltd. akhilesh.k@samsung.com & maninder1.s@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'dddd DD MMM YYYY', + ], + 'months' => ['jenuware', 'febwari', 'maj', 'epril', 'mei', 'jun', 'julae', 'ogis', 'septemba', 'oktoba', 'novemba', 'disemba'], + 'months_short' => ['jen', 'feb', 'maj', 'epr', 'mei', 'jun', 'jul', 'ogi', 'sep', 'okt', 'nov', 'dis'], + 'weekdays' => ['sande', 'mande', 'maj', 'wota', 'fraede', 'sarede'], + 'weekdays_short' => ['san', 'man', 'maj', 'wot', 'fra', 'sar'], + 'weekdays_min' => ['san', 'man', 'maj', 'wot', 'fra', 'sar'], + + 'year' => ':count seven', // less reliable + 'y' => ':count seven', // less reliable + 'a_year' => ':count seven', // less reliable + + 'month' => ':count mi', // less reliable + 'm' => ':count mi', // less reliable + 'a_month' => ':count mi', // less reliable + + 'week' => ':count sarede', // less reliable + 'w' => ':count sarede', // less reliable + 'a_week' => ':count sarede', // less reliable + + 'day' => ':count betde', // less reliable + 'd' => ':count betde', // less reliable + 'a_day' => ':count betde', // less reliable + + 'hour' => ':count klok', // less reliable + 'h' => ':count klok', // less reliable + 'a_hour' => ':count klok', // less reliable + + 'minute' => ':count smol', // less reliable + 'min' => ':count smol', // less reliable + 'a_minute' => ':count smol', // less reliable + + 'second' => ':count tu', // less reliable + 's' => ':count tu', // less reliable + 'a_second' => ':count tu', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bm.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bm.php new file mode 100644 index 0000000..92822d2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bm.php @@ -0,0 +1,70 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Estelle Comment + */ +return [ + 'year' => 'san :count', + 'a_year' => '{1}san kelen|san :count', + 'y' => 'san :count', + 'month' => 'kalo :count', + 'a_month' => '{1}kalo kelen|kalo :count', + 'm' => 'k. :count', + 'week' => 'dɔgɔkun :count', + 'a_week' => 'dɔgɔkun kelen', + 'w' => 'd. :count', + 'day' => 'tile :count', + 'd' => 't. :count', + 'a_day' => '{1}tile kelen|tile :count', + 'hour' => 'lɛrɛ :count', + 'a_hour' => '{1}lɛrɛ kelen|lɛrɛ :count', + 'h' => 'l. :count', + 'minute' => 'miniti :count', + 'a_minute' => '{1}miniti kelen|miniti :count', + 'min' => 'm. :count', + 'second' => 'sekondi :count', + 'a_second' => '{1}sanga dama dama|sekondi :count', + 's' => 'sek. :count', + 'ago' => 'a bɛ :time bɔ', + 'from_now' => ':time kɔnɔ', + 'diff_today' => 'Bi', + 'diff_yesterday' => 'Kunu', + 'diff_yesterday_regexp' => 'Kunu(?:\\s+lɛrɛ)?', + 'diff_tomorrow' => 'Sini', + 'diff_tomorrow_regexp' => 'Sini(?:\\s+lɛrɛ)?', + 'diff_today_regexp' => 'Bi(?:\\s+lɛrɛ)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'MMMM [tile] D [san] YYYY', + 'LLL' => 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', + 'LLLL' => 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Bi lɛrɛ] LT', + 'nextDay' => '[Sini lɛrɛ] LT', + 'nextWeek' => 'dddd [don lɛrɛ] LT', + 'lastDay' => '[Kunu lɛrɛ] LT', + 'lastWeek' => 'dddd [tɛmɛnen lɛrɛ] LT', + 'sameElse' => 'L', + ], + 'months' => ['Zanwuyekalo', 'Fewuruyekalo', 'Marisikalo', 'Awirilikalo', 'Mɛkalo', 'Zuwɛnkalo', 'Zuluyekalo', 'Utikalo', 'Sɛtanburukalo', 'ɔkutɔburukalo', 'Nowanburukalo', 'Desanburukalo'], + 'months_short' => ['Zan', 'Few', 'Mar', 'Awi', 'Mɛ', 'Zuw', 'Zul', 'Uti', 'Sɛt', 'ɔku', 'Now', 'Des'], + 'weekdays' => ['Kari', 'Ntɛnɛn', 'Tarata', 'Araba', 'Alamisa', 'Juma', 'Sibiri'], + 'weekdays_short' => ['Kar', 'Ntɛ', 'Tar', 'Ara', 'Ala', 'Jum', 'Sib'], + 'weekdays_min' => ['Ka', 'Nt', 'Ta', 'Ar', 'Al', 'Ju', 'Si'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' ni '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn.php new file mode 100644 index 0000000..8e14789 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn.php @@ -0,0 +1,100 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Shakib Hossain + * - Raju + * - Aniruddha Adhikary + * - JD Isaacks + * - Saiful Islam + * - Faisal Islam + */ +return [ + 'year' => ':count বছর', + 'a_year' => 'এক বছর|:count বছর', + 'y' => '১ বছর|:count বছর', + 'month' => ':count মাস', + 'a_month' => 'এক মাস|:count মাস', + 'm' => '১ মাস|:count মাস', + 'week' => ':count সপ্তাহ', + 'a_week' => '১ সপ্তাহ|:count সপ্তাহ', + 'w' => '১ সপ্তাহ|:count সপ্তাহ', + 'day' => ':count দিন', + 'a_day' => 'এক দিন|:count দিন', + 'd' => '১ দিন|:count দিন', + 'hour' => ':count ঘন্টা', + 'a_hour' => 'এক ঘন্টা|:count ঘন্টা', + 'h' => '১ ঘন্টা|:count ঘন্টা', + 'minute' => ':count মিনিট', + 'a_minute' => 'এক মিনিট|:count মিনিট', + 'min' => '১ মিনিট|:count মিনিট', + 'second' => ':count সেকেন্ড', + 'a_second' => 'কয়েক সেকেন্ড|:count সেকেন্ড', + 's' => '১ সেকেন্ড|:count সেকেন্ড', + 'ago' => ':time আগে', + 'from_now' => ':time পরে', + 'after' => ':time পরে', + 'before' => ':time আগে', + 'diff_now' => 'এখন', + 'diff_today' => 'আজ', + 'diff_yesterday' => 'গতকাল', + 'diff_tomorrow' => 'আগামীকাল', + 'period_recurrences' => ':count বার|:count বার', + 'period_interval' => 'প্রতি :interval', + 'period_start_date' => ':date থেকে', + 'period_end_date' => ':date পর্যন্ত', + 'formats' => [ + 'LT' => 'A Oh:Om সময়', + 'LTS' => 'A Oh:Om:Os সময়', + 'L' => 'OD/OM/OY', + 'LL' => 'OD MMMM OY', + 'LLL' => 'OD MMMM OY, A Oh:Om সময়', + 'LLLL' => 'dddd, OD MMMM OY, A Oh:Om সময়', + ], + 'calendar' => [ + 'sameDay' => '[আজ] LT', + 'nextDay' => '[আগামীকাল] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[গতকাল] LT', + 'lastWeek' => '[গত] dddd, LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'রাত'; + } + if ($hour < 10) { + return 'সকাল'; + } + if ($hour < 17) { + return 'দুপুর'; + } + if ($hour < 20) { + return 'বিকাল'; + } + + return 'রাত'; + }, + 'months' => ['জানুয়ারী', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'], + 'months_short' => ['জানু', 'ফেব', 'মার্চ', 'এপ্র', 'মে', 'জুন', 'জুল', 'আগ', 'সেপ্ট', 'অক্টো', 'নভে', 'ডিসে'], + 'weekdays' => ['রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার'], + 'weekdays_short' => ['রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহস্পতি', 'শুক্র', 'শনি'], + 'weekdays_min' => ['রবি', 'সোম', 'মঙ্গ', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি'], + 'list' => [', ', ' এবং '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'weekdays_standalone' => ['রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহষ্পতিবার', 'শুক্রবার', 'শনিবার'], + 'weekdays_min_standalone' => ['রঃ', 'সোঃ', 'মঃ', 'বুঃ', 'বৃঃ', 'শুঃ', 'শনি'], + 'months_short_standalone' => ['জানুয়ারী', 'ফেব্রুয়ারী', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'], + 'alt_numbers' => ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn_BD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn_BD.php new file mode 100644 index 0000000..b5b28dd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn_BD.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ankur Group, Taneem Ahmed, Jamil Ahmed + */ +return array_replace_recursive(require __DIR__.'/bn.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['জানুয়ারী', 'ফেব্রুয়ারী', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'], + 'months_short' => ['জানু', 'ফেব', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'], + 'weekdays' => ['রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার'], + 'weekdays_short' => ['রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি'], + 'weekdays_min' => ['রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি'], + 'first_day_of_week' => 5, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn_IN.php new file mode 100644 index 0000000..8b3a50e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bn_IN.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/bn.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['জানুয়ারী', 'ফেব্রুয়ারী', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'], + 'months_short' => ['জানু', 'ফেব', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'], + 'weekdays' => ['রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার'], + 'weekdays_short' => ['রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহস্পতি', 'শুক্র', 'শনি'], + 'weekdays_min' => ['রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহস্পতি', 'শুক্র', 'শনি'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo.php new file mode 100644 index 0000000..99e1bf4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo.php @@ -0,0 +1,71 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - JD Isaacks + */ +return [ + 'year' => '{1}ལོ་གཅིག|]1,Inf[:count ལོ', + 'month' => '{1}ཟླ་བ་གཅིག|]1,Inf[:count ཟླ་བ', + 'week' => ':count བདུན་ཕྲག', + 'day' => '{1}ཉིན་གཅིག|]1,Inf[:count ཉིན་', + 'hour' => '{1}ཆུ་ཚོད་གཅིག|]1,Inf[:count ཆུ་ཚོད', + 'minute' => '{1}སྐར་མ་གཅིག|]1,Inf[:count སྐར་མ', + 'second' => '{1}ལམ་སང|]1,Inf[:count སྐར་ཆ།', + 'ago' => ':time སྔན་ལ', + 'from_now' => ':time ལ་', + 'diff_yesterday' => 'ཁ་སང', + 'diff_today' => 'དི་རིང', + 'diff_tomorrow' => 'སང་ཉིན', + 'formats' => [ + 'LT' => 'A h:mm', + 'LTS' => 'A h:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm', + ], + 'calendar' => [ + 'sameDay' => '[དི་རིང] LT', + 'nextDay' => '[སང་ཉིན] LT', + 'nextWeek' => '[བདུན་ཕྲག་རྗེས་མ], LT', + 'lastDay' => '[ཁ་སང] LT', + 'lastWeek' => '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'མཚན་མོ'; + } + if ($hour < 10) { + return 'ཞོགས་ཀས'; + } + if ($hour < 17) { + return 'ཉིན་གུང'; + } + if ($hour < 20) { + return 'དགོང་དག'; + } + + return 'མཚན་མོ'; + }, + 'months' => ['ཟླ་བ་དང་པོ', 'ཟླ་བ་གཉིས་པ', 'ཟླ་བ་གསུམ་པ', 'ཟླ་བ་བཞི་པ', 'ཟླ་བ་ལྔ་པ', 'ཟླ་བ་དྲུག་པ', 'ཟླ་བ་བདུན་པ', 'ཟླ་བ་བརྒྱད་པ', 'ཟླ་བ་དགུ་པ', 'ཟླ་བ་བཅུ་པ', 'ཟླ་བ་བཅུ་གཅིག་པ', 'ཟླ་བ་བཅུ་གཉིས་པ'], + 'months_short' => ['ཟླ་བ་དང་པོ', 'ཟླ་བ་གཉིས་པ', 'ཟླ་བ་གསུམ་པ', 'ཟླ་བ་བཞི་པ', 'ཟླ་བ་ལྔ་པ', 'ཟླ་བ་དྲུག་པ', 'ཟླ་བ་བདུན་པ', 'ཟླ་བ་བརྒྱད་པ', 'ཟླ་བ་དགུ་པ', 'ཟླ་བ་བཅུ་པ', 'ཟླ་བ་བཅུ་གཅིག་པ', 'ཟླ་བ་བཅུ་གཉིས་པ'], + 'weekdays' => ['གཟའ་ཉི་མ་', 'གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་པ་', 'གཟའ་ཕུར་བུ', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་པ་'], + 'weekdays_short' => ['ཉི་མ་', 'ཟླ་བ་', 'མིག་དམར་', 'ལྷག་པ་', 'ཕུར་བུ', 'པ་སངས་', 'སྤེན་པ་'], + 'weekdays_min' => ['ཉི་མ་', 'ཟླ་བ་', 'མིག་དམར་', 'ལྷག་པ་', 'ཕུར་བུ', 'པ་སངས་', 'སྤེན་པ་'], + 'list' => [', ', ' ཨནད་ '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'months_standalone' => ['ཟླ་བ་དང་པོ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་པ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུན་པ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo_CN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo_CN.php new file mode 100644 index 0000000..380abb1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo_CN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/bo.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo_IN.php new file mode 100644 index 0000000..ca50d04 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bo_IN.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/bo.php', [ + 'meridiem' => ['སྔ་དྲོ་', 'ཕྱི་དྲོ་'], + 'weekdays' => ['གཟའ་ཉི་མ་', 'གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་པ་', 'གཟའ་ཕུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་པ་'], + 'weekdays_short' => ['ཉི་མ་', 'ཟླ་བ་', 'མིག་དམར་', 'ལྷག་པ་', 'ཕུར་བུ་', 'པ་སངས་', 'སྤེན་པ་'], + 'weekdays_min' => ['ཉི་མ་', 'ཟླ་བ་', 'མིག་དམར་', 'ལྷག་པ་', 'ཕུར་བུ་', 'པ་སངས་', 'སྤེན་པ་'], + 'months' => ['ཟླ་བ་དང་པོ', 'ཟླ་བ་གཉིས་པ', 'ཟླ་བ་གསུམ་པ', 'ཟླ་བ་བཞི་པ', 'ཟླ་བ་ལྔ་པ', 'ཟླ་བ་དྲུག་པ', 'ཟླ་བ་བདུན་པ', 'ཟླ་བ་བརྒྱད་པ', 'ཟླ་བ་དགུ་པ', 'ཟླ་བ་བཅུ་པ', 'ཟླ་བ་བཅུ་གཅིག་པ', 'ཟླ་བ་བཅུ་གཉིས་པ'], + 'months_short' => ['ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢'], + 'months_standalone' => ['ཟླ་བ་དང་པོ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་པ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུན་པ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་'], + 'weekend' => [0, 0], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'YYYY-MM-DD', + 'LL' => 'YYYY ལོའི་MMMཚེས་D', + 'LLL' => 'སྤྱི་ལོ་YYYY MMMMའི་ཚེས་D h:mm a', + 'LLLL' => 'YYYY MMMMའི་ཚེས་D, dddd h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/br.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/br.php new file mode 100644 index 0000000..583472f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/br.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Serhan Apaydın + * - JD Isaacks + */ +return [ + 'year' => '{1}:count bloaz|{3,4,5,9}:count bloaz|[0,Inf[:count vloaz', + 'a_year' => '{1}ur bloaz|{3,4,5,9}:count bloaz|[0,Inf[:count vloaz', + 'month' => '{1}:count miz|{2}:count viz|[0,Inf[:count miz', + 'a_month' => '{1}ur miz|{2}:count viz|[0,Inf[:count miz', + 'week' => ':count sizhun', + 'a_week' => '{1}ur sizhun|:count sizhun', + 'day' => '{1}:count devezh|{2}:count zevezh|[0,Inf[:count devezh', + 'a_day' => '{1}un devezh|{2}:count zevezh|[0,Inf[:count devezh', + 'hour' => ':count eur', + 'a_hour' => '{1}un eur|:count eur', + 'minute' => '{1}:count vunutenn|{2}:count vunutenn|[0,Inf[:count munutenn', + 'a_minute' => '{1}ur vunutenn|{2}:count vunutenn|[0,Inf[:count munutenn', + 'second' => ':count eilenn', + 'a_second' => '{1}un nebeud segondennoù|[0,Inf[:count eilenn', + 'ago' => ':time \'zo', + 'from_now' => 'a-benn :time', + 'diff_now' => 'bremañ', + 'diff_today' => 'Hiziv', + 'diff_today_regexp' => 'Hiziv(?:\\s+da)?', + 'diff_yesterday' => 'decʼh', + 'diff_yesterday_regexp' => 'Dec\'h(?:\\s+da)?', + 'diff_tomorrow' => 'warcʼhoazh', + 'diff_tomorrow_regexp' => 'Warc\'hoazh(?:\\s+da)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D [a viz] MMMM YYYY', + 'LLL' => 'D [a viz] MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D [a viz] MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Hiziv da] LT', + 'nextDay' => '[Warc\'hoazh da] LT', + 'nextWeek' => 'dddd [da] LT', + 'lastDay' => '[Dec\'h da] LT', + 'lastWeek' => 'dddd [paset da] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + return $number.($number === 1 ? 'añ' : 'vet'); + }, + 'months' => ['Genver', 'C\'hwevrer', 'Meurzh', 'Ebrel', 'Mae', 'Mezheven', 'Gouere', 'Eost', 'Gwengolo', 'Here', 'Du', 'Kerzu'], + 'months_short' => ['Gen', 'C\'hwe', 'Meu', 'Ebr', 'Mae', 'Eve', 'Gou', 'Eos', 'Gwe', 'Her', 'Du', 'Ker'], + 'weekdays' => ['Sul', 'Lun', 'Meurzh', 'Merc\'her', 'Yaou', 'Gwener', 'Sadorn'], + 'weekdays_short' => ['Sul', 'Lun', 'Meu', 'Mer', 'Yao', 'Gwe', 'Sad'], + 'weekdays_min' => ['Su', 'Lu', 'Me', 'Mer', 'Ya', 'Gw', 'Sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' hag '], + 'meridiem' => ['A.M.', 'G.M.'], + + 'y' => ':count bl.', + 'd' => ':count d', + 'h' => ':count e', + 'min' => ':count min', + 's' => ':count s', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/br_FR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/br_FR.php new file mode 100644 index 0000000..7f54185 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/br_FR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/br.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/brx.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/brx.php new file mode 100644 index 0000000..a0a7bf9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/brx.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/brx_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/brx_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/brx_IN.php new file mode 100644 index 0000000..2d80ced --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/brx_IN.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'M/D/YY', + ], + 'months' => ['जानुवारी', 'फेब्रुवारी', 'मार्स', 'एफ्रिल', 'मे', 'जुन', 'जुलाइ', 'आगस्थ', 'सेबथेज्ब़र', 'अखथबर', 'नबेज्ब़र', 'दिसेज्ब़र'], + 'months_short' => ['जानुवारी', 'फेब्रुवारी', 'मार्स', 'एप्रिल', 'मे', 'जुन', 'जुलाइ', 'आगस्थ', 'सेबथेज्ब़र', 'अखथबर', 'नबेज्ब़र', 'दिसेज्ब़र'], + 'weekdays' => ['रबिबार', 'सोबार', 'मंगलबार', 'बुदबार', 'बिसथिबार', 'सुखुरबार', 'सुनिबार'], + 'weekdays_short' => ['रबि', 'सम', 'मंगल', 'बुद', 'बिसथि', 'सुखुर', 'सुनि'], + 'weekdays_min' => ['रबि', 'सम', 'मंगल', 'बुद', 'बिसथि', 'सुखुर', 'सुनि'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['फुं.', 'बेलासे.'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs.php new file mode 100644 index 0000000..e5d6808 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs.php @@ -0,0 +1,97 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bokideckonja + * - Josh Soref + * - François B + * - shaishavgandhi05 + * - Serhan Apaydın + * - JD Isaacks + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count godina|:count godine|:count godina', + 'y' => ':count godina|:count godine|:count godina', + 'month' => ':count mjesec|:count mjeseca|:count mjeseci', + 'm' => ':count mjesec|:count mjeseca|:count mjeseci', + 'week' => ':count sedmice|:count sedmicu|:count sedmica', + 'w' => ':count sedmice|:count sedmicu|:count sedmica', + 'day' => ':count dan|:count dana|:count dana', + 'd' => ':count dan|:count dana|:count dana', + 'hour' => ':count sat|:count sata|:count sati', + 'h' => ':count sat|:count sata|:count sati', + 'minute' => ':count minut|:count minuta|:count minuta', + 'min' => ':count minut|:count minuta|:count minuta', + 'second' => ':count sekund|:count sekunda|:count sekundi', + 's' => ':count sekund|:count sekunda|:count sekundi', + 'ago' => 'prije :time', + 'from_now' => 'za :time', + 'after' => 'nakon :time', + 'before' => ':time ranije', + 'diff_now' => 'sada', + 'diff_today' => 'danas', + 'diff_today_regexp' => 'danas(?:\\s+u)?', + 'diff_yesterday' => 'jučer', + 'diff_yesterday_regexp' => 'jučer(?:\\s+u)?', + 'diff_tomorrow' => 'sutra', + 'diff_tomorrow_regexp' => 'sutra(?:\\s+u)?', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY H:mm', + 'LLLL' => 'dddd, D. MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[danas u] LT', + 'nextDay' => '[sutra u] LT', + 'nextWeek' => function (CarbonInterface $current) { + switch ($current->dayOfWeek) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + default: + return '[u] dddd [u] LT'; + } + }, + 'lastDay' => '[jučer u] LT', + 'lastWeek' => function (CarbonInterface $current) { + switch ($current->dayOfWeek) { + case 0: + case 3: + return '[prošlu] dddd [u] LT'; + case 6: + return '[prošle] [subote] [u] LT'; + default: + return '[prošli] dddd [u] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['januar', 'februar', 'mart', 'april', 'maj', 'juni', 'juli', 'august', 'septembar', 'oktobar', 'novembar', 'decembar'], + 'months_short' => ['jan.', 'feb.', 'mar.', 'apr.', 'maj.', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'], + 'weekdays' => ['nedjelja', 'ponedjeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'], + 'weekdays_short' => ['ned.', 'pon.', 'uto.', 'sri.', 'čet.', 'pet.', 'sub.'], + 'weekdays_min' => ['ne', 'po', 'ut', 'sr', 'če', 'pe', 'su'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' i '], + 'meridiem' => ['prijepodne', 'popodne'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_BA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_BA.php new file mode 100644 index 0000000..0a59117 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_BA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/bs.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_Cyrl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_Cyrl.php new file mode 100644 index 0000000..e1a1744 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_Cyrl.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/bs.php', [ + 'meridiem' => ['пре подне', 'поподне'], + 'weekdays' => ['недјеља', 'понедјељак', 'уторак', 'сриједа', 'четвртак', 'петак', 'субота'], + 'weekdays_short' => ['нед', 'пон', 'уто', 'сри', 'чет', 'пет', 'суб'], + 'weekdays_min' => ['нед', 'пон', 'уто', 'сри', 'чет', 'пет', 'суб'], + 'months' => ['јануар', 'фебруар', 'март', 'април', 'мај', 'јуни', 'јули', 'аугуст', 'септембар', 'октобар', 'новембар', 'децембар'], + 'months_short' => ['јан', 'феб', 'мар', 'апр', 'мај', 'јун', 'јул', 'ауг', 'сеп', 'окт', 'нов', 'дец'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D.M.YYYY.', + 'LL' => 'DD.MM.YYYY.', + 'LLL' => 'DD. MMMM YYYY. HH:mm', + 'LLLL' => 'dddd, DD. MMMM YYYY. HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_Latn.php new file mode 100644 index 0000000..b4e363e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/bs_Latn.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/bs.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/byn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/byn.php new file mode 100644 index 0000000..7125f3d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/byn.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/byn_ER.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/byn_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/byn_ER.php new file mode 100644 index 0000000..ad67533 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/byn_ER.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ልደትሪ', 'ካብኽብቲ', 'ክብላ', 'ፋጅኺሪ', 'ክቢቅሪ', 'ምኪኤል ትጓ̅ኒሪ', 'ኰርኩ', 'ማርያም ትሪ', 'ያኸኒ መሳቅለሪ', 'መተሉ', 'ምኪኤል መሽወሪ', 'ተሕሳስሪ'], + 'months_short' => ['ልደት', 'ካብኽ', 'ክብላ', 'ፋጅኺ', 'ክቢቅ', 'ም/ት', 'ኰር', 'ማርያ', 'ያኸኒ', 'መተሉ', 'ም/ም', 'ተሕሳ'], + 'weekdays' => ['ሰንበር ቅዳዅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ ወሪ ለብዋ', 'ኣምድ', 'ኣርብ', 'ሰንበር ሽጓዅ'], + 'weekdays_short' => ['ሰ/ቅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ', 'ኣምድ', 'ኣርብ', 'ሰ/ሽ'], + 'weekdays_min' => ['ሰ/ቅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ', 'ኣምድ', 'ኣርብ', 'ሰ/ሽ'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ፋዱስ ጃብ', 'ፋዱስ ደምቢ'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca.php new file mode 100644 index 0000000..b8b1994 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca.php @@ -0,0 +1,117 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - mestremuten + * - François B + * - Marc Ordinas i Llopis + * - Pere Orga + * - JD Isaacks + * - Quentí + * - Víctor Díaz + * - Xavi + * - qcardona + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count any|:count anys', + 'a_year' => 'un any|:count anys', + 'y' => ':count any|:count anys', + 'month' => ':count mes|:count mesos', + 'a_month' => 'un mes|:count mesos', + 'm' => ':count mes|:count mesos', + 'week' => ':count setmana|:count setmanes', + 'a_week' => 'una setmana|:count setmanes', + 'w' => ':count setmana|:count setmanes', + 'day' => ':count dia|:count dies', + 'a_day' => 'un dia|:count dies', + 'd' => ':count d', + 'hour' => ':count hora|:count hores', + 'a_hour' => 'una hora|:count hores', + 'h' => ':count h', + 'minute' => ':count minut|:count minuts', + 'a_minute' => 'un minut|:count minuts', + 'min' => ':count min', + 'second' => ':count segon|:count segons', + 'a_second' => 'uns segons|:count segons', + 's' => ':count s', + 'ago' => 'fa :time', + 'from_now' => 'd\'aquí a :time', + 'after' => ':time després', + 'before' => ':time abans', + 'diff_now' => 'ara mateix', + 'diff_today' => 'avui', + 'diff_today_regexp' => 'avui(?:\\s+a)?(?:\\s+les)?', + 'diff_yesterday' => 'ahir', + 'diff_yesterday_regexp' => 'ahir(?:\\s+a)?(?:\\s+les)?', + 'diff_tomorrow' => 'demà', + 'diff_tomorrow_regexp' => 'demà(?:\\s+a)?(?:\\s+les)?', + 'diff_before_yesterday' => 'abans d\'ahir', + 'diff_after_tomorrow' => 'demà passat', + 'period_recurrences' => ':count cop|:count cops', + 'period_interval' => 'cada :interval', + 'period_start_date' => 'de :date', + 'period_end_date' => 'fins a :date', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM [de] YYYY', + 'LLL' => 'D MMMM [de] YYYY [a les] H:mm', + 'LLLL' => 'dddd D MMMM [de] YYYY [a les] H:mm', + ], + 'calendar' => [ + 'sameDay' => function (CarbonInterface $current) { + return '[avui a '.($current->hour !== 1 ? 'les' : 'la').'] LT'; + }, + 'nextDay' => function (CarbonInterface $current) { + return '[demà a '.($current->hour !== 1 ? 'les' : 'la').'] LT'; + }, + 'nextWeek' => function (CarbonInterface $current) { + return 'dddd [a '.($current->hour !== 1 ? 'les' : 'la').'] LT'; + }, + 'lastDay' => function (CarbonInterface $current) { + return '[ahir a '.($current->hour !== 1 ? 'les' : 'la').'] LT'; + }, + 'lastWeek' => function (CarbonInterface $current) { + return '[el] dddd [passat a '.($current->hour !== 1 ? 'les' : 'la').'] LT'; + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + return $number.( + ($period === 'w' || $period === 'W') ? 'a' : ( + ($number === 1) ? 'r' : ( + ($number === 2) ? 'n' : ( + ($number === 3) ? 'r' : ( + ($number === 4) ? 't' : 'è' + ) + ) + ) + ) + ); + }, + 'months' => ['de gener', 'de febrer', 'de març', 'd\'abril', 'de maig', 'de juny', 'de juliol', 'd\'agost', 'de setembre', 'd\'octubre', 'de novembre', 'de desembre'], + 'months_standalone' => ['gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre'], + 'months_short' => ['de gen.', 'de febr.', 'de març', 'd\'abr.', 'de maig', 'de juny', 'de jul.', 'd\'ag.', 'de set.', 'd\'oct.', 'de nov.', 'de des.'], + 'months_short_standalone' => ['gen.', 'febr.', 'març', 'abr.', 'maig', 'juny', 'jul.', 'ag.', 'set.', 'oct.', 'nov.', 'des.'], + 'months_regexp' => '/(D[oD]?[\s,]+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte'], + 'weekdays_short' => ['dg.', 'dl.', 'dt.', 'dc.', 'dj.', 'dv.', 'ds.'], + 'weekdays_min' => ['dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' i '], + 'meridiem' => ['a. m.', 'p. m.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_AD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_AD.php new file mode 100644 index 0000000..861acd2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_AD.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ca.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES.php new file mode 100644 index 0000000..5004978 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ca.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php new file mode 100644 index 0000000..1c16421 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php @@ -0,0 +1,23 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'ca'); + }, 'ca_ES_Valencia'); +} +// @codeCoverageIgnoreEnd + +return array_replace_recursive(require __DIR__.'/ca.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_FR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_FR.php new file mode 100644 index 0000000..861acd2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_FR.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ca.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_IT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_IT.php new file mode 100644 index 0000000..861acd2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ca_IT.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ca.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ccp.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ccp.php new file mode 100644 index 0000000..99c1dca --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ccp.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['𑄢𑄧𑄝𑄨𑄝𑄢𑄴', '𑄥𑄧𑄟𑄴𑄝𑄢𑄴', '𑄟𑄧𑄁𑄉𑄧𑄣𑄴𑄝𑄢𑄴', '𑄝𑄪𑄖𑄴𑄝𑄢𑄴', '𑄝𑄳𑄢𑄨𑄥𑄪𑄛𑄴𑄝𑄢𑄴', '𑄥𑄪𑄇𑄴𑄇𑄮𑄢𑄴𑄝𑄢𑄴', '𑄥𑄧𑄚𑄨𑄝𑄢𑄴'], + 'weekdays_short' => ['𑄢𑄧𑄝𑄨', '𑄥𑄧𑄟𑄴', '𑄟𑄧𑄁𑄉𑄧𑄣𑄴', '𑄝𑄪𑄖𑄴', '𑄝𑄳𑄢𑄨𑄥𑄪𑄛𑄴', '𑄥𑄪𑄇𑄴𑄇𑄮𑄢𑄴', '𑄥𑄧𑄚𑄨'], + 'weekdays_min' => ['𑄢𑄧𑄝𑄨', '𑄥𑄧𑄟𑄴', '𑄟𑄧𑄁𑄉𑄧𑄣𑄴', '𑄝𑄪𑄖𑄴', '𑄝𑄳𑄢𑄨𑄥𑄪𑄛𑄴', '𑄥𑄪𑄇𑄴𑄇𑄮𑄢𑄴', '𑄥𑄧𑄚𑄨'], + 'months' => ['𑄎𑄚𑄪𑄠𑄢𑄨', '𑄜𑄬𑄛𑄴𑄝𑄳𑄢𑄪𑄠𑄢𑄨', '𑄟𑄢𑄴𑄌𑄧', '𑄃𑄬𑄛𑄳𑄢𑄨𑄣𑄴', '𑄟𑄬', '𑄎𑄪𑄚𑄴', '𑄎𑄪𑄣𑄭', '𑄃𑄉𑄧𑄌𑄴𑄑𑄴', '𑄥𑄬𑄛𑄴𑄑𑄬𑄟𑄴𑄝𑄧𑄢𑄴', '𑄃𑄧𑄇𑄴𑄑𑄬𑄝𑄧𑄢𑄴', '𑄚𑄧𑄞𑄬𑄟𑄴𑄝𑄧𑄢𑄴', '𑄓𑄨𑄥𑄬𑄟𑄴𑄝𑄧𑄢𑄴'], + 'months_short' => ['𑄎𑄚𑄪', '𑄜𑄬𑄛𑄴', '𑄟𑄢𑄴𑄌𑄧', '𑄃𑄬𑄛𑄳𑄢𑄨𑄣𑄴', '𑄟𑄬', '𑄎𑄪𑄚𑄴', '𑄎𑄪𑄣𑄭', '𑄃𑄉𑄧𑄌𑄴𑄑𑄴', '𑄥𑄬𑄛𑄴𑄑𑄬𑄟𑄴𑄝𑄧𑄢𑄴', '𑄃𑄧𑄇𑄴𑄑𑄮𑄝𑄧𑄢𑄴', '𑄚𑄧𑄞𑄬𑄟𑄴𑄝𑄧𑄢𑄴', '𑄓𑄨𑄥𑄬𑄟𑄴𑄝𑄢𑄴'], + 'months_short_standalone' => ['𑄎𑄚𑄪𑄠𑄢𑄨', '𑄜𑄬𑄛𑄴𑄝𑄳𑄢𑄪𑄠𑄢𑄨', '𑄟𑄢𑄴𑄌𑄧', '𑄃𑄬𑄛𑄳𑄢𑄨𑄣𑄴', '𑄟𑄬', '𑄎𑄪𑄚𑄴', '𑄎𑄪𑄣𑄭', '𑄃𑄉𑄧𑄌𑄴𑄑𑄴', '𑄥𑄬𑄛𑄴𑄑𑄬𑄟𑄴𑄝𑄧𑄢𑄴', '𑄃𑄧𑄇𑄴𑄑𑄮𑄝𑄧𑄢𑄴', '𑄚𑄧𑄞𑄬𑄟𑄴𑄝𑄧𑄢𑄴', '𑄓𑄨𑄥𑄬𑄟𑄴𑄝𑄧𑄢𑄴'], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM, YYYY h:mm a', + 'LLLL' => 'dddd, D MMMM, YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ccp_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ccp_IN.php new file mode 100644 index 0000000..c1fa8af --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ccp_IN.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ccp.php', [ + 'weekend' => [0, 0], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ce.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ce.php new file mode 100644 index 0000000..f99f6ff --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ce.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ce_RU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ce_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ce_RU.php new file mode 100644 index 0000000..f769856 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ce_RU.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - ANCHR + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY.DD.MM', + ], + 'months' => ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'], + 'months_short' => ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'weekdays' => ['КӀиранан де', 'Оршотан де', 'Шинарин де', 'Кхаарин де', 'Еарин де', 'ПӀераскан де', 'Шот де'], + 'weekdays_short' => ['КӀ', 'Ор', 'Ши', 'Кх', 'Еа', 'ПӀ', 'Шо'], + 'weekdays_min' => ['КӀ', 'Ор', 'Ши', 'Кх', 'Еа', 'ПӀ', 'Шо'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => ':count шо', + 'y' => ':count шо', + 'a_year' => ':count шо', + + 'month' => ':count бутт', + 'm' => ':count бутт', + 'a_month' => ':count бутт', + + 'week' => ':count кӏира', + 'w' => ':count кӏира', + 'a_week' => ':count кӏира', + + 'day' => ':count де', + 'd' => ':count де', + 'a_day' => ':count де', + + 'hour' => ':count сахьт', + 'h' => ':count сахьт', + 'a_hour' => ':count сахьт', + + 'minute' => ':count минот', + 'min' => ':count минот', + 'a_minute' => ':count минот', + + 'second' => ':count секунд', + 's' => ':count секунд', + 'a_second' => ':count секунд', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cgg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cgg.php new file mode 100644 index 0000000..09bcc1c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cgg.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Sande', 'Orwokubanza', 'Orwakabiri', 'Orwakashatu', 'Orwakana', 'Orwakataano', 'Orwamukaaga'], + 'weekdays_short' => ['SAN', 'ORK', 'OKB', 'OKS', 'OKN', 'OKT', 'OMK'], + 'weekdays_min' => ['SAN', 'ORK', 'OKB', 'OKS', 'OKN', 'OKT', 'OMK'], + 'months' => ['Okwokubanza', 'Okwakabiri', 'Okwakashatu', 'Okwakana', 'Okwakataana', 'Okwamukaaga', 'Okwamushanju', 'Okwamunaana', 'Okwamwenda', 'Okwaikumi', 'Okwaikumi na kumwe', 'Okwaikumi na ibiri'], + 'months_short' => ['KBZ', 'KBR', 'KST', 'KKN', 'KTN', 'KMK', 'KMS', 'KMN', 'KMW', 'KKM', 'KNK', 'KNB'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'day' => ':count ruhanga', // less reliable + 'd' => ':count ruhanga', // less reliable + 'a_day' => ':count ruhanga', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/chr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/chr.php new file mode 100644 index 0000000..e26190f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/chr.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/chr_US.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/chr_US.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/chr_US.php new file mode 100644 index 0000000..371353e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/chr_US.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Cherokee Nation Joseph Erb josepherb7@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'MM/DD/YYYY', + ], + 'months' => ['ᎤᏃᎸᏔᏅ', 'ᎧᎦᎵ', 'ᎠᏅᏱ', 'ᎧᏬᏂ', 'ᎠᏂᏍᎬᏘ', 'ᏕᎭᎷᏱ', 'ᎫᏰᏉᏂ', 'ᎦᎶᏂ', 'ᏚᎵᏍᏗ', 'ᏚᏂᏅᏗ', 'ᏅᏓᏕᏆ', 'ᎥᏍᎩᏱ'], + 'months_short' => ['ᎤᏃ', 'ᎧᎦ', 'ᎠᏅ', 'ᎧᏬ', 'ᎠᏂ', 'ᏕᎭ', 'ᎫᏰ', 'ᎦᎶ', 'ᏚᎵ', 'ᏚᏂ', 'ᏅᏓ', 'ᎥᏍ'], + 'weekdays' => ['ᎤᎾᏙᏓᏆᏍᎬ', 'ᎤᎾᏙᏓᏉᏅᎯ', 'ᏔᎵᏁᎢᎦ', 'ᏦᎢᏁᎢᎦ', 'ᏅᎩᏁᎢᎦ', 'ᏧᎾᎩᎶᏍᏗ', 'ᎤᎾᏙᏓᏈᏕᎾ'], + 'weekdays_short' => ['ᏆᏍᎬ', 'ᏉᏅᎯ', 'ᏔᎵᏁ', 'ᏦᎢᏁ', 'ᏅᎩᏁ', 'ᏧᎾᎩ', 'ᏈᏕᎾ'], + 'weekdays_min' => ['ᏆᏍᎬ', 'ᏉᏅᎯ', 'ᏔᎵᏁ', 'ᏦᎢᏁ', 'ᏅᎩᏁ', 'ᏧᎾᎩ', 'ᏈᏕᎾ'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ᏌᎾᎴ', 'ᏒᎯᏱᎢᏗᏢ', 'ꮜꮎꮄ', 'ꮢꭿᏹꭲꮧꮲ'], + + 'second' => ':count ᏐᎢ', // less reliable + 's' => ':count ᏐᎢ', // less reliable + 'a_second' => ':count ᏐᎢ', // less reliable + + 'year' => ':count ᏑᏕᏘᏴᏓ', + 'y' => ':count ᏑᏕᏘᏴᏓ', + 'a_year' => ':count ᏑᏕᏘᏴᏓ', + + 'month' => ':count ᏏᏅᏙ', + 'm' => ':count ᏏᏅᏙ', + 'a_month' => ':count ᏏᏅᏙ', + + 'week' => ':count ᏑᎾᏙᏓᏆᏍᏗ', + 'w' => ':count ᏑᎾᏙᏓᏆᏍᏗ', + 'a_week' => ':count ᏑᎾᏙᏓᏆᏍᏗ', + + 'day' => ':count ᎢᎦ', + 'd' => ':count ᎢᎦ', + 'a_day' => ':count ᎢᎦ', + + 'hour' => ':count ᏑᏟᎶᏛ', + 'h' => ':count ᏑᏟᎶᏛ', + 'a_hour' => ':count ᏑᏟᎶᏛ', + + 'minute' => ':count ᎢᏯᏔᏬᏍᏔᏅ', + 'min' => ':count ᎢᏯᏔᏬᏍᏔᏅ', + 'a_minute' => ':count ᎢᏯᏔᏬᏍᏔᏅ', + + 'ago' => ':time ᏥᎨᏒ', + 'from_now' => 'ᎾᎿ :time', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ckb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ckb.php new file mode 100644 index 0000000..acf4dc2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ckb.php @@ -0,0 +1,89 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Swara Mohammed + */ +$months = [ + 'ڕێبەندان', + 'ڕەشەمە', + 'نەورۆز', + 'گوڵان', + 'جۆزەردان', + 'پوشپەڕ', + 'گەلاوێژ', + 'خەرمانان', + 'ڕەزبەر', + 'گەڵاڕێزان', + 'سەرماوەرز', + 'بەفرانبار', +]; + +return [ + 'year' => implode('|', ['{0}:count ساڵێک', '{1}ساڵێک', '{2}دوو ساڵ', ']2,11[:count ساڵ', ']10,Inf[:count ساڵ']), + 'a_year' => implode('|', ['{0}:count ساڵێک', '{1}ساڵێک', '{2}دوو ساڵ', ']2,11[:count ساڵ', ']10,Inf[:count ساڵ']), + 'month' => implode('|', ['{0}:count مانگێک', '{1}مانگێک', '{2}دوو مانگ', ']2,11[:count مانگ', ']10,Inf[:count مانگ']), + 'a_month' => implode('|', ['{0}:count مانگێک', '{1}مانگێک', '{2}دوو مانگ', ']2,11[:count مانگ', ']10,Inf[:count مانگ']), + 'week' => implode('|', ['{0}:count هەفتەیەک', '{1}هەفتەیەک', '{2}دوو هەفتە', ']2,11[:count هەفتە', ']10,Inf[:count هەفتە']), + 'a_week' => implode('|', ['{0}:count هەفتەیەک', '{1}هەفتەیەک', '{2}دوو هەفتە', ']2,11[:count هەفتە', ']10,Inf[:count هەفتە']), + 'day' => implode('|', ['{0}:count ڕۆژێک', '{1}ڕۆژێک', '{2}دوو ڕۆژ', ']2,11[:count ڕۆژ', ']10,Inf[:count ڕۆژ']), + 'a_day' => implode('|', ['{0}:count ڕۆژێک', '{1}ڕۆژێک', '{2}دوو ڕۆژ', ']2,11[:count ڕۆژ', ']10,Inf[:count ڕۆژ']), + 'hour' => implode('|', ['{0}:count کاتژمێرێک', '{1}کاتژمێرێک', '{2}دوو کاتژمێر', ']2,11[:count کاتژمێر', ']10,Inf[:count کاتژمێر']), + 'a_hour' => implode('|', ['{0}:count کاتژمێرێک', '{1}کاتژمێرێک', '{2}دوو کاتژمێر', ']2,11[:count کاتژمێر', ']10,Inf[:count کاتژمێر']), + 'minute' => implode('|', ['{0}:count خولەکێک', '{1}خولەکێک', '{2}دوو خولەک', ']2,11[:count خولەک', ']10,Inf[:count خولەک']), + 'a_minute' => implode('|', ['{0}:count خولەکێک', '{1}خولەکێک', '{2}دوو خولەک', ']2,11[:count خولەک', ']10,Inf[:count خولەک']), + 'second' => implode('|', ['{0}:count چرکەیەک', '{1}چرکەیەک', '{2}دوو چرکە', ']2,11[:count چرکە', ']10,Inf[:count چرکە']), + 'a_second' => implode('|', ['{0}:count چرکەیەک', '{1}چرکەیەک', '{2}دوو چرکە', ']2,11[:count چرکە', ']10,Inf[:count چرکە']), + 'ago' => 'پێش :time', + 'from_now' => ':time لە ئێستاوە', + 'after' => 'دوای :time', + 'before' => 'پێش :time', + 'diff_now' => 'ئێستا', + 'diff_today' => 'ئەمڕۆ', + 'diff_today_regexp' => 'ڕۆژ(?:\\s+لە)?(?:\\s+کاتژمێر)?', + 'diff_yesterday' => 'دوێنێ', + 'diff_yesterday_regexp' => 'دوێنێ(?:\\s+لە)?(?:\\s+کاتژمێر)?', + 'diff_tomorrow' => 'سبەینێ', + 'diff_tomorrow_regexp' => 'سبەینێ(?:\\s+لە)?(?:\\s+کاتژمێر)?', + 'diff_before_yesterday' => 'پێش دوێنێ', + 'diff_after_tomorrow' => 'دوای سبەینێ', + 'period_recurrences' => implode('|', ['{0}جار', '{1}جار', '{2}:count دووجار', ']2,11[:count جار', ']10,Inf[:count جار']), + 'period_interval' => 'هەموو :interval', + 'period_start_date' => 'لە :date', + 'period_end_date' => 'بۆ :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'هەینی', 'شەممە'], + 'weekdays_short' => ['یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'هەینی', 'شەممە'], + 'weekdays_min' => ['یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'هەینی', 'شەممە'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[ئەمڕۆ لە کاتژمێر] LT', + 'nextDay' => '[سبەینێ لە کاتژمێر] LT', + 'nextWeek' => 'dddd [لە کاتژمێر] LT', + 'lastDay' => '[دوێنێ لە کاتژمێر] LT', + 'lastWeek' => 'dddd [لە کاتژمێر] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['پ.ن', 'د.ن'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cmn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cmn.php new file mode 100644 index 0000000..80b1d69 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cmn.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/cmn_TW.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cmn_TW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cmn_TW.php new file mode 100644 index 0000000..7e43f9d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cmn_TW.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY年MM月DD號', + ], + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => [' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月'], + 'weekdays' => ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], + 'weekdays_short' => ['日', '一', '二', '三', '四', '五', '六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'meridiem' => ['上午', '下午'], + + 'year' => ':count 年', + 'y' => ':count 年', + 'a_year' => ':count 年', + + 'month' => ':count 月', + 'm' => ':count 月', + 'a_month' => ':count 月', + + 'week' => ':count 周', + 'w' => ':count 周', + 'a_week' => ':count 周', + + 'day' => ':count 白天', + 'd' => ':count 白天', + 'a_day' => ':count 白天', + + 'hour' => ':count 小时', + 'h' => ':count 小时', + 'a_hour' => ':count 小时', + + 'minute' => ':count 分钟', + 'min' => ':count 分钟', + 'a_minute' => ':count 分钟', + + 'second' => ':count 秒', + 's' => ':count 秒', + 'a_second' => ':count 秒', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/crh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/crh.php new file mode 100644 index 0000000..a1d7ce6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/crh.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/crh_UA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/crh_UA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/crh_UA.php new file mode 100644 index 0000000..0513933 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/crh_UA.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Reşat SABIQ tilde.birlik@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'Mayıs', 'İyun', 'İyul', 'Avgust', 'Sentâbr', 'Oktâbr', 'Noyabr', 'Dekabr'], + 'months_short' => ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avg', 'Sen', 'Okt', 'Noy', 'Dek'], + 'weekdays' => ['Bazar', 'Bazarertesi', 'Salı', 'Çarşembe', 'Cumaaqşamı', 'Cuma', 'Cumaertesi'], + 'weekdays_short' => ['Baz', 'Ber', 'Sal', 'Çar', 'Caq', 'Cum', 'Cer'], + 'weekdays_min' => ['Baz', 'Ber', 'Sal', 'Çar', 'Caq', 'Cum', 'Cer'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ÜE', 'ÜS'], + + 'year' => ':count yıl', + 'y' => ':count yıl', + 'a_year' => ':count yıl', + + 'month' => ':count ay', + 'm' => ':count ay', + 'a_month' => ':count ay', + + 'week' => ':count afta', + 'w' => ':count afta', + 'a_week' => ':count afta', + + 'day' => ':count kün', + 'd' => ':count kün', + 'a_day' => ':count kün', + + 'hour' => ':count saat', + 'h' => ':count saat', + 'a_hour' => ':count saat', + + 'minute' => ':count daqqa', + 'min' => ':count daqqa', + 'a_minute' => ':count daqqa', + + 'second' => ':count ekinci', + 's' => ':count ekinci', + 'a_second' => ':count ekinci', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cs.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cs.php new file mode 100644 index 0000000..c01e3cc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cs.php @@ -0,0 +1,123 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Jakub Tesinsky + * - Martin Suja + * - Nikos Timiopulos + * - Bohuslav Blín + * - Tsutomu Kuroda + * - tjku + * - Lukas Svoboda + * - Max Melentiev + * - Juanito Fatas + * - Akira Matsuda + * - Christopher Dell + * - Václav Pávek + * - CodeSkills + * - Tlapi + * - newman101 + * - Petr Kadlec + * - tommaskraus + * - Karel Sommer (calvera) + */ +$za = function ($time) { + return 'za '.strtr($time, [ + 'hodina' => 'hodinu', + 'minuta' => 'minutu', + 'sekunda' => 'sekundu', + ]); +}; + +$pred = function ($time) { + $time = strtr($time, [ + 'hodina' => 'hodinou', + 'minuta' => 'minutou', + 'sekunda' => 'sekundou', + ]); + $time = preg_replace('/hodiny?(?!\w)/', 'hodinami', $time); + $time = preg_replace('/minuty?(?!\w)/', 'minutami', $time); + $time = preg_replace('/sekundy?(?!\w)/', 'sekundami', $time); + + return "před $time"; +}; + +return [ + 'year' => ':count rok|:count roky|:count let', + 'y' => ':count rok|:count roky|:count let', + 'a_year' => 'rok|:count roky|:count let', + 'month' => ':count měsíc|:count měsíce|:count měsíců', + 'm' => ':count měs.', + 'a_month' => 'měsíc|:count měsíce|:count měsíců', + 'week' => ':count týden|:count týdny|:count týdnů', + 'w' => ':count týd.', + 'a_week' => 'týden|:count týdny|:count týdnů', + 'day' => ':count den|:count dny|:count dní', + 'd' => ':count den|:count dny|:count dní', + 'a_day' => 'den|:count dny|:count dní', + 'hour' => ':count hodina|:count hodiny|:count hodin', + 'h' => ':count hod.', + 'a_hour' => 'hodina|:count hodiny|:count hodin', + 'minute' => ':count minuta|:count minuty|:count minut', + 'min' => ':count min.', + 'a_minute' => 'minuta|:count minuty|:count minut', + 'second' => ':count sekunda|:count sekundy|:count sekund', + 's' => ':count sek.', + 'a_second' => 'pár sekund|:count sekundy|:count sekund', + + 'month_ago' => ':count měsícem|:count měsíci|:count měsíci', + 'a_month_ago' => 'měsícem|:count měsíci|:count měsíci', + 'day_ago' => ':count dnem|:count dny|:count dny', + 'a_day_ago' => 'dnem|:count dny|:count dny', + 'week_ago' => ':count týdnem|:count týdny|:count týdny', + 'a_week_ago' => 'týdnem|:count týdny|:count týdny', + 'year_ago' => ':count rokem|:count roky|:count lety', + 'y_ago' => ':count rok.|:count rok.|:count let.', + 'a_year_ago' => 'rokem|:count roky|:count lety', + + 'month_before' => ':count měsícem|:count měsíci|:count měsíci', + 'a_month_before' => 'měsícem|:count měsíci|:count měsíci', + 'day_before' => ':count dnem|:count dny|:count dny', + 'a_day_before' => 'dnem|:count dny|:count dny', + 'week_before' => ':count týdnem|:count týdny|:count týdny', + 'a_week_before' => 'týdnem|:count týdny|:count týdny', + 'year_before' => ':count rokem|:count roky|:count lety', + 'y_before' => ':count rok.|:count rok.|:count let.', + 'a_year_before' => 'rokem|:count roky|:count lety', + + 'ago' => $pred, + 'from_now' => $za, + 'before' => $pred, + 'after' => $za, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'months' => ['ledna', 'února', 'března', 'dubna', 'května', 'června', 'července', 'srpna', 'září', 'října', 'listopadu', 'prosince'], + 'months_standalone' => ['leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec'], + 'months_short' => ['led', 'úno', 'bře', 'dub', 'kvě', 'čvn', 'čvc', 'srp', 'zář', 'říj', 'lis', 'pro'], + 'weekdays' => ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'], + 'weekdays_short' => ['ned', 'pon', 'úte', 'stř', 'čtv', 'pát', 'sob'], + 'weekdays_min' => ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'], + 'list' => [', ', ' a '], + 'diff_now' => 'nyní', + 'diff_yesterday' => 'včera', + 'diff_tomorrow' => 'zítra', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD. MM. YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd D. MMMM YYYY HH:mm', + ], + 'meridiem' => ['dopoledne', 'odpoledne'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cs_CZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cs_CZ.php new file mode 100644 index 0000000..ea2517e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cs_CZ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/cs.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/csb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/csb.php new file mode 100644 index 0000000..a35d281 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/csb.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/csb_PL.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/csb_PL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/csb_PL.php new file mode 100644 index 0000000..25e0ca8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/csb_PL.php @@ -0,0 +1,41 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - csb_PL locale Michal Ostrowski bug-glibc-locales@gnu.org + */ +return [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'MMMM DD, YYYY', + 'LLL' => 'DD MMM HH:mm', + 'LLLL' => 'MMMM DD, YYYY HH:mm', + ], + 'months' => ['stëcznika', 'gromicznika', 'strëmiannika', 'łżëkwiata', 'maja', 'czerwińca', 'lëpińca', 'zélnika', 'séwnika', 'rujana', 'lëstopadnika', 'gòdnika'], + 'months_short' => ['stë', 'gro', 'str', 'łżë', 'maj', 'cze', 'lëp', 'zél', 'séw', 'ruj', 'lës', 'gòd'], + 'weekdays' => ['niedzela', 'pòniedzôłk', 'wtórk', 'strzoda', 'czwiôrtk', 'piątk', 'sobòta'], + 'weekdays_short' => ['nie', 'pòn', 'wtó', 'str', 'czw', 'pią', 'sob'], + 'weekdays_min' => ['nie', 'pòn', 'wtó', 'str', 'czw', 'pią', 'sob'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' a téż '], + 'two_words_connector' => ' a téż ', + 'year' => ':count rok', + 'month' => ':count miesiąc', + 'week' => ':count tidzéń', + 'day' => ':count dzéń', + 'hour' => ':count gòdzëna', + 'minute' => ':count minuta', + 'second' => ':count sekunda', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cu.php new file mode 100644 index 0000000..d6d1312 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cu.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'months' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], + 'months_short' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'YYYY MMMM D, dddd HH:mm', + ], + + 'year' => ':count лѣто', + 'y' => ':count лѣто', + 'a_year' => ':count лѣто', + + 'month' => ':count мѣсѧць', + 'm' => ':count мѣсѧць', + 'a_month' => ':count мѣсѧць', + + 'week' => ':count сєдмица', + 'w' => ':count сєдмица', + 'a_week' => ':count сєдмица', + + 'day' => ':count дьнь', + 'd' => ':count дьнь', + 'a_day' => ':count дьнь', + + 'hour' => ':count година', + 'h' => ':count година', + 'a_hour' => ':count година', + + 'minute' => ':count малъ', // less reliable + 'min' => ':count малъ', // less reliable + 'a_minute' => ':count малъ', // less reliable + + 'second' => ':count въторъ', + 's' => ':count въторъ', + 'a_second' => ':count въторъ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cv.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cv.php new file mode 100644 index 0000000..8aeb73a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cv.php @@ -0,0 +1,65 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - JD Isaacks + */ +return [ + 'year' => ':count ҫул', + 'a_year' => '{1}пӗр ҫул|:count ҫул', + 'month' => ':count уйӑх', + 'a_month' => '{1}пӗр уйӑх|:count уйӑх', + 'week' => ':count эрне', + 'a_week' => '{1}пӗр эрне|:count эрне', + 'day' => ':count кун', + 'a_day' => '{1}пӗр кун|:count кун', + 'hour' => ':count сехет', + 'a_hour' => '{1}пӗр сехет|:count сехет', + 'minute' => ':count минут', + 'a_minute' => '{1}пӗр минут|:count минут', + 'second' => ':count ҫеккунт', + 'a_second' => '{1}пӗр-ик ҫеккунт|:count ҫеккунт', + 'ago' => ':time каялла', + 'from_now' => function ($time) { + return $time.(preg_match('/сехет$/u', $time) ? 'рен' : (preg_match('/ҫул/u', $time) ? 'тан' : 'ран')); + }, + 'diff_yesterday' => 'Ӗнер', + 'diff_today' => 'Паян', + 'diff_tomorrow' => 'Ыран', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD-MM-YYYY', + 'LL' => 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', + 'LLL' => 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', + 'LLLL' => 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Паян] LT [сехетре]', + 'nextDay' => '[Ыран] LT [сехетре]', + 'nextWeek' => '[Ҫитес] dddd LT [сехетре]', + 'lastDay' => '[Ӗнер] LT [сехетре]', + 'lastWeek' => '[Иртнӗ] dddd LT [сехетре]', + 'sameElse' => 'L', + ], + 'ordinal' => ':number-мӗш', + 'months' => ['кӑрлач', 'нарӑс', 'пуш', 'ака', 'май', 'ҫӗртме', 'утӑ', 'ҫурла', 'авӑн', 'юпа', 'чӳк', 'раштав'], + 'months_short' => ['кӑр', 'нар', 'пуш', 'ака', 'май', 'ҫӗр', 'утӑ', 'ҫур', 'авн', 'юпа', 'чӳк', 'раш'], + 'weekdays' => ['вырсарникун', 'тунтикун', 'ытларикун', 'юнкун', 'кӗҫнерникун', 'эрнекун', 'шӑматкун'], + 'weekdays_short' => ['выр', 'тун', 'ытл', 'юн', 'кӗҫ', 'эрн', 'шӑм'], + 'weekdays_min' => ['вр', 'тн', 'ыт', 'юн', 'кҫ', 'эр', 'шм'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' тата '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cv_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cv_RU.php new file mode 100644 index 0000000..197bd8d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cv_RU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/cv.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cy.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cy.php new file mode 100644 index 0000000..119274f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cy.php @@ -0,0 +1,79 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - JD Isaacks + * - Daniel Monaghan + */ +return [ + 'year' => '{1}blwyddyn|]1,Inf[:count flynedd', + 'y' => ':countbl', + 'month' => '{1}mis|]1,Inf[:count mis', + 'm' => ':countmi', + 'week' => ':count wythnos', + 'w' => ':countw', + 'day' => '{1}diwrnod|]1,Inf[:count diwrnod', + 'd' => ':countd', + 'hour' => '{1}awr|]1,Inf[:count awr', + 'h' => ':counth', + 'minute' => '{1}munud|]1,Inf[:count munud', + 'min' => ':countm', + 'second' => '{1}ychydig eiliadau|]1,Inf[:count eiliad', + 's' => ':counts', + 'ago' => ':time yn ôl', + 'from_now' => 'mewn :time', + 'after' => ':time ar ôl', + 'before' => ':time o\'r blaen', + 'diff_now' => 'nawr', + 'diff_today' => 'Heddiw', + 'diff_today_regexp' => 'Heddiw(?:\\s+am)?', + 'diff_yesterday' => 'ddoe', + 'diff_yesterday_regexp' => 'Ddoe(?:\\s+am)?', + 'diff_tomorrow' => 'yfory', + 'diff_tomorrow_regexp' => 'Yfory(?:\\s+am)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Heddiw am] LT', + 'nextDay' => '[Yfory am] LT', + 'nextWeek' => 'dddd [am] LT', + 'lastDay' => '[Ddoe am] LT', + 'lastWeek' => 'dddd [diwethaf am] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + return $number.( + $number > 20 + ? (\in_array((int) $number, [40, 50, 60, 80, 100], true) ? 'fed' : 'ain') + : ([ + '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed + 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed', // 11eg to 20fed + ])[$number] ?? '' + ); + }, + 'months' => ['Ionawr', 'Chwefror', 'Mawrth', 'Ebrill', 'Mai', 'Mehefin', 'Gorffennaf', 'Awst', 'Medi', 'Hydref', 'Tachwedd', 'Rhagfyr'], + 'months_short' => ['Ion', 'Chwe', 'Maw', 'Ebr', 'Mai', 'Meh', 'Gor', 'Aws', 'Med', 'Hyd', 'Tach', 'Rhag'], + 'weekdays' => ['Dydd Sul', 'Dydd Llun', 'Dydd Mawrth', 'Dydd Mercher', 'Dydd Iau', 'Dydd Gwener', 'Dydd Sadwrn'], + 'weekdays_short' => ['Sul', 'Llun', 'Maw', 'Mer', 'Iau', 'Gwe', 'Sad'], + 'weekdays_min' => ['Su', 'Ll', 'Ma', 'Me', 'Ia', 'Gw', 'Sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' a '], + 'meridiem' => ['yb', 'yh'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cy_GB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cy_GB.php new file mode 100644 index 0000000..2c8148d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/cy_GB.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/cy.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da.php new file mode 100644 index 0000000..322f91d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da.php @@ -0,0 +1,81 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Rune Mønnike + * - François B + * - codenhagen + * - JD Isaacks + * - Jens Herlevsen + * - Ulrik McArdle (mcardle) + * - Frederik Sauer (FrittenKeeZ) + * - Janus Bahs Jacquet (kokoshneta) + */ +return [ + 'year' => ':count år|:count år', + 'a_year' => 'et år|:count år', + 'y' => ':count år|:count år', + 'month' => ':count måned|:count måneder', + 'a_month' => 'en måned|:count måneder', + 'm' => ':count mdr.', + 'week' => ':count uge|:count uger', + 'a_week' => 'en uge|:count uger', + 'w' => ':count u.', + 'day' => ':count dag|:count dage', + 'a_day' => ':count dag|:count dage', + 'd' => ':count d.', + 'hour' => ':count time|:count timer', + 'a_hour' => 'en time|:count timer', + 'h' => ':count t.', + 'minute' => ':count minut|:count minutter', + 'a_minute' => 'et minut|:count minutter', + 'min' => ':count min.', + 'second' => ':count sekund|:count sekunder', + 'a_second' => 'få sekunder|:count sekunder', + 's' => ':count s.', + 'ago' => 'for :time siden', + 'from_now' => 'om :time', + 'after' => ':time efter', + 'before' => ':time før', + 'diff_now' => 'nu', + 'diff_today' => 'i dag', + 'diff_today_regexp' => 'i dag(?:\\s+kl.)?', + 'diff_yesterday' => 'i går', + 'diff_yesterday_regexp' => 'i går(?:\\s+kl.)?', + 'diff_tomorrow' => 'i morgen', + 'diff_tomorrow_regexp' => 'i morgen(?:\\s+kl.)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd [d.] D. MMMM YYYY [kl.] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[i dag kl.] LT', + 'nextDay' => '[i morgen kl.] LT', + 'nextWeek' => 'på dddd [kl.] LT', + 'lastDay' => '[i går kl.] LT', + 'lastWeek' => '[i] dddd[s kl.] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december'], + 'months_short' => ['jan.', 'feb.', 'mar.', 'apr.', 'maj.', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'], + 'weekdays' => ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'], + 'weekdays_short' => ['søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.'], + 'weekdays_min' => ['sø', 'ma', 'ti', 'on', 'to', 'fr', 'lø'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' og '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da_DK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da_DK.php new file mode 100644 index 0000000..392c484 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da_DK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/da.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da_GL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da_GL.php new file mode 100644 index 0000000..ea5698b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/da_GL.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/da.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + 'LL' => 'D. MMM YYYY', + 'LLL' => 'D. MMMM YYYY HH.mm', + 'LLLL' => 'dddd [den] D. MMMM YYYY HH.mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dav.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dav.php new file mode 100644 index 0000000..e95ec4b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dav.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Luma lwa K', 'luma lwa p'], + 'weekdays' => ['Ituku ja jumwa', 'Kuramuka jimweri', 'Kuramuka kawi', 'Kuramuka kadadu', 'Kuramuka kana', 'Kuramuka kasanu', 'Kifula nguwo'], + 'weekdays_short' => ['Jum', 'Jim', 'Kaw', 'Kad', 'Kan', 'Kas', 'Ngu'], + 'weekdays_min' => ['Jum', 'Jim', 'Kaw', 'Kad', 'Kan', 'Kas', 'Ngu'], + 'months' => ['Mori ghwa imbiri', 'Mori ghwa kawi', 'Mori ghwa kadadu', 'Mori ghwa kana', 'Mori ghwa kasanu', 'Mori ghwa karandadu', 'Mori ghwa mfungade', 'Mori ghwa wunyanya', 'Mori ghwa ikenda', 'Mori ghwa ikumi', 'Mori ghwa ikumi na imweri', 'Mori ghwa ikumi na iwi'], + 'months_short' => ['Imb', 'Kaw', 'Kad', 'Kan', 'Kas', 'Kar', 'Mfu', 'Wun', 'Ike', 'Iku', 'Imw', 'Iwi'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de.php new file mode 100644 index 0000000..3b70750 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de.php @@ -0,0 +1,117 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Michael Hohl + * - sheriffmarley + * - dennisoderwald + * - Timo + * - Karag2006 + * - Pete Scopes (pdscopes) + */ +return [ + 'year' => ':count Jahr|:count Jahre', + 'a_year' => 'ein Jahr|:count Jahre', + 'y' => ':count J.', + 'month' => ':count Monat|:count Monate', + 'a_month' => 'ein Monat|:count Monate', + 'm' => ':count Mon.', + 'week' => ':count Woche|:count Wochen', + 'a_week' => 'eine Woche|:count Wochen', + 'w' => ':count Wo.', + 'day' => ':count Tag|:count Tage', + 'a_day' => 'ein Tag|:count Tage', + 'd' => ':count Tg.', + 'hour' => ':count Stunde|:count Stunden', + 'a_hour' => 'eine Stunde|:count Stunden', + 'h' => ':count Std.', + 'minute' => ':count Minute|:count Minuten', + 'a_minute' => 'eine Minute|:count Minuten', + 'min' => ':count Min.', + 'second' => ':count Sekunde|:count Sekunden', + 'a_second' => 'ein paar Sekunden|:count Sekunden', + 's' => ':count Sek.', + 'millisecond' => ':count Millisekunde|:count Millisekunden', + 'a_millisecond' => 'eine Millisekunde|:count Millisekunden', + 'ms' => ':countms', + 'microsecond' => ':count Mikrosekunde|:count Mikrosekunden', + 'a_microsecond' => 'eine Mikrosekunde|:count Mikrosekunden', + 'µs' => ':countµs', + 'ago' => 'vor :time', + 'from_now' => 'in :time', + 'after' => ':time später', + 'before' => ':time zuvor', + + 'year_from_now' => ':count Jahr|:count Jahren', + 'month_from_now' => ':count Monat|:count Monaten', + 'week_from_now' => ':count Woche|:count Wochen', + 'day_from_now' => ':count Tag|:count Tagen', + 'year_ago' => ':count Jahr|:count Jahren', + 'month_ago' => ':count Monat|:count Monaten', + 'week_ago' => ':count Woche|:count Wochen', + 'day_ago' => ':count Tag|:count Tagen', + 'a_year_from_now' => 'ein Jahr|:count Jahren', + 'a_month_from_now' => 'ein Monat|:count Monaten', + 'a_week_from_now' => 'eine Woche|:count Wochen', + 'a_day_from_now' => 'ein Tag|:count Tagen', + 'a_year_ago' => 'ein Jahr|:count Jahren', + 'a_month_ago' => 'ein Monat|:count Monaten', + 'a_week_ago' => 'eine Woche|:count Wochen', + 'a_day_ago' => 'ein Tag|:count Tagen', + + 'diff_now' => 'Gerade eben', + 'diff_today' => 'heute', + 'diff_today_regexp' => 'heute(?:\\s+um)?', + 'diff_yesterday' => 'Gestern', + 'diff_yesterday_regexp' => 'gestern(?:\\s+um)?', + 'diff_tomorrow' => 'Morgen', + 'diff_tomorrow_regexp' => 'morgen(?:\\s+um)?', + 'diff_before_yesterday' => 'Vorgestern', + 'diff_after_tomorrow' => 'Übermorgen', + + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D. MMMM YYYY HH:mm', + ], + + 'calendar' => [ + 'sameDay' => '[heute um] LT [Uhr]', + 'nextDay' => '[morgen um] LT [Uhr]', + 'nextWeek' => 'dddd [um] LT [Uhr]', + 'lastDay' => '[gestern um] LT [Uhr]', + 'lastWeek' => '[letzten] dddd [um] LT [Uhr]', + 'sameElse' => 'L', + ], + + 'months' => ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], + 'months_short' => ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], + 'weekdays' => ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], + 'weekdays_short' => ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'], + 'weekdays_min' => ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], + 'ordinal' => ':number.', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' und '], + 'ordinal_words' => [ + 'of' => 'im', + 'first' => 'erster', + 'second' => 'zweiter', + 'third' => 'dritter', + 'fourth' => 'vierten', + 'fifth' => 'fünfter', + 'last' => 'letzten', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_AT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_AT.php new file mode 100644 index 0000000..a2ea4c0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_AT.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - sheriffmarley + * - Timo + * - Michael Hohl + * - Namoshek + * - Bernhard Baumrock (BernhardBaumrock) + */ +return array_replace_recursive(require __DIR__.'/de.php', [ + 'months' => [ + 0 => 'Jänner', + ], + 'months_short' => [ + 0 => 'Jän', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_BE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_BE.php new file mode 100644 index 0000000..8ed8dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_BE.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/de.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_CH.php new file mode 100644 index 0000000..a869ab4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_CH.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - sheriffmarley + * - Timo + * - Michael Hohl + */ +return array_replace_recursive(require __DIR__.'/de.php', [ + 'weekdays_short' => ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_DE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_DE.php new file mode 100644 index 0000000..fb1209d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_DE.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return require __DIR__.'/de.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_IT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_IT.php new file mode 100644 index 0000000..604a856 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_IT.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Matthias Dieter Wallno:fer libc-locales@sourceware.org + */ +return require __DIR__.'/de.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_LI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_LI.php new file mode 100644 index 0000000..03e606a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_LI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/de.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_LU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_LU.php new file mode 100644 index 0000000..8ed8dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/de_LU.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/de.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dje.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dje.php new file mode 100644 index 0000000..74b7ac1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dje.php @@ -0,0 +1,40 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Subbaahi', 'Zaarikay b'], + 'weekdays' => ['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamisi', 'Alzuma', 'Asibti'], + 'weekdays_short' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'], + 'weekdays_min' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'], + 'months' => ['Žanwiye', 'Feewiriye', 'Marsi', 'Awiril', 'Me', 'Žuweŋ', 'Žuyye', 'Ut', 'Sektanbur', 'Oktoobur', 'Noowanbur', 'Deesanbur'], + 'months_short' => ['Žan', 'Fee', 'Mar', 'Awi', 'Me', 'Žuw', 'Žuy', 'Ut', 'Sek', 'Okt', 'Noo', 'Dee'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'year' => ':count hari', // less reliable + 'y' => ':count hari', // less reliable + 'a_year' => ':count hari', // less reliable + + 'week' => ':count alzuma', // less reliable + 'w' => ':count alzuma', // less reliable + 'a_week' => ':count alzuma', // less reliable + + 'second' => ':count atinni', // less reliable + 's' => ':count atinni', // less reliable + 'a_second' => ':count atinni', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/doi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/doi.php new file mode 100644 index 0000000..cb679c5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/doi.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/doi_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/doi_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/doi_IN.php new file mode 100644 index 0000000..d359721 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/doi_IN.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat Pune libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'एप्रैल', 'मेई', 'जून', 'जूलै', 'अगस्त', 'सितंबर', 'अक्तूबर', 'नवंबर', 'दिसंबर'], + 'months_short' => ['जनवरी', 'फरवरी', 'मार्च', 'एप्रैल', 'मेई', 'जून', 'जूलै', 'अगस्त', 'सितंबर', 'अक्तूबर', 'नवंबर', 'दिसंबर'], + 'weekdays' => ['ऐतबार', 'सोमबार', 'मंगलबर', 'बुधबार', 'बीरबार', 'शुक्करबार', 'श्नीचरबार'], + 'weekdays_short' => ['ऐत', 'सोम', 'मंगल', 'बुध', 'बीर', 'शुक्कर', 'श्नीचर'], + 'weekdays_min' => ['ऐत', 'सोम', 'मंगल', 'बुध', 'बीर', 'शुक्कर', 'श्नीचर'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['सञं', 'सबेर'], + + 'second' => ':count सङार', // less reliable + 's' => ':count सङार', // less reliable + 'a_second' => ':count सङार', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dsb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dsb.php new file mode 100644 index 0000000..1d214d5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dsb.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/dsb_DE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dsb_DE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dsb_DE.php new file mode 100644 index 0000000..1b94187 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dsb_DE.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Information from Michael Wolf bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'DD. MMMM YYYY', + 'LLL' => 'DD. MMMM, HH:mm [góź.]', + 'LLLL' => 'dddd, DD. MMMM YYYY, HH:mm [góź.]', + ], + 'months' => ['januara', 'februara', 'měrca', 'apryla', 'maja', 'junija', 'julija', 'awgusta', 'septembra', 'oktobra', 'nowembra', 'decembra'], + 'months_short' => ['Jan', 'Feb', 'Měr', 'Apr', 'Maj', 'Jun', 'Jul', 'Awg', 'Sep', 'Okt', 'Now', 'Dec'], + 'weekdays' => ['Njeźela', 'Pónjeźele', 'Wałtora', 'Srjoda', 'Stwórtk', 'Pětk', 'Sobota'], + 'weekdays_short' => ['Nj', 'Pó', 'Wa', 'Sr', 'St', 'Pě', 'So'], + 'weekdays_min' => ['Nj', 'Pó', 'Wa', 'Sr', 'St', 'Pě', 'So'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count lěto', + 'y' => ':count lěto', + 'a_year' => ':count lěto', + + 'month' => ':count mjasec', + 'm' => ':count mjasec', + 'a_month' => ':count mjasec', + + 'week' => ':count tyźeń', + 'w' => ':count tyźeń', + 'a_week' => ':count tyźeń', + + 'day' => ':count źeń', + 'd' => ':count źeń', + 'a_day' => ':count źeń', + + 'hour' => ':count góźina', + 'h' => ':count góźina', + 'a_hour' => ':count góźina', + + 'minute' => ':count minuta', + 'min' => ':count minuta', + 'a_minute' => ':count minuta', + + 'second' => ':count drugi', + 's' => ':count drugi', + 'a_second' => ':count drugi', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dua.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dua.php new file mode 100644 index 0000000..55e5c7c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dua.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['idiɓa', 'ebyámu'], + 'weekdays' => ['éti', 'mɔ́sú', 'kwasú', 'mukɔ́sú', 'ŋgisú', 'ɗónɛsú', 'esaɓasú'], + 'weekdays_short' => ['ét', 'mɔ́s', 'kwa', 'muk', 'ŋgi', 'ɗón', 'esa'], + 'weekdays_min' => ['ét', 'mɔ́s', 'kwa', 'muk', 'ŋgi', 'ɗón', 'esa'], + 'months' => ['dimɔ́di', 'ŋgɔndɛ', 'sɔŋɛ', 'diɓáɓá', 'emiasele', 'esɔpɛsɔpɛ', 'madiɓɛ́díɓɛ́', 'diŋgindi', 'nyɛtɛki', 'mayésɛ́', 'tiníní', 'eláŋgɛ́'], + 'months_short' => ['di', 'ŋgɔn', 'sɔŋ', 'diɓ', 'emi', 'esɔ', 'mad', 'diŋ', 'nyɛt', 'may', 'tin', 'elá'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'year' => ':count ma mbu', // less reliable + 'y' => ':count ma mbu', // less reliable + 'a_year' => ':count ma mbu', // less reliable + + 'month' => ':count myo̱di', // less reliable + 'm' => ':count myo̱di', // less reliable + 'a_month' => ':count myo̱di', // less reliable + + 'week' => ':count woki', // less reliable + 'w' => ':count woki', // less reliable + 'a_week' => ':count woki', // less reliable + + 'day' => ':count buńa', // less reliable + 'd' => ':count buńa', // less reliable + 'a_day' => ':count buńa', // less reliable + + 'hour' => ':count ma awa', // less reliable + 'h' => ':count ma awa', // less reliable + 'a_hour' => ':count ma awa', // less reliable + + 'minute' => ':count minuti', // less reliable + 'min' => ':count minuti', // less reliable + 'a_minute' => ':count minuti', // less reliable + + 'second' => ':count maba', // less reliable + 's' => ':count maba', // less reliable + 'a_second' => ':count maba', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dv.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dv.php new file mode 100644 index 0000000..4b8d7e1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dv.php @@ -0,0 +1,89 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +$months = [ + 'ޖެނުއަރީ', + 'ފެބްރުއަރީ', + 'މާރިޗު', + 'އޭޕްރީލު', + 'މޭ', + 'ޖޫން', + 'ޖުލައި', + 'އޯގަސްޓު', + 'ސެޕްޓެމްބަރު', + 'އޮކްޓޯބަރު', + 'ނޮވެމްބަރު', + 'ޑިސެމްބަރު', +]; + +$weekdays = [ + 'އާދިއްތަ', + 'ހޯމަ', + 'އަންގާރަ', + 'ބުދަ', + 'ބުރާސްފަތި', + 'ހުކުރު', + 'ހޮނިހިރު', +]; + +/* + * Authors: + * - Josh Soref + * - Jawish Hameed + */ +return [ + 'year' => ':count '.'އަހަރު', + 'a_year' => '{1}'.'އަހަރެއް'.'|:count '.'އަހަރު', + 'month' => ':count '.'މަސް', + 'a_month' => '{1}'.'މަހެއް'.'|:count '.'މަސް', + 'week' => ':count '.'ހަފްތާ', + 'a_week' => '{1}'.'ސިކުންތުކޮޅެއް'.'|:count '.'ހަފްތާ', + 'day' => ':count '.'ދުވަސް', + 'a_day' => '{1}'.'ދުވަހެއް'.'|:count '.'ދުވަސް', + 'hour' => ':count '.'ގަޑިއިރު', + 'a_hour' => '{1}'.'ގަޑިއިރެއް'.'|:count '.'ގަޑިއިރު', + 'minute' => ':count '.'މިނިޓު', + 'a_minute' => '{1}'.'މިނިޓެއް'.'|:count '.'މިނިޓު', + 'second' => ':count '.'ސިކުންތު', + 'a_second' => '{1}'.'ސިކުންތުކޮޅެއް'.'|:count '.'ސިކުންތު', + 'ago' => 'ކުރިން :time', + 'from_now' => 'ތެރޭގައި :time', + 'after' => ':time ފަހުން', + 'before' => ':time ކުރި', + 'diff_yesterday' => 'އިއްޔެ', + 'diff_today' => 'މިއަދު', + 'diff_tomorrow' => 'މާދަމާ', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[މިއަދު] LT', + 'nextDay' => '[މާދަމާ] LT', + 'nextWeek' => 'dddd LT', + 'lastDay' => '[އިއްޔެ] LT', + 'lastWeek' => '[ފާއިތުވި] dddd LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['މކ', 'މފ'], + 'months' => $months, + 'months_short' => $months, + 'weekdays' => $weekdays, + 'weekdays_short' => $weekdays, + 'weekdays_min' => ['އާދި', 'ހޯމަ', 'އަން', 'ބުދަ', 'ބުރާ', 'ހުކު', 'ހޮނި'], + 'list' => [', ', ' އަދި '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dv_MV.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dv_MV.php new file mode 100644 index 0000000..2668d5b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dv_MV.php @@ -0,0 +1,87 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ahmed Ali + */ + +$months = [ + 'ޖެނުއަރީ', + 'ފެބްރުއަރީ', + 'މާރިޗު', + 'އޭޕްރީލު', + 'މޭ', + 'ޖޫން', + 'ޖުލައި', + 'އޯގަސްޓު', + 'ސެޕްޓެމްބަރު', + 'އޮކްޓޯބަރު', + 'ނޮވެމްބަރު', + 'ޑިސެމްބަރު', +]; + +$weekdays = [ + 'އާދިއްތަ', + 'ހޯމަ', + 'އަންގާރަ', + 'ބުދަ', + 'ބުރާސްފަތި', + 'ހުކުރު', + 'ހޮނިހިރު', +]; + +return [ + 'year' => '{0}އަހަރެއް|[1,Inf]:count އަހަރު', + 'y' => '{0}އަހަރެއް|[1,Inf]:count އަހަރު', + 'month' => '{0}މައްސަރެއް|[1,Inf]:count މަސް', + 'm' => '{0}މައްސަރެއް|[1,Inf]:count މަސް', + 'week' => '{0}ހަފްތާއެއް|[1,Inf]:count ހަފްތާ', + 'w' => '{0}ހަފްތާއެއް|[1,Inf]:count ހަފްތާ', + 'day' => '{0}ދުވަސް|[1,Inf]:count ދުވަސް', + 'd' => '{0}ދުވަސް|[1,Inf]:count ދުވަސް', + 'hour' => '{0}ގަޑިއިރެއް|[1,Inf]:count ގަޑި', + 'h' => '{0}ގަޑިއިރެއް|[1,Inf]:count ގަޑި', + 'minute' => '{0}މިނެޓެއް|[1,Inf]:count މިނެޓް', + 'min' => '{0}މިނެޓެއް|[1,Inf]:count މިނެޓް', + 'second' => '{0}ސިކުންތެއް|[1,Inf]:count ސިކުންތު', + 's' => '{0}ސިކުންތެއް|[1,Inf]:count ސިކުންތު', + 'ago' => ':time ކުރިން', + 'from_now' => ':time ފަހުން', + 'after' => ':time ފަހުން', + 'before' => ':time ކުރި', + 'diff_yesterday' => 'އިއްޔެ', + 'diff_today' => 'މިއަދު', + 'diff_tomorrow' => 'މާދަމާ', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[މިއަދު] LT', + 'nextDay' => '[މާދަމާ] LT', + 'nextWeek' => 'dddd LT', + 'lastDay' => '[އިއްޔެ] LT', + 'lastWeek' => '[ފާއިތުވި] dddd LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['މކ', 'މފ'], + 'months' => $months, + 'months_short' => $months, + 'weekdays' => $weekdays, + 'weekdays_short' => $weekdays, + 'weekdays_min' => ['އާދި', 'ހޯމަ', 'އަން', 'ބުދަ', 'ބުރާ', 'ހުކު', 'ހޮނި'], + 'list' => [', ', ' އަދި '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dyo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dyo.php new file mode 100644 index 0000000..33082e6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dyo.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Dimas', 'Teneŋ', 'Talata', 'Alarbay', 'Aramisay', 'Arjuma', 'Sibiti'], + 'weekdays_short' => ['Dim', 'Ten', 'Tal', 'Ala', 'Ara', 'Arj', 'Sib'], + 'weekdays_min' => ['Dim', 'Ten', 'Tal', 'Ala', 'Ara', 'Arj', 'Sib'], + 'months' => ['Sanvie', 'Fébirie', 'Mars', 'Aburil', 'Mee', 'Sueŋ', 'Súuyee', 'Ut', 'Settembar', 'Oktobar', 'Novembar', 'Disambar'], + 'months_short' => ['Sa', 'Fe', 'Ma', 'Ab', 'Me', 'Su', 'Sú', 'Ut', 'Se', 'Ok', 'No', 'De'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dz.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dz.php new file mode 100644 index 0000000..cc17e69 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dz.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/dz_BT.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dz_BT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dz_BT.php new file mode 100644 index 0000000..bfbcaf4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/dz_BT.php @@ -0,0 +1,43 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Sherubtse College bug-glibc@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'པསྱི་ལོYYཟལMMཚེསDD', + ], + 'months' => ['ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་'], + 'months_short' => ['ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢'], + 'weekdays' => ['གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་', 'གཟའ་ཉི་མ་'], + 'weekdays_short' => ['ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་', 'ཉི་'], + 'weekdays_min' => ['ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་', 'ཉི་'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ངས་ཆ', 'ཕྱི་ཆ'], + + 'year' => ':count ཆརཔ', // less reliable + 'y' => ':count ཆརཔ', // less reliable + 'a_year' => ':count ཆརཔ', // less reliable + + 'month' => ':count ཟླ་བ', // less reliable + 'm' => ':count ཟླ་བ', // less reliable + 'a_month' => ':count ཟླ་བ', // less reliable + + 'day' => ':count ཉི', // less reliable + 'd' => ':count ཉི', // less reliable + 'a_day' => ':count ཉི', // less reliable + + 'second' => ':count ཆ', // less reliable + 's' => ':count ཆ', // less reliable + 'a_second' => ':count ཆ', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ebu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ebu.php new file mode 100644 index 0000000..f60bc6f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ebu.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['KI', 'UT'], + 'weekdays' => ['Kiumia', 'Njumatatu', 'Njumaine', 'Njumatano', 'Aramithi', 'Njumaa', 'NJumamothii'], + 'weekdays_short' => ['Kma', 'Tat', 'Ine', 'Tan', 'Arm', 'Maa', 'NMM'], + 'weekdays_min' => ['Kma', 'Tat', 'Ine', 'Tan', 'Arm', 'Maa', 'NMM'], + 'months' => ['Mweri wa mbere', 'Mweri wa kaĩri', 'Mweri wa kathatũ', 'Mweri wa kana', 'Mweri wa gatano', 'Mweri wa gatantatũ', 'Mweri wa mũgwanja', 'Mweri wa kanana', 'Mweri wa kenda', 'Mweri wa ikũmi', 'Mweri wa ikũmi na ũmwe', 'Mweri wa ikũmi na Kaĩrĩ'], + 'months_short' => ['Mbe', 'Kai', 'Kat', 'Kan', 'Gat', 'Gan', 'Mug', 'Knn', 'Ken', 'Iku', 'Imw', 'Igi'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ee.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ee.php new file mode 100644 index 0000000..f96c5c9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ee.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['ŋ', 'ɣ'], + 'weekdays' => ['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], + 'weekdays_short' => ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], + 'weekdays_min' => ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], + 'months' => ['dzove', 'dzodze', 'tedoxe', 'afɔfĩe', 'dama', 'masa', 'siamlɔm', 'deasiamime', 'anyɔnyɔ', 'kele', 'adeɛmekpɔxe', 'dzome'], + 'months_short' => ['dzv', 'dzd', 'ted', 'afɔ', 'dam', 'mas', 'sia', 'dea', 'any', 'kel', 'ade', 'dzm'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'a [ga] h:mm', + 'LTS' => 'a [ga] h:mm:ss', + 'L' => 'M/D/YYYY', + 'LL' => 'MMM D [lia], YYYY', + 'LLL' => 'a [ga] h:mm MMMM D [lia] YYYY', + 'LLLL' => 'a [ga] h:mm dddd, MMMM D [lia] YYYY', + ], + + 'year' => 'ƒe :count', + 'y' => 'ƒe :count', + 'a_year' => 'ƒe :count', + + 'month' => 'ɣleti :count', + 'm' => 'ɣleti :count', + 'a_month' => 'ɣleti :count', + + 'week' => 'kwasiɖa :count', + 'w' => 'kwasiɖa :count', + 'a_week' => 'kwasiɖa :count', + + 'day' => 'ŋkeke :count', + 'd' => 'ŋkeke :count', + 'a_day' => 'ŋkeke :count', + + 'hour' => 'gaƒoƒo :count', + 'h' => 'gaƒoƒo :count', + 'a_hour' => 'gaƒoƒo :count', + + 'minute' => 'miniti :count', // less reliable + 'min' => 'miniti :count', // less reliable + 'a_minute' => 'miniti :count', // less reliable + + 'second' => 'sɛkɛnd :count', // less reliable + 's' => 'sɛkɛnd :count', // less reliable + 'a_second' => 'sɛkɛnd :count', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ee_TG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ee_TG.php new file mode 100644 index 0000000..7a8b36c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ee_TG.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ee.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'LLL' => 'HH:mm MMMM D [lia] YYYY', + 'LLLL' => 'HH:mm dddd, MMMM D [lia] YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el.php new file mode 100644 index 0000000..7c40f9c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el.php @@ -0,0 +1,93 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Alessandro Di Felice + * - François B + * - Tim Fish + * - Gabriel Monteagudo + * - JD Isaacks + * - yiannisdesp + * - Ilias Kasmeridis (iliaskasm) + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count χρόνος|:count χρόνια', + 'a_year' => 'ένας χρόνος|:count χρόνια', + 'y' => ':count χρ.', + 'month' => ':count μήνας|:count μήνες', + 'a_month' => 'ένας μήνας|:count μήνες', + 'm' => ':count μήν.', + 'week' => ':count εβδομάδα|:count εβδομάδες', + 'a_week' => 'μια εβδομάδα|:count εβδομάδες', + 'w' => ':count εβδ.', + 'day' => ':count μέρα|:count μέρες', + 'a_day' => 'μία μέρα|:count μέρες', + 'd' => ':count μέρ.', + 'hour' => ':count ώρα|:count ώρες', + 'a_hour' => 'μία ώρα|:count ώρες', + 'h' => ':count ώρα|:count ώρες', + 'minute' => ':count λεπτό|:count λεπτά', + 'a_minute' => 'ένα λεπτό|:count λεπτά', + 'min' => ':count λεπ.', + 'second' => ':count δευτερόλεπτο|:count δευτερόλεπτα', + 'a_second' => 'λίγα δευτερόλεπτα|:count δευτερόλεπτα', + 's' => ':count δευ.', + 'ago' => 'πριν :time', + 'from_now' => 'σε :time', + 'after' => ':time μετά', + 'before' => ':time πριν', + 'diff_now' => 'τώρα', + 'diff_today' => 'Σήμερα', + 'diff_today_regexp' => 'Σήμερα(?:\\s+{})?', + 'diff_yesterday' => 'χθες', + 'diff_yesterday_regexp' => 'Χθες(?:\\s+{})?', + 'diff_tomorrow' => 'αύριο', + 'diff_tomorrow_regexp' => 'Αύριο(?:\\s+{})?', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm A', + 'LLLL' => 'dddd, D MMMM YYYY h:mm A', + ], + 'calendar' => [ + 'sameDay' => '[Σήμερα {}] LT', + 'nextDay' => '[Αύριο {}] LT', + 'nextWeek' => 'dddd [{}] LT', + 'lastDay' => '[Χθες {}] LT', + 'lastWeek' => function (CarbonInterface $current) { + switch ($current->dayOfWeek) { + case 6: + return '[το προηγούμενο] dddd [{}] LT'; + default: + return '[την προηγούμενη] dddd [{}] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':numberη', + 'meridiem' => ['ΠΜ', 'ΜΜ', 'πμ', 'μμ'], + 'months' => ['Ιανουαρίου', 'Φεβρουαρίου', 'Μαρτίου', 'Απριλίου', 'Μαΐου', 'Ιουνίου', 'Ιουλίου', 'Αυγούστου', 'Σεπτεμβρίου', 'Οκτωβρίου', 'Νοεμβρίου', 'Δεκεμβρίου'], + 'months_standalone' => ['Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάιος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος'], + 'months_regexp' => '/(D[oD]?[\s,]+MMMM|L{2,4}|l{2,4})/', + 'months_short' => ['Ιαν', 'Φεβ', 'Μαρ', 'Απρ', 'Μαϊ', 'Ιουν', 'Ιουλ', 'Αυγ', 'Σεπ', 'Οκτ', 'Νοε', 'Δεκ'], + 'weekdays' => ['Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο'], + 'weekdays_short' => ['Κυρ', 'Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ'], + 'weekdays_min' => ['Κυ', 'Δε', 'Τρ', 'Τε', 'Πε', 'Πα', 'Σα'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' και '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el_CY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el_CY.php new file mode 100644 index 0000000..8a693c1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el_CY.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Greek Debian Translation Team bug-glibc@gnu.org + */ +return array_replace_recursive(require __DIR__.'/el.php', [ + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el_GR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el_GR.php new file mode 100644 index 0000000..df196af --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/el_GR.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/el.php', [ + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en.php new file mode 100644 index 0000000..f81f617 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en.php @@ -0,0 +1,87 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Milos Sakovic + * - Paul + * - Pete Scopes (pdscopes) + */ +return [ + /* + * {1}, {0} and ]1,Inf[ are not needed as it's the default for English pluralization. + * But as some languages are using en.php as a fallback, it's better to specify it + * explicitly so those languages also fallback to English pluralization when a unit + * is missing. + */ + 'year' => '{1}:count year|{0}:count years|]1,Inf[:count years', + 'a_year' => '{1}a year|{0}:count years|]1,Inf[:count years', + 'y' => '{1}:countyr|{0}:countyrs|]1,Inf[:countyrs', + 'month' => '{1}:count month|{0}:count months|]1,Inf[:count months', + 'a_month' => '{1}a month|{0}:count months|]1,Inf[:count months', + 'm' => '{1}:countmo|{0}:countmos|]1,Inf[:countmos', + 'week' => '{1}:count week|{0}:count weeks|]1,Inf[:count weeks', + 'a_week' => '{1}a week|{0}:count weeks|]1,Inf[:count weeks', + 'w' => ':countw', + 'day' => '{1}:count day|{0}:count days|]1,Inf[:count days', + 'a_day' => '{1}a day|{0}:count days|]1,Inf[:count days', + 'd' => ':countd', + 'hour' => '{1}:count hour|{0}:count hours|]1,Inf[:count hours', + 'a_hour' => '{1}an hour|{0}:count hours|]1,Inf[:count hours', + 'h' => ':counth', + 'minute' => '{1}:count minute|{0}:count minutes|]1,Inf[:count minutes', + 'a_minute' => '{1}a minute|{0}:count minutes|]1,Inf[:count minutes', + 'min' => ':countm', + 'second' => '{1}:count second|{0}:count seconds|]1,Inf[:count seconds', + 'a_second' => '{1}a few seconds|{0}:count seconds|]1,Inf[:count seconds', + 's' => ':counts', + 'millisecond' => '{1}:count millisecond|{0}:count milliseconds|]1,Inf[:count milliseconds', + 'a_millisecond' => '{1}a millisecond|{0}:count milliseconds|]1,Inf[:count milliseconds', + 'ms' => ':countms', + 'microsecond' => '{1}:count microsecond|{0}:count microseconds|]1,Inf[:count microseconds', + 'a_microsecond' => '{1}a microsecond|{0}:count microseconds|]1,Inf[:count microseconds', + 'µs' => ':countµs', + 'ago' => ':time ago', + 'from_now' => ':time from now', + 'after' => ':time after', + 'before' => ':time before', + 'diff_now' => 'just now', + 'diff_today' => 'today', + 'diff_yesterday' => 'yesterday', + 'diff_tomorrow' => 'tomorrow', + 'diff_before_yesterday' => 'before yesterday', + 'diff_after_tomorrow' => 'after tomorrow', + 'period_recurrences' => '{1}once|{0}:count times|]1,Inf[:count times', + 'period_interval' => 'every :interval', + 'period_start_date' => 'from :date', + 'period_end_date' => 'to :date', + 'months' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + 'weekdays' => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + 'weekdays_short' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + 'weekdays_min' => ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + 'ordinal' => function ($number) { + $lastDigit = $number % 10; + + return $number.( + ((int) ($number % 100 / 10) === 1) ? 'th' : ( + ($lastDigit === 1) ? 'st' : ( + ($lastDigit === 2) ? 'nd' : ( + ($lastDigit === 3) ? 'rd' : 'th' + ) + ) + ) + ); + }, + 'list' => [', ', ' and '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_001.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_001.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_001.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_150.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_150.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_150.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AG.php new file mode 100644 index 0000000..2c1c64f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AG.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AI.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AI.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AS.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AS.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AT.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AT.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AU.php new file mode 100644 index 0000000..f16bd4f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_AU.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kunal Marwaha + * - François B + * - Mayank Badola + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm A', + 'LLLL' => 'dddd, D MMMM YYYY h:mm A', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BB.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BB.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BE.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BE.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BI.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BI.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BM.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BM.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BS.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BS.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BW.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BZ.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_BZ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CA.php new file mode 100644 index 0000000..e656086 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CA.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Zhan Tong Zhang + * - Mayank Badola + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'YYYY-MM-DD', + 'LL' => 'MMMM D, YYYY', + 'LLL' => 'MMMM D, YYYY h:mm A', + 'LLLL' => 'dddd, MMMM D, YYYY h:mm A', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CC.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php new file mode 100644 index 0000000..10d9cd8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CK.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CK.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CM.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CM.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CX.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CX.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CX.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CY.php new file mode 100644 index 0000000..a44c350 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_CY.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - NehaGautam + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD-MM-YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DE.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DE.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DG.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DG.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DK.php new file mode 100644 index 0000000..9e8a8c6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DK.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Danish Standards Association bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DM.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_DM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ER.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ER.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FI.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FI.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FJ.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FJ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FK.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FK.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FM.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_FM.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GB.php new file mode 100644 index 0000000..67d9fd6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GB.php @@ -0,0 +1,30 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Mayank Badola + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GD.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GD.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GG.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GG.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GH.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GH.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GI.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GI.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GM.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GM.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GU.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GY.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_GY.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_HK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_HK.php new file mode 100644 index 0000000..34aae98 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_HK.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IE.php new file mode 100644 index 0000000..c8d3c2f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IE.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Martin McWhorter + * - François B + * - Chris Cartlidge + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD-MM-YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IL.php new file mode 100644 index 0000000..e607924 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IL.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Yoav Amit + * - François B + * - Mayank Badola + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IM.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IM.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IN.php new file mode 100644 index 0000000..00414e9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IN.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YY', + 'LL' => 'MMMM DD, YYYY', + 'LLL' => 'DD MMM HH:mm', + 'LLLL' => 'MMMM DD, YYYY HH:mm', + ], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IO.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_IO.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ISO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ISO.php new file mode 100644 index 0000000..11457b0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ISO.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'dddd, YYYY MMMM DD HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_JE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_JE.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_JE.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_JM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_JM.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_JM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KE.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KI.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KI.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KN.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KN.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KY.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_KY.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LC.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LR.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LR.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LS.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_LS.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MG.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MG.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MH.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MH.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MO.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MP.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MP.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MP.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MS.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MS.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MT.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MT.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MU.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MU.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MW.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MW.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MY.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_MY.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NA.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NA.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NF.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NF.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NG.php new file mode 100644 index 0000000..67bceaa --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NG.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NL.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NL.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NR.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NR.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NU.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NU.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NZ.php new file mode 100644 index 0000000..6a206a0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_NZ.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Mayank Badola + * - Luke McGregor + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm A', + 'LLLL' => 'dddd, D MMMM YYYY h:mm A', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PG.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PG.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PH.php new file mode 100644 index 0000000..34aae98 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PH.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PK.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PN.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PN.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PR.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PW.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_PW.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_RW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_RW.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_RW.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SB.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SB.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SC.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SD.php new file mode 100644 index 0000000..c4e2557 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SD.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 6, + 'weekend' => [5, 6], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SE.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SE.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SG.php new file mode 100644 index 0000000..5ee9524 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SG.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'from_now' => 'in :time', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SH.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SH.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SI.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SI.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SL.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SL.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SS.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SS.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SX.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SX.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SX.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SZ.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_SZ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TC.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TK.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TK.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TO.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TO.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TT.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TT.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TV.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TV.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TV.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TZ.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_TZ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_UG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_UG.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_UG.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_UM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_UM.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_UM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_US.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_US.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_US.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_US_Posix.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_US_Posix.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_US_Posix.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VC.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VG.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VG.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VI.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VU.php new file mode 100644 index 0000000..e2dd81d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_VU.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_WS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_WS.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_WS.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZA.php new file mode 100644 index 0000000..48ea947 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZA.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YY', + 'LL' => 'MMMM DD, YYYY', + 'LLL' => 'DD MMM HH:mm', + 'LLLL' => 'MMMM DD, YYYY HH:mm', + ], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZM.php new file mode 100644 index 0000000..d8a8cb5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZM.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - ANLoc Martin Benjamin locales@africanlocalization.net + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZW.php new file mode 100644 index 0000000..f086dc6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/en_ZW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/en.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eo.php new file mode 100644 index 0000000..7c2efba --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eo.php @@ -0,0 +1,77 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - Mia Nordentoft + * - JD Isaacks + */ +return [ + 'year' => ':count jaro|:count jaroj', + 'a_year' => 'jaro|:count jaroj', + 'y' => ':count j.', + 'month' => ':count monato|:count monatoj', + 'a_month' => 'monato|:count monatoj', + 'm' => ':count mo.', + 'week' => ':count semajno|:count semajnoj', + 'a_week' => 'semajno|:count semajnoj', + 'w' => ':count sem.', + 'day' => ':count tago|:count tagoj', + 'a_day' => 'tago|:count tagoj', + 'd' => ':count t.', + 'hour' => ':count horo|:count horoj', + 'a_hour' => 'horo|:count horoj', + 'h' => ':count h.', + 'minute' => ':count minuto|:count minutoj', + 'a_minute' => 'minuto|:count minutoj', + 'min' => ':count min.', + 'second' => ':count sekundo|:count sekundoj', + 'a_second' => 'sekundoj|:count sekundoj', + 's' => ':count sek.', + 'ago' => 'antaŭ :time', + 'from_now' => 'post :time', + 'after' => ':time poste', + 'before' => ':time antaŭe', + 'diff_yesterday' => 'Hieraŭ', + 'diff_yesterday_regexp' => 'Hieraŭ(?:\\s+je)?', + 'diff_today' => 'Hodiaŭ', + 'diff_today_regexp' => 'Hodiaŭ(?:\\s+je)?', + 'diff_tomorrow' => 'Morgaŭ', + 'diff_tomorrow_regexp' => 'Morgaŭ(?:\\s+je)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'D[-a de] MMMM, YYYY', + 'LLL' => 'D[-a de] MMMM, YYYY HH:mm', + 'LLLL' => 'dddd, [la] D[-a de] MMMM, YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Hodiaŭ je] LT', + 'nextDay' => '[Morgaŭ je] LT', + 'nextWeek' => 'dddd [je] LT', + 'lastDay' => '[Hieraŭ je] LT', + 'lastWeek' => '[pasinta] dddd [je] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numbera', + 'meridiem' => ['a.t.m.', 'p.t.m.'], + 'months' => ['januaro', 'februaro', 'marto', 'aprilo', 'majo', 'junio', 'julio', 'aŭgusto', 'septembro', 'oktobro', 'novembro', 'decembro'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aŭg', 'sep', 'okt', 'nov', 'dec'], + 'weekdays' => ['dimanĉo', 'lundo', 'mardo', 'merkredo', 'ĵaŭdo', 'vendredo', 'sabato'], + 'weekdays_short' => ['dim', 'lun', 'mard', 'merk', 'ĵaŭ', 'ven', 'sab'], + 'weekdays_min' => ['di', 'lu', 'ma', 'me', 'ĵa', 've', 'sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' kaj '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es.php new file mode 100644 index 0000000..1c4fcfd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es.php @@ -0,0 +1,121 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kunal Marwaha + * - kostas + * - François B + * - Tim Fish + * - Claire Coloma + * - Steven Heinrich + * - JD Isaacks + * - Raphael Amorim + * - Jorge Y. Castillo + * - Víctor Díaz + * - Diego + * - Sebastian Thierer + * - quinterocesar + * - Daniel Commesse Liévanos (danielcommesse) + * - Pete Scopes (pdscopes) + * - gam04 + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count año|:count años', + 'a_year' => 'un año|:count años', + 'y' => ':count año|:count años', + 'month' => ':count mes|:count meses', + 'a_month' => 'un mes|:count meses', + 'm' => ':count mes|:count meses', + 'week' => ':count semana|:count semanas', + 'a_week' => 'una semana|:count semanas', + 'w' => ':countsem', + 'day' => ':count día|:count días', + 'a_day' => 'un día|:count días', + 'd' => ':countd', + 'hour' => ':count hora|:count horas', + 'a_hour' => 'una hora|:count horas', + 'h' => ':counth', + 'minute' => ':count minuto|:count minutos', + 'a_minute' => 'un minuto|:count minutos', + 'min' => ':countm', + 'second' => ':count segundo|:count segundos', + 'a_second' => 'unos segundos|:count segundos', + 's' => ':counts', + 'millisecond' => ':count milisegundo|:count milisegundos', + 'a_millisecond' => 'un milisegundo|:count milisegundos', + 'ms' => ':countms', + 'microsecond' => ':count microsegundo|:count microsegundos', + 'a_microsecond' => 'un microsegundo|:count microsegundos', + 'µs' => ':countµs', + 'ago' => 'hace :time', + 'from_now' => 'en :time', + 'after' => ':time después', + 'before' => ':time antes', + 'diff_now' => 'ahora mismo', + 'diff_today' => 'hoy', + 'diff_today_regexp' => 'hoy(?:\\s+a)?(?:\\s+las)?', + 'diff_yesterday' => 'ayer', + 'diff_yesterday_regexp' => 'ayer(?:\\s+a)?(?:\\s+las)?', + 'diff_tomorrow' => 'mañana', + 'diff_tomorrow_regexp' => 'mañana(?:\\s+a)?(?:\\s+las)?', + 'diff_before_yesterday' => 'anteayer', + 'diff_after_tomorrow' => 'pasado mañana', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D [de] MMMM [de] YYYY', + 'LLL' => 'D [de] MMMM [de] YYYY H:mm', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => function (CarbonInterface $current) { + return '[hoy a la'.($current->hour !== 1 ? 's' : '').'] LT'; + }, + 'nextDay' => function (CarbonInterface $current) { + return '[mañana a la'.($current->hour !== 1 ? 's' : '').'] LT'; + }, + 'nextWeek' => function (CarbonInterface $current) { + return 'dddd [a la'.($current->hour !== 1 ? 's' : '').'] LT'; + }, + 'lastDay' => function (CarbonInterface $current) { + return '[ayer a la'.($current->hour !== 1 ? 's' : '').'] LT'; + }, + 'lastWeek' => function (CarbonInterface $current) { + return '[el] dddd [pasado a la'.($current->hour !== 1 ? 's' : '').'] LT'; + }, + 'sameElse' => 'L', + ], + 'months' => ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'], + 'months_short' => ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'], + 'mmm_suffix' => '.', + 'ordinal' => ':numberº', + 'weekdays' => ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], + 'weekdays_short' => ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], + 'weekdays_min' => ['do', 'lu', 'ma', 'mi', 'ju', 'vi', 'sá'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' y '], + 'meridiem' => ['a. m.', 'p. m.'], + 'ordinal_words' => [ + 'of' => 'de', + 'first' => 'primer', + 'second' => 'segundo', + 'third' => 'tercer', + 'fourth' => 'cuarto', + 'fifth' => 'quinto', + 'last' => 'último', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_419.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_419.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_419.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_AR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_AR.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_AR.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BO.php new file mode 100644 index 0000000..c9b8432 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BO.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BR.php new file mode 100644 index 0000000..378d054 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BR.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BZ.php new file mode 100644 index 0000000..378d054 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_BZ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CL.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CL.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CO.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CO.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CR.php new file mode 100644 index 0000000..553fc09 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CR.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CU.php new file mode 100644 index 0000000..f02e1a6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_CU.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_DO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_DO.php new file mode 100644 index 0000000..0f855ba --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_DO.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - kostas + * - François B + * - Tim Fish + * - Chiel Robben + * - Claire Coloma + * - Steven Heinrich + * - JD Isaacks + * - Raphael Amorim + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'diff_before_yesterday' => 'anteayer', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'LLL' => 'D [de] MMMM [de] YYYY h:mm A', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY h:mm A', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_EA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_EA.php new file mode 100644 index 0000000..f02e1a6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_EA.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_EC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_EC.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_EC.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_ES.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_ES.php new file mode 100644 index 0000000..19217c2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_ES.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return require __DIR__.'/es.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_GQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_GQ.php new file mode 100644 index 0000000..f02e1a6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_GQ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_GT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_GT.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_GT.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_HN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_HN.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_HN.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_IC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_IC.php new file mode 100644 index 0000000..f02e1a6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_IC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_MX.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_MX.php new file mode 100644 index 0000000..61e14cf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_MX.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'diff_before_yesterday' => 'antier', + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_NI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_NI.php new file mode 100644 index 0000000..6b964c1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_NI.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PA.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PA.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PE.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PE.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PH.php new file mode 100644 index 0000000..deae06a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PH.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/M/yy', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D [de] MMMM [de] YYYY h:mm a', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PR.php new file mode 100644 index 0000000..6b964c1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PR.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PY.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_PY.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_SV.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_SV.php new file mode 100644 index 0000000..00db08e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_SV.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'months' => ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'], + 'months_short' => ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_US.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_US.php new file mode 100644 index 0000000..f333136 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_US.php @@ -0,0 +1,38 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kunal Marwaha + * - Josh Soref + * - Jørn Ølmheim + * - Craig Patik + * - bustta + * - François B + * - Tim Fish + * - Claire Coloma + * - Steven Heinrich + * - JD Isaacks + * - Raphael Amorim + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'diff_before_yesterday' => 'anteayer', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'MM/DD/YYYY', + 'LL' => 'MMMM [de] D [de] YYYY', + 'LLL' => 'MMMM [de] D [de] YYYY h:mm A', + 'LLLL' => 'dddd, MMMM [de] D [de] YYYY h:mm A', + ], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_UY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_UY.php new file mode 100644 index 0000000..39baff8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_UY.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'months' => ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'setiembre', 'octubre', 'noviembre', 'diciembre'], + 'months_short' => ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'dic'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_VE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_VE.php new file mode 100644 index 0000000..a74806e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/es_VE.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/es.php', [ + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/et.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/et.php new file mode 100644 index 0000000..f49c880 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/et.php @@ -0,0 +1,93 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Andres Ivanov + * - Tsutomu Kuroda + * - tjku + * - Max Melentiev + * - Juanito Fatas + * - RM87 + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Esko Lehtme + * - Mart Karu + * - Nicolás Hock Isaza + * - Kevin Valdek + * - Zahhar Kirillov + * - João Magalhães + * - Ingmar + * - Illimar Tambek + * - Mihkel + */ +return [ + 'year' => ':count aasta|:count aastat', + 'y' => ':count a', + 'month' => ':count kuu|:count kuud', + 'm' => ':count k', + 'week' => ':count nädal|:count nädalat', + 'w' => ':count näd', + 'day' => ':count päev|:count päeva', + 'd' => ':count p', + 'hour' => ':count tund|:count tundi', + 'h' => ':count t', + 'minute' => ':count minut|:count minutit', + 'min' => ':count min', + 'second' => ':count sekund|:count sekundit', + 's' => ':count s', + 'ago' => ':time tagasi', + 'from_now' => ':time pärast', + 'after' => ':time pärast', + 'before' => ':time enne', + 'year_from_now' => ':count aasta', + 'month_from_now' => ':count kuu', + 'week_from_now' => ':count nädala', + 'day_from_now' => ':count päeva', + 'hour_from_now' => ':count tunni', + 'minute_from_now' => ':count minuti', + 'second_from_now' => ':count sekundi', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'diff_now' => 'nüüd', + 'diff_today' => 'täna', + 'diff_yesterday' => 'eile', + 'diff_tomorrow' => 'homme', + 'diff_before_yesterday' => 'üleeile', + 'diff_after_tomorrow' => 'ülehomme', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D. MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[täna] LT', + 'nextDay' => '[homme] LT', + 'lastDay' => '[eile] LT', + 'nextWeek' => 'dddd LT', + 'lastWeek' => '[eelmine] dddd LT', + 'sameElse' => 'L', + ], + 'months' => ['jaanuar', 'veebruar', 'märts', 'aprill', 'mai', 'juuni', 'juuli', 'august', 'september', 'oktoober', 'november', 'detsember'], + 'months_short' => ['jaan', 'veebr', 'märts', 'apr', 'mai', 'juuni', 'juuli', 'aug', 'sept', 'okt', 'nov', 'dets'], + 'weekdays' => ['pühapäev', 'esmaspäev', 'teisipäev', 'kolmapäev', 'neljapäev', 'reede', 'laupäev'], + 'weekdays_short' => ['P', 'E', 'T', 'K', 'N', 'R', 'L'], + 'weekdays_min' => ['P', 'E', 'T', 'K', 'N', 'R', 'L'], + 'list' => [', ', ' ja '], + 'meridiem' => ['enne lõunat', 'pärast lõunat'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/et_EE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/et_EE.php new file mode 100644 index 0000000..0f112b3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/et_EE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/et.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eu.php new file mode 100644 index 0000000..a543f1a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eu.php @@ -0,0 +1,67 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - JD Isaacks + */ +return [ + 'year' => 'urte bat|:count urte', + 'y' => 'Urte 1|:count urte', + 'month' => 'hilabete bat|:count hilabete', + 'm' => 'Hile 1|:count hile', + 'week' => 'Aste 1|:count aste', + 'w' => 'Aste 1|:count aste', + 'day' => 'egun bat|:count egun', + 'd' => 'Egun 1|:count egun', + 'hour' => 'ordu bat|:count ordu', + 'h' => 'Ordu 1|:count ordu', + 'minute' => 'minutu bat|:count minutu', + 'min' => 'Minutu 1|:count minutu', + 'second' => 'segundo batzuk|:count segundo', + 's' => 'Segundu 1|:count segundu', + 'ago' => 'duela :time', + 'from_now' => ':time barru', + 'after' => ':time geroago', + 'before' => ':time lehenago', + 'diff_now' => 'orain', + 'diff_today' => 'gaur', + 'diff_yesterday' => 'atzo', + 'diff_tomorrow' => 'bihar', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'YYYY[ko] MMMM[ren] D[a]', + 'LLL' => 'YYYY[ko] MMMM[ren] D[a] HH:mm', + 'LLLL' => 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[gaur] LT[etan]', + 'nextDay' => '[bihar] LT[etan]', + 'nextWeek' => 'dddd LT[etan]', + 'lastDay' => '[atzo] LT[etan]', + 'lastWeek' => '[aurreko] dddd LT[etan]', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['urtarrila', 'otsaila', 'martxoa', 'apirila', 'maiatza', 'ekaina', 'uztaila', 'abuztua', 'iraila', 'urria', 'azaroa', 'abendua'], + 'months_short' => ['urt.', 'ots.', 'mar.', 'api.', 'mai.', 'eka.', 'uzt.', 'abu.', 'ira.', 'urr.', 'aza.', 'abe.'], + 'weekdays' => ['igandea', 'astelehena', 'asteartea', 'asteazkena', 'osteguna', 'ostirala', 'larunbata'], + 'weekdays_short' => ['ig.', 'al.', 'ar.', 'az.', 'og.', 'ol.', 'lr.'], + 'weekdays_min' => ['ig', 'al', 'ar', 'az', 'og', 'ol', 'lr'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' eta '], + 'meridiem' => ['g', 'a'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eu_ES.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eu_ES.php new file mode 100644 index 0000000..0d1e82a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/eu_ES.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/eu.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ewo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ewo.php new file mode 100644 index 0000000..7808ab5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ewo.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['kíkíríg', 'ngəgógəle'], + 'weekdays' => ['sɔ́ndɔ', 'mɔ́ndi', 'sɔ́ndɔ məlú mə́bɛ̌', 'sɔ́ndɔ məlú mə́lɛ́', 'sɔ́ndɔ məlú mə́nyi', 'fúladé', 'séradé'], + 'weekdays_short' => ['sɔ́n', 'mɔ́n', 'smb', 'sml', 'smn', 'fúl', 'sér'], + 'weekdays_min' => ['sɔ́n', 'mɔ́n', 'smb', 'sml', 'smn', 'fúl', 'sér'], + 'months' => ['ngɔn osú', 'ngɔn bɛ̌', 'ngɔn lála', 'ngɔn nyina', 'ngɔn tána', 'ngɔn saməna', 'ngɔn zamgbála', 'ngɔn mwom', 'ngɔn ebulú', 'ngɔn awóm', 'ngɔn awóm ai dziá', 'ngɔn awóm ai bɛ̌'], + 'months_short' => ['ngo', 'ngb', 'ngl', 'ngn', 'ngt', 'ngs', 'ngz', 'ngm', 'nge', 'nga', 'ngad', 'ngab'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + // Too unreliable + /* + 'year' => ':count mbu', // less reliable + 'y' => ':count mbu', // less reliable + 'a_year' => ':count mbu', // less reliable + + 'month' => ':count ngòn', // less reliable + 'm' => ':count ngòn', // less reliable + 'a_month' => ':count ngòn', // less reliable + + 'week' => ':count mësë', // less reliable + 'w' => ':count mësë', // less reliable + 'a_week' => ':count mësë', // less reliable + + 'day' => ':count mësë', // less reliable + 'd' => ':count mësë', // less reliable + 'a_day' => ':count mësë', // less reliable + + 'hour' => ':count awola', // less reliable + 'h' => ':count awola', // less reliable + 'a_hour' => ':count awola', // less reliable + + 'minute' => ':count awola', // less reliable + 'min' => ':count awola', // less reliable + 'a_minute' => ':count awola', // less reliable + */ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa.php new file mode 100644 index 0000000..72e0308 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa.php @@ -0,0 +1,84 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - Nasser Ghiasi + * - JD Isaacks + * - Hossein Jabbari + * - nimamo + * - hafezdivandari + * - Hassan Pezeshk (hpez) + */ +return [ + 'year' => ':count سال', + 'a_year' => 'یک سال'.'|:count '.'سال', + 'y' => ':count سال', + 'month' => ':count ماه', + 'a_month' => 'یک ماه'.'|:count '.'ماه', + 'm' => ':count ماه', + 'week' => ':count هفته', + 'a_week' => 'یک هفته'.'|:count '.'هفته', + 'w' => ':count هفته', + 'day' => ':count روز', + 'a_day' => 'یک روز'.'|:count '.'روز', + 'd' => ':count روز', + 'hour' => ':count ساعت', + 'a_hour' => 'یک ساعت'.'|:count '.'ساعت', + 'h' => ':count ساعت', + 'minute' => ':count دقیقه', + 'a_minute' => 'یک دقیقه'.'|:count '.'دقیقه', + 'min' => ':count دقیقه', + 'second' => ':count ثانیه', + 's' => ':count ثانیه', + 'ago' => ':time پیش', + 'from_now' => ':time دیگر', + 'after' => ':time پس از', + 'before' => ':time پیش از', + 'diff_now' => 'اکنون', + 'diff_today' => 'امروز', + 'diff_today_regexp' => 'امروز(?:\\s+ساعت)?', + 'diff_yesterday' => 'دیروز', + 'diff_yesterday_regexp' => 'دیروز(?:\\s+ساعت)?', + 'diff_tomorrow' => 'فردا', + 'diff_tomorrow_regexp' => 'فردا(?:\\s+ساعت)?', + 'formats' => [ + 'LT' => 'OH:Om', + 'LTS' => 'OH:Om:Os', + 'L' => 'OD/OM/OY', + 'LL' => 'OD MMMM OY', + 'LLL' => 'OD MMMM OY OH:Om', + 'LLLL' => 'dddd, OD MMMM OY OH:Om', + ], + 'calendar' => [ + 'sameDay' => '[امروز ساعت] LT', + 'nextDay' => '[فردا ساعت] LT', + 'nextWeek' => 'dddd [ساعت] LT', + 'lastDay' => '[دیروز ساعت] LT', + 'lastWeek' => 'dddd [پیش] [ساعت] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':timeم', + 'meridiem' => ['قبل از ظهر', 'بعد از ظهر'], + 'months' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اکتبر', 'نوامبر', 'دسامبر'], + 'months_short' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اکتبر', 'نوامبر', 'دسامبر'], + 'weekdays' => ['یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'], + 'weekdays_short' => ['یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'], + 'weekdays_min' => ['ی', 'د', 'س', 'چ', 'پ', 'ج', 'ش'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'list' => ['، ', ' و '], + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰۴', '۰۵', '۰۶', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱۴', '۱۵', '۱۶', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲۴', '۲۵', '۲۶', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳۴', '۳۵', '۳۶', '۳۷', '۳۸', '۳۹', '۴۰', '۴۱', '۴۲', '۴۳', '۴۴', '۴۵', '۴۶', '۴۷', '۴۸', '۴۹', '۵۰', '۵۱', '۵۲', '۵۳', '۵۴', '۵۵', '۵۶', '۵۷', '۵۸', '۵۹', '۶۰', '۶۱', '۶۲', '۶۳', '۶۴', '۶۵', '۶۶', '۶۷', '۶۸', '۶۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷۴', '۷۵', '۷۶', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸۴', '۸۵', '۸۶', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹۴', '۹۵', '۹۶', '۹۷', '۹۸', '۹۹'], + 'months_short_standalone' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اکتبر', 'نوامبر', 'دسامبر'], + 'weekend' => [5, 5], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa_AF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa_AF.php new file mode 100644 index 0000000..6947100 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa_AF.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fa.php', [ + 'meridiem' => ['ق', 'ب'], + 'weekend' => [4, 5], + 'formats' => [ + 'L' => 'OY/OM/OD', + 'LL' => 'OD MMM OY', + 'LLL' => 'OD MMMM OY،‏ H:mm', + 'LLLL' => 'dddd OD MMMM OY،‏ H:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa_IR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa_IR.php new file mode 100644 index 0000000..08d0182 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fa_IR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fa.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff.php new file mode 100644 index 0000000..9525c95 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'months' => ['siilo', 'colte', 'mbooy', 'seeɗto', 'duujal', 'korse', 'morso', 'juko', 'siilto', 'yarkomaa', 'jolal', 'bowte'], + 'months_short' => ['sii', 'col', 'mbo', 'see', 'duu', 'kor', 'mor', 'juk', 'slt', 'yar', 'jol', 'bow'], + 'weekdays' => ['dewo', 'aaɓnde', 'mawbaare', 'njeslaare', 'naasaande', 'mawnde', 'hoore-biir'], + 'weekdays_short' => ['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'], + 'weekdays_min' => ['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['subaka', 'kikiiɗe'], + + 'year' => ':count baret', // less reliable + 'y' => ':count baret', // less reliable + 'a_year' => ':count baret', // less reliable + + 'month' => ':count lewru', // less reliable + 'm' => ':count lewru', // less reliable + 'a_month' => ':count lewru', // less reliable + + 'week' => ':count naange', // less reliable + 'w' => ':count naange', // less reliable + 'a_week' => ':count naange', // less reliable + + 'day' => ':count dian', // less reliable + 'd' => ':count dian', // less reliable + 'a_day' => ':count dian', // less reliable + + 'hour' => ':count montor', // less reliable + 'h' => ':count montor', // less reliable + 'a_hour' => ':count montor', // less reliable + + 'minute' => ':count tokossuoum', // less reliable + 'min' => ':count tokossuoum', // less reliable + 'a_minute' => ':count tokossuoum', // less reliable + + 'second' => ':count tenen', // less reliable + 's' => ':count tenen', // less reliable + 'a_second' => ':count tenen', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_CM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_CM.php new file mode 100644 index 0000000..b797ac0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_CM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ff.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_GN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_GN.php new file mode 100644 index 0000000..b797ac0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_GN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ff.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_MR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_MR.php new file mode 100644 index 0000000..2f4c29f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_MR.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ff.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_SN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_SN.php new file mode 100644 index 0000000..1e4c8b6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ff_SN.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Pular-Fulfulde.org Ibrahima Sarr admin@pulaar-fulfulde.org + */ +return require __DIR__.'/ff.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fi.php new file mode 100644 index 0000000..edf2d6d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fi.php @@ -0,0 +1,88 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Janne Warén + * - digitalfrost + * - Tsutomu Kuroda + * - Roope Salmi + * - tjku + * - Max Melentiev + * - Sami Haahtinen + * - Teemu Leisti + * - Artem Ignatyev + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Robert Bjarnason + * - Aaron Patterson + * - Nicolás Hock Isaza + * - Tom Hughes + * - Sven Fuchs + * - Petri Kivikangas + * - Nizar Jouini + * - Marko Seppae + * - Tomi Mynttinen (Pikseli) + * - Petteri (powergrip) + */ +return [ + 'year' => ':count vuosi|:count vuotta', + 'y' => ':count v', + 'month' => ':count kuukausi|:count kuukautta', + 'm' => ':count kk', + 'week' => ':count viikko|:count viikkoa', + 'w' => ':count vk', + 'day' => ':count päivä|:count päivää', + 'd' => ':count pv', + 'hour' => ':count tunti|:count tuntia', + 'h' => ':count t', + 'minute' => ':count minuutti|:count minuuttia', + 'min' => ':count min', + 'second' => ':count sekunti|:count sekuntia', + 'a_second' => 'muutama sekunti|:count sekuntia', + 's' => ':count s', + 'ago' => ':time sitten', + 'from_now' => ':time päästä', + 'year_from_now' => ':count vuoden', + 'month_from_now' => ':count kuukauden', + 'week_from_now' => ':count viikon', + 'day_from_now' => ':count päivän', + 'hour_from_now' => ':count tunnin', + 'minute_from_now' => ':count minuutin', + 'second_from_now' => ':count sekunnin', + 'after' => ':time sen jälkeen', + 'before' => ':time ennen', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' ja '], + 'diff_now' => 'nyt', + 'diff_yesterday' => 'eilen', + 'diff_tomorrow' => 'huomenna', + 'formats' => [ + 'LT' => 'HH.mm', + 'LTS' => 'HH.mm:ss', + 'L' => 'D.M.YYYY', + 'LL' => 'dddd D. MMMM[ta] YYYY', + 'll' => 'ddd D. MMM YYYY', + 'LLL' => 'D.MM. HH.mm', + 'LLLL' => 'D. MMMM[ta] YYYY HH.mm', + 'llll' => 'D. MMM YY HH.mm', + ], + 'weekdays' => ['sunnuntai', 'maanantai', 'tiistai', 'keskiviikko', 'torstai', 'perjantai', 'lauantai'], + 'weekdays_short' => ['su', 'ma', 'ti', 'ke', 'to', 'pe', 'la'], + 'weekdays_min' => ['su', 'ma', 'ti', 'ke', 'to', 'pe', 'la'], + 'months' => ['tammikuu', 'helmikuu', 'maaliskuu', 'huhtikuu', 'toukokuu', 'kesäkuu', 'heinäkuu', 'elokuu', 'syyskuu', 'lokakuu', 'marraskuu', 'joulukuu'], + 'months_short' => ['tammi', 'helmi', 'maalis', 'huhti', 'touko', 'kesä', 'heinä', 'elo', 'syys', 'loka', 'marras', 'joulu'], + 'meridiem' => ['aamupäivä', 'iltapäivä'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fi_FI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fi_FI.php new file mode 100644 index 0000000..920f1ca --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fi_FI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fi.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fil.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fil.php new file mode 100644 index 0000000..61114e3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fil.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/fil_PH.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fil_PH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fil_PH.php new file mode 100644 index 0000000..bcf1580 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fil_PH.php @@ -0,0 +1,62 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Rene Torres Rene Torres, Pablo Saratxaga rgtorre@rocketmail.com, pablo@mandrakesoft.com + * - Jaycee Mariano (alohajaycee) + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'MM/DD/YY', + ], + 'months' => ['Enero', 'Pebrero', 'Marso', 'Abril', 'Mayo', 'Hunyo', 'Hulyo', 'Agosto', 'Setyembre', 'Oktubre', 'Nobyembre', 'Disyembre'], + 'months_short' => ['Ene', 'Peb', 'Mar', 'Abr', 'May', 'Hun', 'Hul', 'Ago', 'Set', 'Okt', 'Nob', 'Dis'], + 'weekdays' => ['Linggo', 'Lunes', 'Martes', 'Miyerkoles', 'Huwebes', 'Biyernes', 'Sabado'], + 'weekdays_short' => ['Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab'], + 'weekdays_min' => ['Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['N.U.', 'N.H.'], + + 'before' => ':time bago', + 'after' => ':time pagkatapos', + + 'year' => ':count taon', + 'y' => ':count taon', + 'a_year' => ':count taon', + + 'month' => ':count buwan', + 'm' => ':count buwan', + 'a_month' => ':count buwan', + + 'week' => ':count linggo', + 'w' => ':count linggo', + 'a_week' => ':count linggo', + + 'day' => ':count araw', + 'd' => ':count araw', + 'a_day' => ':count araw', + + 'hour' => ':count oras', + 'h' => ':count oras', + 'a_hour' => ':count oras', + + 'minute' => ':count minuto', + 'min' => ':count minuto', + 'a_minute' => ':count minuto', + + 'second' => ':count segundo', + 's' => ':count segundo', + 'a_second' => ':count segundo', + + 'ago' => ':time ang nakalipas', + 'from_now' => 'sa :time', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo.php new file mode 100644 index 0000000..6a14a6f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo.php @@ -0,0 +1,69 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kristian Sakarisson + * - François B + * - JD Isaacks + * - Sverri Mohr Olsen + */ +return [ + 'year' => 'eitt ár|:count ár', + 'y' => ':count ár|:count ár', + 'month' => 'ein mánaði|:count mánaðir', + 'm' => ':count mánaður|:count mánaðir', + 'week' => ':count vika|:count vikur', + 'w' => ':count vika|:count vikur', + 'day' => 'ein dagur|:count dagar', + 'd' => ':count dag|:count dagar', + 'hour' => 'ein tími|:count tímar', + 'h' => ':count tími|:count tímar', + 'minute' => 'ein minutt|:count minuttir', + 'min' => ':count minutt|:count minuttir', + 'second' => 'fá sekund|:count sekundir', + 's' => ':count sekund|:count sekundir', + 'ago' => ':time síðani', + 'from_now' => 'um :time', + 'after' => ':time aftaná', + 'before' => ':time áðrenn', + 'diff_today' => 'Í', + 'diff_yesterday' => 'Í', + 'diff_yesterday_regexp' => 'Í(?:\\s+gjár)?(?:\\s+kl.)?', + 'diff_tomorrow' => 'Í', + 'diff_tomorrow_regexp' => 'Í(?:\\s+morgin)?(?:\\s+kl.)?', + 'diff_today_regexp' => 'Í(?:\\s+dag)?(?:\\s+kl.)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D. MMMM, YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Í dag kl.] LT', + 'nextDay' => '[Í morgin kl.] LT', + 'nextWeek' => 'dddd [kl.] LT', + 'lastDay' => '[Í gjár kl.] LT', + 'lastWeek' => '[síðstu] dddd [kl] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['januar', 'februar', 'mars', 'apríl', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'], + 'weekdays' => ['sunnudagur', 'mánadagur', 'týsdagur', 'mikudagur', 'hósdagur', 'fríggjadagur', 'leygardagur'], + 'weekdays_short' => ['sun', 'mán', 'týs', 'mik', 'hós', 'frí', 'ley'], + 'weekdays_min' => ['su', 'má', 'tý', 'mi', 'hó', 'fr', 'le'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' og '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo_DK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo_DK.php new file mode 100644 index 0000000..657f2c5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo_DK.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fo.php', [ + 'formats' => [ + 'L' => 'DD.MM.yy', + 'LL' => 'DD.MM.YYYY', + 'LLL' => 'D. MMMM YYYY, HH:mm', + 'LLLL' => 'dddd, D. MMMM YYYY, HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo_FO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo_FO.php new file mode 100644 index 0000000..6d73616 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fo_FO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fo.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr.php new file mode 100644 index 0000000..f4c7247 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr.php @@ -0,0 +1,123 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Dieter Sting + * - François B + * - Maxime VALY + * - JD Isaacks + * - Dieter Sting + * - François B + * - JD Isaacks + * - Sebastian Thierer + * - Fastfuel + * - Pete Scopes (pdscopes) + */ +return [ + 'year' => ':count an|:count ans', + 'a_year' => 'un an|:count ans', + 'y' => ':count an|:count ans', + 'month' => ':count mois|:count mois', + 'a_month' => 'un mois|:count mois', + 'm' => ':count mois', + 'week' => ':count semaine|:count semaines', + 'a_week' => 'une semaine|:count semaines', + 'w' => ':count sem.', + 'day' => ':count jour|:count jours', + 'a_day' => 'un jour|:count jours', + 'd' => ':count j', + 'hour' => ':count heure|:count heures', + 'a_hour' => 'une heure|:count heures', + 'h' => ':count h', + 'minute' => ':count minute|:count minutes', + 'a_minute' => 'une minute|:count minutes', + 'min' => ':count min', + 'second' => ':count seconde|:count secondes', + 'a_second' => 'quelques secondes|:count secondes', + 's' => ':count s', + 'millisecond' => ':count milliseconde|:count millisecondes', + 'a_millisecond' => 'une milliseconde|:count millisecondes', + 'ms' => ':countms', + 'microsecond' => ':count microseconde|:count microsecondes', + 'a_microsecond' => 'une microseconde|:count microsecondes', + 'µs' => ':countµs', + 'ago' => 'il y a :time', + 'from_now' => 'dans :time', + 'after' => ':time après', + 'before' => ':time avant', + 'diff_now' => "à l'instant", + 'diff_today' => "aujourd'hui", + 'diff_today_regexp' => "aujourd'hui(?:\s+à)?", + 'diff_yesterday' => 'hier', + 'diff_yesterday_regexp' => 'hier(?:\s+à)?', + 'diff_tomorrow' => 'demain', + 'diff_tomorrow_regexp' => 'demain(?:\s+à)?', + 'diff_before_yesterday' => 'avant-hier', + 'diff_after_tomorrow' => 'après-demain', + 'period_recurrences' => ':count fois', + 'period_interval' => 'tous les :interval', + 'period_start_date' => 'de :date', + 'period_end_date' => 'à :date', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Aujourd’hui à] LT', + 'nextDay' => '[Demain à] LT', + 'nextWeek' => 'dddd [à] LT', + 'lastDay' => '[Hier à] LT', + 'lastWeek' => 'dddd [dernier à] LT', + 'sameElse' => 'L', + ], + 'months' => ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'], + 'months_short' => ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'], + 'weekdays' => ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], + 'weekdays_short' => ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], + 'weekdays_min' => ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'], + 'ordinal' => function ($number, $period) { + switch ($period) { + // In French, only the first has to be ordinal, other number remains cardinal + // @link https://fr.wikihow.com/%C3%A9crire-la-date-en-fran%C3%A7ais + case 'D': + return $number.($number === 1 ? 'er' : ''); + + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + return $number.($number === 1 ? 'er' : 'e'); + + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return $number.($number === 1 ? 're' : 'e'); + } + }, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' et '], + 'ordinal_words' => [ + 'of' => 'de', + 'first' => 'premier', + 'second' => 'deuxième', + 'third' => 'troisième', + 'fourth' => 'quatrième', + 'fifth' => 'cinquième', + 'last' => 'dernier', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BE.php new file mode 100644 index 0000000..f6cafe8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BE.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'months_short' => ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BF.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BI.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BJ.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BJ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BL.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_BL.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CA.php new file mode 100644 index 0000000..c9f6346 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CA.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Dieter Sting + * - François B + * - Maxime VALY + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CD.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CD.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CF.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CG.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CH.php new file mode 100644 index 0000000..8674c27 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CH.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Dieter Sting + * - François B + * - Gaspard Bucher + * - Maxime VALY + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CI.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CM.php new file mode 100644 index 0000000..67d3787 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_CM.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'meridiem' => ['mat.', 'soir'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_DJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_DJ.php new file mode 100644 index 0000000..2f06086 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_DJ.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'first_day_of_week' => 6, + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_DZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_DZ.php new file mode 100644 index 0000000..ae8db5f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_DZ.php @@ -0,0 +1,23 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'first_day_of_week' => 6, + 'weekend' => [5, 6], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_FR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_FR.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_FR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GA.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GF.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GN.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GP.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GP.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GP.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GQ.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_GQ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_HT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_HT.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_HT.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_KM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_KM.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_KM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_LU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_LU.php new file mode 100644 index 0000000..8e37d85 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_LU.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months_short' => ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MA.php new file mode 100644 index 0000000..1bf034d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MA.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'first_day_of_week' => 6, + 'weekend' => [5, 6], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MC.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MC.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MF.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MG.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_ML.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_ML.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_ML.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MQ.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MQ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MR.php new file mode 100644 index 0000000..37cf83f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MR.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MU.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_MU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_NC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_NC.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_NC.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_NE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_NE.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_NE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_PF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_PF.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_PF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_PM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_PM.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_PM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_RE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_RE.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_RE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_RW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_RW.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_RW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SC.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SC.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SN.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SY.php new file mode 100644 index 0000000..ae8db5f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_SY.php @@ -0,0 +1,23 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'first_day_of_week' => 6, + 'weekend' => [5, 6], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TD.php new file mode 100644 index 0000000..37cf83f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TD.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TG.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TN.php new file mode 100644 index 0000000..6905e7a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_TN.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'weekend' => [5, 6], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_VU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_VU.php new file mode 100644 index 0000000..37cf83f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_VU.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fr.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_WF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_WF.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_WF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_YT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_YT.php new file mode 100644 index 0000000..ec3ee35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fr_YT.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/fr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fur.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fur.php new file mode 100644 index 0000000..36c2564 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fur.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/fur_IT.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fur_IT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fur_IT.php new file mode 100644 index 0000000..0147a59 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fur_IT.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Pablo Saratxaga pablo@mandrakesoft.com + */ +return [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD. MM. YY', + 'LL' => 'DD di MMMM dal YYYY', + 'LLL' => 'DD di MMM HH:mm', + 'LLLL' => 'DD di MMMM dal YYYY HH:mm', + ], + 'months' => ['zenâr', 'fevrâr', 'març', 'avrîl', 'mai', 'jugn', 'lui', 'avost', 'setembar', 'otubar', 'novembar', 'dicembar'], + 'months_short' => ['zen', 'fev', 'mar', 'avr', 'mai', 'jug', 'lui', 'avo', 'set', 'otu', 'nov', 'dic'], + 'weekdays' => ['domenie', 'lunis', 'martars', 'miercus', 'joibe', 'vinars', 'sabide'], + 'weekdays_short' => ['dom', 'lun', 'mar', 'mie', 'joi', 'vin', 'sab'], + 'weekdays_min' => ['dom', 'lun', 'mar', 'mie', 'joi', 'vin', 'sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'year' => ':count an', + 'month' => ':count mês', + 'week' => ':count setemane', + 'day' => ':count zornade', + 'hour' => ':count ore', + 'minute' => ':count minût', + 'second' => ':count secont', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy.php new file mode 100644 index 0000000..c1b5439 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Tim Fish + * - JD Isaacks + */ +return [ + 'year' => ':count jier|:count jierren', + 'a_year' => 'ien jier|:count jierren', + 'y' => ':count j', + 'month' => ':count moanne|:count moannen', + 'a_month' => 'ien moanne|:count moannen', + 'm' => ':count moa.', + 'week' => ':count wike|:count wiken', + 'a_week' => 'in wike|:count wiken', + 'a' => ':count w.', + 'day' => ':count dei|:count dagen', + 'a_day' => 'ien dei|:count dagen', + 'd' => ':count d.', + 'hour' => ':count oere|:count oeren', + 'a_hour' => 'ien oere|:count oeren', + 'h' => ':count o.', + 'minute' => ':count minút|:count minuten', + 'a_minute' => 'ien minút|:count minuten', + 'min' => ':count min.', + 'second' => ':count sekonde|:count sekonden', + 'a_second' => 'in pear sekonden|:count sekonden', + 's' => ':count s.', + 'ago' => ':time lyn', + 'from_now' => 'oer :time', + 'diff_yesterday' => 'juster', + 'diff_yesterday_regexp' => 'juster(?:\\s+om)?', + 'diff_today' => 'hjoed', + 'diff_today_regexp' => 'hjoed(?:\\s+om)?', + 'diff_tomorrow' => 'moarn', + 'diff_tomorrow_regexp' => 'moarn(?:\\s+om)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD-MM-YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[hjoed om] LT', + 'nextDay' => '[moarn om] LT', + 'nextWeek' => 'dddd [om] LT', + 'lastDay' => '[juster om] LT', + 'lastWeek' => '[ôfrûne] dddd [om] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + return $number.(($number === 1 || $number === 8 || $number >= 20) ? 'ste' : 'de'); + }, + 'months' => ['jannewaris', 'febrewaris', 'maart', 'april', 'maaie', 'juny', 'july', 'augustus', 'septimber', 'oktober', 'novimber', 'desimber'], + 'months_short' => ['jan', 'feb', 'mrt', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'], + 'mmm_suffix' => '.', + 'weekdays' => ['snein', 'moandei', 'tiisdei', 'woansdei', 'tongersdei', 'freed', 'sneon'], + 'weekdays_short' => ['si.', 'mo.', 'ti.', 'wo.', 'to.', 'fr.', 'so.'], + 'weekdays_min' => ['Si', 'Mo', 'Ti', 'Wo', 'To', 'Fr', 'So'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' en '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy_DE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy_DE.php new file mode 100644 index 0000000..8559d5c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy_DE.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - information from Kenneth Christiansen Kenneth Christiansen, Pablo Saratxaga kenneth@gnu.org, pablo@mandriva.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Jaunuwoa', 'Februwoa', 'Moaz', 'Aprell', 'Mai', 'Juni', 'Juli', 'August', 'Septamba', 'Oktoba', 'Nowamba', 'Dezamba'], + 'months_short' => ['Jan', 'Feb', 'Moz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Now', 'Dez'], + 'weekdays' => ['Sinndag', 'Mondag', 'Dingsdag', 'Meddwäakj', 'Donnadag', 'Friedag', 'Sinnowend'], + 'weekdays_short' => ['Sdg', 'Mdg', 'Dsg', 'Mwk', 'Ddg', 'Fdg', 'Swd'], + 'weekdays_min' => ['Sdg', 'Mdg', 'Dsg', 'Mwk', 'Ddg', 'Fdg', 'Swd'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy_NL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy_NL.php new file mode 100644 index 0000000..01cc96c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/fy_NL.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/fy.php', [ + 'formats' => [ + 'L' => 'DD-MM-YY', + ], + 'months' => ['Jannewaris', 'Febrewaris', 'Maart', 'April', 'Maaie', 'Juny', 'July', 'Augustus', 'Septimber', 'Oktober', 'Novimber', 'Desimber'], + 'months_short' => ['Jan', 'Feb', 'Mrt', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Snein', 'Moandei', 'Tiisdei', 'Woansdei', 'Tongersdei', 'Freed', 'Sneon'], + 'weekdays_short' => ['Sn', 'Mo', 'Ti', 'Wo', 'To', 'Fr', 'Sn'], + 'weekdays_min' => ['Sn', 'Mo', 'Ti', 'Wo', 'To', 'Fr', 'Sn'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ga.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ga.php new file mode 100644 index 0000000..9f07a26 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ga.php @@ -0,0 +1,77 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Thanks to André Silva : https://github.com/askpt + */ + +return [ + 'year' => ':count bliain', + 'a_year' => '{1}bliain|:count bliain', + 'y' => ':countb', + 'month' => ':count mí', + 'a_month' => '{1}mí|:count mí', + 'm' => ':countm', + 'week' => ':count sheachtain', + 'a_week' => '{1}sheachtain|:count sheachtain', + 'w' => ':countsh', + 'day' => ':count lá', + 'a_day' => '{1}lá|:count lá', + 'd' => ':countl', + 'hour' => ':count uair an chloig', + 'a_hour' => '{1}uair an chloig|:count uair an chloig', + 'h' => ':countu', + 'minute' => ':count nóiméad', + 'a_minute' => '{1}nóiméad|:count nóiméad', + 'min' => ':countn', + 'second' => ':count soicind', + 'a_second' => '{1}cúpla soicind|:count soicind', + 's' => ':countso', + 'ago' => ':time ó shin', + 'from_now' => 'i :time', + 'after' => ':time tar éis', + 'before' => ':time roimh', + 'diff_now' => 'anois', + 'diff_today' => 'Inniu', + 'diff_today_regexp' => 'Inniu(?:\\s+ag)?', + 'diff_yesterday' => 'inné', + 'diff_yesterday_regexp' => 'Inné(?:\\s+aig)?', + 'diff_tomorrow' => 'amárach', + 'diff_tomorrow_regexp' => 'Amárach(?:\\s+ag)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Inniu ag] LT', + 'nextDay' => '[Amárach ag] LT', + 'nextWeek' => 'dddd [ag] LT', + 'lastDay' => '[Inné aig] LT', + 'lastWeek' => 'dddd [seo caite] [ag] LT', + 'sameElse' => 'L', + ], + 'months' => ['Eanáir', 'Feabhra', 'Márta', 'Aibreán', 'Bealtaine', 'Méitheamh', 'Iúil', 'Lúnasa', 'Meán Fómhair', 'Deaireadh Fómhair', 'Samhain', 'Nollaig'], + 'months_short' => ['Eaná', 'Feab', 'Márt', 'Aibr', 'Beal', 'Méit', 'Iúil', 'Lúna', 'Meán', 'Deai', 'Samh', 'Noll'], + 'weekdays' => ['Dé Domhnaigh', 'Dé Luain', 'Dé Máirt', 'Dé Céadaoin', 'Déardaoin', 'Dé hAoine', 'Dé Satharn'], + 'weekdays_short' => ['Dom', 'Lua', 'Mái', 'Céa', 'Déa', 'hAo', 'Sat'], + 'weekdays_min' => ['Do', 'Lu', 'Má', 'Ce', 'Dé', 'hA', 'Sa'], + 'ordinal' => function ($number) { + return $number.($number === 1 ? 'd' : ($number % 10 === 2 ? 'na' : 'mh')); + }, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' agus '], + 'meridiem' => ['r.n.', 'i.n.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ga_IE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ga_IE.php new file mode 100644 index 0000000..57b0c4f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ga_IE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ga.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gd.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gd.php new file mode 100644 index 0000000..63d064d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gd.php @@ -0,0 +1,75 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Jon Ashdown + */ +return [ + 'year' => ':count bliadhna', + 'a_year' => '{1}bliadhna|:count bliadhna', + 'y' => ':count b.', + 'month' => ':count mìosan', + 'a_month' => '{1}mìos|:count mìosan', + 'm' => ':count ms.', + 'week' => ':count seachdainean', + 'a_week' => '{1}seachdain|:count seachdainean', + 'w' => ':count s.', + 'day' => ':count latha', + 'a_day' => '{1}latha|:count latha', + 'd' => ':count l.', + 'hour' => ':count uairean', + 'a_hour' => '{1}uair|:count uairean', + 'h' => ':count u.', + 'minute' => ':count mionaidean', + 'a_minute' => '{1}mionaid|:count mionaidean', + 'min' => ':count md.', + 'second' => ':count diogan', + 'a_second' => '{1}beagan diogan|:count diogan', + 's' => ':count d.', + 'ago' => 'bho chionn :time', + 'from_now' => 'ann an :time', + 'diff_yesterday' => 'An-dè', + 'diff_yesterday_regexp' => 'An-dè(?:\\s+aig)?', + 'diff_today' => 'An-diugh', + 'diff_today_regexp' => 'An-diugh(?:\\s+aig)?', + 'diff_tomorrow' => 'A-màireach', + 'diff_tomorrow_regexp' => 'A-màireach(?:\\s+aig)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[An-diugh aig] LT', + 'nextDay' => '[A-màireach aig] LT', + 'nextWeek' => 'dddd [aig] LT', + 'lastDay' => '[An-dè aig] LT', + 'lastWeek' => 'dddd [seo chaidh] [aig] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + return $number.($number === 1 ? 'd' : ($number % 10 === 2 ? 'na' : 'mh')); + }, + 'months' => ['Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd'], + 'months_short' => ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh'], + 'weekdays' => ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne'], + 'weekdays_short' => ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis'], + 'weekdays_min' => ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' agus '], + 'meridiem' => ['m', 'f'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gd_GB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gd_GB.php new file mode 100644 index 0000000..4fc26b3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gd_GB.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/gd.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez.php new file mode 100644 index 0000000..b8a2f0e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/gez_ER.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez_ER.php new file mode 100644 index 0000000..f19d1df --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez_ER.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጠሐረ', 'ከተተ', 'መገበ', 'አኀዘ', 'ግንባት', 'ሠንየ', 'ሐመለ', 'ነሐሰ', 'ከረመ', 'ጠቀመ', 'ኀደረ', 'ኀሠሠ'], + 'months_short' => ['ጠሐረ', 'ከተተ', 'መገበ', 'አኀዘ', 'ግንባ', 'ሠንየ', 'ሐመለ', 'ነሐሰ', 'ከረመ', 'ጠቀመ', 'ኀደረ', 'ኀሠሠ'], + 'weekdays' => ['እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚት'], + 'weekdays_short' => ['እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚ'], + 'weekdays_min' => ['እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚ'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ጽባሕ', 'ምሴት'], + + 'month' => ':count ወርሕ', // less reliable + 'm' => ':count ወርሕ', // less reliable + 'a_month' => ':count ወርሕ', // less reliable + + 'week' => ':count ሰብዑ', // less reliable + 'w' => ':count ሰብዑ', // less reliable + 'a_week' => ':count ሰብዑ', // less reliable + + 'hour' => ':count አንትሙ', // less reliable + 'h' => ':count አንትሙ', // less reliable + 'a_hour' => ':count አንትሙ', // less reliable + + 'minute' => ':count ንኡስ', // less reliable + 'min' => ':count ንኡስ', // less reliable + 'a_minute' => ':count ንኡስ', // less reliable + + 'year' => ':count ዓመት', + 'y' => ':count ዓመት', + 'a_year' => ':count ዓመት', + + 'day' => ':count ዕለት', + 'd' => ':count ዕለት', + 'a_day' => ':count ዕለት', + + 'second' => ':count ካልእ', + 's' => ':count ካልእ', + 'a_second' => ':count ካልእ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez_ET.php new file mode 100644 index 0000000..3933009 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gez_ET.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር'], + 'months_short' => ['ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም'], + 'weekdays' => ['እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚት'], + 'weekdays_short' => ['እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚ'], + 'weekdays_min' => ['እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚ'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ጽባሕ', 'ምሴት'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gl.php new file mode 100644 index 0000000..088b0f2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gl.php @@ -0,0 +1,98 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Fidel Pita + * - JD Isaacks + * - Diego Vilariño + * - Sebastian Thierer + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count ano|:count anos', + 'a_year' => 'un ano|:count anos', + 'y' => ':count a.', + 'month' => ':count mes|:count meses', + 'a_month' => 'un mes|:count meses', + 'm' => ':count mes.', + 'week' => ':count semana|:count semanas', + 'a_week' => 'unha semana|:count semanas', + 'w' => ':count sem.', + 'day' => ':count día|:count días', + 'a_day' => 'un día|:count días', + 'd' => ':count d.', + 'hour' => ':count hora|:count horas', + 'a_hour' => 'unha hora|:count horas', + 'h' => ':count h.', + 'minute' => ':count minuto|:count minutos', + 'a_minute' => 'un minuto|:count minutos', + 'min' => ':count min.', + 'second' => ':count segundo|:count segundos', + 'a_second' => 'uns segundos|:count segundos', + 's' => ':count seg.', + 'ago' => 'hai :time', + 'from_now' => function ($time) { + if (str_starts_with($time, 'un')) { + return "n$time"; + } + + return "en $time"; + }, + 'diff_now' => 'agora', + 'diff_today' => 'hoxe', + 'diff_today_regexp' => 'hoxe(?:\\s+ás)?', + 'diff_yesterday' => 'onte', + 'diff_yesterday_regexp' => 'onte(?:\\s+á)?', + 'diff_tomorrow' => 'mañá', + 'diff_tomorrow_regexp' => 'mañá(?:\\s+ás)?', + 'after' => ':time despois', + 'before' => ':time antes', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D [de] MMMM [de] YYYY', + 'LLL' => 'D [de] MMMM [de] YYYY H:mm', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => function (CarbonInterface $current) { + return '[hoxe '.($current->hour !== 1 ? 'ás' : 'á').'] LT'; + }, + 'nextDay' => function (CarbonInterface $current) { + return '[mañá '.($current->hour !== 1 ? 'ás' : 'á').'] LT'; + }, + 'nextWeek' => function (CarbonInterface $current) { + return 'dddd ['.($current->hour !== 1 ? 'ás' : 'á').'] LT'; + }, + 'lastDay' => function (CarbonInterface $current) { + return '[onte '.($current->hour !== 1 ? 'á' : 'a').'] LT'; + }, + 'lastWeek' => function (CarbonInterface $current) { + return '[o] dddd [pasado '.($current->hour !== 1 ? 'ás' : 'á').'] LT'; + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':numberº', + 'months' => ['xaneiro', 'febreiro', 'marzo', 'abril', 'maio', 'xuño', 'xullo', 'agosto', 'setembro', 'outubro', 'novembro', 'decembro'], + 'months_short' => ['xan.', 'feb.', 'mar.', 'abr.', 'mai.', 'xuñ.', 'xul.', 'ago.', 'set.', 'out.', 'nov.', 'dec.'], + 'weekdays' => ['domingo', 'luns', 'martes', 'mércores', 'xoves', 'venres', 'sábado'], + 'weekdays_short' => ['dom.', 'lun.', 'mar.', 'mér.', 'xov.', 'ven.', 'sáb.'], + 'weekdays_min' => ['do', 'lu', 'ma', 'mé', 'xo', 've', 'sá'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' e '], + 'meridiem' => ['a.m.', 'p.m.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gl_ES.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gl_ES.php new file mode 100644 index 0000000..9d6c1d9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gl_ES.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/gl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gom.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gom.php new file mode 100644 index 0000000..2a0584f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gom.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/gom_Latn.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gom_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gom_Latn.php new file mode 100644 index 0000000..612bb88 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gom_Latn.php @@ -0,0 +1,79 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return [ + 'year' => ':count voros|:count vorsam', + 'y' => ':countv', + 'month' => ':count mhoino|:count mhoine', + 'm' => ':countmh', + 'week' => ':count satolleacho|:count satolleache', + 'w' => ':countsa|:countsa', + 'day' => ':count dis', + 'd' => ':countd', + 'hour' => ':count hor|:count horam', + 'h' => ':counth', + 'minute' => ':count minute|:count mintam', + 'min' => ':countm', + 'second' => ':count second', + 's' => ':counts', + + 'diff_today' => 'Aiz', + 'diff_yesterday' => 'Kal', + 'diff_tomorrow' => 'Faleam', + 'formats' => [ + 'LT' => 'A h:mm [vazta]', + 'LTS' => 'A h:mm:ss [vazta]', + 'L' => 'DD-MM-YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY A h:mm [vazta]', + 'LLLL' => 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]', + 'llll' => 'ddd, D MMM YYYY, A h:mm [vazta]', + ], + + 'calendar' => [ + 'sameDay' => '[Aiz] LT', + 'nextDay' => '[Faleam] LT', + 'nextWeek' => '[Ieta to] dddd[,] LT', + 'lastDay' => '[Kal] LT', + 'lastWeek' => '[Fatlo] dddd[,] LT', + 'sameElse' => 'L', + ], + + 'months' => ['Janer', 'Febrer', 'Mars', 'Abril', 'Mai', 'Jun', 'Julai', 'Agost', 'Setembr', 'Otubr', 'Novembr', 'Dezembr'], + 'months_short' => ['Jan.', 'Feb.', 'Mars', 'Abr.', 'Mai', 'Jun', 'Jul.', 'Ago.', 'Set.', 'Otu.', 'Nov.', 'Dez.'], + 'weekdays' => ['Aitar', 'Somar', 'Mongllar', 'Budvar', 'Brestar', 'Sukrar', 'Son\'var'], + 'weekdays_short' => ['Ait.', 'Som.', 'Mon.', 'Bud.', 'Bre.', 'Suk.', 'Son.'], + 'weekdays_min' => ['Ai', 'Sm', 'Mo', 'Bu', 'Br', 'Su', 'Sn'], + + 'ordinal' => function ($number, $period) { + return $number.($period === 'D' ? 'er' : ''); + }, + + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'rati'; + } + if ($hour < 12) { + return 'sokalli'; + } + if ($hour < 16) { + return 'donparam'; + } + if ($hour < 20) { + return 'sanje'; + } + + return 'rati'; + }, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' ani '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw.php new file mode 100644 index 0000000..c5c850e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Christopher Dell + * - Akira Matsuda + * - Enrique Vidal + * - Simone Carletti + * - Henning Kiel + * - Aaron Patterson + * - Florian Hanke + */ +return [ + 'year' => ':count Johr', + 'month' => ':count Monet', + 'week' => ':count Woche', + 'day' => ':count Tag', + 'hour' => ':count Schtund', + 'minute' => ':count Minute', + 'second' => ':count Sekunde', + 'weekdays' => ['Sunntig', 'Mäntig', 'Ziischtig', 'Mittwuch', 'Dunschtig', 'Friitig', 'Samschtig'], + 'weekdays_short' => ['Su', 'Mä', 'Zi', 'Mi', 'Du', 'Fr', 'Sa'], + 'weekdays_min' => ['Su', 'Mä', 'Zi', 'Mi', 'Du', 'Fr', 'Sa'], + 'months' => ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'Auguscht', 'September', 'Oktober', 'November', 'Dezember'], + 'months_short' => ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], + 'meridiem' => ['am Vormittag', 'am Namittag'], + 'ordinal' => ':number.', + 'list' => [', ', ' und '], + 'diff_now' => 'now', + 'diff_yesterday' => 'geschter', + 'diff_tomorrow' => 'moorn', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'Do MMMM YYYY', + 'LLL' => 'Do MMMM, HH:mm [Uhr]', + 'LLLL' => 'dddd, Do MMMM YYYY, HH:mm [Uhr]', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_CH.php new file mode 100644 index 0000000..594eb25 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_CH.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/gsw.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_FR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_FR.php new file mode 100644 index 0000000..3581dcf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_FR.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/gsw.php', [ + 'meridiem' => ['vorm.', 'nam.'], + 'months' => ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'Auguscht', 'Septämber', 'Oktoober', 'Novämber', 'Dezämber'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LLL' => 'Do MMMM YYYY HH:mm', + 'LLLL' => 'dddd, Do MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_LI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_LI.php new file mode 100644 index 0000000..3581dcf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gsw_LI.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/gsw.php', [ + 'meridiem' => ['vorm.', 'nam.'], + 'months' => ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'Auguscht', 'Septämber', 'Oktoober', 'Novämber', 'Dezämber'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LLL' => 'Do MMMM YYYY HH:mm', + 'LLLL' => 'dddd, Do MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gu.php new file mode 100644 index 0000000..8bc4311 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gu.php @@ -0,0 +1,82 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Kaushik Thanki + * - Josh Soref + */ +return [ + 'year' => 'એક વર્ષ|:count વર્ષ', + 'y' => ':countવર્ષ|:countવર્ષો', + 'month' => 'એક મહિનો|:count મહિના', + 'm' => ':countમહિનો|:countમહિના', + 'week' => ':count અઠવાડિયું|:count અઠવાડિયા', + 'w' => ':countઅઠ.|:countઅઠ.', + 'day' => 'એક દિવસ|:count દિવસ', + 'd' => ':countદિ.|:countદિ.', + 'hour' => 'એક કલાક|:count કલાક', + 'h' => ':countક.|:countક.', + 'minute' => 'એક મિનિટ|:count મિનિટ', + 'min' => ':countમિ.|:countમિ.', + 'second' => 'અમુક પળો|:count સેકંડ', + 's' => ':countસે.|:countસે.', + 'ago' => ':time પેહલા', + 'from_now' => ':time મા', + 'after' => ':time પછી', + 'before' => ':time પહેલા', + 'diff_now' => 'હમણાં', + 'diff_today' => 'આજ', + 'diff_yesterday' => 'ગઇકાલે', + 'diff_tomorrow' => 'કાલે', + 'formats' => [ + 'LT' => 'A h:mm વાગ્યે', + 'LTS' => 'A h:mm:ss વાગ્યે', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm વાગ્યે', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm વાગ્યે', + ], + 'calendar' => [ + 'sameDay' => '[આજ] LT', + 'nextDay' => '[કાલે] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[ગઇકાલે] LT', + 'lastWeek' => '[પાછલા] dddd, LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'રાત'; + } + if ($hour < 10) { + return 'સવાર'; + } + if ($hour < 17) { + return 'બપોર'; + } + if ($hour < 20) { + return 'સાંજ'; + } + + return 'રાત'; + }, + 'months' => ['જાન્યુઆરી', 'ફેબ્રુઆરી', 'માર્ચ', 'એપ્રિલ', 'મે', 'જૂન', 'જુલાઈ', 'ઑગસ્ટ', 'સપ્ટેમ્બર', 'ઑક્ટ્બર', 'નવેમ્બર', 'ડિસેમ્બર'], + 'months_short' => ['જાન્યુ.', 'ફેબ્રુ.', 'માર્ચ', 'એપ્રિ.', 'મે', 'જૂન', 'જુલા.', 'ઑગ.', 'સપ્ટે.', 'ઑક્ટ્.', 'નવે.', 'ડિસે.'], + 'weekdays' => ['રવિવાર', 'સોમવાર', 'મંગળવાર', 'બુધ્વાર', 'ગુરુવાર', 'શુક્રવાર', 'શનિવાર'], + 'weekdays_short' => ['રવિ', 'સોમ', 'મંગળ', 'બુધ્', 'ગુરુ', 'શુક્ર', 'શનિ'], + 'weekdays_min' => ['ર', 'સો', 'મં', 'બુ', 'ગુ', 'શુ', 'શ'], + 'list' => [', ', ' અને '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gu_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gu_IN.php new file mode 100644 index 0000000..02654b1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gu_IN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/gu.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/guz.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/guz.php new file mode 100644 index 0000000..6230165 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/guz.php @@ -0,0 +1,47 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Ma', 'Mo'], + 'weekdays' => ['Chumapiri', 'Chumatato', 'Chumaine', 'Chumatano', 'Aramisi', 'Ichuma', 'Esabato'], + 'weekdays_short' => ['Cpr', 'Ctt', 'Cmn', 'Cmt', 'Ars', 'Icm', 'Est'], + 'weekdays_min' => ['Cpr', 'Ctt', 'Cmn', 'Cmt', 'Ars', 'Icm', 'Est'], + 'months' => ['Chanuari', 'Feburari', 'Machi', 'Apiriri', 'Mei', 'Juni', 'Chulai', 'Agosti', 'Septemba', 'Okitoba', 'Nobemba', 'Disemba'], + 'months_short' => ['Can', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Cul', 'Agt', 'Sep', 'Okt', 'Nob', 'Dis'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'month' => ':count omotunyi', // less reliable + 'm' => ':count omotunyi', // less reliable + 'a_month' => ':count omotunyi', // less reliable + + 'week' => ':count isano naibere', // less reliable + 'w' => ':count isano naibere', // less reliable + 'a_week' => ':count isano naibere', // less reliable + + 'second' => ':count ibere', // less reliable + 's' => ':count ibere', // less reliable + 'a_second' => ':count ibere', // less reliable + + 'year' => ':count omwaka', + 'y' => ':count omwaka', + 'a_year' => ':count omwaka', + + 'day' => ':count rituko', + 'd' => ':count rituko', + 'a_day' => ':count rituko', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gv.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gv.php new file mode 100644 index 0000000..7c52b94 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gv.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/gv_GB.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gv_GB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gv_GB.php new file mode 100644 index 0000000..6b1168f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/gv_GB.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Alastair McKinstry bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Jerrey-geuree', 'Toshiaght-arree', 'Mayrnt', 'Averil', 'Boaldyn', 'Mean-souree', 'Jerrey-souree', 'Luanistyn', 'Mean-fouyir', 'Jerrey-fouyir', 'Mee Houney', 'Mee ny Nollick'], + 'months_short' => ['J-guer', 'T-arree', 'Mayrnt', 'Avrril', 'Boaldyn', 'M-souree', 'J-souree', 'Luanistyn', 'M-fouyir', 'J-fouyir', 'M.Houney', 'M.Nollick'], + 'weekdays' => ['Jedoonee', 'Jelhein', 'Jemayrt', 'Jercean', 'Jerdein', 'Jeheiney', 'Jesarn'], + 'weekdays_short' => ['Jed', 'Jel', 'Jem', 'Jerc', 'Jerd', 'Jeh', 'Jes'], + 'weekdays_min' => ['Jed', 'Jel', 'Jem', 'Jerc', 'Jerd', 'Jeh', 'Jes'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count blein', + 'y' => ':count blein', + 'a_year' => ':count blein', + + 'month' => ':count mee', + 'm' => ':count mee', + 'a_month' => ':count mee', + + 'week' => ':count shiaghtin', + 'w' => ':count shiaghtin', + 'a_week' => ':count shiaghtin', + + 'day' => ':count laa', + 'd' => ':count laa', + 'a_day' => ':count laa', + + 'hour' => ':count oor', + 'h' => ':count oor', + 'a_hour' => ':count oor', + + 'minute' => ':count feer veg', + 'min' => ':count feer veg', + 'a_minute' => ':count feer veg', + + 'second' => ':count derrey', + 's' => ':count derrey', + 'a_second' => ':count derrey', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha.php new file mode 100644 index 0000000..cd8e34d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - pablo@mandriva.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM, YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM, YYYY HH:mm', + ], + 'months' => ['Janairu', 'Faburairu', 'Maris', 'Afirilu', 'Mayu', 'Yuni', 'Yuli', 'Agusta', 'Satumba', 'Oktoba', 'Nuwamba', 'Disamba'], + 'months_short' => ['Jan', 'Fab', 'Mar', 'Afi', 'May', 'Yun', 'Yul', 'Agu', 'Sat', 'Okt', 'Nuw', 'Dis'], + 'weekdays' => ['Lahadi', 'Litini', 'Talata', 'Laraba', 'Alhamis', 'Jumaʼa', 'Asabar'], + 'weekdays_short' => ['Lah', 'Lit', 'Tal', 'Lar', 'Alh', 'Jum', 'Asa'], + 'weekdays_min' => ['Lh', 'Li', 'Ta', 'Lr', 'Al', 'Ju', 'As'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => 'shekara :count', + 'y' => 'shekara :count', + 'a_year' => 'shekara :count', + + 'month' => ':count wátàa', + 'm' => ':count wátàa', + 'a_month' => ':count wátàa', + + 'week' => ':count mako', + 'w' => ':count mako', + 'a_week' => ':count mako', + + 'day' => ':count rana', + 'd' => ':count rana', + 'a_day' => ':count rana', + + 'hour' => ':count áwàa', + 'h' => ':count áwàa', + 'a_hour' => ':count áwàa', + + 'minute' => 'minti :count', + 'min' => 'minti :count', + 'a_minute' => 'minti :count', + + 'second' => ':count ná bíyú', + 's' => ':count ná bíyú', + 'a_second' => ':count ná bíyú', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_GH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_GH.php new file mode 100644 index 0000000..f9f99a7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_GH.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ha.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_NE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_NE.php new file mode 100644 index 0000000..f9f99a7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_NE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ha.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_NG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_NG.php new file mode 100644 index 0000000..f9f99a7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ha_NG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ha.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hak.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hak.php new file mode 100644 index 0000000..6c3260e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hak.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/hak_TW.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hak_TW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hak_TW.php new file mode 100644 index 0000000..fe23986 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hak_TW.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY年MM月DD日', + ], + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => [' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月'], + 'weekdays' => ['禮拜日', '禮拜一', '禮拜二', '禮拜三', '禮拜四', '禮拜五', '禮拜六'], + 'weekdays_short' => ['日', '一', '二', '三', '四', '五', '六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['上晝', '下晝'], + + 'year' => ':count ngien11', + 'y' => ':count ngien11', + 'a_year' => ':count ngien11', + + 'month' => ':count ngie̍t', + 'm' => ':count ngie̍t', + 'a_month' => ':count ngie̍t', + + 'week' => ':count lî-pai', + 'w' => ':count lî-pai', + 'a_week' => ':count lî-pai', + + 'day' => ':count ngit', + 'd' => ':count ngit', + 'a_day' => ':count ngit', + + 'hour' => ':count sṳ̀', + 'h' => ':count sṳ̀', + 'a_hour' => ':count sṳ̀', + + 'minute' => ':count fûn', + 'min' => ':count fûn', + 'a_minute' => ':count fûn', + + 'second' => ':count miéu', + 's' => ':count miéu', + 'a_second' => ':count miéu', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/haw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/haw.php new file mode 100644 index 0000000..cdd3686 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/haw.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'months' => ['Ianuali', 'Pepeluali', 'Malaki', 'ʻApelila', 'Mei', 'Iune', 'Iulai', 'ʻAukake', 'Kepakemapa', 'ʻOkakopa', 'Nowemapa', 'Kekemapa'], + 'months_short' => ['Ian.', 'Pep.', 'Mal.', 'ʻAp.', 'Mei', 'Iun.', 'Iul.', 'ʻAu.', 'Kep.', 'ʻOk.', 'Now.', 'Kek.'], + 'weekdays' => ['Lāpule', 'Poʻakahi', 'Poʻalua', 'Poʻakolu', 'Poʻahā', 'Poʻalima', 'Poʻaono'], + 'weekdays_short' => ['LP', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6'], + 'weekdays_min' => ['S', 'M', 'T', 'W', 'T', 'F', 'S'], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd, D MMMM YYYY h:mm a', + ], + + 'year' => ':count makahiki', + 'y' => ':count makahiki', + 'a_year' => ':count makahiki', + + 'month' => ':count mahina', + 'm' => ':count mahina', + 'a_month' => ':count mahina', + + 'week' => ':count pule', + 'w' => ':count pule', + 'a_week' => ':count pule', + + 'day' => ':count lā', + 'd' => ':count lā', + 'a_day' => ':count lā', + + 'hour' => ':count hola', + 'h' => ':count hola', + 'a_hour' => ':count hola', + + 'minute' => ':count minuke', + 'min' => ':count minuke', + 'a_minute' => ':count minuke', + + 'second' => ':count lua', + 's' => ':count lua', + 'a_second' => ':count lua', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/he.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/he.php new file mode 100644 index 0000000..c3fb3e9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/he.php @@ -0,0 +1,86 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Daniel Cohen Gindi + * - JD Isaacks + * - Itai Nathaniel + * - GabMic + * - Yaakov Dahan (yakidahan) + */ +return [ + 'year' => 'שנה|{2}שנתיים|:count שנים', + 'y' => 'שנה|:count שנ׳', + 'month' => 'חודש|{2}חודשיים|:count חודשים', + 'm' => 'חודש|:count חו׳', + 'week' => 'שבוע|{2}שבועיים|:count שבועות', + 'w' => 'שבוע|:count שב׳', + 'day' => 'יום|{2}יומיים|:count ימים', + 'd' => 'יום|:count ימ׳', + 'hour' => 'שעה|{2}שעתיים|:count שעות', + 'h' => 'שעה|:count שע׳', + 'minute' => 'דקה|{2}שתי דקות|:count דקות', + 'min' => 'דקה|:count דק׳', + 'second' => 'שנייה|:count שניות', + 'a_second' => 'כמה שניות|:count שניות', + 's' => 'שניה|:count שנ׳', + 'ago' => 'לפני :time', + 'from_now' => 'בעוד :time מעכשיו', + 'after' => 'אחרי :time', + 'before' => 'לפני :time', + 'diff_now' => 'עכשיו', + 'diff_today' => 'היום', + 'diff_today_regexp' => 'היום(?:\\s+ב־)?', + 'diff_yesterday' => 'אתמול', + 'diff_yesterday_regexp' => 'אתמול(?:\\s+ב־)?', + 'diff_tomorrow' => 'מחר', + 'diff_tomorrow_regexp' => 'מחר(?:\\s+ב־)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D [ב]MMMM YYYY', + 'LLL' => 'D [ב]MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D [ב]MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[היום ב־]LT', + 'nextDay' => '[מחר ב־]LT', + 'nextWeek' => 'dddd [בשעה] LT', + 'lastDay' => '[אתמול ב־]LT', + 'lastWeek' => '[ביום] dddd [האחרון בשעה] LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour, $minute, $isLower) { + if ($hour < 5) { + return 'לפנות בוקר'; + } + if ($hour < 10) { + return 'בבוקר'; + } + if ($hour < 12) { + return $isLower ? 'לפנה"צ' : 'לפני הצהריים'; + } + if ($hour < 18) { + return $isLower ? 'אחה"צ' : 'אחרי הצהריים'; + } + + return 'בערב'; + }, + 'months' => ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'], + 'months_short' => ['ינו׳', 'פבר׳', 'מרץ', 'אפר׳', 'מאי', 'יוני', 'יולי', 'אוג׳', 'ספט׳', 'אוק׳', 'נוב׳', 'דצמ׳'], + 'weekdays' => ['ראשון', 'שני', 'שלישי', 'רביעי', 'חמישי', 'שישי', 'שבת'], + 'weekdays_short' => ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳', 'ש׳'], + 'weekdays_min' => ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ש'], + 'list' => [', ', ' ו -'], + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/he_IL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/he_IL.php new file mode 100644 index 0000000..14fab3e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/he_IL.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/he.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hi.php new file mode 100644 index 0000000..70c57a2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hi.php @@ -0,0 +1,82 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - abhimanyu003 + * - Josh Soref + * - JD Isaacks + */ +return [ + 'year' => 'एक वर्ष|:count वर्ष', + 'y' => '1 वर्ष|:count वर्षों', + 'month' => 'एक महीने|:count महीने', + 'm' => '1 माह|:count महीने', + 'week' => '1 सप्ताह|:count सप्ताह', + 'w' => '1 सप्ताह|:count सप्ताह', + 'day' => 'एक दिन|:count दिन', + 'd' => '1 दिन|:count दिनों', + 'hour' => 'एक घंटा|:count घंटे', + 'h' => '1 घंटा|:count घंटे', + 'minute' => 'एक मिनट|:count मिनट', + 'min' => '1 मिनट|:count मिनटों', + 'second' => 'कुछ ही क्षण|:count सेकंड', + 's' => '1 सेकंड|:count सेकंड', + 'ago' => ':time पहले', + 'from_now' => ':time में', + 'after' => ':time के बाद', + 'before' => ':time के पहले', + 'diff_now' => 'अब', + 'diff_today' => 'आज', + 'diff_yesterday' => 'कल', + 'diff_tomorrow' => 'कल', + 'formats' => [ + 'LT' => 'A h:mm बजे', + 'LTS' => 'A h:mm:ss बजे', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm बजे', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm बजे', + ], + 'calendar' => [ + 'sameDay' => '[आज] LT', + 'nextDay' => '[कल] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[कल] LT', + 'lastWeek' => '[पिछले] dddd, LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'रात'; + } + if ($hour < 10) { + return 'सुबह'; + } + if ($hour < 17) { + return 'दोपहर'; + } + if ($hour < 20) { + return 'शाम'; + } + + return 'रात'; + }, + 'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'months_short' => ['जन.', 'फ़र.', 'मार्च', 'अप्रै.', 'मई', 'जून', 'जुल.', 'अग.', 'सित.', 'अक्टू.', 'नव.', 'दिस.'], + 'weekdays' => ['रविवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'गुरूवार', 'शुक्रवार', 'शनिवार'], + 'weekdays_short' => ['रवि', 'सोम', 'मंगल', 'बुध', 'गुरू', 'शुक्र', 'शनि'], + 'weekdays_min' => ['र', 'सो', 'मं', 'बु', 'गु', 'शु', 'श'], + 'list' => [', ', ' और '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hi_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hi_IN.php new file mode 100644 index 0000000..749dd97 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hi_IN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/hi.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hif.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hif.php new file mode 100644 index 0000000..65791dd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hif.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/hif_FJ.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hif_FJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hif_FJ.php new file mode 100644 index 0000000..30ad5e7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hif_FJ.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Samsung Electronics Co., Ltd. akhilesh.k@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'dddd DD MMM YYYY', + ], + 'months' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + 'weekdays' => ['Ravivar', 'Somvar', 'Mangalvar', 'Budhvar', 'Guruvar', 'Shukravar', 'Shanivar'], + 'weekdays_short' => ['Ravi', 'Som', 'Mangal', 'Budh', 'Guru', 'Shukra', 'Shani'], + 'weekdays_min' => ['Ravi', 'Som', 'Mangal', 'Budh', 'Guru', 'Shukra', 'Shani'], + 'meridiem' => ['Purvahan', 'Aparaahna'], + + 'hour' => ':count minit', // less reliable + 'h' => ':count minit', // less reliable + 'a_hour' => ':count minit', // less reliable + + 'year' => ':count saal', + 'y' => ':count saal', + 'a_year' => ':count saal', + + 'month' => ':count Mahina', + 'm' => ':count Mahina', + 'a_month' => ':count Mahina', + + 'week' => ':count Hafta', + 'w' => ':count Hafta', + 'a_week' => ':count Hafta', + + 'day' => ':count Din', + 'd' => ':count Din', + 'a_day' => ':count Din', + + 'minute' => ':count Minit', + 'min' => ':count Minit', + 'a_minute' => ':count Minit', + + 'second' => ':count Second', + 's' => ':count Second', + 'a_second' => ':count Second', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hne.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hne.php new file mode 100644 index 0000000..4bcb05c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hne.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/hne_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hne_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hne_IN.php new file mode 100644 index 0000000..a5ca758 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hne_IN.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat, Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अपरेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितमबर', 'अकटूबर', 'नवमबर', 'दिसमबर'], + 'months_short' => ['जन', 'फर', 'मार्च', 'अप', 'मई', 'जून', 'जुला', 'अग', 'सित', 'अकटू', 'नव', 'दिस'], + 'weekdays' => ['इतवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'बिरसपत', 'सुकरवार', 'सनिवार'], + 'weekdays_short' => ['इत', 'सोम', 'मंग', 'बुध', 'बिर', 'सुक', 'सनि'], + 'weekdays_min' => ['इत', 'सोम', 'मंग', 'बुध', 'बिर', 'सुक', 'सनि'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['बिहिनियाँ', 'मंझनियाँ'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr.php new file mode 100644 index 0000000..cfd85fd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr.php @@ -0,0 +1,111 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - Tim Fish + * - shaishavgandhi05 + * - Serhan Apaydın + * - JD Isaacks + * - tomhorvat + * - Josh Soref + * - François B + * - shaishavgandhi05 + * - Serhan Apaydın + * - JD Isaacks + * - tomhorvat + * - Stjepan Majdak + * - Vanja Retkovac (vr00) + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count godinu|:count godine|:count godina', + 'y' => ':count god.|:count god.|:count god.', + 'month' => ':count mjesec|:count mjeseca|:count mjeseci', + 'm' => ':count mj.|:count mj.|:count mj.', + 'week' => ':count tjedan|:count tjedna|:count tjedana', + 'w' => ':count tj.|:count tj.|:count tj.', + 'day' => ':count dan|:count dana|:count dana', + 'd' => ':count d.|:count d.|:count d.', + 'hour' => ':count sat|:count sata|:count sati', + 'h' => ':count sat|:count sata|:count sati', + 'minute' => ':count minutu|:count minute|:count minuta', + 'min' => ':count min.|:count min.|:count min.', + 'second' => ':count sekundu|:count sekunde|:count sekundi', + 'a_second' => 'nekoliko sekundi|:count sekunde|:count sekundi', + 's' => ':count sek.|:count sek.|:count sek.', + 'ago' => 'prije :time', + 'from_now' => 'za :time', + 'after' => ':time poslije', + 'before' => ':time prije', + 'diff_now' => 'sad', + 'diff_today' => 'danas', + 'diff_today_regexp' => 'danas(?:\\s+u)?', + 'diff_yesterday' => 'jučer', + 'diff_yesterday_regexp' => 'jučer(?:\\s+u)?', + 'diff_tomorrow' => 'sutra', + 'diff_tomorrow_regexp' => 'sutra(?:\\s+u)?', + 'diff_before_yesterday' => 'prekjučer', + 'diff_after_tomorrow' => 'prekosutra', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'D. M. YYYY.', + 'LL' => 'D. MMMM YYYY.', + 'LLL' => 'D. MMMM YYYY. H:mm', + 'LLLL' => 'dddd, D. MMMM YYYY. H:mm', + ], + 'calendar' => [ + 'sameDay' => '[danas u] LT', + 'nextDay' => '[sutra u] LT', + 'nextWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + default: + return '[u] dddd [u] LT'; + } + }, + 'lastDay' => '[jučer u] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + case 3: + return '[prošlu] dddd [u] LT'; + case 6: + return '[prošle] [subote] [u] LT'; + default: + return '[prošli] dddd [u] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['siječnja', 'veljače', 'ožujka', 'travnja', 'svibnja', 'lipnja', 'srpnja', 'kolovoza', 'rujna', 'listopada', 'studenoga', 'prosinca'], + 'months_standalone' => ['siječanj', 'veljača', 'ožujak', 'travanj', 'svibanj', 'lipanj', 'srpanj', 'kolovoz', 'rujan', 'listopad', 'studeni', 'prosinac'], + 'months_short' => ['sij.', 'velj.', 'ožu.', 'tra.', 'svi.', 'lip.', 'srp.', 'kol.', 'ruj.', 'lis.', 'stu.', 'pro.'], + 'months_regexp' => '/(D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['nedjelju', 'ponedjeljak', 'utorak', 'srijedu', 'četvrtak', 'petak', 'subotu'], + 'weekdays_standalone' => ['nedjelja', 'ponedjeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'], + 'weekdays_short' => ['ned.', 'pon.', 'uto.', 'sri.', 'čet.', 'pet.', 'sub.'], + 'weekdays_min' => ['ne', 'po', 'ut', 'sr', 'če', 'pe', 'su'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' i '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr_BA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr_BA.php new file mode 100644 index 0000000..7763a45 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr_BA.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - DarkoDevelop + */ +return array_replace_recursive(require __DIR__.'/hr.php', [ + 'weekdays' => ['nedjelja', 'ponedjeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'], + 'weekdays_short' => ['ned', 'pon', 'uto', 'sri', 'čet', 'pet', 'sub'], + 'weekdays_min' => ['ned', 'pon', 'uto', 'sri', 'čet', 'pet', 'sub'], + 'months' => ['siječnja', 'veljače', 'ožujka', 'travnja', 'svibnja', 'lipnja', 'srpnja', 'kolovoza', 'rujna', 'listopada', 'studenoga', 'prosinca'], + 'months_short' => ['sij', 'velj', 'ožu', 'tra', 'svi', 'lip', 'srp', 'kol', 'ruj', 'lis', 'stu', 'pro'], + 'months_standalone' => ['siječanj', 'veljača', 'ožujak', 'travanj', 'svibanj', 'lipanj', 'srpanj', 'kolovoz', 'rujan', 'listopad', 'studeni', 'prosinac'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D. M. yy.', + 'LL' => 'D. MMM YYYY.', + 'LLL' => 'D. MMMM YYYY. HH:mm', + 'LLLL' => 'dddd, D. MMMM YYYY. HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr_HR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr_HR.php new file mode 100644 index 0000000..db74d8c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hr_HR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/hr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hsb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hsb.php new file mode 100644 index 0000000..3537b8b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hsb.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/hsb_DE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hsb_DE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hsb_DE.php new file mode 100644 index 0000000..6ba2271 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hsb_DE.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Information from Michael Wolf Andrzej Krzysztofowicz ankry@mif.pg.gda.pl + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'DD. MMMM YYYY', + 'LLL' => 'DD. MMMM, HH:mm [hodź.]', + 'LLLL' => 'dddd, DD. MMMM YYYY, HH:mm [hodź.]', + ], + 'months' => ['januara', 'februara', 'měrca', 'apryla', 'meje', 'junija', 'julija', 'awgusta', 'septembra', 'oktobra', 'nowembra', 'decembra'], + 'months_short' => ['Jan', 'Feb', 'Měr', 'Apr', 'Mej', 'Jun', 'Jul', 'Awg', 'Sep', 'Okt', 'Now', 'Dec'], + 'weekdays' => ['Njedźela', 'Póndźela', 'Wutora', 'Srjeda', 'Štvórtk', 'Pjatk', 'Sobota'], + 'weekdays_short' => ['Nj', 'Pó', 'Wu', 'Sr', 'Št', 'Pj', 'So'], + 'weekdays_min' => ['Nj', 'Pó', 'Wu', 'Sr', 'Št', 'Pj', 'So'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count lěto', + 'y' => ':count lěto', + 'a_year' => ':count lěto', + + 'month' => ':count měsac', + 'm' => ':count měsac', + 'a_month' => ':count měsac', + + 'week' => ':count tydźeń', + 'w' => ':count tydźeń', + 'a_week' => ':count tydźeń', + + 'day' => ':count dźeń', + 'd' => ':count dźeń', + 'a_day' => ':count dźeń', + + 'hour' => ':count hodźina', + 'h' => ':count hodźina', + 'a_hour' => ':count hodźina', + + 'minute' => ':count chwila', + 'min' => ':count chwila', + 'a_minute' => ':count chwila', + + 'second' => ':count druhi', + 's' => ':count druhi', + 'a_second' => ':count druhi', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ht.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ht.php new file mode 100644 index 0000000..ebd12ad --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ht.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ht_HT.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ht_HT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ht_HT.php new file mode 100644 index 0000000..139b813 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ht_HT.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Sugar Labs // OLPC sugarlabs.org libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['janvye', 'fevriye', 'mas', 'avril', 'me', 'jen', 'jiyè', 'out', 'septanm', 'oktòb', 'novanm', 'desanm'], + 'months_short' => ['jan', 'fev', 'mas', 'avr', 'me', 'jen', 'jiy', 'out', 'sep', 'okt', 'nov', 'des'], + 'weekdays' => ['dimanch', 'lendi', 'madi', 'mèkredi', 'jedi', 'vandredi', 'samdi'], + 'weekdays_short' => ['dim', 'len', 'mad', 'mèk', 'jed', 'van', 'sam'], + 'weekdays_min' => ['dim', 'len', 'mad', 'mèk', 'jed', 'van', 'sam'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => ':count lane', + 'y' => ':count lane', + 'a_year' => ':count lane', + + 'month' => 'mwa :count', + 'm' => 'mwa :count', + 'a_month' => 'mwa :count', + + 'week' => 'semèn :count', + 'w' => 'semèn :count', + 'a_week' => 'semèn :count', + + 'day' => ':count jou', + 'd' => ':count jou', + 'a_day' => ':count jou', + + 'hour' => ':count lè', + 'h' => ':count lè', + 'a_hour' => ':count lè', + + 'minute' => ':count minit', + 'min' => ':count minit', + 'a_minute' => ':count minit', + + 'second' => ':count segonn', + 's' => ':count segonn', + 'a_second' => ':count segonn', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hu.php new file mode 100644 index 0000000..b7583ee --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hu.php @@ -0,0 +1,118 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Adam Brunner + * - Brett Johnson + * - balping + */ + +use Carbon\CarbonInterface; + +$huWeekEndings = ['vasárnap', 'hétfőn', 'kedden', 'szerdán', 'csütörtökön', 'pénteken', 'szombaton']; + +return [ + 'year' => ':count év', + 'y' => ':count év', + 'month' => ':count hónap', + 'm' => ':count hónap', + 'week' => ':count hét', + 'w' => ':count hét', + 'day' => ':count nap', + 'd' => ':count nap', + 'hour' => ':count óra', + 'h' => ':count óra', + 'minute' => ':count perc', + 'min' => ':count perc', + 'second' => ':count másodperc', + 's' => ':count másodperc', + 'ago' => ':time', + 'from_now' => ':time múlva', + 'after' => ':time később', + 'before' => ':time korábban', + 'year_ago' => ':count éve', + 'y_ago' => ':count éve', + 'month_ago' => ':count hónapja', + 'm_ago' => ':count hónapja', + 'week_ago' => ':count hete', + 'w_ago' => ':count hete', + 'day_ago' => ':count napja', + 'd_ago' => ':count napja', + 'hour_ago' => ':count órája', + 'h_ago' => ':count órája', + 'minute_ago' => ':count perce', + 'min_ago' => ':count perce', + 'second_ago' => ':count másodperce', + 's_ago' => ':count másodperce', + 'year_after' => ':count évvel', + 'y_after' => ':count évvel', + 'month_after' => ':count hónappal', + 'm_after' => ':count hónappal', + 'week_after' => ':count héttel', + 'w_after' => ':count héttel', + 'day_after' => ':count nappal', + 'd_after' => ':count nappal', + 'hour_after' => ':count órával', + 'h_after' => ':count órával', + 'minute_after' => ':count perccel', + 'min_after' => ':count perccel', + 'second_after' => ':count másodperccel', + 's_after' => ':count másodperccel', + 'year_before' => ':count évvel', + 'y_before' => ':count évvel', + 'month_before' => ':count hónappal', + 'm_before' => ':count hónappal', + 'week_before' => ':count héttel', + 'w_before' => ':count héttel', + 'day_before' => ':count nappal', + 'd_before' => ':count nappal', + 'hour_before' => ':count órával', + 'h_before' => ':count órával', + 'minute_before' => ':count perccel', + 'min_before' => ':count perccel', + 'second_before' => ':count másodperccel', + 's_before' => ':count másodperccel', + 'months' => ['január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december'], + 'months_short' => ['jan.', 'febr.', 'márc.', 'ápr.', 'máj.', 'jún.', 'júl.', 'aug.', 'szept.', 'okt.', 'nov.', 'dec.'], + 'weekdays' => ['vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat'], + 'weekdays_short' => ['vas', 'hét', 'kedd', 'sze', 'csüt', 'pén', 'szo'], + 'weekdays_min' => ['v', 'h', 'k', 'sze', 'cs', 'p', 'sz'], + 'ordinal' => ':number.', + 'diff_now' => 'most', + 'diff_today' => 'ma', + 'diff_yesterday' => 'tegnap', + 'diff_tomorrow' => 'holnap', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'YYYY.MM.DD.', + 'LL' => 'YYYY. MMMM D.', + 'LLL' => 'YYYY. MMMM D. H:mm', + 'LLLL' => 'YYYY. MMMM D., dddd H:mm', + ], + 'calendar' => [ + 'sameDay' => '[ma] LT[-kor]', + 'nextDay' => '[holnap] LT[-kor]', + 'nextWeek' => function (CarbonInterface $date) use ($huWeekEndings) { + return '['.$huWeekEndings[$date->dayOfWeek].'] LT[-kor]'; + }, + 'lastDay' => '[tegnap] LT[-kor]', + 'lastWeek' => function (CarbonInterface $date) use ($huWeekEndings) { + return '[múlt '.$huWeekEndings[$date->dayOfWeek].'] LT[-kor]'; + }, + 'sameElse' => 'L', + ], + 'meridiem' => ['DE', 'DU'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' és '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hu_HU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hu_HU.php new file mode 100644 index 0000000..b1c4854 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hu_HU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/hu.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hy.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hy.php new file mode 100644 index 0000000..8b12994 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hy.php @@ -0,0 +1,95 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - mhamlet + */ +return [ + 'year' => ':count տարի', + 'a_year' => 'տարի|:count տարի', + 'y' => ':countտ', + 'month' => ':count ամիս', + 'a_month' => 'ամիս|:count ամիս', + 'm' => ':countամ', + 'week' => ':count շաբաթ', + 'a_week' => 'շաբաթ|:count շաբաթ', + 'w' => ':countշ', + 'day' => ':count օր', + 'a_day' => 'օր|:count օր', + 'd' => ':countօր', + 'hour' => ':count ժամ', + 'a_hour' => 'ժամ|:count ժամ', + 'h' => ':countժ', + 'minute' => ':count րոպե', + 'a_minute' => 'րոպե|:count րոպե', + 'min' => ':countր', + 'second' => ':count վայրկյան', + 'a_second' => 'մի քանի վայրկյան|:count վայրկյան', + 's' => ':countվրկ', + 'ago' => ':time առաջ', + 'from_now' => ':timeից', + 'after' => ':time հետո', + 'before' => ':time առաջ', + 'diff_now' => 'հիմա', + 'diff_today' => 'այսօր', + 'diff_yesterday' => 'երեկ', + 'diff_tomorrow' => 'վաղը', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY թ.', + 'LLL' => 'D MMMM YYYY թ., HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY թ., HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[այսօր] LT', + 'nextDay' => '[վաղը] LT', + 'nextWeek' => 'dddd [օրը ժամը] LT', + 'lastDay' => '[երեկ] LT', + 'lastWeek' => '[անցած] dddd [օրը ժամը] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'DDD': + case 'w': + case 'W': + case 'DDDo': + return $number.($number === 1 ? '-ին' : '-րդ'); + default: + return $number; + } + }, + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'գիշերվա'; + } + if ($hour < 12) { + return 'առավոտվա'; + } + if ($hour < 17) { + return 'ցերեկվա'; + } + + return 'երեկոյան'; + }, + 'months' => ['հունվարի', 'փետրվարի', 'մարտի', 'ապրիլի', 'մայիսի', 'հունիսի', 'հուլիսի', 'օգոստոսի', 'սեպտեմբերի', 'հոկտեմբերի', 'նոյեմբերի', 'դեկտեմբերի'], + 'months_standalone' => ['հունվար', 'փետրվար', 'մարտ', 'ապրիլ', 'մայիս', 'հունիս', 'հուլիս', 'օգոստոս', 'սեպտեմբեր', 'հոկտեմբեր', 'նոյեմբեր', 'դեկտեմբեր'], + 'months_short' => ['հնվ', 'փտր', 'մրտ', 'ապր', 'մյս', 'հնս', 'հլս', 'օգս', 'սպտ', 'հկտ', 'նմբ', 'դկտ'], + 'months_regexp' => '/(D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['կիրակի', 'երկուշաբթի', 'երեքշաբթի', 'չորեքշաբթի', 'հինգշաբթի', 'ուրբաթ', 'շաբաթ'], + 'weekdays_short' => ['կրկ', 'երկ', 'երք', 'չրք', 'հնգ', 'ուրբ', 'շբթ'], + 'weekdays_min' => ['կրկ', 'երկ', 'երք', 'չրք', 'հնգ', 'ուրբ', 'շբթ'], + 'list' => [', ', ' եւ '], + 'first_day_of_week' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hy_AM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hy_AM.php new file mode 100644 index 0000000..4587df5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/hy_AM.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - Tim Fish + * - Serhan Apaydın + * - JD Isaacks + */ +return array_replace_recursive(require __DIR__.'/hy.php', [ + 'from_now' => ':time հետո', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/i18n.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/i18n.php new file mode 100644 index 0000000..e65449b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/i18n.php @@ -0,0 +1,23 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], + 'months' => ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], + 'months_short' => ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], + 'weekdays' => ['1', '2', '3', '4', '5', '6', '7'], + 'weekdays_short' => ['1', '2', '3', '4', '5', '6', '7'], + 'weekdays_min' => ['1', '2', '3', '4', '5', '6', '7'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ia.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ia.php new file mode 100644 index 0000000..0a0d5e6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ia.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ia_FR.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ia_FR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ia_FR.php new file mode 100644 index 0000000..de4b2fa --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ia_FR.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Fedora Project Nik Kalach nikka@fedoraproject.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['januario', 'februario', 'martio', 'april', 'maio', 'junio', 'julio', 'augusto', 'septembre', 'octobre', 'novembre', 'decembre'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'], + 'weekdays' => ['dominica', 'lunedi', 'martedi', 'mercuridi', 'jovedi', 'venerdi', 'sabbato'], + 'weekdays_short' => ['dom', 'lun', 'mar', 'mer', 'jov', 'ven', 'sab'], + 'weekdays_min' => ['dom', 'lun', 'mar', 'mer', 'jov', 'ven', 'sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => 'anno :count', + 'y' => 'anno :count', + 'a_year' => 'anno :count', + + 'month' => ':count mense', + 'm' => ':count mense', + 'a_month' => ':count mense', + + 'week' => ':count septimana', + 'w' => ':count septimana', + 'a_week' => ':count septimana', + + 'day' => ':count die', + 'd' => ':count die', + 'a_day' => ':count die', + + 'hour' => ':count hora', + 'h' => ':count hora', + 'a_hour' => ':count hora', + + 'minute' => ':count minuscule', + 'min' => ':count minuscule', + 'a_minute' => ':count minuscule', + + 'second' => ':count secunda', + 's' => ':count secunda', + 'a_second' => ':count secunda', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/id.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/id.php new file mode 100644 index 0000000..afaf78f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/id.php @@ -0,0 +1,92 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - du + * - JD Isaacks + * - Nafies Luthfi + * - Raymundus Jati Primanda (mundusjp) + * - diankur313 + * - a-wip0 + */ +return [ + 'year' => ':count tahun', + 'a_year' => '{1}setahun|]1,Inf[:count tahun', + 'y' => ':countthn', + 'month' => ':count bulan', + 'a_month' => '{1}sebulan|]1,Inf[:count bulan', + 'm' => ':countbln', + 'week' => ':count minggu', + 'a_week' => '{1}seminggu|]1,Inf[:count minggu', + 'w' => ':countmgg', + 'day' => ':count hari', + 'a_day' => '{1}sehari|]1,Inf[:count hari', + 'd' => ':counthr', + 'hour' => ':count jam', + 'a_hour' => '{1}sejam|]1,Inf[:count jam', + 'h' => ':countj', + 'minute' => ':count menit', + 'a_minute' => '{1}semenit|]1,Inf[:count menit', + 'min' => ':countmnt', + 'second' => ':count detik', + 'a_second' => '{1}beberapa detik|]1,Inf[:count detik', + 's' => ':countdt', + 'ago' => ':time yang lalu', + 'from_now' => ':time dari sekarang', + 'after' => ':time setelahnya', + 'before' => ':time sebelumnya', + 'diff_now' => 'sekarang', + 'diff_today' => 'Hari', + 'diff_today_regexp' => 'Hari(?:\\s+ini)?(?:\\s+pukul)?', + 'diff_yesterday' => 'kemarin', + 'diff_yesterday_regexp' => 'Kemarin(?:\\s+pukul)?', + 'diff_tomorrow' => 'besok', + 'diff_tomorrow_regexp' => 'Besok(?:\\s+pukul)?', + 'formats' => [ + 'LT' => 'HH.mm', + 'LTS' => 'HH.mm.ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY [pukul] HH.mm', + 'LLLL' => 'dddd, D MMMM YYYY [pukul] HH.mm', + ], + 'calendar' => [ + 'sameDay' => '[Hari ini pukul] LT', + 'nextDay' => '[Besok pukul] LT', + 'nextWeek' => 'dddd [pukul] LT', + 'lastDay' => '[Kemarin pukul] LT', + 'lastWeek' => 'dddd [lalu pukul] LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 11) { + return 'pagi'; + } + if ($hour < 15) { + return 'siang'; + } + if ($hour < 19) { + return 'sore'; + } + + return 'malam'; + }, + 'months' => ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agt', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'], + 'weekdays_short' => ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'], + 'weekdays_min' => ['Mg', 'Sn', 'Sl', 'Rb', 'Km', 'Jm', 'Sb'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' dan '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/id_ID.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/id_ID.php new file mode 100644 index 0000000..d5953a1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/id_ID.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/id.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ig.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ig.php new file mode 100644 index 0000000..de51e9c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ig.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ig_NG.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ig_NG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ig_NG.php new file mode 100644 index 0000000..0034e35 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ig_NG.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - pablo@mandriva.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Jenụwarị', 'Febrụwarị', 'Maachị', 'Eprel', 'Mee', 'Juun', 'Julaị', 'Ọgọọst', 'Septemba', 'Ọktoba', 'Novemba', 'Disemba'], + 'months_short' => ['Jen', 'Feb', 'Maa', 'Epr', 'Mee', 'Juu', 'Jul', 'Ọgọ', 'Sep', 'Ọkt', 'Nov', 'Dis'], + 'weekdays' => ['sọnde', 'mọnde', 'tuzde', 'wenzde', 'tọsde', 'fraịde', 'satọde'], + 'weekdays_short' => ['sọn', 'mọn', 'tuz', 'wen', 'tọs', 'fra', 'sat'], + 'weekdays_min' => ['sọn', 'mọn', 'tuz', 'wen', 'tọs', 'fra', 'sat'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => 'afo :count', + 'y' => 'afo :count', + 'a_year' => 'afo :count', + + 'month' => 'önwa :count', + 'm' => 'önwa :count', + 'a_month' => 'önwa :count', + + 'week' => 'izu :count', + 'w' => 'izu :count', + 'a_week' => 'izu :count', + + 'day' => 'ụbọchị :count', + 'd' => 'ụbọchị :count', + 'a_day' => 'ụbọchị :count', + + 'hour' => 'awa :count', + 'h' => 'awa :count', + 'a_hour' => 'awa :count', + + 'minute' => 'minit :count', + 'min' => 'minit :count', + 'a_minute' => 'minit :count', + + 'second' => 'sekọnd :count', + 's' => 'sekọnd :count', + 'a_second' => 'sekọnd :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ii.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ii.php new file mode 100644 index 0000000..a4246c2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ii.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['ꎸꄑ', 'ꁯꋒ'], + 'weekdays' => ['ꑭꆏꑍ', 'ꆏꊂꋍ', 'ꆏꊂꑍ', 'ꆏꊂꌕ', 'ꆏꊂꇖ', 'ꆏꊂꉬ', 'ꆏꊂꃘ'], + 'weekdays_short' => ['ꑭꆏ', 'ꆏꋍ', 'ꆏꑍ', 'ꆏꌕ', 'ꆏꇖ', 'ꆏꉬ', 'ꆏꃘ'], + 'weekdays_min' => ['ꑭꆏ', 'ꆏꋍ', 'ꆏꑍ', 'ꆏꌕ', 'ꆏꇖ', 'ꆏꉬ', 'ꆏꃘ'], + 'months' => null, + 'months_short' => ['ꋍꆪ', 'ꑍꆪ', 'ꌕꆪ', 'ꇖꆪ', 'ꉬꆪ', 'ꃘꆪ', 'ꏃꆪ', 'ꉆꆪ', 'ꈬꆪ', 'ꊰꆪ', 'ꊰꊪꆪ', 'ꊰꑋꆪ'], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D h:mm a', + 'LLLL' => 'YYYY MMMM D, dddd h:mm a', + ], + + 'year' => ':count ꒉ', // less reliable + 'y' => ':count ꒉ', // less reliable + 'a_year' => ':count ꒉ', // less reliable + + 'month' => ':count ꆪ', + 'm' => ':count ꆪ', + 'a_month' => ':count ꆪ', + + 'week' => ':count ꏃ', // less reliable + 'w' => ':count ꏃ', // less reliable + 'a_week' => ':count ꏃ', // less reliable + + 'day' => ':count ꏜ', // less reliable + 'd' => ':count ꏜ', // less reliable + 'a_day' => ':count ꏜ', // less reliable + + 'hour' => ':count ꄮꈉ', + 'h' => ':count ꄮꈉ', + 'a_hour' => ':count ꄮꈉ', + + 'minute' => ':count ꀄꊭ', // less reliable + 'min' => ':count ꀄꊭ', // less reliable + 'a_minute' => ':count ꀄꊭ', // less reliable + + 'second' => ':count ꇅ', // less reliable + 's' => ':count ꇅ', // less reliable + 'a_second' => ':count ꇅ', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ik.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ik.php new file mode 100644 index 0000000..7a13aa2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ik.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ik_CA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ik_CA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ik_CA.php new file mode 100644 index 0000000..bb2a109 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ik_CA.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - pablo@mandriva.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Siqiññaatchiaq', 'Siqiññaasrugruk', 'Paniqsiqsiivik', 'Qilġich Tatqiat', 'Suppivik', 'Iġñivik', 'Itchavik', 'Tiññivik', 'Amiġaiqsivik', 'Sikkuvik', 'Nippivik', 'Siqiñġiḷaq'], + 'months_short' => ['Sñt', 'Sñs', 'Pan', 'Qil', 'Sup', 'Iġñ', 'Itc', 'Tiñ', 'Ami', 'Sik', 'Nip', 'Siq'], + 'weekdays' => ['Minġuiqsioiq', 'Savałłiq', 'Ilaqtchiioiq', 'Qitchiioiq', 'Sisamiioiq', 'Tallimmiioiq', 'Maqinġuoiq'], + 'weekdays_short' => ['Min', 'Sav', 'Ila', 'Qit', 'Sis', 'Tal', 'Maq'], + 'weekdays_min' => ['Min', 'Sav', 'Ila', 'Qit', 'Sis', 'Tal', 'Maq'], + 'day_of_first_week_of_year' => 1, + + 'year' => ':count ukiuq', + 'y' => ':count ukiuq', + 'a_year' => ':count ukiuq', + + 'month' => ':count Tatqiat', + 'm' => ':count Tatqiat', + 'a_month' => ':count Tatqiat', + + 'week' => ':count tatqiat', // less reliable + 'w' => ':count tatqiat', // less reliable + 'a_week' => ':count tatqiat', // less reliable + + 'day' => ':count siqiñiq', // less reliable + 'd' => ':count siqiñiq', // less reliable + 'a_day' => ':count siqiñiq', // less reliable + + 'hour' => ':count Siḷa', // less reliable + 'h' => ':count Siḷa', // less reliable + 'a_hour' => ':count Siḷa', // less reliable + + 'second' => ':count iġñiq', // less reliable + 's' => ':count iġñiq', // less reliable + 'a_second' => ':count iġñiq', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/in.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/in.php new file mode 100644 index 0000000..d5953a1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/in.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/id.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/is.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/is.php new file mode 100644 index 0000000..9990168 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/is.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kristján Ingi Geirsson + */ +return [ + 'year' => '1 ár|:count ár', + 'y' => '1 ár|:count ár', + 'month' => '1 mánuður|:count mánuðir', + 'm' => '1 mánuður|:count mánuðir', + 'week' => '1 vika|:count vikur', + 'w' => '1 vika|:count vikur', + 'day' => '1 dagur|:count dagar', + 'd' => '1 dagur|:count dagar', + 'hour' => '1 klukkutími|:count klukkutímar', + 'h' => '1 klukkutími|:count klukkutímar', + 'minute' => '1 mínúta|:count mínútur', + 'min' => '1 mínúta|:count mínútur', + 'second' => '1 sekúnda|:count sekúndur', + 's' => '1 sekúnda|:count sekúndur', + 'ago' => ':time síðan', + 'from_now' => ':time síðan', + 'after' => ':time eftir', + 'before' => ':time fyrir', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' og '], + 'meridiem' => ['fh', 'eh'], + 'diff_now' => 'núna', + 'diff_yesterday' => 'í gær', + 'diff_tomorrow' => 'á morgun', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM [kl.] HH:mm', + 'LLLL' => 'dddd D. MMMM YYYY [kl.] HH:mm', + ], + 'weekdays' => ['sunnudaginn', 'mánudaginn', 'þriðjudaginn', 'miðvikudaginn', 'fimmtudaginn', 'föstudaginn', 'laugardaginn'], + 'weekdays_short' => ['sun', 'mán', 'þri', 'mið', 'fim', 'fös', 'lau'], + 'weekdays_min' => ['sun', 'mán', 'þri', 'mið', 'fim', 'fös', 'lau'], + 'months' => ['janúar', 'febrúar', 'mars', 'apríl', 'maí', 'júní', 'júlí', 'ágúst', 'september', 'október', 'nóvember', 'desember'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'maí', 'jún', 'júl', 'ágú', 'sep', 'okt', 'nóv', 'des'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/is_IS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/is_IS.php new file mode 100644 index 0000000..4d35c44 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/is_IS.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/is.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it.php new file mode 100644 index 0000000..49875d7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it.php @@ -0,0 +1,115 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ash + * - François B + * - Marco Perrando + * - Massimiliano Caniparoli + * - JD Isaacks + * - Andrea Martini + * - Francesco Marasco + * - Tizianoz93 + * - Davide Casiraghi (davide-casiraghi) + * - Pete Scopes (pdscopes) + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count anno|:count anni', + 'a_year' => 'un anno|:count anni', + 'y' => ':count anno|:count anni', + 'month' => ':count mese|:count mesi', + 'a_month' => 'un mese|:count mesi', + 'm' => ':count mese|:count mesi', + 'week' => ':count settimana|:count settimane', + 'a_week' => 'una settimana|:count settimane', + 'w' => ':count set.', + 'day' => ':count giorno|:count giorni', + 'a_day' => 'un giorno|:count giorni', + 'd' => ':count g|:count gg', + 'hour' => ':count ora|:count ore', + 'a_hour' => 'un\'ora|:count ore', + 'h' => ':count h', + 'minute' => ':count minuto|:count minuti', + 'a_minute' => 'un minuto|:count minuti', + 'min' => ':count min.', + 'second' => ':count secondo|:count secondi', + 'a_second' => 'alcuni secondi|:count secondi', + 's' => ':count sec.', + 'millisecond' => ':count millisecondo|:count millisecondi', + 'a_millisecond' => 'un millisecondo|:count millisecondi', + 'ms' => ':countms', + 'microsecond' => ':count microsecondo|:count microsecondi', + 'a_microsecond' => 'un microsecondo|:count microsecondi', + 'µs' => ':countµs', + 'ago' => ':time fa', + 'from_now' => function ($time) { + return (preg_match('/^\d.+$/', $time) ? 'tra' : 'in')." $time"; + }, + 'after' => ':time dopo', + 'before' => ':time prima', + 'diff_now' => 'proprio ora', + 'diff_today' => 'Oggi', + 'diff_today_regexp' => 'Oggi(?:\\s+alle)?', + 'diff_yesterday' => 'ieri', + 'diff_yesterday_regexp' => 'Ieri(?:\\s+alle)?', + 'diff_tomorrow' => 'domani', + 'diff_tomorrow_regexp' => 'Domani(?:\\s+alle)?', + 'diff_before_yesterday' => 'l\'altro ieri', + 'diff_after_tomorrow' => 'dopodomani', + 'period_interval' => 'ogni :interval', + 'period_start_date' => 'dal :date', + 'period_end_date' => 'al :date', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Oggi alle] LT', + 'nextDay' => '[Domani alle] LT', + 'nextWeek' => 'dddd [alle] LT', + 'lastDay' => '[Ieri alle] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[la scorsa] dddd [alle] LT'; + default: + return '[lo scorso] dddd [alle] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':numberº', + 'months' => ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'], + 'months_short' => ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'], + 'weekdays' => ['domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato'], + 'weekdays_short' => ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'], + 'weekdays_min' => ['do', 'lu', 'ma', 'me', 'gi', 've', 'sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' e '], + 'ordinal_words' => [ + 'of' => 'di', + 'first' => 'primo', + 'second' => 'secondo', + 'third' => 'terzo', + 'fourth' => 'quarto', + 'fifth' => 'quinto', + 'last' => 'ultimo', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_CH.php new file mode 100644 index 0000000..c23cc50 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_CH.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Propaganistas + */ +return array_replace_recursive(require __DIR__.'/it.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_IT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_IT.php new file mode 100644 index 0000000..a5d1981 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_IT.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return require __DIR__.'/it.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_SM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_SM.php new file mode 100644 index 0000000..5e8fc92 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_SM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/it.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_VA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_VA.php new file mode 100644 index 0000000..5e8fc92 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/it_VA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/it.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iu.php new file mode 100644 index 0000000..4fa9742 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iu.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/iu_CA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iu_CA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iu_CA.php new file mode 100644 index 0000000..6ab7e14 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iu_CA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Pablo Saratxaga pablo@mandriva.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'MM/DD/YY', + ], + 'months' => ['ᔮᓄᐊᓕ', 'ᕕᕗᐊᓕ', 'ᒪᔅᓯ', 'ᐃᐳᓗ', 'ᒪᐃ', 'ᔪᓂ', 'ᔪᓚᐃ', 'ᐊᒋᓯ', 'ᓯᑎᕙ', 'ᐊᑦᑐᕙ', 'ᓄᕕᕙ', 'ᑎᓯᕝᕙ'], + 'months_short' => ['ᔮᓄ', 'ᕕᕗ', 'ᒪᔅ', 'ᐃᐳ', 'ᒪᐃ', 'ᔪᓂ', 'ᔪᓚ', 'ᐊᒋ', 'ᓯᑎ', 'ᐊᑦ', 'ᓄᕕ', 'ᑎᓯ'], + 'weekdays' => ['ᓈᑦᑎᖑᔭᕐᕕᒃ', 'ᓇᒡᒐᔾᔭᐅ', 'ᓇᒡᒐᔾᔭᐅᓕᖅᑭᑦ', 'ᐱᖓᓲᓕᖅᓯᐅᑦ', 'ᕿᑎᖅᑰᑦ', 'ᐅᓪᓗᕈᓘᑐᐃᓇᖅ', 'ᓯᕙᑖᕕᒃ'], + 'weekdays_short' => ['ᓈ', 'ᓇ', 'ᓕ', 'ᐱ', 'ᕿ', 'ᐅ', 'ᓯ'], + 'weekdays_min' => ['ᓈ', 'ᓇ', 'ᓕ', 'ᐱ', 'ᕿ', 'ᐅ', 'ᓯ'], + 'day_of_first_week_of_year' => 1, + + 'year' => ':count ᐅᑭᐅᖅ', + 'y' => ':count ᐅᑭᐅᖅ', + 'a_year' => ':count ᐅᑭᐅᖅ', + + 'month' => ':count qaammat', + 'm' => ':count qaammat', + 'a_month' => ':count qaammat', + + 'week' => ':count sapaatip akunnera', + 'w' => ':count sapaatip akunnera', + 'a_week' => ':count sapaatip akunnera', + + 'day' => ':count ulloq', + 'd' => ':count ulloq', + 'a_day' => ':count ulloq', + + 'hour' => ':count ikarraq', + 'h' => ':count ikarraq', + 'a_hour' => ':count ikarraq', + + 'minute' => ':count titiqqaralaaq', // less reliable + 'min' => ':count titiqqaralaaq', // less reliable + 'a_minute' => ':count titiqqaralaaq', // less reliable + + 'second' => ':count marluk', // less reliable + 's' => ':count marluk', // less reliable + 'a_second' => ':count marluk', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iw.php new file mode 100644 index 0000000..a26e350 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/iw.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'months' => ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'], + 'months_short' => ['ינו׳', 'פבר׳', 'מרץ', 'אפר׳', 'מאי', 'יוני', 'יולי', 'אוג׳', 'ספט׳', 'אוק׳', 'נוב׳', 'דצמ׳'], + 'weekdays' => ['יום ראשון', 'יום שני', 'יום שלישי', 'יום רביעי', 'יום חמישי', 'יום שישי', 'יום שבת'], + 'weekdays_short' => ['יום א׳', 'יום ב׳', 'יום ג׳', 'יום ד׳', 'יום ה׳', 'יום ו׳', 'שבת'], + 'weekdays_min' => ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳', 'ש׳'], + 'meridiem' => ['לפנה״צ', 'אחה״צ'], + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'D.M.YYYY', + 'LL' => 'D בMMM YYYY', + 'LLL' => 'D בMMMM YYYY H:mm', + 'LLLL' => 'dddd, D בMMMM YYYY H:mm', + ], + + 'year' => ':count שנה', + 'y' => ':count שנה', + 'a_year' => ':count שנה', + + 'month' => ':count חודש', + 'm' => ':count חודש', + 'a_month' => ':count חודש', + + 'week' => ':count שבוע', + 'w' => ':count שבוע', + 'a_week' => ':count שבוע', + + 'day' => ':count יום', + 'd' => ':count יום', + 'a_day' => ':count יום', + + 'hour' => ':count שעה', + 'h' => ':count שעה', + 'a_hour' => ':count שעה', + + 'minute' => ':count דקה', + 'min' => ':count דקה', + 'a_minute' => ':count דקה', + + 'second' => ':count שניה', + 's' => ':count שניה', + 'a_second' => ':count שניה', + + 'ago' => 'לפני :time', + 'from_now' => 'בעוד :time', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ja.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ja.php new file mode 100644 index 0000000..1ca6751 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ja.php @@ -0,0 +1,102 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Takuya Sawada + * - Atsushi Tanaka + * - François B + * - Jason Katz-Brown + * - Serhan Apaydın + * - XueWei + * - JD Isaacks + * - toyama satoshi + * - atakigawa + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count年', + 'y' => ':count年', + 'month' => ':countヶ月', + 'm' => ':countヶ月', + 'week' => ':count週間', + 'w' => ':count週間', + 'day' => ':count日', + 'd' => ':count日', + 'hour' => ':count時間', + 'h' => ':count時間', + 'minute' => ':count分', + 'min' => ':count分', + 'second' => ':count秒', + 'a_second' => '{1}数秒|]1,Inf[:count秒', + 's' => ':count秒', + 'ago' => ':time前', + 'from_now' => ':time後', + 'after' => ':time後', + 'before' => ':time前', + 'diff_now' => '今', + 'diff_today' => '今日', + 'diff_yesterday' => '昨日', + 'diff_tomorrow' => '明日', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY/MM/DD', + 'LL' => 'YYYY年M月D日', + 'LLL' => 'YYYY年M月D日 HH:mm', + 'LLLL' => 'YYYY年M月D日 dddd HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[今日] LT', + 'nextDay' => '[明日] LT', + 'nextWeek' => function (CarbonInterface $current, CarbonInterface $other) { + if ($other->week !== $current->week) { + return '[来週]dddd LT'; + } + + return 'dddd LT'; + }, + 'lastDay' => '[昨日] LT', + 'lastWeek' => function (CarbonInterface $current, CarbonInterface $other) { + if ($other->week !== $current->week) { + return '[先週]dddd LT'; + } + + return 'dddd LT'; + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'd': + case 'D': + case 'DDD': + return $number.'日'; + default: + return $number; + } + }, + 'meridiem' => ['午前', '午後'], + 'months' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], + 'months_short' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], + 'weekdays' => ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'], + 'weekdays_short' => ['日', '月', '火', '水', '木', '金', '土'], + 'weekdays_min' => ['日', '月', '火', '水', '木', '金', '土'], + 'list' => '、', + 'alt_numbers' => ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '二十一', '二十二', '二十三', '二十四', '二十五', '二十六', '二十七', '二十八', '二十九', '三十', '三十一', '三十二', '三十三', '三十四', '三十五', '三十六', '三十七', '三十八', '三十九', '四十', '四十一', '四十二', '四十三', '四十四', '四十五', '四十六', '四十七', '四十八', '四十九', '五十', '五十一', '五十二', '五十三', '五十四', '五十五', '五十六', '五十七', '五十八', '五十九', '六十', '六十一', '六十二', '六十三', '六十四', '六十五', '六十六', '六十七', '六十八', '六十九', '七十', '七十一', '七十二', '七十三', '七十四', '七十五', '七十六', '七十七', '七十八', '七十九', '八十', '八十一', '八十二', '八十三', '八十四', '八十五', '八十六', '八十七', '八十八', '八十九', '九十', '九十一', '九十二', '九十三', '九十四', '九十五', '九十六', '九十七', '九十八', '九十九'], + 'alt_numbers_pow' => [ + 10000 => '万', + 1000 => '千', + 100 => '百', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ja_JP.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ja_JP.php new file mode 100644 index 0000000..c283625 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ja_JP.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ja.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jgo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jgo.php new file mode 100644 index 0000000..6a1e77a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jgo.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jmc.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jmc.php new file mode 100644 index 0000000..ed92e8e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jmc.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['utuko', 'kyiukonyi'], + 'weekdays' => ['Jumapilyi', 'Jumatatuu', 'Jumanne', 'Jumatanu', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'weekdays_min' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprilyi', 'Mei', 'Junyi', 'Julyai', 'Agusti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jv.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jv.php new file mode 100644 index 0000000..bcbe044 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/jv.php @@ -0,0 +1,71 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - tgfjt + * - JD Isaacks + */ +return [ + 'year' => '{1}setaun|]1,Inf[:count taun', + 'month' => '{1}sewulan|]1,Inf[:count wulan', + 'week' => '{1}sakminggu|]1,Inf[:count minggu', + 'day' => '{1}sedinten|]1,Inf[:count dinten', + 'hour' => '{1}setunggal jam|]1,Inf[:count jam', + 'minute' => '{1}setunggal menit|]1,Inf[:count menit', + 'second' => '{1}sawetawis detik|]1,Inf[:count detik', + 'ago' => ':time ingkang kepengker', + 'from_now' => 'wonten ing :time', + 'diff_today' => 'Dinten', + 'diff_yesterday' => 'Kala', + 'diff_yesterday_regexp' => 'Kala(?:\\s+wingi)?(?:\\s+pukul)?', + 'diff_tomorrow' => 'Mbenjang', + 'diff_tomorrow_regexp' => 'Mbenjang(?:\\s+pukul)?', + 'diff_today_regexp' => 'Dinten(?:\\s+puniko)?(?:\\s+pukul)?', + 'formats' => [ + 'LT' => 'HH.mm', + 'LTS' => 'HH.mm.ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY [pukul] HH.mm', + 'LLLL' => 'dddd, D MMMM YYYY [pukul] HH.mm', + ], + 'calendar' => [ + 'sameDay' => '[Dinten puniko pukul] LT', + 'nextDay' => '[Mbenjang pukul] LT', + 'nextWeek' => 'dddd [pukul] LT', + 'lastDay' => '[Kala wingi pukul] LT', + 'lastWeek' => 'dddd [kepengker pukul] LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 11) { + return 'enjing'; + } + if ($hour < 15) { + return 'siyang'; + } + if ($hour < 19) { + return 'sonten'; + } + + return 'ndalu'; + }, + 'months' => ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'Nopember', 'Desember'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Ags', 'Sep', 'Okt', 'Nop', 'Des'], + 'weekdays' => ['Minggu', 'Senen', 'Seloso', 'Rebu', 'Kemis', 'Jemuwah', 'Septu'], + 'weekdays_short' => ['Min', 'Sen', 'Sel', 'Reb', 'Kem', 'Jem', 'Sep'], + 'weekdays_min' => ['Mg', 'Sn', 'Sl', 'Rb', 'Km', 'Jm', 'Sp'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' lan '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ka.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ka.php new file mode 100644 index 0000000..a5d563d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ka.php @@ -0,0 +1,204 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Tornike Razmadze + * - François B + * - Lasha Dolidze + * - Tim Fish + * - JD Isaacks + * - Tornike Razmadze + * - François B + * - Lasha Dolidze + * - JD Isaacks + * - LONGMAN + * - Avtandil Kikabidze (akalongman) + * - Levan Velijanashvili (Stichoza) + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count წელი', + 'y' => ':count წელი', + 'a_year' => '{1}წელი|]1,Inf[:count წელი', + 'month' => ':count თვე', + 'm' => ':count თვე', + 'a_month' => '{1}თვე|]1,Inf[:count თვე', + 'week' => ':count კვირა', + 'w' => ':count კვირა', + 'a_week' => '{1}კვირა|]1,Inf[:count კვირა', + 'day' => ':count დღე', + 'd' => ':count დღე', + 'a_day' => '{1}დღე|]1,Inf[:count დღე', + 'hour' => ':count საათი', + 'h' => ':count საათი', + 'a_hour' => '{1}საათი|]1,Inf[:count საათი', + 'minute' => ':count წუთი', + 'min' => ':count წუთი', + 'a_minute' => '{1}წუთი|]1,Inf[:count წუთი', + 'second' => ':count წამი', + 's' => ':count წამი', + 'a_second' => '{1}რამდენიმე წამი|]1,Inf[:count წამი', + 'ago' => function ($time) { + $replacements = [ + // year + 'წელი' => 'წლის', + // month + 'თვე' => 'თვის', + // week + 'კვირა' => 'კვირის', + // day + 'დღე' => 'დღის', + // hour + 'საათი' => 'საათის', + // minute + 'წუთი' => 'წუთის', + // second + 'წამი' => 'წამის', + ]; + $time = strtr($time, array_flip($replacements)); + $time = strtr($time, $replacements); + + return "$time წინ"; + }, + 'from_now' => function ($time) { + $replacements = [ + // year + 'წელი' => 'წელიწადში', + // week + 'კვირა' => 'კვირაში', + // day + 'დღე' => 'დღეში', + // month + 'თვე' => 'თვეში', + // hour + 'საათი' => 'საათში', + // minute + 'წუთი' => 'წუთში', + // second + 'წამი' => 'წამში', + ]; + $time = strtr($time, array_flip($replacements)); + $time = strtr($time, $replacements); + + return $time; + }, + 'after' => function ($time) { + $replacements = [ + // year + 'წელი' => 'წლის', + // month + 'თვე' => 'თვის', + // week + 'კვირა' => 'კვირის', + // day + 'დღე' => 'დღის', + // hour + 'საათი' => 'საათის', + // minute + 'წუთი' => 'წუთის', + // second + 'წამი' => 'წამის', + ]; + $time = strtr($time, array_flip($replacements)); + $time = strtr($time, $replacements); + + return "$time შემდეგ"; + }, + 'before' => function ($time) { + $replacements = [ + // year + 'წელი' => 'წლით', + // month + 'თვე' => 'თვით', + // week + 'კვირა' => 'კვირით', + // day + 'დღე' => 'დღით', + // hour + 'საათი' => 'საათით', + // minute + 'წუთი' => 'წუთით', + // second + 'წამი' => 'წამით', + ]; + $time = strtr($time, array_flip($replacements)); + $time = strtr($time, $replacements); + + return "$time ადრე"; + }, + 'diff_now' => 'ახლა', + 'diff_today' => 'დღეს', + 'diff_yesterday' => 'გუშინ', + 'diff_tomorrow' => 'ხვალ', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[დღეს], LT[-ზე]', + 'nextDay' => '[ხვალ], LT[-ზე]', + 'nextWeek' => function (CarbonInterface $current, CarbonInterface $other) { + return ($current->isSameWeek($other) ? '' : '[შემდეგ] ').'dddd, LT[-ზე]'; + }, + 'lastDay' => '[გუშინ], LT[-ზე]', + 'lastWeek' => '[წინა] dddd, LT-ზე', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + if ($number === 0) { + return $number; + } + if ($number === 1) { + return $number.'-ლი'; + } + if (($number < 20) || ($number <= 100 && ($number % 20 === 0)) || ($number % 100 === 0)) { + return 'მე-'.$number; + } + + return $number.'-ე'; + }, + 'months' => ['იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'], + 'months_standalone' => ['იანვარს', 'თებერვალს', 'მარტს', 'აპრილს', 'მაისს', 'ივნისს', 'ივლისს', 'აგვისტოს', 'სექტემბერს', 'ოქტომბერს', 'ნოემბერს', 'დეკემბერს'], + 'months_short' => ['იან', 'თებ', 'მარ', 'აპრ', 'მაი', 'ივნ', 'ივლ', 'აგვ', 'სექ', 'ოქტ', 'ნოე', 'დეკ'], + 'months_regexp' => '/(D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['კვირას', 'ორშაბათს', 'სამშაბათს', 'ოთხშაბათს', 'ხუთშაბათს', 'პარასკევს', 'შაბათს'], + 'weekdays_standalone' => ['კვირა', 'ორშაბათი', 'სამშაბათი', 'ოთხშაბათი', 'ხუთშაბათი', 'პარასკევი', 'შაბათი'], + 'weekdays_short' => ['კვი', 'ორშ', 'სამ', 'ოთხ', 'ხუთ', 'პარ', 'შაბ'], + 'weekdays_min' => ['კვ', 'ორ', 'სა', 'ოთ', 'ხუ', 'პა', 'შა'], + 'weekdays_regexp' => '/^([^d].*|.*[^d])$/', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' და '], + 'meridiem' => function ($hour) { + if ($hour >= 4) { + if ($hour < 11) { + return 'დილის'; + } + + if ($hour < 16) { + return 'შუადღის'; + } + + if ($hour < 22) { + return 'საღამოს'; + } + } + + return 'ღამის'; + }, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ka_GE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ka_GE.php new file mode 100644 index 0000000..a26d930 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ka_GE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ka.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kab.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kab.php new file mode 100644 index 0000000..94d6473 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kab.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/kab_DZ.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kab_DZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kab_DZ.php new file mode 100644 index 0000000..796660b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kab_DZ.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - belkacem77@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Yennayer', 'Fuṛar', 'Meɣres', 'Yebrir', 'Mayyu', 'Yunyu', 'Yulyu', 'ɣuct', 'Ctembeṛ', 'Tubeṛ', 'Wambeṛ', 'Dujembeṛ'], + 'months_short' => ['Yen', 'Fur', 'Meɣ', 'Yeb', 'May', 'Yun', 'Yul', 'ɣuc', 'Cte', 'Tub', 'Wam', 'Duj'], + 'weekdays' => ['Acer', 'Arim', 'Aram', 'Ahad', 'Amhad', 'Sem', 'Sed'], + 'weekdays_short' => ['Ace', 'Ari', 'Ara', 'Aha', 'Amh', 'Sem', 'Sed'], + 'weekdays_min' => ['Ace', 'Ari', 'Ara', 'Aha', 'Amh', 'Sem', 'Sed'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['FT', 'MD'], + + 'year' => ':count n yiseggasen', + 'y' => ':count n yiseggasen', + 'a_year' => ':count n yiseggasen', + + 'month' => ':count n wayyuren', + 'm' => ':count n wayyuren', + 'a_month' => ':count n wayyuren', + + 'week' => ':count n ledwaṛ', // less reliable + 'w' => ':count n ledwaṛ', // less reliable + 'a_week' => ':count n ledwaṛ', // less reliable + + 'day' => ':count n wussan', + 'd' => ':count n wussan', + 'a_day' => ':count n wussan', + + 'hour' => ':count n tsaɛtin', + 'h' => ':count n tsaɛtin', + 'a_hour' => ':count n tsaɛtin', + + 'minute' => ':count n tedqiqin', + 'min' => ':count n tedqiqin', + 'a_minute' => ':count n tedqiqin', + + 'second' => ':count tasdidt', // less reliable + 's' => ':count tasdidt', // less reliable + 'a_second' => ':count tasdidt', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kam.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kam.php new file mode 100644 index 0000000..0fc70d7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kam.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Ĩyakwakya', 'Ĩyawĩoo'], + 'weekdays' => ['Wa kyumwa', 'Wa kwambĩlĩlya', 'Wa kelĩ', 'Wa katatũ', 'Wa kana', 'Wa katano', 'Wa thanthatũ'], + 'weekdays_short' => ['Wky', 'Wkw', 'Wkl', 'Wtũ', 'Wkn', 'Wtn', 'Wth'], + 'weekdays_min' => ['Wky', 'Wkw', 'Wkl', 'Wtũ', 'Wkn', 'Wtn', 'Wth'], + 'months' => ['Mwai wa mbee', 'Mwai wa kelĩ', 'Mwai wa katatũ', 'Mwai wa kana', 'Mwai wa katano', 'Mwai wa thanthatũ', 'Mwai wa muonza', 'Mwai wa nyaanya', 'Mwai wa kenda', 'Mwai wa ĩkumi', 'Mwai wa ĩkumi na ĩmwe', 'Mwai wa ĩkumi na ilĩ'], + 'months_short' => ['Mbe', 'Kel', 'Ktũ', 'Kan', 'Ktn', 'Tha', 'Moo', 'Nya', 'Knd', 'Ĩku', 'Ĩkm', 'Ĩkl'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + // Too unreliable + /* + 'year' => ':count mbua', // less reliable + 'y' => ':count mbua', // less reliable + 'a_year' => ':count mbua', // less reliable + + 'month' => ':count ndakitali', // less reliable + 'm' => ':count ndakitali', // less reliable + 'a_month' => ':count ndakitali', // less reliable + + 'day' => ':count wia', // less reliable + 'd' => ':count wia', // less reliable + 'a_day' => ':count wia', // less reliable + + 'hour' => ':count orasan', // less reliable + 'h' => ':count orasan', // less reliable + 'a_hour' => ':count orasan', // less reliable + + 'minute' => ':count orasan', // less reliable + 'min' => ':count orasan', // less reliable + 'a_minute' => ':count orasan', // less reliable + */ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kde.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kde.php new file mode 100644 index 0000000..fbcc9f3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kde.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Muhi', 'Chilo'], + 'weekdays' => ['Liduva lyapili', 'Liduva lyatatu', 'Liduva lyanchechi', 'Liduva lyannyano', 'Liduva lyannyano na linji', 'Liduva lyannyano na mavili', 'Liduva litandi'], + 'weekdays_short' => ['Ll2', 'Ll3', 'Ll4', 'Ll5', 'Ll6', 'Ll7', 'Ll1'], + 'weekdays_min' => ['Ll2', 'Ll3', 'Ll4', 'Ll5', 'Ll6', 'Ll7', 'Ll1'], + 'months' => ['Mwedi Ntandi', 'Mwedi wa Pili', 'Mwedi wa Tatu', 'Mwedi wa Nchechi', 'Mwedi wa Nnyano', 'Mwedi wa Nnyano na Umo', 'Mwedi wa Nnyano na Mivili', 'Mwedi wa Nnyano na Mitatu', 'Mwedi wa Nnyano na Nchechi', 'Mwedi wa Nnyano na Nnyano', 'Mwedi wa Nnyano na Nnyano na U', 'Mwedi wa Nnyano na Nnyano na M'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kea.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kea.php new file mode 100644 index 0000000..8b6c21b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kea.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['a', 'p'], + 'weekdays' => ['dumingu', 'sigunda-fera', 'tersa-fera', 'kuarta-fera', 'kinta-fera', 'sesta-fera', 'sabadu'], + 'weekdays_short' => ['dum', 'sig', 'ter', 'kua', 'kin', 'ses', 'sab'], + 'weekdays_min' => ['du', 'si', 'te', 'ku', 'ki', 'se', 'sa'], + 'weekdays_standalone' => ['dumingu', 'sigunda-fera', 'tersa-fera', 'kuarta-fera', 'kinta-fera', 'sesta-fera', 'sábadu'], + 'months' => ['Janeru', 'Febreru', 'Marsu', 'Abril', 'Maiu', 'Junhu', 'Julhu', 'Agostu', 'Setenbru', 'Otubru', 'Nuvenbru', 'Dizenbru'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Otu', 'Nuv', 'Diz'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D [di] MMMM [di] YYYY HH:mm', + 'LLLL' => 'dddd, D [di] MMMM [di] YYYY HH:mm', + ], + + 'year' => ':count otunu', // less reliable + 'y' => ':count otunu', // less reliable + 'a_year' => ':count otunu', // less reliable + + 'week' => ':count día dumingu', // less reliable + 'w' => ':count día dumingu', // less reliable + 'a_week' => ':count día dumingu', // less reliable + + 'day' => ':count diâ', // less reliable + 'd' => ':count diâ', // less reliable + 'a_day' => ':count diâ', // less reliable + + 'minute' => ':count sugundu', // less reliable + 'min' => ':count sugundu', // less reliable + 'a_minute' => ':count sugundu', // less reliable + + 'second' => ':count dós', // less reliable + 's' => ':count dós', // less reliable + 'a_second' => ':count dós', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/khq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/khq.php new file mode 100644 index 0000000..7a834cf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/khq.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Adduha', 'Aluula'], + 'weekdays' => ['Alhadi', 'Atini', 'Atalata', 'Alarba', 'Alhamiisa', 'Aljuma', 'Assabdu'], + 'weekdays_short' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alj', 'Ass'], + 'weekdays_min' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alj', 'Ass'], + 'months' => ['Žanwiye', 'Feewiriye', 'Marsi', 'Awiril', 'Me', 'Žuweŋ', 'Žuyye', 'Ut', 'Sektanbur', 'Oktoobur', 'Noowanbur', 'Deesanbur'], + 'months_short' => ['Žan', 'Fee', 'Mar', 'Awi', 'Me', 'Žuw', 'Žuy', 'Ut', 'Sek', 'Okt', 'Noo', 'Dee'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ki.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ki.php new file mode 100644 index 0000000..d86afc5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ki.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Kiroko', 'Hwaĩ-inĩ'], + 'weekdays' => ['Kiumia', 'Njumatatũ', 'Njumaine', 'Njumatana', 'Aramithi', 'Njumaa', 'Njumamothi'], + 'weekdays_short' => ['KMA', 'NTT', 'NMN', 'NMT', 'ART', 'NMA', 'NMM'], + 'weekdays_min' => ['KMA', 'NTT', 'NMN', 'NMT', 'ART', 'NMA', 'NMM'], + 'months' => ['Njenuarĩ', 'Mwere wa kerĩ', 'Mwere wa gatatũ', 'Mwere wa kana', 'Mwere wa gatano', 'Mwere wa gatandatũ', 'Mwere wa mũgwanja', 'Mwere wa kanana', 'Mwere wa kenda', 'Mwere wa ikũmi', 'Mwere wa ikũmi na ũmwe', 'Ndithemba'], + 'months_short' => ['JEN', 'WKR', 'WGT', 'WKN', 'WTN', 'WTD', 'WMJ', 'WNN', 'WKD', 'WIK', 'WMW', 'DIT'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'year' => ':count mĩaka', // less reliable + 'y' => ':count mĩaka', // less reliable + 'a_year' => ':count mĩaka', // less reliable + + 'month' => ':count mweri', // less reliable + 'm' => ':count mweri', // less reliable + 'a_month' => ':count mweri', // less reliable + + 'week' => ':count kiumia', // less reliable + 'w' => ':count kiumia', // less reliable + 'a_week' => ':count kiumia', // less reliable + + 'day' => ':count mũthenya', // less reliable + 'd' => ':count mũthenya', // less reliable + 'a_day' => ':count mũthenya', // less reliable + + 'hour' => ':count thaa', // less reliable + 'h' => ':count thaa', // less reliable + 'a_hour' => ':count thaa', // less reliable + + 'minute' => ':count mundu', // less reliable + 'min' => ':count mundu', // less reliable + 'a_minute' => ':count mundu', // less reliable + + 'second' => ':count igego', // less reliable + 's' => ':count igego', // less reliable + 'a_second' => ':count igego', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kk.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kk.php new file mode 100644 index 0000000..59fa9af --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kk.php @@ -0,0 +1,103 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - Talat Uspanov + * - Нурлан Рахимжанов + * - Toleugazy Kali + */ +return [ + 'year' => ':count жыл', + 'a_year' => '{1}бір жыл|:count жыл', + 'y' => ':count ж.', + 'month' => ':count ай', + 'a_month' => '{1}бір ай|:count ай', + 'm' => ':count ай', + 'week' => ':count апта', + 'a_week' => '{1}бір апта', + 'w' => ':count ап.', + 'day' => ':count күн', + 'a_day' => '{1}бір күн|:count күн', + 'd' => ':count к.', + 'hour' => ':count сағат', + 'a_hour' => '{1}бір сағат|:count сағат', + 'h' => ':count са.', + 'minute' => ':count минут', + 'a_minute' => '{1}бір минут|:count минут', + 'min' => ':count м.', + 'second' => ':count секунд', + 'a_second' => '{1}бірнеше секунд|:count секунд', + 's' => ':count се.', + 'ago' => ':time бұрын', + 'from_now' => ':time ішінде', + 'after' => ':time кейін', + 'before' => ':time бұрын', + 'diff_now' => 'қазір', + 'diff_today' => 'Бүгін', + 'diff_today_regexp' => 'Бүгін(?:\\s+сағат)?', + 'diff_yesterday' => 'кеше', + 'diff_yesterday_regexp' => 'Кеше(?:\\s+сағат)?', + 'diff_tomorrow' => 'ертең', + 'diff_tomorrow_regexp' => 'Ертең(?:\\s+сағат)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Бүгін сағат] LT', + 'nextDay' => '[Ертең сағат] LT', + 'nextWeek' => 'dddd [сағат] LT', + 'lastDay' => '[Кеше сағат] LT', + 'lastWeek' => '[Өткен аптаның] dddd [сағат] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + static $suffixes = [ + 0 => '-ші', + 1 => '-ші', + 2 => '-ші', + 3 => '-ші', + 4 => '-ші', + 5 => '-ші', + 6 => '-шы', + 7 => '-ші', + 8 => '-ші', + 9 => '-шы', + 10 => '-шы', + 20 => '-шы', + 30 => '-шы', + 40 => '-шы', + 50 => '-ші', + 60 => '-шы', + 70 => '-ші', + 80 => '-ші', + 90 => '-шы', + 100 => '-ші', + ]; + + return $number.($suffixes[$number] ?? $suffixes[$number % 10] ?? $suffixes[$number >= 100 ? 100 : -1] ?? ''); + }, + 'months' => ['қаңтар', 'ақпан', 'наурыз', 'сәуір', 'мамыр', 'маусым', 'шілде', 'тамыз', 'қыркүйек', 'қазан', 'қараша', 'желтоқсан'], + 'months_short' => ['қаң', 'ақп', 'нау', 'сәу', 'мам', 'мау', 'шіл', 'там', 'қыр', 'қаз', 'қар', 'жел'], + 'weekdays' => ['жексенбі', 'дүйсенбі', 'сейсенбі', 'сәрсенбі', 'бейсенбі', 'жұма', 'сенбі'], + 'weekdays_short' => ['жек', 'дүй', 'сей', 'сәр', 'бей', 'жұм', 'сен'], + 'weekdays_min' => ['жк', 'дй', 'сй', 'ср', 'бй', 'жм', 'сн'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' және '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kk_KZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kk_KZ.php new file mode 100644 index 0000000..7dc5ebc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kk_KZ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/kk.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kkj.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kkj.php new file mode 100644 index 0000000..6a1e77a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kkj.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kl.php new file mode 100644 index 0000000..7329a07 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kl.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/kl_GL.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kl_GL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kl_GL.php new file mode 100644 index 0000000..4fed720 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kl_GL.php @@ -0,0 +1,64 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Danish Standards Association bug-glibc-locales@gnu.org + * - John Eyðstein Johannesen (mashema) + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd [d.] D. MMMM YYYY [kl.] HH:mm', + ], + 'months' => ['januaarip', 'februaarip', 'marsip', 'apriilip', 'maajip', 'juunip', 'juulip', 'aggustip', 'septembarip', 'oktobarip', 'novembarip', 'decembarip'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'weekdays' => ['sapaat', 'ataasinngorneq', 'marlunngorneq', 'pingasunngorneq', 'sisamanngorneq', 'tallimanngorneq', 'arfininngorneq'], + 'weekdays_short' => ['sap', 'ata', 'mar', 'pin', 'sis', 'tal', 'arf'], + 'weekdays_min' => ['sap', 'ata', 'mar', 'pin', 'sis', 'tal', 'arf'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => '{1}ukioq :count|{0}:count ukiut|]1,Inf[ukiut :count', + 'a_year' => '{1}ukioq|{0}:count ukiut|]1,Inf[ukiut :count', + 'y' => '{1}:countyr|{0}:countyrs|]1,Inf[:countyrs', + + 'month' => '{1}qaammat :count|{0}:count qaammatit|]1,Inf[qaammatit :count', + 'a_month' => '{1}qaammat|{0}:count qaammatit|]1,Inf[qaammatit :count', + 'm' => '{1}:countmo|{0}:countmos|]1,Inf[:countmos', + + 'week' => '{1}:count sap. ak.|{0}:count sap. ak.|]1,Inf[:count sap. ak.', + 'a_week' => '{1}a sap. ak.|{0}:count sap. ak.|]1,Inf[:count sap. ak.', + 'w' => ':countw', + + 'day' => '{1}:count ulloq|{0}:count ullut|]1,Inf[:count ullut', + 'a_day' => '{1}a ulloq|{0}:count ullut|]1,Inf[:count ullut', + 'd' => ':countd', + + 'hour' => '{1}:count tiimi|{0}:count tiimit|]1,Inf[:count tiimit', + 'a_hour' => '{1}tiimi|{0}:count tiimit|]1,Inf[:count tiimit', + 'h' => ':counth', + + 'minute' => '{1}:count minutsi|{0}:count minutsit|]1,Inf[:count minutsit', + 'a_minute' => '{1}a minutsi|{0}:count minutsit|]1,Inf[:count minutsit', + 'min' => ':countm', + + 'second' => '{1}:count sikunti|{0}:count sikuntit|]1,Inf[:count sikuntit', + 'a_second' => '{1}sikunti|{0}:count sikuntit|]1,Inf[:count sikuntit', + 's' => ':counts', + + 'ago' => ':time matuma siorna', + +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kln.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kln.php new file mode 100644 index 0000000..b9c3996 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kln.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['krn', 'koosk'], + 'weekdays' => ['Kotisap', 'Kotaai', 'Koaeng’', 'Kosomok', 'Koang’wan', 'Komuut', 'Kolo'], + 'weekdays_short' => ['Kts', 'Kot', 'Koo', 'Kos', 'Koa', 'Kom', 'Kol'], + 'weekdays_min' => ['Kts', 'Kot', 'Koo', 'Kos', 'Koa', 'Kom', 'Kol'], + 'months' => ['Mulgul', 'Ng’atyaato', 'Kiptaamo', 'Iwootkuut', 'Mamuut', 'Paagi', 'Ng’eiyeet', 'Rooptui', 'Bureet', 'Epeeso', 'Kipsuunde ne taai', 'Kipsuunde nebo aeng’'], + 'months_short' => ['Mul', 'Ngat', 'Taa', 'Iwo', 'Mam', 'Paa', 'Nge', 'Roo', 'Bur', 'Epe', 'Kpt', 'Kpa'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'year' => ':count maghatiat', // less reliable + 'y' => ':count maghatiat', // less reliable + 'a_year' => ':count maghatiat', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/km.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/km.php new file mode 100644 index 0000000..da790ac --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/km.php @@ -0,0 +1,71 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kruy Vanna + * - Sereysethy Touch + * - JD Isaacks + * - Sovichet Tep + */ +return [ + 'year' => '{1}មួយឆ្នាំ|]1,Inf[:count ឆ្នាំ', + 'y' => ':count ឆ្នាំ', + 'month' => '{1}មួយខែ|]1,Inf[:count ខែ', + 'm' => ':count ខែ', + 'week' => ':count សប្ដាហ៍', + 'w' => ':count សប្ដាហ៍', + 'day' => '{1}មួយថ្ងៃ|]1,Inf[:count ថ្ងៃ', + 'd' => ':count ថ្ងៃ', + 'hour' => '{1}មួយម៉ោង|]1,Inf[:count ម៉ោង', + 'h' => ':count ម៉ោង', + 'minute' => '{1}មួយនាទី|]1,Inf[:count នាទី', + 'min' => ':count នាទី', + 'second' => '{1}ប៉ុន្មានវិនាទី|]1,Inf[:count វិនាទី', + 's' => ':count វិនាទី', + 'ago' => ':timeមុន', + 'from_now' => ':timeទៀត', + 'after' => 'នៅ​ក្រោយ :time', + 'before' => 'នៅ​មុន :time', + 'diff_now' => 'ឥឡូវ', + 'diff_today' => 'ថ្ងៃនេះ', + 'diff_today_regexp' => 'ថ្ងៃនេះ(?:\\s+ម៉ោង)?', + 'diff_yesterday' => 'ម្សិលមិញ', + 'diff_yesterday_regexp' => 'ម្សិលមិញ(?:\\s+ម៉ោង)?', + 'diff_tomorrow' => 'ថ្ងៃ​ស្អែក', + 'diff_tomorrow_regexp' => 'ស្អែក(?:\\s+ម៉ោង)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[ថ្ងៃនេះ ម៉ោង] LT', + 'nextDay' => '[ស្អែក ម៉ោង] LT', + 'nextWeek' => 'dddd [ម៉ោង] LT', + 'lastDay' => '[ម្សិលមិញ ម៉ោង] LT', + 'lastWeek' => 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', + 'sameElse' => 'L', + ], + 'ordinal' => 'ទី:number', + 'meridiem' => ['ព្រឹក', 'ល្ងាច'], + 'months' => ['មករា', 'កុម្ភៈ', 'មីនា', 'មេសា', 'ឧសភា', 'មិថុនា', 'កក្កដា', 'សីហា', 'កញ្ញា', 'តុលា', 'វិច្ឆិកា', 'ធ្នូ'], + 'months_short' => ['មករា', 'កុម្ភៈ', 'មីនា', 'មេសា', 'ឧសភា', 'មិថុនា', 'កក្កដា', 'សីហា', 'កញ្ញា', 'តុលា', 'វិច្ឆិកា', 'ធ្នូ'], + 'weekdays' => ['អាទិត្យ', 'ច័ន្ទ', 'អង្គារ', 'ពុធ', 'ព្រហស្បតិ៍', 'សុក្រ', 'សៅរ៍'], + 'weekdays_short' => ['អា', 'ច', 'អ', 'ព', 'ព្រ', 'សុ', 'ស'], + 'weekdays_min' => ['អា', 'ច', 'អ', 'ព', 'ព្រ', 'សុ', 'ស'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', 'និង '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/km_KH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/km_KH.php new file mode 100644 index 0000000..92e5fdb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/km_KH.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/km.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kn.php new file mode 100644 index 0000000..0d2ad08 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kn.php @@ -0,0 +1,75 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - MOHAN M U + * - François B + * - rajeevnaikte + */ +return [ + 'year' => '{1}ಒಂದು ವರ್ಷ|]1,Inf[:count ವರ್ಷ', + 'month' => '{1}ಒಂದು ತಿಂಗಳು|]1,Inf[:count ತಿಂಗಳು', + 'week' => '{1}ಒಂದು ವಾರ|]1,Inf[:count ವಾರಗಳು', + 'day' => '{1}ಒಂದು ದಿನ|]1,Inf[:count ದಿನ', + 'hour' => '{1}ಒಂದು ಗಂಟೆ|]1,Inf[:count ಗಂಟೆ', + 'minute' => '{1}ಒಂದು ನಿಮಿಷ|]1,Inf[:count ನಿಮಿಷ', + 'second' => '{1}ಕೆಲವು ಕ್ಷಣಗಳು|]1,Inf[:count ಸೆಕೆಂಡುಗಳು', + 'ago' => ':time ಹಿಂದೆ', + 'from_now' => ':time ನಂತರ', + 'diff_now' => 'ಈಗ', + 'diff_today' => 'ಇಂದು', + 'diff_yesterday' => 'ನಿನ್ನೆ', + 'diff_tomorrow' => 'ನಾಳೆ', + 'formats' => [ + 'LT' => 'A h:mm', + 'LTS' => 'A h:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm', + ], + 'calendar' => [ + 'sameDay' => '[ಇಂದು] LT', + 'nextDay' => '[ನಾಳೆ] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[ನಿನ್ನೆ] LT', + 'lastWeek' => '[ಕೊನೆಯ] dddd, LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numberನೇ', + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'ರಾತ್ರಿ'; + } + if ($hour < 10) { + return 'ಬೆಳಿಗ್ಗೆ'; + } + if ($hour < 17) { + return 'ಮಧ್ಯಾಹ್ನ'; + } + if ($hour < 20) { + return 'ಸಂಜೆ'; + } + + return 'ರಾತ್ರಿ'; + }, + 'months' => ['ಜನವರಿ', 'ಫೆಬ್ರವರಿ', 'ಮಾರ್ಚ್', 'ಏಪ್ರಿಲ್', 'ಮೇ', 'ಜೂನ್', 'ಜುಲೈ', 'ಆಗಸ್ಟ್', 'ಸೆಪ್ಟೆಂಬರ್', 'ಅಕ್ಟೋಬರ್', 'ನವೆಂಬರ್', 'ಡಿಸೆಂಬರ್'], + 'months_short' => ['ಜನ', 'ಫೆಬ್ರ', 'ಮಾರ್ಚ್', 'ಏಪ್ರಿಲ್', 'ಮೇ', 'ಜೂನ್', 'ಜುಲೈ', 'ಆಗಸ್ಟ್', 'ಸೆಪ್ಟೆಂ', 'ಅಕ್ಟೋ', 'ನವೆಂ', 'ಡಿಸೆಂ'], + 'weekdays' => ['ಭಾನುವಾರ', 'ಸೋಮವಾರ', 'ಮಂಗಳವಾರ', 'ಬುಧವಾರ', 'ಗುರುವಾರ', 'ಶುಕ್ರವಾರ', 'ಶನಿವಾರ'], + 'weekdays_short' => ['ಭಾನು', 'ಸೋಮ', 'ಮಂಗಳ', 'ಬುಧ', 'ಗುರು', 'ಶುಕ್ರ', 'ಶನಿ'], + 'weekdays_min' => ['ಭಾ', 'ಸೋ', 'ಮಂ', 'ಬು', 'ಗು', 'ಶು', 'ಶ'], + 'list' => ', ', + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kn_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kn_IN.php new file mode 100644 index 0000000..30e3d88 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kn_IN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/kn.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko.php new file mode 100644 index 0000000..4fa6237 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko.php @@ -0,0 +1,91 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kunal Marwaha + * - FourwingsY + * - François B + * - Jason Katz-Brown + * - Seokjun Kim + * - Junho Kim + * - JD Isaacks + * - Juwon Kim + */ +return [ + 'year' => ':count년', + 'a_year' => '{1}일년|]1,Inf[:count년', + 'y' => ':count년', + 'month' => ':count개월', + 'a_month' => '{1}한달|]1,Inf[:count개월', + 'm' => ':count개월', + 'week' => ':count주', + 'a_week' => '{1}일주일|]1,Inf[:count 주', + 'w' => ':count주일', + 'day' => ':count일', + 'a_day' => '{1}하루|]1,Inf[:count일', + 'd' => ':count일', + 'hour' => ':count시간', + 'a_hour' => '{1}한시간|]1,Inf[:count시간', + 'h' => ':count시간', + 'minute' => ':count분', + 'a_minute' => '{1}일분|]1,Inf[:count분', + 'min' => ':count분', + 'second' => ':count초', + 'a_second' => '{1}몇초|]1,Inf[:count초', + 's' => ':count초', + 'ago' => ':time 전', + 'from_now' => ':time 후', + 'after' => ':time 후', + 'before' => ':time 전', + 'diff_now' => '지금', + 'diff_today' => '오늘', + 'diff_yesterday' => '어제', + 'diff_tomorrow' => '내일', + 'formats' => [ + 'LT' => 'A h:mm', + 'LTS' => 'A h:mm:ss', + 'L' => 'YYYY.MM.DD.', + 'LL' => 'YYYY년 MMMM D일', + 'LLL' => 'YYYY년 MMMM D일 A h:mm', + 'LLLL' => 'YYYY년 MMMM D일 dddd A h:mm', + ], + 'calendar' => [ + 'sameDay' => '오늘 LT', + 'nextDay' => '내일 LT', + 'nextWeek' => 'dddd LT', + 'lastDay' => '어제 LT', + 'lastWeek' => '지난주 dddd LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'd': + case 'D': + case 'DDD': + return $number.'일'; + case 'M': + return $number.'월'; + case 'w': + case 'W': + return $number.'주'; + default: + return $number; + } + }, + 'meridiem' => ['오전', '오후'], + 'months' => ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'], + 'months_short' => ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'], + 'weekdays' => ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'], + 'weekdays_short' => ['일', '월', '화', '수', '목', '금', '토'], + 'weekdays_min' => ['일', '월', '화', '수', '목', '금', '토'], + 'list' => ' ', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko_KP.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko_KP.php new file mode 100644 index 0000000..4ba802b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko_KP.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ko.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko_KR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko_KR.php new file mode 100644 index 0000000..9d873a2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ko_KR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ko.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kok.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kok.php new file mode 100644 index 0000000..4adcddc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kok.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/kok_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kok_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kok_IN.php new file mode 100644 index 0000000..92ba844 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kok_IN.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat, Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D-M-YY', + ], + 'months' => ['जानेवारी', 'फेब्रुवारी', 'मार्च', 'एप्रिल', 'मे', 'जून', 'जुलै', 'ओगस्ट', 'सेप्टेंबर', 'ओक्टोबर', 'नोव्हेंबर', 'डिसेंबर'], + 'months_short' => ['जानेवारी', 'फेब्रुवारी', 'मार्च', 'एप्रिल', 'मे', 'जून', 'जुलै', 'ओगस्ट', 'सेप्टेंबर', 'ओक्टोबर', 'नोव्हेंबर', 'डिसेंबर'], + 'weekdays' => ['आयतार', 'सोमार', 'मंगळवार', 'बुधवार', 'बेरेसतार', 'शुकरार', 'शेनवार'], + 'weekdays_short' => ['आयतार', 'सोमार', 'मंगळवार', 'बुधवार', 'बेरेसतार', 'शुकरार', 'शेनवार'], + 'weekdays_min' => ['आयतार', 'सोमार', 'मंगळवार', 'बुधवार', 'बेरेसतार', 'शुकरार', 'शेनवार'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['म.पू.', 'म.नं.'], + + 'year' => ':count वैशाकु', // less reliable + 'y' => ':count वैशाकु', // less reliable + 'a_year' => ':count वैशाकु', // less reliable + + 'week' => ':count आदित्यवार', // less reliable + 'w' => ':count आदित्यवार', // less reliable + 'a_week' => ':count आदित्यवार', // less reliable + + 'minute' => ':count नोंद', // less reliable + 'min' => ':count नोंद', // less reliable + 'a_minute' => ':count नोंद', // less reliable + + 'second' => ':count तेंको', // less reliable + 's' => ':count तेंको', // less reliable + 'a_second' => ':count तेंको', // less reliable + + 'month' => ':count मैनो', + 'm' => ':count मैनो', + 'a_month' => ':count मैनो', + + 'day' => ':count दिवसु', + 'd' => ':count दिवसु', + 'a_day' => ':count दिवसु', + + 'hour' => ':count घंते', + 'h' => ':count घंते', + 'a_hour' => ':count घंते', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks.php new file mode 100644 index 0000000..9876079 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ks_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks_IN.php new file mode 100644 index 0000000..ce9d5d4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks_IN.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat, Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'M/D/YY', + ], + 'months' => ['جنؤری', 'فرؤری', 'مارٕچ', 'اپریل', 'میٔ', 'جوٗن', 'جوٗلایی', 'اگست', 'ستمبر', 'اکتوٗبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنؤری', 'فرؤری', 'مارٕچ', 'اپریل', 'میٔ', 'جوٗن', 'جوٗلایی', 'اگست', 'ستمبر', 'اکتوٗبر', 'نومبر', 'دسمبر'], + 'weekdays' => ['آتهوار', 'ژءندروار', 'بوءںوار', 'بودهوار', 'برىسوار', 'جمع', 'بٹوار'], + 'weekdays_short' => ['آتهوار', 'ژءنتروار', 'بوءںوار', 'بودهوار', 'برىسوار', 'جمع', 'بٹوار'], + 'weekdays_min' => ['آتهوار', 'ژءنتروار', 'بوءںوار', 'بودهوار', 'برىسوار', 'جمع', 'بٹوار'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['دوپھربرونھ', 'دوپھرپتھ'], + + 'year' => ':count آب', // less reliable + 'y' => ':count آب', // less reliable + 'a_year' => ':count آب', // less reliable + + 'month' => ':count रान्', // less reliable + 'm' => ':count रान्', // less reliable + 'a_month' => ':count रान्', // less reliable + + 'week' => ':count آتھٕوار', // less reliable + 'w' => ':count آتھٕوار', // less reliable + 'a_week' => ':count آتھٕوار', // less reliable + + 'hour' => ':count سۄن', // less reliable + 'h' => ':count سۄن', // less reliable + 'a_hour' => ':count سۄن', // less reliable + + 'minute' => ':count فَن', // less reliable + 'min' => ':count فَن', // less reliable + 'a_minute' => ':count فَن', // less reliable + + 'second' => ':count दोʼयुम', // less reliable + 's' => ':count दोʼयुम', // less reliable + 'a_second' => ':count दोʼयुम', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks_IN@devanagari.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks_IN@devanagari.php new file mode 100644 index 0000000..a2ae8b6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ks_IN@devanagari.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - ks-gnome-trans-commits@lists.code.indlinux.net + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'M/D/YY', + ], + 'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'months_short' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'weekdays' => ['आथवार', 'चॅ़दुरवार', 'बोमवार', 'ब्वदवार', 'ब्रसवार', 'शोकुरवार', 'बटुवार'], + 'weekdays_short' => ['आथ ', 'चॅ़दुर', 'बोम', 'ब्वद', 'ब्रस', 'शोकुर', 'बटु'], + 'weekdays_min' => ['आथ ', 'चॅ़दुर', 'बोम', 'ब्वद', 'ब्रस', 'शोकुर', 'बटु'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksb.php new file mode 100644 index 0000000..aaa0061 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksb.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['makeo', 'nyiaghuo'], + 'weekdays' => ['Jumaapii', 'Jumaatatu', 'Jumaane', 'Jumaatano', 'Alhamisi', 'Ijumaa', 'Jumaamosi'], + 'weekdays_short' => ['Jpi', 'Jtt', 'Jmn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'weekdays_min' => ['Jpi', 'Jtt', 'Jmn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'months' => ['Januali', 'Febluali', 'Machi', 'Aplili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksf.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksf.php new file mode 100644 index 0000000..84a5967 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksf.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['sárúwá', 'cɛɛ́nko'], + 'weekdays' => ['sɔ́ndǝ', 'lǝndí', 'maadí', 'mɛkrɛdí', 'jǝǝdí', 'júmbá', 'samdí'], + 'weekdays_short' => ['sɔ́n', 'lǝn', 'maa', 'mɛk', 'jǝǝ', 'júm', 'sam'], + 'weekdays_min' => ['sɔ́n', 'lǝn', 'maa', 'mɛk', 'jǝǝ', 'júm', 'sam'], + 'months' => ['ŋwíí a ntɔ́ntɔ', 'ŋwíí akǝ bɛ́ɛ', 'ŋwíí akǝ ráá', 'ŋwíí akǝ nin', 'ŋwíí akǝ táan', 'ŋwíí akǝ táafɔk', 'ŋwíí akǝ táabɛɛ', 'ŋwíí akǝ táaraa', 'ŋwíí akǝ táanin', 'ŋwíí akǝ ntɛk', 'ŋwíí akǝ ntɛk di bɔ́k', 'ŋwíí akǝ ntɛk di bɛ́ɛ'], + 'months_short' => ['ŋ1', 'ŋ2', 'ŋ3', 'ŋ4', 'ŋ5', 'ŋ6', 'ŋ7', 'ŋ8', 'ŋ9', 'ŋ10', 'ŋ11', 'ŋ12'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksh.php new file mode 100644 index 0000000..95457e2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ksh.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['v.M.', 'n.M.'], + 'weekdays' => ['Sunndaach', 'Mohndaach', 'Dinnsdaach', 'Metwoch', 'Dunnersdaach', 'Friidaach', 'Samsdaach'], + 'weekdays_short' => ['Su.', 'Mo.', 'Di.', 'Me.', 'Du.', 'Fr.', 'Sa.'], + 'weekdays_min' => ['Su', 'Mo', 'Di', 'Me', 'Du', 'Fr', 'Sa'], + 'months' => ['Jannewa', 'Fäbrowa', 'Määz', 'Aprell', 'Mai', 'Juuni', 'Juuli', 'Oujoß', 'Septämber', 'Oktohber', 'Novämber', 'Dezämber'], + 'months_short' => ['Jan', 'Fäb', 'Mäz', 'Apr', 'Mai', 'Jun', 'Jul', 'Ouj', 'Säp', 'Okt', 'Nov', 'Dez'], + 'months_short_standalone' => ['Jan.', 'Fäb.', 'Mäz.', 'Apr.', 'Mai', 'Jun.', 'Jul.', 'Ouj.', 'Säp.', 'Okt.', 'Nov.', 'Dez.'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D. M. YYYY', + 'LL' => 'D. MMM. YYYY', + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd, [dä] D. MMMM YYYY HH:mm', + ], + + 'year' => ':count Johr', + 'y' => ':count Johr', + 'a_year' => ':count Johr', + + 'month' => ':count Moohnd', + 'm' => ':count Moohnd', + 'a_month' => ':count Moohnd', + + 'week' => ':count woch', + 'w' => ':count woch', + 'a_week' => ':count woch', + + 'day' => ':count Daach', + 'd' => ':count Daach', + 'a_day' => ':count Daach', + + 'hour' => ':count Uhr', + 'h' => ':count Uhr', + 'a_hour' => ':count Uhr', + + 'minute' => ':count Menutt', + 'min' => ':count Menutt', + 'a_minute' => ':count Menutt', + + 'second' => ':count Sekůndt', + 's' => ':count Sekůndt', + 'a_second' => ':count Sekůndt', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ku.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ku.php new file mode 100644 index 0000000..189960c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ku.php @@ -0,0 +1,40 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Unicode, Inc. + */ + +return [ + 'ago' => 'berî :time', + 'from_now' => 'di :time de', + 'after' => ':time piştî', + 'before' => ':time berê', + 'year' => ':count sal', + 'year_ago' => ':count salê|:count salan', + 'year_from_now' => 'salekê|:count salan', + 'month' => ':count meh', + 'week' => ':count hefte', + 'day' => ':count roj', + 'hour' => ':count saet', + 'minute' => ':count deqîqe', + 'second' => ':count saniye', + 'months' => ['rêbendanê', 'reşemiyê', 'adarê', 'avrêlê', 'gulanê', 'pûşperê', 'tîrmehê', 'gelawêjê', 'rezberê', 'kewçêrê', 'sermawezê', 'berfanbarê'], + 'months_standalone' => ['rêbendan', 'reşemî', 'adar', 'avrêl', 'gulan', 'pûşper', 'tîrmeh', 'gelawêj', 'rezber', 'kewçêr', 'sermawez', 'berfanbar'], + 'months_short' => ['rêb', 'reş', 'ada', 'avr', 'gul', 'pûş', 'tîr', 'gel', 'rez', 'kew', 'ser', 'ber'], + 'weekdays' => ['yekşem', 'duşem', 'sêşem', 'çarşem', 'pêncşem', 'în', 'şemî'], + 'weekdays_short' => ['yş', 'dş', 'sş', 'çş', 'pş', 'în', 'ş'], + 'weekdays_min' => ['Y', 'D', 'S', 'Ç', 'P', 'Î', 'Ş'], + 'list' => [', ', ' û '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ku_TR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ku_TR.php new file mode 100644 index 0000000..4243a82 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ku_TR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ku.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kw.php new file mode 100644 index 0000000..26e242e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kw.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/kw_GB.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kw_GB.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kw_GB.php new file mode 100644 index 0000000..00bf52b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/kw_GB.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Alastair McKinstry bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['mis Genver', 'mis Hwevrer', 'mis Meurth', 'mis Ebrel', 'mis Me', 'mis Metheven', 'mis Gortheren', 'mis Est', 'mis Gwynngala', 'mis Hedra', 'mis Du', 'mis Kevardhu'], + 'months_short' => ['Gen', 'Hwe', 'Meu', 'Ebr', 'Me', 'Met', 'Gor', 'Est', 'Gwn', 'Hed', 'Du', 'Kev'], + 'weekdays' => ['De Sul', 'De Lun', 'De Merth', 'De Merher', 'De Yow', 'De Gwener', 'De Sadorn'], + 'weekdays_short' => ['Sul', 'Lun', 'Mth', 'Mhr', 'Yow', 'Gwe', 'Sad'], + 'weekdays_min' => ['Sul', 'Lun', 'Mth', 'Mhr', 'Yow', 'Gwe', 'Sad'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count bledhen', + 'y' => ':count bledhen', + 'a_year' => ':count bledhen', + + 'month' => ':count mis', + 'm' => ':count mis', + 'a_month' => ':count mis', + + 'week' => ':count seythen', + 'w' => ':count seythen', + 'a_week' => ':count seythen', + + 'day' => ':count dydh', + 'd' => ':count dydh', + 'a_day' => ':count dydh', + + 'hour' => ':count eur', + 'h' => ':count eur', + 'a_hour' => ':count eur', + + 'minute' => ':count mynysen', + 'min' => ':count mynysen', + 'a_minute' => ':count mynysen', + + 'second' => ':count pryjwyth', + 's' => ':count pryjwyth', + 'a_second' => ':count pryjwyth', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ky.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ky.php new file mode 100644 index 0000000..e0d1af1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ky.php @@ -0,0 +1,106 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - acutexyz + * - Josh Soref + * - François B + * - Chyngyz Arystan uulu + * - Chyngyz + * - acutexyz + * - Josh Soref + * - François B + * - Chyngyz Arystan uulu + */ +return [ + 'year' => ':count жыл', + 'a_year' => '{1}бир жыл|:count жыл', + 'y' => ':count жыл', + 'month' => ':count ай', + 'a_month' => '{1}бир ай|:count ай', + 'm' => ':count ай', + 'week' => ':count апта', + 'a_week' => '{1}бир апта|:count апта', + 'w' => ':count апт.', + 'day' => ':count күн', + 'a_day' => '{1}бир күн|:count күн', + 'd' => ':count күн', + 'hour' => ':count саат', + 'a_hour' => '{1}бир саат|:count саат', + 'h' => ':count саат.', + 'minute' => ':count мүнөт', + 'a_minute' => '{1}бир мүнөт|:count мүнөт', + 'min' => ':count мүн.', + 'second' => ':count секунд', + 'a_second' => '{1}бирнече секунд|:count секунд', + 's' => ':count сек.', + 'ago' => ':time мурун', + 'from_now' => ':time ичинде', + 'diff_now' => 'азыр', + 'diff_today' => 'Бүгүн', + 'diff_today_regexp' => 'Бүгүн(?:\\s+саат)?', + 'diff_yesterday' => 'кечээ', + 'diff_yesterday_regexp' => 'Кече(?:\\s+саат)?', + 'diff_tomorrow' => 'эртең', + 'diff_tomorrow_regexp' => 'Эртең(?:\\s+саат)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Бүгүн саат] LT', + 'nextDay' => '[Эртең саат] LT', + 'nextWeek' => 'dddd [саат] LT', + 'lastDay' => '[Кече саат] LT', + 'lastWeek' => '[Өткен аптанын] dddd [күнү] [саат] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + static $suffixes = [ + 0 => '-чү', + 1 => '-чи', + 2 => '-чи', + 3 => '-чү', + 4 => '-чү', + 5 => '-чи', + 6 => '-чы', + 7 => '-чи', + 8 => '-чи', + 9 => '-чу', + 10 => '-чу', + 20 => '-чы', + 30 => '-чу', + 40 => '-чы', + 50 => '-чү', + 60 => '-чы', + 70 => '-чи', + 80 => '-чи', + 90 => '-чу', + 100 => '-чү', + ]; + + return $number.($suffixes[$number] ?? $suffixes[$number % 10] ?? $suffixes[$number >= 100 ? 100 : -1] ?? ''); + }, + 'months' => ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'], + 'months_short' => ['янв', 'фев', 'март', 'апр', 'май', 'июнь', 'июль', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'weekdays' => ['Жекшемби', 'Дүйшөмбү', 'Шейшемби', 'Шаршемби', 'Бейшемби', 'Жума', 'Ишемби'], + 'weekdays_short' => ['Жек', 'Дүй', 'Шей', 'Шар', 'Бей', 'Жум', 'Ише'], + 'weekdays_min' => ['Жк', 'Дй', 'Шй', 'Шр', 'Бй', 'Жм', 'Иш'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => ' ', + 'meridiem' => ['таңкы', 'түштөн кийинки'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ky_KG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ky_KG.php new file mode 100644 index 0000000..9923a31 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ky_KG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ky.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lag.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lag.php new file mode 100644 index 0000000..f3f57f6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lag.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['TOO', 'MUU'], + 'weekdays' => ['Jumapíiri', 'Jumatátu', 'Jumaíne', 'Jumatáano', 'Alamíisi', 'Ijumáa', 'Jumamóosi'], + 'weekdays_short' => ['Píili', 'Táatu', 'Íne', 'Táano', 'Alh', 'Ijm', 'Móosi'], + 'weekdays_min' => ['Píili', 'Táatu', 'Íne', 'Táano', 'Alh', 'Ijm', 'Móosi'], + 'months' => ['Kʉfúngatɨ', 'Kʉnaanɨ', 'Kʉkeenda', 'Kwiikumi', 'Kwiinyambála', 'Kwiidwaata', 'Kʉmʉʉnchɨ', 'Kʉvɨɨrɨ', 'Kʉsaatʉ', 'Kwiinyi', 'Kʉsaano', 'Kʉsasatʉ'], + 'months_short' => ['Fúngatɨ', 'Naanɨ', 'Keenda', 'Ikúmi', 'Inyambala', 'Idwaata', 'Mʉʉnchɨ', 'Vɨɨrɨ', 'Saatʉ', 'Inyi', 'Saano', 'Sasatʉ'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lb.php new file mode 100644 index 0000000..7636655 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lb.php @@ -0,0 +1,88 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Tsutomu Kuroda + * - dan-nl + * - Simon Lelorrain (slelorrain) + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count Joer', + 'y' => ':countJ', + 'month' => ':count Mount|:count Méint', + 'm' => ':countMo', + 'week' => ':count Woch|:count Wochen', + 'w' => ':countWo|:countWo', + 'day' => ':count Dag|:count Deeg', + 'd' => ':countD', + 'hour' => ':count Stonn|:count Stonnen', + 'h' => ':countSto', + 'minute' => ':count Minutt|:count Minutten', + 'min' => ':countM', + 'second' => ':count Sekonn|:count Sekonnen', + 's' => ':countSek', + + 'ago' => 'virun :time', + 'from_now' => 'an :time', + 'before' => ':time virdrun', + 'after' => ':time duerno', + + 'diff_today' => 'Haut', + 'diff_yesterday' => 'Gëschter', + 'diff_yesterday_regexp' => 'Gëschter(?:\\s+um)?', + 'diff_tomorrow' => 'Muer', + 'diff_tomorrow_regexp' => 'Muer(?:\\s+um)?', + 'diff_today_regexp' => 'Haut(?:\\s+um)?', + 'formats' => [ + 'LT' => 'H:mm [Auer]', + 'LTS' => 'H:mm:ss [Auer]', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY H:mm [Auer]', + 'LLLL' => 'dddd, D. MMMM YYYY H:mm [Auer]', + ], + + 'calendar' => [ + 'sameDay' => '[Haut um] LT', + 'nextDay' => '[Muer um] LT', + 'nextWeek' => 'dddd [um] LT', + 'lastDay' => '[Gëschter um] LT', + 'lastWeek' => function (CarbonInterface $date) { + // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule + switch ($date->dayOfWeek) { + case 2: + case 4: + return '[Leschten] dddd [um] LT'; + default: + return '[Leschte] dddd [um] LT'; + } + }, + 'sameElse' => 'L', + ], + + 'months' => ['Januar', 'Februar', 'Mäerz', 'Abrëll', 'Mee', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], + 'months_short' => ['Jan.', 'Febr.', 'Mrz.', 'Abr.', 'Mee', 'Jun.', 'Jul.', 'Aug.', 'Sept.', 'Okt.', 'Nov.', 'Dez.'], + 'weekdays' => ['Sonndeg', 'Méindeg', 'Dënschdeg', 'Mëttwoch', 'Donneschdeg', 'Freideg', 'Samschdeg'], + 'weekdays_short' => ['So.', 'Mé.', 'Dë.', 'Më.', 'Do.', 'Fr.', 'Sa.'], + 'weekdays_min' => ['So', 'Mé', 'Dë', 'Më', 'Do', 'Fr', 'Sa'], + 'ordinal' => ':number.', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' an '], + 'meridiem' => ['moies', 'mëttes'], + 'weekdays_short_standalone' => ['Son', 'Méi', 'Dën', 'Mët', 'Don', 'Fre', 'Sam'], + 'months_short_standalone' => ['Jan', 'Feb', 'Mäe', 'Abr', 'Mee', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lb_LU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lb_LU.php new file mode 100644 index 0000000..414bd4d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lb_LU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/lb.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lg.php new file mode 100644 index 0000000..48bc68b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lg.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/lg_UG.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lg_UG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lg_UG.php new file mode 100644 index 0000000..aa02214 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lg_UG.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Akademe ya Luganda Kizito Birabwa kompyuta@kizito.uklinux.net + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Janwaliyo', 'Febwaliyo', 'Marisi', 'Apuli', 'Maayi', 'Juuni', 'Julaayi', 'Agusito', 'Sebuttemba', 'Okitobba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apu', 'Maa', 'Juu', 'Jul', 'Agu', 'Seb', 'Oki', 'Nov', 'Des'], + 'weekdays' => ['Sabiiti', 'Balaza', 'Lwakubiri', 'Lwakusatu', 'Lwakuna', 'Lwakutaano', 'Lwamukaaga'], + 'weekdays_short' => ['Sab', 'Bal', 'Lw2', 'Lw3', 'Lw4', 'Lw5', 'Lw6'], + 'weekdays_min' => ['Sab', 'Bal', 'Lw2', 'Lw3', 'Lw4', 'Lw5', 'Lw6'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'month' => ':count njuba', // less reliable + 'm' => ':count njuba', // less reliable + 'a_month' => ':count njuba', // less reliable + + 'year' => ':count mwaaka', + 'y' => ':count mwaaka', + 'a_year' => ':count mwaaka', + + 'week' => ':count sabbiiti', + 'w' => ':count sabbiiti', + 'a_week' => ':count sabbiiti', + + 'day' => ':count lunaku', + 'd' => ':count lunaku', + 'a_day' => ':count lunaku', + + 'hour' => 'saawa :count', + 'h' => 'saawa :count', + 'a_hour' => 'saawa :count', + + 'minute' => 'ddakiika :count', + 'min' => 'ddakiika :count', + 'a_minute' => 'ddakiika :count', + + 'second' => ':count kyʼokubiri', + 's' => ':count kyʼokubiri', + 'a_second' => ':count kyʼokubiri', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/li.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/li.php new file mode 100644 index 0000000..86c3009 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/li.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/li_NL.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/li_NL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/li_NL.php new file mode 100644 index 0000000..6c5feb7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/li_NL.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - information from Kenneth Christiansen Kenneth Christiansen, Pablo Saratxaga kenneth@gnu.org, pablo@mandriva.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['jannewarie', 'fibberwarie', 'miert', 'eprèl', 'meij', 'junie', 'julie', 'augustus', 'september', 'oktober', 'november', 'desember'], + 'months_short' => ['jan', 'fib', 'mie', 'epr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'], + 'weekdays' => ['zóndig', 'maondig', 'daensdig', 'goonsdig', 'dónderdig', 'vriedig', 'zaoterdig'], + 'weekdays_short' => ['zón', 'mao', 'dae', 'goo', 'dón', 'vri', 'zao'], + 'weekdays_min' => ['zón', 'mao', 'dae', 'goo', 'dón', 'vri', 'zao'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'minute' => ':count momênt', // less reliable + 'min' => ':count momênt', // less reliable + 'a_minute' => ':count momênt', // less reliable + + 'year' => ':count jaor', + 'y' => ':count jaor', + 'a_year' => ':count jaor', + + 'month' => ':count maond', + 'm' => ':count maond', + 'a_month' => ':count maond', + + 'week' => ':count waek', + 'w' => ':count waek', + 'a_week' => ':count waek', + + 'day' => ':count daag', + 'd' => ':count daag', + 'a_day' => ':count daag', + + 'hour' => ':count oer', + 'h' => ':count oer', + 'a_hour' => ':count oer', + + 'second' => ':count Secónd', + 's' => ':count Secónd', + 'a_second' => ':count Secónd', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lij.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lij.php new file mode 100644 index 0000000..45732b5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lij.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/lij_IT.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lij_IT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lij_IT.php new file mode 100644 index 0000000..f8726fd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lij_IT.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Gastaldi alessio.gastaldi@libero.it + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['zenâ', 'fevrâ', 'marzo', 'avrî', 'mazzo', 'zûgno', 'lûggio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dixembre'], + 'months_short' => ['zen', 'fev', 'mar', 'arv', 'maz', 'zûg', 'lûg', 'ago', 'set', 'ött', 'nov', 'dix'], + 'weekdays' => ['domenega', 'lûnedì', 'martedì', 'mercUrdì', 'zêggia', 'venardì', 'sabbo'], + 'weekdays_short' => ['dom', 'lûn', 'mar', 'mer', 'zêu', 'ven', 'sab'], + 'weekdays_min' => ['dom', 'lûn', 'mar', 'mer', 'zêu', 'ven', 'sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count etæ', // less reliable + 'y' => ':count etæ', // less reliable + 'a_year' => ':count etæ', // less reliable + + 'month' => ':count meize', + 'm' => ':count meize', + 'a_month' => ':count meize', + + 'week' => ':count settemannha', + 'w' => ':count settemannha', + 'a_week' => ':count settemannha', + + 'day' => ':count giorno', + 'd' => ':count giorno', + 'a_day' => ':count giorno', + + 'hour' => ':count reléuio', // less reliable + 'h' => ':count reléuio', // less reliable + 'a_hour' => ':count reléuio', // less reliable + + 'minute' => ':count menûo', + 'min' => ':count menûo', + 'a_minute' => ':count menûo', + + 'second' => ':count segondo', + 's' => ':count segondo', + 'a_second' => ':count segondo', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lkt.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lkt.php new file mode 100644 index 0000000..ae73a97 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lkt.php @@ -0,0 +1,41 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + + 'month' => ':count haŋwí', // less reliable + 'm' => ':count haŋwí', // less reliable + 'a_month' => ':count haŋwí', // less reliable + + 'week' => ':count šakówiŋ', // less reliable + 'w' => ':count šakówiŋ', // less reliable + 'a_week' => ':count šakówiŋ', // less reliable + + 'hour' => ':count maza škaŋškaŋ', // less reliable + 'h' => ':count maza škaŋškaŋ', // less reliable + 'a_hour' => ':count maza škaŋškaŋ', // less reliable + + 'minute' => ':count číkʼala', // less reliable + 'min' => ':count číkʼala', // less reliable + 'a_minute' => ':count číkʼala', // less reliable + + 'year' => ':count waníyetu', + 'y' => ':count waníyetu', + 'a_year' => ':count waníyetu', + + 'day' => ':count aŋpétu', + 'd' => ':count aŋpétu', + 'a_day' => ':count aŋpétu', + + 'second' => ':count icinuŋpa', + 's' => ':count icinuŋpa', + 'a_second' => ':count icinuŋpa', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln.php new file mode 100644 index 0000000..9d5c35d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ubuntu René Manassé GALEKWA renemanasse@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'months' => ['sánzá ya yambo', 'sánzá ya míbalé', 'sánzá ya mísáto', 'sánzá ya mínei', 'sánzá ya mítáno', 'sánzá ya motóbá', 'sánzá ya nsambo', 'sánzá ya mwambe', 'sánzá ya libwa', 'sánzá ya zómi', 'sánzá ya zómi na mɔ̌kɔ́', 'sánzá ya zómi na míbalé'], + 'months_short' => ['yan', 'fbl', 'msi', 'apl', 'mai', 'yun', 'yul', 'agt', 'stb', 'ɔtb', 'nvb', 'dsb'], + 'weekdays' => ['Lomíngo', 'Mosálá mɔ̌kɔ́', 'Misálá míbalé', 'Misálá mísáto', 'Misálá mínei', 'Misálá mítáno', 'Mpɔ́sɔ'], + 'weekdays_short' => ['m1.', 'm2.', 'm3.', 'm4.', 'm5.', 'm6.', 'm7.'], + 'weekdays_min' => ['m1.', 'm2.', 'm3.', 'm4.', 'm5.', 'm6.', 'm7.'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => 'mbula :count', + 'y' => 'mbula :count', + 'a_year' => 'mbula :count', + + 'month' => 'sánzá :count', + 'm' => 'sánzá :count', + 'a_month' => 'sánzá :count', + + 'week' => 'mpɔ́sɔ :count', + 'w' => 'mpɔ́sɔ :count', + 'a_week' => 'mpɔ́sɔ :count', + + 'day' => 'mokɔlɔ :count', + 'd' => 'mokɔlɔ :count', + 'a_day' => 'mokɔlɔ :count', + + 'hour' => 'ngonga :count', + 'h' => 'ngonga :count', + 'a_hour' => 'ngonga :count', + + 'minute' => 'miniti :count', + 'min' => 'miniti :count', + 'a_minute' => 'miniti :count', + + 'second' => 'segɔnde :count', + 's' => 'segɔnde :count', + 'a_second' => 'segɔnde :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_AO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_AO.php new file mode 100644 index 0000000..7fdb7f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_AO.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ln.php', [ + 'weekdays' => ['eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', 'mokɔlɔ mwa mísáto', 'mokɔlɔ ya mínéi', 'mokɔlɔ ya mítáno', 'mpɔ́sɔ'], + 'weekdays_short' => ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], + 'weekdays_min' => ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], + 'meridiem' => ['ntɔ́ngɔ́', 'mpókwa'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CD.php new file mode 100644 index 0000000..13635fc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CD.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ubuntu René Manassé GALEKWA renemanasse@gmail.com + */ +return require __DIR__.'/ln.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CF.php new file mode 100644 index 0000000..7fdb7f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CF.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ln.php', [ + 'weekdays' => ['eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', 'mokɔlɔ mwa mísáto', 'mokɔlɔ ya mínéi', 'mokɔlɔ ya mítáno', 'mpɔ́sɔ'], + 'weekdays_short' => ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], + 'weekdays_min' => ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], + 'meridiem' => ['ntɔ́ngɔ́', 'mpókwa'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CG.php new file mode 100644 index 0000000..7fdb7f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ln_CG.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ln.php', [ + 'weekdays' => ['eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', 'mokɔlɔ mwa mísáto', 'mokɔlɔ ya mínéi', 'mokɔlɔ ya mítáno', 'mpɔ́sɔ'], + 'weekdays_short' => ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], + 'weekdays_min' => ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], + 'meridiem' => ['ntɔ́ngɔ́', 'mpókwa'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lo.php new file mode 100644 index 0000000..48715f5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lo.php @@ -0,0 +1,62 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - ryanhart2 + */ +return [ + 'year' => ':count ປີ', + 'y' => ':count ປີ', + 'month' => ':count ເດືອນ', + 'm' => ':count ດ. ', + 'week' => ':count ອາທິດ', + 'w' => ':count ອທ. ', + 'day' => ':count ມື້', + 'd' => ':count ມື້', + 'hour' => ':count ຊົ່ວໂມງ', + 'h' => ':count ຊມ. ', + 'minute' => ':count ນາທີ', + 'min' => ':count ນທ. ', + 'second' => '{1}ບໍ່ເທົ່າໃດວິນາທີ|]1,Inf[:count ວິນາທີ', + 's' => ':count ວິ. ', + 'ago' => ':timeຜ່ານມາ', + 'from_now' => 'ອີກ :time', + 'diff_now' => 'ຕອນນີ້', + 'diff_today' => 'ມື້ນີ້ເວລາ', + 'diff_yesterday' => 'ມື້ວານນີ້ເວລາ', + 'diff_tomorrow' => 'ມື້ອື່ນເວລາ', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'ວັນdddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[ມື້ນີ້ເວລາ] LT', + 'nextDay' => '[ມື້ອື່ນເວລາ] LT', + 'nextWeek' => '[ວັນ]dddd[ໜ້າເວລາ] LT', + 'lastDay' => '[ມື້ວານນີ້ເວລາ] LT', + 'lastWeek' => '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', + 'sameElse' => 'L', + ], + 'ordinal' => 'ທີ່:number', + 'meridiem' => ['ຕອນເຊົ້າ', 'ຕອນແລງ'], + 'months' => ['ມັງກອນ', 'ກຸມພາ', 'ມີນາ', 'ເມສາ', 'ພຶດສະພາ', 'ມິຖຸນາ', 'ກໍລະກົດ', 'ສິງຫາ', 'ກັນຍາ', 'ຕຸລາ', 'ພະຈິກ', 'ທັນວາ'], + 'months_short' => ['ມັງກອນ', 'ກຸມພາ', 'ມີນາ', 'ເມສາ', 'ພຶດສະພາ', 'ມິຖຸນາ', 'ກໍລະກົດ', 'ສິງຫາ', 'ກັນຍາ', 'ຕຸລາ', 'ພະຈິກ', 'ທັນວາ'], + 'weekdays' => ['ອາທິດ', 'ຈັນ', 'ອັງຄານ', 'ພຸດ', 'ພະຫັດ', 'ສຸກ', 'ເສົາ'], + 'weekdays_short' => ['ທິດ', 'ຈັນ', 'ອັງຄານ', 'ພຸດ', 'ພະຫັດ', 'ສຸກ', 'ເສົາ'], + 'weekdays_min' => ['ທ', 'ຈ', 'ອຄ', 'ພ', 'ພຫ', 'ສກ', 'ສ'], + 'list' => [', ', 'ແລະ '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lo_LA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lo_LA.php new file mode 100644 index 0000000..9b7fd9b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lo_LA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/lo.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lrc.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lrc.php new file mode 100644 index 0000000..546e679 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lrc.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + + 'minute' => ':count هنر', // less reliable + 'min' => ':count هنر', // less reliable + 'a_minute' => ':count هنر', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lrc_IQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lrc_IQ.php new file mode 100644 index 0000000..d42f5e9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lrc_IQ.php @@ -0,0 +1,13 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/lrc.php', [ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lt.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lt.php new file mode 100644 index 0000000..7d1b6f7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lt.php @@ -0,0 +1,135 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Tsutomu Kuroda + * - tjku + * - valdas406 + * - Justas Palumickas + * - Max Melentiev + * - Andrius Janauskas + * - Juanito Fatas + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Nicolás Hock Isaza + * - Laurynas Butkus + * - Sven Fuchs + * - Dominykas Tijūnaitis + * - Justinas Bolys + * - Ričardas + * - Kirill Chalkin + * - Rolandas + * - Justinas (Gamesh) + */ +return [ + 'year' => ':count metai|:count metai|:count metų', + 'y' => ':count m.', + 'month' => ':count mėnuo|:count mėnesiai|:count mėnesį', + 'm' => ':count mėn.', + 'week' => ':count savaitė|:count savaitės|:count savaitę', + 'w' => ':count sav.', + 'day' => ':count diena|:count dienos|:count dienų', + 'd' => ':count d.', + 'hour' => ':count valanda|:count valandos|:count valandų', + 'h' => ':count val.', + 'minute' => ':count minutė|:count minutės|:count minutę', + 'min' => ':count min.', + 'second' => ':count sekundė|:count sekundės|:count sekundžių', + 's' => ':count sek.', + + 'year_ago' => ':count metus|:count metus|:count metų', + 'month_ago' => ':count mėnesį|:count mėnesius|:count mėnesių', + 'week_ago' => ':count savaitę|:count savaites|:count savaičių', + 'day_ago' => ':count dieną|:count dienas|:count dienų', + 'hour_ago' => ':count valandą|:count valandas|:count valandų', + 'minute_ago' => ':count minutę|:count minutes|:count minučių', + 'second_ago' => ':count sekundę|:count sekundes|:count sekundžių', + + 'year_from_now' => ':count metų', + 'month_from_now' => ':count mėnesio|:count mėnesių|:count mėnesių', + 'week_from_now' => ':count savaitės|:count savaičių|:count savaičių', + 'day_from_now' => ':count dienos|:count dienų|:count dienų', + 'hour_from_now' => ':count valandos|:count valandų|:count valandų', + 'minute_from_now' => ':count minutės|:count minučių|:count minučių', + 'second_from_now' => ':count sekundės|:count sekundžių|:count sekundžių', + + 'year_after' => ':count metų', + 'month_after' => ':count mėnesio|:count mėnesių|:count mėnesių', + 'week_after' => ':count savaitės|:count savaičių|:count savaičių', + 'day_after' => ':count dienos|:count dienų|:count dienų', + 'hour_after' => ':count valandos|:count valandų|:count valandų', + 'minute_after' => ':count minutės|:count minučių|:count minučių', + 'second_after' => ':count sekundės|:count sekundžių|:count sekundžių', + + 'ago' => 'prieš :time', + 'from_now' => ':time nuo dabar', + 'after' => 'po :time', + 'before' => 'už :time', + + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'diff_now' => 'ką tik', + 'diff_today' => 'Šiandien', + 'diff_yesterday' => 'vakar', + 'diff_yesterday_regexp' => 'Vakar', + 'diff_tomorrow' => 'rytoj', + 'diff_tomorrow_regexp' => 'Rytoj', + 'diff_before_yesterday' => 'užvakar', + 'diff_after_tomorrow' => 'poryt', + + 'period_recurrences' => 'kartą|:count kartų', + 'period_interval' => 'kiekvieną :interval', + 'period_start_date' => 'nuo :date', + 'period_end_date' => 'iki :date', + + 'months' => ['sausio', 'vasario', 'kovo', 'balandžio', 'gegužės', 'birželio', 'liepos', 'rugpjūčio', 'rugsėjo', 'spalio', 'lapkričio', 'gruodžio'], + 'months_standalone' => ['sausis', 'vasaris', 'kovas', 'balandis', 'gegužė', 'birželis', 'liepa', 'rugpjūtis', 'rugsėjis', 'spalis', 'lapkritis', 'gruodis'], + 'months_regexp' => '/(L{2,4}|D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?)/', + 'months_short' => ['sau', 'vas', 'kov', 'bal', 'geg', 'bir', 'lie', 'rgp', 'rgs', 'spa', 'lap', 'gru'], + 'weekdays' => ['sekmadienį', 'pirmadienį', 'antradienį', 'trečiadienį', 'ketvirtadienį', 'penktadienį', 'šeštadienį'], + 'weekdays_standalone' => ['sekmadienis', 'pirmadienis', 'antradienis', 'trečiadienis', 'ketvirtadienis', 'penktadienis', 'šeštadienis'], + 'weekdays_short' => ['sek', 'pir', 'ant', 'tre', 'ket', 'pen', 'šeš'], + 'weekdays_min' => ['se', 'pi', 'an', 'tr', 'ke', 'pe', 'še'], + 'list' => [', ', ' ir '], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'MMMM DD, YYYY', + 'LLL' => 'DD MMM HH:mm', + 'LLLL' => 'MMMM DD, YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Šiandien] LT', + 'nextDay' => '[Rytoj] LT', + 'nextWeek' => 'dddd LT', + 'lastDay' => '[Vakar] LT', + 'lastWeek' => '[Paskutinį] dddd LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + switch ($number) { + case 0: + return '0-is'; + case 3: + return '3-ias'; + default: + return "$number-as"; + } + }, + 'meridiem' => ['priešpiet', 'popiet'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lt_LT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lt_LT.php new file mode 100644 index 0000000..f772d38 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lt_LT.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/lt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lu.php new file mode 100644 index 0000000..c8cd83a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lu.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Dinda', 'Dilolo'], + 'weekdays' => ['Lumingu', 'Nkodya', 'Ndàayà', 'Ndangù', 'Njòwa', 'Ngòvya', 'Lubingu'], + 'weekdays_short' => ['Lum', 'Nko', 'Ndy', 'Ndg', 'Njw', 'Ngv', 'Lub'], + 'weekdays_min' => ['Lum', 'Nko', 'Ndy', 'Ndg', 'Njw', 'Ngv', 'Lub'], + 'months' => ['Ciongo', 'Lùishi', 'Lusòlo', 'Mùuyà', 'Lumùngùlù', 'Lufuimi', 'Kabàlàshìpù', 'Lùshìkà', 'Lutongolo', 'Lungùdi', 'Kaswèkèsè', 'Ciswà'], + 'months_short' => ['Cio', 'Lui', 'Lus', 'Muu', 'Lum', 'Luf', 'Kab', 'Lush', 'Lut', 'Lun', 'Kas', 'Cis'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/luo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/luo.php new file mode 100644 index 0000000..b55af73 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/luo.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['OD', 'OT'], + 'weekdays' => ['Jumapil', 'Wuok Tich', 'Tich Ariyo', 'Tich Adek', 'Tich Ang’wen', 'Tich Abich', 'Ngeso'], + 'weekdays_short' => ['JMP', 'WUT', 'TAR', 'TAD', 'TAN', 'TAB', 'NGS'], + 'weekdays_min' => ['JMP', 'WUT', 'TAR', 'TAD', 'TAN', 'TAB', 'NGS'], + 'months' => ['Dwe mar Achiel', 'Dwe mar Ariyo', 'Dwe mar Adek', 'Dwe mar Ang’wen', 'Dwe mar Abich', 'Dwe mar Auchiel', 'Dwe mar Abiriyo', 'Dwe mar Aboro', 'Dwe mar Ochiko', 'Dwe mar Apar', 'Dwe mar gi achiel', 'Dwe mar Apar gi ariyo'], + 'months_short' => ['DAC', 'DAR', 'DAD', 'DAN', 'DAH', 'DAU', 'DAO', 'DAB', 'DOC', 'DAP', 'DGI', 'DAG'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'year' => 'higni :count', + 'y' => 'higni :count', + 'a_year' => ':higni :count', + + 'month' => 'dweche :count', + 'm' => 'dweche :count', + 'a_month' => 'dweche :count', + + 'week' => 'jumbe :count', + 'w' => 'jumbe :count', + 'a_week' => 'jumbe :count', + + 'day' => 'ndalo :count', + 'd' => 'ndalo :count', + 'a_day' => 'ndalo :count', + + 'hour' => 'seche :count', + 'h' => 'seche :count', + 'a_hour' => 'seche :count', + + 'minute' => 'dakika :count', + 'min' => 'dakika :count', + 'a_minute' => 'dakika :count', + + 'second' => 'nus dakika :count', + 's' => 'nus dakika :count', + 'a_second' => 'nus dakika :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/luy.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/luy.php new file mode 100644 index 0000000..2b37e3e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/luy.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Jumapiri', 'Jumatatu', 'Jumanne', 'Jumatano', 'Murwa wa Kanne', 'Murwa wa Katano', 'Jumamosi'], + 'weekdays_short' => ['J2', 'J3', 'J4', 'J5', 'Al', 'Ij', 'J1'], + 'weekdays_min' => ['J2', 'J3', 'J4', 'J5', 'Al', 'Ij', 'J1'], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + // Too unreliable + /* + 'year' => ':count liliino', // less reliable + 'y' => ':count liliino', // less reliable + 'a_year' => ':count liliino', // less reliable + + 'month' => ':count kumwesi', // less reliable + 'm' => ':count kumwesi', // less reliable + 'a_month' => ':count kumwesi', // less reliable + + 'week' => ':count olutambi', // less reliable + 'w' => ':count olutambi', // less reliable + 'a_week' => ':count olutambi', // less reliable + + 'day' => ':count luno', // less reliable + 'd' => ':count luno', // less reliable + 'a_day' => ':count luno', // less reliable + + 'hour' => ':count ekengele', // less reliable + 'h' => ':count ekengele', // less reliable + 'a_hour' => ':count ekengele', // less reliable + + 'minute' => ':count omundu', // less reliable + 'min' => ':count omundu', // less reliable + 'a_minute' => ':count omundu', // less reliable + + 'second' => ':count liliino', // less reliable + 's' => ':count liliino', // less reliable + 'a_second' => ':count liliino', // less reliable + */ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lv.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lv.php new file mode 100644 index 0000000..d5cba7c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lv.php @@ -0,0 +1,183 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Carbon\CarbonInterface; + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - pirminis + * - Tsutomu Kuroda + * - tjku + * - Andris Zāģeris + * - Max Melentiev + * - Edgars Beigarts + * - Juanito Fatas + * - Vitauts Stočka + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Kaspars Bankovskis + * - Nicolás Hock Isaza + * - Viesturs Kavacs (Kavacky) + * - zakse + * - Janis Eglitis (janiseglitis) + * - Guntars + * - Juris Sudmalis + */ +$daysOfWeek = ['svētdiena', 'pirmdiena', 'otrdiena', 'trešdiena', 'ceturtdiena', 'piektdiena', 'sestdiena']; +$daysOfWeekLocativum = ['svētdien', 'pirmdien', 'otrdien', 'trešdien', 'ceturtdien', 'piektdien', 'sestdien']; + +$transformDiff = function ($input) { + return strtr($input, [ + // Nominative => "pirms/pēc" Dative + 'gads' => 'gada', + 'gadi' => 'gadiem', + 'gadu' => 'gadiem', + 'mēnesis' => 'mēneša', + 'mēneši' => 'mēnešiem', + 'mēnešu' => 'mēnešiem', + 'nedēļa' => 'nedēļas', + 'nedēļas' => 'nedēļām', + 'nedēļu' => 'nedēļām', + 'diena' => 'dienas', + 'dienas' => 'dienām', + 'dienu' => 'dienām', + 'stunda' => 'stundas', + 'stundas' => 'stundām', + 'stundu' => 'stundām', + 'minūte' => 'minūtes', + 'minūtes' => 'minūtēm', + 'minūšu' => 'minūtēm', + 'sekunde' => 'sekundes', + 'sekundes' => 'sekundēm', + 'sekunžu' => 'sekundēm', + ]); +}; + +return [ + 'ago' => function ($time) use ($transformDiff) { + return 'pirms '.$transformDiff($time); + }, + 'from_now' => function ($time) use ($transformDiff) { + return 'pēc '.$transformDiff($time); + }, + + 'year' => '0 gadu|:count gads|:count gadi', + 'y' => ':count g.', + 'a_year' => '{1}gads|0 gadu|:count gads|:count gadi', + 'month' => '0 mēnešu|:count mēnesis|:count mēneši', + 'm' => ':count mēn.', + 'a_month' => '{1}mēnesis|0 mēnešu|:count mēnesis|:count mēneši', + 'week' => '0 nedēļu|:count nedēļa|:count nedēļas', + 'w' => ':count ned.', + 'a_week' => '{1}nedēļa|0 nedēļu|:count nedēļa|:count nedēļas', + 'day' => '0 dienu|:count diena|:count dienas', + 'd' => ':count d.', + 'a_day' => '{1}diena|0 dienu|:count diena|:count dienas', + 'hour' => '0 stundu|:count stunda|:count stundas', + 'h' => ':count st.', + 'a_hour' => '{1}stunda|0 stundu|:count stunda|:count stundas', + 'minute' => '0 minūšu|:count minūte|:count minūtes', + 'min' => ':count min.', + 'a_minute' => '{1}minūte|0 minūšu|:count minūte|:count minūtes', + 'second' => '0 sekunžu|:count sekunde|:count sekundes', + 's' => ':count sek.', + 'a_second' => '{1}sekunde|0 sekunžu|:count sekunde|:count sekundes', + + 'after' => ':time vēlāk', + 'year_after' => '0 gadus|:count gadu|:count gadus', + 'a_year_after' => '{1}gadu|0 gadus|:count gadu|:count gadus', + 'month_after' => '0 mēnešus|:count mēnesi|:count mēnešus', + 'a_month_after' => '{1}mēnesi|0 mēnešus|:count mēnesi|:count mēnešus', + 'week_after' => '0 nedēļas|:count nedēļu|:count nedēļas', + 'a_week_after' => '{1}nedēļu|0 nedēļas|:count nedēļu|:count nedēļas', + 'day_after' => '0 dienas|:count dienu|:count dienas', + 'a_day_after' => '{1}dienu|0 dienas|:count dienu|:count dienas', + 'hour_after' => '0 stundas|:count stundu|:count stundas', + 'a_hour_after' => '{1}stundu|0 stundas|:count stundu|:count stundas', + 'minute_after' => '0 minūtes|:count minūti|:count minūtes', + 'a_minute_after' => '{1}minūti|0 minūtes|:count minūti|:count minūtes', + 'second_after' => '0 sekundes|:count sekundi|:count sekundes', + 'a_second_after' => '{1}sekundi|0 sekundes|:count sekundi|:count sekundes', + + 'before' => ':time agrāk', + 'year_before' => '0 gadus|:count gadu|:count gadus', + 'a_year_before' => '{1}gadu|0 gadus|:count gadu|:count gadus', + 'month_before' => '0 mēnešus|:count mēnesi|:count mēnešus', + 'a_month_before' => '{1}mēnesi|0 mēnešus|:count mēnesi|:count mēnešus', + 'week_before' => '0 nedēļas|:count nedēļu|:count nedēļas', + 'a_week_before' => '{1}nedēļu|0 nedēļas|:count nedēļu|:count nedēļas', + 'day_before' => '0 dienas|:count dienu|:count dienas', + 'a_day_before' => '{1}dienu|0 dienas|:count dienu|:count dienas', + 'hour_before' => '0 stundas|:count stundu|:count stundas', + 'a_hour_before' => '{1}stundu|0 stundas|:count stundu|:count stundas', + 'minute_before' => '0 minūtes|:count minūti|:count minūtes', + 'a_minute_before' => '{1}minūti|0 minūtes|:count minūti|:count minūtes', + 'second_before' => '0 sekundes|:count sekundi|:count sekundes', + 'a_second_before' => '{1}sekundi|0 sekundes|:count sekundi|:count sekundes', + + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' un '], + + 'diff_now' => 'tagad', + 'diff_today' => 'šodien', + 'diff_yesterday' => 'vakar', + 'diff_before_yesterday' => 'aizvakar', + 'diff_tomorrow' => 'rīt', + 'diff_after_tomorrow' => 'parīt', + + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY.', + 'LL' => 'YYYY. [gada] D. MMMM', + 'LLL' => 'DD.MM.YYYY., HH:mm', + 'LLLL' => 'YYYY. [gada] D. MMMM, HH:mm', + ], + + 'calendar' => [ + 'sameDay' => '[šodien] [plkst.] LT', + 'nextDay' => '[rīt] [plkst.] LT', + 'nextWeek' => function (CarbonInterface $current, CarbonInterface $other) use ($daysOfWeekLocativum) { + if ($current->week !== $other->week) { + return '[nākošo] ['.$daysOfWeekLocativum[$current->dayOfWeek].'] [plkst.] LT'; + } + + return '['.$daysOfWeekLocativum[$current->dayOfWeek].'] [plkst.] LT'; + }, + 'lastDay' => '[vakar] [plkst.] LT', + 'lastWeek' => function (CarbonInterface $current) use ($daysOfWeekLocativum) { + return '[pagājušo] ['.$daysOfWeekLocativum[$current->dayOfWeek].'] [plkst.] LT'; + }, + 'sameElse' => 'L', + ], + + 'weekdays' => $daysOfWeek, + 'weekdays_short' => ['Sv.', 'P.', 'O.', 'T.', 'C.', 'Pk.', 'S.'], + 'weekdays_min' => ['Sv.', 'P.', 'O.', 'T.', 'C.', 'Pk.', 'S.'], + 'months' => ['janvāris', 'februāris', 'marts', 'aprīlis', 'maijs', 'jūnijs', 'jūlijs', 'augusts', 'septembris', 'oktobris', 'novembris', 'decembris'], + 'months_standalone' => ['janvārī', 'februārī', 'martā', 'aprīlī', 'maijā', 'jūnijā', 'jūlijā', 'augustā', 'septembrī', 'oktobrī', 'novembrī', 'decembrī'], + 'months_short' => ['janv.', 'febr.', 'martā', 'apr.', 'maijā', 'jūn.', 'jūl.', 'aug.', 'sept.', 'okt.', 'nov.', 'dec.'], + 'meridiem' => ['priekšpusdiena', 'pēcpusdiena'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lv_LV.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lv_LV.php new file mode 100644 index 0000000..ee91c36 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lv_LV.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/lv.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lzh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lzh.php new file mode 100644 index 0000000..1180c6b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lzh.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/lzh_TW.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lzh_TW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lzh_TW.php new file mode 100644 index 0000000..3b1493e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/lzh_TW.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'OY[年]MMMMOD[日]', + ], + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => [' 一 ', ' 二 ', ' 三 ', ' 四 ', ' 五 ', ' 六 ', ' 七 ', ' 八 ', ' 九 ', ' 十 ', '十一', '十二'], + 'weekdays' => ['週日', '週一', '週二', '週三', '週四', '週五', '週六'], + 'weekdays_short' => ['日', '一', '二', '三', '四', '五', '六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '廿', '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '卅', '卅一'], + 'meridiem' => ['朝', '暮'], + + 'year' => ':count 夏', // less reliable + 'y' => ':count 夏', // less reliable + 'a_year' => ':count 夏', // less reliable + + 'month' => ':count 月', // less reliable + 'm' => ':count 月', // less reliable + 'a_month' => ':count 月', // less reliable + + 'hour' => ':count 氧', // less reliable + 'h' => ':count 氧', // less reliable + 'a_hour' => ':count 氧', // less reliable + + 'minute' => ':count 點', // less reliable + 'min' => ':count 點', // less reliable + 'a_minute' => ':count 點', // less reliable + + 'second' => ':count 楚', // less reliable + 's' => ':count 楚', // less reliable + 'a_second' => ':count 楚', // less reliable + + 'week' => ':count 星期', + 'w' => ':count 星期', + 'a_week' => ':count 星期', + + 'day' => ':count 日(曆法)', + 'd' => ':count 日(曆法)', + 'a_day' => ':count 日(曆法)', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mag.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mag.php new file mode 100644 index 0000000..7532436 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mag.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mag_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mag_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mag_IN.php new file mode 100644 index 0000000..193f67a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mag_IN.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bhashaghar@googlegroups.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'months_short' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'weekdays' => ['एतवार', 'सोमार', 'मंगर', 'बुध', 'बिफे', 'सूक', 'सनिचर'], + 'weekdays_short' => ['एतवार', 'सोमार', 'मंगर', 'बुध', 'बिफे', 'सूक', 'सनिचर'], + 'weekdays_min' => ['एतवार', 'सोमार', 'मंगर', 'बुध', 'बिफे', 'सूक', 'सनिचर'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mai.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mai.php new file mode 100644 index 0000000..792b973 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mai.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mai_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mai_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mai_IN.php new file mode 100644 index 0000000..03049d4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mai_IN.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Maithili Computing Research Center, Pune, India rajeshkajha@yahoo.com,akhilesh.k@samusng.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['बैसाख', 'जेठ', 'अषाढ़', 'सावोन', 'भादो', 'आसिन', 'कातिक', 'अगहन', 'पूस', 'माघ', 'फागुन', 'चैति'], + 'months_short' => ['बैसाख', 'जेठ', 'अषाढ़', 'सावोन', 'भादो', 'आसिन', 'कातिक', 'अगहन', 'पूस', 'माघ', 'फागुन', 'चैति'], + 'weekdays' => ['रविदिन', 'सोमदिन', 'मंगलदिन', 'बुधदिन', 'बृहस्पतीदिन', 'शुक्रदिन', 'शनीदिन'], + 'weekdays_short' => ['रवि', 'सोम', 'मंगल', 'बुध', 'बृहस्पती', 'शुक्र', 'शनी'], + 'weekdays_min' => ['रवि', 'सोम', 'मंगल', 'बुध', 'बृहस्पती', 'शुक्र', 'शनी'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], + + 'year' => ':count ऋतु', // less reliable + 'y' => ':count ऋतु', // less reliable + 'a_year' => ':count ऋतु', // less reliable + + 'month' => ':count महिना', + 'm' => ':count महिना', + 'a_month' => ':count महिना', + + 'week' => ':count श्रेणी:क्यालेन्डर', // less reliable + 'w' => ':count श्रेणी:क्यालेन्डर', // less reliable + 'a_week' => ':count श्रेणी:क्यालेन्डर', // less reliable + + 'day' => ':count दिन', + 'd' => ':count दिन', + 'a_day' => ':count दिन', + + 'hour' => ':count घण्टा', + 'h' => ':count घण्टा', + 'a_hour' => ':count घण्टा', + + 'minute' => ':count समय', // less reliable + 'min' => ':count समय', // less reliable + 'a_minute' => ':count समय', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mas.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mas.php new file mode 100644 index 0000000..cbd610c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mas.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Ɛnkakɛnyá', 'Ɛndámâ'], + 'weekdays' => ['Jumapílí', 'Jumatátu', 'Jumane', 'Jumatánɔ', 'Alaámisi', 'Jumáa', 'Jumamósi'], + 'weekdays_short' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'weekdays_min' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'months' => ['Oladalʉ́', 'Arát', 'Ɔɛnɨ́ɔɨŋɔk', 'Olodoyíóríê inkókúâ', 'Oloilépūnyīē inkókúâ', 'Kújúɔrɔk', 'Mórusásin', 'Ɔlɔ́ɨ́bɔ́rárɛ', 'Kúshîn', 'Olgísan', 'Pʉshʉ́ka', 'Ntʉ́ŋʉ́s'], + 'months_short' => ['Dal', 'Ará', 'Ɔɛn', 'Doy', 'Lép', 'Rok', 'Sás', 'Bɔ́r', 'Kús', 'Gís', 'Shʉ́', 'Ntʉ́'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'year' => ':count olameyu', // less reliable + 'y' => ':count olameyu', // less reliable + 'a_year' => ':count olameyu', // less reliable + + 'week' => ':count engolongeare orwiki', // less reliable + 'w' => ':count engolongeare orwiki', // less reliable + 'a_week' => ':count engolongeare orwiki', // less reliable + + 'hour' => ':count esahabu', // less reliable + 'h' => ':count esahabu', // less reliable + 'a_hour' => ':count esahabu', // less reliable + + 'second' => ':count are', // less reliable + 's' => ':count are', // less reliable + 'a_second' => ':count are', // less reliable + + 'month' => ':count olapa', + 'm' => ':count olapa', + 'a_month' => ':count olapa', + + 'day' => ':count enkolongʼ', + 'd' => ':count enkolongʼ', + 'a_day' => ':count enkolongʼ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mas_TZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mas_TZ.php new file mode 100644 index 0000000..56e2905 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mas_TZ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/mas.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mer.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mer.php new file mode 100644 index 0000000..2e14597 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mer.php @@ -0,0 +1,43 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['RŨ', 'ŨG'], + 'weekdays' => ['Kiumia', 'Muramuko', 'Wairi', 'Wethatu', 'Wena', 'Wetano', 'Jumamosi'], + 'weekdays_short' => ['KIU', 'MRA', 'WAI', 'WET', 'WEN', 'WTN', 'JUM'], + 'weekdays_min' => ['KIU', 'MRA', 'WAI', 'WET', 'WEN', 'WTN', 'JUM'], + 'months' => ['Januarĩ', 'Feburuarĩ', 'Machi', 'Ĩpurũ', 'Mĩĩ', 'Njuni', 'Njuraĩ', 'Agasti', 'Septemba', 'Oktũba', 'Novemba', 'Dicemba'], + 'months_short' => ['JAN', 'FEB', 'MAC', 'ĨPU', 'MĨĨ', 'NJU', 'NJR', 'AGA', 'SPT', 'OKT', 'NOV', 'DEC'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'year' => ':count murume', // less reliable + 'y' => ':count murume', // less reliable + 'a_year' => ':count murume', // less reliable + + 'month' => ':count muchaara', // less reliable + 'm' => ':count muchaara', // less reliable + 'a_month' => ':count muchaara', // less reliable + + 'minute' => ':count monto', // less reliable + 'min' => ':count monto', // less reliable + 'a_minute' => ':count monto', // less reliable + + 'second' => ':count gikeno', // less reliable + 's' => ':count gikeno', // less reliable + 'a_second' => ':count gikeno', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mfe.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mfe.php new file mode 100644 index 0000000..4d6e6b6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mfe.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mfe_MU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mfe_MU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mfe_MU.php new file mode 100644 index 0000000..2d27b45 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mfe_MU.php @@ -0,0 +1,53 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Samsung Electronics Co., Ltd. akhilesh.k@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['zanvie', 'fevriye', 'mars', 'avril', 'me', 'zin', 'zilye', 'out', 'septam', 'oktob', 'novam', 'desam'], + 'months_short' => ['zan', 'fev', 'mar', 'avr', 'me', 'zin', 'zil', 'out', 'sep', 'okt', 'nov', 'des'], + 'weekdays' => ['dimans', 'lindi', 'mardi', 'merkredi', 'zedi', 'vandredi', 'samdi'], + 'weekdays_short' => ['dim', 'lin', 'mar', 'mer', 'ze', 'van', 'sam'], + 'weekdays_min' => ['dim', 'lin', 'mar', 'mer', 'ze', 'van', 'sam'], + + 'year' => ':count banané', + 'y' => ':count banané', + 'a_year' => ':count banané', + + 'month' => ':count mwa', + 'm' => ':count mwa', + 'a_month' => ':count mwa', + + 'week' => ':count sémenn', + 'w' => ':count sémenn', + 'a_week' => ':count sémenn', + + 'day' => ':count zour', + 'd' => ':count zour', + 'a_day' => ':count zour', + + 'hour' => ':count -er-tan', + 'h' => ':count -er-tan', + 'a_hour' => ':count -er-tan', + + 'minute' => ':count minitt', + 'min' => ':count minitt', + 'a_minute' => ':count minitt', + + 'second' => ':count déziém', + 's' => ':count déziém', + 'a_second' => ':count déziém', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mg.php new file mode 100644 index 0000000..40bc2a8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mg.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mg_MG.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mg_MG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mg_MG.php new file mode 100644 index 0000000..6a14535 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mg_MG.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - The Debian Project modified by GNU//Linux Malagasy Rado Ramarotafika,Do-Risika RAFIEFERANTSIARONJY rado@linuxmg.org,dourix@free.fr + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Janoary', 'Febroary', 'Martsa', 'Aprily', 'Mey', 'Jona', 'Jolay', 'Aogositra', 'Septambra', 'Oktobra', 'Novambra', 'Desambra'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'Mey', 'Jon', 'Jol', 'Aog', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['alahady', 'alatsinainy', 'talata', 'alarobia', 'alakamisy', 'zoma', 'sabotsy'], + 'weekdays_short' => ['lhd', 'lts', 'tlt', 'lrb', 'lkm', 'zom', 'sab'], + 'weekdays_min' => ['lhd', 'lts', 'tlt', 'lrb', 'lkm', 'zom', 'sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'minute' => ':count minitra', // less reliable + 'min' => ':count minitra', // less reliable + 'a_minute' => ':count minitra', // less reliable + + 'year' => ':count taona', + 'y' => ':count taona', + 'a_year' => ':count taona', + + 'month' => ':count volana', + 'm' => ':count volana', + 'a_month' => ':count volana', + + 'week' => ':count herinandro', + 'w' => ':count herinandro', + 'a_week' => ':count herinandro', + + 'day' => ':count andro', + 'd' => ':count andro', + 'a_day' => ':count andro', + + 'hour' => ':count ora', + 'h' => ':count ora', + 'a_hour' => ':count ora', + + 'second' => ':count segondra', + 's' => ':count segondra', + 'a_second' => ':count segondra', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mgh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mgh.php new file mode 100644 index 0000000..2a80960 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mgh.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['wichishu', 'mchochil’l'], + 'weekdays' => ['Sabato', 'Jumatatu', 'Jumanne', 'Jumatano', 'Arahamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Sab', 'Jtt', 'Jnn', 'Jtn', 'Ara', 'Iju', 'Jmo'], + 'weekdays_min' => ['Sab', 'Jtt', 'Jnn', 'Jtn', 'Ara', 'Iju', 'Jmo'], + 'months' => ['Mweri wo kwanza', 'Mweri wo unayeli', 'Mweri wo uneraru', 'Mweri wo unecheshe', 'Mweri wo unethanu', 'Mweri wo thanu na mocha', 'Mweri wo saba', 'Mweri wo nane', 'Mweri wo tisa', 'Mweri wo kumi', 'Mweri wo kumi na moja', 'Mweri wo kumi na yel’li'], + 'months_short' => ['Kwa', 'Una', 'Rar', 'Che', 'Tha', 'Moc', 'Sab', 'Nan', 'Tis', 'Kum', 'Moj', 'Yel'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mgo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mgo.php new file mode 100644 index 0000000..a126c9f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mgo.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Aneg 1', 'Aneg 2', 'Aneg 3', 'Aneg 4', 'Aneg 5', 'Aneg 6', 'Aneg 7'], + 'weekdays_short' => ['Aneg 1', 'Aneg 2', 'Aneg 3', 'Aneg 4', 'Aneg 5', 'Aneg 6', 'Aneg 7'], + 'weekdays_min' => ['1', '2', '3', '4', '5', '6', '7'], + 'months' => ['iməg mbegtug', 'imeg àbùbì', 'imeg mbəŋchubi', 'iməg ngwə̀t', 'iməg fog', 'iməg ichiibɔd', 'iməg àdùmbə̀ŋ', 'iməg ichika', 'iməg kud', 'iməg tèsiʼe', 'iməg zò', 'iməg krizmed'], + 'months_short' => ['mbegtug', 'imeg àbùbì', 'imeg mbəŋchubi', 'iməg ngwə̀t', 'iməg fog', 'iməg ichiibɔd', 'iməg àdùmbə̀ŋ', 'iməg ichika', 'iməg kud', 'iməg tèsiʼe', 'iməg zò', 'iməg krizmed'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'dddd, YYYY MMMM DD HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mhr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mhr.php new file mode 100644 index 0000000..6bbc9f6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mhr.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mhr_RU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mhr_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mhr_RU.php new file mode 100644 index 0000000..309ead9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mhr_RU.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - PeshSajSoft Ltd. Vyacheslav Kileev slavakileev@yandex.ru + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY.MM.DD', + ], + 'months' => ['Шорыкйол', 'Пургыж', 'Ӱярня', 'Вӱдшор', 'Ага', 'Пеледыш', 'Сӱрем', 'Сорла', 'Идым', 'Шыжа', 'Кылме', 'Теле'], + 'months_short' => ['Шрк', 'Пгж', 'Ӱрн', 'Вшр', 'Ага', 'Пдш', 'Срм', 'Срл', 'Идм', 'Шыж', 'Клм', 'Тел'], + 'weekdays' => ['Рушарня', 'Шочмо', 'Кушкыжмо', 'Вӱргече', 'Изарня', 'Кугарня', 'Шуматкече'], + 'weekdays_short' => ['Ршр', 'Шчм', 'Кжм', 'Вгч', 'Изр', 'Кгр', 'Шмт'], + 'weekdays_min' => ['Ршр', 'Шчм', 'Кжм', 'Вгч', 'Изр', 'Кгр', 'Шмт'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => ':count идалык', + 'y' => ':count идалык', + 'a_year' => ':count идалык', + + 'month' => ':count Тылзе', + 'm' => ':count Тылзе', + 'a_month' => ':count Тылзе', + + 'week' => ':count арня', + 'w' => ':count арня', + 'a_week' => ':count арня', + + 'day' => ':count кече', + 'd' => ':count кече', + 'a_day' => ':count кече', + + 'hour' => ':count час', + 'h' => ':count час', + 'a_hour' => ':count час', + + 'minute' => ':count минут', + 'min' => ':count минут', + 'a_minute' => ':count минут', + + 'second' => ':count кокымшан', + 's' => ':count кокымшан', + 'a_second' => ':count кокымшан', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mi.php new file mode 100644 index 0000000..b7f51ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mi.php @@ -0,0 +1,66 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - John Corrigan + * - François B + */ +return [ + 'year' => ':count tau', + 'a_year' => '{1}he tau|:count tau', + 'month' => ':count marama', + 'a_month' => '{1}he marama|:count marama', + 'week' => ':count wiki', + 'a_week' => '{1}he wiki|:count wiki', + 'day' => ':count ra', + 'a_day' => '{1}he ra|:count ra', + 'hour' => ':count haora', + 'a_hour' => '{1}te haora|:count haora', + 'minute' => ':count meneti', + 'a_minute' => '{1}he meneti|:count meneti', + 'second' => ':count hēkona', + 'a_second' => '{1}te hēkona ruarua|:count hēkona', + 'ago' => ':time i mua', + 'from_now' => 'i roto i :time', + 'diff_yesterday' => 'inanahi', + 'diff_yesterday_regexp' => 'inanahi(?:\\s+i)?', + 'diff_today' => 'i teie', + 'diff_today_regexp' => 'i teie(?:\\s+mahana,)?(?:\\s+i)?', + 'diff_tomorrow' => 'apopo', + 'diff_tomorrow_regexp' => 'apopo(?:\\s+i)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY [i] HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY [i] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[i teie mahana, i] LT', + 'nextDay' => '[apopo i] LT', + 'nextWeek' => 'dddd [i] LT', + 'lastDay' => '[inanahi i] LT', + 'lastWeek' => 'dddd [whakamutunga i] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numberº', + 'months' => ['Kohi-tāte', 'Hui-tanguru', 'Poutū-te-rangi', 'Paenga-whāwhā', 'Haratua', 'Pipiri', 'Hōngoingoi', 'Here-turi-kōkā', 'Mahuru', 'Whiringa-ā-nuku', 'Whiringa-ā-rangi', 'Hakihea'], + 'months_short' => ['Kohi', 'Hui', 'Pou', 'Pae', 'Hara', 'Pipi', 'Hōngoi', 'Here', 'Mahu', 'Whi-nu', 'Whi-ra', 'Haki'], + 'weekdays' => ['Rātapu', 'Mane', 'Tūrei', 'Wenerei', 'Tāite', 'Paraire', 'Hātarei'], + 'weekdays_short' => ['Ta', 'Ma', 'Tū', 'We', 'Tāi', 'Pa', 'Hā'], + 'weekdays_min' => ['Ta', 'Ma', 'Tū', 'We', 'Tāi', 'Pa', 'Hā'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' me te '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mi_NZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mi_NZ.php new file mode 100644 index 0000000..6b964e3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mi_NZ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/mi.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/miq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/miq.php new file mode 100644 index 0000000..51e5a98 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/miq.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/miq_NI.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/miq_NI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/miq_NI.php new file mode 100644 index 0000000..57faa31 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/miq_NI.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['siakwa kati', 'kuswa kati', 'kakamuk kati', 'lî wainhka kati', 'lih mairin kati', 'lî kati', 'pastara kati', 'sikla kati', 'wîs kati', 'waupasa kati', 'yahbra kati', 'trisu kati'], + 'months_short' => ['siakwa kati', 'kuswa kati', 'kakamuk kati', 'lî wainhka kati', 'lih mairin kati', 'lî kati', 'pastara kati', 'sikla kati', 'wîs kati', 'waupasa kati', 'yahbra kati', 'trisu kati'], + 'weekdays' => ['sandi', 'mundi', 'tiusdi', 'wensde', 'tausde', 'praidi', 'satadi'], + 'weekdays_short' => ['san', 'mun', 'tius', 'wens', 'taus', 'prai', 'sat'], + 'weekdays_min' => ['san', 'mun', 'tius', 'wens', 'taus', 'prai', 'sat'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 7, + 'meridiem' => ['VM', 'NM'], + + 'month' => ':count kati', // less reliable + 'm' => ':count kati', // less reliable + 'a_month' => ':count kati', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mjw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mjw.php new file mode 100644 index 0000000..617154c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mjw.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mjw_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mjw_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mjw_IN.php new file mode 100644 index 0000000..58ed0d1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mjw_IN.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Jor Teron bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['Arkoi', 'Thangthang', 'There', 'Jangmi', 'Aru', 'Vosik', 'Jakhong', 'Paipai', 'Chiti', 'Phere', 'Phaikuni', 'Matijong'], + 'months_short' => ['Ark', 'Thang', 'The', 'Jang', 'Aru', 'Vos', 'Jak', 'Pai', 'Chi', 'Phe', 'Phai', 'Mati'], + 'weekdays' => ['Bhomkuru', 'Urmi', 'Durmi', 'Thelang', 'Theman', 'Bhomta', 'Bhomti'], + 'weekdays_short' => ['Bhom', 'Ur', 'Dur', 'Tkel', 'Tkem', 'Bhta', 'Bhti'], + 'weekdays_min' => ['Bhom', 'Ur', 'Dur', 'Tkel', 'Tkem', 'Bhta', 'Bhti'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mk.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mk.php new file mode 100644 index 0000000..d822de0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mk.php @@ -0,0 +1,116 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Sashko Todorov + * - Josh Soref + * - François B + * - Serhan Apaydın + * - Borislav Mickov + * - JD Isaacks + * - Tomi Atanasoski + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count година|:count години', + 'a_year' => 'година|:count години', + 'y' => ':count год.', + 'month' => ':count месец|:count месеци', + 'a_month' => 'месец|:count месеци', + 'm' => ':count месец|:count месеци', + 'week' => ':count седмица|:count седмици', + 'a_week' => 'седмица|:count седмици', + 'w' => ':count седмица|:count седмици', + 'day' => ':count ден|:count дена', + 'a_day' => 'ден|:count дена', + 'd' => ':count ден|:count дена', + 'hour' => ':count час|:count часа', + 'a_hour' => 'час|:count часа', + 'h' => ':count час|:count часа', + 'minute' => ':count минута|:count минути', + 'a_minute' => 'минута|:count минути', + 'min' => ':count мин.', + 'second' => ':count секунда|:count секунди', + 'a_second' => 'неколку секунди|:count секунди', + 's' => ':count сек.', + 'ago' => 'пред :time', + 'from_now' => 'после :time', + 'after' => 'по :time', + 'before' => 'пред :time', + 'diff_now' => 'сега', + 'diff_today' => 'Денес', + 'diff_today_regexp' => 'Денес(?:\\s+во)?', + 'diff_yesterday' => 'вчера', + 'diff_yesterday_regexp' => 'Вчера(?:\\s+во)?', + 'diff_tomorrow' => 'утре', + 'diff_tomorrow_regexp' => 'Утре(?:\\s+во)?', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'D.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY H:mm', + 'LLLL' => 'dddd, D MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[Денес во] LT', + 'nextDay' => '[Утре во] LT', + 'nextWeek' => '[Во] dddd [во] LT', + 'lastDay' => '[Вчера во] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + case 3: + case 6: + return '[Изминатата] dddd [во] LT'; + default: + return '[Изминатиот] dddd [во] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + $lastDigit = $number % 10; + $last2Digits = $number % 100; + if ($number === 0) { + return $number.'-ев'; + } + if ($last2Digits === 0) { + return $number.'-ен'; + } + if ($last2Digits > 10 && $last2Digits < 20) { + return $number.'-ти'; + } + if ($lastDigit === 1) { + return $number.'-ви'; + } + if ($lastDigit === 2) { + return $number.'-ри'; + } + if ($lastDigit === 7 || $lastDigit === 8) { + return $number.'-ми'; + } + + return $number.'-ти'; + }, + 'months' => ['јануари', 'февруари', 'март', 'април', 'мај', 'јуни', 'јули', 'август', 'септември', 'октомври', 'ноември', 'декември'], + 'months_short' => ['јан', 'фев', 'мар', 'апр', 'мај', 'јун', 'јул', 'авг', 'сеп', 'окт', 'ное', 'дек'], + 'weekdays' => ['недела', 'понеделник', 'вторник', 'среда', 'четврток', 'петок', 'сабота'], + 'weekdays_short' => ['нед', 'пон', 'вто', 'сре', 'чет', 'пет', 'саб'], + 'weekdays_min' => ['нe', 'пo', 'вт', 'ср', 'че', 'пе', 'сa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' и '], + 'meridiem' => ['АМ', 'ПМ'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mk_MK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mk_MK.php new file mode 100644 index 0000000..95e2ff9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mk_MK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/mk.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ml.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ml.php new file mode 100644 index 0000000..1abd6c4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ml.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - JD Isaacks + */ +return [ + 'year' => ':count വർഷം', + 'a_year' => 'ഒരു വർഷം|:count വർഷം', + 'month' => ':count മാസം', + 'a_month' => 'ഒരു മാസം|:count മാസം', + 'week' => ':count ആഴ്ച', + 'a_week' => 'ഒരാഴ്ച|:count ആഴ്ച', + 'day' => ':count ദിവസം', + 'a_day' => 'ഒരു ദിവസം|:count ദിവസം', + 'hour' => ':count മണിക്കൂർ', + 'a_hour' => 'ഒരു മണിക്കൂർ|:count മണിക്കൂർ', + 'minute' => ':count മിനിറ്റ്', + 'a_minute' => 'ഒരു മിനിറ്റ്|:count മിനിറ്റ്', + 'second' => ':count സെക്കൻഡ്', + 'a_second' => 'അൽപ നിമിഷങ്ങൾ|:count സെക്കൻഡ്', + 'ago' => ':time മുൻപ്', + 'from_now' => ':time കഴിഞ്ഞ്', + 'diff_now' => 'ഇപ്പോൾ', + 'diff_today' => 'ഇന്ന്', + 'diff_yesterday' => 'ഇന്നലെ', + 'diff_tomorrow' => 'നാളെ', + 'formats' => [ + 'LT' => 'A h:mm -നു', + 'LTS' => 'A h:mm:ss -നു', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm -നു', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm -നു', + ], + 'calendar' => [ + 'sameDay' => '[ഇന്ന്] LT', + 'nextDay' => '[നാളെ] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[ഇന്നലെ] LT', + 'lastWeek' => '[കഴിഞ്ഞ] dddd, LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'രാത്രി'; + } + if ($hour < 12) { + return 'രാവിലെ'; + } + if ($hour < 17) { + return 'ഉച്ച കഴിഞ്ഞ്'; + } + if ($hour < 20) { + return 'വൈകുന്നേരം'; + } + + return 'രാത്രി'; + }, + 'months' => ['ജനുവരി', 'ഫെബ്രുവരി', 'മാർച്ച്', 'ഏപ്രിൽ', 'മേയ്', 'ജൂൺ', 'ജൂലൈ', 'ഓഗസ്റ്റ്', 'സെപ്റ്റംബർ', 'ഒക്ടോബർ', 'നവംബർ', 'ഡിസംബർ'], + 'months_short' => ['ജനു.', 'ഫെബ്രു.', 'മാർ.', 'ഏപ്രി.', 'മേയ്', 'ജൂൺ', 'ജൂലൈ.', 'ഓഗ.', 'സെപ്റ്റ.', 'ഒക്ടോ.', 'നവം.', 'ഡിസം.'], + 'weekdays' => ['ഞായറാഴ്ച', 'തിങ്കളാഴ്ച', 'ചൊവ്വാഴ്ച', 'ബുധനാഴ്ച', 'വ്യാഴാഴ്ച', 'വെള്ളിയാഴ്ച', 'ശനിയാഴ്ച'], + 'weekdays_short' => ['ഞായർ', 'തിങ്കൾ', 'ചൊവ്വ', 'ബുധൻ', 'വ്യാഴം', 'വെള്ളി', 'ശനി'], + 'weekdays_min' => ['ഞാ', 'തി', 'ചൊ', 'ബു', 'വ്യാ', 'വെ', 'ശ'], + 'list' => ', ', + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ml_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ml_IN.php new file mode 100644 index 0000000..000e795 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ml_IN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ml.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mn.php new file mode 100644 index 0000000..38c6434 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mn.php @@ -0,0 +1,116 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Tsutomu Kuroda + * - tjku + * - Max Melentiev + * - Zolzaya Erdenebaatar + * - Tom Hughes + * - Akira Matsuda + * - Christopher Dell + * - Michael Kessler + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Nicolás Hock Isaza + * - Ochirkhuyag + * - Batmandakh + * - lucifer-crybaby + */ +return [ + 'year' => ':count жил', + 'y' => ':count жил', + 'month' => ':count сар', + 'm' => ':count сар', + 'week' => ':count долоо хоног', + 'w' => ':count долоо хоног', + 'day' => ':count өдөр', + 'd' => ':count өдөр', + 'hour' => ':count цаг', + 'h' => ':countц', + 'minute' => ':count минут', + 'min' => ':countм', + 'second' => ':count секунд', + 's' => ':countс', + + 'ago_mode' => 'last', + 'ago' => ':time өмнө', + 'year_ago' => ':count жилийн', + 'y_ago' => ':count жилийн', + 'month_ago' => ':count сарын', + 'm_ago' => ':count сарын', + 'day_ago' => ':count хоногийн', + 'd_ago' => ':count хоногийн', + 'week_ago' => ':count долоо хоногийн', + 'w_ago' => ':count долоо хоногийн', + 'hour_ago' => ':count цагийн', + 'minute_ago' => ':count минутын', + 'second_ago' => ':count секундын', + + 'from_now_mode' => 'last', + 'from_now' => 'одоогоос :time', + 'year_from_now' => ':count жилийн дараа', + 'y_from_now' => ':count жилийн дараа', + 'month_from_now' => ':count сарын дараа', + 'm_from_now' => ':count сарын дараа', + 'day_from_now' => ':count хоногийн дараа', + 'd_from_now' => ':count хоногийн дараа', + 'hour_from_now' => ':count цагийн дараа', + 'minute_from_now' => ':count минутын дараа', + 'second_from_now' => ':count секундын дараа', + + 'after_mode' => 'last', + 'after' => ':time дараа', + 'year_after' => ':count жилийн', + 'y_after' => ':count жилийн', + 'month_after' => ':count сарын', + 'm_after' => ':count сарын', + 'day_after' => ':count хоногийн', + 'd_after' => ':count хоногийн', + 'hour_after' => ':count цагийн', + 'minute_after' => ':count минутын', + 'second_after' => ':count секундын', + + 'before_mode' => 'last', + 'before' => ':time өмнө', + 'year_before' => ':count жилийн', + 'y_before' => ':count жилийн', + 'month_before' => ':count сарын', + 'm_before' => ':count сарын', + 'day_before' => ':count хоногийн', + 'd_before' => ':count хоногийн', + 'hour_before' => ':count цагийн', + 'minute_before' => ':count минутын', + 'second_before' => ':count секундын', + + 'list' => ', ', + 'diff_now' => 'одоо', + 'diff_yesterday' => 'өчигдөр', + 'diff_tomorrow' => 'маргааш', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'YYYY MMMM DD', + 'LLL' => 'YY-MM-DD, HH:mm', + 'LLLL' => 'YYYY MMMM DD, HH:mm', + ], + 'weekdays' => ['Ням', 'Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба'], + 'weekdays_short' => ['Ня', 'Да', 'Мя', 'Лх', 'Пү', 'Ба', 'Бя'], + 'weekdays_min' => ['Ня', 'Да', 'Мя', 'Лх', 'Пү', 'Ба', 'Бя'], + 'months' => ['1 сар', '2 сар', '3 сар', '4 сар', '5 сар', '6 сар', '7 сар', '8 сар', '9 сар', '10 сар', '11 сар', '12 сар'], + 'months_short' => ['1 сар', '2 сар', '3 сар', '4 сар', '5 сар', '6 сар', '7 сар', '8 сар', '9 сар', '10 сар', '11 сар', '12 сар'], + 'meridiem' => ['өглөө', 'орой'], + 'first_day_of_week' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mn_MN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mn_MN.php new file mode 100644 index 0000000..e5ce426 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mn_MN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/mn.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mni.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mni.php new file mode 100644 index 0000000..cafa2f8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mni.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/mni_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mni_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mni_IN.php new file mode 100644 index 0000000..45d430e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mni_IN.php @@ -0,0 +1,35 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat Pune libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['জানুৱারি', 'ফেব্রুৱারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগষ্ট', 'সেপ্তেম্বর', 'ওক্তোবর', 'নবেম্বর', 'ডিসেম্বর'], + 'months_short' => ['জান', 'ফেব', 'মার', 'এপ্রি', 'মে', 'জুন', 'জুল', 'আগ', 'সেপ', 'ওক্ত', 'নবে', 'ডিস'], + 'weekdays' => ['নোংমাইজিং', 'নিংথৌকাবা', 'লৈবাকপোকপা', 'য়ুমশকৈশা', 'শগোলশেন', 'ইরাই', 'থাংজ'], + 'weekdays_short' => ['নোং', 'নিং', 'লৈবাক', 'য়ুম', 'শগোল', 'ইরা', 'থাং'], + 'weekdays_min' => ['নোং', 'নিং', 'লৈবাক', 'য়ুম', 'শগোল', 'ইরা', 'থাং'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['এ.ম.', 'প.ম.'], + + 'year' => ':count ইসিং', // less reliable + 'y' => ':count ইসিং', // less reliable + 'a_year' => ':count ইসিং', // less reliable + + 'second' => ':count ꯅꯤꯡꯊꯧꯀꯥꯕ', // less reliable + 's' => ':count ꯅꯤꯡꯊꯧꯀꯥꯕ', // less reliable + 'a_second' => ':count ꯅꯤꯡꯊꯧꯀꯥꯕ', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mo.php new file mode 100644 index 0000000..102afcd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mo.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ro.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mr.php new file mode 100644 index 0000000..4aaeafd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mr.php @@ -0,0 +1,86 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Vikram-enyota + */ +return [ + 'year' => ':count वर्ष', + 'y' => ':count वर्ष', + 'month' => ':count महिना|:count महिने', + 'm' => ':count महिना|:count महिने', + 'week' => ':count आठवडा|:count आठवडे', + 'w' => ':count आठवडा|:count आठवडे', + 'day' => ':count दिवस', + 'd' => ':count दिवस', + 'hour' => ':count तास', + 'h' => ':count तास', + 'minute' => ':count मिनिटे', + 'min' => ':count मिनिटे', + 'second' => ':count सेकंद', + 's' => ':count सेकंद', + + 'ago' => ':timeपूर्वी', + 'from_now' => ':timeमध्ये', + 'before' => ':timeपूर्वी', + 'after' => ':timeनंतर', + + 'diff_now' => 'आत्ता', + 'diff_today' => 'आज', + 'diff_yesterday' => 'काल', + 'diff_tomorrow' => 'उद्या', + + 'formats' => [ + 'LT' => 'A h:mm वाजता', + 'LTS' => 'A h:mm:ss वाजता', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm वाजता', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm वाजता', + ], + + 'calendar' => [ + 'sameDay' => '[आज] LT', + 'nextDay' => '[उद्या] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[काल] LT', + 'lastWeek' => '[मागील] dddd, LT', + 'sameElse' => 'L', + ], + + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'रात्री'; + } + if ($hour < 10) { + return 'सकाळी'; + } + if ($hour < 17) { + return 'दुपारी'; + } + if ($hour < 20) { + return 'सायंकाळी'; + } + + return 'रात्री'; + }, + + 'months' => ['जानेवारी', 'फेब्रुवारी', 'मार्च', 'एप्रिल', 'मे', 'जून', 'जुलै', 'ऑगस्ट', 'सप्टेंबर', 'ऑक्टोबर', 'नोव्हेंबर', 'डिसेंबर'], + 'months_short' => ['जाने.', 'फेब्रु.', 'मार्च.', 'एप्रि.', 'मे.', 'जून.', 'जुलै.', 'ऑग.', 'सप्टें.', 'ऑक्टो.', 'नोव्हें.', 'डिसें.'], + 'weekdays' => ['रविवार', 'सोमवार', 'मंगळवार', 'बुधवार', 'गुरूवार', 'शुक्रवार', 'शनिवार'], + 'weekdays_short' => ['रवि', 'सोम', 'मंगळ', 'बुध', 'गुरू', 'शुक्र', 'शनि'], + 'weekdays_min' => ['र', 'सो', 'मं', 'बु', 'गु', 'शु', 'श'], + 'list' => [', ', ' आणि '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mr_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mr_IN.php new file mode 100644 index 0000000..7bca919 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mr_IN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/mr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms.php new file mode 100644 index 0000000..c9e8085 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms.php @@ -0,0 +1,104 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Azri Jamil + * - JD Isaacks + * - Josh Soref + * - Azri Jamil + * - Hariadi Hinta + * - Ashraf Kamarudin + */ +return [ + 'year' => ':count tahun', + 'a_year' => '{1}setahun|]1,Inf[:count tahun', + 'y' => ':count tahun', + 'month' => ':count bulan', + 'a_month' => '{1}sebulan|]1,Inf[:count bulan', + 'm' => ':count bulan', + 'week' => ':count minggu', + 'a_week' => '{1}seminggu|]1,Inf[:count minggu', + 'w' => ':count minggu', + 'day' => ':count hari', + 'a_day' => '{1}sehari|]1,Inf[:count hari', + 'd' => ':count hari', + 'hour' => ':count jam', + 'a_hour' => '{1}sejam|]1,Inf[:count jam', + 'h' => ':count jam', + 'minute' => ':count minit', + 'a_minute' => '{1}seminit|]1,Inf[:count minit', + 'min' => ':count minit', + 'second' => ':count saat', + 'a_second' => '{1}beberapa saat|]1,Inf[:count saat', + 'millisecond' => ':count milisaat', + 'a_millisecond' => '{1}semilisaat|]1,Inf[:count milliseconds', + 'microsecond' => ':count mikrodetik', + 'a_microsecond' => '{1}semikrodetik|]1,Inf[:count mikrodetik', + 's' => ':count saat', + 'ago' => ':time yang lepas', + 'from_now' => ':time dari sekarang', + 'after' => ':time kemudian', + 'before' => ':time sebelum', + 'diff_now' => 'sekarang', + 'diff_today' => 'Hari', + 'diff_today_regexp' => 'Hari(?:\\s+ini)?(?:\\s+pukul)?', + 'diff_yesterday' => 'semalam', + 'diff_yesterday_regexp' => 'Semalam(?:\\s+pukul)?', + 'diff_tomorrow' => 'esok', + 'diff_tomorrow_regexp' => 'Esok(?:\\s+pukul)?', + 'diff_before_yesterday' => 'kelmarin', + 'diff_after_tomorrow' => 'lusa', + 'formats' => [ + 'LT' => 'HH.mm', + 'LTS' => 'HH.mm.ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY [pukul] HH.mm', + 'LLLL' => 'dddd, D MMMM YYYY [pukul] HH.mm', + ], + 'calendar' => [ + 'sameDay' => '[Hari ini pukul] LT', + 'nextDay' => '[Esok pukul] LT', + 'nextWeek' => 'dddd [pukul] LT', + 'lastDay' => '[Kelmarin pukul] LT', + 'lastWeek' => 'dddd [lepas pukul] LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 1) { + return 'tengah malam'; + } + + if ($hour < 12) { + return 'pagi'; + } + + if ($hour < 13) { + return 'tengah hari'; + } + + if ($hour < 19) { + return 'petang'; + } + + return 'malam'; + }, + 'months' => ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogs', 'Sep', 'Okt', 'Nov', 'Dis'], + 'weekdays' => ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'], + 'weekdays_short' => ['Ahd', 'Isn', 'Sel', 'Rab', 'Kha', 'Jum', 'Sab'], + 'weekdays_min' => ['Ah', 'Is', 'Sl', 'Rb', 'Km', 'Jm', 'Sb'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' dan '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_BN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_BN.php new file mode 100644 index 0000000..ef837a2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_BN.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ms.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/MM/yy', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY, h:mm a', + 'LLLL' => 'dd MMMM YYYY, h:mm a', + ], + 'meridiem' => ['a', 'p'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_MY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_MY.php new file mode 100644 index 0000000..970d604 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_MY.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Azri Jamil + * - JD Isaacks + */ +return require __DIR__.'/ms.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_SG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_SG.php new file mode 100644 index 0000000..77cb83d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ms_SG.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ms.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/MM/yy', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY, h:mm a', + 'LLLL' => 'dddd, D MMMM YYYY, h:mm a', + ], + 'meridiem' => ['a', 'p'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mt.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mt.php new file mode 100644 index 0000000..e8aadcc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mt.php @@ -0,0 +1,65 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Alessandro Maruccia + */ +return [ + 'year' => 'sena|:count sni|:count sni|:count sni', + 'y' => 'sa sena|:count snin|:count snin|:count snin', + 'month' => 'xahar|:count xhur|:count xhur|:count xhur', + 'm' => ':count xahar|:count xhur|:count xhur|:count xhur', + 'week' => 'gimgħa|:count ġimgħat|:count ġimgħat|:count ġimgħat', + 'w' => 'ġimgħa|:count ġimgħat|:count ġimgħat|:count ġimgħat', + 'day' => 'ġurnata|:count ġranet|:count ġranet|:count ġranet', + 'd' => 'ġurnata|:count ġranet|:count ġranet|:count ġranet', + 'hour' => 'siegħa|:count siegħat|:count siegħat|:count siegħat', + 'h' => 'siegħa|:count sigħat|:count sigħat|:count sigħat', + 'minute' => 'minuta|:count minuti|:count minuti|:count minuti', + 'min' => 'min.|:count min.|:count min.|:count min.', + 'second' => 'ftit sekondi|:count sekondi|:count sekondi|:count sekondi', + 's' => 'sek.|:count sek.|:count sek.|:count sek.', + 'ago' => ':time ilu', + 'from_now' => 'f’ :time', + 'diff_now' => 'issa', + 'diff_today' => 'Illum', + 'diff_today_regexp' => 'Illum(?:\\s+fil-)?', + 'diff_yesterday' => 'lbieraħ', + 'diff_yesterday_regexp' => 'Il-bieraħ(?:\\s+fil-)?', + 'diff_tomorrow' => 'għada', + 'diff_tomorrow_regexp' => 'Għada(?:\\s+fil-)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Illum fil-]LT', + 'nextDay' => '[Għada fil-]LT', + 'nextWeek' => 'dddd [fil-]LT', + 'lastDay' => '[Il-bieraħ fil-]LT', + 'lastWeek' => 'dddd [li għadda] [fil-]LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numberº', + 'months' => ['Jannar', 'Frar', 'Marzu', 'April', 'Mejju', 'Ġunju', 'Lulju', 'Awwissu', 'Settembru', 'Ottubru', 'Novembru', 'Diċembru'], + 'months_short' => ['Jan', 'Fra', 'Mar', 'Apr', 'Mej', 'Ġun', 'Lul', 'Aww', 'Set', 'Ott', 'Nov', 'Diċ'], + 'weekdays' => ['Il-Ħadd', 'It-Tnejn', 'It-Tlieta', 'L-Erbgħa', 'Il-Ħamis', 'Il-Ġimgħa', 'Is-Sibt'], + 'weekdays_short' => ['Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib'], + 'weekdays_min' => ['Ħa', 'Tn', 'Tl', 'Er', 'Ħa', 'Ġi', 'Si'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' u '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mt_MT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mt_MT.php new file mode 100644 index 0000000..9534f68 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mt_MT.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/mt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mua.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mua.php new file mode 100644 index 0000000..a3a3c6f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mua.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['comme', 'lilli'], + 'weekdays' => ['Com’yakke', 'Comlaaɗii', 'Comzyiiɗii', 'Comkolle', 'Comkaldǝɓlii', 'Comgaisuu', 'Comzyeɓsuu'], + 'weekdays_short' => ['Cya', 'Cla', 'Czi', 'Cko', 'Cka', 'Cga', 'Cze'], + 'weekdays_min' => ['Cya', 'Cla', 'Czi', 'Cko', 'Cka', 'Cga', 'Cze'], + 'months' => ['Fĩi Loo', 'Cokcwaklaŋne', 'Cokcwaklii', 'Fĩi Marfoo', 'Madǝǝuutǝbijaŋ', 'Mamǝŋgwãafahbii', 'Mamǝŋgwãalii', 'Madǝmbii', 'Fĩi Dǝɓlii', 'Fĩi Mundaŋ', 'Fĩi Gwahlle', 'Fĩi Yuru'], + 'months_short' => ['FLO', 'CLA', 'CKI', 'FMF', 'MAD', 'MBI', 'MLI', 'MAM', 'FDE', 'FMU', 'FGW', 'FYU'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/my.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/my.php new file mode 100644 index 0000000..bbdfba4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/my.php @@ -0,0 +1,70 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - JD Isaacks + * - Nay Lin Aung + */ +return [ + 'year' => '{1}တစ်နှစ်|]1,Inf[:count နှစ်', + 'y' => ':count နှစ်', + 'month' => '{1}တစ်လ|]1,Inf[:count လ', + 'm' => ':count လ', + 'week' => ':count ပတ်', + 'w' => ':count ပတ်', + 'day' => '{1}တစ်ရက်|]1,Inf[:count ရက်', + 'd' => ':count ရက်', + 'hour' => '{1}တစ်နာရီ|]1,Inf[:count နာရီ', + 'h' => ':count နာရီ', + 'minute' => '{1}တစ်မိနစ်|]1,Inf[:count မိနစ်', + 'min' => ':count မိနစ်', + 'second' => '{1}စက္ကန်.အနည်းငယ်|]1,Inf[:count စက္ကန့်', + 's' => ':count စက္ကန့်', + 'ago' => 'လွန်ခဲ့သော :time က', + 'from_now' => 'လာမည့် :time မှာ', + 'after' => ':time ကြာပြီးနောက်', + 'before' => ':time မတိုင်ခင်', + 'diff_now' => 'အခုလေးတင်', + 'diff_today' => 'ယနေ.', + 'diff_yesterday' => 'မနေ့က', + 'diff_yesterday_regexp' => 'မနေ.က', + 'diff_tomorrow' => 'မနက်ဖြန်', + 'diff_before_yesterday' => 'တမြန်နေ့က', + 'diff_after_tomorrow' => 'တဘက်ခါ', + 'period_recurrences' => ':count ကြိမ်', + 'formats' => [ + 'LT' => 'Oh:Om A', + 'LTS' => 'Oh:Om:Os A', + 'L' => 'OD/OM/OY', + 'LL' => 'OD MMMM OY', + 'LLL' => 'OD MMMM OY Oh:Om A', + 'LLLL' => 'dddd OD MMMM OY Oh:Om A', + ], + 'calendar' => [ + 'sameDay' => '[ယနေ.] LT [မှာ]', + 'nextDay' => '[မနက်ဖြန်] LT [မှာ]', + 'nextWeek' => 'dddd LT [မှာ]', + 'lastDay' => '[မနေ.က] LT [မှာ]', + 'lastWeek' => '[ပြီးခဲ့သော] dddd LT [မှာ]', + 'sameElse' => 'L', + ], + 'months' => ['ဇန်နဝါရီ', 'ဖေဖော်ဝါရီ', 'မတ်', 'ဧပြီ', 'မေ', 'ဇွန်', 'ဇူလိုင်', 'သြဂုတ်', 'စက်တင်ဘာ', 'အောက်တိုဘာ', 'နိုဝင်ဘာ', 'ဒီဇင်ဘာ'], + 'months_short' => ['ဇန်', 'ဖေ', 'မတ်', 'ပြီ', 'မေ', 'ဇွန်', 'လိုင်', 'သြ', 'စက်', 'အောက်', 'နို', 'ဒီ'], + 'weekdays' => ['တနင်္ဂနွေ', 'တနင်္လာ', 'အင်္ဂါ', 'ဗုဒ္ဓဟူး', 'ကြာသပတေး', 'သောကြာ', 'စနေ'], + 'weekdays_short' => ['နွေ', 'လာ', 'ဂါ', 'ဟူး', 'ကြာ', 'သော', 'နေ'], + 'weekdays_min' => ['နွေ', 'လာ', 'ဂါ', 'ဟူး', 'ကြာ', 'သော', 'နေ'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'alt_numbers' => ['၀၀', '၀၁', '၀၂', '၀၃', '၀၄', '၀၅', '၀၆', '၀၇', '၀၈', '၀၉', '၁၀', '၁၁', '၁၂', '၁၃', '၁၄', '၁၅', '၁၆', '၁၇', '၁၈', '၁၉', '၂၀', '၂၁', '၂၂', '၂၃', '၂၄', '၂၅', '၂၆', '၂၇', '၂၈', '၂၉', '၃၀', '၃၁', '၃၂', '၃၃', '၃၄', '၃၅', '၃၆', '၃၇', '၃၈', '၃၉', '၄၀', '၄၁', '၄၂', '၄၃', '၄၄', '၄၅', '၄၆', '၄၇', '၄၈', '၄၉', '၅၀', '၅၁', '၅၂', '၅၃', '၅၄', '၅၅', '၅၆', '၅၇', '၅၈', '၅၉', '၆၀', '၆၁', '၆၂', '၆၃', '၆၄', '၆၅', '၆၆', '၆၇', '၆၈', '၆၉', '၇၀', '၇၁', '၇၂', '၇၃', '၇၄', '၇၅', '၇၆', '၇၇', '၇၈', '၇၉', '၈၀', '၈၁', '၈၂', '၈၃', '၈၄', '၈၅', '၈၆', '၈၇', '၈၈', '၈၉', '၉၀', '၉၁', '၉၂', '၉၃', '၉၄', '၉၅', '၉၆', '၉၇', '၉၈', '၉၉'], + 'meridiem' => ['နံနက်', 'ညနေ'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/my_MM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/my_MM.php new file mode 100644 index 0000000..a0108dd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/my_MM.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/my.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mzn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mzn.php new file mode 100644 index 0000000..70f5f23 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/mzn.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fa.php', [ + 'months' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اکتبر', 'نوامبر', 'دسامبر'], + 'months_short' => ['ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اکتبر', 'نوامبر', 'دسامبر'], + 'first_day_of_week' => 6, + 'weekend' => [5, 5], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'YYYY MMMM D, dddd HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan.php new file mode 100644 index 0000000..0affece --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/nan_TW.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan_TW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan_TW.php new file mode 100644 index 0000000..5c50aa4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan_TW.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY年MM月DD日', + ], + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => [' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月'], + 'weekdays' => ['禮拜日', '禮拜一', '禮拜二', '禮拜三', '禮拜四', '禮拜五', '禮拜六'], + 'weekdays_short' => ['日', '一', '二', '三', '四', '五', '六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['頂晡', '下晡'], + + 'year' => ':count 年', + 'y' => ':count 年', + 'a_year' => ':count 年', + + 'month' => ':count goe̍h', + 'm' => ':count goe̍h', + 'a_month' => ':count goe̍h', + + 'week' => ':count lé-pài', + 'w' => ':count lé-pài', + 'a_week' => ':count lé-pài', + + 'day' => ':count 日', + 'd' => ':count 日', + 'a_day' => ':count 日', + + 'hour' => ':count tiám-cheng', + 'h' => ':count tiám-cheng', + 'a_hour' => ':count tiám-cheng', + + 'minute' => ':count Hun-cheng', + 'min' => ':count Hun-cheng', + 'a_minute' => ':count Hun-cheng', + + 'second' => ':count Bió', + 's' => ':count Bió', + 'a_second' => ':count Bió', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan_TW@latin.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan_TW@latin.php new file mode 100644 index 0000000..99ca2a4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nan_TW@latin.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Arne Goetje arne@canonical.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], + 'months' => ['1goe̍h', '2goe̍h', '3goe̍h', '4goe̍h', '5goe̍h', '6goe̍h', '7goe̍h', '8goe̍h', '9goe̍h', '10goe̍h', '11goe̍h', '12goe̍h'], + 'months_short' => ['1g', '2g', '3g', '4g', '5g', '6g', '7g', '8g', '9g', '10g', '11g', '12g'], + 'weekdays' => ['lé-pài-ji̍t', 'pài-it', 'pài-jī', 'pài-saⁿ', 'pài-sì', 'pài-gō͘', 'pài-la̍k'], + 'weekdays_short' => ['lp', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6'], + 'weekdays_min' => ['lp', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['téng-po͘', 'ē-po͘'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/naq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/naq.php new file mode 100644 index 0000000..fbd9be9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/naq.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['ǁgoagas', 'ǃuias'], + 'weekdays' => ['Sontaxtsees', 'Mantaxtsees', 'Denstaxtsees', 'Wunstaxtsees', 'Dondertaxtsees', 'Fraitaxtsees', 'Satertaxtsees'], + 'weekdays_short' => ['Son', 'Ma', 'De', 'Wu', 'Do', 'Fr', 'Sat'], + 'weekdays_min' => ['Son', 'Ma', 'De', 'Wu', 'Do', 'Fr', 'Sat'], + 'months' => ['ǃKhanni', 'ǃKhanǀgôab', 'ǀKhuuǁkhâb', 'ǃHôaǂkhaib', 'ǃKhaitsâb', 'Gamaǀaeb', 'ǂKhoesaob', 'Aoǁkhuumûǁkhâb', 'Taraǀkhuumûǁkhâb', 'ǂNûǁnâiseb', 'ǀHooǂgaeb', 'Hôasoreǁkhâb'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd, D MMMM YYYY h:mm a', + ], + + 'year' => ':count kurigu', + 'y' => ':count kurigu', + 'a_year' => ':count kurigu', + + 'month' => ':count ǁaub', // less reliable + 'm' => ':count ǁaub', // less reliable + 'a_month' => ':count ǁaub', // less reliable + + 'week' => ':count hû', // less reliable + 'w' => ':count hû', // less reliable + 'a_week' => ':count hû', // less reliable + + 'day' => ':count ǀhobas', // less reliable + 'd' => ':count ǀhobas', // less reliable + 'a_day' => ':count ǀhobas', // less reliable + + 'hour' => ':count ǂgaes', // less reliable + 'h' => ':count ǂgaes', // less reliable + 'a_hour' => ':count ǂgaes', // less reliable + + 'minute' => ':count minutga', // less reliable + 'min' => ':count minutga', // less reliable + 'a_minute' => ':count minutga', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb.php new file mode 100644 index 0000000..371ee84 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb.php @@ -0,0 +1,84 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Alexander Tømmerås + * - Sigurd Gartmann + * - JD Isaacks + */ +return [ + 'year' => ':count år|:count år', + 'a_year' => 'ett år|:count år', + 'y' => ':count år|:count år', + 'month' => ':count måned|:count måneder', + 'a_month' => 'en måned|:count måneder', + 'm' => ':count md.', + 'week' => ':count uke|:count uker', + 'a_week' => 'en uke|:count uker', + 'w' => ':count u.', + 'day' => ':count dag|:count dager', + 'a_day' => 'en dag|:count dager', + 'd' => ':count d.', + 'hour' => ':count time|:count timer', + 'a_hour' => 'en time|:count timer', + 'h' => ':count t', + 'minute' => ':count minutt|:count minutter', + 'a_minute' => 'ett minutt|:count minutter', + 'min' => ':count min', + 'second' => ':count sekund|:count sekunder', + 'a_second' => 'noen sekunder|:count sekunder', + 's' => ':count sek', + 'ago' => ':time siden', + 'from_now' => 'om :time', + 'after' => ':time etter', + 'before' => ':time før', + 'diff_now' => 'akkurat nå', + 'diff_today' => 'i dag', + 'diff_today_regexp' => 'i dag(?:\\s+kl.)?', + 'diff_yesterday' => 'i går', + 'diff_yesterday_regexp' => 'i går(?:\\s+kl.)?', + 'diff_tomorrow' => 'i morgen', + 'diff_tomorrow_regexp' => 'i morgen(?:\\s+kl.)?', + 'diff_before_yesterday' => 'i forgårs', + 'diff_after_tomorrow' => 'i overmorgen', + 'period_recurrences' => 'en gang|:count ganger', + 'period_interval' => 'hver :interval', + 'period_start_date' => 'fra :date', + 'period_end_date' => 'til :date', + 'months' => ['januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'], + 'weekdays' => ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'], + 'weekdays_short' => ['søn', 'man', 'tir', 'ons', 'tor', 'fre', 'lør'], + 'weekdays_min' => ['sø', 'ma', 'ti', 'on', 'to', 'fr', 'lø'], + 'ordinal' => ':number.', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY [kl.] HH:mm', + 'LLLL' => 'dddd D. MMMM YYYY [kl.] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[i dag kl.] LT', + 'nextDay' => '[i morgen kl.] LT', + 'nextWeek' => 'dddd [kl.] LT', + 'lastDay' => '[i går kl.] LT', + 'lastWeek' => '[forrige] dddd [kl.] LT', + 'sameElse' => 'L', + ], + 'list' => [', ', ' og '], + 'meridiem' => ['a.m.', 'p.m.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb_NO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb_NO.php new file mode 100644 index 0000000..31678c5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb_NO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/nb.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb_SJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb_SJ.php new file mode 100644 index 0000000..ce0210b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nb_SJ.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/nb.php', [ + 'formats' => [ + 'LL' => 'D. MMM YYYY', + 'LLL' => 'D. MMMM YYYY, HH:mm', + 'LLLL' => 'dddd D. MMMM YYYY, HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nd.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nd.php new file mode 100644 index 0000000..f75d9a7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nd.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Sonto', 'Mvulo', 'Sibili', 'Sithathu', 'Sine', 'Sihlanu', 'Mgqibelo'], + 'weekdays_short' => ['Son', 'Mvu', 'Sib', 'Sit', 'Sin', 'Sih', 'Mgq'], + 'weekdays_min' => ['Son', 'Mvu', 'Sib', 'Sit', 'Sin', 'Sih', 'Mgq'], + 'months' => ['Zibandlela', 'Nhlolanja', 'Mbimbitho', 'Mabasa', 'Nkwenkwezi', 'Nhlangula', 'Ntulikazi', 'Ncwabakazi', 'Mpandula', 'Mfumfu', 'Lwezi', 'Mpalakazi'], + 'months_short' => ['Zib', 'Nhlo', 'Mbi', 'Mab', 'Nkw', 'Nhla', 'Ntu', 'Ncw', 'Mpan', 'Mfu', 'Lwe', 'Mpal'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + + 'year' => 'okweminyaka engu-:count', // less reliable + 'y' => 'okweminyaka engu-:count', // less reliable + 'a_year' => 'okweminyaka engu-:count', // less reliable + + 'month' => 'inyanga ezingu-:count', + 'm' => 'inyanga ezingu-:count', + 'a_month' => 'inyanga ezingu-:count', + + 'week' => 'amaviki angu-:count', + 'w' => 'amaviki angu-:count', + 'a_week' => 'amaviki angu-:count', + + 'day' => 'kwamalanga angu-:count', + 'd' => 'kwamalanga angu-:count', + 'a_day' => 'kwamalanga angu-:count', + + 'hour' => 'amahola angu-:count', + 'h' => 'amahola angu-:count', + 'a_hour' => 'amahola angu-:count', + + 'minute' => 'imizuzu engu-:count', + 'min' => 'imizuzu engu-:count', + 'a_minute' => 'imizuzu engu-:count', + + 'second' => 'imizuzwana engu-:count', + 's' => 'imizuzwana engu-:count', + 'a_second' => 'imizuzwana engu-:count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds.php new file mode 100644 index 0000000..c0b3775 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/nds_DE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds_DE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds_DE.php new file mode 100644 index 0000000..a6c57a9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds_DE.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - information from Kenneth Christiansen Kenneth Christiansen, Pablo Saratxaga kenneth@gnu.org, pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Jannuaar', 'Feberwaar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], + 'months_short' => ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], + 'weekdays' => ['Sünndag', 'Maandag', 'Dingsdag', 'Middeweek', 'Dunnersdag', 'Freedag', 'Sünnavend'], + 'weekdays_short' => ['Sdag', 'Maan', 'Ding', 'Midd', 'Dunn', 'Free', 'Svd.'], + 'weekdays_min' => ['Sd', 'Ma', 'Di', 'Mi', 'Du', 'Fr', 'Sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count Johr', + 'y' => ':countJ', + 'a_year' => '{1}een Johr|:count Johr', + + 'month' => ':count Maand', + 'm' => ':countM', + 'a_month' => '{1}een Maand|:count Maand', + + 'week' => ':count Week|:count Weken', + 'w' => ':countW', + 'a_week' => '{1}een Week|:count Week|:count Weken', + + 'day' => ':count Dag|:count Daag', + 'd' => ':countD', + 'a_day' => '{1}een Dag|:count Dag|:count Daag', + + 'hour' => ':count Stünn|:count Stünnen', + 'h' => ':countSt', + 'a_hour' => '{1}een Stünn|:count Stünn|:count Stünnen', + + 'minute' => ':count Minuut|:count Minuten', + 'min' => ':countm', + 'a_minute' => '{1}een Minuut|:count Minuut|:count Minuten', + + 'second' => ':count Sekunn|:count Sekunnen', + 's' => ':counts', + 'a_second' => 'en poor Sekunnen|:count Sekunn|:count Sekunnen', + + 'ago' => 'vör :time', + 'from_now' => 'in :time', + 'before' => ':time vörher', + 'after' => ':time later', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds_NL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds_NL.php new file mode 100644 index 0000000..de2c57b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nds_NL.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - information from Kenneth Christiansen Kenneth Christiansen, Pablo Saratxaga kenneth@gnu.org, pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Jaunuwoa', 'Februwoa', 'Moaz', 'Aprell', 'Mai', 'Juni', 'Juli', 'August', 'Septamba', 'Oktoba', 'Nowamba', 'Dezamba'], + 'months_short' => ['Jan', 'Feb', 'Moz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Now', 'Dez'], + 'weekdays' => ['Sinndag', 'Mondag', 'Dingsdag', 'Meddwäakj', 'Donnadag', 'Friedag', 'Sinnowend'], + 'weekdays_short' => ['Sdg', 'Mdg', 'Dsg', 'Mwk', 'Ddg', 'Fdg', 'Swd'], + 'weekdays_min' => ['Sdg', 'Mdg', 'Dsg', 'Mwk', 'Ddg', 'Fdg', 'Swd'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne.php new file mode 100644 index 0000000..d4caf0e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne.php @@ -0,0 +1,82 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - nootanghimire + * - Josh Soref + * - Nj Subedi + * - JD Isaacks + */ +return [ + 'year' => 'एक बर्ष|:count बर्ष', + 'y' => ':count वर्ष', + 'month' => 'एक महिना|:count महिना', + 'm' => ':count महिना', + 'week' => ':count हप्ता', + 'w' => ':count हप्ता', + 'day' => 'एक दिन|:count दिन', + 'd' => ':count दिन', + 'hour' => 'एक घण्टा|:count घण्टा', + 'h' => ':count घण्टा', + 'minute' => 'एक मिनेट|:count मिनेट', + 'min' => ':count मिनेट', + 'second' => 'केही क्षण|:count सेकेण्ड', + 's' => ':count सेकेण्ड', + 'ago' => ':time अगाडि', + 'from_now' => ':timeमा', + 'after' => ':time पछि', + 'before' => ':time अघि', + 'diff_now' => 'अहिले', + 'diff_today' => 'आज', + 'diff_yesterday' => 'हिजो', + 'diff_tomorrow' => 'भोलि', + 'formats' => [ + 'LT' => 'Aको h:mm बजे', + 'LTS' => 'Aको h:mm:ss बजे', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, Aको h:mm बजे', + 'LLLL' => 'dddd, D MMMM YYYY, Aको h:mm बजे', + ], + 'calendar' => [ + 'sameDay' => '[आज] LT', + 'nextDay' => '[भोलि] LT', + 'nextWeek' => '[आउँदो] dddd[,] LT', + 'lastDay' => '[हिजो] LT', + 'lastWeek' => '[गएको] dddd[,] LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 3) { + return 'राति'; + } + if ($hour < 12) { + return 'बिहान'; + } + if ($hour < 16) { + return 'दिउँसो'; + } + if ($hour < 20) { + return 'साँझ'; + } + + return 'राति'; + }, + 'months' => ['जनवरी', 'फेब्रुवरी', 'मार्च', 'अप्रिल', 'मई', 'जुन', 'जुलाई', 'अगष्ट', 'सेप्टेम्बर', 'अक्टोबर', 'नोभेम्बर', 'डिसेम्बर'], + 'months_short' => ['जन.', 'फेब्रु.', 'मार्च', 'अप्रि.', 'मई', 'जुन', 'जुलाई.', 'अग.', 'सेप्ट.', 'अक्टो.', 'नोभे.', 'डिसे.'], + 'weekdays' => ['आइतबार', 'सोमबार', 'मङ्गलबार', 'बुधबार', 'बिहिबार', 'शुक्रबार', 'शनिबार'], + 'weekdays_short' => ['आइत.', 'सोम.', 'मङ्गल.', 'बुध.', 'बिहि.', 'शुक्र.', 'शनि.'], + 'weekdays_min' => ['आ.', 'सो.', 'मं.', 'बु.', 'बि.', 'शु.', 'श.'], + 'list' => [', ', ' र '], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne_IN.php new file mode 100644 index 0000000..f68d00e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne_IN.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ne.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'yy/M/d', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D, h:mm a', + 'LLLL' => 'YYYY MMMM D, dddd, h:mm a', + ], + 'months' => ['जनवरी', 'फेब्रुअरी', 'मार्च', 'अप्रिल', 'मे', 'जुन', 'जुलाई', 'अगस्ट', 'सेप्टेम्बर', 'अक्टोबर', 'नोभेम्बर', 'डिसेम्बर'], + 'months_short' => ['जनवरी', 'फेब्रुअरी', 'मार्च', 'अप्रिल', 'मे', 'जुन', 'जुलाई', 'अगस्ट', 'सेप्टेम्बर', 'अक्टोबर', 'नोभेम्बर', 'डिसेम्बर'], + 'weekend' => [0, 0], + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne_NP.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne_NP.php new file mode 100644 index 0000000..27840c0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ne_NP.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ne.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nhn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nhn.php new file mode 100644 index 0000000..5a85831 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nhn.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/nhn_MX.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nhn_MX.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nhn_MX.php new file mode 100644 index 0000000..9db88a1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nhn_MX.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'], + 'months_short' => ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'], + 'weekdays' => ['teoilhuitl', 'ceilhuitl', 'omeilhuitl', 'yeilhuitl', 'nahuilhuitl', 'macuililhuitl', 'chicuaceilhuitl'], + 'weekdays_short' => ['teo', 'cei', 'ome', 'yei', 'nau', 'mac', 'chi'], + 'weekdays_min' => ['teo', 'cei', 'ome', 'yei', 'nau', 'mac', 'chi'], + 'day_of_first_week_of_year' => 1, + + 'month' => ':count metztli', // less reliable + 'm' => ':count metztli', // less reliable + 'a_month' => ':count metztli', // less reliable + + 'week' => ':count tonalli', // less reliable + 'w' => ':count tonalli', // less reliable + 'a_week' => ':count tonalli', // less reliable + + 'day' => ':count tonatih', // less reliable + 'd' => ':count tonatih', // less reliable + 'a_day' => ':count tonatih', // less reliable + + 'minute' => ':count toltecayotl', // less reliable + 'min' => ':count toltecayotl', // less reliable + 'a_minute' => ':count toltecayotl', // less reliable + + 'second' => ':count ome', // less reliable + 's' => ':count ome', // less reliable + 'a_second' => ':count ome', // less reliable + + 'year' => ':count xihuitl', + 'y' => ':count xihuitl', + 'a_year' => ':count xihuitl', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/niu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/niu.php new file mode 100644 index 0000000..bd9be8a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/niu.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/niu_NU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/niu_NU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/niu_NU.php new file mode 100644 index 0000000..6e7a697 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/niu_NU.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RockET Systems Emani Fakaotimanava-Lui emani@niue.nu + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Ianuali', 'Fepuali', 'Masi', 'Apelila', 'Me', 'Iuni', 'Iulai', 'Aokuso', 'Sepetema', 'Oketopa', 'Novema', 'Tesemo'], + 'months_short' => ['Ian', 'Fep', 'Mas', 'Ape', 'Me', 'Iun', 'Iul', 'Aok', 'Sep', 'Oke', 'Nov', 'Tes'], + 'weekdays' => ['Aho Tapu', 'Aho Gofua', 'Aho Ua', 'Aho Lotu', 'Aho Tuloto', 'Aho Falaile', 'Aho Faiumu'], + 'weekdays_short' => ['Tapu', 'Gofua', 'Ua', 'Lotu', 'Tuloto', 'Falaile', 'Faiumu'], + 'weekdays_min' => ['Tapu', 'Gofua', 'Ua', 'Lotu', 'Tuloto', 'Falaile', 'Faiumu'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => ':count tau', + 'y' => ':count tau', + 'a_year' => ':count tau', + + 'month' => ':count mahina', + 'm' => ':count mahina', + 'a_month' => ':count mahina', + + 'week' => ':count faahi tapu', + 'w' => ':count faahi tapu', + 'a_week' => ':count faahi tapu', + + 'day' => ':count aho', + 'd' => ':count aho', + 'a_day' => ':count aho', + + 'hour' => ':count e tulā', + 'h' => ':count e tulā', + 'a_hour' => ':count e tulā', + + 'minute' => ':count minuti', + 'min' => ':count minuti', + 'a_minute' => ':count minuti', + + 'second' => ':count sekone', + 's' => ':count sekone', + 'a_second' => ':count sekone', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl.php new file mode 100644 index 0000000..2d73770 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl.php @@ -0,0 +1,113 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Roy + * - Stephan + * - François B + * - Tim Fish + * - Kevin Huang + * - Jacob Middag + * - JD Isaacks + * - Roy + * - Stephan + * - François B + * - Tim Fish + * - Jacob Middag + * - JD Isaacks + * - Propaganistas + * - MegaXLR + * - adriaanzon + * - MonkeyPhysics + * - JeroenG + * - RikSomers + * - proclame + * - Rik de Groot (hwdegroot) + */ +return [ + 'year' => ':count jaar|:count jaar', + 'a_year' => 'een jaar|:count jaar', + 'y' => ':countj', + 'month' => ':count maand|:count maanden', + 'a_month' => 'een maand|:count maanden', + 'm' => ':countmnd', + 'week' => ':count week|:count weken', + 'a_week' => 'een week|:count weken', + 'w' => ':countw', + 'day' => ':count dag|:count dagen', + 'a_day' => 'een dag|:count dagen', + 'd' => ':countd', + 'hour' => ':count uur|:count uur', + 'a_hour' => 'een uur|:count uur', + 'h' => ':countu', + 'minute' => ':count minuut|:count minuten', + 'a_minute' => 'een minuut|:count minuten', + 'min' => ':countmin', + 'second' => ':count seconde|:count seconden', + 'a_second' => 'een paar seconden|:count seconden', + 's' => ':counts', + 'ago' => ':time geleden', + 'from_now' => 'over :time', + 'after' => ':time later', + 'before' => ':time eerder', + 'diff_now' => 'nu', + 'diff_today' => 'vandaag', + 'diff_today_regexp' => 'vandaag(?:\\s+om)?', + 'diff_yesterday' => 'gisteren', + 'diff_yesterday_regexp' => 'gisteren(?:\\s+om)?', + 'diff_tomorrow' => 'morgen', + 'diff_tomorrow_regexp' => 'morgen(?:\\s+om)?', + 'diff_after_tomorrow' => 'overmorgen', + 'diff_before_yesterday' => 'eergisteren', + 'period_recurrences' => ':count keer', + 'period_interval' => function (string $interval = '') { + /** @var string $output */ + $output = preg_replace('/^(een|één|1)\s+/u', '', $interval); + + if (preg_match('/^(een|één|1)( jaar|j| uur|u)/u', $interval)) { + return "elk $output"; + } + + return "elke $output"; + }, + 'period_start_date' => 'van :date', + 'period_end_date' => 'tot :date', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD-MM-YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[vandaag om] LT', + 'nextDay' => '[morgen om] LT', + 'nextWeek' => 'dddd [om] LT', + 'lastDay' => '[gisteren om] LT', + 'lastWeek' => '[afgelopen] dddd [om] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + return $number.(($number === 1 || $number === 8 || $number >= 20) ? 'ste' : 'de'); + }, + 'months' => ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'], + 'months_short' => ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'mmm_suffix' => '.', + 'weekdays' => ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'], + 'weekdays_short' => ['zo.', 'ma.', 'di.', 'wo.', 'do.', 'vr.', 'za.'], + 'weekdays_min' => ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' en '], + 'meridiem' => ['\'s ochtends', '\'s middags'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_AW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_AW.php new file mode 100644 index 0000000..5ec136d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_AW.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/nl.php', [ + 'formats' => [ + 'L' => 'DD-MM-YY', + ], + 'months' => ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'], + 'months_short' => ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'weekdays' => ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'], + 'weekdays_short' => ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'], + 'weekdays_min' => ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_BE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_BE.php new file mode 100644 index 0000000..037f5b4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_BE.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Roy + * - Stephan + * - François B + * - Tim Fish + * - Kevin Huang + * - Jacob Middag + * - JD Isaacks + * - Propaganistas + */ +return array_replace_recursive(require __DIR__.'/nl.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_BQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_BQ.php new file mode 100644 index 0000000..c269197 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_BQ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/nl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_CW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_CW.php new file mode 100644 index 0000000..c269197 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_CW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/nl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_NL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_NL.php new file mode 100644 index 0000000..14e4853 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_NL.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/nl.php', [ + 'months' => ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'], + 'months_short' => ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'weekdays' => ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'], + 'weekdays_short' => ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'], + 'weekdays_min' => ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_SR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_SR.php new file mode 100644 index 0000000..c269197 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_SR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/nl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_SX.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_SX.php new file mode 100644 index 0000000..c269197 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nl_SX.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/nl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nmg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nmg.php new file mode 100644 index 0000000..4d1df6e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nmg.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['maná', 'kugú'], + 'weekdays' => ['sɔ́ndɔ', 'mɔ́ndɔ', 'sɔ́ndɔ mafú mába', 'sɔ́ndɔ mafú málal', 'sɔ́ndɔ mafú mána', 'mabágá má sukul', 'sásadi'], + 'weekdays_short' => ['sɔ́n', 'mɔ́n', 'smb', 'sml', 'smn', 'mbs', 'sas'], + 'weekdays_min' => ['sɔ́n', 'mɔ́n', 'smb', 'sml', 'smn', 'mbs', 'sas'], + 'months' => ['ngwɛn matáhra', 'ngwɛn ńmba', 'ngwɛn ńlal', 'ngwɛn ńna', 'ngwɛn ńtan', 'ngwɛn ńtuó', 'ngwɛn hɛmbuɛrí', 'ngwɛn lɔmbi', 'ngwɛn rɛbvuâ', 'ngwɛn wum', 'ngwɛn wum navǔr', 'krísimin'], + 'months_short' => ['ng1', 'ng2', 'ng3', 'ng4', 'ng5', 'ng6', 'ng7', 'ng8', 'ng9', 'ng10', 'ng11', 'kris'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nn.php new file mode 100644 index 0000000..041f7b2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nn.php @@ -0,0 +1,78 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Alexander Tømmerås + * - Øystein + * - JD Isaacks + * - Gaute Hvoslef Kvalnes (gaute) + */ +return [ + 'year' => ':count år', + 'a_year' => 'eit år|:count år', + 'y' => ':count år', + 'month' => ':count månad|:count månader', + 'a_month' => 'ein månad|:count månader', + 'm' => ':count md', + 'week' => ':count veke|:count veker', + 'a_week' => 'ei veke|:count veker', + 'w' => ':countv', + 'day' => ':count dag|:count dagar', + 'a_day' => 'ein dag|:count dagar', + 'd' => ':countd', + 'hour' => ':count time|:count timar', + 'a_hour' => 'ein time|:count timar', + 'h' => ':countt', + 'minute' => ':count minutt', + 'a_minute' => 'eit minutt|:count minutt', + 'min' => ':countm', + 'second' => ':count sekund', + 'a_second' => 'nokre sekund|:count sekund', + 's' => ':counts', + 'ago' => ':time sidan', + 'from_now' => 'om :time', + 'after' => ':time etter', + 'before' => ':time før', + 'diff_today' => 'I dag', + 'diff_yesterday' => 'I går', + 'diff_yesterday_regexp' => 'I går(?:\\s+klokka)?', + 'diff_tomorrow' => 'I morgon', + 'diff_tomorrow_regexp' => 'I morgon(?:\\s+klokka)?', + 'diff_today_regexp' => 'I dag(?:\\s+klokka)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY [kl.] H:mm', + 'LLLL' => 'dddd D. MMMM YYYY [kl.] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[I dag klokka] LT', + 'nextDay' => '[I morgon klokka] LT', + 'nextWeek' => 'dddd [klokka] LT', + 'lastDay' => '[I går klokka] LT', + 'lastWeek' => '[Føregåande] dddd [klokka] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'], + 'weekdays' => ['sundag', 'måndag', 'tysdag', 'onsdag', 'torsdag', 'fredag', 'laurdag'], + 'weekdays_short' => ['sun', 'mån', 'tys', 'ons', 'tor', 'fre', 'lau'], + 'weekdays_min' => ['su', 'må', 'ty', 'on', 'to', 'fr', 'la'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' og '], + 'meridiem' => ['f.m.', 'e.m.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nn_NO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nn_NO.php new file mode 100644 index 0000000..8e16871 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nn_NO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/nn.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nnh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nnh.php new file mode 100644 index 0000000..007d239 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nnh.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['mbaʼámbaʼ', 'ncwònzém'], + 'weekdays' => null, + 'weekdays_short' => ['lyɛʼɛ́ sẅíŋtè', 'mvfò lyɛ̌ʼ', 'mbɔ́ɔntè mvfò lyɛ̌ʼ', 'tsètsɛ̀ɛ lyɛ̌ʼ', 'mbɔ́ɔntè tsetsɛ̀ɛ lyɛ̌ʼ', 'mvfò màga lyɛ̌ʼ', 'màga lyɛ̌ʼ'], + 'weekdays_min' => null, + 'months' => null, + 'months_short' => ['saŋ tsetsɛ̀ɛ lùm', 'saŋ kàg ngwóŋ', 'saŋ lepyè shúm', 'saŋ cÿó', 'saŋ tsɛ̀ɛ cÿó', 'saŋ njÿoláʼ', 'saŋ tyɛ̀b tyɛ̀b mbʉ̀ŋ', 'saŋ mbʉ̀ŋ', 'saŋ ngwɔ̀ʼ mbÿɛ', 'saŋ tàŋa tsetsáʼ', 'saŋ mejwoŋó', 'saŋ lùm'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/yy', + 'LL' => 'D MMM, YYYY', + 'LLL' => '[lyɛ]̌ʼ d [na] MMMM, YYYY HH:mm', + 'LLLL' => 'dddd , [lyɛ]̌ʼ d [na] MMMM, YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/no.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/no.php new file mode 100644 index 0000000..f4497c7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/no.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Daniel S. Billing + * - Paul + * - Jimmie Johansson + * - Jens Herlevsen + */ +return array_replace_recursive(require __DIR__.'/nb.php', [ + 'formats' => [ + 'LLL' => 'D. MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D. MMMM YYYY [kl.] HH:mm', + ], + 'calendar' => [ + 'nextWeek' => 'på dddd [kl.] LT', + 'lastWeek' => '[i] dddd[s kl.] LT', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nr.php new file mode 100644 index 0000000..1bc999f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nr.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/nr_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nr_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nr_ZA.php new file mode 100644 index 0000000..f9a7be8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nr_ZA.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Janabari', 'uFeberbari', 'uMatjhi', 'u-Apreli', 'Meyi', 'Juni', 'Julayi', 'Arhostosi', 'Septemba', 'Oktoba', 'Usinyikhaba', 'Disemba'], + 'months_short' => ['Jan', 'Feb', 'Mat', 'Apr', 'Mey', 'Jun', 'Jul', 'Arh', 'Sep', 'Okt', 'Usi', 'Dis'], + 'weekdays' => ['uSonto', 'uMvulo', 'uLesibili', 'lesithathu', 'uLesine', 'ngoLesihlanu', 'umGqibelo'], + 'weekdays_short' => ['Son', 'Mvu', 'Bil', 'Tha', 'Ne', 'Hla', 'Gqi'], + 'weekdays_min' => ['Son', 'Mvu', 'Bil', 'Tha', 'Ne', 'Hla', 'Gqi'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nso.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nso.php new file mode 100644 index 0000000..2a6cabb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nso.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/nso_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nso_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nso_ZA.php new file mode 100644 index 0000000..b08fe6d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nso_ZA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Janaware', 'Febereware', 'Matšhe', 'Aprele', 'Mei', 'June', 'Julae', 'Agostose', 'Setemere', 'Oktobere', 'Nofemere', 'Disemere'], + 'months_short' => ['Jan', 'Feb', 'Mat', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Set', 'Okt', 'Nof', 'Dis'], + 'weekdays' => ['LaMorena', 'Mošupologo', 'Labobedi', 'Laboraro', 'Labone', 'Labohlano', 'Mokibelo'], + 'weekdays_short' => ['Son', 'Moš', 'Bed', 'Rar', 'Ne', 'Hla', 'Mok'], + 'weekdays_min' => ['Son', 'Moš', 'Bed', 'Rar', 'Ne', 'Hla', 'Mok'], + 'day_of_first_week_of_year' => 1, + + 'year' => ':count ngwaga', + 'y' => ':count ngwaga', + 'a_year' => ':count ngwaga', + + 'month' => ':count Kgwedi', + 'm' => ':count Kgwedi', + 'a_month' => ':count Kgwedi', + + 'week' => ':count Beke', + 'w' => ':count Beke', + 'a_week' => ':count Beke', + + 'day' => ':count Letšatši', + 'd' => ':count Letšatši', + 'a_day' => ':count Letšatši', + + 'hour' => ':count Iri', + 'h' => ':count Iri', + 'a_hour' => ':count Iri', + + 'minute' => ':count Motsotso', + 'min' => ':count Motsotso', + 'a_minute' => ':count Motsotso', + + 'second' => ':count motsotswana', + 's' => ':count motsotswana', + 'a_second' => ':count motsotswana', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nus.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nus.php new file mode 100644 index 0000000..789bc39 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nus.php @@ -0,0 +1,36 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['RW', 'TŊ'], + 'weekdays' => ['Cäŋ kuɔth', 'Jiec la̱t', 'Rɛw lätni', 'Diɔ̱k lätni', 'Ŋuaan lätni', 'Dhieec lätni', 'Bäkɛl lätni'], + 'weekdays_short' => ['Cäŋ', 'Jiec', 'Rɛw', 'Diɔ̱k', 'Ŋuaan', 'Dhieec', 'Bäkɛl'], + 'weekdays_min' => ['Cäŋ', 'Jiec', 'Rɛw', 'Diɔ̱k', 'Ŋuaan', 'Dhieec', 'Bäkɛl'], + 'months' => ['Tiop thar pɛt', 'Pɛt', 'Duɔ̱ɔ̱ŋ', 'Guak', 'Duät', 'Kornyoot', 'Pay yie̱tni', 'Tho̱o̱r', 'Tɛɛr', 'Laath', 'Kur', 'Tio̱p in di̱i̱t'], + 'months_short' => ['Tiop', 'Pɛt', 'Duɔ̱ɔ̱', 'Guak', 'Duä', 'Kor', 'Pay', 'Thoo', 'Tɛɛ', 'Laa', 'Kur', 'Tid'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd D MMMM YYYY h:mm a', + ], + + 'year' => ':count jiök', // less reliable + 'y' => ':count jiök', // less reliable + 'a_year' => ':count jiök', // less reliable + + 'month' => ':count pay', // less reliable + 'm' => ':count pay', // less reliable + 'a_month' => ':count pay', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nyn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nyn.php new file mode 100644 index 0000000..8660ea4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/nyn.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Sande', 'Orwokubanza', 'Orwakabiri', 'Orwakashatu', 'Orwakana', 'Orwakataano', 'Orwamukaaga'], + 'weekdays_short' => ['SAN', 'ORK', 'OKB', 'OKS', 'OKN', 'OKT', 'OMK'], + 'weekdays_min' => ['SAN', 'ORK', 'OKB', 'OKS', 'OKN', 'OKT', 'OMK'], + 'months' => ['Okwokubanza', 'Okwakabiri', 'Okwakashatu', 'Okwakana', 'Okwakataana', 'Okwamukaaga', 'Okwamushanju', 'Okwamunaana', 'Okwamwenda', 'Okwaikumi', 'Okwaikumi na kumwe', 'Okwaikumi na ibiri'], + 'months_short' => ['KBZ', 'KBR', 'KST', 'KKN', 'KTN', 'KMK', 'KMS', 'KMN', 'KMW', 'KKM', 'KNK', 'KNB'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/oc.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/oc.php new file mode 100644 index 0000000..c9411d6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/oc.php @@ -0,0 +1,100 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Quentí + */ +// @codeCoverageIgnoreStart +use Symfony\Component\Translation\PluralizationRules; + +if (class_exists('Symfony\\Component\\Translation\\PluralizationRules')) { + PluralizationRules::set(static function ($number) { + return $number == 1 ? 0 : 1; + }, 'oc'); +} +// @codeCoverageIgnoreEnd + +return [ + 'year' => ':count an|:count ans', + 'a_year' => 'un an|:count ans', + 'y' => ':count an|:count ans', + 'month' => ':count mes|:count meses', + 'a_month' => 'un mes|:count meses', + 'm' => ':count mes|:count meses', + 'week' => ':count setmana|:count setmanas', + 'a_week' => 'una setmana|:count setmanas', + 'w' => ':count setmana|:count setmanas', + 'day' => ':count jorn|:count jorns', + 'a_day' => 'un jorn|:count jorns', + 'd' => ':count jorn|:count jorns', + 'hour' => ':count ora|:count oras', + 'a_hour' => 'una ora|:count oras', + 'h' => ':count ora|:count oras', + 'minute' => ':count minuta|:count minutas', + 'a_minute' => 'una minuta|:count minutas', + 'min' => ':count minuta|:count minutas', + 'second' => ':count segonda|:count segondas', + 'a_second' => 'una segonda|:count segondas', + 's' => ':count segonda|:count segondas', + 'ago' => 'fa :time', + 'from_now' => 'd\'aquí :time', + 'after' => ':time aprèp', + 'before' => ':time abans', + 'diff_now' => 'ara meteis', + 'diff_today' => 'Uèi', + 'diff_today_regexp' => 'Uèi(?:\\s+a)?', + 'diff_yesterday' => 'ièr', + 'diff_yesterday_regexp' => 'Ièr(?:\\s+a)?', + 'diff_tomorrow' => 'deman', + 'diff_tomorrow_regexp' => 'Deman(?:\\s+a)?', + 'diff_before_yesterday' => 'ièr delà', + 'diff_after_tomorrow' => 'deman passat', + 'period_recurrences' => ':count còp|:count còps', + 'period_interval' => 'cada :interval', + 'period_start_date' => 'de :date', + 'period_end_date' => 'fins a :date', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM [de] YYYY', + 'LLL' => 'D MMMM [de] YYYY [a] H:mm', + 'LLLL' => 'dddd D MMMM [de] YYYY [a] H:mm', + ], + 'calendar' => [ + 'sameDay' => '[Uèi a] LT', + 'nextDay' => '[Deman a] LT', + 'nextWeek' => 'dddd [a] LT', + 'lastDay' => '[Ièr a] LT', + 'lastWeek' => 'dddd [passat a] LT', + 'sameElse' => 'L', + ], + 'months' => ['de genièr', 'de febrièr', 'de març', 'd\'abrial', 'de mai', 'de junh', 'de julhet', 'd\'agost', 'de setembre', 'd’octòbre', 'de novembre', 'de decembre'], + 'months_standalone' => ['genièr', 'febrièr', 'març', 'abrial', 'mai', 'junh', 'julh', 'agost', 'setembre', 'octòbre', 'novembre', 'decembre'], + 'months_short' => ['gen.', 'feb.', 'març', 'abr.', 'mai', 'junh', 'julh', 'ago.', 'sep.', 'oct.', 'nov.', 'dec.'], + 'weekdays' => ['dimenge', 'diluns', 'dimars', 'dimècres', 'dijòus', 'divendres', 'dissabte'], + 'weekdays_short' => ['dg', 'dl', 'dm', 'dc', 'dj', 'dv', 'ds'], + 'weekdays_min' => ['dg', 'dl', 'dm', 'dc', 'dj', 'dv', 'ds'], + 'ordinal' => function ($number, string $period = '') { + $ordinal = [1 => 'èr', 2 => 'nd'][(int) $number] ?? 'en'; + + // feminine for year, week, hour, minute, second + if (preg_match('/^[yYwWhHgGis]$/', $period)) { + $ordinal .= 'a'; + } + + return $number.$ordinal; + }, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' e '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/oc_FR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/oc_FR.php new file mode 100644 index 0000000..01eb5c1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/oc_FR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/oc.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om.php new file mode 100644 index 0000000..b8d5a0b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation & Sagalee Oromoo Publishing Co. Inc. locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'dd-MMM-YYYY', + 'LLL' => 'dd MMMM YYYY HH:mm', + 'LLLL' => 'dddd, MMMM D, YYYY HH:mm', + ], + 'months' => ['Amajjii', 'Guraandhala', 'Bitooteessa', 'Elba', 'Caamsa', 'Waxabajjii', 'Adooleessa', 'Hagayya', 'Fuulbana', 'Onkololeessa', 'Sadaasa', 'Muddee'], + 'months_short' => ['Ama', 'Gur', 'Bit', 'Elb', 'Cam', 'Wax', 'Ado', 'Hag', 'Ful', 'Onk', 'Sad', 'Mud'], + 'weekdays' => ['Dilbata', 'Wiixata', 'Qibxata', 'Roobii', 'Kamiisa', 'Jimaata', 'Sanbata'], + 'weekdays_short' => ['Dil', 'Wix', 'Qib', 'Rob', 'Kam', 'Jim', 'San'], + 'weekdays_min' => ['Dil', 'Wix', 'Qib', 'Rob', 'Kam', 'Jim', 'San'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['WD', 'WB'], + + 'year' => 'wggoota :count', + 'y' => 'wggoota :count', + 'a_year' => 'wggoota :count', + + 'month' => 'ji’a :count', + 'm' => 'ji’a :count', + 'a_month' => 'ji’a :count', + + 'week' => 'torban :count', + 'w' => 'torban :count', + 'a_week' => 'torban :count', + + 'day' => 'guyyaa :count', + 'd' => 'guyyaa :count', + 'a_day' => 'guyyaa :count', + + 'hour' => 'saʼaatii :count', + 'h' => 'saʼaatii :count', + 'a_hour' => 'saʼaatii :count', + + 'minute' => 'daqiiqaa :count', + 'min' => 'daqiiqaa :count', + 'a_minute' => 'daqiiqaa :count', + + 'second' => 'sekoondii :count', + 's' => 'sekoondii :count', + 'a_second' => 'sekoondii :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om_ET.php new file mode 100644 index 0000000..044760e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om_ET.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/om.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om_KE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om_KE.php new file mode 100644 index 0000000..f5a4d1c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/om_KE.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/om.php', [ + 'day_of_first_week_of_year' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/or.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/or.php new file mode 100644 index 0000000..3aa7173 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/or.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/or_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/or_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/or_IN.php new file mode 100644 index 0000000..57a89f5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/or_IN.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM AP Linux Technology Center, Yamato Software Laboratory bug-glibc@gnu.org + */ +return [ + 'diff_now' => 'ବର୍ତ୍ତମାନ', + 'diff_yesterday' => 'ଗତକାଲି', + 'diff_tomorrow' => 'ଆସନ୍ତାକାଲି', + 'formats' => [ + 'LT' => 'Oh:Om A', + 'LTS' => 'Oh:Om:Os A', + 'L' => 'OD-OM-OY', + 'LL' => 'OD MMMM OY', + 'LLL' => 'OD MMMM OY Oh:Om A', + 'LLLL' => 'dddd OD MMMM OY Oh:Om A', + ], + 'months' => ['ଜାନୁଆରୀ', 'ଫେବୃଆରୀ', 'ମାର୍ଚ୍ଚ', 'ଅପ୍ରେଲ', 'ମଇ', 'ଜୁନ', 'ଜୁଲାଇ', 'ଅଗଷ୍ଟ', 'ସେପ୍ଟେମ୍ବର', 'ଅକ୍ଟୋବର', 'ନଭେମ୍ବର', 'ଡିସେମ୍ବର'], + 'months_short' => ['ଜାନୁଆରୀ', 'ଫେବୃଆରୀ', 'ମାର୍ଚ୍ଚ', 'ଅପ୍ରେଲ', 'ମଇ', 'ଜୁନ', 'ଜୁଲାଇ', 'ଅଗଷ୍ଟ', 'ସେପ୍ଟେମ୍ବର', 'ଅକ୍ଟୋବର', 'ନଭେମ୍ବର', 'ଡିସେମ୍ବର'], + 'weekdays' => ['ରବିବାର', 'ସୋମବାର', 'ମଙ୍ଗଳବାର', 'ବୁଧବାର', 'ଗୁରୁବାର', 'ଶୁକ୍ରବାର', 'ଶନିବାର'], + 'weekdays_short' => ['ରବି', 'ସୋମ', 'ମଙ୍ଗଳ', 'ବୁଧ', 'ଗୁରୁ', 'ଶୁକ୍ର', 'ଶନି'], + 'weekdays_min' => ['ରବି', 'ସୋମ', 'ମଙ୍ଗଳ', 'ବୁଧ', 'ଗୁରୁ', 'ଶୁକ୍ର', 'ଶନି'], + 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', '୯', '୧୦', '୧୧', '୧୨', '୧୩', '୧୪', '୧୫', '୧୬', '୧୭', '୧୮', '୧୯', '୨୦', '୨୧', '୨୨', '୨୩', '୨୪', '୨୫', '୨୬', '୨୭', '୨୮', '୨୯', '୩୦', '୩୧', '୩୨', '୩୩', '୩୪', '୩୫', '୩୬', '୩୭', '୩୮', '୩୯', '୪୦', '୪୧', '୪୨', '୪୩', '୪୪', '୪୫', '୪୬', '୪୭', '୪୮', '୪୯', '୫୦', '୫୧', '୫୨', '୫୩', '୫୪', '୫୫', '୫୬', '୫୭', '୫୮', '୫୯', '୬୦', '୬୧', '୬୨', '୬୩', '୬୪', '୬୫', '୬୬', '୬୭', '୬୮', '୬୯', '୭୦', '୭୧', '୭୨', '୭୩', '୭୪', '୭୫', '୭୬', '୭୭', '୭୮', '୭୯', '୮୦', '୮୧', '୮୨', '୮୩', '୮୪', '୮୫', '୮୬', '୮୭', '୮୮', '୮୯', '୯୦', '୯୧', '୯୨', '୯୩', '୯୪', '୯୫', '୯୬', '୯୭', '୯୮', '୯୯'], + 'year' => ':count ବର୍ଷ', + 'y' => ':count ବ.', + 'month' => ':count ମାସ', + 'm' => ':count ମା.', + 'week' => ':count ସପ୍ତାହ', + 'w' => ':count ସପ୍ତା.', + 'day' => ':count ଦିନ', + 'd' => ':count ଦିନ', + 'hour' => ':count ଘଣ୍ତ', + 'h' => ':count ଘ.', + 'minute' => ':count ମିନଟ', + 'min' => ':count ମି.', + 'second' => ':count ସେକଣ୍ଢ', + 's' => ':count ସେ.', + 'ago' => ':time ପୂର୍ବେ', + 'from_now' => ':timeରେ', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/os.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/os.php new file mode 100644 index 0000000..5f55e8a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/os.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/os_RU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/os_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/os_RU.php new file mode 100644 index 0000000..9592d15 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/os_RU.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['январы', 'февралы', 'мартъийы', 'апрелы', 'майы', 'июны', 'июлы', 'августы', 'сентябры', 'октябры', 'ноябры', 'декабры'], + 'months_short' => ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'], + 'weekdays' => ['Хуыцаубон', 'Къуырисæр', 'Дыццæг', 'Æртыццæг', 'Цыппæрæм', 'Майрæмбон', 'Сабат'], + 'weekdays_short' => ['Хцб', 'Крс', 'Дцг', 'Æрт', 'Цпр', 'Мрб', 'Сбт'], + 'weekdays_min' => ['Хцб', 'Крс', 'Дцг', 'Æрт', 'Цпр', 'Мрб', 'Сбт'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'minute' => ':count гыццыл', // less reliable + 'min' => ':count гыццыл', // less reliable + 'a_minute' => ':count гыццыл', // less reliable + + 'second' => ':count æндæр', // less reliable + 's' => ':count æндæр', // less reliable + 'a_second' => ':count æндæр', // less reliable + + 'year' => ':count аз', + 'y' => ':count аз', + 'a_year' => ':count аз', + + 'month' => ':count мӕй', + 'm' => ':count мӕй', + 'a_month' => ':count мӕй', + + 'week' => ':count къуыри', + 'w' => ':count къуыри', + 'a_week' => ':count къуыри', + + 'day' => ':count бон', + 'd' => ':count бон', + 'a_day' => ':count бон', + + 'hour' => ':count сахат', + 'h' => ':count сахат', + 'a_hour' => ':count сахат', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa.php new file mode 100644 index 0000000..48b2033 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Tsutomu Kuroda + * - Punjab + */ +return [ + 'year' => 'ਇੱਕ ਸਾਲ|:count ਸਾਲ', + 'month' => 'ਇੱਕ ਮਹੀਨਾ|:count ਮਹੀਨੇ', + 'week' => 'ਹਫਤਾ|:count ਹਫ਼ਤੇ', + 'day' => 'ਇੱਕ ਦਿਨ|:count ਦਿਨ', + 'hour' => 'ਇੱਕ ਘੰਟਾ|:count ਘੰਟੇ', + 'minute' => 'ਇਕ ਮਿੰਟ|:count ਮਿੰਟ', + 'second' => 'ਕੁਝ ਸਕਿੰਟ|:count ਸਕਿੰਟ', + 'ago' => ':time ਪਹਿਲਾਂ', + 'from_now' => ':time ਵਿੱਚ', + 'before' => ':time ਤੋਂ ਪਹਿਲਾਂ', + 'after' => ':time ਤੋਂ ਬਾਅਦ', + 'diff_now' => 'ਹੁਣ', + 'diff_today' => 'ਅਜ', + 'diff_yesterday' => 'ਕਲ', + 'diff_tomorrow' => 'ਕਲ', + 'formats' => [ + 'LT' => 'A h:mm ਵਜੇ', + 'LTS' => 'A h:mm:ss ਵਜੇ', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm ਵਜੇ', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm ਵਜੇ', + ], + 'calendar' => [ + 'sameDay' => '[ਅਜ] LT', + 'nextDay' => '[ਕਲ] LT', + 'nextWeek' => '[ਅਗਲਾ] dddd, LT', + 'lastDay' => '[ਕਲ] LT', + 'lastWeek' => '[ਪਿਛਲੇ] dddd, LT', + 'sameElse' => 'L', + ], + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'ਰਾਤ'; + } + if ($hour < 10) { + return 'ਸਵੇਰ'; + } + if ($hour < 17) { + return 'ਦੁਪਹਿਰ'; + } + if ($hour < 20) { + return 'ਸ਼ਾਮ'; + } + + return 'ਰਾਤ'; + }, + 'months' => ['ਜਨਵਰੀ', 'ਫ਼ਰਵਰੀ', 'ਮਾਰਚ', 'ਅਪ੍ਰੈਲ', 'ਮਈ', 'ਜੂਨ', 'ਜੁਲਾਈ', 'ਅਗਸਤ', 'ਸਤੰਬਰ', 'ਅਕਤੂਬਰ', 'ਨਵੰਬਰ', 'ਦਸੰਬਰ'], + 'months_short' => ['ਜਨਵਰੀ', 'ਫ਼ਰਵਰੀ', 'ਮਾਰਚ', 'ਅਪ੍ਰੈਲ', 'ਮਈ', 'ਜੂਨ', 'ਜੁਲਾਈ', 'ਅਗਸਤ', 'ਸਤੰਬਰ', 'ਅਕਤੂਬਰ', 'ਨਵੰਬਰ', 'ਦਸੰਬਰ'], + 'weekdays' => ['ਐਤਵਾਰ', 'ਸੋਮਵਾਰ', 'ਮੰਗਲਵਾਰ', 'ਬੁਧਵਾਰ', 'ਵੀਰਵਾਰ', 'ਸ਼ੁੱਕਰਵਾਰ', 'ਸ਼ਨੀਚਰਵਾਰ'], + 'weekdays_short' => ['ਐਤ', 'ਸੋਮ', 'ਮੰਗਲ', 'ਬੁਧ', 'ਵੀਰ', 'ਸ਼ੁਕਰ', 'ਸ਼ਨੀ'], + 'weekdays_min' => ['ਐਤ', 'ਸੋਮ', 'ਮੰਗਲ', 'ਬੁਧ', 'ਵੀਰ', 'ਸ਼ੁਕਰ', 'ਸ਼ਨੀ'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' ਅਤੇ '], + 'weekend' => [0, 0], + 'alt_numbers' => ['੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_Arab.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_Arab.php new file mode 100644 index 0000000..39b0653 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_Arab.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ur.php', [ + 'weekdays' => ['اتوار', 'پیر', 'منگل', 'بُدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], + 'weekdays_short' => ['اتوار', 'پیر', 'منگل', 'بُدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], + 'weekdays_min' => ['اتوار', 'پیر', 'منگل', 'بُدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], + 'months' => ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئ', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئ', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd, DD MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_Guru.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_Guru.php new file mode 100644 index 0000000..7adff5c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_Guru.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/pa.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D/M/yy', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY, h:mm a', + 'LLLL' => 'dddd, D MMMM YYYY, h:mm a', + ], + 'months' => ['ਜਨਵਰੀ', 'ਫ਼ਰਵਰੀ', 'ਮਾਰਚ', 'ਅਪ੍ਰੈਲ', 'ਮਈ', 'ਜੂਨ', 'ਜੁਲਾਈ', 'ਅਗਸਤ', 'ਸਤੰਬਰ', 'ਅਕਤੂਬਰ', 'ਨਵੰਬਰ', 'ਦਸੰਬਰ'], + 'months_short' => ['ਜਨ', 'ਫ਼ਰ', 'ਮਾਰਚ', 'ਅਪ੍ਰੈ', 'ਮਈ', 'ਜੂਨ', 'ਜੁਲਾ', 'ਅਗ', 'ਸਤੰ', 'ਅਕਤੂ', 'ਨਵੰ', 'ਦਸੰ'], + 'weekdays' => ['ਐਤਵਾਰ', 'ਸੋਮਵਾਰ', 'ਮੰਗਲਵਾਰ', 'ਬੁੱਧਵਾਰ', 'ਵੀਰਵਾਰ', 'ਸ਼ੁੱਕਰਵਾਰ', 'ਸ਼ਨਿੱਚਰਵਾਰ'], + 'weekdays_short' => ['ਐਤ', 'ਸੋਮ', 'ਮੰਗਲ', 'ਬੁੱਧ', 'ਵੀਰ', 'ਸ਼ੁੱਕਰ', 'ਸ਼ਨਿੱਚਰ'], + 'weekdays_min' => ['ਐਤ', 'ਸੋਮ', 'ਮੰਗ', 'ਬੁੱਧ', 'ਵੀਰ', 'ਸ਼ੁੱਕ', 'ਸ਼ਨਿੱ'], + 'weekend' => [0, 0], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_IN.php new file mode 100644 index 0000000..ca67642 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_IN.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Guo Xiang Tan + * - Josh Soref + * - Ash + * - harpreetkhalsagtbit + */ +return require __DIR__.'/pa.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_PK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_PK.php new file mode 100644 index 0000000..f9af11c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pa_PK.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['جنوري', 'فروري', 'مارچ', 'اپريل', 'مٓی', 'جون', 'جولاي', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنوري', 'فروري', 'مارچ', 'اپريل', 'مٓی', 'جون', 'جولاي', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر'], + 'weekdays' => ['اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته'], + 'weekdays_short' => ['اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته'], + 'weekdays_min' => ['اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ص', 'ش'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap.php new file mode 100644 index 0000000..b4c1706 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return [ + 'formats' => [ + 'LT' => 'HH.mm', + 'LTS' => 'HH.mm:ss', + 'L' => 'DD-MM-YY', + 'LL' => 'MMMM [di] DD, YYYY', + 'LLL' => 'DD MMM HH.mm', + 'LLLL' => 'MMMM DD, YYYY HH.mm', + ], + 'months' => ['yanüari', 'febrüari', 'mart', 'aprel', 'mei', 'yüni', 'yüli', 'ougùstùs', 'sèptèmber', 'oktober', 'novèmber', 'desèmber'], + 'months_short' => ['yan', 'feb', 'mar', 'apr', 'mei', 'yün', 'yül', 'oug', 'sèp', 'okt', 'nov', 'des'], + 'weekdays' => ['djadomingo', 'djaluna', 'djamars', 'djawebs', 'djarason', 'djabierne', 'djasabra'], + 'weekdays_short' => ['do', 'lu', 'ma', 'we', 'ra', 'bi', 'sa'], + 'weekdays_min' => ['do', 'lu', 'ma', 'we', 'ra', 'bi', 'sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'year' => ':count aña', + 'month' => ':count luna', + 'week' => ':count siman', + 'day' => ':count dia', + 'hour' => ':count ora', + 'minute' => ':count minüt', + 'second' => ':count sekònde', + 'list' => [', ', ' i '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap_AW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap_AW.php new file mode 100644 index 0000000..e9a48ff --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap_AW.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - information from native speaker Pablo Saratxaga pablo@mandrakesoft.com + */ +return require __DIR__.'/pap.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap_CW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap_CW.php new file mode 100644 index 0000000..e9a48ff --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pap_CW.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - information from native speaker Pablo Saratxaga pablo@mandrakesoft.com + */ +return require __DIR__.'/pap.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pl.php new file mode 100644 index 0000000..b720535 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pl.php @@ -0,0 +1,126 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Wacław Jacek + * - François B + * - Tim Fish + * - Serhan Apaydın + * - Massimiliano Caniparoli + * - JD Isaacks + * - Jakub Szwacz + * - Jan + * - Paul + * - damlys + * - Marek (marast78) + * - Peter (UnrulyNatives) + * - Qrzysio + * - Jan (aso824) + * - diverpl + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count rok|:count lata|:count lat', + 'a_year' => 'rok|:count lata|:count lat', + 'y' => ':count r|:count l|:count l', + 'month' => ':count miesiąc|:count miesiące|:count miesięcy', + 'a_month' => 'miesiąc|:count miesiące|:count miesięcy', + 'm' => ':count mies.', + 'week' => ':count tydzień|:count tygodnie|:count tygodni', + 'a_week' => 'tydzień|:count tygodnie|:count tygodni', + 'w' => ':count tyg.', + 'day' => ':count dzień|:count dni|:count dni', + 'a_day' => 'dzień|:count dni|:count dni', + 'd' => ':count d', + 'hour' => ':count godzina|:count godziny|:count godzin', + 'a_hour' => 'godzina|:count godziny|:count godzin', + 'h' => ':count godz.', + 'minute' => ':count minuta|:count minuty|:count minut', + 'a_minute' => 'minuta|:count minuty|:count minut', + 'min' => ':count min', + 'second' => ':count sekunda|:count sekundy|:count sekund', + 'a_second' => '{1}kilka sekund|:count sekunda|:count sekundy|:count sekund', + 's' => ':count sek.', + 'ago' => ':time temu', + 'from_now' => static function ($time) { + return 'za '.strtr($time, [ + 'godzina' => 'godzinę', + 'minuta' => 'minutę', + 'sekunda' => 'sekundę', + ]); + }, + 'after' => ':time po', + 'before' => ':time przed', + 'diff_now' => 'teraz', + 'diff_today' => 'Dziś', + 'diff_today_regexp' => 'Dziś(?:\\s+o)?', + 'diff_yesterday' => 'wczoraj', + 'diff_yesterday_regexp' => 'Wczoraj(?:\\s+o)?', + 'diff_tomorrow' => 'jutro', + 'diff_tomorrow_regexp' => 'Jutro(?:\\s+o)?', + 'diff_before_yesterday' => 'przedwczoraj', + 'diff_after_tomorrow' => 'pojutrze', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Dziś o] LT', + 'nextDay' => '[Jutro o] LT', + 'nextWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[W niedzielę o] LT'; + case 2: + return '[We wtorek o] LT'; + case 3: + return '[W środę o] LT'; + case 6: + return '[W sobotę o] LT'; + default: + return '[W] dddd [o] LT'; + } + }, + 'lastDay' => '[Wczoraj o] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[W zeszłą niedzielę o] LT'; + case 3: + return '[W zeszłą środę o] LT'; + case 6: + return '[W zeszłą sobotę o] LT'; + default: + return '[W zeszły] dddd [o] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['stycznia', 'lutego', 'marca', 'kwietnia', 'maja', 'czerwca', 'lipca', 'sierpnia', 'września', 'października', 'listopada', 'grudnia'], + 'months_standalone' => ['styczeń', 'luty', 'marzec', 'kwiecień', 'maj', 'czerwiec', 'lipiec', 'sierpień', 'wrzesień', 'październik', 'listopad', 'grudzień'], + 'months_short' => ['sty', 'lut', 'mar', 'kwi', 'maj', 'cze', 'lip', 'sie', 'wrz', 'paź', 'lis', 'gru'], + 'months_regexp' => '/(DD?o?\.?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['niedziela', 'poniedziałek', 'wtorek', 'środa', 'czwartek', 'piątek', 'sobota'], + 'weekdays_short' => ['ndz', 'pon', 'wt', 'śr', 'czw', 'pt', 'sob'], + 'weekdays_min' => ['Nd', 'Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' i '], + 'meridiem' => ['przed południem', 'po południu'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pl_PL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pl_PL.php new file mode 100644 index 0000000..222bcdb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pl_PL.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/prg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/prg.php new file mode 100644 index 0000000..6e63f4a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/prg.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'months' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], + 'months_short' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'YYYY MMMM D, dddd HH:mm', + ], + + 'year' => ':count meta', + 'y' => ':count meta', + 'a_year' => ':count meta', + + 'month' => ':count mēniks', // less reliable + 'm' => ':count mēniks', // less reliable + 'a_month' => ':count mēniks', // less reliable + + 'week' => ':count sawaītin', // less reliable + 'w' => ':count sawaītin', // less reliable + 'a_week' => ':count sawaītin', // less reliable + + 'day' => ':count di', + 'd' => ':count di', + 'a_day' => ':count di', + + 'hour' => ':count bruktēt', // less reliable + 'h' => ':count bruktēt', // less reliable + 'a_hour' => ':count bruktēt', // less reliable + + 'minute' => ':count līkuts', // less reliable + 'min' => ':count līkuts', // less reliable + 'a_minute' => ':count līkuts', // less reliable + + 'second' => ':count kitan', // less reliable + 's' => ':count kitan', // less reliable + 'a_second' => ':count kitan', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ps.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ps.php new file mode 100644 index 0000000..a928b28 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ps.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Muhammad Nasir Rahimi + * - Nassim Nasibullah (spinzar) + */ +return [ + 'year' => ':count کال|:count کاله', + 'y' => ':countکال|:countکاله', + 'month' => ':count مياشت|:count مياشتي', + 'm' => ':countمياشت|:countمياشتي', + 'week' => ':count اونۍ|:count اونۍ', + 'w' => ':countاونۍ|:countاونۍ', + 'day' => ':count ورځ|:count ورځي', + 'd' => ':countورځ|:countورځي', + 'hour' => ':count ساعت|:count ساعته', + 'h' => ':countساعت|:countساعته', + 'minute' => ':count دقيقه|:count دقيقې', + 'min' => ':countدقيقه|:countدقيقې', + 'second' => ':count ثانيه|:count ثانيې', + 's' => ':countثانيه|:countثانيې', + 'ago' => ':time دمخه', + 'from_now' => ':time له اوس څخه', + 'after' => ':time وروسته', + 'before' => ':time دمخه', + 'list' => ['، ', ' او '], + 'meridiem' => ['غ.م.', 'غ.و.'], + 'weekdays' => ['اتوار', 'ګل', 'نهه', 'شورو', 'زيارت', 'جمعه', 'خالي'], + 'weekdays_short' => ['ا', 'ګ', 'ن', 'ش', 'ز', 'ج', 'خ'], + 'weekdays_min' => ['ا', 'ګ', 'ن', 'ش', 'ز', 'ج', 'خ'], + 'months' => ['جنوري', 'فبروري', 'مارچ', 'اپریل', 'مۍ', 'جون', 'جولای', 'اگست', 'سېپتمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنوري', 'فبروري', 'مارچ', 'اپریل', 'مۍ', 'جون', 'جولای', 'اگست', 'سېپتمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_standalone' => ['جنوري', 'فېبروري', 'مارچ', 'اپریل', 'مۍ', 'جون', 'جولای', 'اگست', 'سپتمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_short_standalone' => ['جنوري', 'فبروري', 'مارچ', 'اپریل', 'مۍ', 'جون', 'جولای', 'اگست', 'سپتمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'first_day_of_week' => 6, + 'weekend' => [4, 5], + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'YYYY/M/d', + 'LL' => 'YYYY MMM D', + 'LLL' => 'د YYYY د MMMM D H:mm', + 'LLLL' => 'dddd د YYYY د MMMM D H:mm', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ps_AF.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ps_AF.php new file mode 100644 index 0000000..6ec5180 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ps_AF.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ps.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt.php new file mode 100644 index 0000000..bb6359b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt.php @@ -0,0 +1,116 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Cassiano Montanari + * - Matt Pope + * - François B + * - Prodis + * - JD Isaacks + * - Raphael Amorim + * - João Magalhães + * - victortobias + * - Paulo Freitas + * - Sebastian Thierer + * - Claudson Martins (claudsonm) + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count ano|:count anos', + 'a_year' => 'um ano|:count anos', + 'y' => ':counta', + 'month' => ':count mês|:count meses', + 'a_month' => 'um mês|:count meses', + 'm' => ':countm', + 'week' => ':count semana|:count semanas', + 'a_week' => 'uma semana|:count semanas', + 'w' => ':countsem', + 'day' => ':count dia|:count dias', + 'a_day' => 'um dia|:count dias', + 'd' => ':countd', + 'hour' => ':count hora|:count horas', + 'a_hour' => 'uma hora|:count horas', + 'h' => ':counth', + 'minute' => ':count minuto|:count minutos', + 'a_minute' => 'um minuto|:count minutos', + 'min' => ':countmin', + 'second' => ':count segundo|:count segundos', + 'a_second' => 'alguns segundos|:count segundos', + 's' => ':counts', + 'millisecond' => ':count milissegundo|:count milissegundos', + 'a_millisecond' => 'um milissegundo|:count milissegundos', + 'ms' => ':countms', + 'microsecond' => ':count microssegundo|:count microssegundos', + 'a_microsecond' => 'um microssegundo|:count microssegundos', + 'µs' => ':countµs', + 'ago' => 'há :time', + 'from_now' => 'em :time', + 'after' => ':time depois', + 'before' => ':time antes', + 'diff_now' => 'agora', + 'diff_today' => 'Hoje', + 'diff_today_regexp' => 'Hoje(?:\\s+às)?', + 'diff_yesterday' => 'ontem', + 'diff_yesterday_regexp' => 'Ontem(?:\\s+às)?', + 'diff_tomorrow' => 'amanhã', + 'diff_tomorrow_regexp' => 'Amanhã(?:\\s+às)?', + 'diff_before_yesterday' => 'anteontem', + 'diff_after_tomorrow' => 'depois de amanhã', + 'period_recurrences' => 'uma vez|:count vezes', + 'period_interval' => 'cada :interval', + 'period_start_date' => 'de :date', + 'period_end_date' => 'até :date', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D [de] MMMM [de] YYYY', + 'LLL' => 'D [de] MMMM [de] YYYY HH:mm', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Hoje às] LT', + 'nextDay' => '[Amanhã às] LT', + 'nextWeek' => 'dddd [às] LT', + 'lastDay' => '[Ontem às] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + case 6: + return '[Último] dddd [às] LT'; + default: + return '[Última] dddd [às] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':numberº', + 'months' => ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'], + 'months_short' => ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'], + 'weekdays' => ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'], + 'weekdays_short' => ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'], + 'weekdays_min' => ['Do', '2ª', '3ª', '4ª', '5ª', '6ª', 'Sá'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' e '], + 'ordinal_words' => [ + 'of' => 'de', + 'first' => 'primeira', + 'second' => 'segunda', + 'third' => 'terceira', + 'fourth' => 'quarta', + 'fifth' => 'quinta', + 'last' => 'última', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_AO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_AO.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_AO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_BR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_BR.php new file mode 100644 index 0000000..e917c5c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_BR.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Cassiano Montanari + * - Eduardo Dalla Vecchia + * - David Rodrigues + * - Matt Pope + * - François B + * - Prodis + * - Marlon Maxwel + * - JD Isaacks + * - Raphael Amorim + * - Rafael Raupp + * - felipeleite1 + * - swalker + * - Lucas Macedo + * - Paulo Freitas + * - Sebastian Thierer + */ +return array_replace_recursive(require __DIR__.'/pt.php', [ + 'period_recurrences' => 'uma|:count vez', + 'period_interval' => 'toda :interval', + 'formats' => [ + 'LLL' => 'D [de] MMMM [de] YYYY [às] HH:mm', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY [às] HH:mm', + ], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_CH.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_CH.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_CV.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_CV.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_CV.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_GQ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_GQ.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_GQ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_GW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_GW.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_GW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_LU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_LU.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_LU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_MO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_MO.php new file mode 100644 index 0000000..f2b5eab --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_MO.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/pt.php', [ + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'LLL' => 'D [de] MMMM [de] YYYY, h:mm a', + 'LLLL' => 'dddd, D [de] MMMM [de] YYYY, h:mm a', + ], + 'first_day_of_week' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_MZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_MZ.php new file mode 100644 index 0000000..fbc0c97 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_MZ.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/pt.php', [ + 'first_day_of_week' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_PT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_PT.php new file mode 100644 index 0000000..2a76fc1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_PT.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RAP bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/pt.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'], + 'months_short' => ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'], + 'weekdays' => ['domingo', 'segunda', 'terça', 'quarta', 'quinta', 'sexta', 'sábado'], + 'weekdays_short' => ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'], + 'weekdays_min' => ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_ST.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_ST.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_ST.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_TL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_TL.php new file mode 100644 index 0000000..22c01ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/pt_TL.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/pt.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu.php new file mode 100644 index 0000000..65278cd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/es_UY.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM, YYYY HH:mm', + ], + 'first_day_of_week' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu_BO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu_BO.php new file mode 100644 index 0000000..d5db6bf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu_BO.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/qu.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu_EC.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu_EC.php new file mode 100644 index 0000000..d5db6bf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/qu_EC.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/qu.php', [ + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/quz.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/quz.php new file mode 100644 index 0000000..1640c02 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/quz.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/quz_PE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/quz_PE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/quz_PE.php new file mode 100644 index 0000000..d322918 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/quz_PE.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Sugar Labs // OLPC sugarlabs.org libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['iniru', 'phiwriru', 'marsu', 'awril', 'mayu', 'huniyu', 'huliyu', 'agustu', 'siptiyimri', 'uktuwri', 'nuwiyimri', 'tisiyimri'], + 'months_short' => ['ini', 'phi', 'mar', 'awr', 'may', 'hun', 'hul', 'agu', 'sip', 'ukt', 'nuw', 'tis'], + 'weekdays' => ['tuminku', 'lunis', 'martis', 'miyirkulis', 'juywis', 'wiyirnis', 'sawatu'], + 'weekdays_short' => ['tum', 'lun', 'mar', 'miy', 'juy', 'wiy', 'saw'], + 'weekdays_min' => ['tum', 'lun', 'mar', 'miy', 'juy', 'wiy', 'saw'], + 'day_of_first_week_of_year' => 1, + + 'minute' => ':count uchuy', // less reliable + 'min' => ':count uchuy', // less reliable + 'a_minute' => ':count uchuy', // less reliable + + 'year' => ':count wata', + 'y' => ':count wata', + 'a_year' => ':count wata', + + 'month' => ':count killa', + 'm' => ':count killa', + 'a_month' => ':count killa', + + 'week' => ':count simana', + 'w' => ':count simana', + 'a_week' => ':count simana', + + 'day' => ':count pʼunchaw', + 'd' => ':count pʼunchaw', + 'a_day' => ':count pʼunchaw', + + 'hour' => ':count ura', + 'h' => ':count ura', + 'a_hour' => ':count ura', + + 'second' => ':count iskay ñiqin', + 's' => ':count iskay ñiqin', + 'a_second' => ':count iskay ñiqin', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/raj.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/raj.php new file mode 100644 index 0000000..26138c9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/raj.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/raj_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/raj_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/raj_IN.php new file mode 100644 index 0000000..7b4589c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/raj_IN.php @@ -0,0 +1,47 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - meghrajsuthar03@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर'], + 'months_short' => ['जन', 'फर', 'मार्च', 'अप्रै', 'मई', 'जून', 'जुल', 'अग', 'सित', 'अक्टू', 'नव', 'दिस'], + 'weekdays' => ['रविवार', 'सोमवार', 'मंगल्लवार', 'बुधवार', 'बृहस्पतिवार', 'शुक्रवार', 'शनिवार'], + 'weekdays_short' => ['रवि', 'सोम', 'मंगल', 'बुध', 'बृहस्पति', 'शुक्र', 'शनि'], + 'weekdays_min' => ['रवि', 'सोम', 'मंगल', 'बुध', 'बृहस्पति', 'शुक्र', 'शनि'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], + + 'year' => ':count आंहू', // less reliable + 'y' => ':count आंहू', // less reliable + 'a_year' => ':count आंहू', // less reliable + + 'month' => ':count सूरज', // less reliable + 'm' => ':count सूरज', // less reliable + 'a_month' => ':count सूरज', // less reliable + + 'week' => ':count निवाज', // less reliable + 'w' => ':count निवाज', // less reliable + 'a_week' => ':count निवाज', // less reliable + + 'day' => ':count अेक', // less reliable + 'd' => ':count अेक', // less reliable + 'a_day' => ':count अेक', // less reliable + + 'hour' => ':count दुनियांण', // less reliable + 'h' => ':count दुनियांण', // less reliable + 'a_hour' => ':count दुनियांण', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rm.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rm.php new file mode 100644 index 0000000..1843f45 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rm.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - tjku + * - Max Melentiev + * - Juanito Fatas + * - Tsutomu Kuroda + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Nicolás Hock Isaza + * - sebastian de castelberg + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'Do MMMM YYYY', + 'LLL' => 'Do MMMM, HH:mm [Uhr]', + 'LLLL' => 'dddd, Do MMMM YYYY, HH:mm [Uhr]', + ], + 'year' => ':count onn|:count onns', + 'month' => ':count mais', + 'week' => ':count emna|:count emnas', + 'day' => ':count di|:count dis', + 'hour' => ':count oura|:count ouras', + 'minute' => ':count minuta|:count minutas', + 'second' => ':count secunda|:count secundas', + 'weekdays' => ['dumengia', 'glindesdi', 'mardi', 'mesemna', 'gievgia', 'venderdi', 'sonda'], + 'weekdays_short' => ['du', 'gli', 'ma', 'me', 'gie', 've', 'so'], + 'weekdays_min' => ['du', 'gli', 'ma', 'me', 'gie', 've', 'so'], + 'months' => ['schaner', 'favrer', 'mars', 'avrigl', 'matg', 'zercladur', 'fanadur', 'avust', 'settember', 'october', 'november', 'december'], + 'months_short' => ['schan', 'favr', 'mars', 'avr', 'matg', 'zercl', 'fan', 'avust', 'sett', 'oct', 'nov', 'dec'], + 'meridiem' => ['avantmezdi', 'suentermezdi'], + 'list' => [', ', ' e '], + 'first_day_of_week' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rn.php new file mode 100644 index 0000000..8ab958e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rn.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Z.MU.', 'Z.MW.'], + 'weekdays' => ['Ku w’indwi', 'Ku wa mbere', 'Ku wa kabiri', 'Ku wa gatatu', 'Ku wa kane', 'Ku wa gatanu', 'Ku wa gatandatu'], + 'weekdays_short' => ['cu.', 'mbe.', 'kab.', 'gtu.', 'kan.', 'gnu.', 'gnd.'], + 'weekdays_min' => ['cu.', 'mbe.', 'kab.', 'gtu.', 'kan.', 'gnu.', 'gnd.'], + 'months' => ['Nzero', 'Ruhuhuma', 'Ntwarante', 'Ndamukiza', 'Rusama', 'Ruheshi', 'Mukakaro', 'Nyandagaro', 'Nyakanga', 'Gitugutu', 'Munyonyo', 'Kigarama'], + 'months_short' => ['Mut.', 'Gas.', 'Wer.', 'Mat.', 'Gic.', 'Kam.', 'Nya.', 'Kan.', 'Nze.', 'Ukw.', 'Ugu.', 'Uku.'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'year' => 'imyaka :count', + 'y' => 'imyaka :count', + 'a_year' => 'imyaka :count', + + 'month' => 'amezi :count', + 'm' => 'amezi :count', + 'a_month' => 'amezi :count', + + 'week' => 'indwi :count', + 'w' => 'indwi :count', + 'a_week' => 'indwi :count', + + 'day' => 'imisi :count', + 'd' => 'imisi :count', + 'a_day' => 'imisi :count', + + 'hour' => 'amasaha :count', + 'h' => 'amasaha :count', + 'a_hour' => 'amasaha :count', + + 'minute' => 'iminuta :count', + 'min' => 'iminuta :count', + 'a_minute' => 'iminuta :count', + + 'second' => 'inguvu :count', // less reliable + 's' => 'inguvu :count', // less reliable + 'a_second' => 'inguvu :count', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro.php new file mode 100644 index 0000000..868a327 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro.php @@ -0,0 +1,77 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - JD Isaacks + * - Cătălin Georgescu + * - Valentin Ivaşcu (oriceon) + */ +return [ + 'year' => ':count an|:count ani|:count ani', + 'a_year' => 'un an|:count ani|:count ani', + 'y' => ':count a.', + 'month' => ':count lună|:count luni|:count luni', + 'a_month' => 'o lună|:count luni|:count luni', + 'm' => ':count l.', + 'week' => ':count săptămână|:count săptămâni|:count săptămâni', + 'a_week' => 'o săptămână|:count săptămâni|:count săptămâni', + 'w' => ':count săp.', + 'day' => ':count zi|:count zile|:count zile', + 'a_day' => 'o zi|:count zile|:count zile', + 'd' => ':count z.', + 'hour' => ':count oră|:count ore|:count ore', + 'a_hour' => 'o oră|:count ore|:count ore', + 'h' => ':count o.', + 'minute' => ':count minut|:count minute|:count minute', + 'a_minute' => 'un minut|:count minute|:count minute', + 'min' => ':count m.', + 'second' => ':count secundă|:count secunde|:count secunde', + 'a_second' => 'câteva secunde|:count secunde|:count secunde', + 's' => ':count sec.', + 'ago' => ':time în urmă', + 'from_now' => 'peste :time', + 'after' => 'peste :time', + 'before' => 'acum :time', + 'diff_now' => 'acum', + 'diff_today' => 'azi', + 'diff_today_regexp' => 'azi(?:\\s+la)?', + 'diff_yesterday' => 'ieri', + 'diff_yesterday_regexp' => 'ieri(?:\\s+la)?', + 'diff_tomorrow' => 'mâine', + 'diff_tomorrow_regexp' => 'mâine(?:\\s+la)?', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY H:mm', + 'LLLL' => 'dddd, D MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[azi la] LT', + 'nextDay' => '[mâine la] LT', + 'nextWeek' => 'dddd [la] LT', + 'lastDay' => '[ieri la] LT', + 'lastWeek' => '[fosta] dddd [la] LT', + 'sameElse' => 'L', + ], + 'months' => ['ianuarie', 'februarie', 'martie', 'aprilie', 'mai', 'iunie', 'iulie', 'august', 'septembrie', 'octombrie', 'noiembrie', 'decembrie'], + 'months_short' => ['ian.', 'feb.', 'mar.', 'apr.', 'mai', 'iun.', 'iul.', 'aug.', 'sept.', 'oct.', 'nov.', 'dec.'], + 'weekdays' => ['duminică', 'luni', 'marți', 'miercuri', 'joi', 'vineri', 'sâmbătă'], + 'weekdays_short' => ['dum', 'lun', 'mar', 'mie', 'joi', 'vin', 'sâm'], + 'weekdays_min' => ['du', 'lu', 'ma', 'mi', 'jo', 'vi', 'sâ'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' și '], + 'meridiem' => ['a.m.', 'p.m.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro_MD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro_MD.php new file mode 100644 index 0000000..ad1d2fa --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro_MD.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ro.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY, HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY, HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro_RO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro_RO.php new file mode 100644 index 0000000..102afcd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ro_RO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ro.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rof.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rof.php new file mode 100644 index 0000000..205fc26 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rof.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['kang’ama', 'kingoto'], + 'weekdays' => ['Ijumapili', 'Ijumatatu', 'Ijumanne', 'Ijumatano', 'Alhamisi', 'Ijumaa', 'Ijumamosi'], + 'weekdays_short' => ['Ijp', 'Ijt', 'Ijn', 'Ijtn', 'Alh', 'Iju', 'Ijm'], + 'weekdays_min' => ['Ijp', 'Ijt', 'Ijn', 'Ijtn', 'Alh', 'Iju', 'Ijm'], + 'months' => ['Mweri wa kwanza', 'Mweri wa kaili', 'Mweri wa katatu', 'Mweri wa kaana', 'Mweri wa tanu', 'Mweri wa sita', 'Mweri wa saba', 'Mweri wa nane', 'Mweri wa tisa', 'Mweri wa ikumi', 'Mweri wa ikumi na moja', 'Mweri wa ikumi na mbili'], + 'months_short' => ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru.php new file mode 100644 index 0000000..673b043 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru.php @@ -0,0 +1,191 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Bari Badamshin + * - Jørn Ølmheim + * - François B + * - Tim Fish + * - Коренберг Марк (imac) + * - Serhan Apaydın + * - RomeroMsk + * - vsn4ik + * - JD Isaacks + * - Bari Badamshin + * - Jørn Ølmheim + * - François B + * - Коренберг Марк (imac) + * - Serhan Apaydın + * - RomeroMsk + * - vsn4ik + * - JD Isaacks + * - Fellzo + * - andrey-helldar + * - Pavel Skripkin (psxx) + * - AlexWalkerson + * - Vladislav UnsealedOne + * - dima-bzz + */ + +use Carbon\CarbonInterface; + +$transformDiff = function ($input) { + return strtr($input, [ + 'неделя' => 'неделю', + 'секунда' => 'секунду', + 'минута' => 'минуту', + ]); +}; + +return [ + 'year' => ':count год|:count года|:count лет', + 'y' => ':count г.|:count г.|:count л.', + 'a_year' => '{1}год|:count год|:count года|:count лет', + 'month' => ':count месяц|:count месяца|:count месяцев', + 'm' => ':count мес.', + 'a_month' => '{1}месяц|:count месяц|:count месяца|:count месяцев', + 'week' => ':count неделя|:count недели|:count недель', + 'w' => ':count нед.', + 'a_week' => '{1}неделя|:count неделю|:count недели|:count недель', + 'day' => ':count день|:count дня|:count дней', + 'd' => ':count д.', + 'a_day' => '{1}день|:count день|:count дня|:count дней', + 'hour' => ':count час|:count часа|:count часов', + 'h' => ':count ч.', + 'a_hour' => '{1}час|:count час|:count часа|:count часов', + 'minute' => ':count минута|:count минуты|:count минут', + 'min' => ':count мин.', + 'a_minute' => '{1}минута|:count минута|:count минуты|:count минут', + 'second' => ':count секунда|:count секунды|:count секунд', + 's' => ':count сек.', + 'a_second' => '{1}несколько секунд|:count секунду|:count секунды|:count секунд', + 'ago' => function ($time) use ($transformDiff) { + return $transformDiff($time).' назад'; + }, + 'from_now' => function ($time) use ($transformDiff) { + return 'через '.$transformDiff($time); + }, + 'after' => function ($time) use ($transformDiff) { + return $transformDiff($time).' после'; + }, + 'before' => function ($time) use ($transformDiff) { + return $transformDiff($time).' до'; + }, + 'diff_now' => 'только что', + 'diff_today' => 'Сегодня,', + 'diff_today_regexp' => 'Сегодня,?(?:\\s+в)?', + 'diff_yesterday' => 'вчера', + 'diff_yesterday_regexp' => 'Вчера,?(?:\\s+в)?', + 'diff_tomorrow' => 'завтра', + 'diff_tomorrow_regexp' => 'Завтра,?(?:\\s+в)?', + 'diff_before_yesterday' => 'позавчера', + 'diff_after_tomorrow' => 'послезавтра', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY г.', + 'LLL' => 'D MMMM YYYY г., H:mm', + 'LLLL' => 'dddd, D MMMM YYYY г., H:mm', + ], + 'calendar' => [ + 'sameDay' => '[Сегодня, в] LT', + 'nextDay' => '[Завтра, в] LT', + 'nextWeek' => function (CarbonInterface $current, CarbonInterface $other) { + if ($current->week !== $other->week) { + switch ($current->dayOfWeek) { + case 0: + return '[В следующее] dddd, [в] LT'; + case 1: + case 2: + case 4: + return '[В следующий] dddd, [в] LT'; + case 3: + case 5: + case 6: + return '[В следующую] dddd, [в] LT'; + } + } + + if ($current->dayOfWeek === 2) { + return '[Во] dddd, [в] LT'; + } + + return '[В] dddd, [в] LT'; + }, + 'lastDay' => '[Вчера, в] LT', + 'lastWeek' => function (CarbonInterface $current, CarbonInterface $other) { + if ($current->week !== $other->week) { + switch ($current->dayOfWeek) { + case 0: + return '[В прошлое] dddd, [в] LT'; + case 1: + case 2: + case 4: + return '[В прошлый] dddd, [в] LT'; + case 3: + case 5: + case 6: + return '[В прошлую] dddd, [в] LT'; + } + } + + if ($current->dayOfWeek === 2) { + return '[Во] dddd, [в] LT'; + } + + return '[В] dddd, [в] LT'; + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'M': + case 'd': + case 'DDD': + return $number.'-й'; + case 'D': + return $number.'-го'; + case 'w': + case 'W': + return $number.'-я'; + default: + return $number; + } + }, + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'ночи'; + } + if ($hour < 12) { + return 'утра'; + } + if ($hour < 17) { + return 'дня'; + } + + return 'вечера'; + }, + 'months' => ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'], + 'months_standalone' => ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'], + 'months_short' => ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'months_short_standalone' => ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'months_regexp' => '/(DD?o?\.?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => ['воскресенье', 'понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу'], + 'weekdays_standalone' => ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'], + 'weekdays_short' => ['вск', 'пнд', 'втр', 'срд', 'чтв', 'птн', 'сбт'], + 'weekdays_min' => ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'], + 'weekdays_regexp' => '/\[\s*(В|в)\s*((?:прошлую|следующую|эту)\s*)?\]\s*dddd/', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' и '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_BY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_BY.php new file mode 100644 index 0000000..8ca7df3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_BY.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ru.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_KG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_KG.php new file mode 100644 index 0000000..8ca7df3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_KG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ru.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_KZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_KZ.php new file mode 100644 index 0000000..8ca7df3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_KZ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ru.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_MD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_MD.php new file mode 100644 index 0000000..8ca7df3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_MD.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ru.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_RU.php new file mode 100644 index 0000000..8ca7df3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_RU.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ru.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_UA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_UA.php new file mode 100644 index 0000000..db958d6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ru_UA.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - RFC 2319 bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/ru.php', [ + 'weekdays' => ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'], + 'weekdays_short' => ['вск', 'пнд', 'вто', 'срд', 'чтв', 'птн', 'суб'], + 'weekdays_min' => ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'су'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rw.php new file mode 100644 index 0000000..bc4a347 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rw.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/rw_RW.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rw_RW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rw_RW.php new file mode 100644 index 0000000..9b3e068 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rw_RW.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Rwanda Steve Murphy murf@e-tools.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Mutarama', 'Gashyantare', 'Werurwe', 'Mata', 'Gicuransi', 'Kamena', 'Nyakanga', 'Kanama', 'Nzeli', 'Ukwakira', 'Ugushyingo', 'Ukuboza'], + 'months_short' => ['Mut', 'Gas', 'Wer', 'Mat', 'Gic', 'Kam', 'Nya', 'Kan', 'Nze', 'Ukw', 'Ugu', 'Uku'], + 'weekdays' => ['Ku cyumweru', 'Kuwa mbere', 'Kuwa kabiri', 'Kuwa gatatu', 'Kuwa kane', 'Kuwa gatanu', 'Kuwa gatandatu'], + 'weekdays_short' => ['Mwe', 'Mbe', 'Kab', 'Gtu', 'Kan', 'Gnu', 'Gnd'], + 'weekdays_min' => ['Mwe', 'Mbe', 'Kab', 'Gtu', 'Kan', 'Gnu', 'Gnd'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'second' => ':count vuna', // less reliable + 's' => ':count vuna', // less reliable + 'a_second' => ':count vuna', // less reliable + + 'year' => 'aka :count', + 'y' => 'aka :count', + 'a_year' => 'aka :count', + + 'month' => 'ezi :count', + 'm' => 'ezi :count', + 'a_month' => 'ezi :count', + + 'week' => ':count icyumweru', + 'w' => ':count icyumweru', + 'a_week' => ':count icyumweru', + + 'day' => ':count nsi', + 'd' => ':count nsi', + 'a_day' => ':count nsi', + + 'hour' => 'saha :count', + 'h' => 'saha :count', + 'a_hour' => 'saha :count', + + 'minute' => ':count -nzinya', + 'min' => ':count -nzinya', + 'a_minute' => ':count -nzinya', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rwk.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rwk.php new file mode 100644 index 0000000..ed92e8e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/rwk.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['utuko', 'kyiukonyi'], + 'weekdays' => ['Jumapilyi', 'Jumatatuu', 'Jumanne', 'Jumatanu', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'weekdays_min' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprilyi', 'Mei', 'Junyi', 'Julyai', 'Agusti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sa.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sa.php new file mode 100644 index 0000000..1357c03 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sa.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sa_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sa_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sa_IN.php new file mode 100644 index 0000000..cfda9a6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sa_IN.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - The Debian project Christian Perrier bubulle@debian.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D-MM-YY', + ], + 'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'months_short' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'weekdays' => ['रविवासर:', 'सोमवासर:', 'मंगलवासर:', 'बुधवासर:', 'बृहस्पतिवासरः', 'शुक्रवासर', 'शनिवासर:'], + 'weekdays_short' => ['रविः', 'सोम:', 'मंगल:', 'बुध:', 'बृहस्पतिः', 'शुक्र', 'शनि:'], + 'weekdays_min' => ['रविः', 'सोम:', 'मंगल:', 'बुध:', 'बृहस्पतिः', 'शुक्र', 'शनि:'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], + + 'minute' => ':count होरा', // less reliable + 'min' => ':count होरा', // less reliable + 'a_minute' => ':count होरा', // less reliable + + 'year' => ':count वर्ष', + 'y' => ':count वर्ष', + 'a_year' => ':count वर्ष', + + 'month' => ':count मास', + 'm' => ':count मास', + 'a_month' => ':count मास', + + 'week' => ':count सप्ताहः saptahaĥ', + 'w' => ':count सप्ताहः saptahaĥ', + 'a_week' => ':count सप्ताहः saptahaĥ', + + 'day' => ':count दिन', + 'd' => ':count दिन', + 'a_day' => ':count दिन', + + 'hour' => ':count घण्टा', + 'h' => ':count घण्टा', + 'a_hour' => ':count घण्टा', + + 'second' => ':count द्वितीयः', + 's' => ':count द्वितीयः', + 'a_second' => ':count द्वितीयः', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sah.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sah.php new file mode 100644 index 0000000..b828824 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sah.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sah_RU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sah_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sah_RU.php new file mode 100644 index 0000000..94cc0cb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sah_RU.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Valery Timiriliyev Valery Timiriliyev timiriliyev@gmail.com + */ +return array_replace_recursive(require __DIR__.'/ru.php', [ + 'formats' => [ + 'L' => 'YYYY.MM.DD', + ], + 'months' => ['тохсунньу', 'олунньу', 'кулун тутар', 'муус устар', 'ыам ыйын', 'бэс ыйын', 'от ыйын', 'атырдьах ыйын', 'балаҕан ыйын', 'алтынньы', 'сэтинньи', 'ахсынньы'], + 'months_short' => ['тохс', 'олун', 'кул', 'муус', 'ыам', 'бэс', 'от', 'атыр', 'бал', 'алт', 'сэт', 'ахс'], + 'weekdays' => ['баскыһыанньа', 'бэнидиэнньик', 'оптуорунньук', 'сэрэдэ', 'чэппиэр', 'бээтинсэ', 'субуота'], + 'weekdays_short' => ['бс', 'бн', 'оп', 'ср', 'чп', 'бт', 'сб'], + 'weekdays_min' => ['бс', 'бн', 'оп', 'ср', 'чп', 'бт', 'сб'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/saq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/saq.php new file mode 100644 index 0000000..ff8bf60 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/saq.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Tesiran', 'Teipa'], + 'weekdays' => ['Mderot ee are', 'Mderot ee kuni', 'Mderot ee ong’wan', 'Mderot ee inet', 'Mderot ee ile', 'Mderot ee sapa', 'Mderot ee kwe'], + 'weekdays_short' => ['Are', 'Kun', 'Ong', 'Ine', 'Ile', 'Sap', 'Kwe'], + 'weekdays_min' => ['Are', 'Kun', 'Ong', 'Ine', 'Ile', 'Sap', 'Kwe'], + 'months' => ['Lapa le obo', 'Lapa le waare', 'Lapa le okuni', 'Lapa le ong’wan', 'Lapa le imet', 'Lapa le ile', 'Lapa le sapa', 'Lapa le isiet', 'Lapa le saal', 'Lapa le tomon', 'Lapa le tomon obo', 'Lapa le tomon waare'], + 'months_short' => ['Obo', 'Waa', 'Oku', 'Ong', 'Ime', 'Ile', 'Sap', 'Isi', 'Saa', 'Tom', 'Tob', 'Tow'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sat.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sat.php new file mode 100644 index 0000000..c9914c6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sat.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sat_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sat_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sat_IN.php new file mode 100644 index 0000000..632b1af --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sat_IN.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat Pune libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रेल', 'मई', 'जुन', 'जुलाई', 'अगस्त', 'सितम्बर', 'अखथबर', 'नवम्बर', 'दिसम्बर'], + 'months_short' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रेल', 'मई', 'जुन', 'जुलाई', 'अगस्त', 'सितम्बर', 'अखथबर', 'नवम्बर', 'दिसम्बर'], + 'weekdays' => ['सिंगेमाँहाँ', 'ओतेमाँहाँ', 'बालेमाँहाँ', 'सागुनमाँहाँ', 'सारदीमाँहाँ', 'जारुममाँहाँ', 'ञुहुममाँहाँ'], + 'weekdays_short' => ['सिंगे', 'ओते', 'बाले', 'सागुन', 'सारदी', 'जारुम', 'ञुहुम'], + 'weekdays_min' => ['सिंगे', 'ओते', 'बाले', 'सागुन', 'सारदी', 'जारुम', 'ञुहुम'], + 'day_of_first_week_of_year' => 1, + + 'month' => ':count ńindạ cando', // less reliable + 'm' => ':count ńindạ cando', // less reliable + 'a_month' => ':count ńindạ cando', // less reliable + + 'week' => ':count mãhã', // less reliable + 'w' => ':count mãhã', // less reliable + 'a_week' => ':count mãhã', // less reliable + + 'hour' => ':count ᱥᱳᱱᱚ', // less reliable + 'h' => ':count ᱥᱳᱱᱚ', // less reliable + 'a_hour' => ':count ᱥᱳᱱᱚ', // less reliable + + 'minute' => ':count ᱯᱤᱞᱪᱩ', // less reliable + 'min' => ':count ᱯᱤᱞᱪᱩ', // less reliable + 'a_minute' => ':count ᱯᱤᱞᱪᱩ', // less reliable + + 'second' => ':count ar', // less reliable + 's' => ':count ar', // less reliable + 'a_second' => ':count ar', // less reliable + + 'year' => ':count ne̲s', + 'y' => ':count ne̲s', + 'a_year' => ':count ne̲s', + + 'day' => ':count ᱫᱤᱱ', + 'd' => ':count ᱫᱤᱱ', + 'a_day' => ':count ᱫᱤᱱ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sbp.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sbp.php new file mode 100644 index 0000000..e29ca37 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sbp.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Lwamilawu', 'Pashamihe'], + 'weekdays' => ['Mulungu', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alahamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Mul', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'weekdays_min' => ['Mul', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'months' => ['Mupalangulwa', 'Mwitope', 'Mushende', 'Munyi', 'Mushende Magali', 'Mujimbi', 'Mushipepo', 'Mupuguto', 'Munyense', 'Mokhu', 'Musongandembwe', 'Muhaano'], + 'months_short' => ['Mup', 'Mwi', 'Msh', 'Mun', 'Mag', 'Muj', 'Msp', 'Mpg', 'Mye', 'Mok', 'Mus', 'Muh'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sc.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sc.php new file mode 100644 index 0000000..7178cf4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sc.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sc_IT.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sc_IT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sc_IT.php new file mode 100644 index 0000000..5d1e4ce --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sc_IT.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Sardinian Translators Team Massimeddu Cireddu massimeddu@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD. MM. YY', + ], + 'months' => ['Ghennàrgiu', 'Freàrgiu', 'Martzu', 'Abrile', 'Maju', 'Làmpadas', 'Argiolas//Trìulas', 'Austu', 'Cabudanni', 'Santugaine//Ladàmine', 'Onniasantu//Santandria', 'Nadale//Idas'], + 'months_short' => ['Ghe', 'Fre', 'Mar', 'Abr', 'Maj', 'Làm', 'Arg', 'Aus', 'Cab', 'Lad', 'Onn', 'Nad'], + 'weekdays' => ['Domìnigu', 'Lunis', 'Martis', 'Mèrcuris', 'Giòbia', 'Chenàbura', 'Sàbadu'], + 'weekdays_short' => ['Dom', 'Lun', 'Mar', 'Mèr', 'Giò', 'Che', 'Sàb'], + 'weekdays_min' => ['Dom', 'Lun', 'Mar', 'Mèr', 'Giò', 'Che', 'Sàb'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'minute' => ':count mementu', // less reliable + 'min' => ':count mementu', // less reliable + 'a_minute' => ':count mementu', // less reliable + + 'year' => ':count annu', + 'y' => ':count annu', + 'a_year' => ':count annu', + + 'month' => ':count mese', + 'm' => ':count mese', + 'a_month' => ':count mese', + + 'week' => ':count chida', + 'w' => ':count chida', + 'a_week' => ':count chida', + + 'day' => ':count dí', + 'd' => ':count dí', + 'a_day' => ':count dí', + + 'hour' => ':count ora', + 'h' => ':count ora', + 'a_hour' => ':count ora', + + 'second' => ':count secundu', + 's' => ':count secundu', + 'a_second' => ':count secundu', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd.php new file mode 100644 index 0000000..0022c5a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd.php @@ -0,0 +1,81 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +$months = [ + 'جنوري', + 'فيبروري', + 'مارچ', + 'اپريل', + 'مئي', + 'جون', + 'جولاءِ', + 'آگسٽ', + 'سيپٽمبر', + 'آڪٽوبر', + 'نومبر', + 'ڊسمبر', +]; + +$weekdays = [ + 'آچر', + 'سومر', + 'اڱارو', + 'اربع', + 'خميس', + 'جمع', + 'ڇنڇر', +]; + +/* + * Authors: + * - Narain Sagar + * - Sawood Alam + * - Narain Sagar + */ +return [ + 'year' => '{1}'.'هڪ سال'.'|:count '.'سال', + 'month' => '{1}'.'هڪ مهينو'.'|:count '.'مهينا', + 'week' => '{1}'.'ھڪ ھفتو'.'|:count '.'هفتا', + 'day' => '{1}'.'هڪ ڏينهن'.'|:count '.'ڏينهن', + 'hour' => '{1}'.'هڪ ڪلاڪ'.'|:count '.'ڪلاڪ', + 'minute' => '{1}'.'هڪ منٽ'.'|:count '.'منٽ', + 'second' => '{1}'.'چند سيڪنڊ'.'|:count '.'سيڪنڊ', + 'ago' => ':time اڳ', + 'from_now' => ':time پوء', + 'diff_yesterday' => 'ڪالهه', + 'diff_today' => 'اڄ', + 'diff_tomorrow' => 'سڀاڻي', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd، D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[اڄ] LT', + 'nextDay' => '[سڀاڻي] LT', + 'nextWeek' => 'dddd [اڳين هفتي تي] LT', + 'lastDay' => '[ڪالهه] LT', + 'lastWeek' => '[گزريل هفتي] dddd [تي] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['صبح', 'شام'], + 'months' => $months, + 'months_short' => $months, + 'weekdays' => $weekdays, + 'weekdays_short' => $weekdays, + 'weekdays_min' => $weekdays, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => ['، ', ' ۽ '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd_IN.php new file mode 100644 index 0000000..de1dad0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd_IN.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat, Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/sd.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['جنوري', 'فبروري', 'مارچ', 'اپريل', 'مي', 'جون', 'جولاءِ', 'آگسٽ', 'سيپٽيمبر', 'آڪٽوبر', 'نومبر', 'ڊسمبر'], + 'months_short' => ['جنوري', 'فبروري', 'مارچ', 'اپريل', 'مي', 'جون', 'جولاءِ', 'آگسٽ', 'سيپٽيمبر', 'آڪٽوبر', 'نومبر', 'ڊسمبر'], + 'weekdays' => ['آرتوارُ', 'سومرُ', 'منگلُ', 'ٻُڌرُ', 'وسپت', 'جُمو', 'ڇنڇر'], + 'weekdays_short' => ['آرتوارُ', 'سومرُ', 'منگلُ', 'ٻُڌرُ', 'وسپت', 'جُمو', 'ڇنڇر'], + 'weekdays_min' => ['آرتوارُ', 'سومرُ', 'منگلُ', 'ٻُڌرُ', 'وسپت', 'جُمو', 'ڇنڇر'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd_IN@devanagari.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd_IN@devanagari.php new file mode 100644 index 0000000..061fcc1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sd_IN@devanagari.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat, Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/sd.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['जनवरी', 'फबरवरी', 'मार्चि', 'अप्रेल', 'मे', 'जूनि', 'जूलाइ', 'आगस्टु', 'सेप्टेंबरू', 'आक्टूबरू', 'नवंबरू', 'ॾिसंबरू'], + 'months_short' => ['जनवरी', 'फबरवरी', 'मार्चि', 'अप्रेल', 'मे', 'जूनि', 'जूलाइ', 'आगस्टु', 'सेप्टेंबरू', 'आक्टूबरू', 'नवंबरू', 'ॾिसंबरू'], + 'weekdays' => ['आर्तवारू', 'सूमरू', 'मंगलू', 'ॿुधरू', 'विस्पति', 'जुमो', 'छंछस'], + 'weekdays_short' => ['आर्तवारू', 'सूमरू', 'मंगलू', 'ॿुधरू', 'विस्पति', 'जुमो', 'छंछस'], + 'weekdays_min' => ['आर्तवारू', 'सूमरू', 'मंगलू', 'ॿुधरू', 'विस्पति', 'जुमो', 'छंछस'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['म.पू.', 'म.नं.'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se.php new file mode 100644 index 0000000..7c4b92a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se.php @@ -0,0 +1,73 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Karamell + */ +return [ + 'year' => '{1}:count jahki|:count jagit', + 'a_year' => '{1}okta jahki|:count jagit', + 'y' => ':count j.', + 'month' => '{1}:count mánnu|:count mánut', + 'a_month' => '{1}okta mánnu|:count mánut', + 'm' => ':count mán.', + 'week' => '{1}:count vahkku|:count vahkku', + 'a_week' => '{1}okta vahkku|:count vahkku', + 'w' => ':count v.', + 'day' => '{1}:count beaivi|:count beaivvit', + 'a_day' => '{1}okta beaivi|:count beaivvit', + 'd' => ':count b.', + 'hour' => '{1}:count diimmu|:count diimmut', + 'a_hour' => '{1}okta diimmu|:count diimmut', + 'h' => ':count d.', + 'minute' => '{1}:count minuhta|:count minuhtat', + 'a_minute' => '{1}okta minuhta|:count minuhtat', + 'min' => ':count min.', + 'second' => '{1}:count sekunddat|:count sekunddat', + 'a_second' => '{1}moadde sekunddat|:count sekunddat', + 's' => ':count s.', + 'ago' => 'maŋit :time', + 'from_now' => ':time geažes', + 'diff_yesterday' => 'ikte', + 'diff_yesterday_regexp' => 'ikte(?:\\s+ti)?', + 'diff_today' => 'otne', + 'diff_today_regexp' => 'otne(?:\\s+ti)?', + 'diff_tomorrow' => 'ihttin', + 'diff_tomorrow_regexp' => 'ihttin(?:\\s+ti)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'MMMM D. [b.] YYYY', + 'LLL' => 'MMMM D. [b.] YYYY [ti.] HH:mm', + 'LLLL' => 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[otne ti] LT', + 'nextDay' => '[ihttin ti] LT', + 'nextWeek' => 'dddd [ti] LT', + 'lastDay' => '[ikte ti] LT', + 'lastWeek' => '[ovddit] dddd [ti] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['ođđajagemánnu', 'guovvamánnu', 'njukčamánnu', 'cuoŋománnu', 'miessemánnu', 'geassemánnu', 'suoidnemánnu', 'borgemánnu', 'čakčamánnu', 'golggotmánnu', 'skábmamánnu', 'juovlamánnu'], + 'months_short' => ['ođđj', 'guov', 'njuk', 'cuo', 'mies', 'geas', 'suoi', 'borg', 'čakč', 'golg', 'skáb', 'juov'], + 'weekdays' => ['sotnabeaivi', 'vuossárga', 'maŋŋebárga', 'gaskavahkku', 'duorastat', 'bearjadat', 'lávvardat'], + 'weekdays_short' => ['sotn', 'vuos', 'maŋ', 'gask', 'duor', 'bear', 'láv'], + 'weekdays_min' => ['s', 'v', 'm', 'g', 'd', 'b', 'L'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' ja '], + 'meridiem' => ['i.b.', 'e.b.'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_FI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_FI.php new file mode 100644 index 0000000..cf01805 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_FI.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/se.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'months' => ['ođđajagemánnu', 'guovvamánnu', 'njukčamánnu', 'cuoŋománnu', 'miessemánnu', 'geassemánnu', 'suoidnemánnu', 'borgemánnu', 'čakčamánnu', 'golggotmánnu', 'skábmamánnu', 'juovlamánnu'], + 'months_short' => ['ođđj', 'guov', 'njuk', 'cuoŋ', 'mies', 'geas', 'suoi', 'borg', 'čakč', 'golg', 'skáb', 'juov'], + 'weekdays' => ['sotnabeaivi', 'mánnodat', 'disdat', 'gaskavahkku', 'duorastat', 'bearjadat', 'lávvordat'], + 'weekdays_short' => ['so', 'má', 'di', 'ga', 'du', 'be', 'lá'], + 'weekdays_min' => ['so', 'má', 'di', 'ga', 'du', 'be', 'lá'], + 'meridiem' => ['i', 'e'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_NO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_NO.php new file mode 100644 index 0000000..177c7e9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_NO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/se.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_SE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_SE.php new file mode 100644 index 0000000..177c7e9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/se_SE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/se.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/seh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/seh.php new file mode 100644 index 0000000..babf9af --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/seh.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['Dimingu', 'Chiposi', 'Chipiri', 'Chitatu', 'Chinai', 'Chishanu', 'Sabudu'], + 'weekdays_short' => ['Dim', 'Pos', 'Pir', 'Tat', 'Nai', 'Sha', 'Sab'], + 'weekdays_min' => ['Dim', 'Pos', 'Pir', 'Tat', 'Nai', 'Sha', 'Sab'], + 'months' => ['Janeiro', 'Fevreiro', 'Marco', 'Abril', 'Maio', 'Junho', 'Julho', 'Augusto', 'Setembro', 'Otubro', 'Novembro', 'Decembro'], + 'months_short' => ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Aug', 'Set', 'Otu', 'Nov', 'Dec'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'd [de] MMM [de] YYYY', + 'LLL' => 'd [de] MMMM [de] YYYY HH:mm', + 'LLLL' => 'dddd, d [de] MMMM [de] YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ses.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ses.php new file mode 100644 index 0000000..e1099e6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ses.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Adduha', 'Aluula'], + 'weekdays' => ['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamiisa', 'Alzuma', 'Asibti'], + 'weekdays_short' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'], + 'weekdays_min' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'], + 'months' => ['Žanwiye', 'Feewiriye', 'Marsi', 'Awiril', 'Me', 'Žuweŋ', 'Žuyye', 'Ut', 'Sektanbur', 'Oktoobur', 'Noowanbur', 'Deesanbur'], + 'months_short' => ['Žan', 'Fee', 'Mar', 'Awi', 'Me', 'Žuw', 'Žuy', 'Ut', 'Sek', 'Okt', 'Noo', 'Dee'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'month' => ':count alaada', // less reliable + 'm' => ':count alaada', // less reliable + 'a_month' => ':count alaada', // less reliable + + 'hour' => ':count ɲaajin', // less reliable + 'h' => ':count ɲaajin', // less reliable + 'a_hour' => ':count ɲaajin', // less reliable + + 'minute' => ':count zarbu', // less reliable + 'min' => ':count zarbu', // less reliable + 'a_minute' => ':count zarbu', // less reliable + + 'year' => ':count jiiri', + 'y' => ':count jiiri', + 'a_year' => ':count jiiri', + + 'week' => ':count jirbiiyye', + 'w' => ':count jirbiiyye', + 'a_week' => ':count jirbiiyye', + + 'day' => ':count zaari', + 'd' => ':count zaari', + 'a_day' => ':count zaari', + + 'second' => ':count ihinkante', + 's' => ':count ihinkante', + 'a_second' => ':count ihinkante', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sg.php new file mode 100644 index 0000000..9264e89 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sg.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['ND', 'LK'], + 'weekdays' => ['Bikua-ôko', 'Bïkua-ûse', 'Bïkua-ptâ', 'Bïkua-usïö', 'Bïkua-okü', 'Lâpôsö', 'Lâyenga'], + 'weekdays_short' => ['Bk1', 'Bk2', 'Bk3', 'Bk4', 'Bk5', 'Lâp', 'Lây'], + 'weekdays_min' => ['Bk1', 'Bk2', 'Bk3', 'Bk4', 'Bk5', 'Lâp', 'Lây'], + 'months' => ['Nyenye', 'Fulundïgi', 'Mbängü', 'Ngubùe', 'Bêläwü', 'Föndo', 'Lengua', 'Kükürü', 'Mvuka', 'Ngberere', 'Nabändüru', 'Kakauka'], + 'months_short' => ['Nye', 'Ful', 'Mbä', 'Ngu', 'Bêl', 'Fön', 'Len', 'Kük', 'Mvu', 'Ngb', 'Nab', 'Kak'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'year' => ':count dā', // less reliable + 'y' => ':count dā', // less reliable + 'a_year' => ':count dā', // less reliable + + 'week' => ':count bïkua-okü', // less reliable + 'w' => ':count bïkua-okü', // less reliable + 'a_week' => ':count bïkua-okü', // less reliable + + 'day' => ':count ziggawâ', // less reliable + 'd' => ':count ziggawâ', // less reliable + 'a_day' => ':count ziggawâ', // less reliable + + 'hour' => ':count yângâködörö', // less reliable + 'h' => ':count yângâködörö', // less reliable + 'a_hour' => ':count yângâködörö', // less reliable + + 'second' => ':count bïkua-ôko', // less reliable + 's' => ':count bïkua-ôko', // less reliable + 'a_second' => ':count bïkua-ôko', // less reliable + + 'month' => ':count Nze tî ngu', + 'm' => ':count Nze tî ngu', + 'a_month' => ':count Nze tî ngu', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sgs.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sgs.php new file mode 100644 index 0000000..864b989 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sgs.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sgs_LT.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sgs_LT.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sgs_LT.php new file mode 100644 index 0000000..aa9e942 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sgs_LT.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Arnas Udovičius bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY.MM.DD', + ], + 'months' => ['sausė', 'vasarė', 'kuova', 'balondė', 'gegožės', 'bėrželė', 'lëpas', 'rogpjūtė', 'siejės', 'spalė', 'lapkrėstė', 'grůdė'], + 'months_short' => ['Sau', 'Vas', 'Kuo', 'Bal', 'Geg', 'Bėr', 'Lëp', 'Rgp', 'Sie', 'Spa', 'Lap', 'Grd'], + 'weekdays' => ['nedielės dëna', 'panedielis', 'oterninks', 'sereda', 'četvergs', 'petnīčė', 'sobata'], + 'weekdays_short' => ['Nd', 'Pn', 'Ot', 'Sr', 'Čt', 'Pt', 'Sb'], + 'weekdays_min' => ['Nd', 'Pn', 'Ot', 'Sr', 'Čt', 'Pt', 'Sb'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'minute' => ':count mažos', // less reliable + 'min' => ':count mažos', // less reliable + 'a_minute' => ':count mažos', // less reliable + + 'year' => ':count metā', + 'y' => ':count metā', + 'a_year' => ':count metā', + + 'month' => ':count mienou', + 'm' => ':count mienou', + 'a_month' => ':count mienou', + + 'week' => ':count nedielė', + 'w' => ':count nedielė', + 'a_week' => ':count nedielė', + + 'day' => ':count dīna', + 'd' => ':count dīna', + 'a_day' => ':count dīna', + + 'hour' => ':count adīna', + 'h' => ':count adīna', + 'a_hour' => ':count adīna', + + 'second' => ':count Sekondė', + 's' => ':count Sekondė', + 'a_second' => ':count Sekondė', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sh.php new file mode 100644 index 0000000..e03b506 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sh.php @@ -0,0 +1,68 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +// @codeCoverageIgnoreStart +use Symfony\Component\Translation\PluralizationRules; + +if (class_exists('Symfony\\Component\\Translation\\PluralizationRules')) { + PluralizationRules::set(static function ($number) { + return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); + }, 'sh'); +} +// @codeCoverageIgnoreEnd + +/* + * Authors: + * - Томица Кораћ + * - Enrique Vidal + * - Christopher Dell + * - dmilisic + * - danijel + * - Miroslav Matkovic (mikki021) + */ +return [ + 'diff_now' => 'sada', + 'diff_yesterday' => 'juče', + 'diff_tomorrow' => 'sutra', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'MMMM D, YYYY', + 'LLL' => 'DD MMM HH:mm', + 'LLLL' => 'MMMM DD, YYYY HH:mm', + ], + 'year' => ':count godina|:count godine|:count godina', + 'y' => ':count g.', + 'month' => ':count mesec|:count meseca|:count meseci', + 'm' => ':count m.', + 'week' => ':count nedelja|:count nedelje|:count nedelja', + 'w' => ':count n.', + 'day' => ':count dan|:count dana|:count dana', + 'd' => ':count d.', + 'hour' => ':count sat|:count sata|:count sati', + 'h' => ':count č.', + 'minute' => ':count minut|:count minuta|:count minuta', + 'min' => ':count min.', + 'second' => ':count sekund|:count sekunde|:count sekundi', + 's' => ':count s.', + 'ago' => 'pre :time', + 'from_now' => 'za :time', + 'after' => 'nakon :time', + 'before' => ':time raniјe', + 'weekdays' => ['Nedelja', 'Ponedeljak', 'Utorak', 'Sreda', 'Četvrtak', 'Petak', 'Subota'], + 'weekdays_short' => ['Ned', 'Pon', 'Uto', 'Sre', 'Čet', 'Pet', 'Sub'], + 'weekdays_min' => ['Ned', 'Pon', 'Uto', 'Sre', 'Čet', 'Pet', 'Sub'], + 'months' => ['Januar', 'Februar', 'Mart', 'April', 'Maj', 'Jun', 'Jul', 'Avgust', 'Septembar', 'Oktobar', 'Novembar', 'Decembar'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Avg', 'Sep', 'Okt', 'Nov', 'Dec'], + 'list' => [', ', ' i '], + 'meridiem' => ['pre podne', 'po podne'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi.php new file mode 100644 index 0000000..7815186 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['ⵜⵉⴼⴰⵡⵜ', 'ⵜⴰⴷⴳⴳⵯⴰⵜ'], + 'weekdays' => ['ⴰⵙⴰⵎⴰⵙ', 'ⴰⵢⵏⴰⵙ', 'ⴰⵙⵉⵏⴰⵙ', 'ⴰⴽⵕⴰⵙ', 'ⴰⴽⵡⴰⵙ', 'ⵙⵉⵎⵡⴰⵙ', 'ⴰⵙⵉⴹⵢⴰⵙ'], + 'weekdays_short' => ['ⴰⵙⴰ', 'ⴰⵢⵏ', 'ⴰⵙⵉ', 'ⴰⴽⵕ', 'ⴰⴽⵡ', 'ⴰⵙⵉⵎ', 'ⴰⵙⵉⴹ'], + 'weekdays_min' => ['ⴰⵙⴰ', 'ⴰⵢⵏ', 'ⴰⵙⵉ', 'ⴰⴽⵕ', 'ⴰⴽⵡ', 'ⴰⵙⵉⵎ', 'ⴰⵙⵉⴹ'], + 'months' => ['ⵉⵏⵏⴰⵢⵔ', 'ⴱⵕⴰⵢⵕ', 'ⵎⴰⵕⵚ', 'ⵉⴱⵔⵉⵔ', 'ⵎⴰⵢⵢⵓ', 'ⵢⵓⵏⵢⵓ', 'ⵢⵓⵍⵢⵓⵣ', 'ⵖⵓⵛⵜ', 'ⵛⵓⵜⴰⵏⴱⵉⵔ', 'ⴽⵜⵓⴱⵔ', 'ⵏⵓⵡⴰⵏⴱⵉⵔ', 'ⴷⵓⵊⴰⵏⴱⵉⵔ'], + 'months_short' => ['ⵉⵏⵏ', 'ⴱⵕⴰ', 'ⵎⴰⵕ', 'ⵉⴱⵔ', 'ⵎⴰⵢ', 'ⵢⵓⵏ', 'ⵢⵓⵍ', 'ⵖⵓⵛ', 'ⵛⵓⵜ', 'ⴽⵜⵓ', 'ⵏⵓⵡ', 'ⴷⵓⵊ'], + 'first_day_of_week' => 6, + 'weekend' => [5, 6], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'year' => ':count aseggwas', + 'y' => ':count aseggwas', + 'a_year' => ':count aseggwas', + + 'month' => ':count ayyur', + 'm' => ':count ayyur', + 'a_month' => ':count ayyur', + + 'week' => ':count imalass', + 'w' => ':count imalass', + 'a_week' => ':count imalass', + + 'day' => ':count ass', + 'd' => ':count ass', + 'a_day' => ':count ass', + + 'hour' => ':count urɣ', // less reliable + 'h' => ':count urɣ', // less reliable + 'a_hour' => ':count urɣ', // less reliable + + 'minute' => ':count ⴰⵎⵥⵉ', // less reliable + 'min' => ':count ⴰⵎⵥⵉ', // less reliable + 'a_minute' => ':count ⴰⵎⵥⵉ', // less reliable + + 'second' => ':count sin', // less reliable + 's' => ':count sin', // less reliable + 'a_second' => ':count sin', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi_Latn.php new file mode 100644 index 0000000..cddfb24 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi_Latn.php @@ -0,0 +1,33 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/shi.php', [ + 'meridiem' => ['tifawt', 'tadggʷat'], + 'weekdays' => ['asamas', 'aynas', 'asinas', 'akṛas', 'akwas', 'asimwas', 'asiḍyas'], + 'weekdays_short' => ['asa', 'ayn', 'asi', 'akṛ', 'akw', 'asim', 'asiḍ'], + 'weekdays_min' => ['asa', 'ayn', 'asi', 'akṛ', 'akw', 'asim', 'asiḍ'], + 'months' => ['innayr', 'bṛayṛ', 'maṛṣ', 'ibrir', 'mayyu', 'yunyu', 'yulyuz', 'ɣuct', 'cutanbir', 'ktubr', 'nuwanbir', 'dujanbir'], + 'months_short' => ['inn', 'bṛa', 'maṛ', 'ibr', 'may', 'yun', 'yul', 'ɣuc', 'cut', 'ktu', 'nuw', 'duj'], + 'first_day_of_week' => 6, + 'weekend' => [5, 6], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + + 'minute' => ':count agur', // less reliable + 'min' => ':count agur', // less reliable + 'a_minute' => ':count agur', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi_Tfng.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi_Tfng.php new file mode 100644 index 0000000..f3df1f2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shi_Tfng.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/shi.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shn.php new file mode 100644 index 0000000..fe7b1ea --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shn.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/shn_MM.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shn_MM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shn_MM.php new file mode 100644 index 0000000..f399acf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shn_MM.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - ubuntu Myanmar LoCo Team https://ubuntu-mm.net Bone Pyae Sone bone.burma@mail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'OY MMM OD dddd', + ], + 'months' => ['လိူၼ်ၵမ်', 'လိူၼ်သၢမ်', 'လိူၼ်သီ', 'လိူၼ်ႁႃႈ', 'လိူၼ်ႁူၵ်း', 'လိူၼ်ၸဵတ်း', 'လိူၼ်ပႅတ်ႇ', 'လိူၼ်ၵဝ်ႈ', 'လိူၼ်သိပ်း', 'လိူၼ်သိပ်းဢိတ်း', 'လိူၼ်သိပ်းဢိတ်းသွင်', 'လိူၼ်ၸဵင်'], + 'months_short' => ['လိူၼ်ၵမ်', 'လိူၼ်သၢမ်', 'လိူၼ်သီ', 'လိူၼ်ႁႃႈ', 'လိူၼ်ႁူၵ်း', 'လိူၼ်ၸဵတ်း', 'လိူၼ်ပႅတ်ႇ', 'လိူၼ်ၵဝ်ႈ', 'လိူၼ်သိပ်း', 'လိူၼ်သိပ်းဢိတ်း', 'လိူၼ်သိပ်းဢိတ်းသွင်', 'လိူၼ်ၸဵင်'], + 'weekdays' => ['ဝၼ်းဢႃးတိတ်ႉ', 'ဝၼ်းၸၼ်', 'ဝၼ်း​ဢၢင်း​ၵၢၼ်း', 'ဝၼ်းပူတ်ႉ', 'ဝၼ်းၽတ်း', 'ဝၼ်းသုၵ်း', 'ဝၼ်းသဝ်'], + 'weekdays_short' => ['တိတ့်', 'ၸၼ်', 'ၵၢၼ်း', 'ပုတ့်', 'ၽတ်း', 'သုၵ်း', 'သဝ်'], + 'weekdays_min' => ['တိတ့်', 'ၸၼ်', 'ၵၢၼ်း', 'ပုတ့်', 'ၽတ်း', 'သုၵ်း', 'သဝ်'], + 'alt_numbers' => ['႐႐', '႐႑', '႐႒', '႐႓', '႐႔', '႐႕', '႐႖', '႐႗', '႐႘', '႐႙', '႑႐', '႑႑', '႑႒', '႑႓', '႑႔', '႑႕', '႑႖', '႑႗', '႑႘', '႑႙', '႒႐', '႒႑', '႒႒', '႒႓', '႒႔', '႒႕', '႒႖', '႒႗', '႒႘', '႒႙', '႓႐', '႓႑', '႓႒', '႓႓', '႓႔', '႓႕', '႓႖', '႓႗', '႓႘', '႓႙', '႔႐', '႔႑', '႔႒', '႔႓', '႔႔', '႔႕', '႔႖', '႔႗', '႔႘', '႔႙', '႕႐', '႕႑', '႕႒', '႕႓', '႕႔', '႕႕', '႕႖', '႕႗', '႕႘', '႕႙', '႖႐', '႖႑', '႖႒', '႖႓', '႖႔', '႖႕', '႖႖', '႖႗', '႖႘', '႖႙', '႗႐', '႗႑', '႗႒', '႗႓', '႗႔', '႗႕', '႗႖', '႗႗', '႗႘', '႗႙', '႘႐', '႘႑', '႘႒', '႘႓', '႘႔', '႘႕', '႘႖', '႘႗', '႘႘', '႘႙', '႙႐', '႙႑', '႙႒', '႙႓', '႙႔', '႙႕', '႙႖', '႙႗', '႙႘', '႙႙'], + 'meridiem' => ['ၵၢင်ၼႂ်', 'တၢမ်းၶမ်ႈ'], + + 'month' => ':count လိူၼ်', // less reliable + 'm' => ':count လိူၼ်', // less reliable + 'a_month' => ':count လိူၼ်', // less reliable + + 'week' => ':count ဝၼ်း', // less reliable + 'w' => ':count ဝၼ်း', // less reliable + 'a_week' => ':count ဝၼ်း', // less reliable + + 'hour' => ':count ຕີ', // less reliable + 'h' => ':count ຕີ', // less reliable + 'a_hour' => ':count ຕີ', // less reliable + + 'minute' => ':count ເດັກ', // less reliable + 'min' => ':count ເດັກ', // less reliable + 'a_minute' => ':count ເດັກ', // less reliable + + 'second' => ':count ဢိုၼ်ႇ', // less reliable + 's' => ':count ဢိုၼ်ႇ', // less reliable + 'a_second' => ':count ဢိုၼ်ႇ', // less reliable + + 'year' => ':count ပီ', + 'y' => ':count ပီ', + 'a_year' => ':count ပီ', + + 'day' => ':count ກາງວັນ', + 'd' => ':count ກາງວັນ', + 'a_day' => ':count ກາງວັນ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shs.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shs.php new file mode 100644 index 0000000..8d2e1d7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shs.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/shs_CA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shs_CA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shs_CA.php new file mode 100644 index 0000000..08d385e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/shs_CA.php @@ -0,0 +1,38 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Neskie Manuel bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Pellkwet̓min', 'Pelctsipwen̓ten', 'Pellsqépts', 'Peslléwten', 'Pell7ell7é7llqten', 'Pelltspéntsk', 'Pelltqwelq̓wél̓t', 'Pellct̓éxel̓cten', 'Pesqelqlélten', 'Pesllwélsten', 'Pellc7ell7é7llcwten̓', 'Pelltetétq̓em'], + 'months_short' => ['Kwe', 'Tsi', 'Sqe', 'Éwt', 'Ell', 'Tsp', 'Tqw', 'Ct̓é', 'Qel', 'Wél', 'U7l', 'Tet'], + 'weekdays' => ['Sxetspesq̓t', 'Spetkesq̓t', 'Selesq̓t', 'Skellesq̓t', 'Smesesq̓t', 'Stselkstesq̓t', 'Stqmekstesq̓t'], + 'weekdays_short' => ['Sxe', 'Spe', 'Sel', 'Ske', 'Sme', 'Sts', 'Stq'], + 'weekdays_min' => ['Sxe', 'Spe', 'Sel', 'Ske', 'Sme', 'Sts', 'Stq'], + 'day_of_first_week_of_year' => 1, + + 'year' => ':count sqlélten', // less reliable + 'y' => ':count sqlélten', // less reliable + 'a_year' => ':count sqlélten', // less reliable + + 'month' => ':count swewll', // less reliable + 'm' => ':count swewll', // less reliable + 'a_month' => ':count swewll', // less reliable + + 'hour' => ':count seqwlút', // less reliable + 'h' => ':count seqwlút', // less reliable + 'a_hour' => ':count seqwlút', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/si.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/si.php new file mode 100644 index 0000000..636bf69 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/si.php @@ -0,0 +1,78 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Serhan Apaydın + * - JD Isaacks + * - Malinda Weerasinghe (MalindaWMD) + */ +return [ + 'year' => '{1}වසර 1|වසර :count', + 'a_year' => '{1}වසරක්|වසර :count', + 'month' => '{1}මාස 1|මාස :count', + 'a_month' => '{1}මාසය|මාස :count', + 'week' => '{1}සති 1|සති :count', + 'a_week' => '{1}සතියක්|සති :count', + 'day' => '{1}දින 1|දින :count', + 'a_day' => '{1}දිනක්|දින :count', + 'hour' => '{1}පැය 1|පැය :count', + 'a_hour' => '{1}පැයක්|පැය :count', + 'minute' => '{1}මිනිත්තු 1|මිනිත්තු :count', + 'a_minute' => '{1}මිනිත්තුවක්|මිනිත්තු :count', + 'second' => '{1}තත්පර 1|තත්පර :count', + 'a_second' => '{1}තත්පර කිහිපයකට|තත්පර :count', + 'ago' => ':time කට පෙර', + 'from_now' => function ($time) { + if (preg_match('/දින \d/u', $time)) { + return $time.' න්'; + } + + return $time.' කින්'; + }, + 'before' => ':time කට පෙර', + 'after' => function ($time) { + if (preg_match('/දින \d/u', $time)) { + return $time.' න්'; + } + + return $time.' කින්'; + }, + 'diff_now' => 'දැන්', + 'diff_today' => 'අද', + 'diff_yesterday' => 'ඊයේ', + 'diff_tomorrow' => 'හෙට', + 'formats' => [ + 'LT' => 'a h:mm', + 'LTS' => 'a h:mm:ss', + 'L' => 'YYYY/MM/DD', + 'LL' => 'YYYY MMMM D', + 'LLL' => 'YYYY MMMM D, a h:mm', + 'LLLL' => 'YYYY MMMM D [වැනි] dddd, a h:mm:ss', + ], + 'calendar' => [ + 'sameDay' => '[අද] LT[ට]', + 'nextDay' => '[හෙට] LT[ට]', + 'nextWeek' => 'dddd LT[ට]', + 'lastDay' => '[ඊයේ] LT[ට]', + 'lastWeek' => '[පසුගිය] dddd LT[ට]', + 'sameElse' => 'L', + ], + 'ordinal' => ':number වැනි', + 'meridiem' => ['පෙර වරු', 'පස් වරු', 'පෙ.ව.', 'ප.ව.'], + 'months' => ['ජනවාරි', 'පෙබරවාරි', 'මාර්තු', 'අප්‍රේල්', 'මැයි', 'ජූනි', 'ජූලි', 'අගෝස්තු', 'සැප්තැම්බර්', 'ඔක්තෝබර්', 'නොවැම්බර්', 'දෙසැම්බර්'], + 'months_short' => ['ජන', 'පෙබ', 'මාර්', 'අප්', 'මැයි', 'ජූනි', 'ජූලි', 'අගෝ', 'සැප්', 'ඔක්', 'නොවැ', 'දෙසැ'], + 'weekdays' => ['ඉරිදා', 'සඳුදා', 'අඟහරුවාදා', 'බදාදා', 'බ්‍රහස්පතින්දා', 'සිකුරාදා', 'සෙනසුරාදා'], + 'weekdays_short' => ['ඉරි', 'සඳු', 'අඟ', 'බදා', 'බ්‍රහ', 'සිකු', 'සෙන'], + 'weekdays_min' => ['ඉ', 'ස', 'අ', 'බ', 'බ්‍ර', 'සි', 'සෙ'], + 'first_day_of_week' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/si_LK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/si_LK.php new file mode 100644 index 0000000..81c44e0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/si_LK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/si.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sid.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sid.php new file mode 100644 index 0000000..b1c6521 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sid.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sid_ET.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sid_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sid_ET.php new file mode 100644 index 0000000..1296f9b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sid_ET.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + 'weekdays' => ['Sambata', 'Sanyo', 'Maakisanyo', 'Roowe', 'Hamuse', 'Arbe', 'Qidaame'], + 'weekdays_short' => ['Sam', 'San', 'Mak', 'Row', 'Ham', 'Arb', 'Qid'], + 'weekdays_min' => ['Sam', 'San', 'Mak', 'Row', 'Ham', 'Arb', 'Qid'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['soodo', 'hawwaro'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sk.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sk.php new file mode 100644 index 0000000..f9702e9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sk.php @@ -0,0 +1,155 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Martin Suja + * - Tsutomu Kuroda + * - tjku + * - Max Melentiev + * - Juanito Fatas + * - Ivan Stana + * - Akira Matsuda + * - Christopher Dell + * - James McKinney + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Jozef Fulop + * - Nicolás Hock Isaza + * - Tom Hughes + * - Simon Hürlimann (CyT) + * - jofi + * - Jakub ADAMEC + * - Marek Adamický + * - AlterwebStudio + */ + +use Carbon\CarbonInterface; + +$fromNow = function ($time) { + return 'o '.strtr($time, [ + 'hodina' => 'hodinu', + 'minúta' => 'minútu', + 'sekunda' => 'sekundu', + ]); +}; + +$ago = function ($time) { + $replacements = [ + '/\bhodina\b/' => 'hodinou', + '/\bminúta\b/' => 'minútou', + '/\bsekunda\b/' => 'sekundou', + '/\bdeň\b/u' => 'dňom', + '/\btýždeň\b/u' => 'týždňom', + '/\bmesiac\b/' => 'mesiacom', + '/\brok\b/' => 'rokom', + ]; + + $replacementsPlural = [ + '/\bhodiny\b/' => 'hodinami', + '/\bminúty\b/' => 'minútami', + '/\bsekundy\b/' => 'sekundami', + '/\bdni\b/' => 'dňami', + '/\btýždne\b/' => 'týždňami', + '/\bmesiace\b/' => 'mesiacmi', + '/\broky\b/' => 'rokmi', + ]; + + foreach ($replacements + $replacementsPlural as $pattern => $replacement) { + $time = preg_replace($pattern, $replacement, $time); + } + + return "pred $time"; +}; + +return [ + 'year' => ':count rok|:count roky|:count rokov', + 'a_year' => 'rok|:count roky|:count rokov', + 'y' => ':count r', + 'month' => ':count mesiac|:count mesiace|:count mesiacov', + 'a_month' => 'mesiac|:count mesiace|:count mesiacov', + 'm' => ':count m', + 'week' => ':count týždeň|:count týždne|:count týždňov', + 'a_week' => 'týždeň|:count týždne|:count týždňov', + 'w' => ':count t', + 'day' => ':count deň|:count dni|:count dní', + 'a_day' => 'deň|:count dni|:count dní', + 'd' => ':count d', + 'hour' => ':count hodina|:count hodiny|:count hodín', + 'a_hour' => 'hodina|:count hodiny|:count hodín', + 'h' => ':count h', + 'minute' => ':count minúta|:count minúty|:count minút', + 'a_minute' => 'minúta|:count minúty|:count minút', + 'min' => ':count min', + 'second' => ':count sekunda|:count sekundy|:count sekúnd', + 'a_second' => 'sekunda|:count sekundy|:count sekúnd', + 's' => ':count s', + 'millisecond' => ':count milisekunda|:count milisekundy|:count milisekúnd', + 'a_millisecond' => 'milisekunda|:count milisekundy|:count milisekúnd', + 'ms' => ':count ms', + 'microsecond' => ':count mikrosekunda|:count mikrosekundy|:count mikrosekúnd', + 'a_microsecond' => 'mikrosekunda|:count mikrosekundy|:count mikrosekúnd', + 'µs' => ':count µs', + + 'ago' => $ago, + 'from_now' => $fromNow, + 'before' => ':time pred', + 'after' => ':time po', + + 'hour_after' => ':count hodinu|:count hodiny|:count hodín', + 'minute_after' => ':count minútu|:count minúty|:count minút', + 'second_after' => ':count sekundu|:count sekundy|:count sekúnd', + + 'hour_before' => ':count hodinu|:count hodiny|:count hodín', + 'minute_before' => ':count minútu|:count minúty|:count minút', + 'second_before' => ':count sekundu|:count sekundy|:count sekúnd', + + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' a '], + 'diff_now' => 'teraz', + 'diff_yesterday' => 'včera', + 'diff_tomorrow' => 'zajtra', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'DD. MMMM YYYY', + 'LLL' => 'D. M. HH:mm', + 'LLLL' => 'dddd D. MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[dnes o] LT', + 'nextDay' => '[zajtra o] LT', + 'lastDay' => '[včera o] LT', + 'nextWeek' => 'dddd [o] LT', + 'lastWeek' => static function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 1: + case 2: + case 4: + case 5: + return '[minulý] dddd [o] LT'; //pondelok/utorok/štvrtok/piatok + default: + return '[minulá] dddd [o] LT'; + } + }, + 'sameElse' => 'L', + ], + 'weekdays' => ['nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota'], + 'weekdays_short' => ['ned', 'pon', 'uto', 'str', 'štv', 'pia', 'sob'], + 'weekdays_min' => ['ne', 'po', 'ut', 'st', 'št', 'pi', 'so'], + 'months' => ['január', 'február', 'marec', 'apríl', 'máj', 'jún', 'júl', 'august', 'september', 'október', 'november', 'december'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'meridiem' => ['dopoludnia', 'popoludní'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sk_SK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sk_SK.php new file mode 100644 index 0000000..0515601 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sk_SK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sk.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sl.php new file mode 100644 index 0000000..1f1d1b3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sl.php @@ -0,0 +1,129 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Tsutomu Kuroda + * - tjku + * - Max Melentiev + * - Juanito Fatas + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Nicolás Hock Isaza + * - Miha Rebernik + * - Gal Jakič (morpheus7CS) + * - Glavić + * - Anže Časar + * - Lovro Tramšek (Lovro1107) + * - burut13 + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count leto|:count leti|:count leta|:count let', + 'y' => ':count leto|:count leti|:count leta|:count let', + 'month' => ':count mesec|:count meseca|:count mesece|:count mesecev', + 'm' => ':count mes.', + 'week' => ':count teden|:count tedna|:count tedne|:count tednov', + 'w' => ':count ted.', + 'day' => ':count dan|:count dni|:count dni|:count dni', + 'd' => ':count dan|:count dni|:count dni|:count dni', + 'hour' => ':count ura|:count uri|:count ure|:count ur', + 'h' => ':count h', + 'minute' => ':count minuta|:count minuti|:count minute|:count minut', + 'min' => ':count min.', + 'second' => ':count sekunda|:count sekundi|:count sekunde|:count sekund', + 'a_second' => '{1}nekaj sekund|:count sekunda|:count sekundi|:count sekunde|:count sekund', + 's' => ':count s', + + 'year_ago' => ':count letom|:count letoma|:count leti|:count leti', + 'y_ago' => ':count letom|:count letoma|:count leti|:count leti', + 'month_ago' => ':count mesecem|:count mesecema|:count meseci|:count meseci', + 'week_ago' => ':count tednom|:count tednoma|:count tedni|:count tedni', + 'day_ago' => ':count dnem|:count dnevoma|:count dnevi|:count dnevi', + 'd_ago' => ':count dnem|:count dnevoma|:count dnevi|:count dnevi', + 'hour_ago' => ':count uro|:count urama|:count urami|:count urami', + 'minute_ago' => ':count minuto|:count minutama|:count minutami|:count minutami', + 'second_ago' => ':count sekundo|:count sekundama|:count sekundami|:count sekundami', + + 'day_from_now' => ':count dan|:count dneva|:count dni|:count dni', + 'd_from_now' => ':count dan|:count dneva|:count dni|:count dni', + 'hour_from_now' => ':count uro|:count uri|:count ure|:count ur', + 'minute_from_now' => ':count minuto|:count minuti|:count minute|:count minut', + 'second_from_now' => ':count sekundo|:count sekundi|:count sekunde|:count sekund', + + 'ago' => 'pred :time', + 'from_now' => 'čez :time', + 'after' => ':time kasneje', + 'before' => ':time prej', + + 'diff_now' => 'ravnokar', + 'diff_today' => 'danes', + 'diff_today_regexp' => 'danes(?:\\s+ob)?', + 'diff_yesterday' => 'včeraj', + 'diff_yesterday_regexp' => 'včeraj(?:\\s+ob)?', + 'diff_tomorrow' => 'jutri', + 'diff_tomorrow_regexp' => 'jutri(?:\\s+ob)?', + 'diff_before_yesterday' => 'predvčerajšnjim', + 'diff_after_tomorrow' => 'pojutrišnjem', + + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'period_start_date' => 'od :date', + 'period_end_date' => 'do :date', + + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY H:mm', + 'LLLL' => 'dddd, D. MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[danes ob] LT', + 'nextDay' => '[jutri ob] LT', + 'nextWeek' => 'dddd [ob] LT', + 'lastDay' => '[včeraj ob] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[preteklo] [nedeljo] [ob] LT'; + case 1: + return '[pretekli] [ponedeljek] [ob] LT'; + case 2: + return '[pretekli] [torek] [ob] LT'; + case 3: + return '[preteklo] [sredo] [ob] LT'; + case 4: + return '[pretekli] [četrtek] [ob] LT'; + case 5: + return '[pretekli] [petek] [ob] LT'; + case 6: + return '[preteklo] [soboto] [ob] LT'; + } + }, + 'sameElse' => 'L', + ], + 'months' => ['januar', 'februar', 'marec', 'april', 'maj', 'junij', 'julij', 'avgust', 'september', 'oktober', 'november', 'december'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'avg', 'sep', 'okt', 'nov', 'dec'], + 'weekdays' => ['nedelja', 'ponedeljek', 'torek', 'sreda', 'četrtek', 'petek', 'sobota'], + 'weekdays_short' => ['ned', 'pon', 'tor', 'sre', 'čet', 'pet', 'sob'], + 'weekdays_min' => ['ne', 'po', 'to', 'sr', 'če', 'pe', 'so'], + 'list' => [', ', ' in '], + 'meridiem' => ['dopoldan', 'popoldan'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sl_SI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sl_SI.php new file mode 100644 index 0000000..5dad8c8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sl_SI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sm.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sm.php new file mode 100644 index 0000000..e8c118a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sm.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/sm_WS.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sm_WS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sm_WS.php new file mode 100644 index 0000000..f066068 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sm_WS.php @@ -0,0 +1,53 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Samsung Electronics Co., Ltd. akhilesh.k@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Ianuari', 'Fepuari', 'Mati', 'Aperila', 'Me', 'Iuni', 'Iulai', 'Auguso', 'Setema', 'Oketopa', 'Novema', 'Tesema'], + 'months_short' => ['Ian', 'Fep', 'Mat', 'Ape', 'Me', 'Iun', 'Iul', 'Aug', 'Set', 'Oke', 'Nov', 'Tes'], + 'weekdays' => ['Aso Sa', 'Aso Gafua', 'Aso Lua', 'Aso Lulu', 'Aso Tofi', 'Aso Farail', 'Aso To\'ana\'i'], + 'weekdays_short' => ['Aso Sa', 'Aso Gaf', 'Aso Lua', 'Aso Lul', 'Aso Tof', 'Aso Far', 'Aso To\''], + 'weekdays_min' => ['Aso Sa', 'Aso Gaf', 'Aso Lua', 'Aso Lul', 'Aso Tof', 'Aso Far', 'Aso To\''], + + 'hour' => ':count uati', // less reliable + 'h' => ':count uati', // less reliable + 'a_hour' => ':count uati', // less reliable + + 'minute' => ':count itiiti', // less reliable + 'min' => ':count itiiti', // less reliable + 'a_minute' => ':count itiiti', // less reliable + + 'second' => ':count lua', // less reliable + 's' => ':count lua', // less reliable + 'a_second' => ':count lua', // less reliable + + 'year' => ':count tausaga', + 'y' => ':count tausaga', + 'a_year' => ':count tausaga', + + 'month' => ':count māsina', + 'm' => ':count māsina', + 'a_month' => ':count māsina', + + 'week' => ':count vaiaso', + 'w' => ':count vaiaso', + 'a_week' => ':count vaiaso', + + 'day' => ':count aso', + 'd' => ':count aso', + 'a_day' => ':count aso', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/smn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/smn.php new file mode 100644 index 0000000..20add02 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/smn.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['ip.', 'ep.'], + 'weekdays' => ['pasepeeivi', 'vuossaargâ', 'majebaargâ', 'koskoho', 'tuorâstuv', 'vástuppeeivi', 'lávurduv'], + 'weekdays_short' => ['pas', 'vuo', 'maj', 'kos', 'tuo', 'vás', 'láv'], + 'weekdays_min' => ['pa', 'vu', 'ma', 'ko', 'tu', 'vá', 'lá'], + 'weekdays_standalone' => ['pasepeivi', 'vuossargâ', 'majebargâ', 'koskokko', 'tuorâstâh', 'vástuppeivi', 'lávurdâh'], + 'months' => ['uđđâivemáánu', 'kuovâmáánu', 'njuhčâmáánu', 'cuáŋuimáánu', 'vyesimáánu', 'kesimáánu', 'syeinimáánu', 'porgemáánu', 'čohčâmáánu', 'roovvâdmáánu', 'skammâmáánu', 'juovlâmáánu'], + 'months_short' => ['uđiv', 'kuovâ', 'njuhčâ', 'cuáŋui', 'vyesi', 'kesi', 'syeini', 'porge', 'čohčâ', 'roovvâd', 'skammâ', 'juovlâ'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'H.mm', + 'LTS' => 'H.mm.ss', + 'L' => 'D.M.YYYY', + 'LL' => 'MMM D. YYYY', + 'LLL' => 'MMMM D. YYYY H.mm', + 'LLLL' => 'dddd, MMMM D. YYYY H.mm', + ], + + 'hour' => ':count äigi', // less reliable + 'h' => ':count äigi', // less reliable + 'a_hour' => ':count äigi', // less reliable + + 'year' => ':count ihe', + 'y' => ':count ihe', + 'a_year' => ':count ihe', + + 'month' => ':count mánuppaje', + 'm' => ':count mánuppaje', + 'a_month' => ':count mánuppaje', + + 'week' => ':count okko', + 'w' => ':count okko', + 'a_week' => ':count okko', + + 'day' => ':count peivi', + 'd' => ':count peivi', + 'a_day' => ':count peivi', + + 'minute' => ':count miinut', + 'min' => ':count miinut', + 'a_minute' => ':count miinut', + + 'second' => ':count nubbe', + 's' => ':count nubbe', + 'a_second' => ':count nubbe', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sn.php new file mode 100644 index 0000000..4f25028 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sn.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['a', 'p'], + 'weekdays' => ['Svondo', 'Muvhuro', 'Chipiri', 'Chitatu', 'China', 'Chishanu', 'Mugovera'], + 'weekdays_short' => ['Svo', 'Muv', 'Chp', 'Cht', 'Chn', 'Chs', 'Mug'], + 'weekdays_min' => ['Sv', 'Mu', 'Cp', 'Ct', 'Cn', 'Cs', 'Mg'], + 'months' => ['Ndira', 'Kukadzi', 'Kurume', 'Kubvumbi', 'Chivabvu', 'Chikumi', 'Chikunguru', 'Nyamavhuvhu', 'Gunyana', 'Gumiguru', 'Mbudzi', 'Zvita'], + 'months_short' => ['Ndi', 'Kuk', 'Kur', 'Kub', 'Chv', 'Chk', 'Chg', 'Nya', 'Gun', 'Gum', 'Mbu', 'Zvi'], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'YYYY MMMM D, dddd HH:mm', + ], + + 'year' => 'makore :count', + 'y' => 'makore :count', + 'a_year' => 'makore :count', + + 'month' => 'mwedzi :count', + 'm' => 'mwedzi :count', + 'a_month' => 'mwedzi :count', + + 'week' => 'vhiki :count', + 'w' => 'vhiki :count', + 'a_week' => 'vhiki :count', + + 'day' => 'mazuva :count', + 'd' => 'mazuva :count', + 'a_day' => 'mazuva :count', + + 'hour' => 'maawa :count', + 'h' => 'maawa :count', + 'a_hour' => 'maawa :count', + + 'minute' => 'minitsi :count', + 'min' => 'minitsi :count', + 'a_minute' => 'minitsi :count', + + 'second' => 'sekonzi :count', + 's' => 'sekonzi :count', + 'a_second' => 'sekonzi :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so.php new file mode 100644 index 0000000..5785271 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so.php @@ -0,0 +1,74 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Author: + * - Abdifatah Abdilahi(@abdifatahz) + */ +return [ + 'year' => ':count sanad|:count sanadood', + 'a_year' => 'sanad|:count sanadood', + 'y' => '{1}:countsn|{0}:countsns|]1,Inf[:countsn', + 'month' => ':count bil|:count bilood', + 'a_month' => 'bil|:count bilood', + 'm' => ':countbil', + 'week' => ':count isbuuc', + 'a_week' => 'isbuuc|:count isbuuc', + 'w' => ':countis', + 'day' => ':count maalin|:count maalmood', + 'a_day' => 'maalin|:count maalmood', + 'd' => ':countml', + 'hour' => ':count saac', + 'a_hour' => 'saacad|:count saac', + 'h' => ':countsc', + 'minute' => ':count daqiiqo', + 'a_minute' => 'daqiiqo|:count daqiiqo', + 'min' => ':countdq', + 'second' => ':count ilbidhiqsi', + 'a_second' => 'xooga ilbidhiqsiyo|:count ilbidhiqsi', + 's' => ':countil', + 'ago' => ':time kahor', + 'from_now' => ':time gudahood', + 'after' => ':time kedib', + 'before' => ':time kahor', + 'diff_now' => 'hada', + 'diff_today' => 'maanta', + 'diff_today_regexp' => 'maanta(?:\s+markay\s+(?:tahay|ahayd))?', + 'diff_yesterday' => 'shalayto', + 'diff_yesterday_regexp' => 'shalayto(?:\s+markay\s+ahayd)?', + 'diff_tomorrow' => 'beri', + 'diff_tomorrow_regexp' => 'beri(?:\s+markay\s+tahay)?', + 'diff_before_yesterday' => 'doraato', + 'diff_after_tomorrow' => 'saadanbe', + 'period_recurrences' => 'mar|:count jeer', + 'period_interval' => ':interval kasta', + 'period_start_date' => 'laga bilaabo :date', + 'period_end_date' => 'ilaa :date', + 'months' => ['Janaayo', 'Febraayo', 'Abriil', 'Maajo', 'Juun', 'Luuliyo', 'Agoosto', 'Sebteembar', 'Oktoobar', 'Nofeembar', 'Diseembar'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Abr', 'Mjo', 'Jun', 'Lyo', 'Agt', 'Seb', 'Okt', 'Nof', 'Dis'], + 'weekdays' => ['Axad', 'Isniin', 'Talaada', 'Arbaca', 'Khamiis', 'Jimce', 'Sabti'], + 'weekdays_short' => ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sbt'], + 'weekdays_min' => ['Ax', 'Is', 'Ta', 'Ar', 'Kh', 'Ji', 'Sa'], + 'list' => [', ', ' and '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'calendar' => [ + 'sameDay' => '[Maanta markay tahay] LT', + 'nextDay' => '[Beri markay tahay] LT', + 'nextWeek' => 'dddd [markay tahay] LT', + 'lastDay' => '[Shalay markay ahayd] LT', + 'lastWeek' => '[Hore] dddd [Markay ahayd] LT', + 'sameElse' => 'L', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_DJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_DJ.php new file mode 100644 index 0000000..273dda8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_DJ.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/so.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_ET.php new file mode 100644 index 0000000..7b69971 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_ET.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return require __DIR__.'/so.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_KE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_KE.php new file mode 100644 index 0000000..7b69971 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_KE.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return require __DIR__.'/so.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_SO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_SO.php new file mode 100644 index 0000000..7b69971 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/so_SO.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return require __DIR__.'/so.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq.php new file mode 100644 index 0000000..ffa592e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq.php @@ -0,0 +1,79 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - JD Isaacks + * - Fadion Dashi + */ +return [ + 'year' => ':count vit|:count vjet', + 'a_year' => 'një vit|:count vite', + 'y' => ':count v.', + 'month' => ':count muaj', + 'a_month' => 'një muaj|:count muaj', + 'm' => ':count muaj', + 'week' => ':count javë', + 'a_week' => ':count javë|:count javë', + 'w' => ':count j.', + 'day' => ':count ditë', + 'a_day' => 'një ditë|:count ditë', + 'd' => ':count d.', + 'hour' => ':count orë', + 'a_hour' => 'një orë|:count orë', + 'h' => ':count o.', + 'minute' => ':count minutë|:count minuta', + 'a_minute' => 'një minutë|:count minuta', + 'min' => ':count min.', + 'second' => ':count sekondë|:count sekonda', + 'a_second' => 'disa sekonda|:count sekonda', + 's' => ':count s.', + 'ago' => ':time më parë', + 'from_now' => 'në :time', + 'after' => ':time pas', + 'before' => ':time para', + 'diff_now' => 'tani', + 'diff_today' => 'Sot', + 'diff_today_regexp' => 'Sot(?:\\s+në)?', + 'diff_yesterday' => 'dje', + 'diff_yesterday_regexp' => 'Dje(?:\\s+në)?', + 'diff_tomorrow' => 'nesër', + 'diff_tomorrow_regexp' => 'Nesër(?:\\s+në)?', + 'diff_before_yesterday' => 'pardje', + 'diff_after_tomorrow' => 'pasnesër', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Sot në] LT', + 'nextDay' => '[Nesër në] LT', + 'nextWeek' => 'dddd [në] LT', + 'lastDay' => '[Dje në] LT', + 'lastWeek' => 'dddd [e kaluar në] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'meridiem' => ['PD', 'MD'], + 'months' => ['janar', 'shkurt', 'mars', 'prill', 'maj', 'qershor', 'korrik', 'gusht', 'shtator', 'tetor', 'nëntor', 'dhjetor'], + 'months_short' => ['jan', 'shk', 'mar', 'pri', 'maj', 'qer', 'kor', 'gus', 'sht', 'tet', 'nën', 'dhj'], + 'weekdays' => ['e diel', 'e hënë', 'e martë', 'e mërkurë', 'e enjte', 'e premte', 'e shtunë'], + 'weekdays_short' => ['die', 'hën', 'mar', 'mër', 'enj', 'pre', 'sht'], + 'weekdays_min' => ['d', 'h', 'ma', 'më', 'e', 'p', 'sh'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' dhe '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_AL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_AL.php new file mode 100644 index 0000000..ea5df3f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_AL.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sq.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_MK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_MK.php new file mode 100644 index 0000000..62f752c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_MK.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/sq.php', [ + 'formats' => [ + 'L' => 'D.M.YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY, HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY, HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_XK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_XK.php new file mode 100644 index 0000000..62f752c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sq_XK.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/sq.php', [ + 'formats' => [ + 'L' => 'D.M.YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY, HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY, HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr.php new file mode 100644 index 0000000..68ba663 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr.php @@ -0,0 +1,112 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - shaishavgandhi05 + * - Serhan Apaydın + * - JD Isaacks + * - Glavić + * - Milos Sakovic + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count godina|:count godine|:count godina', + 'y' => ':count g.', + 'month' => ':count mesec|:count meseca|:count meseci', + 'm' => ':count mj.', + 'week' => ':count nedelja|:count nedelje|:count nedelja', + 'w' => ':count ned.', + 'day' => ':count dan|:count dana|:count dana', + 'd' => ':count d.', + 'hour' => ':count sat|:count sata|:count sati', + 'h' => ':count č.', + 'minute' => ':count minut|:count minuta|:count minuta', + 'min' => ':count min.', + 'second' => ':count sekundu|:count sekunde|:count sekundi', + 's' => ':count sek.', + 'ago' => 'pre :time', + 'from_now' => 'za :time', + 'after' => 'nakon :time', + 'before' => 'pre :time', + + 'year_from_now' => ':count godinu|:count godine|:count godina', + 'year_ago' => ':count godinu|:count godine|:count godina', + 'week_from_now' => ':count nedelju|:count nedelje|:count nedelja', + 'week_ago' => ':count nedelju|:count nedelje|:count nedelja', + + 'diff_now' => 'upravo sada', + 'diff_today' => 'danas', + 'diff_today_regexp' => 'danas(?:\\s+u)?', + 'diff_yesterday' => 'juče', + 'diff_yesterday_regexp' => 'juče(?:\\s+u)?', + 'diff_tomorrow' => 'sutra', + 'diff_tomorrow_regexp' => 'sutra(?:\\s+u)?', + 'diff_before_yesterday' => 'prekjuče', + 'diff_after_tomorrow' => 'preksutra', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY H:mm', + 'LLLL' => 'dddd, D. MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[danas u] LT', + 'nextDay' => '[sutra u] LT', + 'nextWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[u nedelju u] LT'; + case 3: + return '[u sredu u] LT'; + case 6: + return '[u subotu u] LT'; + default: + return '[u] dddd [u] LT'; + } + }, + 'lastDay' => '[juče u] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[prošle nedelje u] LT'; + case 1: + return '[prošlog ponedeljka u] LT'; + case 2: + return '[prošlog utorka u] LT'; + case 3: + return '[prošle srede u] LT'; + case 4: + return '[prošlog četvrtka u] LT'; + case 5: + return '[prošlog petka u] LT'; + default: + return '[prošle subote u] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'], + 'months_short' => ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun', 'jul', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'], + 'weekdays' => ['nedelja', 'ponedeljak', 'utorak', 'sreda', 'četvrtak', 'petak', 'subota'], + 'weekdays_short' => ['ned.', 'pon.', 'uto.', 'sre.', 'čet.', 'pet.', 'sub.'], + 'weekdays_min' => ['ne', 'po', 'ut', 'sr', 'če', 'pe', 'su'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' i '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php new file mode 100644 index 0000000..8becbc5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php @@ -0,0 +1,112 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - shaishavgandhi05 + * - Serhan Apaydın + * - JD Isaacks + * - Glavić + * - Nikola Zeravcic + * - Milos Sakovic + */ + +use Carbon\CarbonInterface; + +return [ + 'year' => ':count година|:count године|:count година', + 'y' => ':count г.', + 'month' => ':count месец|:count месеца|:count месеци', + 'm' => ':count м.', + 'week' => ':count недеља|:count недеље|:count недеља', + 'w' => ':count нед.', + 'day' => ':count дан|:count дана|:count дана', + 'd' => ':count д.', + 'hour' => ':count сат|:count сата|:count сати', + 'h' => ':count ч.', + 'minute' => ':count минут|:count минута|:count минута', + 'min' => ':count мин.', + 'second' => ':count секунд|:count секунде|:count секунди', + 's' => ':count сек.', + 'ago' => 'пре :time', + 'from_now' => 'за :time', + 'after' => ':time након', + 'before' => ':time пре', + 'year_from_now' => ':count годину|:count године|:count година', + 'year_ago' => ':count годину|:count године|:count година', + 'week_from_now' => ':count недељу|:count недеље|:count недеља', + 'week_ago' => ':count недељу|:count недеље|:count недеља', + 'diff_now' => 'управо сада', + 'diff_today' => 'данас', + 'diff_today_regexp' => 'данас(?:\\s+у)?', + 'diff_yesterday' => 'јуче', + 'diff_yesterday_regexp' => 'јуче(?:\\s+у)?', + 'diff_tomorrow' => 'сутра', + 'diff_tomorrow_regexp' => 'сутра(?:\\s+у)?', + 'diff_before_yesterday' => 'прекјуче', + 'diff_after_tomorrow' => 'прекосутра', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY H:mm', + 'LLLL' => 'dddd, D. MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[данас у] LT', + 'nextDay' => '[сутра у] LT', + 'nextWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[у недељу у] LT'; + case 3: + return '[у среду у] LT'; + case 6: + return '[у суботу у] LT'; + default: + return '[у] dddd [у] LT'; + } + }, + 'lastDay' => '[јуче у] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[прошле недеље у] LT'; + case 1: + return '[прошлог понедељка у] LT'; + case 2: + return '[прошлог уторка у] LT'; + case 3: + return '[прошле среде у] LT'; + case 4: + return '[прошлог четвртка у] LT'; + case 5: + return '[прошлог петка у] LT'; + default: + return '[прошле суботе у] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['јануар', 'фебруар', 'март', 'април', 'мај', 'јун', 'јул', 'август', 'септембар', 'октобар', 'новембар', 'децембар'], + 'months_short' => ['јан.', 'феб.', 'мар.', 'апр.', 'мај', 'јун', 'јул', 'авг.', 'сеп.', 'окт.', 'нов.', 'дец.'], + 'weekdays' => ['недеља', 'понедељак', 'уторак', 'среда', 'четвртак', 'петак', 'субота'], + 'weekdays_short' => ['нед.', 'пон.', 'уто.', 'сре.', 'чет.', 'пет.', 'суб.'], + 'weekdays_min' => ['не', 'по', 'ут', 'ср', 'че', 'пе', 'су'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' и '], + 'meridiem' => ['АМ', 'ПМ'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php new file mode 100644 index 0000000..4b29a45 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php @@ -0,0 +1,33 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Cyrl_BA'); +} +// @codeCoverageIgnoreEnd + +return array_replace_recursive(require __DIR__.'/sr_Cyrl.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D.M.yy.', + 'LL' => 'DD.MM.YYYY.', + 'LLL' => 'DD. MMMM YYYY. HH:mm', + 'LLLL' => 'dddd, DD. MMMM YYYY. HH:mm', + ], + 'weekdays' => ['недјеља', 'понедељак', 'уторак', 'сриједа', 'четвртак', 'петак', 'субота'], + 'weekdays_short' => ['нед.', 'пон.', 'ут.', 'ср.', 'чет.', 'пет.', 'суб.'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php new file mode 100644 index 0000000..28d22fd --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php @@ -0,0 +1,118 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Glavić + * - Milos Sakovic + */ + +use Carbon\CarbonInterface; +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Cyrl_ME'); +} +// @codeCoverageIgnoreEnd + +return [ + 'year' => ':count година|:count године|:count година', + 'y' => ':count г.', + 'month' => ':count мјесец|:count мјесеца|:count мјесеци', + 'm' => ':count мј.', + 'week' => ':count недјеља|:count недјеље|:count недјеља', + 'w' => ':count нед.', + 'day' => ':count дан|:count дана|:count дана', + 'd' => ':count д.', + 'hour' => ':count сат|:count сата|:count сати', + 'h' => ':count ч.', + 'minute' => ':count минут|:count минута|:count минута', + 'min' => ':count мин.', + 'second' => ':count секунд|:count секунде|:count секунди', + 's' => ':count сек.', + 'ago' => 'прије :time', + 'from_now' => 'за :time', + 'after' => ':time након', + 'before' => ':time прије', + + 'year_from_now' => ':count годину|:count године|:count година', + 'year_ago' => ':count годину|:count године|:count година', + + 'week_from_now' => ':count недјељу|:count недјеље|:count недјеља', + 'week_ago' => ':count недјељу|:count недјеље|:count недјеља', + + 'diff_now' => 'управо сада', + 'diff_today' => 'данас', + 'diff_today_regexp' => 'данас(?:\\s+у)?', + 'diff_yesterday' => 'јуче', + 'diff_yesterday_regexp' => 'јуче(?:\\s+у)?', + 'diff_tomorrow' => 'сутра', + 'diff_tomorrow_regexp' => 'сутра(?:\\s+у)?', + 'diff_before_yesterday' => 'прекјуче', + 'diff_after_tomorrow' => 'прекосјутра', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM YYYY', + 'LLL' => 'D. MMMM YYYY H:mm', + 'LLLL' => 'dddd, D. MMMM YYYY H:mm', + ], + 'calendar' => [ + 'sameDay' => '[данас у] LT', + 'nextDay' => '[сутра у] LT', + 'nextWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[у недељу у] LT'; + case 3: + return '[у среду у] LT'; + case 6: + return '[у суботу у] LT'; + default: + return '[у] dddd [у] LT'; + } + }, + 'lastDay' => '[јуче у] LT', + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[прошле недеље у] LT'; + case 1: + return '[прошлог понедељка у] LT'; + case 2: + return '[прошлог уторка у] LT'; + case 3: + return '[прошле среде у] LT'; + case 4: + return '[прошлог четвртка у] LT'; + case 5: + return '[прошлог петка у] LT'; + default: + return '[прошле суботе у] LT'; + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['јануар', 'фебруар', 'март', 'април', 'мај', 'јун', 'јул', 'август', 'септембар', 'октобар', 'новембар', 'децембар'], + 'months_short' => ['јан.', 'феб.', 'мар.', 'апр.', 'мај', 'јун', 'јул', 'авг.', 'сеп.', 'окт.', 'нов.', 'дец.'], + 'weekdays' => ['недеља', 'понедељак', 'уторак', 'среда', 'четвртак', 'петак', 'субота'], + 'weekdays_short' => ['нед.', 'пон.', 'уто.', 'сре.', 'чет.', 'пет.', 'суб.'], + 'weekdays_min' => ['не', 'по', 'ут', 'ср', 'че', 'пе', 'су'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' и '], + 'meridiem' => ['АМ', 'ПМ'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php new file mode 100644 index 0000000..d6e29b8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Cyrl_XK'); +} +// @codeCoverageIgnoreEnd + +return array_replace_recursive(require __DIR__.'/sr_Cyrl_BA.php', [ + 'weekdays' => ['недеља', 'понедељак', 'уторак', 'среда', 'четвртак', 'петак', 'субота'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn.php new file mode 100644 index 0000000..9971674 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php new file mode 100644 index 0000000..95b2770 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php @@ -0,0 +1,33 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Latn_BA'); +} +// @codeCoverageIgnoreEnd + +return array_replace_recursive(require __DIR__.'/sr_Latn.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D.M.yy.', + 'LL' => 'DD.MM.YYYY.', + 'LLL' => 'DD. MMMM YYYY. HH:mm', + 'LLLL' => 'dddd, DD. MMMM YYYY. HH:mm', + ], + 'weekdays' => ['nedjelja', 'ponedeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'], + 'weekdays_short' => ['ned.', 'pon.', 'ut.', 'sr.', 'čet.', 'pet.', 'sub.'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php new file mode 100644 index 0000000..5b8f2d0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Glavić + * - Milos Sakovic + */ + +use Carbon\CarbonInterface; +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Latn_ME'); +} +// @codeCoverageIgnoreEnd + +return array_replace_recursive(require __DIR__.'/sr.php', [ + 'month' => ':count mjesec|:count mjeseca|:count mjeseci', + 'week' => ':count nedjelja|:count nedjelje|:count nedjelja', + 'second' => ':count sekund|:count sekunde|:count sekundi', + 'ago' => 'prije :time', + 'from_now' => 'za :time', + 'after' => ':time nakon', + 'before' => ':time prije', + 'week_from_now' => ':count nedjelju|:count nedjelje|:count nedjelja', + 'week_ago' => ':count nedjelju|:count nedjelje|:count nedjelja', + 'second_ago' => ':count sekund|:count sekunde|:count sekundi', + 'diff_tomorrow' => 'sjutra', + 'calendar' => [ + 'nextDay' => '[sjutra u] LT', + 'nextWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[u nedjelju u] LT'; + case 3: + return '[u srijedu u] LT'; + case 6: + return '[u subotu u] LT'; + default: + return '[u] dddd [u] LT'; + } + }, + 'lastWeek' => function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 0: + return '[prošle nedjelje u] LT'; + case 1: + return '[prošle nedjelje u] LT'; + case 2: + return '[prošlog utorka u] LT'; + case 3: + return '[prošle srijede u] LT'; + case 4: + return '[prošlog četvrtka u] LT'; + case 5: + return '[prošlog petka u] LT'; + default: + return '[prošle subote u] LT'; + } + }, + ], + 'weekdays' => ['nedjelja', 'ponedjeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'], + 'weekdays_short' => ['ned.', 'pon.', 'uto.', 'sri.', 'čet.', 'pet.', 'sub.'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php new file mode 100644 index 0000000..5278e2e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Latn_XK'); +} +// @codeCoverageIgnoreEnd + +return array_replace_recursive(require __DIR__.'/sr_Latn_BA.php', [ + 'weekdays' => ['nedelja', 'ponedeljak', 'utorak', 'sreda', 'četvrtak', 'petak', 'subota'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_ME.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_ME.php new file mode 100644 index 0000000..d7c65b9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_ME.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sr_Latn_ME.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_RS.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_RS.php new file mode 100644 index 0000000..bc5e04b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_RS.php @@ -0,0 +1,16 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - sr_YU, sr_CS locale Danilo Segan bug-glibc-locales@gnu.org + */ +return require __DIR__.'/sr_Cyrl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_RS@latin.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_RS@latin.php new file mode 100644 index 0000000..9971674 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sr_RS@latin.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ss.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ss.php new file mode 100644 index 0000000..1c52c9b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ss.php @@ -0,0 +1,78 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Nicolai Davies + */ +return [ + 'year' => '{1}umnyaka|:count iminyaka', + 'month' => '{1}inyanga|:count tinyanga', + 'week' => '{1}:count liviki|:count emaviki', + 'day' => '{1}lilanga|:count emalanga', + 'hour' => '{1}lihora|:count emahora', + 'minute' => '{1}umzuzu|:count emizuzu', + 'second' => '{1}emizuzwana lomcane|:count mzuzwana', + 'ago' => 'wenteka nga :time', + 'from_now' => 'nga :time', + 'diff_yesterday' => 'Itolo', + 'diff_yesterday_regexp' => 'Itolo(?:\\s+nga)?', + 'diff_today' => 'Namuhla', + 'diff_today_regexp' => 'Namuhla(?:\\s+nga)?', + 'diff_tomorrow' => 'Kusasa', + 'diff_tomorrow_regexp' => 'Kusasa(?:\\s+nga)?', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm A', + 'LLLL' => 'dddd, D MMMM YYYY h:mm A', + ], + 'calendar' => [ + 'sameDay' => '[Namuhla nga] LT', + 'nextDay' => '[Kusasa nga] LT', + 'nextWeek' => 'dddd [nga] LT', + 'lastDay' => '[Itolo nga] LT', + 'lastWeek' => 'dddd [leliphelile] [nga] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + $lastDigit = $number % 10; + + return $number.( + ((int) ($number % 100 / 10) === 1) ? 'e' : ( + ($lastDigit === 1 || $lastDigit === 2) ? 'a' : 'e' + ) + ); + }, + 'meridiem' => function ($hour) { + if ($hour < 11) { + return 'ekuseni'; + } + if ($hour < 15) { + return 'emini'; + } + if ($hour < 19) { + return 'entsambama'; + } + + return 'ebusuku'; + }, + 'months' => ['Bhimbidvwane', 'Indlovana', 'Indlov\'lenkhulu', 'Mabasa', 'Inkhwekhweti', 'Inhlaba', 'Kholwane', 'Ingci', 'Inyoni', 'Imphala', 'Lweti', 'Ingongoni'], + 'months_short' => ['Bhi', 'Ina', 'Inu', 'Mab', 'Ink', 'Inh', 'Kho', 'Igc', 'Iny', 'Imp', 'Lwe', 'Igo'], + 'weekdays' => ['Lisontfo', 'Umsombuluko', 'Lesibili', 'Lesitsatfu', 'Lesine', 'Lesihlanu', 'Umgcibelo'], + 'weekdays_short' => ['Lis', 'Umb', 'Lsb', 'Les', 'Lsi', 'Lsh', 'Umg'], + 'weekdays_min' => ['Li', 'Us', 'Lb', 'Lt', 'Ls', 'Lh', 'Ug'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ss_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ss_ZA.php new file mode 100644 index 0000000..ba89527 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ss_ZA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/ss.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/st.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/st.php new file mode 100644 index 0000000..b065445 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/st.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/st_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/st_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/st_ZA.php new file mode 100644 index 0000000..5bce7f2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/st_ZA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Pherekgong', 'Hlakola', 'Tlhakubele', 'Mmese', 'Motsheanong', 'Phupjane', 'Phupu', 'Phato', 'Leotse', 'Mphalane', 'Pudungwana', 'Tshitwe'], + 'months_short' => ['Phe', 'Hla', 'TlH', 'Mme', 'Mot', 'Jan', 'Upu', 'Pha', 'Leo', 'Mph', 'Pud', 'Tsh'], + 'weekdays' => ['Sontaha', 'Mantaha', 'Labobedi', 'Laboraro', 'Labone', 'Labohlano', 'Moqebelo'], + 'weekdays_short' => ['Son', 'Mma', 'Bed', 'Rar', 'Ne', 'Hla', 'Moq'], + 'weekdays_min' => ['Son', 'Mma', 'Bed', 'Rar', 'Ne', 'Hla', 'Moq'], + 'day_of_first_week_of_year' => 1, + + 'week' => ':count Sontaha', // less reliable + 'w' => ':count Sontaha', // less reliable + 'a_week' => ':count Sontaha', // less reliable + + 'day' => ':count letsatsi', // less reliable + 'd' => ':count letsatsi', // less reliable + 'a_day' => ':count letsatsi', // less reliable + + 'hour' => ':count sešupanako', // less reliable + 'h' => ':count sešupanako', // less reliable + 'a_hour' => ':count sešupanako', // less reliable + + 'minute' => ':count menyane', // less reliable + 'min' => ':count menyane', // less reliable + 'a_minute' => ':count menyane', // less reliable + + 'second' => ':count thusa', // less reliable + 's' => ':count thusa', // less reliable + 'a_second' => ':count thusa', // less reliable + + 'year' => ':count selemo', + 'y' => ':count selemo', + 'a_year' => ':count selemo', + + 'month' => ':count kgwedi', + 'm' => ':count kgwedi', + 'a_month' => ':count kgwedi', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv.php new file mode 100644 index 0000000..1706c71 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv.php @@ -0,0 +1,87 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Kristoffer Snabb + * - JD Isaacks + * - Jens Herlevsen + * - Nightpine + * - Anders Nygren (litemerafrukt) + */ +return [ + 'year' => ':count år', + 'a_year' => 'ett år|:count år', + 'y' => ':count år', + 'month' => ':count månad|:count månader', + 'a_month' => 'en månad|:count månader', + 'm' => ':count mån', + 'week' => ':count vecka|:count veckor', + 'a_week' => 'en vecka|:count veckor', + 'w' => ':count v', + 'day' => ':count dag|:count dagar', + 'a_day' => 'en dag|:count dagar', + 'd' => ':count dgr', + 'hour' => ':count timme|:count timmar', + 'a_hour' => 'en timme|:count timmar', + 'h' => ':count tim', + 'minute' => ':count minut|:count minuter', + 'a_minute' => 'en minut|:count minuter', + 'min' => ':count min', + 'second' => ':count sekund|:count sekunder', + 'a_second' => 'några sekunder|:count sekunder', + 's' => ':count s', + 'ago' => 'för :time sedan', + 'from_now' => 'om :time', + 'after' => ':time efter', + 'before' => ':time före', + 'diff_now' => 'nu', + 'diff_today' => 'I dag', + 'diff_yesterday' => 'i går', + 'diff_yesterday_regexp' => 'I går', + 'diff_tomorrow' => 'i morgon', + 'diff_tomorrow_regexp' => 'I morgon', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY [kl.] HH:mm', + 'LLLL' => 'dddd D MMMM YYYY [kl.] HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[I dag] LT', + 'nextDay' => '[I morgon] LT', + 'nextWeek' => '[På] dddd LT', + 'lastDay' => '[I går] LT', + 'lastWeek' => '[I] dddd[s] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + $lastDigit = $number % 10; + + return $number.( + ((int) ($number % 100 / 10) === 1) ? 'e' : ( + ($lastDigit === 1 || $lastDigit === 2) ? 'a' : 'e' + ) + ); + }, + 'months' => ['januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december'], + 'months_short' => ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'weekdays' => ['söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag'], + 'weekdays_short' => ['sön', 'mån', 'tis', 'ons', 'tors', 'fre', 'lör'], + 'weekdays_min' => ['sö', 'må', 'ti', 'on', 'to', 'fr', 'lö'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' och '], + 'meridiem' => ['fm', 'em'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_AX.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_AX.php new file mode 100644 index 0000000..70cc558 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_AX.php @@ -0,0 +1,19 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/sv.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-dd', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_FI.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_FI.php new file mode 100644 index 0000000..d7182c8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_FI.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sv.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_SE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_SE.php new file mode 100644 index 0000000..d7182c8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sv_SE.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/sv.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw.php new file mode 100644 index 0000000..f8630d5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw.php @@ -0,0 +1,74 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - leyluj + * - Josh Soref + * - ryanhart2 + */ +return [ + 'year' => 'mwaka :count|miaka :count', + 'a_year' => 'mwaka mmoja|miaka :count', + 'y' => 'mwaka :count|miaka :count', + 'month' => 'mwezi :count|miezi :count', + 'a_month' => 'mwezi mmoja|miezi :count', + 'm' => 'mwezi :count|miezi :count', + 'week' => 'wiki :count', + 'a_week' => 'wiki mmoja|wiki :count', + 'w' => 'w. :count', + 'day' => 'siku :count', + 'a_day' => 'siku moja|masiku :count', + 'd' => 'si. :count', + 'hour' => 'saa :count|masaa :count', + 'a_hour' => 'saa limoja|masaa :count', + 'h' => 'saa :count|masaa :count', + 'minute' => 'dakika :count', + 'a_minute' => 'dakika moja|dakika :count', + 'min' => 'd. :count', + 'second' => 'sekunde :count', + 'a_second' => 'hivi punde|sekunde :count', + 's' => 'se. :count', + 'ago' => 'tokea :time', + 'from_now' => ':time baadaye', + 'after' => ':time baada', + 'before' => ':time kabla', + 'diff_now' => 'sasa hivi', + 'diff_today' => 'leo', + 'diff_today_regexp' => 'leo(?:\\s+saa)?', + 'diff_yesterday' => 'jana', + 'diff_tomorrow' => 'kesho', + 'diff_tomorrow_regexp' => 'kesho(?:\\s+saa)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[leo saa] LT', + 'nextDay' => '[kesho saa] LT', + 'nextWeek' => '[wiki ijayo] dddd [saat] LT', + 'lastDay' => '[jana] LT', + 'lastWeek' => '[wiki iliyopita] dddd [saat] LT', + 'sameElse' => 'L', + ], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Jpl', 'Jtat', 'Jnne', 'Jtan', 'Alh', 'Ijm', 'Jmos'], + 'weekdays_min' => ['J2', 'J3', 'J4', 'J5', 'Al', 'Ij', 'J1'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' na '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_CD.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_CD.php new file mode 100644 index 0000000..ec9117b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_CD.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/sw.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_KE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_KE.php new file mode 100644 index 0000000..2ace0db --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_KE.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kamusi Project Martin Benjamin locales@kamusi.org + */ +return array_replace_recursive(require __DIR__.'/sw.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1'], + 'weekdays_min' => ['J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['asubuhi', 'alasiri'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_TZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_TZ.php new file mode 100644 index 0000000..fab3cd6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_TZ.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kamusi Project Martin Benjamin locales@kamusi.org + */ +return array_replace_recursive(require __DIR__.'/sw.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1'], + 'weekdays_min' => ['J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['asubuhi', 'alasiri'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_UG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_UG.php new file mode 100644 index 0000000..ec9117b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/sw_UG.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/sw.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/szl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/szl.php new file mode 100644 index 0000000..4429c4f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/szl.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/szl_PL.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/szl_PL.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/szl_PL.php new file mode 100644 index 0000000..9adddcf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/szl_PL.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - szl_PL locale Przemyslaw Buczkowski libc-alpha@sourceware.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['styczyń', 'luty', 'merc', 'kwjeciyń', 'moj', 'czyrwjyń', 'lipjyń', 'siyrpjyń', 'wrzesiyń', 'październik', 'listopad', 'grudziyń'], + 'months_short' => ['sty', 'lut', 'mer', 'kwj', 'moj', 'czy', 'lip', 'siy', 'wrz', 'paź', 'lis', 'gru'], + 'weekdays' => ['niydziela', 'pyńdziŏek', 'wtŏrek', 'strzŏda', 'sztwortek', 'pjōntek', 'sobŏta'], + 'weekdays_short' => ['niy', 'pyń', 'wtŏ', 'str', 'szt', 'pjō', 'sob'], + 'weekdays_min' => ['niy', 'pyń', 'wtŏ', 'str', 'szt', 'pjō', 'sob'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count rok', + 'y' => ':count rok', + 'a_year' => ':count rok', + + 'month' => ':count mjeśůnc', + 'm' => ':count mjeśůnc', + 'a_month' => ':count mjeśůnc', + + 'week' => ':count tydźyń', + 'w' => ':count tydźyń', + 'a_week' => ':count tydźyń', + + 'day' => ':count dźyń', + 'd' => ':count dźyń', + 'a_day' => ':count dźyń', + + 'hour' => ':count godzina', + 'h' => ':count godzina', + 'a_hour' => ':count godzina', + + 'minute' => ':count minuta', + 'min' => ':count minuta', + 'a_minute' => ':count minuta', + + 'second' => ':count sekůnda', + 's' => ':count sekůnda', + 'a_second' => ':count sekůnda', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta.php new file mode 100644 index 0000000..c1d89cb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta.php @@ -0,0 +1,97 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - François B + * - JD Isaacks + * - Satheez + */ +return [ + 'year' => ':count வருடம்|:count ஆண்டுகள்', + 'a_year' => 'ஒரு வருடம்|:count ஆண்டுகள்', + 'y' => ':count வருட.|:count ஆண்.', + 'month' => ':count மாதம்|:count மாதங்கள்', + 'a_month' => 'ஒரு மாதம்|:count மாதங்கள்', + 'm' => ':count மாத.', + 'week' => ':count வாரம்|:count வாரங்கள்', + 'a_week' => 'ஒரு வாரம்|:count வாரங்கள்', + 'w' => ':count வார.', + 'day' => ':count நாள்|:count நாட்கள்', + 'a_day' => 'ஒரு நாள்|:count நாட்கள்', + 'd' => ':count நாள்|:count நாட்.', + 'hour' => ':count மணி நேரம்|:count மணி நேரம்', + 'a_hour' => 'ஒரு மணி நேரம்|:count மணி நேரம்', + 'h' => ':count மணி.', + 'minute' => ':count நிமிடம்|:count நிமிடங்கள்', + 'a_minute' => 'ஒரு நிமிடம்|:count நிமிடங்கள்', + 'min' => ':count நிமி.', + 'second' => ':count சில விநாடிகள்|:count விநாடிகள்', + 'a_second' => 'ஒரு சில விநாடிகள்|:count விநாடிகள்', + 's' => ':count விநா.', + 'ago' => ':time முன்', + 'from_now' => ':time இல்', + 'before' => ':time முன்', + 'after' => ':time பின்', + 'diff_now' => 'இப்போது', + 'diff_today' => 'இன்று', + 'diff_yesterday' => 'நேற்று', + 'diff_tomorrow' => 'நாளை', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY, HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[இன்று] LT', + 'nextDay' => '[நாளை] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[நேற்று] LT', + 'lastWeek' => '[கடந்த வாரம்] dddd, LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numberவது', + 'meridiem' => function ($hour) { + if ($hour < 2) { + return ' யாமம்'; + } + if ($hour < 6) { + return ' வைகறை'; + } + if ($hour < 10) { + return ' காலை'; + } + if ($hour < 14) { + return ' நண்பகல்'; + } + if ($hour < 18) { + return ' எற்பாடு'; + } + if ($hour < 22) { + return ' மாலை'; + } + + return ' யாமம்'; + }, + 'months' => ['ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டெம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்'], + 'months_short' => ['ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டெம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்'], + 'weekdays' => ['ஞாயிற்றுக்கிழமை', 'திங்கட்கிழமை', 'செவ்வாய்கிழமை', 'புதன்கிழமை', 'வியாழக்கிழமை', 'வெள்ளிக்கிழமை', 'சனிக்கிழமை'], + 'weekdays_short' => ['ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி'], + 'weekdays_min' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' மற்றும் '], + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_IN.php new file mode 100644 index 0000000..492d4c5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_IN.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/ta.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்'], + 'months_short' => ['ஜன.', 'பிப்.', 'மார்.', 'ஏப்.', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக.', 'செப்.', 'அக்.', 'நவ.', 'டிச.'], + 'weekdays' => ['ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி'], + 'weekdays_short' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'weekdays_min' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['காலை', 'மாலை'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_LK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_LK.php new file mode 100644 index 0000000..8e2afbf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_LK.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - J.Yogaraj 94-777-315206 yogaraj.ubuntu@gmail.com + */ +return array_replace_recursive(require __DIR__.'/ta.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்'], + 'months_short' => ['ஜன', 'பிப்', 'மார்', 'ஏப்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக', 'செப்', 'அக்', 'நவ', 'டிச'], + 'weekdays' => ['ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி'], + 'weekdays_short' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'weekdays_min' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['காலை', 'மாலை'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_MY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_MY.php new file mode 100644 index 0000000..a6cd8b5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_MY.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ta.php', [ + 'formats' => [ + 'LT' => 'a h:mm', + 'LTS' => 'a h:mm:ss', + 'L' => 'D/M/yy', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM, YYYY, a h:mm', + 'LLLL' => 'dddd, D MMMM, YYYY, a h:mm', + ], + 'months' => ['ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்'], + 'months_short' => ['ஜன.', 'பிப்.', 'மார்.', 'ஏப்.', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக.', 'செப்.', 'அக்.', 'நவ.', 'டிச.'], + 'weekdays' => ['ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி'], + 'weekdays_short' => ['ஞாயி.', 'திங்.', 'செவ்.', 'புத.', 'வியா.', 'வெள்.', 'சனி'], + 'weekdays_min' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'first_day_of_week' => 1, + 'meridiem' => ['மு.ப', 'பி.ப'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_SG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_SG.php new file mode 100644 index 0000000..7dbedee --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ta_SG.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ta.php', [ + 'formats' => [ + 'LT' => 'a h:mm', + 'LTS' => 'a h:mm:ss', + 'L' => 'D/M/yy', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM, YYYY, a h:mm', + 'LLLL' => 'dddd, D MMMM, YYYY, a h:mm', + ], + 'months' => ['ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்'], + 'months_short' => ['ஜன.', 'பிப்.', 'மார்.', 'ஏப்.', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக.', 'செப்.', 'அக்.', 'நவ.', 'டிச.'], + 'weekdays' => ['ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி'], + 'weekdays_short' => ['ஞாயி.', 'திங்.', 'செவ்.', 'புத.', 'வியா.', 'வெள்.', 'சனி'], + 'weekdays_min' => ['ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச'], + 'meridiem' => ['மு.ப', 'பி.ப'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tcy.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tcy.php new file mode 100644 index 0000000..2eb9905 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tcy.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/tcy_IN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tcy_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tcy_IN.php new file mode 100644 index 0000000..2ff20e0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tcy_IN.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IndLinux.org, Samsung Electronics Co., Ltd. alexey.merzlyakov@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['ಜನವರಿ', 'ಫೆಬ್ರುವರಿ', 'ಮಾರ್ಚ್', 'ಏಪ್ರಿಲ್‌‌', 'ಮೇ', 'ಜೂನ್', 'ಜುಲೈ', 'ಆಗಸ್ಟ್', 'ಸೆಪ್ಟೆಂಬರ್‌', 'ಅಕ್ಟೋಬರ್', 'ನವೆಂಬರ್', 'ಡಿಸೆಂಬರ್'], + 'months_short' => ['ಜ', 'ಫೆ', 'ಮಾ', 'ಏ', 'ಮೇ', 'ಜೂ', 'ಜು', 'ಆ', 'ಸೆ', 'ಅ', 'ನ', 'ಡಿ'], + 'weekdays' => ['ಐಥಾರ', 'ಸೋಮಾರ', 'ಅಂಗರೆ', 'ಬುಧಾರ', 'ಗುರುವಾರ', 'ಶುಕ್ರರ', 'ಶನಿವಾರ'], + 'weekdays_short' => ['ಐ', 'ಸೋ', 'ಅಂ', 'ಬು', 'ಗು', 'ಶು', 'ಶ'], + 'weekdays_min' => ['ಐ', 'ಸೋ', 'ಅಂ', 'ಬು', 'ಗು', 'ಶು', 'ಶ'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ಕಾಂಡೆ', 'ಬಯ್ಯ'], + + 'year' => ':count ನೀರ್', // less reliable + 'y' => ':count ನೀರ್', // less reliable + 'a_year' => ':count ನೀರ್', // less reliable + + 'month' => ':count ಮೀನ್', // less reliable + 'm' => ':count ಮೀನ್', // less reliable + 'a_month' => ':count ಮೀನ್', // less reliable + + 'day' => ':count ಸುಗ್ಗಿ', // less reliable + 'd' => ':count ಸುಗ್ಗಿ', // less reliable + 'a_day' => ':count ಸುಗ್ಗಿ', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/te.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/te.php new file mode 100644 index 0000000..ac38218 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/te.php @@ -0,0 +1,89 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kunal Marwaha + * - Josh Soref + * - François B + * - kc + */ +return [ + 'year' => ':count సంవత్సరం|:count సంవత్సరాలు', + 'a_year' => 'ఒక సంవత్సరం|:count సంవత్సరాలు', + 'y' => ':count సం.', + 'month' => ':count నెల|:count నెలలు', + 'a_month' => 'ఒక నెల|:count నెలలు', + 'm' => ':count నెల|:count నెల.', + 'week' => ':count వారం|:count వారాలు', + 'a_week' => 'ఒక వారం|:count వారాలు', + 'w' => ':count వార.|:count వారా.', + 'day' => ':count రోజు|:count రోజులు', + 'a_day' => 'ఒక రోజు|:count రోజులు', + 'd' => ':count రోజు|:count రోజు.', + 'hour' => ':count గంట|:count గంటలు', + 'a_hour' => 'ఒక గంట|:count గంటలు', + 'h' => ':count గం.', + 'minute' => ':count నిమిషం|:count నిమిషాలు', + 'a_minute' => 'ఒక నిమిషం|:count నిమిషాలు', + 'min' => ':count నిమి.', + 'second' => ':count సెకను|:count సెకన్లు', + 'a_second' => 'కొన్ని క్షణాలు|:count సెకన్లు', + 's' => ':count సెక.', + 'ago' => ':time క్రితం', + 'from_now' => ':time లో', + 'diff_now' => 'ప్రస్తుతం', + 'diff_today' => 'నేడు', + 'diff_yesterday' => 'నిన్న', + 'diff_tomorrow' => 'రేపు', + 'formats' => [ + 'LT' => 'A h:mm', + 'LTS' => 'A h:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, A h:mm', + 'LLLL' => 'dddd, D MMMM YYYY, A h:mm', + ], + 'calendar' => [ + 'sameDay' => '[నేడు] LT', + 'nextDay' => '[రేపు] LT', + 'nextWeek' => 'dddd, LT', + 'lastDay' => '[నిన్న] LT', + 'lastWeek' => '[గత] dddd, LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numberవ', + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'రాత్రి'; + } + if ($hour < 10) { + return 'ఉదయం'; + } + if ($hour < 17) { + return 'మధ్యాహ్నం'; + } + if ($hour < 20) { + return 'సాయంత్రం'; + } + + return ' రాత్రి'; + }, + 'months' => ['జనవరి', 'ఫిబ్రవరి', 'మార్చి', 'ఏప్రిల్', 'మే', 'జూన్', 'జూలై', 'ఆగస్టు', 'సెప్టెంబర్', 'అక్టోబర్', 'నవంబర్', 'డిసెంబర్'], + 'months_short' => ['జన.', 'ఫిబ్ర.', 'మార్చి', 'ఏప్రి.', 'మే', 'జూన్', 'జూలై', 'ఆగ.', 'సెప్.', 'అక్టో.', 'నవ.', 'డిసె.'], + 'weekdays' => ['ఆదివారం', 'సోమవారం', 'మంగళవారం', 'బుధవారం', 'గురువారం', 'శుక్రవారం', 'శనివారం'], + 'weekdays_short' => ['ఆది', 'సోమ', 'మంగళ', 'బుధ', 'గురు', 'శుక్ర', 'శని'], + 'weekdays_min' => ['ఆ', 'సో', 'మం', 'బు', 'గు', 'శు', 'శ'], + 'list' => ', ', + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'weekend' => [0, 0], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/te_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/te_IN.php new file mode 100644 index 0000000..3963f8d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/te_IN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/te.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/teo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/teo.php new file mode 100644 index 0000000..ca30c37 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/teo.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ta.php', [ + 'meridiem' => ['Taparachu', 'Ebongi'], + 'weekdays' => ['Nakaejuma', 'Nakaebarasa', 'Nakaare', 'Nakauni', 'Nakaung’on', 'Nakakany', 'Nakasabiti'], + 'weekdays_short' => ['Jum', 'Bar', 'Aar', 'Uni', 'Ung', 'Kan', 'Sab'], + 'weekdays_min' => ['Jum', 'Bar', 'Aar', 'Uni', 'Ung', 'Kan', 'Sab'], + 'months' => ['Orara', 'Omuk', 'Okwamg’', 'Odung’el', 'Omaruk', 'Omodok’king’ol', 'Ojola', 'Opedel', 'Osokosokoma', 'Otibar', 'Olabor', 'Opoo'], + 'months_short' => ['Rar', 'Muk', 'Kwa', 'Dun', 'Mar', 'Mod', 'Jol', 'Ped', 'Sok', 'Tib', 'Lab', 'Poo'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/teo_KE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/teo_KE.php new file mode 100644 index 0000000..010a04f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/teo_KE.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/teo.php', [ + 'first_day_of_week' => 0, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tet.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tet.php new file mode 100644 index 0000000..d0544d4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tet.php @@ -0,0 +1,64 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Joshua Brooks + * - François B + */ +return [ + 'year' => 'tinan :count', + 'a_year' => '{1}tinan ida|tinan :count', + 'month' => 'fulan :count', + 'a_month' => '{1}fulan ida|fulan :count', + 'week' => 'semana :count', + 'a_week' => '{1}semana ida|semana :count', + 'day' => 'loron :count', + 'a_day' => '{1}loron ida|loron :count', + 'hour' => 'oras :count', + 'a_hour' => '{1}oras ida|oras :count', + 'minute' => 'minutu :count', + 'a_minute' => '{1}minutu ida|minutu :count', + 'second' => 'segundu :count', + 'a_second' => '{1}segundu balun|segundu :count', + 'ago' => ':time liuba', + 'from_now' => 'iha :time', + 'diff_yesterday' => 'Horiseik', + 'diff_yesterday_regexp' => 'Horiseik(?:\\s+iha)?', + 'diff_today' => 'Ohin', + 'diff_today_regexp' => 'Ohin(?:\\s+iha)?', + 'diff_tomorrow' => 'Aban', + 'diff_tomorrow_regexp' => 'Aban(?:\\s+iha)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Ohin iha] LT', + 'nextDay' => '[Aban iha] LT', + 'nextWeek' => 'dddd [iha] LT', + 'lastDay' => '[Horiseik iha] LT', + 'lastWeek' => 'dddd [semana kotuk] [iha] LT', + 'sameElse' => 'L', + ], + 'ordinal' => ':numberº', + 'months' => ['Janeiru', 'Fevereiru', 'Marsu', 'Abril', 'Maiu', 'Juñu', 'Jullu', 'Agustu', 'Setembru', 'Outubru', 'Novembru', 'Dezembru'], + 'months_short' => ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'], + 'weekdays' => ['Domingu', 'Segunda', 'Tersa', 'Kuarta', 'Kinta', 'Sesta', 'Sabadu'], + 'weekdays_short' => ['Dom', 'Seg', 'Ters', 'Kua', 'Kint', 'Sest', 'Sab'], + 'weekdays_min' => ['Do', 'Seg', 'Te', 'Ku', 'Ki', 'Ses', 'Sa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tg.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tg.php new file mode 100644 index 0000000..b7df893 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tg.php @@ -0,0 +1,104 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Orif N. Jr + */ +return [ + 'year' => '{1}як сол|:count сол', + 'month' => '{1}як моҳ|:count моҳ', + 'week' => '{1}як ҳафта|:count ҳафта', + 'day' => '{1}як рӯз|:count рӯз', + 'hour' => '{1}як соат|:count соат', + 'minute' => '{1}як дақиқа|:count дақиқа', + 'second' => '{1}якчанд сония|:count сония', + 'ago' => ':time пеш', + 'from_now' => 'баъди :time', + 'diff_today' => 'Имрӯз', + 'diff_yesterday' => 'Дирӯз', + 'diff_yesterday_regexp' => 'Дирӯз(?:\\s+соати)?', + 'diff_tomorrow' => 'Пагоҳ', + 'diff_tomorrow_regexp' => 'Пагоҳ(?:\\s+соати)?', + 'diff_today_regexp' => 'Имрӯз(?:\\s+соати)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Имрӯз соати] LT', + 'nextDay' => '[Пагоҳ соати] LT', + 'nextWeek' => 'dddd[и] [ҳафтаи оянда соати] LT', + 'lastDay' => '[Дирӯз соати] LT', + 'lastWeek' => 'dddd[и] [ҳафтаи гузашта соати] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number) { + if ($number === 0) { // special case for zero + return "$number-ıncı"; + } + + static $suffixes = [ + 0 => '-ум', + 1 => '-ум', + 2 => '-юм', + 3 => '-юм', + 4 => '-ум', + 5 => '-ум', + 6 => '-ум', + 7 => '-ум', + 8 => '-ум', + 9 => '-ум', + 10 => '-ум', + 12 => '-ум', + 13 => '-ум', + 20 => '-ум', + 30 => '-юм', + 40 => '-ум', + 50 => '-ум', + 60 => '-ум', + 70 => '-ум', + 80 => '-ум', + 90 => '-ум', + 100 => '-ум', + ]; + + return $number.($suffixes[$number] ?? $suffixes[$number % 10] ?? $suffixes[$number >= 100 ? 100 : -1] ?? ''); + }, + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'шаб'; + } + if ($hour < 11) { + return 'субҳ'; + } + if ($hour < 16) { + return 'рӯз'; + } + if ($hour < 19) { + return 'бегоҳ'; + } + + return 'шаб'; + }, + 'months' => ['январ', 'феврал', 'март', 'апрел', 'май', 'июн', 'июл', 'август', 'сентябр', 'октябр', 'ноябр', 'декабр'], + 'months_short' => ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'weekdays' => ['якшанбе', 'душанбе', 'сешанбе', 'чоршанбе', 'панҷшанбе', 'ҷумъа', 'шанбе'], + 'weekdays_short' => ['яшб', 'дшб', 'сшб', 'чшб', 'пшб', 'ҷум', 'шнб'], + 'weekdays_min' => ['яш', 'дш', 'сш', 'чш', 'пш', 'ҷм', 'шб'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' ва '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tg_TJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tg_TJ.php new file mode 100644 index 0000000..badc7d1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tg_TJ.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/tg.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/th.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/th.php new file mode 100644 index 0000000..6397f6e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/th.php @@ -0,0 +1,73 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Nate Whittaker + * - John MacAslan + * - Chanintorn Asavavichairoj + * - JD Isaacks + * - ROKAISAKKON + * - RO'KAISAKKON + * - Andreas Möller + * - nithisa + */ +return [ + 'year' => ':count ปี', + 'y' => ':count ปี', + 'month' => ':count เดือน', + 'm' => ':count เดือน', + 'week' => ':count สัปดาห์', + 'w' => ':count สัปดาห์', + 'day' => ':count วัน', + 'd' => ':count วัน', + 'hour' => ':count ชั่วโมง', + 'h' => ':count ชั่วโมง', + 'minute' => ':count นาที', + 'min' => ':count นาที', + 'second' => ':count วินาที', + 'a_second' => '{1}ไม่กี่วินาที|]1,Inf[:count วินาที', + 's' => ':count วินาที', + 'ago' => ':timeที่แล้ว', + 'from_now' => 'อีก :time', + 'after' => ':timeหลังจากนี้', + 'before' => ':timeก่อน', + 'diff_now' => 'ขณะนี้', + 'diff_today' => 'วันนี้', + 'diff_today_regexp' => 'วันนี้(?:\\s+เวลา)?', + 'diff_yesterday' => 'เมื่อวาน', + 'diff_yesterday_regexp' => 'เมื่อวานนี้(?:\\s+เวลา)?', + 'diff_tomorrow' => 'พรุ่งนี้', + 'diff_tomorrow_regexp' => 'พรุ่งนี้(?:\\s+เวลา)?', + 'formats' => [ + 'LT' => 'H:mm', + 'LTS' => 'H:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY เวลา H:mm', + 'LLLL' => 'วันddddที่ D MMMM YYYY เวลา H:mm', + ], + 'calendar' => [ + 'sameDay' => '[วันนี้ เวลา] LT', + 'nextDay' => '[พรุ่งนี้ เวลา] LT', + 'nextWeek' => 'dddd[หน้า เวลา] LT', + 'lastDay' => '[เมื่อวานนี้ เวลา] LT', + 'lastWeek' => '[วัน]dddd[ที่แล้ว เวลา] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ก่อนเที่ยง', 'หลังเที่ยง'], + 'months' => ['มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'], + 'months_short' => ['ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.'], + 'weekdays' => ['อาทิตย์', 'จันทร์', 'อังคาร', 'พุธ', 'พฤหัสบดี', 'ศุกร์', 'เสาร์'], + 'weekdays_short' => ['อาทิตย์', 'จันทร์', 'อังคาร', 'พุธ', 'พฤหัส', 'ศุกร์', 'เสาร์'], + 'weekdays_min' => ['อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'], + 'list' => [', ', ' และ '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/th_TH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/th_TH.php new file mode 100644 index 0000000..b9f94b2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/th_TH.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/th.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/the.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/the.php new file mode 100644 index 0000000..85f8333 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/the.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/the_NP.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/the_NP.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/the_NP.php new file mode 100644 index 0000000..34da162 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/the_NP.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Chitwanix OS Development info@chitwanix.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'dddd DD MMM YYYY', + ], + 'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'months_short' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], + 'weekdays' => ['आइतबार', 'सोमबार', 'मंगलबार', 'बुधबार', 'बिहिबार', 'शुक्रबार', 'शनिबार'], + 'weekdays_short' => ['आइत', 'सोम', 'मंगल', 'बुध', 'बिहि', 'शुक्र', 'शनि'], + 'weekdays_min' => ['आइत', 'सोम', 'मंगल', 'बुध', 'बिहि', 'शुक्र', 'शनि'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti.php new file mode 100644 index 0000000..ffd3236 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ti_ER.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti_ER.php new file mode 100644 index 0000000..310c51c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti_ER.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጥሪ', 'ለካቲት', 'መጋቢት', 'ሚያዝያ', 'ግንቦት', 'ሰነ', 'ሓምለ', 'ነሓሰ', 'መስከረም', 'ጥቅምቲ', 'ሕዳር', 'ታሕሳስ'], + 'months_short' => ['ጥሪ ', 'ለካቲ', 'መጋቢ', 'ሚያዝ', 'ግንቦ', 'ሰነ ', 'ሓምለ', 'ነሓሰ', 'መስከ', 'ጥቅም', 'ሕዳር', 'ታሕሳ'], + 'weekdays' => ['ሰንበት', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም'], + 'weekdays_short' => ['ሰንበ', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም'], + 'weekdays_min' => ['ሰንበ', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ንጉሆ ሰዓተ', 'ድሕር ሰዓት'], + + 'year' => ':count ዓመት', + 'y' => ':count ዓመት', + 'a_year' => ':count ዓመት', + + 'month' => 'ወርሒ :count', + 'm' => 'ወርሒ :count', + 'a_month' => 'ወርሒ :count', + + 'week' => ':count ሰሙን', + 'w' => ':count ሰሙን', + 'a_week' => ':count ሰሙን', + + 'day' => ':count መዓልቲ', + 'd' => ':count መዓልቲ', + 'a_day' => ':count መዓልቲ', + + 'hour' => ':count ሰዓት', + 'h' => ':count ሰዓት', + 'a_hour' => ':count ሰዓት', + + 'minute' => ':count ደቒቕ', + 'min' => ':count ደቒቕ', + 'a_minute' => ':count ደቒቕ', + + 'second' => ':count ሰከንድ', + 's' => ':count ሰከንድ', + 'a_second' => ':count ሰከንድ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti_ET.php new file mode 100644 index 0000000..024217f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ti_ET.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር'], + 'months_short' => ['ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም'], + 'weekdays' => ['ሰንበት', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም'], + 'weekdays_short' => ['ሰንበ', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም'], + 'weekdays_min' => ['ሰንበ', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ንጉሆ ሰዓተ', 'ድሕር ሰዓት'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tig.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tig.php new file mode 100644 index 0000000..186fe71 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tig.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/tig_ER.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tig_ER.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tig_ER.php new file mode 100644 index 0000000..46887b0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tig_ER.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጥሪ', 'ለካቲት', 'መጋቢት', 'ሚያዝያ', 'ግንቦት', 'ሰነ', 'ሓምለ', 'ነሓሰ', 'መስከረም', 'ጥቅምቲ', 'ሕዳር', 'ታሕሳስ'], + 'months_short' => ['ጥሪ ', 'ለካቲ', 'መጋቢ', 'ሚያዝ', 'ግንቦ', 'ሰነ ', 'ሓምለ', 'ነሓሰ', 'መስከ', 'ጥቅም', 'ሕዳር', 'ታሕሳ'], + 'weekdays' => ['ሰንበት ዓባይ', 'ሰኖ', 'ታላሸኖ', 'ኣረርባዓ', 'ከሚሽ', 'ጅምዓት', 'ሰንበት ንኢሽ'], + 'weekdays_short' => ['ሰ//ዓ', 'ሰኖ ', 'ታላሸ', 'ኣረር', 'ከሚሽ', 'ጅምዓ', 'ሰ//ን'], + 'weekdays_min' => ['ሰ//ዓ', 'ሰኖ ', 'ታላሸ', 'ኣረር', 'ከሚሽ', 'ጅምዓ', 'ሰ//ን'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ቀደም ሰር ምዕል', 'ሓቆ ሰር ምዕል'], + + 'year' => ':count ማይ', // less reliable + 'y' => ':count ማይ', // less reliable + 'a_year' => ':count ማይ', // less reliable + + 'month' => ':count ሸምሽ', // less reliable + 'm' => ':count ሸምሽ', // less reliable + 'a_month' => ':count ሸምሽ', // less reliable + + 'week' => ':count ሰቡዕ', // less reliable + 'w' => ':count ሰቡዕ', // less reliable + 'a_week' => ':count ሰቡዕ', // less reliable + + 'day' => ':count ዎሮ', // less reliable + 'd' => ':count ዎሮ', // less reliable + 'a_day' => ':count ዎሮ', // less reliable + + 'hour' => ':count ሰዓት', // less reliable + 'h' => ':count ሰዓት', // less reliable + 'a_hour' => ':count ሰዓት', // less reliable + + 'minute' => ':count ካልኣይት', // less reliable + 'min' => ':count ካልኣይት', // less reliable + 'a_minute' => ':count ካልኣይት', // less reliable + + 'second' => ':count ካልኣይ', + 's' => ':count ካልኣይ', + 'a_second' => ':count ካልኣይ', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tk.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tk.php new file mode 100644 index 0000000..d8f7d19 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tk.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/tk_TM.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tk_TM.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tk_TM.php new file mode 100644 index 0000000..f949a43 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tk_TM.php @@ -0,0 +1,77 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Authors: + * - Ghorban M. Tavakoly Pablo Saratxaga & Ghorban M. Tavakoly pablo@walon.org & gmt314@yahoo.com + * - SuperManPHP + * - Maksat Meredow (isadma) + */ +$transformDiff = function ($input) { + return strtr($input, [ + 'sekunt' => 'sekunt', + 'hepde' => 'hepde', + ]); +}; + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Ýanwar', 'Fewral', 'Mart', 'Aprel', 'Maý', 'Iýun', 'Iýul', 'Awgust', 'Sentýabr', 'Oktýabr', 'Noýabr', 'Dekabr'], + 'months_short' => ['Ýan', 'Few', 'Mar', 'Apr', 'Maý', 'Iýn', 'Iýl', 'Awg', 'Sen', 'Okt', 'Noý', 'Dek'], + 'weekdays' => ['Duşenbe', 'Sişenbe', 'Çarşenbe', 'Penşenbe', 'Anna', 'Şenbe', 'Ýekşenbe'], + 'weekdays_short' => ['Duş', 'Siş', 'Çar', 'Pen', 'Ann', 'Şen', 'Ýek'], + 'weekdays_min' => ['Du', 'Si', 'Ça', 'Pe', 'An', 'Şe', 'Ýe'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + + 'year' => ':count ýyl', + 'y' => ':count ýyl', + 'a_year' => ':count ýyl', + + 'month' => ':count aý', + 'm' => ':count aý', + 'a_month' => ':count aý', + + 'week' => ':count hepde', + 'w' => ':count hepde', + 'a_week' => ':count hepde', + + 'day' => ':count gün', + 'd' => ':count gün', + 'a_day' => ':count gün', + + 'hour' => ':count sagat', + 'h' => ':count sagat', + 'a_hour' => ':count sagat', + + 'minute' => ':count minut', + 'min' => ':count minut', + 'a_minute' => ':count minut', + + 'second' => ':count sekunt', + 's' => ':count sekunt', + 'a_second' => ':count sekunt', + + 'ago' => function ($time) use ($transformDiff) { + return $transformDiff($time).' ozal'; + }, + 'from_now' => function ($time) use ($transformDiff) { + return $transformDiff($time).' soňra'; + }, + 'after' => function ($time) use ($transformDiff) { + return $transformDiff($time).' soň'; + }, + 'before' => function ($time) use ($transformDiff) { + return $transformDiff($time).' öň'; + }, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tl.php new file mode 100644 index 0000000..410a266 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tl.php @@ -0,0 +1,61 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return [ + 'year' => ':count taon', + 'a_year' => '{1}isang taon|:count taon', + 'month' => ':count buwan', + 'a_month' => '{1}isang buwan|:count buwan', + 'week' => ':count linggo', + 'a_week' => '{1}isang linggo|:count linggo', + 'day' => ':count araw', + 'a_day' => '{1}isang araw|:count araw', + 'hour' => ':count oras', + 'a_hour' => '{1}isang oras|:count oras', + 'minute' => ':count minuto', + 'a_minute' => '{1}isang minuto|:count minuto', + 'min' => ':count min.', + 'second' => ':count segundo', + 'a_second' => '{1}ilang segundo|:count segundo', + 's' => ':count seg.', + 'ago' => ':time ang nakalipas', + 'from_now' => 'sa loob ng :time', + 'diff_now' => 'ngayon', + 'diff_today' => 'ngayong', + 'diff_today_regexp' => 'ngayong(?:\\s+araw)?', + 'diff_yesterday' => 'kahapon', + 'diff_tomorrow' => 'bukas', + 'diff_tomorrow_regexp' => 'Bukas(?:\\s+ng)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'MM/D/YYYY', + 'LL' => 'MMMM D, YYYY', + 'LLL' => 'MMMM D, YYYY HH:mm', + 'LLLL' => 'dddd, MMMM DD, YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => 'LT [ngayong araw]', + 'nextDay' => '[Bukas ng] LT', + 'nextWeek' => 'LT [sa susunod na] dddd', + 'lastDay' => 'LT [kahapon]', + 'lastWeek' => 'LT [noong nakaraang] dddd', + 'sameElse' => 'L', + ], + 'months' => ['Enero', 'Pebrero', 'Marso', 'Abril', 'Mayo', 'Hunyo', 'Hulyo', 'Agosto', 'Setyembre', 'Oktubre', 'Nobyembre', 'Disyembre'], + 'months_short' => ['Ene', 'Peb', 'Mar', 'Abr', 'May', 'Hun', 'Hul', 'Ago', 'Set', 'Okt', 'Nob', 'Dis'], + 'weekdays' => ['Linggo', 'Lunes', 'Martes', 'Miyerkules', 'Huwebes', 'Biyernes', 'Sabado'], + 'weekdays_short' => ['Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab'], + 'weekdays_min' => ['Li', 'Lu', 'Ma', 'Mi', 'Hu', 'Bi', 'Sab'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' at '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tl_PH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tl_PH.php new file mode 100644 index 0000000..95f508c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tl_PH.php @@ -0,0 +1,18 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Ian De La Cruz + * - JD Isaacks + */ +return require __DIR__.'/tl.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tlh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tlh.php new file mode 100644 index 0000000..fbf9e6f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tlh.php @@ -0,0 +1,72 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Serhan Apaydın + * - Dominika + */ +return [ + 'year' => '{1}wa’ DIS|:count DIS', + 'month' => '{1}wa’ jar|:count jar', + 'week' => '{1}wa’ hogh|:count hogh', + 'day' => '{1}wa’ jaj|:count jaj', + 'hour' => '{1}wa’ rep|:count rep', + 'minute' => '{1}wa’ tup|:count tup', + 'second' => '{1}puS lup|:count lup', + 'ago' => function ($time) { + $output = strtr($time, [ + 'jaj' => 'Hu’', + 'jar' => 'wen', + 'DIS' => 'ben', + ]); + + return $output === $time ? "$time ret" : $output; + }, + 'from_now' => function ($time) { + $output = strtr($time, [ + 'jaj' => 'leS', + 'jar' => 'waQ', + 'DIS' => 'nem', + ]); + + return $output === $time ? "$time pIq" : $output; + }, + 'diff_yesterday' => 'wa’Hu’', + 'diff_today' => 'DaHjaj', + 'diff_tomorrow' => 'wa’leS', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[DaHjaj] LT', + 'nextDay' => '[wa’leS] LT', + 'nextWeek' => 'LLL', + 'lastDay' => '[wa’Hu’] LT', + 'lastWeek' => 'LLL', + 'sameElse' => 'L', + ], + 'ordinal' => ':number.', + 'months' => ['tera’ jar wa’', 'tera’ jar cha’', 'tera’ jar wej', 'tera’ jar loS', 'tera’ jar vagh', 'tera’ jar jav', 'tera’ jar Soch', 'tera’ jar chorgh', 'tera’ jar Hut', 'tera’ jar wa’maH', 'tera’ jar wa’maH wa’', 'tera’ jar wa’maH cha’'], + 'months_short' => ['jar wa’', 'jar cha’', 'jar wej', 'jar loS', 'jar vagh', 'jar jav', 'jar Soch', 'jar chorgh', 'jar Hut', 'jar wa’maH', 'jar wa’maH wa’', 'jar wa’maH cha’'], + 'weekdays' => ['lojmItjaj', 'DaSjaj', 'povjaj', 'ghItlhjaj', 'loghjaj', 'buqjaj', 'ghInjaj'], + 'weekdays_short' => ['lojmItjaj', 'DaSjaj', 'povjaj', 'ghItlhjaj', 'loghjaj', 'buqjaj', 'ghInjaj'], + 'weekdays_min' => ['lojmItjaj', 'DaSjaj', 'povjaj', 'ghItlhjaj', 'loghjaj', 'buqjaj', 'ghInjaj'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' ’ej '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tn.php new file mode 100644 index 0000000..f29bdf6 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tn.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/tn_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tn_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tn_ZA.php new file mode 100644 index 0000000..aada7db --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tn_ZA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Ferikgong', 'Tlhakole', 'Mopitlwe', 'Moranang', 'Motsheganong', 'Seetebosigo', 'Phukwi', 'Phatwe', 'Lwetse', 'Diphalane', 'Ngwanatsele', 'Sedimonthole'], + 'months_short' => ['Fer', 'Tlh', 'Mop', 'Mor', 'Mot', 'See', 'Phu', 'Pha', 'Lwe', 'Dip', 'Ngw', 'Sed'], + 'weekdays' => ['laTshipi', 'Mosupologo', 'Labobedi', 'Laboraro', 'Labone', 'Labotlhano', 'Lamatlhatso'], + 'weekdays_short' => ['Tsh', 'Mos', 'Bed', 'Rar', 'Ne', 'Tlh', 'Mat'], + 'weekdays_min' => ['Tsh', 'Mos', 'Bed', 'Rar', 'Ne', 'Tlh', 'Mat'], + 'day_of_first_week_of_year' => 1, + + 'year' => 'dingwaga di le :count', + 'y' => 'dingwaga di le :count', + 'a_year' => 'dingwaga di le :count', + + 'month' => 'dikgwedi di le :count', + 'm' => 'dikgwedi di le :count', + 'a_month' => 'dikgwedi di le :count', + + 'week' => 'dibeke di le :count', + 'w' => 'dibeke di le :count', + 'a_week' => 'dibeke di le :count', + + 'day' => 'malatsi :count', + 'd' => 'malatsi :count', + 'a_day' => 'malatsi :count', + + 'hour' => 'diura di le :count', + 'h' => 'diura di le :count', + 'a_hour' => 'diura di le :count', + + 'minute' => 'metsotso e le :count', + 'min' => 'metsotso e le :count', + 'a_minute' => 'metsotso e le :count', + + 'second' => 'metsotswana e le :count', + 's' => 'metsotswana e le :count', + 'a_second' => 'metsotswana e le :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/to.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/to.php new file mode 100644 index 0000000..20581bb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/to.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/to_TO.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/to_TO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/to_TO.php new file mode 100644 index 0000000..335c69a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/to_TO.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - International Components for Unicode akhilesh.k@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'dddd DD MMM YYYY', + ], + 'months' => ['Sānuali', 'Fēpueli', 'Maʻasi', 'ʻEpeleli', 'Mē', 'Sune', 'Siulai', 'ʻAokosi', 'Sepitema', 'ʻOkatopa', 'Nōvema', 'Tīsema'], + 'months_short' => ['Sān', 'Fēp', 'Maʻa', 'ʻEpe', 'Mē', 'Sun', 'Siu', 'ʻAok', 'Sep', 'ʻOka', 'Nōv', 'Tīs'], + 'weekdays' => ['Sāpate', 'Mōnite', 'Tūsite', 'Pulelulu', 'Tuʻapulelulu', 'Falaite', 'Tokonaki'], + 'weekdays_short' => ['Sāp', 'Mōn', 'Tūs', 'Pul', 'Tuʻa', 'Fal', 'Tok'], + 'weekdays_min' => ['Sāp', 'Mōn', 'Tūs', 'Pul', 'Tuʻa', 'Fal', 'Tok'], + 'meridiem' => ['hengihengi', 'efiafi'], + + 'year' => ':count fitu', // less reliable + 'y' => ':count fitu', // less reliable + 'a_year' => ':count fitu', // less reliable + + 'month' => ':count mahina', // less reliable + 'm' => ':count mahina', // less reliable + 'a_month' => ':count mahina', // less reliable + + 'week' => ':count Sapate', // less reliable + 'w' => ':count Sapate', // less reliable + 'a_week' => ':count Sapate', // less reliable + + 'day' => ':count ʻaho', // less reliable + 'd' => ':count ʻaho', // less reliable + 'a_day' => ':count ʻaho', // less reliable + + 'hour' => ':count houa', + 'h' => ':count houa', + 'a_hour' => ':count houa', + + 'minute' => ':count miniti', + 'min' => ':count miniti', + 'a_minute' => ':count miniti', + + 'second' => ':count sekoni', + 's' => ':count sekoni', + 'a_second' => ':count sekoni', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tpi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tpi.php new file mode 100644 index 0000000..7d38dae --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tpi.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/tpi_PG.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tpi_PG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tpi_PG.php new file mode 100644 index 0000000..5f58c44 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tpi_PG.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Samsung Electronics Co., Ltd. akhilesh.k@samsung.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Janueri', 'Februeri', 'Mas', 'Epril', 'Me', 'Jun', 'Julai', 'Ogas', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mas', 'Epr', 'Me', 'Jun', 'Jul', 'Oga', 'Sep', 'Okt', 'Nov', 'Des'], + 'weekdays' => ['Sande', 'Mande', 'Tunde', 'Trinde', 'Fonde', 'Fraide', 'Sarere'], + 'weekdays_short' => ['San', 'Man', 'Tun', 'Tri', 'Fon', 'Fra', 'Sar'], + 'weekdays_min' => ['San', 'Man', 'Tun', 'Tri', 'Fon', 'Fra', 'Sar'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['biknait', 'apinun'], + + 'year' => 'yia :count', + 'y' => 'yia :count', + 'a_year' => 'yia :count', + + 'month' => ':count mun', + 'm' => ':count mun', + 'a_month' => ':count mun', + + 'week' => ':count wik', + 'w' => ':count wik', + 'a_week' => ':count wik', + + 'day' => ':count de', + 'd' => ':count de', + 'a_day' => ':count de', + + 'hour' => ':count aua', + 'h' => ':count aua', + 'a_hour' => ':count aua', + + 'minute' => ':count minit', + 'min' => ':count minit', + 'a_minute' => ':count minit', + + 'second' => ':count namba tu', + 's' => ':count namba tu', + 'a_second' => ':count namba tu', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr.php new file mode 100644 index 0000000..f5d9f4c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr.php @@ -0,0 +1,121 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Alan Agius + * - Erhan Gundogan + * - François B + * - JD Isaacks + * - Murat Yüksel + * - Baran Şengül + * - Selami (selamialtin) + * - TeomanBey + */ +return [ + 'year' => ':count yıl', + 'a_year' => '{1}bir yıl|]1,Inf[:count yıl', + 'y' => ':county', + 'month' => ':count ay', + 'a_month' => '{1}bir ay|]1,Inf[:count ay', + 'm' => ':countay', + 'week' => ':count hafta', + 'a_week' => '{1}bir hafta|]1,Inf[:count hafta', + 'w' => ':counth', + 'day' => ':count gün', + 'a_day' => '{1}bir gün|]1,Inf[:count gün', + 'd' => ':countg', + 'hour' => ':count saat', + 'a_hour' => '{1}bir saat|]1,Inf[:count saat', + 'h' => ':countsa', + 'minute' => ':count dakika', + 'a_minute' => '{1}bir dakika|]1,Inf[:count dakika', + 'min' => ':countdk', + 'second' => ':count saniye', + 'a_second' => '{1}birkaç saniye|]1,Inf[:count saniye', + 's' => ':countsn', + 'ago' => ':time önce', + 'from_now' => ':time sonra', + 'after' => ':time sonra', + 'before' => ':time önce', + 'diff_now' => 'şimdi', + 'diff_today' => 'bugün', + 'diff_today_regexp' => 'bugün(?:\\s+saat)?', + 'diff_yesterday' => 'dün', + 'diff_tomorrow' => 'yarın', + 'diff_tomorrow_regexp' => 'yarın(?:\\s+saat)?', + 'diff_before_yesterday' => 'evvelsi gün', + 'diff_after_tomorrow' => 'öbür gün', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[bugün saat] LT', + 'nextDay' => '[yarın saat] LT', + 'nextWeek' => '[gelecek] dddd [saat] LT', + 'lastDay' => '[dün] LT', + 'lastWeek' => '[geçen] dddd [saat] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'd': + case 'D': + case 'Do': + case 'DD': + return $number; + default: + if ($number === 0) { // special case for zero + return "$number'ıncı"; + } + + static $suffixes = [ + 1 => '\'inci', + 5 => '\'inci', + 8 => '\'inci', + 70 => '\'inci', + 80 => '\'inci', + 2 => '\'nci', + 7 => '\'nci', + 20 => '\'nci', + 50 => '\'nci', + 3 => '\'üncü', + 4 => '\'üncü', + 100 => '\'üncü', + 6 => '\'ncı', + 9 => '\'uncu', + 10 => '\'uncu', + 30 => '\'uncu', + 60 => '\'ıncı', + 90 => '\'ıncı', + ]; + + $lastDigit = $number % 10; + + return $number.($suffixes[$lastDigit] ?? $suffixes[$number % 100 - $lastDigit] ?? $suffixes[$number >= 100 ? 100 : -1] ?? ''); + } + }, + 'meridiem' => ['ÖÖ', 'ÖS', 'öö', 'ös'], + 'months' => ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'], + 'months_short' => ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara'], + 'weekdays' => ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi'], + 'weekdays_short' => ['Paz', 'Pts', 'Sal', 'Çar', 'Per', 'Cum', 'Cts'], + 'weekdays_min' => ['Pz', 'Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' ve '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr_CY.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr_CY.php new file mode 100644 index 0000000..23f1144 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr_CY.php @@ -0,0 +1,23 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/tr.php', [ + 'weekdays_short' => ['Paz', 'Pzt', 'Sal', 'Çar', 'Per', 'Cum', 'Cmt'], + 'weekdays_min' => ['Pa', 'Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct'], + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'D.MM.YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'D MMMM YYYY dddd h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr_TR.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr_TR.php new file mode 100644 index 0000000..9e99482 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tr_TR.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/tr.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ts.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ts.php new file mode 100644 index 0000000..525736b --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ts.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ts_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ts_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ts_ZA.php new file mode 100644 index 0000000..37a24ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ts_ZA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Sunguti', 'Nyenyenyani', 'Nyenyankulu', 'Dzivamisoko', 'Mudyaxihi', 'Khotavuxika', 'Mawuwani', 'Mhawuri', 'Ndzhati', 'Nhlangula', 'Hukuri', 'N\'wendzamhala'], + 'months_short' => ['Sun', 'Yan', 'Kul', 'Dzi', 'Mud', 'Kho', 'Maw', 'Mha', 'Ndz', 'Nhl', 'Huk', 'N\'w'], + 'weekdays' => ['Sonto', 'Musumbhunuku', 'Ravumbirhi', 'Ravunharhu', 'Ravumune', 'Ravuntlhanu', 'Mugqivela'], + 'weekdays_short' => ['Son', 'Mus', 'Bir', 'Har', 'Ne', 'Tlh', 'Mug'], + 'weekdays_min' => ['Son', 'Mus', 'Bir', 'Har', 'Ne', 'Tlh', 'Mug'], + 'day_of_first_week_of_year' => 1, + + 'year' => 'malembe ya :count', + 'y' => 'malembe ya :count', + 'a_year' => 'malembe ya :count', + + 'month' => 'tin’hweti ta :count', + 'm' => 'tin’hweti ta :count', + 'a_month' => 'tin’hweti ta :count', + + 'week' => 'mavhiki ya :count', + 'w' => 'mavhiki ya :count', + 'a_week' => 'mavhiki ya :count', + + 'day' => 'masiku :count', + 'd' => 'masiku :count', + 'a_day' => 'masiku :count', + + 'hour' => 'tiawara ta :count', + 'h' => 'tiawara ta :count', + 'a_hour' => 'tiawara ta :count', + + 'minute' => 'timinete ta :count', + 'min' => 'timinete ta :count', + 'a_minute' => 'timinete ta :count', + + 'second' => 'tisekoni ta :count', + 's' => 'tisekoni ta :count', + 'a_second' => 'tisekoni ta :count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt.php new file mode 100644 index 0000000..d67d896 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/tt_RU.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt_RU.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt_RU.php new file mode 100644 index 0000000..38e42d0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt_RU.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Rinat Norkin Pablo Saratxaga, Rinat Norkin pablo@mandrakesoft.com, rinat@taif.ru + */ +return [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'DD MMM, HH:mm', + 'LLLL' => 'DD MMMM YYYY, HH:mm', + ], + 'months' => ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'], + 'months_short' => ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'weekdays' => ['якшәмбе', 'дышәмбе', 'сишәмбе', 'чәршәәмбе', 'пәнҗешмбе', 'җомга', 'шимбә'], + 'weekdays_short' => ['якш', 'дыш', 'сиш', 'чәрш', 'пәнҗ', 'җом', 'шим'], + 'weekdays_min' => ['якш', 'дыш', 'сиш', 'чәрш', 'пәнҗ', 'җом', 'шим'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'year' => ':count ел', + 'month' => ':count ай', + 'week' => ':count атна', + 'day' => ':count көн', + 'hour' => ':count сәгать', + 'minute' => ':count минут', + 'second' => ':count секунд', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt_RU@iqtelif.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt_RU@iqtelif.php new file mode 100644 index 0000000..16b8efb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tt_RU@iqtelif.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Reshat Sabiq tatar.iqtelif.i18n@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD.MM.YYYY', + ], + 'months' => ['Ğınwar', 'Fiwral\'', 'Mart', 'April', 'May', 'Yün', 'Yül', 'Awgust', 'Sintebír', 'Üktebír', 'Noyebír', 'Dikebír'], + 'months_short' => ['Ğın', 'Fiw', 'Mar', 'Apr', 'May', 'Yün', 'Yül', 'Awg', 'Sin', 'Ükt', 'Noy', 'Dik'], + 'weekdays' => ['Yekşembí', 'Düşembí', 'Sişembí', 'Çerşembí', 'Pencíşembí', 'Comğa', 'Şimbe'], + 'weekdays_short' => ['Yek', 'Düş', 'Siş', 'Çer', 'Pen', 'Com', 'Şim'], + 'weekdays_min' => ['Yek', 'Düş', 'Siş', 'Çer', 'Pen', 'Com', 'Şim'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ÖA', 'ÖS'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/twq.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/twq.php new file mode 100644 index 0000000..5cbb46e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/twq.php @@ -0,0 +1,14 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/ses.php', [ + 'meridiem' => ['Subbaahi', 'Zaarikay b'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzl.php new file mode 100644 index 0000000..50bf26d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzl.php @@ -0,0 +1,65 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return [ + 'year' => '[0,1]:count ar|:count ars', + 'y' => '[0,1]:count ar|:count ars', + 'month' => '[0,1]:count mes|:count mesen', + 'm' => '[0,1]:count mes|:count mesen', + 'week' => '[0,1]:count seifetziua|:count seifetziuas', + 'w' => '[0,1]:count seifetziua|:count seifetziuas', + 'day' => '[0,1]:count ziua|:count ziuas', + 'd' => '[0,1]:count ziua|:count ziuas', + 'hour' => '[0,1]:count þora|:count þoras', + 'h' => '[0,1]:count þora|:count þoras', + 'minute' => '[0,1]:count míut|:count míuts', + 'min' => '[0,1]:count míut|:count míuts', + 'second' => ':count secunds', + 's' => ':count secunds', + + 'ago' => 'ja :time', + 'from_now' => 'osprei :time', + + 'diff_yesterday' => 'ieiri', + 'diff_yesterday_regexp' => 'ieiri(?:\\s+à)?', + 'diff_today' => 'oxhi', + 'diff_today_regexp' => 'oxhi(?:\\s+à)?', + 'diff_tomorrow' => 'demà', + 'diff_tomorrow_regexp' => 'demà(?:\\s+à)?', + + 'formats' => [ + 'LT' => 'HH.mm', + 'LTS' => 'HH.mm.ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D. MMMM [dallas] YYYY', + 'LLL' => 'D. MMMM [dallas] YYYY HH.mm', + 'LLLL' => 'dddd, [li] D. MMMM [dallas] YYYY HH.mm', + ], + + 'calendar' => [ + 'sameDay' => '[oxhi à] LT', + 'nextDay' => '[demà à] LT', + 'nextWeek' => 'dddd [à] LT', + 'lastDay' => '[ieiri à] LT', + 'lastWeek' => '[sür el] dddd [lasteu à] LT', + 'sameElse' => 'L', + ], + + 'meridiem' => ["D'A", "D'O"], + 'months' => ['Januar', 'Fevraglh', 'Març', 'Avrïu', 'Mai', 'Gün', 'Julia', 'Guscht', 'Setemvar', 'Listopäts', 'Noemvar', 'Zecemvar'], + 'months_short' => ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Gün', 'Jul', 'Gus', 'Set', 'Lis', 'Noe', 'Zec'], + 'weekdays' => ['Súladi', 'Lúneçi', 'Maitzi', 'Márcuri', 'Xhúadi', 'Viénerçi', 'Sáturi'], + 'weekdays_short' => ['Súl', 'Lún', 'Mai', 'Már', 'Xhú', 'Vié', 'Sát'], + 'weekdays_min' => ['Sú', 'Lú', 'Ma', 'Má', 'Xh', 'Vi', 'Sá'], + 'ordinal' => ':number.', + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzm.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzm.php new file mode 100644 index 0000000..2a1a0f2 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzm.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - JD Isaacks + */ +return [ + 'year' => '{1}ⴰⵙⴳⴰⵙ|:count ⵉⵙⴳⴰⵙⵏ', + 'month' => '{1}ⴰⵢoⵓⵔ|:count ⵉⵢⵢⵉⵔⵏ', + 'week' => ':count ⵉⵎⴰⵍⴰⵙⵙ', + 'day' => '{1}ⴰⵙⵙ|:count oⵙⵙⴰⵏ', + 'hour' => '{1}ⵙⴰⵄⴰ|:count ⵜⴰⵙⵙⴰⵄⵉⵏ', + 'minute' => '{1}ⵎⵉⵏⵓⴺ|:count ⵎⵉⵏⵓⴺ', + 'second' => '{1}ⵉⵎⵉⴽ|:count ⵉⵎⵉⴽ', + 'ago' => 'ⵢⴰⵏ :time', + 'from_now' => 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ :time', + 'diff_today' => 'ⴰⵙⴷⵅ', + 'diff_yesterday' => 'ⴰⵚⴰⵏⵜ', + 'diff_yesterday_regexp' => 'ⴰⵚⴰⵏⵜ(?:\\s+ⴴ)?', + 'diff_tomorrow' => 'ⴰⵙⴽⴰ', + 'diff_tomorrow_regexp' => 'ⴰⵙⴽⴰ(?:\\s+ⴴ)?', + 'diff_today_regexp' => 'ⴰⵙⴷⵅ(?:\\s+ⴴ)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[ⴰⵙⴷⵅ ⴴ] LT', + 'nextDay' => '[ⴰⵙⴽⴰ ⴴ] LT', + 'nextWeek' => 'dddd [ⴴ] LT', + 'lastDay' => '[ⴰⵚⴰⵏⵜ ⴴ] LT', + 'lastWeek' => 'dddd [ⴴ] LT', + 'sameElse' => 'L', + ], + 'months' => ['ⵉⵏⵏⴰⵢⵔ', 'ⴱⵕⴰⵢⵕ', 'ⵎⴰⵕⵚ', 'ⵉⴱⵔⵉⵔ', 'ⵎⴰⵢⵢⵓ', 'ⵢⵓⵏⵢⵓ', 'ⵢⵓⵍⵢⵓⵣ', 'ⵖⵓⵛⵜ', 'ⵛⵓⵜⴰⵏⴱⵉⵔ', 'ⴽⵟⵓⴱⵕ', 'ⵏⵓⵡⴰⵏⴱⵉⵔ', 'ⴷⵓⵊⵏⴱⵉⵔ'], + 'months_short' => ['ⵉⵏⵏⴰⵢⵔ', 'ⴱⵕⴰⵢⵕ', 'ⵎⴰⵕⵚ', 'ⵉⴱⵔⵉⵔ', 'ⵎⴰⵢⵢⵓ', 'ⵢⵓⵏⵢⵓ', 'ⵢⵓⵍⵢⵓⵣ', 'ⵖⵓⵛⵜ', 'ⵛⵓⵜⴰⵏⴱⵉⵔ', 'ⴽⵟⵓⴱⵕ', 'ⵏⵓⵡⴰⵏⴱⵉⵔ', 'ⴷⵓⵊⵏⴱⵉⵔ'], + 'weekdays' => ['ⴰⵙⴰⵎⴰⵙ', 'ⴰⵢⵏⴰⵙ', 'ⴰⵙⵉⵏⴰⵙ', 'ⴰⴽⵔⴰⵙ', 'ⴰⴽⵡⴰⵙ', 'ⴰⵙⵉⵎⵡⴰⵙ', 'ⴰⵙⵉⴹⵢⴰⵙ'], + 'weekdays_short' => ['ⴰⵙⴰⵎⴰⵙ', 'ⴰⵢⵏⴰⵙ', 'ⴰⵙⵉⵏⴰⵙ', 'ⴰⴽⵔⴰⵙ', 'ⴰⴽⵡⴰⵙ', 'ⴰⵙⵉⵎⵡⴰⵙ', 'ⴰⵙⵉⴹⵢⴰⵙ'], + 'weekdays_min' => ['ⴰⵙⴰⵎⴰⵙ', 'ⴰⵢⵏⴰⵙ', 'ⴰⵙⵉⵏⴰⵙ', 'ⴰⴽⵔⴰⵙ', 'ⴰⴽⵡⴰⵙ', 'ⴰⵙⵉⵎⵡⴰⵙ', 'ⴰⵙⵉⴹⵢⴰⵙ'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'weekend' => [5, 6], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzm_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzm_Latn.php new file mode 100644 index 0000000..5840d20 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/tzm_Latn.php @@ -0,0 +1,64 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - JD Isaacks + */ +return [ + 'year' => '{1}:count asgas|:count isgasn', + 'a_year' => 'asgas|:count isgasn', + 'month' => '{1}:count ayowr|:count iyyirn', + 'a_month' => 'ayowr|:count iyyirn', + 'week' => ':count imalass', + 'a_week' => ':imalass', + 'day' => '{1}:count ass|:count ossan', + 'a_day' => 'ass|:count ossan', + 'hour' => '{1}:count saɛa|:count tassaɛin', + 'a_hour' => '{1}saɛa|:count tassaɛin', + 'minute' => ':count minuḍ', + 'a_minute' => '{1}minuḍ|:count minuḍ', + 'second' => ':count imik', + 'a_second' => '{1}imik|:count imik', + 'ago' => 'yan :time', + 'from_now' => 'dadkh s yan :time', + 'diff_yesterday' => 'assant', + 'diff_yesterday_regexp' => 'assant(?:\\s+g)?', + 'diff_today' => 'asdkh', + 'diff_today_regexp' => 'asdkh(?:\\s+g)?', + 'diff_tomorrow' => 'aska', + 'diff_tomorrow_regexp' => 'aska(?:\\s+g)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[asdkh g] LT', + 'nextDay' => '[aska g] LT', + 'nextWeek' => 'dddd [g] LT', + 'lastDay' => '[assant g] LT', + 'lastWeek' => 'dddd [g] LT', + 'sameElse' => 'L', + ], + 'months' => ['innayr', 'brˤayrˤ', 'marˤsˤ', 'ibrir', 'mayyw', 'ywnyw', 'ywlywz', 'ɣwšt', 'šwtanbir', 'ktˤwbrˤ', 'nwwanbir', 'dwjnbir'], + 'months_short' => ['innayr', 'brˤayrˤ', 'marˤsˤ', 'ibrir', 'mayyw', 'ywnyw', 'ywlywz', 'ɣwšt', 'šwtanbir', 'ktˤwbrˤ', 'nwwanbir', 'dwjnbir'], + 'weekdays' => ['asamas', 'aynas', 'asinas', 'akras', 'akwas', 'asimwas', 'asiḍyas'], + 'weekdays_short' => ['asamas', 'aynas', 'asinas', 'akras', 'akwas', 'asimwas', 'asiḍyas'], + 'weekdays_min' => ['asamas', 'aynas', 'asinas', 'akras', 'akwas', 'asimwas', 'asiḍyas'], + 'meridiem' => ['Zdat azal', 'Ḍeffir aza'], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ug.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ug.php new file mode 100644 index 0000000..259b99a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ug.php @@ -0,0 +1,90 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Philippe Vaucher + * - Tsutomu Kuroda + * - yasinn + */ +return [ + 'year' => '{1}'.'بىر يىل'.'|:count '.'يىل', + 'month' => '{1}'.'بىر ئاي'.'|:count '.'ئاي', + 'week' => '{1}'.'بىر ھەپتە'.'|:count '.'ھەپتە', + 'day' => '{1}'.'بىر كۈن'.'|:count '.'كۈن', + 'hour' => '{1}'.'بىر سائەت'.'|:count '.'سائەت', + 'minute' => '{1}'.'بىر مىنۇت'.'|:count '.'مىنۇت', + 'second' => '{1}'.'نەچچە سېكونت'.'|:count '.'سېكونت', + 'ago' => ':time بۇرۇن', + 'from_now' => ':time كېيىن', + 'diff_today' => 'بۈگۈن', + 'diff_yesterday' => 'تۆنۈگۈن', + 'diff_tomorrow' => 'ئەتە', + 'diff_tomorrow_regexp' => 'ئەتە(?:\\s+سائەت)?', + 'diff_today_regexp' => 'بۈگۈن(?:\\s+سائەت)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-DD', + 'LL' => 'YYYY-يىلىM-ئاينىڭD-كۈنى', + 'LLL' => 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', + 'LLLL' => 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[بۈگۈن سائەت] LT', + 'nextDay' => '[ئەتە سائەت] LT', + 'nextWeek' => '[كېلەركى] dddd [سائەت] LT', + 'lastDay' => '[تۆنۈگۈن] LT', + 'lastWeek' => '[ئالدىنقى] dddd [سائەت] LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'd': + case 'D': + case 'DDD': + return $number.'-كۈنى'; + case 'w': + case 'W': + return $number.'-ھەپتە'; + default: + return $number; + } + }, + 'meridiem' => function ($hour, $minute) { + $time = $hour * 100 + $minute; + if ($time < 600) { + return 'يېرىم كېچە'; + } + if ($time < 900) { + return 'سەھەر'; + } + if ($time < 1130) { + return 'چۈشتىن بۇرۇن'; + } + if ($time < 1230) { + return 'چۈش'; + } + if ($time < 1800) { + return 'چۈشتىن كېيىن'; + } + + return 'كەچ'; + }, + 'months' => ['يانۋار', 'فېۋرال', 'مارت', 'ئاپرېل', 'ماي', 'ئىيۇن', 'ئىيۇل', 'ئاۋغۇست', 'سېنتەبىر', 'ئۆكتەبىر', 'نويابىر', 'دېكابىر'], + 'months_short' => ['يانۋار', 'فېۋرال', 'مارت', 'ئاپرېل', 'ماي', 'ئىيۇن', 'ئىيۇل', 'ئاۋغۇست', 'سېنتەبىر', 'ئۆكتەبىر', 'نويابىر', 'دېكابىر'], + 'weekdays' => ['يەكشەنبە', 'دۈشەنبە', 'سەيشەنبە', 'چارشەنبە', 'پەيشەنبە', 'جۈمە', 'شەنبە'], + 'weekdays_short' => ['يە', 'دۈ', 'سە', 'چا', 'پە', 'جۈ', 'شە'], + 'weekdays_min' => ['يە', 'دۈ', 'سە', 'چا', 'پە', 'جۈ', 'شە'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' ۋە '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ug_CN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ug_CN.php new file mode 100644 index 0000000..deb828c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ug_CN.php @@ -0,0 +1,17 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Kunal Marwaha + * - Alim Boyaq + */ +return require __DIR__.'/ug.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uk.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uk.php new file mode 100644 index 0000000..4217d16 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uk.php @@ -0,0 +1,212 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Carbon\CarbonInterface; + +$processHoursFunction = function (CarbonInterface $date, string $format) { + return $format.'о'.($date->hour === 11 ? 'б' : '').'] LT'; +}; + +/* + * Authors: + * - Kunal Marwaha + * - Josh Soref + * - François B + * - Tim Fish + * - Serhan Apaydın + * - Max Mykhailenko + * - JD Isaacks + * - Max Kovpak + * - AucT + * - Philippe Vaucher + * - Ilya Shaplyko + * - Vadym Ievsieiev + * - Denys Kurets + * - Igor Kasyanchuk + * - Tsutomu Kuroda + * - tjku + * - Max Melentiev + * - Oleh + * - epaminond + * - Juanito Fatas + * - Vitalii Khustochka + * - Akira Matsuda + * - Christopher Dell + * - Enrique Vidal + * - Simone Carletti + * - Aaron Patterson + * - Andriy Tyurnikov + * - Nicolás Hock Isaza + * - Iwakura Taro + * - Andrii Ponomarov + * - alecrabbit + * - vystepanenko + * - AlexWalkerson + * - Andre Havryliuk (Andrend) + * - Max Datsenko (datsenko-md) + */ +return [ + 'year' => ':count рік|:count роки|:count років', + 'y' => ':countр|:countрр|:countрр', + 'a_year' => '{1}рік|:count рік|:count роки|:count років', + 'month' => ':count місяць|:count місяці|:count місяців', + 'm' => ':countм', + 'a_month' => '{1}місяць|:count місяць|:count місяці|:count місяців', + 'week' => ':count тиждень|:count тижні|:count тижнів', + 'w' => ':countт', + 'a_week' => '{1}тиждень|:count тиждень|:count тижні|:count тижнів', + 'day' => ':count день|:count дні|:count днів', + 'd' => ':countд', + 'a_day' => '{1}день|:count день|:count дні|:count днів', + 'hour' => ':count година|:count години|:count годин', + 'h' => ':countг', + 'a_hour' => '{1}година|:count година|:count години|:count годин', + 'minute' => ':count хвилина|:count хвилини|:count хвилин', + 'min' => ':countхв', + 'a_minute' => '{1}хвилина|:count хвилина|:count хвилини|:count хвилин', + 'second' => ':count секунда|:count секунди|:count секунд', + 's' => ':countсек', + 'a_second' => '{1}декілька секунд|:count секунда|:count секунди|:count секунд', + + 'hour_ago' => ':count годину|:count години|:count годин', + 'a_hour_ago' => '{1}годину|:count годину|:count години|:count годин', + 'minute_ago' => ':count хвилину|:count хвилини|:count хвилин', + 'a_minute_ago' => '{1}хвилину|:count хвилину|:count хвилини|:count хвилин', + 'second_ago' => ':count секунду|:count секунди|:count секунд', + 'a_second_ago' => '{1}декілька секунд|:count секунду|:count секунди|:count секунд', + + 'hour_from_now' => ':count годину|:count години|:count годин', + 'a_hour_from_now' => '{1}годину|:count годину|:count години|:count годин', + 'minute_from_now' => ':count хвилину|:count хвилини|:count хвилин', + 'a_minute_from_now' => '{1}хвилину|:count хвилину|:count хвилини|:count хвилин', + 'second_from_now' => ':count секунду|:count секунди|:count секунд', + 'a_second_from_now' => '{1}декілька секунд|:count секунду|:count секунди|:count секунд', + + 'hour_after' => ':count годину|:count години|:count годин', + 'a_hour_after' => '{1}годину|:count годину|:count години|:count годин', + 'minute_after' => ':count хвилину|:count хвилини|:count хвилин', + 'a_minute_after' => '{1}хвилину|:count хвилину|:count хвилини|:count хвилин', + 'second_after' => ':count секунду|:count секунди|:count секунд', + 'a_second_after' => '{1}декілька секунд|:count секунду|:count секунди|:count секунд', + + 'hour_before' => ':count годину|:count години|:count годин', + 'a_hour_before' => '{1}годину|:count годину|:count години|:count годин', + 'minute_before' => ':count хвилину|:count хвилини|:count хвилин', + 'a_minute_before' => '{1}хвилину|:count хвилину|:count хвилини|:count хвилин', + 'second_before' => ':count секунду|:count секунди|:count секунд', + 'a_second_before' => '{1}декілька секунд|:count секунду|:count секунди|:count секунд', + + 'ago' => ':time тому', + 'from_now' => 'за :time', + 'after' => ':time після', + 'before' => ':time до', + 'diff_now' => 'щойно', + 'diff_today' => 'Сьогодні', + 'diff_today_regexp' => 'Сьогодні(?:\\s+о)?', + 'diff_yesterday' => 'вчора', + 'diff_yesterday_regexp' => 'Вчора(?:\\s+о)?', + 'diff_tomorrow' => 'завтра', + 'diff_tomorrow_regexp' => 'Завтра(?:\\s+о)?', + 'diff_before_yesterday' => 'позавчора', + 'diff_after_tomorrow' => 'післязавтра', + 'period_recurrences' => 'один раз|:count рази|:count разів', + 'period_interval' => 'кожні :interval', + 'period_start_date' => 'з :date', + 'period_end_date' => 'до :date', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY, HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY, HH:mm', + ], + 'calendar' => [ + 'sameDay' => function (CarbonInterface $date) use ($processHoursFunction) { + return $processHoursFunction($date, '[Сьогодні '); + }, + 'nextDay' => function (CarbonInterface $date) use ($processHoursFunction) { + return $processHoursFunction($date, '[Завтра '); + }, + 'nextWeek' => function (CarbonInterface $date) use ($processHoursFunction) { + return $processHoursFunction($date, '[У] dddd ['); + }, + 'lastDay' => function (CarbonInterface $date) use ($processHoursFunction) { + return $processHoursFunction($date, '[Вчора '); + }, + 'lastWeek' => function (CarbonInterface $date) use ($processHoursFunction) { + switch ($date->dayOfWeek) { + case 0: + case 3: + case 5: + case 6: + return $processHoursFunction($date, '[Минулої] dddd ['); + default: + return $processHoursFunction($date, '[Минулого] dddd ['); + } + }, + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'M': + case 'd': + case 'DDD': + case 'w': + case 'W': + return $number.'-й'; + case 'D': + return $number.'-го'; + default: + return $number; + } + }, + 'meridiem' => function ($hour) { + if ($hour < 4) { + return 'ночі'; + } + if ($hour < 12) { + return 'ранку'; + } + if ($hour < 17) { + return 'дня'; + } + + return 'вечора'; + }, + 'months' => ['січня', 'лютого', 'березня', 'квітня', 'травня', 'червня', 'липня', 'серпня', 'вересня', 'жовтня', 'листопада', 'грудня'], + 'months_standalone' => ['січень', 'лютий', 'березень', 'квітень', 'травень', 'червень', 'липень', 'серпень', 'вересень', 'жовтень', 'листопад', 'грудень'], + 'months_short' => ['січ', 'лют', 'бер', 'кві', 'тра', 'чер', 'лип', 'сер', 'вер', 'жов', 'лис', 'гру'], + 'months_regexp' => '/(D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|L{2,4}|l{2,4})/', + 'weekdays' => function (CarbonInterface $date, $format, $index) { + static $words = [ + 'nominative' => ['неділя', 'понеділок', 'вівторок', 'середа', 'четвер', 'п’ятниця', 'субота'], + 'accusative' => ['неділю', 'понеділок', 'вівторок', 'середу', 'четвер', 'п’ятницю', 'суботу'], + 'genitive' => ['неділі', 'понеділка', 'вівторка', 'середи', 'четверга', 'п’ятниці', 'суботи'], + ]; + + $format = $format ?? ''; + $nounCase = preg_match('/(\[(В|в|У|у)\])\s+dddd/u', $format) + ? 'accusative' + : ( + preg_match('/\[?(?:минулої|наступної)?\s*\]\s+dddd/u', $format) + ? 'genitive' + : 'nominative' + ); + + return $words[$nounCase][$index] ?? null; + }, + 'weekdays_short' => ['нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'], + 'weekdays_min' => ['нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' i '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uk_UA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uk_UA.php new file mode 100644 index 0000000..bd11d86 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uk_UA.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/uk.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/unm.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/unm.php new file mode 100644 index 0000000..d3f19f0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/unm.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/unm_US.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/unm_US.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/unm_US.php new file mode 100644 index 0000000..fa5c374 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/unm_US.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['enikwsi', 'chkwali', 'xamokhwite', 'kwetayoxe', 'tainipen', 'kichinipen', 'lainipen', 'winaminke', 'kichitahkok', 'puksit', 'wini', 'muxkotae'], + 'months_short' => ['eni', 'chk', 'xam', 'kwe', 'tai', 'nip', 'lai', 'win', 'tah', 'puk', 'kun', 'mux'], + 'weekdays' => ['kentuwei', 'manteke', 'tusteke', 'lelai', 'tasteke', 'pelaiteke', 'sateteke'], + 'weekdays_short' => ['ken', 'man', 'tus', 'lel', 'tas', 'pel', 'sat'], + 'weekdays_min' => ['ken', 'man', 'tus', 'lel', 'tas', 'pel', 'sat'], + 'day_of_first_week_of_year' => 1, + + // Too unreliable + /* + 'year' => ':count kaxtëne', + 'y' => ':count kaxtëne', + 'a_year' => ':count kaxtëne', + + 'month' => ':count piskewëni kishux', // less reliable + 'm' => ':count piskewëni kishux', // less reliable + 'a_month' => ':count piskewëni kishux', // less reliable + + 'week' => ':count kishku', // less reliable + 'w' => ':count kishku', // less reliable + 'a_week' => ':count kishku', // less reliable + + 'day' => ':count kishku', + 'd' => ':count kishku', + 'a_day' => ':count kishku', + + 'hour' => ':count xkuk', // less reliable + 'h' => ':count xkuk', // less reliable + 'a_hour' => ':count xkuk', // less reliable + + 'minute' => ':count txituwàk', // less reliable + 'min' => ':count txituwàk', // less reliable + 'a_minute' => ':count txituwàk', // less reliable + + 'second' => ':count nisha', // less reliable + 's' => ':count nisha', // less reliable + 'a_second' => ':count nisha', // less reliable + */ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur.php new file mode 100644 index 0000000..dc16c2c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur.php @@ -0,0 +1,94 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +$months = [ + 'جنوری', + 'فروری', + 'مارچ', + 'اپریل', + 'مئی', + 'جون', + 'جولائی', + 'اگست', + 'ستمبر', + 'اکتوبر', + 'نومبر', + 'دسمبر', +]; + +$weekdays = [ + 'اتوار', + 'پیر', + 'منگل', + 'بدھ', + 'جمعرات', + 'جمعہ', + 'ہفتہ', +]; + +/* + * Authors: + * - Sawood Alam + * - Mehshan + * - Philippe Vaucher + * - Tsutomu Kuroda + * - tjku + * - Zaid Akram + * - Max Melentiev + * - hafezdivandari + * - Hossein Jabbari + * - nimamo + */ +return [ + 'year' => 'ایک سال|:count سال', + 'month' => 'ایک ماہ|:count ماہ', + 'week' => ':count ہفتے', + 'day' => 'ایک دن|:count دن', + 'hour' => 'ایک گھنٹہ|:count گھنٹے', + 'minute' => 'ایک منٹ|:count منٹ', + 'second' => 'چند سیکنڈ|:count سیکنڈ', + 'ago' => ':time قبل', + 'from_now' => ':time بعد', + 'after' => ':time بعد', + 'before' => ':time پہلے', + 'diff_now' => 'اب', + 'diff_today' => 'آج', + 'diff_today_regexp' => 'آج(?:\\s+بوقت)?', + 'diff_yesterday' => 'گزشتہ کل', + 'diff_yesterday_regexp' => 'گذشتہ(?:\\s+روز)?(?:\\s+بوقت)?', + 'diff_tomorrow' => 'آئندہ کل', + 'diff_tomorrow_regexp' => 'کل(?:\\s+بوقت)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd، D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[آج بوقت] LT', + 'nextDay' => '[کل بوقت] LT', + 'nextWeek' => 'dddd [بوقت] LT', + 'lastDay' => '[گذشتہ روز بوقت] LT', + 'lastWeek' => '[گذشتہ] dddd [بوقت] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['صبح', 'شام'], + 'months' => $months, + 'months_short' => $months, + 'weekdays' => $weekdays, + 'weekdays_short' => $weekdays, + 'weekdays_min' => $weekdays, + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => ['، ', ' اور '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur_IN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur_IN.php new file mode 100644 index 0000000..f81c84d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur_IN.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Red Hat, Pune bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/ur.php', [ + 'formats' => [ + 'L' => 'D/M/YY', + ], + 'months' => ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'weekdays' => ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'سنیچر'], + 'weekdays_short' => ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'سنیچر'], + 'weekdays_min' => ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'سنیچر'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur_PK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur_PK.php new file mode 100644 index 0000000..8cd593d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ur_PK.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/ur.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'weekdays' => ['اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته'], + 'weekdays_short' => ['اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته'], + 'weekdays_min' => ['اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته'], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ص', 'ش'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz.php new file mode 100644 index 0000000..61f3b64 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz.php @@ -0,0 +1,85 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Dmitriy Shabanov + * - JD Isaacks + * - Inoyatulloh + * - Jamshid + * - aarkhipov + * - Philippe Vaucher + * - felixthemagnificent + * - Tsutomu Kuroda + * - tjku + * - Max Melentiev + * - Juanito Fatas + * - Alisher Ulugbekov + * - Ergashev Adizbek + */ +return [ + 'year' => ':count йил', + 'a_year' => '{1}бир йил|:count йил', + 'y' => ':count й', + 'month' => ':count ой', + 'a_month' => '{1}бир ой|:count ой', + 'm' => ':count о', + 'week' => ':count ҳафта', + 'a_week' => '{1}бир ҳафта|:count ҳафта', + 'w' => ':count ҳ', + 'day' => ':count кун', + 'a_day' => '{1}бир кун|:count кун', + 'd' => ':count к', + 'hour' => ':count соат', + 'a_hour' => '{1}бир соат|:count соат', + 'h' => ':count с', + 'minute' => ':count дақиқа', + 'a_minute' => '{1}бир дақиқа|:count дақиқа', + 'min' => ':count д', + 'second' => ':count сония', + 'a_second' => '{1}сония|:count сония', + 's' => ':count с', + 'ago' => ':time аввал', + 'from_now' => 'Якин :time ичида', + 'after' => ':timeдан кейин', + 'before' => ':time олдин', + 'diff_now' => 'ҳозир', + 'diff_today' => 'Бугун', + 'diff_today_regexp' => 'Бугун(?:\\s+соат)?', + 'diff_yesterday' => 'Кеча', + 'diff_yesterday_regexp' => 'Кеча(?:\\s+соат)?', + 'diff_tomorrow' => 'Эртага', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'D MMMM YYYY, dddd HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Бугун соат] LT [да]', + 'nextDay' => '[Эртага] LT [да]', + 'nextWeek' => 'dddd [куни соат] LT [да]', + 'lastDay' => '[Кеча соат] LT [да]', + 'lastWeek' => '[Утган] dddd [куни соат] LT [да]', + 'sameElse' => 'L', + ], + 'months' => ['январ', 'феврал', 'март', 'апрел', 'май', 'июн', 'июл', 'август', 'сентябр', 'октябр', 'ноябр', 'декабр'], + 'months_short' => ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], + 'weekdays' => ['якшанба', 'душанба', 'сешанба', 'чоршанба', 'пайшанба', 'жума', 'шанба'], + 'weekdays_short' => ['якш', 'душ', 'сеш', 'чор', 'пай', 'жум', 'шан'], + 'weekdays_min' => ['як', 'ду', 'се', 'чо', 'па', 'жу', 'ша'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['эрталаб', 'кечаси'], + 'list' => [', ', ' ва '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Arab.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Arab.php new file mode 100644 index 0000000..ffb5131 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Arab.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/fa.php', [ + 'weekdays' => ['یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'], + 'weekdays_short' => ['ی.', 'د.', 'س.', 'چ.', 'پ.', 'ج.', 'ش.'], + 'weekdays_min' => ['ی.', 'د.', 'س.', 'چ.', 'پ.', 'ج.', 'ش.'], + 'months' => ['جنوری', 'فبروری', 'مارچ', 'اپریل', 'می', 'جون', 'جولای', 'اگست', 'سپتمبر', 'اکتوبر', 'نومبر', 'دسمبر'], + 'months_short' => ['جنو', 'فبر', 'مار', 'اپر', 'می', 'جون', 'جول', 'اگس', 'سپت', 'اکت', 'نوم', 'دسم'], + 'first_day_of_week' => 6, + 'weekend' => [4, 5], + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'YYYY MMMM D, dddd HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Cyrl.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Cyrl.php new file mode 100644 index 0000000..89e9971 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Cyrl.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/uz.php', [ + 'formats' => [ + 'L' => 'DD/MM/yy', + 'LL' => 'D MMM, YYYY', + 'LLL' => 'D MMMM, YYYY HH:mm', + 'LLLL' => 'dddd, DD MMMM, YYYY HH:mm', + ], + 'meridiem' => ['ТО', 'ТК'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Latn.php new file mode 100644 index 0000000..ecceeaa --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_Latn.php @@ -0,0 +1,74 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Josh Soref + * - Rasulbek + * - Ilyosjon Kamoldinov (ilyosjon09) + */ +return [ + 'year' => ':count yil', + 'a_year' => '{1}bir yil|:count yil', + 'y' => ':count y', + 'month' => ':count oy', + 'a_month' => '{1}bir oy|:count oy', + 'm' => ':count o', + 'week' => ':count hafta', + 'a_week' => '{1}bir hafta|:count hafta', + 'w' => ':count h', + 'day' => ':count kun', + 'a_day' => '{1}bir kun|:count kun', + 'd' => ':count k', + 'hour' => ':count soat', + 'a_hour' => '{1}bir soat|:count soat', + 'h' => ':count soat', + 'minute' => ':count daqiqa', + 'a_minute' => '{1}bir daqiqa|:count daqiqa', + 'min' => ':count d', + 'second' => ':count soniya', + 'a_second' => '{1}soniya|:count soniya', + 's' => ':count son.', + 'ago' => ':time avval', + 'from_now' => 'Yaqin :time ichida', + 'after' => ':timedan keyin', + 'before' => ':time oldin', + 'diff_yesterday' => 'Kecha', + 'diff_yesterday_regexp' => 'Kecha(?:\\s+soat)?', + 'diff_today' => 'Bugun', + 'diff_today_regexp' => 'Bugun(?:\\s+soat)?', + 'diff_tomorrow' => 'Ertaga', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'D MMMM YYYY, dddd HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Bugun soat] LT [da]', + 'nextDay' => '[Ertaga] LT [da]', + 'nextWeek' => 'dddd [kuni soat] LT [da]', + 'lastDay' => '[Kecha soat] LT [da]', + 'lastWeek' => '[O\'tgan] dddd [kuni soat] LT [da]', + 'sameElse' => 'L', + ], + 'months' => ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'Iyun', 'Iyul', 'Avgust', 'Sentabr', 'Oktabr', 'Noyabr', 'Dekabr'], + 'months_short' => ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'Iyun', 'Iyul', 'Avg', 'Sen', 'Okt', 'Noy', 'Dek'], + 'weekdays' => ['Yakshanba', 'Dushanba', 'Seshanba', 'Chorshanba', 'Payshanba', 'Juma', 'Shanba'], + 'weekdays_short' => ['Yak', 'Dush', 'Sesh', 'Chor', 'Pay', 'Jum', 'Shan'], + 'weekdays_min' => ['Ya', 'Du', 'Se', 'Cho', 'Pa', 'Ju', 'Sha'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' va '], + 'meridiem' => ['TO', 'TK'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_UZ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_UZ.php new file mode 100644 index 0000000..d41bfee --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_UZ.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Bobir Ismailov Bobir Ismailov, Pablo Saratxaga, Mashrab Kuvatov bobir_is@yahoo.com, pablo@mandrakesoft.com, kmashrab@uni-bremen.de + */ +return array_replace_recursive(require __DIR__.'/uz_Latn.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'Iyun', 'Iyul', 'Avgust', 'Sentabr', 'Oktabr', 'Noyabr', 'Dekabr'], + 'months_short' => ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'Iyn', 'Iyl', 'Avg', 'Sen', 'Okt', 'Noy', 'Dek'], + 'weekdays' => ['Yakshanba', 'Dushanba', 'Seshanba', 'Chorshanba', 'Payshanba', 'Juma', 'Shanba'], + 'weekdays_short' => ['Yak', 'Du', 'Se', 'Cho', 'Pay', 'Ju', 'Sha'], + 'weekdays_min' => ['Yak', 'Du', 'Se', 'Cho', 'Pay', 'Ju', 'Sha'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_UZ@cyrillic.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_UZ@cyrillic.php new file mode 100644 index 0000000..2fa967c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/uz_UZ@cyrillic.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Mashrab Kuvatov Mashrab Kuvatov, Pablo Saratxaga kmashrab@uni-bremen.de, pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/uz.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['Январ', 'Феврал', 'Март', 'Апрел', 'Май', 'Июн', 'Июл', 'Август', 'Сентябр', 'Октябр', 'Ноябр', 'Декабр'], + 'months_short' => ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'], + 'weekdays' => ['Якшанба', 'Душанба', 'Сешанба', 'Чоршанба', 'Пайшанба', 'Жума', 'Шанба'], + 'weekdays_short' => ['Якш', 'Душ', 'Сеш', 'Чор', 'Пай', 'Жум', 'Шан'], + 'weekdays_min' => ['Якш', 'Душ', 'Сеш', 'Чор', 'Пай', 'Жум', 'Шан'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai.php new file mode 100644 index 0000000..3c378df --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai.php @@ -0,0 +1,35 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['ꕞꕌꔵ', 'ꗳꗡꘉ', 'ꕚꕞꕚ', 'ꕉꕞꕒ', 'ꕉꔤꕆꕢ', 'ꕉꔤꕀꕮ', 'ꔻꔬꔳ'], + 'weekdays_short' => ['ꕞꕌꔵ', 'ꗳꗡꘉ', 'ꕚꕞꕚ', 'ꕉꕞꕒ', 'ꕉꔤꕆꕢ', 'ꕉꔤꕀꕮ', 'ꔻꔬꔳ'], + 'weekdays_min' => ['ꕞꕌꔵ', 'ꗳꗡꘉ', 'ꕚꕞꕚ', 'ꕉꕞꕒ', 'ꕉꔤꕆꕢ', 'ꕉꔤꕀꕮ', 'ꔻꔬꔳ'], + 'months' => ['ꖨꖕ ꕪꕴ ꔞꔀꕮꕊ', 'ꕒꕡꖝꖕ', 'ꕾꖺ', 'ꖢꖕ', 'ꖑꕱ', 'ꖱꘋ', 'ꖱꕞꔤ', 'ꗛꔕ', 'ꕢꕌ', 'ꕭꖃ', 'ꔞꘋꕔꕿ ꕸꖃꗏ', 'ꖨꖕ ꕪꕴ ꗏꖺꕮꕊ'], + 'months_short' => ['ꖨꖕꔞ', 'ꕒꕡ', 'ꕾꖺ', 'ꖢꖕ', 'ꖑꕱ', 'ꖱꘋ', 'ꖱꕞ', 'ꗛꔕ', 'ꕢꕌ', 'ꕭꖃ', 'ꔞꘋ', 'ꖨꖕꗏ'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd, D MMMM YYYY h:mm a', + ], + + 'year' => ':count ꕀ', // less reliable + 'y' => ':count ꕀ', // less reliable + 'a_year' => ':count ꕀ', // less reliable + + 'second' => ':count ꗱꕞꕯꕊ', // less reliable + 's' => ':count ꗱꕞꕯꕊ', // less reliable + 'a_second' => ':count ꗱꕞꕯꕊ', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai_Latn.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai_Latn.php new file mode 100644 index 0000000..51e83cc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai_Latn.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'weekdays' => ['lahadi', 'tɛɛnɛɛ', 'talata', 'alaba', 'aimisa', 'aijima', 'siɓiti'], + 'weekdays_short' => ['lahadi', 'tɛɛnɛɛ', 'talata', 'alaba', 'aimisa', 'aijima', 'siɓiti'], + 'weekdays_min' => ['lahadi', 'tɛɛnɛɛ', 'talata', 'alaba', 'aimisa', 'aijima', 'siɓiti'], + 'months' => ['luukao kemã', 'ɓandaɓu', 'vɔɔ', 'fulu', 'goo', '6', '7', 'kɔnde', 'saah', 'galo', 'kenpkato ɓololɔ', 'luukao lɔma'], + 'months_short' => ['luukao kemã', 'ɓandaɓu', 'vɔɔ', 'fulu', 'goo', '6', '7', 'kɔnde', 'saah', 'galo', 'kenpkato ɓololɔ', 'luukao lɔma'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'h:mm a', + 'LTS' => 'h:mm:ss a', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm a', + 'LLLL' => 'dddd, D MMMM YYYY h:mm a', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai_Vaii.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai_Vaii.php new file mode 100644 index 0000000..b4bb533 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vai_Vaii.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/vai.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ve.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ve.php new file mode 100644 index 0000000..7f10aeb --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ve.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/ve_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ve_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ve_ZA.php new file mode 100644 index 0000000..5eb2b91 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/ve_ZA.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Phando', 'Luhuhi', 'Ṱhafamuhwe', 'Lambamai', 'Shundunthule', 'Fulwi', 'Fulwana', 'Ṱhangule', 'Khubvumedzi', 'Tshimedzi', 'Ḽara', 'Nyendavhusiku'], + 'months_short' => ['Pha', 'Luh', 'Fam', 'Lam', 'Shu', 'Lwi', 'Lwa', 'Ngu', 'Khu', 'Tsh', 'Ḽar', 'Nye'], + 'weekdays' => ['Swondaha', 'Musumbuluwo', 'Ḽavhuvhili', 'Ḽavhuraru', 'Ḽavhuṋa', 'Ḽavhuṱanu', 'Mugivhela'], + 'weekdays_short' => ['Swo', 'Mus', 'Vhi', 'Rar', 'ṋa', 'Ṱan', 'Mug'], + 'weekdays_min' => ['Swo', 'Mus', 'Vhi', 'Rar', 'ṋa', 'Ṱan', 'Mug'], + 'day_of_first_week_of_year' => 1, + + // Too unreliable + /* + 'day' => ':count vhege', // less reliable + 'd' => ':count vhege', // less reliable + 'a_day' => ':count vhege', // less reliable + + 'hour' => ':count watshi', // less reliable + 'h' => ':count watshi', // less reliable + 'a_hour' => ':count watshi', // less reliable + + 'minute' => ':count watshi', // less reliable + 'min' => ':count watshi', // less reliable + 'a_minute' => ':count watshi', // less reliable + + 'second' => ':count Mu', // less reliable + 's' => ':count Mu', // less reliable + 'a_second' => ':count Mu', // less reliable + + 'week' => ':count vhege', + 'w' => ':count vhege', + 'a_week' => ':count vhege', + */ +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vi.php new file mode 100644 index 0000000..73e2852 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vi.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Andre Polykanine A.K.A. Menelion Elensúlë + * - JD Isaacks + */ +return [ + 'year' => ':count năm', + 'a_year' => '{1}một năm|]1, Inf[:count năm', + 'y' => ':count năm', + 'month' => ':count tháng', + 'a_month' => '{1}một tháng|]1, Inf[:count tháng', + 'm' => ':count tháng', + 'week' => ':count tuần', + 'a_week' => '{1}một tuần|]1, Inf[:count tuần', + 'w' => ':count tuần', + 'day' => ':count ngày', + 'a_day' => '{1}một ngày|]1, Inf[:count ngày', + 'd' => ':count ngày', + 'hour' => ':count giờ', + 'a_hour' => '{1}một giờ|]1, Inf[:count giờ', + 'h' => ':count giờ', + 'minute' => ':count phút', + 'a_minute' => '{1}một phút|]1, Inf[:count phút', + 'min' => ':count phút', + 'second' => ':count giây', + 'a_second' => '{1}vài giây|]1, Inf[:count giây', + 's' => ':count giây', + 'ago' => ':time trước', + 'from_now' => ':time tới', + 'after' => ':time sau', + 'before' => ':time trước', + 'diff_now' => 'bây giờ', + 'diff_today' => 'Hôm', + 'diff_today_regexp' => 'Hôm(?:\\s+nay)?(?:\\s+lúc)?', + 'diff_yesterday' => 'Hôm qua', + 'diff_yesterday_regexp' => 'Hôm(?:\\s+qua)?(?:\\s+lúc)?', + 'diff_tomorrow' => 'Ngày mai', + 'diff_tomorrow_regexp' => 'Ngày(?:\\s+mai)?(?:\\s+lúc)?', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM [năm] YYYY', + 'LLL' => 'D MMMM [năm] YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM [năm] YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[Hôm nay lúc] LT', + 'nextDay' => '[Ngày mai lúc] LT', + 'nextWeek' => 'dddd [tuần tới lúc] LT', + 'lastDay' => '[Hôm qua lúc] LT', + 'lastWeek' => 'dddd [tuần trước lúc] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['SA', 'CH'], + 'months' => ['tháng 1', 'tháng 2', 'tháng 3', 'tháng 4', 'tháng 5', 'tháng 6', 'tháng 7', 'tháng 8', 'tháng 9', 'tháng 10', 'tháng 11', 'tháng 12'], + 'months_short' => ['Th01', 'Th02', 'Th03', 'Th04', 'Th05', 'Th06', 'Th07', 'Th08', 'Th09', 'Th10', 'Th11', 'Th12'], + 'weekdays' => ['chủ nhật', 'thứ hai', 'thứ ba', 'thứ tư', 'thứ năm', 'thứ sáu', 'thứ bảy'], + 'weekdays_short' => ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], + 'weekdays_min' => ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => [', ', ' và '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vi_VN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vi_VN.php new file mode 100644 index 0000000..18d8987 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vi_VN.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/vi.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vo.php new file mode 100644 index 0000000..e273033 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vo.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'months' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], + 'months_short' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY-MM-dd', + 'LL' => 'YYYY MMM D', + 'LLL' => 'YYYY MMMM D HH:mm', + 'LLLL' => 'YYYY MMMM D, dddd HH:mm', + ], + + 'year' => ':count yel', + 'y' => ':count yel', + 'a_year' => ':count yel', + + 'month' => ':count mul', + 'm' => ':count mul', + 'a_month' => ':count mul', + + 'week' => ':count vig', + 'w' => ':count vig', + 'a_week' => ':count vig', + + 'day' => ':count del', + 'd' => ':count del', + 'a_day' => ':count del', + + 'hour' => ':count düp', + 'h' => ':count düp', + 'a_hour' => ':count düp', + + 'minute' => ':count minut', + 'min' => ':count minut', + 'a_minute' => ':count minut', + + 'second' => ':count sekun', + 's' => ':count sekun', + 'a_second' => ':count sekun', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vun.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vun.php new file mode 100644 index 0000000..ed92e8e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/vun.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['utuko', 'kyiukonyi'], + 'weekdays' => ['Jumapilyi', 'Jumatatuu', 'Jumanne', 'Jumatanu', 'Alhamisi', 'Ijumaa', 'Jumamosi'], + 'weekdays_short' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'weekdays_min' => ['Jpi', 'Jtt', 'Jnn', 'Jtn', 'Alh', 'Iju', 'Jmo'], + 'months' => ['Januari', 'Februari', 'Machi', 'Aprilyi', 'Mei', 'Junyi', 'Julyai', 'Agusti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wa.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wa.php new file mode 100644 index 0000000..f6dc4cc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wa.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/wa_BE.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wa_BE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wa_BE.php new file mode 100644 index 0000000..a76d80d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wa_BE.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Djan SACRE Pablo Saratxaga pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['di djanvî', 'di fevrî', 'di måss', 'd’ avri', 'di may', 'di djun', 'di djulete', 'd’ awousse', 'di setimbe', 'd’ octôbe', 'di nôvimbe', 'di decimbe'], + 'months_short' => ['dja', 'fev', 'mås', 'avr', 'may', 'djn', 'djl', 'awo', 'set', 'oct', 'nôv', 'dec'], + 'weekdays' => ['dimegne', 'londi', 'mårdi', 'mierkidi', 'djudi', 'vénrdi', 'semdi'], + 'weekdays_short' => ['dim', 'lon', 'mår', 'mie', 'dju', 'vén', 'sem'], + 'weekdays_min' => ['dim', 'lon', 'mår', 'mie', 'dju', 'vén', 'sem'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'year' => ':count anêye', + 'y' => ':count anêye', + 'a_year' => ':count anêye', + + 'month' => ':count meûs', + 'm' => ':count meûs', + 'a_month' => ':count meûs', + + 'week' => ':count samwinne', + 'w' => ':count samwinne', + 'a_week' => ':count samwinne', + + 'day' => ':count djoû', + 'd' => ':count djoû', + 'a_day' => ':count djoû', + + 'hour' => ':count eure', + 'h' => ':count eure', + 'a_hour' => ':count eure', + + 'minute' => ':count munute', + 'min' => ':count munute', + 'a_minute' => ':count munute', + + 'second' => ':count Sigonde', + 's' => ':count Sigonde', + 'a_second' => ':count Sigonde', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wae.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wae.php new file mode 100644 index 0000000..bf57f23 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wae.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/wae_CH.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wae_CH.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wae_CH.php new file mode 100644 index 0000000..2af50b4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wae_CH.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Walser Translation Team ml@translate-wae.ch + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], + 'months' => ['Jenner', 'Hornig', 'Märze', 'Abrille', 'Meije', 'Bráčet', 'Heiwet', 'Öigšte', 'Herbštmánet', 'Wímánet', 'Wintermánet', 'Chrištmánet'], + 'months_short' => ['Jen', 'Hor', 'Mär', 'Abr', 'Mei', 'Brá', 'Hei', 'Öig', 'Her', 'Wím', 'Win', 'Chr'], + 'weekdays' => ['Suntag', 'Mäntag', 'Zischtag', 'Mittwuch', 'Frontag', 'Fritag', 'Samschtag'], + 'weekdays_short' => ['Sun', 'Män', 'Zis', 'Mit', 'Fro', 'Fri', 'Sam'], + 'weekdays_min' => ['Sun', 'Män', 'Zis', 'Mit', 'Fro', 'Fri', 'Sam'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + + 'month' => ':count Maano', // less reliable + 'm' => ':count Maano', // less reliable + 'a_month' => ':count Maano', // less reliable +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wal.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wal.php new file mode 100644 index 0000000..e8ec40f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wal.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/wal_ET.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wal_ET.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wal_ET.php new file mode 100644 index 0000000..a4e619a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wal_ET.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Ge'ez Frontier Foundation locales@geez.org + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር'], + 'months_short' => ['ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም'], + 'weekdays' => ['ወጋ', 'ሳይኖ', 'ማቆሳኛ', 'አሩዋ', 'ሃሙሳ', 'አርባ', 'ቄራ'], + 'weekdays_short' => ['ወጋ ', 'ሳይኖ', 'ማቆሳ', 'አሩዋ', 'ሃሙሳ', 'አርባ', 'ቄራ '], + 'weekdays_min' => ['ወጋ ', 'ሳይኖ', 'ማቆሳ', 'አሩዋ', 'ሃሙሳ', 'አርባ', 'ቄራ '], + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['ማለዶ', 'ቃማ'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wo.php new file mode 100644 index 0000000..74b95df --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wo.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/wo_SN.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wo_SN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wo_SN.php new file mode 100644 index 0000000..f8a85b3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/wo_SN.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - The Debian Project Christian Perrier bubulle@debian.org + */ +return [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'MMMM DD, YYYY', + 'LLL' => 'DD MMM HH:mm', + 'LLLL' => 'MMMM DD, YYYY HH:mm', + ], + 'months' => ['sanwiy\'e', 'feebriy\'e', 'mars', 'awril', 'me', 'suwen', 'sulet', 'uut', 'septaambar', 'oktoobar', 'nowaambar', 'desaambar'], + 'months_short' => ['san', 'fee', 'mar', 'awr', 'me ', 'suw', 'sul', 'uut', 'sep', 'okt', 'now', 'des'], + 'weekdays' => ['dib\'eer', 'altine', 'talaata', 'allarba', 'alxames', 'ajjuma', 'gaawu'], + 'weekdays_short' => ['dib', 'alt', 'tal', 'all', 'alx', 'ajj', 'gaa'], + 'weekdays_min' => ['dib', 'alt', 'tal', 'all', 'alx', 'ajj', 'gaa'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'year' => ':count at', + 'month' => ':count wèr', + 'week' => ':count ayubés', + 'day' => ':count bés', + 'hour' => ':count waxtu', + 'minute' => ':count simili', + 'second' => ':count saa', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xh.php new file mode 100644 index 0000000..e88c78d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xh.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/xh_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xh_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xh_ZA.php new file mode 100644 index 0000000..910f831 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xh_ZA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['eyoMqungu', 'eyoMdumba', 'eyoKwindla', 'uTshazimpuzi', 'uCanzibe', 'eyeSilimela', 'eyeKhala', 'eyeThupa', 'eyoMsintsi', 'eyeDwarha', 'eyeNkanga', 'eyoMnga'], + 'months_short' => ['Mqu', 'Mdu', 'Kwi', 'Tsh', 'Can', 'Sil', 'Kha', 'Thu', 'Msi', 'Dwa', 'Nka', 'Mng'], + 'weekdays' => ['iCawa', 'uMvulo', 'lwesiBini', 'lwesiThathu', 'ulweSine', 'lwesiHlanu', 'uMgqibelo'], + 'weekdays_short' => ['Caw', 'Mvu', 'Bin', 'Tha', 'Sin', 'Hla', 'Mgq'], + 'weekdays_min' => ['Caw', 'Mvu', 'Bin', 'Tha', 'Sin', 'Hla', 'Mgq'], + 'day_of_first_week_of_year' => 1, + + 'year' => ':count ihlobo', // less reliable + 'y' => ':count ihlobo', // less reliable + 'a_year' => ':count ihlobo', // less reliable + + 'hour' => ':count iwotshi', // less reliable + 'h' => ':count iwotshi', // less reliable + 'a_hour' => ':count iwotshi', // less reliable + + 'minute' => ':count ingqalelo', // less reliable + 'min' => ':count ingqalelo', // less reliable + 'a_minute' => ':count ingqalelo', // less reliable + + 'second' => ':count nceda', // less reliable + 's' => ':count nceda', // less reliable + 'a_second' => ':count nceda', // less reliable + + 'month' => ':count inyanga', + 'm' => ':count inyanga', + 'a_month' => ':count inyanga', + + 'week' => ':count veki', + 'w' => ':count veki', + 'a_week' => ':count veki', + + 'day' => ':count imini', + 'd' => ':count imini', + 'a_day' => ':count imini', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xog.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xog.php new file mode 100644 index 0000000..eb55b4a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/xog.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['Munkyo', 'Eigulo'], + 'weekdays' => ['Sabiiti', 'Balaza', 'Owokubili', 'Owokusatu', 'Olokuna', 'Olokutaanu', 'Olomukaaga'], + 'weekdays_short' => ['Sabi', 'Bala', 'Kubi', 'Kusa', 'Kuna', 'Kuta', 'Muka'], + 'weekdays_min' => ['Sabi', 'Bala', 'Kubi', 'Kusa', 'Kuna', 'Kuta', 'Muka'], + 'months' => ['Janwaliyo', 'Febwaliyo', 'Marisi', 'Apuli', 'Maayi', 'Juuni', 'Julaayi', 'Agusito', 'Sebuttemba', 'Okitobba', 'Novemba', 'Desemba'], + 'months_short' => ['Jan', 'Feb', 'Mar', 'Apu', 'Maa', 'Juu', 'Jul', 'Agu', 'Seb', 'Oki', 'Nov', 'Des'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yav.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yav.php new file mode 100644 index 0000000..225a20d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yav.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/en.php', [ + 'meridiem' => ['kiɛmɛ́ɛm', 'kisɛ́ndɛ'], + 'weekdays' => ['sɔ́ndiɛ', 'móndie', 'muányáŋmóndie', 'metúkpíápɛ', 'kúpélimetúkpiapɛ', 'feléte', 'séselé'], + 'weekdays_short' => ['sd', 'md', 'mw', 'et', 'kl', 'fl', 'ss'], + 'weekdays_min' => ['sd', 'md', 'mw', 'et', 'kl', 'fl', 'ss'], + 'months' => ['pikítíkítie, oólí ú kutúan', 'siɛyɛ́, oóli ú kándíɛ', 'ɔnsúmbɔl, oóli ú kátátúɛ', 'mesiŋ, oóli ú kénie', 'ensil, oóli ú kátánuɛ', 'ɔsɔn', 'efute', 'pisuyú', 'imɛŋ i puɔs', 'imɛŋ i putúk,oóli ú kátíɛ', 'makandikɛ', 'pilɔndɔ́'], + 'months_short' => ['o.1', 'o.2', 'o.3', 'o.4', 'o.5', 'o.6', 'o.7', 'o.8', 'o.9', 'o.10', 'o.11', 'o.12'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yi.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yi.php new file mode 100644 index 0000000..8f32022 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yi.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/yi_US.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yi_US.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yi_US.php new file mode 100644 index 0000000..f764d36 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yi_US.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - http://www.uyip.org/ Pablo Saratxaga pablo@mandrakesoft.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['יאַנואַר', 'פֿעברואַר', 'מערץ', 'אַפּריל', 'מיי', 'יוני', 'יולי', 'אויגוסט', 'סעפּטעמבער', 'אקטאבער', 'נאוועמבער', 'דעצעמבער'], + 'months_short' => ['יאַנ', 'פֿעב', 'מאַר', 'אַפּר', 'מײַ ', 'יונ', 'יול', 'אױג', 'סעפּ', 'אָקט', 'נאָװ', 'דעצ'], + 'weekdays' => ['זונטיק', 'מאָנטיק', 'דינסטיק', 'מיטװאָך', 'דאָנערשטיק', 'פֿרײַטיק', 'שבת'], + 'weekdays_short' => ['זונ\'', 'מאָנ\'', 'דינ\'', 'מיט\'', 'דאָנ\'', 'פֿרײַ\'', 'שבת'], + 'weekdays_min' => ['זונ\'', 'מאָנ\'', 'דינ\'', 'מיט\'', 'דאָנ\'', 'פֿרײַ\'', 'שבת'], + 'day_of_first_week_of_year' => 1, + + 'year' => ':count יאר', + 'y' => ':count יאר', + 'a_year' => ':count יאר', + + 'month' => ':count חודש', + 'm' => ':count חודש', + 'a_month' => ':count חודש', + + 'week' => ':count וואָך', + 'w' => ':count וואָך', + 'a_week' => ':count וואָך', + + 'day' => ':count טאָג', + 'd' => ':count טאָג', + 'a_day' => ':count טאָג', + + 'hour' => ':count שעה', + 'h' => ':count שעה', + 'a_hour' => ':count שעה', + + 'minute' => ':count מינוט', + 'min' => ':count מינוט', + 'a_minute' => ':count מינוט', + + 'second' => ':count סעקונדע', + 's' => ':count סעקונדע', + 'a_second' => ':count סעקונדע', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo.php new file mode 100644 index 0000000..0a82981 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo.php @@ -0,0 +1,65 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - François B + * - Atolagbe Abisoye + */ +return [ + 'year' => 'ọdún :count', + 'a_year' => '{1}ọdún kan|ọdún :count', + 'month' => 'osù :count', + 'a_month' => '{1}osù kan|osù :count', + 'week' => 'ọsẹ :count', + 'a_week' => '{1}ọsẹ kan|ọsẹ :count', + 'day' => 'ọjọ́ :count', + 'a_day' => '{1}ọjọ́ kan|ọjọ́ :count', + 'hour' => 'wákati :count', + 'a_hour' => '{1}wákati kan|wákati :count', + 'minute' => 'ìsẹjú :count', + 'a_minute' => '{1}ìsẹjú kan|ìsẹjú :count', + 'second' => 'iaayá :count', + 'a_second' => '{1}ìsẹjú aayá die|aayá :count', + 'ago' => ':time kọjá', + 'from_now' => 'ní :time', + 'diff_yesterday' => 'Àna', + 'diff_yesterday_regexp' => 'Àna(?:\\s+ni)?', + 'diff_today' => 'Ònì', + 'diff_today_regexp' => 'Ònì(?:\\s+ni)?', + 'diff_tomorrow' => 'Ọ̀la', + 'diff_tomorrow_regexp' => 'Ọ̀la(?:\\s+ni)?', + 'formats' => [ + 'LT' => 'h:mm A', + 'LTS' => 'h:mm:ss A', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY h:mm A', + 'LLLL' => 'dddd, D MMMM YYYY h:mm A', + ], + 'calendar' => [ + 'sameDay' => '[Ònì ni] LT', + 'nextDay' => '[Ọ̀la ni] LT', + 'nextWeek' => 'dddd [Ọsẹ̀ tón\'bọ] [ni] LT', + 'lastDay' => '[Àna ni] LT', + 'lastWeek' => 'dddd [Ọsẹ̀ tólọ́] [ni] LT', + 'sameElse' => 'L', + ], + 'ordinal' => 'ọjọ́ :number', + 'months' => ['Sẹ́rẹ́', 'Èrèlè', 'Ẹrẹ̀nà', 'Ìgbé', 'Èbibi', 'Òkùdu', 'Agẹmo', 'Ògún', 'Owewe', 'Ọ̀wàrà', 'Bélú', 'Ọ̀pẹ̀̀'], + 'months_short' => ['Sẹ́r', 'Èrl', 'Ẹrn', 'Ìgb', 'Èbi', 'Òkù', 'Agẹ', 'Ògú', 'Owe', 'Ọ̀wà', 'Bél', 'Ọ̀pẹ̀̀'], + 'weekdays' => ['Àìkú', 'Ajé', 'Ìsẹ́gun', 'Ọjọ́rú', 'Ọjọ́bọ', 'Ẹtì', 'Àbámẹ́ta'], + 'weekdays_short' => ['Àìk', 'Ajé', 'Ìsẹ́', 'Ọjr', 'Ọjb', 'Ẹtì', 'Àbá'], + 'weekdays_min' => ['Àì', 'Aj', 'Ìs', 'Ọr', 'Ọb', 'Ẹt', 'Àb'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'meridiem' => ['Àárọ̀', 'Ọ̀sán'], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo_BJ.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo_BJ.php new file mode 100644 index 0000000..12b9e81 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo_BJ.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return array_replace_recursive(require __DIR__.'/yo.php', [ + 'meridiem' => ['Àárɔ̀', 'Ɔ̀sán'], + 'weekdays' => ['Ɔjɔ́ Àìkú', 'Ɔjɔ́ Ajé', 'Ɔjɔ́ Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɔjɔ́ Ɛtì', 'Ɔjɔ́ Àbámɛ́ta'], + 'weekdays_short' => ['Àìkú', 'Ajé', 'Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɛtì', 'Àbámɛ́ta'], + 'weekdays_min' => ['Àìkú', 'Ajé', 'Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɛtì', 'Àbámɛ́ta'], + 'months' => ['Oshù Shɛ́rɛ́', 'Oshù Èrèlè', 'Oshù Ɛrɛ̀nà', 'Oshù Ìgbé', 'Oshù Ɛ̀bibi', 'Oshù Òkúdu', 'Oshù Agɛmɔ', 'Oshù Ògún', 'Oshù Owewe', 'Oshù Ɔ̀wàrà', 'Oshù Bélú', 'Oshù Ɔ̀pɛ̀'], + 'months_short' => ['Shɛ́rɛ́', 'Èrèlè', 'Ɛrɛ̀nà', 'Ìgbé', 'Ɛ̀bibi', 'Òkúdu', 'Agɛmɔ', 'Ògún', 'Owewe', 'Ɔ̀wàrà', 'Bélú', 'Ɔ̀pɛ̀'], + 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd, D MMMM YYYY HH:mm', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo_NG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo_NG.php new file mode 100644 index 0000000..6860bc1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yo_NG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/yo.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue.php new file mode 100644 index 0000000..ce233a4 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/yue_HK.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_HK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_HK.php new file mode 100644 index 0000000..4e7d5c3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_HK.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/zh_HK.php', [ + 'formats' => [ + 'L' => 'YYYY年MM月DD日 dddd', + ], + 'months' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], + 'months_short' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], + 'weekdays' => ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], + 'weekdays_short' => ['日', '一', '二', '三', '四', '五', '六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'first_day_of_week' => 0, + 'day_of_first_week_of_year' => 1, + 'meridiem' => ['上午', '下午'], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_Hans.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_Hans.php new file mode 100644 index 0000000..db913ca --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_Hans.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hans.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_Hant.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_Hant.php new file mode 100644 index 0000000..e2526f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yue_Hant.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hant.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yuw.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yuw.php new file mode 100644 index 0000000..8efdc93 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yuw.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/yuw_PG.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yuw_PG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yuw_PG.php new file mode 100644 index 0000000..b99ad2e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/yuw_PG.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Information from native speakers Hannah Sarvasy nungon.localization@gmail.com + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YY', + ], + 'months' => ['jenuari', 'febuari', 'mas', 'epril', 'mei', 'jun', 'julai', 'ögus', 'septemba', 'öktoba', 'nöwemba', 'diksemba'], + 'months_short' => ['jen', 'feb', 'mas', 'epr', 'mei', 'jun', 'jul', 'ögu', 'sep', 'ökt', 'nöw', 'dis'], + 'weekdays' => ['sönda', 'mönda', 'sinda', 'mitiwö', 'sogipbono', 'nenggo', 'söndanggie'], + 'weekdays_short' => ['sön', 'mön', 'sin', 'mit', 'soi', 'nen', 'sab'], + 'weekdays_min' => ['sön', 'mön', 'sin', 'mit', 'soi', 'nen', 'sab'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zgh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zgh.php new file mode 100644 index 0000000..4d2c3b3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zgh.php @@ -0,0 +1,80 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - BAKTETE Miloud + */ +return [ + 'year' => ':count ⵓⵙⴳⴳⵯⴰⵙ|:count ⵉⵙⴳⴳⵓⵙⴰ', + 'a_year' => 'ⵓⵙⴳⴳⵯⴰⵙ|:count ⵉⵙⴳⴳⵓⵙⴰ', + 'y' => ':count ⵓⵙⴳⴳⵯⴰⵙ|:count ⵉⵙⴳⴳⵓⵙⴰ', + 'month' => ':count ⵡⴰⵢⵢⵓⵔ|:count ⴰⵢⵢⵓⵔⵏ', + 'a_month' => 'ⵉⴷⵊ ⵡⴰⵢⵢⵓⵔ|:count ⴰⵢⵢⵓⵔⵏ', + 'm' => ':count ⴰⵢⵢⵓⵔⵏ', + 'week' => ':count ⵉⵎⴰⵍⴰⵙⵙ|:count ⵉⵎⴰⵍⴰⵙⵙⵏ', + 'a_week' => 'ⵉⵛⵜ ⵉⵎⴰⵍⴰⵙⵙ|:count ⵉⵎⴰⵍⴰⵙⵙⵏ', + 'w' => ':count ⵉⵎⴰⵍⴰⵙⵙ.', + 'day' => ':count ⵡⴰⵙⵙ|:count ⵓⵙⵙⴰⵏ', + 'a_day' => 'ⵉⴷⵊ ⵡⴰⵙⵙ|:count ⵓⵙⵙⴰⵏ', + 'd' => ':count ⵓ', + 'hour' => ':count ⵜⵙⵔⴰⴳⵜ|:count ⵜⵉⵙⵔⴰⴳⵉⵏ', + 'a_hour' => 'ⵉⵛⵜ ⵜⵙⵔⴰⴳⵜ|:count ⵜⵉⵙⵔⴰⴳⵉⵏ', + 'h' => ':count ⵜ', + 'minute' => ':count ⵜⵓⵙⴷⵉⴷⵜ|:count ⵜⵓⵙⴷⵉⴷⵉⵏ', + 'a_minute' => 'ⵉⵛⵜ ⵜⵓⵙⴷⵉⴷⵜ|:count ⵜⵓⵙⴷⵉⴷⵉⵏ', + 'min' => ':count ⵜⵓⵙ', + 'second' => ':count ⵜⵙⵉⵏⵜ|:count ⵜⵉⵙⵉⵏⴰ', + 'a_second' => 'ⴽⵔⴰ ⵜⵉⵙⵉⵏⴰ|:count ⵜⵉⵙⵉⵏⴰ', + 's' => ':count ⵜ', + 'ago' => 'ⵣⴳ :time', + 'from_now' => 'ⴷⴳ :time', + 'after' => ':time ⴰⵡⴰⵔ', + 'before' => ':time ⴷⴰⵜ', + 'diff_now' => 'ⴰⴷⵡⴰⵍⵉ', + 'diff_today' => 'ⴰⵙⵙ', + 'diff_today_regexp' => 'ⴰⵙⵙ(?:\\s+ⴰ/ⴰⴷ)?(?:\\s+ⴳ)?', + 'diff_yesterday' => 'ⴰⵙⵙⵏⵏⴰⵟ', + 'diff_yesterday_regexp' => 'ⴰⵙⵙⵏⵏⴰⵟ(?:\\s+ⴳ)?', + 'diff_tomorrow' => 'ⴰⵙⴽⴽⴰ', + 'diff_tomorrow_regexp' => 'ⴰⵙⴽⴽⴰ(?:\\s+ⴳ)?', + 'diff_before_yesterday' => 'ⴼⵔ ⵉⴹⵏⵏⴰⵟ', + 'diff_after_tomorrow' => 'ⵏⴰⴼ ⵓⵙⴽⴽⴰ', + 'period_recurrences' => ':count ⵜⵉⴽⴽⴰⵍ', + 'period_interval' => 'ⴽⵓ :interval', + 'period_start_date' => 'ⴳ :date', + 'period_end_date' => 'ⵉ :date', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD/MM/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[ⴰⵙⵙ ⴰ/ⴰⴷ ⴳ] LT', + 'nextDay' => '[ⴰⵙⴽⴽⴰ ⴳ] LT', + 'nextWeek' => 'dddd [ⴳ] LT', + 'lastDay' => '[ⴰⵙⵙⵏⵏⴰⵟ ⴳ] LT', + 'lastWeek' => 'dddd [ⴰⵎⴳⴳⴰⵔⵓ ⴳ] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['ⵜⵉⴼⴰⵡⵜ', 'ⵜⴰⴷⴳⴳⵯⴰⵜ'], + 'months' => ['ⵉⵏⵏⴰⵢⵔ', 'ⴱⵕⴰⵢⵕ', 'ⵎⴰⵕⵚ', 'ⵉⴱⵔⵉⵔ', 'ⵎⴰⵢⵢⵓ', 'ⵢⵓⵏⵢⵓ', 'ⵢⵓⵍⵢⵓⵣ', 'ⵖⵓⵛⵜ', 'ⵛⵓⵜⴰⵏⴱⵉⵔ', 'ⴽⵟⵓⴱⵕ', 'ⵏⵓⵡⴰⵏⴱⵉⵔ', 'ⴷⵓⵊⴰⵏⴱⵉⵔ'], + 'months_short' => ['ⵉⵏⵏ', 'ⴱⵕⴰ', 'ⵎⴰⵕ', 'ⵉⴱⵔ', 'ⵎⴰⵢ', 'ⵢⵓⵏ', 'ⵢⵓⵍ', 'ⵖⵓⵛ', 'ⵛⵓⵜ', 'ⴽⵟⵓ', 'ⵏⵓⵡ', 'ⴷⵓⵊ'], + 'weekdays' => ['ⵓⵙⴰⵎⴰⵙ', 'ⵡⴰⵢⵏⴰⵙ', 'ⵓⵙⵉⵏⴰⵙ', 'ⵡⴰⴽⵕⴰⵙ', 'ⵓⴽⵡⴰⵙ', 'ⵓⵙⵉⵎⵡⴰⵙ', 'ⵓⵙⵉⴹⵢⴰⵙ'], + 'weekdays_short' => ['ⵓⵙⴰ', 'ⵡⴰⵢ', 'ⵓⵙⵉ', 'ⵡⴰⴽ', 'ⵓⴽⵡ', 'ⵓⵙⵉⵎ', 'ⵓⵙⵉⴹ'], + 'weekdays_min' => ['ⵓⵙⴰ', 'ⵡⴰⵢ', 'ⵓⵙⵉ', 'ⵡⴰⴽ', 'ⵓⴽⵡ', 'ⵓⵙⵉⵎ', 'ⵓⵙⵉⴹ'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 1, + 'list' => [', ', ' ⴷ '], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh.php new file mode 100644 index 0000000..1187c3d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - xuri + * - sycuato + * - bokideckonja + * - Luo Ning + * - William Yang (williamyang233) + */ +return array_merge(require __DIR__.'/zh_Hans.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY/MM/DD', + 'LL' => 'YYYY年M月D日', + 'LLL' => 'YYYY年M月D日 A h点mm分', + 'LLLL' => 'YYYY年M月D日dddd A h点mm分', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_CN.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_CN.php new file mode 100644 index 0000000..9c05d5a --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_CN.php @@ -0,0 +1,33 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - monkeycon + * - François B + * - Jason Katz-Brown + * - Serhan Apaydın + * - Matt Johnson + * - JD Isaacks + * - Zeno Zeng + * - Chris Hemp + * - shankesgk2 + */ +return array_merge(require __DIR__.'/zh.php', [ + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY/MM/DD', + 'LL' => 'YYYY年M月D日', + 'LLL' => 'YYYY年M月D日Ah点mm分', + 'LLLL' => 'YYYY年M月D日ddddAh点mm分', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_HK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_HK.php new file mode 100644 index 0000000..c3ee9fc --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_HK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hant_HK.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans.php new file mode 100644 index 0000000..9b91785 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans.php @@ -0,0 +1,109 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - monkeycon + * - François B + * - Jason Katz-Brown + * - Konstantin Konev + * - Chris Lam + * - Serhan Apaydın + * - Gary Lo + * - JD Isaacks + * - Chris Hemp + * - shankesgk2 + * - Daniel Cheung (danvim) + */ +return [ + 'year' => ':count:optional-space年', + 'y' => ':count:optional-space年', + 'month' => ':count:optional-space个月', + 'm' => ':count:optional-space个月', + 'week' => ':count:optional-space周', + 'w' => ':count:optional-space周', + 'day' => ':count:optional-space天', + 'd' => ':count:optional-space天', + 'hour' => ':count:optional-space小时', + 'h' => ':count:optional-space小时', + 'minute' => ':count:optional-space分钟', + 'min' => ':count:optional-space分钟', + 'second' => ':count:optional-space秒', + 'a_second' => '{1}几秒|]1,Inf[:count:optional-space秒', + 's' => ':count:optional-space秒', + 'ago' => ':time前', + 'from_now' => ':time后', + 'after' => ':time后', + 'before' => ':time前', + 'diff_now' => '现在', + 'diff_today' => '今天', + 'diff_yesterday' => '昨天', + 'diff_tomorrow' => '明天', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY/MM/DD', + 'LL' => 'YYYY年M月D日', + 'LLL' => 'YYYY年M月D日 HH:mm', + 'LLLL' => 'YYYY年M月D日dddd HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[今天]LT', + 'nextDay' => '[明天]LT', + 'nextWeek' => '[下]ddddLT', + 'lastDay' => '[昨天]LT', + 'lastWeek' => '[上]ddddLT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'd': + case 'D': + case 'DDD': + return $number.'日'; + case 'M': + return $number.'月'; + case 'w': + case 'W': + return $number.'周'; + default: + return $number; + } + }, + 'meridiem' => function ($hour, $minute) { + $time = $hour * 100 + $minute; + if ($time < 600) { + return '凌晨'; + } + if ($time < 900) { + return '早上'; + } + if ($time < 1130) { + return '上午'; + } + if ($time < 1230) { + return '中午'; + } + if ($time < 1800) { + return '下午'; + } + + return '晚上'; + }, + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], + 'weekdays' => ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], + 'weekdays_short' => ['周日', '周一', '周二', '周三', '周四', '周五', '周六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => '', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_HK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_HK.php new file mode 100644 index 0000000..db913ca --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_HK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hans.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_MO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_MO.php new file mode 100644 index 0000000..db913ca --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_MO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hans.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_SG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_SG.php new file mode 100644 index 0000000..db913ca --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hans_SG.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hans.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant.php new file mode 100644 index 0000000..a27b610 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant.php @@ -0,0 +1,111 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Adam + * - monkeycon + * - François B + * - Jason Katz-Brown + * - Chris Lam + * - Serhan Apaydın + * - Gary Lo + * - JD Isaacks + * - Chris Hemp + * - Eddie + * - KID + * - shankesgk2 + * - Daniel Cheung (danvim) + */ +return [ + 'year' => ':count:optional-space年', + 'y' => ':count:optional-space年', + 'month' => ':count:optional-space個月', + 'm' => ':count:optional-space月', + 'week' => ':count:optional-space週', + 'w' => ':count:optional-space週', + 'day' => ':count:optional-space天', + 'd' => ':count:optional-space天', + 'hour' => ':count:optional-space小時', + 'h' => ':count:optional-space小時', + 'minute' => ':count:optional-space分鐘', + 'min' => ':count:optional-space分鐘', + 'second' => ':count:optional-space秒', + 'a_second' => '{1}幾秒|]1,Inf[:count:optional-space秒', + 's' => ':count:optional-space秒', + 'ago' => ':time前', + 'from_now' => ':time後', + 'after' => ':time後', + 'before' => ':time前', + 'diff_now' => '現在', + 'diff_today' => '今天', + 'diff_yesterday' => '昨天', + 'diff_tomorrow' => '明天', + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'YYYY/MM/DD', + 'LL' => 'YYYY年M月D日', + 'LLL' => 'YYYY年M月D日 HH:mm', + 'LLLL' => 'YYYY年M月D日dddd HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[今天] LT', + 'nextDay' => '[明天] LT', + 'nextWeek' => '[下]dddd LT', + 'lastDay' => '[昨天] LT', + 'lastWeek' => '[上]dddd LT', + 'sameElse' => 'L', + ], + 'ordinal' => function ($number, $period) { + switch ($period) { + case 'd': + case 'D': + case 'DDD': + return $number.'日'; + case 'M': + return $number.'月'; + case 'w': + case 'W': + return $number.'周'; + default: + return $number; + } + }, + 'meridiem' => function ($hour, $minute) { + $time = $hour * 100 + $minute; + if ($time < 600) { + return '凌晨'; + } + if ($time < 900) { + return '早上'; + } + if ($time < 1130) { + return '上午'; + } + if ($time < 1230) { + return '中午'; + } + if ($time < 1800) { + return '下午'; + } + + return '晚上'; + }, + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], + 'weekdays' => ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], + 'weekdays_short' => ['週日', '週一', '週二', '週三', '週四', '週五', '週六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'first_day_of_week' => 1, + 'day_of_first_week_of_year' => 4, + 'list' => '', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_HK.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_HK.php new file mode 100644 index 0000000..e2526f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_HK.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hant.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_MO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_MO.php new file mode 100644 index 0000000..e2526f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_MO.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hant.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_TW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_TW.php new file mode 100644 index 0000000..e2526f1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_Hant_TW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hant.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_MO.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_MO.php new file mode 100644 index 0000000..1c86d47 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_MO.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - tarunvelli + * - Eddie + * - KID + * - shankesgk2 + */ +return array_replace_recursive(require __DIR__.'/zh_Hant.php', [ + 'after' => ':time后', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_SG.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_SG.php new file mode 100644 index 0000000..c451a56 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_SG.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/zh.php', [ + 'formats' => [ + 'L' => 'YYYY年MM月DD日', + ], + 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'months_short' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], + 'weekdays' => ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], + 'weekdays_short' => ['日', '一', '二', '三', '四', '五', '六'], + 'weekdays_min' => ['日', '一', '二', '三', '四', '五', '六'], + 'day_of_first_week_of_year' => 1, +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_TW.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_TW.php new file mode 100644 index 0000000..c6789ed --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_TW.php @@ -0,0 +1,12 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return require __DIR__.'/zh_Hant_TW.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_YUE.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_YUE.php new file mode 100644 index 0000000..b0d9ba8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zh_YUE.php @@ -0,0 +1,20 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + */ +return array_replace_recursive(require __DIR__.'/zh.php', [ + 'formats' => [ + 'L' => 'YYYY-MM-DD', + ], +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zu.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zu.php new file mode 100644 index 0000000..9a6cce0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zu.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Unknown default region, use the first alphabetically. + */ +return require __DIR__.'/zu_ZA.php'; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zu_ZA.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zu_ZA.php new file mode 100644 index 0000000..6bfb72f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Lang/zu_ZA.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Zuza Software Foundation (Translate.org.za) Dwayne Bailey dwayne@translate.org.za + */ +return array_replace_recursive(require __DIR__.'/en.php', [ + 'formats' => [ + 'L' => 'DD/MM/YYYY', + ], + 'months' => ['Januwari', 'Februwari', 'Mashi', 'Ephreli', 'Meyi', 'Juni', 'Julayi', 'Agasti', 'Septhemba', 'Okthoba', 'Novemba', 'Disemba'], + 'months_short' => ['Jan', 'Feb', 'Mas', 'Eph', 'Mey', 'Jun', 'Jul', 'Aga', 'Sep', 'Okt', 'Nov', 'Dis'], + 'weekdays' => ['iSonto', 'uMsombuluko', 'uLwesibili', 'uLwesithathu', 'uLwesine', 'uLwesihlanu', 'uMgqibelo'], + 'weekdays_short' => ['Son', 'Mso', 'Bil', 'Tha', 'Sin', 'Hla', 'Mgq'], + 'weekdays_min' => ['Son', 'Mso', 'Bil', 'Tha', 'Sin', 'Hla', 'Mgq'], + 'day_of_first_week_of_year' => 1, + + 'year' => 'kweminyaka engu-:count', + 'y' => 'kweminyaka engu-:count', + 'a_year' => 'kweminyaka engu-:count', + + 'month' => 'izinyanga ezingu-:count', + 'm' => 'izinyanga ezingu-:count', + 'a_month' => 'izinyanga ezingu-:count', + + 'week' => 'lwamasonto angu-:count', + 'w' => 'lwamasonto angu-:count', + 'a_week' => 'lwamasonto angu-:count', + + 'day' => 'ezingaba ngu-:count', + 'd' => 'ezingaba ngu-:count', + 'a_day' => 'ezingaba ngu-:count', + + 'hour' => 'amahora angu-:count', + 'h' => 'amahora angu-:count', + 'a_hour' => 'amahora angu-:count', + + 'minute' => 'ngemizuzu engu-:count', + 'min' => 'ngemizuzu engu-:count', + 'a_minute' => 'ngemizuzu engu-:count', + + 'second' => 'imizuzwana engu-:count', + 's' => 'imizuzwana engu-:count', + 'a_second' => 'imizuzwana engu-:count', +]); diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Language.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Language.php new file mode 100644 index 0000000..1fb5baf --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Language.php @@ -0,0 +1,342 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use JsonSerializable; +use ReturnTypeWillChange; + +class Language implements JsonSerializable +{ + /** + * @var array + */ + protected static $languagesNames; + + /** + * @var array + */ + protected static $regionsNames; + + /** + * @var string + */ + protected $id; + + /** + * @var string + */ + protected $code; + + /** + * @var string|null + */ + protected $variant; + + /** + * @var string|null + */ + protected $region; + + /** + * @var array + */ + protected $names; + + /** + * @var string + */ + protected $isoName; + + /** + * @var string + */ + protected $nativeName; + + public function __construct(string $id) + { + $this->id = str_replace('-', '_', $id); + $parts = explode('_', $this->id); + $this->code = $parts[0]; + + if (isset($parts[1])) { + if (!preg_match('/^[A-Z]+$/', $parts[1])) { + $this->variant = $parts[1]; + $parts[1] = $parts[2] ?? null; + } + if ($parts[1]) { + $this->region = $parts[1]; + } + } + } + + /** + * Get the list of the known languages. + * + * @return array + */ + public static function all() + { + if (!static::$languagesNames) { + static::$languagesNames = require __DIR__.'/List/languages.php'; + } + + return static::$languagesNames; + } + + /** + * Get the list of the known regions. + * + * @return array + */ + public static function regions() + { + if (!static::$regionsNames) { + static::$regionsNames = require __DIR__.'/List/regions.php'; + } + + return static::$regionsNames; + } + + /** + * Get both isoName and nativeName as an array. + * + * @return array + */ + public function getNames(): array + { + if (!$this->names) { + $this->names = static::all()[$this->code] ?? [ + 'isoName' => $this->code, + 'nativeName' => $this->code, + ]; + } + + return $this->names; + } + + /** + * Returns the original locale ID. + * + * @return string + */ + public function getId(): string + { + return $this->id; + } + + /** + * Returns the code of the locale "en"/"fr". + * + * @return string + */ + public function getCode(): string + { + return $this->code; + } + + /** + * Returns the variant code such as cyrl/latn. + * + * @return string|null + */ + public function getVariant(): ?string + { + return $this->variant; + } + + /** + * Returns the variant such as Cyrillic/Latin. + * + * @return string|null + */ + public function getVariantName(): ?string + { + if ($this->variant === 'Latn') { + return 'Latin'; + } + + if ($this->variant === 'Cyrl') { + return 'Cyrillic'; + } + + return $this->variant; + } + + /** + * Returns the region part of the locale. + * + * @return string|null + */ + public function getRegion(): ?string + { + return $this->region; + } + + /** + * Returns the region name for the current language. + * + * @return string|null + */ + public function getRegionName(): ?string + { + return $this->region ? (static::regions()[$this->region] ?? $this->region) : null; + } + + /** + * Returns the long ISO language name. + * + * @return string + */ + public function getFullIsoName(): string + { + if (!$this->isoName) { + $this->isoName = $this->getNames()['isoName']; + } + + return $this->isoName; + } + + /** + * Set the ISO language name. + * + * @param string $isoName + */ + public function setIsoName(string $isoName): self + { + $this->isoName = $isoName; + + return $this; + } + + /** + * Return the full name of the language in this language. + * + * @return string + */ + public function getFullNativeName(): string + { + if (!$this->nativeName) { + $this->nativeName = $this->getNames()['nativeName']; + } + + return $this->nativeName; + } + + /** + * Set the name of the language in this language. + * + * @param string $nativeName + */ + public function setNativeName(string $nativeName): self + { + $this->nativeName = $nativeName; + + return $this; + } + + /** + * Returns the short ISO language name. + * + * @return string + */ + public function getIsoName(): string + { + $name = $this->getFullIsoName(); + + return trim(strstr($name, ',', true) ?: $name); + } + + /** + * Get the short name of the language in this language. + * + * @return string + */ + public function getNativeName(): string + { + $name = $this->getFullNativeName(); + + return trim(strstr($name, ',', true) ?: $name); + } + + /** + * Get a string with short ISO name, region in parentheses if applicable, variant in parentheses if applicable. + * + * @return string + */ + public function getIsoDescription() + { + $region = $this->getRegionName(); + $variant = $this->getVariantName(); + + return $this->getIsoName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); + } + + /** + * Get a string with short native name, region in parentheses if applicable, variant in parentheses if applicable. + * + * @return string + */ + public function getNativeDescription() + { + $region = $this->getRegionName(); + $variant = $this->getVariantName(); + + return $this->getNativeName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); + } + + /** + * Get a string with long ISO name, region in parentheses if applicable, variant in parentheses if applicable. + * + * @return string + */ + public function getFullIsoDescription() + { + $region = $this->getRegionName(); + $variant = $this->getVariantName(); + + return $this->getFullIsoName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); + } + + /** + * Get a string with long native name, region in parentheses if applicable, variant in parentheses if applicable. + * + * @return string + */ + public function getFullNativeDescription() + { + $region = $this->getRegionName(); + $variant = $this->getVariantName(); + + return $this->getFullNativeName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); + } + + /** + * Returns the original locale ID. + * + * @return string + */ + public function __toString() + { + return $this->getId(); + } + + /** + * Get a string with short ISO name, region in parentheses if applicable, variant in parentheses if applicable. + * + * @return string + */ + #[ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->getIsoDescription(); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php new file mode 100644 index 0000000..84e241e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php @@ -0,0 +1,127 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Laravel; + +use Carbon\Carbon; +use Carbon\CarbonImmutable; +use Carbon\CarbonInterval; +use Carbon\CarbonPeriod; +use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; +use Illuminate\Events\Dispatcher; +use Illuminate\Events\EventDispatcher; +use Illuminate\Support\Carbon as IlluminateCarbon; +use Illuminate\Support\Facades\Date; +use Throwable; + +class ServiceProvider extends \Illuminate\Support\ServiceProvider +{ + /** @var callable|null */ + protected $appGetter = null; + + /** @var callable|null */ + protected $localeGetter = null; + + public function setAppGetter(?callable $appGetter): void + { + $this->appGetter = $appGetter; + } + + public function setLocaleGetter(?callable $localeGetter): void + { + $this->localeGetter = $localeGetter; + } + + public function boot() + { + $this->updateLocale(); + + if (!$this->app->bound('events')) { + return; + } + + $service = $this; + $events = $this->app['events']; + + if ($this->isEventDispatcher($events)) { + $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { + $service->updateLocale(); + }); + } + } + + public function updateLocale() + { + $locale = $this->getLocale(); + + if ($locale === null) { + return; + } + + Carbon::setLocale($locale); + CarbonImmutable::setLocale($locale); + CarbonPeriod::setLocale($locale); + CarbonInterval::setLocale($locale); + + if (class_exists(IlluminateCarbon::class)) { + IlluminateCarbon::setLocale($locale); + } + + if (class_exists(Date::class)) { + try { + $root = Date::getFacadeRoot(); + $root->setLocale($locale); + } catch (Throwable $e) { + // Non Carbon class in use in Date facade + } + } + } + + public function register() + { + // Needed for Laravel < 5.3 compatibility + } + + protected function getLocale() + { + if ($this->localeGetter) { + return ($this->localeGetter)(); + } + + $app = $this->getApp(); + $app = $app && method_exists($app, 'getLocale') + ? $app + : $this->getGlobalApp('translator'); + + return $app ? $app->getLocale() : null; + } + + protected function getApp() + { + if ($this->appGetter) { + return ($this->appGetter)(); + } + + return $this->app ?? $this->getGlobalApp(); + } + + protected function getGlobalApp(...$args) + { + return \function_exists('app') ? \app(...$args) : null; + } + + protected function isEventDispatcher($instance) + { + return $instance instanceof EventDispatcher + || $instance instanceof Dispatcher + || $instance instanceof DispatcherContract; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/List/languages.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/List/languages.php new file mode 100644 index 0000000..5b5d9a1 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/List/languages.php @@ -0,0 +1,1239 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +return [ + /* + * ISO 639-2 + */ + 'ab' => [ + 'isoName' => 'Abkhazian', + 'nativeName' => 'аҧсуа бызшәа, аҧсшәа', + ], + 'aa' => [ + 'isoName' => 'Afar', + 'nativeName' => 'Afaraf', + ], + 'af' => [ + 'isoName' => 'Afrikaans', + 'nativeName' => 'Afrikaans', + ], + 'ak' => [ + 'isoName' => 'Akan', + 'nativeName' => 'Akan', + ], + 'sq' => [ + 'isoName' => 'Albanian', + 'nativeName' => 'Shqip', + ], + 'am' => [ + 'isoName' => 'Amharic', + 'nativeName' => 'አማርኛ', + ], + 'ar' => [ + 'isoName' => 'Arabic', + 'nativeName' => 'العربية', + ], + 'an' => [ + 'isoName' => 'Aragonese', + 'nativeName' => 'aragonés', + ], + 'hy' => [ + 'isoName' => 'Armenian', + 'nativeName' => 'Հայերեն', + ], + 'as' => [ + 'isoName' => 'Assamese', + 'nativeName' => 'অসমীয়া', + ], + 'av' => [ + 'isoName' => 'Avaric', + 'nativeName' => 'авар мацӀ, магӀарул мацӀ', + ], + 'ae' => [ + 'isoName' => 'Avestan', + 'nativeName' => 'avesta', + ], + 'ay' => [ + 'isoName' => 'Aymara', + 'nativeName' => 'aymar aru', + ], + 'az' => [ + 'isoName' => 'Azerbaijani', + 'nativeName' => 'azərbaycan dili', + ], + 'bm' => [ + 'isoName' => 'Bambara', + 'nativeName' => 'bamanankan', + ], + 'ba' => [ + 'isoName' => 'Bashkir', + 'nativeName' => 'башҡорт теле', + ], + 'eu' => [ + 'isoName' => 'Basque', + 'nativeName' => 'euskara, euskera', + ], + 'be' => [ + 'isoName' => 'Belarusian', + 'nativeName' => 'беларуская мова', + ], + 'bn' => [ + 'isoName' => 'Bengali', + 'nativeName' => 'বাংলা', + ], + 'bh' => [ + 'isoName' => 'Bihari languages', + 'nativeName' => 'भोजपुरी', + ], + 'bi' => [ + 'isoName' => 'Bislama', + 'nativeName' => 'Bislama', + ], + 'bs' => [ + 'isoName' => 'Bosnian', + 'nativeName' => 'bosanski jezik', + ], + 'br' => [ + 'isoName' => 'Breton', + 'nativeName' => 'brezhoneg', + ], + 'bg' => [ + 'isoName' => 'Bulgarian', + 'nativeName' => 'български език', + ], + 'my' => [ + 'isoName' => 'Burmese', + 'nativeName' => 'ဗမာစာ', + ], + 'ca' => [ + 'isoName' => 'Catalan, Valencian', + 'nativeName' => 'català, valencià', + ], + 'ch' => [ + 'isoName' => 'Chamorro', + 'nativeName' => 'Chamoru', + ], + 'ce' => [ + 'isoName' => 'Chechen', + 'nativeName' => 'нохчийн мотт', + ], + 'ny' => [ + 'isoName' => 'Chichewa, Chewa, Nyanja', + 'nativeName' => 'chiCheŵa, chinyanja', + ], + 'zh' => [ + 'isoName' => 'Chinese', + 'nativeName' => '中文 (Zhōngwén), 汉语, 漢語', + ], + 'cv' => [ + 'isoName' => 'Chuvash', + 'nativeName' => 'чӑваш чӗлхи', + ], + 'kw' => [ + 'isoName' => 'Cornish', + 'nativeName' => 'Kernewek', + ], + 'co' => [ + 'isoName' => 'Corsican', + 'nativeName' => 'corsu, lingua corsa', + ], + 'cr' => [ + 'isoName' => 'Cree', + 'nativeName' => 'ᓀᐦᐃᔭᐍᐏᐣ', + ], + 'hr' => [ + 'isoName' => 'Croatian', + 'nativeName' => 'hrvatski jezik', + ], + 'cs' => [ + 'isoName' => 'Czech', + 'nativeName' => 'čeština, český jazyk', + ], + 'da' => [ + 'isoName' => 'Danish', + 'nativeName' => 'dansk', + ], + 'dv' => [ + 'isoName' => 'Divehi, Dhivehi, Maldivian', + 'nativeName' => 'ދިވެހި', + ], + 'nl' => [ + 'isoName' => 'Dutch, Flemish', + 'nativeName' => 'Nederlands, Vlaams', + ], + 'dz' => [ + 'isoName' => 'Dzongkha', + 'nativeName' => 'རྫོང་ཁ', + ], + 'en' => [ + 'isoName' => 'English', + 'nativeName' => 'English', + ], + 'eo' => [ + 'isoName' => 'Esperanto', + 'nativeName' => 'Esperanto', + ], + 'et' => [ + 'isoName' => 'Estonian', + 'nativeName' => 'eesti, eesti keel', + ], + 'ee' => [ + 'isoName' => 'Ewe', + 'nativeName' => 'Eʋegbe', + ], + 'fo' => [ + 'isoName' => 'Faroese', + 'nativeName' => 'føroyskt', + ], + 'fj' => [ + 'isoName' => 'Fijian', + 'nativeName' => 'vosa Vakaviti', + ], + 'fi' => [ + 'isoName' => 'Finnish', + 'nativeName' => 'suomi, suomen kieli', + ], + 'fr' => [ + 'isoName' => 'French', + 'nativeName' => 'français', + ], + 'ff' => [ + 'isoName' => 'Fulah', + 'nativeName' => 'Fulfulde, Pulaar, Pular', + ], + 'gl' => [ + 'isoName' => 'Galician', + 'nativeName' => 'Galego', + ], + 'ka' => [ + 'isoName' => 'Georgian', + 'nativeName' => 'ქართული', + ], + 'de' => [ + 'isoName' => 'German', + 'nativeName' => 'Deutsch', + ], + 'el' => [ + 'isoName' => 'Greek (modern)', + 'nativeName' => 'ελληνικά', + ], + 'gn' => [ + 'isoName' => 'Guaraní', + 'nativeName' => 'Avañe\'ẽ', + ], + 'gu' => [ + 'isoName' => 'Gujarati', + 'nativeName' => 'ગુજરાતી', + ], + 'ht' => [ + 'isoName' => 'Haitian, Haitian Creole', + 'nativeName' => 'Kreyòl ayisyen', + ], + 'ha' => [ + 'isoName' => 'Hausa', + 'nativeName' => '(Hausa) هَوُسَ', + ], + 'he' => [ + 'isoName' => 'Hebrew (modern)', + 'nativeName' => 'עברית', + ], + 'hz' => [ + 'isoName' => 'Herero', + 'nativeName' => 'Otjiherero', + ], + 'hi' => [ + 'isoName' => 'Hindi', + 'nativeName' => 'हिन्दी, हिंदी', + ], + 'ho' => [ + 'isoName' => 'Hiri Motu', + 'nativeName' => 'Hiri Motu', + ], + 'hu' => [ + 'isoName' => 'Hungarian', + 'nativeName' => 'magyar', + ], + 'ia' => [ + 'isoName' => 'Interlingua', + 'nativeName' => 'Interlingua', + ], + 'id' => [ + 'isoName' => 'Indonesian', + 'nativeName' => 'Bahasa Indonesia', + ], + 'ie' => [ + 'isoName' => 'Interlingue', + 'nativeName' => 'Originally called Occidental; then Interlingue after WWII', + ], + 'ga' => [ + 'isoName' => 'Irish', + 'nativeName' => 'Gaeilge', + ], + 'ig' => [ + 'isoName' => 'Igbo', + 'nativeName' => 'Asụsụ Igbo', + ], + 'ik' => [ + 'isoName' => 'Inupiaq', + 'nativeName' => 'Iñupiaq, Iñupiatun', + ], + 'io' => [ + 'isoName' => 'Ido', + 'nativeName' => 'Ido', + ], + 'is' => [ + 'isoName' => 'Icelandic', + 'nativeName' => 'Íslenska', + ], + 'it' => [ + 'isoName' => 'Italian', + 'nativeName' => 'Italiano', + ], + 'iu' => [ + 'isoName' => 'Inuktitut', + 'nativeName' => 'ᐃᓄᒃᑎᑐᑦ', + ], + 'ja' => [ + 'isoName' => 'Japanese', + 'nativeName' => '日本語 (にほんご)', + ], + 'jv' => [ + 'isoName' => 'Javanese', + 'nativeName' => 'ꦧꦱꦗꦮ, Basa Jawa', + ], + 'kl' => [ + 'isoName' => 'Kalaallisut, Greenlandic', + 'nativeName' => 'kalaallisut, kalaallit oqaasii', + ], + 'kn' => [ + 'isoName' => 'Kannada', + 'nativeName' => 'ಕನ್ನಡ', + ], + 'kr' => [ + 'isoName' => 'Kanuri', + 'nativeName' => 'Kanuri', + ], + 'ks' => [ + 'isoName' => 'Kashmiri', + 'nativeName' => 'कश्मीरी, كشميري‎', + ], + 'kk' => [ + 'isoName' => 'Kazakh', + 'nativeName' => 'қазақ тілі', + ], + 'km' => [ + 'isoName' => 'Central Khmer', + 'nativeName' => 'ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ', + ], + 'ki' => [ + 'isoName' => 'Kikuyu, Gikuyu', + 'nativeName' => 'Gĩkũyũ', + ], + 'rw' => [ + 'isoName' => 'Kinyarwanda', + 'nativeName' => 'Ikinyarwanda', + ], + 'ky' => [ + 'isoName' => 'Kirghiz, Kyrgyz', + 'nativeName' => 'Кыргызча, Кыргыз тили', + ], + 'kv' => [ + 'isoName' => 'Komi', + 'nativeName' => 'коми кыв', + ], + 'kg' => [ + 'isoName' => 'Kongo', + 'nativeName' => 'Kikongo', + ], + 'ko' => [ + 'isoName' => 'Korean', + 'nativeName' => '한국어', + ], + 'ku' => [ + 'isoName' => 'Kurdish', + 'nativeName' => 'Kurdî, کوردی‎', + ], + 'kj' => [ + 'isoName' => 'Kuanyama, Kwanyama', + 'nativeName' => 'Kuanyama', + ], + 'la' => [ + 'isoName' => 'Latin', + 'nativeName' => 'latine, lingua latina', + ], + 'lb' => [ + 'isoName' => 'Luxembourgish, Letzeburgesch', + 'nativeName' => 'Lëtzebuergesch', + ], + 'lg' => [ + 'isoName' => 'Ganda', + 'nativeName' => 'Luganda', + ], + 'li' => [ + 'isoName' => 'Limburgan, Limburger, Limburgish', + 'nativeName' => 'Limburgs', + ], + 'ln' => [ + 'isoName' => 'Lingala', + 'nativeName' => 'Lingála', + ], + 'lo' => [ + 'isoName' => 'Lao', + 'nativeName' => 'ພາສາລາວ', + ], + 'lt' => [ + 'isoName' => 'Lithuanian', + 'nativeName' => 'lietuvių kalba', + ], + 'lu' => [ + 'isoName' => 'Luba-Katanga', + 'nativeName' => 'Kiluba', + ], + 'lv' => [ + 'isoName' => 'Latvian', + 'nativeName' => 'latviešu valoda', + ], + 'gv' => [ + 'isoName' => 'Manx', + 'nativeName' => 'Gaelg, Gailck', + ], + 'mk' => [ + 'isoName' => 'Macedonian', + 'nativeName' => 'македонски јазик', + ], + 'mg' => [ + 'isoName' => 'Malagasy', + 'nativeName' => 'fiteny malagasy', + ], + 'ms' => [ + 'isoName' => 'Malay', + 'nativeName' => 'Bahasa Melayu, بهاس ملايو‎', + ], + 'ml' => [ + 'isoName' => 'Malayalam', + 'nativeName' => 'മലയാളം', + ], + 'mt' => [ + 'isoName' => 'Maltese', + 'nativeName' => 'Malti', + ], + 'mi' => [ + 'isoName' => 'Maori', + 'nativeName' => 'te reo Māori', + ], + 'mr' => [ + 'isoName' => 'Marathi', + 'nativeName' => 'मराठी', + ], + 'mh' => [ + 'isoName' => 'Marshallese', + 'nativeName' => 'Kajin M̧ajeļ', + ], + 'mn' => [ + 'isoName' => 'Mongolian', + 'nativeName' => 'Монгол хэл', + ], + 'na' => [ + 'isoName' => 'Nauru', + 'nativeName' => 'Dorerin Naoero', + ], + 'nv' => [ + 'isoName' => 'Navajo, Navaho', + 'nativeName' => 'Diné bizaad', + ], + 'nd' => [ + 'isoName' => 'North Ndebele', + 'nativeName' => 'isiNdebele', + ], + 'ne' => [ + 'isoName' => 'Nepali', + 'nativeName' => 'नेपाली', + ], + 'ng' => [ + 'isoName' => 'Ndonga', + 'nativeName' => 'Owambo', + ], + 'nb' => [ + 'isoName' => 'Norwegian Bokmål', + 'nativeName' => 'Norsk Bokmål', + ], + 'nn' => [ + 'isoName' => 'Norwegian Nynorsk', + 'nativeName' => 'Norsk Nynorsk', + ], + 'no' => [ + 'isoName' => 'Norwegian', + 'nativeName' => 'Norsk', + ], + 'ii' => [ + 'isoName' => 'Sichuan Yi, Nuosu', + 'nativeName' => 'ꆈꌠ꒿ Nuosuhxop', + ], + 'nr' => [ + 'isoName' => 'South Ndebele', + 'nativeName' => 'isiNdebele', + ], + 'oc' => [ + 'isoName' => 'Occitan', + 'nativeName' => 'occitan, lenga d\'òc', + ], + 'oj' => [ + 'isoName' => 'Ojibwa', + 'nativeName' => 'ᐊᓂᔑᓈᐯᒧᐎᓐ', + ], + 'cu' => [ + 'isoName' => 'Church Slavic, Church Slavonic, Old Church Slavonic, Old Slavonic, Old Bulgarian', + 'nativeName' => 'ѩзыкъ словѣньскъ', + ], + 'om' => [ + 'isoName' => 'Oromo', + 'nativeName' => 'Afaan Oromoo', + ], + 'or' => [ + 'isoName' => 'Oriya', + 'nativeName' => 'ଓଡ଼ିଆ', + ], + 'os' => [ + 'isoName' => 'Ossetian, Ossetic', + 'nativeName' => 'ирон æвзаг', + ], + 'pa' => [ + 'isoName' => 'Panjabi, Punjabi', + 'nativeName' => 'ਪੰਜਾਬੀ', + ], + 'pi' => [ + 'isoName' => 'Pali', + 'nativeName' => 'पाऴि', + ], + 'fa' => [ + 'isoName' => 'Persian', + 'nativeName' => 'فارسی', + ], + 'pl' => [ + 'isoName' => 'Polish', + 'nativeName' => 'język polski, polszczyzna', + ], + 'ps' => [ + 'isoName' => 'Pashto, Pushto', + 'nativeName' => 'پښتو', + ], + 'pt' => [ + 'isoName' => 'Portuguese', + 'nativeName' => 'Português', + ], + 'qu' => [ + 'isoName' => 'Quechua', + 'nativeName' => 'Runa Simi, Kichwa', + ], + 'rm' => [ + 'isoName' => 'Romansh', + 'nativeName' => 'Rumantsch Grischun', + ], + 'rn' => [ + 'isoName' => 'Rundi', + 'nativeName' => 'Ikirundi', + ], + 'ro' => [ + 'isoName' => 'Romanian, Moldavian, Moldovan', + 'nativeName' => 'Română', + ], + 'ru' => [ + 'isoName' => 'Russian', + 'nativeName' => 'русский', + ], + 'sa' => [ + 'isoName' => 'Sanskrit', + 'nativeName' => 'संस्कृतम्', + ], + 'sc' => [ + 'isoName' => 'Sardinian', + 'nativeName' => 'sardu', + ], + 'sd' => [ + 'isoName' => 'Sindhi', + 'nativeName' => 'सिन्धी, سنڌي، سندھی‎', + ], + 'se' => [ + 'isoName' => 'Northern Sami', + 'nativeName' => 'Davvisámegiella', + ], + 'sm' => [ + 'isoName' => 'Samoan', + 'nativeName' => 'gagana fa\'a Samoa', + ], + 'sg' => [ + 'isoName' => 'Sango', + 'nativeName' => 'yângâ tî sängö', + ], + 'sr' => [ + 'isoName' => 'Serbian', + 'nativeName' => 'српски језик', + ], + 'gd' => [ + 'isoName' => 'Gaelic, Scottish Gaelic', + 'nativeName' => 'Gàidhlig', + ], + 'sn' => [ + 'isoName' => 'Shona', + 'nativeName' => 'chiShona', + ], + 'si' => [ + 'isoName' => 'Sinhala, Sinhalese', + 'nativeName' => 'සිංහල', + ], + 'sk' => [ + 'isoName' => 'Slovak', + 'nativeName' => 'Slovenčina, Slovenský Jazyk', + ], + 'sl' => [ + 'isoName' => 'Slovene', + 'nativeName' => 'Slovenski Jezik, Slovenščina', + ], + 'so' => [ + 'isoName' => 'Somali', + 'nativeName' => 'Soomaaliga, af Soomaali', + ], + 'st' => [ + 'isoName' => 'Southern Sotho', + 'nativeName' => 'Sesotho', + ], + 'es' => [ + 'isoName' => 'Spanish, Castilian', + 'nativeName' => 'Español', + ], + 'su' => [ + 'isoName' => 'Sundanese', + 'nativeName' => 'Basa Sunda', + ], + 'sw' => [ + 'isoName' => 'Swahili', + 'nativeName' => 'Kiswahili', + ], + 'ss' => [ + 'isoName' => 'Swati', + 'nativeName' => 'SiSwati', + ], + 'sv' => [ + 'isoName' => 'Swedish', + 'nativeName' => 'Svenska', + ], + 'ta' => [ + 'isoName' => 'Tamil', + 'nativeName' => 'தமிழ்', + ], + 'te' => [ + 'isoName' => 'Telugu', + 'nativeName' => 'తెలుగు', + ], + 'tg' => [ + 'isoName' => 'Tajik', + 'nativeName' => 'тоҷикӣ, toçikī, تاجیکی‎', + ], + 'th' => [ + 'isoName' => 'Thai', + 'nativeName' => 'ไทย', + ], + 'ti' => [ + 'isoName' => 'Tigrinya', + 'nativeName' => 'ትግርኛ', + ], + 'bo' => [ + 'isoName' => 'Tibetan', + 'nativeName' => 'བོད་ཡིག', + ], + 'tk' => [ + 'isoName' => 'Turkmen', + 'nativeName' => 'Türkmen, Түркмен', + ], + 'tl' => [ + 'isoName' => 'Tagalog', + 'nativeName' => 'Wikang Tagalog', + ], + 'tn' => [ + 'isoName' => 'Tswana', + 'nativeName' => 'Setswana', + ], + 'to' => [ + 'isoName' => 'Tongan (Tonga Islands)', + 'nativeName' => 'Faka Tonga', + ], + 'tr' => [ + 'isoName' => 'Turkish', + 'nativeName' => 'Türkçe', + ], + 'ts' => [ + 'isoName' => 'Tsonga', + 'nativeName' => 'Xitsonga', + ], + 'tt' => [ + 'isoName' => 'Tatar', + 'nativeName' => 'татар теле, tatar tele', + ], + 'tw' => [ + 'isoName' => 'Twi', + 'nativeName' => 'Twi', + ], + 'ty' => [ + 'isoName' => 'Tahitian', + 'nativeName' => 'Reo Tahiti', + ], + 'ug' => [ + 'isoName' => 'Uighur, Uyghur', + 'nativeName' => 'Uyƣurqə, ‫ئۇيغۇرچ', + ], + 'uk' => [ + 'isoName' => 'Ukrainian', + 'nativeName' => 'Українська', + ], + 'ur' => [ + 'isoName' => 'Urdu', + 'nativeName' => 'اردو', + ], + 'uz' => [ + 'isoName' => 'Uzbek', + 'nativeName' => 'Oʻzbek, Ўзбек, أۇزبېك‎', + ], + 've' => [ + 'isoName' => 'Venda', + 'nativeName' => 'Tshivenḓa', + ], + 'vi' => [ + 'isoName' => 'Vietnamese', + 'nativeName' => 'Tiếng Việt', + ], + 'vo' => [ + 'isoName' => 'Volapük', + 'nativeName' => 'Volapük', + ], + 'wa' => [ + 'isoName' => 'Walloon', + 'nativeName' => 'Walon', + ], + 'cy' => [ + 'isoName' => 'Welsh', + 'nativeName' => 'Cymraeg', + ], + 'wo' => [ + 'isoName' => 'Wolof', + 'nativeName' => 'Wollof', + ], + 'fy' => [ + 'isoName' => 'Western Frisian', + 'nativeName' => 'Frysk', + ], + 'xh' => [ + 'isoName' => 'Xhosa', + 'nativeName' => 'isiXhosa', + ], + 'yi' => [ + 'isoName' => 'Yiddish', + 'nativeName' => 'ייִדיש', + ], + 'yo' => [ + 'isoName' => 'Yoruba', + 'nativeName' => 'Yorùbá', + ], + 'za' => [ + 'isoName' => 'Zhuang, Chuang', + 'nativeName' => 'Saɯ cueŋƅ, Saw cuengh', + ], + 'zu' => [ + 'isoName' => 'Zulu', + 'nativeName' => 'isiZulu', + ], + /* + * Add ISO 639-3 languages available in Carbon + */ + 'agq' => [ + 'isoName' => 'Aghem', + 'nativeName' => 'Aghem', + ], + 'agr' => [ + 'isoName' => 'Aguaruna', + 'nativeName' => 'Aguaruna', + ], + 'anp' => [ + 'isoName' => 'Angika', + 'nativeName' => 'Angika', + ], + 'asa' => [ + 'isoName' => 'Asu', + 'nativeName' => 'Asu', + ], + 'ast' => [ + 'isoName' => 'Asturian', + 'nativeName' => 'Asturian', + ], + 'ayc' => [ + 'isoName' => 'Southern Aymara', + 'nativeName' => 'Southern Aymara', + ], + 'bas' => [ + 'isoName' => 'Basaa', + 'nativeName' => 'Basaa', + ], + 'bem' => [ + 'isoName' => 'Bemba', + 'nativeName' => 'Bemba', + ], + 'bez' => [ + 'isoName' => 'Bena', + 'nativeName' => 'Bena', + ], + 'bhb' => [ + 'isoName' => 'Bhili', + 'nativeName' => 'Bhili', + ], + 'bho' => [ + 'isoName' => 'Bhojpuri', + 'nativeName' => 'Bhojpuri', + ], + 'brx' => [ + 'isoName' => 'Bodo', + 'nativeName' => 'Bodo', + ], + 'byn' => [ + 'isoName' => 'Bilin', + 'nativeName' => 'Bilin', + ], + 'ccp' => [ + 'isoName' => 'Chakma', + 'nativeName' => 'Chakma', + ], + 'cgg' => [ + 'isoName' => 'Chiga', + 'nativeName' => 'Chiga', + ], + 'chr' => [ + 'isoName' => 'Cherokee', + 'nativeName' => 'Cherokee', + ], + 'cmn' => [ + 'isoName' => 'Chinese', + 'nativeName' => 'Chinese', + ], + 'crh' => [ + 'isoName' => 'Crimean Turkish', + 'nativeName' => 'Crimean Turkish', + ], + 'csb' => [ + 'isoName' => 'Kashubian', + 'nativeName' => 'Kashubian', + ], + 'dav' => [ + 'isoName' => 'Taita', + 'nativeName' => 'Taita', + ], + 'dje' => [ + 'isoName' => 'Zarma', + 'nativeName' => 'Zarma', + ], + 'doi' => [ + 'isoName' => 'Dogri (macrolanguage)', + 'nativeName' => 'Dogri (macrolanguage)', + ], + 'dsb' => [ + 'isoName' => 'Lower Sorbian', + 'nativeName' => 'Lower Sorbian', + ], + 'dua' => [ + 'isoName' => 'Duala', + 'nativeName' => 'Duala', + ], + 'dyo' => [ + 'isoName' => 'Jola-Fonyi', + 'nativeName' => 'Jola-Fonyi', + ], + 'ebu' => [ + 'isoName' => 'Embu', + 'nativeName' => 'Embu', + ], + 'ewo' => [ + 'isoName' => 'Ewondo', + 'nativeName' => 'Ewondo', + ], + 'fil' => [ + 'isoName' => 'Filipino', + 'nativeName' => 'Filipino', + ], + 'fur' => [ + 'isoName' => 'Friulian', + 'nativeName' => 'Friulian', + ], + 'gez' => [ + 'isoName' => 'Geez', + 'nativeName' => 'Geez', + ], + 'gom' => [ + 'isoName' => 'Konkani, Goan', + 'nativeName' => 'ಕೊಂಕಣಿ', + ], + 'gsw' => [ + 'isoName' => 'Swiss German', + 'nativeName' => 'Swiss German', + ], + 'guz' => [ + 'isoName' => 'Gusii', + 'nativeName' => 'Gusii', + ], + 'hak' => [ + 'isoName' => 'Hakka Chinese', + 'nativeName' => 'Hakka Chinese', + ], + 'haw' => [ + 'isoName' => 'Hawaiian', + 'nativeName' => 'Hawaiian', + ], + 'hif' => [ + 'isoName' => 'Fiji Hindi', + 'nativeName' => 'Fiji Hindi', + ], + 'hne' => [ + 'isoName' => 'Chhattisgarhi', + 'nativeName' => 'Chhattisgarhi', + ], + 'hsb' => [ + 'isoName' => 'Upper Sorbian', + 'nativeName' => 'Upper Sorbian', + ], + 'jgo' => [ + 'isoName' => 'Ngomba', + 'nativeName' => 'Ngomba', + ], + 'jmc' => [ + 'isoName' => 'Machame', + 'nativeName' => 'Machame', + ], + 'kab' => [ + 'isoName' => 'Kabyle', + 'nativeName' => 'Kabyle', + ], + 'kam' => [ + 'isoName' => 'Kamba', + 'nativeName' => 'Kamba', + ], + 'kde' => [ + 'isoName' => 'Makonde', + 'nativeName' => 'Makonde', + ], + 'kea' => [ + 'isoName' => 'Kabuverdianu', + 'nativeName' => 'Kabuverdianu', + ], + 'khq' => [ + 'isoName' => 'Koyra Chiini', + 'nativeName' => 'Koyra Chiini', + ], + 'kkj' => [ + 'isoName' => 'Kako', + 'nativeName' => 'Kako', + ], + 'kln' => [ + 'isoName' => 'Kalenjin', + 'nativeName' => 'Kalenjin', + ], + 'kok' => [ + 'isoName' => 'Konkani', + 'nativeName' => 'Konkani', + ], + 'ksb' => [ + 'isoName' => 'Shambala', + 'nativeName' => 'Shambala', + ], + 'ksf' => [ + 'isoName' => 'Bafia', + 'nativeName' => 'Bafia', + ], + 'ksh' => [ + 'isoName' => 'Colognian', + 'nativeName' => 'Colognian', + ], + 'lag' => [ + 'isoName' => 'Langi', + 'nativeName' => 'Langi', + ], + 'lij' => [ + 'isoName' => 'Ligurian', + 'nativeName' => 'Ligurian', + ], + 'lkt' => [ + 'isoName' => 'Lakota', + 'nativeName' => 'Lakota', + ], + 'lrc' => [ + 'isoName' => 'Northern Luri', + 'nativeName' => 'Northern Luri', + ], + 'luo' => [ + 'isoName' => 'Luo', + 'nativeName' => 'Luo', + ], + 'luy' => [ + 'isoName' => 'Luyia', + 'nativeName' => 'Luyia', + ], + 'lzh' => [ + 'isoName' => 'Literary Chinese', + 'nativeName' => 'Literary Chinese', + ], + 'mag' => [ + 'isoName' => 'Magahi', + 'nativeName' => 'Magahi', + ], + 'mai' => [ + 'isoName' => 'Maithili', + 'nativeName' => 'Maithili', + ], + 'mas' => [ + 'isoName' => 'Masai', + 'nativeName' => 'Masai', + ], + 'mer' => [ + 'isoName' => 'Meru', + 'nativeName' => 'Meru', + ], + 'mfe' => [ + 'isoName' => 'Morisyen', + 'nativeName' => 'Morisyen', + ], + 'mgh' => [ + 'isoName' => 'Makhuwa-Meetto', + 'nativeName' => 'Makhuwa-Meetto', + ], + 'mgo' => [ + 'isoName' => 'Metaʼ', + 'nativeName' => 'Metaʼ', + ], + 'mhr' => [ + 'isoName' => 'Eastern Mari', + 'nativeName' => 'Eastern Mari', + ], + 'miq' => [ + 'isoName' => 'Mískito', + 'nativeName' => 'Mískito', + ], + 'mjw' => [ + 'isoName' => 'Karbi', + 'nativeName' => 'Karbi', + ], + 'mni' => [ + 'isoName' => 'Manipuri', + 'nativeName' => 'Manipuri', + ], + 'mua' => [ + 'isoName' => 'Mundang', + 'nativeName' => 'Mundang', + ], + 'mzn' => [ + 'isoName' => 'Mazanderani', + 'nativeName' => 'Mazanderani', + ], + 'nan' => [ + 'isoName' => 'Min Nan Chinese', + 'nativeName' => 'Min Nan Chinese', + ], + 'naq' => [ + 'isoName' => 'Nama', + 'nativeName' => 'Nama', + ], + 'nds' => [ + 'isoName' => 'Low German', + 'nativeName' => 'Low German', + ], + 'nhn' => [ + 'isoName' => 'Central Nahuatl', + 'nativeName' => 'Central Nahuatl', + ], + 'niu' => [ + 'isoName' => 'Niuean', + 'nativeName' => 'Niuean', + ], + 'nmg' => [ + 'isoName' => 'Kwasio', + 'nativeName' => 'Kwasio', + ], + 'nnh' => [ + 'isoName' => 'Ngiemboon', + 'nativeName' => 'Ngiemboon', + ], + 'nso' => [ + 'isoName' => 'Northern Sotho', + 'nativeName' => 'Northern Sotho', + ], + 'nus' => [ + 'isoName' => 'Nuer', + 'nativeName' => 'Nuer', + ], + 'nyn' => [ + 'isoName' => 'Nyankole', + 'nativeName' => 'Nyankole', + ], + 'pap' => [ + 'isoName' => 'Papiamento', + 'nativeName' => 'Papiamento', + ], + 'prg' => [ + 'isoName' => 'Prussian', + 'nativeName' => 'Prussian', + ], + 'quz' => [ + 'isoName' => 'Cusco Quechua', + 'nativeName' => 'Cusco Quechua', + ], + 'raj' => [ + 'isoName' => 'Rajasthani', + 'nativeName' => 'Rajasthani', + ], + 'rof' => [ + 'isoName' => 'Rombo', + 'nativeName' => 'Rombo', + ], + 'rwk' => [ + 'isoName' => 'Rwa', + 'nativeName' => 'Rwa', + ], + 'sah' => [ + 'isoName' => 'Sakha', + 'nativeName' => 'Sakha', + ], + 'saq' => [ + 'isoName' => 'Samburu', + 'nativeName' => 'Samburu', + ], + 'sat' => [ + 'isoName' => 'Santali', + 'nativeName' => 'Santali', + ], + 'sbp' => [ + 'isoName' => 'Sangu', + 'nativeName' => 'Sangu', + ], + 'scr' => [ + 'isoName' => 'Serbo Croatian', + 'nativeName' => 'Serbo Croatian', + ], + 'seh' => [ + 'isoName' => 'Sena', + 'nativeName' => 'Sena', + ], + 'ses' => [ + 'isoName' => 'Koyraboro Senni', + 'nativeName' => 'Koyraboro Senni', + ], + 'sgs' => [ + 'isoName' => 'Samogitian', + 'nativeName' => 'Samogitian', + ], + 'shi' => [ + 'isoName' => 'Tachelhit', + 'nativeName' => 'Tachelhit', + ], + 'shn' => [ + 'isoName' => 'Shan', + 'nativeName' => 'Shan', + ], + 'shs' => [ + 'isoName' => 'Shuswap', + 'nativeName' => 'Shuswap', + ], + 'sid' => [ + 'isoName' => 'Sidamo', + 'nativeName' => 'Sidamo', + ], + 'smn' => [ + 'isoName' => 'Inari Sami', + 'nativeName' => 'Inari Sami', + ], + 'szl' => [ + 'isoName' => 'Silesian', + 'nativeName' => 'Silesian', + ], + 'tcy' => [ + 'isoName' => 'Tulu', + 'nativeName' => 'Tulu', + ], + 'teo' => [ + 'isoName' => 'Teso', + 'nativeName' => 'Teso', + ], + 'tet' => [ + 'isoName' => 'Tetum', + 'nativeName' => 'Tetum', + ], + 'the' => [ + 'isoName' => 'Chitwania Tharu', + 'nativeName' => 'Chitwania Tharu', + ], + 'tig' => [ + 'isoName' => 'Tigre', + 'nativeName' => 'Tigre', + ], + 'tlh' => [ + 'isoName' => 'Klingon', + 'nativeName' => 'tlhIngan Hol', + ], + 'tpi' => [ + 'isoName' => 'Tok Pisin', + 'nativeName' => 'Tok Pisin', + ], + 'twq' => [ + 'isoName' => 'Tasawaq', + 'nativeName' => 'Tasawaq', + ], + 'tzl' => [ + 'isoName' => 'Talossan', + 'nativeName' => 'Talossan', + ], + 'tzm' => [ + 'isoName' => 'Tamazight, Central Atlas', + 'nativeName' => 'ⵜⵎⴰⵣⵉⵖⵜ', + ], + 'unm' => [ + 'isoName' => 'Unami', + 'nativeName' => 'Unami', + ], + 'vai' => [ + 'isoName' => 'Vai', + 'nativeName' => 'Vai', + ], + 'vun' => [ + 'isoName' => 'Vunjo', + 'nativeName' => 'Vunjo', + ], + 'wae' => [ + 'isoName' => 'Walser', + 'nativeName' => 'Walser', + ], + 'wal' => [ + 'isoName' => 'Wolaytta', + 'nativeName' => 'Wolaytta', + ], + 'xog' => [ + 'isoName' => 'Soga', + 'nativeName' => 'Soga', + ], + 'yav' => [ + 'isoName' => 'Yangben', + 'nativeName' => 'Yangben', + ], + 'yue' => [ + 'isoName' => 'Cantonese', + 'nativeName' => 'Cantonese', + ], + 'yuw' => [ + 'isoName' => 'Yau (Morobe Province)', + 'nativeName' => 'Yau (Morobe Province)', + ], + 'zgh' => [ + 'isoName' => 'Standard Moroccan Tamazight', + 'nativeName' => 'Standard Moroccan Tamazight', + ], +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/List/regions.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/List/regions.php new file mode 100644 index 0000000..8ab8a9e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/List/regions.php @@ -0,0 +1,265 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * ISO 3166-2 + */ +return [ + 'AD' => 'Andorra', + 'AE' => 'United Arab Emirates', + 'AF' => 'Afghanistan', + 'AG' => 'Antigua and Barbuda', + 'AI' => 'Anguilla', + 'AL' => 'Albania', + 'AM' => 'Armenia', + 'AO' => 'Angola', + 'AQ' => 'Antarctica', + 'AR' => 'Argentina', + 'AS' => 'American Samoa', + 'AT' => 'Austria', + 'AU' => 'Australia', + 'AW' => 'Aruba', + 'AX' => 'Åland Islands', + 'AZ' => 'Azerbaijan', + 'BA' => 'Bosnia and Herzegovina', + 'BB' => 'Barbados', + 'BD' => 'Bangladesh', + 'BE' => 'Belgium', + 'BF' => 'Burkina Faso', + 'BG' => 'Bulgaria', + 'BH' => 'Bahrain', + 'BI' => 'Burundi', + 'BJ' => 'Benin', + 'BL' => 'Saint Barthélemy', + 'BM' => 'Bermuda', + 'BN' => 'Brunei Darussalam', + 'BO' => 'Bolivia (Plurinational State of)', + 'BQ' => 'Bonaire, Sint Eustatius and Saba', + 'BR' => 'Brazil', + 'BS' => 'Bahamas', + 'BT' => 'Bhutan', + 'BV' => 'Bouvet Island', + 'BW' => 'Botswana', + 'BY' => 'Belarus', + 'BZ' => 'Belize', + 'CA' => 'Canada', + 'CC' => 'Cocos (Keeling) Islands', + 'CD' => 'Congo, Democratic Republic of the', + 'CF' => 'Central African Republic', + 'CG' => 'Congo', + 'CH' => 'Switzerland', + 'CI' => 'Côte d\'Ivoire', + 'CK' => 'Cook Islands', + 'CL' => 'Chile', + 'CM' => 'Cameroon', + 'CN' => 'China', + 'CO' => 'Colombia', + 'CR' => 'Costa Rica', + 'CU' => 'Cuba', + 'CV' => 'Cabo Verde', + 'CW' => 'Curaçao', + 'CX' => 'Christmas Island', + 'CY' => 'Cyprus', + 'CZ' => 'Czechia', + 'DE' => 'Germany', + 'DJ' => 'Djibouti', + 'DK' => 'Denmark', + 'DM' => 'Dominica', + 'DO' => 'Dominican Republic', + 'DZ' => 'Algeria', + 'EC' => 'Ecuador', + 'EE' => 'Estonia', + 'EG' => 'Egypt', + 'EH' => 'Western Sahara', + 'ER' => 'Eritrea', + 'ES' => 'Spain', + 'ET' => 'Ethiopia', + 'FI' => 'Finland', + 'FJ' => 'Fiji', + 'FK' => 'Falkland Islands (Malvinas)', + 'FM' => 'Micronesia (Federated States of)', + 'FO' => 'Faroe Islands', + 'FR' => 'France', + 'GA' => 'Gabon', + 'GB' => 'United Kingdom of Great Britain and Northern Ireland', + 'GD' => 'Grenada', + 'GE' => 'Georgia', + 'GF' => 'French Guiana', + 'GG' => 'Guernsey', + 'GH' => 'Ghana', + 'GI' => 'Gibraltar', + 'GL' => 'Greenland', + 'GM' => 'Gambia', + 'GN' => 'Guinea', + 'GP' => 'Guadeloupe', + 'GQ' => 'Equatorial Guinea', + 'GR' => 'Greece', + 'GS' => 'South Georgia and the South Sandwich Islands', + 'GT' => 'Guatemala', + 'GU' => 'Guam', + 'GW' => 'Guinea-Bissau', + 'GY' => 'Guyana', + 'HK' => 'Hong Kong', + 'HM' => 'Heard Island and McDonald Islands', + 'HN' => 'Honduras', + 'HR' => 'Croatia', + 'HT' => 'Haiti', + 'HU' => 'Hungary', + 'ID' => 'Indonesia', + 'IE' => 'Ireland', + 'IL' => 'Israel', + 'IM' => 'Isle of Man', + 'IN' => 'India', + 'IO' => 'British Indian Ocean Territory', + 'IQ' => 'Iraq', + 'IR' => 'Iran (Islamic Republic of)', + 'IS' => 'Iceland', + 'IT' => 'Italy', + 'JE' => 'Jersey', + 'JM' => 'Jamaica', + 'JO' => 'Jordan', + 'JP' => 'Japan', + 'KE' => 'Kenya', + 'KG' => 'Kyrgyzstan', + 'KH' => 'Cambodia', + 'KI' => 'Kiribati', + 'KM' => 'Comoros', + 'KN' => 'Saint Kitts and Nevis', + 'KP' => 'Korea (Democratic People\'s Republic of)', + 'KR' => 'Korea, Republic of', + 'KW' => 'Kuwait', + 'KY' => 'Cayman Islands', + 'KZ' => 'Kazakhstan', + 'LA' => 'Lao People\'s Democratic Republic', + 'LB' => 'Lebanon', + 'LC' => 'Saint Lucia', + 'LI' => 'Liechtenstein', + 'LK' => 'Sri Lanka', + 'LR' => 'Liberia', + 'LS' => 'Lesotho', + 'LT' => 'Lithuania', + 'LU' => 'Luxembourg', + 'LV' => 'Latvia', + 'LY' => 'Libya', + 'MA' => 'Morocco', + 'MC' => 'Monaco', + 'MD' => 'Moldova, Republic of', + 'ME' => 'Montenegro', + 'MF' => 'Saint Martin (French part)', + 'MG' => 'Madagascar', + 'MH' => 'Marshall Islands', + 'MK' => 'Macedonia, the former Yugoslav Republic of', + 'ML' => 'Mali', + 'MM' => 'Myanmar', + 'MN' => 'Mongolia', + 'MO' => 'Macao', + 'MP' => 'Northern Mariana Islands', + 'MQ' => 'Martinique', + 'MR' => 'Mauritania', + 'MS' => 'Montserrat', + 'MT' => 'Malta', + 'MU' => 'Mauritius', + 'MV' => 'Maldives', + 'MW' => 'Malawi', + 'MX' => 'Mexico', + 'MY' => 'Malaysia', + 'MZ' => 'Mozambique', + 'NA' => 'Namibia', + 'NC' => 'New Caledonia', + 'NE' => 'Niger', + 'NF' => 'Norfolk Island', + 'NG' => 'Nigeria', + 'NI' => 'Nicaragua', + 'NL' => 'Netherlands', + 'NO' => 'Norway', + 'NP' => 'Nepal', + 'NR' => 'Nauru', + 'NU' => 'Niue', + 'NZ' => 'New Zealand', + 'OM' => 'Oman', + 'PA' => 'Panama', + 'PE' => 'Peru', + 'PF' => 'French Polynesia', + 'PG' => 'Papua New Guinea', + 'PH' => 'Philippines', + 'PK' => 'Pakistan', + 'PL' => 'Poland', + 'PM' => 'Saint Pierre and Miquelon', + 'PN' => 'Pitcairn', + 'PR' => 'Puerto Rico', + 'PS' => 'Palestine, State of', + 'PT' => 'Portugal', + 'PW' => 'Palau', + 'PY' => 'Paraguay', + 'QA' => 'Qatar', + 'RE' => 'Réunion', + 'RO' => 'Romania', + 'RS' => 'Serbia', + 'RU' => 'Russian Federation', + 'RW' => 'Rwanda', + 'SA' => 'Saudi Arabia', + 'SB' => 'Solomon Islands', + 'SC' => 'Seychelles', + 'SD' => 'Sudan', + 'SE' => 'Sweden', + 'SG' => 'Singapore', + 'SH' => 'Saint Helena, Ascension and Tristan da Cunha', + 'SI' => 'Slovenia', + 'SJ' => 'Svalbard and Jan Mayen', + 'SK' => 'Slovakia', + 'SL' => 'Sierra Leone', + 'SM' => 'San Marino', + 'SN' => 'Senegal', + 'SO' => 'Somalia', + 'SR' => 'Suriname', + 'SS' => 'South Sudan', + 'ST' => 'Sao Tome and Principe', + 'SV' => 'El Salvador', + 'SX' => 'Sint Maarten (Dutch part)', + 'SY' => 'Syrian Arab Republic', + 'SZ' => 'Eswatini', + 'TC' => 'Turks and Caicos Islands', + 'TD' => 'Chad', + 'TF' => 'French Southern Territories', + 'TG' => 'Togo', + 'TH' => 'Thailand', + 'TJ' => 'Tajikistan', + 'TK' => 'Tokelau', + 'TL' => 'Timor-Leste', + 'TM' => 'Turkmenistan', + 'TN' => 'Tunisia', + 'TO' => 'Tonga', + 'TR' => 'Turkey', + 'TT' => 'Trinidad and Tobago', + 'TV' => 'Tuvalu', + 'TW' => 'Taiwan, Province of China', + 'TZ' => 'Tanzania, United Republic of', + 'UA' => 'Ukraine', + 'UG' => 'Uganda', + 'UM' => 'United States Minor Outlying Islands', + 'US' => 'United States of America', + 'UY' => 'Uruguay', + 'UZ' => 'Uzbekistan', + 'VA' => 'Holy See', + 'VC' => 'Saint Vincent and the Grenadines', + 'VE' => 'Venezuela (Bolivarian Republic of)', + 'VG' => 'Virgin Islands (British)', + 'VI' => 'Virgin Islands (U.S.)', + 'VN' => 'Viet Nam', + 'VU' => 'Vanuatu', + 'WF' => 'Wallis and Futuna', + 'WS' => 'Samoa', + 'YE' => 'Yemen', + 'YT' => 'Mayotte', + 'ZA' => 'South Africa', + 'ZM' => 'Zambia', + 'ZW' => 'Zimbabwe', +]; diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/MessageFormatter/MessageFormatterMapper.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/MessageFormatter/MessageFormatterMapper.php new file mode 100644 index 0000000..c054808 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/MessageFormatter/MessageFormatterMapper.php @@ -0,0 +1,44 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\MessageFormatter; + +use ReflectionMethod; +use Symfony\Component\Translation\Formatter\MessageFormatter; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +// @codeCoverageIgnoreStart +$transMethod = new ReflectionMethod(MessageFormatterInterface::class, 'format'); + +require $transMethod->getParameters()[0]->hasType() + ? __DIR__.'/../../../lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php' + : __DIR__.'/../../../lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php'; +// @codeCoverageIgnoreEnd + +final class MessageFormatterMapper extends LazyMessageFormatter +{ + /** + * Wrapped formatter. + * + * @var MessageFormatterInterface + */ + protected $formatter; + + public function __construct(?MessageFormatterInterface $formatter = null) + { + $this->formatter = $formatter ?? new MessageFormatter(); + } + + protected function transformLocale(?string $locale): ?string + { + return $locale ? preg_replace('/[_@][A-Za-z][a-z]{2,}/', '', $locale) : $locale; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php new file mode 100644 index 0000000..fde67b3 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php @@ -0,0 +1,286 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use Closure; +use InvalidArgumentException; +use PHPStan\BetterReflection\Reflection\Adapter\ReflectionParameter as AdapterReflectionParameter; +use PHPStan\BetterReflection\Reflection\Adapter\ReflectionType as AdapterReflectionType; +use PHPStan\BetterReflection\Reflection\ReflectionClass as BetterReflectionClass; +use PHPStan\BetterReflection\Reflection\ReflectionFunction as BetterReflectionFunction; +use PHPStan\BetterReflection\Reflection\ReflectionParameter as BetterReflectionParameter; +use PHPStan\Reflection\Php\BuiltinMethodReflection; +use PHPStan\TrinaryLogic; +use ReflectionClass; +use ReflectionFunction; +use ReflectionMethod; +use ReflectionParameter; +use ReflectionType; +use stdClass; +use Throwable; + +abstract class AbstractMacro implements BuiltinMethodReflection +{ + /** + * The reflection function/method. + * + * @var ReflectionFunction|ReflectionMethod + */ + protected $reflectionFunction; + + /** + * The class name. + * + * @var class-string + */ + private $className; + + /** + * The method name. + * + * @var string + */ + private $methodName; + + /** + * The parameters. + * + * @var ReflectionParameter[] + */ + private $parameters; + + /** + * The is static. + * + * @var bool + */ + private $static = false; + + /** + * Macro constructor. + * + * @param class-string $className + * @param string $methodName + * @param callable $macro + */ + public function __construct(string $className, string $methodName, $macro) + { + $this->className = $className; + $this->methodName = $methodName; + $rawReflectionFunction = \is_array($macro) + ? new ReflectionMethod($macro[0], $macro[1]) + : new ReflectionFunction($macro); + $this->reflectionFunction = self::hasModernParser() + ? $this->getReflectionFunction($macro) + : $rawReflectionFunction; // @codeCoverageIgnore + $this->parameters = array_map( + function ($parameter) { + if ($parameter instanceof BetterReflectionParameter) { + return new AdapterReflectionParameter($parameter); + } + + return $parameter; // @codeCoverageIgnore + }, + $this->reflectionFunction->getParameters() + ); + + if ($rawReflectionFunction->isClosure()) { + try { + $closure = $rawReflectionFunction->getClosure(); + $boundClosure = Closure::bind($closure, new stdClass()); + $this->static = (!$boundClosure || (new ReflectionFunction($boundClosure))->getClosureThis() === null); + } catch (Throwable $e) { + $this->static = true; + } + } + } + + private function getReflectionFunction($spec) + { + if (\is_array($spec) && \count($spec) === 2 && \is_string($spec[1])) { + \assert($spec[1] !== ''); + + if (\is_object($spec[0])) { + return BetterReflectionClass::createFromInstance($spec[0]) + ->getMethod($spec[1]); + } + + return BetterReflectionClass::createFromName($spec[0]) + ->getMethod($spec[1]); + } + + if (\is_string($spec)) { + return BetterReflectionFunction::createFromName($spec); + } + + if ($spec instanceof Closure) { + return BetterReflectionFunction::createFromClosure($spec); + } + + throw new InvalidArgumentException('Could not create reflection from the spec given'); // @codeCoverageIgnore + } + + /** + * {@inheritdoc} + */ + public function getDeclaringClass(): ReflectionClass + { + return new ReflectionClass($this->className); + } + + /** + * {@inheritdoc} + */ + public function isPrivate(): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isPublic(): bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public function isFinal(): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isInternal(): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isAbstract(): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isStatic(): bool + { + return $this->static; + } + + /** + * {@inheritdoc} + */ + public function getDocComment(): ?string + { + return $this->reflectionFunction->getDocComment() ?: null; + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return $this->methodName; + } + + /** + * {@inheritdoc} + */ + public function getParameters(): array + { + return $this->parameters; + } + + /** + * {@inheritdoc} + */ + public function getReturnType(): ?ReflectionType + { + $type = $this->reflectionFunction->getReturnType(); + + if ($type instanceof ReflectionType) { + return $type; // @codeCoverageIgnore + } + + return self::adaptType($type); + } + + /** + * {@inheritdoc} + */ + public function isDeprecated(): TrinaryLogic + { + return TrinaryLogic::createFromBoolean( + $this->reflectionFunction->isDeprecated() || + preg_match('/@deprecated/i', $this->getDocComment() ?: '') + ); + } + + /** + * {@inheritdoc} + */ + public function isVariadic(): bool + { + return $this->reflectionFunction->isVariadic(); + } + + /** + * {@inheritdoc} + */ + public function getPrototype(): BuiltinMethodReflection + { + return $this; + } + + public function getTentativeReturnType(): ?ReflectionType + { + return null; + } + + public function returnsByReference(): TrinaryLogic + { + return TrinaryLogic::createNo(); + } + + private static function adaptType($type) + { + $method = method_exists(AdapterReflectionType::class, 'fromTypeOrNull') + ? 'fromTypeOrNull' + : 'fromReturnTypeOrNull'; // @codeCoverageIgnore + + return AdapterReflectionType::$method($type); + } + + private static function hasModernParser(): bool + { + static $modernParser = null; + + if ($modernParser !== null) { + return $modernParser; + } + + $modernParser = method_exists(AdapterReflectionType::class, 'fromTypeOrNull'); + + return $modernParser; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php new file mode 100644 index 0000000..de3e51f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use PHPStan\BetterReflection\Reflection\Adapter; +use PHPStan\Reflection\Php\BuiltinMethodReflection; +use ReflectionMethod; + +$method = new ReflectionMethod(BuiltinMethodReflection::class, 'getReflection'); + +require $method->hasReturnType() && $method->getReturnType()->getName() === Adapter\ReflectionMethod::class + ? __DIR__.'/../../../lazy/Carbon/PHPStan/AbstractMacroStatic.php' + : __DIR__.'/../../../lazy/Carbon/PHPStan/AbstractMacroBuiltin.php'; + +$method = new ReflectionMethod(BuiltinMethodReflection::class, 'getFileName'); + +require $method->hasReturnType() + ? __DIR__.'/../../../lazy/Carbon/PHPStan/MacroStrongType.php' + : __DIR__.'/../../../lazy/Carbon/PHPStan/MacroWeakType.php'; + +final class Macro extends LazyMacro +{ +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php new file mode 100644 index 0000000..2cd6fce --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php @@ -0,0 +1,88 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use PHPStan\Reflection\Assertions; +use PHPStan\Reflection\ClassReflection; +use PHPStan\Reflection\MethodReflection; +use PHPStan\Reflection\MethodsClassReflectionExtension; +use PHPStan\Reflection\Php\PhpMethodReflectionFactory; +use PHPStan\Reflection\ReflectionProvider; +use PHPStan\Type\TypehintHelper; + +/** + * Class MacroExtension. + * + * @codeCoverageIgnore Pure PHPStan wrapper. + */ +final class MacroExtension implements MethodsClassReflectionExtension +{ + /** + * @var PhpMethodReflectionFactory + */ + protected $methodReflectionFactory; + + /** + * @var MacroScanner + */ + protected $scanner; + + /** + * Extension constructor. + * + * @param PhpMethodReflectionFactory $methodReflectionFactory + * @param ReflectionProvider $reflectionProvider + */ + public function __construct( + PhpMethodReflectionFactory $methodReflectionFactory, + ReflectionProvider $reflectionProvider + ) { + $this->scanner = new MacroScanner($reflectionProvider); + $this->methodReflectionFactory = $methodReflectionFactory; + } + + /** + * {@inheritdoc} + */ + public function hasMethod(ClassReflection $classReflection, string $methodName): bool + { + return $this->scanner->hasMethod($classReflection->getName(), $methodName); + } + + /** + * {@inheritdoc} + */ + public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection + { + $builtinMacro = $this->scanner->getMethod($classReflection->getName(), $methodName); + $supportAssertions = class_exists(Assertions::class); + + return $this->methodReflectionFactory->create( + $classReflection, + null, + $builtinMacro, + $classReflection->getActiveTemplateTypeMap(), + [], + TypehintHelper::decideTypeFromReflection($builtinMacro->getReturnType()), + null, + null, + $builtinMacro->isDeprecated()->yes(), + $builtinMacro->isInternal(), + $builtinMacro->isFinal(), + $supportAssertions ? null : $builtinMacro->getDocComment(), + $supportAssertions ? Assertions::createEmpty() : null, + null, + $builtinMacro->getDocComment(), + [] + ); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php new file mode 100644 index 0000000..eb8957d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php @@ -0,0 +1,83 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use Carbon\CarbonInterface; +use PHPStan\Reflection\ReflectionProvider; +use ReflectionClass; +use ReflectionException; + +final class MacroScanner +{ + /** + * @var \PHPStan\Reflection\ReflectionProvider + */ + private $reflectionProvider; + + /** + * MacroScanner constructor. + * + * @param \PHPStan\Reflection\ReflectionProvider $reflectionProvider + */ + public function __construct(ReflectionProvider $reflectionProvider) + { + $this->reflectionProvider = $reflectionProvider; + } + + /** + * Return true if the given pair class-method is a Carbon macro. + * + * @param class-string $className + * @param string $methodName + * + * @return bool + */ + public function hasMethod(string $className, string $methodName): bool + { + $classReflection = $this->reflectionProvider->getClass($className); + + if ( + $classReflection->getName() !== CarbonInterface::class && + !$classReflection->isSubclassOf(CarbonInterface::class) + ) { + return false; + } + + return \is_callable([$className, 'hasMacro']) && + $className::hasMacro($methodName); + } + + /** + * Return the Macro for a given pair class-method. + * + * @param class-string $className + * @param string $methodName + * + * @throws ReflectionException + * + * @return Macro + */ + public function getMethod(string $className, string $methodName): Macro + { + $reflectionClass = new ReflectionClass($className); + $property = $reflectionClass->getProperty('globalMacros'); + + $property->setAccessible(true); + $macro = $property->getValue()[$methodName]; + + return new Macro( + $className, + $methodName, + $macro + ); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Boundaries.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Boundaries.php new file mode 100644 index 0000000..71bbb72 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Boundaries.php @@ -0,0 +1,443 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Exceptions\UnknownUnitException; + +/** + * Trait Boundaries. + * + * startOf, endOf and derived method for each unit. + * + * Depends on the following properties: + * + * @property int $year + * @property int $month + * @property int $daysInMonth + * @property int $quarter + * + * Depends on the following methods: + * + * @method $this setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0) + * @method $this setDate(int $year, int $month, int $day) + * @method $this addMonths(int $value = 1) + */ +trait Boundaries +{ + /** + * Resets the time to 00:00:00 start of day + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfDay(); + * ``` + * + * @return static + */ + public function startOfDay() + { + return $this->setTime(0, 0, 0, 0); + } + + /** + * Resets the time to 23:59:59.999999 end of day + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfDay(); + * ``` + * + * @return static + */ + public function endOfDay() + { + return $this->setTime(static::HOURS_PER_DAY - 1, static::MINUTES_PER_HOUR - 1, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1); + } + + /** + * Resets the date to the first day of the month and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfMonth(); + * ``` + * + * @return static + */ + public function startOfMonth() + { + return $this->setDate($this->year, $this->month, 1)->startOfDay(); + } + + /** + * Resets the date to end of the month and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfMonth(); + * ``` + * + * @return static + */ + public function endOfMonth() + { + return $this->setDate($this->year, $this->month, $this->daysInMonth)->endOfDay(); + } + + /** + * Resets the date to the first day of the quarter and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfQuarter(); + * ``` + * + * @return static + */ + public function startOfQuarter() + { + $month = ($this->quarter - 1) * static::MONTHS_PER_QUARTER + 1; + + return $this->setDate($this->year, $month, 1)->startOfDay(); + } + + /** + * Resets the date to end of the quarter and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfQuarter(); + * ``` + * + * @return static + */ + public function endOfQuarter() + { + return $this->startOfQuarter()->addMonths(static::MONTHS_PER_QUARTER - 1)->endOfMonth(); + } + + /** + * Resets the date to the first day of the year and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfYear(); + * ``` + * + * @return static + */ + public function startOfYear() + { + return $this->setDate($this->year, 1, 1)->startOfDay(); + } + + /** + * Resets the date to end of the year and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfYear(); + * ``` + * + * @return static + */ + public function endOfYear() + { + return $this->setDate($this->year, 12, 31)->endOfDay(); + } + + /** + * Resets the date to the first day of the decade and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfDecade(); + * ``` + * + * @return static + */ + public function startOfDecade() + { + $year = $this->year - $this->year % static::YEARS_PER_DECADE; + + return $this->setDate($year, 1, 1)->startOfDay(); + } + + /** + * Resets the date to end of the decade and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfDecade(); + * ``` + * + * @return static + */ + public function endOfDecade() + { + $year = $this->year - $this->year % static::YEARS_PER_DECADE + static::YEARS_PER_DECADE - 1; + + return $this->setDate($year, 12, 31)->endOfDay(); + } + + /** + * Resets the date to the first day of the century and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfCentury(); + * ``` + * + * @return static + */ + public function startOfCentury() + { + $year = $this->year - ($this->year - 1) % static::YEARS_PER_CENTURY; + + return $this->setDate($year, 1, 1)->startOfDay(); + } + + /** + * Resets the date to end of the century and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfCentury(); + * ``` + * + * @return static + */ + public function endOfCentury() + { + $year = $this->year - 1 - ($this->year - 1) % static::YEARS_PER_CENTURY + static::YEARS_PER_CENTURY; + + return $this->setDate($year, 12, 31)->endOfDay(); + } + + /** + * Resets the date to the first day of the millennium and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfMillennium(); + * ``` + * + * @return static + */ + public function startOfMillennium() + { + $year = $this->year - ($this->year - 1) % static::YEARS_PER_MILLENNIUM; + + return $this->setDate($year, 1, 1)->startOfDay(); + } + + /** + * Resets the date to end of the millennium and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfMillennium(); + * ``` + * + * @return static + */ + public function endOfMillennium() + { + $year = $this->year - 1 - ($this->year - 1) % static::YEARS_PER_MILLENNIUM + static::YEARS_PER_MILLENNIUM; + + return $this->setDate($year, 12, 31)->endOfDay(); + } + + /** + * Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->startOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek(Carbon::SUNDAY) . "\n"; + * ``` + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return static + */ + public function startOfWeek($weekStartsAt = null) + { + return $this->subDays((7 + $this->dayOfWeek - ($weekStartsAt ?? $this->firstWeekDay)) % 7)->startOfDay(); + } + + /** + * Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59.999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->endOfWeek() . "\n"; + * echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek(Carbon::SATURDAY) . "\n"; + * ``` + * + * @param int $weekEndsAt optional start allow you to specify the day of week to use to end the week + * + * @return static + */ + public function endOfWeek($weekEndsAt = null) + { + return $this->addDays((7 - $this->dayOfWeek + ($weekEndsAt ?? $this->lastWeekDay)) % 7)->endOfDay(); + } + + /** + * Modify to start of current hour, minutes and seconds become 0 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfHour(); + * ``` + * + * @return static + */ + public function startOfHour() + { + return $this->setTime($this->hour, 0, 0, 0); + } + + /** + * Modify to end of current hour, minutes and seconds become 59 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfHour(); + * ``` + * + * @return static + */ + public function endOfHour() + { + return $this->setTime($this->hour, static::MINUTES_PER_HOUR - 1, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1); + } + + /** + * Modify to start of current minute, seconds become 0 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->startOfMinute(); + * ``` + * + * @return static + */ + public function startOfMinute() + { + return $this->setTime($this->hour, $this->minute, 0, 0); + } + + /** + * Modify to end of current minute, seconds become 59 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16')->endOfMinute(); + * ``` + * + * @return static + */ + public function endOfMinute() + { + return $this->setTime($this->hour, $this->minute, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1); + } + + /** + * Modify to start of current second, microseconds become 0 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->startOfSecond() + * ->format('H:i:s.u'); + * ``` + * + * @return static + */ + public function startOfSecond() + { + return $this->setTime($this->hour, $this->minute, $this->second, 0); + } + + /** + * Modify to end of current second, microseconds become 999999 + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->endOfSecond() + * ->format('H:i:s.u'); + * ``` + * + * @return static + */ + public function endOfSecond() + { + return $this->setTime($this->hour, $this->minute, $this->second, static::MICROSECONDS_PER_SECOND - 1); + } + + /** + * Modify to start of current given unit. + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->startOf('month') + * ->endOf('week', Carbon::FRIDAY); + * ``` + * + * @param string $unit + * @param array<int, mixed> $params + * + * @return static + */ + public function startOf($unit, ...$params) + { + $ucfUnit = ucfirst(static::singularUnit($unit)); + $method = "startOf$ucfUnit"; + if (!method_exists($this, $method)) { + throw new UnknownUnitException($unit); + } + + return $this->$method(...$params); + } + + /** + * Modify to end of current given unit. + * + * @example + * ``` + * echo Carbon::parse('2018-07-25 12:45:16.334455') + * ->startOf('month') + * ->endOf('week', Carbon::FRIDAY); + * ``` + * + * @param string $unit + * @param array<int, mixed> $params + * + * @return static + */ + public function endOf($unit, ...$params) + { + $ucfUnit = ucfirst(static::singularUnit($unit)); + $method = "endOf$ucfUnit"; + if (!method_exists($this, $method)) { + throw new UnknownUnitException($unit); + } + + return $this->$method(...$params); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Cast.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Cast.php new file mode 100644 index 0000000..5f7c7c0 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Cast.php @@ -0,0 +1,43 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Exceptions\InvalidCastException; +use DateTimeInterface; + +/** + * Trait Cast. + * + * Utils to cast into an other class. + */ +trait Cast +{ + /** + * Cast the current instance into the given class. + * + * @param string $className The $className::instance() method will be called to cast the current object. + * + * @return DateTimeInterface + */ + public function cast(string $className) + { + if (!method_exists($className, 'instance')) { + if (is_a($className, DateTimeInterface::class, true)) { + return new $className($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone()); + } + + throw new InvalidCastException("$className has not the instance() method needed to cast the date."); + } + + return $className::instance($this); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php new file mode 100644 index 0000000..f6261d8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php @@ -0,0 +1,1125 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use BadMethodCallException; +use Carbon\CarbonInterface; +use Carbon\Exceptions\BadComparisonUnitException; +use InvalidArgumentException; + +/** + * Trait Comparison. + * + * Comparison utils and testers. All the following methods return booleans. + * nowWithSameTz + * + * Depends on the following methods: + * + * @method static resolveCarbon($date) + * @method static copy() + * @method static nowWithSameTz() + * @method static static yesterday($timezone = null) + * @method static static tomorrow($timezone = null) + */ +trait Comparison +{ + /** @var bool */ + protected $endOfTime = false; + + /** @var bool */ + protected $startOfTime = false; + + /** + * Determines if the instance is equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true + * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see equalTo() + * + * @return bool + */ + public function eq($date): bool + { + return $this->equalTo($date); + } + + /** + * Determines if the instance is equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true + * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function equalTo($date): bool + { + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this == $this->resolveCarbon($date); + } + + /** + * Determines if the instance is not equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false + * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see notEqualTo() + * + * @return bool + */ + public function ne($date): bool + { + return $this->notEqualTo($date); + } + + /** + * Determines if the instance is not equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false + * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function notEqualTo($date): bool + { + return !$this->equalTo($date); + } + + /** + * Determines if the instance is greater (after) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see greaterThan() + * + * @return bool + */ + public function gt($date): bool + { + return $this->greaterThan($date); + } + + /** + * Determines if the instance is greater (after) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function greaterThan($date): bool + { + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this > $this->resolveCarbon($date); + } + + /** + * Determines if the instance is greater (after) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see greaterThan() + * + * @return bool + */ + public function isAfter($date): bool + { + return $this->greaterThan($date); + } + + /** + * Determines if the instance is greater (after) than or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see greaterThanOrEqualTo() + * + * @return bool + */ + public function gte($date): bool + { + return $this->greaterThanOrEqualTo($date); + } + + /** + * Determines if the instance is greater (after) than or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true + * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function greaterThanOrEqualTo($date): bool + { + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this >= $this->resolveCarbon($date); + } + + /** + * Determines if the instance is less (before) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see lessThan() + * + * @return bool + */ + public function lt($date): bool + { + return $this->lessThan($date); + } + + /** + * Determines if the instance is less (before) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function lessThan($date): bool + { + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this < $this->resolveCarbon($date); + } + + /** + * Determines if the instance is less (before) than another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false + * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see lessThan() + * + * @return bool + */ + public function isBefore($date): bool + { + return $this->lessThan($date); + } + + /** + * Determines if the instance is less (before) or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see lessThanOrEqualTo() + * + * @return bool + */ + public function lte($date): bool + { + return $this->lessThanOrEqualTo($date); + } + + /** + * Determines if the instance is less (before) or equal to another + * + * @example + * ``` + * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false + * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true + * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return bool + */ + public function lessThanOrEqualTo($date): bool + { + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this <= $this->resolveCarbon($date); + } + + /** + * Determines if the instance is between two others. + * + * The third argument allow you to specify if bounds are included or not (true by default) + * but for when you including/excluding bounds may produce different results in your application, + * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. + * + * @example + * ``` + * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * @param bool $equal Indicates if an equal to comparison should be done + * + * @return bool + */ + public function between($date1, $date2, $equal = true): bool + { + $date1 = $this->resolveCarbon($date1); + $date2 = $this->resolveCarbon($date2); + + if ($date1->greaterThan($date2)) { + [$date1, $date2] = [$date2, $date1]; + } + + if ($equal) { + return $this >= $date1 && $this <= $date2; + } + + return $this > $date1 && $this < $date2; + } + + /** + * Determines if the instance is between two others, bounds included. + * + * @example + * ``` + * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return bool + */ + public function betweenIncluded($date1, $date2): bool + { + return $this->between($date1, $date2, true); + } + + /** + * Determines if the instance is between two others, bounds excluded. + * + * @example + * ``` + * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return bool + */ + public function betweenExcluded($date1, $date2): bool + { + return $this->between($date1, $date2, false); + } + + /** + * Determines if the instance is between two others + * + * @example + * ``` + * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false + * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true + * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * @param bool $equal Indicates if an equal to comparison should be done + * + * @return bool + */ + public function isBetween($date1, $date2, $equal = true): bool + { + return $this->between($date1, $date2, $equal); + } + + /** + * Determines if the instance is a weekday. + * + * @example + * ``` + * Carbon::parse('2019-07-14')->isWeekday(); // false + * Carbon::parse('2019-07-15')->isWeekday(); // true + * ``` + * + * @return bool + */ + public function isWeekday() + { + return !$this->isWeekend(); + } + + /** + * Determines if the instance is a weekend day. + * + * @example + * ``` + * Carbon::parse('2019-07-14')->isWeekend(); // true + * Carbon::parse('2019-07-15')->isWeekend(); // false + * ``` + * + * @return bool + */ + public function isWeekend() + { + return \in_array($this->dayOfWeek, static::$weekendDays, true); + } + + /** + * Determines if the instance is yesterday. + * + * @example + * ``` + * Carbon::yesterday()->isYesterday(); // true + * Carbon::tomorrow()->isYesterday(); // false + * ``` + * + * @return bool + */ + public function isYesterday() + { + return $this->toDateString() === static::yesterday($this->getTimezone())->toDateString(); + } + + /** + * Determines if the instance is today. + * + * @example + * ``` + * Carbon::today()->isToday(); // true + * Carbon::tomorrow()->isToday(); // false + * ``` + * + * @return bool + */ + public function isToday() + { + return $this->toDateString() === $this->nowWithSameTz()->toDateString(); + } + + /** + * Determines if the instance is tomorrow. + * + * @example + * ``` + * Carbon::tomorrow()->isTomorrow(); // true + * Carbon::yesterday()->isTomorrow(); // false + * ``` + * + * @return bool + */ + public function isTomorrow() + { + return $this->toDateString() === static::tomorrow($this->getTimezone())->toDateString(); + } + + /** + * Determines if the instance is in the future, ie. greater (after) than now. + * + * @example + * ``` + * Carbon::now()->addHours(5)->isFuture(); // true + * Carbon::now()->subHours(5)->isFuture(); // false + * ``` + * + * @return bool + */ + public function isFuture() + { + return $this->greaterThan($this->nowWithSameTz()); + } + + /** + * Determines if the instance is in the past, ie. less (before) than now. + * + * @example + * ``` + * Carbon::now()->subHours(5)->isPast(); // true + * Carbon::now()->addHours(5)->isPast(); // false + * ``` + * + * @return bool + */ + public function isPast() + { + return $this->lessThan($this->nowWithSameTz()); + } + + /** + * Determines if the instance is a leap year. + * + * @example + * ``` + * Carbon::parse('2020-01-01')->isLeapYear(); // true + * Carbon::parse('2019-01-01')->isLeapYear(); // false + * ``` + * + * @return bool + */ + public function isLeapYear() + { + return $this->rawFormat('L') === '1'; + } + + /** + * Determines if the instance is a long year (using calendar year). + * + * ⚠️ This method completely ignores month and day to use the numeric year number, + * it's not correct if the exact date matters. For instance as `2019-12-30` is already + * in the first week of the 2020 year, if you want to know from this date if ISO week + * year 2020 is a long year, use `isLongIsoYear` instead. + * + * @example + * ``` + * Carbon::create(2015)->isLongYear(); // true + * Carbon::create(2016)->isLongYear(); // false + * ``` + * + * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * @return bool + */ + public function isLongYear() + { + return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; + } + + /** + * Determines if the instance is a long year (using ISO 8601 year). + * + * @example + * ``` + * Carbon::parse('2015-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-03')->isLongIsoYear(); // false + * Carbon::parse('2019-12-29')->isLongIsoYear(); // false + * Carbon::parse('2019-12-30')->isLongIsoYear(); // true + * ``` + * + * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * @return bool + */ + public function isLongIsoYear() + { + return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; + } + + /** + * Compares the formatted values of the two dates. + * + * @example + * ``` + * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true + * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false + * ``` + * + * @param string $format date formats to compare. + * @param \Carbon\Carbon|\DateTimeInterface|string|null $date instance to compare with or null to use current day. + * + * @return bool + */ + public function isSameAs($format, $date = null) + { + return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); + } + + /** + * Determines if the instance is in the current unit given. + * + * @example + * ``` + * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true + * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false + * ``` + * + * @param string $unit singular unit string + * @param \Carbon\Carbon|\DateTimeInterface|null $date instance to compare with or null to use current day. + * + * @throws BadComparisonUnitException + * + * @return bool + */ + public function isSameUnit($unit, $date = null) + { + $units = [ + // @call isSameUnit + 'year' => 'Y', + // @call isSameUnit + 'week' => 'o-W', + // @call isSameUnit + 'day' => 'Y-m-d', + // @call isSameUnit + 'hour' => 'Y-m-d H', + // @call isSameUnit + 'minute' => 'Y-m-d H:i', + // @call isSameUnit + 'second' => 'Y-m-d H:i:s', + // @call isSameUnit + 'micro' => 'Y-m-d H:i:s.u', + // @call isSameUnit + 'microsecond' => 'Y-m-d H:i:s.u', + ]; + + if (isset($units[$unit])) { + return $this->isSameAs($units[$unit], $date); + } + + if (isset($this->$unit)) { + return $this->resolveCarbon($date)->$unit === $this->$unit; + } + + if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) { + throw new BadComparisonUnitException($unit); + } + + return false; + } + + /** + * Determines if the instance is in the current unit given. + * + * @example + * ``` + * Carbon::now()->isCurrentUnit('hour'); // true + * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false + * ``` + * + * @param string $unit The unit to test. + * + * @throws BadMethodCallException + * + * @return bool + */ + public function isCurrentUnit($unit) + { + return $this->{'isSame'.ucfirst($unit)}(); + } + + /** + * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). + * + * @example + * ``` + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false + * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|string|null $date The instance to compare with or null to use current day. + * @param bool $ofSameYear Check if it is the same month in the same year. + * + * @return bool + */ + public function isSameQuarter($date = null, $ofSameYear = true) + { + $date = $this->resolveCarbon($date); + + return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); + } + + /** + * Checks if the passed in date is in the same month as the instance´s month. + * + * @example + * ``` + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false + * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use the current date. + * @param bool $ofSameYear Check if it is the same month in the same year. + * + * @return bool + */ + public function isSameMonth($date = null, $ofSameYear = true) + { + return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); + } + + /** + * Checks if this day is a specific day of the week. + * + * @example + * ``` + * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true + * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false + * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true + * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false + * ``` + * + * @param int $dayOfWeek + * + * @return bool + */ + public function isDayOfWeek($dayOfWeek) + { + if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { + $dayOfWeek = \constant($constant); + } + + return $this->dayOfWeek === $dayOfWeek; + } + + /** + * Check if its the birthday. Compares the date/month values of the two dates. + * + * @example + * ``` + * Carbon::now()->subYears(5)->isBirthday(); // true + * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false + * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true + * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false + * ``` + * + * @param \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use current day. + * + * @return bool + */ + public function isBirthday($date = null) + { + return $this->isSameAs('md', $date); + } + + /** + * Check if today is the last day of the Month + * + * @example + * ``` + * Carbon::parse('2019-02-28')->isLastOfMonth(); // true + * Carbon::parse('2019-03-28')->isLastOfMonth(); // false + * Carbon::parse('2019-03-30')->isLastOfMonth(); // false + * Carbon::parse('2019-03-31')->isLastOfMonth(); // true + * Carbon::parse('2019-04-30')->isLastOfMonth(); // true + * ``` + * + * @return bool + */ + public function isLastOfMonth() + { + return $this->day === $this->daysInMonth; + } + + /** + * Check if the instance is start of day / midnight. + * + * @example + * ``` + * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true + * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true + * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false + * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true + * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false + * ``` + * + * @param bool $checkMicroseconds check time at microseconds precision + * + * @return bool + */ + public function isStartOfDay($checkMicroseconds = false) + { + /* @var CarbonInterface $this */ + return $checkMicroseconds + ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' + : $this->rawFormat('H:i:s') === '00:00:00'; + } + + /** + * Check if the instance is end of day. + * + * @example + * ``` + * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true + * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true + * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true + * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false + * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true + * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false + * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false + * ``` + * + * @param bool $checkMicroseconds check time at microseconds precision + * + * @return bool + */ + public function isEndOfDay($checkMicroseconds = false) + { + /* @var CarbonInterface $this */ + return $checkMicroseconds + ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' + : $this->rawFormat('H:i:s') === '23:59:59'; + } + + /** + * Check if the instance is start of day / midnight. + * + * @example + * ``` + * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true + * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true + * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false + * ``` + * + * @return bool + */ + public function isMidnight() + { + return $this->isStartOfDay(); + } + + /** + * Check if the instance is midday. + * + * @example + * ``` + * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false + * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true + * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true + * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false + * ``` + * + * @return bool + */ + public function isMidday() + { + /* @var CarbonInterface $this */ + return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; + } + + /** + * Checks if the (date)time string is in a given format. + * + * @example + * ``` + * Carbon::hasFormat('11:12:45', 'h:i:s'); // true + * Carbon::hasFormat('13:12:45', 'h:i:s'); // false + * ``` + * + * @param string $date + * @param string $format + * + * @return bool + */ + public static function hasFormat($date, $format) + { + // createFromFormat() is known to handle edge cases silently. + // E.g. "1975-5-1" (Y-n-j) will still be parsed correctly when "Y-m-d" is supplied as the format. + // To ensure we're really testing against our desired format, perform an additional regex validation. + + return self::matchFormatPattern((string) $date, preg_quote((string) $format, '/'), static::$regexFormats); + } + + /** + * Checks if the (date)time string is in a given format. + * + * @example + * ``` + * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true + * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false + * ``` + * + * @param string $date + * @param string $format + * + * @return bool + */ + public static function hasFormatWithModifiers($date, $format): bool + { + return self::matchFormatPattern((string) $date, (string) $format, array_merge(static::$regexFormats, static::$regexFormatModifiers)); + } + + /** + * Checks if the (date)time string is in a given format and valid to create a + * new instance. + * + * @example + * ``` + * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true + * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false + * ``` + * + * @param string $date + * @param string $format + * + * @return bool + */ + public static function canBeCreatedFromFormat($date, $format) + { + try { + // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string + // doesn't match the format in any way. + if (!static::rawCreateFromFormat($format, $date)) { + return false; + } + } catch (InvalidArgumentException $e) { + return false; + } + + return static::hasFormatWithModifiers($date, $format); + } + + /** + * Returns true if the current date matches the given string. + * + * @example + * ``` + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false + * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true + * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true + * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false + * ``` + * + * @param string $tester day name, month name, hour, date, etc. as string + * + * @return bool + */ + public function is(string $tester) + { + $tester = trim($tester); + + if (preg_match('/^\d+$/', $tester)) { + return $this->year === (int) $tester; + } + + if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { + return $this->isSameMonth(static::parse($tester)); + } + + if (preg_match('/^\d{1,2}-\d{1,2}$/', $tester)) { + return $this->isSameDay(static::parse($this->year.'-'.$tester)); + } + + $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); + + /* @var CarbonInterface $max */ + $median = static::parse('5555-06-15 12:30:30.555555')->modify($modifier); + $current = $this->avoidMutation(); + /* @var CarbonInterface $other */ + $other = $this->avoidMutation()->modify($modifier); + + if ($current->eq($other)) { + return true; + } + + if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { + return $current->startOfSecond()->eq($other); + } + + if (preg_match('/\d:\d{1,2}$/', $tester)) { + return $current->startOfMinute()->eq($other); + } + + if (preg_match('/\d(?:h|am|pm)$/', $tester)) { + return $current->startOfHour()->eq($other); + } + + if (preg_match( + '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', + $tester + )) { + return $current->startOfMonth()->eq($other->startOfMonth()); + } + + $units = [ + 'month' => [1, 'year'], + 'day' => [1, 'month'], + 'hour' => [0, 'day'], + 'minute' => [0, 'hour'], + 'second' => [0, 'minute'], + 'microsecond' => [0, 'second'], + ]; + + foreach ($units as $unit => [$minimum, $startUnit]) { + if ($minimum === $median->$unit) { + $current = $current->startOf($startUnit); + + break; + } + } + + return $current->eq($other); + } + + /** + * Checks if the (date)time string is in a given format with + * given list of pattern replacements. + * + * @example + * ``` + * Carbon::hasFormat('11:12:45', 'h:i:s'); // true + * Carbon::hasFormat('13:12:45', 'h:i:s'); // false + * ``` + * + * @param string $date + * @param string $format + * @param array $replacements + * + * @return bool + */ + private static function matchFormatPattern(string $date, string $format, array $replacements): bool + { + // Preg quote, but remove escaped backslashes since we'll deal with escaped characters in the format string. + $regex = str_replace('\\\\', '\\', $format); + // Replace not-escaped letters + $regex = preg_replace_callback( + '/(?<!\\\\)((?:\\\\{2})*)(['.implode('', array_keys($replacements)).'])/', + function ($match) use ($replacements) { + return $match[1].strtr($match[2], $replacements); + }, + $regex + ); + // Replace escaped letters by the letter itself + $regex = preg_replace('/(?<!\\\\)((?:\\\\{2})*)\\\\(\w)/', '$1$2', $regex); + // Escape not escaped slashes + $regex = preg_replace('#(?<!\\\\)((?:\\\\{2})*)/#', '$1\\/', $regex); + + return (bool) @preg_match('/^'.$regex.'$/', $date); + } + + /** + * Returns true if the date was created using CarbonImmutable::startOfTime() + * + * @return bool + */ + public function isStartOfTime(): bool + { + return $this->startOfTime ?? false; + } + + /** + * Returns true if the date was created using CarbonImmutable::endOfTime() + * + * @return bool + */ + public function isEndOfTime(): bool + { + return $this->endOfTime ?? false; + } + + private function discourageNull($value): void + { + if ($value === null) { + @trigger_error("Since 2.61.0, it's deprecated to compare a date to null, meaning of such comparison is ambiguous and will no longer be possible in 3.0.0, you should explicitly pass 'now' or make an other check to eliminate null values.", \E_USER_DEPRECATED); + } + } + + private function discourageBoolean($value): void + { + if (\is_bool($value)) { + @trigger_error("Since 2.61.0, it's deprecated to compare a date to true or false, meaning of such comparison is ambiguous and will no longer be possible in 3.0.0, you should explicitly pass 'now' or make an other check to eliminate boolean values.", \E_USER_DEPRECATED); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php new file mode 100644 index 0000000..fff8a60 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php @@ -0,0 +1,639 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Carbon; +use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; +use Carbon\CarbonInterval; +use Carbon\CarbonPeriod; +use Carbon\CarbonPeriodImmutable; +use Carbon\Exceptions\UnitException; +use Closure; +use DateTime; +use DateTimeImmutable; +use ReturnTypeWillChange; + +/** + * Trait Converter. + * + * Change date into different string formats and types and + * handle the string cast. + * + * Depends on the following methods: + * + * @method static copy() + */ +trait Converter +{ + use ToStringFormat; + + /** + * Returns the formatted date string on success or FALSE on failure. + * + * @see https://php.net/manual/en/datetime.format.php + * + * @param string $format + * + * @return string + */ + #[ReturnTypeWillChange] + public function format($format) + { + $function = $this->localFormatFunction ?: static::$formatFunction; + + if (!$function) { + return $this->rawFormat($format); + } + + if (\is_string($function) && method_exists($this, $function)) { + $function = [$this, $function]; + } + + return $function(...\func_get_args()); + } + + /** + * @see https://php.net/manual/en/datetime.format.php + * + * @param string $format + * + * @return string + */ + public function rawFormat($format) + { + return parent::format($format); + } + + /** + * Format the instance as a string using the set format + * + * @example + * ``` + * echo Carbon::now(); // Carbon instances can be cast to string + * ``` + * + * @return string + */ + public function __toString() + { + $format = $this->localToStringFormat ?? static::$toStringFormat; + + return $format instanceof Closure + ? $format($this) + : $this->rawFormat($format ?: ( + \defined('static::DEFAULT_TO_STRING_FORMAT') + ? static::DEFAULT_TO_STRING_FORMAT + : CarbonInterface::DEFAULT_TO_STRING_FORMAT + )); + } + + /** + * Format the instance as date + * + * @example + * ``` + * echo Carbon::now()->toDateString(); + * ``` + * + * @return string + */ + public function toDateString() + { + return $this->rawFormat('Y-m-d'); + } + + /** + * Format the instance as a readable date + * + * @example + * ``` + * echo Carbon::now()->toFormattedDateString(); + * ``` + * + * @return string + */ + public function toFormattedDateString() + { + return $this->rawFormat('M j, Y'); + } + + /** + * Format the instance with the day, and a readable date + * + * @example + * ``` + * echo Carbon::now()->toFormattedDayDateString(); + * ``` + * + * @return string + */ + public function toFormattedDayDateString(): string + { + return $this->rawFormat('D, M j, Y'); + } + + /** + * Format the instance as time + * + * @example + * ``` + * echo Carbon::now()->toTimeString(); + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toTimeString($unitPrecision = 'second') + { + return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision)); + } + + /** + * Format the instance as date and time + * + * @example + * ``` + * echo Carbon::now()->toDateTimeString(); + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toDateTimeString($unitPrecision = 'second') + { + return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)); + } + + /** + * Return a format from H:i to H:i:s.u according to given unit precision. + * + * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" + * + * @return string + */ + public static function getTimeFormatByPrecision($unitPrecision) + { + switch (static::singularUnit($unitPrecision)) { + case 'minute': + return 'H:i'; + case 'second': + return 'H:i:s'; + case 'm': + case 'millisecond': + return 'H:i:s.v'; + case 'µ': + case 'microsecond': + return 'H:i:s.u'; + } + + throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'); + } + + /** + * Format the instance as date and time T-separated with no timezone + * + * @example + * ``` + * echo Carbon::now()->toDateTimeLocalString(); + * echo "\n"; + * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toDateTimeLocalString($unitPrecision = 'second') + { + return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision)); + } + + /** + * Format the instance with day, date and time + * + * @example + * ``` + * echo Carbon::now()->toDayDateTimeString(); + * ``` + * + * @return string + */ + public function toDayDateTimeString() + { + return $this->rawFormat('D, M j, Y g:i A'); + } + + /** + * Format the instance as ATOM + * + * @example + * ``` + * echo Carbon::now()->toAtomString(); + * ``` + * + * @return string + */ + public function toAtomString() + { + return $this->rawFormat(DateTime::ATOM); + } + + /** + * Format the instance as COOKIE + * + * @example + * ``` + * echo Carbon::now()->toCookieString(); + * ``` + * + * @return string + */ + public function toCookieString() + { + return $this->rawFormat(DateTime::COOKIE); + } + + /** + * Format the instance as ISO8601 + * + * @example + * ``` + * echo Carbon::now()->toIso8601String(); + * ``` + * + * @return string + */ + public function toIso8601String() + { + return $this->toAtomString(); + } + + /** + * Format the instance as RFC822 + * + * @example + * ``` + * echo Carbon::now()->toRfc822String(); + * ``` + * + * @return string + */ + public function toRfc822String() + { + return $this->rawFormat(DateTime::RFC822); + } + + /** + * Convert the instance to UTC and return as Zulu ISO8601 + * + * @example + * ``` + * echo Carbon::now()->toIso8601ZuluString(); + * ``` + * + * @param string $unitPrecision + * + * @return string + */ + public function toIso8601ZuluString($unitPrecision = 'second') + { + return $this->avoidMutation() + ->utc() + ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z'); + } + + /** + * Format the instance as RFC850 + * + * @example + * ``` + * echo Carbon::now()->toRfc850String(); + * ``` + * + * @return string + */ + public function toRfc850String() + { + return $this->rawFormat(DateTime::RFC850); + } + + /** + * Format the instance as RFC1036 + * + * @example + * ``` + * echo Carbon::now()->toRfc1036String(); + * ``` + * + * @return string + */ + public function toRfc1036String() + { + return $this->rawFormat(DateTime::RFC1036); + } + + /** + * Format the instance as RFC1123 + * + * @example + * ``` + * echo Carbon::now()->toRfc1123String(); + * ``` + * + * @return string + */ + public function toRfc1123String() + { + return $this->rawFormat(DateTime::RFC1123); + } + + /** + * Format the instance as RFC2822 + * + * @example + * ``` + * echo Carbon::now()->toRfc2822String(); + * ``` + * + * @return string + */ + public function toRfc2822String() + { + return $this->rawFormat(DateTime::RFC2822); + } + + /** + * Format the instance as RFC3339 + * + * @param bool $extended + * + * @example + * ``` + * echo Carbon::now()->toRfc3339String() . "\n"; + * echo Carbon::now()->toRfc3339String(true) . "\n"; + * ``` + * + * @return string + */ + public function toRfc3339String($extended = false) + { + $format = DateTime::RFC3339; + if ($extended) { + $format = DateTime::RFC3339_EXTENDED; + } + + return $this->rawFormat($format); + } + + /** + * Format the instance as RSS + * + * @example + * ``` + * echo Carbon::now()->toRssString(); + * ``` + * + * @return string + */ + public function toRssString() + { + return $this->rawFormat(DateTime::RSS); + } + + /** + * Format the instance as W3C + * + * @example + * ``` + * echo Carbon::now()->toW3cString(); + * ``` + * + * @return string + */ + public function toW3cString() + { + return $this->rawFormat(DateTime::W3C); + } + + /** + * Format the instance as RFC7231 + * + * @example + * ``` + * echo Carbon::now()->toRfc7231String(); + * ``` + * + * @return string + */ + public function toRfc7231String() + { + return $this->avoidMutation() + ->setTimezone('GMT') + ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT); + } + + /** + * Get default array representation. + * + * @example + * ``` + * var_dump(Carbon::now()->toArray()); + * ``` + * + * @return array + */ + public function toArray() + { + return [ + 'year' => $this->year, + 'month' => $this->month, + 'day' => $this->day, + 'dayOfWeek' => $this->dayOfWeek, + 'dayOfYear' => $this->dayOfYear, + 'hour' => $this->hour, + 'minute' => $this->minute, + 'second' => $this->second, + 'micro' => $this->micro, + 'timestamp' => $this->timestamp, + 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), + 'timezone' => $this->timezone, + ]; + } + + /** + * Get default object representation. + * + * @example + * ``` + * var_dump(Carbon::now()->toObject()); + * ``` + * + * @return object + */ + public function toObject() + { + return (object) $this->toArray(); + } + + /** + * Returns english human readable complete date string. + * + * @example + * ``` + * echo Carbon::now()->toString(); + * ``` + * + * @return string + */ + public function toString() + { + return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + } + + /** + * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: + * 1977-04-22T01:00:00-05:00). + * + * @example + * ``` + * echo Carbon::now('America/Toronto')->toISOString() . "\n"; + * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; + * ``` + * + * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. + * + * @return null|string + */ + public function toISOString($keepOffset = false) + { + if (!$this->isValid()) { + return null; + } + + $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; + $tzFormat = $keepOffset ? 'Z' : '[Z]'; + $date = $keepOffset ? $this : $this->avoidMutation()->utc(); + + return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$tzFormat"); + } + + /** + * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. + * + * @example + * ``` + * echo Carbon::now('America/Toronto')->toJSON(); + * ``` + * + * @return null|string + */ + public function toJSON() + { + return $this->toISOString(); + } + + /** + * Return native DateTime PHP object matching the current instance. + * + * @example + * ``` + * var_dump(Carbon::now()->toDateTime()); + * ``` + * + * @return DateTime + */ + public function toDateTime() + { + return new DateTime($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone()); + } + + /** + * Return native toDateTimeImmutable PHP object matching the current instance. + * + * @example + * ``` + * var_dump(Carbon::now()->toDateTimeImmutable()); + * ``` + * + * @return DateTimeImmutable + */ + public function toDateTimeImmutable() + { + return new DateTimeImmutable($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone()); + } + + /** + * @alias toDateTime + * + * Return native DateTime PHP object matching the current instance. + * + * @example + * ``` + * var_dump(Carbon::now()->toDate()); + * ``` + * + * @return DateTime + */ + public function toDate() + { + return $this->toDateTime(); + } + + /** + * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). + * + * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int + * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit + * @param string|null $unit if specified, $interval must be an integer + * + * @return CarbonPeriod + */ + public function toPeriod($end = null, $interval = null, $unit = null) + { + if ($unit) { + $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); + } + + $period = ($this->isMutable() ? new CarbonPeriod() : new CarbonPeriodImmutable()) + ->setDateClass(static::class) + ->setStartDate($this); + + if ($interval) { + $period = $period->setDateInterval($interval); + } + + if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { + $period = $period->setRecurrences($end); + } elseif ($end) { + $period = $period->setEndDate($end); + } + + return $period; + } + + /** + * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). + * + * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date + * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit + * @param string|null $unit if specified, $interval must be an integer + * + * @return CarbonPeriod + */ + public function range($end = null, $interval = null, $unit = null) + { + return $this->toPeriod($end, $interval, $unit); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php new file mode 100644 index 0000000..0d611ea --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php @@ -0,0 +1,977 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Carbon; +use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; +use Carbon\Exceptions\InvalidDateException; +use Carbon\Exceptions\InvalidFormatException; +use Carbon\Exceptions\OutOfRangeException; +use Carbon\Translator; +use Closure; +use DateMalformedStringException; +use DateTimeImmutable; +use DateTimeInterface; +use DateTimeZone; +use Exception; +use ReturnTypeWillChange; + +/** + * Trait Creator. + * + * Static creators. + * + * Depends on the following methods: + * + * @method static Carbon|CarbonImmutable getTestNow() + */ +trait Creator +{ + use ObjectInitialisation; + + /** + * The errors that can occur. + * + * @var array + */ + protected static $lastErrors; + + /** + * Create a new Carbon instance. + * + * Please see the testing aids section (specifically static::setTestNow()) + * for more on the possibility of this constructor returning a test instance. + * + * @param DateTimeInterface|string|null $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + */ + public function __construct($time = null, $tz = null) + { + if ($time instanceof DateTimeInterface) { + $time = $this->constructTimezoneFromDateTime($time, $tz)->format('Y-m-d H:i:s.u'); + } + + if (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { + $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); + } + + // If the class has a test now set and we are trying to create a now() + // instance then override as required + $isNow = empty($time) || $time === 'now'; + + if (method_exists(static::class, 'hasTestNow') && + method_exists(static::class, 'getTestNow') && + static::hasTestNow() && + ($isNow || static::hasRelativeKeywords($time)) + ) { + static::mockConstructorParameters($time, $tz); + } + + // Work-around for PHP bug https://bugs.php.net/bug.php?id=67127 + if (!str_contains((string) .1, '.')) { + $locale = setlocale(LC_NUMERIC, '0'); // @codeCoverageIgnore + setlocale(LC_NUMERIC, 'C'); // @codeCoverageIgnore + } + + try { + parent::__construct($time ?: 'now', static::safeCreateDateTimeZone($tz) ?: null); + } catch (Exception $exception) { + throw new InvalidFormatException($exception->getMessage(), 0, $exception); + } + + $this->constructedObjectId = spl_object_hash($this); + + if (isset($locale)) { + setlocale(LC_NUMERIC, $locale); // @codeCoverageIgnore + } + + self::setLastErrors(parent::getLastErrors()); + } + + /** + * Get timezone from a datetime instance. + * + * @param DateTimeInterface $date + * @param DateTimeZone|string|null $tz + * + * @return DateTimeInterface + */ + private function constructTimezoneFromDateTime(DateTimeInterface $date, &$tz) + { + if ($tz !== null) { + $safeTz = static::safeCreateDateTimeZone($tz); + + if ($safeTz) { + return ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); + } + + return $date; + } + + $tz = $date->getTimezone(); + + return $date; + } + + /** + * Update constructedObjectId on cloned. + */ + public function __clone() + { + $this->constructedObjectId = spl_object_hash($this); + } + + /** + * Create a Carbon instance from a DateTime one. + * + * @param DateTimeInterface $date + * + * @return static + */ + public static function instance($date) + { + if ($date instanceof static) { + return clone $date; + } + + static::expectDateTime($date); + + $instance = new static($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); + + if ($date instanceof CarbonInterface) { + $settings = $date->getSettings(); + + if (!$date->hasLocalTranslator()) { + unset($settings['locale']); + } + + $instance->settings($settings); + } + + return $instance; + } + + /** + * Create a carbon instance from a string. + * + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * + * @param string|DateTimeInterface|null $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function rawParse($time = null, $tz = null) + { + if ($time instanceof DateTimeInterface) { + return static::instance($time); + } + + try { + return new static($time, $tz); + } catch (Exception $exception) { + // @codeCoverageIgnoreStart + try { + $date = @static::now($tz)->change($time); + } catch (DateMalformedStringException $ignoredException) { + $date = null; + } + // @codeCoverageIgnoreEnd + + if (!$date) { + throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); + } + + return $date; + } + } + + /** + * Create a carbon instance from a string. + * + * This is an alias for the constructor that allows better fluent syntax + * as it allows you to do Carbon::parse('Monday next week')->fn() rather + * than (new Carbon('Monday next week'))->fn(). + * + * @param string|DateTimeInterface|null $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function parse($time = null, $tz = null) + { + $function = static::$parseFunction; + + if (!$function) { + return static::rawParse($time, $tz); + } + + if (\is_string($function) && method_exists(static::class, $function)) { + $function = [static::class, $function]; + } + + return $function(...\func_get_args()); + } + + /** + * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). + * + * @param string $time date/time string in the given language (may also contain English). + * @param string|null $locale if locale is null or not specified, current global locale will be + * used instead. + * @param DateTimeZone|string|null $tz optional timezone for the new instance. + * + * @throws InvalidFormatException + * + * @return static + */ + public static function parseFromLocale($time, $locale = null, $tz = null) + { + return static::rawParse(static::translateTimeString($time, $locale, 'en'), $tz); + } + + /** + * Get a Carbon instance for the current date and time. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function now($tz = null) + { + return new static(null, $tz); + } + + /** + * Create a Carbon instance for today. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function today($tz = null) + { + return static::rawParse('today', $tz); + } + + /** + * Create a Carbon instance for tomorrow. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function tomorrow($tz = null) + { + return static::rawParse('tomorrow', $tz); + } + + /** + * Create a Carbon instance for yesterday. + * + * @param DateTimeZone|string|null $tz + * + * @return static + */ + public static function yesterday($tz = null) + { + return static::rawParse('yesterday', $tz); + } + + /** + * Create a Carbon instance for the greatest supported date. + * + * @return static + */ + public static function maxValue() + { + if (self::$PHPIntSize === 4) { + // 32 bit + return static::createFromTimestamp(PHP_INT_MAX); // @codeCoverageIgnore + } + + // 64 bit + return static::create(9999, 12, 31, 23, 59, 59); + } + + /** + * Create a Carbon instance for the lowest supported date. + * + * @return static + */ + public static function minValue() + { + if (self::$PHPIntSize === 4) { + // 32 bit + return static::createFromTimestamp(~PHP_INT_MAX); // @codeCoverageIgnore + } + + // 64 bit + return static::create(1, 1, 1, 0, 0, 0); + } + + private static function assertBetween($unit, $value, $min, $max) + { + if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { + throw new OutOfRangeException($unit, $min, $max, $value); + } + } + + private static function createNowInstance($tz) + { + if (!static::hasTestNow()) { + return static::now($tz); + } + + $now = static::getTestNow(); + + if ($now instanceof Closure) { + return $now(static::now($tz)); + } + + return $now->avoidMutation()->tz($tz); + } + + /** + * Create a new Carbon instance from a specific date and time. + * + * If any of $year, $month or $day are set to null their now() values will + * be used. + * + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * + * If $hour is not null then the default values for $minute and $second + * will be 0. + * + * @param DateTimeInterface|int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) + { + if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { + return static::parse($year, $tz ?: (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); + } + + $defaults = null; + $getDefault = function ($unit) use ($tz, &$defaults) { + if ($defaults === null) { + $now = self::createNowInstance($tz); + + $defaults = array_combine([ + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); + } + + return $defaults[$unit]; + }; + + $year = $year ?? $getDefault('year'); + $month = $month ?? $getDefault('month'); + $day = $day ?? $getDefault('day'); + $hour = $hour ?? $getDefault('hour'); + $minute = $minute ?? $getDefault('minute'); + $second = (float) ($second ?? $getDefault('second')); + + self::assertBetween('month', $month, 0, 99); + self::assertBetween('day', $day, 0, 99); + self::assertBetween('hour', $hour, 0, 99); + self::assertBetween('minute', $minute, 0, 99); + self::assertBetween('second', $second, 0, 99); + + $fixYear = null; + + if ($year < 0) { + $fixYear = $year; + $year = 0; + } elseif ($year > 9999) { + $fixYear = $year - 9999; + $year = 9999; + } + + $second = ($second < 10 ? '0' : '').number_format($second, 6); + $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $tz); + + if ($fixYear !== null) { + $instance = $instance->addYears($fixYear); + } + + return $instance; + } + + /** + * Create a new safe Carbon instance from a specific date and time. + * + * If any of $year, $month or $day are set to null their now() values will + * be used. + * + * If $hour is null it will be set to its now() value and the default + * values for $minute and $second will be their now() values. + * + * If $hour is not null then the default values for $minute and $second + * will be 0. + * + * If one of the set values is not valid, an InvalidDateException + * will be thrown. + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidDateException + * + * @return static|false + */ + public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) + { + $fields = static::getRangesByUnit(); + + foreach ($fields as $field => $range) { + if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { + if (static::isStrictModeEnabled()) { + throw new InvalidDateException($field, $$field); + } + + return false; + } + } + + $instance = static::create($year, $month, $day, $hour, $minute, $second, $tz); + + foreach (array_reverse($fields) as $field => $range) { + if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { + if (static::isStrictModeEnabled()) { + throw new InvalidDateException($field, $$field); + } + + return false; + } + } + + return $instance; + } + + /** + * Create a new Carbon instance from a specific date and time using strict validation. + * + * @see create() + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $tz = null): self + { + $initialStrictMode = static::isStrictModeEnabled(); + static::useStrictMode(true); + + try { + $date = static::create($year, $month, $day, $hour, $minute, $second, $tz); + } finally { + static::useStrictMode($initialStrictMode); + } + + return $date; + } + + /** + * Create a Carbon instance from just a date. The time portion is set to now. + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createFromDate($year = null, $month = null, $day = null, $tz = null) + { + return static::create($year, $month, $day, null, null, null, $tz); + } + + /** + * Create a Carbon instance from just a date. The time portion is set to midnight. + * + * @param int|null $year + * @param int|null $month + * @param int|null $day + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createMidnightDate($year = null, $month = null, $day = null, $tz = null) + { + return static::create($year, $month, $day, 0, 0, 0, $tz); + } + + /** + * Create a Carbon instance from just a time. The date portion is set to today. + * + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null) + { + return static::create(null, null, null, $hour, $minute, $second, $tz); + } + + /** + * Create a Carbon instance from a time string. The date portion is set to today. + * + * @param string $time + * @param DateTimeZone|string|null $tz + * + * @throws InvalidFormatException + * + * @return static + */ + public static function createFromTimeString($time, $tz = null) + { + return static::today($tz)->setTimeFromTimeString($time); + } + + /** + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $originalTz + * + * @return DateTimeInterface|false + */ + private static function createFromFormatAndTimezone($format, $time, $originalTz) + { + // Work-around for https://bugs.php.net/bug.php?id=75577 + // @codeCoverageIgnoreStart + if (version_compare(PHP_VERSION, '7.3.0-dev', '<')) { + $format = str_replace('.v', '.u', $format); + } + // @codeCoverageIgnoreEnd + + if ($originalTz === null) { + return parent::createFromFormat($format, (string) $time); + } + + $tz = \is_int($originalTz) + ? @timezone_name_from_abbr('', (int) ($originalTz * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE), 1) + : $originalTz; + + $tz = static::safeCreateDateTimeZone($tz, $originalTz); + + if ($tz === false) { + return false; + } + + return parent::createFromFormat($format, (string) $time, $tz); + } + + /** + * Create a Carbon instance from a specific format. + * + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function rawCreateFromFormat($format, $time, $tz = null) + { + // Work-around for https://bugs.php.net/bug.php?id=80141 + $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); + + if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && + preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && + $aMatches[1][1] < $hMatches[1][1] && + preg_match('/(am|pm|AM|PM)/', $time) + ) { + $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); + $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); + } + + if ($tz === false) { + $tz = null; + } + + // First attempt to create an instance, so that error messages are based on the unmodified format. + $date = self::createFromFormatAndTimezone($format, $time, $tz); + $lastErrors = parent::getLastErrors(); + /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ + $mock = static::getMockedTestNow($tz); + + if ($mock && $date instanceof DateTimeInterface) { + // Set timezone from mock if custom timezone was neither given directly nor as a part of format. + // First let's skip the part that will be ignored by the parser. + $nonEscaped = '(?<!\\\\)(\\\\{2})*'; + + $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); + + if ($tz === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { + $tz = clone $mock->getTimezone(); + } + + $mock = $mock->copy(); + + // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. + if (!preg_match("/{$nonEscaped}[!|]/", $format)) { + if (preg_match('/[HhGgisvuB]/', $format)) { + $mock = $mock->setTime(0, 0); + } + + $format = static::MOCK_DATETIME_FORMAT.' '.$format; + $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; + } + + // Regenerate date from the modified format to base result on the mocked instance instead of now. + $date = self::createFromFormatAndTimezone($format, $time, $tz); + } + + if ($date instanceof DateTimeInterface) { + $instance = static::instance($date); + $instance::setLastErrors($lastErrors); + + return $instance; + } + + if (static::isStrictModeEnabled()) { + throw new InvalidFormatException(implode(PHP_EOL, $lastErrors['errors'])); + } + + return false; + } + + /** + * Create a Carbon instance from a specific format. + * + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + #[ReturnTypeWillChange] + public static function createFromFormat($format, $time, $tz = null) + { + $function = static::$createFromFormatFunction; + + if (!$function) { + return static::rawCreateFromFormat($format, $time, $tz); + } + + if (\is_string($function) && method_exists(static::class, $function)) { + $function = [static::class, $function]; + } + + return $function(...\func_get_args()); + } + + /** + * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). + * + * @param string $format Datetime format + * @param string $time + * @param DateTimeZone|string|false|null $tz optional timezone + * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) + * @param \Symfony\Component\Translation\TranslatorInterface $translator optional custom translator to use for macro-formats + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null) + { + $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { + [$code] = $match; + + static $formats = null; + + if ($formats === null) { + $translator = $translator ?: Translator::get($locale); + + $formats = [ + 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale, 'h:mm A'), + 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale, 'h:mm:ss A'), + 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale, 'MM/DD/YYYY'), + 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale, 'MMMM D, YYYY'), + 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale, 'MMMM D, YYYY h:mm A'), + 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'), + ]; + } + + return $formats[$code] ?? preg_replace_callback( + '/MMMM|MM|DD|dddd/', + function ($code) { + return mb_substr($code[0], 1); + }, + $formats[strtoupper($code)] ?? '' + ); + }, $format); + + $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { + [$code] = $match; + + static $replacements = null; + + if ($replacements === null) { + $replacements = [ + 'OD' => 'd', + 'OM' => 'M', + 'OY' => 'Y', + 'OH' => 'G', + 'Oh' => 'g', + 'Om' => 'i', + 'Os' => 's', + 'D' => 'd', + 'DD' => 'd', + 'Do' => 'd', + 'd' => '!', + 'dd' => '!', + 'ddd' => 'D', + 'dddd' => 'D', + 'DDD' => 'z', + 'DDDD' => 'z', + 'DDDo' => 'z', + 'e' => '!', + 'E' => '!', + 'H' => 'G', + 'HH' => 'H', + 'h' => 'g', + 'hh' => 'h', + 'k' => 'G', + 'kk' => 'G', + 'hmm' => 'gi', + 'hmmss' => 'gis', + 'Hmm' => 'Gi', + 'Hmmss' => 'Gis', + 'm' => 'i', + 'mm' => 'i', + 'a' => 'a', + 'A' => 'a', + 's' => 's', + 'ss' => 's', + 'S' => '*', + 'SS' => '*', + 'SSS' => '*', + 'SSSS' => '*', + 'SSSSS' => '*', + 'SSSSSS' => 'u', + 'SSSSSSS' => 'u*', + 'SSSSSSSS' => 'u*', + 'SSSSSSSSS' => 'u*', + 'M' => 'm', + 'MM' => 'm', + 'MMM' => 'M', + 'MMMM' => 'M', + 'Mo' => 'm', + 'Q' => '!', + 'Qo' => '!', + 'G' => '!', + 'GG' => '!', + 'GGG' => '!', + 'GGGG' => '!', + 'GGGGG' => '!', + 'g' => '!', + 'gg' => '!', + 'ggg' => '!', + 'gggg' => '!', + 'ggggg' => '!', + 'W' => '!', + 'WW' => '!', + 'Wo' => '!', + 'w' => '!', + 'ww' => '!', + 'wo' => '!', + 'x' => 'U???', + 'X' => 'U', + 'Y' => 'Y', + 'YY' => 'y', + 'YYYY' => 'Y', + 'YYYYY' => 'Y', + 'YYYYYY' => 'Y', + 'z' => 'e', + 'zz' => 'e', + 'Z' => 'e', + 'ZZ' => 'e', + ]; + } + + $format = $replacements[$code] ?? '?'; + + if ($format === '!') { + throw new InvalidFormatException("Format $code not supported for creation."); + } + + return $format; + }, $format); + + return static::rawCreateFromFormat($format, $time, $tz); + } + + /** + * Create a Carbon instance from a specific format and a string in a given language. + * + * @param string $format Datetime format + * @param string $locale + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function createFromLocaleFormat($format, $locale, $time, $tz = null) + { + $format = preg_replace_callback( + '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', + static function (array $match) use ($locale): string { + $word = str_replace('\\', '', $match[0]); + $translatedWord = static::translateTimeString($word, $locale, 'en'); + + return $word === $translatedWord + ? $match[0] + : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); + }, + $format + ); + + return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, 'en'), $tz); + } + + /** + * Create a Carbon instance from a specific ISO format and a string in a given language. + * + * @param string $format Datetime ISO format + * @param string $locale + * @param string $time + * @param DateTimeZone|string|false|null $tz + * + * @throws InvalidFormatException + * + * @return static|false + */ + public static function createFromLocaleIsoFormat($format, $locale, $time, $tz = null) + { + $time = static::translateTimeString($time, $locale, 'en', CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); + + return static::createFromIsoFormat($format, $time, $tz, $locale); + } + + /** + * Make a Carbon instance from given variable if possible. + * + * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals + * and recurrences). Throw an exception for invalid format, but otherwise return null. + * + * @param mixed $var + * + * @throws InvalidFormatException + * + * @return static|null + */ + public static function make($var) + { + if ($var instanceof DateTimeInterface) { + return static::instance($var); + } + + $date = null; + + if (\is_string($var)) { + $var = trim($var); + + if (!preg_match('/^P[\dT]/', $var) && + !preg_match('/^R\d/', $var) && + preg_match('/[a-z\d]/i', $var) + ) { + $date = static::parse($var); + } + } + + return $date; + } + + /** + * Set last errors. + * + * @param array|bool $lastErrors + * + * @return void + */ + private static function setLastErrors($lastErrors) + { + if (\is_array($lastErrors) || $lastErrors === false) { + static::$lastErrors = \is_array($lastErrors) ? $lastErrors : [ + 'warning_count' => 0, + 'warnings' => [], + 'error_count' => 0, + 'errors' => [], + ]; + } + } + + /** + * {@inheritdoc} + * + * @return array + */ + #[ReturnTypeWillChange] + public static function getLastErrors() + { + return static::$lastErrors; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Date.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Date.php new file mode 100644 index 0000000..8ae5c17 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Date.php @@ -0,0 +1,2747 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use BadMethodCallException; +use Carbon\Carbon; +use Carbon\CarbonInterface; +use Carbon\CarbonPeriod; +use Carbon\CarbonTimeZone; +use Carbon\Exceptions\BadComparisonUnitException; +use Carbon\Exceptions\ImmutableException; +use Carbon\Exceptions\InvalidTimeZoneException; +use Carbon\Exceptions\InvalidTypeException; +use Carbon\Exceptions\UnknownGetterException; +use Carbon\Exceptions\UnknownMethodException; +use Carbon\Exceptions\UnknownSetterException; +use Carbon\Exceptions\UnknownUnitException; +use Closure; +use DateInterval; +use DatePeriod; +use DateTime; +use DateTimeImmutable; +use DateTimeInterface; +use DateTimeZone; +use InvalidArgumentException; +use ReflectionException; +use ReturnTypeWillChange; +use Throwable; + +/** + * A simple API extension for DateTime. + * + * @mixin DeprecatedProperties + * + * <autodoc generated by `composer phpdoc`> + * + * @property int $year + * @property int $yearIso + * @property int $month + * @property int $day + * @property int $hour + * @property int $minute + * @property int $second + * @property int $micro + * @property int $microsecond + * @property int|float|string $timestamp seconds since the Unix Epoch + * @property string $englishDayOfWeek the day of week in English + * @property string $shortEnglishDayOfWeek the abbreviated day of week in English + * @property string $englishMonth the month in English + * @property string $shortEnglishMonth the abbreviated month in English + * @property int $milliseconds + * @property int $millisecond + * @property int $milli + * @property int $week 1 through 53 + * @property int $isoWeek 1 through 53 + * @property int $weekYear year according to week format + * @property int $isoWeekYear year according to ISO week format + * @property int $dayOfYear 1 through 366 + * @property int $age does a diffInYears() with default parameters + * @property int $offset the timezone offset in seconds from UTC + * @property int $offsetMinutes the timezone offset in minutes from UTC + * @property int $offsetHours the timezone offset in hours from UTC + * @property CarbonTimeZone $timezone the current timezone + * @property CarbonTimeZone $tz alias of $timezone + * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) + * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) + * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday + * @property-read int $daysInMonth number of days in the given month + * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read int $noZeroHour current hour from 1 to 24 + * @property-read int $weeksInYear 51 through 53 + * @property-read int $isoWeeksInYear 51 through 53 + * @property-read int $weekOfMonth 1 through 5 + * @property-read int $weekNumberInMonth 1 through 5 + * @property-read int $firstWeekDay 0 through 6 + * @property-read int $lastWeekDay 0 through 6 + * @property-read int $daysInYear 365 or 366 + * @property-read int $quarter the quarter of this instance, 1 - 4 + * @property-read int $decade the decade of this instance + * @property-read int $century the century of this instance + * @property-read int $millennium the millennium of this instance + * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise + * @property-read bool $local checks if the timezone is local, true if local, false otherwise + * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise + * @property-read string $timezoneName the current timezone name + * @property-read string $tzName alias of $timezoneName + * @property-read string $locale locale of the current instance + * + * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + * @method bool isLocal() Check if the current instance has non-UTC timezone. + * @method bool isValid() Check if the current instance is a valid date. + * @method bool isDST() Check if the current instance is in a daylight saving time. + * @method bool isSunday() Checks if the instance day is sunday. + * @method bool isMonday() Checks if the instance day is monday. + * @method bool isTuesday() Checks if the instance day is tuesday. + * @method bool isWednesday() Checks if the instance day is wednesday. + * @method bool isThursday() Checks if the instance day is thursday. + * @method bool isFriday() Checks if the instance day is friday. + * @method bool isSaturday() Checks if the instance day is saturday. + * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. + * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. + * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. + * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. + * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. + * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. + * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. + * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. + * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. + * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. + * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. + * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. + * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. + * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. + * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. + * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. + * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. + * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. + * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. + * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. + * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. + * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. + * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. + * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. + * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. + * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. + * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. + * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. + * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. + * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. + * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. + * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. + * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. + * @method CarbonInterface years(int $value) Set current instance year to the given value. + * @method CarbonInterface year(int $value) Set current instance year to the given value. + * @method CarbonInterface setYears(int $value) Set current instance year to the given value. + * @method CarbonInterface setYear(int $value) Set current instance year to the given value. + * @method CarbonInterface months(int $value) Set current instance month to the given value. + * @method CarbonInterface month(int $value) Set current instance month to the given value. + * @method CarbonInterface setMonths(int $value) Set current instance month to the given value. + * @method CarbonInterface setMonth(int $value) Set current instance month to the given value. + * @method CarbonInterface days(int $value) Set current instance day to the given value. + * @method CarbonInterface day(int $value) Set current instance day to the given value. + * @method CarbonInterface setDays(int $value) Set current instance day to the given value. + * @method CarbonInterface setDay(int $value) Set current instance day to the given value. + * @method CarbonInterface hours(int $value) Set current instance hour to the given value. + * @method CarbonInterface hour(int $value) Set current instance hour to the given value. + * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. + * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. + * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. + * @method CarbonInterface minute(int $value) Set current instance minute to the given value. + * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. + * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. + * @method CarbonInterface seconds(int $value) Set current instance second to the given value. + * @method CarbonInterface second(int $value) Set current instance second to the given value. + * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. + * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. + * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface setMicrosecond(int $value) Set current instance microsecond to the given value. + * @method CarbonInterface addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addYear() Add one year to the instance (using date interval). + * @method CarbonInterface subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subYear() Sub one year to the instance (using date interval). + * @method CarbonInterface addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMonth() Add one month to the instance (using date interval). + * @method CarbonInterface subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). + * @method CarbonInterface addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addDay() Add one day to the instance (using date interval). + * @method CarbonInterface subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subDay() Sub one day to the instance (using date interval). + * @method CarbonInterface addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addHour() Add one hour to the instance (using date interval). + * @method CarbonInterface subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). + * @method CarbonInterface addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). + * @method CarbonInterface subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). + * @method CarbonInterface addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addSecond() Add one second to the instance (using date interval). + * @method CarbonInterface subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). + * @method CarbonInterface addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). + * @method CarbonInterface subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). + * @method CarbonInterface addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). + * @method CarbonInterface subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). + * @method CarbonInterface addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). + * @method CarbonInterface subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). + * @method CarbonInterface addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). + * @method CarbonInterface subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). + * @method CarbonInterface addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). + * @method CarbonInterface subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). + * @method CarbonInterface addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addCentury() Add one century to the instance (using date interval). + * @method CarbonInterface subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). + * @method CarbonInterface addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). + * @method CarbonInterface subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). + * @method CarbonInterface addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). + * @method CarbonInterface subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). + * @method CarbonInterface addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonInterface addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonInterface addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addWeek() Add one week to the instance (using date interval). + * @method CarbonInterface subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). + * @method CarbonInterface addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). + * @method CarbonInterface subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). + * @method CarbonInterface addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMicro() Add one microsecond to the instance (using timestamp). + * @method CarbonInterface subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMicro() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonInterface addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMicrosecond() Add one microsecond to the instance (using timestamp). + * @method CarbonInterface subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMicrosecond() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonInterface addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMilli() Add one millisecond to the instance (using timestamp). + * @method CarbonInterface subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMilli() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonInterface addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMillisecond() Add one millisecond to the instance (using timestamp). + * @method CarbonInterface subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMillisecond() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonInterface addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealSecond() Add one second to the instance (using timestamp). + * @method CarbonInterface subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealSecond() Sub one second to the instance (using timestamp). + * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. + * @method CarbonInterface addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMinute() Add one minute to the instance (using timestamp). + * @method CarbonInterface subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMinute() Sub one minute to the instance (using timestamp). + * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. + * @method CarbonInterface addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealHour() Add one hour to the instance (using timestamp). + * @method CarbonInterface subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealHour() Sub one hour to the instance (using timestamp). + * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. + * @method CarbonInterface addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealDay() Add one day to the instance (using timestamp). + * @method CarbonInterface subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealDay() Sub one day to the instance (using timestamp). + * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. + * @method CarbonInterface addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealWeek() Add one week to the instance (using timestamp). + * @method CarbonInterface subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealWeek() Sub one week to the instance (using timestamp). + * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. + * @method CarbonInterface addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMonth() Add one month to the instance (using timestamp). + * @method CarbonInterface subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMonth() Sub one month to the instance (using timestamp). + * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. + * @method CarbonInterface addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealQuarter() Add one quarter to the instance (using timestamp). + * @method CarbonInterface subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealQuarter() Sub one quarter to the instance (using timestamp). + * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. + * @method CarbonInterface addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealYear() Add one year to the instance (using timestamp). + * @method CarbonInterface subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealYear() Sub one year to the instance (using timestamp). + * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. + * @method CarbonInterface addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealDecade() Add one decade to the instance (using timestamp). + * @method CarbonInterface subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealDecade() Sub one decade to the instance (using timestamp). + * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. + * @method CarbonInterface addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealCentury() Add one century to the instance (using timestamp). + * @method CarbonInterface subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealCentury() Sub one century to the instance (using timestamp). + * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. + * @method CarbonInterface addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface addRealMillennium() Add one millennium to the instance (using timestamp). + * @method CarbonInterface subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonInterface subRealMillennium() Sub one millennium to the instance (using timestamp). + * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. + * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * + * </autodoc> + */ +trait Date +{ + use Boundaries; + use Comparison; + use Converter; + use Creator; + use Difference; + use Macro; + use MagicParameter; + use Modifiers; + use Mutability; + use ObjectInitialisation; + use Options; + use Rounding; + use Serialization; + use Test; + use Timestamp; + use Units; + use Week; + + /** + * Names of days of the week. + * + * @var array + */ + protected static $days = [ + // @call isDayOfWeek + CarbonInterface::SUNDAY => 'Sunday', + // @call isDayOfWeek + CarbonInterface::MONDAY => 'Monday', + // @call isDayOfWeek + CarbonInterface::TUESDAY => 'Tuesday', + // @call isDayOfWeek + CarbonInterface::WEDNESDAY => 'Wednesday', + // @call isDayOfWeek + CarbonInterface::THURSDAY => 'Thursday', + // @call isDayOfWeek + CarbonInterface::FRIDAY => 'Friday', + // @call isDayOfWeek + CarbonInterface::SATURDAY => 'Saturday', + ]; + + /** + * Will UTF8 encoding be used to print localized date/time ? + * + * @var bool + */ + protected static $utf8 = false; + + /** + * List of unit and magic methods associated as doc-comments. + * + * @var array + */ + protected static $units = [ + // @call setUnit + // @call addUnit + 'year', + // @call setUnit + // @call addUnit + 'month', + // @call setUnit + // @call addUnit + 'day', + // @call setUnit + // @call addUnit + 'hour', + // @call setUnit + // @call addUnit + 'minute', + // @call setUnit + // @call addUnit + 'second', + // @call setUnit + // @call addUnit + 'milli', + // @call setUnit + // @call addUnit + 'millisecond', + // @call setUnit + // @call addUnit + 'micro', + // @call setUnit + // @call addUnit + 'microsecond', + ]; + + /** + * Creates a DateTimeZone from a string, DateTimeZone or integer offset. + * + * @param DateTimeZone|string|int|null $object original value to get CarbonTimeZone from it. + * @param DateTimeZone|string|int|null $objectDump dump of the object for error messages. + * + * @throws InvalidTimeZoneException + * + * @return CarbonTimeZone|false + */ + protected static function safeCreateDateTimeZone($object, $objectDump = null) + { + return CarbonTimeZone::instance($object, $objectDump); + } + + /** + * Get the TimeZone associated with the Carbon instance (as CarbonTimeZone). + * + * @return CarbonTimeZone + * + * @link https://php.net/manual/en/datetime.gettimezone.php + */ + #[ReturnTypeWillChange] + public function getTimezone() + { + return CarbonTimeZone::instance(parent::getTimezone()); + } + + /** + * List of minimum and maximums for each unit. + * + * @param int $daysInMonth + * + * @return array + */ + protected static function getRangesByUnit(int $daysInMonth = 31): array + { + return [ + // @call roundUnit + 'year' => [1, 9999], + // @call roundUnit + 'month' => [1, static::MONTHS_PER_YEAR], + // @call roundUnit + 'day' => [1, $daysInMonth], + // @call roundUnit + 'hour' => [0, static::HOURS_PER_DAY - 1], + // @call roundUnit + 'minute' => [0, static::MINUTES_PER_HOUR - 1], + // @call roundUnit + 'second' => [0, static::SECONDS_PER_MINUTE - 1], + ]; + } + + /** + * Get a copy of the instance. + * + * @return static + */ + public function copy() + { + return clone $this; + } + + /** + * @alias copy + * + * Get a copy of the instance. + * + * @return static + */ + public function clone() + { + return clone $this; + } + + /** + * Clone the current instance if it's mutable. + * + * This method is convenient to ensure you don't mutate the initial object + * but avoid to make a useless copy of it if it's already immutable. + * + * @return static + */ + public function avoidMutation(): self + { + if ($this instanceof DateTimeImmutable) { + return $this; + } + + return clone $this; + } + + /** + * Returns a present instance in the same timezone. + * + * @return static + */ + public function nowWithSameTz() + { + return static::now($this->getTimezone()); + } + + /** + * Throws an exception if the given object is not a DateTime and does not implement DateTimeInterface. + * + * @param mixed $date + * @param string|array $other + * + * @throws InvalidTypeException + */ + protected static function expectDateTime($date, $other = []) + { + $message = 'Expected '; + foreach ((array) $other as $expect) { + $message .= "$expect, "; + } + + if (!$date instanceof DateTime && !$date instanceof DateTimeInterface) { + throw new InvalidTypeException( + $message.'DateTime or DateTimeInterface, '. + (\is_object($date) ? \get_class($date) : \gettype($date)).' given' + ); + } + } + + /** + * Return the Carbon instance passed through, a now instance in the same timezone + * if null given or parse the input if string given. + * + * @param Carbon|DateTimeInterface|string|null $date + * + * @return static + */ + protected function resolveCarbon($date = null) + { + if (!$date) { + return $this->nowWithSameTz(); + } + + if (\is_string($date)) { + return static::parse($date, $this->getTimezone()); + } + + static::expectDateTime($date, ['null', 'string']); + + return $date instanceof self ? $date : static::instance($date); + } + + /** + * Return the Carbon instance passed through, a now instance in UTC + * if null given or parse the input if string given (using current timezone + * then switching to UTC). + * + * @param Carbon|DateTimeInterface|string|null $date + * + * @return static + */ + protected function resolveUTC($date = null): self + { + if (!$date) { + return static::now('UTC'); + } + + if (\is_string($date)) { + return static::parse($date, $this->getTimezone())->utc(); + } + + static::expectDateTime($date, ['null', 'string']); + + return $date instanceof self ? $date : static::instance($date)->utc(); + } + + /** + * Return the Carbon instance passed through, a now instance in the same timezone + * if null given or parse the input if string given. + * + * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date + * + * @return static + */ + public function carbonize($date = null) + { + if ($date instanceof DateInterval) { + return $this->avoidMutation()->add($date); + } + + if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { + $date = $date->getStartDate(); + } + + return $this->resolveCarbon($date); + } + + /////////////////////////////////////////////////////////////////// + ///////////////////////// GETTERS AND SETTERS ///////////////////// + /////////////////////////////////////////////////////////////////// + + /** + * Get a part of the Carbon object + * + * @param string $name + * + * @throws UnknownGetterException + * + * @return string|int|bool|DateTimeZone|null + */ + public function __get($name) + { + return $this->get($name); + } + + /** + * Get a part of the Carbon object + * + * @param string $name + * + * @throws UnknownGetterException + * + * @return string|int|bool|DateTimeZone|null + */ + public function get($name) + { + static $formats = [ + // @property int + 'year' => 'Y', + // @property int + 'yearIso' => 'o', + // @property int + // @call isSameUnit + 'month' => 'n', + // @property int + 'day' => 'j', + // @property int + 'hour' => 'G', + // @property int + 'minute' => 'i', + // @property int + 'second' => 's', + // @property int + 'micro' => 'u', + // @property int + 'microsecond' => 'u', + // @property-read int 0 (for Sunday) through 6 (for Saturday) + 'dayOfWeek' => 'w', + // @property-read int 1 (for Monday) through 7 (for Sunday) + 'dayOfWeekIso' => 'N', + // @property-read int ISO-8601 week number of year, weeks starting on Monday + 'weekOfYear' => 'W', + // @property-read int number of days in the given month + 'daysInMonth' => 't', + // @property int|float|string seconds since the Unix Epoch + 'timestamp' => 'U', + // @property-read string "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + 'latinMeridiem' => 'a', + // @property-read string "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + 'latinUpperMeridiem' => 'A', + // @property string the day of week in English + 'englishDayOfWeek' => 'l', + // @property string the abbreviated day of week in English + 'shortEnglishDayOfWeek' => 'D', + // @property string the month in English + 'englishMonth' => 'F', + // @property string the abbreviated month in English + 'shortEnglishMonth' => 'M', + // @property string the day of week in current locale LC_TIME + // @deprecated + // reason: It uses OS language package and strftime() which is deprecated since PHP 8.1. + // replacement: Use ->isoFormat('MMM') instead. + // since: 2.55.0 + 'localeDayOfWeek' => '%A', + // @property string the abbreviated day of week in current locale LC_TIME + // @deprecated + // reason: It uses OS language package and strftime() which is deprecated since PHP 8.1. + // replacement: Use ->isoFormat('dddd') instead. + // since: 2.55.0 + 'shortLocaleDayOfWeek' => '%a', + // @property string the month in current locale LC_TIME + // @deprecated + // reason: It uses OS language package and strftime() which is deprecated since PHP 8.1. + // replacement: Use ->isoFormat('ddd') instead. + // since: 2.55.0 + 'localeMonth' => '%B', + // @property string the abbreviated month in current locale LC_TIME + // @deprecated + // reason: It uses OS language package and strftime() which is deprecated since PHP 8.1. + // replacement: Use ->isoFormat('MMMM') instead. + // since: 2.55.0 + 'shortLocaleMonth' => '%b', + // @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + 'timezoneAbbreviatedName' => 'T', + // @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + 'tzAbbrName' => 'T', + ]; + + switch (true) { + case isset($formats[$name]): + $format = $formats[$name]; + $method = str_starts_with($format, '%') ? 'formatLocalized' : 'rawFormat'; + $value = $this->$method($format); + + return is_numeric($value) ? (int) $value : $value; + + // @property-read string long name of weekday translated according to Carbon locale, in english if no translation available for current language + case $name === 'dayName': + return $this->getTranslatedDayName(); + // @property-read string short name of weekday translated according to Carbon locale, in english if no translation available for current language + case $name === 'shortDayName': + return $this->getTranslatedShortDayName(); + // @property-read string very short name of weekday translated according to Carbon locale, in english if no translation available for current language + case $name === 'minDayName': + return $this->getTranslatedMinDayName(); + // @property-read string long name of month translated according to Carbon locale, in english if no translation available for current language + case $name === 'monthName': + return $this->getTranslatedMonthName(); + // @property-read string short name of month translated according to Carbon locale, in english if no translation available for current language + case $name === 'shortMonthName': + return $this->getTranslatedShortMonthName(); + // @property-read string lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + case $name === 'meridiem': + return $this->meridiem(true); + // @property-read string uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + case $name === 'upperMeridiem': + return $this->meridiem(); + // @property-read int current hour from 1 to 24 + case $name === 'noZeroHour': + return $this->hour ?: 24; + // @property int + case $name === 'milliseconds': + // @property int + case $name === 'millisecond': + // @property int + case $name === 'milli': + return (int) floor(((int) $this->rawFormat('u')) / 1000); + + // @property int 1 through 53 + case $name === 'week': + return (int) $this->week(); + + // @property int 1 through 53 + case $name === 'isoWeek': + return (int) $this->isoWeek(); + + // @property int year according to week format + case $name === 'weekYear': + return (int) $this->weekYear(); + + // @property int year according to ISO week format + case $name === 'isoWeekYear': + return (int) $this->isoWeekYear(); + + // @property-read int 51 through 53 + case $name === 'weeksInYear': + return $this->weeksInYear(); + + // @property-read int 51 through 53 + case $name === 'isoWeeksInYear': + return $this->isoWeeksInYear(); + + // @property-read int 1 through 5 + case $name === 'weekOfMonth': + return (int) ceil($this->day / static::DAYS_PER_WEEK); + + // @property-read int 1 through 5 + case $name === 'weekNumberInMonth': + return (int) ceil(($this->day + $this->avoidMutation()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK); + + // @property-read int 0 through 6 + case $name === 'firstWeekDay': + return $this->localTranslator ? ($this->getTranslationMessage('first_day_of_week') ?? 0) : static::getWeekStartsAt(); + + // @property-read int 0 through 6 + case $name === 'lastWeekDay': + return $this->localTranslator ? (($this->getTranslationMessage('first_day_of_week') ?? 0) + static::DAYS_PER_WEEK - 1) % static::DAYS_PER_WEEK : static::getWeekEndsAt(); + + // @property int 1 through 366 + case $name === 'dayOfYear': + return 1 + (int) ($this->rawFormat('z')); + + // @property-read int 365 or 366 + case $name === 'daysInYear': + return $this->isLeapYear() ? 366 : 365; + + // @property int does a diffInYears() with default parameters + case $name === 'age': + return $this->diffInYears(); + + // @property-read int the quarter of this instance, 1 - 4 + // @call isSameUnit + case $name === 'quarter': + return (int) ceil($this->month / static::MONTHS_PER_QUARTER); + + // @property-read int the decade of this instance + // @call isSameUnit + case $name === 'decade': + return (int) ceil($this->year / static::YEARS_PER_DECADE); + + // @property-read int the century of this instance + // @call isSameUnit + case $name === 'century': + $factor = 1; + $year = $this->year; + if ($year < 0) { + $year = -$year; + $factor = -1; + } + + return (int) ($factor * ceil($year / static::YEARS_PER_CENTURY)); + + // @property-read int the millennium of this instance + // @call isSameUnit + case $name === 'millennium': + $factor = 1; + $year = $this->year; + if ($year < 0) { + $year = -$year; + $factor = -1; + } + + return (int) ($factor * ceil($year / static::YEARS_PER_MILLENNIUM)); + + // @property int the timezone offset in seconds from UTC + case $name === 'offset': + return $this->getOffset(); + + // @property int the timezone offset in minutes from UTC + case $name === 'offsetMinutes': + return $this->getOffset() / static::SECONDS_PER_MINUTE; + + // @property int the timezone offset in hours from UTC + case $name === 'offsetHours': + return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR; + + // @property-read bool daylight savings time indicator, true if DST, false otherwise + case $name === 'dst': + return $this->rawFormat('I') === '1'; + + // @property-read bool checks if the timezone is local, true if local, false otherwise + case $name === 'local': + return $this->getOffset() === $this->avoidMutation()->setTimezone(date_default_timezone_get())->getOffset(); + + // @property-read bool checks if the timezone is UTC, true if UTC, false otherwise + case $name === 'utc': + return $this->getOffset() === 0; + + // @property CarbonTimeZone $timezone the current timezone + // @property CarbonTimeZone $tz alias of $timezone + case $name === 'timezone' || $name === 'tz': + return CarbonTimeZone::instance($this->getTimezone()); + + // @property-read string $timezoneName the current timezone name + // @property-read string $tzName alias of $timezoneName + case $name === 'timezoneName' || $name === 'tzName': + return $this->getTimezone()->getName(); + + // @property-read string locale of the current instance + case $name === 'locale': + return $this->getTranslatorLocale(); + + default: + $macro = $this->getLocalMacro('get'.ucfirst($name)); + + if ($macro) { + return $this->executeCallableWithContext($macro); + } + + throw new UnknownGetterException($name); + } + } + + /** + * Check if an attribute exists on the object + * + * @param string $name + * + * @return bool + */ + public function __isset($name) + { + try { + $this->__get($name); + } catch (UnknownGetterException | ReflectionException $e) { + return false; + } + + return true; + } + + /** + * Set a part of the Carbon object + * + * @param string $name + * @param string|int|DateTimeZone $value + * + * @throws UnknownSetterException|ReflectionException + * + * @return void + */ + public function __set($name, $value) + { + if ($this->constructedObjectId === spl_object_hash($this)) { + $this->set($name, $value); + + return; + } + + $this->$name = $value; + } + + /** + * Set a part of the Carbon object + * + * @param string|array $name + * @param string|int|DateTimeZone $value + * + * @throws ImmutableException|UnknownSetterException + * + * @return $this + */ + public function set($name, $value = null) + { + if ($this->isImmutable()) { + throw new ImmutableException(sprintf('%s class', static::class)); + } + + if (\is_array($name)) { + foreach ($name as $key => $value) { + $this->set($key, $value); + } + + return $this; + } + + switch ($name) { + case 'milliseconds': + case 'millisecond': + case 'milli': + case 'microseconds': + case 'microsecond': + case 'micro': + if (str_starts_with($name, 'milli')) { + $value *= 1000; + } + + while ($value < 0) { + $this->subSecond(); + $value += static::MICROSECONDS_PER_SECOND; + } + + while ($value >= static::MICROSECONDS_PER_SECOND) { + $this->addSecond(); + $value -= static::MICROSECONDS_PER_SECOND; + } + + $this->modify($this->rawFormat('H:i:s.').str_pad((string) round($value), 6, '0', STR_PAD_LEFT)); + + break; + + case 'year': + case 'month': + case 'day': + case 'hour': + case 'minute': + case 'second': + [$year, $month, $day, $hour, $minute, $second] = array_map('intval', explode('-', $this->rawFormat('Y-n-j-G-i-s'))); + $$name = $value; + $this->setDateTime($year, $month, $day, $hour, $minute, $second); + + break; + + case 'week': + $this->week($value); + + break; + + case 'isoWeek': + $this->isoWeek($value); + + break; + + case 'weekYear': + $this->weekYear($value); + + break; + + case 'isoWeekYear': + $this->isoWeekYear($value); + + break; + + case 'dayOfYear': + $this->addDays($value - $this->dayOfYear); + + break; + + case 'timestamp': + $this->setTimestamp($value); + + break; + + case 'offset': + $this->setTimezone(static::safeCreateDateTimeZone($value / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR)); + + break; + + case 'offsetMinutes': + $this->setTimezone(static::safeCreateDateTimeZone($value / static::MINUTES_PER_HOUR)); + + break; + + case 'offsetHours': + $this->setTimezone(static::safeCreateDateTimeZone($value)); + + break; + + case 'timezone': + case 'tz': + $this->setTimezone($value); + + break; + + default: + $macro = $this->getLocalMacro('set'.ucfirst($name)); + + if ($macro) { + $this->executeCallableWithContext($macro, $value); + + break; + } + + if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) { + throw new UnknownSetterException($name); + } + + $this->$name = $value; + } + + return $this; + } + + protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) + { + $key = $baseKey.$keySuffix; + $standaloneKey = "{$key}_standalone"; + $baseTranslation = $this->getTranslationMessage($key); + + if ($baseTranslation instanceof Closure) { + return $baseTranslation($this, $context, $subKey) ?: $defaultValue; + } + + if ( + $this->getTranslationMessage("$standaloneKey.$subKey") && + (!$context || (($regExp = $this->getTranslationMessage("{$baseKey}_regexp")) && !preg_match($regExp, $context))) + ) { + $key = $standaloneKey; + } + + return $this->getTranslationMessage("$key.$subKey", null, $defaultValue); + } + + /** + * Get the translation of the current week day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * @param string $keySuffix "", "_short" or "_min" + * @param string|null $defaultValue default value if translation missing + * + * @return string + */ + public function getTranslatedDayName($context = null, $keySuffix = '', $defaultValue = null) + { + return $this->getTranslatedFormByRegExp('weekdays', $keySuffix, $context, $this->dayOfWeek, $defaultValue ?: $this->englishDayOfWeek); + } + + /** + * Get the translation of the current short week day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * + * @return string + */ + public function getTranslatedShortDayName($context = null) + { + return $this->getTranslatedDayName($context, '_short', $this->shortEnglishDayOfWeek); + } + + /** + * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * + * @return string + */ + public function getTranslatedMinDayName($context = null) + { + return $this->getTranslatedDayName($context, '_min', $this->shortEnglishDayOfWeek); + } + + /** + * Get the translation of the current month day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * @param string $keySuffix "" or "_short" + * @param string|null $defaultValue default value if translation missing + * + * @return string + */ + public function getTranslatedMonthName($context = null, $keySuffix = '', $defaultValue = null) + { + return $this->getTranslatedFormByRegExp('months', $keySuffix, $context, $this->month - 1, $defaultValue ?: $this->englishMonth); + } + + /** + * Get the translation of the current short month day name (with context for languages with multiple forms). + * + * @param string|null $context whole format string + * + * @return string + */ + public function getTranslatedShortMonthName($context = null) + { + return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth); + } + + /** + * Get/set the day of year. + * + * @param int|null $value new value for day of year if using as setter. + * + * @return static|int + */ + public function dayOfYear($value = null) + { + $dayOfYear = $this->dayOfYear; + + return $value === null ? $dayOfYear : $this->addDays($value - $dayOfYear); + } + + /** + * Get/set the weekday from 0 (Sunday) to 6 (Saturday). + * + * @param int|null $value new value for weekday if using as setter. + * + * @return static|int + */ + public function weekday($value = null) + { + if ($value === null) { + return $this->dayOfWeek; + } + + $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); + $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; + + return $this->addDays((($value + 7 - $firstDay) % 7) - $dayOfWeek); + } + + /** + * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). + * + * @param int|null $value new value for weekday if using as setter. + * + * @return static|int + */ + public function isoWeekday($value = null) + { + $dayOfWeekIso = $this->dayOfWeekIso; + + return $value === null ? $dayOfWeekIso : $this->addDays($value - $dayOfWeekIso); + } + + /** + * Return the number of days since the start of the week (using the current locale or the first parameter + * if explicitly given). + * + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return int + */ + public function getDaysFromStartOfWeek(int $weekStartsAt = null): int + { + $firstDay = (int) ($weekStartsAt ?? $this->getTranslationMessage('first_day_of_week') ?? 0); + + return ($this->dayOfWeek + 7 - $firstDay) % 7; + } + + /** + * Set the day (keeping the current time) to the start of the week + the number of days passed as the first + * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. + * + * @param int $numberOfDays number of days to add after the start of the current week + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return static + */ + public function setDaysFromStartOfWeek(int $numberOfDays, int $weekStartsAt = null) + { + return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek($weekStartsAt)); + } + + /** + * Set any unit to a new value without overflowing current other unit given. + * + * @param string $valueUnit unit name to modify + * @param int $value new value for the input unit + * @param string $overflowUnit unit name to not overflow + * + * @return static + */ + public function setUnitNoOverflow($valueUnit, $value, $overflowUnit) + { + try { + $original = $this->avoidMutation(); + /** @var static $date */ + $date = $this->$valueUnit($value); + $end = $original->avoidMutation()->endOf($overflowUnit); + $start = $original->avoidMutation()->startOf($overflowUnit); + if ($date < $start) { + $date = $date->setDateTimeFrom($start); + } elseif ($date > $end) { + $date = $date->setDateTimeFrom($end); + } + + return $date; + } catch (BadMethodCallException | ReflectionException $exception) { + throw new UnknownUnitException($valueUnit, 0, $exception); + } + } + + /** + * Add any unit to a new value without overflowing current other unit given. + * + * @param string $valueUnit unit name to modify + * @param int $value amount to add to the input unit + * @param string $overflowUnit unit name to not overflow + * + * @return static + */ + public function addUnitNoOverflow($valueUnit, $value, $overflowUnit) + { + return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit); + } + + /** + * Subtract any unit to a new value without overflowing current other unit given. + * + * @param string $valueUnit unit name to modify + * @param int $value amount to subtract to the input unit + * @param string $overflowUnit unit name to not overflow + * + * @return static + */ + public function subUnitNoOverflow($valueUnit, $value, $overflowUnit) + { + return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit); + } + + /** + * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. + * + * @param int|null $minuteOffset + * + * @return int|static + */ + public function utcOffset(int $minuteOffset = null) + { + if (\func_num_args() < 1) { + return $this->offsetMinutes; + } + + return $this->setTimezone(CarbonTimeZone::createFromMinuteOffset($minuteOffset)); + } + + /** + * Set the date with gregorian year, month and day numbers. + * + * @see https://php.net/manual/en/datetime.setdate.php + * + * @param int $year + * @param int $month + * @param int $day + * + * @return static + */ + #[ReturnTypeWillChange] + public function setDate($year, $month, $day) + { + return parent::setDate((int) $year, (int) $month, (int) $day); + } + + /** + * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. + * + * @see https://php.net/manual/en/datetime.setisodate.php + * + * @param int $year + * @param int $week + * @param int $day + * + * @return static + */ + #[ReturnTypeWillChange] + public function setISODate($year, $week, $day = 1) + { + return parent::setISODate((int) $year, (int) $week, (int) $day); + } + + /** + * Set the date and time all together. + * + * @param int $year + * @param int $month + * @param int $day + * @param int $hour + * @param int $minute + * @param int $second + * @param int $microseconds + * + * @return static + */ + public function setDateTime($year, $month, $day, $hour, $minute, $second = 0, $microseconds = 0) + { + return $this->setDate($year, $month, $day)->setTime((int) $hour, (int) $minute, (int) $second, (int) $microseconds); + } + + /** + * Resets the current time of the DateTime object to a different time. + * + * @see https://php.net/manual/en/datetime.settime.php + * + * @param int $hour + * @param int $minute + * @param int $second + * @param int $microseconds + * + * @return static + */ + #[ReturnTypeWillChange] + public function setTime($hour, $minute, $second = 0, $microseconds = 0) + { + return parent::setTime((int) $hour, (int) $minute, (int) $second, (int) $microseconds); + } + + /** + * Set the instance's timestamp. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $unixTimestamp + * + * @return static + */ + #[ReturnTypeWillChange] + public function setTimestamp($unixTimestamp) + { + [$timestamp, $microseconds] = self::getIntegerAndDecimalParts($unixTimestamp); + + return parent::setTimestamp((int) $timestamp)->setMicroseconds((int) $microseconds); + } + + /** + * Set the time by time string. + * + * @param string $time + * + * @return static + */ + public function setTimeFromTimeString($time) + { + if (!str_contains($time, ':')) { + $time .= ':0'; + } + + return $this->modify($time); + } + + /** + * @alias setTimezone + * + * @param DateTimeZone|string $value + * + * @return static + */ + public function timezone($value) + { + return $this->setTimezone($value); + } + + /** + * Set the timezone or returns the timezone name if no arguments passed. + * + * @param DateTimeZone|string $value + * + * @return static|string + */ + public function tz($value = null) + { + if (\func_num_args() < 1) { + return $this->tzName; + } + + return $this->setTimezone($value); + } + + /** + * Set the instance's timezone from a string or object. + * + * @param DateTimeZone|string $value + * + * @return static + */ + #[ReturnTypeWillChange] + public function setTimezone($value) + { + $tz = static::safeCreateDateTimeZone($value); + + if ($tz === false && !self::isStrictModeEnabled()) { + $tz = new CarbonTimeZone(); + } + + return parent::setTimezone($tz); + } + + /** + * Set the instance's timezone from a string or object and add/subtract the offset difference. + * + * @param DateTimeZone|string $value + * + * @return static + */ + public function shiftTimezone($value) + { + $dateTimeString = $this->format('Y-m-d H:i:s.u'); + + return $this + ->setTimezone($value) + ->modify($dateTimeString); + } + + /** + * Set the instance's timezone to UTC. + * + * @return static + */ + public function utc() + { + return $this->setTimezone('UTC'); + } + + /** + * Set the year, month, and date for this instance to that of the passed instance. + * + * @param Carbon|DateTimeInterface $date now if null + * + * @return static + */ + public function setDateFrom($date = null) + { + $date = $this->resolveCarbon($date); + + return $this->setDate($date->year, $date->month, $date->day); + } + + /** + * Set the hour, minute, second and microseconds for this instance to that of the passed instance. + * + * @param Carbon|DateTimeInterface $date now if null + * + * @return static + */ + public function setTimeFrom($date = null) + { + $date = $this->resolveCarbon($date); + + return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond); + } + + /** + * Set the date and time for this instance to that of the passed instance. + * + * @param Carbon|DateTimeInterface $date + * + * @return static + */ + public function setDateTimeFrom($date = null) + { + $date = $this->resolveCarbon($date); + + return $this->modify($date->rawFormat('Y-m-d H:i:s.u')); + } + + /** + * Get the days of the week + * + * @return array + */ + public static function getDays() + { + return static::$days; + } + + /////////////////////////////////////////////////////////////////// + /////////////////////// WEEK SPECIAL DAYS ///////////////////////// + /////////////////////////////////////////////////////////////////// + + private static function getFirstDayOfWeek(): int + { + return (int) static::getTranslationMessageWith( + static::getTranslator(), + 'first_day_of_week' + ); + } + + /** + * Get the first day of week + * + * @return int + */ + public static function getWeekStartsAt() + { + if (static::$weekStartsAt === static::WEEK_DAY_AUTO) { + return self::getFirstDayOfWeek(); + } + + return static::$weekStartsAt; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the + * 'first_day_of_week' locale setting to change the start of week according to current locale + * selected and implicitly the end of week. + * + * Set the first day of week + * + * @param int|string $day week start day (or 'auto' to get the first day of week from Carbon::getLocale() culture). + * + * @return void + */ + public static function setWeekStartsAt($day) + { + static::$weekStartsAt = $day === static::WEEK_DAY_AUTO ? $day : max(0, (7 + $day) % 7); + } + + /** + * Get the last day of week + * + * @return int + */ + public static function getWeekEndsAt() + { + if (static::$weekStartsAt === static::WEEK_DAY_AUTO) { + return (int) (static::DAYS_PER_WEEK - 1 + self::getFirstDayOfWeek()) % static::DAYS_PER_WEEK; + } + + return static::$weekEndsAt; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek + * or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the + * start of week according to current locale selected and implicitly the end of week. + * + * Set the last day of week + * + * @param int|string $day week end day (or 'auto' to get the day before the first day of week + * from Carbon::getLocale() culture). + * + * @return void + */ + public static function setWeekEndsAt($day) + { + static::$weekEndsAt = $day === static::WEEK_DAY_AUTO ? $day : max(0, (7 + $day) % 7); + } + + /** + * Get weekend days + * + * @return array + */ + public static function getWeekendDays() + { + return static::$weekendDays; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider week-end is always saturday and sunday, and if you have some custom + * week-end days to handle, give to those days an other name and create a macro for them: + * + * ``` + * Carbon::macro('isDayOff', function ($date) { + * return $date->isSunday() || $date->isMonday(); + * }); + * Carbon::macro('isNotDayOff', function ($date) { + * return !$date->isDayOff(); + * }); + * if ($someDate->isDayOff()) ... + * if ($someDate->isNotDayOff()) ... + * // Add 5 not-off days + * $count = 5; + * while ($someDate->isDayOff() || ($count-- > 0)) { + * $someDate->addDay(); + * } + * ``` + * + * Set weekend days + * + * @param array $days + * + * @return void + */ + public static function setWeekendDays($days) + { + static::$weekendDays = $days; + } + + /** + * Determine if a time string will produce a relative date. + * + * @param string $time + * + * @return bool true if time match a relative date, false if absolute or invalid time string + */ + public static function hasRelativeKeywords($time) + { + if (!$time || strtotime($time) === false) { + return false; + } + + $date1 = new DateTime('2000-01-01T00:00:00Z'); + $date1->modify($time); + $date2 = new DateTime('2001-12-25T00:00:00Z'); + $date2->modify($time); + + return $date1 != $date2; + } + + /////////////////////////////////////////////////////////////////// + /////////////////////// STRING FORMATTING ///////////////////////// + /////////////////////////////////////////////////////////////////// + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use UTF-8 language packages on every machine. + * + * Set if UTF8 will be used for localized date/time. + * + * @param bool $utf8 + */ + public static function setUtf8($utf8) + { + static::$utf8 = $utf8; + } + + /** + * Format the instance with the current locale. You can set the current + * locale using setlocale() https://php.net/setlocale. + * + * @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1. + * Use ->isoFormat() instead. + * Deprecated since 2.55.0 + * + * @param string $format + * + * @return string + */ + public function formatLocalized($format) + { + // Check for Windows to find and replace the %e modifier correctly. + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format); // @codeCoverageIgnore + } + + $time = strtotime($this->toDateTimeString()); + $formatted = ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) + ? strftime($format, $time) + : @strftime($format, $time); + + return static::$utf8 + ? ( + \function_exists('mb_convert_encoding') + ? mb_convert_encoding($formatted, 'UTF-8', mb_list_encodings()) + : utf8_encode($formatted) + ) + : $formatted; + } + + /** + * Returns list of locale formats for ISO formatting. + * + * @param string|null $locale current locale used if null + * + * @return array + */ + public function getIsoFormats($locale = null) + { + return [ + 'LT' => $this->getTranslationMessage('formats.LT', $locale, 'h:mm A'), + 'LTS' => $this->getTranslationMessage('formats.LTS', $locale, 'h:mm:ss A'), + 'L' => $this->getTranslationMessage('formats.L', $locale, 'MM/DD/YYYY'), + 'LL' => $this->getTranslationMessage('formats.LL', $locale, 'MMMM D, YYYY'), + 'LLL' => $this->getTranslationMessage('formats.LLL', $locale, 'MMMM D, YYYY h:mm A'), + 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'), + 'l' => $this->getTranslationMessage('formats.l', $locale), + 'll' => $this->getTranslationMessage('formats.ll', $locale), + 'lll' => $this->getTranslationMessage('formats.lll', $locale), + 'llll' => $this->getTranslationMessage('formats.llll', $locale), + ]; + } + + /** + * Returns list of calendar formats for ISO formatting. + * + * @param string|null $locale current locale used if null + * + * @return array + */ + public function getCalendarFormats($locale = null) + { + return [ + 'sameDay' => $this->getTranslationMessage('calendar.sameDay', $locale, '[Today at] LT'), + 'nextDay' => $this->getTranslationMessage('calendar.nextDay', $locale, '[Tomorrow at] LT'), + 'nextWeek' => $this->getTranslationMessage('calendar.nextWeek', $locale, 'dddd [at] LT'), + 'lastDay' => $this->getTranslationMessage('calendar.lastDay', $locale, '[Yesterday at] LT'), + 'lastWeek' => $this->getTranslationMessage('calendar.lastWeek', $locale, '[Last] dddd [at] LT'), + 'sameElse' => $this->getTranslationMessage('calendar.sameElse', $locale, 'L'), + ]; + } + + /** + * Returns list of locale units for ISO formatting. + * + * @return array + */ + public static function getIsoUnits() + { + static $units = null; + + if ($units === null) { + $units = [ + 'OD' => ['getAltNumber', ['day']], + 'OM' => ['getAltNumber', ['month']], + 'OY' => ['getAltNumber', ['year']], + 'OH' => ['getAltNumber', ['hour']], + 'Oh' => ['getAltNumber', ['h']], + 'Om' => ['getAltNumber', ['minute']], + 'Os' => ['getAltNumber', ['second']], + 'D' => 'day', + 'DD' => ['rawFormat', ['d']], + 'Do' => ['ordinal', ['day', 'D']], + 'd' => 'dayOfWeek', + 'dd' => function (CarbonInterface $date, $originalFormat = null) { + return $date->getTranslatedMinDayName($originalFormat); + }, + 'ddd' => function (CarbonInterface $date, $originalFormat = null) { + return $date->getTranslatedShortDayName($originalFormat); + }, + 'dddd' => function (CarbonInterface $date, $originalFormat = null) { + return $date->getTranslatedDayName($originalFormat); + }, + 'DDD' => 'dayOfYear', + 'DDDD' => ['getPaddedUnit', ['dayOfYear', 3]], + 'DDDo' => ['ordinal', ['dayOfYear', 'DDD']], + 'e' => ['weekday', []], + 'E' => 'dayOfWeekIso', + 'H' => ['rawFormat', ['G']], + 'HH' => ['rawFormat', ['H']], + 'h' => ['rawFormat', ['g']], + 'hh' => ['rawFormat', ['h']], + 'k' => 'noZeroHour', + 'kk' => ['getPaddedUnit', ['noZeroHour']], + 'hmm' => ['rawFormat', ['gi']], + 'hmmss' => ['rawFormat', ['gis']], + 'Hmm' => ['rawFormat', ['Gi']], + 'Hmmss' => ['rawFormat', ['Gis']], + 'm' => 'minute', + 'mm' => ['rawFormat', ['i']], + 'a' => 'meridiem', + 'A' => 'upperMeridiem', + 's' => 'second', + 'ss' => ['getPaddedUnit', ['second']], + 'S' => function (CarbonInterface $date) { + return (string) floor($date->micro / 100000); + }, + 'SS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro / 10000), 2, '0', STR_PAD_LEFT); + }, + 'SSS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro / 1000), 3, '0', STR_PAD_LEFT); + }, + 'SSSS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro / 100), 4, '0', STR_PAD_LEFT); + }, + 'SSSSS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro / 10), 5, '0', STR_PAD_LEFT); + }, + 'SSSSSS' => ['getPaddedUnit', ['micro', 6]], + 'SSSSSSS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro * 10), 7, '0', STR_PAD_LEFT); + }, + 'SSSSSSSS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro * 100), 8, '0', STR_PAD_LEFT); + }, + 'SSSSSSSSS' => function (CarbonInterface $date) { + return str_pad((string) floor($date->micro * 1000), 9, '0', STR_PAD_LEFT); + }, + 'M' => 'month', + 'MM' => ['rawFormat', ['m']], + 'MMM' => function (CarbonInterface $date, $originalFormat = null) { + $month = $date->getTranslatedShortMonthName($originalFormat); + $suffix = $date->getTranslationMessage('mmm_suffix'); + if ($suffix && $month !== $date->monthName) { + $month .= $suffix; + } + + return $month; + }, + 'MMMM' => function (CarbonInterface $date, $originalFormat = null) { + return $date->getTranslatedMonthName($originalFormat); + }, + 'Mo' => ['ordinal', ['month', 'M']], + 'Q' => 'quarter', + 'Qo' => ['ordinal', ['quarter', 'M']], + 'G' => 'isoWeekYear', + 'GG' => ['getPaddedUnit', ['isoWeekYear']], + 'GGG' => ['getPaddedUnit', ['isoWeekYear', 3]], + 'GGGG' => ['getPaddedUnit', ['isoWeekYear', 4]], + 'GGGGG' => ['getPaddedUnit', ['isoWeekYear', 5]], + 'g' => 'weekYear', + 'gg' => ['getPaddedUnit', ['weekYear']], + 'ggg' => ['getPaddedUnit', ['weekYear', 3]], + 'gggg' => ['getPaddedUnit', ['weekYear', 4]], + 'ggggg' => ['getPaddedUnit', ['weekYear', 5]], + 'W' => 'isoWeek', + 'WW' => ['getPaddedUnit', ['isoWeek']], + 'Wo' => ['ordinal', ['isoWeek', 'W']], + 'w' => 'week', + 'ww' => ['getPaddedUnit', ['week']], + 'wo' => ['ordinal', ['week', 'w']], + 'x' => ['valueOf', []], + 'X' => 'timestamp', + 'Y' => 'year', + 'YY' => ['rawFormat', ['y']], + 'YYYY' => ['getPaddedUnit', ['year', 4]], + 'YYYYY' => ['getPaddedUnit', ['year', 5]], + 'YYYYYY' => function (CarbonInterface $date) { + return ($date->year < 0 ? '' : '+').$date->getPaddedUnit('year', 6); + }, + 'z' => ['rawFormat', ['T']], + 'zz' => 'tzName', + 'Z' => ['getOffsetString', []], + 'ZZ' => ['getOffsetString', ['']], + ]; + } + + return $units; + } + + /** + * Returns a unit of the instance padded with 0 by default or any other string if specified. + * + * @param string $unit Carbon unit name + * @param int $length Length of the output (2 by default) + * @param string $padString String to use for padding ("0" by default) + * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) + * + * @return string + */ + public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT) + { + return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType); + } + + /** + * Return a property with its ordinal. + * + * @param string $key + * @param string|null $period + * + * @return string + */ + public function ordinal(string $key, ?string $period = null): string + { + $number = $this->$key; + $result = $this->translate('ordinal', [ + ':number' => $number, + ':period' => (string) $period, + ]); + + return (string) ($result === 'ordinal' ? $number : $result); + } + + /** + * Return the meridiem of the current time in the current locale. + * + * @param bool $isLower if true, returns lowercase variant if available in the current locale. + * + * @return string + */ + public function meridiem(bool $isLower = false): string + { + $hour = $this->hour; + $index = $hour < 12 ? 0 : 1; + + if ($isLower) { + $key = 'meridiem.'.($index + 2); + $result = $this->translate($key); + + if ($result !== $key) { + return $result; + } + } + + $key = "meridiem.$index"; + $result = $this->translate($key); + if ($result === $key) { + $result = $this->translate('meridiem', [ + ':hour' => $this->hour, + ':minute' => $this->minute, + ':isLower' => $isLower, + ]); + + if ($result === 'meridiem') { + return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; + } + } elseif ($isLower) { + $result = mb_strtolower($result); + } + + return $result; + } + + /** + * Returns the alternative number for a given date property if available in the current locale. + * + * @param string $key date property + * + * @return string + */ + public function getAltNumber(string $key): string + { + return $this->translateNumber(\strlen($key) > 1 ? $this->$key : $this->rawFormat('h')); + } + + /** + * Format in the current language using ISO replacement patterns. + * + * @param string $format + * @param string|null $originalFormat provide context if a chunk has been passed alone + * + * @return string + */ + public function isoFormat(string $format, ?string $originalFormat = null): string + { + $result = ''; + $length = mb_strlen($format); + $originalFormat = $originalFormat ?: $format; + $inEscaped = false; + $formats = null; + $units = null; + + for ($i = 0; $i < $length; $i++) { + $char = mb_substr($format, $i, 1); + + if ($char === '\\') { + $result .= mb_substr($format, ++$i, 1); + + continue; + } + + if ($char === '[' && !$inEscaped) { + $inEscaped = true; + + continue; + } + + if ($char === ']' && $inEscaped) { + $inEscaped = false; + + continue; + } + + if ($inEscaped) { + $result .= $char; + + continue; + } + + $input = mb_substr($format, $i); + + if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { + if ($formats === null) { + $formats = $this->getIsoFormats(); + } + + $code = $match[0]; + $sequence = $formats[$code] ?? preg_replace_callback( + '/MMMM|MM|DD|dddd/', + function ($code) { + return mb_substr($code[0], 1); + }, + $formats[strtoupper($code)] ?? '' + ); + $rest = mb_substr($format, $i + mb_strlen($code)); + $format = mb_substr($format, 0, $i).$sequence.$rest; + $length = mb_strlen($format); + $input = $sequence.$rest; + } + + if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { + $code = $match[0]; + + if ($units === null) { + $units = static::getIsoUnits(); + } + + $sequence = $units[$code] ?? ''; + + if ($sequence instanceof Closure) { + $sequence = $sequence($this, $originalFormat); + } elseif (\is_array($sequence)) { + try { + $sequence = $this->{$sequence[0]}(...$sequence[1]); + } catch (ReflectionException | InvalidArgumentException | BadMethodCallException $e) { + $sequence = ''; + } + } elseif (\is_string($sequence)) { + $sequence = $this->$sequence ?? $code; + } + + $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); + $i += mb_strlen((string) $sequence) - 1; + $length = mb_strlen($format); + $char = $sequence; + } + + $result .= $char; + } + + return $result; + } + + /** + * List of replacements from date() format to isoFormat(). + * + * @return array + */ + public static function getFormatsToIsoReplacements() + { + static $replacements = null; + + if ($replacements === null) { + $replacements = [ + 'd' => true, + 'D' => 'ddd', + 'j' => true, + 'l' => 'dddd', + 'N' => true, + 'S' => function ($date) { + $day = $date->rawFormat('j'); + + return str_replace((string) $day, '', $date->isoFormat('Do')); + }, + 'w' => true, + 'z' => true, + 'W' => true, + 'F' => 'MMMM', + 'm' => true, + 'M' => 'MMM', + 'n' => true, + 't' => true, + 'L' => true, + 'o' => true, + 'Y' => true, + 'y' => true, + 'a' => 'a', + 'A' => 'A', + 'B' => true, + 'g' => true, + 'G' => true, + 'h' => true, + 'H' => true, + 'i' => true, + 's' => true, + 'u' => true, + 'v' => true, + 'E' => true, + 'I' => true, + 'O' => true, + 'P' => true, + 'Z' => true, + 'c' => true, + 'r' => true, + 'U' => true, + 'T' => true, + ]; + } + + return $replacements; + } + + /** + * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) + * but translate words whenever possible (months, day names, etc.) using the current locale. + * + * @param string $format + * + * @return string + */ + public function translatedFormat(string $format): string + { + $replacements = static::getFormatsToIsoReplacements(); + $context = ''; + $isoFormat = ''; + $length = mb_strlen($format); + + for ($i = 0; $i < $length; $i++) { + $char = mb_substr($format, $i, 1); + + if ($char === '\\') { + $replacement = mb_substr($format, $i, 2); + $isoFormat .= $replacement; + $i++; + + continue; + } + + if (!isset($replacements[$char])) { + $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; + $isoFormat .= $replacement; + $context .= $replacement; + + continue; + } + + $replacement = $replacements[$char]; + + if ($replacement === true) { + static $contextReplacements = null; + + if ($contextReplacements === null) { + $contextReplacements = [ + 'm' => 'MM', + 'd' => 'DD', + 't' => 'D', + 'j' => 'D', + 'N' => 'e', + 'w' => 'e', + 'n' => 'M', + 'o' => 'YYYY', + 'Y' => 'YYYY', + 'y' => 'YY', + 'g' => 'h', + 'G' => 'H', + 'h' => 'hh', + 'H' => 'HH', + 'i' => 'mm', + 's' => 'ss', + ]; + } + + $isoFormat .= '['.$this->rawFormat($char).']'; + $context .= $contextReplacements[$char] ?? ' '; + + continue; + } + + if ($replacement instanceof Closure) { + $replacement = '['.$replacement($this).']'; + $isoFormat .= $replacement; + $context .= $replacement; + + continue; + } + + $isoFormat .= $replacement; + $context .= $replacement; + } + + return $this->isoFormat($isoFormat, $context); + } + + /** + * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). + * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first + * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something + * like "-12:00". + * + * @param string $separator string to place between hours and minutes (":" by default) + * + * @return string + */ + public function getOffsetString($separator = ':') + { + $second = $this->getOffset(); + $symbol = $second < 0 ? '-' : '+'; + $minute = abs($second) / static::SECONDS_PER_MINUTE; + $hour = str_pad((string) floor($minute / static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT); + $minute = str_pad((string) (((int) $minute) % static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT); + + return "$symbol$hour$separator$minute"; + } + + protected static function executeStaticCallable($macro, ...$parameters) + { + return static::bindMacroContext(null, function () use (&$macro, &$parameters) { + if ($macro instanceof Closure) { + $boundMacro = @Closure::bind($macro, null, static::class); + + return ($boundMacro ?: $macro)(...$parameters); + } + + return $macro(...$parameters); + }); + } + + /** + * Dynamically handle calls to the class. + * + * @param string $method magic method name called + * @param array $parameters parameters list + * + * @throws BadMethodCallException + * + * @return mixed + */ + public static function __callStatic($method, $parameters) + { + if (!static::hasMacro($method)) { + foreach (static::getGenericMacros() as $callback) { + try { + return static::executeStaticCallable($callback, $method, ...$parameters); + } catch (BadMethodCallException $exception) { + continue; + } + } + if (static::isStrictModeEnabled()) { + throw new UnknownMethodException(sprintf('%s::%s', static::class, $method)); + } + + return null; + } + + return static::executeStaticCallable(static::$globalMacros[$method], ...$parameters); + } + + /** + * Set specified unit to new given value. + * + * @param string $unit year, month, day, hour, minute, second or microsecond + * @param int $value new value for given unit + * + * @return static + */ + public function setUnit($unit, $value = null) + { + $unit = static::singularUnit($unit); + $dateUnits = ['year', 'month', 'day']; + if (\in_array($unit, $dateUnits)) { + return $this->setDate(...array_map(function ($name) use ($unit, $value) { + return (int) ($name === $unit ? $value : $this->$name); + }, $dateUnits)); + } + + $units = ['hour', 'minute', 'second', 'micro']; + if ($unit === 'millisecond' || $unit === 'milli') { + $value *= 1000; + $unit = 'micro'; + } elseif ($unit === 'microsecond') { + $unit = 'micro'; + } + + return $this->setTime(...array_map(function ($name) use ($unit, $value) { + return (int) ($name === $unit ? $value : $this->$name); + }, $units)); + } + + /** + * Returns standardized singular of a given singular/plural unit name (in English). + * + * @param string $unit + * + * @return string + */ + public static function singularUnit(string $unit): string + { + $unit = rtrim(mb_strtolower($unit), 's'); + + if ($unit === 'centurie') { + return 'century'; + } + + if ($unit === 'millennia') { + return 'millennium'; + } + + return $unit; + } + + /** + * Returns standardized plural of a given singular/plural unit name (in English). + * + * @param string $unit + * + * @return string + */ + public static function pluralUnit(string $unit): string + { + $unit = rtrim(strtolower($unit), 's'); + + if ($unit === 'century') { + return 'centuries'; + } + + if ($unit === 'millennium' || $unit === 'millennia') { + return 'millennia'; + } + + return "{$unit}s"; + } + + protected function executeCallable($macro, ...$parameters) + { + if ($macro instanceof Closure) { + $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); + + return ($boundMacro ?: $macro)(...$parameters); + } + + return $macro(...$parameters); + } + + protected function executeCallableWithContext($macro, ...$parameters) + { + return static::bindMacroContext($this, function () use (&$macro, &$parameters) { + return $this->executeCallable($macro, ...$parameters); + }); + } + + protected static function getGenericMacros() + { + foreach (static::$globalGenericMacros as $list) { + foreach ($list as $macro) { + yield $macro; + } + } + } + + /** + * Dynamically handle calls to the class. + * + * @param string $method magic method name called + * @param array $parameters parameters list + * + * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable + * + * @return mixed + */ + public function __call($method, $parameters) + { + $diffSizes = [ + // @mode diffForHumans + 'short' => true, + // @mode diffForHumans + 'long' => false, + ]; + $diffSyntaxModes = [ + // @call diffForHumans + 'Absolute' => CarbonInterface::DIFF_ABSOLUTE, + // @call diffForHumans + 'Relative' => CarbonInterface::DIFF_RELATIVE_AUTO, + // @call diffForHumans + 'RelativeToNow' => CarbonInterface::DIFF_RELATIVE_TO_NOW, + // @call diffForHumans + 'RelativeToOther' => CarbonInterface::DIFF_RELATIVE_TO_OTHER, + ]; + $sizePattern = implode('|', array_keys($diffSizes)); + $syntaxPattern = implode('|', array_keys($diffSyntaxModes)); + + if (preg_match("/^(?<size>$sizePattern)(?<syntax>$syntaxPattern)DiffForHumans$/", $method, $match)) { + $dates = array_filter($parameters, function ($parameter) { + return $parameter instanceof DateTimeInterface; + }); + $other = null; + + if (\count($dates)) { + $key = key($dates); + $other = current($dates); + array_splice($parameters, $key, 1); + } + + return $this->diffForHumans($other, $diffSyntaxModes[$match['syntax']], $diffSizes[$match['size']], ...$parameters); + } + + $roundedValue = $this->callRoundMethod($method, $parameters); + + if ($roundedValue !== null) { + return $roundedValue; + } + + $unit = rtrim($method, 's'); + + if (str_starts_with($unit, 'is')) { + $word = substr($unit, 2); + + if (\in_array($word, static::$days, true)) { + return $this->isDayOfWeek($word); + } + + switch ($word) { + // @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + case 'Utc': + case 'UTC': + return $this->utc; + // @call is Check if the current instance has non-UTC timezone. + case 'Local': + return $this->local; + // @call is Check if the current instance is a valid date. + case 'Valid': + return $this->year !== 0; + // @call is Check if the current instance is in a daylight saving time. + case 'DST': + return $this->dst; + } + } + + $action = substr($unit, 0, 3); + $overflow = null; + + if ($action === 'set') { + $unit = strtolower(substr($unit, 3)); + } + + if (\in_array($unit, static::$units, true)) { + return $this->setUnit($unit, ...$parameters); + } + + if ($action === 'add' || $action === 'sub') { + $unit = substr($unit, 3); + + if (str_starts_with($unit, 'Real')) { + $unit = static::singularUnit(substr($unit, 4)); + + return $this->{"{$action}RealUnit"}($unit, ...$parameters); + } + + if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { + $unit = $match[1]; + $overflow = $match[2] === 'With'; + } + + $unit = static::singularUnit($unit); + } + + if (static::isModifiableUnit($unit)) { + return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); + } + + $sixFirstLetters = substr($unit, 0, 6); + $factor = -1; + + if ($sixFirstLetters === 'isLast') { + $sixFirstLetters = 'isNext'; + $factor = 1; + } + + if ($sixFirstLetters === 'isNext') { + $lowerUnit = strtolower(substr($unit, 6)); + + if (static::isModifiableUnit($lowerUnit)) { + return $this->copy()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...$parameters); + } + } + + if ($sixFirstLetters === 'isSame') { + try { + return $this->isSameUnit(strtolower(substr($unit, 6)), ...$parameters); + } catch (BadComparisonUnitException $exception) { + // Try next + } + } + + if (str_starts_with($unit, 'isCurrent')) { + try { + return $this->isCurrentUnit(strtolower(substr($unit, 9))); + } catch (BadComparisonUnitException | BadMethodCallException $exception) { + // Try next + } + } + + if (str_ends_with($method, 'Until')) { + try { + $unit = static::singularUnit(substr($method, 0, -5)); + + return $this->range( + $this->getMagicParameter($parameters, 0, 'endDate', $this), + $this->getMagicParameter($parameters, 1, 'factor', 1), + $unit + ); + } catch (InvalidArgumentException $exception) { + // Try macros + } + } + + return static::bindMacroContext($this, function () use (&$method, &$parameters) { + $macro = $this->getLocalMacro($method); + + if (!$macro) { + foreach ([$this->localGenericMacros ?: [], static::getGenericMacros()] as $list) { + foreach ($list as $callback) { + try { + return $this->executeCallable($callback, $method, ...$parameters); + } catch (BadMethodCallException $exception) { + continue; + } + } + } + + if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) { + throw new UnknownMethodException($method); + } + + return null; + } + + return $this->executeCallable($macro, ...$parameters); + }); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/DeprecatedProperties.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/DeprecatedProperties.php new file mode 100644 index 0000000..5acc6f5 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/DeprecatedProperties.php @@ -0,0 +1,61 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +trait DeprecatedProperties +{ + /** + * the day of week in current locale LC_TIME + * + * @var string + * + * @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1. + * Use ->isoFormat('MMM') instead. + * Deprecated since 2.55.0 + */ + public $localeDayOfWeek; + + /** + * the abbreviated day of week in current locale LC_TIME + * + * @var string + * + * @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1. + * Use ->isoFormat('dddd') instead. + * Deprecated since 2.55.0 + */ + public $shortLocaleDayOfWeek; + + /** + * the month in current locale LC_TIME + * + * @var string + * + * @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1. + * Use ->isoFormat('ddd') instead. + * Deprecated since 2.55.0 + */ + public $localeMonth; + + /** + * the abbreviated month in current locale LC_TIME + * + * @var string + * + * @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1. + * Use ->isoFormat('MMMM') instead. + * Deprecated since 2.55.0 + */ + public $shortLocaleMonth; +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php new file mode 100644 index 0000000..ab5b65d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php @@ -0,0 +1,1182 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Carbon; +use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; +use Carbon\CarbonInterval; +use Carbon\CarbonPeriod; +use Carbon\Translator; +use Closure; +use DateInterval; +use DateTimeInterface; +use ReturnTypeWillChange; + +/** + * Trait Difference. + * + * Depends on the following methods: + * + * @method bool lessThan($date) + * @method static copy() + * @method static resolveCarbon($date = null) + * @method static Translator translator() + */ +trait Difference +{ + /** + * @codeCoverageIgnore + * + * @param CarbonInterval $diff + */ + protected static function fixNegativeMicroseconds(CarbonInterval $diff) + { + if ($diff->s !== 0 || $diff->i !== 0 || $diff->h !== 0 || $diff->d !== 0 || $diff->m !== 0 || $diff->y !== 0) { + $diff->f = (round($diff->f * 1000000) + 1000000) / 1000000; + $diff->s--; + + if ($diff->s < 0) { + $diff->s += 60; + $diff->i--; + + if ($diff->i < 0) { + $diff->i += 60; + $diff->h--; + + if ($diff->h < 0) { + $diff->h += 24; + $diff->d--; + + if ($diff->d < 0) { + $diff->d += 30; + $diff->m--; + + if ($diff->m < 0) { + $diff->m += 12; + $diff->y--; + } + } + } + } + } + + return; + } + + $diff->f *= -1; + $diff->invert(); + } + + /** + * @param DateInterval $diff + * @param bool $absolute + * + * @return CarbonInterval + */ + protected static function fixDiffInterval(DateInterval $diff, $absolute, array $skip = []) + { + $diff = CarbonInterval::instance($diff, $skip); + + // Work-around for https://bugs.php.net/bug.php?id=77145 + // @codeCoverageIgnoreStart + if ($diff->f > 0 && $diff->y === -1 && $diff->m === 11 && $diff->d >= 27 && $diff->h === 23 && $diff->i === 59 && $diff->s === 59) { + $diff->y = 0; + $diff->m = 0; + $diff->d = 0; + $diff->h = 0; + $diff->i = 0; + $diff->s = 0; + $diff->f = (1000000 - round($diff->f * 1000000)) / 1000000; + $diff->invert(); + } elseif ($diff->f < 0) { + static::fixNegativeMicroseconds($diff); + } + // @codeCoverageIgnoreEnd + + if ($absolute && $diff->invert) { + $diff->invert(); + } + + return $diff; + } + + /** + * Get the difference as a DateInterval instance. + * Return relative interval (negative if $absolute flag is not set to true and the given date is before + * current one). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return DateInterval + */ + #[ReturnTypeWillChange] + public function diff($date = null, $absolute = false) + { + $other = $this->resolveCarbon($date); + + // Work-around for https://bugs.php.net/bug.php?id=81458 + // It was initially introduced for https://bugs.php.net/bug.php?id=80998 + // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 + // So we still need to keep this for now + // @codeCoverageIgnoreStart + if (version_compare(PHP_VERSION, '8.1.0-dev', '>=') && $other->tz !== $this->tz) { + $other = $other->avoidMutation()->tz($this->tz); + } + // @codeCoverageIgnoreEnd + + return parent::diff($other, (bool) $absolute); + } + + /** + * Get the difference as a CarbonInterval instance. + * Return relative interval (negative if $absolute flag is not set to true and the given date is before + * current one). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return CarbonInterval + */ + public function diffAsCarbonInterval($date = null, $absolute = true, array $skip = []) + { + return static::fixDiffInterval($this->diff($this->resolveCarbon($date), $absolute), $absolute, $skip); + } + + /** + * Get the difference in years + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInYears($date = null, $absolute = true) + { + return (int) $this->diff($this->resolveCarbon($date), $absolute)->format('%r%y'); + } + + /** + * Get the difference in quarters rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInQuarters($date = null, $absolute = true) + { + return (int) ($this->diffInMonths($date, $absolute) / static::MONTHS_PER_QUARTER); + } + + /** + * Get the difference in months rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMonths($date = null, $absolute = true) + { + $date = $this->resolveCarbon($date)->avoidMutation()->tz($this->tz); + + [$yearStart, $monthStart, $dayStart] = explode('-', $this->format('Y-m-dHisu')); + [$yearEnd, $monthEnd, $dayEnd] = explode('-', $date->format('Y-m-dHisu')); + + $diff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + + ((int) $monthEnd) - ((int) $monthStart); + + if ($diff > 0) { + $diff -= ($dayStart > $dayEnd ? 1 : 0); + } elseif ($diff < 0) { + $diff += ($dayStart < $dayEnd ? 1 : 0); + } + + return $absolute ? abs($diff) : $diff; + } + + /** + * Get the difference in weeks rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInWeeks($date = null, $absolute = true) + { + return (int) ($this->diffInDays($date, $absolute) / static::DAYS_PER_WEEK); + } + + /** + * Get the difference in days rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInDays($date = null, $absolute = true) + { + return $this->getIntervalDayDiff($this->diff($this->resolveCarbon($date), $absolute)); + } + + /** + * Get the difference in days using a filter closure rounded down. + * + * @param Closure $callback + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInDaysFiltered(Closure $callback, $date = null, $absolute = true) + { + return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); + } + + /** + * Get the difference in hours using a filter closure rounded down. + * + * @param Closure $callback + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInHoursFiltered(Closure $callback, $date = null, $absolute = true) + { + return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); + } + + /** + * Get the difference by the given interval using a filter closure. + * + * @param CarbonInterval $ci An interval to traverse by + * @param Closure $callback + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, $absolute = true) + { + $start = $this; + $end = $this->resolveCarbon($date); + $inverse = false; + + if ($end < $start) { + $start = $end; + $end = $this; + $inverse = true; + } + + $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); + $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); + + return $inverse && !$absolute ? -$diff : $diff; + } + + /** + * Get the difference in weekdays rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInWeekdays($date = null, $absolute = true) + { + return $this->diffInDaysFiltered(static function (CarbonInterface $date) { + return $date->isWeekday(); + }, $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute); + } + + /** + * Get the difference in weekend days using a filter rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInWeekendDays($date = null, $absolute = true) + { + return $this->diffInDaysFiltered(static function (CarbonInterface $date) { + return $date->isWeekend(); + }, $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute); + } + + /** + * Get the difference in hours rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInHours($date = null, $absolute = true) + { + return (int) ($this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR); + } + + /** + * Get the difference in hours rounded down using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealHours($date = null, $absolute = true) + { + return (int) ($this->diffInRealSeconds($date, $absolute) / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR); + } + + /** + * Get the difference in minutes rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMinutes($date = null, $absolute = true) + { + return (int) ($this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE); + } + + /** + * Get the difference in minutes rounded down using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealMinutes($date = null, $absolute = true) + { + return (int) ($this->diffInRealSeconds($date, $absolute) / static::SECONDS_PER_MINUTE); + } + + /** + * Get the difference in seconds rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInSeconds($date = null, $absolute = true) + { + $diff = $this->diff($date); + + if ($diff->days === 0) { + $diff = static::fixDiffInterval($diff, $absolute); + } + + $value = (((($diff->m || $diff->y ? $diff->days : $diff->d) * static::HOURS_PER_DAY) + + $diff->h) * static::MINUTES_PER_HOUR + + $diff->i) * static::SECONDS_PER_MINUTE + + $diff->s; + + return $absolute || !$diff->invert ? $value : -$value; + } + + /** + * Get the difference in microseconds. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMicroseconds($date = null, $absolute = true) + { + $diff = $this->diff($date); + $value = (int) round(((((($diff->m || $diff->y ? $diff->days : $diff->d) * static::HOURS_PER_DAY) + + $diff->h) * static::MINUTES_PER_HOUR + + $diff->i) * static::SECONDS_PER_MINUTE + + ($diff->f + $diff->s)) * static::MICROSECONDS_PER_SECOND); + + return $absolute || !$diff->invert ? $value : -$value; + } + + /** + * Get the difference in milliseconds rounded down. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInMilliseconds($date = null, $absolute = true) + { + return (int) ($this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND); + } + + /** + * Get the difference in seconds using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealSeconds($date = null, $absolute = true) + { + /** @var CarbonInterface $date */ + $date = $this->resolveCarbon($date); + $value = $date->getTimestamp() - $this->getTimestamp(); + + return $absolute ? abs($value) : $value; + } + + /** + * Get the difference in microseconds using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealMicroseconds($date = null, $absolute = true) + { + /** @var CarbonInterface $date */ + $date = $this->resolveCarbon($date); + $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + + $date->micro - $this->micro; + + return $absolute ? abs($value) : $value; + } + + /** + * Get the difference in milliseconds rounded down using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return int + */ + public function diffInRealMilliseconds($date = null, $absolute = true) + { + return (int) ($this->diffInRealMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND); + } + + /** + * Get the difference in seconds as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInSeconds($date = null, $absolute = true) + { + return (float) ($this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_SECOND); + } + + /** + * Get the difference in minutes as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInMinutes($date = null, $absolute = true) + { + return $this->floatDiffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; + } + + /** + * Get the difference in hours as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInHours($date = null, $absolute = true) + { + return $this->floatDiffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; + } + + /** + * Get the difference in days as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInDays($date = null, $absolute = true) + { + $hoursDiff = $this->floatDiffInHours($date, $absolute); + $interval = $this->diff($date, $absolute); + + if ($interval->y === 0 && $interval->m === 0 && $interval->d === 0) { + return $hoursDiff / static::HOURS_PER_DAY; + } + + $daysDiff = $this->getIntervalDayDiff($interval); + + return $daysDiff + fmod($hoursDiff, static::HOURS_PER_DAY) / static::HOURS_PER_DAY; + } + + /** + * Get the difference in weeks as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInWeeks($date = null, $absolute = true) + { + return $this->floatDiffInDays($date, $absolute) / static::DAYS_PER_WEEK; + } + + /** + * Get the difference in months as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInMonths($date = null, $absolute = true) + { + $start = $this; + $end = $this->resolveCarbon($date); + $ascending = ($start <= $end); + $sign = $absolute || $ascending ? 1 : -1; + if (!$ascending) { + [$start, $end] = [$end, $start]; + } + $monthsDiff = $start->diffInMonths($end); + /** @var Carbon|CarbonImmutable $floorEnd */ + $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); + + if ($floorEnd >= $end) { + return $sign * $monthsDiff; + } + + /** @var Carbon|CarbonImmutable $startOfMonthAfterFloorEnd */ + $startOfMonthAfterFloorEnd = $floorEnd->avoidMutation()->addMonth()->startOfMonth(); + + if ($startOfMonthAfterFloorEnd > $end) { + return $sign * ($monthsDiff + $floorEnd->floatDiffInDays($end) / $floorEnd->daysInMonth); + } + + return $sign * ($monthsDiff + $floorEnd->floatDiffInDays($startOfMonthAfterFloorEnd) / $floorEnd->daysInMonth + $startOfMonthAfterFloorEnd->floatDiffInDays($end) / $end->daysInMonth); + } + + /** + * Get the difference in year as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInYears($date = null, $absolute = true) + { + $start = $this; + $end = $this->resolveCarbon($date); + $ascending = ($start <= $end); + $sign = $absolute || $ascending ? 1 : -1; + if (!$ascending) { + [$start, $end] = [$end, $start]; + } + $yearsDiff = $start->diffInYears($end); + /** @var Carbon|CarbonImmutable $floorEnd */ + $floorEnd = $start->avoidMutation()->addYears($yearsDiff); + + if ($floorEnd >= $end) { + return $sign * $yearsDiff; + } + + /** @var Carbon|CarbonImmutable $startOfYearAfterFloorEnd */ + $startOfYearAfterFloorEnd = $floorEnd->avoidMutation()->addYear()->startOfYear(); + + if ($startOfYearAfterFloorEnd > $end) { + return $sign * ($yearsDiff + $floorEnd->floatDiffInDays($end) / $floorEnd->daysInYear); + } + + return $sign * ($yearsDiff + $floorEnd->floatDiffInDays($startOfYearAfterFloorEnd) / $floorEnd->daysInYear + $startOfYearAfterFloorEnd->floatDiffInDays($end) / $end->daysInYear); + } + + /** + * Get the difference in seconds as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealSeconds($date = null, $absolute = true) + { + return $this->diffInRealMicroseconds($date, $absolute) / static::MICROSECONDS_PER_SECOND; + } + + /** + * Get the difference in minutes as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealMinutes($date = null, $absolute = true) + { + return $this->floatDiffInRealSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; + } + + /** + * Get the difference in hours as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealHours($date = null, $absolute = true) + { + return $this->floatDiffInRealMinutes($date, $absolute) / static::MINUTES_PER_HOUR; + } + + /** + * Get the difference in days as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealDays($date = null, $absolute = true) + { + $date = $this->resolveUTC($date); + $utc = $this->avoidMutation()->utc(); + $hoursDiff = $utc->floatDiffInRealHours($date, $absolute); + + return ($hoursDiff < 0 ? -1 : 1) * $utc->diffInDays($date) + fmod($hoursDiff, static::HOURS_PER_DAY) / static::HOURS_PER_DAY; + } + + /** + * Get the difference in weeks as float (microsecond-precision). + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealWeeks($date = null, $absolute = true) + { + return $this->floatDiffInRealDays($date, $absolute) / static::DAYS_PER_WEEK; + } + + /** + * Get the difference in months as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealMonths($date = null, $absolute = true) + { + $start = $this; + $end = $this->resolveCarbon($date); + $ascending = ($start <= $end); + $sign = $absolute || $ascending ? 1 : -1; + if (!$ascending) { + [$start, $end] = [$end, $start]; + } + $monthsDiff = $start->diffInMonths($end); + /** @var Carbon|CarbonImmutable $floorEnd */ + $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); + + if ($floorEnd >= $end) { + return $sign * $monthsDiff; + } + + /** @var Carbon|CarbonImmutable $startOfMonthAfterFloorEnd */ + $startOfMonthAfterFloorEnd = $floorEnd->avoidMutation()->addMonth()->startOfMonth(); + + if ($startOfMonthAfterFloorEnd > $end) { + return $sign * ($monthsDiff + $floorEnd->floatDiffInRealDays($end) / $floorEnd->daysInMonth); + } + + return $sign * ($monthsDiff + $floorEnd->floatDiffInRealDays($startOfMonthAfterFloorEnd) / $floorEnd->daysInMonth + $startOfMonthAfterFloorEnd->floatDiffInRealDays($end) / $end->daysInMonth); + } + + /** + * Get the difference in year as float (microsecond-precision) using timestamps. + * + * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date + * @param bool $absolute Get the absolute of the difference + * + * @return float + */ + public function floatDiffInRealYears($date = null, $absolute = true) + { + $start = $this; + $end = $this->resolveCarbon($date); + $ascending = ($start <= $end); + $sign = $absolute || $ascending ? 1 : -1; + if (!$ascending) { + [$start, $end] = [$end, $start]; + } + $yearsDiff = $start->diffInYears($end); + /** @var Carbon|CarbonImmutable $floorEnd */ + $floorEnd = $start->avoidMutation()->addYears($yearsDiff); + + if ($floorEnd >= $end) { + return $sign * $yearsDiff; + } + + /** @var Carbon|CarbonImmutable $startOfYearAfterFloorEnd */ + $startOfYearAfterFloorEnd = $floorEnd->avoidMutation()->addYear()->startOfYear(); + + if ($startOfYearAfterFloorEnd > $end) { + return $sign * ($yearsDiff + $floorEnd->floatDiffInRealDays($end) / $floorEnd->daysInYear); + } + + return $sign * ($yearsDiff + $floorEnd->floatDiffInRealDays($startOfYearAfterFloorEnd) / $floorEnd->daysInYear + $startOfYearAfterFloorEnd->floatDiffInRealDays($end) / $end->daysInYear); + } + + /** + * The number of seconds since midnight. + * + * @return int + */ + public function secondsSinceMidnight() + { + return $this->diffInSeconds($this->avoidMutation()->startOfDay()); + } + + /** + * The number of seconds until 23:59:59. + * + * @return int + */ + public function secondsUntilEndOfDay() + { + return $this->diffInSeconds($this->avoidMutation()->endOfDay()); + } + + /** + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + * + * @example + * ``` + * echo Carbon::tomorrow()->diffForHumans() . "\n"; + * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; + * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; + * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; + * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; + * ``` + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'skip' entry, list of units to skip (array of strings or a single string, + * ` it can be the unit name (singular or plural) or its shortcut + * ` (y, m, w, d, h, min, s, ms, µs). + * - 'aUnit' entry, prefer "an hour" over "1 hour" if true + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * - 'minimumUnit' entry determines the smallest unit of time to display can be long or + * ` short form of the units, e.g. 'hour' or 'h' (default value: s) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null) + { + /* @var CarbonInterface $this */ + if (\is_array($other)) { + $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; + $syntax = $other; + $other = $syntax['other'] ?? null; + } + + $intSyntax = &$syntax; + if (\is_array($syntax)) { + $syntax['syntax'] = $syntax['syntax'] ?? null; + $intSyntax = &$syntax['syntax']; + } + $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); + $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; + + $parts = min(7, max(1, (int) $parts)); + $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; + + return $this->diffAsCarbonInterval($other, false, (array) $skip) + ->setLocalTranslator($this->getLocalTranslator()) + ->forHumans($syntax, (bool) $short, $parts, $options ?? $this->localHumanDiffOptions ?? static::getHumanDiffOptions()); + } + + /** + * @alias diffForHumans + * + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) + { + return $this->diffForHumans($other, $syntax, $short, $parts, $options); + } + + /** + * @alias diffForHumans + * + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + */ + public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) + { + return $this->diffForHumans($other, $syntax, $short, $parts, $options); + } + + /** + * Get the difference in a human readable format in the current locale from an other + * instance given (or now if null given) to current instance. + * + * When comparing a value in the past to default now: + * 1 hour from now + * 5 months from now + * + * When comparing a value in the future to default now: + * 1 hour ago + * 5 months ago + * + * When comparing a value in the past to another value: + * 1 hour after + * 5 months after + * + * When comparing a value in the future to another value: + * 1 hour before + * 5 months before + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) + { + if (!$syntax && !$other) { + $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; + } + + return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); + } + + /** + * @alias to + * + * Get the difference in a human readable format in the current locale from an other + * instance given (or now if null given) to current instance. + * + * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; + * if null passed, now will be used as comparison reference; + * if any other type, it will be converted to date and used as reference. + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * - 'other' entry (see above) + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) + { + return $this->to($other, $syntax, $short, $parts, $options); + } + + /** + * Get the difference in a human readable format in the current locale from current + * instance to now. + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single unit) + * @param int $options human diff options + * + * @return string + */ + public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) + { + $other = null; + + if ($syntax instanceof DateTimeInterface) { + [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); + } + + return $this->from($other, $syntax, $short, $parts, $options); + } + + /** + * Get the difference in a human readable format in the current locale from an other + * instance given to now + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single part) + * @param int $options human diff options + * + * @return string + */ + public function toNow($syntax = null, $short = false, $parts = 1, $options = null) + { + return $this->to(null, $syntax, $short, $parts, $options); + } + + /** + * Get the difference in a human readable format in the current locale from an other + * instance given to now + * + * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: + * - 'syntax' entry (see below) + * - 'short' entry (see below) + * - 'parts' entry (see below) + * - 'options' entry (see below) + * - 'join' entry determines how to join multiple parts of the string + * ` - if $join is a string, it's used as a joiner glue + * ` - if $join is a callable/closure, it get the list of string and should return a string + * ` - if $join is an array, the first item will be the default glue, and the second item + * ` will be used instead of the glue for the last item + * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) + * ` - if $join is missing, a space will be used as glue + * if int passed, it add modifiers: + * Possible values: + * - CarbonInterface::DIFF_ABSOLUTE no modifiers + * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier + * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier + * Default value: CarbonInterface::DIFF_ABSOLUTE + * @param bool $short displays short format of time units + * @param int $parts maximum number of parts to display (default value: 1: single part) + * @param int $options human diff options + * + * @return string + */ + public function ago($syntax = null, $short = false, $parts = 1, $options = null) + { + $other = null; + + if ($syntax instanceof DateTimeInterface) { + [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); + } + + return $this->from($other, $syntax, $short, $parts, $options); + } + + /** + * Get the difference in a human readable format in the current locale from current instance to an other + * instance given (or now if null given). + * + * @return string + */ + public function timespan($other = null, $timezone = null) + { + if (!$other instanceof DateTimeInterface) { + $other = static::parse($other, $timezone); + } + + return $this->diffForHumans($other, [ + 'join' => ', ', + 'syntax' => CarbonInterface::DIFF_ABSOLUTE, + 'options' => CarbonInterface::NO_ZERO_DIFF, + 'parts' => -1, + ]); + } + + /** + * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, + * or a calendar date (e.g. "10/29/2017") otherwise. + * + * Language, date and time formats will change according to the current locale. + * + * @param Carbon|\DateTimeInterface|string|null $referenceTime + * @param array $formats + * + * @return string + */ + public function calendar($referenceTime = null, array $formats = []) + { + /** @var CarbonInterface $current */ + $current = $this->avoidMutation()->startOfDay(); + /** @var CarbonInterface $other */ + $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); + $diff = $other->diffInDays($current, false); + $format = $diff < -6 ? 'sameElse' : ( + $diff < -1 ? 'lastWeek' : ( + $diff < 0 ? 'lastDay' : ( + $diff < 1 ? 'sameDay' : ( + $diff < 2 ? 'nextDay' : ( + $diff < 7 ? 'nextWeek' : 'sameElse' + ) + ) + ) + ) + ); + $format = array_merge($this->getCalendarFormats(), $formats)[$format]; + if ($format instanceof Closure) { + $format = $format($current, $other) ?? ''; + } + + return $this->isoFormat((string) $format); + } + + private function getIntervalDayDiff(DateInterval $interval): int + { + $daysDiff = (int) $interval->format('%a'); + $sign = $interval->format('%r') === '-' ? -1 : 1; + + if (\is_int($interval->days) && + $interval->y === 0 && + $interval->m === 0 && + version_compare(PHP_VERSION, '8.1.0-dev', '<') && + abs($interval->d - $daysDiff) === 1 + ) { + $daysDiff = abs($interval->d); // @codeCoverageIgnore + } + + return $daysDiff * $sign; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php new file mode 100644 index 0000000..f069c28 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterval; +use Carbon\Exceptions\InvalidIntervalException; +use DateInterval; + +/** + * Trait to call rounding methods to interval or the interval of a period. + */ +trait IntervalRounding +{ + protected function callRoundMethod(string $method, array $parameters) + { + $action = substr($method, 0, 4); + + if ($action !== 'ceil') { + $action = substr($method, 0, 5); + } + + if (\in_array($action, ['round', 'floor', 'ceil'])) { + return $this->{$action.'Unit'}(substr($method, \strlen($action)), ...$parameters); + } + + return null; + } + + protected function roundWith($precision, $function) + { + $unit = 'second'; + + if ($precision instanceof DateInterval) { + $precision = (string) CarbonInterval::instance($precision, [], true); + } + + if (\is_string($precision) && preg_match('/^\s*(?<precision>\d+)?\s*(?<unit>\w+)(?<other>\W.*)?$/', $precision, $match)) { + if (trim($match['other'] ?? '') !== '') { + throw new InvalidIntervalException('Rounding is only possible with single unit intervals.'); + } + + $precision = (int) ($match['precision'] ?: 1); + $unit = $match['unit']; + } + + return $this->roundUnit($unit, $precision, $function); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/IntervalStep.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/IntervalStep.php new file mode 100644 index 0000000..82d7c32 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/IntervalStep.php @@ -0,0 +1,93 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Carbon; +use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; +use Closure; +use DateTimeImmutable; +use DateTimeInterface; + +trait IntervalStep +{ + /** + * Step to apply instead of a fixed interval to get the new date. + * + * @var Closure|null + */ + protected $step; + + /** + * Get the dynamic step in use. + * + * @return Closure + */ + public function getStep(): ?Closure + { + return $this->step; + } + + /** + * Set a step to apply instead of a fixed interval to get the new date. + * + * Or pass null to switch to fixed interval. + * + * @param Closure|null $step + */ + public function setStep(?Closure $step): void + { + $this->step = $step; + } + + /** + * Take a date and apply either the step if set, or the current interval else. + * + * The interval/step is applied negatively (typically subtraction instead of addition) if $negated is true. + * + * @param DateTimeInterface $dateTime + * @param bool $negated + * + * @return CarbonInterface + */ + public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface + { + /** @var CarbonInterface $carbonDate */ + $carbonDate = $dateTime instanceof CarbonInterface ? $dateTime : $this->resolveCarbon($dateTime); + + if ($this->step) { + return $carbonDate->setDateTimeFrom(($this->step)($carbonDate->avoidMutation(), $negated)); + } + + if ($negated) { + return $carbonDate->rawSub($this); + } + + return $carbonDate->rawAdd($this); + } + + /** + * Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance. + * + * @param DateTimeInterface $dateTime + * + * @return Carbon|CarbonImmutable + */ + private function resolveCarbon(DateTimeInterface $dateTime) + { + if ($dateTime instanceof DateTimeImmutable) { + return CarbonImmutable::instance($dateTime); + } + + return Carbon::instance($dateTime); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php new file mode 100644 index 0000000..46aff11 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php @@ -0,0 +1,840 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterface; +use Carbon\Exceptions\InvalidTypeException; +use Carbon\Exceptions\NotLocaleAwareException; +use Carbon\Language; +use Carbon\Translator; +use Carbon\TranslatorStrongTypeInterface; +use Closure; +use Symfony\Component\Translation\TranslatorBagInterface; +use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\LocaleAwareInterface; +use Symfony\Contracts\Translation\TranslatorInterface as ContractsTranslatorInterface; + +// @codeCoverageIgnoreStart +if (interface_exists('Symfony\\Contracts\\Translation\\TranslatorInterface') && + !interface_exists('Symfony\\Component\\Translation\\TranslatorInterface') +) { + class_alias( + 'Symfony\\Contracts\\Translation\\TranslatorInterface', + 'Symfony\\Component\\Translation\\TranslatorInterface' + ); +} +// @codeCoverageIgnoreEnd + +/** + * Trait Localization. + * + * Embed default and locale translators and translation base methods. + */ +trait Localization +{ + /** + * Default translator. + * + * @var \Symfony\Component\Translation\TranslatorInterface + */ + protected static $translator; + + /** + * Specific translator of the current instance. + * + * @var \Symfony\Component\Translation\TranslatorInterface + */ + protected $localTranslator; + + /** + * Options for diffForHumans(). + * + * @var int + */ + protected static $humanDiffOptions = CarbonInterface::NO_ZERO_DIFF; + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * @param int $humanDiffOptions + */ + public static function setHumanDiffOptions($humanDiffOptions) + { + static::$humanDiffOptions = $humanDiffOptions; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * @param int $humanDiffOption + */ + public static function enableHumanDiffOption($humanDiffOption) + { + static::$humanDiffOptions = static::getHumanDiffOptions() | $humanDiffOption; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * @param int $humanDiffOption + */ + public static function disableHumanDiffOption($humanDiffOption) + { + static::$humanDiffOptions = static::getHumanDiffOptions() & ~$humanDiffOption; + } + + /** + * Return default humanDiff() options (merged flags as integer). + * + * @return int + */ + public static function getHumanDiffOptions() + { + return static::$humanDiffOptions; + } + + /** + * Get the default translator instance in use. + * + * @return \Symfony\Component\Translation\TranslatorInterface + */ + public static function getTranslator() + { + return static::translator(); + } + + /** + * Set the default translator instance to use. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator + * + * @return void + */ + public static function setTranslator(TranslatorInterface $translator) + { + static::$translator = $translator; + } + + /** + * Return true if the current instance has its own translator. + * + * @return bool + */ + public function hasLocalTranslator() + { + return isset($this->localTranslator); + } + + /** + * Get the translator of the current instance or the default if none set. + * + * @return \Symfony\Component\Translation\TranslatorInterface + */ + public function getLocalTranslator() + { + return $this->localTranslator ?: static::translator(); + } + + /** + * Set the translator for the current instance. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator + * + * @return $this + */ + public function setLocalTranslator(TranslatorInterface $translator) + { + $this->localTranslator = $translator; + + return $this; + } + + /** + * Returns raw translation message for a given key. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator the translator to use + * @param string $key key to find + * @param string|null $locale current locale used if null + * @param string|null $default default value if translation returns the key + * + * @return string + */ + public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) + { + if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { + throw new InvalidTypeException( + 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. + (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.' + ); + } + + if (!$locale && $translator instanceof LocaleAwareInterface) { + $locale = $translator->getLocale(); + } + + $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); + + return $result === $key ? $default : $result; + } + + /** + * Returns raw translation message for a given key. + * + * @param string $key key to find + * @param string|null $locale current locale used if null + * @param string|null $default default value if translation returns the key + * @param \Symfony\Component\Translation\TranslatorInterface $translator an optional translator to use + * + * @return string + */ + public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) + { + return static::getTranslationMessageWith($translator ?: $this->getLocalTranslator(), $key, $locale, $default); + } + + /** + * Translate using translation string or callback available. + * + * @param \Symfony\Component\Translation\TranslatorInterface $translator + * @param string $key + * @param array $parameters + * @param null $number + * + * @return string + */ + public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string + { + $message = static::getTranslationMessageWith($translator, $key, null, $key); + if ($message instanceof Closure) { + return (string) $message(...array_values($parameters)); + } + + if ($number !== null) { + $parameters['%count%'] = $number; + } + if (isset($parameters['%count%'])) { + $parameters[':count'] = $parameters['%count%']; + } + + // @codeCoverageIgnoreStart + $choice = $translator instanceof ContractsTranslatorInterface + ? $translator->trans($key, $parameters) + : $translator->transChoice($key, $number, $parameters); + // @codeCoverageIgnoreEnd + + return (string) $choice; + } + + /** + * Translate using translation string or callback available. + * + * @param string $key + * @param array $parameters + * @param string|int|float|null $number + * @param \Symfony\Component\Translation\TranslatorInterface|null $translator + * @param bool $altNumbers + * + * @return string + */ + public function translate(string $key, array $parameters = [], $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false): string + { + $translation = static::translateWith($translator ?: $this->getLocalTranslator(), $key, $parameters, $number); + + if ($number !== null && $altNumbers) { + return str_replace($number, $this->translateNumber($number), $translation); + } + + return $translation; + } + + /** + * Returns the alternative number for a given integer if available in the current locale. + * + * @param int $number + * + * @return string + */ + public function translateNumber(int $number): string + { + $translateKey = "alt_numbers.$number"; + $symbol = $this->translate($translateKey); + + if ($symbol !== $translateKey) { + return $symbol; + } + + if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { + $start = ''; + foreach ([10000, 1000, 100] as $exp) { + $key = "alt_numbers_pow.$exp"; + if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { + $unit = floor($number / $exp); + $number -= $unit * $exp; + $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; + } + } + $result = ''; + while ($number) { + $chunk = $number % 100; + $result = $this->translate("alt_numbers.$chunk").$result; + $number = floor($number / 100); + } + + return "$start$result"; + } + + if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { + $result = ''; + while ($number) { + $chunk = $number % 10; + $result = $this->translate("alt_numbers.$chunk").$result; + $number = floor($number / 10); + } + + return $result; + } + + return (string) $number; + } + + /** + * Translate a time string from a locale to an other. + * + * @param string $timeString date/time/duration string to translate (may also contain English) + * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) + * @param string|null $to output locale of the result returned (`"en"` by default) + * @param int $mode specify what to translate with options: + * - CarbonInterface::TRANSLATE_ALL (default) + * - CarbonInterface::TRANSLATE_MONTHS + * - CarbonInterface::TRANSLATE_DAYS + * - CarbonInterface::TRANSLATE_UNITS + * - CarbonInterface::TRANSLATE_MERIDIEM + * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS + * + * @return string + */ + public static function translateTimeString($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL) + { + // Fallback source and destination locales + $from = $from ?: static::getLocale(); + $to = $to ?: 'en'; + + if ($from === $to) { + return $timeString; + } + + // Standardize apostrophe + $timeString = strtr($timeString, ['’' => "'"]); + + $fromTranslations = []; + $toTranslations = []; + + foreach (['from', 'to'] as $key) { + $language = $$key; + $translator = Translator::get($language); + $translations = $translator->getMessages(); + + if (!isset($translations[$language])) { + return $timeString; + } + + $translationKey = $key.'Translations'; + $messages = $translations[$language]; + $months = $messages['months'] ?? []; + $weekdays = $messages['weekdays'] ?? []; + $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; + + if (isset($messages['ordinal_words'])) { + $timeString = self::replaceOrdinalWords( + $timeString, + $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] + ); + } + + if ($key === 'from') { + foreach (['months', 'weekdays'] as $variable) { + $list = $messages[$variable.'_standalone'] ?? null; + + if ($list) { + foreach ($$variable as $index => &$name) { + $name .= '|'.$messages[$variable.'_standalone'][$index]; + } + } + } + } + + $$translationKey = array_merge( + $mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($months, 12, $timeString) : [], + $mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($messages['months_short'] ?? [], 12, $timeString) : [], + $mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($weekdays, 7, $timeString) : [], + $mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($messages['weekdays_short'] ?? [], 7, $timeString) : [], + $mode & CarbonInterface::TRANSLATE_DIFF ? static::translateWordsByKeys([ + 'diff_now', + 'diff_today', + 'diff_yesterday', + 'diff_tomorrow', + 'diff_before_yesterday', + 'diff_after_tomorrow', + ], $messages, $key) : [], + $mode & CarbonInterface::TRANSLATE_UNITS ? static::translateWordsByKeys([ + 'year', + 'month', + 'week', + 'day', + 'hour', + 'minute', + 'second', + ], $messages, $key) : [], + $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { + if (\is_array($meridiem)) { + return $meridiem[$hour < 12 ? 0 : 1]; + } + + return $meridiem($hour, 0, false); + }, range(0, 23)) : [] + ); + } + + return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { + [$chunk] = $match; + + foreach ($fromTranslations as $index => $word) { + if (preg_match("/^$word\$/iu", $chunk)) { + return $toTranslations[$index] ?? ''; + } + } + + return $chunk; // @codeCoverageIgnore + }, " $timeString "), 1, -1); + } + + /** + * Translate a time string from the current locale (`$date->locale()`) to an other. + * + * @param string $timeString time string to translate + * @param string|null $to output locale of the result returned ("en" by default) + * + * @return string + */ + public function translateTimeStringTo($timeString, $to = null) + { + return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); + } + + /** + * Get/set the locale for the current instance. + * + * @param string|null $locale + * @param string ...$fallbackLocales + * + * @return $this|string + */ + public function locale(string $locale = null, ...$fallbackLocales) + { + if ($locale === null) { + return $this->getTranslatorLocale(); + } + + if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { + $translator = Translator::get($locale); + + if (!empty($fallbackLocales)) { + $translator->setFallbackLocales($fallbackLocales); + + foreach ($fallbackLocales as $fallbackLocale) { + $messages = Translator::get($fallbackLocale)->getMessages(); + + if (isset($messages[$fallbackLocale])) { + $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); + } + } + } + + $this->localTranslator = $translator; + } + + return $this; + } + + /** + * Get the current translator locale. + * + * @return string + */ + public static function getLocale() + { + return static::getLocaleAwareTranslator()->getLocale(); + } + + /** + * Set the current translator locale and indicate if the source locale file exists. + * Pass 'auto' as locale to use closest language from the current LC_TIME locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function setLocale($locale) + { + return static::getLocaleAwareTranslator()->setLocale($locale) !== false; + } + + /** + * Set the fallback locale. + * + * @see https://symfony.com/doc/current/components/translation.html#fallback-locales + * + * @param string $locale + */ + public static function setFallbackLocale($locale) + { + $translator = static::getTranslator(); + + if (method_exists($translator, 'setFallbackLocales')) { + $translator->setFallbackLocales([$locale]); + + if ($translator instanceof Translator) { + $preferredLocale = $translator->getLocale(); + $translator->setMessages($preferredLocale, array_replace_recursive( + $translator->getMessages()[$locale] ?? [], + Translator::get($locale)->getMessages()[$locale] ?? [], + $translator->getMessages($preferredLocale) + )); + } + } + } + + /** + * Get the fallback locale. + * + * @see https://symfony.com/doc/current/components/translation.html#fallback-locales + * + * @return string|null + */ + public static function getFallbackLocale() + { + $translator = static::getTranslator(); + + if (method_exists($translator, 'getFallbackLocales')) { + return $translator->getFallbackLocales()[0] ?? null; + } + + return null; + } + + /** + * Set the current locale to the given, execute the passed function, reset the locale to previous one, + * then return the result of the closure (or null if the closure was void). + * + * @param string $locale locale ex. en + * @param callable $func + * + * @return mixed + */ + public static function executeWithLocale($locale, $func) + { + $currentLocale = static::getLocale(); + $result = $func(static::setLocale($locale) ? static::getLocale() : false, static::translator()); + static::setLocale($currentLocale); + + return $result; + } + + /** + * Returns true if the given locale is internally supported and has short-units support. + * Support is considered enabled if either year, day or hour has a short variant translated. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasShortUnits($locale) + { + return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { + return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( + ($y = static::translateWith($translator, 'd')) !== 'd' && + $y !== static::translateWith($translator, 'day') + ) || ( + ($y = static::translateWith($translator, 'h')) !== 'h' && + $y !== static::translateWith($translator, 'hour') + ); + }); + } + + /** + * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasDiffSyntax($locale) + { + return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { + if (!$newLocale) { + return false; + } + + foreach (['ago', 'from_now', 'before', 'after'] as $key) { + if ($translator instanceof TranslatorBagInterface && + self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure + ) { + continue; + } + + if ($translator->trans($key) === $key) { + return false; + } + } + + return true; + }); + } + + /** + * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). + * Support is considered enabled if the 3 words are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasDiffOneDayWords($locale) + { + return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { + return $newLocale && + $translator->trans('diff_now') !== 'diff_now' && + $translator->trans('diff_yesterday') !== 'diff_yesterday' && + $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; + }); + } + + /** + * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). + * Support is considered enabled if the 2 words are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasDiffTwoDayWords($locale) + { + return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { + return $newLocale && + $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && + $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; + }); + } + + /** + * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). + * Support is considered enabled if the 4 sentences are translated in the given locale. + * + * @param string $locale locale ex. en + * + * @return bool + */ + public static function localeHasPeriodSyntax($locale) + { + return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { + return $newLocale && + $translator->trans('period_recurrences') !== 'period_recurrences' && + $translator->trans('period_interval') !== 'period_interval' && + $translator->trans('period_start_date') !== 'period_start_date' && + $translator->trans('period_end_date') !== 'period_end_date'; + }); + } + + /** + * Returns the list of internally available locales and already loaded custom locales. + * (It will ignore custom translator dynamic loading.) + * + * @return array + */ + public static function getAvailableLocales() + { + $translator = static::getLocaleAwareTranslator(); + + return $translator instanceof Translator + ? $translator->getAvailableLocales() + : [$translator->getLocale()]; + } + + /** + * Returns list of Language object for each available locale. This object allow you to get the ISO name, native + * name, region and variant of the locale. + * + * @return Language[] + */ + public static function getAvailableLocalesInfo() + { + $languages = []; + foreach (static::getAvailableLocales() as $id) { + $languages[$id] = new Language($id); + } + + return $languages; + } + + /** + * Initialize the default translator instance if necessary. + * + * @return \Symfony\Component\Translation\TranslatorInterface + */ + protected static function translator() + { + if (static::$translator === null) { + static::$translator = Translator::get(); + } + + return static::$translator; + } + + /** + * Get the locale of a given translator. + * + * If null or omitted, current local translator is used. + * If no local translator is in use, current global translator is used. + * + * @param null $translator + * + * @return string|null + */ + protected function getTranslatorLocale($translator = null): ?string + { + if (\func_num_args() === 0) { + $translator = $this->getLocalTranslator(); + } + + $translator = static::getLocaleAwareTranslator($translator); + + return $translator ? $translator->getLocale() : null; + } + + /** + * Throw an error if passed object is not LocaleAwareInterface. + * + * @param LocaleAwareInterface|null $translator + * + * @return LocaleAwareInterface|null + */ + protected static function getLocaleAwareTranslator($translator = null) + { + if (\func_num_args() === 0) { + $translator = static::translator(); + } + + if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { + throw new NotLocaleAwareException($translator); // @codeCoverageIgnore + } + + return $translator; + } + + /** + * @param mixed $translator + * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue + * + * @return mixed + */ + private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') + { + return $translator instanceof TranslatorStrongTypeInterface + ? $translator->getFromCatalogue($catalogue, $id, $domain) // @codeCoverageIgnore + : $catalogue->get($id, $domain); + } + + /** + * Return the word cleaned from its translation codes. + * + * @param string $word + * + * @return string + */ + private static function cleanWordFromTranslationString($word) + { + $word = str_replace([':count', '%count', ':time'], '', $word); + $word = strtr($word, ['’' => "'"]); + $word = preg_replace('/({\d+(,(\d+|Inf))?}|[\[\]]\d+(,(\d+|Inf))?[\[\]])/', '', $word); + + return trim($word); + } + + /** + * Translate a list of words. + * + * @param string[] $keys keys to translate. + * @param string[] $messages messages bag handling translations. + * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). + * + * @return string[] + */ + private static function translateWordsByKeys($keys, $messages, $key): array + { + return array_map(function ($wordKey) use ($messages, $key) { + $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) + ? $messages[$wordKey.'_regexp'] + : ($messages[$wordKey] ?? null); + + if (!$message) { + return '>>DO NOT REPLACE<<'; + } + + $parts = explode('|', $message); + + return $key === 'to' + ? self::cleanWordFromTranslationString(end($parts)) + : '(?:'.implode('|', array_map([static::class, 'cleanWordFromTranslationString'], $parts)).')'; + }, $keys); + } + + /** + * Get an array of translations based on the current date. + * + * @param callable $translation + * @param int $length + * @param string $timeString + * + * @return string[] + */ + private static function getTranslationArray($translation, $length, $timeString): array + { + $filler = '>>DO NOT REPLACE<<'; + + if (\is_array($translation)) { + return array_pad($translation, $length, $filler); + } + + $list = []; + $date = static::now(); + + for ($i = 0; $i < $length; $i++) { + $list[] = $translation($date, $timeString, $i) ?? $filler; + } + + return $list; + } + + private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string + { + return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { + return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; + }, $timeString); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Macro.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Macro.php new file mode 100644 index 0000000..92b6c9d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Macro.php @@ -0,0 +1,136 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +/** + * Trait Macros. + * + * Allows users to register macros within the Carbon class. + */ +trait Macro +{ + use Mixin; + + /** + * The registered macros. + * + * @var array + */ + protected static $globalMacros = []; + + /** + * The registered generic macros. + * + * @var array + */ + protected static $globalGenericMacros = []; + + /** + * Register a custom macro. + * + * @example + * ``` + * $userSettings = [ + * 'locale' => 'pt', + * 'timezone' => 'America/Sao_Paulo', + * ]; + * Carbon::macro('userFormat', function () use ($userSettings) { + * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar(); + * }); + * echo Carbon::yesterday()->hours(11)->userFormat(); + * ``` + * + * @param string $name + * @param object|callable $macro + * + * @return void + */ + public static function macro($name, $macro) + { + static::$globalMacros[$name] = $macro; + } + + /** + * Remove all macros and generic macros. + */ + public static function resetMacros() + { + static::$globalMacros = []; + static::$globalGenericMacros = []; + } + + /** + * Register a custom macro. + * + * @param object|callable $macro + * @param int $priority marco with higher priority is tried first + * + * @return void + */ + public static function genericMacro($macro, $priority = 0) + { + if (!isset(static::$globalGenericMacros[$priority])) { + static::$globalGenericMacros[$priority] = []; + krsort(static::$globalGenericMacros, SORT_NUMERIC); + } + + static::$globalGenericMacros[$priority][] = $macro; + } + + /** + * Checks if macro is registered globally. + * + * @param string $name + * + * @return bool + */ + public static function hasMacro($name) + { + return isset(static::$globalMacros[$name]); + } + + /** + * Get the raw callable macro registered globally for a given name. + * + * @param string $name + * + * @return callable|null + */ + public static function getMacro($name) + { + return static::$globalMacros[$name] ?? null; + } + + /** + * Checks if macro is registered globally or locally. + * + * @param string $name + * + * @return bool + */ + public function hasLocalMacro($name) + { + return ($this->localMacros && isset($this->localMacros[$name])) || static::hasMacro($name); + } + + /** + * Get the raw callable macro registered globally or locally for a given name. + * + * @param string $name + * + * @return callable|null + */ + public function getLocalMacro($name) + { + return ($this->localMacros ?? [])[$name] ?? static::getMacro($name); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/MagicParameter.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/MagicParameter.php new file mode 100644 index 0000000..310a44d --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/MagicParameter.php @@ -0,0 +1,33 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +/** + * Trait MagicParameter. + * + * Allows to retrieve parameter in magic calls by index or name. + */ +trait MagicParameter +{ + private function getMagicParameter(array $parameters, int $index, string $key, $default) + { + if (\array_key_exists($index, $parameters)) { + return $parameters[$index]; + } + + if (\array_key_exists($key, $parameters)) { + return $parameters[$key]; + } + + return $default; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php new file mode 100644 index 0000000..5822454 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php @@ -0,0 +1,226 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterface; +use Carbon\CarbonInterval; +use Carbon\CarbonPeriod; +use Closure; +use Generator; +use ReflectionClass; +use ReflectionException; +use ReflectionMethod; +use Throwable; + +/** + * Trait Mixin. + * + * Allows mixing in entire classes with multiple macros. + */ +trait Mixin +{ + /** + * Stack of macro instance contexts. + * + * @var array + */ + protected static $macroContextStack = []; + + /** + * Mix another object into the class. + * + * @example + * ``` + * Carbon::mixin(new class { + * public function addMoon() { + * return function () { + * return $this->addDays(30); + * }; + * } + * public function subMoon() { + * return function () { + * return $this->subDays(30); + * }; + * } + * }); + * $fullMoon = Carbon::create('2018-12-22'); + * $nextFullMoon = $fullMoon->addMoon(); + * $blackMoon = Carbon::create('2019-01-06'); + * $previousBlackMoon = $blackMoon->subMoon(); + * echo "$nextFullMoon\n"; + * echo "$previousBlackMoon\n"; + * ``` + * + * @param object|string $mixin + * + * @throws ReflectionException + * + * @return void + */ + public static function mixin($mixin) + { + \is_string($mixin) && trait_exists($mixin) + ? self::loadMixinTrait($mixin) + : self::loadMixinClass($mixin); + } + + /** + * @param object|string $mixin + * + * @throws ReflectionException + */ + private static function loadMixinClass($mixin) + { + $methods = (new ReflectionClass($mixin))->getMethods( + ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED + ); + + foreach ($methods as $method) { + if ($method->isConstructor() || $method->isDestructor()) { + continue; + } + + $method->setAccessible(true); + + static::macro($method->name, $method->invoke($mixin)); + } + } + + /** + * @param string $trait + */ + private static function loadMixinTrait($trait) + { + $context = eval(self::getAnonymousClassCodeForTrait($trait)); + $className = \get_class($context); + $baseClass = static::class; + + foreach (self::getMixableMethods($context) as $name) { + $closureBase = Closure::fromCallable([$context, $name]); + + static::macro($name, function (...$parameters) use ($closureBase, $className, $baseClass) { + $downContext = isset($this) ? ($this) : new $baseClass(); + $context = isset($this) ? $this->cast($className) : new $className(); + + try { + // @ is required to handle error if not converted into exceptions + $closure = @$closureBase->bindTo($context); + } catch (Throwable $throwable) { // @codeCoverageIgnore + $closure = $closureBase; // @codeCoverageIgnore + } + + // in case of errors not converted into exceptions + $closure = $closure ?: $closureBase; + + $result = $closure(...$parameters); + + if (!($result instanceof $className)) { + return $result; + } + + if ($downContext instanceof CarbonInterface && $result instanceof CarbonInterface) { + if ($context !== $result) { + $downContext = $downContext->copy(); + } + + return $downContext + ->setTimezone($result->getTimezone()) + ->modify($result->format('Y-m-d H:i:s.u')) + ->settings($result->getSettings()); + } + + if ($downContext instanceof CarbonInterval && $result instanceof CarbonInterval) { + if ($context !== $result) { + $downContext = $downContext->copy(); + } + + $downContext->copyProperties($result); + self::copyStep($downContext, $result); + self::copyNegativeUnits($downContext, $result); + + return $downContext->settings($result->getSettings()); + } + + if ($downContext instanceof CarbonPeriod && $result instanceof CarbonPeriod) { + if ($context !== $result) { + $downContext = $downContext->copy(); + } + + return $downContext + ->setDates($result->getStartDate(), $result->getEndDate()) + ->setRecurrences($result->getRecurrences()) + ->setOptions($result->getOptions()) + ->settings($result->getSettings()); + } + + return $result; + }); + } + } + + private static function getAnonymousClassCodeForTrait(string $trait) + { + return 'return new class() extends '.static::class.' {use '.$trait.';};'; + } + + private static function getMixableMethods(self $context): Generator + { + foreach (get_class_methods($context) as $name) { + if (method_exists(static::class, $name)) { + continue; + } + + yield $name; + } + } + + /** + * Stack a Carbon context from inside calls of self::this() and execute a given action. + * + * @param static|null $context + * @param callable $callable + * + * @throws Throwable + * + * @return mixed + */ + protected static function bindMacroContext($context, callable $callable) + { + static::$macroContextStack[] = $context; + + try { + return $callable(); + } finally { + array_pop(static::$macroContextStack); + } + } + + /** + * Return the current context from inside a macro callee or a null if static. + * + * @return static|null + */ + protected static function context() + { + return end(static::$macroContextStack) ?: null; + } + + /** + * Return the current context from inside a macro callee or a new one if static. + * + * @return static + */ + protected static function this() + { + return end(static::$macroContextStack) ?: new static(); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php new file mode 100644 index 0000000..39343d8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php @@ -0,0 +1,472 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterface; +use ReturnTypeWillChange; + +/** + * Trait Modifiers. + * + * Returns dates relative to current date using modifier short-hand. + */ +trait Modifiers +{ + /** + * Midday/noon hour. + * + * @var int + */ + protected static $midDayAt = 12; + + /** + * get midday/noon hour + * + * @return int + */ + public static function getMidDayAt() + { + return static::$midDayAt; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather consider mid-day is always 12pm, then if you need to test if it's an other + * hour, test it explicitly: + * $date->format('G') == 13 + * or to set explicitly to a given hour: + * $date->setTime(13, 0, 0, 0) + * + * Set midday/noon hour + * + * @param int $hour midday hour + * + * @return void + */ + public static function setMidDayAt($hour) + { + static::$midDayAt = $hour; + } + + /** + * Modify to midday, default to self::$midDayAt + * + * @return static + */ + public function midDay() + { + return $this->setTime(static::$midDayAt, 0, 0, 0); + } + + /** + * Modify to the next occurrence of a given modifier such as a day of + * the week. If no modifier is provided, modify to the next occurrence + * of the current day of the week. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param string|int|null $modifier + * + * @return static|false + */ + public function next($modifier = null) + { + if ($modifier === null) { + $modifier = $this->dayOfWeek; + } + + return $this->change( + 'next '.(\is_string($modifier) ? $modifier : static::$days[$modifier]) + ); + } + + /** + * Go forward or backward to the next week- or weekend-day. + * + * @param bool $weekday + * @param bool $forward + * + * @return static + */ + private function nextOrPreviousDay($weekday = true, $forward = true) + { + /** @var CarbonInterface $date */ + $date = $this; + $step = $forward ? 1 : -1; + + do { + $date = $date->addDays($step); + } while ($weekday ? $date->isWeekend() : $date->isWeekday()); + + return $date; + } + + /** + * Go forward to the next weekday. + * + * @return static + */ + public function nextWeekday() + { + return $this->nextOrPreviousDay(); + } + + /** + * Go backward to the previous weekday. + * + * @return static + */ + public function previousWeekday() + { + return $this->nextOrPreviousDay(true, false); + } + + /** + * Go forward to the next weekend day. + * + * @return static + */ + public function nextWeekendDay() + { + return $this->nextOrPreviousDay(false); + } + + /** + * Go backward to the previous weekend day. + * + * @return static + */ + public function previousWeekendDay() + { + return $this->nextOrPreviousDay(false, false); + } + + /** + * Modify to the previous occurrence of a given modifier such as a day of + * the week. If no dayOfWeek is provided, modify to the previous occurrence + * of the current day of the week. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param string|int|null $modifier + * + * @return static|false + */ + public function previous($modifier = null) + { + if ($modifier === null) { + $modifier = $this->dayOfWeek; + } + + return $this->change( + 'last '.(\is_string($modifier) ? $modifier : static::$days[$modifier]) + ); + } + + /** + * Modify to the first occurrence of a given day of the week + * in the current month. If no dayOfWeek is provided, modify to the + * first day of the current month. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek + * + * @return static + */ + public function firstOfMonth($dayOfWeek = null) + { + $date = $this->startOfDay(); + + if ($dayOfWeek === null) { + return $date->day(1); + } + + return $date->modify('first '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year); + } + + /** + * Modify to the last occurrence of a given day of the week + * in the current month. If no dayOfWeek is provided, modify to the + * last day of the current month. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek + * + * @return static + */ + public function lastOfMonth($dayOfWeek = null) + { + $date = $this->startOfDay(); + + if ($dayOfWeek === null) { + return $date->day($date->daysInMonth); + } + + return $date->modify('last '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year); + } + + /** + * Modify to the given occurrence of a given day of the week + * in the current month. If the calculated occurrence is outside the scope + * of the current month, then return false and no modifications are made. + * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int $nth + * @param int $dayOfWeek + * + * @return mixed + */ + public function nthOfMonth($nth, $dayOfWeek) + { + $date = $this->avoidMutation()->firstOfMonth(); + $check = $date->rawFormat('Y-m'); + $date = $date->modify('+'.$nth.' '.static::$days[$dayOfWeek]); + + return $date->rawFormat('Y-m') === $check ? $this->modify((string) $date) : false; + } + + /** + * Modify to the first occurrence of a given day of the week + * in the current quarter. If no dayOfWeek is provided, modify to the + * first day of the current quarter. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function firstOfQuarter($dayOfWeek = null) + { + return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER - 2, 1)->firstOfMonth($dayOfWeek); + } + + /** + * Modify to the last occurrence of a given day of the week + * in the current quarter. If no dayOfWeek is provided, modify to the + * last day of the current quarter. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function lastOfQuarter($dayOfWeek = null) + { + return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER, 1)->lastOfMonth($dayOfWeek); + } + + /** + * Modify to the given occurrence of a given day of the week + * in the current quarter. If the calculated occurrence is outside the scope + * of the current quarter, then return false and no modifications are made. + * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int $nth + * @param int $dayOfWeek + * + * @return mixed + */ + public function nthOfQuarter($nth, $dayOfWeek) + { + $date = $this->avoidMutation()->day(1)->month($this->quarter * static::MONTHS_PER_QUARTER); + $lastMonth = $date->month; + $year = $date->year; + $date = $date->firstOfQuarter()->modify('+'.$nth.' '.static::$days[$dayOfWeek]); + + return ($lastMonth < $date->month || $year !== $date->year) ? false : $this->modify((string) $date); + } + + /** + * Modify to the first occurrence of a given day of the week + * in the current year. If no dayOfWeek is provided, modify to the + * first day of the current year. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function firstOfYear($dayOfWeek = null) + { + return $this->month(1)->firstOfMonth($dayOfWeek); + } + + /** + * Modify to the last occurrence of a given day of the week + * in the current year. If no dayOfWeek is provided, modify to the + * last day of the current year. Use the supplied constants + * to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int|null $dayOfWeek day of the week default null + * + * @return static + */ + public function lastOfYear($dayOfWeek = null) + { + return $this->month(static::MONTHS_PER_YEAR)->lastOfMonth($dayOfWeek); + } + + /** + * Modify to the given occurrence of a given day of the week + * in the current year. If the calculated occurrence is outside the scope + * of the current year, then return false and no modifications are made. + * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. + * + * @param int $nth + * @param int $dayOfWeek + * + * @return mixed + */ + public function nthOfYear($nth, $dayOfWeek) + { + $date = $this->avoidMutation()->firstOfYear()->modify('+'.$nth.' '.static::$days[$dayOfWeek]); + + return $this->year === $date->year ? $this->modify((string) $date) : false; + } + + /** + * Modify the current instance to the average of a given instance (default now) and the current instance + * (second-precision). + * + * @param \Carbon\Carbon|\DateTimeInterface|null $date + * + * @return static + */ + public function average($date = null) + { + return $this->addRealMicroseconds((int) ($this->diffInRealMicroseconds($this->resolveCarbon($date), false) / 2)); + } + + /** + * Get the closest date from the instance (second-precision). + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return static + */ + public function closest($date1, $date2) + { + return $this->diffInRealMicroseconds($date1) < $this->diffInRealMicroseconds($date2) ? $date1 : $date2; + } + + /** + * Get the farthest date from the instance (second-precision). + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 + * + * @return static + */ + public function farthest($date1, $date2) + { + return $this->diffInRealMicroseconds($date1) > $this->diffInRealMicroseconds($date2) ? $date1 : $date2; + } + + /** + * Get the minimum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return static + */ + public function min($date = null) + { + $date = $this->resolveCarbon($date); + + return $this->lt($date) ? $this : $date; + } + + /** + * Get the minimum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see min() + * + * @return static + */ + public function minimum($date = null) + { + return $this->min($date); + } + + /** + * Get the maximum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @return static + */ + public function max($date = null) + { + $date = $this->resolveCarbon($date); + + return $this->gt($date) ? $this : $date; + } + + /** + * Get the maximum instance between a given instance (default now) and the current instance. + * + * @param \Carbon\Carbon|\DateTimeInterface|mixed $date + * + * @see max() + * + * @return static + */ + public function maximum($date = null) + { + return $this->max($date); + } + + /** + * Calls \DateTime::modify if mutable or \DateTimeImmutable::modify else. + * + * @see https://php.net/manual/en/datetime.modify.php + * + * @return static|false + */ + #[ReturnTypeWillChange] + public function modify($modify) + { + return parent::modify((string) $modify); + } + + /** + * Similar to native modify() method of DateTime but can handle more grammars. + * + * @example + * ``` + * echo Carbon::now()->change('next 2pm'); + * ``` + * + * @link https://php.net/manual/en/datetime.modify.php + * + * @param string $modifier + * + * @return static|false + */ + public function change($modifier) + { + return $this->modify(preg_replace_callback('/^(next|previous|last)\s+(\d{1,2}(h|am|pm|:\d{1,2}(:\d{1,2})?))$/i', function ($match) { + $match[2] = str_replace('h', ':00', $match[2]); + $test = $this->avoidMutation()->modify($match[2]); + $method = $match[1] === 'next' ? 'lt' : 'gt'; + $match[1] = $test->$method($this) ? $match[1].' day' : 'today'; + + return $match[1].' '.$match[2]; + }, strtr(trim($modifier), [ + ' at ' => ' ', + 'just now' => 'now', + 'after tomorrow' => 'tomorrow +1 day', + 'before yesterday' => 'yesterday -1 day', + ]))); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Mutability.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Mutability.php new file mode 100644 index 0000000..561c867 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Mutability.php @@ -0,0 +1,71 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Carbon; +use Carbon\CarbonImmutable; + +/** + * Trait Mutability. + * + * Utils to know if the current object is mutable or immutable and convert it. + */ +trait Mutability +{ + use Cast; + + /** + * Returns true if the current class/instance is mutable. + * + * @return bool + */ + public static function isMutable() + { + return false; + } + + /** + * Returns true if the current class/instance is immutable. + * + * @return bool + */ + public static function isImmutable() + { + return !static::isMutable(); + } + + /** + * Return a mutable copy of the instance. + * + * @return Carbon + */ + public function toMutable() + { + /** @var Carbon $date */ + $date = $this->cast(Carbon::class); + + return $date; + } + + /** + * Return a immutable copy of the instance. + * + * @return CarbonImmutable + */ + public function toImmutable() + { + /** @var CarbonImmutable $date */ + $date = $this->cast(CarbonImmutable::class); + + return $date; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/ObjectInitialisation.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/ObjectInitialisation.php new file mode 100644 index 0000000..c77a102 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/ObjectInitialisation.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +trait ObjectInitialisation +{ + /** + * True when parent::__construct has been called. + * + * @var string + */ + protected $constructedObjectId; +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Options.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Options.php new file mode 100644 index 0000000..48f9739 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Options.php @@ -0,0 +1,471 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterface; +use DateTimeInterface; +use Throwable; + +/** + * Trait Options. + * + * Embed base methods to change settings of Carbon classes. + * + * Depends on the following methods: + * + * @method static shiftTimezone($timezone) Set the timezone + */ +trait Options +{ + use Localization; + + /** + * Customizable PHP_INT_SIZE override. + * + * @var int + */ + public static $PHPIntSize = PHP_INT_SIZE; + + /** + * First day of week. + * + * @var int|string + */ + protected static $weekStartsAt = CarbonInterface::MONDAY; + + /** + * Last day of week. + * + * @var int|string + */ + protected static $weekEndsAt = CarbonInterface::SUNDAY; + + /** + * Days of weekend. + * + * @var array + */ + protected static $weekendDays = [ + CarbonInterface::SATURDAY, + CarbonInterface::SUNDAY, + ]; + + /** + * Format regex patterns. + * + * @var array<string, string> + */ + protected static $regexFormats = [ + 'd' => '(3[01]|[12][0-9]|0[1-9])', + 'D' => '(Sun|Mon|Tue|Wed|Thu|Fri|Sat)', + 'j' => '([123][0-9]|[1-9])', + 'l' => '([a-zA-Z]{2,})', + 'N' => '([1-7])', + 'S' => '(st|nd|rd|th)', + 'w' => '([0-6])', + 'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])', + 'W' => '(5[012]|[1-4][0-9]|0?[1-9])', + 'F' => '([a-zA-Z]{2,})', + 'm' => '(1[012]|0[1-9])', + 'M' => '([a-zA-Z]{3})', + 'n' => '(1[012]|[1-9])', + 't' => '(2[89]|3[01])', + 'L' => '(0|1)', + 'o' => '([1-9][0-9]{0,4})', + 'Y' => '([1-9]?[0-9]{4})', + 'y' => '([0-9]{2})', + 'a' => '(am|pm)', + 'A' => '(AM|PM)', + 'B' => '([0-9]{3})', + 'g' => '(1[012]|[1-9])', + 'G' => '(2[0-3]|1?[0-9])', + 'h' => '(1[012]|0[1-9])', + 'H' => '(2[0-3]|[01][0-9])', + 'i' => '([0-5][0-9])', + 's' => '([0-5][0-9])', + 'u' => '([0-9]{1,6})', + 'v' => '([0-9]{1,3})', + 'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\\/[a-zA-Z]*)', + 'I' => '(0|1)', + 'O' => '([+-](1[012]|0[0-9])[0134][05])', + 'P' => '([+-](1[012]|0[0-9]):[0134][05])', + 'p' => '(Z|[+-](1[012]|0[0-9]):[0134][05])', + 'T' => '([a-zA-Z]{1,5})', + 'Z' => '(-?[1-5]?[0-9]{1,4})', + 'U' => '([0-9]*)', + + // The formats below are combinations of the above formats. + 'c' => '(([1-9]?[0-9]{4})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[+-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP + 'r' => '(([a-zA-Z]{3}), ([123][0-9]|0[1-9]) ([a-zA-Z]{3}) ([1-9]?[0-9]{4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [+-](1[012]|0[0-9])([0134][05]))', // D, d M Y H:i:s O + ]; + + /** + * Format modifiers (such as available in createFromFormat) regex patterns. + * + * @var array + */ + protected static $regexFormatModifiers = [ + '*' => '.+', + ' ' => '[ ]', + '#' => '[;:\\/.,()-]', + '?' => '([^a]|[a])', + '!' => '', + '|' => '', + '+' => '', + ]; + + /** + * Indicates if months should be calculated with overflow. + * Global setting. + * + * @var bool + */ + protected static $monthsOverflow = true; + + /** + * Indicates if years should be calculated with overflow. + * Global setting. + * + * @var bool + */ + protected static $yearsOverflow = true; + + /** + * Indicates if the strict mode is in use. + * Global setting. + * + * @var bool + */ + protected static $strictModeEnabled = true; + + /** + * Function to call instead of format. + * + * @var string|callable|null + */ + protected static $formatFunction; + + /** + * Function to call instead of createFromFormat. + * + * @var string|callable|null + */ + protected static $createFromFormatFunction; + + /** + * Function to call instead of parse. + * + * @var string|callable|null + */ + protected static $parseFunction; + + /** + * Indicates if months should be calculated with overflow. + * Specific setting. + * + * @var bool|null + */ + protected $localMonthsOverflow; + + /** + * Indicates if years should be calculated with overflow. + * Specific setting. + * + * @var bool|null + */ + protected $localYearsOverflow; + + /** + * Indicates if the strict mode is in use. + * Specific setting. + * + * @var bool|null + */ + protected $localStrictModeEnabled; + + /** + * Options for diffForHumans and forHumans methods. + * + * @var bool|null + */ + protected $localHumanDiffOptions; + + /** + * Format to use on string cast. + * + * @var string|null + */ + protected $localToStringFormat; + + /** + * Format to use on JSON serialization. + * + * @var string|null + */ + protected $localSerializer; + + /** + * Instance-specific macros. + * + * @var array|null + */ + protected $localMacros; + + /** + * Instance-specific generic macros. + * + * @var array|null + */ + protected $localGenericMacros; + + /** + * Function to call instead of format. + * + * @var string|callable|null + */ + protected $localFormatFunction; + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * @see settings + * + * Enable the strict mode (or disable with passing false). + * + * @param bool $strictModeEnabled + */ + public static function useStrictMode($strictModeEnabled = true) + { + static::$strictModeEnabled = $strictModeEnabled; + } + + /** + * Returns true if the strict mode is globally in use, false else. + * (It can be overridden in specific instances.) + * + * @return bool + */ + public static function isStrictModeEnabled() + { + return static::$strictModeEnabled; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Indicates if months should be calculated with overflow. + * + * @param bool $monthsOverflow + * + * @return void + */ + public static function useMonthsOverflow($monthsOverflow = true) + { + static::$monthsOverflow = $monthsOverflow; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Reset the month overflow behavior. + * + * @return void + */ + public static function resetMonthsOverflow() + { + static::$monthsOverflow = true; + } + + /** + * Get the month overflow global behavior (can be overridden in specific instances). + * + * @return bool + */ + public static function shouldOverflowMonths() + { + return static::$monthsOverflow; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Indicates if years should be calculated with overflow. + * + * @param bool $yearsOverflow + * + * @return void + */ + public static function useYearsOverflow($yearsOverflow = true) + { + static::$yearsOverflow = $yearsOverflow; + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather use the ->settings() method. + * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants + * are available for quarters, years, decade, centuries, millennia (singular and plural forms). + * @see settings + * + * Reset the month overflow behavior. + * + * @return void + */ + public static function resetYearsOverflow() + { + static::$yearsOverflow = true; + } + + /** + * Get the month overflow global behavior (can be overridden in specific instances). + * + * @return bool + */ + public static function shouldOverflowYears() + { + return static::$yearsOverflow; + } + + /** + * Set specific options. + * - strictMode: true|false|null + * - monthOverflow: true|false|null + * - yearOverflow: true|false|null + * - humanDiffOptions: int|null + * - toStringFormat: string|Closure|null + * - toJsonFormat: string|Closure|null + * - locale: string|null + * - timezone: \DateTimeZone|string|int|null + * - macros: array|null + * - genericMacros: array|null + * + * @param array $settings + * + * @return $this|static + */ + public function settings(array $settings) + { + $this->localStrictModeEnabled = $settings['strictMode'] ?? null; + $this->localMonthsOverflow = $settings['monthOverflow'] ?? null; + $this->localYearsOverflow = $settings['yearOverflow'] ?? null; + $this->localHumanDiffOptions = $settings['humanDiffOptions'] ?? null; + $this->localToStringFormat = $settings['toStringFormat'] ?? null; + $this->localSerializer = $settings['toJsonFormat'] ?? null; + $this->localMacros = $settings['macros'] ?? null; + $this->localGenericMacros = $settings['genericMacros'] ?? null; + $this->localFormatFunction = $settings['formatFunction'] ?? null; + + if (isset($settings['locale'])) { + $locales = $settings['locale']; + + if (!\is_array($locales)) { + $locales = [$locales]; + } + + $this->locale(...$locales); + } + + if (isset($settings['innerTimezone'])) { + return $this->setTimezone($settings['innerTimezone']); + } + + if (isset($settings['timezone'])) { + return $this->shiftTimezone($settings['timezone']); + } + + return $this; + } + + /** + * Returns current local settings. + * + * @return array + */ + public function getSettings() + { + $settings = []; + $map = [ + 'localStrictModeEnabled' => 'strictMode', + 'localMonthsOverflow' => 'monthOverflow', + 'localYearsOverflow' => 'yearOverflow', + 'localHumanDiffOptions' => 'humanDiffOptions', + 'localToStringFormat' => 'toStringFormat', + 'localSerializer' => 'toJsonFormat', + 'localMacros' => 'macros', + 'localGenericMacros' => 'genericMacros', + 'locale' => 'locale', + 'tzName' => 'timezone', + 'localFormatFunction' => 'formatFunction', + ]; + + foreach ($map as $property => $key) { + $value = $this->$property ?? null; + + if ($value !== null && ($key !== 'locale' || $value !== 'en' || $this->localTranslator)) { + $settings[$key] = $value; + } + } + + return $settings; + } + + /** + * Show truthy properties on var_dump(). + * + * @return array + */ + public function __debugInfo() + { + $infos = array_filter(get_object_vars($this), static function ($var) { + return $var; + }); + + foreach (['dumpProperties', 'constructedObjectId', 'constructed'] as $property) { + if (isset($infos[$property])) { + unset($infos[$property]); + } + } + + $this->addExtraDebugInfos($infos); + + return $infos; + } + + protected function addExtraDebugInfos(&$infos): void + { + if ($this instanceof DateTimeInterface) { + try { + if (!isset($infos['date'])) { + $infos['date'] = $this->format(CarbonInterface::MOCK_DATETIME_FORMAT); + } + + if (!isset($infos['timezone'])) { + $infos['timezone'] = $this->tzName; + } + } catch (Throwable $exception) { + // noop + } + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php new file mode 100644 index 0000000..85ff5a7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php @@ -0,0 +1,254 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterface; +use Carbon\Exceptions\UnknownUnitException; + +/** + * Trait Rounding. + * + * Round, ceil, floor units. + * + * Depends on the following methods: + * + * @method static copy() + * @method static startOfWeek(int $weekStartsAt = null) + */ +trait Rounding +{ + use IntervalRounding; + + /** + * Round the current instance at the given unit with given precision if specified and the given function. + * + * @param string $unit + * @param float|int $precision + * @param string $function + * + * @return CarbonInterface + */ + public function roundUnit($unit, $precision = 1, $function = 'round') + { + $metaUnits = [ + // @call roundUnit + 'millennium' => [static::YEARS_PER_MILLENNIUM, 'year'], + // @call roundUnit + 'century' => [static::YEARS_PER_CENTURY, 'year'], + // @call roundUnit + 'decade' => [static::YEARS_PER_DECADE, 'year'], + // @call roundUnit + 'quarter' => [static::MONTHS_PER_QUARTER, 'month'], + // @call roundUnit + 'millisecond' => [1000, 'microsecond'], + ]; + $normalizedUnit = static::singularUnit($unit); + $ranges = array_merge(static::getRangesByUnit($this->daysInMonth), [ + // @call roundUnit + 'microsecond' => [0, 999999], + ]); + $factor = 1; + + if ($normalizedUnit === 'week') { + $normalizedUnit = 'day'; + $precision *= static::DAYS_PER_WEEK; + } + + if (isset($metaUnits[$normalizedUnit])) { + [$factor, $normalizedUnit] = $metaUnits[$normalizedUnit]; + } + + $precision *= $factor; + + if (!isset($ranges[$normalizedUnit])) { + throw new UnknownUnitException($unit); + } + + $found = false; + $fraction = 0; + $arguments = null; + $initialValue = null; + $factor = $this->year < 0 ? -1 : 1; + $changes = []; + $minimumInc = null; + + foreach ($ranges as $unit => [$minimum, $maximum]) { + if ($normalizedUnit === $unit) { + $arguments = [$this->$unit, $minimum]; + $initialValue = $this->$unit; + $fraction = $precision - floor($precision); + $found = true; + + continue; + } + + if ($found) { + $delta = $maximum + 1 - $minimum; + $factor /= $delta; + $fraction *= $delta; + $inc = ($this->$unit - $minimum) * $factor; + + if ($inc !== 0.0) { + $minimumInc = $minimumInc ?? ($arguments[0] / pow(2, 52)); + + // If value is still the same when adding a non-zero increment/decrement, + // it means precision got lost in the addition + if (abs($inc) < $minimumInc) { + $inc = $minimumInc * ($inc < 0 ? -1 : 1); + } + + // If greater than $precision, assume precision loss caused an overflow + if ($function !== 'floor' || abs($arguments[0] + $inc - $initialValue) >= $precision) { + $arguments[0] += $inc; + } + } + + $changes[$unit] = round( + $minimum + ($fraction ? $fraction * $function(($this->$unit - $minimum) / $fraction) : 0) + ); + + // Cannot use modulo as it lose double precision + while ($changes[$unit] >= $delta) { + $changes[$unit] -= $delta; + } + + $fraction -= floor($fraction); + } + } + + [$value, $minimum] = $arguments; + $normalizedValue = floor($function(($value - $minimum) / $precision) * $precision + $minimum); + + /** @var CarbonInterface $result */ + $result = $this; + + foreach ($changes as $unit => $value) { + $result = $result->$unit($value); + } + + return $result->$normalizedUnit($normalizedValue); + } + + /** + * Truncate the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int $precision + * + * @return CarbonInterface + */ + public function floorUnit($unit, $precision = 1) + { + return $this->roundUnit($unit, $precision, 'floor'); + } + + /** + * Ceil the current instance at the given unit with given precision if specified. + * + * @param string $unit + * @param float|int $precision + * + * @return CarbonInterface + */ + public function ceilUnit($unit, $precision = 1) + { + return $this->roundUnit($unit, $precision, 'ceil'); + } + + /** + * Round the current instance second with given precision if specified. + * + * @param float|int|string|\DateInterval|null $precision + * @param string $function + * + * @return CarbonInterface + */ + public function round($precision = 1, $function = 'round') + { + return $this->roundWith($precision, $function); + } + + /** + * Round the current instance second with given precision if specified. + * + * @param float|int|string|\DateInterval|null $precision + * + * @return CarbonInterface + */ + public function floor($precision = 1) + { + return $this->round($precision, 'floor'); + } + + /** + * Ceil the current instance second with given precision if specified. + * + * @param float|int|string|\DateInterval|null $precision + * + * @return CarbonInterface + */ + public function ceil($precision = 1) + { + return $this->round($precision, 'ceil'); + } + + /** + * Round the current instance week. + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return CarbonInterface + */ + public function roundWeek($weekStartsAt = null) + { + return $this->closest( + $this->avoidMutation()->floorWeek($weekStartsAt), + $this->avoidMutation()->ceilWeek($weekStartsAt) + ); + } + + /** + * Truncate the current instance week. + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return CarbonInterface + */ + public function floorWeek($weekStartsAt = null) + { + return $this->startOfWeek($weekStartsAt); + } + + /** + * Ceil the current instance week. + * + * @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week + * + * @return CarbonInterface + */ + public function ceilWeek($weekStartsAt = null) + { + if ($this->isMutable()) { + $startOfWeek = $this->avoidMutation()->startOfWeek($weekStartsAt); + + return $startOfWeek != $this ? + $this->startOfWeek($weekStartsAt)->addWeek() : + $this; + } + + $startOfWeek = $this->startOfWeek($weekStartsAt); + + return $startOfWeek != $this ? + $startOfWeek->addWeek() : + $this->avoidMutation(); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php new file mode 100644 index 0000000..c1d5c5e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php @@ -0,0 +1,326 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\Exceptions\InvalidFormatException; +use ReturnTypeWillChange; +use Throwable; + +/** + * Trait Serialization. + * + * Serialization and JSON stuff. + * + * Depends on the following properties: + * + * @property int $year + * @property int $month + * @property int $daysInMonth + * @property int $quarter + * + * Depends on the following methods: + * + * @method string|static locale(string $locale = null, string ...$fallbackLocales) + * @method string toJSON() + */ +trait Serialization +{ + use ObjectInitialisation; + + /** + * The custom Carbon JSON serializer. + * + * @var callable|null + */ + protected static $serializer; + + /** + * List of key to use for dump/serialization. + * + * @var string[] + */ + protected $dumpProperties = ['date', 'timezone_type', 'timezone']; + + /** + * Locale to dump comes here before serialization. + * + * @var string|null + */ + protected $dumpLocale; + + /** + * Embed date properties to dump in a dedicated variables so it won't overlap native + * DateTime ones. + * + * @var array|null + */ + protected $dumpDateProperties; + + /** + * Return a serialized string of the instance. + * + * @return string + */ + public function serialize() + { + return serialize($this); + } + + /** + * Create an instance from a serialized string. + * + * @param string $value + * + * @throws InvalidFormatException + * + * @return static + */ + public static function fromSerialized($value) + { + $instance = @unserialize((string) $value); + + if (!$instance instanceof static) { + throw new InvalidFormatException("Invalid serialized value: $value"); + } + + return $instance; + } + + /** + * The __set_state handler. + * + * @param string|array $dump + * + * @return static + */ + #[ReturnTypeWillChange] + public static function __set_state($dump) + { + if (\is_string($dump)) { + return static::parse($dump); + } + + /** @var \DateTimeInterface $date */ + $date = get_parent_class(static::class) && method_exists(parent::class, '__set_state') + ? parent::__set_state((array) $dump) + : (object) $dump; + + return static::instance($date); + } + + /** + * Returns the list of properties to dump on serialize() called on. + * + * Only used by PHP < 7.4. + * + * @return array + */ + public function __sleep() + { + $properties = $this->getSleepProperties(); + + if ($this->localTranslator ?? null) { + $properties[] = 'dumpLocale'; + $this->dumpLocale = $this->locale ?? null; + } + + return $properties; + } + + /** + * Returns the values to dump on serialize() called on. + * + * Only used by PHP >= 7.4. + * + * @return array + */ + public function __serialize(): array + { + // @codeCoverageIgnoreStart + if (isset($this->timezone_type, $this->timezone, $this->date)) { + return [ + 'date' => $this->date ?? null, + 'timezone_type' => $this->timezone_type, + 'timezone' => $this->timezone ?? null, + ]; + } + // @codeCoverageIgnoreEnd + + $timezone = $this->getTimezone(); + $export = [ + 'date' => $this->format('Y-m-d H:i:s.u'), + 'timezone_type' => $timezone->getType(), + 'timezone' => $timezone->getName(), + ]; + + // @codeCoverageIgnoreStart + if (\extension_loaded('msgpack') && isset($this->constructedObjectId)) { + $export['dumpDateProperties'] = [ + 'date' => $this->format('Y-m-d H:i:s.u'), + 'timezone' => serialize($this->timezone ?? null), + ]; + } + // @codeCoverageIgnoreEnd + + if ($this->localTranslator ?? null) { + $export['dumpLocale'] = $this->locale ?? null; + } + + return $export; + } + + /** + * Set locale if specified on unserialize() called. + * + * Only used by PHP < 7.4. + * + * @return void + */ + #[ReturnTypeWillChange] + public function __wakeup() + { + if (parent::class && method_exists(parent::class, '__wakeup')) { + // @codeCoverageIgnoreStart + try { + parent::__wakeup(); + } catch (Throwable $exception) { + try { + // FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later. + ['date' => $date, 'timezone' => $timezone] = $this->dumpDateProperties; + parent::__construct($date, unserialize($timezone)); + } catch (Throwable $ignoredException) { + throw $exception; + } + } + // @codeCoverageIgnoreEnd + } + + $this->constructedObjectId = spl_object_hash($this); + + if (isset($this->dumpLocale)) { + $this->locale($this->dumpLocale); + $this->dumpLocale = null; + } + + $this->cleanupDumpProperties(); + } + + /** + * Set locale if specified on unserialize() called. + * + * Only used by PHP >= 7.4. + * + * @return void + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + try { + $this->__construct($data['date'] ?? null, $data['timezone'] ?? null); + } catch (Throwable $exception) { + if (!isset($data['dumpDateProperties']['date'], $data['dumpDateProperties']['timezone'])) { + throw $exception; + } + + try { + // FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later. + ['date' => $date, 'timezone' => $timezone] = $data['dumpDateProperties']; + $this->__construct($date, unserialize($timezone)); + } catch (Throwable $ignoredException) { + throw $exception; + } + } + // @codeCoverageIgnoreEnd + + if (isset($data['dumpLocale'])) { + $this->locale($data['dumpLocale']); + } + } + + /** + * Prepare the object for JSON serialization. + * + * @return array|string + */ + #[ReturnTypeWillChange] + public function jsonSerialize() + { + $serializer = $this->localSerializer ?? static::$serializer; + + if ($serializer) { + return \is_string($serializer) + ? $this->rawFormat($serializer) + : $serializer($this); + } + + return $this->toJSON(); + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather transform Carbon object before the serialization. + * + * JSON serialize all Carbon instances using the given callback. + * + * @param callable $callback + * + * @return void + */ + public static function serializeUsing($callback) + { + static::$serializer = $callback; + } + + /** + * Cleanup properties attached to the public scope of DateTime when a dump of the date is requested. + * foreach ($date as $_) {} + * serializer($date) + * var_export($date) + * get_object_vars($date) + */ + public function cleanupDumpProperties() + { + // @codeCoverageIgnoreStart + if (PHP_VERSION < 8.2) { + foreach ($this->dumpProperties as $property) { + if (isset($this->$property)) { + unset($this->$property); + } + } + } + // @codeCoverageIgnoreEnd + + return $this; + } + + private function getSleepProperties(): array + { + $properties = $this->dumpProperties; + + // @codeCoverageIgnoreStart + if (!\extension_loaded('msgpack')) { + return $properties; + } + + if (isset($this->constructedObjectId)) { + $this->dumpDateProperties = [ + 'date' => $this->format('Y-m-d H:i:s.u'), + 'timezone' => serialize($this->timezone ?? null), + ]; + + $properties[] = 'dumpDateProperties'; + } + + return $properties; + // @codeCoverageIgnoreEnd + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Test.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Test.php new file mode 100644 index 0000000..f23c72e --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Test.php @@ -0,0 +1,228 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonInterface; +use Carbon\CarbonTimeZone; +use Closure; +use DateTimeImmutable; +use DateTimeInterface; +use InvalidArgumentException; +use Throwable; + +trait Test +{ + /////////////////////////////////////////////////////////////////// + ///////////////////////// TESTING AIDS //////////////////////////// + /////////////////////////////////////////////////////////////////// + + /** + * A test Carbon instance to be returned when now instances are created. + * + * @var Closure|static|null + */ + protected static $testNow; + + /** + * The timezone to resto to when clearing the time mock. + * + * @var string|null + */ + protected static $testDefaultTimezone; + + /** + * Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * + * Note the timezone parameter was left out of the examples above and + * has no affect as the mock value will be returned regardless of its value. + * + * Only the moment is mocked with setTestNow(), the timezone will still be the one passed + * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()). + * + * To clear the test instance call this method using the default + * parameter of null. + * + * /!\ Use this method for unit tests only. + * + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + */ + public static function setTestNow($testNow = null) + { + static::$testNow = $testNow instanceof self || $testNow instanceof Closure + ? $testNow + : static::make($testNow); + } + + /** + * Set a Carbon instance (real or mock) to be returned when a "now" + * instance is created. The provided instance will be returned + * specifically under the following conditions: + * - A call to the static now() method, ex. Carbon::now() + * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) + * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') + * - When a string containing the desired time is passed to Carbon::parse(). + * + * It will also align default timezone (e.g. call date_default_timezone_set()) with + * the second argument or if null, with the timezone of the given date object. + * + * To clear the test instance call this method using the default + * parameter of null. + * + * /!\ Use this method for unit tests only. + * + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + */ + public static function setTestNowAndTimezone($testNow = null, $tz = null) + { + if ($testNow) { + self::$testDefaultTimezone = self::$testDefaultTimezone ?? date_default_timezone_get(); + } + + $useDateInstanceTimezone = $testNow instanceof DateTimeInterface; + + if ($useDateInstanceTimezone) { + self::setDefaultTimezone($testNow->getTimezone()->getName(), $testNow); + } + + static::setTestNow($testNow); + + if (!$useDateInstanceTimezone) { + $now = static::getMockedTestNow(\func_num_args() === 1 ? null : $tz); + $tzName = $now ? $now->tzName : null; + self::setDefaultTimezone($tzName ?? self::$testDefaultTimezone ?? 'UTC', $now); + } + + if (!$testNow) { + self::$testDefaultTimezone = null; + } + } + + /** + * Temporarily sets a static date to be used within the callback. + * Using setTestNow to set the date, executing the callback, then + * clearing the test instance. + * + * /!\ Use this method for unit tests only. + * + * @template T + * + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + * @param Closure(): T $callback + * + * @return T + */ + public static function withTestNow($testNow, $callback) + { + static::setTestNow($testNow); + + try { + $result = $callback(); + } finally { + static::setTestNow(); + } + + return $result; + } + + /** + * Get the Carbon instance (real or mock) to be returned when a "now" + * instance is created. + * + * @return Closure|static the current instance used for testing + */ + public static function getTestNow() + { + return static::$testNow; + } + + /** + * Determine if there is a valid test instance set. A valid test instance + * is anything that is not null. + * + * @return bool true if there is a test instance, otherwise false + */ + public static function hasTestNow() + { + return static::getTestNow() !== null; + } + + /** + * Get the mocked date passed in setTestNow() and if it's a Closure, execute it. + * + * @param string|\DateTimeZone $tz + * + * @return \Carbon\CarbonImmutable|\Carbon\Carbon|null + */ + protected static function getMockedTestNow($tz) + { + $testNow = static::getTestNow(); + + if ($testNow instanceof Closure) { + $realNow = new DateTimeImmutable('now'); + $testNow = $testNow(static::parse( + $realNow->format('Y-m-d H:i:s.u'), + $tz ?: $realNow->getTimezone() + )); + } + /* @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $testNow */ + + return $testNow instanceof CarbonInterface + ? $testNow->avoidMutation()->tz($tz) + : $testNow; + } + + protected static function mockConstructorParameters(&$time, $tz) + { + /** @var \Carbon\CarbonImmutable|\Carbon\Carbon $testInstance */ + $testInstance = clone static::getMockedTestNow($tz); + + if (static::hasRelativeKeywords($time)) { + $testInstance = $testInstance->modify($time); + } + + $time = $testInstance instanceof self + ? $testInstance->rawFormat(static::MOCK_DATETIME_FORMAT) + : $testInstance->format(static::MOCK_DATETIME_FORMAT); + } + + private static function setDefaultTimezone($timezone, DateTimeInterface $date = null) + { + $previous = null; + $success = false; + + try { + $success = date_default_timezone_set($timezone); + } catch (Throwable $exception) { + $previous = $exception; + } + + if (!$success) { + $suggestion = @CarbonTimeZone::create($timezone)->toRegionName($date); + + throw new InvalidArgumentException( + "Timezone ID '$timezone' is invalid". + ($suggestion && $suggestion !== $timezone ? ", did you mean '$suggestion'?" : '.')."\n". + "It must be one of the IDs from DateTimeZone::listIdentifiers(),\n". + 'For the record, hours/minutes offset are relevant only for a particular moment, '. + 'but not as a default timezone.', + 0, + $previous + ); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php new file mode 100644 index 0000000..88a465c --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php @@ -0,0 +1,198 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +/** + * Trait Timestamp. + */ +trait Timestamp +{ + /** + * Create a Carbon instance from a timestamp and set the timezone (use default one if not specified). + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * @param \DateTimeZone|string|null $tz + * + * @return static + */ + public static function createFromTimestamp($timestamp, $tz = null) + { + return static::createFromTimestampUTC($timestamp)->setTimezone($tz); + } + + /** + * Create a Carbon instance from an timestamp keeping the timezone to UTC. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * + * @return static + */ + public static function createFromTimestampUTC($timestamp) + { + [$integer, $decimal] = self::getIntegerAndDecimalParts($timestamp); + $delta = floor($decimal / static::MICROSECONDS_PER_SECOND); + $integer += $delta; + $decimal -= $delta * static::MICROSECONDS_PER_SECOND; + $decimal = str_pad((string) $decimal, 6, '0', STR_PAD_LEFT); + + return static::rawCreateFromFormat('U u', "$integer $decimal"); + } + + /** + * Create a Carbon instance from a timestamp in milliseconds. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * + * @return static + */ + public static function createFromTimestampMsUTC($timestamp) + { + [$milliseconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp, 3); + $sign = $milliseconds < 0 || ($milliseconds === 0.0 && $microseconds < 0) ? -1 : 1; + $milliseconds = abs($milliseconds); + $microseconds = $sign * abs($microseconds) + static::MICROSECONDS_PER_MILLISECOND * ($milliseconds % static::MILLISECONDS_PER_SECOND); + $seconds = $sign * floor($milliseconds / static::MILLISECONDS_PER_SECOND); + $delta = floor($microseconds / static::MICROSECONDS_PER_SECOND); + $seconds += $delta; + $microseconds -= $delta * static::MICROSECONDS_PER_SECOND; + $microseconds = str_pad($microseconds, 6, '0', STR_PAD_LEFT); + + return static::rawCreateFromFormat('U u', "$seconds $microseconds"); + } + + /** + * Create a Carbon instance from a timestamp in milliseconds. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $timestamp + * @param \DateTimeZone|string|null $tz + * + * @return static + */ + public static function createFromTimestampMs($timestamp, $tz = null) + { + return static::createFromTimestampMsUTC($timestamp) + ->setTimezone($tz); + } + + /** + * Set the instance's timestamp. + * + * Timestamp input can be given as int, float or a string containing one or more numbers. + * + * @param float|int|string $unixTimestamp + * + * @return static + */ + public function timestamp($unixTimestamp) + { + return $this->setTimestamp($unixTimestamp); + } + + /** + * Returns a timestamp rounded with the given precision (6 by default). + * + * @example getPreciseTimestamp() 1532087464437474 (microsecond maximum precision) + * @example getPreciseTimestamp(6) 1532087464437474 + * @example getPreciseTimestamp(5) 153208746443747 (1/100000 second precision) + * @example getPreciseTimestamp(4) 15320874644375 (1/10000 second precision) + * @example getPreciseTimestamp(3) 1532087464437 (millisecond precision) + * @example getPreciseTimestamp(2) 153208746444 (1/100 second precision) + * @example getPreciseTimestamp(1) 15320874644 (1/10 second precision) + * @example getPreciseTimestamp(0) 1532087464 (second precision) + * @example getPreciseTimestamp(-1) 153208746 (10 second precision) + * @example getPreciseTimestamp(-2) 15320875 (100 second precision) + * + * @param int $precision + * + * @return float + */ + public function getPreciseTimestamp($precision = 6) + { + return round(((float) $this->rawFormat('Uu')) / pow(10, 6 - $precision)); + } + + /** + * Returns the milliseconds timestamps used amongst other by Date javascript objects. + * + * @return float + */ + public function valueOf() + { + return $this->getPreciseTimestamp(3); + } + + /** + * Returns the timestamp with millisecond precision. + * + * @return int + */ + public function getTimestampMs() + { + return (int) $this->getPreciseTimestamp(3); + } + + /** + * @alias getTimestamp + * + * Returns the UNIX timestamp for the current date. + * + * @return int + */ + public function unix() + { + return $this->getTimestamp(); + } + + /** + * Return an array with integer part digits and decimals digits split from one or more positive numbers + * (such as timestamps) as string with the given number of decimals (6 by default). + * + * By splitting integer and decimal, this method obtain a better precision than + * number_format when the input is a string. + * + * @param float|int|string $numbers one or more numbers + * @param int $decimals number of decimals precision (6 by default) + * + * @return array 0-index is integer part, 1-index is decimal part digits + */ + private static function getIntegerAndDecimalParts($numbers, $decimals = 6) + { + if (\is_int($numbers) || \is_float($numbers)) { + $numbers = number_format($numbers, $decimals, '.', ''); + } + + $sign = str_starts_with($numbers, '-') ? -1 : 1; + $integer = 0; + $decimal = 0; + + foreach (preg_split('`[^\d.]+`', $numbers) as $chunk) { + [$integerPart, $decimalPart] = explode('.', "$chunk."); + + $integer += (int) $integerPart; + $decimal += (float) ("0.$decimalPart"); + } + + $overflow = floor($decimal); + $integer += $overflow; + $decimal -= $overflow; + + return [$sign * $integer, $decimal === 0.0 ? 0.0 : $sign * round($decimal * pow(10, $decimals))]; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/ToStringFormat.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/ToStringFormat.php new file mode 100644 index 0000000..a81164f --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/ToStringFormat.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Closure; + +/** + * Trait ToStringFormat. + * + * Handle global format customization for string cast of the object. + */ +trait ToStringFormat +{ + /** + * Format to use for __toString method when type juggling occurs. + * + * @var string|Closure|null + */ + protected static $toStringFormat; + + /** + * Reset the format used to the default when type juggling a Carbon instance to a string + * + * @return void + */ + public static function resetToStringFormat() + { + static::setToStringFormat(null); + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string + * format. + * + * Set the default format used when type juggling a Carbon instance to a string. + * + * @param string|Closure|null $format + * + * @return void + */ + public static function setToStringFormat($format) + { + static::$toStringFormat = $format; + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Units.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Units.php new file mode 100644 index 0000000..5be14ec --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Units.php @@ -0,0 +1,412 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Carbon\CarbonConverterInterface; +use Carbon\CarbonInterface; +use Carbon\CarbonInterval; +use Carbon\Exceptions\UnitException; +use Closure; +use DateInterval; +use DateMalformedStringException; +use ReturnTypeWillChange; + +/** + * Trait Units. + * + * Add, subtract and set units. + */ +trait Units +{ + /** + * Add seconds to the instance using timestamp. Positive $value travels + * forward while negative $value travels into the past. + * + * @param string $unit + * @param int $value + * + * @return static + */ + public function addRealUnit($unit, $value = 1) + { + switch ($unit) { + // @call addRealUnit + case 'micro': + + // @call addRealUnit + case 'microsecond': + /* @var CarbonInterface $this */ + $diff = $this->microsecond + $value; + $time = $this->getTimestamp(); + $seconds = (int) floor($diff / static::MICROSECONDS_PER_SECOND); + $time += $seconds; + $diff -= $seconds * static::MICROSECONDS_PER_SECOND; + $microtime = str_pad((string) $diff, 6, '0', STR_PAD_LEFT); + $tz = $this->tz; + + return $this->tz('UTC')->modify("@$time.$microtime")->tz($tz); + + // @call addRealUnit + case 'milli': + // @call addRealUnit + case 'millisecond': + return $this->addRealUnit('microsecond', $value * static::MICROSECONDS_PER_MILLISECOND); + + // @call addRealUnit + case 'second': + break; + + // @call addRealUnit + case 'minute': + $value *= static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'hour': + $value *= static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'day': + $value *= static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'week': + $value *= static::DAYS_PER_WEEK * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'month': + $value *= 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'quarter': + $value *= static::MONTHS_PER_QUARTER * 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'year': + $value *= 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'decade': + $value *= static::YEARS_PER_DECADE * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'century': + $value *= static::YEARS_PER_CENTURY * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + // @call addRealUnit + case 'millennium': + $value *= static::YEARS_PER_MILLENNIUM * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE; + + break; + + default: + if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) { + throw new UnitException("Invalid unit for real timestamp add/sub: '$unit'"); + } + + return $this; + } + + /* @var CarbonInterface $this */ + return $this->setTimestamp((int) ($this->getTimestamp() + $value)); + } + + public function subRealUnit($unit, $value = 1) + { + return $this->addRealUnit($unit, -$value); + } + + /** + * Returns true if a property can be changed via setter. + * + * @param string $unit + * + * @return bool + */ + public static function isModifiableUnit($unit) + { + static $modifiableUnits = [ + // @call addUnit + 'millennium', + // @call addUnit + 'century', + // @call addUnit + 'decade', + // @call addUnit + 'quarter', + // @call addUnit + 'week', + // @call addUnit + 'weekday', + ]; + + return \in_array($unit, $modifiableUnits, true) || \in_array($unit, static::$units, true); + } + + /** + * Call native PHP DateTime/DateTimeImmutable add() method. + * + * @param DateInterval $interval + * + * @return static + */ + public function rawAdd(DateInterval $interval) + { + return parent::add($interval); + } + + /** + * Add given units or interval to the current instance. + * + * @example $date->add('hour', 3) + * @example $date->add(15, 'days') + * @example $date->add(CarbonInterval::days(4)) + * + * @param string|DateInterval|Closure|CarbonConverterInterface $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + #[ReturnTypeWillChange] + public function add($unit, $value = 1, $overflow = null) + { + if (\is_string($unit) && \func_num_args() === 1) { + $unit = CarbonInterval::make($unit, [], true); + } + + if ($unit instanceof CarbonConverterInterface) { + return $this->resolveCarbon($unit->convertDate($this, false)); + } + + if ($unit instanceof Closure) { + return $this->resolveCarbon($unit($this, false)); + } + + if ($unit instanceof DateInterval) { + return parent::add($unit); + } + + if (is_numeric($unit)) { + [$value, $unit] = [$unit, $value]; + } + + return $this->addUnit($unit, $value, $overflow); + } + + /** + * Add given units to the current instance. + * + * @param string $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + public function addUnit($unit, $value = 1, $overflow = null) + { + $originalArgs = \func_get_args(); + + $date = $this; + + if (!is_numeric($value) || !(float) $value) { + return $date->isMutable() ? $date : $date->avoidMutation(); + } + + $unit = self::singularUnit($unit); + $metaUnits = [ + 'millennium' => [static::YEARS_PER_MILLENNIUM, 'year'], + 'century' => [static::YEARS_PER_CENTURY, 'year'], + 'decade' => [static::YEARS_PER_DECADE, 'year'], + 'quarter' => [static::MONTHS_PER_QUARTER, 'month'], + ]; + + if (isset($metaUnits[$unit])) { + [$factor, $unit] = $metaUnits[$unit]; + $value *= $factor; + } + + if ($unit === 'weekday') { + $weekendDays = static::getWeekendDays(); + + if ($weekendDays !== [static::SATURDAY, static::SUNDAY]) { + $absoluteValue = abs($value); + $sign = $value / max(1, $absoluteValue); + $weekDaysCount = 7 - min(6, \count(array_unique($weekendDays))); + $weeks = floor($absoluteValue / $weekDaysCount); + + for ($diff = $absoluteValue % $weekDaysCount; $diff; $diff--) { + /** @var static $date */ + $date = $date->addDays($sign); + + while (\in_array($date->dayOfWeek, $weekendDays, true)) { + $date = $date->addDays($sign); + } + } + + $value = $weeks * $sign; + $unit = 'week'; + } + + $timeString = $date->toTimeString(); + } elseif ($canOverflow = (\in_array($unit, [ + 'month', + 'year', + ]) && ($overflow === false || ( + $overflow === null && + ($ucUnit = ucfirst($unit).'s') && + !($this->{'local'.$ucUnit.'Overflow'} ?? static::{'shouldOverflow'.$ucUnit}()) + )))) { + $day = $date->day; + } + + $value = (int) $value; + + if ($unit === 'milli' || $unit === 'millisecond') { + $unit = 'microsecond'; + $value *= static::MICROSECONDS_PER_MILLISECOND; + } + + // Work-around for bug https://bugs.php.net/bug.php?id=75642 + if ($unit === 'micro' || $unit === 'microsecond') { + $microseconds = $this->micro + $value; + $second = (int) floor($microseconds / static::MICROSECONDS_PER_SECOND); + $microseconds %= static::MICROSECONDS_PER_SECOND; + if ($microseconds < 0) { + $microseconds += static::MICROSECONDS_PER_SECOND; + } + $date = $date->microseconds($microseconds); + $unit = 'second'; + $value = $second; + } + + try { + $date = $date->modify("$value $unit"); + + if (isset($timeString)) { + $date = $date->setTimeFromTimeString($timeString); + } elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) { + $date = $date->modify('last day of previous month'); + } + } catch (DateMalformedStringException $ignoredException) { // @codeCoverageIgnore + $date = null; // @codeCoverageIgnore + } + + if (!$date) { + throw new UnitException('Unable to add unit '.var_export($originalArgs, true)); + } + + return $date; + } + + /** + * Subtract given units to the current instance. + * + * @param string $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + public function subUnit($unit, $value = 1, $overflow = null) + { + return $this->addUnit($unit, -$value, $overflow); + } + + /** + * Call native PHP DateTime/DateTimeImmutable sub() method. + * + * @param DateInterval $interval + * + * @return static + */ + public function rawSub(DateInterval $interval) + { + return parent::sub($interval); + } + + /** + * Subtract given units or interval to the current instance. + * + * @example $date->sub('hour', 3) + * @example $date->sub(15, 'days') + * @example $date->sub(CarbonInterval::days(4)) + * + * @param string|DateInterval|Closure|CarbonConverterInterface $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + #[ReturnTypeWillChange] + public function sub($unit, $value = 1, $overflow = null) + { + if (\is_string($unit) && \func_num_args() === 1) { + $unit = CarbonInterval::make($unit, [], true); + } + + if ($unit instanceof CarbonConverterInterface) { + return $this->resolveCarbon($unit->convertDate($this, true)); + } + + if ($unit instanceof Closure) { + return $this->resolveCarbon($unit($this, true)); + } + + if ($unit instanceof DateInterval) { + return parent::sub($unit); + } + + if (is_numeric($unit)) { + [$value, $unit] = [$unit, $value]; + } + + return $this->addUnit($unit, -(float) $value, $overflow); + } + + /** + * Subtract given units or interval to the current instance. + * + * @see sub() + * + * @param string|DateInterval $unit + * @param int $value + * @param bool|null $overflow + * + * @return static + */ + public function subtract($unit, $value = 1, $overflow = null) + { + if (\is_string($unit) && \func_num_args() === 1) { + $unit = CarbonInterval::make($unit, [], true); + } + + return $this->sub($unit, $value, $overflow); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Week.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Week.php new file mode 100644 index 0000000..6f14814 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Traits/Week.php @@ -0,0 +1,219 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +/** + * Trait Week. + * + * week and ISO week number, year and count in year. + * + * Depends on the following properties: + * + * @property int $daysInYear + * @property int $dayOfWeek + * @property int $dayOfYear + * @property int $year + * + * Depends on the following methods: + * + * @method static addWeeks(int $weeks = 1) + * @method static copy() + * @method static dayOfYear(int $dayOfYear) + * @method string getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) + * @method static next(int|string $day = null) + * @method static startOfWeek(int $day = 1) + * @method static subWeeks(int $weeks = 1) + * @method static year(int $year = null) + */ +trait Week +{ + /** + * Set/get the week number of year using given first day of week and first + * day of year included in the first week. Or use ISO format if no settings + * given. + * + * @param int|null $year if null, act as a getter, if not null, set the year and return current instance. + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int|static + */ + public function isoWeekYear($year = null, $dayOfWeek = null, $dayOfYear = null) + { + return $this->weekYear( + $year, + $dayOfWeek ?? 1, + $dayOfYear ?? 4 + ); + } + + /** + * Set/get the week number of year using given first day of week and first + * day of year included in the first week. Or use US format if no settings + * given (Sunday / Jan 6). + * + * @param int|null $year if null, act as a getter, if not null, set the year and return current instance. + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int|static + */ + public function weekYear($year = null, $dayOfWeek = null, $dayOfYear = null) + { + $dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? 0; + $dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1; + + if ($year !== null) { + $year = (int) round($year); + + if ($this->weekYear(null, $dayOfWeek, $dayOfYear) === $year) { + return $this->avoidMutation(); + } + + $week = $this->week(null, $dayOfWeek, $dayOfYear); + $day = $this->dayOfWeek; + $date = $this->year($year); + switch ($date->weekYear(null, $dayOfWeek, $dayOfYear) - $year) { + case 1: + $date = $date->subWeeks(26); + + break; + case -1: + $date = $date->addWeeks(26); + + break; + } + + $date = $date->addWeeks($week - $date->week(null, $dayOfWeek, $dayOfYear))->startOfWeek($dayOfWeek); + + if ($date->dayOfWeek === $day) { + return $date; + } + + return $date->next($day); + } + + $year = $this->year; + $day = $this->dayOfYear; + $date = $this->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); + + if ($date->year === $year && $day < $date->dayOfYear) { + return $year - 1; + } + + $date = $this->avoidMutation()->addYear()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); + + if ($date->year === $year && $day >= $date->dayOfYear) { + return $year + 1; + } + + return $year; + } + + /** + * Get the number of weeks of the current week-year using given first day of week and first + * day of year included in the first week. Or use ISO format if no settings + * given. + * + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int + */ + public function isoWeeksInYear($dayOfWeek = null, $dayOfYear = null) + { + return $this->weeksInYear( + $dayOfWeek ?? 1, + $dayOfYear ?? 4 + ); + } + + /** + * Get the number of weeks of the current week-year using given first day of week and first + * day of year included in the first week. Or use US format if no settings + * given (Sunday / Jan 6). + * + * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) + * @param int|null $dayOfYear first day of year included in the week #1 + * + * @return int + */ + public function weeksInYear($dayOfWeek = null, $dayOfYear = null) + { + $dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? 0; + $dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1; + $year = $this->year; + $start = $this->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); + $startDay = $start->dayOfYear; + if ($start->year !== $year) { + $startDay -= $start->daysInYear; + } + $end = $this->avoidMutation()->addYear()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); + $endDay = $end->dayOfYear; + if ($end->year !== $year) { + $endDay += $this->daysInYear; + } + + return (int) round(($endDay - $startDay) / 7); + } + + /** + * Get/set the week number using given first day of week and first + * day of year included in the first week. Or use US format if no settings + * given (Sunday / Jan 6). + * + * @param int|null $week + * @param int|null $dayOfWeek + * @param int|null $dayOfYear + * + * @return int|static + */ + public function week($week = null, $dayOfWeek = null, $dayOfYear = null) + { + $date = $this; + $dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? 0; + $dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1; + + if ($week !== null) { + return $date->addWeeks(round($week) - $this->week(null, $dayOfWeek, $dayOfYear)); + } + + $start = $date->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); + $end = $date->avoidMutation()->startOfWeek($dayOfWeek); + if ($start > $end) { + $start = $start->subWeeks(26)->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); + } + $week = (int) ($start->diffInDays($end) / 7 + 1); + + return $week > $end->weeksInYear($dayOfWeek, $dayOfYear) ? 1 : $week; + } + + /** + * Get/set the week number using given first day of week and first + * day of year included in the first week. Or use ISO format if no settings + * given. + * + * @param int|null $week + * @param int|null $dayOfWeek + * @param int|null $dayOfYear + * + * @return int|static + */ + public function isoWeek($week = null, $dayOfWeek = null, $dayOfYear = null) + { + return $this->week( + $week, + $dayOfWeek ?? 1, + $dayOfYear ?? 4 + ); + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Translator.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Translator.php new file mode 100644 index 0000000..491c9e7 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/Translator.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use ReflectionMethod; +use Symfony\Component\Translation; +use Symfony\Contracts\Translation\TranslatorInterface; + +$transMethod = new ReflectionMethod( + class_exists(TranslatorInterface::class) + ? TranslatorInterface::class + : Translation\Translator::class, + 'trans' +); + +require $transMethod->hasReturnType() + ? __DIR__.'/../../lazy/Carbon/TranslatorStrongType.php' + : __DIR__.'/../../lazy/Carbon/TranslatorWeakType.php'; + +class Translator extends LazyTranslator +{ + // Proxy dynamically loaded LazyTranslator in a static way +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php new file mode 100644 index 0000000..ce6b2f9 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php @@ -0,0 +1,99 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Carbon\Exceptions\ImmutableException; +use Symfony\Component\Config\ConfigCacheFactoryInterface; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +class TranslatorImmutable extends Translator +{ + /** @var bool */ + private $constructed = false; + + public function __construct($locale, MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false) + { + parent::__construct($locale, $formatter, $cacheDir, $debug); + $this->constructed = true; + } + + /** + * @codeCoverageIgnore + */ + public function setDirectories(array $directories) + { + $this->disallowMutation(__METHOD__); + + return parent::setDirectories($directories); + } + + public function setLocale($locale) + { + $this->disallowMutation(__METHOD__); + + return parent::setLocale($locale); + } + + /** + * @codeCoverageIgnore + */ + public function setMessages($locale, $messages) + { + $this->disallowMutation(__METHOD__); + + return parent::setMessages($locale, $messages); + } + + /** + * @codeCoverageIgnore + */ + public function setTranslations($messages) + { + $this->disallowMutation(__METHOD__); + + return parent::setTranslations($messages); + } + + /** + * @codeCoverageIgnore + */ + public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory): void + { + $this->disallowMutation(__METHOD__); + + parent::setConfigCacheFactory($configCacheFactory); + } + + public function resetMessages($locale = null) + { + $this->disallowMutation(__METHOD__); + + return parent::resetMessages($locale); + } + + /** + * @codeCoverageIgnore + */ + public function setFallbackLocales(array $locales) + { + $this->disallowMutation(__METHOD__); + + parent::setFallbackLocales($locales); + } + + private function disallowMutation($method) + { + if ($this->constructed) { + throw new ImmutableException($method.' not allowed on '.static::class); + } + } +} diff --git a/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/TranslatorStrongTypeInterface.php b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/TranslatorStrongTypeInterface.php new file mode 100644 index 0000000..ef4dee8 --- /dev/null +++ b/php/libraries/composer/vendor/nesbot/carbon/src/Carbon/TranslatorStrongTypeInterface.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Carbon package. + * + * (c) Brian Nesbitt <brian@nesbot.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +use Symfony\Component\Translation\MessageCatalogueInterface; + +/** + * Mark translator using strong type from symfony/translation >= 6. + */ +interface TranslatorStrongTypeInterface +{ + public function getFromCatalogue(MessageCatalogueInterface $catalogue, string $id, string $domain = 'messages'); +} diff --git a/php/libraries/composer/vendor/nette/schema/composer.json b/php/libraries/composer/vendor/nette/schema/composer.json new file mode 100644 index 0000000..626e98f --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/composer.json @@ -0,0 +1,39 @@ +{ + "name": "nette/schema", + "description": "📐 Nette Schema: validating data structures against a given Schema.", + "keywords": ["nette", "config"], + "homepage": "https://nette.org", + "license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "require": { + "php": "8.1 - 8.3", + "nette/utils": "^4.0" + }, + "require-dev": { + "nette/tester": "^2.4", + "tracy/tracy": "^2.8", + "phpstan/phpstan-nette": "^1.0" + }, + "autoload": { + "classmap": ["src/"] + }, + "minimum-stability": "dev", + "scripts": { + "phpstan": "phpstan analyse", + "tester": "tester tests -s" + }, + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + } +} diff --git a/php/libraries/composer/vendor/nette/schema/license.md b/php/libraries/composer/vendor/nette/schema/license.md new file mode 100644 index 0000000..cf741bd --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/license.md @@ -0,0 +1,60 @@ +Licenses +======== + +Good news! You may use Nette Framework under the terms of either +the New BSD License or the GNU General Public License (GPL) version 2 or 3. + +The BSD License is recommended for most projects. It is easy to understand and it +places almost no restrictions on what you can do with the framework. If the GPL +fits better to your project, you can use the framework under this license. + +You don't have to notify anyone which license you are using. You can freely +use Nette Framework in commercial projects as long as the copyright header +remains intact. + +Please be advised that the name "Nette Framework" is a protected trademark and its +usage has some limitations. So please do not use word "Nette" in the name of your +project or top-level domain, and choose a name that stands on its own merits. +If your stuff is good, it will not take long to establish a reputation for yourselves. + + +New BSD License +--------------- + +Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of "Nette Framework" nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are +disclaimed. In no event shall the copyright owner or contributors be liable for +any direct, indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused and on +any theory of liability, whether in contract, strict liability, or tort +(including negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + + +GNU General Public License +-------------------------- + +GPL licenses are very very long, so instead of including them here we offer +you URLs with full text: + +- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) +- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) diff --git a/php/libraries/composer/vendor/nette/schema/readme.md b/php/libraries/composer/vendor/nette/schema/readme.md new file mode 100644 index 0000000..c88f6bd --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/readme.md @@ -0,0 +1,537 @@ +Nette Schema +************ + +[![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema) +[![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions) +[![Coverage Status](https://coveralls.io/repos/github/nette/schema/badge.svg?branch=master)](https://coveralls.io/github/nette/schema?branch=master) +[![Latest Stable Version](https://poser.pugx.org/nette/schema/v/stable)](https://github.com/nette/schema/releases) +[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/schema/blob/master/license.md) + + +Introduction +============ + +A practical library for validation and normalization of data structures against a given schema with a smart & easy-to-understand API. + +Documentation can be found on the [website](https://doc.nette.org/schema). + +Installation: + +```shell +composer require nette/schema +``` + +It requires PHP version 8.1 and supports PHP up to 8.3. + + +[Support Me](https://github.com/sponsors/dg) +-------------------------------------------- + +Do you like Nette Schema? Are you looking forward to the new features? + +[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) + +Thank you! + + +Basic Usage +----------- + +In variable `$schema` we have a validation schema (what exactly this means and how to create it we will say later) and in variable `$data` we have a data structure that we want to validate and normalize. This can be, for example, data sent by the user through an API, configuration file, etc. + +The task is handled by the [Nette\Schema\Processor](https://api.nette.org/schema/master/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws an [Nette\Schema\ValidationException](https://api.nette.org/schema/master/Nette/Schema/ValidationException.html) exception on error. + +```php +$processor = new Nette\Schema\Processor; + +try { + $normalized = $processor->process($schema, $data); +} catch (Nette\Schema\ValidationException $e) { + echo 'Data is invalid: ' . $e->getMessage(); +} +``` + +Method `$e->getMessages()` returns array of all message strings and `$e->getMessageObjects()` return all messages as [Nette\Schema\Message](https://api.nette.org/schema/master/Nette/Schema/Message.html) objects. + + +Defining Schema +--------------- + +And now let's create a schema. The class [Nette\Schema\Expect](https://api.nette.org/schema/master/Nette/Schema/Expect.html) is used to define it, we actually define expectations of what the data should look like. Let's say that the input data must be a structure (e.g. an array) containing elements `processRefund` of type bool and `refundAmount` of type int. + +```php +use Nette\Schema\Expect; + +$schema = Expect::structure([ + 'processRefund' => Expect::bool(), + 'refundAmount' => Expect::int(), +]); +``` + +We believe that the schema definition looks clear, even if you see it for the very first time. + +Lets send the following data for validation: + +```php +$data = [ + 'processRefund' => true, + 'refundAmount' => 17, +]; + +$normalized = $processor->process($schema, $data); // OK, it passes +``` + +The output, i.e. the value `$normalized`, is the object `stdClass`. If we want the output to be an array, we add a cast to schema `Expect::structure([...])->castTo('array')`. + +All elements of the structure are optional and have a default value `null`. Example: + +```php +$data = [ + 'refundAmount' => 17, +]; + +$normalized = $processor->process($schema, $data); // OK, it passes +// $normalized = {'processRefund' => null, 'refundAmount' => 17} +``` + +The fact that the default value is `null` does not mean that it would be accepted in the input data `'processRefund' => null`. No, the input must be boolean, i.e. only `true` or `false`. We would have to explicitly allow `null` via `Expect::bool()->nullable()`. + +An item can be made mandatory using `Expect::bool()->required()`. We change the default value to `false` using `Expect::bool()->default(false)` or shortly using `Expect::bool(false)`. + +And what if we wanted to accept `1` and `0` besides booleans? Then we list the allowed values, which we will also normalize to boolean: + +```php +$schema = Expect::structure([ + 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), + 'refundAmount' => Expect::int(), +]); + +$normalized = $processor->process($schema, $data); +is_bool($normalized->processRefund); // true +``` + +Now you know the basics of how the schema is defined and how the individual elements of the structure behave. We will now show what all the other elements can be used in defining a schema. + + +Data Types: type() +------------------ + +All standard PHP data types can be listed in the schema: + +```php +Expect::string($default = null) +Expect::int($default = null) +Expect::float($default = null) +Expect::bool($default = null) +Expect::null() +Expect::array($default = []) +``` + +And then all types [supported by the Validators](https://doc.nette.org/validators#toc-validation-rules) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`. + +You can also use union notation: + +```php +Expect::type('bool|string|array') +``` + +The default value is always `null` except for `array` and `list`, where it is an empty array. (A list is an array indexed in ascending order of numeric keys from zero, that is, a non-associative array). + + +Array of Values: arrayOf() listOf() +----------------------------------- + +The array is too general structure, it is more useful to specify exactly what elements it can contain. For example, an array whose elements can only be strings: + +```php +$schema = Expect::arrayOf('string'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK +$processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string +``` + +The second parameter can be used to specify keys (since version 1.2): + +```php +$schema = Expect::arrayOf('string', 'int'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not int +``` + +The list is an indexed array: + +```php +$schema = Expect::listOf('string'); + +$processor->process($schema, ['a', 'b']); // OK +$processor->process($schema, ['a', 123]); // ERROR: 123 is not a string +$processor->process($schema, ['key' => 'a']); // ERROR: is not a list +$processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: is not a list +``` + +The parameter can also be a schema, so we can write: + +```php +Expect::arrayOf(Expect::bool()) +``` + +The default value is an empty array. If you specify a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)`. + + +Enumeration: anyOf() +-------------------- + +`anyOf()` is a set of values ​​or schemas that a value can be. Here's how to write an array of elements that can be either `'a'`, `true`, or `null`: + +```php +$schema = Expect::listOf( + Expect::anyOf('a', true, null), +); + +$processor->process($schema, ['a', true, null, 'a']); // OK +$processor->process($schema, ['a', false]); // ERROR: false does not belong there +``` + +The enumeration elements can also be schemas: + +```php +$schema = Expect::listOf( + Expect::anyOf(Expect::string(), true, null), +); + +$processor->process($schema, ['foo', true, null, 'bar']); // OK +$processor->process($schema, [123]); // ERROR +``` + +The `anyOf()` method accepts variants as individual parameters, not as array. To pass it an array of values, use the unpacking operator `anyOf(...$variants)`. + +The default value is `null`. Use the `firstIsDefault()` method to make the first element the default: + +```php +// default is 'hello' +Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); +``` + + +Structures +---------- + +Structures are objects with defined keys. Each of these key => value pairs is referred to as a "property": + +Structures accept arrays and objects and return objects `stdClass` (unless you change it with `castTo('array')`, etc.). + +By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`: + +```php +$schema = Expect::structure([ + 'required' => Expect::string()->required(), + 'optional' => Expect::string(), // the default value is null +]); + +$processor->process($schema, ['optional' => '']); +// ERROR: option 'required' is missing + +$processor->process($schema, ['required' => 'foo']); +// OK, returns {'required' => 'foo', 'optional' => null} +``` + +If you do not want to output properties with only a default value, use `skipDefaults()`: + +```php +$schema = Expect::structure([ + 'required' => Expect::string()->required(), + 'optional' => Expect::string(), +])->skipDefaults(); + +$processor->process($schema, ['required' => 'foo']); +// OK, returns {'required' => 'foo'} +``` + +Although `null` is the default value of the `optional` property, it is not allowed in the input data (the value must be a string). Properties accepting `null` are defined using `nullable()`: + +```php +$schema = Expect::structure([ + 'optional' => Expect::string(), + 'nullable' => Expect::string()->nullable(), +]); + +$processor->process($schema, ['optional' => null]); +// ERROR: 'optional' expects to be string, null given. + +$processor->process($schema, ['nullable' => null]); +// OK, returns {'optional' => null, 'nullable' => null} +``` + +By default, there can be no extra items in the input data: + +```php +$schema = Expect::structure([ + 'key' => Expect::string(), +]); + +$processor->process($schema, ['additional' => 1]); +// ERROR: Unexpected item 'additional' +``` + +Which we can change with `otherItems()`. As a parameter, we will specify the schema for each extra element: + +```php +$schema = Expect::structure([ + 'key' => Expect::string(), +])->otherItems(Expect::int()); + +$processor->process($schema, ['additional' => 1]); // OK +$processor->process($schema, ['additional' => true]); // ERROR +``` + + +Deprecations +------------ + +You can deprecate property using the `deprecated([string $message])` method. Deprecation notices are returned by `$processor->getWarnings()`: + +```php +$schema = Expect::structure([ + 'old' => Expect::int()->deprecated('The item %path% is deprecated'), +]); + +$processor->process($schema, ['old' => 1]); // OK +$processor->getWarnings(); // ["The item 'old' is deprecated"] +``` + + +Ranges: min() max() +------------------- + +Use `min()` and `max()` to limit the number of elements for arrays: + +```php +// array, at least 10 items, maximum 20 items +Expect::array()->min(10)->max(20); +``` + +For strings, limit their length: + +```php +// string, at least 10 characters long, maximum 20 characters +Expect::string()->min(10)->max(20); +``` + +For numbers, limit their value: + +```php +// integer, between 10 and 20 inclusive +Expect::int()->min(10)->max(20); +``` + +Of course, it is possible to mention only `min()`, or only `max()`: + +```php +// string, maximum 20 characters +Expect::string()->max(20); +``` + + +Regular Expressions: pattern() +------------------------------ + +Using `pattern()`, you can specify a regular expression which the **whole** input string must match (i.e. as if it were wrapped in characters `^` a `$`): + +```php +// just 9 digits +Expect::string()->pattern('\d{9}'); +``` + + +Custom Assertions: assert() +--------------------------- + +You can add any other restrictions using `assert(callable $fn)`. + +```php +$countIsEven = fn($v) => count($v) % 2 === 0; + +$schema = Expect::arrayOf('string') + ->assert($countIsEven); // the count must be even + +$processor->process($schema, ['a', 'b']); // OK +$processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not even +``` + +Or + +```php +Expect::string()->assert('is_file'); // the file must exist +``` + +You can add your own description for each assertion. It will be part of the error message. + +```php +$schema = Expect::arrayOf('string') + ->assert($countIsEven, 'Even items in array'); + +$processor->process($schema, ['a', 'b', 'c']); +// Failed assertion "Even items in array" for item with value array. +``` + +The method can be called repeatedly to add multiple constraints. It can be intermixed with calls to `transform()` and `castTo()`. + + +Transformation: transform() +--------------------------- + +Successfully validated data can be modified using a custom function: + +```php +// conversion to uppercase: +Expect::string()->transform(fn(string $s) => strtoupper($s)); +``` + +The method can be called repeatedly to add multiple transformations. It can be intermixed with calls to `assert()` and `castTo()`. The operations will be executed in the order in which they are declared: + +```php +Expect::type('string|int') + ->castTo('string') + ->assert('ctype_lower', 'All characters must be lowercased') + ->transform(fn(string $s) => strtoupper($s)); // conversion to uppercase +``` + +The `transform()` method can both transform and validate the value simultaneously. This is often simpler and less redundant than chaining `transform()` and `assert()`. For this purpose, the function receives a [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object with an `addError()` method, which can be used to add information about validation issues: + +```php +Expect::string() + ->transform(function (string $s, Nette\Schema\Context $context) { + if (!ctype_lower($s)) { + $context->addError('All characters must be lowercased', 'my.case.error'); + return null; + } + + return strtoupper($s); + }); +``` + + +Casting: castTo() +----------------- + +Successfully validated data can be cast: + +```php +Expect::scalar()->castTo('string'); +``` + +In addition to native PHP types, you can also cast to classes. It distinguishes whether it is a simple class without a constructor or a class with a constructor. If the class has no constructor, an instance of it is created and all elements of the structure are written to its properties: + +```php +class Info +{ + public bool $processRefund; + public int $refundAmount; +} + +Expect::structure([ + 'processRefund' => Expect::bool(), + 'refundAmount' => Expect::int(), +])->castTo(Info::class); + +// creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount +``` + +If the class has a constructor, the elements of the structure are passed as named parameters to the constructor: + +```php +class Info +{ + public function __construct( + public bool $processRefund, + public int $refundAmount, + ) { + } +} + +// creates $obj = new Info(processRefund: ..., refundAmount: ...) +``` + +Casting combined with a scalar parameter creates an object and passes the value as the sole parameter to the constructor: + +```php +Expect::string()->castTo(DateTime::class); +// creates new DateTime(...) +``` + + +Normalization: before() +----------------------- + +Prior to the validation itself, the data can be normalized using the method `before()`. As an example, let's have an element that must be an array of strings (eg `['a', 'b', 'c']`), but receives input in the form of a string `a b c`: + +```php +$explode = fn($v) => explode(' ', $v); + +$schema = Expect::arrayOf('string') + ->before($explode); + +$normalized = $processor->process($schema, 'a b c'); +// OK, returns ['a', 'b', 'c'] +``` + + +Mapping to Objects: from() +-------------------------- + +You can generate structure schema from the class. Example: + +```php +class Config +{ + /** @var string */ + public $name; + /** @var string|null */ + public $password; + /** @var bool */ + public $admin = false; +} + +$schema = Expect::from(new Config); + +$data = [ + 'name' => 'jeff', +]; + +$normalized = $processor->process($schema, $data); +// $normalized instanceof Config +// $normalized = {'name' => 'jeff', 'password' => null, 'admin' => false} +``` + +If you are using PHP 7.4 or higher, you can use native types: + +```php +class Config +{ + public string $name; + public ?string $password; + public bool $admin = false; +} + +$schema = Expect::from(new Config); +``` + +Anonymous classes are also supported: + +```php +$schema = Expect::from(new class { + public string $name; + public ?string $password; + public bool $admin = false; +}); +``` + +Because the information obtained from the class definition may not be sufficient, you can add a custom schema for the elements with the second parameter: + +```php +$schema = Expect::from(new Config, [ + 'name' => Expect::string()->pattern('\w:.*'), +]); +``` diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Context.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Context.php new file mode 100644 index 0000000..0f51265 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Context.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + + +final class Context +{ + public bool $skipDefaults = false; + + /** @var string[] */ + public array $path = []; + + public bool $isKey = false; + + /** @var Message[] */ + public array $errors = []; + + /** @var Message[] */ + public array $warnings = []; + + /** @var array[] */ + public array $dynamics = []; + + + public function addError(string $message, string $code, array $variables = []): Message + { + $variables['isKey'] = $this->isKey; + return $this->errors[] = new Message($message, $code, $this->path, $variables); + } + + + public function addWarning(string $message, string $code, array $variables = []): Message + { + return $this->warnings[] = new Message($message, $code, $this->path, $variables); + } + + + /** @return \Closure(): bool */ + public function createChecker(): \Closure + { + $count = count($this->errors); + return fn(): bool => $count === count($this->errors); + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/DynamicParameter.php b/php/libraries/composer/vendor/nette/schema/src/Schema/DynamicParameter.php new file mode 100644 index 0000000..8dd6105 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/DynamicParameter.php @@ -0,0 +1,15 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + + +interface DynamicParameter +{ +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/AnyOf.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/AnyOf.php new file mode 100644 index 0000000..6c9d0ce --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/AnyOf.php @@ -0,0 +1,147 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema\Elements; + +use Nette; +use Nette\Schema\Context; +use Nette\Schema\Helpers; +use Nette\Schema\Schema; + + +final class AnyOf implements Schema +{ + use Base; + + private array $set; + + + public function __construct(mixed ...$set) + { + if (!$set) { + throw new Nette\InvalidStateException('The enumeration must not be empty.'); + } + + $this->set = $set; + } + + + public function firstIsDefault(): self + { + $this->default = $this->set[0]; + return $this; + } + + + public function nullable(): self + { + $this->set[] = null; + return $this; + } + + + public function dynamic(): self + { + $this->set[] = new Type(Nette\Schema\DynamicParameter::class); + return $this; + } + + + /********************* processing ****************d*g**/ + + + public function normalize(mixed $value, Context $context): mixed + { + return $this->doNormalize($value, $context); + } + + + public function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + return $value; + } + + return Helpers::merge($value, $base); + } + + + public function complete(mixed $value, Context $context): mixed + { + $isOk = $context->createChecker(); + $value = $this->findAlternative($value, $context); + $isOk() && $value = $this->doTransform($value, $context); + return $isOk() ? $value : null; + } + + + private function findAlternative(mixed $value, Context $context): mixed + { + $expecteds = $innerErrors = []; + foreach ($this->set as $item) { + if ($item instanceof Schema) { + $dolly = new Context; + $dolly->path = $context->path; + $res = $item->complete($item->normalize($value, $dolly), $dolly); + if (!$dolly->errors) { + $context->warnings = array_merge($context->warnings, $dolly->warnings); + return $res; + } + + foreach ($dolly->errors as $error) { + if ($error->path !== $context->path || empty($error->variables['expected'])) { + $innerErrors[] = $error; + } else { + $expecteds[] = $error->variables['expected']; + } + } + } else { + if ($item === $value) { + return $value; + } + + $expecteds[] = Nette\Schema\Helpers::formatValue($item); + } + } + + if ($innerErrors) { + $context->errors = array_merge($context->errors, $innerErrors); + } else { + $context->addError( + 'The %label% %path% expects to be %expected%, %value% given.', + Nette\Schema\Message::TypeMismatch, + [ + 'value' => $value, + 'expected' => implode('|', array_unique($expecteds)), + ], + ); + } + + return null; + } + + + public function completeDefault(Context $context): mixed + { + if ($this->required) { + $context->addError( + 'The mandatory item %path% is missing.', + Nette\Schema\Message::MissingItem, + ); + return null; + } + + if ($this->default instanceof Schema) { + return $this->default->completeDefault($context); + } + + return $this->default; + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Base.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Base.php new file mode 100644 index 0000000..1dfda8a --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Base.php @@ -0,0 +1,162 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema\Elements; + +use Nette; +use Nette\Schema\Context; +use Nette\Schema\Helpers; + + +/** + * @internal + */ +trait Base +{ + private bool $required = false; + private mixed $default = null; + + /** @var ?callable */ + private $before; + + /** @var callable[] */ + private array $transforms = []; + private ?string $deprecated = null; + + + public function default(mixed $value): self + { + $this->default = $value; + return $this; + } + + + public function required(bool $state = true): self + { + $this->required = $state; + return $this; + } + + + public function before(callable $handler): self + { + $this->before = $handler; + return $this; + } + + + public function castTo(string $type): self + { + return $this->transform(Helpers::getCastStrategy($type)); + } + + + public function transform(callable $handler): self + { + $this->transforms[] = $handler; + return $this; + } + + + public function assert(callable $handler, ?string $description = null): self + { + $expected = $description ?: (is_string($handler) ? "$handler()" : '#' . count($this->transforms)); + return $this->transform(function ($value, Context $context) use ($handler, $description, $expected) { + if ($handler($value)) { + return $value; + } + $context->addError( + 'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.', + Nette\Schema\Message::FailedAssertion, + ['value' => $value, 'assertion' => $expected], + ); + }); + } + + + /** Marks as deprecated */ + public function deprecated(string $message = 'The item %path% is deprecated.'): self + { + $this->deprecated = $message; + return $this; + } + + + public function completeDefault(Context $context): mixed + { + if ($this->required) { + $context->addError( + 'The mandatory item %path% is missing.', + Nette\Schema\Message::MissingItem, + ); + return null; + } + + return $this->default; + } + + + public function doNormalize(mixed $value, Context $context): mixed + { + if ($this->before) { + $value = ($this->before)($value); + } + + return $value; + } + + + private function doDeprecation(Context $context): void + { + if ($this->deprecated !== null) { + $context->addWarning( + $this->deprecated, + Nette\Schema\Message::Deprecated, + ); + } + } + + + private function doTransform(mixed $value, Context $context): mixed + { + $isOk = $context->createChecker(); + foreach ($this->transforms as $handler) { + $value = $handler($value, $context); + if (!$isOk()) { + return null; + } + } + return $value; + } + + + /** @deprecated use Nette\Schema\Validators::validateType() */ + private function doValidate(mixed $value, string $expected, Context $context): bool + { + $isOk = $context->createChecker(); + Helpers::validateType($value, $expected, $context); + return $isOk(); + } + + + /** @deprecated use Nette\Schema\Validators::validateRange() */ + private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool + { + $isOk = $context->createChecker(); + Helpers::validateRange($value, $range, $context, $types); + return $isOk(); + } + + + /** @deprecated use doTransform() */ + private function doFinalize(mixed $value, Context $context): mixed + { + return $this->doTransform($value, $context); + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Structure.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Structure.php new file mode 100644 index 0000000..56f5ffe --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Structure.php @@ -0,0 +1,200 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema\Elements; + +use Nette; +use Nette\Schema\Context; +use Nette\Schema\Helpers; +use Nette\Schema\Schema; + + +final class Structure implements Schema +{ + use Base; + + /** @var Schema[] */ + private array $items; + + /** for array|list */ + private ?Schema $otherItems = null; + + /** @var array{?int, ?int} */ + private array $range = [null, null]; + private bool $skipDefaults = false; + + + /** + * @param Schema[] $items + */ + public function __construct(array $items) + { + (function (Schema ...$items) {})(...array_values($items)); + $this->items = $items; + $this->castTo('object'); + $this->required = true; + } + + + public function default(mixed $value): self + { + throw new Nette\InvalidStateException('Structure cannot have default value.'); + } + + + public function min(?int $min): self + { + $this->range[0] = $min; + return $this; + } + + + public function max(?int $max): self + { + $this->range[1] = $max; + return $this; + } + + + public function otherItems(string|Schema $type = 'mixed'): self + { + $this->otherItems = $type instanceof Schema ? $type : new Type($type); + return $this; + } + + + public function skipDefaults(bool $state = true): self + { + $this->skipDefaults = $state; + return $this; + } + + + /********************* processing ****************d*g**/ + + + public function normalize(mixed $value, Context $context): mixed + { + if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) { + unset($value[Helpers::PreventMerging]); + } + + $value = $this->doNormalize($value, $context); + if (is_object($value)) { + $value = (array) $value; + } + + if (is_array($value)) { + foreach ($value as $key => $val) { + $itemSchema = $this->items[$key] ?? $this->otherItems; + if ($itemSchema) { + $context->path[] = $key; + $value[$key] = $itemSchema->normalize($val, $context); + array_pop($context->path); + } + } + + if ($prevent) { + $value[Helpers::PreventMerging] = true; + } + } + + return $value; + } + + + public function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + $base = null; + } + + if (is_array($value) && is_array($base)) { + $index = 0; + foreach ($value as $key => $val) { + if ($key === $index) { + $base[] = $val; + $index++; + } elseif (array_key_exists($key, $base)) { + $itemSchema = $this->items[$key] ?? $this->otherItems; + $base[$key] = $itemSchema + ? $itemSchema->merge($val, $base[$key]) + : Helpers::merge($val, $base[$key]); + } else { + $base[$key] = $val; + } + } + + return $base; + } + + return Helpers::merge($value, $base); + } + + + public function complete(mixed $value, Context $context): mixed + { + if ($value === null) { + $value = []; // is unable to distinguish null from array in NEON + } + + $this->doDeprecation($context); + + $isOk = $context->createChecker(); + Helpers::validateType($value, 'array', $context); + $isOk() && Helpers::validateRange($value, $this->range, $context); + $isOk() && $this->validateItems($value, $context); + $isOk() && $value = $this->doTransform($value, $context); + return $isOk() ? $value : null; + } + + + private function validateItems(array &$value, Context $context): void + { + $items = $this->items; + if ($extraKeys = array_keys(array_diff_key($value, $items))) { + if ($this->otherItems) { + $items += array_fill_keys($extraKeys, $this->otherItems); + } else { + $keys = array_map('strval', array_keys($items)); + foreach ($extraKeys as $key) { + $hint = Nette\Utils\Helpers::getSuggestion($keys, (string) $key); + $context->addError( + 'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'), + Nette\Schema\Message::UnexpectedItem, + ['hint' => $hint], + )->path[] = $key; + } + } + } + + foreach ($items as $itemKey => $itemVal) { + $context->path[] = $itemKey; + if (array_key_exists($itemKey, $value)) { + $value[$itemKey] = $itemVal->complete($value[$itemKey], $context); + } else { + $default = $itemVal->completeDefault($context); // checks required item + if (!$context->skipDefaults && !$this->skipDefaults) { + $value[$itemKey] = $default; + } + } + + array_pop($context->path); + } + } + + + public function completeDefault(Context $context): mixed + { + return $this->required + ? $this->complete([], $context) + : null; + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Type.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Type.php new file mode 100644 index 0000000..4094442 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Elements/Type.php @@ -0,0 +1,208 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema\Elements; + +use Nette\Schema\Context; +use Nette\Schema\DynamicParameter; +use Nette\Schema\Helpers; +use Nette\Schema\Schema; + + +final class Type implements Schema +{ + use Base; + + private string $type; + private ?Schema $itemsValue = null; + private ?Schema $itemsKey = null; + + /** @var array{?float, ?float} */ + private array $range = [null, null]; + private ?string $pattern = null; + private bool $merge = true; + + + public function __construct(string $type) + { + $defaults = ['list' => [], 'array' => []]; + $this->type = $type; + $this->default = strpos($type, '[]') ? [] : $defaults[$type] ?? null; + } + + + public function nullable(): self + { + $this->type = 'null|' . $this->type; + return $this; + } + + + public function mergeDefaults(bool $state = true): self + { + $this->merge = $state; + return $this; + } + + + public function dynamic(): self + { + $this->type = DynamicParameter::class . '|' . $this->type; + return $this; + } + + + public function min(?float $min): self + { + $this->range[0] = $min; + return $this; + } + + + public function max(?float $max): self + { + $this->range[1] = $max; + return $this; + } + + + /** + * @internal use arrayOf() or listOf() + */ + public function items(string|Schema $valueType = 'mixed', string|Schema $keyType = null): self + { + $this->itemsValue = $valueType instanceof Schema + ? $valueType + : new self($valueType); + $this->itemsKey = $keyType instanceof Schema || $keyType === null + ? $keyType + : new self($keyType); + return $this; + } + + + public function pattern(?string $pattern): self + { + $this->pattern = $pattern; + return $this; + } + + + /********************* processing ****************d*g**/ + + + public function normalize(mixed $value, Context $context): mixed + { + if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) { + unset($value[Helpers::PreventMerging]); + } + + $value = $this->doNormalize($value, $context); + if (is_array($value) && $this->itemsValue) { + $res = []; + foreach ($value as $key => $val) { + $context->path[] = $key; + $context->isKey = true; + $key = $this->itemsKey + ? $this->itemsKey->normalize($key, $context) + : $key; + $context->isKey = false; + $res[$key] = $this->itemsValue->normalize($val, $context); + array_pop($context->path); + } + + $value = $res; + } + + if ($prevent && is_array($value)) { + $value[Helpers::PreventMerging] = true; + } + + return $value; + } + + + public function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + return $value; + } + + if (is_array($value) && is_array($base) && $this->itemsValue) { + $index = 0; + foreach ($value as $key => $val) { + if ($key === $index) { + $base[] = $val; + $index++; + } else { + $base[$key] = array_key_exists($key, $base) + ? $this->itemsValue->merge($val, $base[$key]) + : $val; + } + } + + return $base; + } + + return Helpers::merge($value, $base); + } + + + public function complete(mixed $value, Context $context): mixed + { + $merge = $this->merge; + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + $merge = false; + } + + if ($value === null && is_array($this->default)) { + $value = []; // is unable to distinguish null from array in NEON + } + + $this->doDeprecation($context); + + $isOk = $context->createChecker(); + Helpers::validateType($value, $this->type, $context); + $isOk() && Helpers::validateRange($value, $this->range, $context, $this->type); + $isOk() && $value !== null && $this->pattern !== null && Helpers::validatePattern($value, $this->pattern, $context); + $isOk() && is_array($value) && $this->validateItems($value, $context); + $isOk() && $merge && $value = Helpers::merge($value, $this->default); + $isOk() && $value = $this->doTransform($value, $context); + if (!$isOk()) { + return null; + } + + if ($value instanceof DynamicParameter) { + $expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range)); + $context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path]; + } + return $value; + } + + + private function validateItems(array &$value, Context $context): void + { + if (!$this->itemsValue) { + return; + } + + $res = []; + foreach ($value as $key => $val) { + $context->path[] = $key; + $context->isKey = true; + $key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key; + $context->isKey = false; + $res[$key] = $this->itemsValue->complete($val, $context); + array_pop($context->path); + } + $value = $res; + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Expect.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Expect.php new file mode 100644 index 0000000..38f1c81 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Expect.php @@ -0,0 +1,108 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + +use Nette; +use Nette\Schema\Elements\AnyOf; +use Nette\Schema\Elements\Structure; +use Nette\Schema\Elements\Type; + + +/** + * Schema generator. + * + * @method static Type scalar($default = null) + * @method static Type string($default = null) + * @method static Type int($default = null) + * @method static Type float($default = null) + * @method static Type bool($default = null) + * @method static Type null() + * @method static Type array($default = []) + * @method static Type list($default = []) + * @method static Type mixed($default = null) + * @method static Type email($default = null) + * @method static Type unicode($default = null) + */ +final class Expect +{ + public static function __callStatic(string $name, array $args): Type + { + $type = new Type($name); + if ($args) { + $type->default($args[0]); + } + + return $type; + } + + + public static function type(string $type): Type + { + return new Type($type); + } + + + public static function anyOf(mixed ...$set): AnyOf + { + return new AnyOf(...$set); + } + + + /** + * @param Schema[] $items + */ + public static function structure(array $items): Structure + { + return new Structure($items); + } + + + public static function from(object $object, array $items = []): Structure + { + $ro = new \ReflectionObject($object); + $props = $ro->hasMethod('__construct') + ? $ro->getMethod('__construct')->getParameters() + : $ro->getProperties(); + + foreach ($props as $prop) { + $item = &$items[$prop->getName()]; + if (!$item) { + $type = Helpers::getPropertyType($prop) ?? 'mixed'; + $item = new Type($type); + if ($prop instanceof \ReflectionProperty ? $prop->isInitialized($object) : $prop->isOptional()) { + $def = ($prop instanceof \ReflectionProperty ? $prop->getValue($object) : $prop->getDefaultValue()); + if (is_object($def)) { + $item = static::from($def); + } elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) { + $item->required(); + } else { + $item->default($def); + } + } else { + $item->required(); + } + } + } + + return (new Structure($items))->castTo($ro->getName()); + } + + + public static function arrayOf(string|Schema $valueType, string|Schema $keyType = null): Type + { + return (new Type('array'))->items($valueType, $keyType); + } + + + public static function listOf(string|Schema $type): Type + { + return (new Type('list'))->items($type); + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Helpers.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Helpers.php new file mode 100644 index 0000000..70bf183 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Helpers.php @@ -0,0 +1,183 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + +use Nette; +use Nette\Utils\Reflection; + + +/** + * @internal + */ +final class Helpers +{ + use Nette\StaticClass; + + public const PreventMerging = '_prevent_merging'; + + + /** + * Merges dataset. Left has higher priority than right one. + */ + public static function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[self::PreventMerging])) { + unset($value[self::PreventMerging]); + return $value; + } + + if (is_array($value) && is_array($base)) { + $index = 0; + foreach ($value as $key => $val) { + if ($key === $index) { + $base[] = $val; + $index++; + } else { + $base[$key] = static::merge($val, $base[$key] ?? null); + } + } + + return $base; + + } elseif ($value === null && is_array($base)) { + return $base; + + } else { + return $value; + } + } + + + public static function getPropertyType(\ReflectionProperty|\ReflectionParameter $prop): ?string + { + if ($type = Nette\Utils\Type::fromReflection($prop)) { + return (string) $type; + } elseif ( + ($prop instanceof \ReflectionProperty) + && ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var'))) + ) { + $class = Reflection::getPropertyDeclaringClass($prop); + return preg_replace_callback('#[\w\\\\]+#', fn($m) => Reflection::expandClassName($m[0], $class), $type); + } + + return null; + } + + + /** + * Returns an annotation value. + * @param \ReflectionProperty $ref + */ + public static function parseAnnotation(\Reflector $ref, string $name): ?string + { + if (!Reflection::areCommentsAvailable()) { + throw new Nette\InvalidStateException('You have to enable phpDoc comments in opcode cache.'); + } + + $re = '#[\s*]@' . preg_quote($name, '#') . '(?=\s|$)(?:[ \t]+([^@\s]\S*))?#'; + if ($ref->getDocComment() && preg_match($re, trim($ref->getDocComment(), '/*'), $m)) { + return $m[1] ?? ''; + } + + return null; + } + + + public static function formatValue(mixed $value): string + { + if ($value instanceof DynamicParameter) { + return 'dynamic'; + } elseif (is_object($value)) { + return 'object ' . $value::class; + } elseif (is_string($value)) { + return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'"; + } elseif (is_scalar($value)) { + return var_export($value, return: true); + } else { + return get_debug_type($value); + } + } + + + public static function validateType(mixed $value, string $expected, Context $context): void + { + if (!Nette\Utils\Validators::is($value, $expected)) { + $expected = str_replace(DynamicParameter::class . '|', '', $expected); + $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); + $context->addError( + 'The %label% %path% expects to be %expected%, %value% given.', + Message::TypeMismatch, + ['value' => $value, 'expected' => $expected], + ); + } + } + + + public static function validateRange(mixed $value, array $range, Context $context, string $types = ''): void + { + if (is_array($value) || is_string($value)) { + [$length, $label] = is_array($value) + ? [count($value), 'items'] + : (in_array('unicode', explode('|', $types), true) + ? [Nette\Utils\Strings::length($value), 'characters'] + : [strlen($value), 'bytes']); + + if (!self::isInRange($length, $range)) { + $context->addError( + "The length of %label% %path% expects to be in range %expected%, %length% $label given.", + Message::LengthOutOfRange, + ['value' => $value, 'length' => $length, 'expected' => implode('..', $range)], + ); + } + } elseif ((is_int($value) || is_float($value)) && !self::isInRange($value, $range)) { + $context->addError( + 'The %label% %path% expects to be in range %expected%, %value% given.', + Message::ValueOutOfRange, + ['value' => $value, 'expected' => implode('..', $range)], + ); + } + } + + + public static function isInRange(mixed $value, array $range): bool + { + return ($range[0] === null || $value >= $range[0]) + && ($range[1] === null || $value <= $range[1]); + } + + + public static function validatePattern(string $value, string $pattern, Context $context): void + { + if (!preg_match("\x01^(?:$pattern)$\x01Du", $value)) { + $context->addError( + "The %label% %path% expects to match pattern '%pattern%', %value% given.", + Message::PatternMismatch, + ['value' => $value, 'pattern' => $pattern], + ); + } + } + + + public static function getCastStrategy(string $type): \Closure + { + if (Nette\Utils\Reflection::isBuiltinType($type)) { + return static function ($value) use ($type) { + settype($value, $type); + return $value; + }; + } elseif (method_exists($type, '__construct')) { + return static fn($value) => is_array($value) || $value instanceof \stdClass + ? new $type(...(array) $value) + : new $type($value); + } else { + return static fn($value) => Nette\Utils\Arrays::toObject((array) $value, new $type); + } + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Message.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Message.php new file mode 100644 index 0000000..4e976d0 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Message.php @@ -0,0 +1,98 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + +use Nette; + + +final class Message +{ + /** variables: {value: mixed, expected: string} */ + public const TypeMismatch = 'schema.typeMismatch'; + + /** variables: {value: mixed, expected: string} */ + public const ValueOutOfRange = 'schema.valueOutOfRange'; + + /** variables: {value: mixed, length: int, expected: string} */ + public const LengthOutOfRange = 'schema.lengthOutOfRange'; + + /** variables: {value: string, pattern: string} */ + public const PatternMismatch = 'schema.patternMismatch'; + + /** variables: {value: mixed, assertion: string} */ + public const FailedAssertion = 'schema.failedAssertion'; + + /** no variables */ + public const MissingItem = 'schema.missingItem'; + + /** variables: {hint: string} */ + public const UnexpectedItem = 'schema.unexpectedItem'; + + /** no variables */ + public const Deprecated = 'schema.deprecated'; + + /** @deprecated use Message::TypeMismatch */ + public const TYPE_MISMATCH = self::TypeMismatch; + + /** @deprecated use Message::ValueOutOfRange */ + public const VALUE_OUT_OF_RANGE = self::ValueOutOfRange; + + /** @deprecated use Message::LengthOutOfRange */ + public const LENGTH_OUT_OF_RANGE = self::LengthOutOfRange; + + /** @deprecated use Message::PatternMismatch */ + public const PATTERN_MISMATCH = self::PatternMismatch; + + /** @deprecated use Message::FailedAssertion */ + public const FAILED_ASSERTION = self::FailedAssertion; + + /** @deprecated use Message::MissingItem */ + public const MISSING_ITEM = self::MissingItem; + + /** @deprecated use Message::UnexpectedItem */ + public const UNEXPECTED_ITEM = self::UnexpectedItem; + + /** @deprecated use Message::Deprecated */ + public const DEPRECATED = self::Deprecated; + + public string $message; + public string $code; + + /** @var string[] */ + public array $path; + + /** @var string[] */ + public array $variables; + + + public function __construct(string $message, string $code, array $path, array $variables = []) + { + $this->message = $message; + $this->code = $code; + $this->path = $path; + $this->variables = $variables; + } + + + public function toString(): string + { + $vars = $this->variables; + $vars['label'] = empty($vars['isKey']) ? 'item' : 'key of item'; + $vars['path'] = $this->path + ? "'" . implode("\u{a0}›\u{a0}", $this->path) . "'" + : null; + $vars['value'] = Helpers::formatValue($vars['value'] ?? null); + + return preg_replace_callback('~( ?)%(\w+)%~', function ($m) use ($vars) { + [, $space, $key] = $m; + return $vars[$key] === null ? '' : $space . $vars[$key]; + }, $this->message) ?? throw new Nette\InvalidStateException(preg_last_error_msg()); + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Processor.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Processor.php new file mode 100644 index 0000000..3290ba6 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Processor.php @@ -0,0 +1,96 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + +use Nette; + + +/** + * Schema validator. + */ +final class Processor +{ + public array $onNewContext = []; + private Context $context; + private bool $skipDefaults = false; + + + public function skipDefaults(bool $value = true): void + { + $this->skipDefaults = $value; + } + + + /** + * Normalizes and validates data. Result is a clean completed data. + * @throws ValidationException + */ + public function process(Schema $schema, mixed $data): mixed + { + $this->createContext(); + $data = $schema->normalize($data, $this->context); + $this->throwsErrors(); + $data = $schema->complete($data, $this->context); + $this->throwsErrors(); + return $data; + } + + + /** + * Normalizes and validates and merges multiple data. Result is a clean completed data. + * @throws ValidationException + */ + public function processMultiple(Schema $schema, array $dataset): mixed + { + $this->createContext(); + $flatten = null; + $first = true; + foreach ($dataset as $data) { + $data = $schema->normalize($data, $this->context); + $this->throwsErrors(); + $flatten = $first ? $data : $schema->merge($data, $flatten); + $first = false; + } + + $data = $schema->complete($flatten, $this->context); + $this->throwsErrors(); + return $data; + } + + + /** + * @return string[] + */ + public function getWarnings(): array + { + $res = []; + foreach ($this->context->warnings as $message) { + $res[] = $message->toString(); + } + + return $res; + } + + + private function throwsErrors(): void + { + if ($this->context->errors) { + throw new ValidationException(null, $this->context->errors); + } + } + + + private function createContext(): void + { + $this->context = new Context; + $this->context->skipDefaults = $this->skipDefaults; + Nette\Utils\Arrays::invoke($this->onNewContext, $this->context); + } +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/Schema.php b/php/libraries/composer/vendor/nette/schema/src/Schema/Schema.php new file mode 100644 index 0000000..3ded769 --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/Schema.php @@ -0,0 +1,37 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + + +interface Schema +{ + /** + * Normalization. + * @return mixed + */ + function normalize(mixed $value, Context $context); + + /** + * Merging. + * @return mixed + */ + function merge(mixed $value, mixed $base); + + /** + * Validation and finalization. + * @return mixed + */ + function complete(mixed $value, Context $context); + + /** + * @return mixed + */ + function completeDefault(Context $context); +} diff --git a/php/libraries/composer/vendor/nette/schema/src/Schema/ValidationException.php b/php/libraries/composer/vendor/nette/schema/src/Schema/ValidationException.php new file mode 100644 index 0000000..caae0be --- /dev/null +++ b/php/libraries/composer/vendor/nette/schema/src/Schema/ValidationException.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Schema; + +use Nette; + + +/** + * Validation error. + */ +class ValidationException extends Nette\InvalidStateException +{ + /** @var Message[] */ + private array $messages; + + + /** + * @param Message[] $messages + */ + public function __construct(?string $message, array $messages = []) + { + parent::__construct($message ?: $messages[0]->toString()); + $this->messages = $messages; + } + + + /** + * @return string[] + */ + public function getMessages(): array + { + $res = []; + foreach ($this->messages as $message) { + $res[] = $message->toString(); + } + + return $res; + } + + + /** + * @return Message[] + */ + public function getMessageObjects(): array + { + return $this->messages; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/.phpstorm.meta.php b/php/libraries/composer/vendor/nette/utils/.phpstorm.meta.php new file mode 100644 index 0000000..25851af --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/.phpstorm.meta.php @@ -0,0 +1,13 @@ +<?php + +declare(strict_types=1); + +namespace PHPSTORM_META; + +override(\Nette\Utils\Arrays::get(0), elementType(0)); +override(\Nette\Utils\Arrays::getRef(0), elementType(0)); +override(\Nette\Utils\Arrays::grep(0), type(0)); +override(\Nette\Utils\Arrays::toObject(0), type(1)); + +expectedArguments(\Nette\Utils\Image::resize(), 2, \Nette\Utils\Image::ShrinkOnly, \Nette\Utils\Image::Stretch, \Nette\Utils\Image::OrSmaller, \Nette\Utils\Image::OrBigger, \Nette\Utils\Image::Cover); +expectedArguments(\Nette\Utils\Image::calculateSize(), 4, \Nette\Utils\Image::ShrinkOnly, \Nette\Utils\Image::Stretch, \Nette\Utils\Image::OrSmaller, \Nette\Utils\Image::OrBigger, \Nette\Utils\Image::Cover); diff --git a/php/libraries/composer/vendor/nette/utils/composer.json b/php/libraries/composer/vendor/nette/utils/composer.json new file mode 100644 index 0000000..eaa039e --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/composer.json @@ -0,0 +1,51 @@ +{ + "name": "nette/utils", + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "keywords": ["nette", "images", "json", "password", "validation", "utility", "string", "array", "core", "slugify", "utf-8", "unicode", "paginator", "datetime"], + "homepage": "https://nette.org", + "license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "require": { + "php": ">=8.0 <8.4" + }, + "require-dev": { + "nette/tester": "^2.5", + "tracy/tracy": "^2.9", + "phpstan/phpstan": "^1.0", + "jetbrains/phpstorm-attributes": "dev-master" + }, + "conflict": { + "nette/finder": "<3", + "nette/schema": "<1.2.2" + }, + "suggest": { + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-gd": "to use Image", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" + }, + "autoload": { + "classmap": ["src/"] + }, + "minimum-stability": "dev", + "scripts": { + "phpstan": "phpstan analyse", + "tester": "tester tests -s" + }, + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + } +} diff --git a/php/libraries/composer/vendor/nette/utils/license.md b/php/libraries/composer/vendor/nette/utils/license.md new file mode 100644 index 0000000..cf741bd --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/license.md @@ -0,0 +1,60 @@ +Licenses +======== + +Good news! You may use Nette Framework under the terms of either +the New BSD License or the GNU General Public License (GPL) version 2 or 3. + +The BSD License is recommended for most projects. It is easy to understand and it +places almost no restrictions on what you can do with the framework. If the GPL +fits better to your project, you can use the framework under this license. + +You don't have to notify anyone which license you are using. You can freely +use Nette Framework in commercial projects as long as the copyright header +remains intact. + +Please be advised that the name "Nette Framework" is a protected trademark and its +usage has some limitations. So please do not use word "Nette" in the name of your +project or top-level domain, and choose a name that stands on its own merits. +If your stuff is good, it will not take long to establish a reputation for yourselves. + + +New BSD License +--------------- + +Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of "Nette Framework" nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are +disclaimed. In no event shall the copyright owner or contributors be liable for +any direct, indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused and on +any theory of liability, whether in contract, strict liability, or tort +(including negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + + +GNU General Public License +-------------------------- + +GPL licenses are very very long, so instead of including them here we offer +you URLs with full text: + +- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) +- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) diff --git a/php/libraries/composer/vendor/nette/utils/readme.md b/php/libraries/composer/vendor/nette/utils/readme.md new file mode 100644 index 0000000..530915f --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/readme.md @@ -0,0 +1,56 @@ +Nette Utility Classes +===================== + +[![Downloads this Month](https://img.shields.io/packagist/dm/nette/utils.svg)](https://packagist.org/packages/nette/utils) +[![Tests](https://github.com/nette/utils/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/utils/actions) +[![Coverage Status](https://coveralls.io/repos/github/nette/utils/badge.svg?branch=master)](https://coveralls.io/github/nette/utils?branch=master) +[![Latest Stable Version](https://poser.pugx.org/nette/utils/v/stable)](https://github.com/nette/utils/releases) +[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/utils/blob/master/license.md) + + +Introduction +------------ + +In package nette/utils you will find a set of [useful classes](https://doc.nette.org/utils) for everyday use: + +- [Arrays](https://doc.nette.org/utils/arrays) - manipulate arrays +- [Callback](https://doc.nette.org/utils/callback) - PHP callbacks +- [Date and Time](https://doc.nette.org/utils/datetime) - modify times and dates +- [Filesystem](https://doc.nette.org/utils/filesystem) - copying, renaming, … +- [Finder](https://doc.nette.org/utils/finder) - finds files and directories +- [Helper Functions](https://doc.nette.org/utils/helpers) +- [HTML elements](https://doc.nette.org/utils/html-elements) - generate HTML +- [Images](https://doc.nette.org/utils/images) - crop, resize, rotate images +- [JSON](https://doc.nette.org/utils/json) - encoding and decoding +- [Generating Random Strings](https://doc.nette.org/utils/random) +- [Paginator](https://doc.nette.org/utils/paginator) - pagination math +- [PHP Reflection](https://doc.nette.org/utils/reflection) +- [Strings](https://doc.nette.org/utils/strings) - useful text functions +- [SmartObject](https://doc.nette.org/utils/smartobject) - PHP object enhancements +- [Validation](https://doc.nette.org/utils/validators) - validate inputs +- [Type](https://doc.nette.org/utils/type) - PHP data type + + +Installation +------------ + +The recommended way to install is via Composer: + +``` +composer require nette/utils +``` + +- Nette Utils 4.0 is compatible with PHP 8.0 to 8.3 +- Nette Utils 3.2 is compatible with PHP 7.2 to 8.3 +- Nette Utils 3.1 is compatible with PHP 7.1 to 8.0 +- Nette Utils 3.0 is compatible with PHP 7.1 to 8.0 +- Nette Utils 2.5 is compatible with PHP 5.6 to 8.0 + +[Support Me](https://github.com/sponsors/dg) +-------------------------------------------- + +Do you like Nette Utils? Are you looking forward to the new features? + +[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) + +Thank you! diff --git a/php/libraries/composer/vendor/nette/utils/src/HtmlStringable.php b/php/libraries/composer/vendor/nette/utils/src/HtmlStringable.php new file mode 100644 index 0000000..d749d4e --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/HtmlStringable.php @@ -0,0 +1,22 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette; + + +interface HtmlStringable +{ + /** + * Returns string in HTML format + */ + function __toString(): string; +} + + +interface_exists(Utils\IHtmlString::class); diff --git a/php/libraries/composer/vendor/nette/utils/src/Iterators/CachingIterator.php b/php/libraries/composer/vendor/nette/utils/src/Iterators/CachingIterator.php new file mode 100644 index 0000000..18b1397 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Iterators/CachingIterator.php @@ -0,0 +1,164 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Iterators; + +use Nette; + + +/** + * Smarter caching iterator. + * + * @property-read bool $first + * @property-read bool $last + * @property-read bool $empty + * @property-read bool $odd + * @property-read bool $even + * @property-read int $counter + * @property-read mixed $nextKey + * @property-read mixed $nextValue + */ +class CachingIterator extends \CachingIterator implements \Countable +{ + use Nette\SmartObject; + + private int $counter = 0; + + + public function __construct($iterator) + { + if (is_array($iterator) || $iterator instanceof \stdClass) { + $iterator = new \ArrayIterator($iterator); + + } elseif ($iterator instanceof \IteratorAggregate) { + do { + $iterator = $iterator->getIterator(); + } while ($iterator instanceof \IteratorAggregate); + + assert($iterator instanceof \Iterator); + + } elseif ($iterator instanceof \Iterator) { + } elseif ($iterator instanceof \Traversable) { + $iterator = new \IteratorIterator($iterator); + } else { + throw new Nette\InvalidArgumentException(sprintf('Invalid argument passed to %s; array or Traversable expected, %s given.', self::class, get_debug_type($iterator))); + } + + parent::__construct($iterator, 0); + } + + + /** + * Is the current element the first one? + */ + public function isFirst(?int $gridWidth = null): bool + { + return $this->counter === 1 || ($gridWidth && $this->counter !== 0 && (($this->counter - 1) % $gridWidth) === 0); + } + + + /** + * Is the current element the last one? + */ + public function isLast(?int $gridWidth = null): bool + { + return !$this->hasNext() || ($gridWidth && ($this->counter % $gridWidth) === 0); + } + + + /** + * Is the iterator empty? + */ + public function isEmpty(): bool + { + return $this->counter === 0; + } + + + /** + * Is the counter odd? + */ + public function isOdd(): bool + { + return $this->counter % 2 === 1; + } + + + /** + * Is the counter even? + */ + public function isEven(): bool + { + return $this->counter % 2 === 0; + } + + + /** + * Returns the counter. + */ + public function getCounter(): int + { + return $this->counter; + } + + + /** + * Returns the count of elements. + */ + public function count(): int + { + $inner = $this->getInnerIterator(); + if ($inner instanceof \Countable) { + return $inner->count(); + + } else { + throw new Nette\NotSupportedException('Iterator is not countable.'); + } + } + + + /** + * Forwards to the next element. + */ + public function next(): void + { + parent::next(); + if (parent::valid()) { + $this->counter++; + } + } + + + /** + * Rewinds the Iterator. + */ + public function rewind(): void + { + parent::rewind(); + $this->counter = parent::valid() ? 1 : 0; + } + + + /** + * Returns the next key. + */ + public function getNextKey(): mixed + { + return $this->getInnerIterator()->key(); + } + + + /** + * Returns the next element. + */ + public function getNextValue(): mixed + { + return $this->getInnerIterator()->current(); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Iterators/Mapper.php b/php/libraries/composer/vendor/nette/utils/src/Iterators/Mapper.php new file mode 100644 index 0000000..87823ba --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Iterators/Mapper.php @@ -0,0 +1,34 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Iterators; + + + +/** + * Applies the callback to the elements of the inner iterator. + */ +class Mapper extends \IteratorIterator +{ + /** @var callable */ + private $callback; + + + public function __construct(\Traversable $iterator, callable $callback) + { + parent::__construct($iterator); + $this->callback = $callback; + } + + + public function current(): mixed + { + return ($this->callback)(parent::current(), parent::key()); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/SmartObject.php b/php/libraries/composer/vendor/nette/utils/src/SmartObject.php new file mode 100644 index 0000000..3b2203f --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/SmartObject.php @@ -0,0 +1,140 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette; + +use Nette\Utils\ObjectHelpers; + + +/** + * Strict class for better experience. + * - 'did you mean' hints + * - access to undeclared members throws exceptions + * - support for @property annotations + * - support for calling event handlers stored in $onEvent via onEvent() + */ +trait SmartObject +{ + /** + * @return mixed + * @throws MemberAccessException + */ + public function __call(string $name, array $args) + { + $class = static::class; + + if (ObjectHelpers::hasProperty($class, $name) === 'event') { // calling event handlers + $handlers = $this->$name ?? null; + if (is_iterable($handlers)) { + foreach ($handlers as $handler) { + $handler(...$args); + } + } elseif ($handlers !== null) { + throw new UnexpectedValueException("Property $class::$$name must be iterable or null, " . get_debug_type($handlers) . ' given.'); + } + + return null; + } + + ObjectHelpers::strictCall($class, $name); + } + + + /** + * @throws MemberAccessException + */ + public static function __callStatic(string $name, array $args) + { + ObjectHelpers::strictStaticCall(static::class, $name); + } + + + /** + * @return mixed + * @throws MemberAccessException if the property is not defined. + */ + public function &__get(string $name) + { + $class = static::class; + + if ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { // property getter + if (!($prop & 0b0001)) { + throw new MemberAccessException("Cannot read a write-only property $class::\$$name."); + } + + $m = ($prop & 0b0010 ? 'get' : 'is') . ucfirst($name); + if ($prop & 0b10000) { + $trace = debug_backtrace(0, 1)[0]; // suppose this method is called from __call() + $loc = isset($trace['file'], $trace['line']) + ? " in $trace[file] on line $trace[line]" + : ''; + trigger_error("Property $class::\$$name is deprecated, use $class::$m() method$loc.", E_USER_DEPRECATED); + } + + if ($prop & 0b0100) { // return by reference + return $this->$m(); + } else { + $val = $this->$m(); + return $val; + } + } else { + ObjectHelpers::strictGet($class, $name); + } + } + + + /** + * @throws MemberAccessException if the property is not defined or is read-only + */ + public function __set(string $name, mixed $value): void + { + $class = static::class; + + if (ObjectHelpers::hasProperty($class, $name)) { // unsetted property + $this->$name = $value; + + } elseif ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { // property setter + if (!($prop & 0b1000)) { + throw new MemberAccessException("Cannot write to a read-only property $class::\$$name."); + } + + $m = 'set' . ucfirst($name); + if ($prop & 0b10000) { + $trace = debug_backtrace(0, 1)[0]; // suppose this method is called from __call() + $loc = isset($trace['file'], $trace['line']) + ? " in $trace[file] on line $trace[line]" + : ''; + trigger_error("Property $class::\$$name is deprecated, use $class::$m() method$loc.", E_USER_DEPRECATED); + } + + $this->$m($value); + + } else { + ObjectHelpers::strictSet($class, $name); + } + } + + + /** + * @throws MemberAccessException + */ + public function __unset(string $name): void + { + $class = static::class; + if (!ObjectHelpers::hasProperty($class, $name)) { + throw new MemberAccessException("Cannot unset the property $class::\$$name."); + } + } + + + public function __isset(string $name): bool + { + return isset(ObjectHelpers::getMagicProperties(static::class)[$name]); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/StaticClass.php b/php/libraries/composer/vendor/nette/utils/src/StaticClass.php new file mode 100644 index 0000000..b1d8486 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/StaticClass.php @@ -0,0 +1,34 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette; + + +/** + * Static class. + */ +trait StaticClass +{ + /** + * Class is static and cannot be instantiated. + */ + private function __construct() + { + } + + + /** + * Call to undefined static method. + * @throws MemberAccessException + */ + public static function __callStatic(string $name, array $args): mixed + { + Utils\ObjectHelpers::strictStaticCall(static::class, $name); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Translator.php b/php/libraries/composer/vendor/nette/utils/src/Translator.php new file mode 100644 index 0000000..f973f5f --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Translator.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Localization; + + +/** + * Translator adapter. + */ +interface Translator +{ + /** + * Translates the given string. + */ + function translate(string|\Stringable $message, mixed ...$parameters): string|\Stringable; +} + + +interface_exists(ITranslator::class); diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/ArrayHash.php b/php/libraries/composer/vendor/nette/utils/src/Utils/ArrayHash.php new file mode 100644 index 0000000..349ffe0 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/ArrayHash.php @@ -0,0 +1,106 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Provides objects to work as array. + * @template T + * @implements \IteratorAggregate<array-key, T> + * @implements \ArrayAccess<array-key, T> + */ +class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * Transforms array to ArrayHash. + * @param array<T> $array + */ + public static function from(array $array, bool $recursive = true): static + { + $obj = new static; + foreach ($array as $key => $value) { + $obj->$key = $recursive && is_array($value) + ? static::from($value) + : $value; + } + + return $obj; + } + + + /** + * Returns an iterator over all items. + * @return \Iterator<array-key, T> + */ + public function &getIterator(): \Iterator + { + foreach ((array) $this as $key => $foo) { + yield $key => $this->$key; + } + } + + + /** + * Returns items count. + */ + public function count(): int + { + return count((array) $this); + } + + + /** + * Replaces or appends a item. + * @param array-key $key + * @param T $value + */ + public function offsetSet($key, $value): void + { + if (!is_scalar($key)) { // prevents null + throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', get_debug_type($key))); + } + + $this->$key = $value; + } + + + /** + * Returns a item. + * @param array-key $key + * @return T + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->$key; + } + + + /** + * Determines whether a item exists. + * @param array-key $key + */ + public function offsetExists($key): bool + { + return isset($this->$key); + } + + + /** + * Removes the element from this list. + * @param array-key $key + */ + public function offsetUnset($key): void + { + unset($this->$key); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/ArrayList.php b/php/libraries/composer/vendor/nette/utils/src/Utils/ArrayList.php new file mode 100644 index 0000000..a402f9b --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/ArrayList.php @@ -0,0 +1,136 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Provides the base class for a generic list (items can be accessed by index). + * @template T + * @implements \IteratorAggregate<int, T> + * @implements \ArrayAccess<int, T> + */ +class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate +{ + use Nette\SmartObject; + + private array $list = []; + + + /** + * Transforms array to ArrayList. + * @param list<T> $array + */ + public static function from(array $array): static + { + if (!Arrays::isList($array)) { + throw new Nette\InvalidArgumentException('Array is not valid list.'); + } + + $obj = new static; + $obj->list = $array; + return $obj; + } + + + /** + * Returns an iterator over all items. + * @return \Iterator<int, T> + */ + public function &getIterator(): \Iterator + { + foreach ($this->list as &$item) { + yield $item; + } + } + + + /** + * Returns items count. + */ + public function count(): int + { + return count($this->list); + } + + + /** + * Replaces or appends a item. + * @param int|null $index + * @param T $value + * @throws Nette\OutOfRangeException + */ + public function offsetSet($index, $value): void + { + if ($index === null) { + $this->list[] = $value; + + } elseif (!is_int($index) || $index < 0 || $index >= count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + + } else { + $this->list[$index] = $value; + } + } + + + /** + * Returns a item. + * @param int $index + * @return T + * @throws Nette\OutOfRangeException + */ + public function offsetGet($index): mixed + { + if (!is_int($index) || $index < 0 || $index >= count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } + + return $this->list[$index]; + } + + + /** + * Determines whether a item exists. + * @param int $index + */ + public function offsetExists($index): bool + { + return is_int($index) && $index >= 0 && $index < count($this->list); + } + + + /** + * Removes the element at the specified position in this list. + * @param int $index + * @throws Nette\OutOfRangeException + */ + public function offsetUnset($index): void + { + if (!is_int($index) || $index < 0 || $index >= count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } + + array_splice($this->list, $index, 1); + } + + + /** + * Prepends a item. + * @param T $value + */ + public function prepend(mixed $value): void + { + $first = array_slice($this->list, 0, 1); + $this->offsetSet(0, $value); + array_splice($this->list, 1, 0, $first); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Arrays.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Arrays.php new file mode 100644 index 0000000..c33fb9a --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Arrays.php @@ -0,0 +1,522 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use JetBrains\PhpStorm\Language; +use Nette; +use function is_array, is_int, is_object, count; + + +/** + * Array tools library. + */ +class Arrays +{ + use Nette\StaticClass; + + /** + * Returns item from array. If it does not exist, it throws an exception, unless a default value is set. + * @template T + * @param array<T> $array + * @param array-key|array-key[] $key + * @param ?T $default + * @return ?T + * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided + */ + public static function get(array $array, string|int|array $key, mixed $default = null): mixed + { + foreach (is_array($key) ? $key : [$key] as $k) { + if (is_array($array) && array_key_exists($k, $array)) { + $array = $array[$k]; + } else { + if (func_num_args() < 3) { + throw new Nette\InvalidArgumentException("Missing item '$k'."); + } + + return $default; + } + } + + return $array; + } + + + /** + * Returns reference to array item. If the index does not exist, new one is created with value null. + * @template T + * @param array<T> $array + * @param array-key|array-key[] $key + * @return ?T + * @throws Nette\InvalidArgumentException if traversed item is not an array + */ + public static function &getRef(array &$array, string|int|array $key): mixed + { + foreach (is_array($key) ? $key : [$key] as $k) { + if (is_array($array) || $array === null) { + $array = &$array[$k]; + } else { + throw new Nette\InvalidArgumentException('Traversed item is not an array.'); + } + } + + return $array; + } + + + /** + * Recursively merges two fields. It is useful, for example, for merging tree structures. It behaves as + * the + operator for array, ie. it adds a key/value pair from the second array to the first one and retains + * the value from the first array in the case of a key collision. + * @template T1 + * @template T2 + * @param array<T1> $array1 + * @param array<T2> $array2 + * @return array<T1|T2> + */ + public static function mergeTree(array $array1, array $array2): array + { + $res = $array1 + $array2; + foreach (array_intersect_key($array1, $array2) as $k => $v) { + if (is_array($v) && is_array($array2[$k])) { + $res[$k] = self::mergeTree($v, $array2[$k]); + } + } + + return $res; + } + + + /** + * Returns zero-indexed position of given array key. Returns null if key is not found. + */ + public static function getKeyOffset(array $array, string|int $key): ?int + { + return Helpers::falseToNull(array_search(self::toKey($key), array_keys($array), strict: true)); + } + + + /** + * @deprecated use getKeyOffset() + */ + public static function searchKey(array $array, $key): ?int + { + return self::getKeyOffset($array, $key); + } + + + /** + * Tests an array for the presence of value. + */ + public static function contains(array $array, mixed $value): bool + { + return in_array($value, $array, true); + } + + + /** + * Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * The $predicate has the signature `function (mixed $value, int|string $key, array $array): bool`. + * @template T + * @param array<T> $array + * @return ?T + */ + public static function first(array $array, ?callable $predicate = null, ?callable $else = null): mixed + { + $key = self::firstKey($array, $predicate); + return $key === null + ? ($else ? $else() : null) + : $array[$key]; + } + + + /** + * Returns the last item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * The $predicate has the signature `function (mixed $value, int|string $key, array $array): bool`. + * @template T + * @param array<T> $array + * @return ?T + */ + public static function last(array $array, ?callable $predicate = null, ?callable $else = null): mixed + { + $key = self::lastKey($array, $predicate); + return $key === null + ? ($else ? $else() : null) + : $array[$key]; + } + + + /** + * Returns the key of first item (matching the specified predicate if given) or null if there is no such item. + * The $predicate has the signature `function (mixed $value, int|string $key, array $array): bool`. + */ + public static function firstKey(array $array, ?callable $predicate = null): int|string|null + { + if (!$predicate) { + return array_key_first($array); + } + foreach ($array as $k => $v) { + if ($predicate($v, $k, $array)) { + return $k; + } + } + return null; + } + + + /** + * Returns the key of last item (matching the specified predicate if given) or null if there is no such item. + * The $predicate has the signature `function (mixed $value, int|string $key, array $array): bool`. + */ + public static function lastKey(array $array, ?callable $predicate = null): int|string|null + { + return $predicate + ? self::firstKey(array_reverse($array, preserve_keys: true), $predicate) + : array_key_last($array); + } + + + /** + * Inserts the contents of the $inserted array into the $array immediately after the $key. + * If $key is null (or does not exist), it is inserted at the beginning. + */ + public static function insertBefore(array &$array, string|int|null $key, array $inserted): void + { + $offset = $key === null ? 0 : (int) self::getKeyOffset($array, $key); + $array = array_slice($array, 0, $offset, preserve_keys: true) + + $inserted + + array_slice($array, $offset, count($array), preserve_keys: true); + } + + + /** + * Inserts the contents of the $inserted array into the $array before the $key. + * If $key is null (or does not exist), it is inserted at the end. + */ + public static function insertAfter(array &$array, string|int|null $key, array $inserted): void + { + if ($key === null || ($offset = self::getKeyOffset($array, $key)) === null) { + $offset = count($array) - 1; + } + + $array = array_slice($array, 0, $offset + 1, preserve_keys: true) + + $inserted + + array_slice($array, $offset + 1, count($array), preserve_keys: true); + } + + + /** + * Renames key in array. + */ + public static function renameKey(array &$array, string|int $oldKey, string|int $newKey): bool + { + $offset = self::getKeyOffset($array, $oldKey); + if ($offset === null) { + return false; + } + + $val = &$array[$oldKey]; + $keys = array_keys($array); + $keys[$offset] = $newKey; + $array = array_combine($keys, $array); + $array[$newKey] = &$val; + return true; + } + + + /** + * Returns only those array items, which matches a regular expression $pattern. + * @param string[] $array + * @return string[] + */ + public static function grep( + array $array, + #[Language('RegExp')] + string $pattern, + bool|int $invert = false, + ): array + { + $flags = $invert ? PREG_GREP_INVERT : 0; + return Strings::pcre('preg_grep', [$pattern, $array, $flags]); + } + + + /** + * Transforms multidimensional array to flat array. + */ + public static function flatten(array $array, bool $preserveKeys = false): array + { + $res = []; + $cb = $preserveKeys + ? function ($v, $k) use (&$res): void { $res[$k] = $v; } + : function ($v) use (&$res): void { $res[] = $v; }; + array_walk_recursive($array, $cb); + return $res; + } + + + /** + * Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list. + * @return ($value is list ? true : false) + */ + public static function isList(mixed $value): bool + { + return is_array($value) && (PHP_VERSION_ID < 80100 + ? !$value || array_keys($value) === range(0, count($value) - 1) + : array_is_list($value) + ); + } + + + /** + * Reformats table to associative tree. Path looks like 'field|field[]field->field=field'. + * @param string|string[] $path + */ + public static function associate(array $array, $path): array|\stdClass + { + $parts = is_array($path) + ? $path + : preg_split('#(\[\]|->|=|\|)#', $path, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + + if (!$parts || $parts === ['->'] || $parts[0] === '=' || $parts[0] === '|') { + throw new Nette\InvalidArgumentException("Invalid path '$path'."); + } + + $res = $parts[0] === '->' ? new \stdClass : []; + + foreach ($array as $rowOrig) { + $row = (array) $rowOrig; + $x = &$res; + + for ($i = 0; $i < count($parts); $i++) { + $part = $parts[$i]; + if ($part === '[]') { + $x = &$x[]; + + } elseif ($part === '=') { + if (isset($parts[++$i])) { + $x = $row[$parts[$i]]; + $row = null; + } + } elseif ($part === '->') { + if (isset($parts[++$i])) { + if ($x === null) { + $x = new \stdClass; + } + + $x = &$x->{$row[$parts[$i]]}; + } else { + $row = is_object($rowOrig) ? $rowOrig : (object) $row; + } + } elseif ($part !== '|') { + $x = &$x[(string) $row[$part]]; + } + } + + if ($x === null) { + $x = $row; + } + } + + return $res; + } + + + /** + * Normalizes array to associative array. Replace numeric keys with their values, the new value will be $filling. + */ + public static function normalize(array $array, mixed $filling = null): array + { + $res = []; + foreach ($array as $k => $v) { + $res[is_int($k) ? $v : $k] = is_int($k) ? $filling : $v; + } + + return $res; + } + + + /** + * Returns and removes the value of an item from an array. If it does not exist, it throws an exception, + * or returns $default, if provided. + * @template T + * @param array<T> $array + * @param ?T $default + * @return ?T + * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided + */ + public static function pick(array &$array, string|int $key, mixed $default = null): mixed + { + if (array_key_exists($key, $array)) { + $value = $array[$key]; + unset($array[$key]); + return $value; + + } elseif (func_num_args() < 3) { + throw new Nette\InvalidArgumentException("Missing item '$key'."); + + } else { + return $default; + } + } + + + /** + * Tests whether at least one element in the array passes the test implemented by the provided function, + * which has the signature `function ($value, $key, array $array): bool`. + * @template K + * @template V + * @param iterable<K, V> $array + * @param callable(V, K, ($array is array ? array<K, V> : iterable<K, V>)): bool $predicate + */ + public static function some(iterable $array, callable $predicate): bool + { + foreach ($array as $k => $v) { + if ($predicate($v, $k, $array)) { + return true; + } + } + + return false; + } + + + /** + * Tests whether all elements in the array pass the test implemented by the provided function, + * which has the signature `function ($value, $key, array $array): bool`. + * @template K + * @template V + * @param iterable<K, V> $array + * @param callable(V, K, ($array is array ? array<K, V> : iterable<K, V>)): bool $predicate + */ + public static function every(iterable $array, callable $predicate): bool + { + foreach ($array as $k => $v) { + if (!$predicate($v, $k, $array)) { + return false; + } + } + + return true; + } + + + /** + * Returns a new array containing all key-value pairs matching the given $predicate. + * The callback has the signature `function (mixed $value, int|string $key, array $array): bool`. + * @template K of array-key + * @template V + * @param array<K, V> $array + * @param callable(V, K, array<K, V>): bool $predicate + * @return array<K, V> + */ + public static function filter(array $array, callable $predicate): array + { + $res = []; + foreach ($array as $k => $v) { + if ($predicate($v, $k, $array)) { + $res[$k] = $v; + } + } + return $res; + } + + + /** + * Returns an array containing the original keys and results of applying the given transform function to each element. + * The function has signature `function ($value, $key, array $array): mixed`. + * @template K of array-key + * @template V + * @template R + * @param iterable<K, V> $array + * @param callable(V, K, ($array is array ? array<K, V> : iterable<K, V>)): R $transformer + * @return array<K, R> + */ + public static function map(iterable $array, callable $transformer): array + { + $res = []; + foreach ($array as $k => $v) { + $res[$k] = $transformer($v, $k, $array); + } + + return $res; + } + + + /** + * Invokes all callbacks and returns array of results. + * @param callable[] $callbacks + */ + public static function invoke(iterable $callbacks, ...$args): array + { + $res = []; + foreach ($callbacks as $k => $cb) { + $res[$k] = $cb(...$args); + } + + return $res; + } + + + /** + * Invokes method on every object in an array and returns array of results. + * @param object[] $objects + */ + public static function invokeMethod(iterable $objects, string $method, ...$args): array + { + $res = []; + foreach ($objects as $k => $obj) { + $res[$k] = $obj->$method(...$args); + } + + return $res; + } + + + /** + * Copies the elements of the $array array to the $object object and then returns it. + * @template T of object + * @param T $object + * @return T + */ + public static function toObject(iterable $array, object $object): object + { + foreach ($array as $k => $v) { + $object->$k = $v; + } + + return $object; + } + + + /** + * Converts value to array key. + */ + public static function toKey(mixed $value): int|string + { + return key([$value => null]); + } + + + /** + * Returns copy of the $array where every item is converted to string + * and prefixed by $prefix and suffixed by $suffix. + * @param string[] $array + * @return string[] + */ + public static function wrap(array $array, string $prefix = '', string $suffix = ''): array + { + $res = []; + foreach ($array as $k => $v) { + $res[$k] = $prefix . $v . $suffix; + } + + return $res; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Callback.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Callback.php new file mode 100644 index 0000000..732af96 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Callback.php @@ -0,0 +1,137 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; +use function is_array, is_object, is_string; + + +/** + * PHP callable tools. + */ +final class Callback +{ + use Nette\StaticClass; + + /** + * Invokes internal PHP function with own error handler. + */ + public static function invokeSafe(string $function, array $args, callable $onError): mixed + { + $prev = set_error_handler(function ($severity, $message, $file) use ($onError, &$prev, $function): ?bool { + if ($file === __FILE__) { + $msg = ini_get('html_errors') + ? Html::htmlToText($message) + : $message; + $msg = preg_replace("#^$function\\(.*?\\): #", '', $msg); + if ($onError($msg, $severity) !== false) { + return null; + } + } + + return $prev ? $prev(...func_get_args()) : false; + }); + + try { + return $function(...$args); + } finally { + restore_error_handler(); + } + } + + + /** + * Checks that $callable is valid PHP callback. Otherwise throws exception. If the $syntax is set to true, only verifies + * that $callable has a valid structure to be used as a callback, but does not verify if the class or method actually exists. + * @return callable + * @throws Nette\InvalidArgumentException + */ + public static function check(mixed $callable, bool $syntax = false) + { + if (!is_callable($callable, $syntax)) { + throw new Nette\InvalidArgumentException( + $syntax + ? 'Given value is not a callable type.' + : sprintf("Callback '%s' is not callable.", self::toString($callable)), + ); + } + + return $callable; + } + + + /** + * Converts PHP callback to textual form. Class or method may not exists. + */ + public static function toString(mixed $callable): string + { + if ($callable instanceof \Closure) { + $inner = self::unwrap($callable); + return '{closure' . ($inner instanceof \Closure ? '}' : ' ' . self::toString($inner) . '}'); + } else { + is_callable(is_object($callable) ? [$callable, '__invoke'] : $callable, true, $textual); + return $textual; + } + } + + + /** + * Returns reflection for method or function used in PHP callback. + * @param callable $callable type check is escalated to ReflectionException + * @throws \ReflectionException if callback is not valid + */ + public static function toReflection($callable): \ReflectionMethod|\ReflectionFunction + { + if ($callable instanceof \Closure) { + $callable = self::unwrap($callable); + } + + if (is_string($callable) && str_contains($callable, '::')) { + return new ReflectionMethod($callable); + } elseif (is_array($callable)) { + return new ReflectionMethod($callable[0], $callable[1]); + } elseif (is_object($callable) && !$callable instanceof \Closure) { + return new ReflectionMethod($callable, '__invoke'); + } else { + return new \ReflectionFunction($callable); + } + } + + + /** + * Checks whether PHP callback is function or static method. + */ + public static function isStatic(callable $callable): bool + { + return is_string(is_array($callable) ? $callable[0] : $callable); + } + + + /** + * Unwraps closure created by Closure::fromCallable(). + */ + public static function unwrap(\Closure $closure): callable|array + { + $r = new \ReflectionFunction($closure); + $class = $r->getClosureScopeClass()?->name; + if (str_ends_with($r->name, '}')) { + return $closure; + + } elseif (($obj = $r->getClosureThis()) && $obj::class === $class) { + return [$obj, $r->name]; + + } elseif ($class) { + return [$class, $r->name]; + + } else { + return $r->name; + } + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/DateTime.php b/php/libraries/composer/vendor/nette/utils/src/Utils/DateTime.php new file mode 100644 index 0000000..6ad6520 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/DateTime.php @@ -0,0 +1,140 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * DateTime. + */ +class DateTime extends \DateTime implements \JsonSerializable +{ + use Nette\SmartObject; + + /** minute in seconds */ + public const MINUTE = 60; + + /** hour in seconds */ + public const HOUR = 60 * self::MINUTE; + + /** day in seconds */ + public const DAY = 24 * self::HOUR; + + /** week in seconds */ + public const WEEK = 7 * self::DAY; + + /** average month in seconds */ + public const MONTH = 2_629_800; + + /** average year in seconds */ + public const YEAR = 31_557_600; + + + /** + * Creates a DateTime object from a string, UNIX timestamp, or other DateTimeInterface object. + * @throws \Exception if the date and time are not valid. + */ + public static function from(string|int|\DateTimeInterface|null $time): static + { + if ($time instanceof \DateTimeInterface) { + return new static($time->format('Y-m-d H:i:s.u'), $time->getTimezone()); + + } elseif (is_numeric($time)) { + if ($time <= self::YEAR) { + $time += time(); + } + + return (new static)->setTimestamp((int) $time); + + } else { // textual or null + return new static((string) $time); + } + } + + + /** + * Creates DateTime object. + * @throws Nette\InvalidArgumentException if the date and time are not valid. + */ + public static function fromParts( + int $year, + int $month, + int $day, + int $hour = 0, + int $minute = 0, + float $second = 0.0, + ): static + { + $s = sprintf('%04d-%02d-%02d %02d:%02d:%02.5F', $year, $month, $day, $hour, $minute, $second); + if ( + !checkdate($month, $day, $year) + || $hour < 0 + || $hour > 23 + || $minute < 0 + || $minute > 59 + || $second < 0 + || $second >= 60 + ) { + throw new Nette\InvalidArgumentException("Invalid date '$s'"); + } + + return new static($s); + } + + + /** + * Returns new DateTime object formatted according to the specified format. + */ + public static function createFromFormat( + string $format, + string $time, + string|\DateTimeZone|null $timezone = null, + ): static|false + { + if ($timezone === null) { + $timezone = new \DateTimeZone(date_default_timezone_get()); + + } elseif (is_string($timezone)) { + $timezone = new \DateTimeZone($timezone); + } + + $date = parent::createFromFormat($format, $time, $timezone); + return $date ? static::from($date) : false; + } + + + /** + * Returns JSON representation in ISO 8601 (used by JavaScript). + */ + public function jsonSerialize(): string + { + return $this->format('c'); + } + + + /** + * Returns the date and time in the format 'Y-m-d H:i:s'. + */ + public function __toString(): string + { + return $this->format('Y-m-d H:i:s'); + } + + + /** + * You'd better use: (clone $dt)->modify(...) + */ + public function modifyClone(string $modify = ''): static + { + $dolly = clone $this; + return $modify ? $dolly->modify($modify) : $dolly; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/FileInfo.php b/php/libraries/composer/vendor/nette/utils/src/Utils/FileInfo.php new file mode 100644 index 0000000..fb92d11 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/FileInfo.php @@ -0,0 +1,69 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Represents the file or directory returned by the Finder. + * @internal do not create instances directly + */ +final class FileInfo extends \SplFileInfo +{ + private string $relativePath; + + + public function __construct(string $file, string $relativePath = '') + { + parent::__construct($file); + $this->setInfoClass(static::class); + $this->relativePath = $relativePath; + } + + + /** + * Returns the relative directory path. + */ + public function getRelativePath(): string + { + return $this->relativePath; + } + + + /** + * Returns the relative path including file name. + */ + public function getRelativePathname(): string + { + return ($this->relativePath === '' ? '' : $this->relativePath . DIRECTORY_SEPARATOR) + . $this->getBasename(); + } + + + /** + * Returns the contents of the file. + * @throws Nette\IOException + */ + public function read(): string + { + return FileSystem::read($this->getPathname()); + } + + + /** + * Writes the contents to the file. + * @throws Nette\IOException + */ + public function write(string $content): void + { + FileSystem::write($this->getPathname(), $content); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/FileSystem.php b/php/libraries/composer/vendor/nette/utils/src/Utils/FileSystem.php new file mode 100644 index 0000000..ab9a7e8 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/FileSystem.php @@ -0,0 +1,326 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * File system tool. + */ +final class FileSystem +{ + /** + * Creates a directory if it does not exist, including parent directories. + * @throws Nette\IOException on error occurred + */ + public static function createDir(string $dir, int $mode = 0777): void + { + if (!is_dir($dir) && !@mkdir($dir, $mode, recursive: true) && !is_dir($dir)) { // @ - dir may already exist + throw new Nette\IOException(sprintf( + "Unable to create directory '%s' with mode %s. %s", + self::normalizePath($dir), + decoct($mode), + Helpers::getLastError(), + )); + } + } + + + /** + * Copies a file or an entire directory. Overwrites existing files and directories by default. + * @throws Nette\IOException on error occurred + * @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists + */ + public static function copy(string $origin, string $target, bool $overwrite = true): void + { + if (stream_is_local($origin) && !file_exists($origin)) { + throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin))); + + } elseif (!$overwrite && file_exists($target)) { + throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target))); + + } elseif (is_dir($origin)) { + static::createDir($target); + foreach (new \FilesystemIterator($target) as $item) { + static::delete($item->getPathname()); + } + + foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($origin, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) { + if ($item->isDir()) { + static::createDir($target . '/' . $iterator->getSubPathName()); + } else { + static::copy($item->getPathname(), $target . '/' . $iterator->getSubPathName()); + } + } + } else { + static::createDir(dirname($target)); + if (@stream_copy_to_stream(static::open($origin, 'rb'), static::open($target, 'wb')) === false) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to copy file '%s' to '%s'. %s", + self::normalizePath($origin), + self::normalizePath($target), + Helpers::getLastError(), + )); + } + } + } + + + /** + * Opens file and returns resource. + * @return resource + * @throws Nette\IOException on error occurred + */ + public static function open(string $path, string $mode) + { + $f = @fopen($path, $mode); // @ is escalated to exception + if (!$f) { + throw new Nette\IOException(sprintf( + "Unable to open file '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + return $f; + } + + + /** + * Deletes a file or an entire directory if exists. If the directory is not empty, it deletes its contents first. + * @throws Nette\IOException on error occurred + */ + public static function delete(string $path): void + { + if (is_file($path) || is_link($path)) { + $func = DIRECTORY_SEPARATOR === '\\' && is_dir($path) ? 'rmdir' : 'unlink'; + if (!@$func($path)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to delete '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + } elseif (is_dir($path)) { + foreach (new \FilesystemIterator($path) as $item) { + static::delete($item->getPathname()); + } + + if (!@rmdir($path)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to delete directory '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + } + } + + + /** + * Renames or moves a file or a directory. Overwrites existing files and directories by default. + * @throws Nette\IOException on error occurred + * @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists + */ + public static function rename(string $origin, string $target, bool $overwrite = true): void + { + if (!$overwrite && file_exists($target)) { + throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target))); + + } elseif (!file_exists($origin)) { + throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin))); + + } else { + static::createDir(dirname($target)); + if (realpath($origin) !== realpath($target)) { + static::delete($target); + } + + if (!@rename($origin, $target)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to rename file or directory '%s' to '%s'. %s", + self::normalizePath($origin), + self::normalizePath($target), + Helpers::getLastError(), + )); + } + } + } + + + /** + * Reads the content of a file. + * @throws Nette\IOException on error occurred + */ + public static function read(string $file): string + { + $content = @file_get_contents($file); // @ is escalated to exception + if ($content === false) { + throw new Nette\IOException(sprintf( + "Unable to read file '%s'. %s", + self::normalizePath($file), + Helpers::getLastError(), + )); + } + + return $content; + } + + + /** + * Reads the file content line by line. Because it reads continuously as we iterate over the lines, + * it is possible to read files larger than the available memory. + * @return \Generator<int, string> + * @throws Nette\IOException on error occurred + */ + public static function readLines(string $file, bool $stripNewLines = true): \Generator + { + return (function ($f) use ($file, $stripNewLines) { + $counter = 0; + do { + $line = Callback::invokeSafe('fgets', [$f], fn($error) => throw new Nette\IOException(sprintf( + "Unable to read file '%s'. %s", + self::normalizePath($file), + $error, + ))); + if ($line === false) { + fclose($f); + break; + } + if ($stripNewLines) { + $line = rtrim($line, "\r\n"); + } + + yield $counter++ => $line; + + } while (true); + })(static::open($file, 'r')); + } + + + /** + * Writes the string to a file. + * @throws Nette\IOException on error occurred + */ + public static function write(string $file, string $content, ?int $mode = 0666): void + { + static::createDir(dirname($file)); + if (@file_put_contents($file, $content) === false) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to write file '%s'. %s", + self::normalizePath($file), + Helpers::getLastError(), + )); + } + + if ($mode !== null && !@chmod($file, $mode)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to chmod file '%s' to mode %s. %s", + self::normalizePath($file), + decoct($mode), + Helpers::getLastError(), + )); + } + } + + + /** + * Sets file permissions to `$fileMode` or directory permissions to `$dirMode`. + * Recursively traverses and sets permissions on the entire contents of the directory as well. + * @throws Nette\IOException on error occurred + */ + public static function makeWritable(string $path, int $dirMode = 0777, int $fileMode = 0666): void + { + if (is_file($path)) { + if (!@chmod($path, $fileMode)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to chmod file '%s' to mode %s. %s", + self::normalizePath($path), + decoct($fileMode), + Helpers::getLastError(), + )); + } + } elseif (is_dir($path)) { + foreach (new \FilesystemIterator($path) as $item) { + static::makeWritable($item->getPathname(), $dirMode, $fileMode); + } + + if (!@chmod($path, $dirMode)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to chmod directory '%s' to mode %s. %s", + self::normalizePath($path), + decoct($dirMode), + Helpers::getLastError(), + )); + } + } else { + throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($path))); + } + } + + + /** + * Determines if the path is absolute. + */ + public static function isAbsolute(string $path): bool + { + return (bool) preg_match('#([a-z]:)?[/\\\\]|[a-z][a-z0-9+.-]*://#Ai', $path); + } + + + /** + * Normalizes `..` and `.` and directory separators in path. + */ + public static function normalizePath(string $path): string + { + $parts = $path === '' ? [] : preg_split('~[/\\\\]+~', $path); + $res = []; + foreach ($parts as $part) { + if ($part === '..' && $res && end($res) !== '..' && end($res) !== '') { + array_pop($res); + } elseif ($part !== '.') { + $res[] = $part; + } + } + + return $res === [''] + ? DIRECTORY_SEPARATOR + : implode(DIRECTORY_SEPARATOR, $res); + } + + + /** + * Joins all segments of the path and normalizes the result. + */ + public static function joinPaths(string ...$paths): string + { + return self::normalizePath(implode('/', $paths)); + } + + + /** + * Converts backslashes to slashes. + */ + public static function unixSlashes(string $path): string + { + return strtr($path, '\\', '/'); + } + + + /** + * Converts slashes to platform-specific directory separators. + */ + public static function platformSlashes(string $path): string + { + return DIRECTORY_SEPARATOR === '/' + ? strtr($path, '\\', '/') + : str_replace(':\\\\', '://', strtr($path, '/', '\\')); // protocol:// + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Finder.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Finder.php new file mode 100644 index 0000000..a496528 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Finder.php @@ -0,0 +1,510 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Finder allows searching through directory trees using iterator. + * + * Finder::findFiles('*.php') + * ->size('> 10kB') + * ->from('.') + * ->exclude('temp'); + * + * @implements \IteratorAggregate<string, FileInfo> + */ +class Finder implements \IteratorAggregate +{ + use Nette\SmartObject; + + /** @var array<array{string, string}> */ + private array $find = []; + + /** @var string[] */ + private array $in = []; + + /** @var \Closure[] */ + private array $filters = []; + + /** @var \Closure[] */ + private array $descentFilters = []; + + /** @var array<string|self> */ + private array $appends = []; + private bool $childFirst = false; + + /** @var ?callable */ + private $sort; + private int $maxDepth = -1; + private bool $ignoreUnreadableDirs = true; + + + /** + * Begins search for files and directories matching mask. + */ + public static function find(string|array $masks = ['*']): static + { + $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic + return (new static)->addMask($masks, 'dir')->addMask($masks, 'file'); + } + + + /** + * Begins search for files matching mask. + */ + public static function findFiles(string|array $masks = ['*']): static + { + $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic + return (new static)->addMask($masks, 'file'); + } + + + /** + * Begins search for directories matching mask. + */ + public static function findDirectories(string|array $masks = ['*']): static + { + $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic + return (new static)->addMask($masks, 'dir'); + } + + + /** + * Finds files matching the specified masks. + */ + public function files(string|array $masks = ['*']): static + { + return $this->addMask((array) $masks, 'file'); + } + + + /** + * Finds directories matching the specified masks. + */ + public function directories(string|array $masks = ['*']): static + { + return $this->addMask((array) $masks, 'dir'); + } + + + private function addMask(array $masks, string $mode): static + { + foreach ($masks as $mask) { + $mask = FileSystem::unixSlashes($mask); + if ($mode === 'dir') { + $mask = rtrim($mask, '/'); + } + if ($mask === '' || ($mode === 'file' && str_ends_with($mask, '/'))) { + throw new Nette\InvalidArgumentException("Invalid mask '$mask'"); + } + if (str_starts_with($mask, '**/')) { + $mask = substr($mask, 3); + } + $this->find[] = [$mask, $mode]; + } + return $this; + } + + + /** + * Searches in the given directories. Wildcards are allowed. + */ + public function in(string|array $paths): static + { + $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic + $this->addLocation($paths, ''); + return $this; + } + + + /** + * Searches recursively from the given directories. Wildcards are allowed. + */ + public function from(string|array $paths): static + { + $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic + $this->addLocation($paths, '/**'); + return $this; + } + + + private function addLocation(array $paths, string $ext): void + { + foreach ($paths as $path) { + if ($path === '') { + throw new Nette\InvalidArgumentException("Invalid directory '$path'"); + } + $path = rtrim(FileSystem::unixSlashes($path), '/'); + $this->in[] = $path . $ext; + } + } + + + /** + * Lists directory's contents before the directory itself. By default, this is disabled. + */ + public function childFirst(bool $state = true): static + { + $this->childFirst = $state; + return $this; + } + + + /** + * Ignores unreadable directories. By default, this is enabled. + */ + public function ignoreUnreadableDirs(bool $state = true): static + { + $this->ignoreUnreadableDirs = $state; + return $this; + } + + + /** + * Set a compare function for sorting directory entries. The function will be called to sort entries from the same directory. + * @param callable(FileInfo, FileInfo): int $callback + */ + public function sortBy(callable $callback): static + { + $this->sort = $callback; + return $this; + } + + + /** + * Sorts files in each directory naturally by name. + */ + public function sortByName(): static + { + $this->sort = fn(FileInfo $a, FileInfo $b): int => strnatcmp($a->getBasename(), $b->getBasename()); + return $this; + } + + + /** + * Adds the specified paths or appends a new finder that returns. + */ + public function append(string|array|null $paths = null): static + { + if ($paths === null) { + return $this->appends[] = new static; + } + + $this->appends = array_merge($this->appends, (array) $paths); + return $this; + } + + + /********************* filtering ****************d*g**/ + + + /** + * Skips entries that matches the given masks relative to the ones defined with the in() or from() methods. + */ + public function exclude(string|array $masks): static + { + $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic + foreach ($masks as $mask) { + $mask = FileSystem::unixSlashes($mask); + if (!preg_match('~^/?(\*\*/)?(.+)(/\*\*|/\*|/|)$~D', $mask, $m)) { + throw new Nette\InvalidArgumentException("Invalid mask '$mask'"); + } + $end = $m[3]; + $re = $this->buildPattern($m[2]); + $filter = fn(FileInfo $file): bool => ($end && !$file->isDir()) + || !preg_match($re, FileSystem::unixSlashes($file->getRelativePathname())); + + $this->descentFilter($filter); + if ($end !== '/*') { + $this->filter($filter); + } + } + + return $this; + } + + + /** + * Yields only entries which satisfy the given filter. + * @param callable(FileInfo): bool $callback + */ + public function filter(callable $callback): static + { + $this->filters[] = \Closure::fromCallable($callback); + return $this; + } + + + /** + * It descends only to directories that match the specified filter. + * @param callable(FileInfo): bool $callback + */ + public function descentFilter(callable $callback): static + { + $this->descentFilters[] = \Closure::fromCallable($callback); + return $this; + } + + + /** + * Sets the maximum depth of entries. + */ + public function limitDepth(?int $depth): static + { + $this->maxDepth = $depth ?? -1; + return $this; + } + + + /** + * Restricts the search by size. $operator accepts "[operator] [size] [unit]" example: >=10kB + */ + public function size(string $operator, ?int $size = null): static + { + if (func_num_args() === 1) { // in $operator is predicate + if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?((?:\d*\.)?\d+)\s*(K|M|G|)B?$#Di', $operator, $matches)) { + throw new Nette\InvalidArgumentException('Invalid size predicate format.'); + } + + [, $operator, $size, $unit] = $matches; + $units = ['' => 1, 'k' => 1e3, 'm' => 1e6, 'g' => 1e9]; + $size *= $units[strtolower($unit)]; + $operator = $operator ?: '='; + } + + return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getSize(), $operator, $size)); + } + + + /** + * Restricts the search by modified time. $operator accepts "[operator] [date]" example: >1978-01-23 + */ + public function date(string $operator, string|int|\DateTimeInterface|null $date = null): static + { + if (func_num_args() === 1) { // in $operator is predicate + if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?(.+)$#Di', $operator, $matches)) { + throw new Nette\InvalidArgumentException('Invalid date predicate format.'); + } + + [, $operator, $date] = $matches; + $operator = $operator ?: '='; + } + + $date = DateTime::from($date)->format('U'); + return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getMTime(), $operator, $date)); + } + + + /********************* iterator generator ****************d*g**/ + + + /** + * Returns an array with all found files and directories. + * @return list<FileInfo> + */ + public function collect(): array + { + return iterator_to_array($this->getIterator(), preserve_keys: false); + } + + + /** @return \Generator<string, FileInfo> */ + public function getIterator(): \Generator + { + $plan = $this->buildPlan(); + foreach ($plan as $dir => $searches) { + yield from $this->traverseDir($dir, $searches); + } + + foreach ($this->appends as $item) { + if ($item instanceof self) { + yield from $item->getIterator(); + } else { + $item = FileSystem::platformSlashes($item); + yield $item => new FileInfo($item); + } + } + } + + + /** + * @param array<object{pattern: string, mode: string, recursive: bool}> $searches + * @param string[] $subdirs + * @return \Generator<string, FileInfo> + */ + private function traverseDir(string $dir, array $searches, array $subdirs = []): \Generator + { + if ($this->maxDepth >= 0 && count($subdirs) > $this->maxDepth) { + return; + } elseif (!is_dir($dir)) { + throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($dir, '/\\'))); + } + + try { + $pathNames = new \FilesystemIterator($dir, \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::UNIX_PATHS); + } catch (\UnexpectedValueException $e) { + if ($this->ignoreUnreadableDirs) { + return; + } else { + throw new Nette\InvalidStateException($e->getMessage()); + } + } + + $files = $this->convertToFiles($pathNames, implode('/', $subdirs), FileSystem::isAbsolute($dir)); + + if ($this->sort) { + $files = iterator_to_array($files); + usort($files, $this->sort); + } + + foreach ($files as $file) { + $pathName = $file->getPathname(); + $cache = $subSearch = []; + + if ($file->isDir()) { + foreach ($searches as $search) { + if ($search->recursive && $this->proveFilters($this->descentFilters, $file, $cache)) { + $subSearch[] = $search; + } + } + } + + if ($this->childFirst && $subSearch) { + yield from $this->traverseDir($pathName, $subSearch, array_merge($subdirs, [$file->getBasename()])); + } + + $relativePathname = FileSystem::unixSlashes($file->getRelativePathname()); + foreach ($searches as $search) { + if ( + $file->{'is' . $search->mode}() + && preg_match($search->pattern, $relativePathname) + && $this->proveFilters($this->filters, $file, $cache) + ) { + yield $pathName => $file; + break; + } + } + + if (!$this->childFirst && $subSearch) { + yield from $this->traverseDir($pathName, $subSearch, array_merge($subdirs, [$file->getBasename()])); + } + } + } + + + private function convertToFiles(iterable $pathNames, string $relativePath, bool $absolute): \Generator + { + foreach ($pathNames as $pathName) { + if (!$absolute) { + $pathName = preg_replace('~\.?/~A', '', $pathName); + } + $pathName = FileSystem::platformSlashes($pathName); + yield new FileInfo($pathName, $relativePath); + } + } + + + private function proveFilters(array $filters, FileInfo $file, array &$cache): bool + { + foreach ($filters as $filter) { + $res = &$cache[spl_object_id($filter)]; + $res ??= $filter($file); + if (!$res) { + return false; + } + } + + return true; + } + + + /** @return array<string, array<object{pattern: string, mode: string, recursive: bool}>> */ + private function buildPlan(): array + { + $plan = $dirCache = []; + foreach ($this->find as [$mask, $mode]) { + $splits = []; + if (FileSystem::isAbsolute($mask)) { + if ($this->in) { + throw new Nette\InvalidStateException("You cannot combine the absolute path in the mask '$mask' and the directory to search '{$this->in[0]}'."); + } + $splits[] = self::splitRecursivePart($mask); + } else { + foreach ($this->in ?: ['.'] as $in) { + $in = strtr($in, ['[' => '[[]', ']' => '[]]']); // in path, do not treat [ and ] as a pattern by glob() + $splits[] = self::splitRecursivePart($in . '/' . $mask); + } + } + + foreach ($splits as [$base, $rest, $recursive]) { + $base = $base === '' ? '.' : $base; + $dirs = $dirCache[$base] ??= strpbrk($base, '*?[') + ? glob($base, GLOB_NOSORT | GLOB_ONLYDIR | GLOB_NOESCAPE) + : [strtr($base, ['[[]' => '[', '[]]' => ']'])]; // unescape [ and ] + + if (!$dirs) { + throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($base, '/\\'))); + } + + $search = (object) ['pattern' => $this->buildPattern($rest), 'mode' => $mode, 'recursive' => $recursive]; + foreach ($dirs as $dir) { + $plan[$dir][] = $search; + } + } + } + + return $plan; + } + + + /** + * Since glob() does not know ** wildcard, we divide the path into a part for glob and a part for manual traversal. + */ + private static function splitRecursivePart(string $path): array + { + $a = strrpos($path, '/'); + $parts = preg_split('~(?<=^|/)\*\*($|/)~', substr($path, 0, $a + 1), 2); + return isset($parts[1]) + ? [$parts[0], $parts[1] . substr($path, $a + 1), true] + : [$parts[0], substr($path, $a + 1), false]; + } + + + /** + * Converts wildcards to regular expression. + */ + private function buildPattern(string $mask): string + { + if ($mask === '*') { + return '##'; + } elseif (str_starts_with($mask, './')) { + $anchor = '^'; + $mask = substr($mask, 2); + } else { + $anchor = '(?:^|/)'; + } + + $pattern = strtr( + preg_quote($mask, '#'), + [ + '\*\*/' => '(.+/)?', + '\*' => '[^/]*', + '\?' => '[^/]', + '\[\!' => '[^', + '\[' => '[', + '\]' => ']', + '\-' => '-', + ], + ); + return '#' . $anchor . $pattern . '$#D' . (defined('PHP_WINDOWS_VERSION_BUILD') ? 'i' : ''); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Floats.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Floats.php new file mode 100644 index 0000000..cc2781d --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Floats.php @@ -0,0 +1,107 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Floating-point numbers comparison. + */ +class Floats +{ + use Nette\StaticClass; + + private const Epsilon = 1e-10; + + + public static function isZero(float $value): bool + { + return abs($value) < self::Epsilon; + } + + + public static function isInteger(float $value): bool + { + return abs(round($value) - $value) < self::Epsilon; + } + + + /** + * Compare two floats. If $a < $b it returns -1, if they are equal it returns 0 and if $a > $b it returns 1 + * @throws \LogicException if one of parameters is NAN + */ + public static function compare(float $a, float $b): int + { + if (is_nan($a) || is_nan($b)) { + throw new \LogicException('Trying to compare NAN'); + + } elseif (!is_finite($a) && !is_finite($b) && $a === $b) { + return 0; + } + + $diff = abs($a - $b); + if (($diff < self::Epsilon || ($diff / max(abs($a), abs($b)) < self::Epsilon))) { + return 0; + } + + return $a < $b ? -1 : 1; + } + + + /** + * Returns true if $a = $b + * @throws \LogicException if one of parameters is NAN + */ + public static function areEqual(float $a, float $b): bool + { + return self::compare($a, $b) === 0; + } + + + /** + * Returns true if $a < $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isLessThan(float $a, float $b): bool + { + return self::compare($a, $b) < 0; + } + + + /** + * Returns true if $a <= $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isLessThanOrEqualTo(float $a, float $b): bool + { + return self::compare($a, $b) <= 0; + } + + + /** + * Returns true if $a > $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isGreaterThan(float $a, float $b): bool + { + return self::compare($a, $b) > 0; + } + + + /** + * Returns true if $a >= $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isGreaterThanOrEqualTo(float $a, float $b): bool + { + return self::compare($a, $b) >= 0; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Helpers.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Helpers.php new file mode 100644 index 0000000..b3586c1 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Helpers.php @@ -0,0 +1,104 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +class Helpers +{ + /** + * Executes a callback and returns the captured output as a string. + */ + public static function capture(callable $func): string + { + ob_start(function () {}); + try { + $func(); + return ob_get_clean(); + } catch (\Throwable $e) { + ob_end_clean(); + throw $e; + } + } + + + /** + * Returns the last occurred PHP error or an empty string if no error occurred. Unlike error_get_last(), + * it is nit affected by the PHP directive html_errors and always returns text, not HTML. + */ + public static function getLastError(): string + { + $message = error_get_last()['message'] ?? ''; + $message = ini_get('html_errors') ? Html::htmlToText($message) : $message; + $message = preg_replace('#^\w+\(.*?\): #', '', $message); + return $message; + } + + + /** + * Converts false to null, does not change other values. + */ + public static function falseToNull(mixed $value): mixed + { + return $value === false ? null : $value; + } + + + /** + * Returns value clamped to the inclusive range of min and max. + */ + public static function clamp(int|float $value, int|float $min, int|float $max): int|float + { + if ($min > $max) { + throw new Nette\InvalidArgumentException("Minimum ($min) is not less than maximum ($max)."); + } + + return min(max($value, $min), $max); + } + + + /** + * Looks for a string from possibilities that is most similar to value, but not the same (for 8-bit encoding). + * @param string[] $possibilities + */ + public static function getSuggestion(array $possibilities, string $value): ?string + { + $best = null; + $min = (strlen($value) / 4 + 1) * 10 + .1; + foreach (array_unique($possibilities) as $item) { + if ($item !== $value && ($len = levenshtein($item, $value, 10, 11, 10)) < $min) { + $min = $len; + $best = $item; + } + } + + return $best; + } + + + /** + * Compares two values in the same way that PHP does. Recognizes operators: >, >=, <, <=, =, ==, ===, !=, !==, <> + */ + public static function compare(mixed $left, string $operator, mixed $right): bool + { + return match ($operator) { + '>' => $left > $right, + '>=' => $left >= $right, + '<' => $left < $right, + '<=' => $left <= $right, + '=', '==' => $left == $right, + '===' => $left === $right, + '!=', '<>' => $left != $right, + '!==' => $left !== $right, + default => throw new Nette\InvalidArgumentException("Unknown operator '$operator'"), + }; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Html.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Html.php new file mode 100644 index 0000000..fc0e3ef --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Html.php @@ -0,0 +1,839 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; +use Nette\HtmlStringable; +use function is_array, is_float, is_object, is_string; + + +/** + * HTML helper. + * + * @property string|null $accept + * @property string|null $accesskey + * @property string|null $action + * @property string|null $align + * @property string|null $allow + * @property string|null $alt + * @property bool|null $async + * @property string|null $autocapitalize + * @property string|null $autocomplete + * @property bool|null $autofocus + * @property bool|null $autoplay + * @property string|null $charset + * @property bool|null $checked + * @property string|null $cite + * @property string|null $class + * @property int|null $cols + * @property int|null $colspan + * @property string|null $content + * @property bool|null $contenteditable + * @property bool|null $controls + * @property string|null $coords + * @property string|null $crossorigin + * @property string|null $data + * @property string|null $datetime + * @property string|null $decoding + * @property bool|null $default + * @property bool|null $defer + * @property string|null $dir + * @property string|null $dirname + * @property bool|null $disabled + * @property bool|null $download + * @property string|null $draggable + * @property string|null $dropzone + * @property string|null $enctype + * @property string|null $for + * @property string|null $form + * @property string|null $formaction + * @property string|null $formenctype + * @property string|null $formmethod + * @property bool|null $formnovalidate + * @property string|null $formtarget + * @property string|null $headers + * @property int|null $height + * @property bool|null $hidden + * @property float|null $high + * @property string|null $href + * @property string|null $hreflang + * @property string|null $id + * @property string|null $integrity + * @property string|null $inputmode + * @property bool|null $ismap + * @property string|null $itemprop + * @property string|null $kind + * @property string|null $label + * @property string|null $lang + * @property string|null $list + * @property bool|null $loop + * @property float|null $low + * @property float|null $max + * @property int|null $maxlength + * @property int|null $minlength + * @property string|null $media + * @property string|null $method + * @property float|null $min + * @property bool|null $multiple + * @property bool|null $muted + * @property string|null $name + * @property bool|null $novalidate + * @property bool|null $open + * @property float|null $optimum + * @property string|null $pattern + * @property string|null $ping + * @property string|null $placeholder + * @property string|null $poster + * @property string|null $preload + * @property string|null $radiogroup + * @property bool|null $readonly + * @property string|null $rel + * @property bool|null $required + * @property bool|null $reversed + * @property int|null $rows + * @property int|null $rowspan + * @property string|null $sandbox + * @property string|null $scope + * @property bool|null $selected + * @property string|null $shape + * @property int|null $size + * @property string|null $sizes + * @property string|null $slot + * @property int|null $span + * @property string|null $spellcheck + * @property string|null $src + * @property string|null $srcdoc + * @property string|null $srclang + * @property string|null $srcset + * @property int|null $start + * @property float|null $step + * @property string|null $style + * @property int|null $tabindex + * @property string|null $target + * @property string|null $title + * @property string|null $translate + * @property string|null $type + * @property string|null $usemap + * @property string|null $value + * @property int|null $width + * @property string|null $wrap + * + * @method self accept(?string $val) + * @method self accesskey(?string $val, bool $state = null) + * @method self action(?string $val) + * @method self align(?string $val) + * @method self allow(?string $val, bool $state = null) + * @method self alt(?string $val) + * @method self async(?bool $val) + * @method self autocapitalize(?string $val) + * @method self autocomplete(?string $val) + * @method self autofocus(?bool $val) + * @method self autoplay(?bool $val) + * @method self charset(?string $val) + * @method self checked(?bool $val) + * @method self cite(?string $val) + * @method self class(?string $val, bool $state = null) + * @method self cols(?int $val) + * @method self colspan(?int $val) + * @method self content(?string $val) + * @method self contenteditable(?bool $val) + * @method self controls(?bool $val) + * @method self coords(?string $val) + * @method self crossorigin(?string $val) + * @method self datetime(?string $val) + * @method self decoding(?string $val) + * @method self default(?bool $val) + * @method self defer(?bool $val) + * @method self dir(?string $val) + * @method self dirname(?string $val) + * @method self disabled(?bool $val) + * @method self download(?bool $val) + * @method self draggable(?string $val) + * @method self dropzone(?string $val) + * @method self enctype(?string $val) + * @method self for(?string $val) + * @method self form(?string $val) + * @method self formaction(?string $val) + * @method self formenctype(?string $val) + * @method self formmethod(?string $val) + * @method self formnovalidate(?bool $val) + * @method self formtarget(?string $val) + * @method self headers(?string $val, bool $state = null) + * @method self height(?int $val) + * @method self hidden(?bool $val) + * @method self high(?float $val) + * @method self hreflang(?string $val) + * @method self id(?string $val) + * @method self integrity(?string $val) + * @method self inputmode(?string $val) + * @method self ismap(?bool $val) + * @method self itemprop(?string $val) + * @method self kind(?string $val) + * @method self label(?string $val) + * @method self lang(?string $val) + * @method self list(?string $val) + * @method self loop(?bool $val) + * @method self low(?float $val) + * @method self max(?float $val) + * @method self maxlength(?int $val) + * @method self minlength(?int $val) + * @method self media(?string $val) + * @method self method(?string $val) + * @method self min(?float $val) + * @method self multiple(?bool $val) + * @method self muted(?bool $val) + * @method self name(?string $val) + * @method self novalidate(?bool $val) + * @method self open(?bool $val) + * @method self optimum(?float $val) + * @method self pattern(?string $val) + * @method self ping(?string $val, bool $state = null) + * @method self placeholder(?string $val) + * @method self poster(?string $val) + * @method self preload(?string $val) + * @method self radiogroup(?string $val) + * @method self readonly(?bool $val) + * @method self rel(?string $val) + * @method self required(?bool $val) + * @method self reversed(?bool $val) + * @method self rows(?int $val) + * @method self rowspan(?int $val) + * @method self sandbox(?string $val, bool $state = null) + * @method self scope(?string $val) + * @method self selected(?bool $val) + * @method self shape(?string $val) + * @method self size(?int $val) + * @method self sizes(?string $val) + * @method self slot(?string $val) + * @method self span(?int $val) + * @method self spellcheck(?string $val) + * @method self src(?string $val) + * @method self srcdoc(?string $val) + * @method self srclang(?string $val) + * @method self srcset(?string $val) + * @method self start(?int $val) + * @method self step(?float $val) + * @method self style(?string $property, string $val = null) + * @method self tabindex(?int $val) + * @method self target(?string $val) + * @method self title(?string $val) + * @method self translate(?string $val) + * @method self type(?string $val) + * @method self usemap(?string $val) + * @method self value(?string $val) + * @method self width(?int $val) + * @method self wrap(?string $val) + */ +class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringable +{ + use Nette\SmartObject; + + /** @var array<string, mixed> element's attributes */ + public $attrs = []; + + /** void elements */ + public static $emptyElements = [ + 'img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1, + 'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1, + 'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1, + ]; + + /** @var array<int, HtmlStringable|string> nodes */ + protected $children = []; + + /** element's name */ + private string $name = ''; + + private bool $isEmpty = false; + + + /** + * Constructs new HTML element. + * @param array|string $attrs element's attributes or plain text content + */ + public static function el(?string $name = null, array|string|null $attrs = null): static + { + $el = new static; + $parts = explode(' ', (string) $name, 2); + $el->setName($parts[0]); + + if (is_array($attrs)) { + $el->attrs = $attrs; + + } elseif ($attrs !== null) { + $el->setText($attrs); + } + + if (isset($parts[1])) { + foreach (Strings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\2|\s))?#i') as $m) { + $el->attrs[$m[1]] = $m[3] ?? true; + } + } + + return $el; + } + + + /** + * Returns an object representing HTML text. + */ + public static function fromHtml(string $html): static + { + return (new static)->setHtml($html); + } + + + /** + * Returns an object representing plain text. + */ + public static function fromText(string $text): static + { + return (new static)->setText($text); + } + + + /** + * Converts to HTML. + */ + final public function toHtml(): string + { + return $this->render(); + } + + + /** + * Converts to plain text. + */ + final public function toText(): string + { + return $this->getText(); + } + + + /** + * Converts given HTML code to plain text. + */ + public static function htmlToText(string $html): string + { + return html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + } + + + /** + * Changes element's name. + */ + final public function setName(string $name, ?bool $isEmpty = null): static + { + $this->name = $name; + $this->isEmpty = $isEmpty ?? isset(static::$emptyElements[$name]); + return $this; + } + + + /** + * Returns element's name. + */ + final public function getName(): string + { + return $this->name; + } + + + /** + * Is element empty? + */ + final public function isEmpty(): bool + { + return $this->isEmpty; + } + + + /** + * Sets multiple attributes. + */ + public function addAttributes(array $attrs): static + { + $this->attrs = array_merge($this->attrs, $attrs); + return $this; + } + + + /** + * Appends value to element's attribute. + */ + public function appendAttribute(string $name, mixed $value, mixed $option = true): static + { + if (is_array($value)) { + $prev = isset($this->attrs[$name]) ? (array) $this->attrs[$name] : []; + $this->attrs[$name] = $value + $prev; + + } elseif ((string) $value === '') { + $tmp = &$this->attrs[$name]; // appending empty value? -> ignore, but ensure it exists + + } elseif (!isset($this->attrs[$name]) || is_array($this->attrs[$name])) { // needs array + $this->attrs[$name][$value] = $option; + + } else { + $this->attrs[$name] = [$this->attrs[$name] => true, $value => $option]; + } + + return $this; + } + + + /** + * Sets element's attribute. + */ + public function setAttribute(string $name, mixed $value): static + { + $this->attrs[$name] = $value; + return $this; + } + + + /** + * Returns element's attribute. + */ + public function getAttribute(string $name): mixed + { + return $this->attrs[$name] ?? null; + } + + + /** + * Unsets element's attribute. + */ + public function removeAttribute(string $name): static + { + unset($this->attrs[$name]); + return $this; + } + + + /** + * Unsets element's attributes. + */ + public function removeAttributes(array $attributes): static + { + foreach ($attributes as $name) { + unset($this->attrs[$name]); + } + + return $this; + } + + + /** + * Overloaded setter for element's attribute. + */ + final public function __set(string $name, mixed $value): void + { + $this->attrs[$name] = $value; + } + + + /** + * Overloaded getter for element's attribute. + */ + final public function &__get(string $name): mixed + { + return $this->attrs[$name]; + } + + + /** + * Overloaded tester for element's attribute. + */ + final public function __isset(string $name): bool + { + return isset($this->attrs[$name]); + } + + + /** + * Overloaded unsetter for element's attribute. + */ + final public function __unset(string $name): void + { + unset($this->attrs[$name]); + } + + + /** + * Overloaded setter for element's attribute. + */ + final public function __call(string $m, array $args): mixed + { + $p = substr($m, 0, 3); + if ($p === 'get' || $p === 'set' || $p === 'add') { + $m = substr($m, 3); + $m[0] = $m[0] | "\x20"; + if ($p === 'get') { + return $this->attrs[$m] ?? null; + + } elseif ($p === 'add') { + $args[] = true; + } + } + + if (count($args) === 0) { // invalid + + } elseif (count($args) === 1) { // set + $this->attrs[$m] = $args[0]; + + } else { // add + $this->appendAttribute($m, $args[0], $args[1]); + } + + return $this; + } + + + /** + * Special setter for element's attribute. + */ + final public function href(string $path, array $query = []): static + { + if ($query) { + $query = http_build_query($query, '', '&'); + if ($query !== '') { + $path .= '?' . $query; + } + } + + $this->attrs['href'] = $path; + return $this; + } + + + /** + * Setter for data-* attributes. Booleans are converted to 'true' resp. 'false'. + */ + public function data(string $name, mixed $value = null): static + { + if (func_num_args() === 1) { + $this->attrs['data'] = $name; + } else { + $this->attrs["data-$name"] = is_bool($value) + ? json_encode($value) + : $value; + } + + return $this; + } + + + /** + * Sets element's HTML content. + */ + final public function setHtml(mixed $html): static + { + $this->children = [(string) $html]; + return $this; + } + + + /** + * Returns element's HTML content. + */ + final public function getHtml(): string + { + return implode('', $this->children); + } + + + /** + * Sets element's textual content. + */ + final public function setText(mixed $text): static + { + if (!$text instanceof HtmlStringable) { + $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8'); + } + + $this->children = [(string) $text]; + return $this; + } + + + /** + * Returns element's textual content. + */ + final public function getText(): string + { + return self::htmlToText($this->getHtml()); + } + + + /** + * Adds new element's child. + */ + final public function addHtml(mixed $child): static + { + return $this->insert(null, $child); + } + + + /** + * Appends plain-text string to element content. + */ + public function addText(mixed $text): static + { + if (!$text instanceof HtmlStringable) { + $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8'); + } + + return $this->insert(null, $text); + } + + + /** + * Creates and adds a new Html child. + */ + final public function create(string $name, array|string|null $attrs = null): static + { + $this->insert(null, $child = static::el($name, $attrs)); + return $child; + } + + + /** + * Inserts child node. + */ + public function insert(?int $index, HtmlStringable|string $child, bool $replace = false): static + { + $child = $child instanceof self ? $child : (string) $child; + if ($index === null) { // append + $this->children[] = $child; + + } else { // insert or replace + array_splice($this->children, $index, $replace ? 1 : 0, [$child]); + } + + return $this; + } + + + /** + * Inserts (replaces) child node (\ArrayAccess implementation). + * @param int|null $index position or null for appending + * @param Html|string $child Html node or raw HTML string + */ + final public function offsetSet($index, $child): void + { + $this->insert($index, $child, replace: true); + } + + + /** + * Returns child node (\ArrayAccess implementation). + * @param int $index + */ + final public function offsetGet($index): HtmlStringable|string + { + return $this->children[$index]; + } + + + /** + * Exists child node? (\ArrayAccess implementation). + * @param int $index + */ + final public function offsetExists($index): bool + { + return isset($this->children[$index]); + } + + + /** + * Removes child node (\ArrayAccess implementation). + * @param int $index + */ + public function offsetUnset($index): void + { + if (isset($this->children[$index])) { + array_splice($this->children, $index, 1); + } + } + + + /** + * Returns children count. + */ + final public function count(): int + { + return count($this->children); + } + + + /** + * Removes all children. + */ + public function removeChildren(): void + { + $this->children = []; + } + + + /** + * Iterates over elements. + * @return \ArrayIterator<int, HtmlStringable|string> + */ + final public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->children); + } + + + /** + * Returns all children. + */ + final public function getChildren(): array + { + return $this->children; + } + + + /** + * Renders element's start tag, content and end tag. + */ + final public function render(?int $indent = null): string + { + $s = $this->startTag(); + + if (!$this->isEmpty) { + // add content + if ($indent !== null) { + $indent++; + } + + foreach ($this->children as $child) { + if ($child instanceof self) { + $s .= $child->render($indent); + } else { + $s .= $child; + } + } + + // add end tag + $s .= $this->endTag(); + } + + if ($indent !== null) { + return "\n" . str_repeat("\t", $indent - 1) . $s . "\n" . str_repeat("\t", max(0, $indent - 2)); + } + + return $s; + } + + + final public function __toString(): string + { + return $this->render(); + } + + + /** + * Returns element's start tag. + */ + final public function startTag(): string + { + return $this->name + ? '<' . $this->name . $this->attributes() . '>' + : ''; + } + + + /** + * Returns element's end tag. + */ + final public function endTag(): string + { + return $this->name && !$this->isEmpty ? '</' . $this->name . '>' : ''; + } + + + /** + * Returns element's attributes. + * @internal + */ + final public function attributes(): string + { + if (!is_array($this->attrs)) { + return ''; + } + + $s = ''; + $attrs = $this->attrs; + foreach ($attrs as $key => $value) { + if ($value === null || $value === false) { + continue; + + } elseif ($value === true) { + $s .= ' ' . $key; + + continue; + + } elseif (is_array($value)) { + if (strncmp($key, 'data-', 5) === 0) { + $value = Json::encode($value); + + } else { + $tmp = null; + foreach ($value as $k => $v) { + if ($v != null) { // intentionally ==, skip nulls & empty string + // composite 'style' vs. 'others' + $tmp[] = $v === true + ? $k + : (is_string($k) ? $k . ':' . $v : $v); + } + } + + if ($tmp === null) { + continue; + } + + $value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp); + } + } elseif (is_float($value)) { + $value = rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.'); + + } else { + $value = (string) $value; + } + + $q = str_contains($value, '"') ? "'" : '"'; + $s .= ' ' . $key . '=' . $q + . str_replace( + ['&', $q, '<'], + ['&', $q === '"' ? '"' : ''', '<'], + $value, + ) + . (str_contains($value, '`') && strpbrk($value, ' <>"\'') === false ? ' ' : '') + . $q; + } + + $s = str_replace('@', '@', $s); + return $s; + } + + + /** + * Clones all children too. + */ + public function __clone() + { + foreach ($this->children as $key => $value) { + if (is_object($value)) { + $this->children[$key] = clone $value; + } + } + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Image.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Image.php new file mode 100644 index 0000000..eb728f6 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Image.php @@ -0,0 +1,829 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Basic manipulation with images. Supported types are JPEG, PNG, GIF, WEBP, AVIF and BMP. + * + * <code> + * $image = Image::fromFile('nette.jpg'); + * $image->resize(150, 100); + * $image->sharpen(); + * $image->send(); + * </code> + * + * @method Image affine(array $affine, ?array $clip = null) + * @method void alphaBlending(bool $enable) + * @method void antialias(bool $enable) + * @method void arc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color) + * @method int colorAllocate(int $red, int $green, int $blue) + * @method int colorAllocateAlpha(int $red, int $green, int $blue, int $alpha) + * @method int colorAt(int $x, int $y) + * @method int colorClosest(int $red, int $green, int $blue) + * @method int colorClosestAlpha(int $red, int $green, int $blue, int $alpha) + * @method int colorClosestHWB(int $red, int $green, int $blue) + * @method void colorDeallocate(int $color) + * @method int colorExact(int $red, int $green, int $blue) + * @method int colorExactAlpha(int $red, int $green, int $blue, int $alpha) + * @method void colorMatch(Image $image2) + * @method int colorResolve(int $red, int $green, int $blue) + * @method int colorResolveAlpha(int $red, int $green, int $blue, int $alpha) + * @method void colorSet(int $index, int $red, int $green, int $blue, int $alpha = 0) + * @method array colorsForIndex(int $color) + * @method int colorsTotal() + * @method int colorTransparent(?int $color = null) + * @method void convolution(array $matrix, float $div, float $offset) + * @method void copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH) + * @method void copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct) + * @method void copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct) + * @method void copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH) + * @method void copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH) + * @method Image cropAuto(int $mode = IMG_CROP_DEFAULT, float $threshold = .5, ?ImageColor $color = null) + * @method void ellipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color) + * @method void fill(int $x, int $y, ImageColor $color) + * @method void filledArc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color, int $style) + * @method void filledEllipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color) + * @method void filledPolygon(array $points, ImageColor $color) + * @method void filledRectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color) + * @method void fillToBorder(int $x, int $y, ImageColor $borderColor, ImageColor $color) + * @method void filter(int $filter, ...$args) + * @method void flip(int $mode) + * @method array ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options = []) + * @method void gammaCorrect(float $inputgamma, float $outputgamma) + * @method array getClip() + * @method int getInterpolation() + * @method int interlace(?bool $enable = null) + * @method bool isTrueColor() + * @method void layerEffect(int $effect) + * @method void line(int $x1, int $y1, int $x2, int $y2, ImageColor $color) + * @method void openPolygon(array $points, ImageColor $color) + * @method void paletteCopy(Image $source) + * @method void paletteToTrueColor() + * @method void polygon(array $points, ImageColor $color) + * @method void rectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color) + * @method mixed resolution(?int $resolutionX = null, ?int $resolutionY = null) + * @method Image rotate(float $angle, ImageColor $backgroundColor) + * @method void saveAlpha(bool $enable) + * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = IMG_BILINEAR_FIXED) + * @method void setBrush(Image $brush) + * @method void setClip(int $x1, int $y1, int $x2, int $y2) + * @method void setInterpolation(int $method = IMG_BILINEAR_FIXED) + * @method void setPixel(int $x, int $y, ImageColor $color) + * @method void setStyle(array $style) + * @method void setThickness(int $thickness) + * @method void setTile(Image $tile) + * @method void trueColorToPalette(bool $dither, int $ncolors) + * @method array ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array $options = []) + * @property-read positive-int $width + * @property-read positive-int $height + * @property-read \GdImage $imageResource + */ +class Image +{ + use Nette\SmartObject; + + /** Prevent from getting resized to a bigger size than the original */ + public const ShrinkOnly = 0b0001; + + /** Resizes to a specified width and height without keeping aspect ratio */ + public const Stretch = 0b0010; + + /** Resizes to fit into a specified width and height and preserves aspect ratio */ + public const OrSmaller = 0b0000; + + /** Resizes while bounding the smaller dimension to the specified width or height and preserves aspect ratio */ + public const OrBigger = 0b0100; + + /** Resizes to the smallest possible size to completely cover specified width and height and reserves aspect ratio */ + public const Cover = 0b1000; + + /** @deprecated use Image::ShrinkOnly */ + public const SHRINK_ONLY = self::ShrinkOnly; + + /** @deprecated use Image::Stretch */ + public const STRETCH = self::Stretch; + + /** @deprecated use Image::OrSmaller */ + public const FIT = self::OrSmaller; + + /** @deprecated use Image::OrBigger */ + public const FILL = self::OrBigger; + + /** @deprecated use Image::Cover */ + public const EXACT = self::Cover; + + /** @deprecated use Image::EmptyGIF */ + public const EMPTY_GIF = self::EmptyGIF; + + /** image types */ + public const + JPEG = ImageType::JPEG, + PNG = ImageType::PNG, + GIF = ImageType::GIF, + WEBP = ImageType::WEBP, + AVIF = ImageType::AVIF, + BMP = ImageType::BMP; + + public const EmptyGIF = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"; + + private const Formats = [ImageType::JPEG => 'jpeg', ImageType::PNG => 'png', ImageType::GIF => 'gif', ImageType::WEBP => 'webp', ImageType::AVIF => 'avif', ImageType::BMP => 'bmp']; + + private \GdImage $image; + + + /** + * Returns RGB color (0..255) and transparency (0..127). + * @deprecated use ImageColor::rgb() + */ + public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array + { + return [ + 'red' => max(0, min(255, $red)), + 'green' => max(0, min(255, $green)), + 'blue' => max(0, min(255, $blue)), + 'alpha' => max(0, min(127, $transparency)), + ]; + } + + + /** + * Reads an image from a file and returns its type in $type. + * @throws Nette\NotSupportedException if gd extension is not loaded + * @throws UnknownImageFileException if file not found or file type is not known + */ + public static function fromFile(string $file, ?int &$type = null): static + { + if (!extension_loaded('gd')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + + $type = self::detectTypeFromFile($file); + if (!$type) { + throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found."); + } + + return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__); + } + + + /** + * Reads an image from a string and returns its type in $type. + * @throws Nette\NotSupportedException if gd extension is not loaded + * @throws ImageException + */ + public static function fromString(string $s, ?int &$type = null): static + { + if (!extension_loaded('gd')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + + $type = self::detectTypeFromString($s); + if (!$type) { + throw new UnknownImageFileException('Unknown type of image.'); + } + + return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__); + } + + + private static function invokeSafe(string $func, string $arg, string $message, string $callee): static + { + $errors = []; + $res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void { + $errors[] = $message; + }); + + if (!$res) { + throw new ImageException($message . ' Errors: ' . implode(', ', $errors)); + } elseif ($errors) { + trigger_error($callee . '(): ' . implode(', ', $errors), E_USER_WARNING); + } + + return new static($res); + } + + + /** + * Creates a new true color image of the given dimensions. The default color is black. + * @param positive-int $width + * @param positive-int $height + * @throws Nette\NotSupportedException if gd extension is not loaded + */ + public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static + { + if (!extension_loaded('gd')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + + if ($width < 1 || $height < 1) { + throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.'); + } + + $image = new static(imagecreatetruecolor($width, $height)); + if ($color) { + $image->alphablending(false); + $image->filledrectangle(0, 0, $width - 1, $height - 1, $color); + $image->alphablending(true); + } + + return $image; + } + + + /** + * Returns the type of image from file. + * @return ImageType::*|null + */ + public static function detectTypeFromFile(string $file, &$width = null, &$height = null): ?int + { + [$width, $height, $type] = @getimagesize($file); // @ - files smaller than 12 bytes causes read error + return isset(self::Formats[$type]) ? $type : null; + } + + + /** + * Returns the type of image from string. + * @return ImageType::*|null + */ + public static function detectTypeFromString(string $s, &$width = null, &$height = null): ?int + { + [$width, $height, $type] = @getimagesizefromstring($s); // @ - strings smaller than 12 bytes causes read error + return isset(self::Formats[$type]) ? $type : null; + } + + + /** + * Returns the file extension for the given image type. + * @param ImageType::* $type + * @return value-of<self::Formats> + */ + public static function typeToExtension(int $type): string + { + if (!isset(self::Formats[$type])) { + throw new Nette\InvalidArgumentException("Unsupported image type '$type'."); + } + + return self::Formats[$type]; + } + + + /** + * Returns the image type for given file extension. + * @return ImageType::* + */ + public static function extensionToType(string $extension): int + { + $extensions = array_flip(self::Formats) + ['jpg' => ImageType::JPEG]; + $extension = strtolower($extension); + if (!isset($extensions[$extension])) { + throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'."); + } + + return $extensions[$extension]; + } + + + /** + * Returns the mime type for the given image type. + * @param ImageType::* $type + */ + public static function typeToMimeType(int $type): string + { + return 'image/' . self::typeToExtension($type); + } + + + /** + * @param ImageType::* $type + */ + public static function isTypeSupported(int $type): bool + { + return (bool) (imagetypes() & match ($type) { + ImageType::JPEG => IMG_JPG, + ImageType::PNG => IMG_PNG, + ImageType::GIF => IMG_GIF, + ImageType::WEBP => IMG_WEBP, + ImageType::AVIF => 256, // IMG_AVIF, + ImageType::BMP => IMG_BMP, + default => 0, + }); + } + + + /** @return ImageType[] */ + public static function getSupportedTypes(): array + { + $flag = imagetypes(); + return array_filter([ + $flag & IMG_GIF ? ImageType::GIF : null, + $flag & IMG_JPG ? ImageType::JPEG : null, + $flag & IMG_PNG ? ImageType::PNG : null, + $flag & IMG_WEBP ? ImageType::WEBP : null, + $flag & 256 ? ImageType::AVIF : null, // IMG_AVIF + $flag & IMG_BMP ? ImageType::BMP : null, + ]); + } + + + /** + * Wraps GD image. + */ + public function __construct(\GdImage $image) + { + $this->setImageResource($image); + imagesavealpha($image, true); + } + + + /** + * Returns image width. + * @return positive-int + */ + public function getWidth(): int + { + return imagesx($this->image); + } + + + /** + * Returns image height. + * @return positive-int + */ + public function getHeight(): int + { + return imagesy($this->image); + } + + + /** + * Sets image resource. + */ + protected function setImageResource(\GdImage $image): static + { + $this->image = $image; + return $this; + } + + + /** + * Returns image GD resource. + */ + public function getImageResource(): \GdImage + { + return $this->image; + } + + + /** + * Scales an image. Width and height accept pixels or percent. + * @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode + */ + public function resize(int|string|null $width, int|string|null $height, int $mode = self::OrSmaller): static + { + if ($mode & self::Cover) { + return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height); + } + + [$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $mode); + + if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize + $newImage = static::fromBlank($newWidth, $newHeight, ImageColor::rgb(0, 0, 0, 0))->getImageResource(); + imagecopyresampled( + $newImage, + $this->image, + 0, + 0, + 0, + 0, + $newWidth, + $newHeight, + $this->getWidth(), + $this->getHeight(), + ); + $this->image = $newImage; + } + + if ($width < 0 || $height < 0) { + imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL); + } + + return $this; + } + + + /** + * Calculates dimensions of resized image. Width and height accept pixels or percent. + * @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode + */ + public static function calculateSize( + int $srcWidth, + int $srcHeight, + $newWidth, + $newHeight, + int $mode = self::OrSmaller, + ): array + { + if ($newWidth === null) { + } elseif (self::isPercent($newWidth)) { + $newWidth = (int) round($srcWidth / 100 * abs($newWidth)); + $percents = true; + } else { + $newWidth = abs($newWidth); + } + + if ($newHeight === null) { + } elseif (self::isPercent($newHeight)) { + $newHeight = (int) round($srcHeight / 100 * abs($newHeight)); + $mode |= empty($percents) ? 0 : self::Stretch; + } else { + $newHeight = abs($newHeight); + } + + if ($mode & self::Stretch) { // non-proportional + if (!$newWidth || !$newHeight) { + throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.'); + } + + if ($mode & self::ShrinkOnly) { + $newWidth = min($srcWidth, $newWidth); + $newHeight = min($srcHeight, $newHeight); + } + } else { // proportional + if (!$newWidth && !$newHeight) { + throw new Nette\InvalidArgumentException('At least width or height must be specified.'); + } + + $scale = []; + if ($newWidth > 0) { // fit width + $scale[] = $newWidth / $srcWidth; + } + + if ($newHeight > 0) { // fit height + $scale[] = $newHeight / $srcHeight; + } + + if ($mode & self::OrBigger) { + $scale = [max($scale)]; + } + + if ($mode & self::ShrinkOnly) { + $scale[] = 1; + } + + $scale = min($scale); + $newWidth = (int) round($srcWidth * $scale); + $newHeight = (int) round($srcHeight * $scale); + } + + return [max($newWidth, 1), max($newHeight, 1)]; + } + + + /** + * Crops image. Arguments accepts pixels or percent. + */ + public function crop(int|string $left, int|string $top, int|string $width, int|string $height): static + { + [$r['x'], $r['y'], $r['width'], $r['height']] + = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height); + if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') { + $this->image = imagecrop($this->image, $r); + imagesavealpha($this->image, true); + } else { + $newImage = static::fromBlank($r['width'], $r['height'], ImageColor::rgb(0, 0, 0, 0))->getImageResource(); + imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']); + $this->image = $newImage; + } + + return $this; + } + + + /** + * Calculates dimensions of cutout in image. Arguments accepts pixels or percent. + */ + public static function calculateCutout( + int $srcWidth, + int $srcHeight, + int|string $left, + int|string $top, + int|string $newWidth, + int|string $newHeight, + ): array + { + if (self::isPercent($newWidth)) { + $newWidth = (int) round($srcWidth / 100 * $newWidth); + } + + if (self::isPercent($newHeight)) { + $newHeight = (int) round($srcHeight / 100 * $newHeight); + } + + if (self::isPercent($left)) { + $left = (int) round(($srcWidth - $newWidth) / 100 * $left); + } + + if (self::isPercent($top)) { + $top = (int) round(($srcHeight - $newHeight) / 100 * $top); + } + + if ($left < 0) { + $newWidth += $left; + $left = 0; + } + + if ($top < 0) { + $newHeight += $top; + $top = 0; + } + + $newWidth = min($newWidth, $srcWidth - $left); + $newHeight = min($newHeight, $srcHeight - $top); + return [$left, $top, $newWidth, $newHeight]; + } + + + /** + * Sharpens image a little bit. + */ + public function sharpen(): static + { + imageconvolution($this->image, [ // my magic numbers ;) + [-1, -1, -1], + [-1, 24, -1], + [-1, -1, -1], + ], 16, 0); + return $this; + } + + + /** + * Puts another image into this image. Left and top accepts pixels or percent. + * @param int<0, 100> $opacity 0..100 + */ + public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static + { + $opacity = max(0, min(100, $opacity)); + if ($opacity === 0) { + return $this; + } + + $width = $image->getWidth(); + $height = $image->getHeight(); + + if (self::isPercent($left)) { + $left = (int) round(($this->getWidth() - $width) / 100 * $left); + } + + if (self::isPercent($top)) { + $top = (int) round(($this->getHeight() - $height) / 100 * $top); + } + + $output = $input = $image->image; + if ($opacity < 100) { + $tbl = []; + for ($i = 0; $i < 128; $i++) { + $tbl[$i] = round(127 - (127 - $i) * $opacity / 100); + } + + $output = imagecreatetruecolor($width, $height); + imagealphablending($output, false); + if (!$image->isTrueColor()) { + $input = $output; + imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127)); + imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height); + } + + for ($x = 0; $x < $width; $x++) { + for ($y = 0; $y < $height; $y++) { + $c = \imagecolorat($input, $x, $y); + $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24); + \imagesetpixel($output, $x, $y, $c); + } + } + + imagealphablending($output, true); + } + + imagecopy( + $this->image, + $output, + $left, + $top, + 0, + 0, + $width, + $height, + ); + return $this; + } + + + /** + * Calculates the bounding box for a TrueType text. Returns keys left, top, width and height. + */ + public static function calculateTextBox( + string $text, + string $fontFile, + float $size, + float $angle = 0, + array $options = [], + ): array + { + $box = imagettfbbox($size, $angle, $fontFile, $text, $options); + return [ + 'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]), + 'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]), + 'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1, + 'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1, + ]; + } + + + /** + * Draw a rectangle. + */ + public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void + { + if ($width !== 0 && $height !== 0) { + $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color); + } + } + + + /** + * Draw a filled rectangle. + */ + public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void + { + if ($width !== 0 && $height !== 0) { + $this->filledRectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color); + } + } + + + /** + * Saves image to the file. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * @param ImageType::*|null $type + * @throws ImageException + */ + public function save(string $file, ?int $quality = null, ?int $type = null): void + { + $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION)); + $this->output($type, $quality, $file); + } + + + /** + * Outputs image to string. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * @param ImageType::* $type + */ + public function toString(int $type = ImageType::JPEG, ?int $quality = null): string + { + return Helpers::capture(function () use ($type, $quality): void { + $this->output($type, $quality); + }); + } + + + /** + * Outputs image to string. + */ + public function __toString(): string + { + return $this->toString(); + } + + + /** + * Outputs image to browser. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * @param ImageType::* $type + * @throws ImageException + */ + public function send(int $type = ImageType::JPEG, ?int $quality = null): void + { + header('Content-Type: ' . self::typeToMimeType($type)); + $this->output($type, $quality); + } + + + /** + * Outputs image to browser or file. + * @param ImageType::* $type + * @throws ImageException + */ + private function output(int $type, ?int $quality, ?string $file = null): void + { + switch ($type) { + case ImageType::JPEG: + $quality = $quality === null ? 85 : max(0, min(100, $quality)); + $success = @imagejpeg($this->image, $file, $quality); // @ is escalated to exception + break; + + case ImageType::PNG: + $quality = $quality === null ? 9 : max(0, min(9, $quality)); + $success = @imagepng($this->image, $file, $quality); // @ is escalated to exception + break; + + case ImageType::GIF: + $success = @imagegif($this->image, $file); // @ is escalated to exception + break; + + case ImageType::WEBP: + $quality = $quality === null ? 80 : max(0, min(100, $quality)); + $success = @imagewebp($this->image, $file, $quality); // @ is escalated to exception + break; + + case ImageType::AVIF: + $quality = $quality === null ? 30 : max(0, min(100, $quality)); + $success = @imageavif($this->image, $file, $quality); // @ is escalated to exception + break; + + case ImageType::BMP: + $success = @imagebmp($this->image, $file); // @ is escalated to exception + break; + + default: + throw new Nette\InvalidArgumentException("Unsupported image type '$type'."); + } + + if (!$success) { + throw new ImageException(Helpers::getLastError() ?: 'Unknown error'); + } + } + + + /** + * Call to undefined method. + * @throws Nette\MemberAccessException + */ + public function __call(string $name, array $args): mixed + { + $function = 'image' . $name; + if (!function_exists($function)) { + ObjectHelpers::strictCall(static::class, $name); + } + + foreach ($args as $key => $value) { + if ($value instanceof self) { + $args[$key] = $value->getImageResource(); + + } elseif ($value instanceof ImageColor || (is_array($value) && isset($value['red']))) { + $args[$key] = $this->resolveColor($value); + } + } + + $res = $function($this->image, ...$args); + return $res instanceof \GdImage + ? $this->setImageResource($res) + : $res; + } + + + public function __clone() + { + ob_start(function () {}); + imagepng($this->image, null, 0); + $this->setImageResource(imagecreatefromstring(ob_get_clean())); + } + + + private static function isPercent(int|string &$num): bool + { + if (is_string($num) && str_ends_with($num, '%')) { + $num = (float) substr($num, 0, -1); + return true; + } elseif (is_int($num) || $num === (string) (int) $num) { + $num = (int) $num; + return false; + } + + throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given."); + } + + + /** + * Prevents serialization. + */ + public function __sleep(): array + { + throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.'); + } + + + public function resolveColor(ImageColor|array $color): int + { + $color = $color instanceof ImageColor ? $color->toRGBA() : array_values($color); + return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/ImageColor.php b/php/libraries/composer/vendor/nette/utils/src/Utils/ImageColor.php new file mode 100644 index 0000000..013adbd --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/ImageColor.php @@ -0,0 +1,75 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Represent RGB color (0..255) with opacity (0..1). + */ +class ImageColor +{ + public static function rgb(int $red, int $green, int $blue, float $opacity = 1): self + { + return new self($red, $green, $blue, $opacity); + } + + + /** + * Accepts formats #RRGGBB, #RRGGBBAA, #RGB, #RGBA + */ + public static function hex(string $hex): self + { + $hex = ltrim($hex, '#'); + $len = strlen($hex); + if ($len === 3 || $len === 4) { + return new self( + (int) hexdec($hex[0]) * 17, + (int) hexdec($hex[1]) * 17, + (int) hexdec($hex[2]) * 17, + (int) hexdec($hex[3] ?? 'F') * 17 / 255, + ); + } elseif ($len === 6 || $len === 8) { + return new self( + (int) hexdec($hex[0] . $hex[1]), + (int) hexdec($hex[2] . $hex[3]), + (int) hexdec($hex[4] . $hex[5]), + (int) hexdec(($hex[6] ?? 'F') . ($hex[7] ?? 'F')) / 255, + ); + } else { + throw new Nette\InvalidArgumentException('Invalid hex color format.'); + } + } + + + private function __construct( + public int $red, + public int $green, + public int $blue, + public float $opacity = 1, + ) { + $this->red = max(0, min(255, $red)); + $this->green = max(0, min(255, $green)); + $this->blue = max(0, min(255, $blue)); + $this->opacity = max(0, min(1, $opacity)); + } + + + public function toRGBA(): array + { + return [ + max(0, min(255, $this->red)), + max(0, min(255, $this->green)), + max(0, min(255, $this->blue)), + max(0, min(127, (int) round(127 - $this->opacity * 127))), + ]; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/ImageType.php b/php/libraries/composer/vendor/nette/utils/src/Utils/ImageType.php new file mode 100644 index 0000000..3092c8f --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/ImageType.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + + +/** + * Type of image file. + */ +/*enum*/ final class ImageType +{ + public const + JPEG = IMAGETYPE_JPEG, + PNG = IMAGETYPE_PNG, + GIF = IMAGETYPE_GIF, + WEBP = IMAGETYPE_WEBP, + AVIF = 19, // IMAGETYPE_AVIF, + BMP = IMAGETYPE_BMP; +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Iterables.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Iterables.php new file mode 100644 index 0000000..a2a0b53 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Iterables.php @@ -0,0 +1,159 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Utilities for iterables. + */ +final class Iterables +{ + use Nette\StaticClass; + + /** + * Tests for the presence of value. + */ + public static function contains(iterable $iterable, mixed $value): bool + { + foreach ($iterable as $v) { + if ($v === $value) { + return true; + } + } + return false; + } + + + /** + * Tests for the presence of key. + */ + public static function containsKey(iterable $iterable, mixed $key): bool + { + foreach ($iterable as $k => $v) { + if ($k === $key) { + return true; + } + } + return false; + } + + + /** + * Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * The $predicate has the signature `function (mixed $value, mixed $key, iterable $iterable): bool`. + * @template T + * @param iterable<T> $iterable + * @return ?T + */ + public static function first(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed + { + foreach ($iterable as $k => $v) { + if (!$predicate || $predicate($v, $k, $iterable)) { + return $v; + } + } + return $else ? $else() : null; + } + + + /** + * Returns the key of first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * The $predicate has the signature `function (mixed $value, mixed $key, iterable $iterable): bool`. + * @template T + * @param iterable<T, mixed> $iterable + * @return ?T + */ + public static function firstKey(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed + { + foreach ($iterable as $k => $v) { + if (!$predicate || $predicate($v, $k, $iterable)) { + return $k; + } + } + return $else ? $else() : null; + } + + + /** + * Tests whether at least one element in the iterator passes the test implemented by the + * provided callback with signature `function (mixed $value, mixed $key, iterable $iterable): bool`. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): bool $predicate + */ + public static function some(iterable $iterable, callable $predicate): bool + { + foreach ($iterable as $k => $v) { + if ($predicate($v, $k, $iterable)) { + return true; + } + } + return false; + } + + + /** + * Tests whether all elements in the iterator pass the test implemented by the provided function, + * which has the signature `function (mixed $value, mixed $key, iterable $iterable): bool`. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): bool $predicate + */ + public static function every(iterable $iterable, callable $predicate): bool + { + foreach ($iterable as $k => $v) { + if (!$predicate($v, $k, $iterable)) { + return false; + } + } + return true; + } + + + /** + * Iterator that filters elements according to a given $predicate. Maintains original keys. + * The callback has the signature `function (mixed $value, mixed $key, iterable $iterable): bool`. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): bool $predicate + * @return \Generator<K, V> + */ + public static function filter(iterable $iterable, callable $predicate): \Generator + { + foreach ($iterable as $k => $v) { + if ($predicate($v, $k, $iterable)) { + yield $k => $v; + } + } + } + + + /** + * Iterator that transforms values by calling $transformer. Maintains original keys. + * The callback has the signature `function (mixed $value, mixed $key, iterable $iterable): bool`. + * @template K + * @template V + * @template R + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): R $transformer + * @return \Generator<K, R> + */ + public static function map(iterable $iterable, callable $transformer): \Generator + { + foreach ($iterable as $k => $v) { + yield $k => $transformer($v, $k, $iterable); + } + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Json.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Json.php new file mode 100644 index 0000000..b87917b --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Json.php @@ -0,0 +1,84 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * JSON encoder and decoder. + */ +final class Json +{ + use Nette\StaticClass; + + /** @deprecated use Json::decode(..., forceArrays: true) */ + public const FORCE_ARRAY = JSON_OBJECT_AS_ARRAY; + + /** @deprecated use Json::encode(..., pretty: true) */ + public const PRETTY = JSON_PRETTY_PRINT; + + /** @deprecated use Json::encode(..., asciiSafe: true) */ + public const ESCAPE_UNICODE = 1 << 19; + + + /** + * Converts value to JSON format. Use $pretty for easier reading and clarity, $asciiSafe for ASCII output + * and $htmlSafe for HTML escaping, $forceObjects enforces the encoding of non-associateve arrays as objects. + * @throws JsonException + */ + public static function encode( + mixed $value, + bool|int $pretty = false, + bool $asciiSafe = false, + bool $htmlSafe = false, + bool $forceObjects = false, + ): string + { + if (is_int($pretty)) { // back compatibility + $flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE); + } else { + $flags = ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE) + | ($pretty ? JSON_PRETTY_PRINT : 0) + | ($forceObjects ? JSON_FORCE_OBJECT : 0) + | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0); + } + + $flags |= JSON_UNESCAPED_SLASHES + | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7 + + $json = json_encode($value, $flags); + if ($error = json_last_error()) { + throw new JsonException(json_last_error_msg(), $error); + } + + return $json; + } + + + /** + * Parses JSON to PHP value. The $forceArrays enforces the decoding of objects as arrays. + * @throws JsonException + */ + public static function decode(string $json, bool|int $forceArrays = false): mixed + { + $flags = is_int($forceArrays) // back compatibility + ? $forceArrays + : ($forceArrays ? JSON_OBJECT_AS_ARRAY : 0); + $flags |= JSON_BIGINT_AS_STRING; + + $value = json_decode($json, flags: $flags); + if ($error = json_last_error()) { + throw new JsonException(json_last_error_msg(), $error); + } + + return $value; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/ObjectHelpers.php b/php/libraries/composer/vendor/nette/utils/src/Utils/ObjectHelpers.php new file mode 100644 index 0000000..f4bd55f --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/ObjectHelpers.php @@ -0,0 +1,229 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; +use Nette\MemberAccessException; + + +/** + * Nette\SmartObject helpers. + * @internal + */ +final class ObjectHelpers +{ + use Nette\StaticClass; + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictGet(string $class, string $name): void + { + $rc = new \ReflectionClass($class); + $hint = self::getSuggestion(array_merge( + array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()), + self::parseFullDoc($rc, '~^[ \t*]*@property(?:-read)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'), + ), $name); + throw new MemberAccessException("Cannot read an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.')); + } + + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictSet(string $class, string $name): void + { + $rc = new \ReflectionClass($class); + $hint = self::getSuggestion(array_merge( + array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()), + self::parseFullDoc($rc, '~^[ \t*]*@property(?:-write)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'), + ), $name); + throw new MemberAccessException("Cannot write to an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.')); + } + + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictCall(string $class, string $method, array $additionalMethods = []): void + { + $trace = debug_backtrace(0, 3); // suppose this method is called from __call() + $context = ($trace[1]['function'] ?? null) === '__call' + ? ($trace[2]['class'] ?? null) + : null; + + if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method() + $class = get_parent_class($context); + } + + if (method_exists($class, $method)) { // insufficient visibility + $rm = new \ReflectionMethod($class, $method); + $visibility = $rm->isPrivate() + ? 'private ' + : ($rm->isProtected() ? 'protected ' : ''); + throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.')); + + } else { + $hint = self::getSuggestion(array_merge( + get_class_methods($class), + self::parseFullDoc(new \ReflectionClass($class), '~^[ \t*]*@method[ \t]+(?:static[ \t]+)?(?:\S+[ \t]+)??(\w+)\(~m'), + $additionalMethods, + ), $method); + throw new MemberAccessException("Call to undefined method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.')); + } + } + + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictStaticCall(string $class, string $method): void + { + $trace = debug_backtrace(0, 3); // suppose this method is called from __callStatic() + $context = ($trace[1]['function'] ?? null) === '__callStatic' + ? ($trace[2]['class'] ?? null) + : null; + + if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method() + $class = get_parent_class($context); + } + + if (method_exists($class, $method)) { // insufficient visibility + $rm = new \ReflectionMethod($class, $method); + $visibility = $rm->isPrivate() + ? 'private ' + : ($rm->isProtected() ? 'protected ' : ''); + throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.')); + + } else { + $hint = self::getSuggestion( + array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), fn($m) => $m->isStatic()), + $method, + ); + throw new MemberAccessException("Call to undefined static method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.')); + } + } + + + /** + * Returns array of magic properties defined by annotation @property. + * @return array of [name => bit mask] + * @internal + */ + public static function getMagicProperties(string $class): array + { + static $cache; + $props = &$cache[$class]; + if ($props !== null) { + return $props; + } + + $rc = new \ReflectionClass($class); + preg_match_all( + '~^ [ \t*]* @property(|-read|-write|-deprecated) [ \t]+ [^\s$]+ [ \t]+ \$ (\w+) ()~mx', + (string) $rc->getDocComment(), + $matches, + PREG_SET_ORDER, + ); + + $props = []; + foreach ($matches as [, $type, $name]) { + $uname = ucfirst($name); + $write = $type !== '-read' + && $rc->hasMethod($nm = 'set' . $uname) + && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic(); + $read = $type !== '-write' + && ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname)) + && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic(); + + if ($read || $write) { + $props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3 | ($type === '-deprecated') << 4; + } + } + + foreach ($rc->getTraits() as $trait) { + $props += self::getMagicProperties($trait->name); + } + + if ($parent = get_parent_class($class)) { + $props += self::getMagicProperties($parent); + } + + return $props; + } + + + /** + * Finds the best suggestion (for 8-bit encoding). + * @param (\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionClass|\ReflectionProperty|string)[] $possibilities + * @internal + */ + public static function getSuggestion(array $possibilities, string $value): ?string + { + $norm = preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '+', $value); + $best = null; + $min = (strlen($value) / 4 + 1) * 10 + .1; + foreach (array_unique($possibilities, SORT_REGULAR) as $item) { + $item = $item instanceof \Reflector ? $item->name : $item; + if ($item !== $value && ( + ($len = levenshtein($item, $value, 10, 11, 10)) < $min + || ($len = levenshtein(preg_replace($re, '*', $item), $norm, 10, 11, 10)) < $min + )) { + $min = $len; + $best = $item; + } + } + + return $best; + } + + + private static function parseFullDoc(\ReflectionClass $rc, string $pattern): array + { + do { + $doc[] = $rc->getDocComment(); + $traits = $rc->getTraits(); + while ($trait = array_pop($traits)) { + $doc[] = $trait->getDocComment(); + $traits += $trait->getTraits(); + } + } while ($rc = $rc->getParentClass()); + + return preg_match_all($pattern, implode('', $doc), $m) ? $m[1] : []; + } + + + /** + * Checks if the public non-static property exists. + * Returns 'event' if the property exists and has event like name + * @internal + */ + public static function hasProperty(string $class, string $name): bool|string + { + static $cache; + $prop = &$cache[$class][$name]; + if ($prop === null) { + $prop = false; + try { + $rp = new \ReflectionProperty($class, $name); + if ($rp->isPublic() && !$rp->isStatic()) { + $prop = $name >= 'onA' && $name < 'on_' ? 'event' : true; + } + } catch (\ReflectionException $e) { + } + } + + return $prop; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Paginator.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Paginator.php new file mode 100644 index 0000000..aa4812c --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Paginator.php @@ -0,0 +1,245 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Paginating math. + * + * @property int $page + * @property-read int $firstPage + * @property-read int|null $lastPage + * @property-read int<0,max> $firstItemOnPage + * @property-read int<0,max> $lastItemOnPage + * @property int $base + * @property-read bool $first + * @property-read bool $last + * @property-read int<0,max>|null $pageCount + * @property positive-int $itemsPerPage + * @property int<0,max>|null $itemCount + * @property-read int<0,max> $offset + * @property-read int<0,max>|null $countdownOffset + * @property-read int<0,max> $length + */ +class Paginator +{ + use Nette\SmartObject; + + private int $base = 1; + + /** @var positive-int */ + private int $itemsPerPage = 1; + + private int $page = 1; + + /** @var int<0, max>|null */ + private ?int $itemCount = null; + + + /** + * Sets current page number. + */ + public function setPage(int $page): static + { + $this->page = $page; + return $this; + } + + + /** + * Returns current page number. + */ + public function getPage(): int + { + return $this->base + $this->getPageIndex(); + } + + + /** + * Returns first page number. + */ + public function getFirstPage(): int + { + return $this->base; + } + + + /** + * Returns last page number. + */ + public function getLastPage(): ?int + { + return $this->itemCount === null + ? null + : $this->base + max(0, $this->getPageCount() - 1); + } + + + /** + * Returns the sequence number of the first element on the page + * @return int<0, max> + */ + public function getFirstItemOnPage(): int + { + return $this->itemCount !== 0 + ? $this->offset + 1 + : 0; + } + + + /** + * Returns the sequence number of the last element on the page + * @return int<0, max> + */ + public function getLastItemOnPage(): int + { + return $this->offset + $this->length; + } + + + /** + * Sets first page (base) number. + */ + public function setBase(int $base): static + { + $this->base = $base; + return $this; + } + + + /** + * Returns first page (base) number. + */ + public function getBase(): int + { + return $this->base; + } + + + /** + * Returns zero-based page number. + * @return int<0, max> + */ + protected function getPageIndex(): int + { + $index = max(0, $this->page - $this->base); + return $this->itemCount === null + ? $index + : min($index, max(0, $this->getPageCount() - 1)); + } + + + /** + * Is the current page the first one? + */ + public function isFirst(): bool + { + return $this->getPageIndex() === 0; + } + + + /** + * Is the current page the last one? + */ + public function isLast(): bool + { + return $this->itemCount === null + ? false + : $this->getPageIndex() >= $this->getPageCount() - 1; + } + + + /** + * Returns the total number of pages. + * @return int<0, max>|null + */ + public function getPageCount(): ?int + { + return $this->itemCount === null + ? null + : (int) ceil($this->itemCount / $this->itemsPerPage); + } + + + /** + * Sets the number of items to display on a single page. + */ + public function setItemsPerPage(int $itemsPerPage): static + { + $this->itemsPerPage = max(1, $itemsPerPage); + return $this; + } + + + /** + * Returns the number of items to display on a single page. + * @return positive-int + */ + public function getItemsPerPage(): int + { + return $this->itemsPerPage; + } + + + /** + * Sets the total number of items. + */ + public function setItemCount(?int $itemCount = null): static + { + $this->itemCount = $itemCount === null ? null : max(0, $itemCount); + return $this; + } + + + /** + * Returns the total number of items. + * @return int<0, max>|null + */ + public function getItemCount(): ?int + { + return $this->itemCount; + } + + + /** + * Returns the absolute index of the first item on current page. + * @return int<0, max> + */ + public function getOffset(): int + { + return $this->getPageIndex() * $this->itemsPerPage; + } + + + /** + * Returns the absolute index of the first item on current page in countdown paging. + * @return int<0, max>|null + */ + public function getCountdownOffset(): ?int + { + return $this->itemCount === null + ? null + : max(0, $this->itemCount - ($this->getPageIndex() + 1) * $this->itemsPerPage); + } + + + /** + * Returns the number of items on current page. + * @return int<0, max> + */ + public function getLength(): int + { + return $this->itemCount === null + ? $this->itemsPerPage + : min($this->itemsPerPage, $this->itemCount - $this->getPageIndex() * $this->itemsPerPage); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Random.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Random.php new file mode 100644 index 0000000..b14fbd5 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Random.php @@ -0,0 +1,52 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; +use Random\Randomizer; + + +/** + * Secure random string generator. + */ +final class Random +{ + use Nette\StaticClass; + + /** + * Generates a random string of given length from characters specified in second argument. + * Supports intervals, such as `0-9` or `A-Z`. + */ + public static function generate(int $length = 10, string $charlist = '0-9a-z'): string + { + $charlist = preg_replace_callback( + '#.-.#', + fn(array $m): string => implode('', range($m[0][0], $m[0][2])), + $charlist, + ); + $charlist = count_chars($charlist, mode: 3); + $chLen = strlen($charlist); + + if ($length < 1) { + throw new Nette\InvalidArgumentException('Length must be greater than zero.'); + } elseif ($chLen < 2) { + throw new Nette\InvalidArgumentException('Character list must contain at least two chars.'); + } elseif (PHP_VERSION_ID >= 80300) { + return (new Randomizer)->getBytesFromString($charlist, $length); + } + + $res = ''; + for ($i = 0; $i < $length; $i++) { + $res .= $charlist[random_int(0, $chLen - 1)]; + } + + return $res; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Reflection.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Reflection.php new file mode 100644 index 0000000..5a4f2ab --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Reflection.php @@ -0,0 +1,320 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * PHP reflection helpers. + */ +final class Reflection +{ + use Nette\StaticClass; + + /** @deprecated use Nette\Utils\Validator::isBuiltinType() */ + public static function isBuiltinType(string $type): bool + { + return Validators::isBuiltinType($type); + } + + + /** @deprecated use Nette\Utils\Validator::isClassKeyword() */ + public static function isClassKeyword(string $name): bool + { + return Validators::isClassKeyword($name); + } + + + /** @deprecated use native ReflectionParameter::getDefaultValue() */ + public static function getParameterDefaultValue(\ReflectionParameter $param): mixed + { + if ($param->isDefaultValueConstant()) { + $const = $orig = $param->getDefaultValueConstantName(); + $pair = explode('::', $const); + if (isset($pair[1])) { + $pair[0] = Type::resolve($pair[0], $param); + try { + $rcc = new \ReflectionClassConstant($pair[0], $pair[1]); + } catch (\ReflectionException $e) { + $name = self::toString($param); + throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.", 0, $e); + } + + return $rcc->getValue(); + + } elseif (!defined($const)) { + $const = substr((string) strrchr($const, '\\'), 1); + if (!defined($const)) { + $name = self::toString($param); + throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name."); + } + } + + return constant($const); + } + + return $param->getDefaultValue(); + } + + + /** + * Returns a reflection of a class or trait that contains a declaration of given property. Property can also be declared in the trait. + */ + public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass + { + foreach ($prop->getDeclaringClass()->getTraits() as $trait) { + if ($trait->hasProperty($prop->name) + // doc-comment guessing as workaround for insufficient PHP reflection + && $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment() + ) { + return self::getPropertyDeclaringClass($trait->getProperty($prop->name)); + } + } + + return $prop->getDeclaringClass(); + } + + + /** + * Returns a reflection of a method that contains a declaration of $method. + * Usually, each method is its own declaration, but the body of the method can also be in the trait and under a different name. + */ + public static function getMethodDeclaringMethod(\ReflectionMethod $method): \ReflectionMethod + { + // file & line guessing as workaround for insufficient PHP reflection + $decl = $method->getDeclaringClass(); + if ($decl->getFileName() === $method->getFileName() + && $decl->getStartLine() <= $method->getStartLine() + && $decl->getEndLine() >= $method->getEndLine() + ) { + return $method; + } + + $hash = [$method->getFileName(), $method->getStartLine(), $method->getEndLine()]; + if (($alias = $decl->getTraitAliases()[$method->name] ?? null) + && ($m = new \ReflectionMethod($alias)) + && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()] + ) { + return self::getMethodDeclaringMethod($m); + } + + foreach ($decl->getTraits() as $trait) { + if ($trait->hasMethod($method->name) + && ($m = $trait->getMethod($method->name)) + && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()] + ) { + return self::getMethodDeclaringMethod($m); + } + } + + return $method; + } + + + /** + * Finds out if reflection has access to PHPdoc comments. Comments may not be available due to the opcode cache. + */ + public static function areCommentsAvailable(): bool + { + static $res; + return $res ?? $res = (bool) (new \ReflectionMethod(__METHOD__))->getDocComment(); + } + + + public static function toString(\Reflector $ref): string + { + if ($ref instanceof \ReflectionClass) { + return $ref->name; + } elseif ($ref instanceof \ReflectionMethod) { + return $ref->getDeclaringClass()->name . '::' . $ref->name . '()'; + } elseif ($ref instanceof \ReflectionFunction) { + return $ref->name . '()'; + } elseif ($ref instanceof \ReflectionProperty) { + return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name; + } elseif ($ref instanceof \ReflectionParameter) { + return '$' . $ref->name . ' in ' . self::toString($ref->getDeclaringFunction()); + } else { + throw new Nette\InvalidArgumentException; + } + } + + + /** + * Expands the name of the class to full name in the given context of given class. + * Thus, it returns how the PHP parser would understand $name if it were written in the body of the class $context. + * @throws Nette\InvalidArgumentException + */ + public static function expandClassName(string $name, \ReflectionClass $context): string + { + $lower = strtolower($name); + if (empty($name)) { + throw new Nette\InvalidArgumentException('Class name must not be empty.'); + + } elseif (Validators::isBuiltinType($lower)) { + return $lower; + + } elseif ($lower === 'self' || $lower === 'static') { + return $context->name; + + } elseif ($lower === 'parent') { + return $context->getParentClass() + ? $context->getParentClass()->name + : 'parent'; + + } elseif ($name[0] === '\\') { // fully qualified name + return ltrim($name, '\\'); + } + + $uses = self::getUseStatements($context); + $parts = explode('\\', $name, 2); + if (isset($uses[$parts[0]])) { + $parts[0] = $uses[$parts[0]]; + return implode('\\', $parts); + + } elseif ($context->inNamespace()) { + return $context->getNamespaceName() . '\\' . $name; + + } else { + return $name; + } + } + + + /** @return array<string, class-string> of [alias => class] */ + public static function getUseStatements(\ReflectionClass $class): array + { + if ($class->isAnonymous()) { + throw new Nette\NotImplementedException('Anonymous classes are not supported.'); + } + + static $cache = []; + if (!isset($cache[$name = $class->name])) { + if ($class->isInternal()) { + $cache[$name] = []; + } else { + $code = file_get_contents($class->getFileName()); + $cache = self::parseUseStatements($code, $name) + $cache; + } + } + + return $cache[$name]; + } + + + /** + * Parses PHP code to [class => [alias => class, ...]] + */ + private static function parseUseStatements(string $code, ?string $forClass = null): array + { + try { + $tokens = \PhpToken::tokenize($code, TOKEN_PARSE); + } catch (\ParseError $e) { + trigger_error($e->getMessage(), E_USER_NOTICE); + $tokens = []; + } + + $namespace = $class = null; + $classLevel = $level = 0; + $res = $uses = []; + + $nameTokens = [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED]; + + while ($token = current($tokens)) { + next($tokens); + switch ($token->id) { + case T_NAMESPACE: + $namespace = ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\'); + $uses = []; + break; + + case T_CLASS: + case T_INTERFACE: + case T_TRAIT: + case PHP_VERSION_ID < 80100 + ? T_CLASS + : T_ENUM: + if ($name = self::fetch($tokens, T_STRING)) { + $class = $namespace . $name; + $classLevel = $level + 1; + $res[$class] = $uses; + if ($class === $forClass) { + return $res; + } + } + + break; + + case T_USE: + while (!$class && ($name = self::fetch($tokens, $nameTokens))) { + $name = ltrim($name, '\\'); + if (self::fetch($tokens, '{')) { + while ($suffix = self::fetch($tokens, $nameTokens)) { + if (self::fetch($tokens, T_AS)) { + $uses[self::fetch($tokens, T_STRING)] = $name . $suffix; + } else { + $tmp = explode('\\', $suffix); + $uses[end($tmp)] = $name . $suffix; + } + + if (!self::fetch($tokens, ',')) { + break; + } + } + } elseif (self::fetch($tokens, T_AS)) { + $uses[self::fetch($tokens, T_STRING)] = $name; + + } else { + $tmp = explode('\\', $name); + $uses[end($tmp)] = $name; + } + + if (!self::fetch($tokens, ',')) { + break; + } + } + + break; + + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + case ord('{'): + $level++; + break; + + case ord('}'): + if ($level === $classLevel) { + $class = $classLevel = 0; + } + + $level--; + } + } + + return $res; + } + + + private static function fetch(array &$tokens, string|int|array $take): ?string + { + $res = null; + while ($token = current($tokens)) { + if ($token->is($take)) { + $res .= $token->text; + } elseif (!$token->is([T_DOC_COMMENT, T_WHITESPACE, T_COMMENT])) { + break; + } + + next($tokens); + } + + return $res; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/ReflectionMethod.php b/php/libraries/composer/vendor/nette/utils/src/Utils/ReflectionMethod.php new file mode 100644 index 0000000..b003fcb --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/ReflectionMethod.php @@ -0,0 +1,36 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + + +/** + * ReflectionMethod preserving the original class name. + * @internal + */ +final class ReflectionMethod extends \ReflectionMethod +{ + private \ReflectionClass $originalClass; + + + public function __construct(object|string $objectOrMethod, ?string $method = null) + { + if (is_string($objectOrMethod) && str_contains($objectOrMethod, '::')) { + [$objectOrMethod, $method] = explode('::', $objectOrMethod, 2); + } + parent::__construct($objectOrMethod, $method); + $this->originalClass = new \ReflectionClass($objectOrMethod); + } + + + public function getOriginalClass(): \ReflectionClass + { + return $this->originalClass; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Strings.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Strings.php new file mode 100644 index 0000000..1615b3e --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Strings.php @@ -0,0 +1,708 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use JetBrains\PhpStorm\Language; +use Nette; +use function is_array, is_object, strlen; + + +/** + * String tools library. + */ +class Strings +{ + use Nette\StaticClass; + + public const TrimCharacters = " \t\n\r\0\x0B\u{A0}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{200B}"; + + /** @deprecated use Strings::TrimCharacters */ + public const TRIM_CHARACTERS = self::TrimCharacters; + + + /** + * @deprecated use Nette\Utils\Validator::isUnicode() + */ + public static function checkEncoding(string $s): bool + { + return $s === self::fixEncoding($s); + } + + + /** + * Removes all invalid UTF-8 characters from a string. + */ + public static function fixEncoding(string $s): string + { + // removes xD800-xDFFF, x110000 and higher + return htmlspecialchars_decode(htmlspecialchars($s, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES); + } + + + /** + * Returns a specific character in UTF-8 from code point (number in range 0x0000..D7FF or 0xE000..10FFFF). + * @throws Nette\InvalidArgumentException if code point is not in valid range + */ + public static function chr(int $code): string + { + if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) { + throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.'); + } elseif (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + + return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code)); + } + + + /** + * Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF). + */ + public static function ord(string $c): int + { + if (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + + $tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c); + if (!$tmp) { + throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".'); + } + + return unpack('N', $tmp)[1]; + } + + + /** + * @deprecated use str_starts_with() + */ + public static function startsWith(string $haystack, string $needle): bool + { + return str_starts_with($haystack, $needle); + } + + + /** + * @deprecated use str_ends_with() + */ + public static function endsWith(string $haystack, string $needle): bool + { + return str_ends_with($haystack, $needle); + } + + + /** + * @deprecated use str_contains() + */ + public static function contains(string $haystack, string $needle): bool + { + return str_contains($haystack, $needle); + } + + + /** + * Returns a part of UTF-8 string specified by starting position and length. If start is negative, + * the returned string will start at the start'th character from the end of string. + */ + public static function substring(string $s, int $start, ?int $length = null): string + { + if (function_exists('mb_substr')) { + return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster + } elseif (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.'); + } elseif ($length === null) { + $length = self::length($s); + } elseif ($start < 0 && $length < 0) { + $start += self::length($s); // unifies iconv_substr behavior with mb_substr + } + + return iconv_substr($s, $start, $length, 'UTF-8'); + } + + + /** + * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines, + * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC. + */ + public static function normalize(string $s): string + { + // convert to compressed normal form (NFC) + if (class_exists('Normalizer', false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) { + $s = $n; + } + + $s = self::unixNewLines($s); + + // remove control characters; leave \t + \n + $s = self::pcre('preg_replace', ['#[\x00-\x08\x0B-\x1F\x7F-\x9F]+#u', '', $s]); + + // right trim + $s = self::pcre('preg_replace', ['#[\t ]+$#m', '', $s]); + + // leading and trailing blank lines + $s = trim($s, "\n"); + + return $s; + } + + + /** @deprecated use Strings::unixNewLines() */ + public static function normalizeNewLines(string $s): string + { + return self::unixNewLines($s); + } + + + /** + * Converts line endings to \n used on Unix-like systems. + * Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator. + */ + public static function unixNewLines(string $s): string + { + return preg_replace("~\r\n?|\u{2028}|\u{2029}~", "\n", $s); + } + + + /** + * Converts line endings to platform-specific, i.e. \r\n on Windows and \n elsewhere. + * Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator. + */ + public static function platformNewLines(string $s): string + { + return preg_replace("~\r\n?|\n|\u{2028}|\u{2029}~", PHP_EOL, $s); + } + + + /** + * Converts UTF-8 string to ASCII, ie removes diacritics etc. + */ + public static function toAscii(string $s): string + { + $iconv = defined('ICONV_IMPL') ? trim(ICONV_IMPL, '"\'') : null; + static $transliterator = null; + if ($transliterator === null) { + if (class_exists('Transliterator', false)) { + $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII'); + } else { + trigger_error(__METHOD__ . "(): it is recommended to enable PHP extensions 'intl'.", E_USER_NOTICE); + $transliterator = false; + } + } + + // remove control characters and check UTF-8 validity + $s = self::pcre('preg_replace', ['#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s]); + + // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly + $s = strtr($s, ["\u{201E}" => '"', "\u{201C}" => '"', "\u{201D}" => '"', "\u{201A}" => "'", "\u{2018}" => "'", "\u{2019}" => "'", "\u{B0}" => '^', "\u{42F}" => 'Ya', "\u{44F}" => 'ya', "\u{42E}" => 'Yu', "\u{44E}" => 'yu', "\u{c4}" => 'Ae', "\u{d6}" => 'Oe', "\u{dc}" => 'Ue', "\u{1e9e}" => 'Ss', "\u{e4}" => 'ae', "\u{f6}" => 'oe', "\u{fc}" => 'ue', "\u{df}" => 'ss']); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß + if ($iconv !== 'libiconv') { + $s = strtr($s, ["\u{AE}" => '(R)', "\u{A9}" => '(c)', "\u{2026}" => '...', "\u{AB}" => '<<', "\u{BB}" => '>>', "\u{A3}" => 'lb', "\u{A5}" => 'yen', "\u{B2}" => '^2', "\u{B3}" => '^3', "\u{B5}" => 'u', "\u{B9}" => '^1', "\u{BA}" => 'o', "\u{BF}" => '?', "\u{2CA}" => "'", "\u{2CD}" => '_', "\u{2DD}" => '"', "\u{1FEF}" => '', "\u{20AC}" => 'EUR', "\u{2122}" => 'TM', "\u{212E}" => 'e', "\u{2190}" => '<-', "\u{2191}" => '^', "\u{2192}" => '->', "\u{2193}" => 'V', "\u{2194}" => '<->']); // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔ + } + + if ($transliterator) { + $s = $transliterator->transliterate($s); + // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ + if ($iconv === 'glibc') { + $s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates + $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + $s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters + } elseif ($iconv === 'libiconv') { + $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + } else { // null or 'unknown' (#216) + $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars + } + } elseif ($iconv === 'glibc' || $iconv === 'libiconv') { + // temporarily hide these characters to distinguish them from the garbage that iconv creates + $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06"); + if ($iconv === 'glibc') { + // glibc implementation is very limited. transliterate into Windows-1250 and then into ASCII, so most Eastern European characters are preserved + $s = iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); + $s = strtr( + $s, + "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x96\xa0\x8b\x97\x9b\xa6\xad\xb7", + 'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.', + ); + $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); + } else { + $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + } + + // remove garbage that iconv creates during transliteration (eg Ý -> Y') + $s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s); + // restore temporarily hidden characters + $s = strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?'); + } else { + $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars + } + + return $s; + } + + + /** + * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters + * except letters of the English alphabet and numbers with a hyphens. + */ + public static function webalize(string $s, ?string $charlist = null, bool $lower = true): string + { + $s = self::toAscii($s); + if ($lower) { + $s = strtolower($s); + } + + $s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]); + $s = trim($s, '-'); + return $s; + } + + + /** + * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated, + * an ellipsis (or something else set with third argument) is appended to the string. + */ + public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string + { + if (self::length($s) > $maxLen) { + $maxLen -= self::length($append); + if ($maxLen < 1) { + return $append; + + } elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us')) { + return $matches[0] . $append; + + } else { + return self::substring($s, 0, $maxLen) . $append; + } + } + + return $s; + } + + + /** + * Indents a multiline text from the left. Second argument sets how many indentation chars should be used, + * while the indent itself is the third argument (*tab* by default). + */ + public static function indent(string $s, int $level = 1, string $chars = "\t"): string + { + if ($level > 0) { + $s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level)); + } + + return $s; + } + + + /** + * Converts all characters of UTF-8 string to lower case. + */ + public static function lower(string $s): string + { + return mb_strtolower($s, 'UTF-8'); + } + + + /** + * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged. + */ + public static function firstLower(string $s): string + { + return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1); + } + + + /** + * Converts all characters of a UTF-8 string to upper case. + */ + public static function upper(string $s): string + { + return mb_strtoupper($s, 'UTF-8'); + } + + + /** + * Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged. + */ + public static function firstUpper(string $s): string + { + return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1); + } + + + /** + * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case. + */ + public static function capitalize(string $s): string + { + return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8'); + } + + + /** + * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared, + * if it is negative, the corresponding number of characters from the end of the strings is compared, + * otherwise the appropriate number of characters from the beginning is compared. + */ + public static function compare(string $left, string $right, ?int $length = null): bool + { + if (class_exists('Normalizer', false)) { + $left = \Normalizer::normalize($left, \Normalizer::FORM_D); // form NFD is faster + $right = \Normalizer::normalize($right, \Normalizer::FORM_D); // form NFD is faster + } + + if ($length < 0) { + $left = self::substring($left, $length, -$length); + $right = self::substring($right, $length, -$length); + } elseif ($length !== null) { + $left = self::substring($left, 0, $length); + $right = self::substring($right, 0, $length); + } + + return self::lower($left) === self::lower($right); + } + + + /** + * Finds the common prefix of strings or returns empty string if the prefix was not found. + * @param string[] $strings + */ + public static function findPrefix(array $strings): string + { + $first = array_shift($strings); + for ($i = 0; $i < strlen($first); $i++) { + foreach ($strings as $s) { + if (!isset($s[$i]) || $first[$i] !== $s[$i]) { + while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") { + $i--; + } + + return substr($first, 0, $i); + } + } + } + + return $first; + } + + + /** + * Returns number of characters (not bytes) in UTF-8 string. + * That is the number of Unicode code points which may differ from the number of graphemes. + */ + public static function length(string $s): int + { + return match (true) { + extension_loaded('mbstring') => mb_strlen($s, 'UTF-8'), + extension_loaded('iconv') => iconv_strlen($s, 'UTF-8'), + default => strlen(@utf8_decode($s)), // deprecated + }; + } + + + /** + * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string. + */ + public static function trim(string $s, string $charlist = self::TrimCharacters): string + { + $charlist = preg_quote($charlist, '#'); + return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', ''); + } + + + /** + * Pads a UTF-8 string to given length by prepending the $pad string to the beginning. + * @param non-empty-string $pad + */ + public static function padLeft(string $s, int $length, string $pad = ' '): string + { + $length = max(0, $length - self::length($s)); + $padLen = self::length($pad); + return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s; + } + + + /** + * Pads UTF-8 string to given length by appending the $pad string to the end. + * @param non-empty-string $pad + */ + public static function padRight(string $s, int $length, string $pad = ' '): string + { + $length = max(0, $length - self::length($s)); + $padLen = self::length($pad); + return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen); + } + + + /** + * Reverses UTF-8 string. + */ + public static function reverse(string $s): string + { + if (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + + return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', $s))); + } + + + /** + * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found. + * Negative value means searching from the end. + */ + public static function before(string $haystack, string $needle, int $nth = 1): ?string + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null + ? null + : substr($haystack, 0, $pos); + } + + + /** + * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found. + * Negative value means searching from the end. + */ + public static function after(string $haystack, string $needle, int $nth = 1): ?string + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null + ? null + : substr($haystack, $pos + strlen($needle)); + } + + + /** + * Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found. + * Negative value of `$nth` means searching from the end. + */ + public static function indexOf(string $haystack, string $needle, int $nth = 1): ?int + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null + ? null + : self::length(substr($haystack, 0, $pos)); + } + + + /** + * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found. + */ + private static function pos(string $haystack, string $needle, int $nth = 1): ?int + { + if (!$nth) { + return null; + } elseif ($nth > 0) { + if ($needle === '') { + return 0; + } + + $pos = 0; + while (($pos = strpos($haystack, $needle, $pos)) !== false && --$nth) { + $pos++; + } + } else { + $len = strlen($haystack); + if ($needle === '') { + return $len; + } elseif ($len === 0) { + return null; + } + + $pos = $len - 1; + while (($pos = strrpos($haystack, $needle, $pos - $len)) !== false && ++$nth) { + $pos--; + } + } + + return Helpers::falseToNull($pos); + } + + + /** + * Divides the string into arrays according to the regular expression. Expressions in parentheses will be captured and returned as well. + */ + public static function split( + string $subject, + #[Language('RegExp')] + string $pattern, + bool|int $captureOffset = false, + bool $skipEmpty = false, + int $limit = -1, + bool $utf8 = false, + ): array + { + $flags = is_int($captureOffset) // back compatibility + ? $captureOffset + : ($captureOffset ? PREG_SPLIT_OFFSET_CAPTURE : 0) | ($skipEmpty ? PREG_SPLIT_NO_EMPTY : 0); + + $pattern .= $utf8 ? 'u' : ''; + $m = self::pcre('preg_split', [$pattern, $subject, $limit, $flags | PREG_SPLIT_DELIM_CAPTURE]); + return $utf8 && $captureOffset + ? self::bytesToChars($subject, [$m])[0] + : $m; + + } + + + /** + * Searches the string for the part matching the regular expression and returns + * an array with the found expression and individual subexpressions, or `null`. + */ + public static function match( + string $subject, + #[Language('RegExp')] + string $pattern, + bool|int $captureOffset = false, + int $offset = 0, + bool $unmatchedAsNull = false, + bool $utf8 = false, + ): ?array + { + $flags = is_int($captureOffset) // back compatibility + ? $captureOffset + : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0); + + if ($utf8) { + $offset = strlen(self::substring($subject, 0, $offset)); + $pattern .= 'u'; + } + + if ($offset > strlen($subject)) { + return null; + } elseif (!self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])) { + return null; + } elseif ($utf8 && $captureOffset) { + return self::bytesToChars($subject, [$m])[0]; + } else { + return $m; + } + } + + + /** + * Searches the string for all occurrences matching the regular expression and + * returns an array of arrays containing the found expression and each subexpression. + */ + public static function matchAll( + string $subject, + #[Language('RegExp')] + string $pattern, + bool|int $captureOffset = false, + int $offset = 0, + bool $unmatchedAsNull = false, + bool $patternOrder = false, + bool $utf8 = false, + ): array + { + $flags = is_int($captureOffset) // back compatibility + ? $captureOffset + : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0) | ($patternOrder ? PREG_PATTERN_ORDER : 0); + + if ($utf8) { + $offset = strlen(self::substring($subject, 0, $offset)); + $pattern .= 'u'; + } + + if ($offset > strlen($subject)) { + return []; + } + + self::pcre('preg_match_all', [ + $pattern, $subject, &$m, + ($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER), + $offset, + ]); + return $utf8 && $captureOffset + ? self::bytesToChars($subject, $m) + : $m; + + } + + + /** + * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`. + */ + public static function replace( + string $subject, + #[Language('RegExp')] + string|array $pattern, + string|callable $replacement = '', + int $limit = -1, + bool $captureOffset = false, + bool $unmatchedAsNull = false, + bool $utf8 = false, + ): string + { + if (is_object($replacement) || is_array($replacement)) { + if (!is_callable($replacement, false, $textual)) { + throw new Nette\InvalidStateException("Callback '$textual' is not callable."); + } + + $flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0); + if ($utf8) { + $pattern .= 'u'; + if ($captureOffset) { + $replacement = fn($m) => $replacement(self::bytesToChars($subject, [$m])[0]); + } + } + + return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]); + + } elseif (is_array($pattern) && is_string(key($pattern))) { + $replacement = array_values($pattern); + $pattern = array_keys($pattern); + } + + if ($utf8) { + $pattern = array_map(fn($item) => $item . 'u', (array) $pattern); + } + + return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]); + } + + + private static function bytesToChars(string $s, array $groups): array + { + $lastBytes = $lastChars = 0; + foreach ($groups as &$matches) { + foreach ($matches as &$match) { + if ($match[1] > $lastBytes) { + $lastChars += self::length(substr($s, $lastBytes, $match[1] - $lastBytes)); + } elseif ($match[1] < $lastBytes) { + $lastChars -= self::length(substr($s, $match[1], $lastBytes - $match[1])); + } + + $lastBytes = $match[1]; + $match[1] = $lastChars; + } + } + + return $groups; + } + + + /** @internal */ + public static function pcre(string $func, array $args) + { + $res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void { + // compile-time error, not detectable by preg_last_error + throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0])); + }); + + if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars + && ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], true)) + ) { + throw new RegexpException(preg_last_error_msg() + . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code); + } + + return $res; + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Type.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Type.php new file mode 100644 index 0000000..7a17881 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Type.php @@ -0,0 +1,267 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * PHP type reflection. + */ +final class Type +{ + /** @var array<int, string|self> */ + private array $types; + private bool $simple; + private string $kind; // | & + + + /** + * Creates a Type object based on reflection. Resolves self, static and parent to the actual class name. + * If the subject has no type, it returns null. + */ + public static function fromReflection( + \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $reflection, + ): ?self + { + $type = $reflection instanceof \ReflectionFunctionAbstract + ? $reflection->getReturnType() ?? (PHP_VERSION_ID >= 80100 && $reflection instanceof \ReflectionMethod ? $reflection->getTentativeReturnType() : null) + : $reflection->getType(); + + return $type ? self::fromReflectionType($type, $reflection, asObject: true) : null; + } + + + private static function fromReflectionType(\ReflectionType $type, $of, bool $asObject): self|string + { + if ($type instanceof \ReflectionNamedType) { + $name = self::resolve($type->getName(), $of); + return $asObject + ? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name]) + : $name; + + } elseif ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) { + return new self( + array_map(fn($t) => self::fromReflectionType($t, $of, asObject: false), $type->getTypes()), + $type instanceof \ReflectionUnionType ? '|' : '&', + ); + + } else { + throw new Nette\InvalidStateException('Unexpected type of ' . Reflection::toString($of)); + } + } + + + /** + * Creates the Type object according to the text notation. + */ + public static function fromString(string $type): self + { + if (!Validators::isTypeDeclaration($type)) { + throw new Nette\InvalidArgumentException("Invalid type '$type'."); + } + + if ($type[0] === '?') { + return new self([substr($type, 1), 'null']); + } + + $unions = []; + foreach (explode('|', $type) as $part) { + $part = explode('&', trim($part, '()')); + $unions[] = count($part) === 1 ? $part[0] : new self($part, '&'); + } + + return count($unions) === 1 && $unions[0] instanceof self + ? $unions[0] + : new self($unions); + } + + + /** + * Resolves 'self', 'static' and 'parent' to the actual class name. + */ + public static function resolve( + string $type, + \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $of, + ): string + { + $lower = strtolower($type); + if ($of instanceof \ReflectionFunction) { + return $type; + } elseif ($lower === 'self') { + return $of->getDeclaringClass()->name; + } elseif ($lower === 'static') { + return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $of->getDeclaringClass())->name; + } elseif ($lower === 'parent' && $of->getDeclaringClass()->getParentClass()) { + return $of->getDeclaringClass()->getParentClass()->name; + } else { + return $type; + } + } + + + private function __construct(array $types, string $kind = '|') + { + $o = array_search('null', $types, strict: true); + if ($o !== false) { // null as last + array_splice($types, $o, 1); + $types[] = 'null'; + } + + $this->types = $types; + $this->simple = is_string($types[0]) && ($types[1] ?? 'null') === 'null'; + $this->kind = count($types) > 1 ? $kind : ''; + } + + + public function __toString(): string + { + $multi = count($this->types) > 1; + if ($this->simple) { + return ($multi ? '?' : '') . $this->types[0]; + } + + $res = []; + foreach ($this->types as $type) { + $res[] = $type instanceof self && $multi ? "($type)" : $type; + } + return implode($this->kind, $res); + } + + + /** + * Returns the array of subtypes that make up the compound type as strings. + * @return array<int, string|string[]> + */ + public function getNames(): array + { + return array_map(fn($t) => $t instanceof self ? $t->getNames() : $t, $this->types); + } + + + /** + * Returns the array of subtypes that make up the compound type as Type objects: + * @return self[] + */ + public function getTypes(): array + { + return array_map(fn($t) => $t instanceof self ? $t : new self([$t]), $this->types); + } + + + /** + * Returns the type name for simple types, otherwise null. + */ + public function getSingleName(): ?string + { + return $this->simple + ? $this->types[0] + : null; + } + + + /** + * Returns true whether it is a union type. + */ + public function isUnion(): bool + { + return $this->kind === '|'; + } + + + /** + * Returns true whether it is an intersection type. + */ + public function isIntersection(): bool + { + return $this->kind === '&'; + } + + + /** + * Returns true whether it is a simple type. Single nullable types are also considered to be simple types. + */ + public function isSimple(): bool + { + return $this->simple; + } + + + /** @deprecated use isSimple() */ + public function isSingle(): bool + { + return $this->simple; + } + + + /** + * Returns true whether the type is both a simple and a PHP built-in type. + */ + public function isBuiltin(): bool + { + return $this->simple && Validators::isBuiltinType($this->types[0]); + } + + + /** + * Returns true whether the type is both a simple and a class name. + */ + public function isClass(): bool + { + return $this->simple && !Validators::isBuiltinType($this->types[0]); + } + + + /** + * Determines if type is special class name self/parent/static. + */ + public function isClassKeyword(): bool + { + return $this->simple && Validators::isClassKeyword($this->types[0]); + } + + + /** + * Verifies type compatibility. For example, it checks if a value of a certain type could be passed as a parameter. + */ + public function allows(string $subtype): bool + { + if ($this->types === ['mixed']) { + return true; + } + + $subtype = self::fromString($subtype); + return $subtype->isUnion() + ? Arrays::every($subtype->types, fn($t) => $this->allows2($t instanceof self ? $t->types : [$t])) + : $this->allows2($subtype->types); + } + + + private function allows2(array $subtypes): bool + { + return $this->isUnion() + ? Arrays::some($this->types, fn($t) => $this->allows3($t instanceof self ? $t->types : [$t], $subtypes)) + : $this->allows3($this->types, $subtypes); + } + + + private function allows3(array $types, array $subtypes): bool + { + return Arrays::every( + $types, + fn($type) => Arrays::some( + $subtypes, + fn($subtype) => Validators::isBuiltinType($type) + ? strcasecmp($type, $subtype) === 0 + : is_a($subtype, $type, allow_string: true) + ) + ); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/Validators.php b/php/libraries/composer/vendor/nette/utils/src/Utils/Validators.php new file mode 100644 index 0000000..61ccf09 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/Validators.php @@ -0,0 +1,416 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + + +/** + * Validation utilities. + */ +class Validators +{ + use Nette\StaticClass; + + private const BuiltinTypes = [ + 'string' => 1, 'int' => 1, 'float' => 1, 'bool' => 1, 'array' => 1, 'object' => 1, + 'callable' => 1, 'iterable' => 1, 'void' => 1, 'null' => 1, 'mixed' => 1, 'false' => 1, + 'never' => 1, 'true' => 1, + ]; + + /** @var array<string,?callable> */ + protected static $validators = [ + // PHP types + 'array' => 'is_array', + 'bool' => 'is_bool', + 'boolean' => 'is_bool', + 'float' => 'is_float', + 'int' => 'is_int', + 'integer' => 'is_int', + 'null' => 'is_null', + 'object' => 'is_object', + 'resource' => 'is_resource', + 'scalar' => 'is_scalar', + 'string' => 'is_string', + + // pseudo-types + 'callable' => [self::class, 'isCallable'], + 'iterable' => 'is_iterable', + 'list' => [Arrays::class, 'isList'], + 'mixed' => [self::class, 'isMixed'], + 'none' => [self::class, 'isNone'], + 'number' => [self::class, 'isNumber'], + 'numeric' => [self::class, 'isNumeric'], + 'numericint' => [self::class, 'isNumericInt'], + + // string patterns + 'alnum' => 'ctype_alnum', + 'alpha' => 'ctype_alpha', + 'digit' => 'ctype_digit', + 'lower' => 'ctype_lower', + 'pattern' => null, + 'space' => 'ctype_space', + 'unicode' => [self::class, 'isUnicode'], + 'upper' => 'ctype_upper', + 'xdigit' => 'ctype_xdigit', + + // syntax validation + 'email' => [self::class, 'isEmail'], + 'identifier' => [self::class, 'isPhpIdentifier'], + 'uri' => [self::class, 'isUri'], + 'url' => [self::class, 'isUrl'], + + // environment validation + 'class' => 'class_exists', + 'interface' => 'interface_exists', + 'directory' => 'is_dir', + 'file' => 'is_file', + 'type' => [self::class, 'isType'], + ]; + + /** @var array<string,callable> */ + protected static $counters = [ + 'string' => 'strlen', + 'unicode' => [Strings::class, 'length'], + 'array' => 'count', + 'list' => 'count', + 'alnum' => 'strlen', + 'alpha' => 'strlen', + 'digit' => 'strlen', + 'lower' => 'strlen', + 'space' => 'strlen', + 'upper' => 'strlen', + 'xdigit' => 'strlen', + ]; + + + /** + * Verifies that the value is of expected types separated by pipe. + * @throws AssertionException + */ + public static function assert(mixed $value, string $expected, string $label = 'variable'): void + { + if (!static::is($value, $expected)) { + $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); + $translate = ['boolean' => 'bool', 'integer' => 'int', 'double' => 'float', 'NULL' => 'null']; + $type = $translate[gettype($value)] ?? gettype($value); + if (is_int($value) || is_float($value) || (is_string($value) && strlen($value) < 40)) { + $type .= ' ' . var_export($value, return: true); + } elseif (is_object($value)) { + $type .= ' ' . $value::class; + } + + throw new AssertionException("The $label expects to be $expected, $type given."); + } + } + + + /** + * Verifies that element $key in array is of expected types separated by pipe. + * @param mixed[] $array + * @throws AssertionException + */ + public static function assertField( + array $array, + $key, + ?string $expected = null, + string $label = "item '%' in array", + ): void + { + if (!array_key_exists($key, $array)) { + throw new AssertionException('Missing ' . str_replace('%', $key, $label) . '.'); + + } elseif ($expected) { + static::assert($array[$key], $expected, str_replace('%', $key, $label)); + } + } + + + /** + * Verifies that the value is of expected types separated by pipe. + */ + public static function is(mixed $value, string $expected): bool + { + foreach (explode('|', $expected) as $item) { + if (str_ends_with($item, '[]')) { + if (is_iterable($value) && self::everyIs($value, substr($item, 0, -2))) { + return true; + } + + continue; + } elseif (str_starts_with($item, '?')) { + $item = substr($item, 1); + if ($value === null) { + return true; + } + } + + [$type] = $item = explode(':', $item, 2); + if (isset(static::$validators[$type])) { + try { + if (!static::$validators[$type]($value)) { + continue; + } + } catch (\TypeError $e) { + continue; + } + } elseif ($type === 'pattern') { + if (Strings::match($value, '|^' . ($item[1] ?? '') . '$|D')) { + return true; + } + + continue; + } elseif (!$value instanceof $type) { + continue; + } + + if (isset($item[1])) { + $length = $value; + if (isset(static::$counters[$type])) { + $length = static::$counters[$type]($value); + } + + $range = explode('..', $item[1]); + if (!isset($range[1])) { + $range[1] = $range[0]; + } + + if (($range[0] !== '' && $length < $range[0]) || ($range[1] !== '' && $length > $range[1])) { + continue; + } + } + + return true; + } + + return false; + } + + + /** + * Finds whether all values are of expected types separated by pipe. + * @param mixed[] $values + */ + public static function everyIs(iterable $values, string $expected): bool + { + foreach ($values as $value) { + if (!static::is($value, $expected)) { + return false; + } + } + + return true; + } + + + /** + * Checks if the value is an integer or a float. + * @return ($value is int|float ? true : false) + */ + public static function isNumber(mixed $value): bool + { + return is_int($value) || is_float($value); + } + + + /** + * Checks if the value is an integer or a integer written in a string. + * @return ($value is non-empty-string ? bool : ($value is int ? true : false)) + */ + public static function isNumericInt(mixed $value): bool + { + return is_int($value) || (is_string($value) && preg_match('#^[+-]?[0-9]+$#D', $value)); + } + + + /** + * Checks if the value is a number or a number written in a string. + * @return ($value is non-empty-string ? bool : ($value is int|float ? true : false)) + */ + public static function isNumeric(mixed $value): bool + { + return is_float($value) || is_int($value) || (is_string($value) && preg_match('#^[+-]?([0-9]++\.?[0-9]*|\.[0-9]+)$#D', $value)); + } + + + /** + * Checks if the value is a syntactically correct callback. + */ + public static function isCallable(mixed $value): bool + { + return $value && is_callable($value, syntax_only: true); + } + + + /** + * Checks if the value is a valid UTF-8 string. + */ + public static function isUnicode(mixed $value): bool + { + return is_string($value) && preg_match('##u', $value); + } + + + /** + * Checks if the value is 0, '', false or null. + * @return ($value is 0|''|false|null ? true : false) + */ + public static function isNone(mixed $value): bool + { + return $value == null; // intentionally == + } + + + /** @internal */ + public static function isMixed(): bool + { + return true; + } + + + /** + * Checks if a variable is a zero-based integer indexed array. + * @deprecated use Nette\Utils\Arrays::isList + * @return ($value is list ? true : false) + */ + public static function isList(mixed $value): bool + { + return Arrays::isList($value); + } + + + /** + * Checks if the value is in the given range [min, max], where the upper or lower limit can be omitted (null). + * Numbers, strings and DateTime objects can be compared. + */ + public static function isInRange(mixed $value, array $range): bool + { + if ($value === null || !(isset($range[0]) || isset($range[1]))) { + return false; + } + + $limit = $range[0] ?? $range[1]; + if (is_string($limit)) { + $value = (string) $value; + } elseif ($limit instanceof \DateTimeInterface) { + if (!$value instanceof \DateTimeInterface) { + return false; + } + } elseif (is_numeric($value)) { + $value *= 1; + } else { + return false; + } + + return (!isset($range[0]) || ($value >= $range[0])) && (!isset($range[1]) || ($value <= $range[1])); + } + + + /** + * Checks if the value is a valid email address. It does not verify that the domain actually exists, only the syntax is verified. + */ + public static function isEmail(string $value): bool + { + $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part + $alpha = "a-z\x80-\xFF"; // superset of IDN + return (bool) preg_match(<<<XX + (^(?n) + ("([ !#-[\\]-~]*|\\\\[ -~])+"|$atom+(\\.$atom+)*) # quoted or unquoted + @ + ([0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)+ # domain - RFC 1034 + [$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain + $)Dix + XX, $value); + } + + + /** + * Checks if the value is a valid URL address. + */ + public static function isUrl(string $value): bool + { + $alpha = "a-z\x80-\xFF"; + return (bool) preg_match(<<<XX + (^(?n) + https?://( + (([-_0-9$alpha]+\\.)* # subdomain + [0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)? # domain + [$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain + |\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} # IPv4 + |\\[[0-9a-f:]{3,39}\\] # IPv6 + )(:\\d{1,5})? # port + (/\\S*)? # path + (\\?\\S*)? # query + (\\#\\S*)? # fragment + $)Dix + XX, $value); + } + + + /** + * Checks if the value is a valid URI address, that is, actually a string beginning with a syntactically valid schema. + */ + public static function isUri(string $value): bool + { + return (bool) preg_match('#^[a-z\d+\.-]+:\S+$#Di', $value); + } + + + /** + * Checks whether the input is a class, interface or trait. + * @deprecated + */ + public static function isType(string $type): bool + { + return class_exists($type) || interface_exists($type) || trait_exists($type); + } + + + /** + * Checks whether the input is a valid PHP identifier. + */ + public static function isPhpIdentifier(string $value): bool + { + return preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#D', $value) === 1; + } + + + /** + * Determines if type is PHP built-in type. Otherwise, it is the class name. + */ + public static function isBuiltinType(string $type): bool + { + return isset(self::BuiltinTypes[strtolower($type)]); + } + + + /** + * Determines if type is special class name self/parent/static. + */ + public static function isClassKeyword(string $name): bool + { + return (bool) preg_match('#^(self|parent|static)$#Di', $name); + } + + + /** + * Checks whether the given type declaration is syntactically valid. + */ + public static function isTypeDeclaration(string $type): bool + { + return (bool) preg_match(<<<'XX' + ~((?n) + \?? (?<type> \\? (?<name> [a-zA-Z_\x7f-\xff][\w\x7f-\xff]*) (\\ (?&name))* ) | + (?<intersection> (?&type) (& (?&type))+ ) | + (?<upart> (?&type) | \( (?&intersection) \) ) (\| (?&upart))+ + )$~xAD + XX, $type); + } +} diff --git a/php/libraries/composer/vendor/nette/utils/src/Utils/exceptions.php b/php/libraries/composer/vendor/nette/utils/src/Utils/exceptions.php new file mode 100644 index 0000000..af949ce --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/Utils/exceptions.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + + +/** + * The exception that is thrown when an image error occurs. + */ +class ImageException extends \Exception +{ +} + + +/** + * The exception that indicates invalid image file. + */ +class UnknownImageFileException extends ImageException +{ +} + + +/** + * The exception that indicates error of JSON encoding/decoding. + */ +class JsonException extends \JsonException +{ +} + + +/** + * The exception that indicates error of the last Regexp execution. + */ +class RegexpException extends \Exception +{ +} + + +/** + * The exception that indicates assertion error. + */ +class AssertionException extends \Exception +{ +} diff --git a/php/libraries/composer/vendor/nette/utils/src/compatibility.php b/php/libraries/composer/vendor/nette/utils/src/compatibility.php new file mode 100644 index 0000000..9df5480 --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/compatibility.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette\Utils; + +use Nette; + +if (false) { + /** @deprecated use Nette\HtmlStringable */ + interface IHtmlString extends Nette\HtmlStringable + { + } +} elseif (!interface_exists(IHtmlString::class)) { + class_alias(Nette\HtmlStringable::class, IHtmlString::class); +} + +namespace Nette\Localization; + +if (false) { + /** @deprecated use Nette\Localization\Translator */ + interface ITranslator extends Translator + { + } +} elseif (!interface_exists(ITranslator::class)) { + class_alias(Translator::class, ITranslator::class); +} diff --git a/php/libraries/composer/vendor/nette/utils/src/exceptions.php b/php/libraries/composer/vendor/nette/utils/src/exceptions.php new file mode 100644 index 0000000..bbda7dd --- /dev/null +++ b/php/libraries/composer/vendor/nette/utils/src/exceptions.php @@ -0,0 +1,109 @@ +<?php + +/** + * This file is part of the Nette Framework (https://nette.org) + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) + */ + +declare(strict_types=1); + +namespace Nette; + + +/** + * The exception that is thrown when the value of an argument is + * outside the allowable range of values as defined by the invoked method. + */ +class ArgumentOutOfRangeException extends \InvalidArgumentException +{ +} + + +/** + * The exception that is thrown when a method call is invalid for the object's + * current state, method has been invoked at an illegal or inappropriate time. + */ +class InvalidStateException extends \RuntimeException +{ +} + + +/** + * The exception that is thrown when a requested method or operation is not implemented. + */ +class NotImplementedException extends \LogicException +{ +} + + +/** + * The exception that is thrown when an invoked method is not supported. For scenarios where + * it is sometimes possible to perform the requested operation, see InvalidStateException. + */ +class NotSupportedException extends \LogicException +{ +} + + +/** + * The exception that is thrown when a requested method or operation is deprecated. + */ +class DeprecatedException extends NotSupportedException +{ +} + + +/** + * The exception that is thrown when accessing a class member (property or method) fails. + */ +class MemberAccessException extends \Error +{ +} + + +/** + * The exception that is thrown when an I/O error occurs. + */ +class IOException extends \RuntimeException +{ +} + + +/** + * The exception that is thrown when accessing a file that does not exist on disk. + */ +class FileNotFoundException extends IOException +{ +} + + +/** + * The exception that is thrown when part of a file or directory cannot be found. + */ +class DirectoryNotFoundException extends IOException +{ +} + + +/** + * The exception that is thrown when an argument does not match with the expected value. + */ +class InvalidArgumentException extends \InvalidArgumentException +{ +} + + +/** + * The exception that is thrown when an illegal index was requested. + */ +class OutOfRangeException extends \OutOfRangeException +{ +} + + +/** + * The exception that is thrown when a value (typically returned by function) does not match with the expected value. + */ +class UnexpectedValueException extends \UnexpectedValueException +{ +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/LICENSE b/php/libraries/composer/vendor/nikic/php-parser/LICENSE new file mode 100644 index 0000000..2e56718 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2011, Nikita Popov +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/php/libraries/composer/vendor/nikic/php-parser/README.md b/php/libraries/composer/vendor/nikic/php-parser/README.md new file mode 100644 index 0000000..7555838 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/README.md @@ -0,0 +1,233 @@ +PHP Parser +========== + +[![Coverage Status](https://coveralls.io/repos/github/nikic/PHP-Parser/badge.svg?branch=master)](https://coveralls.io/github/nikic/PHP-Parser?branch=master) + +This is a PHP parser written in PHP. Its purpose is to simplify static code analysis and +manipulation. + +[**Documentation for version 5.x**][doc_master] (current; for running on PHP >= 7.4; for parsing PHP 7.0 to PHP 8.3, with limited support for parsing PHP 5.x). + +[Documentation for version 4.x][doc_4_x] (supported; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 8.3). + +Features +-------- + +The main features provided by this library are: + + * Parsing PHP 7, and PHP 8 code into an abstract syntax tree (AST). + * Invalid code can be parsed into a partial AST. + * The AST contains accurate location information. + * Dumping the AST in human-readable form. + * Converting an AST back to PHP code. + * Formatting can be preserved for partially changed ASTs. + * Infrastructure to traverse and modify ASTs. + * Resolution of namespaced names. + * Evaluation of constant expressions. + * Builders to simplify AST construction for code generation. + * Converting an AST into JSON and back. + +Quick Start +----------- + +Install the library using [composer](https://getcomposer.org): + + php composer.phar require nikic/php-parser + +Parse some PHP code into an AST and dump the result in human-readable form: + +```php +<?php +use PhpParser\Error; +use PhpParser\NodeDumper; +use PhpParser\ParserFactory; + +$code = <<<'CODE' +<?php + +function test($foo) +{ + var_dump($foo); +} +CODE; + +$parser = (new ParserFactory())->createForNewestSupportedVersion(); +try { + $ast = $parser->parse($code); +} catch (Error $error) { + echo "Parse error: {$error->getMessage()}\n"; + return; +} + +$dumper = new NodeDumper; +echo $dumper->dump($ast) . "\n"; +``` + +This dumps an AST looking something like this: + +``` +array( + 0: Stmt_Function( + attrGroups: array( + ) + byRef: false + name: Identifier( + name: test + ) + params: array( + 0: Param( + attrGroups: array( + ) + flags: 0 + type: null + byRef: false + variadic: false + var: Expr_Variable( + name: foo + ) + default: null + ) + ) + returnType: null + stmts: array( + 0: Stmt_Expression( + expr: Expr_FuncCall( + name: Name( + name: var_dump + ) + args: array( + 0: Arg( + name: null + value: Expr_Variable( + name: foo + ) + byRef: false + unpack: false + ) + ) + ) + ) + ) + ) +) +``` + +Let's traverse the AST and perform some kind of modification. For example, drop all function bodies: + +```php +use PhpParser\Node; +use PhpParser\Node\Stmt\Function_; +use PhpParser\NodeTraverser; +use PhpParser\NodeVisitorAbstract; + +$traverser = new NodeTraverser(); +$traverser->addVisitor(new class extends NodeVisitorAbstract { + public function enterNode(Node $node) { + if ($node instanceof Function_) { + // Clean out the function body + $node->stmts = []; + } + } +}); + +$ast = $traverser->traverse($ast); +echo $dumper->dump($ast) . "\n"; +``` + +This gives us an AST where the `Function_::$stmts` are empty: + +``` +array( + 0: Stmt_Function( + attrGroups: array( + ) + byRef: false + name: Identifier( + name: test + ) + params: array( + 0: Param( + attrGroups: array( + ) + type: null + byRef: false + variadic: false + var: Expr_Variable( + name: foo + ) + default: null + ) + ) + returnType: null + stmts: array( + ) + ) +) +``` + +Finally, we can convert the new AST back to PHP code: + +```php +use PhpParser\PrettyPrinter; + +$prettyPrinter = new PrettyPrinter\Standard; +echo $prettyPrinter->prettyPrintFile($ast); +``` + +This gives us our original code, minus the `var_dump()` call inside the function: + +```php +<?php + +function test($foo) +{ +} +``` + +For a more comprehensive introduction, see the documentation. + +Documentation +------------- + + 1. [Introduction](doc/0_Introduction.markdown) + 2. [Usage of basic components](doc/2_Usage_of_basic_components.markdown) + +Component documentation: + + * [Walking the AST](doc/component/Walking_the_AST.markdown) + * Node visitors + * Modifying the AST from a visitor + * Short-circuiting traversals + * Interleaved visitors + * Simple node finding API + * Parent and sibling references + * [Name resolution](doc/component/Name_resolution.markdown) + * Name resolver options + * Name resolution context + * [Pretty printing](doc/component/Pretty_printing.markdown) + * Converting AST back to PHP code + * Customizing formatting + * Formatting-preserving code transformations + * [AST builders](doc/component/AST_builders.markdown) + * Fluent builders for AST nodes + * [Lexer](doc/component/Lexer.markdown) + * Emulation + * Tokens, positions and attributes + * [Error handling](doc/component/Error_handling.markdown) + * Column information for errors + * Error recovery (parsing of syntactically incorrect code) + * [Constant expression evaluation](doc/component/Constant_expression_evaluation.markdown) + * Evaluating constant/property/etc initializers + * Handling errors and unsupported expressions + * [JSON representation](doc/component/JSON_representation.markdown) + * JSON encoding and decoding of ASTs + * [Performance](doc/component/Performance.markdown) + * Disabling Xdebug + * Reusing objects + * Garbage collection impact + * [Frequently asked questions](doc/component/FAQ.markdown) + * Parent and sibling references + + [doc_3_x]: https://github.com/nikic/PHP-Parser/tree/3.x/doc + [doc_4_x]: https://github.com/nikic/PHP-Parser/tree/4.x/doc + [doc_master]: https://github.com/nikic/PHP-Parser/tree/master/doc diff --git a/php/libraries/composer/vendor/nikic/php-parser/bin/php-parse b/php/libraries/composer/vendor/nikic/php-parser/bin/php-parse new file mode 100755 index 0000000..fc44f23 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/bin/php-parse @@ -0,0 +1,206 @@ +#!/usr/bin/env php +<?php + +foreach ([__DIR__ . '/../../../autoload.php', __DIR__ . '/../vendor/autoload.php'] as $file) { + if (file_exists($file)) { + require $file; + break; + } +} + +ini_set('xdebug.max_nesting_level', 3000); + +// Disable Xdebug var_dump() output truncation +ini_set('xdebug.var_display_max_children', -1); +ini_set('xdebug.var_display_max_data', -1); +ini_set('xdebug.var_display_max_depth', -1); + +list($operations, $files, $attributes) = parseArgs($argv); + +/* Dump nodes by default */ +if (empty($operations)) { + $operations[] = 'dump'; +} + +if (empty($files)) { + showHelp("Must specify at least one file."); +} + +$parser = (new PhpParser\ParserFactory())->createForVersion($attributes['version']); +$dumper = new PhpParser\NodeDumper([ + 'dumpComments' => true, + 'dumpPositions' => $attributes['with-positions'], +]); +$prettyPrinter = new PhpParser\PrettyPrinter\Standard; + +$traverser = new PhpParser\NodeTraverser(); +$traverser->addVisitor(new PhpParser\NodeVisitor\NameResolver); + +foreach ($files as $file) { + if ($file === '-') { + $code = file_get_contents('php://stdin'); + fwrite(STDERR, "====> Stdin:\n"); + } else if (strpos($file, '<?php') === 0) { + $code = $file; + fwrite(STDERR, "====> Code $code\n"); + } else { + if (!file_exists($file)) { + fwrite(STDERR, "File $file does not exist.\n"); + exit(1); + } + + $code = file_get_contents($file); + fwrite(STDERR, "====> File $file:\n"); + } + + if ($attributes['with-recovery']) { + $errorHandler = new PhpParser\ErrorHandler\Collecting; + $stmts = $parser->parse($code, $errorHandler); + foreach ($errorHandler->getErrors() as $error) { + $message = formatErrorMessage($error, $code, $attributes['with-column-info']); + fwrite(STDERR, $message . "\n"); + } + if (null === $stmts) { + continue; + } + } else { + try { + $stmts = $parser->parse($code); + } catch (PhpParser\Error $error) { + $message = formatErrorMessage($error, $code, $attributes['with-column-info']); + fwrite(STDERR, $message . "\n"); + exit(1); + } + } + + foreach ($operations as $operation) { + if ('dump' === $operation) { + fwrite(STDERR, "==> Node dump:\n"); + echo $dumper->dump($stmts, $code), "\n"; + } elseif ('pretty-print' === $operation) { + fwrite(STDERR, "==> Pretty print:\n"); + echo $prettyPrinter->prettyPrintFile($stmts), "\n"; + } elseif ('json-dump' === $operation) { + fwrite(STDERR, "==> JSON dump:\n"); + echo json_encode($stmts, JSON_PRETTY_PRINT), "\n"; + } elseif ('var-dump' === $operation) { + fwrite(STDERR, "==> var_dump():\n"); + var_dump($stmts); + } elseif ('resolve-names' === $operation) { + fwrite(STDERR, "==> Resolved names.\n"); + $stmts = $traverser->traverse($stmts); + } + } +} + +function formatErrorMessage(PhpParser\Error $e, $code, $withColumnInfo) { + if ($withColumnInfo && $e->hasColumnInfo()) { + return $e->getMessageWithColumnInfo($code); + } else { + return $e->getMessage(); + } +} + +function showHelp($error = '') { + if ($error) { + fwrite(STDERR, $error . "\n\n"); + } + fwrite($error ? STDERR : STDOUT, <<<'OUTPUT' +Usage: php-parse [operations] file1.php [file2.php ...] + or: php-parse [operations] "<?php code" +Turn PHP source code into an abstract syntax tree. + +Operations is a list of the following options (--dump by default): + + -d, --dump Dump nodes using NodeDumper + -p, --pretty-print Pretty print file using PrettyPrinter\Standard + -j, --json-dump Print json_encode() result + --var-dump var_dump() nodes (for exact structure) + -N, --resolve-names Resolve names using NodeVisitor\NameResolver + -c, --with-column-info Show column-numbers for errors (if available) + -P, --with-positions Show positions in node dumps + -r, --with-recovery Use parsing with error recovery + --version=VERSION Target specific PHP version (default: newest) + -h, --help Display this page + +Example: + php-parse -d -p -N -d file.php + + Dumps nodes, pretty prints them, then resolves names and dumps them again. + + +OUTPUT + ); + exit($error ? 1 : 0); +} + +function parseArgs($args) { + $operations = []; + $files = []; + $attributes = [ + 'with-column-info' => false, + 'with-positions' => false, + 'with-recovery' => false, + 'version' => PhpParser\PhpVersion::getNewestSupported(), + ]; + + array_shift($args); + $parseOptions = true; + foreach ($args as $arg) { + if (!$parseOptions) { + $files[] = $arg; + continue; + } + + switch ($arg) { + case '--dump': + case '-d': + $operations[] = 'dump'; + break; + case '--pretty-print': + case '-p': + $operations[] = 'pretty-print'; + break; + case '--json-dump': + case '-j': + $operations[] = 'json-dump'; + break; + case '--var-dump': + $operations[] = 'var-dump'; + break; + case '--resolve-names': + case '-N'; + $operations[] = 'resolve-names'; + break; + case '--with-column-info': + case '-c'; + $attributes['with-column-info'] = true; + break; + case '--with-positions': + case '-P': + $attributes['with-positions'] = true; + break; + case '--with-recovery': + case '-r': + $attributes['with-recovery'] = true; + break; + case '--help': + case '-h'; + showHelp(); + break; + case '--': + $parseOptions = false; + break; + default: + if (preg_match('/^--version=(.*)$/', $arg, $matches)) { + $attributes['version'] = PhpParser\PhpVersion::fromString($matches[1]); + } elseif ($arg[0] === '-' && \strlen($arg[0]) > 1) { + showHelp("Invalid operation $arg."); + } else { + $files[] = $arg; + } + } + } + + return [$operations, $files, $attributes]; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/composer.json b/php/libraries/composer/vendor/nikic/php-parser/composer.json new file mode 100644 index 0000000..b4b1bca --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/composer.json @@ -0,0 +1,43 @@ +{ + "name": "nikic/php-parser", + "type": "library", + "description": "A PHP parser written in PHP", + "keywords": [ + "php", + "parser" + ], + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Nikita Popov" + } + ], + "require": { + "php": ">=7.4", + "ext-tokenizer": "*", + "ext-json": "*", + "ext-ctype": "*" + }, + "require-dev": { + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", + "ircmaxell/php-yacc": "^0.0.7" + }, + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "autoload-dev": { + "psr-4": { + "PhpParser\\": "test/PhpParser/" + } + }, + "bin": [ + "bin/php-parse" + ] +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder.php new file mode 100644 index 0000000..d6aa124 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder.php @@ -0,0 +1,12 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +interface Builder { + /** + * Returns the built node. + * + * @return Node The built node + */ + public function getNode(): Node; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/ClassConst.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/ClassConst.php new file mode 100644 index 0000000..fa5dc10 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/ClassConst.php @@ -0,0 +1,150 @@ +<?php + +declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Const_; +use PhpParser\Node\Identifier; +use PhpParser\Node\Stmt; + +class ClassConst implements PhpParser\Builder { + protected int $flags = 0; + /** @var array<string, mixed> */ + protected array $attributes = []; + /** @var list<Const_> */ + protected array $constants = []; + + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + /** @var Identifier|Node\Name|Node\ComplexType|null */ + protected ?Node $type = null; + + /** + * Creates a class constant builder + * + * @param string|Identifier $name Name + * @param Node\Expr|bool|null|int|float|string|array $value Value + */ + public function __construct($name, $value) { + $this->constants = [new Const_($name, BuilderHelpers::normalizeValue($value))]; + } + + /** + * Add another constant to const group + * + * @param string|Identifier $name Name + * @param Node\Expr|bool|null|int|float|string|array $value Value + * + * @return $this The builder instance (for fluid interface) + */ + public function addConst($name, $value) { + $this->constants[] = new Const_($name, BuilderHelpers::normalizeValue($value)); + + return $this; + } + + /** + * Makes the constant public. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePublic() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PUBLIC); + + return $this; + } + + /** + * Makes the constant protected. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeProtected() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PROTECTED); + + return $this; + } + + /** + * Makes the constant private. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePrivate() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PRIVATE); + + return $this; + } + + /** + * Makes the constant final. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeFinal() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::FINAL); + + return $this; + } + + /** + * Sets doc comment for the constant. + * + * @param PhpParser\Comment\Doc|string $docComment Doc comment to set + * + * @return $this The builder instance (for fluid interface) + */ + public function setDocComment($docComment) { + $this->attributes = [ + 'comments' => [BuilderHelpers::normalizeDocComment($docComment)] + ]; + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Sets the constant type. + * + * @param string|Node\Name|Identifier|Node\ComplexType $type + * + * @return $this + */ + public function setType($type) { + $this->type = BuilderHelpers::normalizeType($type); + + return $this; + } + + /** + * Returns the built class node. + * + * @return Stmt\ClassConst The built constant node + */ + public function getNode(): PhpParser\Node { + return new Stmt\ClassConst( + $this->constants, + $this->flags, + $this->attributes, + $this->attributeGroups, + $this->type + ); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Class_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Class_.php new file mode 100644 index 0000000..6f39431 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Class_.php @@ -0,0 +1,151 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt; + +class Class_ extends Declaration { + protected string $name; + protected ?Name $extends = null; + /** @var list<Name> */ + protected array $implements = []; + protected int $flags = 0; + /** @var list<Stmt\TraitUse> */ + protected array $uses = []; + /** @var list<Stmt\ClassConst> */ + protected array $constants = []; + /** @var list<Stmt\Property> */ + protected array $properties = []; + /** @var list<Stmt\ClassMethod> */ + protected array $methods = []; + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates a class builder. + * + * @param string $name Name of the class + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Extends a class. + * + * @param Name|string $class Name of class to extend + * + * @return $this The builder instance (for fluid interface) + */ + public function extend($class) { + $this->extends = BuilderHelpers::normalizeName($class); + + return $this; + } + + /** + * Implements one or more interfaces. + * + * @param Name|string ...$interfaces Names of interfaces to implement + * + * @return $this The builder instance (for fluid interface) + */ + public function implement(...$interfaces) { + foreach ($interfaces as $interface) { + $this->implements[] = BuilderHelpers::normalizeName($interface); + } + + return $this; + } + + /** + * Makes the class abstract. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeAbstract() { + $this->flags = BuilderHelpers::addClassModifier($this->flags, Modifiers::ABSTRACT); + + return $this; + } + + /** + * Makes the class final. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeFinal() { + $this->flags = BuilderHelpers::addClassModifier($this->flags, Modifiers::FINAL); + + return $this; + } + + /** + * Makes the class readonly. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeReadonly() { + $this->flags = BuilderHelpers::addClassModifier($this->flags, Modifiers::READONLY); + + return $this; + } + + /** + * Adds a statement. + * + * @param Stmt|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + $stmt = BuilderHelpers::normalizeNode($stmt); + + if ($stmt instanceof Stmt\Property) { + $this->properties[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassMethod) { + $this->methods[] = $stmt; + } elseif ($stmt instanceof Stmt\TraitUse) { + $this->uses[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassConst) { + $this->constants[] = $stmt; + } else { + throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType())); + } + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built class node. + * + * @return Stmt\Class_ The built class node + */ + public function getNode(): PhpParser\Node { + return new Stmt\Class_($this->name, [ + 'flags' => $this->flags, + 'extends' => $this->extends, + 'implements' => $this->implements, + 'stmts' => array_merge($this->uses, $this->constants, $this->properties, $this->methods), + 'attrGroups' => $this->attributeGroups, + ], $this->attributes); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Declaration.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Declaration.php new file mode 100644 index 0000000..488b721 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Declaration.php @@ -0,0 +1,50 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; + +abstract class Declaration implements PhpParser\Builder { + /** @var array<string, mixed> */ + protected array $attributes = []; + + /** + * Adds a statement. + * + * @param PhpParser\Node\Stmt|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + abstract public function addStmt($stmt); + + /** + * Adds multiple statements. + * + * @param (PhpParser\Node\Stmt|PhpParser\Builder)[] $stmts The statements to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmts(array $stmts) { + foreach ($stmts as $stmt) { + $this->addStmt($stmt); + } + + return $this; + } + + /** + * Sets doc comment for the declaration. + * + * @param PhpParser\Comment\Doc|string $docComment Doc comment to set + * + * @return $this The builder instance (for fluid interface) + */ + public function setDocComment($docComment) { + $this->attributes['comments'] = [ + BuilderHelpers::normalizeDocComment($docComment) + ]; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/EnumCase.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/EnumCase.php new file mode 100644 index 0000000..04058bf --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/EnumCase.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Identifier; +use PhpParser\Node\Stmt; + +class EnumCase implements PhpParser\Builder { + /** @var Identifier|string */ + protected $name; + /** @var ?Node\Expr */ + protected ?Node\Expr $value = null; + /** @var array<string, mixed> */ + protected array $attributes = []; + + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates an enum case builder. + * + * @param string|Identifier $name Name + */ + public function __construct($name) { + $this->name = $name; + } + + /** + * Sets the value. + * + * @param Node\Expr|string|int $value + * + * @return $this + */ + public function setValue($value) { + $this->value = BuilderHelpers::normalizeValue($value); + + return $this; + } + + /** + * Sets doc comment for the constant. + * + * @param PhpParser\Comment\Doc|string $docComment Doc comment to set + * + * @return $this The builder instance (for fluid interface) + */ + public function setDocComment($docComment) { + $this->attributes = [ + 'comments' => [BuilderHelpers::normalizeDocComment($docComment)] + ]; + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built enum case node. + * + * @return Stmt\EnumCase The built constant node + */ + public function getNode(): PhpParser\Node { + return new Stmt\EnumCase( + $this->name, + $this->value, + $this->attributeGroups, + $this->attributes + ); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Enum_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Enum_.php new file mode 100644 index 0000000..c00df03 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Enum_.php @@ -0,0 +1,116 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt; + +class Enum_ extends Declaration { + protected string $name; + protected ?Identifier $scalarType = null; + /** @var list<Name> */ + protected array $implements = []; + /** @var list<Stmt\TraitUse> */ + protected array $uses = []; + /** @var list<Stmt\EnumCase> */ + protected array $enumCases = []; + /** @var list<Stmt\ClassConst> */ + protected array $constants = []; + /** @var list<Stmt\ClassMethod> */ + protected array $methods = []; + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates an enum builder. + * + * @param string $name Name of the enum + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Sets the scalar type. + * + * @param string|Identifier $scalarType + * + * @return $this + */ + public function setScalarType($scalarType) { + $this->scalarType = BuilderHelpers::normalizeType($scalarType); + + return $this; + } + + /** + * Implements one or more interfaces. + * + * @param Name|string ...$interfaces Names of interfaces to implement + * + * @return $this The builder instance (for fluid interface) + */ + public function implement(...$interfaces) { + foreach ($interfaces as $interface) { + $this->implements[] = BuilderHelpers::normalizeName($interface); + } + + return $this; + } + + /** + * Adds a statement. + * + * @param Stmt|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + $stmt = BuilderHelpers::normalizeNode($stmt); + + if ($stmt instanceof Stmt\EnumCase) { + $this->enumCases[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassMethod) { + $this->methods[] = $stmt; + } elseif ($stmt instanceof Stmt\TraitUse) { + $this->uses[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassConst) { + $this->constants[] = $stmt; + } else { + throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType())); + } + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built class node. + * + * @return Stmt\Enum_ The built enum node + */ + public function getNode(): PhpParser\Node { + return new Stmt\Enum_($this->name, [ + 'scalarType' => $this->scalarType, + 'implements' => $this->implements, + 'stmts' => array_merge($this->uses, $this->enumCases, $this->constants, $this->methods), + 'attrGroups' => $this->attributeGroups, + ], $this->attributes); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/FunctionLike.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/FunctionLike.php new file mode 100644 index 0000000..ff79cb6 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/FunctionLike.php @@ -0,0 +1,73 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser\BuilderHelpers; +use PhpParser\Node; + +abstract class FunctionLike extends Declaration { + protected bool $returnByRef = false; + /** @var Node\Param[] */ + protected array $params = []; + + /** @var Node\Identifier|Node\Name|Node\ComplexType|null */ + protected ?Node $returnType = null; + + /** + * Make the function return by reference. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeReturnByRef() { + $this->returnByRef = true; + + return $this; + } + + /** + * Adds a parameter. + * + * @param Node\Param|Param $param The parameter to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addParam($param) { + $param = BuilderHelpers::normalizeNode($param); + + if (!$param instanceof Node\Param) { + throw new \LogicException(sprintf('Expected parameter node, got "%s"', $param->getType())); + } + + $this->params[] = $param; + + return $this; + } + + /** + * Adds multiple parameters. + * + * @param (Node\Param|Param)[] $params The parameters to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addParams(array $params) { + foreach ($params as $param) { + $this->addParam($param); + } + + return $this; + } + + /** + * Sets the return type for PHP 7. + * + * @param string|Node\Name|Node\Identifier|Node\ComplexType $type + * + * @return $this The builder instance (for fluid interface) + */ + public function setReturnType($type) { + $this->returnType = BuilderHelpers::normalizeType($type); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Function_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Function_.php new file mode 100644 index 0000000..48f5f69 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Function_.php @@ -0,0 +1,67 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class Function_ extends FunctionLike { + protected string $name; + /** @var list<Stmt> */ + protected array $stmts = []; + + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates a function builder. + * + * @param string $name Name of the function + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Adds a statement. + * + * @param Node|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + $this->stmts[] = BuilderHelpers::normalizeStmt($stmt); + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built function node. + * + * @return Stmt\Function_ The built function node + */ + public function getNode(): Node { + return new Stmt\Function_($this->name, [ + 'byRef' => $this->returnByRef, + 'params' => $this->params, + 'returnType' => $this->returnType, + 'stmts' => $this->stmts, + 'attrGroups' => $this->attributeGroups, + ], $this->attributes); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Interface_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Interface_.php new file mode 100644 index 0000000..13dd3f7 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Interface_.php @@ -0,0 +1,94 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt; + +class Interface_ extends Declaration { + protected string $name; + /** @var list<Name> */ + protected array $extends = []; + /** @var list<Stmt\ClassConst> */ + protected array $constants = []; + /** @var list<Stmt\ClassMethod> */ + protected array $methods = []; + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates an interface builder. + * + * @param string $name Name of the interface + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Extends one or more interfaces. + * + * @param Name|string ...$interfaces Names of interfaces to extend + * + * @return $this The builder instance (for fluid interface) + */ + public function extend(...$interfaces) { + foreach ($interfaces as $interface) { + $this->extends[] = BuilderHelpers::normalizeName($interface); + } + + return $this; + } + + /** + * Adds a statement. + * + * @param Stmt|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + $stmt = BuilderHelpers::normalizeNode($stmt); + + if ($stmt instanceof Stmt\ClassConst) { + $this->constants[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassMethod) { + // we erase all statements in the body of an interface method + $stmt->stmts = null; + $this->methods[] = $stmt; + } else { + throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType())); + } + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built interface node. + * + * @return Stmt\Interface_ The built interface node + */ + public function getNode(): PhpParser\Node { + return new Stmt\Interface_($this->name, [ + 'extends' => $this->extends, + 'stmts' => array_merge($this->constants, $this->methods), + 'attrGroups' => $this->attributeGroups, + ], $this->attributes); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Method.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Method.php new file mode 100644 index 0000000..8358dbe --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Method.php @@ -0,0 +1,147 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class Method extends FunctionLike { + protected string $name; + + protected int $flags = 0; + + /** @var list<Stmt>|null */ + protected ?array $stmts = []; + + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates a method builder. + * + * @param string $name Name of the method + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Makes the method public. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePublic() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PUBLIC); + + return $this; + } + + /** + * Makes the method protected. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeProtected() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PROTECTED); + + return $this; + } + + /** + * Makes the method private. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePrivate() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PRIVATE); + + return $this; + } + + /** + * Makes the method static. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeStatic() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::STATIC); + + return $this; + } + + /** + * Makes the method abstract. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeAbstract() { + if (!empty($this->stmts)) { + throw new \LogicException('Cannot make method with statements abstract'); + } + + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::ABSTRACT); + $this->stmts = null; // abstract methods don't have statements + + return $this; + } + + /** + * Makes the method final. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeFinal() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::FINAL); + + return $this; + } + + /** + * Adds a statement. + * + * @param Node|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + if (null === $this->stmts) { + throw new \LogicException('Cannot add statements to an abstract method'); + } + + $this->stmts[] = BuilderHelpers::normalizeStmt($stmt); + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built method node. + * + * @return Stmt\ClassMethod The built method node + */ + public function getNode(): Node { + return new Stmt\ClassMethod($this->name, [ + 'flags' => $this->flags, + 'byRef' => $this->returnByRef, + 'params' => $this->params, + 'returnType' => $this->returnType, + 'stmts' => $this->stmts, + 'attrGroups' => $this->attributeGroups, + ], $this->attributes); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Namespace_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Namespace_.php new file mode 100644 index 0000000..80fe6f8 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Namespace_.php @@ -0,0 +1,45 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class Namespace_ extends Declaration { + private ?Node\Name $name; + /** @var Stmt[] */ + private array $stmts = []; + + /** + * Creates a namespace builder. + * + * @param Node\Name|string|null $name Name of the namespace + */ + public function __construct($name) { + $this->name = null !== $name ? BuilderHelpers::normalizeName($name) : null; + } + + /** + * Adds a statement. + * + * @param Node|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + $this->stmts[] = BuilderHelpers::normalizeStmt($stmt); + + return $this; + } + + /** + * Returns the built node. + * + * @return Stmt\Namespace_ The built node + */ + public function getNode(): Node { + return new Stmt\Namespace_($this->name, $this->stmts, $this->attributes); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Param.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Param.php new file mode 100644 index 0000000..f439e87 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Param.php @@ -0,0 +1,149 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Modifiers; +use PhpParser\Node; + +class Param implements PhpParser\Builder { + protected string $name; + protected ?Node\Expr $default = null; + /** @var Node\Identifier|Node\Name|Node\ComplexType|null */ + protected ?Node $type = null; + protected bool $byRef = false; + protected int $flags = 0; + protected bool $variadic = false; + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates a parameter builder. + * + * @param string $name Name of the parameter + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Sets default value for the parameter. + * + * @param mixed $value Default value to use + * + * @return $this The builder instance (for fluid interface) + */ + public function setDefault($value) { + $this->default = BuilderHelpers::normalizeValue($value); + + return $this; + } + + /** + * Sets type for the parameter. + * + * @param string|Node\Name|Node\Identifier|Node\ComplexType $type Parameter type + * + * @return $this The builder instance (for fluid interface) + */ + public function setType($type) { + $this->type = BuilderHelpers::normalizeType($type); + if ($this->type == 'void') { + throw new \LogicException('Parameter type cannot be void'); + } + + return $this; + } + + /** + * Make the parameter accept the value by reference. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeByRef() { + $this->byRef = true; + + return $this; + } + + /** + * Make the parameter variadic + * + * @return $this The builder instance (for fluid interface) + */ + public function makeVariadic() { + $this->variadic = true; + + return $this; + } + + /** + * Makes the (promoted) parameter public. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePublic() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PUBLIC); + + return $this; + } + + /** + * Makes the (promoted) parameter protected. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeProtected() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PROTECTED); + + return $this; + } + + /** + * Makes the (promoted) parameter private. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePrivate() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PRIVATE); + + return $this; + } + + /** + * Makes the (promoted) parameter readonly. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeReadonly() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::READONLY); + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built parameter node. + * + * @return Node\Param The built parameter node + */ + public function getNode(): Node { + return new Node\Param( + new Node\Expr\Variable($this->name), + $this->default, $this->type, $this->byRef, $this->variadic, [], $this->flags, $this->attributeGroups + ); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Property.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Property.php new file mode 100644 index 0000000..3fc96d9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Property.php @@ -0,0 +1,161 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt; +use PhpParser\Node\ComplexType; + +class Property implements PhpParser\Builder { + protected string $name; + + protected int $flags = 0; + + protected ?Node\Expr $default = null; + /** @var array<string, mixed> */ + protected array $attributes = []; + /** @var null|Identifier|Name|ComplexType */ + protected ?Node $type = null; + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates a property builder. + * + * @param string $name Name of the property + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Makes the property public. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePublic() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PUBLIC); + + return $this; + } + + /** + * Makes the property protected. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeProtected() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PROTECTED); + + return $this; + } + + /** + * Makes the property private. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePrivate() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::PRIVATE); + + return $this; + } + + /** + * Makes the property static. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeStatic() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::STATIC); + + return $this; + } + + /** + * Makes the property readonly. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeReadonly() { + $this->flags = BuilderHelpers::addModifier($this->flags, Modifiers::READONLY); + + return $this; + } + + /** + * Sets default value for the property. + * + * @param mixed $value Default value to use + * + * @return $this The builder instance (for fluid interface) + */ + public function setDefault($value) { + $this->default = BuilderHelpers::normalizeValue($value); + + return $this; + } + + /** + * Sets doc comment for the property. + * + * @param PhpParser\Comment\Doc|string $docComment Doc comment to set + * + * @return $this The builder instance (for fluid interface) + */ + public function setDocComment($docComment) { + $this->attributes = [ + 'comments' => [BuilderHelpers::normalizeDocComment($docComment)] + ]; + + return $this; + } + + /** + * Sets the property type for PHP 7.4+. + * + * @param string|Name|Identifier|ComplexType $type + * + * @return $this + */ + public function setType($type) { + $this->type = BuilderHelpers::normalizeType($type); + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built class node. + * + * @return Stmt\Property The built property node + */ + public function getNode(): PhpParser\Node { + return new Stmt\Property( + $this->flags !== 0 ? $this->flags : Modifiers::PUBLIC, + [ + new Node\PropertyItem($this->name, $this->default) + ], + $this->attributes, + $this->type, + $this->attributeGroups + ); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUse.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUse.php new file mode 100644 index 0000000..cf21c82 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUse.php @@ -0,0 +1,65 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser\Builder; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class TraitUse implements Builder { + /** @var Node\Name[] */ + protected array $traits = []; + /** @var Stmt\TraitUseAdaptation[] */ + protected array $adaptations = []; + + /** + * Creates a trait use builder. + * + * @param Node\Name|string ...$traits Names of used traits + */ + public function __construct(...$traits) { + foreach ($traits as $trait) { + $this->and($trait); + } + } + + /** + * Adds used trait. + * + * @param Node\Name|string $trait Trait name + * + * @return $this The builder instance (for fluid interface) + */ + public function and($trait) { + $this->traits[] = BuilderHelpers::normalizeName($trait); + return $this; + } + + /** + * Adds trait adaptation. + * + * @param Stmt\TraitUseAdaptation|Builder\TraitUseAdaptation $adaptation Trait adaptation + * + * @return $this The builder instance (for fluid interface) + */ + public function with($adaptation) { + $adaptation = BuilderHelpers::normalizeNode($adaptation); + + if (!$adaptation instanceof Stmt\TraitUseAdaptation) { + throw new \LogicException('Adaptation must have type TraitUseAdaptation'); + } + + $this->adaptations[] = $adaptation; + return $this; + } + + /** + * Returns the built node. + * + * @return Node The built node + */ + public function getNode(): Node { + return new Stmt\TraitUse($this->traits, $this->adaptations); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUseAdaptation.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUseAdaptation.php new file mode 100644 index 0000000..fee0958 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUseAdaptation.php @@ -0,0 +1,145 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser\Builder; +use PhpParser\BuilderHelpers; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class TraitUseAdaptation implements Builder { + private const TYPE_UNDEFINED = 0; + private const TYPE_ALIAS = 1; + private const TYPE_PRECEDENCE = 2; + + protected int $type; + protected ?Node\Name $trait; + protected Node\Identifier $method; + protected ?int $modifier = null; + protected ?Node\Identifier $alias = null; + /** @var Node\Name[] */ + protected array $insteadof = []; + + /** + * Creates a trait use adaptation builder. + * + * @param Node\Name|string|null $trait Name of adapted trait + * @param Node\Identifier|string $method Name of adapted method + */ + public function __construct($trait, $method) { + $this->type = self::TYPE_UNDEFINED; + + $this->trait = is_null($trait) ? null : BuilderHelpers::normalizeName($trait); + $this->method = BuilderHelpers::normalizeIdentifier($method); + } + + /** + * Sets alias of method. + * + * @param Node\Identifier|string $alias Alias for adapted method + * + * @return $this The builder instance (for fluid interface) + */ + public function as($alias) { + if ($this->type === self::TYPE_UNDEFINED) { + $this->type = self::TYPE_ALIAS; + } + + if ($this->type !== self::TYPE_ALIAS) { + throw new \LogicException('Cannot set alias for not alias adaptation buider'); + } + + $this->alias = BuilderHelpers::normalizeIdentifier($alias); + return $this; + } + + /** + * Sets adapted method public. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePublic() { + $this->setModifier(Modifiers::PUBLIC); + return $this; + } + + /** + * Sets adapted method protected. + * + * @return $this The builder instance (for fluid interface) + */ + public function makeProtected() { + $this->setModifier(Modifiers::PROTECTED); + return $this; + } + + /** + * Sets adapted method private. + * + * @return $this The builder instance (for fluid interface) + */ + public function makePrivate() { + $this->setModifier(Modifiers::PRIVATE); + return $this; + } + + /** + * Adds overwritten traits. + * + * @param Node\Name|string ...$traits Traits for overwrite + * + * @return $this The builder instance (for fluid interface) + */ + public function insteadof(...$traits) { + if ($this->type === self::TYPE_UNDEFINED) { + if (is_null($this->trait)) { + throw new \LogicException('Precedence adaptation must have trait'); + } + + $this->type = self::TYPE_PRECEDENCE; + } + + if ($this->type !== self::TYPE_PRECEDENCE) { + throw new \LogicException('Cannot add overwritten traits for not precedence adaptation buider'); + } + + foreach ($traits as $trait) { + $this->insteadof[] = BuilderHelpers::normalizeName($trait); + } + + return $this; + } + + protected function setModifier(int $modifier): void { + if ($this->type === self::TYPE_UNDEFINED) { + $this->type = self::TYPE_ALIAS; + } + + if ($this->type !== self::TYPE_ALIAS) { + throw new \LogicException('Cannot set access modifier for not alias adaptation buider'); + } + + if (is_null($this->modifier)) { + $this->modifier = $modifier; + } else { + throw new \LogicException('Multiple access type modifiers are not allowed'); + } + } + + /** + * Returns the built node. + * + * @return Node The built node + */ + public function getNode(): Node { + switch ($this->type) { + case self::TYPE_ALIAS: + return new Stmt\TraitUseAdaptation\Alias($this->trait, $this->method, $this->modifier, $this->alias); + case self::TYPE_PRECEDENCE: + return new Stmt\TraitUseAdaptation\Precedence($this->trait, $this->method, $this->insteadof); + default: + throw new \LogicException('Type of adaptation is not defined'); + } + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Trait_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Trait_.php new file mode 100644 index 0000000..ffa1bd5 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Trait_.php @@ -0,0 +1,83 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class Trait_ extends Declaration { + protected string $name; + /** @var list<Stmt\TraitUse> */ + protected array $uses = []; + /** @var list<Stmt\ClassConst> */ + protected array $constants = []; + /** @var list<Stmt\Property> */ + protected array $properties = []; + /** @var list<Stmt\ClassMethod> */ + protected array $methods = []; + /** @var list<Node\AttributeGroup> */ + protected array $attributeGroups = []; + + /** + * Creates an interface builder. + * + * @param string $name Name of the interface + */ + public function __construct(string $name) { + $this->name = $name; + } + + /** + * Adds a statement. + * + * @param Stmt|PhpParser\Builder $stmt The statement to add + * + * @return $this The builder instance (for fluid interface) + */ + public function addStmt($stmt) { + $stmt = BuilderHelpers::normalizeNode($stmt); + + if ($stmt instanceof Stmt\Property) { + $this->properties[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassMethod) { + $this->methods[] = $stmt; + } elseif ($stmt instanceof Stmt\TraitUse) { + $this->uses[] = $stmt; + } elseif ($stmt instanceof Stmt\ClassConst) { + $this->constants[] = $stmt; + } else { + throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType())); + } + + return $this; + } + + /** + * Adds an attribute group. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return $this The builder instance (for fluid interface) + */ + public function addAttribute($attribute) { + $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); + + return $this; + } + + /** + * Returns the built trait node. + * + * @return Stmt\Trait_ The built interface node + */ + public function getNode(): PhpParser\Node { + return new Stmt\Trait_( + $this->name, [ + 'stmts' => array_merge($this->uses, $this->constants, $this->properties, $this->methods), + 'attrGroups' => $this->attributeGroups, + ], $this->attributes + ); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Use_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Use_.php new file mode 100644 index 0000000..b82cf13 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Builder/Use_.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Builder; + +use PhpParser\Builder; +use PhpParser\BuilderHelpers; +use PhpParser\Node; +use PhpParser\Node\Stmt; + +class Use_ implements Builder { + protected Node\Name $name; + /** @var Stmt\Use_::TYPE_* */ + protected int $type; + protected ?string $alias = null; + + /** + * Creates a name use (alias) builder. + * + * @param Node\Name|string $name Name of the entity (namespace, class, function, constant) to alias + * @param Stmt\Use_::TYPE_* $type One of the Stmt\Use_::TYPE_* constants + */ + public function __construct($name, int $type) { + $this->name = BuilderHelpers::normalizeName($name); + $this->type = $type; + } + + /** + * Sets alias for used name. + * + * @param string $alias Alias to use (last component of full name by default) + * + * @return $this The builder instance (for fluid interface) + */ + public function as(string $alias) { + $this->alias = $alias; + return $this; + } + + /** + * Returns the built node. + * + * @return Stmt\Use_ The built node + */ + public function getNode(): Node { + return new Stmt\Use_([ + new Node\UseItem($this->name, $this->alias) + ], $this->type); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/BuilderFactory.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/BuilderFactory.php new file mode 100644 index 0000000..b7efe5e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/BuilderFactory.php @@ -0,0 +1,375 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\BinaryOp\Concat; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt\Use_; + +class BuilderFactory { + /** + * Creates an attribute node. + * + * @param string|Name $name Name of the attribute + * @param array $args Attribute named arguments + */ + public function attribute($name, array $args = []): Node\Attribute { + return new Node\Attribute( + BuilderHelpers::normalizeName($name), + $this->args($args) + ); + } + + /** + * Creates a namespace builder. + * + * @param null|string|Node\Name $name Name of the namespace + * + * @return Builder\Namespace_ The created namespace builder + */ + public function namespace($name): Builder\Namespace_ { + return new Builder\Namespace_($name); + } + + /** + * Creates a class builder. + * + * @param string $name Name of the class + * + * @return Builder\Class_ The created class builder + */ + public function class(string $name): Builder\Class_ { + return new Builder\Class_($name); + } + + /** + * Creates an interface builder. + * + * @param string $name Name of the interface + * + * @return Builder\Interface_ The created interface builder + */ + public function interface(string $name): Builder\Interface_ { + return new Builder\Interface_($name); + } + + /** + * Creates a trait builder. + * + * @param string $name Name of the trait + * + * @return Builder\Trait_ The created trait builder + */ + public function trait(string $name): Builder\Trait_ { + return new Builder\Trait_($name); + } + + /** + * Creates an enum builder. + * + * @param string $name Name of the enum + * + * @return Builder\Enum_ The created enum builder + */ + public function enum(string $name): Builder\Enum_ { + return new Builder\Enum_($name); + } + + /** + * Creates a trait use builder. + * + * @param Node\Name|string ...$traits Trait names + * + * @return Builder\TraitUse The created trait use builder + */ + public function useTrait(...$traits): Builder\TraitUse { + return new Builder\TraitUse(...$traits); + } + + /** + * Creates a trait use adaptation builder. + * + * @param Node\Name|string|null $trait Trait name + * @param Node\Identifier|string $method Method name + * + * @return Builder\TraitUseAdaptation The created trait use adaptation builder + */ + public function traitUseAdaptation($trait, $method = null): Builder\TraitUseAdaptation { + if ($method === null) { + $method = $trait; + $trait = null; + } + + return new Builder\TraitUseAdaptation($trait, $method); + } + + /** + * Creates a method builder. + * + * @param string $name Name of the method + * + * @return Builder\Method The created method builder + */ + public function method(string $name): Builder\Method { + return new Builder\Method($name); + } + + /** + * Creates a parameter builder. + * + * @param string $name Name of the parameter + * + * @return Builder\Param The created parameter builder + */ + public function param(string $name): Builder\Param { + return new Builder\Param($name); + } + + /** + * Creates a property builder. + * + * @param string $name Name of the property + * + * @return Builder\Property The created property builder + */ + public function property(string $name): Builder\Property { + return new Builder\Property($name); + } + + /** + * Creates a function builder. + * + * @param string $name Name of the function + * + * @return Builder\Function_ The created function builder + */ + public function function(string $name): Builder\Function_ { + return new Builder\Function_($name); + } + + /** + * Creates a namespace/class use builder. + * + * @param Node\Name|string $name Name of the entity (namespace or class) to alias + * + * @return Builder\Use_ The created use builder + */ + public function use($name): Builder\Use_ { + return new Builder\Use_($name, Use_::TYPE_NORMAL); + } + + /** + * Creates a function use builder. + * + * @param Node\Name|string $name Name of the function to alias + * + * @return Builder\Use_ The created use function builder + */ + public function useFunction($name): Builder\Use_ { + return new Builder\Use_($name, Use_::TYPE_FUNCTION); + } + + /** + * Creates a constant use builder. + * + * @param Node\Name|string $name Name of the const to alias + * + * @return Builder\Use_ The created use const builder + */ + public function useConst($name): Builder\Use_ { + return new Builder\Use_($name, Use_::TYPE_CONSTANT); + } + + /** + * Creates a class constant builder. + * + * @param string|Identifier $name Name + * @param Node\Expr|bool|null|int|float|string|array $value Value + * + * @return Builder\ClassConst The created use const builder + */ + public function classConst($name, $value): Builder\ClassConst { + return new Builder\ClassConst($name, $value); + } + + /** + * Creates an enum case builder. + * + * @param string|Identifier $name Name + * + * @return Builder\EnumCase The created use const builder + */ + public function enumCase($name): Builder\EnumCase { + return new Builder\EnumCase($name); + } + + /** + * Creates node a for a literal value. + * + * @param Expr|bool|null|int|float|string|array $value $value + */ + public function val($value): Expr { + return BuilderHelpers::normalizeValue($value); + } + + /** + * Creates variable node. + * + * @param string|Expr $name Name + */ + public function var($name): Expr\Variable { + if (!\is_string($name) && !$name instanceof Expr) { + throw new \LogicException('Variable name must be string or Expr'); + } + + return new Expr\Variable($name); + } + + /** + * Normalizes an argument list. + * + * Creates Arg nodes for all arguments and converts literal values to expressions. + * + * @param array $args List of arguments to normalize + * + * @return list<Arg> + */ + public function args(array $args): array { + $normalizedArgs = []; + foreach ($args as $key => $arg) { + if (!($arg instanceof Arg)) { + $arg = new Arg(BuilderHelpers::normalizeValue($arg)); + } + if (\is_string($key)) { + $arg->name = BuilderHelpers::normalizeIdentifier($key); + } + $normalizedArgs[] = $arg; + } + return $normalizedArgs; + } + + /** + * Creates a function call node. + * + * @param string|Name|Expr $name Function name + * @param array $args Function arguments + */ + public function funcCall($name, array $args = []): Expr\FuncCall { + return new Expr\FuncCall( + BuilderHelpers::normalizeNameOrExpr($name), + $this->args($args) + ); + } + + /** + * Creates a method call node. + * + * @param Expr $var Variable the method is called on + * @param string|Identifier|Expr $name Method name + * @param array $args Method arguments + */ + public function methodCall(Expr $var, $name, array $args = []): Expr\MethodCall { + return new Expr\MethodCall( + $var, + BuilderHelpers::normalizeIdentifierOrExpr($name), + $this->args($args) + ); + } + + /** + * Creates a static method call node. + * + * @param string|Name|Expr $class Class name + * @param string|Identifier|Expr $name Method name + * @param array $args Method arguments + */ + public function staticCall($class, $name, array $args = []): Expr\StaticCall { + return new Expr\StaticCall( + BuilderHelpers::normalizeNameOrExpr($class), + BuilderHelpers::normalizeIdentifierOrExpr($name), + $this->args($args) + ); + } + + /** + * Creates an object creation node. + * + * @param string|Name|Expr $class Class name + * @param array $args Constructor arguments + */ + public function new($class, array $args = []): Expr\New_ { + return new Expr\New_( + BuilderHelpers::normalizeNameOrExpr($class), + $this->args($args) + ); + } + + /** + * Creates a constant fetch node. + * + * @param string|Name $name Constant name + */ + public function constFetch($name): Expr\ConstFetch { + return new Expr\ConstFetch(BuilderHelpers::normalizeName($name)); + } + + /** + * Creates a property fetch node. + * + * @param Expr $var Variable holding object + * @param string|Identifier|Expr $name Property name + */ + public function propertyFetch(Expr $var, $name): Expr\PropertyFetch { + return new Expr\PropertyFetch($var, BuilderHelpers::normalizeIdentifierOrExpr($name)); + } + + /** + * Creates a class constant fetch node. + * + * @param string|Name|Expr $class Class name + * @param string|Identifier|Expr $name Constant name + */ + public function classConstFetch($class, $name): Expr\ClassConstFetch { + return new Expr\ClassConstFetch( + BuilderHelpers::normalizeNameOrExpr($class), + BuilderHelpers::normalizeIdentifierOrExpr($name) + ); + } + + /** + * Creates nested Concat nodes from a list of expressions. + * + * @param Expr|string ...$exprs Expressions or literal strings + */ + public function concat(...$exprs): Concat { + $numExprs = count($exprs); + if ($numExprs < 2) { + throw new \LogicException('Expected at least two expressions'); + } + + $lastConcat = $this->normalizeStringExpr($exprs[0]); + for ($i = 1; $i < $numExprs; $i++) { + $lastConcat = new Concat($lastConcat, $this->normalizeStringExpr($exprs[$i])); + } + return $lastConcat; + } + + /** + * @param string|Expr $expr + */ + private function normalizeStringExpr($expr): Expr { + if ($expr instanceof Expr) { + return $expr; + } + + if (\is_string($expr)) { + return new String_($expr); + } + + throw new \LogicException('Expected string or Expr'); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/BuilderHelpers.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/BuilderHelpers.php new file mode 100644 index 0000000..3e41b26 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/BuilderHelpers.php @@ -0,0 +1,333 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Node\ComplexType; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\NullableType; +use PhpParser\Node\Scalar; +use PhpParser\Node\Stmt; + +/** + * This class defines helpers used in the implementation of builders. Don't use it directly. + * + * @internal + */ +final class BuilderHelpers { + /** + * Normalizes a node: Converts builder objects to nodes. + * + * @param Node|Builder $node The node to normalize + * + * @return Node The normalized node + */ + public static function normalizeNode($node): Node { + if ($node instanceof Builder) { + return $node->getNode(); + } + + if ($node instanceof Node) { + return $node; + } + + throw new \LogicException('Expected node or builder object'); + } + + /** + * Normalizes a node to a statement. + * + * Expressions are wrapped in a Stmt\Expression node. + * + * @param Node|Builder $node The node to normalize + * + * @return Stmt The normalized statement node + */ + public static function normalizeStmt($node): Stmt { + $node = self::normalizeNode($node); + if ($node instanceof Stmt) { + return $node; + } + + if ($node instanceof Expr) { + return new Stmt\Expression($node); + } + + throw new \LogicException('Expected statement or expression node'); + } + + /** + * Normalizes strings to Identifier. + * + * @param string|Identifier $name The identifier to normalize + * + * @return Identifier The normalized identifier + */ + public static function normalizeIdentifier($name): Identifier { + if ($name instanceof Identifier) { + return $name; + } + + if (\is_string($name)) { + return new Identifier($name); + } + + throw new \LogicException('Expected string or instance of Node\Identifier'); + } + + /** + * Normalizes strings to Identifier, also allowing expressions. + * + * @param string|Identifier|Expr $name The identifier to normalize + * + * @return Identifier|Expr The normalized identifier or expression + */ + public static function normalizeIdentifierOrExpr($name) { + if ($name instanceof Identifier || $name instanceof Expr) { + return $name; + } + + if (\is_string($name)) { + return new Identifier($name); + } + + throw new \LogicException('Expected string or instance of Node\Identifier or Node\Expr'); + } + + /** + * Normalizes a name: Converts string names to Name nodes. + * + * @param Name|string $name The name to normalize + * + * @return Name The normalized name + */ + public static function normalizeName($name): Name { + if ($name instanceof Name) { + return $name; + } + + if (is_string($name)) { + if (!$name) { + throw new \LogicException('Name cannot be empty'); + } + + if ($name[0] === '\\') { + return new Name\FullyQualified(substr($name, 1)); + } + + if (0 === strpos($name, 'namespace\\')) { + return new Name\Relative(substr($name, strlen('namespace\\'))); + } + + return new Name($name); + } + + throw new \LogicException('Name must be a string or an instance of Node\Name'); + } + + /** + * Normalizes a name: Converts string names to Name nodes, while also allowing expressions. + * + * @param Expr|Name|string $name The name to normalize + * + * @return Name|Expr The normalized name or expression + */ + public static function normalizeNameOrExpr($name) { + if ($name instanceof Expr) { + return $name; + } + + if (!is_string($name) && !($name instanceof Name)) { + throw new \LogicException( + 'Name must be a string or an instance of Node\Name or Node\Expr' + ); + } + + return self::normalizeName($name); + } + + /** + * Normalizes a type: Converts plain-text type names into proper AST representation. + * + * In particular, builtin types become Identifiers, custom types become Names and nullables + * are wrapped in NullableType nodes. + * + * @param string|Name|Identifier|ComplexType $type The type to normalize + * + * @return Name|Identifier|ComplexType The normalized type + */ + public static function normalizeType($type) { + if (!is_string($type)) { + if ( + !$type instanceof Name && !$type instanceof Identifier && + !$type instanceof ComplexType + ) { + throw new \LogicException( + 'Type must be a string, or an instance of Name, Identifier or ComplexType' + ); + } + return $type; + } + + $nullable = false; + if (strlen($type) > 0 && $type[0] === '?') { + $nullable = true; + $type = substr($type, 1); + } + + $builtinTypes = [ + 'array', + 'callable', + 'bool', + 'int', + 'float', + 'string', + 'iterable', + 'void', + 'object', + 'null', + 'false', + 'mixed', + 'never', + 'true', + ]; + + $lowerType = strtolower($type); + if (in_array($lowerType, $builtinTypes)) { + $type = new Identifier($lowerType); + } else { + $type = self::normalizeName($type); + } + + $notNullableTypes = [ + 'void', 'mixed', 'never', + ]; + if ($nullable && in_array((string) $type, $notNullableTypes)) { + throw new \LogicException(sprintf('%s type cannot be nullable', $type)); + } + + return $nullable ? new NullableType($type) : $type; + } + + /** + * Normalizes a value: Converts nulls, booleans, integers, + * floats, strings and arrays into their respective nodes + * + * @param Node\Expr|bool|null|int|float|string|array $value The value to normalize + * + * @return Expr The normalized value + */ + public static function normalizeValue($value): Expr { + if ($value instanceof Node\Expr) { + return $value; + } + + if (is_null($value)) { + return new Expr\ConstFetch( + new Name('null') + ); + } + + if (is_bool($value)) { + return new Expr\ConstFetch( + new Name($value ? 'true' : 'false') + ); + } + + if (is_int($value)) { + return new Scalar\Int_($value); + } + + if (is_float($value)) { + return new Scalar\Float_($value); + } + + if (is_string($value)) { + return new Scalar\String_($value); + } + + if (is_array($value)) { + $items = []; + $lastKey = -1; + foreach ($value as $itemKey => $itemValue) { + // for consecutive, numeric keys don't generate keys + if (null !== $lastKey && ++$lastKey === $itemKey) { + $items[] = new Node\ArrayItem( + self::normalizeValue($itemValue) + ); + } else { + $lastKey = null; + $items[] = new Node\ArrayItem( + self::normalizeValue($itemValue), + self::normalizeValue($itemKey) + ); + } + } + + return new Expr\Array_($items); + } + + throw new \LogicException('Invalid value'); + } + + /** + * Normalizes a doc comment: Converts plain strings to PhpParser\Comment\Doc. + * + * @param Comment\Doc|string $docComment The doc comment to normalize + * + * @return Comment\Doc The normalized doc comment + */ + public static function normalizeDocComment($docComment): Comment\Doc { + if ($docComment instanceof Comment\Doc) { + return $docComment; + } + + if (is_string($docComment)) { + return new Comment\Doc($docComment); + } + + throw new \LogicException('Doc comment must be a string or an instance of PhpParser\Comment\Doc'); + } + + /** + * Normalizes a attribute: Converts attribute to the Attribute Group if needed. + * + * @param Node\Attribute|Node\AttributeGroup $attribute + * + * @return Node\AttributeGroup The Attribute Group + */ + public static function normalizeAttribute($attribute): Node\AttributeGroup { + if ($attribute instanceof Node\AttributeGroup) { + return $attribute; + } + + if (!($attribute instanceof Node\Attribute)) { + throw new \LogicException('Attribute must be an instance of PhpParser\Node\Attribute or PhpParser\Node\AttributeGroup'); + } + + return new Node\AttributeGroup([$attribute]); + } + + /** + * Adds a modifier and returns new modifier bitmask. + * + * @param int $modifiers Existing modifiers + * @param int $modifier Modifier to set + * + * @return int New modifiers + */ + public static function addModifier(int $modifiers, int $modifier): int { + Modifiers::verifyModifier($modifiers, $modifier); + return $modifiers | $modifier; + } + + /** + * Adds a modifier and returns new modifier bitmask. + * @return int New modifiers + */ + public static function addClassModifier(int $existingModifiers, int $modifierToSet): int { + Modifiers::verifyClassModifier($existingModifiers, $modifierToSet); + return $existingModifiers | $modifierToSet; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Comment.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Comment.php new file mode 100644 index 0000000..17dc4c7 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Comment.php @@ -0,0 +1,207 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +class Comment implements \JsonSerializable { + protected string $text; + protected int $startLine; + protected int $startFilePos; + protected int $startTokenPos; + protected int $endLine; + protected int $endFilePos; + protected int $endTokenPos; + + /** + * Constructs a comment node. + * + * @param string $text Comment text (including comment delimiters like /*) + * @param int $startLine Line number the comment started on + * @param int $startFilePos File offset the comment started on + * @param int $startTokenPos Token offset the comment started on + */ + public function __construct( + string $text, + int $startLine = -1, int $startFilePos = -1, int $startTokenPos = -1, + int $endLine = -1, int $endFilePos = -1, int $endTokenPos = -1 + ) { + $this->text = $text; + $this->startLine = $startLine; + $this->startFilePos = $startFilePos; + $this->startTokenPos = $startTokenPos; + $this->endLine = $endLine; + $this->endFilePos = $endFilePos; + $this->endTokenPos = $endTokenPos; + } + + /** + * Gets the comment text. + * + * @return string The comment text (including comment delimiters like /*) + */ + public function getText(): string { + return $this->text; + } + + /** + * Gets the line number the comment started on. + * + * @return int Line number (or -1 if not available) + */ + public function getStartLine(): int { + return $this->startLine; + } + + /** + * Gets the file offset the comment started on. + * + * @return int File offset (or -1 if not available) + */ + public function getStartFilePos(): int { + return $this->startFilePos; + } + + /** + * Gets the token offset the comment started on. + * + * @return int Token offset (or -1 if not available) + */ + public function getStartTokenPos(): int { + return $this->startTokenPos; + } + + /** + * Gets the line number the comment ends on. + * + * @return int Line number (or -1 if not available) + */ + public function getEndLine(): int { + return $this->endLine; + } + + /** + * Gets the file offset the comment ends on. + * + * @return int File offset (or -1 if not available) + */ + public function getEndFilePos(): int { + return $this->endFilePos; + } + + /** + * Gets the token offset the comment ends on. + * + * @return int Token offset (or -1 if not available) + */ + public function getEndTokenPos(): int { + return $this->endTokenPos; + } + + /** + * Gets the comment text. + * + * @return string The comment text (including comment delimiters like /*) + */ + public function __toString(): string { + return $this->text; + } + + /** + * Gets the reformatted comment text. + * + * "Reformatted" here means that we try to clean up the whitespace at the + * starts of the lines. This is necessary because we receive the comments + * without leading whitespace on the first line, but with leading whitespace + * on all subsequent lines. + * + * Additionally, this normalizes CRLF newlines to LF newlines. + */ + public function getReformattedText(): string { + $text = str_replace("\r\n", "\n", $this->text); + $newlinePos = strpos($text, "\n"); + if (false === $newlinePos) { + // Single line comments don't need further processing + return $text; + } + if (preg_match('(^.*(?:\n\s+\*.*)+$)', $text)) { + // Multi line comment of the type + // + // /* + // * Some text. + // * Some more text. + // */ + // + // is handled by replacing the whitespace sequences before the * by a single space + return preg_replace('(^\s+\*)m', ' *', $text); + } + if (preg_match('(^/\*\*?\s*\n)', $text) && preg_match('(\n(\s*)\*/$)', $text, $matches)) { + // Multi line comment of the type + // + // /* + // Some text. + // Some more text. + // */ + // + // is handled by removing the whitespace sequence on the line before the closing + // */ on all lines. So if the last line is " */", then " " is removed at the + // start of all lines. + return preg_replace('(^' . preg_quote($matches[1]) . ')m', '', $text); + } + if (preg_match('(^/\*\*?\s*(?!\s))', $text, $matches)) { + // Multi line comment of the type + // + // /* Some text. + // Some more text. + // Indented text. + // Even more text. */ + // + // is handled by removing the difference between the shortest whitespace prefix on all + // lines and the length of the "/* " opening sequence. + $prefixLen = $this->getShortestWhitespacePrefixLen(substr($text, $newlinePos + 1)); + $removeLen = $prefixLen - strlen($matches[0]); + return preg_replace('(^\s{' . $removeLen . '})m', '', $text); + } + + // No idea how to format this comment, so simply return as is + return $text; + } + + /** + * Get length of shortest whitespace prefix (at the start of a line). + * + * If there is a line with no prefix whitespace, 0 is a valid return value. + * + * @param string $str String to check + * @return int Length in characters. Tabs count as single characters. + */ + private function getShortestWhitespacePrefixLen(string $str): int { + $lines = explode("\n", $str); + $shortestPrefixLen = \PHP_INT_MAX; + foreach ($lines as $line) { + preg_match('(^\s*)', $line, $matches); + $prefixLen = strlen($matches[0]); + if ($prefixLen < $shortestPrefixLen) { + $shortestPrefixLen = $prefixLen; + } + } + return $shortestPrefixLen; + } + + /** + * @return array{nodeType:string, text:mixed, line:mixed, filePos:mixed} + */ + public function jsonSerialize(): array { + // Technically not a node, but we make it look like one anyway + $type = $this instanceof Comment\Doc ? 'Comment_Doc' : 'Comment'; + return [ + 'nodeType' => $type, + 'text' => $this->text, + // TODO: Rename these to include "start". + 'line' => $this->startLine, + 'filePos' => $this->startFilePos, + 'tokenPos' => $this->startTokenPos, + 'endLine' => $this->endLine, + 'endFilePos' => $this->endFilePos, + 'endTokenPos' => $this->endTokenPos, + ]; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Comment/Doc.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Comment/Doc.php new file mode 100644 index 0000000..bb3e914 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Comment/Doc.php @@ -0,0 +1,6 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Comment; + +class Doc extends \PhpParser\Comment { +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluationException.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluationException.php new file mode 100644 index 0000000..7964058 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluationException.php @@ -0,0 +1,6 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +class ConstExprEvaluationException extends \Exception { +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluator.php new file mode 100644 index 0000000..73e59fc --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluator.php @@ -0,0 +1,234 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Node\Expr; +use PhpParser\Node\Scalar; + +use function array_merge; + +/** + * Evaluates constant expressions. + * + * This evaluator is able to evaluate all constant expressions (as defined by PHP), which can be + * evaluated without further context. If a subexpression is not of this type, a user-provided + * fallback evaluator is invoked. To support all constant expressions that are also supported by + * PHP (and not already handled by this class), the fallback evaluator must be able to handle the + * following node types: + * + * * All Scalar\MagicConst\* nodes. + * * Expr\ConstFetch nodes. Only null/false/true are already handled by this class. + * * Expr\ClassConstFetch nodes. + * + * The fallback evaluator should throw ConstExprEvaluationException for nodes it cannot evaluate. + * + * The evaluation is dependent on runtime configuration in two respects: Firstly, floating + * point to string conversions are affected by the precision ini setting. Secondly, they are also + * affected by the LC_NUMERIC locale. + */ +class ConstExprEvaluator { + /** @var callable|null */ + private $fallbackEvaluator; + + /** + * Create a constant expression evaluator. + * + * The provided fallback evaluator is invoked whenever a subexpression cannot be evaluated. See + * class doc comment for more information. + * + * @param callable|null $fallbackEvaluator To call if subexpression cannot be evaluated + */ + public function __construct(?callable $fallbackEvaluator = null) { + $this->fallbackEvaluator = $fallbackEvaluator ?? function (Expr $expr) { + throw new ConstExprEvaluationException( + "Expression of type {$expr->getType()} cannot be evaluated" + ); + }; + } + + /** + * Silently evaluates a constant expression into a PHP value. + * + * Thrown Errors, warnings or notices will be converted into a ConstExprEvaluationException. + * The original source of the exception is available through getPrevious(). + * + * If some part of the expression cannot be evaluated, the fallback evaluator passed to the + * constructor will be invoked. By default, if no fallback is provided, an exception of type + * ConstExprEvaluationException is thrown. + * + * See class doc comment for caveats and limitations. + * + * @param Expr $expr Constant expression to evaluate + * @return mixed Result of evaluation + * + * @throws ConstExprEvaluationException if the expression cannot be evaluated or an error occurred + */ + public function evaluateSilently(Expr $expr) { + set_error_handler(function ($num, $str, $file, $line) { + throw new \ErrorException($str, 0, $num, $file, $line); + }); + + try { + return $this->evaluate($expr); + } catch (\Throwable $e) { + if (!$e instanceof ConstExprEvaluationException) { + $e = new ConstExprEvaluationException( + "An error occurred during constant expression evaluation", 0, $e); + } + throw $e; + } finally { + restore_error_handler(); + } + } + + /** + * Directly evaluates a constant expression into a PHP value. + * + * May generate Error exceptions, warnings or notices. Use evaluateSilently() to convert these + * into a ConstExprEvaluationException. + * + * If some part of the expression cannot be evaluated, the fallback evaluator passed to the + * constructor will be invoked. By default, if no fallback is provided, an exception of type + * ConstExprEvaluationException is thrown. + * + * See class doc comment for caveats and limitations. + * + * @param Expr $expr Constant expression to evaluate + * @return mixed Result of evaluation + * + * @throws ConstExprEvaluationException if the expression cannot be evaluated + */ + public function evaluateDirectly(Expr $expr) { + return $this->evaluate($expr); + } + + /** @return mixed */ + private function evaluate(Expr $expr) { + if ($expr instanceof Scalar\Int_ + || $expr instanceof Scalar\Float_ + || $expr instanceof Scalar\String_ + ) { + return $expr->value; + } + + if ($expr instanceof Expr\Array_) { + return $this->evaluateArray($expr); + } + + // Unary operators + if ($expr instanceof Expr\UnaryPlus) { + return +$this->evaluate($expr->expr); + } + if ($expr instanceof Expr\UnaryMinus) { + return -$this->evaluate($expr->expr); + } + if ($expr instanceof Expr\BooleanNot) { + return !$this->evaluate($expr->expr); + } + if ($expr instanceof Expr\BitwiseNot) { + return ~$this->evaluate($expr->expr); + } + + if ($expr instanceof Expr\BinaryOp) { + return $this->evaluateBinaryOp($expr); + } + + if ($expr instanceof Expr\Ternary) { + return $this->evaluateTernary($expr); + } + + if ($expr instanceof Expr\ArrayDimFetch && null !== $expr->dim) { + return $this->evaluate($expr->var)[$this->evaluate($expr->dim)]; + } + + if ($expr instanceof Expr\ConstFetch) { + return $this->evaluateConstFetch($expr); + } + + return ($this->fallbackEvaluator)($expr); + } + + private function evaluateArray(Expr\Array_ $expr): array { + $array = []; + foreach ($expr->items as $item) { + if (null !== $item->key) { + $array[$this->evaluate($item->key)] = $this->evaluate($item->value); + } elseif ($item->unpack) { + $array = array_merge($array, $this->evaluate($item->value)); + } else { + $array[] = $this->evaluate($item->value); + } + } + return $array; + } + + /** @return mixed */ + private function evaluateTernary(Expr\Ternary $expr) { + if (null === $expr->if) { + return $this->evaluate($expr->cond) ?: $this->evaluate($expr->else); + } + + return $this->evaluate($expr->cond) + ? $this->evaluate($expr->if) + : $this->evaluate($expr->else); + } + + /** @return mixed */ + private function evaluateBinaryOp(Expr\BinaryOp $expr) { + if ($expr instanceof Expr\BinaryOp\Coalesce + && $expr->left instanceof Expr\ArrayDimFetch + ) { + // This needs to be special cased to respect BP_VAR_IS fetch semantics + return $this->evaluate($expr->left->var)[$this->evaluate($expr->left->dim)] + ?? $this->evaluate($expr->right); + } + + // The evaluate() calls are repeated in each branch, because some of the operators are + // short-circuiting and evaluating the RHS in advance may be illegal in that case + $l = $expr->left; + $r = $expr->right; + switch ($expr->getOperatorSigil()) { + case '&': return $this->evaluate($l) & $this->evaluate($r); + case '|': return $this->evaluate($l) | $this->evaluate($r); + case '^': return $this->evaluate($l) ^ $this->evaluate($r); + case '&&': return $this->evaluate($l) && $this->evaluate($r); + case '||': return $this->evaluate($l) || $this->evaluate($r); + case '??': return $this->evaluate($l) ?? $this->evaluate($r); + case '.': return $this->evaluate($l) . $this->evaluate($r); + case '/': return $this->evaluate($l) / $this->evaluate($r); + case '==': return $this->evaluate($l) == $this->evaluate($r); + case '>': return $this->evaluate($l) > $this->evaluate($r); + case '>=': return $this->evaluate($l) >= $this->evaluate($r); + case '===': return $this->evaluate($l) === $this->evaluate($r); + case 'and': return $this->evaluate($l) and $this->evaluate($r); + case 'or': return $this->evaluate($l) or $this->evaluate($r); + case 'xor': return $this->evaluate($l) xor $this->evaluate($r); + case '-': return $this->evaluate($l) - $this->evaluate($r); + case '%': return $this->evaluate($l) % $this->evaluate($r); + case '*': return $this->evaluate($l) * $this->evaluate($r); + case '!=': return $this->evaluate($l) != $this->evaluate($r); + case '!==': return $this->evaluate($l) !== $this->evaluate($r); + case '+': return $this->evaluate($l) + $this->evaluate($r); + case '**': return $this->evaluate($l) ** $this->evaluate($r); + case '<<': return $this->evaluate($l) << $this->evaluate($r); + case '>>': return $this->evaluate($l) >> $this->evaluate($r); + case '<': return $this->evaluate($l) < $this->evaluate($r); + case '<=': return $this->evaluate($l) <= $this->evaluate($r); + case '<=>': return $this->evaluate($l) <=> $this->evaluate($r); + } + + throw new \Exception('Should not happen'); + } + + /** @return mixed */ + private function evaluateConstFetch(Expr\ConstFetch $expr) { + $name = $expr->name->toLowerString(); + switch ($name) { + case 'null': return null; + case 'false': return false; + case 'true': return true; + } + + return ($this->fallbackEvaluator)($expr); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Error.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Error.php new file mode 100644 index 0000000..02feace --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Error.php @@ -0,0 +1,171 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +class Error extends \RuntimeException { + protected string $rawMessage; + /** @var array<string, mixed> */ + protected array $attributes; + + /** + * Creates an Exception signifying a parse error. + * + * @param string $message Error message + * @param array<string, mixed> $attributes Attributes of node/token where error occurred + */ + public function __construct(string $message, array $attributes = []) { + $this->rawMessage = $message; + $this->attributes = $attributes; + $this->updateMessage(); + } + + /** + * Gets the error message + * + * @return string Error message + */ + public function getRawMessage(): string { + return $this->rawMessage; + } + + /** + * Gets the line the error starts in. + * + * @return int Error start line + */ + public function getStartLine(): int { + return $this->attributes['startLine'] ?? -1; + } + + /** + * Gets the line the error ends in. + * + * @return int Error end line + */ + public function getEndLine(): int { + return $this->attributes['endLine'] ?? -1; + } + + /** + * Gets the attributes of the node/token the error occurred at. + * + * @return array<string, mixed> + */ + public function getAttributes(): array { + return $this->attributes; + } + + /** + * Sets the attributes of the node/token the error occurred at. + * + * @param array<string, mixed> $attributes + */ + public function setAttributes(array $attributes): void { + $this->attributes = $attributes; + $this->updateMessage(); + } + + /** + * Sets the line of the PHP file the error occurred in. + * + * @param string $message Error message + */ + public function setRawMessage(string $message): void { + $this->rawMessage = $message; + $this->updateMessage(); + } + + /** + * Sets the line the error starts in. + * + * @param int $line Error start line + */ + public function setStartLine(int $line): void { + $this->attributes['startLine'] = $line; + $this->updateMessage(); + } + + /** + * Returns whether the error has start and end column information. + * + * For column information enable the startFilePos and endFilePos in the lexer options. + */ + public function hasColumnInfo(): bool { + return isset($this->attributes['startFilePos'], $this->attributes['endFilePos']); + } + + /** + * Gets the start column (1-based) into the line where the error started. + * + * @param string $code Source code of the file + */ + public function getStartColumn(string $code): int { + if (!$this->hasColumnInfo()) { + throw new \RuntimeException('Error does not have column information'); + } + + return $this->toColumn($code, $this->attributes['startFilePos']); + } + + /** + * Gets the end column (1-based) into the line where the error ended. + * + * @param string $code Source code of the file + */ + public function getEndColumn(string $code): int { + if (!$this->hasColumnInfo()) { + throw new \RuntimeException('Error does not have column information'); + } + + return $this->toColumn($code, $this->attributes['endFilePos']); + } + + /** + * Formats message including line and column information. + * + * @param string $code Source code associated with the error, for calculation of the columns + * + * @return string Formatted message + */ + public function getMessageWithColumnInfo(string $code): string { + return sprintf( + '%s from %d:%d to %d:%d', $this->getRawMessage(), + $this->getStartLine(), $this->getStartColumn($code), + $this->getEndLine(), $this->getEndColumn($code) + ); + } + + /** + * Converts a file offset into a column. + * + * @param string $code Source code that $pos indexes into + * @param int $pos 0-based position in $code + * + * @return int 1-based column (relative to start of line) + */ + private function toColumn(string $code, int $pos): int { + if ($pos > strlen($code)) { + throw new \RuntimeException('Invalid position information'); + } + + $lineStartPos = strrpos($code, "\n", $pos - strlen($code)); + if (false === $lineStartPos) { + $lineStartPos = -1; + } + + return $pos - $lineStartPos; + } + + /** + * Updates the exception message after a change to rawMessage or rawLine. + */ + protected function updateMessage(): void { + $this->message = $this->rawMessage; + + if (-1 === $this->getStartLine()) { + $this->message .= ' on unknown line'; + } else { + $this->message .= ' on line ' . $this->getStartLine(); + } + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler.php new file mode 100644 index 0000000..51ad730 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler.php @@ -0,0 +1,12 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +interface ErrorHandler { + /** + * Handle an error generated during lexing, parsing or some other operation. + * + * @param Error $error The error that needs to be handled + */ + public function handleError(Error $error): void; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Collecting.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Collecting.php new file mode 100644 index 0000000..eee6349 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Collecting.php @@ -0,0 +1,43 @@ +<?php declare(strict_types=1); + +namespace PhpParser\ErrorHandler; + +use PhpParser\Error; +use PhpParser\ErrorHandler; + +/** + * Error handler that collects all errors into an array. + * + * This allows graceful handling of errors. + */ +class Collecting implements ErrorHandler { + /** @var Error[] Collected errors */ + private array $errors = []; + + public function handleError(Error $error): void { + $this->errors[] = $error; + } + + /** + * Get collected errors. + * + * @return Error[] + */ + public function getErrors(): array { + return $this->errors; + } + + /** + * Check whether there are any errors. + */ + public function hasErrors(): bool { + return !empty($this->errors); + } + + /** + * Reset/clear collected errors. + */ + public function clearErrors(): void { + $this->errors = []; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Throwing.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Throwing.php new file mode 100644 index 0000000..dff33dd --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Throwing.php @@ -0,0 +1,17 @@ +<?php declare(strict_types=1); + +namespace PhpParser\ErrorHandler; + +use PhpParser\Error; +use PhpParser\ErrorHandler; + +/** + * Error handler that handles all errors by throwing them. + * + * This is the default strategy used by all components. + */ +class Throwing implements ErrorHandler { + public function handleError(Error $error): void { + throw $error; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/DiffElem.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/DiffElem.php new file mode 100644 index 0000000..7433b5d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/DiffElem.php @@ -0,0 +1,31 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Internal; + +/** + * @internal + */ +class DiffElem { + public const TYPE_KEEP = 0; + public const TYPE_REMOVE = 1; + public const TYPE_ADD = 2; + public const TYPE_REPLACE = 3; + + /** @var int One of the TYPE_* constants */ + public int $type; + /** @var mixed Is null for add operations */ + public $old; + /** @var mixed Is null for remove operations */ + public $new; + + /** + * @param int $type One of the TYPE_* constants + * @param mixed $old Is null for add operations + * @param mixed $new Is null for remove operations + */ + public function __construct(int $type, $old, $new) { + $this->type = $type; + $this->old = $old; + $this->new = $new; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/Differ.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/Differ.php new file mode 100644 index 0000000..253e175 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/Differ.php @@ -0,0 +1,178 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Internal; + +/** + * Implements the Myers diff algorithm. + * + * Myers, Eugene W. "An O (ND) difference algorithm and its variations." + * Algorithmica 1.1 (1986): 251-266. + * + * @template T + * @internal + */ +class Differ { + /** @var callable(T, T): bool */ + private $isEqual; + + /** + * Create differ over the given equality relation. + * + * @param callable(T, T): bool $isEqual Equality relation + */ + public function __construct(callable $isEqual) { + $this->isEqual = $isEqual; + } + + /** + * Calculate diff (edit script) from $old to $new. + * + * @param T[] $old Original array + * @param T[] $new New array + * + * @return DiffElem[] Diff (edit script) + */ + public function diff(array $old, array $new): array { + $old = \array_values($old); + $new = \array_values($new); + list($trace, $x, $y) = $this->calculateTrace($old, $new); + return $this->extractDiff($trace, $x, $y, $old, $new); + } + + /** + * Calculate diff, including "replace" operations. + * + * If a sequence of remove operations is followed by the same number of add operations, these + * will be coalesced into replace operations. + * + * @param T[] $old Original array + * @param T[] $new New array + * + * @return DiffElem[] Diff (edit script), including replace operations + */ + public function diffWithReplacements(array $old, array $new): array { + return $this->coalesceReplacements($this->diff($old, $new)); + } + + /** + * @param T[] $old + * @param T[] $new + * @return array{array<int, array<int, int>>, int, int} + */ + private function calculateTrace(array $old, array $new): array { + $n = \count($old); + $m = \count($new); + $max = $n + $m; + $v = [1 => 0]; + $trace = []; + for ($d = 0; $d <= $max; $d++) { + $trace[] = $v; + for ($k = -$d; $k <= $d; $k += 2) { + if ($k === -$d || ($k !== $d && $v[$k - 1] < $v[$k + 1])) { + $x = $v[$k + 1]; + } else { + $x = $v[$k - 1] + 1; + } + + $y = $x - $k; + while ($x < $n && $y < $m && ($this->isEqual)($old[$x], $new[$y])) { + $x++; + $y++; + } + + $v[$k] = $x; + if ($x >= $n && $y >= $m) { + return [$trace, $x, $y]; + } + } + } + throw new \Exception('Should not happen'); + } + + /** + * @param array<int, array<int, int>> $trace + * @param T[] $old + * @param T[] $new + * @return DiffElem[] + */ + private function extractDiff(array $trace, int $x, int $y, array $old, array $new): array { + $result = []; + for ($d = \count($trace) - 1; $d >= 0; $d--) { + $v = $trace[$d]; + $k = $x - $y; + + if ($k === -$d || ($k !== $d && $v[$k - 1] < $v[$k + 1])) { + $prevK = $k + 1; + } else { + $prevK = $k - 1; + } + + $prevX = $v[$prevK]; + $prevY = $prevX - $prevK; + + while ($x > $prevX && $y > $prevY) { + $result[] = new DiffElem(DiffElem::TYPE_KEEP, $old[$x - 1], $new[$y - 1]); + $x--; + $y--; + } + + if ($d === 0) { + break; + } + + while ($x > $prevX) { + $result[] = new DiffElem(DiffElem::TYPE_REMOVE, $old[$x - 1], null); + $x--; + } + + while ($y > $prevY) { + $result[] = new DiffElem(DiffElem::TYPE_ADD, null, $new[$y - 1]); + $y--; + } + } + return array_reverse($result); + } + + /** + * Coalesce equal-length sequences of remove+add into a replace operation. + * + * @param DiffElem[] $diff + * @return DiffElem[] + */ + private function coalesceReplacements(array $diff): array { + $newDiff = []; + $c = \count($diff); + for ($i = 0; $i < $c; $i++) { + $diffType = $diff[$i]->type; + if ($diffType !== DiffElem::TYPE_REMOVE) { + $newDiff[] = $diff[$i]; + continue; + } + + $j = $i; + while ($j < $c && $diff[$j]->type === DiffElem::TYPE_REMOVE) { + $j++; + } + + $k = $j; + while ($k < $c && $diff[$k]->type === DiffElem::TYPE_ADD) { + $k++; + } + + if ($j - $i === $k - $j) { + $len = $j - $i; + for ($n = 0; $n < $len; $n++) { + $newDiff[] = new DiffElem( + DiffElem::TYPE_REPLACE, $diff[$i + $n]->old, $diff[$j + $n]->new + ); + } + } else { + for (; $i < $k; $i++) { + $newDiff[] = $diff[$i]; + } + } + $i = $k - 1; + } + return $newDiff; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/PrintableNewAnonClassNode.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/PrintableNewAnonClassNode.php new file mode 100644 index 0000000..b30a99a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/PrintableNewAnonClassNode.php @@ -0,0 +1,71 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Internal; + +use PhpParser\Node; +use PhpParser\Node\Expr; + +/** + * This node is used internally by the format-preserving pretty printer to print anonymous classes. + * + * The normal anonymous class structure violates assumptions about the order of token offsets. + * Namely, the constructor arguments are part of the Expr\New_ node and follow the class node, even + * though they are actually interleaved with them. This special node type is used temporarily to + * restore a sane token offset order. + * + * @internal + */ +class PrintableNewAnonClassNode extends Expr { + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + /** @var int Modifiers */ + public int $flags; + /** @var (Node\Arg|Node\VariadicPlaceholder)[] Arguments */ + public array $args; + /** @var null|Node\Name Name of extended class */ + public ?Node\Name $extends; + /** @var Node\Name[] Names of implemented interfaces */ + public array $implements; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * @param Node\AttributeGroup[] $attrGroups PHP attribute groups + * @param (Node\Arg|Node\VariadicPlaceholder)[] $args Arguments + * @param Node\Name|null $extends Name of extended class + * @param Node\Name[] $implements Names of implemented interfaces + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Attributes + */ + public function __construct( + array $attrGroups, int $flags, array $args, ?Node\Name $extends, array $implements, + array $stmts, array $attributes + ) { + parent::__construct($attributes); + $this->attrGroups = $attrGroups; + $this->flags = $flags; + $this->args = $args; + $this->extends = $extends; + $this->implements = $implements; + $this->stmts = $stmts; + } + + public static function fromNewNode(Expr\New_ $newNode): self { + $class = $newNode->class; + assert($class instanceof Node\Stmt\Class_); + // We don't assert that $class->name is null here, to allow consumers to assign unique names + // to anonymous classes for their own purposes. We simplify ignore the name here. + return new self( + $class->attrGroups, $class->flags, $newNode->args, $class->extends, $class->implements, + $class->stmts, $newNode->getAttributes() + ); + } + + public function getType(): string { + return 'Expr_PrintableNewAnonClass'; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'flags', 'args', 'extends', 'implements', 'stmts']; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenPolyfill.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenPolyfill.php new file mode 100644 index 0000000..36022d0 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenPolyfill.php @@ -0,0 +1,237 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Internal; + +if (\PHP_VERSION_ID >= 80000) { + class TokenPolyfill extends \PhpToken { + } + return; +} + +/** + * This is a polyfill for the PhpToken class introduced in PHP 8.0. We do not actually polyfill + * PhpToken, because composer might end up picking a different polyfill implementation, which does + * not meet our requirements. + * + * @internal + */ +class TokenPolyfill { + /** @var int The ID of the token. Either a T_* constant of a character code < 256. */ + public int $id; + /** @var string The textual content of the token. */ + public string $text; + /** @var int The 1-based starting line of the token (or -1 if unknown). */ + public int $line; + /** @var int The 0-based starting position of the token (or -1 if unknown). */ + public int $pos; + + /** @var array<int, bool> Tokens ignored by the PHP parser. */ + private const IGNORABLE_TOKENS = [ + \T_WHITESPACE => true, + \T_COMMENT => true, + \T_DOC_COMMENT => true, + \T_OPEN_TAG => true, + ]; + + /** @var array<int, bool> Tokens that may be part of a T_NAME_* identifier. */ + private static array $identifierTokens; + + /** + * Create a Token with the given ID and text, as well optional line and position information. + */ + final public function __construct(int $id, string $text, int $line = -1, int $pos = -1) { + $this->id = $id; + $this->text = $text; + $this->line = $line; + $this->pos = $pos; + } + + /** + * Get the name of the token. For single-char tokens this will be the token character. + * Otherwise it will be a T_* style name, or null if the token ID is unknown. + */ + public function getTokenName(): ?string { + if ($this->id < 256) { + return \chr($this->id); + } + + $name = token_name($this->id); + return $name === 'UNKNOWN' ? null : $name; + } + + /** + * Check whether the token is of the given kind. The kind may be either an integer that matches + * the token ID, a string that matches the token text, or an array of integers/strings. In the + * latter case, the function returns true if any of the kinds in the array match. + * + * @param int|string|(int|string)[] $kind + */ + public function is($kind): bool { + if (\is_int($kind)) { + return $this->id === $kind; + } + if (\is_string($kind)) { + return $this->text === $kind; + } + if (\is_array($kind)) { + foreach ($kind as $entry) { + if (\is_int($entry)) { + if ($this->id === $entry) { + return true; + } + } elseif (\is_string($entry)) { + if ($this->text === $entry) { + return true; + } + } else { + throw new \TypeError( + 'Argument #1 ($kind) must only have elements of type string|int, ' . + gettype($entry) . ' given'); + } + } + return false; + } + throw new \TypeError( + 'Argument #1 ($kind) must be of type string|int|array, ' .gettype($kind) . ' given'); + } + + /** + * Check whether this token would be ignored by the PHP parser. Returns true for T_WHITESPACE, + * T_COMMENT, T_DOC_COMMENT and T_OPEN_TAG, and false for everything else. + */ + public function isIgnorable(): bool { + return isset(self::IGNORABLE_TOKENS[$this->id]); + } + + /** + * Return the textual content of the token. + */ + public function __toString(): string { + return $this->text; + } + + /** + * Tokenize the given source code and return an array of tokens. + * + * This performs certain canonicalizations to match the PHP 8.0 token format: + * * Bad characters are represented using T_BAD_CHARACTER rather than omitted. + * * T_COMMENT does not include trailing newlines, instead the newline is part of a following + * T_WHITESPACE token. + * * Namespaced names are represented using T_NAME_* tokens. + * + * @return static[] + */ + public static function tokenize(string $code, int $flags = 0): array { + self::init(); + + $tokens = []; + $line = 1; + $pos = 0; + $origTokens = \token_get_all($code, $flags); + + $numTokens = \count($origTokens); + for ($i = 0; $i < $numTokens; $i++) { + $token = $origTokens[$i]; + if (\is_string($token)) { + if (\strlen($token) === 2) { + // b" and B" are tokenized as single-char tokens, even though they aren't. + $tokens[] = new static(\ord('"'), $token, $line, $pos); + $pos += 2; + } else { + $tokens[] = new static(\ord($token), $token, $line, $pos); + $pos++; + } + } else { + $id = $token[0]; + $text = $token[1]; + + // Emulate PHP 8.0 comment format, which does not include trailing whitespace anymore. + if ($id === \T_COMMENT && \substr($text, 0, 2) !== '/*' && + \preg_match('/(\r\n|\n|\r)$/D', $text, $matches) + ) { + $trailingNewline = $matches[0]; + $text = \substr($text, 0, -\strlen($trailingNewline)); + $tokens[] = new static($id, $text, $line, $pos); + $pos += \strlen($text); + + if ($i + 1 < $numTokens && $origTokens[$i + 1][0] === \T_WHITESPACE) { + // Move trailing newline into following T_WHITESPACE token, if it already exists. + $origTokens[$i + 1][1] = $trailingNewline . $origTokens[$i + 1][1]; + $origTokens[$i + 1][2]--; + } else { + // Otherwise, we need to create a new T_WHITESPACE token. + $tokens[] = new static(\T_WHITESPACE, $trailingNewline, $line, $pos); + $line++; + $pos += \strlen($trailingNewline); + } + continue; + } + + // Emulate PHP 8.0 T_NAME_* tokens, by combining sequences of T_NS_SEPARATOR and + // T_STRING into a single token. + if (($id === \T_NS_SEPARATOR || isset(self::$identifierTokens[$id]))) { + $newText = $text; + $lastWasSeparator = $id === \T_NS_SEPARATOR; + for ($j = $i + 1; $j < $numTokens; $j++) { + if ($lastWasSeparator) { + if (!isset(self::$identifierTokens[$origTokens[$j][0]])) { + break; + } + $lastWasSeparator = false; + } else { + if ($origTokens[$j][0] !== \T_NS_SEPARATOR) { + break; + } + $lastWasSeparator = true; + } + $newText .= $origTokens[$j][1]; + } + if ($lastWasSeparator) { + // Trailing separator is not part of the name. + $j--; + $newText = \substr($newText, 0, -1); + } + if ($j > $i + 1) { + if ($id === \T_NS_SEPARATOR) { + $id = \T_NAME_FULLY_QUALIFIED; + } elseif ($id === \T_NAMESPACE) { + $id = \T_NAME_RELATIVE; + } else { + $id = \T_NAME_QUALIFIED; + } + $tokens[] = new static($id, $newText, $line, $pos); + $pos += \strlen($newText); + $i = $j - 1; + continue; + } + } + + $tokens[] = new static($id, $text, $line, $pos); + $line += \substr_count($text, "\n"); + $pos += \strlen($text); + } + } + return $tokens; + } + + /** Initialize private static state needed by tokenize(). */ + private static function init(): void { + if (isset(self::$identifierTokens)) { + return; + } + + // Based on semi_reserved production. + self::$identifierTokens = \array_fill_keys([ + \T_STRING, + \T_STATIC, \T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_READONLY, + \T_INCLUDE, \T_INCLUDE_ONCE, \T_EVAL, \T_REQUIRE, \T_REQUIRE_ONCE, \T_LOGICAL_OR, \T_LOGICAL_XOR, \T_LOGICAL_AND, + \T_INSTANCEOF, \T_NEW, \T_CLONE, \T_EXIT, \T_IF, \T_ELSEIF, \T_ELSE, \T_ENDIF, \T_ECHO, \T_DO, \T_WHILE, + \T_ENDWHILE, \T_FOR, \T_ENDFOR, \T_FOREACH, \T_ENDFOREACH, \T_DECLARE, \T_ENDDECLARE, \T_AS, \T_TRY, \T_CATCH, + \T_FINALLY, \T_THROW, \T_USE, \T_INSTEADOF, \T_GLOBAL, \T_VAR, \T_UNSET, \T_ISSET, \T_EMPTY, \T_CONTINUE, \T_GOTO, + \T_FUNCTION, \T_CONST, \T_RETURN, \T_PRINT, \T_YIELD, \T_LIST, \T_SWITCH, \T_ENDSWITCH, \T_CASE, \T_DEFAULT, + \T_BREAK, \T_ARRAY, \T_CALLABLE, \T_EXTENDS, \T_IMPLEMENTS, \T_NAMESPACE, \T_TRAIT, \T_INTERFACE, \T_CLASS, + \T_CLASS_C, \T_TRAIT_C, \T_FUNC_C, \T_METHOD_C, \T_LINE, \T_FILE, \T_DIR, \T_NS_C, \T_HALT_COMPILER, \T_FN, + \T_MATCH, + ], true); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenStream.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenStream.php new file mode 100644 index 0000000..c02844a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenStream.php @@ -0,0 +1,275 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Internal; + +use PhpParser\Token; + +/** + * Provides operations on token streams, for use by pretty printer. + * + * @internal + */ +class TokenStream { + /** @var Token[] Tokens (in PhpToken::tokenize() format) */ + private array $tokens; + /** @var int[] Map from position to indentation */ + private array $indentMap; + + /** + * Create token stream instance. + * + * @param Token[] $tokens Tokens in PhpToken::tokenize() format + */ + public function __construct(array $tokens) { + $this->tokens = $tokens; + $this->indentMap = $this->calcIndentMap(); + } + + /** + * Whether the given position is immediately surrounded by parenthesis. + * + * @param int $startPos Start position + * @param int $endPos End position + */ + public function haveParens(int $startPos, int $endPos): bool { + return $this->haveTokenImmediatelyBefore($startPos, '(') + && $this->haveTokenImmediatelyAfter($endPos, ')'); + } + + /** + * Whether the given position is immediately surrounded by braces. + * + * @param int $startPos Start position + * @param int $endPos End position + */ + public function haveBraces(int $startPos, int $endPos): bool { + return ($this->haveTokenImmediatelyBefore($startPos, '{') + || $this->haveTokenImmediatelyBefore($startPos, T_CURLY_OPEN)) + && $this->haveTokenImmediatelyAfter($endPos, '}'); + } + + /** + * Check whether the position is directly preceded by a certain token type. + * + * During this check whitespace and comments are skipped. + * + * @param int $pos Position before which the token should occur + * @param int|string $expectedTokenType Token to check for + * + * @return bool Whether the expected token was found + */ + public function haveTokenImmediatelyBefore(int $pos, $expectedTokenType): bool { + $tokens = $this->tokens; + $pos--; + for (; $pos >= 0; $pos--) { + $token = $tokens[$pos]; + if ($token->is($expectedTokenType)) { + return true; + } + if (!$token->isIgnorable()) { + break; + } + } + return false; + } + + /** + * Check whether the position is directly followed by a certain token type. + * + * During this check whitespace and comments are skipped. + * + * @param int $pos Position after which the token should occur + * @param int|string $expectedTokenType Token to check for + * + * @return bool Whether the expected token was found + */ + public function haveTokenImmediatelyAfter(int $pos, $expectedTokenType): bool { + $tokens = $this->tokens; + $pos++; + for ($c = \count($tokens); $pos < $c; $pos++) { + $token = $tokens[$pos]; + if ($token->is($expectedTokenType)) { + return true; + } + if (!$token->isIgnorable()) { + break; + } + } + return false; + } + + /** @param int|string|(int|string)[] $skipTokenType */ + public function skipLeft(int $pos, $skipTokenType): int { + $tokens = $this->tokens; + + $pos = $this->skipLeftWhitespace($pos); + if ($skipTokenType === \T_WHITESPACE) { + return $pos; + } + + if (!$tokens[$pos]->is($skipTokenType)) { + // Shouldn't happen. The skip token MUST be there + throw new \Exception('Encountered unexpected token'); + } + $pos--; + + return $this->skipLeftWhitespace($pos); + } + + /** @param int|string|(int|string)[] $skipTokenType */ + public function skipRight(int $pos, $skipTokenType): int { + $tokens = $this->tokens; + + $pos = $this->skipRightWhitespace($pos); + if ($skipTokenType === \T_WHITESPACE) { + return $pos; + } + + if (!$tokens[$pos]->is($skipTokenType)) { + // Shouldn't happen. The skip token MUST be there + throw new \Exception('Encountered unexpected token'); + } + $pos++; + + return $this->skipRightWhitespace($pos); + } + + /** + * Return first non-whitespace token position smaller or equal to passed position. + * + * @param int $pos Token position + * @return int Non-whitespace token position + */ + public function skipLeftWhitespace(int $pos): int { + $tokens = $this->tokens; + for (; $pos >= 0; $pos--) { + if (!$tokens[$pos]->isIgnorable()) { + break; + } + } + return $pos; + } + + /** + * Return first non-whitespace position greater or equal to passed position. + * + * @param int $pos Token position + * @return int Non-whitespace token position + */ + public function skipRightWhitespace(int $pos): int { + $tokens = $this->tokens; + for ($count = \count($tokens); $pos < $count; $pos++) { + if (!$tokens[$pos]->isIgnorable()) { + break; + } + } + return $pos; + } + + /** @param int|string|(int|string)[] $findTokenType */ + public function findRight(int $pos, $findTokenType): int { + $tokens = $this->tokens; + for ($count = \count($tokens); $pos < $count; $pos++) { + if ($tokens[$pos]->is($findTokenType)) { + return $pos; + } + } + return -1; + } + + /** + * Whether the given position range contains a certain token type. + * + * @param int $startPos Starting position (inclusive) + * @param int $endPos Ending position (exclusive) + * @param int|string $tokenType Token type to look for + * @return bool Whether the token occurs in the given range + */ + public function haveTokenInRange(int $startPos, int $endPos, $tokenType): bool { + $tokens = $this->tokens; + for ($pos = $startPos; $pos < $endPos; $pos++) { + if ($tokens[$pos]->is($tokenType)) { + return true; + } + } + return false; + } + + public function haveTagInRange(int $startPos, int $endPos): bool { + return $this->haveTokenInRange($startPos, $endPos, \T_OPEN_TAG) + || $this->haveTokenInRange($startPos, $endPos, \T_CLOSE_TAG); + } + + /** + * Get indentation before token position. + * + * @param int $pos Token position + * + * @return int Indentation depth (in spaces) + */ + public function getIndentationBefore(int $pos): int { + return $this->indentMap[$pos]; + } + + /** + * Get the code corresponding to a token offset range, optionally adjusted for indentation. + * + * @param int $from Token start position (inclusive) + * @param int $to Token end position (exclusive) + * @param int $indent By how much the code should be indented (can be negative as well) + * + * @return string Code corresponding to token range, adjusted for indentation + */ + public function getTokenCode(int $from, int $to, int $indent): string { + $tokens = $this->tokens; + $result = ''; + for ($pos = $from; $pos < $to; $pos++) { + $token = $tokens[$pos]; + $id = $token->id; + $text = $token->text; + if ($id === \T_CONSTANT_ENCAPSED_STRING || $id === \T_ENCAPSED_AND_WHITESPACE) { + $result .= $text; + } else { + // TODO Handle non-space indentation + if ($indent < 0) { + $result .= str_replace("\n" . str_repeat(" ", -$indent), "\n", $text); + } elseif ($indent > 0) { + $result .= str_replace("\n", "\n" . str_repeat(" ", $indent), $text); + } else { + $result .= $text; + } + } + } + return $result; + } + + /** + * Precalculate the indentation at every token position. + * + * @return int[] Token position to indentation map + */ + private function calcIndentMap(): array { + $indentMap = []; + $indent = 0; + foreach ($this->tokens as $i => $token) { + $indentMap[] = $indent; + + if ($token->id === \T_WHITESPACE) { + $content = $token->text; + $newlinePos = \strrpos($content, "\n"); + if (false !== $newlinePos) { + $indent = \strlen($content) - $newlinePos - 1; + } elseif ($i === 1 && $this->tokens[0]->id === \T_OPEN_TAG && + $this->tokens[0]->text[\strlen($this->tokens[0]->text) - 1] === "\n") { + // Special case: Newline at the end of opening tag followed by whitespace. + $indent = \strlen($content); + } + } + } + + // Add a sentinel for one past end of the file + $indentMap[] = $indent; + + return $indentMap; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/JsonDecoder.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/JsonDecoder.php new file mode 100644 index 0000000..7be4142 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/JsonDecoder.php @@ -0,0 +1,108 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +class JsonDecoder { + /** @var \ReflectionClass<Node>[] Node type to reflection class map */ + private array $reflectionClassCache; + + /** @return mixed */ + public function decode(string $json) { + $value = json_decode($json, true); + if (json_last_error()) { + throw new \RuntimeException('JSON decoding error: ' . json_last_error_msg()); + } + + return $this->decodeRecursive($value); + } + + /** + * @param mixed $value + * @return mixed + */ + private function decodeRecursive($value) { + if (\is_array($value)) { + if (isset($value['nodeType'])) { + if ($value['nodeType'] === 'Comment' || $value['nodeType'] === 'Comment_Doc') { + return $this->decodeComment($value); + } + return $this->decodeNode($value); + } + return $this->decodeArray($value); + } + return $value; + } + + private function decodeArray(array $array): array { + $decodedArray = []; + foreach ($array as $key => $value) { + $decodedArray[$key] = $this->decodeRecursive($value); + } + return $decodedArray; + } + + private function decodeNode(array $value): Node { + $nodeType = $value['nodeType']; + if (!\is_string($nodeType)) { + throw new \RuntimeException('Node type must be a string'); + } + + $reflectionClass = $this->reflectionClassFromNodeType($nodeType); + $node = $reflectionClass->newInstanceWithoutConstructor(); + + if (isset($value['attributes'])) { + if (!\is_array($value['attributes'])) { + throw new \RuntimeException('Attributes must be an array'); + } + + $node->setAttributes($this->decodeArray($value['attributes'])); + } + + foreach ($value as $name => $subNode) { + if ($name === 'nodeType' || $name === 'attributes') { + continue; + } + + $node->$name = $this->decodeRecursive($subNode); + } + + return $node; + } + + private function decodeComment(array $value): Comment { + $className = $value['nodeType'] === 'Comment' ? Comment::class : Comment\Doc::class; + if (!isset($value['text'])) { + throw new \RuntimeException('Comment must have text'); + } + + return new $className( + $value['text'], + $value['line'] ?? -1, $value['filePos'] ?? -1, $value['tokenPos'] ?? -1, + $value['endLine'] ?? -1, $value['endFilePos'] ?? -1, $value['endTokenPos'] ?? -1 + ); + } + + /** @return \ReflectionClass<Node> */ + private function reflectionClassFromNodeType(string $nodeType): \ReflectionClass { + if (!isset($this->reflectionClassCache[$nodeType])) { + $className = $this->classNameFromNodeType($nodeType); + $this->reflectionClassCache[$nodeType] = new \ReflectionClass($className); + } + return $this->reflectionClassCache[$nodeType]; + } + + /** @return class-string<Node> */ + private function classNameFromNodeType(string $nodeType): string { + $className = 'PhpParser\\Node\\' . strtr($nodeType, '_', '\\'); + if (class_exists($className)) { + return $className; + } + + $className .= '_'; + if (class_exists($className)) { + return $className; + } + + throw new \RuntimeException("Unknown node type \"$nodeType\""); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer.php new file mode 100644 index 0000000..5e2ece9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer.php @@ -0,0 +1,116 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +require __DIR__ . '/compatibility_tokens.php'; + +class Lexer { + /** + * Tokenize the provided source code. + * + * The token array is in the same format as provided by the PhpToken::tokenize() method in + * PHP 8.0. The tokens are instances of PhpParser\Token, to abstract over a polyfill + * implementation in earlier PHP version. + * + * The token array is terminated by a sentinel token with token ID 0. + * The token array does not discard any tokens (i.e. whitespace and comments are included). + * The token position attributes are against this token array. + * + * @param string $code The source code to tokenize. + * @param ErrorHandler|null $errorHandler Error handler to use for lexing errors. Defaults to + * ErrorHandler\Throwing. + * @return Token[] Tokens + */ + public function tokenize(string $code, ?ErrorHandler $errorHandler = null): array { + if (null === $errorHandler) { + $errorHandler = new ErrorHandler\Throwing(); + } + + $scream = ini_set('xdebug.scream', '0'); + + $tokens = @Token::tokenize($code); + $this->postprocessTokens($tokens, $errorHandler); + + if (false !== $scream) { + ini_set('xdebug.scream', $scream); + } + + return $tokens; + } + + private function handleInvalidCharacter(Token $token, ErrorHandler $errorHandler): void { + $chr = $token->text; + if ($chr === "\0") { + // PHP cuts error message after null byte, so need special case + $errorMsg = 'Unexpected null byte'; + } else { + $errorMsg = sprintf( + 'Unexpected character "%s" (ASCII %d)', $chr, ord($chr) + ); + } + + $errorHandler->handleError(new Error($errorMsg, [ + 'startLine' => $token->line, + 'endLine' => $token->line, + 'startFilePos' => $token->pos, + 'endFilePos' => $token->pos, + ])); + } + + private function isUnterminatedComment(Token $token): bool { + return $token->is([\T_COMMENT, \T_DOC_COMMENT]) + && substr($token->text, 0, 2) === '/*' + && substr($token->text, -2) !== '*/'; + } + + /** + * @param list<Token> $tokens + */ + protected function postprocessTokens(array &$tokens, ErrorHandler $errorHandler): void { + // This function reports errors (bad characters and unterminated comments) in the token + // array, and performs certain canonicalizations: + // * Use PHP 8.1 T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG and + // T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG tokens used to disambiguate intersection types. + // * Add a sentinel token with ID 0. + + $numTokens = \count($tokens); + if ($numTokens === 0) { + // Empty input edge case: Just add the sentinel token. + $tokens[] = new Token(0, "\0", 1, 0); + return; + } + + for ($i = 0; $i < $numTokens; $i++) { + $token = $tokens[$i]; + if ($token->id === \T_BAD_CHARACTER) { + $this->handleInvalidCharacter($token, $errorHandler); + } + + if ($token->id === \ord('&')) { + $next = $i + 1; + while (isset($tokens[$next]) && $tokens[$next]->id === \T_WHITESPACE) { + $next++; + } + $followedByVarOrVarArg = isset($tokens[$next]) && + $tokens[$next]->is([\T_VARIABLE, \T_ELLIPSIS]); + $token->id = $followedByVarOrVarArg + ? \T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG + : \T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG; + } + } + + // Check for unterminated comment + $lastToken = $tokens[$numTokens - 1]; + if ($this->isUnterminatedComment($lastToken)) { + $errorHandler->handleError(new Error('Unterminated comment', [ + 'startLine' => $lastToken->line, + 'endLine' => $lastToken->getEndLine(), + 'startFilePos' => $lastToken->pos, + 'endFilePos' => $lastToken->getEndPos(), + ])); + } + + // Add sentinel token. + $tokens[] = new Token(0, "\0", $lastToken->getEndLine(), $lastToken->getEndPos()); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/Emulative.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/Emulative.php new file mode 100644 index 0000000..934954c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/Emulative.php @@ -0,0 +1,226 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer; + +use PhpParser\Error; +use PhpParser\ErrorHandler; +use PhpParser\Lexer; +use PhpParser\Lexer\TokenEmulator\AttributeEmulator; +use PhpParser\Lexer\TokenEmulator\EnumTokenEmulator; +use PhpParser\Lexer\TokenEmulator\CoaleseEqualTokenEmulator; +use PhpParser\Lexer\TokenEmulator\ExplicitOctalEmulator; +use PhpParser\Lexer\TokenEmulator\FlexibleDocStringEmulator; +use PhpParser\Lexer\TokenEmulator\FnTokenEmulator; +use PhpParser\Lexer\TokenEmulator\MatchTokenEmulator; +use PhpParser\Lexer\TokenEmulator\NullsafeTokenEmulator; +use PhpParser\Lexer\TokenEmulator\NumericLiteralSeparatorEmulator; +use PhpParser\Lexer\TokenEmulator\ReadonlyFunctionTokenEmulator; +use PhpParser\Lexer\TokenEmulator\ReadonlyTokenEmulator; +use PhpParser\Lexer\TokenEmulator\ReverseEmulator; +use PhpParser\Lexer\TokenEmulator\TokenEmulator; +use PhpParser\PhpVersion; +use PhpParser\Token; + +class Emulative extends Lexer { + /** @var array{int, string, string}[] Patches used to reverse changes introduced in the code */ + private array $patches = []; + + /** @var list<TokenEmulator> */ + private array $emulators = []; + + private PhpVersion $targetPhpVersion; + + private PhpVersion $hostPhpVersion; + + /** + * @param PhpVersion|null $phpVersion PHP version to emulate. Defaults to newest supported. + */ + public function __construct(?PhpVersion $phpVersion = null) { + $this->targetPhpVersion = $phpVersion ?? PhpVersion::getNewestSupported(); + $this->hostPhpVersion = PhpVersion::getHostVersion(); + + $emulators = [ + new MatchTokenEmulator(), + new NullsafeTokenEmulator(), + new AttributeEmulator(), + new EnumTokenEmulator(), + new ReadonlyTokenEmulator(), + new ExplicitOctalEmulator(), + new ReadonlyFunctionTokenEmulator(), + ]; + + // Collect emulators that are relevant for the PHP version we're running + // and the PHP version we're targeting for emulation. + foreach ($emulators as $emulator) { + $emulatorPhpVersion = $emulator->getPhpVersion(); + if ($this->isForwardEmulationNeeded($emulatorPhpVersion)) { + $this->emulators[] = $emulator; + } elseif ($this->isReverseEmulationNeeded($emulatorPhpVersion)) { + $this->emulators[] = new ReverseEmulator($emulator); + } + } + } + + public function tokenize(string $code, ?ErrorHandler $errorHandler = null): array { + $emulators = array_filter($this->emulators, function ($emulator) use ($code) { + return $emulator->isEmulationNeeded($code); + }); + + if (empty($emulators)) { + // Nothing to emulate, yay + return parent::tokenize($code, $errorHandler); + } + + if ($errorHandler === null) { + $errorHandler = new ErrorHandler\Throwing(); + } + + $this->patches = []; + foreach ($emulators as $emulator) { + $code = $emulator->preprocessCode($code, $this->patches); + } + + $collector = new ErrorHandler\Collecting(); + $tokens = parent::tokenize($code, $collector); + $this->sortPatches(); + $tokens = $this->fixupTokens($tokens); + + $errors = $collector->getErrors(); + if (!empty($errors)) { + $this->fixupErrors($errors); + foreach ($errors as $error) { + $errorHandler->handleError($error); + } + } + + foreach ($emulators as $emulator) { + $tokens = $emulator->emulate($code, $tokens); + } + + return $tokens; + } + + private function isForwardEmulationNeeded(PhpVersion $emulatorPhpVersion): bool { + return $this->hostPhpVersion->older($emulatorPhpVersion) + && $this->targetPhpVersion->newerOrEqual($emulatorPhpVersion); + } + + private function isReverseEmulationNeeded(PhpVersion $emulatorPhpVersion): bool { + return $this->hostPhpVersion->newerOrEqual($emulatorPhpVersion) + && $this->targetPhpVersion->older($emulatorPhpVersion); + } + + private function sortPatches(): void { + // Patches may be contributed by different emulators. + // Make sure they are sorted by increasing patch position. + usort($this->patches, function ($p1, $p2) { + return $p1[0] <=> $p2[0]; + }); + } + + /** + * @param list<Token> $tokens + * @return list<Token> + */ + private function fixupTokens(array $tokens): array { + if (\count($this->patches) === 0) { + return $tokens; + } + + // Load first patch + $patchIdx = 0; + list($patchPos, $patchType, $patchText) = $this->patches[$patchIdx]; + + // We use a manual loop over the tokens, because we modify the array on the fly + $posDelta = 0; + $lineDelta = 0; + for ($i = 0, $c = \count($tokens); $i < $c; $i++) { + $token = $tokens[$i]; + $pos = $token->pos; + $token->pos += $posDelta; + $token->line += $lineDelta; + $localPosDelta = 0; + $len = \strlen($token->text); + while ($patchPos >= $pos && $patchPos < $pos + $len) { + $patchTextLen = \strlen($patchText); + if ($patchType === 'remove') { + if ($patchPos === $pos && $patchTextLen === $len) { + // Remove token entirely + array_splice($tokens, $i, 1, []); + $i--; + $c--; + } else { + // Remove from token string + $token->text = substr_replace( + $token->text, '', $patchPos - $pos + $localPosDelta, $patchTextLen + ); + $localPosDelta -= $patchTextLen; + } + $lineDelta -= \substr_count($patchText, "\n"); + } elseif ($patchType === 'add') { + // Insert into the token string + $token->text = substr_replace( + $token->text, $patchText, $patchPos - $pos + $localPosDelta, 0 + ); + $localPosDelta += $patchTextLen; + $lineDelta += \substr_count($patchText, "\n"); + } elseif ($patchType === 'replace') { + // Replace inside the token string + $token->text = substr_replace( + $token->text, $patchText, $patchPos - $pos + $localPosDelta, $patchTextLen + ); + } else { + assert(false); + } + + // Fetch the next patch + $patchIdx++; + if ($patchIdx >= \count($this->patches)) { + // No more patches. However, we still need to adjust position. + $patchPos = \PHP_INT_MAX; + break; + } + + list($patchPos, $patchType, $patchText) = $this->patches[$patchIdx]; + } + + $posDelta += $localPosDelta; + } + return $tokens; + } + + /** + * Fixup line and position information in errors. + * + * @param Error[] $errors + */ + private function fixupErrors(array $errors): void { + foreach ($errors as $error) { + $attrs = $error->getAttributes(); + + $posDelta = 0; + $lineDelta = 0; + foreach ($this->patches as $patch) { + list($patchPos, $patchType, $patchText) = $patch; + if ($patchPos >= $attrs['startFilePos']) { + // No longer relevant + break; + } + + if ($patchType === 'add') { + $posDelta += strlen($patchText); + $lineDelta += substr_count($patchText, "\n"); + } elseif ($patchType === 'remove') { + $posDelta -= strlen($patchText); + $lineDelta -= substr_count($patchText, "\n"); + } + } + + $attrs['startFilePos'] += $posDelta; + $attrs['endFilePos'] += $posDelta; + $attrs['startLine'] += $lineDelta; + $attrs['endLine'] += $lineDelta; + $error->setAttributes($attrs); + } + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/AttributeEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/AttributeEmulator.php new file mode 100644 index 0000000..2c12f33 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/AttributeEmulator.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; +use PhpParser\Token; + +final class AttributeEmulator extends TokenEmulator { + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 0); + } + + public function isEmulationNeeded(string $code): bool { + return strpos($code, '#[') !== false; + } + + public function emulate(string $code, array $tokens): array { + // We need to manually iterate and manage a count because we'll change + // the tokens array on the way. + for ($i = 0, $c = count($tokens); $i < $c; ++$i) { + $token = $tokens[$i]; + if ($token->text === '#' && isset($tokens[$i + 1]) && $tokens[$i + 1]->text === '[') { + array_splice($tokens, $i, 2, [ + new Token(\T_ATTRIBUTE, '#[', $token->line, $token->pos), + ]); + $c--; + continue; + } + } + + return $tokens; + } + + public function reverseEmulate(string $code, array $tokens): array { + // TODO + return $tokens; + } + + public function preprocessCode(string $code, array &$patches): string { + $pos = 0; + while (false !== $pos = strpos($code, '#[', $pos)) { + // Replace #[ with %[ + $code[$pos] = '%'; + $patches[] = [$pos, 'replace', '#']; + $pos += 2; + } + return $code; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/EnumTokenEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/EnumTokenEmulator.php new file mode 100644 index 0000000..5418f52 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/EnumTokenEmulator.php @@ -0,0 +1,26 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; + +final class EnumTokenEmulator extends KeywordEmulator { + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 1); + } + + public function getKeywordString(): string { + return 'enum'; + } + + public function getKeywordToken(): int { + return \T_ENUM; + } + + protected function isKeywordContext(array $tokens, int $pos): bool { + return parent::isKeywordContext($tokens, $pos) + && isset($tokens[$pos + 2]) + && $tokens[$pos + 1]->id === \T_WHITESPACE + && $tokens[$pos + 2]->id === \T_STRING; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ExplicitOctalEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ExplicitOctalEmulator.php new file mode 100644 index 0000000..9cadf42 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ExplicitOctalEmulator.php @@ -0,0 +1,45 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; +use PhpParser\Token; + +class ExplicitOctalEmulator extends TokenEmulator { + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 1); + } + + public function isEmulationNeeded(string $code): bool { + return strpos($code, '0o') !== false || strpos($code, '0O') !== false; + } + + public function emulate(string $code, array $tokens): array { + for ($i = 0, $c = count($tokens); $i < $c; ++$i) { + $token = $tokens[$i]; + if ($token->id == \T_LNUMBER && $token->text === '0' && + isset($tokens[$i + 1]) && $tokens[$i + 1]->id == \T_STRING && + preg_match('/[oO][0-7]+(?:_[0-7]+)*/', $tokens[$i + 1]->text) + ) { + $tokenKind = $this->resolveIntegerOrFloatToken($tokens[$i + 1]->text); + array_splice($tokens, $i, 2, [ + new Token($tokenKind, '0' . $tokens[$i + 1]->text, $token->line, $token->pos), + ]); + $c--; + } + } + return $tokens; + } + + private function resolveIntegerOrFloatToken(string $str): int { + $str = substr($str, 1); + $str = str_replace('_', '', $str); + $num = octdec($str); + return is_float($num) ? \T_DNUMBER : \T_LNUMBER; + } + + public function reverseEmulate(string $code, array $tokens): array { + // Explicit octals were not legal code previously, don't bother. + return $tokens; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/KeywordEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/KeywordEmulator.php new file mode 100644 index 0000000..9803f99 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/KeywordEmulator.php @@ -0,0 +1,56 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\Token; + +abstract class KeywordEmulator extends TokenEmulator { + abstract public function getKeywordString(): string; + abstract public function getKeywordToken(): int; + + public function isEmulationNeeded(string $code): bool { + return strpos(strtolower($code), $this->getKeywordString()) !== false; + } + + /** @param Token[] $tokens */ + protected function isKeywordContext(array $tokens, int $pos): bool { + $previousNonSpaceToken = $this->getPreviousNonSpaceToken($tokens, $pos); + return $previousNonSpaceToken === null || $previousNonSpaceToken->id !== \T_OBJECT_OPERATOR; + } + + public function emulate(string $code, array $tokens): array { + $keywordString = $this->getKeywordString(); + foreach ($tokens as $i => $token) { + if ($token->id === T_STRING && strtolower($token->text) === $keywordString + && $this->isKeywordContext($tokens, $i)) { + $token->id = $this->getKeywordToken(); + } + } + + return $tokens; + } + + /** @param Token[] $tokens */ + private function getPreviousNonSpaceToken(array $tokens, int $start): ?Token { + for ($i = $start - 1; $i >= 0; --$i) { + if ($tokens[$i]->id === T_WHITESPACE) { + continue; + } + + return $tokens[$i]; + } + + return null; + } + + public function reverseEmulate(string $code, array $tokens): array { + $keywordToken = $this->getKeywordToken(); + foreach ($tokens as $token) { + if ($token->id === $keywordToken) { + $token->id = \T_STRING; + } + } + + return $tokens; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/MatchTokenEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/MatchTokenEmulator.php new file mode 100644 index 0000000..0fa5fbc --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/MatchTokenEmulator.php @@ -0,0 +1,19 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; + +final class MatchTokenEmulator extends KeywordEmulator { + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 0); + } + + public function getKeywordString(): string { + return 'match'; + } + + public function getKeywordToken(): int { + return \T_MATCH; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NullsafeTokenEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NullsafeTokenEmulator.php new file mode 100644 index 0000000..cede96f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NullsafeTokenEmulator.php @@ -0,0 +1,60 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; +use PhpParser\Token; + +final class NullsafeTokenEmulator extends TokenEmulator { + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 0); + } + + public function isEmulationNeeded(string $code): bool { + return strpos($code, '?->') !== false; + } + + public function emulate(string $code, array $tokens): array { + // We need to manually iterate and manage a count because we'll change + // the tokens array on the way + for ($i = 0, $c = count($tokens); $i < $c; ++$i) { + $token = $tokens[$i]; + if ($token->text === '?' && isset($tokens[$i + 1]) && $tokens[$i + 1]->id === \T_OBJECT_OPERATOR) { + array_splice($tokens, $i, 2, [ + new Token(\T_NULLSAFE_OBJECT_OPERATOR, '?->', $token->line, $token->pos), + ]); + $c--; + continue; + } + + // Handle ?-> inside encapsed string. + if ($token->id === \T_ENCAPSED_AND_WHITESPACE && isset($tokens[$i - 1]) + && $tokens[$i - 1]->id === \T_VARIABLE + && preg_match('/^\?->([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/', $token->text, $matches) + ) { + $replacement = [ + new Token(\T_NULLSAFE_OBJECT_OPERATOR, '?->', $token->line, $token->pos), + new Token(\T_STRING, $matches[1], $token->line, $token->pos + 3), + ]; + $matchLen = \strlen($matches[0]); + if ($matchLen !== \strlen($token->text)) { + $replacement[] = new Token( + \T_ENCAPSED_AND_WHITESPACE, + \substr($token->text, $matchLen), + $token->line, $token->pos + $matchLen + ); + } + array_splice($tokens, $i, 1, $replacement); + $c += \count($replacement) - 1; + continue; + } + } + + return $tokens; + } + + public function reverseEmulate(string $code, array $tokens): array { + // ?-> was not valid code previously, don't bother. + return $tokens; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReadonlyFunctionTokenEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReadonlyFunctionTokenEmulator.php new file mode 100644 index 0000000..5990d7f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReadonlyFunctionTokenEmulator.php @@ -0,0 +1,31 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; + +/* + * In PHP 8.1, "readonly(" was special cased in the lexer in order to support functions with + * name readonly. In PHP 8.2, this may conflict with readonly properties having a DNF type. For + * this reason, PHP 8.2 instead treats this as T_READONLY and then handles it specially in the + * parser. This emulator only exists to handle this special case, which is skipped by the + * PHP 8.1 ReadonlyTokenEmulator. + */ +class ReadonlyFunctionTokenEmulator extends KeywordEmulator { + public function getKeywordString(): string { + return 'readonly'; + } + + public function getKeywordToken(): int { + return \T_READONLY; + } + + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 2); + } + + public function reverseEmulate(string $code, array $tokens): array { + // Don't bother + return $tokens; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReadonlyTokenEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReadonlyTokenEmulator.php new file mode 100644 index 0000000..37240f7 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReadonlyTokenEmulator.php @@ -0,0 +1,31 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; + +final class ReadonlyTokenEmulator extends KeywordEmulator { + public function getPhpVersion(): PhpVersion { + return PhpVersion::fromComponents(8, 1); + } + + public function getKeywordString(): string { + return 'readonly'; + } + + public function getKeywordToken(): int { + return \T_READONLY; + } + + protected function isKeywordContext(array $tokens, int $pos): bool { + if (!parent::isKeywordContext($tokens, $pos)) { + return false; + } + // Support "function readonly(" + return !(isset($tokens[$pos + 1]) && + ($tokens[$pos + 1]->text === '(' || + ($tokens[$pos + 1]->id === \T_WHITESPACE && + isset($tokens[$pos + 2]) && + $tokens[$pos + 2]->text === '('))); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReverseEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReverseEmulator.php new file mode 100644 index 0000000..851b5c4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReverseEmulator.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; + +/** + * Reverses emulation direction of the inner emulator. + */ +final class ReverseEmulator extends TokenEmulator { + /** @var TokenEmulator Inner emulator */ + private TokenEmulator $emulator; + + public function __construct(TokenEmulator $emulator) { + $this->emulator = $emulator; + } + + public function getPhpVersion(): PhpVersion { + return $this->emulator->getPhpVersion(); + } + + public function isEmulationNeeded(string $code): bool { + return $this->emulator->isEmulationNeeded($code); + } + + public function emulate(string $code, array $tokens): array { + return $this->emulator->reverseEmulate($code, $tokens); + } + + public function reverseEmulate(string $code, array $tokens): array { + return $this->emulator->emulate($code, $tokens); + } + + public function preprocessCode(string $code, array &$patches): string { + return $code; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/TokenEmulator.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/TokenEmulator.php new file mode 100644 index 0000000..fec2f19 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/TokenEmulator.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Lexer\TokenEmulator; + +use PhpParser\PhpVersion; +use PhpParser\Token; + +/** @internal */ +abstract class TokenEmulator { + abstract public function getPhpVersion(): PhpVersion; + + abstract public function isEmulationNeeded(string $code): bool; + + /** + * @param Token[] $tokens Original tokens + * @return Token[] Modified Tokens + */ + abstract public function emulate(string $code, array $tokens): array; + + /** + * @param Token[] $tokens Original tokens + * @return Token[] Modified Tokens + */ + abstract public function reverseEmulate(string $code, array $tokens): array; + + /** @param array{int, string, string}[] $patches */ + public function preprocessCode(string $code, array &$patches): string { + return $code; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Modifiers.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Modifiers.php new file mode 100644 index 0000000..b7120ee --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Modifiers.php @@ -0,0 +1,69 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +/** + * Modifiers used (as a bit mask) by various flags subnodes, for example on classes, functions, + * properties and constants. + */ +final class Modifiers { + public const PUBLIC = 1; + public const PROTECTED = 2; + public const PRIVATE = 4; + public const STATIC = 8; + public const ABSTRACT = 16; + public const FINAL = 32; + public const READONLY = 64; + + public const VISIBILITY_MASK = 1 | 2 | 4; + + /** + * @internal + */ + public static function verifyClassModifier(int $a, int $b): void { + if ($a & Modifiers::ABSTRACT && $b & Modifiers::ABSTRACT) { + throw new Error('Multiple abstract modifiers are not allowed'); + } + + if ($a & Modifiers::FINAL && $b & Modifiers::FINAL) { + throw new Error('Multiple final modifiers are not allowed'); + } + + if ($a & Modifiers::READONLY && $b & Modifiers::READONLY) { + throw new Error('Multiple readonly modifiers are not allowed'); + } + + if ($a & 48 && $b & 48) { + throw new Error('Cannot use the final modifier on an abstract class'); + } + } + + /** + * @internal + */ + public static function verifyModifier(int $a, int $b): void { + if ($a & Modifiers::VISIBILITY_MASK && $b & Modifiers::VISIBILITY_MASK) { + throw new Error('Multiple access type modifiers are not allowed'); + } + + if ($a & Modifiers::ABSTRACT && $b & Modifiers::ABSTRACT) { + throw new Error('Multiple abstract modifiers are not allowed'); + } + + if ($a & Modifiers::STATIC && $b & Modifiers::STATIC) { + throw new Error('Multiple static modifiers are not allowed'); + } + + if ($a & Modifiers::FINAL && $b & Modifiers::FINAL) { + throw new Error('Multiple final modifiers are not allowed'); + } + + if ($a & Modifiers::READONLY && $b & Modifiers::READONLY) { + throw new Error('Multiple readonly modifiers are not allowed'); + } + + if ($a & 48 && $b & 48) { + throw new Error('Cannot use the final modifier on an abstract class member'); + } + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NameContext.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NameContext.php new file mode 100644 index 0000000..292df69 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NameContext.php @@ -0,0 +1,284 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; +use PhpParser\Node\Stmt; + +class NameContext { + /** @var null|Name Current namespace */ + protected ?Name $namespace; + + /** @var Name[][] Map of format [aliasType => [aliasName => originalName]] */ + protected array $aliases = []; + + /** @var Name[][] Same as $aliases but preserving original case */ + protected array $origAliases = []; + + /** @var ErrorHandler Error handler */ + protected ErrorHandler $errorHandler; + + /** + * Create a name context. + * + * @param ErrorHandler $errorHandler Error handling used to report errors + */ + public function __construct(ErrorHandler $errorHandler) { + $this->errorHandler = $errorHandler; + } + + /** + * Start a new namespace. + * + * This also resets the alias table. + * + * @param Name|null $namespace Null is the global namespace + */ + public function startNamespace(?Name $namespace = null): void { + $this->namespace = $namespace; + $this->origAliases = $this->aliases = [ + Stmt\Use_::TYPE_NORMAL => [], + Stmt\Use_::TYPE_FUNCTION => [], + Stmt\Use_::TYPE_CONSTANT => [], + ]; + } + + /** + * Add an alias / import. + * + * @param Name $name Original name + * @param string $aliasName Aliased name + * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* + * @param array<string, mixed> $errorAttrs Attributes to use to report an error + */ + public function addAlias(Name $name, string $aliasName, int $type, array $errorAttrs = []): void { + // Constant names are case sensitive, everything else case insensitive + if ($type === Stmt\Use_::TYPE_CONSTANT) { + $aliasLookupName = $aliasName; + } else { + $aliasLookupName = strtolower($aliasName); + } + + if (isset($this->aliases[$type][$aliasLookupName])) { + $typeStringMap = [ + Stmt\Use_::TYPE_NORMAL => '', + Stmt\Use_::TYPE_FUNCTION => 'function ', + Stmt\Use_::TYPE_CONSTANT => 'const ', + ]; + + $this->errorHandler->handleError(new Error( + sprintf( + 'Cannot use %s%s as %s because the name is already in use', + $typeStringMap[$type], $name, $aliasName + ), + $errorAttrs + )); + return; + } + + $this->aliases[$type][$aliasLookupName] = $name; + $this->origAliases[$type][$aliasName] = $name; + } + + /** + * Get current namespace. + * + * @return null|Name Namespace (or null if global namespace) + */ + public function getNamespace(): ?Name { + return $this->namespace; + } + + /** + * Get resolved name. + * + * @param Name $name Name to resolve + * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_{FUNCTION|CONSTANT} + * + * @return null|Name Resolved name, or null if static resolution is not possible + */ + public function getResolvedName(Name $name, int $type): ?Name { + // don't resolve special class names + if ($type === Stmt\Use_::TYPE_NORMAL && $name->isSpecialClassName()) { + if (!$name->isUnqualified()) { + $this->errorHandler->handleError(new Error( + sprintf("'\\%s' is an invalid class name", $name->toString()), + $name->getAttributes() + )); + } + return $name; + } + + // fully qualified names are already resolved + if ($name->isFullyQualified()) { + return $name; + } + + // Try to resolve aliases + if (null !== $resolvedName = $this->resolveAlias($name, $type)) { + return $resolvedName; + } + + if ($type !== Stmt\Use_::TYPE_NORMAL && $name->isUnqualified()) { + if (null === $this->namespace) { + // outside of a namespace unaliased unqualified is same as fully qualified + return new FullyQualified($name, $name->getAttributes()); + } + + // Cannot resolve statically + return null; + } + + // if no alias exists prepend current namespace + return FullyQualified::concat($this->namespace, $name, $name->getAttributes()); + } + + /** + * Get resolved class name. + * + * @param Name $name Class ame to resolve + * + * @return Name Resolved name + */ + public function getResolvedClassName(Name $name): Name { + return $this->getResolvedName($name, Stmt\Use_::TYPE_NORMAL); + } + + /** + * Get possible ways of writing a fully qualified name (e.g., by making use of aliases). + * + * @param string $name Fully-qualified name (without leading namespace separator) + * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* + * + * @return Name[] Possible representations of the name + */ + public function getPossibleNames(string $name, int $type): array { + $lcName = strtolower($name); + + if ($type === Stmt\Use_::TYPE_NORMAL) { + // self, parent and static must always be unqualified + if ($lcName === "self" || $lcName === "parent" || $lcName === "static") { + return [new Name($name)]; + } + } + + // Collect possible ways to write this name, starting with the fully-qualified name + $possibleNames = [new FullyQualified($name)]; + + if (null !== $nsRelativeName = $this->getNamespaceRelativeName($name, $lcName, $type)) { + // Make sure there is no alias that makes the normally namespace-relative name + // into something else + if (null === $this->resolveAlias($nsRelativeName, $type)) { + $possibleNames[] = $nsRelativeName; + } + } + + // Check for relevant namespace use statements + foreach ($this->origAliases[Stmt\Use_::TYPE_NORMAL] as $alias => $orig) { + $lcOrig = $orig->toLowerString(); + if (0 === strpos($lcName, $lcOrig . '\\')) { + $possibleNames[] = new Name($alias . substr($name, strlen($lcOrig))); + } + } + + // Check for relevant type-specific use statements + foreach ($this->origAliases[$type] as $alias => $orig) { + if ($type === Stmt\Use_::TYPE_CONSTANT) { + // Constants are are complicated-sensitive + $normalizedOrig = $this->normalizeConstName($orig->toString()); + if ($normalizedOrig === $this->normalizeConstName($name)) { + $possibleNames[] = new Name($alias); + } + } else { + // Everything else is case-insensitive + if ($orig->toLowerString() === $lcName) { + $possibleNames[] = new Name($alias); + } + } + } + + return $possibleNames; + } + + /** + * Get shortest representation of this fully-qualified name. + * + * @param string $name Fully-qualified name (without leading namespace separator) + * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* + * + * @return Name Shortest representation + */ + public function getShortName(string $name, int $type): Name { + $possibleNames = $this->getPossibleNames($name, $type); + + // Find shortest name + $shortestName = null; + $shortestLength = \INF; + foreach ($possibleNames as $possibleName) { + $length = strlen($possibleName->toCodeString()); + if ($length < $shortestLength) { + $shortestName = $possibleName; + $shortestLength = $length; + } + } + + return $shortestName; + } + + private function resolveAlias(Name $name, int $type): ?FullyQualified { + $firstPart = $name->getFirst(); + + if ($name->isQualified()) { + // resolve aliases for qualified names, always against class alias table + $checkName = strtolower($firstPart); + if (isset($this->aliases[Stmt\Use_::TYPE_NORMAL][$checkName])) { + $alias = $this->aliases[Stmt\Use_::TYPE_NORMAL][$checkName]; + return FullyQualified::concat($alias, $name->slice(1), $name->getAttributes()); + } + } elseif ($name->isUnqualified()) { + // constant aliases are case-sensitive, function aliases case-insensitive + $checkName = $type === Stmt\Use_::TYPE_CONSTANT ? $firstPart : strtolower($firstPart); + if (isset($this->aliases[$type][$checkName])) { + // resolve unqualified aliases + return new FullyQualified($this->aliases[$type][$checkName], $name->getAttributes()); + } + } + + // No applicable aliases + return null; + } + + private function getNamespaceRelativeName(string $name, string $lcName, int $type): ?Name { + if (null === $this->namespace) { + return new Name($name); + } + + if ($type === Stmt\Use_::TYPE_CONSTANT) { + // The constants true/false/null always resolve to the global symbols, even inside a + // namespace, so they may be used without qualification + if ($lcName === "true" || $lcName === "false" || $lcName === "null") { + return new Name($name); + } + } + + $namespacePrefix = strtolower($this->namespace . '\\'); + if (0 === strpos($lcName, $namespacePrefix)) { + return new Name(substr($name, strlen($namespacePrefix))); + } + + return null; + } + + private function normalizeConstName(string $name): string { + $nsSep = strrpos($name, '\\'); + if (false === $nsSep) { + return $name; + } + + // Constants have case-insensitive namespace and case-sensitive short-name + $ns = substr($name, 0, $nsSep); + $shortName = substr($name, $nsSep + 1); + return strtolower($ns) . '\\' . $shortName; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node.php new file mode 100644 index 0000000..258e451 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node.php @@ -0,0 +1,146 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +interface Node { + /** + * Gets the type of the node. + * + * @return string Type of the node + */ + public function getType(): string; + + /** + * Gets the names of the sub nodes. + * + * @return string[] Names of sub nodes + */ + public function getSubNodeNames(): array; + + /** + * Gets line the node started in (alias of getStartLine). + * + * @return int Start line (or -1 if not available) + * + * @deprecated Use getStartLine() instead + */ + public function getLine(): int; + + /** + * Gets line the node started in. + * + * Requires the 'startLine' attribute to be enabled in the lexer (enabled by default). + * + * @return int Start line (or -1 if not available) + */ + public function getStartLine(): int; + + /** + * Gets the line the node ended in. + * + * Requires the 'endLine' attribute to be enabled in the lexer (enabled by default). + * + * @return int End line (or -1 if not available) + */ + public function getEndLine(): int; + + /** + * Gets the token offset of the first token that is part of this node. + * + * The offset is an index into the array returned by Lexer::getTokens(). + * + * Requires the 'startTokenPos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int Token start position (or -1 if not available) + */ + public function getStartTokenPos(): int; + + /** + * Gets the token offset of the last token that is part of this node. + * + * The offset is an index into the array returned by Lexer::getTokens(). + * + * Requires the 'endTokenPos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int Token end position (or -1 if not available) + */ + public function getEndTokenPos(): int; + + /** + * Gets the file offset of the first character that is part of this node. + * + * Requires the 'startFilePos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int File start position (or -1 if not available) + */ + public function getStartFilePos(): int; + + /** + * Gets the file offset of the last character that is part of this node. + * + * Requires the 'endFilePos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int File end position (or -1 if not available) + */ + public function getEndFilePos(): int; + + /** + * Gets all comments directly preceding this node. + * + * The comments are also available through the "comments" attribute. + * + * @return Comment[] + */ + public function getComments(): array; + + /** + * Gets the doc comment of the node. + * + * @return null|Comment\Doc Doc comment object or null + */ + public function getDocComment(): ?Comment\Doc; + + /** + * Sets the doc comment of the node. + * + * This will either replace an existing doc comment or add it to the comments array. + * + * @param Comment\Doc $docComment Doc comment to set + */ + public function setDocComment(Comment\Doc $docComment): void; + + /** + * Sets an attribute on a node. + * + * @param mixed $value + */ + public function setAttribute(string $key, $value): void; + + /** + * Returns whether an attribute exists. + */ + public function hasAttribute(string $key): bool; + + /** + * Returns the value of an attribute. + * + * @param mixed $default + * + * @return mixed + */ + public function getAttribute(string $key, $default = null); + + /** + * Returns all the attributes of this node. + * + * @return array<string, mixed> + */ + public function getAttributes(): array; + + /** + * Replaces all the attributes of this node. + * + * @param array<string, mixed> $attributes + */ + public function setAttributes(array $attributes): void; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Arg.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Arg.php new file mode 100644 index 0000000..6680efa --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Arg.php @@ -0,0 +1,44 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class Arg extends NodeAbstract { + /** @var Identifier|null Parameter name (for named parameters) */ + public ?Identifier $name; + /** @var Expr Value to pass */ + public Expr $value; + /** @var bool Whether to pass by ref */ + public bool $byRef; + /** @var bool Whether to unpack the argument */ + public bool $unpack; + + /** + * Constructs a function call argument node. + * + * @param Expr $value Value to pass + * @param bool $byRef Whether to pass by ref + * @param bool $unpack Whether to unpack the argument + * @param array<string, mixed> $attributes Additional attributes + * @param Identifier|null $name Parameter name (for named parameters) + */ + public function __construct( + Expr $value, bool $byRef = false, bool $unpack = false, array $attributes = [], + ?Identifier $name = null + ) { + $this->attributes = $attributes; + $this->name = $name; + $this->value = $value; + $this->byRef = $byRef; + $this->unpack = $unpack; + } + + public function getSubNodeNames(): array { + return ['name', 'value', 'byRef', 'unpack']; + } + + public function getType(): string { + return 'Arg'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ArrayItem.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ArrayItem.php new file mode 100644 index 0000000..fa1cff5 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ArrayItem.php @@ -0,0 +1,43 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class ArrayItem extends NodeAbstract { + /** @var null|Expr Key */ + public ?Expr $key; + /** @var Expr Value */ + public Expr $value; + /** @var bool Whether to assign by reference */ + public bool $byRef; + /** @var bool Whether to unpack the argument */ + public bool $unpack; + + /** + * Constructs an array item node. + * + * @param Expr $value Value + * @param null|Expr $key Key + * @param bool $byRef Whether to assign by reference + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $value, ?Expr $key = null, bool $byRef = false, array $attributes = [], bool $unpack = false) { + $this->attributes = $attributes; + $this->key = $key; + $this->value = $value; + $this->byRef = $byRef; + $this->unpack = $unpack; + } + + public function getSubNodeNames(): array { + return ['key', 'value', 'byRef', 'unpack']; + } + + public function getType(): string { + return 'ArrayItem'; + } +} + +// @deprecated compatibility alias +class_alias(ArrayItem::class, Expr\ArrayItem::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Attribute.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Attribute.php new file mode 100644 index 0000000..9d89243 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Attribute.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; +use PhpParser\NodeAbstract; + +class Attribute extends NodeAbstract { + /** @var Name Attribute name */ + public Name $name; + + /** @var list<Arg> Attribute arguments */ + public array $args; + + /** + * @param Node\Name $name Attribute name + * @param list<Arg> $args Attribute arguments + * @param array<string, mixed> $attributes Additional node attributes + */ + public function __construct(Name $name, array $args = [], array $attributes = []) { + $this->attributes = $attributes; + $this->name = $name; + $this->args = $args; + } + + public function getSubNodeNames(): array { + return ['name', 'args']; + } + + public function getType(): string { + return 'Attribute'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/AttributeGroup.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/AttributeGroup.php new file mode 100644 index 0000000..b9eb588 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/AttributeGroup.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class AttributeGroup extends NodeAbstract { + /** @var Attribute[] Attributes */ + public array $attrs; + + /** + * @param Attribute[] $attrs PHP attributes + * @param array<string, mixed> $attributes Additional node attributes + */ + public function __construct(array $attrs, array $attributes = []) { + $this->attributes = $attributes; + $this->attrs = $attrs; + } + + public function getSubNodeNames(): array { + return ['attrs']; + } + + public function getType(): string { + return 'AttributeGroup'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ClosureUse.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ClosureUse.php new file mode 100644 index 0000000..e313280 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ClosureUse.php @@ -0,0 +1,36 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class ClosureUse extends NodeAbstract { + /** @var Expr\Variable Variable to use */ + public Expr\Variable $var; + /** @var bool Whether to use by reference */ + public bool $byRef; + + /** + * Constructs a closure use node. + * + * @param Expr\Variable $var Variable to use + * @param bool $byRef Whether to use by reference + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr\Variable $var, bool $byRef = false, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->byRef = $byRef; + } + + public function getSubNodeNames(): array { + return ['var', 'byRef']; + } + + public function getType(): string { + return 'ClosureUse'; + } +} + +// @deprecated compatibility alias +class_alias(ClosureUse::class, Expr\ClosureUse::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ComplexType.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ComplexType.php new file mode 100644 index 0000000..05a5e5e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/ComplexType.php @@ -0,0 +1,13 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +/** + * This is a base class for complex types, including nullable types and union types. + * + * It does not provide any shared behavior and exists only for type-checking purposes. + */ +abstract class ComplexType extends NodeAbstract { +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Const_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Const_.php new file mode 100644 index 0000000..8b26ae8 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Const_.php @@ -0,0 +1,36 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class Const_ extends NodeAbstract { + /** @var Identifier Name */ + public Identifier $name; + /** @var Expr Value */ + public Expr $value; + + /** @var Name|null Namespaced name (if using NameResolver) */ + public ?Name $namespacedName; + + /** + * Constructs a const node for use in class const and const statements. + * + * @param string|Identifier $name Name + * @param Expr $value Value + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, Expr $value, array $attributes = []) { + $this->attributes = $attributes; + $this->name = \is_string($name) ? new Identifier($name) : $name; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['name', 'value']; + } + + public function getType(): string { + return 'Const'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/DeclareItem.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/DeclareItem.php new file mode 100644 index 0000000..55c1fe4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/DeclareItem.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; +use PhpParser\NodeAbstract; + +class DeclareItem extends NodeAbstract { + /** @var Node\Identifier Key */ + public Identifier $key; + /** @var Node\Expr Value */ + public Expr $value; + + /** + * Constructs a declare key=>value pair node. + * + * @param string|Node\Identifier $key Key + * @param Node\Expr $value Value + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($key, Node\Expr $value, array $attributes = []) { + $this->attributes = $attributes; + $this->key = \is_string($key) ? new Node\Identifier($key) : $key; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['key', 'value']; + } + + public function getType(): string { + return 'DeclareItem'; + } +} + +// @deprecated compatibility alias +class_alias(DeclareItem::class, Stmt\DeclareDeclare::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr.php new file mode 100644 index 0000000..8b7dbb6 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr.php @@ -0,0 +1,8 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +abstract class Expr extends NodeAbstract { +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayDimFetch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayDimFetch.php new file mode 100644 index 0000000..24427bb --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayDimFetch.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class ArrayDimFetch extends Expr { + /** @var Expr Variable */ + public Expr $var; + /** @var null|Expr Array index / dim */ + public ?Expr $dim; + + /** + * Constructs an array index fetch node. + * + * @param Expr $var Variable + * @param null|Expr $dim Array index / dim + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, ?Expr $dim = null, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->dim = $dim; + } + + public function getSubNodeNames(): array { + return ['var', 'dim']; + } + + public function getType(): string { + return 'Expr_ArrayDimFetch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayItem.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayItem.php new file mode 100644 index 0000000..490ac93 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayItem.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../ArrayItem.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Array_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Array_.php new file mode 100644 index 0000000..3c8c9c2 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Array_.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\ArrayItem; +use PhpParser\Node\Expr; + +class Array_ extends Expr { + // For use in "kind" attribute + public const KIND_LONG = 1; // array() syntax + public const KIND_SHORT = 2; // [] syntax + + /** @var ArrayItem[] Items */ + public array $items; + + /** + * Constructs an array node. + * + * @param ArrayItem[] $items Items of the array + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $items = [], array $attributes = []) { + $this->attributes = $attributes; + $this->items = $items; + } + + public function getSubNodeNames(): array { + return ['items']; + } + + public function getType(): string { + return 'Expr_Array'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrowFunction.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrowFunction.php new file mode 100644 index 0000000..0e98ce9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrowFunction.php @@ -0,0 +1,84 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\FunctionLike; + +class ArrowFunction extends Expr implements FunctionLike { + /** @var bool Whether the closure is static */ + public bool $static; + + /** @var bool Whether to return by reference */ + public bool $byRef; + + /** @var Node\Param[] */ + public array $params = []; + + /** @var null|Node\Identifier|Node\Name|Node\ComplexType */ + public ?Node $returnType; + + /** @var Expr Expression body */ + public Expr $expr; + /** @var Node\AttributeGroup[] */ + public array $attrGroups; + + /** + * @param array{ + * expr: Expr, + * static?: bool, + * byRef?: bool, + * params?: Node\Param[], + * returnType?: null|Node\Identifier|Node\Name|Node\ComplexType, + * attrGroups?: Node\AttributeGroup[] + * } $subNodes Array of the following subnodes: + * 'expr' : Expression body + * 'static' => false : Whether the closure is static + * 'byRef' => false : Whether to return by reference + * 'params' => array() : Parameters + * 'returnType' => null : Return type + * 'attrGroups' => array() : PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $subNodes, array $attributes = []) { + $this->attributes = $attributes; + $this->static = $subNodes['static'] ?? false; + $this->byRef = $subNodes['byRef'] ?? false; + $this->params = $subNodes['params'] ?? []; + $this->returnType = $subNodes['returnType'] ?? null; + $this->expr = $subNodes['expr']; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'static', 'byRef', 'params', 'returnType', 'expr']; + } + + public function returnsByRef(): bool { + return $this->byRef; + } + + public function getParams(): array { + return $this->params; + } + + public function getReturnType() { + return $this->returnType; + } + + public function getAttrGroups(): array { + return $this->attrGroups; + } + + /** + * @return Node\Stmt\Return_[] + */ + public function getStmts(): array { + return [new Node\Stmt\Return_($this->expr)]; + } + + public function getType(): string { + return 'Expr_ArrowFunction'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Assign.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Assign.php new file mode 100644 index 0000000..dcbf84d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Assign.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Assign extends Expr { + /** @var Expr Variable */ + public Expr $var; + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs an assignment node. + * + * @param Expr $var Variable + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['var', 'expr']; + } + + public function getType(): string { + return 'Expr_Assign'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp.php new file mode 100644 index 0000000..5209a64 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +abstract class AssignOp extends Expr { + /** @var Expr Variable */ + public Expr $var; + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a compound assignment operation node. + * + * @param Expr $var Variable + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['var', 'expr']; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseAnd.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseAnd.php new file mode 100644 index 0000000..4f3623f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseAnd.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class BitwiseAnd extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_BitwiseAnd'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseOr.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseOr.php new file mode 100644 index 0000000..23efe10 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseOr.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class BitwiseOr extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_BitwiseOr'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseXor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseXor.php new file mode 100644 index 0000000..24be730 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseXor.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class BitwiseXor extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_BitwiseXor'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Coalesce.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Coalesce.php new file mode 100644 index 0000000..b78ea90 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Coalesce.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Coalesce extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Coalesce'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Concat.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Concat.php new file mode 100644 index 0000000..f419e2e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Concat.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Concat extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Concat'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Div.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Div.php new file mode 100644 index 0000000..98b0472 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Div.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Div extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Div'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Minus.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Minus.php new file mode 100644 index 0000000..2076599 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Minus.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Minus extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Minus'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mod.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mod.php new file mode 100644 index 0000000..526430e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mod.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Mod extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Mod'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mul.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mul.php new file mode 100644 index 0000000..81241ac --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mul.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Mul extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Mul'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Plus.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Plus.php new file mode 100644 index 0000000..0bca8cc --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Plus.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Plus extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Plus'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Pow.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Pow.php new file mode 100644 index 0000000..4e3279c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Pow.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class Pow extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_Pow'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftLeft.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftLeft.php new file mode 100644 index 0000000..7a5dd60 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftLeft.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class ShiftLeft extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_ShiftLeft'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftRight.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftRight.php new file mode 100644 index 0000000..4f27086 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftRight.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\AssignOp; + +use PhpParser\Node\Expr\AssignOp; + +class ShiftRight extends AssignOp { + public function getType(): string { + return 'Expr_AssignOp_ShiftRight'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignRef.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignRef.php new file mode 100644 index 0000000..9714650 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignRef.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class AssignRef extends Expr { + /** @var Expr Variable reference is assigned to */ + public Expr $var; + /** @var Expr Variable which is referenced */ + public Expr $expr; + + /** + * Constructs an assignment node. + * + * @param Expr $var Variable + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['var', 'expr']; + } + + public function getType(): string { + return 'Expr_AssignRef'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp.php new file mode 100644 index 0000000..1b92bd4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +abstract class BinaryOp extends Expr { + /** @var Expr The left hand side expression */ + public Expr $left; + /** @var Expr The right hand side expression */ + public Expr $right; + + /** + * Constructs a binary operator node. + * + * @param Expr $left The left hand side expression + * @param Expr $right The right hand side expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $left, Expr $right, array $attributes = []) { + $this->attributes = $attributes; + $this->left = $left; + $this->right = $right; + } + + public function getSubNodeNames(): array { + return ['left', 'right']; + } + + /** + * Get the operator sigil for this binary operation. + * + * In the case there are multiple possible sigils for an operator, this method does not + * necessarily return the one used in the parsed code. + */ + abstract public function getOperatorSigil(): string; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseAnd.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseAnd.php new file mode 100644 index 0000000..5930c54 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseAnd.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class BitwiseAnd extends BinaryOp { + public function getOperatorSigil(): string { + return '&'; + } + + public function getType(): string { + return 'Expr_BinaryOp_BitwiseAnd'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseOr.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseOr.php new file mode 100644 index 0000000..adcefd0 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseOr.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class BitwiseOr extends BinaryOp { + public function getOperatorSigil(): string { + return '|'; + } + + public function getType(): string { + return 'Expr_BinaryOp_BitwiseOr'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php new file mode 100644 index 0000000..92bca60 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class BitwiseXor extends BinaryOp { + public function getOperatorSigil(): string { + return '^'; + } + + public function getType(): string { + return 'Expr_BinaryOp_BitwiseXor'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php new file mode 100644 index 0000000..82a6b5a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class BooleanAnd extends BinaryOp { + public function getOperatorSigil(): string { + return '&&'; + } + + public function getType(): string { + return 'Expr_BinaryOp_BooleanAnd'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanOr.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanOr.php new file mode 100644 index 0000000..739edaf --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanOr.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class BooleanOr extends BinaryOp { + public function getOperatorSigil(): string { + return '||'; + } + + public function getType(): string { + return 'Expr_BinaryOp_BooleanOr'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php new file mode 100644 index 0000000..ab75a23 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Coalesce extends BinaryOp { + public function getOperatorSigil(): string { + return '??'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Coalesce'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Concat.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Concat.php new file mode 100644 index 0000000..a730f57 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Concat.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Concat extends BinaryOp { + public function getOperatorSigil(): string { + return '.'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Concat'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Div.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Div.php new file mode 100644 index 0000000..ba1f629 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Div.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Div extends BinaryOp { + public function getOperatorSigil(): string { + return '/'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Div'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Equal.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Equal.php new file mode 100644 index 0000000..28bde81 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Equal.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Equal extends BinaryOp { + public function getOperatorSigil(): string { + return '=='; + } + + public function getType(): string { + return 'Expr_BinaryOp_Equal'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Greater.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Greater.php new file mode 100644 index 0000000..6215c50 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Greater.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Greater extends BinaryOp { + public function getOperatorSigil(): string { + return '>'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Greater'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/GreaterOrEqual.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/GreaterOrEqual.php new file mode 100644 index 0000000..4d440b1 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/GreaterOrEqual.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class GreaterOrEqual extends BinaryOp { + public function getOperatorSigil(): string { + return '>='; + } + + public function getType(): string { + return 'Expr_BinaryOp_GreaterOrEqual'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Identical.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Identical.php new file mode 100644 index 0000000..e25d17c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Identical.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Identical extends BinaryOp { + public function getOperatorSigil(): string { + return '==='; + } + + public function getType(): string { + return 'Expr_BinaryOp_Identical'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php new file mode 100644 index 0000000..9b9ea1f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class LogicalAnd extends BinaryOp { + public function getOperatorSigil(): string { + return 'and'; + } + + public function getType(): string { + return 'Expr_BinaryOp_LogicalAnd'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalOr.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalOr.php new file mode 100644 index 0000000..a6235ee --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalOr.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class LogicalOr extends BinaryOp { + public function getOperatorSigil(): string { + return 'or'; + } + + public function getType(): string { + return 'Expr_BinaryOp_LogicalOr'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalXor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalXor.php new file mode 100644 index 0000000..7ff2fdb --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalXor.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class LogicalXor extends BinaryOp { + public function getOperatorSigil(): string { + return 'xor'; + } + + public function getType(): string { + return 'Expr_BinaryOp_LogicalXor'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Minus.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Minus.php new file mode 100644 index 0000000..8924c55 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Minus.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Minus extends BinaryOp { + public function getOperatorSigil(): string { + return '-'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Minus'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mod.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mod.php new file mode 100644 index 0000000..56619de --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mod.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Mod extends BinaryOp { + public function getOperatorSigil(): string { + return '%'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Mod'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mul.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mul.php new file mode 100644 index 0000000..98745fb --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mul.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Mul extends BinaryOp { + public function getOperatorSigil(): string { + return '*'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Mul'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php new file mode 100644 index 0000000..72d03c4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class NotEqual extends BinaryOp { + public function getOperatorSigil(): string { + return '!='; + } + + public function getType(): string { + return 'Expr_BinaryOp_NotEqual'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotIdentical.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotIdentical.php new file mode 100644 index 0000000..e9befd8 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotIdentical.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class NotIdentical extends BinaryOp { + public function getOperatorSigil(): string { + return '!=='; + } + + public function getType(): string { + return 'Expr_BinaryOp_NotIdentical'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Plus.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Plus.php new file mode 100644 index 0000000..fe34b84 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Plus.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Plus extends BinaryOp { + public function getOperatorSigil(): string { + return '+'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Plus'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Pow.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Pow.php new file mode 100644 index 0000000..e4e641c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Pow.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Pow extends BinaryOp { + public function getOperatorSigil(): string { + return '**'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Pow'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php new file mode 100644 index 0000000..22c6260 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class ShiftLeft extends BinaryOp { + public function getOperatorSigil(): string { + return '<<'; + } + + public function getType(): string { + return 'Expr_BinaryOp_ShiftLeft'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftRight.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftRight.php new file mode 100644 index 0000000..cd42644 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftRight.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class ShiftRight extends BinaryOp { + public function getOperatorSigil(): string { + return '>>'; + } + + public function getType(): string { + return 'Expr_BinaryOp_ShiftRight'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Smaller.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Smaller.php new file mode 100644 index 0000000..01e9b23 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Smaller.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Smaller extends BinaryOp { + public function getOperatorSigil(): string { + return '<'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Smaller'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/SmallerOrEqual.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/SmallerOrEqual.php new file mode 100644 index 0000000..2c88f38 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/SmallerOrEqual.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class SmallerOrEqual extends BinaryOp { + public function getOperatorSigil(): string { + return '<='; + } + + public function getType(): string { + return 'Expr_BinaryOp_SmallerOrEqual'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Spaceship.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Spaceship.php new file mode 100644 index 0000000..974ec7d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Spaceship.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\BinaryOp; + +use PhpParser\Node\Expr\BinaryOp; + +class Spaceship extends BinaryOp { + public function getOperatorSigil(): string { + return '<=>'; + } + + public function getType(): string { + return 'Expr_BinaryOp_Spaceship'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BitwiseNot.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BitwiseNot.php new file mode 100644 index 0000000..b7175a7 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BitwiseNot.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class BitwiseNot extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a bitwise not node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_BitwiseNot'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BooleanNot.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BooleanNot.php new file mode 100644 index 0000000..c66d233 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BooleanNot.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class BooleanNot extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a boolean not node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_BooleanNot'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/CallLike.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/CallLike.php new file mode 100644 index 0000000..2af2245 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/CallLike.php @@ -0,0 +1,35 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\VariadicPlaceholder; + +abstract class CallLike extends Expr { + /** + * Return raw arguments, which may be actual Args, or VariadicPlaceholders for first-class + * callables. + * + * @return array<Arg|VariadicPlaceholder> + */ + abstract public function getRawArgs(): array; + + /** + * Returns whether this call expression is actually a first class callable. + */ + public function isFirstClassCallable(): bool { + $rawArgs = $this->getRawArgs(); + return count($rawArgs) === 1 && current($rawArgs) instanceof VariadicPlaceholder; + } + + /** + * Assert that this is not a first-class callable and return only ordinary Args. + * + * @return Arg[] + */ + public function getArgs(): array { + assert(!$this->isFirstClassCallable()); + return $this->getRawArgs(); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast.php new file mode 100644 index 0000000..c2751de --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast.php @@ -0,0 +1,25 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +abstract class Cast extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a cast node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Array_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Array_.php new file mode 100644 index 0000000..471cb82 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Array_.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class Array_ extends Cast { + public function getType(): string { + return 'Expr_Cast_Array'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Bool_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Bool_.php new file mode 100644 index 0000000..3aed497 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Bool_.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class Bool_ extends Cast { + public function getType(): string { + return 'Expr_Cast_Bool'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Double.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Double.php new file mode 100644 index 0000000..e7f5cd9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Double.php @@ -0,0 +1,16 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class Double extends Cast { + // For use in "kind" attribute + public const KIND_DOUBLE = 1; // "double" syntax + public const KIND_FLOAT = 2; // "float" syntax + public const KIND_REAL = 3; // "real" syntax + + public function getType(): string { + return 'Expr_Cast_Double'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Int_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Int_.php new file mode 100644 index 0000000..20744b9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Int_.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class Int_ extends Cast { + public function getType(): string { + return 'Expr_Cast_Int'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Object_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Object_.php new file mode 100644 index 0000000..dffa9e5 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Object_.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class Object_ extends Cast { + public function getType(): string { + return 'Expr_Cast_Object'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/String_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/String_.php new file mode 100644 index 0000000..c7605ab --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/String_.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class String_ extends Cast { + public function getType(): string { + return 'Expr_Cast_String'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Unset_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Unset_.php new file mode 100644 index 0000000..cb709a4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Unset_.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr\Cast; + +use PhpParser\Node\Expr\Cast; + +class Unset_ extends Cast { + public function getType(): string { + return 'Expr_Cast_Unset'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClassConstFetch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClassConstFetch.php new file mode 100644 index 0000000..7fdd40e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClassConstFetch.php @@ -0,0 +1,36 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; + +class ClassConstFetch extends Expr { + /** @var Name|Expr Class name */ + public Node $class; + /** @var Identifier|Expr|Error Constant name */ + public Node $name; + + /** + * Constructs a class const fetch node. + * + * @param Name|Expr $class Class name + * @param string|Identifier|Expr|Error $name Constant name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node $class, $name, array $attributes = []) { + $this->attributes = $attributes; + $this->class = $class; + $this->name = \is_string($name) ? new Identifier($name) : $name; + } + + public function getSubNodeNames(): array { + return ['class', 'name']; + } + + public function getType(): string { + return 'Expr_ClassConstFetch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Clone_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Clone_.php new file mode 100644 index 0000000..d85bc9a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Clone_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Clone_ extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a clone node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_Clone'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Closure.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Closure.php new file mode 100644 index 0000000..0680446 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Closure.php @@ -0,0 +1,86 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\ClosureUse; +use PhpParser\Node\Expr; +use PhpParser\Node\FunctionLike; + +class Closure extends Expr implements FunctionLike { + /** @var bool Whether the closure is static */ + public bool $static; + /** @var bool Whether to return by reference */ + public bool $byRef; + /** @var Node\Param[] Parameters */ + public array $params; + /** @var ClosureUse[] use()s */ + public array $uses; + /** @var null|Node\Identifier|Node\Name|Node\ComplexType Return type */ + public ?Node $returnType; + /** @var Node\Stmt[] Statements */ + public array $stmts; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** + * Constructs a lambda function node. + * + * @param array{ + * static?: bool, + * byRef?: bool, + * params?: Node\Param[], + * uses?: ClosureUse[], + * returnType?: null|Node\Identifier|Node\Name|Node\ComplexType, + * stmts?: Node\Stmt[], + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'static' => false : Whether the closure is static + * 'byRef' => false : Whether to return by reference + * 'params' => array(): Parameters + * 'uses' => array(): use()s + * 'returnType' => null : Return type + * 'stmts' => array(): Statements + * 'attrGroups' => array(): PHP attributes groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->static = $subNodes['static'] ?? false; + $this->byRef = $subNodes['byRef'] ?? false; + $this->params = $subNodes['params'] ?? []; + $this->uses = $subNodes['uses'] ?? []; + $this->returnType = $subNodes['returnType'] ?? null; + $this->stmts = $subNodes['stmts'] ?? []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'static', 'byRef', 'params', 'uses', 'returnType', 'stmts']; + } + + public function returnsByRef(): bool { + return $this->byRef; + } + + public function getParams(): array { + return $this->params; + } + + public function getReturnType() { + return $this->returnType; + } + + /** @return Node\Stmt[] */ + public function getStmts(): array { + return $this->stmts; + } + + public function getAttrGroups(): array { + return $this->attrGroups; + } + + public function getType(): string { + return 'Expr_Closure'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClosureUse.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClosureUse.php new file mode 100644 index 0000000..681ff31 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClosureUse.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../ClosureUse.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ConstFetch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ConstFetch.php new file mode 100644 index 0000000..47191c5 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ConstFetch.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; +use PhpParser\Node\Name; + +class ConstFetch extends Expr { + /** @var Name Constant name */ + public Name $name; + + /** + * Constructs a const fetch node. + * + * @param Name $name Constant name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Name $name, array $attributes = []) { + $this->attributes = $attributes; + $this->name = $name; + } + + public function getSubNodeNames(): array { + return ['name']; + } + + public function getType(): string { + return 'Expr_ConstFetch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Empty_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Empty_.php new file mode 100644 index 0000000..d2f3050 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Empty_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Empty_ extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs an empty() node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_Empty'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Error.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Error.php new file mode 100644 index 0000000..43010ac --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Error.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +/** + * Error node used during parsing with error recovery. + * + * An error node may be placed at a position where an expression is required, but an error occurred. + * Error nodes will not be present if the parser is run in throwOnError mode (the default). + */ +class Error extends Expr { + /** + * Constructs an error node. + * + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $attributes = []) { + $this->attributes = $attributes; + } + + public function getSubNodeNames(): array { + return []; + } + + public function getType(): string { + return 'Expr_Error'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ErrorSuppress.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ErrorSuppress.php new file mode 100644 index 0000000..32625a2 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ErrorSuppress.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class ErrorSuppress extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs an error suppress node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_ErrorSuppress'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Eval_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Eval_.php new file mode 100644 index 0000000..5120b1b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Eval_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Eval_ extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs an eval() node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_Eval'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Exit_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Exit_.php new file mode 100644 index 0000000..cf00246 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Exit_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Exit_ extends Expr { + /* For use in "kind" attribute */ + public const KIND_EXIT = 1; + public const KIND_DIE = 2; + + /** @var null|Expr Expression */ + public ?Expr $expr; + + /** + * Constructs an exit() node. + * + * @param null|Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Expr $expr = null, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_Exit'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/FuncCall.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/FuncCall.php new file mode 100644 index 0000000..0b85840 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/FuncCall.php @@ -0,0 +1,38 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; + +class FuncCall extends CallLike { + /** @var Node\Name|Expr Function name */ + public Node $name; + /** @var array<Node\Arg|Node\VariadicPlaceholder> Arguments */ + public array $args; + + /** + * Constructs a function call node. + * + * @param Node\Name|Expr $name Function name + * @param array<Node\Arg|Node\VariadicPlaceholder> $args Arguments + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node $name, array $args = [], array $attributes = []) { + $this->attributes = $attributes; + $this->name = $name; + $this->args = $args; + } + + public function getSubNodeNames(): array { + return ['name', 'args']; + } + + public function getType(): string { + return 'Expr_FuncCall'; + } + + public function getRawArgs(): array { + return $this->args; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Include_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Include_.php new file mode 100644 index 0000000..e1187b1 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Include_.php @@ -0,0 +1,38 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Include_ extends Expr { + public const TYPE_INCLUDE = 1; + public const TYPE_INCLUDE_ONCE = 2; + public const TYPE_REQUIRE = 3; + public const TYPE_REQUIRE_ONCE = 4; + + /** @var Expr Expression */ + public Expr $expr; + /** @var int Type of include */ + public int $type; + + /** + * Constructs an include node. + * + * @param Expr $expr Expression + * @param int $type Type of include + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, int $type, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + $this->type = $type; + } + + public function getSubNodeNames(): array { + return ['expr', 'type']; + } + + public function getType(): string { + return 'Expr_Include'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Instanceof_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Instanceof_.php new file mode 100644 index 0000000..a2783cb --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Instanceof_.php @@ -0,0 +1,35 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Name; + +class Instanceof_ extends Expr { + /** @var Expr Expression */ + public Expr $expr; + /** @var Name|Expr Class name */ + public Node $class; + + /** + * Constructs an instanceof check node. + * + * @param Expr $expr Expression + * @param Name|Expr $class Class name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, Node $class, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + $this->class = $class; + } + + public function getSubNodeNames(): array { + return ['expr', 'class']; + } + + public function getType(): string { + return 'Expr_Instanceof'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Isset_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Isset_.php new file mode 100644 index 0000000..4f80fff --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Isset_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Isset_ extends Expr { + /** @var Expr[] Variables */ + public array $vars; + + /** + * Constructs an array node. + * + * @param Expr[] $vars Variables + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $vars, array $attributes = []) { + $this->attributes = $attributes; + $this->vars = $vars; + } + + public function getSubNodeNames(): array { + return ['vars']; + } + + public function getType(): string { + return 'Expr_Isset'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/List_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/List_.php new file mode 100644 index 0000000..496b7b3 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/List_.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\ArrayItem; +use PhpParser\Node\Expr; + +class List_ extends Expr { + // For use in "kind" attribute + public const KIND_LIST = 1; // list() syntax + public const KIND_ARRAY = 2; // [] syntax + + /** @var (ArrayItem|null)[] List of items to assign to */ + public array $items; + + /** + * Constructs a list() destructuring node. + * + * @param (ArrayItem|null)[] $items List of items to assign to + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $items, array $attributes = []) { + $this->attributes = $attributes; + $this->items = $items; + } + + public function getSubNodeNames(): array { + return ['items']; + } + + public function getType(): string { + return 'Expr_List'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Match_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Match_.php new file mode 100644 index 0000000..cd028a2 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Match_.php @@ -0,0 +1,32 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\MatchArm; + +class Match_ extends Node\Expr { + /** @var Node\Expr Condition */ + public Node\Expr $cond; + /** @var MatchArm[] */ + public array $arms; + + /** + * @param Node\Expr $cond Condition + * @param MatchArm[] $arms + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $cond, array $arms = [], array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->arms = $arms; + } + + public function getSubNodeNames(): array { + return ['cond', 'arms']; + } + + public function getType(): string { + return 'Expr_Match'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/MethodCall.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/MethodCall.php new file mode 100644 index 0000000..2703c75 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/MethodCall.php @@ -0,0 +1,45 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; +use PhpParser\Node\VariadicPlaceholder; + +class MethodCall extends CallLike { + /** @var Expr Variable holding object */ + public Expr $var; + /** @var Identifier|Expr Method name */ + public Node $name; + /** @var array<Arg|VariadicPlaceholder> Arguments */ + public array $args; + + /** + * Constructs a function call node. + * + * @param Expr $var Variable holding object + * @param string|Identifier|Expr $name Method name + * @param array<Arg|VariadicPlaceholder> $args Arguments + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, $name, array $args = [], array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->name = \is_string($name) ? new Identifier($name) : $name; + $this->args = $args; + } + + public function getSubNodeNames(): array { + return ['var', 'name', 'args']; + } + + public function getType(): string { + return 'Expr_MethodCall'; + } + + public function getRawArgs(): array { + return $this->args; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/New_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/New_.php new file mode 100644 index 0000000..eedaaa1 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/New_.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\VariadicPlaceholder; + +class New_ extends CallLike { + /** @var Node\Name|Expr|Node\Stmt\Class_ Class name */ + public Node $class; + /** @var array<Arg|VariadicPlaceholder> Arguments */ + public array $args; + + /** + * Constructs a function call node. + * + * @param Node\Name|Expr|Node\Stmt\Class_ $class Class name (or class node for anonymous classes) + * @param array<Arg|VariadicPlaceholder> $args Arguments + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node $class, array $args = [], array $attributes = []) { + $this->attributes = $attributes; + $this->class = $class; + $this->args = $args; + } + + public function getSubNodeNames(): array { + return ['class', 'args']; + } + + public function getType(): string { + return 'Expr_New'; + } + + public function getRawArgs(): array { + return $this->args; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafeMethodCall.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafeMethodCall.php new file mode 100644 index 0000000..a151f71 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafeMethodCall.php @@ -0,0 +1,45 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; +use PhpParser\Node\VariadicPlaceholder; + +class NullsafeMethodCall extends CallLike { + /** @var Expr Variable holding object */ + public Expr $var; + /** @var Identifier|Expr Method name */ + public Node $name; + /** @var array<Arg|VariadicPlaceholder> Arguments */ + public array $args; + + /** + * Constructs a nullsafe method call node. + * + * @param Expr $var Variable holding object + * @param string|Identifier|Expr $name Method name + * @param array<Arg|VariadicPlaceholder> $args Arguments + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, $name, array $args = [], array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->name = \is_string($name) ? new Identifier($name) : $name; + $this->args = $args; + } + + public function getSubNodeNames(): array { + return ['var', 'name', 'args']; + } + + public function getType(): string { + return 'Expr_NullsafeMethodCall'; + } + + public function getRawArgs(): array { + return $this->args; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafePropertyFetch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafePropertyFetch.php new file mode 100644 index 0000000..6f73a16 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafePropertyFetch.php @@ -0,0 +1,35 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; + +class NullsafePropertyFetch extends Expr { + /** @var Expr Variable holding object */ + public Expr $var; + /** @var Identifier|Expr Property name */ + public Node $name; + + /** + * Constructs a nullsafe property fetch node. + * + * @param Expr $var Variable holding object + * @param string|Identifier|Expr $name Property name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, $name, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->name = \is_string($name) ? new Identifier($name) : $name; + } + + public function getSubNodeNames(): array { + return ['var', 'name']; + } + + public function getType(): string { + return 'Expr_NullsafePropertyFetch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostDec.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostDec.php new file mode 100644 index 0000000..3dca8fd --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostDec.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class PostDec extends Expr { + /** @var Expr Variable */ + public Expr $var; + + /** + * Constructs a post decrement node. + * + * @param Expr $var Variable + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + } + + public function getSubNodeNames(): array { + return ['var']; + } + + public function getType(): string { + return 'Expr_PostDec'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostInc.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostInc.php new file mode 100644 index 0000000..bc990c3 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostInc.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class PostInc extends Expr { + /** @var Expr Variable */ + public Expr $var; + + /** + * Constructs a post increment node. + * + * @param Expr $var Variable + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + } + + public function getSubNodeNames(): array { + return ['var']; + } + + public function getType(): string { + return 'Expr_PostInc'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreDec.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreDec.php new file mode 100644 index 0000000..2f16873 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreDec.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class PreDec extends Expr { + /** @var Expr Variable */ + public Expr $var; + + /** + * Constructs a pre decrement node. + * + * @param Expr $var Variable + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + } + + public function getSubNodeNames(): array { + return ['var']; + } + + public function getType(): string { + return 'Expr_PreDec'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreInc.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreInc.php new file mode 100644 index 0000000..fd455f5 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreInc.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class PreInc extends Expr { + /** @var Expr Variable */ + public Expr $var; + + /** + * Constructs a pre increment node. + * + * @param Expr $var Variable + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + } + + public function getSubNodeNames(): array { + return ['var']; + } + + public function getType(): string { + return 'Expr_PreInc'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Print_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Print_.php new file mode 100644 index 0000000..6057476 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Print_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Print_ extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs an print() node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_Print'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PropertyFetch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PropertyFetch.php new file mode 100644 index 0000000..8c416a8 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PropertyFetch.php @@ -0,0 +1,35 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; + +class PropertyFetch extends Expr { + /** @var Expr Variable holding object */ + public Expr $var; + /** @var Identifier|Expr Property name */ + public Node $name; + + /** + * Constructs a function call node. + * + * @param Expr $var Variable holding object + * @param string|Identifier|Expr $name Property name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $var, $name, array $attributes = []) { + $this->attributes = $attributes; + $this->var = $var; + $this->name = \is_string($name) ? new Identifier($name) : $name; + } + + public function getSubNodeNames(): array { + return ['var', 'name']; + } + + public function getType(): string { + return 'Expr_PropertyFetch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ShellExec.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ShellExec.php new file mode 100644 index 0000000..e400351 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ShellExec.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; +use PhpParser\Node\InterpolatedStringPart; + +class ShellExec extends Expr { + /** @var (Expr|InterpolatedStringPart)[] Interpolated string array */ + public array $parts; + + /** + * Constructs a shell exec (backtick) node. + * + * @param (Expr|InterpolatedStringPart)[] $parts Interpolated string array + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $parts, array $attributes = []) { + $this->attributes = $attributes; + $this->parts = $parts; + } + + public function getSubNodeNames(): array { + return ['parts']; + } + + public function getType(): string { + return 'Expr_ShellExec'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticCall.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticCall.php new file mode 100644 index 0000000..707f34b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticCall.php @@ -0,0 +1,45 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; +use PhpParser\Node\VariadicPlaceholder; + +class StaticCall extends CallLike { + /** @var Node\Name|Expr Class name */ + public Node $class; + /** @var Identifier|Expr Method name */ + public Node $name; + /** @var array<Arg|VariadicPlaceholder> Arguments */ + public array $args; + + /** + * Constructs a static method call node. + * + * @param Node\Name|Expr $class Class name + * @param string|Identifier|Expr $name Method name + * @param array<Arg|VariadicPlaceholder> $args Arguments + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node $class, $name, array $args = [], array $attributes = []) { + $this->attributes = $attributes; + $this->class = $class; + $this->name = \is_string($name) ? new Identifier($name) : $name; + $this->args = $args; + } + + public function getSubNodeNames(): array { + return ['class', 'name', 'args']; + } + + public function getType(): string { + return 'Expr_StaticCall'; + } + + public function getRawArgs(): array { + return $this->args; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticPropertyFetch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticPropertyFetch.php new file mode 100644 index 0000000..4836a65 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticPropertyFetch.php @@ -0,0 +1,36 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Name; +use PhpParser\Node\VarLikeIdentifier; + +class StaticPropertyFetch extends Expr { + /** @var Name|Expr Class name */ + public Node $class; + /** @var VarLikeIdentifier|Expr Property name */ + public Node $name; + + /** + * Constructs a static property fetch node. + * + * @param Name|Expr $class Class name + * @param string|VarLikeIdentifier|Expr $name Property name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node $class, $name, array $attributes = []) { + $this->attributes = $attributes; + $this->class = $class; + $this->name = \is_string($name) ? new VarLikeIdentifier($name) : $name; + } + + public function getSubNodeNames(): array { + return ['class', 'name']; + } + + public function getType(): string { + return 'Expr_StaticPropertyFetch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Ternary.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Ternary.php new file mode 100644 index 0000000..d4837e6 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Ternary.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Ternary extends Expr { + /** @var Expr Condition */ + public Expr $cond; + /** @var null|Expr Expression for true */ + public ?Expr $if; + /** @var Expr Expression for false */ + public Expr $else; + + /** + * Constructs a ternary operator node. + * + * @param Expr $cond Condition + * @param null|Expr $if Expression for true + * @param Expr $else Expression for false + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $cond, ?Expr $if, Expr $else, array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->if = $if; + $this->else = $else; + } + + public function getSubNodeNames(): array { + return ['cond', 'if', 'else']; + } + + public function getType(): string { + return 'Expr_Ternary'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Throw_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Throw_.php new file mode 100644 index 0000000..ee49f83 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Throw_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node; + +class Throw_ extends Node\Expr { + /** @var Node\Expr Expression */ + public Node\Expr $expr; + + /** + * Constructs a throw expression node. + * + * @param Node\Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_Throw'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryMinus.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryMinus.php new file mode 100644 index 0000000..cd06f74 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryMinus.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class UnaryMinus extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a unary minus node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_UnaryMinus'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryPlus.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryPlus.php new file mode 100644 index 0000000..1b44f7b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryPlus.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class UnaryPlus extends Expr { + /** @var Expr Expression */ + public Expr $expr; + + /** + * Constructs a unary plus node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_UnaryPlus'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Variable.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Variable.php new file mode 100644 index 0000000..bab7492 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Variable.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Variable extends Expr { + /** @var string|Expr Name */ + public $name; + + /** + * Constructs a variable node. + * + * @param string|Expr $name Name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $attributes = []) { + $this->attributes = $attributes; + $this->name = $name; + } + + public function getSubNodeNames(): array { + return ['name']; + } + + public function getType(): string { + return 'Expr_Variable'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/YieldFrom.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/YieldFrom.php new file mode 100644 index 0000000..5cff88f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/YieldFrom.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class YieldFrom extends Expr { + /** @var Expr Expression to yield from */ + public Expr $expr; + + /** + * Constructs an "yield from" node. + * + * @param Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Expr_YieldFrom'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Yield_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Yield_.php new file mode 100644 index 0000000..bd81e69 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Yield_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Expr; + +use PhpParser\Node\Expr; + +class Yield_ extends Expr { + /** @var null|Expr Key expression */ + public ?Expr $key; + /** @var null|Expr Value expression */ + public ?Expr $value; + + /** + * Constructs a yield expression node. + * + * @param null|Expr $value Value expression + * @param null|Expr $key Key expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Expr $value = null, ?Expr $key = null, array $attributes = []) { + $this->attributes = $attributes; + $this->key = $key; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['key', 'value']; + } + + public function getType(): string { + return 'Expr_Yield'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php new file mode 100644 index 0000000..58f653a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; + +interface FunctionLike extends Node { + /** + * Whether to return by reference + */ + public function returnsByRef(): bool; + + /** + * List of parameters + * + * @return Param[] + */ + public function getParams(): array; + + /** + * Get the declared return type or null + * + * @return null|Identifier|Name|ComplexType + */ + public function getReturnType(); + + /** + * The function body + * + * @return Stmt[]|null + */ + public function getStmts(): ?array; + + /** + * Get PHP attribute groups. + * + * @return AttributeGroup[] + */ + public function getAttrGroups(): array; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Identifier.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Identifier.php new file mode 100644 index 0000000..266166c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Identifier.php @@ -0,0 +1,75 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +/** + * Represents a non-namespaced name. Namespaced names are represented using Name nodes. + */ +class Identifier extends NodeAbstract { + /** @var string Identifier as string */ + public string $name; + + /** @var array<string, bool> */ + private static array $specialClassNames = [ + 'self' => true, + 'parent' => true, + 'static' => true, + ]; + + /** + * Constructs an identifier node. + * + * @param string $name Identifier as string + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(string $name, array $attributes = []) { + $this->attributes = $attributes; + $this->name = $name; + } + + public function getSubNodeNames(): array { + return ['name']; + } + + /** + * Get identifier as string. + * + * @return string Identifier as string. + */ + public function toString(): string { + return $this->name; + } + + /** + * Get lowercased identifier as string. + * + * @return string Lowercased identifier as string + */ + public function toLowerString(): string { + return strtolower($this->name); + } + + /** + * Checks whether the identifier is a special class name (self, parent or static). + * + * @return bool Whether identifier is a special class name + */ + public function isSpecialClassName(): bool { + return isset(self::$specialClassNames[strtolower($this->name)]); + } + + /** + * Get identifier as string. + * + * @return string Identifier as string + */ + public function __toString(): string { + return $this->name; + } + + public function getType(): string { + return 'Identifier'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/InterpolatedStringPart.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/InterpolatedStringPart.php new file mode 100644 index 0000000..576dac4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/InterpolatedStringPart.php @@ -0,0 +1,32 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class InterpolatedStringPart extends NodeAbstract { + /** @var string String value */ + public string $value; + + /** + * Constructs a node representing a string part of an interpolated string. + * + * @param string $value String value + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(string $value, array $attributes = []) { + $this->attributes = $attributes; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['value']; + } + + public function getType(): string { + return 'InterpolatedStringPart'; + } +} + +// @deprecated compatibility alias +class_alias(InterpolatedStringPart::class, Scalar\EncapsedStringPart::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/IntersectionType.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/IntersectionType.php new file mode 100644 index 0000000..3b39cf1 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/IntersectionType.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +class IntersectionType extends ComplexType { + /** @var (Identifier|Name)[] Types */ + public array $types; + + /** + * Constructs an intersection type. + * + * @param (Identifier|Name)[] $types Types + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $types, array $attributes = []) { + $this->attributes = $attributes; + $this->types = $types; + } + + public function getSubNodeNames(): array { + return ['types']; + } + + public function getType(): string { + return 'IntersectionType'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/MatchArm.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/MatchArm.php new file mode 100644 index 0000000..2927f02 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/MatchArm.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; +use PhpParser\NodeAbstract; + +class MatchArm extends NodeAbstract { + /** @var null|list<Node\Expr> */ + public ?array $conds; + /** @var Node\Expr */ + public Expr $body; + + /** + * @param null|list<Node\Expr> $conds + */ + public function __construct(?array $conds, Node\Expr $body, array $attributes = []) { + $this->conds = $conds; + $this->body = $body; + $this->attributes = $attributes; + } + + public function getSubNodeNames(): array { + return ['conds', 'body']; + } + + public function getType(): string { + return 'MatchArm'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name.php new file mode 100644 index 0000000..26b863e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name.php @@ -0,0 +1,269 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +class Name extends NodeAbstract { + /** @var string Name as string */ + public string $name; + + /** @var array<string, bool> */ + private static array $specialClassNames = [ + 'self' => true, + 'parent' => true, + 'static' => true, + ]; + + /** + * Constructs a name node. + * + * @param string|string[]|self $name Name as string, part array or Name instance (copy ctor) + * @param array<string, mixed> $attributes Additional attributes + */ + final public function __construct($name, array $attributes = []) { + $this->attributes = $attributes; + $this->name = self::prepareName($name); + } + + public function getSubNodeNames(): array { + return ['name']; + } + + /** + * Get parts of name (split by the namespace separator). + * + * @return string[] Parts of name + */ + public function getParts(): array { + return \explode('\\', $this->name); + } + + /** + * Gets the first part of the name, i.e. everything before the first namespace separator. + * + * @return string First part of the name + */ + public function getFirst(): string { + if (false !== $pos = \strpos($this->name, '\\')) { + return \substr($this->name, 0, $pos); + } + return $this->name; + } + + /** + * Gets the last part of the name, i.e. everything after the last namespace separator. + * + * @return string Last part of the name + */ + public function getLast(): string { + if (false !== $pos = \strrpos($this->name, '\\')) { + return \substr($this->name, $pos + 1); + } + return $this->name; + } + + /** + * Checks whether the name is unqualified. (E.g. Name) + * + * @return bool Whether the name is unqualified + */ + public function isUnqualified(): bool { + return false === \strpos($this->name, '\\'); + } + + /** + * Checks whether the name is qualified. (E.g. Name\Name) + * + * @return bool Whether the name is qualified + */ + public function isQualified(): bool { + return false !== \strpos($this->name, '\\'); + } + + /** + * Checks whether the name is fully qualified. (E.g. \Name) + * + * @return bool Whether the name is fully qualified + */ + public function isFullyQualified(): bool { + return false; + } + + /** + * Checks whether the name is explicitly relative to the current namespace. (E.g. namespace\Name) + * + * @return bool Whether the name is relative + */ + public function isRelative(): bool { + return false; + } + + /** + * Returns a string representation of the name itself, without taking the name type into + * account (e.g., not including a leading backslash for fully qualified names). + * + * @return string String representation + */ + public function toString(): string { + return $this->name; + } + + /** + * Returns a string representation of the name as it would occur in code (e.g., including + * leading backslash for fully qualified names. + * + * @return string String representation + */ + public function toCodeString(): string { + return $this->toString(); + } + + /** + * Returns lowercased string representation of the name, without taking the name type into + * account (e.g., no leading backslash for fully qualified names). + * + * @return string Lowercased string representation + */ + public function toLowerString(): string { + return strtolower($this->name); + } + + /** + * Checks whether the identifier is a special class name (self, parent or static). + * + * @return bool Whether identifier is a special class name + */ + public function isSpecialClassName(): bool { + return isset(self::$specialClassNames[strtolower($this->name)]); + } + + /** + * Returns a string representation of the name by imploding the namespace parts with the + * namespace separator. + * + * @return string String representation + */ + public function __toString(): string { + return $this->name; + } + + /** + * Gets a slice of a name (similar to array_slice). + * + * This method returns a new instance of the same type as the original and with the same + * attributes. + * + * If the slice is empty, null is returned. The null value will be correctly handled in + * concatenations using concat(). + * + * Offset and length have the same meaning as in array_slice(). + * + * @param int $offset Offset to start the slice at (may be negative) + * @param int|null $length Length of the slice (may be negative) + * + * @return static|null Sliced name + */ + public function slice(int $offset, ?int $length = null) { + if ($offset === 1 && $length === null) { + // Short-circuit the common case. + if (false !== $pos = \strpos($this->name, '\\')) { + return new static(\substr($this->name, $pos + 1)); + } + return null; + } + + $parts = \explode('\\', $this->name); + $numParts = \count($parts); + + $realOffset = $offset < 0 ? $offset + $numParts : $offset; + if ($realOffset < 0 || $realOffset > $numParts) { + throw new \OutOfBoundsException(sprintf('Offset %d is out of bounds', $offset)); + } + + if (null === $length) { + $realLength = $numParts - $realOffset; + } else { + $realLength = $length < 0 ? $length + $numParts - $realOffset : $length; + if ($realLength < 0 || $realLength > $numParts - $realOffset) { + throw new \OutOfBoundsException(sprintf('Length %d is out of bounds', $length)); + } + } + + if ($realLength === 0) { + // Empty slice is represented as null + return null; + } + + return new static(array_slice($parts, $realOffset, $realLength), $this->attributes); + } + + /** + * Concatenate two names, yielding a new Name instance. + * + * The type of the generated instance depends on which class this method is called on, for + * example Name\FullyQualified::concat() will yield a Name\FullyQualified instance. + * + * If one of the arguments is null, a new instance of the other name will be returned. If both + * arguments are null, null will be returned. As such, writing + * Name::concat($namespace, $shortName) + * where $namespace is a Name node or null will work as expected. + * + * @param string|string[]|self|null $name1 The first name + * @param string|string[]|self|null $name2 The second name + * @param array<string, mixed> $attributes Attributes to assign to concatenated name + * + * @return static|null Concatenated name + */ + public static function concat($name1, $name2, array $attributes = []) { + if (null === $name1 && null === $name2) { + return null; + } + if (null === $name1) { + return new static($name2, $attributes); + } + if (null === $name2) { + return new static($name1, $attributes); + } else { + return new static( + self::prepareName($name1) . '\\' . self::prepareName($name2), $attributes + ); + } + } + + /** + * Prepares a (string, array or Name node) name for use in name changing methods by converting + * it to a string. + * + * @param string|string[]|self $name Name to prepare + * + * @return string Prepared name + */ + private static function prepareName($name): string { + if (\is_string($name)) { + if ('' === $name) { + throw new \InvalidArgumentException('Name cannot be empty'); + } + + return $name; + } + if (\is_array($name)) { + if (empty($name)) { + throw new \InvalidArgumentException('Name cannot be empty'); + } + + return implode('\\', $name); + } + if ($name instanceof self) { + return $name->name; + } + + throw new \InvalidArgumentException( + 'Expected string, array of parts or Name instance' + ); + } + + public function getType(): string { + return 'Name'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name/FullyQualified.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name/FullyQualified.php new file mode 100644 index 0000000..2118378 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name/FullyQualified.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Name; + +class FullyQualified extends \PhpParser\Node\Name { + /** + * Checks whether the name is unqualified. (E.g. Name) + * + * @return bool Whether the name is unqualified + */ + public function isUnqualified(): bool { + return false; + } + + /** + * Checks whether the name is qualified. (E.g. Name\Name) + * + * @return bool Whether the name is qualified + */ + public function isQualified(): bool { + return false; + } + + /** + * Checks whether the name is fully qualified. (E.g. \Name) + * + * @return bool Whether the name is fully qualified + */ + public function isFullyQualified(): bool { + return true; + } + + /** + * Checks whether the name is explicitly relative to the current namespace. (E.g. namespace\Name) + * + * @return bool Whether the name is relative + */ + public function isRelative(): bool { + return false; + } + + public function toCodeString(): string { + return '\\' . $this->toString(); + } + + public function getType(): string { + return 'Name_FullyQualified'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name/Relative.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name/Relative.php new file mode 100644 index 0000000..0226a4e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Name/Relative.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Name; + +class Relative extends \PhpParser\Node\Name { + /** + * Checks whether the name is unqualified. (E.g. Name) + * + * @return bool Whether the name is unqualified + */ + public function isUnqualified(): bool { + return false; + } + + /** + * Checks whether the name is qualified. (E.g. Name\Name) + * + * @return bool Whether the name is qualified + */ + public function isQualified(): bool { + return false; + } + + /** + * Checks whether the name is fully qualified. (E.g. \Name) + * + * @return bool Whether the name is fully qualified + */ + public function isFullyQualified(): bool { + return false; + } + + /** + * Checks whether the name is explicitly relative to the current namespace. (E.g. namespace\Name) + * + * @return bool Whether the name is relative + */ + public function isRelative(): bool { + return true; + } + + public function toCodeString(): string { + return 'namespace\\' . $this->toString(); + } + + public function getType(): string { + return 'Name_Relative'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/NullableType.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/NullableType.php new file mode 100644 index 0000000..b99acd1 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/NullableType.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; + +class NullableType extends ComplexType { + /** @var Identifier|Name Type */ + public Node $type; + + /** + * Constructs a nullable type (wrapping another type). + * + * @param Identifier|Name $type Type + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node $type, array $attributes = []) { + $this->attributes = $attributes; + $this->type = $type; + } + + public function getSubNodeNames(): array { + return ['type']; + } + + public function getType(): string { + return 'NullableType'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Param.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Param.php new file mode 100644 index 0000000..0e9ff0e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Param.php @@ -0,0 +1,84 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\NodeAbstract; + +class Param extends NodeAbstract { + /** @var null|Identifier|Name|ComplexType Type declaration */ + public ?Node $type; + /** @var bool Whether parameter is passed by reference */ + public bool $byRef; + /** @var bool Whether this is a variadic argument */ + public bool $variadic; + /** @var Expr\Variable|Expr\Error Parameter variable */ + public Expr $var; + /** @var null|Expr Default value */ + public ?Expr $default; + /** @var int Optional visibility flags */ + public int $flags; + /** @var AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** + * Constructs a parameter node. + * + * @param Expr\Variable|Expr\Error $var Parameter variable + * @param null|Expr $default Default value + * @param null|Identifier|Name|ComplexType $type Type declaration + * @param bool $byRef Whether is passed by reference + * @param bool $variadic Whether this is a variadic argument + * @param array<string, mixed> $attributes Additional attributes + * @param int $flags Optional visibility flags + * @param list<AttributeGroup> $attrGroups PHP attribute groups + */ + public function __construct( + Expr $var, ?Expr $default = null, ?Node $type = null, + bool $byRef = false, bool $variadic = false, + array $attributes = [], + int $flags = 0, + array $attrGroups = [] + ) { + $this->attributes = $attributes; + $this->type = $type; + $this->byRef = $byRef; + $this->variadic = $variadic; + $this->var = $var; + $this->default = $default; + $this->flags = $flags; + $this->attrGroups = $attrGroups; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'flags', 'type', 'byRef', 'variadic', 'var', 'default']; + } + + public function getType(): string { + return 'Param'; + } + + /** + * Whether this parameter uses constructor property promotion. + */ + public function isPromoted(): bool { + return $this->flags !== 0; + } + + public function isPublic(): bool { + return (bool) ($this->flags & Modifiers::PUBLIC); + } + + public function isProtected(): bool { + return (bool) ($this->flags & Modifiers::PROTECTED); + } + + public function isPrivate(): bool { + return (bool) ($this->flags & Modifiers::PRIVATE); + } + + public function isReadonly(): bool { + return (bool) ($this->flags & Modifiers::READONLY); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/PropertyItem.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/PropertyItem.php new file mode 100644 index 0000000..101611e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/PropertyItem.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; +use PhpParser\NodeAbstract; + +class PropertyItem extends NodeAbstract { + /** @var Node\VarLikeIdentifier Name */ + public VarLikeIdentifier $name; + /** @var null|Node\Expr Default */ + public ?Expr $default; + + /** + * Constructs a class property item node. + * + * @param string|Node\VarLikeIdentifier $name Name + * @param null|Node\Expr $default Default value + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, ?Node\Expr $default = null, array $attributes = []) { + $this->attributes = $attributes; + $this->name = \is_string($name) ? new Node\VarLikeIdentifier($name) : $name; + $this->default = $default; + } + + public function getSubNodeNames(): array { + return ['name', 'default']; + } + + public function getType(): string { + return 'PropertyItem'; + } +} + +// @deprecated compatibility alias +class_alias(PropertyItem::class, Stmt\PropertyProperty::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar.php new file mode 100644 index 0000000..3df2572 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar.php @@ -0,0 +1,6 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +abstract class Scalar extends Expr { +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/DNumber.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/DNumber.php new file mode 100644 index 0000000..ad3937a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/DNumber.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/Float_.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Encapsed.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Encapsed.php new file mode 100644 index 0000000..c5aaf5b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Encapsed.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/InterpolatedString.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/EncapsedStringPart.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/EncapsedStringPart.php new file mode 100644 index 0000000..990e980 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/EncapsedStringPart.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../InterpolatedStringPart.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Float_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Float_.php new file mode 100644 index 0000000..5af1319 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Float_.php @@ -0,0 +1,78 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar; + +use PhpParser\Node\Scalar; + +class Float_ extends Scalar { + /** @var float Number value */ + public float $value; + + /** + * Constructs a float number scalar node. + * + * @param float $value Value of the number + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(float $value, array $attributes = []) { + $this->attributes = $attributes; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['value']; + } + + /** + * @param mixed[] $attributes + */ + public static function fromString(string $str, array $attributes = []): Float_ { + $attributes['rawValue'] = $str; + $float = self::parse($str); + + return new Float_($float, $attributes); + } + + /** + * @internal + * + * Parses a DNUMBER token like PHP would. + * + * @param string $str A string number + * + * @return float The parsed number + */ + public static function parse(string $str): float { + $str = str_replace('_', '', $str); + + // Check whether this is one of the special integer notations. + if ('0' === $str[0]) { + // hex + if ('x' === $str[1] || 'X' === $str[1]) { + return hexdec($str); + } + + // bin + if ('b' === $str[1] || 'B' === $str[1]) { + return bindec($str); + } + + // oct, but only if the string does not contain any of '.eE'. + if (false === strpbrk($str, '.eE')) { + // substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit + // (8 or 9) so that only the digits before that are used. + return octdec(substr($str, 0, strcspn($str, '89'))); + } + } + + // dec + return (float) $str; + } + + public function getType(): string { + return 'Scalar_Float'; + } +} + +// @deprecated compatibility alias +class_alias(Float_::class, DNumber::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Int_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Int_.php new file mode 100644 index 0000000..bcc257a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Int_.php @@ -0,0 +1,82 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar; + +use PhpParser\Error; +use PhpParser\Node\Scalar; + +class Int_ extends Scalar { + /* For use in "kind" attribute */ + public const KIND_BIN = 2; + public const KIND_OCT = 8; + public const KIND_DEC = 10; + public const KIND_HEX = 16; + + /** @var int Number value */ + public int $value; + + /** + * Constructs an integer number scalar node. + * + * @param int $value Value of the number + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(int $value, array $attributes = []) { + $this->attributes = $attributes; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['value']; + } + + /** + * Constructs an Int node from a string number literal. + * + * @param string $str String number literal (decimal, octal, hex or binary) + * @param array<string, mixed> $attributes Additional attributes + * @param bool $allowInvalidOctal Whether to allow invalid octal numbers (PHP 5) + * + * @return Int_ The constructed LNumber, including kind attribute + */ + public static function fromString(string $str, array $attributes = [], bool $allowInvalidOctal = false): Int_ { + $attributes['rawValue'] = $str; + + $str = str_replace('_', '', $str); + + if ('0' !== $str[0] || '0' === $str) { + $attributes['kind'] = Int_::KIND_DEC; + return new Int_((int) $str, $attributes); + } + + if ('x' === $str[1] || 'X' === $str[1]) { + $attributes['kind'] = Int_::KIND_HEX; + return new Int_(hexdec($str), $attributes); + } + + if ('b' === $str[1] || 'B' === $str[1]) { + $attributes['kind'] = Int_::KIND_BIN; + return new Int_(bindec($str), $attributes); + } + + if (!$allowInvalidOctal && strpbrk($str, '89')) { + throw new Error('Invalid numeric literal', $attributes); + } + + // Strip optional explicit octal prefix. + if ('o' === $str[1] || 'O' === $str[1]) { + $str = substr($str, 2); + } + + // use intval instead of octdec to get proper cutting behavior with malformed numbers + $attributes['kind'] = Int_::KIND_OCT; + return new Int_(intval($str, 8), $attributes); + } + + public function getType(): string { + return 'Scalar_Int'; + } +} + +// @deprecated compatibility alias +class_alias(Int_::class, LNumber::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/InterpolatedString.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/InterpolatedString.php new file mode 100644 index 0000000..9336dfe --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/InterpolatedString.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar; + +use PhpParser\Node\Expr; +use PhpParser\Node\InterpolatedStringPart; +use PhpParser\Node\Scalar; + +class InterpolatedString extends Scalar { + /** @var (Expr|InterpolatedStringPart)[] list of string parts */ + public array $parts; + + /** + * Constructs an interpolated string node. + * + * @param (Expr|InterpolatedStringPart)[] $parts Interpolated string parts + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $parts, array $attributes = []) { + $this->attributes = $attributes; + $this->parts = $parts; + } + + public function getSubNodeNames(): array { + return ['parts']; + } + + public function getType(): string { + return 'Scalar_InterpolatedString'; + } +} + +// @deprecated compatibility alias +class_alias(InterpolatedString::class, Encapsed::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/LNumber.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/LNumber.php new file mode 100644 index 0000000..cfe8c8c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/LNumber.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/Int_.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst.php new file mode 100644 index 0000000..1da9b39 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar; + +use PhpParser\Node\Scalar; + +abstract class MagicConst extends Scalar { + /** + * Constructs a magic constant node. + * + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $attributes = []) { + $this->attributes = $attributes; + } + + public function getSubNodeNames(): array { + return []; + } + + /** + * Get name of magic constant. + * + * @return string Name of magic constant + */ + abstract public function getName(): string; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Class_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Class_.php new file mode 100644 index 0000000..732ed14 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Class_.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Class_ extends MagicConst { + public function getName(): string { + return '__CLASS__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Class'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Dir.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Dir.php new file mode 100644 index 0000000..64daa71 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Dir.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Dir extends MagicConst { + public function getName(): string { + return '__DIR__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Dir'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/File.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/File.php new file mode 100644 index 0000000..91041f0 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/File.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class File extends MagicConst { + public function getName(): string { + return '__FILE__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_File'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Function_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Function_.php new file mode 100644 index 0000000..c242d2d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Function_.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Function_ extends MagicConst { + public function getName(): string { + return '__FUNCTION__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Function'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Line.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Line.php new file mode 100644 index 0000000..58d8ce3 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Line.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Line extends MagicConst { + public function getName(): string { + return '__LINE__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Line'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Method.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Method.php new file mode 100644 index 0000000..47f341f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Method.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Method extends MagicConst { + public function getName(): string { + return '__METHOD__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Method'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php new file mode 100644 index 0000000..e9f8c0e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Namespace_ extends MagicConst { + public function getName(): string { + return '__NAMESPACE__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Namespace'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Trait_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Trait_.php new file mode 100644 index 0000000..25f4973 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Trait_.php @@ -0,0 +1,15 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar\MagicConst; + +use PhpParser\Node\Scalar\MagicConst; + +class Trait_ extends MagicConst { + public function getName(): string { + return '__TRAIT__'; + } + + public function getType(): string { + return 'Scalar_MagicConst_Trait'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/String_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/String_.php new file mode 100644 index 0000000..c965366 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/String_.php @@ -0,0 +1,161 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Scalar; + +use PhpParser\Error; +use PhpParser\Node\Scalar; + +class String_ extends Scalar { + /* For use in "kind" attribute */ + public const KIND_SINGLE_QUOTED = 1; + public const KIND_DOUBLE_QUOTED = 2; + public const KIND_HEREDOC = 3; + public const KIND_NOWDOC = 4; + + /** @var string String value */ + public string $value; + + /** @var array<string, string> Escaped character to its decoded value */ + protected static array $replacements = [ + '\\' => '\\', + '$' => '$', + 'n' => "\n", + 'r' => "\r", + 't' => "\t", + 'f' => "\f", + 'v' => "\v", + 'e' => "\x1B", + ]; + + /** + * Constructs a string scalar node. + * + * @param string $value Value of the string + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(string $value, array $attributes = []) { + $this->attributes = $attributes; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['value']; + } + + /** + * @param array<string, mixed> $attributes + * @param bool $parseUnicodeEscape Whether to parse PHP 7 \u escapes + */ + public static function fromString(string $str, array $attributes = [], bool $parseUnicodeEscape = true): self { + $attributes['kind'] = ($str[0] === "'" || ($str[1] === "'" && ($str[0] === 'b' || $str[0] === 'B'))) + ? Scalar\String_::KIND_SINGLE_QUOTED + : Scalar\String_::KIND_DOUBLE_QUOTED; + + $attributes['rawValue'] = $str; + + $string = self::parse($str, $parseUnicodeEscape); + + return new self($string, $attributes); + } + + /** + * @internal + * + * Parses a string token. + * + * @param string $str String token content + * @param bool $parseUnicodeEscape Whether to parse PHP 7 \u escapes + * + * @return string The parsed string + */ + public static function parse(string $str, bool $parseUnicodeEscape = true): string { + $bLength = 0; + if ('b' === $str[0] || 'B' === $str[0]) { + $bLength = 1; + } + + if ('\'' === $str[$bLength]) { + return str_replace( + ['\\\\', '\\\''], + ['\\', '\''], + substr($str, $bLength + 1, -1) + ); + } else { + return self::parseEscapeSequences( + substr($str, $bLength + 1, -1), '"', $parseUnicodeEscape + ); + } + } + + /** + * @internal + * + * Parses escape sequences in strings (all string types apart from single quoted). + * + * @param string $str String without quotes + * @param null|string $quote Quote type + * @param bool $parseUnicodeEscape Whether to parse PHP 7 \u escapes + * + * @return string String with escape sequences parsed + */ + public static function parseEscapeSequences(string $str, ?string $quote, bool $parseUnicodeEscape = true): string { + if (null !== $quote) { + $str = str_replace('\\' . $quote, $quote, $str); + } + + $extra = ''; + if ($parseUnicodeEscape) { + $extra = '|u\{([0-9a-fA-F]+)\}'; + } + + return preg_replace_callback( + '~\\\\([\\\\$nrtfve]|[xX][0-9a-fA-F]{1,2}|[0-7]{1,3}' . $extra . ')~', + function ($matches) { + $str = $matches[1]; + + if (isset(self::$replacements[$str])) { + return self::$replacements[$str]; + } + if ('x' === $str[0] || 'X' === $str[0]) { + return chr(hexdec(substr($str, 1))); + } + if ('u' === $str[0]) { + $dec = hexdec($matches[2]); + // If it overflowed to float, treat as INT_MAX, it will throw an error anyway. + return self::codePointToUtf8(\is_int($dec) ? $dec : \PHP_INT_MAX); + } else { + return chr(octdec($str)); + } + }, + $str + ); + } + + /** + * Converts a Unicode code point to its UTF-8 encoded representation. + * + * @param int $num Code point + * + * @return string UTF-8 representation of code point + */ + private static function codePointToUtf8(int $num): string { + if ($num <= 0x7F) { + return chr($num); + } + if ($num <= 0x7FF) { + return chr(($num >> 6) + 0xC0) . chr(($num & 0x3F) + 0x80); + } + if ($num <= 0xFFFF) { + return chr(($num >> 12) + 0xE0) . chr((($num >> 6) & 0x3F) + 0x80) . chr(($num & 0x3F) + 0x80); + } + if ($num <= 0x1FFFFF) { + return chr(($num >> 18) + 0xF0) . chr((($num >> 12) & 0x3F) + 0x80) + . chr((($num >> 6) & 0x3F) + 0x80) . chr(($num & 0x3F) + 0x80); + } + throw new Error('Invalid UTF-8 codepoint escape sequence: Codepoint too large'); + } + + public function getType(): string { + return 'Scalar_String'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/StaticVar.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/StaticVar.php new file mode 100644 index 0000000..517c0ed --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/StaticVar.php @@ -0,0 +1,39 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; +use PhpParser\NodeAbstract; + +class StaticVar extends NodeAbstract { + /** @var Expr\Variable Variable */ + public Expr\Variable $var; + /** @var null|Node\Expr Default value */ + public ?Expr $default; + + /** + * Constructs a static variable node. + * + * @param Expr\Variable $var Name + * @param null|Node\Expr $default Default value + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct( + Expr\Variable $var, ?Node\Expr $default = null, array $attributes = [] + ) { + $this->attributes = $attributes; + $this->var = $var; + $this->default = $default; + } + + public function getSubNodeNames(): array { + return ['var', 'default']; + } + + public function getType(): string { + return 'StaticVar'; + } +} + +// @deprecated compatibility alias +class_alias(StaticVar::class, Stmt\StaticVar::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt.php new file mode 100644 index 0000000..481d31a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt.php @@ -0,0 +1,8 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +abstract class Stmt extends NodeAbstract { +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Block.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Block.php new file mode 100644 index 0000000..073df20 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Block.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Stmt; + +class Block extends Stmt { + /** @var Stmt[] Statements */ + public array $stmts; + + /** + * A block of statements. + * + * @param Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $stmts, array $attributes = []) { + $this->attributes = $attributes; + $this->stmts = $stmts; + } + + public function getType(): string { + return 'Stmt_Block'; + } + + public function getSubNodeNames(): array { + return ['stmts']; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Break_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Break_.php new file mode 100644 index 0000000..d2bcc5e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Break_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Break_ extends Node\Stmt { + /** @var null|Node\Expr Number of loops to break */ + public ?Node\Expr $num; + + /** + * Constructs a break node. + * + * @param null|Node\Expr $num Number of loops to break + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Node\Expr $num = null, array $attributes = []) { + $this->attributes = $attributes; + $this->num = $num; + } + + public function getSubNodeNames(): array { + return ['num']; + } + + public function getType(): string { + return 'Stmt_Break'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Case_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Case_.php new file mode 100644 index 0000000..a06ca18 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Case_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Case_ extends Node\Stmt { + /** @var null|Node\Expr Condition (null for default) */ + public ?Node\Expr $cond; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs a case node. + * + * @param null|Node\Expr $cond Condition (null for default) + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Node\Expr $cond, array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['cond', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Case'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Catch_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Catch_.php new file mode 100644 index 0000000..e8d39c9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Catch_.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; +use PhpParser\Node\Expr; + +class Catch_ extends Node\Stmt { + /** @var Node\Name[] Types of exceptions to catch */ + public array $types; + /** @var Expr\Variable|null Variable for exception */ + public ?Expr\Variable $var; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs a catch node. + * + * @param Node\Name[] $types Types of exceptions to catch + * @param Expr\Variable|null $var Variable for exception + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct( + array $types, ?Expr\Variable $var = null, array $stmts = [], array $attributes = [] + ) { + $this->attributes = $attributes; + $this->types = $types; + $this->var = $var; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['types', 'var', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Catch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassConst.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassConst.php new file mode 100644 index 0000000..9bdce1f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassConst.php @@ -0,0 +1,77 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Modifiers; +use PhpParser\Node; + +class ClassConst extends Node\Stmt { + /** @var int Modifiers */ + public int $flags; + /** @var Node\Const_[] Constant declarations */ + public array $consts; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + /** @var Node\Identifier|Node\Name|Node\ComplexType|null Type declaration */ + public ?Node $type; + + /** + * Constructs a class const list node. + * + * @param Node\Const_[] $consts Constant declarations + * @param int $flags Modifiers + * @param array<string, mixed> $attributes Additional attributes + * @param list<Node\AttributeGroup> $attrGroups PHP attribute groups + * @param null|Node\Identifier|Node\Name|Node\ComplexType $type Type declaration + */ + public function __construct( + array $consts, + int $flags = 0, + array $attributes = [], + array $attrGroups = [], + ?Node $type = null + ) { + $this->attributes = $attributes; + $this->flags = $flags; + $this->consts = $consts; + $this->attrGroups = $attrGroups; + $this->type = $type; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'flags', 'type', 'consts']; + } + + /** + * Whether constant is explicitly or implicitly public. + */ + public function isPublic(): bool { + return ($this->flags & Modifiers::PUBLIC) !== 0 + || ($this->flags & Modifiers::VISIBILITY_MASK) === 0; + } + + /** + * Whether constant is protected. + */ + public function isProtected(): bool { + return (bool) ($this->flags & Modifiers::PROTECTED); + } + + /** + * Whether constant is private. + */ + public function isPrivate(): bool { + return (bool) ($this->flags & Modifiers::PRIVATE); + } + + /** + * Whether constant is final. + */ + public function isFinal(): bool { + return (bool) ($this->flags & Modifiers::FINAL); + } + + public function getType(): string { + return 'Stmt_ClassConst'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassLike.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassLike.php new file mode 100644 index 0000000..fb9ba4f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassLike.php @@ -0,0 +1,109 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; +use PhpParser\Node\PropertyItem; + +abstract class ClassLike extends Node\Stmt { + /** @var Node\Identifier|null Name */ + public ?Node\Identifier $name; + /** @var Node\Stmt[] Statements */ + public array $stmts; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** @var Node\Name|null Namespaced name (if using NameResolver) */ + public ?Node\Name $namespacedName; + + /** + * @return TraitUse[] + */ + public function getTraitUses(): array { + $traitUses = []; + foreach ($this->stmts as $stmt) { + if ($stmt instanceof TraitUse) { + $traitUses[] = $stmt; + } + } + return $traitUses; + } + + /** + * @return ClassConst[] + */ + public function getConstants(): array { + $constants = []; + foreach ($this->stmts as $stmt) { + if ($stmt instanceof ClassConst) { + $constants[] = $stmt; + } + } + return $constants; + } + + /** + * @return Property[] + */ + public function getProperties(): array { + $properties = []; + foreach ($this->stmts as $stmt) { + if ($stmt instanceof Property) { + $properties[] = $stmt; + } + } + return $properties; + } + + /** + * Gets property with the given name defined directly in this class/interface/trait. + * + * @param string $name Name of the property + * + * @return Property|null Property node or null if the property does not exist + */ + public function getProperty(string $name): ?Property { + foreach ($this->stmts as $stmt) { + if ($stmt instanceof Property) { + foreach ($stmt->props as $prop) { + if ($prop instanceof PropertyItem && $name === $prop->name->toString()) { + return $stmt; + } + } + } + } + return null; + } + + /** + * Gets all methods defined directly in this class/interface/trait + * + * @return ClassMethod[] + */ + public function getMethods(): array { + $methods = []; + foreach ($this->stmts as $stmt) { + if ($stmt instanceof ClassMethod) { + $methods[] = $stmt; + } + } + return $methods; + } + + /** + * Gets method with the given name defined directly in this class/interface/trait. + * + * @param string $name Name of the method (compared case-insensitively) + * + * @return ClassMethod|null Method node or null if the method does not exist + */ + public function getMethod(string $name): ?ClassMethod { + $lowerName = strtolower($name); + foreach ($this->stmts as $stmt) { + if ($stmt instanceof ClassMethod && $lowerName === $stmt->name->toLowerString()) { + return $stmt; + } + } + return null; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassMethod.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassMethod.php new file mode 100644 index 0000000..59c0519 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassMethod.php @@ -0,0 +1,154 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\FunctionLike; + +class ClassMethod extends Node\Stmt implements FunctionLike { + /** @var int Flags */ + public int $flags; + /** @var bool Whether to return by reference */ + public bool $byRef; + /** @var Node\Identifier Name */ + public Node\Identifier $name; + /** @var Node\Param[] Parameters */ + public array $params; + /** @var null|Node\Identifier|Node\Name|Node\ComplexType Return type */ + public ?Node $returnType; + /** @var Node\Stmt[]|null Statements */ + public ?array $stmts; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** @var array<string, bool> */ + private static array $magicNames = [ + '__construct' => true, + '__destruct' => true, + '__call' => true, + '__callstatic' => true, + '__get' => true, + '__set' => true, + '__isset' => true, + '__unset' => true, + '__sleep' => true, + '__wakeup' => true, + '__tostring' => true, + '__set_state' => true, + '__clone' => true, + '__invoke' => true, + '__debuginfo' => true, + '__serialize' => true, + '__unserialize' => true, + ]; + + /** + * Constructs a class method node. + * + * @param string|Node\Identifier $name Name + * @param array{ + * flags?: int, + * byRef?: bool, + * params?: Node\Param[], + * returnType?: null|Node\Identifier|Node\Name|Node\ComplexType, + * stmts?: Node\Stmt[]|null, + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'flags => 0 : Flags + * 'byRef' => false : Whether to return by reference + * 'params' => array() : Parameters + * 'returnType' => null : Return type + * 'stmts' => array() : Statements + * 'attrGroups' => array() : PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->flags = $subNodes['flags'] ?? $subNodes['type'] ?? 0; + $this->byRef = $subNodes['byRef'] ?? false; + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->params = $subNodes['params'] ?? []; + $this->returnType = $subNodes['returnType'] ?? null; + $this->stmts = array_key_exists('stmts', $subNodes) ? $subNodes['stmts'] : []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'flags', 'byRef', 'name', 'params', 'returnType', 'stmts']; + } + + public function returnsByRef(): bool { + return $this->byRef; + } + + public function getParams(): array { + return $this->params; + } + + public function getReturnType() { + return $this->returnType; + } + + public function getStmts(): ?array { + return $this->stmts; + } + + public function getAttrGroups(): array { + return $this->attrGroups; + } + + /** + * Whether the method is explicitly or implicitly public. + */ + public function isPublic(): bool { + return ($this->flags & Modifiers::PUBLIC) !== 0 + || ($this->flags & Modifiers::VISIBILITY_MASK) === 0; + } + + /** + * Whether the method is protected. + */ + public function isProtected(): bool { + return (bool) ($this->flags & Modifiers::PROTECTED); + } + + /** + * Whether the method is private. + */ + public function isPrivate(): bool { + return (bool) ($this->flags & Modifiers::PRIVATE); + } + + /** + * Whether the method is abstract. + */ + public function isAbstract(): bool { + return (bool) ($this->flags & Modifiers::ABSTRACT); + } + + /** + * Whether the method is final. + */ + public function isFinal(): bool { + return (bool) ($this->flags & Modifiers::FINAL); + } + + /** + * Whether the method is static. + */ + public function isStatic(): bool { + return (bool) ($this->flags & Modifiers::STATIC); + } + + /** + * Whether the method is magic. + */ + public function isMagic(): bool { + return isset(self::$magicNames[$this->name->toLowerString()]); + } + + public function getType(): string { + return 'Stmt_ClassMethod'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Class_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Class_.php new file mode 100644 index 0000000..3f492b7 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Class_.php @@ -0,0 +1,94 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Modifiers; +use PhpParser\Node; + +class Class_ extends ClassLike { + /** @deprecated Use Modifiers::PUBLIC instead */ + public const MODIFIER_PUBLIC = 1; + /** @deprecated Use Modifiers::PROTECTED instead */ + public const MODIFIER_PROTECTED = 2; + /** @deprecated Use Modifiers::PRIVATE instead */ + public const MODIFIER_PRIVATE = 4; + /** @deprecated Use Modifiers::STATIC instead */ + public const MODIFIER_STATIC = 8; + /** @deprecated Use Modifiers::ABSTRACT instead */ + public const MODIFIER_ABSTRACT = 16; + /** @deprecated Use Modifiers::FINAL instead */ + public const MODIFIER_FINAL = 32; + /** @deprecated Use Modifiers::READONLY instead */ + public const MODIFIER_READONLY = 64; + + /** @deprecated Use Modifiers::VISIBILITY_MASK instead */ + public const VISIBILITY_MODIFIER_MASK = 7; // 1 | 2 | 4 + + /** @var int Modifiers */ + public int $flags; + /** @var null|Node\Name Name of extended class */ + public ?Node\Name $extends; + /** @var Node\Name[] Names of implemented interfaces */ + public array $implements; + + /** + * Constructs a class node. + * + * @param string|Node\Identifier|null $name Name + * @param array{ + * flags?: int, + * extends?: Node\Name|null, + * implements?: Node\Name[], + * stmts?: Node\Stmt[], + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'flags' => 0 : Flags + * 'extends' => null : Name of extended class + * 'implements' => array(): Names of implemented interfaces + * 'stmts' => array(): Statements + * 'attrGroups' => array(): PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->flags = $subNodes['flags'] ?? $subNodes['type'] ?? 0; + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->extends = $subNodes['extends'] ?? null; + $this->implements = $subNodes['implements'] ?? []; + $this->stmts = $subNodes['stmts'] ?? []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'flags', 'name', 'extends', 'implements', 'stmts']; + } + + /** + * Whether the class is explicitly abstract. + */ + public function isAbstract(): bool { + return (bool) ($this->flags & Modifiers::ABSTRACT); + } + + /** + * Whether the class is final. + */ + public function isFinal(): bool { + return (bool) ($this->flags & Modifiers::FINAL); + } + + public function isReadonly(): bool { + return (bool) ($this->flags & Modifiers::READONLY); + } + + /** + * Whether the class is anonymous. + */ + public function isAnonymous(): bool { + return null === $this->name; + } + + public function getType(): string { + return 'Stmt_Class'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Const_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Const_.php new file mode 100644 index 0000000..f1165fd --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Const_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Const_ extends Node\Stmt { + /** @var Node\Const_[] Constant declarations */ + public array $consts; + + /** + * Constructs a const list node. + * + * @param Node\Const_[] $consts Constant declarations + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $consts, array $attributes = []) { + $this->attributes = $attributes; + $this->consts = $consts; + } + + public function getSubNodeNames(): array { + return ['consts']; + } + + public function getType(): string { + return 'Stmt_Const'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Continue_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Continue_.php new file mode 100644 index 0000000..54e979d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Continue_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Continue_ extends Node\Stmt { + /** @var null|Node\Expr Number of loops to continue */ + public ?Node\Expr $num; + + /** + * Constructs a continue node. + * + * @param null|Node\Expr $num Number of loops to continue + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Node\Expr $num = null, array $attributes = []) { + $this->attributes = $attributes; + $this->num = $num; + } + + public function getSubNodeNames(): array { + return ['num']; + } + + public function getType(): string { + return 'Stmt_Continue'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/DeclareDeclare.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/DeclareDeclare.php new file mode 100644 index 0000000..cb9e837 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/DeclareDeclare.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../DeclareItem.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Declare_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Declare_.php new file mode 100644 index 0000000..3c0547b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Declare_.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; +use PhpParser\Node\DeclareItem; + +class Declare_ extends Node\Stmt { + /** @var DeclareItem[] List of declares */ + public array $declares; + /** @var Node\Stmt[]|null Statements */ + public ?array $stmts; + + /** + * Constructs a declare node. + * + * @param DeclareItem[] $declares List of declares + * @param Node\Stmt[]|null $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $declares, ?array $stmts = null, array $attributes = []) { + $this->attributes = $attributes; + $this->declares = $declares; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['declares', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Declare'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Do_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Do_.php new file mode 100644 index 0000000..6124442 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Do_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Do_ extends Node\Stmt { + /** @var Node\Stmt[] Statements */ + public array $stmts; + /** @var Node\Expr Condition */ + public Node\Expr $cond; + + /** + * Constructs a do while node. + * + * @param Node\Expr $cond Condition + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $cond, array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['stmts', 'cond']; + } + + public function getType(): string { + return 'Stmt_Do'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Echo_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Echo_.php new file mode 100644 index 0000000..4d42452 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Echo_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Echo_ extends Node\Stmt { + /** @var Node\Expr[] Expressions */ + public array $exprs; + + /** + * Constructs an echo node. + * + * @param Node\Expr[] $exprs Expressions + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $exprs, array $attributes = []) { + $this->attributes = $attributes; + $this->exprs = $exprs; + } + + public function getSubNodeNames(): array { + return ['exprs']; + } + + public function getType(): string { + return 'Stmt_Echo'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ElseIf_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ElseIf_.php new file mode 100644 index 0000000..b26d59c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ElseIf_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class ElseIf_ extends Node\Stmt { + /** @var Node\Expr Condition */ + public Node\Expr $cond; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs an elseif node. + * + * @param Node\Expr $cond Condition + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $cond, array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['cond', 'stmts']; + } + + public function getType(): string { + return 'Stmt_ElseIf'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Else_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Else_.php new file mode 100644 index 0000000..3d2b066 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Else_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Else_ extends Node\Stmt { + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs an else node. + * + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['stmts']; + } + + public function getType(): string { + return 'Stmt_Else'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/EnumCase.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/EnumCase.php new file mode 100644 index 0000000..c071a0a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/EnumCase.php @@ -0,0 +1,36 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; +use PhpParser\Node\AttributeGroup; + +class EnumCase extends Node\Stmt { + /** @var Node\Identifier Enum case name */ + public Node\Identifier $name; + /** @var Node\Expr|null Enum case expression */ + public ?Node\Expr $expr; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** + * @param string|Node\Identifier $name Enum case name + * @param Node\Expr|null $expr Enum case expression + * @param list<AttributeGroup> $attrGroups PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, ?Node\Expr $expr = null, array $attrGroups = [], array $attributes = []) { + parent::__construct($attributes); + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->expr = $expr; + $this->attrGroups = $attrGroups; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'name', 'expr']; + } + + public function getType(): string { + return 'Stmt_EnumCase'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Enum_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Enum_.php new file mode 100644 index 0000000..7eea6a6 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Enum_.php @@ -0,0 +1,44 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Enum_ extends ClassLike { + /** @var null|Node\Identifier Scalar Type */ + public ?Node $scalarType; + /** @var Node\Name[] Names of implemented interfaces */ + public array $implements; + + /** + * @param string|Node\Identifier|null $name Name + * @param array{ + * scalarType?: Node\Identifier|null, + * implements?: Node\Name[], + * stmts?: Node\Stmt[], + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'scalarType' => null : Scalar type + * 'implements' => array() : Names of implemented interfaces + * 'stmts' => array() : Statements + * 'attrGroups' => array() : PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $subNodes = [], array $attributes = []) { + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->scalarType = $subNodes['scalarType'] ?? null; + $this->implements = $subNodes['implements'] ?? []; + $this->stmts = $subNodes['stmts'] ?? []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + + parent::__construct($attributes); + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'name', 'scalarType', 'implements', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Enum'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Expression.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Expression.php new file mode 100644 index 0000000..89751fa --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Expression.php @@ -0,0 +1,32 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +/** + * Represents statements of type "expr;" + */ +class Expression extends Node\Stmt { + /** @var Node\Expr Expression */ + public Node\Expr $expr; + + /** + * Constructs an expression statement. + * + * @param Node\Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $expr, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Stmt_Expression'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Finally_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Finally_.php new file mode 100644 index 0000000..69ecf25 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Finally_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Finally_ extends Node\Stmt { + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs a finally node. + * + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['stmts']; + } + + public function getType(): string { + return 'Stmt_Finally'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/For_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/For_.php new file mode 100644 index 0000000..6f2fbb9 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/For_.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class For_ extends Node\Stmt { + /** @var Node\Expr[] Init expressions */ + public array $init; + /** @var Node\Expr[] Loop conditions */ + public array $cond; + /** @var Node\Expr[] Loop expressions */ + public array $loop; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs a for loop node. + * + * @param array{ + * init?: Node\Expr[], + * cond?: Node\Expr[], + * loop?: Node\Expr[], + * stmts?: Node\Stmt[], + * } $subNodes Array of the following optional subnodes: + * 'init' => array(): Init expressions + * 'cond' => array(): Loop conditions + * 'loop' => array(): Loop expressions + * 'stmts' => array(): Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->init = $subNodes['init'] ?? []; + $this->cond = $subNodes['cond'] ?? []; + $this->loop = $subNodes['loop'] ?? []; + $this->stmts = $subNodes['stmts'] ?? []; + } + + public function getSubNodeNames(): array { + return ['init', 'cond', 'loop', 'stmts']; + } + + public function getType(): string { + return 'Stmt_For'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Foreach_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Foreach_.php new file mode 100644 index 0000000..c5d9a8b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Foreach_.php @@ -0,0 +1,50 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Foreach_ extends Node\Stmt { + /** @var Node\Expr Expression to iterate */ + public Node\Expr $expr; + /** @var null|Node\Expr Variable to assign key to */ + public ?Node\Expr $keyVar; + /** @var bool Whether to assign value by reference */ + public bool $byRef; + /** @var Node\Expr Variable to assign value to */ + public Node\Expr $valueVar; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs a foreach node. + * + * @param Node\Expr $expr Expression to iterate + * @param Node\Expr $valueVar Variable to assign value to + * @param array{ + * keyVar?: Node\Expr|null, + * byRef?: bool, + * stmts?: Node\Stmt[], + * } $subNodes Array of the following optional subnodes: + * 'keyVar' => null : Variable to assign key to + * 'byRef' => false : Whether to assign value by reference + * 'stmts' => array(): Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $expr, Node\Expr $valueVar, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + $this->keyVar = $subNodes['keyVar'] ?? null; + $this->byRef = $subNodes['byRef'] ?? false; + $this->valueVar = $valueVar; + $this->stmts = $subNodes['stmts'] ?? []; + } + + public function getSubNodeNames(): array { + return ['expr', 'keyVar', 'byRef', 'valueVar', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Foreach'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Function_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Function_.php new file mode 100644 index 0000000..2111bab --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Function_.php @@ -0,0 +1,81 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; +use PhpParser\Node\FunctionLike; + +class Function_ extends Node\Stmt implements FunctionLike { + /** @var bool Whether function returns by reference */ + public bool $byRef; + /** @var Node\Identifier Name */ + public Node\Identifier $name; + /** @var Node\Param[] Parameters */ + public array $params; + /** @var null|Node\Identifier|Node\Name|Node\ComplexType Return type */ + public ?Node $returnType; + /** @var Node\Stmt[] Statements */ + public array $stmts; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** @var Node\Name|null Namespaced name (if using NameResolver) */ + public ?Node\Name $namespacedName; + + /** + * Constructs a function node. + * + * @param string|Node\Identifier $name Name + * @param array{ + * byRef?: bool, + * params?: Node\Param[], + * returnType?: null|Node\Identifier|Node\Name|Node\ComplexType, + * stmts?: Node\Stmt[], + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'byRef' => false : Whether to return by reference + * 'params' => array(): Parameters + * 'returnType' => null : Return type + * 'stmts' => array(): Statements + * 'attrGroups' => array(): PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->byRef = $subNodes['byRef'] ?? false; + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->params = $subNodes['params'] ?? []; + $this->returnType = $subNodes['returnType'] ?? null; + $this->stmts = $subNodes['stmts'] ?? []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'byRef', 'name', 'params', 'returnType', 'stmts']; + } + + public function returnsByRef(): bool { + return $this->byRef; + } + + public function getParams(): array { + return $this->params; + } + + public function getReturnType() { + return $this->returnType; + } + + public function getAttrGroups(): array { + return $this->attrGroups; + } + + /** @return Node\Stmt[] */ + public function getStmts(): array { + return $this->stmts; + } + + public function getType(): string { + return 'Stmt_Function'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Global_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Global_.php new file mode 100644 index 0000000..d3ab12f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Global_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Global_ extends Node\Stmt { + /** @var Node\Expr[] Variables */ + public array $vars; + + /** + * Constructs a global variables list node. + * + * @param Node\Expr[] $vars Variables to unset + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $vars, array $attributes = []) { + $this->attributes = $attributes; + $this->vars = $vars; + } + + public function getSubNodeNames(): array { + return ['vars']; + } + + public function getType(): string { + return 'Stmt_Global'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Goto_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Goto_.php new file mode 100644 index 0000000..26a0d01 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Goto_.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Identifier; +use PhpParser\Node\Stmt; + +class Goto_ extends Stmt { + /** @var Identifier Name of label to jump to */ + public Identifier $name; + + /** + * Constructs a goto node. + * + * @param string|Identifier $name Name of label to jump to + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $attributes = []) { + $this->attributes = $attributes; + $this->name = \is_string($name) ? new Identifier($name) : $name; + } + + public function getSubNodeNames(): array { + return ['name']; + } + + public function getType(): string { + return 'Stmt_Goto'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/GroupUse.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/GroupUse.php new file mode 100644 index 0000000..0ec8e9d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/GroupUse.php @@ -0,0 +1,41 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Name; +use PhpParser\Node\Stmt; +use PhpParser\Node\UseItem; + +class GroupUse extends Stmt { + /** + * @var Use_::TYPE_* Type of group use + */ + public int $type; + /** @var Name Prefix for uses */ + public Name $prefix; + /** @var UseItem[] Uses */ + public array $uses; + + /** + * Constructs a group use node. + * + * @param Name $prefix Prefix for uses + * @param UseItem[] $uses Uses + * @param Use_::TYPE_* $type Type of group use + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Name $prefix, array $uses, int $type = Use_::TYPE_NORMAL, array $attributes = []) { + $this->attributes = $attributes; + $this->type = $type; + $this->prefix = $prefix; + $this->uses = $uses; + } + + public function getSubNodeNames(): array { + return ['type', 'prefix', 'uses']; + } + + public function getType(): string { + return 'Stmt_GroupUse'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/HaltCompiler.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/HaltCompiler.php new file mode 100644 index 0000000..665bacd --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/HaltCompiler.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Stmt; + +class HaltCompiler extends Stmt { + /** @var string Remaining text after halt compiler statement. */ + public string $remaining; + + /** + * Constructs a __halt_compiler node. + * + * @param string $remaining Remaining text after halt compiler statement. + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(string $remaining, array $attributes = []) { + $this->attributes = $attributes; + $this->remaining = $remaining; + } + + public function getSubNodeNames(): array { + return ['remaining']; + } + + public function getType(): string { + return 'Stmt_HaltCompiler'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/If_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/If_.php new file mode 100644 index 0000000..544390f --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/If_.php @@ -0,0 +1,46 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class If_ extends Node\Stmt { + /** @var Node\Expr Condition expression */ + public Node\Expr $cond; + /** @var Node\Stmt[] Statements */ + public array $stmts; + /** @var ElseIf_[] Elseif clauses */ + public array $elseifs; + /** @var null|Else_ Else clause */ + public ?Else_ $else; + + /** + * Constructs an if node. + * + * @param Node\Expr $cond Condition + * @param array{ + * stmts?: Node\Stmt[], + * elseifs?: ElseIf_[], + * else?: Else_|null, + * } $subNodes Array of the following optional subnodes: + * 'stmts' => array(): Statements + * 'elseifs' => array(): Elseif clauses + * 'else' => null : Else clause + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $cond, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->stmts = $subNodes['stmts'] ?? []; + $this->elseifs = $subNodes['elseifs'] ?? []; + $this->else = $subNodes['else'] ?? null; + } + + public function getSubNodeNames(): array { + return ['cond', 'stmts', 'elseifs', 'else']; + } + + public function getType(): string { + return 'Stmt_If'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/InlineHTML.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/InlineHTML.php new file mode 100644 index 0000000..0515d02 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/InlineHTML.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Stmt; + +class InlineHTML extends Stmt { + /** @var string String */ + public string $value; + + /** + * Constructs an inline HTML node. + * + * @param string $value String + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(string $value, array $attributes = []) { + $this->attributes = $attributes; + $this->value = $value; + } + + public function getSubNodeNames(): array { + return ['value']; + } + + public function getType(): string { + return 'Stmt_InlineHTML'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Interface_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Interface_.php new file mode 100644 index 0000000..9359064 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Interface_.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Interface_ extends ClassLike { + /** @var Node\Name[] Extended interfaces */ + public array $extends; + + /** + * Constructs a class node. + * + * @param string|Node\Identifier $name Name + * @param array{ + * extends?: Node\Name[], + * stmts?: Node\Stmt[], + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'extends' => array(): Name of extended interfaces + * 'stmts' => array(): Statements + * 'attrGroups' => array(): PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->extends = $subNodes['extends'] ?? []; + $this->stmts = $subNodes['stmts'] ?? []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'name', 'extends', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Interface'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Label.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Label.php new file mode 100644 index 0000000..658468d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Label.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Identifier; +use PhpParser\Node\Stmt; + +class Label extends Stmt { + /** @var Identifier Name */ + public Identifier $name; + + /** + * Constructs a label node. + * + * @param string|Identifier $name Name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $attributes = []) { + $this->attributes = $attributes; + $this->name = \is_string($name) ? new Identifier($name) : $name; + } + + public function getSubNodeNames(): array { + return ['name']; + } + + public function getType(): string { + return 'Stmt_Label'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Namespace_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Namespace_.php new file mode 100644 index 0000000..f5b59ad --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Namespace_.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Namespace_ extends Node\Stmt { + /* For use in the "kind" attribute */ + public const KIND_SEMICOLON = 1; + public const KIND_BRACED = 2; + + /** @var null|Node\Name Name */ + public ?Node\Name $name; + /** @var Node\Stmt[] Statements */ + public $stmts; + + /** + * Constructs a namespace node. + * + * @param null|Node\Name $name Name + * @param null|Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Node\Name $name = null, ?array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->name = $name; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['name', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Namespace'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Nop.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Nop.php new file mode 100644 index 0000000..3acfa46 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Nop.php @@ -0,0 +1,16 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +/** Nop/empty statement (;). */ +class Nop extends Node\Stmt { + public function getSubNodeNames(): array { + return []; + } + + public function getType(): string { + return 'Stmt_Nop'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Property.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Property.php new file mode 100644 index 0000000..872ea6b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Property.php @@ -0,0 +1,82 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\ComplexType; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\PropertyItem; + +class Property extends Node\Stmt { + /** @var int Modifiers */ + public int $flags; + /** @var PropertyItem[] Properties */ + public array $props; + /** @var null|Identifier|Name|ComplexType Type declaration */ + public ?Node $type; + /** @var Node\AttributeGroup[] PHP attribute groups */ + public array $attrGroups; + + /** + * Constructs a class property list node. + * + * @param int $flags Modifiers + * @param PropertyItem[] $props Properties + * @param array<string, mixed> $attributes Additional attributes + * @param null|Identifier|Name|ComplexType $type Type declaration + * @param Node\AttributeGroup[] $attrGroups PHP attribute groups + */ + public function __construct(int $flags, array $props, array $attributes = [], ?Node $type = null, array $attrGroups = []) { + $this->attributes = $attributes; + $this->flags = $flags; + $this->props = $props; + $this->type = $type; + $this->attrGroups = $attrGroups; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'flags', 'type', 'props']; + } + + /** + * Whether the property is explicitly or implicitly public. + */ + public function isPublic(): bool { + return ($this->flags & Modifiers::PUBLIC) !== 0 + || ($this->flags & Modifiers::VISIBILITY_MASK) === 0; + } + + /** + * Whether the property is protected. + */ + public function isProtected(): bool { + return (bool) ($this->flags & Modifiers::PROTECTED); + } + + /** + * Whether the property is private. + */ + public function isPrivate(): bool { + return (bool) ($this->flags & Modifiers::PRIVATE); + } + + /** + * Whether the property is static. + */ + public function isStatic(): bool { + return (bool) ($this->flags & Modifiers::STATIC); + } + + /** + * Whether the property is readonly. + */ + public function isReadonly(): bool { + return (bool) ($this->flags & Modifiers::READONLY); + } + + public function getType(): string { + return 'Stmt_Property'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/PropertyProperty.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/PropertyProperty.php new file mode 100644 index 0000000..4a21a88 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/PropertyProperty.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../PropertyItem.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Return_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Return_.php new file mode 100644 index 0000000..9c44cca --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Return_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Return_ extends Node\Stmt { + /** @var null|Node\Expr Expression */ + public ?Node\Expr $expr; + + /** + * Constructs a return node. + * + * @param null|Node\Expr $expr Expression + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Node\Expr $expr = null, array $attributes = []) { + $this->attributes = $attributes; + $this->expr = $expr; + } + + public function getSubNodeNames(): array { + return ['expr']; + } + + public function getType(): string { + return 'Stmt_Return'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/StaticVar.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/StaticVar.php new file mode 100644 index 0000000..88452e7 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/StaticVar.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../StaticVar.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Static_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Static_.php new file mode 100644 index 0000000..a84de10 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Static_.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\StaticVar; +use PhpParser\Node\Stmt; + +class Static_ extends Stmt { + /** @var StaticVar[] Variable definitions */ + public array $vars; + + /** + * Constructs a static variables list node. + * + * @param StaticVar[] $vars Variable definitions + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $vars, array $attributes = []) { + $this->attributes = $attributes; + $this->vars = $vars; + } + + public function getSubNodeNames(): array { + return ['vars']; + } + + public function getType(): string { + return 'Stmt_Static'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Switch_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Switch_.php new file mode 100644 index 0000000..21e5efa --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Switch_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Switch_ extends Node\Stmt { + /** @var Node\Expr Condition */ + public Node\Expr $cond; + /** @var Case_[] Case list */ + public array $cases; + + /** + * Constructs a case node. + * + * @param Node\Expr $cond Condition + * @param Case_[] $cases Case list + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $cond, array $cases, array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->cases = $cases; + } + + public function getSubNodeNames(): array { + return ['cond', 'cases']; + } + + public function getType(): string { + return 'Stmt_Switch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUse.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUse.php new file mode 100644 index 0000000..7705a57 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUse.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class TraitUse extends Node\Stmt { + /** @var Node\Name[] Traits */ + public array $traits; + /** @var TraitUseAdaptation[] Adaptations */ + public array $adaptations; + + /** + * Constructs a trait use node. + * + * @param Node\Name[] $traits Traits + * @param TraitUseAdaptation[] $adaptations Adaptations + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $traits, array $adaptations = [], array $attributes = []) { + $this->attributes = $attributes; + $this->traits = $traits; + $this->adaptations = $adaptations; + } + + public function getSubNodeNames(): array { + return ['traits', 'adaptations']; + } + + public function getType(): string { + return 'Stmt_TraitUse'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation.php new file mode 100644 index 0000000..987bc88 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation.php @@ -0,0 +1,12 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +abstract class TraitUseAdaptation extends Node\Stmt { + /** @var Node\Name|null Trait name */ + public ?Node\Name $trait; + /** @var Node\Identifier Method name */ + public Node\Identifier $method; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Alias.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Alias.php new file mode 100644 index 0000000..449671e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Alias.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt\TraitUseAdaptation; + +use PhpParser\Node; + +class Alias extends Node\Stmt\TraitUseAdaptation { + /** @var null|int New modifier */ + public ?int $newModifier; + /** @var null|Node\Identifier New name */ + public ?Node\Identifier $newName; + + /** + * Constructs a trait use precedence adaptation node. + * + * @param null|Node\Name $trait Trait name + * @param string|Node\Identifier $method Method name + * @param null|int $newModifier New modifier + * @param null|string|Node\Identifier $newName New name + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(?Node\Name $trait, $method, ?int $newModifier, $newName, array $attributes = []) { + $this->attributes = $attributes; + $this->trait = $trait; + $this->method = \is_string($method) ? new Node\Identifier($method) : $method; + $this->newModifier = $newModifier; + $this->newName = \is_string($newName) ? new Node\Identifier($newName) : $newName; + } + + public function getSubNodeNames(): array { + return ['trait', 'method', 'newModifier', 'newName']; + } + + public function getType(): string { + return 'Stmt_TraitUseAdaptation_Alias'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Precedence.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Precedence.php new file mode 100644 index 0000000..7bc4083 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Precedence.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt\TraitUseAdaptation; + +use PhpParser\Node; + +class Precedence extends Node\Stmt\TraitUseAdaptation { + /** @var Node\Name[] Overwritten traits */ + public array $insteadof; + + /** + * Constructs a trait use precedence adaptation node. + * + * @param Node\Name $trait Trait name + * @param string|Node\Identifier $method Method name + * @param Node\Name[] $insteadof Overwritten traits + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Name $trait, $method, array $insteadof, array $attributes = []) { + $this->attributes = $attributes; + $this->trait = $trait; + $this->method = \is_string($method) ? new Node\Identifier($method) : $method; + $this->insteadof = $insteadof; + } + + public function getSubNodeNames(): array { + return ['trait', 'method', 'insteadof']; + } + + public function getType(): string { + return 'Stmt_TraitUseAdaptation_Precedence'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Trait_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Trait_.php new file mode 100644 index 0000000..5f2b330 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Trait_.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Trait_ extends ClassLike { + /** + * Constructs a trait node. + * + * @param string|Node\Identifier $name Name + * @param array{ + * stmts?: Node\Stmt[], + * attrGroups?: Node\AttributeGroup[], + * } $subNodes Array of the following optional subnodes: + * 'stmts' => array(): Statements + * 'attrGroups' => array(): PHP attribute groups + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct($name, array $subNodes = [], array $attributes = []) { + $this->attributes = $attributes; + $this->name = \is_string($name) ? new Node\Identifier($name) : $name; + $this->stmts = $subNodes['stmts'] ?? []; + $this->attrGroups = $subNodes['attrGroups'] ?? []; + } + + public function getSubNodeNames(): array { + return ['attrGroups', 'name', 'stmts']; + } + + public function getType(): string { + return 'Stmt_Trait'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TryCatch.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TryCatch.php new file mode 100644 index 0000000..6414c46 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TryCatch.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class TryCatch extends Node\Stmt { + /** @var Node\Stmt[] Statements */ + public array $stmts; + /** @var Catch_[] Catches */ + public array $catches; + /** @var null|Finally_ Optional finally node */ + public ?Finally_ $finally; + + /** + * Constructs a try catch node. + * + * @param Node\Stmt[] $stmts Statements + * @param Catch_[] $catches Catches + * @param null|Finally_ $finally Optional finally node + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $stmts, array $catches, ?Finally_ $finally = null, array $attributes = []) { + $this->attributes = $attributes; + $this->stmts = $stmts; + $this->catches = $catches; + $this->finally = $finally; + } + + public function getSubNodeNames(): array { + return ['stmts', 'catches', 'finally']; + } + + public function getType(): string { + return 'Stmt_TryCatch'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Unset_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Unset_.php new file mode 100644 index 0000000..c211beb --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Unset_.php @@ -0,0 +1,29 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class Unset_ extends Node\Stmt { + /** @var Node\Expr[] Variables to unset */ + public array $vars; + + /** + * Constructs an unset node. + * + * @param Node\Expr[] $vars Variables to unset + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $vars, array $attributes = []) { + $this->attributes = $attributes; + $this->vars = $vars; + } + + public function getSubNodeNames(): array { + return ['vars']; + } + + public function getType(): string { + return 'Stmt_Unset'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/UseUse.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/UseUse.php new file mode 100644 index 0000000..85830ed --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/UseUse.php @@ -0,0 +1,3 @@ +<?php declare(strict_types=1); + +require __DIR__ . '/../UseItem.php'; diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Use_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Use_.php new file mode 100644 index 0000000..5b2d864 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Use_.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node\Stmt; +use PhpParser\Node\UseItem; + +class Use_ extends Stmt { + /** + * Unknown type. Both Stmt\Use_ / Stmt\GroupUse and Stmt\UseUse have a $type property, one of them will always be + * TYPE_UNKNOWN while the other has one of the three other possible types. For normal use statements the type on the + * Stmt\UseUse is unknown. It's only the other way around for mixed group use declarations. + */ + public const TYPE_UNKNOWN = 0; + /** Class or namespace import */ + public const TYPE_NORMAL = 1; + /** Function import */ + public const TYPE_FUNCTION = 2; + /** Constant import */ + public const TYPE_CONSTANT = 3; + + /** @var self::TYPE_* Type of alias */ + public int $type; + /** @var UseItem[] Aliases */ + public array $uses; + + /** + * Constructs an alias (use) list node. + * + * @param UseItem[] $uses Aliases + * @param Stmt\Use_::TYPE_* $type Type of alias + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $uses, int $type = self::TYPE_NORMAL, array $attributes = []) { + $this->attributes = $attributes; + $this->type = $type; + $this->uses = $uses; + } + + public function getSubNodeNames(): array { + return ['type', 'uses']; + } + + public function getType(): string { + return 'Stmt_Use'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/While_.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/While_.php new file mode 100644 index 0000000..2f7aed2 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/While_.php @@ -0,0 +1,33 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node\Stmt; + +use PhpParser\Node; + +class While_ extends Node\Stmt { + /** @var Node\Expr Condition */ + public Node\Expr $cond; + /** @var Node\Stmt[] Statements */ + public array $stmts; + + /** + * Constructs a while node. + * + * @param Node\Expr $cond Condition + * @param Node\Stmt[] $stmts Statements + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Expr $cond, array $stmts = [], array $attributes = []) { + $this->attributes = $attributes; + $this->cond = $cond; + $this->stmts = $stmts; + } + + public function getSubNodeNames(): array { + return ['cond', 'stmts']; + } + + public function getType(): string { + return 'Stmt_While'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/UnionType.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/UnionType.php new file mode 100644 index 0000000..bad88d2 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/UnionType.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +class UnionType extends ComplexType { + /** @var (Identifier|Name|IntersectionType)[] Types */ + public array $types; + + /** + * Constructs a union type. + * + * @param (Identifier|Name|IntersectionType)[] $types Types + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $types, array $attributes = []) { + $this->attributes = $attributes; + $this->types = $types; + } + + public function getSubNodeNames(): array { + return ['types']; + } + + public function getType(): string { + return 'UnionType'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/UseItem.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/UseItem.php new file mode 100644 index 0000000..a7d9fc4 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/UseItem.php @@ -0,0 +1,55 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\Node; +use PhpParser\NodeAbstract; +use PhpParser\Node\Stmt\Use_; + +class UseItem extends NodeAbstract { + /** + * @var Use_::TYPE_* One of the Stmt\Use_::TYPE_* constants. Will only differ from TYPE_UNKNOWN for mixed group uses + */ + public int $type; + /** @var Node\Name Namespace, class, function or constant to alias */ + public Name $name; + /** @var Identifier|null Alias */ + public ?Identifier $alias; + + /** + * Constructs an alias (use) item node. + * + * @param Node\Name $name Namespace/Class to alias + * @param null|string|Identifier $alias Alias + * @param Use_::TYPE_* $type Type of the use element (for mixed group use only) + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(Node\Name $name, $alias = null, int $type = Use_::TYPE_UNKNOWN, array $attributes = []) { + $this->attributes = $attributes; + $this->type = $type; + $this->name = $name; + $this->alias = \is_string($alias) ? new Identifier($alias) : $alias; + } + + public function getSubNodeNames(): array { + return ['type', 'name', 'alias']; + } + + /** + * Get alias. If not explicitly given this is the last component of the used name. + */ + public function getAlias(): Identifier { + if (null !== $this->alias) { + return $this->alias; + } + + return new Identifier($this->name->getLast()); + } + + public function getType(): string { + return 'UseItem'; + } +} + +// @deprecated compatibility alias +class_alias(UseItem::class, Stmt\UseUse::class); diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/VarLikeIdentifier.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/VarLikeIdentifier.php new file mode 100644 index 0000000..9baa6fe --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/VarLikeIdentifier.php @@ -0,0 +1,16 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +/** + * Represents a name that is written in source code with a leading dollar, + * but is not a proper variable. The leading dollar is not stored as part of the name. + * + * Examples: Names in property declarations are formatted as variables. Names in static property + * lookups are also formatted as variables. + */ +class VarLikeIdentifier extends Identifier { + public function getType(): string { + return 'VarLikeIdentifier'; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/VariadicPlaceholder.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/VariadicPlaceholder.php new file mode 100644 index 0000000..48c4f33 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Node/VariadicPlaceholder.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Node; + +use PhpParser\NodeAbstract; + +/** + * Represents the "..." in "foo(...)" of the first-class callable syntax. + */ +class VariadicPlaceholder extends NodeAbstract { + /** + * Create a variadic argument placeholder (first-class callable syntax). + * + * @param array<string, mixed> $attributes Additional attributes + */ + public function __construct(array $attributes = []) { + $this->attributes = $attributes; + } + + public function getType(): string { + return 'VariadicPlaceholder'; + } + + public function getSubNodeNames(): array { + return []; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeAbstract.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeAbstract.php new file mode 100644 index 0000000..7c3a360 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeAbstract.php @@ -0,0 +1,178 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +abstract class NodeAbstract implements Node, \JsonSerializable { + /** @var array<string, mixed> Attributes */ + protected array $attributes; + + /** + * Creates a Node. + * + * @param array<string, mixed> $attributes Array of attributes + */ + public function __construct(array $attributes = []) { + $this->attributes = $attributes; + } + + /** + * Gets line the node started in (alias of getStartLine). + * + * @return int Start line (or -1 if not available) + */ + public function getLine(): int { + return $this->attributes['startLine'] ?? -1; + } + + /** + * Gets line the node started in. + * + * Requires the 'startLine' attribute to be enabled in the lexer (enabled by default). + * + * @return int Start line (or -1 if not available) + */ + public function getStartLine(): int { + return $this->attributes['startLine'] ?? -1; + } + + /** + * Gets the line the node ended in. + * + * Requires the 'endLine' attribute to be enabled in the lexer (enabled by default). + * + * @return int End line (or -1 if not available) + */ + public function getEndLine(): int { + return $this->attributes['endLine'] ?? -1; + } + + /** + * Gets the token offset of the first token that is part of this node. + * + * The offset is an index into the array returned by Lexer::getTokens(). + * + * Requires the 'startTokenPos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int Token start position (or -1 if not available) + */ + public function getStartTokenPos(): int { + return $this->attributes['startTokenPos'] ?? -1; + } + + /** + * Gets the token offset of the last token that is part of this node. + * + * The offset is an index into the array returned by Lexer::getTokens(). + * + * Requires the 'endTokenPos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int Token end position (or -1 if not available) + */ + public function getEndTokenPos(): int { + return $this->attributes['endTokenPos'] ?? -1; + } + + /** + * Gets the file offset of the first character that is part of this node. + * + * Requires the 'startFilePos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int File start position (or -1 if not available) + */ + public function getStartFilePos(): int { + return $this->attributes['startFilePos'] ?? -1; + } + + /** + * Gets the file offset of the last character that is part of this node. + * + * Requires the 'endFilePos' attribute to be enabled in the lexer (DISABLED by default). + * + * @return int File end position (or -1 if not available) + */ + public function getEndFilePos(): int { + return $this->attributes['endFilePos'] ?? -1; + } + + /** + * Gets all comments directly preceding this node. + * + * The comments are also available through the "comments" attribute. + * + * @return Comment[] + */ + public function getComments(): array { + return $this->attributes['comments'] ?? []; + } + + /** + * Gets the doc comment of the node. + * + * @return null|Comment\Doc Doc comment object or null + */ + public function getDocComment(): ?Comment\Doc { + $comments = $this->getComments(); + for ($i = count($comments) - 1; $i >= 0; $i--) { + $comment = $comments[$i]; + if ($comment instanceof Comment\Doc) { + return $comment; + } + } + + return null; + } + + /** + * Sets the doc comment of the node. + * + * This will either replace an existing doc comment or add it to the comments array. + * + * @param Comment\Doc $docComment Doc comment to set + */ + public function setDocComment(Comment\Doc $docComment): void { + $comments = $this->getComments(); + for ($i = count($comments) - 1; $i >= 0; $i--) { + if ($comments[$i] instanceof Comment\Doc) { + // Replace existing doc comment. + $comments[$i] = $docComment; + $this->setAttribute('comments', $comments); + return; + } + } + + // Append new doc comment. + $comments[] = $docComment; + $this->setAttribute('comments', $comments); + } + + public function setAttribute(string $key, $value): void { + $this->attributes[$key] = $value; + } + + public function hasAttribute(string $key): bool { + return array_key_exists($key, $this->attributes); + } + + public function getAttribute(string $key, $default = null) { + if (array_key_exists($key, $this->attributes)) { + return $this->attributes[$key]; + } + + return $default; + } + + public function getAttributes(): array { + return $this->attributes; + } + + public function setAttributes(array $attributes): void { + $this->attributes = $attributes; + } + + /** + * @return array<string, mixed> + */ + public function jsonSerialize(): array { + return ['nodeType' => $this->getType()] + get_object_vars($this); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeDumper.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeDumper.php new file mode 100644 index 0000000..a2535de --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeDumper.php @@ -0,0 +1,290 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Node\Expr\Array_; +use PhpParser\Node\Expr\Include_; +use PhpParser\Node\Expr\List_; +use PhpParser\Node\Scalar\Int_; +use PhpParser\Node\Scalar\InterpolatedString; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt\GroupUse; +use PhpParser\Node\Stmt\Use_; +use PhpParser\Node\UseItem; + +class NodeDumper { + private bool $dumpComments; + private bool $dumpPositions; + private bool $dumpOtherAttributes; + private ?string $code; + private string $res; + private string $nl; + + private const IGNORE_ATTRIBUTES = [ + 'comments' => true, + 'startLine' => true, + 'endLine' => true, + 'startFilePos' => true, + 'endFilePos' => true, + 'startTokenPos' => true, + 'endTokenPos' => true, + ]; + + /** + * Constructs a NodeDumper. + * + * Supported options: + * * bool dumpComments: Whether comments should be dumped. + * * bool dumpPositions: Whether line/offset information should be dumped. To dump offset + * information, the code needs to be passed to dump(). + * * bool dumpOtherAttributes: Whether non-comment, non-position attributes should be dumped. + * + * @param array $options Options (see description) + */ + public function __construct(array $options = []) { + $this->dumpComments = !empty($options['dumpComments']); + $this->dumpPositions = !empty($options['dumpPositions']); + $this->dumpOtherAttributes = !empty($options['dumpOtherAttributes']); + } + + /** + * Dumps a node or array. + * + * @param array|Node $node Node or array to dump + * @param string|null $code Code corresponding to dumped AST. This only needs to be passed if + * the dumpPositions option is enabled and the dumping of node offsets + * is desired. + * + * @return string Dumped value + */ + public function dump($node, ?string $code = null): string { + $this->code = $code; + $this->res = ''; + $this->nl = "\n"; + $this->dumpRecursive($node, false); + return $this->res; + } + + /** @param mixed $node */ + protected function dumpRecursive($node, bool $indent = true): void { + if ($indent) { + $this->nl .= " "; + } + if ($node instanceof Node) { + $this->res .= $node->getType(); + if ($this->dumpPositions && null !== $p = $this->dumpPosition($node)) { + $this->res .= $p; + } + $this->res .= '('; + + foreach ($node->getSubNodeNames() as $key) { + $this->res .= "$this->nl " . $key . ': '; + + $value = $node->$key; + if (\is_int($value)) { + if ('flags' === $key || 'newModifier' === $key) { + $this->res .= $this->dumpFlags($value); + continue; + } + if ('type' === $key && $node instanceof Include_) { + $this->res .= $this->dumpIncludeType($value); + continue; + } + if ('type' === $key + && ($node instanceof Use_ || $node instanceof UseItem || $node instanceof GroupUse)) { + $this->res .= $this->dumpUseType($value); + continue; + } + } + $this->dumpRecursive($value); + } + + if ($this->dumpComments && $comments = $node->getComments()) { + $this->res .= "$this->nl comments: "; + $this->dumpRecursive($comments); + } + + if ($this->dumpOtherAttributes) { + foreach ($node->getAttributes() as $key => $value) { + if (isset(self::IGNORE_ATTRIBUTES[$key])) { + continue; + } + + $this->res .= "$this->nl $key: "; + if (\is_int($value)) { + if ('kind' === $key) { + if ($node instanceof Int_) { + $this->res .= $this->dumpIntKind($value); + continue; + } + if ($node instanceof String_ || $node instanceof InterpolatedString) { + $this->res .= $this->dumpStringKind($value); + continue; + } + if ($node instanceof Array_) { + $this->res .= $this->dumpArrayKind($value); + continue; + } + if ($node instanceof List_) { + $this->res .= $this->dumpListKind($value); + continue; + } + } + } + $this->dumpRecursive($value); + } + } + $this->res .= "$this->nl)"; + } elseif (\is_array($node)) { + $this->res .= 'array('; + foreach ($node as $key => $value) { + $this->res .= "$this->nl " . $key . ': '; + $this->dumpRecursive($value); + } + $this->res .= "$this->nl)"; + } elseif ($node instanceof Comment) { + $this->res .= \str_replace("\n", $this->nl, $node->getReformattedText()); + } elseif (\is_string($node)) { + $this->res .= \str_replace("\n", $this->nl, (string)$node); + } elseif (\is_int($node) || \is_float($node)) { + $this->res .= $node; + } elseif (null === $node) { + $this->res .= 'null'; + } elseif (false === $node) { + $this->res .= 'false'; + } elseif (true === $node) { + $this->res .= 'true'; + } else { + throw new \InvalidArgumentException('Can only dump nodes and arrays.'); + } + if ($indent) { + $this->nl = \substr($this->nl, 0, -4); + } + } + + protected function dumpFlags(int $flags): string { + $strs = []; + if ($flags & Modifiers::PUBLIC) { + $strs[] = 'PUBLIC'; + } + if ($flags & Modifiers::PROTECTED) { + $strs[] = 'PROTECTED'; + } + if ($flags & Modifiers::PRIVATE) { + $strs[] = 'PRIVATE'; + } + if ($flags & Modifiers::ABSTRACT) { + $strs[] = 'ABSTRACT'; + } + if ($flags & Modifiers::STATIC) { + $strs[] = 'STATIC'; + } + if ($flags & Modifiers::FINAL) { + $strs[] = 'FINAL'; + } + if ($flags & Modifiers::READONLY) { + $strs[] = 'READONLY'; + } + + if ($strs) { + return implode(' | ', $strs) . ' (' . $flags . ')'; + } else { + return (string) $flags; + } + } + + /** @param array<int, string> $map */ + private function dumpEnum(int $value, array $map): string { + if (!isset($map[$value])) { + return (string) $value; + } + return $map[$value] . ' (' . $value . ')'; + } + + private function dumpIncludeType(int $type): string { + return $this->dumpEnum($type, [ + Include_::TYPE_INCLUDE => 'TYPE_INCLUDE', + Include_::TYPE_INCLUDE_ONCE => 'TYPE_INCLUDE_ONCE', + Include_::TYPE_REQUIRE => 'TYPE_REQUIRE', + Include_::TYPE_REQUIRE_ONCE => 'TYPE_REQUIRE_ONCE', + ]); + } + + private function dumpUseType(int $type): string { + return $this->dumpEnum($type, [ + Use_::TYPE_UNKNOWN => 'TYPE_UNKNOWN', + Use_::TYPE_NORMAL => 'TYPE_NORMAL', + Use_::TYPE_FUNCTION => 'TYPE_FUNCTION', + Use_::TYPE_CONSTANT => 'TYPE_CONSTANT', + ]); + } + + private function dumpIntKind(int $kind): string { + return $this->dumpEnum($kind, [ + Int_::KIND_BIN => 'KIND_BIN', + Int_::KIND_OCT => 'KIND_OCT', + Int_::KIND_DEC => 'KIND_DEC', + Int_::KIND_HEX => 'KIND_HEX', + ]); + } + + private function dumpStringKind(int $kind): string { + return $this->dumpEnum($kind, [ + String_::KIND_SINGLE_QUOTED => 'KIND_SINGLE_QUOTED', + String_::KIND_DOUBLE_QUOTED => 'KIND_DOUBLE_QUOTED', + String_::KIND_HEREDOC => 'KIND_HEREDOC', + String_::KIND_NOWDOC => 'KIND_NOWDOC', + ]); + } + + private function dumpArrayKind(int $kind): string { + return $this->dumpEnum($kind, [ + Array_::KIND_LONG => 'KIND_LONG', + Array_::KIND_SHORT => 'KIND_SHORT', + ]); + } + + private function dumpListKind(int $kind): string { + return $this->dumpEnum($kind, [ + List_::KIND_LIST => 'KIND_LIST', + List_::KIND_ARRAY => 'KIND_ARRAY', + ]); + } + + /** + * Dump node position, if possible. + * + * @param Node $node Node for which to dump position + * + * @return string|null Dump of position, or null if position information not available + */ + protected function dumpPosition(Node $node): ?string { + if (!$node->hasAttribute('startLine') || !$node->hasAttribute('endLine')) { + return null; + } + + $start = $node->getStartLine(); + $end = $node->getEndLine(); + if ($node->hasAttribute('startFilePos') && $node->hasAttribute('endFilePos') + && null !== $this->code + ) { + $start .= ':' . $this->toColumn($this->code, $node->getStartFilePos()); + $end .= ':' . $this->toColumn($this->code, $node->getEndFilePos()); + } + return "[$start - $end]"; + } + + // Copied from Error class + private function toColumn(string $code, int $pos): int { + if ($pos > strlen($code)) { + throw new \RuntimeException('Invalid position information'); + } + + $lineStartPos = strrpos($code, "\n", $pos - strlen($code)); + if (false === $lineStartPos) { + $lineStartPos = -1; + } + + return $pos - $lineStartPos; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeFinder.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeFinder.php new file mode 100644 index 0000000..96c8452 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeFinder.php @@ -0,0 +1,90 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\NodeVisitor\FindingVisitor; +use PhpParser\NodeVisitor\FirstFindingVisitor; + +class NodeFinder { + /** + * Find all nodes satisfying a filter callback. + * + * @param Node|Node[] $nodes Single node or array of nodes to search in + * @param callable $filter Filter callback: function(Node $node) : bool + * + * @return Node[] Found nodes satisfying the filter callback + */ + public function find($nodes, callable $filter): array { + if ($nodes === []) { + return []; + } + + if (!is_array($nodes)) { + $nodes = [$nodes]; + } + + $visitor = new FindingVisitor($filter); + + $traverser = new NodeTraverser($visitor); + $traverser->traverse($nodes); + + return $visitor->getFoundNodes(); + } + + /** + * Find all nodes that are instances of a certain class. + + * @template TNode as Node + * + * @param Node|Node[] $nodes Single node or array of nodes to search in + * @param class-string<TNode> $class Class name + * + * @return TNode[] Found nodes (all instances of $class) + */ + public function findInstanceOf($nodes, string $class): array { + return $this->find($nodes, function ($node) use ($class) { + return $node instanceof $class; + }); + } + + /** + * Find first node satisfying a filter callback. + * + * @param Node|Node[] $nodes Single node or array of nodes to search in + * @param callable $filter Filter callback: function(Node $node) : bool + * + * @return null|Node Found node (or null if none found) + */ + public function findFirst($nodes, callable $filter): ?Node { + if ($nodes === []) { + return null; + } + + if (!is_array($nodes)) { + $nodes = [$nodes]; + } + + $visitor = new FirstFindingVisitor($filter); + + $traverser = new NodeTraverser($visitor); + $traverser->traverse($nodes); + + return $visitor->getFoundNode(); + } + + /** + * Find first node that is an instance of a certain class. + * + * @template TNode as Node + * + * @param Node|Node[] $nodes Single node or array of nodes to search in + * @param class-string<TNode> $class Class name + * + * @return null|TNode Found node, which is an instance of $class (or null if none found) + */ + public function findFirstInstanceOf($nodes, string $class): ?Node { + return $this->findFirst($nodes, function ($node) use ($class) { + return $node instanceof $class; + }); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeTraverser.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeTraverser.php new file mode 100644 index 0000000..f5b868a --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeTraverser.php @@ -0,0 +1,278 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +class NodeTraverser implements NodeTraverserInterface { + /** + * @deprecated Use NodeVisitor::DONT_TRAVERSE_CHILDREN instead. + */ + public const DONT_TRAVERSE_CHILDREN = NodeVisitor::DONT_TRAVERSE_CHILDREN; + + /** + * @deprecated Use NodeVisitor::STOP_TRAVERSAL instead. + */ + public const STOP_TRAVERSAL = NodeVisitor::STOP_TRAVERSAL; + + /** + * @deprecated Use NodeVisitor::REMOVE_NODE instead. + */ + public const REMOVE_NODE = NodeVisitor::REMOVE_NODE; + + /** + * @deprecated Use NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN instead. + */ + public const DONT_TRAVERSE_CURRENT_AND_CHILDREN = NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + + /** @var list<NodeVisitor> Visitors */ + protected array $visitors = []; + + /** @var bool Whether traversal should be stopped */ + protected bool $stopTraversal; + + /** + * Create a traverser with the given visitors. + * + * @param NodeVisitor ...$visitors Node visitors + */ + public function __construct(NodeVisitor ...$visitors) { + $this->visitors = $visitors; + } + + /** + * Adds a visitor. + * + * @param NodeVisitor $visitor Visitor to add + */ + public function addVisitor(NodeVisitor $visitor): void { + $this->visitors[] = $visitor; + } + + /** + * Removes an added visitor. + */ + public function removeVisitor(NodeVisitor $visitor): void { + $index = array_search($visitor, $this->visitors); + if ($index !== false) { + array_splice($this->visitors, $index, 1, []); + } + } + + /** + * Traverses an array of nodes using the registered visitors. + * + * @param Node[] $nodes Array of nodes + * + * @return Node[] Traversed array of nodes + */ + public function traverse(array $nodes): array { + $this->stopTraversal = false; + + foreach ($this->visitors as $visitor) { + if (null !== $return = $visitor->beforeTraverse($nodes)) { + $nodes = $return; + } + } + + $nodes = $this->traverseArray($nodes); + + for ($i = \count($this->visitors) - 1; $i >= 0; --$i) { + $visitor = $this->visitors[$i]; + if (null !== $return = $visitor->afterTraverse($nodes)) { + $nodes = $return; + } + } + + return $nodes; + } + + /** + * Recursively traverse a node. + * + * @param Node $node Node to traverse. + */ + protected function traverseNode(Node $node): void { + foreach ($node->getSubNodeNames() as $name) { + $subNode = $node->$name; + + if (\is_array($subNode)) { + $node->$name = $this->traverseArray($subNode); + if ($this->stopTraversal) { + break; + } + } elseif ($subNode instanceof Node) { + $traverseChildren = true; + $visitorIndex = -1; + + foreach ($this->visitors as $visitorIndex => $visitor) { + $return = $visitor->enterNode($subNode); + if (null !== $return) { + if ($return instanceof Node) { + $this->ensureReplacementReasonable($subNode, $return); + $subNode = $node->$name = $return; + } elseif (NodeVisitor::DONT_TRAVERSE_CHILDREN === $return) { + $traverseChildren = false; + } elseif (NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN === $return) { + $traverseChildren = false; + break; + } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { + $this->stopTraversal = true; + break 2; + } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { + $node->$name = null; + continue 2; + } else { + throw new \LogicException( + 'enterNode() returned invalid value of type ' . gettype($return) + ); + } + } + } + + if ($traverseChildren) { + $this->traverseNode($subNode); + if ($this->stopTraversal) { + break; + } + } + + for (; $visitorIndex >= 0; --$visitorIndex) { + $visitor = $this->visitors[$visitorIndex]; + $return = $visitor->leaveNode($subNode); + + if (null !== $return) { + if ($return instanceof Node) { + $this->ensureReplacementReasonable($subNode, $return); + $subNode = $node->$name = $return; + } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { + $this->stopTraversal = true; + break 2; + } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { + $node->$name = null; + break; + } elseif (\is_array($return)) { + throw new \LogicException( + 'leaveNode() may only return an array ' . + 'if the parent structure is an array' + ); + } else { + throw new \LogicException( + 'leaveNode() returned invalid value of type ' . gettype($return) + ); + } + } + } + } + } + } + + /** + * Recursively traverse array (usually of nodes). + * + * @param array $nodes Array to traverse + * + * @return array Result of traversal (may be original array or changed one) + */ + protected function traverseArray(array $nodes): array { + $doNodes = []; + + foreach ($nodes as $i => $node) { + if ($node instanceof Node) { + $traverseChildren = true; + $visitorIndex = -1; + + foreach ($this->visitors as $visitorIndex => $visitor) { + $return = $visitor->enterNode($node); + if (null !== $return) { + if ($return instanceof Node) { + $this->ensureReplacementReasonable($node, $return); + $nodes[$i] = $node = $return; + } elseif (\is_array($return)) { + $doNodes[] = [$i, $return]; + continue 2; + } elseif (NodeVisitor::REMOVE_NODE === $return) { + $doNodes[] = [$i, []]; + continue 2; + } elseif (NodeVisitor::DONT_TRAVERSE_CHILDREN === $return) { + $traverseChildren = false; + } elseif (NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN === $return) { + $traverseChildren = false; + break; + } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { + $this->stopTraversal = true; + break 2; + } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { + throw new \LogicException( + 'REPLACE_WITH_NULL can not be used if the parent structure is an array'); + } else { + throw new \LogicException( + 'enterNode() returned invalid value of type ' . gettype($return) + ); + } + } + } + + if ($traverseChildren) { + $this->traverseNode($node); + if ($this->stopTraversal) { + break; + } + } + + for (; $visitorIndex >= 0; --$visitorIndex) { + $visitor = $this->visitors[$visitorIndex]; + $return = $visitor->leaveNode($node); + + if (null !== $return) { + if ($return instanceof Node) { + $this->ensureReplacementReasonable($node, $return); + $nodes[$i] = $node = $return; + } elseif (\is_array($return)) { + $doNodes[] = [$i, $return]; + break; + } elseif (NodeVisitor::REMOVE_NODE === $return) { + $doNodes[] = [$i, []]; + break; + } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { + $this->stopTraversal = true; + break 2; + } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { + throw new \LogicException( + 'REPLACE_WITH_NULL can not be used if the parent structure is an array'); + } else { + throw new \LogicException( + 'leaveNode() returned invalid value of type ' . gettype($return) + ); + } + } + } + } elseif (\is_array($node)) { + throw new \LogicException('Invalid node structure: Contains nested arrays'); + } + } + + if (!empty($doNodes)) { + while (list($i, $replace) = array_pop($doNodes)) { + array_splice($nodes, $i, 1, $replace); + } + } + + return $nodes; + } + + private function ensureReplacementReasonable(Node $old, Node $new): void { + if ($old instanceof Node\Stmt && $new instanceof Node\Expr) { + throw new \LogicException( + "Trying to replace statement ({$old->getType()}) " . + "with expression ({$new->getType()}). Are you missing a " . + "Stmt_Expression wrapper?" + ); + } + + if ($old instanceof Node\Expr && $new instanceof Node\Stmt) { + throw new \LogicException( + "Trying to replace expression ({$old->getType()}) " . + "with statement ({$new->getType()})" + ); + } + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeTraverserInterface.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeTraverserInterface.php new file mode 100644 index 0000000..c3992b3 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeTraverserInterface.php @@ -0,0 +1,26 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +interface NodeTraverserInterface { + /** + * Adds a visitor. + * + * @param NodeVisitor $visitor Visitor to add + */ + public function addVisitor(NodeVisitor $visitor): void; + + /** + * Removes an added visitor. + */ + public function removeVisitor(NodeVisitor $visitor): void; + + /** + * Traverses an array of nodes using the registered visitors. + * + * @param Node[] $nodes Array of nodes + * + * @return Node[] Traversed array of nodes + */ + public function traverse(array $nodes): array; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor.php new file mode 100644 index 0000000..0ec4f7b --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor.php @@ -0,0 +1,124 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +interface NodeVisitor { + /** + * If NodeVisitor::enterNode() returns DONT_TRAVERSE_CHILDREN, child nodes + * of the current node will not be traversed for any visitors. + * + * For subsequent visitors enterNode() will still be called on the current + * node and leaveNode() will also be invoked for the current node. + */ + public const DONT_TRAVERSE_CHILDREN = 1; + + /** + * If NodeVisitor::enterNode() or NodeVisitor::leaveNode() returns + * STOP_TRAVERSAL, traversal is aborted. + * + * The afterTraverse() method will still be invoked. + */ + public const STOP_TRAVERSAL = 2; + + /** + * If NodeVisitor::leaveNode() returns REMOVE_NODE for a node that occurs + * in an array, it will be removed from the array. + * + * For subsequent visitors leaveNode() will still be invoked for the + * removed node. + */ + public const REMOVE_NODE = 3; + + /** + * If NodeVisitor::enterNode() returns DONT_TRAVERSE_CURRENT_AND_CHILDREN, child nodes + * of the current node will not be traversed for any visitors. + * + * For subsequent visitors enterNode() will not be called as well. + * leaveNode() will be invoked for visitors that has enterNode() method invoked. + */ + public const DONT_TRAVERSE_CURRENT_AND_CHILDREN = 4; + + /** + * If NodeVisitor::enterNode() or NodeVisitor::leaveNode() returns REPLACE_WITH_NULL, + * the node will be replaced with null. This is not a legal return value if the node is part + * of an array, rather than another node. + */ + public const REPLACE_WITH_NULL = 5; + + /** + * Called once before traversal. + * + * Return value semantics: + * * null: $nodes stays as-is + * * otherwise: $nodes is set to the return value + * + * @param Node[] $nodes Array of nodes + * + * @return null|Node[] Array of nodes + */ + public function beforeTraverse(array $nodes); + + /** + * Called when entering a node. + * + * Return value semantics: + * * null + * => $node stays as-is + * * array (of Nodes) + * => The return value is merged into the parent array (at the position of the $node) + * * NodeVisitor::REMOVE_NODE + * => $node is removed from the parent array + * * NodeVisitor::REPLACE_WITH_NULL + * => $node is replaced with null + * * NodeVisitor::DONT_TRAVERSE_CHILDREN + * => Children of $node are not traversed. $node stays as-is + * * NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN + * => Further visitors for the current node are skipped, and its children are not + * traversed. $node stays as-is. + * * NodeVisitor::STOP_TRAVERSAL + * => Traversal is aborted. $node stays as-is + * * otherwise + * => $node is set to the return value + * + * @param Node $node Node + * + * @return null|int|Node|Node[] Replacement node (or special return value) + */ + public function enterNode(Node $node); + + /** + * Called when leaving a node. + * + * Return value semantics: + * * null + * => $node stays as-is + * * NodeVisitor::REMOVE_NODE + * => $node is removed from the parent array + * * NodeVisitor::REPLACE_WITH_NULL + * => $node is replaced with null + * * NodeVisitor::STOP_TRAVERSAL + * => Traversal is aborted. $node stays as-is + * * array (of Nodes) + * => The return value is merged into the parent array (at the position of the $node) + * * otherwise + * => $node is set to the return value + * + * @param Node $node Node + * + * @return null|int|Node|Node[] Replacement node (or special return value) + */ + public function leaveNode(Node $node); + + /** + * Called once after traversal. + * + * Return value semantics: + * * null: $nodes stays as-is + * * otherwise: $nodes is set to the return value + * + * @param Node[] $nodes Array of nodes + * + * @return null|Node[] Array of nodes + */ + public function afterTraverse(array $nodes); +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CloningVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CloningVisitor.php new file mode 100644 index 0000000..cba9249 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CloningVisitor.php @@ -0,0 +1,19 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\Node; +use PhpParser\NodeVisitorAbstract; + +/** + * Visitor cloning all nodes and linking to the original nodes using an attribute. + * + * This visitor is required to perform format-preserving pretty prints. + */ +class CloningVisitor extends NodeVisitorAbstract { + public function enterNode(Node $origNode) { + $node = clone $origNode; + $node->setAttribute('origNode', $origNode); + return $node; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CommentAnnotatingVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CommentAnnotatingVisitor.php new file mode 100644 index 0000000..5e2aed3 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CommentAnnotatingVisitor.php @@ -0,0 +1,82 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\Comment; +use PhpParser\Node; +use PhpParser\NodeVisitorAbstract; +use PhpParser\Token; + +class CommentAnnotatingVisitor extends NodeVisitorAbstract { + /** @var int Last seen token start position */ + private int $pos = 0; + /** @var Token[] Token array */ + private array $tokens; + /** @var list<int> Token positions of comments */ + private array $commentPositions = []; + + /** + * Create a comment annotation visitor. + * + * @param Token[] $tokens Token array + */ + public function __construct(array $tokens) { + $this->tokens = $tokens; + + // Collect positions of comments. We use this to avoid traversing parts of the AST where + // there are no comments. + foreach ($tokens as $i => $token) { + if ($token->id === \T_COMMENT || $token->id === \T_DOC_COMMENT) { + $this->commentPositions[] = $i; + } + } + } + + public function enterNode(Node $node) { + $nextCommentPos = current($this->commentPositions); + if ($nextCommentPos === false) { + // No more comments. + return self::STOP_TRAVERSAL; + } + + $oldPos = $this->pos; + $this->pos = $pos = $node->getStartTokenPos(); + if ($nextCommentPos > $oldPos && $nextCommentPos < $pos) { + $comments = []; + while (--$pos >= $oldPos) { + $token = $this->tokens[$pos]; + if ($token->id === \T_DOC_COMMENT) { + $comments[] = new Comment\Doc( + $token->text, $token->line, $token->pos, $pos, + $token->getEndLine(), $token->getEndPos() - 1, $pos); + continue; + } + if ($token->id === \T_COMMENT) { + $comments[] = new Comment( + $token->text, $token->line, $token->pos, $pos, + $token->getEndLine(), $token->getEndPos() - 1, $pos); + continue; + } + if ($token->id !== \T_WHITESPACE) { + break; + } + } + if (!empty($comments)) { + $node->setAttribute('comments', array_reverse($comments)); + } + + do { + $nextCommentPos = next($this->commentPositions); + } while ($nextCommentPos !== false && $nextCommentPos < $this->pos); + } + + $endPos = $node->getEndTokenPos(); + if ($nextCommentPos > $endPos) { + // Skip children if there are no comments located inside this node. + $this->pos = $endPos; + return self::DONT_TRAVERSE_CHILDREN; + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FindingVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FindingVisitor.php new file mode 100644 index 0000000..1f3f4ba --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FindingVisitor.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\Node; +use PhpParser\NodeVisitorAbstract; + +/** + * This visitor can be used to find and collect all nodes satisfying some criterion determined by + * a filter callback. + */ +class FindingVisitor extends NodeVisitorAbstract { + /** @var callable Filter callback */ + protected $filterCallback; + /** @var Node[] Found nodes */ + protected array $foundNodes; + + public function __construct(callable $filterCallback) { + $this->filterCallback = $filterCallback; + } + + /** + * Get found nodes satisfying the filter callback. + * + * Nodes are returned in pre-order. + * + * @return Node[] Found nodes + */ + public function getFoundNodes(): array { + return $this->foundNodes; + } + + public function beforeTraverse(array $nodes): ?array { + $this->foundNodes = []; + + return null; + } + + public function enterNode(Node $node) { + $filterCallback = $this->filterCallback; + if ($filterCallback($node)) { + $this->foundNodes[] = $node; + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FirstFindingVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FirstFindingVisitor.php new file mode 100644 index 0000000..05deed5 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FirstFindingVisitor.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; +use PhpParser\NodeVisitorAbstract; + +/** + * This visitor can be used to find the first node satisfying some criterion determined by + * a filter callback. + */ +class FirstFindingVisitor extends NodeVisitorAbstract { + /** @var callable Filter callback */ + protected $filterCallback; + /** @var null|Node Found node */ + protected ?Node $foundNode; + + public function __construct(callable $filterCallback) { + $this->filterCallback = $filterCallback; + } + + /** + * Get found node satisfying the filter callback. + * + * Returns null if no node satisfies the filter callback. + * + * @return null|Node Found node (or null if not found) + */ + public function getFoundNode(): ?Node { + return $this->foundNode; + } + + public function beforeTraverse(array $nodes): ?array { + $this->foundNode = null; + + return null; + } + + public function enterNode(Node $node) { + $filterCallback = $this->filterCallback; + if ($filterCallback($node)) { + $this->foundNode = $node; + return NodeVisitor::STOP_TRAVERSAL; + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NameResolver.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NameResolver.php new file mode 100644 index 0000000..ccd014e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NameResolver.php @@ -0,0 +1,262 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\ErrorHandler; +use PhpParser\NameContext; +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; +use PhpParser\Node\Stmt; +use PhpParser\NodeVisitorAbstract; + +class NameResolver extends NodeVisitorAbstract { + /** @var NameContext Naming context */ + protected NameContext $nameContext; + + /** @var bool Whether to preserve original names */ + protected bool $preserveOriginalNames; + + /** @var bool Whether to replace resolved nodes in place, or to add resolvedNode attributes */ + protected bool $replaceNodes; + + /** + * Constructs a name resolution visitor. + * + * Options: + * * preserveOriginalNames (default false): An "originalName" attribute will be added to + * all name nodes that underwent resolution. + * * replaceNodes (default true): Resolved names are replaced in-place. Otherwise, a + * resolvedName attribute is added. (Names that cannot be statically resolved receive a + * namespacedName attribute, as usual.) + * + * @param ErrorHandler|null $errorHandler Error handler + * @param array{preserveOriginalNames?: bool, replaceNodes?: bool} $options Options + */ + public function __construct(?ErrorHandler $errorHandler = null, array $options = []) { + $this->nameContext = new NameContext($errorHandler ?? new ErrorHandler\Throwing()); + $this->preserveOriginalNames = $options['preserveOriginalNames'] ?? false; + $this->replaceNodes = $options['replaceNodes'] ?? true; + } + + /** + * Get name resolution context. + */ + public function getNameContext(): NameContext { + return $this->nameContext; + } + + public function beforeTraverse(array $nodes): ?array { + $this->nameContext->startNamespace(); + return null; + } + + public function enterNode(Node $node) { + if ($node instanceof Stmt\Namespace_) { + $this->nameContext->startNamespace($node->name); + } elseif ($node instanceof Stmt\Use_) { + foreach ($node->uses as $use) { + $this->addAlias($use, $node->type, null); + } + } elseif ($node instanceof Stmt\GroupUse) { + foreach ($node->uses as $use) { + $this->addAlias($use, $node->type, $node->prefix); + } + } elseif ($node instanceof Stmt\Class_) { + if (null !== $node->extends) { + $node->extends = $this->resolveClassName($node->extends); + } + + foreach ($node->implements as &$interface) { + $interface = $this->resolveClassName($interface); + } + + $this->resolveAttrGroups($node); + if (null !== $node->name) { + $this->addNamespacedName($node); + } else { + $node->namespacedName = null; + } + } elseif ($node instanceof Stmt\Interface_) { + foreach ($node->extends as &$interface) { + $interface = $this->resolveClassName($interface); + } + + $this->resolveAttrGroups($node); + $this->addNamespacedName($node); + } elseif ($node instanceof Stmt\Enum_) { + foreach ($node->implements as &$interface) { + $interface = $this->resolveClassName($interface); + } + + $this->resolveAttrGroups($node); + $this->addNamespacedName($node); + } elseif ($node instanceof Stmt\Trait_) { + $this->resolveAttrGroups($node); + $this->addNamespacedName($node); + } elseif ($node instanceof Stmt\Function_) { + $this->resolveSignature($node); + $this->resolveAttrGroups($node); + $this->addNamespacedName($node); + } elseif ($node instanceof Stmt\ClassMethod + || $node instanceof Expr\Closure + || $node instanceof Expr\ArrowFunction + ) { + $this->resolveSignature($node); + $this->resolveAttrGroups($node); + } elseif ($node instanceof Stmt\Property) { + if (null !== $node->type) { + $node->type = $this->resolveType($node->type); + } + $this->resolveAttrGroups($node); + } elseif ($node instanceof Stmt\Const_) { + foreach ($node->consts as $const) { + $this->addNamespacedName($const); + } + } elseif ($node instanceof Stmt\ClassConst) { + if (null !== $node->type) { + $node->type = $this->resolveType($node->type); + } + $this->resolveAttrGroups($node); + } elseif ($node instanceof Stmt\EnumCase) { + $this->resolveAttrGroups($node); + } elseif ($node instanceof Expr\StaticCall + || $node instanceof Expr\StaticPropertyFetch + || $node instanceof Expr\ClassConstFetch + || $node instanceof Expr\New_ + || $node instanceof Expr\Instanceof_ + ) { + if ($node->class instanceof Name) { + $node->class = $this->resolveClassName($node->class); + } + } elseif ($node instanceof Stmt\Catch_) { + foreach ($node->types as &$type) { + $type = $this->resolveClassName($type); + } + } elseif ($node instanceof Expr\FuncCall) { + if ($node->name instanceof Name) { + $node->name = $this->resolveName($node->name, Stmt\Use_::TYPE_FUNCTION); + } + } elseif ($node instanceof Expr\ConstFetch) { + $node->name = $this->resolveName($node->name, Stmt\Use_::TYPE_CONSTANT); + } elseif ($node instanceof Stmt\TraitUse) { + foreach ($node->traits as &$trait) { + $trait = $this->resolveClassName($trait); + } + + foreach ($node->adaptations as $adaptation) { + if (null !== $adaptation->trait) { + $adaptation->trait = $this->resolveClassName($adaptation->trait); + } + + if ($adaptation instanceof Stmt\TraitUseAdaptation\Precedence) { + foreach ($adaptation->insteadof as &$insteadof) { + $insteadof = $this->resolveClassName($insteadof); + } + } + } + } + + return null; + } + + /** @param Stmt\Use_::TYPE_* $type */ + private function addAlias(Node\UseItem $use, int $type, ?Name $prefix = null): void { + // Add prefix for group uses + $name = $prefix ? Name::concat($prefix, $use->name) : $use->name; + // Type is determined either by individual element or whole use declaration + $type |= $use->type; + + $this->nameContext->addAlias( + $name, (string) $use->getAlias(), $type, $use->getAttributes() + ); + } + + /** @param Stmt\Function_|Stmt\ClassMethod|Expr\Closure|Expr\ArrowFunction $node */ + private function resolveSignature($node): void { + foreach ($node->params as $param) { + $param->type = $this->resolveType($param->type); + $this->resolveAttrGroups($param); + } + $node->returnType = $this->resolveType($node->returnType); + } + + /** + * @template T of Node\Identifier|Name|Node\ComplexType|null + * @param T $node + * @return T + */ + private function resolveType(?Node $node): ?Node { + if ($node instanceof Name) { + return $this->resolveClassName($node); + } + if ($node instanceof Node\NullableType) { + $node->type = $this->resolveType($node->type); + return $node; + } + if ($node instanceof Node\UnionType || $node instanceof Node\IntersectionType) { + foreach ($node->types as &$type) { + $type = $this->resolveType($type); + } + return $node; + } + return $node; + } + + /** + * Resolve name, according to name resolver options. + * + * @param Name $name Function or constant name to resolve + * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* + * + * @return Name Resolved name, or original name with attribute + */ + protected function resolveName(Name $name, int $type): Name { + if (!$this->replaceNodes) { + $resolvedName = $this->nameContext->getResolvedName($name, $type); + if (null !== $resolvedName) { + $name->setAttribute('resolvedName', $resolvedName); + } else { + $name->setAttribute('namespacedName', FullyQualified::concat( + $this->nameContext->getNamespace(), $name, $name->getAttributes())); + } + return $name; + } + + if ($this->preserveOriginalNames) { + // Save the original name + $originalName = $name; + $name = clone $originalName; + $name->setAttribute('originalName', $originalName); + } + + $resolvedName = $this->nameContext->getResolvedName($name, $type); + if (null !== $resolvedName) { + return $resolvedName; + } + + // unqualified names inside a namespace cannot be resolved at compile-time + // add the namespaced version of the name as an attribute + $name->setAttribute('namespacedName', FullyQualified::concat( + $this->nameContext->getNamespace(), $name, $name->getAttributes())); + return $name; + } + + protected function resolveClassName(Name $name): Name { + return $this->resolveName($name, Stmt\Use_::TYPE_NORMAL); + } + + protected function addNamespacedName(Node $node): void { + $node->namespacedName = Name::concat( + $this->nameContext->getNamespace(), (string) $node->name); + } + + protected function resolveAttrGroups(Node $node): void { + foreach ($node->attrGroups as $attrGroup) { + foreach ($attrGroup->attrs as $attr) { + $attr->name = $this->resolveClassName($attr->name); + } + } + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NodeConnectingVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NodeConnectingVisitor.php new file mode 100644 index 0000000..38fedfd --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NodeConnectingVisitor.php @@ -0,0 +1,51 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\Node; +use PhpParser\NodeVisitorAbstract; + +/** + * Visitor that connects a child node to its parent node + * as well as its sibling nodes. + * + * On the child node, the parent node can be accessed through + * <code>$node->getAttribute('parent')</code>, the previous + * node can be accessed through <code>$node->getAttribute('previous')</code>, + * and the next node can be accessed through <code>$node->getAttribute('next')</code>. + */ +final class NodeConnectingVisitor extends NodeVisitorAbstract { + /** + * @var Node[] + */ + private array $stack = []; + + /** + * @var ?Node + */ + private $previous; + + public function beforeTraverse(array $nodes) { + $this->stack = []; + $this->previous = null; + } + + public function enterNode(Node $node) { + if (!empty($this->stack)) { + $node->setAttribute('parent', $this->stack[count($this->stack) - 1]); + } + + if ($this->previous !== null && $this->previous->getAttribute('parent') === $node->getAttribute('parent')) { + $node->setAttribute('previous', $this->previous); + $this->previous->setAttribute('next', $node); + } + + $this->stack[] = $node; + } + + public function leaveNode(Node $node) { + $this->previous = $node; + + array_pop($this->stack); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/ParentConnectingVisitor.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/ParentConnectingVisitor.php new file mode 100644 index 0000000..1e7e9e8 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/ParentConnectingVisitor.php @@ -0,0 +1,38 @@ +<?php declare(strict_types=1); + +namespace PhpParser\NodeVisitor; + +use PhpParser\Node; +use PhpParser\NodeVisitorAbstract; + +use function array_pop; +use function count; + +/** + * Visitor that connects a child node to its parent node. + * + * On the child node, the parent node can be accessed through + * <code>$node->getAttribute('parent')</code>. + */ +final class ParentConnectingVisitor extends NodeVisitorAbstract { + /** + * @var Node[] + */ + private array $stack = []; + + public function beforeTraverse(array $nodes) { + $this->stack = []; + } + + public function enterNode(Node $node) { + if (!empty($this->stack)) { + $node->setAttribute('parent', $this->stack[count($this->stack) - 1]); + } + + $this->stack[] = $node; + } + + public function leaveNode(Node $node) { + array_pop($this->stack); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitorAbstract.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitorAbstract.php new file mode 100644 index 0000000..6fb15cc --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/NodeVisitorAbstract.php @@ -0,0 +1,24 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +/** + * @codeCoverageIgnore + */ +abstract class NodeVisitorAbstract implements NodeVisitor { + public function beforeTraverse(array $nodes) { + return null; + } + + public function enterNode(Node $node) { + return null; + } + + public function leaveNode(Node $node) { + return null; + } + + public function afterTraverse(array $nodes) { + return null; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser.php new file mode 100644 index 0000000..68954af --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser.php @@ -0,0 +1,24 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +interface Parser { + /** + * Parses PHP code into a node tree. + * + * @param string $code The source code to parse + * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults + * to ErrorHandler\Throwing. + * + * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and + * the parser was unable to recover from an error). + */ + public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array; + + /** + * Return tokens for the last parse. + * + * @return Token[] + */ + public function getTokens(): array; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser/Php7.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser/Php7.php new file mode 100644 index 0000000..8015935 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser/Php7.php @@ -0,0 +1,2699 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Parser; + +use PhpParser\Error; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar; +use PhpParser\Node\Stmt; + +/* This is an automatically GENERATED file, which should not be manually edited. + * Instead edit one of the following: + * * the grammar file grammar/php.y + * * the skeleton file grammar/parser.template + * * the preprocessing script grammar/rebuildParsers.php + */ +class Php7 extends \PhpParser\ParserAbstract +{ + public const YYERRTOK = 256; + public const T_THROW = 257; + public const T_INCLUDE = 258; + public const T_INCLUDE_ONCE = 259; + public const T_EVAL = 260; + public const T_REQUIRE = 261; + public const T_REQUIRE_ONCE = 262; + public const T_LOGICAL_OR = 263; + public const T_LOGICAL_XOR = 264; + public const T_LOGICAL_AND = 265; + public const T_PRINT = 266; + public const T_YIELD = 267; + public const T_DOUBLE_ARROW = 268; + public const T_YIELD_FROM = 269; + public const T_PLUS_EQUAL = 270; + public const T_MINUS_EQUAL = 271; + public const T_MUL_EQUAL = 272; + public const T_DIV_EQUAL = 273; + public const T_CONCAT_EQUAL = 274; + public const T_MOD_EQUAL = 275; + public const T_AND_EQUAL = 276; + public const T_OR_EQUAL = 277; + public const T_XOR_EQUAL = 278; + public const T_SL_EQUAL = 279; + public const T_SR_EQUAL = 280; + public const T_POW_EQUAL = 281; + public const T_COALESCE_EQUAL = 282; + public const T_COALESCE = 283; + public const T_BOOLEAN_OR = 284; + public const T_BOOLEAN_AND = 285; + public const T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG = 286; + public const T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG = 287; + public const T_IS_EQUAL = 288; + public const T_IS_NOT_EQUAL = 289; + public const T_IS_IDENTICAL = 290; + public const T_IS_NOT_IDENTICAL = 291; + public const T_SPACESHIP = 292; + public const T_IS_SMALLER_OR_EQUAL = 293; + public const T_IS_GREATER_OR_EQUAL = 294; + public const T_SL = 295; + public const T_SR = 296; + public const T_INSTANCEOF = 297; + public const T_INC = 298; + public const T_DEC = 299; + public const T_INT_CAST = 300; + public const T_DOUBLE_CAST = 301; + public const T_STRING_CAST = 302; + public const T_ARRAY_CAST = 303; + public const T_OBJECT_CAST = 304; + public const T_BOOL_CAST = 305; + public const T_UNSET_CAST = 306; + public const T_POW = 307; + public const T_NEW = 308; + public const T_CLONE = 309; + public const T_EXIT = 310; + public const T_IF = 311; + public const T_ELSEIF = 312; + public const T_ELSE = 313; + public const T_ENDIF = 314; + public const T_LNUMBER = 315; + public const T_DNUMBER = 316; + public const T_STRING = 317; + public const T_STRING_VARNAME = 318; + public const T_VARIABLE = 319; + public const T_NUM_STRING = 320; + public const T_INLINE_HTML = 321; + public const T_ENCAPSED_AND_WHITESPACE = 322; + public const T_CONSTANT_ENCAPSED_STRING = 323; + public const T_ECHO = 324; + public const T_DO = 325; + public const T_WHILE = 326; + public const T_ENDWHILE = 327; + public const T_FOR = 328; + public const T_ENDFOR = 329; + public const T_FOREACH = 330; + public const T_ENDFOREACH = 331; + public const T_DECLARE = 332; + public const T_ENDDECLARE = 333; + public const T_AS = 334; + public const T_SWITCH = 335; + public const T_MATCH = 336; + public const T_ENDSWITCH = 337; + public const T_CASE = 338; + public const T_DEFAULT = 339; + public const T_BREAK = 340; + public const T_CONTINUE = 341; + public const T_GOTO = 342; + public const T_FUNCTION = 343; + public const T_FN = 344; + public const T_CONST = 345; + public const T_RETURN = 346; + public const T_TRY = 347; + public const T_CATCH = 348; + public const T_FINALLY = 349; + public const T_USE = 350; + public const T_INSTEADOF = 351; + public const T_GLOBAL = 352; + public const T_STATIC = 353; + public const T_ABSTRACT = 354; + public const T_FINAL = 355; + public const T_PRIVATE = 356; + public const T_PROTECTED = 357; + public const T_PUBLIC = 358; + public const T_READONLY = 359; + public const T_VAR = 360; + public const T_UNSET = 361; + public const T_ISSET = 362; + public const T_EMPTY = 363; + public const T_HALT_COMPILER = 364; + public const T_CLASS = 365; + public const T_TRAIT = 366; + public const T_INTERFACE = 367; + public const T_ENUM = 368; + public const T_EXTENDS = 369; + public const T_IMPLEMENTS = 370; + public const T_OBJECT_OPERATOR = 371; + public const T_NULLSAFE_OBJECT_OPERATOR = 372; + public const T_LIST = 373; + public const T_ARRAY = 374; + public const T_CALLABLE = 375; + public const T_CLASS_C = 376; + public const T_TRAIT_C = 377; + public const T_METHOD_C = 378; + public const T_FUNC_C = 379; + public const T_LINE = 380; + public const T_FILE = 381; + public const T_START_HEREDOC = 382; + public const T_END_HEREDOC = 383; + public const T_DOLLAR_OPEN_CURLY_BRACES = 384; + public const T_CURLY_OPEN = 385; + public const T_PAAMAYIM_NEKUDOTAYIM = 386; + public const T_NAMESPACE = 387; + public const T_NS_C = 388; + public const T_DIR = 389; + public const T_NS_SEPARATOR = 390; + public const T_ELLIPSIS = 391; + public const T_NAME_FULLY_QUALIFIED = 392; + public const T_NAME_QUALIFIED = 393; + public const T_NAME_RELATIVE = 394; + public const T_ATTRIBUTE = 395; + + protected int $tokenToSymbolMapSize = 396; + protected int $actionTableSize = 1258; + protected int $gotoTableSize = 567; + + protected int $invalidSymbol = 168; + protected int $errorSymbol = 1; + protected int $defaultAction = -32766; + protected int $unexpectedTokenRule = 32767; + + protected int $YY2TBLSTATE = 435; + protected int $numNonLeafStates = 739; + + protected array $symbolToName = array( + "EOF", + "error", + "T_THROW", + "T_INCLUDE", + "T_INCLUDE_ONCE", + "T_EVAL", + "T_REQUIRE", + "T_REQUIRE_ONCE", + "','", + "T_LOGICAL_OR", + "T_LOGICAL_XOR", + "T_LOGICAL_AND", + "T_PRINT", + "T_YIELD", + "T_DOUBLE_ARROW", + "T_YIELD_FROM", + "'='", + "T_PLUS_EQUAL", + "T_MINUS_EQUAL", + "T_MUL_EQUAL", + "T_DIV_EQUAL", + "T_CONCAT_EQUAL", + "T_MOD_EQUAL", + "T_AND_EQUAL", + "T_OR_EQUAL", + "T_XOR_EQUAL", + "T_SL_EQUAL", + "T_SR_EQUAL", + "T_POW_EQUAL", + "T_COALESCE_EQUAL", + "'?'", + "':'", + "T_COALESCE", + "T_BOOLEAN_OR", + "T_BOOLEAN_AND", + "'|'", + "'^'", + "T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG", + "T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG", + "T_IS_EQUAL", + "T_IS_NOT_EQUAL", + "T_IS_IDENTICAL", + "T_IS_NOT_IDENTICAL", + "T_SPACESHIP", + "'<'", + "T_IS_SMALLER_OR_EQUAL", + "'>'", + "T_IS_GREATER_OR_EQUAL", + "T_SL", + "T_SR", + "'+'", + "'-'", + "'.'", + "'*'", + "'/'", + "'%'", + "'!'", + "T_INSTANCEOF", + "'~'", + "T_INC", + "T_DEC", + "T_INT_CAST", + "T_DOUBLE_CAST", + "T_STRING_CAST", + "T_ARRAY_CAST", + "T_OBJECT_CAST", + "T_BOOL_CAST", + "T_UNSET_CAST", + "'@'", + "T_POW", + "'['", + "T_NEW", + "T_CLONE", + "T_EXIT", + "T_IF", + "T_ELSEIF", + "T_ELSE", + "T_ENDIF", + "T_LNUMBER", + "T_DNUMBER", + "T_STRING", + "T_STRING_VARNAME", + "T_VARIABLE", + "T_NUM_STRING", + "T_INLINE_HTML", + "T_ENCAPSED_AND_WHITESPACE", + "T_CONSTANT_ENCAPSED_STRING", + "T_ECHO", + "T_DO", + "T_WHILE", + "T_ENDWHILE", + "T_FOR", + "T_ENDFOR", + "T_FOREACH", + "T_ENDFOREACH", + "T_DECLARE", + "T_ENDDECLARE", + "T_AS", + "T_SWITCH", + "T_MATCH", + "T_ENDSWITCH", + "T_CASE", + "T_DEFAULT", + "T_BREAK", + "T_CONTINUE", + "T_GOTO", + "T_FUNCTION", + "T_FN", + "T_CONST", + "T_RETURN", + "T_TRY", + "T_CATCH", + "T_FINALLY", + "T_USE", + "T_INSTEADOF", + "T_GLOBAL", + "T_STATIC", + "T_ABSTRACT", + "T_FINAL", + "T_PRIVATE", + "T_PROTECTED", + "T_PUBLIC", + "T_READONLY", + "T_VAR", + "T_UNSET", + "T_ISSET", + "T_EMPTY", + "T_HALT_COMPILER", + "T_CLASS", + "T_TRAIT", + "T_INTERFACE", + "T_ENUM", + "T_EXTENDS", + "T_IMPLEMENTS", + "T_OBJECT_OPERATOR", + "T_NULLSAFE_OBJECT_OPERATOR", + "T_LIST", + "T_ARRAY", + "T_CALLABLE", + "T_CLASS_C", + "T_TRAIT_C", + "T_METHOD_C", + "T_FUNC_C", + "T_LINE", + "T_FILE", + "T_START_HEREDOC", + "T_END_HEREDOC", + "T_DOLLAR_OPEN_CURLY_BRACES", + "T_CURLY_OPEN", + "T_PAAMAYIM_NEKUDOTAYIM", + "T_NAMESPACE", + "T_NS_C", + "T_DIR", + "T_NS_SEPARATOR", + "T_ELLIPSIS", + "T_NAME_FULLY_QUALIFIED", + "T_NAME_QUALIFIED", + "T_NAME_RELATIVE", + "T_ATTRIBUTE", + "';'", + "']'", + "'('", + "')'", + "'{'", + "'}'", + "'`'", + "'\"'", + "'$'" + ); + + protected array $tokenToSymbol = array( + 0, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 56, 166, 168, 167, 55, 168, 168, + 161, 162, 53, 50, 8, 51, 52, 54, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 31, 159, + 44, 16, 46, 30, 68, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 70, 168, 160, 36, 168, 165, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 163, 35, 164, 58, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 1, 2, 3, 4, + 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 32, 33, 34, 37, 38, 39, 40, + 41, 42, 43, 45, 47, 48, 49, 57, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 69, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, + 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, + 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, + 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, + 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, + 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, + 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, + 153, 154, 155, 156, 157, 158 + ); + + protected array $action = array( + 133, 134, 135, 582, 136, 137, 0, 751, 752, 753, + 138, 38,-32766,-32766,-32766, 151,-32766,-32766,-32766,-32767, + -32767,-32767,-32767, 102, 103, 104, 105, 106, 1112, 1113, + 1114, 1111, 1110, 1109, 1115, 745, 744,-32766,-32766,-32766, + -32766,-32766,-32766,-32766,-32766,-32766,-32767,-32767,-32767,-32767, + -32767, 1245, 837,-32766, 1322, 754,-32766,-32766,-32766,-32766, + -594,-32766,-32766,-32766, 104, 105, 106, -594, 1306, 265, + 139, 404, 758, 759, 760, 761, 990,-32766, 429,-32766, + -32766, -16,-32766, 242, 1027, 815, 762, 763, 764, 765, + 766, 767, 768, 769, 770, 771, 791, 583, 792, 793, + 794, 795, 783, 784, 345, 346, 786, 787, 772, 773, + 774, 776, 777, 778, 356, 818, 819, 820, 821, 822, + 584, 779, 780, 585, 586,-32766, 803, 801, 802, 814, + 798, 799, 835, 826, 587, 588, 797, 589, 590, 591, + 592, 593, 594, 826, 459, 460, 461, 1036, 800, 595, + 596, 941, 140, 2, 133, 134, 135, 582, 136, 137, + 1060, 751, 752, 753, 138, 38, -328, -110, -110, 1326, + 290, 23, -110,-32766,-32766,-32766, 1325, 35, -110, 1112, + 1113, 1114, 1111, 1110, 1109, 1115, 612,-32766, 129, 745, + 744, 107, 108, 109,-32766, 274,-32766,-32766,-32766,-32766, + -32766,-32766,-32766, 828, 991, -194, 145, 110, 298, 754, + 836, 75,-32766,-32766,-32766, 1351, 142, 326, 1352, -594, + 326, -594, 254, 265, 139, 404, 758, 759, 760, 761, + 82, -272, 429,-32766, 326,-32766,-32766,-32766,-32766, 815, + 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, + 791, 583, 792, 793, 794, 795, 783, 784, 345, 346, + 786, 787, 772, 773, 774, 776, 777, 778, 356, 818, + 819, 820, 821, 822, 584, 779, 780, 585, 586, 830, + 803, 801, 802, 814, 798, 799, 712, 309, 587, 588, + 797, 589, 590, 591, 592, 593, 594, -78, 83, 84, + 85, -85, 800, 595, 596, 311, 149, 775, 746, 747, + 748, 749, 750, 725, 751, 752, 753, 788, 789, 37, + -328, 86, 87, 88, 89, 90, 91, 92, 93, 94, + 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 323, 274, 482,-32766,-32766, + -32766, -58,-32766,-32766,-32766, 959, 960, 127, 110, -194, + 961, 339, 754,-32766,-32766,-32766, 955, -85, 291,-32766, + 1088,-32766,-32766,-32766,-32766,-32766, 755, 756, 757, 758, + 759, 760, 761, -193,-32766, 824,-32766,-32766,-32766, -367, + 429, -367, 815, 762, 763, 764, 765, 766, 767, 768, + 769, 770, 771, 791, 813, 792, 793, 794, 795, 783, + 784, 785, 812, 786, 787, 772, 773, 774, 776, 777, + 778, 817, 818, 819, 820, 821, 822, 823, 779, 780, + 781, 782, -548, 803, 801, 802, 814, 798, 799, 340, + 327, 790, 796, 797, 804, 805, 807, 806, 808, 809, + 1033, 391, 606, 7,-32766, 800, 811, 810, 50, 51, + 52, 513, 53, 54, 831, 1240, 1239, 1241, 55, 56, + -110, 57, 1036, 920, 1090, -110, 1036, -110, 291, 483, + 745, 744, 305, 382, 381, -110, -110, -110, -110, -110, + -110, -110, -110, 423, 920, 283, -548, -548, 152, 290, + 380, 381, 1245, 715, 467, 468, 58, 59, 370, 21, + 423, -545, 60, 556, 61, 248, 249, 62, 63, 64, + 65, 66, 67, 68, 69, -548, 28, 267, 70, 445, + 514, 1104, 374, -342, 1272, 1273, 515, -193, 835, 154, + 832, -544, 1270, 42, 25, 516, 389, 517, 241, 518, + 920, 519, 298, 1238, 520, 521, 910, 920, 441, 44, + 45, 446, 377, 376,-32766, 46, 522, 1023, 1022, 1021, + 1024, 368, 338, 442, 1278, -545, -545, 910, 1231, 443, + 524, 525, 526, 835, 1245, 835, 1036, 716, 1341, 1236, + -545, 155, 528, 529,-32766, 1259, 1260, 1261, 1262, 1256, + 1257, 297, -551, 943, -545, -544, -544, 1263, 1258, 290, + 1035, 1240, 1239, 1241, 298, 444, 1036, 71, 1266, 841, + -544, 321, 322, 326, -153, -153, -153, 920, 1240, 1239, + 1241, 922, -550, 910, -544, 710, 943, -591,-32766, -153, + 910, -153, 357, -153, -591, -153, 862, 1033, 863, 1089, + 36, 251, 922, 737, 156, 375, 710, 717, 862, -585, + 863, -585, 75, 158, -546, 835, 959, 960, 326, 1036, + -57, 523, 920,-32766,-32766, 362, 896, 955, -110, -110, + -110, 32, 111, 112, 113, 114, 115, 116, 117, 118, + 119, 120, 121, 122, 123, 745, 744, 656, 26, 835, + -110, -110, 720, 745, 744, -110, 33, 834, 922, 124, + 910, -110, 710, -153, 125, 922, 675, 676, 130, 710, + -32766, 150, 407, 131, 1150, 1152, 48, 144, -546, -546, + 378, 379,-32766, 383, 384, -543, 28, 159, 1238, 920, + 160, 298, 1059, -546, 75,-32766,-32766,-32766, 835,-32766, + 326,-32766, 1270,-32766, -87, 910,-32766, -546, 647, 648, + 161,-32766,-32766,-32766, -4, 920, -84,-32766,-32766, 727, + 162, 287, 163,-32766, 420, -302, -78, -73, -72, -71, + 141, 287,-32766, -70, 326, 976, 745, 744, 1231, 710, + 299, 300, -69, -68, -67, -298, -591, -66, -591, -543, + -543, -65, 528, 529, -46, 1259, 1260, 1261, 1262, 1256, + 1257, -18, 74, 148, -543, 273, 284, 1263, 1258, 126, + -543, 726, 910,-32766, 729, 919, 147, 73, -543, 1238, + 922, 690, 322, 326, 710, 279,-32766,-32766,-32766, 280, + -32766, 285,-32766, 286,-32766, 332, 288,-32766, 910, 289, + 292, 49,-32766,-32766,-32766, 293, 274, 1033,-32766,-32766, + 937, 110, -50, 685,-32766, 420, 146, 691, 826, 701, + 375, 703, 436,-32766, 1353, 20, 561, 296, 645, 1036, + 835, 959, 960, 1119, -543, -543, 523,-32766, 692, 693, + 306, 527, 955, -110, -110, -110, 132, 922, 834, -543, + 464, 710, 283, 662, 657,-32766, 1240, 1239, 1241, 678, + 304, 1238, 283, -543, 10, 301, 302, 493,-32766,-32766, + -32766, 663,-32766, 922,-32766, 679,-32766, 710, -4,-32766, + 373, 40, -508, 956,-32766,-32766,-32766, -275, 731,-32766, + -32766,-32766, 920, 303, 128, 1238,-32766, 420, 310, 0, + 567, 0,-32766,-32766,-32766,-32766,-32766, 0,-32766, 0, + -32766,-32766, 0,-32766, 0, 1277, -498, 0,-32766,-32766, + -32766,-32766, 1279, 0,-32766,-32766, 8, 1238, 24, 372, + -32766, 420, 920, 1267,-32766,-32766,-32766, 610,-32766,-32766, + -32766, 939,-32766, 298, -579,-32766, 846, 41, 734, 488, + -32766,-32766,-32766,-32766, 735, 854,-32766,-32766, 901, 1238, + 574, 1000,-32766, 420, 977, 984,-32766,-32766,-32766, 974, + -32766,-32766,-32766, 985,-32766, 910, 899,-32766, 972, 1093, + 1096, 1097,-32766,-32766,-32766, 1094, 1095, 1101,-32766,-32766, + 1292, -250, -250, -250,-32766, 420, 1310, 375, 1344, 650, + 28, 267, -578,-32766, -577, -551, -550, -549, 959, 960, + -492, 1, 835, 523, 29, 910, 1270, 30, 896, 955, + -110, -110, -110, 39, 43, 47, 72, 76, 77, 78, + 79, -249, -249, -249, 80, 81, 143, 375, 153, 157, + 897, 247, 328, 357, 358, 359, 360, 361, 959, 960, + 922, 362, 1231, 523, 710, -250, 363, 364, 896, 955, + -110, -110, -110, 365, 366, 367, 369, 529, 28, 1259, + 1260, 1261, 1262, 1256, 1257, 437, 555, 1348, -273, -272, + 835, 1263, 1258, 13, 1270, 14,-32766, 15, 16, 18, + 922, 73, 1238, 1350, 710, -249, 322, 326, 406,-32766, + -32766,-32766, 484,-32766, 485,-32766, 492,-32766, 495, 496, + -32766, 497, 498, 502, 503,-32766,-32766,-32766, 504, 511, + 1231,-32766,-32766, 572, 696, 1249, 1190,-32766, 420, 1268, + 1062, 1061, 1042, 1226, 1038, 529,-32766, 1259, 1260, 1261, + 1262, 1256, 1257, -277, -102, 12, 17, 27, 295, 1263, + 1258, 405, 603, 607, 636, 702, 1194, 1244, 1191, 73, + 34, 1323, 0, 320, 322, 326, 371, 711, 714, 718, + 719, 721, 722, 723, 724, 0, 728, 713, 0, 857, + 856, 865, 949, 992, 864, 1349, 948, 946, 947, 950, + 1222, 930, 940, 928, 982, 983, 634, 1347, 1304, 1293, + 1311, 1320, 0, 1207, 0, 1271, 0, 326 + ); + + protected array $actionCheck = array( + 2, 3, 4, 5, 6, 7, 0, 9, 10, 11, + 12, 13, 9, 10, 11, 14, 9, 10, 11, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 116, 117, + 118, 119, 120, 121, 122, 37, 38, 30, 116, 32, + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 1, 1, 9, 1, 57, 9, 10, 11, 137, + 1, 9, 10, 11, 50, 51, 52, 8, 1, 71, + 72, 73, 74, 75, 76, 77, 31, 30, 80, 32, + 33, 31, 30, 14, 1, 87, 88, 89, 90, 91, + 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, + 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, + 122, 123, 124, 125, 126, 116, 128, 129, 130, 131, + 132, 133, 82, 80, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 80, 129, 130, 131, 138, 150, 151, + 152, 1, 154, 8, 2, 3, 4, 5, 6, 7, + 162, 9, 10, 11, 12, 13, 8, 117, 118, 1, + 161, 8, 122, 9, 10, 11, 8, 8, 128, 116, + 117, 118, 119, 120, 121, 122, 51, 137, 8, 37, + 38, 53, 54, 55, 30, 57, 32, 33, 34, 35, + 36, 37, 38, 80, 159, 8, 8, 69, 158, 57, + 159, 161, 9, 10, 11, 80, 163, 167, 83, 160, + 167, 162, 8, 71, 72, 73, 74, 75, 76, 77, + 163, 162, 80, 30, 167, 32, 33, 34, 35, 87, + 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, + 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 156, + 128, 129, 130, 131, 132, 133, 163, 8, 136, 137, + 138, 139, 140, 141, 142, 143, 144, 16, 9, 10, + 11, 31, 150, 151, 152, 8, 154, 2, 3, 4, + 5, 6, 7, 163, 9, 10, 11, 12, 13, 30, + 162, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, 54, 55, 8, 57, 31, 9, 10, + 11, 16, 9, 10, 11, 117, 118, 14, 69, 162, + 122, 8, 57, 9, 10, 11, 128, 97, 30, 30, + 1, 32, 33, 34, 35, 36, 71, 72, 73, 74, + 75, 76, 77, 8, 30, 80, 32, 33, 34, 106, + 80, 108, 87, 88, 89, 90, 91, 92, 93, 94, + 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, + 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, + 125, 126, 70, 128, 129, 130, 131, 132, 133, 8, + 70, 136, 137, 138, 139, 140, 141, 142, 143, 144, + 116, 106, 1, 108, 116, 150, 151, 152, 2, 3, + 4, 5, 6, 7, 80, 155, 156, 157, 12, 13, + 101, 15, 138, 1, 164, 106, 138, 108, 30, 163, + 37, 38, 113, 106, 107, 116, 117, 118, 119, 120, + 121, 122, 123, 116, 1, 161, 134, 135, 14, 161, + 106, 107, 1, 31, 134, 135, 50, 51, 8, 101, + 116, 70, 56, 85, 58, 59, 60, 61, 62, 63, + 64, 65, 66, 67, 68, 163, 70, 71, 72, 73, + 74, 123, 8, 164, 78, 79, 80, 162, 82, 14, + 156, 70, 86, 87, 88, 89, 8, 91, 97, 93, + 1, 95, 158, 80, 98, 99, 84, 1, 8, 103, + 104, 105, 106, 107, 116, 109, 110, 119, 120, 121, + 122, 115, 116, 8, 146, 134, 135, 84, 122, 8, + 124, 125, 126, 82, 1, 82, 138, 31, 85, 116, + 149, 14, 136, 137, 116, 139, 140, 141, 142, 143, + 144, 145, 161, 122, 163, 134, 135, 151, 152, 161, + 137, 155, 156, 157, 158, 8, 138, 161, 1, 8, + 149, 165, 166, 167, 75, 76, 77, 1, 155, 156, + 157, 159, 161, 84, 163, 163, 122, 1, 137, 90, + 84, 92, 161, 94, 8, 96, 106, 116, 108, 159, + 147, 148, 159, 163, 14, 106, 163, 31, 106, 160, + 108, 162, 161, 14, 70, 82, 117, 118, 167, 138, + 16, 122, 1, 9, 10, 161, 127, 128, 129, 130, + 131, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 37, 38, 75, 76, 82, + 117, 118, 31, 37, 38, 122, 14, 155, 159, 16, + 84, 128, 163, 164, 16, 159, 75, 76, 16, 163, + 137, 101, 102, 16, 59, 60, 70, 16, 134, 135, + 106, 107, 74, 106, 107, 70, 70, 16, 80, 1, + 16, 158, 1, 149, 161, 87, 88, 89, 82, 91, + 167, 93, 86, 95, 31, 84, 98, 163, 111, 112, + 16, 103, 104, 105, 0, 1, 31, 109, 110, 31, + 16, 30, 16, 115, 116, 35, 31, 31, 31, 31, + 163, 30, 124, 31, 167, 159, 37, 38, 122, 163, + 134, 135, 31, 31, 31, 35, 160, 31, 162, 134, + 135, 31, 136, 137, 31, 139, 140, 141, 142, 143, + 144, 31, 154, 31, 149, 31, 31, 151, 152, 163, + 70, 31, 84, 74, 31, 31, 31, 161, 163, 80, + 159, 80, 166, 167, 163, 35, 87, 88, 89, 35, + 91, 35, 93, 35, 95, 35, 37, 98, 84, 37, + 37, 70, 103, 104, 105, 37, 57, 116, 109, 110, + 38, 69, 31, 77, 115, 116, 70, 116, 80, 80, + 106, 92, 108, 124, 83, 97, 89, 113, 113, 138, + 82, 117, 118, 82, 134, 135, 122, 85, 137, 138, + 114, 127, 128, 129, 130, 131, 31, 159, 155, 149, + 97, 163, 161, 96, 90, 74, 155, 156, 157, 94, + 133, 80, 161, 163, 150, 134, 135, 97, 87, 88, + 89, 100, 91, 159, 93, 100, 95, 163, 164, 98, + 149, 159, 149, 128, 103, 104, 105, 162, 164, 74, + 109, 110, 1, 132, 163, 80, 115, 116, 132, -1, + 153, -1, 87, 88, 89, 124, 91, -1, 93, -1, + 95, 137, -1, 98, -1, 146, 149, -1, 103, 104, + 105, 74, 146, -1, 109, 110, 149, 80, 149, 149, + 115, 116, 1, 160, 87, 88, 89, 153, 91, 124, + 93, 154, 95, 158, 161, 98, 160, 159, 159, 102, + 103, 104, 105, 74, 159, 159, 109, 110, 159, 80, + 81, 159, 115, 116, 159, 159, 87, 88, 89, 159, + 91, 124, 93, 159, 95, 84, 159, 98, 159, 159, + 159, 159, 103, 104, 105, 159, 159, 159, 109, 110, + 160, 100, 101, 102, 115, 116, 160, 106, 160, 160, + 70, 71, 161, 124, 161, 161, 161, 161, 117, 118, + 161, 161, 82, 122, 161, 84, 86, 161, 127, 128, + 129, 130, 131, 161, 161, 161, 161, 161, 161, 161, + 161, 100, 101, 102, 161, 161, 161, 106, 161, 161, + 164, 161, 161, 161, 161, 161, 161, 161, 117, 118, + 159, 161, 122, 122, 163, 164, 161, 161, 127, 128, + 129, 130, 131, 161, 161, 161, 161, 137, 70, 139, + 140, 141, 142, 143, 144, 161, 161, 164, 162, 162, + 82, 151, 152, 162, 86, 162, 74, 162, 162, 162, + 159, 161, 80, 164, 163, 164, 166, 167, 162, 87, + 88, 89, 162, 91, 162, 93, 162, 95, 162, 162, + 98, 162, 162, 162, 162, 103, 104, 105, 162, 162, + 122, 109, 110, 162, 162, 162, 162, 115, 116, 162, + 162, 162, 162, 162, 162, 137, 124, 139, 140, 141, + 142, 143, 144, 162, 162, 162, 162, 162, 162, 151, + 152, 162, 162, 162, 162, 162, 162, 162, 162, 161, + 163, 162, -1, 163, 166, 167, 163, 163, 163, 163, + 163, 163, 163, 163, 163, -1, 163, 163, -1, 164, + 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, + 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, + 164, 164, -1, 165, -1, 166, -1, 167 + ); + + protected array $actionBase = array( + 0, -2, 152, 549, 764, 941, 981, 751, 617, 310, + 123, 877, 556, 671, 671, 738, 671, 472, 626, 789, + 63, 305, 305, 789, 305, 493, 493, 493, 658, 658, + 658, 658, 749, 749, 897, 897, 929, 865, 831, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 51, 45, 451, 692, 1036, 1044, + 1040, 1045, 1034, 1033, 1039, 1041, 1046, 1083, 1084, 795, + 1085, 1086, 1082, 1087, 1042, 889, 1035, 1043, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 44, 343, 664, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 52, 52, + 52, 666, 666, 47, 354, 980, 203, 1048, 1048, 1048, + 1048, 1048, 1048, 1048, 1048, 1048, 665, 339, 164, 164, + 7, 7, 7, 7, 7, 50, 369, 583, -25, -25, + -25, -25, 448, 741, 501, 408, 283, 338, 394, 334, + 334, 14, 14, 531, 531, 9, 9, 531, 531, 531, + 478, 478, 478, 478, 441, 471, 552, 428, 824, 53, + 53, 53, 53, 824, 824, 824, 824, 826, 1089, 824, + 824, 824, 594, 750, 750, 781, 138, 138, 138, 750, + 540, 503, 503, 540, 238, 503, 67, 135, -78, 805, + 377, 499, -78, 362, 656, 636, 59, 743, 624, 743, + 1032, 481, 802, 802, 514, 773, 746, 878, 1064, 1049, + 821, 1080, 825, 1081, 15, 370, 745, 1031, 1031, 1031, + 1031, 1031, 1031, 1031, 1031, 1031, 1031, 1031, 1090, 443, + 1032, 384, 1090, 1090, 1090, 443, 443, 443, 443, 443, + 443, 443, 443, 443, 443, 647, 384, 622, 641, 384, + 810, 443, 51, 817, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 780, 316, 51, 45, 150, 150, + 490, 83, 150, 150, 150, 150, 51, 51, 51, 51, + 624, 799, 797, 627, 834, 375, 799, 799, 799, 270, + 158, 69, 197, 740, 760, 345, 788, 788, 801, 900, + 900, 788, 798, 788, 801, 914, 788, 788, 900, 900, + 835, 180, 550, 353, 524, 565, 900, 279, 788, 788, + 788, 788, 816, 571, 788, 214, 198, 788, 788, 816, + 811, 785, 145, 777, 900, 900, 900, 816, 500, 777, + 777, 777, 839, 845, 765, 784, 337, 297, 611, 169, + 822, 784, 784, 788, 538, 765, 784, 765, 784, 837, + 784, 784, 784, 765, 784, 798, 431, 784, 721, 607, + 163, 784, 6, 915, 916, 723, 917, 912, 918, 964, + 919, 923, 1054, 899, 930, 913, 924, 965, 906, 903, + 794, 693, 698, 827, 783, 896, 792, 792, 792, 894, + 792, 792, 792, 792, 792, 792, 792, 792, 693, 823, + 830, 787, 933, 702, 707, 1011, 819, 926, 1088, 932, + 1013, 925, 772, 711, 977, 934, 774, 1050, 935, 936, + 986, 1014, 846, 1017, 963, 796, 979, 1065, 836, 945, + 1055, 792, 915, 923, 735, 913, 924, 906, 903, 770, + 766, 762, 763, 761, 752, 747, 748, 782, 1018, 893, + 833, 880, 940, 895, 693, 886, 971, 1047, 990, 992, + 1053, 803, 791, 888, 1066, 946, 952, 953, 1056, 1019, + 1057, 838, 973, 775, 994, 820, 1067, 996, 997, 999, + 1000, 1058, 1068, 1059, 891, 1060, 849, 814, 966, 807, + 1069, 1, 806, 808, 818, 955, 484, 931, 1061, 1070, + 1071, 1001, 1002, 1006, 1072, 1073, 927, 852, 975, 815, + 976, 967, 855, 856, 525, 813, 1020, 800, 804, 812, + 577, 640, 1074, 1075, 1076, 928, 790, 786, 860, 864, + 1021, 809, 1022, 1077, 649, 867, 724, 1078, 1012, 744, + 754, 281, 654, 335, 756, 779, 1063, 829, 776, 778, + 954, 754, 793, 869, 1079, 870, 871, 872, 1007, 876, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 456, 456, 456, 456, 456, 456, 305, 305, 305, 305, + 305, 456, 456, 456, 456, 456, 456, 456, 305, 305, + 0, 0, 305, 0, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 473, 473, 289, 289, 473, 289, 473, 473, 473, 473, + 473, 473, 473, 473, 473, 0, 289, 289, 289, 289, + 289, 289, 289, 289, 473, 835, 473, 138, 138, 138, + 138, 473, 473, 473, -88, -88, 473, 238, 473, 473, + 138, 138, 473, 473, 473, 473, 473, 473, 473, 473, + 473, 473, 473, 0, 0, 384, 503, 473, 798, 798, + 798, 798, 473, 473, 473, 473, 503, 503, 473, 473, + 473, 0, 0, 0, 0, 0, 0, 0, 0, 384, + 0, 0, 384, 0, 0, 798, 798, 473, 238, 835, + 168, 473, 0, 0, 0, 0, 384, 798, 384, 443, + 788, 503, 503, 788, 443, 443, 150, 51, 168, 620, + 620, 620, 620, 0, 0, 624, 835, 835, 835, 835, + 835, 835, 835, 835, 835, 835, 835, 798, 0, 835, + 0, 798, 798, 798, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 798, + 0, 0, 900, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 914, 0, 0, 0, 0, 0, 0, + 798, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 792, 803, 0, 803, 0, 792, 792, 792, 0, 0, + 0, 0, 813, 809 + ); + + protected array $actionDefault = array( + 3,32767, 102,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767, 100,32767,32767,32767,32767, 597, 597, + 597, 597,32767,32767, 254, 102,32767,32767, 470, 387, + 387, 387,32767,32767, 541, 541, 541, 541, 541, 541, + 32767,32767,32767,32767,32767,32767, 470,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767, 100, + 32767,32767,32767, 36, 7, 8, 10, 11, 49, 17, + 324,32767,32767,32767,32767, 102,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767, 590,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767, 474, 453, + 454, 456, 457, 386, 542, 596, 327, 593, 385, 145, + 339, 329, 242, 330, 258, 475, 259, 476, 479, 480, + 215, 287, 382, 149, 150, 417, 471, 419, 469, 473, + 418, 392, 398, 399, 400, 401, 402, 403, 404, 405, + 406, 407, 408, 409, 410, 390, 391, 472, 450, 449, + 448,32767,32767, 415, 416,32767, 420,32767,32767,32767, + 32767,32767,32767,32767, 102,32767, 389, 423, 421, 422, + 439, 440, 437, 438, 441,32767,32767,32767, 442, 443, + 444, 445, 316,32767,32767, 366, 364, 316, 111,32767, + 32767, 430, 431,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767, 535, 447,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767, 102, + 32767, 100, 537, 412, 414, 504, 425, 426, 424, 393, + 32767, 511,32767, 102,32767, 513,32767,32767,32767,32767, + 32767,32767,32767, 536,32767, 543, 543,32767, 497, 100, + 195,32767,32767, 512,32767, 195, 195,32767,32767,32767, + 32767,32767,32767,32767,32767, 604, 497, 110, 110, 110, + 110, 110, 110, 110, 110, 110, 110, 110,32767, 195, + 110,32767,32767,32767, 100, 195, 195, 195, 195, 195, + 195, 195, 195, 195, 195, 190,32767, 268, 270, 102, + 558, 195,32767, 516,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767, 509,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 497, 435, 138,32767, 138, 543, 427, 428, 429, 499, + 543, 543, 543, 312, 289,32767,32767,32767,32767, 514, + 514, 100, 100, 100, 100, 509,32767,32767,32767,32767, + 111, 99, 99, 99, 99, 99, 103, 101,32767,32767, + 32767,32767, 223, 99,32767, 101, 101,32767,32767, 223, + 225, 212, 101, 227,32767, 562, 563, 223, 101, 227, + 227, 227, 247, 247, 486, 318, 101, 99, 101, 101, + 197, 318, 318,32767, 101, 486, 318, 486, 318, 199, + 318, 318, 318, 486, 318,32767, 101, 318, 214, 99, + 99, 318,32767,32767,32767, 499,32767,32767,32767,32767, + 32767,32767,32767, 222,32767,32767,32767,32767,32767,32767, + 32767,32767, 530,32767, 547, 560, 433, 434, 436, 545, + 458, 459, 460, 461, 462, 463, 464, 466, 592,32767, + 503,32767,32767,32767, 338,32767, 602,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767, 603,32767, 543,32767,32767,32767, + 32767, 432, 9, 74, 492, 42, 43, 51, 57, 520, + 521, 522, 523, 517, 518, 524, 519,32767,32767, 525, + 568,32767,32767, 544, 595,32767,32767,32767,32767,32767, + 32767, 138,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767, 530,32767, 136,32767,32767,32767,32767, + 32767,32767,32767,32767, 526,32767,32767,32767, 543,32767, + 32767,32767,32767, 314, 311,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767, 543,32767,32767,32767,32767,32767, 291,32767, 308, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767, 286,32767,32767, 381, + 499, 294, 296, 297,32767,32767,32767,32767, 360,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 152, 152, 3, 3, 341, 152, 152, 152, 341, 341, + 152, 341, 341, 341, 152, 152, 152, 152, 152, 152, + 280, 185, 262, 265, 247, 247, 152, 352, 152 + ); + + protected array $goto = array( + 196, 196, 1034, 1065, 697, 431, 661, 621, 658, 319, + 706, 425, 313, 314, 335, 576, 430, 336, 432, 638, + 654, 655, 852, 672, 673, 674, 853, 167, 167, 167, + 167, 221, 197, 193, 193, 177, 179, 216, 193, 193, + 193, 193, 193, 194, 194, 194, 194, 194, 194, 188, + 189, 190, 191, 192, 218, 216, 219, 536, 537, 421, + 538, 540, 541, 542, 543, 544, 545, 546, 547, 1136, + 168, 169, 170, 195, 171, 172, 173, 166, 174, 175, + 176, 178, 215, 217, 220, 238, 243, 244, 246, 257, + 258, 259, 260, 261, 262, 263, 264, 268, 269, 270, + 271, 281, 282, 316, 317, 318, 426, 427, 428, 581, + 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 180, 237, 181, 198, 199, + 200, 239, 188, 189, 190, 191, 192, 218, 1136, 201, + 182, 183, 184, 202, 198, 185, 240, 203, 201, 165, + 204, 205, 186, 206, 207, 208, 187, 209, 210, 211, + 212, 213, 214, 855, 466, 466, 278, 278, 278, 278, + 623, 623, 351, 466, 1269, 600, 1269, 1269, 1269, 1269, + 1269, 1269, 1269, 1269, 1269, 1287, 1287, 599, 1100, 1287, + 709, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, + 508, 700, 458, 1098, 975, 559, 552, 860, 419, 909, + 904, 905, 918, 861, 906, 858, 907, 908, 859, 848, + 827, 912, 354, 354, 354, 354, 396, 399, 560, 601, + 605, 1087, 1082, 1083, 1084, 341, 552, 559, 568, 569, + 344, 579, 602, 616, 617, 408, 409, 1232, 440, 479, + 670, 22, 671, 886, 412, 413, 414, 481, 684, 349, + 1237, 415, 1237, 1107, 1108, 347, 833, 1034, 1034, 1237, + 573, 848, 1034, 1327, 1034, 1034, 1040, 1039, 1034, 1034, + 1034, 1034, 1034, 1034, 1034, 1034, 1034, 1034, 1034, 1319, + 1319, 1319, 1319, 1237, 893, 851, 893, 893, 1237, 1237, + 1237, 1237, 1233, 1234, 1237, 1237, 1237, 833, 355, 833, + 843, 996, 252, 252, 1043, 1044, 1037, 1037, 355, 355, + 681, 952, 394, 926, 1029, 1045, 1046, 927, 1235, 1295, + 1296, 942, 355, 355, 942, 913, 355, 914, 1354, 250, + 250, 250, 250, 245, 253, 548, 548, 548, 548, 554, + 604, 1285, 1285, 355, 355, 1285, 571, 1285, 1285, 1285, + 1285, 1285, 1285, 1285, 1285, 1285, 539, 539, 342, 424, + 539, 611, 539, 539, 539, 539, 539, 539, 539, 539, + 539, 566, 476, 1312, 1313, 733, 637, 639, 325, 308, + 659, 848, 343, 342, 683, 687, 1010, 695, 704, 1006, + 660, 1298, 609, 624, 627, 628, 629, 630, 651, 652, + 653, 708, 1216, 944, 1314, 1315, 1217, 1220, 945, 1221, + 1337, 1337, 686, 352, 353, 868, 553, 563, 450, 450, + 450, 553, 1309, 563, 1309, 1133, 397, 462, 1337, 1058, + 880, 1309, 1185, 867, 500, 5, 501, 6, 469, 580, + 470, 471, 507, 554, 878, 1340, 1340, 1345, 1346, 433, + 438, 550, 666, 550, 433, 682, 1321, 1321, 1321, 1321, + 550, 337, 1041, 1041, 931, 1123, 873, 665, 1052, 1048, + 1049, 619, 845, 876, 324, 275, 324, 1015, 967, 410, + 705, 577, 614, 1305, 456, 872, 403, 664, 994, 969, + 969, 969, 969, 866, 870, 456, 963, 970, 881, 869, + 1070, 1074, 631, 633, 635, 1227, 1230, 958, 615, 978, + 450, 450, 450, 450, 450, 450, 450, 450, 450, 450, + 450, 999, 1018, 450, 971, 1073, 732, 477, 1228, 1307, + 1307, 1073, 736, 968, 551, 1008, 1003, 882, 694, 1075, + 1071, 829, 255, 255, 980, 0, 1118, 0, 1013, 1013, + 694, 0, 0, 0, 694, 1116, 885 + ); + + protected array $gotoCheck = array( + 42, 42, 73, 127, 73, 66, 66, 56, 56, 66, + 9, 66, 66, 66, 66, 66, 66, 66, 66, 66, + 86, 86, 26, 86, 86, 86, 27, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 15, 149, 149, 23, 23, 23, 23, + 108, 108, 97, 149, 108, 130, 108, 108, 108, 108, + 108, 108, 108, 108, 108, 170, 170, 8, 8, 170, + 8, 170, 170, 170, 170, 170, 170, 170, 170, 170, + 8, 8, 83, 8, 49, 76, 76, 15, 43, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 22, + 6, 15, 24, 24, 24, 24, 59, 59, 59, 59, + 59, 15, 15, 15, 15, 76, 76, 76, 76, 76, + 76, 76, 76, 76, 76, 82, 82, 20, 83, 84, + 82, 76, 82, 45, 82, 82, 82, 84, 82, 179, + 73, 82, 73, 144, 144, 82, 12, 73, 73, 73, + 172, 22, 73, 181, 73, 73, 118, 118, 73, 73, + 73, 73, 73, 73, 73, 73, 73, 73, 73, 9, + 9, 9, 9, 73, 25, 25, 25, 25, 73, 73, + 73, 73, 20, 20, 73, 73, 73, 12, 14, 12, + 20, 103, 5, 5, 119, 119, 89, 89, 14, 14, + 89, 89, 62, 73, 89, 89, 89, 73, 20, 20, + 20, 9, 14, 14, 9, 65, 14, 65, 14, 5, + 5, 5, 5, 5, 5, 107, 107, 107, 107, 14, + 107, 171, 171, 14, 14, 171, 104, 171, 171, 171, + 171, 171, 171, 171, 171, 171, 173, 173, 168, 13, + 173, 13, 173, 173, 173, 173, 173, 173, 173, 173, + 173, 48, 176, 176, 176, 48, 48, 48, 169, 169, + 48, 22, 168, 168, 48, 48, 48, 48, 48, 48, + 64, 14, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 79, 79, 178, 178, 79, 79, 79, 79, + 182, 182, 14, 97, 97, 35, 9, 9, 23, 23, + 23, 9, 130, 9, 130, 150, 9, 9, 182, 114, + 35, 130, 151, 35, 155, 46, 155, 46, 9, 9, + 9, 9, 155, 14, 9, 182, 182, 9, 9, 117, + 113, 19, 120, 19, 117, 116, 130, 130, 130, 130, + 19, 29, 117, 117, 17, 17, 39, 117, 117, 117, + 117, 17, 18, 9, 24, 24, 24, 17, 93, 93, + 93, 2, 2, 130, 19, 17, 28, 17, 17, 19, + 19, 19, 19, 17, 37, 19, 19, 19, 16, 16, + 16, 16, 85, 85, 85, 17, 14, 92, 80, 16, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 50, 110, 23, 50, 130, 50, 157, 160, 130, + 130, 130, 99, 16, 50, 50, 50, 41, 7, 132, + 129, 7, 5, 5, 96, -1, 147, -1, 107, 107, + 7, -1, -1, -1, 7, 16, 16 + ); + + protected array $gotoBase = array( + 0, 0, -221, 0, 0, 311, 200, 541, 179, -10, + 0, 0, -30, 32, 11, -185, 56, 9, 173, 196, + -146, 0, -59, 163, 219, 291, 18, 22, 159, 175, + 0, 0, 0, 0, 0, 54, 0, 165, 0, 153, + 0, 106, -1, 189, 0, 230, -291, 0, -330, 186, + 519, 0, 0, 0, 0, 0, -33, 0, 0, 181, + 0, 0, 280, 0, 158, 321, -236, 0, 0, 0, + 0, 0, 0, -5, 0, 0, -140, 0, 0, 4, + 174, 44, -246, -76, -220, 33, -698, 0, 0, 37, + 0, 0, 188, 184, 0, 0, 111, -311, 0, 135, + 0, 0, 0, 276, 313, 0, 0, 317, -71, 0, + 162, 0, 0, 183, 166, 0, 182, 187, -3, 29, + 172, 0, 0, 0, 0, 0, 0, 1, 0, 176, + 167, 0, 107, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, -12, 0, 0, 112, 0, 130, + 190, 168, 0, 0, 0, -51, 0, 97, 0, 0, + 169, 0, 0, 0, 0, 0, 0, 0, 71, 67, + -56, 110, 241, 125, 0, 0, 82, 0, 42, 229, + 0, 242, 113, 0, 0 + ); + + protected array $gotoDefault = array( + -32768, 512, 740, 4, 741, 935, 816, 825, 597, 530, + 707, 348, 625, 422, 1303, 911, 1122, 578, 844, 1246, + 1254, 457, 847, 330, 730, 923, 894, 895, 400, 386, + 392, 398, 649, 626, 494, 879, 453, 871, 486, 874, + 452, 883, 164, 418, 510, 887, 3, 890, 557, 921, + 973, 387, 898, 388, 677, 900, 562, 902, 903, 395, + 401, 402, 1127, 570, 622, 915, 256, 564, 916, 385, + 917, 925, 390, 393, 688, 465, 505, 499, 411, 1102, + 565, 608, 646, 447, 473, 620, 632, 618, 480, 434, + 416, 329, 957, 965, 487, 463, 979, 350, 987, 738, + 1135, 640, 489, 995, 641, 1002, 1005, 531, 532, 478, + 1017, 272, 1020, 490, 19, 667, 1031, 1032, 668, 642, + 1054, 643, 669, 644, 1056, 472, 598, 1064, 454, 1072, + 1291, 455, 1076, 266, 1079, 277, 417, 435, 1085, 1086, + 9, 1092, 698, 699, 11, 276, 509, 1117, 689, 451, + 1134, 439, 1204, 1206, 558, 491, 1224, 1223, 680, 506, + 1229, 448, 1294, 449, 533, 474, 315, 534, 1338, 307, + 333, 312, 549, 294, 334, 535, 475, 1300, 1308, 331, + 31, 1328, 1339, 575, 613 + ); + + protected array $ruleToNonTerminal = array( + 0, 1, 3, 3, 2, 5, 5, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, + 7, 7, 7, 7, 7, 8, 8, 9, 10, 11, + 11, 11, 12, 12, 13, 13, 14, 15, 15, 16, + 16, 17, 17, 18, 18, 21, 21, 22, 23, 23, + 24, 24, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 29, 29, 30, 30, 32, 34, 34, + 28, 36, 36, 33, 38, 38, 35, 35, 37, 37, + 39, 39, 31, 40, 40, 41, 43, 44, 44, 45, + 45, 46, 46, 48, 47, 47, 47, 47, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, + 49, 49, 25, 25, 50, 69, 69, 72, 72, 71, + 70, 70, 63, 75, 75, 76, 76, 77, 77, 78, + 78, 79, 79, 80, 80, 26, 26, 27, 27, 27, + 27, 27, 88, 88, 90, 90, 83, 83, 91, 91, + 92, 92, 92, 84, 84, 87, 87, 85, 85, 93, + 94, 94, 57, 57, 65, 65, 68, 68, 68, 67, + 95, 95, 96, 58, 58, 58, 58, 97, 97, 98, + 98, 99, 99, 100, 101, 101, 102, 102, 103, 103, + 55, 55, 51, 51, 105, 53, 53, 106, 52, 52, + 54, 54, 64, 64, 64, 64, 81, 81, 109, 109, + 111, 111, 112, 112, 112, 112, 110, 110, 110, 114, + 114, 114, 114, 89, 89, 117, 117, 117, 118, 118, + 115, 115, 119, 119, 121, 121, 122, 122, 116, 123, + 123, 120, 124, 124, 124, 124, 113, 113, 82, 82, + 82, 20, 20, 20, 126, 125, 125, 127, 127, 127, + 127, 60, 128, 128, 129, 61, 131, 131, 132, 132, + 133, 133, 86, 134, 134, 134, 134, 134, 134, 134, + 139, 139, 140, 140, 141, 141, 141, 141, 141, 142, + 143, 143, 138, 138, 135, 135, 137, 137, 145, 145, + 144, 144, 144, 144, 144, 144, 144, 136, 146, 146, + 148, 147, 147, 62, 104, 149, 149, 56, 56, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 156, 150, 150, 155, 155, 158, 159, + 159, 160, 161, 162, 162, 162, 162, 19, 19, 73, + 73, 73, 73, 151, 151, 151, 151, 164, 164, 152, + 152, 154, 154, 154, 157, 157, 170, 170, 170, 170, + 170, 170, 170, 170, 170, 171, 171, 171, 108, 173, + 173, 173, 173, 153, 153, 153, 153, 153, 153, 153, + 153, 59, 59, 167, 167, 167, 167, 174, 174, 163, + 163, 163, 175, 175, 175, 175, 175, 175, 74, 74, + 66, 66, 66, 66, 130, 130, 130, 130, 178, 177, + 166, 166, 166, 166, 166, 166, 166, 165, 165, 165, + 176, 176, 176, 176, 107, 172, 180, 180, 179, 179, + 181, 181, 181, 181, 181, 181, 181, 181, 169, 169, + 169, 169, 168, 183, 182, 182, 182, 182, 182, 182, + 182, 182, 184, 184, 184, 184 + ); + + protected array $ruleToLength = array( + 1, 1, 2, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, + 1, 0, 1, 1, 2, 1, 3, 4, 1, 2, + 0, 1, 1, 1, 1, 4, 3, 5, 4, 3, + 4, 2, 3, 1, 1, 7, 6, 2, 3, 1, + 2, 3, 1, 2, 3, 1, 1, 3, 1, 3, + 1, 2, 2, 3, 1, 3, 2, 3, 1, 3, + 3, 2, 0, 1, 1, 1, 1, 1, 3, 7, + 10, 5, 7, 9, 5, 3, 3, 3, 3, 3, + 3, 1, 2, 5, 7, 9, 6, 5, 6, 3, + 2, 1, 1, 1, 1, 0, 2, 1, 3, 8, + 0, 4, 2, 1, 3, 0, 1, 0, 1, 0, + 1, 3, 1, 1, 1, 8, 9, 7, 8, 7, + 6, 8, 0, 2, 0, 2, 1, 2, 1, 2, + 1, 1, 1, 0, 2, 0, 2, 0, 2, 2, + 1, 3, 1, 4, 1, 4, 1, 1, 4, 2, + 1, 3, 3, 3, 4, 4, 5, 0, 2, 4, + 3, 1, 1, 7, 0, 2, 1, 3, 3, 4, + 1, 4, 0, 2, 5, 0, 2, 6, 0, 2, + 0, 3, 1, 2, 1, 1, 2, 0, 1, 3, + 0, 2, 1, 1, 1, 1, 6, 8, 6, 1, + 2, 1, 1, 1, 1, 1, 1, 1, 1, 3, + 3, 3, 1, 3, 3, 3, 3, 3, 1, 3, + 3, 1, 1, 2, 1, 1, 0, 1, 0, 2, + 2, 2, 4, 3, 1, 1, 3, 1, 2, 2, + 3, 2, 3, 1, 1, 2, 3, 1, 1, 3, + 2, 0, 1, 5, 5, 6, 10, 3, 5, 1, + 1, 3, 0, 2, 4, 5, 4, 4, 4, 3, + 1, 1, 1, 1, 1, 1, 0, 1, 1, 2, + 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, + 1, 1, 3, 2, 2, 3, 1, 0, 1, 1, + 3, 3, 3, 4, 4, 1, 1, 2, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, + 3, 4, 4, 2, 2, 4, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 1, 3, 2, + 1, 2, 4, 2, 2, 8, 9, 8, 9, 9, + 10, 9, 10, 8, 3, 2, 0, 4, 2, 1, + 3, 2, 1, 2, 2, 2, 4, 1, 1, 1, + 1, 1, 1, 1, 1, 3, 1, 1, 1, 0, + 3, 0, 1, 1, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 3, 5, 3, 3, 4, + 1, 1, 3, 1, 1, 1, 1, 1, 3, 2, + 3, 0, 1, 1, 3, 1, 1, 1, 1, 1, + 3, 1, 1, 4, 4, 1, 4, 4, 0, 1, + 1, 1, 3, 3, 1, 4, 2, 2, 1, 3, + 1, 4, 4, 3, 3, 3, 3, 1, 3, 1, + 1, 3, 1, 1, 4, 1, 1, 1, 3, 1, + 1, 2, 1, 3, 4, 3, 2, 0, 2, 2, + 1, 2, 1, 1, 1, 4, 3, 3, 3, 3, + 6, 3, 1, 1, 2, 1 + ); + + protected function initReduceCallbacks(): void { + $this->reduceCallbacks = [ + 0 => null, + 1 => static function ($self, $stackPos) { + $self->semValue = $self->handleNamespaces($self->semStack[$stackPos-(1-1)]); + }, + 2 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(2-2)] !== null) { $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; } $self->semValue = $self->semStack[$stackPos-(2-1)];; + }, + 3 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 4 => static function ($self, $stackPos) { + $nop = $self->maybeCreateZeroLengthNop($self->tokenPos);; + if ($nop !== null) { $self->semStack[$stackPos-(1-1)][] = $nop; } $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 5 => null, + 6 => null, + 7 => null, + 8 => null, + 9 => null, + 10 => null, + 11 => null, + 12 => null, + 13 => null, + 14 => null, + 15 => null, + 16 => null, + 17 => null, + 18 => null, + 19 => null, + 20 => null, + 21 => null, + 22 => null, + 23 => null, + 24 => null, + 25 => null, + 26 => null, + 27 => null, + 28 => null, + 29 => null, + 30 => null, + 31 => null, + 32 => null, + 33 => null, + 34 => null, + 35 => null, + 36 => null, + 37 => null, + 38 => null, + 39 => null, + 40 => null, + 41 => null, + 42 => null, + 43 => null, + 44 => null, + 45 => null, + 46 => null, + 47 => null, + 48 => null, + 49 => null, + 50 => null, + 51 => null, + 52 => null, + 53 => null, + 54 => null, + 55 => null, + 56 => null, + 57 => null, + 58 => null, + 59 => null, + 60 => null, + 61 => null, + 62 => null, + 63 => null, + 64 => null, + 65 => null, + 66 => null, + 67 => null, + 68 => null, + 69 => null, + 70 => null, + 71 => null, + 72 => null, + 73 => null, + 74 => null, + 75 => null, + 76 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; if ($self->semValue === "<?=") $self->emitError(new Error('Cannot use "<?=" as an identifier', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]))); + }, + 77 => null, + 78 => null, + 79 => null, + 80 => null, + 81 => null, + 82 => null, + 83 => null, + 84 => null, + 85 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 86 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 87 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 88 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 89 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 90 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 91 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 92 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 93 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 94 => null, + 95 => static function ($self, $stackPos) { + $self->semValue = new Name(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 96 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 97 => static function ($self, $stackPos) { + /* nothing */ + }, + 98 => static function ($self, $stackPos) { + /* nothing */ + }, + 99 => static function ($self, $stackPos) { + /* nothing */ + }, + 100 => static function ($self, $stackPos) { + $self->emitError(new Error('A trailing comma is not allowed here', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]))); + }, + 101 => null, + 102 => null, + 103 => static function ($self, $stackPos) { + $self->semValue = new Node\Attribute($self->semStack[$stackPos-(1-1)], [], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 104 => static function ($self, $stackPos) { + $self->semValue = new Node\Attribute($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 105 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 106 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 107 => static function ($self, $stackPos) { + $self->semValue = new Node\AttributeGroup($self->semStack[$stackPos-(4-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 108 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 109 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 110 => static function ($self, $stackPos) { + $self->semValue = []; + }, + 111 => null, + 112 => null, + 113 => null, + 114 => null, + 115 => static function ($self, $stackPos) { + $self->semValue = new Stmt\HaltCompiler($self->handleHaltCompiler(), $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 116 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Namespace_($self->semStack[$stackPos-(3-2)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('kind', Stmt\Namespace_::KIND_SEMICOLON); + $self->checkNamespace($self->semValue); + }, + 117 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Namespace_($self->semStack[$stackPos-(5-2)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('kind', Stmt\Namespace_::KIND_BRACED); + $self->checkNamespace($self->semValue); + }, + 118 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Namespace_(null, $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('kind', Stmt\Namespace_::KIND_BRACED); + $self->checkNamespace($self->semValue); + }, + 119 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Use_($self->semStack[$stackPos-(3-2)], Stmt\Use_::TYPE_NORMAL, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 120 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Use_($self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 121 => null, + 122 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Const_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 123 => static function ($self, $stackPos) { + $self->semValue = Stmt\Use_::TYPE_FUNCTION; + }, + 124 => static function ($self, $stackPos) { + $self->semValue = Stmt\Use_::TYPE_CONSTANT; + }, + 125 => static function ($self, $stackPos) { + $self->semValue = new Stmt\GroupUse($self->semStack[$stackPos-(7-3)], $self->semStack[$stackPos-(7-6)], $self->semStack[$stackPos-(7-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 126 => static function ($self, $stackPos) { + $self->semValue = new Stmt\GroupUse($self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-5)], Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 127 => null, + 128 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 129 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 130 => null, + 131 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 132 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 133 => null, + 134 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 135 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 136 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(1-1)], null, Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(1-1)); + }, + 137 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(3-3)); + }, + 138 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(1-1)], null, Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(1-1)); + }, + 139 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(3-3)); + }, + 140 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; $self->semValue->type = Stmt\Use_::TYPE_NORMAL; + }, + 141 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; $self->semValue->type = $self->semStack[$stackPos-(2-1)]; + }, + 142 => null, + 143 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 144 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 145 => static function ($self, $stackPos) { + $self->semValue = new Node\Const_($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 146 => null, + 147 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 148 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 149 => static function ($self, $stackPos) { + $self->semValue = new Node\Const_(new Node\Identifier($self->semStack[$stackPos-(3-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos-(3-1)])), $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 150 => static function ($self, $stackPos) { + $self->semValue = new Node\Const_(new Node\Identifier($self->semStack[$stackPos-(3-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos-(3-1)])), $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 151 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(2-2)] !== null) { $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; } $self->semValue = $self->semStack[$stackPos-(2-1)];; + }, + 152 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 153 => static function ($self, $stackPos) { + $nop = $self->maybeCreateZeroLengthNop($self->tokenPos);; + if ($nop !== null) { $self->semStack[$stackPos-(1-1)][] = $nop; } $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 154 => null, + 155 => null, + 156 => null, + 157 => static function ($self, $stackPos) { + throw new Error('__HALT_COMPILER() can only be used from the outermost scope', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 158 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Block($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 159 => static function ($self, $stackPos) { + $self->semValue = new Stmt\If_($self->semStack[$stackPos-(7-3)], ['stmts' => $self->semStack[$stackPos-(7-5)], 'elseifs' => $self->semStack[$stackPos-(7-6)], 'else' => $self->semStack[$stackPos-(7-7)]], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 160 => static function ($self, $stackPos) { + $self->semValue = new Stmt\If_($self->semStack[$stackPos-(10-3)], ['stmts' => $self->semStack[$stackPos-(10-6)], 'elseifs' => $self->semStack[$stackPos-(10-7)], 'else' => $self->semStack[$stackPos-(10-8)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + }, + 161 => static function ($self, $stackPos) { + $self->semValue = new Stmt\While_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 162 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Do_($self->semStack[$stackPos-(7-5)], $self->semStack[$stackPos-(7-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 163 => static function ($self, $stackPos) { + $self->semValue = new Stmt\For_(['init' => $self->semStack[$stackPos-(9-3)], 'cond' => $self->semStack[$stackPos-(9-5)], 'loop' => $self->semStack[$stackPos-(9-7)], 'stmts' => $self->semStack[$stackPos-(9-9)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 164 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Switch_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 165 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Break_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 166 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Continue_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 167 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Return_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 168 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Global_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 169 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Static_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 170 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Echo_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 171 => static function ($self, $stackPos) { + + $self->semValue = new Stmt\InlineHTML($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('hasLeadingNewline', $self->inlineHtmlHasLeadingNewline($stackPos-(1-1))); + + }, + 172 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Expression($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 173 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Unset_($self->semStack[$stackPos-(5-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 174 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Foreach_($self->semStack[$stackPos-(7-3)], $self->semStack[$stackPos-(7-5)][0], ['keyVar' => null, 'byRef' => $self->semStack[$stackPos-(7-5)][1], 'stmts' => $self->semStack[$stackPos-(7-7)]], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 175 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Foreach_($self->semStack[$stackPos-(9-3)], $self->semStack[$stackPos-(9-7)][0], ['keyVar' => $self->semStack[$stackPos-(9-5)], 'byRef' => $self->semStack[$stackPos-(9-7)][1], 'stmts' => $self->semStack[$stackPos-(9-9)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 176 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Foreach_($self->semStack[$stackPos-(6-3)], new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(6-4)], $self->tokenEndStack[$stackPos-(6-4)])), ['stmts' => $self->semStack[$stackPos-(6-6)]], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 177 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Declare_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 178 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TryCatch($self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-5)], $self->semStack[$stackPos-(6-6)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); $self->checkTryCatch($self->semValue); + }, + 179 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Goto_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 180 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Label($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 181 => static function ($self, $stackPos) { + $self->semValue = null; /* means: no statement */ + }, + 182 => null, + 183 => static function ($self, $stackPos) { + $self->semValue = $self->maybeCreateNop($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]); + }, + 184 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(1-1)] instanceof Stmt\Block) { $self->semValue = $self->semStack[$stackPos-(1-1)]->stmts; } else if ($self->semStack[$stackPos-(1-1)] === null) { $self->semValue = []; } else { $self->semValue = [$self->semStack[$stackPos-(1-1)]]; }; + }, + 185 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 186 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 187 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 188 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 189 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Catch_($self->semStack[$stackPos-(8-3)], $self->semStack[$stackPos-(8-4)], $self->semStack[$stackPos-(8-7)], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 190 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 191 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Finally_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 192 => null, + 193 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 194 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 195 => static function ($self, $stackPos) { + $self->semValue = false; + }, + 196 => static function ($self, $stackPos) { + $self->semValue = true; + }, + 197 => static function ($self, $stackPos) { + $self->semValue = false; + }, + 198 => static function ($self, $stackPos) { + $self->semValue = true; + }, + 199 => static function ($self, $stackPos) { + $self->semValue = false; + }, + 200 => static function ($self, $stackPos) { + $self->semValue = true; + }, + 201 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 202 => static function ($self, $stackPos) { + $self->semValue = []; + }, + 203 => null, + 204 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 205 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Function_($self->semStack[$stackPos-(8-3)], ['byRef' => $self->semStack[$stackPos-(8-2)], 'params' => $self->semStack[$stackPos-(8-5)], 'returnType' => $self->semStack[$stackPos-(8-7)], 'stmts' => $self->semStack[$stackPos-(8-8)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 206 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Function_($self->semStack[$stackPos-(9-4)], ['byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-6)], 'returnType' => $self->semStack[$stackPos-(9-8)], 'stmts' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => $self->semStack[$stackPos-(9-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 207 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Class_($self->semStack[$stackPos-(7-2)], ['type' => $self->semStack[$stackPos-(7-1)], 'extends' => $self->semStack[$stackPos-(7-3)], 'implements' => $self->semStack[$stackPos-(7-4)], 'stmts' => $self->semStack[$stackPos-(7-6)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + $self->checkClass($self->semValue, $stackPos-(7-2)); + }, + 208 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Class_($self->semStack[$stackPos-(8-3)], ['type' => $self->semStack[$stackPos-(8-2)], 'extends' => $self->semStack[$stackPos-(8-4)], 'implements' => $self->semStack[$stackPos-(8-5)], 'stmts' => $self->semStack[$stackPos-(8-7)], 'attrGroups' => $self->semStack[$stackPos-(8-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + $self->checkClass($self->semValue, $stackPos-(8-3)); + }, + 209 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Interface_($self->semStack[$stackPos-(7-3)], ['extends' => $self->semStack[$stackPos-(7-4)], 'stmts' => $self->semStack[$stackPos-(7-6)], 'attrGroups' => $self->semStack[$stackPos-(7-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + $self->checkInterface($self->semValue, $stackPos-(7-3)); + }, + 210 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Trait_($self->semStack[$stackPos-(6-3)], ['stmts' => $self->semStack[$stackPos-(6-5)], 'attrGroups' => $self->semStack[$stackPos-(6-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 211 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Enum_($self->semStack[$stackPos-(8-3)], ['scalarType' => $self->semStack[$stackPos-(8-4)], 'implements' => $self->semStack[$stackPos-(8-5)], 'stmts' => $self->semStack[$stackPos-(8-7)], 'attrGroups' => $self->semStack[$stackPos-(8-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + $self->checkEnum($self->semValue, $stackPos-(8-3)); + }, + 212 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 213 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 214 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 215 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 216 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 217 => null, + 218 => null, + 219 => static function ($self, $stackPos) { + $self->checkClassModifier($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $stackPos-(2-2)); $self->semValue = $self->semStack[$stackPos-(2-1)] | $self->semStack[$stackPos-(2-2)]; + }, + 220 => static function ($self, $stackPos) { + $self->semValue = Modifiers::ABSTRACT; + }, + 221 => static function ($self, $stackPos) { + $self->semValue = Modifiers::FINAL; + }, + 222 => static function ($self, $stackPos) { + $self->semValue = Modifiers::READONLY; + }, + 223 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 224 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 225 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 226 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 227 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 228 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 229 => null, + 230 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 231 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 232 => null, + 233 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 234 => null, + 235 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 236 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(1-1)] instanceof Stmt\Block) { $self->semValue = $self->semStack[$stackPos-(1-1)]->stmts; } else if ($self->semStack[$stackPos-(1-1)] === null) { $self->semValue = []; } else { $self->semValue = [$self->semStack[$stackPos-(1-1)]]; }; + }, + 237 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 238 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 239 => null, + 240 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 241 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 242 => static function ($self, $stackPos) { + $self->semValue = new Node\DeclareItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 243 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 244 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-3)]; + }, + 245 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 246 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(5-3)]; + }, + 247 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 248 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 249 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Case_($self->semStack[$stackPos-(4-2)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 250 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Case_(null, $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 251 => null, + 252 => null, + 253 => static function ($self, $stackPos) { + $self->semValue = new Expr\Match_($self->semStack[$stackPos-(7-3)], $self->semStack[$stackPos-(7-6)], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 254 => static function ($self, $stackPos) { + $self->semValue = []; + }, + 255 => null, + 256 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 257 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 258 => static function ($self, $stackPos) { + $self->semValue = new Node\MatchArm($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 259 => static function ($self, $stackPos) { + $self->semValue = new Node\MatchArm(null, $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 260 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 261 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 262 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 263 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 264 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ElseIf_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 265 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 266 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 267 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ElseIf_($self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-6)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); $self->fixupAlternativeElse($self->semValue); + }, + 268 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 269 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Else_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 270 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 271 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Else_($self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->fixupAlternativeElse($self->semValue); + }, + 272 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)], false); + }, + 273 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(2-2)], true); + }, + 274 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)], false); + }, + 275 => static function ($self, $stackPos) { + $self->semValue = array($self->fixupArrayDestructuring($self->semStack[$stackPos-(1-1)]), false); + }, + 276 => null, + 277 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 278 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 279 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 280 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 281 => static function ($self, $stackPos) { + $self->checkModifier($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $stackPos-(2-2)); $self->semValue = $self->semStack[$stackPos-(2-1)] | $self->semStack[$stackPos-(2-2)]; + }, + 282 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PUBLIC; + }, + 283 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PROTECTED; + }, + 284 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PRIVATE; + }, + 285 => static function ($self, $stackPos) { + $self->semValue = Modifiers::READONLY; + }, + 286 => static function ($self, $stackPos) { + $self->semValue = new Node\Param($self->semStack[$stackPos-(6-6)], null, $self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-4)], $self->semStack[$stackPos-(6-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-1)]); + $self->checkParam($self->semValue); + }, + 287 => static function ($self, $stackPos) { + $self->semValue = new Node\Param($self->semStack[$stackPos-(8-6)], $self->semStack[$stackPos-(8-8)], $self->semStack[$stackPos-(8-3)], $self->semStack[$stackPos-(8-4)], $self->semStack[$stackPos-(8-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(8-2)], $self->semStack[$stackPos-(8-1)]); + $self->checkParam($self->semValue); + }, + 288 => static function ($self, $stackPos) { + $self->semValue = new Node\Param(new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])), null, $self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-4)], $self->semStack[$stackPos-(6-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-1)]); + }, + 289 => null, + 290 => static function ($self, $stackPos) { + $self->semValue = new Node\NullableType($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 291 => static function ($self, $stackPos) { + $self->semValue = new Node\UnionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 292 => null, + 293 => null, + 294 => static function ($self, $stackPos) { + $self->semValue = new Node\Name('static', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 295 => static function ($self, $stackPos) { + $self->semValue = $self->handleBuiltinTypes($self->semStack[$stackPos-(1-1)]); + }, + 296 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier('array', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 297 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier('callable', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 298 => null, + 299 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 300 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 301 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 302 => null, + 303 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 304 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 305 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 306 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 307 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 308 => static function ($self, $stackPos) { + $self->semValue = new Node\IntersectionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 309 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 310 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 311 => static function ($self, $stackPos) { + $self->semValue = new Node\IntersectionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 312 => null, + 313 => static function ($self, $stackPos) { + $self->semValue = new Node\NullableType($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 314 => static function ($self, $stackPos) { + $self->semValue = new Node\UnionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 315 => null, + 316 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 317 => null, + 318 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 319 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 320 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 321 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 322 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 323 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-2)]); + }, + 324 => static function ($self, $stackPos) { + $self->semValue = new Node\VariadicPlaceholder($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 325 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 326 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 327 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(1-1)], false, false, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 328 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(2-2)], true, false, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 329 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(2-2)], false, true, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 330 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(3-3)], false, false, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(3-1)]); + }, + 331 => null, + 332 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 333 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 334 => null, + 335 => null, + 336 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 337 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 338 => static function ($self, $stackPos) { + $self->semValue = new Node\StaticVar($self->semStack[$stackPos-(1-1)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 339 => static function ($self, $stackPos) { + $self->semValue = new Node\StaticVar($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 340 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(2-2)] !== null) { $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; } else { $self->semValue = $self->semStack[$stackPos-(2-1)]; } + }, + 341 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 342 => static function ($self, $stackPos) { + $nop = $self->maybeCreateZeroLengthNop($self->tokenPos);; + if ($nop !== null) { $self->semStack[$stackPos-(1-1)][] = $nop; } $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 343 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Property($self->semStack[$stackPos-(5-2)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-1)]); + $self->checkProperty($self->semValue, $stackPos-(5-2)); + }, + 344 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ClassConst($self->semStack[$stackPos-(5-4)], $self->semStack[$stackPos-(5-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(5-1)]); + $self->checkClassConst($self->semValue, $stackPos-(5-2)); + }, + 345 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ClassConst($self->semStack[$stackPos-(6-5)], $self->semStack[$stackPos-(6-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(6-1)], $self->semStack[$stackPos-(6-4)]); + $self->checkClassConst($self->semValue, $stackPos-(6-2)); + }, + 346 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ClassMethod($self->semStack[$stackPos-(10-5)], ['type' => $self->semStack[$stackPos-(10-2)], 'byRef' => $self->semStack[$stackPos-(10-4)], 'params' => $self->semStack[$stackPos-(10-7)], 'returnType' => $self->semStack[$stackPos-(10-9)], 'stmts' => $self->semStack[$stackPos-(10-10)], 'attrGroups' => $self->semStack[$stackPos-(10-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + $self->checkClassMethod($self->semValue, $stackPos-(10-2)); + }, + 347 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUse($self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 348 => static function ($self, $stackPos) { + $self->semValue = new Stmt\EnumCase($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-4)], $self->semStack[$stackPos-(5-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 349 => static function ($self, $stackPos) { + $self->semValue = null; /* will be skipped */ + }, + 350 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 351 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 352 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 353 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 354 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Precedence($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 355 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(5-1)][0], $self->semStack[$stackPos-(5-1)][1], $self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 356 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], $self->semStack[$stackPos-(4-3)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 357 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], null, $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 358 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], null, $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 359 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 360 => null, + 361 => static function ($self, $stackPos) { + $self->semValue = array(null, $self->semStack[$stackPos-(1-1)]); + }, + 362 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 363 => null, + 364 => null, + 365 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 366 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 367 => null, + 368 => null, + 369 => static function ($self, $stackPos) { + $self->checkModifier($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $stackPos-(2-2)); $self->semValue = $self->semStack[$stackPos-(2-1)] | $self->semStack[$stackPos-(2-2)]; + }, + 370 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PUBLIC; + }, + 371 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PROTECTED; + }, + 372 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PRIVATE; + }, + 373 => static function ($self, $stackPos) { + $self->semValue = Modifiers::STATIC; + }, + 374 => static function ($self, $stackPos) { + $self->semValue = Modifiers::ABSTRACT; + }, + 375 => static function ($self, $stackPos) { + $self->semValue = Modifiers::FINAL; + }, + 376 => static function ($self, $stackPos) { + $self->semValue = Modifiers::READONLY; + }, + 377 => null, + 378 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 379 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 380 => static function ($self, $stackPos) { + $self->semValue = new Node\VarLikeIdentifier(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 381 => static function ($self, $stackPos) { + $self->semValue = new Node\PropertyItem($self->semStack[$stackPos-(1-1)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 382 => static function ($self, $stackPos) { + $self->semValue = new Node\PropertyItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 383 => null, + 384 => null, + 385 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 386 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 387 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 388 => null, + 389 => null, + 390 => static function ($self, $stackPos) { + $self->semValue = new Expr\Assign($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 391 => static function ($self, $stackPos) { + $self->semValue = new Expr\Assign($self->fixupArrayDestructuring($self->semStack[$stackPos-(3-1)]), $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 392 => static function ($self, $stackPos) { + $self->semValue = new Expr\Assign($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 393 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignRef($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 394 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignRef($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + if (!$self->phpVersion->allowsAssignNewByReference()) { + $self->emitError(new Error('Cannot assign new by reference', $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos]))); + } + + }, + 395 => null, + 396 => null, + 397 => static function ($self, $stackPos) { + $self->semValue = new Expr\Clone_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 398 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Plus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 399 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Minus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 400 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Mul($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 401 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Div($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 402 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Concat($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 403 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Mod($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 404 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\BitwiseAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 405 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\BitwiseOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 406 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\BitwiseXor($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 407 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\ShiftLeft($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 408 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\ShiftRight($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 409 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Pow($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 410 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Coalesce($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 411 => static function ($self, $stackPos) { + $self->semValue = new Expr\PostInc($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 412 => static function ($self, $stackPos) { + $self->semValue = new Expr\PreInc($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 413 => static function ($self, $stackPos) { + $self->semValue = new Expr\PostDec($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 414 => static function ($self, $stackPos) { + $self->semValue = new Expr\PreDec($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 415 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BooleanOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 416 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BooleanAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 417 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\LogicalOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 418 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\LogicalAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 419 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\LogicalXor($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 420 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 421 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 422 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 423 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseXor($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 424 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Concat($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 425 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Plus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 426 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Minus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 427 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Mul($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 428 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Div($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 429 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Mod($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 430 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\ShiftLeft($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 431 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\ShiftRight($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 432 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Pow($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 433 => static function ($self, $stackPos) { + $self->semValue = new Expr\UnaryPlus($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 434 => static function ($self, $stackPos) { + $self->semValue = new Expr\UnaryMinus($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 435 => static function ($self, $stackPos) { + $self->semValue = new Expr\BooleanNot($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 436 => static function ($self, $stackPos) { + $self->semValue = new Expr\BitwiseNot($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 437 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Identical($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 438 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\NotIdentical($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 439 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Equal($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 440 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\NotEqual($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 441 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Spaceship($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 442 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Smaller($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 443 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\SmallerOrEqual($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 444 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Greater($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 445 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\GreaterOrEqual($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 446 => static function ($self, $stackPos) { + $self->semValue = new Expr\Instanceof_($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 447 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 448 => static function ($self, $stackPos) { + $self->semValue = new Expr\Ternary($self->semStack[$stackPos-(5-1)], $self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 449 => static function ($self, $stackPos) { + $self->semValue = new Expr\Ternary($self->semStack[$stackPos-(4-1)], null, $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 450 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Coalesce($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 451 => static function ($self, $stackPos) { + $self->semValue = new Expr\Isset_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 452 => static function ($self, $stackPos) { + $self->semValue = new Expr\Empty_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 453 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_INCLUDE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 454 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_INCLUDE_ONCE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 455 => static function ($self, $stackPos) { + $self->semValue = new Expr\Eval_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 456 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_REQUIRE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 457 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_REQUIRE_ONCE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 458 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Int_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 459 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]); + $attrs['kind'] = $self->getFloatCastKind($self->semStack[$stackPos-(2-1)]); + $self->semValue = new Expr\Cast\Double($self->semStack[$stackPos-(2-2)], $attrs); + }, + 460 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\String_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 461 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Array_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 462 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Object_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 463 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Bool_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 464 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Unset_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 465 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]); + $attrs['kind'] = strtolower($self->semStack[$stackPos-(2-1)]) === 'exit' ? Expr\Exit_::KIND_EXIT : Expr\Exit_::KIND_DIE; + $self->semValue = new Expr\Exit_($self->semStack[$stackPos-(2-2)], $attrs); + }, + 466 => static function ($self, $stackPos) { + $self->semValue = new Expr\ErrorSuppress($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 467 => null, + 468 => static function ($self, $stackPos) { + $self->semValue = new Expr\ShellExec($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 469 => static function ($self, $stackPos) { + $self->semValue = new Expr\Print_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 470 => static function ($self, $stackPos) { + $self->semValue = new Expr\Yield_(null, null, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 471 => static function ($self, $stackPos) { + $self->semValue = new Expr\Yield_($self->semStack[$stackPos-(2-2)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 472 => static function ($self, $stackPos) { + $self->semValue = new Expr\Yield_($self->semStack[$stackPos-(4-4)], $self->semStack[$stackPos-(4-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 473 => static function ($self, $stackPos) { + $self->semValue = new Expr\YieldFrom($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 474 => static function ($self, $stackPos) { + $self->semValue = new Expr\Throw_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 475 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => false, 'byRef' => $self->semStack[$stackPos-(8-2)], 'params' => $self->semStack[$stackPos-(8-4)], 'returnType' => $self->semStack[$stackPos-(8-6)], 'expr' => $self->semStack[$stackPos-(8-8)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 476 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => true, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'returnType' => $self->semStack[$stackPos-(9-7)], 'expr' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 477 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => false, 'byRef' => $self->semStack[$stackPos-(8-2)], 'params' => $self->semStack[$stackPos-(8-4)], 'uses' => $self->semStack[$stackPos-(8-6)], 'returnType' => $self->semStack[$stackPos-(8-7)], 'stmts' => $self->semStack[$stackPos-(8-8)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 478 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => true, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'uses' => $self->semStack[$stackPos-(9-7)], 'returnType' => $self->semStack[$stackPos-(9-8)], 'stmts' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 479 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => false, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'returnType' => $self->semStack[$stackPos-(9-7)], 'expr' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => $self->semStack[$stackPos-(9-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 480 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => true, 'byRef' => $self->semStack[$stackPos-(10-4)], 'params' => $self->semStack[$stackPos-(10-6)], 'returnType' => $self->semStack[$stackPos-(10-8)], 'expr' => $self->semStack[$stackPos-(10-10)], 'attrGroups' => $self->semStack[$stackPos-(10-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + }, + 481 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => false, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'uses' => $self->semStack[$stackPos-(9-7)], 'returnType' => $self->semStack[$stackPos-(9-8)], 'stmts' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => $self->semStack[$stackPos-(9-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 482 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => true, 'byRef' => $self->semStack[$stackPos-(10-4)], 'params' => $self->semStack[$stackPos-(10-6)], 'uses' => $self->semStack[$stackPos-(10-8)], 'returnType' => $self->semStack[$stackPos-(10-9)], 'stmts' => $self->semStack[$stackPos-(10-10)], 'attrGroups' => $self->semStack[$stackPos-(10-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + }, + 483 => static function ($self, $stackPos) { + $self->semValue = array(new Stmt\Class_(null, ['type' => $self->semStack[$stackPos-(8-2)], 'extends' => $self->semStack[$stackPos-(8-4)], 'implements' => $self->semStack[$stackPos-(8-5)], 'stmts' => $self->semStack[$stackPos-(8-7)], 'attrGroups' => $self->semStack[$stackPos-(8-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])), $self->semStack[$stackPos-(8-3)]); + $self->checkClass($self->semValue[0], -1); + }, + 484 => static function ($self, $stackPos) { + $self->semValue = new Expr\New_($self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 485 => static function ($self, $stackPos) { + list($class, $ctorArgs) = $self->semStack[$stackPos-(2-2)]; $self->semValue = new Expr\New_($class, $ctorArgs, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 486 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 487 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-3)]; + }, + 488 => null, + 489 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 490 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 491 => static function ($self, $stackPos) { + $self->semValue = new Node\ClosureUse($self->semStack[$stackPos-(2-2)], $self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 492 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 493 => static function ($self, $stackPos) { + $self->semValue = new Expr\FuncCall($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 494 => static function ($self, $stackPos) { + $self->semValue = new Expr\FuncCall($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 495 => static function ($self, $stackPos) { + $self->semValue = new Expr\FuncCall($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 496 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticCall($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 497 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 498 => null, + 499 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 500 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 501 => static function ($self, $stackPos) { + $self->semValue = new Name\FullyQualified(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 502 => static function ($self, $stackPos) { + $self->semValue = new Name\Relative(substr($self->semStack[$stackPos-(1-1)], 10), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 503 => null, + 504 => null, + 505 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 506 => static function ($self, $stackPos) { + $self->semValue = new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 507 => null, + 508 => null, + 509 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 510 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 511 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 512 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); foreach ($self->semValue as $s) { if ($s instanceof Node\InterpolatedStringPart) { $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, '`', $self->phpVersion->supportsUnicodeEscapes()); } }; + }, + 513 => static function ($self, $stackPos) { + foreach ($self->semStack[$stackPos-(1-1)] as $s) { if ($s instanceof Node\InterpolatedStringPart) { $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, '`', $self->phpVersion->supportsUnicodeEscapes()); } }; $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 514 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 515 => null, + 516 => static function ($self, $stackPos) { + $self->semValue = new Expr\ConstFetch($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 517 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Line($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 518 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\File($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 519 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Dir($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 520 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Class_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 521 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Trait_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 522 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Method($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 523 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Function_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 524 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Namespace_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 525 => static function ($self, $stackPos) { + $self->semValue = new Expr\ClassConstFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 526 => static function ($self, $stackPos) { + $self->semValue = new Expr\ClassConstFetch($self->semStack[$stackPos-(5-1)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 527 => static function ($self, $stackPos) { + $self->semValue = new Expr\ClassConstFetch($self->semStack[$stackPos-(3-1)], new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(3-3)], $self->tokenEndStack[$stackPos-(3-3)])), $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 528 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]); $attrs['kind'] = Expr\Array_::KIND_SHORT; + $self->semValue = new Expr\Array_($self->semStack[$stackPos-(3-2)], $attrs); + }, + 529 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos]); $attrs['kind'] = Expr\Array_::KIND_LONG; + $self->semValue = new Expr\Array_($self->semStack[$stackPos-(4-3)], $attrs); + $self->createdArrays->attach($self->semValue); + }, + 530 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; $self->createdArrays->attach($self->semValue); + }, + 531 => static function ($self, $stackPos) { + $self->semValue = Scalar\String_::fromString($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]), $self->phpVersion->supportsUnicodeEscapes()); + }, + 532 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]); $attrs['kind'] = Scalar\String_::KIND_DOUBLE_QUOTED; + foreach ($self->semStack[$stackPos-(3-2)] as $s) { if ($s instanceof Node\InterpolatedStringPart) { $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, '"', $self->phpVersion->supportsUnicodeEscapes()); } }; $self->semValue = new Scalar\InterpolatedString($self->semStack[$stackPos-(3-2)], $attrs); + }, + 533 => static function ($self, $stackPos) { + $self->semValue = $self->parseLNumber($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]), $self->phpVersion->allowsInvalidOctals()); + }, + 534 => static function ($self, $stackPos) { + $self->semValue = Scalar\Float_::fromString($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 535 => null, + 536 => null, + 537 => null, + 538 => static function ($self, $stackPos) { + $self->semValue = $self->parseDocString($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]), $self->getAttributes($self->tokenStartStack[$stackPos-(3-3)], $self->tokenEndStack[$stackPos-(3-3)]), true); + }, + 539 => static function ($self, $stackPos) { + $self->semValue = $self->parseDocString($self->semStack[$stackPos-(2-1)], '', $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]), $self->getAttributes($self->tokenStartStack[$stackPos-(2-2)], $self->tokenEndStack[$stackPos-(2-2)]), true); + }, + 540 => static function ($self, $stackPos) { + $self->semValue = $self->parseDocString($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]), $self->getAttributes($self->tokenStartStack[$stackPos-(3-3)], $self->tokenEndStack[$stackPos-(3-3)]), true); + }, + 541 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 542 => null, + 543 => null, + 544 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 545 => null, + 546 => null, + 547 => null, + 548 => null, + 549 => null, + 550 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 551 => null, + 552 => null, + 553 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 554 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 555 => null, + 556 => static function ($self, $stackPos) { + $self->semValue = new Expr\MethodCall($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 557 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafeMethodCall($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 558 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 559 => null, + 560 => null, + 561 => null, + 562 => static function ($self, $stackPos) { + $self->semValue = new Expr\PropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 563 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafePropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 564 => null, + 565 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 566 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 567 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable(new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])), $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 568 => static function ($self, $stackPos) { + $var = $self->semStack[$stackPos-(1-1)]->name; $self->semValue = \is_string($var) ? new Node\VarLikeIdentifier($var, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])) : $var; + }, + 569 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticPropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 570 => null, + 571 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 572 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 573 => static function ($self, $stackPos) { + $self->semValue = new Expr\PropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 574 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafePropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 575 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticPropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 576 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticPropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 577 => null, + 578 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 579 => null, + 580 => null, + 581 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 582 => null, + 583 => static function ($self, $stackPos) { + $self->semValue = new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 584 => static function ($self, $stackPos) { + $self->semValue = new Expr\List_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); $self->semValue->setAttribute('kind', Expr\List_::KIND_LIST); + $self->postprocessList($self->semValue); + }, + 585 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; $end = count($self->semValue)-1; if ($self->semValue[$end]->value instanceof Expr\Error) array_pop($self->semValue); + }, + 586 => null, + 587 => static function ($self, $stackPos) { + /* do nothing -- prevent default action of $$=$self->semStack[$1]. See $551. */ + }, + 588 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 589 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 590 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(1-1)], null, false, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 591 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(2-2)], null, true, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 592 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(1-1)], null, false, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 593 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(3-3)], $self->semStack[$stackPos-(3-1)], false, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 594 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(4-4)], $self->semStack[$stackPos-(4-1)], true, $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 595 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(3-3)], $self->semStack[$stackPos-(3-1)], false, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 596 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(2-2)], null, false, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]), true); + }, + 597 => static function ($self, $stackPos) { + /* Create an Error node now to remember the position. We'll later either report an error, + or convert this into a null element, depending on whether this is a creation or destructuring context. */ + $attrs = $self->createEmptyElemAttributes($self->tokenPos); + $self->semValue = new Node\ArrayItem(new Expr\Error($attrs), null, false, $attrs); + }, + 598 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 599 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 600 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 601 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)]); + }, + 602 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]); $attrs['rawValue'] = $self->semStack[$stackPos-(1-1)]; $self->semValue = new Node\InterpolatedStringPart($self->semStack[$stackPos-(1-1)], $attrs); + }, + 603 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 604 => null, + 605 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 606 => static function ($self, $stackPos) { + $self->semValue = new Expr\PropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 607 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafePropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 608 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 609 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 610 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 611 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 612 => static function ($self, $stackPos) { + $self->semValue = new Scalar\String_($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 613 => static function ($self, $stackPos) { + $self->semValue = $self->parseNumString($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 614 => static function ($self, $stackPos) { + $self->semValue = $self->parseNumString('-' . $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 615 => null, + ]; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser/Php8.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser/Php8.php new file mode 100644 index 0000000..27154d2 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Parser/Php8.php @@ -0,0 +1,2717 @@ +<?php declare(strict_types=1); + +namespace PhpParser\Parser; + +use PhpParser\Error; +use PhpParser\Modifiers; +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar; +use PhpParser\Node\Stmt; + +/* This is an automatically GENERATED file, which should not be manually edited. + * Instead edit one of the following: + * * the grammar file grammar/php.y + * * the skeleton file grammar/parser.template + * * the preprocessing script grammar/rebuildParsers.php + */ +class Php8 extends \PhpParser\ParserAbstract +{ + public const YYERRTOK = 256; + public const T_THROW = 257; + public const T_INCLUDE = 258; + public const T_INCLUDE_ONCE = 259; + public const T_EVAL = 260; + public const T_REQUIRE = 261; + public const T_REQUIRE_ONCE = 262; + public const T_LOGICAL_OR = 263; + public const T_LOGICAL_XOR = 264; + public const T_LOGICAL_AND = 265; + public const T_PRINT = 266; + public const T_YIELD = 267; + public const T_DOUBLE_ARROW = 268; + public const T_YIELD_FROM = 269; + public const T_PLUS_EQUAL = 270; + public const T_MINUS_EQUAL = 271; + public const T_MUL_EQUAL = 272; + public const T_DIV_EQUAL = 273; + public const T_CONCAT_EQUAL = 274; + public const T_MOD_EQUAL = 275; + public const T_AND_EQUAL = 276; + public const T_OR_EQUAL = 277; + public const T_XOR_EQUAL = 278; + public const T_SL_EQUAL = 279; + public const T_SR_EQUAL = 280; + public const T_POW_EQUAL = 281; + public const T_COALESCE_EQUAL = 282; + public const T_COALESCE = 283; + public const T_BOOLEAN_OR = 284; + public const T_BOOLEAN_AND = 285; + public const T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG = 286; + public const T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG = 287; + public const T_IS_EQUAL = 288; + public const T_IS_NOT_EQUAL = 289; + public const T_IS_IDENTICAL = 290; + public const T_IS_NOT_IDENTICAL = 291; + public const T_SPACESHIP = 292; + public const T_IS_SMALLER_OR_EQUAL = 293; + public const T_IS_GREATER_OR_EQUAL = 294; + public const T_SL = 295; + public const T_SR = 296; + public const T_INSTANCEOF = 297; + public const T_INC = 298; + public const T_DEC = 299; + public const T_INT_CAST = 300; + public const T_DOUBLE_CAST = 301; + public const T_STRING_CAST = 302; + public const T_ARRAY_CAST = 303; + public const T_OBJECT_CAST = 304; + public const T_BOOL_CAST = 305; + public const T_UNSET_CAST = 306; + public const T_POW = 307; + public const T_NEW = 308; + public const T_CLONE = 309; + public const T_EXIT = 310; + public const T_IF = 311; + public const T_ELSEIF = 312; + public const T_ELSE = 313; + public const T_ENDIF = 314; + public const T_LNUMBER = 315; + public const T_DNUMBER = 316; + public const T_STRING = 317; + public const T_STRING_VARNAME = 318; + public const T_VARIABLE = 319; + public const T_NUM_STRING = 320; + public const T_INLINE_HTML = 321; + public const T_ENCAPSED_AND_WHITESPACE = 322; + public const T_CONSTANT_ENCAPSED_STRING = 323; + public const T_ECHO = 324; + public const T_DO = 325; + public const T_WHILE = 326; + public const T_ENDWHILE = 327; + public const T_FOR = 328; + public const T_ENDFOR = 329; + public const T_FOREACH = 330; + public const T_ENDFOREACH = 331; + public const T_DECLARE = 332; + public const T_ENDDECLARE = 333; + public const T_AS = 334; + public const T_SWITCH = 335; + public const T_MATCH = 336; + public const T_ENDSWITCH = 337; + public const T_CASE = 338; + public const T_DEFAULT = 339; + public const T_BREAK = 340; + public const T_CONTINUE = 341; + public const T_GOTO = 342; + public const T_FUNCTION = 343; + public const T_FN = 344; + public const T_CONST = 345; + public const T_RETURN = 346; + public const T_TRY = 347; + public const T_CATCH = 348; + public const T_FINALLY = 349; + public const T_USE = 350; + public const T_INSTEADOF = 351; + public const T_GLOBAL = 352; + public const T_STATIC = 353; + public const T_ABSTRACT = 354; + public const T_FINAL = 355; + public const T_PRIVATE = 356; + public const T_PROTECTED = 357; + public const T_PUBLIC = 358; + public const T_READONLY = 359; + public const T_VAR = 360; + public const T_UNSET = 361; + public const T_ISSET = 362; + public const T_EMPTY = 363; + public const T_HALT_COMPILER = 364; + public const T_CLASS = 365; + public const T_TRAIT = 366; + public const T_INTERFACE = 367; + public const T_ENUM = 368; + public const T_EXTENDS = 369; + public const T_IMPLEMENTS = 370; + public const T_OBJECT_OPERATOR = 371; + public const T_NULLSAFE_OBJECT_OPERATOR = 372; + public const T_LIST = 373; + public const T_ARRAY = 374; + public const T_CALLABLE = 375; + public const T_CLASS_C = 376; + public const T_TRAIT_C = 377; + public const T_METHOD_C = 378; + public const T_FUNC_C = 379; + public const T_LINE = 380; + public const T_FILE = 381; + public const T_START_HEREDOC = 382; + public const T_END_HEREDOC = 383; + public const T_DOLLAR_OPEN_CURLY_BRACES = 384; + public const T_CURLY_OPEN = 385; + public const T_PAAMAYIM_NEKUDOTAYIM = 386; + public const T_NAMESPACE = 387; + public const T_NS_C = 388; + public const T_DIR = 389; + public const T_NS_SEPARATOR = 390; + public const T_ELLIPSIS = 391; + public const T_NAME_FULLY_QUALIFIED = 392; + public const T_NAME_QUALIFIED = 393; + public const T_NAME_RELATIVE = 394; + public const T_ATTRIBUTE = 395; + + protected int $tokenToSymbolMapSize = 396; + protected int $actionTableSize = 1257; + protected int $gotoTableSize = 657; + + protected int $invalidSymbol = 168; + protected int $errorSymbol = 1; + protected int $defaultAction = -32766; + protected int $unexpectedTokenRule = 32767; + + protected int $YY2TBLSTATE = 435; + protected int $numNonLeafStates = 739; + + protected array $symbolToName = array( + "EOF", + "error", + "T_THROW", + "T_INCLUDE", + "T_INCLUDE_ONCE", + "T_EVAL", + "T_REQUIRE", + "T_REQUIRE_ONCE", + "','", + "T_LOGICAL_OR", + "T_LOGICAL_XOR", + "T_LOGICAL_AND", + "T_PRINT", + "T_YIELD", + "T_DOUBLE_ARROW", + "T_YIELD_FROM", + "'='", + "T_PLUS_EQUAL", + "T_MINUS_EQUAL", + "T_MUL_EQUAL", + "T_DIV_EQUAL", + "T_CONCAT_EQUAL", + "T_MOD_EQUAL", + "T_AND_EQUAL", + "T_OR_EQUAL", + "T_XOR_EQUAL", + "T_SL_EQUAL", + "T_SR_EQUAL", + "T_POW_EQUAL", + "T_COALESCE_EQUAL", + "'?'", + "':'", + "T_COALESCE", + "T_BOOLEAN_OR", + "T_BOOLEAN_AND", + "'|'", + "'^'", + "T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG", + "T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG", + "T_IS_EQUAL", + "T_IS_NOT_EQUAL", + "T_IS_IDENTICAL", + "T_IS_NOT_IDENTICAL", + "T_SPACESHIP", + "'<'", + "T_IS_SMALLER_OR_EQUAL", + "'>'", + "T_IS_GREATER_OR_EQUAL", + "'.'", + "T_SL", + "T_SR", + "'+'", + "'-'", + "'*'", + "'/'", + "'%'", + "'!'", + "T_INSTANCEOF", + "'~'", + "T_INC", + "T_DEC", + "T_INT_CAST", + "T_DOUBLE_CAST", + "T_STRING_CAST", + "T_ARRAY_CAST", + "T_OBJECT_CAST", + "T_BOOL_CAST", + "T_UNSET_CAST", + "'@'", + "T_POW", + "'['", + "T_NEW", + "T_CLONE", + "T_EXIT", + "T_IF", + "T_ELSEIF", + "T_ELSE", + "T_ENDIF", + "T_LNUMBER", + "T_DNUMBER", + "T_STRING", + "T_STRING_VARNAME", + "T_VARIABLE", + "T_NUM_STRING", + "T_INLINE_HTML", + "T_ENCAPSED_AND_WHITESPACE", + "T_CONSTANT_ENCAPSED_STRING", + "T_ECHO", + "T_DO", + "T_WHILE", + "T_ENDWHILE", + "T_FOR", + "T_ENDFOR", + "T_FOREACH", + "T_ENDFOREACH", + "T_DECLARE", + "T_ENDDECLARE", + "T_AS", + "T_SWITCH", + "T_MATCH", + "T_ENDSWITCH", + "T_CASE", + "T_DEFAULT", + "T_BREAK", + "T_CONTINUE", + "T_GOTO", + "T_FUNCTION", + "T_FN", + "T_CONST", + "T_RETURN", + "T_TRY", + "T_CATCH", + "T_FINALLY", + "T_USE", + "T_INSTEADOF", + "T_GLOBAL", + "T_STATIC", + "T_ABSTRACT", + "T_FINAL", + "T_PRIVATE", + "T_PROTECTED", + "T_PUBLIC", + "T_READONLY", + "T_VAR", + "T_UNSET", + "T_ISSET", + "T_EMPTY", + "T_HALT_COMPILER", + "T_CLASS", + "T_TRAIT", + "T_INTERFACE", + "T_ENUM", + "T_EXTENDS", + "T_IMPLEMENTS", + "T_OBJECT_OPERATOR", + "T_NULLSAFE_OBJECT_OPERATOR", + "T_LIST", + "T_ARRAY", + "T_CALLABLE", + "T_CLASS_C", + "T_TRAIT_C", + "T_METHOD_C", + "T_FUNC_C", + "T_LINE", + "T_FILE", + "T_START_HEREDOC", + "T_END_HEREDOC", + "T_DOLLAR_OPEN_CURLY_BRACES", + "T_CURLY_OPEN", + "T_PAAMAYIM_NEKUDOTAYIM", + "T_NAMESPACE", + "T_NS_C", + "T_DIR", + "T_NS_SEPARATOR", + "T_ELLIPSIS", + "T_NAME_FULLY_QUALIFIED", + "T_NAME_QUALIFIED", + "T_NAME_RELATIVE", + "T_ATTRIBUTE", + "';'", + "']'", + "'('", + "')'", + "'{'", + "'}'", + "'`'", + "'\"'", + "'$'" + ); + + protected array $tokenToSymbol = array( + 0, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 56, 166, 168, 167, 55, 168, 168, + 161, 162, 53, 51, 8, 52, 48, 54, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 31, 159, + 44, 16, 46, 30, 68, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 70, 168, 160, 36, 168, 165, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 163, 35, 164, 58, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, + 168, 168, 168, 168, 168, 168, 1, 2, 3, 4, + 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 32, 33, 34, 37, 38, 39, 40, + 41, 42, 43, 45, 47, 49, 50, 57, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 69, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, + 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, + 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, + 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, + 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, + 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, + 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, + 153, 154, 155, 156, 157, 158 + ); + + protected array $action = array( + 133, 134, 135, 582, 136, 137, 0, 751, 752, 753, + 138, 38, 327,-32766,-32766,-32766,-32766,-32766,-32766, 837, + 826,-32767,-32767,-32767,-32767, 102, 103, 104, 1112, 1113, + 1114, 1111, 1110, 1109, 1115, 745, 744,-32766, 1027,-32766, + -32766,-32766,-32766,-32766,-32766,-32766,-32767,-32767,-32767,-32767, + -32767, 1245,-32766,-32766, 1322, 754, 1112, 1113, 1114, 1111, + 1110, 1109, 1115, 459, 460, 461, 2, 990, 1306, 265, + 139, 404, 758, 759, 760, 761, 467, 468, 429, 835, + 606, -16, 1341, 23, 292, 815, 762, 763, 764, 765, + 766, 767, 768, 769, 770, 771, 791, 583, 792, 793, + 794, 795, 783, 784, 345, 346, 786, 787, 772, 773, + 774, 776, 777, 778, 356, 818, 819, 820, 821, 822, + 584, 779, 780, 585, 586, 941, 803, 801, 802, 814, + 798, 799, 835, 826, 587, 588, 797, 589, 590, 591, + 592, 593, 594, -328, 36, 251, 35, -194, 800, 595, + 596, -193, 140, -85, 133, 134, 135, 582, 136, 137, + 1060, 751, 752, 753, 138, 38, 129, -110, -110, -585, + -32766, -585, -110,-32766,-32766,-32766, 241, 836, -110, 145, + 959, 960,-32766,-32766,-32766, 961, -594,-32766, 482, 745, + 744, 955, 1036, -594,-32766, 991,-32766,-32766,-32766,-32766, + -32766,-32766,-32766,-32766,-32766,-32766,-32766,-32766, 299, 754, + 831, 75,-32766,-32766,-32766, 291, 142, 326, 242, -85, + 326, 382, 381, 265, 139, 404, 758, 759, 760, 761, + 82, 423, 429,-32766, 326,-32766,-32766,-32766,-32766, 815, + 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, + 791, 583, 792, 793, 794, 795, 783, 784, 345, 346, + 786, 787, 772, 773, 774, 776, 777, 778, 356, 818, + 819, 820, 821, 822, 584, 779, 780, 585, 586, 254, + 803, 801, 802, 814, 798, 799, 832, 725, 587, 588, + 797, 589, 590, 591, 592, 593, 594, -328, 83, 84, + 85, -194, 800, 595, 596, -193, 149, 775, 746, 747, + 748, 749, 750, 151, 751, 752, 753, 788, 789, 37, + 483, 86, 87, 88, 89, 90, 91, 92, 93, 94, + 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, -594, 274, -594,-32766,-32766, + -32766,-32766,-32766,-32766, 310, 1089, 127, 312, 110, 737, + 1326, 21, 754,-32766,-32766,-32766, -272, 1325,-32766,-32766, + 1088,-32766,-32766,-32766,-32766,-32766, 755, 756, 757, 758, + 759, 760, 761, 1104,-32766, 824,-32766,-32766, -545, 429, + 1036, 323, 815, 762, 763, 764, 765, 766, 767, 768, + 769, 770, 771, 791, 813, 792, 793, 794, 795, 783, + 784, 785, 812, 786, 787, 772, 773, 774, 776, 777, + 778, 817, 818, 819, 820, 821, 822, 823, 779, 780, + 781, 782, 1033, 803, 801, 802, 814, 798, 799, 745, + 744, 790, 796, 797, 804, 805, 807, 806, 808, 809, + 152,-32766, -545, -545, 1036, 800, 811, 810, 50, 51, + 52, 513, 53, 54, 1240, 1239, 1241, -545, 55, 56, + -110, 57,-32766, 1090, 920, -110, 556, -110, 292, -551, + 339, -545, 306, 103, 104, -110, -110, -110, -110, -110, + -110, -110, -110, 105, 106, 107, 108, 109, 1245, 274, + 380, 381, -591, -367, 715, -367, 340, 58, 59, -591, + 423, 110, 60, 370, 61, 248, 249, 62, 63, 64, + 65, 66, 67, 68, 69, -544, 28, 267, 70, 445, + 514,-32766, 374, -342, 1272, 1273, 515, 1278, 835, 862, + 389, 863, 1270, 42, 25, 516, 943, 517, 943, 518, + 920, 519, 299, 1036, 520, 521, 1266, 910, 441, 44, + 45, 446, 377, 376,-32766, 46, 522, 1023, 1022, 1021, + 1024, 368, 338, 391, 1238, 7, 291, 442, 1231, 835, + 524, 525, 526, 443, 1245, 357, 1036, 362, 834, -544, + -544, 154, 528, 529, 444, 1259, 1260, 1261, 1262, 1256, + 1257, 298,-32766,-32766, -544, -548, 1059, 1263, 1258, 291, + 1236, 1240, 1239, 1241, 299, 841, -550, 71, -544, 656, + 26, 321, 322, 326, -153, -153, -153, 920, 612, 675, + 676, 1035, 922, 910,-32766, 286, 710, 835, 155, -153, + 828, -153, 862, -153, 863, -153, 150, 407, 156, 1240, + 1239, 1241,-32766,-32766,-32766, 375, 1351, 716, 75, 1352, + 158, -591, 33, -591, 326, 835, 959, 960, -78, -548, + -548, 523, 920,-32766, 378, 379, 896, 955, -110, -110, + -110, 32, 111, 112, 113, 114, 115, 116, 117, 118, + 119, 120, 121, 122, 123, 745, 744, -58, -548, -57, + -110, -110, 717, 745, 744, -110, 383, 384, 922, 1033, + 910, -110, 710, -153, 647, 648, 830, 124, 141, 125, + -32766, 1033, 326, 712, 1150, 1152, 48, 130, 131, 144, + 159, 1036,-32766, 160, 161, -543, 28, 162, 1238, 920, + 163, 299, 920, 1036, 75,-32766,-32766,-32766, 835,-32766, + 326,-32766, 1270,-32766, 282, 910,-32766, -87, -84, -78, + -73,-32766,-32766,-32766, -4, 920, 282,-32766,-32766, 720, + -72, -71, 727,-32766, 420, -70, -69, -68, -67, -66, + 287, 286,-32766, -65, -46, 922, 745, 744, 1231, 710, + 300, 301, -546, -18, 148, -302, 273, 283, 726, -543, + -543, 729, 528, 529, 920, 1259, 1260, 1261, 1262, 1256, + 1257, 919, 74, 147, -543, 288, 293, 1263, 1258, 126, + -298, 280, 910,-32766, 281, 910, 284, 73, -543, 1238, + 976, 690, 322, 326, 710, 285,-32766,-32766,-32766, 332, + -32766, 274,-32766, 294,-32766, 937, 110,-32766, 910, 685, + 835, -543,-32766,-32766,-32766, 826, -546, -546,-32766,-32766, + 146,-32766, -50, 701,-32766, 420, 703, 691, 20, 1119, + 375, -546, 436,-32766, 645, 1353, 1277, 297, 657,-32766, + 1279, 959, 960, 561, 956, -546, 523, 910, 692, 693, + 678, 527, 955, -110, -110, -110, 132, 922, 662, 663, + 922, 710, 464, -508, 710,-32766, 1240, 1239, 1241, 493, + 679, 1238, 282, 939, 10, -543, -543, 40,-32766,-32766, + -32766, 731,-32766, 922,-32766, 307,-32766, 710, -4,-32766, + -543, 305, 41, 304,-32766,-32766,-32766, 0, 0,-32766, + -32766,-32766, 920, 0, -543, 1238,-32766, 420, 311, 0, + 567, 299,-32766,-32766,-32766,-32766,-32766, -498,-32766, 897, + -32766, 0, 922,-32766, 8, 0, 710, 24,-32766,-32766, + -32766,-32766, 372, 610,-32766,-32766, 834, 1238, 734, -275, + -32766, 420, 920, 735,-32766,-32766,-32766, 854,-32766,-32766, + -32766, 901,-32766, 1000, 977,-32766, 49, 984, 974, 488, + -32766,-32766,-32766,-32766, 985, 899,-32766,-32766, 972, 1238, + 574, 1093,-32766, 420, 1096, 1097,-32766,-32766,-32766, 1094, + -32766,-32766,-32766, 1095,-32766, 910, 1101,-32766, 1267, 846, + 1292, 1310,-32766,-32766,-32766, 1344, 650, 34,-32766,-32766, + -579, -250, -250, -250,-32766, 420, -578, 375, -577, -551, + 28, 267, -550,-32766, -549, -492, 1, 29, 959, 960, + 302, 303, 835, 523, 30, 910, 1270, 39, 896, 955, + -110, -110, -110, 43, 47, 373, 72, 76, 77, 78, + 79, -249, -249, -249, 80, 81, 143, 375, 153, 128, + -273, 157, 247, 328, 357, 358, 359, 360, 959, 960, + 922, 361, 1231, 523, 710, -250, 362, 363, 896, 955, + -110, -110, -110, 364, 365, 366, 367, 529, 28, 1259, + 1260, 1261, 1262, 1256, 1257, 369, 437, 555, 1207, -272, + 835, 1263, 1258, 13, 1270, 14,-32766, 15, 16, 18, + 922, 73, 1238, 1348, 710, -249, 322, 326, 406,-32766, + -32766,-32766, 484,-32766, 485,-32766, 492,-32766, 495, 496, + -32766, 497, 498, 502, 503,-32766,-32766,-32766, 504, 511, + 1231,-32766,-32766, 572, 696, 1249, 1190,-32766, 420, 1268, + 1062, 1061, 1042, 1226, 1038, 529,-32766, 1259, 1260, 1261, + 1262, 1256, 1257, -277, -102, 12, 17, 27, 296, 1263, + 1258, 405, 603, 607, 636, 702, 1194, 1244, 1191, 73, + 320, 1323, 0, 371, 322, 326, 711, 714, 718, 719, + 721, 722, 723, 724, 728, 0, 713, 0, 1350, 857, + 856, 865, 949, 992, 864, 1349, 948, 946, 947, 950, + 1222, 930, 940, 928, 982, 983, 634, 1347, 1304, 1293, + 1311, 1320, 0, 0, 1271, 0, 326 + ); + + protected array $actionCheck = array( + 2, 3, 4, 5, 6, 7, 0, 9, 10, 11, + 12, 13, 70, 9, 10, 11, 9, 10, 11, 1, + 80, 44, 45, 46, 47, 48, 49, 50, 116, 117, + 118, 119, 120, 121, 122, 37, 38, 30, 1, 32, + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 1, 9, 10, 1, 57, 116, 117, 118, 119, + 120, 121, 122, 129, 130, 131, 8, 31, 1, 71, + 72, 73, 74, 75, 76, 77, 134, 135, 80, 82, + 1, 31, 85, 8, 30, 87, 88, 89, 90, 91, + 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, + 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, + 122, 123, 124, 125, 126, 1, 128, 129, 130, 131, + 132, 133, 82, 80, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 8, 147, 148, 8, 8, 150, 151, + 152, 8, 154, 31, 2, 3, 4, 5, 6, 7, + 162, 9, 10, 11, 12, 13, 8, 117, 118, 160, + 116, 162, 122, 9, 10, 11, 97, 159, 128, 8, + 117, 118, 9, 10, 11, 122, 1, 137, 31, 37, + 38, 128, 138, 8, 30, 159, 32, 33, 34, 35, + 36, 37, 38, 30, 9, 32, 33, 34, 158, 57, + 80, 161, 9, 10, 11, 161, 163, 167, 14, 97, + 167, 106, 107, 71, 72, 73, 74, 75, 76, 77, + 163, 116, 80, 30, 167, 32, 33, 34, 35, 87, + 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, + 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 8, + 128, 129, 130, 131, 132, 133, 156, 163, 136, 137, + 138, 139, 140, 141, 142, 143, 144, 162, 9, 10, + 11, 162, 150, 151, 152, 162, 154, 2, 3, 4, + 5, 6, 7, 14, 9, 10, 11, 12, 13, 30, + 163, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, 54, 55, 160, 57, 162, 9, 10, + 11, 9, 10, 11, 8, 159, 14, 8, 69, 163, + 1, 101, 57, 9, 10, 11, 162, 8, 116, 30, + 1, 32, 33, 34, 35, 36, 71, 72, 73, 74, + 75, 76, 77, 123, 30, 80, 32, 33, 70, 80, + 138, 8, 87, 88, 89, 90, 91, 92, 93, 94, + 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, + 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, + 125, 126, 116, 128, 129, 130, 131, 132, 133, 37, + 38, 136, 137, 138, 139, 140, 141, 142, 143, 144, + 14, 116, 134, 135, 138, 150, 151, 152, 2, 3, + 4, 5, 6, 7, 155, 156, 157, 149, 12, 13, + 101, 15, 137, 164, 1, 106, 85, 108, 30, 161, + 8, 163, 113, 49, 50, 116, 117, 118, 119, 120, + 121, 122, 123, 51, 52, 53, 54, 55, 1, 57, + 106, 107, 1, 106, 31, 108, 8, 51, 52, 8, + 116, 69, 56, 8, 58, 59, 60, 61, 62, 63, + 64, 65, 66, 67, 68, 70, 70, 71, 72, 73, + 74, 116, 8, 164, 78, 79, 80, 146, 82, 106, + 8, 108, 86, 87, 88, 89, 122, 91, 122, 93, + 1, 95, 158, 138, 98, 99, 1, 84, 8, 103, + 104, 105, 106, 107, 116, 109, 110, 119, 120, 121, + 122, 115, 116, 106, 80, 108, 161, 8, 122, 82, + 124, 125, 126, 8, 1, 161, 138, 161, 155, 134, + 135, 14, 136, 137, 8, 139, 140, 141, 142, 143, + 144, 145, 51, 52, 149, 70, 1, 151, 152, 161, + 116, 155, 156, 157, 158, 8, 161, 161, 163, 75, + 76, 165, 166, 167, 75, 76, 77, 1, 52, 75, + 76, 137, 159, 84, 137, 30, 163, 82, 14, 90, + 80, 92, 106, 94, 108, 96, 101, 102, 14, 155, + 156, 157, 9, 10, 11, 106, 80, 31, 161, 83, + 14, 160, 14, 162, 167, 82, 117, 118, 16, 134, + 135, 122, 1, 30, 106, 107, 127, 128, 129, 130, + 131, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 37, 38, 16, 163, 16, + 117, 118, 31, 37, 38, 122, 106, 107, 159, 116, + 84, 128, 163, 164, 111, 112, 156, 16, 163, 16, + 137, 116, 167, 163, 59, 60, 70, 16, 16, 16, + 16, 138, 74, 16, 16, 70, 70, 16, 80, 1, + 16, 158, 1, 138, 161, 87, 88, 89, 82, 91, + 167, 93, 86, 95, 161, 84, 98, 31, 31, 31, + 31, 103, 104, 105, 0, 1, 161, 109, 110, 31, + 31, 31, 31, 115, 116, 31, 31, 31, 31, 31, + 37, 30, 124, 31, 31, 159, 37, 38, 122, 163, + 134, 135, 70, 31, 31, 35, 31, 31, 31, 134, + 135, 31, 136, 137, 1, 139, 140, 141, 142, 143, + 144, 31, 154, 31, 149, 37, 37, 151, 152, 163, + 35, 35, 84, 74, 35, 84, 35, 161, 163, 80, + 159, 80, 166, 167, 163, 35, 87, 88, 89, 35, + 91, 57, 93, 37, 95, 38, 69, 98, 84, 77, + 82, 70, 103, 104, 105, 80, 134, 135, 109, 110, + 70, 85, 31, 80, 115, 116, 92, 116, 97, 82, + 106, 149, 108, 124, 113, 83, 146, 113, 90, 137, + 146, 117, 118, 89, 128, 163, 122, 84, 137, 138, + 94, 127, 128, 129, 130, 131, 31, 159, 96, 100, + 159, 163, 97, 149, 163, 74, 155, 156, 157, 97, + 100, 80, 161, 154, 150, 134, 135, 159, 87, 88, + 89, 164, 91, 159, 93, 114, 95, 163, 164, 98, + 149, 133, 159, 132, 103, 104, 105, -1, -1, 74, + 109, 110, 1, -1, 163, 80, 115, 116, 132, -1, + 153, 158, 87, 88, 89, 124, 91, 149, 93, 164, + 95, -1, 159, 98, 149, -1, 163, 149, 103, 104, + 105, 74, 149, 153, 109, 110, 155, 80, 159, 162, + 115, 116, 1, 159, 87, 88, 89, 159, 91, 124, + 93, 159, 95, 159, 159, 98, 70, 159, 159, 102, + 103, 104, 105, 74, 159, 159, 109, 110, 159, 80, + 81, 159, 115, 116, 159, 159, 87, 88, 89, 159, + 91, 124, 93, 159, 95, 84, 159, 98, 160, 160, + 160, 160, 103, 104, 105, 160, 160, 163, 109, 110, + 161, 100, 101, 102, 115, 116, 161, 106, 161, 161, + 70, 71, 161, 124, 161, 161, 161, 161, 117, 118, + 134, 135, 82, 122, 161, 84, 86, 161, 127, 128, + 129, 130, 131, 161, 161, 149, 161, 161, 161, 161, + 161, 100, 101, 102, 161, 161, 161, 106, 161, 163, + 162, 161, 161, 161, 161, 161, 161, 161, 117, 118, + 159, 161, 122, 122, 163, 164, 161, 161, 127, 128, + 129, 130, 131, 161, 161, 161, 161, 137, 70, 139, + 140, 141, 142, 143, 144, 161, 161, 161, 165, 162, + 82, 151, 152, 162, 86, 162, 74, 162, 162, 162, + 159, 161, 80, 164, 163, 164, 166, 167, 162, 87, + 88, 89, 162, 91, 162, 93, 162, 95, 162, 162, + 98, 162, 162, 162, 162, 103, 104, 105, 162, 162, + 122, 109, 110, 162, 162, 162, 162, 115, 116, 162, + 162, 162, 162, 162, 162, 137, 124, 139, 140, 141, + 142, 143, 144, 162, 162, 162, 162, 162, 162, 151, + 152, 162, 162, 162, 162, 162, 162, 162, 162, 161, + 163, 162, -1, 163, 166, 167, 163, 163, 163, 163, + 163, 163, 163, 163, 163, -1, 163, -1, 164, 164, + 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, + 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, + 164, 164, -1, -1, 166, -1, 167 + ); + + protected array $actionBase = array( + 0, -2, 152, 549, 764, 941, 981, 751, 555, 309, + 560, 864, 626, 738, 738, 741, 738, 473, 671, 783, + -60, 305, 305, 783, 305, 803, 803, 803, 658, 658, + 658, 658, 749, 749, 897, 897, 929, 865, 831, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, 1062, + 1062, 1062, 1062, 1062, 18, 36, 79, 648, 1036, 1044, + 1040, 1045, 1034, 1033, 1039, 1041, 1046, 1083, 1084, 782, + 1085, 1086, 1082, 1087, 1042, 876, 1035, 1043, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 195, 342, 43, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 643, 643, + 643, 666, 666, 354, 173, 980, 203, 1048, 1048, 1048, + 1048, 1048, 1048, 1048, 1048, 1048, 665, 339, 164, 164, + 7, 7, 7, 7, 7, 50, 369, 583, -23, -23, + -23, -23, 448, 605, 497, 260, 397, 434, 54, 394, + 593, 593, 316, 316, 415, 415, 316, 316, 316, 442, + 442, 252, 252, 252, 252, 318, 455, 433, 391, 742, + 53, 53, 53, 53, 742, 742, 742, 742, 734, 1088, + 742, 742, 742, 722, 781, 781, 926, 551, 551, 781, + 536, -3, -3, 536, 63, -3, 67, 576, 335, 756, + 115, 9, 335, 535, 656, 501, 185, 821, 568, 821, + 1032, 424, 776, 776, 426, 753, 729, 867, 1063, 1049, + 799, 1080, 810, 1081, -66, -58, 728, 1031, 1031, 1031, + 1031, 1031, 1031, 1031, 1031, 1031, 1031, 1031, 1089, 402, + 1032, 130, 1089, 1089, 1089, 402, 402, 402, 402, 402, + 402, 402, 402, 402, 402, 603, 130, 544, 554, 130, + 804, 402, 18, 808, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 762, 157, 18, 36, 124, 124, + 196, 37, 124, 124, 124, 124, 18, 18, 18, 18, + 568, 784, 797, 600, 820, 143, 784, 784, 784, 122, + 135, 204, 139, 760, 785, 467, 775, 775, 787, 895, + 895, 775, 768, 775, 787, 913, 775, 775, 895, 895, + 793, 158, 550, 472, 524, 569, 895, 346, 775, 775, + 775, 775, 816, 575, 775, 271, 171, 775, 775, 816, + 801, 766, 58, 798, 895, 895, 895, 816, 505, 798, + 798, 798, 819, 824, 761, 765, 383, 349, 607, 138, + 807, 765, 765, 775, 532, 761, 765, 761, 765, 759, + 765, 765, 765, 761, 765, 768, 498, 765, 714, 586, + 75, 765, 6, 915, 916, 726, 917, 906, 918, 965, + 919, 923, 1053, 894, 931, 912, 924, 966, 903, 896, + 780, 701, 703, 815, 754, 893, 777, 777, 777, 888, + 777, 777, 777, 777, 777, 777, 777, 777, 701, 868, + 823, 794, 934, 711, 712, 1011, 730, 795, 963, 933, + 1013, 925, 758, 713, 977, 935, 757, 1047, 936, 940, + 986, 1014, 828, 1017, 979, 790, 1064, 1065, 869, 946, + 1054, 777, 915, 923, 727, 912, 924, 903, 896, 752, + 748, 746, 747, 745, 744, 739, 740, 763, 1018, 887, + 879, 870, 945, 891, 701, 871, 971, 874, 990, 992, + 1050, 805, 792, 875, 1066, 952, 953, 954, 1055, 1019, + 1056, 773, 973, 817, 994, 812, 1067, 996, 997, 999, + 1000, 1057, 1068, 1058, 885, 1059, 832, 788, 928, 802, + 1069, 299, 791, 800, 806, 964, 436, 932, 1060, 1070, + 1071, 1001, 1002, 1006, 1072, 1073, 927, 834, 975, 796, + 976, 967, 835, 838, 577, 779, 1020, 786, 789, 778, + 624, 634, 1074, 1075, 1076, 930, 767, 772, 839, 845, + 1021, 743, 1022, 1077, 646, 846, 717, 1078, 1012, 718, + 721, 652, 683, 681, 724, 774, 1061, 818, 811, 771, + 955, 721, 770, 849, 1079, 852, 855, 856, 1007, 860, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 456, 456, 456, 456, 456, 456, 305, 305, 305, 305, + 305, 456, 456, 456, 456, 456, 456, 456, 305, 305, + 0, 0, 305, 0, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, + 456, 456, 456, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, + 494, 494, 289, 289, 494, 289, 494, 494, 494, 494, + 494, 494, 494, 494, 494, 0, 289, 289, 289, 289, + 289, 289, 289, 289, 494, 793, 494, 442, 442, 442, + 442, 494, 494, 494, -88, -88, 442, 494, 63, 494, + 494, 494, 494, 494, 494, 494, 494, 494, 0, 0, + 494, 494, 494, 494, 0, 0, 130, -3, 494, 768, + 768, 768, 768, 494, 494, 494, 494, -3, -3, 494, + 494, 494, 0, 0, 0, 0, 442, 442, 0, 130, + 0, 0, 130, 0, 0, 768, 768, 494, 63, 793, + 359, 494, 0, 0, 0, 0, 130, 768, 130, 402, + 775, -3, -3, 775, 402, 402, 124, 18, 359, 545, + 545, 545, 545, 0, 0, 568, 793, 793, 793, 793, + 793, 793, 793, 793, 793, 793, 793, 768, 0, 793, + 0, 768, 768, 768, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 768, + 0, 0, 895, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 913, 0, 0, 0, 0, 0, 0, + 768, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 777, 805, 0, 805, 0, 777, 777, 777, 0, 0, + 0, 0, 779, 743 + ); + + protected array $actionDefault = array( + 3,32767, 102,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767, 100,32767,32767,32767,32767, 597, 597, + 597, 597,32767,32767, 254, 102,32767,32767, 470, 387, + 387, 387,32767,32767, 541, 541, 541, 541, 541, 541, + 32767,32767,32767,32767,32767,32767, 470,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767, 100, + 32767,32767,32767, 36, 7, 8, 10, 11, 49, 17, + 324,32767,32767,32767,32767, 102,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767, 590,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767, 474, 453, + 454, 456, 457, 386, 542, 596, 327, 593, 385, 145, + 339, 329, 242, 330, 258, 475, 259, 476, 479, 480, + 215, 287, 382, 149, 150, 417, 471, 419, 469, 473, + 418, 392, 398, 399, 400, 401, 402, 403, 404, 405, + 406, 407, 408, 409, 410, 390, 391, 472, 450, 449, + 448,32767,32767, 415, 416,32767, 420,32767,32767,32767, + 32767,32767,32767,32767, 102,32767, 389, 423, 421, 422, + 439, 440, 437, 438, 441,32767,32767,32767, 442, 443, + 444, 445, 316,32767,32767, 366, 364, 424, 316, 111, + 32767,32767,32767,32767,32767,32767,32767,32767,32767, 430, + 431,32767,32767,32767,32767, 535, 447,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 102,32767, 100, 537, 412, 414, 504, 425, 426, 393, + 32767, 511,32767, 102,32767, 513,32767,32767,32767,32767, + 32767,32767,32767, 536,32767, 543, 543,32767, 497, 100, + 195,32767,32767, 512,32767, 195, 195,32767,32767,32767, + 32767,32767,32767,32767,32767, 604, 497, 110, 110, 110, + 110, 110, 110, 110, 110, 110, 110, 110,32767, 195, + 110,32767,32767,32767, 100, 195, 195, 195, 195, 195, + 195, 195, 195, 195, 195, 190,32767, 268, 270, 102, + 558, 195,32767, 516,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767, 509,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 497, 435, 138,32767, 138, 543, 427, 428, 429, 499, + 543, 543, 543, 312, 289,32767,32767,32767,32767, 514, + 514, 100, 100, 100, 100, 509,32767,32767,32767,32767, + 111, 99, 99, 99, 99, 99, 103, 101,32767,32767, + 32767,32767, 223, 99,32767, 101, 101,32767,32767, 223, + 225, 212, 101, 227,32767, 562, 563, 223, 101, 227, + 227, 227, 247, 247, 486, 318, 101, 99, 101, 101, + 197, 318, 318,32767, 101, 486, 318, 486, 318, 199, + 318, 318, 318, 486, 318,32767, 101, 318, 214, 99, + 99, 318,32767,32767,32767, 499,32767,32767,32767,32767, + 32767,32767,32767, 222,32767,32767,32767,32767,32767,32767, + 32767,32767, 530,32767, 547, 560, 433, 434, 436, 545, + 458, 459, 460, 461, 462, 463, 464, 466, 592,32767, + 503,32767,32767,32767, 338,32767, 602,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767, 603,32767, 543,32767,32767,32767, + 32767, 432, 9, 74, 492, 42, 43, 51, 57, 520, + 521, 522, 523, 517, 518, 524, 519,32767,32767, 525, + 568,32767,32767, 544, 595,32767,32767,32767,32767,32767, + 32767, 138,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767, 530,32767, 136,32767,32767,32767,32767, + 32767,32767,32767,32767, 526,32767,32767,32767, 543,32767, + 32767,32767,32767, 314, 311,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767, 543,32767,32767,32767,32767,32767, 291,32767, 308, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 32767,32767,32767,32767,32767,32767, 286,32767,32767, 381, + 499, 294, 296, 297,32767,32767,32767,32767, 360,32767, + 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, + 152, 152, 3, 3, 341, 152, 152, 152, 341, 341, + 152, 341, 341, 341, 152, 152, 152, 152, 152, 152, + 280, 185, 262, 265, 247, 247, 152, 352, 152 + ); + + protected array $goto = array( + 196, 196, 1034, 1065, 697, 431, 661, 621, 658, 319, + 706, 425, 314, 315, 335, 576, 430, 336, 432, 638, + 654, 655, 852, 672, 673, 674, 853, 167, 167, 167, + 167, 221, 197, 193, 193, 177, 179, 216, 193, 193, + 193, 193, 193, 194, 194, 194, 194, 194, 194, 188, + 189, 190, 191, 192, 218, 216, 219, 536, 537, 421, + 538, 540, 541, 542, 543, 544, 545, 546, 547, 1136, + 168, 169, 170, 195, 171, 172, 173, 166, 174, 175, + 176, 178, 215, 217, 220, 238, 243, 244, 246, 257, + 258, 259, 260, 261, 262, 263, 264, 268, 269, 270, + 271, 277, 289, 290, 317, 318, 426, 427, 428, 581, + 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 180, 237, 181, 198, 199, + 200, 239, 188, 189, 190, 191, 192, 218, 1136, 201, + 182, 183, 184, 202, 198, 185, 240, 203, 201, 165, + 204, 205, 186, 206, 207, 208, 187, 209, 210, 211, + 212, 213, 214, 855, 1232, 975, 279, 279, 279, 279, + 623, 623, 419, 351, 1269, 600, 1269, 1269, 1269, 1269, + 1269, 1269, 1269, 1269, 1269, 1287, 1287, 599, 1100, 1287, + 709, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, + 508, 700, 827, 1098, 458, 559, 552, 860, 833, 909, + 904, 905, 918, 861, 906, 858, 907, 908, 859, 1233, + 1234, 912, 500, 886, 501, 252, 252, 843, 1107, 1108, + 507, 1087, 1082, 1083, 1084, 341, 552, 559, 568, 569, + 344, 579, 602, 616, 617, 1235, 1295, 1296, 833, 440, + 833, 22, 250, 250, 250, 250, 245, 253, 694, 573, + 1237, 829, 1237, 893, 851, 893, 893, 1034, 1034, 1237, + 694, 349, 342, 1034, 694, 1034, 1034, 1034, 1034, 1034, + 1034, 1034, 1034, 1034, 848, 1327, 1034, 1034, 1034, 1034, + 1319, 1319, 1319, 1319, 1237, 343, 342, 1040, 1039, 1237, + 1237, 1237, 1237, 868, 996, 1237, 1237, 1237, 913, 355, + 914, 354, 354, 354, 354, 466, 466, 479, 880, 355, + 355, 867, 394, 926, 466, 481, 571, 927, 967, 410, + 705, 942, 355, 355, 942, 848, 355, 660, 1354, 609, + 624, 627, 628, 629, 630, 651, 652, 653, 708, 554, + 1133, 1285, 1285, 355, 355, 1285, 1058, 1285, 1285, 1285, + 1285, 1285, 1285, 1285, 1285, 1285, 539, 539, 1185, 424, + 539, 611, 539, 539, 539, 539, 539, 539, 539, 539, + 539, 566, 682, 1337, 1337, 733, 637, 639, 1043, 1044, + 659, 476, 1312, 1313, 683, 687, 1010, 695, 704, 1006, + 1337, 1298, 438, 408, 409, 631, 633, 635, 670, 5, + 671, 6, 412, 413, 414, 337, 684, 1340, 1340, 415, + 325, 309, 686, 347, 352, 353, 553, 563, 450, 450, + 450, 553, 1309, 563, 1309, 666, 397, 462, 845, 1314, + 1315, 1309, 548, 548, 548, 548, 873, 604, 469, 580, + 470, 471, 403, 554, 878, 848, 958, 1345, 1346, 577, + 614, 870, 550, 615, 550, 255, 255, 1321, 1321, 1321, + 1321, 550, 999, 1018, 477, 971, 1228, 732, 736, 881, + 869, 1070, 1074, 876, 882, 551, 1008, 1003, 1071, 1075, + 978, 980, 0, 1305, 1118, 0, 456, 0, 0, 0, + 0, 969, 969, 969, 969, 0, 0, 456, 963, 970, + 0, 0, 0, 0, 968, 0, 1230, 0, 0, 0, + 450, 450, 450, 450, 450, 450, 450, 450, 450, 450, + 450, 931, 1123, 450, 0, 1073, 1116, 885, 619, 1307, + 1307, 1073, 1216, 944, 1015, 433, 1217, 1220, 945, 1221, + 0, 433, 872, 0, 664, 994, 0, 1041, 1041, 0, + 866, 0, 0, 0, 665, 1052, 1048, 1049, 0, 0, + 0, 0, 1227, 324, 275, 324, 1037, 1037, 681, 952, + 0, 0, 1029, 1045, 1046, 396, 399, 560, 601, 605, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1013, 1013 + ); + + protected array $gotoCheck = array( + 42, 42, 73, 127, 73, 66, 66, 56, 56, 66, + 9, 66, 66, 66, 66, 66, 66, 66, 66, 66, + 86, 86, 26, 86, 86, 86, 27, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 15, 20, 49, 23, 23, 23, 23, + 108, 108, 43, 97, 108, 130, 108, 108, 108, 108, + 108, 108, 108, 108, 108, 170, 170, 8, 8, 170, + 8, 170, 170, 170, 170, 170, 170, 170, 170, 170, + 8, 8, 6, 8, 83, 76, 76, 15, 12, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 20, + 20, 15, 155, 45, 155, 5, 5, 20, 144, 144, + 155, 15, 15, 15, 15, 76, 76, 76, 76, 76, + 76, 76, 76, 76, 76, 20, 20, 20, 12, 83, + 12, 76, 5, 5, 5, 5, 5, 5, 7, 172, + 73, 7, 73, 25, 25, 25, 25, 73, 73, 73, + 7, 179, 168, 73, 7, 73, 73, 73, 73, 73, + 73, 73, 73, 73, 22, 181, 73, 73, 73, 73, + 9, 9, 9, 9, 73, 168, 168, 118, 118, 73, + 73, 73, 73, 35, 103, 73, 73, 73, 65, 14, + 65, 24, 24, 24, 24, 149, 149, 84, 35, 14, + 14, 35, 62, 73, 149, 84, 104, 73, 93, 93, + 93, 9, 14, 14, 9, 22, 14, 64, 14, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 14, + 150, 171, 171, 14, 14, 171, 114, 171, 171, 171, + 171, 171, 171, 171, 171, 171, 173, 173, 151, 13, + 173, 13, 173, 173, 173, 173, 173, 173, 173, 173, + 173, 48, 116, 182, 182, 48, 48, 48, 119, 119, + 48, 176, 176, 176, 48, 48, 48, 48, 48, 48, + 182, 14, 113, 82, 82, 85, 85, 85, 82, 46, + 82, 46, 82, 82, 82, 29, 82, 182, 182, 82, + 169, 169, 14, 82, 97, 97, 9, 9, 23, 23, + 23, 9, 130, 9, 130, 120, 9, 9, 18, 178, + 178, 130, 107, 107, 107, 107, 39, 107, 9, 9, + 9, 9, 28, 14, 9, 22, 92, 9, 9, 2, + 2, 37, 19, 80, 19, 5, 5, 130, 130, 130, + 130, 19, 50, 110, 157, 50, 160, 50, 99, 16, + 16, 16, 16, 9, 41, 50, 50, 50, 129, 132, + 16, 96, -1, 130, 147, -1, 19, -1, -1, -1, + -1, 19, 19, 19, 19, -1, -1, 19, 19, 19, + -1, -1, -1, -1, 16, -1, 14, -1, -1, -1, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 17, 17, 23, -1, 130, 16, 16, 17, 130, + 130, 130, 79, 79, 17, 117, 79, 79, 79, 79, + -1, 117, 17, -1, 17, 17, -1, 117, 117, -1, + 17, -1, -1, -1, 117, 117, 117, 117, -1, -1, + -1, -1, 17, 24, 24, 24, 89, 89, 89, 89, + -1, -1, 89, 89, 89, 59, 59, 59, 59, 59, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 107, 107 + ); + + protected array $gotoBase = array( + 0, 0, -253, 0, 0, 224, 182, 251, 179, -10, + 0, 0, -89, 32, 11, -185, 27, 66, 128, 197, + -229, 0, 5, 163, 308, 260, 18, 22, 115, 118, + 0, 0, 0, 0, 0, -68, 0, 122, 0, 123, + 0, 43, -1, 153, 0, 200, -327, 0, -330, 147, + 460, 0, 0, 0, 0, 0, -33, 0, 0, 540, + 0, 0, 280, 0, 95, 294, -236, 0, 0, 0, + 0, 0, 0, -5, 0, 0, -140, 0, 0, 134, + 119, -19, -88, -75, -152, -74, -698, 0, 0, 296, + 0, 0, 127, 23, 0, 0, 48, -310, 0, 71, + 0, 0, 0, 269, 283, 0, 0, 414, -71, 0, + 103, 0, 0, 124, 83, 0, 100, 273, 17, 104, + 144, 0, 0, 0, 0, 0, 0, 1, 0, 114, + 167, 0, 47, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, -47, 0, 0, 50, 0, 281, + 105, 94, 0, 0, 0, -273, 0, 34, 0, 0, + 107, 0, 0, 0, 0, 0, 0, 0, -26, 99, + -56, 110, 230, 125, 0, 0, 90, 0, 67, 241, + 0, 254, 75, 0, 0 + ); + + protected array $gotoDefault = array( + -32768, 512, 740, 4, 741, 935, 816, 825, 597, 530, + 707, 348, 625, 422, 1303, 911, 1122, 578, 844, 1246, + 1254, 457, 847, 330, 730, 923, 894, 895, 400, 386, + 392, 398, 649, 626, 494, 879, 453, 871, 486, 874, + 452, 883, 164, 418, 510, 887, 3, 890, 557, 921, + 973, 387, 898, 388, 677, 900, 562, 902, 903, 395, + 401, 402, 1127, 570, 622, 915, 256, 564, 916, 385, + 917, 925, 390, 393, 688, 465, 505, 499, 411, 1102, + 565, 608, 646, 447, 473, 620, 632, 618, 480, 434, + 416, 329, 957, 965, 487, 463, 979, 350, 987, 738, + 1135, 640, 489, 995, 641, 1002, 1005, 531, 532, 478, + 1017, 272, 1020, 490, 19, 667, 1031, 1032, 668, 642, + 1054, 643, 669, 644, 1056, 472, 598, 1064, 454, 1072, + 1291, 455, 1076, 266, 1079, 278, 417, 435, 1085, 1086, + 9, 1092, 698, 699, 11, 276, 509, 1117, 689, 451, + 1134, 439, 1204, 1206, 558, 491, 1224, 1223, 680, 506, + 1229, 448, 1294, 449, 533, 474, 316, 534, 1338, 308, + 333, 313, 549, 295, 334, 535, 475, 1300, 1308, 331, + 31, 1328, 1339, 575, 613 + ); + + protected array $ruleToNonTerminal = array( + 0, 1, 3, 3, 2, 5, 5, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, + 7, 7, 7, 7, 7, 8, 8, 9, 10, 11, + 11, 11, 12, 12, 13, 13, 14, 15, 15, 16, + 16, 17, 17, 18, 18, 21, 21, 22, 23, 23, + 24, 24, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 29, 29, 30, 30, 32, 34, 34, + 28, 36, 36, 33, 38, 38, 35, 35, 37, 37, + 39, 39, 31, 40, 40, 41, 43, 44, 44, 45, + 45, 46, 46, 48, 47, 47, 47, 47, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, + 49, 49, 25, 25, 50, 69, 69, 72, 72, 71, + 70, 70, 63, 75, 75, 76, 76, 77, 77, 78, + 78, 79, 79, 80, 80, 26, 26, 27, 27, 27, + 27, 27, 88, 88, 90, 90, 83, 83, 91, 91, + 92, 92, 92, 84, 84, 87, 87, 85, 85, 93, + 94, 94, 57, 57, 65, 65, 68, 68, 68, 67, + 95, 95, 96, 58, 58, 58, 58, 97, 97, 98, + 98, 99, 99, 100, 101, 101, 102, 102, 103, 103, + 55, 55, 51, 51, 105, 53, 53, 106, 52, 52, + 54, 54, 64, 64, 64, 64, 81, 81, 109, 109, + 111, 111, 112, 112, 112, 112, 110, 110, 110, 114, + 114, 114, 114, 89, 89, 117, 117, 117, 118, 118, + 115, 115, 119, 119, 121, 121, 122, 122, 116, 123, + 123, 120, 124, 124, 124, 124, 113, 113, 82, 82, + 82, 20, 20, 20, 126, 125, 125, 127, 127, 127, + 127, 60, 128, 128, 129, 61, 131, 131, 132, 132, + 133, 133, 86, 134, 134, 134, 134, 134, 134, 134, + 139, 139, 140, 140, 141, 141, 141, 141, 141, 142, + 143, 143, 138, 138, 135, 135, 137, 137, 145, 145, + 144, 144, 144, 144, 144, 144, 144, 136, 146, 146, + 148, 147, 147, 62, 104, 149, 149, 56, 56, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 156, 150, 150, 155, 155, 158, 159, + 159, 160, 161, 162, 162, 162, 162, 19, 19, 73, + 73, 73, 73, 151, 151, 151, 151, 164, 164, 152, + 152, 154, 154, 154, 157, 157, 170, 170, 170, 170, + 170, 170, 170, 170, 170, 171, 171, 171, 108, 173, + 173, 173, 173, 153, 153, 153, 153, 153, 153, 153, + 153, 59, 59, 167, 167, 167, 167, 174, 174, 163, + 163, 163, 175, 175, 175, 175, 175, 175, 74, 74, + 66, 66, 66, 66, 130, 130, 130, 130, 178, 177, + 166, 166, 166, 166, 166, 166, 166, 165, 165, 165, + 176, 176, 176, 176, 107, 172, 180, 180, 179, 179, + 181, 181, 181, 181, 181, 181, 181, 181, 169, 169, + 169, 169, 168, 183, 182, 182, 182, 182, 182, 182, + 182, 182, 184, 184, 184, 184 + ); + + protected array $ruleToLength = array( + 1, 1, 2, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, + 1, 0, 1, 1, 2, 1, 3, 4, 1, 2, + 0, 1, 1, 1, 1, 4, 3, 5, 4, 3, + 4, 2, 3, 1, 1, 7, 6, 2, 3, 1, + 2, 3, 1, 2, 3, 1, 1, 3, 1, 3, + 1, 2, 2, 3, 1, 3, 2, 3, 1, 3, + 3, 2, 0, 1, 1, 1, 1, 1, 3, 7, + 10, 5, 7, 9, 5, 3, 3, 3, 3, 3, + 3, 1, 2, 5, 7, 9, 6, 5, 6, 3, + 2, 1, 1, 1, 1, 0, 2, 1, 3, 8, + 0, 4, 2, 1, 3, 0, 1, 0, 1, 0, + 1, 3, 1, 1, 1, 8, 9, 7, 8, 7, + 6, 8, 0, 2, 0, 2, 1, 2, 1, 2, + 1, 1, 1, 0, 2, 0, 2, 0, 2, 2, + 1, 3, 1, 4, 1, 4, 1, 1, 4, 2, + 1, 3, 3, 3, 4, 4, 5, 0, 2, 4, + 3, 1, 1, 7, 0, 2, 1, 3, 3, 4, + 1, 4, 0, 2, 5, 0, 2, 6, 0, 2, + 0, 3, 1, 2, 1, 1, 2, 0, 1, 3, + 0, 2, 1, 1, 1, 1, 6, 8, 6, 1, + 2, 1, 1, 1, 1, 1, 1, 1, 1, 3, + 3, 3, 1, 3, 3, 3, 3, 3, 1, 3, + 3, 1, 1, 2, 1, 1, 0, 1, 0, 2, + 2, 2, 4, 3, 1, 1, 3, 1, 2, 2, + 3, 2, 3, 1, 1, 2, 3, 1, 1, 3, + 2, 0, 1, 5, 5, 6, 10, 3, 5, 1, + 1, 3, 0, 2, 4, 5, 4, 4, 4, 3, + 1, 1, 1, 1, 1, 1, 0, 1, 1, 2, + 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, + 1, 1, 3, 2, 2, 3, 1, 0, 1, 1, + 3, 3, 3, 4, 4, 1, 1, 2, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, + 3, 4, 4, 2, 2, 4, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 1, 3, 2, + 1, 2, 4, 2, 2, 8, 9, 8, 9, 9, + 10, 9, 10, 8, 3, 2, 0, 4, 2, 1, + 3, 2, 1, 2, 2, 2, 4, 1, 1, 1, + 1, 1, 1, 1, 1, 3, 1, 1, 1, 0, + 3, 0, 1, 1, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 3, 5, 3, 3, 4, + 1, 1, 3, 1, 1, 1, 1, 1, 3, 2, + 3, 0, 1, 1, 3, 1, 1, 1, 1, 1, + 3, 1, 1, 4, 4, 1, 4, 4, 0, 1, + 1, 1, 3, 3, 1, 4, 2, 2, 1, 3, + 1, 4, 4, 3, 3, 3, 3, 1, 3, 1, + 1, 3, 1, 1, 4, 1, 1, 1, 3, 1, + 1, 2, 1, 3, 4, 3, 2, 0, 2, 2, + 1, 2, 1, 1, 1, 4, 3, 3, 3, 3, + 6, 3, 1, 1, 2, 1 + ); + + protected function initReduceCallbacks(): void { + $this->reduceCallbacks = [ + 0 => null, + 1 => static function ($self, $stackPos) { + $self->semValue = $self->handleNamespaces($self->semStack[$stackPos-(1-1)]); + }, + 2 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(2-2)] !== null) { $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; } $self->semValue = $self->semStack[$stackPos-(2-1)];; + }, + 3 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 4 => static function ($self, $stackPos) { + $nop = $self->maybeCreateZeroLengthNop($self->tokenPos);; + if ($nop !== null) { $self->semStack[$stackPos-(1-1)][] = $nop; } $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 5 => null, + 6 => null, + 7 => null, + 8 => null, + 9 => null, + 10 => null, + 11 => null, + 12 => null, + 13 => null, + 14 => null, + 15 => null, + 16 => null, + 17 => null, + 18 => null, + 19 => null, + 20 => null, + 21 => null, + 22 => null, + 23 => null, + 24 => null, + 25 => null, + 26 => null, + 27 => null, + 28 => null, + 29 => null, + 30 => null, + 31 => null, + 32 => null, + 33 => null, + 34 => null, + 35 => null, + 36 => null, + 37 => null, + 38 => null, + 39 => null, + 40 => null, + 41 => null, + 42 => null, + 43 => null, + 44 => null, + 45 => null, + 46 => null, + 47 => null, + 48 => null, + 49 => null, + 50 => null, + 51 => null, + 52 => null, + 53 => null, + 54 => null, + 55 => null, + 56 => null, + 57 => null, + 58 => null, + 59 => null, + 60 => null, + 61 => null, + 62 => null, + 63 => null, + 64 => null, + 65 => null, + 66 => null, + 67 => null, + 68 => null, + 69 => null, + 70 => null, + 71 => null, + 72 => null, + 73 => null, + 74 => null, + 75 => null, + 76 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; if ($self->semValue === "<?=") $self->emitError(new Error('Cannot use "<?=" as an identifier', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]))); + }, + 77 => null, + 78 => null, + 79 => null, + 80 => null, + 81 => null, + 82 => null, + 83 => null, + 84 => null, + 85 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 86 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 87 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 88 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 89 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 90 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 91 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 92 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 93 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 94 => null, + 95 => static function ($self, $stackPos) { + $self->semValue = new Name(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 96 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 97 => static function ($self, $stackPos) { + /* nothing */ + }, + 98 => static function ($self, $stackPos) { + /* nothing */ + }, + 99 => static function ($self, $stackPos) { + /* nothing */ + }, + 100 => static function ($self, $stackPos) { + $self->emitError(new Error('A trailing comma is not allowed here', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]))); + }, + 101 => null, + 102 => null, + 103 => static function ($self, $stackPos) { + $self->semValue = new Node\Attribute($self->semStack[$stackPos-(1-1)], [], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 104 => static function ($self, $stackPos) { + $self->semValue = new Node\Attribute($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 105 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 106 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 107 => static function ($self, $stackPos) { + $self->semValue = new Node\AttributeGroup($self->semStack[$stackPos-(4-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 108 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 109 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 110 => static function ($self, $stackPos) { + $self->semValue = []; + }, + 111 => null, + 112 => null, + 113 => null, + 114 => null, + 115 => static function ($self, $stackPos) { + $self->semValue = new Stmt\HaltCompiler($self->handleHaltCompiler(), $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 116 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Namespace_($self->semStack[$stackPos-(3-2)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('kind', Stmt\Namespace_::KIND_SEMICOLON); + $self->checkNamespace($self->semValue); + }, + 117 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Namespace_($self->semStack[$stackPos-(5-2)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('kind', Stmt\Namespace_::KIND_BRACED); + $self->checkNamespace($self->semValue); + }, + 118 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Namespace_(null, $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('kind', Stmt\Namespace_::KIND_BRACED); + $self->checkNamespace($self->semValue); + }, + 119 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Use_($self->semStack[$stackPos-(3-2)], Stmt\Use_::TYPE_NORMAL, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 120 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Use_($self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 121 => null, + 122 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Const_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 123 => static function ($self, $stackPos) { + $self->semValue = Stmt\Use_::TYPE_FUNCTION; + }, + 124 => static function ($self, $stackPos) { + $self->semValue = Stmt\Use_::TYPE_CONSTANT; + }, + 125 => static function ($self, $stackPos) { + $self->semValue = new Stmt\GroupUse($self->semStack[$stackPos-(7-3)], $self->semStack[$stackPos-(7-6)], $self->semStack[$stackPos-(7-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 126 => static function ($self, $stackPos) { + $self->semValue = new Stmt\GroupUse($self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-5)], Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 127 => null, + 128 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 129 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 130 => null, + 131 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 132 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 133 => null, + 134 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 135 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 136 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(1-1)], null, Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(1-1)); + }, + 137 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(3-3)); + }, + 138 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(1-1)], null, Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(1-1)); + }, + 139 => static function ($self, $stackPos) { + $self->semValue = new Node\UseItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], Stmt\Use_::TYPE_UNKNOWN, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->checkUseUse($self->semValue, $stackPos-(3-3)); + }, + 140 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; $self->semValue->type = Stmt\Use_::TYPE_NORMAL; + }, + 141 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; $self->semValue->type = $self->semStack[$stackPos-(2-1)]; + }, + 142 => null, + 143 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 144 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 145 => static function ($self, $stackPos) { + $self->semValue = new Node\Const_($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 146 => null, + 147 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 148 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 149 => static function ($self, $stackPos) { + $self->semValue = new Node\Const_(new Node\Identifier($self->semStack[$stackPos-(3-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos-(3-1)])), $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 150 => static function ($self, $stackPos) { + $self->semValue = new Node\Const_(new Node\Identifier($self->semStack[$stackPos-(3-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos-(3-1)])), $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 151 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(2-2)] !== null) { $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; } $self->semValue = $self->semStack[$stackPos-(2-1)];; + }, + 152 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 153 => static function ($self, $stackPos) { + $nop = $self->maybeCreateZeroLengthNop($self->tokenPos);; + if ($nop !== null) { $self->semStack[$stackPos-(1-1)][] = $nop; } $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 154 => null, + 155 => null, + 156 => null, + 157 => static function ($self, $stackPos) { + throw new Error('__HALT_COMPILER() can only be used from the outermost scope', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 158 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Block($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 159 => static function ($self, $stackPos) { + $self->semValue = new Stmt\If_($self->semStack[$stackPos-(7-3)], ['stmts' => $self->semStack[$stackPos-(7-5)], 'elseifs' => $self->semStack[$stackPos-(7-6)], 'else' => $self->semStack[$stackPos-(7-7)]], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 160 => static function ($self, $stackPos) { + $self->semValue = new Stmt\If_($self->semStack[$stackPos-(10-3)], ['stmts' => $self->semStack[$stackPos-(10-6)], 'elseifs' => $self->semStack[$stackPos-(10-7)], 'else' => $self->semStack[$stackPos-(10-8)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + }, + 161 => static function ($self, $stackPos) { + $self->semValue = new Stmt\While_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 162 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Do_($self->semStack[$stackPos-(7-5)], $self->semStack[$stackPos-(7-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 163 => static function ($self, $stackPos) { + $self->semValue = new Stmt\For_(['init' => $self->semStack[$stackPos-(9-3)], 'cond' => $self->semStack[$stackPos-(9-5)], 'loop' => $self->semStack[$stackPos-(9-7)], 'stmts' => $self->semStack[$stackPos-(9-9)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 164 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Switch_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 165 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Break_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 166 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Continue_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 167 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Return_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 168 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Global_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 169 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Static_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 170 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Echo_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 171 => static function ($self, $stackPos) { + + $self->semValue = new Stmt\InlineHTML($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + $self->semValue->setAttribute('hasLeadingNewline', $self->inlineHtmlHasLeadingNewline($stackPos-(1-1))); + + }, + 172 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Expression($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 173 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Unset_($self->semStack[$stackPos-(5-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 174 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Foreach_($self->semStack[$stackPos-(7-3)], $self->semStack[$stackPos-(7-5)][0], ['keyVar' => null, 'byRef' => $self->semStack[$stackPos-(7-5)][1], 'stmts' => $self->semStack[$stackPos-(7-7)]], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 175 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Foreach_($self->semStack[$stackPos-(9-3)], $self->semStack[$stackPos-(9-7)][0], ['keyVar' => $self->semStack[$stackPos-(9-5)], 'byRef' => $self->semStack[$stackPos-(9-7)][1], 'stmts' => $self->semStack[$stackPos-(9-9)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 176 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Foreach_($self->semStack[$stackPos-(6-3)], new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(6-4)], $self->tokenEndStack[$stackPos-(6-4)])), ['stmts' => $self->semStack[$stackPos-(6-6)]], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 177 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Declare_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 178 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TryCatch($self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-5)], $self->semStack[$stackPos-(6-6)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); $self->checkTryCatch($self->semValue); + }, + 179 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Goto_($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 180 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Label($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 181 => static function ($self, $stackPos) { + $self->semValue = null; /* means: no statement */ + }, + 182 => null, + 183 => static function ($self, $stackPos) { + $self->semValue = $self->maybeCreateNop($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]); + }, + 184 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(1-1)] instanceof Stmt\Block) { $self->semValue = $self->semStack[$stackPos-(1-1)]->stmts; } else if ($self->semStack[$stackPos-(1-1)] === null) { $self->semValue = []; } else { $self->semValue = [$self->semStack[$stackPos-(1-1)]]; }; + }, + 185 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 186 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 187 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 188 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 189 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Catch_($self->semStack[$stackPos-(8-3)], $self->semStack[$stackPos-(8-4)], $self->semStack[$stackPos-(8-7)], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 190 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 191 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Finally_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 192 => null, + 193 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 194 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 195 => static function ($self, $stackPos) { + $self->semValue = false; + }, + 196 => static function ($self, $stackPos) { + $self->semValue = true; + }, + 197 => static function ($self, $stackPos) { + $self->semValue = false; + }, + 198 => static function ($self, $stackPos) { + $self->semValue = true; + }, + 199 => static function ($self, $stackPos) { + $self->semValue = false; + }, + 200 => static function ($self, $stackPos) { + $self->semValue = true; + }, + 201 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 202 => static function ($self, $stackPos) { + $self->semValue = []; + }, + 203 => null, + 204 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 205 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Function_($self->semStack[$stackPos-(8-3)], ['byRef' => $self->semStack[$stackPos-(8-2)], 'params' => $self->semStack[$stackPos-(8-5)], 'returnType' => $self->semStack[$stackPos-(8-7)], 'stmts' => $self->semStack[$stackPos-(8-8)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 206 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Function_($self->semStack[$stackPos-(9-4)], ['byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-6)], 'returnType' => $self->semStack[$stackPos-(9-8)], 'stmts' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => $self->semStack[$stackPos-(9-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 207 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Class_($self->semStack[$stackPos-(7-2)], ['type' => $self->semStack[$stackPos-(7-1)], 'extends' => $self->semStack[$stackPos-(7-3)], 'implements' => $self->semStack[$stackPos-(7-4)], 'stmts' => $self->semStack[$stackPos-(7-6)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + $self->checkClass($self->semValue, $stackPos-(7-2)); + }, + 208 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Class_($self->semStack[$stackPos-(8-3)], ['type' => $self->semStack[$stackPos-(8-2)], 'extends' => $self->semStack[$stackPos-(8-4)], 'implements' => $self->semStack[$stackPos-(8-5)], 'stmts' => $self->semStack[$stackPos-(8-7)], 'attrGroups' => $self->semStack[$stackPos-(8-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + $self->checkClass($self->semValue, $stackPos-(8-3)); + }, + 209 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Interface_($self->semStack[$stackPos-(7-3)], ['extends' => $self->semStack[$stackPos-(7-4)], 'stmts' => $self->semStack[$stackPos-(7-6)], 'attrGroups' => $self->semStack[$stackPos-(7-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + $self->checkInterface($self->semValue, $stackPos-(7-3)); + }, + 210 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Trait_($self->semStack[$stackPos-(6-3)], ['stmts' => $self->semStack[$stackPos-(6-5)], 'attrGroups' => $self->semStack[$stackPos-(6-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 211 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Enum_($self->semStack[$stackPos-(8-3)], ['scalarType' => $self->semStack[$stackPos-(8-4)], 'implements' => $self->semStack[$stackPos-(8-5)], 'stmts' => $self->semStack[$stackPos-(8-7)], 'attrGroups' => $self->semStack[$stackPos-(8-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + $self->checkEnum($self->semValue, $stackPos-(8-3)); + }, + 212 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 213 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 214 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 215 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 216 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 217 => null, + 218 => null, + 219 => static function ($self, $stackPos) { + $self->checkClassModifier($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $stackPos-(2-2)); $self->semValue = $self->semStack[$stackPos-(2-1)] | $self->semStack[$stackPos-(2-2)]; + }, + 220 => static function ($self, $stackPos) { + $self->semValue = Modifiers::ABSTRACT; + }, + 221 => static function ($self, $stackPos) { + $self->semValue = Modifiers::FINAL; + }, + 222 => static function ($self, $stackPos) { + $self->semValue = Modifiers::READONLY; + }, + 223 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 224 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 225 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 226 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 227 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 228 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 229 => null, + 230 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 231 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 232 => null, + 233 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 234 => null, + 235 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 236 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(1-1)] instanceof Stmt\Block) { $self->semValue = $self->semStack[$stackPos-(1-1)]->stmts; } else if ($self->semStack[$stackPos-(1-1)] === null) { $self->semValue = []; } else { $self->semValue = [$self->semStack[$stackPos-(1-1)]]; }; + }, + 237 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 238 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 239 => null, + 240 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 241 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 242 => static function ($self, $stackPos) { + $self->semValue = new Node\DeclareItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 243 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 244 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-3)]; + }, + 245 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 246 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(5-3)]; + }, + 247 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 248 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 249 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Case_($self->semStack[$stackPos-(4-2)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 250 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Case_(null, $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 251 => null, + 252 => null, + 253 => static function ($self, $stackPos) { + $self->semValue = new Expr\Match_($self->semStack[$stackPos-(7-3)], $self->semStack[$stackPos-(7-6)], $self->getAttributes($self->tokenStartStack[$stackPos-(7-1)], $self->tokenEndStack[$stackPos])); + }, + 254 => static function ($self, $stackPos) { + $self->semValue = []; + }, + 255 => null, + 256 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 257 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 258 => static function ($self, $stackPos) { + $self->semValue = new Node\MatchArm($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 259 => static function ($self, $stackPos) { + $self->semValue = new Node\MatchArm(null, $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 260 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 261 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 262 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 263 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 264 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ElseIf_($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 265 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 266 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 267 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ElseIf_($self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-6)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); $self->fixupAlternativeElse($self->semValue); + }, + 268 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 269 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Else_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 270 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 271 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Else_($self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->fixupAlternativeElse($self->semValue); + }, + 272 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)], false); + }, + 273 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(2-2)], true); + }, + 274 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)], false); + }, + 275 => static function ($self, $stackPos) { + $self->semValue = array($self->fixupArrayDestructuring($self->semStack[$stackPos-(1-1)]), false); + }, + 276 => null, + 277 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 278 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 279 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 280 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 281 => static function ($self, $stackPos) { + $self->checkModifier($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $stackPos-(2-2)); $self->semValue = $self->semStack[$stackPos-(2-1)] | $self->semStack[$stackPos-(2-2)]; + }, + 282 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PUBLIC; + }, + 283 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PROTECTED; + }, + 284 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PRIVATE; + }, + 285 => static function ($self, $stackPos) { + $self->semValue = Modifiers::READONLY; + }, + 286 => static function ($self, $stackPos) { + $self->semValue = new Node\Param($self->semStack[$stackPos-(6-6)], null, $self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-4)], $self->semStack[$stackPos-(6-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-1)]); + $self->checkParam($self->semValue); + }, + 287 => static function ($self, $stackPos) { + $self->semValue = new Node\Param($self->semStack[$stackPos-(8-6)], $self->semStack[$stackPos-(8-8)], $self->semStack[$stackPos-(8-3)], $self->semStack[$stackPos-(8-4)], $self->semStack[$stackPos-(8-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(8-2)], $self->semStack[$stackPos-(8-1)]); + $self->checkParam($self->semValue); + }, + 288 => static function ($self, $stackPos) { + $self->semValue = new Node\Param(new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])), null, $self->semStack[$stackPos-(6-3)], $self->semStack[$stackPos-(6-4)], $self->semStack[$stackPos-(6-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-1)]); + }, + 289 => null, + 290 => static function ($self, $stackPos) { + $self->semValue = new Node\NullableType($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 291 => static function ($self, $stackPos) { + $self->semValue = new Node\UnionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 292 => null, + 293 => null, + 294 => static function ($self, $stackPos) { + $self->semValue = new Node\Name('static', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 295 => static function ($self, $stackPos) { + $self->semValue = $self->handleBuiltinTypes($self->semStack[$stackPos-(1-1)]); + }, + 296 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier('array', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 297 => static function ($self, $stackPos) { + $self->semValue = new Node\Identifier('callable', $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 298 => null, + 299 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 300 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 301 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 302 => null, + 303 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 304 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 305 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 306 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 307 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 308 => static function ($self, $stackPos) { + $self->semValue = new Node\IntersectionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 309 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 310 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 311 => static function ($self, $stackPos) { + $self->semValue = new Node\IntersectionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 312 => null, + 313 => static function ($self, $stackPos) { + $self->semValue = new Node\NullableType($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 314 => static function ($self, $stackPos) { + $self->semValue = new Node\UnionType($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 315 => null, + 316 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 317 => null, + 318 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 319 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(2-2)]; + }, + 320 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 321 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 322 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-2)]; + }, + 323 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-2)]); + }, + 324 => static function ($self, $stackPos) { + $self->semValue = new Node\VariadicPlaceholder($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 325 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 326 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 327 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(1-1)], false, false, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 328 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(2-2)], true, false, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 329 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(2-2)], false, true, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 330 => static function ($self, $stackPos) { + $self->semValue = new Node\Arg($self->semStack[$stackPos-(3-3)], false, false, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(3-1)]); + }, + 331 => null, + 332 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 333 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 334 => null, + 335 => null, + 336 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 337 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 338 => static function ($self, $stackPos) { + $self->semValue = new Node\StaticVar($self->semStack[$stackPos-(1-1)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 339 => static function ($self, $stackPos) { + $self->semValue = new Node\StaticVar($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 340 => static function ($self, $stackPos) { + if ($self->semStack[$stackPos-(2-2)] !== null) { $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; } else { $self->semValue = $self->semStack[$stackPos-(2-1)]; } + }, + 341 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 342 => static function ($self, $stackPos) { + $nop = $self->maybeCreateZeroLengthNop($self->tokenPos);; + if ($nop !== null) { $self->semStack[$stackPos-(1-1)][] = $nop; } $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 343 => static function ($self, $stackPos) { + $self->semValue = new Stmt\Property($self->semStack[$stackPos-(5-2)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-1)]); + $self->checkProperty($self->semValue, $stackPos-(5-2)); + }, + 344 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ClassConst($self->semStack[$stackPos-(5-4)], $self->semStack[$stackPos-(5-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(5-1)]); + $self->checkClassConst($self->semValue, $stackPos-(5-2)); + }, + 345 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ClassConst($self->semStack[$stackPos-(6-5)], $self->semStack[$stackPos-(6-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos]), $self->semStack[$stackPos-(6-1)], $self->semStack[$stackPos-(6-4)]); + $self->checkClassConst($self->semValue, $stackPos-(6-2)); + }, + 346 => static function ($self, $stackPos) { + $self->semValue = new Stmt\ClassMethod($self->semStack[$stackPos-(10-5)], ['type' => $self->semStack[$stackPos-(10-2)], 'byRef' => $self->semStack[$stackPos-(10-4)], 'params' => $self->semStack[$stackPos-(10-7)], 'returnType' => $self->semStack[$stackPos-(10-9)], 'stmts' => $self->semStack[$stackPos-(10-10)], 'attrGroups' => $self->semStack[$stackPos-(10-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + $self->checkClassMethod($self->semValue, $stackPos-(10-2)); + }, + 347 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUse($self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 348 => static function ($self, $stackPos) { + $self->semValue = new Stmt\EnumCase($self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-4)], $self->semStack[$stackPos-(5-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 349 => static function ($self, $stackPos) { + $self->semValue = null; /* will be skipped */ + }, + 350 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 351 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 352 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 353 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 354 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Precedence($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 355 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(5-1)][0], $self->semStack[$stackPos-(5-1)][1], $self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 356 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], $self->semStack[$stackPos-(4-3)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 357 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], null, $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 358 => static function ($self, $stackPos) { + $self->semValue = new Stmt\TraitUseAdaptation\Alias($self->semStack[$stackPos-(4-1)][0], $self->semStack[$stackPos-(4-1)][1], null, $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 359 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)]); + }, + 360 => null, + 361 => static function ($self, $stackPos) { + $self->semValue = array(null, $self->semStack[$stackPos-(1-1)]); + }, + 362 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 363 => null, + 364 => null, + 365 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 366 => static function ($self, $stackPos) { + $self->semValue = 0; + }, + 367 => null, + 368 => null, + 369 => static function ($self, $stackPos) { + $self->checkModifier($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $stackPos-(2-2)); $self->semValue = $self->semStack[$stackPos-(2-1)] | $self->semStack[$stackPos-(2-2)]; + }, + 370 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PUBLIC; + }, + 371 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PROTECTED; + }, + 372 => static function ($self, $stackPos) { + $self->semValue = Modifiers::PRIVATE; + }, + 373 => static function ($self, $stackPos) { + $self->semValue = Modifiers::STATIC; + }, + 374 => static function ($self, $stackPos) { + $self->semValue = Modifiers::ABSTRACT; + }, + 375 => static function ($self, $stackPos) { + $self->semValue = Modifiers::FINAL; + }, + 376 => static function ($self, $stackPos) { + $self->semValue = Modifiers::READONLY; + }, + 377 => null, + 378 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 379 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 380 => static function ($self, $stackPos) { + $self->semValue = new Node\VarLikeIdentifier(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 381 => static function ($self, $stackPos) { + $self->semValue = new Node\PropertyItem($self->semStack[$stackPos-(1-1)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 382 => static function ($self, $stackPos) { + $self->semValue = new Node\PropertyItem($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 383 => null, + 384 => null, + 385 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 386 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 387 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 388 => null, + 389 => null, + 390 => static function ($self, $stackPos) { + $self->semValue = new Expr\Assign($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 391 => static function ($self, $stackPos) { + $self->semValue = new Expr\Assign($self->fixupArrayDestructuring($self->semStack[$stackPos-(3-1)]), $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 392 => static function ($self, $stackPos) { + $self->semValue = new Expr\Assign($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 393 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignRef($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 394 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignRef($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + if (!$self->phpVersion->allowsAssignNewByReference()) { + $self->emitError(new Error('Cannot assign new by reference', $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos]))); + } + + }, + 395 => null, + 396 => null, + 397 => static function ($self, $stackPos) { + $self->semValue = new Expr\Clone_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 398 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Plus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 399 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Minus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 400 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Mul($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 401 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Div($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 402 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Concat($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 403 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Mod($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 404 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\BitwiseAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 405 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\BitwiseOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 406 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\BitwiseXor($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 407 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\ShiftLeft($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 408 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\ShiftRight($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 409 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Pow($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 410 => static function ($self, $stackPos) { + $self->semValue = new Expr\AssignOp\Coalesce($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 411 => static function ($self, $stackPos) { + $self->semValue = new Expr\PostInc($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 412 => static function ($self, $stackPos) { + $self->semValue = new Expr\PreInc($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 413 => static function ($self, $stackPos) { + $self->semValue = new Expr\PostDec($self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 414 => static function ($self, $stackPos) { + $self->semValue = new Expr\PreDec($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 415 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BooleanOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 416 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BooleanAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 417 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\LogicalOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 418 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\LogicalAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 419 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\LogicalXor($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 420 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseOr($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 421 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 422 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseAnd($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 423 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\BitwiseXor($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 424 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Concat($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 425 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Plus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 426 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Minus($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 427 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Mul($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 428 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Div($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 429 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Mod($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 430 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\ShiftLeft($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 431 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\ShiftRight($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 432 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Pow($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 433 => static function ($self, $stackPos) { + $self->semValue = new Expr\UnaryPlus($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 434 => static function ($self, $stackPos) { + $self->semValue = new Expr\UnaryMinus($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 435 => static function ($self, $stackPos) { + $self->semValue = new Expr\BooleanNot($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 436 => static function ($self, $stackPos) { + $self->semValue = new Expr\BitwiseNot($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 437 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Identical($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 438 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\NotIdentical($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 439 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Equal($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 440 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\NotEqual($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 441 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Spaceship($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 442 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Smaller($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 443 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\SmallerOrEqual($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 444 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Greater($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 445 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\GreaterOrEqual($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 446 => static function ($self, $stackPos) { + $self->semValue = new Expr\Instanceof_($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 447 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 448 => static function ($self, $stackPos) { + $self->semValue = new Expr\Ternary($self->semStack[$stackPos-(5-1)], $self->semStack[$stackPos-(5-3)], $self->semStack[$stackPos-(5-5)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 449 => static function ($self, $stackPos) { + $self->semValue = new Expr\Ternary($self->semStack[$stackPos-(4-1)], null, $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 450 => static function ($self, $stackPos) { + $self->semValue = new Expr\BinaryOp\Coalesce($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 451 => static function ($self, $stackPos) { + $self->semValue = new Expr\Isset_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 452 => static function ($self, $stackPos) { + $self->semValue = new Expr\Empty_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 453 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_INCLUDE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 454 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_INCLUDE_ONCE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 455 => static function ($self, $stackPos) { + $self->semValue = new Expr\Eval_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 456 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_REQUIRE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 457 => static function ($self, $stackPos) { + $self->semValue = new Expr\Include_($self->semStack[$stackPos-(2-2)], Expr\Include_::TYPE_REQUIRE_ONCE, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 458 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Int_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 459 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]); + $attrs['kind'] = $self->getFloatCastKind($self->semStack[$stackPos-(2-1)]); + $self->semValue = new Expr\Cast\Double($self->semStack[$stackPos-(2-2)], $attrs); + }, + 460 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\String_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 461 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Array_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 462 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Object_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 463 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Bool_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 464 => static function ($self, $stackPos) { + $self->semValue = new Expr\Cast\Unset_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 465 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]); + $attrs['kind'] = strtolower($self->semStack[$stackPos-(2-1)]) === 'exit' ? Expr\Exit_::KIND_EXIT : Expr\Exit_::KIND_DIE; + $self->semValue = new Expr\Exit_($self->semStack[$stackPos-(2-2)], $attrs); + }, + 466 => static function ($self, $stackPos) { + $self->semValue = new Expr\ErrorSuppress($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 467 => null, + 468 => static function ($self, $stackPos) { + $self->semValue = new Expr\ShellExec($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 469 => static function ($self, $stackPos) { + $self->semValue = new Expr\Print_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 470 => static function ($self, $stackPos) { + $self->semValue = new Expr\Yield_(null, null, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 471 => static function ($self, $stackPos) { + $self->semValue = new Expr\Yield_($self->semStack[$stackPos-(2-2)], null, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 472 => static function ($self, $stackPos) { + $self->semValue = new Expr\Yield_($self->semStack[$stackPos-(4-4)], $self->semStack[$stackPos-(4-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 473 => static function ($self, $stackPos) { + $self->semValue = new Expr\YieldFrom($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 474 => static function ($self, $stackPos) { + $self->semValue = new Expr\Throw_($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 475 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => false, 'byRef' => $self->semStack[$stackPos-(8-2)], 'params' => $self->semStack[$stackPos-(8-4)], 'returnType' => $self->semStack[$stackPos-(8-6)], 'expr' => $self->semStack[$stackPos-(8-8)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 476 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => true, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'returnType' => $self->semStack[$stackPos-(9-7)], 'expr' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 477 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => false, 'byRef' => $self->semStack[$stackPos-(8-2)], 'params' => $self->semStack[$stackPos-(8-4)], 'uses' => $self->semStack[$stackPos-(8-6)], 'returnType' => $self->semStack[$stackPos-(8-7)], 'stmts' => $self->semStack[$stackPos-(8-8)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])); + }, + 478 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => true, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'uses' => $self->semStack[$stackPos-(9-7)], 'returnType' => $self->semStack[$stackPos-(9-8)], 'stmts' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => []], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 479 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => false, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'returnType' => $self->semStack[$stackPos-(9-7)], 'expr' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => $self->semStack[$stackPos-(9-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 480 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrowFunction(['static' => true, 'byRef' => $self->semStack[$stackPos-(10-4)], 'params' => $self->semStack[$stackPos-(10-6)], 'returnType' => $self->semStack[$stackPos-(10-8)], 'expr' => $self->semStack[$stackPos-(10-10)], 'attrGroups' => $self->semStack[$stackPos-(10-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + }, + 481 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => false, 'byRef' => $self->semStack[$stackPos-(9-3)], 'params' => $self->semStack[$stackPos-(9-5)], 'uses' => $self->semStack[$stackPos-(9-7)], 'returnType' => $self->semStack[$stackPos-(9-8)], 'stmts' => $self->semStack[$stackPos-(9-9)], 'attrGroups' => $self->semStack[$stackPos-(9-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(9-1)], $self->tokenEndStack[$stackPos])); + }, + 482 => static function ($self, $stackPos) { + $self->semValue = new Expr\Closure(['static' => true, 'byRef' => $self->semStack[$stackPos-(10-4)], 'params' => $self->semStack[$stackPos-(10-6)], 'uses' => $self->semStack[$stackPos-(10-8)], 'returnType' => $self->semStack[$stackPos-(10-9)], 'stmts' => $self->semStack[$stackPos-(10-10)], 'attrGroups' => $self->semStack[$stackPos-(10-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(10-1)], $self->tokenEndStack[$stackPos])); + }, + 483 => static function ($self, $stackPos) { + $self->semValue = array(new Stmt\Class_(null, ['type' => $self->semStack[$stackPos-(8-2)], 'extends' => $self->semStack[$stackPos-(8-4)], 'implements' => $self->semStack[$stackPos-(8-5)], 'stmts' => $self->semStack[$stackPos-(8-7)], 'attrGroups' => $self->semStack[$stackPos-(8-1)]], $self->getAttributes($self->tokenStartStack[$stackPos-(8-1)], $self->tokenEndStack[$stackPos])), $self->semStack[$stackPos-(8-3)]); + $self->checkClass($self->semValue[0], -1); + }, + 484 => static function ($self, $stackPos) { + $self->semValue = new Expr\New_($self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 485 => static function ($self, $stackPos) { + list($class, $ctorArgs) = $self->semStack[$stackPos-(2-2)]; $self->semValue = new Expr\New_($class, $ctorArgs, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 486 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 487 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(4-3)]; + }, + 488 => null, + 489 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 490 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 491 => static function ($self, $stackPos) { + $self->semValue = new Node\ClosureUse($self->semStack[$stackPos-(2-2)], $self->semStack[$stackPos-(2-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 492 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 493 => static function ($self, $stackPos) { + $self->semValue = new Expr\FuncCall($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 494 => static function ($self, $stackPos) { + $self->semValue = new Expr\FuncCall($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 495 => static function ($self, $stackPos) { + $self->semValue = new Expr\FuncCall($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 496 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticCall($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 497 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 498 => null, + 499 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 500 => static function ($self, $stackPos) { + $self->semValue = new Name($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 501 => static function ($self, $stackPos) { + $self->semValue = new Name\FullyQualified(substr($self->semStack[$stackPos-(1-1)], 1), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 502 => static function ($self, $stackPos) { + $self->semValue = new Name\Relative(substr($self->semStack[$stackPos-(1-1)], 10), $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 503 => null, + 504 => null, + 505 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 506 => static function ($self, $stackPos) { + $self->semValue = new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 507 => null, + 508 => null, + 509 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 510 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 511 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 512 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); foreach ($self->semValue as $s) { if ($s instanceof Node\InterpolatedStringPart) { $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, '`', $self->phpVersion->supportsUnicodeEscapes()); } }; + }, + 513 => static function ($self, $stackPos) { + foreach ($self->semStack[$stackPos-(1-1)] as $s) { if ($s instanceof Node\InterpolatedStringPart) { $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, '`', $self->phpVersion->supportsUnicodeEscapes()); } }; $self->semValue = $self->semStack[$stackPos-(1-1)]; + }, + 514 => static function ($self, $stackPos) { + $self->semValue = array(); + }, + 515 => null, + 516 => static function ($self, $stackPos) { + $self->semValue = new Expr\ConstFetch($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 517 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Line($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 518 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\File($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 519 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Dir($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 520 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Class_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 521 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Trait_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 522 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Method($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 523 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Function_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 524 => static function ($self, $stackPos) { + $self->semValue = new Scalar\MagicConst\Namespace_($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 525 => static function ($self, $stackPos) { + $self->semValue = new Expr\ClassConstFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 526 => static function ($self, $stackPos) { + $self->semValue = new Expr\ClassConstFetch($self->semStack[$stackPos-(5-1)], $self->semStack[$stackPos-(5-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(5-1)], $self->tokenEndStack[$stackPos])); + }, + 527 => static function ($self, $stackPos) { + $self->semValue = new Expr\ClassConstFetch($self->semStack[$stackPos-(3-1)], new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(3-3)], $self->tokenEndStack[$stackPos-(3-3)])), $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 528 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]); $attrs['kind'] = Expr\Array_::KIND_SHORT; + $self->semValue = new Expr\Array_($self->semStack[$stackPos-(3-2)], $attrs); + }, + 529 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos]); $attrs['kind'] = Expr\Array_::KIND_LONG; + $self->semValue = new Expr\Array_($self->semStack[$stackPos-(4-3)], $attrs); + $self->createdArrays->attach($self->semValue); + }, + 530 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; $self->createdArrays->attach($self->semValue); + }, + 531 => static function ($self, $stackPos) { + $self->semValue = Scalar\String_::fromString($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]), $self->phpVersion->supportsUnicodeEscapes()); + }, + 532 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]); $attrs['kind'] = Scalar\String_::KIND_DOUBLE_QUOTED; + foreach ($self->semStack[$stackPos-(3-2)] as $s) { if ($s instanceof Node\InterpolatedStringPart) { $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, '"', $self->phpVersion->supportsUnicodeEscapes()); } }; $self->semValue = new Scalar\InterpolatedString($self->semStack[$stackPos-(3-2)], $attrs); + }, + 533 => static function ($self, $stackPos) { + $self->semValue = $self->parseLNumber($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]), $self->phpVersion->allowsInvalidOctals()); + }, + 534 => static function ($self, $stackPos) { + $self->semValue = Scalar\Float_::fromString($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 535 => null, + 536 => null, + 537 => null, + 538 => static function ($self, $stackPos) { + $self->semValue = $self->parseDocString($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]), $self->getAttributes($self->tokenStartStack[$stackPos-(3-3)], $self->tokenEndStack[$stackPos-(3-3)]), true); + }, + 539 => static function ($self, $stackPos) { + $self->semValue = $self->parseDocString($self->semStack[$stackPos-(2-1)], '', $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]), $self->getAttributes($self->tokenStartStack[$stackPos-(2-2)], $self->tokenEndStack[$stackPos-(2-2)]), true); + }, + 540 => static function ($self, $stackPos) { + $self->semValue = $self->parseDocString($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-2)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos]), $self->getAttributes($self->tokenStartStack[$stackPos-(3-3)], $self->tokenEndStack[$stackPos-(3-3)]), true); + }, + 541 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 542 => null, + 543 => null, + 544 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 545 => null, + 546 => null, + 547 => null, + 548 => null, + 549 => null, + 550 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 551 => null, + 552 => null, + 553 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 554 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 555 => null, + 556 => static function ($self, $stackPos) { + $self->semValue = new Expr\MethodCall($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 557 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafeMethodCall($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->semStack[$stackPos-(4-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 558 => static function ($self, $stackPos) { + $self->semValue = null; + }, + 559 => null, + 560 => null, + 561 => null, + 562 => static function ($self, $stackPos) { + $self->semValue = new Expr\PropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 563 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafePropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 564 => null, + 565 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 566 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 567 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable(new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])), $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 568 => static function ($self, $stackPos) { + $var = $self->semStack[$stackPos-(1-1)]->name; $self->semValue = \is_string($var) ? new Node\VarLikeIdentifier($var, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])) : $var; + }, + 569 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticPropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 570 => null, + 571 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 572 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 573 => static function ($self, $stackPos) { + $self->semValue = new Expr\PropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 574 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafePropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 575 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticPropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 576 => static function ($self, $stackPos) { + $self->semValue = new Expr\StaticPropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 577 => null, + 578 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 579 => null, + 580 => null, + 581 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 582 => null, + 583 => static function ($self, $stackPos) { + $self->semValue = new Expr\Error($self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); $self->errorState = 2; + }, + 584 => static function ($self, $stackPos) { + $self->semValue = new Expr\List_($self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); $self->semValue->setAttribute('kind', Expr\List_::KIND_LIST); + $self->postprocessList($self->semValue); + }, + 585 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(1-1)]; $end = count($self->semValue)-1; if ($self->semValue[$end]->value instanceof Expr\Error) array_pop($self->semValue); + }, + 586 => null, + 587 => static function ($self, $stackPos) { + /* do nothing -- prevent default action of $$=$self->semStack[$1]. See $551. */ + }, + 588 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(3-1)][] = $self->semStack[$stackPos-(3-3)]; $self->semValue = $self->semStack[$stackPos-(3-1)]; + }, + 589 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 590 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(1-1)], null, false, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 591 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(2-2)], null, true, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 592 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(1-1)], null, false, $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 593 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(3-3)], $self->semStack[$stackPos-(3-1)], false, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 594 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(4-4)], $self->semStack[$stackPos-(4-1)], true, $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 595 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(3-3)], $self->semStack[$stackPos-(3-1)], false, $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 596 => static function ($self, $stackPos) { + $self->semValue = new Node\ArrayItem($self->semStack[$stackPos-(2-2)], null, false, $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos]), true); + }, + 597 => static function ($self, $stackPos) { + /* Create an Error node now to remember the position. We'll later either report an error, + or convert this into a null element, depending on whether this is a creation or destructuring context. */ + $attrs = $self->createEmptyElemAttributes($self->tokenPos); + $self->semValue = new Node\ArrayItem(new Expr\Error($attrs), null, false, $attrs); + }, + 598 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 599 => static function ($self, $stackPos) { + $self->semStack[$stackPos-(2-1)][] = $self->semStack[$stackPos-(2-2)]; $self->semValue = $self->semStack[$stackPos-(2-1)]; + }, + 600 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(1-1)]); + }, + 601 => static function ($self, $stackPos) { + $self->semValue = array($self->semStack[$stackPos-(2-1)], $self->semStack[$stackPos-(2-2)]); + }, + 602 => static function ($self, $stackPos) { + $attrs = $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos]); $attrs['rawValue'] = $self->semStack[$stackPos-(1-1)]; $self->semValue = new Node\InterpolatedStringPart($self->semStack[$stackPos-(1-1)], $attrs); + }, + 603 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 604 => null, + 605 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(4-1)], $self->semStack[$stackPos-(4-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(4-1)], $self->tokenEndStack[$stackPos])); + }, + 606 => static function ($self, $stackPos) { + $self->semValue = new Expr\PropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 607 => static function ($self, $stackPos) { + $self->semValue = new Expr\NullsafePropertyFetch($self->semStack[$stackPos-(3-1)], $self->semStack[$stackPos-(3-3)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 608 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 609 => static function ($self, $stackPos) { + $self->semValue = new Expr\Variable($self->semStack[$stackPos-(3-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(3-1)], $self->tokenEndStack[$stackPos])); + }, + 610 => static function ($self, $stackPos) { + $self->semValue = new Expr\ArrayDimFetch($self->semStack[$stackPos-(6-2)], $self->semStack[$stackPos-(6-4)], $self->getAttributes($self->tokenStartStack[$stackPos-(6-1)], $self->tokenEndStack[$stackPos])); + }, + 611 => static function ($self, $stackPos) { + $self->semValue = $self->semStack[$stackPos-(3-2)]; + }, + 612 => static function ($self, $stackPos) { + $self->semValue = new Scalar\String_($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 613 => static function ($self, $stackPos) { + $self->semValue = $self->parseNumString($self->semStack[$stackPos-(1-1)], $self->getAttributes($self->tokenStartStack[$stackPos-(1-1)], $self->tokenEndStack[$stackPos])); + }, + 614 => static function ($self, $stackPos) { + $self->semValue = $self->parseNumString('-' . $self->semStack[$stackPos-(2-2)], $self->getAttributes($self->tokenStartStack[$stackPos-(2-1)], $self->tokenEndStack[$stackPos])); + }, + 615 => null, + ]; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php new file mode 100644 index 0000000..4272331 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php @@ -0,0 +1,1241 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +/* + * This parser is based on a skeleton written by Moriyoshi Koizumi, which in + * turn is based on work by Masato Bito. + */ + +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\Array_; +use PhpParser\Node\Expr\Cast\Double; +use PhpParser\Node\Identifier; +use PhpParser\Node\InterpolatedStringPart; +use PhpParser\Node\Name; +use PhpParser\Node\Param; +use PhpParser\Node\Scalar\InterpolatedString; +use PhpParser\Node\Scalar\Int_; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt; +use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\ClassConst; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\Node\Stmt\Else_; +use PhpParser\Node\Stmt\ElseIf_; +use PhpParser\Node\Stmt\Enum_; +use PhpParser\Node\Stmt\Interface_; +use PhpParser\Node\Stmt\Namespace_; +use PhpParser\Node\Stmt\Nop; +use PhpParser\Node\Stmt\Property; +use PhpParser\Node\Stmt\TryCatch; +use PhpParser\Node\UseItem; +use PhpParser\NodeVisitor\CommentAnnotatingVisitor; + +abstract class ParserAbstract implements Parser { + private const SYMBOL_NONE = -1; + + /** @var Lexer Lexer that is used when parsing */ + protected Lexer $lexer; + /** @var PhpVersion PHP version to target on a best-effort basis */ + protected PhpVersion $phpVersion; + + /* + * The following members will be filled with generated parsing data: + */ + + /** @var int Size of $tokenToSymbol map */ + protected int $tokenToSymbolMapSize; + /** @var int Size of $action table */ + protected int $actionTableSize; + /** @var int Size of $goto table */ + protected int $gotoTableSize; + + /** @var int Symbol number signifying an invalid token */ + protected int $invalidSymbol; + /** @var int Symbol number of error recovery token */ + protected int $errorSymbol; + /** @var int Action number signifying default action */ + protected int $defaultAction; + /** @var int Rule number signifying that an unexpected token was encountered */ + protected int $unexpectedTokenRule; + + protected int $YY2TBLSTATE; + /** @var int Number of non-leaf states */ + protected int $numNonLeafStates; + + /** @var int[] Map of PHP token IDs to internal symbols */ + protected array $phpTokenToSymbol; + /** @var array<int, bool> Map of PHP token IDs to drop */ + protected array $dropTokens; + /** @var int[] Map of external symbols (static::T_*) to internal symbols */ + protected array $tokenToSymbol; + /** @var string[] Map of symbols to their names */ + protected array $symbolToName; + /** @var array<int, string> Names of the production rules (only necessary for debugging) */ + protected array $productions; + + /** @var int[] Map of states to a displacement into the $action table. The corresponding action for this + * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the + * action is defaulted, i.e. $actionDefault[$state] should be used instead. */ + protected array $actionBase; + /** @var int[] Table of actions. Indexed according to $actionBase comment. */ + protected array $action; + /** @var int[] Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol + * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */ + protected array $actionCheck; + /** @var int[] Map of states to their default action */ + protected array $actionDefault; + /** @var callable[] Semantic action callbacks */ + protected array $reduceCallbacks; + + /** @var int[] Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this + * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */ + protected array $gotoBase; + /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */ + protected array $goto; + /** @var int[] Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal + * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */ + protected array $gotoCheck; + /** @var int[] Map of non-terminals to the default state to goto after their reduction */ + protected array $gotoDefault; + + /** @var int[] Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for + * determining the state to goto after reduction. */ + protected array $ruleToNonTerminal; + /** @var int[] Map of rules to the length of their right-hand side, which is the number of elements that have to + * be popped from the stack(s) on reduction. */ + protected array $ruleToLength; + + /* + * The following members are part of the parser state: + */ + + /** @var mixed Temporary value containing the result of last semantic action (reduction) */ + protected $semValue; + /** @var mixed[] Semantic value stack (contains values of tokens and semantic action results) */ + protected array $semStack; + /** @var int[] Token start position stack */ + protected array $tokenStartStack; + /** @var int[] Token end position stack */ + protected array $tokenEndStack; + + /** @var ErrorHandler Error handler */ + protected ErrorHandler $errorHandler; + /** @var int Error state, used to avoid error floods */ + protected int $errorState; + + /** @var \SplObjectStorage<Array_, null>|null Array nodes created during parsing, for postprocessing of empty elements. */ + protected ?\SplObjectStorage $createdArrays; + + /** @var Token[] Tokens for the current parse */ + protected array $tokens; + /** @var int Current position in token array */ + protected int $tokenPos; + + /** + * Initialize $reduceCallbacks map. + */ + abstract protected function initReduceCallbacks(): void; + + /** + * Creates a parser instance. + * + * Options: + * * phpVersion: ?PhpVersion, + * + * @param Lexer $lexer A lexer + * @param PhpVersion $phpVersion PHP version to target, defaults to latest supported. This + * option is best-effort: Even if specified, parsing will generally assume the latest + * supported version and only adjust behavior in minor ways, for example by omitting + * errors in older versions and interpreting type hints as a name or identifier depending + * on version. + */ + public function __construct(Lexer $lexer, ?PhpVersion $phpVersion = null) { + $this->lexer = $lexer; + $this->phpVersion = $phpVersion ?? PhpVersion::getNewestSupported(); + + $this->initReduceCallbacks(); + $this->phpTokenToSymbol = $this->createTokenMap(); + $this->dropTokens = array_fill_keys( + [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], true + ); + } + + /** + * Parses PHP code into a node tree. + * + * If a non-throwing error handler is used, the parser will continue parsing after an error + * occurred and attempt to build a partial AST. + * + * @param string $code The source code to parse + * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults + * to ErrorHandler\Throwing. + * + * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and + * the parser was unable to recover from an error). + */ + public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array { + $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing(); + $this->createdArrays = new \SplObjectStorage(); + + $this->tokens = $this->lexer->tokenize($code, $this->errorHandler); + $result = $this->doParse(); + + // Report errors for any empty elements used inside arrays. This is delayed until after the main parse, + // because we don't know a priori whether a given array expression will be used in a destructuring context + // or not. + foreach ($this->createdArrays as $node) { + foreach ($node->items as $item) { + if ($item->value instanceof Expr\Error) { + $this->errorHandler->handleError( + new Error('Cannot use empty array elements in arrays', $item->getAttributes())); + } + } + } + + // Clear out some of the interior state, so we don't hold onto unnecessary + // memory between uses of the parser + $this->tokenStartStack = []; + $this->tokenEndStack = []; + $this->semStack = []; + $this->semValue = null; + $this->createdArrays = null; + + if ($result !== null) { + $traverser = new NodeTraverser(new CommentAnnotatingVisitor($this->tokens)); + $traverser->traverse($result); + } + + return $result; + } + + public function getTokens(): array { + return $this->tokens; + } + + /** @return Stmt[]|null */ + protected function doParse(): ?array { + // We start off with no lookahead-token + $symbol = self::SYMBOL_NONE; + $tokenValue = null; + $this->tokenPos = -1; + + // Keep stack of start and end attributes + $this->tokenStartStack = []; + $this->tokenEndStack = [0]; + + // Start off in the initial state and keep a stack of previous states + $state = 0; + $stateStack = [$state]; + + // Semantic value stack (contains values of tokens and semantic action results) + $this->semStack = []; + + // Current position in the stack(s) + $stackPos = 0; + + $this->errorState = 0; + + for (;;) { + //$this->traceNewState($state, $symbol); + + if ($this->actionBase[$state] === 0) { + $rule = $this->actionDefault[$state]; + } else { + if ($symbol === self::SYMBOL_NONE) { + do { + $token = $this->tokens[++$this->tokenPos]; + $tokenId = $token->id; + } while (isset($this->dropTokens[$tokenId])); + + // Map the lexer token id to the internally used symbols. + $tokenValue = $token->text; + if (!isset($this->phpTokenToSymbol[$tokenId])) { + throw new \RangeException(sprintf( + 'The lexer returned an invalid token (id=%d, value=%s)', + $tokenId, $tokenValue + )); + } + $symbol = $this->phpTokenToSymbol[$tokenId]; + + //$this->traceRead($symbol); + } + + $idx = $this->actionBase[$state] + $symbol; + if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol) + || ($state < $this->YY2TBLSTATE + && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0 + && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol)) + && ($action = $this->action[$idx]) !== $this->defaultAction) { + /* + * >= numNonLeafStates: shift and reduce + * > 0: shift + * = 0: accept + * < 0: reduce + * = -YYUNEXPECTED: error + */ + if ($action > 0) { + /* shift */ + //$this->traceShift($symbol); + + ++$stackPos; + $stateStack[$stackPos] = $state = $action; + $this->semStack[$stackPos] = $tokenValue; + $this->tokenStartStack[$stackPos] = $this->tokenPos; + $this->tokenEndStack[$stackPos] = $this->tokenPos; + $symbol = self::SYMBOL_NONE; + + if ($this->errorState) { + --$this->errorState; + } + + if ($action < $this->numNonLeafStates) { + continue; + } + + /* $yyn >= numNonLeafStates means shift-and-reduce */ + $rule = $action - $this->numNonLeafStates; + } else { + $rule = -$action; + } + } else { + $rule = $this->actionDefault[$state]; + } + } + + for (;;) { + if ($rule === 0) { + /* accept */ + //$this->traceAccept(); + return $this->semValue; + } + if ($rule !== $this->unexpectedTokenRule) { + /* reduce */ + //$this->traceReduce($rule); + + $ruleLength = $this->ruleToLength[$rule]; + try { + $callback = $this->reduceCallbacks[$rule]; + if ($callback !== null) { + $callback($this, $stackPos); + } elseif ($ruleLength > 0) { + $this->semValue = $this->semStack[$stackPos - $ruleLength + 1]; + } + } catch (Error $e) { + if (-1 === $e->getStartLine()) { + $e->setStartLine($this->tokens[$this->tokenPos]->line); + } + + $this->emitError($e); + // Can't recover from this type of error + return null; + } + + /* Goto - shift nonterminal */ + $lastTokenEnd = $this->tokenEndStack[$stackPos]; + $stackPos -= $ruleLength; + $nonTerminal = $this->ruleToNonTerminal[$rule]; + $idx = $this->gotoBase[$nonTerminal] + $stateStack[$stackPos]; + if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] === $nonTerminal) { + $state = $this->goto[$idx]; + } else { + $state = $this->gotoDefault[$nonTerminal]; + } + + ++$stackPos; + $stateStack[$stackPos] = $state; + $this->semStack[$stackPos] = $this->semValue; + $this->tokenEndStack[$stackPos] = $lastTokenEnd; + if ($ruleLength === 0) { + // Empty productions use the start attributes of the lookahead token. + $this->tokenStartStack[$stackPos] = $this->tokenPos; + } + } else { + /* error */ + switch ($this->errorState) { + case 0: + $msg = $this->getErrorMessage($symbol, $state); + $this->emitError(new Error($msg, $this->getAttributesForToken($this->tokenPos))); + // Break missing intentionally + // no break + case 1: + case 2: + $this->errorState = 3; + + // Pop until error-expecting state uncovered + while (!( + (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0 + && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol) + || ($state < $this->YY2TBLSTATE + && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $this->errorSymbol) >= 0 + && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol) + ) || ($action = $this->action[$idx]) === $this->defaultAction) { // Not totally sure about this + if ($stackPos <= 0) { + // Could not recover from error + return null; + } + $state = $stateStack[--$stackPos]; + //$this->tracePop($state); + } + + //$this->traceShift($this->errorSymbol); + ++$stackPos; + $stateStack[$stackPos] = $state = $action; + + // We treat the error symbol as being empty, so we reset the end attributes + // to the end attributes of the last non-error symbol + $this->tokenStartStack[$stackPos] = $this->tokenPos; + $this->tokenEndStack[$stackPos] = $this->tokenEndStack[$stackPos - 1]; + break; + + case 3: + if ($symbol === 0) { + // Reached EOF without recovering from error + return null; + } + + //$this->traceDiscard($symbol); + $symbol = self::SYMBOL_NONE; + break 2; + } + } + + if ($state < $this->numNonLeafStates) { + break; + } + + /* >= numNonLeafStates means shift-and-reduce */ + $rule = $state - $this->numNonLeafStates; + } + } + + throw new \RuntimeException('Reached end of parser loop'); + } + + protected function emitError(Error $error): void { + $this->errorHandler->handleError($error); + } + + /** + * Format error message including expected tokens. + * + * @param int $symbol Unexpected symbol + * @param int $state State at time of error + * + * @return string Formatted error message + */ + protected function getErrorMessage(int $symbol, int $state): string { + $expectedString = ''; + if ($expected = $this->getExpectedTokens($state)) { + $expectedString = ', expecting ' . implode(' or ', $expected); + } + + return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString; + } + + /** + * Get limited number of expected tokens in given state. + * + * @param int $state State + * + * @return string[] Expected tokens. If too many, an empty array is returned. + */ + protected function getExpectedTokens(int $state): array { + $expected = []; + + $base = $this->actionBase[$state]; + foreach ($this->symbolToName as $symbol => $name) { + $idx = $base + $symbol; + if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol + || $state < $this->YY2TBLSTATE + && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0 + && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol + ) { + if ($this->action[$idx] !== $this->unexpectedTokenRule + && $this->action[$idx] !== $this->defaultAction + && $symbol !== $this->errorSymbol + ) { + if (count($expected) === 4) { + /* Too many expected tokens */ + return []; + } + + $expected[] = $name; + } + } + } + + return $expected; + } + + /** + * Get attributes for a node with the given start and end token positions. + * + * @param int $tokenStartPos Token position the node starts at + * @param int $tokenEndPos Token position the node ends at + * @return array<string, mixed> Attributes + */ + protected function getAttributes(int $tokenStartPos, int $tokenEndPos): array { + $startToken = $this->tokens[$tokenStartPos]; + $afterEndToken = $this->tokens[$tokenEndPos + 1]; + return [ + 'startLine' => $startToken->line, + 'startTokenPos' => $tokenStartPos, + 'startFilePos' => $startToken->pos, + 'endLine' => $afterEndToken->line, + 'endTokenPos' => $tokenEndPos, + 'endFilePos' => $afterEndToken->pos - 1, + ]; + } + + /** + * Get attributes for a single token at the given token position. + * + * @return array<string, mixed> Attributes + */ + protected function getAttributesForToken(int $tokenPos): array { + if ($tokenPos < \count($this->tokens) - 1) { + return $this->getAttributes($tokenPos, $tokenPos); + } + + // Get attributes for the sentinel token. + $token = $this->tokens[$tokenPos]; + return [ + 'startLine' => $token->line, + 'startTokenPos' => $tokenPos, + 'startFilePos' => $token->pos, + 'endLine' => $token->line, + 'endTokenPos' => $tokenPos, + 'endFilePos' => $token->pos, + ]; + } + + /* + * Tracing functions used for debugging the parser. + */ + + /* + protected function traceNewState($state, $symbol): void { + echo '% State ' . $state + . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n"; + } + + protected function traceRead($symbol): void { + echo '% Reading ' . $this->symbolToName[$symbol] . "\n"; + } + + protected function traceShift($symbol): void { + echo '% Shift ' . $this->symbolToName[$symbol] . "\n"; + } + + protected function traceAccept(): void { + echo "% Accepted.\n"; + } + + protected function traceReduce($n): void { + echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n"; + } + + protected function tracePop($state): void { + echo '% Recovering, uncovered state ' . $state . "\n"; + } + + protected function traceDiscard($symbol): void { + echo '% Discard ' . $this->symbolToName[$symbol] . "\n"; + } + */ + + /* + * Helper functions invoked by semantic actions + */ + + /** + * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions. + * + * @param Node\Stmt[] $stmts + * @return Node\Stmt[] + */ + protected function handleNamespaces(array $stmts): array { + $hasErrored = false; + $style = $this->getNamespacingStyle($stmts); + if (null === $style) { + // not namespaced, nothing to do + return $stmts; + } + if ('brace' === $style) { + // For braced namespaces we only have to check that there are no invalid statements between the namespaces + $afterFirstNamespace = false; + foreach ($stmts as $stmt) { + if ($stmt instanceof Node\Stmt\Namespace_) { + $afterFirstNamespace = true; + } elseif (!$stmt instanceof Node\Stmt\HaltCompiler + && !$stmt instanceof Node\Stmt\Nop + && $afterFirstNamespace && !$hasErrored) { + $this->emitError(new Error( + 'No code may exist outside of namespace {}', $stmt->getAttributes())); + $hasErrored = true; // Avoid one error for every statement + } + } + return $stmts; + } else { + // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts + $resultStmts = []; + $targetStmts = &$resultStmts; + $lastNs = null; + foreach ($stmts as $stmt) { + if ($stmt instanceof Node\Stmt\Namespace_) { + if ($lastNs !== null) { + $this->fixupNamespaceAttributes($lastNs); + } + if ($stmt->stmts === null) { + $stmt->stmts = []; + $targetStmts = &$stmt->stmts; + $resultStmts[] = $stmt; + } else { + // This handles the invalid case of mixed style namespaces + $resultStmts[] = $stmt; + $targetStmts = &$resultStmts; + } + $lastNs = $stmt; + } elseif ($stmt instanceof Node\Stmt\HaltCompiler) { + // __halt_compiler() is not moved into the namespace + $resultStmts[] = $stmt; + } else { + $targetStmts[] = $stmt; + } + } + if ($lastNs !== null) { + $this->fixupNamespaceAttributes($lastNs); + } + return $resultStmts; + } + } + + private function fixupNamespaceAttributes(Node\Stmt\Namespace_ $stmt): void { + // We moved the statements into the namespace node, as such the end of the namespace node + // needs to be extended to the end of the statements. + if (empty($stmt->stmts)) { + return; + } + + // We only move the builtin end attributes here. This is the best we can do with the + // knowledge we have. + $endAttributes = ['endLine', 'endFilePos', 'endTokenPos']; + $lastStmt = $stmt->stmts[count($stmt->stmts) - 1]; + foreach ($endAttributes as $endAttribute) { + if ($lastStmt->hasAttribute($endAttribute)) { + $stmt->setAttribute($endAttribute, $lastStmt->getAttribute($endAttribute)); + } + } + } + + /** @return array<string, mixed> */ + private function getNamespaceErrorAttributes(Namespace_ $node): array { + $attrs = $node->getAttributes(); + // Adjust end attributes to only cover the "namespace" keyword, not the whole namespace. + if (isset($attrs['startLine'])) { + $attrs['endLine'] = $attrs['startLine']; + } + if (isset($attrs['startTokenPos'])) { + $attrs['endTokenPos'] = $attrs['startTokenPos']; + } + if (isset($attrs['startFilePos'])) { + $attrs['endFilePos'] = $attrs['startFilePos'] + \strlen('namespace') - 1; + } + return $attrs; + } + + /** + * Determine namespacing style (semicolon or brace) + * + * @param Node[] $stmts Top-level statements. + * + * @return null|string One of "semicolon", "brace" or null (no namespaces) + */ + private function getNamespacingStyle(array $stmts): ?string { + $style = null; + $hasNotAllowedStmts = false; + foreach ($stmts as $i => $stmt) { + if ($stmt instanceof Node\Stmt\Namespace_) { + $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace'; + if (null === $style) { + $style = $currentStyle; + if ($hasNotAllowedStmts) { + $this->emitError(new Error( + 'Namespace declaration statement has to be the very first statement in the script', + $this->getNamespaceErrorAttributes($stmt) + )); + } + } elseif ($style !== $currentStyle) { + $this->emitError(new Error( + 'Cannot mix bracketed namespace declarations with unbracketed namespace declarations', + $this->getNamespaceErrorAttributes($stmt) + )); + // Treat like semicolon style for namespace normalization + return 'semicolon'; + } + continue; + } + + /* declare(), __halt_compiler() and nops can be used before a namespace declaration */ + if ($stmt instanceof Node\Stmt\Declare_ + || $stmt instanceof Node\Stmt\HaltCompiler + || $stmt instanceof Node\Stmt\Nop) { + continue; + } + + /* There may be a hashbang line at the very start of the file */ + if ($i === 0 && $stmt instanceof Node\Stmt\InlineHTML && preg_match('/\A#!.*\r?\n\z/', $stmt->value)) { + continue; + } + + /* Everything else if forbidden before namespace declarations */ + $hasNotAllowedStmts = true; + } + return $style; + } + + /** @return Name|Identifier */ + protected function handleBuiltinTypes(Name $name) { + if (!$name->isUnqualified()) { + return $name; + } + + $lowerName = $name->toLowerString(); + if (!$this->phpVersion->supportsBuiltinType($lowerName)) { + return $name; + } + + return new Node\Identifier($lowerName, $name->getAttributes()); + } + + /** + * Get combined start and end attributes at a stack location + * + * @param int $stackPos Stack location + * + * @return array<string, mixed> Combined start and end attributes + */ + protected function getAttributesAt(int $stackPos): array { + return $this->getAttributes($this->tokenStartStack[$stackPos], $this->tokenEndStack[$stackPos]); + } + + protected function getFloatCastKind(string $cast): int { + $cast = strtolower($cast); + if (strpos($cast, 'float') !== false) { + return Double::KIND_FLOAT; + } + + if (strpos($cast, 'real') !== false) { + return Double::KIND_REAL; + } + + return Double::KIND_DOUBLE; + } + + /** @param array<string, mixed> $attributes */ + protected function parseLNumber(string $str, array $attributes, bool $allowInvalidOctal = false): Int_ { + try { + return Int_::fromString($str, $attributes, $allowInvalidOctal); + } catch (Error $error) { + $this->emitError($error); + // Use dummy value + return new Int_(0, $attributes); + } + } + + /** + * Parse a T_NUM_STRING token into either an integer or string node. + * + * @param string $str Number string + * @param array<string, mixed> $attributes Attributes + * + * @return Int_|String_ Integer or string node. + */ + protected function parseNumString(string $str, array $attributes) { + if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) { + return new String_($str, $attributes); + } + + $num = +$str; + if (!is_int($num)) { + return new String_($str, $attributes); + } + + return new Int_($num, $attributes); + } + + /** @param array<string, mixed> $attributes */ + protected function stripIndentation( + string $string, int $indentLen, string $indentChar, + bool $newlineAtStart, bool $newlineAtEnd, array $attributes + ): string { + if ($indentLen === 0) { + return $string; + } + + $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)'; + $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])'; + $regex = '/' . $start . '([ \t]*)(' . $end . ')?/'; + return preg_replace_callback( + $regex, + function ($matches) use ($indentLen, $indentChar, $attributes) { + $prefix = substr($matches[1], 0, $indentLen); + if (false !== strpos($prefix, $indentChar === " " ? "\t" : " ")) { + $this->emitError(new Error( + 'Invalid indentation - tabs and spaces cannot be mixed', $attributes + )); + } elseif (strlen($prefix) < $indentLen && !isset($matches[2])) { + $this->emitError(new Error( + 'Invalid body indentation level ' . + '(expecting an indentation level of at least ' . $indentLen . ')', + $attributes + )); + } + return substr($matches[0], strlen($prefix)); + }, + $string + ); + } + + /** + * @param string|(Expr|InterpolatedStringPart)[] $contents + * @param array<string, mixed> $attributes + * @param array<string, mixed> $endTokenAttributes + */ + protected function parseDocString( + string $startToken, $contents, string $endToken, + array $attributes, array $endTokenAttributes, bool $parseUnicodeEscape + ): Expr { + $kind = strpos($startToken, "'") === false + ? String_::KIND_HEREDOC : String_::KIND_NOWDOC; + + $regex = '/\A[bB]?<<<[ \t]*[\'"]?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\'"]?(?:\r\n|\n|\r)\z/'; + $result = preg_match($regex, $startToken, $matches); + assert($result === 1); + $label = $matches[1]; + + $result = preg_match('/\A[ \t]*/', $endToken, $matches); + assert($result === 1); + $indentation = $matches[0]; + + $attributes['kind'] = $kind; + $attributes['docLabel'] = $label; + $attributes['docIndentation'] = $indentation; + + $indentHasSpaces = false !== strpos($indentation, " "); + $indentHasTabs = false !== strpos($indentation, "\t"); + if ($indentHasSpaces && $indentHasTabs) { + $this->emitError(new Error( + 'Invalid indentation - tabs and spaces cannot be mixed', + $endTokenAttributes + )); + + // Proceed processing as if this doc string is not indented + $indentation = ''; + } + + $indentLen = \strlen($indentation); + $indentChar = $indentHasSpaces ? " " : "\t"; + + if (\is_string($contents)) { + if ($contents === '') { + $attributes['rawValue'] = $contents; + return new String_('', $attributes); + } + + $contents = $this->stripIndentation( + $contents, $indentLen, $indentChar, true, true, $attributes + ); + $contents = preg_replace('~(\r\n|\n|\r)\z~', '', $contents); + $attributes['rawValue'] = $contents; + + if ($kind === String_::KIND_HEREDOC) { + $contents = String_::parseEscapeSequences($contents, null, $parseUnicodeEscape); + } + + return new String_($contents, $attributes); + } else { + assert(count($contents) > 0); + if (!$contents[0] instanceof Node\InterpolatedStringPart) { + // If there is no leading encapsed string part, pretend there is an empty one + $this->stripIndentation( + '', $indentLen, $indentChar, true, false, $contents[0]->getAttributes() + ); + } + + $newContents = []; + foreach ($contents as $i => $part) { + if ($part instanceof Node\InterpolatedStringPart) { + $isLast = $i === \count($contents) - 1; + $part->value = $this->stripIndentation( + $part->value, $indentLen, $indentChar, + $i === 0, $isLast, $part->getAttributes() + ); + if ($isLast) { + $part->value = preg_replace('~(\r\n|\n|\r)\z~', '', $part->value); + } + $part->setAttribute('rawValue', $part->value); + $part->value = String_::parseEscapeSequences($part->value, null, $parseUnicodeEscape); + if ('' === $part->value) { + continue; + } + } + $newContents[] = $part; + } + return new InterpolatedString($newContents, $attributes); + } + } + + protected function createCommentFromToken(Token $token, int $tokenPos): Comment { + assert($token->id === \T_COMMENT || $token->id == \T_DOC_COMMENT); + return \T_DOC_COMMENT === $token->id + ? new Comment\Doc($token->text, $token->line, $token->pos, $tokenPos, + $token->getEndLine(), $token->getEndPos() - 1, $tokenPos) + : new Comment($token->text, $token->line, $token->pos, $tokenPos, + $token->getEndLine(), $token->getEndPos() - 1, $tokenPos); + } + + /** + * Get last comment before the given token position, if any + */ + protected function getCommentBeforeToken(int $tokenPos): ?Comment { + while (--$tokenPos >= 0) { + $token = $this->tokens[$tokenPos]; + if (!isset($this->dropTokens[$token->id])) { + break; + } + + if ($token->id === \T_COMMENT || $token->id === \T_DOC_COMMENT) { + return $this->createCommentFromToken($token, $tokenPos); + } + } + return null; + } + + /** + * Create a zero-length nop to capture preceding comments, if any. + */ + protected function maybeCreateZeroLengthNop(int $tokenPos): ?Nop { + $comment = $this->getCommentBeforeToken($tokenPos); + if ($comment === null) { + return null; + } + + $commentEndLine = $comment->getEndLine(); + $commentEndFilePos = $comment->getEndFilePos(); + $commentEndTokenPos = $comment->getEndTokenPos(); + $attributes = [ + 'startLine' => $commentEndLine, + 'endLine' => $commentEndLine, + 'startFilePos' => $commentEndFilePos + 1, + 'endFilePos' => $commentEndFilePos, + 'startTokenPos' => $commentEndTokenPos + 1, + 'endTokenPos' => $commentEndTokenPos, + ]; + return new Nop($attributes); + } + + protected function maybeCreateNop(int $tokenStartPos, int $tokenEndPos): ?Nop { + if ($this->getCommentBeforeToken($tokenStartPos) === null) { + return null; + } + return new Nop($this->getAttributes($tokenStartPos, $tokenEndPos)); + } + + protected function handleHaltCompiler(): string { + // Prevent the lexer from returning any further tokens. + $nextToken = $this->tokens[$this->tokenPos + 1]; + $this->tokenPos = \count($this->tokens) - 2; + + // Return text after __halt_compiler. + return $nextToken->id === \T_INLINE_HTML ? $nextToken->text : ''; + } + + protected function inlineHtmlHasLeadingNewline(int $stackPos): bool { + $tokenPos = $this->tokenStartStack[$stackPos]; + $token = $this->tokens[$tokenPos]; + assert($token->id == \T_INLINE_HTML); + if ($tokenPos > 0) { + $prevToken = $this->tokens[$tokenPos - 1]; + assert($prevToken->id == \T_CLOSE_TAG); + return false !== strpos($prevToken->text, "\n") + || false !== strpos($prevToken->text, "\r"); + } + return true; + } + + /** + * @return array<string, mixed> + */ + protected function createEmptyElemAttributes(int $tokenPos): array { + return $this->getAttributesForToken($tokenPos); + } + + protected function fixupArrayDestructuring(Array_ $node): Expr\List_ { + $this->createdArrays->detach($node); + return new Expr\List_(array_map(function (Node\ArrayItem $item) { + if ($item->value instanceof Expr\Error) { + // We used Error as a placeholder for empty elements, which are legal for destructuring. + return null; + } + if ($item->value instanceof Array_) { + return new Node\ArrayItem( + $this->fixupArrayDestructuring($item->value), + $item->key, $item->byRef, $item->getAttributes()); + } + return $item; + }, $node->items), ['kind' => Expr\List_::KIND_ARRAY] + $node->getAttributes()); + } + + protected function postprocessList(Expr\List_ $node): void { + foreach ($node->items as $i => $item) { + if ($item->value instanceof Expr\Error) { + // We used Error as a placeholder for empty elements, which are legal for destructuring. + $node->items[$i] = null; + } + } + } + + /** @param ElseIf_|Else_ $node */ + protected function fixupAlternativeElse($node): void { + // Make sure a trailing nop statement carrying comments is part of the node. + $numStmts = \count($node->stmts); + if ($numStmts !== 0 && $node->stmts[$numStmts - 1] instanceof Nop) { + $nopAttrs = $node->stmts[$numStmts - 1]->getAttributes(); + if (isset($nopAttrs['endLine'])) { + $node->setAttribute('endLine', $nopAttrs['endLine']); + } + if (isset($nopAttrs['endFilePos'])) { + $node->setAttribute('endFilePos', $nopAttrs['endFilePos']); + } + if (isset($nopAttrs['endTokenPos'])) { + $node->setAttribute('endTokenPos', $nopAttrs['endTokenPos']); + } + } + } + + protected function checkClassModifier(int $a, int $b, int $modifierPos): void { + try { + Modifiers::verifyClassModifier($a, $b); + } catch (Error $error) { + $error->setAttributes($this->getAttributesAt($modifierPos)); + $this->emitError($error); + } + } + + protected function checkModifier(int $a, int $b, int $modifierPos): void { + // Jumping through some hoops here because verifyModifier() is also used elsewhere + try { + Modifiers::verifyModifier($a, $b); + } catch (Error $error) { + $error->setAttributes($this->getAttributesAt($modifierPos)); + $this->emitError($error); + } + } + + protected function checkParam(Param $node): void { + if ($node->variadic && null !== $node->default) { + $this->emitError(new Error( + 'Variadic parameter cannot have a default value', + $node->default->getAttributes() + )); + } + } + + protected function checkTryCatch(TryCatch $node): void { + if (empty($node->catches) && null === $node->finally) { + $this->emitError(new Error( + 'Cannot use try without catch or finally', $node->getAttributes() + )); + } + } + + protected function checkNamespace(Namespace_ $node): void { + if (null !== $node->stmts) { + foreach ($node->stmts as $stmt) { + if ($stmt instanceof Namespace_) { + $this->emitError(new Error( + 'Namespace declarations cannot be nested', $stmt->getAttributes() + )); + } + } + } + } + + private function checkClassName(?Identifier $name, int $namePos): void { + if (null !== $name && $name->isSpecialClassName()) { + $this->emitError(new Error( + sprintf('Cannot use \'%s\' as class name as it is reserved', $name), + $this->getAttributesAt($namePos) + )); + } + } + + /** @param Name[] $interfaces */ + private function checkImplementedInterfaces(array $interfaces): void { + foreach ($interfaces as $interface) { + if ($interface->isSpecialClassName()) { + $this->emitError(new Error( + sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface), + $interface->getAttributes() + )); + } + } + } + + protected function checkClass(Class_ $node, int $namePos): void { + $this->checkClassName($node->name, $namePos); + + if ($node->extends && $node->extends->isSpecialClassName()) { + $this->emitError(new Error( + sprintf('Cannot use \'%s\' as class name as it is reserved', $node->extends), + $node->extends->getAttributes() + )); + } + + $this->checkImplementedInterfaces($node->implements); + } + + protected function checkInterface(Interface_ $node, int $namePos): void { + $this->checkClassName($node->name, $namePos); + $this->checkImplementedInterfaces($node->extends); + } + + protected function checkEnum(Enum_ $node, int $namePos): void { + $this->checkClassName($node->name, $namePos); + $this->checkImplementedInterfaces($node->implements); + } + + protected function checkClassMethod(ClassMethod $node, int $modifierPos): void { + if ($node->flags & Modifiers::STATIC) { + switch ($node->name->toLowerString()) { + case '__construct': + $this->emitError(new Error( + sprintf('Constructor %s() cannot be static', $node->name), + $this->getAttributesAt($modifierPos))); + break; + case '__destruct': + $this->emitError(new Error( + sprintf('Destructor %s() cannot be static', $node->name), + $this->getAttributesAt($modifierPos))); + break; + case '__clone': + $this->emitError(new Error( + sprintf('Clone method %s() cannot be static', $node->name), + $this->getAttributesAt($modifierPos))); + break; + } + } + + if ($node->flags & Modifiers::READONLY) { + $this->emitError(new Error( + sprintf('Method %s() cannot be readonly', $node->name), + $this->getAttributesAt($modifierPos))); + } + } + + protected function checkClassConst(ClassConst $node, int $modifierPos): void { + if ($node->flags & Modifiers::STATIC) { + $this->emitError(new Error( + "Cannot use 'static' as constant modifier", + $this->getAttributesAt($modifierPos))); + } + if ($node->flags & Modifiers::ABSTRACT) { + $this->emitError(new Error( + "Cannot use 'abstract' as constant modifier", + $this->getAttributesAt($modifierPos))); + } + if ($node->flags & Modifiers::READONLY) { + $this->emitError(new Error( + "Cannot use 'readonly' as constant modifier", + $this->getAttributesAt($modifierPos))); + } + } + + protected function checkProperty(Property $node, int $modifierPos): void { + if ($node->flags & Modifiers::ABSTRACT) { + $this->emitError(new Error('Properties cannot be declared abstract', + $this->getAttributesAt($modifierPos))); + } + + if ($node->flags & Modifiers::FINAL) { + $this->emitError(new Error('Properties cannot be declared final', + $this->getAttributesAt($modifierPos))); + } + } + + protected function checkUseUse(UseItem $node, int $namePos): void { + if ($node->alias && $node->alias->isSpecialClassName()) { + $this->emitError(new Error( + sprintf( + 'Cannot use %s as %s because \'%2$s\' is a special class name', + $node->name, $node->alias + ), + $this->getAttributesAt($namePos) + )); + } + } + + /** + * Creates the token map. + * + * The token map maps the PHP internal token identifiers + * to the identifiers used by the Parser. Additionally it + * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'. + * + * @return array<int, int> The token map + */ + protected function createTokenMap(): array { + $tokenMap = []; + + for ($i = 0; $i < 1000; ++$i) { + if ($i < 256) { + // Single-char tokens use an identity mapping. + $tokenMap[$i] = $i; + } elseif (\T_DOUBLE_COLON === $i) { + // T_DOUBLE_COLON is equivalent to T_PAAMAYIM_NEKUDOTAYIM + $tokenMap[$i] = static::T_PAAMAYIM_NEKUDOTAYIM; + } elseif (\T_OPEN_TAG_WITH_ECHO === $i) { + // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO + $tokenMap[$i] = static::T_ECHO; + } elseif (\T_CLOSE_TAG === $i) { + // T_CLOSE_TAG is equivalent to ';' + $tokenMap[$i] = ord(';'); + } elseif ('UNKNOWN' !== $name = token_name($i)) { + if (defined($name = static::class . '::' . $name)) { + // Other tokens can be mapped directly + $tokenMap[$i] = constant($name); + } + } + } + + // Assign tokens for which we define compatibility constants, as token_name() does not know them. + $tokenMap[\T_FN] = static::T_FN; + $tokenMap[\T_COALESCE_EQUAL] = static::T_COALESCE_EQUAL; + $tokenMap[\T_NAME_QUALIFIED] = static::T_NAME_QUALIFIED; + $tokenMap[\T_NAME_FULLY_QUALIFIED] = static::T_NAME_FULLY_QUALIFIED; + $tokenMap[\T_NAME_RELATIVE] = static::T_NAME_RELATIVE; + $tokenMap[\T_MATCH] = static::T_MATCH; + $tokenMap[\T_NULLSAFE_OBJECT_OPERATOR] = static::T_NULLSAFE_OBJECT_OPERATOR; + $tokenMap[\T_ATTRIBUTE] = static::T_ATTRIBUTE; + $tokenMap[\T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG] = static::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG; + $tokenMap[\T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG] = static::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG; + $tokenMap[\T_ENUM] = static::T_ENUM; + $tokenMap[\T_READONLY] = static::T_READONLY; + + // We have create a map from PHP token IDs to external symbol IDs. + // Now map them to the internal symbol ID. + $fullTokenMap = []; + foreach ($tokenMap as $phpToken => $extSymbol) { + $intSymbol = $this->tokenToSymbol[$extSymbol]; + if ($intSymbol === $this->invalidSymbol) { + continue; + } + $fullTokenMap[$phpToken] = $intSymbol; + } + + return $fullTokenMap; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php new file mode 100644 index 0000000..3a7586e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php @@ -0,0 +1,42 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Parser\Php7; +use PhpParser\Parser\Php8; + +class ParserFactory { + /** + * Create a parser targeting the given version on a best-effort basis. The parser will generally + * accept code for the newest supported version, but will try to accommodate code that becomes + * invalid in newer versions or changes in interpretation. + */ + public function createForVersion(PhpVersion $version): Parser { + if ($version->isHostVersion()) { + $lexer = new Lexer(); + } else { + $lexer = new Lexer\Emulative($version); + } + if ($version->id >= 80000) { + return new Php8($lexer, $version); + } + return new Php7($lexer, $version); + } + + /** + * Create a parser targeting the newest version supported by this library. Code for older + * versions will be accepted if there have been no relevant backwards-compatibility breaks in + * PHP. + */ + public function createForNewestSupportedVersion(): Parser { + return $this->createForVersion(PhpVersion::getNewestSupported()); + } + + /** + * Create a parser targeting the host PHP version, that is the PHP version we're currently + * running on. This parser will not use any token emulation. + */ + public function createForHostVersion(): Parser { + return $this->createForVersion(PhpVersion::getHostVersion()); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PhpVersion.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PhpVersion.php new file mode 100644 index 0000000..db85b1e --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PhpVersion.php @@ -0,0 +1,164 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +/** + * A PHP version, representing only the major and minor version components. + */ +class PhpVersion { + /** @var int Version ID in PHP_VERSION_ID format */ + public int $id; + + /** @var int[] Minimum versions for builtin types */ + private const BUILTIN_TYPE_VERSIONS = [ + 'array' => 50100, + 'callable' => 50400, + 'bool' => 70000, + 'int' => 70000, + 'float' => 70000, + 'string' => 70000, + 'iterable' => 70100, + 'void' => 70100, + 'object' => 70200, + 'null' => 80000, + 'false' => 80000, + 'mixed' => 80000, + 'never' => 80100, + 'true' => 80200, + ]; + + private function __construct(int $id) { + $this->id = $id; + } + + /** + * Create a PhpVersion object from major and minor version components. + */ + public static function fromComponents(int $major, int $minor): self { + return new self($major * 10000 + $minor * 100); + } + + /** + * Get the newest PHP version supported by this library. Support for this version may be partial, + * if it is still under development. + */ + public static function getNewestSupported(): self { + return self::fromComponents(8, 3); + } + + /** + * Get the host PHP version, that is the PHP version we're currently running on. + */ + public static function getHostVersion(): self { + return self::fromComponents(\PHP_MAJOR_VERSION, \PHP_MINOR_VERSION); + } + + /** + * Parse the version from a string like "8.1". + */ + public static function fromString(string $version): self { + if (!preg_match('/^(\d+)\.(\d+)/', $version, $matches)) { + throw new \LogicException("Invalid PHP version \"$version\""); + } + return self::fromComponents((int) $matches[1], (int) $matches[2]); + } + + /** + * Check whether two versions are the same. + */ + public function equals(PhpVersion $other): bool { + return $this->id === $other->id; + } + + /** + * Check whether this version is greater than or equal to the argument. + */ + public function newerOrEqual(PhpVersion $other): bool { + return $this->id >= $other->id; + } + + /** + * Check whether this version is older than the argument. + */ + public function older(PhpVersion $other): bool { + return $this->id < $other->id; + } + + /** + * Check whether this is the host PHP version. + */ + public function isHostVersion(): bool { + return $this->equals(self::getHostVersion()); + } + + /** + * Check whether this PHP version supports the given builtin type. Type name must be lowercase. + */ + public function supportsBuiltinType(string $type): bool { + $minVersion = self::BUILTIN_TYPE_VERSIONS[$type] ?? null; + return $minVersion !== null && $this->id >= $minVersion; + } + + /** + * Whether this version supports [] array literals. + */ + public function supportsShortArraySyntax(): bool { + return $this->id >= 50400; + } + + /** + * Whether this version supports [] for destructuring. + */ + public function supportsShortArrayDestructuring(): bool { + return $this->id >= 70100; + } + + /** + * Whether this version supports flexible heredoc/nowdoc. + */ + public function supportsFlexibleHeredoc(): bool { + return $this->id >= 70300; + } + + /** + * Whether this version supports trailing commas in parameter lists. + */ + public function supportsTrailingCommaInParamList(): bool { + return $this->id >= 80000; + } + + /** + * Whether this version allows "$var =& new Obj". + */ + public function allowsAssignNewByReference(): bool { + return $this->id < 70000; + } + + /** + * Whether this version allows invalid octals like "08". + */ + public function allowsInvalidOctals(): bool { + return $this->id < 70000; + } + + /** + * Whether this version allows DEL (\x7f) to occur in identifiers. + */ + public function allowsDelInIdentifiers(): bool { + return $this->id < 70100; + } + + /** + * Whether this version supports yield in expression context without parentheses. + */ + public function supportsYieldWithoutParentheses(): bool { + return $this->id >= 70000; + } + + /** + * Whether this version supports unicode escape sequences in strings. + */ + public function supportsUnicodeEscapes(): bool { + return $this->id >= 70000; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter.php new file mode 100644 index 0000000..892c686 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter.php @@ -0,0 +1,51 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Node\Expr; + +interface PrettyPrinter { + /** + * Pretty prints an array of statements. + * + * @param Node[] $stmts Array of statements + * + * @return string Pretty printed statements + */ + public function prettyPrint(array $stmts): string; + + /** + * Pretty prints an expression. + * + * @param Expr $node Expression node + * + * @return string Pretty printed node + */ + public function prettyPrintExpr(Expr $node): string; + + /** + * Pretty prints a file of statements (includes the opening <?php tag if it is required). + * + * @param Node[] $stmts Array of statements + * + * @return string Pretty printed statements + */ + public function prettyPrintFile(array $stmts): string; + + /** + * Perform a format-preserving pretty print of an AST. + * + * The format preservation is best effort. For some changes to the AST the formatting will not + * be preserved (at least not locally). + * + * In order to use this method a number of prerequisites must be satisfied: + * * The startTokenPos and endTokenPos attributes in the lexer must be enabled. + * * The CloningVisitor must be run on the AST prior to modification. + * * The original tokens must be provided, using the getTokens() method on the lexer. + * + * @param Node[] $stmts Modified AST with links to original AST + * @param Node[] $origStmts Original AST with token offset information + * @param Token[] $origTokens Tokens of the original code + */ + public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string; +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter/Standard.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter/Standard.php new file mode 100644 index 0000000..6a0349c --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter/Standard.php @@ -0,0 +1,1177 @@ +<?php declare(strict_types=1); + +namespace PhpParser\PrettyPrinter; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\AssignOp; +use PhpParser\Node\Expr\BinaryOp; +use PhpParser\Node\Expr\Cast; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar; +use PhpParser\Node\Scalar\MagicConst; +use PhpParser\Node\Stmt; +use PhpParser\PrettyPrinterAbstract; + +class Standard extends PrettyPrinterAbstract { + // Special nodes + + protected function pParam(Node\Param $node): string { + return $this->pAttrGroups($node->attrGroups, true) + . $this->pModifiers($node->flags) + . ($node->type ? $this->p($node->type) . ' ' : '') + . ($node->byRef ? '&' : '') + . ($node->variadic ? '...' : '') + . $this->p($node->var) + . ($node->default ? ' = ' . $this->p($node->default) : ''); + } + + protected function pArg(Node\Arg $node): string { + return ($node->name ? $node->name->toString() . ': ' : '') + . ($node->byRef ? '&' : '') . ($node->unpack ? '...' : '') + . $this->p($node->value); + } + + protected function pVariadicPlaceholder(Node\VariadicPlaceholder $node): string { + return '...'; + } + + protected function pConst(Node\Const_ $node): string { + return $node->name . ' = ' . $this->p($node->value); + } + + protected function pNullableType(Node\NullableType $node): string { + return '?' . $this->p($node->type); + } + + protected function pUnionType(Node\UnionType $node): string { + $types = []; + foreach ($node->types as $typeNode) { + if ($typeNode instanceof Node\IntersectionType) { + $types[] = '('. $this->p($typeNode) . ')'; + continue; + } + $types[] = $this->p($typeNode); + } + return implode('|', $types); + } + + protected function pIntersectionType(Node\IntersectionType $node): string { + return $this->pImplode($node->types, '&'); + } + + protected function pIdentifier(Node\Identifier $node): string { + return $node->name; + } + + protected function pVarLikeIdentifier(Node\VarLikeIdentifier $node): string { + return '$' . $node->name; + } + + protected function pAttribute(Node\Attribute $node): string { + return $this->p($node->name) + . ($node->args ? '(' . $this->pCommaSeparated($node->args) . ')' : ''); + } + + protected function pAttributeGroup(Node\AttributeGroup $node): string { + return '#[' . $this->pCommaSeparated($node->attrs) . ']'; + } + + // Names + + protected function pName(Name $node): string { + return $node->name; + } + + protected function pName_FullyQualified(Name\FullyQualified $node): string { + return '\\' . $node->name; + } + + protected function pName_Relative(Name\Relative $node): string { + return 'namespace\\' . $node->name; + } + + // Magic Constants + + protected function pScalar_MagicConst_Class(MagicConst\Class_ $node): string { + return '__CLASS__'; + } + + protected function pScalar_MagicConst_Dir(MagicConst\Dir $node): string { + return '__DIR__'; + } + + protected function pScalar_MagicConst_File(MagicConst\File $node): string { + return '__FILE__'; + } + + protected function pScalar_MagicConst_Function(MagicConst\Function_ $node): string { + return '__FUNCTION__'; + } + + protected function pScalar_MagicConst_Line(MagicConst\Line $node): string { + return '__LINE__'; + } + + protected function pScalar_MagicConst_Method(MagicConst\Method $node): string { + return '__METHOD__'; + } + + protected function pScalar_MagicConst_Namespace(MagicConst\Namespace_ $node): string { + return '__NAMESPACE__'; + } + + protected function pScalar_MagicConst_Trait(MagicConst\Trait_ $node): string { + return '__TRAIT__'; + } + + // Scalars + + private function indentString(string $str): string { + return str_replace("\n", $this->nl, $str); + } + + protected function pScalar_String(Scalar\String_ $node): string { + $kind = $node->getAttribute('kind', Scalar\String_::KIND_SINGLE_QUOTED); + switch ($kind) { + case Scalar\String_::KIND_NOWDOC: + $label = $node->getAttribute('docLabel'); + if ($label && !$this->containsEndLabel($node->value, $label)) { + $shouldIdent = $this->phpVersion->supportsFlexibleHeredoc(); + $nl = $shouldIdent ? $this->nl : $this->newline; + if ($node->value === '') { + return "<<<'$label'$nl$label{$this->docStringEndToken}"; + } + + // Make sure trailing \r is not combined with following \n into CRLF. + if ($node->value[strlen($node->value) - 1] !== "\r") { + $value = $shouldIdent ? $this->indentString($node->value) : $node->value; + return "<<<'$label'$nl$value$nl$label{$this->docStringEndToken}"; + } + } + /* break missing intentionally */ + // no break + case Scalar\String_::KIND_SINGLE_QUOTED: + return $this->pSingleQuotedString($node->value); + case Scalar\String_::KIND_HEREDOC: + $label = $node->getAttribute('docLabel'); + $escaped = $this->escapeString($node->value, null); + if ($label && !$this->containsEndLabel($escaped, $label)) { + $nl = $this->phpVersion->supportsFlexibleHeredoc() ? $this->nl : $this->newline; + if ($escaped === '') { + return "<<<$label$nl$label{$this->docStringEndToken}"; + } + + return "<<<$label$nl$escaped$nl$label{$this->docStringEndToken}"; + } + /* break missing intentionally */ + // no break + case Scalar\String_::KIND_DOUBLE_QUOTED: + return '"' . $this->escapeString($node->value, '"') . '"'; + } + throw new \Exception('Invalid string kind'); + } + + protected function pScalar_InterpolatedString(Scalar\InterpolatedString $node): string { + if ($node->getAttribute('kind') === Scalar\String_::KIND_HEREDOC) { + $label = $node->getAttribute('docLabel'); + if ($label && !$this->encapsedContainsEndLabel($node->parts, $label)) { + $nl = $this->phpVersion->supportsFlexibleHeredoc() ? $this->nl : $this->newline; + if (count($node->parts) === 1 + && $node->parts[0] instanceof Node\InterpolatedStringPart + && $node->parts[0]->value === '' + ) { + return "<<<$label$nl$label{$this->docStringEndToken}"; + } + + return "<<<$label$nl" . $this->pEncapsList($node->parts, null) + . "$nl$label{$this->docStringEndToken}"; + } + } + return '"' . $this->pEncapsList($node->parts, '"') . '"'; + } + + protected function pScalar_Int(Scalar\Int_ $node): string { + if ($node->value === -\PHP_INT_MAX - 1) { + // PHP_INT_MIN cannot be represented as a literal, + // because the sign is not part of the literal + return '(-' . \PHP_INT_MAX . '-1)'; + } + + $kind = $node->getAttribute('kind', Scalar\Int_::KIND_DEC); + if (Scalar\Int_::KIND_DEC === $kind) { + return (string) $node->value; + } + + if ($node->value < 0) { + $sign = '-'; + $str = (string) -$node->value; + } else { + $sign = ''; + $str = (string) $node->value; + } + switch ($kind) { + case Scalar\Int_::KIND_BIN: + return $sign . '0b' . base_convert($str, 10, 2); + case Scalar\Int_::KIND_OCT: + return $sign . '0' . base_convert($str, 10, 8); + case Scalar\Int_::KIND_HEX: + return $sign . '0x' . base_convert($str, 10, 16); + } + throw new \Exception('Invalid number kind'); + } + + protected function pScalar_Float(Scalar\Float_ $node): string { + if (!is_finite($node->value)) { + if ($node->value === \INF) { + return '1.0E+1000'; + } + if ($node->value === -\INF) { + return '-1.0E+1000'; + } else { + return '\NAN'; + } + } + + // Try to find a short full-precision representation + $stringValue = sprintf('%.16G', $node->value); + if ($node->value !== (float) $stringValue) { + $stringValue = sprintf('%.17G', $node->value); + } + + // %G is locale dependent and there exists no locale-independent alternative. We don't want + // mess with switching locales here, so let's assume that a comma is the only non-standard + // decimal separator we may encounter... + $stringValue = str_replace(',', '.', $stringValue); + + // ensure that number is really printed as float + return preg_match('/^-?[0-9]+$/', $stringValue) ? $stringValue . '.0' : $stringValue; + } + + // Assignments + + protected function pExpr_Assign(Expr\Assign $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\Assign::class, $this->p($node->var) . ' = ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignRef(Expr\AssignRef $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\AssignRef::class, $this->p($node->var) . ' =& ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Plus(AssignOp\Plus $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Plus::class, $this->p($node->var) . ' += ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Minus(AssignOp\Minus $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Minus::class, $this->p($node->var) . ' -= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Mul(AssignOp\Mul $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Mul::class, $this->p($node->var) . ' *= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Div(AssignOp\Div $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Div::class, $this->p($node->var) . ' /= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Concat(AssignOp\Concat $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Concat::class, $this->p($node->var) . ' .= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Mod(AssignOp\Mod $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Mod::class, $this->p($node->var) . ' %= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_BitwiseAnd(AssignOp\BitwiseAnd $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\BitwiseAnd::class, $this->p($node->var) . ' &= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_BitwiseOr(AssignOp\BitwiseOr $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\BitwiseOr::class, $this->p($node->var) . ' |= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_BitwiseXor(AssignOp\BitwiseXor $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\BitwiseXor::class, $this->p($node->var) . ' ^= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_ShiftLeft(AssignOp\ShiftLeft $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\ShiftLeft::class, $this->p($node->var) . ' <<= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_ShiftRight(AssignOp\ShiftRight $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\ShiftRight::class, $this->p($node->var) . ' >>= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Pow(AssignOp\Pow $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Pow::class, $this->p($node->var) . ' **= ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_AssignOp_Coalesce(AssignOp\Coalesce $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(AssignOp\Coalesce::class, $this->p($node->var) . ' ??= ', $node->expr, $precedence, $lhsPrecedence); + } + + // Binary expressions + + protected function pExpr_BinaryOp_Plus(BinaryOp\Plus $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Plus::class, $node->left, ' + ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Minus(BinaryOp\Minus $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Minus::class, $node->left, ' - ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Mul(BinaryOp\Mul $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Mul::class, $node->left, ' * ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Div(BinaryOp\Div $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Div::class, $node->left, ' / ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Concat(BinaryOp\Concat $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Concat::class, $node->left, ' . ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Mod(BinaryOp\Mod $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Mod::class, $node->left, ' % ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_BooleanAnd(BinaryOp\BooleanAnd $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\BooleanAnd::class, $node->left, ' && ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_BooleanOr(BinaryOp\BooleanOr $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\BooleanOr::class, $node->left, ' || ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_BitwiseAnd(BinaryOp\BitwiseAnd $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\BitwiseAnd::class, $node->left, ' & ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_BitwiseOr(BinaryOp\BitwiseOr $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\BitwiseOr::class, $node->left, ' | ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_BitwiseXor(BinaryOp\BitwiseXor $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\BitwiseXor::class, $node->left, ' ^ ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_ShiftLeft(BinaryOp\ShiftLeft $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\ShiftLeft::class, $node->left, ' << ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_ShiftRight(BinaryOp\ShiftRight $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\ShiftRight::class, $node->left, ' >> ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Pow(BinaryOp\Pow $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Pow::class, $node->left, ' ** ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_LogicalAnd(BinaryOp\LogicalAnd $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\LogicalAnd::class, $node->left, ' and ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_LogicalOr(BinaryOp\LogicalOr $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\LogicalOr::class, $node->left, ' or ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_LogicalXor(BinaryOp\LogicalXor $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\LogicalXor::class, $node->left, ' xor ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Equal(BinaryOp\Equal $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Equal::class, $node->left, ' == ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_NotEqual(BinaryOp\NotEqual $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\NotEqual::class, $node->left, ' != ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Identical(BinaryOp\Identical $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Identical::class, $node->left, ' === ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_NotIdentical(BinaryOp\NotIdentical $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\NotIdentical::class, $node->left, ' !== ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Spaceship(BinaryOp\Spaceship $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Spaceship::class, $node->left, ' <=> ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Greater(BinaryOp\Greater $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Greater::class, $node->left, ' > ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_GreaterOrEqual(BinaryOp\GreaterOrEqual $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\GreaterOrEqual::class, $node->left, ' >= ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Smaller(BinaryOp\Smaller $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Smaller::class, $node->left, ' < ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_SmallerOrEqual(BinaryOp\SmallerOrEqual $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\SmallerOrEqual::class, $node->left, ' <= ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_BinaryOp_Coalesce(BinaryOp\Coalesce $node, int $precedence, int $lhsPrecedence): string { + return $this->pInfixOp(BinaryOp\Coalesce::class, $node->left, ' ?? ', $node->right, $precedence, $lhsPrecedence); + } + + protected function pExpr_Instanceof(Expr\Instanceof_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPostfixOp( + Expr\Instanceof_::class, $node->expr, + ' instanceof ' . $this->pNewOperand($node->class), + $precedence, $lhsPrecedence); + } + + // Unary expressions + + protected function pExpr_BooleanNot(Expr\BooleanNot $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\BooleanNot::class, '!', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_BitwiseNot(Expr\BitwiseNot $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\BitwiseNot::class, '~', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_UnaryMinus(Expr\UnaryMinus $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\UnaryMinus::class, '-', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_UnaryPlus(Expr\UnaryPlus $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\UnaryPlus::class, '+', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_PreInc(Expr\PreInc $node): string { + return '++' . $this->p($node->var); + } + + protected function pExpr_PreDec(Expr\PreDec $node): string { + return '--' . $this->p($node->var); + } + + protected function pExpr_PostInc(Expr\PostInc $node): string { + return $this->p($node->var) . '++'; + } + + protected function pExpr_PostDec(Expr\PostDec $node): string { + return $this->p($node->var) . '--'; + } + + protected function pExpr_ErrorSuppress(Expr\ErrorSuppress $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\ErrorSuppress::class, '@', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_YieldFrom(Expr\YieldFrom $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\YieldFrom::class, 'yield from ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Print(Expr\Print_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\Print_::class, 'print ', $node->expr, $precedence, $lhsPrecedence); + } + + // Casts + + protected function pExpr_Cast_Int(Cast\Int_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Cast\Int_::class, '(int) ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Cast_Double(Cast\Double $node, int $precedence, int $lhsPrecedence): string { + $kind = $node->getAttribute('kind', Cast\Double::KIND_DOUBLE); + if ($kind === Cast\Double::KIND_DOUBLE) { + $cast = '(double)'; + } elseif ($kind === Cast\Double::KIND_FLOAT) { + $cast = '(float)'; + } else { + assert($kind === Cast\Double::KIND_REAL); + $cast = '(real)'; + } + return $this->pPrefixOp(Cast\Double::class, $cast . ' ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Cast_String(Cast\String_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Cast\String_::class, '(string) ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Cast_Array(Cast\Array_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Cast\Array_::class, '(array) ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Cast_Object(Cast\Object_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Cast\Object_::class, '(object) ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Cast_Bool(Cast\Bool_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Cast\Bool_::class, '(bool) ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Cast_Unset(Cast\Unset_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Cast\Unset_::class, '(unset) ', $node->expr, $precedence, $lhsPrecedence); + } + + // Function calls and similar constructs + + protected function pExpr_FuncCall(Expr\FuncCall $node): string { + return $this->pCallLhs($node->name) + . '(' . $this->pMaybeMultiline($node->args) . ')'; + } + + protected function pExpr_MethodCall(Expr\MethodCall $node): string { + return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name) + . '(' . $this->pMaybeMultiline($node->args) . ')'; + } + + protected function pExpr_NullsafeMethodCall(Expr\NullsafeMethodCall $node): string { + return $this->pDereferenceLhs($node->var) . '?->' . $this->pObjectProperty($node->name) + . '(' . $this->pMaybeMultiline($node->args) . ')'; + } + + protected function pExpr_StaticCall(Expr\StaticCall $node): string { + return $this->pStaticDereferenceLhs($node->class) . '::' + . ($node->name instanceof Expr + ? ($node->name instanceof Expr\Variable + ? $this->p($node->name) + : '{' . $this->p($node->name) . '}') + : $node->name) + . '(' . $this->pMaybeMultiline($node->args) . ')'; + } + + protected function pExpr_Empty(Expr\Empty_ $node): string { + return 'empty(' . $this->p($node->expr) . ')'; + } + + protected function pExpr_Isset(Expr\Isset_ $node): string { + return 'isset(' . $this->pCommaSeparated($node->vars) . ')'; + } + + protected function pExpr_Eval(Expr\Eval_ $node): string { + return 'eval(' . $this->p($node->expr) . ')'; + } + + protected function pExpr_Include(Expr\Include_ $node, int $precedence, int $lhsPrecedence): string { + static $map = [ + Expr\Include_::TYPE_INCLUDE => 'include', + Expr\Include_::TYPE_INCLUDE_ONCE => 'include_once', + Expr\Include_::TYPE_REQUIRE => 'require', + Expr\Include_::TYPE_REQUIRE_ONCE => 'require_once', + ]; + + return $this->pPrefixOp(Expr\Include_::class, $map[$node->type] . ' ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_List(Expr\List_ $node): string { + $syntax = $node->getAttribute('kind', + $this->phpVersion->supportsShortArrayDestructuring() ? Expr\List_::KIND_ARRAY : Expr\List_::KIND_LIST); + if ($syntax === Expr\List_::KIND_ARRAY) { + return '[' . $this->pMaybeMultiline($node->items, true) . ']'; + } else { + return 'list(' . $this->pMaybeMultiline($node->items, true) . ')'; + } + } + + // Other + + protected function pExpr_Error(Expr\Error $node): string { + throw new \LogicException('Cannot pretty-print AST with Error nodes'); + } + + protected function pExpr_Variable(Expr\Variable $node): string { + if ($node->name instanceof Expr) { + return '${' . $this->p($node->name) . '}'; + } else { + return '$' . $node->name; + } + } + + protected function pExpr_Array(Expr\Array_ $node): string { + $syntax = $node->getAttribute('kind', + $this->shortArraySyntax ? Expr\Array_::KIND_SHORT : Expr\Array_::KIND_LONG); + if ($syntax === Expr\Array_::KIND_SHORT) { + return '[' . $this->pMaybeMultiline($node->items, true) . ']'; + } else { + return 'array(' . $this->pMaybeMultiline($node->items, true) . ')'; + } + } + + protected function pKey(?Node $node): string { + if ($node === null) { + return ''; + } + + // => is not really an operator and does not typically participate in precedence resolution. + // However, there is an exception if yield expressions with keys are involved: + // [yield $a => $b] is interpreted as [(yield $a => $b)], so we need to ensure that + // [(yield $a) => $b] is printed with parentheses. We approximate this by lowering the LHS + // precedence to that of yield (which will also print unnecessary parentheses for rare low + // precedence unary operators like include). + $yieldPrecedence = $this->precedenceMap[Expr\Yield_::class][0]; + return $this->p($node, self::MAX_PRECEDENCE, $yieldPrecedence) . ' => '; + } + + protected function pArrayItem(Node\ArrayItem $node): string { + return $this->pKey($node->key) + . ($node->byRef ? '&' : '') + . ($node->unpack ? '...' : '') + . $this->p($node->value); + } + + protected function pExpr_ArrayDimFetch(Expr\ArrayDimFetch $node): string { + return $this->pDereferenceLhs($node->var) + . '[' . (null !== $node->dim ? $this->p($node->dim) : '') . ']'; + } + + protected function pExpr_ConstFetch(Expr\ConstFetch $node): string { + return $this->p($node->name); + } + + protected function pExpr_ClassConstFetch(Expr\ClassConstFetch $node): string { + return $this->pStaticDereferenceLhs($node->class) . '::' . $this->pObjectProperty($node->name); + } + + protected function pExpr_PropertyFetch(Expr\PropertyFetch $node): string { + return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name); + } + + protected function pExpr_NullsafePropertyFetch(Expr\NullsafePropertyFetch $node): string { + return $this->pDereferenceLhs($node->var) . '?->' . $this->pObjectProperty($node->name); + } + + protected function pExpr_StaticPropertyFetch(Expr\StaticPropertyFetch $node): string { + return $this->pStaticDereferenceLhs($node->class) . '::$' . $this->pObjectProperty($node->name); + } + + protected function pExpr_ShellExec(Expr\ShellExec $node): string { + return '`' . $this->pEncapsList($node->parts, '`') . '`'; + } + + protected function pExpr_Closure(Expr\Closure $node): string { + return $this->pAttrGroups($node->attrGroups, true) + . $this->pStatic($node->static) + . 'function ' . ($node->byRef ? '&' : '') + . '(' . $this->pMaybeMultiline($node->params, $this->phpVersion->supportsTrailingCommaInParamList()) . ')' + . (!empty($node->uses) ? ' use (' . $this->pCommaSeparated($node->uses) . ')' : '') + . (null !== $node->returnType ? ': ' . $this->p($node->returnType) : '') + . ' {' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pExpr_Match(Expr\Match_ $node): string { + return 'match (' . $this->p($node->cond) . ') {' + . $this->pCommaSeparatedMultiline($node->arms, true) + . $this->nl + . '}'; + } + + protected function pMatchArm(Node\MatchArm $node): string { + $result = ''; + if ($node->conds) { + for ($i = 0, $c = \count($node->conds); $i + 1 < $c; $i++) { + $result .= $this->p($node->conds[$i]) . ', '; + } + $result .= $this->pKey($node->conds[$i]); + } else { + $result = 'default => '; + } + return $result . $this->p($node->body); + } + + protected function pExpr_ArrowFunction(Expr\ArrowFunction $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp( + Expr\ArrowFunction::class, + $this->pAttrGroups($node->attrGroups, true) + . $this->pStatic($node->static) + . 'fn' . ($node->byRef ? '&' : '') + . '(' . $this->pMaybeMultiline($node->params, $this->phpVersion->supportsTrailingCommaInParamList()) . ')' + . (null !== $node->returnType ? ': ' . $this->p($node->returnType) : '') + . ' => ', + $node->expr, $precedence, $lhsPrecedence); + } + + protected function pClosureUse(Node\ClosureUse $node): string { + return ($node->byRef ? '&' : '') . $this->p($node->var); + } + + protected function pExpr_New(Expr\New_ $node): string { + if ($node->class instanceof Stmt\Class_) { + $args = $node->args ? '(' . $this->pMaybeMultiline($node->args) . ')' : ''; + return 'new ' . $this->pClassCommon($node->class, $args); + } + return 'new ' . $this->pNewOperand($node->class) + . '(' . $this->pMaybeMultiline($node->args) . ')'; + } + + protected function pExpr_Clone(Expr\Clone_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\Clone_::class, 'clone ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Ternary(Expr\Ternary $node, int $precedence, int $lhsPrecedence): string { + // a bit of cheating: we treat the ternary as a binary op where the ?...: part is the operator. + // this is okay because the part between ? and : never needs parentheses. + return $this->pInfixOp(Expr\Ternary::class, + $node->cond, ' ?' . (null !== $node->if ? ' ' . $this->p($node->if) . ' ' : '') . ': ', $node->else, + $precedence, $lhsPrecedence + ); + } + + protected function pExpr_Exit(Expr\Exit_ $node): string { + $kind = $node->getAttribute('kind', Expr\Exit_::KIND_DIE); + return ($kind === Expr\Exit_::KIND_EXIT ? 'exit' : 'die') + . (null !== $node->expr ? '(' . $this->p($node->expr) . ')' : ''); + } + + protected function pExpr_Throw(Expr\Throw_ $node, int $precedence, int $lhsPrecedence): string { + return $this->pPrefixOp(Expr\Throw_::class, 'throw ', $node->expr, $precedence, $lhsPrecedence); + } + + protected function pExpr_Yield(Expr\Yield_ $node, int $precedence, int $lhsPrecedence): string { + if ($node->value === null) { + $opPrecedence = $this->precedenceMap[Expr\Yield_::class][0]; + return $opPrecedence >= $lhsPrecedence ? '(yield)' : 'yield'; + } else { + if (!$this->phpVersion->supportsYieldWithoutParentheses()) { + return '(yield ' . $this->pKey($node->key) . $this->p($node->value) . ')'; + } + return $this->pPrefixOp( + Expr\Yield_::class, 'yield ' . $this->pKey($node->key), + $node->value, $precedence, $lhsPrecedence); + } + } + + // Declarations + + protected function pStmt_Namespace(Stmt\Namespace_ $node): string { + if ($this->canUseSemicolonNamespaces) { + return 'namespace ' . $this->p($node->name) . ';' + . $this->nl . $this->pStmts($node->stmts, false); + } else { + return 'namespace' . (null !== $node->name ? ' ' . $this->p($node->name) : '') + . ' {' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + } + + protected function pStmt_Use(Stmt\Use_ $node): string { + return 'use ' . $this->pUseType($node->type) + . $this->pCommaSeparated($node->uses) . ';'; + } + + protected function pStmt_GroupUse(Stmt\GroupUse $node): string { + return 'use ' . $this->pUseType($node->type) . $this->pName($node->prefix) + . '\{' . $this->pCommaSeparated($node->uses) . '};'; + } + + protected function pUseItem(Node\UseItem $node): string { + return $this->pUseType($node->type) . $this->p($node->name) + . (null !== $node->alias ? ' as ' . $node->alias : ''); + } + + protected function pUseType(int $type): string { + return $type === Stmt\Use_::TYPE_FUNCTION ? 'function ' + : ($type === Stmt\Use_::TYPE_CONSTANT ? 'const ' : ''); + } + + protected function pStmt_Interface(Stmt\Interface_ $node): string { + return $this->pAttrGroups($node->attrGroups) + . 'interface ' . $node->name + . (!empty($node->extends) ? ' extends ' . $this->pCommaSeparated($node->extends) : '') + . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Enum(Stmt\Enum_ $node): string { + return $this->pAttrGroups($node->attrGroups) + . 'enum ' . $node->name + . ($node->scalarType ? ' : ' . $this->p($node->scalarType) : '') + . (!empty($node->implements) ? ' implements ' . $this->pCommaSeparated($node->implements) : '') + . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Class(Stmt\Class_ $node): string { + return $this->pClassCommon($node, ' ' . $node->name); + } + + protected function pStmt_Trait(Stmt\Trait_ $node): string { + return $this->pAttrGroups($node->attrGroups) + . 'trait ' . $node->name + . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_EnumCase(Stmt\EnumCase $node): string { + return $this->pAttrGroups($node->attrGroups) + . 'case ' . $node->name + . ($node->expr ? ' = ' . $this->p($node->expr) : '') + . ';'; + } + + protected function pStmt_TraitUse(Stmt\TraitUse $node): string { + return 'use ' . $this->pCommaSeparated($node->traits) + . (empty($node->adaptations) + ? ';' + : ' {' . $this->pStmts($node->adaptations) . $this->nl . '}'); + } + + protected function pStmt_TraitUseAdaptation_Precedence(Stmt\TraitUseAdaptation\Precedence $node): string { + return $this->p($node->trait) . '::' . $node->method + . ' insteadof ' . $this->pCommaSeparated($node->insteadof) . ';'; + } + + protected function pStmt_TraitUseAdaptation_Alias(Stmt\TraitUseAdaptation\Alias $node): string { + return (null !== $node->trait ? $this->p($node->trait) . '::' : '') + . $node->method . ' as' + . (null !== $node->newModifier ? ' ' . rtrim($this->pModifiers($node->newModifier), ' ') : '') + . (null !== $node->newName ? ' ' . $node->newName : '') + . ';'; + } + + protected function pStmt_Property(Stmt\Property $node): string { + return $this->pAttrGroups($node->attrGroups) + . (0 === $node->flags ? 'var ' : $this->pModifiers($node->flags)) + . ($node->type ? $this->p($node->type) . ' ' : '') + . $this->pCommaSeparated($node->props) . ';'; + } + + protected function pPropertyItem(Node\PropertyItem $node): string { + return '$' . $node->name + . (null !== $node->default ? ' = ' . $this->p($node->default) : ''); + } + + protected function pStmt_ClassMethod(Stmt\ClassMethod $node): string { + return $this->pAttrGroups($node->attrGroups) + . $this->pModifiers($node->flags) + . 'function ' . ($node->byRef ? '&' : '') . $node->name + . '(' . $this->pMaybeMultiline($node->params, $this->phpVersion->supportsTrailingCommaInParamList()) . ')' + . (null !== $node->returnType ? ': ' . $this->p($node->returnType) : '') + . (null !== $node->stmts + ? $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}' + : ';'); + } + + protected function pStmt_ClassConst(Stmt\ClassConst $node): string { + return $this->pAttrGroups($node->attrGroups) + . $this->pModifiers($node->flags) + . 'const ' + . (null !== $node->type ? $this->p($node->type) . ' ' : '') + . $this->pCommaSeparated($node->consts) . ';'; + } + + protected function pStmt_Function(Stmt\Function_ $node): string { + return $this->pAttrGroups($node->attrGroups) + . 'function ' . ($node->byRef ? '&' : '') . $node->name + . '(' . $this->pMaybeMultiline($node->params, $this->phpVersion->supportsTrailingCommaInParamList()) . ')' + . (null !== $node->returnType ? ': ' . $this->p($node->returnType) : '') + . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Const(Stmt\Const_ $node): string { + return 'const ' . $this->pCommaSeparated($node->consts) . ';'; + } + + protected function pStmt_Declare(Stmt\Declare_ $node): string { + return 'declare (' . $this->pCommaSeparated($node->declares) . ')' + . (null !== $node->stmts ? ' {' . $this->pStmts($node->stmts) . $this->nl . '}' : ';'); + } + + protected function pDeclareItem(Node\DeclareItem $node): string { + return $node->key . '=' . $this->p($node->value); + } + + // Control flow + + protected function pStmt_If(Stmt\If_ $node): string { + return 'if (' . $this->p($node->cond) . ') {' + . $this->pStmts($node->stmts) . $this->nl . '}' + . ($node->elseifs ? ' ' . $this->pImplode($node->elseifs, ' ') : '') + . (null !== $node->else ? ' ' . $this->p($node->else) : ''); + } + + protected function pStmt_ElseIf(Stmt\ElseIf_ $node): string { + return 'elseif (' . $this->p($node->cond) . ') {' + . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Else(Stmt\Else_ $node): string { + if (\count($node->stmts) === 1 && $node->stmts[0] instanceof Stmt\If_) { + // Print as "else if" rather than "else { if }" + return 'else ' . $this->p($node->stmts[0]); + } + return 'else {' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_For(Stmt\For_ $node): string { + return 'for (' + . $this->pCommaSeparated($node->init) . ';' . (!empty($node->cond) ? ' ' : '') + . $this->pCommaSeparated($node->cond) . ';' . (!empty($node->loop) ? ' ' : '') + . $this->pCommaSeparated($node->loop) + . ') {' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Foreach(Stmt\Foreach_ $node): string { + return 'foreach (' . $this->p($node->expr) . ' as ' + . (null !== $node->keyVar ? $this->p($node->keyVar) . ' => ' : '') + . ($node->byRef ? '&' : '') . $this->p($node->valueVar) . ') {' + . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_While(Stmt\While_ $node): string { + return 'while (' . $this->p($node->cond) . ') {' + . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Do(Stmt\Do_ $node): string { + return 'do {' . $this->pStmts($node->stmts) . $this->nl + . '} while (' . $this->p($node->cond) . ');'; + } + + protected function pStmt_Switch(Stmt\Switch_ $node): string { + return 'switch (' . $this->p($node->cond) . ') {' + . $this->pStmts($node->cases) . $this->nl . '}'; + } + + protected function pStmt_Case(Stmt\Case_ $node): string { + return (null !== $node->cond ? 'case ' . $this->p($node->cond) : 'default') . ':' + . $this->pStmts($node->stmts); + } + + protected function pStmt_TryCatch(Stmt\TryCatch $node): string { + return 'try {' . $this->pStmts($node->stmts) . $this->nl . '}' + . ($node->catches ? ' ' . $this->pImplode($node->catches, ' ') : '') + . ($node->finally !== null ? ' ' . $this->p($node->finally) : ''); + } + + protected function pStmt_Catch(Stmt\Catch_ $node): string { + return 'catch (' . $this->pImplode($node->types, '|') + . ($node->var !== null ? ' ' . $this->p($node->var) : '') + . ') {' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Finally(Stmt\Finally_ $node): string { + return 'finally {' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pStmt_Break(Stmt\Break_ $node): string { + return 'break' . ($node->num !== null ? ' ' . $this->p($node->num) : '') . ';'; + } + + protected function pStmt_Continue(Stmt\Continue_ $node): string { + return 'continue' . ($node->num !== null ? ' ' . $this->p($node->num) : '') . ';'; + } + + protected function pStmt_Return(Stmt\Return_ $node): string { + return 'return' . (null !== $node->expr ? ' ' . $this->p($node->expr) : '') . ';'; + } + + protected function pStmt_Label(Stmt\Label $node): string { + return $node->name . ':'; + } + + protected function pStmt_Goto(Stmt\Goto_ $node): string { + return 'goto ' . $node->name . ';'; + } + + // Other + + protected function pStmt_Expression(Stmt\Expression $node): string { + return $this->p($node->expr) . ';'; + } + + protected function pStmt_Echo(Stmt\Echo_ $node): string { + return 'echo ' . $this->pCommaSeparated($node->exprs) . ';'; + } + + protected function pStmt_Static(Stmt\Static_ $node): string { + return 'static ' . $this->pCommaSeparated($node->vars) . ';'; + } + + protected function pStmt_Global(Stmt\Global_ $node): string { + return 'global ' . $this->pCommaSeparated($node->vars) . ';'; + } + + protected function pStaticVar(Node\StaticVar $node): string { + return $this->p($node->var) + . (null !== $node->default ? ' = ' . $this->p($node->default) : ''); + } + + protected function pStmt_Unset(Stmt\Unset_ $node): string { + return 'unset(' . $this->pCommaSeparated($node->vars) . ');'; + } + + protected function pStmt_InlineHTML(Stmt\InlineHTML $node): string { + $newline = $node->getAttribute('hasLeadingNewline', true) ? $this->newline : ''; + return '?>' . $newline . $node->value . '<?php '; + } + + protected function pStmt_HaltCompiler(Stmt\HaltCompiler $node): string { + return '__halt_compiler();' . $node->remaining; + } + + protected function pStmt_Nop(Stmt\Nop $node): string { + return ''; + } + + protected function pStmt_Block(Stmt\Block $node): string { + return '{' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + // Helpers + + protected function pClassCommon(Stmt\Class_ $node, string $afterClassToken): string { + return $this->pAttrGroups($node->attrGroups, $node->name === null) + . $this->pModifiers($node->flags) + . 'class' . $afterClassToken + . (null !== $node->extends ? ' extends ' . $this->p($node->extends) : '') + . (!empty($node->implements) ? ' implements ' . $this->pCommaSeparated($node->implements) : '') + . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'; + } + + protected function pObjectProperty(Node $node): string { + if ($node instanceof Expr) { + return '{' . $this->p($node) . '}'; + } else { + assert($node instanceof Node\Identifier); + return $node->name; + } + } + + /** @param (Expr|Node\InterpolatedStringPart)[] $encapsList */ + protected function pEncapsList(array $encapsList, ?string $quote): string { + $return = ''; + foreach ($encapsList as $element) { + if ($element instanceof Node\InterpolatedStringPart) { + $return .= $this->escapeString($element->value, $quote); + } else { + $return .= '{' . $this->p($element) . '}'; + } + } + + return $return; + } + + protected function pSingleQuotedString(string $string): string { + // It is idiomatic to only escape backslashes when necessary, i.e. when followed by ', \ or + // the end of the string ('Foo\Bar' instead of 'Foo\\Bar'). However, we also don't want to + // produce an odd number of backslashes, so '\\\\a' should not get rendered as '\\\a', even + // though that would be legal. + $regex = '/\'|\\\\(?=[\'\\\\]|$)|(?<=\\\\)\\\\/'; + return '\'' . preg_replace($regex, '\\\\$0', $string) . '\''; + } + + protected function escapeString(string $string, ?string $quote): string { + if (null === $quote) { + // For doc strings, don't escape newlines + $escaped = addcslashes($string, "\t\f\v$\\"); + // But do escape isolated \r. Combined with the terminating newline, it might get + // interpreted as \r\n and dropped from the string contents. + $escaped = preg_replace('/\r(?!\n)/', '\\r', $escaped); + if ($this->phpVersion->supportsFlexibleHeredoc()) { + $escaped = $this->indentString($escaped); + } + } else { + $escaped = addcslashes($string, "\n\r\t\f\v$" . $quote . "\\"); + } + + // Escape control characters and non-UTF-8 characters. + // Regex based on https://stackoverflow.com/a/11709412/385378. + $regex = '/( + [\x00-\x08\x0E-\x1F] # Control characters + | [\xC0-\xC1] # Invalid UTF-8 Bytes + | [\xF5-\xFF] # Invalid UTF-8 Bytes + | \xE0(?=[\x80-\x9F]) # Overlong encoding of prior code point + | \xF0(?=[\x80-\x8F]) # Overlong encoding of prior code point + | [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start + | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start + | [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start + | (?<=[\x00-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle + | (?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF4]|[\xF0-\xF4][\x80-\xBF]|[\xF0-\xF4][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence + | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence + | (?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence + | (?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2) + )/x'; + return preg_replace_callback($regex, function ($matches): string { + assert(strlen($matches[0]) === 1); + $hex = dechex(ord($matches[0])); + return '\\x' . str_pad($hex, 2, '0', \STR_PAD_LEFT); + }, $escaped); + } + + protected function containsEndLabel(string $string, string $label, bool $atStart = true): bool { + $start = $atStart ? '(?:^|[\r\n])[ \t]*' : '[\r\n][ \t]*'; + return false !== strpos($string, $label) + && preg_match('/' . $start . $label . '(?:$|[^_A-Za-z0-9\x80-\xff])/', $string); + } + + /** @param (Expr|Node\InterpolatedStringPart)[] $parts */ + protected function encapsedContainsEndLabel(array $parts, string $label): bool { + foreach ($parts as $i => $part) { + if ($part instanceof Node\InterpolatedStringPart + && $this->containsEndLabel($this->escapeString($part->value, null), $label, $i === 0) + ) { + return true; + } + } + return false; + } + + protected function pDereferenceLhs(Node $node): string { + if (!$this->dereferenceLhsRequiresParens($node)) { + return $this->p($node); + } else { + return '(' . $this->p($node) . ')'; + } + } + + protected function pStaticDereferenceLhs(Node $node): string { + if (!$this->staticDereferenceLhsRequiresParens($node)) { + return $this->p($node); + } else { + return '(' . $this->p($node) . ')'; + } + } + + protected function pCallLhs(Node $node): string { + if (!$this->callLhsRequiresParens($node)) { + return $this->p($node); + } else { + return '(' . $this->p($node) . ')'; + } + } + + protected function pNewOperand(Node $node): string { + if (!$this->newOperandRequiresParens($node)) { + return $this->p($node); + } else { + return '(' . $this->p($node) . ')'; + } + } + + /** + * @param Node[] $nodes + */ + protected function hasNodeWithComments(array $nodes): bool { + foreach ($nodes as $node) { + if ($node && $node->getComments()) { + return true; + } + } + return false; + } + + /** @param Node[] $nodes */ + protected function pMaybeMultiline(array $nodes, bool $trailingComma = false): string { + if (!$this->hasNodeWithComments($nodes)) { + return $this->pCommaSeparated($nodes); + } else { + return $this->pCommaSeparatedMultiline($nodes, $trailingComma) . $this->nl; + } + } + + /** @param Node\AttributeGroup[] $nodes */ + protected function pAttrGroups(array $nodes, bool $inline = false): string { + $result = ''; + $sep = $inline ? ' ' : $this->nl; + foreach ($nodes as $node) { + $result .= $this->p($node) . $sep; + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinterAbstract.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinterAbstract.php new file mode 100644 index 0000000..8303c42 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinterAbstract.php @@ -0,0 +1,1655 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +use PhpParser\Internal\DiffElem; +use PhpParser\Internal\Differ; +use PhpParser\Internal\PrintableNewAnonClassNode; +use PhpParser\Internal\TokenStream; +use PhpParser\Node\AttributeGroup; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\AssignOp; +use PhpParser\Node\Expr\BinaryOp; +use PhpParser\Node\Expr\Cast; +use PhpParser\Node\IntersectionType; +use PhpParser\Node\MatchArm; +use PhpParser\Node\Param; +use PhpParser\Node\Scalar; +use PhpParser\Node\Stmt; +use PhpParser\Node\UnionType; + +abstract class PrettyPrinterAbstract implements PrettyPrinter { + protected const FIXUP_PREC_LEFT = 0; // LHS operand affected by precedence + protected const FIXUP_PREC_RIGHT = 1; // RHS operand affected by precedence + protected const FIXUP_PREC_UNARY = 2; // Only operand affected by precedence + protected const FIXUP_CALL_LHS = 3; // LHS of call + protected const FIXUP_DEREF_LHS = 4; // LHS of dereferencing operation + protected const FIXUP_STATIC_DEREF_LHS = 5; // LHS of static dereferencing operation + protected const FIXUP_BRACED_NAME = 6; // Name operand that may require bracing + protected const FIXUP_VAR_BRACED_NAME = 7; // Name operand that may require ${} bracing + protected const FIXUP_ENCAPSED = 8; // Encapsed string part + protected const FIXUP_NEW = 9; // New/instanceof operand + + protected const MAX_PRECEDENCE = 1000; + + /** @var array<class-string, array{int, int, int}> */ + protected array $precedenceMap = [ + // [precedence, precedenceLHS, precedenceRHS] + // Where the latter two are the precedences to use for the LHS and RHS of a binary operator, + // where 1 is added to one of the sides depending on associativity. This information is not + // used for unary operators and set to -1. + Expr\Clone_::class => [-10, 0, 1], + BinaryOp\Pow::class => [ 0, 0, 1], + Expr\BitwiseNot::class => [ 10, -1, -1], + Expr\UnaryPlus::class => [ 10, -1, -1], + Expr\UnaryMinus::class => [ 10, -1, -1], + Cast\Int_::class => [ 10, -1, -1], + Cast\Double::class => [ 10, -1, -1], + Cast\String_::class => [ 10, -1, -1], + Cast\Array_::class => [ 10, -1, -1], + Cast\Object_::class => [ 10, -1, -1], + Cast\Bool_::class => [ 10, -1, -1], + Cast\Unset_::class => [ 10, -1, -1], + Expr\ErrorSuppress::class => [ 10, -1, -1], + Expr\Instanceof_::class => [ 20, -1, -1], + Expr\BooleanNot::class => [ 30, -1, -1], + BinaryOp\Mul::class => [ 40, 41, 40], + BinaryOp\Div::class => [ 40, 41, 40], + BinaryOp\Mod::class => [ 40, 41, 40], + BinaryOp\Plus::class => [ 50, 51, 50], + BinaryOp\Minus::class => [ 50, 51, 50], + BinaryOp\Concat::class => [ 50, 51, 50], + BinaryOp\ShiftLeft::class => [ 60, 61, 60], + BinaryOp\ShiftRight::class => [ 60, 61, 60], + BinaryOp\Smaller::class => [ 70, 70, 70], + BinaryOp\SmallerOrEqual::class => [ 70, 70, 70], + BinaryOp\Greater::class => [ 70, 70, 70], + BinaryOp\GreaterOrEqual::class => [ 70, 70, 70], + BinaryOp\Equal::class => [ 80, 80, 80], + BinaryOp\NotEqual::class => [ 80, 80, 80], + BinaryOp\Identical::class => [ 80, 80, 80], + BinaryOp\NotIdentical::class => [ 80, 80, 80], + BinaryOp\Spaceship::class => [ 80, 80, 80], + BinaryOp\BitwiseAnd::class => [ 90, 91, 90], + BinaryOp\BitwiseXor::class => [100, 101, 100], + BinaryOp\BitwiseOr::class => [110, 111, 110], + BinaryOp\BooleanAnd::class => [120, 121, 120], + BinaryOp\BooleanOr::class => [130, 131, 130], + BinaryOp\Coalesce::class => [140, 140, 141], + Expr\Ternary::class => [150, -1, -1], + Expr\Assign::class => [160, -1, -1], + Expr\AssignRef::class => [160, -1, -1], + AssignOp\Plus::class => [160, -1, -1], + AssignOp\Minus::class => [160, -1, -1], + AssignOp\Mul::class => [160, -1, -1], + AssignOp\Div::class => [160, -1, -1], + AssignOp\Concat::class => [160, -1, -1], + AssignOp\Mod::class => [160, -1, -1], + AssignOp\BitwiseAnd::class => [160, -1, -1], + AssignOp\BitwiseOr::class => [160, -1, -1], + AssignOp\BitwiseXor::class => [160, -1, -1], + AssignOp\ShiftLeft::class => [160, -1, -1], + AssignOp\ShiftRight::class => [160, -1, -1], + AssignOp\Pow::class => [160, -1, -1], + AssignOp\Coalesce::class => [160, -1, -1], + Expr\YieldFrom::class => [170, -1, -1], + Expr\Yield_::class => [175, -1, -1], + Expr\Print_::class => [180, -1, -1], + BinaryOp\LogicalAnd::class => [190, 191, 190], + BinaryOp\LogicalXor::class => [200, 201, 200], + BinaryOp\LogicalOr::class => [210, 211, 210], + Expr\Include_::class => [220, -1, -1], + Expr\ArrowFunction::class => [230, -1, -1], + Expr\Throw_::class => [240, -1, -1], + ]; + + /** @var int Current indentation level. */ + protected int $indentLevel; + /** @var string Newline style. Does not include current indentation. */ + protected string $newline; + /** @var string Newline including current indentation. */ + protected string $nl; + /** @var string|null Token placed at end of doc string to ensure it is followed by a newline. + * Null if flexible doc strings are used. */ + protected ?string $docStringEndToken; + /** @var bool Whether semicolon namespaces can be used (i.e. no global namespace is used) */ + protected bool $canUseSemicolonNamespaces; + /** @var bool Whether to use short array syntax if the node specifies no preference */ + protected bool $shortArraySyntax; + /** @var PhpVersion PHP version to target */ + protected PhpVersion $phpVersion; + + /** @var TokenStream|null Original tokens for use in format-preserving pretty print */ + protected ?TokenStream $origTokens; + /** @var Internal\Differ<Node> Differ for node lists */ + protected Differ $nodeListDiffer; + /** @var array<string, bool> Map determining whether a certain character is a label character */ + protected array $labelCharMap; + /** + * @var array<string, array<string, int>> Map from token classes and subnode names to FIXUP_* constants. + * This is used during format-preserving prints to place additional parens/braces if necessary. + */ + protected array $fixupMap; + /** + * @var array<string, array{left?: int|string, right?: int|string}> Map from "{$node->getType()}->{$subNode}" + * to ['left' => $l, 'right' => $r], where $l and $r specify the token type that needs to be stripped + * when removing this node. + */ + protected array $removalMap; + /** + * @var array<string, array{int|string|null, bool, string|null, string|null}> Map from + * "{$node->getType()}->{$subNode}" to [$find, $beforeToken, $extraLeft, $extraRight]. + * $find is an optional token after which the insertion occurs. $extraLeft/Right + * are optionally added before/after the main insertions. + */ + protected array $insertionMap; + /** + * @var array<string, string> Map From "{$class}->{$subNode}" to string that should be inserted + * between elements of this list subnode. + */ + protected array $listInsertionMap; + + /** + * @var array<string, array{int|string|null, string, string}> + */ + protected array $emptyListInsertionMap; + /** @var array<string, array{string, int}> Map from "{$class}->{$subNode}" to [$printFn, $token] + * where $printFn is the function to print the modifiers and $token is the token before which + * the modifiers should be reprinted. */ + protected array $modifierChangeMap; + + /** + * Creates a pretty printer instance using the given options. + * + * Supported options: + * * PhpVersion $phpVersion: The PHP version to target (default to PHP 7.4). This option + * controls compatibility of the generated code with older PHP + * versions in cases where a simple stylistic choice exists (e.g. + * array() vs []). It is safe to pretty-print an AST for a newer + * PHP version while specifying an older target (but the result will + * of course not be compatible with the older version in that case). + * * string $newline: The newline style to use. Should be "\n" (default) or "\r\n". + * * bool $shortArraySyntax: Whether to use [] instead of array() as the default array + * syntax, if the node does not specify a format. Defaults to whether + * the phpVersion support short array syntax. + * + * @param array{ + * phpVersion?: PhpVersion, newline?: string, shortArraySyntax?: bool + * } $options Dictionary of formatting options + */ + public function __construct(array $options = []) { + $this->phpVersion = $options['phpVersion'] ?? PhpVersion::fromComponents(7, 4); + + $this->newline = $options['newline'] ?? "\n"; + if ($this->newline !== "\n" && $this->newline != "\r\n") { + throw new \LogicException('Option "newline" must be one of "\n" or "\r\n"'); + } + + $this->shortArraySyntax = + $options['shortArraySyntax'] ?? $this->phpVersion->supportsShortArraySyntax(); + $this->docStringEndToken = + $this->phpVersion->supportsFlexibleHeredoc() ? null : '_DOC_STRING_END_' . mt_rand(); + } + + /** + * Reset pretty printing state. + */ + protected function resetState(): void { + $this->indentLevel = 0; + $this->nl = $this->newline; + $this->origTokens = null; + } + + /** + * Set indentation level + * + * @param int $level Level in number of spaces + */ + protected function setIndentLevel(int $level): void { + $this->indentLevel = $level; + $this->nl = $this->newline . \str_repeat(' ', $level); + } + + /** + * Increase indentation level. + */ + protected function indent(): void { + $this->indentLevel += 4; + $this->nl .= ' '; + } + + /** + * Decrease indentation level. + */ + protected function outdent(): void { + assert($this->indentLevel >= 4); + $this->indentLevel -= 4; + $this->nl = $this->newline . str_repeat(' ', $this->indentLevel); + } + + /** + * Pretty prints an array of statements. + * + * @param Node[] $stmts Array of statements + * + * @return string Pretty printed statements + */ + public function prettyPrint(array $stmts): string { + $this->resetState(); + $this->preprocessNodes($stmts); + + return ltrim($this->handleMagicTokens($this->pStmts($stmts, false))); + } + + /** + * Pretty prints an expression. + * + * @param Expr $node Expression node + * + * @return string Pretty printed node + */ + public function prettyPrintExpr(Expr $node): string { + $this->resetState(); + return $this->handleMagicTokens($this->p($node)); + } + + /** + * Pretty prints a file of statements (includes the opening <?php tag if it is required). + * + * @param Node[] $stmts Array of statements + * + * @return string Pretty printed statements + */ + public function prettyPrintFile(array $stmts): string { + if (!$stmts) { + return "<?php" . $this->newline . $this->newline; + } + + $p = "<?php" . $this->newline . $this->newline . $this->prettyPrint($stmts); + + if ($stmts[0] instanceof Stmt\InlineHTML) { + $p = preg_replace('/^<\?php\s+\?>\r?\n?/', '', $p); + } + if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) { + $p = preg_replace('/<\?php$/', '', rtrim($p)); + } + + return $p; + } + + /** + * Preprocesses the top-level nodes to initialize pretty printer state. + * + * @param Node[] $nodes Array of nodes + */ + protected function preprocessNodes(array $nodes): void { + /* We can use semicolon-namespaces unless there is a global namespace declaration */ + $this->canUseSemicolonNamespaces = true; + foreach ($nodes as $node) { + if ($node instanceof Stmt\Namespace_ && null === $node->name) { + $this->canUseSemicolonNamespaces = false; + break; + } + } + } + + /** + * Handles (and removes) doc-string-end tokens. + */ + protected function handleMagicTokens(string $str): string { + if ($this->docStringEndToken !== null) { + // Replace doc-string-end tokens with nothing or a newline + $str = str_replace( + $this->docStringEndToken . ';' . $this->newline, + ';' . $this->newline, + $str); + $str = str_replace($this->docStringEndToken, $this->newline, $str); + } + + return $str; + } + + /** + * Pretty prints an array of nodes (statements) and indents them optionally. + * + * @param Node[] $nodes Array of nodes + * @param bool $indent Whether to indent the printed nodes + * + * @return string Pretty printed statements + */ + protected function pStmts(array $nodes, bool $indent = true): string { + if ($indent) { + $this->indent(); + } + + $result = ''; + foreach ($nodes as $node) { + $comments = $node->getComments(); + if ($comments) { + $result .= $this->nl . $this->pComments($comments); + if ($node instanceof Stmt\Nop) { + continue; + } + } + + $result .= $this->nl . $this->p($node); + } + + if ($indent) { + $this->outdent(); + } + + return $result; + } + + /** + * Pretty-print an infix operation while taking precedence into account. + * + * @param string $class Node class of operator + * @param Node $leftNode Left-hand side node + * @param string $operatorString String representation of the operator + * @param Node $rightNode Right-hand side node + * @param int $precedence Precedence of parent operator + * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator + * + * @return string Pretty printed infix operation + */ + protected function pInfixOp( + string $class, Node $leftNode, string $operatorString, Node $rightNode, + int $precedence, int $lhsPrecedence + ): string { + list($opPrecedence, $newPrecedenceLHS, $newPrecedenceRHS) = $this->precedenceMap[$class]; + $prefix = ''; + $suffix = ''; + if ($opPrecedence >= $precedence) { + $prefix = '('; + $suffix = ')'; + $lhsPrecedence = self::MAX_PRECEDENCE; + } + return $prefix . $this->p($leftNode, $newPrecedenceLHS, $newPrecedenceLHS) + . $operatorString . $this->p($rightNode, $newPrecedenceRHS, $lhsPrecedence) . $suffix; + } + + /** + * Pretty-print a prefix operation while taking precedence into account. + * + * @param string $class Node class of operator + * @param string $operatorString String representation of the operator + * @param Node $node Node + * @param int $precedence Precedence of parent operator + * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator + * + * @return string Pretty printed prefix operation + */ + protected function pPrefixOp(string $class, string $operatorString, Node $node, int $precedence, int $lhsPrecedence): string { + $opPrecedence = $this->precedenceMap[$class][0]; + $prefix = ''; + $suffix = ''; + if ($opPrecedence >= $lhsPrecedence) { + $prefix = '('; + $suffix = ')'; + $lhsPrecedence = self::MAX_PRECEDENCE; + } + $printedArg = $this->p($node, $opPrecedence, $lhsPrecedence); + if (($operatorString === '+' && $printedArg[0] === '+') || + ($operatorString === '-' && $printedArg[0] === '-') + ) { + // Avoid printing +(+$a) as ++$a and similar. + $printedArg = '(' . $printedArg . ')'; + } + return $prefix . $operatorString . $printedArg . $suffix; + } + + /** + * Pretty-print a postfix operation while taking precedence into account. + * + * @param string $class Node class of operator + * @param string $operatorString String representation of the operator + * @param Node $node Node + * @param int $precedence Precedence of parent operator + * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator + * + * @return string Pretty printed postfix operation + */ + protected function pPostfixOp(string $class, Node $node, string $operatorString, int $precedence, int $lhsPrecedence): string { + $opPrecedence = $this->precedenceMap[$class][0]; + $prefix = ''; + $suffix = ''; + if ($opPrecedence >= $precedence) { + $prefix = '('; + $suffix = ')'; + $lhsPrecedence = self::MAX_PRECEDENCE; + } + if ($opPrecedence < $lhsPrecedence) { + $lhsPrecedence = $opPrecedence; + } + return $prefix . $this->p($node, $opPrecedence, $lhsPrecedence) . $operatorString . $suffix; + } + + /** + * Pretty prints an array of nodes and implodes the printed values. + * + * @param Node[] $nodes Array of Nodes to be printed + * @param string $glue Character to implode with + * + * @return string Imploded pretty printed nodes> $pre + */ + protected function pImplode(array $nodes, string $glue = ''): string { + $pNodes = []; + foreach ($nodes as $node) { + if (null === $node) { + $pNodes[] = ''; + } else { + $pNodes[] = $this->p($node); + } + } + + return implode($glue, $pNodes); + } + + /** + * Pretty prints an array of nodes and implodes the printed values with commas. + * + * @param Node[] $nodes Array of Nodes to be printed + * + * @return string Comma separated pretty printed nodes + */ + protected function pCommaSeparated(array $nodes): string { + return $this->pImplode($nodes, ', '); + } + + /** + * Pretty prints a comma-separated list of nodes in multiline style, including comments. + * + * The result includes a leading newline and one level of indentation (same as pStmts). + * + * @param Node[] $nodes Array of Nodes to be printed + * @param bool $trailingComma Whether to use a trailing comma + * + * @return string Comma separated pretty printed nodes in multiline style + */ + protected function pCommaSeparatedMultiline(array $nodes, bool $trailingComma): string { + $this->indent(); + + $result = ''; + $lastIdx = count($nodes) - 1; + foreach ($nodes as $idx => $node) { + if ($node !== null) { + $comments = $node->getComments(); + if ($comments) { + $result .= $this->nl . $this->pComments($comments); + } + + $result .= $this->nl . $this->p($node); + } else { + $result .= $this->nl; + } + if ($trailingComma || $idx !== $lastIdx) { + $result .= ','; + } + } + + $this->outdent(); + return $result; + } + + /** + * Prints reformatted text of the passed comments. + * + * @param Comment[] $comments List of comments + * + * @return string Reformatted text of comments + */ + protected function pComments(array $comments): string { + $formattedComments = []; + + foreach ($comments as $comment) { + $formattedComments[] = str_replace("\n", $this->nl, $comment->getReformattedText()); + } + + return implode($this->nl, $formattedComments); + } + + /** + * Perform a format-preserving pretty print of an AST. + * + * The format preservation is best effort. For some changes to the AST the formatting will not + * be preserved (at least not locally). + * + * In order to use this method a number of prerequisites must be satisfied: + * * The startTokenPos and endTokenPos attributes in the lexer must be enabled. + * * The CloningVisitor must be run on the AST prior to modification. + * * The original tokens must be provided, using the getTokens() method on the lexer. + * + * @param Node[] $stmts Modified AST with links to original AST + * @param Node[] $origStmts Original AST with token offset information + * @param Token[] $origTokens Tokens of the original code + */ + public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string { + $this->initializeNodeListDiffer(); + $this->initializeLabelCharMap(); + $this->initializeFixupMap(); + $this->initializeRemovalMap(); + $this->initializeInsertionMap(); + $this->initializeListInsertionMap(); + $this->initializeEmptyListInsertionMap(); + $this->initializeModifierChangeMap(); + + $this->resetState(); + $this->origTokens = new TokenStream($origTokens); + + $this->preprocessNodes($stmts); + + $pos = 0; + $result = $this->pArray($stmts, $origStmts, $pos, 0, 'File', 'stmts', null); + if (null !== $result) { + $result .= $this->origTokens->getTokenCode($pos, count($origTokens) - 1, 0); + } else { + // Fallback + // TODO Add <?php properly + $result = "<?php" . $this->newline . $this->pStmts($stmts, false); + } + + return $this->handleMagicTokens($result); + } + + protected function pFallback(Node $node, int $precedence, int $lhsPrecedence): string { + return $this->{'p' . $node->getType()}($node, $precedence, $lhsPrecedence); + } + + /** + * Pretty prints a node. + * + * This method also handles formatting preservation for nodes. + * + * @param Node $node Node to be pretty printed + * @param int $precedence Precedence of parent operator + * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator + * @param bool $parentFormatPreserved Whether parent node has preserved formatting + * + * @return string Pretty printed node + */ + protected function p( + Node $node, int $precedence = self::MAX_PRECEDENCE, int $lhsPrecedence = self::MAX_PRECEDENCE, + bool $parentFormatPreserved = false + ): string { + // No orig tokens means this is a normal pretty print without preservation of formatting + if (!$this->origTokens) { + return $this->{'p' . $node->getType()}($node, $precedence, $lhsPrecedence); + } + + /** @var Node|null $origNode */ + $origNode = $node->getAttribute('origNode'); + if (null === $origNode) { + return $this->pFallback($node, $precedence, $lhsPrecedence); + } + + $class = \get_class($node); + \assert($class === \get_class($origNode)); + + $startPos = $origNode->getStartTokenPos(); + $endPos = $origNode->getEndTokenPos(); + \assert($startPos >= 0 && $endPos >= 0); + + $fallbackNode = $node; + if ($node instanceof Expr\New_ && $node->class instanceof Stmt\Class_) { + // Normalize node structure of anonymous classes + assert($origNode instanceof Expr\New_); + $node = PrintableNewAnonClassNode::fromNewNode($node); + $origNode = PrintableNewAnonClassNode::fromNewNode($origNode); + $class = PrintableNewAnonClassNode::class; + } + + // InlineHTML node does not contain closing and opening PHP tags. If the parent formatting + // is not preserved, then we need to use the fallback code to make sure the tags are + // printed. + if ($node instanceof Stmt\InlineHTML && !$parentFormatPreserved) { + return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); + } + + $indentAdjustment = $this->indentLevel - $this->origTokens->getIndentationBefore($startPos); + + $type = $node->getType(); + $fixupInfo = $this->fixupMap[$class] ?? null; + + $result = ''; + $pos = $startPos; + foreach ($node->getSubNodeNames() as $subNodeName) { + $subNode = $node->$subNodeName; + $origSubNode = $origNode->$subNodeName; + + if ((!$subNode instanceof Node && $subNode !== null) + || (!$origSubNode instanceof Node && $origSubNode !== null) + ) { + if ($subNode === $origSubNode) { + // Unchanged, can reuse old code + continue; + } + + if (is_array($subNode) && is_array($origSubNode)) { + // Array subnode changed, we might be able to reconstruct it + $listResult = $this->pArray( + $subNode, $origSubNode, $pos, $indentAdjustment, $class, $subNodeName, + $fixupInfo[$subNodeName] ?? null + ); + if (null === $listResult) { + return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); + } + + $result .= $listResult; + continue; + } + + // Check if this is a modifier change + $key = $class . '->' . $subNodeName; + if (!isset($this->modifierChangeMap[$key])) { + return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); + } + + [$printFn, $findToken] = $this->modifierChangeMap[$key]; + $result .= $this->$printFn($subNode); + $pos = $this->origTokens->findRight($pos, $findToken); + continue; + } + + $extraLeft = ''; + $extraRight = ''; + if ($origSubNode !== null) { + $subStartPos = $origSubNode->getStartTokenPos(); + $subEndPos = $origSubNode->getEndTokenPos(); + \assert($subStartPos >= 0 && $subEndPos >= 0); + } else { + if ($subNode === null) { + // Both null, nothing to do + continue; + } + + // A node has been inserted, check if we have insertion information for it + $key = $type . '->' . $subNodeName; + if (!isset($this->insertionMap[$key])) { + return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); + } + + list($findToken, $beforeToken, $extraLeft, $extraRight) = $this->insertionMap[$key]; + if (null !== $findToken) { + $subStartPos = $this->origTokens->findRight($pos, $findToken) + + (int) !$beforeToken; + } else { + $subStartPos = $pos; + } + + if (null === $extraLeft && null !== $extraRight) { + // If inserting on the right only, skipping whitespace looks better + $subStartPos = $this->origTokens->skipRightWhitespace($subStartPos); + } + $subEndPos = $subStartPos - 1; + } + + if (null === $subNode) { + // A node has been removed, check if we have removal information for it + $key = $type . '->' . $subNodeName; + if (!isset($this->removalMap[$key])) { + return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); + } + + // Adjust positions to account for additional tokens that must be skipped + $removalInfo = $this->removalMap[$key]; + if (isset($removalInfo['left'])) { + $subStartPos = $this->origTokens->skipLeft($subStartPos - 1, $removalInfo['left']) + 1; + } + if (isset($removalInfo['right'])) { + $subEndPos = $this->origTokens->skipRight($subEndPos + 1, $removalInfo['right']) - 1; + } + } + + $result .= $this->origTokens->getTokenCode($pos, $subStartPos, $indentAdjustment); + + if (null !== $subNode) { + $result .= $extraLeft; + + $origIndentLevel = $this->indentLevel; + $this->setIndentLevel($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment); + + // If it's the same node that was previously in this position, it certainly doesn't + // need fixup. It's important to check this here, because our fixup checks are more + // conservative than strictly necessary. + if (isset($fixupInfo[$subNodeName]) + && $subNode->getAttribute('origNode') !== $origSubNode + ) { + $fixup = $fixupInfo[$subNodeName]; + $res = $this->pFixup($fixup, $subNode, $class, $subStartPos, $subEndPos); + } else { + $res = $this->p($subNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true); + } + + $this->safeAppend($result, $res); + $this->setIndentLevel($origIndentLevel); + + $result .= $extraRight; + } + + $pos = $subEndPos + 1; + } + + $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment); + return $result; + } + + /** + * Perform a format-preserving pretty print of an array. + * + * @param Node[] $nodes New nodes + * @param Node[] $origNodes Original nodes + * @param int $pos Current token position (updated by reference) + * @param int $indentAdjustment Adjustment for indentation + * @param string $parentNodeClass Class of the containing node. + * @param string $subNodeName Name of array subnode. + * @param null|int $fixup Fixup information for array item nodes + * + * @return null|string Result of pretty print or null if cannot preserve formatting + */ + protected function pArray( + array $nodes, array $origNodes, int &$pos, int $indentAdjustment, + string $parentNodeClass, string $subNodeName, ?int $fixup + ): ?string { + $diff = $this->nodeListDiffer->diffWithReplacements($origNodes, $nodes); + + $mapKey = $parentNodeClass . '->' . $subNodeName; + $insertStr = $this->listInsertionMap[$mapKey] ?? null; + $isStmtList = $subNodeName === 'stmts'; + + $beforeFirstKeepOrReplace = true; + $skipRemovedNode = false; + $delayedAdd = []; + $lastElemIndentLevel = $this->indentLevel; + + $insertNewline = false; + if ($insertStr === "\n") { + $insertStr = ''; + $insertNewline = true; + } + + if ($isStmtList && \count($origNodes) === 1 && \count($nodes) !== 1) { + $startPos = $origNodes[0]->getStartTokenPos(); + $endPos = $origNodes[0]->getEndTokenPos(); + \assert($startPos >= 0 && $endPos >= 0); + if (!$this->origTokens->haveBraces($startPos, $endPos)) { + // This was a single statement without braces, but either additional statements + // have been added, or the single statement has been removed. This requires the + // addition of braces. For now fall back. + // TODO: Try to preserve formatting + return null; + } + } + + $result = ''; + foreach ($diff as $i => $diffElem) { + $diffType = $diffElem->type; + /** @var Node|string|null $arrItem */ + $arrItem = $diffElem->new; + /** @var Node|string|null $origArrItem */ + $origArrItem = $diffElem->old; + + if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) { + $beforeFirstKeepOrReplace = false; + + if ($origArrItem === null || $arrItem === null) { + // We can only handle the case where both are null + if ($origArrItem === $arrItem) { + continue; + } + return null; + } + + if (!$arrItem instanceof Node || !$origArrItem instanceof Node) { + // We can only deal with nodes. This can occur for Names, which use string arrays. + return null; + } + + $itemStartPos = $origArrItem->getStartTokenPos(); + $itemEndPos = $origArrItem->getEndTokenPos(); + \assert($itemStartPos >= 0 && $itemEndPos >= 0 && $itemStartPos >= $pos); + + $origIndentLevel = $this->indentLevel; + $lastElemIndentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment; + $this->setIndentLevel($lastElemIndentLevel); + + $comments = $arrItem->getComments(); + $origComments = $origArrItem->getComments(); + $commentStartPos = $origComments ? $origComments[0]->getStartTokenPos() : $itemStartPos; + \assert($commentStartPos >= 0); + + if ($commentStartPos < $pos) { + // Comments may be assigned to multiple nodes if they start at the same position. + // Make sure we don't try to print them multiple times. + $commentStartPos = $itemStartPos; + } + + if ($skipRemovedNode) { + if ($isStmtList && $this->origTokens->haveTagInRange($pos, $itemStartPos)) { + // We'd remove an opening/closing PHP tag. + // TODO: Preserve formatting. + $this->setIndentLevel($origIndentLevel); + return null; + } + } else { + $result .= $this->origTokens->getTokenCode( + $pos, $commentStartPos, $indentAdjustment); + } + + if (!empty($delayedAdd)) { + /** @var Node $delayedAddNode */ + foreach ($delayedAdd as $delayedAddNode) { + if ($insertNewline) { + $delayedAddComments = $delayedAddNode->getComments(); + if ($delayedAddComments) { + $result .= $this->pComments($delayedAddComments) . $this->nl; + } + } + + $this->safeAppend($result, $this->p($delayedAddNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true)); + + if ($insertNewline) { + $result .= $insertStr . $this->nl; + } else { + $result .= $insertStr; + } + } + + $delayedAdd = []; + } + + if ($comments !== $origComments) { + if ($comments) { + $result .= $this->pComments($comments) . $this->nl; + } + } else { + $result .= $this->origTokens->getTokenCode( + $commentStartPos, $itemStartPos, $indentAdjustment); + } + + // If we had to remove anything, we have done so now. + $skipRemovedNode = false; + } elseif ($diffType === DiffElem::TYPE_ADD) { + if (null === $insertStr) { + // We don't have insertion information for this list type + return null; + } + + if (!$arrItem instanceof Node) { + // We only support list insertion of nodes. + return null; + } + + // We go multiline if the original code was multiline, + // or if it's an array item with a comment above it. + // Match always uses multiline formatting. + if ($insertStr === ', ' && + ($this->isMultiline($origNodes) || $arrItem->getComments() || + $parentNodeClass === Expr\Match_::class) + ) { + $insertStr = ','; + $insertNewline = true; + } + + if ($beforeFirstKeepOrReplace) { + // Will be inserted at the next "replace" or "keep" element + $delayedAdd[] = $arrItem; + continue; + } + + $itemStartPos = $pos; + $itemEndPos = $pos - 1; + + $origIndentLevel = $this->indentLevel; + $this->setIndentLevel($lastElemIndentLevel); + + if ($insertNewline) { + $result .= $insertStr . $this->nl; + $comments = $arrItem->getComments(); + if ($comments) { + $result .= $this->pComments($comments) . $this->nl; + } + } else { + $result .= $insertStr; + } + } elseif ($diffType === DiffElem::TYPE_REMOVE) { + if (!$origArrItem instanceof Node) { + // We only support removal for nodes + return null; + } + + $itemStartPos = $origArrItem->getStartTokenPos(); + $itemEndPos = $origArrItem->getEndTokenPos(); + \assert($itemStartPos >= 0 && $itemEndPos >= 0); + + // Consider comments part of the node. + $origComments = $origArrItem->getComments(); + if ($origComments) { + $itemStartPos = $origComments[0]->getStartTokenPos(); + } + + if ($i === 0) { + // If we're removing from the start, keep the tokens before the node and drop those after it, + // instead of the other way around. + $result .= $this->origTokens->getTokenCode( + $pos, $itemStartPos, $indentAdjustment); + $skipRemovedNode = true; + } else { + if ($isStmtList && $this->origTokens->haveTagInRange($pos, $itemStartPos)) { + // We'd remove an opening/closing PHP tag. + // TODO: Preserve formatting. + return null; + } + } + + $pos = $itemEndPos + 1; + continue; + } else { + throw new \Exception("Shouldn't happen"); + } + + if (null !== $fixup && $arrItem->getAttribute('origNode') !== $origArrItem) { + $res = $this->pFixup($fixup, $arrItem, null, $itemStartPos, $itemEndPos); + } else { + $res = $this->p($arrItem, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true); + } + $this->safeAppend($result, $res); + + $this->setIndentLevel($origIndentLevel); + $pos = $itemEndPos + 1; + } + + if ($skipRemovedNode) { + // TODO: Support removing single node. + return null; + } + + if (!empty($delayedAdd)) { + if (!isset($this->emptyListInsertionMap[$mapKey])) { + return null; + } + + list($findToken, $extraLeft, $extraRight) = $this->emptyListInsertionMap[$mapKey]; + if (null !== $findToken) { + $insertPos = $this->origTokens->findRight($pos, $findToken) + 1; + $result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment); + $pos = $insertPos; + } + + $first = true; + $result .= $extraLeft; + foreach ($delayedAdd as $delayedAddNode) { + if (!$first) { + $result .= $insertStr; + if ($insertNewline) { + $result .= $this->nl; + } + } + $result .= $this->p($delayedAddNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true); + $first = false; + } + $result .= $extraRight === "\n" ? $this->nl : $extraRight; + } + + return $result; + } + + /** + * Print node with fixups. + * + * Fixups here refer to the addition of extra parentheses, braces or other characters, that + * are required to preserve program semantics in a certain context (e.g. to maintain precedence + * or because only certain expressions are allowed in certain places). + * + * @param int $fixup Fixup type + * @param Node $subNode Subnode to print + * @param string|null $parentClass Class of parent node + * @param int $subStartPos Original start pos of subnode + * @param int $subEndPos Original end pos of subnode + * + * @return string Result of fixed-up print of subnode + */ + protected function pFixup(int $fixup, Node $subNode, ?string $parentClass, int $subStartPos, int $subEndPos): string { + switch ($fixup) { + case self::FIXUP_PREC_LEFT: + // We use a conservative approximation where lhsPrecedence == precedence. + if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) { + $precedence = $this->precedenceMap[$parentClass][1]; + return $this->p($subNode, $precedence, $precedence); + } + break; + case self::FIXUP_PREC_RIGHT: + if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) { + $precedence = $this->precedenceMap[$parentClass][2]; + return $this->p($subNode, $precedence, $precedence); + } + break; + case self::FIXUP_PREC_UNARY: + if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) { + $precedence = $this->precedenceMap[$parentClass][0]; + return $this->p($subNode, $precedence, $precedence); + } + break; + case self::FIXUP_CALL_LHS: + if ($this->callLhsRequiresParens($subNode) + && !$this->origTokens->haveParens($subStartPos, $subEndPos) + ) { + return '(' . $this->p($subNode) . ')'; + } + break; + case self::FIXUP_DEREF_LHS: + if ($this->dereferenceLhsRequiresParens($subNode) + && !$this->origTokens->haveParens($subStartPos, $subEndPos) + ) { + return '(' . $this->p($subNode) . ')'; + } + break; + case self::FIXUP_STATIC_DEREF_LHS: + if ($this->staticDereferenceLhsRequiresParens($subNode) + && !$this->origTokens->haveParens($subStartPos, $subEndPos) + ) { + return '(' . $this->p($subNode) . ')'; + } + break; + case self::FIXUP_NEW: + if ($this->newOperandRequiresParens($subNode) + && !$this->origTokens->haveParens($subStartPos, $subEndPos)) { + return '(' . $this->p($subNode) . ')'; + } + break; + case self::FIXUP_BRACED_NAME: + case self::FIXUP_VAR_BRACED_NAME: + if ($subNode instanceof Expr + && !$this->origTokens->haveBraces($subStartPos, $subEndPos) + ) { + return ($fixup === self::FIXUP_VAR_BRACED_NAME ? '$' : '') + . '{' . $this->p($subNode) . '}'; + } + break; + case self::FIXUP_ENCAPSED: + if (!$subNode instanceof Node\InterpolatedStringPart + && !$this->origTokens->haveBraces($subStartPos, $subEndPos) + ) { + return '{' . $this->p($subNode) . '}'; + } + break; + default: + throw new \Exception('Cannot happen'); + } + + // Nothing special to do + return $this->p($subNode); + } + + /** + * Appends to a string, ensuring whitespace between label characters. + * + * Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x". + * Without safeAppend the result would be "echox", which does not preserve semantics. + */ + protected function safeAppend(string &$str, string $append): void { + if ($str === "") { + $str = $append; + return; + } + + if ($append === "") { + return; + } + + if (!$this->labelCharMap[$append[0]] + || !$this->labelCharMap[$str[\strlen($str) - 1]]) { + $str .= $append; + } else { + $str .= " " . $append; + } + } + + /** + * Determines whether the LHS of a call must be wrapped in parenthesis. + * + * @param Node $node LHS of a call + * + * @return bool Whether parentheses are required + */ + protected function callLhsRequiresParens(Node $node): bool { + return !($node instanceof Node\Name + || $node instanceof Expr\Variable + || $node instanceof Expr\ArrayDimFetch + || $node instanceof Expr\FuncCall + || $node instanceof Expr\MethodCall + || $node instanceof Expr\NullsafeMethodCall + || $node instanceof Expr\StaticCall + || $node instanceof Expr\Array_); + } + + /** + * Determines whether the LHS of an array/object operation must be wrapped in parentheses. + * + * @param Node $node LHS of dereferencing operation + * + * @return bool Whether parentheses are required + */ + protected function dereferenceLhsRequiresParens(Node $node): bool { + // A constant can occur on the LHS of an array/object deref, but not a static deref. + return $this->staticDereferenceLhsRequiresParens($node) + && !$node instanceof Expr\ConstFetch; + } + + /** + * Determines whether the LHS of a static operation must be wrapped in parentheses. + * + * @param Node $node LHS of dereferencing operation + * + * @return bool Whether parentheses are required + */ + protected function staticDereferenceLhsRequiresParens(Node $node): bool { + return !($node instanceof Expr\Variable + || $node instanceof Node\Name + || $node instanceof Expr\ArrayDimFetch + || $node instanceof Expr\PropertyFetch + || $node instanceof Expr\NullsafePropertyFetch + || $node instanceof Expr\StaticPropertyFetch + || $node instanceof Expr\FuncCall + || $node instanceof Expr\MethodCall + || $node instanceof Expr\NullsafeMethodCall + || $node instanceof Expr\StaticCall + || $node instanceof Expr\Array_ + || $node instanceof Scalar\String_ + || $node instanceof Expr\ClassConstFetch); + } + + /** + * Determines whether an expression used in "new" or "instanceof" requires parentheses. + * + * @param Node $node New or instanceof operand + * + * @return bool Whether parentheses are required + */ + protected function newOperandRequiresParens(Node $node): bool { + if ($node instanceof Node\Name || $node instanceof Expr\Variable) { + return false; + } + if ($node instanceof Expr\ArrayDimFetch || $node instanceof Expr\PropertyFetch || + $node instanceof Expr\NullsafePropertyFetch + ) { + return $this->newOperandRequiresParens($node->var); + } + if ($node instanceof Expr\StaticPropertyFetch) { + return $this->newOperandRequiresParens($node->class); + } + return true; + } + + /** + * Print modifiers, including trailing whitespace. + * + * @param int $modifiers Modifier mask to print + * + * @return string Printed modifiers + */ + protected function pModifiers(int $modifiers): string { + return ($modifiers & Modifiers::FINAL ? 'final ' : '') + . ($modifiers & Modifiers::ABSTRACT ? 'abstract ' : '') + . ($modifiers & Modifiers::PUBLIC ? 'public ' : '') + . ($modifiers & Modifiers::PROTECTED ? 'protected ' : '') + . ($modifiers & Modifiers::PRIVATE ? 'private ' : '') + . ($modifiers & Modifiers::STATIC ? 'static ' : '') + . ($modifiers & Modifiers::READONLY ? 'readonly ' : ''); + } + + protected function pStatic(bool $static): string { + return $static ? 'static ' : ''; + } + + /** + * Determine whether a list of nodes uses multiline formatting. + * + * @param (Node|null)[] $nodes Node list + * + * @return bool Whether multiline formatting is used + */ + protected function isMultiline(array $nodes): bool { + if (\count($nodes) < 2) { + return false; + } + + $pos = -1; + foreach ($nodes as $node) { + if (null === $node) { + continue; + } + + $endPos = $node->getEndTokenPos() + 1; + if ($pos >= 0) { + $text = $this->origTokens->getTokenCode($pos, $endPos, 0); + if (false === strpos($text, "\n")) { + // We require that a newline is present between *every* item. If the formatting + // is inconsistent, with only some items having newlines, we don't consider it + // as multiline + return false; + } + } + $pos = $endPos; + } + + return true; + } + + /** + * Lazily initializes label char map. + * + * The label char map determines whether a certain character may occur in a label. + */ + protected function initializeLabelCharMap(): void { + if (isset($this->labelCharMap)) { + return; + } + + $this->labelCharMap = []; + for ($i = 0; $i < 256; $i++) { + $chr = chr($i); + $this->labelCharMap[$chr] = $i >= 0x80 || ctype_alnum($chr); + } + + if ($this->phpVersion->allowsDelInIdentifiers()) { + $this->labelCharMap["\x7f"] = true; + } + } + + /** + * Lazily initializes node list differ. + * + * The node list differ is used to determine differences between two array subnodes. + */ + protected function initializeNodeListDiffer(): void { + if (isset($this->nodeListDiffer)) { + return; + } + + $this->nodeListDiffer = new Internal\Differ(function ($a, $b) { + if ($a instanceof Node && $b instanceof Node) { + return $a === $b->getAttribute('origNode'); + } + // Can happen for array destructuring + return $a === null && $b === null; + }); + } + + /** + * Lazily initializes fixup map. + * + * The fixup map is used to determine whether a certain subnode of a certain node may require + * some kind of "fixup" operation, e.g. the addition of parenthesis or braces. + */ + protected function initializeFixupMap(): void { + if (isset($this->fixupMap)) { + return; + } + + $this->fixupMap = [ + Expr\Instanceof_::class => [ + 'expr' => self::FIXUP_PREC_UNARY, + 'class' => self::FIXUP_NEW, + ], + Expr\Ternary::class => [ + 'cond' => self::FIXUP_PREC_LEFT, + 'else' => self::FIXUP_PREC_RIGHT, + ], + Expr\Yield_::class => ['value' => self::FIXUP_PREC_UNARY], + + Expr\FuncCall::class => ['name' => self::FIXUP_CALL_LHS], + Expr\StaticCall::class => ['class' => self::FIXUP_STATIC_DEREF_LHS], + Expr\ArrayDimFetch::class => ['var' => self::FIXUP_DEREF_LHS], + Expr\ClassConstFetch::class => [ + 'class' => self::FIXUP_STATIC_DEREF_LHS, + 'name' => self::FIXUP_BRACED_NAME, + ], + Expr\New_::class => ['class' => self::FIXUP_NEW], + Expr\MethodCall::class => [ + 'var' => self::FIXUP_DEREF_LHS, + 'name' => self::FIXUP_BRACED_NAME, + ], + Expr\NullsafeMethodCall::class => [ + 'var' => self::FIXUP_DEREF_LHS, + 'name' => self::FIXUP_BRACED_NAME, + ], + Expr\StaticPropertyFetch::class => [ + 'class' => self::FIXUP_STATIC_DEREF_LHS, + 'name' => self::FIXUP_VAR_BRACED_NAME, + ], + Expr\PropertyFetch::class => [ + 'var' => self::FIXUP_DEREF_LHS, + 'name' => self::FIXUP_BRACED_NAME, + ], + Expr\NullsafePropertyFetch::class => [ + 'var' => self::FIXUP_DEREF_LHS, + 'name' => self::FIXUP_BRACED_NAME, + ], + Scalar\InterpolatedString::class => [ + 'parts' => self::FIXUP_ENCAPSED, + ], + ]; + + $binaryOps = [ + BinaryOp\Pow::class, BinaryOp\Mul::class, BinaryOp\Div::class, BinaryOp\Mod::class, + BinaryOp\Plus::class, BinaryOp\Minus::class, BinaryOp\Concat::class, + BinaryOp\ShiftLeft::class, BinaryOp\ShiftRight::class, BinaryOp\Smaller::class, + BinaryOp\SmallerOrEqual::class, BinaryOp\Greater::class, BinaryOp\GreaterOrEqual::class, + BinaryOp\Equal::class, BinaryOp\NotEqual::class, BinaryOp\Identical::class, + BinaryOp\NotIdentical::class, BinaryOp\Spaceship::class, BinaryOp\BitwiseAnd::class, + BinaryOp\BitwiseXor::class, BinaryOp\BitwiseOr::class, BinaryOp\BooleanAnd::class, + BinaryOp\BooleanOr::class, BinaryOp\Coalesce::class, BinaryOp\LogicalAnd::class, + BinaryOp\LogicalXor::class, BinaryOp\LogicalOr::class, + ]; + foreach ($binaryOps as $binaryOp) { + $this->fixupMap[$binaryOp] = [ + 'left' => self::FIXUP_PREC_LEFT, + 'right' => self::FIXUP_PREC_RIGHT + ]; + } + + $prefixOps = [ + Expr\Clone_::class, Expr\BitwiseNot::class, Expr\BooleanNot::class, Expr\UnaryPlus::class, Expr\UnaryMinus::class, + Cast\Int_::class, Cast\Double::class, Cast\String_::class, Cast\Array_::class, + Cast\Object_::class, Cast\Bool_::class, Cast\Unset_::class, Expr\ErrorSuppress::class, + Expr\YieldFrom::class, Expr\Print_::class, Expr\Include_::class, + Expr\Assign::class, Expr\AssignRef::class, AssignOp\Plus::class, AssignOp\Minus::class, + AssignOp\Mul::class, AssignOp\Div::class, AssignOp\Concat::class, AssignOp\Mod::class, + AssignOp\BitwiseAnd::class, AssignOp\BitwiseOr::class, AssignOp\BitwiseXor::class, + AssignOp\ShiftLeft::class, AssignOp\ShiftRight::class, AssignOp\Pow::class, AssignOp\Coalesce::class, + Expr\ArrowFunction::class, Expr\Throw_::class, + ]; + foreach ($prefixOps as $prefixOp) { + $this->fixupMap[$prefixOp] = ['expr' => self::FIXUP_PREC_UNARY]; + } + } + + /** + * Lazily initializes the removal map. + * + * The removal map is used to determine which additional tokens should be removed when a + * certain node is replaced by null. + */ + protected function initializeRemovalMap(): void { + if (isset($this->removalMap)) { + return; + } + + $stripBoth = ['left' => \T_WHITESPACE, 'right' => \T_WHITESPACE]; + $stripLeft = ['left' => \T_WHITESPACE]; + $stripRight = ['right' => \T_WHITESPACE]; + $stripDoubleArrow = ['right' => \T_DOUBLE_ARROW]; + $stripColon = ['left' => ':']; + $stripEquals = ['left' => '=']; + $this->removalMap = [ + 'Expr_ArrayDimFetch->dim' => $stripBoth, + 'ArrayItem->key' => $stripDoubleArrow, + 'Expr_ArrowFunction->returnType' => $stripColon, + 'Expr_Closure->returnType' => $stripColon, + 'Expr_Exit->expr' => $stripBoth, + 'Expr_Ternary->if' => $stripBoth, + 'Expr_Yield->key' => $stripDoubleArrow, + 'Expr_Yield->value' => $stripBoth, + 'Param->type' => $stripRight, + 'Param->default' => $stripEquals, + 'Stmt_Break->num' => $stripBoth, + 'Stmt_Catch->var' => $stripLeft, + 'Stmt_ClassConst->type' => $stripRight, + 'Stmt_ClassMethod->returnType' => $stripColon, + 'Stmt_Class->extends' => ['left' => \T_EXTENDS], + 'Stmt_Enum->scalarType' => $stripColon, + 'Stmt_EnumCase->expr' => $stripEquals, + 'Expr_PrintableNewAnonClass->extends' => ['left' => \T_EXTENDS], + 'Stmt_Continue->num' => $stripBoth, + 'Stmt_Foreach->keyVar' => $stripDoubleArrow, + 'Stmt_Function->returnType' => $stripColon, + 'Stmt_If->else' => $stripLeft, + 'Stmt_Namespace->name' => $stripLeft, + 'Stmt_Property->type' => $stripRight, + 'PropertyItem->default' => $stripEquals, + 'Stmt_Return->expr' => $stripBoth, + 'Stmt_StaticVar->default' => $stripEquals, + 'Stmt_TraitUseAdaptation_Alias->newName' => $stripLeft, + 'Stmt_TryCatch->finally' => $stripLeft, + // 'Stmt_Case->cond': Replace with "default" + // 'Stmt_Class->name': Unclear what to do + // 'Stmt_Declare->stmts': Not a plain node + // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a plain node + ]; + } + + protected function initializeInsertionMap(): void { + if (isset($this->insertionMap)) { + return; + } + + // TODO: "yield" where both key and value are inserted doesn't work + // [$find, $beforeToken, $extraLeft, $extraRight] + $this->insertionMap = [ + 'Expr_ArrayDimFetch->dim' => ['[', false, null, null], + 'ArrayItem->key' => [null, false, null, ' => '], + 'Expr_ArrowFunction->returnType' => [')', false, ': ', null], + 'Expr_Closure->returnType' => [')', false, ': ', null], + 'Expr_Ternary->if' => ['?', false, ' ', ' '], + 'Expr_Yield->key' => [\T_YIELD, false, null, ' => '], + 'Expr_Yield->value' => [\T_YIELD, false, ' ', null], + 'Param->type' => [null, false, null, ' '], + 'Param->default' => [null, false, ' = ', null], + 'Stmt_Break->num' => [\T_BREAK, false, ' ', null], + 'Stmt_Catch->var' => [null, false, ' ', null], + 'Stmt_ClassMethod->returnType' => [')', false, ': ', null], + 'Stmt_ClassConst->type' => [\T_CONST, false, ' ', null], + 'Stmt_Class->extends' => [null, false, ' extends ', null], + 'Stmt_Enum->scalarType' => [null, false, ' : ', null], + 'Stmt_EnumCase->expr' => [null, false, ' = ', null], + 'Expr_PrintableNewAnonClass->extends' => [null, false, ' extends ', null], + 'Stmt_Continue->num' => [\T_CONTINUE, false, ' ', null], + 'Stmt_Foreach->keyVar' => [\T_AS, false, null, ' => '], + 'Stmt_Function->returnType' => [')', false, ': ', null], + 'Stmt_If->else' => [null, false, ' ', null], + 'Stmt_Namespace->name' => [\T_NAMESPACE, false, ' ', null], + 'Stmt_Property->type' => [\T_VARIABLE, true, null, ' '], + 'PropertyItem->default' => [null, false, ' = ', null], + 'Stmt_Return->expr' => [\T_RETURN, false, ' ', null], + 'Stmt_StaticVar->default' => [null, false, ' = ', null], + //'Stmt_TraitUseAdaptation_Alias->newName' => [T_AS, false, ' ', null], // TODO + 'Stmt_TryCatch->finally' => [null, false, ' ', null], + + // 'Expr_Exit->expr': Complicated due to optional () + // 'Stmt_Case->cond': Conversion from default to case + // 'Stmt_Class->name': Unclear + // 'Stmt_Declare->stmts': Not a proper node + // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a proper node + ]; + } + + protected function initializeListInsertionMap(): void { + if (isset($this->listInsertionMap)) { + return; + } + + $this->listInsertionMap = [ + // special + //'Expr_ShellExec->parts' => '', // TODO These need to be treated more carefully + //'Scalar_InterpolatedString->parts' => '', + Stmt\Catch_::class . '->types' => '|', + UnionType::class . '->types' => '|', + IntersectionType::class . '->types' => '&', + Stmt\If_::class . '->elseifs' => ' ', + Stmt\TryCatch::class . '->catches' => ' ', + + // comma-separated lists + Expr\Array_::class . '->items' => ', ', + Expr\ArrowFunction::class . '->params' => ', ', + Expr\Closure::class . '->params' => ', ', + Expr\Closure::class . '->uses' => ', ', + Expr\FuncCall::class . '->args' => ', ', + Expr\Isset_::class . '->vars' => ', ', + Expr\List_::class . '->items' => ', ', + Expr\MethodCall::class . '->args' => ', ', + Expr\NullsafeMethodCall::class . '->args' => ', ', + Expr\New_::class . '->args' => ', ', + PrintableNewAnonClassNode::class . '->args' => ', ', + Expr\StaticCall::class . '->args' => ', ', + Stmt\ClassConst::class . '->consts' => ', ', + Stmt\ClassMethod::class . '->params' => ', ', + Stmt\Class_::class . '->implements' => ', ', + Stmt\Enum_::class . '->implements' => ', ', + PrintableNewAnonClassNode::class . '->implements' => ', ', + Stmt\Const_::class . '->consts' => ', ', + Stmt\Declare_::class . '->declares' => ', ', + Stmt\Echo_::class . '->exprs' => ', ', + Stmt\For_::class . '->init' => ', ', + Stmt\For_::class . '->cond' => ', ', + Stmt\For_::class . '->loop' => ', ', + Stmt\Function_::class . '->params' => ', ', + Stmt\Global_::class . '->vars' => ', ', + Stmt\GroupUse::class . '->uses' => ', ', + Stmt\Interface_::class . '->extends' => ', ', + Expr\Match_::class . '->arms' => ', ', + Stmt\Property::class . '->props' => ', ', + Stmt\StaticVar::class . '->vars' => ', ', + Stmt\TraitUse::class . '->traits' => ', ', + Stmt\TraitUseAdaptation\Precedence::class . '->insteadof' => ', ', + Stmt\Unset_::class . '->vars' => ', ', + Stmt\UseUse::class . '->uses' => ', ', + MatchArm::class . '->conds' => ', ', + AttributeGroup::class . '->attrs' => ', ', + + // statement lists + Expr\Closure::class . '->stmts' => "\n", + Stmt\Case_::class . '->stmts' => "\n", + Stmt\Catch_::class . '->stmts' => "\n", + Stmt\Class_::class . '->stmts' => "\n", + Stmt\Enum_::class . '->stmts' => "\n", + PrintableNewAnonClassNode::class . '->stmts' => "\n", + Stmt\Interface_::class . '->stmts' => "\n", + Stmt\Trait_::class . '->stmts' => "\n", + Stmt\ClassMethod::class . '->stmts' => "\n", + Stmt\Declare_::class . '->stmts' => "\n", + Stmt\Do_::class . '->stmts' => "\n", + Stmt\ElseIf_::class . '->stmts' => "\n", + Stmt\Else_::class . '->stmts' => "\n", + Stmt\Finally_::class . '->stmts' => "\n", + Stmt\Foreach_::class . '->stmts' => "\n", + Stmt\For_::class . '->stmts' => "\n", + Stmt\Function_::class . '->stmts' => "\n", + Stmt\If_::class . '->stmts' => "\n", + Stmt\Namespace_::class . '->stmts' => "\n", + Stmt\Block::class . '->stmts' => "\n", + + // Attribute groups + Stmt\Class_::class . '->attrGroups' => "\n", + Stmt\Enum_::class . '->attrGroups' => "\n", + Stmt\EnumCase::class . '->attrGroups' => "\n", + Stmt\Interface_::class . '->attrGroups' => "\n", + Stmt\Trait_::class . '->attrGroups' => "\n", + Stmt\Function_::class . '->attrGroups' => "\n", + Stmt\ClassMethod::class . '->attrGroups' => "\n", + Stmt\ClassConst::class . '->attrGroups' => "\n", + Stmt\Property::class . '->attrGroups' => "\n", + PrintableNewAnonClassNode::class . '->attrGroups' => ' ', + Expr\Closure::class . '->attrGroups' => ' ', + Expr\ArrowFunction::class . '->attrGroups' => ' ', + Param::class . '->attrGroups' => ' ', + Stmt\Switch_::class . '->cases' => "\n", + Stmt\TraitUse::class . '->adaptations' => "\n", + Stmt\TryCatch::class . '->stmts' => "\n", + Stmt\While_::class . '->stmts' => "\n", + + // dummy for top-level context + 'File->stmts' => "\n", + ]; + } + + protected function initializeEmptyListInsertionMap(): void { + if (isset($this->emptyListInsertionMap)) { + return; + } + + // TODO Insertion into empty statement lists. + + // [$find, $extraLeft, $extraRight] + $this->emptyListInsertionMap = [ + Expr\ArrowFunction::class . '->params' => ['(', '', ''], + Expr\Closure::class . '->uses' => [')', ' use (', ')'], + Expr\Closure::class . '->params' => ['(', '', ''], + Expr\FuncCall::class . '->args' => ['(', '', ''], + Expr\MethodCall::class . '->args' => ['(', '', ''], + Expr\NullsafeMethodCall::class . '->args' => ['(', '', ''], + Expr\New_::class . '->args' => ['(', '', ''], + PrintableNewAnonClassNode::class . '->args' => ['(', '', ''], + PrintableNewAnonClassNode::class . '->implements' => [null, ' implements ', ''], + Expr\StaticCall::class . '->args' => ['(', '', ''], + Stmt\Class_::class . '->implements' => [null, ' implements ', ''], + Stmt\Enum_::class . '->implements' => [null, ' implements ', ''], + Stmt\ClassMethod::class . '->params' => ['(', '', ''], + Stmt\Interface_::class . '->extends' => [null, ' extends ', ''], + Stmt\Function_::class . '->params' => ['(', '', ''], + Stmt\Interface_::class . '->attrGroups' => [null, '', "\n"], + Stmt\Class_::class . '->attrGroups' => [null, '', "\n"], + Stmt\ClassConst::class . '->attrGroups' => [null, '', "\n"], + Stmt\ClassMethod::class . '->attrGroups' => [null, '', "\n"], + Stmt\Function_::class . '->attrGroups' => [null, '', "\n"], + Stmt\Property::class . '->attrGroups' => [null, '', "\n"], + Stmt\Trait_::class . '->attrGroups' => [null, '', "\n"], + Expr\ArrowFunction::class . '->attrGroups' => [null, '', ' '], + Expr\Closure::class . '->attrGroups' => [null, '', ' '], + PrintableNewAnonClassNode::class . '->attrGroups' => [\T_NEW, ' ', ''], + + /* These cannot be empty to start with: + * Expr_Isset->vars + * Stmt_Catch->types + * Stmt_Const->consts + * Stmt_ClassConst->consts + * Stmt_Declare->declares + * Stmt_Echo->exprs + * Stmt_Global->vars + * Stmt_GroupUse->uses + * Stmt_Property->props + * Stmt_StaticVar->vars + * Stmt_TraitUse->traits + * Stmt_TraitUseAdaptation_Precedence->insteadof + * Stmt_Unset->vars + * Stmt_Use->uses + * UnionType->types + */ + + /* TODO + * Stmt_If->elseifs + * Stmt_TryCatch->catches + * Expr_Array->items + * Expr_List->items + * Stmt_For->init + * Stmt_For->cond + * Stmt_For->loop + */ + ]; + } + + protected function initializeModifierChangeMap(): void { + if (isset($this->modifierChangeMap)) { + return; + } + + $this->modifierChangeMap = [ + Stmt\ClassConst::class . '->flags' => ['pModifiers', \T_CONST], + Stmt\ClassMethod::class . '->flags' => ['pModifiers', \T_FUNCTION], + Stmt\Class_::class . '->flags' => ['pModifiers', \T_CLASS], + Stmt\Property::class . '->flags' => ['pModifiers', \T_VARIABLE], + PrintableNewAnonClassNode::class . '->flags' => ['pModifiers', \T_CLASS], + Param::class . '->flags' => ['pModifiers', \T_VARIABLE], + Expr\Closure::class . '->static' => ['pStatic', \T_FUNCTION], + Expr\ArrowFunction::class . '->static' => ['pStatic', \T_FN], + //Stmt\TraitUseAdaptation\Alias::class . '->newModifier' => 0, // TODO + ]; + + // List of integer subnodes that are not modifiers: + // Expr_Include->type + // Stmt_GroupUse->type + // Stmt_Use->type + // UseItem->type + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Token.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Token.php new file mode 100644 index 0000000..6683310 --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/Token.php @@ -0,0 +1,18 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +/** + * A PHP token. On PHP 8.0 this extends from PhpToken. + */ +class Token extends Internal\TokenPolyfill { + /** Get (exclusive) zero-based end position of the token. */ + public function getEndPos(): int { + return $this->pos + \strlen($this->text); + } + + /** Get 1-based end line number of the token. */ + public function getEndLine(): int { + return $this->line + \substr_count($this->text, "\n"); + } +} diff --git a/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/compatibility_tokens.php b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/compatibility_tokens.php new file mode 100644 index 0000000..273271d --- /dev/null +++ b/php/libraries/composer/vendor/nikic/php-parser/lib/PhpParser/compatibility_tokens.php @@ -0,0 +1,63 @@ +<?php declare(strict_types=1); + +namespace PhpParser; + +if (!\function_exists('PhpParser\defineCompatibilityTokens')) { + function defineCompatibilityTokens(): void { + $compatTokens = [ + // PHP 8.0 + 'T_NAME_QUALIFIED', + 'T_NAME_FULLY_QUALIFIED', + 'T_NAME_RELATIVE', + 'T_MATCH', + 'T_NULLSAFE_OBJECT_OPERATOR', + 'T_ATTRIBUTE', + // PHP 8.1 + 'T_ENUM', + 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', + 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', + 'T_READONLY', + ]; + + // PHP-Parser might be used together with another library that also emulates some or all + // of these tokens. Perform a sanity-check that all already defined tokens have been + // assigned a unique ID. + $usedTokenIds = []; + foreach ($compatTokens as $token) { + if (\defined($token)) { + $tokenId = \constant($token); + if (!\is_int($tokenId)) { + throw new \Error(sprintf( + 'Token %s has ID of type %s, should be int. ' . + 'You may be using a library with broken token emulation', + $token, \gettype($tokenId) + )); + } + $clashingToken = $usedTokenIds[$tokenId] ?? null; + if ($clashingToken !== null) { + throw new \Error(sprintf( + 'Token %s has same ID as token %s, ' . + 'you may be using a library with broken token emulation', + $token, $clashingToken + )); + } + $usedTokenIds[$tokenId] = $token; + } + } + + // Now define any tokens that have not yet been emulated. Try to assign IDs from -1 + // downwards, but skip any IDs that may already be in use. + $newTokenId = -1; + foreach ($compatTokens as $token) { + if (!\defined($token)) { + while (isset($usedTokenIds[$newTokenId])) { + $newTokenId--; + } + \define($token, $newTokenId); + $newTokenId--; + } + } + } + + defineCompatibilityTokens(); +} diff --git a/php/libraries/composer/vendor/opis/closure/CHANGELOG.md b/php/libraries/composer/vendor/opis/closure/CHANGELOG.md new file mode 100644 index 0000000..16c9e3d --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/CHANGELOG.md @@ -0,0 +1,260 @@ +CHANGELOG +--------- + +### v3.6.2, 2021.04.09 + +- Fixed string interpolation + +### v3.6.1, 2020.11.07 + +- Fixed serialization error [#84](https://github.com/opis/closure/issues/84) + +### v3.6.0, 2020.10.12 + +- Initial PHP 8 Support [#67](https://github.com/opis/closure/issues/67). + +### v3.5.7, 2020.09.06 + +- Fixed issue [#76](https://github.com/opis/closure/issues/76). +- Fixed issue [#78](https://github.com/opis/closure/issues/78). + +### v3.5.6, 2020.08.11 + +- Fixed issue [#70](https://github.com/opis/closure/issues/70) + +### v3.5.5, 2020.06.17 + +- Fixed a false-positive when using `Opis\Closure\ReflectionClosure::isScopeRequired` method + +### v3.5.4, 2020.06.07 + +- Fixed a false-positive when using `Opis\Closure\ReflectionClosure::isScopeRequired` method +- Fixed a bug related to `T_STRING_VARNAME` + +### v3.5.3, 2020.05.25 + +- Improved parser +- The class scope optimisation is no longer used. We always bind now to the closure's original class scope. +When the class scope was `null`, the optimisation failed to work as expected and kept the wrong `SerializableClosure` scope. + +### v3.5.2, 2020.05.21 + +- Removed extra semicolon in short closures, since is not part of the closure's body. + +### v3.5.1, 2019.11.30 + +- Bugfix. See #47 + +### v3.5.0, 2019.11.29 + +- Added support for short closures (arrow functions) +- Added `isShortClosure` method to `Opis\Closure\ReflectionClosure` + +### v3.4.2, 2019.11.29 + +- Added `stream_set_option()` + +### v3.4.1, 2019.10.19 + +- Fixed a [bug](https://github.com/opis/closure/issues/40) that prevented serialization to work correctly. + +### v3.4.0, 2019.09.03 + +- Added `createClosure` static method in `Opis\Closure\SerializableClosure`. +This method creates a new closure from arbitrary code, emulating `create_function`, +but without using eval + +### v3.3.1, 2019.07.10 + +- Use `sha1` instead of `md5` for hashing file names in `Opis\Closure\ReflectionClosure` class + +### v3.3.0, 2019.05.31 + +- Fixed a bug that prevented signed closures to properly work when the serialized string +contains invalid UTF-8 chars. Starting with this version `json_encode` is no longer used +when signing a closure. Backward compatibility is maintained and all closures that were +previously signed using the old method will continue to work. + +### v3.2.0, 2019.05.05 + +- Since an unsigned closure can be unserialized when no security provider is set, +there is no reason to treat differently a signed closure in the same situation. +Therefore, the `Opis\Closure\SecurityException` exception is no longer thrown when +unserializing a signed closure, if no security provider is set. + +### v3.1.6, 2019.02.22 + +- Fixed a bug that occurred when trying to set properties of classes that were not defined in user-land. +Those properties are now ignored. + +### v3.1.5, 2019.01.14 + +- Improved parser + +### v3.1.4, 2019.01.14 + +- Added support for static methods that are named using PHP keywords or magic constants. +Ex: `A::new()`, `A::use()`, `A::if()`, `A::function()`, `A::__DIR__()`, etc. +- Used `@internal` to mark classes & methods that are for internal use only and +backward compatibility is not guaranteed. + +### v3.1.3, 2019.01.07 + +- Fixed a bug that prevented traits to be correctly resolved when used by an +anonymous class +- Fixed a bug that occurred when `$this` keyword was used inside an anonymous class + +### v3.1.2, 2018.12.16 + +* Fixed a bug regarding comma trail in group-use statements. See [issue 23](https://github.com/opis/closure/issues/23) + +### v3.1.1, 2018.10.02 + +* Fixed a bug where `parent` keyword was treated like a class-name and scope was not added to the +serialized closure +* Fixed a bug where return type was not properly handled for nested closures +* Support for anonymous classes was improved + +### v3.1.0, 2018.09.20 + +* Added `transformUseVariables` and `resolveUseVariables` to +`Opis\Closure\SerializableClosure` class. +* Added `removeSecurityProvider` static method to +`Opis\Closure\SerializableClosure` class. +* Fixed some security related issues where a user was able to unserialize an unsigned +closure, even when a security provider was in use. + +### v3.0.12, 2018.02.23 + +* Bugfix. See [issue 20](https://github.com/opis/closure/issues/20) + +### v3.0.11, 2018.01.22 + +* Bugfix. See [issue 18](https://github.com/opis/closure/issues/18) + +### v3.0.10, 2018.01.04 + +* Improved support for PHP 7.1 & 7.2 + +### v3.0.9, 2018.01.04 + +* Fixed a bug where the return type was not properly resolved. +See [issue 17](https://github.com/opis/closure/issues/17) +* Added more tests + +### v3.0.8, 2017.12.18 + +* Fixed a bug. See [issue 16](https://github.com/opis/closure/issues/16) + +### v3.0.7, 2017.10.31 + +* Bugfix: static properties are ignored now, since they are not serializable + +### v3.0.6, 2017.10.06 + +* Fixed a bug introduced by accident in 3.0.5 + +### v3.0.5, 2017.09.18 + +* Fixed a bug related to nested references + +### v3.0.4, 2017.09.18 + +* \[*internal*\] Refactored `SerializableClosure::mapPointers` method +* \[*internal*\] Added a new optional argument to `SerializableClosure::unwrapClosures` +* \[*internal*\] Removed `SerializableClosure::getClosurePointer` method +* Fixed various bugs + +### v3.0.3, 2017.09.06 + +* Fixed a bug related to nested object references +* \[*internal*\] `Opis\Closure\ClosureScope` now extends `SplObjectStorage` +* \[*internal*\] The `storage` property was removed from `Opis\Closure\ClosureScope` +* \[*internal*\] The `instances` and `objects` properties were removed from `Opis\Closure\ClosureContext` + +### v3.0.2, 2017.08.28 + +* Fixed a bug where `$this` object was not handled properly inside the +`SerializableClosre::serialize` method. + +### v3.0.1, 2017.04.13 + +* Fixed a bug in 'ignore_next' state + +### v3.0.0, 2017.04.07 + +* Dropped PHP 5.3 support +* Moved source files from `lib` to `src` folder +* Removed second parameter from `Opis\Closure\SerializableClosure::from` method and from constructor +* Removed `Opis\Closure\{SecurityProviderInterface, DefaultSecurityProvider, SecureClosure}` classes +* Refactored how signed closures were handled +* Added `wrapClosures` and `unwrapClosures` static methods to `Opis\Closure\SerializableClosure` class +* Added `Opis\Colosure\serialize` and `Opis\Closure\unserialize` functions +* Improved serialization. You can now serialize arbitrary objects and the library will automatically wrap all closures + +### v2.4.0, 2016.12.16 + +* The parser was refactored and improved +* Refactored `Opis\Closure\SerializableClosure::__invoke` method +* `Opis\Closure\{ISecurityProvider, SecurityProvider}` were added +* `Opis\Closure\{SecurityProviderInterface, DefaultSecurityProvider, SecureClosure}` were deprecated +and they will be removed in the next major version +* `setSecretKey` and `addSecurityProvider` static methods were added to `Opis\Closure\SerializableClosure` + +### v2.3.2, 2016.12.15 + +* Fixed a bug that prevented namespace resolution to be done properly + +### v2.3.1, 2016.12.13 + +* Hotfix. See [PR](https://github.com/opis/closure/pull/7) + +### v2.3.0, 2016.11.17 + +* Added `isBindingRequired` and `isScopeRequired` to the `Opis\Closure\ReflectionClosure` class +* Automatically detects when the scope and/or the bound object of a closure needs to be serialized. + +### v2.2.1, 2016.08.20 + +* Fixed a bug in `Opis\Closure\ReflectionClosure::fetchItems` + +### v2.2.0, 2016.07.26 + +* Fixed CS +* `Opis\Closure\ClosureContext`, `Opis\Closure\ClosureScope`, `Opis\Closure\SelfReference` + and `Opis\Closure\SecurityException` classes were moved into separate files +* Added support for PHP7 syntax +* Fixed some bugs in `Opis\Closure\ReflectionClosure` class +* Improved closure parser +* Added an analyzer for SuperClosure library + +### v2.1.0, 2015.09.30 + +* Added support for the missing `__METHOD__`, `__FUNCTION__` and `__TRAIT__` magic constants +* Added some security related classes and interfaces: `Opis\Closure\SecurityProviderInterface`, +`Opis\Closure\DefaultSecurityProvider`, `Opis\Closure\SecureClosure`, `Opis\Closure\SecurityException`. +* Fiexed a bug in `Opis\Closure\ReflectionClosure::getClasses` method +* Other minor bugfixes +* Added support for static closures +* Added public `isStatic` method to `Opis\Closure\ReflectionClosure` class + + +### v2.0.1, 2015.09.23 + +* Removed `branch-alias` property from `composer.json` +* Bugfix. See [issue #6](https://github.com/opis/closure/issues/6) + +### v2.0.0, 2015.07.31 + +* The closure parser was improved +* Class names are now automatically resolved +* Added support for the `#trackme` directive which allows tracking closure's residing source + +### v1.3.0, 2014.10.18 + +* Added autoload file +* Changed README file + +### Opis Closure 1.2.2 + +* Started changelog diff --git a/php/libraries/composer/vendor/opis/closure/LICENSE b/php/libraries/composer/vendor/opis/closure/LICENSE new file mode 100644 index 0000000..9c0a19b --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018-2019 Zindex Software + +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/php/libraries/composer/vendor/opis/closure/NOTICE b/php/libraries/composer/vendor/opis/closure/NOTICE new file mode 100644 index 0000000..ae5caa6 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/NOTICE @@ -0,0 +1,9 @@ +Opis Closure +Copyright 2018-2019 Zindex Software + +This product includes software developed at +Zindex Software (http://zindex.software). + +This software was originally developed by Marius Sarca and Sorin Sarca +(Copyright 2014-2018). The copyright info was changed with the permission +of the original authors. \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/README.md b/php/libraries/composer/vendor/opis/closure/README.md new file mode 100644 index 0000000..f5f3ad8 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/README.md @@ -0,0 +1,92 @@ +Opis Closure +==================== +[![Tests](https://github.com/opis/closure/workflows/Tests/badge.svg)](https://github.com/opis/closure/actions) +[![Latest Stable Version](https://poser.pugx.org/opis/closure/v/stable.png)](https://packagist.org/packages/opis/closure) +[![Latest Unstable Version](https://poser.pugx.org/opis/closure/v/unstable.png)](https://packagist.org/packages/opis/closure) +[![License](https://poser.pugx.org/opis/closure/license.png)](https://packagist.org/packages/opis/closure) + +Serializable closures +--------------------- +**Opis Closure** is a library that aims to overcome PHP's limitations regarding closure +serialization by providing a wrapper that will make all closures serializable. + +**The library's key features:** + +- Serialize any closure +- Serialize arbitrary objects +- Doesn't use `eval` for closure serialization or unserialization +- Works with any PHP version that has support for closures +- Supports PHP 7 syntax +- Handles all variables referenced/imported in `use()` and automatically wraps all referenced/imported closures for +proper serialization +- Handles recursive closures +- Handles magic constants like `__FILE__`, `__DIR__`, `__LINE__`, `__NAMESPACE__`, `__CLASS__`, +`__TRAIT__`, `__METHOD__` and `__FUNCTION__`. +- Automatically resolves all class names, function names and constant names used inside the closure +- Track closure's residing source by using the `#trackme` directive +- Simple and very fast parser +- Any error or exception, that might occur when executing an unserialized closure, can be caught and treated properly +- You can serialize/unserialize any closure unlimited times, even those previously unserialized +(this is possible because `eval()` is not used for unserialization) +- Handles static closures +- Supports cryptographically signed closures +- Provides a reflector that can give you information about the serialized closure +- Provides an analyzer for *SuperClosure* library +- Automatically detects when the scope and/or the bound object of a closure needs to be serialized +in order for the closure to work after deserialization + +## Documentation + +The full documentation for this library can be found [here][documentation]. + +## License + +**Opis Closure** is licensed under the [MIT License (MIT)][license]. + +## Requirements + +* PHP ^5.4 || ^7.0 || ^8.0 + +## Installation + +**Opis Closure** is available on [Packagist] and it can be installed from a +command line interface by using [Composer]. + +```bash +composer require opis/closure +``` + +Or you could directly reference it into your `composer.json` file as a dependency + +```json +{ + "require": { + "opis/closure": "^3.5" + } +} +``` + +### Migrating from 2.x + +If your project needs to support PHP 5.3 you can continue using the `2.x` version +of **Opis Closure**. Otherwise, assuming you are not using one of the removed/refactored classes or features(see +[CHANGELOG]), migrating to version `3.x` is simply a matter of updating your `composer.json` file. + +### Semantic versioning + +**Opis Closure** follows [semantic versioning][SemVer] specifications. + +### Arbitrary object serialization + +We've added this feature in order to be able to support the serialization of a closure's bound object. +The implementation is far from being perfect, and it's really hard to make it work flawless. +We will try to improve this, but we can't guarantee anything. +So our advice regarding the `Opis\Closure\serialize|unserialize` functions is to use them with caution. + + +[documentation]: https://www.opis.io/closure "Opis Closure" +[license]: http://opensource.org/licenses/MIT "MIT License" +[Packagist]: https://packagist.org/packages/opis/closure "Packagist" +[Composer]: https://getcomposer.org "Composer" +[SemVer]: http://semver.org/ "Semantic versioning" +[CHANGELOG]: https://github.com/opis/closure/blob/master/CHANGELOG.md "Changelog" diff --git a/php/libraries/composer/vendor/opis/closure/autoload.php b/php/libraries/composer/vendor/opis/closure/autoload.php new file mode 100644 index 0000000..2354ea5 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/autoload.php @@ -0,0 +1,39 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +require_once __DIR__ . '/functions.php'; + +spl_autoload_register(function($class){ + + $class = ltrim($class, '\\'); + $dir = __DIR__ . '/src'; + $namespace = 'Opis\Closure'; + + if(strpos($class, $namespace) === 0) + { + $class = substr($class, strlen($namespace)); + $path = ''; + if(($pos = strripos($class, '\\')) !== FALSE) + { + $path = str_replace('\\', '/', substr($class, 0, $pos)) . '/'; + $class = substr($class, $pos + 1); + } + $path .= str_replace('_', '/', $class) . '.php'; + $dir .= '/' . $path; + + if(file_exists($dir)) + { + include $dir; + return true; + } + + return false; + } + + return false; + +}); diff --git a/php/libraries/composer/vendor/opis/closure/composer.json b/php/libraries/composer/vendor/opis/closure/composer.json new file mode 100644 index 0000000..5d7d77a --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/composer.json @@ -0,0 +1,44 @@ +{ + "name": "opis/closure", + "description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.", + "keywords": ["closure", "serialization", "function", "serializable", "serialize", "anonymous functions"], + "homepage": "https://opis.io/closure", + "license": "MIT", + "authors": [ + { + "name": "Marius Sarca", + "email": "marius.sarca@gmail.com" + }, + { + "name": "Sorin Sarca", + "email": "sarca_sorin@hotmail.com" + } + ], + "require": { + "php": "^5.4 || ^7.0 || ^8.0" + }, + "require-dev": { + "jeremeamia/superclosure": "^2.0", + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0" + }, + "autoload": { + "psr-4": { + "Opis\\Closure\\": "src/" + }, + "files": ["functions.php"] + }, + "autoload-dev": { + "psr-4": { + "Opis\\Closure\\Test\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.6.x-dev" + } + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/php/libraries/composer/vendor/opis/closure/functions.php b/php/libraries/composer/vendor/opis/closure/functions.php new file mode 100644 index 0000000..38dcb91 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/functions.php @@ -0,0 +1,41 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +/** + * Serialize + * + * @param mixed $data + * @return string + */ +function serialize($data) +{ + SerializableClosure::enterContext(); + SerializableClosure::wrapClosures($data); + $data = \serialize($data); + SerializableClosure::exitContext(); + return $data; +} + +/** + * Unserialize + * + * @param string $data + * @param array|null $options + * @return mixed + */ +function unserialize($data, array $options = null) +{ + SerializableClosure::enterContext(); + $data = ($options === null || \PHP_MAJOR_VERSION < 7) + ? \unserialize($data) + : \unserialize($data, $options); + SerializableClosure::unwrapClosures($data); + SerializableClosure::exitContext(); + return $data; +} diff --git a/php/libraries/composer/vendor/opis/closure/src/Analyzer.php b/php/libraries/composer/vendor/opis/closure/src/Analyzer.php new file mode 100644 index 0000000..9618b1c --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/Analyzer.php @@ -0,0 +1,62 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +use Closure; +use SuperClosure\Analyzer\ClosureAnalyzer; + +/** + * @deprecated We'll remove this class + */ +class Analyzer extends ClosureAnalyzer +{ + /** + * Analyzer a given closure. + * + * @param Closure $closure + * + * @return array + */ + public function analyze(Closure $closure) + { + $reflection = new ReflectionClosure($closure); + $scope = $reflection->getClosureScopeClass(); + + $data = [ + 'reflection' => $reflection, + 'code' => $reflection->getCode(), + 'hasThis' => $reflection->isBindingRequired(), + 'context' => $reflection->getUseVariables(), + 'hasRefs' => false, + 'binding' => $reflection->getClosureThis(), + 'scope' => $scope ? $scope->getName() : null, + 'isStatic' => $reflection->isStatic(), + ]; + + return $data; + } + + /** + * @param array $data + * @return mixed + */ + protected function determineCode(array &$data) + { + return null; + } + + /** + * @param array $data + * @return mixed + */ + protected function determineContext(array &$data) + { + return null; + } + +} diff --git a/php/libraries/composer/vendor/opis/closure/src/ClosureContext.php b/php/libraries/composer/vendor/opis/closure/src/ClosureContext.php new file mode 100644 index 0000000..d8f13d9 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/ClosureContext.php @@ -0,0 +1,34 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +/** + * Closure context class + * @internal + */ +class ClosureContext +{ + /** + * @var ClosureScope Closures scope + */ + public $scope; + + /** + * @var integer + */ + public $locks; + + /** + * Constructor + */ + public function __construct() + { + $this->scope = new ClosureScope(); + $this->locks = 0; + } +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/src/ClosureScope.php b/php/libraries/composer/vendor/opis/closure/src/ClosureScope.php new file mode 100644 index 0000000..3afd9b5 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/ClosureScope.php @@ -0,0 +1,25 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +/** + * Closure scope class + * @internal + */ +class ClosureScope extends \SplObjectStorage +{ + /** + * @var integer Number of serializations in current scope + */ + public $serializations = 0; + + /** + * @var integer Number of closures that have to be serialized + */ + public $toserialize = 0; +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/src/ClosureStream.php b/php/libraries/composer/vendor/opis/closure/src/ClosureStream.php new file mode 100644 index 0000000..d77d97c --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/ClosureStream.php @@ -0,0 +1,99 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +/** + * @internal + */ +class ClosureStream +{ + const STREAM_PROTO = 'closure'; + + protected static $isRegistered = false; + + protected $content; + + protected $length; + + protected $pointer = 0; + + function stream_open($path, $mode, $options, &$opened_path) + { + $this->content = "<?php\nreturn " . substr($path, strlen(static::STREAM_PROTO . '://')) . ";"; + $this->length = strlen($this->content); + return true; + } + + public function stream_read($count) + { + $value = substr($this->content, $this->pointer, $count); + $this->pointer += $count; + return $value; + } + + public function stream_eof() + { + return $this->pointer >= $this->length; + } + + public function stream_set_option($option, $arg1, $arg2) + { + return false; + } + + public function stream_stat() + { + $stat = stat(__FILE__); + $stat[7] = $stat['size'] = $this->length; + return $stat; + } + + public function url_stat($path, $flags) + { + $stat = stat(__FILE__); + $stat[7] = $stat['size'] = $this->length; + return $stat; + } + + public function stream_seek($offset, $whence = SEEK_SET) + { + $crt = $this->pointer; + + switch ($whence) { + case SEEK_SET: + $this->pointer = $offset; + break; + case SEEK_CUR: + $this->pointer += $offset; + break; + case SEEK_END: + $this->pointer = $this->length + $offset; + break; + } + + if ($this->pointer < 0 || $this->pointer >= $this->length) { + $this->pointer = $crt; + return false; + } + + return true; + } + + public function stream_tell() + { + return $this->pointer; + } + + public static function register() + { + if (!static::$isRegistered) { + static::$isRegistered = stream_wrapper_register(static::STREAM_PROTO, __CLASS__); + } + } + +} diff --git a/php/libraries/composer/vendor/opis/closure/src/ISecurityProvider.php b/php/libraries/composer/vendor/opis/closure/src/ISecurityProvider.php new file mode 100644 index 0000000..54e2e20 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/ISecurityProvider.php @@ -0,0 +1,25 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +interface ISecurityProvider +{ + /** + * Sign serialized closure + * @param string $closure + * @return array + */ + public function sign($closure); + + /** + * Verify signature + * @param array $data + * @return bool + */ + public function verify(array $data); +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/src/ReflectionClosure.php b/php/libraries/composer/vendor/opis/closure/src/ReflectionClosure.php new file mode 100644 index 0000000..1f6a832 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/ReflectionClosure.php @@ -0,0 +1,1093 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +defined('T_NAME_QUALIFIED') || define('T_NAME_QUALIFIED', -4); +defined('T_NAME_FULLY_QUALIFIED') || define('T_NAME_FULLY_QUALIFIED', -5); +defined('T_FN') || define('T_FN', -6); + +use Closure; +use ReflectionFunction; + +class ReflectionClosure extends ReflectionFunction +{ + protected $code; + protected $tokens; + protected $hashedName; + protected $useVariables; + protected $isStaticClosure; + protected $isScopeRequired; + protected $isBindingRequired; + protected $isShortClosure; + + protected static $files = array(); + protected static $classes = array(); + protected static $functions = array(); + protected static $constants = array(); + protected static $structures = array(); + + + /** + * ReflectionClosure constructor. + * @param Closure $closure + * @param string|null $code This is ignored. Do not use it + * @throws \ReflectionException + */ + public function __construct(Closure $closure, $code = null) + { + parent::__construct($closure); + } + + /** + * @return bool + */ + public function isStatic() + { + if ($this->isStaticClosure === null) { + $this->isStaticClosure = strtolower(substr($this->getCode(), 0, 6)) === 'static'; + } + + return $this->isStaticClosure; + } + + public function isShortClosure() + { + if ($this->isShortClosure === null) { + $code = $this->getCode(); + if ($this->isStatic()) { + $code = substr($code, 6); + } + $this->isShortClosure = strtolower(substr(trim($code), 0, 2)) === 'fn'; + } + + return $this->isShortClosure; + } + + /** + * @return string + */ + public function getCode() + { + if($this->code !== null){ + return $this->code; + } + + $fileName = $this->getFileName(); + $line = $this->getStartLine() - 1; + + $className = null; + + if (null !== $className = $this->getClosureScopeClass()) { + $className = '\\' . trim($className->getName(), '\\'); + } + + $builtin_types = self::getBuiltinTypes(); + $class_keywords = ['self', 'static', 'parent']; + + $ns = $this->getNamespaceName(); + $nsf = $ns == '' ? '' : ($ns[0] == '\\' ? $ns : '\\' . $ns); + + $_file = var_export($fileName, true); + $_dir = var_export(dirname($fileName), true); + $_namespace = var_export($ns, true); + $_class = var_export(trim($className, '\\'), true); + $_function = $ns . ($ns == '' ? '' : '\\') . '{closure}'; + $_method = ($className == '' ? '' : trim($className, '\\') . '::') . $_function; + $_function = var_export($_function, true); + $_method = var_export($_method, true); + $_trait = null; + + $tokens = $this->getTokens(); + $state = $lastState = 'start'; + $inside_structure = false; + $isShortClosure = false; + $inside_structure_mark = 0; + $open = 0; + $code = ''; + $id_start = $id_start_ci = $id_name = $context = ''; + $classes = $functions = $constants = null; + $use = array(); + $lineAdd = 0; + $isUsingScope = false; + $isUsingThisObject = false; + + for($i = 0, $l = count($tokens); $i < $l; $i++) { + $token = $tokens[$i]; + switch ($state) { + case 'start': + if ($token[0] === T_FUNCTION || $token[0] === T_STATIC) { + $code .= $token[1]; + $state = $token[0] === T_FUNCTION ? 'function' : 'static'; + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } + break; + case 'static': + if ($token[0] === T_WHITESPACE || $token[0] === T_COMMENT || $token[0] === T_FUNCTION) { + $code .= $token[1]; + if ($token[0] === T_FUNCTION) { + $state = 'function'; + } + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } else { + $code = ''; + $state = 'start'; + } + break; + case 'function': + switch ($token[0]){ + case T_STRING: + $code = ''; + $state = 'named_function'; + break; + case '(': + $code .= '('; + $state = 'closure_args'; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'named_function': + if($token[0] === T_FUNCTION || $token[0] === T_STATIC){ + $code = $token[1]; + $state = $token[0] === T_FUNCTION ? 'function' : 'static'; + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } + break; + case 'closure_args': + switch ($token[0]){ + case T_NAME_QUALIFIED: + list($id_start, $id_start_ci, $id_name) = $this->parseNameQualified($token[1]); + $context = 'args'; + $state = 'id_name'; + $lastState = 'closure_args'; + break; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'args'; + $state = 'id_name'; + $lastState = 'closure_args'; + break; + case T_USE: + $code .= $token[1]; + $state = 'use'; + break; + case T_DOUBLE_ARROW: + $code .= $token[1]; + if ($isShortClosure) { + $state = 'closure'; + } + break; + case ':': + $code .= ':'; + $state = 'return'; + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'use': + switch ($token[0]){ + case T_VARIABLE: + $use[] = substr($token[1], 1); + $code .= $token[1]; + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + case ':': + $code .= ':'; + $state = 'return'; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + break; + } + break; + case 'return': + switch ($token[0]){ + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'return_type'; + $state = 'id_name'; + $lastState = 'return'; + break 2; + case T_NAME_QUALIFIED: + list($id_start, $id_start_ci, $id_name) = $this->parseNameQualified($token[1]); + $context = 'return_type'; + $state = 'id_name'; + $lastState = 'return'; + break 2; + case T_DOUBLE_ARROW: + $code .= $token[1]; + if ($isShortClosure) { + $state = 'closure'; + } + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + break; + } + break; + case 'closure': + switch ($token[0]){ + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + case '{': + $code .= is_array($token) ? $token[1] : $token; + $open++; + break; + case '}': + $code .= '}'; + if(--$open === 0 && !$isShortClosure){ + break 3; + } elseif ($inside_structure) { + $inside_structure = !($open === $inside_structure_mark); + } + break; + case '(': + case '[': + $code .= $token[0]; + if ($isShortClosure) { + $open++; + } + break; + case ')': + case ']': + if ($isShortClosure) { + if ($open === 0) { + break 3; + } + --$open; + } + $code .= $token[0]; + break; + case ',': + case ';': + if ($isShortClosure && $open === 0) { + break 3; + } + $code .= $token[0]; + break; + case T_LINE: + $code .= $token[2] - $line + $lineAdd; + break; + case T_FILE: + $code .= $_file; + break; + case T_DIR: + $code .= $_dir; + break; + case T_NS_C: + $code .= $_namespace; + break; + case T_CLASS_C: + $code .= $inside_structure ? $token[1] : $_class; + break; + case T_FUNC_C: + $code .= $inside_structure ? $token[1] : $_function; + break; + case T_METHOD_C: + $code .= $inside_structure ? $token[1] : $_method; + break; + case T_COMMENT: + if (substr($token[1], 0, 8) === '#trackme') { + $timestamp = time(); + $code .= '/**' . PHP_EOL; + $code .= '* Date : ' . date(DATE_W3C, $timestamp) . PHP_EOL; + $code .= '* Timestamp : ' . $timestamp . PHP_EOL; + $code .= '* Line : ' . ($line + 1) . PHP_EOL; + $code .= '* File : ' . $_file . PHP_EOL . '*/' . PHP_EOL; + $lineAdd += 5; + } else { + $code .= $token[1]; + } + break; + case T_VARIABLE: + if($token[1] == '$this' && !$inside_structure){ + $isUsingThisObject = true; + } + $code .= $token[1]; + break; + case T_STATIC: + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'root'; + $state = 'id_name'; + $lastState = 'closure'; + break 2; + case T_NAME_QUALIFIED: + list($id_start, $id_start_ci, $id_name) = $this->parseNameQualified($token[1]); + $context = 'root'; + $state = 'id_name'; + $lastState = 'closure'; + break 2; + case T_NEW: + $code .= $token[1]; + $context = 'new'; + $state = 'id_start'; + $lastState = 'closure'; + break 2; + case T_USE: + $code .= $token[1]; + $context = 'use'; + $state = 'id_start'; + $lastState = 'closure'; + break; + case T_INSTANCEOF: + case T_INSTEADOF: + $code .= $token[1]; + $context = 'instanceof'; + $state = 'id_start'; + $lastState = 'closure'; + break; + case T_OBJECT_OPERATOR: + case T_DOUBLE_COLON: + $code .= $token[1]; + $lastState = 'closure'; + $state = 'ignore_next'; + break; + case T_FUNCTION: + $code .= $token[1]; + $state = 'closure_args'; + if (!$inside_structure) { + $inside_structure = true; + $inside_structure_mark = $open; + } + break; + case T_TRAIT_C: + if ($_trait === null) { + $startLine = $this->getStartLine(); + $endLine = $this->getEndLine(); + $structures = $this->getStructures(); + + $_trait = ''; + + foreach ($structures as &$struct) { + if ($struct['type'] === 'trait' && + $struct['start'] <= $startLine && + $struct['end'] >= $endLine + ) { + $_trait = ($ns == '' ? '' : $ns . '\\') . $struct['name']; + break; + } + } + + $_trait = var_export($_trait, true); + } + + $code .= $_trait; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'ignore_next': + switch ($token[0]){ + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_CLASS: + case T_NEW: + case T_STATIC: + case T_VARIABLE: + case T_STRING: + case T_CLASS_C: + case T_FILE: + case T_DIR: + case T_METHOD_C: + case T_FUNC_C: + case T_FUNCTION: + case T_INSTANCEOF: + case T_LINE: + case T_NS_C: + case T_TRAIT_C: + case T_USE: + $code .= $token[1]; + $state = $lastState; + break; + default: + $state = $lastState; + $i--; + } + break; + case 'id_start': + switch ($token[0]){ + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_NS_SEPARATOR: + case T_NAME_FULLY_QUALIFIED: + case T_STRING: + case T_STATIC: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $state = 'id_name'; + break 2; + case T_NAME_QUALIFIED: + list($id_start, $id_start_ci, $id_name) = $this->parseNameQualified($token[1]); + $state = 'id_name'; + break 2; + case T_VARIABLE: + $code .= $token[1]; + $state = $lastState; + break; + case T_CLASS: + $code .= $token[1]; + $state = 'anonymous'; + break; + default: + $i--;//reprocess last + $state = 'id_name'; + } + break; + case 'id_name': + switch ($token[0]){ + case T_NAME_QUALIFIED: + case T_NS_SEPARATOR: + case T_STRING: + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $id_name .= $token[1]; + break; + case '(': + if ($isShortClosure) { + $open++; + } + if($context === 'new' || false !== strpos($id_name, '\\')){ + if($id_start_ci === 'self' || $id_start_ci === 'static') { + if (!$inside_structure) { + $isUsingScope = true; + } + } elseif ($id_start !== '\\' && !in_array($id_start_ci, $class_keywords)) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if($id_start[0] !== '\\'){ + $id_start = $nsf . '\\' . $id_start; + } + } + } else { + if($id_start !== '\\'){ + if($functions === null){ + $functions = $this->getFunctions(); + } + if(isset($functions[$id_start_ci])){ + $id_start = $functions[$id_start_ci]; + } elseif ($nsf !== '\\' && function_exists($nsf . '\\' . $id_start)) { + $id_start = $nsf . '\\' . $id_start; + // Cache it to functions array + $functions[$id_start_ci] = $id_start; + } + } + } + $code .= $id_start . $id_name . '('; + $state = $lastState; + break; + case T_VARIABLE: + case T_DOUBLE_COLON: + if($id_start !== '\\') { + if($id_start_ci === 'self' || $id_start_ci === 'parent'){ + if (!$inside_structure) { + $isUsingScope = true; + } + } elseif ($id_start_ci === 'static') { + if (!$inside_structure) { + $isUsingScope = $token[0] === T_DOUBLE_COLON; + } + } elseif (!(\PHP_MAJOR_VERSION >= 7 && in_array($id_start_ci, $builtin_types))){ + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if($id_start[0] !== '\\'){ + $id_start = $nsf . '\\' . $id_start; + } + } + } + + $code .= $id_start . $id_name . $token[1]; + $state = $token[0] === T_DOUBLE_COLON ? 'ignore_next' : $lastState; + break; + default: + if($id_start !== '\\' && !defined($id_start)){ + if($constants === null){ + $constants = $this->getConstants(); + } + if(isset($constants[$id_start])){ + $id_start = $constants[$id_start]; + } elseif($context === 'new'){ + if(in_array($id_start_ci, $class_keywords)) { + if (!$inside_structure) { + $isUsingScope = true; + } + } else { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf . '\\' . $id_start; + } + } + } elseif($context === 'use' || + $context === 'instanceof' || + $context === 'args' || + $context === 'return_type' || + $context === 'extends' || + $context === 'root' + ){ + if(in_array($id_start_ci, $class_keywords)){ + if (!$inside_structure && !$id_start_ci === 'static') { + $isUsingScope = true; + } + } elseif (!(\PHP_MAJOR_VERSION >= 7 && in_array($id_start_ci, $builtin_types))){ + if($classes === null){ + $classes = $this->getClasses(); + } + if(isset($classes[$id_start_ci])){ + $id_start = $classes[$id_start_ci]; + } + if($id_start[0] !== '\\'){ + $id_start = $nsf . '\\' . $id_start; + } + } + } + } + $code .= $id_start . $id_name; + $state = $lastState; + $i--;//reprocess last token + } + break; + case 'anonymous': + switch ($token[0]) { + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $state = 'id_name'; + $context = 'extends'; + $lastState = 'anonymous'; + break; + case '{': + $state = 'closure'; + if (!$inside_structure) { + $inside_structure = true; + $inside_structure_mark = $open; + } + $i--; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + } + } + + if ($isShortClosure) { + $this->useVariables = $this->getStaticVariables(); + } else { + $this->useVariables = empty($use) ? $use : array_intersect_key($this->getStaticVariables(), array_flip($use)); + } + + $this->isShortClosure = $isShortClosure; + $this->isBindingRequired = $isUsingThisObject; + $this->isScopeRequired = $isUsingScope; + $this->code = $code; + + return $this->code; + } + + /** + * @return array + */ + private static function getBuiltinTypes() + { + // PHP 5 + if (\PHP_MAJOR_VERSION === 5) { + return ['array', 'callable']; + } + + // PHP 8 + if (\PHP_MAJOR_VERSION === 8) { + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object', 'mixed', 'false', 'null']; + } + + // PHP 7 + switch (\PHP_MINOR_VERSION) { + case 0: + return ['array', 'callable', 'string', 'int', 'bool', 'float']; + case 1: + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void']; + default: + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object']; + } + } + + /** + * @return array + */ + public function getUseVariables() + { + if($this->useVariables !== null){ + return $this->useVariables; + } + + $tokens = $this->getTokens(); + $use = array(); + $state = 'start'; + + foreach ($tokens as &$token) { + $is_array = is_array($token); + + switch ($state) { + case 'start': + if ($is_array && $token[0] === T_USE) { + $state = 'use'; + } + break; + case 'use': + if ($is_array) { + if ($token[0] === T_VARIABLE) { + $use[] = substr($token[1], 1); + } + } elseif ($token == ')') { + break 2; + } + break; + } + } + + $this->useVariables = empty($use) ? $use : array_intersect_key($this->getStaticVariables(), array_flip($use)); + + return $this->useVariables; + } + + /** + * return bool + */ + public function isBindingRequired() + { + if($this->isBindingRequired === null){ + $this->getCode(); + } + + return $this->isBindingRequired; + } + + /** + * return bool + */ + public function isScopeRequired() + { + if($this->isScopeRequired === null){ + $this->getCode(); + } + + return $this->isScopeRequired; + } + + /** + * @return string + */ + protected function getHashedFileName() + { + if ($this->hashedName === null) { + $this->hashedName = sha1($this->getFileName()); + } + + return $this->hashedName; + } + + /** + * @return array + */ + protected function getFileTokens() + { + $key = $this->getHashedFileName(); + + if (!isset(static::$files[$key])) { + static::$files[$key] = token_get_all(file_get_contents($this->getFileName())); + } + + return static::$files[$key]; + } + + /** + * @return array + */ + protected function getTokens() + { + if ($this->tokens === null) { + $tokens = $this->getFileTokens(); + $startLine = $this->getStartLine(); + $endLine = $this->getEndLine(); + $results = array(); + $start = false; + + foreach ($tokens as &$token) { + if (!is_array($token)) { + if ($start) { + $results[] = $token; + } + + continue; + } + + $line = $token[2]; + + if ($line <= $endLine) { + if ($line >= $startLine) { + $start = true; + $results[] = $token; + } + + continue; + } + + break; + } + + $this->tokens = $results; + } + + return $this->tokens; + } + + /** + * @return array + */ + protected function getClasses() + { + $key = $this->getHashedFileName(); + + if (!isset(static::$classes[$key])) { + $this->fetchItems(); + } + + return static::$classes[$key]; + } + + /** + * @return array + */ + protected function getFunctions() + { + $key = $this->getHashedFileName(); + + if (!isset(static::$functions[$key])) { + $this->fetchItems(); + } + + return static::$functions[$key]; + } + + /** + * @return array + */ + protected function getConstants() + { + $key = $this->getHashedFileName(); + + if (!isset(static::$constants[$key])) { + $this->fetchItems(); + } + + return static::$constants[$key]; + } + + /** + * @return array + */ + protected function getStructures() + { + $key = $this->getHashedFileName(); + + if (!isset(static::$structures[$key])) { + $this->fetchItems(); + } + + return static::$structures[$key]; + } + + protected function fetchItems() + { + $key = $this->getHashedFileName(); + + $classes = array(); + $functions = array(); + $constants = array(); + $structures = array(); + $tokens = $this->getFileTokens(); + + $open = 0; + $state = 'start'; + $lastState = ''; + $prefix = ''; + $name = ''; + $alias = ''; + $isFunc = $isConst = false; + + $startLine = $endLine = 0; + $structType = $structName = ''; + $structIgnore = false; + + foreach ($tokens as $token) { + + switch ($state) { + case 'start': + switch ($token[0]) { + case T_CLASS: + case T_INTERFACE: + case T_TRAIT: + $state = 'before_structure'; + $startLine = $token[2]; + $structType = $token[0] == T_CLASS + ? 'class' + : ($token[0] == T_INTERFACE ? 'interface' : 'trait'); + break; + case T_USE: + $state = 'use'; + $prefix = $name = $alias = ''; + $isFunc = $isConst = false; + break; + case T_FUNCTION: + $state = 'structure'; + $structIgnore = true; + break; + case T_NEW: + $state = 'new'; + break; + case T_OBJECT_OPERATOR: + case T_DOUBLE_COLON: + $state = 'invoke'; + break; + } + break; + case 'use': + switch ($token[0]) { + case T_FUNCTION: + $isFunc = true; + break; + case T_CONST: + $isConst = true; + break; + case T_NS_SEPARATOR: + $name .= $token[1]; + break; + case T_STRING: + $name .= $token[1]; + $alias = $token[1]; + break; + case T_NAME_QUALIFIED: + $name .= $token[1]; + $pieces = explode('\\', $token[1]); + $alias = end($pieces); + break; + case T_AS: + $lastState = 'use'; + $state = 'alias'; + break; + case '{': + $prefix = $name; + $name = $alias = ''; + $state = 'use-group'; + break; + case ',': + case ';': + if ($name === '' || $name[0] !== '\\') { + $name = '\\' . $name; + } + + if ($alias !== '') { + if ($isFunc) { + $functions[strtolower($alias)] = $name; + } elseif ($isConst) { + $constants[$alias] = $name; + } else { + $classes[strtolower($alias)] = $name; + } + } + $name = $alias = ''; + $state = $token === ';' ? 'start' : 'use'; + break; + } + break; + case 'use-group': + switch ($token[0]) { + case T_NS_SEPARATOR: + $name .= $token[1]; + break; + case T_NAME_QUALIFIED: + $name .= $token[1]; + $pieces = explode('\\', $token[1]); + $alias = end($pieces); + break; + case T_STRING: + $name .= $token[1]; + $alias = $token[1]; + break; + case T_AS: + $lastState = 'use-group'; + $state = 'alias'; + break; + case ',': + case '}': + + if ($prefix === '' || $prefix[0] !== '\\') { + $prefix = '\\' . $prefix; + } + + if ($alias !== '') { + if ($isFunc) { + $functions[strtolower($alias)] = $prefix . $name; + } elseif ($isConst) { + $constants[$alias] = $prefix . $name; + } else { + $classes[strtolower($alias)] = $prefix . $name; + } + } + $name = $alias = ''; + $state = $token === '}' ? 'use' : 'use-group'; + break; + } + break; + case 'alias': + if ($token[0] === T_STRING) { + $alias = $token[1]; + $state = $lastState; + } + break; + case 'new': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + break 2; + case T_CLASS: + $state = 'structure'; + $structIgnore = true; + break; + default: + $state = 'start'; + } + break; + case 'invoke': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + break 2; + default: + $state = 'start'; + } + break; + case 'before_structure': + if ($token[0] == T_STRING) { + $structName = $token[1]; + $state = 'structure'; + } + break; + case 'structure': + switch ($token[0]) { + case '{': + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + $open++; + break; + case '}': + if (--$open == 0) { + if(!$structIgnore){ + $structures[] = array( + 'type' => $structType, + 'name' => $structName, + 'start' => $startLine, + 'end' => $endLine, + ); + } + $structIgnore = false; + $state = 'start'; + } + break; + default: + if (is_array($token)) { + $endLine = $token[2]; + } + } + break; + } + } + + static::$classes[$key] = $classes; + static::$functions[$key] = $functions; + static::$constants[$key] = $constants; + static::$structures[$key] = $structures; + } + + private function parseNameQualified($token) + { + $pieces = explode('\\', $token); + + $id_start = array_shift($pieces); + + $id_start_ci = strtolower($id_start); + + $id_name = '\\' . implode('\\', $pieces); + + return [$id_start, $id_start_ci, $id_name]; + } +} diff --git a/php/libraries/composer/vendor/opis/closure/src/SecurityException.php b/php/libraries/composer/vendor/opis/closure/src/SecurityException.php new file mode 100644 index 0000000..b65f5cb --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/SecurityException.php @@ -0,0 +1,18 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +use Exception; + +/** + * Security exception class + */ +class SecurityException extends Exception +{ + +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/src/SecurityProvider.php b/php/libraries/composer/vendor/opis/closure/src/SecurityProvider.php new file mode 100644 index 0000000..1952917 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/SecurityProvider.php @@ -0,0 +1,42 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +class SecurityProvider implements ISecurityProvider +{ + /** @var string */ + protected $secret; + + /** + * SecurityProvider constructor. + * @param string $secret + */ + public function __construct($secret) + { + $this->secret = $secret; + } + + /** + * @inheritdoc + */ + public function sign($closure) + { + return array( + 'closure' => $closure, + 'hash' => base64_encode(hash_hmac('sha256', $closure, $this->secret, true)), + ); + } + + /** + * @inheritdoc + */ + public function verify(array $data) + { + return base64_encode(hash_hmac('sha256', $data['closure'], $this->secret, true)) === $data['hash']; + } +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/src/SelfReference.php b/php/libraries/composer/vendor/opis/closure/src/SelfReference.php new file mode 100644 index 0000000..425edf2 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/SelfReference.php @@ -0,0 +1,31 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + + +/** + * Helper class used to indicate a reference to an object + * @internal + */ +class SelfReference +{ + /** + * @var string An unique hash representing the object + */ + public $hash; + + /** + * Constructor + * + * @param string $hash + */ + public function __construct($hash) + { + $this->hash = $hash; + } +} \ No newline at end of file diff --git a/php/libraries/composer/vendor/opis/closure/src/SerializableClosure.php b/php/libraries/composer/vendor/opis/closure/src/SerializableClosure.php new file mode 100644 index 0000000..1025ff5 --- /dev/null +++ b/php/libraries/composer/vendor/opis/closure/src/SerializableClosure.php @@ -0,0 +1,678 @@ +<?php +/* =========================================================================== + * Copyright (c) 2018-2021 Zindex Software + * + * Licensed under the MIT License + * =========================================================================== */ + +namespace Opis\Closure; + +use Closure; +use Serializable; +use SplObjectStorage; +use ReflectionObject; + +/** + * Provides a wrapper for serialization of closures + */ +class SerializableClosure implements Serializable +{ + /** + * @var Closure Wrapped closure + * + * @see \Opis\Closure\SerializableClosure::getClosure() + */ + protected $closure; + + /** + * @var ReflectionClosure A reflection instance for closure + * + * @see \Opis\Closure\SerializableClosure::getReflector() + */ + protected $reflector; + + /** + * @var mixed Used at deserialization to hold variables + * + * @see \Opis\Closure\SerializableClosure::unserialize() + * @see \Opis\Closure\SerializableClosure::getReflector() + */ + protected $code; + + /** + * @var string Closure's ID + */ + protected $reference; + + /** + * @var string Closure scope + */ + protected $scope; + + /** + * @var ClosureContext Context of closure, used in serialization + */ + protected static $context; + + /** + * @var ISecurityProvider|null + */ + protected static $securityProvider; + + /** Array recursive constant*/ + const ARRAY_RECURSIVE_KEY = '¯\_(ツ)_/¯'; + + /** + * Constructor + * + * @param Closure $closure Closure you want to serialize + */ + public function __construct(Closure $closure) + { + $this->closure = $closure; + if (static::$context !== null) { + $this->scope = static::$context->scope; + $this->scope->toserialize++; + } + } + + /** + * Get the Closure object + * + * @return Closure The wrapped closure + */ + public function getClosure() + { + return $this->closure; + } + + /** + * Get the reflector for closure + * + * @return ReflectionClosure + */ + public function getReflector() + { + if ($this->reflector === null) { + $this->reflector = new ReflectionClosure($this->closure); + $this->code = null; + } + + return $this->reflector; + } + + /** + * Implementation of magic method __invoke() + */ + public function __invoke() + { + return call_user_func_array($this->closure, func_get_args()); + } + + /** + * Implementation of Serializable::serialize() + * + * @return string The serialized closure + */ + public function serialize() + { + if ($this->scope === null) { + $this->scope = new ClosureScope(); + $this->scope->toserialize++; + } + + $this->scope->serializations++; + + $scope = $object = null; + $reflector = $this->getReflector(); + + if($reflector->isBindingRequired()){ + $object = $reflector->getClosureThis(); + static::wrapClosures($object, $this->scope); + if($scope = $reflector->getClosureScopeClass()){ + $scope = $scope->name; + } + } else { + if($scope = $reflector->getClosureScopeClass()){ + $scope = $scope->name; + } + } + + $this->reference = spl_object_hash($this->closure); + + $this->scope[$this->closure] = $this; + + $use = $this->transformUseVariables($reflector->getUseVariables()); + $code = $reflector->getCode(); + + $this->mapByReference($use); + + $ret = \serialize(array( + 'use' => $use, + 'function' => $code, + 'scope' => $scope, + 'this' => $object, + 'self' => $this->reference, + )); + + if (static::$securityProvider !== null) { + $data = static::$securityProvider->sign($ret); + $ret = '@' . $data['hash'] . '.' . $data['closure']; + } + + if (!--$this->scope->serializations && !--$this->scope->toserialize) { + $this->scope = null; + } + + return $ret; + } + + /** + * Transform the use variables before serialization. + * + * @param array $data The Closure's use variables + * @return array + */ + protected function transformUseVariables($data) + { + return $data; + } + + /** + * Implementation of Serializable::unserialize() + * + * @param string $data Serialized data + * @throws SecurityException + */ + public function unserialize($data) + { + ClosureStream::register(); + + if (static::$securityProvider !== null) { + if ($data[0] !== '@') { + throw new SecurityException("The serialized closure is not signed. ". + "Make sure you use a security provider for both serialization and unserialization."); + } + + if ($data[1] !== '{') { + $separator = strpos($data, '.'); + if ($separator === false) { + throw new SecurityException('Invalid signed closure'); + } + $hash = substr($data, 1, $separator - 1); + $closure = substr($data, $separator + 1); + + $data = ['hash' => $hash, 'closure' => $closure]; + + unset($hash, $closure); + } else { + $data = json_decode(substr($data, 1), true); + } + + if (!is_array($data) || !static::$securityProvider->verify($data)) { + throw new SecurityException("Your serialized closure might have been modified and it's unsafe to be unserialized. " . + "Make sure you use the same security provider, with the same settings, " . + "both for serialization and unserialization."); + } + + $data = $data['closure']; + } elseif ($data[0] === '@') { + if ($data[1] !== '{') { + $separator = strpos($data, '.'); + if ($separator === false) { + throw new SecurityException('Invalid signed closure'); + } + $hash = substr($data, 1, $separator - 1); + $closure = substr($data, $separator + 1); + + $data = ['hash' => $hash, 'closure' => $closure]; + + unset($hash, $closure); + } else { + $data = json_decode(substr($data, 1), true); + } + + if (!is_array($data) || !isset($data['closure']) || !isset($data['hash'])) { + throw new SecurityException('Invalid signed closure'); + } + + $data = $data['closure']; + } + + $this->code = \unserialize($data); + + // unset data + unset($data); + + $this->code['objects'] = array(); + + if ($this->code['use']) { + $this->scope = new ClosureScope(); + $this->code['use'] = $this->resolveUseVariables($this->code['use']); + $this->mapPointers($this->code['use']); + extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS); + $this->scope = null; + } + + $this->closure = include(ClosureStream::STREAM_PROTO . '://' . $this->code['function']); + + if($this->code['this'] === $this){ + $this->code['this'] = null; + } + + $this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']); + + if(!empty($this->code['objects'])){ + foreach ($this->code['objects'] as $item){ + $item['property']->setValue($item['instance'], $item['object']->getClosure()); + } + } + + $this->code = $this->code['function']; + } + + /** + * Resolve the use variables after unserialization. + * + * @param array $data The Closure's transformed use variables + * @return array + */ + protected function resolveUseVariables($data) + { + return $data; + } + + /** + * Wraps a closure and sets the serialization context (if any) + * + * @param Closure $closure Closure to be wrapped + * + * @return self The wrapped closure + */ + public static function from(Closure $closure) + { + if (static::$context === null) { + $instance = new static($closure); + } elseif (isset(static::$context->scope[$closure])) { + $instance = static::$context->scope[$closure]; + } else { + $instance = new static($closure); + static::$context->scope[$closure] = $instance; + } + + return $instance; + } + + /** + * Increments the context lock counter or creates a new context if none exist + */ + public static function enterContext() + { + if (static::$context === null) { + static::$context = new ClosureContext(); + } + + static::$context->locks++; + } + + /** + * Decrements the context lock counter and destroy the context when it reaches to 0 + */ + public static function exitContext() + { + if (static::$context !== null && !--static::$context->locks) { + static::$context = null; + } + } + + /** + * @param string $secret + */ + public static function setSecretKey($secret) + { + if(static::$securityProvider === null){ + static::$securityProvider = new SecurityProvider($secret); + } + } + + /** + * @param ISecurityProvider $securityProvider + */ + public static function addSecurityProvider(ISecurityProvider $securityProvider) + { + static::$securityProvider = $securityProvider; + } + + /** + * Remove security provider + */ + public static function removeSecurityProvider() + { + static::$securityProvider = null; + } + + /** + * @return null|ISecurityProvider + */ + public static function getSecurityProvider() + { + return static::$securityProvider; + } + + /** + * Wrap closures + * + * @internal + * @param $data + * @param ClosureScope|SplObjectStorage|null $storage + */ + public static function wrapClosures(&$data, SplObjectStorage $storage = null) + { + if($storage === null){ + $storage = static::$context->scope; + } + + if($data instanceof Closure){ + $data = static::from($data); + } elseif (is_array($data)){ + if(isset($data[self::ARRAY_RECURSIVE_KEY])){ + return; + } + $data[self::ARRAY_RECURSIVE_KEY] = true; + foreach ($data as $key => &$value){ + if($key === self::ARRAY_RECURSIVE_KEY){ + continue; + } + static::wrapClosures($value, $storage); + } + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif($data instanceof \stdClass){ + if(isset($storage[$data])){ + $data = $storage[$data]; + return; + } + $data = $storage[$data] = clone($data); + foreach ($data as &$value){ + static::wrapClosures($value, $storage); + } + unset($value); + } elseif (is_object($data) && ! $data instanceof static){ + if(isset($storage[$data])){ + $data = $storage[$data]; + return; + } + $instance = $data; + $reflection = new ReflectionObject($instance); + if(!$reflection->isUserDefined()){ + $storage[$instance] = $data; + return; + } + $storage[$instance] = $data = $reflection->newInstanceWithoutConstructor(); + + do{ + if(!$reflection->isUserDefined()){ + break; + } + foreach ($reflection->getProperties() as $property){ + if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ + continue; + } + $property->setAccessible(true); + if (PHP_VERSION >= 7.4 && !$property->isInitialized($instance)) { + continue; + } + $value = $property->getValue($instance); + if(is_array($value) || is_object($value)){ + static::wrapClosures($value, $storage); + } + $property->setValue($data, $value); + }; + } while($reflection = $reflection->getParentClass()); + } + } + + /** + * Unwrap closures + * + * @internal + * @param $data + * @param SplObjectStorage|null $storage + */ + public static function unwrapClosures(&$data, SplObjectStorage $storage = null) + { + if($storage === null){ + $storage = static::$context->scope; + } + + if($data instanceof static){ + $data = $data->getClosure(); + } elseif (is_array($data)){ + if(isset($data[self::ARRAY_RECURSIVE_KEY])){ + return; + } + $data[self::ARRAY_RECURSIVE_KEY] = true; + foreach ($data as $key => &$value){ + if($key === self::ARRAY_RECURSIVE_KEY){ + continue; + } + static::unwrapClosures($value, $storage); + } + unset($data[self::ARRAY_RECURSIVE_KEY]); + }elseif ($data instanceof \stdClass){ + if(isset($storage[$data])){ + return; + } + $storage[$data] = true; + foreach ($data as &$property){ + static::unwrapClosures($property, $storage); + } + } elseif (is_object($data) && !($data instanceof Closure)){ + if(isset($storage[$data])){ + return; + } + $storage[$data] = true; + $reflection = new ReflectionObject($data); + + do{ + if(!$reflection->isUserDefined()){ + break; + } + foreach ($reflection->getProperties() as $property){ + if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ + continue; + } + $property->setAccessible(true); + if (PHP_VERSION >= 7.4 && !$property->isInitialized($data)) { + continue; + } + $value = $property->getValue($data); + if(is_array($value) || is_object($value)){ + static::unwrapClosures($value, $storage); + $property->setValue($data, $value); + } + }; + } while($reflection = $reflection->getParentClass()); + } + } + + /** + * Creates a new closure from arbitrary code, + * emulating create_function, but without using eval + * + * @param string$args + * @param string $code + * @return Closure + */ + public static function createClosure($args, $code) + { + ClosureStream::register(); + return include(ClosureStream::STREAM_PROTO . '://function(' . $args. '){' . $code . '};'); + } + + /** + * Internal method used to map closure pointers + * @internal + * @param $data + */ + protected function mapPointers(&$data) + { + $scope = $this->scope; + + if ($data instanceof static) { + $data = &$data->closure; + } elseif (is_array($data)) { + if(isset($data[self::ARRAY_RECURSIVE_KEY])){ + return; + } + $data[self::ARRAY_RECURSIVE_KEY] = true; + foreach ($data as $key => &$value){ + if($key === self::ARRAY_RECURSIVE_KEY){ + continue; + } elseif ($value instanceof static) { + $data[$key] = &$value->closure; + } elseif ($value instanceof SelfReference && $value->hash === $this->code['self']){ + $data[$key] = &$this->closure; + } else { + $this->mapPointers($value); + } + } + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if(isset($scope[$data])){ + return; + } + $scope[$data] = true; + foreach ($data as $key => &$value){ + if ($value instanceof SelfReference && $value->hash === $this->code['self']){ + $data->{$key} = &$this->closure; + } elseif(is_array($value) || is_object($value)) { + $this->mapPointers($value); + } + } + unset($value); + } elseif (is_object($data) && !($data instanceof Closure)){ + if(isset($scope[$data])){ + return; + } + $scope[$data] = true; + $reflection = new ReflectionObject($data); + do{ + if(!$reflection->isUserDefined()){ + break; + } + foreach ($reflection->getProperties() as $property){ + if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ + continue; + } + $property->setAccessible(true); + if (PHP_VERSION >= 7.4 && !$property->isInitialized($data)) { + continue; + } + $item = $property->getValue($data); + if ($item instanceof SerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) { + $this->code['objects'][] = array( + 'instance' => $data, + 'property' => $property, + 'object' => $item instanceof SelfReference ? $this : $item, + ); + } elseif (is_array($item) || is_object($item)) { + $this->mapPointers($item); + $property->setValue($data, $item); + } + } + } while($reflection = $reflection->getParentClass()); + } + } + + /** + * Internal method used to map closures by reference + * + * @internal + * @param mixed &$data + */ + protected function mapByReference(&$data) + { + if ($data instanceof Closure) { + if($data === $this->closure){ + $data = new SelfReference($this->reference); + return; + } + + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + return; + } + + $instance = new static($data); + + if (static::$context !== null) { + static::$context->scope->toserialize--; + } else { + $instance->scope = $this->scope; + } + + $data = $this->scope[$data] = $instance; + } elseif (is_array($data)) { + if(isset($data[self::ARRAY_RECURSIVE_KEY])){ + return; + } + $data[self::ARRAY_RECURSIVE_KEY] = true; + foreach ($data as $key => &$value){ + if($key === self::ARRAY_RECURSIVE_KEY){ + continue; + } + $this->mapByReference($value); + } + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if(isset($this->scope[$data])){ + $data = $this->scope[$data]; + return; + } + $instance = $data; + $this->scope[$instance] = $data = clone($data); + + foreach ($data as &$value){ + $this->mapByReference($value); + } + unset($value); + } elseif (is_object($data) && !$data instanceof SerializableClosure){ + if(isset($this->scope[$data])){ + $data = $this->scope[$data]; + return; + } + + $instance = $data; + $reflection = new ReflectionObject($data); + if(!$reflection->isUserDefined()){ + $this->scope[$instance] = $data; + return; + } + $this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor(); + + do{ + if(!$reflection->isUserDefined()){ + break; + } + foreach ($reflection->getProperties() as $property){ + if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ + continue; + } + $property->setAccessible(true); + if (PHP_VERSION >= 7.4 && !$property->isInitialized($instance)) { + continue; + } + $value = $property->getValue($instance); + if(is_array($value) || is_object($value)){ + $this->mapByReference($value); + } + $property->setValue($data, $value); + } + } while($reflection = $reflection->getParentClass()); + } + } + +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/COMMITMENT b/php/libraries/composer/vendor/phpmailer/phpmailer/COMMITMENT new file mode 100644 index 0000000..a687e0d --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/COMMITMENT @@ -0,0 +1,46 @@ +GPL Cooperation Commitment +Version 1.0 + +Before filing or continuing to prosecute any legal proceeding or claim +(other than a Defensive Action) arising from termination of a Covered +License, we commit to extend to the person or entity ('you') accused +of violating the Covered License the following provisions regarding +cure and reinstatement, taken from GPL version 3. As used here, the +term 'this License' refers to the specific Covered License being +enforced. + + However, if you cease all violation of this License, then your + license from a particular copyright holder is reinstated (a) + provisionally, unless and until the copyright holder explicitly + and finally terminates your license, and (b) permanently, if the + copyright holder fails to notify you of the violation by some + reasonable means prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is + reinstated permanently if the copyright holder notifies you of the + violation by some reasonable means, this is the first time you + have received notice of violation of this License (for any work) + from that copyright holder, and you cure the violation prior to 30 + days after your receipt of the notice. + +We intend this Commitment to be irrevocable, and binding and +enforceable against us and assignees of or successors to our +copyrights. + +Definitions + +'Covered License' means the GNU General Public License, version 2 +(GPLv2), the GNU Lesser General Public License, version 2.1 +(LGPLv2.1), or the GNU Library General Public License, version 2 +(LGPLv2), all as published by the Free Software Foundation. + +'Defensive Action' means a legal proceeding or claim that We bring +against you in response to a prior proceeding or claim initiated by +you or your affiliate. + +'We' means each contributor to this repository as of the date of +inclusion of this file, including subsidiaries of a corporate +contributor. + +This work is available under a Creative Commons Attribution-ShareAlike +4.0 International license (https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/LICENSE b/php/libraries/composer/vendor/phpmailer/phpmailer/LICENSE new file mode 100644 index 0000000..f166cc5 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! \ No newline at end of file diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/README.md b/php/libraries/composer/vendor/phpmailer/phpmailer/README.md new file mode 100644 index 0000000..fa27d2f --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/README.md @@ -0,0 +1,222 @@ +![PHPMailer](https://raw.github.com/PHPMailer/PHPMailer/master/examples/images/phpmailer.png) + +# PHPMailer – A full-featured email creation and transfer class for PHP + +[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions) [![Latest Stable Version](https://poser.pugx.org/phpmailer/phpmailer/v/stable.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![Total Downloads](https://poser.pugx.org/phpmailer/phpmailer/downloads)](https://packagist.org/packages/phpmailer/phpmailer) [![License](https://poser.pugx.org/phpmailer/phpmailer/license.svg)](https://packagist.org/packages/phpmailer/phpmailer) [![API Docs](https://github.com/phpmailer/phpmailer/workflows/Docs/badge.svg)](https://phpmailer.github.io/PHPMailer/) + +## Features +- Probably the world's most popular code for sending email from PHP! +- Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more +- Integrated SMTP support – send without a local mail server +- Send emails with multiple To, CC, BCC and Reply-to addresses +- Multipart/alternative emails for mail clients that do not read HTML email +- Add attachments, including inline +- Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings +- SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports +- Validates email addresses automatically +- Protects against header injection attacks +- Error messages in over 50 languages! +- DKIM and S/MIME signing support +- Compatible with PHP 5.5 and later, including PHP 8.0 +- Namespaced to prevent name clashes +- Much more! + +## Why you might need it +Many PHP developers need to send email from their code. The only PHP function that supports this directly is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments. + +Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong, if not unsafe! + +The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the `mail()` function should be avoided when possible; it's both faster and [safer](https://exploitbox.io/paper/Pwning-PHP-Mail-Function-For-Fun-And-RCE.html) to use SMTP to localhost. + +*Please* don't be tempted to do it yourself – if you don't use PHPMailer, there are many other excellent libraries that +you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/) +, [Laminas/Mail](https://docs.laminas.dev/laminas-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail) etc. + +## License +This software is distributed under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read [LICENSE](https://github.com/PHPMailer/PHPMailer/blob/master/LICENSE) for information on the software availability and distribution. + +## Installation & loading +PHPMailer is available on [Packagist](https://packagist.org/packages/phpmailer/phpmailer) (using semantic versioning), and installation via [Composer](https://getcomposer.org) is the recommended way to install PHPMailer. Just add this line to your `composer.json` file: + +```json +"phpmailer/phpmailer": "^6.2" +``` + +or run + +```sh +composer require phpmailer/phpmailer +``` + +Note that the `vendor` folder and the `vendor/autoload.php` script are generated by Composer; they are not part of PHPMailer. + +If you want to use the Gmail XOAUTH2 authentication class, you will also need to add a dependency on the `league/oauth2-client` package in your `composer.json`. + +Alternatively, if you're not using Composer, you +can [download PHPMailer as a zip file](https://github.com/PHPMailer/PHPMailer/archive/master.zip), (note that docs and examples are not included in the zip file), then copy the contents of the PHPMailer folder into one of the `include_path` directories specified in your PHP configuration and load each class file manually: + +```php +<?php +use PHPMailer\PHPMailer\PHPMailer; +use PHPMailer\PHPMailer\Exception; + +require 'path/to/PHPMailer/src/Exception.php'; +require 'path/to/PHPMailer/src/PHPMailer.php'; +require 'path/to/PHPMailer/src/SMTP.php'; +``` + +If you're not using the `SMTP` class explicitly (you're probably not), you don't need a `use` line for the SMTP class. Even if you're not using exceptions, you do still need to load the `Exception` class as it is used internally. + +## Legacy versions +PHPMailer 5.2 (which is compatible with PHP 5.0 — 7.0) is no longer supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), switch to the 6.x releases. + +### Upgrading from 5.2 +The biggest changes are that source files are now in the `src/` folder, and PHPMailer now declares the namespace `PHPMailer\PHPMailer`. This has several important effects – [read the upgrade guide](https://github.com/PHPMailer/PHPMailer/tree/master/UPGRADING.md) for more details. + +### Minimal installation +While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need [src/PHPMailer.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/PHPMailer.php). If you're using SMTP, you'll need [src/SMTP.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/SMTP.php), and if you're using POP-before SMTP (*very* unlikely!), you'll need [src/POP3.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/POP3.php). You can skip the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need [src/OAuth.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/OAuth.php) as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer! + +## A Simple Example + +```php +<?php +//Import PHPMailer classes into the global namespace +//These must be at the top of your script, not inside a function +use PHPMailer\PHPMailer\PHPMailer; +use PHPMailer\PHPMailer\SMTP; +use PHPMailer\PHPMailer\Exception; + +//Load Composer's autoloader +require 'vendor/autoload.php'; + +//Instantiation and passing `true` enables exceptions +$mail = new PHPMailer(true); + +try { + //Server settings + $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output + $mail->isSMTP(); //Send using SMTP + $mail->Host = 'smtp.example.com'; //Set the SMTP server to send through + $mail->SMTPAuth = true; //Enable SMTP authentication + $mail->Username = 'user@example.com'; //SMTP username + $mail->Password = 'secret'; //SMTP password + $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged + $mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above + + //Recipients + $mail->setFrom('from@example.com', 'Mailer'); + $mail->addAddress('joe@example.net', 'Joe User'); //Add a recipient + $mail->addAddress('ellen@example.com'); //Name is optional + $mail->addReplyTo('info@example.com', 'Information'); + $mail->addCC('cc@example.com'); + $mail->addBCC('bcc@example.com'); + + //Attachments + $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments + $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name + + //Content + $mail->isHTML(true); //Set email format to HTML + $mail->Subject = 'Here is the subject'; + $mail->Body = 'This is the HTML message body <b>in bold!</b>'; + $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; + + $mail->send(); + echo 'Message has been sent'; +} catch (Exception $e) { + echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; +} +``` + +You'll find plenty to play with in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder, which covers many common scenarios including sending through gmail, building contact forms, sending to mailing lists, and more. + +If you are re-using the instance (e.g. when sending to a mailing list), you may need to clear the recipient list to avoid sending duplicate messages. See [the mailing list example](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps) for further guidance. + +That's it. You should now be ready to use PHPMailer! + +## Localization +PHPMailer defaults to English, but in the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder you'll find many translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this: + +```php +//To load the French version +$mail->setLanguage('fr', '/optional/path/to/language/directory/'); +``` + +We welcome corrections and new languages – if you're looking for corrections, run the [PHPMailerLangTest.php](https://github.com/PHPMailer/PHPMailer/tree/master/test/PHPMailerLangTest.php) script in the tests folder and it will show any missing translations. + +## Documentation +Start reading at the [GitHub wiki](https://github.com/PHPMailer/PHPMailer/wiki). If you're having trouble, head for [the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting) as it's frequently updated. + +Examples of how to use PHPMailer for common scenarios can be found in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder. If you're looking for a good starting point, we recommend you start with [the Gmail example](https://github.com/PHPMailer/PHPMailer/tree/master/examples/gmail.phps). + +To reduce PHPMailer's deployed code footprint, examples are not included if you load PHPMailer via Composer or via [GitHub's zip file download](https://github.com/PHPMailer/PHPMailer/archive/master.zip), so you'll need to either clone the git repository or use the above links to get to the examples directly. + +Complete generated API documentation is [available online](https://phpmailer.github.io/PHPMailer/). + +You can generate complete API-level documentation by running `phpdoc` in the top-level folder, and documentation will appear in the `docs` folder, though you'll need to have [PHPDocumentor](http://www.phpdoc.org) installed. You may find [the unit tests](https://github.com/PHPMailer/PHPMailer/blob/master/test/PHPMailerTest.php) a good reference for how to do various operations such as encryption. + +If the documentation doesn't cover what you need, search the [many questions on Stack Overflow](http://stackoverflow.com/questions/tagged/phpmailer), and before you ask a question about "SMTP Error: Could not connect to SMTP host.", [read the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting). + +## Tests +[PHPMailer tests](https://github.com/PHPMailer/PHPMailer/tree/master/test/) use PHPUnit 9, with [a polyfill](https://github.com/Yoast/PHPUnit-Polyfills) to let 9-style tests run on older PHPUnit and PHP versions. + +[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions) + +If this isn't passing, is there something you can do to help? + +## Security +Please disclose any vulnerabilities found responsibly – report security issues to the maintainers privately. + +See [SECURITY](https://github.com/PHPMailer/PHPMailer/tree/master/SECURITY.md) and [PHPMailer's security advisories on GitHub](https://github.com/PHPMailer/PHPMailer/security). + +## Contributing +Please submit bug reports, suggestions and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues). + +We're particularly interested in fixing edge-cases, expanding test coverage and updating translations. + +If you found a mistake in the docs, or want to add something, go ahead and amend the wiki – anyone can edit it. + +If you have git clones from prior to the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone: + +```sh +git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git +``` + +Please *don't* use the SourceForge or Google Code projects any more; they are obsolete and no longer maintained. + +## Sponsorship +Development time and resources for PHPMailer are provided by [Smartmessages.net](https://info.smartmessages.net/), the world's only privacy-first email marketing system. + +<a href="https://info.smartmessages.net/"><img src="https://www.smartmessages.net/img/smartmessages-logo.svg" width="550" alt="Smartmessages.net privacy-first email marketing logo"></a> + +Donations are very welcome, whether in beer 🍺, T-shirts 👕, or cold, hard cash 💰. Sponsorship through GitHub is a simple and convenient way to say "thank you" to PHPMailer's maintainers and contributors – just click the "Sponsor" button [on the project page](https://github.com/PHPMailer/PHPMailer). If your company uses PHPMailer, consider taking part in Tidelift's enterprise support programme. + +## PHPMailer For Enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of PHPMailer and thousands of other packages are working with Tidelift to deliver commercial +support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact packages you +use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-phpmailer-phpmailer?utm_source=packagist-phpmailer-phpmailer&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Changelog +See [changelog](changelog.md). + +## History +- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/). +- [Marcus Bointon](https://github.com/Synchro) (`coolbru` on SF) and Andy Prevost (`codeworxtech`) took over the project in 2004. +- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski. +- Marcus created [his fork on GitHub](https://github.com/Synchro/PHPMailer) in 2008. +- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer in 2013. +- PHPMailer moves to [the PHPMailer organisation](https://github.com/PHPMailer) on GitHub in 2013. + +### What's changed since moving from SourceForge? +- Official successor to the SourceForge and Google Code projects. +- Test suite. +- Continuous integration with Github Actions. +- Composer support. +- Public development. +- Additional languages and language strings. +- CRAM-MD5 authentication support. +- Preserves full repo history of authors, commits and branches from the original SourceForge project. diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/SECURITY.md b/php/libraries/composer/vendor/phpmailer/phpmailer/SECURITY.md new file mode 100644 index 0000000..5a6a8f4 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/SECURITY.md @@ -0,0 +1,32 @@ +# Security notices relating to PHPMailer + +Please disclose any security issues or vulnerabilities found through [Tidelift's coordinated disclosure system](https://tidelift.com/security) or to the maintainers privately. + +PHPMailer versions between 6.1.8 and 6.4.0 contain a regression of the earlier CVE-2018-19296 object injection vulnerability as a result of [a fix for Windows UNC paths in 6.1.8](https://github.com/PHPMailer/PHPMailer/commit/e2e07a355ee8ff36aba21d0242c5950c56e4c6f9). Recorded as [CVE-2020-36326](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-36326). Reported by Fariskhi Vidyan via Tidelift. 6.4.1 fixes this issue, and also enforces stricter checks for URL schemes in local path contexts. + +PHPMailer versions 6.1.5 and earlier contain an output escaping bug that occurs in `Content-Type` and `Content-Disposition` when filenames passed into `addAttachment` and other methods that accept attachment names contain double quote characters, in contravention of RFC822 3.4.1. No specific vulnerability has been found relating to this, but it could allow file attachments to bypass attachment filters that are based on matching filename extensions. Recorded as [CVE-2020-13625](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-13625). Reported by Elar Lang of Clarified Security. + +PHPMailer versions prior to 6.0.6 and 5.2.27 are vulnerable to an object injection attack by passing `phar://` paths into `addAttachment()` and other functions that may receive unfiltered local paths, possibly leading to RCE. Recorded as [CVE-2018-19296](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-19296). See [this article](https://knasmueller.net/5-answers-about-php-phar-exploitation) for more info on this type of vulnerability. Mitigated by blocking the use of paths containing URL-protocol style prefixes such as `phar://`. Reported by Sehun Oh of cyberone.kr. + +PHPMailer versions prior to 5.2.24 (released July 26th 2017) have an XSS vulnerability in one of the code examples, [CVE-2017-11503](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-11503). The `code_generator.phps` example did not filter user input prior to output. This file is distributed with a `.phps` extension, so it it not normally executable unless it is explicitly renamed, and the file is not included when PHPMailer is loaded through composer, so it is safe by default. There was also an undisclosed potential XSS vulnerability in the default exception handler (unused by default). Patches for both issues kindly provided by Patrick Monnerat of the Fedora Project. + +PHPMailer versions prior to 5.2.22 (released January 9th 2017) have a local file disclosure vulnerability, [CVE-2017-5223](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-5223). If content passed into `msgHTML()` is sourced from unfiltered user input, relative paths can map to absolute local file paths and added as attachments. Also note that `addAttachment` (just like `file_get_contents`, `passthru`, `unlink`, etc) should not be passed user-sourced params either! Reported by Yongxiang Li of Asiasecurity. + +PHPMailer versions prior to 5.2.20 (released December 28th 2016) are vulnerable to [CVE-2016-10045](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10045) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln-Patch-Bypass.html), and patched by Paul Buonopane (@Zenexer). + +PHPMailer versions prior to 5.2.18 (released December 2016) are vulnerable to [CVE-2016-10033](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10033) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](http://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html). + +PHPMailer versions prior to 5.2.14 (released November 2015) are vulnerable to [CVE-2015-8476](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2015-8476) an SMTP CRLF injection bug permitting arbitrary message sending. + +PHPMailer versions prior to 5.2.10 (released May 2015) are vulnerable to [CVE-2008-5619](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2008-5619), a remote code execution vulnerability in the bundled html2text library. This file was removed in 5.2.10, so if you are using a version prior to that and make use of the html2text function, it's vitally important that you upgrade and remove this file. + +PHPMailer versions prior to 2.0.7 and 2.2.1 are vulnerable to [CVE-2012-0796](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-0796), an email header injection attack. + +Joomla 1.6.0 uses PHPMailer in an unsafe way, allowing it to reveal local file paths, reported in [CVE-2011-3747](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-3747). + +PHPMailer didn't sanitise the `$lang_path` parameter in `SetLanguage`. This wasn't a problem in itself, but some apps (PHPClassifieds, ATutor) also failed to sanitise user-provided parameters passed to it, permitting semi-arbitrary local file inclusion, reported in [CVE-2010-4914](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-4914), [CVE-2007-2021](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2007-2021) and [CVE-2006-5734](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2006-5734). + +PHPMailer 1.7.2 and earlier contained a possible DDoS vulnerability reported in [CVE-2005-1807](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-1807). + +PHPMailer 1.7 and earlier (June 2003) have a possible vulnerability in the `SendmailSend` method where shell commands may not be sanitised. Reported in [CVE-2007-3215](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2007-3215). + diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/VERSION b/php/libraries/composer/vendor/phpmailer/phpmailer/VERSION new file mode 100644 index 0000000..306894a --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/VERSION @@ -0,0 +1 @@ +6.4.1 \ No newline at end of file diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/composer.json b/php/libraries/composer/vendor/phpmailer/phpmailer/composer.json new file mode 100644 index 0000000..58393b2 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/composer.json @@ -0,0 +1,65 @@ +{ + "name": "phpmailer/phpmailer", + "type": "library", + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "require": { + "php": ">=5.5.0", + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.5.6", + "yoast/phpunit-polyfills": "^0.2.0" + }, + "suggest": { + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" + }, + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "PHPMailer\\Test\\": "test/" + } + }, + "license": "LGPL-2.1-only", + "scripts": { + "check": "./vendor/bin/phpcs", + "test": "./vendor/bin/phpunit" + } +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/get_oauth_token.php b/php/libraries/composer/vendor/phpmailer/phpmailer/get_oauth_token.php new file mode 100644 index 0000000..befdc34 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/get_oauth_token.php @@ -0,0 +1,146 @@ +<?php + +/** + * PHPMailer - PHP email creation and transport class. + * PHP Version 5.5 + * @package PHPMailer + * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +/** + * Get an OAuth2 token from an OAuth2 provider. + * * Install this script on your server so that it's accessible + * as [https/http]://<yourdomain>/<folder>/get_oauth_token.php + * e.g.: http://localhost/phpmailer/get_oauth_token.php + * * Ensure dependencies are installed with 'composer install' + * * Set up an app in your Google/Yahoo/Microsoft account + * * Set the script address as the app's redirect URL + * If no refresh token is obtained when running this file, + * revoke access to your app and run the script again. + */ + +namespace PHPMailer\PHPMailer; + +/** + * Aliases for League Provider Classes + * Make sure you have added these to your composer.json and run `composer install` + * Plenty to choose from here: + * @see http://oauth2-client.thephpleague.com/providers/thirdparty/ + */ +//@see https://github.com/thephpleague/oauth2-google +use League\OAuth2\Client\Provider\Google; +//@see https://packagist.org/packages/hayageek/oauth2-yahoo +use Hayageek\OAuth2\Client\Provider\Yahoo; +//@see https://github.com/stevenmaguire/oauth2-microsoft +use Stevenmaguire\OAuth2\Client\Provider\Microsoft; + +if (!isset($_GET['code']) && !isset($_GET['provider'])) { + ?> +<html> +<body>Select Provider:<br> +<a href='?provider=Google'>Google</a><br> +<a href='?provider=Yahoo'>Yahoo</a><br> +<a href='?provider=Microsoft'>Microsoft/Outlook/Hotmail/Live/Office365</a><br> +</body> +</html> + <?php + exit; +} + +require 'vendor/autoload.php'; + +session_start(); + +$providerName = ''; + +if (array_key_exists('provider', $_GET)) { + $providerName = $_GET['provider']; + $_SESSION['provider'] = $providerName; +} elseif (array_key_exists('provider', $_SESSION)) { + $providerName = $_SESSION['provider']; +} +if (!in_array($providerName, ['Google', 'Microsoft', 'Yahoo'])) { + exit('Only Google, Microsoft and Yahoo OAuth2 providers are currently supported in this script.'); +} + +//These details are obtained by setting up an app in the Google developer console, +//or whichever provider you're using. +$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com'; +$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP'; + +//If this automatic URL doesn't work, set it yourself manually to the URL of this script +$redirectUri = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; +//$redirectUri = 'http://localhost/PHPMailer/redirect'; + +$params = [ + 'clientId' => $clientId, + 'clientSecret' => $clientSecret, + 'redirectUri' => $redirectUri, + 'accessType' => 'offline' +]; + +$options = []; +$provider = null; + +switch ($providerName) { + case 'Google': + $provider = new Google($params); + $options = [ + 'scope' => [ + 'https://mail.google.com/' + ] + ]; + break; + case 'Yahoo': + $provider = new Yahoo($params); + break; + case 'Microsoft': + $provider = new Microsoft($params); + $options = [ + 'scope' => [ + 'wl.imap', + 'wl.offline_access' + ] + ]; + break; +} + +if (null === $provider) { + exit('Provider missing'); +} + +if (!isset($_GET['code'])) { + //If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl($options); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + exit; + //Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + unset($_SESSION['oauth2state']); + unset($_SESSION['provider']); + exit('Invalid state'); +} else { + unset($_SESSION['provider']); + //Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken( + 'authorization_code', + [ + 'code' => $_GET['code'] + ] + ); + //Use this to interact with an API on the users behalf + //Use this to get a new access token if the old one expires + echo 'Refresh Token: ', $token->getRefreshToken(); +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-af.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-af.php new file mode 100644 index 0000000..0b2a72d --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-af.php @@ -0,0 +1,26 @@ +<?php + +/** + * Afrikaans PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP-fout: kon nie geverifieer word nie.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon nie aan SMTP-verbind nie.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data nie aanvaar nie.'; +$PHPMAILER_LANG['empty_message'] = 'Boodskapliggaam leeg.'; +$PHPMAILER_LANG['encoding'] = 'Onbekende kodering: '; +$PHPMAILER_LANG['execute'] = 'Kon nie uitvoer nie: '; +$PHPMAILER_LANG['file_access'] = 'Kon nie lêer oopmaak nie: '; +$PHPMAILER_LANG['file_open'] = 'Lêerfout: Kon nie lêer oopmaak nie: '; +$PHPMAILER_LANG['from_failed'] = 'Die volgende Van adres misluk: '; +$PHPMAILER_LANG['instantiate'] = 'Kon nie posfunksie instansieer nie.'; +$PHPMAILER_LANG['invalid_address'] = 'Ongeldige adres: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer word nie ondersteun nie.'; +$PHPMAILER_LANG['provide_address'] = 'U moet ten minste een ontvanger e-pos adres verskaf.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: Die volgende ontvangers het misluk: '; +$PHPMAILER_LANG['signing'] = 'Ondertekening Fout: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP-verbinding () misluk.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP-bediener fout: '; +$PHPMAILER_LANG['variable_set'] = 'Kan nie veranderlike instel of herstel nie: '; +$PHPMAILER_LANG['extension_missing'] = 'Uitbreiding ontbreek: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ar.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ar.php new file mode 100644 index 0000000..8ab485c --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ar.php @@ -0,0 +1,28 @@ +<?php + +/** + * Arabic PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author bahjat al mostafa <bahjat983@hotmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'خطأ SMTP : لا يمكن تأكيد الهوية.'; +$PHPMAILER_LANG['connect_host'] = 'خطأ SMTP: لا يمكن الاتصال بالخادم SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'خطأ SMTP: لم يتم قبول المعلومات .'; +$PHPMAILER_LANG['empty_message'] = 'نص الرسالة فارغ'; +$PHPMAILER_LANG['encoding'] = 'ترميز غير معروف: '; +$PHPMAILER_LANG['execute'] = 'لا يمكن تنفيذ : '; +$PHPMAILER_LANG['file_access'] = 'لا يمكن الوصول للملف: '; +$PHPMAILER_LANG['file_open'] = 'خطأ في الملف: لا يمكن فتحه: '; +$PHPMAILER_LANG['from_failed'] = 'خطأ على مستوى عنوان المرسل : '; +$PHPMAILER_LANG['instantiate'] = 'لا يمكن توفير خدمة البريد.'; +$PHPMAILER_LANG['invalid_address'] = 'الإرسال غير ممكن لأن عنوان البريد الإلكتروني غير صالح: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' برنامج الإرسال غير مدعوم.'; +$PHPMAILER_LANG['provide_address'] = 'يجب توفير عنوان البريد الإلكتروني لمستلم واحد على الأقل.'; +$PHPMAILER_LANG['recipients_failed'] = 'خطأ SMTP: الأخطاء التالية ' . + 'فشل في الارسال لكل من : '; +$PHPMAILER_LANG['signing'] = 'خطأ في التوقيع: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() غير ممكن.'; +$PHPMAILER_LANG['smtp_error'] = 'خطأ على مستوى الخادم SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'لا يمكن تعيين أو إعادة تعيين متغير: '; +$PHPMAILER_LANG['extension_missing'] = 'الإضافة غير موجودة: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-az.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-az.php new file mode 100644 index 0000000..552167e --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-az.php @@ -0,0 +1,27 @@ +<?php + +/** + * Azerbaijani PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author @mirjalal + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP xətası: Giriş uğursuz oldu.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP xətası: SMTP serverinə qoşulma uğursuz oldu.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP xətası: Verilənlər qəbul edilməyib.'; +$PHPMAILER_LANG['empty_message'] = 'Boş mesaj göndərilə bilməz.'; +$PHPMAILER_LANG['encoding'] = 'Qeyri-müəyyən kodlaşdırma: '; +$PHPMAILER_LANG['execute'] = 'Əmr yerinə yetirilmədi: '; +$PHPMAILER_LANG['file_access'] = 'Fayla giriş yoxdur: '; +$PHPMAILER_LANG['file_open'] = 'Fayl xətası: Fayl açıla bilmədi: '; +$PHPMAILER_LANG['from_failed'] = 'Göstərilən poçtlara göndərmə uğursuz oldu: '; +$PHPMAILER_LANG['instantiate'] = 'Mail funksiyası işə salına bilmədi.'; +$PHPMAILER_LANG['invalid_address'] = 'Düzgün olmayan e-mail adresi: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' - e-mail kitabxanası dəstəklənmir.'; +$PHPMAILER_LANG['provide_address'] = 'Ən azı bir e-mail adresi daxil edilməlidir.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP xətası: Aşağıdakı ünvanlar üzrə alıcılara göndərmə uğursuzdur: '; +$PHPMAILER_LANG['signing'] = 'İmzalama xətası: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP serverinə qoşulma uğursuz oldu.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP serveri xətası: '; +$PHPMAILER_LANG['variable_set'] = 'Dəyişənin quraşdırılması uğursuz oldu: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ba.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ba.php new file mode 100644 index 0000000..3694f34 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ba.php @@ -0,0 +1,27 @@ +<?php + +/** + * Bosnian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Ermin Islamagić <ermin@islamagic.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Greška: Neuspjela prijava.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Greška: Nije moguće spojiti se sa SMTP serverom.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Greška: Podatci nisu prihvaćeni.'; +$PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznata kriptografija: '; +$PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; +$PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; +$PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP Greška: Slanje sa navedenih e-mail adresa nije uspjelo: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Greška: Slanje na navedene e-mail adrese nije uspjelo: '; +$PHPMAILER_LANG['instantiate'] = 'Ne mogu pokrenuti mail funkcionalnost.'; +$PHPMAILER_LANG['invalid_address'] = 'E-mail nije poslan. Neispravna e-mail adresa: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer nije podržan.'; +$PHPMAILER_LANG['provide_address'] = 'Definišite barem jednu adresu primaoca.'; +$PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Spajanje na SMTP server nije uspjelo.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP greška: '; +$PHPMAILER_LANG['variable_set'] = 'Nije moguće postaviti varijablu ili je vratiti nazad: '; +$PHPMAILER_LANG['extension_missing'] = 'Nedostaje ekstenzija: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-be.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-be.php new file mode 100644 index 0000000..9e92dda --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-be.php @@ -0,0 +1,27 @@ +<?php + +/** + * Belarusian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Aleksander Maksymiuk <info@setpro.pl> + */ + +$PHPMAILER_LANG['authenticate'] = 'Памылка SMTP: памылка ідэнтыфікацыі.'; +$PHPMAILER_LANG['connect_host'] = 'Памылка SMTP: нельга ўстанавіць сувязь з SMTP-серверам.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Памылка SMTP: звесткі непрынятыя.'; +$PHPMAILER_LANG['empty_message'] = 'Пустое паведамленне.'; +$PHPMAILER_LANG['encoding'] = 'Невядомая кадыроўка тэксту: '; +$PHPMAILER_LANG['execute'] = 'Нельга выканаць каманду: '; +$PHPMAILER_LANG['file_access'] = 'Няма доступу да файла: '; +$PHPMAILER_LANG['file_open'] = 'Нельга адкрыць файл: '; +$PHPMAILER_LANG['from_failed'] = 'Няправільны адрас адпраўніка: '; +$PHPMAILER_LANG['instantiate'] = 'Нельга прымяніць функцыю mail().'; +$PHPMAILER_LANG['invalid_address'] = 'Нельга даслаць паведамленне, няправільны email атрымальніка: '; +$PHPMAILER_LANG['provide_address'] = 'Запоўніце, калі ласка, правільны email атрымальніка.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' - паштовы сервер не падтрымліваецца.'; +$PHPMAILER_LANG['recipients_failed'] = 'Памылка SMTP: няправільныя атрымальнікі: '; +$PHPMAILER_LANG['signing'] = 'Памылка подпісу паведамлення: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Памылка сувязі з SMTP-серверам.'; +$PHPMAILER_LANG['smtp_error'] = 'Памылка SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Нельга ўстанавіць або перамяніць значэнне пераменнай: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-bg.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-bg.php new file mode 100644 index 0000000..c41f675 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-bg.php @@ -0,0 +1,27 @@ +<?php + +/** + * Bulgarian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Mikhail Kyosev <mialygk@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP грешка: Не може да се удостовери пред сървъра.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP грешка: Не може да се свърже с SMTP хоста.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP грешка: данните не са приети.'; +$PHPMAILER_LANG['empty_message'] = 'Съдържанието на съобщението е празно'; +$PHPMAILER_LANG['encoding'] = 'Неизвестно кодиране: '; +$PHPMAILER_LANG['execute'] = 'Не може да се изпълни: '; +$PHPMAILER_LANG['file_access'] = 'Няма достъп до файл: '; +$PHPMAILER_LANG['file_open'] = 'Файлова грешка: Не може да се отвори файл: '; +$PHPMAILER_LANG['from_failed'] = 'Следните адреси за подател са невалидни: '; +$PHPMAILER_LANG['instantiate'] = 'Не може да се инстанцира функцията mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Невалиден адрес: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' - пощенски сървър не се поддържа.'; +$PHPMAILER_LANG['provide_address'] = 'Трябва да предоставите поне един email адрес за получател.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP грешка: Следните адреси за Получател са невалидни: '; +$PHPMAILER_LANG['signing'] = 'Грешка при подписване: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP провален connect().'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP сървърна грешка: '; +$PHPMAILER_LANG['variable_set'] = 'Не може да се установи или възстанови променлива: '; +$PHPMAILER_LANG['extension_missing'] = 'Липсва разширение: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ca.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ca.php new file mode 100644 index 0000000..3468485 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ca.php @@ -0,0 +1,27 @@ +<?php + +/** + * Catalan PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Ivan <web AT microstudi DOT com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Error SMTP: No s’ha pogut autenticar.'; +$PHPMAILER_LANG['connect_host'] = 'Error SMTP: No es pot connectar al servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Dades no acceptades.'; +$PHPMAILER_LANG['empty_message'] = 'El cos del missatge està buit.'; +$PHPMAILER_LANG['encoding'] = 'Codificació desconeguda: '; +$PHPMAILER_LANG['execute'] = 'No es pot executar: '; +$PHPMAILER_LANG['file_access'] = 'No es pot accedir a l’arxiu: '; +$PHPMAILER_LANG['file_open'] = 'Error d’Arxiu: No es pot obrir l’arxiu: '; +$PHPMAILER_LANG['from_failed'] = 'La(s) següent(s) adreces de remitent han fallat: '; +$PHPMAILER_LANG['instantiate'] = 'No s’ha pogut crear una instància de la funció Mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Adreça d’email invalida: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer no està suportat'; +$PHPMAILER_LANG['provide_address'] = 'S’ha de proveir almenys una adreça d’email com a destinatari.'; +$PHPMAILER_LANG['recipients_failed'] = 'Error SMTP: Els següents destinataris han fallat: '; +$PHPMAILER_LANG['signing'] = 'Error al signar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ha fallat el SMTP Connect().'; +$PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'No s’ha pogut establir o restablir la variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ch.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ch.php new file mode 100644 index 0000000..500c952 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ch.php @@ -0,0 +1,27 @@ +<?php + +/** + * Chinese PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author LiuXin <http://www.80x86.cn/blog/> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 错误:身份验证失败。'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 错误: 不能连接SMTP主机。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 错误: 数据不可接受。'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = '未知编码:'; +$PHPMAILER_LANG['execute'] = '不能执行: '; +$PHPMAILER_LANG['file_access'] = '不能访问文件:'; +$PHPMAILER_LANG['file_open'] = '文件错误:不能打开文件:'; +$PHPMAILER_LANG['from_failed'] = '下面的发送地址邮件发送失败了: '; +$PHPMAILER_LANG['instantiate'] = '不能实现mail方法。'; +//$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' 您所选择的发送邮件的方法并不支持。'; +$PHPMAILER_LANG['provide_address'] = '您必须提供至少一个 收信人的email地址。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 错误: 下面的 收件人失败了: '; +//$PHPMAILER_LANG['signing'] = 'Signing Error: '; +//$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +//$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; +//$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-cs.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-cs.php new file mode 100644 index 0000000..e770a1a --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-cs.php @@ -0,0 +1,28 @@ +<?php + +/** + * Czech PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'Chyba SMTP: Autentizace selhala.'; +$PHPMAILER_LANG['connect_host'] = 'Chyba SMTP: Nelze navázat spojení se SMTP serverem.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Chyba SMTP: Data nebyla přijata.'; +$PHPMAILER_LANG['empty_message'] = 'Prázdné tělo zprávy'; +$PHPMAILER_LANG['encoding'] = 'Neznámé kódování: '; +$PHPMAILER_LANG['execute'] = 'Nelze provést: '; +$PHPMAILER_LANG['file_access'] = 'Nelze získat přístup k souboru: '; +$PHPMAILER_LANG['file_open'] = 'Chyba souboru: Nelze otevřít soubor pro čtení: '; +$PHPMAILER_LANG['from_failed'] = 'Následující adresa odesílatele je nesprávná: '; +$PHPMAILER_LANG['instantiate'] = 'Nelze vytvořit instanci emailové funkce.'; +$PHPMAILER_LANG['invalid_address'] = 'Neplatná adresa: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Záznam hostitele je nesprávný: '; +$PHPMAILER_LANG['invalid_host'] = 'Hostitel je nesprávný: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer není podporován.'; +$PHPMAILER_LANG['provide_address'] = 'Musíte zadat alespoň jednu emailovou adresu příjemce.'; +$PHPMAILER_LANG['recipients_failed'] = 'Chyba SMTP: Následující adresy příjemců nejsou správně: '; +$PHPMAILER_LANG['signing'] = 'Chyba přihlašování: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() selhal.'; +$PHPMAILER_LANG['smtp_error'] = 'Chyba SMTP serveru: '; +$PHPMAILER_LANG['variable_set'] = 'Nelze nastavit nebo změnit proměnnou: '; +$PHPMAILER_LANG['extension_missing'] = 'Chybí rozšíření: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-da.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-da.php new file mode 100644 index 0000000..1edba1d --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-da.php @@ -0,0 +1,29 @@ +<?php + +/** + * Danish PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author John Sebastian <jms@iwb.dk> + * Rewrite and extension of the work by Mikael Stokkebro <info@stokkebro.dk> + * + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP fejl: Login mislykkedes.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP fejl: Forbindelse til SMTP serveren kunne ikke oprettes.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP fejl: Data blev ikke accepteret.'; +$PHPMAILER_LANG['empty_message'] = 'Meddelelsen er uden indhold'; +$PHPMAILER_LANG['encoding'] = 'Ukendt encode-format: '; +$PHPMAILER_LANG['execute'] = 'Kunne ikke afvikle: '; +$PHPMAILER_LANG['file_access'] = 'Kunne ikke tilgå filen: '; +$PHPMAILER_LANG['file_open'] = 'Fil fejl: Kunne ikke åbne filen: '; +$PHPMAILER_LANG['from_failed'] = 'Følgende afsenderadresse er forkert: '; +$PHPMAILER_LANG['instantiate'] = 'Email funktionen kunne ikke initialiseres.'; +$PHPMAILER_LANG['invalid_address'] = 'Udgyldig adresse: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer understøttes ikke.'; +$PHPMAILER_LANG['provide_address'] = 'Indtast mindst en modtagers email adresse.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP fejl: Følgende modtagere er forkerte: '; +$PHPMAILER_LANG['signing'] = 'Signeringsfejl: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fejlede.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP server fejl: '; +$PHPMAILER_LANG['variable_set'] = 'Kunne ikke definere eller nulstille variablen: '; +$PHPMAILER_LANG['extension_missing'] = 'Udvidelse mangler: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-de.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-de.php new file mode 100644 index 0000000..e7e59d2 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-de.php @@ -0,0 +1,28 @@ +<?php + +/** + * German PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP-Fehler: Konnte keine Verbindung zum SMTP-Host herstellen.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-Fehler: Daten werden nicht akzeptiert.'; +$PHPMAILER_LANG['empty_message'] = 'E-Mail-Inhalt ist leer.'; +$PHPMAILER_LANG['encoding'] = 'Unbekannte Kodierung: '; +$PHPMAILER_LANG['execute'] = 'Konnte folgenden Befehl nicht ausführen: '; +$PHPMAILER_LANG['file_access'] = 'Zugriff auf folgende Datei fehlgeschlagen: '; +$PHPMAILER_LANG['file_open'] = 'Dateifehler: Konnte folgende Datei nicht öffnen: '; +$PHPMAILER_LANG['from_failed'] = 'Die folgende Absenderadresse ist nicht korrekt: '; +$PHPMAILER_LANG['instantiate'] = 'Mail-Funktion konnte nicht initialisiert werden.'; +$PHPMAILER_LANG['invalid_address'] = 'Die Adresse ist ungültig: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Ungültiger Hosteintrag: '; +$PHPMAILER_LANG['invalid_host'] = 'Ungültiger Host: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer wird nicht unterstützt.'; +$PHPMAILER_LANG['provide_address'] = 'Bitte geben Sie mindestens eine Empfängeradresse an.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP-Fehler: Die folgenden Empfänger sind nicht korrekt: '; +$PHPMAILER_LANG['signing'] = 'Fehler beim Signieren: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Verbindung zum SMTP-Server fehlgeschlagen.'; +$PHPMAILER_LANG['smtp_error'] = 'Fehler vom SMTP-Server: '; +$PHPMAILER_LANG['variable_set'] = 'Kann Variable nicht setzen oder zurücksetzen: '; +$PHPMAILER_LANG['extension_missing'] = 'Fehlende Erweiterung: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-el.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-el.php new file mode 100644 index 0000000..b3d5ca9 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-el.php @@ -0,0 +1,26 @@ +<?php + +/** + * Greek PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Σφάλμα: Αδυναμία πιστοποίησης (authentication).'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Σφάλμα: Αδυναμία σύνδεσης στον SMTP-Host.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Σφάλμα: Τα δεδομένα δεν έγιναν αποδεκτά.'; +$PHPMAILER_LANG['empty_message'] = 'Το E-Mail δεν έχει περιεχόμενο .'; +$PHPMAILER_LANG['encoding'] = 'Αγνωστο Encoding-Format: '; +$PHPMAILER_LANG['execute'] = 'Αδυναμία εκτέλεσης ακόλουθης εντολής: '; +$PHPMAILER_LANG['file_access'] = 'Αδυναμία προσπέλασης του αρχείου: '; +$PHPMAILER_LANG['file_open'] = 'Σφάλμα Αρχείου: Δεν είναι δυνατό το άνοιγμα του ακόλουθου αρχείου: '; +$PHPMAILER_LANG['from_failed'] = 'Η παρακάτω διεύθυνση αποστολέα δεν είναι σωστή: '; +$PHPMAILER_LANG['instantiate'] = 'Αδυναμία εκκίνησης Mail function.'; +$PHPMAILER_LANG['invalid_address'] = 'Το μήνυμα δεν εστάλη, η διεύθυνση δεν είναι έγκυρη: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer δεν υποστηρίζεται.'; +$PHPMAILER_LANG['provide_address'] = 'Παρακαλούμε δώστε τουλάχιστον μια e-mail διεύθυνση παραλήπτη.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Σφάλμα: Οι παρακάτω διευθύνσεις παραλήπτη δεν είναι έγκυρες: '; +$PHPMAILER_LANG['signing'] = 'Σφάλμα υπογραφής: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Αποτυχία σύνδεσης στον SMTP Server.'; +$PHPMAILER_LANG['smtp_error'] = 'Σφάλμα από τον SMTP Server: '; +$PHPMAILER_LANG['variable_set'] = 'Αδυναμία ορισμού ή αρχικοποίησης μεταβλητής: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-eo.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-eo.php new file mode 100644 index 0000000..fa8c2c1 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-eo.php @@ -0,0 +1,26 @@ +<?php + +/** + * Esperanto PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'Eraro de servilo SMTP : aŭtentigo malsukcesis.'; +$PHPMAILER_LANG['connect_host'] = 'Eraro de servilo SMTP : konektado al servilo malsukcesis.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Eraro de servilo SMTP : neĝustaj datumoj.'; +$PHPMAILER_LANG['empty_message'] = 'Teksto de mesaĝo mankas.'; +$PHPMAILER_LANG['encoding'] = 'Nekonata kodoprezento: '; +$PHPMAILER_LANG['execute'] = 'Lanĉi rulumadon ne eblis: '; +$PHPMAILER_LANG['file_access'] = 'Aliro al dosiero ne sukcesis: '; +$PHPMAILER_LANG['file_open'] = 'Eraro de dosiero: malfermo neeblas: '; +$PHPMAILER_LANG['from_failed'] = 'Jena adreso de sendinto malsukcesis: '; +$PHPMAILER_LANG['instantiate'] = 'Genero de retmesaĝa funkcio neeblis.'; +$PHPMAILER_LANG['invalid_address'] = 'Retadreso ne validas: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mesaĝilo ne subtenata.'; +$PHPMAILER_LANG['provide_address'] = 'Vi devas tajpi almenaŭ unu recevontan retadreson.'; +$PHPMAILER_LANG['recipients_failed'] = 'Eraro de servilo SMTP : la jenaj poŝtrecivuloj kaŭzis eraron: '; +$PHPMAILER_LANG['signing'] = 'Eraro de subskribo: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP konektado malsukcesis.'; +$PHPMAILER_LANG['smtp_error'] = 'Eraro de servilo SMTP : '; +$PHPMAILER_LANG['variable_set'] = 'Variablo ne pravalorizeblas aŭ ne repravalorizeblas: '; +$PHPMAILER_LANG['extension_missing'] = 'Mankas etendo: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-es.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-es.php new file mode 100644 index 0000000..6ba7462 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-es.php @@ -0,0 +1,27 @@ +<?php + +/** + * Spanish PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Matt Sturdy <matt.sturdy@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Error SMTP: Imposible autentificar.'; +$PHPMAILER_LANG['connect_host'] = 'Error SMTP: Imposible conectar al servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Datos no aceptados.'; +$PHPMAILER_LANG['empty_message'] = 'El cuerpo del mensaje está vacío.'; +$PHPMAILER_LANG['encoding'] = 'Codificación desconocida: '; +$PHPMAILER_LANG['execute'] = 'Imposible ejecutar: '; +$PHPMAILER_LANG['file_access'] = 'Imposible acceder al archivo: '; +$PHPMAILER_LANG['file_open'] = 'Error de Archivo: Imposible abrir el archivo: '; +$PHPMAILER_LANG['from_failed'] = 'La(s) siguiente(s) direcciones de remitente fallaron: '; +$PHPMAILER_LANG['instantiate'] = 'Imposible crear una instancia de la función Mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Imposible enviar: dirección de email inválido: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer no está soportado.'; +$PHPMAILER_LANG['provide_address'] = 'Debe proporcionar al menos una dirección de email de destino.'; +$PHPMAILER_LANG['recipients_failed'] = 'Error SMTP: Los siguientes destinos fallaron: '; +$PHPMAILER_LANG['signing'] = 'Error al firmar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falló.'; +$PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'No se pudo configurar la variable: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensión faltante: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-et.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-et.php new file mode 100644 index 0000000..93addc9 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-et.php @@ -0,0 +1,28 @@ +<?php + +/** + * Estonian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Indrek Päri + * @author Elan Ruusamäe <glen@delfi.ee> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Viga: Autoriseerimise viga.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Viga: Ei õnnestunud luua ühendust SMTP serveriga.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Viga: Vigased andmed.'; +$PHPMAILER_LANG['empty_message'] = 'Tühi kirja sisu'; +$PHPMAILER_LANG["encoding"] = 'Tundmatu kodeering: '; +$PHPMAILER_LANG['execute'] = 'Tegevus ebaõnnestus: '; +$PHPMAILER_LANG['file_access'] = 'Pole piisavalt õiguseid järgneva faili avamiseks: '; +$PHPMAILER_LANG['file_open'] = 'Faili Viga: Faili avamine ebaõnnestus: '; +$PHPMAILER_LANG['from_failed'] = 'Järgnev saatja e-posti aadress on vigane: '; +$PHPMAILER_LANG['instantiate'] = 'mail funktiooni käivitamine ebaõnnestus.'; +$PHPMAILER_LANG['invalid_address'] = 'Saatmine peatatud, e-posti address vigane: '; +$PHPMAILER_LANG['provide_address'] = 'Te peate määrama vähemalt ühe saaja e-posti aadressi.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' maileri tugi puudub.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Viga: Järgnevate saajate e-posti aadressid on vigased: '; +$PHPMAILER_LANG["signing"] = 'Viga allkirjastamisel: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() ebaõnnestus.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP serveri viga: '; +$PHPMAILER_LANG['variable_set'] = 'Ei õnnestunud määrata või lähtestada muutujat: '; +$PHPMAILER_LANG['extension_missing'] = 'Nõutud laiendus on puudu: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fa.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fa.php new file mode 100644 index 0000000..295a47f --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fa.php @@ -0,0 +1,28 @@ +<?php + +/** + * Persian/Farsi PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Ali Jazayeri <jaza.ali@gmail.com> + * @author Mohammad Hossein Mojtahedi <mhm5000@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'خطای SMTP: احراز هویت با شکست مواجه شد.'; +$PHPMAILER_LANG['connect_host'] = 'خطای SMTP: اتصال به سرور SMTP برقرار نشد.'; +$PHPMAILER_LANG['data_not_accepted'] = 'خطای SMTP: داده‌ها نا‌درست هستند.'; +$PHPMAILER_LANG['empty_message'] = 'بخش متن پیام خالی است.'; +$PHPMAILER_LANG['encoding'] = 'کد‌گذاری نا‌شناخته: '; +$PHPMAILER_LANG['execute'] = 'امکان اجرا وجود ندارد: '; +$PHPMAILER_LANG['file_access'] = 'امکان دسترسی به فایل وجود ندارد: '; +$PHPMAILER_LANG['file_open'] = 'خطای File: امکان بازکردن فایل وجود ندارد: '; +$PHPMAILER_LANG['from_failed'] = 'آدرس فرستنده اشتباه است: '; +$PHPMAILER_LANG['instantiate'] = 'امکان معرفی تابع ایمیل وجود ندارد.'; +$PHPMAILER_LANG['invalid_address'] = 'آدرس ایمیل معتبر نیست: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer پشتیبانی نمی‌شود.'; +$PHPMAILER_LANG['provide_address'] = 'باید حداقل یک آدرس گیرنده وارد کنید.'; +$PHPMAILER_LANG['recipients_failed'] = 'خطای SMTP: ارسال به آدرس گیرنده با خطا مواجه شد: '; +$PHPMAILER_LANG['signing'] = 'خطا در امضا: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'خطا در اتصال به SMTP.'; +$PHPMAILER_LANG['smtp_error'] = 'خطا در SMTP Server: '; +$PHPMAILER_LANG['variable_set'] = 'امکان ارسال یا ارسال مجدد متغیر‌ها وجود ندارد: '; +$PHPMAILER_LANG['extension_missing'] = 'افزونه موجود نیست: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fi.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fi.php new file mode 100644 index 0000000..243c054 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fi.php @@ -0,0 +1,28 @@ +<?php + +/** + * Finnish PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Jyry Kuukanen + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP-virhe: käyttäjätunnistus epäonnistui.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP-virhe: yhteys palvelimeen ei onnistu.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-virhe: data on virheellinen.'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = 'Tuntematon koodaustyyppi: '; +$PHPMAILER_LANG['execute'] = 'Suoritus epäonnistui: '; +$PHPMAILER_LANG['file_access'] = 'Seuraavaan tiedostoon ei ole oikeuksia: '; +$PHPMAILER_LANG['file_open'] = 'Tiedostovirhe: Ei voida avata tiedostoa: '; +$PHPMAILER_LANG['from_failed'] = 'Seuraava lähettäjän osoite on virheellinen: '; +$PHPMAILER_LANG['instantiate'] = 'mail-funktion luonti epäonnistui.'; +//$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; +$PHPMAILER_LANG['mailer_not_supported'] = 'postivälitintyyppiä ei tueta.'; +$PHPMAILER_LANG['provide_address'] = 'Aseta vähintään yksi vastaanottajan sähköpostiosoite.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP-virhe: seuraava vastaanottaja osoite on virheellinen.'; +$PHPMAILER_LANG['encoding'] = 'Tuntematon koodaustyyppi: '; +//$PHPMAILER_LANG['signing'] = 'Signing Error: '; +//$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +//$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; +//$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fo.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fo.php new file mode 100644 index 0000000..b30f052 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fo.php @@ -0,0 +1,27 @@ +<?php + +/** + * Faroese PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Dávur Sørensen <http://www.profo-webdesign.dk> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP feilur: Kundi ikki góðkenna.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP feilur: Kundi ikki knýta samband við SMTP vert.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP feilur: Data ikki góðkent.'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = 'Ókend encoding: '; +$PHPMAILER_LANG['execute'] = 'Kundi ikki útføra: '; +$PHPMAILER_LANG['file_access'] = 'Kundi ikki tilganga fílu: '; +$PHPMAILER_LANG['file_open'] = 'Fílu feilur: Kundi ikki opna fílu: '; +$PHPMAILER_LANG['from_failed'] = 'fylgjandi Frá/From adressa miseydnaðist: '; +$PHPMAILER_LANG['instantiate'] = 'Kuni ikki instantiera mail funktión.'; +//$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' er ikki supporterað.'; +$PHPMAILER_LANG['provide_address'] = 'Tú skal uppgeva minst móttakara-emailadressu(r).'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Feilur: Fylgjandi móttakarar miseydnaðust: '; +//$PHPMAILER_LANG['signing'] = 'Signing Error: '; +//$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +//$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; +//$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fr.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fr.php new file mode 100644 index 0000000..b57f0ec --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-fr.php @@ -0,0 +1,32 @@ +<?php + +/** + * French PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * Some French punctuation requires a thin non-breaking space (U+202F) character before it, + * for example before a colon or exclamation mark. + * There is one of these characters between these quotes: " " + * @see http://unicode.org/udhr/n/notes_fra.html + */ + +$PHPMAILER_LANG['authenticate'] = 'Erreur SMTP : échec de l\'authentification.'; +$PHPMAILER_LANG['connect_host'] = 'Erreur SMTP : impossible de se connecter au serveur SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erreur SMTP : données incorrectes.'; +$PHPMAILER_LANG['empty_message'] = 'Corps du message vide.'; +$PHPMAILER_LANG['encoding'] = 'Encodage inconnu : '; +$PHPMAILER_LANG['execute'] = 'Impossible de lancer l\'exécution : '; +$PHPMAILER_LANG['file_access'] = 'Impossible d\'accéder au fichier : '; +$PHPMAILER_LANG['file_open'] = 'Ouverture du fichier impossible : '; +$PHPMAILER_LANG['from_failed'] = 'L\'adresse d\'expéditeur suivante a échoué : '; +$PHPMAILER_LANG['instantiate'] = 'Impossible d\'instancier la fonction mail.'; +$PHPMAILER_LANG['invalid_address'] = 'L\'adresse courriel n\'est pas valide : '; +$PHPMAILER_LANG['invalid_hostentry'] = 'L\'entrée hôte n\'est pas valide : '; +$PHPMAILER_LANG['invalid_host'] = 'L\'hôte n\'est pas valide : '; +$PHPMAILER_LANG['mailer_not_supported'] = ' client de messagerie non supporté.'; +$PHPMAILER_LANG['provide_address'] = 'Vous devez fournir au moins une adresse de destinataire.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erreur SMTP : les destinataires suivants sont en erreur : '; +$PHPMAILER_LANG['signing'] = 'Erreur de signature : '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Échec de la connexion SMTP.'; +$PHPMAILER_LANG['smtp_error'] = 'Erreur du serveur SMTP : '; +$PHPMAILER_LANG['variable_set'] = 'Impossible d\'initialiser ou de réinitialiser une variable : '; +$PHPMAILER_LANG['extension_missing'] = 'Extension manquante : '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-gl.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-gl.php new file mode 100644 index 0000000..3f3ab37 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-gl.php @@ -0,0 +1,27 @@ +<?php + +/** + * Galician PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author by Donato Rouco <donatorouco@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Erro SMTP: Non puido ser autentificado.'; +$PHPMAILER_LANG['connect_host'] = 'Erro SMTP: Non puido conectar co servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erro SMTP: Datos non aceptados.'; +$PHPMAILER_LANG['empty_message'] = 'Corpo da mensaxe vacía'; +$PHPMAILER_LANG['encoding'] = 'Codificación descoñecida: '; +$PHPMAILER_LANG['execute'] = 'Non puido ser executado: '; +$PHPMAILER_LANG['file_access'] = 'Nob puido acceder ó arquivo: '; +$PHPMAILER_LANG['file_open'] = 'Erro de Arquivo: No puido abrir o arquivo: '; +$PHPMAILER_LANG['from_failed'] = 'A(s) seguinte(s) dirección(s) de remitente(s) deron erro: '; +$PHPMAILER_LANG['instantiate'] = 'Non puido crear unha instancia da función Mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Non puido envia-lo correo: dirección de email inválida: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer non está soportado.'; +$PHPMAILER_LANG['provide_address'] = 'Debe engadir polo menos unha dirección de email coma destino.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erro SMTP: Os seguintes destinos fallaron: '; +$PHPMAILER_LANG['signing'] = 'Erro ó firmar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fallou.'; +$PHPMAILER_LANG['smtp_error'] = 'Erro do servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Non puidemos axustar ou reaxustar a variábel: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-he.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-he.php new file mode 100644 index 0000000..b123aa5 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-he.php @@ -0,0 +1,27 @@ +<?php + +/** + * Hebrew PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Ronny Sherer <ronny@hoojima.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'שגיאת SMTP: פעולת האימות נכשלה.'; +$PHPMAILER_LANG['connect_host'] = 'שגיאת SMTP: לא הצלחתי להתחבר לשרת SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'שגיאת SMTP: מידע לא התקבל.'; +$PHPMAILER_LANG['empty_message'] = 'גוף ההודעה ריק'; +$PHPMAILER_LANG['invalid_address'] = 'כתובת שגויה: '; +$PHPMAILER_LANG['encoding'] = 'קידוד לא מוכר: '; +$PHPMAILER_LANG['execute'] = 'לא הצלחתי להפעיל את: '; +$PHPMAILER_LANG['file_access'] = 'לא ניתן לגשת לקובץ: '; +$PHPMAILER_LANG['file_open'] = 'שגיאת קובץ: לא ניתן לגשת לקובץ: '; +$PHPMAILER_LANG['from_failed'] = 'כתובות הנמענים הבאות נכשלו: '; +$PHPMAILER_LANG['instantiate'] = 'לא הצלחתי להפעיל את פונקציית המייל.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' אינה נתמכת.'; +$PHPMAILER_LANG['provide_address'] = 'חובה לספק לפחות כתובת אחת של מקבל המייל.'; +$PHPMAILER_LANG['recipients_failed'] = 'שגיאת SMTP: הנמענים הבאים נכשלו: '; +$PHPMAILER_LANG['signing'] = 'שגיאת חתימה: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +$PHPMAILER_LANG['smtp_error'] = 'שגיאת שרת SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'לא ניתן לקבוע או לשנות את המשתנה: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hi.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hi.php new file mode 100644 index 0000000..d973a35 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hi.php @@ -0,0 +1,27 @@ +<?php + +/** + * Hindi PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Yash Karanke <mr.karanke@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP त्रुटि: प्रामाणिकता की जांच नहीं हो सका। '; +$PHPMAILER_LANG['connect_host'] = 'SMTP त्रुटि: SMTP सर्वर से कनेक्ट नहीं हो सका। '; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP त्रुटि: डेटा स्वीकार नहीं किया जाता है। '; +$PHPMAILER_LANG['empty_message'] = 'संदेश खाली है। '; +$PHPMAILER_LANG['encoding'] = 'अज्ञात एन्कोडिंग प्रकार। '; +$PHPMAILER_LANG['execute'] = 'आदेश को निष्पादित करने में विफल। '; +$PHPMAILER_LANG['file_access'] = 'फ़ाइल उपलब्ध नहीं है। '; +$PHPMAILER_LANG['file_open'] = 'फ़ाइल त्रुटि: फाइल को खोला नहीं जा सका। '; +$PHPMAILER_LANG['from_failed'] = 'प्रेषक का पता गलत है। '; +$PHPMAILER_LANG['instantiate'] = 'मेल फ़ंक्शन कॉल नहीं कर सकता है।'; +$PHPMAILER_LANG['invalid_address'] = 'पता गलत है। '; +$PHPMAILER_LANG['mailer_not_supported'] = 'मेल सर्वर के साथ काम नहीं करता है। '; +$PHPMAILER_LANG['provide_address'] = 'आपको कम से कम एक प्राप्तकर्ता का ई-मेल पता प्रदान करना होगा।'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP त्रुटि: निम्न प्राप्तकर्ताओं को पते भेजने में विफल। '; +$PHPMAILER_LANG['signing'] = 'साइनअप त्रुटि:। '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP का connect () फ़ंक्शन विफल हुआ। '; +$PHPMAILER_LANG['smtp_error'] = 'SMTP सर्वर त्रुटि। '; +$PHPMAILER_LANG['variable_set'] = 'चर को बना या संशोधित नहीं किया जा सकता। '; +$PHPMAILER_LANG['extension_missing'] = 'एक्सटेन्षन गायब है: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hr.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hr.php new file mode 100644 index 0000000..cacb6c3 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hr.php @@ -0,0 +1,27 @@ +<?php + +/** + * Croatian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Hrvoj3e <hrvoj3e@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Greška: Neuspjela autentikacija.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Greška: Ne mogu se spojiti na SMTP poslužitelj.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Greška: Podatci nisu prihvaćeni.'; +$PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznati encoding: '; +$PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; +$PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; +$PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP Greška: Slanje s navedenih e-mail adresa nije uspjelo: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Greška: Slanje na navedenih e-mail adresa nije uspjelo: '; +$PHPMAILER_LANG['instantiate'] = 'Ne mogu pokrenuti mail funkcionalnost.'; +$PHPMAILER_LANG['invalid_address'] = 'E-mail nije poslan. Neispravna e-mail adresa: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer nije podržan.'; +$PHPMAILER_LANG['provide_address'] = 'Definirajte barem jednu adresu primatelja.'; +$PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Spajanje na SMTP poslužitelj nije uspjelo.'; +$PHPMAILER_LANG['smtp_error'] = 'Greška SMTP poslužitelja: '; +$PHPMAILER_LANG['variable_set'] = 'Ne mogu postaviti varijablu niti ju vratiti nazad: '; +$PHPMAILER_LANG['extension_missing'] = 'Nedostaje proširenje: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hu.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hu.php new file mode 100644 index 0000000..e6b58b0 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hu.php @@ -0,0 +1,27 @@ +<?php + +/** + * Hungarian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author @dominicus-75 + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP hiba: az azonosítás sikertelen.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP hiba: nem lehet kapcsolódni az SMTP-szerverhez.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP hiba: adatok visszautasítva.'; +$PHPMAILER_LANG['empty_message'] = 'Üres az üzenettörzs.'; +$PHPMAILER_LANG['encoding'] = 'Ismeretlen kódolás: '; +$PHPMAILER_LANG['execute'] = 'Nem lehet végrehajtani: '; +$PHPMAILER_LANG['file_access'] = 'A következő fájl nem elérhető: '; +$PHPMAILER_LANG['file_open'] = 'Fájl hiba: a következő fájlt nem lehet megnyitni: '; +$PHPMAILER_LANG['from_failed'] = 'A feladóként megadott következő cím hibás: '; +$PHPMAILER_LANG['instantiate'] = 'A PHP mail() függvényt nem sikerült végrehajtani.'; +$PHPMAILER_LANG['invalid_address'] = 'Érvénytelen cím: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' a mailer-osztály nem támogatott.'; +$PHPMAILER_LANG['provide_address'] = 'Legalább egy címzettet fel kell tüntetni.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP hiba: a címzettként megadott következő címek hibásak: '; +$PHPMAILER_LANG['signing'] = 'Hibás aláírás: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Hiba az SMTP-kapcsolatban.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP-szerver hiba: '; +$PHPMAILER_LANG['variable_set'] = 'A következő változók beállítása nem sikerült: '; +$PHPMAILER_LANG['extension_missing'] = 'Bővítmény hiányzik: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hy.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hy.php new file mode 100644 index 0000000..bb05d2d --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-hy.php @@ -0,0 +1,27 @@ +<?php + +/** + * Armenian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Hrayr Grigoryan <hrayr@bits.am> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP -ի սխալ: չհաջողվեց ստուգել իսկությունը.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP -ի սխալ: չհաջողվեց կապ հաստատել SMTP սերվերի հետ.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP -ի սխալ: տվյալները ընդունված չեն.'; +$PHPMAILER_LANG['empty_message'] = 'Հաղորդագրությունը դատարկ է'; +$PHPMAILER_LANG['encoding'] = 'Կոդավորման անհայտ տեսակ: '; +$PHPMAILER_LANG['execute'] = 'Չհաջողվեց իրականացնել հրամանը: '; +$PHPMAILER_LANG['file_access'] = 'Ֆայլը հասանելի չէ: '; +$PHPMAILER_LANG['file_open'] = 'Ֆայլի սխալ: ֆայլը չհաջողվեց բացել: '; +$PHPMAILER_LANG['from_failed'] = 'Ուղարկողի հետևյալ հասցեն սխալ է: '; +$PHPMAILER_LANG['instantiate'] = 'Հնարավոր չէ կանչել mail ֆունկցիան.'; +$PHPMAILER_LANG['invalid_address'] = 'Հասցեն սխալ է: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' փոստային սերվերի հետ չի աշխատում.'; +$PHPMAILER_LANG['provide_address'] = 'Անհրաժեշտ է տրամադրել գոնե մեկ ստացողի e-mail հասցե.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP -ի սխալ: չի հաջողվել ուղարկել հետևյալ ստացողների հասցեներին: '; +$PHPMAILER_LANG['signing'] = 'Ստորագրման սխալ: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP -ի connect() ֆունկցիան չի հաջողվել'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP սերվերի սխալ: '; +$PHPMAILER_LANG['variable_set'] = 'Չի հաջողվում ստեղծել կամ վերափոխել փոփոխականը: '; +$PHPMAILER_LANG['extension_missing'] = 'Հավելվածը բացակայում է: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-id.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-id.php new file mode 100644 index 0000000..212a11f --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-id.php @@ -0,0 +1,31 @@ +<?php + +/** + * Indonesian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Cecep Prawiro <cecep.prawiro@gmail.com> + * @author @januridp + * @author Ian Mustafa <mail@ianmustafa.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Kesalahan SMTP: Tidak dapat mengotentikasi.'; +$PHPMAILER_LANG['connect_host'] = 'Kesalahan SMTP: Tidak dapat terhubung ke host SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Kesalahan SMTP: Data tidak diterima.'; +$PHPMAILER_LANG['empty_message'] = 'Isi pesan kosong'; +$PHPMAILER_LANG['encoding'] = 'Pengkodean karakter tidak dikenali: '; +$PHPMAILER_LANG['execute'] = 'Tidak dapat menjalankan proses: '; +$PHPMAILER_LANG['file_access'] = 'Tidak dapat mengakses berkas: '; +$PHPMAILER_LANG['file_open'] = 'Kesalahan Berkas: Berkas tidak dapat dibuka: '; +$PHPMAILER_LANG['from_failed'] = 'Alamat pengirim berikut mengakibatkan kesalahan: '; +$PHPMAILER_LANG['instantiate'] = 'Tidak dapat menginisialisasi fungsi surel.'; +$PHPMAILER_LANG['invalid_address'] = 'Gagal terkirim, alamat surel tidak sesuai: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Gagal terkirim, entri host tidak sesuai: '; +$PHPMAILER_LANG['invalid_host'] = 'Gagal terkirim, host tidak sesuai: '; +$PHPMAILER_LANG['provide_address'] = 'Harus tersedia minimal satu alamat tujuan'; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer tidak didukung'; +$PHPMAILER_LANG['recipients_failed'] = 'Kesalahan SMTP: Alamat tujuan berikut menyebabkan kesalahan: '; +$PHPMAILER_LANG['signing'] = 'Kesalahan dalam penandatangan SSL: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() gagal.'; +$PHPMAILER_LANG['smtp_error'] = 'Kesalahan pada pelayan SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Tidak dapat mengatur atau mengatur ulang variabel: '; +$PHPMAILER_LANG['extension_missing'] = 'Ekstensi PHP tidak tersedia: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-it.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-it.php new file mode 100644 index 0000000..08a6b73 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-it.php @@ -0,0 +1,28 @@ +<?php + +/** + * Italian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Ilias Bartolini <brain79@inwind.it> + * @author Stefano Sabatini <sabas88@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Error: Impossibile autenticarsi.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Impossibile connettersi all\'host SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Dati non accettati dal server.'; +$PHPMAILER_LANG['empty_message'] = 'Il corpo del messaggio è vuoto'; +$PHPMAILER_LANG['encoding'] = 'Codifica dei caratteri sconosciuta: '; +$PHPMAILER_LANG['execute'] = 'Impossibile eseguire l\'operazione: '; +$PHPMAILER_LANG['file_access'] = 'Impossibile accedere al file: '; +$PHPMAILER_LANG['file_open'] = 'File Error: Impossibile aprire il file: '; +$PHPMAILER_LANG['from_failed'] = 'I seguenti indirizzi mittenti hanno generato errore: '; +$PHPMAILER_LANG['instantiate'] = 'Impossibile istanziare la funzione mail'; +$PHPMAILER_LANG['invalid_address'] = 'Impossibile inviare, l\'indirizzo email non è valido: '; +$PHPMAILER_LANG['provide_address'] = 'Deve essere fornito almeno un indirizzo ricevente'; +$PHPMAILER_LANG['mailer_not_supported'] = 'Mailer non supportato'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: I seguenti indirizzi destinatari hanno generato un errore: '; +$PHPMAILER_LANG['signing'] = 'Errore nella firma: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fallita.'; +$PHPMAILER_LANG['smtp_error'] = 'Errore del server SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Impossibile impostare o resettare la variabile: '; +$PHPMAILER_LANG['extension_missing'] = 'Estensione mancante: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ja.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ja.php new file mode 100644 index 0000000..eee7989 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ja.php @@ -0,0 +1,28 @@ +<?php + +/** + * Japanese PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Mitsuhiro Yoshida <http://mitstek.com/> + * @author Yoshi Sakai <http://bluemooninc.jp/> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTPエラー: 認証できませんでした。'; +$PHPMAILER_LANG['connect_host'] = 'SMTPエラー: SMTPホストに接続できませんでした。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTPエラー: データが受け付けられませんでした。'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = '不明なエンコーディング: '; +$PHPMAILER_LANG['execute'] = '実行できませんでした: '; +$PHPMAILER_LANG['file_access'] = 'ファイルにアクセスできません: '; +$PHPMAILER_LANG['file_open'] = 'ファイルエラー: ファイルを開けません: '; +$PHPMAILER_LANG['from_failed'] = 'Fromアドレスを登録する際にエラーが発生しました: '; +$PHPMAILER_LANG['instantiate'] = 'メール関数が正常に動作しませんでした。'; +//$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; +$PHPMAILER_LANG['provide_address'] = '少なくとも1つメールアドレスを 指定する必要があります。'; +$PHPMAILER_LANG['mailer_not_supported'] = ' メーラーがサポートされていません。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTPエラー: 次の受信者アドレスに 間違いがあります: '; +//$PHPMAILER_LANG['signing'] = 'Signing Error: '; +//$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +//$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; +//$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ka.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ka.php new file mode 100644 index 0000000..51fe403 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ka.php @@ -0,0 +1,27 @@ +<?php + +/** + * Georgian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP შეცდომა: ავტორიზაცია შეუძლებელია.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP შეცდომა: SMTP სერვერთან დაკავშირება შეუძლებელია.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP შეცდომა: მონაცემები არ იქნა მიღებული.'; +$PHPMAILER_LANG['encoding'] = 'კოდირების უცნობი ტიპი: '; +$PHPMAILER_LANG['execute'] = 'შეუძლებელია შემდეგი ბრძანების შესრულება: '; +$PHPMAILER_LANG['file_access'] = 'შეუძლებელია წვდომა ფაილთან: '; +$PHPMAILER_LANG['file_open'] = 'ფაილური სისტემის შეცდომა: არ იხსნება ფაილი: '; +$PHPMAILER_LANG['from_failed'] = 'გამგზავნის არასწორი მისამართი: '; +$PHPMAILER_LANG['instantiate'] = 'mail ფუნქციის გაშვება ვერ ხერხდება.'; +$PHPMAILER_LANG['provide_address'] = 'გთხოვთ მიუთითოთ ერთი ადრესატის e-mail მისამართი მაინც.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' - საფოსტო სერვერის მხარდაჭერა არ არის.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP შეცდომა: შემდეგ მისამართებზე გაგზავნა ვერ მოხერხდა: '; +$PHPMAILER_LANG['empty_message'] = 'შეტყობინება ცარიელია'; +$PHPMAILER_LANG['invalid_address'] = 'არ გაიგზავნა, e-mail მისამართის არასწორი ფორმატი: '; +$PHPMAILER_LANG['signing'] = 'ხელმოწერის შეცდომა: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'შეცდომა SMTP სერვერთან დაკავშირებისას'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP სერვერის შეცდომა: '; +$PHPMAILER_LANG['variable_set'] = 'შეუძლებელია შემდეგი ცვლადის შექმნა ან შეცვლა: '; +$PHPMAILER_LANG['extension_missing'] = 'ბიბლიოთეკა არ არსებობს: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ko.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ko.php new file mode 100644 index 0000000..8c97dd9 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ko.php @@ -0,0 +1,27 @@ +<?php + +/** + * Korean PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author ChalkPE <amato0617@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 오류: 인증할 수 없습니다.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 오류: SMTP 호스트에 접속할 수 없습니다.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 오류: 데이터가 받아들여지지 않았습니다.'; +$PHPMAILER_LANG['empty_message'] = '메세지 내용이 없습니다'; +$PHPMAILER_LANG['encoding'] = '알 수 없는 인코딩: '; +$PHPMAILER_LANG['execute'] = '실행 불가: '; +$PHPMAILER_LANG['file_access'] = '파일 접근 불가: '; +$PHPMAILER_LANG['file_open'] = '파일 오류: 파일을 열 수 없습니다: '; +$PHPMAILER_LANG['from_failed'] = '다음 From 주소에서 오류가 발생했습니다: '; +$PHPMAILER_LANG['instantiate'] = 'mail 함수를 인스턴스화할 수 없습니다'; +$PHPMAILER_LANG['invalid_address'] = '잘못된 주소: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' 메일러는 지원되지 않습니다.'; +$PHPMAILER_LANG['provide_address'] = '적어도 한 개 이상의 수신자 메일 주소를 제공해야 합니다.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 오류: 다음 수신자에서 오류가 발생했습니다: '; +$PHPMAILER_LANG['signing'] = '서명 오류: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP 연결을 실패하였습니다.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP 서버 오류: '; +$PHPMAILER_LANG['variable_set'] = '변수 설정 및 초기화 불가: '; +$PHPMAILER_LANG['extension_missing'] = '확장자 없음: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-lt.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-lt.php new file mode 100644 index 0000000..4f115b1 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-lt.php @@ -0,0 +1,27 @@ +<?php + +/** + * Lithuanian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Dainius Kaupaitis <dk@sum.lt> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP klaida: autentifikacija nepavyko.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP klaida: nepavyksta prisijungti prie SMTP stoties.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP klaida: duomenys nepriimti.'; +$PHPMAILER_LANG['empty_message'] = 'Laiško turinys tuščias'; +$PHPMAILER_LANG['encoding'] = 'Neatpažinta koduotė: '; +$PHPMAILER_LANG['execute'] = 'Nepavyko įvykdyti komandos: '; +$PHPMAILER_LANG['file_access'] = 'Byla nepasiekiama: '; +$PHPMAILER_LANG['file_open'] = 'Bylos klaida: Nepavyksta atidaryti: '; +$PHPMAILER_LANG['from_failed'] = 'Neteisingas siuntėjo adresas: '; +$PHPMAILER_LANG['instantiate'] = 'Nepavyko paleisti mail funkcijos.'; +$PHPMAILER_LANG['invalid_address'] = 'Neteisingas adresas: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' pašto stotis nepalaikoma.'; +$PHPMAILER_LANG['provide_address'] = 'Nurodykite bent vieną gavėjo adresą.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP klaida: nepavyko išsiųsti šiems gavėjams: '; +$PHPMAILER_LANG['signing'] = 'Prisijungimo klaida: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP susijungimo klaida'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP stoties klaida: '; +$PHPMAILER_LANG['variable_set'] = 'Nepavyko priskirti reikšmės kintamajam: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-lv.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-lv.php new file mode 100644 index 0000000..679b18c --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-lv.php @@ -0,0 +1,27 @@ +<?php + +/** + * Latvian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Eduards M. <e@npd.lv> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP kļūda: Autorizācija neizdevās.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Kļūda: Nevar izveidot savienojumu ar SMTP serveri.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Kļūda: Nepieņem informāciju.'; +$PHPMAILER_LANG['empty_message'] = 'Ziņojuma teksts ir tukšs'; +$PHPMAILER_LANG['encoding'] = 'Neatpazīts kodējums: '; +$PHPMAILER_LANG['execute'] = 'Neizdevās izpildīt komandu: '; +$PHPMAILER_LANG['file_access'] = 'Fails nav pieejams: '; +$PHPMAILER_LANG['file_open'] = 'Faila kļūda: Nevar atvērt failu: '; +$PHPMAILER_LANG['from_failed'] = 'Nepareiza sūtītāja adrese: '; +$PHPMAILER_LANG['instantiate'] = 'Nevar palaist sūtīšanas funkciju.'; +$PHPMAILER_LANG['invalid_address'] = 'Nepareiza adrese: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' sūtītājs netiek atbalstīts.'; +$PHPMAILER_LANG['provide_address'] = 'Lūdzu, norādiet vismaz vienu adresātu.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP kļūda: neizdevās nosūtīt šādiem saņēmējiem: '; +$PHPMAILER_LANG['signing'] = 'Autorizācijas kļūda: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP savienojuma kļūda'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP servera kļūda: '; +$PHPMAILER_LANG['variable_set'] = 'Nevar piešķirt mainīgā vērtību: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-mg.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-mg.php new file mode 100644 index 0000000..8a94f6a --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-mg.php @@ -0,0 +1,27 @@ +<?php + +/** + * Malagasy PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Hackinet <piyushjha8164@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Hadisoana SMTP: Tsy nahomby ny fanamarinana.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Tsy afaka mampifandray amin\'ny mpampiantrano SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP diso: tsy voarakitra ny angona.'; +$PHPMAILER_LANG['empty_message'] = 'Tsy misy ny votoaty mailaka.'; +$PHPMAILER_LANG['encoding'] = 'Tsy fantatra encoding: '; +$PHPMAILER_LANG['execute'] = 'Tsy afaka manatanteraka ity baiko manaraka ity: '; +$PHPMAILER_LANG['file_access'] = 'Tsy nahomby ny fidirana amin\'ity rakitra ity: '; +$PHPMAILER_LANG['file_open'] = 'Hadisoana diso: Tsy afaka nanokatra ity file manaraka ity: '; +$PHPMAILER_LANG['from_failed'] = 'Ny adiresy iraka manaraka dia diso: '; +$PHPMAILER_LANG['instantiate'] = 'Tsy afaka nanomboka ny hetsika mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Tsy mety ny adiresy: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer tsy manohana.'; +$PHPMAILER_LANG['provide_address'] = 'Alefaso azafady iray adiresy iray farafahakeliny.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Tsy mety ireo mpanaraka ireto: '; +$PHPMAILER_LANG['signing'] = 'Error nandritra ny sonia:'; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Tsy nahomby ny fifandraisana tamin\'ny server SMTP.'; +$PHPMAILER_LANG['smtp_error'] = 'Fahadisoana tamin\'ny server SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Tsy azo atao ny mametraka na mamerina ny variable: '; +$PHPMAILER_LANG['extension_missing'] = 'Tsy hita ny ampahany: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ms.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ms.php new file mode 100644 index 0000000..71db338 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ms.php @@ -0,0 +1,27 @@ +<?php + +/** + * Malaysian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Nawawi Jamili <nawawi@rutweb.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Ralat SMTP: Tidak dapat pengesahan.'; +$PHPMAILER_LANG['connect_host'] = 'Ralat SMTP: Tidak dapat menghubungi hos pelayan SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Ralat SMTP: Data tidak diterima oleh pelayan.'; +$PHPMAILER_LANG['empty_message'] = 'Tiada isi untuk mesej'; +$PHPMAILER_LANG['encoding'] = 'Pengekodan tidak diketahui: '; +$PHPMAILER_LANG['execute'] = 'Tidak dapat melaksanakan: '; +$PHPMAILER_LANG['file_access'] = 'Tidak dapat mengakses fail: '; +$PHPMAILER_LANG['file_open'] = 'Ralat Fail: Tidak dapat membuka fail: '; +$PHPMAILER_LANG['from_failed'] = 'Berikut merupakan ralat dari alamat e-mel: '; +$PHPMAILER_LANG['instantiate'] = 'Tidak dapat memberi contoh fungsi e-mel.'; +$PHPMAILER_LANG['invalid_address'] = 'Alamat emel tidak sah: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' jenis penghantar emel tidak disokong.'; +$PHPMAILER_LANG['provide_address'] = 'Anda perlu menyediakan sekurang-kurangnya satu alamat e-mel penerima.'; +$PHPMAILER_LANG['recipients_failed'] = 'Ralat SMTP: Penerima e-mel berikut telah gagal: '; +$PHPMAILER_LANG['signing'] = 'Ralat pada tanda tangan: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() telah gagal.'; +$PHPMAILER_LANG['smtp_error'] = 'Ralat pada pelayan SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Tidak boleh menetapkan atau menetapkan semula pembolehubah: '; +$PHPMAILER_LANG['extension_missing'] = 'Sambungan hilang: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-nb.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-nb.php new file mode 100644 index 0000000..65793ce --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-nb.php @@ -0,0 +1,26 @@ +<?php + +/** + * Norwegian Bokmål PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Feil: Kunne ikke autentisere.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Feil: Kunne ikke koble til SMTP tjener.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Feil: Datainnhold ikke akseptert.'; +$PHPMAILER_LANG['empty_message'] = 'Meldingsinnhold mangler'; +$PHPMAILER_LANG['encoding'] = 'Ukjent koding: '; +$PHPMAILER_LANG['execute'] = 'Kunne ikke utføre: '; +$PHPMAILER_LANG['file_access'] = 'Får ikke tilgang til filen: '; +$PHPMAILER_LANG['file_open'] = 'Fil Feil: Kunne ikke åpne filen: '; +$PHPMAILER_LANG['from_failed'] = 'Følgende Frå adresse feilet: '; +$PHPMAILER_LANG['instantiate'] = 'Kunne ikke initialisere post funksjon.'; +$PHPMAILER_LANG['invalid_address'] = 'Ugyldig adresse: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' sender er ikke støttet.'; +$PHPMAILER_LANG['provide_address'] = 'Du må opppgi minst en mottakeradresse.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Feil: Følgende mottakeradresse feilet: '; +$PHPMAILER_LANG['signing'] = 'Signering Feil: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP connect() feilet.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP server feil: '; +$PHPMAILER_LANG['variable_set'] = 'Kan ikke skrive eller omskrive variabel: '; +$PHPMAILER_LANG['extension_missing'] = 'Utvidelse mangler: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-nl.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-nl.php new file mode 100644 index 0000000..bf41ade --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-nl.php @@ -0,0 +1,29 @@ +<?php + +/** + * Dutch PHPMailer language file: refer to PHPMailer.php for definitive list. + * @package PHPMailer + * @author Tuxion <team@tuxion.nl> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP-fout: authenticatie mislukt.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon niet verbinden met SMTP-host.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data niet geaccepteerd.'; +$PHPMAILER_LANG['empty_message'] = 'Berichttekst is leeg'; +$PHPMAILER_LANG['encoding'] = 'Onbekende codering: '; +$PHPMAILER_LANG['execute'] = 'Kon niet uitvoeren: '; +$PHPMAILER_LANG['file_access'] = 'Kreeg geen toegang tot bestand: '; +$PHPMAILER_LANG['file_open'] = 'Bestandsfout: kon bestand niet openen: '; +$PHPMAILER_LANG['from_failed'] = 'Het volgende afzendersadres is mislukt: '; +$PHPMAILER_LANG['instantiate'] = 'Kon mailfunctie niet initialiseren.'; +$PHPMAILER_LANG['invalid_address'] = 'Ongeldig adres: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Ongeldige hostentry: '; +$PHPMAILER_LANG['invalid_host'] = 'Ongeldige host: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer wordt niet ondersteund.'; +$PHPMAILER_LANG['provide_address'] = 'Er moet minstens één ontvanger worden opgegeven.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: de volgende ontvangers zijn mislukt: '; +$PHPMAILER_LANG['signing'] = 'Signeerfout: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Verbinding mislukt.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP-serverfout: '; +$PHPMAILER_LANG['variable_set'] = 'Kan de volgende variabele niet instellen of resetten: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensie afwezig: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pl.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pl.php new file mode 100644 index 0000000..23caa71 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pl.php @@ -0,0 +1,27 @@ +<?php + +/** + * Polish PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + */ + +$PHPMAILER_LANG['authenticate'] = 'Błąd SMTP: Nie można przeprowadzić uwierzytelnienia.'; +$PHPMAILER_LANG['connect_host'] = 'Błąd SMTP: Nie można połączyć się z wybranym hostem.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Błąd SMTP: Dane nie zostały przyjęte.'; +$PHPMAILER_LANG['empty_message'] = 'Wiadomość jest pusta.'; +$PHPMAILER_LANG['encoding'] = 'Nieznany sposób kodowania znaków: '; +$PHPMAILER_LANG['execute'] = 'Nie można uruchomić: '; +$PHPMAILER_LANG['file_access'] = 'Brak dostępu do pliku: '; +$PHPMAILER_LANG['file_open'] = 'Nie można otworzyć pliku: '; +$PHPMAILER_LANG['from_failed'] = 'Następujący adres Nadawcy jest nieprawidłowy: '; +$PHPMAILER_LANG['instantiate'] = 'Nie można wywołać funkcji mail(). Sprawdź konfigurację serwera.'; +$PHPMAILER_LANG['invalid_address'] = 'Nie można wysłać wiadomości, ' . + 'następujący adres Odbiorcy jest nieprawidłowy: '; +$PHPMAILER_LANG['provide_address'] = 'Należy podać prawidłowy adres email Odbiorcy.'; +$PHPMAILER_LANG['mailer_not_supported'] = 'Wybrana metoda wysyłki wiadomości nie jest obsługiwana.'; +$PHPMAILER_LANG['recipients_failed'] = 'Błąd SMTP: Następujący odbiorcy są nieprawidłowi: '; +$PHPMAILER_LANG['signing'] = 'Błąd podpisywania wiadomości: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() zakończone niepowodzeniem.'; +$PHPMAILER_LANG['smtp_error'] = 'Błąd SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Nie można ustawić lub zmodyfikować zmiennej: '; +$PHPMAILER_LANG['extension_missing'] = 'Brakujące rozszerzenie: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt.php new file mode 100644 index 0000000..f1ce946 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt.php @@ -0,0 +1,27 @@ +<?php + +/** + * Portuguese (European) PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Jonadabe <jonadabe@hotmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Erro do SMTP: Não foi possível realizar a autenticação.'; +$PHPMAILER_LANG['connect_host'] = 'Erro do SMTP: Não foi possível realizar ligação com o servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erro do SMTP: Os dados foram rejeitados.'; +$PHPMAILER_LANG['empty_message'] = 'A mensagem no e-mail está vazia.'; +$PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: '; +$PHPMAILER_LANG['execute'] = 'Não foi possível executar: '; +$PHPMAILER_LANG['file_access'] = 'Não foi possível aceder o ficheiro: '; +$PHPMAILER_LANG['file_open'] = 'Abertura do ficheiro: Não foi possível abrir o ficheiro: '; +$PHPMAILER_LANG['from_failed'] = 'Ocorreram falhas nos endereços dos seguintes remententes: '; +$PHPMAILER_LANG['instantiate'] = 'Não foi possível iniciar uma instância da função mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Não foi enviado nenhum e-mail para o endereço de e-mail inválido: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.'; +$PHPMAILER_LANG['provide_address'] = 'Tem de fornecer pelo menos um endereço como destinatário do e-mail.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erro do SMTP: O endereço do seguinte destinatário falhou: '; +$PHPMAILER_LANG['signing'] = 'Erro ao assinar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.'; +$PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensão em falta: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt_br.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt_br.php new file mode 100644 index 0000000..d863809 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt_br.php @@ -0,0 +1,30 @@ +<?php + +/** + * Brazilian Portuguese PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Paulo Henrique Garcia <paulo@controllerweb.com.br> + * @author Lucas Guimarães <lucas@lucasguimaraes.com> + * @author Phelipe Alves <phelipealvesdesouza@gmail.com> + * @author Fabio Beneditto <fabiobeneditto@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Erro de SMTP: Não foi possível autenticar.'; +$PHPMAILER_LANG['connect_host'] = 'Erro de SMTP: Não foi possível conectar ao servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erro de SMTP: Dados rejeitados.'; +$PHPMAILER_LANG['empty_message'] = 'Mensagem vazia'; +$PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: '; +$PHPMAILER_LANG['execute'] = 'Não foi possível executar: '; +$PHPMAILER_LANG['file_access'] = 'Não foi possível acessar o arquivo: '; +$PHPMAILER_LANG['file_open'] = 'Erro de Arquivo: Não foi possível abrir o arquivo: '; +$PHPMAILER_LANG['from_failed'] = 'Os seguintes remetentes falharam: '; +$PHPMAILER_LANG['instantiate'] = 'Não foi possível instanciar a função mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Endereço de e-mail inválido: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.'; +$PHPMAILER_LANG['provide_address'] = 'Você deve informar pelo menos um destinatário.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erro de SMTP: Os seguintes destinatários falharam: '; +$PHPMAILER_LANG['signing'] = 'Erro de Assinatura: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.'; +$PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensão não existe: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ro.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ro.php new file mode 100644 index 0000000..292ec1e --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ro.php @@ -0,0 +1,27 @@ +<?php + +/** + * Romanian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Alex Florea <alecz.fia@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'Eroare SMTP: Autentificarea a eșuat.'; +$PHPMAILER_LANG['connect_host'] = 'Eroare SMTP: Conectarea la serverul SMTP a eșuat.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Eroare SMTP: Datele nu au fost acceptate.'; +$PHPMAILER_LANG['empty_message'] = 'Mesajul este gol.'; +$PHPMAILER_LANG['encoding'] = 'Encodare necunoscută: '; +$PHPMAILER_LANG['execute'] = 'Nu se poate executa următoarea comandă: '; +$PHPMAILER_LANG['file_access'] = 'Nu se poate accesa următorul fișier: '; +$PHPMAILER_LANG['file_open'] = 'Eroare fișier: Nu se poate deschide următorul fișier: '; +$PHPMAILER_LANG['from_failed'] = 'Următoarele adrese From au dat eroare: '; +$PHPMAILER_LANG['instantiate'] = 'Funcția mail nu a putut fi inițializată.'; +$PHPMAILER_LANG['invalid_address'] = 'Adresa de email nu este validă: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer nu este suportat.'; +$PHPMAILER_LANG['provide_address'] = 'Trebuie să adăugați cel puțin o adresă de email.'; +$PHPMAILER_LANG['recipients_failed'] = 'Eroare SMTP: Următoarele adrese de email au eșuat: '; +$PHPMAILER_LANG['signing'] = 'A aparut o problemă la semnarea emailului. '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Conectarea la serverul SMTP a eșuat.'; +$PHPMAILER_LANG['smtp_error'] = 'Eroare server SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Nu se poate seta/reseta variabila. '; +$PHPMAILER_LANG['extension_missing'] = 'Lipsește extensia: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ru.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ru.php new file mode 100644 index 0000000..8c8c5e8 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-ru.php @@ -0,0 +1,28 @@ +<?php + +/** + * Russian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Alexey Chumakov <alex@chumakov.ru> + * @author Foster Snowhill <i18n@forstwoof.ru> + */ + +$PHPMAILER_LANG['authenticate'] = 'Ошибка SMTP: ошибка авторизации.'; +$PHPMAILER_LANG['connect_host'] = 'Ошибка SMTP: не удается подключиться к SMTP-серверу.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Ошибка SMTP: данные не приняты.'; +$PHPMAILER_LANG['encoding'] = 'Неизвестная кодировка: '; +$PHPMAILER_LANG['execute'] = 'Невозможно выполнить команду: '; +$PHPMAILER_LANG['file_access'] = 'Нет доступа к файлу: '; +$PHPMAILER_LANG['file_open'] = 'Файловая ошибка: не удаётся открыть файл: '; +$PHPMAILER_LANG['from_failed'] = 'Неверный адрес отправителя: '; +$PHPMAILER_LANG['instantiate'] = 'Невозможно запустить функцию mail().'; +$PHPMAILER_LANG['provide_address'] = 'Пожалуйста, введите хотя бы один email-адрес получателя.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' — почтовый сервер не поддерживается.'; +$PHPMAILER_LANG['recipients_failed'] = 'Ошибка SMTP: не удалась отправка таким адресатам: '; +$PHPMAILER_LANG['empty_message'] = 'Пустое сообщение'; +$PHPMAILER_LANG['invalid_address'] = 'Не отправлено из-за неправильного формата email-адреса: '; +$PHPMAILER_LANG['signing'] = 'Ошибка подписи: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ошибка соединения с SMTP-сервером'; +$PHPMAILER_LANG['smtp_error'] = 'Ошибка SMTP-сервера: '; +$PHPMAILER_LANG['variable_set'] = 'Невозможно установить или сбросить переменную: '; +$PHPMAILER_LANG['extension_missing'] = 'Расширение отсутствует: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sk.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sk.php new file mode 100644 index 0000000..028f5bc --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sk.php @@ -0,0 +1,30 @@ +<?php + +/** + * Slovak PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Michal Tinka <michaltinka@gmail.com> + * @author Peter Orlický <pcmanik91@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Error: Chyba autentifikácie.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Nebolo možné nadviazať spojenie so SMTP serverom.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Dáta neboli prijaté'; +$PHPMAILER_LANG['empty_message'] = 'Prázdne telo správy.'; +$PHPMAILER_LANG['encoding'] = 'Neznáme kódovanie: '; +$PHPMAILER_LANG['execute'] = 'Nedá sa vykonať: '; +$PHPMAILER_LANG['file_access'] = 'Súbor nebol nájdený: '; +$PHPMAILER_LANG['file_open'] = 'File Error: Súbor sa otvoriť pre čítanie: '; +$PHPMAILER_LANG['from_failed'] = 'Následujúca adresa From je nesprávna: '; +$PHPMAILER_LANG['instantiate'] = 'Nedá sa vytvoriť inštancia emailovej funkcie.'; +$PHPMAILER_LANG['invalid_address'] = 'Neodoslané, emailová adresa je nesprávna: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Záznam hostiteľa je nesprávny: '; +$PHPMAILER_LANG['invalid_host'] = 'Hostiteľ je nesprávny: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' emailový klient nieje podporovaný.'; +$PHPMAILER_LANG['provide_address'] = 'Musíte zadať aspoň jednu emailovú adresu príjemcu.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Adresy príjemcov niesu správne '; +$PHPMAILER_LANG['signing'] = 'Chyba prihlasovania: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() zlyhalo.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP chyba serveru: '; +$PHPMAILER_LANG['variable_set'] = 'Nemožno nastaviť alebo resetovať premennú: '; +$PHPMAILER_LANG['extension_missing'] = 'Chýba rozšírenie: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php new file mode 100644 index 0000000..c437a88 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php @@ -0,0 +1,31 @@ +<?php + +/** + * Slovene PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Klemen Tušar <techouse@gmail.com> + * @author Filip Š <projects@filips.si> + * @author Blaž Oražem <blaz@orazem.si> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP napaka: Avtentikacija ni uspela.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP napaka: Vzpostavljanje povezave s SMTP gostiteljem ni uspelo.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP napaka: Strežnik zavrača podatke.'; +$PHPMAILER_LANG['empty_message'] = 'E-poštno sporočilo nima vsebine.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznan tip kodiranja: '; +$PHPMAILER_LANG['execute'] = 'Operacija ni uspela: '; +$PHPMAILER_LANG['file_access'] = 'Nimam dostopa do datoteke: '; +$PHPMAILER_LANG['file_open'] = 'Ne morem odpreti datoteke: '; +$PHPMAILER_LANG['from_failed'] = 'Neveljaven e-naslov pošiljatelja: '; +$PHPMAILER_LANG['instantiate'] = 'Ne morem inicializirati mail funkcije.'; +$PHPMAILER_LANG['invalid_address'] = 'E-poštno sporočilo ni bilo poslano. E-naslov je neveljaven: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Neveljaven vnos gostitelja: '; +$PHPMAILER_LANG['invalid_host'] = 'Neveljaven gostitelj: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer ni podprt.'; +$PHPMAILER_LANG['provide_address'] = 'Prosimo, vnesite vsaj enega naslovnika.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP napaka: Sledeči naslovniki so neveljavni: '; +$PHPMAILER_LANG['signing'] = 'Napaka pri podpisovanju: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ne morem vzpostaviti povezave s SMTP strežnikom.'; +$PHPMAILER_LANG['smtp_error'] = 'Napaka SMTP strežnika: '; +$PHPMAILER_LANG['variable_set'] = 'Ne morem nastaviti oz. ponastaviti spremenljivke: '; +$PHPMAILER_LANG['extension_missing'] = 'Manjkajoča razširitev: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr.php new file mode 100644 index 0000000..0b5280f --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr.php @@ -0,0 +1,28 @@ +<?php + +/** + * Serbian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Александар Јевремовић <ajevremovic@gmail.com> + * @author Miloš Milanović <mmilanovic016@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP грешка: аутентификација није успела.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP грешка: повезивање са SMTP сервером није успело.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP грешка: подаци нису прихваћени.'; +$PHPMAILER_LANG['empty_message'] = 'Садржај поруке је празан.'; +$PHPMAILER_LANG['encoding'] = 'Непознато кодирање: '; +$PHPMAILER_LANG['execute'] = 'Није могуће извршити наредбу: '; +$PHPMAILER_LANG['file_access'] = 'Није могуће приступити датотеци: '; +$PHPMAILER_LANG['file_open'] = 'Није могуће отворити датотеку: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP грешка: слање са следећих адреса није успело: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP грешка: слање на следеће адресе није успело: '; +$PHPMAILER_LANG['instantiate'] = 'Није могуће покренути mail функцију.'; +$PHPMAILER_LANG['invalid_address'] = 'Порука није послата. Неисправна адреса: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' мејлер није подржан.'; +$PHPMAILER_LANG['provide_address'] = 'Дефинишите бар једну адресу примаоца.'; +$PHPMAILER_LANG['signing'] = 'Грешка приликом пријаве: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Повезивање са SMTP сервером није успело.'; +$PHPMAILER_LANG['smtp_error'] = 'Грешка SMTP сервера: '; +$PHPMAILER_LANG['variable_set'] = 'Није могуће задати нити ресетовати променљиву: '; +$PHPMAILER_LANG['extension_missing'] = 'Недостаје проширење: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php new file mode 100644 index 0000000..6213832 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php @@ -0,0 +1,28 @@ +<?php + +/** + * Serbian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Александар Јевремовић <ajevremovic@gmail.com> + * @author Miloš Milanović <mmilanovic016@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP greška: autentifikacija nije uspela.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP greška: povezivanje sa SMTP serverom nije uspelo.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP greška: podaci nisu prihvaćeni.'; +$PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznato kodiranje: '; +$PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; +$PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; +$PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP greška: slanje sa sledećih adresa nije uspelo: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP greška: slanje na sledeće adrese nije uspelo: '; +$PHPMAILER_LANG['instantiate'] = 'Nije moguće pokrenuti mail funkciju.'; +$PHPMAILER_LANG['invalid_address'] = 'Poruka nije poslata. Neispravna adresa: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' majler nije podržan.'; +$PHPMAILER_LANG['provide_address'] = 'Definišite bar jednu adresu primaoca.'; +$PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Povezivanje sa SMTP serverom nije uspelo.'; +$PHPMAILER_LANG['smtp_error'] = 'Greška SMTP servera: '; +$PHPMAILER_LANG['variable_set'] = 'Nije moguće zadati niti resetovati promenljivu: '; +$PHPMAILER_LANG['extension_missing'] = 'Nedostaje proširenje: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php new file mode 100644 index 0000000..9872c19 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php @@ -0,0 +1,27 @@ +<?php + +/** + * Swedish PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Johan Linnér <johan@linner.biz> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP fel: Kunde inte autentisera.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP fel: Kunde inte ansluta till SMTP-server.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP fel: Data accepterades inte.'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = 'Okänt encode-format: '; +$PHPMAILER_LANG['execute'] = 'Kunde inte köra: '; +$PHPMAILER_LANG['file_access'] = 'Ingen åtkomst till fil: '; +$PHPMAILER_LANG['file_open'] = 'Fil fel: Kunde inte öppna fil: '; +$PHPMAILER_LANG['from_failed'] = 'Följande avsändaradress är felaktig: '; +$PHPMAILER_LANG['instantiate'] = 'Kunde inte initiera e-postfunktion.'; +$PHPMAILER_LANG['invalid_address'] = 'Felaktig adress: '; +$PHPMAILER_LANG['provide_address'] = 'Du måste ange minst en mottagares e-postadress.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer stöds inte.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP fel: Följande mottagare är felaktig: '; +$PHPMAILER_LANG['signing'] = 'Signeringsfel: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() misslyckades.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP serverfel: '; +$PHPMAILER_LANG['variable_set'] = 'Kunde inte definiera eller återställa variabel: '; +$PHPMAILER_LANG['extension_missing'] = 'Tillägg ej tillgängligt: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-tl.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-tl.php new file mode 100644 index 0000000..d15bed1 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-tl.php @@ -0,0 +1,28 @@ +<?php + +/** + * Tagalog PHPMailer language file: refer to English translation for definitive list + * + * @package PHPMailer + * @author Adriane Justine Tan <eidoriantan@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Error: Hindi mapatotohanan.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Hindi makakonekta sa SMTP host.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Ang datos ay hindi naitanggap.'; +$PHPMAILER_LANG['empty_message'] = 'Walang laman ang mensahe'; +$PHPMAILER_LANG['encoding'] = 'Hindi alam ang encoding: '; +$PHPMAILER_LANG['execute'] = 'Hindi maisasagawa: '; +$PHPMAILER_LANG['file_access'] = 'Hindi ma-access ang file: '; +$PHPMAILER_LANG['file_open'] = 'File Error: Hindi mabuksan ang file: '; +$PHPMAILER_LANG['from_failed'] = 'Ang sumusunod na address ay nabigo: '; +$PHPMAILER_LANG['instantiate'] = 'Hindi maisimulan ang instance ng mail function.'; +$PHPMAILER_LANG['invalid_address'] = 'Hindi wasto ang address na naibigay: '; +$PHPMAILER_LANG['mailer_not_supported'] = 'Ang mailer ay hindi suportado.'; +$PHPMAILER_LANG['provide_address'] = 'Kailangan mong magbigay ng kahit isang email address na tatanggap.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Ang mga sumusunod na tatanggap ay nabigo: '; +$PHPMAILER_LANG['signing'] = 'Hindi ma-sign: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ang SMTP connect() ay nabigo.'; +$PHPMAILER_LANG['smtp_error'] = 'Ang server ng SMTP ay nabigo: '; +$PHPMAILER_LANG['variable_set'] = 'Hindi matatakda o ma-reset ang mga variables: '; +$PHPMAILER_LANG['extension_missing'] = 'Nawawala ang extension: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-tr.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-tr.php new file mode 100644 index 0000000..f938f80 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-tr.php @@ -0,0 +1,31 @@ +<?php + +/** + * Turkish PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Elçin Özel + * @author Can Yılmaz + * @author Mehmet Benlioğlu + * @author @yasinaydin + * @author Ogün Karakuş + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Hatası: Oturum açılamadı.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Hatası: SMTP sunucusuna bağlanılamadı.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Hatası: Veri kabul edilmedi.'; +$PHPMAILER_LANG['empty_message'] = 'Mesajın içeriği boş'; +$PHPMAILER_LANG['encoding'] = 'Bilinmeyen karakter kodlama: '; +$PHPMAILER_LANG['execute'] = 'Çalıştırılamadı: '; +$PHPMAILER_LANG['file_access'] = 'Dosyaya erişilemedi: '; +$PHPMAILER_LANG['file_open'] = 'Dosya Hatası: Dosya açılamadı: '; +$PHPMAILER_LANG['from_failed'] = 'Belirtilen adreslere gönderme başarısız: '; +$PHPMAILER_LANG['instantiate'] = 'Örnek e-posta fonksiyonu oluşturulamadı.'; +$PHPMAILER_LANG['invalid_address'] = 'Geçersiz e-posta adresi: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' e-posta kütüphanesi desteklenmiyor.'; +$PHPMAILER_LANG['provide_address'] = 'En az bir alıcı e-posta adresi belirtmelisiniz.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Hatası: Belirtilen alıcılara ulaşılamadı: '; +$PHPMAILER_LANG['signing'] = 'İmzalama hatası: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP connect() fonksiyonu başarısız.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP sunucu hatası: '; +$PHPMAILER_LANG['variable_set'] = 'Değişken ayarlanamadı ya da sıfırlanamadı: '; +$PHPMAILER_LANG['extension_missing'] = 'Eklenti bulunamadı: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-uk.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-uk.php new file mode 100644 index 0000000..3dea055 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-uk.php @@ -0,0 +1,28 @@ +<?php + +/** + * Ukrainian PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author Yuriy Rudyy <yrudyy@prs.net.ua> + * @fixed by Boris Yurchenko <boris@yurchenko.pp.ua> + */ + +$PHPMAILER_LANG['authenticate'] = 'Помилка SMTP: помилка авторизації.'; +$PHPMAILER_LANG['connect_host'] = 'Помилка SMTP: не вдається під\'єднатися до SMTP-серверу.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Помилка SMTP: дані не прийнято.'; +$PHPMAILER_LANG['encoding'] = 'Невідоме кодування: '; +$PHPMAILER_LANG['execute'] = 'Неможливо виконати команду: '; +$PHPMAILER_LANG['file_access'] = 'Немає доступу до файлу: '; +$PHPMAILER_LANG['file_open'] = 'Помилка файлової системи: не вдається відкрити файл: '; +$PHPMAILER_LANG['from_failed'] = 'Невірна адреса відправника: '; +$PHPMAILER_LANG['instantiate'] = 'Неможливо запустити функцію mail().'; +$PHPMAILER_LANG['provide_address'] = 'Будь ласка, введіть хоча б одну email-адресу отримувача.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' - поштовий сервер не підтримується.'; +$PHPMAILER_LANG['recipients_failed'] = 'Помилка SMTP: не вдалося відправлення для таких отримувачів: '; +$PHPMAILER_LANG['empty_message'] = 'Пусте повідомлення'; +$PHPMAILER_LANG['invalid_address'] = 'Не відправлено через неправильний формат email-адреси: '; +$PHPMAILER_LANG['signing'] = 'Помилка підпису: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Помилка з\'єднання з SMTP-сервером'; +$PHPMAILER_LANG['smtp_error'] = 'Помилка SMTP-сервера: '; +$PHPMAILER_LANG['variable_set'] = 'Неможливо встановити або скинути змінну: '; +$PHPMAILER_LANG['extension_missing'] = 'Розширення відсутнє: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-vi.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-vi.php new file mode 100644 index 0000000..d65576e --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-vi.php @@ -0,0 +1,27 @@ +<?php + +/** + * Vietnamese (Tiếng Việt) PHPMailer language file: refer to English translation for definitive list. + * @package PHPMailer + * @author VINADES.,JSC <contact@vinades.vn> + */ + +$PHPMAILER_LANG['authenticate'] = 'Lỗi SMTP: Không thể xác thực.'; +$PHPMAILER_LANG['connect_host'] = 'Lỗi SMTP: Không thể kết nối máy chủ SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Lỗi SMTP: Dữ liệu không được chấp nhận.'; +$PHPMAILER_LANG['empty_message'] = 'Không có nội dung'; +$PHPMAILER_LANG['encoding'] = 'Mã hóa không xác định: '; +$PHPMAILER_LANG['execute'] = 'Không thực hiện được: '; +$PHPMAILER_LANG['file_access'] = 'Không thể truy cập tệp tin '; +$PHPMAILER_LANG['file_open'] = 'Lỗi Tập tin: Không thể mở tệp tin: '; +$PHPMAILER_LANG['from_failed'] = 'Lỗi địa chỉ gửi đi: '; +$PHPMAILER_LANG['instantiate'] = 'Không dùng được các hàm gửi thư.'; +$PHPMAILER_LANG['invalid_address'] = 'Đại chỉ emai không đúng: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' trình gửi thư không được hỗ trợ.'; +$PHPMAILER_LANG['provide_address'] = 'Bạn phải cung cấp ít nhất một địa chỉ người nhận.'; +$PHPMAILER_LANG['recipients_failed'] = 'Lỗi SMTP: lỗi địa chỉ người nhận: '; +$PHPMAILER_LANG['signing'] = 'Lỗi đăng nhập: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Lỗi kết nối với SMTP'; +$PHPMAILER_LANG['smtp_error'] = 'Lỗi máy chủ smtp '; +$PHPMAILER_LANG['variable_set'] = 'Không thể thiết lập hoặc thiết lập lại biến: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh.php new file mode 100644 index 0000000..35e4e70 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh.php @@ -0,0 +1,29 @@ +<?php + +/** + * Traditional Chinese PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author liqwei <liqwei@liqwei.com> + * @author Peter Dave Hello <@PeterDaveHello/> + * @author Jason Chiang <xcojad@gmail.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 錯誤:登入失敗。'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 錯誤:無法連線到 SMTP 主機。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 錯誤:無法接受的資料。'; +$PHPMAILER_LANG['empty_message'] = '郵件內容為空'; +$PHPMAILER_LANG['encoding'] = '未知編碼: '; +$PHPMAILER_LANG['execute'] = '無法執行:'; +$PHPMAILER_LANG['file_access'] = '無法存取檔案:'; +$PHPMAILER_LANG['file_open'] = '檔案錯誤:無法開啟檔案:'; +$PHPMAILER_LANG['from_failed'] = '發送地址錯誤:'; +$PHPMAILER_LANG['instantiate'] = '未知函數呼叫。'; +$PHPMAILER_LANG['invalid_address'] = '因為電子郵件地址無效,無法傳送: '; +$PHPMAILER_LANG['mailer_not_supported'] = '不支援的發信客戶端。'; +$PHPMAILER_LANG['provide_address'] = '必須提供至少一個收件人地址。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 錯誤:以下收件人地址錯誤:'; +$PHPMAILER_LANG['signing'] = '電子簽章錯誤: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP 連線失敗'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP 伺服器錯誤: '; +$PHPMAILER_LANG['variable_set'] = '無法設定或重設變數: '; +$PHPMAILER_LANG['extension_missing'] = '遺失模組 Extension: '; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php new file mode 100644 index 0000000..728a499 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php @@ -0,0 +1,29 @@ +<?php + +/** + * Simplified Chinese PHPMailer language file: refer to English translation for definitive list + * @package PHPMailer + * @author liqwei <liqwei@liqwei.com> + * @author young <masxy@foxmail.com> + * @author Teddysun <i@teddysun.com> + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 错误:登录失败。'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 错误:无法连接到 SMTP 主机。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 错误:数据不被接受。'; +$PHPMAILER_LANG['empty_message'] = '邮件正文为空。'; +$PHPMAILER_LANG['encoding'] = '未知编码:'; +$PHPMAILER_LANG['execute'] = '无法执行:'; +$PHPMAILER_LANG['file_access'] = '无法访问文件:'; +$PHPMAILER_LANG['file_open'] = '文件错误:无法打开文件:'; +$PHPMAILER_LANG['from_failed'] = '发送地址错误:'; +$PHPMAILER_LANG['instantiate'] = '未知函数调用。'; +$PHPMAILER_LANG['invalid_address'] = '发送失败,电子邮箱地址是无效的:'; +$PHPMAILER_LANG['mailer_not_supported'] = '发信客户端不被支持。'; +$PHPMAILER_LANG['provide_address'] = '必须提供至少一个收件人地址。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 错误:收件人地址错误:'; +$PHPMAILER_LANG['signing'] = '登录失败:'; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP服务器连接失败。'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP服务器出错:'; +$PHPMAILER_LANG['variable_set'] = '无法设置或重置变量:'; +$PHPMAILER_LANG['extension_missing'] = '丢失模块 Extension:'; diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/phpunit.xml.dist b/php/libraries/composer/vendor/phpmailer/phpmailer/phpunit.xml.dist new file mode 100644 index 0000000..c68df96 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/phpunit.xml.dist @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<phpunit + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.5/phpunit.xsd" + backupGlobals="true" + bootstrap="vendor/autoload.php" + verbose="true" + colors="true" + forceCoversAnnotation="false" + > + <testsuites> + <testsuite name="PHPMailerTests"> + <directory>./test/</directory> + </testsuite> + </testsuites> + <listeners> + <listener class="PHPMailer\Test\DebugLogTestListener" /> + </listeners> + <groups> + <exclude> + <group>languages</group> + <group>pop3</group> + </exclude> + </groups> + <filter> + <whitelist addUncoveredFilesFromWhitelist="true"> + <directory suffix=".php">./src</directory> + </whitelist> + </filter> + <logging> + <log type="coverage-text" target="php://stdout" showUncoveredFiles="true"/> + <log type="coverage-clover" target="build/logs/clover.xml"/> + <log type="junit" target="build/logs/junit.xml"/> + </logging> +</phpunit> diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/src/Exception.php b/php/libraries/composer/vendor/phpmailer/phpmailer/src/Exception.php new file mode 100644 index 0000000..a50a899 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/src/Exception.php @@ -0,0 +1,40 @@ +<?php + +/** + * PHPMailer Exception class. + * PHP Version 5.5. + * + * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer exception handler. + * + * @author Marcus Bointon <phpmailer@synchromedia.co.uk> + */ +class Exception extends \Exception +{ + /** + * Prettify error message output. + * + * @return string + */ + public function errorMessage() + { + return '<strong>' . htmlspecialchars($this->getMessage()) . "</strong><br />\n"; + } +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/src/OAuth.php b/php/libraries/composer/vendor/phpmailer/phpmailer/src/OAuth.php new file mode 100644 index 0000000..c93d0be --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/src/OAuth.php @@ -0,0 +1,139 @@ +<?php + +/** + * PHPMailer - PHP email creation and transport class. + * PHP Version 5.5. + * + * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +use League\OAuth2\Client\Grant\RefreshToken; +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Token\AccessToken; + +/** + * OAuth - OAuth2 authentication wrapper class. + * Uses the oauth2-client package from the League of Extraordinary Packages. + * + * @see http://oauth2-client.thephpleague.com + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + */ +class OAuth +{ + /** + * An instance of the League OAuth Client Provider. + * + * @var AbstractProvider + */ + protected $provider; + + /** + * The current OAuth access token. + * + * @var AccessToken + */ + protected $oauthToken; + + /** + * The user's email address, usually used as the login ID + * and also the from address when sending email. + * + * @var string + */ + protected $oauthUserEmail = ''; + + /** + * The client secret, generated in the app definition of the service you're connecting to. + * + * @var string + */ + protected $oauthClientSecret = ''; + + /** + * The client ID, generated in the app definition of the service you're connecting to. + * + * @var string + */ + protected $oauthClientId = ''; + + /** + * The refresh token, used to obtain new AccessTokens. + * + * @var string + */ + protected $oauthRefreshToken = ''; + + /** + * OAuth constructor. + * + * @param array $options Associative array containing + * `provider`, `userName`, `clientSecret`, `clientId` and `refreshToken` elements + */ + public function __construct($options) + { + $this->provider = $options['provider']; + $this->oauthUserEmail = $options['userName']; + $this->oauthClientSecret = $options['clientSecret']; + $this->oauthClientId = $options['clientId']; + $this->oauthRefreshToken = $options['refreshToken']; + } + + /** + * Get a new RefreshToken. + * + * @return RefreshToken + */ + protected function getGrant() + { + return new RefreshToken(); + } + + /** + * Get a new AccessToken. + * + * @return AccessToken + */ + protected function getToken() + { + return $this->provider->getAccessToken( + $this->getGrant(), + ['refresh_token' => $this->oauthRefreshToken] + ); + } + + /** + * Generate a base64-encoded OAuth token. + * + * @return string + */ + public function getOauth64() + { + //Get a new token if it's not available or has expired + if (null === $this->oauthToken || $this->oauthToken->hasExpired()) { + $this->oauthToken = $this->getToken(); + } + + return base64_encode( + 'user=' . + $this->oauthUserEmail . + "\001auth=Bearer " . + $this->oauthToken . + "\001\001" + ); + } +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/src/PHPMailer.php b/php/libraries/composer/vendor/phpmailer/phpmailer/src/PHPMailer.php new file mode 100644 index 0000000..2d16116 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/src/PHPMailer.php @@ -0,0 +1,4948 @@ +<?php + +/** + * PHPMailer - PHP email creation and transport class. + * PHP Version 5.5. + * + * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer - PHP email creation and transport class. + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + */ +class PHPMailer +{ + const CHARSET_ASCII = 'us-ascii'; + const CHARSET_ISO88591 = 'iso-8859-1'; + const CHARSET_UTF8 = 'utf-8'; + + const CONTENT_TYPE_PLAINTEXT = 'text/plain'; + const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; + const CONTENT_TYPE_TEXT_HTML = 'text/html'; + const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; + const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; + const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; + + const ENCODING_7BIT = '7bit'; + const ENCODING_8BIT = '8bit'; + const ENCODING_BASE64 = 'base64'; + const ENCODING_BINARY = 'binary'; + const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; + + const ENCRYPTION_STARTTLS = 'tls'; + const ENCRYPTION_SMTPS = 'ssl'; + + const ICAL_METHOD_REQUEST = 'REQUEST'; + const ICAL_METHOD_PUBLISH = 'PUBLISH'; + const ICAL_METHOD_REPLY = 'REPLY'; + const ICAL_METHOD_ADD = 'ADD'; + const ICAL_METHOD_CANCEL = 'CANCEL'; + const ICAL_METHOD_REFRESH = 'REFRESH'; + const ICAL_METHOD_COUNTER = 'COUNTER'; + const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; + + /** + * Email priority. + * Options: null (default), 1 = High, 3 = Normal, 5 = low. + * When null, the header is not set at all. + * + * @var int|null + */ + public $Priority; + + /** + * The character set of the message. + * + * @var string + */ + public $CharSet = self::CHARSET_ISO88591; + + /** + * The MIME Content-type of the message. + * + * @var string + */ + public $ContentType = self::CONTENT_TYPE_PLAINTEXT; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * + * @var string + */ + public $Encoding = self::ENCODING_8BIT; + + /** + * Holds the most recent mailer error message. + * + * @var string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * + * @var string + */ + public $From = 'root@localhost'; + + /** + * The From name of the message. + * + * @var string + */ + public $FromName = 'Root User'; + + /** + * The envelope sender of the message. + * This will usually be turned into a Return-Path header by the receiver, + * and is the address that bounces will be sent to. + * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. + * + * @var string + */ + public $Sender = ''; + + /** + * The Subject of the message. + * + * @var string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * + * @var string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * + * @var string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. + * + * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ + * @see http://kigkonsult.se/iCalcreator/ + * + * @var string + */ + public $Ical = ''; + + /** + * Value-array of "method" in Contenttype header "text/calendar" + * + * @var string[] + */ + protected static $IcalMethods = [ + self::ICAL_METHOD_REQUEST, + self::ICAL_METHOD_PUBLISH, + self::ICAL_METHOD_REPLY, + self::ICAL_METHOD_ADD, + self::ICAL_METHOD_CANCEL, + self::ICAL_METHOD_REFRESH, + self::ICAL_METHOD_COUNTER, + self::ICAL_METHOD_DECLINECOUNTER, + ]; + + /** + * The complete compiled MIME message body. + * + * @var string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * + * @var string + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * + * @var string + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. + * + * @see static::STD_LINE_LENGTH + * + * @var int + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * + * @var string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * + * @var string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * + * @var bool + */ + public $UseSendmailOptions = true; + + /** + * The email address that a reading confirmation should be sent to, also known as read receipt. + * + * @var string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in the Message-ID header and as default HELO string. + * If empty, PHPMailer attempts to find one with, in order, + * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value + * 'localhost.localdomain'. + * + * @see PHPMailer::$Helo + * + * @var string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-ID header. + * If empty, a unique id will be generated. + * You can set your own, but it must be in the format "<id@domain>", + * as defined in RFC5322 section 3.6.4 or it will be ignored. + * + * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 + * + * @var string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * + * @var string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * You can also specify encryption type, for example: + * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). + * Hosts will be tried in order. + * + * @var string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * + * @var int + */ + public $Port = 25; + + /** + * The SMTP HELO/EHLO name used for the SMTP connection. + * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find + * one with the same method described above for $Hostname. + * + * @see PHPMailer::$Hostname + * + * @var string + */ + public $Helo = ''; + + /** + * What kind of encryption to use on the SMTP connection. + * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. + * + * @var string + */ + public $SMTPSecure = ''; + + /** + * Whether to enable TLS encryption automatically if a server supports it, + * even if `SMTPSecure` is not set to 'tls'. + * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. + * + * @var bool + */ + public $SMTPAutoTLS = true; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * + * @see PHPMailer::$Username + * @see PHPMailer::$Password + * + * @var bool + */ + public $SMTPAuth = false; + + /** + * Options array passed to stream_context_create when connecting via SMTP. + * + * @var array + */ + public $SMTPOptions = []; + + /** + * SMTP username. + * + * @var string + */ + public $Username = ''; + + /** + * SMTP password. + * + * @var string + */ + public $Password = ''; + + /** + * SMTP auth type. + * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified. + * + * @var string + */ + public $AuthType = ''; + + /** + * An instance of the PHPMailer OAuth class. + * + * @var OAuth + */ + protected $oauth; + + /** + * The SMTP server timeout in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * + * @var int + */ + public $Timeout = 300; + + /** + * Comma separated list of DSN notifications + * 'NEVER' under no circumstances a DSN must be returned to the sender. + * If you use NEVER all other notifications will be ignored. + * 'SUCCESS' will notify you when your mail has arrived at its destination. + * 'FAILURE' will arrive if an error occurred during delivery. + * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual + * delivery's outcome (success or failure) is not yet decided. + * + * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY + */ + public $dsn = ''; + + /** + * SMTP class debug output mode. + * Debug output level. + * Options: + * @see SMTP::DEBUG_OFF: No output + * @see SMTP::DEBUG_CLIENT: Client messages + * @see SMTP::DEBUG_SERVER: Client and server messages + * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status + * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed + * + * @see SMTP::$do_debug + * + * @var int + */ + public $SMTPDebug = 0; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * ```php + * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * ``` + * + * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` + * level output is used: + * + * ```php + * $mail->Debugoutput = new myPsr3Logger; + * ``` + * + * @see SMTP::$Debugoutput + * + * @var string|callable|\Psr\Log\LoggerInterface + */ + public $Debugoutput = 'echo'; + + /** + * Whether to keep SMTP connection open after each message. + * If this is set to true then to close the connection + * requires an explicit call to smtpClose(). + * + * @var bool + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * Only supported in `mail` and `sendmail` transports, not in SMTP. + * + * @var bool + * + * @deprecated 6.0.0 PHPMailer isn't a mailing list manager! + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * + * @var array + */ + protected $SingleToArray = []; + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * + * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path + * @see http://www.postfix.org/VERP_README.html Postfix VERP info + * + * @var bool + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * + * @var bool + */ + public $AllowEmpty = false; + + /** + * DKIM selector. + * + * @var string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email. + * + * @var string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * + * @var string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * + * @example 'example.com' + * + * @var string + */ + public $DKIM_domain = ''; + + /** + * DKIM Copy header field values for diagnostic use. + * + * @var bool + */ + public $DKIM_copyHeaderFields = true; + + /** + * DKIM Extra signing headers. + * + * @example ['List-Unsubscribe', 'List-Help'] + * + * @var array + */ + public $DKIM_extraHeaders = []; + + /** + * DKIM private key file path. + * + * @var string + */ + public $DKIM_private = ''; + + /** + * DKIM private key string. + * + * If set, takes precedence over `$DKIM_private`. + * + * @var string + */ + public $DKIM_private_string = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be any php callable: http://www.php.net/is_callable + * + * Parameters: + * bool $result result of the send action + * array $to email addresses of the recipients + * array $cc cc email addresses + * array $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * string $extra extra information of possible use + * "smtp_transaction_id' => last smtp transaction id + * + * @var string + */ + public $action_function = ''; + + /** + * What to put in the X-Mailer header. + * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. + * + * @var string|null + */ + public $XMailer = ''; + + /** + * Which validator to use by default when validating email addresses. + * May be a callable to inject your own validator, but there are several built-in validators. + * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. + * + * @see PHPMailer::validateAddress() + * + * @var string|callable + */ + public static $validator = 'php'; + + /** + * An instance of the SMTP sender class. + * + * @var SMTP + */ + protected $smtp; + + /** + * The array of 'to' names and addresses. + * + * @var array + */ + protected $to = []; + + /** + * The array of 'cc' names and addresses. + * + * @var array + */ + protected $cc = []; + + /** + * The array of 'bcc' names and addresses. + * + * @var array + */ + protected $bcc = []; + + /** + * The array of reply-to names and addresses. + * + * @var array + */ + protected $ReplyTo = []; + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * + * @var array + */ + protected $all_recipients = []; + + /** + * An array of names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $all_recipients + * and one of $to, $cc, or $bcc. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * @see PHPMailer::$all_recipients + * + * @var array + */ + protected $RecipientsQueue = []; + + /** + * An array of reply-to names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $ReplyTo. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$ReplyTo + * + * @var array + */ + protected $ReplyToQueue = []; + + /** + * The array of attachments. + * + * @var array + */ + protected $attachment = []; + + /** + * The array of custom headers. + * + * @var array + */ + protected $CustomHeader = []; + + /** + * The most recent Message-ID (including angular brackets). + * + * @var string + */ + protected $lastMessageID = ''; + + /** + * The message's MIME type. + * + * @var string + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * + * @var array + */ + protected $boundary = []; + + /** + * The array of available languages. + * + * @var array + */ + protected $language = []; + + /** + * The number of errors encountered. + * + * @var int + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * + * @var string + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * + * @var string + */ + protected $sign_key_file = ''; + + /** + * The optional S/MIME extra certificates ("CA Chain") file path. + * + * @var string + */ + protected $sign_extracerts_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * + * @var string + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * + * @var bool + */ + protected $exceptions = false; + + /** + * Unique ID used for message ID and boundaries. + * + * @var string + */ + protected $uniqueid = ''; + + /** + * The PHPMailer Version number. + * + * @var string + */ + const VERSION = '6.4.1'; + + /** + * Error severity: message only, continue processing. + * + * @var int + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing. + * + * @var int + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached. + * + * @var int + */ + const STOP_CRITICAL = 2; + + /** + * The SMTP standard CRLF line break. + * If you want to change line break format, change static::$LE, not this. + */ + const CRLF = "\r\n"; + + /** + * "Folding White Space" a white space string used for line folding. + */ + const FWS = ' '; + + /** + * SMTP RFC standard line ending; Carriage Return, Line Feed. + * + * @var string + */ + protected static $LE = self::CRLF; + + /** + * The maximum line length supported by mail(). + * + * Background: mail() will sometimes corrupt messages + * with headers headers longer than 65 chars, see #818. + * + * @var int + */ + const MAIL_MAX_LINE_LENGTH = 63; + + /** + * The maximum line length allowed by RFC 2822 section 2.1.1. + * + * @var int + */ + const MAX_LINE_LENGTH = 998; + + /** + * The lower maximum line length allowed by RFC 2822 section 2.1.1. + * This length does NOT include the line break + * 76 means that lines will be 77 or 78 chars depending on whether + * the line break format is LF or CRLF; both are valid. + * + * @var int + */ + const STD_LINE_LENGTH = 76; + + /** + * Constructor. + * + * @param bool $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = null) + { + if (null !== $exceptions) { + $this->exceptions = (bool) $exceptions; + } + //Pick an appropriate debug output format automatically + $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); + } + + /** + * Destructor. + */ + public function __destruct() + { + //Close any open SMTP connection nicely + $this->smtpClose(); + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do). + * + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string|null $params Params + * + * @return bool + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + //Check overloading of mail function to avoid double-encoding + if (ini_get('mbstring.func_overload') & 1) { + $subject = $this->secureHeader($subject); + } else { + $subject = $this->encodeHeader($this->secureHeader($subject)); + } + //Calling mail() with null params breaks + $this->edebug('Sending with mail()'); + $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); + $this->edebug("Envelope sender: {$this->Sender}"); + $this->edebug("To: {$to}"); + $this->edebug("Subject: {$subject}"); + $this->edebug("Headers: {$header}"); + if (!$this->UseSendmailOptions || null === $params) { + $result = @mail($to, $subject, $body, $header); + } else { + $this->edebug("Additional params: {$params}"); + $result = @mail($to, $subject, $body, $header, $params); + } + $this->edebug('Result: ' . ($result ? 'true' : 'false')); + return $result; + } + + /** + * Output debugging info via a user-defined method. + * Only generates output if debug output is enabled. + * + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * + * @param string $str + */ + protected function edebug($str) + { + if ($this->SMTPDebug <= 0) { + return; + } + //Is this a PSR-3 logger? + if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { + $this->Debugoutput->debug($str); + + return; + } + //Avoid clash with built-in function names + if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + call_user_func($this->Debugoutput, $str, $this->SMTPDebug); + + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + /** @noinspection ForgottenDebugOutputInspection */ + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ), "<br>\n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n|\r/m', "\n", $str); + echo gmdate('Y-m-d H:i:s'), + "\t", + //Trim trailing space + trim( + //Indent for readability, except for trailing break + str_replace( + "\n", + "\n \t ", + trim($str) + ) + ), + "\n"; + } + } + + /** + * Sets message type to HTML or plain. + * + * @param bool $isHtml True for HTML mode + */ + public function isHTML($isHtml = true) + { + if ($isHtml) { + $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; + } else { + $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; + } + } + + /** + * Send messages using SMTP. + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Send messages using $Sendmail. + */ + public function isSendmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'sendmail')) { + $this->Sendmail = '/usr/sbin/sendmail'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + */ + public function isQmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'qmail')) { + $this->Sendmail = '/var/qmail/bin/qmail-inject'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'qmail'; + } + + /** + * Add a "To" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addAddress($address, $name = '') + { + return $this->addOrEnqueueAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addBCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-To" address. + * + * @param string $address The email address to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addReplyTo($address, $name = '') + { + return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer + * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still + * be modified after calling this function), addition of such addresses is delayed until send(). + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addOrEnqueueAnAddress($kind, $address, $name) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + $pos = strrpos($address, '@'); + if (false === $pos) { + //At-sign is missing. + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + $params = [$kind, $address, $name]; + //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. + if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { + if ('Reply-To' !== $kind) { + if (!array_key_exists($address, $this->RecipientsQueue)) { + $this->RecipientsQueue[$address] = $params; + + return true; + } + } elseif (!array_key_exists($address, $this->ReplyToQueue)) { + $this->ReplyToQueue[$address] = $params; + + return true; + } + + return false; + } + + //Immediately add standard addresses without IDN. + return call_user_func_array([$this, 'addAnAddress'], $params); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addAnAddress($kind, $address, $name = '') + { + if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { + $error_message = sprintf( + '%s: %s', + $this->lang('Invalid recipient kind'), + $kind + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if (!static::validateAddress($address)) { + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if ('Reply-To' !== $kind) { + if (!array_key_exists(strtolower($address), $this->all_recipients)) { + $this->{$kind}[] = [$address, $name]; + $this->all_recipients[strtolower($address)] = true; + + return true; + } + } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = [$address, $name]; + + return true; + } + + return false; + } + + /** + * Parse and validate a string containing one or more RFC822-style comma-separated email addresses + * of the form "display name <address>" into an array of name/address pairs. + * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. + * Note that quotes in the name part are removed. + * + * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation + * + * @param string $addrstr The address list string + * @param bool $useimap Whether to use the IMAP extension to parse the list + * + * @return array + */ + public static function parseAddresses($addrstr, $useimap = true) + { + $addresses = []; + if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { + //Use this built-in parser if it's available + $list = imap_rfc822_parse_adrlist($addrstr, ''); + foreach ($list as $address) { + if ( + ('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress( + $address->mailbox . '@' . $address->host + ) + ) { + //Decode the name part if it's present and encoded + if ( + property_exists($address, 'personal') && + extension_loaded('mbstring') && + preg_match('/^=\?.*\?=$/', $address->personal) + ) { + $address->personal = mb_decode_mimeheader($address->personal); + } + + $addresses[] = [ + 'name' => (property_exists($address, 'personal') ? $address->personal : ''), + 'address' => $address->mailbox . '@' . $address->host, + ]; + } + } + } else { + //Use this simpler parser + $list = explode(',', $addrstr); + foreach ($list as $address) { + $address = trim($address); + //Is there a separate name part? + if (strpos($address, '<') === false) { + //No separate name, just use the whole thing + if (static::validateAddress($address)) { + $addresses[] = [ + 'name' => '', + 'address' => $address, + ]; + } + } else { + list($name, $email) = explode('<', $address); + $email = trim(str_replace('>', '', $email)); + $name = trim($name); + if (static::validateAddress($email)) { + //If this name is encoded, decode it + if (preg_match('/^=\?.*\?=$/', $name)) { + $name = mb_decode_mimeheader($name); + } + $addresses[] = [ + //Remove any surrounding quotes and spaces from the name + 'name' => trim($name, '\'" '), + 'address' => $email, + ]; + } + } + } + } + + return $addresses; + } + + /** + * Set the From and FromName properties. + * + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * + * @throws Exception + * + * @return bool + */ + public function setFrom($address, $name = '', $auto = true) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + //Don't validate now addresses with IDN. Will be done in send(). + $pos = strrpos($address, '@'); + if ( + (false === $pos) + || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) + && !static::validateAddress($address)) + ) { + $error_message = sprintf( + '%s (From): %s', + $this->lang('invalid_address'), + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto && empty($this->Sender)) { + $this->Sender = $address; + } + + return true; + } + + /** + * Return the Message-ID header of the last email. + * Technically this is the value from the last time the headers were created, + * but it's also the message ID of the last sent message except in + * pathological cases. + * + * @return string + */ + public function getLastMessageID() + { + return $this->lastMessageID; + } + + /** + * Check that a string looks like an email address. + * Validation patterns supported: + * * `auto` Pick best pattern automatically; + * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; + * * `pcre` Use old PCRE implementation; + * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; + * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. + * * `noregex` Don't use a regex: super fast, really dumb. + * Alternatively you may pass in a callable to inject your own validator, for example: + * + * ```php + * PHPMailer::validateAddress('user@example.com', function($address) { + * return (strpos($address, '@') !== false); + * }); + * ``` + * + * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. + * + * @param string $address The email address to check + * @param string|callable $patternselect Which pattern to use + * + * @return bool + */ + public static function validateAddress($address, $patternselect = null) + { + if (null === $patternselect) { + $patternselect = static::$validator; + } + if (is_callable($patternselect)) { + return call_user_func($patternselect, $address); + } + //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 + if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { + return false; + } + switch ($patternselect) { + case 'pcre': //Kept for BC + case 'pcre8': + /* + * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL + * is based. + * In addition to the addresses allowed by filter_var, also permits: + * * dotless domains: `a@b` + * * comments: `1234 @ local(blah) .machine .example` + * * quoted elements: `'"test blah"@example.org'` + * * numeric TLDs: `a@b.123` + * * unbracketed IPv4 literals: `a@192.168.0.1` + * * IPv6 literals: 'first.last@[IPv6:a1::]' + * Not all of these will necessarily work for sending! + * + * @see http://squiloople.com/2009/12/20/email-address-validation/ + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (bool) preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + case 'html5': + /* + * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. + * + * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) + */ + return (bool) preg_match( + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . + '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', + $address + ); + case 'php': + default: + return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; + } + } + + /** + * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the + * `intl` and `mbstring` PHP extensions. + * + * @return bool `true` if required functions for IDN support are present + */ + public static function idnSupported() + { + return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); + } + + /** + * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. + * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. + * This function silently returns unmodified address if: + * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) + * - Conversion to punycode is impossible (e.g. required PHP functions are not available) + * or fails for any reason (e.g. domain contains characters not allowed in an IDN). + * + * @see PHPMailer::$CharSet + * + * @param string $address The email address to convert + * + * @return string The encoded address in ASCII form + */ + public function punyencodeAddress($address) + { + //Verify we have required functions, CharSet, and at-sign. + $pos = strrpos($address, '@'); + if ( + !empty($this->CharSet) && + false !== $pos && + static::idnSupported() + ) { + $domain = substr($address, ++$pos); + //Verify CharSet string is a valid one, and domain properly encoded in this CharSet. + if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { + //Convert the domain from whatever charset it's in to UTF-8 + $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet); + //Ignore IDE complaints about this line - method signature changed in PHP 5.4 + $errorcode = 0; + if (defined('INTL_IDNA_VARIANT_UTS46')) { + //Use the current punycode standard (appeared in PHP 7.2) + $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_UTS46); + } elseif (defined('INTL_IDNA_VARIANT_2003')) { + //Fall back to this old, deprecated/removed encoding + $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); + } else { + //Fall back to a default we don't know about + $punycode = idn_to_ascii($domain, $errorcode); + } + if (false !== $punycode) { + return substr($address, 0, $pos) . $punycode; + } + } + } + + return $address; + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * + * @throws Exception + * + * @return bool false on error - See the ErrorInfo property for details of the error + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + + return $this->postSend(); + } catch (Exception $exc) { + $this->mailHeader = ''; + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Prepare a message for sending. + * + * @throws Exception + * + * @return bool + */ + public function preSend() + { + if ( + 'smtp' === $this->Mailer + || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) + ) { + //SMTP mandates RFC-compliant line endings + //and it's also used with mail() on Windows + static::setLE(self::CRLF); + } else { + //Maintain backward compatibility with legacy Linux command line mailers + static::setLE(PHP_EOL); + } + //Check for buggy PHP versions that add a header with an incorrect line break + if ( + 'mail' === $this->Mailer + && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) + || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) + && ini_get('mail.add_x_header') === '1' + && stripos(PHP_OS, 'WIN') === 0 + ) { + trigger_error( + 'Your version of PHP is affected by a bug that may result in corrupted messages.' . + ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . + ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', + E_USER_WARNING + ); + } + + try { + $this->error_count = 0; //Reset errors + $this->mailHeader = ''; + + //Dequeue recipient and Reply-To addresses with IDN + foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { + $params[1] = $this->punyencodeAddress($params[1]); + call_user_func_array([$this, 'addAnAddress'], $params); + } + if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { + throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); + } + + //Validate From, Sender, and ConfirmReadingTo addresses + foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { + $this->$address_kind = trim($this->$address_kind); + if (empty($this->$address_kind)) { + continue; + } + $this->$address_kind = $this->punyencodeAddress($this->$address_kind); + if (!static::validateAddress($this->$address_kind)) { + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $address_kind, + $this->$address_kind + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + } + + //Set whether the message is multipart/alternative + if ($this->alternativeExists()) { + $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; + } + + $this->setMessageType(); + //Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty && empty($this->Body)) { + throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + } + + //Trim subject consistently + $this->Subject = trim($this->Subject); + //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) + $this->MIMEHeader = ''; + $this->MIMEBody = $this->createBody(); + //createBody may have added some headers, so retain them + $tempheaders = $this->MIMEHeader; + $this->MIMEHeader = $this->createHeader(); + $this->MIMEHeader .= $tempheaders; + + //To capture the complete message when using mail(), create + //an extra header list which createHeader() doesn't fold in + if ('mail' === $this->Mailer) { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend('To', $this->to); + } else { + $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader($this->Subject)) + ); + } + + //Sign with DKIM if enabled + if ( + !empty($this->DKIM_domain) + && !empty($this->DKIM_selector) + && (!empty($this->DKIM_private_string) + || (!empty($this->DKIM_private) + && static::isPermittedPath($this->DKIM_private) + && file_exists($this->DKIM_private) + ) + ) + ) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . + static::normalizeBreaks($header_dkim) . static::$LE; + } + + return true; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Actually send a message via the selected mechanism. + * + * @throws Exception + * + * @return bool + */ + public function postSend() + { + try { + //Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + case 'qmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + $sendMethod = $this->Mailer . 'Send'; + if (method_exists($this, $sendMethod)) { + return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); + } + + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (Exception $exc) { + if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) { + $this->smtp->reset(); + } + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + } + + return false; + } + + /** + * Send mail using the $Sendmail program. + * + * @see PHPMailer::$Sendmail + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function sendmailSend($header, $body) + { + if ($this->Mailer === 'qmail') { + $this->edebug('Sending with qmail'); + } else { + $this->edebug('Sending with sendmail'); + } + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html + //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html + //Example problem: https://www.drupal.org/node/1057954 + if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { + //PHP config has a sender address we can use + $this->Sender = ini_get('sendmail_from'); + } + //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { + if ($this->Mailer === 'qmail') { + $sendmailFmt = '%s -f%s'; + } else { + $sendmailFmt = '%s -oi -f%s -t'; + } + } else { + //allow sendmail to choose a default envelope sender. It may + //seem preferable to force it to use the From header as with + //SMTP, but that introduces new problems (see + //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and + //it has historically worked this way. + $sendmailFmt = '%s -oi -t'; + } + + $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); + $this->edebug('Sendmail path: ' . $this->Sendmail); + $this->edebug('Sendmail command: ' . $sendmail); + $this->edebug('Envelope sender: ' . $this->Sender); + $this->edebug("Headers: {$header}"); + + if ($this->SingleTo) { + foreach ($this->SingleToArray as $toAddr) { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + $this->edebug("To: {$toAddr}"); + fwrite($mail, 'To: ' . $toAddr . "\n"); + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $addrinfo = static::parseAddresses($toAddr); + $this->doCallback( + ($result === 0), + [[$addrinfo['address'], $addrinfo['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + if (0 !== $result) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result === 0), + $this->to, + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + if (0 !== $result) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + + return true; + } + + /** + * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. + * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. + * + * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report + * + * @param string $string The string to be validated + * + * @return bool + */ + protected static function isShellSafe($string) + { + //Future-proof + if ( + escapeshellcmd($string) !== $string + || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) + ) { + return false; + } + + $length = strlen($string); + + for ($i = 0; $i < $length; ++$i) { + $c = $string[$i]; + + //All other characters have a special meaning in at least one common shell, including = and +. + //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. + //Note that this does permit non-Latin alphanumeric characters based on the current locale. + if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { + return false; + } + } + + return true; + } + + /** + * Check whether a file path is of a permitted type. + * Used to reject URLs and phar files from functions that access local file paths, + * such as addAttachment. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function isPermittedPath($path) + { + //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1 + return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); + } + + /** + * Check whether a file path is safe, accessible, and readable. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function fileIsAccessible($path) + { + if (!static::isPermittedPath($path)) { + return false; + } + $readable = file_exists($path); + //If not a UNC path (expected to start with \\), check read permission, see #2069 + if (strpos($path, '\\\\') !== 0) { + $readable = $readable && is_readable($path); + } + return $readable; + } + + /** + * Send mail using the PHP mail() function. + * + * @see http://www.php.net/manual/en/book.mail.php + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function mailSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + + $toArr = []; + foreach ($this->to as $toaddr) { + $toArr[] = $this->addrFormat($toaddr); + } + $to = implode(', ', $toArr); + + $params = null; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html + //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html + //Example problem: https://www.drupal.org/node/1057954 + //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { + //PHP config has a sender address we can use + $this->Sender = ini_get('sendmail_from'); + } + if (!empty($this->Sender) && static::validateAddress($this->Sender)) { + if (self::isShellSafe($this->Sender)) { + $params = sprintf('-f%s', $this->Sender); + } + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $result = false; + if ($this->SingleTo && count($toArr) > 1) { + foreach ($toArr as $toAddr) { + $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); + $addrinfo = static::parseAddresses($toAddr); + $this->doCallback( + $result, + [[$addrinfo['address'], $addrinfo['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + } + } else { + $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$result) { + throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); + } + + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation, + * or set one with setSMTPInstance. + * + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP(); + } + + return $this->smtp; + } + + /** + * Provide an instance to use for SMTP operations. + * + * @return SMTP + */ + public function setSMTPInstance(SMTP $smtp) + { + $this->smtp = $smtp; + + return $this->smtp; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * + * @see PHPMailer::setSMTPInstance() to use a different class. + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function smtpSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $bad_rcpt = []; + if (!$this->smtpConnect($this->SMTPOptions)) { + throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + //Sender already validated in preSend() + if ('' === $this->Sender) { + $smtp_from = $this->From; + } else { + $smtp_from = $this->Sender; + } + if (!$this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); + } + + $callbacks = []; + //Attempt to send to all recipients + foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { + foreach ($togroup as $to) { + if (!$this->smtp->recipient($to[0], $this->dsn)) { + $error = $this->smtp->getError(); + $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; + $isSent = false; + } else { + $isSent = true; + } + + $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]]; + } + } + + //Only send the DATA command if we have viable recipients + if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { + throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); + } + + $smtp_transaction_id = $this->smtp->getLastTransactionID(); + + if ($this->SMTPKeepAlive) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + + foreach ($callbacks as $cb) { + $this->doCallback( + $cb['issent'], + [[$cb['to'], $cb['name']]], + [], + [], + $this->Subject, + $body, + $this->From, + ['smtp_transaction_id' => $smtp_transaction_id] + ); + } + + //Create error message for any bad addresses + if (count($bad_rcpt) > 0) { + $errstr = ''; + foreach ($bad_rcpt as $bad) { + $errstr .= $bad['to'] . ': ' . $bad['error']; + } + throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); + } + + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * + * @param array $options An array of options compatible with stream_context_create() + * + * @throws Exception + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @return bool + */ + public function smtpConnect($options = null) + { + if (null === $this->smtp) { + $this->smtp = $this->getSMTPInstance(); + } + + //If no options are provided, use whatever is set in the instance + if (null === $options) { + $options = $this->SMTPOptions; + } + + //Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = []; + if ( + !preg_match( + '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', + trim($hostentry), + $hostinfo + ) + ) { + $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); + //Not a valid host entry + continue; + } + //$hostinfo[1]: optional ssl or tls prefix + //$hostinfo[2]: the hostname + //$hostinfo[3]: optional port number + //The host string prefix can temporarily override the current setting for SMTPSecure + //If it's not specified, the default value is used + + //Check the host name is a valid name or IP address before trying to use it + if (!static::isValidHost($hostinfo[2])) { + $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); + continue; + } + $prefix = ''; + $secure = $this->SMTPSecure; + $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); + if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { + $prefix = 'ssl://'; + $tls = false; //Can't have SSL and TLS at the same time + $secure = static::ENCRYPTION_SMTPS; + } elseif ('tls' === $hostinfo[1]) { + $tls = true; + //TLS doesn't use a prefix + $secure = static::ENCRYPTION_STARTTLS; + } + //Do we need the OpenSSL extension? + $sslext = defined('OPENSSL_ALGO_SHA256'); + if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { + //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled + if (!$sslext) { + throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); + } + } + $host = $hostinfo[2]; + $port = $this->Port; + if ( + array_key_exists(3, $hostinfo) && + is_numeric($hostinfo[3]) && + $hostinfo[3] > 0 && + $hostinfo[3] < 65536 + ) { + $port = (int) $hostinfo[3]; + } + if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + //Automatically enable TLS encryption if: + //* it's not disabled + //* we have openssl extension + //* we are not already using SSL + //* the server offers STARTTLS + if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) { + $tls = true; + } + if ($tls) { + if (!$this->smtp->startTLS()) { + throw new Exception($this->lang('connect_host')); + } + //We must resend EHLO after TLS negotiation + $this->smtp->hello($hello); + } + if ( + $this->SMTPAuth && !$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->oauth + ) + ) { + throw new Exception($this->lang('authenticate')); + } + + return true; + } catch (Exception $exc) { + $lastexception = $exc; + $this->edebug($exc->getMessage()); + //We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + //If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + //As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions && null !== $lastexception) { + throw $lastexception; + } + + return false; + } + + /** + * Close the active SMTP session if one exists. + */ + public function smtpClose() + { + if ((null !== $this->smtp) && $this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + + /** + * Set the language for error messages. + * Returns false if it cannot load the language file. + * The default language is English. + * + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * + * @return bool + */ + public function setLanguage($langcode = 'en', $lang_path = '') + { + //Backwards compatibility for renamed language codes + $renamed_langcodes = [ + 'br' => 'pt_br', + 'cz' => 'cs', + 'dk' => 'da', + 'no' => 'nb', + 'se' => 'sv', + 'rs' => 'sr', + 'tg' => 'tl', + 'am' => 'hy', + ]; + + if (array_key_exists($langcode, $renamed_langcodes)) { + $langcode = $renamed_langcodes[$langcode]; + } + + //Define full set of translatable strings in English + $PHPMAILER_LANG = [ + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address: ', + 'invalid_hostentry' => 'Invalid hostentry: ', + 'invalid_host' => 'Invalid host: ', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ', + 'extension_missing' => 'Extension missing: ', + ]; + if (empty($lang_path)) { + //Calculate an absolute path so it can work if CWD is not here + $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; + } + //Validate $langcode + if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { + $langcode = 'en'; + } + $foundlang = true; + $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; + //There is no English translation file + if ('en' !== $langcode) { + //Make sure language file path is readable + if (!static::fileIsAccessible($lang_file)) { + $foundlang = false; + } else { + //Overwrite language-specific strings. + //This way we'll never have missing translation keys. + $foundlang = include $lang_file; + } + } + $this->language = $PHPMAILER_LANG; + + return (bool) $foundlang; //Returns false if language not found + } + + /** + * Get the array of strings for the current language. + * + * @return array + */ + public function getTranslations() + { + return $this->language; + } + + /** + * Create recipient headers. + * + * @param string $type + * @param array $addr An array of recipients, + * where each recipient is a 2-element indexed array with element 0 containing an address + * and element 1 containing a name, like: + * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']] + * + * @return string + */ + public function addrAppend($type, $addr) + { + $addresses = []; + foreach ($addr as $address) { + $addresses[] = $this->addrFormat($address); + } + + return $type . ': ' . implode(', ', $addresses) . static::$LE; + } + + /** + * Format an address for use in a message header. + * + * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like + * ['joe@example.com', 'Joe User'] + * + * @return string + */ + public function addrFormat($addr) + { + if (empty($addr[1])) { //No name provided + return $this->secureHeader($addr[0]); + } + + return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . + ' <' . $this->secureHeader($addr[0]) . '>'; + } + + /** + * Word-wrap message. + * For use with mailers that do not automatically perform wrapping + * and for quoted-printable encoded messages. + * Original written by philippe. + * + * @param string $message The message to wrap + * @param int $length The line length to wrap to + * @param bool $qp_mode Whether to run in Quoted-Printable mode + * + * @return string + */ + public function wrapText($message, $length, $qp_mode = false) + { + if ($qp_mode) { + $soft_break = sprintf(' =%s', static::$LE); + } else { + $soft_break = static::$LE; + } + //If utf-8 encoding is used, we will need to make sure we don't + //split multibyte characters when we wrap + $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet); + $lelen = strlen(static::$LE); + $crlflen = strlen(static::$LE); + + $message = static::normalizeBreaks($message); + //Remove a trailing line break + if (substr($message, -$lelen) === static::$LE) { + $message = substr($message, 0, -$lelen); + } + + //Split message into lines + $lines = explode(static::$LE, $message); + //Message will be rebuilt in here + $message = ''; + foreach ($lines as $line) { + $words = explode(' ', $line); + $buf = ''; + $firstword = true; + foreach ($words as $word) { + if ($qp_mode && (strlen($word) > $length)) { + $space_left = $length - strlen($buf) - $crlflen; + if (!$firstword) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif ('=' === substr($word, $len - 1, 1)) { + --$len; + } elseif ('=' === substr($word, $len - 2, 1)) { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf('=%s', static::$LE); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while ($word !== '') { + if ($length <= 0) { + break; + } + $len = $length; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif ('=' === substr($word, $len - 1, 1)) { + --$len; + } elseif ('=' === substr($word, $len - 2, 1)) { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = (string) substr($word, $len); + + if ($word !== '') { + $message .= $part . sprintf('=%s', static::$LE); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + if (!$firstword) { + $buf .= ' '; + } + $buf .= $word; + + if ('' !== $buf_o && strlen($buf) > $length) { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + $firstword = false; + } + $message .= $buf . static::$LE; + } + + return $message; + } + + /** + * Find the last character boundary prior to $maxLength in a utf-8 + * quoted-printable encoded string. + * Original written by Colin Brown. + * + * @param string $encodedText utf-8 QP text + * @param int $maxLength Find the last character boundary prior to this length + * + * @return int + */ + public function utf8CharBoundary($encodedText, $maxLength) + { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, '='); + if (false !== $encodedCharPos) { + //Found start of encoded character byte within $lookBack block. + //Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { + //Single byte character. + //If the encoded char was found at pos 0, it will fit + //otherwise reduce maxLength to start of the encoded char + if ($encodedCharPos > 0) { + $maxLength -= $lookBack - $encodedCharPos; + } + $foundSplitPos = true; + } elseif ($dec >= 192) { + //First byte of a multi byte character + //Reduce maxLength to split at start of character + $maxLength -= $lookBack - $encodedCharPos; + $foundSplitPos = true; + } elseif ($dec < 192) { + //Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + //No encoded character found + $foundSplitPos = true; + } + } + + return $maxLength; + } + + /** + * Apply word wrapping to the message body. + * Wraps the message body to the number of chars set in the WordWrap property. + * You should only do this to plain-text bodies as wrapping HTML tags may break them. + * This is called automatically by createBody(), so you don't need to call it yourself. + */ + public function setWordWrap() + { + if ($this->WordWrap < 1) { + return; + } + + switch ($this->message_type) { + case 'alt': + case 'alt_inline': + case 'alt_attach': + case 'alt_inline_attach': + $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->wrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assemble message headers. + * + * @return string The assembled headers + */ + public function createHeader() + { + $result = ''; + + $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); + + //The To header is created automatically by mail(), so needs to be omitted here + if ('mail' !== $this->Mailer) { + if ($this->SingleTo) { + foreach ($this->to as $toaddr) { + $this->SingleToArray[] = $this->addrFormat($toaddr); + } + } elseif (count($this->to) > 0) { + $result .= $this->addrAppend('To', $this->to); + } elseif (count($this->cc) === 0) { + $result .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + } + $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]); + + //sendmail and mail() extract Cc from the header before sending + if (count($this->cc) > 0) { + $result .= $this->addrAppend('Cc', $this->cc); + } + + //sendmail and mail() extract Bcc from the header before sending + if ( + ( + 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer + ) + && count($this->bcc) > 0 + ) { + $result .= $this->addrAppend('Bcc', $this->bcc); + } + + if (count($this->ReplyTo) > 0) { + $result .= $this->addrAppend('Reply-To', $this->ReplyTo); + } + + //mail() sets the subject itself + if ('mail' !== $this->Mailer) { + $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); + } + + //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 + //https://tools.ietf.org/html/rfc5322#section-3.6.4 + if ('' !== $this->MessageID && preg_match('/^<.*@.*>$/', $this->MessageID)) { + $this->lastMessageID = $this->MessageID; + } else { + $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); + } + $result .= $this->headerLine('Message-ID', $this->lastMessageID); + if (null !== $this->Priority) { + $result .= $this->headerLine('X-Priority', $this->Priority); + } + if ('' === $this->XMailer) { + $result .= $this->headerLine( + 'X-Mailer', + 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)' + ); + } else { + $myXmailer = trim($this->XMailer); + if ($myXmailer) { + $result .= $this->headerLine('X-Mailer', $myXmailer); + } + } + + if ('' !== $this->ConfirmReadingTo) { + $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); + } + + //Add custom headers + foreach ($this->CustomHeader as $header) { + $result .= $this->headerLine( + trim($header[0]), + $this->encodeHeader(trim($header[1])) + ); + } + if (!$this->sign_key_file) { + $result .= $this->headerLine('MIME-Version', '1.0'); + $result .= $this->getMailMIME(); + } + + return $result; + } + + /** + * Get the message MIME type headers. + * + * @return string + */ + public function getMailMIME() + { + $result = ''; + $ismultipart = true; + switch ($this->message_type) { + case 'inline': + $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); + break; + case 'attach': + case 'inline_attach': + case 'alt_attach': + case 'alt_inline_attach': + $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';'); + $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); + break; + case 'alt': + case 'alt_inline': + $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); + $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); + break; + default: + //Catches case 'plain': and case '': + $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); + $ismultipart = false; + break; + } + //RFC1341 part 5 says 7bit is assumed if not specified + if (static::ENCODING_7BIT !== $this->Encoding) { + //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE + if ($ismultipart) { + if (static::ENCODING_8BIT === $this->Encoding) { + $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); + } + //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible + } else { + $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); + } + } + + return $result; + } + + /** + * Returns the whole MIME message. + * Includes complete headers and body. + * Only valid post preSend(). + * + * @see PHPMailer::preSend() + * + * @return string + */ + public function getSentMIMEMessage() + { + return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) . + static::$LE . static::$LE . $this->MIMEBody; + } + + /** + * Create a unique ID to use for boundaries. + * + * @return string + */ + protected function generateId() + { + $len = 32; //32 bytes = 256 bits + $bytes = ''; + if (function_exists('random_bytes')) { + try { + $bytes = random_bytes($len); + } catch (\Exception $e) { + //Do nothing + } + } elseif (function_exists('openssl_random_pseudo_bytes')) { + /** @noinspection CryptographicallySecureRandomnessInspection */ + $bytes = openssl_random_pseudo_bytes($len); + } + if ($bytes === '') { + //We failed to produce a proper random string, so make do. + //Use a hash to force the length to the same as the other methods + $bytes = hash('sha256', uniqid((string) mt_rand(), true), true); + } + + //We don't care about messing up base64 format here, just want a random string + return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true))); + } + + /** + * Assemble the message body. + * Returns an empty string on failure. + * + * @throws Exception + * + * @return string The assembled message body + */ + public function createBody() + { + $body = ''; + //Create unique IDs and preset boundaries + $this->uniqueid = $this->generateId(); + $this->boundary[1] = 'b1_' . $this->uniqueid; + $this->boundary[2] = 'b2_' . $this->uniqueid; + $this->boundary[3] = 'b3_' . $this->uniqueid; + + if ($this->sign_key_file) { + $body .= $this->getMailMIME() . static::$LE; + } + + $this->setWordWrap(); + + $bodyEncoding = $this->Encoding; + $bodyCharSet = $this->CharSet; + //Can we do a 7-bit downgrade? + if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) { + $bodyEncoding = static::ENCODING_7BIT; + //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit + $bodyCharSet = static::CHARSET_ASCII; + } + //If lines are too long, and we're not already using an encoding that will shorten them, + //change to quoted-printable transfer encoding for the body part only + if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) { + $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE; + } + + $altBodyEncoding = $this->Encoding; + $altBodyCharSet = $this->CharSet; + //Can we do a 7-bit downgrade? + if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) { + $altBodyEncoding = static::ENCODING_7BIT; + //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit + $altBodyCharSet = static::CHARSET_ASCII; + } + //If lines are too long, and we're not already using an encoding that will shorten them, + //change to quoted-printable transfer encoding for the alt body part only + if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { + $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; + } + //Use this as a preamble in all multipart message types + $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE; + switch ($this->message_type) { + case 'inline': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[1]); + break; + case 'attach': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'inline_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); + $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); + $body .= static::$LE; + $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt': + $body .= $mimepre; + $body .= $this->getBoundary( + $this->boundary[1], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[1], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + if (!empty($this->Ical)) { + $method = static::ICAL_METHOD_REQUEST; + foreach (static::$IcalMethods as $imethod) { + if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { + $method = $imethod; + break; + } + } + $body .= $this->getBoundary( + $this->boundary[1], + '', + static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, + '' + ); + $body .= $this->encodeString($this->Ical, $this->Encoding); + $body .= static::$LE; + } + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_inline': + $body .= $mimepre; + $body .= $this->getBoundary( + $this->boundary[1], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); + $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= static::$LE; + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + if (!empty($this->Ical)) { + $method = static::ICAL_METHOD_REQUEST; + foreach (static::$IcalMethods as $imethod) { + if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { + $method = $imethod; + break; + } + } + $body .= $this->getBoundary( + $this->boundary[2], + '', + static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, + '' + ); + $body .= $this->encodeString($this->Ical, $this->Encoding); + } + $body .= $this->endBoundary($this->boundary[2]); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt_inline_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->textLine('--' . $this->boundary[2]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";'); + $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[3], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[3]); + $body .= static::$LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + default: + //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types + //Reset the `Encoding` property in case we changed it for line length reasons + $this->Encoding = $bodyEncoding; + $body .= $this->encodeString($this->Body, $this->Encoding); + break; + } + + if ($this->isError()) { + $body = ''; + if ($this->exceptions) { + throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + } + } elseif ($this->sign_key_file) { + try { + if (!defined('PKCS7_TEXT')) { + throw new Exception($this->lang('extension_missing') . 'openssl'); + } + + $file = tempnam(sys_get_temp_dir(), 'srcsign'); + $signed = tempnam(sys_get_temp_dir(), 'mailsign'); + file_put_contents($file, $body); + + //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 + if (empty($this->sign_extracerts_file)) { + $sign = @openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], + [] + ); + } else { + $sign = @openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], + [], + PKCS7_DETACHED, + $this->sign_extracerts_file + ); + } + + @unlink($file); + if ($sign) { + $body = file_get_contents($signed); + @unlink($signed); + //The message returned by openssl contains both headers and body, so need to split them up + $parts = explode("\n\n", $body, 2); + $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; + $body = $parts[1]; + } else { + @unlink($signed); + throw new Exception($this->lang('signing') . openssl_error_string()); + } + } catch (Exception $exc) { + $body = ''; + if ($this->exceptions) { + throw $exc; + } + } + } + + return $body; + } + + /** + * Return the start of a message boundary. + * + * @param string $boundary + * @param string $charSet + * @param string $contentType + * @param string $encoding + * + * @return string + */ + protected function getBoundary($boundary, $charSet, $contentType, $encoding) + { + $result = ''; + if ('' === $charSet) { + $charSet = $this->CharSet; + } + if ('' === $contentType) { + $contentType = $this->ContentType; + } + if ('' === $encoding) { + $encoding = $this->Encoding; + } + $result .= $this->textLine('--' . $boundary); + $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); + $result .= static::$LE; + //RFC1341 part 5 says 7bit is assumed if not specified + if (static::ENCODING_7BIT !== $encoding) { + $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); + } + $result .= static::$LE; + + return $result; + } + + /** + * Return the end of a message boundary. + * + * @param string $boundary + * + * @return string + */ + protected function endBoundary($boundary) + { + return static::$LE . '--' . $boundary . '--' . static::$LE; + } + + /** + * Set the message type. + * PHPMailer only supports some preset message types, not arbitrary MIME structures. + */ + protected function setMessageType() + { + $type = []; + if ($this->alternativeExists()) { + $type[] = 'alt'; + } + if ($this->inlineImageExists()) { + $type[] = 'inline'; + } + if ($this->attachmentExists()) { + $type[] = 'attach'; + } + $this->message_type = implode('_', $type); + if ('' === $this->message_type) { + //The 'plain' message_type refers to the message having a single body element, not that it is plain-text + $this->message_type = 'plain'; + } + } + + /** + * Format a header line. + * + * @param string $name + * @param string|int $value + * + * @return string + */ + public function headerLine($name, $value) + { + return $name . ': ' . $value . static::$LE; + } + + /** + * Return a formatted mail line. + * + * @param string $value + * + * @return string + */ + public function textLine($value) + { + return $value . static::$LE; + } + + /** + * Add an attachment from a path on the filesystem. + * Never use a user-supplied path to a file! + * Returns false if the file could not be found or read. + * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. + * If you need to do that, fetch the resource yourself and pass it in via a local file or string. + * + * @param string $path Path to the attachment + * @param string $name Overrides the attachment name + * @param string $encoding File encoding (see $Encoding) + * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool + */ + public function addAttachment( + $path, + $name = '', + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'attachment' + ) { + try { + if (!static::fileIsAccessible($path)) { + throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + //If a MIME type is not specified, try to work it out from the file name + if ('' === $type) { + $type = static::filenameToType($path); + } + + $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); + if ('' === $name) { + $name = $filename; + } + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + $this->attachment[] = [ + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, //isStringAttachment + 6 => $disposition, + 7 => $name, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Return the array of attachments. + * + * @return array + */ + public function getAttachments() + { + return $this->attachment; + } + + /** + * Attach all file, string, and binary attachments to the message. + * Returns an empty string on failure. + * + * @param string $disposition_type + * @param string $boundary + * + * @throws Exception + * + * @return string + */ + protected function attachAll($disposition_type, $boundary) + { + //Return text of body + $mime = []; + $cidUniq = []; + $incl = []; + + //Add all attachments + foreach ($this->attachment as $attachment) { + //Check if it is a valid disposition_filter + if ($attachment[6] === $disposition_type) { + //Check for string attachment + $string = ''; + $path = ''; + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + $inclhash = hash('sha256', serialize($attachment)); + if (in_array($inclhash, $incl, true)) { + continue; + } + $incl[] = $inclhash; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) { + continue; + } + $cidUniq[$cid] = true; + + $mime[] = sprintf('--%s%s', $boundary, static::$LE); + //Only include a filename property if we have one + if (!empty($name)) { + $mime[] = sprintf( + 'Content-Type: %s; name=%s%s', + $type, + static::quotedString($this->encodeHeader($this->secureHeader($name))), + static::$LE + ); + } else { + $mime[] = sprintf( + 'Content-Type: %s%s', + $type, + static::$LE + ); + } + //RFC1341 part 5 says 7bit is assumed if not specified + if (static::ENCODING_7BIT !== $encoding) { + $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE); + } + + //Only set Content-IDs on inline attachments + if ((string) $cid !== '' && $disposition === 'inline') { + $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE; + } + + //Allow for bypassing the Content-Disposition header + if (!empty($disposition)) { + $encoded_name = $this->encodeHeader($this->secureHeader($name)); + if (!empty($encoded_name)) { + $mime[] = sprintf( + 'Content-Disposition: %s; filename=%s%s', + $disposition, + static::quotedString($encoded_name), + static::$LE . static::$LE + ); + } else { + $mime[] = sprintf( + 'Content-Disposition: %s%s', + $disposition, + static::$LE . static::$LE + ); + } + } else { + $mime[] = static::$LE; + } + + //Encode as string attachment + if ($bString) { + $mime[] = $this->encodeString($string, $encoding); + } else { + $mime[] = $this->encodeFile($path, $encoding); + } + if ($this->isError()) { + return ''; + } + $mime[] = static::$LE; + } + } + + $mime[] = sprintf('--%s--%s', $boundary, static::$LE); + + return implode('', $mime); + } + + /** + * Encode a file attachment in requested format. + * Returns an empty string on failure. + * + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * + * @return string + */ + protected function encodeFile($path, $encoding = self::ENCODING_BASE64) + { + try { + if (!static::fileIsAccessible($path)) { + throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $file_buffer = file_get_contents($path); + if (false === $file_buffer) { + throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $file_buffer = $this->encodeString($file_buffer, $encoding); + + return $file_buffer; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return ''; + } + } + + /** + * Encode a string in requested format. + * Returns an empty string on failure. + * + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * + * @throws Exception + * + * @return string + */ + public function encodeString($str, $encoding = self::ENCODING_BASE64) + { + $encoded = ''; + switch (strtolower($encoding)) { + case static::ENCODING_BASE64: + $encoded = chunk_split( + base64_encode($str), + static::STD_LINE_LENGTH, + static::$LE + ); + break; + case static::ENCODING_7BIT: + case static::ENCODING_8BIT: + $encoded = static::normalizeBreaks($str); + //Make sure it ends with a line break + if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) { + $encoded .= static::$LE; + } + break; + case static::ENCODING_BINARY: + $encoded = $str; + break; + case static::ENCODING_QUOTED_PRINTABLE: + $encoded = $this->encodeQP($str); + break; + default: + $this->setError($this->lang('encoding') . $encoding); + if ($this->exceptions) { + throw new Exception($this->lang('encoding') . $encoding); + } + break; + } + + return $encoded; + } + + /** + * Encode a header value (not including its label) optimally. + * Picks shortest of Q, B, or none. Result includes folding if needed. + * See RFC822 definitions for phrase, comment and text positions. + * + * @param string $str The header value to encode + * @param string $position What context the string will be used in + * + * @return string + */ + public function encodeHeader($str, $position = 'text') + { + $matchcount = 0; + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + //Can't use addslashes as we don't know the value of magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return $encoded; + } + + return "\"$encoded\""; + } + $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + /* @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $matchcount = preg_match_all('/[()"]/', $str, $matches); + //fallthrough + case 'text': + default: + $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($this->has8bitChars($str)) { + $charset = $this->CharSet; + } else { + $charset = static::CHARSET_ASCII; + } + + //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`"). + $overhead = 8 + strlen($charset); + + if ('mail' === $this->Mailer) { + $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead; + } else { + $maxlen = static::MAX_LINE_LENGTH - $overhead; + } + + //Select the encoding that produces the shortest output and/or prevents corruption. + if ($matchcount > strlen($str) / 3) { + //More than 1/3 of the content needs encoding, use B-encode. + $encoding = 'B'; + } elseif ($matchcount > 0) { + //Less than 1/3 of the content needs encoding, use Q-encode. + $encoding = 'Q'; + } elseif (strlen($str) > $maxlen) { + //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption. + $encoding = 'Q'; + } else { + //No reformatting needed + $encoding = false; + } + + switch ($encoding) { + case 'B': + if ($this->hasMultiBytes($str)) { + //Use a custom function which correctly encodes and wraps long + //multibyte strings without breaking lines within a character + $encoded = $this->base64EncodeWrapMB($str, "\n"); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); + break; + case 'Q': + $encoded = $this->encodeQ($str, $position); + $encoded = $this->wrapText($encoded, $maxlen, true); + $encoded = str_replace('=' . static::$LE, "\n", trim($encoded)); + $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); + break; + default: + return $str; + } + + return trim(static::normalizeBreaks($encoded)); + } + + /** + * Check if a string contains multi-byte characters. + * + * @param string $str multi-byte text to wrap encode + * + * @return bool + */ + public function hasMultiBytes($str) + { + if (function_exists('mb_strlen')) { + return strlen($str) > mb_strlen($str, $this->CharSet); + } + + //Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + + /** + * Does a string contain any 8-bit chars (in any charset)? + * + * @param string $text + * + * @return bool + */ + public function has8bitChars($text) + { + return (bool) preg_match('/[\x80-\xFF]/', $text); + } + + /** + * Encode and wrap long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid. + * + * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 + * + * @param string $str multi-byte text to wrap encode + * @param string $linebreak string to use as linefeed/end-of-line + * + * @return string + */ + public function base64EncodeWrapMB($str, $linebreak = null) + { + $start = '=?' . $this->CharSet . '?B?'; + $end = '?='; + $encoded = ''; + if (null === $linebreak) { + $linebreak = static::$LE; + } + + $mb_length = mb_strlen($str, $this->CharSet); + //Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + //Average multi-byte ratio + $ratio = $mb_length / strlen($str); + //Base64 has a 4:3 ratio + $avgLength = floor($length * $ratio * .75); + + $offset = 0; + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + ++$lookBack; + } while (strlen($chunk) > $length); + $encoded .= $chunk . $linebreak; + } + + //Chomp the last linefeed + return substr($encoded, 0, -strlen($linebreak)); + } + + /** + * Encode a string in quoted-printable format. + * According to RFC2045 section 6.7. + * + * @param string $string The text to encode + * + * @return string + */ + public function encodeQP($string) + { + return static::normalizeBreaks(quoted_printable_encode($string)); + } + + /** + * Encode a string using Q encoding. + * + * @see http://tools.ietf.org/html/rfc2047#section-4.2 + * + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * + * @return string + */ + public function encodeQ($str, $position = 'text') + { + //There should not be any EOL in the string + $pattern = ''; + $encoded = str_replace(["\r", "\n"], '', $str); + switch (strtolower($position)) { + case 'phrase': + //RFC 2047 section 5.3 + $pattern = '^A-Za-z0-9!*+\/ -'; + break; + /* + * RFC 2047 section 5.2. + * Build $pattern without including delimiters and [] + */ + /* @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $pattern = '\(\)"'; + /* Intentional fall through */ + case 'text': + default: + //RFC 2047 section 5.1 + //Replace every high ascii, control, =, ? and _ characters + $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; + break; + } + $matches = []; + if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { + //If the string contains an '=', make sure it's the first thing we replace + //so as to avoid double-encoding + $eqkey = array_search('=', $matches[0], true); + if (false !== $eqkey) { + unset($matches[0][$eqkey]); + array_unshift($matches[0], '='); + } + foreach (array_unique($matches[0]) as $char) { + $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); + } + } + //Replace spaces with _ (more readable than =20) + //RFC 2047 section 4.2(2) + return str_replace(' ', '_', $encoded); + } + + /** + * Add a string or binary attachment (non-filesystem). + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * + * @param string $string String attachment data + * @param string $filename Name of the attachment + * @param string $encoding File encoding (see $Encoding) + * @param string $type File extension (MIME) type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool True on successfully adding an attachment + */ + public function addStringAttachment( + $string, + $filename, + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'attachment' + ) { + try { + //If a MIME type is not specified, try to work it out from the file name + if ('' === $type) { + $type = static::filenameToType($filename); + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + //Append to $attachment array + $this->attachment[] = [ + 0 => $string, + 1 => $filename, + 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME), + 3 => $encoding, + 4 => $type, + 5 => true, //isStringAttachment + 6 => $disposition, + 7 => 0, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Add an embedded (inline) attachment from a file. + * This can include images, sounds, and just about any other document type. + * These differ from 'regular' attachments in that they are intended to be + * displayed inline with the message, not just attached for download. + * This is used in HTML messages that embed the images + * the HTML refers to using the $cid value. + * Never use a user-supplied path to a file! + * + * @param string $path Path to the attachment + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML + * @param string $name Overrides the attachment name + * @param string $encoding File encoding (see $Encoding) + * @param string $type File MIME type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool True on successfully adding an attachment + */ + public function addEmbeddedImage( + $path, + $cid, + $name = '', + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'inline' + ) { + try { + if (!static::fileIsAccessible($path)) { + throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + //If a MIME type is not specified, try to work it out from the file name + if ('' === $type) { + $type = static::filenameToType($path); + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); + if ('' === $name) { + $name = $filename; + } + + //Append to $attachment array + $this->attachment[] = [ + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, //isStringAttachment + 6 => $disposition, + 7 => $cid, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Add an embedded stringified attachment. + * This can include images, sounds, and just about any other document type. + * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type. + * + * @param string $string The attachment binary data + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML + * @param string $name A filename for the attachment. If this contains an extension, + * PHPMailer will attempt to set a MIME type for the attachment. + * For example 'file.jpg' would get an 'image/jpeg' MIME type. + * @param string $encoding File encoding (see $Encoding), defaults to 'base64' + * @param string $type MIME type - will be used in preference to any automatically derived type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool True on successfully adding an attachment + */ + public function addStringEmbeddedImage( + $string, + $cid, + $name = '', + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'inline' + ) { + try { + //If a MIME type is not specified, try to work it out from the name + if ('' === $type && !empty($name)) { + $type = static::filenameToType($name); + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + //Append to $attachment array + $this->attachment[] = [ + 0 => $string, + 1 => $name, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => true, //isStringAttachment + 6 => $disposition, + 7 => $cid, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Validate encodings. + * + * @param string $encoding + * + * @return bool + */ + protected function validateEncoding($encoding) + { + return in_array( + $encoding, + [ + self::ENCODING_7BIT, + self::ENCODING_QUOTED_PRINTABLE, + self::ENCODING_BASE64, + self::ENCODING_8BIT, + self::ENCODING_BINARY, + ], + true + ); + } + + /** + * Check if an embedded attachment is present with this cid. + * + * @param string $cid + * + * @return bool + */ + protected function cidExists($cid) + { + foreach ($this->attachment as $attachment) { + if ('inline' === $attachment[6] && $cid === $attachment[7]) { + return true; + } + } + + return false; + } + + /** + * Check if an inline attachment is present. + * + * @return bool + */ + public function inlineImageExists() + { + foreach ($this->attachment as $attachment) { + if ('inline' === $attachment[6]) { + return true; + } + } + + return false; + } + + /** + * Check if an attachment (non-inline) is present. + * + * @return bool + */ + public function attachmentExists() + { + foreach ($this->attachment as $attachment) { + if ('attachment' === $attachment[6]) { + return true; + } + } + + return false; + } + + /** + * Check if this message has an alternative body set. + * + * @return bool + */ + public function alternativeExists() + { + return !empty($this->AltBody); + } + + /** + * Clear queued addresses of given kind. + * + * @param string $kind 'to', 'cc', or 'bcc' + */ + public function clearQueuedAddresses($kind) + { + $this->RecipientsQueue = array_filter( + $this->RecipientsQueue, + static function ($params) use ($kind) { + return $params[0] !== $kind; + } + ); + } + + /** + * Clear all To recipients. + */ + public function clearAddresses() + { + foreach ($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = []; + $this->clearQueuedAddresses('to'); + } + + /** + * Clear all CC recipients. + */ + public function clearCCs() + { + foreach ($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = []; + $this->clearQueuedAddresses('cc'); + } + + /** + * Clear all BCC recipients. + */ + public function clearBCCs() + { + foreach ($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = []; + $this->clearQueuedAddresses('bcc'); + } + + /** + * Clear all ReplyTo recipients. + */ + public function clearReplyTos() + { + $this->ReplyTo = []; + $this->ReplyToQueue = []; + } + + /** + * Clear all recipient types. + */ + public function clearAllRecipients() + { + $this->to = []; + $this->cc = []; + $this->bcc = []; + $this->all_recipients = []; + $this->RecipientsQueue = []; + } + + /** + * Clear all filesystem, string, and binary attachments. + */ + public function clearAttachments() + { + $this->attachment = []; + } + + /** + * Clear all custom headers. + */ + public function clearCustomHeaders() + { + $this->CustomHeader = []; + } + + /** + * Add an error message to the error container. + * + * @param string $msg + */ + protected function setError($msg) + { + ++$this->error_count; + if ('smtp' === $this->Mailer && null !== $this->smtp) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror['error'])) { + $msg .= $this->lang('smtp_error') . $lasterror['error']; + if (!empty($lasterror['detail'])) { + $msg .= ' Detail: ' . $lasterror['detail']; + } + if (!empty($lasterror['smtp_code'])) { + $msg .= ' SMTP code: ' . $lasterror['smtp_code']; + } + if (!empty($lasterror['smtp_code_ex'])) { + $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; + } + } + } + $this->ErrorInfo = $msg; + } + + /** + * Return an RFC 822 formatted date. + * + * @return string + */ + public static function rfcDate() + { + //Set the time zone to whatever the default is to avoid 500 errors + //Will default to UTC if it's not set properly in php.ini + date_default_timezone_set(@date_default_timezone_get()); + + return date('D, j M Y H:i:s O'); + } + + /** + * Get the server hostname. + * Returns 'localhost.localdomain' if unknown. + * + * @return string + */ + protected function serverHostname() + { + $result = ''; + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { + $result = $_SERVER['SERVER_NAME']; + } elseif (function_exists('gethostname') && gethostname() !== false) { + $result = gethostname(); + } elseif (php_uname('n') !== false) { + $result = php_uname('n'); + } + if (!static::isValidHost($result)) { + return 'localhost.localdomain'; + } + + return $result; + } + + /** + * Validate whether a string contains a valid value to use as a hostname or IP address. + * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`. + * + * @param string $host The host name or IP address to check + * + * @return bool + */ + public static function isValidHost($host) + { + //Simple syntax limits + if ( + empty($host) + || !is_string($host) + || strlen($host) > 256 + || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+])$/', $host) + ) { + return false; + } + //Looks like a bracketed IPv6 address + if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') { + return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + } + //If removing all the dots results in a numeric string, it must be an IPv4 address. + //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names + if (is_numeric(str_replace('.', '', $host))) { + //Is it a valid IPv4 address? + return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; + } + if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) { + //Is it a syntactically valid hostname? + return true; + } + + return false; + } + + /** + * Get an error message in the current language. + * + * @param string $key + * + * @return string + */ + protected function lang($key) + { + if (count($this->language) < 1) { + $this->setLanguage(); //Set the default language + } + + if (array_key_exists($key, $this->language)) { + if ('smtp_connect_failed' === $key) { + //Include a link to troubleshooting docs on SMTP connection failure. + //This is by far the biggest cause of support questions + //but it's usually not PHPMailer's fault. + return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; + } + + return $this->language[$key]; + } + + //Return the key as a fallback + return $key; + } + + /** + * Check if an error occurred. + * + * @return bool True if an error did occur + */ + public function isError() + { + return $this->error_count > 0; + } + + /** + * Add a custom header. + * $name value can be overloaded to contain + * both header name and value (name:value). + * + * @param string $name Custom header name + * @param string|null $value Header value + * + * @throws Exception + */ + public function addCustomHeader($name, $value = null) + { + if (null === $value && strpos($name, ':') !== false) { + //Value passed in as name:value + list($name, $value) = explode(':', $name, 2); + } + $name = trim($name); + $value = trim($value); + //Ensure name is not empty, and that neither name nor value contain line breaks + if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { + if ($this->exceptions) { + throw new Exception('Invalid header name or value'); + } + + return false; + } + $this->CustomHeader[] = [$name, $value]; + + return true; + } + + /** + * Returns all custom headers. + * + * @return array + */ + public function getCustomHeaders() + { + return $this->CustomHeader; + } + + /** + * Create a message body from an HTML string. + * Automatically inlines images and creates a plain-text version by converting the HTML, + * overwriting any existing values in Body and AltBody. + * Do not source $message content from user input! + * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty + * will look for an image file in $basedir/images/a.png and convert it to inline. + * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) + * Converts data-uri images into embedded attachments. + * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. + * + * @param string $message HTML message string + * @param string $basedir Absolute path to a base directory to prepend to relative paths to images + * @param bool|callable $advanced Whether to use the internal HTML to text converter + * or your own custom converter + * @return string The transformed message body + * + * @throws Exception + * + * @see PHPMailer::html2text() + */ + public function msgHTML($message, $basedir = '', $advanced = false) + { + preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images); + if (array_key_exists(2, $images)) { + if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { + //Ensure $basedir has a trailing / + $basedir .= '/'; + } + foreach ($images[2] as $imgindex => $url) { + //Convert data URIs into embedded images + //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" + $match = []; + if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) { + if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) { + $data = base64_decode($match[3]); + } elseif ('' === $match[2]) { + $data = rawurldecode($match[3]); + } else { + //Not recognised so leave it alone + continue; + } + //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places + //will only be embedded once, even if it used a different encoding + $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2 + + if (!$this->cidExists($cid)) { + $this->addStringEmbeddedImage( + $data, + $cid, + 'embed' . $imgindex, + static::ENCODING_BASE64, + $match[1] + ); + } + $message = str_replace( + $images[0][$imgindex], + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + continue; + } + if ( + //Only process relative URLs if a basedir is provided (i.e. no absolute local paths) + !empty($basedir) + //Ignore URLs containing parent dir traversal (..) + && (strpos($url, '..') === false) + //Do not change urls that are already inline images + && 0 !== strpos($url, 'cid:') + //Do not change absolute URLs, including anonymous protocol + && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) + ) { + $filename = static::mb_pathinfo($url, PATHINFO_BASENAME); + $directory = dirname($url); + if ('.' === $directory) { + $directory = ''; + } + //RFC2392 S 2 + $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; + if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { + $basedir .= '/'; + } + if (strlen($directory) > 1 && '/' !== substr($directory, -1)) { + $directory .= '/'; + } + if ( + $this->addEmbeddedImage( + $basedir . $directory . $filename, + $cid, + $filename, + static::ENCODING_BASE64, + static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)) + ) + ) { + $message = preg_replace( + '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + } + } + } + } + $this->isHTML(); + //Convert all message body line breaks to LE, makes quoted-printable encoding work much better + $this->Body = static::normalizeBreaks($message); + $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced)); + if (!$this->alternativeExists()) { + $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.' + . static::$LE; + } + + return $this->Body; + } + + /** + * Convert an HTML string into plain text. + * This is used by msgHTML(). + * Note - older versions of this function used a bundled advanced converter + * which was removed for license reasons in #232. + * Example usage: + * + * ```php + * //Use default conversion + * $plain = $mail->html2text($html); + * //Use your own custom converter + * $plain = $mail->html2text($html, function($html) { + * $converter = new MyHtml2text($html); + * return $converter->get_text(); + * }); + * ``` + * + * @param string $html The HTML text to convert + * @param bool|callable $advanced Any boolean value to use the internal converter, + * or provide your own callable for custom conversion + * + * @return string + */ + public function html2text($html, $advanced = false) + { + if (is_callable($advanced)) { + return call_user_func($advanced, $html); + } + + return html_entity_decode( + trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), + ENT_QUOTES, + $this->CharSet + ); + } + + /** + * Get the MIME type for a file extension. + * + * @param string $ext File extension + * + * @return string MIME type of file + */ + public static function _mime_types($ext = '') + { + $mimes = [ + 'xl' => 'application/excel', + 'js' => 'application/javascript', + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'bin' => 'application/macbinary', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'class' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'm4a' => 'audio/mp4', + 'mpga' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'wav' => 'audio/x-wav', + 'mka' => 'audio/x-matroska', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'eml' => 'message/rfc822', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'log' => 'text/plain', + 'text' => 'text/plain', + 'txt' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'vcf' => 'text/vcard', + 'vcard' => 'text/vcard', + 'ics' => 'text/calendar', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'wmv' => 'video/x-ms-wmv', + 'mpeg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mp4' => 'video/mp4', + 'm4v' => 'video/mp4', + 'mov' => 'video/quicktime', + 'qt' => 'video/quicktime', + 'rv' => 'video/vnd.rn-realvideo', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'webm' => 'video/webm', + 'mkv' => 'video/x-matroska', + ]; + $ext = strtolower($ext); + if (array_key_exists($ext, $mimes)) { + return $mimes[$ext]; + } + + return 'application/octet-stream'; + } + + /** + * Map a file name to a MIME type. + * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. + * + * @param string $filename A file name or full path, does not need to exist as a file + * + * @return string + */ + public static function filenameToType($filename) + { + //In case the path is a URL, strip any query string before getting extension + $qpos = strpos($filename, '?'); + if (false !== $qpos) { + $filename = substr($filename, 0, $qpos); + } + $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION); + + return static::_mime_types($ext); + } + + /** + * Multi-byte-safe pathinfo replacement. + * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe. + * + * @see http://www.php.net/manual/en/function.pathinfo.php#107461 + * + * @param string $path A filename or path, does not need to exist as a file + * @param int|string $options Either a PATHINFO_* constant, + * or a string name to return only the specified piece + * + * @return string|array + */ + public static function mb_pathinfo($path, $options = null) + { + $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '']; + $pathinfo = []; + if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) { + if (array_key_exists(1, $pathinfo)) { + $ret['dirname'] = $pathinfo[1]; + } + if (array_key_exists(2, $pathinfo)) { + $ret['basename'] = $pathinfo[2]; + } + if (array_key_exists(5, $pathinfo)) { + $ret['extension'] = $pathinfo[5]; + } + if (array_key_exists(3, $pathinfo)) { + $ret['filename'] = $pathinfo[3]; + } + } + switch ($options) { + case PATHINFO_DIRNAME: + case 'dirname': + return $ret['dirname']; + case PATHINFO_BASENAME: + case 'basename': + return $ret['basename']; + case PATHINFO_EXTENSION: + case 'extension': + return $ret['extension']; + case PATHINFO_FILENAME: + case 'filename': + return $ret['filename']; + default: + return $ret; + } + } + + /** + * Set or reset instance properties. + * You should avoid this function - it's more verbose, less efficient, more error-prone and + * harder to debug than setting properties directly. + * Usage Example: + * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);` + * is the same as: + * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`. + * + * @param string $name The property name to set + * @param mixed $value The value to set the property to + * + * @return bool + */ + public function set($name, $value = '') + { + if (property_exists($this, $name)) { + $this->$name = $value; + + return true; + } + $this->setError($this->lang('variable_set') . $name); + + return false; + } + + /** + * Strip newlines to prevent header injection. + * + * @param string $str + * + * @return string + */ + public function secureHeader($str) + { + return trim(str_replace(["\r", "\n"], '', $str)); + } + + /** + * Normalize line breaks in a string. + * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. + * Defaults to CRLF (for message bodies) and preserves consecutive breaks. + * + * @param string $text + * @param string $breaktype What kind of line break to use; defaults to static::$LE + * + * @return string + */ + public static function normalizeBreaks($text, $breaktype = null) + { + if (null === $breaktype) { + $breaktype = static::$LE; + } + //Normalise to \n + $text = str_replace([self::CRLF, "\r"], "\n", $text); + //Now convert LE as needed + if ("\n" !== $breaktype) { + $text = str_replace("\n", $breaktype, $text); + } + + return $text; + } + + /** + * Remove trailing breaks from a string. + * + * @param string $text + * + * @return string The text to remove breaks from + */ + public static function stripTrailingWSP($text) + { + return rtrim($text, " \r\n\t"); + } + + /** + * Return the current line break format string. + * + * @return string + */ + public static function getLE() + { + return static::$LE; + } + + /** + * Set the line break format string, e.g. "\r\n". + * + * @param string $le + */ + protected static function setLE($le) + { + static::$LE = $le; + } + + /** + * Set the public and private key files and password for S/MIME signing. + * + * @param string $cert_filename + * @param string $key_filename + * @param string $key_pass Password for private key + * @param string $extracerts_filename Optional path to chain certificate + */ + public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') + { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + $this->sign_extracerts_file = $extracerts_filename; + } + + /** + * Quoted-Printable-encode a DKIM header. + * + * @param string $txt + * + * @return string + */ + public function DKIM_QP($txt) + { + $line = ''; + $len = strlen($txt); + for ($i = 0; $i < $len; ++$i) { + $ord = ord($txt[$i]); + if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { + $line .= $txt[$i]; + } else { + $line .= '=' . sprintf('%02X', $ord); + } + } + + return $line; + } + + /** + * Generate a DKIM signature. + * + * @param string $signHeader + * + * @throws Exception + * + * @return string The DKIM signature value + */ + public function DKIM_Sign($signHeader) + { + if (!defined('PKCS7_TEXT')) { + if ($this->exceptions) { + throw new Exception($this->lang('extension_missing') . 'openssl'); + } + + return ''; + } + $privKeyStr = !empty($this->DKIM_private_string) ? + $this->DKIM_private_string : + file_get_contents($this->DKIM_private); + if ('' !== $this->DKIM_passphrase) { + $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); + } else { + $privKey = openssl_pkey_get_private($privKeyStr); + } + if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { + if (\PHP_MAJOR_VERSION < 8) { + openssl_pkey_free($privKey); + } + + return base64_encode($signature); + } + if (\PHP_MAJOR_VERSION < 8) { + openssl_pkey_free($privKey); + } + + return ''; + } + + /** + * Generate a DKIM canonicalization header. + * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. + * Canonicalized headers should *always* use CRLF, regardless of mailer setting. + * + * @see https://tools.ietf.org/html/rfc6376#section-3.4.2 + * + * @param string $signHeader Header + * + * @return string + */ + public function DKIM_HeaderC($signHeader) + { + //Normalize breaks to CRLF (regardless of the mailer) + $signHeader = static::normalizeBreaks($signHeader, self::CRLF); + //Unfold header lines + //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]` + //@see https://tools.ietf.org/html/rfc5322#section-2.2 + //That means this may break if you do something daft like put vertical tabs in your headers. + $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader); + //Break headers out into an array + $lines = explode(self::CRLF, $signHeader); + foreach ($lines as $key => $line) { + //If the header is missing a :, skip it as it's invalid + //This is likely to happen because the explode() above will also split + //on the trailing LE, leaving an empty line + if (strpos($line, ':') === false) { + continue; + } + list($heading, $value) = explode(':', $line, 2); + //Lower-case header name + $heading = strtolower($heading); + //Collapse white space within the value, also convert WSP to space + $value = preg_replace('/[ \t]+/', ' ', $value); + //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value + //But then says to delete space before and after the colon. + //Net result is the same as trimming both ends of the value. + //By elimination, the same applies to the field name + $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t"); + } + + return implode(self::CRLF, $lines); + } + + /** + * Generate a DKIM canonicalization body. + * Uses the 'simple' algorithm from RFC6376 section 3.4.3. + * Canonicalized bodies should *always* use CRLF, regardless of mailer setting. + * + * @see https://tools.ietf.org/html/rfc6376#section-3.4.3 + * + * @param string $body Message Body + * + * @return string + */ + public function DKIM_BodyC($body) + { + if (empty($body)) { + return self::CRLF; + } + //Normalize line endings to CRLF + $body = static::normalizeBreaks($body, self::CRLF); + + //Reduce multiple trailing line breaks to a single one + return static::stripTrailingWSP($body) . self::CRLF; + } + + /** + * Create the DKIM header and body in a new message header. + * + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body + * + * @throws Exception + * + * @return string + */ + public function DKIM_Add($headers_line, $subject, $body) + { + $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body + $DKIMquery = 'dns/txt'; //Query method + $DKIMtime = time(); + //Always sign these headers without being asked + //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1 + $autoSignHeaders = [ + 'from', + 'to', + 'cc', + 'date', + 'subject', + 'reply-to', + 'message-id', + 'content-type', + 'mime-version', + 'x-mailer', + ]; + if (stripos($headers_line, 'Subject') === false) { + $headers_line .= 'Subject: ' . $subject . static::$LE; + } + $headerLines = explode(static::$LE, $headers_line); + $currentHeaderLabel = ''; + $currentHeaderValue = ''; + $parsedHeaders = []; + $headerLineIndex = 0; + $headerLineCount = count($headerLines); + foreach ($headerLines as $headerLine) { + $matches = []; + if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) { + if ($currentHeaderLabel !== '') { + //We were previously in another header; This is the start of a new header, so save the previous one + $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; + } + $currentHeaderLabel = $matches[1]; + $currentHeaderValue = $matches[2]; + } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) { + //This is a folded continuation of the current header, so unfold it + $currentHeaderValue .= ' ' . $matches[1]; + } + ++$headerLineIndex; + if ($headerLineIndex >= $headerLineCount) { + //This was the last line, so finish off this header + $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; + } + } + $copiedHeaders = []; + $headersToSignKeys = []; + $headersToSign = []; + foreach ($parsedHeaders as $header) { + //Is this header one that must be included in the DKIM signature? + if (in_array(strtolower($header['label']), $autoSignHeaders, true)) { + $headersToSignKeys[] = $header['label']; + $headersToSign[] = $header['label'] . ': ' . $header['value']; + if ($this->DKIM_copyHeaderFields) { + $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC + str_replace('|', '=7C', $this->DKIM_QP($header['value'])); + } + continue; + } + //Is this an extra custom header we've been asked to sign? + if (in_array($header['label'], $this->DKIM_extraHeaders, true)) { + //Find its value in custom headers + foreach ($this->CustomHeader as $customHeader) { + if ($customHeader[0] === $header['label']) { + $headersToSignKeys[] = $header['label']; + $headersToSign[] = $header['label'] . ': ' . $header['value']; + if ($this->DKIM_copyHeaderFields) { + $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC + str_replace('|', '=7C', $this->DKIM_QP($header['value'])); + } + //Skip straight to the next header + continue 2; + } + } + } + } + $copiedHeaderFields = ''; + if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) { + //Assemble a DKIM 'z' tag + $copiedHeaderFields = ' z='; + $first = true; + foreach ($copiedHeaders as $copiedHeader) { + if (!$first) { + $copiedHeaderFields .= static::$LE . ' |'; + } + //Fold long values + if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) { + $copiedHeaderFields .= substr( + chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS), + 0, + -strlen(static::$LE . self::FWS) + ); + } else { + $copiedHeaderFields .= $copiedHeader; + } + $first = false; + } + $copiedHeaderFields .= ';' . static::$LE; + } + $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE; + $headerValues = implode(static::$LE, $headersToSign); + $body = $this->DKIM_BodyC($body); + //Base64 of packed binary SHA-256 hash of body + $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); + $ident = ''; + if ('' !== $this->DKIM_identity) { + $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE; + } + //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag + //which is appended after calculating the signature + //https://tools.ietf.org/html/rfc6376#section-3.5 + $dkimSignatureHeader = 'DKIM-Signature: v=1;' . + ' d=' . $this->DKIM_domain . ';' . + ' s=' . $this->DKIM_selector . ';' . static::$LE . + ' a=' . $DKIMsignatureType . ';' . + ' q=' . $DKIMquery . ';' . + ' t=' . $DKIMtime . ';' . + ' c=' . $DKIMcanonicalization . ';' . static::$LE . + $headerKeys . + $ident . + $copiedHeaderFields . + ' bh=' . $DKIMb64 . ';' . static::$LE . + ' b='; + //Canonicalize the set of headers + $canonicalizedHeaders = $this->DKIM_HeaderC( + $headerValues . static::$LE . $dkimSignatureHeader + ); + $signature = $this->DKIM_Sign($canonicalizedHeaders); + $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS)); + + return static::normalizeBreaks($dkimSignatureHeader . $signature); + } + + /** + * Detect if a string contains a line longer than the maximum line length + * allowed by RFC 2822 section 2.1.1. + * + * @param string $str + * + * @return bool + */ + public static function hasLineLongerThanMax($str) + { + return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str); + } + + /** + * If a string contains any "special" characters, double-quote the name, + * and escape any double quotes with a backslash. + * + * @param string $str + * + * @return string + * + * @see RFC822 3.4.1 + */ + public static function quotedString($str) + { + if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) { + //If the string contains any of these chars, it must be double-quoted + //and any double quotes must be escaped with a backslash + return '"' . str_replace('"', '\\"', $str) . '"'; + } + + //Return the string untouched, it doesn't need quoting + return $str; + } + + /** + * Allows for public read access to 'to' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getToAddresses() + { + return $this->to; + } + + /** + * Allows for public read access to 'cc' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getCcAddresses() + { + return $this->cc; + } + + /** + * Allows for public read access to 'bcc' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getBccAddresses() + { + return $this->bcc; + } + + /** + * Allows for public read access to 'ReplyTo' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getReplyToAddresses() + { + return $this->ReplyTo; + } + + /** + * Allows for public read access to 'all_recipients' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getAllRecipientAddresses() + { + return $this->all_recipients; + } + + /** + * Perform a callback. + * + * @param bool $isSent + * @param array $to + * @param array $cc + * @param array $bcc + * @param string $subject + * @param string $body + * @param string $from + * @param array $extra + */ + protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra) + { + if (!empty($this->action_function) && is_callable($this->action_function)) { + call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra); + } + } + + /** + * Get the OAuth instance. + * + * @return OAuth + */ + public function getOAuth() + { + return $this->oauth; + } + + /** + * Set an OAuth instance. + */ + public function setOAuth(OAuth $oauth) + { + $this->oauth = $oauth; + } +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/src/POP3.php b/php/libraries/composer/vendor/phpmailer/phpmailer/src/POP3.php new file mode 100644 index 0000000..a39f480 --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/src/POP3.php @@ -0,0 +1,448 @@ +<?php + +/** + * PHPMailer POP-Before-SMTP Authentication Class. + * PHP Version 5.5. + * + * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer POP-Before-SMTP Authentication Class. + * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. + * 1) This class does not support APOP authentication. + * 2) Opening and closing lots of POP3 connections can be quite slow. If you need + * to send a batch of emails then just perform the authentication once at the start, + * and then loop through your mail sending script. Providing this process doesn't + * take longer than the verification period lasts on your POP3 server, you should be fine. + * 3) This is really ancient technology; you should only need to use it to talk to very old systems. + * 4) This POP3 class is deliberately lightweight and incomplete, implementing just + * enough to do authentication. + * If you want a more complete class there are other POP3 classes for PHP available. + * + * @author Richard Davey (original author) <rich@corephp.co.uk> + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + */ +class POP3 +{ + /** + * The POP3 PHPMailer Version number. + * + * @var string + */ + const VERSION = '6.4.1'; + + /** + * Default POP3 port number. + * + * @var int + */ + const DEFAULT_PORT = 110; + + /** + * Default timeout in seconds. + * + * @var int + */ + const DEFAULT_TIMEOUT = 30; + + /** + * POP3 class debug output mode. + * Debug output level. + * Options: + * @see POP3::DEBUG_OFF: No output + * @see POP3::DEBUG_SERVER: Server messages, connection/server errors + * @see POP3::DEBUG_CLIENT: Client and Server messages, connection/server errors + * + * @var int + */ + public $do_debug = self::DEBUG_OFF; + + /** + * POP3 mail server hostname. + * + * @var string + */ + public $host; + + /** + * POP3 port number. + * + * @var int + */ + public $port; + + /** + * POP3 Timeout Value in seconds. + * + * @var int + */ + public $tval; + + /** + * POP3 username. + * + * @var string + */ + public $username; + + /** + * POP3 password. + * + * @var string + */ + public $password; + + /** + * Resource handle for the POP3 connection socket. + * + * @var resource + */ + protected $pop_conn; + + /** + * Are we connected? + * + * @var bool + */ + protected $connected = false; + + /** + * Error container. + * + * @var array + */ + protected $errors = []; + + /** + * Line break constant. + */ + const LE = "\r\n"; + + /** + * Debug level for no output. + * + * @var int + */ + const DEBUG_OFF = 0; + + /** + * Debug level to show server -> client messages + * also shows clients connection errors or errors from server + * + * @var int + */ + const DEBUG_SERVER = 1; + + /** + * Debug level to show client -> server and server -> client messages. + * + * @var int + */ + const DEBUG_CLIENT = 2; + + /** + * Simple static wrapper for all-in-one POP before SMTP. + * + * @param string $host The hostname to connect to + * @param int|bool $port The port number to connect to + * @param int|bool $timeout The timeout value + * @param string $username + * @param string $password + * @param int $debug_level + * + * @return bool + */ + public static function popBeforeSmtp( + $host, + $port = false, + $timeout = false, + $username = '', + $password = '', + $debug_level = 0 + ) { + $pop = new self(); + + return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level); + } + + /** + * Authenticate with a POP3 server. + * A connect, login, disconnect sequence + * appropriate for POP-before SMTP authorisation. + * + * @param string $host The hostname to connect to + * @param int|bool $port The port number to connect to + * @param int|bool $timeout The timeout value + * @param string $username + * @param string $password + * @param int $debug_level + * + * @return bool + */ + public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) + { + $this->host = $host; + //If no port value provided, use default + if (false === $port) { + $this->port = static::DEFAULT_PORT; + } else { + $this->port = (int) $port; + } + //If no timeout value provided, use default + if (false === $timeout) { + $this->tval = static::DEFAULT_TIMEOUT; + } else { + $this->tval = (int) $timeout; + } + $this->do_debug = $debug_level; + $this->username = $username; + $this->password = $password; + //Reset the error log + $this->errors = []; + //Connect + $result = $this->connect($this->host, $this->port, $this->tval); + if ($result) { + $login_result = $this->login($this->username, $this->password); + if ($login_result) { + $this->disconnect(); + + return true; + } + } + //We need to disconnect regardless of whether the login succeeded + $this->disconnect(); + + return false; + } + + /** + * Connect to a POP3 server. + * + * @param string $host + * @param int|bool $port + * @param int $tval + * + * @return bool + */ + public function connect($host, $port = false, $tval = 30) + { + //Are we already connected? + if ($this->connected) { + return true; + } + + //On Windows this will raise a PHP Warning error if the hostname doesn't exist. + //Rather than suppress it with @fsockopen, capture it cleanly instead + set_error_handler([$this, 'catchWarning']); + + if (false === $port) { + $port = static::DEFAULT_PORT; + } + + //Connect to the POP3 server + $errno = 0; + $errstr = ''; + $this->pop_conn = fsockopen( + $host, //POP3 Host + $port, //Port # + $errno, //Error Number + $errstr, //Error Message + $tval + ); //Timeout (seconds) + //Restore the error handler + restore_error_handler(); + + //Did we connect? + if (false === $this->pop_conn) { + //It would appear not... + $this->setError( + "Failed to connect to server $host on port $port. errno: $errno; errstr: $errstr" + ); + + return false; + } + + //Increase the stream time-out + stream_set_timeout($this->pop_conn, $tval, 0); + + //Get the POP3 server response + $pop3_response = $this->getResponse(); + //Check for the +OK + if ($this->checkResponse($pop3_response)) { + //The connection is established and the POP3 server is talking + $this->connected = true; + + return true; + } + + return false; + } + + /** + * Log in to the POP3 server. + * Does not support APOP (RFC 2828, 4949). + * + * @param string $username + * @param string $password + * + * @return bool + */ + public function login($username = '', $password = '') + { + if (!$this->connected) { + $this->setError('Not connected to POP3 server'); + } + if (empty($username)) { + $username = $this->username; + } + if (empty($password)) { + $password = $this->password; + } + + //Send the Username + $this->sendString("USER $username" . static::LE); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + //Send the Password + $this->sendString("PASS $password" . static::LE); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + return true; + } + } + + return false; + } + + /** + * Disconnect from the POP3 server. + */ + public function disconnect() + { + $this->sendString('QUIT'); + //The QUIT command may cause the daemon to exit, which will kill our connection + //So ignore errors here + try { + @fclose($this->pop_conn); + } catch (Exception $e) { + //Do nothing + } + } + + /** + * Get a response from the POP3 server. + * + * @param int $size The maximum number of bytes to retrieve + * + * @return string + */ + protected function getResponse($size = 128) + { + $response = fgets($this->pop_conn, $size); + if ($this->do_debug >= self::DEBUG_SERVER) { + echo 'Server -> Client: ', $response; + } + + return $response; + } + + /** + * Send raw data to the POP3 server. + * + * @param string $string + * + * @return int + */ + protected function sendString($string) + { + if ($this->pop_conn) { + if ($this->do_debug >= self::DEBUG_CLIENT) { //Show client messages when debug >= 2 + echo 'Client -> Server: ', $string; + } + + return fwrite($this->pop_conn, $string, strlen($string)); + } + + return 0; + } + + /** + * Checks the POP3 server response. + * Looks for for +OK or -ERR. + * + * @param string $string + * + * @return bool + */ + protected function checkResponse($string) + { + if (strpos($string, '+OK') !== 0) { + $this->setError("Server reported an error: $string"); + + return false; + } + + return true; + } + + /** + * Add an error to the internal error store. + * Also display debug output if it's enabled. + * + * @param string $error + */ + protected function setError($error) + { + $this->errors[] = $error; + if ($this->do_debug >= self::DEBUG_SERVER) { + echo '<pre>'; + foreach ($this->errors as $e) { + print_r($e); + } + echo '</pre>'; + } + } + + /** + * Get an array of error messages, if any. + * + * @return array + */ + public function getErrors() + { + return $this->errors; + } + + /** + * POP3 connection error handler. + * + * @param int $errno + * @param string $errstr + * @param string $errfile + * @param int $errline + */ + protected function catchWarning($errno, $errstr, $errfile, $errline) + { + $this->setError( + 'Connecting to the POP3 server raised a PHP warning:' . + "errno: $errno errstr: $errstr; errfile: $errfile; errline: $errline" + ); + } +} diff --git a/php/libraries/composer/vendor/phpmailer/phpmailer/src/SMTP.php b/php/libraries/composer/vendor/phpmailer/phpmailer/src/SMTP.php new file mode 100644 index 0000000..0e7f53d --- /dev/null +++ b/php/libraries/composer/vendor/phpmailer/phpmailer/src/SMTP.php @@ -0,0 +1,1455 @@ +<?php + +/** + * PHPMailer RFC821 SMTP email transport class. + * PHP Version 5.5. + * + * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> + * @author Jim Jagielski (jimjag) <jimjag@gmail.com> + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer RFC821 SMTP email transport class. + * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. + * + * @author Chris Ryan + * @author Marcus Bointon <phpmailer@synchromedia.co.uk> + */ +class SMTP +{ + /** + * The PHPMailer SMTP version number. + * + * @var string + */ + const VERSION = '6.4.1'; + + /** + * SMTP line break constant. + * + * @var string + */ + const LE = "\r\n"; + + /** + * The SMTP port to use if one is not specified. + * + * @var int + */ + const DEFAULT_PORT = 25; + + /** + * The maximum line length allowed by RFC 5321 section 4.5.3.1.6, + * *excluding* a trailing CRLF break. + * + * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.6 + * + * @var int + */ + const MAX_LINE_LENGTH = 998; + + /** + * The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5, + * *including* a trailing CRLF line break. + * + * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.5 + * + * @var int + */ + const MAX_REPLY_LENGTH = 512; + + /** + * Debug level for no output. + * + * @var int + */ + const DEBUG_OFF = 0; + + /** + * Debug level to show client -> server messages. + * + * @var int + */ + const DEBUG_CLIENT = 1; + + /** + * Debug level to show client -> server and server -> client messages. + * + * @var int + */ + const DEBUG_SERVER = 2; + + /** + * Debug level to show connection status, client -> server and server -> client messages. + * + * @var int + */ + const DEBUG_CONNECTION = 3; + + /** + * Debug level to show all messages. + * + * @var int + */ + const DEBUG_LOWLEVEL = 4; + + /** + * Debug output level. + * Options: + * * self::DEBUG_OFF (`0`) No debug output, default + * * self::DEBUG_CLIENT (`1`) Client commands + * * self::DEBUG_SERVER (`2`) Client commands and server responses + * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status + * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages. + * + * @var int + */ + public $do_debug = self::DEBUG_OFF; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * ```php + * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * ``` + * + * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` + * level output is used: + * + * ```php + * $mail->Debugoutput = new myPsr3Logger; + * ``` + * + * @var string|callable|\Psr\Log\LoggerInterface + */ + public $Debugoutput = 'echo'; + + /** + * Whether to use VERP. + * + * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path + * @see http://www.postfix.org/VERP_README.html Info on VERP + * + * @var bool + */ + public $do_verp = false; + + /** + * The timeout value for connection, in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. + * + * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2 + * + * @var int + */ + public $Timeout = 300; + + /** + * How long to wait for commands to complete, in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * + * @var int + */ + public $Timelimit = 300; + + /** + * Patterns to extract an SMTP transaction id from reply to a DATA command. + * The first capture group in each regex will be used as the ID. + * MS ESMTP returns the message ID, which may not be correct for internal tracking. + * + * @var string[] + */ + protected $smtp_transaction_id_patterns = [ + 'exim' => '/[\d]{3} OK id=(.*)/', + 'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/', + 'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/', + 'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/', + 'Amazon_SES' => '/[\d]{3} Ok (.*)/', + 'SendGrid' => '/[\d]{3} Ok: queued as (.*)/', + 'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/', + ]; + + /** + * The last transaction ID issued in response to a DATA command, + * if one was detected. + * + * @var string|bool|null + */ + protected $last_smtp_transaction_id; + + /** + * The socket for the server connection. + * + * @var ?resource + */ + protected $smtp_conn; + + /** + * Error information, if any, for the last SMTP command. + * + * @var array + */ + protected $error = [ + 'error' => '', + 'detail' => '', + 'smtp_code' => '', + 'smtp_code_ex' => '', + ]; + + /** + * The reply the server sent to us for HELO. + * If null, no HELO string has yet been received. + * + * @var string|null + */ + protected $helo_rply; + + /** + * The set of SMTP extensions sent in reply to EHLO command. + * Indexes of the array are extension names. + * Value at index 'HELO' or 'EHLO' (according to command that was sent) + * represents the server name. In case of HELO it is the only element of the array. + * Other values can be boolean TRUE or an array containing extension options. + * If null, no HELO/EHLO string has yet been received. + * + * @var array|null + */ + protected $server_caps; + + /** + * The most recent reply received from the server. + * + * @var string + */ + protected $last_reply = ''; + + /** + * Output debugging info via a user-selected method. + * + * @param string $str Debug string to output + * @param int $level The debug level of this message; see DEBUG_* constants + * + * @see SMTP::$Debugoutput + * @see SMTP::$do_debug + */ + protected function edebug($str, $level = 0) + { + if ($level > $this->do_debug) { + return; + } + //Is this a PSR-3 logger? + if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { + $this->Debugoutput->debug($str); + + return; + } + //Avoid clash with built-in function names + if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + call_user_func($this->Debugoutput, $str, $level); + + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo gmdate('Y-m-d H:i:s'), ' ', htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ), "<br>\n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n|\r/m', "\n", $str); + echo gmdate('Y-m-d H:i:s'), + "\t", + //Trim trailing space + trim( + //Indent for readability, except for trailing break + str_replace( + "\n", + "\n \t ", + trim($str) + ) + ), + "\n"; + } + } + + /** + * Connect to an SMTP server. + * + * @param string $host SMTP server IP or host name + * @param int $port The port number to connect to + * @param int $timeout How long to wait for the connection to open + * @param array $options An array of options for stream_context_create() + * + * @return bool + */ + public function connect($host, $port = null, $timeout = 30, $options = []) + { + //Clear errors to avoid confusion + $this->setError(''); + //Make sure we are __not__ connected + if ($this->connected()) { + //Already connected, generate error + $this->setError('Already connected to a server'); + + return false; + } + if (empty($port)) { + $port = self::DEFAULT_PORT; + } + //Connect to the SMTP server + $this->edebug( + "Connection: opening to $host:$port, timeout=$timeout, options=" . + (count($options) > 0 ? var_export($options, true) : 'array()'), + self::DEBUG_CONNECTION + ); + + $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options); + + if ($this->smtp_conn === false) { + //Error info already set inside `getSMTPConnection()` + return false; + } + + $this->edebug('Connection: opened', self::DEBUG_CONNECTION); + + //Get any announcement + $this->last_reply = $this->get_lines(); + $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); + $responseCode = (int)substr($this->last_reply, 0, 3); + if ($responseCode === 220) { + return true; + } + //Anything other than a 220 response means something went wrong + //RFC 5321 says the server will wait for us to send a QUIT in response to a 554 error + //https://tools.ietf.org/html/rfc5321#section-3.1 + if ($responseCode === 554) { + $this->quit(); + } + //This will handle 421 responses which may not wait for a QUIT (e.g. if the server is being shut down) + $this->edebug('Connection: closing due to error', self::DEBUG_CONNECTION); + $this->close(); + return false; + } + + /** + * Create connection to the SMTP server. + * + * @param string $host SMTP server IP or host name + * @param int $port The port number to connect to + * @param int $timeout How long to wait for the connection to open + * @param array $options An array of options for stream_context_create() + * + * @return false|resource + */ + protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = []) + { + static $streamok; + //This is enabled by default since 5.0.0 but some providers disable it + //Check this once and cache the result + if (null === $streamok) { + $streamok = function_exists('stream_socket_client'); + } + + $errno = 0; + $errstr = ''; + if ($streamok) { + $socket_context = stream_context_create($options); + set_error_handler([$this, 'errorHandler']); + $connection = stream_socket_client( + $host . ':' . $port, + $errno, + $errstr, + $timeout, + STREAM_CLIENT_CONNECT, + $socket_context + ); + restore_error_handler(); + } else { + //Fall back to fsockopen which should work in more places, but is missing some features + $this->edebug( + 'Connection: stream_socket_client not available, falling back to fsockopen', + self::DEBUG_CONNECTION + ); + set_error_handler([$this, 'errorHandler']); + $connection = fsockopen( + $host, + $port, + $errno, + $errstr, + $timeout + ); + restore_error_handler(); + } + + //Verify we connected properly + if (!is_resource($connection)) { + $this->setError( + 'Failed to connect to server', + '', + (string) $errno, + $errstr + ); + $this->edebug( + 'SMTP ERROR: ' . $this->error['error'] + . ": $errstr ($errno)", + self::DEBUG_CLIENT + ); + + return false; + } + + //SMTP server can take longer to respond, give longer timeout for first read + //Windows does not have support for this timeout function + if (strpos(PHP_OS, 'WIN') !== 0) { + $max = (int)ini_get('max_execution_time'); + //Don't bother if unlimited, or if set_time_limit is disabled + if (0 !== $max && $timeout > $max && strpos(ini_get('disable_functions'), 'set_time_limit') === false) { + @set_time_limit($timeout); + } + stream_set_timeout($connection, $timeout, 0); + } + + return $connection; + } + + /** + * Initiate a TLS (encrypted) session. + * + * @return bool + */ + public function startTLS() + { + if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { + return false; + } + + //Allow the best TLS version(s) we can + $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; + + //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT + //so add them back in manually if we can + if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { + $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; + } + + //Begin encrypted connection + set_error_handler([$this, 'errorHandler']); + $crypto_ok = stream_socket_enable_crypto( + $this->smtp_conn, + true, + $crypto_method + ); + restore_error_handler(); + + return (bool) $crypto_ok; + } + + /** + * Perform SMTP authentication. + * Must be run after hello(). + * + * @see hello() + * + * @param string $username The user name + * @param string $password The password + * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2) + * @param OAuth $OAuth An optional OAuth instance for XOAUTH2 authentication + * + * @return bool True if successfully authenticated + */ + public function authenticate( + $username, + $password, + $authtype = null, + $OAuth = null + ) { + if (!$this->server_caps) { + $this->setError('Authentication is not allowed before HELO/EHLO'); + + return false; + } + + if (array_key_exists('EHLO', $this->server_caps)) { + //SMTP extensions are available; try to find a proper authentication method + if (!array_key_exists('AUTH', $this->server_caps)) { + $this->setError('Authentication is not allowed at this stage'); + //'at this stage' means that auth may be allowed after the stage changes + //e.g. after STARTTLS + + return false; + } + + $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL); + $this->edebug( + 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), + self::DEBUG_LOWLEVEL + ); + + //If we have requested a specific auth type, check the server supports it before trying others + if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) { + $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL); + $authtype = null; + } + + if (empty($authtype)) { + //If no auth mechanism is specified, attempt to use these, in this order + //Try CRAM-MD5 first as it's more secure than the others + foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) { + if (in_array($method, $this->server_caps['AUTH'], true)) { + $authtype = $method; + break; + } + } + if (empty($authtype)) { + $this->setError('No supported authentication methods found'); + + return false; + } + $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL); + } + + if (!in_array($authtype, $this->server_caps['AUTH'], true)) { + $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); + + return false; + } + } elseif (empty($authtype)) { + $authtype = 'LOGIN'; + } + switch ($authtype) { + case 'PLAIN': + //Start authentication + if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { + return false; + } + //Send encoded username and password + if ( + //Format from https://tools.ietf.org/html/rfc4616#section-2 + //We skip the first field (it's forgery), so the string starts with a null byte + !$this->sendCommand( + 'User & Password', + base64_encode("\0" . $username . "\0" . $password), + 235 + ) + ) { + return false; + } + break; + case 'LOGIN': + //Start authentication + if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { + return false; + } + if (!$this->sendCommand('Username', base64_encode($username), 334)) { + return false; + } + if (!$this->sendCommand('Password', base64_encode($password), 235)) { + return false; + } + break; + case 'CRAM-MD5': + //Start authentication + if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { + return false; + } + //Get the challenge + $challenge = base64_decode(substr($this->last_reply, 4)); + + //Build the response + $response = $username . ' ' . $this->hmac($challenge, $password); + + //send encoded credentials + return $this->sendCommand('Username', base64_encode($response), 235); + case 'XOAUTH2': + //The OAuth instance must be set up prior to requesting auth. + if (null === $OAuth) { + return false; + } + $oauth = $OAuth->getOauth64(); + + //Start authentication + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { + return false; + } + break; + default: + $this->setError("Authentication method \"$authtype\" is not supported"); + + return false; + } + + return true; + } + + /** + * Calculate an MD5 HMAC hash. + * Works like hash_hmac('md5', $data, $key) + * in case that function is not available. + * + * @param string $data The data to hash + * @param string $key The key to hash with + * + * @return string + */ + protected function hmac($data, $key) + { + if (function_exists('hash_hmac')) { + return hash_hmac('md5', $data, $key); + } + + //The following borrowed from + //http://php.net/manual/en/function.mhash.php#27225 + + //RFC 2104 HMAC implementation for php. + //Creates an md5 HMAC. + //Eliminates the need to install mhash to compute a HMAC + //by Lance Rushing + + $bytelen = 64; //byte length for md5 + if (strlen($key) > $bytelen) { + $key = pack('H*', md5($key)); + } + $key = str_pad($key, $bytelen, chr(0x00)); + $ipad = str_pad('', $bytelen, chr(0x36)); + $opad = str_pad('', $bytelen, chr(0x5c)); + $k_ipad = $key ^ $ipad; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } + + /** + * Check connection state. + * + * @return bool True if connected + */ + public function connected() + { + if (is_resource($this->smtp_conn)) { + $sock_status = stream_get_meta_data($this->smtp_conn); + if ($sock_status['eof']) { + //The socket is valid but we are not connected + $this->edebug( + 'SMTP NOTICE: EOF caught while checking if connected', + self::DEBUG_CLIENT + ); + $this->close(); + + return false; + } + + return true; //everything looks good + } + + return false; + } + + /** + * Close the socket and clean up the state of the class. + * Don't use this function without first trying to use QUIT. + * + * @see quit() + */ + public function close() + { + $this->setError(''); + $this->server_caps = null; + $this->helo_rply = null; + if (is_resource($this->smtp_conn)) { + //Close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = null; //Makes for cleaner serialization + $this->edebug('Connection: closed', self::DEBUG_CONNECTION); + } + } + + /** + * Send an SMTP DATA command. + * Issues a data command and sends the msg_data to the server, + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a <CRLF> with the message headers + * and the message body being separated by an additional <CRLF>. + * Implements RFC 821: DATA <CRLF>. + * + * @param string $msg_data Message data to send + * + * @return bool + */ + public function data($msg_data) + { + //This will use the standard timelimit + if (!$this->sendCommand('DATA', 'DATA', 354)) { + return false; + } + + /* The server is ready to accept data! + * According to rfc821 we should not send more than 1000 characters on a single line (including the LE) + * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into + * smaller lines to fit within the limit. + * We will also look for lines that start with a '.' and prepend an additional '.'. + * NOTE: this does not count towards line-length limit. + */ + + //Normalize line breaks before exploding + $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data)); + + /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field + * of the first line (':' separated) does not contain a space then it _should_ be a header and we will + * process all lines before a blank line as headers. + */ + + $field = substr($lines[0], 0, strpos($lines[0], ':')); + $in_headers = false; + if (!empty($field) && strpos($field, ' ') === false) { + $in_headers = true; + } + + foreach ($lines as $line) { + $lines_out = []; + if ($in_headers && $line === '') { + $in_headers = false; + } + //Break this line up into several smaller lines if it's too long + //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), + while (isset($line[self::MAX_LINE_LENGTH])) { + //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on + //so as to avoid breaking in the middle of a word + $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); + //Deliberately matches both false and 0 + if (!$pos) { + //No nice break found, add a hard break + $pos = self::MAX_LINE_LENGTH - 1; + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos); + } else { + //Break at the found point + $lines_out[] = substr($line, 0, $pos); + //Move along by the amount we dealt with + $line = substr($line, $pos + 1); + } + //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 + if ($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + //Send the lines to the server + foreach ($lines_out as $line_out) { + //Dot-stuffing as per RFC5321 section 4.5.2 + //https://tools.ietf.org/html/rfc5321#section-4.5.2 + if (!empty($line_out) && $line_out[0] === '.') { + $line_out = '.' . $line_out; + } + $this->client_send($line_out . static::LE, 'DATA'); + } + } + + //Message data has been sent, complete the command + //Increase timelimit for end of DATA command + $savetimelimit = $this->Timelimit; + $this->Timelimit *= 2; + $result = $this->sendCommand('DATA END', '.', 250); + $this->recordLastTransactionID(); + //Restore timelimit + $this->Timelimit = $savetimelimit; + + return $result; + } + + /** + * Send an SMTP HELO or EHLO command. + * Used to identify the sending server to the receiving server. + * This makes sure that client and server are in a known state. + * Implements RFC 821: HELO <SP> <domain> <CRLF> + * and RFC 2821 EHLO. + * + * @param string $host The host name or IP to connect to + * + * @return bool + */ + public function hello($host = '') + { + //Try extended hello first (RFC 2821) + if ($this->sendHello('EHLO', $host)) { + return true; + } + + //Some servers shut down the SMTP service here (RFC 5321) + if (substr($this->helo_rply, 0, 3) == '421') { + return false; + } + + return $this->sendHello('HELO', $host); + } + + /** + * Send an SMTP HELO or EHLO command. + * Low-level implementation used by hello(). + * + * @param string $hello The HELO string + * @param string $host The hostname to say we are + * + * @return bool + * + * @see hello() + */ + protected function sendHello($hello, $host) + { + $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); + $this->helo_rply = $this->last_reply; + if ($noerror) { + $this->parseHelloFields($hello); + } else { + $this->server_caps = null; + } + + return $noerror; + } + + /** + * Parse a reply to HELO/EHLO command to discover server extensions. + * In case of HELO, the only parameter that can be discovered is a server name. + * + * @param string $type `HELO` or `EHLO` + */ + protected function parseHelloFields($type) + { + $this->server_caps = []; + $lines = explode("\n", $this->helo_rply); + + foreach ($lines as $n => $s) { + //First 4 chars contain response code followed by - or space + $s = trim(substr($s, 4)); + if (empty($s)) { + continue; + } + $fields = explode(' ', $s); + if (!empty($fields)) { + if (!$n) { + $name = $type; + $fields = $fields[0]; + } else { + $name = array_shift($fields); + switch ($name) { + case 'SIZE': + $fields = ($fields ? $fields[0] : 0); + break; + case 'AUTH': + if (!is_array($fields)) { + $fields = []; + } + break; + default: + $fields = true; + } + } + $this->server_caps[$name] = $fields; + } + } + } + + /** + * Send an SMTP MAIL command. + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. + * Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>. + * + * @param string $from Source address of this message + * + * @return bool + */ + public function mail($from) + { + $useVerp = ($this->do_verp ? ' XVERP' : ''); + + return $this->sendCommand( + 'MAIL FROM', + 'MAIL FROM:<' . $from . '>' . $useVerp, + 250 + ); + } + + /** + * Send an SMTP QUIT command. + * Closes the socket if there is no error or the $close_on_error argument is true. + * Implements from RFC 821: QUIT <CRLF>. + * + * @param bool $close_on_error Should the connection close if an error occurs? + * + * @return bool + */ + public function quit($close_on_error = true) + { + $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + $err = $this->error; //Save any error + if ($noerror || $close_on_error) { + $this->close(); + $this->error = $err; //Restore any error from the quit command + } + + return $noerror; + } + + /** + * Send an SMTP RCPT command. + * Sets the TO argument to $toaddr. + * Returns true if the recipient was accepted false if it was rejected. + * Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>. + * + * @param string $address The address the message is being sent to + * @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE + * or DELAY. If you specify NEVER all other notifications are ignored. + * + * @return bool + */ + public function recipient($address, $dsn = '') + { + if (empty($dsn)) { + $rcpt = 'RCPT TO:<' . $address . '>'; + } else { + $dsn = strtoupper($dsn); + $notify = []; + + if (strpos($dsn, 'NEVER') !== false) { + $notify[] = 'NEVER'; + } else { + foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) { + if (strpos($dsn, $value) !== false) { + $notify[] = $value; + } + } + } + + $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify); + } + + return $this->sendCommand( + 'RCPT TO', + $rcpt, + [250, 251] + ); + } + + /** + * Send an SMTP RSET command. + * Abort any transaction that is currently in progress. + * Implements RFC 821: RSET <CRLF>. + * + * @return bool True on success + */ + public function reset() + { + return $this->sendCommand('RSET', 'RSET', 250); + } + + /** + * Send a command to an SMTP server and check its return code. + * + * @param string $command The command name - not sent to the server + * @param string $commandstring The actual command to send + * @param int|array $expect One or more expected integer success codes + * + * @return bool True on success + */ + protected function sendCommand($command, $commandstring, $expect) + { + if (!$this->connected()) { + $this->setError("Called $command without being connected"); + + return false; + } + //Reject line breaks in all commands + if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) { + $this->setError("Command '$command' contained line breaks"); + + return false; + } + $this->client_send($commandstring . static::LE, $command); + + $this->last_reply = $this->get_lines(); + //Fetch SMTP code and possible error code explanation + $matches = []; + if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) { + $code = (int) $matches[1]; + $code_ex = (count($matches) > 2 ? $matches[2] : null); + //Cut off error code from each response line + $detail = preg_replace( + "/{$code}[ -]" . + ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m', + '', + $this->last_reply + ); + } else { + //Fall back to simple parsing if regex fails + $code = (int) substr($this->last_reply, 0, 3); + $code_ex = null; + $detail = substr($this->last_reply, 4); + } + + $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); + + if (!in_array($code, (array) $expect, true)) { + $this->setError( + "$command command failed", + $detail, + $code, + $code_ex + ); + $this->edebug( + 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, + self::DEBUG_CLIENT + ); + + return false; + } + + $this->setError(''); + + return true; + } + + /** + * Send an SMTP SAML command. + * Starts a mail transaction from the email address specified in $from. + * Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>. + * + * @param string $from The address the message is from + * + * @return bool + */ + public function sendAndMail($from) + { + return $this->sendCommand('SAML', "SAML FROM:$from", 250); + } + + /** + * Send an SMTP VRFY command. + * + * @param string $name The name to verify + * + * @return bool + */ + public function verify($name) + { + return $this->sendCommand('VRFY', "VRFY $name", [250, 251]); + } + + /** + * Send an SMTP NOOP command. + * Used to keep keep-alives alive, doesn't actually do anything. + * + * @return bool + */ + public function noop() + { + return $this->sendCommand('NOOP', 'NOOP', 250); + } + + /** + * Send an SMTP TURN command. + * This is an optional command for SMTP that this class does not support. + * This method is here to make the RFC821 Definition complete for this class + * and _may_ be implemented in future. + * Implements from RFC 821: TURN <CRLF>. + * + * @return bool + */ + public function turn() + { + $this->setError('The SMTP TURN command is not implemented'); + $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); + + return false; + } + + /** + * Send raw data to the server. + * + * @param string $data The data to send + * @param string $command Optionally, the command this is part of, used only for controlling debug output + * + * @return int|bool The number of bytes sent to the server or false on error + */ + public function client_send($data, $command = '') + { + //If SMTP transcripts are left enabled, or debug output is posted online + //it can leak credentials, so hide credentials in all but lowest level + if ( + self::DEBUG_LOWLEVEL > $this->do_debug && + in_array($command, ['User & Password', 'Username', 'Password'], true) + ) { + $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT); + } else { + $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT); + } + set_error_handler([$this, 'errorHandler']); + $result = fwrite($this->smtp_conn, $data); + restore_error_handler(); + + return $result; + } + + /** + * Get the latest error. + * + * @return array + */ + public function getError() + { + return $this->error; + } + + /** + * Get SMTP extensions available on the server. + * + * @return array|null + */ + public function getServerExtList() + { + return $this->server_caps; + } + + /** + * Get metadata about the SMTP server from its HELO/EHLO response. + * The method works in three ways, dependent on argument value and current state: + * 1. HELO/EHLO has not been sent - returns null and populates $this->error. + * 2. HELO has been sent - + * $name == 'HELO': returns server name + * $name == 'EHLO': returns boolean false + * $name == any other string: returns null and populates $this->error + * 3. EHLO has been sent - + * $name == 'HELO'|'EHLO': returns the server name + * $name == any other string: if extension $name exists, returns True + * or its options (e.g. AUTH mechanisms supported). Otherwise returns False. + * + * @param string $name Name of SMTP extension or 'HELO'|'EHLO' + * + * @return string|bool|null + */ + public function getServerExt($name) + { + if (!$this->server_caps) { + $this->setError('No HELO/EHLO was sent'); + + return; + } + + if (!array_key_exists($name, $this->server_caps)) { + if ('HELO' === $name) { + return $this->server_caps['EHLO']; + } + if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) { + return false; + } + $this->setError('HELO handshake was used; No information about server extensions available'); + + return; + } + + return $this->server_caps[$name]; + } + + /** + * Get the last reply from the server. + * + * @return string + */ + public function getLastReply() + { + return $this->last_reply; + } + + /** + * Read the SMTP server's response. + * Either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * + * @return string + */ + protected function get_lines() + { + //If the connection is bad, give up straight away + if (!is_resource($this->smtp_conn)) { + return ''; + } + $data = ''; + $endtime = 0; + stream_set_timeout($this->smtp_conn, $this->Timeout); + if ($this->Timelimit > 0) { + $endtime = time() + $this->Timelimit; + } + $selR = [$this->smtp_conn]; + $selW = null; + while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { + //Must pass vars in here as params are by reference + //solution for signals inspired by https://github.com/symfony/symfony/pull/6540 + set_error_handler([$this, 'errorHandler']); + $n = stream_select($selR, $selW, $selW, $this->Timelimit); + restore_error_handler(); + + if ($n === false) { + $message = $this->getError()['detail']; + + $this->edebug( + 'SMTP -> get_lines(): select failed (' . $message . ')', + self::DEBUG_LOWLEVEL + ); + + //stream_select returns false when the `select` system call is interrupted + //by an incoming signal, try the select again + if (stripos($message, 'interrupted system call') !== false) { + $this->edebug( + 'SMTP -> get_lines(): retrying stream_select', + self::DEBUG_LOWLEVEL + ); + $this->setError(''); + continue; + } + + break; + } + + if (!$n) { + $this->edebug( + 'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + + //Deliberate noise suppression - errors are handled afterwards + $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH); + $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL); + $data .= $str; + //If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled), + //or 4th character is a space or a line break char, we are done reading, break the loop. + //String array access is a significant micro-optimisation over strlen + if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") { + break; + } + //Timed-out? Log and break + $info = stream_get_meta_data($this->smtp_conn); + if ($info['timed_out']) { + $this->edebug( + 'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + //Now check if reads took too long + if ($endtime && time() > $endtime) { + $this->edebug( + 'SMTP -> get_lines(): timelimit reached (' . + $this->Timelimit . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + } + + return $data; + } + + /** + * Enable or disable VERP address generation. + * + * @param bool $enabled + */ + public function setVerp($enabled = false) + { + $this->do_verp = $enabled; + } + + /** + * Get VERP address generation mode. + * + * @return bool + */ + public function getVerp() + { + return $this->do_verp; + } + + /** + * Set error messages and codes. + * + * @param string $message The error message + * @param string $detail Further detail on the error + * @param string $smtp_code An associated SMTP error code + * @param string $smtp_code_ex Extended SMTP code + */ + protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') + { + $this->error = [ + 'error' => $message, + 'detail' => $detail, + 'smtp_code' => $smtp_code, + 'smtp_code_ex' => $smtp_code_ex, + ]; + } + + /** + * Set debug output method. + * + * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it + */ + public function setDebugOutput($method = 'echo') + { + $this->Debugoutput = $method; + } + + /** + * Get debug output method. + * + * @return string + */ + public function getDebugOutput() + { + return $this->Debugoutput; + } + + /** + * Set debug output level. + * + * @param int $level + */ + public function setDebugLevel($level = 0) + { + $this->do_debug = $level; + } + + /** + * Get debug output level. + * + * @return int + */ + public function getDebugLevel() + { + return $this->do_debug; + } + + /** + * Set SMTP timeout. + * + * @param int $timeout The timeout duration in seconds + */ + public function setTimeout($timeout = 0) + { + $this->Timeout = $timeout; + } + + /** + * Get SMTP timeout. + * + * @return int + */ + public function getTimeout() + { + return $this->Timeout; + } + + /** + * Reports an error number and string. + * + * @param int $errno The error number returned by PHP + * @param string $errmsg The error message returned by PHP + * @param string $errfile The file the error occurred in + * @param int $errline The line number the error occurred on + */ + protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) + { + $notice = 'Connection failed.'; + $this->setError( + $notice, + $errmsg, + (string) $errno + ); + $this->edebug( + "$notice Error #$errno: $errmsg [$errfile line $errline]", + self::DEBUG_CONNECTION + ); + } + + /** + * Extract and return the ID of the last SMTP transaction based on + * a list of patterns provided in SMTP::$smtp_transaction_id_patterns. + * Relies on the host providing the ID in response to a DATA command. + * If no reply has been received yet, it will return null. + * If no pattern was matched, it will return false. + * + * @return bool|string|null + */ + protected function recordLastTransactionID() + { + $reply = $this->getLastReply(); + + if (empty($reply)) { + $this->last_smtp_transaction_id = null; + } else { + $this->last_smtp_transaction_id = false; + foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { + $matches = []; + if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) { + $this->last_smtp_transaction_id = trim($matches[1]); + break; + } + } + } + + return $this->last_smtp_transaction_id; + } + + /** + * Get the queue/transaction ID of the last SMTP transaction + * If no reply has been received yet, it will return null. + * If no pattern was matched, it will return false. + * + * @return bool|string|null + * + * @see recordLastTransactionID() + */ + public function getLastTransactionID() + { + return $this->last_smtp_transaction_id; + } +} diff --git a/php/libraries/composer/vendor/phpoption/phpoption/LICENSE b/php/libraries/composer/vendor/phpoption/phpoption/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/php/libraries/composer/vendor/phpoption/phpoption/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/php/libraries/composer/vendor/phpoption/phpoption/composer.json b/php/libraries/composer/vendor/phpoption/phpoption/composer.json new file mode 100644 index 0000000..77f50a3 --- /dev/null +++ b/php/libraries/composer/vendor/phpoption/phpoption/composer.json @@ -0,0 +1,52 @@ +{ + "name": "phpoption/phpoption", + "description": "Option Type for PHP", + "keywords": ["php", "option", "language", "type"], + "license": "Apache-2.0", + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "autoload-dev": { + "psr-4": { + "PhpOption\\Tests\\": "tests/PhpOption/Tests/" + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist" + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/LazyOption.php b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/LazyOption.php new file mode 100644 index 0000000..9cb77c8 --- /dev/null +++ b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/LazyOption.php @@ -0,0 +1,175 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use Traversable; + +/** + * @template T + * + * @extends Option<T> + */ +final class LazyOption extends Option +{ + /** @var callable(mixed...):(Option<T>) */ + private $callback; + + /** @var array<int, mixed> */ + private $arguments; + + /** @var Option<T>|null */ + private $option; + + /** + * @template S + * @param callable(mixed...):(Option<S>) $callback + * @param array<int, mixed> $arguments + * + * @return LazyOption<S> + */ + public static function create($callback, array $arguments = []): self + { + return new self($callback, $arguments); + } + + /** + * @param callable(mixed...):(Option<T>) $callback + * @param array<int, mixed> $arguments + */ + public function __construct($callback, array $arguments = []) + { + if (!is_callable($callback)) { + throw new \InvalidArgumentException('Invalid callback given'); + } + + $this->callback = $callback; + $this->arguments = $arguments; + } + + public function isDefined(): bool + { + return $this->option()->isDefined(); + } + + public function isEmpty(): bool + { + return $this->option()->isEmpty(); + } + + public function get() + { + return $this->option()->get(); + } + + public function getOrElse($default) + { + return $this->option()->getOrElse($default); + } + + public function getOrCall($callable) + { + return $this->option()->getOrCall($callable); + } + + public function getOrThrow(\Exception $ex) + { + return $this->option()->getOrThrow($ex); + } + + public function orElse(Option $else) + { + return $this->option()->orElse($else); + } + + public function ifDefined($callable) + { + $this->option()->forAll($callable); + } + + public function forAll($callable) + { + return $this->option()->forAll($callable); + } + + public function map($callable) + { + return $this->option()->map($callable); + } + + public function flatMap($callable) + { + return $this->option()->flatMap($callable); + } + + public function filter($callable) + { + return $this->option()->filter($callable); + } + + public function filterNot($callable) + { + return $this->option()->filterNot($callable); + } + + public function select($value) + { + return $this->option()->select($value); + } + + public function reject($value) + { + return $this->option()->reject($value); + } + + /** + * @return Traversable<T> + */ + public function getIterator(): Traversable + { + return $this->option()->getIterator(); + } + + public function foldLeft($initialValue, $callable) + { + return $this->option()->foldLeft($initialValue, $callable); + } + + public function foldRight($initialValue, $callable) + { + return $this->option()->foldRight($initialValue, $callable); + } + + /** + * @return Option<T> + */ + private function option(): Option + { + if (null === $this->option) { + /** @var mixed */ + $option = call_user_func_array($this->callback, $this->arguments); + if ($option instanceof Option) { + $this->option = $option; + } else { + throw new \RuntimeException(sprintf('Expected instance of %s', Option::class)); + } + } + + return $this->option; + } +} diff --git a/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/None.php b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/None.php new file mode 100644 index 0000000..4b85d22 --- /dev/null +++ b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/None.php @@ -0,0 +1,136 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use EmptyIterator; + +/** + * @extends Option<mixed> + */ +final class None extends Option +{ + /** @var None|null */ + private static $instance; + + /** + * @return None + */ + public static function create(): self + { + if (null === self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + public function get() + { + throw new \RuntimeException('None has no value.'); + } + + public function getOrCall($callable) + { + return $callable(); + } + + public function getOrElse($default) + { + return $default; + } + + public function getOrThrow(\Exception $ex) + { + throw $ex; + } + + public function isEmpty(): bool + { + return true; + } + + public function isDefined(): bool + { + return false; + } + + public function orElse(Option $else) + { + return $else; + } + + public function ifDefined($callable) + { + // Just do nothing in that case. + } + + public function forAll($callable) + { + return $this; + } + + public function map($callable) + { + return $this; + } + + public function flatMap($callable) + { + return $this; + } + + public function filter($callable) + { + return $this; + } + + public function filterNot($callable) + { + return $this; + } + + public function select($value) + { + return $this; + } + + public function reject($value) + { + return $this; + } + + public function getIterator(): EmptyIterator + { + return new EmptyIterator(); + } + + public function foldLeft($initialValue, $callable) + { + return $initialValue; + } + + public function foldRight($initialValue, $callable) + { + return $initialValue; + } + + private function __construct() + { + } +} diff --git a/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/Option.php b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/Option.php new file mode 100644 index 0000000..172924c --- /dev/null +++ b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/Option.php @@ -0,0 +1,434 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use ArrayAccess; +use IteratorAggregate; + +/** + * @template T + * + * @implements IteratorAggregate<T> + */ +abstract class Option implements IteratorAggregate +{ + /** + * Creates an option given a return value. + * + * This is intended for consuming existing APIs and allows you to easily + * convert them to an option. By default, we treat ``null`` as the None + * case, and everything else as Some. + * + * @template S + * + * @param S $value The actual return value. + * @param S $noneValue The value which should be considered "None"; null by + * default. + * + * @return Option<S> + */ + public static function fromValue($value, $noneValue = null) + { + if ($value === $noneValue) { + return None::create(); + } + + return new Some($value); + } + + /** + * Creates an option from an array's value. + * + * If the key does not exist in the array, the array is not actually an + * array, or the array's value at the given key is null, None is returned. + * Otherwise, Some is returned wrapping the value at the given key. + * + * @template S + * + * @param array<string|int,S>|ArrayAccess<string|int,S>|null $array A potential array or \ArrayAccess value. + * @param string $key The key to check. + * + * @return Option<S> + */ + public static function fromArraysValue($array, $key) + { + if (!(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) { + return None::create(); + } + + return new Some($array[$key]); + } + + /** + * Creates a lazy-option with the given callback. + * + * This is also a helper constructor for lazy-consuming existing APIs where + * the return value is not yet an option. By default, we treat ``null`` as + * None case, and everything else as Some. + * + * @template S + * + * @param callable $callback The callback to evaluate. + * @param array $arguments The arguments for the callback. + * @param S $noneValue The value which should be considered "None"; + * null by default. + * + * @return LazyOption<S> + */ + public static function fromReturn($callback, array $arguments = [], $noneValue = null) + { + return new LazyOption(static function () use ($callback, $arguments, $noneValue) { + /** @var mixed */ + $return = call_user_func_array($callback, $arguments); + + if ($return === $noneValue) { + return None::create(); + } + + return new Some($return); + }); + } + + /** + * Option factory, which creates new option based on passed value. + * + * If value is already an option, it simply returns. If value is callable, + * LazyOption with passed callback created and returned. If Option + * returned from callback, it returns directly. On other case value passed + * to Option::fromValue() method. + * + * @template S + * + * @param Option<S>|callable|S $value + * @param S $noneValue Used when $value is mixed or + * callable, for None-check. + * + * @return Option<S>|LazyOption<S> + */ + public static function ensure($value, $noneValue = null) + { + if ($value instanceof self) { + return $value; + } elseif (is_callable($value)) { + return new LazyOption(static function () use ($value, $noneValue) { + /** @var mixed */ + $return = $value(); + + if ($return instanceof self) { + return $return; + } else { + return self::fromValue($return, $noneValue); + } + }); + } else { + return self::fromValue($value, $noneValue); + } + } + + /** + * Lift a function so that it accepts Option as parameters. + * + * We return a new closure that wraps the original callback. If any of the + * parameters passed to the lifted function is empty, the function will + * return a value of None. Otherwise, we will pass all parameters to the + * original callback and return the value inside a new Option, unless an + * Option is returned from the function, in which case, we use that. + * + * @template S + * + * @param callable $callback + * @param mixed $noneValue + * + * @return callable + */ + public static function lift($callback, $noneValue = null) + { + return static function () use ($callback, $noneValue) { + /** @var array<int, mixed> */ + $args = func_get_args(); + + $reduced_args = array_reduce( + $args, + /** @param bool $status */ + static function ($status, self $o) { + return $o->isEmpty() ? true : $status; + }, + false + ); + // if at least one parameter is empty, return None + if ($reduced_args) { + return None::create(); + } + + $args = array_map( + /** @return T */ + static function (self $o) { + // it is safe to do so because the fold above checked + // that all arguments are of type Some + /** @var T */ + return $o->get(); + }, + $args + ); + + return self::ensure(call_user_func_array($callback, $args), $noneValue); + }; + } + + /** + * Returns the value if available, or throws an exception otherwise. + * + * @throws \RuntimeException If value is not available. + * + * @return T + */ + abstract public function get(); + + /** + * Returns the value if available, or the default value if not. + * + * @template S + * + * @param S $default + * + * @return T|S + */ + abstract public function getOrElse($default); + + /** + * Returns the value if available, or the results of the callable. + * + * This is preferable over ``getOrElse`` if the computation of the default + * value is expensive. + * + * @template S + * + * @param callable():S $callable + * + * @return T|S + */ + abstract public function getOrCall($callable); + + /** + * Returns the value if available, or throws the passed exception. + * + * @param \Exception $ex + * + * @return T + */ + abstract public function getOrThrow(\Exception $ex); + + /** + * Returns true if no value is available, false otherwise. + * + * @return bool + */ + abstract public function isEmpty(); + + /** + * Returns true if a value is available, false otherwise. + * + * @return bool + */ + abstract public function isDefined(); + + /** + * Returns this option if non-empty, or the passed option otherwise. + * + * This can be used to try multiple alternatives, and is especially useful + * with lazy evaluating options: + * + * ```php + * $repo->findSomething() + * ->orElse(new LazyOption(array($repo, 'findSomethingElse'))) + * ->orElse(new LazyOption(array($repo, 'createSomething'))); + * ``` + * + * @param Option<T> $else + * + * @return Option<T> + */ + abstract public function orElse(self $else); + + /** + * This is similar to map() below except that the return value has no meaning; + * the passed callable is simply executed if the option is non-empty, and + * ignored if the option is empty. + * + * In all cases, the return value of the callable is discarded. + * + * ```php + * $comment->getMaybeFile()->ifDefined(function($file) { + * // Do something with $file here. + * }); + * ``` + * + * If you're looking for something like ``ifEmpty``, you can use ``getOrCall`` + * and ``getOrElse`` in these cases. + * + * @deprecated Use forAll() instead. + * + * @param callable(T):mixed $callable + * + * @return void + */ + abstract public function ifDefined($callable); + + /** + * This is similar to map() except that the return value of the callable has no meaning. + * + * The passed callable is simply executed if the option is non-empty, and ignored if the + * option is empty. This method is preferred for callables with side-effects, while map() + * is intended for callables without side-effects. + * + * @param callable(T):mixed $callable + * + * @return Option<T> + */ + abstract public function forAll($callable); + + /** + * Applies the callable to the value of the option if it is non-empty, + * and returns the return value of the callable wrapped in Some(). + * + * If the option is empty, then the callable is not applied. + * + * ```php + * (new Some("foo"))->map('strtoupper')->get(); // "FOO" + * ``` + * + * @template S + * + * @param callable(T):S $callable + * + * @return Option<S> + */ + abstract public function map($callable); + + /** + * Applies the callable to the value of the option if it is non-empty, and + * returns the return value of the callable directly. + * + * In contrast to ``map``, the return value of the callable is expected to + * be an Option itself; it is not automatically wrapped in Some(). + * + * @template S + * + * @param callable(T):Option<S> $callable must return an Option + * + * @return Option<S> + */ + abstract public function flatMap($callable); + + /** + * If the option is empty, it is returned immediately without applying the callable. + * + * If the option is non-empty, the callable is applied, and if it returns true, + * the option itself is returned; otherwise, None is returned. + * + * @param callable(T):bool $callable + * + * @return Option<T> + */ + abstract public function filter($callable); + + /** + * If the option is empty, it is returned immediately without applying the callable. + * + * If the option is non-empty, the callable is applied, and if it returns false, + * the option itself is returned; otherwise, None is returned. + * + * @param callable(T):bool $callable + * + * @return Option<T> + */ + abstract public function filterNot($callable); + + /** + * If the option is empty, it is returned immediately. + * + * If the option is non-empty, and its value does not equal the passed value + * (via a shallow comparison ===), then None is returned. Otherwise, the + * Option is returned. + * + * In other words, this will filter all but the passed value. + * + * @param T $value + * + * @return Option<T> + */ + abstract public function select($value); + + /** + * If the option is empty, it is returned immediately. + * + * If the option is non-empty, and its value does equal the passed value (via + * a shallow comparison ===), then None is returned; otherwise, the Option is + * returned. + * + * In other words, this will let all values through except the passed value. + * + * @param T $value + * + * @return Option<T> + */ + abstract public function reject($value); + + /** + * Binary operator for the initial value and the option's value. + * + * If empty, the initial value is returned. If non-empty, the callable + * receives the initial value and the option's value as arguments. + * + * ```php + * + * $some = new Some(5); + * $none = None::create(); + * $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6) + * $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1) + * + * // This can be used instead of something like the following: + * $option = Option::fromValue($integerOrNull); + * $result = 1; + * if ( ! $option->isEmpty()) { + * $result += $option->get(); + * } + * ``` + * + * @template S + * + * @param S $initialValue + * @param callable(S, T):S $callable + * + * @return S + */ + abstract public function foldLeft($initialValue, $callable); + + /** + * foldLeft() but with reversed arguments for the callable. + * + * @template S + * + * @param S $initialValue + * @param callable(T, S):S $callable + * + * @return S + */ + abstract public function foldRight($initialValue, $callable); +} diff --git a/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/Some.php b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/Some.php new file mode 100644 index 0000000..032632e --- /dev/null +++ b/php/libraries/composer/vendor/phpoption/phpoption/src/PhpOption/Some.php @@ -0,0 +1,169 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use ArrayIterator; + +/** + * @template T + * + * @extends Option<T> + */ +final class Some extends Option +{ + /** @var T */ + private $value; + + /** + * @param T $value + */ + public function __construct($value) + { + $this->value = $value; + } + + /** + * @template U + * + * @param U $value + * + * @return Some<U> + */ + public static function create($value): self + { + return new self($value); + } + + public function isDefined(): bool + { + return true; + } + + public function isEmpty(): bool + { + return false; + } + + public function get() + { + return $this->value; + } + + public function getOrElse($default) + { + return $this->value; + } + + public function getOrCall($callable) + { + return $this->value; + } + + public function getOrThrow(\Exception $ex) + { + return $this->value; + } + + public function orElse(Option $else) + { + return $this; + } + + public function ifDefined($callable) + { + $this->forAll($callable); + } + + public function forAll($callable) + { + $callable($this->value); + + return $this; + } + + public function map($callable) + { + return new self($callable($this->value)); + } + + public function flatMap($callable) + { + /** @var mixed */ + $rs = $callable($this->value); + if (!$rs instanceof Option) { + throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?'); + } + + return $rs; + } + + public function filter($callable) + { + if (true === $callable($this->value)) { + return $this; + } + + return None::create(); + } + + public function filterNot($callable) + { + if (false === $callable($this->value)) { + return $this; + } + + return None::create(); + } + + public function select($value) + { + if ($this->value === $value) { + return $this; + } + + return None::create(); + } + + public function reject($value) + { + if ($this->value === $value) { + return None::create(); + } + + return $this; + } + + /** + * @return ArrayIterator<int, T> + */ + public function getIterator(): ArrayIterator + { + return new ArrayIterator([$this->value]); + } + + public function foldLeft($initialValue, $callable) + { + return $callable($initialValue, $this->value); + } + + public function foldRight($initialValue, $callable) + { + return $callable($this->value, $initialValue); + } +} diff --git a/php/libraries/composer/vendor/psr/clock/CHANGELOG.md b/php/libraries/composer/vendor/psr/clock/CHANGELOG.md new file mode 100644 index 0000000..3cd6b9b --- /dev/null +++ b/php/libraries/composer/vendor/psr/clock/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.0 + +First stable release after PSR-20 acceptance + +## 0.1.0 + +First release diff --git a/php/libraries/composer/vendor/psr/clock/LICENSE b/php/libraries/composer/vendor/psr/clock/LICENSE new file mode 100644 index 0000000..be68342 --- /dev/null +++ b/php/libraries/composer/vendor/psr/clock/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 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/php/libraries/composer/vendor/psr/clock/README.md b/php/libraries/composer/vendor/psr/clock/README.md new file mode 100644 index 0000000..6ca877e --- /dev/null +++ b/php/libraries/composer/vendor/psr/clock/README.md @@ -0,0 +1,61 @@ +# PSR Clock + +This repository holds the interface for [PSR-20][psr-url]. + +Note that this is not a clock of its own. It is merely an interface that +describes a clock. See the specification for more details. + +## Installation + +```bash +composer require psr/clock +``` + +## Usage + +If you need a clock, you can use the interface like this: + +```php +<?php + +use Psr\Clock\ClockInterface; + +class Foo +{ + private ClockInterface $clock; + + public function __construct(ClockInterface $clock) + { + $this->clock = $clock; + } + + public function doSomething() + { + /** @var DateTimeImmutable $currentDateAndTime */ + $currentDateAndTime = $this->clock->now(); + // do something useful with that information + } +} +``` + +You can then pick one of the [implementations][implementation-url] of the interface to get a clock. + +If you want to implement the interface, you can require this package and +implement `Psr\Clock\ClockInterface` in your code. + +Don't forget to add `psr/clock-implementation` to your `composer.json`s `provides`-section like this: + +```json +{ + "provides": { + "psr/clock-implementation": "1.0" + } +} +``` + +And please read the [specification text][specification-url] for details on the interface. + +[psr-url]: https://www.php-fig.org/psr/psr-20 +[package-url]: https://packagist.org/packages/psr/clock +[implementation-url]: https://packagist.org/providers/psr/clock-implementation +[specification-url]: https://github.com/php-fig/fig-standards/blob/master/proposed/clock.md diff --git a/php/libraries/composer/vendor/psr/clock/composer.json b/php/libraries/composer/vendor/psr/clock/composer.json new file mode 100644 index 0000000..77992ed --- /dev/null +++ b/php/libraries/composer/vendor/psr/clock/composer.json @@ -0,0 +1,21 @@ +{ + "name": "psr/clock", + "description": "Common interface for reading the clock.", + "keywords": ["psr", "psr-20", "time", "clock", "now"], + "homepage": "https://github.com/php-fig/clock", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": "^7.0 || ^8.0" + }, + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + } +} diff --git a/php/libraries/composer/vendor/psr/clock/src/ClockInterface.php b/php/libraries/composer/vendor/psr/clock/src/ClockInterface.php new file mode 100644 index 0000000..7b6d8d8 --- /dev/null +++ b/php/libraries/composer/vendor/psr/clock/src/ClockInterface.php @@ -0,0 +1,13 @@ +<?php + +namespace Psr\Clock; + +use DateTimeImmutable; + +interface ClockInterface +{ + /** + * Returns the current time as a DateTimeImmutable Object + */ + public function now(): DateTimeImmutable; +} diff --git a/php/libraries/composer/vendor/psr/container/.gitignore b/php/libraries/composer/vendor/psr/container/.gitignore new file mode 100644 index 0000000..b2395aa --- /dev/null +++ b/php/libraries/composer/vendor/psr/container/.gitignore @@ -0,0 +1,3 @@ +composer.lock +composer.phar +/vendor/ diff --git a/php/libraries/composer/vendor/psr/container/LICENSE b/php/libraries/composer/vendor/psr/container/LICENSE new file mode 100644 index 0000000..2877a48 --- /dev/null +++ b/php/libraries/composer/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/php/libraries/composer/vendor/psr/container/README.md b/php/libraries/composer/vendor/psr/container/README.md new file mode 100644 index 0000000..1b9d9e5 --- /dev/null +++ b/php/libraries/composer/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/php/libraries/composer/vendor/psr/container/composer.json b/php/libraries/composer/vendor/psr/container/composer.json new file mode 100644 index 0000000..017f41e --- /dev/null +++ b/php/libraries/composer/vendor/psr/container/composer.json @@ -0,0 +1,22 @@ +{ + "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/" + } + } +} diff --git a/php/libraries/composer/vendor/psr/container/src/ContainerExceptionInterface.php b/php/libraries/composer/vendor/psr/container/src/ContainerExceptionInterface.php new file mode 100644 index 0000000..0f213f2 --- /dev/null +++ b/php/libraries/composer/vendor/psr/container/src/ContainerExceptionInterface.php @@ -0,0 +1,12 @@ +<?php + +namespace Psr\Container; + +use Throwable; + +/** + * Base interface representing a generic exception in a container. + */ +interface ContainerExceptionInterface extends Throwable +{ +} diff --git a/php/libraries/composer/vendor/psr/container/src/ContainerInterface.php b/php/libraries/composer/vendor/psr/container/src/ContainerInterface.php new file mode 100644 index 0000000..cf8e7fd --- /dev/null +++ b/php/libraries/composer/vendor/psr/container/src/ContainerInterface.php @@ -0,0 +1,36 @@ +<?php + +declare(strict_types=1); + +namespace Psr\Container; + +/** + * Describes the interface of a container that exposes methods to read its entries. + */ +interface ContainerInterface +{ + /** + * Finds an entry of the container by its identifier and returns it. + * + * @param string $id Identifier of the entry to look for. + * + * @throws NotFoundExceptionInterface No entry was found for **this** identifier. + * @throws ContainerExceptionInterface Error while retrieving the entry. + * + * @return mixed Entry. + */ + public function get(string $id); + + /** + * Returns true if the container can return an entry for the given identifier. + * Returns false otherwise. + * + * `has($id)` returning true does not mean that `get($id)` will not throw an exception. + * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`. + * + * @param string $id Identifier of the entry to look for. + * + * @return bool + */ + public function has(string $id); +} diff --git a/php/libraries/composer/vendor/psr/container/src/NotFoundExceptionInterface.php b/php/libraries/composer/vendor/psr/container/src/NotFoundExceptionInterface.php new file mode 100644 index 0000000..650bf46 --- /dev/null +++ b/php/libraries/composer/vendor/psr/container/src/NotFoundExceptionInterface.php @@ -0,0 +1,10 @@ +<?php + +namespace Psr\Container; + +/** + * No entry was found in the container. + */ +interface NotFoundExceptionInterface extends ContainerExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/.editorconfig b/php/libraries/composer/vendor/psr/event-dispatcher/.editorconfig new file mode 100644 index 0000000..164f092 --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[Makefile] +indent_style = tab diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/.gitignore b/php/libraries/composer/vendor/psr/event-dispatcher/.gitignore new file mode 100644 index 0000000..3a9875b --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/.gitignore @@ -0,0 +1,2 @@ +/vendor/ +composer.lock diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/LICENSE b/php/libraries/composer/vendor/psr/event-dispatcher/LICENSE new file mode 100644 index 0000000..3f1559b --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 PHP-FIG + +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/php/libraries/composer/vendor/psr/event-dispatcher/README.md b/php/libraries/composer/vendor/psr/event-dispatcher/README.md new file mode 100644 index 0000000..294214a --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/README.md @@ -0,0 +1,6 @@ +PSR Event Dispatcher +==================== + +This repository holds the interfaces related to [PSR-14](http://www.php-fig.org/psr/psr-14/). + +Note that this is not an Event Dispatcher implementation of its own. It is merely interfaces that describe the components of an Event Dispatcher. See the specification for more details. diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/composer.json b/php/libraries/composer/vendor/psr/event-dispatcher/composer.json new file mode 100644 index 0000000..667a714 --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/event-dispatcher", + "description": "Standard interfaces for event handling.", + "type": "library", + "keywords": ["psr", "psr-14", "events"], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.2.0" + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php b/php/libraries/composer/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php new file mode 100644 index 0000000..4306fa9 --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php @@ -0,0 +1,21 @@ +<?php +declare(strict_types=1); + +namespace Psr\EventDispatcher; + +/** + * Defines a dispatcher for events. + */ +interface EventDispatcherInterface +{ + /** + * Provide all relevant listeners with an event to process. + * + * @param object $event + * The object to process. + * + * @return object + * The Event that was passed, now modified by listeners. + */ + public function dispatch(object $event); +} diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/src/ListenerProviderInterface.php b/php/libraries/composer/vendor/psr/event-dispatcher/src/ListenerProviderInterface.php new file mode 100644 index 0000000..bdacb6e --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/src/ListenerProviderInterface.php @@ -0,0 +1,19 @@ +<?php +declare(strict_types=1); + +namespace Psr\EventDispatcher; + +/** + * Mapper from an event to the listeners that are applicable to that event. + */ +interface ListenerProviderInterface +{ + /** + * @param object $event + * An event for which to return the relevant listeners. + * @return iterable[callable] + * An iterable (array, iterator, or generator) of callables. Each + * callable MUST be type-compatible with $event. + */ + public function getListenersForEvent(object $event) : iterable; +} diff --git a/php/libraries/composer/vendor/psr/event-dispatcher/src/StoppableEventInterface.php b/php/libraries/composer/vendor/psr/event-dispatcher/src/StoppableEventInterface.php new file mode 100644 index 0000000..5955081 --- /dev/null +++ b/php/libraries/composer/vendor/psr/event-dispatcher/src/StoppableEventInterface.php @@ -0,0 +1,26 @@ +<?php +declare(strict_types=1); + +namespace Psr\EventDispatcher; + +/** + * An Event whose processing may be interrupted when the event has been handled. + * + * A Dispatcher implementation MUST check to determine if an Event + * is marked as stopped after each listener is called. If it is then it should + * return immediately without calling any further Listeners. + */ +interface StoppableEventInterface +{ + /** + * Is propagation stopped? + * + * This will typically only be used by the Dispatcher to determine if the + * previous listener halted propagation. + * + * @return bool + * True if the Event is complete and no further listeners should be called. + * False to continue calling listeners. + */ + public function isPropagationStopped() : bool; +} diff --git a/php/libraries/composer/vendor/psr/http-client/CHANGELOG.md b/php/libraries/composer/vendor/psr/http-client/CHANGELOG.md new file mode 100644 index 0000000..babba7c --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.3 + +Add `source` link in composer.json. No code changes. + +## 1.0.2 + +Allow PSR-7 (psr/http-message) 2.0. No code changes. + +## 1.0.1 + +Allow installation with PHP 8. No code changes. + +## 1.0.0 + +First stable release. No changes since 0.3.0. + +## 0.3.0 + +Added Interface suffix on exceptions + +## 0.2.0 + +All exceptions are in `Psr\Http\Client` namespace + +## 0.1.0 + +First release diff --git a/php/libraries/composer/vendor/psr/http-client/LICENSE b/php/libraries/composer/vendor/psr/http-client/LICENSE new file mode 100644 index 0000000..cd5e002 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 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/php/libraries/composer/vendor/psr/http-client/README.md b/php/libraries/composer/vendor/psr/http-client/README.md new file mode 100644 index 0000000..84af5c5 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/README.md @@ -0,0 +1,12 @@ +HTTP Client +=========== + +This repository holds all the common code related to [PSR-18 (HTTP Client)][psr-url]. + +Note that this is not a HTTP Client implementation of its own. It is merely abstractions that describe the components of a HTTP Client. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-18 +[package-url]: https://packagist.org/packages/psr/http-client +[implementation-url]: https://packagist.org/providers/psr/http-client-implementation diff --git a/php/libraries/composer/vendor/psr/http-client/composer.json b/php/libraries/composer/vendor/psr/http-client/composer.json new file mode 100644 index 0000000..6fed350 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/composer.json @@ -0,0 +1,30 @@ +{ + "name": "psr/http-client", + "description": "Common interface for HTTP clients", + "keywords": ["psr", "psr-18", "http", "http-client"], + "homepage": "https://github.com/php-fig/http-client", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/psr/http-client/src/ClientExceptionInterface.php b/php/libraries/composer/vendor/psr/http-client/src/ClientExceptionInterface.php new file mode 100644 index 0000000..aa0b9cf --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/src/ClientExceptionInterface.php @@ -0,0 +1,10 @@ +<?php + +namespace Psr\Http\Client; + +/** + * Every HTTP client related exception MUST implement this interface. + */ +interface ClientExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/psr/http-client/src/ClientInterface.php b/php/libraries/composer/vendor/psr/http-client/src/ClientInterface.php new file mode 100644 index 0000000..ad99fd4 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/src/ClientInterface.php @@ -0,0 +1,20 @@ +<?php + +namespace Psr\Http\Client; + +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + +interface ClientInterface +{ + /** + * Sends a PSR-7 request and returns a PSR-7 response. + * + * @param RequestInterface $request + * + * @return ResponseInterface + * + * @throws \Psr\Http\Client\ClientExceptionInterface If an error happens while processing the request. + */ + public function sendRequest(RequestInterface $request): ResponseInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-client/src/NetworkExceptionInterface.php b/php/libraries/composer/vendor/psr/http-client/src/NetworkExceptionInterface.php new file mode 100644 index 0000000..4a11627 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/src/NetworkExceptionInterface.php @@ -0,0 +1,24 @@ +<?php + +namespace Psr\Http\Client; + +use Psr\Http\Message\RequestInterface; + +/** + * Thrown when the request cannot be completed because of network issues. + * + * There is no response object as this exception is thrown when no response has been received. + * + * Example: the target host name can not be resolved or the connection failed. + */ +interface NetworkExceptionInterface extends ClientExceptionInterface +{ + /** + * Returns the request. + * + * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() + * + * @return RequestInterface + */ + public function getRequest(): RequestInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-client/src/RequestExceptionInterface.php b/php/libraries/composer/vendor/psr/http-client/src/RequestExceptionInterface.php new file mode 100644 index 0000000..b17fc34 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-client/src/RequestExceptionInterface.php @@ -0,0 +1,24 @@ +<?php + +namespace Psr\Http\Client; + +use Psr\Http\Message\RequestInterface; + +/** + * Exception for when a request failed. + * + * Examples: + * - Request is invalid (e.g. method is missing) + * - Runtime request errors (e.g. the body stream is not seekable) + */ +interface RequestExceptionInterface extends ClientExceptionInterface +{ + /** + * Returns the request. + * + * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() + * + * @return RequestInterface + */ + public function getRequest(): RequestInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-factory/LICENSE b/php/libraries/composer/vendor/psr/http-factory/LICENSE new file mode 100644 index 0000000..3f1559b --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 PHP-FIG + +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/php/libraries/composer/vendor/psr/http-factory/README.md b/php/libraries/composer/vendor/psr/http-factory/README.md new file mode 100644 index 0000000..bf8913b --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/README.md @@ -0,0 +1,12 @@ +HTTP Factories +============== + +This repository holds all interfaces related to [PSR-17 (HTTP Factories)][psr-url]. + +Note that this is not a HTTP Factory implementation of its own. It is merely interfaces that describe the components of a HTTP Factory. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-17/ +[package-url]: https://packagist.org/packages/psr/http-factory +[implementation-url]: https://packagist.org/providers/psr/http-factory-implementation diff --git a/php/libraries/composer/vendor/psr/http-factory/composer.json b/php/libraries/composer/vendor/psr/http-factory/composer.json new file mode 100644 index 0000000..d1bbdde --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/composer.json @@ -0,0 +1,35 @@ +{ + "name": "psr/http-factory", + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "psr", + "psr-7", + "psr-17", + "http", + "factory", + "message", + "request", + "response" + ], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/psr/http-factory/src/RequestFactoryInterface.php b/php/libraries/composer/vendor/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 0000000..cb39a08 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Http\Message; + +interface RequestFactoryInterface +{ + /** + * Create a new request. + * + * @param string $method The HTTP method associated with the request. + * @param UriInterface|string $uri The URI associated with the request. If + * the value is a string, the factory MUST create a UriInterface + * instance based on it. + * + * @return RequestInterface + */ + public function createRequest(string $method, $uri): RequestInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-factory/src/ResponseFactoryInterface.php b/php/libraries/composer/vendor/psr/http-factory/src/ResponseFactoryInterface.php new file mode 100644 index 0000000..212562f --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/src/ResponseFactoryInterface.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Http\Message; + +interface ResponseFactoryInterface +{ + /** + * Create a new response. + * + * @param int $code HTTP status code; defaults to 200 + * @param string $reasonPhrase Reason phrase to associate with status code + * in generated response; if none is provided implementations MAY use + * the defaults as suggested in the HTTP specification. + * + * @return ResponseInterface + */ + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php b/php/libraries/composer/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php new file mode 100644 index 0000000..9fe031a --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php @@ -0,0 +1,24 @@ +<?php + +namespace Psr\Http\Message; + +interface ServerRequestFactoryInterface +{ + /** + * Create a new server request. + * + * Note that server-params are taken precisely as given - no parsing/processing + * of the given values is performed, and, in particular, no attempt is made to + * determine the HTTP method or URI, which must be provided explicitly. + * + * @param string $method The HTTP method associated with the request. + * @param UriInterface|string $uri The URI associated with the request. If + * the value is a string, the factory MUST create a UriInterface + * instance based on it. + * @param array $serverParams Array of SAPI parameters with which to seed + * the generated request instance. + * + * @return ServerRequestInterface + */ + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-factory/src/StreamFactoryInterface.php b/php/libraries/composer/vendor/psr/http-factory/src/StreamFactoryInterface.php new file mode 100644 index 0000000..90e3240 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/src/StreamFactoryInterface.php @@ -0,0 +1,45 @@ +<?php + +namespace Psr\Http\Message; + +interface StreamFactoryInterface +{ + /** + * Create a new stream from a string. + * + * The stream SHOULD be created with a temporary resource. + * + * @param string $content String content with which to populate the stream. + * + * @return StreamInterface + */ + public function createStream(string $content = ''): StreamInterface; + + /** + * Create a stream from an existing file. + * + * The file MUST be opened using the given mode, which may be any mode + * supported by the `fopen` function. + * + * The `$filename` MAY be any string supported by `fopen()`. + * + * @param string $filename Filename or stream URI to use as basis of stream. + * @param string $mode Mode with which to open the underlying filename/stream. + * + * @return StreamInterface + * @throws \RuntimeException If the file cannot be opened. + * @throws \InvalidArgumentException If the mode is invalid. + */ + public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface; + + /** + * Create a new stream from an existing resource. + * + * The stream MUST be readable and may be writable. + * + * @param resource $resource PHP resource to use as basis of stream. + * + * @return StreamInterface + */ + public function createStreamFromResource($resource): StreamInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php b/php/libraries/composer/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php new file mode 100644 index 0000000..7db4e30 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php @@ -0,0 +1,34 @@ +<?php + +namespace Psr\Http\Message; + +interface UploadedFileFactoryInterface +{ + /** + * Create a new uploaded file. + * + * If a size is not provided it will be determined by checking the size of + * the file. + * + * @see http://php.net/manual/features.file-upload.post-method.php + * @see http://php.net/manual/features.file-upload.errors.php + * + * @param StreamInterface $stream Underlying stream representing the + * uploaded file content. + * @param int $size in bytes + * @param int $error PHP file upload error + * @param string $clientFilename Filename as provided by the client, if any. + * @param string $clientMediaType Media type as provided by the client, if any. + * + * @return UploadedFileInterface + * + * @throws \InvalidArgumentException If the file resource is not readable. + */ + public function createUploadedFile( + StreamInterface $stream, + int $size = null, + int $error = \UPLOAD_ERR_OK, + string $clientFilename = null, + string $clientMediaType = null + ): UploadedFileInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-factory/src/UriFactoryInterface.php b/php/libraries/composer/vendor/psr/http-factory/src/UriFactoryInterface.php new file mode 100644 index 0000000..06df0b4 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-factory/src/UriFactoryInterface.php @@ -0,0 +1,17 @@ +<?php + +namespace Psr\Http\Message; + +interface UriFactoryInterface +{ + /** + * Create a new URI. + * + * @param string $uri + * + * @return UriInterface + * + * @throws \InvalidArgumentException If the given URI cannot be parsed. + */ + public function createUri(string $uri = ''): UriInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-message/CHANGELOG.md b/php/libraries/composer/vendor/psr/http-message/CHANGELOG.md new file mode 100644 index 0000000..74b1ef9 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 - 2016-08-06 + +### Added + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Updated all `@return self` annotation references in interfaces to use + `@return static`, which more closelly follows the semantics of the + specification. +- Updated the `MessageInterface::getHeaders()` return annotation to use the + value `string[][]`, indicating the format is a nested array of strings. +- Updated the `@link` annotation for `RequestInterface::withRequestTarget()` + to point to the correct section of RFC 7230. +- Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation + to add the parameter name (`$uploadedFiles`). +- Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` + method to correctly reference the method parameter (it was referencing an + incorrect parameter name previously). + +## 1.0.0 - 2016-05-18 + +Initial stable release; reflects accepted PSR-7 specification. diff --git a/php/libraries/composer/vendor/psr/http-message/LICENSE b/php/libraries/composer/vendor/psr/http-message/LICENSE new file mode 100644 index 0000000..c2d8e45 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 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/php/libraries/composer/vendor/psr/http-message/README.md b/php/libraries/composer/vendor/psr/http-message/README.md new file mode 100644 index 0000000..2668be6 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/README.md @@ -0,0 +1,16 @@ +PSR Http Message +================ + +This repository holds all interfaces/classes/traits related to +[PSR-7](http://www.php-fig.org/psr/psr-7/). + +Note that this is not a HTTP message implementation of its own. It is merely an +interface that describes a HTTP message. See the specification for more details. + +Usage +----- + +Before reading the usage guide we recommend reading the PSR-7 interfaces method list: + +* [`PSR-7 Interfaces Method List`](docs/PSR7-Interfaces.md) +* [`PSR-7 Usage Guide`](docs/PSR7-Usage.md) \ No newline at end of file diff --git a/php/libraries/composer/vendor/psr/http-message/composer.json b/php/libraries/composer/vendor/psr/http-message/composer.json new file mode 100644 index 0000000..c66e5ab --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/http-message", + "description": "Common interface for HTTP messages", + "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], + "homepage": "https://github.com/php-fig/http-message", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": "^7.2 || ^8.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/psr/http-message/docs/PSR7-Interfaces.md b/php/libraries/composer/vendor/psr/http-message/docs/PSR7-Interfaces.md new file mode 100644 index 0000000..3a7e7dd --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/docs/PSR7-Interfaces.md @@ -0,0 +1,130 @@ +# Interfaces + +The purpose of this list is to help in finding the methods when working with PSR-7. This can be considered as a cheatsheet for PSR-7 interfaces. + +The interfaces defined in PSR-7 are the following: + +| Class Name | Description | +|---|---| +| [Psr\Http\Message\MessageInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagemessageinterface) | Representation of a HTTP message | +| [Psr\Http\Message\RequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagerequestinterface) | Representation of an outgoing, client-side request. | +| [Psr\Http\Message\ServerRequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageserverrequestinterface) | Representation of an incoming, server-side HTTP request. | +| [Psr\Http\Message\ResponseInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageresponseinterface) | Representation of an outgoing, server-side response. | +| [Psr\Http\Message\StreamInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagestreaminterface) | Describes a data stream | +| [Psr\Http\Message\UriInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuriinterface) | Value object representing a URI. | +| [Psr\Http\Message\UploadedFileInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuploadedfileinterface) | Value object representing a file uploaded through an HTTP request. | + +## `Psr\Http\Message\MessageInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getProtocolVersion()` | Retrieve HTTP protocol version | 1.0 or 1.1 | +| `withProtocolVersion($version)` | Returns new message instance with given HTTP protocol version | | +| `getHeaders()` | Retrieve all HTTP Headers | [Request Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields), [Response Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Response_fields) | +| `hasHeader($name)` | Checks if HTTP Header with given name exists | | +| `getHeader($name)` | Retrieves a array with the values for a single header | | +| `getHeaderLine($name)` | Retrieves a comma-separated string of the values for a single header | | +| `withHeader($name, $value)` | Returns new message instance with given HTTP Header | if the header existed in the original instance, replaces the header value from the original message with the value provided when creating the new instance. | +| `withAddedHeader($name, $value)` | Returns new message instance with appended value to given header | If header already exists value will be appended, if not a new header will be created | +| `withoutHeader($name)` | Removes HTTP Header with given name| | +| `getBody()` | Retrieves the HTTP Message Body | Returns object implementing `StreamInterface`| +| `withBody(StreamInterface $body)` | Returns new message instance with given HTTP Message Body | | + + +## `Psr\Http\Message\RequestInterface` Methods + +Same methods as `Psr\Http\Message\MessageInterface` + the following methods: + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getRequestTarget()` | Retrieves the message's request target | origin-form, absolute-form, authority-form, asterisk-form ([RFC7230](https://www.rfc-editor.org/rfc/rfc7230.txt)) | +| `withRequestTarget($requestTarget)` | Return a new message instance with the specific request-target | | +| `getMethod()` | Retrieves the HTTP method of the request. | GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE (defined in [RFC7231](https://tools.ietf.org/html/rfc7231)), PATCH (defined in [RFC5789](https://tools.ietf.org/html/rfc5789)) | +| `withMethod($method)` | Returns a new message instance with the provided HTTP method | | +| `getUri()` | Retrieves the URI instance | | +| `withUri(UriInterface $uri, $preserveHost = false)` | Returns a new message instance with the provided URI | | + + +## `Psr\Http\Message\ServerRequestInterface` Methods + +Same methods as `Psr\Http\Message\RequestInterface` + the following methods: + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getServerParams() ` | Retrieve server parameters | Typically derived from `$_SERVER` | +| `getCookieParams()` | Retrieves cookies sent by the client to the server. | Typically derived from `$_COOKIES` | +| `withCookieParams(array $cookies)` | Returns a new request instance with the specified cookies | | +| `withQueryParams(array $query)` | Returns a new request instance with the specified query string arguments | | +| `getUploadedFiles()` | Retrieve normalized file upload data | | +| `withUploadedFiles(array $uploadedFiles)` | Returns a new request instance with the specified uploaded files | | +| `getParsedBody()` | Retrieve any parameters provided in the request body | | +| `withParsedBody($data)` | Returns a new request instance with the specified body parameters | | +| `getAttributes()` | Retrieve attributes derived from the request | | +| `getAttribute($name, $default = null)` | Retrieve a single derived request attribute | | +| `withAttribute($name, $value)` | Returns a new request instance with the specified derived request attribute | | +| `withoutAttribute($name)` | Returns a new request instance that without the specified derived request attribute | | + +## `Psr\Http\Message\ResponseInterface` Methods: + +Same methods as `Psr\Http\Message\MessageInterface` + the following methods: + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getStatusCode()` | Gets the response status code. | | +| `withStatus($code, $reasonPhrase = '')` | Returns a new response instance with the specified status code and, optionally, reason phrase. | | +| `getReasonPhrase()` | Gets the response reason phrase associated with the status code. | | + +## `Psr\Http\Message\StreamInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `__toString()` | Reads all data from the stream into a string, from the beginning to end. | | +| `close()` | Closes the stream and any underlying resources. | | +| `detach()` | Separates any underlying resources from the stream. | | +| `getSize()` | Get the size of the stream if known. | | +| `eof()` | Returns true if the stream is at the end of the stream.| | +| `isSeekable()` | Returns whether or not the stream is seekable. | | +| `seek($offset, $whence = SEEK_SET)` | Seek to a position in the stream. | | +| `rewind()` | Seek to the beginning of the stream. | | +| `isWritable()` | Returns whether or not the stream is writable. | | +| `write($string)` | Write data to the stream. | | +| `isReadable()` | Returns whether or not the stream is readable. | | +| `read($length)` | Read data from the stream. | | +| `getContents()` | Returns the remaining contents in a string | | +| `getMetadata($key = null)()` | Get stream metadata as an associative array or retrieve a specific key. | | + +## `Psr\Http\Message\UriInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getScheme()` | Retrieve the scheme component of the URI. | | +| `getAuthority()` | Retrieve the authority component of the URI. | | +| `getUserInfo()` | Retrieve the user information component of the URI. | | +| `getHost()` | Retrieve the host component of the URI. | | +| `getPort()` | Retrieve the port component of the URI. | | +| `getPath()` | Retrieve the path component of the URI. | | +| `getQuery()` | Retrieve the query string of the URI. | | +| `getFragment()` | Retrieve the fragment component of the URI. | | +| `withScheme($scheme)` | Return an instance with the specified scheme. | | +| `withUserInfo($user, $password = null)` | Return an instance with the specified user information. | | +| `withHost($host)` | Return an instance with the specified host. | | +| `withPort($port)` | Return an instance with the specified port. | | +| `withPath($path)` | Return an instance with the specified path. | | +| `withQuery($query)` | Return an instance with the specified query string. | | +| `withFragment($fragment)` | Return an instance with the specified URI fragment. | | +| `__toString()` | Return the string representation as a URI reference. | | + +## `Psr\Http\Message\UploadedFileInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getStream()` | Retrieve a stream representing the uploaded file. | | +| `moveTo($targetPath)` | Move the uploaded file to a new location. | | +| `getSize()` | Retrieve the file size. | | +| `getError()` | Retrieve the error associated with the uploaded file. | | +| `getClientFilename()` | Retrieve the filename sent by the client. | | +| `getClientMediaType()` | Retrieve the media type sent by the client. | | + +> `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + diff --git a/php/libraries/composer/vendor/psr/http-message/docs/PSR7-Usage.md b/php/libraries/composer/vendor/psr/http-message/docs/PSR7-Usage.md new file mode 100644 index 0000000..b6d048a --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/docs/PSR7-Usage.md @@ -0,0 +1,159 @@ +### PSR-7 Usage + +All PSR-7 applications comply with these interfaces +They were created to establish a standard between middleware implementations. + +> `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + + +The following examples will illustrate how basic operations are done in PSR-7. + +##### Examples + + +For this examples to work (at least) a PSR-7 implementation package is required. (eg: zendframework/zend-diactoros, guzzlehttp/psr7, slim/slim, etc) +All PSR-7 implementations should have the same behaviour. + +The following will be assumed: +`$request` is an object of `Psr\Http\Message\RequestInterface` and + +`$response` is an object implementing `Psr\Http\Message\RequestInterface` + + +### Working with HTTP Headers + +#### Adding headers to response: + +```php +$response->withHeader('My-Custom-Header', 'My Custom Message'); +``` + +#### Appending values to headers + +```php +$response->withAddedHeader('My-Custom-Header', 'The second message'); +``` + +#### Checking if header exists: + +```php +$request->hasHeader('My-Custom-Header'); // will return false +$response->hasHeader('My-Custom-Header'); // will return true +``` + +> Note: My-Custom-Header was only added in the Response + +#### Getting comma-separated values from a header (also applies to request) + +```php +// getting value from request headers +$request->getHeaderLine('Content-Type'); // will return: "text/html; charset=UTF-8" +// getting value from response headers +$response->getHeaderLine('My-Custom-Header'); // will return: "My Custom Message; The second message" +``` + +#### Getting array of value from a header (also applies to request) +```php +// getting value from request headers +$request->getHeader('Content-Type'); // will return: ["text/html", "charset=UTF-8"] +// getting value from response headers +$response->getHeader('My-Custom-Header'); // will return: ["My Custom Message", "The second message"] +``` + +#### Removing headers from HTTP Messages +```php +// removing a header from Request, removing deprecated "Content-MD5" header +$request->withoutHeader('Content-MD5'); + +// removing a header from Response +// effect: the browser won't know the size of the stream +// the browser will download the stream till it ends +$response->withoutHeader('Content-Length'); +``` + +### Working with HTTP Message Body + +When working with the PSR-7 there are two methods of implementation: +#### 1. Getting the body separately + +> This method makes the body handling easier to understand and is useful when repeatedly calling body methods. (You only call `getBody()` once). Using this method mistakes like `$response->write()` are also prevented. + +```php +$body = $response->getBody(); +// operations on body, eg. read, write, seek +// ... +// replacing the old body +$response->withBody($body); +// this last statement is optional as we working with objects +// in this case the "new" body is same with the "old" one +// the $body variable has the same value as the one in $request, only the reference is passed +``` + +#### 2. Working directly on response + +> This method is useful when only performing few operations as the `$request->getBody()` statement fragment is required + +```php +$response->getBody()->write('hello'); +``` + +### Getting the body contents + +The following snippet gets the contents of a stream contents. +> Note: Streams must be rewinded, if content was written into streams, it will be ignored when calling `getContents()` because the stream pointer is set to the last character, which is `\0` - meaning end of stream. +```php +$body = $response->getBody(); +$body->rewind(); // or $body->seek(0); +$bodyText = $body->getContents(); +``` +> Note: If `$body->seek(1)` is called before `$body->getContents()`, the first character will be ommited as the starting pointer is set to `1`, not `0`. This is why using `$body->rewind()` is recommended. + +### Append to body + +```php +$response->getBody()->write('Hello'); // writing directly +$body = $request->getBody(); // which is a `StreamInterface` +$body->write('xxxxx'); +``` + +### Prepend to body +Prepending is different when it comes to streams. The content must be copied before writing the content to be prepended. +The following example will explain the behaviour of streams. + +```php +// assuming our response is initially empty +$body = $repsonse->getBody(); +// writing the string "abcd" +$body->write('abcd'); + +// seeking to start of stream +$body->seek(0); +// writing 'ef' +$body->write('ef'); // at this point the stream contains "efcd" +``` + +#### Prepending by rewriting separately + +```php +// assuming our response body stream only contains: "abcd" +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // abcd +// seeking the stream to beginning +$body->rewind(); +$body->write('ef'); // stream contains "efcd" +$body->write($contents); // stream contains "efabcd" +``` + +> Note: `getContents()` seeks the stream while reading it, therefore if the second `rewind()` method call was not present the stream would have resulted in `abcdefabcd` because the `write()` method appends to stream if not preceeded by `rewind()` or `seek(0)`. + +#### Prepending by using contents as a string +```php +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // efabcd +$contents = 'ef'.$contents; +$body->rewind(); +$body->write($contents); +``` diff --git a/php/libraries/composer/vendor/psr/http-message/src/MessageInterface.php b/php/libraries/composer/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..a83c985 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +<?php + +namespace Psr\Http\Message; + +/** + * HTTP messages consist of requests from a client to a server and responses + * from a server to a client. This interface defines the methods common to + * each. + * + * Messages are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + * + * @link http://www.ietf.org/rfc/rfc7230.txt + * @link http://www.ietf.org/rfc/rfc7231.txt + */ +interface MessageInterface +{ + /** + * Retrieves the HTTP protocol version as a string. + * + * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). + * + * @return string HTTP protocol version. + */ + public function getProtocolVersion(): string; + + /** + * Return an instance with the specified HTTP protocol version. + * + * The version string MUST contain only the HTTP version number (e.g., + * "1.1", "1.0"). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new protocol version. + * + * @param string $version HTTP protocol version + * @return static + */ + public function withProtocolVersion(string $version): MessageInterface; + + /** + * Retrieves all message header values. + * + * The keys represent the header name as it will be sent over the wire, and + * each value is an array of strings associated with the header. + * + * // Represent the headers as a string + * foreach ($message->getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(): array; + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader(string $name): bool; + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader(string $name): array; + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine(string $name): string; + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader(string $name, $value): MessageInterface; + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader(string $name, $value): MessageInterface; + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader(string $name): MessageInterface; + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(): StreamInterface; + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body): MessageInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-message/src/RequestInterface.php b/php/libraries/composer/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..33f85e5 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,130 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Representation of an outgoing, client-side request. + * + * Per the HTTP specification, this interface includes properties for + * each of the following: + * + * - Protocol version + * - HTTP method + * - URI + * - Headers + * - Message body + * + * During construction, implementations MUST attempt to set the Host header from + * a provided URI if no Host header is provided. + * + * Requests are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + */ +interface RequestInterface extends MessageInterface +{ + /** + * Retrieves the message's request target. + * + * Retrieves the message's request-target either as it will appear (for + * clients), as it appeared at request (for servers), or as it was + * specified for the instance (see withRequestTarget()). + * + * In most cases, this will be the origin-form of the composed URI, + * unless a value was provided to the concrete implementation (see + * withRequestTarget() below). + * + * If no URI is available, and no request-target has been specifically + * provided, this method MUST return the string "/". + * + * @return string + */ + public function getRequestTarget(): string; + + /** + * Return an instance with the specific request-target. + * + * If the request needs a non-origin-form request-target — e.g., for + * specifying an absolute-form, authority-form, or asterisk-form — + * this method may be used to create an instance with the specified + * request-target, verbatim. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * changed request target. + * + * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various + * request-target forms allowed in request messages) + * @param string $requestTarget + * @return static + */ + public function withRequestTarget(string $requestTarget): RequestInterface; + + + /** + * Retrieves the HTTP method of the request. + * + * @return string Returns the request method. + */ + public function getMethod(): string; + + /** + * Return an instance with the provided HTTP method. + * + * While HTTP method names are typically all uppercase characters, HTTP + * method names are case-sensitive and thus implementations SHOULD NOT + * modify the given string. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * changed request method. + * + * @param string $method Case-sensitive method. + * @return static + * @throws \InvalidArgumentException for invalid HTTP methods. + */ + public function withMethod(string $method): RequestInterface; + + /** + * Retrieves the URI instance. + * + * This method MUST return a UriInterface instance. + * + * @link http://tools.ietf.org/html/rfc3986#section-4.3 + * @return UriInterface Returns a UriInterface instance + * representing the URI of the request. + */ + public function getUri(): UriInterface; + + /** + * Returns an instance with the provided URI. + * + * This method MUST update the Host header of the returned request by + * default if the URI contains a host component. If the URI does not + * contain a host component, any pre-existing Host header MUST be carried + * over to the returned request. + * + * You can opt-in to preserving the original state of the Host header by + * setting `$preserveHost` to `true`. When `$preserveHost` is set to + * `true`, this method interacts with the Host header in the following ways: + * + * - If the Host header is missing or empty, and the new URI contains + * a host component, this method MUST update the Host header in the returned + * request. + * - If the Host header is missing or empty, and the new URI does not contain a + * host component, this method MUST NOT update the Host header in the returned + * request. + * - If a Host header is present and non-empty, this method MUST NOT update + * the Host header in the returned request. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new UriInterface instance. + * + * @link http://tools.ietf.org/html/rfc3986#section-4.3 + * @param UriInterface $uri New request URI to use. + * @param bool $preserveHost Preserve the original state of the Host header. + * @return static + */ + public function withUri(UriInterface $uri, bool $preserveHost = false): RequestInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-message/src/ResponseInterface.php b/php/libraries/composer/vendor/psr/http-message/src/ResponseInterface.php new file mode 100644 index 0000000..e9299a9 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/ResponseInterface.php @@ -0,0 +1,68 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Representation of an outgoing, server-side response. + * + * Per the HTTP specification, this interface includes properties for + * each of the following: + * + * - Protocol version + * - Status code and reason phrase + * - Headers + * - Message body + * + * Responses are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + */ +interface ResponseInterface extends MessageInterface +{ + /** + * Gets the response status code. + * + * The status code is a 3-digit integer result code of the server's attempt + * to understand and satisfy the request. + * + * @return int Status code. + */ + public function getStatusCode(): int; + + /** + * Return an instance with the specified status code and, optionally, reason phrase. + * + * If no reason phrase is specified, implementations MAY choose to default + * to the RFC 7231 or IANA recommended reason phrase for the response's + * status code. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated status and reason phrase. + * + * @link http://tools.ietf.org/html/rfc7231#section-6 + * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + * @param int $code The 3-digit integer result code to set. + * @param string $reasonPhrase The reason phrase to use with the + * provided status code; if none is provided, implementations MAY + * use the defaults as suggested in the HTTP specification. + * @return static + * @throws \InvalidArgumentException For invalid status code arguments. + */ + public function withStatus(int $code, string $reasonPhrase = ''): ResponseInterface; + + /** + * Gets the response reason phrase associated with the status code. + * + * Because a reason phrase is not a required element in a response + * status line, the reason phrase value MAY be null. Implementations MAY + * choose to return the default RFC 7231 recommended reason phrase (or those + * listed in the IANA HTTP Status Code Registry) for the response's + * status code. + * + * @link http://tools.ietf.org/html/rfc7231#section-6 + * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + * @return string Reason phrase; must return an empty string if none present. + */ + public function getReasonPhrase(): string; +} diff --git a/php/libraries/composer/vendor/psr/http-message/src/ServerRequestInterface.php b/php/libraries/composer/vendor/psr/http-message/src/ServerRequestInterface.php new file mode 100644 index 0000000..8625d0e --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/ServerRequestInterface.php @@ -0,0 +1,261 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Representation of an incoming, server-side HTTP request. + * + * Per the HTTP specification, this interface includes properties for + * each of the following: + * + * - Protocol version + * - HTTP method + * - URI + * - Headers + * - Message body + * + * Additionally, it encapsulates all data as it has arrived to the + * application from the CGI and/or PHP environment, including: + * + * - The values represented in $_SERVER. + * - Any cookies provided (generally via $_COOKIE) + * - Query string arguments (generally via $_GET, or as parsed via parse_str()) + * - Upload files, if any (as represented by $_FILES) + * - Deserialized body parameters (generally from $_POST) + * + * $_SERVER values MUST be treated as immutable, as they represent application + * state at the time of request; as such, no methods are provided to allow + * modification of those values. The other values provide such methods, as they + * can be restored from $_SERVER or the request body, and may need treatment + * during the application (e.g., body parameters may be deserialized based on + * content type). + * + * Additionally, this interface recognizes the utility of introspecting a + * request to derive and match additional parameters (e.g., via URI path + * matching, decrypting cookie values, deserializing non-form-encoded body + * content, matching authorization headers to users, etc). These parameters + * are stored in an "attributes" property. + * + * Requests are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + */ +interface ServerRequestInterface extends RequestInterface +{ + /** + * Retrieve server parameters. + * + * Retrieves data related to the incoming request environment, + * typically derived from PHP's $_SERVER superglobal. The data IS NOT + * REQUIRED to originate from $_SERVER. + * + * @return array + */ + public function getServerParams(): array; + + /** + * Retrieve cookies. + * + * Retrieves cookies sent by the client to the server. + * + * The data MUST be compatible with the structure of the $_COOKIE + * superglobal. + * + * @return array + */ + public function getCookieParams(): array; + + /** + * Return an instance with the specified cookies. + * + * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST + * be compatible with the structure of $_COOKIE. Typically, this data will + * be injected at instantiation. + * + * This method MUST NOT update the related Cookie header of the request + * instance, nor related values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated cookie values. + * + * @param array $cookies Array of key/value pairs representing cookies. + * @return static + */ + public function withCookieParams(array $cookies): ServerRequestInterface; + + /** + * Retrieve query string arguments. + * + * Retrieves the deserialized query string arguments, if any. + * + * Note: the query params might not be in sync with the URI or server + * params. If you need to ensure you are only getting the original + * values, you may need to parse the query string from `getUri()->getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(): array; + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query): ServerRequestInterface; + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(): array; + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface; + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data): ServerRequestInterface; + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(): array; + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute(string $name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute(string $name, $value): ServerRequestInterface; + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute(string $name): ServerRequestInterface; +} diff --git a/php/libraries/composer/vendor/psr/http-message/src/StreamInterface.php b/php/libraries/composer/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..a62aabb --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Describes a data stream. + * + * Typically, an instance will wrap a PHP stream; this interface provides + * a wrapper around the most common operations, including serialization of + * the entire stream to a string. + */ +interface StreamInterface +{ + /** + * Reads all data from the stream into a string, from the beginning to end. + * + * This method MUST attempt to seek to the beginning of the stream before + * reading data and read the stream until the end is reached. + * + * Warning: This could attempt to load a large amount of data into memory. + * + * This method MUST NOT raise an exception in order to conform with PHP's + * string casting operations. + * + * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring + * @return string + */ + public function __toString(): string; + + /** + * Closes the stream and any underlying resources. + * + * @return void + */ + public function close(): void; + + /** + * Separates any underlying resources from the stream. + * + * After the stream has been detached, the stream is in an unusable state. + * + * @return resource|null Underlying PHP stream, if any + */ + public function detach(); + + /** + * Get the size of the stream if known. + * + * @return int|null Returns the size in bytes if known, or null if unknown. + */ + public function getSize(): ?int; + + /** + * Returns the current position of the file read/write pointer + * + * @return int Position of the file pointer + * @throws \RuntimeException on error. + */ + public function tell(): int; + + /** + * Returns true if the stream is at the end of the stream. + * + * @return bool + */ + public function eof(): bool; + + /** + * Returns whether or not the stream is seekable. + * + * @return bool + */ + public function isSeekable(): bool; + + /** + * Seek to a position in the stream. + * + * @link http://www.php.net/manual/en/function.fseek.php + * @param int $offset Stream offset + * @param int $whence Specifies how the cursor position will be calculated + * based on the seek offset. Valid values are identical to the built-in + * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to + * offset bytes SEEK_CUR: Set position to current location plus offset + * SEEK_END: Set position to end-of-stream plus offset. + * @throws \RuntimeException on failure. + */ + public function seek(int $offset, int $whence = SEEK_SET): void; + + /** + * Seek to the beginning of the stream. + * + * If the stream is not seekable, this method will raise an exception; + * otherwise, it will perform a seek(0). + * + * @see seek() + * @link http://www.php.net/manual/en/function.fseek.php + * @throws \RuntimeException on failure. + */ + public function rewind(): void; + + /** + * Returns whether or not the stream is writable. + * + * @return bool + */ + public function isWritable(): bool; + + /** + * Write data to the stream. + * + * @param string $string The string that is to be written. + * @return int Returns the number of bytes written to the stream. + * @throws \RuntimeException on failure. + */ + public function write(string $string): int; + + /** + * Returns whether or not the stream is readable. + * + * @return bool + */ + public function isReadable(): bool; + + /** + * Read data from the stream. + * + * @param int $length Read up to $length bytes from the object and return + * them. Fewer than $length bytes may be returned if underlying stream + * call returns fewer bytes. + * @return string Returns the data read from the stream, or an empty string + * if no bytes are available. + * @throws \RuntimeException if an error occurs. + */ + public function read(int $length): string; + + /** + * Returns the remaining contents in a string + * + * @return string + * @throws \RuntimeException if unable to read or an error occurs while + * reading. + */ + public function getContents(): string; + + /** + * Get stream metadata as an associative array or retrieve a specific key. + * + * The keys returned are identical to the keys returned from PHP's + * stream_get_meta_data() function. + * + * @link http://php.net/manual/en/function.stream-get-meta-data.php + * @param string|null $key Specific metadata to retrieve. + * @return array|mixed|null Returns an associative array if no key is + * provided. Returns a specific key value if a key is provided and the + * value is found, or null if the key is not found. + */ + public function getMetadata(?string $key = null); +} diff --git a/php/libraries/composer/vendor/psr/http-message/src/UploadedFileInterface.php b/php/libraries/composer/vendor/psr/http-message/src/UploadedFileInterface.php new file mode 100644 index 0000000..dd19d65 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/UploadedFileInterface.php @@ -0,0 +1,123 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Value object representing a file uploaded through an HTTP request. + * + * Instances of this interface are considered immutable; all methods that + * might change state MUST be implemented such that they retain the internal + * state of the current instance and return an instance that contains the + * changed state. + */ +interface UploadedFileInterface +{ + /** + * Retrieve a stream representing the uploaded file. + * + * This method MUST return a StreamInterface instance, representing the + * uploaded file. The purpose of this method is to allow utilizing native PHP + * stream functionality to manipulate the file upload, such as + * stream_copy_to_stream() (though the result will need to be decorated in a + * native PHP stream wrapper to work with such functions). + * + * If the moveTo() method has been called previously, this method MUST raise + * an exception. + * + * @return StreamInterface Stream representation of the uploaded file. + * @throws \RuntimeException in cases when no stream is available or can be + * created. + */ + public function getStream(): StreamInterface; + + /** + * Move the uploaded file to a new location. + * + * Use this method as an alternative to move_uploaded_file(). This method is + * guaranteed to work in both SAPI and non-SAPI environments. + * Implementations must determine which environment they are in, and use the + * appropriate method (move_uploaded_file(), rename(), or a stream + * operation) to perform the operation. + * + * $targetPath may be an absolute path, or a relative path. If it is a + * relative path, resolution should be the same as used by PHP's rename() + * function. + * + * The original file or stream MUST be removed on completion. + * + * If this method is called more than once, any subsequent calls MUST raise + * an exception. + * + * When used in an SAPI environment where $_FILES is populated, when writing + * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be + * used to ensure permissions and upload status are verified correctly. + * + * If you wish to move to a stream, use getStream(), as SAPI operations + * cannot guarantee writing to stream destinations. + * + * @see http://php.net/is_uploaded_file + * @see http://php.net/move_uploaded_file + * @param string $targetPath Path to which to move the uploaded file. + * @throws \InvalidArgumentException if the $targetPath specified is invalid. + * @throws \RuntimeException on any error during the move operation, or on + * the second or subsequent call to the method. + */ + public function moveTo(string $targetPath): void; + + /** + * Retrieve the file size. + * + * Implementations SHOULD return the value stored in the "size" key of + * the file in the $_FILES array if available, as PHP calculates this based + * on the actual size transmitted. + * + * @return int|null The file size in bytes or null if unknown. + */ + public function getSize(): ?int; + + /** + * Retrieve the error associated with the uploaded file. + * + * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants. + * + * If the file was uploaded successfully, this method MUST return + * UPLOAD_ERR_OK. + * + * Implementations SHOULD return the value stored in the "error" key of + * the file in the $_FILES array. + * + * @see http://php.net/manual/en/features.file-upload.errors.php + * @return int One of PHP's UPLOAD_ERR_XXX constants. + */ + public function getError(): int; + + /** + * Retrieve the filename sent by the client. + * + * Do not trust the value returned by this method. A client could send + * a malicious filename with the intention to corrupt or hack your + * application. + * + * Implementations SHOULD return the value stored in the "name" key of + * the file in the $_FILES array. + * + * @return string|null The filename sent by the client or null if none + * was provided. + */ + public function getClientFilename(): ?string; + + /** + * Retrieve the media type sent by the client. + * + * Do not trust the value returned by this method. A client could send + * a malicious media type with the intention to corrupt or hack your + * application. + * + * Implementations SHOULD return the value stored in the "type" key of + * the file in the $_FILES array. + * + * @return string|null The media type sent by the client or null if none + * was provided. + */ + public function getClientMediaType(): ?string; +} diff --git a/php/libraries/composer/vendor/psr/http-message/src/UriInterface.php b/php/libraries/composer/vendor/psr/http-message/src/UriInterface.php new file mode 100644 index 0000000..15e2cf2 --- /dev/null +++ b/php/libraries/composer/vendor/psr/http-message/src/UriInterface.php @@ -0,0 +1,324 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Value object representing a URI. + * + * This interface is meant to represent URIs according to RFC 3986 and to + * provide methods for most common operations. Additional functionality for + * working with URIs can be provided on top of the interface or externally. + * Its primary use is for HTTP requests, but may also be used in other + * contexts. + * + * Instances of this interface are considered immutable; all methods that + * might change state MUST be implemented such that they retain the internal + * state of the current instance and return an instance that contains the + * changed state. + * + * Typically the Host header will be also be present in the request message. + * For server-side requests, the scheme will typically be discoverable in the + * server parameters. + * + * @link http://tools.ietf.org/html/rfc3986 (the URI specification) + */ +interface UriInterface +{ + /** + * Retrieve the scheme component of the URI. + * + * If no scheme is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.1. + * + * The trailing ":" character is not part of the scheme and MUST NOT be + * added. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.1 + * @return string The URI scheme. + */ + public function getScheme(): string; + + /** + * Retrieve the authority component of the URI. + * + * If no authority information is present, this method MUST return an empty + * string. + * + * The authority syntax of the URI is: + * + * <pre> + * [user-info@]host[:port] + * </pre> + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(): string; + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(): string; + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(): string; + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(): ?int; + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(): string; + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(): string; + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(): string; + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme(string $scheme): UriInterface; + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo(string $user, ?string $password = null): UriInterface; + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost(string $host): UriInterface; + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort(?int $port): UriInterface; + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath(string $path): UriInterface; + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery(string $query): UriInterface; + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment(string $fragment): UriInterface; + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(): string; +} diff --git a/php/libraries/composer/vendor/psr/log/LICENSE b/php/libraries/composer/vendor/psr/log/LICENSE new file mode 100644 index 0000000..474c952 --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 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/php/libraries/composer/vendor/psr/log/README.md b/php/libraries/composer/vendor/psr/log/README.md new file mode 100644 index 0000000..a9f20c4 --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/README.md @@ -0,0 +1,58 @@ +PSR Log +======= + +This repository holds all interfaces/classes/traits related to +[PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). + +Note that this is not a logger of its own. It is merely an interface that +describes a logger. See the specification for more details. + +Installation +------------ + +```bash +composer require psr/log +``` + +Usage +----- + +If you need a logger, you can use the interface like this: + +```php +<?php + +use Psr\Log\LoggerInterface; + +class Foo +{ + private $logger; + + public function __construct(LoggerInterface $logger = null) + { + $this->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/php/libraries/composer/vendor/psr/log/composer.json b/php/libraries/composer/vendor/psr/log/composer.json new file mode 100644 index 0000000..f3f0667 --- /dev/null +++ b/php/libraries/composer/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": "2.0.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/psr/log/src/AbstractLogger.php b/php/libraries/composer/vendor/psr/log/src/AbstractLogger.php new file mode 100644 index 0000000..d60a091 --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/AbstractLogger.php @@ -0,0 +1,15 @@ +<?php + +namespace Psr\Log; + +/** + * This is a simple Logger implementation that other Loggers can inherit from. + * + * It simply delegates all log-level-specific methods to the `log` method to + * reduce boilerplate code that a simple Logger that does the same thing with + * messages regardless of the error level has to implement. + */ +abstract class AbstractLogger implements LoggerInterface +{ + use LoggerTrait; +} diff --git a/php/libraries/composer/vendor/psr/log/src/InvalidArgumentException.php b/php/libraries/composer/vendor/psr/log/src/InvalidArgumentException.php new file mode 100644 index 0000000..67f852d --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/InvalidArgumentException.php @@ -0,0 +1,7 @@ +<?php + +namespace Psr\Log; + +class InvalidArgumentException extends \InvalidArgumentException +{ +} diff --git a/php/libraries/composer/vendor/psr/log/src/LogLevel.php b/php/libraries/composer/vendor/psr/log/src/LogLevel.php new file mode 100644 index 0000000..9cebcac --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/LogLevel.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Log; + +/** + * Describes log levels. + */ +class LogLevel +{ + const EMERGENCY = 'emergency'; + const ALERT = 'alert'; + const CRITICAL = 'critical'; + const ERROR = 'error'; + const WARNING = 'warning'; + const NOTICE = 'notice'; + const INFO = 'info'; + const DEBUG = 'debug'; +} diff --git a/php/libraries/composer/vendor/psr/log/src/LoggerAwareInterface.php b/php/libraries/composer/vendor/psr/log/src/LoggerAwareInterface.php new file mode 100644 index 0000000..4d64f47 --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/LoggerAwareInterface.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Log; + +/** + * Describes a logger-aware instance. + */ +interface LoggerAwareInterface +{ + /** + * Sets a logger instance on the object. + * + * @param LoggerInterface $logger + * + * @return void + */ + public function setLogger(LoggerInterface $logger); +} diff --git a/php/libraries/composer/vendor/psr/log/src/LoggerAwareTrait.php b/php/libraries/composer/vendor/psr/log/src/LoggerAwareTrait.php new file mode 100644 index 0000000..5f1553a --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/LoggerAwareTrait.php @@ -0,0 +1,26 @@ +<?php + +namespace Psr\Log; + +/** + * Basic Implementation of LoggerAwareInterface. + */ +trait LoggerAwareTrait +{ + /** + * The logger instance. + * + * @var LoggerInterface|null + */ + protected ?LoggerInterface $logger = null; + + /** + * Sets a logger. + * + * @param LoggerInterface $logger + */ + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + } +} diff --git a/php/libraries/composer/vendor/psr/log/src/LoggerInterface.php b/php/libraries/composer/vendor/psr/log/src/LoggerInterface.php new file mode 100644 index 0000000..b4d062b --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/LoggerInterface.php @@ -0,0 +1,125 @@ +<?php + +namespace Psr\Log; + +/** + * Describes a logger instance. + * + * The message MUST be a string or object implementing __toString(). + * + * The message MAY contain placeholders in the form: {foo} where foo + * will be replaced by the context data in key "foo". + * + * The context array can contain arbitrary data. The only assumption that + * can be made by implementors is that if an Exception instance is given + * to produce a stack trace, it MUST be in a key named "exception". + * + * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md + * for the full interface specification. + */ +interface LoggerInterface +{ + /** + * System is unusable. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function emergency(string|\Stringable $message, array $context = []); + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function alert(string|\Stringable $message, array $context = []); + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function critical(string|\Stringable $message, array $context = []); + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function error(string|\Stringable $message, array $context = []); + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function warning(string|\Stringable $message, array $context = []); + + /** + * Normal but significant events. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function notice(string|\Stringable $message, array $context = []); + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function info(string|\Stringable $message, array $context = []); + + /** + * Detailed debug information. + * + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + */ + public function debug(string|\Stringable $message, array $context = []); + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param mixed[] $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []); +} diff --git a/php/libraries/composer/vendor/psr/log/src/LoggerTrait.php b/php/libraries/composer/vendor/psr/log/src/LoggerTrait.php new file mode 100644 index 0000000..920bda7 --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/LoggerTrait.php @@ -0,0 +1,142 @@ +<?php + +namespace Psr\Log; + +/** + * This is a simple Logger trait that classes unable to extend AbstractLogger + * (because they extend another class, etc) can include. + * + * It simply delegates all log-level-specific methods to the `log` method to + * reduce boilerplate code that a simple Logger that does the same thing with + * messages regardless of the error level has to implement. + */ +trait LoggerTrait +{ + /** + * System is unusable. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function emergency(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function alert(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function critical(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function error(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function warning(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function notice(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function info(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function debug(string|\Stringable $message, array $context = []) + { + $this->log(LogLevel::DEBUG, $message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, string|\Stringable $message, array $context = []); +} diff --git a/php/libraries/composer/vendor/psr/log/src/NullLogger.php b/php/libraries/composer/vendor/psr/log/src/NullLogger.php new file mode 100644 index 0000000..5607705 --- /dev/null +++ b/php/libraries/composer/vendor/psr/log/src/NullLogger.php @@ -0,0 +1,30 @@ +<?php + +namespace Psr\Log; + +/** + * This Logger can be used to avoid conditional log calls. + * + * Logging should always be optional, and if no logger is provided to your + * library creating a NullLogger instance to have something to throw logs at + * is a good way to avoid littering your code with `if ($this->logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []) + { + // noop + } +} diff --git a/php/libraries/composer/vendor/psr/simple-cache/.editorconfig b/php/libraries/composer/vendor/psr/simple-cache/.editorconfig new file mode 100644 index 0000000..48542cb --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/.editorconfig @@ -0,0 +1,12 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/php/libraries/composer/vendor/psr/simple-cache/LICENSE.md b/php/libraries/composer/vendor/psr/simple-cache/LICENSE.md new file mode 100644 index 0000000..e49a7c8 --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +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/php/libraries/composer/vendor/psr/simple-cache/README.md b/php/libraries/composer/vendor/psr/simple-cache/README.md new file mode 100644 index 0000000..43641d1 --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/README.md @@ -0,0 +1,8 @@ +PHP FIG Simple Cache PSR +======================== + +This repository holds all interfaces related to PSR-16. + +Note that this is not a cache implementation of its own. It is merely an interface that describes a cache implementation. See [the specification](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md) for more details. + +You can find implementations of the specification by looking for packages providing the [psr/simple-cache-implementation](https://packagist.org/providers/psr/simple-cache-implementation) virtual package. diff --git a/php/libraries/composer/vendor/psr/simple-cache/composer.json b/php/libraries/composer/vendor/psr/simple-cache/composer.json new file mode 100644 index 0000000..2978fa5 --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/composer.json @@ -0,0 +1,25 @@ +{ + "name": "psr/simple-cache", + "description": "Common interfaces for simple caching", + "keywords": ["psr", "psr-16", "cache", "simple-cache", "caching"], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\SimpleCache\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/psr/simple-cache/src/CacheException.php b/php/libraries/composer/vendor/psr/simple-cache/src/CacheException.php new file mode 100644 index 0000000..eba5381 --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/src/CacheException.php @@ -0,0 +1,10 @@ +<?php + +namespace Psr\SimpleCache; + +/** + * Interface used for all types of exceptions thrown by the implementing library. + */ +interface CacheException +{ +} diff --git a/php/libraries/composer/vendor/psr/simple-cache/src/CacheInterface.php b/php/libraries/composer/vendor/psr/simple-cache/src/CacheInterface.php new file mode 100644 index 0000000..99e8d95 --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/src/CacheInterface.php @@ -0,0 +1,114 @@ +<?php + +namespace Psr\SimpleCache; + +interface CacheInterface +{ + /** + * Fetches a value from the cache. + * + * @param string $key The unique key of this item in the cache. + * @param mixed $default Default value to return if the key does not exist. + * + * @return mixed The value of the item from the cache, or $default in case of cache miss. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + */ + public function get($key, $default = null); + + /** + * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. + * + * @param string $key The key of the item to store. + * @param mixed $value The value of the item to store, must be serializable. + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * + * @return bool True on success and false on failure. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + */ + public function set($key, $value, $ttl = null); + + /** + * Delete an item from the cache by its unique key. + * + * @param string $key The unique cache key of the item to delete. + * + * @return bool True if the item was successfully removed. False if there was an error. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + */ + public function delete($key); + + /** + * Wipes clean the entire cache's keys. + * + * @return bool True on success and false on failure. + */ + public function clear(); + + /** + * Obtains multiple cache items by their unique keys. + * + * @param iterable $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 iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + */ + public function getMultiple($keys, $default = null); + + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * @param iterable $values A list of key => value pairs for a multiple-set operation. + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * + * @return bool True on success and false on failure. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $values is neither an array nor a Traversable, + * or if any of the $values are not a legal value. + */ + public function setMultiple($values, $ttl = null); + + /** + * Deletes multiple cache items in a single operation. + * + * @param iterable $keys A list of string-based keys to be deleted. + * + * @return bool True if the items were successfully removed. False if there was an error. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + */ + public function deleteMultiple($keys); + + /** + * Determines whether an item is present in the cache. + * + * 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 bool + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + */ + public function has($key); +} diff --git a/php/libraries/composer/vendor/psr/simple-cache/src/InvalidArgumentException.php b/php/libraries/composer/vendor/psr/simple-cache/src/InvalidArgumentException.php new file mode 100644 index 0000000..6a9524a --- /dev/null +++ b/php/libraries/composer/vendor/psr/simple-cache/src/InvalidArgumentException.php @@ -0,0 +1,13 @@ +<?php + +namespace Psr\SimpleCache; + +/** + * Exception interface for invalid cache arguments. + * + * When an invalid argument is passed it must throw an exception which implements + * this interface + */ +interface InvalidArgumentException extends CacheException +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/LICENSE b/php/libraries/composer/vendor/psy/psysh/LICENSE new file mode 100644 index 0000000..007634a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2023 Justin Hileman + +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/php/libraries/composer/vendor/psy/psysh/README.md b/php/libraries/composer/vendor/psy/psysh/README.md new file mode 100644 index 0000000..fc731d1 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/README.md @@ -0,0 +1,36 @@ +# PsySH + +PsySH is a runtime developer console, interactive debugger and [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) for PHP. Learn more at [psysh.org](http://psysh.org/) and [in the manual](https://github.com/bobthecow/psysh/wiki/Home). + + +[![Package version](https://img.shields.io/packagist/v/psy/psysh.svg?style=flat-square)](https://packagist.org/packages/psy/psysh) +[![Monthly downloads](http://img.shields.io/packagist/dm/psy/psysh.svg?style=flat-square)](https://packagist.org/packages/psy/psysh) +[![Made out of awesome](https://img.shields.io/badge/made_out_of_awesome-✓-brightgreen.svg?style=flat-square)](http://psysh.org) + +[![Build status](https://img.shields.io/github/actions/workflow/status/bobthecow/psysh/tests.yml?branch=main&style=flat-square)](https://github.com/bobthecow/psysh/actions?query=branch:main) +[![StyleCI](https://styleci.io/repos/4549925/shield)](https://styleci.io/repos/4549925) + + +<a id="downloading-the-manual"></a> + +## [PsySH manual](https://github.com/bobthecow/psysh/wiki/Home) + +### [💾 Installation](https://github.com/bobthecow/psysh/wiki/Installation) + * [📕 PHP manual installation](https://github.com/bobthecow/psysh/wiki/PHP-manual) + * <a class="internal present" href="https://github.com/bobthecow/psysh/wiki/Windows"><img src="https://user-images.githubusercontent.com/53660/40878809-407e8368-664b-11e8-8455-f11602c41dfe.png" width="18"> Windows</a> + +### [🖥 Usage](https://github.com/bobthecow/psysh/wiki/Usage) + * [✨ Magic variables](https://github.com/bobthecow/psysh/wiki/Magic-variables) + * [⏳ Managing history](https://github.com/bobthecow/psysh/wiki/History) + * [💲 System shell integration](https://github.com/bobthecow/psysh/wiki/Shell-integration) + * [🎥 Tutorials & guides](https://github.com/bobthecow/psysh/wiki/Tutorials) + * [🐛 Troubleshooting](https://github.com/bobthecow/psysh/wiki/Troubleshooting) + +### [📢 Commands](https://github.com/bobthecow/psysh/wiki/Commands) + +### [🛠 Configuration](https://github.com/bobthecow/psysh/wiki/Configuration) + * [🎛 Config options](https://github.com/bobthecow/psysh/wiki/Config-options) + * [🎨 Themes](https://github.com/bobthecow/psysh/wiki/Themes) + * [📄 Sample config file](https://github.com/bobthecow/psysh/wiki/Sample-config) + +### [🔌 Integrations](https://github.com/bobthecow/psysh/wiki/Integrations) diff --git a/php/libraries/composer/vendor/psy/psysh/bin/psysh b/php/libraries/composer/vendor/psy/psysh/bin/psysh new file mode 100755 index 0000000..a20a3e1 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/bin/psysh @@ -0,0 +1,148 @@ +#!/usr/bin/env php +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +// Try to find an autoloader for a local psysh version. +// We'll wrap this whole mess in a Closure so it doesn't leak any globals. +call_user_func(function () { + $cwd = null; + + // Find the cwd arg (if present) + $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array(); + foreach ($argv as $i => $arg) { + if ($arg === '--cwd') { + if ($i >= count($argv) - 1) { + fwrite(STDERR, 'Missing --cwd argument.' . PHP_EOL); + exit(1); + } + $cwd = $argv[$i + 1]; + break; + } + + if (preg_match('/^--cwd=/', $arg)) { + $cwd = substr($arg, 6); + break; + } + } + + // Or fall back to the actual cwd + if (!isset($cwd)) { + $cwd = getcwd(); + } + + $cwd = str_replace('\\', '/', $cwd); + + $chunks = explode('/', $cwd); + while (!empty($chunks)) { + $path = implode('/', $chunks); + $prettyPath = $path; + if (isset($_SERVER['HOME']) && $_SERVER['HOME']) { + $prettyPath = preg_replace('/^' . preg_quote($_SERVER['HOME'], '/') . '/', '~', $path); + } + + // Find composer.json + if (is_file($path . '/composer.json')) { + if ($cfg = json_decode(file_get_contents($path . '/composer.json'), true)) { + if (isset($cfg['name']) && $cfg['name'] === 'psy/psysh') { + // We're inside the psysh project. Let's use the local Composer autoload. + if (is_file($path . '/vendor/autoload.php')) { + if (realpath($path) !== realpath(__DIR__ . '/..')) { + fwrite(STDERR, 'Using local PsySH version at ' . $prettyPath . PHP_EOL); + } + + require $path . '/vendor/autoload.php'; + } + + return; + } + } + } + + // Or a composer.lock + if (is_file($path . '/composer.lock')) { + if ($cfg = json_decode(file_get_contents($path . '/composer.lock'), true)) { + foreach (array_merge($cfg['packages'], $cfg['packages-dev']) as $pkg) { + if (isset($pkg['name']) && $pkg['name'] === 'psy/psysh') { + // We're inside a project which requires psysh. We'll use the local Composer autoload. + if (is_file($path . '/vendor/autoload.php')) { + if (realpath($path . '/vendor') !== realpath(__DIR__ . '/../../..')) { + fwrite(STDERR, 'Using local PsySH version at ' . $prettyPath . PHP_EOL); + } + + require $path . '/vendor/autoload.php'; + } + + return; + } + } + } + } + + array_pop($chunks); + } +}); + +// We didn't find an autoloader for a local version, so use the autoloader that +// came with this script. +if (!class_exists('Psy\Shell')) { +/* <<< */ + if (is_file(__DIR__ . '/../vendor/autoload.php')) { + require __DIR__ . '/../vendor/autoload.php'; + } elseif (is_file(__DIR__ . '/../../../autoload.php')) { + require __DIR__ . '/../../../autoload.php'; + } else { + fwrite(STDERR, 'PsySH dependencies not found, be sure to run `composer install`.' . PHP_EOL); + fwrite(STDERR, 'See https://getcomposer.org to get Composer.' . PHP_EOL); + exit(1); + } +/* >>> */ +} + +// If the psysh binary was included directly, assume they just wanted an +// autoloader and bail early. +// +// Keep this PHP 5.3 and 5.4 code around for a while in case someone is using a +// globally installed psysh as a bin launcher for older local versions. +if (version_compare(PHP_VERSION, '5.3.6', '<')) { + $trace = debug_backtrace(); +} elseif (version_compare(PHP_VERSION, '5.4.0', '<')) { + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); +} else { + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); +} + +if (Psy\Shell::isIncluded($trace)) { + unset($trace); + + return; +} + +// Clean up after ourselves. +unset($trace); + +// If the local version is too old, we can't do this +if (!function_exists('Psy\bin')) { + $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array(); + $first = array_shift($argv); + if (preg_match('/php(\.exe)?$/', $first)) { + array_shift($argv); + } + array_unshift($argv, 'vendor/bin/psysh'); + + fwrite(STDERR, 'A local PsySH dependency was found, but it cannot be loaded. Please update to' . PHP_EOL); + fwrite(STDERR, 'the latest version, or run the local copy directly, e.g.:' . PHP_EOL); + fwrite(STDERR, PHP_EOL); + fwrite(STDERR, ' ' . implode(' ', $argv) . PHP_EOL); + exit(1); +} + +// And go! +call_user_func(Psy\bin()); diff --git a/php/libraries/composer/vendor/psy/psysh/composer.json b/php/libraries/composer/vendor/psy/psysh/composer.json new file mode 100644 index 0000000..62295dc --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/composer.json @@ -0,0 +1,60 @@ +{ + "name": "psy/psysh", + "description": "An interactive shell for modern PHP.", + "type": "library", + "keywords": ["console", "interactive", "shell", "repl"], + "homepage": "http://psysh.org", + "license": "MIT", + "authors": [ + { + "name": "Justin Hileman", + "email": "justin@justinhileman.info", + "homepage": "http://justinhileman.com" + } + ], + "require": { + "php": "^8.0 || ^7.4", + "ext-json": "*", + "ext-tokenizer": "*", + "nikic/php-parser": "^5.0 || ^4.0", + "symfony/console": "^7.0 || ^6.0 || ^5.0 || ^4.0 || ^3.4", + "symfony/var-dumper": "^7.0 || ^6.0 || ^5.0 || ^4.0 || ^3.4" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.2" + }, + "suggest": { + "ext-pcntl": "Enabling the PCNTL extension makes PsySH a lot happier :)", + "ext-posix": "If you have PCNTL, you'll want the POSIX extension as well.", + "ext-pdo-sqlite": "The doc command requires SQLite to work." + }, + "autoload": { + "files": ["src/functions.php"], + "psr-4": { + "Psy\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Psy\\Test\\": "test/" + } + }, + "bin": ["bin/psysh"], + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + } + }, + "extra": { + "branch-alias": { + "dev-main": "0.12.x-dev" + }, + "bamarni-bin": { + "bin-links": false, + "forward-command": false + } + }, + "conflict": { + "symfony/console": "4.4.37 || 5.3.14 || 5.3.15 || 5.4.3 || 5.4.4 || 6.0.3 || 6.0.4" + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner.php new file mode 100644 index 0000000..0d9900b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner.php @@ -0,0 +1,389 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +use PhpParser\NodeTraverser; +use PhpParser\Parser; +use PhpParser\PrettyPrinter\Standard as Printer; +use Psy\CodeCleaner\AbstractClassPass; +use Psy\CodeCleaner\AssignThisVariablePass; +use Psy\CodeCleaner\CalledClassPass; +use Psy\CodeCleaner\CallTimePassByReferencePass; +use Psy\CodeCleaner\CodeCleanerPass; +use Psy\CodeCleaner\EmptyArrayDimFetchPass; +use Psy\CodeCleaner\ExitPass; +use Psy\CodeCleaner\FinalClassPass; +use Psy\CodeCleaner\FunctionContextPass; +use Psy\CodeCleaner\FunctionReturnInWriteContextPass; +use Psy\CodeCleaner\ImplicitReturnPass; +use Psy\CodeCleaner\IssetPass; +use Psy\CodeCleaner\LabelContextPass; +use Psy\CodeCleaner\LeavePsyshAlonePass; +use Psy\CodeCleaner\ListPass; +use Psy\CodeCleaner\LoopContextPass; +use Psy\CodeCleaner\MagicConstantsPass; +use Psy\CodeCleaner\NamespacePass; +use Psy\CodeCleaner\PassableByReferencePass; +use Psy\CodeCleaner\RequirePass; +use Psy\CodeCleaner\ReturnTypePass; +use Psy\CodeCleaner\StrictTypesPass; +use Psy\CodeCleaner\UseStatementPass; +use Psy\CodeCleaner\ValidClassNamePass; +use Psy\CodeCleaner\ValidConstructorPass; +use Psy\CodeCleaner\ValidFunctionNamePass; +use Psy\Exception\ParseErrorException; + +/** + * A service to clean up user input, detect parse errors before they happen, + * and generally work around issues with the PHP code evaluation experience. + */ +class CodeCleaner +{ + private $yolo = false; + private $strictTypes = false; + + private $parser; + private $printer; + private $traverser; + private $namespace; + + /** + * CodeCleaner constructor. + * + * @param Parser|null $parser A PhpParser Parser instance. One will be created if not explicitly supplied + * @param Printer|null $printer A PhpParser Printer instance. One will be created if not explicitly supplied + * @param NodeTraverser|null $traverser A PhpParser NodeTraverser instance. One will be created if not explicitly supplied + * @param bool $yolo run without input validation + * @param bool $strictTypes enforce strict types by default + */ + public function __construct(Parser $parser = null, Printer $printer = null, NodeTraverser $traverser = null, bool $yolo = false, bool $strictTypes = false) + { + $this->yolo = $yolo; + $this->strictTypes = $strictTypes; + + $this->parser = $parser ?? (new ParserFactory())->createParser(); + $this->printer = $printer ?: new Printer(); + $this->traverser = $traverser ?: new NodeTraverser(); + + foreach ($this->getDefaultPasses() as $pass) { + $this->traverser->addVisitor($pass); + } + } + + /** + * Check whether this CodeCleaner is in YOLO mode. + */ + public function yolo(): bool + { + return $this->yolo; + } + + /** + * Get default CodeCleaner passes. + * + * @return CodeCleanerPass[] + */ + private function getDefaultPasses(): array + { + if ($this->yolo) { + return $this->getYoloPasses(); + } + + $useStatementPass = new UseStatementPass(); + $namespacePass = new NamespacePass($this); + + // Try to add implicit `use` statements and an implicit namespace, + // based on the file in which the `debug` call was made. + $this->addImplicitDebugContext([$useStatementPass, $namespacePass]); + + return [ + // Validation passes + new AbstractClassPass(), + new AssignThisVariablePass(), + new CalledClassPass(), + new CallTimePassByReferencePass(), + new FinalClassPass(), + new FunctionContextPass(), + new FunctionReturnInWriteContextPass(), + new IssetPass(), + new LabelContextPass(), + new LeavePsyshAlonePass(), + new ListPass(), + new LoopContextPass(), + new PassableByReferencePass(), + new ReturnTypePass(), + new EmptyArrayDimFetchPass(), + new ValidConstructorPass(), + + // Rewriting shenanigans + $useStatementPass, // must run before the namespace pass + new ExitPass(), + new ImplicitReturnPass(), + new MagicConstantsPass(), + $namespacePass, // must run after the implicit return pass + new RequirePass(), + new StrictTypesPass($this->strictTypes), + + // Namespace-aware validation (which depends on aforementioned shenanigans) + new ValidClassNamePass(), + new ValidFunctionNamePass(), + ]; + } + + /** + * A set of code cleaner passes that don't try to do any validation, and + * only do minimal rewriting to make things work inside the REPL. + * + * This list should stay in sync with the "rewriting shenanigans" in + * getDefaultPasses above. + * + * @return CodeCleanerPass[] + */ + private function getYoloPasses(): array + { + $useStatementPass = new UseStatementPass(); + $namespacePass = new NamespacePass($this); + + // Try to add implicit `use` statements and an implicit namespace, + // based on the file in which the `debug` call was made. + $this->addImplicitDebugContext([$useStatementPass, $namespacePass]); + + return [ + new LeavePsyshAlonePass(), + $useStatementPass, // must run before the namespace pass + new ExitPass(), + new ImplicitReturnPass(), + new MagicConstantsPass(), + $namespacePass, // must run after the implicit return pass + new RequirePass(), + new StrictTypesPass($this->strictTypes), + ]; + } + + /** + * "Warm up" code cleaner passes when we're coming from a debug call. + * + * This is useful, for example, for `UseStatementPass` and `NamespacePass` + * which keep track of state between calls, to maintain the current + * namespace and a map of use statements. + * + * @param array $passes + */ + private function addImplicitDebugContext(array $passes) + { + $file = $this->getDebugFile(); + if ($file === null) { + return; + } + + try { + $code = @\file_get_contents($file); + if (!$code) { + return; + } + + $stmts = $this->parse($code, true); + if ($stmts === false) { + return; + } + + // Set up a clean traverser for just these code cleaner passes + $traverser = new NodeTraverser(); + foreach ($passes as $pass) { + $traverser->addVisitor($pass); + } + + $traverser->traverse($stmts); + } catch (\Throwable $e) { + // Don't care. + } + } + + /** + * Search the stack trace for a file in which the user called Psy\debug. + * + * @return string|null + */ + private static function getDebugFile() + { + $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + + foreach (\array_reverse($trace) as $stackFrame) { + if (!self::isDebugCall($stackFrame)) { + continue; + } + + if (\preg_match('/eval\(/', $stackFrame['file'])) { + \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches); + + return $matches[1][0]; + } + + return $stackFrame['file']; + } + } + + /** + * Check whether a given backtrace frame is a call to Psy\debug. + * + * @param array $stackFrame + */ + private static function isDebugCall(array $stackFrame): bool + { + $class = isset($stackFrame['class']) ? $stackFrame['class'] : null; + $function = isset($stackFrame['function']) ? $stackFrame['function'] : null; + + return ($class === null && $function === 'Psy\\debug') || + ($class === Shell::class && $function === 'debug'); + } + + /** + * Clean the given array of code. + * + * @throws ParseErrorException if the code is invalid PHP, and cannot be coerced into valid PHP + * + * @param array $codeLines + * @param bool $requireSemicolons + * + * @return string|false Cleaned PHP code, False if the input is incomplete + */ + public function clean(array $codeLines, bool $requireSemicolons = false) + { + $stmts = $this->parse('<?php '.\implode(\PHP_EOL, $codeLines).\PHP_EOL, $requireSemicolons); + if ($stmts === false) { + return false; + } + + // Catch fatal errors before they happen + $stmts = $this->traverser->traverse($stmts); + + // Work around https://github.com/nikic/PHP-Parser/issues/399 + $oldLocale = \setlocale(\LC_NUMERIC, 0); + \setlocale(\LC_NUMERIC, 'C'); + + $code = $this->printer->prettyPrint($stmts); + + // Now put the locale back + \setlocale(\LC_NUMERIC, $oldLocale); + + return $code; + } + + /** + * Set the current local namespace. + * + * @param array|null $namespace (default: null) + */ + public function setNamespace(array $namespace = null) + { + $this->namespace = $namespace; + } + + /** + * Get the current local namespace. + * + * @return array|null + */ + public function getNamespace() + { + return $this->namespace; + } + + /** + * Lex and parse a block of code. + * + * @see Parser::parse + * + * @throws ParseErrorException for parse errors that can't be resolved by + * waiting a line to see what comes next + * + * @param string $code + * @param bool $requireSemicolons + * + * @return array|false A set of statements, or false if incomplete + */ + protected function parse(string $code, bool $requireSemicolons = false) + { + try { + return $this->parser->parse($code); + } catch (\PhpParser\Error $e) { + if ($this->parseErrorIsUnclosedString($e, $code)) { + return false; + } + + if ($this->parseErrorIsUnterminatedComment($e, $code)) { + return false; + } + + if ($this->parseErrorIsTrailingComma($e, $code)) { + return false; + } + + if (!$this->parseErrorIsEOF($e)) { + throw ParseErrorException::fromParseError($e); + } + + if ($requireSemicolons) { + return false; + } + + try { + // Unexpected EOF, try again with an implicit semicolon + return $this->parser->parse($code.';'); + } catch (\PhpParser\Error $e) { + return false; + } + } + } + + private function parseErrorIsEOF(\PhpParser\Error $e): bool + { + $msg = $e->getRawMessage(); + + return ($msg === 'Unexpected token EOF') || (\strpos($msg, 'Syntax error, unexpected EOF') !== false); + } + + /** + * A special test for unclosed single-quoted strings. + * + * Unlike (all?) other unclosed statements, single quoted strings have + * their own special beautiful snowflake syntax error just for + * themselves. + * + * @param \PhpParser\Error $e + * @param string $code + */ + private function parseErrorIsUnclosedString(\PhpParser\Error $e, string $code): bool + { + if ($e->getRawMessage() !== 'Syntax error, unexpected T_ENCAPSED_AND_WHITESPACE') { + return false; + } + + try { + $this->parser->parse($code."';"); + } catch (\Throwable $e) { + return false; + } + + return true; + } + + private function parseErrorIsUnterminatedComment(\PhpParser\Error $e, $code): bool + { + return $e->getRawMessage() === 'Unterminated comment'; + } + + private function parseErrorIsTrailingComma(\PhpParser\Error $e, $code): bool + { + return ($e->getRawMessage() === 'A trailing comma is not allowed here') && (\substr(\rtrim($code), -1) === ','); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/AbstractClassPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/AbstractClassPass.php new file mode 100644 index 0000000..5b491ce --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/AbstractClassPass.php @@ -0,0 +1,75 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\ClassMethod; +use Psy\Exception\FatalErrorException; + +/** + * The abstract class pass handles abstract classes and methods, complaining if there are too few or too many of either. + */ +class AbstractClassPass extends CodeCleanerPass +{ + private $class; + private $abstractMethods; + + /** + * @throws FatalErrorException if the node is an abstract function with a body + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Class_) { + $this->class = $node; + $this->abstractMethods = []; + } elseif ($node instanceof ClassMethod) { + if ($node->isAbstract()) { + $name = \sprintf('%s::%s', $this->class->name, $node->name); + $this->abstractMethods[] = $name; + + if ($node->stmts !== null) { + $msg = \sprintf('Abstract function %s cannot contain body', $name); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } + } + + /** + * @throws FatalErrorException if the node is a non-abstract class with abstract methods + * + * @param Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if ($node instanceof Class_) { + $count = \count($this->abstractMethods); + if ($count > 0 && !$node->isAbstract()) { + $msg = \sprintf( + 'Class %s contains %d abstract method%s must therefore be declared abstract or implement the remaining methods (%s)', + $node->name, + $count, + ($count === 1) ? '' : 's', + \implode(', ', $this->abstractMethods) + ); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/AssignThisVariablePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/AssignThisVariablePass.php new file mode 100644 index 0000000..cdcb84a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/AssignThisVariablePass.php @@ -0,0 +1,41 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Assign; +use PhpParser\Node\Expr\Variable; +use Psy\Exception\FatalErrorException; + +/** + * Validate that the user input does not assign the `$this` variable. + * + * @author Martin Hasoň <martin.hason@gmail.com> + */ +class AssignThisVariablePass extends CodeCleanerPass +{ + /** + * Validate that the user input does not assign the `$this` variable. + * + * @throws FatalErrorException if the user assign the `$this` variable + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Assign && $node->var instanceof Variable && $node->var->name === 'this') { + throw new FatalErrorException('Cannot re-assign $this', 0, \E_ERROR, null, $node->getStartLine()); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CallTimePassByReferencePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CallTimePassByReferencePass.php new file mode 100644 index 0000000..c3eaed1 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CallTimePassByReferencePass.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\VariadicPlaceholder; +use Psy\Exception\FatalErrorException; + +/** + * Validate that the user did not use the call-time pass-by-reference that causes a fatal error. + * + * As of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error. + * + * @author Martin Hasoň <martin.hason@gmail.com> + */ +class CallTimePassByReferencePass extends CodeCleanerPass +{ + const EXCEPTION_MESSAGE = 'Call-time pass-by-reference has been removed'; + + /** + * Validate of use call-time pass-by-reference. + * + * @throws FatalErrorException if the user used call-time pass-by-reference + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if (!$node instanceof FuncCall && !$node instanceof MethodCall && !$node instanceof StaticCall) { + return; + } + + foreach ($node->args as $arg) { + if ($arg instanceof VariadicPlaceholder) { + continue; + } + + if ($arg->byRef) { + throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CalledClassPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CalledClassPass.php new file mode 100644 index 0000000..441685f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CalledClassPass.php @@ -0,0 +1,94 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\ConstFetch; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\Trait_; +use PhpParser\Node\VariadicPlaceholder; +use Psy\Exception\ErrorException; + +/** + * The called class pass throws warnings for get_class() and get_called_class() + * outside a class context. + */ +class CalledClassPass extends CodeCleanerPass +{ + private $inClass; + + /** + * @param array $nodes + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->inClass = false; + } + + /** + * @throws ErrorException if get_class or get_called_class is called without an object from outside a class + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Class_ || $node instanceof Trait_) { + $this->inClass = true; + } elseif ($node instanceof FuncCall && !$this->inClass) { + // We'll give any args at all (besides null) a pass. + // Technically we should be checking whether the args are objects, but this will do for now. + // + // @todo switch this to actually validate args when we get context-aware code cleaner passes. + if (!empty($node->args) && !$this->isNull($node->args[0])) { + return; + } + + // We'll ignore name expressions as well (things like `$foo()`) + if (!($node->name instanceof Name)) { + return; + } + + $name = \strtolower($node->name); + if (\in_array($name, ['get_class', 'get_called_class'])) { + $msg = \sprintf('%s() called without object from outside a class', $name); + throw new ErrorException($msg, 0, \E_USER_WARNING, null, $node->getStartLine()); + } + } + } + + /** + * @param Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if ($node instanceof Class_) { + $this->inClass = false; + } + } + + private function isNull(Node $node): bool + { + if ($node instanceof VariadicPlaceholder) { + return false; + } + + return $node->value instanceof ConstFetch && \strtolower($node->value->name) === 'null'; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CodeCleanerPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CodeCleanerPass.php new file mode 100644 index 0000000..244c9d4 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/CodeCleanerPass.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\NodeVisitorAbstract; + +/** + * A CodeCleaner pass is a PhpParser Node Visitor. + */ +abstract class CodeCleanerPass extends NodeVisitorAbstract +{ + // Wheee! +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/EmptyArrayDimFetchPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/EmptyArrayDimFetchPass.php new file mode 100644 index 0000000..88cdae9 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/EmptyArrayDimFetchPass.php @@ -0,0 +1,66 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\ArrayDimFetch; +use PhpParser\Node\Expr\Assign; +use PhpParser\Node\Expr\AssignRef; +use PhpParser\Node\Stmt\Foreach_; +use Psy\Exception\FatalErrorException; + +/** + * Validate empty brackets are only used for assignment. + */ +class EmptyArrayDimFetchPass extends CodeCleanerPass +{ + const EXCEPTION_MESSAGE = 'Cannot use [] for reading'; + + private $theseOnesAreFine = []; + + /** + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->theseOnesAreFine = []; + } + + /** + * @throws FatalErrorException if the user used empty array dim fetch outside of assignment + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Assign && $node->var instanceof ArrayDimFetch) { + $this->theseOnesAreFine[] = $node->var; + } elseif ($node instanceof AssignRef && $node->expr instanceof ArrayDimFetch) { + $this->theseOnesAreFine[] = $node->expr; + } elseif ($node instanceof Foreach_ && $node->valueVar instanceof ArrayDimFetch) { + $this->theseOnesAreFine[] = $node->valueVar; + } elseif ($node instanceof ArrayDimFetch && $node->var instanceof ArrayDimFetch) { + // $a[]['b'] = 'c' + if (\in_array($node, $this->theseOnesAreFine)) { + $this->theseOnesAreFine[] = $node->var; + } + } + + if ($node instanceof ArrayDimFetch && $node->dim === null) { + if (!\in_array($node, $this->theseOnesAreFine)) { + throw new FatalErrorException(self::EXCEPTION_MESSAGE, $node->getStartLine()); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ExitPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ExitPass.php new file mode 100644 index 0000000..e58a8d6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ExitPass.php @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Exit_; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use Psy\Exception\BreakException; + +class ExitPass extends CodeCleanerPass +{ + /** + * Converts exit calls to BreakExceptions. + * + * @param \PhpParser\Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if ($node instanceof Exit_) { + return new StaticCall(new FullyQualifiedName(BreakException::class), 'exitShell'); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FinalClassPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FinalClassPass.php new file mode 100644 index 0000000..1507664 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FinalClassPass.php @@ -0,0 +1,72 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Stmt\Class_; +use Psy\Exception\FatalErrorException; + +/** + * The final class pass handles final classes. + */ +class FinalClassPass extends CodeCleanerPass +{ + private $finalClasses; + + /** + * @param array $nodes + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->finalClasses = []; + } + + /** + * @throws FatalErrorException if the node is a class that extends a final class + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Class_) { + if ($node->extends) { + $extends = (string) $node->extends; + if ($this->isFinalClass($extends)) { + $msg = \sprintf('Class %s may not inherit from final class (%s)', $node->name, $extends); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } + + if ($node->isFinal()) { + $this->finalClasses[\strtolower($node->name)] = true; + } + } + } + + /** + * @param string $name Class name + */ + private function isFinalClass(string $name): bool + { + if (!\class_exists($name)) { + return isset($this->finalClasses[\strtolower($name)]); + } + + $refl = new \ReflectionClass($name); + + return $refl->isFinal(); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FunctionContextPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FunctionContextPass.php new file mode 100644 index 0000000..07a3e8f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FunctionContextPass.php @@ -0,0 +1,68 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Yield_; +use PhpParser\Node\FunctionLike; +use Psy\Exception\FatalErrorException; + +class FunctionContextPass extends CodeCleanerPass +{ + /** @var int */ + private $functionDepth; + + /** + * @param array $nodes + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->functionDepth = 0; + } + + /** + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof FunctionLike) { + $this->functionDepth++; + + return; + } + + // node is inside function context + if ($this->functionDepth !== 0) { + return; + } + + // It causes fatal error. + if ($node instanceof Yield_) { + $msg = 'The "yield" expression can only be used inside a function'; + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } + + /** + * @param \PhpParser\Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if ($node instanceof FunctionLike) { + $this->functionDepth--; + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FunctionReturnInWriteContextPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FunctionReturnInWriteContextPass.php new file mode 100644 index 0000000..2c50d5f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/FunctionReturnInWriteContextPass.php @@ -0,0 +1,77 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Array_; +use PhpParser\Node\Expr\Assign; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Expr\Isset_; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Stmt\Unset_; +use PhpParser\Node\VariadicPlaceholder; +use Psy\Exception\FatalErrorException; + +/** + * Validate that the functions are used correctly. + * + * @author Martin Hasoň <martin.hason@gmail.com> + */ +class FunctionReturnInWriteContextPass extends CodeCleanerPass +{ + const ISSET_MESSAGE = 'Cannot use isset() on the result of an expression (you can use "null !== expression" instead)'; + const EXCEPTION_MESSAGE = "Can't use function return value in write context"; + + /** + * Validate that the functions are used correctly. + * + * @throws FatalErrorException if a function is passed as an argument reference + * @throws FatalErrorException if a function is used as an argument in the isset + * @throws FatalErrorException if a value is assigned to a function + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Array_ || $this->isCallNode($node)) { + $items = $node instanceof Array_ ? $node->items : $node->args; + foreach ($items as $item) { + if ($item instanceof VariadicPlaceholder) { + continue; + } + + if ($item && $item->byRef && $this->isCallNode($item->value)) { + throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } elseif ($node instanceof Isset_ || $node instanceof Unset_) { + foreach ($node->vars as $var) { + if (!$this->isCallNode($var)) { + continue; + } + + $msg = $node instanceof Isset_ ? self::ISSET_MESSAGE : self::EXCEPTION_MESSAGE; + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } elseif ($node instanceof Assign && $this->isCallNode($node->var)) { + throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); + } + } + + private function isCallNode(Node $node): bool + { + return $node instanceof FuncCall || $node instanceof MethodCall || $node instanceof StaticCall; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ImplicitReturnPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ImplicitReturnPass.php new file mode 100644 index 0000000..2e4ebf3 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ImplicitReturnPass.php @@ -0,0 +1,125 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\Exit_; +use PhpParser\Node\Stmt; +use PhpParser\Node\Stmt\Break_; +use PhpParser\Node\Stmt\Expression; +use PhpParser\Node\Stmt\If_; +use PhpParser\Node\Stmt\Namespace_; +use PhpParser\Node\Stmt\Return_; +use PhpParser\Node\Stmt\Switch_; + +/** + * Add an implicit "return" to the last statement, provided it can be returned. + */ +class ImplicitReturnPass extends CodeCleanerPass +{ + /** + * @param array $nodes + * + * @return array + */ + public function beforeTraverse(array $nodes): array + { + return $this->addImplicitReturn($nodes); + } + + /** + * @param array $nodes + * + * @return array + */ + private function addImplicitReturn(array $nodes): array + { + // If nodes is empty, it can't have a return value. + if (empty($nodes)) { + return [new Return_(NoReturnValue::create())]; + } + + $last = \end($nodes); + + // Special case a few types of statements to add an implicit return + // value (even though they technically don't have any return value) + // because showing a return value in these instances is useful and not + // very surprising. + if ($last instanceof If_) { + $last->stmts = $this->addImplicitReturn($last->stmts); + + foreach ($last->elseifs as $elseif) { + $elseif->stmts = $this->addImplicitReturn($elseif->stmts); + } + + if ($last->else) { + $last->else->stmts = $this->addImplicitReturn($last->else->stmts); + } + } elseif ($last instanceof Switch_) { + foreach ($last->cases as $case) { + // only add an implicit return to cases which end in break + $caseLast = \end($case->stmts); + if ($caseLast instanceof Break_) { + $case->stmts = $this->addImplicitReturn(\array_slice($case->stmts, 0, -1)); + $case->stmts[] = $caseLast; + } + } + } elseif ($last instanceof Expr && !($last instanceof Exit_)) { + // @codeCoverageIgnoreStart + $nodes[\count($nodes) - 1] = new Return_($last, [ + 'startLine' => $last->getStartLine(), + 'endLine' => $last->getEndLine(), + ]); + // @codeCoverageIgnoreEnd + } elseif ($last instanceof Expression && !($last->expr instanceof Exit_)) { + $nodes[\count($nodes) - 1] = new Return_($last->expr, [ + 'startLine' => $last->getStartLine(), + 'endLine' => $last->getEndLine(), + ]); + } elseif ($last instanceof Namespace_) { + $last->stmts = $this->addImplicitReturn($last->stmts); + } + + // Return a "no return value" for all non-expression statements, so that + // PsySH can suppress the `null` that `eval()` returns otherwise. + // + // Note that statements special cased above (if/elseif/else, switch) + // _might_ implicitly return a value before this catch-all return is + // reached. + // + // We're not adding a fallback return after namespace statements, + // because code outside namespace statements doesn't really work, and + // there's already an implicit return in the namespace statement anyway. + if (self::isNonExpressionStmt($last)) { + $nodes[] = new Return_(NoReturnValue::create()); + } + + return $nodes; + } + + /** + * Check whether a given node is a non-expression statement. + * + * As of PHP Parser 4.x, Expressions are now instances of Stmt as well, so + * we'll exclude them here. + * + * @param Node $node + */ + private static function isNonExpressionStmt(Node $node): bool + { + return $node instanceof Stmt && + !$node instanceof Expression && + !$node instanceof Return_ && + !$node instanceof Namespace_; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/IssetPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/IssetPass.php new file mode 100644 index 0000000..fa8f60c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/IssetPass.php @@ -0,0 +1,49 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\ArrayDimFetch; +use PhpParser\Node\Expr\Isset_; +use PhpParser\Node\Expr\NullsafePropertyFetch; +use PhpParser\Node\Expr\PropertyFetch; +use PhpParser\Node\Expr\Variable; +use Psy\Exception\FatalErrorException; + +/** + * Code cleaner pass to ensure we only allow variables, array fetch and property + * fetch expressions in isset() calls. + */ +class IssetPass extends CodeCleanerPass +{ + const EXCEPTION_MSG = 'Cannot use isset() on the result of an expression (you can use "null !== expression" instead)'; + + /** + * @throws FatalErrorException + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if (!$node instanceof Isset_) { + return; + } + + foreach ($node->vars as $var) { + if (!$var instanceof Variable && !$var instanceof ArrayDimFetch && !$var instanceof PropertyFetch && !$var instanceof NullsafePropertyFetch) { + throw new FatalErrorException(self::EXCEPTION_MSG, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LabelContextPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LabelContextPass.php new file mode 100644 index 0000000..44962f6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LabelContextPass.php @@ -0,0 +1,101 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\FunctionLike; +use PhpParser\Node\Stmt\Goto_; +use PhpParser\Node\Stmt\Label; +use Psy\Exception\FatalErrorException; + +/** + * CodeCleanerPass for label context. + * + * This class partially emulates the PHP label specification. + * PsySH can not declare labels by sequentially executing lines with eval, + * but since it is not a syntax error, no error is raised. + * This class warns before invalid goto causes a fatal error. + * Since this is a simple checker, it does not block real fatal error + * with complex syntax. (ex. it does not parse inside function.) + * + * @see http://php.net/goto + */ +class LabelContextPass extends CodeCleanerPass +{ + /** @var int */ + private $functionDepth; + + /** @var array */ + private $labelDeclarations; + /** @var array */ + private $labelGotos; + + /** + * @param array $nodes + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->functionDepth = 0; + $this->labelDeclarations = []; + $this->labelGotos = []; + } + + /** + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof FunctionLike) { + $this->functionDepth++; + + return; + } + + // node is inside function context + if ($this->functionDepth !== 0) { + return; + } + + if ($node instanceof Goto_) { + $this->labelGotos[\strtolower($node->name)] = $node->getStartLine(); + } elseif ($node instanceof Label) { + $this->labelDeclarations[\strtolower($node->name)] = $node->getStartLine(); + } + } + + /** + * @param \PhpParser\Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if ($node instanceof FunctionLike) { + $this->functionDepth--; + } + } + + /** + * @return Node[]|null Array of nodes + */ + public function afterTraverse(array $nodes) + { + foreach ($this->labelGotos as $name => $line) { + if (!isset($this->labelDeclarations[$name])) { + $msg = "'goto' to undefined label '{$name}'"; + throw new FatalErrorException($msg, 0, \E_ERROR, null, $line); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LeavePsyshAlonePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LeavePsyshAlonePass.php new file mode 100644 index 0000000..67ba68b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LeavePsyshAlonePass.php @@ -0,0 +1,38 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Variable; +use Psy\Exception\RuntimeException; + +/** + * Validate that the user input does not reference the `$__psysh__` variable. + */ +class LeavePsyshAlonePass extends CodeCleanerPass +{ + /** + * Validate that the user input does not reference the `$__psysh__` variable. + * + * @throws RuntimeException if the user is messing with $__psysh__ + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Variable && $node->name === '__psysh__') { + throw new RuntimeException('Don\'t mess with $__psysh__; bad things will happen'); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ListPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ListPass.php new file mode 100644 index 0000000..eb0001a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ListPass.php @@ -0,0 +1,93 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Array_; +use PhpParser\Node\Expr\ArrayDimFetch; +use PhpParser\Node\Expr\ArrayItem; +use PhpParser\Node\Expr\Assign; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Expr\List_; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\PropertyFetch; +use PhpParser\Node\Expr\Variable; +use Psy\Exception\ParseErrorException; + +/** + * Validate that the list assignment. + */ +class ListPass extends CodeCleanerPass +{ + /** + * Validate use of list assignment. + * + * @throws ParseErrorException if the user used empty with anything but a variable + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if (!$node instanceof Assign) { + return; + } + + if (!$node->var instanceof Array_ && !$node->var instanceof List_) { + return; + } + + // Polyfill for PHP-Parser 2.x + $items = isset($node->var->items) ? $node->var->items : $node->var->vars; + + if ($items === [] || $items === [null]) { + throw new ParseErrorException('Cannot use empty list', ['startLine' => $node->var->getStartLine(), 'endLine' => $node->var->getEndLine()]); + } + + $itemFound = false; + foreach ($items as $item) { + if ($item === null) { + continue; + } + + $itemFound = true; + + if (!self::isValidArrayItem($item)) { + $msg = 'Assignments can only happen to writable values'; + throw new ParseErrorException($msg, ['startLine' => $item->getStartLine(), 'endLine' => $item->getEndLine()]); + } + } + + if (!$itemFound) { + throw new ParseErrorException('Cannot use empty list'); + } + } + + /** + * Validate whether a given item in an array is valid for short assignment. + * + * @param Node $item + */ + private static function isValidArrayItem(Node $item): bool + { + $value = ($item instanceof ArrayItem) ? $item->value : $item; + + while ($value instanceof ArrayDimFetch || $value instanceof PropertyFetch) { + $value = $value->var; + } + + // We just kind of give up if it's a method call. We can't tell if it's + // valid via static analysis. + return $value instanceof Variable || $value instanceof MethodCall || $value instanceof FuncCall; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LoopContextPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LoopContextPass.php new file mode 100644 index 0000000..5bb175e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/LoopContextPass.php @@ -0,0 +1,109 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Scalar\DNumber; +use PhpParser\Node\Scalar\LNumber; +use PhpParser\Node\Stmt\Break_; +use PhpParser\Node\Stmt\Continue_; +use PhpParser\Node\Stmt\Do_; +use PhpParser\Node\Stmt\For_; +use PhpParser\Node\Stmt\Foreach_; +use PhpParser\Node\Stmt\Switch_; +use PhpParser\Node\Stmt\While_; +use Psy\Exception\FatalErrorException; + +/** + * The loop context pass handles invalid `break` and `continue` statements. + */ +class LoopContextPass extends CodeCleanerPass +{ + private $loopDepth; + + /** + * {@inheritdoc} + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->loopDepth = 0; + } + + /** + * @throws FatalErrorException if the node is a break or continue in a non-loop or switch context + * @throws FatalErrorException if the node is trying to break out of more nested structures than exist + * @throws FatalErrorException if the node is a break or continue and has a non-numeric argument + * @throws FatalErrorException if the node is a break or continue and has an argument less than 1 + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + switch (true) { + case $node instanceof Do_: + case $node instanceof For_: + case $node instanceof Foreach_: + case $node instanceof Switch_: + case $node instanceof While_: + $this->loopDepth++; + break; + + case $node instanceof Break_: + case $node instanceof Continue_: + $operator = $node instanceof Break_ ? 'break' : 'continue'; + + if ($this->loopDepth === 0) { + $msg = \sprintf("'%s' not in the 'loop' or 'switch' context", $operator); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + + if ($node->num instanceof LNumber || $node->num instanceof DNumber) { + $num = $node->num->value; + if ($node->num instanceof DNumber || $num < 1) { + $msg = \sprintf("'%s' operator accepts only positive numbers", $operator); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + + if ($num > $this->loopDepth) { + $msg = \sprintf("Cannot '%s' %d levels", $operator, $num); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } elseif ($node->num) { + $msg = \sprintf("'%s' operator with non-constant operand is no longer supported", $operator); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + break; + } + } + + /** + * @param Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + switch (true) { + case $node instanceof Do_: + case $node instanceof For_: + case $node instanceof Foreach_: + case $node instanceof Switch_: + case $node instanceof While_: + $this->loopDepth--; + break; + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/MagicConstantsPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/MagicConstantsPass.php new file mode 100644 index 0000000..3c468af --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/MagicConstantsPass.php @@ -0,0 +1,42 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar\MagicConst\Dir; +use PhpParser\Node\Scalar\MagicConst\File; +use PhpParser\Node\Scalar\String_; + +/** + * Swap out __DIR__ and __FILE__ magic constants with our best guess? + */ +class MagicConstantsPass extends CodeCleanerPass +{ + /** + * Swap out __DIR__ and __FILE__ constants, because the default ones when + * calling eval() don't make sense. + * + * @param Node $node + * + * @return FuncCall|String_|null + */ + public function enterNode(Node $node) + { + if ($node instanceof Dir) { + return new FuncCall(new Name('getcwd'), [], $node->getAttributes()); + } elseif ($node instanceof File) { + return new String_('', $node->getAttributes()); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NamespaceAwarePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NamespaceAwarePass.php new file mode 100644 index 0000000..53290fd --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NamespaceAwarePass.php @@ -0,0 +1,85 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use PhpParser\Node\Stmt\Namespace_; + +/** + * Abstract namespace-aware code cleaner pass. + */ +abstract class NamespaceAwarePass extends CodeCleanerPass +{ + protected $namespace; + protected $currentScope; + + /** + * @todo should this be final? Extending classes should be sure to either + * use afterTraverse or call parent::beforeTraverse() when overloading. + * + * Reset the namespace and the current scope before beginning analysis + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->namespace = []; + $this->currentScope = []; + } + + /** + * @todo should this be final? Extending classes should be sure to either use + * leaveNode or call parent::enterNode() when overloading + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Namespace_) { + $this->namespace = isset($node->name) ? $this->getParts($node->name) : []; + } + } + + /** + * Get a fully-qualified name (class, function, interface, etc). + * + * @param mixed $name + */ + protected function getFullyQualifiedName($name): string + { + if ($name instanceof FullyQualifiedName) { + return \implode('\\', $this->getParts($name)); + } + + if ($name instanceof Name) { + $name = $this->getParts($name); + } elseif (!\is_array($name)) { + $name = [$name]; + } + + return \implode('\\', \array_merge($this->namespace, $name)); + } + + /** + * Backwards compatibility shim for PHP-Parser 4.x. + * + * At some point we might want to make $namespace a plain string, to match how Name works? + */ + protected function getParts(Name $name): array + { + return \method_exists($name, 'getParts') ? $name->getParts() : $name->parts; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NamespacePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NamespacePass.php new file mode 100644 index 0000000..25c0be0 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NamespacePass.php @@ -0,0 +1,101 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt\Namespace_; +use Psy\CodeCleaner; + +/** + * Provide implicit namespaces for subsequent execution. + * + * The namespace pass remembers the last standalone namespace line encountered: + * + * namespace Foo\Bar; + * + * ... which it then applies implicitly to all future evaluated code, until the + * namespace is replaced by another namespace. To reset to the top level + * namespace, enter `namespace {}`. This is a bit ugly, but it does the trick :) + */ +class NamespacePass extends CodeCleanerPass +{ + private $namespace = null; + private $cleaner; + + /** + * @param CodeCleaner $cleaner + */ + public function __construct(CodeCleaner $cleaner) + { + $this->cleaner = $cleaner; + } + + /** + * If this is a standalone namespace line, remember it for later. + * + * Otherwise, apply remembered namespaces to the code until a new namespace + * is encountered. + * + * @param array $nodes + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + if (empty($nodes)) { + return $nodes; + } + + $last = \end($nodes); + + if ($last instanceof Namespace_) { + $kind = $last->getAttribute('kind'); + + // Treat all namespace statements pre-PHP-Parser v3.1.2 as "open", + // even though we really have no way of knowing. + if ($kind === null || $kind === Namespace_::KIND_SEMICOLON) { + // Save the current namespace for open namespaces + $this->setNamespace($last->name); + } else { + // Clear the current namespace after a braced namespace + $this->setNamespace(null); + } + + return $nodes; + } + + return $this->namespace ? [new Namespace_($this->namespace, $nodes)] : $nodes; + } + + /** + * Remember the namespace and (re)set the namespace on the CodeCleaner as + * well. + * + * @param Name|null $namespace + */ + private function setNamespace($namespace) + { + $this->namespace = $namespace; + $this->cleaner->setNamespace($namespace === null ? null : $this->getParts($namespace)); + } + + /** + * Backwards compatibility shim for PHP-Parser 4.x. + * + * At some point we might want to make the namespace a plain string, to match how Name works? + */ + protected function getParts(Name $name): array + { + return \method_exists($name, 'getParts') ? $name->getParts() : $name->parts; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NoReturnValue.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NoReturnValue.php new file mode 100644 index 0000000..53f30a2 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/NoReturnValue.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node\Expr\New_; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; + +/** + * A class used internally by CodeCleaner to represent input, such as + * non-expression statements, with no return value. + * + * Note that user code returning an instance of this class will act like it + * has no return value, so you prolly shouldn't do that. + */ +class NoReturnValue +{ + /** + * Get PhpParser AST expression for creating a new NoReturnValue. + */ + public static function create(): New_ + { + return new New_(new FullyQualifiedName(self::class)); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/PassableByReferencePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/PassableByReferencePass.php new file mode 100644 index 0000000..7a33151 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/PassableByReferencePass.php @@ -0,0 +1,119 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\Array_; +use PhpParser\Node\Expr\ArrayDimFetch; +use PhpParser\Node\Expr\ClassConstFetch; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\PropertyFetch; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Expr\Variable; +use Psy\Exception\FatalErrorException; + +/** + * Validate that only variables (and variable-like things) are passed by reference. + */ +class PassableByReferencePass extends CodeCleanerPass +{ + const EXCEPTION_MESSAGE = 'Only variables can be passed by reference'; + + /** + * @throws FatalErrorException if non-variables are passed by reference + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + // @todo support MethodCall and StaticCall as well. + if ($node instanceof FuncCall) { + // if function name is an expression or a variable, give it a pass for now. + if ($node->name instanceof Expr || $node->name instanceof Variable) { + return; + } + + $name = (string) $node->name; + + if ($name === 'array_multisort') { + return $this->validateArrayMultisort($node); + } + + try { + $refl = new \ReflectionFunction($name); + } catch (\ReflectionException $e) { + // Well, we gave it a shot! + return; + } + + foreach ($refl->getParameters() as $key => $param) { + if (\array_key_exists($key, $node->args)) { + $arg = $node->args[$key]; + if ($param->isPassedByReference() && !$this->isPassableByReference($arg)) { + throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } + } + } + + private function isPassableByReference(Node $arg): bool + { + // Unpacked arrays can be passed by reference + if ($arg->value instanceof Array_) { + return $arg->unpack; + } + + // FuncCall, MethodCall and StaticCall are all PHP _warnings_ not fatal errors, so we'll let + // PHP handle those ones :) + return $arg->value instanceof ClassConstFetch || + $arg->value instanceof PropertyFetch || + $arg->value instanceof Variable || + $arg->value instanceof FuncCall || + $arg->value instanceof MethodCall || + $arg->value instanceof StaticCall || + $arg->value instanceof ArrayDimFetch; + } + + /** + * Because array_multisort has a problematic signature... + * + * The argument order is all sorts of wonky, and whether something is passed + * by reference or not depends on the values of the two arguments before it. + * We'll do a good faith attempt at validating this, but err on the side of + * permissive. + * + * This is why you don't design languages where core code and extensions can + * implement APIs that wouldn't be possible in userland code. + * + * @throws FatalErrorException for clearly invalid arguments + * + * @param Node $node + */ + private function validateArrayMultisort(Node $node) + { + $nonPassable = 2; // start with 2 because the first one has to be passable by reference + foreach ($node->args as $arg) { + if ($this->isPassableByReference($arg)) { + $nonPassable = 0; + } elseif (++$nonPassable > 2) { + // There can be *at most* two non-passable-by-reference args in a row. This is about + // as close as we can get to validating the arguments for this function :-/ + throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/RequirePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/RequirePass.php new file mode 100644 index 0000000..0fe7af0 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/RequirePass.php @@ -0,0 +1,133 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr\Include_; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use PhpParser\Node\Scalar\LNumber; +use Psy\Exception\ErrorException; +use Psy\Exception\FatalErrorException; + +/** + * Add runtime validation for `require` and `require_once` calls. + */ +class RequirePass extends CodeCleanerPass +{ + private static $requireTypes = [Include_::TYPE_REQUIRE, Include_::TYPE_REQUIRE_ONCE]; + + /** + * {@inheritdoc} + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $origNode) + { + if (!$this->isRequireNode($origNode)) { + return; + } + + $node = clone $origNode; + + /* + * rewrite + * + * $foo = require $bar + * + * to + * + * $foo = require \Psy\CodeCleaner\RequirePass::resolve($bar) + */ + $node->expr = new StaticCall( + new FullyQualifiedName(self::class), + 'resolve', + [new Arg($origNode->expr), new Arg(new LNumber($origNode->getStartLine()))], + $origNode->getAttributes() + ); + + return $node; + } + + /** + * Runtime validation that $file can be resolved as an include path. + * + * If $file can be resolved, return $file. Otherwise throw a fatal error exception. + * + * If $file collides with a path in the currently running PsySH phar, it will be resolved + * relative to the include path, to prevent PHP from grabbing the phar version of the file. + * + * @throws FatalErrorException when unable to resolve include path for $file + * @throws ErrorException if $file is empty and E_WARNING is included in error_reporting level + * + * @param string $file + * @param int $startLine Line number of the original require expression + * + * @return string Exactly the same as $file, unless $file collides with a path in the currently running phar + */ + public static function resolve($file, $startLine = null): string + { + $file = (string) $file; + + if ($file === '') { + // @todo Shell::handleError would be better here, because we could + // fake the file and line number, but we can't call it statically. + // So we're duplicating some of the logics here. + if (\E_WARNING & \error_reporting()) { + ErrorException::throwException(\E_WARNING, 'Filename cannot be empty', null, $startLine); + } + // @todo trigger an error as fallback? this is pretty ugly… + // trigger_error('Filename cannot be empty', E_USER_WARNING); + } + + $resolvedPath = \stream_resolve_include_path($file); + if ($file === '' || !$resolvedPath) { + $msg = \sprintf("Failed opening required '%s'", $file); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $startLine); + } + + // Special case: if the path is not already relative or absolute, and it would resolve to + // something inside the currently running phar (e.g. `vendor/autoload.php`), we'll resolve + // it relative to the include path so PHP won't grab the phar version. + // + // Note that this only works if the phar has `psysh` in the path. We might want to lift this + // restriction and special case paths that would collide with any running phar? + if ($resolvedPath !== $file && $file[0] !== '.') { + $runningPhar = \Phar::running(); + if (\strpos($runningPhar, 'psysh') !== false && \is_file($runningPhar.\DIRECTORY_SEPARATOR.$file)) { + foreach (self::getIncludePath() as $prefix) { + $resolvedPath = $prefix.\DIRECTORY_SEPARATOR.$file; + if (\is_file($resolvedPath)) { + return $resolvedPath; + } + } + } + } + + return $file; + } + + private function isRequireNode(Node $node): bool + { + return $node instanceof Include_ && \in_array($node->type, self::$requireTypes); + } + + private static function getIncludePath(): array + { + if (\PATH_SEPARATOR === ':') { + return \preg_split('#:(?!//)#', \get_include_path()); + } + + return \explode(\PATH_SEPARATOR, \get_include_path()); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ReturnTypePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ReturnTypePass.php new file mode 100644 index 0000000..c9894fb --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ReturnTypePass.php @@ -0,0 +1,113 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr\Closure; +use PhpParser\Node\Expr\ConstFetch; +use PhpParser\Node\Identifier; +use PhpParser\Node\NullableType; +use PhpParser\Node\Stmt\Function_; +use PhpParser\Node\Stmt\Return_; +use PhpParser\Node\UnionType; +use Psy\Exception\FatalErrorException; + +/** + * Add runtime validation for return types. + */ +class ReturnTypePass extends CodeCleanerPass +{ + const MESSAGE = 'A function with return type must return a value'; + const NULLABLE_MESSAGE = 'A function with return type must return a value (did you mean "return null;" instead of "return;"?)'; + const VOID_MESSAGE = 'A void function must not return a value'; + const VOID_NULL_MESSAGE = 'A void function must not return a value (did you mean "return;" instead of "return null;"?)'; + const NULLABLE_VOID_MESSAGE = 'Void type cannot be nullable'; + + private $returnTypeStack = []; + + /** + * {@inheritdoc} + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($this->isFunctionNode($node)) { + $this->returnTypeStack[] = $node->returnType; + + return; + } + + if (!empty($this->returnTypeStack) && $node instanceof Return_) { + $expectedType = \end($this->returnTypeStack); + if ($expectedType === null) { + return; + } + + $msg = null; + + if ($this->typeName($expectedType) === 'void') { + // Void functions + if ($expectedType instanceof NullableType) { + $msg = self::NULLABLE_VOID_MESSAGE; + } elseif ($node->expr instanceof ConstFetch && \strtolower($node->expr->name) === 'null') { + $msg = self::VOID_NULL_MESSAGE; + } elseif ($node->expr !== null) { + $msg = self::VOID_MESSAGE; + } + } else { + // Everything else + if ($node->expr === null) { + $msg = $expectedType instanceof NullableType ? self::NULLABLE_MESSAGE : self::MESSAGE; + } + } + + if ($msg !== null) { + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } + } + + /** + * {@inheritdoc} + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if (!empty($this->returnTypeStack) && $this->isFunctionNode($node)) { + \array_pop($this->returnTypeStack); + } + } + + private function isFunctionNode(Node $node): bool + { + return $node instanceof Function_ || $node instanceof Closure; + } + + private function typeName(Node $node): string + { + if ($node instanceof UnionType) { + return \implode('|', \array_map([$this, 'typeName'], $node->types)); + } + + if ($node instanceof NullableType) { + return \strtolower($node->type->name); + } + + if ($node instanceof Identifier) { + return \strtolower($node->name); + } + + throw new \InvalidArgumentException('Unable to find type name'); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/StrictTypesPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/StrictTypesPass.php new file mode 100644 index 0000000..d0ce353 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/StrictTypesPass.php @@ -0,0 +1,85 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Scalar\LNumber; +use PhpParser\Node\Stmt\Declare_; +use PhpParser\Node\Stmt\DeclareDeclare; +use Psy\Exception\FatalErrorException; + +/** + * Provide implicit strict types declarations for for subsequent execution. + * + * The strict types pass remembers the last strict types declaration: + * + * declare(strict_types=1); + * + * ... which it then applies implicitly to all future evaluated code, until it + * is replaced by a new declaration. + */ +class StrictTypesPass extends CodeCleanerPass +{ + const EXCEPTION_MESSAGE = 'strict_types declaration must have 0 or 1 as its value'; + + private $strictTypes = false; + + /** + * @param bool $strictTypes enforce strict types by default + */ + public function __construct(bool $strictTypes = false) + { + $this->strictTypes = $strictTypes; + } + + /** + * If this is a standalone strict types declaration, remember it for later. + * + * Otherwise, apply remembered strict types declaration to to the code until + * a new declaration is encountered. + * + * @throws FatalErrorException if an invalid `strict_types` declaration is found + * + * @param array $nodes + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $prependStrictTypes = $this->strictTypes; + + foreach ($nodes as $node) { + if ($node instanceof Declare_) { + foreach ($node->declares as $declare) { + if ($declare->key->toString() === 'strict_types') { + $value = $declare->value; + if (!$value instanceof LNumber || ($value->value !== 0 && $value->value !== 1)) { + throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); + } + + $this->strictTypes = $value->value === 1; + } + } + } + } + + if ($prependStrictTypes) { + $first = \reset($nodes); + if (!$first instanceof Declare_) { + $declare = new Declare_([new DeclareDeclare('strict_types', new LNumber(1))]); + \array_unshift($nodes, $declare); + } + } + + return $nodes; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/UseStatementPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/UseStatementPass.php new file mode 100644 index 0000000..5d4cbdc --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/UseStatementPass.php @@ -0,0 +1,140 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use PhpParser\Node\Stmt\GroupUse; +use PhpParser\Node\Stmt\Namespace_; +use PhpParser\Node\Stmt\Use_; +use PhpParser\Node\Stmt\UseItem; +use PhpParser\Node\Stmt\UseUse; +use PhpParser\NodeTraverser; + +/** + * Provide implicit use statements for subsequent execution. + * + * The use statement pass remembers the last use statement line encountered: + * + * use Foo\Bar as Baz; + * + * ... which it then applies implicitly to all future evaluated code, until the + * current namespace is replaced by another namespace. + */ +class UseStatementPass extends CodeCleanerPass +{ + private $aliases = []; + private $lastAliases = []; + private $lastNamespace = null; + + /** + * Re-load the last set of use statements on re-entering a namespace. + * + * This isn't how namespaces normally work, but because PsySH has to spin + * up a new namespace for every line of code, we do this to make things + * work like you'd expect. + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Namespace_) { + // If this is the same namespace as last namespace, let's do ourselves + // a favor and reload all the aliases... + if (\strtolower($node->name ?: '') === \strtolower($this->lastNamespace ?: '')) { + $this->aliases = $this->lastAliases; + } + } + } + + /** + * If this statement is a namespace, forget all the aliases we had. + * + * If it's a use statement, remember the alias for later. Otherwise, apply + * remembered aliases to the code. + * + * @param Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + // Store a reference to every "use" statement, because we'll need them in a bit. + if ($node instanceof Use_) { + foreach ($node->uses as $useItem) { + $this->aliases[\strtolower($useItem->getAlias())] = $useItem->name; + } + + return NodeTraverser::REMOVE_NODE; + } + + // Expand every "use" statement in the group into a full, standalone "use" and store 'em with the others. + if ($node instanceof GroupUse) { + foreach ($node->uses as $useItem) { + $this->aliases[\strtolower($useItem->getAlias())] = Name::concat($node->prefix, $useItem->name, [ + 'startLine' => $node->prefix->getAttribute('startLine'), + 'endLine' => $useItem->name->getAttribute('endLine'), + ]); + } + + return NodeTraverser::REMOVE_NODE; + } + + // Start fresh, since we're done with this namespace. + if ($node instanceof Namespace_) { + $this->lastNamespace = $node->name; + $this->lastAliases = $this->aliases; + $this->aliases = []; + + return; + } + + // Do nothing with UseItem; this an entry in the list of uses in the use statement. + // @todo Remove UseUse once we drop support for PHP-Parser 4.x + if ($node instanceof UseUse || $node instanceof UseItem) { + return; + } + + // For everything else, we'll implicitly thunk all aliases into fully-qualified names. + foreach ($node as $name => $subNode) { + if ($subNode instanceof Name) { + if ($replacement = $this->findAlias($subNode)) { + $node->$name = $replacement; + } + } + } + + return $node; + } + + /** + * Find class/namespace aliases. + * + * @param Name $name + * + * @return FullyQualifiedName|null + */ + private function findAlias(Name $name) + { + $that = \strtolower($name); + foreach ($this->aliases as $alias => $prefix) { + if ($that === $alias) { + return new FullyQualifiedName($prefix->toString()); + } elseif (\substr($that, 0, \strlen($alias) + 1) === $alias.'\\') { + return new FullyQualifiedName($prefix->toString().\substr($name, \strlen($alias))); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidClassNamePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidClassNamePass.php new file mode 100644 index 0000000..dff32d5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidClassNamePass.php @@ -0,0 +1,326 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\Ternary; +use PhpParser\Node\Stmt; +use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\Do_; +use PhpParser\Node\Stmt\If_; +use PhpParser\Node\Stmt\Interface_; +use PhpParser\Node\Stmt\Switch_; +use PhpParser\Node\Stmt\Trait_; +use PhpParser\Node\Stmt\While_; +use Psy\Exception\FatalErrorException; + +/** + * Validate that classes exist. + * + * This pass throws a FatalErrorException rather than letting PHP run + * headfirst into a real fatal error and die. + */ +class ValidClassNamePass extends NamespaceAwarePass +{ + const CLASS_TYPE = 'class'; + const INTERFACE_TYPE = 'interface'; + const TRAIT_TYPE = 'trait'; + + private $conditionalScopes = 0; + + /** + * Validate class, interface and trait definitions. + * + * Validate them upon entering the node, so that we know about their + * presence and can validate constant fetches and static calls in class or + * trait methods. + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + parent::enterNode($node); + + if (self::isConditional($node)) { + $this->conditionalScopes++; + + return; + } + + if ($this->conditionalScopes === 0) { + if ($node instanceof Class_) { + $this->validateClassStatement($node); + } elseif ($node instanceof Interface_) { + $this->validateInterfaceStatement($node); + } elseif ($node instanceof Trait_) { + $this->validateTraitStatement($node); + } + } + } + + /** + * @param Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if (self::isConditional($node)) { + $this->conditionalScopes--; + } + } + + private static function isConditional(Node $node): bool + { + return $node instanceof If_ || + $node instanceof While_ || + $node instanceof Do_ || + $node instanceof Switch_ || + $node instanceof Ternary; + } + + /** + * Validate a class definition statement. + * + * @param Class_ $stmt + */ + protected function validateClassStatement(Class_ $stmt) + { + $this->ensureCanDefine($stmt, self::CLASS_TYPE); + if (isset($stmt->extends)) { + $this->ensureClassExists($this->getFullyQualifiedName($stmt->extends), $stmt); + } + $this->ensureInterfacesExist($stmt->implements, $stmt); + } + + /** + * Validate an interface definition statement. + * + * @param Interface_ $stmt + */ + protected function validateInterfaceStatement(Interface_ $stmt) + { + $this->ensureCanDefine($stmt, self::INTERFACE_TYPE); + $this->ensureInterfacesExist($stmt->extends, $stmt); + } + + /** + * Validate a trait definition statement. + * + * @param Trait_ $stmt + */ + protected function validateTraitStatement(Trait_ $stmt) + { + $this->ensureCanDefine($stmt, self::TRAIT_TYPE); + } + + /** + * Ensure that no class, interface or trait name collides with a new definition. + * + * @throws FatalErrorException + * + * @param Stmt $stmt + * @param string $scopeType + */ + protected function ensureCanDefine(Stmt $stmt, string $scopeType = self::CLASS_TYPE) + { + // Anonymous classes don't have a name, and uniqueness shouldn't be enforced. + if ($stmt->name === null) { + return; + } + + $name = $this->getFullyQualifiedName($stmt->name); + + // check for name collisions + $errorType = null; + if ($this->classExists($name)) { + $errorType = self::CLASS_TYPE; + } elseif ($this->interfaceExists($name)) { + $errorType = self::INTERFACE_TYPE; + } elseif ($this->traitExists($name)) { + $errorType = self::TRAIT_TYPE; + } + + if ($errorType !== null) { + throw $this->createError(\sprintf('%s named %s already exists', \ucfirst($errorType), $name), $stmt); + } + + // Store creation for the rest of this code snippet so we can find local + // issue too + $this->currentScope[\strtolower($name)] = $scopeType; + } + + /** + * Ensure that a referenced class exists. + * + * @throws FatalErrorException + * + * @param string $name + * @param Stmt $stmt + */ + protected function ensureClassExists(string $name, Stmt $stmt) + { + if (!$this->classExists($name)) { + throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt); + } + } + + /** + * Ensure that a referenced class _or interface_ exists. + * + * @throws FatalErrorException + * + * @param string $name + * @param Stmt $stmt + */ + protected function ensureClassOrInterfaceExists(string $name, Stmt $stmt) + { + if (!$this->classExists($name) && !$this->interfaceExists($name)) { + throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt); + } + } + + /** + * Ensure that a referenced class _or trait_ exists. + * + * @throws FatalErrorException + * + * @param string $name + * @param Stmt $stmt + */ + protected function ensureClassOrTraitExists(string $name, Stmt $stmt) + { + if (!$this->classExists($name) && !$this->traitExists($name)) { + throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt); + } + } + + /** + * Ensure that a statically called method exists. + * + * @throws FatalErrorException + * + * @param string $class + * @param string $name + * @param Stmt $stmt + */ + protected function ensureMethodExists(string $class, string $name, Stmt $stmt) + { + $this->ensureClassOrTraitExists($class, $stmt); + + // let's pretend all calls to self, parent and static are valid + if (\in_array(\strtolower($class), ['self', 'parent', 'static'])) { + return; + } + + // ... and all calls to classes defined right now + if ($this->findInScope($class) === self::CLASS_TYPE) { + return; + } + + // if method name is an expression, give it a pass for now + if ($name instanceof Expr) { + return; + } + + if (!\method_exists($class, $name) && !\method_exists($class, '__callStatic')) { + throw $this->createError(\sprintf('Call to undefined method %s::%s()', $class, $name), $stmt); + } + } + + /** + * Ensure that a referenced interface exists. + * + * @throws FatalErrorException + * + * @param Interface_[] $interfaces + * @param Stmt $stmt + */ + protected function ensureInterfacesExist(array $interfaces, Stmt $stmt) + { + foreach ($interfaces as $interface) { + /** @var string $name */ + $name = $this->getFullyQualifiedName($interface); + if (!$this->interfaceExists($name)) { + throw $this->createError(\sprintf('Interface \'%s\' not found', $name), $stmt); + } + } + } + + /** + * Check whether a class exists, or has been defined in the current code snippet. + * + * Gives `self`, `static` and `parent` a free pass. + * + * @param string $name + */ + protected function classExists(string $name): bool + { + // Give `self`, `static` and `parent` a pass. This will actually let + // some errors through, since we're not checking whether the keyword is + // being used in a class scope. + if (\in_array(\strtolower($name), ['self', 'static', 'parent'])) { + return true; + } + + return \class_exists($name) || $this->findInScope($name) === self::CLASS_TYPE; + } + + /** + * Check whether an interface exists, or has been defined in the current code snippet. + * + * @param string $name + */ + protected function interfaceExists(string $name): bool + { + return \interface_exists($name) || $this->findInScope($name) === self::INTERFACE_TYPE; + } + + /** + * Check whether a trait exists, or has been defined in the current code snippet. + * + * @param string $name + */ + protected function traitExists(string $name): bool + { + return \trait_exists($name) || $this->findInScope($name) === self::TRAIT_TYPE; + } + + /** + * Find a symbol in the current code snippet scope. + * + * @param string $name + * + * @return string|null + */ + protected function findInScope(string $name) + { + $name = \strtolower($name); + if (isset($this->currentScope[$name])) { + return $this->currentScope[$name]; + } + } + + /** + * Error creation factory. + * + * @param string $msg + * @param Stmt $stmt + */ + protected function createError(string $msg, Stmt $stmt): FatalErrorException + { + return new FatalErrorException($msg, 0, \E_ERROR, null, $stmt->getStartLine()); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidConstructorPass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidConstructorPass.php new file mode 100644 index 0000000..481de6f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidConstructorPass.php @@ -0,0 +1,121 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\Node\Stmt\Namespace_; +use Psy\Exception\FatalErrorException; + +/** + * Validate that the constructor method is not static, and does not have a + * return type. + * + * Checks both explicit __construct methods as well as old-style constructor + * methods with the same name as the class (for non-namespaced classes). + * + * As of PHP 5.3.3, methods with the same name as the last element of a + * namespaced class name will no longer be treated as constructor. This change + * doesn't affect non-namespaced classes. + * + * @author Martin Hasoň <martin.hason@gmail.com> + */ +class ValidConstructorPass extends CodeCleanerPass +{ + private $namespace; + + /** + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->namespace = []; + } + + /** + * Validate that the constructor is not static and does not have a return type. + * + * @throws FatalErrorException the constructor function is static + * @throws FatalErrorException the constructor function has a return type + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof Namespace_) { + $this->namespace = isset($node->name) ? $this->getParts($node->name) : []; + } elseif ($node instanceof Class_) { + $constructor = null; + foreach ($node->stmts as $stmt) { + if ($stmt instanceof ClassMethod) { + // If we find a new-style constructor, no need to look for the old-style + if ('__construct' === \strtolower($stmt->name)) { + $this->validateConstructor($stmt, $node); + + return; + } + + // We found a possible old-style constructor (unless there is also a __construct method) + if (empty($this->namespace) && \strtolower($node->name) === \strtolower($stmt->name)) { + $constructor = $stmt; + } + } + } + + if ($constructor) { + $this->validateConstructor($constructor, $node); + } + } + } + + /** + * @throws FatalErrorException the constructor function is static + * @throws FatalErrorException the constructor function has a return type + * + * @param Node $constructor + * @param Node $classNode + */ + private function validateConstructor(Node $constructor, Node $classNode) + { + if ($constructor->isStatic()) { + $msg = \sprintf( + 'Constructor %s::%s() cannot be static', + \implode('\\', \array_merge($this->namespace, (array) $classNode->name->toString())), + $constructor->name + ); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $classNode->getStartLine()); + } + + if (\method_exists($constructor, 'getReturnType') && $constructor->getReturnType()) { + $msg = \sprintf( + 'Constructor %s::%s() cannot declare a return type', + \implode('\\', \array_merge($this->namespace, (array) $classNode->name->toString())), + $constructor->name + ); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $classNode->getStartLine()); + } + } + + /** + * Backwards compatibility shim for PHP-Parser 4.x. + * + * At some point we might want to make $namespace a plain string, to match how Name works? + */ + protected function getParts(Name $name): array + { + return \method_exists($name, 'getParts') ? $name->getParts() : $name->parts; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidFunctionNamePass.php b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidFunctionNamePass.php new file mode 100644 index 0000000..bd20607 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/CodeCleaner/ValidFunctionNamePass.php @@ -0,0 +1,83 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\CodeCleaner; + +use PhpParser\Node; +use PhpParser\Node\Stmt\Do_; +use PhpParser\Node\Stmt\Function_; +use PhpParser\Node\Stmt\If_; +use PhpParser\Node\Stmt\Switch_; +use PhpParser\Node\Stmt\While_; +use Psy\Exception\FatalErrorException; + +/** + * Validate that function calls will succeed. + * + * This pass throws a FatalErrorException rather than letting PHP run + * headfirst into a real fatal error and die. + */ +class ValidFunctionNamePass extends NamespaceAwarePass +{ + private $conditionalScopes = 0; + + /** + * Store newly defined function names on the way in, to allow recursion. + * + * @throws FatalErrorException if a function is redefined in a non-conditional scope + * + * @param Node $node + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + parent::enterNode($node); + + if (self::isConditional($node)) { + $this->conditionalScopes++; + } elseif ($node instanceof Function_) { + $name = $this->getFullyQualifiedName($node->name); + + // @todo add an "else" here which adds a runtime check for instances where we can't tell + // whether a function is being redefined by static analysis alone. + if ($this->conditionalScopes === 0) { + if (\function_exists($name) || + isset($this->currentScope[\strtolower($name)])) { + $msg = \sprintf('Cannot redeclare %s()', $name); + throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getStartLine()); + } + } + + $this->currentScope[\strtolower($name)] = true; + } + } + + /** + * @param Node $node + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if (self::isConditional($node)) { + $this->conditionalScopes--; + } + } + + private static function isConditional(Node $node) + { + return $node instanceof If_ || + $node instanceof While_ || + $node instanceof Do_ || + $node instanceof Switch_; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/BufferCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/BufferCommand.php new file mode 100644 index 0000000..8348aee --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/BufferCommand.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Exception\RuntimeException; +use Psy\Output\ShellOutput; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Interact with the current code buffer. + * + * Shows and clears the buffer for the current multi-line expression. + */ +class BufferCommand extends Command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('buffer') + ->setAliases(['buf']) + ->setDefinition([ + new InputOption('clear', '', InputOption::VALUE_NONE, 'Clear the current buffer.'), + ]) + ->setDescription('Show (or clear) the contents of the code input buffer.') + ->setHelp( + <<<'HELP' +Show the contents of the code buffer for the current multi-line expression. + +Optionally, clear the buffer by passing the <info>--clear</info> option. +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $app = $this->getApplication(); + if (!$app instanceof \Psy\Shell) { + throw new RuntimeException('Buffer command requires a \Psy\Shell application'); + } + + $buf = $app->getCodeBuffer(); + if ($input->getOption('clear')) { + $app->resetCodeBuffer(); + $output->writeln($this->formatLines($buf, 'urgent'), ShellOutput::NUMBER_LINES); + } else { + $output->writeln($this->formatLines($buf), ShellOutput::NUMBER_LINES); + } + + return 0; + } + + /** + * A helper method for wrapping buffer lines in `<urgent>` and `<return>` formatter strings. + * + * @param array $lines + * @param string $type (default: 'return') + * + * @return array Formatted strings + */ + protected function formatLines(array $lines, string $type = 'return'): array + { + $template = \sprintf('<%s>%%s</%s>', $type, $type); + + return \array_map(function ($line) use ($template) { + return \sprintf($template, $line); + }, $lines); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ClearCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ClearCommand.php new file mode 100644 index 0000000..42a66b0 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ClearCommand.php @@ -0,0 +1,53 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Clear the Psy Shell. + * + * Just what it says on the tin. + */ +class ClearCommand extends Command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('clear') + ->setDefinition([]) + ->setDescription('Clear the Psy Shell screen.') + ->setHelp( + <<<'HELP' +Clear the Psy Shell screen. + +Pro Tip: If your PHP has readline support, you should be able to use ctrl+l too! +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $output->write(\sprintf('%c[2J%c[0;0f', 27, 27)); + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/CodeArgumentParser.php b/php/libraries/composer/vendor/psy/psysh/src/Command/CodeArgumentParser.php new file mode 100644 index 0000000..4803aec --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/CodeArgumentParser.php @@ -0,0 +1,59 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use PhpParser\Parser; +use Psy\Exception\ParseErrorException; +use Psy\ParserFactory; + +/** + * Class CodeArgumentParser. + */ +class CodeArgumentParser +{ + private $parser; + + public function __construct(Parser $parser = null) + { + $this->parser = $parser ?? (new ParserFactory())->createParser(); + } + + /** + * Lex and parse a string of code into statements. + * + * This is intended for code arguments, so the code string *should not* start with <?php + * + * @throws ParseErrorException + * + * @return array Statements + */ + public function parse(string $code): array + { + $code = '<?php '.$code; + + try { + return $this->parser->parse($code); + } catch (\PhpParser\Error $e) { + if (\strpos($e->getMessage(), 'unexpected EOF') === false) { + throw ParseErrorException::fromParseError($e); + } + + // If we got an unexpected EOF, let's try it again with a semicolon. + try { + return $this->parser->parse($code.';'); + } catch (\PhpParser\Error $_e) { + // Throw the original error, not the semicolon one. + throw ParseErrorException::fromParseError($e); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/Command.php b/php/libraries/composer/vendor/psy/psysh/src/Command/Command.php new file mode 100644 index 0000000..0d18d2c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/Command.php @@ -0,0 +1,256 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Shell; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command as BaseCommand; +use Symfony\Component\Console\Helper\Table; +use Symfony\Component\Console\Helper\TableStyle; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * The Psy Shell base command. + */ +abstract class Command extends BaseCommand +{ + /** + * Sets the application instance for this command. + * + * @param Application|null $application An Application instance + * + * @api + */ + public function setApplication(Application $application = null): void + { + if ($application !== null && !$application instanceof Shell) { + throw new \InvalidArgumentException('PsySH Commands require an instance of Psy\Shell'); + } + + parent::setApplication($application); + } + + /** + * {@inheritdoc} + */ + public function asText(): string + { + $messages = [ + '<comment>Usage:</comment>', + ' '.$this->getSynopsis(), + '', + ]; + + if ($this->getAliases()) { + $messages[] = $this->aliasesAsText(); + } + + if ($this->getArguments()) { + $messages[] = $this->argumentsAsText(); + } + + if ($this->getOptions()) { + $messages[] = $this->optionsAsText(); + } + + if ($help = $this->getProcessedHelp()) { + $messages[] = '<comment>Help:</comment>'; + $messages[] = ' '.\str_replace("\n", "\n ", $help)."\n"; + } + + return \implode("\n", $messages); + } + + /** + * {@inheritdoc} + */ + private function getArguments(): array + { + $hidden = $this->getHiddenArguments(); + + return \array_filter($this->getNativeDefinition()->getArguments(), function ($argument) use ($hidden) { + return !\in_array($argument->getName(), $hidden); + }); + } + + /** + * These arguments will be excluded from help output. + * + * @return string[] + */ + protected function getHiddenArguments(): array + { + return ['command']; + } + + /** + * {@inheritdoc} + */ + private function getOptions(): array + { + $hidden = $this->getHiddenOptions(); + + return \array_filter($this->getNativeDefinition()->getOptions(), function ($option) use ($hidden) { + return !\in_array($option->getName(), $hidden); + }); + } + + /** + * These options will be excluded from help output. + * + * @return string[] + */ + protected function getHiddenOptions(): array + { + return ['verbose']; + } + + /** + * Format command aliases as text.. + */ + private function aliasesAsText(): string + { + return '<comment>Aliases:</comment> <info>'.\implode(', ', $this->getAliases()).'</info>'.\PHP_EOL; + } + + /** + * Format command arguments as text. + */ + private function argumentsAsText(): string + { + $max = $this->getMaxWidth(); + $messages = []; + + $arguments = $this->getArguments(); + if (!empty($arguments)) { + $messages[] = '<comment>Arguments:</comment>'; + foreach ($arguments as $argument) { + if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) { + $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault())); + } else { + $default = ''; + } + + $description = \str_replace("\n", "\n".\str_pad('', $max + 2, ' '), $argument->getDescription()); + + $messages[] = \sprintf(" <info>%-{$max}s</info> %s%s", $argument->getName(), $description, $default); + } + + $messages[] = ''; + } + + return \implode(\PHP_EOL, $messages); + } + + /** + * Format options as text. + */ + private function optionsAsText(): string + { + $max = $this->getMaxWidth(); + $messages = []; + + $options = $this->getOptions(); + if ($options) { + $messages[] = '<comment>Options:</comment>'; + + foreach ($options as $option) { + if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) { + $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault())); + } else { + $default = ''; + } + + $multiple = $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''; + $description = \str_replace("\n", "\n".\str_pad('', $max + 2, ' '), $option->getDescription()); + + $optionMax = $max - \strlen($option->getName()) - 2; + $messages[] = \sprintf( + " <info>%s</info> %-{$optionMax}s%s%s%s", + '--'.$option->getName(), + $option->getShortcut() ? \sprintf('(-%s) ', $option->getShortcut()) : '', + $description, + $default, + $multiple + ); + } + + $messages[] = ''; + } + + return \implode(\PHP_EOL, $messages); + } + + /** + * Calculate the maximum padding width for a set of lines. + */ + private function getMaxWidth(): int + { + $max = 0; + + foreach ($this->getOptions() as $option) { + $nameLength = \strlen($option->getName()) + 2; + if ($option->getShortcut()) { + $nameLength += \strlen($option->getShortcut()) + 3; + } + + $max = \max($max, $nameLength); + } + + foreach ($this->getArguments() as $argument) { + $max = \max($max, \strlen($argument->getName())); + } + + return ++$max; + } + + /** + * Format an option default as text. + * + * @param mixed $default + */ + private function formatDefaultValue($default): string + { + if (\is_array($default) && $default === \array_values($default)) { + return \sprintf("['%s']", \implode("', '", $default)); + } + + return \str_replace("\n", '', \var_export($default, true)); + } + + /** + * Get a Table instance. + * + * @return Table + */ + protected function getTable(OutputInterface $output) + { + $style = new TableStyle(); + + // Symfony 4.1 deprecated single-argument style setters. + if (\method_exists($style, 'setVerticalBorderChars')) { + $style->setVerticalBorderChars(' '); + $style->setHorizontalBorderChars(''); + $style->setCrossingChars('', '', '', '', '', '', '', '', ''); + } else { + $style->setVerticalBorderChar(' '); + $style->setHorizontalBorderChar(''); + $style->setCrossingChar(''); + } + + $table = new Table($output); + + return $table + ->setRows([]) + ->setStyle($style); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/DocCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/DocCommand.php new file mode 100644 index 0000000..1650ccf --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/DocCommand.php @@ -0,0 +1,252 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Formatter\DocblockFormatter; +use Psy\Formatter\SignatureFormatter; +use Psy\Input\CodeArgument; +use Psy\Output\ShellOutput; +use Psy\Reflection\ReflectionConstant; +use Psy\Reflection\ReflectionLanguageConstruct; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Read the documentation for an object, class, constant, method or property. + */ +class DocCommand extends ReflectingCommand +{ + const INHERIT_DOC_TAG = '{@inheritdoc}'; + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('doc') + ->setAliases(['rtfm', 'man']) + ->setDefinition([ + new InputOption('all', 'a', InputOption::VALUE_NONE, 'Show documentation for superclasses as well as the current class.'), + new CodeArgument('target', CodeArgument::REQUIRED, 'Function, class, instance, constant, method or property to document.'), + ]) + ->setDescription('Read the documentation for an object, class, constant, method or property.') + ->setHelp( + <<<HELP +Read the documentation for an object, class, constant, method or property. + +It's awesome for well-documented code, not quite as awesome for poorly documented code. + +e.g. +<return>>>> doc preg_replace</return> +<return>>>> doc Psy\Shell</return> +<return>>>> doc Psy\Shell::debug</return> +<return>>>> \$s = new Psy\Shell</return> +<return>>>> doc \$s->run</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $value = $input->getArgument('target'); + if (ReflectionLanguageConstruct::isLanguageConstruct($value)) { + $reflector = new ReflectionLanguageConstruct($value); + $doc = $this->getManualDocById($value); + } else { + list($target, $reflector) = $this->getTargetAndReflector($value); + $doc = $this->getManualDoc($reflector) ?: DocblockFormatter::format($reflector); + } + + $db = $this->getApplication()->getManualDb(); + + if ($output instanceof ShellOutput) { + $output->startPaging(); + } + + // Maybe include the declaring class + if ($reflector instanceof \ReflectionMethod || $reflector instanceof \ReflectionProperty) { + $output->writeln(SignatureFormatter::format($reflector->getDeclaringClass())); + } + + $output->writeln(SignatureFormatter::format($reflector)); + $output->writeln(''); + + if (empty($doc) && !$db) { + $output->writeln('<warning>PHP manual not found</warning>'); + $output->writeln(' To document core PHP functionality, download the PHP reference manual:'); + $output->writeln(' https://github.com/bobthecow/psysh/wiki/PHP-manual'); + } else { + $output->writeln($doc); + } + + // Implicit --all if the original docblock has an {@inheritdoc} tag. + if ($input->getOption('all') || \stripos($doc, self::INHERIT_DOC_TAG) !== false) { + $parent = $reflector; + foreach ($this->getParentReflectors($reflector) as $parent) { + $output->writeln(''); + $output->writeln('---'); + $output->writeln(''); + + // Maybe include the declaring class + if ($parent instanceof \ReflectionMethod || $parent instanceof \ReflectionProperty) { + $output->writeln(SignatureFormatter::format($parent->getDeclaringClass())); + } + + $output->writeln(SignatureFormatter::format($parent)); + $output->writeln(''); + + if ($doc = $this->getManualDoc($parent) ?: DocblockFormatter::format($parent)) { + $output->writeln($doc); + } + } + } + + if ($output instanceof ShellOutput) { + $output->stopPaging(); + } + + // Set some magic local variables + $this->setCommandScopeVariables($reflector); + + return 0; + } + + private function getManualDoc($reflector) + { + switch (\get_class($reflector)) { + case \ReflectionClass::class: + case \ReflectionObject::class: + case \ReflectionFunction::class: + $id = $reflector->name; + break; + + case \ReflectionMethod::class: + $id = $reflector->class.'::'.$reflector->name; + break; + + case \ReflectionProperty::class: + $id = $reflector->class.'::$'.$reflector->name; + break; + + case \ReflectionClassConstant::class: + // @todo this is going to collide with ReflectionMethod ids + // someday... start running the query by id + type if the DB + // supports it. + $id = $reflector->class.'::'.$reflector->name; + break; + + case ReflectionConstant::class: + $id = $reflector->name; + break; + + default: + return false; + } + + return $this->getManualDocById($id); + } + + /** + * Get all all parent Reflectors for a given Reflector. + * + * For example, passing a Class, Object or TraitReflector will yield all + * traits and parent classes. Passing a Method or PropertyReflector will + * yield Reflectors for the same-named method or property on all traits and + * parent classes. + * + * @return \Generator a whole bunch of \Reflector instances + */ + private function getParentReflectors($reflector): \Generator + { + $seenClasses = []; + + switch (\get_class($reflector)) { + case \ReflectionClass::class: + case \ReflectionObject::class: + foreach ($reflector->getTraits() as $trait) { + if (!\in_array($trait->getName(), $seenClasses)) { + $seenClasses[] = $trait->getName(); + yield $trait; + } + } + + foreach ($reflector->getInterfaces() as $interface) { + if (!\in_array($interface->getName(), $seenClasses)) { + $seenClasses[] = $interface->getName(); + yield $interface; + } + } + + while ($reflector = $reflector->getParentClass()) { + yield $reflector; + + foreach ($reflector->getTraits() as $trait) { + if (!\in_array($trait->getName(), $seenClasses)) { + $seenClasses[] = $trait->getName(); + yield $trait; + } + } + + foreach ($reflector->getInterfaces() as $interface) { + if (!\in_array($interface->getName(), $seenClasses)) { + $seenClasses[] = $interface->getName(); + yield $interface; + } + } + } + + return; + + case \ReflectionMethod::class: + foreach ($this->getParentReflectors($reflector->getDeclaringClass()) as $parent) { + if ($parent->hasMethod($reflector->getName())) { + $parentMethod = $parent->getMethod($reflector->getName()); + if (!\in_array($parentMethod->getDeclaringClass()->getName(), $seenClasses)) { + $seenClasses[] = $parentMethod->getDeclaringClass()->getName(); + yield $parentMethod; + } + } + } + + return; + + case \ReflectionProperty::class: + foreach ($this->getParentReflectors($reflector->getDeclaringClass()) as $parent) { + if ($parent->hasProperty($reflector->getName())) { + $parentProperty = $parent->getProperty($reflector->getName()); + if (!\in_array($parentProperty->getDeclaringClass()->getName(), $seenClasses)) { + $seenClasses[] = $parentProperty->getDeclaringClass()->getName(); + yield $parentProperty; + } + } + } + break; + } + } + + private function getManualDocById($id) + { + if ($db = $this->getApplication()->getManualDb()) { + $result = $db->query(\sprintf('SELECT doc FROM php_manual WHERE id = %s', $db->quote($id))); + if ($result !== false) { + return $result->fetchColumn(0); + } + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/DumpCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/DumpCommand.php new file mode 100644 index 0000000..88ddbe2 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/DumpCommand.php @@ -0,0 +1,84 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Input\CodeArgument; +use Psy\VarDumper\Presenter; +use Psy\VarDumper\PresenterAware; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Dump an object or primitive. + * + * This is like var_dump but *way* awesomer. + */ +class DumpCommand extends ReflectingCommand implements PresenterAware +{ + private $presenter; + + /** + * PresenterAware interface. + * + * @param Presenter $presenter + */ + public function setPresenter(Presenter $presenter) + { + $this->presenter = $presenter; + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('dump') + ->setDefinition([ + new CodeArgument('target', CodeArgument::REQUIRED, 'A target object or primitive to dump.'), + new InputOption('depth', '', InputOption::VALUE_REQUIRED, 'Depth to parse.', 10), + new InputOption('all', 'a', InputOption::VALUE_NONE, 'Include private and protected methods and properties.'), + ]) + ->setDescription('Dump an object or primitive.') + ->setHelp( + <<<'HELP' +Dump an object or primitive. + +This is like var_dump but <strong>way</strong> awesomer. + +e.g. +<return>>>> dump $_</return> +<return>>>> dump $someVar</return> +<return>>>> dump $stuff->getAll()</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $depth = $input->getOption('depth'); + $target = $this->resolveCode($input->getArgument('target')); + $output->page($this->presenter->present($target, $depth, $input->getOption('all') ? Presenter::VERBOSE : 0)); + + if (\is_object($target)) { + $this->setCommandScopeVariables(new \ReflectionObject($target)); + } + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/EditCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/EditCommand.php new file mode 100644 index 0000000..7612b3d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/EditCommand.php @@ -0,0 +1,188 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Context; +use Psy\ContextAware; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +class EditCommand extends Command implements ContextAware +{ + /** + * @var string + */ + private $runtimeDir = ''; + + /** + * @var Context + */ + private $context; + + /** + * Constructor. + * + * @param string $runtimeDir The directory to use for temporary files + * @param string|null $name The name of the command; passing null means it must be set in configure() + * + * @throws \Symfony\Component\Console\Exception\LogicException When the command name is empty + */ + public function __construct($runtimeDir, $name = null) + { + parent::__construct($name); + + $this->runtimeDir = $runtimeDir; + } + + protected function configure() + { + $this + ->setName('edit') + ->setDefinition([ + new InputArgument('file', InputArgument::OPTIONAL, 'The file to open for editing. If this is not given, edits a temporary file.', null), + new InputOption( + 'exec', + 'e', + InputOption::VALUE_NONE, + 'Execute the file content after editing. This is the default when a file name argument is not given.', + null + ), + new InputOption( + 'no-exec', + 'E', + InputOption::VALUE_NONE, + 'Do not execute the file content after editing. This is the default when a file name argument is given.', + null + ), + ]) + ->setDescription('Open an external editor. Afterwards, get produced code in input buffer.') + ->setHelp('Set the EDITOR environment variable to something you\'d like to use.'); + } + + /** + * @param InputInterface $input + * @param OutputInterface $output + * + * @return int 0 if everything went fine, or an exit code + * + * @throws \InvalidArgumentException when both exec and no-exec flags are given or if a given variable is not found in the current context + * @throws \UnexpectedValueException if file_get_contents on the edited file returns false instead of a string + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + if ($input->getOption('exec') && + $input->getOption('no-exec')) { + throw new \InvalidArgumentException('The --exec and --no-exec flags are mutually exclusive'); + } + + $filePath = $this->extractFilePath($input->getArgument('file')); + + $execute = $this->shouldExecuteFile( + $input->getOption('exec'), + $input->getOption('no-exec'), + $filePath + ); + + $shouldRemoveFile = false; + + if ($filePath === null) { + $filePath = \tempnam($this->runtimeDir, 'psysh-edit-command'); + $shouldRemoveFile = true; + } + + $editedContent = $this->editFile($filePath, $shouldRemoveFile); + + if ($execute) { + $this->getApplication()->addInput($editedContent); + } + + return 0; + } + + /** + * @param bool $execOption + * @param bool $noExecOption + * @param string|null $filePath + */ + private function shouldExecuteFile(bool $execOption, bool $noExecOption, string $filePath = null): bool + { + if ($execOption) { + return true; + } + + if ($noExecOption) { + return false; + } + + // By default, code that is edited is executed if there was no given input file path + return $filePath === null; + } + + /** + * @param string|null $fileArgument + * + * @return string|null The file path to edit, null if the input was null, or the value of the referenced variable + * + * @throws \InvalidArgumentException If the variable is not found in the current context + */ + private function extractFilePath(string $fileArgument = null) + { + // If the file argument was a variable, get it from the context + if ($fileArgument !== null && + $fileArgument !== '' && + $fileArgument[0] === '$') { + $fileArgument = $this->context->get(\preg_replace('/^\$/', '', $fileArgument)); + } + + return $fileArgument; + } + + /** + * @param string $filePath + * @param bool $shouldRemoveFile + * + * @throws \UnexpectedValueException if file_get_contents on $filePath returns false instead of a string + */ + private function editFile(string $filePath, bool $shouldRemoveFile): string + { + $escapedFilePath = \escapeshellarg($filePath); + $editor = (isset($_SERVER['EDITOR']) && $_SERVER['EDITOR']) ? $_SERVER['EDITOR'] : 'nano'; + + $pipes = []; + $proc = \proc_open("{$editor} {$escapedFilePath}", [\STDIN, \STDOUT, \STDERR], $pipes); + \proc_close($proc); + + $editedContent = @\file_get_contents($filePath); + + if ($shouldRemoveFile) { + @\unlink($filePath); + } + + if ($editedContent === false) { + throw new \UnexpectedValueException("Reading {$filePath} returned false"); + } + + return $editedContent; + } + + /** + * Set the Context reference. + * + * @param Context $context + */ + public function setContext(Context $context) + { + $this->context = $context; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ExitCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ExitCommand.php new file mode 100644 index 0000000..6552e28 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ExitCommand.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Exception\BreakException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Exit the Psy Shell. + * + * Just what it says on the tin. + */ +class ExitCommand extends Command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('exit') + ->setAliases(['quit', 'q']) + ->setDefinition([]) + ->setDescription('End the current session and return to caller.') + ->setHelp( + <<<'HELP' +End the current session and return to caller. + +e.g. +<return>>>> exit</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + throw new BreakException('Goodbye'); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/HelpCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/HelpCommand.php new file mode 100644 index 0000000..13ea348 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/HelpCommand.php @@ -0,0 +1,104 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Output\ShellOutput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Help command. + * + * Lists available commands, and gives command-specific help when asked nicely. + */ +class HelpCommand extends Command +{ + private $command; + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('help') + ->setAliases(['?']) + ->setDefinition([ + new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name.', null), + ]) + ->setDescription('Show a list of commands. Type `help [foo]` for information about [foo].') + ->setHelp('My. How meta.'); + } + + /** + * Helper for setting a subcommand to retrieve help for. + * + * @param Command $command + */ + public function setCommand(Command $command) + { + $this->command = $command; + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + if ($this->command !== null) { + // help for an individual command + $output->page($this->command->asText()); + $this->command = null; + } elseif ($name = $input->getArgument('command_name')) { + // help for an individual command + $output->page($this->getApplication()->get($name)->asText()); + } else { + // list available commands + $commands = $this->getApplication()->all(); + + $table = $this->getTable($output); + + foreach ($commands as $name => $command) { + if ($name !== $command->getName()) { + continue; + } + + if ($command->getAliases()) { + $aliases = \sprintf('<comment>Aliases:</comment> %s', \implode(', ', $command->getAliases())); + } else { + $aliases = ''; + } + + $table->addRow([ + \sprintf('<info>%s</info>', $name), + $command->getDescription(), + $aliases, + ]); + } + + if ($output instanceof ShellOutput) { + $output->startPaging(); + } + + $table->render(); + + if ($output instanceof ShellOutput) { + $output->stopPaging(); + } + } + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/HistoryCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/HistoryCommand.php new file mode 100644 index 0000000..cf5f29b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/HistoryCommand.php @@ -0,0 +1,250 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Input\FilterOptions; +use Psy\Output\ShellOutput; +use Psy\Readline\Readline; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Psy Shell history command. + * + * Shows, searches and replays readline history. Not too shabby. + */ +class HistoryCommand extends Command +{ + private $filter; + private $readline; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->filter = new FilterOptions(); + + parent::__construct($name); + } + + /** + * Set the Shell's Readline service. + * + * @param Readline $readline + */ + public function setReadline(Readline $readline) + { + $this->readline = $readline; + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + list($grep, $insensitive, $invert) = FilterOptions::getOptions(); + + $this + ->setName('history') + ->setAliases(['hist']) + ->setDefinition([ + new InputOption('show', 's', InputOption::VALUE_REQUIRED, 'Show the given range of lines.'), + new InputOption('head', 'H', InputOption::VALUE_REQUIRED, 'Display the first N items.'), + new InputOption('tail', 'T', InputOption::VALUE_REQUIRED, 'Display the last N items.'), + + $grep, + $insensitive, + $invert, + + new InputOption('no-numbers', 'N', InputOption::VALUE_NONE, 'Omit line numbers.'), + + new InputOption('save', '', InputOption::VALUE_REQUIRED, 'Save history to a file.'), + new InputOption('replay', '', InputOption::VALUE_NONE, 'Replay.'), + new InputOption('clear', '', InputOption::VALUE_NONE, 'Clear the history.'), + ]) + ->setDescription('Show the Psy Shell history.') + ->setHelp( + <<<'HELP' +Show, search, save or replay the Psy Shell history. + +e.g. +<return>>>> history --grep /[bB]acon/</return> +<return>>>> history --show 0..10 --replay</return> +<return>>>> history --clear</return> +<return>>>> history --tail 1000 --save somefile.txt</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->validateOnlyOne($input, ['show', 'head', 'tail']); + $this->validateOnlyOne($input, ['save', 'replay', 'clear']); + + $history = $this->getHistorySlice( + $input->getOption('show'), + $input->getOption('head'), + $input->getOption('tail') + ); + $highlighted = false; + + $this->filter->bind($input); + if ($this->filter->hasFilter()) { + $matches = []; + $highlighted = []; + foreach ($history as $i => $line) { + if ($this->filter->match($line, $matches)) { + if (isset($matches[0])) { + $chunks = \explode($matches[0], $history[$i]); + $chunks = \array_map([__CLASS__, 'escape'], $chunks); + $glue = \sprintf('<urgent>%s</urgent>', self::escape($matches[0])); + + $highlighted[$i] = \implode($glue, $chunks); + } + } else { + unset($history[$i]); + } + } + } + + if ($save = $input->getOption('save')) { + $output->writeln(\sprintf('Saving history in %s...', $save)); + \file_put_contents($save, \implode(\PHP_EOL, $history).\PHP_EOL); + $output->writeln('<info>History saved.</info>'); + } elseif ($input->getOption('replay')) { + if (!($input->getOption('show') || $input->getOption('head') || $input->getOption('tail'))) { + throw new \InvalidArgumentException('You must limit history via --head, --tail or --show before replaying'); + } + + $count = \count($history); + $output->writeln(\sprintf('Replaying %d line%s of history', $count, ($count !== 1) ? 's' : '')); + $this->getApplication()->addInput($history); + } elseif ($input->getOption('clear')) { + $this->clearHistory(); + $output->writeln('<info>History cleared.</info>'); + } else { + $type = $input->getOption('no-numbers') ? 0 : ShellOutput::NUMBER_LINES; + if (!$highlighted) { + $type = $type | OutputInterface::OUTPUT_RAW; + } + + $output->page($highlighted ?: $history, $type); + } + + return 0; + } + + /** + * Extract a range from a string. + * + * @param string $range + * + * @return array [ start, end ] + */ + private function extractRange(string $range): array + { + if (\preg_match('/^\d+$/', $range)) { + return [$range, $range + 1]; + } + + $matches = []; + if ($range !== '..' && \preg_match('/^(\d*)\.\.(\d*)$/', $range, $matches)) { + $start = $matches[1] ? (int) $matches[1] : 0; + $end = $matches[2] ? (int) $matches[2] + 1 : \PHP_INT_MAX; + + return [$start, $end]; + } + + throw new \InvalidArgumentException('Unexpected range: '.$range); + } + + /** + * Retrieve a slice of the readline history. + * + * @param string|null $show + * @param string|null $head + * @param string|null $tail + * + * @return array A slice of history + */ + private function getHistorySlice($show, $head, $tail): array + { + $history = $this->readline->listHistory(); + + // don't show the current `history` invocation + \array_pop($history); + + if ($show) { + list($start, $end) = $this->extractRange($show); + $length = $end - $start; + } elseif ($head) { + if (!\preg_match('/^\d+$/', $head)) { + throw new \InvalidArgumentException('Please specify an integer argument for --head'); + } + + $start = 0; + $length = (int) $head; + } elseif ($tail) { + if (!\preg_match('/^\d+$/', $tail)) { + throw new \InvalidArgumentException('Please specify an integer argument for --tail'); + } + + $start = \count($history) - $tail; + $length = (int) $tail + 1; + } else { + return $history; + } + + return \array_slice($history, $start, $length, true); + } + + /** + * Validate that only one of the given $options is set. + * + * @param InputInterface $input + * @param array $options + */ + private function validateOnlyOne(InputInterface $input, array $options) + { + $count = 0; + foreach ($options as $opt) { + if ($input->getOption($opt)) { + $count++; + } + } + + if ($count > 1) { + throw new \InvalidArgumentException('Please specify only one of --'.\implode(', --', $options)); + } + } + + /** + * Clear the readline history. + */ + private function clearHistory() + { + $this->readline->clearHistory(); + } + + public static function escape(string $string): string + { + return OutputFormatter::escape($string); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand.php new file mode 100644 index 0000000..1982aa4 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand.php @@ -0,0 +1,275 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Command\ListCommand\ClassConstantEnumerator; +use Psy\Command\ListCommand\ClassEnumerator; +use Psy\Command\ListCommand\ConstantEnumerator; +use Psy\Command\ListCommand\FunctionEnumerator; +use Psy\Command\ListCommand\GlobalVariableEnumerator; +use Psy\Command\ListCommand\MethodEnumerator; +use Psy\Command\ListCommand\PropertyEnumerator; +use Psy\Command\ListCommand\VariableEnumerator; +use Psy\Exception\RuntimeException; +use Psy\Input\CodeArgument; +use Psy\Input\FilterOptions; +use Psy\Output\ShellOutput; +use Psy\VarDumper\Presenter; +use Psy\VarDumper\PresenterAware; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * List available local variables, object properties, etc. + */ +class ListCommand extends ReflectingCommand implements PresenterAware +{ + protected $presenter; + protected $enumerators; + + /** + * PresenterAware interface. + * + * @param Presenter $presenter + */ + public function setPresenter(Presenter $presenter) + { + $this->presenter = $presenter; + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + list($grep, $insensitive, $invert) = FilterOptions::getOptions(); + + $this + ->setName('ls') + ->setAliases(['dir']) + ->setDefinition([ + new CodeArgument('target', CodeArgument::OPTIONAL, 'A target class or object to list.'), + + new InputOption('vars', '', InputOption::VALUE_NONE, 'Display variables.'), + new InputOption('constants', 'c', InputOption::VALUE_NONE, 'Display defined constants.'), + new InputOption('functions', 'f', InputOption::VALUE_NONE, 'Display defined functions.'), + new InputOption('classes', 'k', InputOption::VALUE_NONE, 'Display declared classes.'), + new InputOption('interfaces', 'I', InputOption::VALUE_NONE, 'Display declared interfaces.'), + new InputOption('traits', 't', InputOption::VALUE_NONE, 'Display declared traits.'), + + new InputOption('no-inherit', '', InputOption::VALUE_NONE, 'Exclude inherited methods, properties and constants.'), + + new InputOption('properties', 'p', InputOption::VALUE_NONE, 'Display class or object properties (public properties by default).'), + new InputOption('methods', 'm', InputOption::VALUE_NONE, 'Display class or object methods (public methods by default).'), + + $grep, + $insensitive, + $invert, + + new InputOption('globals', 'g', InputOption::VALUE_NONE, 'Include global variables.'), + new InputOption('internal', 'n', InputOption::VALUE_NONE, 'Limit to internal functions and classes.'), + new InputOption('user', 'u', InputOption::VALUE_NONE, 'Limit to user-defined constants, functions and classes.'), + new InputOption('category', 'C', InputOption::VALUE_REQUIRED, 'Limit to constants in a specific category (e.g. "date").'), + + new InputOption('all', 'a', InputOption::VALUE_NONE, 'Include private and protected methods and properties.'), + new InputOption('long', 'l', InputOption::VALUE_NONE, 'List in long format: includes class names and method signatures.'), + ]) + ->setDescription('List local, instance or class variables, methods and constants.') + ->setHelp( + <<<'HELP' +List variables, constants, classes, interfaces, traits, functions, methods, +and properties. + +Called without options, this will return a list of variables currently in scope. + +If a target object is provided, list properties, constants and methods of that +target. If a class, interface or trait name is passed instead, list constants +and methods on that class. + +e.g. +<return>>>> ls</return> +<return>>>> ls $foo</return> +<return>>>> ls -k --grep mongo -i</return> +<return>>>> ls -al ReflectionClass</return> +<return>>>> ls --constants --category date</return> +<return>>>> ls -l --functions --grep /^array_.*/</return> +<return>>>> ls -l --properties new DateTime()</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->validateInput($input); + $this->initEnumerators(); + + $method = $input->getOption('long') ? 'writeLong' : 'write'; + + if ($target = $input->getArgument('target')) { + list($target, $reflector) = $this->getTargetAndReflector($target); + } else { + $reflector = null; + } + + // @todo something cleaner than this :-/ + if ($output instanceof ShellOutput && $input->getOption('long')) { + $output->startPaging(); + } + + foreach ($this->enumerators as $enumerator) { + $this->$method($output, $enumerator->enumerate($input, $reflector, $target)); + } + + if ($output instanceof ShellOutput && $input->getOption('long')) { + $output->stopPaging(); + } + + // Set some magic local variables + if ($reflector !== null) { + $this->setCommandScopeVariables($reflector); + } + + return 0; + } + + /** + * Initialize Enumerators. + */ + protected function initEnumerators() + { + if (!isset($this->enumerators)) { + $mgr = $this->presenter; + + $this->enumerators = [ + new ClassConstantEnumerator($mgr), + new ClassEnumerator($mgr), + new ConstantEnumerator($mgr), + new FunctionEnumerator($mgr), + new GlobalVariableEnumerator($mgr), + new PropertyEnumerator($mgr), + new MethodEnumerator($mgr), + new VariableEnumerator($mgr, $this->context), + ]; + } + } + + /** + * Write the list items to $output. + * + * @param OutputInterface $output + * @param array $result List of enumerated items + */ + protected function write(OutputInterface $output, array $result) + { + if (\count($result) === 0) { + return; + } + + foreach ($result as $label => $items) { + $names = \array_map([$this, 'formatItemName'], $items); + $output->writeln(\sprintf('<strong>%s</strong>: %s', $label, \implode(', ', $names))); + } + } + + /** + * Write the list items to $output. + * + * Items are listed one per line, and include the item signature. + * + * @param OutputInterface $output + * @param array $result List of enumerated items + */ + protected function writeLong(OutputInterface $output, array $result) + { + if (\count($result) === 0) { + return; + } + + $table = $this->getTable($output); + + foreach ($result as $label => $items) { + $output->writeln(''); + $output->writeln(\sprintf('<strong>%s:</strong>', $label)); + + $table->setRows([]); + foreach ($items as $item) { + $table->addRow([$this->formatItemName($item), $item['value']]); + } + + $table->render(); + } + } + + /** + * Format an item name given its visibility. + * + * @param array $item + */ + private function formatItemName(array $item): string + { + return \sprintf('<%s>%s</%s>', $item['style'], OutputFormatter::escape($item['name']), $item['style']); + } + + /** + * Validate that input options make sense, provide defaults when called without options. + * + * @throws RuntimeException if options are inconsistent + * + * @param InputInterface $input + */ + private function validateInput(InputInterface $input) + { + if (!$input->getArgument('target')) { + // if no target is passed, there can be no properties or methods + foreach (['properties', 'methods', 'no-inherit'] as $option) { + if ($input->getOption($option)) { + throw new RuntimeException('--'.$option.' does not make sense without a specified target'); + } + } + + foreach (['globals', 'vars', 'constants', 'functions', 'classes', 'interfaces', 'traits'] as $option) { + if ($input->getOption($option)) { + return; + } + } + + // default to --vars if no other options are passed + $input->setOption('vars', true); + } else { + // if a target is passed, classes, functions, etc don't make sense + foreach (['vars', 'globals'] as $option) { + if ($input->getOption($option)) { + throw new RuntimeException('--'.$option.' does not make sense with a specified target'); + } + } + + // @todo ensure that 'functions', 'classes', 'interfaces', 'traits' only accept namespace target? + foreach (['constants', 'properties', 'methods', 'functions', 'classes', 'interfaces', 'traits'] as $option) { + if ($input->getOption($option)) { + return; + } + } + + // default to --constants --properties --methods if no other options are passed + $input->setOption('constants', true); + $input->setOption('properties', true); + $input->setOption('methods', true); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ClassConstantEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ClassConstantEnumerator.php new file mode 100644 index 0000000..803a02e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ClassConstantEnumerator.php @@ -0,0 +1,121 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Symfony\Component\Console\Input\InputInterface; + +/** + * Class Constant Enumerator class. + */ +class ClassConstantEnumerator extends Enumerator +{ + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // only list constants when a Reflector is present. + if ($reflector === null) { + return []; + } + + // We can only list constants on actual class (or object) reflectors. + if (!$reflector instanceof \ReflectionClass) { + // @todo handle ReflectionExtension as well + return []; + } + + // only list constants if we are specifically asked + if (!$input->getOption('constants')) { + return []; + } + + $noInherit = $input->getOption('no-inherit'); + $constants = $this->prepareConstants($this->getConstants($reflector, $noInherit)); + + if (empty($constants)) { + return []; + } + + $ret = []; + $ret[$this->getKindLabel($reflector)] = $constants; + + return $ret; + } + + /** + * Get defined constants for the given class or object Reflector. + * + * @param \ReflectionClass $reflector + * @param bool $noInherit Exclude inherited constants + * + * @return array + */ + protected function getConstants(\ReflectionClass $reflector, bool $noInherit = false): array + { + $className = $reflector->getName(); + + $constants = []; + foreach ($reflector->getConstants() as $name => $constant) { + $constReflector = new \ReflectionClassConstant($reflector->name, $name); + + if ($noInherit && $constReflector->getDeclaringClass()->getName() !== $className) { + continue; + } + + $constants[$name] = $constReflector; + } + + \ksort($constants, \SORT_NATURAL | \SORT_FLAG_CASE); + + return $constants; + } + + /** + * Prepare formatted constant array. + * + * @param array $constants + * + * @return array + */ + protected function prepareConstants(array $constants): array + { + // My kingdom for a generator. + $ret = []; + + foreach ($constants as $name => $constant) { + if ($this->showItem($name)) { + $ret[$name] = [ + 'name' => $name, + 'style' => self::IS_CONSTANT, + 'value' => $this->presentRef($constant->getValue()), + ]; + } + } + + return $ret; + } + + /** + * Get a label for the particular kind of "class" represented. + * + * @param \ReflectionClass $reflector + */ + protected function getKindLabel(\ReflectionClass $reflector): string + { + if ($reflector->isInterface()) { + return 'Interface Constants'; + } else { + return 'Class Constants'; + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ClassEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ClassEnumerator.php new file mode 100644 index 0000000..cf80ba7 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ClassEnumerator.php @@ -0,0 +1,132 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Psy\Reflection\ReflectionNamespace; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Class Enumerator class. + */ +class ClassEnumerator extends Enumerator +{ + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // if we have a reflector, ensure that it's a namespace reflector + if (($target !== null || $reflector !== null) && !$reflector instanceof ReflectionNamespace) { + return []; + } + + $internal = $input->getOption('internal'); + $user = $input->getOption('user'); + $prefix = $reflector === null ? null : \strtolower($reflector->getName()).'\\'; + + $ret = []; + + // only list classes, interfaces and traits if we are specifically asked + + if ($input->getOption('classes')) { + $ret = \array_merge($ret, $this->filterClasses('Classes', \get_declared_classes(), $internal, $user, $prefix)); + } + + if ($input->getOption('interfaces')) { + $ret = \array_merge($ret, $this->filterClasses('Interfaces', \get_declared_interfaces(), $internal, $user, $prefix)); + } + + if ($input->getOption('traits')) { + $ret = \array_merge($ret, $this->filterClasses('Traits', \get_declared_traits(), $internal, $user, $prefix)); + } + + return \array_map([$this, 'prepareClasses'], \array_filter($ret)); + } + + /** + * Filter a list of classes, interfaces or traits. + * + * If $internal or $user is defined, results will be limited to internal or + * user-defined classes as appropriate. + * + * @param string $key + * @param array $classes + * @param bool $internal + * @param bool $user + * @param string $prefix + * + * @return array + */ + protected function filterClasses(string $key, array $classes, bool $internal, bool $user, string $prefix = null): array + { + $ret = []; + + if ($internal) { + $ret['Internal '.$key] = \array_filter($classes, function ($class) use ($prefix) { + if ($prefix !== null && \strpos(\strtolower($class), $prefix) !== 0) { + return false; + } + + $refl = new \ReflectionClass($class); + + return $refl->isInternal(); + }); + } + + if ($user) { + $ret['User '.$key] = \array_filter($classes, function ($class) use ($prefix) { + if ($prefix !== null && \strpos(\strtolower($class), $prefix) !== 0) { + return false; + } + + $refl = new \ReflectionClass($class); + + return !$refl->isInternal(); + }); + } + + if (!$user && !$internal) { + $ret[$key] = \array_filter($classes, function ($class) use ($prefix) { + return $prefix === null || \strpos(\strtolower($class), $prefix) === 0; + }); + } + + return $ret; + } + + /** + * Prepare formatted class array. + * + * @param array $classes + * + * @return array + */ + protected function prepareClasses(array $classes): array + { + \natcasesort($classes); + + // My kingdom for a generator. + $ret = []; + + foreach ($classes as $name) { + if ($this->showItem($name)) { + $ret[$name] = [ + 'name' => $name, + 'style' => self::IS_CLASS, + 'value' => $this->presentSignature($name), + ]; + } + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ConstantEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ConstantEnumerator.php new file mode 100644 index 0000000..c8346e9 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/ConstantEnumerator.php @@ -0,0 +1,175 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Psy\Reflection\ReflectionNamespace; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Constant Enumerator class. + */ +class ConstantEnumerator extends Enumerator +{ + // Because `Json` is ugly. + private static $categoryLabels = [ + 'libxml' => 'libxml', + 'openssl' => 'OpenSSL', + 'pcre' => 'PCRE', + 'sqlite3' => 'SQLite3', + 'curl' => 'cURL', + 'dom' => 'DOM', + 'ftp' => 'FTP', + 'gd' => 'GD', + 'gmp' => 'GMP', + 'iconv' => 'iconv', + 'json' => 'JSON', + 'ldap' => 'LDAP', + 'mbstring' => 'mbstring', + 'odbc' => 'ODBC', + 'pcntl' => 'PCNTL', + 'pgsql' => 'pgsql', + 'posix' => 'POSIX', + 'mysqli' => 'mysqli', + 'soap' => 'SOAP', + 'exif' => 'EXIF', + 'sysvmsg' => 'sysvmsg', + 'xml' => 'XML', + 'xsl' => 'XSL', + ]; + + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // if we have a reflector, ensure that it's a namespace reflector + if (($target !== null || $reflector !== null) && !$reflector instanceof ReflectionNamespace) { + return []; + } + + // only list constants if we are specifically asked + if (!$input->getOption('constants')) { + return []; + } + + $user = $input->getOption('user'); + $internal = $input->getOption('internal'); + $category = $input->getOption('category'); + + if ($category) { + $category = \strtolower($category); + + if ($category === 'internal') { + $internal = true; + $category = null; + } elseif ($category === 'user') { + $user = true; + $category = null; + } + } + + $ret = []; + + if ($user) { + $ret['User Constants'] = $this->getConstants('user'); + } + + if ($internal) { + $ret['Internal Constants'] = $this->getConstants('internal'); + } + + if ($category) { + $caseCategory = \array_key_exists($category, self::$categoryLabels) ? self::$categoryLabels[$category] : \ucfirst($category); + $label = $caseCategory.' Constants'; + $ret[$label] = $this->getConstants($category); + } + + if (!$user && !$internal && !$category) { + $ret['Constants'] = $this->getConstants(); + } + + if ($reflector !== null) { + $prefix = \strtolower($reflector->getName()).'\\'; + + foreach ($ret as $key => $names) { + foreach (\array_keys($names) as $name) { + if (\strpos(\strtolower($name), $prefix) !== 0) { + unset($ret[$key][$name]); + } + } + } + } + + return \array_map([$this, 'prepareConstants'], \array_filter($ret)); + } + + /** + * Get defined constants. + * + * Optionally restrict constants to a given category, e.g. "date". If the + * category is "internal", include all non-user-defined constants. + * + * @param string $category + * + * @return array + */ + protected function getConstants(string $category = null): array + { + if (!$category) { + return \get_defined_constants(); + } + + $consts = \get_defined_constants(true); + + if ($category === 'internal') { + unset($consts['user']); + + return \array_merge(...\array_values($consts)); + } + + foreach ($consts as $key => $value) { + if (\strtolower($key) === $category) { + return $value; + } + } + + return []; + } + + /** + * Prepare formatted constant array. + * + * @param array $constants + * + * @return array + */ + protected function prepareConstants(array $constants): array + { + // My kingdom for a generator. + $ret = []; + + $names = \array_keys($constants); + \natcasesort($names); + + foreach ($names as $name) { + if ($this->showItem($name)) { + $ret[$name] = [ + 'name' => $name, + 'style' => self::IS_CONSTANT, + 'value' => $this->presentRef($constants[$name]), + ]; + } + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/Enumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/Enumerator.php new file mode 100644 index 0000000..ecc4613 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/Enumerator.php @@ -0,0 +1,106 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Psy\Formatter\SignatureFormatter; +use Psy\Input\FilterOptions; +use Psy\Util\Mirror; +use Psy\VarDumper\Presenter; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Abstract Enumerator class. + */ +abstract class Enumerator +{ + // Output styles + const IS_PUBLIC = 'public'; + const IS_PROTECTED = 'protected'; + const IS_PRIVATE = 'private'; + const IS_GLOBAL = 'global'; + const IS_CONSTANT = 'const'; + const IS_CLASS = 'class'; + const IS_FUNCTION = 'function'; + + private $filter; + private $presenter; + + /** + * Enumerator constructor. + * + * @param Presenter $presenter + */ + public function __construct(Presenter $presenter) + { + $this->filter = new FilterOptions(); + $this->presenter = $presenter; + } + + /** + * Return a list of categorized things with the given input options and target. + * + * @param InputInterface $input + * @param \Reflector|null $reflector + * @param mixed $target + * + * @return array + */ + public function enumerate(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + $this->filter->bind($input); + + return $this->listItems($input, $reflector, $target); + } + + /** + * Enumerate specific items with the given input options and target. + * + * Implementing classes should return an array of arrays: + * + * [ + * 'Constants' => [ + * 'FOO' => [ + * 'name' => 'FOO', + * 'style' => 'public', + * 'value' => '123', + * ], + * ], + * ] + * + * @param InputInterface $input + * @param \Reflector|null $reflector + * @param mixed $target + * + * @return array + */ + abstract protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array; + + protected function showItem($name) + { + return $this->filter->match($name); + } + + protected function presentRef($value) + { + return $this->presenter->presentRef($value); + } + + protected function presentSignature($target) + { + // This might get weird if the signature is actually for a reflector. Hrm. + if (!$target instanceof \Reflector) { + $target = Mirror::get($target); + } + + return SignatureFormatter::format($target); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/FunctionEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/FunctionEnumerator.php new file mode 100644 index 0000000..beccb4b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/FunctionEnumerator.php @@ -0,0 +1,116 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Psy\Reflection\ReflectionNamespace; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Function Enumerator class. + */ +class FunctionEnumerator extends Enumerator +{ + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // if we have a reflector, ensure that it's a namespace reflector + if (($target !== null || $reflector !== null) && !$reflector instanceof ReflectionNamespace) { + return []; + } + + // only list functions if we are specifically asked + if (!$input->getOption('functions')) { + return []; + } + + if ($input->getOption('user')) { + $label = 'User Functions'; + $functions = $this->getFunctions('user'); + } elseif ($input->getOption('internal')) { + $label = 'Internal Functions'; + $functions = $this->getFunctions('internal'); + } else { + $label = 'Functions'; + $functions = $this->getFunctions(); + } + + $prefix = $reflector === null ? null : \strtolower($reflector->getName()).'\\'; + $functions = $this->prepareFunctions($functions, $prefix); + + if (empty($functions)) { + return []; + } + + $ret = []; + $ret[$label] = $functions; + + return $ret; + } + + /** + * Get defined functions. + * + * Optionally limit functions to "user" or "internal" functions. + * + * @param string|null $type "user" or "internal" (default: both) + * + * @return array + */ + protected function getFunctions(string $type = null): array + { + $funcs = \get_defined_functions(); + + if ($type) { + return $funcs[$type]; + } else { + return \array_merge($funcs['internal'], $funcs['user']); + } + } + + /** + * Prepare formatted function array. + * + * @param array $functions + * @param string $prefix + * + * @return array + */ + protected function prepareFunctions(array $functions, string $prefix = null): array + { + \natcasesort($functions); + + // My kingdom for a generator. + $ret = []; + + foreach ($functions as $name) { + if ($prefix !== null && \strpos(\strtolower($name), $prefix) !== 0) { + continue; + } + + if ($this->showItem($name)) { + try { + $ret[$name] = [ + 'name' => $name, + 'style' => self::IS_FUNCTION, + 'value' => $this->presentSignature($name), + ]; + } catch (\Throwable $e) { + // Ignore failures. + } + } + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/GlobalVariableEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/GlobalVariableEnumerator.php new file mode 100644 index 0000000..fab5970 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/GlobalVariableEnumerator.php @@ -0,0 +1,92 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Symfony\Component\Console\Input\InputInterface; + +/** + * Global Variable Enumerator class. + */ +class GlobalVariableEnumerator extends Enumerator +{ + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // only list globals when no Reflector is present. + if ($reflector !== null || $target !== null) { + return []; + } + + // only list globals if we are specifically asked + if (!$input->getOption('globals')) { + return []; + } + + $globals = $this->prepareGlobals($this->getGlobals()); + + if (empty($globals)) { + return []; + } + + return [ + 'Global Variables' => $globals, + ]; + } + + /** + * Get defined global variables. + * + * @return array + */ + protected function getGlobals(): array + { + global $GLOBALS; + + $names = \array_keys($GLOBALS); + \natcasesort($names); + + $ret = []; + foreach ($names as $name) { + $ret[$name] = $GLOBALS[$name]; + } + + return $ret; + } + + /** + * Prepare formatted global variable array. + * + * @param array $globals + * + * @return array + */ + protected function prepareGlobals(array $globals): array + { + // My kingdom for a generator. + $ret = []; + + foreach ($globals as $name => $value) { + if ($this->showItem($name)) { + $fname = '$'.$name; + $ret[$fname] = [ + 'name' => $fname, + 'style' => self::IS_GLOBAL, + 'value' => $this->presentRef($value), + ]; + } + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/MethodEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/MethodEnumerator.php new file mode 100644 index 0000000..68c74dd --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/MethodEnumerator.php @@ -0,0 +1,142 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Symfony\Component\Console\Input\InputInterface; + +/** + * Method Enumerator class. + */ +class MethodEnumerator extends Enumerator +{ + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // only list methods when a Reflector is present. + if ($reflector === null) { + return []; + } + + // We can only list methods on actual class (or object) reflectors. + if (!$reflector instanceof \ReflectionClass) { + return []; + } + + // only list methods if we are specifically asked + if (!$input->getOption('methods')) { + return []; + } + + $showAll = $input->getOption('all'); + $noInherit = $input->getOption('no-inherit'); + $methods = $this->prepareMethods($this->getMethods($showAll, $reflector, $noInherit)); + + if (empty($methods)) { + return []; + } + + $ret = []; + $ret[$this->getKindLabel($reflector)] = $methods; + + return $ret; + } + + /** + * Get defined methods for the given class or object Reflector. + * + * @param bool $showAll Include private and protected methods + * @param \ReflectionClass $reflector + * @param bool $noInherit Exclude inherited methods + * + * @return array + */ + protected function getMethods(bool $showAll, \ReflectionClass $reflector, bool $noInherit = false): array + { + $className = $reflector->getName(); + + $methods = []; + foreach ($reflector->getMethods() as $name => $method) { + // For some reason PHP reflection shows private methods from the parent class, even + // though they're effectively worthless. Let's suppress them here, like --no-inherit + if (($noInherit || $method->isPrivate()) && $method->getDeclaringClass()->getName() !== $className) { + continue; + } + + if ($showAll || $method->isPublic()) { + $methods[$method->getName()] = $method; + } + } + + \ksort($methods, \SORT_NATURAL | \SORT_FLAG_CASE); + + return $methods; + } + + /** + * Prepare formatted method array. + * + * @param array $methods + * + * @return array + */ + protected function prepareMethods(array $methods): array + { + // My kingdom for a generator. + $ret = []; + + foreach ($methods as $name => $method) { + if ($this->showItem($name)) { + $ret[$name] = [ + 'name' => $name, + 'style' => $this->getVisibilityStyle($method), + 'value' => $this->presentSignature($method), + ]; + } + } + + return $ret; + } + + /** + * Get a label for the particular kind of "class" represented. + * + * @param \ReflectionClass $reflector + */ + protected function getKindLabel(\ReflectionClass $reflector): string + { + if ($reflector->isInterface()) { + return 'Interface Methods'; + } elseif (\method_exists($reflector, 'isTrait') && $reflector->isTrait()) { + return 'Trait Methods'; + } else { + return 'Class Methods'; + } + } + + /** + * Get output style for the given method's visibility. + * + * @param \ReflectionMethod $method + */ + private function getVisibilityStyle(\ReflectionMethod $method): string + { + if ($method->isPublic()) { + return self::IS_PUBLIC; + } elseif ($method->isProtected()) { + return self::IS_PROTECTED; + } else { + return self::IS_PRIVATE; + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/PropertyEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/PropertyEnumerator.php new file mode 100644 index 0000000..dfde8ea --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/PropertyEnumerator.php @@ -0,0 +1,176 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Symfony\Component\Console\Input\InputInterface; + +/** + * Property Enumerator class. + */ +class PropertyEnumerator extends Enumerator +{ + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // only list properties when a Reflector is present. + + if ($reflector === null) { + return []; + } + + // We can only list properties on actual class (or object) reflectors. + if (!$reflector instanceof \ReflectionClass) { + return []; + } + + // only list properties if we are specifically asked + if (!$input->getOption('properties')) { + return []; + } + + $showAll = $input->getOption('all'); + $noInherit = $input->getOption('no-inherit'); + $properties = $this->prepareProperties($this->getProperties($showAll, $reflector, $noInherit), $target); + + if (empty($properties)) { + return []; + } + + $ret = []; + $ret[$this->getKindLabel($reflector)] = $properties; + + return $ret; + } + + /** + * Get defined properties for the given class or object Reflector. + * + * @param bool $showAll Include private and protected properties + * @param \ReflectionClass $reflector + * @param bool $noInherit Exclude inherited properties + * + * @return array + */ + protected function getProperties(bool $showAll, \ReflectionClass $reflector, bool $noInherit = false): array + { + $className = $reflector->getName(); + + $properties = []; + foreach ($reflector->getProperties() as $property) { + if ($noInherit && $property->getDeclaringClass()->getName() !== $className) { + continue; + } + + if ($showAll || $property->isPublic()) { + $properties[$property->getName()] = $property; + } + } + + \ksort($properties, \SORT_NATURAL | \SORT_FLAG_CASE); + + return $properties; + } + + /** + * Prepare formatted property array. + * + * @param array $properties + * + * @return array + */ + protected function prepareProperties(array $properties, $target = null): array + { + // My kingdom for a generator. + $ret = []; + + foreach ($properties as $name => $property) { + if ($this->showItem($name)) { + $fname = '$'.$name; + $ret[$fname] = [ + 'name' => $fname, + 'style' => $this->getVisibilityStyle($property), + 'value' => $this->presentValue($property, $target), + ]; + } + } + + return $ret; + } + + /** + * Get a label for the particular kind of "class" represented. + * + * @param \ReflectionClass $reflector + */ + protected function getKindLabel(\ReflectionClass $reflector): string + { + if (\method_exists($reflector, 'isTrait') && $reflector->isTrait()) { + return 'Trait Properties'; + } else { + return 'Class Properties'; + } + } + + /** + * Get output style for the given property's visibility. + * + * @param \ReflectionProperty $property + */ + private function getVisibilityStyle(\ReflectionProperty $property): string + { + if ($property->isPublic()) { + return self::IS_PUBLIC; + } elseif ($property->isProtected()) { + return self::IS_PROTECTED; + } else { + return self::IS_PRIVATE; + } + } + + /** + * Present the $target's current value for a reflection property. + * + * @param \ReflectionProperty $property + * @param mixed $target + */ + protected function presentValue(\ReflectionProperty $property, $target): string + { + if (!$target) { + return ''; + } + + // If $target is a class or trait (try to) get the default + // value for the property. + if (!\is_object($target)) { + try { + $refl = new \ReflectionClass($target); + $props = $refl->getDefaultProperties(); + if (\array_key_exists($property->name, $props)) { + $suffix = $property->isStatic() ? '' : ' <aside>(default)</aside>'; + + return $this->presentRef($props[$property->name]).$suffix; + } + } catch (\Throwable $e) { + // Well, we gave it a shot. + } + + return ''; + } + + $property->setAccessible(true); + $value = $property->getValue($target); + + return $this->presentRef($value); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/VariableEnumerator.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/VariableEnumerator.php new file mode 100644 index 0000000..38f3f60 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ListCommand/VariableEnumerator.php @@ -0,0 +1,137 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\ListCommand; + +use Psy\Context; +use Psy\VarDumper\Presenter; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Variable Enumerator class. + */ +class VariableEnumerator extends Enumerator +{ + // n.b. this array is the order in which special variables will be listed + private static $specialNames = [ + '_', '_e', '__out', '__function', '__method', '__class', '__namespace', '__file', '__line', '__dir', + ]; + + private $context; + + /** + * Variable Enumerator constructor. + * + * Unlike most other enumerators, the Variable Enumerator needs access to + * the current scope variables, so we need to pass it a Context instance. + * + * @param Presenter $presenter + * @param Context $context + */ + public function __construct(Presenter $presenter, Context $context) + { + $this->context = $context; + parent::__construct($presenter); + } + + /** + * {@inheritdoc} + */ + protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null): array + { + // only list variables when no Reflector is present. + if ($reflector !== null || $target !== null) { + return []; + } + + // only list variables if we are specifically asked + if (!$input->getOption('vars')) { + return []; + } + + $showAll = $input->getOption('all'); + $variables = $this->prepareVariables($this->getVariables($showAll)); + + if (empty($variables)) { + return []; + } + + return [ + 'Variables' => $variables, + ]; + } + + /** + * Get scope variables. + * + * @param bool $showAll Include special variables (e.g. $_) + * + * @return array + */ + protected function getVariables(bool $showAll): array + { + $scopeVars = $this->context->getAll(); + \uksort($scopeVars, function ($a, $b) { + $aIndex = \array_search($a, self::$specialNames); + $bIndex = \array_search($b, self::$specialNames); + + if ($aIndex !== false) { + if ($bIndex !== false) { + return $aIndex - $bIndex; + } + + return 1; + } + + if ($bIndex !== false) { + return -1; + } + + return \strnatcasecmp($a, $b); + }); + + $ret = []; + foreach ($scopeVars as $name => $val) { + if (!$showAll && \in_array($name, self::$specialNames)) { + continue; + } + + $ret[$name] = $val; + } + + return $ret; + } + + /** + * Prepare formatted variable array. + * + * @param array $variables + * + * @return array + */ + protected function prepareVariables(array $variables): array + { + // My kingdom for a generator. + $ret = []; + foreach ($variables as $name => $val) { + if ($this->showItem($name)) { + $fname = '$'.$name; + $ret[$fname] = [ + 'name' => $fname, + 'style' => \in_array($name, self::$specialNames) ? self::IS_PRIVATE : self::IS_PUBLIC, + 'value' => $this->presentRef($val), + ]; + } + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ParseCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ParseCommand.php new file mode 100644 index 0000000..d97c751 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ParseCommand.php @@ -0,0 +1,127 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use PhpParser\Node; +use Psy\Context; +use Psy\ContextAware; +use Psy\Input\CodeArgument; +use Psy\ParserFactory; +use Psy\VarDumper\Presenter; +use Psy\VarDumper\PresenterAware; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\VarDumper\Caster\Caster; + +/** + * Parse PHP code and show the abstract syntax tree. + */ +class ParseCommand extends Command implements ContextAware, PresenterAware +{ + /** + * Context instance (for ContextAware interface). + * + * @var Context + */ + protected $context; + + private $presenter; + private $parser; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->parser = (new ParserFactory())->createParser(); + + parent::__construct($name); + } + + /** + * ContextAware interface. + * + * @param Context $context + */ + public function setContext(Context $context) + { + $this->context = $context; + } + + /** + * PresenterAware interface. + * + * @param Presenter $presenter + */ + public function setPresenter(Presenter $presenter) + { + $this->presenter = clone $presenter; + $this->presenter->addCasters([ + Node::class => function (Node $node, array $a) { + $a = [ + Caster::PREFIX_VIRTUAL.'type' => $node->getType(), + Caster::PREFIX_VIRTUAL.'attributes' => $node->getAttributes(), + ]; + + foreach ($node->getSubNodeNames() as $name) { + $a[Caster::PREFIX_VIRTUAL.$name] = $node->$name; + } + + return $a; + }, + ]); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('parse') + ->setDefinition([ + new CodeArgument('code', CodeArgument::REQUIRED, 'PHP code to parse.'), + new InputOption('depth', '', InputOption::VALUE_REQUIRED, 'Depth to parse.', 10), + ]) + ->setDescription('Parse PHP code and show the abstract syntax tree.') + ->setHelp( + <<<'HELP' +Parse PHP code and show the abstract syntax tree. + +This command is used in the development of PsySH. Given a string of PHP code, +it pretty-prints the PHP Parser parse tree. + +See https://github.com/nikic/PHP-Parser + +It prolly won't be super useful for most of you, but it's here if you want to play. +HELP + ); + } + + /** + * {@inheritdoc} + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $code = $input->getArgument('code'); + $parserKind = $input->getOption('kind'); + $depth = $input->getOption('depth'); + + $nodes = $this->parser->parse($code); + $output->page($this->presenter->present($nodes, $depth)); + + $this->context->setReturnValue($nodes); + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/PsyVersionCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/PsyVersionCommand.php new file mode 100644 index 0000000..959a9a7 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/PsyVersionCommand.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * A dumb little command for printing out the current Psy Shell version. + */ +class PsyVersionCommand extends Command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('version') + ->setDefinition([]) + ->setDescription('Show Psy Shell version.') + ->setHelp('Show Psy Shell version.'); + } + + /** + * {@inheritdoc} + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $output->writeln($this->getApplication()->getVersion()); + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ReflectingCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ReflectingCommand.php new file mode 100644 index 0000000..55b9fbf --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ReflectingCommand.php @@ -0,0 +1,331 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use PhpParser\NodeTraverser; +use PhpParser\PrettyPrinter\Standard as Printer; +use Psy\CodeCleaner\NoReturnValue; +use Psy\Context; +use Psy\ContextAware; +use Psy\Exception\ErrorException; +use Psy\Exception\RuntimeException; +use Psy\Exception\UnexpectedTargetException; +use Psy\Reflection\ReflectionConstant; +use Psy\Sudo\SudoVisitor; +use Psy\Util\Mirror; + +/** + * An abstract command with helpers for inspecting the current context. + */ +abstract class ReflectingCommand extends Command implements ContextAware +{ + const CLASS_OR_FUNC = '/^[\\\\\w]+$/'; + const CLASS_MEMBER = '/^([\\\\\w]+)::(\w+)$/'; + const CLASS_STATIC = '/^([\\\\\w]+)::\$(\w+)$/'; + const INSTANCE_MEMBER = '/^(\$\w+)(::|->)(\w+)$/'; + + /** + * Context instance (for ContextAware interface). + * + * @var Context + */ + protected $context; + + private $parser; + private $traverser; + private $printer; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->parser = new CodeArgumentParser(); + + $this->traverser = new NodeTraverser(); + $this->traverser->addVisitor(new SudoVisitor()); + + $this->printer = new Printer(); + + parent::__construct($name); + } + + /** + * ContextAware interface. + * + * @param Context $context + */ + public function setContext(Context $context) + { + $this->context = $context; + } + + /** + * Get the target for a value. + * + * @throws \InvalidArgumentException when the value specified can't be resolved + * + * @param string $valueName Function, class, variable, constant, method or property name + * + * @return array (class or instance name, member name, kind) + */ + protected function getTarget(string $valueName): array + { + $valueName = \trim($valueName); + $matches = []; + switch (true) { + case \preg_match(self::CLASS_OR_FUNC, $valueName, $matches): + return [$this->resolveName($matches[0], true), null, 0]; + + case \preg_match(self::CLASS_MEMBER, $valueName, $matches): + return [$this->resolveName($matches[1]), $matches[2], Mirror::CONSTANT | Mirror::METHOD]; + + case \preg_match(self::CLASS_STATIC, $valueName, $matches): + return [$this->resolveName($matches[1]), $matches[2], Mirror::STATIC_PROPERTY | Mirror::PROPERTY]; + + case \preg_match(self::INSTANCE_MEMBER, $valueName, $matches): + if ($matches[2] === '->') { + $kind = Mirror::METHOD | Mirror::PROPERTY; + } else { + $kind = Mirror::CONSTANT | Mirror::METHOD; + } + + return [$this->resolveObject($matches[1]), $matches[3], $kind]; + + default: + return [$this->resolveObject($valueName), null, 0]; + } + } + + /** + * Resolve a class or function name (with the current shell namespace). + * + * @throws ErrorException when `self` or `static` is used in a non-class scope + * + * @param string $name + * @param bool $includeFunctions (default: false) + */ + protected function resolveName(string $name, bool $includeFunctions = false): string + { + $shell = $this->getApplication(); + + // While not *technically* 100% accurate, let's treat `self` and `static` as equivalent. + if (\in_array(\strtolower($name), ['self', 'static'])) { + if ($boundClass = $shell->getBoundClass()) { + return $boundClass; + } + + if ($boundObject = $shell->getBoundObject()) { + return \get_class($boundObject); + } + + $msg = \sprintf('Cannot use "%s" when no class scope is active', \strtolower($name)); + throw new ErrorException($msg, 0, \E_USER_ERROR, "eval()'d code", 1); + } + + if (\substr($name, 0, 1) === '\\') { + return $name; + } + + // Check $name against the current namespace and use statements. + if (self::couldBeClassName($name)) { + try { + $name = $this->resolveCode($name.'::class'); + } catch (RuntimeException $e) { + // /shrug + } + } + + if ($namespace = $shell->getNamespace()) { + $fullName = $namespace.'\\'.$name; + + if (\class_exists($fullName) || \interface_exists($fullName) || ($includeFunctions && \function_exists($fullName))) { + return $fullName; + } + } + + return $name; + } + + /** + * Check whether a given name could be a class name. + */ + protected function couldBeClassName(string $name): bool + { + // Regex based on https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class + return \preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*(\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$/', $name) === 1; + } + + /** + * Get a Reflector and documentation for a function, class or instance, constant, method or property. + * + * @param string $valueName Function, class, variable, constant, method or property name + * + * @return array (value, Reflector) + */ + protected function getTargetAndReflector(string $valueName): array + { + list($value, $member, $kind) = $this->getTarget($valueName); + + return [$value, Mirror::get($value, $member, $kind)]; + } + + /** + * Resolve code to a value in the current scope. + * + * @throws RuntimeException when the code does not return a value in the current scope + * + * @param string $code + * + * @return mixed Variable value + */ + protected function resolveCode(string $code) + { + try { + // Add an implicit `sudo` to target resolution. + $nodes = $this->traverser->traverse($this->parser->parse($code)); + $sudoCode = $this->printer->prettyPrint($nodes); + $value = $this->getApplication()->execute($sudoCode, true); + } catch (\Throwable $e) { + // Swallow all exceptions? + } + + if (!isset($value) || $value instanceof NoReturnValue) { + throw new RuntimeException('Unknown target: '.$code); + } + + return $value; + } + + /** + * Resolve code to an object in the current scope. + * + * @throws UnexpectedTargetException when the code resolves to a non-object value + * + * @param string $code + * + * @return object Variable instance + */ + private function resolveObject(string $code) + { + $value = $this->resolveCode($code); + + if (!\is_object($value)) { + throw new UnexpectedTargetException($value, 'Unable to inspect a non-object'); + } + + return $value; + } + + /** + * Get a variable from the current shell scope. + * + * @param string $name + * + * @return mixed + */ + protected function getScopeVariable(string $name) + { + return $this->context->get($name); + } + + /** + * Get all scope variables from the current shell scope. + * + * @return array + */ + protected function getScopeVariables(): array + { + return $this->context->getAll(); + } + + /** + * Given a Reflector instance, set command-scope variables in the shell + * execution context. This is used to inject magic $__class, $__method and + * $__file variables (as well as a handful of others). + * + * @param \Reflector $reflector + */ + protected function setCommandScopeVariables(\Reflector $reflector) + { + $vars = []; + + switch (\get_class($reflector)) { + case \ReflectionClass::class: + case \ReflectionObject::class: + $vars['__class'] = $reflector->name; + if ($reflector->inNamespace()) { + $vars['__namespace'] = $reflector->getNamespaceName(); + } + break; + + case \ReflectionMethod::class: + $vars['__method'] = \sprintf('%s::%s', $reflector->class, $reflector->name); + $vars['__class'] = $reflector->class; + $classReflector = $reflector->getDeclaringClass(); + if ($classReflector->inNamespace()) { + $vars['__namespace'] = $classReflector->getNamespaceName(); + } + break; + + case \ReflectionFunction::class: + $vars['__function'] = $reflector->name; + if ($reflector->inNamespace()) { + $vars['__namespace'] = $reflector->getNamespaceName(); + } + break; + + case \ReflectionGenerator::class: + $funcReflector = $reflector->getFunction(); + $vars['__function'] = $funcReflector->name; + if ($funcReflector->inNamespace()) { + $vars['__namespace'] = $funcReflector->getNamespaceName(); + } + if ($fileName = $reflector->getExecutingFile()) { + $vars['__file'] = $fileName; + $vars['__line'] = $reflector->getExecutingLine(); + $vars['__dir'] = \dirname($fileName); + } + break; + + case \ReflectionProperty::class: + case \ReflectionClassConstant::class: + $classReflector = $reflector->getDeclaringClass(); + $vars['__class'] = $classReflector->name; + if ($classReflector->inNamespace()) { + $vars['__namespace'] = $classReflector->getNamespaceName(); + } + // no line for these, but this'll do + if ($fileName = $reflector->getDeclaringClass()->getFileName()) { + $vars['__file'] = $fileName; + $vars['__dir'] = \dirname($fileName); + } + break; + + case ReflectionConstant::class: + if ($reflector->inNamespace()) { + $vars['__namespace'] = $reflector->getNamespaceName(); + } + break; + } + + if ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionFunctionAbstract) { + if ($fileName = $reflector->getFileName()) { + $vars['__file'] = $fileName; + $vars['__line'] = $reflector->getStartLine(); + $vars['__dir'] = \dirname($fileName); + } + } + + $this->context->setCommandScopeVariables($vars); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ShowCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ShowCommand.php new file mode 100644 index 0000000..4d721d7 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ShowCommand.php @@ -0,0 +1,293 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Exception\RuntimeException; +use Psy\Exception\UnexpectedTargetException; +use Psy\Formatter\CodeFormatter; +use Psy\Formatter\SignatureFormatter; +use Psy\Input\CodeArgument; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Show the code for an object, class, constant, method or property. + */ +class ShowCommand extends ReflectingCommand +{ + private $lastException; + private $lastExceptionIndex; + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('show') + ->setDefinition([ + new CodeArgument('target', CodeArgument::OPTIONAL, 'Function, class, instance, constant, method or property to show.'), + new InputOption('ex', null, InputOption::VALUE_OPTIONAL, 'Show last exception context. Optionally specify a stack index.', 1), + ]) + ->setDescription('Show the code for an object, class, constant, method or property.') + ->setHelp( + <<<HELP +Show the code for an object, class, constant, method or property, or the context +of the last exception. + +<return>cat --ex</return> defaults to showing the lines surrounding the location of the last +exception. Invoking it more than once travels up the exception's stack trace, +and providing a number shows the context of the given index of the trace. + +e.g. +<return>>>> show \$myObject</return> +<return>>>> show Psy\Shell::debug</return> +<return>>>> show --ex</return> +<return>>>> show --ex 3</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + // n.b. As far as I can tell, InputInterface doesn't want to tell me + // whether an option with an optional value was actually passed. If you + // call `$input->getOption('ex')`, it will return the default, both when + // `--ex` is specified with no value, and when `--ex` isn't specified at + // all. + // + // So we're doing something sneaky here. If we call `getOptions`, it'll + // return the default value when `--ex` is not present, and `null` if + // `--ex` is passed with no value. /shrug + $opts = $input->getOptions(); + + // Strict comparison to `1` (the default value) here, because `--ex 1` + // will come in as `"1"`. Now we can tell the difference between + // "no --ex present", because it's the integer 1, "--ex with no value", + // because it's `null`, and "--ex 1", because it's the string "1". + if ($opts['ex'] !== 1) { + if ($input->getArgument('target')) { + throw new \InvalidArgumentException('Too many arguments (supply either "target" or "--ex")'); + } + + $this->writeExceptionContext($input, $output); + + return 0; + } + + if ($input->getArgument('target')) { + $this->writeCodeContext($input, $output); + + return 0; + } + + throw new RuntimeException('Not enough arguments (missing: "target")'); + } + + private function writeCodeContext(InputInterface $input, OutputInterface $output) + { + try { + list($target, $reflector) = $this->getTargetAndReflector($input->getArgument('target')); + } catch (UnexpectedTargetException $e) { + // If we didn't get a target and Reflector, maybe we got a filename? + $target = $e->getTarget(); + if (\is_string($target) && \is_file($target) && $code = @\file_get_contents($target)) { + $file = \realpath($target); + if ($file !== $this->context->get('__file')) { + $this->context->setCommandScopeVariables([ + '__file' => $file, + '__dir' => \dirname($file), + ]); + } + + $output->page(CodeFormatter::formatCode($code)); + + return; + } else { + throw $e; + } + } + + // Set some magic local variables + $this->setCommandScopeVariables($reflector); + + try { + $output->page(CodeFormatter::format($reflector)); + } catch (RuntimeException $e) { + $output->writeln(SignatureFormatter::format($reflector)); + throw $e; + } + } + + private function writeExceptionContext(InputInterface $input, OutputInterface $output) + { + $exception = $this->context->getLastException(); + if ($exception !== $this->lastException) { + $this->lastException = null; + $this->lastExceptionIndex = null; + } + + $opts = $input->getOptions(); + if ($opts['ex'] === null) { + if ($this->lastException && $this->lastExceptionIndex !== null) { + $index = $this->lastExceptionIndex + 1; + } else { + $index = 0; + } + } else { + $index = \max(0, (int) $input->getOption('ex') - 1); + } + + $trace = $exception->getTrace(); + \array_unshift($trace, [ + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + ]); + + if ($index >= \count($trace)) { + $index = 0; + } + + $this->lastException = $exception; + $this->lastExceptionIndex = $index; + + $output->writeln($this->getApplication()->formatException($exception)); + $output->writeln('--'); + $this->writeTraceLine($output, $trace, $index); + $this->writeTraceCodeSnippet($output, $trace, $index); + + $this->setCommandScopeVariablesFromContext($trace[$index]); + } + + private function writeTraceLine(OutputInterface $output, array $trace, $index) + { + $file = isset($trace[$index]['file']) ? $this->replaceCwd($trace[$index]['file']) : 'n/a'; + $line = isset($trace[$index]['line']) ? $trace[$index]['line'] : 'n/a'; + + $output->writeln(\sprintf( + 'From <info>%s:%d</info> at <strong>level %d</strong> of backtrace (of %d):', + OutputFormatter::escape($file), + OutputFormatter::escape($line), + $index + 1, + \count($trace) + )); + } + + private function replaceCwd(string $file): string + { + if ($cwd = \getcwd()) { + $cwd = \rtrim($cwd, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR; + } + + if ($cwd === false) { + return $file; + } else { + return \preg_replace('/^'.\preg_quote($cwd, '/').'/', '', $file); + } + } + + private function writeTraceCodeSnippet(OutputInterface $output, array $trace, $index) + { + if (!isset($trace[$index]['file'])) { + return; + } + + $file = $trace[$index]['file']; + if ($fileAndLine = $this->extractEvalFileAndLine($file)) { + list($file, $line) = $fileAndLine; + } else { + if (!isset($trace[$index]['line'])) { + return; + } + + $line = $trace[$index]['line']; + } + + if (\is_file($file)) { + $code = @\file_get_contents($file); + } + + if (empty($code)) { + return; + } + + $startLine = \max($line - 5, 0); + $endLine = $line + 5; + + $output->write(CodeFormatter::formatCode($code, $startLine, $endLine, $line), false); + } + + private function setCommandScopeVariablesFromContext(array $context) + { + $vars = []; + + if (isset($context['class'])) { + $vars['__class'] = $context['class']; + if (isset($context['function'])) { + $vars['__method'] = $context['function']; + } + + try { + $refl = new \ReflectionClass($context['class']); + if ($namespace = $refl->getNamespaceName()) { + $vars['__namespace'] = $namespace; + } + } catch (\Throwable $e) { + // oh well + } + } elseif (isset($context['function'])) { + $vars['__function'] = $context['function']; + + try { + $refl = new \ReflectionFunction($context['function']); + if ($namespace = $refl->getNamespaceName()) { + $vars['__namespace'] = $namespace; + } + } catch (\Throwable $e) { + // oh well + } + } + + if (isset($context['file'])) { + $file = $context['file']; + if ($fileAndLine = $this->extractEvalFileAndLine($file)) { + list($file, $line) = $fileAndLine; + } elseif (isset($context['line'])) { + $line = $context['line']; + } + + if (\is_file($file)) { + $vars['__file'] = $file; + if (isset($line)) { + $vars['__line'] = $line; + } + $vars['__dir'] = \dirname($file); + } + } + + $this->context->setCommandScopeVariables($vars); + } + + private function extractEvalFileAndLine(string $file) + { + if (\preg_match('/(.*)\\((\\d+)\\) : eval\\(\\)\'d code$/', $file, $matches)) { + return [$matches[1], $matches[2]]; + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/SudoCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/SudoCommand.php new file mode 100644 index 0000000..bd08d14 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/SudoCommand.php @@ -0,0 +1,120 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use PhpParser\NodeTraverser; +use PhpParser\PrettyPrinter\Standard as Printer; +use Psy\Input\CodeArgument; +use Psy\Readline\Readline; +use Psy\Sudo\SudoVisitor; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Evaluate PHP code, bypassing visibility restrictions. + */ +class SudoCommand extends Command +{ + private $readline; + private $parser; + private $traverser; + private $printer; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->parser = new CodeArgumentParser(); + + $this->traverser = new NodeTraverser(); + $this->traverser->addVisitor(new SudoVisitor()); + + $this->printer = new Printer(); + + parent::__construct($name); + } + + /** + * Set the Shell's Readline service. + * + * @param Readline $readline + */ + public function setReadline(Readline $readline) + { + $this->readline = $readline; + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('sudo') + ->setDefinition([ + new CodeArgument('code', CodeArgument::REQUIRED, 'Code to execute.'), + ]) + ->setDescription('Evaluate PHP code, bypassing visibility restrictions.') + ->setHelp( + <<<'HELP' +Evaluate PHP code, bypassing visibility restrictions. + +e.g. +<return>>>> $sekret->whisper("hi")</return> +<return>PHP error: Call to private method Sekret::whisper() from context '' on line 1</return> + +<return>>>> sudo $sekret->whisper("hi")</return> +<return>=> "hi"</return> + +<return>>>> $sekret->word</return> +<return>PHP error: Cannot access private property Sekret::$word on line 1</return> + +<return>>>> sudo $sekret->word</return> +<return>=> "hi"</return> + +<return>>>> $sekret->word = "please"</return> +<return>PHP error: Cannot access private property Sekret::$word on line 1</return> + +<return>>>> sudo $sekret->word = "please"</return> +<return>=> "please"</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $code = $input->getArgument('code'); + + // special case for !! + if ($code === '!!') { + $history = $this->readline->listHistory(); + if (\count($history) < 2) { + throw new \InvalidArgumentException('No previous command to replay'); + } + $code = $history[\count($history) - 2]; + } + + $nodes = $this->traverser->traverse($this->parser->parse($code)); + + $sudoCode = $this->printer->prettyPrint($nodes); + $shell = $this->getApplication(); + $shell->addCode($sudoCode, !$shell->hasCode()); + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/ThrowUpCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/ThrowUpCommand.php new file mode 100644 index 0000000..8e59791 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/ThrowUpCommand.php @@ -0,0 +1,126 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use PhpParser\Node\Arg; +use PhpParser\Node\Expr\New_; +use PhpParser\Node\Expr\Throw_; +use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt\Expression; +use PhpParser\PrettyPrinter\Standard as Printer; +use Psy\Exception\ThrowUpException; +use Psy\Input\CodeArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Throw an exception or error out of the Psy Shell. + */ +class ThrowUpCommand extends Command +{ + private $parser; + private $printer; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->parser = new CodeArgumentParser(); + $this->printer = new Printer(); + + parent::__construct($name); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('throw-up') + ->setDefinition([ + new CodeArgument('exception', CodeArgument::OPTIONAL, 'Exception or Error to throw.'), + ]) + ->setDescription('Throw an exception or error out of the Psy Shell.') + ->setHelp( + <<<'HELP' +Throws an exception or error out of the current the Psy Shell instance. + +By default it throws the most recent exception. + +e.g. +<return>>>> throw-up</return> +<return>>>> throw-up $e</return> +<return>>>> throw-up new Exception('WHEEEEEE!')</return> +<return>>>> throw-up "bye!"</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + * + * @throws \InvalidArgumentException if there is no exception to throw + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $args = $this->prepareArgs($input->getArgument('exception')); + $throwStmt = new Expression(new Throw_(new New_(new FullyQualifiedName(ThrowUpException::class), $args))); + $throwCode = $this->printer->prettyPrint([$throwStmt]); + + $shell = $this->getApplication(); + $shell->addCode($throwCode, !$shell->hasCode()); + + return 0; + } + + /** + * Parse the supplied command argument. + * + * If no argument was given, this falls back to `$_e` + * + * @throws \InvalidArgumentException if there is no exception to throw + * + * @param string $code + * + * @return Arg[] + */ + private function prepareArgs(string $code = null): array + { + if (!$code) { + // Default to last exception if nothing else was supplied + return [new Arg(new Variable('_e'))]; + } + + $nodes = $this->parser->parse($code); + if (\count($nodes) !== 1) { + throw new \InvalidArgumentException('No idea how to throw this'); + } + + $node = $nodes[0]; + $expr = $node->expr; + + $args = [new Arg($expr, false, false, $node->getAttributes())]; + + // Allow throwing via a string, e.g. `throw-up "SUP"` + if ($expr instanceof String_) { + return [new New_(new FullyQualifiedName(\Exception::class), $args)]; + } + + return $args; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/TimeitCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/TimeitCommand.php new file mode 100644 index 0000000..3a2efee --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/TimeitCommand.php @@ -0,0 +1,171 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use PhpParser\NodeTraverser; +use PhpParser\PrettyPrinter\Standard as Printer; +use Psy\Command\TimeitCommand\TimeitVisitor; +use Psy\Input\CodeArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Class TimeitCommand. + */ +class TimeitCommand extends Command +{ + const RESULT_MSG = '<info>Command took %.6f seconds to complete.</info>'; + const AVG_RESULT_MSG = '<info>Command took %.6f seconds on average (%.6f median; %.6f total) to complete.</info>'; + + // All times stored as nanoseconds! + private static $start = null; + private static $times = []; + + private $parser; + private $traverser; + private $printer; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->parser = new CodeArgumentParser(); + + $this->traverser = new NodeTraverser(); + $this->traverser->addVisitor(new TimeitVisitor()); + + $this->printer = new Printer(); + + parent::__construct($name); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('timeit') + ->setDefinition([ + new InputOption('num', 'n', InputOption::VALUE_REQUIRED, 'Number of iterations.'), + new CodeArgument('code', CodeArgument::REQUIRED, 'Code to execute.'), + ]) + ->setDescription('Profiles with a timer.') + ->setHelp( + <<<'HELP' +Time profiling for functions and commands. + +e.g. +<return>>>> timeit sleep(1)</return> +<return>>>> timeit -n1000 $closure()</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $code = $input->getArgument('code'); + $num = (int) ($input->getOption('num') ?: 1); + $shell = $this->getApplication(); + + $instrumentedCode = $this->instrumentCode($code); + + self::$times = []; + + do { + $_ = $shell->execute($instrumentedCode); + $this->ensureEndMarked(); + } while (\count(self::$times) < $num); + + $shell->writeReturnValue($_); + + $times = self::$times; + self::$times = []; + + if ($num === 1) { + $output->writeln(\sprintf(self::RESULT_MSG, $times[0] / 1e+9)); + } else { + $total = \array_sum($times); + \rsort($times); + $median = $times[\round($num / 2)]; + + $output->writeln(\sprintf(self::AVG_RESULT_MSG, ($total / $num) / 1e+9, $median / 1e+9, $total / 1e+9)); + } + + return 0; + } + + /** + * Internal method for marking the start of timeit execution. + * + * A static call to this method will be injected at the start of the timeit + * input code to instrument the call. We will use the saved start time to + * more accurately calculate time elapsed during execution. + */ + public static function markStart() + { + self::$start = \hrtime(true); + } + + /** + * Internal method for marking the end of timeit execution. + * + * A static call to this method is injected by TimeitVisitor at the end + * of the timeit input code to instrument the call. + * + * Note that this accepts an optional $ret parameter, which is used to pass + * the return value of the last statement back out of timeit. This saves us + * a bunch of code rewriting shenanigans. + * + * @param mixed $ret + * + * @return mixed it just passes $ret right back + */ + public static function markEnd($ret = null) + { + self::$times[] = \hrtime(true) - self::$start; + self::$start = null; + + return $ret; + } + + /** + * Ensure that the end of code execution was marked. + * + * The end *should* be marked in the instrumented code, but just in case + * we'll add a fallback here. + */ + private function ensureEndMarked() + { + if (self::$start !== null) { + self::markEnd(); + } + } + + /** + * Instrument code for timeit execution. + * + * This inserts `markStart` and `markEnd` calls to ensure that (reasonably) + * accurate times are recorded for just the code being executed. + */ + private function instrumentCode(string $code): string + { + return $this->printer->prettyPrint($this->traverser->traverse($this->parser->parse($code))); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/TimeitCommand/TimeitVisitor.php b/php/libraries/composer/vendor/psy/psysh/src/Command/TimeitCommand/TimeitVisitor.php new file mode 100644 index 0000000..68948ee --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/TimeitCommand/TimeitVisitor.php @@ -0,0 +1,131 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command\TimeitCommand; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\FunctionLike; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use PhpParser\Node\Stmt\Expression; +use PhpParser\Node\Stmt\Return_; +use PhpParser\NodeVisitorAbstract; +use Psy\CodeCleaner\NoReturnValue; +use Psy\Command\TimeitCommand; + +/** + * A node visitor for instrumenting code to be executed by the `timeit` command. + * + * Injects `TimeitCommand::markStart()` at the start of code to be executed, and + * `TimeitCommand::markEnd()` at the end, and on top-level return statements. + */ +class TimeitVisitor extends NodeVisitorAbstract +{ + private $functionDepth; + + /** + * {@inheritdoc} + * + * @return Node[]|null Array of nodes + */ + public function beforeTraverse(array $nodes) + { + $this->functionDepth = 0; + } + + /** + * {@inheritdoc} + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + // keep track of nested function-like nodes, because they can have + // returns statements... and we don't want to call markEnd for those. + if ($node instanceof FunctionLike) { + $this->functionDepth++; + + return; + } + + // replace any top-level `return` statements with a `markEnd` call + if ($this->functionDepth === 0 && $node instanceof Return_) { + return new Return_($this->getEndCall($node->expr), $node->getAttributes()); + } + } + + /** + * {@inheritdoc} + * + * @return int|Node|Node[]|null Replacement node (or special return value) + */ + public function leaveNode(Node $node) + { + if ($node instanceof FunctionLike) { + $this->functionDepth--; + } + } + + /** + * {@inheritdoc} + * + * @return Node[]|null Array of nodes + */ + public function afterTraverse(array $nodes) + { + // prepend a `markStart` call + \array_unshift($nodes, new Expression($this->getStartCall(), [])); + + // append a `markEnd` call (wrapping the final node, if it's an expression) + $last = $nodes[\count($nodes) - 1]; + if ($last instanceof Expr) { + \array_pop($nodes); + $nodes[] = $this->getEndCall($last); + } elseif ($last instanceof Expression) { + \array_pop($nodes); + $nodes[] = new Expression($this->getEndCall($last->expr), $last->getAttributes()); + } elseif ($last instanceof Return_) { + // nothing to do here, we're already ending with a return call + } else { + $nodes[] = new Expression($this->getEndCall(), []); + } + + return $nodes; + } + + /** + * Get PhpParser AST nodes for a `markStart` call. + * + * @return \PhpParser\Node\Expr\StaticCall + */ + private function getStartCall(): StaticCall + { + return new StaticCall(new FullyQualifiedName(TimeitCommand::class), 'markStart'); + } + + /** + * Get PhpParser AST nodes for a `markEnd` call. + * + * Optionally pass in a return value. + * + * @param Expr|null $arg + */ + private function getEndCall(Expr $arg = null): StaticCall + { + if ($arg === null) { + $arg = NoReturnValue::create(); + } + + return new StaticCall(new FullyQualifiedName(TimeitCommand::class), 'markEnd', [new Arg($arg)]); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/TraceCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/TraceCommand.php new file mode 100644 index 0000000..411237e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/TraceCommand.php @@ -0,0 +1,99 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Formatter\TraceFormatter; +use Psy\Input\FilterOptions; +use Psy\Output\ShellOutput; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Show the current stack trace. + */ +class TraceCommand extends Command +{ + protected $filter; + + /** + * {@inheritdoc} + */ + public function __construct($name = null) + { + $this->filter = new FilterOptions(); + + parent::__construct($name); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + list($grep, $insensitive, $invert) = FilterOptions::getOptions(); + + $this + ->setName('trace') + ->setDefinition([ + new InputOption('include-psy', 'p', InputOption::VALUE_NONE, 'Include Psy in the call stack.'), + new InputOption('num', 'n', InputOption::VALUE_REQUIRED, 'Only include NUM lines.'), + + $grep, + $insensitive, + $invert, + ]) + ->setDescription('Show the current call stack.') + ->setHelp( + <<<'HELP' +Show the current call stack. + +Optionally, include PsySH in the call stack by passing the <info>--include-psy</info> option. + +e.g. +<return>> trace -n10</return> +<return>> trace --include-psy</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->filter->bind($input); + $trace = $this->getBacktrace(new \Exception(), $input->getOption('num'), $input->getOption('include-psy')); + $output->page($trace, ShellOutput::NUMBER_LINES); + + return 0; + } + + /** + * Get a backtrace for an exception or error. + * + * Optionally limit the number of rows to include with $count, and exclude + * Psy from the trace. + * + * @param \Throwable $e The exception or error with a backtrace + * @param int $count (default: PHP_INT_MAX) + * @param bool $includePsy (default: true) + * + * @return array Formatted stacktrace lines + */ + protected function getBacktrace(\Throwable $e, int $count = null, bool $includePsy = true): array + { + return TraceFormatter::formatTrace($e, $this->filter, $count, $includePsy); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/WhereamiCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/WhereamiCommand.php new file mode 100644 index 0000000..b7d569b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/WhereamiCommand.php @@ -0,0 +1,156 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Formatter\CodeFormatter; +use Psy\Output\ShellOutput; +use Psy\Shell; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Show the context of where you opened the debugger. + */ +class WhereamiCommand extends Command +{ + private $backtrace; + + public function __construct() + { + $this->backtrace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + + parent::__construct(); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('whereami') + ->setDefinition([ + new InputOption('num', 'n', InputOption::VALUE_OPTIONAL, 'Number of lines before and after.', '5'), + new InputOption('file', 'f|a', InputOption::VALUE_NONE, 'Show the full source for the current file.'), + ]) + ->setDescription('Show where you are in the code.') + ->setHelp( + <<<'HELP' +Show where you are in the code. + +Optionally, include the number of lines before and after you want to display, +or --file for the whole file. + +e.g. +<return>> whereami </return> +<return>> whereami -n10</return> +<return>> whereami --file</return> +HELP + ); + } + + /** + * Obtains the correct stack frame in the full backtrace. + * + * @return array + */ + protected function trace(): array + { + foreach (\array_reverse($this->backtrace) as $stackFrame) { + if ($this->isDebugCall($stackFrame)) { + return $stackFrame; + } + } + + return \end($this->backtrace); + } + + private static function isDebugCall(array $stackFrame): bool + { + $class = isset($stackFrame['class']) ? $stackFrame['class'] : null; + $function = isset($stackFrame['function']) ? $stackFrame['function'] : null; + + return ($class === null && $function === 'Psy\\debug') || + ($class === Shell::class && \in_array($function, ['__construct', 'debug'])); + } + + /** + * Determine the file and line based on the specific backtrace. + * + * @return array + */ + protected function fileInfo(): array + { + $stackFrame = $this->trace(); + if (\preg_match('/eval\(/', $stackFrame['file'])) { + \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches); + $file = $matches[1][0]; + $line = (int) $matches[2][0]; + } else { + $file = $stackFrame['file']; + $line = $stackFrame['line']; + } + + return \compact('file', 'line'); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $info = $this->fileInfo(); + $num = $input->getOption('num'); + $lineNum = $info['line']; + $startLine = \max($lineNum - $num, 1); + $endLine = $lineNum + $num; + $code = \file_get_contents($info['file']); + + if ($input->getOption('file')) { + $startLine = 1; + $endLine = null; + } + + if ($output instanceof ShellOutput) { + $output->startPaging(); + } + + $output->writeln(\sprintf('From <info>%s:%s</info>:', $this->replaceCwd($info['file']), $lineNum)); + $output->write(CodeFormatter::formatCode($code, $startLine, $endLine, $lineNum), false); + + if ($output instanceof ShellOutput) { + $output->stopPaging(); + } + + return 0; + } + + /** + * Replace the given directory from the start of a filepath. + * + * @param string $file + */ + private function replaceCwd(string $file): string + { + $cwd = \getcwd(); + if ($cwd === false) { + return $file; + } + + $cwd = \rtrim($cwd, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR; + + return \preg_replace('/^'.\preg_quote($cwd, '/').'/', '', $file); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Command/WtfCommand.php b/php/libraries/composer/vendor/psy/psysh/src/Command/WtfCommand.php new file mode 100644 index 0000000..6e2472c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Command/WtfCommand.php @@ -0,0 +1,136 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Command; + +use Psy\Context; +use Psy\ContextAware; +use Psy\Input\FilterOptions; +use Psy\Output\ShellOutput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Show the last uncaught exception. + */ +class WtfCommand extends TraceCommand implements ContextAware +{ + /** + * Context instance (for ContextAware interface). + * + * @var Context + */ + protected $context; + + /** + * ContextAware interface. + * + * @param Context $context + */ + public function setContext(Context $context) + { + $this->context = $context; + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + list($grep, $insensitive, $invert) = FilterOptions::getOptions(); + + $this + ->setName('wtf') + ->setAliases(['last-exception', 'wtf?']) + ->setDefinition([ + new InputArgument('incredulity', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'Number of lines to show.'), + new InputOption('all', 'a', InputOption::VALUE_NONE, 'Show entire backtrace.'), + + $grep, + $insensitive, + $invert, + ]) + ->setDescription('Show the backtrace of the most recent exception.') + ->setHelp( + <<<'HELP' +Shows a few lines of the backtrace of the most recent exception. + +If you want to see more lines, add more question marks or exclamation marks: + +e.g. +<return>>>> wtf ?</return> +<return>>>> wtf ?!???!?!?</return> + +To see the entire backtrace, pass the -a/--all flag: + +e.g. +<return>>>> wtf -a</return> +HELP + ); + } + + /** + * {@inheritdoc} + * + * @return int 0 if everything went fine, or an exit code + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->filter->bind($input); + + $incredulity = \implode('', $input->getArgument('incredulity')); + if (\strlen(\preg_replace('/[\\?!]/', '', $incredulity))) { + throw new \InvalidArgumentException('Incredulity must include only "?" and "!"'); + } + + $exception = $this->context->getLastException(); + $count = $input->getOption('all') ? \PHP_INT_MAX : \max(3, \pow(2, \strlen($incredulity) + 1)); + + $shell = $this->getApplication(); + + if ($output instanceof ShellOutput) { + $output->startPaging(); + } + + do { + $traceCount = \count($exception->getTrace()); + $showLines = $count; + // Show the whole trace if we'd only be hiding a few lines + if ($traceCount < \max($count * 1.2, $count + 2)) { + $showLines = \PHP_INT_MAX; + } + + $trace = $this->getBacktrace($exception, $showLines); + $moreLines = $traceCount - \count($trace); + + $output->writeln($shell->formatException($exception)); + $output->writeln('--'); + $output->write($trace, true, ShellOutput::NUMBER_LINES); + $output->writeln(''); + + if ($moreLines > 0) { + $output->writeln(\sprintf( + '<aside>Use <return>wtf -a</return> to see %d more lines</aside>', + $moreLines + )); + $output->writeln(''); + } + } while ($exception = $exception->getPrevious()); + + if ($output instanceof ShellOutput) { + $output->stopPaging(); + } + + return 0; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ConfigPaths.php b/php/libraries/composer/vendor/psy/psysh/src/ConfigPaths.php new file mode 100644 index 0000000..a091d20 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ConfigPaths.php @@ -0,0 +1,378 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * A Psy Shell configuration path helper. + */ +class ConfigPaths +{ + private $configDir; + private $dataDir; + private $runtimeDir; + private $env; + + /** + * ConfigPaths constructor. + * + * Optionally provide `configDir`, `dataDir` and `runtimeDir` overrides. + * + * @see self::overrideDirs + * + * @param string[] $overrides Directory overrides + * @param EnvInterface $env + */ + public function __construct(array $overrides = [], EnvInterface $env = null) + { + $this->overrideDirs($overrides); + + $this->env = $env ?: (\PHP_SAPI === 'cli-server' ? new SystemEnv() : new SuperglobalsEnv()); + } + + /** + * Provide `configDir`, `dataDir` and `runtimeDir` overrides. + * + * If a key is set but empty, the override will be removed. If it is not set + * at all, any existing override will persist. + * + * @param string[] $overrides Directory overrides + */ + public function overrideDirs(array $overrides) + { + if (\array_key_exists('configDir', $overrides)) { + $this->configDir = $overrides['configDir'] ?: null; + } + + if (\array_key_exists('dataDir', $overrides)) { + $this->dataDir = $overrides['dataDir'] ?: null; + } + + if (\array_key_exists('runtimeDir', $overrides)) { + $this->runtimeDir = $overrides['runtimeDir'] ?: null; + } + } + + /** + * Get the current home directory. + * + * @return string|null + */ + public function homeDir() + { + if ($homeDir = $this->getEnv('HOME') ?: $this->windowsHomeDir()) { + return \strtr($homeDir, '\\', '/'); + } + + return null; + } + + private function windowsHomeDir() + { + if (\defined('PHP_WINDOWS_VERSION_MAJOR')) { + $homeDrive = $this->getEnv('HOMEDRIVE'); + $homePath = $this->getEnv('HOMEPATH'); + if ($homeDrive && $homePath) { + return $homeDrive.'/'.$homePath; + } + } + + return null; + } + + private function homeConfigDir() + { + if ($homeConfigDir = $this->getEnv('XDG_CONFIG_HOME')) { + return $homeConfigDir; + } + + $homeDir = $this->homeDir(); + + return $homeDir === '/' ? $homeDir.'.config' : $homeDir.'/.config'; + } + + /** + * Get potential config directory paths. + * + * Returns `~/.psysh`, `%APPDATA%/PsySH` (when on Windows), and all + * XDG Base Directory config directories: + * + * http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + * + * @return string[] + */ + public function configDirs(): array + { + if ($this->configDir !== null) { + return [$this->configDir]; + } + + $configDirs = $this->getEnvArray('XDG_CONFIG_DIRS') ?: ['/etc/xdg']; + + return $this->allDirNames(\array_merge([$this->homeConfigDir()], $configDirs)); + } + + /** + * Get the current home config directory. + * + * Returns the highest precedence home config directory which actually + * exists. If none of them exists, returns the highest precedence home + * config directory (`%APPDATA%/PsySH` on Windows, `~/.config/psysh` + * everywhere else). + * + * @see self::homeConfigDir + */ + public function currentConfigDir(): string + { + if ($this->configDir !== null) { + return $this->configDir; + } + + $configDirs = $this->allDirNames([$this->homeConfigDir()]); + + foreach ($configDirs as $configDir) { + if (@\is_dir($configDir)) { + return $configDir; + } + } + + return $configDirs[0]; + } + + /** + * Find real config files in config directories. + * + * @param string[] $names Config file names + * + * @return string[] + */ + public function configFiles(array $names): array + { + return $this->allRealFiles($this->configDirs(), $names); + } + + /** + * Get potential data directory paths. + * + * If a `dataDir` option was explicitly set, returns an array containing + * just that directory. + * + * Otherwise, it returns `~/.psysh` and all XDG Base Directory data directories: + * + * http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + * + * @return string[] + */ + public function dataDirs(): array + { + if ($this->dataDir !== null) { + return [$this->dataDir]; + } + + $homeDataDir = $this->getEnv('XDG_DATA_HOME') ?: $this->homeDir().'/.local/share'; + $dataDirs = $this->getEnvArray('XDG_DATA_DIRS') ?: ['/usr/local/share', '/usr/share']; + + return $this->allDirNames(\array_merge([$homeDataDir], $dataDirs)); + } + + /** + * Find real data files in config directories. + * + * @param string[] $names Config file names + * + * @return string[] + */ + public function dataFiles(array $names): array + { + return $this->allRealFiles($this->dataDirs(), $names); + } + + /** + * Get a runtime directory. + * + * Defaults to `/psysh` inside the system's temp dir. + */ + public function runtimeDir(): string + { + if ($this->runtimeDir !== null) { + return $this->runtimeDir; + } + + // Fallback to a boring old folder in the system temp dir. + $runtimeDir = $this->getEnv('XDG_RUNTIME_DIR') ?: \sys_get_temp_dir(); + + return \strtr($runtimeDir, '\\', '/').'/psysh'; + } + + /** + * Get a list of directories in PATH. + * + * If $PATH is unset/empty it defaults to '/usr/sbin:/usr/bin:/sbin:/bin'. + * + * @return string[] + */ + public function pathDirs(): array + { + return $this->getEnvArray('PATH') ?: ['/usr/sbin', '/usr/bin', '/sbin', '/bin']; + } + + /** + * Locate a command (an executable) in $PATH. + * + * Behaves like 'command -v COMMAND' or 'which COMMAND'. + * If $PATH is unset/empty it defaults to '/usr/sbin:/usr/bin:/sbin:/bin'. + * + * @param string $command the executable to locate + * + * @return string + */ + public function which($command) + { + foreach ($this->pathDirs() as $path) { + $fullpath = $path.\DIRECTORY_SEPARATOR.$command; + if (@\is_file($fullpath) && @\is_executable($fullpath)) { + return $fullpath; + } + } + + return null; + } + + /** + * Get all PsySH directory name candidates given a list of base directories. + * + * This expects that XDG-compatible directory paths will be passed in. + * `psysh` will be added to each of $baseDirs, and we'll throw in `~/.psysh` + * and a couple of Windows-friendly paths as well. + * + * @param string[] $baseDirs base directory paths + * + * @return string[] + */ + private function allDirNames(array $baseDirs): array + { + $dirs = \array_map(function ($dir) { + return \strtr($dir, '\\', '/').'/psysh'; + }, $baseDirs); + + // Add ~/.psysh + if ($home = $this->getEnv('HOME')) { + $dirs[] = \strtr($home, '\\', '/').'/.psysh'; + } + + // Add some Windows specific ones :) + if (\defined('PHP_WINDOWS_VERSION_MAJOR')) { + if ($appData = $this->getEnv('APPDATA')) { + // AppData gets preference + \array_unshift($dirs, \strtr($appData, '\\', '/').'/PsySH'); + } + + if ($windowsHomeDir = $this->windowsHomeDir()) { + $dir = \strtr($windowsHomeDir, '\\', '/').'/.psysh'; + if (!\in_array($dir, $dirs)) { + $dirs[] = $dir; + } + } + } + + return $dirs; + } + + /** + * Given a list of directories, and a list of filenames, find the ones that + * are real files. + * + * @return string[] + */ + private function allRealFiles(array $dirNames, array $fileNames): array + { + $files = []; + foreach ($dirNames as $dir) { + foreach ($fileNames as $name) { + $file = $dir.'/'.$name; + if (@\is_file($file)) { + $files[] = $file; + } + } + } + + return $files; + } + + /** + * Ensure that $dir exists and is writable. + * + * Generates E_USER_NOTICE error if the directory is not writable or creatable. + * + * @param string $dir + * + * @return bool False if directory exists but is not writeable, or cannot be created + */ + public static function ensureDir(string $dir): bool + { + if (!\is_dir($dir)) { + // Just try making it and see if it works + @\mkdir($dir, 0700, true); + } + + if (!\is_dir($dir) || !\is_writable($dir)) { + \trigger_error(\sprintf('Writing to directory %s is not allowed.', $dir), \E_USER_NOTICE); + + return false; + } + + return true; + } + + /** + * Ensure that $file exists and is writable, make the parent directory if necessary. + * + * Generates E_USER_NOTICE error if either $file or its directory is not writable. + * + * @param string $file + * + * @return string|false Full path to $file, or false if file is not writable + */ + public static function touchFileWithMkdir(string $file) + { + if (\file_exists($file)) { + if (\is_writable($file)) { + return $file; + } + + \trigger_error(\sprintf('Writing to %s is not allowed.', $file), \E_USER_NOTICE); + + return false; + } + + if (!self::ensureDir(\dirname($file))) { + return false; + } + + \touch($file); + + return $file; + } + + private function getEnv($key) + { + return $this->env->get($key); + } + + private function getEnvArray($key) + { + if ($value = $this->getEnv($key)) { + return \explode(\PATH_SEPARATOR, $value); + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Configuration.php b/php/libraries/composer/vendor/psy/psysh/src/Configuration.php new file mode 100644 index 0000000..c6d0bb5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Configuration.php @@ -0,0 +1,1899 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +use Psy\Exception\DeprecatedException; +use Psy\Exception\RuntimeException; +use Psy\ExecutionLoop\ProcessForker; +use Psy\Output\OutputPager; +use Psy\Output\ShellOutput; +use Psy\Output\Theme; +use Psy\TabCompletion\AutoCompleter; +use Psy\VarDumper\Presenter; +use Psy\VersionUpdater\Checker; +use Psy\VersionUpdater\GitHubChecker; +use Psy\VersionUpdater\IntervalChecker; +use Psy\VersionUpdater\NoopChecker; +use Symfony\Component\Console\Formatter\OutputFormatterStyle; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * The Psy Shell configuration. + */ +class Configuration +{ + const COLOR_MODE_AUTO = 'auto'; + const COLOR_MODE_FORCED = 'forced'; + const COLOR_MODE_DISABLED = 'disabled'; + + const INTERACTIVE_MODE_AUTO = 'auto'; + const INTERACTIVE_MODE_FORCED = 'forced'; + const INTERACTIVE_MODE_DISABLED = 'disabled'; + + const VERBOSITY_QUIET = 'quiet'; + const VERBOSITY_NORMAL = 'normal'; + const VERBOSITY_VERBOSE = 'verbose'; + const VERBOSITY_VERY_VERBOSE = 'very_verbose'; + const VERBOSITY_DEBUG = 'debug'; + + private static $AVAILABLE_OPTIONS = [ + 'codeCleaner', + 'colorMode', + 'configDir', + 'dataDir', + 'defaultIncludes', + 'eraseDuplicates', + 'errorLoggingLevel', + 'forceArrayIndexes', + 'formatterStyles', + 'historyFile', + 'historySize', + 'interactiveMode', + 'manualDbFile', + 'pager', + 'prompt', + 'rawOutput', + 'requireSemicolons', + 'runtimeDir', + 'startupMessage', + 'strictTypes', + 'theme', + 'updateCheck', + 'useBracketedPaste', + 'usePcntl', + 'useReadline', + 'useTabCompletion', + 'useUnicode', + 'verbosity', + 'warnOnMultipleConfigs', + 'yolo', + ]; + + private $defaultIncludes; + private $configDir; + private $dataDir; + private $runtimeDir; + private $configFile; + /** @var string|false */ + private $historyFile; + private $historySize; + private $eraseDuplicates; + private $manualDbFile; + private $hasReadline; + private $useReadline; + private $useBracketedPaste; + private $hasPcntl; + private $usePcntl; + private $newCommands = []; + private $pipedInput; + private $pipedOutput; + private $rawOutput = false; + private $requireSemicolons = false; + private $strictTypes = false; + private $useUnicode; + private $useTabCompletion; + private $newMatchers = []; + private $errorLoggingLevel = \E_ALL; + private $warnOnMultipleConfigs = false; + private $colorMode = self::COLOR_MODE_AUTO; + private $interactiveMode = self::INTERACTIVE_MODE_AUTO; + private $updateCheck; + private $startupMessage; + private $forceArrayIndexes = false; + /** @deprecated */ + private $formatterStyles = []; + private $verbosity = self::VERBOSITY_NORMAL; + private $yolo = false; + /** @var Theme */ + private $theme; + + // services + private $readline; + /** @var ShellOutput */ + private $output; + private $shell; + private $cleaner; + private $pager; + private $manualDb; + private $presenter; + private $autoCompleter; + private $checker; + /** @deprecated */ + private $prompt; + private $configPaths; + + /** + * Construct a Configuration instance. + * + * Optionally, supply an array of configuration values to load. + * + * @param array $config Optional array of configuration values + */ + public function __construct(array $config = []) + { + $this->configPaths = new ConfigPaths(); + + // explicit configFile option + if (isset($config['configFile'])) { + $this->configFile = $config['configFile']; + } elseif (isset($_SERVER['PSYSH_CONFIG']) && $_SERVER['PSYSH_CONFIG']) { + $this->configFile = $_SERVER['PSYSH_CONFIG']; + } elseif (\PHP_SAPI === 'cli-server' && ($configFile = \getenv('PSYSH_CONFIG'))) { + $this->configFile = $configFile; + } + + // legacy baseDir option + if (isset($config['baseDir'])) { + $msg = "The 'baseDir' configuration option is deprecated; ". + "please specify 'configDir' and 'dataDir' options instead"; + throw new DeprecatedException($msg); + } + + unset($config['configFile'], $config['baseDir']); + + // go go gadget, config! + $this->loadConfig($config); + $this->init(); + } + + /** + * Construct a Configuration object from Symfony Console input. + * + * This is great for adding psysh-compatible command line options to framework- or app-specific + * wrappers. + * + * $input should already be bound to an appropriate InputDefinition (see self::getInputOptions + * if you want to build your own) before calling this method. It's not required, but things work + * a lot better if we do. + * + * @see self::getInputOptions + * + * @throws \InvalidArgumentException + * + * @param InputInterface $input + */ + public static function fromInput(InputInterface $input): self + { + $config = new self(['configFile' => self::getConfigFileFromInput($input)]); + + // Handle --color and --no-color (and --ansi and --no-ansi aliases) + if (self::getOptionFromInput($input, ['color', 'ansi'])) { + $config->setColorMode(self::COLOR_MODE_FORCED); + } elseif (self::getOptionFromInput($input, ['no-color', 'no-ansi'])) { + $config->setColorMode(self::COLOR_MODE_DISABLED); + } + + // Handle verbosity options + if ($verbosity = self::getVerbosityFromInput($input)) { + $config->setVerbosity($verbosity); + } + + // Handle interactive mode + if (self::getOptionFromInput($input, ['interactive', 'interaction'], ['-a', '-i'])) { + $config->setInteractiveMode(self::INTERACTIVE_MODE_FORCED); + } elseif (self::getOptionFromInput($input, ['no-interactive', 'no-interaction'], ['-n'])) { + $config->setInteractiveMode(self::INTERACTIVE_MODE_DISABLED); + } + + // Handle --compact + if (self::getOptionFromInput($input, ['compact'])) { + $config->setTheme('compact'); + } + + // Handle --raw-output + // @todo support raw output with interactive input? + if (!$config->getInputInteractive()) { + if (self::getOptionFromInput($input, ['raw-output'], ['-r'])) { + $config->setRawOutput(true); + } + } + + // Handle --yolo + if (self::getOptionFromInput($input, ['yolo'])) { + $config->setYolo(true); + } + + return $config; + } + + /** + * Get the desired config file from the given input. + * + * @return string|null config file path, or null if none is specified + */ + private static function getConfigFileFromInput(InputInterface $input) + { + // Best case, input is properly bound and validated. + if ($input->hasOption('config')) { + return $input->getOption('config'); + } + + return $input->getParameterOption('--config', null, true) ?: $input->getParameterOption('-c', null, true); + } + + /** + * Get a boolean option from the given input. + * + * This helper allows fallback for unbound and unvalidated input. It's not perfect--for example, + * it can't deal with several short options squished together--but it's better than falling over + * any time someone gives us unbound input. + * + * @return bool true if the option (or an alias) is present + */ + private static function getOptionFromInput(InputInterface $input, array $names, array $otherParams = []): bool + { + // Best case, input is properly bound and validated. + foreach ($names as $name) { + if ($input->hasOption($name) && $input->getOption($name)) { + return true; + } + } + + foreach ($names as $name) { + $otherParams[] = '--'.$name; + } + + foreach ($otherParams as $name) { + if ($input->hasParameterOption($name, true)) { + return true; + } + } + + return false; + } + + /** + * Get the desired verbosity from the given input. + * + * This is a bit more complext than the other options parsers. It handles `--quiet` and + * `--verbose`, along with their short aliases, and fancy things like `-vvv`. + * + * @return string|null configuration constant, or null if no verbosity option is specified + */ + private static function getVerbosityFromInput(InputInterface $input) + { + // --quiet wins! + if (self::getOptionFromInput($input, ['quiet'], ['-q'])) { + return self::VERBOSITY_QUIET; + } + + // Best case, input is properly bound and validated. + // + // Note that if the `--verbose` option is incorrectly defined as `VALUE_NONE` rather than + // `VALUE_OPTIONAL` (as it is in Symfony Console by default) it doesn't actually work with + // multiple verbosity levels as it claims. + // + // We can detect this by checking whether the the value === true, and fall back to unbound + // parsing for this option. + if ($input->hasOption('verbose') && $input->getOption('verbose') !== true) { + switch ($input->getOption('verbose')) { + case '-1': + return self::VERBOSITY_QUIET; + case '0': // explicitly normal, overrides config file default + return self::VERBOSITY_NORMAL; + case '1': + case null: // `--verbose` and `-v` + return self::VERBOSITY_VERBOSE; + case '2': + case 'v': // `-vv` + return self::VERBOSITY_VERY_VERBOSE; + case '3': + case 'vv': // `-vvv` + return self::VERBOSITY_DEBUG; + default: // implicitly normal, config file default wins + return; + } + } + + // quiet and normal have to come before verbose, because it eats everything else. + if ($input->hasParameterOption('--verbose=-1', true) || $input->getParameterOption('--verbose', false, true) === '-1') { + return self::VERBOSITY_QUIET; + } + + if ($input->hasParameterOption('--verbose=0', true) || $input->getParameterOption('--verbose', false, true) === '0') { + return self::VERBOSITY_NORMAL; + } + + // `-vvv`, `-vv` and `-v` have to come in descending length order, because `hasParameterOption` matches prefixes. + if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || $input->getParameterOption('--verbose', false, true) === '3') { + return self::VERBOSITY_DEBUG; + } + + if ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || $input->getParameterOption('--verbose', false, true) === '2') { + return self::VERBOSITY_VERY_VERBOSE; + } + + if ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true)) { + return self::VERBOSITY_VERBOSE; + } + } + + /** + * Get a list of input options expected when initializing Configuration via input. + * + * @see self::fromInput + * + * @return InputOption[] + */ + public static function getInputOptions(): array + { + return [ + new InputOption('config', 'c', InputOption::VALUE_REQUIRED, 'Use an alternate PsySH config file location.'), + new InputOption('cwd', null, InputOption::VALUE_REQUIRED, 'Use an alternate working directory.'), + + new InputOption('color', null, InputOption::VALUE_NONE, 'Force colors in output.'), + new InputOption('no-color', null, InputOption::VALUE_NONE, 'Disable colors in output.'), + // --ansi and --no-ansi aliases to match Symfony, Composer, etc. + new InputOption('ansi', null, InputOption::VALUE_NONE, 'Force colors in output.'), + new InputOption('no-ansi', null, InputOption::VALUE_NONE, 'Disable colors in output.'), + + new InputOption('quiet', 'q', InputOption::VALUE_NONE, 'Shhhhhh.'), + new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_OPTIONAL, 'Increase the verbosity of messages.', '0'), + new InputOption('compact', null, InputOption::VALUE_NONE, 'Run PsySH with compact output.'), + new InputOption('interactive', 'i|a', InputOption::VALUE_NONE, 'Force PsySH to run in interactive mode.'), + new InputOption('no-interactive', 'n', InputOption::VALUE_NONE, 'Run PsySH without interactive input. Requires input from stdin.'), + // --interaction and --no-interaction aliases for compatibility with Symfony, Composer, etc + new InputOption('interaction', null, InputOption::VALUE_NONE, 'Force PsySH to run in interactive mode.'), + new InputOption('no-interaction', null, InputOption::VALUE_NONE, 'Run PsySH without interactive input. Requires input from stdin.'), + new InputOption('raw-output', 'r', InputOption::VALUE_NONE, 'Print var_export-style return values (for non-interactive input)'), + + new InputOption('self-update', 'u', InputOption::VALUE_NONE, 'Update to the latest version'), + + new InputOption('yolo', null, InputOption::VALUE_NONE, 'Run PsySH with minimal input validation. You probably don\'t want this.'), + ]; + } + + /** + * Initialize the configuration. + * + * This checks for the presence of Readline and Pcntl extensions. + * + * If a config file is available, it will be loaded and merged with the current config. + * + * If no custom config file was specified and a local project config file + * is available, it will be loaded and merged with the current config. + */ + public function init() + { + // feature detection + $this->hasReadline = \function_exists('readline'); + $this->hasPcntl = ProcessForker::isSupported(); + + if ($configFile = $this->getConfigFile()) { + $this->loadConfigFile($configFile); + } + + if (!$this->configFile && $localConfig = $this->getLocalConfigFile()) { + $this->loadConfigFile($localConfig); + } + + $this->configPaths->overrideDirs([ + 'configDir' => $this->configDir, + 'dataDir' => $this->dataDir, + 'runtimeDir' => $this->runtimeDir, + ]); + } + + /** + * Get the current PsySH config file. + * + * If a `configFile` option was passed to the Configuration constructor, + * this file will be returned. If not, all possible config directories will + * be searched, and the first `config.php` or `rc.php` file which exists + * will be returned. + * + * If you're trying to decide where to put your config file, pick + * + * ~/.config/psysh/config.php + * + * @return string|null + */ + public function getConfigFile() + { + if (isset($this->configFile)) { + return $this->configFile; + } + + $files = $this->configPaths->configFiles(['config.php', 'rc.php']); + + if (!empty($files)) { + if ($this->warnOnMultipleConfigs && \count($files) > 1) { + $msg = \sprintf('Multiple configuration files found: %s. Using %s', \implode(', ', $files), $files[0]); + \trigger_error($msg, \E_USER_NOTICE); + } + + return $files[0]; + } + } + + /** + * Get the local PsySH config file. + * + * Searches for a project specific config file `.psysh.php` in the current + * working directory. + * + * @return string|null + */ + public function getLocalConfigFile() + { + $localConfig = \getcwd().'/.psysh.php'; + + if (@\is_file($localConfig)) { + return $localConfig; + } + } + + /** + * Load configuration values from an array of options. + * + * @param array $options + */ + public function loadConfig(array $options) + { + foreach (self::$AVAILABLE_OPTIONS as $option) { + if (isset($options[$option])) { + $method = 'set'.\ucfirst($option); + $this->$method($options[$option]); + } + } + + // legacy `tabCompletion` option + if (isset($options['tabCompletion'])) { + $msg = '`tabCompletion` is deprecated; use `useTabCompletion` instead.'; + @\trigger_error($msg, \E_USER_DEPRECATED); + + $this->setUseTabCompletion($options['tabCompletion']); + } + + foreach (['commands', 'matchers', 'casters'] as $option) { + if (isset($options[$option])) { + $method = 'add'.\ucfirst($option); + $this->$method($options[$option]); + } + } + + // legacy `tabCompletionMatchers` option + if (isset($options['tabCompletionMatchers'])) { + $msg = '`tabCompletionMatchers` is deprecated; use `matchers` instead.'; + @\trigger_error($msg, \E_USER_DEPRECATED); + + $this->addMatchers($options['tabCompletionMatchers']); + } + } + + /** + * Load a configuration file (default: `$HOME/.config/psysh/config.php`). + * + * This configuration instance will be available to the config file as $config. + * The config file may directly manipulate the configuration, or may return + * an array of options which will be merged with the current configuration. + * + * @throws \InvalidArgumentException if the config file does not exist or returns a non-array result + * + * @param string $file + */ + public function loadConfigFile(string $file) + { + if (!\is_file($file)) { + throw new \InvalidArgumentException(\sprintf('Invalid configuration file specified, %s does not exist', $file)); + } + + $__psysh_config_file__ = $file; + $load = function ($config) use ($__psysh_config_file__) { + $result = require $__psysh_config_file__; + if ($result !== 1) { + return $result; + } + }; + $result = $load($this); + + if (!empty($result)) { + if (\is_array($result)) { + $this->loadConfig($result); + } else { + throw new \InvalidArgumentException('Psy Shell configuration must return an array of options'); + } + } + } + + /** + * Set files to be included by default at the start of each shell session. + * + * @param array $includes + */ + public function setDefaultIncludes(array $includes = []) + { + $this->defaultIncludes = $includes; + } + + /** + * Get files to be included by default at the start of each shell session. + * + * @return string[] + */ + public function getDefaultIncludes(): array + { + return $this->defaultIncludes ?: []; + } + + /** + * Set the shell's config directory location. + * + * @param string $dir + */ + public function setConfigDir(string $dir) + { + $this->configDir = (string) $dir; + + $this->configPaths->overrideDirs([ + 'configDir' => $this->configDir, + 'dataDir' => $this->dataDir, + 'runtimeDir' => $this->runtimeDir, + ]); + } + + /** + * Get the current configuration directory, if any is explicitly set. + * + * @return string|null + */ + public function getConfigDir() + { + return $this->configDir; + } + + /** + * Set the shell's data directory location. + * + * @param string $dir + */ + public function setDataDir(string $dir) + { + $this->dataDir = (string) $dir; + + $this->configPaths->overrideDirs([ + 'configDir' => $this->configDir, + 'dataDir' => $this->dataDir, + 'runtimeDir' => $this->runtimeDir, + ]); + } + + /** + * Get the current data directory, if any is explicitly set. + * + * @return string|null + */ + public function getDataDir() + { + return $this->dataDir; + } + + /** + * Set the shell's temporary directory location. + * + * @param string $dir + */ + public function setRuntimeDir(string $dir) + { + $this->runtimeDir = (string) $dir; + + $this->configPaths->overrideDirs([ + 'configDir' => $this->configDir, + 'dataDir' => $this->dataDir, + 'runtimeDir' => $this->runtimeDir, + ]); + } + + /** + * Get the shell's temporary directory location. + * + * Defaults to `/psysh` inside the system's temp dir unless explicitly + * overridden. + * + * @throws RuntimeException if no temporary directory is set and it is not possible to create one + */ + public function getRuntimeDir(): string + { + $runtimeDir = $this->configPaths->runtimeDir(); + + if (!\is_dir($runtimeDir)) { + if (!@\mkdir($runtimeDir, 0700, true)) { + throw new RuntimeException(\sprintf('Unable to create PsySH runtime directory. Make sure PHP is able to write to %s in order to continue.', \dirname($runtimeDir))); + } + } + + return $runtimeDir; + } + + /** + * Set the readline history file path. + * + * @param string $file + */ + public function setHistoryFile(string $file) + { + $this->historyFile = ConfigPaths::touchFileWithMkdir($file); + } + + /** + * Get the readline history file path. + * + * Defaults to `/history` inside the shell's base config dir unless + * explicitly overridden. + */ + public function getHistoryFile(): string + { + if (isset($this->historyFile)) { + return $this->historyFile; + } + + $files = $this->configPaths->configFiles(['psysh_history', 'history']); + + if (!empty($files)) { + if ($this->warnOnMultipleConfigs && \count($files) > 1) { + $msg = \sprintf('Multiple history files found: %s. Using %s', \implode(', ', $files), $files[0]); + \trigger_error($msg, \E_USER_NOTICE); + } + + $this->setHistoryFile($files[0]); + } else { + // fallback: create our own history file + $this->setHistoryFile($this->configPaths->currentConfigDir().'/psysh_history'); + } + + return $this->historyFile; + } + + /** + * Set the readline max history size. + * + * @param int $value + */ + public function setHistorySize(int $value) + { + $this->historySize = (int) $value; + } + + /** + * Get the readline max history size. + * + * @return int + */ + public function getHistorySize() + { + return $this->historySize; + } + + /** + * Sets whether readline erases old duplicate history entries. + * + * @param bool $value + */ + public function setEraseDuplicates(bool $value) + { + $this->eraseDuplicates = (bool) $value; + } + + /** + * Get whether readline erases old duplicate history entries. + * + * @return bool|null + */ + public function getEraseDuplicates() + { + return $this->eraseDuplicates; + } + + /** + * Get a temporary file of type $type for process $pid. + * + * The file will be created inside the current temporary directory. + * + * @see self::getRuntimeDir + * + * @param string $type + * @param int $pid + * + * @return string Temporary file name + */ + public function getTempFile(string $type, int $pid): string + { + return \tempnam($this->getRuntimeDir(), $type.'_'.$pid.'_'); + } + + /** + * Get a filename suitable for a FIFO pipe of $type for process $pid. + * + * The pipe will be created inside the current temporary directory. + * + * @param string $type + * @param int $pid + * + * @return string Pipe name + */ + public function getPipe(string $type, int $pid): string + { + return \sprintf('%s/%s_%s', $this->getRuntimeDir(), $type, $pid); + } + + /** + * Check whether this PHP instance has Readline available. + * + * @return bool True if Readline is available + */ + public function hasReadline(): bool + { + return $this->hasReadline; + } + + /** + * Enable or disable Readline usage. + * + * @param bool $useReadline + */ + public function setUseReadline(bool $useReadline) + { + $this->useReadline = (bool) $useReadline; + } + + /** + * Check whether to use Readline. + * + * If `setUseReadline` as been set to true, but Readline is not actually + * available, this will return false. + * + * @return bool True if the current Shell should use Readline + */ + public function useReadline(): bool + { + return isset($this->useReadline) ? ($this->hasReadline && $this->useReadline) : $this->hasReadline; + } + + /** + * Set the Psy Shell readline service. + * + * @param Readline\Readline $readline + */ + public function setReadline(Readline\Readline $readline) + { + $this->readline = $readline; + } + + /** + * Get the Psy Shell readline service. + * + * By default, this service uses (in order of preference): + * + * * GNU Readline + * * Libedit + * * A transient array-based readline emulation. + * + * @return Readline\Readline + */ + public function getReadline(): Readline\Readline + { + if (!isset($this->readline)) { + $className = $this->getReadlineClass(); + $this->readline = new $className( + $this->getHistoryFile(), + $this->getHistorySize(), + $this->getEraseDuplicates() + ); + } + + return $this->readline; + } + + /** + * Get the appropriate Readline implementation class name. + * + * @see self::getReadline + */ + private function getReadlineClass(): string + { + if ($this->useReadline()) { + if (Readline\GNUReadline::isSupported()) { + return Readline\GNUReadline::class; + } elseif (Readline\Libedit::isSupported()) { + return Readline\Libedit::class; + } + } + + if (Readline\Userland::isSupported()) { + return Readline\Userland::class; + } + + return Readline\Transient::class; + } + + /** + * Enable or disable bracketed paste. + * + * Note that this only works with readline (not libedit) integration for now. + * + * @param bool $useBracketedPaste + */ + public function setUseBracketedPaste(bool $useBracketedPaste) + { + $this->useBracketedPaste = (bool) $useBracketedPaste; + } + + /** + * Check whether to use bracketed paste with readline. + * + * When this works, it's magical. Tabs in pastes don't try to autcomplete. + * Newlines in paste don't execute code until you get to the end. It makes + * readline act like you'd expect when pasting. + * + * But it often (usually?) does not work. And when it doesn't, it just spews + * escape codes all over the place and generally makes things ugly :( + * + * If `useBracketedPaste` has been set to true, but the current readline + * implementation is anything besides GNU readline, this will return false. + * + * @return bool True if the shell should use bracketed paste + */ + public function useBracketedPaste(): bool + { + $readlineClass = $this->getReadlineClass(); + + return $this->useBracketedPaste && $readlineClass::supportsBracketedPaste(); + + // @todo mebbe turn this on by default some day? + // return $readlineClass::supportsBracketedPaste() && $this->useBracketedPaste !== false; + } + + /** + * Check whether this PHP instance has Pcntl available. + * + * @return bool True if Pcntl is available + */ + public function hasPcntl(): bool + { + return $this->hasPcntl; + } + + /** + * Enable or disable Pcntl usage. + * + * @param bool $usePcntl + */ + public function setUsePcntl(bool $usePcntl) + { + $this->usePcntl = (bool) $usePcntl; + } + + /** + * Check whether to use Pcntl. + * + * If `setUsePcntl` has been set to true, but Pcntl is not actually + * available, this will return false. + * + * @return bool True if the current Shell should use Pcntl + */ + public function usePcntl(): bool + { + if (!isset($this->usePcntl)) { + // Unless pcntl is explicitly *enabled*, don't use it while XDebug is debugging. + // See https://github.com/bobthecow/psysh/issues/742 + if (\function_exists('xdebug_is_debugger_active') && \xdebug_is_debugger_active()) { + return false; + } + + return $this->hasPcntl; + } + + return $this->hasPcntl && $this->usePcntl; + } + + /** + * Check whether to use raw output. + * + * This is set by the --raw-output (-r) flag, and really only makes sense + * when non-interactive, e.g. executing stdin. + * + * @return bool true if raw output is enabled + */ + public function rawOutput(): bool + { + return $this->rawOutput; + } + + /** + * Enable or disable raw output. + * + * @param bool $rawOutput + */ + public function setRawOutput(bool $rawOutput) + { + $this->rawOutput = (bool) $rawOutput; + } + + /** + * Enable or disable strict requirement of semicolons. + * + * @see self::requireSemicolons() + * + * @param bool $requireSemicolons + */ + public function setRequireSemicolons(bool $requireSemicolons) + { + $this->requireSemicolons = (bool) $requireSemicolons; + } + + /** + * Check whether to require semicolons on all statements. + * + * By default, PsySH will automatically insert semicolons at the end of + * statements if they're missing. To strictly require semicolons, set + * `requireSemicolons` to true. + */ + public function requireSemicolons(): bool + { + return $this->requireSemicolons; + } + + /** + * Enable or disable strict types enforcement. + */ + public function setStrictTypes($strictTypes) + { + $this->strictTypes = (bool) $strictTypes; + } + + /** + * Check whether to enforce strict types. + */ + public function strictTypes(): bool + { + return $this->strictTypes; + } + + /** + * Enable or disable Unicode in PsySH specific output. + * + * Note that this does not disable Unicode output in general, it just makes + * it so PsySH won't output any itself. + * + * @param bool $useUnicode + */ + public function setUseUnicode(bool $useUnicode) + { + $this->useUnicode = (bool) $useUnicode; + } + + /** + * Check whether to use Unicode in PsySH specific output. + * + * Note that this does not disable Unicode output in general, it just makes + * it so PsySH won't output any itself. + */ + public function useUnicode(): bool + { + if (isset($this->useUnicode)) { + return $this->useUnicode; + } + + // @todo detect `chsh` != 65001 on Windows and return false + return true; + } + + /** + * Set the error logging level. + * + * @see self::errorLoggingLevel + * + * @param int $errorLoggingLevel + */ + public function setErrorLoggingLevel($errorLoggingLevel) + { + $this->errorLoggingLevel = (\E_ALL | \E_STRICT) & $errorLoggingLevel; + } + + /** + * Get the current error logging level. + * + * By default, PsySH will automatically log all errors, regardless of the + * current `error_reporting` level. + * + * Set `errorLoggingLevel` to 0 to prevent logging non-thrown errors. Set it + * to any valid error_reporting value to log only errors which match that + * level. + * + * http://php.net/manual/en/function.error-reporting.php + */ + public function errorLoggingLevel(): int + { + return $this->errorLoggingLevel; + } + + /** + * Set a CodeCleaner service instance. + * + * @param CodeCleaner $cleaner + */ + public function setCodeCleaner(CodeCleaner $cleaner) + { + $this->cleaner = $cleaner; + } + + /** + * Get a CodeCleaner service instance. + * + * If none has been explicitly defined, this will create a new instance. + */ + public function getCodeCleaner(): CodeCleaner + { + if (!isset($this->cleaner)) { + $this->cleaner = new CodeCleaner(null, null, null, $this->yolo(), $this->strictTypes()); + } + + return $this->cleaner; + } + + /** + * Enable or disable running PsySH without input validation. + * + * You don't want this. + */ + public function setYolo($yolo) + { + $this->yolo = (bool) $yolo; + } + + /** + * Check whether to disable input validation. + */ + public function yolo(): bool + { + return $this->yolo; + } + + /** + * Enable or disable tab completion. + * + * @param bool $useTabCompletion + */ + public function setUseTabCompletion(bool $useTabCompletion) + { + $this->useTabCompletion = (bool) $useTabCompletion; + } + + /** + * @deprecated Call `setUseTabCompletion` instead + * + * @param bool $useTabCompletion + */ + public function setTabCompletion(bool $useTabCompletion) + { + @\trigger_error('`setTabCompletion` is deprecated; call `setUseTabCompletion` instead.', \E_USER_DEPRECATED); + + $this->setUseTabCompletion($useTabCompletion); + } + + /** + * Check whether to use tab completion. + * + * If `setUseTabCompletion` has been set to true, but readline is not + * actually available, this will return false. + * + * @return bool True if the current Shell should use tab completion + */ + public function useTabCompletion(): bool + { + return isset($this->useTabCompletion) ? ($this->hasReadline && $this->useTabCompletion) : $this->hasReadline; + } + + /** + * @deprecated Call `useTabCompletion` instead + */ + public function getTabCompletion(): bool + { + @\trigger_error('`getTabCompletion` is deprecated; call `useTabCompletion` instead.', \E_USER_DEPRECATED); + + return $this->useTabCompletion(); + } + + /** + * Set the Shell Output service. + * + * @param ShellOutput $output + */ + public function setOutput(ShellOutput $output) + { + $this->output = $output; + $this->pipedOutput = null; // Reset cached pipe info + + if (isset($this->theme)) { + $output->setTheme($this->theme); + } + + $this->applyFormatterStyles(); + } + + /** + * Get a Shell Output service instance. + * + * If none has been explicitly provided, this will create a new instance + * with the configured verbosity and output pager supplied by self::getPager + * + * @see self::verbosity + * @see self::getPager + */ + public function getOutput(): ShellOutput + { + if (!isset($this->output)) { + $this->setOutput(new ShellOutput( + $this->getOutputVerbosity(), + null, + null, + $this->getPager() ?: null, + $this->theme() + )); + + // This is racy because `getOutputDecorated` needs access to the + // output stream to figure out if it's piped or not, so create it + // first, then update after we have a stream. + $decorated = $this->getOutputDecorated(); + if ($decorated !== null) { + $this->output->setDecorated($decorated); + } + } + + return $this->output; + } + + /** + * Get the decoration (i.e. color) setting for the Shell Output service. + * + * @return bool|null 3-state boolean corresponding to the current color mode + */ + public function getOutputDecorated() + { + switch ($this->colorMode()) { + case self::COLOR_MODE_FORCED: + return true; + case self::COLOR_MODE_DISABLED: + return false; + case self::COLOR_MODE_AUTO: + default: + return $this->outputIsPiped() ? false : null; + } + } + + /** + * Get the interactive setting for shell input. + */ + public function getInputInteractive(): bool + { + switch ($this->interactiveMode()) { + case self::INTERACTIVE_MODE_FORCED: + return true; + case self::INTERACTIVE_MODE_DISABLED: + return false; + case self::INTERACTIVE_MODE_AUTO: + default: + return !$this->inputIsPiped(); + } + } + + /** + * Set the OutputPager service. + * + * If a string is supplied, a ProcOutputPager will be used which shells out + * to the specified command. + * + * `cat` is special-cased to use the PassthruPager directly. + * + * @throws \InvalidArgumentException if $pager is not a string or OutputPager instance + * + * @param string|OutputPager|false $pager + */ + public function setPager($pager) + { + if ($pager === null || $pager === false || $pager === 'cat') { + $pager = false; + } + + if ($pager !== false && !\is_string($pager) && !$pager instanceof OutputPager) { + throw new \InvalidArgumentException('Unexpected pager instance'); + } + + $this->pager = $pager; + } + + /** + * Get an OutputPager instance or a command for an external Proc pager. + * + * If no Pager has been explicitly provided, and Pcntl is available, this + * will default to `cli.pager` ini value, falling back to `which less`. + * + * @return string|OutputPager|false + */ + public function getPager() + { + if (!isset($this->pager) && $this->usePcntl()) { + if (\getenv('TERM') === 'dumb') { + return false; + } + + if ($pager = \ini_get('cli.pager')) { + // use the default pager + $this->pager = $pager; + } elseif ($less = $this->configPaths->which('less')) { + // check for the presence of less... + $this->pager = $less.' -R -F -X'; + } + } + + return $this->pager; + } + + /** + * Set the Shell AutoCompleter service. + * + * @param AutoCompleter $autoCompleter + */ + public function setAutoCompleter(AutoCompleter $autoCompleter) + { + $this->autoCompleter = $autoCompleter; + } + + /** + * Get an AutoCompleter service instance. + */ + public function getAutoCompleter(): AutoCompleter + { + if (!isset($this->autoCompleter)) { + $this->autoCompleter = new AutoCompleter(); + } + + return $this->autoCompleter; + } + + /** + * @deprecated Nothing should be using this anymore + */ + public function getTabCompletionMatchers(): array + { + @\trigger_error('`getTabCompletionMatchers` is no longer used.', \E_USER_DEPRECATED); + + return []; + } + + /** + * Add tab completion matchers to the AutoCompleter. + * + * This will buffer new matchers in the event that the Shell has not yet + * been instantiated. This allows the user to specify matchers in their + * config rc file, despite the fact that their file is needed in the Shell + * constructor. + * + * @param array $matchers + */ + public function addMatchers(array $matchers) + { + $this->newMatchers = \array_merge($this->newMatchers, $matchers); + if (isset($this->shell)) { + $this->doAddMatchers(); + } + } + + /** + * Internal method for adding tab completion matchers. This will set any new + * matchers once a Shell is available. + */ + private function doAddMatchers() + { + if (!empty($this->newMatchers)) { + $this->shell->addMatchers($this->newMatchers); + $this->newMatchers = []; + } + } + + /** + * @deprecated Use `addMatchers` instead + * + * @param array $matchers + */ + public function addTabCompletionMatchers(array $matchers) + { + @\trigger_error('`addTabCompletionMatchers` is deprecated; call `addMatchers` instead.', \E_USER_DEPRECATED); + + $this->addMatchers($matchers); + } + + /** + * Add commands to the Shell. + * + * This will buffer new commands in the event that the Shell has not yet + * been instantiated. This allows the user to specify commands in their + * config rc file, despite the fact that their file is needed in the Shell + * constructor. + * + * @param array $commands + */ + public function addCommands(array $commands) + { + $this->newCommands = \array_merge($this->newCommands, $commands); + if (isset($this->shell)) { + $this->doAddCommands(); + } + } + + /** + * Internal method for adding commands. This will set any new commands once + * a Shell is available. + */ + private function doAddCommands() + { + if (!empty($this->newCommands)) { + $this->shell->addCommands($this->newCommands); + $this->newCommands = []; + } + } + + /** + * Set the Shell backreference and add any new commands to the Shell. + * + * @param Shell $shell + */ + public function setShell(Shell $shell) + { + $this->shell = $shell; + $this->doAddCommands(); + $this->doAddMatchers(); + } + + /** + * Set the PHP manual database file. + * + * This file should be an SQLite database generated from the phpdoc source + * with the `bin/build_manual` script. + * + * @param string $filename + */ + public function setManualDbFile(string $filename) + { + $this->manualDbFile = (string) $filename; + } + + /** + * Get the current PHP manual database file. + * + * @return string|null Default: '~/.local/share/psysh/php_manual.sqlite' + */ + public function getManualDbFile() + { + if (isset($this->manualDbFile)) { + return $this->manualDbFile; + } + + $files = $this->configPaths->dataFiles(['php_manual.sqlite']); + if (!empty($files)) { + if ($this->warnOnMultipleConfigs && \count($files) > 1) { + $msg = \sprintf('Multiple manual database files found: %s. Using %s', \implode(', ', $files), $files[0]); + \trigger_error($msg, \E_USER_NOTICE); + } + + return $this->manualDbFile = $files[0]; + } + } + + /** + * Get a PHP manual database connection. + * + * @return \PDO|null + */ + public function getManualDb() + { + if (!isset($this->manualDb)) { + $dbFile = $this->getManualDbFile(); + if ($dbFile !== null && \is_file($dbFile)) { + try { + $this->manualDb = new \PDO('sqlite:'.$dbFile); + } catch (\PDOException $e) { + if ($e->getMessage() === 'could not find driver') { + throw new RuntimeException('SQLite PDO driver not found', 0, $e); + } else { + throw $e; + } + } + } + } + + return $this->manualDb; + } + + /** + * Add an array of casters definitions. + * + * @param array $casters + */ + public function addCasters(array $casters) + { + $this->getPresenter()->addCasters($casters); + } + + /** + * Get the Presenter service. + */ + public function getPresenter(): Presenter + { + if (!isset($this->presenter)) { + $this->presenter = new Presenter($this->getOutput()->getFormatter(), $this->forceArrayIndexes()); + } + + return $this->presenter; + } + + /** + * Enable or disable warnings on multiple configuration or data files. + * + * @see self::warnOnMultipleConfigs() + * + * @param bool $warnOnMultipleConfigs + */ + public function setWarnOnMultipleConfigs(bool $warnOnMultipleConfigs) + { + $this->warnOnMultipleConfigs = (bool) $warnOnMultipleConfigs; + } + + /** + * Check whether to warn on multiple configuration or data files. + * + * By default, PsySH will use the file with highest precedence, and will + * silently ignore all others. With this enabled, a warning will be emitted + * (but not an exception thrown) if multiple configuration or data files + * are found. + * + * This will default to true in a future release, but is false for now. + */ + public function warnOnMultipleConfigs(): bool + { + return $this->warnOnMultipleConfigs; + } + + /** + * Set the current color mode. + * + * @throws \InvalidArgumentException if the color mode isn't auto, forced or disabled + * + * @param string $colorMode + */ + public function setColorMode(string $colorMode) + { + $validColorModes = [ + self::COLOR_MODE_AUTO, + self::COLOR_MODE_FORCED, + self::COLOR_MODE_DISABLED, + ]; + + if (!\in_array($colorMode, $validColorModes)) { + throw new \InvalidArgumentException('Invalid color mode: '.$colorMode); + } + + $this->colorMode = $colorMode; + } + + /** + * Get the current color mode. + */ + public function colorMode(): string + { + return $this->colorMode; + } + + /** + * Set the shell's interactive mode. + * + * @throws \InvalidArgumentException if interactive mode isn't disabled, forced, or auto + * + * @param string $interactiveMode + */ + public function setInteractiveMode(string $interactiveMode) + { + $validInteractiveModes = [ + self::INTERACTIVE_MODE_AUTO, + self::INTERACTIVE_MODE_FORCED, + self::INTERACTIVE_MODE_DISABLED, + ]; + + if (!\in_array($interactiveMode, $validInteractiveModes)) { + throw new \InvalidArgumentException('Invalid interactive mode: '.$interactiveMode); + } + + $this->interactiveMode = $interactiveMode; + } + + /** + * Get the current interactive mode. + */ + public function interactiveMode(): string + { + return $this->interactiveMode; + } + + /** + * Set an update checker service instance. + * + * @param Checker $checker + */ + public function setChecker(Checker $checker) + { + $this->checker = $checker; + } + + /** + * Get an update checker service instance. + * + * If none has been explicitly defined, this will create a new instance. + */ + public function getChecker(): Checker + { + if (!isset($this->checker)) { + $interval = $this->getUpdateCheck(); + switch ($interval) { + case Checker::ALWAYS: + $this->checker = new GitHubChecker(); + break; + + case Checker::DAILY: + case Checker::WEEKLY: + case Checker::MONTHLY: + $checkFile = $this->getUpdateCheckCacheFile(); + if ($checkFile === false) { + $this->checker = new NoopChecker(); + } else { + $this->checker = new IntervalChecker($checkFile, $interval); + } + break; + + case Checker::NEVER: + $this->checker = new NoopChecker(); + break; + } + } + + return $this->checker; + } + + /** + * Get the current update check interval. + * + * One of 'always', 'daily', 'weekly', 'monthly' or 'never'. If none is + * explicitly set, default to 'weekly'. + */ + public function getUpdateCheck(): string + { + return isset($this->updateCheck) ? $this->updateCheck : Checker::WEEKLY; + } + + /** + * Set the update check interval. + * + * @throws \InvalidArgumentException if the update check interval is unknown + * + * @param string $interval + */ + public function setUpdateCheck(string $interval) + { + $validIntervals = [ + Checker::ALWAYS, + Checker::DAILY, + Checker::WEEKLY, + Checker::MONTHLY, + Checker::NEVER, + ]; + + if (!\in_array($interval, $validIntervals)) { + throw new \InvalidArgumentException('Invalid update check interval: '.$interval); + } + + $this->updateCheck = $interval; + } + + /** + * Get a cache file path for the update checker. + * + * @return string|false Return false if config file/directory is not writable + */ + public function getUpdateCheckCacheFile() + { + return ConfigPaths::touchFileWithMkdir($this->configPaths->currentConfigDir().'/update_check.json'); + } + + /** + * Set the startup message. + * + * @param string $message + */ + public function setStartupMessage(string $message) + { + $this->startupMessage = $message; + } + + /** + * Get the startup message. + * + * @return string|null + */ + public function getStartupMessage() + { + return $this->startupMessage; + } + + /** + * Set the prompt. + * + * @deprecated The `prompt` configuration has been replaced by Themes and support will + * eventually be removed. In the meantime, prompt is applied first by the Theme, then overridden + * by any explicitly defined prompt. + * + * Note that providing a prompt but not a theme config will implicitly use the `classic` theme. + */ + public function setPrompt(string $prompt) + { + $this->prompt = $prompt; + + if (isset($this->theme)) { + $this->theme->setPrompt($prompt); + } + } + + /** + * Get the prompt. + * + * @return string|null + */ + public function getPrompt() + { + return $this->prompt; + } + + /** + * Get the force array indexes. + */ + public function forceArrayIndexes(): bool + { + return $this->forceArrayIndexes; + } + + /** + * Set the force array indexes. + * + * @param bool $forceArrayIndexes + */ + public function setForceArrayIndexes(bool $forceArrayIndexes) + { + $this->forceArrayIndexes = $forceArrayIndexes; + } + + /** + * Set the current output Theme. + * + * @param Theme|string|array $theme Theme (or Theme config) + */ + public function setTheme($theme) + { + if (!$theme instanceof Theme) { + $theme = new Theme($theme); + } + + $this->theme = $theme; + + if (isset($this->prompt)) { + $this->theme->setPrompt($this->prompt); + } + + if (isset($this->output)) { + $this->output->setTheme($theme); + $this->applyFormatterStyles(); + } + } + + /** + * Get the current output Theme. + */ + public function theme(): Theme + { + if (!isset($this->theme)) { + // If a prompt is explicitly set, and a theme is not, base it on the `classic` theme. + $this->theme = $this->prompt ? new Theme('classic') : new Theme(); + } + + if (isset($this->prompt)) { + $this->theme->setPrompt($this->prompt); + } + + return $this->theme; + } + + /** + * Set the shell output formatter styles. + * + * Accepts a map from style name to [fg, bg, options], for example: + * + * [ + * 'error' => ['white', 'red', ['bold']], + * 'warning' => ['black', 'yellow'], + * ] + * + * Foreground, background or options can be null, or even omitted entirely. + * + * @deprecated The `formatterStyles` configuration has been replaced by Themes and support will + * eventually be removed. In the meantime, styles are applied first by the Theme, then + * overridden by any explicitly defined formatter styles. + */ + public function setFormatterStyles(array $formatterStyles) + { + foreach ($formatterStyles as $name => $style) { + $this->formatterStyles[$name] = new OutputFormatterStyle(...$style); + } + + if (isset($this->output)) { + $this->applyFormatterStyles(); + } + } + + /** + * Internal method for applying output formatter style customization. + * + * This is called on initialization of the shell output, and again if the + * formatter styles config is updated. + * + * @deprecated The `formatterStyles` configuration has been replaced by Themes and support will + * eventually be removed. In the meantime, styles are applied first by the Theme, then + * overridden by any explicitly defined formatter styles. + */ + private function applyFormatterStyles() + { + $formatter = $this->output->getFormatter(); + foreach ($this->formatterStyles as $name => $style) { + $formatter->setStyle($name, $style); + } + + $errorFormatter = $this->output->getErrorOutput()->getFormatter(); + foreach (Theme::ERROR_STYLES as $name) { + if (isset($this->formatterStyles[$name])) { + $errorFormatter->setStyle($name, $this->formatterStyles[$name]); + } + } + } + + /** + * Get the configured output verbosity. + */ + public function verbosity(): string + { + return $this->verbosity; + } + + /** + * Set the shell output verbosity. + * + * Accepts OutputInterface verbosity constants. + * + * @throws \InvalidArgumentException if verbosity level is invalid + * + * @param string $verbosity + */ + public function setVerbosity(string $verbosity) + { + $validVerbosityLevels = [ + self::VERBOSITY_QUIET, + self::VERBOSITY_NORMAL, + self::VERBOSITY_VERBOSE, + self::VERBOSITY_VERY_VERBOSE, + self::VERBOSITY_DEBUG, + ]; + + if (!\in_array($verbosity, $validVerbosityLevels)) { + throw new \InvalidArgumentException('Invalid verbosity level: '.$verbosity); + } + + $this->verbosity = $verbosity; + + if (isset($this->output)) { + $this->output->setVerbosity($this->getOutputVerbosity()); + } + } + + /** + * Map the verbosity configuration to OutputInterface verbosity constants. + * + * @return int OutputInterface verbosity level + */ + public function getOutputVerbosity(): int + { + switch ($this->verbosity()) { + case self::VERBOSITY_QUIET: + return OutputInterface::VERBOSITY_QUIET; + case self::VERBOSITY_VERBOSE: + return OutputInterface::VERBOSITY_VERBOSE; + case self::VERBOSITY_VERY_VERBOSE: + return OutputInterface::VERBOSITY_VERY_VERBOSE; + case self::VERBOSITY_DEBUG: + return OutputInterface::VERBOSITY_DEBUG; + case self::VERBOSITY_NORMAL: + default: + return OutputInterface::VERBOSITY_NORMAL; + } + } + + /** + * Guess whether stdin is piped. + * + * This is mostly useful for deciding whether to use non-interactive mode. + */ + public function inputIsPiped(): bool + { + if ($this->pipedInput === null) { + $this->pipedInput = \defined('STDIN') && self::looksLikeAPipe(\STDIN); + } + + return $this->pipedInput; + } + + /** + * Guess whether shell output is piped. + * + * This is mostly useful for deciding whether to use non-decorated output. + */ + public function outputIsPiped(): bool + { + if ($this->pipedOutput === null) { + $this->pipedOutput = self::looksLikeAPipe($this->getOutput()->getStream()); + } + + return $this->pipedOutput; + } + + /** + * Guess whether an input or output stream is piped. + * + * @param resource|int $stream + */ + private static function looksLikeAPipe($stream): bool + { + if (\function_exists('posix_isatty')) { + return !\posix_isatty($stream); + } + + $stat = \fstat($stream); + $mode = $stat['mode'] & 0170000; + + return $mode === 0010000 || $mode === 0040000 || $mode === 0100000 || $mode === 0120000; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Context.php b/php/libraries/composer/vendor/psy/psysh/src/Context.php new file mode 100644 index 0000000..da698da --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Context.php @@ -0,0 +1,312 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * The Shell execution context. + * + * This class encapsulates the current variables, most recent return value and + * exception, and the current namespace. + */ +class Context +{ + private static $specialNames = ['_', '_e', '__out', '__psysh__', 'this']; + + // Include a very limited number of command-scope magic variable names. + // This might be a bad idea, but future me can sort it out. + private static $commandScopeNames = [ + '__function', '__method', '__class', '__namespace', '__file', '__line', '__dir', + ]; + + private $scopeVariables = []; + private $commandScopeVariables = []; + private $returnValue; + private $lastException; + private $lastStdout; + private $boundObject; + private $boundClass; + + /** + * Get a context variable. + * + * @throws \InvalidArgumentException If the variable is not found in the current context + * + * @param string $name + * + * @return mixed + */ + public function get(string $name) + { + switch ($name) { + case '_': + return $this->returnValue; + + case '_e': + if (isset($this->lastException)) { + return $this->lastException; + } + break; + + case '__out': + if (isset($this->lastStdout)) { + return $this->lastStdout; + } + break; + + case 'this': + if (isset($this->boundObject)) { + return $this->boundObject; + } + break; + + case '__function': + case '__method': + case '__class': + case '__namespace': + case '__file': + case '__line': + case '__dir': + if (\array_key_exists($name, $this->commandScopeVariables)) { + return $this->commandScopeVariables[$name]; + } + break; + + default: + if (\array_key_exists($name, $this->scopeVariables)) { + return $this->scopeVariables[$name]; + } + break; + } + + throw new \InvalidArgumentException('Unknown variable: $'.$name); + } + + /** + * Get all defined variables. + */ + public function getAll(): array + { + return \array_merge($this->scopeVariables, $this->getSpecialVariables()); + } + + /** + * Get all defined magic variables: $_, $_e, $__out, $__class, $__file, etc. + */ + public function getSpecialVariables(): array + { + $vars = [ + '_' => $this->returnValue, + ]; + + if (isset($this->lastException)) { + $vars['_e'] = $this->lastException; + } + + if (isset($this->lastStdout)) { + $vars['__out'] = $this->lastStdout; + } + + if (isset($this->boundObject)) { + $vars['this'] = $this->boundObject; + } + + return \array_merge($vars, $this->commandScopeVariables); + } + + /** + * Set all scope variables. + * + * This method does *not* set any of the magic variables: $_, $_e, $__out, + * $__class, $__file, etc. + * + * @param array $vars + */ + public function setAll(array $vars) + { + foreach (self::$specialNames as $key) { + unset($vars[$key]); + } + + foreach (self::$commandScopeNames as $key) { + unset($vars[$key]); + } + + $this->scopeVariables = $vars; + } + + /** + * Set the most recent return value. + * + * @param mixed $value + */ + public function setReturnValue($value) + { + $this->returnValue = $value; + } + + /** + * Get the most recent return value. + * + * @return mixed + */ + public function getReturnValue() + { + return $this->returnValue; + } + + /** + * Set the most recent Exception or Error. + * + * @param \Throwable $e + */ + public function setLastException(\Throwable $e) + { + $this->lastException = $e; + } + + /** + * Get the most recent Exception or Error. + * + * @throws \InvalidArgumentException If no Exception has been caught + * + * @return \Throwable|null + */ + public function getLastException() + { + if (!isset($this->lastException)) { + throw new \InvalidArgumentException('No most-recent exception'); + } + + return $this->lastException; + } + + /** + * Set the most recent output from evaluated code. + * + * @param string $lastStdout + */ + public function setLastStdout(string $lastStdout) + { + $this->lastStdout = $lastStdout; + } + + /** + * Get the most recent output from evaluated code. + * + * @throws \InvalidArgumentException If no output has happened yet + * + * @return string|null + */ + public function getLastStdout() + { + if (!isset($this->lastStdout)) { + throw new \InvalidArgumentException('No most-recent output'); + } + + return $this->lastStdout; + } + + /** + * Set the bound object ($this variable) for the interactive shell. + * + * Note that this unsets the bound class, if any exists. + * + * @param object|null $boundObject + */ + public function setBoundObject($boundObject) + { + $this->boundObject = \is_object($boundObject) ? $boundObject : null; + $this->boundClass = null; + } + + /** + * Get the bound object ($this variable) for the interactive shell. + * + * @return object|null + */ + public function getBoundObject() + { + return $this->boundObject; + } + + /** + * Set the bound class (self) for the interactive shell. + * + * Note that this unsets the bound object, if any exists. + * + * @param string|null $boundClass + */ + public function setBoundClass($boundClass) + { + $this->boundClass = (\is_string($boundClass) && $boundClass !== '') ? $boundClass : null; + $this->boundObject = null; + } + + /** + * Get the bound class (self) for the interactive shell. + * + * @return string|null + */ + public function getBoundClass() + { + return $this->boundClass; + } + + /** + * Set command-scope magic variables: $__class, $__file, etc. + * + * @param array $commandScopeVariables + */ + public function setCommandScopeVariables(array $commandScopeVariables) + { + $vars = []; + foreach ($commandScopeVariables as $key => $value) { + // kind of type check + if (\is_scalar($value) && \in_array($key, self::$commandScopeNames)) { + $vars[$key] = $value; + } + } + + $this->commandScopeVariables = $vars; + } + + /** + * Get command-scope magic variables: $__class, $__file, etc. + */ + public function getCommandScopeVariables(): array + { + return $this->commandScopeVariables; + } + + /** + * Get unused command-scope magic variables names: __class, __file, etc. + * + * This is used by the shell to unset old command-scope variables after a + * new batch is set. + * + * @return array Array of unused variable names + */ + public function getUnusedCommandScopeVariableNames(): array + { + return \array_diff(self::$commandScopeNames, \array_keys($this->commandScopeVariables)); + } + + /** + * Check whether a variable name is a magic variable. + * + * @param string $name + */ + public static function isSpecialVariableName(string $name): bool + { + return \in_array($name, self::$specialNames) || \in_array($name, self::$commandScopeNames); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ContextAware.php b/php/libraries/composer/vendor/psy/psysh/src/ContextAware.php new file mode 100644 index 0000000..83979ae --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ContextAware.php @@ -0,0 +1,28 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * ContextAware interface. + * + * This interface is used to pass the Shell's context into commands and such + * which require access to the current scope variables. + */ +interface ContextAware +{ + /** + * Set the Context reference. + * + * @param Context $context + */ + public function setContext(Context $context); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/EnvInterface.php b/php/libraries/composer/vendor/psy/psysh/src/EnvInterface.php new file mode 100644 index 0000000..31a738f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/EnvInterface.php @@ -0,0 +1,25 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * Abstraction around environment variables. + */ +interface EnvInterface +{ + /** + * Get an environment variable by name. + * + * @return string|null + */ + public function get(string $key); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/BreakException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/BreakException.php new file mode 100644 index 0000000..4061442 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/BreakException.php @@ -0,0 +1,49 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A break exception, used for halting the Psy Shell. + */ +class BreakException extends \Exception implements Exception +{ + private $rawMessage; + + /** + * {@inheritdoc} + */ + public function __construct($message = '', $code = 0, \Throwable $previous = null) + { + $this->rawMessage = $message; + parent::__construct(\sprintf('Exit: %s', $message), $code, $previous); + } + + /** + * Return a raw (unformatted) version of the error message. + */ + public function getRawMessage(): string + { + return $this->rawMessage; + } + + /** + * Throws BreakException. + * + * Since `throw` can not be inserted into arbitrary expressions, it wraps with function call. + * + * @throws BreakException + */ + public static function exitShell() + { + throw new self('Goodbye'); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/DeprecatedException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/DeprecatedException.php new file mode 100644 index 0000000..f326b53 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/DeprecatedException.php @@ -0,0 +1,20 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A DeprecatedException for Psy. + */ +class DeprecatedException extends RuntimeException +{ + // This space intentionally left blank. +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/ErrorException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/ErrorException.php new file mode 100644 index 0000000..26e886a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/ErrorException.php @@ -0,0 +1,112 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A custom error Exception for Psy with a formatted $message. + */ +class ErrorException extends \ErrorException implements Exception +{ + private $rawMessage; + + /** + * Construct a Psy ErrorException. + * + * @param string $message (default: "") + * @param int $code (default: 0) + * @param int $severity (default: 1) + * @param string|null $filename (default: null) + * @param int|null $lineno (default: null) + * @param \Throwable|null $previous (default: null) + */ + public function __construct($message = '', $code = 0, $severity = 1, $filename = null, $lineno = null, \Throwable $previous = null) + { + $this->rawMessage = $message; + + if (!empty($filename) && \preg_match('{Psy[/\\\\]ExecutionLoop}', $filename)) { + $filename = ''; + } + + switch ($severity) { + case \E_STRICT: + $type = 'Strict error'; + break; + + case \E_NOTICE: + case \E_USER_NOTICE: + $type = 'Notice'; + break; + + case \E_WARNING: + case \E_CORE_WARNING: + case \E_COMPILE_WARNING: + case \E_USER_WARNING: + $type = 'Warning'; + break; + + case \E_DEPRECATED: + case \E_USER_DEPRECATED: + $type = 'Deprecated'; + break; + + case \E_RECOVERABLE_ERROR: + $type = 'Recoverable fatal error'; + break; + + default: + $type = 'Error'; + break; + } + + $message = \sprintf('PHP %s: %s%s on line %d', $type, $message, $filename ? ' in '.$filename : '', $lineno); + parent::__construct($message, $code, $severity, $filename, $lineno, $previous); + } + + /** + * Get the raw (unformatted) message for this error. + */ + public function getRawMessage(): string + { + return $this->rawMessage; + } + + /** + * Helper for throwing an ErrorException. + * + * This allows us to: + * + * set_error_handler([ErrorException::class, 'throwException']); + * + * @throws self + * + * @param int $errno Error type + * @param string $errstr Message + * @param string $errfile Filename + * @param int $errline Line number + */ + public static function throwException($errno, $errstr, $errfile, $errline) + { + throw new self($errstr, 0, $errno, $errfile, $errline); + } + + /** + * Create an ErrorException from an Error. + * + * @deprecated PsySH no longer wraps Errors + * + * @param \Error $e + */ + public static function fromError(\Error $e) + { + @\trigger_error('PsySH no longer wraps Errors', \E_USER_DEPRECATED); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/Exception.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/Exception.php new file mode 100644 index 0000000..db79062 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/Exception.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * An interface for Psy Exceptions. + */ +interface Exception +{ + /** + * This is the only thing, really... + * + * Return a raw (unformatted) version of the message. + * + * @return string + */ + public function getRawMessage(); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/FatalErrorException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/FatalErrorException.php new file mode 100644 index 0000000..21b2234 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/FatalErrorException.php @@ -0,0 +1,50 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A "fatal error" Exception for Psy. + */ +class FatalErrorException extends \ErrorException implements Exception +{ + private $rawMessage; + + /** + * Create a fatal error. + * + * @param string $message (default: "") + * @param int $code (default: 0) + * @param int $severity (default: 1) + * @param string|null $filename (default: null) + * @param int|null $lineno (default: null) + * @param \Throwable|null $previous (default: null) + */ + public function __construct($message = '', $code = 0, $severity = 1, $filename = null, $lineno = null, \Throwable $previous = null) + { + // Since these are basically always PHP Parser Node line numbers, treat -1 as null. + if ($lineno === -1) { + $lineno = null; + } + + $this->rawMessage = $message; + $message = \sprintf('PHP Fatal error: %s in %s on line %d', $message, $filename ?: "eval()'d code", $lineno); + parent::__construct($message, $code, $severity, $filename, $lineno, $previous); + } + + /** + * Return a raw (unformatted) version of the error message. + */ + public function getRawMessage(): string + { + return $this->rawMessage; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/ParseErrorException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/ParseErrorException.php new file mode 100644 index 0000000..ee2e2d4 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/ParseErrorException.php @@ -0,0 +1,46 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A "parse error" Exception for Psy. + */ +class ParseErrorException extends \PhpParser\Error implements Exception +{ + /** + * Constructor! + * + * @param string $message (default: '') + * @param array|int $attributes Attributes of node/token where error occurred + * (or start line of error -- deprecated) + */ + public function __construct(string $message = '', $attributes = []) + { + $message = \sprintf('PHP Parse error: %s', $message); + + if (!\is_array($attributes)) { + $attributes = ['startLine' => $attributes]; + } + + parent::__construct($message, $attributes); + } + + /** + * Create a ParseErrorException from a PhpParser Error. + * + * @param \PhpParser\Error $e + */ + public static function fromParseError(\PhpParser\Error $e): self + { + return new self($e->getRawMessage(), $e->getAttributes()); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/RuntimeException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/RuntimeException.php new file mode 100644 index 0000000..6228813 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/RuntimeException.php @@ -0,0 +1,41 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A RuntimeException for Psy. + */ +class RuntimeException extends \RuntimeException implements Exception +{ + private $rawMessage; + + /** + * Make this bad boy. + * + * @param string $message (default: "") + * @param int $code (default: 0) + * @param \Throwable|null $previous (default: null) + */ + public function __construct(string $message = '', int $code = 0, \Throwable $previous = null) + { + $this->rawMessage = $message; + parent::__construct($message, $code, $previous); + } + + /** + * Return a raw (unformatted) version of the error message. + */ + public function getRawMessage(): string + { + return $this->rawMessage; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/ThrowUpException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/ThrowUpException.php new file mode 100644 index 0000000..b2b758e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/ThrowUpException.php @@ -0,0 +1,47 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +/** + * A throw-up exception, used for throwing an exception out of the Psy Shell. + */ +class ThrowUpException extends \Exception implements Exception +{ + /** + * {@inheritdoc} + */ + public function __construct(\Throwable $throwable) + { + $message = \sprintf("Throwing %s with message '%s'", \get_class($throwable), $throwable->getMessage()); + parent::__construct($message, $throwable->getCode(), $throwable); + } + + /** + * Return a raw (unformatted) version of the error message. + */ + public function getRawMessage(): string + { + return $this->getPrevious()->getMessage(); + } + + /** + * Create a ThrowUpException from a Throwable. + * + * @deprecated PsySH no longer wraps Throwables + * + * @param \Throwable $throwable + */ + public static function fromThrowable($throwable) + { + @\trigger_error('PsySH no longer wraps Throwables', \E_USER_DEPRECATED); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Exception/UnexpectedTargetException.php b/php/libraries/composer/vendor/psy/psysh/src/Exception/UnexpectedTargetException.php new file mode 100644 index 0000000..9d2b70d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Exception/UnexpectedTargetException.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Exception; + +class UnexpectedTargetException extends RuntimeException +{ + private $target; + + /** + * @param mixed $target + * @param string $message (default: "") + * @param int $code (default: 0) + * @param \Throwable|null $previous (default: null) + */ + public function __construct($target, string $message = '', int $code = 0, \Throwable $previous = null) + { + $this->target = $target; + parent::__construct($message, $code, $previous); + } + + /** + * @return mixed + */ + public function getTarget() + { + return $this->target; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ExecutionClosure.php b/php/libraries/composer/vendor/psy/psysh/src/ExecutionClosure.php new file mode 100644 index 0000000..837e931 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ExecutionClosure.php @@ -0,0 +1,91 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * The Psy Shell's execution scope. + */ +class ExecutionClosure +{ + const NOOP_INPUT = 'return null;'; + + private $closure; + + /** + * @param Shell $__psysh__ + */ + public function __construct(Shell $__psysh__) + { + $this->setClosure($__psysh__, function () use ($__psysh__) { + try { + // Restore execution scope variables + \extract($__psysh__->getScopeVariables(false)); + + // Buffer stdout; we'll need it later + \ob_start([$__psysh__, 'writeStdout'], 1); + + // Convert all errors to exceptions + \set_error_handler([$__psysh__, 'handleError']); + + // Evaluate the current code buffer + $_ = eval($__psysh__->onExecute($__psysh__->flushCode() ?: self::NOOP_INPUT)); + } catch (\Throwable $_e) { + // Clean up on our way out. + if (\ob_get_level() > 0) { + \ob_end_clean(); + } + + throw $_e; + } finally { + // Won't be needing this anymore + \restore_error_handler(); + } + + // Flush stdout (write to shell output, plus save to magic variable) + \ob_end_flush(); + + // Save execution scope variables for next time + $__psysh__->setScopeVariables(\get_defined_vars()); + + return $_; + }); + } + + /** + * Set the closure instance. + * + * @param Shell $shell + * @param \Closure $closure + */ + protected function setClosure(Shell $shell, \Closure $closure) + { + $that = $shell->getBoundObject(); + + if (\is_object($that)) { + $this->closure = $closure->bindTo($that, \get_class($that)); + } else { + $this->closure = $closure->bindTo(null, $shell->getBoundClass()); + } + } + + /** + * Go go gadget closure. + * + * @return mixed + */ + public function execute() + { + $closure = $this->closure; + + return $closure(); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/AbstractListener.php b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/AbstractListener.php new file mode 100644 index 0000000..8230c55 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/AbstractListener.php @@ -0,0 +1,62 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\ExecutionLoop; + +use Psy\Shell; + +/** + * Abstract Execution Loop Listener class. + */ +abstract class AbstractListener implements Listener +{ + /** + * {@inheritdoc} + */ + public function beforeRun(Shell $shell) + { + } + + /** + * {@inheritdoc} + */ + public function beforeLoop(Shell $shell) + { + } + + /** + * {@inheritdoc} + */ + public function onInput(Shell $shell, string $input) + { + } + + /** + * {@inheritdoc} + */ + public function onExecute(Shell $shell, string $code) + { + } + + /** + * {@inheritdoc} + */ + public function afterLoop(Shell $shell) + { + } + + /** + * {@inheritdoc} + */ + public function afterRun(Shell $shell) + { + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/Listener.php b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/Listener.php new file mode 100644 index 0000000..9f207f5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/Listener.php @@ -0,0 +1,81 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\ExecutionLoop; + +use Psy\Shell; + +/** + * Execution Loop Listener interface. + */ +interface Listener +{ + /** + * Determines whether this listener should be active. + */ + public static function isSupported(): bool; + + /** + * Called once before the REPL session starts. + * + * @param Shell $shell + */ + public function beforeRun(Shell $shell); + + /** + * Called at the start of each loop. + * + * @param Shell $shell + */ + public function beforeLoop(Shell $shell); + + /** + * Called on user input. + * + * Return a new string to override or rewrite user input. + * + * @param Shell $shell + * @param string $input + * + * @return string|null User input override + */ + public function onInput(Shell $shell, string $input); + + /** + * Called before executing user code. + * + * Return a new string to override or rewrite user code. + * + * Note that this is run *after* the Code Cleaner, so if you return invalid + * or unsafe PHP here, it'll be executed without any of the safety Code + * Cleaner provides. This comes with the big kid warranty :) + * + * @param Shell $shell + * @param string $code + * + * @return string|null User code override + */ + public function onExecute(Shell $shell, string $code); + + /** + * Called at the end of each loop. + * + * @param Shell $shell + */ + public function afterLoop(Shell $shell); + + /** + * Called once after the REPL session ends. + * + * @param Shell $shell + */ + public function afterRun(Shell $shell); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/ProcessForker.php b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/ProcessForker.php new file mode 100644 index 0000000..3d61693 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/ProcessForker.php @@ -0,0 +1,285 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\ExecutionLoop; + +use Psy\Context; +use Psy\Exception\BreakException; +use Psy\Shell; + +/** + * An execution loop listener that forks the process before executing code. + * + * This is awesome, as the session won't die prematurely if user input includes + * a fatal error, such as redeclaring a class or function. + */ +class ProcessForker extends AbstractListener +{ + private $savegame; + private $up; + + private static $pcntlFunctions = [ + 'pcntl_fork', + 'pcntl_signal_dispatch', + 'pcntl_signal', + 'pcntl_waitpid', + 'pcntl_wexitstatus', + ]; + + private static $posixFunctions = [ + 'posix_getpid', + 'posix_kill', + ]; + + /** + * Process forker is supported if pcntl and posix extensions are available. + */ + public static function isSupported(): bool + { + return self::isPcntlSupported() && !self::disabledPcntlFunctions() && self::isPosixSupported() && !self::disabledPosixFunctions(); + } + + /** + * Verify that all required pcntl functions are, in fact, available. + */ + public static function isPcntlSupported(): bool + { + foreach (self::$pcntlFunctions as $func) { + if (!\function_exists($func)) { + return false; + } + } + + return true; + } + + /** + * Check whether required pcntl functions are disabled. + */ + public static function disabledPcntlFunctions() + { + return self::checkDisabledFunctions(self::$pcntlFunctions); + } + + /** + * Verify that all required posix functions are, in fact, available. + */ + public static function isPosixSupported(): bool + { + foreach (self::$posixFunctions as $func) { + if (!\function_exists($func)) { + return false; + } + } + + return true; + } + + /** + * Check whether required posix functions are disabled. + */ + public static function disabledPosixFunctions() + { + return self::checkDisabledFunctions(self::$posixFunctions); + } + + private static function checkDisabledFunctions(array $functions): array + { + return \array_values(\array_intersect($functions, \array_map('strtolower', \array_map('trim', \explode(',', \ini_get('disable_functions')))))); + } + + /** + * Forks into a main and a loop process. + * + * The loop process will handle the evaluation of all instructions, then + * return its state via a socket upon completion. + * + * @param Shell $shell + */ + public function beforeRun(Shell $shell) + { + list($up, $down) = \stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + + if (!$up) { + throw new \RuntimeException('Unable to create socket pair'); + } + + $pid = \pcntl_fork(); + if ($pid < 0) { + throw new \RuntimeException('Unable to start execution loop'); + } elseif ($pid > 0) { + // This is the main thread. We'll just wait for a while. + + // We won't be needing this one. + \fclose($up); + + // Wait for a return value from the loop process. + $read = [$down]; + $write = null; + $except = null; + + do { + $n = @\stream_select($read, $write, $except, null); + + if ($n === 0) { + throw new \RuntimeException('Process timed out waiting for execution loop'); + } + + if ($n === false) { + $err = \error_get_last(); + if (!isset($err['message']) || \stripos($err['message'], 'interrupted system call') === false) { + $msg = $err['message'] ? + \sprintf('Error waiting for execution loop: %s', $err['message']) : + 'Error waiting for execution loop'; + throw new \RuntimeException($msg); + } + } + } while ($n < 1); + + $content = \stream_get_contents($down); + \fclose($down); + + if ($content) { + $shell->setScopeVariables(@\unserialize($content)); + } + + throw new BreakException('Exiting main thread'); + } + + // This is the child process. It's going to do all the work. + if (!@\cli_set_process_title('psysh (loop)')) { + // Fall back to `setproctitle` if that wasn't succesful. + if (\function_exists('setproctitle')) { + @\setproctitle('psysh (loop)'); + } + } + + // We won't be needing this one. + \fclose($down); + + // Save this; we'll need to close it in `afterRun` + $this->up = $up; + } + + /** + * Create a savegame at the start of each loop iteration. + * + * @param Shell $shell + */ + public function beforeLoop(Shell $shell) + { + $this->createSavegame(); + } + + /** + * Clean up old savegames at the end of each loop iteration. + * + * @param Shell $shell + */ + public function afterLoop(Shell $shell) + { + // if there's an old savegame hanging around, let's kill it. + if (isset($this->savegame)) { + \posix_kill($this->savegame, \SIGKILL); + \pcntl_signal_dispatch(); + } + } + + /** + * After the REPL session ends, send the scope variables back up to the main + * thread (if this is a child thread). + * + * @param Shell $shell + */ + public function afterRun(Shell $shell) + { + // We're a child thread. Send the scope variables back up to the main thread. + if (isset($this->up)) { + \fwrite($this->up, $this->serializeReturn($shell->getScopeVariables(false))); + \fclose($this->up); + + \posix_kill(\posix_getpid(), \SIGKILL); + } + } + + /** + * Create a savegame fork. + * + * The savegame contains the current execution state, and can be resumed in + * the event that the worker dies unexpectedly (for example, by encountering + * a PHP fatal error). + */ + private function createSavegame() + { + // the current process will become the savegame + $this->savegame = \posix_getpid(); + + $pid = \pcntl_fork(); + if ($pid < 0) { + throw new \RuntimeException('Unable to create savegame fork'); + } elseif ($pid > 0) { + // we're the savegame now... let's wait and see what happens + \pcntl_waitpid($pid, $status); + + // worker exited cleanly, let's bail + if (!\pcntl_wexitstatus($status)) { + \posix_kill(\posix_getpid(), \SIGKILL); + } + + // worker didn't exit cleanly, we'll need to have another go + $this->createSavegame(); + } + } + + /** + * Serialize all serializable return values. + * + * A naïve serialization will run into issues if there is a Closure or + * SimpleXMLElement (among other things) in scope when exiting the execution + * loop. We'll just ignore these unserializable classes, and serialize what + * we can. + * + * @param array $return + */ + private function serializeReturn(array $return): string + { + $serializable = []; + + foreach ($return as $key => $value) { + // No need to return magic variables + if (Context::isSpecialVariableName($key)) { + continue; + } + + // Resources and Closures don't error, but they don't serialize well either. + if (\is_resource($value) || $value instanceof \Closure) { + continue; + } + + if (\version_compare(\PHP_VERSION, '8.1', '>=') && $value instanceof \UnitEnum) { + // Enums defined in the REPL session can't be unserialized. + $ref = new \ReflectionObject($value); + if (\strpos($ref->getFileName(), ": eval()'d code") !== false) { + continue; + } + } + + try { + @\serialize($value); + $serializable[$key] = $value; + } catch (\Throwable $e) { + // we'll just ignore this one... + } + } + + return @\serialize($serializable); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/RunkitReloader.php b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/RunkitReloader.php new file mode 100644 index 0000000..987fb1c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoop/RunkitReloader.php @@ -0,0 +1,139 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\ExecutionLoop; + +use Psy\Exception\ParseErrorException; +use Psy\ParserFactory; +use Psy\Shell; + +/** + * A runkit-based code reloader, which is pretty much magic. + * + * @todo Remove RunkitReloader once we drop support for PHP 7.x :( + */ +class RunkitReloader extends AbstractListener +{ + private $parser; + private $timestamps = []; + + /** + * Only enabled if Runkit is installed. + */ + public static function isSupported(): bool + { + // runkit_import was removed in runkit7-4.0.0a1 + return \extension_loaded('runkit') || \extension_loaded('runkit7') && \function_exists('runkit_import'); + } + + /** + * Construct a Runkit Reloader. + */ + public function __construct() + { + $this->parser = (new ParserFactory())->createParser(); + } + + /** + * Reload code on input. + * + * @param Shell $shell + * @param string $input + */ + public function onInput(Shell $shell, string $input) + { + $this->reload($shell); + } + + /** + * Look through included files and update anything with a new timestamp. + * + * @param Shell $shell + */ + private function reload(Shell $shell) + { + \clearstatcache(); + $modified = []; + + foreach (\get_included_files() as $file) { + $timestamp = \filemtime($file); + + if (!isset($this->timestamps[$file])) { + $this->timestamps[$file] = $timestamp; + continue; + } + + if ($this->timestamps[$file] === $timestamp) { + continue; + } + + if (!$this->lintFile($file)) { + $msg = \sprintf('Modified file "%s" could not be reloaded', $file); + $shell->writeException(new ParseErrorException($msg)); + continue; + } + + $modified[] = $file; + $this->timestamps[$file] = $timestamp; + } + + // switch (count($modified)) { + // case 0: + // return; + + // case 1: + // printf("Reloading modified file: \"%s\"\n", str_replace(getcwd(), '.', $file)); + // break; + + // default: + // printf("Reloading %d modified files\n", count($modified)); + // break; + // } + + foreach ($modified as $file) { + $flags = ( + RUNKIT_IMPORT_FUNCTIONS | + RUNKIT_IMPORT_CLASSES | + RUNKIT_IMPORT_CLASS_METHODS | + RUNKIT_IMPORT_CLASS_CONSTS | + RUNKIT_IMPORT_CLASS_PROPS | + RUNKIT_IMPORT_OVERRIDE + ); + + // these two const cannot be used with RUNKIT_IMPORT_OVERRIDE in runkit7 + if (\extension_loaded('runkit7')) { + $flags &= ~RUNKIT_IMPORT_CLASS_PROPS & ~RUNKIT_IMPORT_CLASS_STATIC_PROPS; + runkit7_import($file, $flags); + } else { + runkit_import($file, $flags); + } + } + } + + /** + * Should this file be re-imported? + * + * Use PHP-Parser to ensure that the file is valid PHP. + * + * @param string $file + */ + private function lintFile(string $file): bool + { + // first try to parse it + try { + $this->parser->parse(\file_get_contents($file)); + } catch (\Throwable $e) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoopClosure.php b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoopClosure.php new file mode 100644 index 0000000..28c6561 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ExecutionLoopClosure.php @@ -0,0 +1,88 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +use Psy\Exception\BreakException; +use Psy\Exception\ThrowUpException; + +/** + * The Psy Shell's execution loop scope. + * + * @todo Switch ExecutionClosure to a generator and get rid of the duplicate closure implementations? + */ +class ExecutionLoopClosure extends ExecutionClosure +{ + /** + * @param Shell $__psysh__ + */ + public function __construct(Shell $__psysh__) + { + $this->setClosure($__psysh__, function () use ($__psysh__) { + // Restore execution scope variables + \extract($__psysh__->getScopeVariables(false)); + + while (true) { + $__psysh__->beforeLoop(); + + try { + $__psysh__->getInput(); + + try { + // Pull in any new execution scope variables + if ($__psysh__->getLastExecSuccess()) { + \extract($__psysh__->getScopeVariablesDiff(\get_defined_vars())); + } + + // Buffer stdout; we'll need it later + \ob_start([$__psysh__, 'writeStdout'], 1); + + // Convert all errors to exceptions + \set_error_handler([$__psysh__, 'handleError']); + + // Evaluate the current code buffer + $_ = eval($__psysh__->onExecute($__psysh__->flushCode() ?: ExecutionClosure::NOOP_INPUT)); + } catch (\Throwable $_e) { + // Clean up on our way out. + if (\ob_get_level() > 0) { + \ob_end_clean(); + } + + throw $_e; + } finally { + // Won't be needing this anymore + \restore_error_handler(); + } + + // Flush stdout (write to shell output, plus save to magic variable) + \ob_end_flush(); + + // Save execution scope variables for next time + $__psysh__->setScopeVariables(\get_defined_vars()); + + $__psysh__->writeReturnValue($_); + } catch (BreakException $_e) { + $__psysh__->writeException($_e); + + return; + } catch (ThrowUpException $_e) { + $__psysh__->writeException($_e); + + throw $_e; + } catch (\Throwable $_e) { + $__psysh__->writeException($_e); + } + + $__psysh__->afterLoop(); + } + }); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Formatter/CodeFormatter.php b/php/libraries/composer/vendor/psy/psysh/src/Formatter/CodeFormatter.php new file mode 100644 index 0000000..aa70f1b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Formatter/CodeFormatter.php @@ -0,0 +1,317 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Formatter; + +use Psy\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * A pretty-printer for code. + */ +class CodeFormatter implements ReflectorFormatter +{ + const LINE_MARKER = ' <urgent>></urgent> '; + const NO_LINE_MARKER = ' '; + + const HIGHLIGHT_DEFAULT = 'default'; + const HIGHLIGHT_KEYWORD = 'keyword'; + + const HIGHLIGHT_PUBLIC = 'public'; + const HIGHLIGHT_PROTECTED = 'protected'; + const HIGHLIGHT_PRIVATE = 'private'; + + const HIGHLIGHT_CONST = 'const'; + const HIGHLIGHT_NUMBER = 'number'; + const HIGHLIGHT_STRING = 'string'; + const HIGHLIGHT_COMMENT = 'code_comment'; + const HIGHLIGHT_INLINE_HTML = 'inline_html'; + + private static $tokenMap = [ + // Not highlighted + \T_OPEN_TAG => self::HIGHLIGHT_DEFAULT, + \T_OPEN_TAG_WITH_ECHO => self::HIGHLIGHT_DEFAULT, + \T_CLOSE_TAG => self::HIGHLIGHT_DEFAULT, + \T_STRING => self::HIGHLIGHT_DEFAULT, + \T_VARIABLE => self::HIGHLIGHT_DEFAULT, + \T_NS_SEPARATOR => self::HIGHLIGHT_DEFAULT, + + // Visibility + \T_PUBLIC => self::HIGHLIGHT_PUBLIC, + \T_PROTECTED => self::HIGHLIGHT_PROTECTED, + \T_PRIVATE => self::HIGHLIGHT_PRIVATE, + + // Constants + \T_DIR => self::HIGHLIGHT_CONST, + \T_FILE => self::HIGHLIGHT_CONST, + \T_METHOD_C => self::HIGHLIGHT_CONST, + \T_NS_C => self::HIGHLIGHT_CONST, + \T_LINE => self::HIGHLIGHT_CONST, + \T_CLASS_C => self::HIGHLIGHT_CONST, + \T_FUNC_C => self::HIGHLIGHT_CONST, + \T_TRAIT_C => self::HIGHLIGHT_CONST, + + // Types + \T_DNUMBER => self::HIGHLIGHT_NUMBER, + \T_LNUMBER => self::HIGHLIGHT_NUMBER, + \T_ENCAPSED_AND_WHITESPACE => self::HIGHLIGHT_STRING, + \T_CONSTANT_ENCAPSED_STRING => self::HIGHLIGHT_STRING, + + // Comments + \T_COMMENT => self::HIGHLIGHT_COMMENT, + \T_DOC_COMMENT => self::HIGHLIGHT_COMMENT, + + // @todo something better here? + \T_INLINE_HTML => self::HIGHLIGHT_INLINE_HTML, + ]; + + /** + * Format the code represented by $reflector for shell output. + * + * @param \Reflector $reflector + * + * @return string formatted code + */ + public static function format(\Reflector $reflector): string + { + if (self::isReflectable($reflector)) { + if ($code = @\file_get_contents($reflector->getFileName())) { + return self::formatCode($code, self::getStartLine($reflector), $reflector->getEndLine()); + } + } + + throw new RuntimeException('Source code unavailable'); + } + + /** + * Format code for shell output. + * + * Optionally, restrict by $startLine and $endLine line numbers, or pass $markLine to add a line marker. + * + * @param string $code + * @param int $startLine + * @param int|null $endLine + * @param int|null $markLine + * + * @return string formatted code + */ + public static function formatCode(string $code, int $startLine = 1, int $endLine = null, int $markLine = null): string + { + $spans = self::tokenizeSpans($code); + $lines = self::splitLines($spans, $startLine, $endLine); + $lines = self::formatLines($lines); + $lines = self::numberLines($lines, $markLine); + + return \implode('', \iterator_to_array($lines)); + } + + /** + * Get the start line for a given Reflector. + * + * Tries to incorporate doc comments if possible. + * + * This is typehinted as \Reflector but we've narrowed the input via self::isReflectable already. + * + * @param \ReflectionClass|\ReflectionFunctionAbstract $reflector + */ + private static function getStartLine(\Reflector $reflector): int + { + $startLine = $reflector->getStartLine(); + + if ($docComment = $reflector->getDocComment()) { + $startLine -= \preg_match_all('/(\r\n?|\n)/', $docComment) + 1; + } + + return \max($startLine, 1); + } + + /** + * Split code into highlight spans. + * + * Tokenize via \token_get_all, then map these tokens to internal highlight types, combining + * adjacent spans of the same highlight type. + * + * @todo consider switching \token_get_all() out for PHP-Parser-based formatting at some point. + * + * @param string $code + * + * @return \Generator [$spanType, $spanText] highlight spans + */ + private static function tokenizeSpans(string $code): \Generator + { + $spanType = null; + $buffer = ''; + + foreach (\token_get_all($code) as $token) { + $nextType = self::nextHighlightType($token, $spanType); + $spanType = $spanType ?: $nextType; + + if ($spanType !== $nextType) { + yield [$spanType, $buffer]; + $spanType = $nextType; + $buffer = ''; + } + + $buffer .= \is_array($token) ? $token[1] : $token; + } + + if ($spanType !== null && $buffer !== '') { + yield [$spanType, $buffer]; + } + } + + /** + * Given a token and the current highlight span type, compute the next type. + * + * @param array|string $token \token_get_all token + * @param string|null $currentType + * + * @return string|null + */ + private static function nextHighlightType($token, $currentType) + { + if ($token === '"') { + return self::HIGHLIGHT_STRING; + } + + if (\is_array($token)) { + if ($token[0] === \T_WHITESPACE) { + return $currentType; + } + + if (\array_key_exists($token[0], self::$tokenMap)) { + return self::$tokenMap[$token[0]]; + } + } + + return self::HIGHLIGHT_KEYWORD; + } + + /** + * Group highlight spans into an array of lines. + * + * Optionally, restrict by start and end line numbers. + * + * @param \Generator $spans as [$spanType, $spanText] pairs + * @param int $startLine + * @param int|null $endLine + * + * @return \Generator lines, each an array of [$spanType, $spanText] pairs + */ + private static function splitLines(\Generator $spans, int $startLine = 1, int $endLine = null): \Generator + { + $lineNum = 1; + $buffer = []; + + foreach ($spans as list($spanType, $spanText)) { + foreach (\preg_split('/(\r\n?|\n)/', $spanText) as $index => $spanLine) { + if ($index > 0) { + if ($lineNum >= $startLine) { + yield $lineNum => $buffer; + } + + $lineNum++; + $buffer = []; + + if ($endLine !== null && $lineNum > $endLine) { + return; + } + } + + if ($spanLine !== '') { + $buffer[] = [$spanType, $spanLine]; + } + } + } + + if (!empty($buffer)) { + yield $lineNum => $buffer; + } + } + + /** + * Format lines of highlight spans for shell output. + * + * @param \Generator $spanLines lines, each an array of [$spanType, $spanText] pairs + * + * @return \Generator Formatted lines + */ + private static function formatLines(\Generator $spanLines): \Generator + { + foreach ($spanLines as $lineNum => $spanLine) { + $line = ''; + + foreach ($spanLine as list($spanType, $spanText)) { + if ($spanType === self::HIGHLIGHT_DEFAULT) { + $line .= OutputFormatter::escape($spanText); + } else { + $line .= \sprintf('<%s>%s</%s>', $spanType, OutputFormatter::escape($spanText), $spanType); + } + } + + yield $lineNum => $line.\PHP_EOL; + } + } + + /** + * Prepend line numbers to formatted lines. + * + * Lines must be in an associative array with the correct keys in order to be numbered properly. + * + * Optionally, pass $markLine to add a line marker. + * + * @param \Generator $lines Formatted lines + * @param int|null $markLine + * + * @return \Generator Numbered, formatted lines + */ + private static function numberLines(\Generator $lines, int $markLine = null): \Generator + { + $lines = \iterator_to_array($lines); + + // Figure out how much space to reserve for line numbers. + \end($lines); + $pad = \strlen(\key($lines)); + + // If $markLine is before or after our line range, don't bother reserving space for the marker. + if ($markLine !== null) { + if ($markLine > \key($lines)) { + $markLine = null; + } + + \reset($lines); + if ($markLine < \key($lines)) { + $markLine = null; + } + } + + foreach ($lines as $lineNum => $line) { + $mark = ''; + if ($markLine !== null) { + $mark = ($markLine === $lineNum) ? self::LINE_MARKER : self::NO_LINE_MARKER; + } + + yield \sprintf("%s<aside>%{$pad}s</aside>: %s", $mark, $lineNum, $line); + } + } + + /** + * Check whether a Reflector instance is reflectable by this formatter. + * + * @phpstan-assert-if-true \ReflectionClass|\ReflectionFunctionAbstract $reflector + * + * @param \Reflector $reflector + */ + private static function isReflectable(\Reflector $reflector): bool + { + return ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionFunctionAbstract) && \is_file($reflector->getFileName()); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Formatter/DocblockFormatter.php b/php/libraries/composer/vendor/psy/psysh/src/Formatter/DocblockFormatter.php new file mode 100644 index 0000000..282f463 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Formatter/DocblockFormatter.php @@ -0,0 +1,166 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Formatter; + +use Psy\Util\Docblock; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * A pretty-printer for docblocks. + */ +class DocblockFormatter implements ReflectorFormatter +{ + private static $vectorParamTemplates = [ + 'type' => 'info', + 'var' => 'strong', + ]; + + /** + * Format a docblock. + * + * @param \Reflector $reflector + * + * @return string Formatted docblock + */ + public static function format(\Reflector $reflector): string + { + $docblock = new Docblock($reflector); + $chunks = []; + + if (!empty($docblock->desc)) { + $chunks[] = '<comment>Description:</comment>'; + $chunks[] = self::indent(OutputFormatter::escape($docblock->desc), ' '); + $chunks[] = ''; + } + + if (!empty($docblock->tags)) { + foreach ($docblock::$vectors as $name => $vector) { + if (isset($docblock->tags[$name])) { + $chunks[] = \sprintf('<comment>%s:</comment>', self::inflect($name)); + $chunks[] = self::formatVector($vector, $docblock->tags[$name]); + $chunks[] = ''; + } + } + + $tags = self::formatTags(\array_keys($docblock::$vectors), $docblock->tags); + if (!empty($tags)) { + $chunks[] = $tags; + $chunks[] = ''; + } + } + + return \rtrim(\implode("\n", $chunks)); + } + + /** + * Format a docblock vector, for example, `@throws`, `@param`, or `@return`. + * + * @see DocBlock::$vectors + * + * @param array $vector + * @param array $lines + */ + private static function formatVector(array $vector, array $lines): string + { + $template = [' ']; + foreach ($vector as $type) { + $max = 0; + foreach ($lines as $line) { + $chunk = $line[$type]; + $cur = empty($chunk) ? 0 : \strlen($chunk) + 1; + if ($cur > $max) { + $max = $cur; + } + } + + $template[] = self::getVectorParamTemplate($type, $max); + } + $template = \implode(' ', $template); + + return \implode("\n", \array_map(function ($line) use ($template) { + $escaped = \array_map(function ($l) { + if ($l === null) { + return ''; + } + + return OutputFormatter::escape($l); + }, $line); + + return \rtrim(\vsprintf($template, $escaped)); + }, $lines)); + } + + /** + * Format docblock tags. + * + * @param array $skip Tags to exclude + * @param array $tags Tags to format + * + * @return string formatted tags + */ + private static function formatTags(array $skip, array $tags): string + { + $chunks = []; + + foreach ($tags as $name => $values) { + if (\in_array($name, $skip)) { + continue; + } + + foreach ($values as $value) { + $chunks[] = \sprintf('<comment>%s%s</comment> %s', self::inflect($name), empty($value) ? '' : ':', OutputFormatter::escape($value)); + } + + $chunks[] = ''; + } + + return \implode("\n", $chunks); + } + + /** + * Get a docblock vector template. + * + * @param string $type Vector type + * @param int $max Pad width + */ + private static function getVectorParamTemplate(string $type, int $max): string + { + if (!isset(self::$vectorParamTemplates[$type])) { + return \sprintf('%%-%ds', $max); + } + + return \sprintf('<%s>%%-%ds</%s>', self::$vectorParamTemplates[$type], $max, self::$vectorParamTemplates[$type]); + } + + /** + * Indent a string. + * + * @param string $text String to indent + * @param string $indent (default: ' ') + */ + private static function indent(string $text, string $indent = ' '): string + { + return $indent.\str_replace("\n", "\n".$indent, $text); + } + + /** + * Convert underscored or whitespace separated words into sentence case. + * + * @param string $text + */ + private static function inflect(string $text): string + { + $words = \trim(\preg_replace('/[\s_-]+/', ' ', \preg_replace('/([a-z])([A-Z])/', '$1 $2', $text))); + + return \implode(' ', \array_map('ucfirst', \explode(' ', $words))); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Formatter/ReflectorFormatter.php b/php/libraries/composer/vendor/psy/psysh/src/Formatter/ReflectorFormatter.php new file mode 100644 index 0000000..02f426c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Formatter/ReflectorFormatter.php @@ -0,0 +1,23 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Formatter; + +/** + * Reflector formatter interface. + */ +interface ReflectorFormatter +{ + /** + * @param \Reflector $reflector + */ + public static function format(\Reflector $reflector): string; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Formatter/SignatureFormatter.php b/php/libraries/composer/vendor/psy/psysh/src/Formatter/SignatureFormatter.php new file mode 100644 index 0000000..182816b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Formatter/SignatureFormatter.php @@ -0,0 +1,358 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Formatter; + +use Psy\Reflection\ReflectionConstant; +use Psy\Reflection\ReflectionLanguageConstruct; +use Psy\Util\Json; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * An abstract representation of a function, class or property signature. + */ +class SignatureFormatter implements ReflectorFormatter +{ + /** + * Format a signature for the given reflector. + * + * Defers to subclasses to do the actual formatting. + * + * @param \Reflector $reflector + * + * @return string Formatted signature + */ + public static function format(\Reflector $reflector): string + { + switch (true) { + case $reflector instanceof \ReflectionFunction: + case $reflector instanceof ReflectionLanguageConstruct: + return self::formatFunction($reflector); + + case $reflector instanceof \ReflectionClass: + // this case also covers \ReflectionObject + return self::formatClass($reflector); + + case $reflector instanceof \ReflectionClassConstant: + return self::formatClassConstant($reflector); + + case $reflector instanceof \ReflectionMethod: + return self::formatMethod($reflector); + + case $reflector instanceof \ReflectionProperty: + return self::formatProperty($reflector); + + case $reflector instanceof ReflectionConstant: + return self::formatConstant($reflector); + + default: + throw new \InvalidArgumentException('Unexpected Reflector class: '.\get_class($reflector)); + } + } + + /** + * Print the signature name. + * + * @param \ReflectionClass|\ReflectionClassConstant|\ReflectionFunctionAbstract $reflector + * + * @return string Formatted name + */ + public static function formatName(\Reflector $reflector): string + { + return $reflector->getName(); + } + + /** + * Print the method, property or class modifiers. + * + * @param \ReflectionMethod|\ReflectionProperty|\ReflectionClass $reflector + * + * @return string Formatted modifiers + */ + private static function formatModifiers(\Reflector $reflector): string + { + return \implode(' ', \array_map(function ($modifier) { + return \sprintf('<keyword>%s</keyword>', $modifier); + }, \Reflection::getModifierNames($reflector->getModifiers()))); + } + + /** + * Format a class signature. + * + * @param \ReflectionClass $reflector + * + * @return string Formatted signature + */ + private static function formatClass(\ReflectionClass $reflector): string + { + $chunks = []; + + if ($modifiers = self::formatModifiers($reflector)) { + $chunks[] = $modifiers; + } + + if ($reflector->isTrait()) { + $chunks[] = 'trait'; + } else { + $chunks[] = $reflector->isInterface() ? 'interface' : 'class'; + } + + $chunks[] = \sprintf('<class>%s</class>', self::formatName($reflector)); + + if ($parent = $reflector->getParentClass()) { + $chunks[] = 'extends'; + $chunks[] = \sprintf('<class>%s</class>', $parent->getName()); + } + + $interfaces = $reflector->getInterfaceNames(); + if (!empty($interfaces)) { + \sort($interfaces); + + $chunks[] = $reflector->isInterface() ? 'extends' : 'implements'; + $chunks[] = \implode(', ', \array_map(function ($name) { + return \sprintf('<class>%s</class>', $name); + }, $interfaces)); + } + + return \implode(' ', $chunks); + } + + /** + * Format a constant signature. + * + * @param \ReflectionClassConstant $reflector + * + * @return string Formatted signature + */ + private static function formatClassConstant($reflector): string + { + $value = $reflector->getValue(); + $style = self::getTypeStyle($value); + + return \sprintf( + '<keyword>const</keyword> <const>%s</const> = <%s>%s</%s>', + self::formatName($reflector), + $style, + OutputFormatter::escape(Json::encode($value)), + $style + ); + } + + /** + * Format a constant signature. + * + * @param ReflectionConstant $reflector + * + * @return string Formatted signature + */ + private static function formatConstant(ReflectionConstant $reflector): string + { + $value = $reflector->getValue(); + $style = self::getTypeStyle($value); + + return \sprintf( + '<keyword>define</keyword>(<string>%s</string>, <%s>%s</%s>)', + OutputFormatter::escape(Json::encode($reflector->getName())), + $style, + OutputFormatter::escape(Json::encode($value)), + $style + ); + } + + /** + * Helper for getting output style for a given value's type. + * + * @param mixed $value + */ + private static function getTypeStyle($value): string + { + if (\is_int($value) || \is_float($value)) { + return 'number'; + } elseif (\is_string($value)) { + return 'string'; + } elseif (\is_bool($value) || $value === null) { + return 'bool'; + } else { + return 'strong'; // @codeCoverageIgnore + } + } + + /** + * Format a property signature. + * + * @param \ReflectionProperty $reflector + * + * @return string Formatted signature + */ + private static function formatProperty(\ReflectionProperty $reflector): string + { + return \sprintf( + '%s <strong>$%s</strong>', + self::formatModifiers($reflector), + $reflector->getName() + ); + } + + /** + * Format a function signature. + * + * @param \ReflectionFunction $reflector + * + * @return string Formatted signature + */ + private static function formatFunction(\ReflectionFunctionAbstract $reflector): string + { + return \sprintf( + '<keyword>function</keyword> %s<function>%s</function>(%s)%s', + $reflector->returnsReference() ? '&' : '', + self::formatName($reflector), + \implode(', ', self::formatFunctionParams($reflector)), + self::formatFunctionReturnType($reflector) + ); + } + + /** + * Format a function signature's return type (if available). + * + * @param \ReflectionFunctionAbstract $reflector + * + * @return string Formatted return type + */ + private static function formatFunctionReturnType(\ReflectionFunctionAbstract $reflector): string + { + if (!\method_exists($reflector, 'hasReturnType') || !$reflector->hasReturnType()) { + return ''; + } + + return \sprintf(': %s', self::formatReflectionType($reflector->getReturnType(), true)); + } + + /** + * Format a method signature. + * + * @param \ReflectionMethod $reflector + * + * @return string Formatted signature + */ + private static function formatMethod(\ReflectionMethod $reflector): string + { + return \sprintf( + '%s %s', + self::formatModifiers($reflector), + self::formatFunction($reflector) + ); + } + + /** + * Print the function params. + * + * @param \ReflectionFunctionAbstract $reflector + * + * @return array + */ + private static function formatFunctionParams(\ReflectionFunctionAbstract $reflector): array + { + $params = []; + foreach ($reflector->getParameters() as $param) { + $hint = ''; + try { + if (\method_exists($param, 'getType')) { + // Only include the inquisitive nullable type iff param default value is not null. + $defaultIsNull = $param->isOptional() && $param->isDefaultValueAvailable() && $param->getDefaultValue() === null; + $hint = self::formatReflectionType($param->getType(), !$defaultIsNull); + } else { + if ($param->isArray()) { + $hint = '<keyword>array</keyword>'; + } elseif ($class = $param->getClass()) { + $hint = \sprintf('<class>%s</class>', $class->getName()); + } + } + } catch (\Throwable $e) { + // sometimes we just don't know... + // bad class names, or autoloaded classes that haven't been loaded yet, or whathaveyou. + // come to think of it, the only time I've seen this is with the intl extension. + + // Hax: we'll try to extract it :P + + // @codeCoverageIgnoreStart + $chunks = \explode('$'.$param->getName(), (string) $param); + $chunks = \explode(' ', \trim($chunks[0])); + $guess = \end($chunks); + + $hint = \sprintf('<urgent>%s</urgent>', OutputFormatter::escape($guess)); + // @codeCoverageIgnoreEnd + } + + if ($param->isOptional()) { + if (!$param->isDefaultValueAvailable()) { + $value = 'unknown'; + $typeStyle = 'urgent'; + } else { + $value = $param->getDefaultValue(); + $typeStyle = self::getTypeStyle($value); + $value = \is_array($value) ? '[]' : ($value === null ? 'null' : \var_export($value, true)); + } + $default = \sprintf(' = <%s>%s</%s>', $typeStyle, OutputFormatter::escape($value), $typeStyle); + } else { + $default = ''; + } + + $params[] = \sprintf( + '%s%s%s<strong>$%s</strong>%s', + $param->isPassedByReference() ? '&' : '', + $hint, + $hint !== '' ? ' ' : '', + $param->getName(), + $default + ); + } + + return $params; + } + + /** + * Print function param or return type(s). + * + * @param \ReflectionType $type + */ + private static function formatReflectionType(?\ReflectionType $type, bool $indicateNullable): string + { + if ($type === null) { + return ''; + } + + if ($type instanceof \ReflectionUnionType) { + $delimeter = '|'; + } elseif ($type instanceof \ReflectionIntersectionType) { + $delimeter = '&'; + } else { + return self::formatReflectionNamedType($type, $indicateNullable); + } + + $formattedTypes = []; + foreach ($type->getTypes() as $namedType) { + $formattedTypes[] = self::formatReflectionNamedType($namedType, $indicateNullable); + } + + return \implode($delimeter, $formattedTypes); + } + + /** + * Print a single named type. + */ + private static function formatReflectionNamedType(\ReflectionNamedType $type, bool $indicateNullable): string + { + $typeStyle = $type->isBuiltin() ? 'keyword' : 'class'; + $nullable = $indicateNullable && $type->allowsNull() ? '?' : ''; + + return \sprintf('<%s>%s%s</%s>', $typeStyle, $nullable, OutputFormatter::escape($type->getName()), $typeStyle); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Formatter/TraceFormatter.php b/php/libraries/composer/vendor/psy/psysh/src/Formatter/TraceFormatter.php new file mode 100644 index 0000000..f985922 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Formatter/TraceFormatter.php @@ -0,0 +1,96 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Formatter; + +use Psy\Input\FilterOptions; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * Output formatter for exception traces. + */ +class TraceFormatter +{ + /** + * Format the trace of the given exception. + * + * @param \Throwable $throwable The error or exception with a backtrace + * @param FilterOptions $filter (default: null) + * @param int $count (default: PHP_INT_MAX) + * @param bool $includePsy (default: true) + * + * @return string[] Formatted stacktrace lines + */ + public static function formatTrace(\Throwable $throwable, FilterOptions $filter = null, int $count = null, bool $includePsy = true): array + { + if ($cwd = \getcwd()) { + $cwd = \rtrim($cwd, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR; + } + + if ($count === null) { + $count = \PHP_INT_MAX; + } + + $lines = []; + + $trace = $throwable->getTrace(); + \array_unshift($trace, [ + 'function' => '', + 'file' => $throwable->getFile() !== null ? $throwable->getFile() : 'n/a', + 'line' => $throwable->getLine() !== null ? $throwable->getLine() : 'n/a', + 'args' => [], + ]); + + if (!$includePsy) { + for ($i = \count($trace) - 1; $i >= 0; $i--) { + $thing = isset($trace[$i]['class']) ? $trace[$i]['class'] : $trace[$i]['function']; + if (\preg_match('/\\\\?Psy\\\\/', $thing)) { + $trace = \array_slice($trace, $i + 1); + break; + } + } + } + + for ($i = 0, $count = \min($count, \count($trace)); $i < $count; $i++) { + $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : ''; + $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : ''; + $function = $trace[$i]['function']; + $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a'; + $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a'; + + // Make file paths relative to cwd + if ($cwd !== false) { + $file = \preg_replace('/^'.\preg_quote($cwd, '/').'/', '', $file); + } + + // Leave execution loop out of the `eval()'d code` lines + if (\preg_match("#/src/Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code$#", \str_replace('\\', '/', $file))) { + $file = "eval()'d code"; + } + + // Skip any lines that don't match our filter options + if ($filter !== null && !$filter->match(\sprintf('%s%s%s() at %s:%s', $class, $type, $function, $file, $line))) { + continue; + } + + $lines[] = \sprintf( + ' <class>%s</class>%s%s() at <info>%s:%s</info>', + OutputFormatter::escape($class), + OutputFormatter::escape($type), + OutputFormatter::escape($function), + OutputFormatter::escape($file), + OutputFormatter::escape($line) + ); + } + + return $lines; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Input/CodeArgument.php b/php/libraries/composer/vendor/psy/psysh/src/Input/CodeArgument.php new file mode 100644 index 0000000..c415347 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Input/CodeArgument.php @@ -0,0 +1,50 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Input; + +use Symfony\Component\Console\Input\InputArgument; + +/** + * An input argument for code. + * + * A CodeArgument must be the final argument of the command. Once all options + * and other arguments are used, any remaining input until the end of the string + * is considered part of a single CodeArgument, regardless of spaces, quoting, + * escaping, etc. + * + * This means commands can support crazy input like + * + * parse function() { return "wheee\n"; } + * + * ... without having to put the code in a quoted string and escape everything. + */ +class CodeArgument extends InputArgument +{ + /** + * Constructor. + * + * @param string $name The argument name + * @param int $mode The argument mode: self::REQUIRED or self::OPTIONAL + * @param string $description A description text + * @param mixed $default The default value (for self::OPTIONAL mode only) + * + * @throws \InvalidArgumentException When argument mode is not valid + */ + public function __construct(string $name, int $mode = null, string $description = '', $default = null) + { + if ($mode & InputArgument::IS_ARRAY) { + throw new \InvalidArgumentException('Argument mode IS_ARRAY is not valid'); + } + + parent::__construct($name, $mode, $description, $default); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Input/FilterOptions.php b/php/libraries/composer/vendor/psy/psysh/src/Input/FilterOptions.php new file mode 100644 index 0000000..64eee3f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Input/FilterOptions.php @@ -0,0 +1,139 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Input; + +use Psy\Exception\ErrorException; +use Psy\Exception\RuntimeException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; + +/** + * Parse, validate and match --grep, --insensitive and --invert command options. + */ +class FilterOptions +{ + private $filter = false; + private $pattern; + private $insensitive; + private $invert; + + /** + * Get input option definitions for filtering. + * + * @return InputOption[] + */ + public static function getOptions(): array + { + return [ + new InputOption('grep', 'G', InputOption::VALUE_REQUIRED, 'Limit to items matching the given pattern (string or regex).'), + new InputOption('insensitive', 'i', InputOption::VALUE_NONE, 'Case-insensitive search (requires --grep).'), + new InputOption('invert', 'v', InputOption::VALUE_NONE, 'Inverted search (requires --grep).'), + ]; + } + + /** + * Bind input and prepare filter. + * + * @param InputInterface $input + */ + public function bind(InputInterface $input) + { + $this->validateInput($input); + + if (!$pattern = $input->getOption('grep')) { + $this->filter = false; + + return; + } + + if (!$this->stringIsRegex($pattern)) { + $pattern = '/'.\preg_quote($pattern, '/').'/'; + } + + if ($insensitive = $input->getOption('insensitive')) { + $pattern .= 'i'; + } + + $this->validateRegex($pattern); + + $this->filter = true; + $this->pattern = $pattern; + $this->insensitive = $insensitive; + $this->invert = $input->getOption('invert'); + } + + /** + * Check whether the bound input has filter options. + */ + public function hasFilter(): bool + { + return $this->filter; + } + + /** + * Check whether a string matches the current filter options. + * + * @param string $string + * @param array $matches + */ + public function match(string $string, array &$matches = null): bool + { + return $this->filter === false || (\preg_match($this->pattern, $string, $matches) xor $this->invert); + } + + /** + * Validate that grep, invert and insensitive input options are consistent. + * + * @throws RuntimeException if input is invalid + * + * @param InputInterface $input + */ + private function validateInput(InputInterface $input) + { + if (!$input->getOption('grep')) { + foreach (['invert', 'insensitive'] as $option) { + if ($input->getOption($option)) { + throw new RuntimeException('--'.$option.' does not make sense without --grep'); + } + } + } + } + + /** + * Check whether a string appears to be a regular expression. + * + * @param string $string + */ + private function stringIsRegex(string $string): bool + { + return \substr($string, 0, 1) === '/' && \substr($string, -1) === '/' && \strlen($string) >= 3; + } + + /** + * Validate that $pattern is a valid regular expression. + * + * @throws RuntimeException if pattern is invalid + * + * @param string $pattern + */ + private function validateRegex(string $pattern) + { + \set_error_handler([ErrorException::class, 'throwException']); + try { + \preg_match($pattern, ''); + } catch (ErrorException $e) { + throw new RuntimeException(\str_replace('preg_match(): ', 'Invalid regular expression: ', $e->getRawMessage())); + } finally { + \restore_error_handler(); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Input/ShellInput.php b/php/libraries/composer/vendor/psy/psysh/src/Input/ShellInput.php new file mode 100644 index 0000000..9b8bf81 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Input/ShellInput.php @@ -0,0 +1,333 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Input; + +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\StringInput; + +/** + * A StringInput subclass specialized for code arguments. + */ +class ShellInput extends StringInput +{ + public const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)'; + + private $hasCodeArgument = false; + + /** + * Unlike the parent implementation's tokens, this contains an array of + * token/rest pairs, so that code arguments can be handled while parsing. + */ + private $tokenPairs; + private $parsed; + + /** + * Constructor. + * + * @param string $input An array of parameters from the CLI (in the argv format) + */ + public function __construct(string $input) + { + parent::__construct($input); + + $this->tokenPairs = $this->tokenize($input); + } + + /** + * {@inheritdoc} + * + * @throws \InvalidArgumentException if $definition has CodeArgument before the final argument position + */ + public function bind(InputDefinition $definition): void + { + $hasCodeArgument = false; + + if ($definition->getArgumentCount() > 0) { + $args = $definition->getArguments(); + $lastArg = \array_pop($args); + foreach ($args as $arg) { + if ($arg instanceof CodeArgument) { + $msg = \sprintf('Unexpected CodeArgument before the final position: %s', $arg->getName()); + throw new \InvalidArgumentException($msg); + } + } + + if ($lastArg instanceof CodeArgument) { + $hasCodeArgument = true; + } + } + + $this->hasCodeArgument = $hasCodeArgument; + + parent::bind($definition); + } + + /** + * Tokenizes a string. + * + * The version of this on StringInput is good, but doesn't handle code + * arguments if they're at all complicated. This does :) + * + * @param string $input The input to tokenize + * + * @return array An array of token/rest pairs + * + * @throws \InvalidArgumentException When unable to parse input (should never happen) + */ + private function tokenize(string $input): array + { + $tokens = []; + $length = \strlen($input); + $cursor = 0; + while ($cursor < $length) { + if (\preg_match('/\s+/A', $input, $match, 0, $cursor)) { + } elseif (\preg_match('/([^="\'\s]+?)(=?)('.StringInput::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) { + $tokens[] = [ + $match[1].$match[2].\stripcslashes(\str_replace(['"\'', '\'"', '\'\'', '""'], '', \substr($match[3], 1, \strlen($match[3]) - 2))), + \stripcslashes(\substr($input, $cursor)), + ]; + } elseif (\preg_match('/'.StringInput::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) { + $tokens[] = [ + \stripcslashes(\substr($match[0], 1, \strlen($match[0]) - 2)), + \stripcslashes(\substr($input, $cursor)), + ]; + } elseif (\preg_match('/'.self::REGEX_STRING.'/A', $input, $match, 0, $cursor)) { + $tokens[] = [ + \stripcslashes($match[1]), + \stripcslashes(\substr($input, $cursor)), + ]; + } else { + // should never happen + // @codeCoverageIgnoreStart + throw new \InvalidArgumentException(\sprintf('Unable to parse input near "... %s ..."', \substr($input, $cursor, 10))); + // @codeCoverageIgnoreEnd + } + + $cursor += \strlen($match[0]); + } + + return $tokens; + } + + /** + * Same as parent, but with some bonus handling for code arguments. + */ + protected function parse(): void + { + $parseOptions = true; + $this->parsed = $this->tokenPairs; + while (null !== $tokenPair = \array_shift($this->parsed)) { + // token is what you'd expect. rest is the remainder of the input + // string, including token, and will be used if this is a code arg. + list($token, $rest) = $tokenPair; + + if ($parseOptions && '' === $token) { + $this->parseShellArgument($token, $rest); + } elseif ($parseOptions && '--' === $token) { + $parseOptions = false; + } elseif ($parseOptions && 0 === \strpos($token, '--')) { + $this->parseLongOption($token); + } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) { + $this->parseShortOption($token); + } else { + $this->parseShellArgument($token, $rest); + } + } + } + + /** + * Parses an argument, with bonus handling for code arguments. + * + * @param string $token The current token + * @param string $rest The remaining unparsed input, including the current token + * + * @throws \RuntimeException When too many arguments are given + */ + private function parseShellArgument(string $token, string $rest) + { + $c = \count($this->arguments); + + // if input is expecting another argument, add it + if ($this->definition->hasArgument($c)) { + $arg = $this->definition->getArgument($c); + + if ($arg instanceof CodeArgument) { + // When we find a code argument, we're done parsing. Add the + // remaining input to the current argument and call it a day. + $this->parsed = []; + $this->arguments[$arg->getName()] = $rest; + } else { + $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token; + } + + return; + } + + // (copypasta) + // + // @codeCoverageIgnoreStart + + // if last argument isArray(), append token to last argument + if ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) { + $arg = $this->definition->getArgument($c - 1); + $this->arguments[$arg->getName()][] = $token; + + return; + } + + // unexpected argument + $all = $this->definition->getArguments(); + if (\count($all)) { + throw new \RuntimeException(\sprintf('Too many arguments, expected arguments "%s".', \implode('" "', \array_keys($all)))); + } + + throw new \RuntimeException(\sprintf('No arguments expected, got "%s".', $token)); + // @codeCoverageIgnoreEnd + } + + // Everything below this is copypasta from ArgvInput private methods + // @codeCoverageIgnoreStart + + /** + * Parses a short option. + * + * @param string $token The current token + */ + private function parseShortOption(string $token) + { + $name = \substr($token, 1); + + if (\strlen($name) > 1) { + if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) { + // an option with a value (with no space) + $this->addShortOption($name[0], \substr($name, 1)); + } else { + $this->parseShortOptionSet($name); + } + } else { + $this->addShortOption($name, null); + } + } + + /** + * Parses a short option set. + * + * @param string $name The current token + * + * @throws \RuntimeException When option given doesn't exist + */ + private function parseShortOptionSet(string $name) + { + $len = \strlen($name); + for ($i = 0; $i < $len; $i++) { + if (!$this->definition->hasShortcut($name[$i])) { + throw new \RuntimeException(\sprintf('The "-%s" option does not exist.', $name[$i])); + } + + $option = $this->definition->getOptionForShortcut($name[$i]); + if ($option->acceptValue()) { + $this->addLongOption($option->getName(), $i === $len - 1 ? null : \substr($name, $i + 1)); + + break; + } else { + $this->addLongOption($option->getName(), null); + } + } + } + + /** + * Parses a long option. + * + * @param string $token The current token + */ + private function parseLongOption(string $token) + { + $name = \substr($token, 2); + + if (false !== $pos = \strpos($name, '=')) { + if (($value = \substr($name, $pos + 1)) === '') { + \array_unshift($this->parsed, [$value, null]); + } + $this->addLongOption(\substr($name, 0, $pos), $value); + } else { + $this->addLongOption($name, null); + } + } + + /** + * Adds a short option value. + * + * @param string $shortcut The short option key + * @param mixed $value The value for the option + * + * @throws \RuntimeException When option given doesn't exist + */ + private function addShortOption(string $shortcut, $value) + { + if (!$this->definition->hasShortcut($shortcut)) { + throw new \RuntimeException(\sprintf('The "-%s" option does not exist.', $shortcut)); + } + + $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value); + } + + /** + * Adds a long option value. + * + * @param string $name The long option key + * @param mixed $value The value for the option + * + * @throws \RuntimeException When option given doesn't exist + */ + private function addLongOption(string $name, $value) + { + if (!$this->definition->hasOption($name)) { + throw new \RuntimeException(\sprintf('The "--%s" option does not exist.', $name)); + } + + $option = $this->definition->getOption($name); + + if (null !== $value && !$option->acceptValue()) { + throw new \RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name)); + } + + if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) { + // if option accepts an optional or mandatory argument + // let's see if there is one provided + $next = \array_shift($this->parsed); + $nextToken = $next[0]; + if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || \in_array($nextToken, ['', null], true)) { + $value = $nextToken; + } else { + \array_unshift($this->parsed, $next); + } + } + + if ($value === null) { + if ($option->isValueRequired()) { + throw new \RuntimeException(\sprintf('The "--%s" option requires a value.', $name)); + } + + if (!$option->isArray() && !$option->isValueOptional()) { + $value = true; + } + } + + if ($option->isArray()) { + $this->options[$name][] = $value; + } else { + $this->options[$name] = $value; + } + } + + // @codeCoverageIgnoreEnd +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Input/SilentInput.php b/php/libraries/composer/vendor/psy/psysh/src/Input/SilentInput.php new file mode 100644 index 0000000..0c963f5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Input/SilentInput.php @@ -0,0 +1,42 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Input; + +/** + * A simple class used internally by PsySH to represent silent input. + * + * Silent input is generally used for non-user-generated code, such as the + * rewritten user code run by sudo command. Silent input isn't echoed before + * evaluating, and it's not added to the readline history. + */ +class SilentInput +{ + private $inputString; + + /** + * Constructor. + * + * @param string $inputString + */ + public function __construct(string $inputString) + { + $this->inputString = $inputString; + } + + /** + * To. String. + */ + public function __toString(): string + { + return $this->inputString; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Output/OutputPager.php b/php/libraries/composer/vendor/psy/psysh/src/Output/OutputPager.php new file mode 100644 index 0000000..0652b70 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Output/OutputPager.php @@ -0,0 +1,26 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Output; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * An output pager is much the same as a regular OutputInterface, but allows + * the stream to be flushed to a pager periodically. + */ +interface OutputPager extends OutputInterface +{ + /** + * Close the current pager process. + */ + public function close(); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Output/PassthruPager.php b/php/libraries/composer/vendor/psy/psysh/src/Output/PassthruPager.php new file mode 100644 index 0000000..6ad17b5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Output/PassthruPager.php @@ -0,0 +1,39 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Output; + +use Symfony\Component\Console\Output\StreamOutput; + +/** + * A passthrough pager is a no-op. It simply wraps a StreamOutput's stream and + * does nothing when the pager is closed. + */ +class PassthruPager extends StreamOutput implements OutputPager +{ + /** + * Constructor. + * + * @param StreamOutput $output + */ + public function __construct(StreamOutput $output) + { + parent::__construct($output->getStream()); + } + + /** + * Close the current pager process. + */ + public function close() + { + // nothing to do here + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Output/ProcOutputPager.php b/php/libraries/composer/vendor/psy/psysh/src/Output/ProcOutputPager.php new file mode 100644 index 0000000..42e40db --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Output/ProcOutputPager.php @@ -0,0 +1,105 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Output; + +use Symfony\Component\Console\Output\StreamOutput; + +/** + * ProcOutputPager class. + * + * A ProcOutputPager instance wraps a regular StreamOutput's stream. Rather + * than writing directly to the stream, it shells out to a pager process and + * gives that process the stream as stdout. This means regular *nix commands + * like `less` and `more` can be used to page large amounts of output. + */ +class ProcOutputPager extends StreamOutput implements OutputPager +{ + private $proc; + private $pipe; + private $stream; + private $cmd; + + /** + * Constructor. + * + * @param StreamOutput $output + * @param string $cmd Pager process command (default: 'less -R -F -X') + */ + public function __construct(StreamOutput $output, string $cmd = 'less -R -F -X') + { + $this->stream = $output->getStream(); + $this->cmd = $cmd; + } + + /** + * Writes a message to the output. + * + * @param string $message A message to write to the output + * @param bool $newline Whether to add a newline or not + * + * @throws \RuntimeException When unable to write output (should never happen) + */ + public function doWrite($message, $newline): void + { + $pipe = $this->getPipe(); + if (false === @\fwrite($pipe, $message.($newline ? \PHP_EOL : ''))) { + // @codeCoverageIgnoreStart + // should never happen + $this->close(); + throw new \RuntimeException('Unable to write output'); + // @codeCoverageIgnoreEnd + } + + \fflush($pipe); + } + + /** + * Close the current pager process. + */ + public function close() + { + if (isset($this->pipe)) { + \fclose($this->pipe); + } + + if (isset($this->proc)) { + $exit = \proc_close($this->proc); + if ($exit !== 0) { + throw new \RuntimeException('Error closing output stream'); + } + } + + $this->pipe = null; + $this->proc = null; + } + + /** + * Get a pipe for paging output. + * + * If no active pager process exists, fork one and return its input pipe. + */ + private function getPipe() + { + if (!isset($this->pipe) || !isset($this->proc)) { + $desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')]; + $this->proc = \proc_open($this->cmd, $desc, $pipes); + + if (!\is_resource($this->proc)) { + throw new \RuntimeException('Error opening output stream'); + } + + $this->pipe = $pipes[0]; + } + + return $this->pipe; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Output/ShellOutput.php b/php/libraries/composer/vendor/psy/psysh/src/Output/ShellOutput.php new file mode 100644 index 0000000..2ef575d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Output/ShellOutput.php @@ -0,0 +1,208 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Output; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Output\ConsoleOutput; + +/** + * A ConsoleOutput subclass specifically for Psy Shell output. + */ +class ShellOutput extends ConsoleOutput +{ + const NUMBER_LINES = 128; + + private $paging = 0; + + /** @var OutputPager */ + private $pager; + + /** @var Theme */ + private $theme; + + /** + * Construct a ShellOutput instance. + * + * @param mixed $verbosity (default: self::VERBOSITY_NORMAL) + * @param bool|null $decorated (default: null) + * @param OutputFormatterInterface|null $formatter (default: null) + * @param string|OutputPager|null $pager (default: null) + */ + public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null, $pager = null, $theme = null) + { + parent::__construct($verbosity, $decorated, $formatter); + + $this->theme = $theme ?? new Theme('modern'); + $this->initFormatters(); + + if ($pager === null) { + $this->pager = new PassthruPager($this); + } elseif (\is_string($pager)) { + $this->pager = new ProcOutputPager($this, $pager); + } elseif ($pager instanceof OutputPager) { + $this->pager = $pager; + } else { + throw new \InvalidArgumentException('Unexpected pager parameter: '.$pager); + } + } + + /** + * Page multiple lines of output. + * + * The output pager is started + * + * If $messages is callable, it will be called, passing this output instance + * for rendering. Otherwise, all passed $messages are paged to output. + * + * Upon completion, the output pager is flushed. + * + * @param string|array|\Closure $messages A string, array of strings or a callback + * @param int $type (default: 0) + */ + public function page($messages, int $type = 0) + { + if (\is_string($messages)) { + $messages = (array) $messages; + } + + if (!\is_array($messages) && !\is_callable($messages)) { + throw new \InvalidArgumentException('Paged output requires a string, array or callback'); + } + + $this->startPaging(); + + if (\is_callable($messages)) { + $messages($this); + } else { + $this->write($messages, true, $type); + } + + $this->stopPaging(); + } + + /** + * Start sending output to the output pager. + */ + public function startPaging() + { + $this->paging++; + } + + /** + * Stop paging output and flush the output pager. + */ + public function stopPaging() + { + $this->paging--; + $this->closePager(); + } + + /** + * Writes a message to the output. + * + * Optionally, pass `$type | self::NUMBER_LINES` as the $type parameter to + * number the lines of output. + * + * @throws \InvalidArgumentException When unknown output type is given + * + * @param string|array $messages The message as an array of lines or a single string + * @param bool $newline Whether to add a newline or not + * @param int $type The type of output + */ + public function write($messages, $newline = false, $type = 0): void + { + if ($this->getVerbosity() === self::VERBOSITY_QUIET) { + return; + } + + $messages = (array) $messages; + + if ($type & self::NUMBER_LINES) { + $pad = \strlen((string) \count($messages)); + $template = $this->isDecorated() ? "<aside>%{$pad}s</aside>: %s" : "%{$pad}s: %s"; + + if ($type & self::OUTPUT_RAW) { + $messages = \array_map([OutputFormatter::class, 'escape'], $messages); + } + + foreach ($messages as $i => $line) { + $messages[$i] = \sprintf($template, $i, $line); + } + + // clean this up for super. + $type = $type & ~self::NUMBER_LINES & ~self::OUTPUT_RAW; + } + + parent::write($messages, $newline, $type); + } + + /** + * Writes a message to the output. + * + * Handles paged output, or writes directly to the output stream. + * + * @param string $message A message to write to the output + * @param bool $newline Whether to add a newline or not + */ + public function doWrite($message, $newline): void + { + if ($this->paging > 0) { + $this->pager->doWrite($message, $newline); + } else { + parent::doWrite($message, $newline); + } + } + + /** + * Set the output Theme. + */ + public function setTheme(Theme $theme) + { + $this->theme = $theme; + $this->initFormatters(); + } + + /** + * Flush and close the output pager. + */ + private function closePager() + { + if ($this->paging <= 0) { + $this->pager->close(); + } + } + + /** + * Initialize output formatter styles. + */ + private function initFormatters() + { + $useGrayFallback = !$this->grayExists(); + $this->theme->applyStyles($this->getFormatter(), $useGrayFallback); + $this->theme->applyErrorStyles($this->getErrorOutput()->getFormatter(), $useGrayFallback); + } + + /** + * Checks if the "gray" color exists on the output. + */ + private function grayExists(): bool + { + try { + $this->write('<fg=gray></>'); + } catch (\InvalidArgumentException $e) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Output/Theme.php b/php/libraries/composer/vendor/psy/psysh/src/Output/Theme.php new file mode 100644 index 0000000..01023f2 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Output/Theme.php @@ -0,0 +1,282 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Formatter\OutputFormatterStyle; + +/** + * An output Theme, which controls prompt strings, formatter styles, and compact output. + */ +class Theme +{ + const MODERN_THEME = []; // Defaults :) + + const COMPACT_THEME = [ + 'compact' => true, + ]; + + const CLASSIC_THEME = [ + 'compact' => true, + + 'prompt' => '>>> ', + 'bufferPrompt' => '... ', + 'replayPrompt' => '--> ', + 'returnValue' => '=> ', + ]; + + const DEFAULT_STYLES = [ + 'info' => ['white', 'blue', ['bold']], + 'warning' => ['black', 'yellow'], + 'error' => ['white', 'red', ['bold']], + 'whisper' => ['gray'], + + 'aside' => ['blue'], + 'strong' => [null, null, ['bold']], + 'return' => ['cyan'], + 'urgent' => ['red'], + 'hidden' => ['black'], + + // Visibility + 'public' => [null, null, ['bold']], + 'protected' => ['yellow'], + 'private' => ['red'], + 'global' => ['cyan', null, ['bold']], + 'const' => ['cyan'], + 'class' => ['blue', null, ['underscore']], + 'function' => [null], + 'default' => [null], + + // Types + 'number' => ['magenta'], + 'integer' => ['magenta'], + 'float' => ['yellow'], + 'string' => ['green'], + 'bool' => ['cyan'], + 'keyword' => ['yellow'], + 'comment' => ['blue'], + 'code_comment' => ['gray'], + 'object' => ['blue'], + 'resource' => ['yellow'], + + // Code-specific formatting + 'inline_html' => ['cyan'], + ]; + + const ERROR_STYLES = ['info', 'warning', 'error', 'whisper', 'class']; + + private $compact = false; + + private $prompt = '> '; + private $bufferPrompt = '. '; + private $replayPrompt = '- '; + private $returnValue = '= '; + + private $grayFallback = 'blue'; + + private $styles = []; + + /** + * @param string|array $config theme name or config options + */ + public function __construct($config = 'modern') + { + if (\is_string($config)) { + switch ($config) { + case 'modern': + $config = static::MODERN_THEME; + break; + + case 'compact': + $config = static::COMPACT_THEME; + break; + + case 'classic': + $config = static::CLASSIC_THEME; + break; + + default: + \trigger_error(\sprintf('Unknown theme: %s', $config), \E_USER_NOTICE); + $config = static::MODERN_THEME; + break; + } + } + + if (!\is_array($config)) { + throw new \InvalidArgumentException('Invalid theme config'); + } + + foreach ($config as $name => $value) { + switch ($name) { + case 'compact': + $this->setCompact($value); + break; + + case 'prompt': + $this->setPrompt($value); + break; + + case 'bufferPrompt': + $this->setBufferPrompt($value); + break; + + case 'replayPrompt': + $this->setReplayPrompt($value); + break; + + case 'returnValue': + $this->setReturnValue($value); + break; + + case 'grayFallback': + $this->setGrayFallback($value); + break; + } + } + + $this->setStyles($config['styles'] ?? []); + } + + /** + * Enable or disable compact output. + */ + public function setCompact(bool $compact) + { + $this->compact = $compact; + } + + /** + * Get whether to use compact output. + */ + public function compact(): bool + { + return $this->compact; + } + + /** + * Set the prompt string. + */ + public function setPrompt(string $prompt) + { + $this->prompt = $prompt; + } + + /** + * Get the prompt string. + */ + public function prompt(): string + { + return $this->prompt; + } + + /** + * Set the buffer prompt string (used for multi-line input continuation). + */ + public function setBufferPrompt(string $bufferPrompt) + { + $this->bufferPrompt = $bufferPrompt; + } + + /** + * Get the buffer prompt string (used for multi-line input continuation). + */ + public function bufferPrompt(): string + { + return $this->bufferPrompt; + } + + /** + * Set the prompt string used when replaying history. + */ + public function setReplayPrompt(string $replayPrompt) + { + $this->replayPrompt = $replayPrompt; + } + + /** + * Get the prompt string used when replaying history. + */ + public function replayPrompt(): string + { + return $this->replayPrompt; + } + + /** + * Set the return value marker. + */ + public function setReturnValue(string $returnValue) + { + $this->returnValue = $returnValue; + } + + /** + * Get the return value marker. + */ + public function returnValue(): string + { + return $this->returnValue; + } + + /** + * Set the fallback color when "gray" is unavailable. + */ + public function setGrayFallback(string $grayFallback) + { + $this->grayFallback = $grayFallback; + } + + /** + * Set the shell output formatter styles. + * + * Accepts a map from style name to [fg, bg, options], for example: + * + * [ + * 'error' => ['white', 'red', ['bold']], + * 'warning' => ['black', 'yellow'], + * ] + * + * Foreground, background or options can be null, or even omitted entirely. + */ + public function setStyles(array $styles) + { + foreach (\array_keys(static::DEFAULT_STYLES) as $name) { + $this->styles[$name] = $styles[$name] ?? static::DEFAULT_STYLES[$name]; + } + } + + /** + * Apply the current output formatter styles. + */ + public function applyStyles(OutputFormatterInterface $formatter, bool $useGrayFallback) + { + foreach (\array_keys(static::DEFAULT_STYLES) as $name) { + $formatter->setStyle($name, new OutputFormatterStyle(...$this->getStyle($name, $useGrayFallback))); + } + } + + /** + * Apply the current output formatter error styles. + */ + public function applyErrorStyles(OutputFormatterInterface $errorFormatter, bool $useGrayFallback) + { + foreach (static::ERROR_STYLES as $name) { + $errorFormatter->setStyle($name, new OutputFormatterStyle(...$this->getStyle($name, $useGrayFallback))); + } + } + + private function getStyle(string $name, bool $useGrayFallback): array + { + return \array_map(function ($style) use ($useGrayFallback) { + return ($useGrayFallback && $style === 'gray') ? $this->grayFallback : $style; + }, $this->styles[$name]); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/ParserFactory.php b/php/libraries/composer/vendor/psy/psysh/src/ParserFactory.php new file mode 100644 index 0000000..2b37ccd --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/ParserFactory.php @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +use PhpParser\Parser; +use PhpParser\ParserFactory as OriginalParserFactory; + +/** + * Parser factory to abstract over PHP Parser library versions. + */ +class ParserFactory +{ + /** + * New parser instance. + */ + public function createParser(): Parser + { + $factory = new OriginalParserFactory(); + + if (!\method_exists($factory, 'createForHostVersion')) { + return $factory->create(OriginalParserFactory::PREFER_PHP7); + } + + return $factory->createForHostVersion(); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/GNUReadline.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/GNUReadline.php new file mode 100644 index 0000000..877e1a3 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/GNUReadline.php @@ -0,0 +1,168 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Readline; + +/** + * A Readline interface implementation for GNU Readline. + * + * This is by far the coolest way to do it, if you can. + * + * Oh well. + */ +class GNUReadline implements Readline +{ + /** @var string|false */ + protected $historyFile; + /** @var int */ + protected $historySize; + /** @var bool */ + protected $eraseDups; + + /** + * GNU Readline is supported iff `readline_list_history` is defined. PHP + * decided it would be awesome to swap out GNU Readline for Libedit, but + * they ended up shipping an incomplete implementation. So we've got this. + * + * NOTE: As of PHP 7.4, PHP sometimes has history support in the Libedit + * wrapper, so that will use the GNUReadline implementation as well! + */ + public static function isSupported(): bool + { + return \function_exists('readline') && \function_exists('readline_list_history'); + } + + /** + * Check whether this readline implementation supports bracketed paste. + * + * Currently, the GNU readline implementation does, but the libedit wrapper does not. + */ + public static function supportsBracketedPaste(): bool + { + return self::isSupported() && \stripos(\readline_info('library_version') ?: '', 'editline') === false; + } + + public function __construct($historyFile = null, $historySize = 0, $eraseDups = false) + { + $this->historyFile = ($historyFile !== null) ? $historyFile : false; + $this->historySize = $historySize; + $this->eraseDups = $eraseDups; + + \readline_info('readline_name', 'psysh'); + } + + /** + * {@inheritdoc} + */ + public function addHistory(string $line): bool + { + if ($res = \readline_add_history($line)) { + $this->writeHistory(); + } + + return $res; + } + + /** + * {@inheritdoc} + */ + public function clearHistory(): bool + { + if ($res = \readline_clear_history()) { + $this->writeHistory(); + } + + return $res; + } + + /** + * {@inheritdoc} + */ + public function listHistory(): array + { + return \readline_list_history(); + } + + /** + * {@inheritdoc} + */ + public function readHistory(): bool + { + \readline_read_history(); + \readline_clear_history(); + + return \readline_read_history($this->historyFile); + } + + /** + * {@inheritdoc} + */ + public function readline(string $prompt = null) + { + return \readline($prompt); + } + + /** + * {@inheritdoc} + */ + public function redisplay() + { + \readline_redisplay(); + } + + /** + * {@inheritdoc} + */ + public function writeHistory(): bool + { + // We have to write history first, since it is used + // by Libedit to list history + if ($this->historyFile !== false) { + $res = \readline_write_history($this->historyFile); + } else { + $res = true; + } + + if (!$res || !$this->eraseDups && !$this->historySize > 0) { + return $res; + } + + $hist = $this->listHistory(); + if (!$hist) { + return true; + } + + if ($this->eraseDups) { + // flip-flip technique: removes duplicates, latest entries win. + $hist = \array_flip(\array_flip($hist)); + // sort on keys to get the order back + \ksort($hist); + } + + if ($this->historySize > 0) { + $histsize = \count($hist); + if ($histsize > $this->historySize) { + $hist = \array_slice($hist, $histsize - $this->historySize); + } + } + + \readline_clear_history(); + foreach ($hist as $line) { + \readline_add_history($line); + } + + if ($this->historyFile !== false) { + return \readline_write_history($this->historyFile); + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Autocompleter.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Autocompleter.php new file mode 100644 index 0000000..6955de6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Autocompleter.php @@ -0,0 +1,57 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Console\Readline\Autocompleter. + * + * Interface for all auto-completers. + */ +interface Autocompleter +{ + /** + * Complete a word. + * Returns null for no word, a full-word or an array of full-words. + */ + public function complete(&$prefix); + + /** + * Get definition of a word. + * Example: \b\w+\b. PCRE delimiters and options must not be provided. + */ + public function getWordDefinition(): string; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterAggregate.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterAggregate.php new file mode 100644 index 0000000..b7a2223 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterAggregate.php @@ -0,0 +1,118 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Readline\Autocompleter\Aggregate. + * + * Aggregate several autocompleters. + */ +class AutocompleterAggregate implements Autocompleter +{ + /** + * List of autocompleters. + */ + protected $_autocompleters = null; + + /** + * Constructor. + */ + public function __construct(array $autocompleters) + { + $this->setAutocompleters($autocompleters); + + return; + } + + /** + * Complete a word. + * Returns null for no word, a full-word or an array of full-words. + */ + public function complete(&$prefix) + { + foreach ($this->getAutocompleters() as $autocompleter) { + $preg = \preg_match( + '#('.$autocompleter->getWordDefinition().')$#u', + $prefix, + $match + ); + + if (0 === $preg) { + continue; + } + + $_prefix = $match[0]; + + if (null === $out = $autocompleter->complete($_prefix)) { + continue; + } + + $prefix = $_prefix; + + return $out; + } + + return null; + } + + /** + * Set/initialize list of autocompleters. + */ + protected function setAutocompleters(array $autocompleters) + { + $old = $this->_autocompleters; + $this->_autocompleters = new \ArrayObject($autocompleters); + + return $old; + } + + /** + * Get list of autocompleters. + */ + public function getAutocompleters() + { + return $this->_autocompleters; + } + + /** + * Get definition of a word. + */ + public function getWordDefinition(): string + { + return '.*'; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterPath.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterPath.php new file mode 100644 index 0000000..a922b78 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterPath.php @@ -0,0 +1,194 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Readline\Autocompleter\Path. + * + * Path autocompleter. + */ +class AutocompleterPath implements Autocompleter +{ + /** + * Root is the current working directory. + */ + const PWD = null; + + /** + * Root. + */ + protected $_root = null; + + /** + * Iterator factory. Please, see the self::setIteratorFactory method. + */ + protected $_iteratorFactory = null; + + /** + * Constructor. + */ + public function __construct( + string $root = null, + \Closure $iteratorFactory = null + ) { + if (null === $root) { + $root = static::PWD; + } + + if (null !== $root) { + $this->setRoot($root); + } + + if (null !== $iteratorFactory) { + $this->setIteratorFactory($iteratorFactory); + } + } + + /** + * Complete a word. + * Returns null for no word, a full-word or an array of full-words. + */ + public function complete(&$prefix) + { + $root = $this->getRoot(); + + if (static::PWD === $root) { + $root = \getcwd(); + } + + $path = $root.\DIRECTORY_SEPARATOR.$prefix; + + if (!\is_dir($path)) { + $path = \dirname($path).\DIRECTORY_SEPARATOR; + $prefix = \basename($prefix); + } else { + $prefix = null; + } + + $iteratorFactory = $this->getIteratorFactory() ?: + static::getDefaultIteratorFactory(); + + try { + $iterator = $iteratorFactory($path); + $out = []; + $length = \mb_strlen($prefix); + + foreach ($iterator as $fileinfo) { + $filename = $fileinfo->getFilename(); + + if (null === $prefix || + (\mb_substr($filename, 0, $length) === $prefix)) { + if ($fileinfo->isDir()) { + $out[] = $filename.'/'; + } else { + $out[] = $filename; + } + } + } + } catch (\Exception $e) { + return null; + } + + $count = \count($out); + + if (1 === $count) { + return $out[0]; + } + + if (0 === $count) { + return null; + } + + return $out; + } + + /** + * Get definition of a word. + */ + public function getWordDefinition(): string + { + return '/?[\w\d\\_\-\.]+(/[\w\d\\_\-\.]*)*'; + } + + /** + * Set root. + */ + public function setRoot(string $root) + { + $old = $this->_root; + $this->_root = $root; + + return $old; + } + + /** + * Get root. + */ + public function getRoot() + { + return $this->_root; + } + + /** + * Set iterator factory (a finder). + */ + public function setIteratorFactory(\Closure $iteratorFactory) + { + $old = $this->_iteratorFactory; + $this->_iteratorFactory = $iteratorFactory; + + return $old; + } + + /** + * Get iterator factory. + */ + public function getIteratorFactory() + { + return $this->_iteratorFactory; + } + + /** + * Get default iterator factory (based on \DirectoryIterator). + */ + public static function getDefaultIteratorFactory() + { + return function ($path) { + return new \DirectoryIterator($path); + }; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterWord.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterWord.php new file mode 100644 index 0000000..c60823e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/AutocompleterWord.php @@ -0,0 +1,119 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Readline\Autocompleter\Word. + * + * The simplest auto-completer: complete a word. + */ +class AutocompleterWord implements Autocompleter +{ + /** + * List of words. + */ + protected $_words = null; + + /** + * Constructor. + */ + public function __construct(array $words) + { + $this->setWords($words); + } + + /** + * Complete a word. + * Returns null for no word, a full-word or an array of full-words. + * + * @param string &$prefix Prefix to autocomplete + * + * @return mixed + */ + public function complete(&$prefix) + { + $out = []; + $length = \mb_strlen($prefix); + + foreach ($this->getWords() as $word) { + if (\mb_substr($word, 0, $length) === $prefix) { + $out[] = $word; + } + } + + if (empty($out)) { + return null; + } + + if (1 === \count($out)) { + return $out[0]; + } + + return $out; + } + + /** + * Get definition of a word. + */ + public function getWordDefinition(): string + { + return '\b\w+'; + } + + /** + * Set list of words. + * + * @param array $words words + * + * @return array + */ + public function setWords(array $words) + { + $old = $this->_words; + $this->_words = $words; + + return $old; + } + + /** + * Get list of words. + */ + public function getWords(): array + { + return $this->_words; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Console.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Console.php new file mode 100644 index 0000000..17b1fec --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Console.php @@ -0,0 +1,347 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console. + * + * A set of utils and helpers about the console. + */ +class Console +{ + /** + * Pipe mode: FIFO. + */ + const IS_FIFO = 0; + + /** + * Pipe mode: character. + */ + const IS_CHARACTER = 1; + + /** + * Pipe mode: directory. + */ + const IS_DIRECTORY = 2; + + /** + * Pipe mode: block. + */ + const IS_BLOCK = 3; + + /** + * Pipe mode: regular. + */ + const IS_REGULAR = 4; + + /** + * Pipe mode: link. + */ + const IS_LINK = 5; + + /** + * Pipe mode: socket. + */ + const IS_SOCKET = 6; + + /** + * Pipe mode: whiteout. + */ + const IS_WHITEOUT = 7; + + /** + * Advanced interaction is on. + */ + private static $_advanced = null; + + /** + * Previous STTY configuration. + */ + private static $_old = null; + + /** + * Mode. + */ + protected static $_mode = []; + + /** + * Input. + */ + protected static $_input = null; + + /** + * Output. + */ + protected static $_output = null; + + /** + * Tput. + */ + protected static $_tput = null; + + /** + * Prepare the environment for advanced interactions. + */ + public static function advancedInteraction(bool $force = false): bool + { + if (null !== self::$_advanced) { + return self::$_advanced; + } + + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return self::$_advanced = false; + } + + if (false === $force && + true === \defined('STDIN') && + false === self::isDirect(\STDIN)) { + return self::$_advanced = false; + } + + self::$_old = ConsoleProcessus::execute('stty -g < /dev/tty', false); + ConsoleProcessus::execute('stty -echo -icanon min 1 time 0 < /dev/tty', false); + + return self::$_advanced = true; + } + + /** + * Restore previous interaction options. + */ + public static function restoreInteraction() + { + if (null === self::$_old) { + return; + } + + ConsoleProcessus::execute('stty '.self::$_old.' < /dev/tty', false); + + return; + } + + /** + * Get mode of a certain pipe. + * Inspired by sys/stat.h. + */ + public static function getMode($pipe = \STDIN): int + { + $_pipe = (int) $pipe; + + if (isset(self::$_mode[$_pipe])) { + return self::$_mode[$_pipe]; + } + + $stat = \fstat($pipe); + + switch ($stat['mode'] & 0170000) { + // named pipe (fifo). + case 0010000: + $mode = self::IS_FIFO; + + break; + + // character special. + case 0020000: + $mode = self::IS_CHARACTER; + + break; + + // directory. + case 0040000: + $mode = self::IS_DIRECTORY; + + break; + + // block special. + case 0060000: + $mode = self::IS_BLOCK; + + break; + + // regular. + case 0100000: + $mode = self::IS_REGULAR; + + break; + + // symbolic link. + case 0120000: + $mode = self::IS_LINK; + + break; + + // socket. + case 0140000: + $mode = self::IS_SOCKET; + + break; + + // whiteout. + case 0160000: + $mode = self::IS_WHITEOUT; + + break; + + default: + $mode = -1; + } + + return self::$_mode[$_pipe] = $mode; + } + + /** + * Check whether a certain pipe is a character device (keyboard, screen + * etc.). + * For example: + * $ php Mode.php + * In this case, self::isDirect(STDOUT) will return true. + */ + public static function isDirect($pipe): bool + { + return self::IS_CHARACTER === self::getMode($pipe); + } + + /** + * Check whether a certain pipe is a pipe. + * For example: + * $ php Mode.php | foobar + * In this case, self::isPipe(STDOUT) will return true. + */ + public static function isPipe($pipe): bool + { + return self::IS_FIFO === self::getMode($pipe); + } + + /** + * Check whether a certain pipe is a redirection. + * For example: + * $ php Mode.php < foobar + * In this case, self::isRedirection(STDIN) will return true. + */ + public static function isRedirection($pipe): bool + { + $mode = self::getMode($pipe); + + return + self::IS_REGULAR === $mode || + self::IS_DIRECTORY === $mode || + self::IS_LINK === $mode || + self::IS_SOCKET === $mode || + self::IS_BLOCK === $mode; + } + + /** + * Set input layer. + */ + public static function setInput(ConsoleInput $input) + { + $old = static::$_input; + static::$_input = $input; + + return $old; + } + + /** + * Get input layer. + */ + public static function getInput(): ConsoleInput + { + if (null === static::$_input) { + static::$_input = new ConsoleInput(); + } + + return static::$_input; + } + + /** + * Set output layer. + */ + public static function setOutput(ConsoleOutput $output) + { + $old = static::$_output; + static::$_output = $output; + + return $old; + } + + /** + * Get output layer. + */ + public static function getOutput(): ConsoleOutput + { + if (null === static::$_output) { + static::$_output = new ConsoleOutput(); + } + + return static::$_output; + } + + /** + * Set tput. + */ + public static function setTput(ConsoleTput $tput) + { + $old = static::$_tput; + static::$_tput = $tput; + + return $old; + } + + /** + * Get the current tput instance of the current process. + */ + public static function getTput(): ConsoleTput + { + if (null === static::$_tput) { + static::$_tput = new ConsoleTput(); + } + + return static::$_tput; + } + + /** + * Check whether we are running behind TMUX(1). + */ + public static function isTmuxRunning(): bool + { + return isset($_SERVER['TMUX']); + } +} + +/* + * Restore interaction. + */ +\register_shutdown_function([Console::class, 'restoreInteraction']); diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleCursor.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleCursor.php new file mode 100644 index 0000000..6745e25 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleCursor.php @@ -0,0 +1,695 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Cursor. + * + * Allow to manipulate the cursor. + */ +class ConsoleCursor +{ + /** + * Move the cursor. + * Steps can be: + * • u, up, ↑ : move to the previous line; + * • U, UP : move to the first line; + * • r, right, → : move to the next column; + * • R, RIGHT : move to the last column; + * • d, down, ↓ : move to the next line; + * • D, DOWN : move to the last line; + * • l, left, ← : move to the previous column; + * • L, LEFT : move to the first column. + * Steps can be concatened by a single space if $repeat is equal to 1. + */ + public static function move(string $steps, int $repeat = 1) + { + if (1 > $repeat) { + return; + } elseif (1 === $repeat) { + $handle = \explode(' ', $steps); + } else { + $handle = \explode(' ', $steps, 1); + } + + $tput = Console::getTput(); + $output = Console::getOutput(); + + foreach ($handle as $step) { + switch ($step) { + case 'u': + case 'up': + case '↑': + $output->writeAll( + \str_replace( + '%p1%d', + $repeat, + $tput->get('parm_up_cursor') + ) + ); + + break; + + case 'U': + case 'UP': + static::moveTo(null, 1); + + break; + + case 'r': + case 'right': + case '→': + $output->writeAll( + \str_replace( + '%p1%d', + $repeat, + $tput->get('parm_right_cursor') + ) + ); + + break; + + case 'R': + case 'RIGHT': + static::moveTo(9999); + + break; + + case 'd': + case 'down': + case '↓': + $output->writeAll( + \str_replace( + '%p1%d', + $repeat, + $tput->get('parm_down_cursor') + ) + ); + + break; + + case 'D': + case 'DOWN': + static::moveTo(null, 9999); + + break; + + case 'l': + case 'left': + case '←': + $output->writeAll( + \str_replace( + '%p1%d', + $repeat, + $tput->get('parm_left_cursor') + ) + ); + + break; + + case 'L': + case 'LEFT': + static::moveTo(1); + + break; + } + } + } + + /** + * Move to the line X and the column Y. + * If null, use the current coordinate. + */ + public static function moveTo(int $x = null, int $y = null) + { + if (null === $x || null === $y) { + $position = static::getPosition(); + + if (null === $x) { + $x = $position['x']; + } + + if (null === $y) { + $y = $position['y']; + } + } + + Console::getOutput()->writeAll( + \str_replace( + ['%i%p1%d', '%p2%d'], + [$y, $x], + Console::getTput()->get('cursor_address') + ) + ); + } + + /** + * Get current position (x and y) of the cursor. + */ + public static function getPosition(): array + { + $tput = Console::getTput(); + $user7 = $tput->get('user7'); + + if (null === $user7) { + return [ + 'x' => 0, + 'y' => 0, + ]; + } + + Console::getOutput()->writeAll($user7); + + $input = Console::getInput(); + + // Read $tput->get('user6'). + $input->read(2); // skip \033 and [. + + $x = null; + $y = null; + $handle = &$y; + + while (true) { + $char = $input->readCharacter(); + + switch ($char) { + case ';': + $handle = &$x; + + break; + + case 'R': + break 2; + + default: + $handle .= $char; + } + } + + return [ + 'x' => (int) $x, + 'y' => (int) $y, + ]; + } + + /** + * Save current position. + */ + public static function save() + { + Console::getOutput()->writeAll( + Console::getTput()->get('save_cursor') + ); + } + + /** + * Restore cursor to the last saved position. + */ + public static function restore() + { + Console::getOutput()->writeAll( + Console::getTput()->get('restore_cursor') + ); + } + + /** + * Clear the screen. + * Part can be: + * • a, all, ↕ : clear entire screen and static::move(1, 1); + * • u, up, ↑ : clear from cursor to beginning of the screen; + * • r, right, → : clear from cursor to the end of the line; + * • d, down, ↓ : clear from cursor to end of the screen; + * • l, left, ← : clear from cursor to beginning of the screen; + * • line, ↔ : clear all the line and static::move(1). + * Parts can be concatenated by a single space. + */ + public static function clear(string $parts = 'all') + { + $tput = Console::getTput(); + $output = Console::getOutput(); + + foreach (\explode(' ', $parts) as $part) { + switch ($part) { + case 'a': + case 'all': + case '↕': + $output->writeAll($tput->get('clear_screen')); + static::moveTo(1, 1); + + break; + + case 'u': + case 'up': + case '↑': + $output->writeAll("\033[1J"); + + break; + + case 'r': + case 'right': + case '→': + $output->writeAll($tput->get('clr_eol')); + + break; + + case 'd': + case 'down': + case '↓': + $output->writeAll($tput->get('clr_eos')); + + break; + + case 'l': + case 'left': + case '←': + $output->writeAll($tput->get('clr_bol')); + + break; + + case 'line': + case '↔': + $output->writeAll("\r".$tput->get('clr_eol')); + + break; + } + } + } + + /** + * Hide the cursor. + */ + public static function hide() + { + Console::getOutput()->writeAll( + Console::getTput()->get('cursor_invisible') + ); + } + + /** + * Show the cursor. + */ + public static function show() + { + Console::getOutput()->writeAll( + Console::getTput()->get('cursor_visible') + ); + } + + /** + * Colorize cursor. + * Attributes can be: + * • n, normal : normal; + * • b, bold : bold; + * • u, underlined : underlined; + * • bl, blink : blink; + * • i, inverse : inverse; + * • !b, !bold : normal weight; + * • !u, !underlined : not underlined; + * • !bl, !blink : steady; + * • !i, !inverse : positive; + * • fg(color), foreground(color) : set foreground to “color”; + * • bg(color), background(color) : set background to “color”. + * “color” can be: + * • default; + * • black; + * • red; + * • green; + * • yellow; + * • blue; + * • magenta; + * • cyan; + * • white; + * • 0-256 (classic palette); + * • #hexa. + * Attributes can be concatenated by a single space. + */ + public static function colorize(string $attributes) + { + static $_rgbTo256 = null; + + if (null === $_rgbTo256) { + $_rgbTo256 = [ + '000000', '800000', '008000', '808000', '000080', '800080', + '008080', 'c0c0c0', '808080', 'ff0000', '00ff00', 'ffff00', + '0000ff', 'ff00ff', '00ffff', 'ffffff', '000000', '00005f', + '000087', '0000af', '0000d7', '0000ff', '005f00', '005f5f', + '005f87', '005faf', '005fd7', '005fff', '008700', '00875f', + '008787', '0087af', '0087d7', '0087ff', '00af00', '00af5f', + '00af87', '00afaf', '00afd7', '00afff', '00d700', '00d75f', + '00d787', '00d7af', '00d7d7', '00d7ff', '00ff00', '00ff5f', + '00ff87', '00ffaf', '00ffd7', '00ffff', '5f0000', '5f005f', + '5f0087', '5f00af', '5f00d7', '5f00ff', '5f5f00', '5f5f5f', + '5f5f87', '5f5faf', '5f5fd7', '5f5fff', '5f8700', '5f875f', + '5f8787', '5f87af', '5f87d7', '5f87ff', '5faf00', '5faf5f', + '5faf87', '5fafaf', '5fafd7', '5fafff', '5fd700', '5fd75f', + '5fd787', '5fd7af', '5fd7d7', '5fd7ff', '5fff00', '5fff5f', + '5fff87', '5fffaf', '5fffd7', '5fffff', '870000', '87005f', + '870087', '8700af', '8700d7', '8700ff', '875f00', '875f5f', + '875f87', '875faf', '875fd7', '875fff', '878700', '87875f', + '878787', '8787af', '8787d7', '8787ff', '87af00', '87af5f', + '87af87', '87afaf', '87afd7', '87afff', '87d700', '87d75f', + '87d787', '87d7af', '87d7d7', '87d7ff', '87ff00', '87ff5f', + '87ff87', '87ffaf', '87ffd7', '87ffff', 'af0000', 'af005f', + 'af0087', 'af00af', 'af00d7', 'af00ff', 'af5f00', 'af5f5f', + 'af5f87', 'af5faf', 'af5fd7', 'af5fff', 'af8700', 'af875f', + 'af8787', 'af87af', 'af87d7', 'af87ff', 'afaf00', 'afaf5f', + 'afaf87', 'afafaf', 'afafd7', 'afafff', 'afd700', 'afd75f', + 'afd787', 'afd7af', 'afd7d7', 'afd7ff', 'afff00', 'afff5f', + 'afff87', 'afffaf', 'afffd7', 'afffff', 'd70000', 'd7005f', + 'd70087', 'd700af', 'd700d7', 'd700ff', 'd75f00', 'd75f5f', + 'd75f87', 'd75faf', 'd75fd7', 'd75fff', 'd78700', 'd7875f', + 'd78787', 'd787af', 'd787d7', 'd787ff', 'd7af00', 'd7af5f', + 'd7af87', 'd7afaf', 'd7afd7', 'd7afff', 'd7d700', 'd7d75f', + 'd7d787', 'd7d7af', 'd7d7d7', 'd7d7ff', 'd7ff00', 'd7ff5f', + 'd7ff87', 'd7ffaf', 'd7ffd7', 'd7ffff', 'ff0000', 'ff005f', + 'ff0087', 'ff00af', 'ff00d7', 'ff00ff', 'ff5f00', 'ff5f5f', + 'ff5f87', 'ff5faf', 'ff5fd7', 'ff5fff', 'ff8700', 'ff875f', + 'ff8787', 'ff87af', 'ff87d7', 'ff87ff', 'ffaf00', 'ffaf5f', + 'ffaf87', 'ffafaf', 'ffafd7', 'ffafff', 'ffd700', 'ffd75f', + 'ffd787', 'ffd7af', 'ffd7d7', 'ffd7ff', 'ffff00', 'ffff5f', + 'ffff87', 'ffffaf', 'ffffd7', 'ffffff', '080808', '121212', + '1c1c1c', '262626', '303030', '3a3a3a', '444444', '4e4e4e', + '585858', '606060', '666666', '767676', '808080', '8a8a8a', + '949494', '9e9e9e', 'a8a8a8', 'b2b2b2', 'bcbcbc', 'c6c6c6', + 'd0d0d0', 'dadada', 'e4e4e4', 'eeeeee', + ]; + } + + $tput = Console::getTput(); + + if (1 >= $tput->count('max_colors')) { + return; + } + + $handle = []; + + foreach (\explode(' ', $attributes) as $attribute) { + switch ($attribute) { + case 'n': + case 'normal': + $handle[] = 0; + + break; + + case 'b': + case 'bold': + $handle[] = 1; + + break; + + case 'u': + case 'underlined': + $handle[] = 4; + + break; + + case 'bl': + case 'blink': + $handle[] = 5; + + break; + + case 'i': + case 'inverse': + $handle[] = 7; + + break; + + case '!b': + case '!bold': + $handle[] = 22; + + break; + + case '!u': + case '!underlined': + $handle[] = 24; + + break; + + case '!bl': + case '!blink': + $handle[] = 25; + + break; + + case '!i': + case '!inverse': + $handle[] = 27; + + break; + + default: + if (0 === \preg_match('#^([^\(]+)\(([^\)]+)\)$#', $attribute, $m)) { + break; + } + + $shift = 0; + + switch ($m[1]) { + case 'fg': + case 'foreground': + $shift = 0; + + break; + + case 'bg': + case 'background': + $shift = 10; + + break; + + default: + break 2; + } + + $_handle = 0; + $_keyword = true; + + switch ($m[2]) { + case 'black': + $_handle = 30; + + break; + + case 'red': + $_handle = 31; + + break; + + case 'green': + $_handle = 32; + + break; + + case 'yellow': + $_handle = 33; + + break; + + case 'blue': + $_handle = 34; + + break; + + case 'magenta': + $_handle = 35; + + break; + + case 'cyan': + $_handle = 36; + + break; + + case 'white': + $_handle = 37; + + break; + + case 'default': + $_handle = 39; + + break; + + default: + $_keyword = false; + + if (256 <= $tput->count('max_colors') && + '#' === $m[2][0]) { + $rgb = \hexdec(\substr($m[2], 1)); + $r = ($rgb >> 16) & 255; + $g = ($rgb >> 8) & 255; + $b = $rgb & 255; + $distance = null; + + foreach ($_rgbTo256 as $i => $_rgb) { + $_rgb = \hexdec($_rgb); + $_r = ($_rgb >> 16) & 255; + $_g = ($_rgb >> 8) & 255; + $_b = $_rgb & 255; + + $d = \sqrt( + ($_r - $r) ** 2 + + ($_g - $g) ** 2 + + ($_b - $b) ** 2 + ); + + if (null === $distance || + $d <= $distance) { + $distance = $d; + $_handle = $i; + } + } + } else { + $_handle = (int) ($m[2]); + } + } + + if (true === $_keyword) { + $handle[] = $_handle + $shift; + } else { + $handle[] = (38 + $shift).';5;'.$_handle; + } + } + } + + Console::getOutput()->writeAll("\033[".\implode(';', $handle).'m'); + + return; + } + + /** + * Change color number to a specific RGB color. + */ + public static function changeColor(int $fromCode, int $toColor) + { + $tput = Console::getTput(); + + if (true !== $tput->has('can_change')) { + return; + } + + $r = ($toColor >> 16) & 255; + $g = ($toColor >> 8) & 255; + $b = $toColor & 255; + + Console::getOutput()->writeAll( + \str_replace( + [ + '%p1%d', + 'rgb:', + '%p2%{255}%*%{1000}%/%2.2X/', + '%p3%{255}%*%{1000}%/%2.2X/', + '%p4%{255}%*%{1000}%/%2.2X', + ], + [ + $fromCode, + '', + \sprintf('%02x', $r), + \sprintf('%02x', $g), + \sprintf('%02x', $b), + ], + $tput->get('initialize_color') + ) + ); + + return; + } + + /** + * Set cursor style. + * Style can be: + * • b, block, ▋: block; + * • u, underline, _: underline; + * • v, vertical, |: vertical. + */ + public static function setStyle(string $style, bool $blink = true) + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + switch ($style) { + case 'u': + case 'underline': + case '_': + $_style = 2; + + break; + + case 'v': + case 'vertical': + case '|': + $_style = 5; + + break; + + case 'b': + case 'block': + case '▋': + default: + $_style = 1; + + break; + } + + if (false === $blink) { + ++$_style; + } + + // Not sure what tput entry we can use here… + Console::getOutput()->writeAll("\033[".$_style.' q'); + + return; + } + + /** + * Make a stupid “bip”. + */ + public static function bip() + { + Console::getOutput()->writeAll( + Console::getTput()->get('bell') + ); + } +} + +/* + * Advanced interaction. + */ +Console::advancedInteraction(); diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleException.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleException.php new file mode 100644 index 0000000..17e6f60 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleException.php @@ -0,0 +1,46 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Exception. + * + * Extending the \Hoa\Exception\Exception class. + */ +class ConsoleException extends Exception +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleInput.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleInput.php new file mode 100644 index 0000000..faa5ce1 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleInput.php @@ -0,0 +1,168 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Console\Input. + * + * This interface represents the input of a program. Most of the time, this is + * going to be `php://stdin` but it can be `/dev/tty` if the former has been + * closed. + */ +class ConsoleInput implements StreamIn +{ + /** + * Real input stream. + */ + protected $_input = null; + + /** + * Wraps an `Hoa\Stream\IStream\In` stream. + */ + public function __construct(StreamIn $input = null) + { + if (null === $input) { + if (\defined('STDIN') && + false !== @\stream_get_meta_data(\STDIN)) { + $input = new FileRead('php://stdin'); + } else { + $input = new FileRead('/dev/tty'); + } + } + + $this->_input = $input; + + return; + } + + /** + * Get underlying stream. + */ + public function getStream(): StreamIn + { + return $this->_input; + } + + /** + * Test for end-of-file. + */ + public function eof(): bool + { + return $this->_input->eof(); + } + + /** + * Read n characters. + */ + public function read(int $length) + { + return $this->_input->read($length); + } + + /** + * Alias of $this->read(). + */ + public function readString(int $length) + { + return $this->_input->readString($length); + } + + /** + * Read a character. + */ + public function readCharacter() + { + return $this->_input->readCharacter(); + } + + /** + * Read a boolean. + */ + public function readBoolean() + { + return $this->_input->readBoolean(); + } + + /** + * Read an integer. + */ + public function readInteger(int $length = 1) + { + return $this->_input->readInteger($length); + } + + /** + * Read a float. + */ + public function readFloat(int $length = 1) + { + return $this->_input->readFloat($length); + } + + /** + * Read an array. + * Alias of the $this->scanf() method. + */ + public function readArray($argument = null) + { + return $this->_input->readArray($argument); + } + + /** + * Read a line. + */ + public function readLine() + { + return $this->_input->readLine(); + } + + /** + * Read all, i.e. read as much as possible. + */ + public function readAll(int $offset = 0) + { + return $this->_input->readAll($offset); + } + + /** + * Parse input from a stream according to a format. + */ + public function scanf(string $format): array + { + return $this->_input->scanf($format); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleOutput.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleOutput.php new file mode 100644 index 0000000..fbba894 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleOutput.php @@ -0,0 +1,208 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Output. + * + * This class represents the output of a program. Most of the time, this is + * going to be STDOUT. + */ +class ConsoleOutput implements StreamOut +{ + /** + * Whether the multiplexer must be considered while writing on the output. + */ + protected $_considerMultiplexer = false; + + /** + * Real output stream. + */ + protected $_output = null; + + /** + * Wraps an `Hoa\Stream\IStream\Out` stream. + */ + public function __construct(StreamOut $output = null) + { + $this->_output = $output; + + return; + } + + /** + * Get the real output stream. + */ + public function getStream(): StreamOut + { + return $this->_output; + } + + /** + * Write n characters. + */ + public function write(string $string, int $length) + { + if (0 > $length) { + throw new ConsoleException('Length must be greater than 0, given %d.', 0, $length); + } + + $out = \substr($string, 0, $length); + + if (true === $this->isMultiplexerConsidered()) { + if (true === Console::isTmuxRunning()) { + $out = + "\033Ptmux;". + \str_replace("\033", "\033\033", $out). + "\033\\"; + } + + $length = \strlen($out); + } + + if (null === $this->_output) { + echo $out; + } else { + $this->_output->write($out, $length); + } + } + + /** + * Write a string. + */ + public function writeString(string $string) + { + $string = (string) $string; + + return $this->write($string, \strlen($string)); + } + + /** + * Write a character. + */ + public function writeCharacter(string $character) + { + return $this->write((string) $character[0], 1); + } + + /** + * Write a boolean. + */ + public function writeBoolean(bool $boolean) + { + return $this->write(((bool) $boolean) ? '1' : '0', 1); + } + + /** + * Write an integer. + */ + public function writeInteger(int $integer) + { + $integer = (string) (int) $integer; + + return $this->write($integer, \strlen($integer)); + } + + /** + * Write a float. + */ + public function writeFloat(float $float) + { + $float = (string) (float) $float; + + return $this->write($float, \strlen($float)); + } + + /** + * Write an array. + */ + public function writeArray(array $array) + { + $array = \var_export($array, true); + + return $this->write($array, \strlen($array)); + } + + /** + * Write a line. + */ + public function writeLine(string $line) + { + if (false === $n = \strpos($line, "\n")) { + return $this->write($line."\n", \strlen($line) + 1); + } + + ++$n; + + return $this->write(\substr($line, 0, $n), $n); + } + + /** + * Write all, i.e. as much as possible. + */ + public function writeAll(string $string) + { + return $this->write($string ?? '', \strlen($string ?? '')); + } + + /** + * Truncate a stream to a given length. + */ + public function truncate(int $size): bool + { + return false; + } + + /** + * Consider the multiplexer (if running) while writing on the output. + */ + public function considerMultiplexer(bool $consider): bool + { + $old = $this->_considerMultiplexer; + $this->_considerMultiplexer = $consider; + + return $old; + } + + /** + * Check whether the multiplexer must be considered or not. + */ + public function isMultiplexerConsidered(): bool + { + return $this->_considerMultiplexer; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleProcessus.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleProcessus.php new file mode 100644 index 0000000..69bf1dd --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleProcessus.php @@ -0,0 +1,892 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Manipulate a processus as a stream. + */ +class ConsoleProcessus extends Stream implements StreamIn, StreamOut, StreamPathable +{ + /** + * Signal: terminal line hangup (terminate process). + */ + const SIGHUP = 1; + + /** + * Signal: interrupt program (terminate process). + */ + const SIGINT = 2; + + /** + * Signal: quit program (create core image). + */ + const SIGQUIT = 3; + + /** + * Signal: illegal instruction (create core image). + */ + const SIGILL = 4; + + /** + * Signal: trace trap (create core image). + */ + const SIGTRAP = 5; + + /** + * Signal: abort program, formerly SIGIOT (create core image). + */ + const SIGABRT = 6; + + /** + * Signal: emulate instruction executed (create core image). + */ + const SIGEMT = 7; + + /** + * Signal: floating-point exception (create core image). + */ + const SIGFPE = 8; + + /** + * Signal: kill program (terminate process). + */ + const SIGKILL = 9; + + /** + * Signal: bus error. + */ + const SIGBUS = 10; + + /** + * Signal: segmentation violation (create core image). + */ + const SIGSEGV = 11; + + /** + * Signal: non-existent system call invoked (create core image). + */ + const SIGSYS = 12; + + /** + * Signal: write on a pipe with no reader (terminate process). + */ + const SIGPIPE = 13; + + /** + * Signal: real-time timer expired (terminate process). + */ + const SIGALRM = 14; + + /** + * Signal: software termination signal (terminate process). + */ + const SIGTERM = 15; + + /** + * Signal: urgent condition present on socket (discard signal). + */ + const SIGURG = 16; + + /** + * Signal: stop, cannot be caught or ignored (stop proces). + */ + const SIGSTOP = 17; + + /** + * Signal: stop signal generated from keyboard (stop process). + */ + const SIGTSTP = 18; + + /** + * Signal: continue after stop (discard signal). + */ + const SIGCONT = 19; + + /** + * Signal: child status has changed (discard signal). + */ + const SIGCHLD = 20; + + /** + * Signal: background read attempted from control terminal (stop process). + */ + const SIGTTIN = 21; + + /** + * Signal: background write attempted to control terminal (stop process). + */ + const SIGTTOU = 22; + + /** + * Signal: I/O is possible on a descriptor, see fcntl(2) (discard signal). + */ + const SIGIO = 23; + + /** + * Signal: cpu time limit exceeded, see setrlimit(2) (terminate process). + */ + const SIGXCPU = 24; + + /** + * Signal: file size limit exceeded, see setrlimit(2) (terminate process). + */ + const SIGXFSZ = 25; + + /** + * Signal: virtual time alarm, see setitimer(2) (terminate process). + */ + const SIGVTALRM = 26; + + /** + * Signal: profiling timer alarm, see setitimer(2) (terminate process). + */ + const SIGPROF = 27; + + /** + * Signal: Window size change (discard signal). + */ + const SIGWINCH = 28; + + /** + * Signal: status request from keyboard (discard signal). + */ + const SIGINFO = 29; + + /** + * Signal: User defined signal 1 (terminate process). + */ + const SIGUSR1 = 30; + + /** + * Signal: User defined signal 2 (terminate process). + */ + const SIGUSR2 = 31; + + /** + * Command name. + */ + protected $_command = null; + + /** + * Command options (options => value, or input). + */ + protected $_options = []; + + /** + * Current working directory. + */ + protected $_cwd = null; + + /** + * Environment. + */ + protected $_environment = null; + + /** + * Timeout. + */ + protected $_timeout = 30; + + /** + * Descriptor. + */ + protected $_descriptors = [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ]; + + /** + * Pipe descriptors of the processus. + */ + protected $_pipes = null; + + /** + * Seekability of pipes. + */ + protected $_seekable = []; + + /** + * Start a processus. + */ + public function __construct( + string $command, + array $options = null, + array $descriptors = null, + string $cwd = null, + array $environment = null, + int $timeout = 30 + ) { + $this->setCommand($command); + + if (null !== $options) { + $this->setOptions($options); + } + + if (null !== $descriptors) { + $this->_descriptors = []; + + foreach ($descriptors as $descriptor => $nature) { + if (isset($this->_descriptors[$descriptor])) { + throw new ConsoleException('Pipe descriptor %d already exists, cannot '.'redefine it.', 0, $descriptor); + } + + $this->_descriptors[$descriptor] = $nature; + } + } + + $this->setCwd($cwd ?: \getcwd()); + + if (null !== $environment) { + $this->setEnvironment($environment); + } + + $this->setTimeout($timeout); + parent::__construct($this->getCommandLine(), null, true); + $this->getListener()->addIds(['input', 'output', 'timeout', 'start', 'stop']); + + return; + } + + /** + * Open the stream and return the associated resource. + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + $out = @\proc_open( + $streamName, + $this->_descriptors, + $this->_pipes, + $this->getCwd(), + $this->getEnvironment() + ); + + if (false === $out) { + throw new ConsoleException('Something wrong happen when running %s.', 1, $streamName); + } + + return $out; + } + + /** + * Close the current stream. + */ + protected function _close(): bool + { + foreach ($this->_pipes as $pipe) { + @\fclose($pipe); + } + + return (bool) @\proc_close($this->getStream()); + } + + /** + * Run the process and fire events (amongst start, stop, input, output and + * timeout). + * If an event returns false, it will close the current pipe. + * For a simple run without firing events, use the $this->open() method. + */ + public function run() + { + if (false === $this->isOpened()) { + $this->open(); + } else { + $this->_close(); + $this->_setStream($this->_open( + $this->getStreamName(), + $this->getStreamContext() + )); + } + + $this->getListener()->fire('start', new EventBucket()); + + $_read = []; + $_write = []; + $_except = []; + + foreach ($this->_pipes as $p => $pipe) { + switch ($this->_descriptors[$p][1]) { + case 'r': + \stream_set_blocking($pipe, false); + $_write[] = $pipe; + + break; + + case 'w': + case 'a': + \stream_set_blocking($pipe, true); + $_read[] = $pipe; + + break; + } + } + + while (true) { + foreach ($_read as $i => $r) { + if (false === \is_resource($r)) { + unset($_read[$i]); + } + } + + foreach ($_write as $i => $w) { + if (false === \is_resource($w)) { + unset($_write[$i]); + } + } + + foreach ($_except as $i => $e) { + if (false === \is_resource($e)) { + unset($_except[$i]); + } + } + + if (empty($_read) && empty($_write) && empty($_except)) { + break; + } + + $read = $_read; + $write = $_write; + $except = $_except; + $select = \stream_select($read, $write, $except, $this->getTimeout()); + + if (0 === $select) { + $this->getListener()->fire('timeout', new EventBucket()); + + break; + } + + foreach ($read as $i => $_r) { + $pipe = \array_search($_r, $this->_pipes); + $line = $this->readLine($pipe); + + if (false === $line) { + $result = [false]; + } else { + $result = $this->getListener()->fire( + 'output', + new EventBucket([ + 'pipe' => $pipe, + 'line' => $line, + ]) + ); + } + + if (true === \feof($_r) || \in_array(false, $result, true)) { + \fclose($_r); + unset($_read[$i]); + + break; + } + } + + foreach ($write as $j => $_w) { + $result = $this->getListener()->fire( + 'input', + new EventBucket([ + 'pipe' => \array_search($_w, $this->_pipes), + ]) + ); + + if (true === \feof($_w) || \in_array(false, $result, true)) { + \fclose($_w); + unset($_write[$j]); + } + } + + if (empty($_read)) { + break; + } + } + + $this->getListener()->fire('stop', new EventBucket()); + + return; + } + + /** + * Get pipe resource. + */ + protected function getPipe(int $pipe) + { + if (!isset($this->_pipes[$pipe])) { + throw new ConsoleException('Pipe descriptor %d does not exist, cannot read from it.', 2, $pipe); + } + + return $this->_pipes[$pipe]; + } + + /** + * Check if a pipe is seekable or not. + */ + protected function isPipeSeekable(int $pipe): bool + { + if (!isset($this->_seekable[$pipe])) { + $_pipe = $this->getPipe($pipe); + $data = \stream_get_meta_data($_pipe); + $this->_seekable[$pipe] = $data['seekable']; + } + + return $this->_seekable[$pipe]; + } + + /** + * Test for end-of-file. + */ + public function eof(int $pipe = 1): bool + { + return \feof($this->getPipe($pipe)); + } + + /** + * Read n characters. + */ + public function read(int $length, int $pipe = 1) + { + if (0 > $length) { + throw new ConsoleException('Length must be greater than 0, given %d.', 3, $length); + } + + return \fread($this->getPipe($pipe), $length); + } + + /** + * Alias of $this->read(). + */ + public function readString(int $length, int $pipe = 1) + { + return $this->read($length, $pipe); + } + + /** + * Read a character. + */ + public function readCharacter(int $pipe = 1) + { + return \fgetc($this->getPipe($pipe)); + } + + /** + * Read a boolean. + */ + public function readBoolean(int $pipe = 1) + { + return (bool) $this->read(1, $pipe); + } + + /** + * Read an integer. + */ + public function readInteger(int $length = 1, int $pipe = 1) + { + return (int) $this->read($length, $pipe); + } + + /** + * Read a float. + */ + public function readFloat(int $length = 1, int $pipe = 1) + { + return (float) $this->read($length, $pipe); + } + + /** + * Read an array. + * Alias of the $this->scanf() method. + */ + public function readArray(string $format = null, int $pipe = 1) + { + return $this->scanf($format, $pipe); + } + + /** + * Read a line. + */ + public function readLine(int $pipe = 1) + { + return \stream_get_line($this->getPipe($pipe), 1 << 15, "\n"); + } + + /** + * Read all, i.e. read as much as possible. + */ + public function readAll(int $offset = -1, int $pipe = 1) + { + $_pipe = $this->getPipe($pipe); + + if (true === $this->isPipeSeekable($pipe)) { + $offset += \ftell($_pipe); + } else { + $offset = -1; + } + + return \stream_get_contents($_pipe, -1, $offset); + } + + /** + * Parse input from a stream according to a format. + */ + public function scanf(string $format, int $pipe = 1): array + { + return \fscanf($this->getPipe($pipe), $format); + } + + /** + * Write n characters. + */ + public function write(string $string, int $length, int $pipe = 0) + { + if (0 > $length) { + throw new ConsoleException('Length must be greater than 0, given %d.', 4, $length); + } + + return \fwrite($this->getPipe($pipe), $string, $length); + } + + /** + * Write a string. + */ + public function writeString(string $string, int $pipe = 0) + { + $string = (string) $string; + + return $this->write($string, \strlen($string), $pipe); + } + + /** + * Write a character. + */ + public function writeCharacter(string $char, int $pipe = 0) + { + return $this->write((string) $char[0], 1, $pipe); + } + + /** + * Write a boolean. + */ + public function writeBoolean(bool $boolean, int $pipe = 0) + { + return $this->write((string) (bool) $boolean, 1, $pipe); + } + + /** + * Write an integer. + */ + public function writeInteger(int $integer, int $pipe = 0) + { + $integer = (string) (int) $integer; + + return $this->write($integer, \strlen($integer), $pipe); + } + + /** + * Write a float. + */ + public function writeFloat(float $float, int $pipe = 0) + { + $float = (string) (float) $float; + + return $this->write($float, \strlen($float), $pipe); + } + + /** + * Write an array. + */ + public function writeArray(array $array, int $pipe = 0) + { + $array = \var_export($array, true); + + return $this->write($array, \strlen($array), $pipe); + } + + /** + * Write a line. + */ + public function writeLine(string $line, int $pipe = 0) + { + if (false === $n = \strpos($line, "\n")) { + return $this->write($line."\n", \strlen($line) + 1, $pipe); + } + + ++$n; + + return $this->write(\substr($line, 0, $n), $n, $pipe); + } + + /** + * Write all, i.e. as much as possible. + */ + public function writeAll(string $string, int $pipe = 0) + { + return $this->write($string, \strlen($string), $pipe); + } + + /** + * Truncate a file to a given length. + */ + public function truncate(int $size, int $pipe = 0): bool + { + return \ftruncate($this->getPipe($pipe), $size); + } + + /** + * Get filename component of path. + */ + public function getBasename(): string + { + return \basename($this->getCommand()); + } + + /** + * Get directory name component of path. + */ + public function getDirname(): string + { + return \dirname($this->getCommand()); + } + + /** + * Get status. + */ + public function getStatus(): array + { + return \proc_get_status($this->getStream()); + } + + /** + * Get exit code (alias of $this->getStatus()['exitcode']);. + */ + public function getExitCode(): int + { + $handle = $this->getStatus(); + + return $handle['exitcode']; + } + + /** + * Whether the processus have ended successfully. + * + * @return bool + */ + public function isSuccessful(): bool + { + return 0 === $this->getExitCode(); + } + + /** + * Terminate the process. + * + * Valid signals are self::SIGHUP, SIGINT, SIGQUIT, SIGABRT, SIGKILL, + * SIGALRM and SIGTERM. + */ + public function terminate(int $signal = self::SIGTERM): bool + { + return \proc_terminate($this->getStream(), $signal); + } + + /** + * Set command name. + */ + protected function setCommand(string $command) + { + $old = $this->_command; + $this->_command = \escapeshellcmd($command); + + return $old; + } + + /** + * Get command name. + */ + public function getCommand() + { + return $this->_command; + } + + /** + * Set command options. + */ + protected function setOptions(array $options): array + { + foreach ($options as &$option) { + $option = \escapeshellarg($option); + } + + $old = $this->_options; + $this->_options = $options; + + return $old; + } + + /** + * Get options. + */ + public function getOptions(): array + { + return $this->_options; + } + + /** + * Get command-line. + */ + public function getCommandLine(): string + { + $out = $this->getCommand(); + + foreach ($this->getOptions() as $key => $value) { + if (!\is_int($key)) { + $out .= ' '.$key.'='.$value; + } else { + $out .= ' '.$value; + } + } + + return $out; + } + + /** + * Set current working directory of the process. + */ + protected function setCwd(string $cwd) + { + $old = $this->_cwd; + $this->_cwd = $cwd; + + return $old; + } + + /** + * Get current working directory of the process. + */ + public function getCwd(): string + { + return $this->_cwd; + } + + /** + * Set environment of the process. + */ + protected function setEnvironment(array $environment) + { + $old = $this->_environment; + $this->_environment = $environment; + + return $old; + } + + /** + * Get environment of the process. + */ + public function getEnvironment() + { + return $this->_environment; + } + + /** + * Set timeout of the process. + */ + public function setTimeout(int $timeout) + { + $old = $this->_timeout; + $this->_timeout = $timeout; + + return $old; + } + + /** + * Get timeout of the process. + */ + public function getTimeout(): int + { + return $this->_timeout; + } + + /** + * Set process title. + */ + public static function setTitle(string $title) + { + \cli_set_process_title($title); + } + + /** + * Get process title. + */ + public static function getTitle() + { + return \cli_get_process_title(); + } + + /** + * Found the place of a binary. + */ + public static function locate(string $binary) + { + if (isset($_ENV['PATH'])) { + $separator = ':'; + $path = &$_ENV['PATH']; + } elseif (isset($_SERVER['PATH'])) { + $separator = ':'; + $path = &$_SERVER['PATH']; + } elseif (isset($_SERVER['Path'])) { + $separator = ';'; + $path = &$_SERVER['Path']; + } else { + return null; + } + + foreach (\explode($separator, $path) as $directory) { + if (true === \file_exists($out = $directory.\DIRECTORY_SEPARATOR.$binary)) { + return $out; + } + } + + return null; + } + + /** + * Quick process execution. + * Returns only the STDOUT. + */ + public static function execute(string $commandLine, bool $escape = true): string + { + if (true === $escape) { + $commandLine = \escapeshellcmd($commandLine); + } + + return \rtrim(\shell_exec($commandLine) ?? ''); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleTput.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleTput.php new file mode 100644 index 0000000..ba627e3 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleTput.php @@ -0,0 +1,841 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Tput. + * + * Query terminfo database. + * Resources: + * • http://man.cx/terminfo(5), + * • http://pubs.opengroup.org/onlinepubs/7908799/xcurses/terminfo.html, + */ +class ConsoleTput +{ + /** + * Booleans. + */ + protected static $_booleans = [ + 'auto_left_margin', + 'auto_right_margin', + 'no_esc_ctlc', + 'ceol_standout_glitch', + 'eat_newline_glitch', + 'erase_overstrike', + 'generic_type', + 'hard_copy', + 'meta_key', // originally has_meta_key + 'status_line', // originally has_status_line + 'insert_null_glitch', + 'memory_above', + 'memory_below', + 'move_insert_mode', + 'move_standout_mode', + 'over_strike', + 'status_line_esc_ok', + 'dest_tabs_magic_smso', + 'tilde_glitch', + 'transparent_underline', + 'xon_xoff', + 'needs_xon_xoff', + 'prtr_silent', + 'hard_cursor', + 'non_rev_rmcup', + 'no_pad_char', + 'non_dest_scroll_region', + 'can_change', + 'back_color_erase', + 'hue_lightness_saturation', + 'col_addr_glitch', + 'cr_cancels_micro_mode', + 'print_wheel', // originally has_print_wheel + 'row_addr_glitch', + 'semi_auto_right_margin', + 'cpi_changes_res', + 'lpi_changes_res', + // #ifdef __INTERNAL_CAPS_VISIBLE + 'backspaces_with_bs', + 'crt_no_scrolling', + 'no_correctly_working_cr', + 'gnu_meta_key', // originally gnu_has_meta_key + 'linefeed_is_newline', + 'hardware_tabs', // originally has_hardware_tabs + 'return_does_clr_eol', + ]; + + /** + * Numbers. + */ + protected static $_numbers = [ + 'columns', + 'init_tabs', + 'lines', + 'lines_of_memory', + 'magic_cookie_glitch', + 'padding_baud_rate', + 'virtual_terminal', + 'width_status_line', + 'num_labels', + 'label_height', + 'label_width', + 'max_attributes', + 'maximum_windows', + 'max_colors', + 'max_pairs', + 'no_color_video', + 'buffer_capacity', + 'dot_vert_spacing', + 'dot_horz_spacing', + 'max_micro_address', + 'max_micro_jump', + 'micro_col_size', + 'micro_line_size', + 'number_of_pins', + 'output_res_char', + 'output_res_line', + 'output_res_horz_inch', + 'output_res_vert_inch', + 'print_rate', + 'wide_char_size', + 'buttons', + 'bit_image_entwining', + 'bit_image_type', + // #ifdef __INTERNAL_CAPS_VISIBLE + 'magic_cookie_glitch_ul', + 'carriage_return_delay', + 'new_line_delay', + 'backspace_delay', + 'horizontal_tab_delay', + 'number_of_function_keys', + ]; + + /** + * Strings. + */ + protected static $_strings = [ + 'back_tab', + 'bell', + 'carriage_return', + 'change_scroll_region', + 'clear_all_tabs', + 'clear_screen', + 'clr_eol', + 'clr_eos', + 'column_address', + 'command_character', + 'cursor_address', + 'cursor_down', + 'cursor_home', + 'cursor_invisible', + 'cursor_left', + 'cursor_mem_address', + 'cursor_normal', + 'cursor_right', + 'cursor_to_ll', + 'cursor_up', + 'cursor_visible', + 'delete_character', + 'delete_line', + 'dis_status_line', + 'down_half_line', + 'enter_alt_charset_mode', + 'enter_blink_mode', + 'enter_bold_mode', + 'enter_ca_mode', + 'enter_delete_mode', + 'enter_dim_mode', + 'enter_insert_mode', + 'enter_secure_mode', + 'enter_protected_mode', + 'enter_reverse_mode', + 'enter_standout_mode', + 'enter_underline_mode', + 'erase_chars', + 'exit_alt_charset_mode', + 'exit_attribute_mode', + 'exit_ca_mode', + 'exit_delete_mode', + 'exit_insert_mode', + 'exit_standout_mode', + 'exit_underline_mode', + 'flash_screen', + 'form_feed', + 'from_status_line', + 'init_1string', + 'init_2string', + 'init_3string', + 'init_file', + 'insert_character', + 'insert_line', + 'insert_padding', + 'key_backspace', + 'key_catab', + 'key_clear', + 'key_ctab', + 'key_dc', + 'key_dl', + 'key_down', + 'key_eic', + 'key_eol', + 'key_eos', + 'key_f0', + 'key_f1', + 'key_f10', + 'key_f2', + 'key_f3', + 'key_f4', + 'key_f5', + 'key_f6', + 'key_f7', + 'key_f8', + 'key_f9', + 'key_home', + 'key_ic', + 'key_il', + 'key_left', + 'key_ll', + 'key_npage', + 'key_ppage', + 'key_right', + 'key_sf', + 'key_sr', + 'key_stab', + 'key_up', + 'keypad_local', + 'keypad_xmit', + 'lab_f0', + 'lab_f1', + 'lab_f10', + 'lab_f2', + 'lab_f3', + 'lab_f4', + 'lab_f5', + 'lab_f6', + 'lab_f7', + 'lab_f8', + 'lab_f9', + 'meta_off', + 'meta_on', + 'newline', + 'pad_char', + 'parm_dch', + 'parm_delete_line', + 'parm_down_cursor', + 'parm_ich', + 'parm_index', + 'parm_insert_line', + 'parm_left_cursor', + 'parm_right_cursor', + 'parm_rindex', + 'parm_up_cursor', + 'pkey_key', + 'pkey_local', + 'pkey_xmit', + 'print_screen', + 'prtr_off', + 'prtr_on', + 'repeat_char', + 'reset_1string', + 'reset_2string', + 'reset_3string', + 'reset_file', + 'restore_cursor', + 'row_address', + 'save_cursor', + 'scroll_forward', + 'scroll_reverse', + 'set_attributes', + 'set_tab', + 'set_window', + 'tab', + 'to_status_line', + 'underline_char', + 'up_half_line', + 'init_prog', + 'key_a1', + 'key_a3', + 'key_b2', + 'key_c1', + 'key_c3', + 'prtr_non', + 'char_padding', + 'acs_chars', + 'plab_norm', + 'key_btab', + 'enter_xon_mode', + 'exit_xon_mode', + 'enter_am_mode', + 'exit_am_mode', + 'xon_character', + 'xoff_character', + 'ena_acs', + 'label_on', + 'label_off', + 'key_beg', + 'key_cancel', + 'key_close', + 'key_command', + 'key_copy', + 'key_create', + 'key_end', + 'key_enter', + 'key_exit', + 'key_find', + 'key_help', + 'key_mark', + 'key_message', + 'key_move', + 'key_next', + 'key_open', + 'key_options', + 'key_previous', + 'key_print', + 'key_redo', + 'key_reference', + 'key_refresh', + 'key_replace', + 'key_restart', + 'key_resume', + 'key_save', + 'key_suspend', + 'key_undo', + 'key_sbeg', + 'key_scancel', + 'key_scommand', + 'key_scopy', + 'key_screate', + 'key_sdc', + 'key_sdl', + 'key_select', + 'key_send', + 'key_seol', + 'key_sexit', + 'key_sfind', + 'key_shelp', + 'key_shome', + 'key_sic', + 'key_sleft', + 'key_smessage', + 'key_smove', + 'key_snext', + 'key_soptions', + 'key_sprevious', + 'key_sprint', + 'key_sredo', + 'key_sreplace', + 'key_sright', + 'key_srsume', + 'key_ssave', + 'key_ssuspend', + 'key_sundo', + 'req_for_input', + 'key_f11', + 'key_f12', + 'key_f13', + 'key_f14', + 'key_f15', + 'key_f16', + 'key_f17', + 'key_f18', + 'key_f19', + 'key_f20', + 'key_f21', + 'key_f22', + 'key_f23', + 'key_f24', + 'key_f25', + 'key_f26', + 'key_f27', + 'key_f28', + 'key_f29', + 'key_f30', + 'key_f31', + 'key_f32', + 'key_f33', + 'key_f34', + 'key_f35', + 'key_f36', + 'key_f37', + 'key_f38', + 'key_f39', + 'key_f40', + 'key_f41', + 'key_f42', + 'key_f43', + 'key_f44', + 'key_f45', + 'key_f46', + 'key_f47', + 'key_f48', + 'key_f49', + 'key_f50', + 'key_f51', + 'key_f52', + 'key_f53', + 'key_f54', + 'key_f55', + 'key_f56', + 'key_f57', + 'key_f58', + 'key_f59', + 'key_f60', + 'key_f61', + 'key_f62', + 'key_f63', + 'clr_bol', + 'clear_margins', + 'set_left_margin', + 'set_right_margin', + 'label_format', + 'set_clock', + 'display_clock', + 'remove_clock', + 'create_window', + 'goto_window', + 'hangup', + 'dial_phone', + 'quick_dial', + 'tone', + 'pulse', + 'flash_hook', + 'fixed_pause', + 'wait_tone', + 'user0', + 'user1', + 'user2', + 'user3', + 'user4', + 'user5', + 'user6', + 'user7', + 'user8', + 'user9', + 'orig_pair', + 'orig_colors', + 'initialize_color', + 'initialize_pair', + 'set_color_pair', + 'set_foreground', + 'set_background', + 'change_char_pitch', + 'change_line_pitch', + 'change_res_horz', + 'change_res_vert', + 'define_char', + 'enter_doublewide_mode', + 'enter_draft_quality', + 'enter_italics_mode', + 'enter_leftward_mode', + 'enter_micro_mode', + 'enter_near_letter_quality', + 'enter_normal_quality', + 'enter_shadow_mode', + 'enter_subscript_mode', + 'enter_superscript_mode', + 'enter_upward_mode', + 'exit_doublewide_mode', + 'exit_italics_mode', + 'exit_leftward_mode', + 'exit_micro_mode', + 'exit_shadow_mode', + 'exit_subscript_mode', + 'exit_superscript_mode', + 'exit_upward_mode', + 'micro_column_address', + 'micro_down', + 'micro_left', + 'micro_right', + 'micro_row_address', + 'micro_up', + 'order_of_pins', + 'parm_down_micro', + 'parm_left_micro', + 'parm_right_micro', + 'parm_up_micro', + 'select_char_set', + 'set_bottom_margin', + 'set_bottom_margin_parm', + 'set_left_margin_parm', + 'set_right_margin_parm', + 'set_top_margin', + 'set_top_margin_parm', + 'start_bit_image', + 'start_char_set_def', + 'stop_bit_image', + 'stop_char_set_def', + 'subscript_characters', + 'superscript_characters', + 'these_cause_cr', + 'zero_motion', + 'char_set_names', + 'key_mouse', + 'mouse_info', + 'req_mouse_pos', + 'get_mouse', + 'set_a_foreground', + 'set_a_background', + 'pkey_plab', + 'device_type', + 'code_set_init', + 'set0_des_seq', + 'set1_des_seq', + 'set2_des_seq', + 'set3_des_seq', + 'set_lr_margin', + 'set_tb_margin', + 'bit_image_repeat', + 'bit_image_newline', + 'bit_image_carriage_return', + 'color_names', + 'define_bit_image_region', + 'end_bit_image_region', + 'set_color_band', + 'set_page_length', + 'display_pc_char', + 'enter_pc_charset_mode', + 'exit_pc_charset_mode', + 'enter_scancode_mode', + 'exit_scancode_mode', + 'pc_term_options', + 'scancode_escape', + 'alt_scancode_esc', + 'enter_horizontal_hl_mode', + 'enter_left_hl_mode', + 'enter_low_hl_mode', + 'enter_right_hl_mode', + 'enter_top_hl_mode', + 'enter_vertical_hl_mode', + 'set_a_attributes', + 'set_pglen_inch', + // #ifdef __INTERNAL_CAPS_VISIBLE + 'termcap_init2', + 'termcap_reset', + 'linefeed_if_not_lf', + 'backspace_if_not_bs', + 'other_non_function_keys', + 'arrow_key_map', + 'acs_ulcorner', + 'acs_llcorner', + 'acs_urcorner', + 'acs_lrcorner', + 'acs_ltee', + 'acs_rtee', + 'acs_btee', + 'acs_ttee', + 'acs_hline', + 'acs_vline', + 'acs_plus', + 'memory_lock', + 'memory_unlock', + 'box_chars_1', + ]; + + /** + * Computed informations. + */ + protected $_informations = []; + + /** + * Set stream and parse. + */ + public function __construct($terminfo = null) + { + if (null === $terminfo) { + $terminfo = static::getTerminfo(); + } + + $this->parse($terminfo); + + return; + } + + /** + * Parse. + */ + protected function parse(string $terminfo): array + { + if (!\file_exists($terminfo)) { + throw new ConsoleException('Terminfo file %s does not exist.', 0, $terminfo); + } + + $data = \file_get_contents($terminfo); + $length = \strlen($data); + $out = ['file' => $terminfo]; + + $headers = [ + 'data_size' => $length, + 'header_size' => 12, + 'magic_number' => (\ord($data[1]) << 8) | \ord($data[0]), + 'names_size' => (\ord($data[3]) << 8) | \ord($data[2]), + 'bool_count' => (\ord($data[5]) << 8) | \ord($data[4]), + 'number_count' => (\ord($data[7]) << 8) | \ord($data[6]), + 'string_count' => (\ord($data[9]) << 8) | \ord($data[8]), + 'string_table_size' => (\ord($data[11]) << 8) | \ord($data[10]), + ]; + $out['headers'] = $headers; + + // Names. + $i = $headers['header_size']; + $nameAndDescription = \explode('|', \substr($data, $i, $headers['names_size'] - 1)); + $out['name'] = $nameAndDescription[0]; + $out['description'] = $nameAndDescription[1]; + + // Booleans. + $i += $headers['names_size']; + $booleans = []; + $booleanNames = &static::$_booleans; + + for ( + $e = 0, $max = $i + $headers['bool_count']; + $i < $max; + ++$e, ++$i + ) { + $booleans[$booleanNames[$e]] = 1 === \ord($data[$i]); + } + + $out['booleans'] = $booleans; + + // Numbers. + if (1 === ($i % 2)) { + ++$i; + } + + $numbers = []; + $numberNames = &static::$_numbers; + + for ( + $e = 0, $max = $i + $headers['number_count'] * 2; + $i < $max; + ++$e, $i += 2 + ) { + $name = $numberNames[$e]; + $data_i0 = \ord($data[$i]); + $data_i1 = \ord($data[$i + 1]); + + if ($data_i1 === 255 && $data_i0 === 255) { + $numbers[$name] = -1; + } else { + $numbers[$name] = ($data_i1 << 8) | $data_i0; + } + } + + $out['numbers'] = $numbers; + + // Strings. + $strings = []; + $stringNames = &static::$_strings; + $ii = $i + $headers['string_count'] * 2; + + for ( + $e = 0, $max = $ii; + $i < $max; + ++$e, $i += 2 + ) { + $name = $stringNames[$e]; + $data_i0 = \ord($data[$i]); + $data_i1 = \ord($data[$i + 1]); + + if ($data_i1 === 255 && $data_i0 === 255) { + continue; + } + + $a = ($data_i1 << 8) | $data_i0; + $strings[$name] = $a; + + if (65534 === $a) { + continue; + } + + $b = $ii + $a; + $c = $b; + + while ($c < $length && \ord($data[$c])) { + $c++; + } + + $value = \substr($data, $b, $c - $b); + $strings[$name] = false !== $value ? $value : null; + } + + $out['strings'] = $strings; + + return $this->_informations = $out; + } + + /** + * Get all informations. + */ + public function getInformations(): array + { + return $this->_informations; + } + + /** + * Get a boolean value. + */ + public function has(string $boolean): bool + { + if (!isset($this->_informations['booleans'][$boolean])) { + return false; + } + + return $this->_informations['booleans'][$boolean]; + } + + /** + * Get a number value. + */ + public function count(string $number): int + { + if (!isset($this->_informations['numbers'][$number])) { + return 0; + } + + return $this->_informations['numbers'][$number]; + } + + /** + * Get a string value. + */ + public function get(string $string) + { + if (!isset($this->_informations['strings'][$string])) { + return null; + } + + return $this->_informations['strings'][$string]; + } + + /** + * Get current term profile. + */ + public static function getTerm(): string + { + return + isset($_SERVER['TERM']) && !empty($_SERVER['TERM']) + ? $_SERVER['TERM'] + : (\defined('PHP_WINDOWS_VERSION_PLATFORM') ? 'windows-ansi' : 'xterm'); + } + + /** + * Get pathname to the current terminfo. + */ + public static function getTerminfo($term = null): string + { + $paths = []; + + if (isset($_SERVER['TERMINFO'])) { + $paths[] = $_SERVER['TERMINFO']; + } + + if (isset($_SERVER['HOME'])) { + $paths[] = $_SERVER['HOME'].\DIRECTORY_SEPARATOR.'.terminfo'; + } + + if (isset($_SERVER['TERMINFO_DIRS'])) { + foreach (\explode(':', $_SERVER['TERMINFO_DIRS']) as $path) { + $paths[] = $path; + } + } + + $paths[] = '/usr/share/terminfo'; + $paths[] = '/usr/share/lib/terminfo'; + $paths[] = '/lib/terminfo'; + $paths[] = '/usr/lib/terminfo'; + $paths[] = '/usr/local/share/terminfo'; + $paths[] = '/usr/local/share/lib/terminfo'; + $paths[] = '/usr/local/lib/terminfo'; + $paths[] = '/usr/local/ncurses/lib/terminfo'; + $paths[] = 'hoa://Library/Terminfo'; + + $term = $term ?: static::getTerm(); + $fileHexa = \dechex(\ord($term[0])).\DIRECTORY_SEPARATOR.$term; + $fileAlpha = $term[0].\DIRECTORY_SEPARATOR.$term; + $pathname = null; + + foreach ($paths as $path) { + if (\file_exists($_ = $path.\DIRECTORY_SEPARATOR.$fileHexa) || + \file_exists($_ = $path.\DIRECTORY_SEPARATOR.$fileAlpha)) { + $pathname = $_; + + break; + } + } + + if (null === $pathname && 'xterm' !== $term) { + return static::getTerminfo('xterm'); + } + + return $pathname ?? ''; + } + + /** + * Check whether all required terminfo capabilities are defined. + */ + public static function isSupported(): bool + { + if (static::getTerminfo() === '') { + return false; + } + + $requiredVars = [ + 'clear_screen', + 'clr_bol', + 'clr_eol', + 'clr_eos', + 'initialize_color', + 'parm_down_cursor', + 'parm_index', + 'parm_left_cursor', + 'parm_right_cursor', + 'parm_rindex', + 'parm_up_cursor', + 'user6', + 'user7', + ]; + + $tput = new self(); + + foreach ($requiredVars as $var) { + if ($tput->get($var) === null) { + return false; + } + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleWindow.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleWindow.php new file mode 100644 index 0000000..fe77e05 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ConsoleWindow.php @@ -0,0 +1,529 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Allow to manipulate the window. + * + * We can listen the event channel hoa://Event/Console/Window:resize to detect + * if the window has been resized. Please, see the constructor documentation to + * get more informations. + */ +class ConsoleWindow implements EventSource +{ + /** + * Singleton (only for events). + */ + private static $_instance = null; + + /** + * Set the event channel. + * We need to declare(ticks = 1) in the main script to ensure that the event + * is fired. Also, we need the pcntl_signal() function enabled. + */ + private function __construct() + { + Event::register( + 'hoa://Event/Console/Window:resize', + $this + ); + + return; + } + + /** + * Singleton. + */ + public static function getInstance(): self + { + if (null === static::$_instance) { + static::$_instance = new self(); + } + + return static::$_instance; + } + + /** + * Set size to X lines and Y columns. + */ + public static function setSize(int $x, int $y) + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + Console::getOutput()->writeAll("\033[8;".$y.';'.$x.'t'); + + return; + } + + /** + * Get current size (x and y) of the window. + */ + public static function getSize(): array + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + $modecon = \explode("\n", \ltrim(ConsoleProcessus::execute('mode con'))); + + $_y = \trim($modecon[2]); + \preg_match('#[^:]+:\s*([0-9]+)#', $_y, $matches); + $y = (int) $matches[1]; + + $_x = \trim($modecon[3]); + \preg_match('#[^:]+:\s*([0-9]+)#', $_x, $matches); + $x = (int) $matches[1]; + + return [ + 'x' => $x, + 'y' => $y, + ]; + } + + $term = ''; + + if (isset($_SERVER['TERM'])) { + $term = 'TERM="'.$_SERVER['TERM'].'" '; + } + + $command = $term.'tput cols && '.$term.'tput lines'; + $tput = ConsoleProcessus::execute($command, false); + + if (!empty($tput)) { + list($x, $y) = \explode("\n", $tput); + + return [ + 'x' => (int) $x, + 'y' => (int) $y, + ]; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[18t"); + + $input = Console::getInput(); + + // Read \033[8;y;xt. + $input->read(4); // skip \033, [, 8 and ;. + + $x = null; + $y = null; + $handle = &$y; + + while (true) { + $char = $input->readCharacter(); + + switch ($char) { + case ';': + $handle = &$x; + + break; + + case 't': + break 2; + + default: + if (false === \ctype_digit($char)) { + break 2; + } + + $handle .= $char; + } + } + + if (null === $x || null === $y) { + return [ + 'x' => 0, + 'y' => 0, + ]; + } + + return [ + 'x' => (int) $x, + 'y' => (int) $y, + ]; + } + + /** + * Move to X and Y (in pixels). + */ + public static function moveTo(int $x, int $y) + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[3;".$x.';'.$y.'t'); + + return; + } + + /** + * Get current position (x and y) of the window (in pixels). + */ + public static function getPosition(): array + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return ['x' => 0, 'y' => 0]; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[13t"); + + $input = Console::getInput(); + + // Read \033[3;x;yt. + $input->read(4); // skip \033, [, 3 and ;. + + $x = null; + $y = null; + $handle = &$x; + + while (true) { + $char = $input->readCharacter(); + + switch ($char) { + case ';': + $handle = &$y; + + break; + + case 't': + break 2; + + default: + $handle .= $char; + } + } + + return [ + 'x' => (int) $x, + 'y' => (int) $y, + ]; + } + + /** + * Scroll whole page. + * Directions can be: + * • u, up, ↑ : scroll whole page up; + * • d, down, ↓ : scroll whole page down. + * Directions can be concatenated by a single space. + */ + public static function scroll(string $directions, int $repeat = 1) + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + if (1 > $repeat) { + return; + } elseif (1 === $repeat) { + $handle = \explode(' ', $directions); + } else { + $handle = \explode(' ', $directions, 1); + } + + $tput = Console::getTput(); + $count = ['up' => 0, 'down' => 0]; + + foreach ($handle as $direction) { + switch ($direction) { + case 'u': + case 'up': + case '↑': + ++$count['up']; + + break; + + case 'd': + case 'down': + case '↓': + ++$count['down']; + + break; + } + } + + $output = Console::getOutput(); + + if (0 < $count['up']) { + $output->writeAll( + \str_replace( + '%p1%d', + $count['up'] * $repeat, + $tput->get('parm_index') + ) + ); + } + + if (0 < $count['down']) { + $output->writeAll( + \str_replace( + '%p1%d', + $count['down'] * $repeat, + $tput->get('parm_rindex') + ) + ); + } + + return; + } + + /** + * Minimize the window. + */ + public static function minimize() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[2t"); + + return; + } + + /** + * Restore the window (de-minimize). + */ + public static function restore() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + Console::getOutput()->writeAll("\033[1t"); + + return; + } + + /** + * Raise the window to the front of the stacking order. + */ + public static function raise() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + Console::getOutput()->writeAll("\033[5t"); + + return; + } + + /** + * Lower the window to the bottom of the stacking order. + */ + public static function lower() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + Console::getOutput()->writeAll("\033[6t"); + + return; + } + + /** + * Set title. + */ + public static function setTitle(string $title) + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033]0;".$title."\033\\"); + + return; + } + + /** + * Get title. + */ + public static function getTitle() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return null; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[21t"); + + $input = Console::getInput(); + $read = [$input->getStream()->getStream()]; + $write = []; + $except = []; + $out = null; + + if (0 === \stream_select($read, $write, $except, 0, 50000)) { + return $out; + } + + // Read \033]l<title>\033\ + $input->read(3); // skip \033, ] and l. + + while (true) { + $char = $input->readCharacter(); + + if ("\033" === $char) { + $chaar = $input->readCharacter(); + + if ('\\' === $chaar) { + break; + } + + $char .= $chaar; + } + + $out .= $char; + } + + return $out; + } + + /** + * Get label. + */ + public static function getLabel() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return null; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[20t"); + + $input = Console::getInput(); + $read = [$input->getStream()->getStream()]; + $write = []; + $except = []; + $out = null; + + if (0 === \stream_select($read, $write, $except, 0, 50000)) { + return $out; + } + + // Read \033]L<label>\033\ + $input->read(3); // skip \033, ] and L. + + while (true) { + $char = $input->readCharacter(); + + if ("\033" === $char) { + $chaar = $input->readCharacter(); + + if ('\\' === $chaar) { + break; + } + + $char .= $chaar; + } + + $out .= $char; + } + + return $out; + } + + /** + * Refresh the window. + */ + public static function refresh() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + // DECSLPP. + Console::getOutput()->writeAll("\033[7t"); + + return; + } + + /** + * Set clipboard value. + */ + public static function copy(string $data) + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + $out = "\033]52;;".\base64_encode($data)."\033\\"; + $output = Console::getOutput(); + $considerMultiplexer = $output->considerMultiplexer(true); + + $output->writeAll($out); + $output->considerMultiplexer($considerMultiplexer); + + return; + } +} + +/* + * Advanced interaction. + */ +Console::advancedInteraction(); + +/* + * Event. + */ +if (\function_exists('pcntl_signal')) { + ConsoleWindow::getInstance(); + \pcntl_signal( + \SIGWINCH, + function () { + static $_window = null; + + if (null === $_window) { + $_window = ConsoleWindow::getInstance(); + } + + Event::notify( + 'hoa://Event/Console/Window:resize', + $_window, + new EventBucket([ + 'size' => ConsoleWindow::getSize(), + ]) + ); + } + ); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Event.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Event.php new file mode 100644 index 0000000..bb08f32 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Event.php @@ -0,0 +1,193 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Events are asynchronous at registration, anonymous at use (until we + * receive a bucket) and useful to largely spread data through components + * without any known connection between them. + */ +class Event +{ + /** + * Event ID key. + */ + const KEY_EVENT = 0; + + /** + * Source object key. + */ + const KEY_SOURCE = 1; + + /** + * Static register of all observable objects, i.e. `Hoa\Event\Source` + * object, i.e. object that can send event. + */ + private static $_register = []; + + /** + * Collection of callables, i.e. observer objects. + */ + protected $_callable = []; + + /** + * Privatize the constructor. + */ + private function __construct() + { + return; + } + + /** + * Manage multiton of events, with the principle of asynchronous + * attachments. + */ + public static function getEvent(string $eventId): self + { + if (!isset(self::$_register[$eventId][self::KEY_EVENT])) { + self::$_register[$eventId] = [ + self::KEY_EVENT => new self(), + self::KEY_SOURCE => null, + ]; + } + + return self::$_register[$eventId][self::KEY_EVENT]; + } + + /** + * Declares a new object in the observable collection. + * Note: Hoa's libraries use `hoa://Event/anID` for their observable objects. + */ + public static function register(string $eventId, /* Source|string */ $source) + { + if (true === self::eventExists($eventId)) { + throw new EventException('Cannot redeclare an event with the same ID, i.e. the event '.'ID %s already exists.', 0, $eventId); + } + + if (\is_object($source) && !($source instanceof EventSource)) { + throw new EventException('The source must implement \Hoa\Event\Source '.'interface; given %s.', 1, \get_class($source)); + } else { + $reflection = new \ReflectionClass($source); + + if (false === $reflection->implementsInterface('\Psy\Readline\Hoa\EventSource')) { + throw new EventException('The source must implement \Hoa\Event\Source '.'interface; given %s.', 2, $source); + } + } + + if (!isset(self::$_register[$eventId][self::KEY_EVENT])) { + self::$_register[$eventId][self::KEY_EVENT] = new self(); + } + + self::$_register[$eventId][self::KEY_SOURCE] = $source; + } + + /** + * Undeclares an object in the observable collection. + * + * If `$hard` is set to `true, then the source and its attached callables + * will be deleted. + */ + public static function unregister(string $eventId, bool $hard = false) + { + if (false !== $hard) { + unset(self::$_register[$eventId]); + } else { + self::$_register[$eventId][self::KEY_SOURCE] = null; + } + } + + /** + * Attach an object to an event. + * + * It can be a callable or an accepted callable form (please, see the + * `Hoa\Consistency\Xcallable` class). + */ + public function attach($callable): self + { + $callable = Xcallable::from($callable); + $this->_callable[$callable->getHash()] = $callable; + + return $this; + } + + /** + * Detaches an object to an event. + * + * Please see `self::attach` method. + */ + public function detach($callable): self + { + unset($this->_callable[Xcallable::from($callable)->getHash()]); + + return $this; + } + + /** + * Checks if at least one callable is attached to an event. + */ + public function isListened(): bool + { + return !empty($this->_callable); + } + + /** + * Notifies, i.e. send data to observers. + */ + public static function notify(string $eventId, EventSource $source, EventBucket $data) + { + if (false === self::eventExists($eventId)) { + throw new EventException('Event ID %s does not exist, cannot send notification.', 3, $eventId); + } + + $data->setSource($source); + $event = self::getEvent($eventId); + + foreach ($event->_callable as $callable) { + $callable($data); + } + } + + /** + * Checks whether an event exists. + */ + public static function eventExists(string $eventId): bool + { + return + \array_key_exists($eventId, self::$_register) && + self::$_register[$eventId][self::KEY_SOURCE] !== null; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventBucket.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventBucket.php new file mode 100644 index 0000000..37d3ca1 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventBucket.php @@ -0,0 +1,109 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * This class is the object which is transmit through event channels. + */ +class EventBucket +{ + /** + * The source object (must be of kind `Hoa\Event\Source`). + */ + protected $_source = null; + + /** + * Data attached to the bucket. + */ + protected $_data = null; + + /** + * Allocates a new bucket with various data attached to it. + */ + public function __construct($data = null) + { + $this->setData($data); + + return; + } + + /** + * Sends this object on the event channel. + */ + public function send(string $eventId, EventSource $source) + { + return Event::notify($eventId, $source, $this); + } + + /** + * Sets a new source. + */ + public function setSource(EventSource $source) + { + $old = $this->_source; + $this->_source = $source; + + return $old; + } + + /** + * Returns the source. + */ + public function getSource() + { + return $this->_source; + } + + /** + * Sets new data. + */ + public function setData($data) + { + $old = $this->_data; + $this->_data = $data; + + return $old; + } + + /** + * Returns the data. + */ + public function getData() + { + return $this->_data; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventException.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventException.php new file mode 100644 index 0000000..9517d9c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventException.php @@ -0,0 +1,44 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Extending the `Hoa\Exception\Exception` class. + */ +class EventException extends Exception +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListenable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListenable.php new file mode 100644 index 0000000..cefd3e6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListenable.php @@ -0,0 +1,48 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Each object which is listenable must implement this interface. + */ +interface EventListenable extends EventSource +{ + /** + * Attaches a callable to a listenable component. + */ + public function on(string $listenerId, $callable): self; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListener.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListener.php new file mode 100644 index 0000000..8e877e6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListener.php @@ -0,0 +1,137 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * A contrario of events, listeners are synchronous, identified at use and + * useful for close interactions between one or some components. + */ +class EventListener +{ + /** + * Source of listener (for `Hoa\Event\Bucket`). + */ + protected $_source = null; + + /** + * All listener IDs and associated listeners. + */ + protected $_callables = []; + + /** + * Build a listener. + */ + public function __construct(EventListenable $source, array $ids) + { + $this->_source = $source; + $this->addIds($ids); + + return; + } + + /** + * Adds acceptable ID (or reset). + */ + public function addIds(array $ids) + { + foreach ($ids as $id) { + $this->_callables[$id] = []; + } + } + + /** + * Attaches a callable to a listenable component. + */ + public function attach(string $listenerId, $callable): self + { + if (false === $this->listenerExists($listenerId)) { + throw new EventException('Cannot listen %s because it is not defined.', 0, $listenerId); + } + + $callable = Xcallable::from($callable); + $this->_callables[$listenerId][$callable->getHash()] = $callable; + + return $this; + } + + /** + * Detaches a callable from a listenable component. + */ + public function detach(string $listenerId, $callable): self + { + unset($this->_callables[$listenerId][Xcallable::from($callable)->getHash()]); + + return $this; + } + + /** + * Detaches all callables from a listenable component. + */ + public function detachAll(string $listenerId): self + { + unset($this->_callables[$listenerId]); + + return $this; + } + + /** + * Checks if a listener exists. + */ + public function listenerExists(string $listenerId): bool + { + return \array_key_exists($listenerId, $this->_callables); + } + + /** + * Sends/fires a bucket to a listener. + */ + public function fire(string $listenerId, EventBucket $data): array + { + if (false === $this->listenerExists($listenerId)) { + throw new EventException('Cannot fire on %s because it is not defined.', 1, $listenerId); + } + + $data->setSource($this->_source); + $out = []; + + foreach ($this->_callables[$listenerId] as $callable) { + $out[] = $callable($data); + } + + return $out; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListens.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListens.php new file mode 100644 index 0000000..41f1172 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventListens.php @@ -0,0 +1,83 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Implementation of a listener. + */ +trait EventListens +{ + /** + * Listener instance of type `Hoa\Event\Listener`. + */ + protected $_listener = null; + + /** + * Attaches a callable to a listenable component. + */ + public function on(string $listenerId, $callable): EventListenable + { + $listener = $this->getListener(); + + if (null === $listener) { + throw new EventException('Cannot attach a callable to the listener %s because '.'it has not been initialized yet.', 0, static::class); + } + + $listener->attach($listenerId, $callable); + + return $this; + } + + /** + * Sets a new listener. + */ + protected function setListener(EventListener $listener) + { + $old = $this->_listener; + $this->_listener = $listener; + + return $old; + } + + /** + * Returns the listener. + */ + protected function getListener() + { + return $this->_listener; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventSource.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventSource.php new file mode 100644 index 0000000..3a495d4 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/EventSource.php @@ -0,0 +1,44 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Each object which is listenable must implement this interface. + */ +interface EventSource +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Exception.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Exception.php new file mode 100644 index 0000000..e0b8bc8 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Exception.php @@ -0,0 +1,79 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Each exception must extend `Hoa\Exception\Exception`. + */ +class Exception extends ExceptionIdle implements EventSource +{ + /** + * Allocates a new exception. + * + * An exception is built with a formatted message, a code (an ID), and an + * array that contains the list of formatted string for the message. If + * chaining, a previous exception can be added. + */ + public function __construct( + string $message, + int $code = 0, + $arguments = [], + \Throwable $previous = null + ) { + parent::__construct($message, $code, $arguments, $previous); + + if (false === Event::eventExists('hoa://Event/Exception')) { + Event::register('hoa://Event/Exception', __CLASS__); + } + + $this->send(); + + return; + } + + /** + * Sends the exception on `hoa://Event/Exception`. + */ + public function send() + { + Event::notify( + 'hoa://Event/Exception', + $this, + new EventBucket($this) + ); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ExceptionIdle.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ExceptionIdle.php new file mode 100644 index 0000000..1d44c43 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ExceptionIdle.php @@ -0,0 +1,267 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * `Hoa\Exception\Idle` is the mother exception class of libraries. The only + * difference between `Hoa\Exception\Idle` and its direct children + * `Hoa\Exception` is that the latter fires events after beeing constructed. + */ +class ExceptionIdle extends \Exception +{ + /** + * Delay processing on arguments. + */ + protected $_tmpArguments = null; + + /** + * List of arguments to format message. + */ + protected $_arguments = null; + + /** + * Backtrace. + */ + protected $_trace = null; + + /** + * Previous exception if any. + */ + protected $_previous = null; + + /** + * Original exception message. + */ + protected $_rawMessage = null; + + /** + * Allocates a new exception. + * + * An exception is built with a formatted message, a code (an ID) and an + * array that contains the list of formatted strings for the message. If + * chaining, we can add a previous exception. + */ + public function __construct( + string $message, + int $code = 0, + $arguments = [], + \Exception $previous = null + ) { + $this->_tmpArguments = $arguments; + parent::__construct($message, $code, $previous); + $this->_rawMessage = $message; + $this->message = @\vsprintf($message, $this->getArguments()); + + return; + } + + /** + * Returns the backtrace. + * + * Do not use `Exception::getTrace` any more. + */ + public function getBacktrace() + { + if (null === $this->_trace) { + $this->_trace = $this->getTrace(); + } + + return $this->_trace; + } + + /** + * Returns the previous exception if any. + * + * Do not use `Exception::getPrevious` any more. + */ + public function getPreviousThrow() + { + if (null === $this->_previous) { + $this->_previous = $this->getPrevious(); + } + + return $this->_previous; + } + + /** + * Returns the arguments of the message. + */ + public function getArguments() + { + if (null === $this->_arguments) { + $arguments = $this->_tmpArguments; + + if (!\is_array($arguments)) { + $arguments = [$arguments]; + } + + foreach ($arguments as &$value) { + if (null === $value) { + $value = '(null)'; + } + } + + $this->_arguments = $arguments; + unset($this->_tmpArguments); + } + + return $this->_arguments; + } + + /** + * Returns the raw message. + */ + public function getRawMessage(): string + { + return $this->_rawMessage; + } + + /** + * Returns the message already formatted. + */ + public function getFormattedMessage(): string + { + return $this->getMessage(); + } + + /** + * Returns the source of the exception (class, method, function, main etc.). + */ + public function getFrom(): string + { + $trace = $this->getBacktrace(); + $from = '{main}'; + + if (!empty($trace)) { + $t = $trace[0]; + $from = ''; + + if (isset($t['class'])) { + $from .= $t['class'].'::'; + } + + if (isset($t['function'])) { + $from .= $t['function'].'()'; + } + } + + return $from; + } + + /** + * Raises an exception as a string. + */ + public function raise(bool $includePrevious = false): string + { + $message = $this->getFormattedMessage(); + $trace = $this->getBacktrace(); + $file = '/dev/null'; + $line = -1; + $pre = $this->getFrom(); + + if (!empty($trace)) { + $file = $trace['file'] ?? null; + $line = $trace['line'] ?? null; + } + + $pre .= ': '; + + try { + $out = + $pre.'('.$this->getCode().') '.$message."\n". + 'in '.$this->getFile().' at line '. + $this->getLine().'.'; + } catch (\Exception $e) { + $out = + $pre.'('.$this->getCode().') '.$message."\n". + 'in '.$file.' around line '.$line.'.'; + } + + if (true === $includePrevious && + null !== $previous = $this->getPreviousThrow()) { + $out .= + "\n\n".' ⬇'."\n\n". + 'Nested exception ('.\get_class($previous).'):'."\n". + ($previous instanceof self + ? $previous->raise(true) + : $previous->getMessage()); + } + + return $out; + } + + /** + * Catches uncaught exception (only `Hoa\Exception\Idle` and children). + */ + public static function uncaught(\Throwable $exception) + { + if (!($exception instanceof self)) { + throw $exception; + } + + while (0 < \ob_get_level()) { + \ob_end_flush(); + } + + echo 'Uncaught exception ('.\get_class($exception).'):'."\n". + $exception->raise(true); + } + + /** + * String representation of object. + */ + public function __toString(): string + { + return $this->raise(); + } + + /** + * Enables uncaught exception handler. + * + * This is restricted to Hoa's exceptions only. + */ + public static function enableUncaughtHandler(bool $enable = true) + { + if (false === $enable) { + return \restore_exception_handler(); + } + + return \set_exception_handler(function ($exception) { + return self::uncaught($exception); + }); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/File.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/File.php new file mode 100644 index 0000000..96b8c4d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/File.php @@ -0,0 +1,274 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File. + * + * File handler. + */ +abstract class File extends FileGeneric implements StreamBufferable, StreamLockable, StreamPointable +{ + /** + * Open for reading only; place the file pointer at the beginning of the + * file. + */ + const MODE_READ = 'rb'; + + /** + * Open for reading and writing; place the file pointer at the beginning of + * the file. + */ + const MODE_READ_WRITE = 'r+b'; + + /** + * Open for writing only; place the file pointer at the beginning of the + * file and truncate the file to zero length. If the file does not exist, + * attempt to create it. + */ + const MODE_TRUNCATE_WRITE = 'wb'; + + /** + * Open for reading and writing; place the file pointer at the beginning of + * the file and truncate the file to zero length. If the file does not + * exist, attempt to create it. + */ + const MODE_TRUNCATE_READ_WRITE = 'w+b'; + + /** + * Open for writing only; place the file pointer at the end of the file. If + * the file does not exist, attempt to create it. + */ + const MODE_APPEND_WRITE = 'ab'; + + /** + * Open for reading and writing; place the file pointer at the end of the + * file. If the file does not exist, attempt to create it. + */ + const MODE_APPEND_READ_WRITE = 'a+b'; + + /** + * Create and open for writing only; place the file pointer at the beginning + * of the file. If the file already exits, the fopen() call with fail by + * returning false and generating an error of level E_WARNING. If the file + * does not exist, attempt to create it. This is equivalent to specifying + * O_EXCL | O_CREAT flags for the underlying open(2) system call. + */ + const MODE_CREATE_WRITE = 'xb'; + + /** + * Create and open for reading and writing; place the file pointer at the + * beginning of the file. If the file already exists, the fopen() call with + * fail by returning false and generating an error of level E_WARNING. If + * the file does not exist, attempt to create it. This is equivalent to + * specifying O_EXCL | O_CREAT flags for the underlying open(2) system call. + */ + const MODE_CREATE_READ_WRITE = 'x+b'; + + /** + * Open a file. + */ + public function __construct( + string $streamName, + string $mode, + string $context = null, + bool $wait = false + ) { + $this->setMode($mode); + + switch ($streamName) { + case '0': + $streamName = 'php://stdin'; + + break; + + case '1': + $streamName = 'php://stdout'; + + break; + + case '2': + $streamName = 'php://stderr'; + + break; + + default: + if (true === \ctype_digit($streamName)) { + $streamName = 'php://fd/'.$streamName; + } + } + + parent::__construct($streamName, $context, $wait); + + return; + } + + /** + * Open the stream and return the associated resource. + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + if (\substr($streamName, 0, 4) === 'file' && + false === \is_dir(\dirname($streamName))) { + throw new FileException('Directory %s does not exist. Could not open file %s.', 1, [\dirname($streamName), \basename($streamName)]); + } + + if (null === $context) { + if (false === $out = @\fopen($streamName, $this->getMode(), true)) { + throw new FileException('Failed to open stream %s.', 2, $streamName); + } + + return $out; + } + + $out = @\fopen( + $streamName, + $this->getMode(), + true, + $context->getContext() + ); + + if (false === $out) { + throw new FileException('Failed to open stream %s.', 3, $streamName); + } + + return $out; + } + + /** + * Close the current stream. + */ + protected function _close(): bool + { + return @\fclose($this->getStream()); + } + + /** + * Start a new buffer. + * The callable acts like a light filter. + */ + public function newBuffer($callable = null, int $size = null): int + { + $this->setStreamBuffer($size); + + // @todo manage $callable as a filter? + + return 1; + } + + /** + * Flush the output to a stream. + */ + public function flush(): bool + { + return \fflush($this->getStream()); + } + + /** + * Delete buffer. + */ + public function deleteBuffer(): bool + { + return $this->disableStreamBuffer(); + } + + /** + * Get bufffer level. + */ + public function getBufferLevel(): int + { + return 1; + } + + /** + * Get buffer size. + */ + public function getBufferSize(): int + { + return $this->getStreamBufferSize(); + } + + /** + * Portable advisory locking. + */ + public function lock(int $operation): bool + { + return \flock($this->getStream(), $operation); + } + + /** + * Rewind the position of a stream pointer. + */ + public function rewind(): bool + { + return \rewind($this->getStream()); + } + + /** + * Seek on a stream pointer. + */ + public function seek(int $offset, int $whence = StreamPointable::SEEK_SET): int + { + return \fseek($this->getStream(), $offset, $whence); + } + + /** + * Get the current position of the stream pointer. + */ + public function tell(): int + { + $stream = $this->getStream(); + + if (null === $stream) { + return 0; + } + + return \ftell($stream); + } + + /** + * Create a file. + */ + public static function create(string $name) + { + if (\file_exists($name)) { + return true; + } + + return \touch($name); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileDirectory.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileDirectory.php new file mode 100644 index 0000000..e719141 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileDirectory.php @@ -0,0 +1,221 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Directory. + * + * Directory handler. + */ +class FileDirectory extends FileGeneric +{ + /** + * Open for reading. + */ + const MODE_READ = 'rb'; + + /** + * Open for reading and writing. If the directory does not exist, attempt to + * create it. + */ + const MODE_CREATE = 'xb'; + + /** + * Open for reading and writing. If the directory does not exist, attempt to + * create it recursively. + */ + const MODE_CREATE_RECURSIVE = 'xrb'; + + /** + * Open a directory. + */ + public function __construct( + string $streamName, + string $mode = self::MODE_READ, + string $context = null, + bool $wait = false + ) { + $this->setMode($mode); + parent::__construct($streamName, $context, $wait); + + return; + } + + /** + * Open the stream and return the associated resource. + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + if (false === \is_dir($streamName)) { + if ($this->getMode() === self::MODE_READ) { + throw new FileDoesNotExistException('Directory %s does not exist.', 0, $streamName); + } else { + self::create( + $streamName, + $this->getMode(), + null !== $context + ? $context->getContext() + : null + ); + } + } + + $out = null; + + return $out; + } + + /** + * Close the current stream. + */ + protected function _close(): bool + { + return true; + } + + /** + * Recursive copy of a directory. + */ + public function copy(string $to, bool $force = StreamTouchable::DO_NOT_OVERWRITE): bool + { + if (empty($to)) { + throw new FileException('The destination path (to copy) is empty.', 1); + } + + $from = $this->getStreamName(); + $fromLength = \strlen($from) + 1; + $finder = new FileFinder(); + $finder->in($from); + + self::create($to, self::MODE_CREATE_RECURSIVE); + + foreach ($finder as $file) { + $relative = \substr($file->getPathname(), $fromLength); + $_to = $to.\DIRECTORY_SEPARATOR.$relative; + + if (true === $file->isDir()) { + self::create($_to, self::MODE_CREATE); + + continue; + } + + // This is not possible to do `$file->open()->copy(); + // $file->close();` because the file will be opened in read and + // write mode. In a PHAR for instance, this operation is + // forbidden. So a special care must be taken to open file in read + // only mode. + $handle = null; + + if (true === $file->isFile()) { + $handle = new FileRead($file->getPathname()); + } elseif (true === $file->isDir()) { + $handle = new self($file->getPathName()); + } elseif (true === $file->isLink()) { + $handle = new FileLinkRead($file->getPathName()); + } + + if (null !== $handle) { + $handle->copy($_to, $force); + $handle->close(); + } + } + + return true; + } + + /** + * Delete a directory. + */ + public function delete(): bool + { + $from = $this->getStreamName(); + $finder = new FileFinder(); + $finder->in($from) + ->childFirst(); + + foreach ($finder as $file) { + $file->open()->delete(); + $file->close(); + } + + if (null === $this->getStreamContext()) { + return @\rmdir($from); + } + + return @\rmdir($from, $this->getStreamContext()->getContext()); + } + + /** + * Create a directory. + */ + public static function create( + string $name, + string $mode = self::MODE_CREATE_RECURSIVE, + string $context = null + ): bool { + if (true === \is_dir($name)) { + return true; + } + + if (empty($name)) { + return false; + } + + if (null !== $context) { + if (false === StreamContext::contextExists($context)) { + throw new FileException('Context %s was not previously declared, cannot retrieve '.'this context.', 2, $context); + } else { + $context = StreamContext::getInstance($context); + } + } + + if (null === $context) { + return @\mkdir( + $name, + 0755, + self::MODE_CREATE_RECURSIVE === $mode + ); + } + + return @\mkdir( + $name, + 0755, + self::MODE_CREATE_RECURSIVE === $mode, + $context->getContext() + ); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileDoesNotExistException.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileDoesNotExistException.php new file mode 100644 index 0000000..81599a5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileDoesNotExistException.php @@ -0,0 +1,48 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Exception\FileDoesNotExist. + * + * Extending the \Hoa\File\Exception class. + * + * @license New BSD License + */ +class FileDoesNotExistException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileException.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileException.php new file mode 100644 index 0000000..0e224c2 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileException.php @@ -0,0 +1,48 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Exception. + * + * Extending the \Hoa\Exception\Exception class. + * + * @license New BSD License + */ +class FileException extends Exception +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileFinder.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileFinder.php new file mode 100644 index 0000000..1523b36 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileFinder.php @@ -0,0 +1,658 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Finder. + * + * This class allows to find files easily by using filters and flags. + */ +class FileFinder implements \IteratorAggregate +{ + /** + * SplFileInfo classname. + */ + protected $_splFileInfo = \SplFileInfo::class; + + /** + * Paths where to look for. + */ + protected $_paths = []; + + /** + * Max depth in recursion. + */ + protected $_maxDepth = -1; + + /** + * Filters. + */ + protected $_filters = []; + + /** + * Flags. + */ + protected $_flags = -1; + + /** + * Types of files to handle. + */ + protected $_types = []; + + /** + * What comes first: parent or child? + */ + protected $_first = -1; + + /** + * Sorts. + */ + protected $_sorts = []; + + /** + * Initialize. + */ + public function __construct() + { + $this->_flags = IteratorFileSystem::KEY_AS_PATHNAME + | IteratorFileSystem::CURRENT_AS_FILEINFO + | IteratorFileSystem::SKIP_DOTS; + $this->_first = \RecursiveIteratorIterator::SELF_FIRST; + + return; + } + + /** + * Select a directory to scan. + */ + public function in($paths): self + { + if (!\is_array($paths)) { + $paths = [$paths]; + } + + foreach ($paths as $path) { + if (1 === \preg_match('/[\*\?\[\]]/', $path)) { + $iterator = new \CallbackFilterIterator( + new \GlobIterator(\rtrim($path, \DIRECTORY_SEPARATOR)), + function ($current) { + return $current->isDir(); + } + ); + + foreach ($iterator as $fileInfo) { + $this->_paths[] = $fileInfo->getPathname(); + } + } else { + $this->_paths[] = $path; + } + } + + return $this; + } + + /** + * Set max depth for recursion. + */ + public function maxDepth(int $depth): self + { + $this->_maxDepth = $depth; + + return $this; + } + + /** + * Include files in the result. + */ + public function files(): self + { + $this->_types[] = 'file'; + + return $this; + } + + /** + * Include directories in the result. + */ + public function directories(): self + { + $this->_types[] = 'dir'; + + return $this; + } + + /** + * Include links in the result. + */ + public function links(): self + { + $this->_types[] = 'link'; + + return $this; + } + + /** + * Follow symbolink links. + */ + public function followSymlinks(bool $flag = true): self + { + if (true === $flag) { + $this->_flags ^= IteratorFileSystem::FOLLOW_SYMLINKS; + } else { + $this->_flags |= IteratorFileSystem::FOLLOW_SYMLINKS; + } + + return $this; + } + + /** + * Include files that match a regex. + * Example: + * $this->name('#\.php$#');. + */ + public function name(string $regex): self + { + $this->_filters[] = function (\SplFileInfo $current) use ($regex) { + return 0 !== \preg_match($regex, $current->getBasename()); + }; + + return $this; + } + + /** + * Exclude directories that match a regex. + * Example: + * $this->notIn('#^\.(git|hg)$#');. + */ + public function notIn(string $regex): self + { + $this->_filters[] = function (\SplFileInfo $current) use ($regex) { + foreach (\explode(\DIRECTORY_SEPARATOR, $current->getPathname()) as $part) { + if (0 !== \preg_match($regex, $part)) { + return false; + } + } + + return true; + }; + + return $this; + } + + /** + * Include files that respect a certain size. + * The size is a string of the form: + * operator number unit + * where + * • operator could be: <, <=, >, >= or =; + * • number is a positive integer; + * • unit could be: b (default), Kb, Mb, Gb, Tb, Pb, Eb, Zb, Yb. + * Example: + * $this->size('>= 12Kb');. + */ + public function size(string $size): self + { + if (0 === \preg_match('#^(<|<=|>|>=|=)\s*(\d+)\s*((?:[KMGTPEZY])b)?$#', $size, $matches)) { + return $this; + } + + $number = (float) ($matches[2]); + $unit = $matches[3] ?? 'b'; + $operator = $matches[1]; + + switch ($unit) { + case 'b': + break; + + // kilo + case 'Kb': + $number <<= 10; + + break; + + // mega. + case 'Mb': + $number <<= 20; + + break; + + // giga. + case 'Gb': + $number <<= 30; + + break; + + // tera. + case 'Tb': + $number *= 1099511627776; + + break; + + // peta. + case 'Pb': + $number *= 1024 ** 5; + + break; + + // exa. + case 'Eb': + $number *= 1024 ** 6; + + break; + + // zetta. + case 'Zb': + $number *= 1024 ** 7; + + break; + + // yota. + case 'Yb': + $number *= 1024 ** 8; + + break; + } + + $filter = null; + + switch ($operator) { + case '<': + $filter = function (\SplFileInfo $current) use ($number) { + return $current->getSize() < $number; + }; + + break; + + case '<=': + $filter = function (\SplFileInfo $current) use ($number) { + return $current->getSize() <= $number; + }; + + break; + + case '>': + $filter = function (\SplFileInfo $current) use ($number) { + return $current->getSize() > $number; + }; + + break; + + case '>=': + $filter = function (\SplFileInfo $current) use ($number) { + return $current->getSize() >= $number; + }; + + break; + + case '=': + $filter = function (\SplFileInfo $current) use ($number) { + return $current->getSize() === $number; + }; + + break; + } + + $this->_filters[] = $filter; + + return $this; + } + + /** + * Whether we should include dots or not (respectively . and ..). + */ + public function dots(bool $flag = true): self + { + if (true === $flag) { + $this->_flags ^= IteratorFileSystem::SKIP_DOTS; + } else { + $this->_flags |= IteratorFileSystem::SKIP_DOTS; + } + + return $this; + } + + /** + * Include files that are owned by a certain owner. + */ + public function owner(int $owner): self + { + $this->_filters[] = function (\SplFileInfo $current) use ($owner) { + return $current->getOwner() === $owner; + }; + + return $this; + } + + /** + * Format date. + * Date can have the following syntax: + * date + * since date + * until date + * If the date does not have the “ago” keyword, it will be added. + * Example: “42 hours” is equivalent to “since 42 hours” which is equivalent + * to “since 42 hours ago”. + */ + protected function formatDate(string $date, &$operator): int + { + $operator = -1; + + if (0 === \preg_match('#\bago\b#', $date)) { + $date .= ' ago'; + } + + if (0 !== \preg_match('#^(since|until)\b(.+)$#', $date, $matches)) { + $time = \strtotime($matches[2]); + + if ('until' === $matches[1]) { + $operator = 1; + } + } else { + $time = \strtotime($date); + } + + return $time; + } + + /** + * Include files that have been changed from a certain date. + * Example: + * $this->changed('since 13 days');. + */ + public function changed(string $date): self + { + $time = $this->formatDate($date, $operator); + + if (-1 === $operator) { + $this->_filters[] = function (\SplFileInfo $current) use ($time) { + return $current->getCTime() >= $time; + }; + } else { + $this->_filters[] = function (\SplFileInfo $current) use ($time) { + return $current->getCTime() < $time; + }; + } + + return $this; + } + + /** + * Include files that have been modified from a certain date. + * Example: + * $this->modified('since 13 days');. + */ + public function modified(string $date): self + { + $time = $this->formatDate($date, $operator); + + if (-1 === $operator) { + $this->_filters[] = function (\SplFileInfo $current) use ($time) { + return $current->getMTime() >= $time; + }; + } else { + $this->_filters[] = function (\SplFileInfo $current) use ($time) { + return $current->getMTime() < $time; + }; + } + + return $this; + } + + /** + * Add your own filter. + * The callback will receive 3 arguments: $current, $key and $iterator. It + * must return a boolean: true to include the file, false to exclude it. + * Example: + * // Include files that are readable + * $this->filter(function ($current) { + * return $current->isReadable(); + * });. + */ + public function filter($callback): self + { + $this->_filters[] = $callback; + + return $this; + } + + /** + * Sort result by name. + * If \Collator exists (from ext/intl), the $locale argument will be used + * for its constructor. Else, strcmp() will be used. + * Example: + * $this->sortByName('fr_FR');. + */ + public function sortByName(string $locale = 'root'): self + { + if (true === \class_exists('Collator', false)) { + $collator = new \Collator($locale); + + $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) use ($collator) { + return $collator->compare($a->getPathname(), $b->getPathname()); + }; + } else { + $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) { + return \strcmp($a->getPathname(), $b->getPathname()); + }; + } + + return $this; + } + + /** + * Sort result by size. + * Example: + * $this->sortBySize();. + */ + public function sortBySize(): self + { + $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) { + return $a->getSize() < $b->getSize(); + }; + + return $this; + } + + /** + * Add your own sort. + * The callback will receive 2 arguments: $a and $b. Please see the uasort() + * function. + * Example: + * // Sort files by their modified time. + * $this->sort(function ($a, $b) { + * return $a->getMTime() < $b->getMTime(); + * });. + */ + public function sort($callable): self + { + $this->_sorts[] = $callable; + + return $this; + } + + /** + * Child comes first when iterating. + */ + public function childFirst(): self + { + $this->_first = \RecursiveIteratorIterator::CHILD_FIRST; + + return $this; + } + + /** + * Get the iterator. + */ + public function getIterator() + { + $_iterator = new \AppendIterator(); + $types = $this->getTypes(); + + if (!empty($types)) { + $this->_filters[] = function (\SplFileInfo $current) use ($types) { + return \in_array($current->getType(), $types); + }; + } + + $maxDepth = $this->getMaxDepth(); + $splFileInfo = $this->getSplFileInfo(); + + foreach ($this->getPaths() as $path) { + if (1 === $maxDepth) { + $iterator = new \IteratorIterator( + new IteratorRecursiveDirectory( + $path, + $this->getFlags(), + $splFileInfo + ), + $this->getFirst() + ); + } else { + $iterator = new \RecursiveIteratorIterator( + new IteratorRecursiveDirectory( + $path, + $this->getFlags(), + $splFileInfo + ), + $this->getFirst() + ); + + if (1 < $maxDepth) { + $iterator->setMaxDepth($maxDepth - 1); + } + } + + $_iterator->append($iterator); + } + + foreach ($this->getFilters() as $filter) { + $_iterator = new \CallbackFilterIterator( + $_iterator, + $filter + ); + } + + $sorts = $this->getSorts(); + + if (empty($sorts)) { + return $_iterator; + } + + $array = \iterator_to_array($_iterator); + + foreach ($sorts as $sort) { + \uasort($array, $sort); + } + + return new \ArrayIterator($array); + } + + /** + * Set SplFileInfo classname. + */ + public function setSplFileInfo(string $splFileInfo): string + { + $old = $this->_splFileInfo; + $this->_splFileInfo = $splFileInfo; + + return $old; + } + + /** + * Get SplFileInfo classname. + */ + public function getSplFileInfo(): string + { + return $this->_splFileInfo; + } + + /** + * Get all paths. + */ + protected function getPaths(): array + { + return $this->_paths; + } + + /** + * Get max depth. + */ + public function getMaxDepth(): int + { + return $this->_maxDepth; + } + + /** + * Get types. + */ + public function getTypes(): array + { + return $this->_types; + } + + /** + * Get filters. + */ + protected function getFilters(): array + { + return $this->_filters; + } + + /** + * Get sorts. + */ + protected function getSorts(): array + { + return $this->_sorts; + } + + /** + * Get flags. + */ + public function getFlags(): int + { + return $this->_flags; + } + + /** + * Get first. + */ + public function getFirst(): int + { + return $this->_first; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileGeneric.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileGeneric.php new file mode 100644 index 0000000..aa3b70c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileGeneric.php @@ -0,0 +1,487 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Generic. + * + * Describe a super-file. + */ +abstract class FileGeneric extends Stream implements StreamPathable, StreamStatable, StreamTouchable +{ + /** + * Mode. + */ + protected $_mode = null; + + /** + * Get filename component of path. + */ + public function getBasename(): string + { + return \basename($this->getStreamName()); + } + + /** + * Get directory name component of path. + */ + public function getDirname(): string + { + return \dirname($this->getStreamName()); + } + + /** + * Get size. + */ + public function getSize(): int + { + if (false === $this->getStatistic()) { + return false; + } + + return \filesize($this->getStreamName()); + } + + /** + * Get informations about a file. + */ + public function getStatistic(): array + { + return \fstat($this->getStream()); + } + + /** + * Get last access time of file. + */ + public function getATime(): int + { + return \fileatime($this->getStreamName()); + } + + /** + * Get inode change time of file. + */ + public function getCTime(): int + { + return \filectime($this->getStreamName()); + } + + /** + * Get file modification time. + */ + public function getMTime(): int + { + return \filemtime($this->getStreamName()); + } + + /** + * Get file group. + */ + public function getGroup(): int + { + return \filegroup($this->getStreamName()); + } + + /** + * Get file owner. + */ + public function getOwner(): int + { + return \fileowner($this->getStreamName()); + } + + /** + * Get file permissions. + */ + public function getPermissions(): int + { + return \fileperms($this->getStreamName()); + } + + /** + * Get file permissions as a string. + * Result sould be interpreted like this: + * * s: socket; + * * l: symbolic link; + * * -: regular; + * * b: block special; + * * d: directory; + * * c: character special; + * * p: FIFO pipe; + * * u: unknown. + */ + public function getReadablePermissions(): string + { + $p = $this->getPermissions(); + + if (($p & 0xC000) === 0xC000) { + $out = 's'; + } elseif (($p & 0xA000) === 0xA000) { + $out = 'l'; + } elseif (($p & 0x8000) === 0x8000) { + $out = '-'; + } elseif (($p & 0x6000) === 0x6000) { + $out = 'b'; + } elseif (($p & 0x4000) === 0x4000) { + $out = 'd'; + } elseif (($p & 0x2000) === 0x2000) { + $out = 'c'; + } elseif (($p & 0x1000) === 0x1000) { + $out = 'p'; + } else { + $out = 'u'; + } + + $out .= + (($p & 0x0100) ? 'r' : '-'). + (($p & 0x0080) ? 'w' : '-'). + (($p & 0x0040) ? + (($p & 0x0800) ? 's' : 'x') : + (($p & 0x0800) ? 'S' : '-')). + (($p & 0x0020) ? 'r' : '-'). + (($p & 0x0010) ? 'w' : '-'). + (($p & 0x0008) ? + (($p & 0x0400) ? 's' : 'x') : + (($p & 0x0400) ? 'S' : '-')). + (($p & 0x0004) ? 'r' : '-'). + (($p & 0x0002) ? 'w' : '-'). + (($p & 0x0001) ? + (($p & 0x0200) ? 't' : 'x') : + (($p & 0x0200) ? 'T' : '-')); + + return $out; + } + + /** + * Check if the file is readable. + */ + public function isReadable(): bool + { + return \is_readable($this->getStreamName()); + } + + /** + * Check if the file is writable. + */ + public function isWritable(): bool + { + return \is_writable($this->getStreamName()); + } + + /** + * Check if the file is executable. + */ + public function isExecutable(): bool + { + return \is_executable($this->getStreamName()); + } + + /** + * Clear file status cache. + */ + public function clearStatisticCache() + { + \clearstatcache(true, $this->getStreamName()); + } + + /** + * Clear all files status cache. + */ + public static function clearAllStatisticCaches() + { + \clearstatcache(); + } + + /** + * Set access and modification time of file. + */ + public function touch(int $time = null, int $atime = null): bool + { + if (null === $time) { + $time = \time(); + } + + if (null === $atime) { + $atime = $time; + } + + return \touch($this->getStreamName(), $time, $atime); + } + + /** + * Copy file. + * Return the destination file path if succeed, false otherwise. + */ + public function copy(string $to, bool $force = StreamTouchable::DO_NOT_OVERWRITE): bool + { + $from = $this->getStreamName(); + + if ($force === StreamTouchable::DO_NOT_OVERWRITE && + true === \file_exists($to)) { + return true; + } + + if (null === $this->getStreamContext()) { + return @\copy($from, $to); + } + + return @\copy($from, $to, $this->getStreamContext()->getContext()); + } + + /** + * Move a file. + */ + public function move( + string $name, + bool $force = StreamTouchable::DO_NOT_OVERWRITE, + bool $mkdir = StreamTouchable::DO_NOT_MAKE_DIRECTORY + ): bool { + $from = $this->getStreamName(); + + if ($force === StreamTouchable::DO_NOT_OVERWRITE && + true === \file_exists($name)) { + return false; + } + + if (StreamTouchable::MAKE_DIRECTORY === $mkdir) { + FileDirectory::create( + \dirname($name), + FileDirectory::MODE_CREATE_RECURSIVE + ); + } + + if (null === $this->getStreamContext()) { + return @\rename($from, $name); + } + + return @\rename($from, $name, $this->getStreamContext()->getContext()); + } + + /** + * Delete a file. + */ + public function delete(): bool + { + if (null === $this->getStreamContext()) { + return @\unlink($this->getStreamName()); + } + + return @\unlink( + $this->getStreamName(), + $this->getStreamContext()->getContext() + ); + } + + /** + * Change file group. + */ + public function changeGroup($group): bool + { + return \chgrp($this->getStreamName(), $group); + } + + /** + * Change file mode. + */ + public function changeMode(int $mode): bool + { + return \chmod($this->getStreamName(), $mode); + } + + /** + * Change file owner. + */ + public function changeOwner($user): bool + { + return \chown($this->getStreamName(), $user); + } + + /** + * Change the current umask. + */ + public static function umask(int $umask = null): int + { + if (null === $umask) { + return \umask(); + } + + return \umask($umask); + } + + /** + * Check if it is a file. + */ + public function isFile(): bool + { + return \is_file($this->getStreamName()); + } + + /** + * Check if it is a link. + */ + public function isLink(): bool + { + return \is_link($this->getStreamName()); + } + + /** + * Check if it is a directory. + */ + public function isDirectory(): bool + { + return \is_dir($this->getStreamName()); + } + + /** + * Check if it is a socket. + */ + public function isSocket(): bool + { + return \filetype($this->getStreamName()) === 'socket'; + } + + /** + * Check if it is a FIFO pipe. + */ + public function isFIFOPipe(): bool + { + return \filetype($this->getStreamName()) === 'fifo'; + } + + /** + * Check if it is character special file. + */ + public function isCharacterSpecial(): bool + { + return \filetype($this->getStreamName()) === 'char'; + } + + /** + * Check if it is block special. + */ + public function isBlockSpecial(): bool + { + return \filetype($this->getStreamName()) === 'block'; + } + + /** + * Check if it is an unknown type. + */ + public function isUnknown(): bool + { + return \filetype($this->getStreamName()) === 'unknown'; + } + + /** + * Set the open mode. + */ + protected function setMode(string $mode) + { + $old = $this->_mode; + $this->_mode = $mode; + + return $old; + } + + /** + * Get the open mode. + */ + public function getMode() + { + return $this->_mode; + } + + /** + * Get inode. + */ + public function getINode(): int + { + return \fileinode($this->getStreamName()); + } + + /** + * Check if the system is case sensitive or not. + */ + public static function isCaseSensitive(): bool + { + return !( + \file_exists(\mb_strtolower(__FILE__)) && + \file_exists(\mb_strtoupper(__FILE__)) + ); + } + + /** + * Get a canonicalized absolute pathname. + */ + public function getRealPath(): string + { + if (false === $out = \realpath($this->getStreamName())) { + return $this->getStreamName(); + } + + return $out; + } + + /** + * Get file extension (if exists). + */ + public function getExtension(): string + { + return \pathinfo( + $this->getStreamName(), + \PATHINFO_EXTENSION + ); + } + + /** + * Get filename without extension. + */ + public function getFilename(): string + { + $file = \basename($this->getStreamName()); + + if (\defined('PATHINFO_FILENAME')) { + return \pathinfo($file, \PATHINFO_FILENAME); + } + + if (\strstr($file, '.')) { + return \substr($file, 0, \strrpos($file, '.')); + } + + return $file; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLink.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLink.php new file mode 100644 index 0000000..21a4485 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLink.php @@ -0,0 +1,149 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Link. + * + * Link handler. + */ +class FileLink extends File +{ + /** + * Open a link. + */ + public function __construct( + string $streamName, + string $mode, + string $context = null, + bool $wait = false + ) { + if (!\is_link($streamName)) { + throw new FileException('File %s is not a link.', 0, $streamName); + } + + parent::__construct($streamName, $mode, $context, $wait); + + return; + } + + /** + * Get informations about a link. + */ + public function getStatistic(): array + { + return \lstat($this->getStreamName()); + } + + /** + * Change file group. + */ + public function changeGroup($group): bool + { + return \lchgrp($this->getStreamName(), $group); + } + + /** + * Change file owner. + */ + public function changeOwner($user): bool + { + return \lchown($this->getStreamName(), $user); + } + + /** + * Get file permissions. + */ + public function getPermissions(): int + { + return 41453; // i.e. lrwxr-xr-x + } + + /** + * Get the target of a symbolic link. + */ + public function getTarget(): FileGeneric + { + $target = \dirname($this->getStreamName()).\DIRECTORY_SEPARATOR. + $this->getTargetName(); + $context = null !== $this->getStreamContext() + ? $this->getStreamContext()->getCurrentId() + : null; + + if (true === \is_link($target)) { + return new FileLinkReadWrite( + $target, + File::MODE_APPEND_READ_WRITE, + $context + ); + } elseif (true === \is_file($target)) { + return new FileReadWrite( + $target, + File::MODE_APPEND_READ_WRITE, + $context + ); + } elseif (true === \is_dir($target)) { + return new FileDirectory( + $target, + File::MODE_READ, + $context + ); + } + + throw new FileException('Cannot find an appropriated object that matches with '.'path %s when defining it.', 1, $target); + } + + /** + * Get the target name of a symbolic link. + */ + public function getTargetName(): string + { + return \readlink($this->getStreamName()); + } + + /** + * Create a link. + */ + public static function create(string $name, string $target): bool + { + if (false !== \linkinfo($name)) { + return true; + } + + return \symlink($target, $name); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLinkRead.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLinkRead.php new file mode 100644 index 0000000..37bb514 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLinkRead.php @@ -0,0 +1,231 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Link\Read. + * + * File handler. + * + * @license New BSD License + */ +class FileLinkRead extends FileLink implements StreamIn +{ + /** + * Open a file. + * + * @param string $streamName stream name + * @param string $mode open mode, see the parent::MODE_* constants + * @param string $context context ID (please, see the + * \Hoa\Stream\Context class) + * @param bool $wait differ opening or not + */ + public function __construct( + string $streamName, + string $mode = parent::MODE_READ, + string $context = null, + bool $wait = false + ) { + parent::__construct($streamName, $mode, $context, $wait); + + return; + } + + /** + * Open the stream and return the associated resource. + * + * @param string $streamName Stream name (e.g. path or URL). + * @param \Hoa\Stream\Context $context context + * + * @return resource + * + * @throws \Hoa\File\Exception\FileDoesNotExist + * @throws \Hoa\File\Exception + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + static $createModes = [ + parent::MODE_READ, + ]; + + if (!\in_array($this->getMode(), $createModes)) { + throw new FileException('Open mode are not supported; given %d. Only %s are supported.', 0, [$this->getMode(), \implode(', ', $createModes)]); + } + + \preg_match('#^(\w+)://#', $streamName, $match); + + if (((isset($match[1]) && $match[1] === 'file') || !isset($match[1])) && + !\file_exists($streamName)) { + throw new FileDoesNotExistException('File %s does not exist.', 1, $streamName); + } + + $out = parent::_open($streamName, $context); + + return $out; + } + + /** + * Test for end-of-file. + * + * @return bool + */ + public function eof(): bool + { + return \feof($this->getStream()); + } + + /** + * Read n characters. + * + * @param int $length length + * + * @return string + * + * @throws \Hoa\File\Exception + */ + public function read(int $length) + { + if (0 > $length) { + throw new FileException('Length must be greater than 0, given %d.', 2, $length); + } + + return \fread($this->getStream(), $length); + } + + /** + * Alias of $this->read(). + * + * @param int $length length + * + * @return string + */ + public function readString(int $length) + { + return $this->read($length); + } + + /** + * Read a character. + * + * @return string + */ + public function readCharacter() + { + return \fgetc($this->getStream()); + } + + /** + * Read a boolean. + * + * @return bool + */ + public function readBoolean() + { + return (bool) $this->read(1); + } + + /** + * Read an integer. + * + * @param int $length length + * + * @return int + */ + public function readInteger(int $length = 1) + { + return (int) $this->read($length); + } + + /** + * Read a float. + * + * @param int $length length + * + * @return float + */ + public function readFloat(int $length = 1) + { + return (float) $this->read($length); + } + + /** + * Read an array. + * Alias of the $this->scanf() method. + * + * @param string $format format (see printf's formats) + * + * @return array + */ + public function readArray(string $format = null) + { + return $this->scanf($format); + } + + /** + * Read a line. + * + * @return string + */ + public function readLine() + { + return \fgets($this->getStream()); + } + + /** + * Read all, i.e. read as much as possible. + * + * @param int $offset offset + * + * @return string + */ + public function readAll(int $offset = 0) + { + return \stream_get_contents($this->getStream(), -1, $offset); + } + + /** + * Parse input from a stream according to a format. + * + * @param string $format format (see printf's formats) + * + * @return array + */ + public function scanf(string $format): array + { + return \fscanf($this->getStream(), $format); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLinkReadWrite.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLinkReadWrite.php new file mode 100644 index 0000000..0d16585 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileLinkReadWrite.php @@ -0,0 +1,279 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Link\ReadWrite. + * + * File handler. + */ +class FileLinkReadWrite extends FileLink implements StreamIn, StreamOut +{ + /** + * Open a file. + */ + public function __construct( + string $streamName, + string $mode = parent::MODE_APPEND_READ_WRITE, + string $context = null, + bool $wait = false + ) { + parent::__construct($streamName, $mode, $context, $wait); + + return; + } + + /** + * Open the stream and return the associated resource. + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + static $createModes = [ + parent::MODE_READ_WRITE, + parent::MODE_TRUNCATE_READ_WRITE, + parent::MODE_APPEND_READ_WRITE, + parent::MODE_CREATE_READ_WRITE, + ]; + + if (!\in_array($this->getMode(), $createModes)) { + throw new FileException('Open mode are not supported; given %d. Only %s are supported.', 0, [$this->getMode(), \implode(', ', $createModes)]); + } + + \preg_match('#^(\w+)://#', $streamName, $match); + + if (((isset($match[1]) && $match[1] === 'file') || !isset($match[1])) && + !\file_exists($streamName) && + parent::MODE_READ_WRITE === $this->getMode()) { + throw new FileDoesNotExistException('File %s does not exist.', 1, $streamName); + } + + $out = parent::_open($streamName, $context); + + return $out; + } + + /** + * Test for end-of-file. + */ + public function eof(): bool + { + return \feof($this->getStream()); + } + + /** + * Read n characters. + */ + public function read(int $length) + { + if (0 > $length) { + throw new FileException('Length must be greater than 0, given %d.', 2, $length); + } + + return \fread($this->getStream(), $length); + } + + /** + * Alias of $this->read(). + */ + public function readString(int $length) + { + return $this->read($length); + } + + /** + * Read a character. + */ + public function readCharacter() + { + return \fgetc($this->getStream()); + } + + /** + * Read a boolean. + */ + public function readBoolean() + { + return (bool) $this->read(1); + } + + /** + * Read an integer. + */ + public function readInteger(int $length = 1) + { + return (int) $this->read($length); + } + + /** + * Read a float. + */ + public function readFloat(int $length = 1) + { + return (float) $this->read($length); + } + + /** + * Read an array. + * Alias of the $this->scanf() method. + */ + public function readArray(string $format = null) + { + return $this->scanf($format); + } + + /** + * Read a line. + */ + public function readLine() + { + return \fgets($this->getStream()); + } + + /** + * Read all, i.e. read as much as possible. + */ + public function readAll(int $offset = 0) + { + return \stream_get_contents($this->getStream(), -1, $offset); + } + + /** + * Parse input from a stream according to a format. + */ + public function scanf(string $format): array + { + return \fscanf($this->getStream(), $format); + } + + /** + * Write n characters. + */ + public function write(string $string, int $length) + { + if (0 > $length) { + throw new FileException('Length must be greater than 0, given %d.', 3, $length); + } + + return \fwrite($this->getStream(), $string, $length); + } + + /** + * Write a string. + */ + public function writeString(string $string) + { + $string = (string) $string; + + return $this->write($string, \strlen($string)); + } + + /** + * Write a character. + */ + public function writeCharacter(string $char) + { + return $this->write((string) $char[0], 1); + } + + /** + * Write a boolean. + */ + public function writeBoolean(bool $boolean) + { + return $this->write((string) (bool) $boolean, 1); + } + + /** + * Write an integer. + */ + public function writeInteger(int $integer) + { + $integer = (string) (int) $integer; + + return $this->write($integer, \strlen($integer)); + } + + /** + * Write a float. + */ + public function writeFloat(float $float) + { + $float = (string) (float) $float; + + return $this->write($float, \strlen($float)); + } + + /** + * Write an array. + */ + public function writeArray(array $array) + { + $array = \var_export($array, true); + + return $this->write($array, \strlen($array)); + } + + /** + * Write a line. + */ + public function writeLine(string $line) + { + if (false === $n = \strpos($line, "\n")) { + return $this->write($line."\n", \strlen($line) + 1); + } + + ++$n; + + return $this->write(\substr($line, 0, $n), $n); + } + + /** + * Write all, i.e. as much as possible. + */ + public function writeAll(string $string) + { + return $this->write($string, \strlen($string)); + } + + /** + * Truncate a file to a given length. + */ + public function truncate(int $size): bool + { + return \ftruncate($this->getStream(), $size); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileRead.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileRead.php new file mode 100644 index 0000000..9e10fe6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileRead.php @@ -0,0 +1,177 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\Read. + * + * File handler. + */ +class FileRead extends File implements StreamIn +{ + /** + * Open a file. + */ + public function __construct( + string $streamName, + string $mode = parent::MODE_READ, + string $context = null, + bool $wait = false + ) { + parent::__construct($streamName, $mode, $context, $wait); + + return; + } + + /** + * Open the stream and return the associated resource. + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + static $createModes = [ + parent::MODE_READ, + ]; + + if (!\in_array($this->getMode(), $createModes)) { + throw new FileException('Open mode are not supported; given %d. Only %s are supported.', 0, [$this->getMode(), \implode(', ', $createModes)]); + } + + \preg_match('#^(\w+)://#', $streamName, $match); + + if (((isset($match[1]) && $match[1] === 'file') || !isset($match[1])) && + !\file_exists($streamName)) { + throw new FileDoesNotExistException('File %s does not exist.', 1, $streamName); + } + + $out = parent::_open($streamName, $context); + + return $out; + } + + /** + * Test for end-of-file. + */ + public function eof(): bool + { + return \feof($this->getStream()); + } + + /** + * Read n characters. + */ + public function read(int $length) + { + if (0 > $length) { + throw new FileException('Length must be greater than 0, given %d.', 2, $length); + } + + return \fread($this->getStream(), $length); + } + + /** + * Alias of $this->read(). + */ + public function readString(int $length) + { + return $this->read($length); + } + + /** + * Read a character. + */ + public function readCharacter() + { + return \fgetc($this->getStream()); + } + + /** + * Read a boolean. + */ + public function readBoolean() + { + return (bool) $this->read(1); + } + + /** + * Read an integer. + */ + public function readInteger(int $length = 1) + { + return (int) $this->read($length); + } + + /** + * Read a float. + */ + public function readFloat(int $length = 1) + { + return (float) $this->read($length); + } + + /** + * Read an array. + * Alias of the $this->scanf() method. + */ + public function readArray(string $format = null) + { + return $this->scanf($format); + } + + /** + * Read a line. + */ + public function readLine() + { + return \fgets($this->getStream()); + } + + /** + * Read all, i.e. read as much as possible. + */ + public function readAll(int $offset = 0) + { + return \stream_get_contents($this->getStream(), -1, $offset); + } + + /** + * Parse input from a stream according to a format. + */ + public function scanf(string $format): array + { + return \fscanf($this->getStream(), $format); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileReadWrite.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileReadWrite.php new file mode 100644 index 0000000..406b6aa --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/FileReadWrite.php @@ -0,0 +1,279 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\File\ReadWrite. + * + * File handler. + */ +class FileReadWrite extends File implements StreamIn, StreamOut +{ + /** + * Open a file. + */ + public function __construct( + string $streamName, + string $mode = parent::MODE_APPEND_READ_WRITE, + string $context = null, + bool $wait = false + ) { + parent::__construct($streamName, $mode, $context, $wait); + + return; + } + + /** + * Open the stream and return the associated resource. + */ + protected function &_open(string $streamName, StreamContext $context = null) + { + static $createModes = [ + parent::MODE_READ_WRITE, + parent::MODE_TRUNCATE_READ_WRITE, + parent::MODE_APPEND_READ_WRITE, + parent::MODE_CREATE_READ_WRITE, + ]; + + if (!\in_array($this->getMode(), $createModes)) { + throw new FileException('Open mode are not supported; given %d. Only %s are supported.', 0, [$this->getMode(), \implode(', ', $createModes)]); + } + + \preg_match('#^(\w+)://#', $streamName, $match); + + if (((isset($match[1]) && $match[1] === 'file') || !isset($match[1])) && + !\file_exists($streamName) && + parent::MODE_READ_WRITE === $this->getMode()) { + throw new FileDoesNotExistException('File %s does not exist.', 1, $streamName); + } + + $out = parent::_open($streamName, $context); + + return $out; + } + + /** + * Test for end-of-file. + */ + public function eof(): bool + { + return \feof($this->getStream()); + } + + /** + * Read n characters. + */ + public function read(int $length) + { + if (0 > $length) { + throw new FileException('Length must be greater than 0, given %d.', 2, $length); + } + + return \fread($this->getStream(), $length); + } + + /** + * Alias of $this->read(). + */ + public function readString(int $length) + { + return $this->read($length); + } + + /** + * Read a character. + */ + public function readCharacter() + { + return \fgetc($this->getStream()); + } + + /** + * Read a boolean. + */ + public function readBoolean() + { + return (bool) $this->read(1); + } + + /** + * Read an integer. + */ + public function readInteger(int $length = 1) + { + return (int) $this->read($length); + } + + /** + * Read a float. + */ + public function readFloat(int $length = 1) + { + return (float) $this->read($length); + } + + /** + * Read an array. + * Alias of the $this->scanf() method. + */ + public function readArray(string $format = null) + { + return $this->scanf($format); + } + + /** + * Read a line. + */ + public function readLine() + { + return \fgets($this->getStream()); + } + + /** + * Read all, i.e. read as much as possible. + */ + public function readAll(int $offset = 0) + { + return \stream_get_contents($this->getStream(), -1, $offset); + } + + /** + * Parse input from a stream according to a format. + */ + public function scanf(string $format): array + { + return \fscanf($this->getStream(), $format); + } + + /** + * Write n characters. + */ + public function write(string $string, int $length) + { + if (0 > $length) { + throw new FileException('Length must be greater than 0, given %d.', 3, $length); + } + + return \fwrite($this->getStream(), $string, $length); + } + + /** + * Write a string. + */ + public function writeString(string $string) + { + $string = (string) $string; + + return $this->write($string, \strlen($string)); + } + + /** + * Write a character. + */ + public function writeCharacter(string $char) + { + return $this->write((string) $char[0], 1); + } + + /** + * Write a boolean. + */ + public function writeBoolean(bool $boolean) + { + return $this->write((string) (bool) $boolean, 1); + } + + /** + * Write an integer. + */ + public function writeInteger(int $integer) + { + $integer = (string) (int) $integer; + + return $this->write($integer, \strlen($integer)); + } + + /** + * Write a float. + */ + public function writeFloat(float $float) + { + $float = (string) (float) $float; + + return $this->write($float, \strlen($float)); + } + + /** + * Write an array. + */ + public function writeArray(array $array) + { + $array = \var_export($array, true); + + return $this->write($array, \strlen($array)); + } + + /** + * Write a line. + */ + public function writeLine(string $line) + { + if (false === $n = \strpos($line, "\n")) { + return $this->write($line."\n", \strlen($line) + 1); + } + + ++$n; + + return $this->write(\substr($line, 0, $n), $n); + } + + /** + * Write all, i.e. as much as possible. + */ + public function writeAll(string $string) + { + return $this->write($string, \strlen($string)); + } + + /** + * Truncate a file to a given length. + */ + public function truncate(int $size): bool + { + return \ftruncate($this->getStream(), $size); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IStream.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IStream.php new file mode 100644 index 0000000..9b9949a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IStream.php @@ -0,0 +1,50 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Stream. + * + * Interface for all streams. + */ +interface IStream +{ + /** + * Get the current stream. + */ + public function getStream(); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorFileSystem.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorFileSystem.php new file mode 100644 index 0000000..f0fc5c5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorFileSystem.php @@ -0,0 +1,86 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Iterator\FileSystem. + * + * Extending the SPL FileSystemIterator class. + */ +class IteratorFileSystem extends \FilesystemIterator +{ + /** + * SplFileInfo classname. + */ + protected $_splFileInfoClass = null; + + /** + * Constructor. + * Please, see \FileSystemIterator::__construct() method. + * We add the $splFileInfoClass parameter. + */ + public function __construct(string $path, int $flags = null, string $splFileInfoClass = null) + { + $this->_splFileInfoClass = $splFileInfoClass; + + if (null === $flags) { + parent::__construct($path); + } else { + parent::__construct($path, $flags); + } + + return; + } + + /** + * Current. + * Please, see \FileSystemIterator::current() method. + */ + #[\ReturnTypeWillChange] + public function current() + { + $out = parent::current(); + + if (null !== $this->_splFileInfoClass && + $out instanceof \SplFileInfo) { + $out->setInfoClass($this->_splFileInfoClass); + $out = $out->getFileInfo(); + } + + return $out; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorRecursiveDirectory.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorRecursiveDirectory.php new file mode 100644 index 0000000..ad69512 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorRecursiveDirectory.php @@ -0,0 +1,126 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Iterator\Recursive\Directory. + * + * Extending the SPL RecursiveDirectoryIterator class. + */ +class IteratorRecursiveDirectory extends \RecursiveDirectoryIterator +{ + /** + * SplFileInfo classname. + */ + protected $_splFileInfoClass = null; + + /** + * Relative path. + */ + protected $_relativePath = null; + + /** + * Constructor. + * Please, see \RecursiveDirectoryIterator::__construct() method. + * We add the $splFileInfoClass parameter. + */ + public function __construct(string $path, int $flags = null, string $splFileInfoClass = null) + { + if (null === $flags) { + parent::__construct($path); + } else { + parent::__construct($path, $flags); + } + + $this->_relativePath = $path; + $this->setSplFileInfoClass($splFileInfoClass); + + return; + } + + /** + * Current. + * Please, see \RecursiveDirectoryIterator::current() method. + */ + #[\ReturnTypeWillChange] + public function current() + { + $out = parent::current(); + + if (null !== $this->_splFileInfoClass && + $out instanceof \SplFileInfo) { + $out->setInfoClass($this->_splFileInfoClass); + $out = $out->getFileInfo(); + + if ($out instanceof IteratorSplFileInfo) { + $out->setRelativePath($this->getRelativePath()); + } + } + + return $out; + } + + /** + * Get children. + * Please, see \RecursiveDirectoryIterator::getChildren() method. + */ + #[\ReturnTypeWillChange] + public function getChildren() + { + $out = parent::getChildren(); + $out->_relativePath = $this->getRelativePath(); + $out->setSplFileInfoClass($this->_splFileInfoClass); + + return $out; + } + + /** + * Set SplFileInfo classname. + */ + public function setSplFileInfoClass($splFileInfoClass) + { + $this->_splFileInfoClass = $splFileInfoClass; + } + + /** + * Get relative path (if given). + */ + public function getRelativePath(): string + { + return $this->_relativePath; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorSplFileInfo.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorSplFileInfo.php new file mode 100644 index 0000000..3cf54b8 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/IteratorSplFileInfo.php @@ -0,0 +1,122 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Iterator\SplFileInfo. + * + * Enhance SplFileInfo implementation. + */ +class IteratorSplFileInfo extends \SplFileInfo +{ + /** + * Hash. + */ + protected $_hash = null; + + /** + * Relative path. + */ + protected $_relativePath = null; + + /** + * Construct. + */ + public function __construct(string $filename, string $relativePath = null) + { + parent::__construct($filename); + + if (-1 !== $mtime = $this->getMTime()) { + $this->_hash = \md5($this->getPathname().$mtime); + } + + $this->_relativePath = $relativePath; + + return; + } + + /** + * Get the hash. + */ + public function getHash(): string + { + return $this->_hash; + } + + /** + * Get the MTime. + */ + public function getMTime(): int + { + try { + return parent::getMTime(); + } catch (\RuntimeException $e) { + return -1; + } + } + + /** + * Set relative path. + */ + public function setRelativePath(string $relativePath) + { + $old = $this->_relativePath; + $this->_relativePath = $relativePath; + + return $old; + } + + /** + * Get relative path (if given). + */ + public function getRelativePath() + { + return $this->_relativePath; + } + + /** + * Get relative pathname (if possible). + */ + public function getRelativePathname(): string + { + if (null === $relative = $this->getRelativePath()) { + return $this->getPathname(); + } + + return \substr($this->getPathname(), \strlen($relative)); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Protocol.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Protocol.php new file mode 100644 index 0000000..922ddcb --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Protocol.php @@ -0,0 +1,223 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Root of the `hoa://` protocol. + */ +class Protocol extends ProtocolNode +{ + /** + * No resolution value. + * + * @const string + */ + const NO_RESOLUTION = '/hoa/flatland'; + + /** + * Singleton. + */ + private static $_instance = null; + + /** + * Cache of resolver. + */ + private static $_cache = []; + + /** + * Initialize the protocol. + */ + public function __construct() + { + $this->initialize(); + + return; + } + + /** + * Singleton. + * To use the `hoa://` protocol shared by everyone. + */ + public static function getInstance(): self + { + if (null === static::$_instance) { + static::$_instance = new self(); + } + + return static::$_instance; + } + + /** + * Initialize the protocol. + */ + protected function initialize() + { + $root = \dirname(__DIR__, 3); + $argv0 = isset($_SERVER['argv'][0]) ? \realpath($_SERVER['argv'][0]) : false; + + $cwd = + 'cli' === \PHP_SAPI + ? false !== $argv0 ? \dirname($argv0) : '' + : \getcwd(); + + $this[] = new ProtocolNode( + 'Application', + $cwd.\DIRECTORY_SEPARATOR, + [ + new ProtocolNode('Public', 'Public'.\DIRECTORY_SEPARATOR), + ] + ); + + $this[] = new ProtocolNode( + 'Data', + \dirname($cwd).\DIRECTORY_SEPARATOR, + [ + new ProtocolNode( + 'Etc', + 'Etc'.\DIRECTORY_SEPARATOR, + [ + new ProtocolNode('Configuration', 'Configuration'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Locale', 'Locale'.\DIRECTORY_SEPARATOR), + ] + ), + new ProtocolNode('Lost+found', 'Lost+found'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Temporary', 'Temporary'.\DIRECTORY_SEPARATOR), + new ProtocolNode( + 'Variable', + 'Variable'.\DIRECTORY_SEPARATOR, + [ + new ProtocolNode('Cache', 'Cache'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Database', 'Database'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Log', 'Log'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Private', 'Private'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Run', 'Run'.\DIRECTORY_SEPARATOR), + new ProtocolNode('Test', 'Test'.\DIRECTORY_SEPARATOR), + ] + ), + ] + ); + + $this[] = new ProtocolNodeLibrary( + 'Library', + $root.\DIRECTORY_SEPARATOR.'Hoathis'.\DIRECTORY_SEPARATOR.';'. + $root.\DIRECTORY_SEPARATOR.'Hoa'.\DIRECTORY_SEPARATOR + ); + } + + /** + * Resolve (unfold) an `hoa://` path to its real resource. + * + * If `$exists` is set to `true`, try to find the first that exists, + * otherwise returns the first solution. If `$unfold` is set to `true`, + * it returns all the paths. + */ + public function resolve(string $path, bool $exists = true, bool $unfold = false) + { + if (\substr($path, 0, 6) !== 'hoa://') { + if (true === \is_dir($path)) { + $path = \rtrim($path, '/\\'); + + if ('' === $path) { + $path = '/'; + } + } + + return $path; + } + + if (isset(self::$_cache[$path])) { + $handle = self::$_cache[$path]; + } else { + $out = $this->_resolve($path, $handle); + + // Not a path but a resource. + if (!\is_array($handle)) { + return $out; + } + + $handle = \array_values(\array_unique($handle, \SORT_REGULAR)); + + foreach ($handle as &$entry) { + if (true === \is_dir($entry)) { + $entry = \rtrim($entry, '/\\'); + + if ('' === $entry) { + $entry = '/'; + } + } + } + + self::$_cache[$path] = $handle; + } + + if (true === $unfold) { + if (true !== $exists) { + return $handle; + } + + $out = []; + + foreach ($handle as $solution) { + if (\file_exists($solution)) { + $out[] = $solution; + } + } + + return $out; + } + + if (true !== $exists) { + return $handle[0]; + } + + foreach ($handle as $solution) { + if (\file_exists($solution)) { + return $solution; + } + } + + return static::NO_RESOLUTION; + } + + /** + * Clear the cache. + */ + public static function clearCache() + { + self::$_cache = []; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolException.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolException.php new file mode 100644 index 0000000..6b624bb --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolException.php @@ -0,0 +1,44 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Extends the `Hoa\Exception\Exception` class. + */ +class ProtocolException extends Exception +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolNode.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolNode.php new file mode 100644 index 0000000..78812d7 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolNode.php @@ -0,0 +1,323 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Abstract class for all `hoa://`'s nodes. + */ +class ProtocolNode implements \ArrayAccess, \IteratorAggregate +{ + /** + * Node's name. + */ + protected $_name = null; + + /** + * Path for the `reach` method. + */ + protected $_reach = null; + + /** + * Children of the node. + */ + private $_children = []; + + /** + * Construct a protocol's node. + * If it is not a data object (i.e. if it does not extend this class to + * overload the `$_name` attribute), we can set the `$_name` attribute + * dynamically. This is useful to create a node on-the-fly. + */ + public function __construct(string $name = null, string $reach = null, array $children = []) + { + if (null !== $name) { + $this->_name = $name; + } + + if (null !== $reach) { + $this->_reach = $reach; + } + + foreach ($children as $child) { + $this[] = $child; + } + + return; + } + + /** + * Add a node. + */ + #[\ReturnTypeWillChange] + public function offsetSet($name, $node) + { + if (!($node instanceof self)) { + throw new ProtocolException('Protocol node must extend %s.', 0, __CLASS__); + } + + if (empty($name)) { + $name = $node->getName(); + } + + if (empty($name)) { + throw new ProtocolException('Cannot add a node to the `hoa://` protocol without a name.', 1); + } + + $this->_children[$name] = $node; + } + + /** + * Get a specific node. + */ + public function offsetGet($name): self + { + if (!isset($this[$name])) { + throw new ProtocolException('Node %s does not exist.', 2, $name); + } + + return $this->_children[$name]; + } + + /** + * Check if a node exists. + */ + public function offsetExists($name): bool + { + return true === \array_key_exists($name, $this->_children); + } + + /** + * Remove a node. + */ + #[\ReturnTypeWillChange] + public function offsetUnset($name) + { + unset($this->_children[$name]); + } + + /** + * Resolve a path, i.e. iterate the nodes tree and reach the queue of + * the path. + */ + protected function _resolve(string $path, &$accumulator, string $id = null) + { + if (\substr($path, 0, 6) === 'hoa://') { + $path = \substr($path, 6); + } + + if (empty($path)) { + return null; + } + + if (null === $accumulator) { + $accumulator = []; + $posId = \strpos($path, '#'); + + if (false !== $posId) { + $id = \substr($path, $posId + 1); + $path = \substr($path, 0, $posId); + } else { + $id = null; + } + } + + $path = \trim($path, '/'); + $pos = \strpos($path, '/'); + + if (false !== $pos) { + $next = \substr($path, 0, $pos); + } else { + $next = $path; + } + + if (isset($this[$next])) { + if (false === $pos) { + if (null === $id) { + $this->_resolveChoice($this[$next]->reach(), $accumulator); + + return true; + } + + $accumulator = null; + + return $this[$next]->reachId($id); + } + + $tnext = $this[$next]; + $this->_resolveChoice($tnext->reach(), $accumulator); + + return $tnext->_resolve(\substr($path, $pos + 1), $accumulator, $id); + } + + $this->_resolveChoice($this->reach($path), $accumulator); + + return true; + } + + /** + * Resolve choices, i.e. a reach value has a “;”. + */ + protected function _resolveChoice($reach, &$accumulator) + { + if (null === $reach) { + $reach = ''; + } + + if (empty($accumulator)) { + $accumulator = \explode(';', $reach); + + return; + } + + if (false === \strpos($reach, ';')) { + if (false !== $pos = \strrpos($reach, "\r")) { + $reach = \substr($reach, $pos + 1); + + foreach ($accumulator as &$entry) { + $entry = null; + } + } + + foreach ($accumulator as &$entry) { + $entry .= $reach; + } + + return; + } + + $choices = \explode(';', $reach); + $ref = $accumulator; + $accumulator = []; + + foreach ($choices as $choice) { + if (false !== $pos = \strrpos($choice, "\r")) { + $choice = \substr($choice, $pos + 1); + + foreach ($ref as $entry) { + $accumulator[] = $choice; + } + } else { + foreach ($ref as $entry) { + $accumulator[] = $entry.$choice; + } + } + } + + unset($ref); + + return; + } + + /** + * Queue of the node. + * Generic one. Must be overrided in children classes. + */ + public function reach(string $queue = null) + { + return empty($queue) ? $this->_reach : $queue; + } + + /** + * ID of the component. + * Generic one. Should be overrided in children classes. + */ + public function reachId(string $id) + { + throw new ProtocolException('The node %s has no ID support (tried to reach #%s).', 4, [$this->getName(), $id]); + } + + /** + * Set a new reach value. + */ + public function setReach(string $reach) + { + $old = $this->_reach; + $this->_reach = $reach; + + return $old; + } + + /** + * Get node's name. + */ + public function getName() + { + return $this->_name; + } + + /** + * Get reach's root. + */ + protected function getReach() + { + return $this->_reach; + } + + /** + * Get an iterator. + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->_children); + } + + /** + * Get root the protocol. + */ + public static function getRoot(): Protocol + { + return Protocol::getInstance(); + } + + /** + * Print a tree of component. + */ + public function __toString(): string + { + static $i = 0; + + $out = \str_repeat(' ', $i).$this->getName()."\n"; + + foreach ($this as $node) { + ++$i; + $out .= $node; + --$i; + } + + return $out; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolNodeLibrary.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolNodeLibrary.php new file mode 100644 index 0000000..0719374 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolNodeLibrary.php @@ -0,0 +1,90 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * The `hoa://Library/` node. + */ +class ProtocolNodeLibrary extends ProtocolNode +{ + /** + * Queue of the component. + */ + public function reach(string $queue = null) + { + $withComposer = \class_exists('Composer\Autoload\ClassLoader', false) || + ('cli' === \PHP_SAPI && \file_exists(__DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'autoload.php')); + + if ($withComposer) { + return parent::reach($queue); + } + + if (!empty($queue)) { + $head = $queue; + + if (false !== $pos = \strpos($queue, '/')) { + $head = \substr($head, 0, $pos); + $queue = \DIRECTORY_SEPARATOR.\substr($queue, $pos + 1); + } else { + $queue = null; + } + + $out = []; + + foreach (\explode(';', $this->_reach) as $part) { + $out[] = "\r".$part.\strtolower($head).$queue; + } + + $out[] = "\r".\dirname(__DIR__, 5).$queue; + + return \implode(';', $out); + } + + $out = []; + + foreach (\explode(';', $this->_reach) as $part) { + $pos = \strrpos(\rtrim($part, \DIRECTORY_SEPARATOR), \DIRECTORY_SEPARATOR) + 1; + $head = \substr($part, 0, $pos); + $tail = \substr($part, $pos); + $out[] = $head.\strtolower($tail); + } + + $this->_reach = \implode(';', $out); + + return parent::reach($queue); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolWrapper.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolWrapper.php new file mode 100644 index 0000000..8d525e7 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/ProtocolWrapper.php @@ -0,0 +1,473 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Stream wrapper for the `hoa://` protocol. + */ +class ProtocolWrapper +{ + /** + * Opened stream as a resource. + */ + private $_stream = null; + + /** + * Stream name (filename). + */ + private $_streamName = null; + + /** + * Stream context (given by the streamWrapper class) as a resource. + */ + public $context = null; + + /** + * Get the real path of the given URL. + * Could return false if the path cannot be reached. + */ + public static function realPath(string $path, bool $exists = true) + { + return ProtocolNode::getRoot()->resolve($path, $exists); + } + + /** + * Retrieve the underlying resource. + * + * `$castAs` can be `STREAM_CAST_FOR_SELECT` when `stream_select` is + * calling `stream_cast` or `STREAM_CAST_AS_STREAM` when `stream_cast` is + * called for other uses. + */ + public function stream_cast(int $castAs) + { + return null; + } + + /** + * Closes a resource. + * This method is called in response to `fclose`. + * All resources that were locked, or allocated, by the wrapper should be + * released. + */ + public function stream_close() + { + if (true === @\fclose($this->getStream())) { + $this->_stream = null; + $this->_streamName = null; + } + } + + /** + * Tests for end-of-file on a file pointer. + * This method is called in response to feof(). + */ + public function stream_eof(): bool + { + return \feof($this->getStream()); + } + + /** + * Flush the output. + * This method is called in respond to fflush(). + * If we have cached data in our stream but not yet stored it into the + * underlying storage, we should do so now. + */ + public function stream_flush(): bool + { + return \fflush($this->getStream()); + } + + /** + * Advisory file locking. + * This method is called in response to flock(), when file_put_contents() + * (when flags contains LOCK_EX), stream_set_blocking() and when closing the + * stream (LOCK_UN). + * + * Operation is one the following: + * * LOCK_SH to acquire a shared lock (reader) ; + * * LOCK_EX to acquire an exclusive lock (writer) ; + * * LOCK_UN to release a lock (shared or exclusive) ; + * * LOCK_NB if we don't want flock() to + * block while locking (not supported on + * Windows). + */ + public function stream_lock(int $operation): bool + { + return \flock($this->getStream(), $operation); + } + + /** + * Change stream options. + * This method is called to set metadata on the stream. It is called when + * one of the following functions is called on a stream URL: touch, chmod, + * chown or chgrp. + * + * Option must be one of the following constant: + * * STREAM_META_TOUCH, + * * STREAM_META_OWNER_NAME, + * * STREAM_META_OWNER, + * * STREAM_META_GROUP_NAME, + * * STREAM_META_GROUP, + * * STREAM_META_ACCESS. + * + * Values are arguments of `touch`, `chmod`, `chown`, and `chgrp`. + */ + public function stream_metadata(string $path, int $option, $values): bool + { + $path = static::realPath($path, false); + + switch ($option) { + case \STREAM_META_TOUCH: + $arity = \count($values); + + if (0 === $arity) { + $out = \touch($path); + } elseif (1 === $arity) { + $out = \touch($path, $values[0]); + } else { + $out = \touch($path, $values[0], $values[1]); + } + + break; + + case \STREAM_META_OWNER_NAME: + case \STREAM_META_OWNER: + $out = \chown($path, $values); + + break; + + case \STREAM_META_GROUP_NAME: + case \STREAM_META_GROUP: + $out = \chgrp($path, $values); + + break; + + case \STREAM_META_ACCESS: + $out = \chmod($path, $values); + + break; + + default: + $out = false; + } + + return $out; + } + + /** + * Open file or URL. + * This method is called immediately after the wrapper is initialized (f.e. + * by fopen() and file_get_contents()). + */ + public function stream_open(string $path, string $mode, int $options, &$openedPath): bool + { + $path = static::realPath($path, 'r' === $mode[0]); + + if (Protocol::NO_RESOLUTION === $path) { + return false; + } + + if (null === $this->context) { + $openedPath = \fopen($path, $mode, $options & \STREAM_USE_PATH); + } else { + $openedPath = \fopen( + $path, + $mode, + (bool) ($options & \STREAM_USE_PATH), + $this->context + ); + } + + if (false === \is_resource($openedPath)) { + return false; + } + + $this->_stream = $openedPath; + $this->_streamName = $path; + + return true; + } + + /** + * Read from stream. + * This method is called in response to fread() and fgets(). + */ + public function stream_read(int $size): string + { + return \fread($this->getStream(), $size); + } + + /** + * Seek to specific location in a stream. + * This method is called in response to fseek(). + * The read/write position of the stream should be updated according to the + * $offset and $whence. + * + * The possible values for `$whence` are: + * * SEEK_SET to set position equal to $offset bytes, + * * SEEK_CUR to set position to current location plus `$offset`, + * * SEEK_END to set position to end-of-file plus `$offset`. + */ + public function stream_seek(int $offset, int $whence = \SEEK_SET): bool + { + return 0 === \fseek($this->getStream(), $offset, $whence); + } + + /** + * Retrieve information about a file resource. + * This method is called in response to fstat(). + */ + public function stream_stat(): array + { + return \fstat($this->getStream()); + } + + /** + * Retrieve the current position of a stream. + * This method is called in response to ftell(). + */ + public function stream_tell(): int + { + return \ftell($this->getStream()); + } + + /** + * Truncate a stream to a given length. + */ + public function stream_truncate(int $size): bool + { + return \ftruncate($this->getStream(), $size); + } + + /** + * Write to stream. + * This method is called in response to fwrite(). + */ + public function stream_write(string $data): int + { + return \fwrite($this->getStream(), $data); + } + + /** + * Close directory handle. + * This method is called in to closedir(). + * Any resources which were locked, or allocated, during opening and use of + * the directory stream should be released. + */ + public function dir_closedir() + { + \closedir($this->getStream()); + $this->_stream = null; + $this->_streamName = null; + } + + /** + * Open directory handle. + * This method is called in response to opendir(). + * + * The `$options` input represents whether or not to enforce safe_mode + * (0x04). It is not used here. + */ + public function dir_opendir(string $path, int $options): bool + { + $path = static::realPath($path); + $handle = null; + + if (null === $this->context) { + $handle = @\opendir($path); + } else { + $handle = @\opendir($path, $this->context); + } + + if (false === $handle) { + return false; + } + + $this->_stream = $handle; + $this->_streamName = $path; + + return true; + } + + /** + * Read entry from directory handle. + * This method is called in response to readdir(). + * + * @return mixed + */ + public function dir_readdir() + { + return \readdir($this->getStream()); + } + + /** + * Rewind directory handle. + * This method is called in response to rewinddir(). + * Should reset the output generated by self::dir_readdir, i.e. the next + * call to self::dir_readdir should return the first entry in the location + * returned by self::dir_opendir. + */ + public function dir_rewinddir() + { + \rewinddir($this->getStream()); + } + + /** + * Create a directory. + * This method is called in response to mkdir(). + */ + public function mkdir(string $path, int $mode, int $options): bool + { + if (null === $this->context) { + return \mkdir( + static::realPath($path, false), + $mode, + $options | \STREAM_MKDIR_RECURSIVE + ); + } + + return \mkdir( + static::realPath($path, false), + $mode, + (bool) ($options | \STREAM_MKDIR_RECURSIVE), + $this->context + ); + } + + /** + * Rename a file or directory. + * This method is called in response to rename(). + * Should attempt to rename $from to $to. + */ + public function rename(string $from, string $to): bool + { + if (null === $this->context) { + return \rename(static::realPath($from), static::realPath($to, false)); + } + + return \rename( + static::realPath($from), + static::realPath($to, false), + $this->context + ); + } + + /** + * Remove a directory. + * This method is called in response to rmdir(). + * The `$options` input is a bitwise mask of values. It is not used here. + */ + public function rmdir(string $path, int $options): bool + { + if (null === $this->context) { + return \rmdir(static::realPath($path)); + } + + return \rmdir(static::realPath($path), $this->context); + } + + /** + * Delete a file. + * This method is called in response to unlink(). + */ + public function unlink(string $path): bool + { + if (null === $this->context) { + return \unlink(static::realPath($path)); + } + + return \unlink(static::realPath($path), $this->context); + } + + /** + * Retrieve information about a file. + * This method is called in response to all stat() related functions. + * The `$flags` input holds additional flags set by the streams API. It + * can hold one or more of the following values OR'd together. + * STREAM_URL_STAT_LINK: for resource with the ability to link to other + * resource (such as an HTTP location: forward, or a filesystem + * symlink). This flag specified that only information about the link + * itself should be returned, not the resource pointed to by the + * link. This flag is set in response to calls to lstat(), is_link(), or + * filetype(). STREAM_URL_STAT_QUIET: if this flag is set, our wrapper + * should not raise any errors. If this flag is not set, we are + * responsible for reporting errors using the trigger_error() function + * during stating of the path. + */ + public function url_stat(string $path, int $flags) + { + $path = static::realPath($path); + + if (Protocol::NO_RESOLUTION === $path) { + if ($flags & \STREAM_URL_STAT_QUIET) { + return 0; + } else { + return \trigger_error( + 'Path '.$path.' cannot be resolved.', + \E_WARNING + ); + } + } + + if ($flags & \STREAM_URL_STAT_LINK) { + return @\lstat($path); + } + + return @\stat($path); + } + + /** + * Get stream resource. + */ + public function getStream() + { + return $this->_stream; + } + + /** + * Get stream name. + */ + public function getStreamName() + { + return $this->_streamName; + } +} + +/* + * Register the `hoa://` protocol. + */ +\stream_wrapper_register('hoa', ProtocolWrapper::class); diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Readline.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Readline.php new file mode 100644 index 0000000..0338c90 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Readline.php @@ -0,0 +1,1032 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Console\Readline. + * + * Read, edit, bind… a line from the input. + */ +class Readline +{ + /** + * State: continue to read. + */ + const STATE_CONTINUE = 1; + + /** + * State: stop to read. + */ + const STATE_BREAK = 2; + + /** + * State: no output the current buffer. + */ + const STATE_NO_ECHO = 4; + + /** + * Current editing line. + */ + protected $_line = null; + + /** + * Current editing line seek. + */ + protected $_lineCurrent = 0; + + /** + * Current editing line length. + */ + protected $_lineLength = 0; + + /** + * Current buffer (most of the time, a char). + */ + protected $_buffer = null; + + /** + * Mapping. + */ + protected $_mapping = []; + + /** + * History. + */ + protected $_history = []; + + /** + * History current position. + */ + protected $_historyCurrent = 0; + + /** + * History size. + */ + protected $_historySize = 0; + + /** + * Prefix. + */ + protected $_prefix = null; + + /** + * Autocompleter. + */ + protected $_autocompleter = null; + + /** + * Initialize the readline editor. + */ + public function __construct() + { + if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { + return; + } + + $this->_mapping["\033[A"] = [$this, '_bindArrowUp']; + $this->_mapping["\033[B"] = [$this, '_bindArrowDown']; + $this->_mapping["\033[C"] = [$this, '_bindArrowRight']; + $this->_mapping["\033[D"] = [$this, '_bindArrowLeft']; + $this->_mapping["\001"] = [$this, '_bindControlA']; + $this->_mapping["\002"] = [$this, '_bindControlB']; + $this->_mapping["\005"] = [$this, '_bindControlE']; + $this->_mapping["\006"] = [$this, '_bindControlF']; + $this->_mapping["\010"] = + $this->_mapping["\177"] = [$this, '_bindBackspace']; + $this->_mapping["\027"] = [$this, '_bindControlW']; + $this->_mapping["\n"] = [$this, '_bindNewline']; + $this->_mapping["\t"] = [$this, '_bindTab']; + + return; + } + + /** + * Read a line from the input. + */ + public function readLine(string $prefix = null) + { + $input = Console::getInput(); + + if (true === $input->eof()) { + return false; + } + + $direct = Console::isDirect($input->getStream()->getStream()); + $output = Console::getOutput(); + + if (false === $direct || \defined('PHP_WINDOWS_VERSION_PLATFORM')) { + $out = $input->readLine(); + + if (false === $out) { + return false; + } + + $out = \substr($out, 0, -1); + + if (true === $direct) { + $output->writeAll($prefix); + } else { + $output->writeAll($prefix.$out."\n"); + } + + return $out; + } + + $this->resetLine(); + $this->setPrefix($prefix); + $read = [$input->getStream()->getStream()]; + $write = $except = []; + $output->writeAll($prefix); + + while (true) { + @\stream_select($read, $write, $except, 30, 0); + + if (empty($read)) { + $read = [$input->getStream()->getStream()]; + + continue; + } + + $char = $this->_read(); + $this->_buffer = $char; + $return = $this->_readLine($char); + + if (0 === ($return & self::STATE_NO_ECHO)) { + $output->writeAll($this->_buffer); + } + + if (0 !== ($return & self::STATE_BREAK)) { + break; + } + } + + return $this->getLine(); + } + + /** + * Readline core. + */ + public function _readLine(string $char) + { + if (isset($this->_mapping[$char]) && + \is_callable($this->_mapping[$char])) { + $mapping = $this->_mapping[$char]; + + return $mapping($this); + } + + if (isset($this->_mapping[$char])) { + $this->_buffer = $this->_mapping[$char]; + } elseif (false === Ustring::isCharPrintable($char)) { + ConsoleCursor::bip(); + + return static::STATE_CONTINUE | static::STATE_NO_ECHO; + } + + if ($this->getLineLength() === $this->getLineCurrent()) { + $this->appendLine($this->_buffer); + + return static::STATE_CONTINUE; + } + + $this->insertLine($this->_buffer); + $tail = \mb_substr( + $this->getLine(), + $this->getLineCurrent() - 1 + ); + $this->_buffer = "\033[K".$tail.\str_repeat( + "\033[D", + \mb_strlen($tail) - 1 + ); + + return static::STATE_CONTINUE; + } + + /** + * Add mappings. + */ + public function addMappings(array $mappings) + { + foreach ($mappings as $key => $mapping) { + $this->addMapping($key, $mapping); + } + } + + /** + * Add a mapping. + * Supported key: + * • \e[… for \033[…; + * • \C-… for Ctrl-…; + * • abc for a simple mapping. + * A mapping is a callable that has only one parameter of type + * Hoa\Console\Readline and that returns a self::STATE_* constant. + */ + public function addMapping(string $key, $mapping) + { + if ('\e[' === \substr($key, 0, 3)) { + $this->_mapping["\033[".\substr($key, 3)] = $mapping; + } elseif ('\C-' === \substr($key, 0, 3)) { + $_key = \ord(\strtolower(\substr($key, 3))) - 96; + $this->_mapping[\chr($_key)] = $mapping; + } else { + $this->_mapping[$key] = $mapping; + } + } + + /** + * Add an entry in the history. + */ + public function addHistory(string $line = null) + { + if (empty($line)) { + return; + } + + $this->_history[] = $line; + $this->_historyCurrent = $this->_historySize++; + } + + /** + * Clear history. + */ + public function clearHistory() + { + unset($this->_history); + $this->_history = []; + $this->_historyCurrent = 0; + $this->_historySize = 1; + } + + /** + * Get an entry in the history. + */ + public function getHistory(int $i = null) + { + if (null === $i) { + $i = $this->_historyCurrent; + } + + if (!isset($this->_history[$i])) { + return null; + } + + return $this->_history[$i]; + } + + /** + * Go backward in the history. + */ + public function previousHistory() + { + if (0 >= $this->_historyCurrent) { + return $this->getHistory(0); + } + + return $this->getHistory($this->_historyCurrent--); + } + + /** + * Go forward in the history. + */ + public function nextHistory() + { + if ($this->_historyCurrent + 1 >= $this->_historySize) { + return $this->getLine(); + } + + return $this->getHistory(++$this->_historyCurrent); + } + + /** + * Get current line. + */ + public function getLine() + { + return $this->_line; + } + + /** + * Append to current line. + */ + public function appendLine(string $append) + { + $this->_line .= $append; + $this->_lineLength = \mb_strlen($this->_line); + $this->_lineCurrent = $this->_lineLength; + } + + /** + * Insert into current line at the current seek. + */ + public function insertLine(string $insert) + { + if ($this->_lineLength === $this->_lineCurrent) { + return $this->appendLine($insert); + } + + $this->_line = \mb_substr($this->_line, 0, $this->_lineCurrent). + $insert. + \mb_substr($this->_line, $this->_lineCurrent); + $this->_lineLength = \mb_strlen($this->_line); + $this->_lineCurrent += \mb_strlen($insert); + + return; + } + + /** + * Reset current line. + */ + protected function resetLine() + { + $this->_line = null; + $this->_lineCurrent = 0; + $this->_lineLength = 0; + } + + /** + * Get current line seek. + */ + public function getLineCurrent(): int + { + return $this->_lineCurrent; + } + + /** + * Get current line length. + * + * @return int + */ + public function getLineLength(): int + { + return $this->_lineLength; + } + + /** + * Set prefix. + */ + public function setPrefix(string $prefix) + { + $this->_prefix = $prefix; + } + + /** + * Get prefix. + */ + public function getPrefix() + { + return $this->_prefix; + } + + /** + * Get buffer. Not for user. + */ + public function getBuffer() + { + return $this->_buffer; + } + + /** + * Set an autocompleter. + */ + public function setAutocompleter(Autocompleter $autocompleter) + { + $old = $this->_autocompleter; + $this->_autocompleter = $autocompleter; + + return $old; + } + + /** + * Get the autocompleter. + * + * @return ?Autocompleter + */ + public function getAutocompleter() + { + return $this->_autocompleter; + } + + /** + * Read on input. Not for user. + */ + public function _read(int $length = 512): string + { + return Console::getInput()->read($length); + } + + /** + * Set current line. Not for user. + */ + public function setLine(string $line) + { + $this->_line = $line; + $this->_lineLength = \mb_strlen($this->_line ?: ''); + $this->_lineCurrent = $this->_lineLength; + } + + /** + * Set current line seek. Not for user. + */ + public function setLineCurrent(int $current) + { + $this->_lineCurrent = $current; + } + + /** + * Set line length. Not for user. + */ + public function setLineLength(int $length) + { + $this->_lineLength = $length; + } + + /** + * Set buffer. Not for user. + */ + public function setBuffer(string $buffer) + { + $this->_buffer = $buffer; + } + + /** + * Up arrow binding. + * Go backward in the history. + */ + public function _bindArrowUp(self $self): int + { + if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) { + ConsoleCursor::clear('↔'); + Console::getOutput()->writeAll($self->getPrefix()); + } + $buffer = $self->previousHistory() ?? ''; + $self->setBuffer($buffer); + $self->setLine($buffer); + + return static::STATE_CONTINUE; + } + + /** + * Down arrow binding. + * Go forward in the history. + */ + public function _bindArrowDown(self $self): int + { + if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) { + ConsoleCursor::clear('↔'); + Console::getOutput()->writeAll($self->getPrefix()); + } + + $self->setBuffer($buffer = $self->nextHistory()); + $self->setLine($buffer); + + return static::STATE_CONTINUE; + } + + /** + * Right arrow binding. + * Move cursor to the right. + */ + public function _bindArrowRight(self $self): int + { + if ($self->getLineLength() > $self->getLineCurrent()) { + if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) { + ConsoleCursor::move('→'); + } + + $self->setLineCurrent($self->getLineCurrent() + 1); + } + + $self->setBuffer(''); + + return static::STATE_CONTINUE; + } + + /** + * Left arrow binding. + * Move cursor to the left. + */ + public function _bindArrowLeft(self $self): int + { + if (0 < $self->getLineCurrent()) { + if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) { + ConsoleCursor::move('←'); + } + + $self->setLineCurrent($self->getLineCurrent() - 1); + } + + $self->setBuffer(''); + + return static::STATE_CONTINUE; + } + + /** + * Backspace and Control-H binding. + * Delete the first character at the right of the cursor. + */ + public function _bindBackspace(self $self): int + { + $buffer = ''; + + if (0 < $self->getLineCurrent()) { + if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) { + ConsoleCursor::move('←'); + ConsoleCursor::clear('→'); + } + + if ($self->getLineLength() === $current = $self->getLineCurrent()) { + $self->setLine(\mb_substr($self->getLine(), 0, -1)); + } else { + $line = $self->getLine(); + $current = $self->getLineCurrent(); + $tail = \mb_substr($line, $current); + $buffer = $tail.\str_repeat("\033[D", \mb_strlen($tail)); + $self->setLine(\mb_substr($line, 0, $current - 1).$tail); + $self->setLineCurrent($current - 1); + } + } + + $self->setBuffer($buffer); + + return static::STATE_CONTINUE; + } + + /** + * Control-A binding. + * Move cursor to beginning of line. + */ + public function _bindControlA(self $self): int + { + for ($i = $self->getLineCurrent() - 1; 0 <= $i; --$i) { + $self->_bindArrowLeft($self); + } + + return static::STATE_CONTINUE; + } + + /** + * Control-B binding. + * Move cursor backward one word. + */ + public function _bindControlB(self $self): int + { + $current = $self->getLineCurrent(); + + if (0 === $current) { + return static::STATE_CONTINUE; + } + + $words = \preg_split( + '#\b#u', + $self->getLine(), + -1, + \PREG_SPLIT_OFFSET_CAPTURE | \PREG_SPLIT_NO_EMPTY + ); + + for ( + $i = 0, $max = \count($words) - 1; + $i < $max && $words[$i + 1][1] < $current; + ++$i + ) { + } + + for ($j = $words[$i][1] + 1; $current >= $j; ++$j) { + $self->_bindArrowLeft($self); + } + + return static::STATE_CONTINUE; + } + + /** + * Control-E binding. + * Move cursor to end of line. + */ + public function _bindControlE(self $self): int + { + for ( + $i = $self->getLineCurrent(), $max = $self->getLineLength(); + $i < $max; + ++$i + ) { + $self->_bindArrowRight($self); + } + + return static::STATE_CONTINUE; + } + + /** + * Control-F binding. + * Move cursor forward one word. + */ + public function _bindControlF(self $self): int + { + $current = $self->getLineCurrent(); + + if ($self->getLineLength() === $current) { + return static::STATE_CONTINUE; + } + + $words = \preg_split( + '#\b#u', + $self->getLine(), + -1, + \PREG_SPLIT_OFFSET_CAPTURE | \PREG_SPLIT_NO_EMPTY + ); + + for ( + $i = 0, $max = \count($words) - 1; + $i < $max && $words[$i][1] < $current; + ++$i + ) { + } + + if (!isset($words[$i + 1])) { + $words[$i + 1] = [1 => $self->getLineLength()]; + } + + for ($j = $words[$i + 1][1]; $j > $current; --$j) { + $self->_bindArrowRight($self); + } + + return static::STATE_CONTINUE; + } + + /** + * Control-W binding. + * Delete first backward word. + */ + public function _bindControlW(self $self): int + { + $current = $self->getLineCurrent(); + + if (0 === $current) { + return static::STATE_CONTINUE; + } + + $words = \preg_split( + '#\b#u', + $self->getLine(), + -1, + \PREG_SPLIT_OFFSET_CAPTURE | \PREG_SPLIT_NO_EMPTY + ); + + for ( + $i = 0, $max = \count($words) - 1; + $i < $max && $words[$i + 1][1] < $current; + ++$i + ) { + } + + for ($j = $words[$i][1] + 1; $current >= $j; ++$j) { + $self->_bindBackspace($self); + } + + return static::STATE_CONTINUE; + } + + /** + * Newline binding. + */ + public function _bindNewline(self $self): int + { + $self->addHistory($self->getLine()); + + return static::STATE_BREAK; + } + + /** + * Tab binding. + */ + public function _bindTab(self $self): int + { + $output = Console::getOutput(); + $autocompleter = $self->getAutocompleter(); + $state = static::STATE_CONTINUE | static::STATE_NO_ECHO; + + if (null === $autocompleter) { + return $state; + } + + $current = $self->getLineCurrent(); + $line = $self->getLine(); + + if (0 === $current) { + return $state; + } + + $matches = \preg_match_all( + '#'.$autocompleter->getWordDefinition().'$#u', + \mb_substr($line, 0, $current), + $words + ); + + if (0 === $matches) { + return $state; + } + + $word = $words[0][0]; + + if ('' === \trim($word)) { + return $state; + } + + $solution = $autocompleter->complete($word); + $length = \mb_strlen($word); + + if (null === $solution) { + return $state; + } + + if (\is_array($solution)) { + $_solution = $solution; + $count = \count($_solution) - 1; + $cWidth = 0; + $window = ConsoleWindow::getSize(); + $wWidth = $window['x']; + $cursor = ConsoleCursor::getPosition(); + + \array_walk($_solution, function (&$value) use (&$cWidth) { + $handle = \mb_strlen($value); + + if ($handle > $cWidth) { + $cWidth = $handle; + } + + return; + }); + \array_walk($_solution, function (&$value) use (&$cWidth) { + $handle = \mb_strlen($value); + + if ($handle >= $cWidth) { + return; + } + + $value .= \str_repeat(' ', $cWidth - $handle); + + return; + }); + + $mColumns = (int) \floor($wWidth / ($cWidth + 2)); + $mLines = (int) \ceil(($count + 1) / $mColumns); + --$mColumns; + $i = 0; + + if (0 > $window['y'] - $cursor['y'] - $mLines) { + ConsoleWindow::scroll('↑', $mLines); + ConsoleCursor::move('↑', $mLines); + } + + ConsoleCursor::save(); + ConsoleCursor::hide(); + ConsoleCursor::move('↓ LEFT'); + ConsoleCursor::clear('↓'); + + foreach ($_solution as $j => $s) { + $output->writeAll("\033[0m".$s."\033[0m"); + + if ($i++ < $mColumns) { + $output->writeAll(' '); + } else { + $i = 0; + + if (isset($_solution[$j + 1])) { + $output->writeAll("\n"); + } + } + } + + ConsoleCursor::restore(); + ConsoleCursor::show(); + + ++$mColumns; + $input = Console::getInput(); + $read = [$input->getStream()->getStream()]; + $write = $except = []; + $mColumn = -1; + $mLine = -1; + $coord = -1; + $unselect = function () use ( + &$mColumn, + &$mLine, + &$coord, + &$_solution, + &$cWidth, + $output + ) { + ConsoleCursor::save(); + ConsoleCursor::hide(); + ConsoleCursor::move('↓ LEFT'); + ConsoleCursor::move('→', $mColumn * ($cWidth + 2)); + ConsoleCursor::move('↓', $mLine); + $output->writeAll("\033[0m".$_solution[$coord]."\033[0m"); + ConsoleCursor::restore(); + ConsoleCursor::show(); + + return; + }; + $select = function () use ( + &$mColumn, + &$mLine, + &$coord, + &$_solution, + &$cWidth, + $output + ) { + ConsoleCursor::save(); + ConsoleCursor::hide(); + ConsoleCursor::move('↓ LEFT'); + ConsoleCursor::move('→', $mColumn * ($cWidth + 2)); + ConsoleCursor::move('↓', $mLine); + $output->writeAll("\033[7m".$_solution[$coord]."\033[0m"); + ConsoleCursor::restore(); + ConsoleCursor::show(); + + return; + }; + $init = function () use ( + &$mColumn, + &$mLine, + &$coord, + &$select + ) { + $mColumn = 0; + $mLine = 0; + $coord = 0; + $select(); + + return; + }; + + while (true) { + @\stream_select($read, $write, $except, 30, 0); + + if (empty($read)) { + $read = [$input->getStream()->getStream()]; + + continue; + } + + switch ($char = $self->_read()) { + case "\033[A": + if (-1 === $mColumn && -1 === $mLine) { + $init(); + + break; + } + + $unselect(); + $coord = \max(0, $coord - $mColumns); + $mLine = (int) \floor($coord / $mColumns); + $mColumn = $coord % $mColumns; + $select(); + + break; + + case "\033[B": + if (-1 === $mColumn && -1 === $mLine) { + $init(); + + break; + } + + $unselect(); + $coord = \min($count, $coord + $mColumns); + $mLine = (int) \floor($coord / $mColumns); + $mColumn = $coord % $mColumns; + $select(); + + break; + + case "\t": + case "\033[C": + if (-1 === $mColumn && -1 === $mLine) { + $init(); + + break; + } + + $unselect(); + $coord = \min($count, $coord + 1); + $mLine = (int) \floor($coord / $mColumns); + $mColumn = $coord % $mColumns; + $select(); + + break; + + case "\033[D": + if (-1 === $mColumn && -1 === $mLine) { + $init(); + + break; + } + + $unselect(); + $coord = \max(0, $coord - 1); + $mLine = (int) \floor($coord / $mColumns); + $mColumn = $coord % $mColumns; + $select(); + + break; + + case "\n": + if (-1 !== $mColumn && -1 !== $mLine) { + $tail = \mb_substr($line, $current); + $current -= $length; + $self->setLine( + \mb_substr($line, 0, $current). + $solution[$coord]. + $tail + ); + $self->setLineCurrent( + $current + \mb_strlen($solution[$coord]) + ); + + ConsoleCursor::move('←', $length); + $output->writeAll($solution[$coord]); + ConsoleCursor::clear('→'); + $output->writeAll($tail); + ConsoleCursor::move('←', \mb_strlen($tail)); + } + + // no break + default: + $mColumn = -1; + $mLine = -1; + $coord = -1; + ConsoleCursor::save(); + ConsoleCursor::move('↓ LEFT'); + ConsoleCursor::clear('↓'); + ConsoleCursor::restore(); + + if ("\033" !== $char && "\n" !== $char) { + $self->setBuffer($char); + + return $self->_readLine($char); + } + + break 2; + } + } + + return $state; + } + + $tail = \mb_substr($line, $current); + $current -= $length; + $self->setLine( + \mb_substr($line, 0, $current). + $solution. + $tail + ); + $self->setLineCurrent( + $current + \mb_strlen($solution) + ); + + ConsoleCursor::move('←', $length); + $output->writeAll($solution); + ConsoleCursor::clear('→'); + $output->writeAll($tail); + ConsoleCursor::move('←', \mb_strlen($tail)); + + return $state; + } +} + +/* + * Advanced interaction. + */ +Console::advancedInteraction(); diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Stream.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Stream.php new file mode 100644 index 0000000..62e56ce --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Stream.php @@ -0,0 +1,571 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Stream. + * + * Static register for all streams (files, sockets etc.). + */ +abstract class Stream implements IStream, EventListenable +{ + use EventListens; + + /** + * Name index in the stream bucket. + */ + const NAME = 0; + + /** + * Handler index in the stream bucket. + */ + const HANDLER = 1; + + /** + * Resource index in the stream bucket. + */ + const RESOURCE = 2; + + /** + * Context index in the stream bucket. + */ + const CONTEXT = 3; + + /** + * Default buffer size. + */ + const DEFAULT_BUFFER_SIZE = 8192; + + /** + * Current stream bucket. + */ + protected $_bucket = []; + + /** + * Static stream register. + */ + private static $_register = []; + + /** + * Buffer size (default is 8Ko). + */ + protected $_bufferSize = self::DEFAULT_BUFFER_SIZE; + + /** + * Original stream name, given to the stream constructor. + */ + protected $_streamName = null; + + /** + * Context name. + */ + protected $_context = null; + + /** + * Whether the opening has been deferred. + */ + protected $_hasBeenDeferred = false; + + /** + * Whether this stream is already opened by another handler. + */ + protected $_borrowing = false; + + /** + * Set the current stream. + * If not exists in the register, try to call the + * `$this->_open()` method. Please, see the `self::_getStream()` method. + */ + public function __construct(string $streamName, string $context = null, bool $wait = false) + { + $this->_streamName = $streamName; + $this->_context = $context; + $this->_hasBeenDeferred = $wait; + $this->setListener( + new EventListener( + $this, + [ + 'authrequire', + 'authresult', + 'complete', + 'connect', + 'failure', + 'mimetype', + 'progress', + 'redirect', + 'resolve', + 'size', + ] + ) + ); + + if (true === $wait) { + return; + } + + $this->open(); + + return; + } + + /** + * Get a stream in the register. + * If the stream does not exist, try to open it by calling the + * $handler->_open() method. + */ + private static function &_getStream( + string $streamName, + self $handler, + string $context = null + ): array { + $name = \md5($streamName); + + if (null !== $context) { + if (false === StreamContext::contextExists($context)) { + throw new StreamException('Context %s was not previously declared, cannot retrieve '.'this context.', 0, $context); + } + + $context = StreamContext::getInstance($context); + } + + if (!isset(self::$_register[$name])) { + self::$_register[$name] = [ + self::NAME => $streamName, + self::HANDLER => $handler, + self::RESOURCE => $handler->_open($streamName, $context), + self::CONTEXT => $context, + ]; + Event::register( + 'hoa://Event/Stream/'.$streamName, + $handler + ); + // Add :open-ready? + Event::register( + 'hoa://Event/Stream/'.$streamName.':close-before', + $handler + ); + } else { + $handler->_borrowing = true; + } + + if (null === self::$_register[$name][self::RESOURCE]) { + self::$_register[$name][self::RESOURCE] + = $handler->_open($streamName, $context); + } + + return self::$_register[$name]; + } + + /** + * Open the stream and return the associated resource. + * Note: This method is protected, but do not forget that it could be + * overloaded into a public context. + */ + abstract protected function &_open(string $streamName, StreamContext $context = null); + + /** + * Close the current stream. + * Note: this method is protected, but do not forget that it could be + * overloaded into a public context. + */ + abstract protected function _close(): bool; + + /** + * Open the stream. + */ + final public function open(): self + { + $context = $this->_context; + + if (true === $this->hasBeenDeferred()) { + if (null === $context) { + $handle = StreamContext::getInstance(\uniqid()); + $handle->setParameters([ + 'notification' => [$this, '_notify'], + ]); + $context = $handle->getId(); + } elseif (true === StreamContext::contextExists($context)) { + $handle = StreamContext::getInstance($context); + $parameters = $handle->getParameters(); + + if (!isset($parameters['notification'])) { + $handle->setParameters([ + 'notification' => [$this, '_notify'], + ]); + } + } + } + + $this->_bufferSize = self::DEFAULT_BUFFER_SIZE; + $this->_bucket = self::_getStream( + $this->_streamName, + $this, + $context + ); + + return $this; + } + + /** + * Close the current stream. + */ + final public function close() + { + $streamName = $this->getStreamName(); + + if (null === $streamName) { + return; + } + + $name = \md5($streamName); + + if (!isset(self::$_register[$name])) { + return; + } + + Event::notify( + 'hoa://Event/Stream/'.$streamName.':close-before', + $this, + new EventBucket() + ); + + if (false === $this->_close()) { + return; + } + + unset(self::$_register[$name]); + $this->_bucket[self::HANDLER] = null; + Event::unregister( + 'hoa://Event/Stream/'.$streamName + ); + Event::unregister( + 'hoa://Event/Stream/'.$streamName.':close-before' + ); + + return; + } + + /** + * Get the current stream name. + */ + public function getStreamName() + { + if (empty($this->_bucket)) { + return null; + } + + return $this->_bucket[self::NAME]; + } + + /** + * Get the current stream. + */ + public function getStream() + { + if (empty($this->_bucket)) { + return null; + } + + return $this->_bucket[self::RESOURCE]; + } + + /** + * Get the current stream context. + */ + public function getStreamContext() + { + if (empty($this->_bucket)) { + return null; + } + + return $this->_bucket[self::CONTEXT]; + } + + /** + * Get stream handler according to its name. + */ + public static function getStreamHandler(string $streamName) + { + $name = \md5($streamName); + + if (!isset(self::$_register[$name])) { + return null; + } + + return self::$_register[$name][self::HANDLER]; + } + + /** + * Set the current stream. Useful to manage a stack of streams (e.g. socket + * and select). Notice that it could be unsafe to use this method without + * taking time to think about it two minutes. Resource of type “Unknown” is + * considered as valid. + */ + public function _setStream($stream) + { + if (false === \is_resource($stream) && + ('resource' !== \gettype($stream) || + 'Unknown' !== \get_resource_type($stream))) { + throw new StreamException('Try to change the stream resource with an invalid one; '.'given %s.', 1, \gettype($stream)); + } + + $old = $this->_bucket[self::RESOURCE]; + $this->_bucket[self::RESOURCE] = $stream; + + return $old; + } + + /** + * Check if the stream is opened. + */ + public function isOpened(): bool + { + return \is_resource($this->getStream()); + } + + /** + * Set the timeout period. + */ + public function setStreamTimeout(int $seconds, int $microseconds = 0): bool + { + return \stream_set_timeout($this->getStream(), $seconds, $microseconds); + } + + /** + * Whether the opening of the stream has been deferred. + */ + protected function hasBeenDeferred() + { + return $this->_hasBeenDeferred; + } + + /** + * Check whether the connection has timed out or not. + * This is basically a shortcut of `getStreamMetaData` + the `timed_out` + * index, but the resulting code is more readable. + */ + public function hasTimedOut(): bool + { + $metaData = $this->getStreamMetaData(); + + return true === $metaData['timed_out']; + } + + /** + * Set blocking/non-blocking mode. + */ + public function setStreamBlocking(bool $mode): bool + { + return \stream_set_blocking($this->getStream(), $mode); + } + + /** + * Set stream buffer. + * Output using fwrite() (or similar function) is normally buffered at 8 Ko. + * This means that if there are two processes wanting to write to the same + * output stream, each is paused after 8 Ko of data to allow the other to + * write. + */ + public function setStreamBuffer(int $buffer): bool + { + // Zero means success. + $out = 0 === \stream_set_write_buffer($this->getStream(), $buffer); + + if (true === $out) { + $this->_bufferSize = $buffer; + } + + return $out; + } + + /** + * Disable stream buffering. + * Alias of $this->setBuffer(0). + */ + public function disableStreamBuffer(): bool + { + return $this->setStreamBuffer(0); + } + + /** + * Get stream buffer size. + */ + public function getStreamBufferSize(): int + { + return $this->_bufferSize; + } + + /** + * Get stream wrapper name. + */ + public function getStreamWrapperName(): string + { + if (false === $pos = \strpos($this->getStreamName(), '://')) { + return 'file'; + } + + return \substr($this->getStreamName(), 0, $pos); + } + + /** + * Get stream meta data. + */ + public function getStreamMetaData(): array + { + return \stream_get_meta_data($this->getStream()); + } + + /** + * Whether this stream is already opened by another handler. + */ + public function isBorrowing(): bool + { + return $this->_borrowing; + } + + /** + * Notification callback. + */ + public function _notify( + int $ncode, + int $severity, + $message, + $code, + $transferred, + $max + ) { + static $_map = [ + \STREAM_NOTIFY_AUTH_REQUIRED => 'authrequire', + \STREAM_NOTIFY_AUTH_RESULT => 'authresult', + \STREAM_NOTIFY_COMPLETED => 'complete', + \STREAM_NOTIFY_CONNECT => 'connect', + \STREAM_NOTIFY_FAILURE => 'failure', + \STREAM_NOTIFY_MIME_TYPE_IS => 'mimetype', + \STREAM_NOTIFY_PROGRESS => 'progress', + \STREAM_NOTIFY_REDIRECTED => 'redirect', + \STREAM_NOTIFY_RESOLVE => 'resolve', + \STREAM_NOTIFY_FILE_SIZE_IS => 'size', + ]; + + $this->getListener()->fire($_map[$ncode], new EventBucket([ + 'code' => $code, + 'severity' => $severity, + 'message' => $message, + 'transferred' => $transferred, + 'max' => $max, + ])); + } + + /** + * Call the $handler->close() method on each stream in the static stream + * register. + * This method does not check the return value of $handler->close(). Thus, + * if a stream is persistent, the $handler->close() should do anything. It + * is a very generic method. + */ + final public static function _Hoa_Stream() + { + foreach (self::$_register as $entry) { + $entry[self::HANDLER]->close(); + } + + return; + } + + /** + * Transform object to string. + */ + public function __toString(): string + { + return $this->getStreamName(); + } + + /** + * Close the stream when destructing. + */ + public function __destruct() + { + if (false === $this->isOpened()) { + return; + } + + $this->close(); + + return; + } +} + +/** + * Class \Hoa\Stream\_Protocol. + * + * The `hoa://Library/Stream` node. + * + * @license New BSD License + */ +class _Protocol extends ProtocolNode +{ + /** + * Component's name. + * + * @var string + */ + protected $_name = 'Stream'; + + /** + * ID of the component. + * + * @param string $id ID of the component + * + * @return mixed + */ + public function reachId(string $id) + { + return Stream::getStreamHandler($id); + } +} + +/* + * Shutdown method. + */ +\register_shutdown_function([Stream::class, '_Hoa_Stream']); + +/** + * Add the `hoa://Library/Stream` node. Should be use to reach/get an entry + * in the stream register. + */ +$protocol = Protocol::getInstance(); +$protocol['Library'][] = new _Protocol(); diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamBufferable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamBufferable.php new file mode 100644 index 0000000..e431021 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamBufferable.php @@ -0,0 +1,73 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Bufferable. + * + * Interface for bufferable streams. It's complementary to native buffer support + * of Hoa\Stream (please, see *StreamBuffer*() methods). Classes implementing + * this interface are able to create nested buffers, flush them etc. + */ +interface StreamBufferable extends IStream +{ + /** + * Start a new buffer. + * The callable acts like a light filter. + */ + public function newBuffer($callable = null, int $size = null): int; + + /** + * Flush the buffer. + */ + public function flush(); + + /** + * Delete buffer. + */ + public function deleteBuffer(): bool; + + /** + * Get bufffer level. + */ + public function getBufferLevel(): int; + + /** + * Get buffer size. + */ + public function getBufferSize(): int; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamContext.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamContext.php new file mode 100644 index 0000000..f7ec2f1 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamContext.php @@ -0,0 +1,141 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Stream\Context. + * + * Make a multiton of stream contexts. + */ +class StreamContext +{ + /** + * Context ID. + */ + protected $_id = null; + + /** + * @var resource + */ + protected $_context; + + /** + * Multiton. + */ + protected static $_instances = []; + + /** + * Construct a context. + */ + protected function __construct($id) + { + $this->_id = $id; + $this->_context = \stream_context_create(); + + return; + } + + /** + * Multiton. + */ + public static function getInstance(string $id): self + { + if (false === static::contextExists($id)) { + static::$_instances[$id] = new self($id); + } + + return static::$_instances[$id]; + } + + /** + * Get context ID. + */ + public function getId(): string + { + return $this->_id; + } + + /** + * Check if a context exists. + */ + public static function contextExists(string $id): bool + { + return \array_key_exists($id, static::$_instances); + } + + /** + * Set options. + * Please, see http://php.net/context. + */ + public function setOptions(array $options): bool + { + return \stream_context_set_option($this->getContext(), $options); + } + + /** + * Set parameters. + * Please, see http://php.net/context.params. + */ + public function setParameters(array $parameters): bool + { + return \stream_context_set_params($this->getContext(), $parameters); + } + + /** + * Get options. + */ + public function getOptions(): array + { + return \stream_context_get_options($this->getContext()); + } + + /** + * Get parameters. + */ + public function getParameters(): array + { + return \stream_context_get_params($this->getContext()); + } + + /** + * Get context as a resource. + */ + public function getContext() + { + return $this->_context; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamException.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamException.php new file mode 100644 index 0000000..21da03c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamException.php @@ -0,0 +1,46 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Class \Hoa\Stream\Exception. + * + * Extending the \Hoa\Exception\Exception class. + */ +class StreamException extends Exception +{ +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamIn.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamIn.php new file mode 100644 index 0000000..1ced913 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamIn.php @@ -0,0 +1,102 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\In. + * + * Interface for input. + */ +interface StreamIn extends IStream +{ + /** + * Test for end-of-stream. + */ + public function eof(): bool; + + /** + * Read n characters. + */ + public function read(int $length); + + /** + * Alias of $this->read(). + */ + public function readString(int $length); + + /** + * Read a character. + * It could be equivalent to $this->read(1). + */ + public function readCharacter(); + + /** + * Read a boolean. + */ + public function readBoolean(); + + /** + * Read an integer. + */ + public function readInteger(int $length = 1); + + /** + * Read a float. + */ + public function readFloat(int $length = 1); + + /** + * Read an array. + * In most cases, it could be an alias to the $this->scanf() method. + */ + public function readArray(); + + /** + * Read a line. + */ + public function readLine(); + + /** + * Read all, i.e. read as much as possible. + */ + public function readAll(int $offset = 0); + + /** + * Parse input from a stream according to a format. + */ + public function scanf(string $format): array; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamLockable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamLockable.php new file mode 100644 index 0000000..c19c4db --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamLockable.php @@ -0,0 +1,85 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Lockable. + * + * Interface for lockable input/output. + * + * @license New BSD License + */ +interface StreamLockable extends IStream +{ + /** + * Acquire a shared lock (reader). + * + * @const int + */ + const LOCK_SHARED = \LOCK_SH; + + /** + * Acquire an exclusive lock (writer). + * + * @const int + */ + const LOCK_EXCLUSIVE = \LOCK_EX; + + /** + * Release a lock (shared or exclusive). + * + * @const int + */ + const LOCK_RELEASE = \LOCK_UN; + + /** + * If we do not want $this->lock() to block while locking. + * + * @const int + */ + const LOCK_NO_BLOCK = \LOCK_NB; + + /** + * Portable advisory locking. + * Should take a look at stream_supports_lock(). + * + * @param int $operation operation, use the self::LOCK_* constants + * + * @return bool + */ + public function lock(int $operation): bool; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamOut.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamOut.php new file mode 100644 index 0000000..e4bb925 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamOut.php @@ -0,0 +1,95 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Out. + * + * Interface for output. + */ +interface StreamOut extends IStream +{ + /** + * Write n characters. + */ + public function write(string $string, int $length); + + /** + * Write a string. + */ + public function writeString(string $string); + + /** + * Write a character. + */ + public function writeCharacter(string $character); + + /** + * Write a boolean. + */ + public function writeBoolean(bool $boolean); + + /** + * Write an integer. + */ + public function writeInteger(int $integer); + + /** + * Write a float. + */ + public function writeFloat(float $float); + + /** + * Write an array. + */ + public function writeArray(array $array); + + /** + * Write a line. + */ + public function writeLine(string $line); + + /** + * Write all, i.e. as much as possible. + */ + public function writeAll(string $string); + + /** + * Truncate a stream to a given length. + */ + public function truncate(int $size): bool; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamPathable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamPathable.php new file mode 100644 index 0000000..558684a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamPathable.php @@ -0,0 +1,55 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Pathable. + * + * Interface for pathable input/output. + */ +interface StreamPathable extends IStream +{ + /** + * Get filename component of path. + */ + public function getBasename(): string; + + /** + * Get directory name component of path. + */ + public function getDirname(): string; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamPointable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamPointable.php new file mode 100644 index 0000000..4030acb --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamPointable.php @@ -0,0 +1,75 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Pointable. + * + * Interface for pointable input/output. + */ +interface StreamPointable extends IStream +{ + /** + * Set position equal to $offset bytes. + */ + const SEEK_SET = \SEEK_SET; + + /** + * Set position to current location plus $offset. + */ + const SEEK_CURRENT = \SEEK_CUR; + + /** + * Set position to end-of-file plus $offset. + */ + const SEEK_END = \SEEK_END; + + /** + * Rewind the position of a stream pointer. + */ + public function rewind(): bool; + + /** + * Seek on a stream pointer. + */ + public function seek(int $offset, int $whence = self::SEEK_SET): int; + + /** + * Get the current position of the stream pointer. + */ + public function tell(): int; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamStatable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamStatable.php new file mode 100644 index 0000000..9b83696 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamStatable.php @@ -0,0 +1,115 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Statable. + * + * Interface for statable input/output. + */ +interface StreamStatable extends IStream +{ + /** + * Size is undefined. + */ + const SIZE_UNDEFINED = -1; + + /** + * Get size. + */ + public function getSize(): int; + + /** + * Get informations about a file. + */ + public function getStatistic(): array; + + /** + * Get last access time of file. + */ + public function getATime(): int; + + /** + * Get inode change time of file. + */ + public function getCTime(): int; + + /** + * Get file modification time. + */ + public function getMTime(): int; + + /** + * Get file group. + */ + public function getGroup(): int; + + /** + * Get file owner. + */ + public function getOwner(): int; + + /** + * Get file permissions. + */ + public function getPermissions(): int; + + /** + * Check if the file is readable. + */ + public function isReadable(): bool; + + /** + * Check if the file is writable. + */ + public function isWritable(): bool; + + /** + * Check if the file is executable. + */ + public function isExecutable(): bool; + + /** + * Clear file status cache. + */ + public function clearStatisticCache(); + + /** + * Clear all files status cache. + */ + public static function clearAllStatisticCaches(); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamTouchable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamTouchable.php new file mode 100644 index 0000000..08b7525 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/StreamTouchable.php @@ -0,0 +1,110 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Interface \Hoa\Stream\IStream\Touchable. + * + * Interface for touchable input/output. + */ +interface StreamTouchable extends IStream +{ + /** + * Overwrite file if already exists. + */ + const OVERWRITE = true; + + /** + * Do not overwrite file if already exists. + */ + const DO_NOT_OVERWRITE = false; + + /** + * Make directory if does not exist. + */ + const MAKE_DIRECTORY = true; + + /** + * Do not make directory if does not exist. + */ + const DO_NOT_MAKE_DIRECTORY = false; + + /** + * Set access and modification time of file. + */ + public function touch(int $time = -1, int $atime = -1): bool; + + /** + * Copy file. + * Return the destination file path if succeed, false otherwise. + */ + public function copy(string $to, bool $force = self::DO_NOT_OVERWRITE): bool; + + /** + * Move a file. + */ + public function move( + string $name, + bool $force = self::DO_NOT_OVERWRITE, + bool $mkdir = self::DO_NOT_MAKE_DIRECTORY + ): bool; + + /** + * Delete a file. + */ + public function delete(): bool; + + /** + * Change file group. + */ + public function changeGroup($group): bool; + + /** + * Change file mode. + */ + public function changeMode(int $mode): bool; + + /** + * Change file owner. + */ + public function changeOwner($user): bool; + + /** + * Change the current umask. + */ + public static function umask(int $umask = null): int; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/77/windows-ansi b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/77/windows-ansi new file mode 100644 index 0000000..5086423 Binary files /dev/null and b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/77/windows-ansi differ diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/78/xterm b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/78/xterm new file mode 100644 index 0000000..fec988d Binary files /dev/null and b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/78/xterm differ diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/78/xterm-256color b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/78/xterm-256color new file mode 100644 index 0000000..d3be7ef Binary files /dev/null and b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Terminfo/78/xterm-256color differ diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Ustring.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Ustring.php new file mode 100644 index 0000000..8d7312b --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Ustring.php @@ -0,0 +1,143 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * This class represents a UTF-8 string. + * Please, see: + * * http://www.ietf.org/rfc/rfc3454.txt, + * * http://unicode.org/reports/tr9/, + * * http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt. + */ +class Ustring +{ + /** + * Check if ext/mbstring is available. + */ + public static function checkMbString(): bool + { + return \function_exists('mb_substr'); + } + + /** + * Get the number of column positions of a wide-character. + * + * This is a PHP implementation of wcwidth() and wcswidth() (defined in IEEE + * Std 1002.1-2001) for Unicode, by Markus Kuhn. Please, see + * http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c. + * + * The wcwidth(wc) function shall either return 0 (if wc is a null + * wide-character code), or return the number of column positions to be + * occupied by the wide-character code wc, or return -1 (if wc does not + * correspond to a printable wide-character code). + */ + public static function getCharWidth(string $char): int + { + $char = (string) $char; + $c = static::toCode($char); + + // Test for 8-bit control characters. + if (0x0 === $c) { + return 0; + } + + if (0x20 > $c || (0x7F <= $c && $c < 0xA0)) { + return -1; + } + + // Non-spacing characters. + if (0xAD !== $c && + 0 !== \preg_match('#^[\p{Mn}\p{Me}\p{Cf}\x{1160}-\x{11ff}\x{200b}]#u', $char)) { + return 0; + } + + // If we arrive here, $c is not a combining C0/C1 control character. + return 1 + + (0x1100 <= $c && + (0x115F >= $c || // Hangul Jamo init. consonants + 0x2329 === $c || 0x232A === $c || + (0x2E80 <= $c && 0xA4CF >= $c && + 0x303F !== $c) || // CJK…Yi + (0xAC00 <= $c && 0xD7A3 >= $c) || // Hangul Syllables + (0xF900 <= $c && 0xFAFF >= $c) || // CJK Compatibility Ideographs + (0xFE10 <= $c && 0xFE19 >= $c) || // Vertical forms + (0xFE30 <= $c && 0xFE6F >= $c) || // CJK Compatibility Forms + (0xFF00 <= $c && 0xFF60 >= $c) || // Fullwidth Forms + (0xFFE0 <= $c && 0xFFE6 >= $c) || + (0x20000 <= $c && 0x2FFFD >= $c) || + (0x30000 <= $c && 0x3FFFD >= $c))); + } + + /** + * Check whether the character is printable or not. + */ + public static function isCharPrintable(string $char): bool + { + return 1 <= static::getCharWidth($char); + } + + /** + * Get a decimal code representation of a specific character. + */ + public static function toCode(string $char): int + { + $char = (string) $char; + $code = \ord($char[0]); + $bytes = 1; + + if (!($code & 0x80)) { // 0xxxxxxx + return $code; + } + + if (($code & 0xE0) === 0xC0) { // 110xxxxx + $bytes = 2; + $code = $code & ~0xC0; + } elseif (($code & 0xF0) === 0xE0) { // 1110xxxx + $bytes = 3; + $code = $code & ~0xE0; + } elseif (($code & 0xF8) === 0xF0) { // 11110xxx + $bytes = 4; + $code = $code & ~0xF0; + } + + for ($i = 2; $i <= $bytes; $i++) { // 10xxxxxx + $code = ($code << 6) + (\ord($char[$i - 1]) & ~0x80); + } + + return $code; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Xcallable.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Xcallable.php new file mode 100644 index 0000000..e1160a5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Hoa/Xcallable.php @@ -0,0 +1,256 @@ +<?php + +/** + * Hoa + * + * + * @license + * + * New BSD License + * + * Copyright © 2007-2017, Hoa community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Hoa 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 HOLDERS AND 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. + */ + +namespace Psy\Readline\Hoa; + +/** + * Build a callable object, i.e. `function`, `class::method`, `object->method` or + * closure. They all have the same behaviour. This callable is an extension of + * native PHP callable (aka callback) to integrate Hoa's structures. + */ +class Xcallable +{ + /** + * Callback with the PHP format. + */ + protected $_callback = null; + + /** + * Callable hash. + */ + protected $_hash = null; + + /** + * Allocates a xcallable based on a callback. + * + * Accepted forms: + * * `'function'`, + * * `'class::method'`, + * * `'class', 'method'`, + * * `$object, 'method'`, + * * `$object, ''`, + * * `function (…) { … }`, + * * `['class', 'method']`, + * * `[$object, 'method']`. + * + * # Examples + * + * ```php + * $toUpper = new Hoa\Consistency\Xcallable('strtoupper'); + * assert('FOO' === $toUpper('foo')); + * ``` + * + * # Exceptions + * + * A `Hoa\Consistency\Exception` exception is thrown if the callback form + * is invalid. + * + * ```php,must_throw(Hoa\Consistency\Exception) + * new Hoa\Consistency\Xcallable('Foo:'); + * ``` + */ + public function __construct($call, $able = '') + { + if ($call instanceof \Closure) { + $this->_callback = $call; + + return; + } + + if (!\is_string($able)) { + throw new Exception('Bad callback form; the able part must be a string.', 0); + } + + if ('' === $able) { + if (\is_string($call)) { + if (false === \strpos($call, '::')) { + if (!\function_exists($call)) { + throw new Exception('Bad callback form; function %s does not exist.', 1, $call); + } + + $this->_callback = $call; + + return; + } + + list($call, $able) = \explode('::', $call); + } elseif (\is_object($call)) { + if ($call instanceof StreamOut) { + $able = null; + } elseif (\method_exists($call, '__invoke')) { + $able = '__invoke'; + } else { + throw new Exception('Bad callback form; an object but without a known '.'method.', 2); + } + } elseif (\is_array($call) && isset($call[0])) { + if (!isset($call[1])) { + $this->__construct($call[0]); + return; + } + + $this->__construct($call[0], $call[1]); + return; + } else { + throw new Exception('Bad callback form.', 3); + } + } + + $this->_callback = [$call, $able]; + + return; + } + + /** + * Calls the callable. + */ + public function __invoke(...$arguments) + { + $callback = $this->getValidCallback($arguments); + + return $callback(...$arguments); + } + + /** + * Returns a valid PHP callback. + */ + public function getValidCallback(array &$arguments = []) + { + $callback = $this->_callback; + $head = null; + + if (isset($arguments[0])) { + $head = &$arguments[0]; + } + + // If method is undetermined, we find it (we understand event bucket and + // stream). + if (null !== $head && + \is_array($callback) && + null === $callback[1]) { + if ($head instanceof EventBucket) { + $head = $head->getData(); + } + + switch ($type = \gettype($head)) { + case 'string': + if (1 === \strlen($head)) { + $method = 'writeCharacter'; + } else { + $method = 'writeString'; + } + + break; + + case 'boolean': + case 'integer': + case 'array': + $method = 'write'.\ucfirst($type); + + break; + + case 'double': + $method = 'writeFloat'; + + break; + + default: + $method = 'writeAll'; + $head = $head."\n"; + } + + $callback[1] = $method; + } + + return $callback; + } + + /** + * Computes the hash of this callable. + * + * Will produce: + * * `function#…`, + * * `class#…::…`, + * * `object(…)#…::…`, + * * `closure(…)`. + */ + public function getHash(): string + { + if (null !== $this->_hash) { + return $this->_hash; + } + + $_ = &$this->_callback; + + if (\is_string($_)) { + return $this->_hash = 'function#'.$_; + } + + if (\is_array($_)) { + return + $this->_hash = + (\is_object($_[0]) + ? 'object('.\spl_object_hash($_[0]).')'. + '#'.\get_class($_[0]) + : 'class#'.$_[0]). + '::'. + (null !== $_[1] + ? $_[1] + : '???'); + } + + return $this->_hash = 'closure('.\spl_object_hash($_).')'; + } + + /** + * The string representation of a callable is its hash. + */ + public function __toString(): string + { + return $this->getHash(); + } + + /** + * Hoa's xcallable() helper. + */ + public static function from($call, $able = '') + { + if ($call instanceof self) { + return $call; + } + + return new self($call, $able); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Libedit.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Libedit.php new file mode 100644 index 0000000..953ed2a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Libedit.php @@ -0,0 +1,116 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Readline; + +use Psy\Util\Str; + +/** + * A Libedit-based Readline implementation. + * + * This is largely the same as the Readline implementation, but it emulates + * support for `readline_list_history` since PHP decided it was a good idea to + * ship a fake Readline implementation that is missing history support. + * + * NOTE: As of PHP 7.4, PHP sometimes has history support in the Libedit + * wrapper, so it will use the GNUReadline implementation rather than this one. + */ +class Libedit extends GNUReadline +{ + private $hasWarnedOwnership = false; + + /** + * Let's emulate GNU Readline by manually reading and parsing the history file! + */ + public static function isSupported(): bool + { + return \function_exists('readline') && !\function_exists('readline_list_history'); + } + + /** + * {@inheritdoc} + */ + public static function supportsBracketedPaste(): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function listHistory(): array + { + $history = \file_get_contents($this->historyFile); + if (!$history) { + return []; + } + + // libedit doesn't seem to support non-unix line separators. + $history = \explode("\n", $history); + + // remove history signature if it exists + if ($history[0] === '_HiStOrY_V2_') { + \array_shift($history); + } + + // decode the line + $history = \array_map([$this, 'parseHistoryLine'], $history); + // filter empty lines & comments + return \array_values(\array_filter($history)); + } + + /** + * {@inheritdoc} + */ + public function writeHistory(): bool + { + $res = parent::writeHistory(); + + // Libedit apparently refuses to save history if the history file is not + // owned by the user, even if it is writable. Warn when this happens. + // + // See https://github.com/bobthecow/psysh/issues/552 + if ($res === false && !$this->hasWarnedOwnership) { + if (\is_file($this->historyFile) && \is_writable($this->historyFile)) { + $this->hasWarnedOwnership = true; + $msg = \sprintf('Error writing history file, check file ownership: %s', $this->historyFile); + \trigger_error($msg, \E_USER_NOTICE); + } + } + + return $res; + } + + /** + * From GNUReadline (readline/histfile.c & readline/histexpand.c): + * lines starting with "\0" are comments or timestamps; + * if "\0" is found in an entry, + * everything from it until the next line is a comment. + * + * @param string $line The history line to parse + * + * @return string|null + */ + protected function parseHistoryLine(string $line) + { + // empty line, comment or timestamp + if (!$line || $line[0] === "\0") { + return; + } + // if "\0" is found in an entry, then + // everything from it until the end of line is a comment. + if (($pos = \strpos($line, "\0")) !== false) { + $line = \substr($line, 0, $pos); + } + + return ($line !== '') ? Str::unvis($line) : null; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Readline.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Readline.php new file mode 100644 index 0000000..e9b45b3 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Readline.php @@ -0,0 +1,86 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Readline; + +/** + * An interface abstracting the various readline_* functions. + */ +interface Readline +{ + /** + * @param string|false $historyFile + * @param int|null $historySize + * @param bool|null $eraseDups + */ + public function __construct($historyFile = null, $historySize = 0, $eraseDups = false); + + /** + * Check whether this Readline class is supported by the current system. + */ + public static function isSupported(): bool; + + /** + * Check whether this Readline class supports bracketed paste. + */ + public static function supportsBracketedPaste(): bool; + + /** + * Add a line to the command history. + * + * @param string $line + * + * @return bool Success + */ + public function addHistory(string $line): bool; + + /** + * Clear the command history. + * + * @return bool Success + */ + public function clearHistory(): bool; + + /** + * List the command history. + * + * @return string[] + */ + public function listHistory(): array; + + /** + * Read the command history. + * + * @return bool Success + */ + public function readHistory(): bool; + + /** + * Read a single line of input from the user. + * + * @param string|null $prompt + * + * @return false|string + */ + public function readline(string $prompt = null); + + /** + * Redraw readline to redraw the display. + */ + public function redisplay(); + + /** + * Write the command history to a file. + * + * @return bool Success + */ + public function writeHistory(): bool; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Transient.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Transient.php new file mode 100644 index 0000000..43eb285 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Transient.php @@ -0,0 +1,155 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Readline; + +use Psy\Exception\BreakException; + +/** + * An array-based Readline emulation implementation. + */ +class Transient implements Readline +{ + private $history; + private $historySize; + private $eraseDups; + private $stdin; + + /** + * Transient Readline is always supported. + * + * {@inheritdoc} + */ + public static function isSupported(): bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public static function supportsBracketedPaste(): bool + { + return false; + } + + /** + * Transient Readline constructor. + */ + public function __construct($historyFile = null, $historySize = 0, $eraseDups = false) + { + // don't do anything with the history file... + $this->history = []; + $this->historySize = $historySize; + $this->eraseDups = $eraseDups; + } + + /** + * {@inheritdoc} + */ + public function addHistory(string $line): bool + { + if ($this->eraseDups) { + if (($key = \array_search($line, $this->history)) !== false) { + unset($this->history[$key]); + } + } + + $this->history[] = $line; + + if ($this->historySize > 0) { + $histsize = \count($this->history); + if ($histsize > $this->historySize) { + $this->history = \array_slice($this->history, $histsize - $this->historySize); + } + } + + $this->history = \array_values($this->history); + + return true; + } + + /** + * {@inheritdoc} + */ + public function clearHistory(): bool + { + $this->history = []; + + return true; + } + + /** + * {@inheritdoc} + */ + public function listHistory(): array + { + return $this->history; + } + + /** + * {@inheritdoc} + */ + public function readHistory(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * @throws BreakException if user hits Ctrl+D + * + * @return false|string + */ + public function readline(string $prompt = null) + { + echo $prompt; + + return \rtrim(\fgets($this->getStdin()), "\n\r"); + } + + /** + * {@inheritdoc} + */ + public function redisplay() + { + // noop + } + + /** + * {@inheritdoc} + */ + public function writeHistory(): bool + { + return true; + } + + /** + * Get a STDIN file handle. + * + * @throws BreakException if user hits Ctrl+D + * + * @return resource + */ + private function getStdin() + { + if (!isset($this->stdin)) { + $this->stdin = \fopen('php://stdin', 'r'); + } + + if (\feof($this->stdin)) { + throw new BreakException('Ctrl+D'); + } + + return $this->stdin; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Readline/Userland.php b/php/libraries/composer/vendor/psy/psysh/src/Readline/Userland.php new file mode 100644 index 0000000..62018b7 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Readline/Userland.php @@ -0,0 +1,165 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Readline; + +use Psy\Exception\BreakException; +use Psy\Readline\Hoa\Console as HoaConsole; +use Psy\Readline\Hoa\ConsoleCursor as HoaConsoleCursor; +use Psy\Readline\Hoa\ConsoleInput as HoaConsoleInput; +use Psy\Readline\Hoa\ConsoleOutput as HoaConsoleOutput; +use Psy\Readline\Hoa\ConsoleTput as HoaConsoleTput; +use Psy\Readline\Hoa\Readline as HoaReadline; +use Psy\Readline\Hoa\Ustring as HoaUstring; + +/** + * Userland Readline implementation. + */ +class Userland implements Readline +{ + /** @var HoaReadline */ + private $hoaReadline; + + /** @var string|null */ + private $lastPrompt; + + private $tput; + private $input; + private $output; + + public static function isSupported(): bool + { + static::bootstrapHoa(); + + return HoaUstring::checkMbString() && HoaConsoleTput::isSupported(); + } + + /** + * {@inheritdoc} + */ + public static function supportsBracketedPaste(): bool + { + return false; + } + + /** + * Doesn't (currently) support history file, size or erase dupes configs. + */ + public function __construct($historyFile = null, $historySize = 0, $eraseDups = false) + { + static::bootstrapHoa(true); + + $this->hoaReadline = new HoaReadline(); + $this->hoaReadline->addMapping('\C-l', function () { + $this->redisplay(); + + return HoaReadline::STATE_NO_ECHO; + }); + + $this->tput = new HoaConsoleTput(); + HoaConsole::setTput($this->tput); + + $this->input = new HoaConsoleInput(); + HoaConsole::setInput($this->input); + + $this->output = new HoaConsoleOutput(); + HoaConsole::setOutput($this->output); + } + + /** + * Bootstrap some things that Hoa used to do itself. + */ + public static function bootstrapHoa(bool $withTerminalResize = false) + { + // A side effect registers hoa:// stream wrapper + \class_exists('Psy\Readline\Hoa\ProtocolWrapper'); + + // A side effect registers hoa://Library/Stream + \class_exists('Psy\Readline\Hoa\Stream'); + + // A side effect binds terminal resize + $withTerminalResize && \class_exists('Psy\Readline\Hoa\ConsoleWindow'); + } + + /** + * {@inheritdoc} + */ + public function addHistory(string $line): bool + { + $this->hoaReadline->addHistory($line); + + return true; + } + + /** + * {@inheritdoc} + */ + public function clearHistory(): bool + { + $this->hoaReadline->clearHistory(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function listHistory(): array + { + $i = 0; + $list = []; + while (($item = $this->hoaReadline->getHistory($i++)) !== null) { + $list[] = $item; + } + + return $list; + } + + /** + * {@inheritdoc} + */ + public function readHistory(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * @throws BreakException if user hits Ctrl+D + * + * @return string + */ + public function readline(string $prompt = null) + { + $this->lastPrompt = $prompt; + + return $this->hoaReadline->readLine($prompt); + } + + /** + * {@inheritdoc} + */ + public function redisplay() + { + $currentLine = $this->hoaReadline->getLine(); + HoaConsoleCursor::clear('all'); + echo $this->lastPrompt, $currentLine; + } + + /** + * {@inheritdoc} + */ + public function writeHistory(): bool + { + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionConstant.php b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionConstant.php new file mode 100644 index 0000000..763011f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionConstant.php @@ -0,0 +1,170 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Reflection; + +/** + * Somehow the standard reflection library doesn't include constants. + * + * ReflectionConstant corrects that omission. + */ +class ReflectionConstant implements \Reflector +{ + public $name; + private $value; + + private static $magicConstants = [ + '__LINE__', + '__FILE__', + '__DIR__', + '__FUNCTION__', + '__CLASS__', + '__TRAIT__', + '__METHOD__', + '__NAMESPACE__', + '__COMPILER_HALT_OFFSET__', + ]; + + /** + * Construct a ReflectionConstant object. + * + * @param string $name + */ + public function __construct(string $name) + { + $this->name = $name; + + if (!\defined($name) && !self::isMagicConstant($name)) { + throw new \InvalidArgumentException('Unknown constant: '.$name); + } + + if (!self::isMagicConstant($name)) { + $this->value = @\constant($name); + } + } + + /** + * Exports a reflection. + * + * @param string $name + * @param bool $return pass true to return the export, as opposed to emitting it + * + * @return string|null + */ + public static function export(string $name, bool $return = false) + { + $refl = new self($name); + $value = $refl->getValue(); + + $str = \sprintf('Constant [ %s %s ] { %s }', \gettype($value), $refl->getName(), $value); + + if ($return) { + return $str; + } + + echo $str."\n"; + } + + public static function isMagicConstant($name) + { + return \in_array($name, self::$magicConstants); + } + + /** + * Get the constant's docblock. + * + * @return false + */ + public function getDocComment(): bool + { + return false; + } + + /** + * Gets the constant name. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Gets the namespace name. + * + * Returns '' when the constant is not namespaced. + */ + public function getNamespaceName(): string + { + if (!$this->inNamespace()) { + return ''; + } + + return \preg_replace('/\\\\[^\\\\]+$/', '', $this->name); + } + + /** + * Gets the value of the constant. + * + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * Checks if this constant is defined in a namespace. + */ + public function inNamespace(): bool + { + return \strpos($this->name, '\\') !== false; + } + + /** + * To string. + */ + public function __toString(): string + { + return $this->getName(); + } + + /** + * Gets the constant's file name. + * + * Currently returns null, because if it returns a file name the signature + * formatter will barf. + */ + public function getFileName() + { + return; + // return $this->class->getFileName(); + } + + /** + * Get the code start line. + * + * @throws \RuntimeException + */ + public function getStartLine() + { + throw new \RuntimeException('Not yet implemented because it\'s unclear what I should do here :)'); + } + + /** + * Get the code end line. + * + * @throws \RuntimeException + */ + public function getEndLine() + { + return $this->getStartLine(); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionLanguageConstruct.php b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionLanguageConstruct.php new file mode 100644 index 0000000..8902214 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionLanguageConstruct.php @@ -0,0 +1,159 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Reflection; + +/** + * A fake ReflectionFunction but for language constructs. + */ +class ReflectionLanguageConstruct extends \ReflectionFunctionAbstract +{ + public $keyword; + + /** + * Language construct parameter definitions. + */ + private static $languageConstructs = [ + 'isset' => [ + 'var' => [], + '...' => [ + 'isOptional' => true, + 'defaultValue' => null, + ], + ], + + 'unset' => [ + 'var' => [], + '...' => [ + 'isOptional' => true, + 'defaultValue' => null, + ], + ], + + 'empty' => [ + 'var' => [], + ], + + 'echo' => [ + 'arg1' => [], + '...' => [ + 'isOptional' => true, + 'defaultValue' => null, + ], + ], + + 'print' => [ + 'arg' => [], + ], + + 'die' => [ + 'status' => [ + 'isOptional' => true, + 'defaultValue' => 0, + ], + ], + + 'exit' => [ + 'status' => [ + 'isOptional' => true, + 'defaultValue' => 0, + ], + ], + ]; + + /** + * Construct a ReflectionLanguageConstruct object. + * + * @param string $keyword + */ + public function __construct(string $keyword) + { + if (!self::isLanguageConstruct($keyword)) { + throw new \InvalidArgumentException('Unknown language construct: '.$keyword); + } + + $this->keyword = $keyword; + } + + /** + * This can't (and shouldn't) do anything :). + * + * @throws \RuntimeException + */ + public static function export($name) + { + throw new \RuntimeException('Not yet implemented because it\'s unclear what I should do here :)'); + } + + /** + * Get language construct name. + */ + public function getName(): string + { + return $this->keyword; + } + + /** + * None of these return references. + */ + public function returnsReference(): bool + { + return false; + } + + /** + * Get language construct params. + * + * @return array + */ + public function getParameters(): array + { + $params = []; + foreach (self::$languageConstructs[$this->keyword] as $parameter => $opts) { + $params[] = new ReflectionLanguageConstructParameter($this->keyword, $parameter, $opts); + } + + return $params; + } + + /** + * Gets the file name from a language construct. + * + * (Hint: it always returns false) + * + * @todo remove \ReturnTypeWillChange attribute after dropping support for PHP 7.x (when we can use union types) + * + * @return string|false (false) + */ + #[\ReturnTypeWillChange] + public function getFileName() + { + return false; + } + + /** + * To string. + */ + public function __toString(): string + { + return $this->getName(); + } + + /** + * Check whether keyword is a (known) language construct. + * + * @param string $keyword + */ + public static function isLanguageConstruct(string $keyword): bool + { + return \array_key_exists($keyword, self::$languageConstructs); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionLanguageConstructParameter.php b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionLanguageConstructParameter.php new file mode 100644 index 0000000..756dfd8 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionLanguageConstructParameter.php @@ -0,0 +1,108 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Reflection; + +/** + * A fake ReflectionParameter but for language construct parameters. + * + * It stubs out all the important bits and returns whatever was passed in $opts. + */ +class ReflectionLanguageConstructParameter extends \ReflectionParameter +{ + private $function; + private $parameter; + private $opts; + + public function __construct($function, $parameter, array $opts) + { + $this->function = $function; + $this->parameter = $parameter; + $this->opts = $opts; + } + + /** + * No class here. + */ + public function getClass(): ?\ReflectionClass + { + return null; + } + + /** + * Is the param an array? + * + * @return bool + */ + public function isArray(): bool + { + return \array_key_exists('isArray', $this->opts) && $this->opts['isArray']; + } + + /** + * Get param default value. + * + * @todo remove \ReturnTypeWillChange attribute after dropping support for PHP 7.x (when we can use mixed type) + * + * @return mixed + */ + #[\ReturnTypeWillChange] + public function getDefaultValue() + { + if ($this->isDefaultValueAvailable()) { + return $this->opts['defaultValue']; + } + + return null; + } + + /** + * Get param name. + * + * @return string + */ + public function getName(): string + { + return $this->parameter; + } + + /** + * Is the param optional? + * + * @return bool + */ + public function isOptional(): bool + { + return \array_key_exists('isOptional', $this->opts) && $this->opts['isOptional']; + } + + /** + * Does the param have a default value? + * + * @return bool + */ + public function isDefaultValueAvailable(): bool + { + return \array_key_exists('defaultValue', $this->opts); + } + + /** + * Is the param passed by reference? + * + * (I don't think this is true for anything we need to fake a param for) + * + * @return bool + */ + public function isPassedByReference(): bool + { + return \array_key_exists('isPassedByReference', $this->opts) && $this->opts['isPassedByReference']; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionNamespace.php b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionNamespace.php new file mode 100644 index 0000000..3c8b330 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Reflection/ReflectionNamespace.php @@ -0,0 +1,60 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Reflection; + +/** + * A fake Reflector for namespaces. + */ +class ReflectionNamespace implements \Reflector +{ + private $name; + + /** + * Construct a ReflectionNamespace object. + * + * @param string $name + */ + public function __construct(string $name) + { + $this->name = $name; + } + + /** + * Gets the constant name. + * + * @return string + */ + public function getName(): string + { + return $this->name; + } + + /** + * This can't (and shouldn't) do anything :). + * + * @throws \RuntimeException + */ + public static function export($name) + { + throw new \RuntimeException('Not yet implemented because it\'s unclear what I should do here :)'); + } + + /** + * To string. + * + * @return string + */ + public function __toString(): string + { + return $this->getName(); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Shell.php b/php/libraries/composer/vendor/psy/psysh/src/Shell.php new file mode 100644 index 0000000..104699c --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Shell.php @@ -0,0 +1,1617 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +use Psy\CodeCleaner\NoReturnValue; +use Psy\Exception\BreakException; +use Psy\Exception\ErrorException; +use Psy\Exception\Exception as PsyException; +use Psy\Exception\RuntimeException; +use Psy\Exception\ThrowUpException; +use Psy\ExecutionLoop\ProcessForker; +use Psy\ExecutionLoop\RunkitReloader; +use Psy\Formatter\TraceFormatter; +use Psy\Input\ShellInput; +use Psy\Input\SilentInput; +use Psy\Output\ShellOutput; +use Psy\TabCompletion\Matcher; +use Psy\VarDumper\PresenterAware; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command as BaseCommand; +use Symfony\Component\Console\Exception\ExceptionInterface as SymfonyConsoleException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Input\StringInput; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * The Psy Shell application. + * + * Usage: + * + * $shell = new Shell; + * $shell->run(); + * + * @author Justin Hileman <justin@justinhileman.info> + */ +class Shell extends Application +{ + const VERSION = 'v0.12.0'; + + private $config; + private $cleaner; + private $output; + private $originalVerbosity; + private $readline; + private $inputBuffer; + private $code; + private $codeBuffer; + private $codeBufferOpen; + private $codeStack; + private $stdoutBuffer; + private $context; + private $includes; + private $outputWantsNewline = false; + private $loopListeners; + private $autoCompleter; + private $matchers = []; + private $commandsMatcher; + private $lastExecSuccess = true; + private $nonInteractive = false; + private $errorReporting; + + /** + * Create a new Psy Shell. + * + * @param Configuration|null $config (default: null) + */ + public function __construct(Configuration $config = null) + { + $this->config = $config ?: new Configuration(); + $this->cleaner = $this->config->getCodeCleaner(); + $this->context = new Context(); + $this->includes = []; + $this->readline = $this->config->getReadline(); + $this->inputBuffer = []; + $this->codeStack = []; + $this->stdoutBuffer = ''; + $this->loopListeners = $this->getDefaultLoopListeners(); + + parent::__construct('Psy Shell', self::VERSION); + + $this->config->setShell($this); + + // Register the current shell session's config with \Psy\info + \Psy\info($this->config); + } + + /** + * Check whether the first thing in a backtrace is an include call. + * + * This is used by the psysh bin to decide whether to start a shell on boot, + * or to simply autoload the library. + */ + public static function isIncluded(array $trace): bool + { + $isIncluded = isset($trace[0]['function']) && + \in_array($trace[0]['function'], ['require', 'include', 'require_once', 'include_once']); + + // Detect Composer PHP bin proxies. + if ($isIncluded && \array_key_exists('_composer_autoload_path', $GLOBALS) && \preg_match('{[\\\\/]psysh$}', $trace[0]['file'])) { + // If we're in a bin proxy, we'll *always* see one include, but we + // care if we see a second immediately after that. + return isset($trace[1]['function']) && + \in_array($trace[1]['function'], ['require', 'include', 'require_once', 'include_once']); + } + + return $isIncluded; + } + + /** + * Check if the currently running PsySH bin is a phar archive. + */ + public static function isPhar(): bool + { + return \class_exists("\Phar") && \Phar::running() !== '' && \strpos(__FILE__, \Phar::running(true)) === 0; + } + + /** + * Invoke a Psy Shell from the current context. + * + * @see Psy\debug + * @deprecated will be removed in 1.0. Use \Psy\debug instead + * + * @param array $vars Scope variables from the calling context (default: []) + * @param object|string $bindTo Bound object ($this) or class (self) value for the shell + * + * @return array Scope variables from the debugger session + */ + public static function debug(array $vars = [], $bindTo = null): array + { + @\trigger_error('`Psy\\Shell::debug` is deprecated; call `Psy\\debug` instead.', \E_USER_DEPRECATED); + + return \Psy\debug($vars, $bindTo); + } + + /** + * Adds a command object. + * + * {@inheritdoc} + * + * @param BaseCommand $command A Symfony Console Command object + * + * @return BaseCommand The registered command + */ + public function add(BaseCommand $command): BaseCommand + { + if ($ret = parent::add($command)) { + if ($ret instanceof ContextAware) { + $ret->setContext($this->context); + } + + if ($ret instanceof PresenterAware) { + $ret->setPresenter($this->config->getPresenter()); + } + + if (isset($this->commandsMatcher)) { + $this->commandsMatcher->setCommands($this->all()); + } + } + + return $ret; + } + + /** + * Gets the default input definition. + * + * @return InputDefinition An InputDefinition instance + */ + protected function getDefaultInputDefinition(): InputDefinition + { + return new InputDefinition([ + new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), + new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'), + ]); + } + + /** + * Gets the default commands that should always be available. + * + * @return array An array of default Command instances + */ + protected function getDefaultCommands(): array + { + $sudo = new Command\SudoCommand(); + $sudo->setReadline($this->readline); + + $hist = new Command\HistoryCommand(); + $hist->setReadline($this->readline); + + return [ + new Command\HelpCommand(), + new Command\ListCommand(), + new Command\DumpCommand(), + new Command\DocCommand(), + new Command\ShowCommand(), + new Command\WtfCommand(), + new Command\WhereamiCommand(), + new Command\ThrowUpCommand(), + new Command\TimeitCommand(), + new Command\TraceCommand(), + new Command\BufferCommand(), + new Command\ClearCommand(), + new Command\EditCommand($this->config->getRuntimeDir()), + // new Command\PsyVersionCommand(), + $sudo, + $hist, + new Command\ExitCommand(), + ]; + } + + /** + * @return Matcher\AbstractMatcher[] + */ + protected function getDefaultMatchers(): array + { + // Store the Commands Matcher for later. If more commands are added, + // we'll update the Commands Matcher too. + $this->commandsMatcher = new Matcher\CommandsMatcher($this->all()); + + return [ + $this->commandsMatcher, + new Matcher\KeywordsMatcher(), + new Matcher\VariablesMatcher(), + new Matcher\ConstantsMatcher(), + new Matcher\FunctionsMatcher(), + new Matcher\ClassNamesMatcher(), + new Matcher\ClassMethodsMatcher(), + new Matcher\ClassAttributesMatcher(), + new Matcher\ObjectMethodsMatcher(), + new Matcher\ObjectAttributesMatcher(), + new Matcher\ClassMethodDefaultParametersMatcher(), + new Matcher\ObjectMethodDefaultParametersMatcher(), + new Matcher\FunctionDefaultParametersMatcher(), + ]; + } + + /** + * Gets the default command loop listeners. + * + * @return array An array of Execution Loop Listener instances + */ + protected function getDefaultLoopListeners(): array + { + $listeners = []; + + if (ProcessForker::isSupported() && $this->config->usePcntl()) { + $listeners[] = new ProcessForker(); + } + + if (RunkitReloader::isSupported()) { + $listeners[] = new RunkitReloader(); + } + + return $listeners; + } + + /** + * Add tab completion matchers. + * + * @param array $matchers + */ + public function addMatchers(array $matchers) + { + $this->matchers = \array_merge($this->matchers, $matchers); + + if (isset($this->autoCompleter)) { + $this->addMatchersToAutoCompleter($matchers); + } + } + + /** + * @deprecated Call `addMatchers` instead + * + * @param array $matchers + */ + public function addTabCompletionMatchers(array $matchers) + { + @\trigger_error('`addTabCompletionMatchers` is deprecated; call `addMatchers` instead.', \E_USER_DEPRECATED); + + $this->addMatchers($matchers); + } + + /** + * Set the Shell output. + * + * @param OutputInterface $output + */ + public function setOutput(OutputInterface $output) + { + $this->output = $output; + $this->originalVerbosity = $output->getVerbosity(); + } + + /** + * Runs PsySH. + * + * @param InputInterface|null $input An Input instance + * @param OutputInterface|null $output An Output instance + * + * @return int 0 if everything went fine, or an error code + */ + public function run(InputInterface $input = null, OutputInterface $output = null): int + { + // We'll just ignore the input passed in, and set up our own! + $input = new ArrayInput([]); + + if ($output === null) { + $output = $this->config->getOutput(); + } + + $this->setAutoExit(false); + $this->setCatchExceptions(false); + + try { + return parent::run($input, $output); + } catch (\Throwable $e) { + $this->writeException($e); + } + + return 1; + } + + /** + * Runs PsySH. + * + * @throws \Throwable if thrown via the `throw-up` command + * + * @param InputInterface $input An Input instance + * @param OutputInterface $output An Output instance + * + * @return int 0 if everything went fine, or an error code + */ + public function doRun(InputInterface $input, OutputInterface $output): int + { + $this->setOutput($output); + $this->resetCodeBuffer(); + + if ($input->isInteractive()) { + // @todo should it be possible to have raw output in an interactive run? + return $this->doInteractiveRun(); + } else { + return $this->doNonInteractiveRun($this->config->rawOutput()); + } + } + + /** + * Run PsySH in interactive mode. + * + * Initializes tab completion and readline history, then spins up the + * execution loop. + * + * @throws \Throwable if thrown via the `throw-up` command + * + * @return int 0 if everything went fine, or an error code + */ + private function doInteractiveRun(): int + { + $this->initializeTabCompletion(); + $this->readline->readHistory(); + + $this->output->writeln($this->getHeader()); + $this->writeVersionInfo(); + $this->writeStartupMessage(); + + try { + $this->beforeRun(); + $this->loadIncludes(); + $loop = new ExecutionLoopClosure($this); + $loop->execute(); + $this->afterRun(); + } catch (ThrowUpException $e) { + throw $e->getPrevious(); + } catch (BreakException $e) { + // The ProcessForker throws a BreakException to finish the main thread. + } + + return 0; + } + + /** + * Run PsySH in non-interactive mode. + * + * Note that this isn't very useful unless you supply "include" arguments at + * the command line, or code via stdin. + * + * @param bool $rawOutput + * + * @return int 0 if everything went fine, or an error code + */ + private function doNonInteractiveRun(bool $rawOutput): int + { + $this->nonInteractive = true; + + // If raw output is enabled (or output is piped) we don't want startup messages. + if (!$rawOutput && !$this->config->outputIsPiped()) { + $this->output->writeln($this->getHeader()); + $this->writeVersionInfo(); + $this->writeStartupMessage(); + } + + $this->beforeRun(); + $this->loadIncludes(); + + // For non-interactive execution, read only from the input buffer or from piped input. + // Otherwise it'll try to readline and hang, waiting for user input with no indication of + // what's holding things up. + if (!empty($this->inputBuffer) || $this->config->inputIsPiped()) { + $this->getInput(false); + } + + if ($this->hasCode()) { + $ret = $this->execute($this->flushCode()); + $this->writeReturnValue($ret, $rawOutput); + } + + $this->afterRun(); + $this->nonInteractive = false; + + return 0; + } + + /** + * Configures the input and output instances based on the user arguments and options. + */ + protected function configureIO(InputInterface $input, OutputInterface $output): void + { + // @todo overrides via environment variables (or should these happen in config? ... probably config) + $input->setInteractive($this->config->getInputInteractive()); + + if ($this->config->getOutputDecorated() !== null) { + $output->setDecorated($this->config->getOutputDecorated()); + } + + $output->setVerbosity($this->config->getOutputVerbosity()); + } + + /** + * Load user-defined includes. + */ + private function loadIncludes() + { + // Load user-defined includes + $load = function (self $__psysh__) { + \set_error_handler([$__psysh__, 'handleError']); + foreach ($__psysh__->getIncludes() as $__psysh_include__) { + try { + include_once $__psysh_include__; + } catch (\Exception $_e) { + $__psysh__->writeException($_e); + } + } + \restore_error_handler(); + unset($__psysh_include__); + + // Override any new local variables with pre-defined scope variables + \extract($__psysh__->getScopeVariables(false)); + + // ... then add the whole mess of variables back. + $__psysh__->setScopeVariables(\get_defined_vars()); + }; + + $load($this); + } + + /** + * Read user input. + * + * This will continue fetching user input until the code buffer contains + * valid code. + * + * @throws BreakException if user hits Ctrl+D + * + * @param bool $interactive + */ + public function getInput(bool $interactive = true) + { + $this->codeBufferOpen = false; + + do { + // reset output verbosity (in case it was altered by a subcommand) + $this->output->setVerbosity($this->originalVerbosity); + + $input = $this->readline(); + + /* + * Handle Ctrl+D. It behaves differently in different cases: + * + * 1) In an expression, like a function or "if" block, clear the input buffer + * 2) At top-level session, behave like the exit command + * 3) When non-interactive, return, because that's the end of stdin + */ + if ($input === false) { + if (!$interactive) { + return; + } + + $this->output->writeln(''); + + if ($this->hasCode()) { + $this->resetCodeBuffer(); + } else { + throw new BreakException('Ctrl+D'); + } + } + + // handle empty input + if (\trim($input) === '' && !$this->codeBufferOpen) { + continue; + } + + $input = $this->onInput($input); + + // If the input isn't in an open string or comment, check for commands to run. + if ($this->hasCommand($input) && !$this->inputInOpenStringOrComment($input)) { + $this->addHistory($input); + $this->runCommand($input); + + continue; + } + + $this->addCode($input); + } while (!$interactive || !$this->hasValidCode()); + } + + /** + * Check whether the code buffer (plus current input) is in an open string or comment. + * + * @param string $input current line of input + * + * @return bool true if the input is in an open string or comment + */ + private function inputInOpenStringOrComment(string $input): bool + { + if (!$this->hasCode()) { + return false; + } + + $code = $this->codeBuffer; + $code[] = $input; + $tokens = @\token_get_all('<?php '.\implode("\n", $code)); + $last = \array_pop($tokens); + + return $last === '"' || $last === '`' || + (\is_array($last) && \in_array($last[0], [\T_ENCAPSED_AND_WHITESPACE, \T_START_HEREDOC, \T_COMMENT])); + } + + /** + * Run execution loop listeners before the shell session. + */ + protected function beforeRun() + { + foreach ($this->loopListeners as $listener) { + $listener->beforeRun($this); + } + } + + /** + * Run execution loop listeners at the start of each loop. + */ + public function beforeLoop() + { + foreach ($this->loopListeners as $listener) { + $listener->beforeLoop($this); + } + } + + /** + * Run execution loop listeners on user input. + * + * @param string $input + */ + public function onInput(string $input): string + { + foreach ($this->loopListeners as $listeners) { + if (($return = $listeners->onInput($this, $input)) !== null) { + $input = $return; + } + } + + return $input; + } + + /** + * Run execution loop listeners on code to be executed. + * + * @param string $code + */ + public function onExecute(string $code): string + { + $this->errorReporting = \error_reporting(); + + foreach ($this->loopListeners as $listener) { + if (($return = $listener->onExecute($this, $code)) !== null) { + $code = $return; + } + } + + $output = $this->output; + if ($output instanceof ConsoleOutput) { + $output = $output->getErrorOutput(); + } + + $output->writeln(\sprintf('<whisper>%s</whisper>', OutputFormatter::escape($code)), ConsoleOutput::VERBOSITY_DEBUG); + + return $code; + } + + /** + * Run execution loop listeners after each loop. + */ + public function afterLoop() + { + foreach ($this->loopListeners as $listener) { + $listener->afterLoop($this); + } + } + + /** + * Run execution loop listers after the shell session. + */ + protected function afterRun() + { + foreach ($this->loopListeners as $listener) { + $listener->afterRun($this); + } + } + + /** + * Set the variables currently in scope. + * + * @param array $vars + */ + public function setScopeVariables(array $vars) + { + $this->context->setAll($vars); + } + + /** + * Return the set of variables currently in scope. + * + * @param bool $includeBoundObject Pass false to exclude 'this'. If you're + * passing the scope variables to `extract` + * you _must_ exclude 'this' + * + * @return array Associative array of scope variables + */ + public function getScopeVariables(bool $includeBoundObject = true): array + { + $vars = $this->context->getAll(); + + if (!$includeBoundObject) { + unset($vars['this']); + } + + return $vars; + } + + /** + * Return the set of magic variables currently in scope. + * + * @param bool $includeBoundObject Pass false to exclude 'this'. If you're + * passing the scope variables to `extract` + * you _must_ exclude 'this' + * + * @return array Associative array of magic scope variables + */ + public function getSpecialScopeVariables(bool $includeBoundObject = true): array + { + $vars = $this->context->getSpecialVariables(); + + if (!$includeBoundObject) { + unset($vars['this']); + } + + return $vars; + } + + /** + * Return the set of variables currently in scope which differ from the + * values passed as $currentVars. + * + * This is used inside the Execution Loop Closure to pick up scope variable + * changes made by commands while the loop is running. + * + * @param array $currentVars + * + * @return array Associative array of scope variables which differ from $currentVars + */ + public function getScopeVariablesDiff(array $currentVars): array + { + $newVars = []; + + foreach ($this->getScopeVariables(false) as $key => $value) { + if (!\array_key_exists($key, $currentVars) || $currentVars[$key] !== $value) { + $newVars[$key] = $value; + } + } + + return $newVars; + } + + /** + * Get the set of unused command-scope variable names. + * + * @return array Array of unused variable names + */ + public function getUnusedCommandScopeVariableNames(): array + { + return $this->context->getUnusedCommandScopeVariableNames(); + } + + /** + * Get the set of variable names currently in scope. + * + * @return array Array of variable names + */ + public function getScopeVariableNames(): array + { + return \array_keys($this->context->getAll()); + } + + /** + * Get a scope variable value by name. + * + * @param string $name + * + * @return mixed + */ + public function getScopeVariable(string $name) + { + return $this->context->get($name); + } + + /** + * Set the bound object ($this variable) for the interactive shell. + * + * @param object|null $boundObject + */ + public function setBoundObject($boundObject) + { + $this->context->setBoundObject($boundObject); + } + + /** + * Get the bound object ($this variable) for the interactive shell. + * + * @return object|null + */ + public function getBoundObject() + { + return $this->context->getBoundObject(); + } + + /** + * Set the bound class (self) for the interactive shell. + * + * @param string|null $boundClass + */ + public function setBoundClass($boundClass) + { + $this->context->setBoundClass($boundClass); + } + + /** + * Get the bound class (self) for the interactive shell. + * + * @return string|null + */ + public function getBoundClass() + { + return $this->context->getBoundClass(); + } + + /** + * Add includes, to be parsed and executed before running the interactive shell. + * + * @param array $includes + */ + public function setIncludes(array $includes = []) + { + $this->includes = $includes; + } + + /** + * Get PHP files to be parsed and executed before running the interactive shell. + * + * @return string[] + */ + public function getIncludes(): array + { + return \array_merge($this->config->getDefaultIncludes(), $this->includes); + } + + /** + * Check whether this shell's code buffer contains code. + * + * @return bool True if the code buffer contains code + */ + public function hasCode(): bool + { + return !empty($this->codeBuffer); + } + + /** + * Check whether the code in this shell's code buffer is valid. + * + * If the code is valid, the code buffer should be flushed and evaluated. + * + * @return bool True if the code buffer content is valid + */ + protected function hasValidCode(): bool + { + return !$this->codeBufferOpen && $this->code !== false; + } + + /** + * Add code to the code buffer. + * + * @param string $code + * @param bool $silent + */ + public function addCode(string $code, bool $silent = false) + { + try { + // Code lines ending in \ keep the buffer open + if (\substr(\rtrim($code), -1) === '\\') { + $this->codeBufferOpen = true; + $code = \substr(\rtrim($code), 0, -1); + } else { + $this->codeBufferOpen = false; + } + + $this->codeBuffer[] = $silent ? new SilentInput($code) : $code; + $this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons()); + } catch (\Throwable $e) { + // Add failed code blocks to the readline history. + $this->addCodeBufferToHistory(); + + throw $e; + } + } + + /** + * Set the code buffer. + * + * This is mostly used by `Shell::execute`. Any existing code in the input + * buffer is pushed onto a stack and will come back after this new code is + * executed. + * + * @throws \InvalidArgumentException if $code isn't a complete statement + * + * @param string $code + * @param bool $silent + */ + private function setCode(string $code, bool $silent = false) + { + if ($this->hasCode()) { + $this->codeStack[] = [$this->codeBuffer, $this->codeBufferOpen, $this->code]; + } + + $this->resetCodeBuffer(); + try { + $this->addCode($code, $silent); + } catch (\Throwable $e) { + $this->popCodeStack(); + + throw $e; + } + + if (!$this->hasValidCode()) { + $this->popCodeStack(); + + throw new \InvalidArgumentException('Unexpected end of input'); + } + } + + /** + * Get the current code buffer. + * + * This is useful for commands which manipulate the buffer. + * + * @return string[] + */ + public function getCodeBuffer(): array + { + return $this->codeBuffer; + } + + /** + * Run a Psy Shell command given the user input. + * + * @throws \InvalidArgumentException if the input is not a valid command + * + * @param string $input User input string + * + * @return mixed Who knows? + */ + protected function runCommand(string $input) + { + $command = $this->getCommand($input); + + if (empty($command)) { + throw new \InvalidArgumentException('Command not found: '.$input); + } + + $input = new ShellInput(\str_replace('\\', '\\\\', \rtrim($input, " \t\n\r\0\x0B;"))); + + if ($input->hasParameterOption(['--help', '-h'])) { + $helpCommand = $this->get('help'); + if (!$helpCommand instanceof Command\HelpCommand) { + throw new RuntimeException('Invalid help command instance'); + } + $helpCommand->setCommand($command); + + return $helpCommand->run(new StringInput(''), $this->output); + } + + return $command->run($input, $this->output); + } + + /** + * Reset the current code buffer. + * + * This should be run after evaluating user input, catching exceptions, or + * on demand by commands such as BufferCommand. + */ + public function resetCodeBuffer() + { + $this->codeBuffer = []; + $this->code = false; + } + + /** + * Inject input into the input buffer. + * + * This is useful for commands which want to replay history. + * + * @param string|array $input + * @param bool $silent + */ + public function addInput($input, bool $silent = false) + { + foreach ((array) $input as $line) { + $this->inputBuffer[] = $silent ? new SilentInput($line) : $line; + } + } + + /** + * Flush the current (valid) code buffer. + * + * If the code buffer is valid, resets the code buffer and returns the + * current code. + * + * @return string|null PHP code buffer contents + */ + public function flushCode() + { + if ($this->hasValidCode()) { + $this->addCodeBufferToHistory(); + $code = $this->code; + $this->popCodeStack(); + + return $code; + } + } + + /** + * Reset the code buffer and restore any code pushed during `execute` calls. + */ + private function popCodeStack() + { + $this->resetCodeBuffer(); + + if (empty($this->codeStack)) { + return; + } + + list($codeBuffer, $codeBufferOpen, $code) = \array_pop($this->codeStack); + + $this->codeBuffer = $codeBuffer; + $this->codeBufferOpen = $codeBufferOpen; + $this->code = $code; + } + + /** + * (Possibly) add a line to the readline history. + * + * Like Bash, if the line starts with a space character, it will be omitted + * from history. Note that an entire block multi-line code input will be + * omitted iff the first line begins with a space. + * + * Additionally, if a line is "silent", i.e. it was initially added with the + * silent flag, it will also be omitted. + * + * @param string|SilentInput $line + */ + private function addHistory($line) + { + if ($line instanceof SilentInput) { + return; + } + + // Skip empty lines and lines starting with a space + if (\trim($line) !== '' && \substr($line, 0, 1) !== ' ') { + $this->readline->addHistory($line); + } + } + + /** + * Filter silent input from code buffer, write the rest to readline history. + */ + private function addCodeBufferToHistory() + { + $codeBuffer = \array_filter($this->codeBuffer, function ($line) { + return !$line instanceof SilentInput; + }); + + $this->addHistory(\implode("\n", $codeBuffer)); + } + + /** + * Get the current evaluation scope namespace. + * + * @see CodeCleaner::getNamespace + * + * @return string|null Current code namespace + */ + public function getNamespace() + { + if ($namespace = $this->cleaner->getNamespace()) { + return \implode('\\', $namespace); + } + } + + /** + * Write a string to stdout. + * + * This is used by the shell loop for rendering output from evaluated code. + * + * @param string $out + * @param int $phase Output buffering phase + */ + public function writeStdout(string $out, int $phase = \PHP_OUTPUT_HANDLER_END) + { + if ($phase & \PHP_OUTPUT_HANDLER_START) { + if ($this->output instanceof ShellOutput) { + $this->output->startPaging(); + } + } + + $isCleaning = $phase & \PHP_OUTPUT_HANDLER_CLEAN; + + // Incremental flush + if ($out !== '' && !$isCleaning) { + $this->output->write($out, false, OutputInterface::OUTPUT_RAW); + $this->outputWantsNewline = (\substr($out, -1) !== "\n"); + $this->stdoutBuffer .= $out; + } + + // Output buffering is done! + if ($phase & \PHP_OUTPUT_HANDLER_END) { + // Write an extra newline if stdout didn't end with one + if ($this->outputWantsNewline) { + if (!$this->config->rawOutput() && !$this->config->outputIsPiped()) { + $this->output->writeln(\sprintf('<whisper>%s</whisper>', $this->config->useUnicode() ? '⏎' : '\\n')); + } else { + $this->output->writeln(''); + } + $this->outputWantsNewline = false; + } + + // Save the stdout buffer as $__out + if ($this->stdoutBuffer !== '') { + $this->context->setLastStdout($this->stdoutBuffer); + $this->stdoutBuffer = ''; + } + + if ($this->output instanceof ShellOutput) { + $this->output->stopPaging(); + } + } + } + + /** + * Write a return value to stdout. + * + * The return value is formatted or pretty-printed, and rendered in a + * visibly distinct manner (in this case, as cyan). + * + * @see self::presentValue + * + * @param mixed $ret + * @param bool $rawOutput Write raw var_export-style values + */ + public function writeReturnValue($ret, bool $rawOutput = false) + { + $this->lastExecSuccess = true; + + if ($ret instanceof NoReturnValue) { + return; + } + + $this->context->setReturnValue($ret); + + if ($rawOutput) { + $formatted = \var_export($ret, true); + } else { + $prompt = $this->config->theme()->returnValue(); + $indent = \str_repeat(' ', \strlen($prompt)); + $formatted = $this->presentValue($ret); + $formattedRetValue = \sprintf('<whisper>%s</whisper>', $prompt); + + $formatted = $formattedRetValue.\str_replace(\PHP_EOL, \PHP_EOL.$indent, $formatted); + } + + if ($this->output instanceof ShellOutput) { + $this->output->page($formatted.\PHP_EOL); + } else { + $this->output->writeln($formatted); + } + } + + /** + * Renders a caught Exception or Error. + * + * Exceptions are formatted according to severity. ErrorExceptions which were + * warnings or Strict errors aren't rendered as harshly as real errors. + * + * Stores $e as the last Exception in the Shell Context. + * + * @param \Throwable $e An exception or error instance + */ + public function writeException(\Throwable $e) + { + // No need to write the break exception during a non-interactive run. + if ($e instanceof BreakException && $this->nonInteractive) { + $this->resetCodeBuffer(); + + return; + } + + // Break exceptions don't count :) + if (!$e instanceof BreakException) { + $this->lastExecSuccess = false; + $this->context->setLastException($e); + } + + $output = $this->output; + if ($output instanceof ConsoleOutput) { + $output = $output->getErrorOutput(); + } + + if (!$this->config->theme()->compact()) { + $output->writeln(''); + } + + $output->writeln($this->formatException($e)); + + if (!$this->config->theme()->compact()) { + $output->writeln(''); + } + + // Include an exception trace (as long as this isn't a BreakException). + if (!$e instanceof BreakException && $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $trace = TraceFormatter::formatTrace($e); + if (\count($trace) !== 0) { + $output->writeln('--'); + $output->write($trace, true); + $output->writeln(''); + } + } + + $this->resetCodeBuffer(); + } + + /** + * Check whether the last exec was successful. + * + * Returns true if a return value was logged rather than an exception. + */ + public function getLastExecSuccess(): bool + { + return $this->lastExecSuccess; + } + + /** + * Helper for formatting an exception or error for writeException(). + * + * @todo extract this to somewhere it makes more sense + * + * @param \Throwable $e + */ + public function formatException(\Throwable $e): string + { + $indent = $this->config->theme()->compact() ? '' : ' '; + + if ($e instanceof BreakException) { + return \sprintf('%s<info> INFO </info> %s.', $indent, \rtrim($e->getRawMessage(), '.')); + } elseif ($e instanceof PsyException) { + $message = $e->getLine() > 1 + ? \sprintf('%s in %s on line %d', $e->getRawMessage(), $e->getFile(), $e->getLine()) + : \sprintf('%s in %s', $e->getRawMessage(), $e->getFile()); + + $messageLabel = \strtoupper($this->getMessageLabel($e)); + } else { + $message = $e->getMessage(); + $messageLabel = $this->getMessageLabel($e); + } + + $message = \preg_replace( + "#(\\w:)?([\\\\/]\\w+)*[\\\\/]src[\\\\/]Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code#", + "eval()'d code", + $message + ); + + $message = \str_replace(" in eval()'d code", '', $message); + $message = \trim($message); + + // Ensures the given string ends with punctuation... + if (!empty($message) && !\in_array(\substr($message, -1), ['.', '?', '!', ':'])) { + $message = "$message."; + } + + // Ensures the given message only contains relative paths... + $message = \str_replace(\getcwd().\DIRECTORY_SEPARATOR, '', $message); + + $severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error'; + + return \sprintf('%s<%s> %s </%s> %s', $indent, $severity, $messageLabel, $severity, OutputFormatter::escape($message)); + } + + /** + * Helper for getting an output style for the given ErrorException's level. + * + * @param \ErrorException $e + */ + protected function getSeverity(\ErrorException $e): string + { + $severity = $e->getSeverity(); + if ($severity & \error_reporting()) { + switch ($severity) { + case \E_WARNING: + case \E_NOTICE: + case \E_CORE_WARNING: + case \E_COMPILE_WARNING: + case \E_USER_WARNING: + case \E_USER_NOTICE: + case \E_USER_DEPRECATED: + case \E_DEPRECATED: + case \E_STRICT: + return 'warning'; + + default: + return 'error'; + } + } else { + // Since this is below the user's reporting threshold, it's always going to be a warning. + return 'warning'; + } + } + + /** + * Helper for getting an output style for the given ErrorException's level. + * + * @param \Throwable $e + */ + protected function getMessageLabel(\Throwable $e): string + { + if ($e instanceof \ErrorException) { + $severity = $e->getSeverity(); + + if ($severity & \error_reporting()) { + switch ($severity) { + case \E_WARNING: + return 'Warning'; + case \E_NOTICE: + return 'Notice'; + case \E_CORE_WARNING: + return 'Core Warning'; + case \E_COMPILE_WARNING: + return 'Compile Warning'; + case \E_USER_WARNING: + return 'User Warning'; + case \E_USER_NOTICE: + return 'User Notice'; + case \E_USER_DEPRECATED: + return 'User Deprecated'; + case \E_DEPRECATED: + return 'Deprecated'; + case \E_STRICT: + return 'Strict'; + } + } + } + + if ($e instanceof PsyException || $e instanceof SymfonyConsoleException) { + $exceptionShortName = (new \ReflectionClass($e))->getShortName(); + $typeParts = \preg_split('/(?=[A-Z])/', $exceptionShortName); + + switch ($exceptionShortName) { + case 'RuntimeException': + case 'LogicException': + // These ones look weird without 'Exception' + break; + default: + if (\end($typeParts) === 'Exception') { + \array_pop($typeParts); + } + break; + } + + return \trim(\strtoupper(\implode(' ', $typeParts))); + } + + return \get_class($e); + } + + /** + * Execute code in the shell execution context. + * + * @param string $code + * @param bool $throwExceptions + * + * @return mixed + */ + public function execute(string $code, bool $throwExceptions = false) + { + $this->setCode($code, true); + $closure = new ExecutionClosure($this); + + if ($throwExceptions) { + return $closure->execute(); + } + + try { + return $closure->execute(); + } catch (\Throwable $_e) { + $this->writeException($_e); + } + } + + /** + * Helper for throwing an ErrorException. + * + * This allows us to: + * + * set_error_handler([$psysh, 'handleError']); + * + * Unlike ErrorException::throwException, this error handler respects error + * levels; i.e. it logs warnings and notices, but doesn't throw exceptions. + * This should probably only be used in the inner execution loop of the + * shell, as most of the time a thrown exception is much more useful. + * + * If the error type matches the `errorLoggingLevel` config, it will be + * logged as well, regardless of the `error_reporting` level. + * + * @see \Psy\Exception\ErrorException::throwException + * @see \Psy\Shell::writeException + * + * @throws \Psy\Exception\ErrorException depending on the error level + * + * @param int $errno Error type + * @param string $errstr Message + * @param string $errfile Filename + * @param int $errline Line number + */ + public function handleError($errno, $errstr, $errfile, $errline) + { + // This is an error worth throwing. + // + // n.b. Technically we can't handle all of these in userland code, but + // we'll list 'em all for good measure + if ($errno & (\E_ERROR | \E_PARSE | \E_CORE_ERROR | \E_COMPILE_ERROR | \E_USER_ERROR | \E_RECOVERABLE_ERROR)) { + ErrorException::throwException($errno, $errstr, $errfile, $errline); + } + + // When errors are suppressed, the error_reporting value will differ + // from when we started executing. In that case, we won't log errors. + $errorsSuppressed = $this->errorReporting !== null && $this->errorReporting !== \error_reporting(); + + // Otherwise log it and continue. + if ($errno & \error_reporting() || (!$errorsSuppressed && ($errno & $this->config->errorLoggingLevel()))) { + $this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline)); + } + } + + /** + * Format a value for display. + * + * @see Presenter::present + * + * @param mixed $val + * + * @return string Formatted value + */ + protected function presentValue($val): string + { + return $this->config->getPresenter()->present($val); + } + + /** + * Get a command (if one exists) for the current input string. + * + * @param string $input + * + * @return BaseCommand|null + */ + protected function getCommand(string $input) + { + $input = new StringInput($input); + if ($name = $input->getFirstArgument()) { + return $this->get($name); + } + } + + /** + * Check whether a command is set for the current input string. + * + * @param string $input + * + * @return bool True if the shell has a command for the given input + */ + protected function hasCommand(string $input): bool + { + if (\preg_match('/([^\s]+?)(?:\s|$)/A', \ltrim($input), $match)) { + return $this->has($match[1]); + } + + return false; + } + + /** + * Get the current input prompt. + * + * @return string|null + */ + protected function getPrompt() + { + if ($this->output->isQuiet()) { + return null; + } + + $theme = $this->config->theme(); + + if ($this->hasCode()) { + return $theme->bufferPrompt(); + } + + return $theme->prompt(); + } + + /** + * Read a line of user input. + * + * This will return a line from the input buffer (if any exist). Otherwise, + * it will ask the user for input. + * + * If readline is enabled, this delegates to readline. Otherwise, it's an + * ugly `fgets` call. + * + * @param bool $interactive + * + * @return string|false One line of user input + */ + protected function readline(bool $interactive = true) + { + $prompt = $this->config->theme()->replayPrompt(); + + if (!empty($this->inputBuffer)) { + $line = \array_shift($this->inputBuffer); + if (!$line instanceof SilentInput) { + $this->output->writeln(\sprintf('<whisper>%s</whisper><aside>%s</aside>', $prompt, OutputFormatter::escape($line))); + } + + return $line; + } + + $bracketedPaste = $interactive && $this->config->useBracketedPaste(); + + if ($bracketedPaste) { + \printf("\e[?2004h"); // Enable bracketed paste + } + + $line = $this->readline->readline($this->getPrompt()); + + if ($bracketedPaste) { + \printf("\e[?2004l"); // ... and disable it again + } + + return $line; + } + + /** + * Get the shell output header. + */ + protected function getHeader(): string + { + return \sprintf('<whisper>%s by Justin Hileman</whisper>', $this->getVersion()); + } + + /** + * Get the current version of Psy Shell. + * + * @deprecated call self::getVersionHeader instead + */ + public function getVersion(): string + { + @\trigger_error('`getVersion` is deprecated; call `self::getVersionHeader` instead.', \E_USER_DEPRECATED); + + return self::getVersionHeader($this->config->useUnicode()); + } + + /** + * Get a pretty header including the current version of Psy Shell. + * + * @param bool $useUnicode + */ + public static function getVersionHeader(bool $useUnicode = false): string + { + $separator = $useUnicode ? '—' : '-'; + + return \sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, \PHP_VERSION, $separator, \PHP_SAPI); + } + + /** + * Get a PHP manual database instance. + * + * @return \PDO|null + */ + public function getManualDb() + { + return $this->config->getManualDb(); + } + + /** + * Initialize tab completion matchers. + * + * If tab completion is enabled this adds tab completion matchers to the + * auto completer and sets context if needed. + */ + protected function initializeTabCompletion() + { + if (!$this->config->useTabCompletion()) { + return; + } + + $this->autoCompleter = $this->config->getAutoCompleter(); + + // auto completer needs shell to be linked to configuration because of + // the context aware matchers + $this->addMatchersToAutoCompleter($this->getDefaultMatchers()); + $this->addMatchersToAutoCompleter($this->matchers); + + $this->autoCompleter->activate(); + } + + /** + * Add matchers to the auto completer, setting context if needed. + * + * @param array $matchers + */ + private function addMatchersToAutoCompleter(array $matchers) + { + foreach ($matchers as $matcher) { + if ($matcher instanceof ContextAware) { + $matcher->setContext($this->context); + } + $this->autoCompleter->addMatcher($matcher); + } + } + + /** + * @todo Implement prompt to start update + * + * @return void|string + */ + protected function writeVersionInfo() + { + if (\PHP_SAPI !== 'cli') { + return; + } + + try { + $client = $this->config->getChecker(); + if (!$client->isLatest()) { + $this->output->writeln(\sprintf('<whisper>New version is available at psysh.org/psysh (current: %s, latest: %s)</whisper>', self::VERSION, $client->getLatest())); + } + } catch (\InvalidArgumentException $e) { + $this->output->writeln($e->getMessage()); + } + } + + /** + * Write a startup message if set. + */ + protected function writeStartupMessage() + { + $message = $this->config->getStartupMessage(); + if ($message !== null && $message !== '') { + $this->output->writeln($message); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Sudo.php b/php/libraries/composer/vendor/psy/psysh/src/Sudo.php new file mode 100644 index 0000000..a84f31d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Sudo.php @@ -0,0 +1,198 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * Helpers for bypassing visibility restrictions, mostly used in code generated + * by the `sudo` command. + */ +class Sudo +{ + /** + * Fetch a property of an object, bypassing visibility restrictions. + * + * @param object $object + * @param string $property property name + * + * @return mixed Value of $object->property + */ + public static function fetchProperty($object, string $property) + { + $prop = self::getProperty(new \ReflectionObject($object), $property); + + return $prop->getValue($object); + } + + /** + * Assign the value of a property of an object, bypassing visibility restrictions. + * + * @param object $object + * @param string $property property name + * @param mixed $value + * + * @return mixed Value of $object->property + */ + public static function assignProperty($object, string $property, $value) + { + $prop = self::getProperty(new \ReflectionObject($object), $property); + $prop->setValue($object, $value); + + return $value; + } + + /** + * Call a method on an object, bypassing visibility restrictions. + * + * @param object $object + * @param string $method method name + * @param mixed $args... + * + * @return mixed + */ + public static function callMethod($object, string $method, ...$args) + { + $refl = new \ReflectionObject($object); + $reflMethod = $refl->getMethod($method); + $reflMethod->setAccessible(true); + + return $reflMethod->invokeArgs($object, $args); + } + + /** + * Fetch a property of a class, bypassing visibility restrictions. + * + * @param string|object $class class name or instance + * @param string $property property name + * + * @return mixed Value of $class::$property + */ + public static function fetchStaticProperty($class, string $property) + { + $prop = self::getProperty(new \ReflectionClass($class), $property); + $prop->setAccessible(true); + + return $prop->getValue(); + } + + /** + * Assign the value of a static property of a class, bypassing visibility restrictions. + * + * @param string|object $class class name or instance + * @param string $property property name + * @param mixed $value + * + * @return mixed Value of $class::$property + */ + public static function assignStaticProperty($class, string $property, $value) + { + $prop = self::getProperty(new \ReflectionClass($class), $property); + $refl = $prop->getDeclaringClass(); + + if (\method_exists($refl, 'setStaticPropertyValue')) { + $refl->setStaticPropertyValue($property, $value); + } else { + $prop->setValue($value); + } + + return $value; + } + + /** + * Call a static method on a class, bypassing visibility restrictions. + * + * @param string|object $class class name or instance + * @param string $method method name + * @param mixed $args... + * + * @return mixed + */ + public static function callStatic($class, string $method, ...$args) + { + $refl = new \ReflectionClass($class); + $reflMethod = $refl->getMethod($method); + $reflMethod->setAccessible(true); + + return $reflMethod->invokeArgs(null, $args); + } + + /** + * Fetch a class constant, bypassing visibility restrictions. + * + * @param string|object $class class name or instance + * @param string $const constant name + * + * @return mixed + */ + public static function fetchClassConst($class, string $const) + { + $refl = new \ReflectionClass($class); + + do { + if ($refl->hasConstant($const)) { + return $refl->getConstant($const); + } + + $refl = $refl->getParentClass(); + } while ($refl !== false); + + return false; + } + + /** + * Construct an instance of a class, bypassing private constructors. + * + * @param string $class class name + * @param mixed $args... + */ + public static function newInstance(string $class, ...$args) + { + $refl = new \ReflectionClass($class); + $instance = $refl->newInstanceWithoutConstructor(); + + $constructor = $refl->getConstructor(); + $constructor->setAccessible(true); + $constructor->invokeArgs($instance, $args); + + return $instance; + } + + /** + * Get a ReflectionProperty from an object (or its parent classes). + * + * @throws \ReflectionException if neither the object nor any of its parents has this property + * + * @param \ReflectionClass $refl + * @param string $property property name + * + * @return \ReflectionProperty + */ + private static function getProperty(\ReflectionClass $refl, string $property): \ReflectionProperty + { + $firstException = null; + do { + try { + $prop = $refl->getProperty($property); + $prop->setAccessible(true); + + return $prop; + } catch (\ReflectionException $e) { + if ($firstException === null) { + $firstException = $e; + } + + $refl = $refl->getParentClass(); + } + } while ($refl !== false); + + throw $firstException; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Sudo/SudoVisitor.php b/php/libraries/composer/vendor/psy/psysh/src/Sudo/SudoVisitor.php new file mode 100644 index 0000000..151dc52 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Sudo/SudoVisitor.php @@ -0,0 +1,134 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Sudo; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr\Assign; +use PhpParser\Node\Expr\ClassConstFetch; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\New_; +use PhpParser\Node\Expr\PropertyFetch; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Expr\StaticPropertyFetch; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified as FullyQualifiedName; +use PhpParser\Node\Scalar\String_; +use PhpParser\NodeVisitorAbstract; +use Psy\Sudo; + +/** + * A PHP Parser node visitor which rewrites property and method access to use + * the Psy\Sudo visibility bypass methods. + * + * @todo handle assigning by reference + */ +class SudoVisitor extends NodeVisitorAbstract +{ + const PROPERTY_FETCH = 'fetchProperty'; + const PROPERTY_ASSIGN = 'assignProperty'; + const METHOD_CALL = 'callMethod'; + const STATIC_PROPERTY_FETCH = 'fetchStaticProperty'; + const STATIC_PROPERTY_ASSIGN = 'assignStaticProperty'; + const STATIC_CALL = 'callStatic'; + const CLASS_CONST_FETCH = 'fetchClassConst'; + const NEW_INSTANCE = 'newInstance'; + + /** + * {@inheritdoc} + * + * @return int|Node|null Replacement node (or special return value) + */ + public function enterNode(Node $node) + { + if ($node instanceof PropertyFetch) { + $name = $node->name instanceof Identifier ? $node->name->toString() : $node->name; + $args = [ + $node->var, + \is_string($name) ? new String_($name) : $name, + ]; + + return $this->prepareCall(self::PROPERTY_FETCH, $args); + } elseif ($node instanceof Assign && $node->var instanceof PropertyFetch) { + $target = $node->var; + $name = $target->name instanceof Identifier ? $target->name->toString() : $target->name; + $args = [ + $target->var, + \is_string($name) ? new String_($name) : $name, + $node->expr, + ]; + + return $this->prepareCall(self::PROPERTY_ASSIGN, $args); + } elseif ($node instanceof MethodCall) { + $name = $node->name instanceof Identifier ? $node->name->toString() : $node->name; + $args = $node->args; + \array_unshift($args, new Arg(\is_string($name) ? new String_($name) : $name)); + \array_unshift($args, new Arg($node->var)); + + // not using prepareCall because the $node->args we started with are already Arg instances + return new StaticCall(new FullyQualifiedName(Sudo::class), self::METHOD_CALL, $args); + } elseif ($node instanceof StaticPropertyFetch) { + $class = $node->class instanceof Name ? $node->class->toString() : $node->class; + $name = $node->name instanceof Identifier ? $node->name->toString() : $node->name; + $args = [ + \is_string($class) ? new String_($class) : $class, + \is_string($name) ? new String_($name) : $name, + ]; + + return $this->prepareCall(self::STATIC_PROPERTY_FETCH, $args); + } elseif ($node instanceof Assign && $node->var instanceof StaticPropertyFetch) { + $target = $node->var; + $class = $target->class instanceof Name ? $target->class->toString() : $target->class; + $name = $target->name instanceof Identifier ? $target->name->toString() : $target->name; + $args = [ + \is_string($class) ? new String_($class) : $class, + \is_string($name) ? new String_($name) : $name, + $node->expr, + ]; + + return $this->prepareCall(self::STATIC_PROPERTY_ASSIGN, $args); + } elseif ($node instanceof StaticCall) { + $args = $node->args; + $class = $node->class instanceof Name ? $node->class->toString() : $node->class; + $name = $node->name instanceof Identifier ? $node->name->toString() : $node->name; + \array_unshift($args, new Arg(\is_string($name) ? new String_($name) : $name)); + \array_unshift($args, new Arg(\is_string($class) ? new String_($class) : $class)); + + // not using prepareCall because the $node->args we started with are already Arg instances + return new StaticCall(new FullyQualifiedName(Sudo::class), self::STATIC_CALL, $args); + } elseif ($node instanceof ClassConstFetch) { + $class = $node->class instanceof Name ? $node->class->toString() : $node->class; + $name = $node->name instanceof Identifier ? $node->name->toString() : $node->name; + $args = [ + \is_string($class) ? new String_($class) : $class, + \is_string($name) ? new String_($name) : $name, + ]; + + return $this->prepareCall(self::CLASS_CONST_FETCH, $args); + } elseif ($node instanceof New_) { + $args = $node->args; + $class = $node->class instanceof Name ? $node->class->toString() : $node->class; + \array_unshift($args, new Arg(\is_string($class) ? new String_($class) : $class)); + + // not using prepareCall because the $node->args we started with are already Arg instances + return new StaticCall(new FullyQualifiedName(Sudo::class), self::NEW_INSTANCE, $args); + } + } + + private function prepareCall(string $method, array $args): StaticCall + { + return new StaticCall(new FullyQualifiedName(Sudo::class), $method, \array_map(function ($arg) { + return new Arg($arg); + }, $args)); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/SuperglobalsEnv.php b/php/libraries/composer/vendor/psy/psysh/src/SuperglobalsEnv.php new file mode 100644 index 0000000..d3369c6 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/SuperglobalsEnv.php @@ -0,0 +1,32 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * Environment variables implementation via $_SERVER superglobal. + */ +class SuperglobalsEnv implements EnvInterface +{ + /** + * Get an environment variable by name. + * + * @return string|null + */ + public function get(string $key) + { + if (isset($_SERVER[$key]) && $_SERVER[$key]) { + return $_SERVER[$key]; + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/SystemEnv.php b/php/libraries/composer/vendor/psy/psysh/src/SystemEnv.php new file mode 100644 index 0000000..fe2a8ed --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/SystemEnv.php @@ -0,0 +1,34 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +/** + * Environment variables implementation via getenv(). + */ +class SystemEnv implements EnvInterface +{ + /** + * Get an environment variable by name. + * + * @return string|null + */ + public function get(string $key) + { + if (isset($_SERVER[$key]) && $_SERVER[$key]) { + return $_SERVER[$key]; + } + + $result = \getenv($key); + + return $result === false ? null : $result; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/AutoCompleter.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/AutoCompleter.php new file mode 100644 index 0000000..400b797 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/AutoCompleter.php @@ -0,0 +1,112 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion; + +use Psy\TabCompletion\Matcher\AbstractMatcher; + +/** + * A readline tab completion service. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class AutoCompleter +{ + /** @var Matcher\AbstractMatcher[] */ + protected $matchers; + + /** + * Register a tab completion Matcher. + * + * @param AbstractMatcher $matcher + */ + public function addMatcher(AbstractMatcher $matcher) + { + $this->matchers[] = $matcher; + } + + /** + * Activate readline tab completion. + */ + public function activate() + { + \readline_completion_function([&$this, 'callback']); + } + + /** + * Handle readline completion. + * + * @param string $input Readline current word + * @param int $index Current word index + * @param array $info readline_info() data + * + * @return array + */ + public function processCallback(string $input, int $index, array $info = []): array + { + // Some (Windows?) systems provide incomplete `readline_info`, so let's + // try to work around it. + $line = $info['line_buffer']; + if (isset($info['end'])) { + $line = \substr($line, 0, $info['end']); + } + if ($line === '' && $input !== '') { + $line = $input; + } + + $tokens = \token_get_all('<?php '.$line); + + // remove whitespaces + $tokens = \array_filter($tokens, function ($token) { + return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE); + }); + // reset index from 0 to remove missing index number + $tokens = \array_values($tokens); + + $matches = []; + foreach ($this->matchers as $matcher) { + if ($matcher->hasMatched($tokens)) { + $matches = \array_merge($matcher->getMatches($tokens), $matches); + } + } + + $matches = \array_unique($matches); + + return !empty($matches) ? $matches : ['']; + } + + /** + * The readline_completion_function callback handler. + * + * @see processCallback + * + * @param string $input + * @param int $index + * + * @return array + */ + public function callback(string $input, int $index): array + { + return $this->processCallback($input, $index, \readline_info()); + } + + /** + * Remove readline callback handler on destruct. + */ + public function __destruct() + { + // PHP didn't implement the whole readline API when they first switched + // to libedit. And they still haven't. + if (\function_exists('readline_callback_handler_remove')) { + \readline_callback_handler_remove(); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractContextAwareMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractContextAwareMatcher.php new file mode 100644 index 0000000..bc39e60 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractContextAwareMatcher.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +use Psy\Context; +use Psy\ContextAware; + +/** + * An abstract tab completion Matcher which implements ContextAware. + * + * The AutoCompleter service will inject a Context instance into all + * ContextAware Matchers. + * + * @author Marc Garcia <markcial@gmail.com> + */ +abstract class AbstractContextAwareMatcher extends AbstractMatcher implements ContextAware +{ + /** + * Context instance (for ContextAware interface). + * + * @var Context + */ + protected $context; + + /** + * ContextAware interface. + * + * @param Context $context + */ + public function setContext(Context $context) + { + $this->context = $context; + } + + /** + * Get a Context variable by name. + * + * @param string $var Variable name + * + * @return mixed + */ + protected function getVariable(string $var) + { + return $this->context->get($var); + } + + /** + * Get all variables in the current Context. + * + * @return array + */ + protected function getVariables(): array + { + return $this->context->getAll(); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php new file mode 100644 index 0000000..0887333 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php @@ -0,0 +1,74 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +abstract class AbstractDefaultParametersMatcher extends AbstractContextAwareMatcher +{ + /** + * @param \ReflectionParameter[] $reflectionParameters + * + * @return array + */ + public function getDefaultParameterCompletion(array $reflectionParameters): array + { + $parametersProcessed = []; + + foreach ($reflectionParameters as $parameter) { + if (!$parameter->isDefaultValueAvailable()) { + return []; + } + + $defaultValue = $this->valueToShortString($parameter->getDefaultValue()); + + $parametersProcessed[] = \sprintf('$%s = %s', $parameter->getName(), $defaultValue); + } + + if (empty($parametersProcessed)) { + return []; + } + + return [\implode(', ', $parametersProcessed).')']; + } + + /** + * Takes in the default value of a parameter and turns it into a + * string representation that fits inline. + * This is not 100% true to the original (newlines are inlined, for example). + * + * @param mixed $value + */ + private function valueToShortString($value): string + { + if (!\is_array($value)) { + return \json_encode($value); + } + + $chunks = []; + $chunksSequential = []; + + $allSequential = true; + + foreach ($value as $key => $item) { + $allSequential = $allSequential && \is_numeric($key) && $key === \count($chunksSequential); + + $keyString = $this->valueToShortString($key); + $itemString = $this->valueToShortString($item); + + $chunks[] = "{$keyString} => {$itemString}"; + $chunksSequential[] = $itemString; + } + + $chunksToImplode = $allSequential ? $chunksSequential : $chunks; + + return '['.\implode(', ', $chunksToImplode).']'; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractMatcher.php new file mode 100644 index 0000000..209cae2 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/AbstractMatcher.php @@ -0,0 +1,182 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * Abstract tab completion Matcher. + * + * @author Marc Garcia <markcial@gmail.com> + */ +abstract class AbstractMatcher +{ + /** Syntax types */ + const CONSTANT_SYNTAX = '^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$'; + const VAR_SYNTAX = '^\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$'; + const MISC_OPERATORS = '+-*/^|&'; + /** Token values */ + const T_OPEN_TAG = 'T_OPEN_TAG'; + const T_VARIABLE = 'T_VARIABLE'; + const T_OBJECT_OPERATOR = 'T_OBJECT_OPERATOR'; + const T_DOUBLE_COLON = 'T_DOUBLE_COLON'; + const T_NEW = 'T_NEW'; + const T_CLONE = 'T_CLONE'; + const T_NS_SEPARATOR = 'T_NS_SEPARATOR'; + const T_STRING = 'T_STRING'; + const T_NAME_QUALIFIED = 'T_NAME_QUALIFIED'; + const T_WHITESPACE = 'T_WHITESPACE'; + const T_AND_EQUAL = 'T_AND_EQUAL'; + const T_BOOLEAN_AND = 'T_BOOLEAN_AND'; + const T_BOOLEAN_OR = 'T_BOOLEAN_OR'; + + const T_ENCAPSED_AND_WHITESPACE = 'T_ENCAPSED_AND_WHITESPACE'; + const T_REQUIRE = 'T_REQUIRE'; + const T_REQUIRE_ONCE = 'T_REQUIRE_ONCE'; + const T_INCLUDE = 'T_INCLUDE'; + const T_INCLUDE_ONCE = 'T_INCLUDE_ONCE'; + + /** + * Check whether this matcher can provide completions for $tokens. + * + * @param array $tokens Tokenized readline input + * + * @return false + */ + public function hasMatched(array $tokens): bool + { + return false; + } + + /** + * Get current readline input word. + * + * @param array $tokens Tokenized readline input (see token_get_all) + */ + protected function getInput(array $tokens): string + { + $var = ''; + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + $var = $firstToken[1]; + } + + return $var; + } + + /** + * Get current namespace and class (if any) from readline input. + * + * @param array $tokens Tokenized readline input (see token_get_all) + */ + protected function getNamespaceAndClass(array $tokens): string + { + $class = ''; + while (self::hasToken( + [self::T_NS_SEPARATOR, self::T_STRING, self::T_NAME_QUALIFIED], + $token = \array_pop($tokens) + )) { + if (self::needCompleteClass($token)) { + continue; + } + + $class = $token[1].$class; + } + + return $class; + } + + /** + * Provide tab completion matches for readline input. + * + * @param array $tokens information substracted with get_token_all + * @param array $info readline_info object + * + * @return array The matches resulting from the query + */ + abstract public function getMatches(array $tokens, array $info = []): array; + + /** + * Check whether $word starts with $prefix. + * + * @param string $prefix + * @param string $word + */ + public static function startsWith(string $prefix, string $word): bool + { + return \preg_match(\sprintf('#^%s#', $prefix), $word); + } + + /** + * Check whether $token matches a given syntax pattern. + * + * @param mixed $token A PHP token (see token_get_all) + * @param string $syntax A syntax pattern (default: variable pattern) + */ + public static function hasSyntax($token, string $syntax = self::VAR_SYNTAX): bool + { + if (!\is_array($token)) { + return false; + } + + $regexp = \sprintf('#%s#', $syntax); + + return (bool) \preg_match($regexp, $token[1]); + } + + /** + * Check whether $token type is $which. + * + * @param mixed $token A PHP token (see token_get_all) + * @param string $which A PHP token type + */ + public static function tokenIs($token, string $which): bool + { + if (!\is_array($token)) { + return false; + } + + return \token_name($token[0]) === $which; + } + + /** + * Check whether $token is an operator. + * + * @param mixed $token A PHP token (see token_get_all) + */ + public static function isOperator($token): bool + { + if (!\is_string($token)) { + return false; + } + + return \strpos(self::MISC_OPERATORS, $token) !== false; + } + + public static function needCompleteClass($token): bool + { + return \in_array($token[1], ['doc', 'ls', 'show']); + } + + /** + * Check whether $token type is present in $coll. + * + * @param array $coll A list of token types + * @param mixed $token A PHP token (see token_get_all) + */ + public static function hasToken(array $coll, $token): bool + { + if (!\is_array($token)) { + return false; + } + + return \in_array(\token_name($token[0]), $coll); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassAttributesMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassAttributesMatcher.php new file mode 100644 index 0000000..0503d71 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassAttributesMatcher.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A class attribute tab completion Matcher. + * + * Given a namespace and class, this matcher provides completion for constants + * and static properties. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class ClassAttributesMatcher extends AbstractMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + // second token is the nekudotayim operator + \array_pop($tokens); + } + + $class = $this->getNamespaceAndClass($tokens); + + try { + $reflection = new \ReflectionClass($class); + } catch (\ReflectionException $re) { + return []; + } + + $vars = \array_merge( + \array_map( + function ($var) { + return '$'.$var; + }, + \array_keys($reflection->getStaticProperties()) + ), + \array_keys($reflection->getConstants()) + ); + + return \array_map( + function ($name) use ($class) { + $chunks = \explode('\\', $class); + $className = \array_pop($chunks); + + return $className.'::'.$name; + }, + \array_filter( + $vars, + function ($var) use ($input) { + return AbstractMatcher::startsWith($input, $var); + } + ) + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($prevToken, self::T_DOUBLE_COLON) && self::tokenIs($token, self::T_STRING): + case self::tokenIs($token, self::T_DOUBLE_COLON): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php new file mode 100644 index 0000000..118740e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php @@ -0,0 +1,64 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +class ClassMethodDefaultParametersMatcher extends AbstractDefaultParametersMatcher +{ + public function getMatches(array $tokens, array $info = []): array + { + $openBracket = \array_pop($tokens); + $functionName = \array_pop($tokens); + $methodOperator = \array_pop($tokens); + + $class = $this->getNamespaceAndClass($tokens); + + try { + $reflection = new \ReflectionClass($class); + } catch (\ReflectionException $e) { + // In this case the class apparently does not exist, so we can do nothing + return []; + } + + $methods = $reflection->getMethods(\ReflectionMethod::IS_STATIC); + + foreach ($methods as $method) { + if ($method->getName() === $functionName[1]) { + return $this->getDefaultParameterCompletion($method->getParameters()); + } + } + + return []; + } + + public function hasMatched(array $tokens): bool + { + $openBracket = \array_pop($tokens); + + if ($openBracket !== '(') { + return false; + } + + $functionName = \array_pop($tokens); + + if (!self::tokenIs($functionName, self::T_STRING)) { + return false; + } + + $operator = \array_pop($tokens); + + if (!self::tokenIs($operator, self::T_DOUBLE_COLON)) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassMethodsMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassMethodsMatcher.php new file mode 100644 index 0000000..a526e1e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassMethodsMatcher.php @@ -0,0 +1,84 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A class method tab completion Matcher. + * + * Given a namespace and class, this matcher provides completion for static + * methods. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class ClassMethodsMatcher extends AbstractMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + // second token is the nekudotayim operator + \array_pop($tokens); + } + + $class = $this->getNamespaceAndClass($tokens); + + try { + $reflection = new \ReflectionClass($class); + } catch (\ReflectionException $re) { + return []; + } + + if (self::needCompleteClass($tokens[1])) { + $methods = $reflection->getMethods(); + } else { + $methods = $reflection->getMethods(\ReflectionMethod::IS_STATIC); + } + + $methods = \array_map(function (\ReflectionMethod $method) { + return $method->getName(); + }, $methods); + + return \array_map( + function ($name) use ($class) { + $chunks = \explode('\\', $class); + $className = \array_pop($chunks); + + return $className.'::'.$name; + }, + \array_filter($methods, function ($method) use ($input) { + return AbstractMatcher::startsWith($input, $method); + }) + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($prevToken, self::T_DOUBLE_COLON) && self::tokenIs($token, self::T_STRING): + case self::tokenIs($token, self::T_DOUBLE_COLON): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassNamesMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassNamesMatcher.php new file mode 100644 index 0000000..ca2515d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ClassNamesMatcher.php @@ -0,0 +1,77 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A class name tab completion Matcher. + * + * This matcher provides completion for all declared classes. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class ClassNamesMatcher extends AbstractMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $class = $this->getNamespaceAndClass($tokens); + if ($class !== '' && $class[0] === '\\') { + $class = \substr($class, 1, \strlen($class)); + } + $quotedClass = \preg_quote($class); + + return \array_map( + function ($className) use ($class) { + // get the number of namespace separators + $nsPos = \substr_count($class, '\\'); + $pieces = \explode('\\', $className); + // $methods = Mirror::get($class); + return \implode('\\', \array_slice($pieces, $nsPos, \count($pieces))); + }, + \array_filter( + \array_merge(\get_declared_classes(), \get_declared_interfaces()), + function ($className) use ($quotedClass) { + return AbstractMatcher::startsWith($quotedClass, $className); + } + ) + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + $ignoredTokens = [ + self::T_INCLUDE, self::T_INCLUDE_ONCE, self::T_REQUIRE, self::T_REQUIRE_ONCE, + ]; + + switch (true) { + case self::hasToken([$ignoredTokens], $token): + case self::hasToken([$ignoredTokens], $prevToken): + case \is_string($token) && $token === '$': + return false; + case self::hasToken([self::T_NEW, self::T_OPEN_TAG, self::T_NS_SEPARATOR, self::T_STRING], $prevToken): + case self::hasToken([self::T_NEW, self::T_OPEN_TAG, self::T_NS_SEPARATOR], $token): + case self::hasToken([self::T_OPEN_TAG, self::T_VARIABLE], $token): + case self::isOperator($token): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/CommandsMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/CommandsMatcher.php new file mode 100644 index 0000000..952329a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/CommandsMatcher.php @@ -0,0 +1,110 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +use Psy\Command\Command; + +/** + * A Psy Command tab completion Matcher. + * + * This matcher provides completion for all registered Psy Command names and + * aliases. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class CommandsMatcher extends AbstractMatcher +{ + /** @var string[] */ + protected $commands = []; + + /** + * CommandsMatcher constructor. + * + * @param Command[] $commands + */ + public function __construct(array $commands) + { + $this->setCommands($commands); + } + + /** + * Set Commands for completion. + * + * @param Command[] $commands + */ + public function setCommands(array $commands) + { + $names = []; + foreach ($commands as $command) { + $names = \array_merge([$command->getName()], $names); + $names = \array_merge($command->getAliases(), $names); + } + $this->commands = $names; + } + + /** + * Check whether a command $name is defined. + * + * @param string $name + */ + protected function isCommand(string $name): bool + { + return \in_array($name, $this->commands); + } + + /** + * Check whether input matches a defined command. + * + * @param string $name + */ + protected function matchCommand(string $name): bool + { + foreach ($this->commands as $cmd) { + if ($this->startsWith($name, $cmd)) { + return true; + } + } + + return false; + } + + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + return \array_filter($this->commands, function ($command) use ($input) { + return AbstractMatcher::startsWith($input, $command); + }); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + /* $openTag */ \array_shift($tokens); + $command = \array_shift($tokens); + + switch (true) { + case self::tokenIs($command, self::T_STRING) && + !$this->isCommand($command[1]) && + $this->matchCommand($command[1]) && + empty($tokens): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ConstantsMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ConstantsMatcher.php new file mode 100644 index 0000000..cad81a5 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ConstantsMatcher.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A constant name tab completion Matcher. + * + * This matcher provides completion for all defined constants. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class ConstantsMatcher extends AbstractMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $const = $this->getInput($tokens); + + return \array_filter(\array_keys(\get_defined_constants()), function ($constant) use ($const) { + return AbstractMatcher::startsWith($const, $constant); + }); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($prevToken, self::T_NEW): + case self::tokenIs($prevToken, self::T_NS_SEPARATOR): + return false; + case self::hasToken([self::T_OPEN_TAG, self::T_STRING], $token): + case self::isOperator($token): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php new file mode 100644 index 0000000..2bbf126 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php @@ -0,0 +1,53 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +class FunctionDefaultParametersMatcher extends AbstractDefaultParametersMatcher +{ + public function getMatches(array $tokens, array $info = []): array + { + \array_pop($tokens); // open bracket + + $functionName = \array_pop($tokens); + + try { + $reflection = new \ReflectionFunction($functionName[1]); + } catch (\ReflectionException $e) { + return []; + } + + $parameters = $reflection->getParameters(); + + return $this->getDefaultParameterCompletion($parameters); + } + + public function hasMatched(array $tokens): bool + { + $openBracket = \array_pop($tokens); + + if ($openBracket !== '(') { + return false; + } + + $functionName = \array_pop($tokens); + + if (!self::tokenIs($functionName, self::T_STRING)) { + return false; + } + + if (!\function_exists($functionName[1])) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/FunctionsMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/FunctionsMatcher.php new file mode 100644 index 0000000..9645659 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/FunctionsMatcher.php @@ -0,0 +1,56 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A function name tab completion Matcher. + * + * This matcher provides completion for all internal and user-defined functions. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class FunctionsMatcher extends AbstractMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $func = $this->getInput($tokens); + + $functions = \get_defined_functions(); + $allFunctions = \array_merge($functions['user'], $functions['internal']); + + return \array_filter($allFunctions, function ($function) use ($func) { + return AbstractMatcher::startsWith($func, $function); + }); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($prevToken, self::T_NEW): + return false; + case self::hasToken([self::T_OPEN_TAG, self::T_STRING], $token): + case self::isOperator($token): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/KeywordsMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/KeywordsMatcher.php new file mode 100644 index 0000000..9f2bdef --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/KeywordsMatcher.php @@ -0,0 +1,83 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A PHP keyword tab completion Matcher. + * + * This matcher provides completion for all function-like PHP keywords. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class KeywordsMatcher extends AbstractMatcher +{ + protected $keywords = [ + 'array', 'clone', 'declare', 'die', 'echo', 'empty', 'eval', 'exit', 'include', + 'include_once', 'isset', 'list', 'print', 'require', 'require_once', 'unset', + ]; + + protected $mandatoryStartKeywords = [ + 'die', 'echo', 'print', 'unset', + ]; + + /** + * Get all (completable) PHP keywords. + * + * @return string[] + */ + public function getKeywords(): array + { + return $this->keywords; + } + + /** + * Check whether $keyword is a (completable) PHP keyword. + * + * @param string $keyword + */ + public function isKeyword(string $keyword): bool + { + return \in_array($keyword, $this->keywords); + } + + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + return \array_filter($this->keywords, function ($keyword) use ($input) { + return AbstractMatcher::startsWith($input, $keyword); + }); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::hasToken([self::T_OPEN_TAG, self::T_VARIABLE], $token): +// case is_string($token) && $token === '$': + case self::hasToken([self::T_OPEN_TAG, self::T_VARIABLE], $prevToken) && + self::tokenIs($token, self::T_STRING): + case self::isOperator($token): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/MongoClientMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/MongoClientMatcher.php new file mode 100644 index 0000000..3c70ee0 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/MongoClientMatcher.php @@ -0,0 +1,71 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A MongoDB Client tab completion Matcher. + * + * This matcher provides completion for MongoClient database names. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class MongoClientMatcher extends AbstractContextAwareMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + // second token is the object operator + \array_pop($tokens); + } + $objectToken = \array_pop($tokens); + $objectName = \str_replace('$', '', $objectToken[1]); + $object = $this->getVariable($objectName); + + if (!$object instanceof \MongoClient) { + return []; + } + + $list = $object->listDBs(); + + return \array_filter( + \array_map(function ($info) { + return $info['name']; + }, $list['databases']), + function ($var) use ($input) { + return AbstractMatcher::startsWith($input, $var); + } + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($token, self::T_OBJECT_OPERATOR): + case self::tokenIs($prevToken, self::T_OBJECT_OPERATOR): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/MongoDatabaseMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/MongoDatabaseMatcher.php new file mode 100644 index 0000000..7cea95f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/MongoDatabaseMatcher.php @@ -0,0 +1,67 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A MongoDB tab completion Matcher. + * + * This matcher provides completion for Mongo collection names. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class MongoDatabaseMatcher extends AbstractContextAwareMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + // second token is the object operator + \array_pop($tokens); + } + $objectToken = \array_pop($tokens); + $objectName = \str_replace('$', '', $objectToken[1]); + $object = $this->getVariable($objectName); + + if (!$object instanceof \MongoDB) { + return []; + } + + return \array_filter( + $object->getCollectionNames(), + function ($var) use ($input) { + return AbstractMatcher::startsWith($input, $var); + } + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($token, self::T_OBJECT_OPERATOR): + case self::tokenIs($prevToken, self::T_OBJECT_OPERATOR): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectAttributesMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectAttributesMatcher.php new file mode 100644 index 0000000..e0e9667 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectAttributesMatcher.php @@ -0,0 +1,78 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +use InvalidArgumentException; + +/** + * An object attribute tab completion Matcher. + * + * This matcher provides completion for properties of objects in the current + * Context. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class ObjectAttributesMatcher extends AbstractContextAwareMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + // second token is the object operator + \array_pop($tokens); + } + $objectToken = \array_pop($tokens); + if (!\is_array($objectToken)) { + return []; + } + $objectName = \str_replace('$', '', $objectToken[1]); + + try { + $object = $this->getVariable($objectName); + } catch (InvalidArgumentException $e) { + return []; + } + + if (!\is_object($object)) { + return []; + } + + return \array_filter( + \array_keys(\get_class_vars(\get_class($object))), + function ($var) use ($input) { + return AbstractMatcher::startsWith($input, $var); + } + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($token, self::T_OBJECT_OPERATOR): + case self::tokenIs($prevToken, self::T_OBJECT_OPERATOR): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php new file mode 100644 index 0000000..73221fd --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php @@ -0,0 +1,71 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +class ObjectMethodDefaultParametersMatcher extends AbstractDefaultParametersMatcher +{ + public function getMatches(array $tokens, array $info = []): array + { + $openBracket = \array_pop($tokens); + $functionName = \array_pop($tokens); + $methodOperator = \array_pop($tokens); + + $objectToken = \array_pop($tokens); + if (!\is_array($objectToken)) { + return []; + } + + $objectName = \str_replace('$', '', $objectToken[1]); + + try { + $object = $this->getVariable($objectName); + $reflection = new \ReflectionObject($object); + } catch (\InvalidArgumentException $e) { + return []; + } catch (\ReflectionException $e) { + return []; + } + + $methods = $reflection->getMethods(); + + foreach ($methods as $method) { + if ($method->getName() === $functionName[1]) { + return $this->getDefaultParameterCompletion($method->getParameters()); + } + } + + return []; + } + + public function hasMatched(array $tokens): bool + { + $openBracket = \array_pop($tokens); + + if ($openBracket !== '(') { + return false; + } + + $functionName = \array_pop($tokens); + + if (!self::tokenIs($functionName, self::T_STRING)) { + return false; + } + + $operator = \array_pop($tokens); + + if (!self::tokenIs($operator, self::T_OBJECT_OPERATOR)) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectMethodsMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectMethodsMatcher.php new file mode 100644 index 0000000..4f10b07 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/ObjectMethodsMatcher.php @@ -0,0 +1,80 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +use InvalidArgumentException; + +/** + * An object method tab completion Matcher. + * + * This matcher provides completion for methods of objects in the current + * Context. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class ObjectMethodsMatcher extends AbstractContextAwareMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $input = $this->getInput($tokens); + + $firstToken = \array_pop($tokens); + if (self::tokenIs($firstToken, self::T_STRING)) { + // second token is the object operator + \array_pop($tokens); + } + $objectToken = \array_pop($tokens); + if (!\is_array($objectToken)) { + return []; + } + $objectName = \str_replace('$', '', $objectToken[1]); + + try { + $object = $this->getVariable($objectName); + } catch (InvalidArgumentException $e) { + return []; + } + + if (!\is_object($object)) { + return []; + } + + return \array_filter( + \get_class_methods($object), + function ($var) use ($input) { + return AbstractMatcher::startsWith($input, $var) && + // also check that we do not suggest invoking a super method(__construct, __wakeup, …) + !AbstractMatcher::startsWith('__', $var); + } + ); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + $prevToken = \array_pop($tokens); + + switch (true) { + case self::tokenIs($token, self::T_OBJECT_OPERATOR): + case self::tokenIs($prevToken, self::T_OBJECT_OPERATOR): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/VariablesMatcher.php b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/VariablesMatcher.php new file mode 100644 index 0000000..6a5167f --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/TabCompletion/Matcher/VariablesMatcher.php @@ -0,0 +1,51 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\TabCompletion\Matcher; + +/** + * A variable name tab completion Matcher. + * + * This matcher provides completion for variable names in the current Context. + * + * @author Marc Garcia <markcial@gmail.com> + */ +class VariablesMatcher extends AbstractContextAwareMatcher +{ + /** + * {@inheritdoc} + */ + public function getMatches(array $tokens, array $info = []): array + { + $var = \str_replace('$', '', $this->getInput($tokens)); + + return \array_filter(\array_keys($this->getVariables()), function ($variable) use ($var) { + return AbstractMatcher::startsWith($var, $variable); + }); + } + + /** + * {@inheritdoc} + */ + public function hasMatched(array $tokens): bool + { + $token = \array_pop($tokens); + + switch (true) { + case self::hasToken([self::T_OPEN_TAG, self::T_VARIABLE], $token): + case \is_string($token) && $token === '$': + case self::isOperator($token): + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Util/Docblock.php b/php/libraries/composer/vendor/psy/psysh/src/Util/Docblock.php new file mode 100644 index 0000000..1b98f27 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Util/Docblock.php @@ -0,0 +1,245 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Util; + +/** + * A docblock representation. + * + * Based on PHP-DocBlock-Parser by Paul Scott: + * + * {@link http://www.github.com/icio/PHP-DocBlock-Parser} + * + * @author Paul Scott <paul@duedil.com> + * @author Justin Hileman <justin@justinhileman.info> + */ +class Docblock +{ + /** + * Tags in the docblock that have a whitespace-delimited number of parameters + * (such as `@param type var desc` and `@return type desc`) and the names of + * those parameters. + * + * @var array + */ + public static $vectors = [ + 'throws' => ['type', 'desc'], + 'param' => ['type', 'var', 'desc'], + 'return' => ['type', 'desc'], + ]; + + protected $reflector; + + /** + * The description of the symbol. + * + * @var string + */ + public $desc; + + /** + * The tags defined in the docblock. + * + * The array has keys which are the tag names (excluding the @) and values + * that are arrays, each of which is an entry for the tag. + * + * In the case where the tag name is defined in {@see DocBlock::$vectors} the + * value within the tag-value array is an array in itself with keys as + * described by {@see DocBlock::$vectors}. + * + * @var array + */ + public $tags; + + /** + * The entire DocBlock comment that was parsed. + * + * @var string + */ + public $comment; + + /** + * Docblock constructor. + * + * @param \Reflector $reflector + */ + public function __construct(\Reflector $reflector) + { + $this->reflector = $reflector; + + if ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionClassConstant || $reflector instanceof \ReflectionFunctionAbstract || $reflector instanceof \ReflectionProperty) { + $this->setComment($reflector->getDocComment()); + } + } + + /** + * Set and parse the docblock comment. + * + * @param string $comment The docblock + */ + protected function setComment(string $comment) + { + $this->desc = ''; + $this->tags = []; + $this->comment = $comment; + + $this->parseComment($comment); + } + + /** + * Find the length of the docblock prefix. + * + * @param array $lines + * + * @return int Prefix length + */ + protected static function prefixLength(array $lines): int + { + // find only lines with interesting things + $lines = \array_filter($lines, function ($line) { + return \substr($line, \strspn($line, "* \t\n\r\0\x0B")); + }); + + // if we sort the lines, we only have to compare two items + \sort($lines); + + $first = \reset($lines); + $last = \end($lines); + + // Special case for single-line comments + if (\count($lines) === 1) { + return \strspn($first, "* \t\n\r\0\x0B"); + } + + // find the longest common substring + $count = \min(\strlen($first), \strlen($last)); + for ($i = 0; $i < $count; $i++) { + if ($first[$i] !== $last[$i]) { + return $i; + } + } + + return $count; + } + + /** + * Parse the comment into the component parts and set the state of the object. + * + * @param string $comment The docblock + */ + protected function parseComment(string $comment) + { + // Strip the opening and closing tags of the docblock + $comment = \substr($comment, 3, -2); + + // Split into arrays of lines + $comment = \array_filter(\preg_split('/\r?\n\r?/', $comment)); + + // Trim asterisks and whitespace from the beginning and whitespace from the end of lines + $prefixLength = self::prefixLength($comment); + $comment = \array_map(function ($line) use ($prefixLength) { + return \rtrim(\substr($line, $prefixLength)); + }, $comment); + + // Group the lines together by @tags + $blocks = []; + $b = -1; + foreach ($comment as $line) { + if (self::isTagged($line)) { + $b++; + $blocks[] = []; + } elseif ($b === -1) { + $b = 0; + $blocks[] = []; + } + $blocks[$b][] = $line; + } + + // Parse the blocks + foreach ($blocks as $block => $body) { + $body = \trim(\implode("\n", $body)); + + if ($block === 0 && !self::isTagged($body)) { + // This is the description block + $this->desc = $body; + } else { + // This block is tagged + $tag = \substr(self::strTag($body), 1); + $body = \ltrim(\substr($body, \strlen($tag) + 2)); + + if (isset(self::$vectors[$tag])) { + // The tagged block is a vector + $count = \count(self::$vectors[$tag]); + if ($body) { + $parts = \preg_split('/\s+/', $body, $count); + } else { + $parts = []; + } + + // Default the trailing values + $parts = \array_pad($parts, $count, null); + + // Store as a mapped array + $this->tags[$tag][] = \array_combine(self::$vectors[$tag], $parts); + } else { + // The tagged block is only text + $this->tags[$tag][] = $body; + } + } + } + } + + /** + * Whether or not a docblock contains a given @tag. + * + * @param string $tag The name of the @tag to check for + */ + public function hasTag(string $tag): bool + { + return \is_array($this->tags) && \array_key_exists($tag, $this->tags); + } + + /** + * The value of a tag. + * + * @param string $tag + * + * @return array|null + */ + public function tag(string $tag): ?array + { + return $this->hasTag($tag) ? $this->tags[$tag] : null; + } + + /** + * Whether or not a string begins with a @tag. + * + * @param string $str + */ + public static function isTagged(string $str): bool + { + return isset($str[1]) && $str[0] === '@' && !\preg_match('/[^A-Za-z]/', $str[1]); + } + + /** + * The tag at the beginning of a string. + * + * @param string $str + * + * @return string|null + */ + public static function strTag(string $str) + { + if (\preg_match('/^@[a-z0-9_]+/', $str, $matches)) { + return $matches[0]; + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Util/Json.php b/php/libraries/composer/vendor/psy/psysh/src/Util/Json.php new file mode 100644 index 0000000..a7eebca --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Util/Json.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Util; + +/** + * A static class to wrap JSON encoding/decoding with PsySH's default options. + */ +class Json +{ + /** + * Encode a value as JSON. + * + * @param mixed $val + * @param int $opt + */ + public static function encode($val, int $opt = 0): string + { + $opt |= \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE; + + return \json_encode($val, $opt); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Util/Mirror.php b/php/libraries/composer/vendor/psy/psysh/src/Util/Mirror.php new file mode 100644 index 0000000..3aa1807 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Util/Mirror.php @@ -0,0 +1,149 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Util; + +use Psy\Exception\RuntimeException; +use Psy\Reflection\ReflectionConstant; +use Psy\Reflection\ReflectionNamespace; + +/** + * A utility class for getting Reflectors. + */ +class Mirror +{ + const CONSTANT = 1; + const METHOD = 2; + const STATIC_PROPERTY = 4; + const PROPERTY = 8; + + /** + * Get a Reflector for a function, class or instance, constant, method or property. + * + * Optionally, pass a $filter param to restrict the types of members checked. For example, to only Reflectors for + * static properties and constants, pass: + * + * $filter = Mirror::CONSTANT | Mirror::STATIC_PROPERTY + * + * @throws \Psy\Exception\RuntimeException when a $member specified but not present on $value + * @throws \InvalidArgumentException if $value is something other than an object or class/function name + * + * @param mixed $value Class or function name, or variable instance + * @param string $member Optional: property, constant or method name (default: null) + * @param int $filter (default: CONSTANT | METHOD | PROPERTY | STATIC_PROPERTY) + * + * @return \Reflector + */ + public static function get($value, string $member = null, int $filter = 15): \Reflector + { + if ($member === null && \is_string($value)) { + if (\function_exists($value)) { + return new \ReflectionFunction($value); + } elseif (\defined($value) || ReflectionConstant::isMagicConstant($value)) { + return new ReflectionConstant($value); + } + } + + $class = self::getClass($value); + + if ($member === null) { + return $class; + } elseif ($filter & self::CONSTANT && $class->hasConstant($member)) { + return new \ReflectionClassConstant($value, $member); + } elseif ($filter & self::METHOD && $class->hasMethod($member)) { + return $class->getMethod($member); + } elseif ($filter & self::PROPERTY && $class->hasProperty($member)) { + return $class->getProperty($member); + } elseif ($filter & self::STATIC_PROPERTY && $class->hasProperty($member) && $class->getProperty($member)->isStatic()) { + return $class->getProperty($member); + } else { + throw new RuntimeException(\sprintf('Unknown member %s on class %s', $member, \is_object($value) ? \get_class($value) : $value)); + } + } + + /** + * Get a ReflectionClass (or ReflectionObject, or ReflectionNamespace) if possible. + * + * @throws \InvalidArgumentException if $value is not a namespace or class name or instance + * + * @param mixed $value + * + * @return \ReflectionClass|ReflectionNamespace + */ + private static function getClass($value) + { + if (\is_object($value)) { + return new \ReflectionObject($value); + } + + if (!\is_string($value)) { + throw new \InvalidArgumentException('Mirror expects an object or class'); + } + + if (\class_exists($value) || \interface_exists($value) || \trait_exists($value)) { + return new \ReflectionClass($value); + } + + $namespace = \preg_replace('/(^\\\\|\\\\$)/', '', $value); + if (self::namespaceExists($namespace)) { + return new ReflectionNamespace($namespace); + } + + throw new \InvalidArgumentException('Unknown namespace, class or function: '.$value); + } + + /** + * Check declared namespaces for a given namespace. + */ + private static function namespaceExists(string $value): bool + { + return \in_array(\strtolower($value), self::getDeclaredNamespaces()); + } + + /** + * Get an array of all currently declared namespaces. + * + * Note that this relies on at least one function, class, interface, trait + * or constant to have been declared in that namespace. + */ + private static function getDeclaredNamespaces(): array + { + $functions = \get_defined_functions(); + + $allNames = \array_merge( + $functions['internal'], + $functions['user'], + \get_declared_classes(), + \get_declared_interfaces(), + \get_declared_traits(), + \array_keys(\get_defined_constants()) + ); + + $namespaces = []; + foreach ($allNames as $name) { + $chunks = \explode('\\', \strtolower($name)); + + // the last one is the function or class or whatever... + \array_pop($chunks); + + while (!empty($chunks)) { + $namespaces[\implode('\\', $chunks)] = true; + \array_pop($chunks); + } + } + + $namespaceNames = \array_keys($namespaces); + + \sort($namespaceNames); + + return $namespaceNames; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/Util/Str.php b/php/libraries/composer/vendor/psy/psysh/src/Util/Str.php new file mode 100644 index 0000000..032520d --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/Util/Str.php @@ -0,0 +1,110 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\Util; + +/** + * String utility methods. + * + * @author ju1ius + */ +class Str +{ + const UNVIS_RX = <<<'EOS' +/ + \\(?: + ((?:040)|s) + | (240) + | (?: M-(.) ) + | (?: M\^(.) ) + | (?: \^(.) ) + ) +/xS +EOS; + + /** + * Decodes a string encoded by libsd's strvis. + * + * From `man 3 vis`: + * + * Use an ‘M’ to represent meta characters (characters with the 8th bit set), + * and use a caret ‘^’ to represent control characters (see iscntrl(3)). + * The following formats are used: + * + * \040 Represents ASCII space. + * + * \240 Represents Meta-space (  in HTML). + * + * \M-C Represents character ‘C’ with the 8th bit set. + * Spans characters ‘\241’ through ‘\376’. + * + * \M^C Represents control character ‘C’ with the 8th bit set. + * Spans characters ‘\200’ through ‘\237’, and ‘\377’ (as ‘\M^?’). + * + * \^C Represents the control character ‘C’. + * Spans characters ‘\000’ through ‘\037’, and ‘\177’ (as ‘\^?’). + * + * The other formats are supported by PHP's stripcslashes, + * except for the \s sequence (ASCII space). + * + * @param string $input The string to decode + */ + public static function unvis(string $input): string + { + $output = \preg_replace_callback(self::UNVIS_RX, [self::class, 'unvisReplace'], $input); + // other escapes & octal are handled by stripcslashes + return \stripcslashes($output); + } + + /** + * Callback for Str::unvis. + * + * @param array $match The matches passed by preg_replace_callback + */ + protected static function unvisReplace(array $match): string + { + // \040, \s + if (!empty($match[1])) { + return "\x20"; + } + // \240 + if (!empty($match[2])) { + return "\xa0"; + } + // \M-(.) + if (isset($match[3]) && $match[3] !== '') { + $chr = $match[3]; + // unvis S_META1 + $cp = 0200; + $cp |= \ord($chr); + + return \chr($cp); + } + // \M^(.) + if (isset($match[4]) && $match[4] !== '') { + $chr = $match[4]; + // unvis S_META | S_CTRL + $cp = 0200; + $cp |= ($chr === '?') ? 0177 : \ord($chr) & 037; + + return \chr($cp); + } + // \^(.) + if (isset($match[5]) && $match[5] !== '') { + $chr = $match[5]; + // unvis S_CTRL + $cp = 0; + $cp |= ($chr === '?') ? 0177 : \ord($chr) & 037; + + return \chr($cp); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Cloner.php b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Cloner.php new file mode 100644 index 0000000..e0aaab9 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Cloner.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VarDumper; + +use Symfony\Component\VarDumper\Caster\Caster; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Cloner\Stub; +use Symfony\Component\VarDumper\Cloner\VarCloner; + +/** + * A PsySH-specialized VarCloner. + */ +class Cloner extends VarCloner +{ + private $filter = 0; + + /** + * {@inheritdoc} + */ + public function cloneVar($var, $filter = 0): Data + { + $this->filter = $filter; + + return parent::cloneVar($var, $filter); + } + + /** + * {@inheritdoc} + */ + protected function castResource(Stub $stub, $isNested): array + { + return Caster::EXCLUDE_VERBOSE & $this->filter ? [] : parent::castResource($stub, $isNested); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Dumper.php b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Dumper.php new file mode 100644 index 0000000..def61d4 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Dumper.php @@ -0,0 +1,108 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VarDumper; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\VarDumper\Cloner\Cursor; +use Symfony\Component\VarDumper\Dumper\CliDumper; + +/** + * A PsySH-specialized CliDumper. + */ +class Dumper extends CliDumper +{ + private $formatter; + private $forceArrayIndexes; + + private const ONLY_CONTROL_CHARS = '/^[\x00-\x1F\x7F]+$/'; + private const CONTROL_CHARS = '/([\x00-\x1F\x7F]+)/'; + private const CONTROL_CHARS_MAP = [ + "\0" => '\0', + "\t" => '\t', + "\n" => '\n', + "\v" => '\v', + "\f" => '\f', + "\r" => '\r', + "\033" => '\e', + ]; + + public function __construct(OutputFormatter $formatter, $forceArrayIndexes = false) + { + $this->formatter = $formatter; + $this->forceArrayIndexes = $forceArrayIndexes; + parent::__construct(); + $this->setColors(false); + } + + /** + * {@inheritdoc} + */ + public function enterHash(Cursor $cursor, $type, $class, $hasChild): void + { + if (Cursor::HASH_INDEXED === $type || Cursor::HASH_ASSOC === $type) { + $class = 0; + } + parent::enterHash($cursor, $type, $class, $hasChild); + } + + /** + * {@inheritdoc} + */ + protected function dumpKey(Cursor $cursor): void + { + if ($this->forceArrayIndexes || Cursor::HASH_INDEXED !== $cursor->hashType) { + parent::dumpKey($cursor); + } + } + + protected function style($style, $value, $attr = []): string + { + if ('ref' === $style) { + $value = \strtr($value, '@', '#'); + } + + $styled = ''; + $cchr = $this->styles['cchr']; + + $chunks = \preg_split(self::CONTROL_CHARS, $value, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); + foreach ($chunks as $chunk) { + if (\preg_match(self::ONLY_CONTROL_CHARS, $chunk)) { + $chars = ''; + $i = 0; + do { + $chars .= isset(self::CONTROL_CHARS_MAP[$chunk[$i]]) ? self::CONTROL_CHARS_MAP[$chunk[$i]] : \sprintf('\x%02X', \ord($chunk[$i])); + } while (isset($chunk[++$i])); + + $chars = $this->formatter->escape($chars); + $styled .= "<{$cchr}>{$chars}</{$cchr}>"; + } else { + $styled .= $this->formatter->escape($chunk); + } + } + + $style = $this->styles[$style]; + + return "<{$style}>{$styled}</{$style}>"; + } + + /** + * {@inheritdoc} + */ + protected function dumpLine($depth, $endOfValue = false): void + { + if ($endOfValue && 0 < $depth) { + $this->line .= ','; + } + $this->line = $this->formatter->format($this->line); + parent::dumpLine($depth, $endOfValue); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Presenter.php b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Presenter.php new file mode 100644 index 0000000..7e54dac --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/Presenter.php @@ -0,0 +1,135 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VarDumper; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\VarDumper\Caster\Caster; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * A Presenter service. + */ +class Presenter +{ + const VERBOSE = 1; + + private $cloner; + private $dumper; + private $exceptionsImportants = [ + "\0*\0message", + "\0*\0code", + "\0*\0file", + "\0*\0line", + "\0Exception\0previous", + ]; + private $styles = [ + 'num' => 'number', + 'integer' => 'integer', + 'float' => 'float', + 'const' => 'const', + 'str' => 'string', + 'cchr' => 'default', + 'note' => 'class', + 'ref' => 'default', + 'public' => 'public', + 'protected' => 'protected', + 'private' => 'private', + 'meta' => 'comment', + 'key' => 'comment', + 'index' => 'number', + ]; + + public function __construct(OutputFormatter $formatter, $forceArrayIndexes = false) + { + // Work around https://github.com/symfony/symfony/issues/23572 + $oldLocale = \setlocale(\LC_NUMERIC, 0); + \setlocale(\LC_NUMERIC, 'C'); + + $this->dumper = new Dumper($formatter, $forceArrayIndexes); + $this->dumper->setStyles($this->styles); + + // Now put the locale back + \setlocale(\LC_NUMERIC, $oldLocale); + + $this->cloner = new Cloner(); + $this->cloner->addCasters(['*' => function ($obj, array $a, Stub $stub, $isNested, $filter = 0) { + if ($filter || $isNested) { + if ($obj instanceof \Throwable) { + $a = Caster::filter($a, Caster::EXCLUDE_NOT_IMPORTANT | Caster::EXCLUDE_EMPTY, $this->exceptionsImportants); + } else { + $a = Caster::filter($a, Caster::EXCLUDE_PROTECTED | Caster::EXCLUDE_PRIVATE); + } + } + + return $a; + }]); + } + + /** + * Register casters. + * + * @see http://symfony.com/doc/current/components/var_dumper/advanced.html#casters + * + * @param callable[] $casters A map of casters + */ + public function addCasters(array $casters) + { + $this->cloner->addCasters($casters); + } + + /** + * Present a reference to the value. + * + * @param mixed $value + */ + public function presentRef($value): string + { + return $this->present($value, 0); + } + + /** + * Present a full representation of the value. + * + * If $depth is 0, the value will be presented as a ref instead. + * + * @param mixed $value + * @param int $depth (default: null) + * @param int $options One of Presenter constants + */ + public function present($value, int $depth = null, int $options = 0): string + { + $data = $this->cloner->cloneVar($value, !($options & self::VERBOSE) ? Caster::EXCLUDE_VERBOSE : 0); + + if (null !== $depth) { + $data = $data->withMaxDepth($depth); + } + + // Work around https://github.com/symfony/symfony/issues/23572 + $oldLocale = \setlocale(\LC_NUMERIC, 0); + \setlocale(\LC_NUMERIC, 'C'); + + $output = ''; + $this->dumper->dump($data, function ($line, $depth) use (&$output) { + if ($depth >= 0) { + if ('' !== $output) { + $output .= \PHP_EOL; + } + $output .= \str_repeat(' ', $depth).$line; + } + }); + + // Now put the locale back + \setlocale(\LC_NUMERIC, $oldLocale); + + return OutputFormatter::escape($output); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VarDumper/PresenterAware.php b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/PresenterAware.php new file mode 100644 index 0000000..47590fb --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VarDumper/PresenterAware.php @@ -0,0 +1,26 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VarDumper; + +/** + * Presenter injects itself as a dependency to all objects which + * implement PresenterAware. + */ +interface PresenterAware +{ + /** + * Set a reference to the Presenter. + * + * @param Presenter $presenter + */ + public function setPresenter(Presenter $presenter); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Checker.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Checker.php new file mode 100644 index 0000000..4de4801 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Checker.php @@ -0,0 +1,25 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +interface Checker +{ + const ALWAYS = 'always'; + const DAILY = 'daily'; + const WEEKLY = 'weekly'; + const MONTHLY = 'monthly'; + const NEVER = 'never'; + + public function isLatest(): bool; + + public function getLatest(): string; +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader.php new file mode 100644 index 0000000..233db31 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +use Psy\Exception\ErrorException; + +interface Downloader +{ + /** + * Set the directory where the download will be written to. + * + * @param string $tempDir + */ + public function setTempDir(string $tempDir); + + /** + * @param string $url + * + * @throws ErrorException on failure + */ + public function download(string $url): bool; + + /** + * Get the temporary file name the download was written to. + */ + public function getFilename(): string; + + /** + * Delete the downloaded file if it exists. + * + * @return void + */ + public function cleanup(); +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/CurlDownloader.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/CurlDownloader.php new file mode 100644 index 0000000..14ca1d8 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/CurlDownloader.php @@ -0,0 +1,84 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater\Downloader; + +use Psy\Exception\ErrorException; +use Psy\Shell; +use Psy\VersionUpdater\Downloader; + +class CurlDownloader implements Downloader +{ + private $tempDir = null; + private $outputFile = null; + + /** {@inheritDoc} */ + public function setTempDir(string $tempDir) + { + $this->tempDir = $tempDir; + } + + /** {@inheritDoc} */ + public function download(string $url): bool + { + $tempDir = $this->tempDir ?: \sys_get_temp_dir(); + $this->outputFile = \tempnam($tempDir, 'psysh-archive-'); + $targetName = $this->outputFile.'.tar.gz'; + + if (!\rename($this->outputFile, $targetName)) { + return false; + } + + $this->outputFile = $targetName; + + $outputHandle = \fopen($this->outputFile, 'w'); + if (!$outputHandle) { + return false; + } + $curl = \curl_init(); + \curl_setopt_array($curl, [ + \CURLOPT_FAILONERROR => true, + \CURLOPT_HEADER => 0, + \CURLOPT_FOLLOWLOCATION => true, + \CURLOPT_TIMEOUT => 10, + \CURLOPT_FILE => $outputHandle, + \CURLOPT_HTTPHEADER => [ + 'User-Agent' => 'PsySH/'.Shell::VERSION, + ], + ]); + \curl_setopt($curl, \CURLOPT_URL, $url); + $result = \curl_exec($curl); + $error = \curl_error($curl); + \curl_close($curl); + + \fclose($outputHandle); + + if (!$result) { + throw new ErrorException('cURL Error: '.$error); + } + + return (bool) $result; + } + + /** {@inheritDoc} */ + public function getFilename(): string + { + return $this->outputFile; + } + + /** {@inheritDoc} */ + public function cleanup() + { + if (\file_exists($this->outputFile)) { + \unlink($this->outputFile); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/Factory.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/Factory.php new file mode 100644 index 0000000..e1cfd84 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/Factory.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater\Downloader; + +use Psy\Exception\ErrorException; +use Psy\VersionUpdater\Downloader; + +class Factory +{ + /** + * @throws ErrorException If no downloaders can be used + */ + public static function getDownloader(): Downloader + { + if (\extension_loaded('curl')) { + return new CurlDownloader(); + } elseif (\ini_get('allow_url_fopen')) { + return new FileDownloader(); + } + throw new ErrorException('No downloader available.'); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/FileDownloader.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/FileDownloader.php new file mode 100644 index 0000000..4bf3811 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Downloader/FileDownloader.php @@ -0,0 +1,56 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater\Downloader; + +use Psy\VersionUpdater\Downloader; + +class FileDownloader implements Downloader +{ + private $tempDir = null; + private $outputFile = null; + + /** {@inheritDoc} */ + public function setTempDir(string $tempDir) + { + $this->tempDir = $tempDir; + } + + /** {@inheritDoc} */ + public function download(string $url): bool + { + $tempDir = $this->tempDir ?: \sys_get_temp_dir(); + $this->outputFile = \tempnam($tempDir, 'psysh-archive-'); + $targetName = $this->outputFile.'.tar.gz'; + + if (!\rename($this->outputFile, $targetName)) { + return false; + } + + $this->outputFile = $targetName; + + return (bool) \file_put_contents($this->outputFile, \file_get_contents($url)); + } + + /** {@inheritDoc} */ + public function getFilename(): string + { + return $this->outputFile; + } + + /** {@inheritDoc} */ + public function cleanup() + { + if (\file_exists($this->outputFile)) { + \unlink($this->outputFile); + } + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/GitHubChecker.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/GitHubChecker.php new file mode 100644 index 0000000..e1fc7ce --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/GitHubChecker.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +use Psy\Shell; + +class GitHubChecker implements Checker +{ + const URL = 'https://api.github.com/repos/bobthecow/psysh/releases/latest'; + + private $latest; + + public function isLatest(): bool + { + // version_compare doesn't handle semver completely; + // strip pre-release and build metadata before comparing + $version = \preg_replace('/[+-]\w+/', '', Shell::VERSION); + + return \version_compare($version, $this->getLatest(), '>='); + } + + public function getLatest(): string + { + if (!isset($this->latest)) { + $this->setLatest($this->getVersionFromTag()); + } + + return $this->latest; + } + + /** + * @param string $version + */ + public function setLatest(string $version) + { + $this->latest = $version; + } + + /** + * @return string|null + */ + private function getVersionFromTag() + { + $contents = $this->fetchLatestRelease(); + if (!$contents || !isset($contents->tag_name)) { + throw new \InvalidArgumentException('Unable to check for updates'); + } + $this->setLatest($contents->tag_name); + + return $this->getLatest(); + } + + /** + * Set to public to make testing easier. + * + * @return mixed + */ + public function fetchLatestRelease() + { + $context = \stream_context_create([ + 'http' => [ + 'user_agent' => 'PsySH/'.Shell::VERSION, + 'timeout' => 1.0, + ], + ]); + + \set_error_handler(function () { + // Just ignore all errors with this. The checker will throw an exception + // if it doesn't work :) + }); + + $result = @\file_get_contents(self::URL, false, $context); + + \restore_error_handler(); + + return \json_decode($result); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Installer.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Installer.php new file mode 100644 index 0000000..eb20cb8 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/Installer.php @@ -0,0 +1,143 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +use Psy\Exception\ErrorException; + +class Installer +{ + /** + * @var string + */ + protected $installLocation; + + /** + * @var string + */ + protected $tempDirectory; + + public function __construct(string $tempDirectory = null) + { + $this->tempDirectory = $tempDirectory ?: \sys_get_temp_dir(); + $this->installLocation = \Phar::running(false); + } + + /** + * Public to allow the Downloader to use the temporary directory if it's been set. + */ + public function getTempDirectory(): string + { + return $this->tempDirectory; + } + + /** + * Verify the currently installed PsySH phar is writable so it can be replaced. + */ + public function isInstallLocationWritable(): bool + { + return \is_writable($this->installLocation); + } + + /** + * Verify the temporary directory is writable so downloads and backups can be saved there. + */ + public function isTempDirectoryWritable(): bool + { + return \is_writable($this->tempDirectory); + } + + /** + * Verifies the downloaded archive can be extracted with \PharData. + * + * @param string $sourceArchive + */ + public function isValidSource(string $sourceArchive): bool + { + if (!\class_exists('\PharData')) { + return false; + } + $pharArchive = new \PharData($sourceArchive); + + return $pharArchive->valid(); + } + + /** + * Extract the "psysh" phar from the archive and move it, replacing the currently installed phar. + * + * @param string $sourceArchive + */ + public function install(string $sourceArchive): bool + { + $pharArchive = new \PharData($sourceArchive); + $outputDirectory = \tempnam($this->tempDirectory, 'psysh-'); + + // remove the temp file, and replace it with a sub-directory + if (!\unlink($outputDirectory) || !\mkdir($outputDirectory, 0700)) { + return false; + } + + $pharArchive->extractTo($outputDirectory, ['psysh'], true); + + $renamed = \rename($outputDirectory.'/psysh', $this->installLocation); + + // Remove the sub-directory created to extract the psysh binary/phar + \rmdir($outputDirectory); + + return $renamed; + } + + /** + * Create a backup of the currently installed PsySH phar in the temporary directory with a version number postfix. + * + * @param string $version + */ + public function createBackup(string $version): bool + { + $backupFilename = $this->getBackupFilename($version); + + if (\file_exists($backupFilename) && !\is_writable($backupFilename)) { + return false; + } + + return \rename($this->installLocation, $backupFilename); + } + + /** + * Restore the backup file to the original PsySH install location. + * + * @param string $version + * + * @throws ErrorException If the backup file could not be found + */ + public function restoreFromBackup(string $version): bool + { + $backupFilename = $this->getBackupFilename($version); + + if (!\file_exists($backupFilename)) { + throw new ErrorException("Cannot restore from backup. File not found! [{$backupFilename}]"); + } + + return \rename($backupFilename, $this->installLocation); + } + + /** + * Get the full path for the backup target file location. + * + * @param string $version + */ + public function getBackupFilename(string $version): string + { + $installFilename = \basename($this->installLocation); + + return \sprintf('%s/%s.%s', $this->tempDirectory, $installFilename, $version); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/IntervalChecker.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/IntervalChecker.php new file mode 100644 index 0000000..06a6777 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/IntervalChecker.php @@ -0,0 +1,72 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +class IntervalChecker extends GitHubChecker +{ + private $cacheFile; + private $interval; + + public function __construct($cacheFile, $interval) + { + $this->cacheFile = $cacheFile; + $this->interval = $interval; + } + + public function fetchLatestRelease() + { + // Read the cached file + $cached = \json_decode(@\file_get_contents($this->cacheFile, false)); + if ($cached && isset($cached->last_check) && isset($cached->release)) { + $now = new \DateTime(); + $lastCheck = new \DateTime($cached->last_check); + if ($lastCheck >= $now->sub($this->getDateInterval())) { + return $cached->release; + } + } + + // Fall back to fetching from GitHub + $release = parent::fetchLatestRelease(); + if ($release && isset($release->tag_name)) { + $this->updateCache($release); + } + + return $release; + } + + /** + * @throws \RuntimeException if interval passed to constructor is not supported + */ + private function getDateInterval(): \DateInterval + { + switch ($this->interval) { + case Checker::DAILY: + return new \DateInterval('P1D'); + case Checker::WEEKLY: + return new \DateInterval('P1W'); + case Checker::MONTHLY: + return new \DateInterval('P1M'); + } + + throw new \RuntimeException('Invalid interval configured'); + } + + private function updateCache($release) + { + $data = [ + 'last_check' => \date(\DATE_ATOM), + 'release' => $release, + ]; + + \file_put_contents($this->cacheFile, \json_encode($data)); + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/NoopChecker.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/NoopChecker.php new file mode 100644 index 0000000..2c8240e --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/NoopChecker.php @@ -0,0 +1,30 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +use Psy\Shell; + +/** + * A version checker stub which always thinks the current version is up to date. + */ +class NoopChecker implements Checker +{ + public function isLatest(): bool + { + return true; + } + + public function getLatest(): string + { + return Shell::VERSION; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/SelfUpdate.php b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/SelfUpdate.php new file mode 100644 index 0000000..dbda871 --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/VersionUpdater/SelfUpdate.php @@ -0,0 +1,186 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy\VersionUpdater; + +use Psy\Exception\ErrorException; +use Psy\Shell; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Self update command. + * + * If a new version is available, this command will download it and replace the currently installed version + */ +class SelfUpdate +{ + const URL_PREFIX = 'https://github.com/bobthecow/psysh/releases/download'; + const SUCCESS = 0; + const FAILURE = 1; + + /** @var Checker */ + private $checker; + + /** @var Installer */ + private $installer; + + /** @var Downloader */ + private $downloader; + + public function __construct(Checker $checker, Installer $installer) + { + $this->checker = $checker; + $this->installer = $installer; + } + + /** + * Allow the downloader to be injected for testing. + * + * @param Downloader $downloader + * + * @return void + */ + public function setDownloader(Downloader $downloader) + { + $this->downloader = $downloader; + } + + /** + * Get the currently set Downloader or create one based on the capabilities of the php environment. + * + * @throws ErrorException if a downloader cannot be created for the php environment + */ + private function getDownloader(): Downloader + { + if (!isset($this->downloader)) { + return Downloader\Factory::getDownloader(); + } + + return $this->downloader; + } + + /** + * Build the download URL for the latest release. + * + * The file name used in the URL will include the flavour postfix extracted from the current version + * if it's present + * + * @param string $latestVersion + */ + private function getAssetUrl(string $latestVersion): string + { + $versionPostfix = ''; + if (\strpos(Shell::VERSION, '+')) { + $versionPostfix = '-'.\substr(Shell::VERSION, \strpos(Shell::VERSION, '+') + 1); + } + $downloadFilename = \sprintf('psysh-%s%s.tar.gz', $latestVersion, $versionPostfix); + + // check if latest release data contains an asset matching the filename? + + return \sprintf('%s/%s/%s', self::URL_PREFIX, $latestVersion, $downloadFilename); + } + + /** + * Execute the self-update process. + * + * @param InputInterface $input + * @param OutputInterface $output + * + * @throws ErrorException if the current version is not restored when installation fails + */ + public function run(InputInterface $input, OutputInterface $output): int + { + $currentVersion = Shell::VERSION; + + // already have the latest version? + if ($this->checker->isLatest()) { + // current version is latest version... + $output->writeln('<info>Current version is up-to-date.</info>'); + + return self::SUCCESS; + } + + // can overwrite current version? + if (!$this->installer->isInstallLocationWritable()) { + $output->writeln('<error>Installed version is not writable.</error>'); + + return self::FAILURE; + } + // can download to, and create a backup in the temp directory? + if (!$this->installer->isTempDirectoryWritable()) { + $output->writeln('<error>Temporary directory is not writable.</error>'); + + return self::FAILURE; + } + + $latestVersion = $this->checker->getLatest(); + $downloadUrl = $this->getAssetUrl($latestVersion); + + $output->write("Downloading PsySH $latestVersion ..."); + + try { + $downloader = $this->getDownloader(); + $downloader->setTempDir($this->installer->getTempDirectory()); + $downloaded = $downloader->download($downloadUrl); + } catch (ErrorException $e) { + $output->write(' <error>Failed.</error>'); + $output->writeln(\sprintf('<error>%s</error>', $e->getMessage())); + + return self::FAILURE; + } + + if (!$downloaded) { + $output->writeln('<error>Download failed.</error>'); + $downloader->cleanup(); + + return self::FAILURE; + } else { + $output->write(' <info>OK</info>'.\PHP_EOL); + } + + $downloadedFile = $downloader->getFilename(); + + if (!$this->installer->isValidSource($downloadedFile)) { + $downloader->cleanup(); + $output->writeln('<error>Downloaded file is not a valid archive.</error>'); + + return self::FAILURE; + } + + // create backup as bin.old-version in the temporary directory + $backupCreated = $this->installer->createBackup($currentVersion); + if (!$backupCreated) { + $downloader->cleanup(); + $output->writeln('<error>Failed to create a backup of the current version.</error>'); + + return self::FAILURE; + } elseif ($input->getOption('verbose')) { + $backupFilename = $this->installer->getBackupFilename($currentVersion); + $output->writeln('Created backup of current version: '.$backupFilename); + } + + if (!$this->installer->install($downloadedFile)) { + $this->installer->restoreFromBackup($currentVersion); + $downloader->cleanup(); + $output->writeln("<error>Failed to install new PsySH version $latestVersion.</error>"); + + return self::FAILURE; + } + + // Remove the downloaded archive file from the temporary directory + $downloader->cleanup(); + + $output->writeln("Updated PsySH from $currentVersion to <info>$latestVersion</info>"); + + return self::SUCCESS; + } +} diff --git a/php/libraries/composer/vendor/psy/psysh/src/functions.php b/php/libraries/composer/vendor/psy/psysh/src/functions.php new file mode 100644 index 0000000..4b6419a --- /dev/null +++ b/php/libraries/composer/vendor/psy/psysh/src/functions.php @@ -0,0 +1,478 @@ +<?php + +/* + * This file is part of Psy Shell. + * + * (c) 2012-2023 Justin Hileman + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Psy; + +use Psy\ExecutionLoop\ProcessForker; +use Psy\VersionUpdater\GitHubChecker; +use Psy\VersionUpdater\Installer; +use Psy\VersionUpdater\SelfUpdate; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +if (!\function_exists('Psy\\sh')) { + /** + * Command to return the eval-able code to startup PsySH. + * + * eval(\Psy\sh()); + */ + function sh(): string + { + if (\version_compare(\PHP_VERSION, '8.0', '<')) { + return '\extract(\Psy\debug(\get_defined_vars(), isset($this) ? $this : @\get_called_class()));'; + } + + return <<<'EOS' +if (isset($this)) { + \extract(\Psy\debug(\get_defined_vars(), $this)); +} else { + try { + static::class; + \extract(\Psy\debug(\get_defined_vars(), static::class)); + } catch (\Error $e) { + \extract(\Psy\debug(\get_defined_vars())); + } +} +EOS; + } +} + +if (!\function_exists('Psy\\debug')) { + /** + * Invoke a Psy Shell from the current context. + * + * For example: + * + * foreach ($items as $item) { + * \Psy\debug(get_defined_vars()); + * } + * + * If you would like your shell interaction to affect the state of the + * current context, you can extract() the values returned from this call: + * + * foreach ($items as $item) { + * extract(\Psy\debug(get_defined_vars())); + * var_dump($item); // will be whatever you set $item to in Psy Shell + * } + * + * Optionally, supply an object as the `$bindTo` parameter. This determines + * the value `$this` will have in the shell, and sets up class scope so that + * private and protected members are accessible: + * + * class Foo { + * function bar() { + * \Psy\debug(get_defined_vars(), $this); + * } + * } + * + * For the static equivalent, pass a class name as the `$bindTo` parameter. + * This makes `self` work in the shell, and sets up static scope so that + * private and protected static members are accessible: + * + * class Foo { + * static function bar() { + * \Psy\debug(get_defined_vars(), get_called_class()); + * } + * } + * + * @param array $vars Scope variables from the calling context (default: []) + * @param object|string $bindTo Bound object ($this) or class (self) value for the shell + * + * @return array Scope variables from the debugger session + */ + function debug(array $vars = [], $bindTo = null): array + { + echo \PHP_EOL; + + $sh = new Shell(); + $sh->setScopeVariables($vars); + + // Show a couple of lines of call context for the debug session. + // + // @todo come up with a better way of doing this which doesn't involve injecting input :-P + if ($sh->has('whereami')) { + $sh->addInput('whereami -n2', true); + } + + if (\is_string($bindTo)) { + $sh->setBoundClass($bindTo); + } elseif ($bindTo !== null) { + $sh->setBoundObject($bindTo); + } + + $sh->run(); + + return $sh->getScopeVariables(false); + } +} + +if (!\function_exists('Psy\\info')) { + /** + * Get a bunch of debugging info about the current PsySH environment and + * configuration. + * + * If a Configuration param is passed, that configuration is stored and + * used for the current shell session, and no debugging info is returned. + * + * @param Configuration|null $config + * + * @return array|null + */ + function info(Configuration $config = null) + { + static $lastConfig; + if ($config !== null) { + $lastConfig = $config; + + return; + } + + $prettyPath = function ($path) { + return $path; + }; + + $homeDir = (new ConfigPaths())->homeDir(); + if ($homeDir && $homeDir = \rtrim($homeDir, '/')) { + $homePattern = '#^'.\preg_quote($homeDir, '#').'/#'; + $prettyPath = function ($path) use ($homePattern) { + if (\is_string($path)) { + return \preg_replace($homePattern, '~/', $path); + } else { + return $path; + } + }; + } + + $config = $lastConfig ?: new Configuration(); + $configEnv = (isset($_SERVER['PSYSH_CONFIG']) && $_SERVER['PSYSH_CONFIG']) ? $_SERVER['PSYSH_CONFIG'] : false; + if ($configEnv === false && \PHP_SAPI === 'cli-server') { + $configEnv = \getenv('PSYSH_CONFIG'); + } + + $shellInfo = [ + 'PsySH version' => Shell::VERSION, + ]; + + $core = [ + 'PHP version' => \PHP_VERSION, + 'OS' => \PHP_OS, + 'default includes' => $config->getDefaultIncludes(), + 'require semicolons' => $config->requireSemicolons(), + 'strict types' => $config->strictTypes(), + 'error logging level' => $config->errorLoggingLevel(), + 'config file' => [ + 'default config file' => $prettyPath($config->getConfigFile()), + 'local config file' => $prettyPath($config->getLocalConfigFile()), + 'PSYSH_CONFIG env' => $prettyPath($configEnv), + ], + // 'config dir' => $config->getConfigDir(), + // 'data dir' => $config->getDataDir(), + // 'runtime dir' => $config->getRuntimeDir(), + ]; + + // Use an explicit, fresh update check here, rather than relying on whatever is in $config. + $checker = new GitHubChecker(); + $updateAvailable = null; + $latest = null; + try { + $updateAvailable = !$checker->isLatest(); + $latest = $checker->getLatest(); + } catch (\Throwable $e) { + } + + $updates = [ + 'update available' => $updateAvailable, + 'latest release version' => $latest, + 'update check interval' => $config->getUpdateCheck(), + 'update cache file' => $prettyPath($config->getUpdateCheckCacheFile()), + ]; + + $input = [ + 'interactive mode' => $config->interactiveMode(), + 'input interactive' => $config->getInputInteractive(), + 'yolo' => $config->yolo(), + ]; + + if ($config->hasReadline()) { + $info = \readline_info(); + + $readline = [ + 'readline available' => true, + 'readline enabled' => $config->useReadline(), + 'readline service' => \get_class($config->getReadline()), + ]; + + if (isset($info['library_version'])) { + $readline['readline library'] = $info['library_version']; + } + + if (isset($info['readline_name']) && $info['readline_name'] !== '') { + $readline['readline name'] = $info['readline_name']; + } + } else { + $readline = [ + 'readline available' => false, + ]; + } + + $output = [ + 'color mode' => $config->colorMode(), + 'output decorated' => $config->getOutputDecorated(), + 'output verbosity' => $config->verbosity(), + 'output pager' => $config->getPager(), + ]; + + $theme = $config->theme(); + // @todo show styles (but only if they're different than default?) + $output['theme'] = [ + 'compact' => $theme->compact(), + 'prompt' => $theme->prompt(), + 'bufferPrompt' => $theme->bufferPrompt(), + 'replayPrompt' => $theme->replayPrompt(), + 'returnValue' => $theme->returnValue(), + ]; + + $pcntl = [ + 'pcntl available' => ProcessForker::isPcntlSupported(), + 'posix available' => ProcessForker::isPosixSupported(), + ]; + + if ($disabledPcntl = ProcessForker::disabledPcntlFunctions()) { + $pcntl['disabled pcntl functions'] = $disabledPcntl; + } + + if ($disabledPosix = ProcessForker::disabledPosixFunctions()) { + $pcntl['disabled posix functions'] = $disabledPosix; + } + + $pcntl['use pcntl'] = $config->usePcntl(); + + $history = [ + 'history file' => $prettyPath($config->getHistoryFile()), + 'history size' => $config->getHistorySize(), + 'erase duplicates' => $config->getEraseDuplicates(), + ]; + + $docs = [ + 'manual db file' => $prettyPath($config->getManualDbFile()), + 'sqlite available' => true, + ]; + + try { + if ($db = $config->getManualDb()) { + if ($q = $db->query('SELECT * FROM meta;')) { + $q->setFetchMode(\PDO::FETCH_KEY_PAIR); + $meta = $q->fetchAll(); + + foreach ($meta as $key => $val) { + switch ($key) { + case 'built_at': + $d = new \DateTime('@'.$val); + $val = $d->format(\DateTime::RFC2822); + break; + } + $key = 'db '.\str_replace('_', ' ', $key); + $docs[$key] = $val; + } + } else { + $docs['db schema'] = '0.1.0'; + } + } + } catch (Exception\RuntimeException $e) { + if ($e->getMessage() === 'SQLite PDO driver not found') { + $docs['sqlite available'] = false; + } else { + throw $e; + } + } + + $autocomplete = [ + 'tab completion enabled' => $config->useTabCompletion(), + 'bracketed paste' => $config->useBracketedPaste(), + ]; + + // Shenanigans, but totally justified. + try { + if ($shell = Sudo::fetchProperty($config, 'shell')) { + $shellClass = \get_class($shell); + if ($shellClass !== 'Psy\\Shell') { + $shellInfo = [ + 'PsySH version' => $shell::VERSION, + 'Shell class' => $shellClass, + ]; + } + + try { + $core['loop listeners'] = \array_map('get_class', Sudo::fetchProperty($shell, 'loopListeners')); + } catch (\ReflectionException $e) { + // shrug + } + + $core['commands'] = \array_map('get_class', $shell->all()); + + try { + $autocomplete['custom matchers'] = \array_map('get_class', Sudo::fetchProperty($shell, 'matchers')); + } catch (\ReflectionException $e) { + // shrug + } + } + } catch (\ReflectionException $e) { + // shrug + } + + // @todo Show Presenter / custom casters. + + return \array_merge($shellInfo, $core, \compact('updates', 'pcntl', 'input', 'readline', 'output', 'history', 'docs', 'autocomplete')); + } +} + +if (!\function_exists('Psy\\bin')) { + /** + * `psysh` command line executable. + * + * @return \Closure + */ + function bin(): \Closure + { + return function () { + if (!isset($_SERVER['PSYSH_IGNORE_ENV']) || !$_SERVER['PSYSH_IGNORE_ENV']) { + if (\defined('HHVM_VERSION_ID')) { + \fwrite(\STDERR, 'PsySH v0.11 and higher does not support HHVM. Install an older version, or set the environment variable PSYSH_IGNORE_ENV=1 to override this restriction and proceed anyway.'.\PHP_EOL); + exit(1); + } + + if (\PHP_VERSION_ID < 70400) { + \fwrite(\STDERR, 'PHP 7.4.0 or higher is required. You can set the environment variable PSYSH_IGNORE_ENV=1 to override this restriction and proceed anyway.'.\PHP_EOL); + exit(1); + } + + if (\PHP_VERSION_ID > 89999) { + \fwrite(\STDERR, 'PHP 9 or higher is not supported. You can set the environment variable PSYSH_IGNORE_ENV=1 to override this restriction and proceed anyway.'.\PHP_EOL); + exit(1); + } + + if (!\function_exists('json_encode')) { + \fwrite(\STDERR, 'The JSON extension is required. Please install it. You can set the environment variable PSYSH_IGNORE_ENV=1 to override this restriction and proceed anyway.'.\PHP_EOL); + exit(1); + } + + if (!\function_exists('token_get_all')) { + \fwrite(\STDERR, 'The Tokenizer extension is required. Please install it. You can set the environment variable PSYSH_IGNORE_ENV=1 to override this restriction and proceed anyway.'.\PHP_EOL); + exit(1); + } + } + + $usageException = null; + $shellIsPhar = Shell::isPhar(); + + $input = new ArgvInput(); + try { + $input->bind(new InputDefinition(\array_merge(Configuration::getInputOptions(), [ + new InputOption('help', 'h', InputOption::VALUE_NONE), + new InputOption('version', 'V', InputOption::VALUE_NONE), + new InputOption('self-update', 'u', InputOption::VALUE_NONE), + + new InputArgument('include', InputArgument::IS_ARRAY), + ]))); + } catch (\RuntimeException $e) { + $usageException = $e; + } + + try { + $config = Configuration::fromInput($input); + } catch (\InvalidArgumentException $e) { + $usageException = $e; + } + + // Handle --help + if (!isset($config) || $usageException !== null || $input->getOption('help')) { + if ($usageException !== null) { + echo $usageException->getMessage().\PHP_EOL.\PHP_EOL; + } + + $version = Shell::getVersionHeader(false); + $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : []; + $name = $argv ? \basename(\reset($argv)) : 'psysh'; + + echo <<<EOL +$version + +Usage: + $name [--version] [--help] [files...] + +Options: + -h, --help Display this help message. + -c, --config FILE Use an alternate PsySH config file location. + --cwd PATH Use an alternate working directory. + -V, --version Display the PsySH version. + +EOL; + if ($shellIsPhar) { + echo <<<EOL + -u, --self-update Install a newer version if available. + +EOL; + } + echo <<<EOL + --color Force colors in output. + --no-color Disable colors in output. + -i, --interactive Force PsySH to run in interactive mode. + -n, --no-interactive Run PsySH without interactive input. Requires input from stdin. + -r, --raw-output Print var_export-style return values (for non-interactive input) + --compact Run PsySH with compact output. + -q, --quiet Shhhhhh. + -v|vv|vvv, --verbose Increase the verbosity of messages. + --yolo Run PsySH without input validation. You don't want this. + +EOL; + + exit($usageException === null ? 0 : 1); + } + + // Handle --version + if ($input->getOption('version')) { + echo Shell::getVersionHeader($config->useUnicode()).\PHP_EOL; + exit(0); + } + + // Handle --self-update + if ($input->getOption('self-update')) { + if (!$shellIsPhar) { + \fwrite(\STDERR, 'The --self-update option can only be used with with a phar based install.'.\PHP_EOL); + exit(1); + } + $selfUpdate = new SelfUpdate(new GitHubChecker(), new Installer()); + $result = $selfUpdate->run($input, $config->getOutput()); + exit($result); + } + + $shell = new Shell($config); + + // Pass additional arguments to Shell as 'includes' + $shell->setIncludes($input->getArgument('include')); + + try { + // And go! + $shell->run(); + } catch (\Throwable $e) { + \fwrite(\STDERR, $e->getMessage().\PHP_EOL); + + // @todo this triggers the "exited unexpectedly" logic in the + // ForkingLoop, so we can't exit(1) after starting the shell... + // fix this :) + + // exit(1); + } + }; + } +} diff --git a/php/libraries/composer/vendor/ralouphie/getallheaders/LICENSE b/php/libraries/composer/vendor/ralouphie/getallheaders/LICENSE new file mode 100644 index 0000000..be5540c --- /dev/null +++ b/php/libraries/composer/vendor/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/php/libraries/composer/vendor/ralouphie/getallheaders/README.md b/php/libraries/composer/vendor/ralouphie/getallheaders/README.md new file mode 100644 index 0000000..9430d76 --- /dev/null +++ b/php/libraries/composer/vendor/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/php/libraries/composer/vendor/ralouphie/getallheaders/composer.json b/php/libraries/composer/vendor/ralouphie/getallheaders/composer.json new file mode 100644 index 0000000..de8ce62 --- /dev/null +++ b/php/libraries/composer/vendor/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/php/libraries/composer/vendor/ralouphie/getallheaders/src/getallheaders.php b/php/libraries/composer/vendor/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 0000000..c7285a5 --- /dev/null +++ b/php/libraries/composer/vendor/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ +<?php + +if (!function_exists('getallheaders')) { + + /** + * Get all HTTP header key/values as an associative array for the current request. + * + * @return string[string] The HTTP header key/value pairs. + */ + function getallheaders() + { + $headers = array(); + + $copy_server = array( + 'CONTENT_TYPE' => 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/php/libraries/composer/vendor/ramsey/collection/LICENSE b/php/libraries/composer/vendor/ramsey/collection/LICENSE new file mode 100644 index 0000000..a7fcf12 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-2022 Ben Ramsey <ben@benramsey.com> + +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/php/libraries/composer/vendor/ramsey/collection/README.md b/php/libraries/composer/vendor/ramsey/collection/README.md new file mode 100644 index 0000000..c77ffcb --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/README.md @@ -0,0 +1,70 @@ +<h1 align="center">ramsey/collection</h1> + +<p align="center"> + <strong>A PHP library for representing and manipulating collections.</strong> +</p> + +<p align="center"> + <a href="https://github.com/ramsey/collection"><img src="http://img.shields.io/badge/source-ramsey/collection-blue.svg?style=flat-square" alt="Source Code"></a> + <a href="https://packagist.org/packages/ramsey/collection"><img src="https://img.shields.io/packagist/v/ramsey/collection.svg?style=flat-square&label=release" alt="Download Package"></a> + <a href="https://php.net"><img src="https://img.shields.io/packagist/php-v/ramsey/collection.svg?style=flat-square&colorB=%238892BF" alt="PHP Programming Language"></a> + <a href="https://github.com/ramsey/collection/blob/master/LICENSE"><img src="https://img.shields.io/packagist/l/ramsey/collection.svg?style=flat-square&colorB=darkcyan" alt="Read License"></a> + <a href="https://github.com/ramsey/collection/actions/workflows/continuous-integration.yml"><img src="https://img.shields.io/github/actions/workflow/status/ramsey/collection/continuous-integration.yml?branch=main&logo=github&style=flat-square" alt="Build Status"></a> + <a href="https://codecov.io/gh/ramsey/collection"><img src="https://img.shields.io/codecov/c/gh/ramsey/collection?label=codecov&logo=codecov&style=flat-square" alt="Codecov Code Coverage"></a> + <a href="https://shepherd.dev/github/ramsey/collection"><img src="https://img.shields.io/endpoint?style=flat-square&url=https%3A%2F%2Fshepherd.dev%2Fgithub%2Framsey%2Fcollection%2Fcoverage" alt="Psalm Type Coverage"></a> +</p> + +## About + +ramsey/collection is a PHP library for representing and manipulating collections. + +Much inspiration for this library came from the [Java Collections Framework][java]. + +This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). +By participating in this project and its community, you are expected to +uphold this code. + +## Installation + +Install this package as a dependency using [Composer](https://getcomposer.org). + +``` bash +composer require ramsey/collection +``` + +## Usage + +Examples of how to use this library may be found in the +[Wiki pages](https://github.com/ramsey/collection/wiki/Examples). + +## Contributing + +Contributions are welcome! To contribute, please familiarize yourself with +[CONTRIBUTING.md](CONTRIBUTING.md). + +## Coordinated Disclosure + +Keeping user information safe and secure is a top priority, and we welcome the +contribution of external security researchers. If you believe you've found a +security issue in software that is maintained in this repository, please read +[SECURITY.md][] for instructions on submitting a vulnerability report. + +## ramsey/collection for Enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of ramsey/collection and thousands of other packages are working +with Tidelift to deliver commercial support and maintenance for the open source +packages you use to build your applications. Save time, reduce risk, and improve +code health, while paying the maintainers of the exact packages you use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-ramsey-collection?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Copyright and License + +The ramsey/collection library is copyright © [Ben Ramsey](https://benramsey.com) +and licensed for use under the terms of the +MIT License (MIT). Please see [LICENSE](LICENSE) for more information. + + +[java]: http://docs.oracle.com/javase/8/docs/technotes/guides/collections/index.html +[security.md]: https://github.com/ramsey/collection/blob/main/SECURITY.md diff --git a/php/libraries/composer/vendor/ramsey/collection/SECURITY.md b/php/libraries/composer/vendor/ramsey/collection/SECURITY.md new file mode 100644 index 0000000..3de4c0c --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/SECURITY.md @@ -0,0 +1,169 @@ +<!-- + This policy template was created using the HackerOne Policy Builder [1], + with guidance from the National Telecommunications and Information + Administration Coordinated Vulnerability Disclosure Template [2]. + --> + +# Vulnerability Disclosure Policy (VDP) + +## Brand Promise + +<!-- + This is your brand promise. Its objective is to "demonstrate a clear, good + faith commitment to customers and other stakeholders potentially impacted by + security vulnerabilities" [2]. +--> + +Keeping user information safe and secure is a top priority, and we welcome the +contribution of external security researchers. + +## Scope + +<!-- + This is your initial scope. It tells vulnerability finders and reporters + "which systems and capabilities are 'fair game' versus 'off limits'" [2]. + For software packages, this is often a list of currently maintained versions + of the package. +--> + +If you believe you've found a security issue in software that is maintained in +this repository, we encourage you to notify us. + +| Version | In scope | Source code | +| ------- | :------: | ----------- | +| latest | ✅ | https://github.com/ramsey/collection | + +## How to Submit a Report + +<!-- + This is your communication process. It tells security researchers how to + contact you to report a vulnerability. It may be a link to a web form that + uses HTTPS for secure communication, or it may be an email address. + Optionally, you may choose to include a PGP public key, so that researchers + may send you encrypted messages. +--> + +To submit a vulnerability report, please contact us at security@ramsey.dev. +Your submission will be reviewed and validated by a member of our team. + +## Safe Harbor + +<!-- + This section assures vulnerability finders and reporters that they will + receive good faith responses to their good faith acts. In other words, + "we will not take legal action if..." [2]. +--> + +We support safe harbor for security researchers who: + +* Make a good faith effort to avoid privacy violations, destruction of data, and + interruption or degradation of our services. +* Only interact with accounts you own or with explicit permission of the account + holder. If you do encounter Personally Identifiable Information (PII) contact + us immediately, do not proceed with access, and immediately purge any local + information. +* Provide us with a reasonable amount of time to resolve vulnerabilities prior + to any disclosure to the public or a third party. + +We will consider activities conducted consistent with this policy to constitute +"authorized" conduct and will not pursue civil action or initiate a complaint to +law enforcement. We will help to the extent we can if legal action is initiated +by a third party against you. + +Please submit a report to us before engaging in conduct that may be inconsistent +with or unaddressed by this policy. + +## Preferences + +<!-- + The preferences section sets expectations based on priority and submission + volume, rather than legal objection or restriction [2]. + + According to the NTIA [2]: + + This section is a living document that sets expectations for preferences + and priorities, typically maintained by the support and engineering + team. This can outline classes of vulnerabilities, reporting style + (crash dumps, CVSS scoring, proof-of-concept, etc.), tools, etc. Too + many preferences can set the wrong tone or make reporting findings + difficult to navigate. This section also sets expectations to the + researcher community for what types of issues are considered important + or not. +--> + +* Please provide detailed reports with reproducible steps and a clearly defined + impact. +* Include the version number of the vulnerable package in your report +* Social engineering (e.g. phishing, vishing, smishing) is prohibited. + +<!-- + References + + [1] HackerOne. Policy builder. Retrieved from https://hackerone.com/policy-builder/ + + [2] NTIA Safety Working Group. 2016. "Early stage" coordinated vulnerability + disclosure template: Version 1.1. (15 December 2016). Retrieved from + https://www.ntia.doc.gov/files/ntia/publications/ntia_vuln_disclosure_early_stage_template.pdf +--> + +## Encryption Key for security@ramsey.dev + +For increased privacy when reporting sensitive issues, you may encrypt your +message using the following public key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBF+Z9gEBEACbT/pIx8RR0K18t8Z2rDnmEV44YdT7HNsMdq+D6SAlx8UUb6AU +jGIbV9dgBgGNtOLU1pxloaJwL9bWIRbj+X/Qb2WNIP//Vz1Y40ox1dSpfCUrizXx +kb4p58Xml0PsB8dg3b4RDUgKwGC37ne5xmDnigyJPbiB2XJ6Xc46oPCjh86XROTK +wEBB2lY67ClBlSlvC2V9KmbTboRQkLdQDhOaUosMb99zRb0EWqDLaFkZVjY5HI7i +0pTveE6dI12NfHhTwKjZ5pUiAZQGlKA6J1dMjY2unxHZkQj5MlMfrLSyJHZxccdJ +xD94T6OTcTHt/XmMpI2AObpewZDdChDQmcYDZXGfAhFoJmbvXsmLMGXKgzKoZ/ls +RmLsQhh7+/r8E+Pn5r+A6Hh4uAc14ApyEP0ckKeIXw1C6pepHM4E8TEXVr/IA6K/ +z6jlHORixIFX7iNOnfHh+qwOgZw40D6JnBfEzjFi+T2Cy+JzN2uy7I8UnecTMGo3 +5t6astPy6xcH6kZYzFTV7XERR6LIIVyLAiMFd8kF5MbJ8N5ElRFsFHPW+82N2HDX +c60iSaTB85k6R6xd8JIKDiaKE4sSuw2wHFCKq33d/GamYezp1wO+bVUQg88efljC +2JNFyD+vl30josqhw1HcmbE1TP3DlYeIL5jQOlxCMsgai6JtTfHFM/5MYwARAQAB +tBNzZWN1cml0eUByYW1zZXkuZGV2iQJUBBMBCAA+FiEE4drPD+/ofZ570fAYq0bv +vXQCywIFAl+Z9gECGwMFCQeGH4AFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AACgkQ +q0bvvXQCywIkEA//Qcwv8MtTCy01LHZd9c7VslwhNdXQDYymcTyjcYw8x7O22m4B +3hXE6vqAplFhVxxkqXB2ef0tQuzxhPHNJgkCE4Wq4i+V6qGpaSVHQT2W6DN/NIhL +vS8OdScc6zddmIbIkSrzVVAtjwehFNEIrX3DnbbbK+Iku7vsKT5EclOluIsjlYoX +goW8IeReyDBqOe2H3hoCGw6EA0D/NYV2bJnfy53rXVIyarsXXeOLp7eNEH6Td7aW +PVSrMZJe1t+knrEGnEdrXWzlg4lCJJCtemGv+pKBUomnyISXSdqyoRCCzvQjqyig +2kRebUX8BXPW33p4OXPj9sIboUOjZwormWwqqbFMO+J4TiVCUoEoheI7emPFRcNN +QtPJrjbY1++OznBc0GRpfeUkGoU1cbRl1bnepnFIZMTDLkrVW6I1Y4q8ZVwX3BkE +N81ctFrRpHBlU36EdHvjPQmGtuiL77Qq3fWmMv7yTvK1wHJAXfEb0ZJWHZCbck3w +l0CVq0Z+UUAOM8Rp1N0N8m92xtapav0qCFU9qzf2J5qX6GRmWv+d29wPgFHzDWBm +nnrYYIA4wJLx00U6SMcVBSnNe91B+RfGY5XQhbWPjQQecOGCSDsxaFAq2MeOVJyZ +bIjLYfG9GxoLKr5R7oLRJvZI4nKKBc1Kci/crZbdiSdQhSQGlDz88F1OHeCIdQQQ +EQgAHRYhBOhdAxHd+lus86YQ57Atl5icjAcbBQJfmfdIAAoJELAtl5icjAcbFVcA +/1LqB3ZjsnXDAvvAXZVjSPqofSlpMLeRQP6IM/A9Odq0AQCZrtZc1knOMGEcjppK +Rk+sy/R0Mshy8TDuaZIRgh2Ux7kCDQRfmfYBARAAmchKzzVz7IaEq7PnZDb3szQs +T/+E9F3m39yOpV4fEB1YzObonFakXNT7Gw2tZEx0eitUMqQ/13jjfu3UdzlKl2bR +qA8LrSQRhB+PTC9A1XvwxCUYhhjGiLzJ9CZL6hBQB43qHOmE9XJPme90geLsF+gK +u39Waj1SNWzwGg+Gy1Gl5f2AJoDTxznreCuFGj+Vfaczt/hlfgqpOdb9jsmdoE7t +3DSWppA9dRHWwQSgE6J28rR4QySBcqyXS6IMykqaJn7Z26yNIaITLnHCZOSY8zhP +ha7GFsN549EOCgECbrnPt9dmI2+hQE0RO0e7SOBNsIf5sz/i7urhwuj0CbOqhjc2 +X1AEVNFCVcb6HPi/AWefdFCRu0gaWQxn5g+9nkq5slEgvzCCiKYzaBIcr8qR6Hb4 +FaOPVPxO8vndRouq57Ws8XpAwbPttioFuCqF4u9K+tK/8e2/R8QgRYJsE3Cz/Fu8 ++pZFpMnqbDEbK3DL3ss+1ed1sky+mDV8qXXeI33XW5hMFnk1JWshUjHNlQmE6ftC +U0xSTMVUtwJhzH2zDp8lEdu7qi3EsNULOl68ozDr6soWAvCbHPeTdTOnFySGCleG +/3TonsoZJs/sSPPJnxFQ1DtgQL6EbhIwa0ZwU4eKYVHZ9tjxuMX3teFzRvOrJjgs ++ywGlsIURtEckT5Y6nMAEQEAAYkCPAQYAQgAJhYhBOHazw/v6H2ee9HwGKtG7710 +AssCBQJfmfYBAhsMBQkHhh+AAAoJEKtG7710AssC8NcP/iDAcy1aZFvkA0EbZ85p +i7/+ywtE/1wF4U4/9OuLcoskqGGnl1pJNPooMOSBCfreoTB8HimT0Fln0CoaOm4Q +pScNq39JXmf4VxauqUJVARByP6zUfgYarqoaZNeuFF0S4AZJ2HhGzaQPjDz1uKVM +PE6tQSgQkFzdZ9AtRA4vElTH6yRAgmepUsOihk0b0gUtVnwtRYZ8e0Qt3ie97a73 +DxLgAgedFRUbLRYiT0vNaYbainBsLWKpN/T8odwIg/smP0Khjp/ckV60cZTdBiPR +szBTPJESMUTu0VPntc4gWwGsmhZJg/Tt/qP08XYo3VxNYBegyuWwNR66zDWvwvGH +muMv5UchuDxp6Rt3JkIO4voMT1JSjWy9p8krkPEE4V6PxAagLjdZSkt92wVLiK5x +y5gNrtPhU45YdRAKHr36OvJBJQ42CDaZ6nzrzghcIp9CZ7ANHrI+QLRM/csz+AGA +szSp6S4mc1lnxxfbOhPPpebZPn0nIAXoZnnoVKdrxBVedPQHT59ZFvKTQ9Fs7gd3 +sYNuc7tJGFGC2CxBH4ANDpOQkc5q9JJ1HSGrXU3juxIiRgfA26Q22S9c71dXjElw +Ri584QH+bL6kkYmm8xpKF6TVwhwu5xx/jBPrbWqFrtbvLNrnfPoapTihBfdIhkT6 +nmgawbBHA02D5xEqB5SU3WJu +=eJNx +-----END PGP PUBLIC KEY BLOCK----- +``` diff --git a/php/libraries/composer/vendor/ramsey/collection/composer.json b/php/libraries/composer/vendor/ramsey/collection/composer.json new file mode 100644 index 0000000..5670901 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/composer.json @@ -0,0 +1,119 @@ +{ + "name": "ramsey/collection", + "description": "A PHP library for representing and manipulating collections.", + "license": "MIT", + "type": "library", + "keywords": [ + "array", + "collection", + "hash", + "map", + "queue", + "set" + ], + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" + } + ], + "require": { + "php": "^8.1" + }, + "require-dev": { + "captainhook/plugin-composer": "^5.3", + "ergebnis/composer-normalize": "^2.28.3", + "fakerphp/faker": "^1.21", + "hamcrest/hamcrest-php": "^2.0", + "jangregor/phpstan-prophecy": "^1.0", + "mockery/mockery": "^1.5", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpcsstandards/phpcsutils": "^1.0.0-rc1", + "phpspec/prophecy-phpunit": "^2.0", + "phpstan/extension-installer": "^1.2", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.3", + "phpunit/phpunit": "^9.5", + "psalm/plugin-mockery": "^1.1", + "psalm/plugin-phpunit": "^0.18.4", + "ramsey/coding-standard": "^2.0.3", + "ramsey/conventional-commits": "^1.3", + "vimeo/psalm": "^5.4" + }, + "minimum-stability": "RC", + "prefer-stable": true, + "autoload": { + "psr-4": { + "Ramsey\\Collection\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Ramsey\\Collection\\Test\\": "tests/", + "Ramsey\\Test\\Generics\\": "tests/generics/" + }, + "files": [ + "vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest.php" + ] + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true, + "ergebnis/composer-normalize": true, + "phpstan/extension-installer": true, + "captainhook/plugin-composer": true + }, + "sort-packages": true + }, + "extra": { + "captainhook": { + "force-install": true + }, + "ramsey/conventional-commits": { + "configFile": "conventional-commits.json" + } + }, + "scripts": { + "dev:analyze": [ + "@dev:analyze:phpstan", + "@dev:analyze:psalm" + ], + "dev:analyze:phpstan": "phpstan analyse --ansi --memory-limit=1G", + "dev:analyze:psalm": "psalm", + "dev:build:clean": "git clean -fX build/", + "dev:lint": [ + "@dev:lint:syntax", + "@dev:lint:style" + ], + "dev:lint:fix": "phpcbf", + "dev:lint:style": "phpcs --colors", + "dev:lint:syntax": "parallel-lint --colors src/ tests/", + "dev:test": [ + "@dev:lint", + "@dev:analyze", + "@dev:test:unit" + ], + "dev:test:coverage:ci": "phpunit --colors=always --coverage-text --coverage-clover build/coverage/clover.xml --coverage-cobertura build/coverage/cobertura.xml --coverage-crap4j build/coverage/crap4j.xml --coverage-xml build/coverage/coverage-xml --log-junit build/junit.xml", + "dev:test:coverage:html": "phpunit --colors=always --coverage-html build/coverage/coverage-html/", + "dev:test:unit": "phpunit --colors=always", + "test": "@dev:test" + }, + "scripts-descriptions": { + "dev:analyze": "Runs all static analysis checks.", + "dev:analyze:phpstan": "Runs the PHPStan static analyzer.", + "dev:analyze:psalm": "Runs the Psalm static analyzer.", + "dev:build:clean": "Cleans the build/ directory.", + "dev:lint": "Runs all linting checks.", + "dev:lint:fix": "Auto-fixes coding standards issues, if possible.", + "dev:lint:style": "Checks for coding standards issues.", + "dev:lint:syntax": "Checks for syntax errors.", + "dev:test": "Runs linting, static analysis, and unit tests.", + "dev:test:coverage:ci": "Runs unit tests and generates CI coverage reports.", + "dev:test:coverage:html": "Runs unit tests and generates HTML coverage report.", + "dev:test:unit": "Runs unit tests.", + "test": "Runs linting, static analysis, and unit tests." + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/conventional-commits.json b/php/libraries/composer/vendor/ramsey/collection/conventional-commits.json new file mode 100644 index 0000000..5fe21d2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/conventional-commits.json @@ -0,0 +1,22 @@ +{ + "typeCase": "kebab", + "types": [ + "chore", + "ci", + "docs", + "feat", + "fix", + "refactor", + "security", + "style", + "test" + ], + "scopeCase": "kebab", + "scopeRequired": false, + "scopes": [], + "descriptionCase": null, + "descriptionEndMark": "", + "bodyRequired": false, + "bodyWrapWidth": 72, + "requiredFooters": [] +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/AbstractArray.php b/php/libraries/composer/vendor/ramsey/collection/src/AbstractArray.php new file mode 100644 index 0000000..5ce622a --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/AbstractArray.php @@ -0,0 +1,171 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use ArrayIterator; +use Traversable; + +use function count; + +/** + * This class provides a basic implementation of `ArrayInterface`, to minimize + * the effort required to implement this interface. + * + * @template T + * @implements ArrayInterface<T> + */ +abstract class AbstractArray implements ArrayInterface +{ + /** + * The items of this array. + * + * @var array<array-key, T> + */ + protected array $data = []; + + /** + * Constructs a new array object. + * + * @param array<array-key, T> $data The initial items to add to this array. + */ + public function __construct(array $data = []) + { + // Invoke offsetSet() for each value added; in this way, sub-classes + // may provide additional logic about values added to the array object. + foreach ($data as $key => $value) { + $this[$key] = $value; + } + } + + /** + * Returns an iterator for this array. + * + * @link http://php.net/manual/en/iteratoraggregate.getiterator.php IteratorAggregate::getIterator() + * + * @return Traversable<array-key, T> + */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->data); + } + + /** + * Returns `true` if the given offset exists in this array. + * + * @link http://php.net/manual/en/arrayaccess.offsetexists.php ArrayAccess::offsetExists() + * + * @param array-key $offset The offset to check. + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->data[$offset]); + } + + /** + * Returns the value at the specified offset. + * + * @link http://php.net/manual/en/arrayaccess.offsetget.php ArrayAccess::offsetGet() + * + * @param array-key $offset The offset for which a value should be returned. + * + * @return T the value stored at the offset, or null if the offset + * does not exist. + */ + public function offsetGet(mixed $offset): mixed + { + return $this->data[$offset]; + } + + /** + * Sets the given value to the given offset in the array. + * + * @link http://php.net/manual/en/arrayaccess.offsetset.php ArrayAccess::offsetSet() + * + * @param array-key | null $offset The offset to set. If `null`, the value + * may be set at a numerically-indexed offset. + * @param T $value The value to set at the given offset. + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === null) { + $this->data[] = $value; + } else { + $this->data[$offset] = $value; + } + } + + /** + * Removes the given offset and its value from the array. + * + * @link http://php.net/manual/en/arrayaccess.offsetunset.php ArrayAccess::offsetUnset() + * + * @param array-key $offset The offset to remove from the array. + */ + public function offsetUnset(mixed $offset): void + { + unset($this->data[$offset]); + } + + /** + * Returns data suitable for PHP serialization. + * + * @link https://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.serialize + * @link https://www.php.net/serialize + * + * @return array<array-key, T> + */ + public function __serialize(): array + { + return $this->data; + } + + /** + * Adds unserialized data to the object. + * + * @param array<array-key, T> $data + */ + public function __unserialize(array $data): void + { + $this->data = $data; + } + + /** + * Returns the number of items in this array. + * + * @link http://php.net/manual/en/countable.count.php Countable::count() + */ + public function count(): int + { + return count($this->data); + } + + public function clear(): void + { + $this->data = []; + } + + /** + * @inheritDoc + */ + public function toArray(): array + { + return $this->data; + } + + public function isEmpty(): bool + { + return $this->data === []; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/AbstractCollection.php b/php/libraries/composer/vendor/ramsey/collection/src/AbstractCollection.php new file mode 100644 index 0000000..8cb21ec --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/AbstractCollection.php @@ -0,0 +1,393 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use Closure; +use Ramsey\Collection\Exception\CollectionMismatchException; +use Ramsey\Collection\Exception\InvalidArgumentException; +use Ramsey\Collection\Exception\InvalidPropertyOrMethod; +use Ramsey\Collection\Exception\NoSuchElementException; +use Ramsey\Collection\Exception\UnsupportedOperationException; +use Ramsey\Collection\Tool\TypeTrait; +use Ramsey\Collection\Tool\ValueExtractorTrait; +use Ramsey\Collection\Tool\ValueToStringTrait; + +use function array_filter; +use function array_key_first; +use function array_key_last; +use function array_map; +use function array_merge; +use function array_reduce; +use function array_search; +use function array_udiff; +use function array_uintersect; +use function in_array; +use function is_int; +use function is_object; +use function spl_object_id; +use function sprintf; +use function usort; + +/** + * This class provides a basic implementation of `CollectionInterface`, to + * minimize the effort required to implement this interface + * + * @template T + * @extends AbstractArray<T> + * @implements CollectionInterface<T> + */ +abstract class AbstractCollection extends AbstractArray implements CollectionInterface +{ + use TypeTrait; + use ValueToStringTrait; + use ValueExtractorTrait; + + /** + * @throws InvalidArgumentException if $element is of the wrong type. + */ + public function add(mixed $element): bool + { + $this[] = $element; + + return true; + } + + public function contains(mixed $element, bool $strict = true): bool + { + return in_array($element, $this->data, $strict); + } + + /** + * @throws InvalidArgumentException if $element is of the wrong type. + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($this->checkType($this->getType(), $value) === false) { + throw new InvalidArgumentException( + 'Value must be of type ' . $this->getType() . '; value is ' + . $this->toolValueToString($value), + ); + } + + if ($offset === null) { + $this->data[] = $value; + } else { + $this->data[$offset] = $value; + } + } + + public function remove(mixed $element): bool + { + if (($position = array_search($element, $this->data, true)) !== false) { + unset($this[$position]); + + return true; + } + + return false; + } + + /** + * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist + * on the elements in this collection. + * @throws UnsupportedOperationException if unable to call column() on this + * collection. + * + * @inheritDoc + */ + public function column(string $propertyOrMethod): array + { + $temp = []; + + foreach ($this->data as $item) { + /** @psalm-suppress MixedAssignment */ + $temp[] = $this->extractValue($item, $propertyOrMethod); + } + + return $temp; + } + + /** + * @return T + * + * @throws NoSuchElementException if this collection is empty. + */ + public function first(): mixed + { + $firstIndex = array_key_first($this->data); + + if ($firstIndex === null) { + throw new NoSuchElementException('Can\'t determine first item. Collection is empty'); + } + + return $this->data[$firstIndex]; + } + + /** + * @return T + * + * @throws NoSuchElementException if this collection is empty. + */ + public function last(): mixed + { + $lastIndex = array_key_last($this->data); + + if ($lastIndex === null) { + throw new NoSuchElementException('Can\'t determine last item. Collection is empty'); + } + + return $this->data[$lastIndex]; + } + + /** + * @return CollectionInterface<T> + * + * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist + * on the elements in this collection. + * @throws UnsupportedOperationException if unable to call sort() on this + * collection. + */ + public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascending): CollectionInterface + { + $collection = clone $this; + + usort( + $collection->data, + /** + * @param T $a + * @param T $b + */ + function (mixed $a, mixed $b) use ($propertyOrMethod, $order): int { + /** @var mixed $aValue */ + $aValue = $this->extractValue($a, $propertyOrMethod); + + /** @var mixed $bValue */ + $bValue = $this->extractValue($b, $propertyOrMethod); + + return ($aValue <=> $bValue) * ($order === Sort::Descending ? -1 : 1); + }, + ); + + return $collection; + } + + /** + * @param callable(T): bool $callback A callable to use for filtering elements. + * + * @return CollectionInterface<T> + */ + public function filter(callable $callback): CollectionInterface + { + $collection = clone $this; + $collection->data = array_merge([], array_filter($collection->data, $callback)); + + return $collection; + } + + /** + * @return CollectionInterface<T> + * + * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist + * on the elements in this collection. + * @throws UnsupportedOperationException if unable to call where() on this + * collection. + */ + public function where(?string $propertyOrMethod, mixed $value): CollectionInterface + { + return $this->filter( + /** + * @param T $item + */ + function (mixed $item) use ($propertyOrMethod, $value): bool { + /** @var mixed $accessorValue */ + $accessorValue = $this->extractValue($item, $propertyOrMethod); + + return $accessorValue === $value; + }, + ); + } + + /** + * @param callable(T): TCallbackReturn $callback A callable to apply to each + * item of the collection. + * + * @return CollectionInterface<TCallbackReturn> + * + * @template TCallbackReturn + */ + public function map(callable $callback): CollectionInterface + { + /** @var Collection<TCallbackReturn> */ + return new Collection('mixed', array_map($callback, $this->data)); + } + + /** + * @param callable(TCarry, T): TCarry $callback A callable to apply to each + * item of the collection to reduce it to a single value. + * @param TCarry $initial This is the initial value provided to the callback. + * + * @return TCarry + * + * @template TCarry + */ + public function reduce(callable $callback, mixed $initial): mixed + { + /** @var TCarry */ + return array_reduce($this->data, $callback, $initial); + } + + /** + * @param CollectionInterface<T> $other The collection to check for divergent + * items. + * + * @return CollectionInterface<T> + * + * @throws CollectionMismatchException if the compared collections are of + * differing types. + */ + public function diff(CollectionInterface $other): CollectionInterface + { + $this->compareCollectionTypes($other); + + $diffAtoB = array_udiff($this->data, $other->toArray(), $this->getComparator()); + $diffBtoA = array_udiff($other->toArray(), $this->data, $this->getComparator()); + + /** @var array<array-key, T> $diff */ + $diff = array_merge($diffAtoB, $diffBtoA); + + $collection = clone $this; + $collection->data = $diff; + + return $collection; + } + + /** + * @param CollectionInterface<T> $other The collection to check for + * intersecting items. + * + * @return CollectionInterface<T> + * + * @throws CollectionMismatchException if the compared collections are of + * differing types. + */ + public function intersect(CollectionInterface $other): CollectionInterface + { + $this->compareCollectionTypes($other); + + /** @var array<array-key, T> $intersect */ + $intersect = array_uintersect($this->data, $other->toArray(), $this->getComparator()); + + $collection = clone $this; + $collection->data = $intersect; + + return $collection; + } + + /** + * @param CollectionInterface<T> ...$collections The collections to merge. + * + * @return CollectionInterface<T> + * + * @throws CollectionMismatchException if unable to merge any of the given + * collections or items within the given collections due to type + * mismatch errors. + */ + public function merge(CollectionInterface ...$collections): CollectionInterface + { + $mergedCollection = clone $this; + + foreach ($collections as $index => $collection) { + if (!$collection instanceof static) { + throw new CollectionMismatchException( + sprintf('Collection with index %d must be of type %s', $index, static::class), + ); + } + + // When using generics (Collection.php, Set.php, etc), + // we also need to make sure that the internal types match each other + if ($this->getUniformType($collection) !== $this->getUniformType($this)) { + throw new CollectionMismatchException( + sprintf( + 'Collection items in collection with index %d must be of type %s', + $index, + $this->getType(), + ), + ); + } + + foreach ($collection as $key => $value) { + if (is_int($key)) { + $mergedCollection[] = $value; + } else { + $mergedCollection[$key] = $value; + } + } + } + + return $mergedCollection; + } + + /** + * @param CollectionInterface<T> $other + * + * @throws CollectionMismatchException + */ + private function compareCollectionTypes(CollectionInterface $other): void + { + if (!$other instanceof static) { + throw new CollectionMismatchException('Collection must be of type ' . static::class); + } + + // When using generics (Collection.php, Set.php, etc), + // we also need to make sure that the internal types match each other + if ($this->getUniformType($other) !== $this->getUniformType($this)) { + throw new CollectionMismatchException('Collection items must be of type ' . $this->getType()); + } + } + + private function getComparator(): Closure + { + return /** + * @param T $a + * @param T $b + */ + function (mixed $a, mixed $b): int { + // If the two values are object, we convert them to unique scalars. + // If the collection contains mixed values (unlikely) where some are objects + // and some are not, we leave them as they are. + // The comparator should still work and the result of $a < $b should + // be consistent but unpredictable since not documented. + if (is_object($a) && is_object($b)) { + $a = spl_object_id($a); + $b = spl_object_id($b); + } + + return $a === $b ? 0 : ($a < $b ? 1 : -1); + }; + } + + /** + * @param CollectionInterface<mixed> $collection + */ + private function getUniformType(CollectionInterface $collection): string + { + return match ($collection->getType()) { + 'integer' => 'int', + 'boolean' => 'bool', + 'double' => 'float', + default => $collection->getType(), + }; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/AbstractSet.php b/php/libraries/composer/vendor/ramsey/collection/src/AbstractSet.php new file mode 100644 index 0000000..7186939 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/AbstractSet.php @@ -0,0 +1,44 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +/** + * This class contains the basic implementation of a collection that does not + * allow duplicated values (a set), to minimize the effort required to implement + * this specific type of collection. + * + * @template T + * @extends AbstractCollection<T> + */ +abstract class AbstractSet extends AbstractCollection +{ + public function add(mixed $element): bool + { + if ($this->contains($element)) { + return false; + } + + return parent::add($element); + } + + public function offsetSet(mixed $offset, mixed $value): void + { + if ($this->contains($value)) { + return; + } + + parent::offsetSet($offset, $value); + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/ArrayInterface.php b/php/libraries/composer/vendor/ramsey/collection/src/ArrayInterface.php new file mode 100644 index 0000000..bc7f6f4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/ArrayInterface.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use ArrayAccess; +use Countable; +use IteratorAggregate; + +/** + * `ArrayInterface` provides traversable array functionality to data types. + * + * @template T + * @extends ArrayAccess<array-key, T> + * @extends IteratorAggregate<array-key, T> + */ +interface ArrayInterface extends + ArrayAccess, + Countable, + IteratorAggregate +{ + /** + * Removes all items from this array. + */ + public function clear(): void; + + /** + * Returns a native PHP array representation of this array object. + * + * @return array<array-key, T> + */ + public function toArray(): array; + + /** + * Returns `true` if this array is empty. + */ + public function isEmpty(): bool; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Collection.php b/php/libraries/composer/vendor/ramsey/collection/src/Collection.php new file mode 100644 index 0000000..44d26bf --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Collection.php @@ -0,0 +1,95 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +/** + * A collection represents a group of objects. + * + * Each object in the collection is of a specific, defined type. + * + * This is a direct implementation of `CollectionInterface`, provided for + * the sake of convenience. + * + * Example usage: + * + * ``` php + * $collection = new \Ramsey\Collection\Collection('My\\Foo'); + * $collection->add(new \My\Foo()); + * $collection->add(new \My\Foo()); + * + * foreach ($collection as $foo) { + * // Do something with $foo + * } + * ``` + * + * It is preferable to subclass `AbstractCollection` to create your own typed + * collections. For example: + * + * ``` php + * namespace My\Foo; + * + * class FooCollection extends \Ramsey\Collection\AbstractCollection + * { + * public function getType() + * { + * return 'My\\Foo'; + * } + * } + * ``` + * + * And then use it similarly to the earlier example: + * + * ``` php + * $fooCollection = new \My\Foo\FooCollection(); + * $fooCollection->add(new \My\Foo()); + * $fooCollection->add(new \My\Foo()); + * + * foreach ($fooCollection as $foo) { + * // Do something with $foo + * } + * ``` + * + * The benefit with this approach is that you may do type-checking on the + * collection object: + * + * ``` php + * if ($collection instanceof \My\Foo\FooCollection) { + * // the collection is a collection of My\Foo objects + * } + * ``` + * + * @template T + * @extends AbstractCollection<T> + */ +class Collection extends AbstractCollection +{ + /** + * Constructs a collection object of the specified type, optionally with the + * specified data. + * + * @param string $collectionType The type or class name associated with this + * collection. + * @param array<array-key, T> $data The initial items to store in the collection. + */ + public function __construct(private readonly string $collectionType, array $data = []) + { + parent::__construct($data); + } + + public function getType(): string + { + return $this->collectionType; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/CollectionInterface.php b/php/libraries/composer/vendor/ramsey/collection/src/CollectionInterface.php new file mode 100644 index 0000000..e3ad014 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/CollectionInterface.php @@ -0,0 +1,253 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use Ramsey\Collection\Exception\CollectionMismatchException; +use Ramsey\Collection\Exception\InvalidArgumentException; +use Ramsey\Collection\Exception\InvalidPropertyOrMethod; +use Ramsey\Collection\Exception\NoSuchElementException; +use Ramsey\Collection\Exception\UnsupportedOperationException; + +/** + * A collection represents a group of values, known as its elements. + * + * Some collections allow duplicate elements and others do not. Some are ordered + * and others unordered. + * + * @template T + * @extends ArrayInterface<T> + */ +interface CollectionInterface extends ArrayInterface +{ + /** + * Ensures that this collection contains the specified element (optional + * operation). + * + * Returns `true` if this collection changed as a result of the call. + * (Returns `false` if this collection does not permit duplicates and + * already contains the specified element.) + * + * Collections that support this operation may place limitations on what + * elements may be added to this collection. In particular, some + * collections will refuse to add `null` elements, and others will impose + * restrictions on the type of elements that may be added. Collection + * classes should clearly specify in their documentation any restrictions + * on what elements may be added. + * + * If a collection refuses to add a particular element for any reason other + * than that it already contains the element, it must throw an exception + * (rather than returning `false`). This preserves the invariant that a + * collection always contains the specified element after this call returns. + * + * @param T $element The element to add to the collection. + * + * @return bool `true` if this collection changed as a result of the call. + * + * @throws InvalidArgumentException if the collection refuses to add the + * $element for any reason other than that it already contains the element. + */ + public function add(mixed $element): bool; + + /** + * Returns `true` if this collection contains the specified element. + * + * @param T $element The element to check whether the collection contains. + * @param bool $strict Whether to perform a strict type check on the value. + */ + public function contains(mixed $element, bool $strict = true): bool; + + /** + * Returns the type associated with this collection. + */ + public function getType(): string; + + /** + * Removes a single instance of the specified element from this collection, + * if it is present. + * + * @param T $element The element to remove from the collection. + * + * @return bool `true` if an element was removed as a result of this call. + */ + public function remove(mixed $element): bool; + + /** + * Returns the values from the given property, method, or array key. + * + * @param string $propertyOrMethod The name of the property, method, or + * array key to evaluate and return. + * + * @return array<int, mixed> + * + * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist + * on the elements in this collection. + * @throws UnsupportedOperationException if unable to call column() on this + * collection. + */ + public function column(string $propertyOrMethod): array; + + /** + * Returns the first item of the collection. + * + * @return T + * + * @throws NoSuchElementException if this collection is empty. + */ + public function first(): mixed; + + /** + * Returns the last item of the collection. + * + * @return T + * + * @throws NoSuchElementException if this collection is empty. + */ + public function last(): mixed; + + /** + * Sort the collection by a property, method, or array key with the given + * sort order. + * + * If $propertyOrMethod is `null`, this will sort by comparing each element. + * + * This will always leave the original collection untouched and will return + * a new one. + * + * @param string | null $propertyOrMethod The property, method, or array key + * to sort by. + * @param Sort $order The sort order for the resulting collection. + * + * @return CollectionInterface<T> + * + * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist + * on the elements in this collection. + * @throws UnsupportedOperationException if unable to call sort() on this + * collection. + */ + public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascending): self; + + /** + * Filter out items of the collection which don't match the criteria of + * given callback. + * + * This will always leave the original collection untouched and will return + * a new one. + * + * See the {@link http://php.net/manual/en/function.array-filter.php PHP array_filter() documentation} + * for examples of how the `$callback` parameter works. + * + * @param callable(T): bool $callback A callable to use for filtering elements. + * + * @return CollectionInterface<T> + */ + public function filter(callable $callback): self; + + /** + * Create a new collection where the result of the given property, method, + * or array key of each item in the collection equals the given value. + * + * This will always leave the original collection untouched and will return + * a new one. + * + * @param string | null $propertyOrMethod The property, method, or array key + * to evaluate. If `null`, the element itself is compared to $value. + * @param mixed $value The value to match. + * + * @return CollectionInterface<T> + * + * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist + * on the elements in this collection. + * @throws UnsupportedOperationException if unable to call where() on this + * collection. + */ + public function where(?string $propertyOrMethod, mixed $value): self; + + /** + * Apply a given callback method on each item of the collection. + * + * This will always leave the original collection untouched. The new + * collection is created by mapping the callback to each item of the + * original collection. + * + * See the {@link http://php.net/manual/en/function.array-map.php PHP array_map() documentation} + * for examples of how the `$callback` parameter works. + * + * @param callable(T): TCallbackReturn $callback A callable to apply to each + * item of the collection. + * + * @return CollectionInterface<TCallbackReturn> + * + * @template TCallbackReturn + */ + public function map(callable $callback): self; + + /** + * Apply a given callback method on each item of the collection + * to reduce it to a single value. + * + * See the {@link http://php.net/manual/en/function.array-reduce.php PHP array_reduce() documentation} + * for examples of how the `$callback` and `$initial` parameters work. + * + * @param callable(TCarry, T): TCarry $callback A callable to apply to each + * item of the collection to reduce it to a single value. + * @param TCarry $initial This is the initial value provided to the callback. + * + * @return TCarry + * + * @template TCarry + */ + public function reduce(callable $callback, mixed $initial): mixed; + + /** + * Create a new collection with divergent items between current and given + * collection. + * + * @param CollectionInterface<T> $other The collection to check for divergent + * items. + * + * @return CollectionInterface<T> + * + * @throws CollectionMismatchException if the compared collections are of + * differing types. + */ + public function diff(CollectionInterface $other): self; + + /** + * Create a new collection with intersecting item between current and given + * collection. + * + * @param CollectionInterface<T> $other The collection to check for + * intersecting items. + * + * @return CollectionInterface<T> + * + * @throws CollectionMismatchException if the compared collections are of + * differing types. + */ + public function intersect(CollectionInterface $other): self; + + /** + * Merge current items and items of given collections into a new one. + * + * @param CollectionInterface<T> ...$collections The collections to merge. + * + * @return CollectionInterface<T> + * + * @throws CollectionMismatchException if unable to merge any of the given + * collections or items within the given collections due to type + * mismatch errors. + */ + public function merge(CollectionInterface ...$collections): self; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/DoubleEndedQueue.php b/php/libraries/composer/vendor/ramsey/collection/src/DoubleEndedQueue.php new file mode 100644 index 0000000..62947a2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/DoubleEndedQueue.php @@ -0,0 +1,166 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use Ramsey\Collection\Exception\InvalidArgumentException; +use Ramsey\Collection\Exception\NoSuchElementException; + +use function array_key_last; +use function array_pop; +use function array_unshift; + +/** + * This class provides a basic implementation of `DoubleEndedQueueInterface`, to + * minimize the effort required to implement this interface. + * + * @template T + * @extends Queue<T> + * @implements DoubleEndedQueueInterface<T> + */ +class DoubleEndedQueue extends Queue implements DoubleEndedQueueInterface +{ + /** + * Constructs a double-ended queue (dequeue) object of the specified type, + * optionally with the specified data. + * + * @param string $queueType The type or class name associated with this dequeue. + * @param array<array-key, T> $data The initial items to store in the dequeue. + */ + public function __construct(private readonly string $queueType, array $data = []) + { + parent::__construct($this->queueType, $data); + } + + /** + * @throws InvalidArgumentException if $element is of the wrong type + */ + public function addFirst(mixed $element): bool + { + if ($this->checkType($this->getType(), $element) === false) { + throw new InvalidArgumentException( + 'Value must be of type ' . $this->getType() . '; value is ' + . $this->toolValueToString($element), + ); + } + + array_unshift($this->data, $element); + + return true; + } + + /** + * @throws InvalidArgumentException if $element is of the wrong type + */ + public function addLast(mixed $element): bool + { + return $this->add($element); + } + + public function offerFirst(mixed $element): bool + { + try { + return $this->addFirst($element); + } catch (InvalidArgumentException) { + return false; + } + } + + public function offerLast(mixed $element): bool + { + return $this->offer($element); + } + + /** + * @return T the first element in this queue. + * + * @throws NoSuchElementException if the queue is empty + */ + public function removeFirst(): mixed + { + return $this->remove(); + } + + /** + * @return T the last element in this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function removeLast(): mixed + { + return $this->pollLast() ?? throw new NoSuchElementException( + 'Can\'t return element from Queue. Queue is empty.', + ); + } + + /** + * @return T | null the head of this queue, or `null` if this queue is empty. + */ + public function pollFirst(): mixed + { + return $this->poll(); + } + + /** + * @return T | null the tail of this queue, or `null` if this queue is empty. + */ + public function pollLast(): mixed + { + return array_pop($this->data); + } + + /** + * @return T the head of this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function firstElement(): mixed + { + return $this->element(); + } + + /** + * @return T the tail of this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function lastElement(): mixed + { + return $this->peekLast() ?? throw new NoSuchElementException( + 'Can\'t return element from Queue. Queue is empty.', + ); + } + + /** + * @return T | null the head of this queue, or `null` if this queue is empty. + */ + public function peekFirst(): mixed + { + return $this->peek(); + } + + /** + * @return T | null the tail of this queue, or `null` if this queue is empty. + */ + public function peekLast(): mixed + { + $lastIndex = array_key_last($this->data); + + if ($lastIndex === null) { + return null; + } + + return $this->data[$lastIndex]; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php b/php/libraries/composer/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php new file mode 100644 index 0000000..15cc0e9 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php @@ -0,0 +1,313 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use Ramsey\Collection\Exception\NoSuchElementException; +use RuntimeException; + +/** + * A linear collection that supports element insertion and removal at both ends. + * + * Most `DoubleEndedQueueInterface` implementations place no fixed limits on the + * number of elements they may contain, but this interface supports + * capacity-restricted double-ended queues as well as those with no fixed size + * limit. + * + * This interface defines methods to access the elements at both ends of the + * double-ended queue. Methods are provided to insert, remove, and examine the + * element. Each of these methods exists in two forms: one throws an exception + * if the operation fails, the other returns a special value (either `null` or + * `false`, depending on the operation). The latter form of the insert operation + * is designed specifically for use with capacity-restricted implementations; in + * most implementations, insert operations cannot fail. + * + * The twelve methods described above are summarized in the following table: + * + * <table> + * <caption>Summary of DoubleEndedQueueInterface methods</caption> + * <thead> + * <tr> + * <th></th> + * <th colspan=2>First Element (Head)</th> + * <th colspan=2>Last Element (Tail)</th> + * </tr> + * <tr> + * <td></td> + * <td><em>Throws exception</em></td> + * <td><em>Special value</em></td> + * <td><em>Throws exception</em></td> + * <td><em>Special value</em></td> + * </tr> + * </thead> + * <tbody> + * <tr> + * <th>Insert</th> + * <td><code>addFirst()</code></td> + * <td><code>offerFirst()</code></td> + * <td><code>addLast()</code></td> + * <td><code>offerLast()</code></td> + * </tr> + * <tr> + * <th>Remove</th> + * <td><code>removeFirst()</code></td> + * <td><code>pollFirst()</code></td> + * <td><code>removeLast()</code></td> + * <td><code>pollLast()</code></td> + * </tr> + * <tr> + * <th>Examine</th> + * <td><code>firstElement()</code></td> + * <td><code>peekFirst()</code></td> + * <td><code>lastElement()</code></td> + * <td><code>peekLast()</code></td> + * </tr> + * </tbody> + * </table> + * + * This interface extends the `QueueInterface`. When a double-ended queue is + * used as a queue, FIFO (first-in-first-out) behavior results. Elements are + * added at the end of the double-ended queue and removed from the beginning. + * The methods inherited from the `QueueInterface` are precisely equivalent to + * `DoubleEndedQueueInterface` methods as indicated in the following table: + * + * <table> + * <caption>Comparison of QueueInterface and DoubleEndedQueueInterface methods</caption> + * <thead> + * <tr> + * <th>QueueInterface Method</th> + * <th>DoubleEndedQueueInterface Method</th> + * </tr> + * </thead> + * <tbody> + * <tr> + * <td><code>add()</code></td> + * <td><code>addLast()</code></td> + * </tr> + * <tr> + * <td><code>offer()</code></td> + * <td><code>offerLast()</code></td> + * </tr> + * <tr> + * <td><code>remove()</code></td> + * <td><code>removeFirst()</code></td> + * </tr> + * <tr> + * <td><code>poll()</code></td> + * <td><code>pollFirst()</code></td> + * </tr> + * <tr> + * <td><code>element()</code></td> + * <td><code>firstElement()</code></td> + * </tr> + * <tr> + * <td><code>peek()</code></td> + * <td><code>peekFirst()</code></td> + * </tr> + * </tbody> + * </table> + * + * Double-ended queues can also be used as LIFO (last-in-first-out) stacks. When + * a double-ended queue is used as a stack, elements are pushed and popped from + * the beginning of the double-ended queue. Stack concepts are precisely + * equivalent to `DoubleEndedQueueInterface` methods as indicated in the table + * below: + * + * <table> + * <caption>Comparison of stack concepts and DoubleEndedQueueInterface methods</caption> + * <thead> + * <tr> + * <th>Stack concept</th> + * <th>DoubleEndedQueueInterface Method</th> + * </tr> + * </thead> + * <tbody> + * <tr> + * <td><em>push</em></td> + * <td><code>addFirst()</code></td> + * </tr> + * <tr> + * <td><em>pop</em></td> + * <td><code>removeFirst()</code></td> + * </tr> + * <tr> + * <td><em>peek</em></td> + * <td><code>peekFirst()</code></td> + * </tr> + * </tbody> + * </table> + * + * Note that the `peek()` method works equally well when a double-ended queue is + * used as a queue or a stack; in either case, elements are drawn from the + * beginning of the double-ended queue. + * + * While `DoubleEndedQueueInterface` implementations are not strictly required + * to prohibit the insertion of `null` elements, they are strongly encouraged to + * do so. Users of any `DoubleEndedQueueInterface` implementations that do allow + * `null` elements are strongly encouraged *not* to take advantage of the + * ability to insert nulls. This is so because `null` is used as a special + * return value by various methods to indicated that the double-ended queue is + * empty. + * + * @template T + * @extends QueueInterface<T> + */ +interface DoubleEndedQueueInterface extends QueueInterface +{ + /** + * Inserts the specified element at the front of this queue if it is + * possible to do so immediately without violating capacity restrictions. + * + * When using a capacity-restricted double-ended queue, it is generally + * preferable to use the `offerFirst()` method. + * + * @param T $element The element to add to the front of this queue. + * + * @return bool `true` if this queue changed as a result of the call. + * + * @throws RuntimeException if a queue refuses to add a particular element + * for any reason other than that it already contains the element. + * Implementations should use a more-specific exception that extends + * `\RuntimeException`. + */ + public function addFirst(mixed $element): bool; + + /** + * Inserts the specified element at the end of this queue if it is possible + * to do so immediately without violating capacity restrictions. + * + * When using a capacity-restricted double-ended queue, it is generally + * preferable to use the `offerLast()` method. + * + * This method is equivalent to `add()`. + * + * @param T $element The element to add to the end of this queue. + * + * @return bool `true` if this queue changed as a result of the call. + * + * @throws RuntimeException if a queue refuses to add a particular element + * for any reason other than that it already contains the element. + * Implementations should use a more-specific exception that extends + * `\RuntimeException`. + */ + public function addLast(mixed $element): bool; + + /** + * Inserts the specified element at the front of this queue if it is + * possible to do so immediately without violating capacity restrictions. + * + * When using a capacity-restricted queue, this method is generally + * preferable to `addFirst()`, which can fail to insert an element only by + * throwing an exception. + * + * @param T $element The element to add to the front of this queue. + * + * @return bool `true` if the element was added to this queue, else `false`. + */ + public function offerFirst(mixed $element): bool; + + /** + * Inserts the specified element at the end of this queue if it is possible + * to do so immediately without violating capacity restrictions. + * + * When using a capacity-restricted queue, this method is generally + * preferable to `addLast()` which can fail to insert an element only by + * throwing an exception. + * + * @param T $element The element to add to the end of this queue. + * + * @return bool `true` if the element was added to this queue, else `false`. + */ + public function offerLast(mixed $element): bool; + + /** + * Retrieves and removes the head of this queue. + * + * This method differs from `pollFirst()` only in that it throws an + * exception if this queue is empty. + * + * @return T the first element in this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function removeFirst(): mixed; + + /** + * Retrieves and removes the tail of this queue. + * + * This method differs from `pollLast()` only in that it throws an exception + * if this queue is empty. + * + * @return T the last element in this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function removeLast(): mixed; + + /** + * Retrieves and removes the head of this queue, or returns `null` if this + * queue is empty. + * + * @return T | null the head of this queue, or `null` if this queue is empty. + */ + public function pollFirst(): mixed; + + /** + * Retrieves and removes the tail of this queue, or returns `null` if this + * queue is empty. + * + * @return T | null the tail of this queue, or `null` if this queue is empty. + */ + public function pollLast(): mixed; + + /** + * Retrieves, but does not remove, the head of this queue. + * + * This method differs from `peekFirst()` only in that it throws an + * exception if this queue is empty. + * + * @return T the head of this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function firstElement(): mixed; + + /** + * Retrieves, but does not remove, the tail of this queue. + * + * This method differs from `peekLast()` only in that it throws an exception + * if this queue is empty. + * + * @return T the tail of this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function lastElement(): mixed; + + /** + * Retrieves, but does not remove, the head of this queue, or returns `null` + * if this queue is empty. + * + * @return T | null the head of this queue, or `null` if this queue is empty. + */ + public function peekFirst(): mixed; + + /** + * Retrieves, but does not remove, the tail of this queue, or returns `null` + * if this queue is empty. + * + * @return T | null the tail of this queue, or `null` if this queue is empty. + */ + public function peekLast(): mixed; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/CollectionException.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/CollectionException.php new file mode 100644 index 0000000..4aa92be --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/CollectionException.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use Throwable; + +interface CollectionException extends Throwable +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php new file mode 100644 index 0000000..42f5be2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use RuntimeException; + +/** + * Thrown when attempting to operate on collections of differing types. + */ +class CollectionMismatchException extends RuntimeException implements CollectionException +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..7b41b4a --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use InvalidArgumentException as PhpInvalidArgumentException; + +/** + * Thrown to indicate an argument is not of the expected type. + */ +class InvalidArgumentException extends PhpInvalidArgumentException implements CollectionException +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/InvalidPropertyOrMethod.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/InvalidPropertyOrMethod.php new file mode 100644 index 0000000..a53be14 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/InvalidPropertyOrMethod.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use RuntimeException; + +/** + * Thrown when attempting to evaluate a property, method, or array key + * that doesn't exist on an element or cannot otherwise be evaluated in the + * current context. + */ +class InvalidPropertyOrMethod extends RuntimeException implements CollectionException +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/NoSuchElementException.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/NoSuchElementException.php new file mode 100644 index 0000000..cd98f0c --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/NoSuchElementException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use RuntimeException; + +/** + * Thrown when attempting to access an element that does not exist. + */ +class NoSuchElementException extends RuntimeException implements CollectionException +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php new file mode 100644 index 0000000..c75294e --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use OutOfBoundsException as PhpOutOfBoundsException; + +/** + * Thrown when attempting to access an element out of the range of the collection. + */ +class OutOfBoundsException extends PhpOutOfBoundsException implements CollectionException +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php b/php/libraries/composer/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php new file mode 100644 index 0000000..d074f45 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Exception; + +use RuntimeException; + +/** + * Thrown to indicate that the requested operation is not supported. + */ +class UnsupportedOperationException extends RuntimeException implements CollectionException +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/GenericArray.php b/php/libraries/composer/vendor/ramsey/collection/src/GenericArray.php new file mode 100644 index 0000000..2b079aa --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/GenericArray.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +/** + * `GenericArray` represents a standard array object. + * + * @extends AbstractArray<mixed> + */ +class GenericArray extends AbstractArray +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/AbstractMap.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/AbstractMap.php new file mode 100644 index 0000000..7a851a8 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/AbstractMap.php @@ -0,0 +1,203 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +use Ramsey\Collection\AbstractArray; +use Ramsey\Collection\Exception\InvalidArgumentException; +use Traversable; + +use function array_key_exists; +use function array_keys; +use function in_array; +use function var_export; + +/** + * This class provides a basic implementation of `MapInterface`, to minimize the + * effort required to implement this interface. + * + * @template K of array-key + * @template T + * @extends AbstractArray<T> + * @implements MapInterface<K, T> + */ +abstract class AbstractMap extends AbstractArray implements MapInterface +{ + /** + * @param array<K, T> $data The initial items to add to this map. + */ + public function __construct(array $data = []) + { + parent::__construct($data); + } + + /** + * @return Traversable<K, T> + */ + public function getIterator(): Traversable + { + return parent::getIterator(); + } + + /** + * @param K $offset The offset to set + * @param T $value The value to set at the given offset. + * + * @inheritDoc + * @psalm-suppress MoreSpecificImplementedParamType,DocblockTypeContradiction + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === null) { + throw new InvalidArgumentException( + 'Map elements are key/value pairs; a key must be provided for ' + . 'value ' . var_export($value, true), + ); + } + + $this->data[$offset] = $value; + } + + public function containsKey(int | string $key): bool + { + return array_key_exists($key, $this->data); + } + + public function containsValue(mixed $value): bool + { + return in_array($value, $this->data, true); + } + + /** + * @inheritDoc + */ + public function keys(): array + { + return array_keys($this->data); + } + + /** + * @param K $key The key to return from the map. + * @param T | null $defaultValue The default value to use if `$key` is not found. + * + * @return T | null the value or `null` if the key could not be found. + */ + public function get(int | string $key, mixed $defaultValue = null): mixed + { + return $this[$key] ?? $defaultValue; + } + + /** + * @param K $key The key to put or replace in the map. + * @param T $value The value to store at `$key`. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function put(int | string $key, mixed $value): mixed + { + $previousValue = $this->get($key); + $this[$key] = $value; + + return $previousValue; + } + + /** + * @param K $key The key to put in the map. + * @param T $value The value to store at `$key`. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function putIfAbsent(int | string $key, mixed $value): mixed + { + $currentValue = $this->get($key); + + if ($currentValue === null) { + $this[$key] = $value; + } + + return $currentValue; + } + + /** + * @param K $key The key to remove from the map. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function remove(int | string $key): mixed + { + $previousValue = $this->get($key); + unset($this[$key]); + + return $previousValue; + } + + public function removeIf(int | string $key, mixed $value): bool + { + if ($this->get($key) === $value) { + unset($this[$key]); + + return true; + } + + return false; + } + + /** + * @param K $key The key to replace. + * @param T $value The value to set at `$key`. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function replace(int | string $key, mixed $value): mixed + { + $currentValue = $this->get($key); + + if ($this->containsKey($key)) { + $this[$key] = $value; + } + + return $currentValue; + } + + public function replaceIf(int | string $key, mixed $oldValue, mixed $newValue): bool + { + if ($this->get($key) === $oldValue) { + $this[$key] = $newValue; + + return true; + } + + return false; + } + + /** + * @return array<K, T> + */ + public function __serialize(): array + { + return parent::__serialize(); + } + + /** + * @return array<K, T> + */ + public function toArray(): array + { + return parent::toArray(); + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/AbstractTypedMap.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/AbstractTypedMap.php new file mode 100644 index 0000000..92fdcd5 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/AbstractTypedMap.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +use Ramsey\Collection\Exception\InvalidArgumentException; +use Ramsey\Collection\Tool\TypeTrait; +use Ramsey\Collection\Tool\ValueToStringTrait; + +/** + * This class provides a basic implementation of `TypedMapInterface`, to + * minimize the effort required to implement this interface. + * + * @template K of array-key + * @template T + * @extends AbstractMap<K, T> + * @implements TypedMapInterface<K, T> + */ +abstract class AbstractTypedMap extends AbstractMap implements TypedMapInterface +{ + use TypeTrait; + use ValueToStringTrait; + + /** + * @param K $offset + * @param T $value + * + * @inheritDoc + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($this->checkType($this->getKeyType(), $offset) === false) { + throw new InvalidArgumentException( + 'Key must be of type ' . $this->getKeyType() . '; key is ' + . $this->toolValueToString($offset), + ); + } + + if ($this->checkType($this->getValueType(), $value) === false) { + throw new InvalidArgumentException( + 'Value must be of type ' . $this->getValueType() . '; value is ' + . $this->toolValueToString($value), + ); + } + + parent::offsetSet($offset, $value); + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php new file mode 100644 index 0000000..34e4e85 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +/** + * `AssociativeArrayMap` represents a standard associative array object. + * + * @extends AbstractMap<string, mixed> + */ +class AssociativeArrayMap extends AbstractMap +{ +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/MapInterface.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/MapInterface.php new file mode 100644 index 0000000..22ba1bd --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/MapInterface.php @@ -0,0 +1,142 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +use Ramsey\Collection\ArrayInterface; + +/** + * An object that maps keys to values. + * + * A map cannot contain duplicate keys; each key can map to at most one value. + * + * @template K of array-key + * @template T + * @extends ArrayInterface<T> + */ +interface MapInterface extends ArrayInterface +{ + /** + * Returns `true` if this map contains a mapping for the specified key. + * + * @param K $key The key to check in the map. + */ + public function containsKey(int | string $key): bool; + + /** + * Returns `true` if this map maps one or more keys to the specified value. + * + * This performs a strict type check on the value. + * + * @param T $value The value to check in the map. + */ + public function containsValue(mixed $value): bool; + + /** + * Return an array of the keys contained in this map. + * + * @return list<K> + */ + public function keys(): array; + + /** + * Returns the value to which the specified key is mapped, `null` if this + * map contains no mapping for the key, or (optionally) `$defaultValue` if + * this map contains no mapping for the key. + * + * @param K $key The key to return from the map. + * @param T | null $defaultValue The default value to use if `$key` is not found. + * + * @return T | null the value or `null` if the key could not be found. + */ + public function get(int | string $key, mixed $defaultValue = null): mixed; + + /** + * Associates the specified value with the specified key in this map. + * + * If the map previously contained a mapping for the key, the old value is + * replaced by the specified value. + * + * @param K $key The key to put or replace in the map. + * @param T $value The value to store at `$key`. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function put(int | string $key, mixed $value): mixed; + + /** + * Associates the specified value with the specified key in this map only if + * it is not already set. + * + * If there is already a value associated with `$key`, this returns that + * value without replacing it. + * + * @param K $key The key to put in the map. + * @param T $value The value to store at `$key`. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function putIfAbsent(int | string $key, mixed $value): mixed; + + /** + * Removes the mapping for a key from this map if it is present. + * + * @param K $key The key to remove from the map. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function remove(int | string $key): mixed; + + /** + * Removes the entry for the specified key only if it is currently mapped to + * the specified value. + * + * This performs a strict type check on the value. + * + * @param K $key The key to remove from the map. + * @param T $value The value to match. + * + * @return bool true if the value was removed. + */ + public function removeIf(int | string $key, mixed $value): bool; + + /** + * Replaces the entry for the specified key only if it is currently mapped + * to some value. + * + * @param K $key The key to replace. + * @param T $value The value to set at `$key`. + * + * @return T | null the previous value associated with key, or `null` if + * there was no mapping for `$key`. + */ + public function replace(int | string $key, mixed $value): mixed; + + /** + * Replaces the entry for the specified key only if currently mapped to the + * specified value. + * + * This performs a strict type check on the value. + * + * @param K $key The key to remove from the map. + * @param T $oldValue The value to match. + * @param T $newValue The value to use as a replacement. + * + * @return bool true if the value was replaced. + */ + public function replaceIf(int | string $key, mixed $oldValue, mixed $newValue): bool; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/NamedParameterMap.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/NamedParameterMap.php new file mode 100644 index 0000000..f948e47 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/NamedParameterMap.php @@ -0,0 +1,110 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +use Ramsey\Collection\Exception\InvalidArgumentException; +use Ramsey\Collection\Tool\TypeTrait; +use Ramsey\Collection\Tool\ValueToStringTrait; + +use function array_combine; +use function array_key_exists; +use function is_int; + +/** + * `NamedParameterMap` represents a mapping of values to a set of named keys + * that may optionally be typed + * + * @extends AbstractMap<string, mixed> + */ +class NamedParameterMap extends AbstractMap +{ + use TypeTrait; + use ValueToStringTrait; + + /** + * Named parameters defined for this map. + * + * @var array<string, string> + */ + private readonly array $namedParameters; + + /** + * Constructs a new `NamedParameterMap`. + * + * @param array<array-key, string> $namedParameters The named parameters defined for this map. + * @param array<string, mixed> $data An initial set of data to set on this map. + */ + public function __construct(array $namedParameters, array $data = []) + { + $this->namedParameters = $this->filterNamedParameters($namedParameters); + parent::__construct($data); + } + + /** + * Returns named parameters set for this `NamedParameterMap`. + * + * @return array<string, string> + */ + public function getNamedParameters(): array + { + return $this->namedParameters; + } + + public function offsetSet(mixed $offset, mixed $value): void + { + if (!array_key_exists($offset, $this->namedParameters)) { + throw new InvalidArgumentException( + 'Attempting to set value for unconfigured parameter \'' + . $this->toolValueToString($offset) . '\'', + ); + } + + if ($this->checkType($this->namedParameters[$offset], $value) === false) { + throw new InvalidArgumentException( + 'Value for \'' . $offset . '\' must be of type ' + . $this->namedParameters[$offset] . '; value is ' + . $this->toolValueToString($value), + ); + } + + $this->data[$offset] = $value; + } + + /** + * Given an array of named parameters, constructs a proper mapping of + * named parameters to types. + * + * @param array<array-key, string> $namedParameters The named parameters to filter. + * + * @return array<string, string> + */ + protected function filterNamedParameters(array $namedParameters): array + { + $names = []; + $types = []; + + foreach ($namedParameters as $key => $value) { + if (is_int($key)) { + $names[] = $value; + $types[] = 'mixed'; + } else { + $names[] = $key; + $types[] = $value; + } + } + + return array_combine($names, $types) ?: []; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/TypedMap.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/TypedMap.php new file mode 100644 index 0000000..f914d9c --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/TypedMap.php @@ -0,0 +1,112 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +/** + * A `TypedMap` represents a map of elements where key and value are typed. + * + * Each element is identified by a key with defined type and a value of defined + * type. The keys of the map must be unique. The values on the map can be + * repeated but each with its own different key. + * + * The most common case is to use a string type key, but it's not limited to + * this type of keys. + * + * This is a direct implementation of `TypedMapInterface`, provided for the sake + * of convenience. + * + * Example usage: + * + * ```php + * $map = new TypedMap('string', Foo::class); + * $map['x'] = new Foo(); + * foreach ($map as $key => $value) { + * // do something with $key, it will be a Foo::class + * } + * + * // this will throw an exception since key must be string + * $map[10] = new Foo(); + * + * // this will throw an exception since value must be a Foo + * $map['bar'] = 'bar'; + * + * // initialize map with contents + * $map = new TypedMap('string', Foo::class, [ + * new Foo(), new Foo(), new Foo() + * ]); + * ``` + * + * It is preferable to subclass `AbstractTypedMap` to create your own typed map + * implementation: + * + * ```php + * class FooTypedMap extends AbstractTypedMap + * { + * public function getKeyType() + * { + * return 'int'; + * } + * + * public function getValueType() + * { + * return Foo::class; + * } + * } + * ``` + * + * … but you also may use the `TypedMap` class: + * + * ```php + * class FooTypedMap extends TypedMap + * { + * public function __constructor(array $data = []) + * { + * parent::__construct('int', Foo::class, $data); + * } + * } + * ``` + * + * @template K of array-key + * @template T + * @extends AbstractTypedMap<K, T> + */ +class TypedMap extends AbstractTypedMap +{ + /** + * Constructs a map object of the specified key and value types, + * optionally with the specified data. + * + * @param string $keyType The data type of the map's keys. + * @param string $valueType The data type of the map's values. + * @param array<K, T> $data The initial data to set for this map. + */ + public function __construct( + private readonly string $keyType, + private readonly string $valueType, + array $data = [], + ) { + parent::__construct($data); + } + + public function getKeyType(): string + { + return $this->keyType; + } + + public function getValueType(): string + { + return $this->valueType; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Map/TypedMapInterface.php b/php/libraries/composer/vendor/ramsey/collection/src/Map/TypedMapInterface.php new file mode 100644 index 0000000..5a44f06 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Map/TypedMapInterface.php @@ -0,0 +1,36 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Map; + +/** + * A `TypedMapInterface` represents a map of elements where key and value are + * typed. + * + * @template K of array-key + * @template T + * @extends MapInterface<K, T> + */ +interface TypedMapInterface extends MapInterface +{ + /** + * Return the type used on the key. + */ + public function getKeyType(): string; + + /** + * Return the type forced on the values. + */ + public function getValueType(): string; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Queue.php b/php/libraries/composer/vendor/ramsey/collection/src/Queue.php new file mode 100644 index 0000000..0f5b337 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Queue.php @@ -0,0 +1,148 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use Ramsey\Collection\Exception\InvalidArgumentException; +use Ramsey\Collection\Exception\NoSuchElementException; +use Ramsey\Collection\Tool\TypeTrait; +use Ramsey\Collection\Tool\ValueToStringTrait; + +use function array_key_first; + +/** + * This class provides a basic implementation of `QueueInterface`, to minimize + * the effort required to implement this interface. + * + * @template T + * @extends AbstractArray<T> + * @implements QueueInterface<T> + */ +class Queue extends AbstractArray implements QueueInterface +{ + use TypeTrait; + use ValueToStringTrait; + + /** + * Constructs a queue object of the specified type, optionally with the + * specified data. + * + * @param string $queueType The type or class name associated with this queue. + * @param array<array-key, T> $data The initial items to store in the queue. + */ + public function __construct(private readonly string $queueType, array $data = []) + { + parent::__construct($data); + } + + /** + * {@inheritDoc} + * + * Since arbitrary offsets may not be manipulated in a queue, this method + * serves only to fulfill the `ArrayAccess` interface requirements. It is + * invoked by other operations when adding values to the queue. + * + * @throws InvalidArgumentException if $value is of the wrong type. + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($this->checkType($this->getType(), $value) === false) { + throw new InvalidArgumentException( + 'Value must be of type ' . $this->getType() . '; value is ' + . $this->toolValueToString($value), + ); + } + + $this->data[] = $value; + } + + /** + * @throws InvalidArgumentException if $value is of the wrong type. + */ + public function add(mixed $element): bool + { + $this[] = $element; + + return true; + } + + /** + * @return T + * + * @throws NoSuchElementException if this queue is empty. + */ + public function element(): mixed + { + return $this->peek() ?? throw new NoSuchElementException( + 'Can\'t return element from Queue. Queue is empty.', + ); + } + + public function offer(mixed $element): bool + { + try { + return $this->add($element); + } catch (InvalidArgumentException) { + return false; + } + } + + /** + * @return T | null + */ + public function peek(): mixed + { + $index = array_key_first($this->data); + + if ($index === null) { + return null; + } + + return $this[$index]; + } + + /** + * @return T | null + */ + public function poll(): mixed + { + $index = array_key_first($this->data); + + if ($index === null) { + return null; + } + + $head = $this[$index]; + unset($this[$index]); + + return $head; + } + + /** + * @return T + * + * @throws NoSuchElementException if this queue is empty. + */ + public function remove(): mixed + { + return $this->poll() ?? throw new NoSuchElementException( + 'Can\'t return element from Queue. Queue is empty.', + ); + } + + public function getType(): string + { + return $this->queueType; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/QueueInterface.php b/php/libraries/composer/vendor/ramsey/collection/src/QueueInterface.php new file mode 100644 index 0000000..f29ce43 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/QueueInterface.php @@ -0,0 +1,202 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +use Ramsey\Collection\Exception\NoSuchElementException; +use RuntimeException; + +/** + * A queue is a collection in which the entities in the collection are kept in + * order. + * + * The principal operations on the queue are the addition of entities to the end + * (tail), also known as *enqueue*, and removal of entities from the front + * (head), also known as *dequeue*. This makes the queue a first-in-first-out + * (FIFO) data structure. + * + * Besides basic array operations, queues provide additional insertion, + * extraction, and inspection operations. Each of these methods exists in two + * forms: one throws an exception if the operation fails, the other returns a + * special value (either `null` or `false`, depending on the operation). The + * latter form of the insert operation is designed specifically for use with + * capacity-restricted `QueueInterface` implementations; in most + * implementations, insert operations cannot fail. + * + * <table> + * <caption>Summary of QueueInterface methods</caption> + * <thead> + * <tr> + * <td></td> + * <td><em>Throws exception</em></td> + * <td><em>Returns special value</em></td> + * </tr> + * </thead> + * <tbody> + * <tr> + * <th>Insert</th> + * <td><code>add()</code></td> + * <td><code>offer()</code></td> + * </tr> + * <tr> + * <th>Remove</th> + * <td><code>remove()</code></td> + * <td><code>poll()</code></td> + * </tr> + * <tr> + * <th>Examine</th> + * <td><code>element()</code></td> + * <td><code>peek()</code></td> + * </tr> + * </tbody> + * </table> + * + * Queues typically, but do not necessarily, order elements in a FIFO + * (first-in-first-out) manner. Among the exceptions are priority queues, which + * order elements according to a supplied comparator, or the elements' natural + * ordering, and LIFO queues (or stacks) which order the elements LIFO + * (last-in-first-out). Whatever the ordering used, the head of the queue is + * that element which would be removed by a call to remove() or poll(). In a + * FIFO queue, all new elements are inserted at the tail of the queue. Other + * kinds of queues may use different placement rules. Every `QueueInterface` + * implementation must specify its ordering properties. + * + * The `offer()` method inserts an element if possible, otherwise returning + * `false`. This differs from the `add()` method, which can fail to add an + * element only by throwing an unchecked exception. The `offer()` method is + * designed for use when failure is a normal, rather than exceptional + * occurrence, for example, in fixed-capacity (or "bounded") queues. + * + * The `remove()` and `poll()` methods remove and return the head of the queue. + * Exactly which element is removed from the queue is a function of the queue's + * ordering policy, which differs from implementation to implementation. The + * `remove()` and `poll()` methods differ only in their behavior when the queue + * is empty: the `remove()` method throws an exception, while the `poll()` + * method returns `null`. + * + * The `element()` and `peek()` methods return, but do not remove, the head of + * the queue. + * + * `QueueInterface` implementations generally do not allow insertion of `null` + * elements, although some implementations do not prohibit insertion of `null`. + * Even in the implementations that permit it, `null` should not be inserted + * into a queue, as `null` is also used as a special return value by the + * `poll()` method to indicate that the queue contains no elements. + * + * @template T + * @extends ArrayInterface<T> + */ +interface QueueInterface extends ArrayInterface +{ + /** + * Ensures that this queue contains the specified element (optional + * operation). + * + * Returns `true` if this queue changed as a result of the call. (Returns + * `false` if this queue does not permit duplicates and already contains the + * specified element.) + * + * Queues that support this operation may place limitations on what elements + * may be added to this queue. In particular, some queues will refuse to add + * `null` elements, and others will impose restrictions on the type of + * elements that may be added. Queue classes should clearly specify in their + * documentation any restrictions on what elements may be added. + * + * If a queue refuses to add a particular element for any reason other than + * that it already contains the element, it must throw an exception (rather + * than returning `false`). This preserves the invariant that a queue always + * contains the specified element after this call returns. + * + * @see self::offer() + * + * @param T $element The element to add to this queue. + * + * @return bool `true` if this queue changed as a result of the call. + * + * @throws RuntimeException if a queue refuses to add a particular element + * for any reason other than that it already contains the element. + * Implementations should use a more-specific exception that extends + * `\RuntimeException`. + */ + public function add(mixed $element): bool; + + /** + * Retrieves, but does not remove, the head of this queue. + * + * This method differs from `peek()` only in that it throws an exception if + * this queue is empty. + * + * @see self::peek() + * + * @return T the head of this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function element(): mixed; + + /** + * Inserts the specified element into this queue if it is possible to do so + * immediately without violating capacity restrictions. + * + * When using a capacity-restricted queue, this method is generally + * preferable to `add()`, which can fail to insert an element only by + * throwing an exception. + * + * @see self::add() + * + * @param T $element The element to add to this queue. + * + * @return bool `true` if the element was added to this queue, else `false`. + */ + public function offer(mixed $element): bool; + + /** + * Retrieves, but does not remove, the head of this queue, or returns `null` + * if this queue is empty. + * + * @see self::element() + * + * @return T | null the head of this queue, or `null` if this queue is empty. + */ + public function peek(): mixed; + + /** + * Retrieves and removes the head of this queue, or returns `null` + * if this queue is empty. + * + * @see self::remove() + * + * @return T | null the head of this queue, or `null` if this queue is empty. + */ + public function poll(): mixed; + + /** + * Retrieves and removes the head of this queue. + * + * This method differs from `poll()` only in that it throws an exception if + * this queue is empty. + * + * @see self::poll() + * + * @return T the head of this queue. + * + * @throws NoSuchElementException if this queue is empty. + */ + public function remove(): mixed; + + /** + * Returns the type associated with this queue. + */ + public function getType(): string; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Set.php b/php/libraries/composer/vendor/ramsey/collection/src/Set.php new file mode 100644 index 0000000..aa93351 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Set.php @@ -0,0 +1,59 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +/** + * A set is a collection that contains no duplicate elements. + * + * Great care must be exercised if mutable objects are used as set elements. + * The behavior of a set is not specified if the value of an object is changed + * in a manner that affects equals comparisons while the object is an element in + * the set. + * + * Example usage: + * + * ``` php + * $foo = new \My\Foo(); + * $set = new Set(\My\Foo::class); + * + * $set->add($foo); // returns TRUE, the element doesn't exist + * $set->add($foo); // returns FALSE, the element already exists + * + * $bar = new \My\Foo(); + * $set->add($bar); // returns TRUE, $bar !== $foo + * ``` + * + * @template T + * @extends AbstractSet<T> + */ +class Set extends AbstractSet +{ + /** + * Constructs a set object of the specified type, optionally with the + * specified data. + * + * @param string $setType The type or class name associated with this set. + * @param array<array-key, T> $data The initial items to store in the set. + */ + public function __construct(private readonly string $setType, array $data = []) + { + parent::__construct($data); + } + + public function getType(): string + { + return $this->setType; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Sort.php b/php/libraries/composer/vendor/ramsey/collection/src/Sort.php new file mode 100644 index 0000000..0c3c192 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Sort.php @@ -0,0 +1,31 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection; + +/** + * Collection sorting + */ +enum Sort: string +{ + /** + * Sort items in a collection in ascending order. + */ + case Ascending = 'asc'; + + /** + * Sort items in a collection in descending order. + */ + case Descending = 'desc'; +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Tool/TypeTrait.php b/php/libraries/composer/vendor/ramsey/collection/src/Tool/TypeTrait.php new file mode 100644 index 0000000..ac51b7f --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Tool/TypeTrait.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Tool; + +use function is_array; +use function is_bool; +use function is_callable; +use function is_float; +use function is_int; +use function is_numeric; +use function is_object; +use function is_resource; +use function is_scalar; +use function is_string; + +/** + * Provides functionality to check values for specific types. + */ +trait TypeTrait +{ + /** + * Returns `true` if value is of the specified type. + * + * @param string $type The type to check the value against. + * @param mixed $value The value to check. + */ + protected function checkType(string $type, mixed $value): bool + { + return match ($type) { + 'array' => is_array($value), + 'bool', 'boolean' => is_bool($value), + 'callable' => is_callable($value), + 'float', 'double' => is_float($value), + 'int', 'integer' => is_int($value), + 'null' => $value === null, + 'numeric' => is_numeric($value), + 'object' => is_object($value), + 'resource' => is_resource($value), + 'scalar' => is_scalar($value), + 'string' => is_string($value), + 'mixed' => true, + default => $value instanceof $type, + }; + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php b/php/libraries/composer/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php new file mode 100644 index 0000000..44c4222 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php @@ -0,0 +1,81 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Tool; + +use Ramsey\Collection\Exception\InvalidPropertyOrMethod; +use Ramsey\Collection\Exception\UnsupportedOperationException; + +use function is_array; +use function is_object; +use function method_exists; +use function property_exists; +use function sprintf; + +/** + * Provides functionality to extract the value of a property or method from an object. + */ +trait ValueExtractorTrait +{ + /** + * Extracts the value of the given property, method, or array key from the + * element. + * + * If `$propertyOrMethod` is `null`, we return the element as-is. + * + * @param mixed $element The element to extract the value from. + * @param string | null $propertyOrMethod The property or method for which the + * value should be extracted. + * + * @return mixed the value extracted from the specified property, method, + * or array key, or the element itself. + * + * @throws InvalidPropertyOrMethod + * @throws UnsupportedOperationException + */ + protected function extractValue(mixed $element, ?string $propertyOrMethod): mixed + { + if ($propertyOrMethod === null) { + return $element; + } + + if (!is_object($element) && !is_array($element)) { + throw new UnsupportedOperationException(sprintf( + 'The collection type "%s" does not support the $propertyOrMethod parameter', + $this->getType(), + )); + } + + if (is_array($element)) { + return $element[$propertyOrMethod] ?? throw new InvalidPropertyOrMethod(sprintf( + 'Key or index "%s" not found in collection elements', + $propertyOrMethod, + )); + } + + if (property_exists($element, $propertyOrMethod)) { + return $element->$propertyOrMethod; + } + + if (method_exists($element, $propertyOrMethod)) { + return $element->{$propertyOrMethod}(); + } + + throw new InvalidPropertyOrMethod(sprintf( + 'Method or property "%s" not defined in %s', + $propertyOrMethod, + $element::class, + )); + } +} diff --git a/php/libraries/composer/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php b/php/libraries/composer/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php new file mode 100644 index 0000000..64fc5fa --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php @@ -0,0 +1,91 @@ +<?php + +/** + * This file is part of the ramsey/collection library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Collection\Tool; + +use DateTimeInterface; + +use function assert; +use function get_resource_type; +use function is_array; +use function is_bool; +use function is_callable; +use function is_object; +use function is_resource; +use function is_scalar; + +/** + * Provides functionality to express a value as string + */ +trait ValueToStringTrait +{ + /** + * Returns a string representation of the value. + * + * - null value: `'NULL'` + * - boolean: `'TRUE'`, `'FALSE'` + * - array: `'Array'` + * - scalar: converted-value + * - resource: `'(type resource #number)'` + * - object with `__toString()`: result of `__toString()` + * - object DateTime: ISO 8601 date + * - object: `'(className Object)'` + * - anonymous function: same as object + * + * @param mixed $value the value to return as a string. + */ + protected function toolValueToString(mixed $value): string + { + // null + if ($value === null) { + return 'NULL'; + } + + // boolean constants + if (is_bool($value)) { + return $value ? 'TRUE' : 'FALSE'; + } + + // array + if (is_array($value)) { + return 'Array'; + } + + // scalar types (integer, float, string) + if (is_scalar($value)) { + return (string) $value; + } + + // resource + if (is_resource($value)) { + return '(' . get_resource_type($value) . ' resource #' . (int) $value . ')'; + } + + // From here, $value should be an object. + assert(is_object($value)); + + // __toString() is implemented + if (is_callable([$value, '__toString'])) { + return (string) $value->__toString(); + } + + // object of type \DateTime + if ($value instanceof DateTimeInterface) { + return $value->format('c'); + } + + // unknown type + return '(' . $value::class . ' Object)'; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/LICENSE b/php/libraries/composer/vendor/ramsey/uuid/LICENSE new file mode 100644 index 0000000..5b2acc5 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012-2023 Ben Ramsey <ben@benramsey.com> + +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/php/libraries/composer/vendor/ramsey/uuid/README.md b/php/libraries/composer/vendor/ramsey/uuid/README.md new file mode 100644 index 0000000..0db8149 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/README.md @@ -0,0 +1,83 @@ +<h1 align="center">ramsey/uuid</h1> + +<p align="center"> + <strong>A PHP library for generating and working with UUIDs.</strong> +</p> + +<p align="center"> + <a href="https://github.com/ramsey/uuid"><img src="http://img.shields.io/badge/source-ramsey/uuid-blue.svg?style=flat-square" alt="Source Code"></a> + <a href="https://packagist.org/packages/ramsey/uuid"><img src="https://img.shields.io/packagist/v/ramsey/uuid.svg?style=flat-square&label=release" alt="Download Package"></a> + <a href="https://php.net"><img src="https://img.shields.io/packagist/php-v/ramsey/uuid.svg?style=flat-square&colorB=%238892BF" alt="PHP Programming Language"></a> + <a href="https://github.com/ramsey/uuid/blob/4.x/LICENSE"><img src="https://img.shields.io/packagist/l/ramsey/uuid.svg?style=flat-square&colorB=darkcyan" alt="Read License"></a> + <a href="https://github.com/ramsey/uuid/actions/workflows/continuous-integration.yml"><img src="https://img.shields.io/github/actions/workflow/status/ramsey/uuid/continuous-integration.yml?branch=4.x&logo=github&style=flat-square" alt="Build Status"></a> + <a href="https://app.codecov.io/gh/ramsey/uuid/branch/4.x"><img src="https://img.shields.io/codecov/c/github/ramsey/uuid/4.x?label=codecov&logo=codecov&style=flat-square" alt="Codecov Code Coverage"></a> + <a href="https://shepherd.dev/github/ramsey/uuid"><img src="https://img.shields.io/endpoint?style=flat-square&url=https%3A%2F%2Fshepherd.dev%2Fgithub%2Framsey%2Fuuid%2Fcoverage" alt="Psalm Type Coverage"></a> +</p> + +ramsey/uuid is a PHP library for generating and working with universally unique +identifiers (UUIDs). + +This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). +By participating in this project and its community, you are expected to +uphold this code. + +Much inspiration for this library came from the [Java][javauuid] and +[Python][pyuuid] UUID libraries. + +## Installation + +The preferred method of installation is via [Composer][]. Run the following +command to install the package and add it as a requirement to your project's +`composer.json`: + +```bash +composer require ramsey/uuid +``` + +## Upgrading to Version 4 + +See the documentation for a thorough upgrade guide: + +* [Upgrading ramsey/uuid Version 3 to 4](https://uuid.ramsey.dev/en/stable/upgrading/3-to-4.html) + +## Documentation + +Please see <https://uuid.ramsey.dev> for documentation, tips, examples, and +frequently asked questions. + +## Contributing + +Contributions are welcome! To contribute, please familiarize yourself with +[CONTRIBUTING.md](CONTRIBUTING.md). + +## Coordinated Disclosure + +Keeping user information safe and secure is a top priority, and we welcome the +contribution of external security researchers. If you believe you've found a +security issue in software that is maintained in this repository, please read +[SECURITY.md][] for instructions on submitting a vulnerability report. + +## ramsey/uuid for Enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of ramsey/uuid and thousands of other packages are working with +Tidelift to deliver commercial support and maintenance for the open source +packages you use to build your applications. Save time, reduce risk, and improve +code health, while paying the maintainers of the exact packages you use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-ramsey-uuid?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Copyright and License + +The ramsey/uuid library is copyright © [Ben Ramsey](https://benramsey.com/) and +licensed for use under the MIT License (MIT). Please see [LICENSE][] for more +information. + +[rfc4122]: http://tools.ietf.org/html/rfc4122 +[conduct]: https://github.com/ramsey/uuid/blob/4.x/CODE_OF_CONDUCT.md +[javauuid]: http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html +[pyuuid]: http://docs.python.org/3/library/uuid.html +[composer]: http://getcomposer.org/ +[contributing.md]: https://github.com/ramsey/uuid/blob/4.x/CONTRIBUTING.md +[security.md]: https://github.com/ramsey/uuid/blob/4.x/SECURITY.md +[license]: https://github.com/ramsey/uuid/blob/4.x/LICENSE diff --git a/php/libraries/composer/vendor/ramsey/uuid/composer.json b/php/libraries/composer/vendor/ramsey/uuid/composer.json new file mode 100644 index 0000000..9ea4e06 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/composer.json @@ -0,0 +1,108 @@ +{ + "name": "ramsey/uuid", + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "license": "MIT", + "type": "library", + "keywords": [ + "uuid", + "identifier", + "guid" + ], + "require": { + "php": "^8.0", + "ext-json": "*", + "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11", + "ramsey/collection": "^1.2 || ^2.0" + }, + "require-dev": { + "captainhook/captainhook": "^5.10", + "captainhook/plugin-composer": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.8", + "ergebnis/composer-normalize": "^2.15", + "mockery/mockery": "^1.3", + "paragonie/random-lib": "^2", + "php-mock/php-mock": "^2.2", + "php-mock/php-mock-mockery": "^1.3", + "php-parallel-lint/php-parallel-lint": "^1.1", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.1", + "phpunit/phpunit": "^8.5 || ^9", + "ramsey/composer-repl": "^1.4", + "slevomat/coding-standard": "^8.4", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.9" + }, + "replace": { + "rhumsaa/uuid": "self.version" + }, + "suggest": { + "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", + "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + }, + "minimum-stability": "dev", + "prefer-stable": true, + "autoload": { + "psr-4": { + "Ramsey\\Uuid\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Ramsey\\Uuid\\Benchmark\\": "tests/benchmark/", + "Ramsey\\Uuid\\StaticAnalysis\\": "tests/static-analysis/", + "Ramsey\\Uuid\\Test\\": "tests/" + } + }, + "config": { + "allow-plugins": { + "captainhook/plugin-composer": true, + "ergebnis/composer-normalize": true, + "phpstan/extension-installer": true, + "dealerdirect/phpcodesniffer-composer-installer": true, + "ramsey/composer-repl": true + }, + "sort-packages": true + }, + "extra": { + "captainhook": { + "force-install": true + } + }, + "scripts": { + "analyze": [ + "@phpstan", + "@psalm" + ], + "build:clean": "git clean -fX build/", + "lint": "parallel-lint src tests", + "lint:paths": "parallel-lint", + "phpbench": "phpbench run", + "phpcbf": "phpcbf -vpw --cache=build/cache/phpcs.cache", + "phpcs": "phpcs --cache=build/cache/phpcs.cache", + "phpstan": [ + "phpstan analyse --no-progress --memory-limit=1G", + "phpstan analyse -c phpstan-tests.neon --no-progress --memory-limit=1G" + ], + "phpunit": "phpunit --verbose --colors=always", + "phpunit-coverage": "phpunit --verbose --colors=always --coverage-html build/coverage", + "psalm": "psalm --show-info=false --config=psalm.xml", + "test": [ + "@lint", + "@phpbench", + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit" + ] + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/BinaryUtils.php b/php/libraries/composer/vendor/ramsey/uuid/src/BinaryUtils.php new file mode 100644 index 0000000..fb8ba9a --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/BinaryUtils.php @@ -0,0 +1,63 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +/** + * Provides binary math utilities + */ +class BinaryUtils +{ + /** + * Applies the RFC 4122 variant field to the 16-bit clock sequence + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + * + * @param int $clockSeq The 16-bit clock sequence value before the RFC 4122 + * variant is applied + * + * @return int The 16-bit clock sequence multiplexed with the UUID variant + * + * @psalm-pure + */ + public static function applyVariant(int $clockSeq): int + { + $clockSeq = $clockSeq & 0x3fff; + $clockSeq |= 0x8000; + + return $clockSeq; + } + + /** + * Applies the RFC 4122 version number to the 16-bit `time_hi_and_version` field + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + * + * @param int $timeHi The value of the 16-bit `time_hi_and_version` field + * before the RFC 4122 version is applied + * @param int $version The RFC 4122 version to apply to the `time_hi` field + * + * @return int The 16-bit time_hi field of the timestamp multiplexed with + * the UUID version number + * + * @psalm-pure + */ + public static function applyVersion(int $timeHi, int $version): int + { + $timeHi = $timeHi & 0x0fff; + $timeHi |= $version << 12; + + return $timeHi; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Builder/BuilderCollection.php b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/BuilderCollection.php new file mode 100644 index 0000000..9df3110 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/BuilderCollection.php @@ -0,0 +1,85 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Builder; + +use Ramsey\Collection\AbstractCollection; +use Ramsey\Uuid\Converter\Number\GenericNumberConverter; +use Ramsey\Uuid\Converter\Time\GenericTimeConverter; +use Ramsey\Uuid\Converter\Time\PhpTimeConverter; +use Ramsey\Uuid\Guid\GuidBuilder; +use Ramsey\Uuid\Math\BrickMathCalculator; +use Ramsey\Uuid\Nonstandard\UuidBuilder as NonstandardUuidBuilder; +use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder; +use Traversable; + +/** + * A collection of UuidBuilderInterface objects + * + * @deprecated this class has been deprecated, and will be removed in 5.0.0. The use-case for this class comes from + * a pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced + * at runtime: that is no longer necessary, now that you can safely verify your code to be correct, and use + * more generic types like `iterable<T>` instead. + * + * @extends AbstractCollection<UuidBuilderInterface> + */ +class BuilderCollection extends AbstractCollection +{ + public function getType(): string + { + return UuidBuilderInterface::class; + } + + /** + * @psalm-mutation-free + * @psalm-suppress ImpureMethodCall + * @psalm-suppress InvalidTemplateParam + */ + public function getIterator(): Traversable + { + return parent::getIterator(); + } + + /** + * Re-constructs the object from its serialized form + * + * @param string $serialized The serialized PHP string to unserialize into + * a UuidInterface instance + * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress RedundantConditionGivenDocblockType + */ + public function unserialize($serialized): void + { + /** @var array<array-key, UuidBuilderInterface> $data */ + $data = unserialize($serialized, [ + 'allowed_classes' => [ + BrickMathCalculator::class, + GenericNumberConverter::class, + GenericTimeConverter::class, + GuidBuilder::class, + NonstandardUuidBuilder::class, + PhpTimeConverter::class, + Rfc4122UuidBuilder::class, + ], + ]); + + $this->data = array_filter( + $data, + function ($unserialized): bool { + return $unserialized instanceof UuidBuilderInterface; + } + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Builder/DefaultUuidBuilder.php b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/DefaultUuidBuilder.php new file mode 100644 index 0000000..7c4a6f8 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/DefaultUuidBuilder.php @@ -0,0 +1,26 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Builder; + +use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder; + +/** + * @deprecated Transition to {@see Rfc4122UuidBuilder}. + * + * @psalm-immutable + */ +class DefaultUuidBuilder extends Rfc4122UuidBuilder +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php new file mode 100644 index 0000000..20b3842 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php @@ -0,0 +1,67 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Builder; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\Time\DegradedTimeConverter; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\DegradedUuid; +use Ramsey\Uuid\Rfc4122\Fields as Rfc4122Fields; +use Ramsey\Uuid\UuidInterface; + +/** + * @deprecated DegradedUuid instances are no longer necessary to support 32-bit + * systems. Transition to {@see DefaultUuidBuilder}. + * + * @psalm-immutable + */ +class DegradedUuidBuilder implements UuidBuilderInterface +{ + private TimeConverterInterface $timeConverter; + + /** + * @param NumberConverterInterface $numberConverter The number converter to + * use when constructing the DegradedUuid + * @param TimeConverterInterface|null $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to Unix timestamps + */ + public function __construct( + private NumberConverterInterface $numberConverter, + ?TimeConverterInterface $timeConverter = null + ) { + $this->timeConverter = $timeConverter ?: new DegradedTimeConverter(); + } + + /** + * Builds and returns a DegradedUuid + * + * @param CodecInterface $codec The codec to use for building this DegradedUuid instance + * @param string $bytes The byte string from which to construct a UUID + * + * @return DegradedUuid The DegradedUuidBuild returns an instance of Ramsey\Uuid\DegradedUuid + * + * @psalm-pure + */ + public function build(CodecInterface $codec, string $bytes): UuidInterface + { + return new DegradedUuid( + new Rfc4122Fields($bytes), + $this->numberConverter, + $codec, + $this->timeConverter + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php new file mode 100644 index 0000000..ba5f31f --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php @@ -0,0 +1,68 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Builder; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Exception\BuilderNotFoundException; +use Ramsey\Uuid\Exception\UnableToBuildUuidException; +use Ramsey\Uuid\UuidInterface; + +/** + * FallbackBuilder builds a UUID by stepping through a list of UUID builders + * until a UUID can be constructed without exceptions + * + * @psalm-immutable + */ +class FallbackBuilder implements UuidBuilderInterface +{ + /** + * @param iterable<UuidBuilderInterface> $builders An array of UUID builders + */ + public function __construct(private iterable $builders) + { + } + + /** + * Builds and returns a UuidInterface instance using the first builder that + * succeeds + * + * @param CodecInterface $codec The codec to use for building this instance + * @param string $bytes The byte string from which to construct a UUID + * + * @return UuidInterface an instance of a UUID object + * + * @psalm-pure + */ + public function build(CodecInterface $codec, string $bytes): UuidInterface + { + $lastBuilderException = null; + + foreach ($this->builders as $builder) { + try { + return $builder->build($codec, $bytes); + } catch (UnableToBuildUuidException $exception) { + $lastBuilderException = $exception; + + continue; + } + } + + throw new BuilderNotFoundException( + 'Could not find a suitable builder for the provided codec and fields', + 0, + $lastBuilderException + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Builder/UuidBuilderInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/UuidBuilderInterface.php new file mode 100644 index 0000000..8e58b2b --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Builder/UuidBuilderInterface.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Builder; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\UuidInterface; + +/** + * A UUID builder builds instances of UuidInterface + * + * @psalm-immutable + */ +interface UuidBuilderInterface +{ + /** + * Builds and returns a UuidInterface + * + * @param CodecInterface $codec The codec to use for building this UuidInterface instance + * @param string $bytes The byte string from which to construct a UUID + * + * @return UuidInterface Implementations may choose to return more specific + * instances of UUIDs that implement UuidInterface + * + * @psalm-pure + */ + public function build(CodecInterface $codec, string $bytes): UuidInterface; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Codec/CodecInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/CodecInterface.php new file mode 100644 index 0000000..85f8a7e --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/CodecInterface.php @@ -0,0 +1,71 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Codec; + +use Ramsey\Uuid\UuidInterface; + +/** + * A codec encodes and decodes a UUID according to defined rules + * + * @psalm-immutable + */ +interface CodecInterface +{ + /** + * Returns a hexadecimal string representation of a UuidInterface + * + * @param UuidInterface $uuid The UUID for which to create a hexadecimal + * string representation + * + * @return string Hexadecimal string representation of a UUID + * + * @psalm-return non-empty-string + */ + public function encode(UuidInterface $uuid): string; + + /** + * Returns a binary string representation of a UuidInterface + * + * @param UuidInterface $uuid The UUID for which to create a binary string + * representation + * + * @return string Binary string representation of a UUID + * + * @psalm-return non-empty-string + */ + public function encodeBinary(UuidInterface $uuid): string; + + /** + * Returns a UuidInterface derived from a hexadecimal string representation + * + * @param string $encodedUuid The hexadecimal string representation to + * convert into a UuidInterface instance + * + * @return UuidInterface An instance of a UUID decoded from a hexadecimal + * string representation + */ + public function decode(string $encodedUuid): UuidInterface; + + /** + * Returns a UuidInterface derived from a binary string representation + * + * @param string $bytes The binary string representation to convert into a + * UuidInterface instance + * + * @return UuidInterface An instance of a UUID decoded from a binary string + * representation + */ + public function decodeBytes(string $bytes): UuidInterface; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php new file mode 100644 index 0000000..04872e0 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Codec; + +use Ramsey\Uuid\Guid\Guid; +use Ramsey\Uuid\UuidInterface; + +use function bin2hex; +use function sprintf; +use function substr; + +/** + * GuidStringCodec encodes and decodes globally unique identifiers (GUID) + * + * @see Guid + * + * @psalm-immutable + */ +class GuidStringCodec extends StringCodec +{ + public function encode(UuidInterface $uuid): string + { + $hex = bin2hex($uuid->getFields()->getBytes()); + + /** @var non-empty-string */ + return sprintf( + '%02s%02s%02s%02s-%02s%02s-%02s%02s-%04s-%012s', + substr($hex, 6, 2), + substr($hex, 4, 2), + substr($hex, 2, 2), + substr($hex, 0, 2), + substr($hex, 10, 2), + substr($hex, 8, 2), + substr($hex, 14, 2), + substr($hex, 12, 2), + substr($hex, 16, 4), + substr($hex, 20), + ); + } + + public function decode(string $encodedUuid): UuidInterface + { + $bytes = $this->getBytes($encodedUuid); + + return $this->getBuilder()->build($this, $this->swapBytes($bytes)); + } + + public function decodeBytes(string $bytes): UuidInterface + { + // Specifically call parent::decode to preserve correct byte order + return parent::decode(bin2hex($bytes)); + } + + /** + * Swaps bytes according to the GUID rules + */ + private function swapBytes(string $bytes): string + { + return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0] + . $bytes[5] . $bytes[4] + . $bytes[7] . $bytes[6] + . substr($bytes, 8); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Codec/OrderedTimeCodec.php b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/OrderedTimeCodec.php new file mode 100644 index 0000000..0798ebc --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/OrderedTimeCodec.php @@ -0,0 +1,113 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Codec; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; + +use function strlen; +use function substr; + +/** + * OrderedTimeCodec encodes and decodes a UUID, optimizing the byte order for + * more efficient storage + * + * For binary representations of version 1 UUID, this codec may be used to + * reorganize the time fields, making the UUID closer to sequential when storing + * the bytes. According to Percona, this optimization can improve database + * INSERTs and SELECTs using the UUID column as a key. + * + * The string representation of the UUID will remain unchanged. Only the binary + * representation is reordered. + * + * **PLEASE NOTE:** Binary representations of UUIDs encoded with this codec must + * be decoded with this codec. Decoding using another codec can result in + * malformed UUIDs. + * + * @link https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ Storing UUID Values in MySQL + * + * @psalm-immutable + */ +class OrderedTimeCodec extends StringCodec +{ + /** + * Returns a binary string representation of a UUID, with the timestamp + * fields rearranged for optimized storage + * + * @inheritDoc + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function encodeBinary(UuidInterface $uuid): string + { + if ( + !($uuid->getFields() instanceof Rfc4122FieldsInterface) + || $uuid->getFields()->getVersion() !== Uuid::UUID_TYPE_TIME + ) { + throw new InvalidArgumentException( + 'Expected RFC 4122 version 1 (time-based) UUID' + ); + } + + $bytes = $uuid->getFields()->getBytes(); + + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ + return $bytes[6] . $bytes[7] + . $bytes[4] . $bytes[5] + . $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3] + . substr($bytes, 8); + } + + /** + * Returns a UuidInterface derived from an ordered-time binary string + * representation + * + * @throws InvalidArgumentException if $bytes is an invalid length + * + * @inheritDoc + */ + public function decodeBytes(string $bytes): UuidInterface + { + if (strlen($bytes) !== 16) { + throw new InvalidArgumentException( + '$bytes string should contain 16 characters.' + ); + } + + // Rearrange the bytes to their original order. + $rearrangedBytes = $bytes[4] . $bytes[5] . $bytes[6] . $bytes[7] + . $bytes[2] . $bytes[3] + . $bytes[0] . $bytes[1] + . substr($bytes, 8); + + $uuid = parent::decodeBytes($rearrangedBytes); + + if ( + !($uuid->getFields() instanceof Rfc4122FieldsInterface) + || $uuid->getFields()->getVersion() !== Uuid::UUID_TYPE_TIME + ) { + throw new UnsupportedOperationException( + 'Attempting to decode a non-time-based UUID using ' + . 'OrderedTimeCodec' + ); + } + + return $uuid; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Codec/StringCodec.php b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/StringCodec.php new file mode 100644 index 0000000..95f38d2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/StringCodec.php @@ -0,0 +1,131 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Codec; + +use Ramsey\Uuid\Builder\UuidBuilderInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Exception\InvalidUuidStringException; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; + +use function bin2hex; +use function hex2bin; +use function implode; +use function sprintf; +use function str_replace; +use function strlen; +use function substr; + +/** + * StringCodec encodes and decodes RFC 4122 UUIDs + * + * @link http://tools.ietf.org/html/rfc4122 + * + * @psalm-immutable + */ +class StringCodec implements CodecInterface +{ + /** + * Constructs a StringCodec + * + * @param UuidBuilderInterface $builder The builder to use when encoding UUIDs + */ + public function __construct(private UuidBuilderInterface $builder) + { + } + + public function encode(UuidInterface $uuid): string + { + $hex = bin2hex($uuid->getFields()->getBytes()); + + /** @var non-empty-string */ + return sprintf( + '%08s-%04s-%04s-%04s-%012s', + substr($hex, 0, 8), + substr($hex, 8, 4), + substr($hex, 12, 4), + substr($hex, 16, 4), + substr($hex, 20), + ); + } + + /** + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function encodeBinary(UuidInterface $uuid): string + { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ + return $uuid->getFields()->getBytes(); + } + + /** + * @throws InvalidUuidStringException + * + * @inheritDoc + */ + public function decode(string $encodedUuid): UuidInterface + { + return $this->builder->build($this, $this->getBytes($encodedUuid)); + } + + public function decodeBytes(string $bytes): UuidInterface + { + if (strlen($bytes) !== 16) { + throw new InvalidArgumentException( + '$bytes string should contain 16 characters.' + ); + } + + return $this->builder->build($this, $bytes); + } + + /** + * Returns the UUID builder + */ + protected function getBuilder(): UuidBuilderInterface + { + return $this->builder; + } + + /** + * Returns a byte string of the UUID + */ + protected function getBytes(string $encodedUuid): string + { + $parsedUuid = str_replace( + ['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}', '-'], + '', + $encodedUuid + ); + + $components = [ + substr($parsedUuid, 0, 8), + substr($parsedUuid, 8, 4), + substr($parsedUuid, 12, 4), + substr($parsedUuid, 16, 4), + substr($parsedUuid, 20), + ]; + + if (!Uuid::isValid(implode('-', $components))) { + throw new InvalidUuidStringException( + 'Invalid UUID string: ' . $encodedUuid + ); + } + + return (string) hex2bin($parsedUuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Codec/TimestampFirstCombCodec.php b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/TimestampFirstCombCodec.php new file mode 100644 index 0000000..0e0042d --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/TimestampFirstCombCodec.php @@ -0,0 +1,113 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Codec; + +use Ramsey\Uuid\Exception\InvalidUuidStringException; +use Ramsey\Uuid\UuidInterface; + +use function bin2hex; +use function sprintf; +use function substr; +use function substr_replace; + +/** + * TimestampFirstCombCodec encodes and decodes COMBs, with the timestamp as the + * first 48 bits + * + * In contrast with the TimestampLastCombCodec, the TimestampFirstCombCodec + * adds the timestamp to the first 48 bits of the COMB. To generate a + * timestamp-first COMB, set the TimestampFirstCombCodec as the codec, along + * with the CombGenerator as the random generator. + * + * ``` php + * $factory = new UuidFactory(); + * + * $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder())); + * + * $factory->setRandomGenerator(new CombGenerator( + * $factory->getRandomGenerator(), + * $factory->getNumberConverter() + * )); + * + * $timestampFirstComb = $factory->uuid4(); + * ``` + * + * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys + * + * @psalm-immutable + */ +class TimestampFirstCombCodec extends StringCodec +{ + /** + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function encode(UuidInterface $uuid): string + { + $bytes = $this->swapBytes($uuid->getFields()->getBytes()); + + return sprintf( + '%08s-%04s-%04s-%04s-%012s', + bin2hex(substr($bytes, 0, 4)), + bin2hex(substr($bytes, 4, 2)), + bin2hex(substr($bytes, 6, 2)), + bin2hex(substr($bytes, 8, 2)), + bin2hex(substr($bytes, 10)) + ); + } + + /** + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function encodeBinary(UuidInterface $uuid): string + { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ + return $this->swapBytes($uuid->getFields()->getBytes()); + } + + /** + * @throws InvalidUuidStringException + * + * @inheritDoc + */ + public function decode(string $encodedUuid): UuidInterface + { + $bytes = $this->getBytes($encodedUuid); + + return $this->getBuilder()->build($this, $this->swapBytes($bytes)); + } + + public function decodeBytes(string $bytes): UuidInterface + { + return $this->getBuilder()->build($this, $this->swapBytes($bytes)); + } + + /** + * Swaps bytes according to the timestamp-first COMB rules + */ + private function swapBytes(string $bytes): string + { + $first48Bits = substr($bytes, 0, 6); + $last48Bits = substr($bytes, -6); + + $bytes = substr_replace($bytes, $last48Bits, 0, 6); + $bytes = substr_replace($bytes, $first48Bits, -6); + + return $bytes; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Codec/TimestampLastCombCodec.php b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/TimestampLastCombCodec.php new file mode 100644 index 0000000..4856dea --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Codec/TimestampLastCombCodec.php @@ -0,0 +1,51 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Codec; + +/** + * TimestampLastCombCodec encodes and decodes COMBs, with the timestamp as the + * last 48 bits + * + * The CombGenerator when used with the StringCodec (and, by proxy, the + * TimestampLastCombCodec) adds the timestamp to the last 48 bits of the COMB. + * The TimestampLastCombCodec is provided for the sake of consistency. In + * practice, it is identical to the standard StringCodec but, it may be used + * with the CombGenerator for additional context when reading code. + * + * Consider the following code. By default, the codec used by UuidFactory is the + * StringCodec, but here, we explicitly set the TimestampLastCombCodec. It is + * redundant, but it is clear that we intend this COMB to be generated with the + * timestamp appearing at the end. + * + * ``` php + * $factory = new UuidFactory(); + * + * $factory->setCodec(new TimestampLastCombCodec($factory->getUuidBuilder())); + * + * $factory->setRandomGenerator(new CombGenerator( + * $factory->getRandomGenerator(), + * $factory->getNumberConverter() + * )); + * + * $timestampLastComb = $factory->uuid4(); + * ``` + * + * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys + * + * @psalm-immutable + */ +class TimestampLastCombCodec extends StringCodec +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php new file mode 100644 index 0000000..99b88b3 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Number; + +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Math\BrickMathCalculator; + +/** + * Previously used to integrate moontoast/math as a bignum arithmetic library, + * BigNumberConverter is deprecated in favor of GenericNumberConverter + * + * @deprecated Transition to {@see GenericNumberConverter}. + * + * @psalm-immutable + */ +class BigNumberConverter implements NumberConverterInterface +{ + private NumberConverterInterface $converter; + + public function __construct() + { + $this->converter = new GenericNumberConverter(new BrickMathCalculator()); + } + + /** + * @inheritDoc + * @psalm-pure + */ + public function fromHex(string $hex): string + { + return $this->converter->fromHex($hex); + } + + /** + * @inheritDoc + * @psalm-pure + */ + public function toHex(string $number): string + { + return $this->converter->toHex($number); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/DegradedNumberConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/DegradedNumberConverter.php new file mode 100644 index 0000000..c9cfa68 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/DegradedNumberConverter.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Number; + +/** + * @deprecated DegradedNumberConverter is no longer necessary for converting + * numbers on 32-bit systems. Transition to {@see GenericNumberConverter}. + * + * @psalm-immutable + */ +class DegradedNumberConverter extends BigNumberConverter +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php new file mode 100644 index 0000000..043c3c4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Number; + +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Math\CalculatorInterface; +use Ramsey\Uuid\Type\Integer as IntegerObject; + +/** + * GenericNumberConverter uses the provided calculator to convert decimal + * numbers to and from hexadecimal values + * + * @psalm-immutable + */ +class GenericNumberConverter implements NumberConverterInterface +{ + public function __construct(private CalculatorInterface $calculator) + { + } + + /** + * @inheritDoc + * @psalm-pure + * @psalm-return numeric-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function fromHex(string $hex): string + { + return $this->calculator->fromBase($hex, 16)->toString(); + } + + /** + * @inheritDoc + * @psalm-pure + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function toHex(string $number): string + { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ + return $this->calculator->toBase(new IntegerObject($number), 16); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/NumberConverterInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/NumberConverterInterface.php new file mode 100644 index 0000000..b33ec31 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/NumberConverterInterface.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter; + +/** + * A number converter converts UUIDs from hexadecimal characters into + * representations of integers and vice versa + * + * @psalm-immutable + */ +interface NumberConverterInterface +{ + /** + * Converts a hexadecimal number into an string integer representation of + * the number + * + * The integer representation returned is a string representation of the + * integer, to accommodate unsigned integers greater than PHP_INT_MAX. + * + * @param string $hex The hexadecimal string representation to convert + * + * @return string String representation of an integer + * + * @psalm-return numeric-string + * + * @psalm-pure + */ + public function fromHex(string $hex): string; + + /** + * Converts a string integer representation into a hexadecimal string + * representation of the number + * + * @param string $number A string integer representation to convert; this + * must be a numeric string to accommodate unsigned integers greater + * than PHP_INT_MAX. + * + * @return string Hexadecimal string + * + * @psalm-return non-empty-string + * + * @psalm-pure + */ + public function toHex(string $number): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php new file mode 100644 index 0000000..b6bca9e --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php @@ -0,0 +1,48 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Time; + +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Math\BrickMathCalculator; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Time; + +/** + * Previously used to integrate moontoast/math as a bignum arithmetic library, + * BigNumberTimeConverter is deprecated in favor of GenericTimeConverter + * + * @deprecated Transition to {@see GenericTimeConverter}. + * + * @psalm-immutable + */ +class BigNumberTimeConverter implements TimeConverterInterface +{ + private TimeConverterInterface $converter; + + public function __construct() + { + $this->converter = new GenericTimeConverter(new BrickMathCalculator()); + } + + public function calculateTime(string $seconds, string $microseconds): Hexadecimal + { + return $this->converter->calculateTime($seconds, $microseconds); + } + + public function convertTime(Hexadecimal $uuidTimestamp): Time + { + return $this->converter->convertTime($uuidTimestamp); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/DegradedTimeConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/DegradedTimeConverter.php new file mode 100644 index 0000000..cdc2875 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/DegradedTimeConverter.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Time; + +/** + * @deprecated DegradedTimeConverter is no longer necessary for converting + * time on 32-bit systems. Transition to {@see GenericTimeConverter}. + * + * @psalm-immutable + */ +class DegradedTimeConverter extends BigNumberTimeConverter +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php new file mode 100644 index 0000000..f6b60ab --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php @@ -0,0 +1,118 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Time; + +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Math\CalculatorInterface; +use Ramsey\Uuid\Math\RoundingMode; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\Time; + +use function explode; +use function str_pad; + +use const STR_PAD_LEFT; + +/** + * GenericTimeConverter uses the provided calculator to calculate and convert + * time values + * + * @psalm-immutable + */ +class GenericTimeConverter implements TimeConverterInterface +{ + /** + * The number of 100-nanosecond intervals from the Gregorian calendar epoch + * to the Unix epoch. + */ + private const GREGORIAN_TO_UNIX_INTERVALS = '122192928000000000'; + + /** + * The number of 100-nanosecond intervals in one second. + */ + private const SECOND_INTERVALS = '10000000'; + + /** + * The number of 100-nanosecond intervals in one microsecond. + */ + private const MICROSECOND_INTERVALS = '10'; + + public function __construct(private CalculatorInterface $calculator) + { + } + + public function calculateTime(string $seconds, string $microseconds): Hexadecimal + { + $timestamp = new Time($seconds, $microseconds); + + // Convert the seconds into a count of 100-nanosecond intervals. + $sec = $this->calculator->multiply( + $timestamp->getSeconds(), + new IntegerObject(self::SECOND_INTERVALS) + ); + + // Convert the microseconds into a count of 100-nanosecond intervals. + $usec = $this->calculator->multiply( + $timestamp->getMicroseconds(), + new IntegerObject(self::MICROSECOND_INTERVALS) + ); + + // Combine the seconds and microseconds intervals and add the count of + // 100-nanosecond intervals from the Gregorian calendar epoch to the + // Unix epoch. This gives us the correct count of 100-nanosecond + // intervals since the Gregorian calendar epoch for the given seconds + // and microseconds. + /** @var IntegerObject $uuidTime */ + $uuidTime = $this->calculator->add( + $sec, + $usec, + new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS) + ); + + $uuidTimeHex = str_pad( + $this->calculator->toHexadecimal($uuidTime)->toString(), + 16, + '0', + STR_PAD_LEFT + ); + + return new Hexadecimal($uuidTimeHex); + } + + public function convertTime(Hexadecimal $uuidTimestamp): Time + { + // From the total, subtract the number of 100-nanosecond intervals from + // the Gregorian calendar epoch to the Unix epoch. This gives us the + // number of 100-nanosecond intervals from the Unix epoch, which also + // includes the microtime. + $epochNanoseconds = $this->calculator->subtract( + $this->calculator->toInteger($uuidTimestamp), + new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS) + ); + + // Convert the 100-nanosecond intervals into seconds and microseconds. + $unixTimestamp = $this->calculator->divide( + RoundingMode::HALF_UP, + 6, + $epochNanoseconds, + new IntegerObject(self::SECOND_INTERVALS) + ); + + $split = explode('.', (string) $unixTimestamp, 2); + + return new Time($split[0], $split[1] ?? 0); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php new file mode 100644 index 0000000..66009f1 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php @@ -0,0 +1,172 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Time; + +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Math\BrickMathCalculator; +use Ramsey\Uuid\Math\CalculatorInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\Time; + +use function count; +use function dechex; +use function explode; +use function is_float; +use function is_int; +use function str_pad; +use function strlen; +use function substr; + +use const STR_PAD_LEFT; +use const STR_PAD_RIGHT; + +/** + * PhpTimeConverter uses built-in PHP functions and standard math operations + * available to the PHP programming language to provide facilities for + * converting parts of time into representations that may be used in UUIDs + * + * @psalm-immutable + */ +class PhpTimeConverter implements TimeConverterInterface +{ + /** + * The number of 100-nanosecond intervals from the Gregorian calendar epoch + * to the Unix epoch. + */ + private const GREGORIAN_TO_UNIX_INTERVALS = 0x01b21dd213814000; + + /** + * The number of 100-nanosecond intervals in one second. + */ + private const SECOND_INTERVALS = 10000000; + + /** + * The number of 100-nanosecond intervals in one microsecond. + */ + private const MICROSECOND_INTERVALS = 10; + + private int $phpPrecision; + private CalculatorInterface $calculator; + private TimeConverterInterface $fallbackConverter; + + public function __construct( + ?CalculatorInterface $calculator = null, + ?TimeConverterInterface $fallbackConverter = null + ) { + if ($calculator === null) { + $calculator = new BrickMathCalculator(); + } + + if ($fallbackConverter === null) { + $fallbackConverter = new GenericTimeConverter($calculator); + } + + $this->calculator = $calculator; + $this->fallbackConverter = $fallbackConverter; + $this->phpPrecision = (int) ini_get('precision'); + } + + public function calculateTime(string $seconds, string $microseconds): Hexadecimal + { + $seconds = new IntegerObject($seconds); + $microseconds = new IntegerObject($microseconds); + + // Calculate the count of 100-nanosecond intervals since the Gregorian + // calendar epoch for the given seconds and microseconds. + $uuidTime = ((int) $seconds->toString() * self::SECOND_INTERVALS) + + ((int) $microseconds->toString() * self::MICROSECOND_INTERVALS) + + self::GREGORIAN_TO_UNIX_INTERVALS; + + // Check to see whether we've overflowed the max/min integer size. + // If so, we will default to a different time converter. + /** @psalm-suppress RedundantCondition */ + if (!is_int($uuidTime)) { + return $this->fallbackConverter->calculateTime( + $seconds->toString(), + $microseconds->toString() + ); + } + + return new Hexadecimal(str_pad(dechex($uuidTime), 16, '0', STR_PAD_LEFT)); + } + + public function convertTime(Hexadecimal $uuidTimestamp): Time + { + $timestamp = $this->calculator->toInteger($uuidTimestamp); + + // Convert the 100-nanosecond intervals into seconds and microseconds. + $splitTime = $this->splitTime( + ((int) $timestamp->toString() - self::GREGORIAN_TO_UNIX_INTERVALS) + / self::SECOND_INTERVALS + ); + + if (count($splitTime) === 0) { + return $this->fallbackConverter->convertTime($uuidTimestamp); + } + + return new Time($splitTime['sec'], $splitTime['usec']); + } + + /** + * @param float|int $time The time to split into seconds and microseconds + * + * @return string[] + */ + private function splitTime(float | int $time): array + { + $split = explode('.', (string) $time, 2); + + // If the $time value is a float but $split only has 1 element, then the + // float math was rounded up to the next second, so we want to return + // an empty array to allow use of the fallback converter. + if (is_float($time) && count($split) === 1) { + return []; + } + + if (count($split) === 1) { + return [ + 'sec' => $split[0], + 'usec' => '0', + ]; + } + + // If the microseconds are less than six characters AND the length of + // the number is greater than or equal to the PHP precision, then it's + // possible that we lost some precision for the microseconds. Return an + // empty array, so that we can choose to use the fallback converter. + if (strlen($split[1]) < 6 && strlen((string) $time) >= $this->phpPrecision) { + return []; + } + + $microseconds = $split[1]; + + // Ensure the microseconds are no longer than 6 digits. If they are, + // truncate the number to the first 6 digits and round up, if needed. + if (strlen($microseconds) > 6) { + $roundingDigit = (int) substr($microseconds, 6, 1); + $microseconds = (int) substr($microseconds, 0, 6); + + if ($roundingDigit >= 5) { + $microseconds++; + } + } + + return [ + 'sec' => $split[0], + 'usec' => str_pad((string) $microseconds, 6, '0', STR_PAD_RIGHT), + ]; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/UnixTimeConverter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/UnixTimeConverter.php new file mode 100644 index 0000000..4d6d0a8 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/Time/UnixTimeConverter.php @@ -0,0 +1,90 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter\Time; + +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Math\CalculatorInterface; +use Ramsey\Uuid\Math\RoundingMode; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\Time; + +use function explode; +use function str_pad; + +use const STR_PAD_LEFT; + +/** + * UnixTimeConverter converts Unix Epoch timestamps to/from hexadecimal values + * consisting of milliseconds elapsed since the Unix Epoch + * + * @psalm-immutable + */ +class UnixTimeConverter implements TimeConverterInterface +{ + private const MILLISECONDS = 1000; + + public function __construct(private CalculatorInterface $calculator) + { + } + + public function calculateTime(string $seconds, string $microseconds): Hexadecimal + { + $timestamp = new Time($seconds, $microseconds); + + // Convert the seconds into milliseconds. + $sec = $this->calculator->multiply( + $timestamp->getSeconds(), + new IntegerObject(self::MILLISECONDS), + ); + + // Convert the microseconds into milliseconds; the scale is zero because + // we need to discard the fractional part. + $usec = $this->calculator->divide( + RoundingMode::DOWN, // Always round down to stay in the previous millisecond. + 0, + $timestamp->getMicroseconds(), + new IntegerObject(self::MILLISECONDS), + ); + + /** @var IntegerObject $unixTime */ + $unixTime = $this->calculator->add($sec, $usec); + + $unixTimeHex = str_pad( + $this->calculator->toHexadecimal($unixTime)->toString(), + 12, + '0', + STR_PAD_LEFT + ); + + return new Hexadecimal($unixTimeHex); + } + + public function convertTime(Hexadecimal $uuidTimestamp): Time + { + $milliseconds = $this->calculator->toInteger($uuidTimestamp); + + $unixTimestamp = $this->calculator->divide( + RoundingMode::HALF_UP, + 6, + $milliseconds, + new IntegerObject(self::MILLISECONDS) + ); + + $split = explode('.', (string) $unixTimestamp, 2); + + return new Time($split[0], $split[1] ?? '0'); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Converter/TimeConverterInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/TimeConverterInterface.php new file mode 100644 index 0000000..1e84807 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Converter/TimeConverterInterface.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Converter; + +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Time; + +/** + * A time converter converts timestamps into representations that may be used + * in UUIDs + * + * @psalm-immutable + */ +interface TimeConverterInterface +{ + /** + * Uses the provided seconds and micro-seconds to calculate the count of + * 100-nanosecond intervals since UTC 00:00:00.00, 15 October 1582, for + * RFC 4122 variant UUIDs + * + * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 RFC 4122, § 4.2.2: Generation Details + * + * @param string $seconds A string representation of the number of seconds + * since the Unix epoch for the time to calculate + * @param string $microseconds A string representation of the micro-seconds + * associated with the time to calculate + * + * @return Hexadecimal The full UUID timestamp as a Hexadecimal value + * + * @psalm-pure + */ + public function calculateTime(string $seconds, string $microseconds): Hexadecimal; + + /** + * Converts a timestamp extracted from a UUID to a Unix timestamp + * + * @param Hexadecimal $uuidTimestamp A hexadecimal representation of a UUID + * timestamp; a UUID timestamp is a count of 100-nanosecond intervals + * since UTC 00:00:00.00, 15 October 1582. + * + * @return Time An instance of {@see Time} + * + * @psalm-pure + */ + public function convertTime(Hexadecimal $uuidTimestamp): Time; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/DegradedUuid.php b/php/libraries/composer/vendor/ramsey/uuid/src/DegradedUuid.php new file mode 100644 index 0000000..9166042 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/DegradedUuid.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +/** + * @deprecated DegradedUuid is no longer necessary to represent UUIDs on 32-bit + * systems. Transition typehints to {@see UuidInterface}. + * + * @psalm-immutable + */ +class DegradedUuid extends Uuid +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php new file mode 100644 index 0000000..ac01a79 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php @@ -0,0 +1,140 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use DateTimeInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; + +/** + * This interface encapsulates deprecated methods for ramsey/uuid + * + * @psalm-immutable + */ +interface DeprecatedUuidInterface +{ + /** + * @deprecated This method will be removed in 5.0.0. There is no alternative + * recommendation, so plan accordingly. + */ + public function getNumberConverter(): NumberConverterInterface; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. + * + * @return string[] + */ + public function getFieldsHex(): array; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()}. + */ + public function getClockSeqHiAndReservedHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()}. + */ + public function getClockSeqLowHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()}. + */ + public function getClockSequenceHex(): string; + + /** + * @deprecated In ramsey/uuid version 5.0.0, this will be removed from the + * interface. It is available at {@see UuidV1::getDateTime()}. + */ + public function getDateTime(): DateTimeInterface; + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + */ + public function getLeastSignificantBitsHex(): string; + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + */ + public function getMostSignificantBitsHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()}. + */ + public function getNodeHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()}. + */ + public function getTimeHiAndVersionHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()}. + */ + public function getTimeLowHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()}. + */ + public function getTimeMidHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()}. + */ + public function getTimestampHex(): string; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant()}. + */ + public function getVariant(): ?int; + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. + */ + public function getVersion(): ?int; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php new file mode 100644 index 0000000..d3fbb0c --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php @@ -0,0 +1,360 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use DateTimeImmutable; +use DateTimeInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Exception\DateTimeException; +use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Throwable; + +use function str_pad; +use function substr; + +use const STR_PAD_LEFT; + +/** + * This trait encapsulates deprecated methods for ramsey/uuid; this trait and + * its methods will be removed in ramsey/uuid 5.0.0. + * + * @deprecated This trait and its methods will be removed in ramsey/uuid 5.0.0. + * + * @psalm-immutable + */ +trait DeprecatedUuidMethodsTrait +{ + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + */ + public function getClockSeqHiAndReserved(): string + { + return $this->numberConverter->fromHex($this->fields->getClockSeqHiAndReserved()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()}. + */ + public function getClockSeqHiAndReservedHex(): string + { + return $this->fields->getClockSeqHiAndReserved()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + */ + public function getClockSeqLow(): string + { + return $this->numberConverter->fromHex($this->fields->getClockSeqLow()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()}. + */ + public function getClockSeqLowHex(): string + { + return $this->fields->getClockSeqLow()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + */ + public function getClockSequence(): string + { + return $this->numberConverter->fromHex($this->fields->getClockSeq()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()}. + */ + public function getClockSequenceHex(): string + { + return $this->fields->getClockSeq()->toString(); + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no alternative + * recommendation, so plan accordingly. + */ + public function getNumberConverter(): NumberConverterInterface + { + return $this->numberConverter; + } + + /** + * @deprecated In ramsey/uuid version 5.0.0, this will be removed. + * It is available at {@see UuidV1::getDateTime()}. + * + * @return DateTimeImmutable An immutable instance of DateTimeInterface + * + * @throws UnsupportedOperationException if UUID is not time-based + * @throws DateTimeException if DateTime throws an exception/error + */ + public function getDateTime(): DateTimeInterface + { + if ($this->fields->getVersion() !== 1) { + throw new UnsupportedOperationException('Not a time-based UUID'); + } + + $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); + + try { + return new DateTimeImmutable( + '@' + . $time->getSeconds()->toString() + . '.' + . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) + ); + } catch (Throwable $e) { + throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); + } + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. + * + * @return string[] + */ + public function getFieldsHex(): array + { + return [ + 'time_low' => $this->fields->getTimeLow()->toString(), + 'time_mid' => $this->fields->getTimeMid()->toString(), + 'time_hi_and_version' => $this->fields->getTimeHiAndVersion()->toString(), + 'clock_seq_hi_and_reserved' => $this->fields->getClockSeqHiAndReserved()->toString(), + 'clock_seq_low' => $this->fields->getClockSeqLow()->toString(), + 'node' => $this->fields->getNode()->toString(), + ]; + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + */ + public function getLeastSignificantBits(): string + { + $leastSignificantHex = substr($this->getHex()->toString(), 16); + + return $this->numberConverter->fromHex($leastSignificantHex); + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + */ + public function getLeastSignificantBitsHex(): string + { + return substr($this->getHex()->toString(), 16); + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + */ + public function getMostSignificantBits(): string + { + $mostSignificantHex = substr($this->getHex()->toString(), 0, 16); + + return $this->numberConverter->fromHex($mostSignificantHex); + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + */ + public function getMostSignificantBitsHex(): string + { + return substr($this->getHex()->toString(), 0, 16); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()} and use the + * arbitrary-precision math library of your choice to convert it to a + * string integer. + */ + public function getNode(): string + { + return $this->numberConverter->fromHex($this->fields->getNode()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()}. + */ + public function getNodeHex(): string + { + return $this->fields->getNode()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + */ + public function getTimeHiAndVersion(): string + { + return $this->numberConverter->fromHex($this->fields->getTimeHiAndVersion()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()}. + */ + public function getTimeHiAndVersionHex(): string + { + return $this->fields->getTimeHiAndVersion()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()} and use the + * arbitrary-precision math library of your choice to convert it to a + * string integer. + */ + public function getTimeLow(): string + { + return $this->numberConverter->fromHex($this->fields->getTimeLow()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()}. + */ + public function getTimeLowHex(): string + { + return $this->fields->getTimeLow()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()} and use the + * arbitrary-precision math library of your choice to convert it to a + * string integer. + */ + public function getTimeMid(): string + { + return $this->numberConverter->fromHex($this->fields->getTimeMid()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()}. + */ + public function getTimeMidHex(): string + { + return $this->fields->getTimeMid()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()} and use + * the arbitrary-precision math library of your choice to convert it to + * a string integer. + */ + public function getTimestamp(): string + { + if ($this->fields->getVersion() !== 1) { + throw new UnsupportedOperationException('Not a time-based UUID'); + } + + return $this->numberConverter->fromHex($this->fields->getTimestamp()->toString()); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()}. + */ + public function getTimestampHex(): string + { + if ($this->fields->getVersion() !== 1) { + throw new UnsupportedOperationException('Not a time-based UUID'); + } + + return $this->fields->getTimestamp()->toString(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant()}. + */ + public function getVariant(): ?int + { + return $this->fields->getVariant(); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call + * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. + */ + public function getVersion(): ?int + { + return $this->fields->getVersion(); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/BuilderNotFoundException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/BuilderNotFoundException.php new file mode 100644 index 0000000..220ffed --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/BuilderNotFoundException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that no suitable builder could be found + */ +class BuilderNotFoundException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/DateTimeException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/DateTimeException.php new file mode 100644 index 0000000..5f0e658 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/DateTimeException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that the PHP DateTime extension encountered an exception/error + */ +class DateTimeException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/DceSecurityException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/DceSecurityException.php new file mode 100644 index 0000000..e6d8001 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/DceSecurityException.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate an exception occurred while dealing with DCE Security + * (version 2) UUIDs + */ +class DceSecurityException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..2a1fa3a --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidArgumentException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use InvalidArgumentException as PhpInvalidArgumentException; + +/** + * Thrown to indicate that the argument received is not valid + */ +class InvalidArgumentException extends PhpInvalidArgumentException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidBytesException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidBytesException.php new file mode 100644 index 0000000..1c94f65 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidBytesException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that the bytes being operated on are invalid in some way + */ +class InvalidBytesException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidUuidStringException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidUuidStringException.php new file mode 100644 index 0000000..6d97581 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/InvalidUuidStringException.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +/** + * Thrown to indicate that the string received is not a valid UUID + * + * The InvalidArgumentException that this extends is the ramsey/uuid version + * of this exception. It exists in the same namespace as this class. + */ +class InvalidUuidStringException extends InvalidArgumentException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/NameException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/NameException.php new file mode 100644 index 0000000..fd96a1f --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/NameException.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that an error occurred while attempting to hash a + * namespace and name + */ +class NameException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/NodeException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/NodeException.php new file mode 100644 index 0000000..0dbdd50 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/NodeException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that attempting to fetch or create a node ID encountered an error + */ +class NodeException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/RandomSourceException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/RandomSourceException.php new file mode 100644 index 0000000..a44dd34 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/RandomSourceException.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that the source of random data encountered an error + * + * This exception is used mostly to indicate that random_bytes() or random_int() + * threw an exception. However, it may be used for other sources of random data. + */ +class RandomSourceException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/TimeSourceException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/TimeSourceException.php new file mode 100644 index 0000000..fc9cf36 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/TimeSourceException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate that the source of time encountered an error + */ +class TimeSourceException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UnableToBuildUuidException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UnableToBuildUuidException.php new file mode 100644 index 0000000..5ba26d8 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UnableToBuildUuidException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use RuntimeException as PhpRuntimeException; + +/** + * Thrown to indicate a builder is unable to build a UUID + */ +class UnableToBuildUuidException extends PhpRuntimeException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UnsupportedOperationException.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UnsupportedOperationException.php new file mode 100644 index 0000000..e1b3eda --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UnsupportedOperationException.php @@ -0,0 +1,24 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use LogicException as PhpLogicException; + +/** + * Thrown to indicate that the requested operation is not supported + */ +class UnsupportedOperationException extends PhpLogicException implements UuidExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UuidExceptionInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UuidExceptionInterface.php new file mode 100644 index 0000000..a2f1c10 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Exception/UuidExceptionInterface.php @@ -0,0 +1,21 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use Throwable; + +interface UuidExceptionInterface extends Throwable +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/FeatureSet.php b/php/libraries/composer/vendor/ramsey/uuid/src/FeatureSet.php new file mode 100644 index 0000000..b9af869 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/FeatureSet.php @@ -0,0 +1,397 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use Ramsey\Uuid\Builder\FallbackBuilder; +use Ramsey\Uuid\Builder\UuidBuilderInterface; +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Codec\GuidStringCodec; +use Ramsey\Uuid\Codec\StringCodec; +use Ramsey\Uuid\Converter\Number\GenericNumberConverter; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\Time\GenericTimeConverter; +use Ramsey\Uuid\Converter\Time\PhpTimeConverter; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Generator\DceSecurityGenerator; +use Ramsey\Uuid\Generator\DceSecurityGeneratorInterface; +use Ramsey\Uuid\Generator\NameGeneratorFactory; +use Ramsey\Uuid\Generator\NameGeneratorInterface; +use Ramsey\Uuid\Generator\PeclUuidNameGenerator; +use Ramsey\Uuid\Generator\PeclUuidRandomGenerator; +use Ramsey\Uuid\Generator\PeclUuidTimeGenerator; +use Ramsey\Uuid\Generator\RandomGeneratorFactory; +use Ramsey\Uuid\Generator\RandomGeneratorInterface; +use Ramsey\Uuid\Generator\TimeGeneratorFactory; +use Ramsey\Uuid\Generator\TimeGeneratorInterface; +use Ramsey\Uuid\Generator\UnixTimeGenerator; +use Ramsey\Uuid\Guid\GuidBuilder; +use Ramsey\Uuid\Math\BrickMathCalculator; +use Ramsey\Uuid\Math\CalculatorInterface; +use Ramsey\Uuid\Nonstandard\UuidBuilder as NonstandardUuidBuilder; +use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider; +use Ramsey\Uuid\Provider\DceSecurityProviderInterface; +use Ramsey\Uuid\Provider\Node\FallbackNodeProvider; +use Ramsey\Uuid\Provider\Node\RandomNodeProvider; +use Ramsey\Uuid\Provider\Node\SystemNodeProvider; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Provider\Time\SystemTimeProvider; +use Ramsey\Uuid\Provider\TimeProviderInterface; +use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder; +use Ramsey\Uuid\Validator\GenericValidator; +use Ramsey\Uuid\Validator\ValidatorInterface; + +use const PHP_INT_SIZE; + +/** + * FeatureSet detects and exposes available features in the current environment + * + * A feature set is used by UuidFactory to determine the available features and + * capabilities of the environment. + */ +class FeatureSet +{ + private ?TimeProviderInterface $timeProvider = null; + private CalculatorInterface $calculator; + private CodecInterface $codec; + private DceSecurityGeneratorInterface $dceSecurityGenerator; + private NameGeneratorInterface $nameGenerator; + private NodeProviderInterface $nodeProvider; + private NumberConverterInterface $numberConverter; + private RandomGeneratorInterface $randomGenerator; + private TimeConverterInterface $timeConverter; + private TimeGeneratorInterface $timeGenerator; + private TimeGeneratorInterface $unixTimeGenerator; + private UuidBuilderInterface $builder; + private ValidatorInterface $validator; + + /** + * @param bool $useGuids True build UUIDs using the GuidStringCodec + * @param bool $force32Bit True to force the use of 32-bit functionality + * (primarily for testing purposes) + * @param bool $forceNoBigNumber (obsolete) + * @param bool $ignoreSystemNode True to disable attempts to check for the + * system node ID (primarily for testing purposes) + * @param bool $enablePecl True to enable the use of the PeclUuidTimeGenerator + * to generate version 1 UUIDs + */ + public function __construct( + bool $useGuids = false, + private bool $force32Bit = false, + bool $forceNoBigNumber = false, + private bool $ignoreSystemNode = false, + private bool $enablePecl = false + ) { + $this->randomGenerator = $this->buildRandomGenerator(); + $this->setCalculator(new BrickMathCalculator()); + $this->builder = $this->buildUuidBuilder($useGuids); + $this->codec = $this->buildCodec($useGuids); + $this->nodeProvider = $this->buildNodeProvider(); + $this->nameGenerator = $this->buildNameGenerator(); + $this->setTimeProvider(new SystemTimeProvider()); + $this->setDceSecurityProvider(new SystemDceSecurityProvider()); + $this->validator = new GenericValidator(); + + assert($this->timeProvider !== null); + $this->unixTimeGenerator = $this->buildUnixTimeGenerator(); + } + + /** + * Returns the builder configured for this environment + */ + public function getBuilder(): UuidBuilderInterface + { + return $this->builder; + } + + /** + * Returns the calculator configured for this environment + */ + public function getCalculator(): CalculatorInterface + { + return $this->calculator; + } + + /** + * Returns the codec configured for this environment + */ + public function getCodec(): CodecInterface + { + return $this->codec; + } + + /** + * Returns the DCE Security generator configured for this environment + */ + public function getDceSecurityGenerator(): DceSecurityGeneratorInterface + { + return $this->dceSecurityGenerator; + } + + /** + * Returns the name generator configured for this environment + */ + public function getNameGenerator(): NameGeneratorInterface + { + return $this->nameGenerator; + } + + /** + * Returns the node provider configured for this environment + */ + public function getNodeProvider(): NodeProviderInterface + { + return $this->nodeProvider; + } + + /** + * Returns the number converter configured for this environment + */ + public function getNumberConverter(): NumberConverterInterface + { + return $this->numberConverter; + } + + /** + * Returns the random generator configured for this environment + */ + public function getRandomGenerator(): RandomGeneratorInterface + { + return $this->randomGenerator; + } + + /** + * Returns the time converter configured for this environment + */ + public function getTimeConverter(): TimeConverterInterface + { + return $this->timeConverter; + } + + /** + * Returns the time generator configured for this environment + */ + public function getTimeGenerator(): TimeGeneratorInterface + { + return $this->timeGenerator; + } + + /** + * Returns the Unix Epoch time generator configured for this environment + */ + public function getUnixTimeGenerator(): TimeGeneratorInterface + { + return $this->unixTimeGenerator; + } + + /** + * Returns the validator configured for this environment + */ + public function getValidator(): ValidatorInterface + { + return $this->validator; + } + + /** + * Sets the calculator to use in this environment + */ + public function setCalculator(CalculatorInterface $calculator): void + { + $this->calculator = $calculator; + $this->numberConverter = $this->buildNumberConverter($calculator); + $this->timeConverter = $this->buildTimeConverter($calculator); + + /** @psalm-suppress RedundantPropertyInitializationCheck */ + if (isset($this->timeProvider)) { + $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); + } + } + + /** + * Sets the DCE Security provider to use in this environment + */ + public function setDceSecurityProvider(DceSecurityProviderInterface $dceSecurityProvider): void + { + $this->dceSecurityGenerator = $this->buildDceSecurityGenerator($dceSecurityProvider); + } + + /** + * Sets the node provider to use in this environment + */ + public function setNodeProvider(NodeProviderInterface $nodeProvider): void + { + $this->nodeProvider = $nodeProvider; + + if (isset($this->timeProvider)) { + $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); + } + } + + /** + * Sets the time provider to use in this environment + */ + public function setTimeProvider(TimeProviderInterface $timeProvider): void + { + $this->timeProvider = $timeProvider; + $this->timeGenerator = $this->buildTimeGenerator($timeProvider); + } + + /** + * Set the validator to use in this environment + */ + public function setValidator(ValidatorInterface $validator): void + { + $this->validator = $validator; + } + + /** + * Returns a codec configured for this environment + * + * @param bool $useGuids Whether to build UUIDs using the GuidStringCodec + */ + private function buildCodec(bool $useGuids = false): CodecInterface + { + if ($useGuids) { + return new GuidStringCodec($this->builder); + } + + return new StringCodec($this->builder); + } + + /** + * Returns a DCE Security generator configured for this environment + */ + private function buildDceSecurityGenerator( + DceSecurityProviderInterface $dceSecurityProvider + ): DceSecurityGeneratorInterface { + return new DceSecurityGenerator( + $this->numberConverter, + $this->timeGenerator, + $dceSecurityProvider + ); + } + + /** + * Returns a node provider configured for this environment + */ + private function buildNodeProvider(): NodeProviderInterface + { + if ($this->ignoreSystemNode) { + return new RandomNodeProvider(); + } + + return new FallbackNodeProvider([ + new SystemNodeProvider(), + new RandomNodeProvider(), + ]); + } + + /** + * Returns a number converter configured for this environment + */ + private function buildNumberConverter(CalculatorInterface $calculator): NumberConverterInterface + { + return new GenericNumberConverter($calculator); + } + + /** + * Returns a random generator configured for this environment + */ + private function buildRandomGenerator(): RandomGeneratorInterface + { + if ($this->enablePecl) { + return new PeclUuidRandomGenerator(); + } + + return (new RandomGeneratorFactory())->getGenerator(); + } + + /** + * Returns a time generator configured for this environment + * + * @param TimeProviderInterface $timeProvider The time provider to use with + * the time generator + */ + private function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGeneratorInterface + { + if ($this->enablePecl) { + return new PeclUuidTimeGenerator(); + } + + return (new TimeGeneratorFactory( + $this->nodeProvider, + $this->timeConverter, + $timeProvider + ))->getGenerator(); + } + + /** + * Returns a Unix Epoch time generator configured for this environment + */ + private function buildUnixTimeGenerator(): TimeGeneratorInterface + { + return new UnixTimeGenerator($this->randomGenerator); + } + + /** + * Returns a name generator configured for this environment + */ + private function buildNameGenerator(): NameGeneratorInterface + { + if ($this->enablePecl) { + return new PeclUuidNameGenerator(); + } + + return (new NameGeneratorFactory())->getGenerator(); + } + + /** + * Returns a time converter configured for this environment + */ + private function buildTimeConverter(CalculatorInterface $calculator): TimeConverterInterface + { + $genericConverter = new GenericTimeConverter($calculator); + + if ($this->is64BitSystem()) { + return new PhpTimeConverter($calculator, $genericConverter); + } + + return $genericConverter; + } + + /** + * Returns a UUID builder configured for this environment + * + * @param bool $useGuids Whether to build UUIDs using the GuidStringCodec + */ + private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface + { + if ($useGuids) { + return new GuidBuilder($this->numberConverter, $this->timeConverter); + } + + return new FallbackBuilder([ + new Rfc4122UuidBuilder($this->numberConverter, $this->timeConverter), + new NonstandardUuidBuilder($this->numberConverter, $this->timeConverter), + ]); + } + + /** + * Returns true if the PHP build is 64-bit + */ + private function is64BitSystem(): bool + { + return PHP_INT_SIZE === 8 && !$this->force32Bit; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Fields/FieldsInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Fields/FieldsInterface.php new file mode 100644 index 0000000..f1b7a29 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Fields/FieldsInterface.php @@ -0,0 +1,32 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Fields; + +use Serializable; + +/** + * UUIDs are comprised of unsigned integers, the bytes of which are separated + * into fields and arranged in a particular layout defined by the specification + * for the variant + * + * @psalm-immutable + */ +interface FieldsInterface extends Serializable +{ + /** + * Returns the bytes that comprise the fields + */ + public function getBytes(): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php new file mode 100644 index 0000000..3d36b6f --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php @@ -0,0 +1,87 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Fields; + +use ValueError; + +use function base64_decode; +use function sprintf; +use function strlen; + +/** + * Provides common serialization functionality to fields + * + * @psalm-immutable + */ +trait SerializableFieldsTrait +{ + /** + * @param string $bytes The bytes that comprise the fields + */ + abstract public function __construct(string $bytes); + + /** + * Returns the bytes that comprise the fields + */ + abstract public function getBytes(): string; + + /** + * Returns a string representation of object + */ + public function serialize(): string + { + return $this->getBytes(); + } + + /** + * @return array{bytes: string} + */ + public function __serialize(): array + { + return ['bytes' => $this->getBytes()]; + } + + /** + * Constructs the object from a serialized string representation + * + * @param string $data The serialized string representation of the object + * + * @psalm-suppress UnusedMethodCall + */ + public function unserialize(string $data): void + { + if (strlen($data) === 16) { + $this->__construct($data); + } else { + $this->__construct(base64_decode($data)); + } + } + + /** + * @param array{bytes?: string} $data + * + * @psalm-suppress UnusedMethodCall + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['bytes'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['bytes']); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/CombGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/CombGenerator.php new file mode 100644 index 0000000..0e88706 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/CombGenerator.php @@ -0,0 +1,115 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; + +use function bin2hex; +use function explode; +use function hex2bin; +use function microtime; +use function str_pad; +use function substr; + +use const STR_PAD_LEFT; + +/** + * CombGenerator generates COMBs (combined UUID/timestamp) + * + * The CombGenerator, when used with the StringCodec (and, by proxy, the + * TimestampLastCombCodec) or the TimestampFirstCombCodec, combines the current + * timestamp with a UUID (hence the name "COMB"). The timestamp either appears + * as the first or last 48 bits of the COMB, depending on the codec used. + * + * By default, COMBs will have the timestamp set as the last 48 bits of the + * identifier. + * + * ``` php + * $factory = new UuidFactory(); + * + * $factory->setRandomGenerator(new CombGenerator( + * $factory->getRandomGenerator(), + * $factory->getNumberConverter() + * )); + * + * $comb = $factory->uuid4(); + * ``` + * + * To generate a COMB with the timestamp as the first 48 bits, set the + * TimestampFirstCombCodec as the codec. + * + * ``` php + * $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder())); + * ``` + * + * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys + */ +class CombGenerator implements RandomGeneratorInterface +{ + public const TIMESTAMP_BYTES = 6; + + public function __construct( + private RandomGeneratorInterface $generator, + private NumberConverterInterface $numberConverter + ) { + } + + /** + * @throws InvalidArgumentException if $length is not a positive integer + * greater than or equal to CombGenerator::TIMESTAMP_BYTES + * + * @inheritDoc + */ + public function generate(int $length): string + { + if ($length < self::TIMESTAMP_BYTES) { + throw new InvalidArgumentException( + 'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES + ); + } + + $hash = ''; + if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) { + $hash = $this->generator->generate($length - self::TIMESTAMP_BYTES); + } + + $lsbTime = str_pad( + $this->numberConverter->toHex($this->timestamp()), + self::TIMESTAMP_BYTES * 2, + '0', + STR_PAD_LEFT + ); + + return (string) hex2bin( + str_pad( + bin2hex($hash), + $length - self::TIMESTAMP_BYTES, + '0' + ) + . $lsbTime + ); + } + + /** + * Returns current timestamp a string integer, precise to 0.00001 seconds + */ + private function timestamp(): string + { + $time = explode(' ', microtime(false)); + + return $time[1] . substr($time[0], 2, 5); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php new file mode 100644 index 0000000..37ba781 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php @@ -0,0 +1,141 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Exception\DceSecurityException; +use Ramsey\Uuid\Provider\DceSecurityProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Uuid; + +use function hex2bin; +use function in_array; +use function pack; +use function str_pad; +use function strlen; +use function substr_replace; + +use const STR_PAD_LEFT; + +/** + * DceSecurityGenerator generates strings of binary data based on a local + * domain, local identifier, node ID, clock sequence, and the current time + */ +class DceSecurityGenerator implements DceSecurityGeneratorInterface +{ + private const DOMAINS = [ + Uuid::DCE_DOMAIN_PERSON, + Uuid::DCE_DOMAIN_GROUP, + Uuid::DCE_DOMAIN_ORG, + ]; + + /** + * Upper bounds for the clock sequence in DCE Security UUIDs. + */ + private const CLOCK_SEQ_HIGH = 63; + + /** + * Lower bounds for the clock sequence in DCE Security UUIDs. + */ + private const CLOCK_SEQ_LOW = 0; + + public function __construct( + private NumberConverterInterface $numberConverter, + private TimeGeneratorInterface $timeGenerator, + private DceSecurityProviderInterface $dceSecurityProvider + ) { + } + + public function generate( + int $localDomain, + ?IntegerObject $localIdentifier = null, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): string { + if (!in_array($localDomain, self::DOMAINS)) { + throw new DceSecurityException( + 'Local domain must be a valid DCE Security domain' + ); + } + + if ($localIdentifier && $localIdentifier->isNegative()) { + throw new DceSecurityException( + 'Local identifier out of bounds; it must be a value between 0 and 4294967295' + ); + } + + if ($clockSeq > self::CLOCK_SEQ_HIGH || $clockSeq < self::CLOCK_SEQ_LOW) { + throw new DceSecurityException( + 'Clock sequence out of bounds; it must be a value between 0 and 63' + ); + } + + switch ($localDomain) { + case Uuid::DCE_DOMAIN_ORG: + if ($localIdentifier === null) { + throw new DceSecurityException( + 'A local identifier must be provided for the org domain' + ); + } + + break; + case Uuid::DCE_DOMAIN_PERSON: + if ($localIdentifier === null) { + $localIdentifier = $this->dceSecurityProvider->getUid(); + } + + break; + case Uuid::DCE_DOMAIN_GROUP: + default: + if ($localIdentifier === null) { + $localIdentifier = $this->dceSecurityProvider->getGid(); + } + + break; + } + + $identifierHex = $this->numberConverter->toHex($localIdentifier->toString()); + + // The maximum value for the local identifier is 0xffffffff, or + // 4294967295. This is 8 hexadecimal digits, so if the length of + // hexadecimal digits is greater than 8, we know the value is greater + // than 0xffffffff. + if (strlen($identifierHex) > 8) { + throw new DceSecurityException( + 'Local identifier out of bounds; it must be a value between 0 and 4294967295' + ); + } + + $domainByte = pack('n', $localDomain)[1]; + $identifierBytes = (string) hex2bin(str_pad($identifierHex, 8, '0', STR_PAD_LEFT)); + + if ($node instanceof Hexadecimal) { + $node = $node->toString(); + } + + // Shift the clock sequence 8 bits to the left, so it matches 0x3f00. + if ($clockSeq !== null) { + $clockSeq = $clockSeq << 8; + } + + $bytes = $this->timeGenerator->generate($node, $clockSeq); + + // Replace bytes in the time-based UUID with DCE Security values. + $bytes = substr_replace($bytes, $identifierBytes, 0, 4); + + return substr_replace($bytes, $domainByte, 9, 1); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DceSecurityGeneratorInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DceSecurityGeneratorInterface.php new file mode 100644 index 0000000..faa29a5 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DceSecurityGeneratorInterface.php @@ -0,0 +1,53 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Rfc4122\UuidV2; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; + +/** + * A DCE Security generator generates strings of binary data based on a local + * domain, local identifier, node ID, clock sequence, and the current time + * + * @see UuidV2 + */ +interface DceSecurityGeneratorInterface +{ + /** + * Generate a binary string from a local domain, local identifier, node ID, + * clock sequence, and current time + * + * @param int $localDomain The local domain to use when generating bytes, + * according to DCE Security + * @param IntegerObject|null $localIdentifier The local identifier for the + * given domain; this may be a UID or GID on POSIX systems, if the local + * domain is person or group, or it may be a site-defined identifier + * if the local domain is org + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return string A binary string + */ + public function generate( + int $localDomain, + ?IntegerObject $localIdentifier = null, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DefaultNameGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DefaultNameGenerator.php new file mode 100644 index 0000000..7303e9f --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DefaultNameGenerator.php @@ -0,0 +1,48 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Exception\NameException; +use Ramsey\Uuid\UuidInterface; +use ValueError; + +use function hash; + +/** + * DefaultNameGenerator generates strings of binary data based on a namespace, + * name, and hashing algorithm + */ +class DefaultNameGenerator implements NameGeneratorInterface +{ + /** @psalm-pure */ + public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string + { + try { + /** @var string|bool $bytes */ + $bytes = @hash($hashAlgorithm, $ns->getBytes() . $name, true); + } catch (ValueError $e) { + $bytes = false; // keep same behavior than PHP 7 + } + + if ($bytes === false) { + throw new NameException(sprintf( + 'Unable to hash namespace and name with algorithm \'%s\'', + $hashAlgorithm + )); + } + + return (string) $bytes; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php new file mode 100644 index 0000000..ea1e2a6 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php @@ -0,0 +1,129 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Exception\RandomSourceException; +use Ramsey\Uuid\Exception\TimeSourceException; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Provider\TimeProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Throwable; + +use function dechex; +use function hex2bin; +use function is_int; +use function pack; +use function preg_match; +use function sprintf; +use function str_pad; +use function strlen; + +use const STR_PAD_LEFT; + +/** + * DefaultTimeGenerator generates strings of binary data based on a node ID, + * clock sequence, and the current time + */ +class DefaultTimeGenerator implements TimeGeneratorInterface +{ + public function __construct( + private NodeProviderInterface $nodeProvider, + private TimeConverterInterface $timeConverter, + private TimeProviderInterface $timeProvider + ) { + } + + /** + * @throws InvalidArgumentException if the parameters contain invalid values + * @throws RandomSourceException if random_int() throws an exception/error + * + * @inheritDoc + */ + public function generate($node = null, ?int $clockSeq = null): string + { + if ($node instanceof Hexadecimal) { + $node = $node->toString(); + } + + $node = $this->getValidNode($node); + + if ($clockSeq === null) { + try { + // This does not use "stable storage"; see RFC 4122, Section 4.2.1.1. + $clockSeq = random_int(0, 0x3fff); + } catch (Throwable $exception) { + throw new RandomSourceException( + $exception->getMessage(), + (int) $exception->getCode(), + $exception + ); + } + } + + $time = $this->timeProvider->getTime(); + + $uuidTime = $this->timeConverter->calculateTime( + $time->getSeconds()->toString(), + $time->getMicroseconds()->toString() + ); + + $timeHex = str_pad($uuidTime->toString(), 16, '0', STR_PAD_LEFT); + + if (strlen($timeHex) !== 16) { + throw new TimeSourceException(sprintf( + 'The generated time of \'%s\' is larger than expected', + $timeHex + )); + } + + $timeBytes = (string) hex2bin($timeHex); + + return $timeBytes[4] . $timeBytes[5] . $timeBytes[6] . $timeBytes[7] + . $timeBytes[2] . $timeBytes[3] + . $timeBytes[0] . $timeBytes[1] + . pack('n*', $clockSeq) + . $node; + } + + /** + * Uses the node provider given when constructing this instance to get + * the node ID (usually a MAC address) + * + * @param int|string|null $node A node value that may be used to override the node provider + * + * @return string 6-byte binary string representation of the node + * + * @throws InvalidArgumentException + */ + private function getValidNode(int | string | null $node): string + { + if ($node === null) { + $node = $this->nodeProvider->getNode(); + } + + // Convert the node to hex, if it is still an integer. + if (is_int($node)) { + $node = dechex($node); + } + + if (!preg_match('/^[A-Fa-f0-9]+$/', (string) $node) || strlen((string) $node) > 12) { + throw new InvalidArgumentException('Invalid node value'); + } + + return (string) hex2bin(str_pad((string) $node, 12, '0', STR_PAD_LEFT)); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/NameGeneratorFactory.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/NameGeneratorFactory.php new file mode 100644 index 0000000..6f08e29 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/NameGeneratorFactory.php @@ -0,0 +1,30 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +/** + * NameGeneratorFactory retrieves a default name generator, based on the + * environment + */ +class NameGeneratorFactory +{ + /** + * Returns a default name generator, based on the current environment + */ + public function getGenerator(): NameGeneratorInterface + { + return new DefaultNameGenerator(); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/NameGeneratorInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/NameGeneratorInterface.php new file mode 100644 index 0000000..cc43dd0 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/NameGeneratorInterface.php @@ -0,0 +1,38 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\UuidInterface; + +/** + * A name generator generates strings of binary data created by hashing together + * a namespace with a name, according to a hashing algorithm + */ +interface NameGeneratorInterface +{ + /** + * Generate a binary string from a namespace and name hashed together with + * the specified hashing algorithm + * + * @param UuidInterface $ns The namespace + * @param string $name The name to use for creating a UUID + * @param string $hashAlgorithm The hashing algorithm to use + * + * @return string A binary string + * + * @psalm-pure + */ + public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php new file mode 100644 index 0000000..6a6d1ae --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php @@ -0,0 +1,49 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Exception\NameException; +use Ramsey\Uuid\UuidInterface; + +use function sprintf; +use function uuid_generate_md5; +use function uuid_generate_sha1; +use function uuid_parse; + +/** + * PeclUuidNameGenerator generates strings of binary data from a namespace and a + * name, using ext-uuid + * + * @link https://pecl.php.net/package/uuid ext-uuid + */ +class PeclUuidNameGenerator implements NameGeneratorInterface +{ + /** @psalm-pure */ + public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string + { + $uuid = match ($hashAlgorithm) { + 'md5' => uuid_generate_md5($ns->toString(), $name), + 'sha1' => uuid_generate_sha1($ns->toString(), $name), + default => throw new NameException( + sprintf( + 'Unable to hash namespace and name with algorithm \'%s\'', + $hashAlgorithm + ) + ), + }; + + return uuid_parse($uuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidRandomGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidRandomGenerator.php new file mode 100644 index 0000000..07c47d2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidRandomGenerator.php @@ -0,0 +1,35 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use function uuid_create; +use function uuid_parse; + +use const UUID_TYPE_RANDOM; + +/** + * PeclUuidRandomGenerator generates strings of random binary data using ext-uuid + * + * @link https://pecl.php.net/package/uuid ext-uuid + */ +class PeclUuidRandomGenerator implements RandomGeneratorInterface +{ + public function generate(int $length): string + { + $uuid = uuid_create(UUID_TYPE_RANDOM); + + return uuid_parse($uuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidTimeGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidTimeGenerator.php new file mode 100644 index 0000000..e01f44e --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/PeclUuidTimeGenerator.php @@ -0,0 +1,39 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use function uuid_create; +use function uuid_parse; + +use const UUID_TYPE_TIME; + +/** + * PeclUuidTimeGenerator generates strings of binary data for time-base UUIDs, + * using ext-uuid + * + * @link https://pecl.php.net/package/uuid ext-uuid + */ +class PeclUuidTimeGenerator implements TimeGeneratorInterface +{ + /** + * @inheritDoc + */ + public function generate($node = null, ?int $clockSeq = null): string + { + $uuid = uuid_create(UUID_TYPE_TIME); + + return uuid_parse($uuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomBytesGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomBytesGenerator.php new file mode 100644 index 0000000..12edb96 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomBytesGenerator.php @@ -0,0 +1,45 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Exception\RandomSourceException; +use Throwable; + +/** + * RandomBytesGenerator generates strings of random binary data using the + * built-in `random_bytes()` PHP function + * + * @link http://php.net/random_bytes random_bytes() + */ +class RandomBytesGenerator implements RandomGeneratorInterface +{ + /** + * @throws RandomSourceException if random_bytes() throws an exception/error + * + * @inheritDoc + */ + public function generate(int $length): string + { + try { + return random_bytes($length); + } catch (Throwable $exception) { + throw new RandomSourceException( + $exception->getMessage(), + (int) $exception->getCode(), + $exception + ); + } + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomGeneratorFactory.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomGeneratorFactory.php new file mode 100644 index 0000000..b723ac2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomGeneratorFactory.php @@ -0,0 +1,30 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +/** + * RandomGeneratorFactory retrieves a default random generator, based on the + * environment + */ +class RandomGeneratorFactory +{ + /** + * Returns a default random generator, based on the current environment + */ + public function getGenerator(): RandomGeneratorInterface + { + return new RandomBytesGenerator(); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php new file mode 100644 index 0000000..1180b97 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php @@ -0,0 +1,30 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +/** + * A random generator generates strings of random binary data + */ +interface RandomGeneratorInterface +{ + /** + * Generates a string of randomized binary data + * + * @param int<1, max> $length The number of bytes of random binary data to generate + * + * @return string A binary string + */ + public function generate(int $length): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php new file mode 100644 index 0000000..fd0ccc8 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php @@ -0,0 +1,56 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use RandomLib\Factory; +use RandomLib\Generator; + +/** + * RandomLibAdapter generates strings of random binary data using the + * paragonie/random-lib library + * + * @deprecated This class will be removed in 5.0.0. Use the default + * RandomBytesGenerator or implement your own generator that implements + * RandomGeneratorInterface. + * + * @link https://packagist.org/packages/paragonie/random-lib paragonie/random-lib + */ +class RandomLibAdapter implements RandomGeneratorInterface +{ + private Generator $generator; + + /** + * Constructs a RandomLibAdapter + * + * By default, if no Generator is passed in, this creates a high-strength + * generator to use when generating random binary data. + * + * @param Generator|null $generator The generator to use when generating binary data + */ + public function __construct(?Generator $generator = null) + { + if ($generator === null) { + $factory = new Factory(); + $generator = $factory->getHighStrengthGenerator(); + } + + $this->generator = $generator; + } + + public function generate(int $length): string + { + return $this->generator->generate($length); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php new file mode 100644 index 0000000..8d06fc3 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php @@ -0,0 +1,45 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Provider\TimeProviderInterface; + +/** + * TimeGeneratorFactory retrieves a default time generator, based on the + * environment + */ +class TimeGeneratorFactory +{ + public function __construct( + private NodeProviderInterface $nodeProvider, + private TimeConverterInterface $timeConverter, + private TimeProviderInterface $timeProvider + ) { + } + + /** + * Returns a default time generator, based on the current environment + */ + public function getGenerator(): TimeGeneratorInterface + { + return new DefaultTimeGenerator( + $this->nodeProvider, + $this->timeConverter, + $this->timeProvider + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/TimeGeneratorInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/TimeGeneratorInterface.php new file mode 100644 index 0000000..18f21c4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/TimeGeneratorInterface.php @@ -0,0 +1,38 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Ramsey\Uuid\Type\Hexadecimal; + +/** + * A time generator generates strings of binary data based on a node ID, + * clock sequence, and the current time + */ +interface TimeGeneratorInterface +{ + /** + * Generate a binary string from a node ID, clock sequence, and current time + * + * @param Hexadecimal|int|string|null $node A 48-bit number representing the + * hardware address; this number may be represented as an integer or a + * hexadecimal string + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return string A binary string + */ + public function generate($node = null, ?int $clockSeq = null): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Generator/UnixTimeGenerator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/UnixTimeGenerator.php new file mode 100644 index 0000000..d7c8ed4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Generator/UnixTimeGenerator.php @@ -0,0 +1,169 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Generator; + +use Brick\Math\BigInteger; +use DateTimeImmutable; +use DateTimeInterface; +use Ramsey\Uuid\Type\Hexadecimal; + +use function hash; +use function pack; +use function str_pad; +use function strlen; +use function substr; +use function substr_replace; +use function unpack; + +use const PHP_INT_SIZE; +use const STR_PAD_LEFT; + +/** + * UnixTimeGenerator generates bytes that combine a 48-bit timestamp in + * milliseconds since the Unix Epoch with 80 random bits + * + * Code and concepts within this class are borrowed from the symfony/uid package + * and are used under the terms of the MIT license distributed with symfony/uid. + * + * symfony/uid is copyright (c) Fabien Potencier. + * + * @link https://symfony.com/components/Uid Symfony Uid component + * @link https://github.com/symfony/uid/blob/4f9f537e57261519808a7ce1d941490736522bbc/UuidV7.php Symfony UuidV7 class + * @link https://github.com/symfony/uid/blob/6.2/LICENSE MIT License + */ +class UnixTimeGenerator implements TimeGeneratorInterface +{ + private static string $time = ''; + private static ?string $seed = null; + private static int $seedIndex = 0; + + /** @var int[] */ + private static array $rand = []; + + /** @var int[] */ + private static array $seedParts; + + public function __construct( + private RandomGeneratorInterface $randomGenerator, + private int $intSize = PHP_INT_SIZE + ) { + } + + /** + * @param Hexadecimal|int|string|null $node Unused in this generator + * @param int|null $clockSeq Unused in this generator + * @param DateTimeInterface $dateTime A date-time instance to use when + * generating bytes + * + * @inheritDoc + */ + public function generate($node = null, ?int $clockSeq = null, ?DateTimeInterface $dateTime = null): string + { + $time = ($dateTime ?? new DateTimeImmutable('now'))->format('Uv'); + + if ($time > self::$time || ($dateTime !== null && $time !== self::$time)) { + $this->randomize($time); + } else { + $time = $this->increment(); + } + + if ($this->intSize >= 8) { + $time = substr(pack('J', (int) $time), -6); + } else { + $time = str_pad(BigInteger::of($time)->toBytes(false), 6, "\x00", STR_PAD_LEFT); + } + + /** @var non-empty-string */ + return $time . pack('n*', self::$rand[1], self::$rand[2], self::$rand[3], self::$rand[4], self::$rand[5]); + } + + private function randomize(string $time): void + { + if (self::$seed === null) { + $seed = $this->randomGenerator->generate(16); + self::$seed = $seed; + } else { + $seed = $this->randomGenerator->generate(10); + } + + /** @var int[] $rand */ + $rand = unpack('n*', $seed); + $rand[1] &= 0x03ff; + + self::$rand = $rand; + self::$time = $time; + } + + /** + * Special thanks to Nicolas Grekas for sharing the following information: + * + * Within the same ms, we increment the rand part by a random 24-bit number. + * + * Instead of getting this number from random_bytes(), which is slow, we get + * it by sha512-hashing self::$seed. This produces 64 bytes of entropy, + * which we need to split in a list of 24-bit numbers. unpack() first splits + * them into 16 x 32-bit numbers; we take the first byte of each of these + * numbers to get 5 extra 24-bit numbers. Then, we consume those numbers + * one-by-one and run this logic every 21 iterations. + * + * self::$rand holds the random part of the UUID, split into 5 x 16-bit + * numbers for x86 portability. We increment this random part by the next + * 24-bit number in the self::$seedParts list and decrement + * self::$seedIndex. + * + * @link https://twitter.com/nicolasgrekas/status/1583356938825261061 Tweet from Nicolas Grekas + */ + private function increment(): string + { + if (self::$seedIndex === 0 && self::$seed !== null) { + self::$seed = hash('sha512', self::$seed, true); + + /** @var int[] $s */ + $s = unpack('l*', self::$seed); + $s[] = ($s[1] >> 8 & 0xff0000) | ($s[2] >> 16 & 0xff00) | ($s[3] >> 24 & 0xff); + $s[] = ($s[4] >> 8 & 0xff0000) | ($s[5] >> 16 & 0xff00) | ($s[6] >> 24 & 0xff); + $s[] = ($s[7] >> 8 & 0xff0000) | ($s[8] >> 16 & 0xff00) | ($s[9] >> 24 & 0xff); + $s[] = ($s[10] >> 8 & 0xff0000) | ($s[11] >> 16 & 0xff00) | ($s[12] >> 24 & 0xff); + $s[] = ($s[13] >> 8 & 0xff0000) | ($s[14] >> 16 & 0xff00) | ($s[15] >> 24 & 0xff); + + self::$seedParts = $s; + self::$seedIndex = 21; + } + + self::$rand[5] = 0xffff & $carry = self::$rand[5] + 1 + (self::$seedParts[self::$seedIndex--] & 0xffffff); + self::$rand[4] = 0xffff & $carry = self::$rand[4] + ($carry >> 16); + self::$rand[3] = 0xffff & $carry = self::$rand[3] + ($carry >> 16); + self::$rand[2] = 0xffff & $carry = self::$rand[2] + ($carry >> 16); + self::$rand[1] += $carry >> 16; + + if (0xfc00 & self::$rand[1]) { + $time = self::$time; + $mtime = (int) substr($time, -9); + + if ($this->intSize >= 8 || strlen($time) < 10) { + $time = (string) ((int) $time + 1); + } elseif ($mtime === 999999999) { + $time = (1 + (int) substr($time, 0, -9)) . '000000000'; + } else { + $mtime++; + $time = substr_replace($time, str_pad((string) $mtime, 9, '0', STR_PAD_LEFT), -9); + } + + $this->randomize($time); + } + + return self::$time; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Guid/Fields.php b/php/libraries/composer/vendor/ramsey/uuid/src/Guid/Fields.php new file mode 100644 index 0000000..0fc5d1c --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Guid/Fields.php @@ -0,0 +1,195 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Guid; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Fields\SerializableFieldsTrait; +use Ramsey\Uuid\Rfc4122\FieldsInterface; +use Ramsey\Uuid\Rfc4122\MaxTrait; +use Ramsey\Uuid\Rfc4122\NilTrait; +use Ramsey\Uuid\Rfc4122\VariantTrait; +use Ramsey\Uuid\Rfc4122\VersionTrait; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Uuid; + +use function bin2hex; +use function dechex; +use function hexdec; +use function pack; +use function sprintf; +use function str_pad; +use function strlen; +use function substr; +use function unpack; + +use const STR_PAD_LEFT; + +/** + * GUIDs are comprised of a set of named fields, according to RFC 4122 + * + * @see Guid + * + * @psalm-immutable + */ +final class Fields implements FieldsInterface +{ + use MaxTrait; + use NilTrait; + use SerializableFieldsTrait; + use VariantTrait; + use VersionTrait; + + /** + * @param string $bytes A 16-byte binary string representation of a UUID + * + * @throws InvalidArgumentException if the byte string is not exactly 16 bytes + * @throws InvalidArgumentException if the byte string does not represent a GUID + * @throws InvalidArgumentException if the byte string does not contain a valid version + */ + public function __construct(private string $bytes) + { + if (strlen($this->bytes) !== 16) { + throw new InvalidArgumentException( + 'The byte string must be 16 bytes long; ' + . 'received ' . strlen($this->bytes) . ' bytes' + ); + } + + if (!$this->isCorrectVariant()) { + throw new InvalidArgumentException( + 'The byte string received does not conform to the RFC ' + . '4122 or Microsoft Corporation variants' + ); + } + + if (!$this->isCorrectVersion()) { + throw new InvalidArgumentException( + 'The byte string received does not contain a valid version' + ); + } + } + + public function getBytes(): string + { + return $this->bytes; + } + + public function getTimeLow(): Hexadecimal + { + // Swap the bytes from little endian to network byte order. + /** @var array $hex */ + $hex = unpack( + 'H*', + pack( + 'v*', + hexdec(bin2hex(substr($this->bytes, 2, 2))), + hexdec(bin2hex(substr($this->bytes, 0, 2))) + ) + ); + + return new Hexadecimal((string) ($hex[1] ?? '')); + } + + public function getTimeMid(): Hexadecimal + { + // Swap the bytes from little endian to network byte order. + /** @var array $hex */ + $hex = unpack( + 'H*', + pack( + 'v', + hexdec(bin2hex(substr($this->bytes, 4, 2))) + ) + ); + + return new Hexadecimal((string) ($hex[1] ?? '')); + } + + public function getTimeHiAndVersion(): Hexadecimal + { + // Swap the bytes from little endian to network byte order. + /** @var array $hex */ + $hex = unpack( + 'H*', + pack( + 'v', + hexdec(bin2hex(substr($this->bytes, 6, 2))) + ) + ); + + return new Hexadecimal((string) ($hex[1] ?? '')); + } + + public function getTimestamp(): Hexadecimal + { + return new Hexadecimal(sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + $this->getTimeLow()->toString() + )); + } + + public function getClockSeq(): Hexadecimal + { + if ($this->isMax()) { + $clockSeq = 0xffff; + } elseif ($this->isNil()) { + $clockSeq = 0x0000; + } else { + $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; + } + + return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); + } + + public function getClockSeqHiAndReserved(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1))); + } + + public function getClockSeqLow(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1))); + } + + public function getNode(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 10))); + } + + public function getVersion(): ?int + { + if ($this->isNil() || $this->isMax()) { + return null; + } + + /** @var array $parts */ + $parts = unpack('n*', $this->bytes); + + return ((int) $parts[4] >> 4) & 0x00f; + } + + private function isCorrectVariant(): bool + { + if ($this->isNil() || $this->isMax()) { + return true; + } + + $variant = $this->getVariant(); + + return $variant === Uuid::RFC_4122 || $variant === Uuid::RESERVED_MICROSOFT; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Guid/Guid.php b/php/libraries/composer/vendor/ramsey/uuid/src/Guid/Guid.php new file mode 100644 index 0000000..b3ed096 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Guid/Guid.php @@ -0,0 +1,61 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Guid; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Uuid; + +/** + * Guid represents a UUID with "native" (little-endian) byte order + * + * From Wikipedia: + * + * > The first three fields are unsigned 32- and 16-bit integers and are subject + * > to swapping, while the last two fields consist of uninterpreted bytes, not + * > subject to swapping. This byte swapping applies even for versions 3, 4, and + * > 5, where the canonical fields do not correspond to the content of the UUID. + * + * The first three fields of a GUID are encoded in little-endian byte order, + * while the last three fields are in network (big-endian) byte order. This is + * according to the history of the Microsoft definition of a GUID. + * + * According to the .NET Guid.ToByteArray method documentation: + * + * > Note that the order of bytes in the returned byte array is different from + * > the string representation of a Guid value. The order of the beginning + * > four-byte group and the next two two-byte groups is reversed, whereas the + * > order of the last two-byte group and the closing six-byte group is the + * > same. + * + * @link https://en.wikipedia.org/wiki/Universally_unique_identifier#Variants UUID Variants on Wikipedia + * @link https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid Windows GUID structure + * @link https://docs.microsoft.com/en-us/dotnet/api/system.guid .NET Guid Struct + * @link https://docs.microsoft.com/en-us/dotnet/api/system.guid.tobytearray .NET Guid.ToByteArray Method + * + * @psalm-immutable + */ +final class Guid extends Uuid +{ + public function __construct( + Fields $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Guid/GuidBuilder.php b/php/libraries/composer/vendor/ramsey/uuid/src/Guid/GuidBuilder.php new file mode 100644 index 0000000..c036bb2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Guid/GuidBuilder.php @@ -0,0 +1,77 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Guid; + +use Ramsey\Uuid\Builder\UuidBuilderInterface; +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\UnableToBuildUuidException; +use Ramsey\Uuid\UuidInterface; +use Throwable; + +/** + * GuidBuilder builds instances of Guid + * + * @see Guid + * + * @psalm-immutable + */ +class GuidBuilder implements UuidBuilderInterface +{ + /** + * @param NumberConverterInterface $numberConverter The number converter to + * use when constructing the Guid + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to Unix timestamps + */ + public function __construct( + private NumberConverterInterface $numberConverter, + private TimeConverterInterface $timeConverter + ) { + } + + /** + * Builds and returns a Guid + * + * @param CodecInterface $codec The codec to use for building this Guid instance + * @param string $bytes The byte string from which to construct a UUID + * + * @return Guid The GuidBuilder returns an instance of Ramsey\Uuid\Guid\Guid + * + * @psalm-pure + */ + public function build(CodecInterface $codec, string $bytes): UuidInterface + { + try { + return new Guid( + $this->buildFields($bytes), + $this->numberConverter, + $codec, + $this->timeConverter + ); + } catch (Throwable $e) { + throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); + } + } + + /** + * Proxy method to allow injecting a mock, for testing + */ + protected function buildFields(string $bytes): Fields + { + return new Fields($bytes); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php b/php/libraries/composer/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php new file mode 100644 index 0000000..c0b47bb --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php @@ -0,0 +1,572 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Lazy; + +use DateTimeInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Ramsey\Uuid\Fields\FieldsInterface; +use Ramsey\Uuid\Rfc4122\UuidV1; +use Ramsey\Uuid\Rfc4122\UuidV6; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\UuidFactory; +use Ramsey\Uuid\UuidInterface; +use ValueError; + +use function assert; +use function bin2hex; +use function hex2bin; +use function sprintf; +use function str_replace; +use function substr; + +/** + * Lazy version of a UUID: its format has not been determined yet, so it is mostly only usable for string/bytes + * conversion. This object optimizes instantiation, serialization and string conversion time, at the cost of + * increased overhead for more advanced UUID operations. + * + * @internal this type is used internally for performance reasons, and is not supposed to be directly referenced + * in consumer libraries. + * + * @psalm-immutable + * + * Note: the {@see FieldsInterface} does not declare methods that deprecated API + * relies upon: the API has been ported from the {@see \Ramsey\Uuid\Uuid} definition, + * and is deprecated anyway. + * Note: the deprecated API from {@see \Ramsey\Uuid\Uuid} is in use here (on purpose): it will be removed + * once the deprecated API is gone from this class too. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + */ +final class LazyUuidFromString implements UuidInterface +{ + public const VALID_REGEX = '/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ms'; + + private ?UuidInterface $unwrapped = null; + + /** + * @psalm-param non-empty-string $uuid + */ + public function __construct(private string $uuid) + { + } + + /** @psalm-pure */ + public static function fromBytes(string $bytes): self + { + $base16Uuid = bin2hex($bytes); + + return new self( + substr($base16Uuid, 0, 8) + . '-' + . substr($base16Uuid, 8, 4) + . '-' + . substr($base16Uuid, 12, 4) + . '-' + . substr($base16Uuid, 16, 4) + . '-' + . substr($base16Uuid, 20, 12) + ); + } + + public function serialize(): string + { + return $this->uuid; + } + + /** + * @return array{string: string} + * + * @psalm-return array{string: non-empty-string} + */ + public function __serialize(): array + { + return ['string' => $this->uuid]; + } + + /** + * {@inheritDoc} + * + * @param string $data + * + * @psalm-param non-empty-string $data + */ + public function unserialize(string $data): void + { + $this->uuid = $data; + } + + /** + * @param array{string?: string} $data + * + * @psalm-param array{string?: non-empty-string} $data + * @psalm-suppress UnusedMethodCall + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getNumberConverter(): NumberConverterInterface + { + return ($this->unwrapped ?? $this->unwrap()) + ->getNumberConverter(); + } + + /** + * {@inheritDoc} + * + * @psalm-suppress DeprecatedMethod + */ + public function getFieldsHex(): array + { + return ($this->unwrapped ?? $this->unwrap()) + ->getFieldsHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getClockSeqHiAndReservedHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getClockSeqHiAndReservedHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getClockSeqLowHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getClockSeqLowHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getClockSequenceHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getClockSequenceHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getDateTime(): DateTimeInterface + { + return ($this->unwrapped ?? $this->unwrap()) + ->getDateTime(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getLeastSignificantBitsHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getLeastSignificantBitsHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getMostSignificantBitsHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getMostSignificantBitsHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getNodeHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getNodeHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getTimeHiAndVersionHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getTimeHiAndVersionHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getTimeLowHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getTimeLowHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getTimeMidHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getTimeMidHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getTimestampHex(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getTimestampHex(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getUrn(): string + { + return ($this->unwrapped ?? $this->unwrap()) + ->getUrn(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getVariant(): ?int + { + return ($this->unwrapped ?? $this->unwrap()) + ->getVariant(); + } + + /** @psalm-suppress DeprecatedMethod */ + public function getVersion(): ?int + { + return ($this->unwrapped ?? $this->unwrap()) + ->getVersion(); + } + + public function compareTo(UuidInterface $other): int + { + return ($this->unwrapped ?? $this->unwrap()) + ->compareTo($other); + } + + public function equals(?object $other): bool + { + if (! $other instanceof UuidInterface) { + return false; + } + + return $this->uuid === $other->toString(); + } + + /** + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificReturnType + * @psalm-suppress LessSpecificReturnStatement we know that {@see self::$uuid} is a non-empty string, so + * we know that {@see hex2bin} will retrieve a non-empty string too. + */ + public function getBytes(): string + { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ + return (string) hex2bin(str_replace('-', '', $this->uuid)); + } + + public function getFields(): FieldsInterface + { + return ($this->unwrapped ?? $this->unwrap()) + ->getFields(); + } + + public function getHex(): Hexadecimal + { + return ($this->unwrapped ?? $this->unwrap()) + ->getHex(); + } + + public function getInteger(): IntegerObject + { + return ($this->unwrapped ?? $this->unwrap()) + ->getInteger(); + } + + public function toString(): string + { + return $this->uuid; + } + + public function __toString(): string + { + return $this->uuid; + } + + public function jsonSerialize(): string + { + return $this->uuid; + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeqHiAndReserved()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getClockSeqHiAndReserved(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getClockSeqHiAndReserved() + ->toString() + ); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeqLow()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getClockSeqLow(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getClockSeqLow() + ->toString() + ); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeq()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getClockSequence(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getClockSeq() + ->toString() + ); + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getLeastSignificantBits(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex(substr($instance->getHex()->toString(), 16)); + } + + /** + * @deprecated This method will be removed in 5.0.0. There is no direct + * alternative, but the same information may be obtained by splitting + * in half the value returned by {@see UuidInterface::getHex()}. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getMostSignificantBits(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex(substr($instance->getHex()->toString(), 0, 16)); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getNode()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getNode(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getNode() + ->toString() + ); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeHiAndVersion()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getTimeHiAndVersion(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getTimeHiAndVersion() + ->toString() + ); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeLow()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getTimeLow(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getTimeLow() + ->toString() + ); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeMid()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getTimeMid(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + return $instance->getNumberConverter() + ->fromHex( + $instance->getFields() + ->getTimeMid() + ->toString() + ); + } + + /** + * @deprecated Use {@see UuidInterface::getFields()} to get a + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimestamp()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress DeprecatedMethod + * @psalm-suppress MixedArgument + * @psalm-suppress MixedMethodCall + */ + public function getTimestamp(): string + { + $instance = ($this->unwrapped ?? $this->unwrap()); + $fields = $instance->getFields(); + + if ($fields->getVersion() !== 1) { + throw new UnsupportedOperationException('Not a time-based UUID'); + } + + return $instance->getNumberConverter() + ->fromHex($fields->getTimestamp()->toString()); + } + + public function toUuidV1(): UuidV1 + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + if ($instance instanceof UuidV1) { + return $instance; + } + + assert($instance instanceof UuidV6); + + return $instance->toUuidV1(); + } + + public function toUuidV6(): UuidV6 + { + $instance = ($this->unwrapped ?? $this->unwrap()); + + assert($instance instanceof UuidV6); + + return $instance; + } + + /** + * @psalm-suppress ImpureMethodCall the retrieval of the factory is a clear violation of purity here: this is a + * known pitfall of the design of this library, where a value object contains + * a mutable reference to a factory. We use a fixed factory here, so the violation + * will not have real-world effects, as this object is only instantiated with the + * default factory settings/features. + * @psalm-suppress InaccessibleProperty property {@see $unwrapped} is used as a cache: we don't expose it to the + * outside world, so we should be fine here. + */ + private function unwrap(): UuidInterface + { + return $this->unwrapped = (new UuidFactory()) + ->fromString($this->uuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Math/BrickMathCalculator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Math/BrickMathCalculator.php new file mode 100644 index 0000000..f2d8678 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Math/BrickMathCalculator.php @@ -0,0 +1,144 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Math; + +use Brick\Math\BigDecimal; +use Brick\Math\BigInteger; +use Brick\Math\Exception\MathException; +use Brick\Math\RoundingMode as BrickMathRounding; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Type\Decimal; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\NumberInterface; + +/** + * A calculator using the brick/math library for arbitrary-precision arithmetic + * + * @psalm-immutable + */ +final class BrickMathCalculator implements CalculatorInterface +{ + private const ROUNDING_MODE_MAP = [ + RoundingMode::UNNECESSARY => BrickMathRounding::UNNECESSARY, + RoundingMode::UP => BrickMathRounding::UP, + RoundingMode::DOWN => BrickMathRounding::DOWN, + RoundingMode::CEILING => BrickMathRounding::CEILING, + RoundingMode::FLOOR => BrickMathRounding::FLOOR, + RoundingMode::HALF_UP => BrickMathRounding::HALF_UP, + RoundingMode::HALF_DOWN => BrickMathRounding::HALF_DOWN, + RoundingMode::HALF_CEILING => BrickMathRounding::HALF_CEILING, + RoundingMode::HALF_FLOOR => BrickMathRounding::HALF_FLOOR, + RoundingMode::HALF_EVEN => BrickMathRounding::HALF_EVEN, + ]; + + public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface + { + $sum = BigInteger::of($augend->toString()); + + foreach ($addends as $addend) { + $sum = $sum->plus($addend->toString()); + } + + return new IntegerObject((string) $sum); + } + + public function subtract(NumberInterface $minuend, NumberInterface ...$subtrahends): NumberInterface + { + $difference = BigInteger::of($minuend->toString()); + + foreach ($subtrahends as $subtrahend) { + $difference = $difference->minus($subtrahend->toString()); + } + + return new IntegerObject((string) $difference); + } + + public function multiply(NumberInterface $multiplicand, NumberInterface ...$multipliers): NumberInterface + { + $product = BigInteger::of($multiplicand->toString()); + + foreach ($multipliers as $multiplier) { + $product = $product->multipliedBy($multiplier->toString()); + } + + return new IntegerObject((string) $product); + } + + public function divide( + int $roundingMode, + int $scale, + NumberInterface $dividend, + NumberInterface ...$divisors + ): NumberInterface { + $brickRounding = $this->getBrickRoundingMode($roundingMode); + + $quotient = BigDecimal::of($dividend->toString()); + + foreach ($divisors as $divisor) { + $quotient = $quotient->dividedBy($divisor->toString(), $scale, $brickRounding); + } + + if ($scale === 0) { + return new IntegerObject((string) $quotient->toBigInteger()); + } + + return new Decimal((string) $quotient); + } + + public function fromBase(string $value, int $base): IntegerObject + { + try { + return new IntegerObject((string) BigInteger::fromBase($value, $base)); + } catch (MathException | \InvalidArgumentException $exception) { + throw new InvalidArgumentException( + $exception->getMessage(), + (int) $exception->getCode(), + $exception + ); + } + } + + public function toBase(IntegerObject $value, int $base): string + { + try { + return BigInteger::of($value->toString())->toBase($base); + } catch (MathException | \InvalidArgumentException $exception) { + throw new InvalidArgumentException( + $exception->getMessage(), + (int) $exception->getCode(), + $exception + ); + } + } + + public function toHexadecimal(IntegerObject $value): Hexadecimal + { + return new Hexadecimal($this->toBase($value, 16)); + } + + public function toInteger(Hexadecimal $value): IntegerObject + { + return $this->fromBase($value->toString(), 16); + } + + /** + * Maps ramsey/uuid rounding modes to those used by brick/math + */ + private function getBrickRoundingMode(int $roundingMode): int + { + return self::ROUNDING_MODE_MAP[$roundingMode] ?? 0; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Math/CalculatorInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Math/CalculatorInterface.php new file mode 100644 index 0000000..f03645d --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Math/CalculatorInterface.php @@ -0,0 +1,106 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Math; + +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\NumberInterface; + +/** + * A calculator performs arithmetic operations on numbers + * + * @psalm-immutable + */ +interface CalculatorInterface +{ + /** + * Returns the sum of all the provided parameters + * + * @param NumberInterface $augend The first addend (the integer being added to) + * @param NumberInterface ...$addends The additional integers to a add to the augend + * + * @return NumberInterface The sum of all the parameters + */ + public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface; + + /** + * Returns the difference of all the provided parameters + * + * @param NumberInterface $minuend The integer being subtracted from + * @param NumberInterface ...$subtrahends The integers to subtract from the minuend + * + * @return NumberInterface The difference after subtracting all parameters + */ + public function subtract(NumberInterface $minuend, NumberInterface ...$subtrahends): NumberInterface; + + /** + * Returns the product of all the provided parameters + * + * @param NumberInterface $multiplicand The integer to be multiplied + * @param NumberInterface ...$multipliers The factors by which to multiply the multiplicand + * + * @return NumberInterface The product of multiplying all the provided parameters + */ + public function multiply(NumberInterface $multiplicand, NumberInterface ...$multipliers): NumberInterface; + + /** + * Returns the quotient of the provided parameters divided left-to-right + * + * @param int $roundingMode The RoundingMode constant to use for this operation + * @param int $scale The scale to use for this operation + * @param NumberInterface $dividend The integer to be divided + * @param NumberInterface ...$divisors The integers to divide $dividend by, in + * the order in which the division operations should take place + * (left-to-right) + * + * @return NumberInterface The quotient of dividing the provided parameters left-to-right + */ + public function divide( + int $roundingMode, + int $scale, + NumberInterface $dividend, + NumberInterface ...$divisors + ): NumberInterface; + + /** + * Converts a value from an arbitrary base to a base-10 integer value + * + * @param string $value The value to convert + * @param int $base The base to convert from (i.e., 2, 16, 32, etc.) + * + * @return IntegerObject The base-10 integer value of the converted value + */ + public function fromBase(string $value, int $base): IntegerObject; + + /** + * Converts a base-10 integer value to an arbitrary base + * + * @param IntegerObject $value The integer value to convert + * @param int $base The base to convert to (i.e., 2, 16, 32, etc.) + * + * @return string The value represented in the specified base + */ + public function toBase(IntegerObject $value, int $base): string; + + /** + * Converts an Integer instance to a Hexadecimal instance + */ + public function toHexadecimal(IntegerObject $value): Hexadecimal; + + /** + * Converts a Hexadecimal instance to an Integer instance + */ + public function toInteger(Hexadecimal $value): IntegerObject; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Math/RoundingMode.php b/php/libraries/composer/vendor/ramsey/uuid/src/Math/RoundingMode.php new file mode 100644 index 0000000..e710270 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Math/RoundingMode.php @@ -0,0 +1,146 @@ +<?php + +/** + * This file was originally part of brick/math + * + * Copyright (c) 2013-present Benjamin Morel + * + * 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. + * + * @link https://github.com/brick/math brick/math at GitHub + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Math; + +/** + * Specifies a rounding behavior for numerical operations capable of discarding + * precision. + * + * Each rounding mode indicates how the least significant returned digit of a + * rounded result is to be calculated. If fewer digits are returned than the + * digits needed to represent the exact numerical result, the discarded digits + * will be referred to as the discarded fraction regardless the digits' + * contribution to the value of the number. In other words, considered as a + * numerical value, the discarded fraction could have an absolute value greater + * than one. + */ +final class RoundingMode +{ + /** + * Private constructor. This class is not instantiable. + * + * @codeCoverageIgnore + */ + private function __construct() + { + } + + /** + * Asserts that the requested operation has an exact result, hence no + * rounding is necessary. + */ + public const UNNECESSARY = 0; + + /** + * Rounds away from zero. + * + * Always increments the digit prior to a nonzero discarded fraction. + * Note that this rounding mode never decreases the magnitude of the + * calculated value. + */ + public const UP = 1; + + /** + * Rounds towards zero. + * + * Never increments the digit prior to a discarded fraction (i.e., + * truncates). Note that this rounding mode never increases the magnitude of + * the calculated value. + */ + public const DOWN = 2; + + /** + * Rounds towards positive infinity. + * + * If the result is positive, behaves as for UP; if negative, behaves as for + * DOWN. Note that this rounding mode never decreases the calculated value. + */ + public const CEILING = 3; + + /** + * Rounds towards negative infinity. + * + * If the result is positive, behave as for DOWN; if negative, behave as for + * UP. Note that this rounding mode never increases the calculated value. + */ + public const FLOOR = 4; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, + * in which case round up. + * + * Behaves as for UP if the discarded fraction is >= 0.5; otherwise, behaves + * as for DOWN. Note that this is the rounding mode commonly taught at + * school. + */ + public const HALF_UP = 5; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, + * in which case round down. + * + * Behaves as for UP if the discarded fraction is > 0.5; otherwise, behaves + * as for DOWN. + */ + public const HALF_DOWN = 6; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, + * in which case round towards positive infinity. + * + * If the result is positive, behaves as for HALF_UP; if negative, behaves + * as for HALF_DOWN. + */ + public const HALF_CEILING = 7; + + /** + * Rounds towards "nearest neighbor" unless both neighbors are equidistant, + * in which case round towards negative infinity. + * + * If the result is positive, behaves as for HALF_DOWN; if negative, behaves + * as for HALF_UP. + */ + public const HALF_FLOOR = 8; + + /** + * Rounds towards the "nearest neighbor" unless both neighbors are + * equidistant, in which case rounds towards the even neighbor. + * + * Behaves as for HALF_UP if the digit to the left of the discarded fraction + * is odd; behaves as for HALF_DOWN if it's even. + * + * Note that this is the rounding mode that statistically minimizes + * cumulative error when applied repeatedly over a sequence of calculations. + * It is sometimes known as "Banker's rounding", and is chiefly used in the + * USA. + */ + public const HALF_EVEN = 9; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/Fields.php b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/Fields.php new file mode 100644 index 0000000..5dfe610 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/Fields.php @@ -0,0 +1,131 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Nonstandard; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Fields\SerializableFieldsTrait; +use Ramsey\Uuid\Rfc4122\FieldsInterface; +use Ramsey\Uuid\Rfc4122\VariantTrait; +use Ramsey\Uuid\Type\Hexadecimal; + +use function bin2hex; +use function dechex; +use function hexdec; +use function sprintf; +use function str_pad; +use function strlen; +use function substr; + +use const STR_PAD_LEFT; + +/** + * Nonstandard UUID fields do not conform to the RFC 4122 standard + * + * Since some systems may create nonstandard UUIDs, this implements the + * Rfc4122\FieldsInterface, so that functionality of a nonstandard UUID is not + * degraded, in the event these UUIDs are expected to contain RFC 4122 fields. + * + * Internally, this class represents the fields together as a 16-byte binary + * string. + * + * @psalm-immutable + */ +final class Fields implements FieldsInterface +{ + use SerializableFieldsTrait; + use VariantTrait; + + /** + * @param string $bytes A 16-byte binary string representation of a UUID + * + * @throws InvalidArgumentException if the byte string is not exactly 16 bytes + */ + public function __construct(private string $bytes) + { + if (strlen($this->bytes) !== 16) { + throw new InvalidArgumentException( + 'The byte string must be 16 bytes long; ' + . 'received ' . strlen($this->bytes) . ' bytes' + ); + } + } + + public function getBytes(): string + { + return $this->bytes; + } + + public function getClockSeq(): Hexadecimal + { + $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; + + return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); + } + + public function getClockSeqHiAndReserved(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1))); + } + + public function getClockSeqLow(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1))); + } + + public function getNode(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 10))); + } + + public function getTimeHiAndVersion(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 6, 2))); + } + + public function getTimeLow(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 0, 4))); + } + + public function getTimeMid(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 4, 2))); + } + + public function getTimestamp(): Hexadecimal + { + return new Hexadecimal(sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + $this->getTimeLow()->toString() + )); + } + + public function getVersion(): ?int + { + return null; + } + + public function isNil(): bool + { + return false; + } + + public function isMax(): bool + { + return false; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/Uuid.php b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/Uuid.php new file mode 100644 index 0000000..715f825 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/Uuid.php @@ -0,0 +1,37 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Nonstandard; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Uuid as BaseUuid; + +/** + * Nonstandard\Uuid is a UUID that doesn't conform to RFC 4122 + * + * @psalm-immutable + */ +final class Uuid extends BaseUuid +{ + public function __construct( + Fields $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php new file mode 100644 index 0000000..82efd40 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php @@ -0,0 +1,76 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Nonstandard; + +use Ramsey\Uuid\Builder\UuidBuilderInterface; +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\UnableToBuildUuidException; +use Ramsey\Uuid\UuidInterface; +use Throwable; + +/** + * Nonstandard\UuidBuilder builds instances of Nonstandard\Uuid + * + * @psalm-immutable + */ +class UuidBuilder implements UuidBuilderInterface +{ + /** + * @param NumberConverterInterface $numberConverter The number converter to + * use when constructing the Nonstandard\Uuid + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to Unix timestamps + */ + public function __construct( + private NumberConverterInterface $numberConverter, + private TimeConverterInterface $timeConverter + ) { + } + + /** + * Builds and returns a Nonstandard\Uuid + * + * @param CodecInterface $codec The codec to use for building this instance + * @param string $bytes The byte string from which to construct a UUID + * + * @return Uuid The Nonstandard\UuidBuilder returns an instance of + * Nonstandard\Uuid + * + * @psalm-pure + */ + public function build(CodecInterface $codec, string $bytes): UuidInterface + { + try { + return new Uuid( + $this->buildFields($bytes), + $this->numberConverter, + $codec, + $this->timeConverter + ); + } catch (Throwable $e) { + throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); + } + } + + /** + * Proxy method to allow injecting a mock, for testing + */ + protected function buildFields(string $bytes): Fields + { + return new Fields($bytes); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php new file mode 100644 index 0000000..7497dd1 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php @@ -0,0 +1,105 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Nonstandard; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Lazy\LazyUuidFromString; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Rfc4122\TimeTrait; +use Ramsey\Uuid\Rfc4122\UuidInterface; +use Ramsey\Uuid\Rfc4122\UuidV1; +use Ramsey\Uuid\Uuid as BaseUuid; + +/** + * Reordered time, or version 6, UUIDs include timestamp, clock sequence, and + * node values that are combined into a 128-bit unsigned integer + * + * @deprecated Use {@see \Ramsey\Uuid\Rfc4122\UuidV6} instead. + * + * @link https://github.com/uuid6/uuid6-ietf-draft UUID version 6 IETF draft + * @link http://gh.peabody.io/uuidv6/ "Version 6" UUIDs + * + * @psalm-immutable + */ +class UuidV6 extends BaseUuid implements UuidInterface +{ + use TimeTrait; + + /** + * Creates a version 6 (reordered time) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_REORDERED_TIME) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV6 must represent a ' + . 'version 6 (reordered time) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } + + /** + * Converts this UUID into an instance of a version 1 UUID + */ + public function toUuidV1(): UuidV1 + { + $hex = $this->getHex()->toString(); + $hex = substr($hex, 7, 5) + . substr($hex, 13, 3) + . substr($hex, 3, 4) + . '1' . substr($hex, 0, 3) + . substr($hex, 16); + + /** @var LazyUuidFromString $uuid */ + $uuid = Uuid::fromBytes((string) hex2bin($hex)); + + return $uuid->toUuidV1(); + } + + /** + * Converts a version 1 UUID into an instance of a version 6 UUID + */ + public static function fromUuidV1(UuidV1 $uuidV1): \Ramsey\Uuid\Rfc4122\UuidV6 + { + $hex = $uuidV1->getHex()->toString(); + $hex = substr($hex, 13, 3) + . substr($hex, 8, 4) + . substr($hex, 0, 5) + . '6' . substr($hex, 5, 3) + . substr($hex, 16); + + /** @var LazyUuidFromString $uuid */ + $uuid = Uuid::fromBytes((string) hex2bin($hex)); + + return $uuid->toUuidV6(); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php new file mode 100644 index 0000000..d5b6cf0 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php @@ -0,0 +1,231 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Dce; + +use Ramsey\Uuid\Exception\DceSecurityException; +use Ramsey\Uuid\Provider\DceSecurityProviderInterface; +use Ramsey\Uuid\Type\Integer as IntegerObject; + +use function escapeshellarg; +use function preg_split; +use function str_getcsv; +use function strrpos; +use function strtolower; +use function strtoupper; +use function substr; +use function trim; + +use const PREG_SPLIT_NO_EMPTY; + +/** + * SystemDceSecurityProvider retrieves the user or group identifiers from the system + */ +class SystemDceSecurityProvider implements DceSecurityProviderInterface +{ + /** + * @throws DceSecurityException if unable to get a user identifier + * + * @inheritDoc + */ + public function getUid(): IntegerObject + { + /** @var int|float|string|IntegerObject|null $uid */ + static $uid = null; + + if ($uid instanceof IntegerObject) { + return $uid; + } + + if ($uid === null) { + $uid = $this->getSystemUid(); + } + + if ($uid === '') { + throw new DceSecurityException( + 'Unable to get a user identifier using the system DCE ' + . 'Security provider; please provide a custom identifier or ' + . 'use a different provider' + ); + } + + $uid = new IntegerObject($uid); + + return $uid; + } + + /** + * @throws DceSecurityException if unable to get a group identifier + * + * @inheritDoc + */ + public function getGid(): IntegerObject + { + /** @var int|float|string|IntegerObject|null $gid */ + static $gid = null; + + if ($gid instanceof IntegerObject) { + return $gid; + } + + if ($gid === null) { + $gid = $this->getSystemGid(); + } + + if ($gid === '') { + throw new DceSecurityException( + 'Unable to get a group identifier using the system DCE ' + . 'Security provider; please provide a custom identifier or ' + . 'use a different provider' + ); + } + + $gid = new IntegerObject($gid); + + return $gid; + } + + /** + * Returns the UID from the system + */ + private function getSystemUid(): string + { + if (!$this->hasShellExec()) { + return ''; + } + + return match ($this->getOs()) { + 'WIN' => $this->getWindowsUid(), + default => trim((string) shell_exec('id -u')), + }; + } + + /** + * Returns the GID from the system + */ + private function getSystemGid(): string + { + if (!$this->hasShellExec()) { + return ''; + } + + return match ($this->getOs()) { + 'WIN' => $this->getWindowsGid(), + default => trim((string) shell_exec('id -g')), + }; + } + + /** + * Returns true if shell_exec() is available for use + */ + private function hasShellExec(): bool + { + $disabledFunctions = strtolower((string) ini_get('disable_functions')); + + return !str_contains($disabledFunctions, 'shell_exec'); + } + + /** + * Returns the PHP_OS string + */ + private function getOs(): string + { + /** + * @psalm-suppress UnnecessaryVarAnnotation + * @var string $phpOs + */ + $phpOs = constant('PHP_OS'); + + return strtoupper(substr($phpOs, 0, 3)); + } + + /** + * Returns the user identifier for a user on a Windows system + * + * Windows does not have the same concept as an effective POSIX UID for the + * running script. Instead, each user is uniquely identified by an SID + * (security identifier). The SID includes three 32-bit unsigned integers + * that make up a unique domain identifier, followed by an RID (relative + * identifier) that we will use as the UID. The primary caveat is that this + * UID may not be unique to the system, since it is, instead, unique to the + * domain. + * + * @link https://www.lifewire.com/what-is-an-sid-number-2626005 What Is an SID Number? + * @link https://bit.ly/30vE7NM Well-known SID Structures + * @link https://bit.ly/2FWcYKJ Well-known security identifiers in Windows operating systems + * @link https://www.windows-commandline.com/get-sid-of-user/ Get SID of user + */ + private function getWindowsUid(): string + { + $response = shell_exec('whoami /user /fo csv /nh'); + + if ($response === null) { + return ''; + } + + $sid = str_getcsv(trim((string) $response))[1] ?? ''; + + if (($lastHyphen = strrpos($sid, '-')) === false) { + return ''; + } + + return trim(substr($sid, $lastHyphen + 1)); + } + + /** + * Returns a group identifier for a user on a Windows system + * + * Since Windows does not have the same concept as an effective POSIX GID + * for the running script, we will get the local group memberships for the + * user running the script. Then, we will get the SID (security identifier) + * for the first group that appears in that list. Finally, we will return + * the RID (relative identifier) for the group and use that as the GID. + * + * @link https://www.windows-commandline.com/list-of-user-groups-command-line/ List of user groups command line + */ + private function getWindowsGid(): string + { + $response = shell_exec('net user %username% | findstr /b /i "Local Group Memberships"'); + + if ($response === null) { + return ''; + } + + /** @var string[] $userGroups */ + $userGroups = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY); + + $firstGroup = trim($userGroups[1] ?? '', "* \t\n\r\0\x0B"); + + if ($firstGroup === '') { + return ''; + } + + $response = shell_exec('wmic group get name,sid | findstr /b /i ' . escapeshellarg($firstGroup)); + + if ($response === null) { + return ''; + } + + /** @var string[] $userGroup */ + $userGroup = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY); + + $sid = $userGroup[1] ?? ''; + + if (($lastHyphen = strrpos($sid, '-')) === false) { + return ''; + } + + return trim(substr($sid, $lastHyphen + 1)); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/DceSecurityProviderInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/DceSecurityProviderInterface.php new file mode 100644 index 0000000..8325da6 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/DceSecurityProviderInterface.php @@ -0,0 +1,41 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider; + +use Ramsey\Uuid\Rfc4122\UuidV2; +use Ramsey\Uuid\Type\Integer as IntegerObject; + +/** + * A DCE provider provides access to local domain identifiers for version 2, + * DCE Security, UUIDs + * + * @see UuidV2 + */ +interface DceSecurityProviderInterface +{ + /** + * Returns a user identifier for the system + * + * @link https://en.wikipedia.org/wiki/User_identifier User identifier + */ + public function getUid(): IntegerObject; + + /** + * Returns a group identifier for the system + * + * @link https://en.wikipedia.org/wiki/Group_identifier Group identifier + */ + public function getGid(): IntegerObject; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php new file mode 100644 index 0000000..d2eb20b --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php @@ -0,0 +1,54 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Node; + +use Ramsey\Uuid\Exception\NodeException; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; + +/** + * FallbackNodeProvider retrieves the system node ID by stepping through a list + * of providers until a node ID can be obtained + */ +class FallbackNodeProvider implements NodeProviderInterface +{ + /** + * @param iterable<NodeProviderInterface> $providers Array of node providers + */ + public function __construct(private iterable $providers) + { + } + + public function getNode(): Hexadecimal + { + $lastProviderException = null; + + foreach ($this->providers as $provider) { + try { + return $provider->getNode(); + } catch (NodeException $exception) { + $lastProviderException = $exception; + + continue; + } + } + + throw new NodeException( + 'Unable to find a suitable node provider', + 0, + $lastProviderException + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php new file mode 100644 index 0000000..1b979fa --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php @@ -0,0 +1,66 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Node; + +use Ramsey\Collection\AbstractCollection; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; + +/** + * A collection of NodeProviderInterface objects + * + * @deprecated this class has been deprecated, and will be removed in 5.0.0. The use-case for this class comes from + * a pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced + * at runtime: that is no longer necessary, now that you can safely verify your code to be correct, and use + * more generic types like `iterable<T>` instead. + * + * @extends AbstractCollection<NodeProviderInterface> + */ +class NodeProviderCollection extends AbstractCollection +{ + public function getType(): string + { + return NodeProviderInterface::class; + } + + /** + * Re-constructs the object from its serialized form + * + * @param string $serialized The serialized PHP string to unserialize into + * a UuidInterface instance + * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress RedundantConditionGivenDocblockType + */ + public function unserialize($serialized): void + { + /** @var array<array-key, NodeProviderInterface> $data */ + $data = unserialize($serialized, [ + 'allowed_classes' => [ + Hexadecimal::class, + RandomNodeProvider::class, + StaticNodeProvider::class, + SystemNodeProvider::class, + ], + ]); + + $this->data = array_filter( + $data, + function ($unserialized): bool { + return $unserialized instanceof NodeProviderInterface; + } + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/RandomNodeProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/RandomNodeProvider.php new file mode 100644 index 0000000..7614136 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/RandomNodeProvider.php @@ -0,0 +1,69 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Node; + +use Ramsey\Uuid\Exception\RandomSourceException; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Throwable; + +use function bin2hex; +use function dechex; +use function hex2bin; +use function hexdec; +use function str_pad; +use function substr; + +use const STR_PAD_LEFT; + +/** + * RandomNodeProvider generates a random node ID + * + * @link http://tools.ietf.org/html/rfc4122#section-4.5 RFC 4122, § 4.5: Node IDs that Do Not Identify the Host + */ +class RandomNodeProvider implements NodeProviderInterface +{ + public function getNode(): Hexadecimal + { + try { + $nodeBytes = random_bytes(6); + } catch (Throwable $exception) { + throw new RandomSourceException( + $exception->getMessage(), + (int) $exception->getCode(), + $exception + ); + } + + // Split the node bytes for math on 32-bit systems. + $nodeMsb = substr($nodeBytes, 0, 3); + $nodeLsb = substr($nodeBytes, 3); + + // Set the multicast bit; see RFC 4122, section 4.5. + $nodeMsb = hex2bin( + str_pad( + dechex(hexdec(bin2hex($nodeMsb)) | 0x010000), + 6, + '0', + STR_PAD_LEFT + ) + ); + + // Recombine the node bytes. + $node = $nodeMsb . $nodeLsb; + + return new Hexadecimal(str_pad(bin2hex($node), 12, '0', STR_PAD_LEFT)); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php new file mode 100644 index 0000000..0f7536a --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php @@ -0,0 +1,73 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Node; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; + +use function dechex; +use function hexdec; +use function str_pad; +use function substr; + +use const STR_PAD_LEFT; + +/** + * StaticNodeProvider provides a static node value with the multicast bit set + * + * @link http://tools.ietf.org/html/rfc4122#section-4.5 RFC 4122, § 4.5: Node IDs that Do Not Identify the Host + */ +class StaticNodeProvider implements NodeProviderInterface +{ + private Hexadecimal $node; + + /** + * @param Hexadecimal $node The static node value to use + */ + public function __construct(Hexadecimal $node) + { + if (strlen($node->toString()) > 12) { + throw new InvalidArgumentException( + 'Static node value cannot be greater than 12 hexadecimal characters' + ); + } + + $this->node = $this->setMulticastBit($node); + } + + public function getNode(): Hexadecimal + { + return $this->node; + } + + /** + * Set the multicast bit for the static node value + */ + private function setMulticastBit(Hexadecimal $node): Hexadecimal + { + $nodeHex = str_pad($node->toString(), 12, '0', STR_PAD_LEFT); + $firstOctet = substr($nodeHex, 0, 2); + + $firstOctet = str_pad( + dechex(hexdec($firstOctet) | 0x01), + 2, + '0', + STR_PAD_LEFT + ); + + return new Hexadecimal($firstOctet . substr($nodeHex, 2)); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php new file mode 100644 index 0000000..a03c93b --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php @@ -0,0 +1,193 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Node; + +use Ramsey\Uuid\Exception\NodeException; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Type\Hexadecimal; + +use function array_filter; +use function array_map; +use function array_walk; +use function count; +use function ob_get_clean; +use function ob_start; +use function preg_match; +use function preg_match_all; +use function reset; +use function str_contains; +use function str_replace; +use function strtolower; +use function strtoupper; +use function substr; + +use const GLOB_NOSORT; +use const PREG_PATTERN_ORDER; + +/** + * SystemNodeProvider retrieves the system node ID, if possible + * + * The system node ID, or host ID, is often the same as the MAC address for a + * network interface on the host. + */ +class SystemNodeProvider implements NodeProviderInterface +{ + /** + * Pattern to match nodes in ifconfig and ipconfig output. + */ + private const IFCONFIG_PATTERN = '/[^:]([0-9a-f]{2}([:-])[0-9a-f]{2}(\2[0-9a-f]{2}){4})[^:]/i'; + + /** + * Pattern to match nodes in sysfs stream output. + */ + private const SYSFS_PATTERN = '/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i'; + + public function getNode(): Hexadecimal + { + $node = $this->getNodeFromSystem(); + + if ($node === '') { + throw new NodeException( + 'Unable to fetch a node for this system' + ); + } + + return new Hexadecimal($node); + } + + /** + * Returns the system node, if it can find it + */ + protected function getNodeFromSystem(): string + { + static $node = null; + + if ($node !== null) { + return (string) $node; + } + + // First, try a Linux-specific approach. + $node = $this->getSysfs(); + + if ($node === '') { + // Search ifconfig output for MAC addresses & return the first one. + $node = $this->getIfconfig(); + } + + $node = str_replace([':', '-'], '', $node); + + return $node; + } + + /** + * Returns the network interface configuration for the system + * + * @codeCoverageIgnore + */ + protected function getIfconfig(): string + { + $disabledFunctions = strtolower((string) ini_get('disable_functions')); + + if (str_contains($disabledFunctions, 'passthru')) { + return ''; + } + + /** + * @psalm-suppress UnnecessaryVarAnnotation + * @var string $phpOs + */ + $phpOs = constant('PHP_OS'); + + ob_start(); + switch (strtoupper(substr($phpOs, 0, 3))) { + case 'WIN': + passthru('ipconfig /all 2>&1'); + + break; + case 'DAR': + passthru('ifconfig 2>&1'); + + break; + case 'FRE': + passthru('netstat -i -f link 2>&1'); + + break; + case 'LIN': + default: + passthru('netstat -ie 2>&1'); + + break; + } + + $ifconfig = (string) ob_get_clean(); + + if (preg_match_all(self::IFCONFIG_PATTERN, $ifconfig, $matches, PREG_PATTERN_ORDER)) { + foreach ($matches[1] as $iface) { + if ($iface !== '00:00:00:00:00:00' && $iface !== '00-00-00-00-00-00') { + return $iface; + } + } + } + + return ''; + } + + /** + * Returns MAC address from the first system interface via the sysfs interface + */ + protected function getSysfs(): string + { + $mac = ''; + + /** + * @psalm-suppress UnnecessaryVarAnnotation + * @var string $phpOs + */ + $phpOs = constant('PHP_OS'); + + if (strtoupper($phpOs) === 'LINUX') { + $addressPaths = glob('/sys/class/net/*/address', GLOB_NOSORT); + + if ($addressPaths === false || count($addressPaths) === 0) { + return ''; + } + + /** @var array<array-key, string> $macs */ + $macs = []; + + array_walk($addressPaths, function (string $addressPath) use (&$macs): void { + if (is_readable($addressPath)) { + $macs[] = file_get_contents($addressPath); + } + }); + + /** @var callable $trim */ + $trim = 'trim'; + + $macs = array_map($trim, $macs); + + // Remove invalid entries. + $macs = array_filter($macs, function (string $address) { + return $address !== '00:00:00:00:00:00' + && preg_match(self::SYSFS_PATTERN, $address); + }); + + /** @var string|bool $mac */ + $mac = reset($macs); + } + + return (string) $mac; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/NodeProviderInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/NodeProviderInterface.php new file mode 100644 index 0000000..d536b45 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/NodeProviderInterface.php @@ -0,0 +1,30 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider; + +use Ramsey\Uuid\Type\Hexadecimal; + +/** + * A node provider retrieves or generates a node ID + */ +interface NodeProviderInterface +{ + /** + * Returns a node ID + * + * @return Hexadecimal The node ID as a hexadecimal string + */ + public function getNode(): Hexadecimal; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php new file mode 100644 index 0000000..526c8ff --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php @@ -0,0 +1,57 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Time; + +use Ramsey\Uuid\Provider\TimeProviderInterface; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\Time; + +/** + * FixedTimeProvider uses a known time to provide the time + * + * This provider allows the use of a previously-generated, or known, time + * when generating time-based UUIDs. + */ +class FixedTimeProvider implements TimeProviderInterface +{ + public function __construct(private Time $time) + { + } + + /** + * Sets the `usec` component of the time + * + * @param int|string|IntegerObject $value The `usec` value to set + */ + public function setUsec($value): void + { + $this->time = new Time($this->time->getSeconds(), $value); + } + + /** + * Sets the `sec` component of the time + * + * @param int|string|IntegerObject $value The `sec` value to set + */ + public function setSec($value): void + { + $this->time = new Time($value, $this->time->getMicroseconds()); + } + + public function getTime(): Time + { + return $this->time; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Time/SystemTimeProvider.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Time/SystemTimeProvider.php new file mode 100644 index 0000000..3a1e09c --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/Time/SystemTimeProvider.php @@ -0,0 +1,33 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider\Time; + +use Ramsey\Uuid\Provider\TimeProviderInterface; +use Ramsey\Uuid\Type\Time; + +use function gettimeofday; + +/** + * SystemTimeProvider retrieves the current time using built-in PHP functions + */ +class SystemTimeProvider implements TimeProviderInterface +{ + public function getTime(): Time + { + $time = gettimeofday(); + + return new Time($time['sec'], $time['usec']); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Provider/TimeProviderInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/TimeProviderInterface.php new file mode 100644 index 0000000..43588e0 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Provider/TimeProviderInterface.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Provider; + +use Ramsey\Uuid\Type\Time; + +/** + * A time provider retrieves the current time + */ +interface TimeProviderInterface +{ + /** + * Returns a time object + */ + public function getTime(): Time; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/Fields.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/Fields.php new file mode 100644 index 0000000..9acf810 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/Fields.php @@ -0,0 +1,195 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Fields\SerializableFieldsTrait; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Uuid; + +use function bin2hex; +use function dechex; +use function hexdec; +use function sprintf; +use function str_pad; +use function strlen; +use function substr; +use function unpack; + +use const STR_PAD_LEFT; + +/** + * RFC 4122 variant UUIDs are comprised of a set of named fields + * + * Internally, this class represents the fields together as a 16-byte binary + * string. + * + * @psalm-immutable + */ +final class Fields implements FieldsInterface +{ + use MaxTrait; + use NilTrait; + use SerializableFieldsTrait; + use VariantTrait; + use VersionTrait; + + /** + * @param string $bytes A 16-byte binary string representation of a UUID + * + * @throws InvalidArgumentException if the byte string is not exactly 16 bytes + * @throws InvalidArgumentException if the byte string does not represent an RFC 4122 UUID + * @throws InvalidArgumentException if the byte string does not contain a valid version + */ + public function __construct(private string $bytes) + { + if (strlen($this->bytes) !== 16) { + throw new InvalidArgumentException( + 'The byte string must be 16 bytes long; ' + . 'received ' . strlen($this->bytes) . ' bytes' + ); + } + + if (!$this->isCorrectVariant()) { + throw new InvalidArgumentException( + 'The byte string received does not conform to the RFC 4122 variant' + ); + } + + if (!$this->isCorrectVersion()) { + throw new InvalidArgumentException( + 'The byte string received does not contain a valid RFC 4122 version' + ); + } + } + + public function getBytes(): string + { + return $this->bytes; + } + + public function getClockSeq(): Hexadecimal + { + if ($this->isMax()) { + $clockSeq = 0xffff; + } elseif ($this->isNil()) { + $clockSeq = 0x0000; + } else { + $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; + } + + return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); + } + + public function getClockSeqHiAndReserved(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1))); + } + + public function getClockSeqLow(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1))); + } + + public function getNode(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 10))); + } + + public function getTimeHiAndVersion(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 6, 2))); + } + + public function getTimeLow(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 0, 4))); + } + + public function getTimeMid(): Hexadecimal + { + return new Hexadecimal(bin2hex(substr($this->bytes, 4, 2))); + } + + /** + * Returns the full 60-bit timestamp, without the version + * + * For version 2 UUIDs, the time_low field is the local identifier and + * should not be returned as part of the time. For this reason, we set the + * bottom 32 bits of the timestamp to 0's. As a result, there is some loss + * of fidelity of the timestamp, for version 2 UUIDs. The timestamp can be + * off by a range of 0 to 429.4967295 seconds (or 7 minutes, 9 seconds, and + * 496730 microseconds). + * + * For version 6 UUIDs, the timestamp order is reversed from the typical RFC + * 4122 order (the time bits are in the correct bit order, so that it is + * monotonically increasing). In returning the timestamp value, we put the + * bits in the order: time_low + time_mid + time_hi. + */ + public function getTimestamp(): Hexadecimal + { + $timestamp = match ($this->getVersion()) { + Uuid::UUID_TYPE_DCE_SECURITY => sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + '' + ), + Uuid::UUID_TYPE_REORDERED_TIME => sprintf( + '%08s%04s%03x', + $this->getTimeLow()->toString(), + $this->getTimeMid()->toString(), + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff + ), + // The Unix timestamp in version 7 UUIDs is a 48-bit number, + // but for consistency, we will return a 60-bit number, padded + // to the left with zeros. + Uuid::UUID_TYPE_UNIX_TIME => sprintf( + '%011s%04s', + $this->getTimeLow()->toString(), + $this->getTimeMid()->toString(), + ), + default => sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + $this->getTimeLow()->toString() + ), + }; + + return new Hexadecimal($timestamp); + } + + public function getVersion(): ?int + { + if ($this->isNil() || $this->isMax()) { + return null; + } + + /** @var int[] $parts */ + $parts = unpack('n*', $this->bytes); + + return $parts[4] >> 12; + } + + private function isCorrectVariant(): bool + { + if ($this->isNil() || $this->isMax()) { + return true; + } + + return $this->getVariant() === Uuid::RFC_4122; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php new file mode 100644 index 0000000..2241cf5 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php @@ -0,0 +1,128 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Fields\FieldsInterface as BaseFieldsInterface; +use Ramsey\Uuid\Type\Hexadecimal; + +/** + * RFC 4122 defines fields for a specific variant of UUID + * + * The fields of an RFC 4122 variant UUID are: + * + * * **time_low**: The low field of the timestamp, an unsigned 32-bit integer + * * **time_mid**: The middle field of the timestamp, an unsigned 16-bit integer + * * **time_hi_and_version**: The high field of the timestamp multiplexed with + * the version number, an unsigned 16-bit integer + * * **clock_seq_hi_and_reserved**: The high field of the clock sequence + * multiplexed with the variant, an unsigned 8-bit integer + * * **clock_seq_low**: The low field of the clock sequence, an unsigned + * 8-bit integer + * * **node**: The spatially unique node identifier, an unsigned 48-bit + * integer + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1 RFC 4122, § 4.1: Format + * + * @psalm-immutable + */ +interface FieldsInterface extends BaseFieldsInterface +{ + /** + * Returns the full 16-bit clock sequence, with the variant bits (two most + * significant bits) masked out + */ + public function getClockSeq(): Hexadecimal; + + /** + * Returns the high field of the clock sequence multiplexed with the variant + */ + public function getClockSeqHiAndReserved(): Hexadecimal; + + /** + * Returns the low field of the clock sequence + */ + public function getClockSeqLow(): Hexadecimal; + + /** + * Returns the node field + */ + public function getNode(): Hexadecimal; + + /** + * Returns the high field of the timestamp multiplexed with the version + */ + public function getTimeHiAndVersion(): Hexadecimal; + + /** + * Returns the low field of the timestamp + */ + public function getTimeLow(): Hexadecimal; + + /** + * Returns the middle field of the timestamp + */ + public function getTimeMid(): Hexadecimal; + + /** + * Returns the full 60-bit timestamp, without the version + */ + public function getTimestamp(): Hexadecimal; + + /** + * Returns the variant + * + * The variant number describes the layout of the UUID. The variant + * number has the following meaning: + * + * - 0 - Reserved for NCS backward compatibility + * - 2 - The RFC 4122 variant + * - 6 - Reserved, Microsoft Corporation backward compatibility + * - 7 - Reserved for future definition + * + * For RFC 4122 variant UUIDs, this value should always be the integer `2`. + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + */ + public function getVariant(): int; + + /** + * Returns the version + * + * The version number describes how the UUID was generated and has the + * following meaning: + * + * 1. Gregorian time UUID + * 2. DCE security UUID + * 3. Name-based UUID hashed with MD5 + * 4. Randomly generated UUID + * 5. Name-based UUID hashed with SHA-1 + * 6. Reordered time UUID + * 7. Unix Epoch time UUID + * + * This returns `null` if the UUID is not an RFC 4122 variant, since version + * is only meaningful for this variant. + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + */ + public function getVersion(): ?int; + + /** + * Returns true if these fields represent a nil UUID + * + * The nil UUID is special form of UUID that is specified to have all 128 + * bits set to zero. + */ + public function isNil(): bool; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/MaxTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/MaxTrait.php new file mode 100644 index 0000000..dedb727 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/MaxTrait.php @@ -0,0 +1,41 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +/** + * Provides common functionality for max UUIDs + * + * The max UUID is special form of UUID that is specified to have all 128 bits + * set to one. It is the inverse of the nil UUID. + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.10 Max UUID + * + * @psalm-immutable + */ +trait MaxTrait +{ + /** + * Returns the bytes that comprise the fields + */ + abstract public function getBytes(): string; + + /** + * Returns true if the byte string represents a max UUID + */ + public function isMax(): bool + { + return $this->getBytes() === "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/MaxUuid.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/MaxUuid.php new file mode 100644 index 0000000..e5ffa72 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/MaxUuid.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Uuid; + +/** + * The max UUID is special form of UUID that is specified to have all 128 bits + * set to one + * + * @psalm-immutable + */ +final class MaxUuid extends Uuid implements UuidInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/NilTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/NilTrait.php new file mode 100644 index 0000000..9a9774d --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/NilTrait.php @@ -0,0 +1,41 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +/** + * Provides common functionality for nil UUIDs + * + * The nil UUID is special form of UUID that is specified to have all 128 bits + * set to zero. + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.7 RFC 4122, § 4.1.7: Nil UUID + * + * @psalm-immutable + */ +trait NilTrait +{ + /** + * Returns the bytes that comprise the fields + */ + abstract public function getBytes(): string; + + /** + * Returns true if the byte string represents a nil UUID + */ + public function isNil(): bool + { + return $this->getBytes() === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/NilUuid.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/NilUuid.php new file mode 100644 index 0000000..c49b994 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/NilUuid.php @@ -0,0 +1,27 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Uuid; + +/** + * The nil UUID is special form of UUID that is specified to have all 128 bits + * set to zero + * + * @psalm-immutable + */ +final class NilUuid extends Uuid implements UuidInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/TimeTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/TimeTrait.php new file mode 100644 index 0000000..5d939fa --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/TimeTrait.php @@ -0,0 +1,55 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use DateTimeImmutable; +use DateTimeInterface; +use Ramsey\Uuid\Exception\DateTimeException; +use Throwable; + +use function str_pad; + +use const STR_PAD_LEFT; + +/** + * Provides common functionality for getting the time from a time-based UUID + * + * @psalm-immutable + */ +trait TimeTrait +{ + /** + * Returns a DateTimeInterface object representing the timestamp associated + * with the UUID + * + * @return DateTimeImmutable A PHP DateTimeImmutable instance representing + * the timestamp of a time-based UUID + */ + public function getDateTime(): DateTimeInterface + { + $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); + + try { + return new DateTimeImmutable( + '@' + . $time->getSeconds()->toString() + . '.' + . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) + ); + } catch (Throwable $e) { + throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); + } + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php new file mode 100644 index 0000000..2c2677d --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php @@ -0,0 +1,118 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Builder\UuidBuilderInterface; +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\Time\UnixTimeConverter; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\UnableToBuildUuidException; +use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Ramsey\Uuid\Math\BrickMathCalculator; +use Ramsey\Uuid\Rfc4122\UuidInterface as Rfc4122UuidInterface; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; +use Throwable; + +/** + * UuidBuilder builds instances of RFC 4122 UUIDs + * + * @psalm-immutable + */ +class UuidBuilder implements UuidBuilderInterface +{ + private TimeConverterInterface $unixTimeConverter; + + /** + * Constructs the DefaultUuidBuilder + * + * @param NumberConverterInterface $numberConverter The number converter to + * use when constructing the Uuid + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting Gregorian time extracted from version 1, 2, and 6 + * UUIDs to Unix timestamps + * @param TimeConverterInterface|null $unixTimeConverter The time converter + * to use for converter Unix Epoch time extracted from version 7 UUIDs + * to Unix timestamps + */ + public function __construct( + private NumberConverterInterface $numberConverter, + private TimeConverterInterface $timeConverter, + ?TimeConverterInterface $unixTimeConverter = null + ) { + $this->unixTimeConverter = $unixTimeConverter ?? new UnixTimeConverter(new BrickMathCalculator()); + } + + /** + * Builds and returns a Uuid + * + * @param CodecInterface $codec The codec to use for building this Uuid instance + * @param string $bytes The byte string from which to construct a UUID + * + * @return Rfc4122UuidInterface UuidBuilder returns instances of Rfc4122UuidInterface + * + * @psalm-pure + */ + public function build(CodecInterface $codec, string $bytes): UuidInterface + { + try { + /** @var Fields $fields */ + $fields = $this->buildFields($bytes); + + if ($fields->isNil()) { + return new NilUuid($fields, $this->numberConverter, $codec, $this->timeConverter); + } + + if ($fields->isMax()) { + return new MaxUuid($fields, $this->numberConverter, $codec, $this->timeConverter); + } + + switch ($fields->getVersion()) { + case Uuid::UUID_TYPE_TIME: + return new UuidV1($fields, $this->numberConverter, $codec, $this->timeConverter); + case Uuid::UUID_TYPE_DCE_SECURITY: + return new UuidV2($fields, $this->numberConverter, $codec, $this->timeConverter); + case Uuid::UUID_TYPE_HASH_MD5: + return new UuidV3($fields, $this->numberConverter, $codec, $this->timeConverter); + case Uuid::UUID_TYPE_RANDOM: + return new UuidV4($fields, $this->numberConverter, $codec, $this->timeConverter); + case Uuid::UUID_TYPE_HASH_SHA1: + return new UuidV5($fields, $this->numberConverter, $codec, $this->timeConverter); + case Uuid::UUID_TYPE_REORDERED_TIME: + return new UuidV6($fields, $this->numberConverter, $codec, $this->timeConverter); + case Uuid::UUID_TYPE_UNIX_TIME: + return new UuidV7($fields, $this->numberConverter, $codec, $this->unixTimeConverter); + case Uuid::UUID_TYPE_CUSTOM: + return new UuidV8($fields, $this->numberConverter, $codec, $this->timeConverter); + } + + throw new UnsupportedOperationException( + 'The UUID version in the given fields is not supported ' + . 'by this UUID builder' + ); + } catch (Throwable $e) { + throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); + } + } + + /** + * Proxy method to allow injecting a mock, for testing + */ + protected function buildFields(string $bytes): FieldsInterface + { + return new Fields($bytes); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php new file mode 100644 index 0000000..e80f33b --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\UuidInterface as BaseUuidInterface; + +/** + * Also known as a Leach-Salz variant UUID, an RFC 4122 variant UUID is a + * universally unique identifier defined by RFC 4122 + * + * @link https://tools.ietf.org/html/rfc4122 RFC 4122 + * + * @psalm-immutable + */ +interface UuidInterface extends BaseUuidInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php new file mode 100644 index 0000000..515c038 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; + +/** + * Gregorian time, or version 1, UUIDs include timestamp, clock sequence, and node + * values that are combined into a 128-bit unsigned integer + * + * @psalm-immutable + */ +final class UuidV1 extends Uuid implements UuidInterface +{ + use TimeTrait; + + /** + * Creates a version 1 (Gregorian time) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_TIME) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV1 must represent a ' + . 'version 1 (time-based) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php new file mode 100644 index 0000000..c8ccbe4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php @@ -0,0 +1,115 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Uuid; + +use function hexdec; + +/** + * DCE Security version, or version 2, UUIDs include local domain identifier, + * local ID for the specified domain, and node values that are combined into a + * 128-bit unsigned integer + * + * It is important to note that a version 2 UUID suffers from some loss of + * fidelity of the timestamp, due to replacing the time_low field with the + * local identifier. When constructing the timestamp value for date + * purposes, we replace the local identifier bits with zeros. As a result, + * the timestamp can be off by a range of 0 to 429.4967295 seconds (or 7 + * minutes, 9 seconds, and 496730 microseconds). + * + * Astute observers might note this value directly corresponds to 2^32 - 1, + * or 0xffffffff. The local identifier is 32-bits, and we have set each of + * these bits to 0, so the maximum range of timestamp drift is 0x00000000 + * to 0xffffffff (counted in 100-nanosecond intervals). + * + * @link https://publications.opengroup.org/c311 DCE 1.1: Authentication and Security Services + * @link https://publications.opengroup.org/c706 DCE 1.1: Remote Procedure Call + * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01 DCE 1.1: Auth & Sec, §5.2.1.1 + * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1: Auth & Sec, §11.5.1.1 + * @link https://pubs.opengroup.org/onlinepubs/9629399/apdxa.htm DCE 1.1: RPC, Appendix A + * @link https://github.com/google/uuid Go package for UUIDs (includes DCE implementation) + * + * @psalm-immutable + */ +final class UuidV2 extends Uuid implements UuidInterface +{ + use TimeTrait; + + /** + * Creates a version 2 (DCE Security) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_DCE_SECURITY) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV2 must represent a ' + . 'version 2 (DCE Security) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } + + /** + * Returns the local domain used to create this version 2 UUID + */ + public function getLocalDomain(): int + { + /** @var Rfc4122FieldsInterface $fields */ + $fields = $this->getFields(); + + return (int) hexdec($fields->getClockSeqLow()->toString()); + } + + /** + * Returns the string name of the local domain + */ + public function getLocalDomainName(): string + { + return Uuid::DCE_DOMAIN_NAMES[$this->getLocalDomain()]; + } + + /** + * Returns the local identifier for the domain used to create this version 2 UUID + */ + public function getLocalIdentifier(): IntegerObject + { + /** @var Rfc4122FieldsInterface $fields */ + $fields = $this->getFields(); + + return new IntegerObject( + $this->numberConverter->fromHex($fields->getTimeLow()->toString()) + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV3.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV3.php new file mode 100644 index 0000000..deaa54e --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV3.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; + +/** + * Version 3 UUIDs are named-based, using combination of a namespace and name + * that are hashed into a 128-bit unsigned integer using MD5 + * + * @psalm-immutable + */ +final class UuidV3 extends Uuid implements UuidInterface +{ + /** + * Creates a version 3 (name-based, MD5-hashed) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_HASH_MD5) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV3 must represent a ' + . 'version 3 (name-based, MD5-hashed) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV4.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV4.php new file mode 100644 index 0000000..2e57246 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV4.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; + +/** + * Random, or version 4, UUIDs are randomly or pseudo-randomly generated 128-bit + * integers + * + * @psalm-immutable + */ +final class UuidV4 extends Uuid implements UuidInterface +{ + /** + * Creates a version 4 (random) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_RANDOM) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV4 must represent a ' + . 'version 4 (random) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV5.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV5.php new file mode 100644 index 0000000..2ef6ab3 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV5.php @@ -0,0 +1,58 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; + +/** + * Version 5 UUIDs are named-based, using combination of a namespace and name + * that are hashed into a 128-bit unsigned integer using SHA1 + * + * @psalm-immutable + */ +final class UuidV5 extends Uuid implements UuidInterface +{ + /** + * Creates a version 5 (name-based, SHA1-hashed) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_HASH_SHA1) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV5 must represent a ' + . 'version 5 (named-based, SHA1-hashed) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV6.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV6.php new file mode 100644 index 0000000..7e37433 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV6.php @@ -0,0 +1,29 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Nonstandard\UuidV6 as NonstandardUuidV6; + +/** + * Reordered time, or version 6, UUIDs include timestamp, clock sequence, and + * node values that are combined into a 128-bit unsigned integer + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.6 UUID Version 6 + * + * @psalm-immutable + */ +final class UuidV6 extends NonstandardUuidV6 implements UuidInterface +{ +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV7.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV7.php new file mode 100644 index 0000000..5b524c4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV7.php @@ -0,0 +1,62 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; + +/** + * Unix Epoch time, or version 7, UUIDs include a timestamp in milliseconds + * since the Unix Epoch, along with random bytes + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.7 UUID Version 7 + * + * @psalm-immutable + */ +final class UuidV7 extends Uuid implements UuidInterface +{ + use TimeTrait; + + /** + * Creates a version 7 (Unix Epoch time) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_UNIX_TIME) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV7 must represent a ' + . 'version 7 (Unix Epoch time) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV8.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV8.php new file mode 100644 index 0000000..78b0290 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/UuidV8.php @@ -0,0 +1,65 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\InvalidArgumentException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Uuid; + +/** + * Version 8, Custom UUIDs provide an RFC 4122 compatible format for + * experimental or vendor-specific uses + * + * The only requirement for version 8 UUIDs is that the version and variant bits + * must be set. Otherwise, implementations are free to set the other bits + * according to their needs. As a result, the uniqueness of version 8 UUIDs is + * implementation-specific and should not be assumed. + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.8 UUID Version 8 + * + * @psalm-immutable + */ +final class UuidV8 extends Uuid implements UuidInterface +{ + /** + * Creates a version 8 (custom) UUID + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_CUSTOM) { + throw new InvalidArgumentException( + 'Fields used to create a UuidV8 must represent a ' + . 'version 8 (custom) UUID' + ); + } + + parent::__construct($fields, $numberConverter, $codec, $timeConverter); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/Validator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/Validator.php new file mode 100644 index 0000000..e82a11e --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/Validator.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\Validator\ValidatorInterface; + +use function preg_match; +use function str_replace; + +/** + * Rfc4122\Validator validates strings as UUIDs of the RFC 4122 variant + * + * @psalm-immutable + */ +final class Validator implements ValidatorInterface +{ + private const VALID_PATTERN = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-' + . '[1-8][0-9A-Fa-f]{3}-[ABab89][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}\z'; + + /** + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function getPattern(): string + { + return self::VALID_PATTERN; + } + + public function validate(string $uuid): bool + { + $uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid); + $uuid = strtolower($uuid); + + return $uuid === Uuid::NIL || $uuid === Uuid::MAX || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php new file mode 100644 index 0000000..1041de5 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php @@ -0,0 +1,94 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Exception\InvalidBytesException; +use Ramsey\Uuid\Uuid; + +use function decbin; +use function str_pad; +use function str_starts_with; +use function strlen; +use function substr; +use function unpack; + +use const STR_PAD_LEFT; + +/** + * Provides common functionality for handling the variant, as defined by RFC 4122 + * + * @psalm-immutable + */ +trait VariantTrait +{ + /** + * Returns the bytes that comprise the fields + */ + abstract public function getBytes(): string; + + /** + * Returns the variant identifier, according to RFC 4122, for the given bytes + * + * The following values may be returned: + * + * - `0` -- Reserved, NCS backward compatibility. + * - `2` -- The variant specified in RFC 4122. + * - `6` -- Reserved, Microsoft Corporation backward compatibility. + * - `7` -- Reserved for future definition. + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + * + * @return int The variant identifier, according to RFC 4122 + */ + public function getVariant(): int + { + if (strlen($this->getBytes()) !== 16) { + throw new InvalidBytesException('Invalid number of bytes'); + } + + if ($this->isMax() || $this->isNil()) { + // RFC 4122 defines these special types of UUID, so we will consider + // them as belonging to the RFC 4122 variant. + return Uuid::RFC_4122; + } + + /** @var int[] $parts */ + $parts = unpack('n*', $this->getBytes()); + + // $parts[5] is a 16-bit, unsigned integer containing the variant bits + // of the UUID. We convert this integer into a string containing a + // binary representation, padded to 16 characters. We analyze the first + // three characters (three most-significant bits) to determine the + // variant. + $binary = str_pad( + decbin($parts[5]), + 16, + '0', + STR_PAD_LEFT + ); + + $msb = substr($binary, 0, 3); + + if ($msb === '111') { + return Uuid::RESERVED_FUTURE; + } elseif ($msb === '110') { + return Uuid::RESERVED_MICROSOFT; + } elseif (str_starts_with($msb, '10')) { + return Uuid::RFC_4122; + } + + return Uuid::RESERVED_NCS; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php new file mode 100644 index 0000000..0195e46 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php @@ -0,0 +1,60 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Rfc4122; + +use Ramsey\Uuid\Uuid; + +/** + * Provides common functionality for handling the version, as defined by RFC 4122 + * + * @psalm-immutable + */ +trait VersionTrait +{ + /** + * Returns the version + */ + abstract public function getVersion(): ?int; + + /** + * Returns true if these fields represent a max UUID + */ + abstract public function isMax(): bool; + + /** + * Returns true if these fields represent a nil UUID + */ + abstract public function isNil(): bool; + + /** + * Returns true if the version matches one of those defined by RFC 4122 + * + * @return bool True if the UUID version is valid, false otherwise + */ + private function isCorrectVersion(): bool + { + if ($this->isNil() || $this->isMax()) { + return true; + } + + return match ($this->getVersion()) { + Uuid::UUID_TYPE_TIME, Uuid::UUID_TYPE_DCE_SECURITY, + Uuid::UUID_TYPE_HASH_MD5, Uuid::UUID_TYPE_RANDOM, + Uuid::UUID_TYPE_HASH_SHA1, Uuid::UUID_TYPE_REORDERED_TIME, + Uuid::UUID_TYPE_UNIX_TIME, Uuid::UUID_TYPE_CUSTOM => true, + default => false, + }; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Type/Decimal.php b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Decimal.php new file mode 100644 index 0000000..acc5e75 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Decimal.php @@ -0,0 +1,129 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Type; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use ValueError; + +use function is_numeric; +use function sprintf; +use function str_starts_with; + +/** + * A value object representing a decimal + * + * This class exists for type-safety purposes, to ensure that decimals + * returned from ramsey/uuid methods as strings are truly decimals and not some + * other kind of string. + * + * To support values as true decimals and not as floats or doubles, we store the + * decimals as strings. + * + * @psalm-immutable + */ +final class Decimal implements NumberInterface +{ + private string $value; + private bool $isNegative = false; + + public function __construct(float | int | string | self $value) + { + $value = (string) $value; + + if (!is_numeric($value)) { + throw new InvalidArgumentException( + 'Value must be a signed decimal or a string containing only ' + . 'digits 0-9 and, optionally, a decimal point or sign (+ or -)' + ); + } + + // Remove the leading +-symbol. + if (str_starts_with($value, '+')) { + $value = substr($value, 1); + } + + // For cases like `-0` or `-0.0000`, convert the value to `0`. + if (abs((float) $value) === 0.0) { + $value = '0'; + } + + if (str_starts_with($value, '-')) { + $this->isNegative = true; + } + + $this->value = $value; + } + + public function isNegative(): bool + { + return $this->isNegative; + } + + public function toString(): string + { + return $this->value; + } + + public function __toString(): string + { + return $this->toString(); + } + + public function jsonSerialize(): string + { + return $this->toString(); + } + + public function serialize(): string + { + return $this->toString(); + } + + /** + * @return array{string: string} + */ + public function __serialize(): array + { + return ['string' => $this->toString()]; + } + + /** + * Constructs the object from a serialized string representation + * + * @param string $data The serialized string representation of the object + * + * @psalm-suppress UnusedMethodCall + */ + public function unserialize(string $data): void + { + $this->__construct($data); + } + + /** + * @param array{string?: string} $data + * + * @psalm-suppress UnusedMethodCall + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Type/Hexadecimal.php b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Hexadecimal.php new file mode 100644 index 0000000..bf71ec4 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Hexadecimal.php @@ -0,0 +1,115 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Type; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use ValueError; + +use function preg_match; +use function sprintf; +use function substr; + +/** + * A value object representing a hexadecimal number + * + * This class exists for type-safety purposes, to ensure that hexadecimal numbers + * returned from ramsey/uuid methods as strings are truly hexadecimal and not some + * other kind of string. + * + * @psalm-immutable + */ +final class Hexadecimal implements TypeInterface +{ + private string $value; + + /** + * @param self|string $value The hexadecimal value to store + */ + public function __construct(self | string $value) + { + $this->value = $value instanceof self ? (string) $value : $this->prepareValue($value); + } + + public function toString(): string + { + return $this->value; + } + + public function __toString(): string + { + return $this->toString(); + } + + public function jsonSerialize(): string + { + return $this->toString(); + } + + public function serialize(): string + { + return $this->toString(); + } + + /** + * @return array{string: string} + */ + public function __serialize(): array + { + return ['string' => $this->toString()]; + } + + /** + * Constructs the object from a serialized string representation + * + * @param string $data The serialized string representation of the object + * + * @psalm-suppress UnusedMethodCall + */ + public function unserialize(string $data): void + { + $this->__construct($data); + } + + /** + * @param array{string?: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } + + private function prepareValue(string $value): string + { + $value = strtolower($value); + + if (str_starts_with($value, '0x')) { + $value = substr($value, 2); + } + + if (!preg_match('/^[A-Fa-f0-9]+$/', $value)) { + throw new InvalidArgumentException( + 'Value must be a hexadecimal number' + ); + } + + return $value; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Type/Integer.php b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Integer.php new file mode 100644 index 0000000..50dac99 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Integer.php @@ -0,0 +1,158 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Type; + +use Ramsey\Uuid\Exception\InvalidArgumentException; +use ValueError; + +use function assert; +use function is_numeric; +use function preg_match; +use function sprintf; +use function substr; + +/** + * A value object representing an integer + * + * This class exists for type-safety purposes, to ensure that integers + * returned from ramsey/uuid methods as strings are truly integers and not some + * other kind of string. + * + * To support large integers beyond PHP_INT_MAX and PHP_INT_MIN on both 64-bit + * and 32-bit systems, we store the integers as strings. + * + * @psalm-immutable + */ +final class Integer implements NumberInterface +{ + /** + * @psalm-var numeric-string + */ + private string $value; + + private bool $isNegative = false; + + public function __construct(float | int | string | self $value) + { + $this->value = $value instanceof self ? (string) $value : $this->prepareValue($value); + } + + public function isNegative(): bool + { + return $this->isNegative; + } + + /** + * @psalm-return numeric-string + */ + public function toString(): string + { + return $this->value; + } + + /** + * @psalm-return numeric-string + */ + public function __toString(): string + { + return $this->toString(); + } + + public function jsonSerialize(): string + { + return $this->toString(); + } + + public function serialize(): string + { + return $this->toString(); + } + + /** + * @return array{string: string} + */ + public function __serialize(): array + { + return ['string' => $this->toString()]; + } + + /** + * Constructs the object from a serialized string representation + * + * @param string $data The serialized string representation of the object + * + * @psalm-suppress UnusedMethodCall + */ + public function unserialize(string $data): void + { + $this->__construct($data); + } + + /** + * @param array{string?: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } + + /** + * @return numeric-string + */ + private function prepareValue(float | int | string $value): string + { + $value = (string) $value; + $sign = '+'; + + // If the value contains a sign, remove it for digit pattern check. + if (str_starts_with($value, '-') || str_starts_with($value, '+')) { + $sign = substr($value, 0, 1); + $value = substr($value, 1); + } + + if (!preg_match('/^\d+$/', $value)) { + throw new InvalidArgumentException( + 'Value must be a signed integer or a string containing only ' + . 'digits 0-9 and, optionally, a sign (+ or -)' + ); + } + + // Trim any leading zeros. + $value = ltrim($value, '0'); + + // Set to zero if the string is empty after trimming zeros. + if ($value === '') { + $value = '0'; + } + + // Add the negative sign back to the value. + if ($sign === '-' && $value !== '0') { + $value = $sign . $value; + + /** @psalm-suppress InaccessibleProperty */ + $this->isNegative = true; + } + + assert(is_numeric($value)); + + return $value; + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Type/NumberInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Type/NumberInterface.php new file mode 100644 index 0000000..bf4ae9d --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Type/NumberInterface.php @@ -0,0 +1,28 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Type; + +/** + * NumberInterface ensures consistency in numeric values returned by ramsey/uuid + * + * @psalm-immutable + */ +interface NumberInterface extends TypeInterface +{ + /** + * Returns true if this number is less than zero + */ + public function isNegative(): bool; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Type/Time.php b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Time.php new file mode 100644 index 0000000..0cedb44 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Type/Time.php @@ -0,0 +1,128 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Type; + +use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use ValueError; + +use function json_decode; +use function json_encode; +use function sprintf; + +/** + * A value object representing a timestamp + * + * This class exists for type-safety purposes, to ensure that timestamps used + * by ramsey/uuid are truly timestamp integers and not some other kind of string + * or integer. + * + * @psalm-immutable + */ +final class Time implements TypeInterface +{ + private IntegerObject $seconds; + private IntegerObject $microseconds; + + public function __construct( + float | int | string | IntegerObject $seconds, + float | int | string | IntegerObject $microseconds = 0, + ) { + $this->seconds = new IntegerObject($seconds); + $this->microseconds = new IntegerObject($microseconds); + } + + public function getSeconds(): IntegerObject + { + return $this->seconds; + } + + public function getMicroseconds(): IntegerObject + { + return $this->microseconds; + } + + public function toString(): string + { + return $this->seconds->toString() . '.' . sprintf('%06s', $this->microseconds->toString()); + } + + public function __toString(): string + { + return $this->toString(); + } + + /** + * @return string[] + */ + public function jsonSerialize(): array + { + return [ + 'seconds' => $this->getSeconds()->toString(), + 'microseconds' => $this->getMicroseconds()->toString(), + ]; + } + + public function serialize(): string + { + return (string) json_encode($this); + } + + /** + * @return array{seconds: string, microseconds: string} + */ + public function __serialize(): array + { + return [ + 'seconds' => $this->getSeconds()->toString(), + 'microseconds' => $this->getMicroseconds()->toString(), + ]; + } + + /** + * Constructs the object from a serialized string representation + * + * @param string $data The serialized string representation of the object + * + * @psalm-suppress UnusedMethodCall + */ + public function unserialize(string $data): void + { + /** @var array{seconds?: int|float|string, microseconds?: int|float|string} $time */ + $time = json_decode($data, true); + + if (!isset($time['seconds']) || !isset($time['microseconds'])) { + throw new UnsupportedOperationException( + 'Attempted to unserialize an invalid value' + ); + } + + $this->__construct($time['seconds'], $time['microseconds']); + } + + /** + * @param array{seconds?: string, microseconds?: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['seconds']) || !isset($data['microseconds'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->__construct($data['seconds'], $data['microseconds']); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Type/TypeInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Type/TypeInterface.php new file mode 100644 index 0000000..da2d8b2 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Type/TypeInterface.php @@ -0,0 +1,30 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Type; + +use JsonSerializable; +use Serializable; + +/** + * TypeInterface ensures consistency in typed values returned by ramsey/uuid + * + * @psalm-immutable + */ +interface TypeInterface extends JsonSerializable, Serializable +{ + public function toString(): string; + + public function __toString(): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Uuid.php b/php/libraries/composer/vendor/ramsey/uuid/src/Uuid.php new file mode 100644 index 0000000..e0384a5 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Uuid.php @@ -0,0 +1,758 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use BadMethodCallException; +use DateTimeInterface; +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Ramsey\Uuid\Fields\FieldsInterface; +use Ramsey\Uuid\Lazy\LazyUuidFromString; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use ValueError; + +use function assert; +use function bin2hex; +use function method_exists; +use function preg_match; +use function sprintf; +use function str_replace; +use function strcmp; +use function strlen; +use function strtolower; +use function substr; + +/** + * Uuid provides constants and static methods for working with and generating UUIDs + * + * @psalm-immutable + */ +class Uuid implements UuidInterface +{ + use DeprecatedUuidMethodsTrait; + + /** + * When this namespace is specified, the name string is a fully-qualified + * domain name + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs + */ + public const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; + + /** + * When this namespace is specified, the name string is a URL + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs + */ + public const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; + + /** + * When this namespace is specified, the name string is an ISO OID + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs + */ + public const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8'; + + /** + * When this namespace is specified, the name string is an X.500 DN in DER + * or a text output format + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs + */ + public const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'; + + /** + * The nil UUID is a special form of UUID that is specified to have all 128 + * bits set to zero + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.7 RFC 4122, § 4.1.7: Nil UUID + */ + public const NIL = '00000000-0000-0000-0000-000000000000'; + + /** + * The max UUID is a special form of UUID that is specified to have all 128 + * bits set to one + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.10 Max UUID + */ + public const MAX = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; + + /** + * Variant: reserved, NCS backward compatibility + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + */ + public const RESERVED_NCS = 0; + + /** + * Variant: the UUID layout specified in RFC 4122 + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + */ + public const RFC_4122 = 2; + + /** + * Variant: reserved, Microsoft Corporation backward compatibility + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + */ + public const RESERVED_MICROSOFT = 6; + + /** + * Variant: reserved for future definition + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + */ + public const RESERVED_FUTURE = 7; + + /** + * @deprecated Use {@see ValidatorInterface::getPattern()} instead. + */ + public const VALID_PATTERN = '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'; + + /** + * Version 1 (Gregorian time) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + */ + public const UUID_TYPE_TIME = 1; + + /** + * Version 2 (DCE Security) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + */ + public const UUID_TYPE_DCE_SECURITY = 2; + + /** + * @deprecated Use {@see Uuid::UUID_TYPE_DCE_SECURITY} instead. + */ + public const UUID_TYPE_IDENTIFIER = 2; + + /** + * Version 3 (name-based and hashed with MD5) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + */ + public const UUID_TYPE_HASH_MD5 = 3; + + /** + * Version 4 (random) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + */ + public const UUID_TYPE_RANDOM = 4; + + /** + * Version 5 (name-based and hashed with SHA1) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + */ + public const UUID_TYPE_HASH_SHA1 = 5; + + /** + * @deprecated Use {@see Uuid::UUID_TYPE_REORDERED_TIME} instead. + */ + public const UUID_TYPE_PEABODY = 6; + + /** + * Version 6 (reordered time) UUID + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.6 UUID Version 6 + */ + public const UUID_TYPE_REORDERED_TIME = 6; + + /** + * Version 7 (Unix Epoch time) UUID + * + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.7 UUID Version 7 + */ + public const UUID_TYPE_UNIX_TIME = 7; + + /** + * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.8 UUID Version 8 + */ + public const UUID_TYPE_CUSTOM = 8; + + /** + * DCE Security principal domain + * + * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 + */ + public const DCE_DOMAIN_PERSON = 0; + + /** + * DCE Security group domain + * + * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 + */ + public const DCE_DOMAIN_GROUP = 1; + + /** + * DCE Security organization domain + * + * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 + */ + public const DCE_DOMAIN_ORG = 2; + + /** + * DCE Security domain string names + * + * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 + */ + public const DCE_DOMAIN_NAMES = [ + self::DCE_DOMAIN_PERSON => 'person', + self::DCE_DOMAIN_GROUP => 'group', + self::DCE_DOMAIN_ORG => 'org', + ]; + + private static ?UuidFactoryInterface $factory = null; + + /** + * @var bool flag to detect if the UUID factory was replaced internally, + * which disables all optimizations for the default/happy path internal + * scenarios + */ + private static bool $factoryReplaced = false; + + protected CodecInterface $codec; + protected NumberConverterInterface $numberConverter; + protected Rfc4122FieldsInterface $fields; + protected TimeConverterInterface $timeConverter; + + /** + * Creates a universally unique identifier (UUID) from an array of fields + * + * Unless you're making advanced use of this library to generate identifiers + * that deviate from RFC 4122, you probably do not want to instantiate a + * UUID directly. Use the static methods, instead: + * + * ``` + * use Ramsey\Uuid\Uuid; + * + * $timeBasedUuid = Uuid::uuid1(); + * $namespaceMd5Uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'http://php.net/'); + * $randomUuid = Uuid::uuid4(); + * $namespaceSha1Uuid = Uuid::uuid5(Uuid::NAMESPACE_URL, 'http://php.net/'); + * ``` + * + * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID + * @param NumberConverterInterface $numberConverter The number converter to use + * for converting hex values to/from integers + * @param CodecInterface $codec The codec to use when encoding or decoding + * UUID strings + * @param TimeConverterInterface $timeConverter The time converter to use + * for converting timestamps extracted from a UUID to unix timestamps + */ + public function __construct( + Rfc4122FieldsInterface $fields, + NumberConverterInterface $numberConverter, + CodecInterface $codec, + TimeConverterInterface $timeConverter + ) { + $this->fields = $fields; + $this->codec = $codec; + $this->numberConverter = $numberConverter; + $this->timeConverter = $timeConverter; + } + + /** + * @psalm-return non-empty-string + */ + public function __toString(): string + { + return $this->toString(); + } + + /** + * Converts the UUID to a string for JSON serialization + */ + public function jsonSerialize(): string + { + return $this->toString(); + } + + /** + * Converts the UUID to a string for PHP serialization + */ + public function serialize(): string + { + return $this->codec->encode($this); + } + + /** + * @return array{bytes: string} + */ + public function __serialize(): array + { + return ['bytes' => $this->serialize()]; + } + + /** + * Re-constructs the object from its serialized form + * + * @param string $data The serialized PHP string to unserialize into + * a UuidInterface instance + */ + public function unserialize(string $data): void + { + if (strlen($data) === 16) { + /** @var Uuid $uuid */ + $uuid = self::getFactory()->fromBytes($data); + } else { + /** @var Uuid $uuid */ + $uuid = self::getFactory()->fromString($data); + } + + $this->codec = $uuid->codec; + $this->numberConverter = $uuid->numberConverter; + $this->fields = $uuid->fields; + $this->timeConverter = $uuid->timeConverter; + } + + /** + * @param array{bytes?: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['bytes'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['bytes']); + } + + public function compareTo(UuidInterface $other): int + { + $compare = strcmp($this->toString(), $other->toString()); + + if ($compare < 0) { + return -1; + } + + if ($compare > 0) { + return 1; + } + + return 0; + } + + public function equals(?object $other): bool + { + if (!$other instanceof UuidInterface) { + return false; + } + + return $this->compareTo($other) === 0; + } + + /** + * @psalm-return non-empty-string + */ + public function getBytes(): string + { + return $this->codec->encodeBinary($this); + } + + public function getFields(): FieldsInterface + { + return $this->fields; + } + + public function getHex(): Hexadecimal + { + return new Hexadecimal(str_replace('-', '', $this->toString())); + } + + public function getInteger(): IntegerObject + { + return new IntegerObject($this->numberConverter->fromHex($this->getHex()->toString())); + } + + public function getUrn(): string + { + return 'urn:uuid:' . $this->toString(); + } + + /** + * @psalm-return non-empty-string + */ + public function toString(): string + { + return $this->codec->encode($this); + } + + /** + * Returns the factory used to create UUIDs + */ + public static function getFactory(): UuidFactoryInterface + { + if (self::$factory === null) { + self::$factory = new UuidFactory(); + } + + return self::$factory; + } + + /** + * Sets the factory used to create UUIDs + * + * @param UuidFactoryInterface $factory A factory that will be used by this + * class to create UUIDs + */ + public static function setFactory(UuidFactoryInterface $factory): void + { + // Note: non-strict equality is intentional here. If the factory is configured differently, every assumption + // around purity is broken, and we have to internally decide everything differently. + // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedNotEqualOperator + self::$factoryReplaced = ($factory != new UuidFactory()); + + self::$factory = $factory; + } + + /** + * Creates a UUID from a byte string + * + * @param string $bytes A binary string + * + * @return UuidInterface A UuidInterface instance created from a binary + * string representation + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + * + * @psalm-suppress ImpureStaticProperty we know that the factory being replaced can lead to massive + * havoc across all consumers: that should never happen, and + * is generally to be discouraged. Until the factory is kept + * un-replaced, this method is effectively pure. + */ + public static function fromBytes(string $bytes): UuidInterface + { + if (!self::$factoryReplaced && strlen($bytes) === 16) { + $base16Uuid = bin2hex($bytes); + + // Note: we are calling `fromString` internally because we don't know if the given `$bytes` is a valid UUID + return self::fromString( + substr($base16Uuid, 0, 8) + . '-' + . substr($base16Uuid, 8, 4) + . '-' + . substr($base16Uuid, 12, 4) + . '-' + . substr($base16Uuid, 16, 4) + . '-' + . substr($base16Uuid, 20, 12) + ); + } + + return self::getFactory()->fromBytes($bytes); + } + + /** + * Creates a UUID from the string standard representation + * + * @param string $uuid A hexadecimal string + * + * @return UuidInterface A UuidInterface instance created from a hexadecimal + * string representation + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + * + * @psalm-suppress ImpureStaticProperty we know that the factory being replaced can lead to massive + * havoc across all consumers: that should never happen, and + * is generally to be discouraged. Until the factory is kept + * un-replaced, this method is effectively pure. + */ + public static function fromString(string $uuid): UuidInterface + { + $uuid = strtolower($uuid); + if (!self::$factoryReplaced && preg_match(LazyUuidFromString::VALID_REGEX, $uuid) === 1) { + assert($uuid !== ''); + + return new LazyUuidFromString($uuid); + } + + return self::getFactory()->fromString($uuid); + } + + /** + * Creates a UUID from a DateTimeInterface instance + * + * @param DateTimeInterface $dateTime The date and time + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID created from a DateTimeInterface instance + */ + public static function fromDateTime( + DateTimeInterface $dateTime, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface { + return self::getFactory()->fromDateTime($dateTime, $node, $clockSeq); + } + + /** + * Creates a UUID from the Hexadecimal object + * + * @param Hexadecimal $hex Hexadecimal object representing a hexadecimal number + * + * @return UuidInterface A UuidInterface instance created from the Hexadecimal + * object representing a hexadecimal number + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + * @psalm-suppress MixedInferredReturnType,MixedReturnStatement + */ + public static function fromHexadecimal(Hexadecimal $hex): UuidInterface + { + $factory = self::getFactory(); + + if (method_exists($factory, 'fromHexadecimal')) { + /** + * @phpstan-ignore-next-line + * @psalm-suppress UndefinedInterfaceMethod + */ + return self::getFactory()->fromHexadecimal($hex); + } + + throw new BadMethodCallException('The method fromHexadecimal() does not exist on the provided factory'); + } + + /** + * Creates a UUID from a 128-bit integer string + * + * @param string $integer String representation of 128-bit integer + * + * @return UuidInterface A UuidInterface instance created from the string + * representation of a 128-bit integer + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + */ + public static function fromInteger(string $integer): UuidInterface + { + /** @psalm-suppress ImpureMethodCall */ + return self::getFactory()->fromInteger($integer); + } + + /** + * Returns true if the provided string is a valid UUID + * + * @param string $uuid A string to validate as a UUID + * + * @return bool True if the string is a valid UUID, false otherwise + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + * + * @psalm-assert-if-true =non-empty-string $uuid + */ + public static function isValid(string $uuid): bool + { + /** @psalm-suppress ImpureMethodCall */ + return self::getFactory()->getValidator()->validate($uuid); + } + + /** + * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, + * and the current time + * + * @param Hexadecimal|int|string|null $node A 48-bit number representing the + * hardware address; this number may be represented as an integer or a + * hexadecimal string + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * could arise when the clock is set backwards in time or if the node ID + * changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID + */ + public static function uuid1($node = null, ?int $clockSeq = null): UuidInterface + { + return self::getFactory()->uuid1($node, $clockSeq); + } + + /** + * Returns a version 2 (DCE Security) UUID from a local domain, local + * identifier, host ID, clock sequence, and the current time + * + * @param int $localDomain The local domain to use when generating bytes, + * according to DCE Security + * @param IntegerObject|null $localIdentifier The local identifier for the + * given domain; this may be a UID or GID on POSIX systems, if the local + * domain is person or group, or it may be a site-defined identifier + * if the local domain is org + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes (in a version 2 UUID, the lower 8 bits of this number + * are replaced with the domain). + * + * @return UuidInterface A UuidInterface instance that represents a + * version 2 UUID + */ + public static function uuid2( + int $localDomain, + ?IntegerObject $localIdentifier = null, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface { + return self::getFactory()->uuid2($localDomain, $localIdentifier, $node, $clockSeq); + } + + /** + * Returns a version 3 (name-based) UUID based on the MD5 hash of a + * namespace ID and a name + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 3 UUID + * + * @psalm-suppress ImpureMethodCall we know that the factory being replaced can lead to massive + * havoc across all consumers: that should never happen, and + * is generally to be discouraged. Until the factory is kept + * un-replaced, this method is effectively pure. + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + */ + public static function uuid3($ns, string $name): UuidInterface + { + return self::getFactory()->uuid3($ns, $name); + } + + /** + * Returns a version 4 (random) UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 4 UUID + */ + public static function uuid4(): UuidInterface + { + return self::getFactory()->uuid4(); + } + + /** + * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a + * namespace ID and a name + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 5 UUID + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + * + * @psalm-suppress ImpureMethodCall we know that the factory being replaced can lead to massive + * havoc across all consumers: that should never happen, and + * is generally to be discouraged. Until the factory is kept + * un-replaced, this method is effectively pure. + */ + public static function uuid5($ns, string $name): UuidInterface + { + return self::getFactory()->uuid5($ns, $name); + } + + /** + * Returns a version 6 (reordered time) UUID from a host ID, sequence number, + * and the current time + * + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * could arise when the clock is set backwards in time or if the node ID + * changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 6 UUID + */ + public static function uuid6( + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface { + return self::getFactory()->uuid6($node, $clockSeq); + } + + /** + * Returns a version 7 (Unix Epoch time) UUID + * + * @param DateTimeInterface|null $dateTime An optional date/time from which + * to create the version 7 UUID. If not provided, the UUID is generated + * using the current date/time. + * + * @return UuidInterface A UuidInterface instance that represents a + * version 7 UUID + */ + public static function uuid7(?DateTimeInterface $dateTime = null): UuidInterface + { + $factory = self::getFactory(); + + if (method_exists($factory, 'uuid7')) { + /** @var UuidInterface */ + return $factory->uuid7($dateTime); + } + + throw new UnsupportedOperationException( + 'The provided factory does not support the uuid7() method', + ); + } + + /** + * Returns a version 8 (custom) UUID + * + * The bytes provided may contain any value according to your application's + * needs. Be aware, however, that other applications may not understand the + * semantics of the value. + * + * @param string $bytes A 16-byte octet string. This is an open blob + * of data that you may fill with 128 bits of information. Be aware, + * however, bits 48 through 51 will be replaced with the UUID version + * field, and bits 64 and 65 will be replaced with the UUID variant. You + * MUST NOT rely on these bits for your application needs. + * + * @return UuidInterface A UuidInterface instance that represents a + * version 8 UUID + */ + public static function uuid8(string $bytes): UuidInterface + { + $factory = self::getFactory(); + + if (method_exists($factory, 'uuid8')) { + /** @var UuidInterface */ + return $factory->uuid8($bytes); + } + + throw new UnsupportedOperationException( + 'The provided factory does not support the uuid8() method', + ); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/UuidFactory.php b/php/libraries/composer/vendor/ramsey/uuid/src/UuidFactory.php new file mode 100644 index 0000000..1b06ea6 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/UuidFactory.php @@ -0,0 +1,513 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use DateTimeInterface; +use Ramsey\Uuid\Builder\UuidBuilderInterface; +use Ramsey\Uuid\Codec\CodecInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Generator\DceSecurityGeneratorInterface; +use Ramsey\Uuid\Generator\DefaultTimeGenerator; +use Ramsey\Uuid\Generator\NameGeneratorInterface; +use Ramsey\Uuid\Generator\RandomGeneratorInterface; +use Ramsey\Uuid\Generator\TimeGeneratorInterface; +use Ramsey\Uuid\Generator\UnixTimeGenerator; +use Ramsey\Uuid\Lazy\LazyUuidFromString; +use Ramsey\Uuid\Provider\NodeProviderInterface; +use Ramsey\Uuid\Provider\Time\FixedTimeProvider; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Type\Time; +use Ramsey\Uuid\Validator\ValidatorInterface; + +use function bin2hex; +use function hex2bin; +use function pack; +use function str_pad; +use function strtolower; +use function substr; +use function substr_replace; +use function unpack; + +use const STR_PAD_LEFT; + +class UuidFactory implements UuidFactoryInterface +{ + private CodecInterface $codec; + private DceSecurityGeneratorInterface $dceSecurityGenerator; + private NameGeneratorInterface $nameGenerator; + private NodeProviderInterface $nodeProvider; + private NumberConverterInterface $numberConverter; + private RandomGeneratorInterface $randomGenerator; + private TimeConverterInterface $timeConverter; + private TimeGeneratorInterface $timeGenerator; + private TimeGeneratorInterface $unixTimeGenerator; + private UuidBuilderInterface $uuidBuilder; + private ValidatorInterface $validator; + + /** + * @var bool whether the feature set was provided from outside, or we can + * operate under "default" assumptions + */ + private bool $isDefaultFeatureSet; + + /** + * @param FeatureSet|null $features A set of available features in the current environment + */ + public function __construct(?FeatureSet $features = null) + { + $this->isDefaultFeatureSet = $features === null; + + $features = $features ?: new FeatureSet(); + + $this->codec = $features->getCodec(); + $this->dceSecurityGenerator = $features->getDceSecurityGenerator(); + $this->nameGenerator = $features->getNameGenerator(); + $this->nodeProvider = $features->getNodeProvider(); + $this->numberConverter = $features->getNumberConverter(); + $this->randomGenerator = $features->getRandomGenerator(); + $this->timeConverter = $features->getTimeConverter(); + $this->timeGenerator = $features->getTimeGenerator(); + $this->uuidBuilder = $features->getBuilder(); + $this->validator = $features->getValidator(); + $this->unixTimeGenerator = $features->getUnixTimeGenerator(); + } + + /** + * Returns the codec used by this factory + */ + public function getCodec(): CodecInterface + { + return $this->codec; + } + + /** + * Sets the codec to use for this factory + * + * @param CodecInterface $codec A UUID encoder-decoder + */ + public function setCodec(CodecInterface $codec): void + { + $this->isDefaultFeatureSet = false; + + $this->codec = $codec; + } + + /** + * Returns the name generator used by this factory + */ + public function getNameGenerator(): NameGeneratorInterface + { + return $this->nameGenerator; + } + + /** + * Sets the name generator to use for this factory + * + * @param NameGeneratorInterface $nameGenerator A generator to generate + * binary data, based on a namespace and name + */ + public function setNameGenerator(NameGeneratorInterface $nameGenerator): void + { + $this->isDefaultFeatureSet = false; + + $this->nameGenerator = $nameGenerator; + } + + /** + * Returns the node provider used by this factory + */ + public function getNodeProvider(): NodeProviderInterface + { + return $this->nodeProvider; + } + + /** + * Returns the random generator used by this factory + */ + public function getRandomGenerator(): RandomGeneratorInterface + { + return $this->randomGenerator; + } + + /** + * Returns the time generator used by this factory + */ + public function getTimeGenerator(): TimeGeneratorInterface + { + return $this->timeGenerator; + } + + /** + * Sets the time generator to use for this factory + * + * @param TimeGeneratorInterface $generator A generator to generate binary + * data, based on the time + */ + public function setTimeGenerator(TimeGeneratorInterface $generator): void + { + $this->isDefaultFeatureSet = false; + + $this->timeGenerator = $generator; + } + + /** + * Returns the DCE Security generator used by this factory + */ + public function getDceSecurityGenerator(): DceSecurityGeneratorInterface + { + return $this->dceSecurityGenerator; + } + + /** + * Sets the DCE Security generator to use for this factory + * + * @param DceSecurityGeneratorInterface $generator A generator to generate + * binary data, based on a local domain and local identifier + */ + public function setDceSecurityGenerator(DceSecurityGeneratorInterface $generator): void + { + $this->isDefaultFeatureSet = false; + + $this->dceSecurityGenerator = $generator; + } + + /** + * Returns the number converter used by this factory + */ + public function getNumberConverter(): NumberConverterInterface + { + return $this->numberConverter; + } + + /** + * Sets the random generator to use for this factory + * + * @param RandomGeneratorInterface $generator A generator to generate binary + * data, based on some random input + */ + public function setRandomGenerator(RandomGeneratorInterface $generator): void + { + $this->isDefaultFeatureSet = false; + + $this->randomGenerator = $generator; + } + + /** + * Sets the number converter to use for this factory + * + * @param NumberConverterInterface $converter A converter to use for working + * with large integers (i.e. integers greater than PHP_INT_MAX) + */ + public function setNumberConverter(NumberConverterInterface $converter): void + { + $this->isDefaultFeatureSet = false; + + $this->numberConverter = $converter; + } + + /** + * Returns the UUID builder used by this factory + */ + public function getUuidBuilder(): UuidBuilderInterface + { + return $this->uuidBuilder; + } + + /** + * Sets the UUID builder to use for this factory + * + * @param UuidBuilderInterface $builder A builder for constructing instances + * of UuidInterface + */ + public function setUuidBuilder(UuidBuilderInterface $builder): void + { + $this->isDefaultFeatureSet = false; + + $this->uuidBuilder = $builder; + } + + /** + * @psalm-mutation-free + */ + public function getValidator(): ValidatorInterface + { + return $this->validator; + } + + /** + * Sets the validator to use for this factory + * + * @param ValidatorInterface $validator A validator to use for validating + * whether a string is a valid UUID + */ + public function setValidator(ValidatorInterface $validator): void + { + $this->isDefaultFeatureSet = false; + + $this->validator = $validator; + } + + /** + * @psalm-pure + */ + public function fromBytes(string $bytes): UuidInterface + { + return $this->codec->decodeBytes($bytes); + } + + /** + * @psalm-pure + */ + public function fromString(string $uuid): UuidInterface + { + $uuid = strtolower($uuid); + + return $this->codec->decode($uuid); + } + + /** + * @psalm-pure + */ + public function fromInteger(string $integer): UuidInterface + { + $hex = $this->numberConverter->toHex($integer); + $hex = str_pad($hex, 32, '0', STR_PAD_LEFT); + + return $this->fromString($hex); + } + + public function fromDateTime( + DateTimeInterface $dateTime, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface { + $timeProvider = new FixedTimeProvider( + new Time($dateTime->format('U'), $dateTime->format('u')) + ); + + $timeGenerator = new DefaultTimeGenerator( + $this->nodeProvider, + $this->timeConverter, + $timeProvider + ); + + $nodeHex = $node ? $node->toString() : null; + + $bytes = $timeGenerator->generate($nodeHex, $clockSeq); + + return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_TIME); + } + + /** + * @psalm-pure + */ + public function fromHexadecimal(Hexadecimal $hex): UuidInterface + { + return $this->codec->decode($hex->__toString()); + } + + /** + * @inheritDoc + */ + public function uuid1($node = null, ?int $clockSeq = null): UuidInterface + { + $bytes = $this->timeGenerator->generate($node, $clockSeq); + + return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_TIME); + } + + public function uuid2( + int $localDomain, + ?IntegerObject $localIdentifier = null, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface { + $bytes = $this->dceSecurityGenerator->generate( + $localDomain, + $localIdentifier, + $node, + $clockSeq + ); + + return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_DCE_SECURITY); + } + + /** + * @inheritDoc + * @psalm-pure + */ + public function uuid3($ns, string $name): UuidInterface + { + return $this->uuidFromNsAndName($ns, $name, Uuid::UUID_TYPE_HASH_MD5, 'md5'); + } + + public function uuid4(): UuidInterface + { + $bytes = $this->randomGenerator->generate(16); + + return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_RANDOM); + } + + /** + * @inheritDoc + * @psalm-pure + */ + public function uuid5($ns, string $name): UuidInterface + { + return $this->uuidFromNsAndName($ns, $name, Uuid::UUID_TYPE_HASH_SHA1, 'sha1'); + } + + public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface + { + $nodeHex = $node ? $node->toString() : null; + $bytes = $this->timeGenerator->generate($nodeHex, $clockSeq); + + // Rearrange the bytes, according to the UUID version 6 specification. + $v6 = $bytes[6] . $bytes[7] . $bytes[4] . $bytes[5] + . $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3]; + $v6 = bin2hex($v6); + + // Drop the first four bits, while adding an empty four bits for the + // version field. This allows us to reconstruct the correct time from + // the bytes of this UUID. + $v6Bytes = hex2bin(substr($v6, 1, 12) . '0' . substr($v6, -3)); + $v6Bytes .= substr($bytes, 8); + + return $this->uuidFromBytesAndVersion($v6Bytes, Uuid::UUID_TYPE_REORDERED_TIME); + } + + /** + * Returns a version 7 (Unix Epoch time) UUID + * + * @param DateTimeInterface|null $dateTime An optional date/time from which + * to create the version 7 UUID. If not provided, the UUID is generated + * using the current date/time. + * + * @return UuidInterface A UuidInterface instance that represents a + * version 7 UUID + */ + public function uuid7(?DateTimeInterface $dateTime = null): UuidInterface + { + assert($this->unixTimeGenerator instanceof UnixTimeGenerator); + $bytes = $this->unixTimeGenerator->generate(null, null, $dateTime); + + return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_UNIX_TIME); + } + + /** + * Returns a version 8 (Custom) UUID + * + * The bytes provided may contain any value according to your application's + * needs. Be aware, however, that other applications may not understand the + * semantics of the value. + * + * @param string $bytes A 16-byte octet string. This is an open blob + * of data that you may fill with 128 bits of information. Be aware, + * however, bits 48 through 51 will be replaced with the UUID version + * field, and bits 64 and 65 will be replaced with the UUID variant. You + * MUST NOT rely on these bits for your application needs. + * + * @return UuidInterface A UuidInterface instance that represents a + * version 8 UUID + */ + public function uuid8(string $bytes): UuidInterface + { + return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_CUSTOM); + } + + /** + * Returns a Uuid created from the provided byte string + * + * Uses the configured builder and codec and the provided byte string to + * construct a Uuid object. + * + * @param string $bytes The byte string from which to construct a UUID + * + * @return UuidInterface An instance of UuidInterface, created from the + * provided bytes + * + * @psalm-pure + */ + public function uuid(string $bytes): UuidInterface + { + /** @psalm-suppress ImpurePropertyFetch */ + return $this->uuidBuilder->build($this->codec, $bytes); + } + + /** + * Returns a version 3 or 5 namespaced Uuid + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to hash together with the namespace + * @param int $version The version of UUID to create (3 or 5) + * @param string $hashAlgorithm The hashing algorithm to use when hashing + * together the namespace and name + * + * @return UuidInterface An instance of UuidInterface, created by hashing + * together the provided namespace and name + * + * @psalm-pure + */ + private function uuidFromNsAndName( + UuidInterface | string $ns, + string $name, + int $version, + string $hashAlgorithm + ): UuidInterface { + if (!($ns instanceof UuidInterface)) { + $ns = $this->fromString($ns); + } + + $bytes = $this->nameGenerator->generate($ns, $name, $hashAlgorithm); + + return $this->uuidFromBytesAndVersion(substr($bytes, 0, 16), $version); + } + + /** + * Returns an RFC 4122 variant Uuid, created from the provided bytes and version + * + * @param string $bytes The byte string to convert to a UUID + * @param int $version The RFC 4122 version to apply to the UUID + * + * @return UuidInterface An instance of UuidInterface, created from the + * byte string and version + * + * @psalm-pure + */ + private function uuidFromBytesAndVersion(string $bytes, int $version): UuidInterface + { + /** @var array $unpackedTime */ + $unpackedTime = unpack('n*', substr($bytes, 6, 2)); + $timeHi = (int) $unpackedTime[1]; + $timeHiAndVersion = pack('n*', BinaryUtils::applyVersion($timeHi, $version)); + + /** @var array $unpackedClockSeq */ + $unpackedClockSeq = unpack('n*', substr($bytes, 8, 2)); + $clockSeqHi = (int) $unpackedClockSeq[1]; + $clockSeqHiAndReserved = pack('n*', BinaryUtils::applyVariant($clockSeqHi)); + + $bytes = substr_replace($bytes, $timeHiAndVersion, 6, 2); + $bytes = substr_replace($bytes, $clockSeqHiAndReserved, 8, 2); + + if ($this->isDefaultFeatureSet) { + return LazyUuidFromString::fromBytes($bytes); + } + + /** @psalm-suppress ImpureVariable */ + return $this->uuid($bytes); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/UuidFactoryInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/UuidFactoryInterface.php new file mode 100644 index 0000000..d99fc9d --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/UuidFactoryInterface.php @@ -0,0 +1,182 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use DateTimeInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Ramsey\Uuid\Validator\ValidatorInterface; + +/** + * UuidFactoryInterface defines common functionality all `UuidFactory` instances + * must implement + */ +interface UuidFactoryInterface +{ + /** + * Creates a UUID from a byte string + * + * @param string $bytes A binary string + * + * @return UuidInterface A UuidInterface instance created from a binary + * string representation + * + * @psalm-pure + */ + public function fromBytes(string $bytes): UuidInterface; + + /** + * Creates a UUID from a DateTimeInterface instance + * + * @param DateTimeInterface $dateTime The date and time + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID created from a DateTimeInterface instance + */ + public function fromDateTime( + DateTimeInterface $dateTime, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface; + + /** + * Creates a UUID from a 128-bit integer string + * + * @param string $integer String representation of 128-bit integer + * + * @return UuidInterface A UuidInterface instance created from the string + * representation of a 128-bit integer + * + * @psalm-pure + */ + public function fromInteger(string $integer): UuidInterface; + + /** + * Creates a UUID from the string standard representation + * + * @param string $uuid A hexadecimal string + * + * @return UuidInterface A UuidInterface instance created from a hexadecimal + * string representation + * + * @psalm-pure + */ + public function fromString(string $uuid): UuidInterface; + + /** + * Returns the validator to use for the factory + * + * @psalm-mutation-free + */ + public function getValidator(): ValidatorInterface; + + /** + * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, + * and the current time + * + * @param Hexadecimal|int|string|null $node A 48-bit number representing the + * hardware address; this number may be represented as an integer or a + * hexadecimal string + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID + */ + public function uuid1($node = null, ?int $clockSeq = null): UuidInterface; + + /** + * Returns a version 2 (DCE Security) UUID from a local domain, local + * identifier, host ID, clock sequence, and the current time + * + * @param int $localDomain The local domain to use when generating bytes, + * according to DCE Security + * @param IntegerObject|null $localIdentifier The local identifier for the + * given domain; this may be a UID or GID on POSIX systems, if the local + * domain is person or group, or it may be a site-defined identifier + * if the local domain is org + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 2 UUID + */ + public function uuid2( + int $localDomain, + ?IntegerObject $localIdentifier = null, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface; + + /** + * Returns a version 3 (name-based) UUID based on the MD5 hash of a + * namespace ID and a name + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 3 UUID + * + * @psalm-pure + */ + public function uuid3($ns, string $name): UuidInterface; + + /** + * Returns a version 4 (random) UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 4 UUID + */ + public function uuid4(): UuidInterface; + + /** + * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a + * namespace ID and a name + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 5 UUID + * + * @psalm-pure + */ + public function uuid5($ns, string $name): UuidInterface; + + /** + * Returns a version 6 (reordered time) UUID from a host ID, sequence number, + * and the current time + * + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 6 UUID + */ + public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/UuidInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/UuidInterface.php new file mode 100644 index 0000000..cac9457 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/UuidInterface.php @@ -0,0 +1,109 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use JsonSerializable; +use Ramsey\Uuid\Fields\FieldsInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; +use Serializable; +use Stringable; + +/** + * A UUID is a universally unique identifier adhering to an agreed-upon + * representation format and standard for generation + * + * @psalm-immutable + */ +interface UuidInterface extends + DeprecatedUuidInterface, + JsonSerializable, + Serializable, + Stringable +{ + /** + * Returns -1, 0, or 1 if the UUID is less than, equal to, or greater than + * the other UUID + * + * The first of two UUIDs is greater than the second if the most + * significant field in which the UUIDs differ is greater for the first + * UUID. + * + * * Q. What's the value of being able to sort UUIDs? + * * A. Use them as keys in a B-Tree or similar mapping. + * + * @param UuidInterface $other The UUID to compare + * + * @return int<-1,1> -1, 0, or 1 if the UUID is less than, equal to, or greater than $other + */ + public function compareTo(UuidInterface $other): int; + + /** + * Returns true if the UUID is equal to the provided object + * + * The result is true if and only if the argument is not null, is a UUID + * object, has the same variant, and contains the same value, bit for bit, + * as the UUID. + * + * @param object|null $other An object to test for equality with this UUID + * + * @return bool True if the other object is equal to this UUID + */ + public function equals(?object $other): bool; + + /** + * Returns the binary string representation of the UUID + * + * @psalm-return non-empty-string + */ + public function getBytes(): string; + + /** + * Returns the fields that comprise this UUID + */ + public function getFields(): FieldsInterface; + + /** + * Returns the hexadecimal representation of the UUID + */ + public function getHex(): Hexadecimal; + + /** + * Returns the integer representation of the UUID + */ + public function getInteger(): IntegerObject; + + /** + * Returns the string standard representation of the UUID as a URN + * + * @link http://en.wikipedia.org/wiki/Uniform_Resource_Name Uniform Resource Name + * @link https://tools.ietf.org/html/rfc4122#section-3 RFC 4122, § 3: Namespace Registration Template + */ + public function getUrn(): string; + + /** + * Returns the string standard representation of the UUID + * + * @psalm-return non-empty-string + */ + public function toString(): string; + + /** + * Casts the UUID to the string standard representation + * + * @psalm-return non-empty-string + */ + public function __toString(): string; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Validator/GenericValidator.php b/php/libraries/composer/vendor/ramsey/uuid/src/Validator/GenericValidator.php new file mode 100644 index 0000000..fd60955 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Validator/GenericValidator.php @@ -0,0 +1,50 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Validator; + +use Ramsey\Uuid\Uuid; + +use function preg_match; +use function str_replace; + +/** + * GenericValidator validates strings as UUIDs of any variant + * + * @psalm-immutable + */ +final class GenericValidator implements ValidatorInterface +{ + /** + * Regular expression pattern for matching a UUID of any variant. + */ + private const VALID_PATTERN = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\z'; + + /** + * @psalm-return non-empty-string + * @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty + * @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty + */ + public function getPattern(): string + { + return self::VALID_PATTERN; + } + + public function validate(string $uuid): bool + { + $uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid); + + return $uuid === Uuid::NIL || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid); + } +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/Validator/ValidatorInterface.php b/php/libraries/composer/vendor/ramsey/uuid/src/Validator/ValidatorInterface.php new file mode 100644 index 0000000..3d4bd6f --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/Validator/ValidatorInterface.php @@ -0,0 +1,41 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Validator; + +/** + * A validator validates a string as a proper UUID + * + * @psalm-immutable + */ +interface ValidatorInterface +{ + /** + * Returns the regular expression pattern used by this validator + * + * @return string The regular expression pattern this validator uses + * + * @psalm-return non-empty-string + */ + public function getPattern(): string; + + /** + * Returns true if the provided string represents a UUID + * + * @param string $uuid The string to validate as a UUID + * + * @return bool True if the string is a valid UUID, false otherwise + */ + public function validate(string $uuid): bool; +} diff --git a/php/libraries/composer/vendor/ramsey/uuid/src/functions.php b/php/libraries/composer/vendor/ramsey/uuid/src/functions.php new file mode 100644 index 0000000..1b3ce00 --- /dev/null +++ b/php/libraries/composer/vendor/ramsey/uuid/src/functions.php @@ -0,0 +1,158 @@ +<?php + +/** + * This file is part of the ramsey/uuid library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> + * @license http://opensource.org/licenses/MIT MIT + * phpcs:disable Squiz.Functions.GlobalFunction + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid; + +use DateTimeInterface; +use Ramsey\Uuid\Type\Hexadecimal; +use Ramsey\Uuid\Type\Integer as IntegerObject; + +/** + * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, + * and the current time + * + * @param Hexadecimal|int|string|null $node A 48-bit number representing the + * hardware address; this number may be represented as an integer or a + * hexadecimal string + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * could arise when the clock is set backwards in time or if the node ID + * changes + * + * @return non-empty-string Version 1 UUID as a string + */ +function v1($node = null, ?int $clockSeq = null): string +{ + return Uuid::uuid1($node, $clockSeq)->toString(); +} + +/** + * Returns a version 2 (DCE Security) UUID from a local domain, local + * identifier, host ID, clock sequence, and the current time + * + * @param int $localDomain The local domain to use when generating bytes, + * according to DCE Security + * @param IntegerObject|null $localIdentifier The local identifier for the + * given domain; this may be a UID or GID on POSIX systems, if the local + * domain is person or group, or it may be a site-defined identifier + * if the local domain is org + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return non-empty-string Version 2 UUID as a string + */ +function v2( + int $localDomain, + ?IntegerObject $localIdentifier = null, + ?Hexadecimal $node = null, + ?int $clockSeq = null +): string { + return Uuid::uuid2($localDomain, $localIdentifier, $node, $clockSeq)->toString(); +} + +/** + * Returns a version 3 (name-based) UUID based on the MD5 hash of a + * namespace ID and a name + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * + * @return non-empty-string Version 3 UUID as a string + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + */ +function v3($ns, string $name): string +{ + return Uuid::uuid3($ns, $name)->toString(); +} + +/** + * Returns a version 4 (random) UUID + * + * @return non-empty-string Version 4 UUID as a string + */ +function v4(): string +{ + return Uuid::uuid4()->toString(); +} + +/** + * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a + * namespace ID and a name + * + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * + * @return non-empty-string Version 5 UUID as a string + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners + */ +function v5($ns, string $name): string +{ + return Uuid::uuid5($ns, $name)->toString(); +} + +/** + * Returns a version 6 (reordered time) UUID from a host ID, sequence number, + * and the current time + * + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * could arise when the clock is set backwards in time or if the node ID + * changes + * + * @return non-empty-string Version 6 UUID as a string + */ +function v6(?Hexadecimal $node = null, ?int $clockSeq = null): string +{ + return Uuid::uuid6($node, $clockSeq)->toString(); +} + +/** + * Returns a version 7 (Unix Epoch time) UUID + * + * @param DateTimeInterface|null $dateTime An optional date/time from which + * to create the version 7 UUID. If not provided, the UUID is generated + * using the current date/time. + * + * @return non-empty-string Version 7 UUID as a string + */ +function v7(?DateTimeInterface $dateTime = null): string +{ + return Uuid::uuid7($dateTime)->toString(); +} + +/** + * Returns a version 8 (custom) UUID + * + * The bytes provided may contain any value according to your application's + * needs. Be aware, however, that other applications may not understand the + * semantics of the value. + * + * @param string $bytes A 16-byte octet string. This is an open blob + * of data that you may fill with 128 bits of information. Be aware, + * however, bits 48 through 51 will be replaced with the UUID version + * field, and bits 64 and 65 will be replaced with the UUID variant. You + * MUST NOT rely on these bits for your application needs. + * + * @return non-empty-string Version 8 UUID as a string + */ +function v8(string $bytes): string +{ + return Uuid::uuid8($bytes)->toString(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/.gitattributes b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.gitattributes new file mode 100644 index 0000000..dc96281 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.gitattributes @@ -0,0 +1,11 @@ +*.crt -crlf +*.key -crlf +*.srl -crlf +*.pub -crlf +*.priv -crlf +*.txt -crlf + +# ignore directories in the git-generated distributed .zip archive +/doc/notes export-ignore +/tests export-ignore +/phpunit.xml.dist export-ignore diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/ISSUE_TEMPLATE.md b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..5db6524 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,19 @@ +<!-- Please fill in this template according to your issue. --> + +| Q | A +| ------------------- | ----- +| Bug report? | yes/no +| Feature request? | yes/no +| RFC? | yes/no +| How used? | Standalone/Symfony/3party +| Swiftmailer version | x.y.z +| PHP version | x.y.z + +### Observed behaviour +<!-- What does the code do? --> + +### Expected behaviour +<!-- What should the code do? --> + +### Example +<!-- Example to reproduce the issue. --> diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/PULL_REQUEST_TEMPLATE.md b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..4b39510 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +<!-- Please fill in this template according to the PR you're about to submit. --> + +| Q | A +| ------------- | --- +| Bug fix? | yes/no +| New feature? | yes/no +| Doc update? | yes/no +| BC breaks? | yes/no +| Deprecations? | yes/no +| Fixed tickets | #... <!-- #-prefixed issue number(s), if any --> +| License | MIT + + +<!-- Replace this comment by the description of your issue. --> diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/workflows/tests.yml b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/workflows/tests.yml new file mode 100644 index 0000000..dc83ec6 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.github/workflows/tests.yml @@ -0,0 +1,55 @@ +name: tests + +on: + push: + pull_request: + +jobs: + linux_tests: + runs-on: ubuntu-20.04 + + services: + mailcatcher: + image: dockage/mailcatcher:0.7.1 + ports: + - 4456:1025 + + strategy: + fail-fast: true + matrix: + php: ['7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1'] + + name: PHP ${{ matrix.php }} + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, intl + tools: composer:v2 + coverage: none + + - name: Prepare test config files + run: | + cp tests/acceptance.conf.php.default tests/acceptance.conf.php + cp tests/smoke.conf.php.default tests/smoke.conf.php + + - name: Require Symfony PHPUnit Bridge 5.4 for PHP 8.1 + if: ${{ matrix.php >= 8.1 }} + run: composer require symfony/phpunit-bridge:^5.4 --dev --prefer-dist --no-interaction --no-progress + + - name: Install dependencies + uses: nick-invision/retry@v1 + with: + timeout_minutes: 5 + max_attempts: 5 + command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress + + - name: Execute tests + run: vendor/bin/simple-phpunit --verbose + env: + SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT: 1 diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/.gitignore b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.gitignore new file mode 100644 index 0000000..a911ddf --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.gitignore @@ -0,0 +1,9 @@ +/.php_cs.cache +/.phpunit +/.phpunit.result.cache +/build/* +/composer.lock +/phpunit.xml +/tests/acceptance.conf.php +/tests/smoke.conf.php +/vendor/ diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/.php_cs.dist b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.php_cs.dist new file mode 100644 index 0000000..563b48b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/.php_cs.dist @@ -0,0 +1,21 @@ +<?php + +return PhpCsFixer\Config::create() + ->setRules([ + '@Symfony' => true, + '@Symfony:risky' => true, + '@PHPUnit75Migration:risky' => true, + 'php_unit_dedicate_assert' => ['target' => '5.6'], + 'array_syntax' => ['syntax' => 'short'], + 'php_unit_fqcn_annotation' => true, + 'no_unreachable_default_argument_value' => false, + 'braces' => ['allow_single_line_closure' => true], + 'heredoc_to_nowdoc' => false, + 'ordered_imports' => true, + 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], + 'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'all'], + 'fopen_flags' => false, + ]) + ->setRiskyAllowed(true) + ->setFinder(PhpCsFixer\Finder::create()->in(__DIR__)) +; diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/CHANGES b/php/libraries/composer/vendor/swiftmailer/swiftmailer/CHANGES new file mode 100644 index 0000000..a7ffa00 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/CHANGES @@ -0,0 +1,391 @@ +Changelog +========= + +**Swiftmailer will stop being maintained at the end of November 2021.** + +Please, move to Symfony Mailer at your earliest convenience. +Symfony Mailer is the next evolution of Swiftmailer. +It provides the same features with support for modern PHP code and support for third-party providers. +See https://symfony.com/doc/current/mailer.html for more information. + +6.3.0 (2021-10-18) +------------------ + + * Fix support for PHP 8.1 + +6.2.7 (2021-03-09) +------------------ + + * Allow egulias/email-validator 3.1+ + +6.2.6 (2021-03-05) +------------------ + + * Fix Bcc support + +6.2.5 (2021-01-12) +------------------ + + * Don't trust properties at destruct time + * Remove invalid PHPDocs param in EventDispatcher interface + * Bump license year + * Removes PHP version from README + +6.2.4 (2020-12-08) +------------------ + + * Prevent flushing of the bubble queue when event handler raises another event + * Add support for PHP 8 + * Code cleanups + +6.2.3 (2019-11-12) +------------------ + + * no changes + +6.2.2 (2019-11-12) +------------------ + + * fixed compat with PHP 7.4 + * fixed error message when connecting to a stream raises an error before connect() + +6.2.1 (2019-04-21) +------------------ + + * reverted "deprecated Swift_CharacterStream_ArrayCharacterStream and Swift_CharacterStream_NgCharacterStream in favor of Swift_CharacterStream_CharacterStream" + +6.2.0 (2019-03-10) +------------------ + + * added support for symfony/polyfill-intl-dn + * deprecated Swift_CharacterStream_ArrayCharacterStream and Swift_CharacterStream_NgCharacterStream in favor of Swift_CharacterStream_CharacterStream + +6.1.3 (2018-09-11) +------------------ + + * added auto-start to the SMTP transport when sending a message + * tweaked error message when the response from an SMTP server is empty + * fixed missing property in Swift_Mime_IdGenerator + * exposed original body content type with Swift_Mime_SimpleMimeEntity::getBodyContentType() + * fixed typo in variable name in Swift_AddressEncoder_IdnAddressEncoder + * fixed return type in MessageLogger + * fixed missing property addressEncoder in SimpleHeaderFactory class + +6.1.2 (2018-07-13) +------------------ + + * handled recipient errors when pipelining + +6.1.1 (2018-07-04) +------------------ + + * removed hard dependency on an IDN encoder + +6.1.0 (2018-07-02) +------------------ + + * added address encoder exceptions during send + * added support for bubbling up authenticator error messages + * added support for non-ASCII email addresses + * introduced new dependencies: transport.smtphandlers and transport.authhandlers + * deprecated Swift_Signers_OpenDKIMSigner; use Swift_Signers_DKIMSigner instead + * added support for SMTP pipelining + * added Swift_Transport_Esmtp_EightBitMimeHandler + * fixed startTLS only allowed tls1.0, now allowed: tls1.0, tls1.1, tls1.2 + +6.0.2 (2017-09-30) +------------------ + + * fixed DecoratorPlugin + * removed usage of getmypid() + +6.0.1 (2017-05-20) +------------------ + + * fixed BC break that can be avoided easily + +6.0.0 (2017-05-19) +------------------ + + * added Swift_Transport::ping() + * removed Swift_Mime_HeaderFactory, Swift_Mime_HeaderSet, Swift_Mime_Message, Swift_Mime_MimeEntity, + and Swift_Mime_ParameterizedHeader interfaces + * removed Swift_MailTransport and Swift_Transport_MailTransport + * removed Swift_Encoding + * removed the Swift_Transport_MailInvoker interface and Swift_Transport_SimpleMailInvoker class + * removed the Swift_SignedMessage class + * removed newInstance() methods everywhere + * methods operating on Date header now use DateTimeImmutable object instead of Unix timestamp; + Swift_Mime_Headers_DateHeader::getTimestamp()/setTimestamp() renamed to getDateTime()/setDateTime() + * bumped minimum version to PHP 7.0 + * removed Swift_Validate and replaced by egulias/email-validator + +5.4.9 (2018-01-23) +------------------ + + * no changes, last version of the 5.x series + +5.4.8 (2017-05-01) +------------------ + + * fixed encoding inheritance in addPart() + * fixed sorting MIME children when their types are equal + +5.4.7 (2017-04-20) +------------------ + + * fixed NTLMAuthenticator clobbering bcmath scale + +5.4.6 (2017-02-13) +------------------ + + * removed exceptions thrown in destructors as they lead to fatal errors + * switched to use sha256 by default in DKIM as per the RFC + * fixed an 'Undefined variable: pipes' PHP notice + * fixed long To headers when using the mail transport + * fixed NTLMAuthenticator when no domain is passed with the username + * prevented fatal error during unserialization of a message + * fixed a PHP warning when sending a message that has a length of a multiple of 8192 + +5.4.5 (2016-12-29) +------------------ + + * SECURITY FIX: fixed CVE-2016-10074 by disallowing potentially unsafe shell characters + + Prior to 5.4.5, the mail transport (Swift_Transport_MailTransport) was vulnerable to passing + arbitrary shell arguments if the "From", "ReturnPath" or "Sender" header came + from a non-trusted source, potentially allowing Remote Code Execution + * deprecated the mail transport + +5.4.4 (2016-11-23) +------------------ + + * reverted escaping command-line args to mail (PHP mail() function already does it) + +5.4.3 (2016-07-08) +------------------ + + * fixed SimpleHeaderSet::has()/get() when the 0 index is removed + * removed the need to have mcrypt installed + * fixed broken MIME header encoding with quotes/colons and non-ascii chars + * allowed mail transport send for messages without To header + * fixed PHP 7 support + +5.4.2 (2016-05-01) +------------------ + + * fixed support for IPv6 sockets + * added auto-retry when sending messages from the memory spool + * fixed consecutive read calls in Swift_ByteStream_FileByteStream + * added support for iso-8859-15 encoding + * fixed PHP mail extra params on missing reversePath + * added methods to set custom stream context options + * fixed charset changes in QpContentEncoderProxy + * added return-path header to the ignoredHeaders list of DKIMSigner + * fixed crlf for subject using mail + * fixed add soft line break only when necessary + * fixed escaping command-line args to mail + +5.4.1 (2015-06-06) +------------------ + + * made Swiftmailer exceptions confirm to PHP base exception constructor signature + * fixed MAIL FROM & RCPT TO headers to be RFC compliant + +5.4.0 (2015-03-14) +------------------ + + * added the possibility to add extra certs to PKCS#7 signature + * fix base64 encoding with streams + * added a new RESULT_SPOOLED status for SpoolTransport + * fixed getBody() on attachments when called more than once + * removed dots from generated filenames in filespool + +5.3.1 (2014-12-05) +------------------ + + * fixed cloning of messages with attachments + +5.3.0 (2014-10-04) +------------------ + + * fixed cloning when using signers + * reverted removal of Swift_Encoding + * drop support for PHP 5.2.x + +5.2.2 (2014-09-20) +------------------ + + * fixed Japanese support + * fixed the memory spool when the message changes when in the pool + * added support for cloning messages + * fixed PHP warning in the redirect plugin + * changed the way to and cc-ed email are sent to only use one transaction + +5.2.1 (2014-06-13) +------------------ + + * SECURITY FIX: fixed CLI escaping when using sendmail as a transport + + Prior to 5.2.1, the sendmail transport (Swift_Transport_SendmailTransport) + was vulnerable to an arbitrary shell execution if the "From" header came + from a non-trusted source and no "Return-Path" is configured. + + * fixed parameter in DKIMSigner + * fixed compatibility with PHP < 5.4 + +5.2.0 (2014-05-08) +------------------ + + * fixed Swift_ByteStream_FileByteStream::read() to match to the specification + * fixed from-charset and to-charset arguments in mbstring_convert_encoding() usages + * fixed infinite loop in StreamBuffer + * fixed NullTransport to return the number of ignored emails instead of 0 + * Use phpunit and mockery for unit testing (realityking) + +5.1.0 (2014-03-18) +------------------ + + * fixed data writing to stream when sending large messages + * added support for libopendkim (https://github.com/xdecock/php-opendkim) + * merged SignedMessage and Message + * added Gmail XOAuth2 authentication + * updated the list of known mime types + * added NTLM authentication + +5.0.3 (2013-12-03) +------------------ + + * fixed double-dot bug + * fixed DKIM signer + +5.0.2 (2013-08-30) +------------------ + + * handled correct exception type while reading IoBuffer output + +5.0.1 (2013-06-17) +------------------ + + * changed the spool to only start the transport when a mail has to be sent + * fixed compatibility with PHP 5.2 + * fixed LICENSE file + +5.0.0 (2013-04-30) +------------------ + + * changed the license from LGPL to MIT + +4.3.1 (2013-04-11) +------------------ + + * removed usage of the native QP encoder when the charset is not UTF-8 + * fixed usage of uniqid to avoid collisions + * made a performance improvement when tokenizing large headers + * fixed usage of the PHP native QP encoder on PHP 5.4.7+ + +4.3.0 (2013-01-08) +------------------ + + * made the temporary directory configurable via the TMPDIR env variable + * added S/MIME signer and encryption support + +4.2.2 (2012-10-25) +------------------ + + * added the possibility to throttle messages per second in ThrottlerPlugin (mostly for Amazon SES) + * switched mime.qpcontentencoder to automatically use the PHP native encoder on PHP 5.4.7+ + * allowed specifying a whitelist with regular expressions in RedirectingPlugin + +4.2.1 (2012-07-13) +------------------ + + * changed the coding standards to PSR-1/2 + * fixed issue with autoloading + * added NativeQpContentEncoder to enhance performance (for PHP 5.3+) + +4.2.0 (2012-06-29) +------------------ + + * added documentation about how to use the Japanese support introduced in 4.1.8 + * added a way to override the default configuration in a lazy way + * changed the PEAR init script to lazy-load the initialization + * fixed a bug when calling Swift_Preferences before anything else (regression introduced in 4.1.8) + +4.1.8 (2012-06-17) +------------------ + + * added Japanese iso-2022-jp support + * changed the init script to lazy-load the initialization + * fixed docblocks (@id) which caused some problems with libraries parsing the dobclocks + * fixed Swift_Mime_Headers_IdentificationHeader::setId() when passed an array of ids + * fixed encoding of email addresses in headers + * added replacements setter to the Decorator plugin + +4.1.7 (2012-04-26) +------------------ + + * fixed QpEncoder safeMapShareId property + +4.1.6 (2012-03-23) +------------------ + + * reduced the size of serialized Messages + +4.1.5 (2012-01-04) +------------------ + + * enforced Swift_Spool::queueMessage() to return a Boolean + * made an optimization to the memory spool: start the transport only when required + * prevented stream_socket_client() from generating an error and throw a Swift_TransportException instead + * fixed a PHP warning when calling to mail() when safe_mode is off + * many doc tweaks + +4.1.4 (2011-12-16) +------------------ + + * added a memory spool (Swift_MemorySpool) + * fixed too many opened files when sending emails with attachments + +4.1.3 (2011-10-27) +------------------ + + * added STARTTLS support + * added missing @return tags on fluent methods + * added a MessageLogger plugin that logs all sent messages + * added composer.json + +4.1.2 (2011-09-13) +------------------ + + * fixed wrong detection of magic_quotes_runtime + * fixed fatal errors when no To or Subject header has been set + * fixed charset on parameter header continuations + * added documentation about how to install Swiftmailer from the PEAR channel + * fixed various typos and markup problem in the documentation + * fixed warning when cache directory does not exist + * fixed "slashes are escaped" bug + * changed require_once() to require() in autoload + +4.1.1 (2011-07-04) +------------------ + + * added missing file in PEAR package + +4.1.0 (2011-06-30) +------------------ + + * documentation has been converted to ReST + +4.1.0 RC1 (2011-06-17) +---------------------- + +New features: + + * changed the Decorator Plugin to allow replacements in all headers + * added Swift_Mime_Grammar and Swift_Validate to validate an email address + * modified the autoloader to lazy-initialize Swiftmailer + * removed Swift_Mailer::batchSend() + * added NullTransport + * added new plugins: RedirectingPlugin and ImpersonatePlugin + * added a way to send messages asynchronously (Spool) diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/LICENSE b/php/libraries/composer/vendor/swiftmailer/swiftmailer/LICENSE new file mode 100644 index 0000000..ab72077 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2021 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/README.md b/php/libraries/composer/vendor/swiftmailer/swiftmailer/README.md new file mode 100644 index 0000000..788d722 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/README.md @@ -0,0 +1,25 @@ +Swift Mailer +------------ + +**Swiftmailer will stop being maintained at the end of November 2021.** + +Please, move to [Symfony Mailer](https://symfony.com/doc/current/mailer.html) at your earliest convenience. +[Symfony Mailer](https://symfony.com/doc/current/mailer.html) is the next evolution of Swiftmailer. +It provides the same features with support for modern PHP code and support for third-party providers. + +Swift Mailer is a component based mailing solution for PHP. +It is released under the MIT license. + +Swift Mailer is highly object-oriented by design and lends itself +to use in complex web application with a great deal of flexibility. + +For full details on usage, read the [documentation](https://swiftmailer.symfony.com/docs/introduction.html). + +Sponsors +-------- + +<div> + <a href="https://blackfire.io/docs/introduction?utm_source=swiftmailer&utm_medium=github_readme&utm_campaign=logo"> + <img src="https://static.blackfire.io/assets/intemporals/logo/png/blackfire-io_secondary_horizontal_transparent.png?1" width="255px" alt="Blackfire.io"> + </a> +</div> diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/composer.json b/php/libraries/composer/vendor/swiftmailer/swiftmailer/composer.json new file mode 100644 index 0000000..546b3a1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/composer.json @@ -0,0 +1,44 @@ +{ + "name": "swiftmailer/swiftmailer", + "type": "library", + "description": "Swiftmailer, free feature-rich PHP mailer", + "keywords": ["mail","mailer","email"], + "homepage": "https://swiftmailer.symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Chris Corbyn" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "require": { + "php": ">=7.0.0", + "egulias/email-validator": "^2.0|^3.1", + "symfony/polyfill-iconv": "^1.0", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-intl-idn": "^1.10" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "symfony/phpunit-bridge": "^4.4|^5.4" + }, + "suggest": { + "ext-intl": "Needed to support internationalized email addresses" + }, + "autoload": { + "files": ["lib/swift_required.php"] + }, + "autoload-dev": { + "psr-0": { "Swift_": "tests/unit" } + }, + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/headers.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/headers.rst new file mode 100644 index 0000000..8b8bece --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/headers.rst @@ -0,0 +1,621 @@ +Message Headers +=============== + +Sometimes you'll want to add your own headers to a message or modify/remove +headers that are already present. You work with the message's HeaderSet to do +this. + +Header Basics +------------- + +All MIME entities in Swift Mailer -- including the message itself -- store +their headers in a single object called a HeaderSet. This HeaderSet is +retrieved with the ``getHeaders()`` method. + +As mentioned in the previous chapter, everything that forms a part of a message +in Swift Mailer is a MIME entity that is represented by an instance of +``Swift_Mime_SimpleMimeEntity``. This includes -- most notably -- the message +object itself, attachments, MIME parts and embedded images. Each of these MIME +entities consists of a body and a set of headers that describe the body. + +For all of the "standard" headers in these MIME entities, such as the +``Content-Type``, there are named methods for working with them, such as +``setContentType()`` and ``getContentType()``. This is because headers are a +moderately complex area of the library. Each header has a slightly different +required structure that it must meet in order to comply with the standards that +govern email (and that are checked by spam blockers etc). + +You fetch the HeaderSet from a MIME entity like so:: + + $message = new Swift_Message(); + + // Fetch the HeaderSet from a Message object + $headers = $message->getHeaders(); + + $attachment = Swift_Attachment::fromPath('document.pdf'); + + // Fetch the HeaderSet from an attachment object + $headers = $attachment->getHeaders(); + +The job of the HeaderSet is to contain and manage instances of Header objects. +Depending upon the MIME entity the HeaderSet came from, the contents of the +HeaderSet will be different, since an attachment for example has a different +set of headers to those in a message. + +You can find out what the HeaderSet contains with a quick loop, dumping out the +names of the headers:: + + foreach ($headers->getAll() as $header) { + printf("%s<br />\n", $header->getFieldName()); + } + + /* + Content-Transfer-Encoding + Content-Type + MIME-Version + Date + Message-ID + From + Subject + To + */ + +You can also dump out the rendered HeaderSet by calling its ``toString()`` +method:: + + echo $headers->toString(); + + /* + Message-ID: <1234869991.499a9ee7f1d5e@swift.generated> + Date: Tue, 17 Feb 2009 22:26:31 +1100 + Subject: Awesome subject! + From: sender@example.org + To: recipient@example.org + MIME-Version: 1.0 + Content-Type: text/plain; charset=utf-8 + Content-Transfer-Encoding: quoted-printable + */ + +Where the complexity comes in is when you want to modify an existing header. +This complexity comes from the fact that each header can be of a slightly +different type (such as a Date header, or a header that contains email +addresses, or a header that has key-value parameters on it!). Each header in +the HeaderSet is an instance of ``Swift_Mime_Header``. They all have common +functionality, but knowing exactly what type of header you're working with will +allow you a little more control. + +You can determine the type of header by comparing the return value of its +``getFieldType()`` method with the constants ``TYPE_TEXT``, +``TYPE_PARAMETERIZED``, ``TYPE_DATE``, ``TYPE_MAILBOX``, ``TYPE_ID`` and +``TYPE_PATH`` which are defined in ``Swift_Mime_Header``:: + + foreach ($headers->getAll() as $header) { + switch ($header->getFieldType()) { + case Swift_Mime_Header::TYPE_TEXT: $type = 'text'; + break; + case Swift_Mime_Header::TYPE_PARAMETERIZED: $type = 'parameterized'; + break; + case Swift_Mime_Header::TYPE_MAILBOX: $type = 'mailbox'; + break; + case Swift_Mime_Header::TYPE_DATE: $type = 'date'; + break; + case Swift_Mime_Header::TYPE_ID: $type = 'ID'; + break; + case Swift_Mime_Header::TYPE_PATH: $type = 'path'; + break; + } + printf("%s: is a %s header<br />\n", $header->getFieldName(), $type); + } + + /* + Content-Transfer-Encoding: is a text header + Content-Type: is a parameterized header + MIME-Version: is a text header + Date: is a date header + Message-ID: is a ID header + From: is a mailbox header + Subject: is a text header + To: is a mailbox header + */ + +Headers can be removed from the set, modified within the set, or added to the +set. + +The following sections show you how to work with the HeaderSet and explain the +details of each implementation of ``Swift_Mime_Header`` that may exist within +the HeaderSet. + +Header Types +------------ + +Because all headers are modeled on different data (dates, addresses, text!) +there are different types of Header in Swift Mailer. Swift Mailer attempts to +categorize all possible MIME headers into more general groups, defined by a +small number of classes. + +Text Headers +~~~~~~~~~~~~ + +Text headers are the simplest type of Header. They contain textual information +with no special information included within it -- for example the Subject +header in a message. + +There's nothing particularly interesting about a text header, though it is +probably the one you'd opt to use if you need to add a custom header to a +message. It represents text just like you'd think it does. If the text contains +characters that are not permitted in a message header (such as new lines, or +non-ascii characters) then the header takes care of encoding the text so that +it can be used. + +No header -- including text headers -- in Swift Mailer is vulnerable to +header-injection attacks. Swift Mailer breaks any attempt at header injection +by encoding the dangerous data into a non-dangerous form. + +It's easy to add a new text header to a HeaderSet. You do this by calling the +HeaderSet's ``addTextHeader()`` method:: + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addTextHeader('Your-Header-Name', 'the header value'); + +Changing the value of an existing text header is done by calling it's +``setValue()`` method:: + + $subject = $message->getHeaders()->get('Subject'); + $subject->setValue('new subject'); + +When output via ``toString()``, a text header produces something like the +following:: + + $subject = $message->getHeaders()->get('Subject'); + $subject->setValue('amazing subject line'); + echo $subject->toString(); + + /* + + Subject: amazing subject line + + */ + +If the header contains any characters that are outside of the US-ASCII range +however, they will be encoded. This is nothing to be concerned about since mail +clients will decode them back:: + + $subject = $message->getHeaders()->get('Subject'); + $subject->setValue('contains – dash'); + echo $subject->toString(); + + /* + + Subject: contains =?utf-8?Q?=E2=80=93?= dash + + */ + +Parameterized Headers +~~~~~~~~~~~~~~~~~~~~~ + +Parameterized headers are text headers that contain key-value parameters +following the textual content. The Content-Type header of a message is a +parameterized header since it contains charset information after the content +type. + +The parameterized header type is a special type of text header. It extends the +text header by allowing additional information to follow it. All of the methods +from text headers are available in addition to the methods described here. + +Adding a parameterized header to a HeaderSet is done by using the +``addParameterizedHeader()`` method which takes a text value like +``addTextHeader()`` but it also accepts an associative array of key-value +parameters:: + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addParameterizedHeader( + 'Header-Name', 'header value', + ['foo' => 'bar'] + ); + +To change the text value of the header, call it's ``setValue()`` method just as +you do with text headers. + +To change the parameters in the header, call the header's ``setParameters()`` +method or the ``setParameter()`` method (note the pluralization):: + + $type = $message->getHeaders()->get('Content-Type'); + + // setParameters() takes an associative array + $type->setParameters([ + 'name' => 'file.txt', + 'charset' => 'iso-8859-1' + ]); + + // setParameter() takes two args for $key and $value + $type->setParameter('charset', 'iso-8859-1'); + +When output via ``toString()``, a parameterized header produces something like +the following:: + + $type = $message->getHeaders()->get('Content-Type'); + $type->setValue('text/html'); + $type->setParameter('charset', 'utf-8'); + + echo $type->toString(); + + /* + + Content-Type: text/html; charset=utf-8 + + */ + +If the header contains any characters that are outside of the US-ASCII range +however, they will be encoded, just like they are for text headers. This is +nothing to be concerned about since mail clients will decode them back. +Likewise, if the parameters contain any non-ascii characters they will be +encoded so that they can be transmitted safely:: + + $attachment = new Swift_Attachment(); + $disp = $attachment->getHeaders()->get('Content-Disposition'); + $disp->setValue('attachment'); + $disp->setParameter('filename', 'report–may.pdf'); + echo $disp->toString(); + + /* + + Content-Disposition: attachment; filename*=utf-8''report%E2%80%93may.pdf + + */ + +Date Headers +~~~~~~~~~~~~ + +Date headers contains an RFC 2822 formatted date (i.e. what PHP's ``date('r')`` +returns). They are used anywhere a date or time is needed to be presented as a +message header. + +The data on which a date header is modeled as a DateTimeImmutable object. The +object is used to create a correctly structured RFC 2822 formatted date with +timezone such as ``Tue, 17 Feb 2009 22:26:31 +1100``. + +The obvious place this header type is used is in the ``Date:`` header of the +message itself. + +It's easy to add a new date header to a HeaderSet. You do this by calling the +HeaderSet's ``addDateHeader()`` method:: + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addDateHeader('Your-Header', new DateTimeImmutable('3 days ago')); + +Changing the value of an existing date header is done by calling it's +``setDateTime()`` method:: + + $date = $message->getHeaders()->get('Date'); + $date->setDateTime(new DateTimeImmutable()); + +When output via ``toString()``, a date header produces something like the +following:: + + $date = $message->getHeaders()->get('Date'); + echo $date->toString(); + + /* + + Date: Wed, 18 Feb 2009 13:35:02 +1100 + + */ + +Mailbox (e-mail address) Headers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Mailbox headers contain one or more email addresses, possibly with personalized +names attached to them. The data on which they are modeled is represented by an +associative array of email addresses and names. + +Mailbox headers are probably the most complex header type to understand in +Swift Mailer because they accept their input as an array which can take various +forms, as described in the previous chapter. + +All of the headers that contain e-mail addresses in a message -- with the +exception of ``Return-Path:`` which has a stricter syntax -- use this header +type. That is, ``To:``, ``From:`` etc. + +You add a new mailbox header to a HeaderSet by calling the HeaderSet's +``addMailboxHeader()`` method:: + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addMailboxHeader('Your-Header-Name', [ + 'person1@example.org' => 'Person Name One', + 'person2@example.org', + 'person3@example.org', + 'person4@example.org' => 'Another named person' + ]); + +Changing the value of an existing mailbox header is done by calling it's +``setNameAddresses()`` method:: + + $to = $message->getHeaders()->get('To'); + $to->setNameAddresses([ + 'joe@example.org' => 'Joe Bloggs', + 'john@example.org' => 'John Doe', + 'no-name@example.org' + ]); + +If you don't wish to concern yourself with the complicated accepted input +formats accepted by ``setNameAddresses()`` as described in the previous chapter +and you only want to set one or more addresses (not names) then you can just +use the ``setAddresses()`` method instead:: + + $to = $message->getHeaders()->get('To'); + $to->setAddresses([ + 'joe@example.org', + 'john@example.org', + 'no-name@example.org' + ]); + +.. note:: + + Both methods will accept the above input format in practice. + +If all you want to do is set a single address in the header, you can use a +string as the input parameter to ``setAddresses()`` and/or +``setNameAddresses()``:: + + $to = $message->getHeaders()->get('To'); + $to->setAddresses('joe-bloggs@example.org'); + +When output via ``toString()``, a mailbox header produces something like the +following:: + + $to = $message->getHeaders()->get('To'); + $to->setNameAddresses([ + 'person1@example.org' => 'Name of Person', + 'person2@example.org', + 'person3@example.org' => 'Another Person' + ]); + + echo $to->toString(); + + /* + + To: Name of Person <person1@example.org>, person2@example.org, Another Person + <person3@example.org> + + */ + +Internationalized domains are automatically converted to IDN encoding:: + + $to = $message->getHeaders()->get('To'); + $to->setAddresses('joe@ëxämple.org'); + + echo $to->toString(); + + /* + + To: joe@xn--xmple-gra1c.org + + */ + +ID Headers +~~~~~~~~~~ + +ID headers contain identifiers for the entity (or the message). The most +notable ID header is the Message-ID header on the message itself. + +An ID that exists inside an ID header looks more-or-less less like an email +address. For example, ``<1234955437.499becad62ec2@example.org>``. The part to +the left of the @ sign is usually unique, based on the current time and some +random factor. The part on the right is usually a domain name. + +Any ID passed to the header's ``setId()`` method absolutely MUST conform to +this structure, otherwise you'll get an Exception thrown at you by Swift Mailer +(a ``Swift_RfcComplianceException``). This is to ensure that the generated +email complies with relevant RFC documents and therefore is less likely to be +blocked as spam. + +It's easy to add a new ID header to a HeaderSet. You do this by calling the +HeaderSet's ``addIdHeader()`` method:: + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addIdHeader('Your-Header-Name', '123456.unqiue@example.org'); + +Changing the value of an existing ID header is done by calling its ``setId()`` +method:: + + $msgId = $message->getHeaders()->get('Message-ID'); + $msgId->setId(time() . '.' . uniqid('thing') . '@example.org'); + +When output via ``toString()``, an ID header produces something like the +following:: + + $msgId = $message->getHeaders()->get('Message-ID'); + echo $msgId->toString(); + + /* + + Message-ID: <1234955437.499becad62ec2@example.org> + + */ + +Path Headers +~~~~~~~~~~~~ + +Path headers are like very-restricted mailbox headers. They contain a single +email address with no associated name. The Return-Path header of a message is a +path header. + +You add a new path header to a HeaderSet by calling the HeaderSet's +``addPathHeader()`` method:: + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addPathHeader('Your-Header-Name', 'person@example.org'); + +Changing the value of an existing path header is done by calling its +``setAddress()`` method:: + + $return = $message->getHeaders()->get('Return-Path'); + $return->setAddress('my-address@example.org'); + +When output via ``toString()``, a path header produces something like the +following:: + + $return = $message->getHeaders()->get('Return-Path'); + $return->setAddress('person@example.org'); + echo $return->toString(); + + /* + + Return-Path: <person@example.org> + + */ + +Header Operations +----------------- + +Working with the headers in a message involves knowing how to use the methods +on the HeaderSet and on the individual Headers within the HeaderSet. + +Adding new Headers +~~~~~~~~~~~~~~~~~~ + +New headers can be added to the HeaderSet by using one of the provided +``add..Header()`` methods. + +The added header will appear in the message when it is sent:: + + // Adding a custom header to a message + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addTextHeader('X-Mine', 'something here'); + + // Adding a custom header to an attachment + $attachment = Swift_Attachment::fromPath('/path/to/doc.pdf'); + $attachment->getHeaders()->addDateHeader('X-Created-Time', time()); + +Retrieving Headers +~~~~~~~~~~~~~~~~~~ + +Headers are retrieved through the HeaderSet's ``get()`` and ``getAll()`` +methods:: + + $headers = $message->getHeaders(); + + // Get the To: header + $toHeader = $headers->get('To'); + + // Get all headers named "X-Foo" + $fooHeaders = $headers->getAll('X-Foo'); + + // Get the second header named "X-Foo" + $foo = $headers->get('X-Foo', 1); + + // Get all headers that are present + $all = $headers->getAll(); + +When using ``get()`` a single header is returned that matches the name (case +insensitive) that is passed to it. When using ``getAll()`` with a header name, +an array of headers with that name are returned. Calling ``getAll()`` with no +arguments returns an array of all headers present in the entity. + +.. note:: + + It's valid for some headers to appear more than once in a message (e.g. + the Received header). For this reason ``getAll()`` exists to fetch all + headers with a specified name. In addition, ``get()`` accepts an optional + numerical index, starting from zero to specify which header you want more + specifically. + +.. note:: + + If you want to modify the contents of the header and you don't know for + sure what type of header it is then you may need to check the type by + calling its ``getFieldType()`` method. + +Check if a Header Exists +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can check if a named header is present in a HeaderSet by calling its +``has()`` method:: + + $headers = $message->getHeaders(); + + // Check if the To: header exists + if ($headers->has('To')) { + echo 'To: exists'; + } + + // Check if an X-Foo header exists twice (i.e. check for the 2nd one) + if ($headers->has('X-Foo', 1)) { + echo 'Second X-Foo header exists'; + } + +If the header exists, ``true`` will be returned or ``false`` if not. + +.. note:: + + It's valid for some headers to appear more than once in a message (e.g. + the Received header). For this reason ``has()`` accepts an optional + numerical index, starting from zero to specify which header you want to + check more specifically. + +Removing Headers +~~~~~~~~~~~~~~~~ + +Removing a Header from the HeaderSet is done by calling the HeaderSet's +``remove()`` or ``removeAll()`` methods:: + + $headers = $message->getHeaders(); + + // Remove the Subject: header + $headers->remove('Subject'); + + // Remove all X-Foo headers + $headers->removeAll('X-Foo'); + + // Remove only the second X-Foo header + $headers->remove('X-Foo', 1); + +When calling ``remove()`` a single header will be removed. When calling +``removeAll()`` all headers with the given name will be removed. If no headers +exist with the given name, no errors will occur. + +.. note:: + + It's valid for some headers to appear more than once in a message (e.g. + the Received header). For this reason ``remove()`` accepts an optional + numerical index, starting from zero to specify which header you want to + check more specifically. For the same reason, ``removeAll()`` exists to + remove all headers that have the given name. + +Modifying a Header's Content +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To change a Header's content you should know what type of header it is and then +call it's appropriate setter method. All headers also have a +``setFieldBodyModel()`` method that accepts a mixed parameter and delegates to +the correct setter:: + +The header will be updated inside the HeaderSet and the changes will be seen +when the message is sent:: + + $headers = $message->getHeaders(); + + // Change the Subject: header + $subj = $headers->get('Subject'); + $subj->setValue('new subject here'); + + // Change the To: header + $to = $headers->get('To'); + $to->setNameAddresses([ + 'person@example.org' => 'Person', + 'thing@example.org' + ]); + + // Using the setFieldBodyModel() just delegates to the correct method + // So here to calls setNameAddresses() + $to->setFieldBodyModel([ + 'person@example.org' => 'Person', + 'thing@example.org' + ]); diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/index.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/index.rst new file mode 100644 index 0000000..5d92889 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/index.rst @@ -0,0 +1,12 @@ +Swiftmailer +=========== + +.. toctree:: + :maxdepth: 2 + + introduction + messages + headers + sending + plugins + japanese diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/introduction.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/introduction.rst new file mode 100644 index 0000000..8a47ef1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/introduction.rst @@ -0,0 +1,67 @@ +Swiftmailer: A feature-rich PHP Mailer +====================================== + +Swift Mailer is a component based library for sending e-mails from PHP applications. + +**Swiftmailer will stop being maintained at the end of November 2021.** + +Please, move to `Symfony Mailer <https://symfony.com/doc/current/mailer.html>`_ at your earliest convenience. +`Symfony Mailer <https://symfony.com/doc/current/mailer.html>`_ is the next evolution of Swiftmailer. +It provides the same features with support for modern PHP code and support for third-party providers. + +System Requirements +------------------- + +Swift Mailer requires PHP 7.0 or higher (``proc_*`` functions must be +available). + +Swift Mailer does not work when used with function overloading as implemented +by ``mbstring`` when ``mbstring.func_overload`` is set to ``2``. + +Installation +------------ + +The recommended way to install Swiftmailer is via Composer: + +.. code-block:: bash + + $ composer require "swiftmailer/swiftmailer:^6.0" + +Basic Usage +----------- + +Here is the simplest way to send emails with Swift Mailer:: + + require_once '/path/to/vendor/autoload.php'; + + // Create the Transport + $transport = (new Swift_SmtpTransport('smtp.example.org', 25)) + ->setUsername('your username') + ->setPassword('your password') + ; + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + + // Create a message + $message = (new Swift_Message('Wonderful Subject')) + ->setFrom(['john@doe.com' => 'John Doe']) + ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name']) + ->setBody('Here is the message itself') + ; + + // Send the message + $result = $mailer->send($message); + +You can also use Sendmail as a transport:: + + // Sendmail + $transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs'); + +Getting Help +------------ + +For general support, use `Stack Overflow <https://stackoverflow.com>`_. + +For bug reports and feature requests, create a new ticket in `GitHub +<https://github.com/swiftmailer/swiftmailer/issues>`_. diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/japanese.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/japanese.rst new file mode 100644 index 0000000..5454821 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/japanese.rst @@ -0,0 +1,19 @@ +Using Swift Mailer for Japanese Emails +====================================== + +To send emails in Japanese, you need to tweak the default configuration. + +Call the ``Swift::init()`` method with the following code as early as possible +in your code:: + + Swift::init(function () { + Swift_DependencyContainer::getInstance() + ->register('mime.qpheaderencoder') + ->asAliasOf('mime.base64headerencoder'); + + Swift_Preferences::getInstance()->setCharset('iso-2022-jp'); + }); + + /* rest of code goes here */ + +That's all! diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/messages.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/messages.rst new file mode 100644 index 0000000..e03859d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/messages.rst @@ -0,0 +1,949 @@ +Creating Messages +================= + +Creating messages in Swift Mailer is done by making use of the various MIME +entities provided with the library. Complex messages can be quickly created +with very little effort. + +Quick Reference +--------------- + +You can think of creating a Message as being similar to the steps you perform +when you click the Compose button in your mail client. You give it a subject, +specify some recipients, add any attachments and write your message:: + + // Create the message + $message = (new Swift_Message()) + + // Give the message a subject + ->setSubject('Your subject') + + // Set the From address with an associative array + ->setFrom(['john@doe.com' => 'John Doe']) + + // Set the To addresses with an associative array (setTo/setCc/setBcc) + ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name']) + + // Give it a body + ->setBody('Here is the message itself') + + // And optionally an alternative body + ->addPart('<q>Here is the message itself</q>', 'text/html') + + // Optionally add any attachments + ->attach(Swift_Attachment::fromPath('my-document.pdf')) + ; + +Message Basics +-------------- + +A message is a container for anything you want to send to somebody else. There +are several basic aspects of a message that you should know. + +An e-mail message is made up of several relatively simple entities that are +combined in different ways to achieve different results. All of these entities +have the same fundamental outline but serve a different purpose. The Message +itself can be defined as a MIME entity, an Attachment is a MIME entity, all +MIME parts are MIME entities -- and so on! + +The basic units of each MIME entity -- be it the Message itself, or an +Attachment -- are its Headers and its body: + +.. code-block:: text + + Header-Name: A header value + Other-Header: Another value + + The body content itself + +The Headers of a MIME entity, and its body must conform to some strict +standards defined by various RFC documents. Swift Mailer ensures that these +specifications are followed by using various types of object, including +Encoders and different Header types to generate the entity. + +The Structure of a Message +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Of all of the MIME entities, a message -- ``Swift_Message`` is the largest and +most complex. It has many properties that can be updated and it can contain +other MIME entities -- attachments for example -- nested inside it. + +A Message has a lot of different Headers which are there to present information +about the message to the recipients' mail client. Most of these headers will be +familiar to the majority of users, but we'll list the basic ones. Although it's +possible to work directly with the Headers of a Message (or other MIME entity), +the standard Headers have accessor methods provided to abstract away the +complex details for you. For example, although the Date on a message is written +with a strict format, you only need to pass a DateTimeInterface instance to +``setDate()``. + ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| Header | Description | Accessors | ++===============================+====================================================================================================================================+=============================================+ +| ``Message-ID`` | Identifies this message with a unique ID, usually containing the domain name and time generated | ``getId()`` / ``setId()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Return-Path`` | Specifies where bounces should go (Swift Mailer reads this for other uses) | ``getReturnPath()`` / ``setReturnPath()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``From`` | Specifies the address of the person who the message is from. This can be multiple addresses if multiple people wrote the message. | ``getFrom()`` / ``setFrom()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Sender`` | Specifies the address of the person who physically sent the message (higher precedence than ``From:``) | ``getSender()`` / ``setSender()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``To`` | Specifies the addresses of the intended recipients | ``getTo()`` / ``setTo()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Cc`` | Specifies the addresses of recipients who will be copied in on the message | ``getCc()`` / ``setCc()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Bcc`` | Specifies the addresses of recipients who the message will be blind-copied to. Other recipients will not be aware of these copies. | ``getBcc()`` / ``setBcc()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Reply-To`` | Specifies the address where replies are sent to | ``getReplyTo()`` / ``setReplyTo()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Subject`` | Specifies the subject line that is displayed in the recipients' mail client | ``getSubject()`` / ``setSubject()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Date`` | Specifies the date at which the message was sent | ``getDate()`` / ``setDate()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Content-Type`` | Specifies the format of the message (usually ``text/plain`` or ``text/html``) | ``getContentType()`` / ``setContentType()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Content-Transfer-Encoding`` | Specifies the encoding scheme in the message | ``getEncoder()`` / ``setEncoder()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ + +Working with a Message Object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Although there are a lot of available methods on a message object, you only +need to make use of a small subset of them. Usually you'll use +``setSubject()``, ``setTo()`` and ``setFrom()`` before setting the body of your +message with ``setBody()``:: + + $message = new Swift_Message(); + $message->setSubject('My subject'); + +All MIME entities (including a message) have a ``toString()`` method that you +can call if you want to take a look at what is going to be sent. For example, +if you ``echo $message->toString();`` you would see something like this: + +.. code-block:: text + + Message-ID: <1230173678.4952f5eeb1432@swift.generated> + Date: Thu, 25 Dec 2008 13:54:38 +1100 + Subject: Example subject + From: Chris Corbyn <chris@w3style.co.uk> + To: Receiver Name <recipient@example.org> + MIME-Version: 1.0 + Content-Type: text/plain; charset=utf-8 + Content-Transfer-Encoding: quoted-printable + + Here is the message + +We'll take a closer look at the methods you use to create your message in the +following sections. + +Adding Content to Your Message +------------------------------ + +Rich content can be added to messages in Swift Mailer with relative ease by +calling methods such as ``setSubject()``, ``setBody()``, ``addPart()`` and +``attach()``. + +Setting the Subject Line +~~~~~~~~~~~~~~~~~~~~~~~~ + +The subject line, displayed in the recipients' mail client can be set with the +``setSubject()`` method, or as a parameter to ``new Swift_Message()``:: + + // Pass it as a parameter when you create the message + $message = new Swift_Message('My amazing subject'); + + // Or set it after like this + $message->setSubject('My amazing subject'); + +Setting the Body Content +~~~~~~~~~~~~~~~~~~~~~~~~ + +The body of the message -- seen when the user opens the message -- is specified +by calling the ``setBody()`` method. If an alternative body is to be included, +``addPart()`` can be used. + +The body of a message is the main part that is read by the user. Often people +want to send a message in HTML format (``text/html``), other times people want +to send in plain text (``text/plain``), or sometimes people want to send both +versions and allow the recipient to choose how they view the message. + +As a rule of thumb, if you're going to send a HTML email, always include a +plain-text equivalent of the same content so that users who prefer to read +plain text can do so. + +If the recipient's mail client offers preferences for displaying text vs. HTML +then the mail client will present that part to the user where available. In +other cases the mail client will display the "best" part it can - usually HTML +if you've included HTML:: + + // Pass it as a parameter when you create the message + $message = new Swift_Message('Subject here', 'My amazing body'); + + // Or set it after like this + $message->setBody('My <em>amazing</em> body', 'text/html'); + + // Add alternative parts with addPart() + $message->addPart('My amazing body in plain text', 'text/plain'); + +Attaching Files +--------------- + +Attachments are downloadable parts of a message and can be added by calling the +``attach()`` method on the message. You can add attachments that exist on disk, +or you can create attachments on-the-fly. + +Although we refer to files sent over e-mails as "attachments" -- because +they're attached to the message -- lots of other parts of the message are +actually "attached" even if we don't refer to these parts as attachments. + +File attachments are created by the ``Swift_Attachment`` class and then +attached to the message via the ``attach()`` method on it. For all of the +"every day" MIME types such as all image formats, word documents, PDFs and +spreadsheets you don't need to explicitly set the content-type of the +attachment, though it would do no harm to do so. For less common formats you +should set the content-type -- which we'll cover in a moment. + +Attaching Existing Files +~~~~~~~~~~~~~~~~~~~~~~~~ + +Files that already exist, either on disk or at a URL can be attached to a +message with just one line of code, using ``Swift_Attachment::fromPath()``. + +You can attach files that exist locally, or if your PHP installation has +``allow_url_fopen`` turned on you can attach files from other +websites. + +The attachment will be presented to the recipient as a downloadable file with +the same filename as the one you attached:: + + // Create the attachment + // * Note that you can technically leave the content-type parameter out + $attachment = Swift_Attachment::fromPath('/path/to/image.jpg', 'image/jpeg'); + + // Attach it to the message + $message->attach($attachment); + + // The two statements above could be written in one line instead + $message->attach(Swift_Attachment::fromPath('/path/to/image.jpg')); + + // You can attach files from a URL if allow_url_fopen is on in php.ini + $message->attach(Swift_Attachment::fromPath('http://site.tld/logo.png')); + +Setting the Filename +~~~~~~~~~~~~~~~~~~~~ + +Usually you don't need to explicitly set the filename of an attachment because +the name of the attached file will be used by default, but if you want to set +the filename you use the ``setFilename()`` method of the Attachment. + +The attachment will be attached in the normal way, but meta-data sent inside +the email will rename the file to something else:: + + // Create the attachment and call its setFilename() method + $attachment = Swift_Attachment::fromPath('/path/to/image.jpg') + ->setFilename('cool.jpg'); + + // Because there's a fluid interface, you can do this in one statement + $message->attach( + Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('cool.jpg') + ); + +Attaching Dynamic Content +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Files that are generated at runtime, such as PDF documents or images created +via GD can be attached directly to a message without writing them out to disk. +Use ``Swift_Attachment`` directly. + +The attachment will be presented to the recipient as a downloadable file +with the filename and content-type you specify:: + + // Create your file contents in the normal way, but don't write them to disk + $data = create_my_pdf_data(); + + // Create the attachment with your data + $attachment = new Swift_Attachment($data, 'my-file.pdf', 'application/pdf'); + + // Attach it to the message + $message->attach($attachment); + + + // You can alternatively use method chaining to build the attachment + $attachment = (new Swift_Attachment()) + ->setFilename('my-file.pdf') + ->setContentType('application/pdf') + ->setBody($data) + ; + +.. note:: + + If you would usually write the file to disk anyway you should just attach + it with ``Swift_Attachment::fromPath()`` since this will use less memory. + +Changing the Disposition +~~~~~~~~~~~~~~~~~~~~~~~~ + +Attachments just appear as files that can be saved to the Desktop if desired. +You can make attachment appear inline where possible by using the +``setDisposition()`` method of an attachment. + +The attachment will be displayed within the email viewing window if the mail +client knows how to display it:: + + // Create the attachment and call its setDisposition() method + $attachment = Swift_Attachment::fromPath('/path/to/image.jpg') + ->setDisposition('inline'); + + + // Because there's a fluid interface, you can do this in one statement + $message->attach( + Swift_Attachment::fromPath('/path/to/image.jpg')->setDisposition('inline') + ); + +.. note:: + + If you try to create an inline attachment for a non-displayable file type + such as a ZIP file, the mail client should just present the attachment as + normal. + +Embedding Inline Media Files +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Often, people want to include an image or other content inline with a HTML +message. It's easy to do this with HTML linking to remote resources, but this +approach is usually blocked by mail clients. Swift Mailer allows you to embed +your media directly into the message. + +Mail clients usually block downloads from remote resources because this +technique was often abused as a mean of tracking who opened an email. If +you're sending a HTML email and you want to include an image in the message +another approach you can take is to embed the image directly. + +Swift Mailer makes embedding files into messages extremely streamlined. You +embed a file by calling the ``embed()`` method of the message, +which returns a value you can use in a ``src`` or +``href`` attribute in your HTML. + +Just like with attachments, it's possible to embed dynamically generated +content without having an existing file available. + +The embedded files are sent in the email as a special type of attachment that +has a unique ID used to reference them within your HTML attributes. On mail +clients that do not support embedded files they may appear as attachments. + +Although this is commonly done for images, in theory it will work for any +displayable (or playable) media type. Support for other media types (such as +video) is dependent on the mail client however. + +Embedding Existing Files +........................ + +Files that already exist, either on disk or at a URL can be embedded in a +message with just one line of code, using ``Swift_EmbeddedFile::fromPath()``. + +You can embed files that exist locally, or if your PHP installation has +``allow_url_fopen`` turned on you can embed files from other websites. + +The file will be displayed with the message inline with the HTML wherever its ID +is used as a ``src`` attribute:: + + // Create the message + $message = new Swift_Message('My subject'); + + // Set the body + $message->setBody( + '<html>' . + ' <body>' . + ' Here is an image <img src="' . // Embed the file + $message->embed(Swift_Image::fromPath('image.png')) . + '" alt="Image" />' . + ' Rest of message' . + ' </body>' . + '</html>', + 'text/html' // Mark the content-type as HTML + ); + + // You can embed files from a URL if allow_url_fopen is on in php.ini + $message->setBody( + '<html>' . + ' <body>' . + ' Here is an image <img src="' . + $message->embed(Swift_Image::fromPath('http://site.tld/logo.png')) . + '" alt="Image" />' . + ' Rest of message' . + ' </body>' . + '</html>', + 'text/html' + ); + +.. note:: + + ``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one another. + ``Swift_Image`` exists for semantic purposes. + +.. note:: + + You can embed files in two stages if you prefer. Just capture the return + value of ``embed()`` in a variable and use that as the ``src`` attribute:: + + // If placing the embed() code inline becomes cumbersome + // it's easy to do this in two steps + $cid = $message->embed(Swift_Image::fromPath('image.png')); + + $message->setBody( + '<html>' . + ' <body>' . + ' Here is an image <img src="' . $cid . '" alt="Image" />' . + ' Rest of message' . + ' </body>' . + '</html>', + 'text/html' // Mark the content-type as HTML + ); + +Embedding Dynamic Content +......................... + +Images that are generated at runtime, such as images created via GD can be +embedded directly to a message without writing them out to disk. Use the +standard ``new Swift_Image()`` method. + +The file will be displayed with the message inline with the HTML wherever its ID +is used as a ``src`` attribute:: + + // Create your file contents in the normal way, but don't write them to disk + $img_data = create_my_image_data(); + + // Create the message + $message = new Swift_Message('My subject'); + + // Set the body + $message->setBody( + '<html>' . + ' <body>' . + ' Here is an image <img src="' . // Embed the file + $message->embed(new Swift_Image($img_data, 'image.jpg', 'image/jpeg')) . + '" alt="Image" />' . + ' Rest of message' . + ' </body>' . + '</html>', + 'text/html' // Mark the content-type as HTML + ); + +.. note:: + + ``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one another. + ``Swift_Image`` exists for semantic purposes. + +.. note:: + + You can embed files in two stages if you prefer. Just capture the return + value of ``embed()`` in a variable and use that as the ``src`` attribute:: + + // If placing the embed() code inline becomes cumbersome + // it's easy to do this in two steps + $cid = $message->embed(new Swift_Image($img_data, 'image.jpg', 'image/jpeg')); + + $message->setBody( + '<html>' . + ' <body>' . + ' Here is an image <img src="' . $cid . '" alt="Image" />' . + ' Rest of message' . + ' </body>' . + '</html>', + 'text/html' // Mark the content-type as HTML + ); + +Adding Recipients to Your Message +--------------------------------- + +Recipients are specified within the message itself via ``setTo()``, ``setCc()`` +and ``setBcc()``. Swift Mailer reads these recipients from the message when it +gets sent so that it knows where to send the message to. + +Message recipients are one of three types: + +* ``To:`` recipients -- the primary recipients (required) + +* ``Cc:`` recipients -- receive a copy of the message (optional) + +* ``Bcc:`` recipients -- hidden from other recipients (optional) + +Each type can contain one, or several addresses. It's possible to list only the +addresses of the recipients, or you can personalize the address by providing +the real name of the recipient. + +Make sure to add only valid email addresses as recipients. If you try to add an +invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift +Mailer will throw a ``Swift_RfcComplianceException``. + +If you add recipients automatically based on a data source that may contain +invalid email addresses, you can prevent possible exceptions by validating the +addresses using:: + + use Egulias\EmailValidator\EmailValidator; + use Egulias\EmailValidator\Validation\RFCValidation; + + $validator = new EmailValidator(); + $validator->isValid("example@example.com", new RFCValidation()); //true + +and only adding addresses that validate. Another way would be to wrap your ``setTo()``, ``setCc()`` and +``setBcc()`` calls in a try-catch block and handle the +``Swift_RfcComplianceException`` in the catch block. + +.. sidebar:: Syntax for Addresses + + If you only wish to refer to a single email address (for example your + ``From:`` address) then you can just use a string:: + + $message->setFrom('some@address.tld'); + + If you want to include a name then you must use an associative array:: + + $message->setFrom(['some@address.tld' => 'The Name']); + + If you want to include multiple addresses then you must use an array:: + + $message->setTo(['some@address.tld', 'other@address.tld']); + + You can mix personalized (addresses with a name) and non-personalized + addresses in the same list by mixing the use of associative and + non-associative array syntax:: + + $message->setTo([ + 'recipient-with-name@example.org' => 'Recipient Name One', + 'no-name@example.org', // Note that this is not a key-value pair + 'named-recipient@example.org' => 'Recipient Name Two' + ]); + +Setting ``To:`` Recipients +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``To:`` recipients are required in a message and are set with the ``setTo()`` +or ``addTo()`` methods of the message. + +To set ``To:`` recipients, create the message object using either ``new +Swift_Message( ... )``, then call the ``setTo()`` method with a complete array +of addresses, or use the ``addTo()`` method to iteratively add recipients. + +The ``setTo()`` method accepts input in various formats as described earlier in +this chapter. The ``addTo()`` method takes either one or two parameters. The +first being the email address and the second optional parameter being the name +of the recipient. + +``To:`` recipients are visible in the message headers and will be seen by the +other recipients:: + + // Using setTo() to set all recipients in one go + $message->setTo([ + 'person1@example.org', + 'person2@otherdomain.org' => 'Person 2 Name', + 'person3@example.org', + 'person4@example.org', + 'person5@example.org' => 'Person 5 Name' + ]); + +.. note:: + + Multiple calls to ``setTo()`` will not add new recipients -- each + call overrides the previous calls. If you want to iteratively add + recipients, use the ``addTo()`` method:: + + // Using addTo() to add recipients iteratively + $message->addTo('person1@example.org'); + $message->addTo('person2@example.org', 'Person 2 Name'); + +Setting ``Cc:`` Recipients +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Cc:`` recipients are set with the ``setCc()`` or ``addCc()`` methods of the +message. + +To set ``Cc:`` recipients, create the message object using either ``new +Swift_Message( ... )``, then call the ``setCc()`` method with a complete array +of addresses, or use the ``addCc()`` method to iteratively add recipients. + +The ``setCc()`` method accepts input in various formats as described earlier in +this chapter. The ``addCc()`` method takes either one or two parameters. The +first being the email address and the second optional parameter being the name +of the recipient. + +``Cc:`` recipients are visible in the message headers and will be seen by the +other recipients:: + + // Using setTo() to set all recipients in one go + $message->setTo([ + 'person1@example.org', + 'person2@otherdomain.org' => 'Person 2 Name', + 'person3@example.org', + 'person4@example.org', + 'person5@example.org' => 'Person 5 Name' + ]); + +.. note:: + + Multiple calls to ``setCc()`` will not add new recipients -- each call + overrides the previous calls. If you want to iteratively add Cc: + recipients, use the ``addCc()`` method:: + + // Using addCc() to add recipients iteratively + $message->addCc('person1@example.org'); + $message->addCc('person2@example.org', 'Person 2 Name'); + +Setting ``Bcc:`` Recipients +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Bcc:`` recipients receive a copy of the message without anybody else knowing +it, and are set with the ``setBcc()`` or ``addBcc()`` methods of the message. + +To set ``Bcc:`` recipients, create the message object using either ``new +Swift_Message( ... )``, then call the ``setBcc()`` method with a complete array +of addresses, or use the ``addBcc()`` method to iteratively add recipients. + +The ``setBcc()`` method accepts input in various formats as described earlier +in this chapter. The ``addBcc()`` method takes either one or two parameters. +The first being the email address and the second optional parameter being the +name of the recipient. + +Only the individual ``Bcc:`` recipient will see their address in the message +headers. Other recipients (including other ``Bcc:`` recipients) will not see +the address:: + + // Using setBcc() to set all recipients in one go + $message->setBcc([ + 'person1@example.org', + 'person2@otherdomain.org' => 'Person 2 Name', + 'person3@example.org', + 'person4@example.org', + 'person5@example.org' => 'Person 5 Name' + ]); + +.. note:: + + Multiple calls to ``setBcc()`` will not add new recipients -- each call + overrides the previous calls. If you want to iteratively add Bcc: + recipients, use the ``addBcc()`` method:: + + // Using addBcc() to add recipients iteratively + $message->addBcc('person1@example.org'); + $message->addBcc('person2@example.org', 'Person 2 Name'); + +.. sidebar:: Internationalized Email Addresses + + Traditionally only ASCII characters have been allowed in email addresses. + With the introduction of internationalized domain names (IDNs), non-ASCII + characters may appear in the domain name. By default, Swiftmailer encodes + such domain names in Punycode (e.g. xn--xample-ova.invalid). This is + compatible with all mail servers. + + RFC 6531 introduced an SMTP extension, SMTPUTF8, that allows non-ASCII + characters in email addresses on both sides of the @ sign. To send to such + addresses, your outbound SMTP server must support the SMTPUTF8 extension. + You should use the ``Swift_AddressEncoder_Utf8AddressEncoder`` address + encoder and enable the ``Swift_Transport_Esmtp_SmtpUtf8Handler`` SMTP + extension handler:: + + $smtpUtf8 = new Swift_Transport_Esmtp_SmtpUtf8Handler(); + $transport->setExtensionHandlers([$smtpUtf8]); + $utf8Encoder = new Swift_AddressEncoder_Utf8AddressEncoder(); + $transport->setAddressEncoder($utf8Encoder); + +Specifying Sender Details +------------------------- + +An email must include information about who sent it. Usually this is managed by +the ``From:`` address, however there are other options. + +The sender information is contained in three possible places: + +* ``From:`` -- the address(es) of who wrote the message (required) + +* ``Sender:`` -- the address of the single person who sent the message + (optional) + +* ``Return-Path:`` -- the address where bounces should go to (optional) + +You must always include a ``From:`` address by using ``setFrom()`` on the +message. Swift Mailer will use this as the default ``Return-Path:`` unless +otherwise specified. + +The ``Sender:`` address exists because the person who actually sent the email +may not be the person who wrote the email. It has a higher precedence than the +``From:`` address and will be used as the ``Return-Path:`` unless otherwise +specified. + +Setting the ``From:`` Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``From:`` address is required and is set with the ``setFrom()`` method of the +message. ``From:`` addresses specify who actually wrote the email, and usually +who sent it. + +What most people probably don't realize is that you can have more than one +``From:`` address if more than one person wrote the email -- for example if an +email was put together by a committee. + +The ``From:`` address(es) are visible in the message headers and will be seen +by the recipients. + +.. note:: + + If you set multiple ``From:`` addresses then you absolutely must set a + ``Sender:`` address to indicate who physically sent the message. + +:: + + // Set a single From: address + $message->setFrom('your@address.tld'); + + // Set a From: address including a name + $message->setFrom(['your@address.tld' => 'Your Name']); + + // Set multiple From: addresses if multiple people wrote the email + $message->setFrom([ + 'person1@example.org' => 'Sender One', + 'person2@example.org' => 'Sender Two' + ]); + +Setting the ``Sender:`` Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``Sender:`` address specifies who sent the message and is set with the +``setSender()`` method of the message. + +The ``Sender:`` address is visible in the message headers and will be seen by +the recipients. + +This address will be used as the ``Return-Path:`` unless otherwise specified. + +.. note:: + + If you set multiple ``From:`` addresses then you absolutely must set a + ``Sender:`` address to indicate who physically sent the message. + +You must not set more than one sender address on a message because it's not +possible for more than one person to send a single message:: + + $message->setSender('your@address.tld'); + +Setting the ``Return-Path:`` (Bounce) Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``Return-Path:`` address specifies where bounce notifications should be +sent and is set with the ``setReturnPath()`` method of the message. + +You can only have one ``Return-Path:`` and it must not include a personal name. + +Bounce notifications will be sent to this address:: + + $message->setReturnPath('bounces@address.tld'); + +Signed/Encrypted Message +------------------------ + +To increase the integrity/security of a message it is possible to sign and/or +encrypt an message using one or multiple signers. + +S/MIME +~~~~~~ + +S/MIME can sign and/or encrypt a message using the OpenSSL extension. + +When signing a message, the signer creates a signature of the entire content of +the message (including attachments). + +The certificate and private key must be PEM encoded, and can be either created +using for example OpenSSL or obtained at an official Certificate Authority (CA). + +**The recipient must have the CA certificate in the list of trusted issuers in +order to verify the signature.** + +**Make sure the certificate supports emailProtection.** + +When using OpenSSL this can done by the including the *-addtrust +emailProtection* parameter when creating the certificate:: + + $message = new Swift_Message(); + + $smimeSigner = new Swift_Signers_SMimeSigner(); + $smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem'); + $message->attachSigner($smimeSigner); + +When the private key is secured using a passphrase use the following instead:: + + $message = new Swift_Message(); + + $smimeSigner = new Swift_Signers_SMimeSigner(); + $smimeSigner->setSignCertificate('/path/to/certificate.pem', ['/path/to/private-key.pem', 'passphrase']); + $message->attachSigner($smimeSigner); + +By default the signature is added as attachment, making the message still +readable for mailing agents not supporting signed messages. + +Storing the message as binary is also possible but not recommended:: + + $smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem', PKCS7_BINARY); + +When encrypting the message (also known as enveloping), the entire message +(including attachments) is encrypted using a certificate, and the recipient can +then decrypt the message using corresponding private key. + +Encrypting ensures nobody can read the contents of the message without the +private key. + +Normally the recipient provides a certificate for encrypting and keeping the +decryption key private. + +Using both signing and encrypting is also possible:: + + $message = new Swift_Message(); + + $smimeSigner = new Swift_Signers_SMimeSigner(); + $smimeSigner->setSignCertificate('/path/to/sign-certificate.pem', '/path/to/private-key.pem'); + $smimeSigner->setEncryptCertificate('/path/to/encrypt-certificate.pem'); + $message->attachSigner($smimeSigner); + +The used encryption cipher can be set as the second parameter of +setEncryptCertificate() + +See https://secure.php.net/manual/openssl.ciphers for a list of supported ciphers. + +By default the message is first signed and then encrypted, this can be changed +by adding:: + + $smimeSigner->setSignThenEncrypt(false); + +**Changing this is not recommended as most mail agents don't support this +none-standard way.** + +Only when having trouble with sign then encrypt method, this should be changed. + +Requesting a Read Receipt +------------------------- + +It is possible to request a read-receipt to be sent to an address when the +email is opened. To request a read receipt set the address with +``setReadReceiptTo()``:: + + $message->setReadReceiptTo('your@address.tld'); + +When the email is opened, if the mail client supports it a notification will be +sent to this address. + +.. note:: + + Read receipts won't work for the majority of recipients since many mail + clients auto-disable them. Those clients that will send a read receipt + will make the user aware that one has been requested. + +Setting the Character Set +------------------------- + +The character set of the message (and its MIME parts) is set with the +``setCharset()`` method. You can also change the global default of UTF-8 by +working with the ``Swift_Preferences`` class. + +Swift Mailer will default to the UTF-8 character set unless otherwise +overridden. UTF-8 will work in most instances since it includes all of the +standard US keyboard characters in addition to most international characters. + +It is absolutely vital however that you know what character set your message +(or it's MIME parts) are written in otherwise your message may be received +completely garbled. + +There are two places in Swift Mailer where you can change the character set: + +* In the ``Swift_Preferences`` class + +* On each individual message and/or MIME part + +To set the character set of your Message: + +* Change the global UTF-8 setting by calling + ``Swift_Preferences::setCharset()``; or + +* Call the ``setCharset()`` method on the message or the MIME part:: + + // Approach 1: Change the global setting (suggested) + Swift_Preferences::getInstance()->setCharset('iso-8859-2'); + + // Approach 2: Call the setCharset() method of the message + $message = (new Swift_Message()) + ->setCharset('iso-8859-2'); + + // Approach 3: Specify the charset when setting the body + $message->setBody('My body', 'text/html', 'iso-8859-2'); + + // Approach 4: Specify the charset for each part added + $message->addPart('My part', 'text/plain', 'iso-8859-2'); + +Setting the Encoding +-------------------- + +The body of each MIME part needs to be encoded. Binary attachments are encoded +in base64 using the ``Swift_Mime_ContentEncoder_Base64ContentEncoder``. Text +parts are traditionally encoded in quoted-printable using +``Swift_Mime_ContentEncoder_QpContentEncoder`` or +``Swift_Mime_ContentEncoder_NativeQpContentEncoder``. + +The encoder of the message or MIME part is set with the ``setEncoder()`` method. + +Quoted-printable is the safe choice, because it converts 8-bit text as 7-bit. +Most modern SMTP servers support 8-bit text. This is advertised via the 8BITMIME +SMTP extension. If your outbound SMTP server supports this SMTP extension, and +it supports downgrading the message (e.g converting to quoted-printable on the +fly) when delivering to a downstream server that does not support the extension, +you may wish to use ``Swift_Mime_ContentEncoder_PlainContentEncoder`` in +``8bit`` mode instead. This has the advantage that the source data is slightly +more readable and compact, especially for non-Western languages. + + $eightBitMime = new Swift_Transport_Esmtp_EightBitMimeHandler(); + $transport->setExtensionHandlers([$eightBitMime]); + $plainEncoder = new Swift_Mime_ContentEncoder_PlainContentEncoder('8bit'); + $message->setEncoder($plainEncoder); + +Setting the Line Length +----------------------- + +The length of lines in a message can be changed by using the +``setMaxLineLength()`` method on the message:: + + $message->setMaxLineLength(1000); + +Swift Mailer defaults to using 78 characters per line in a message. This is +done for historical reasons and so that the message can be easily viewed in +plain-text terminals + +Lines that are longer than the line length specified will be wrapped between +words. + +.. note:: + + You should never set a maximum length longer than 1000 characters + according to RFC 2822. Doing so could have unspecified side-effects such + as truncating parts of your message when it is transported between SMTP + servers. + +Setting the Message Priority +---------------------------- + +You can change the priority of the message with ``setPriority()``. Setting the +priority will not change the way your email is sent -- it is purely an +indicative setting for the recipient:: + + // Indicate "High" priority + $message->setPriority(2); + +The priority of a message is an indication to the recipient what significance +it has. Swift Mailer allows you to set the priority by calling the +``setPriority`` method. This method takes an integer value between 1 and 5: + +* ``Swift_Mime_SimpleMessage::PRIORITY_HIGHEST``: 1 +* ``Swift_Mime_SimpleMessage::PRIORITY_HIGH``: 2 +* ``Swift_Mime_SimpleMessage::PRIORITY_NORMAL``: 3 +* ``Swift_Mime_SimpleMessage::PRIORITY_LOW``: 4 +* ``Swift_Mime_SimpleMessage::PRIORITY_LOWEST``: 5 + +:: + + // Or use the constant to be more explicit + $message->setPriority(Swift_Mime_SimpleMessage::PRIORITY_HIGH); diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/plugins.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/plugins.rst new file mode 100644 index 0000000..548b07f --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/plugins.rst @@ -0,0 +1,337 @@ +Plugins +======= + +Plugins exist to extend, or modify the behaviour of Swift Mailer. They respond +to Events that are fired within the Transports during sending. + +There are a number of Plugins provided as part of the base Swift Mailer package +and they all follow a common interface to respond to Events fired within the +library. Interfaces are provided to "listen" to each type of Event fired and to +act as desired when a listened-to Event occurs. + +Although several plugins are provided with Swift Mailer out-of-the-box, the +Events system has been specifically designed to make it easy for experienced +object-oriented developers to write their own plugins in order to achieve +goals that may not be possible with the base library. + +AntiFlood Plugin +---------------- + +Many SMTP servers have limits on the number of messages that may be sent during +any single SMTP connection. The AntiFlood plugin provides a way to stay within +this limit while still managing a large number of emails. + +A typical limit for a single connection is 100 emails. If the server you +connect to imposes such a limit, it expects you to disconnect after that number +of emails has been sent. You could manage this manually within a loop, but the +AntiFlood plugin provides the necessary wrapper code so that you don't need to +worry about this logic. + +Regardless of limits imposed by the server, it's usually a good idea to be +conservative with the resources of the SMTP server. Sending will become +sluggish if the server is being over-used so using the AntiFlood plugin will +not be a bad idea even if no limits exist. + +The AntiFlood plugin's logic is basically to disconnect and the immediately +re-connect with the SMTP server every X number of emails sent, where X is a +number you specify to the plugin. + +You can also specify a time period in seconds that Swift Mailer should pause +for between the disconnect/re-connect process. It's a good idea to pause for a +short time (say 30 seconds every 100 emails) simply to give the SMTP server a +chance to process its queue and recover some resources. + +Using the AntiFlood Plugin +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The AntiFlood Plugin -- like all plugins -- is added with the Mailer class's +``registerPlugin()`` method. It takes two constructor parameters: the number of +emails to pause after, and optionally the number of seconds to pause for. + +When Swift Mailer sends messages it will count the number of messages that have +been sent since the last re-connect. Once the number hits your specified +threshold it will disconnect and re-connect, optionally pausing for a specified +amount of time:: + + // Create the Mailer using any Transport + $mailer = new Swift_Mailer( + new Swift_SmtpTransport('smtp.example.org', 25) + ); + + // Use AntiFlood to re-connect after 100 emails + $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100)); + + // And specify a time in seconds to pause for (30 secs) + $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100, 30)); + + // Continue sending as normal + for ($lotsOfRecipients as $recipient) { + ... + + $mailer->send( ... ); + } + +Throttler Plugin +---------------- + +If your SMTP server has restrictions in place to limit the rate at which you +send emails, then your code will need to be aware of this rate-limiting. The +Throttler plugin makes Swift Mailer run at a rate-limited speed. + +Many shared hosts don't open their SMTP servers as a free-for-all. Usually they +have policies in place (probably to discourage spammers) that only allow you to +send a fixed number of emails per-hour/day. + +The Throttler plugin supports two modes of rate-limiting and with each, you +will need to do that math to figure out the values you want. The plugin can +limit based on the number of emails per minute, or the number of +bytes-transferred per-minute. + +Using the Throttler Plugin +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Throttler Plugin -- like all plugins -- is added with the Mailer class' +``registerPlugin()`` method. It has two required constructor parameters that +tell it how to do its rate-limiting. + +When Swift Mailer sends messages it will keep track of the rate at which +sending messages is occurring. If it realises that sending is happening too +fast, it will cause your program to ``sleep()`` for enough time to average out +the rate:: + + // Create the Mailer using any Transport + $mailer = new Swift_Mailer( + new Swift_SmtpTransport('smtp.example.org', 25) + ); + + // Rate limit to 100 emails per-minute + $mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( + 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE + )); + + // Rate limit to 10MB per-minute + $mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( + 1024 * 1024 * 10, Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE + )); + + // Continue sending as normal + for ($lotsOfRecipients as $recipient) { + ... + + $mailer->send( ... ); + } + +Logger Plugin +------------- + +The Logger plugins helps with debugging during the process of sending. It can +help to identify why an SMTP server is rejecting addresses, or any other +hard-to-find problems that may arise. + +The Logger plugin comes in two parts. There's the plugin itself, along with one +of a number of possible Loggers that you may choose to use. For example, the +logger may output messages directly in realtime, or it may capture messages in +an array. + +One other notable feature is the way in which the Logger plugin changes +Exception messages. If Exceptions are being thrown but the error message does +not provide conclusive information as to the source of the problem (such as an +ambiguous SMTP error) the Logger plugin includes the entire SMTP transcript in +the error message so that debugging becomes a simpler task. + +There are a few available Loggers included with Swift Mailer, but writing your +own implementation is incredibly simple and is achieved by creating a short +class that implements the ``Swift_Plugins_Logger`` interface. + +* ``Swift_Plugins_Loggers_ArrayLogger``: Keeps a collection of log messages + inside an array. The array content can be cleared or dumped out to the screen. + +* ``Swift_Plugins_Loggers_EchoLogger``: Prints output to the screen in + realtime. Handy for very rudimentary debug output. + +Using the Logger Plugin +~~~~~~~~~~~~~~~~~~~~~~~ + +The Logger Plugin -- like all plugins -- is added with the Mailer class' +``registerPlugin()`` method. It accepts an instance of ``Swift_Plugins_Logger`` +in its constructor. + +When Swift Mailer sends messages it will keep a log of all the interactions +with the underlying Transport being used. Depending upon the Logger that has +been used the behaviour will differ, but all implementations offer a way to get +the contents of the log:: + + // Create the Mailer using any Transport + $mailer = new Swift_Mailer( + new Swift_SmtpTransport('smtp.example.org', 25) + ); + + // To use the ArrayLogger + $logger = new Swift_Plugins_Loggers_ArrayLogger(); + $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger)); + + // Or to use the Echo Logger + $logger = new Swift_Plugins_Loggers_EchoLogger(); + $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger)); + + // Continue sending as normal + for ($lotsOfRecipients as $recipient) { + ... + + $mailer->send( ... ); + } + + // Dump the log contents + // NOTE: The EchoLogger dumps in realtime so dump() does nothing for it + echo $logger->dump(); + +Decorator Plugin +---------------- + +Often there's a need to send the same message to multiple recipients, but with +tiny variations such as the recipient's name being used inside the message +body. The Decorator plugin aims to provide a solution for allowing these small +differences. + +The decorator plugin works by intercepting the sending process of Swift Mailer, +reading the email address in the To: field and then looking up a set of +replacements for a template. + +While the use of this plugin is simple, it is probably the most commonly +misunderstood plugin due to the way in which it works. The typical mistake +users make is to try registering the plugin multiple times (once for each +recipient) -- inside a loop for example. This is incorrect. + +The Decorator plugin should be registered just once, but containing the list of +all recipients prior to sending. It will use this list of recipients to find +the required replacements during sending. + +Using the Decorator Plugin +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use the Decorator plugin, simply create an associative array of replacements +based on email addresses and then use the mailer's ``registerPlugin()`` method +to add the plugin. + +First create an associative array of replacements based on the email addresses +you'll be sending the message to. + +.. note:: + + The replacements array becomes a 2-dimensional array whose keys are the + email addresses and whose values are an associative array of replacements + for that email address. The curly braces used in this example can be any + type of syntax you choose, provided they match the placeholders in your + email template:: + + $replacements = []; + foreach ($users as $user) { + $replacements[$user['email']] = [ + '{username}'=>$user['username'], + '{resetcode}'=>$user['resetcode'] + ]; + } + +Now create an instance of the Decorator plugin using this array of replacements +and then register it with the Mailer. Do this only once! + +:: + + $decorator = new Swift_Plugins_DecoratorPlugin($replacements); + + $mailer->registerPlugin($decorator); + +When you create your message, replace elements in the body (and/or the subject +line) with your placeholders:: + + $message = (new Swift_Message()) + ->setSubject('Important notice for {username}') + ->setBody( + "Hello {username}, you requested to reset your password.\n" . + "Please visit https://example.com/pwreset and use the reset code {resetcode} to set a new password." + ) + ; + + foreach ($users as $user) { + $message->addTo($user['email']); + } + +When you send this message to each of your recipients listed in your +``$replacements`` array they will receive a message customized for just +themselves. For example, the message used above when received may appear like +this to one user: + +.. code-block:: text + + Subject: Important notice for smilingsunshine2009 + + Hello smilingsunshine2009, you requested to reset your password. + Please visit https://example.com/pwreset and use the reset code 183457 to set a new password. + +While another use may receive the message as: + +.. code-block:: text + + Subject: Important notice for billy-bo-bob + + Hello billy-bo-bob, you requested to reset your password. + Please visit https://example.com/pwreset and use the reset code 539127 to set a new password. + +While the decorator plugin provides a means to solve this problem, there are +various ways you could tackle this problem without the need for a plugin. We're +trying to come up with a better way ourselves and while we have several +(obvious) ideas we don't quite have the perfect solution to go ahead and +implement it. Watch this space. + +Providing Your Own Replacements Lookup for the Decorator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Filling an array with replacements may not be the best solution for providing +replacement information to the decorator. If you have a more elegant algorithm +that performs replacement lookups on-the-fly you may provide your own +implementation. + +Providing your own replacements lookup implementation for the Decorator is +simply a matter of passing an instance of +``Swift_Plugins_Decorator_Replacements`` to the decorator plugin's constructor, +rather than passing in an array. + +The Replacements interface is very simple to implement since it has just one +method: ``getReplacementsFor($address)``. + +Imagine you want to look up replacements from a database on-the-fly, you might +provide an implementation that does this. You need to create a small class:: + + class DbReplacements implements Swift_Plugins_Decorator_Replacements { + public function getReplacementsFor($address) { + global $db; // Your PDO instance with a connection to your database + $query = $db->prepare( + "SELECT * FROM `users` WHERE `email` = ?" + ); + + $query->execute([$address]); + + if ($row = $query->fetch(PDO::FETCH_ASSOC)) { + return [ + '{username}'=>$row['username'], + '{resetcode}'=>$row['resetcode'] + ]; + } + } + } + +Now all you need to do is pass an instance of your class into the Decorator +plugin's constructor instead of passing an array:: + + $decorator = new Swift_Plugins_DecoratorPlugin(new DbReplacements()); + + $mailer->registerPlugin($decorator); + +For each message sent, the plugin will call your class' +``getReplacementsFor()`` method to find the array of replacements it needs. + +.. note:: + + If your lookup algorithm is case sensitive, you should transform the + ``$address`` argument as appropriate -- for example by passing it through + ``strtolower()``. diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/sending.rst b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/sending.rst new file mode 100644 index 0000000..d3a10ad --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/doc/sending.rst @@ -0,0 +1,464 @@ +Sending Messages +================ + +Quick Reference for Sending a Message +------------------------------------- + +Sending a message is very straightforward. You create a Transport, use it to +create the Mailer, then you use the Mailer to send the message. + +When using ``send()`` the message will be sent just like it would be sent if +you used your mail client. An integer is returned which includes the number of +successful recipients. If none of the recipients could be sent to then zero +will be returned, which equates to a boolean ``false``. If you set two ``To:`` +recipients and three ``Bcc:`` recipients in the message and all of the +recipients are delivered to successfully then the value 5 will be returned:: + + // Create the Transport + $transport = (new Swift_SmtpTransport('smtp.example.org', 25)) + ->setUsername('your username') + ->setPassword('your password') + ; + + /* + You could alternatively use a different transport such as Sendmail: + + // Sendmail + $transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs'); + */ + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + + // Create a message + $message = (new Swift_Message('Wonderful Subject')) + ->setFrom(['john@doe.com' => 'John Doe']) + ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name']) + ->setBody('Here is the message itself') + ; + + // Send the message + $result = $mailer->send($message); + +Transport Types +~~~~~~~~~~~~~~~ + +Transports are the classes in Swift Mailer that are responsible for +communicating with a service in order to deliver a Message. There are several +types of Transport in Swift Mailer, all of which implement the +``Swift_Transport`` interface:: + +* ``Swift_SmtpTransport``: Sends messages over SMTP; Supports Authentication; + Supports Encryption. Very portable; Pleasingly predictable results; Provides + good feedback; + +* ``Swift_SendmailTransport``: Communicates with a locally installed + ``sendmail`` executable (Linux/UNIX). Quick time-to-run; Provides + less-accurate feedback than SMTP; Requires ``sendmail`` installation; + +* ``Swift_LoadBalancedTransport``: Cycles through a collection of the other + Transports to manage load-reduction. Provides graceful fallback if one + Transport fails (e.g. an SMTP server is down); Keeps the load on remote + services down by spreading the work; + +* ``Swift_FailoverTransport``: Works in conjunction with a collection of the + other Transports to provide high-availability. Provides graceful fallback if + one Transport fails (e.g. an SMTP server is down). + +The SMTP Transport +.................. + +The SMTP Transport sends messages over the (standardized) Simple Message +Transfer Protocol. It can deal with encryption and authentication. + +The SMTP Transport, ``Swift_SmtpTransport`` is without doubt the most commonly +used Transport because it will work on 99% of web servers (I just made that +number up, but you get the idea). All the server needs is the ability to +connect to a remote (or even local) SMTP server on the correct port number +(usually 25). + +SMTP servers often require users to authenticate with a username and password +before any mail can be sent to other domains. This is easily achieved using +Swift Mailer with the SMTP Transport. + +SMTP is a protocol -- in other words it's a "way" of communicating a job to be +done (i.e. sending a message). The SMTP protocol is the fundamental basis on +which messages are delivered all over the internet 7 days a week, 365 days a +year. For this reason it's the most "direct" method of sending messages you can +use and it's the one that will give you the most power and feedback (such as +delivery failures) when using Swift Mailer. + +Because SMTP is generally run as a remote service (i.e. you connect to it over +the network/internet) it's extremely portable from server-to-server. You can +easily store the SMTP server address and port number in a configuration file +within your application and adjust the settings accordingly if the code is +moved or if the SMTP server is changed. + +Some SMTP servers -- Google for example -- use encryption for security reasons. +Swift Mailer supports using both ``ssl`` (SMTPS = SMTP over TLS) and ``tls`` +(SMTP with STARTTLS) encryption settings. + +Using the SMTP Transport +^^^^^^^^^^^^^^^^^^^^^^^^ + +The SMTP Transport is easy to use. Most configuration options can be set with +the constructor. + +To use the SMTP Transport you need to know which SMTP server your code needs to +connect to. Ask your web host if you're not sure. Lots of people ask me who to +connect to -- I really can't answer that since it's a setting that's extremely +specific to your hosting environment. + +A connection to the SMTP server will be established upon the first call to +``send()``:: + + // Create the Transport + $transport = new Swift_SmtpTransport('smtp.example.org', 25); + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + + /* + It's also possible to use multiple method calls + + $transport = (new Swift_SmtpTransport()) + ->setHost('smtp.example.org') + ->setPort(25) + ; + */ + +Encrypted SMTP +^^^^^^^^^^^^^^ + +You can use ``ssl`` (SMTPS) or ``tls`` (STARTTLS) encryption with the SMTP Transport +by specifying it as a parameter or with a method call:: + + // Create the Transport + // Option #1: SMTPS = SMTP over TLS (always encrypted): + $transport = new Swift_SmtpTransport('smtp.example.org', 587, 'ssl'); + // Option #2: SMTP with STARTTLS (best effort encryption): + $transport = new Swift_SmtpTransport('smtp.example.org', 587, 'tls'); + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + +A connection to the SMTP server will be established upon the first call to +``send()``. The connection will be initiated with the correct encryption +settings. + +.. note:: + For SMTPS or STARTTLS encryption to work your PHP installation must have + appropriate OpenSSL transports wrappers. You can check if "tls" and/or + "ssl" are present in your PHP installation by using the PHP function + ``stream_get_transports()``. + +.. note:: + If you are using Mailcatcher_, make sure you do not set the encryption + for the ``Swift_SmtpTransport``, since Mailcatcher does not support encryption. + +.. note:: + When in doubt, try ``ssl`` first for higher security, since the communication + is always encrypted. + +.. note:: + Usually, port 587 or 465 is used for encrypted SMTP. Check the documentation + of your mail provider. + +SMTP with a Username and Password +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Some servers require authentication. You can provide a username and password +with ``setUsername()`` and ``setPassword()`` methods:: + + // Create the Transport the call setUsername() and setPassword() + $transport = (new Swift_SmtpTransport('smtp.example.org', 25)) + ->setUsername('username') + ->setPassword('password') + ; + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + +Your username and password will be used to authenticate upon first connect when +``send()`` are first used on the Mailer. + +If authentication fails, an Exception of type ``Swift_TransportException`` will +be thrown. + +.. note:: + + If you need to know early whether or not authentication has failed and an + Exception is going to be thrown, call the ``start()`` method on the + created Transport. + +The Sendmail Transport +...................... + +The Sendmail Transport sends messages by communicating with a locally installed +MTA -- such as ``sendmail``. + +The Sendmail Transport, ``Swift_SendmailTransport`` does not directly connect +to any remote services. It is designed for Linux servers that have ``sendmail`` +installed. The Transport starts a local ``sendmail`` process and sends messages +to it. Usually the ``sendmail`` process will respond quickly as it spools your +messages to disk before sending them. + +The Transport is named the Sendmail Transport for historical reasons +(``sendmail`` was the "standard" UNIX tool for sending e-mail for years). It +will send messages using other transfer agents such as Exim or Postfix despite +its name, provided they have the relevant sendmail wrappers so that they can be +started with the correct command-line flags. + +It's a common misconception that because the Sendmail Transport returns a +result very quickly it must therefore deliver messages to recipients quickly -- +this is not true. It's not slow by any means, but it's certainly not faster +than SMTP when it comes to getting messages to the intended recipients. This is +because sendmail itself sends the messages over SMTP once they have been +quickly spooled to disk. + +The Sendmail Transport has the potential to be just as smart of the SMTP +Transport when it comes to notifying Swift Mailer about which recipients were +rejected, but in reality the majority of locally installed ``sendmail`` +instances are not configured well enough to provide any useful feedback. As +such Swift Mailer may report successful deliveries where they did in fact fail +before they even left your server. + +You can run the Sendmail Transport in two different modes specified by command +line flags: + +* "``-bs``" runs in SMTP mode so theoretically it will act like the SMTP + Transport + +* "``-t``" runs in piped mode with no feedback, but theoretically faster, + though not advised + +You can think of the Sendmail Transport as a sort of asynchronous SMTP +Transport -- though if you have problems with delivery failures you should try +using the SMTP Transport instead. Swift Mailer isn't doing the work here, it's +simply passing the work to somebody else (i.e. ``sendmail``). + +Using the Sendmail Transport +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To use the Sendmail Transport you simply need to call ``new +Swift_SendmailTransport()`` with the command as a parameter. + +To use the Sendmail Transport you need to know where ``sendmail`` or another +MTA exists on the server. Swift Mailer uses a default value of +``/usr/sbin/sendmail``, which should work on most systems. + +You specify the entire command as a parameter (i.e. including the command line +flags). Swift Mailer supports operational modes of "``-bs``" (default) and +"``-t``". + +.. note:: + + If you run sendmail in "``-t``" mode you will get no feedback as to whether + or not sending has succeeded. Use "``-bs``" unless you have a reason not to. + +A sendmail process will be started upon the first call to ``send()``. If the +process cannot be started successfully an Exception of type +``Swift_TransportException`` will be thrown:: + + // Create the Transport + $transport = new Swift_SendmailTransport('/usr/sbin/exim -bs'); + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + +Available Methods for Sending Messages +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Mailer class offers one method for sending Messages -- ``send()``. + +When a message is sent in Swift Mailer, the Mailer class communicates with +whichever Transport class you have chosen to use. + +Each recipient in the message should either be accepted or rejected by the +Transport. For example, if the domain name on the email address is not +reachable the SMTP Transport may reject the address because it cannot process +it. ``send()`` will return an integer indicating the number of accepted +recipients. + +.. note:: + + It's possible to find out which recipients were rejected -- we'll cover that + later in this chapter. + +Using the ``send()`` Method +........................... + +The ``send()`` method of the ``Swift_Mailer`` class sends a message using +exactly the same logic as your Desktop mail client would use. Just pass it a +Message and get a result. + +The message will be sent just like it would be sent if you used your mail +client. An integer is returned which includes the number of successful +recipients. If none of the recipients could be sent to then zero will be +returned, which equates to a boolean ``false``. If you set two +``To:`` recipients and three ``Bcc:`` recipients in the message and all of the +recipients are delivered to successfully then the value 5 will be returned:: + + // Create the Transport + $transport = new Swift_SmtpTransport('localhost', 25); + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + + // Create a message + $message = (new Swift_Message('Wonderful Subject')) + ->setFrom(['john@doe.com' => 'John Doe']) + ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name']) + ->setBody('Here is the message itself') + ; + + // Send the message + $numSent = $mailer->send($message); + + printf("Sent %d messages\n", $numSent); + + /* Note that often that only the boolean equivalent of the + return value is of concern (zero indicates FALSE) + + if ($mailer->send($message)) + { + echo "Sent\n"; + } + else + { + echo "Failed\n"; + } + + */ + +Sending Emails in Batch +....................... + +If you want to send a separate message to each recipient so that only their own +address shows up in the ``To:`` field, follow the following recipe: + +* Create a Transport from one of the provided Transports -- + ``Swift_SmtpTransport``, ``Swift_SendmailTransport``, + or one of the aggregate Transports. + +* Create an instance of the ``Swift_Mailer`` class, using the Transport as + it's constructor parameter. + +* Create a Message. + +* Iterate over the recipients and send message via the ``send()`` method on + the Mailer object. + +Each recipient of the messages receives a different copy with only their own +email address on the ``To:`` field. + +Make sure to add only valid email addresses as recipients. If you try to add an +invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift +Mailer will throw a ``Swift_RfcComplianceException``. + +If you add recipients automatically based on a data source that may contain +invalid email addresses, you can prevent possible exceptions by validating the +addresses using ``Egulias\EmailValidator\EmailValidator`` (a dependency that is +installed with Swift Mailer) and only adding addresses that validate. Another +way would be to wrap your ``setTo()``, ``setCc()`` and ``setBcc()`` calls in a +try-catch block and handle the ``Swift_RfcComplianceException`` in the catch +block. + +Handling invalid addresses properly is especially important when sending emails +in large batches since a single invalid address might cause an unhandled +exception and stop the execution or your script early. + +.. note:: + + In the following example, two emails are sent. One to each of + ``receiver@domain.org`` and ``other@domain.org``. These recipients will + not be aware of each other:: + + // Create the Transport + $transport = new Swift_SmtpTransport('localhost', 25); + + // Create the Mailer using your created Transport + $mailer = new Swift_Mailer($transport); + + // Create a message + $message = (new Swift_Message('Wonderful Subject')) + ->setFrom(['john@doe.com' => 'John Doe']) + ->setBody('Here is the message itself') + ; + + // Send the message + $failedRecipients = []; + $numSent = 0; + $to = ['receiver@domain.org', 'other@domain.org' => 'A name']; + + foreach ($to as $address => $name) + { + if (is_int($address)) { + $message->setTo($name); + } else { + $message->setTo([$address => $name]); + } + + $numSent += $mailer->send($message, $failedRecipients); + } + + printf("Sent %d messages\n", $numSent); + +Finding out Rejected Addresses +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It's possible to get a list of addresses that were rejected by the Transport by +using a by-reference parameter to ``send()``. + +As Swift Mailer attempts to send the message to each address given to it, if a +recipient is rejected it will be added to the array. You can pass an existing +array, otherwise one will be created by-reference. + +Collecting the list of recipients that were rejected can be useful in +circumstances where you need to "prune" a mailing list for example when some +addresses cannot be delivered to. + +Getting Failures By-reference +............................. + +Collecting delivery failures by-reference with the ``send()`` method is as +simple as passing a variable name to the method call:: + + $mailer = new Swift_Mailer( ... ); + + $message = (new Swift_Message( ... )) + ->setFrom( ... ) + ->setTo([ + 'receiver@bad-domain.org' => 'Receiver Name', + 'other@domain.org' => 'A name', + 'other-receiver@bad-domain.org' => 'Other Name' + )) + ->setBody( ... ) + ; + + // Pass a variable name to the send() method + if (!$mailer->send($message, $failures)) + { + echo "Failures:"; + print_r($failures); + } + + /* + Failures: + Array ( + 0 => receiver@bad-domain.org, + 1 => other-receiver@bad-domain.org + ) + */ + +If the Transport rejects any of the recipients, the culprit addresses will be +added to the array provided by-reference. + +.. note:: + + If the variable name does not yet exist, it will be initialized as an + empty array and then failures will be added to that array. If the variable + already exists it will be type-cast to an array and failures will be added + to it. + +.. _Mailcatcher: https://mailcatcher.me/ diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php new file mode 100644 index 0000000..51b19c9 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php @@ -0,0 +1,78 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * General utility class in Swift Mailer, not to be instantiated. + * + * @author Chris Corbyn + */ +abstract class Swift +{ + const VERSION = '6.3.0'; + + public static $initialized = false; + public static $inits = []; + + /** + * Registers an initializer callable that will be called the first time + * a SwiftMailer class is autoloaded. + * + * This enables you to tweak the default configuration in a lazy way. + * + * @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class + */ + public static function init($callable) + { + self::$inits[] = $callable; + } + + /** + * Internal autoloader for spl_autoload_register(). + * + * @param string $class + */ + public static function autoload($class) + { + // Don't interfere with other autoloaders + if (0 !== strpos($class, 'Swift_')) { + return; + } + + $path = __DIR__.'/'.str_replace('_', '/', $class).'.php'; + + if (!file_exists($path)) { + return; + } + + require $path; + + if (self::$inits && !self::$initialized) { + self::$initialized = true; + foreach (self::$inits as $init) { + \call_user_func($init); + } + } + } + + /** + * Configure autoloading using Swift Mailer. + * + * This is designed to play nicely with other autoloaders. + * + * @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class + */ + public static function registerAutoload($callable = null) + { + if (null !== $callable) { + self::$inits[] = $callable; + } + spl_autoload_register(['Swift', 'autoload']); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder.php new file mode 100644 index 0000000..a1704ff --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder.php @@ -0,0 +1,25 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2018 Christian Schmidt + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Email address encoder. + * + * @author Christian Schmidt + */ +interface Swift_AddressEncoder +{ + /** + * Encodes an email address. + * + * @throws Swift_AddressEncoderException if the email cannot be represented in + * the encoding implemented by this class + */ + public function encodeString(string $address): string; +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/IdnAddressEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/IdnAddressEncoder.php new file mode 100644 index 0000000..a373ef9 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/IdnAddressEncoder.php @@ -0,0 +1,50 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2018 Christian Schmidt + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An IDN email address encoder. + * + * Encodes the domain part of an address using IDN. This is compatible will all + * SMTP servers. + * + * This encoder does not support email addresses with non-ASCII characters in + * local-part (the substring before @). To send to such addresses, use + * Swift_AddressEncoder_Utf8AddressEncoder together with + * Swift_Transport_Esmtp_SmtpUtf8Handler. Your outbound SMTP server must support + * the SMTPUTF8 extension. + * + * @author Christian Schmidt + */ +class Swift_AddressEncoder_IdnAddressEncoder implements Swift_AddressEncoder +{ + /** + * Encodes the domain part of an address using IDN. + * + * @throws Swift_AddressEncoderException If local-part contains non-ASCII characters + */ + public function encodeString(string $address): string + { + $i = strrpos($address, '@'); + if (false !== $i) { + $local = substr($address, 0, $i); + $domain = substr($address, $i + 1); + + if (preg_match('/[^\x00-\x7F]/', $local)) { + throw new Swift_AddressEncoderException('Non-ASCII characters not supported in local-part', $address); + } + + if (preg_match('/[^\x00-\x7F]/', $domain)) { + $address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46)); + } + } + + return $address; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/Utf8AddressEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/Utf8AddressEncoder.php new file mode 100644 index 0000000..1b45430 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/Utf8AddressEncoder.php @@ -0,0 +1,36 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2018 Christian Schmidt + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A UTF-8 email address encoder. + * + * Returns the email address verbatimly in UTF-8 as permitted by RFC 6531 and + * RFC 6532. It supports addresses containing non-ASCII characters in both + * local-part and domain (i.e. on both sides of @). + * + * This encoder must be used together with Swift_Transport_Esmtp_SmtpUtf8Handler + * and requires that the outbound SMTP server supports the SMTPUTF8 extension. + * + * If your outbound SMTP server does not support SMTPUTF8, use + * Swift_AddressEncoder_IdnAddressEncoder instead. This allows sending to email + * addresses with non-ASCII characters in the domain, but not in local-part. + * + * @author Christian Schmidt + */ +class Swift_AddressEncoder_Utf8AddressEncoder implements Swift_AddressEncoder +{ + /** + * Returns the address verbatimly. + */ + public function encodeString(string $address): string + { + return $address; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoderException.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoderException.php new file mode 100644 index 0000000..9b40547 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoderException.php @@ -0,0 +1,32 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2018 Christian Schmidt + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * AddressEncoderException when the specified email address is in a format that + * cannot be encoded by a given address encoder. + * + * @author Christian Schmidt + */ +class Swift_AddressEncoderException extends Swift_RfcComplianceException +{ + protected $address; + + public function __construct(string $message, string $address) + { + parent::__construct($message); + + $this->address = $address; + } + + public function getAddress(): string + { + return $this->address; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Attachment.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Attachment.php new file mode 100644 index 0000000..7a1420f --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Attachment.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Attachment class for attaching files to a {@link Swift_Mime_SimpleMessage}. + * + * @author Chris Corbyn + */ +class Swift_Attachment extends Swift_Mime_Attachment +{ + /** + * Create a new Attachment. + * + * Details may be optionally provided to the constructor. + * + * @param string|Swift_OutputByteStream $data + * @param string $filename + * @param string $contentType + */ + public function __construct($data = null, $filename = null, $contentType = null) + { + \call_user_func_array( + [$this, 'Swift_Mime_Attachment::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('mime.attachment') + ); + + $this->setBody($data, $contentType); + $this->setFilename($filename); + } + + /** + * Create a new Attachment from a filesystem path. + * + * @param string $path + * @param string $contentType optional + * + * @return self + */ + public static function fromPath($path, $contentType = null) + { + return (new self())->setFile( + new Swift_ByteStream_FileByteStream($path), + $contentType + ); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php new file mode 100644 index 0000000..3a69c15 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php @@ -0,0 +1,176 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Provides the base functionality for an InputStream supporting filters. + * + * @author Chris Corbyn + */ +abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_InputByteStream, Swift_Filterable +{ + /** + * Write sequence. + */ + protected $sequence = 0; + + /** + * StreamFilters. + * + * @var Swift_StreamFilter[] + */ + private $filters = []; + + /** + * A buffer for writing. + */ + private $writeBuffer = ''; + + /** + * Bound streams. + * + * @var Swift_InputByteStream[] + */ + private $mirrors = []; + + /** + * Commit the given bytes to the storage medium immediately. + * + * @param string $bytes + */ + abstract protected function doCommit($bytes); + + /** + * Flush any buffers/content with immediate effect. + */ + abstract protected function flush(); + + /** + * Add a StreamFilter to this InputByteStream. + * + * @param string $key + */ + public function addFilter(Swift_StreamFilter $filter, $key) + { + $this->filters[$key] = $filter; + } + + /** + * Remove an already present StreamFilter based on its $key. + * + * @param string $key + */ + public function removeFilter($key) + { + unset($this->filters[$key]); + } + + /** + * Writes $bytes to the end of the stream. + * + * @param string $bytes + * + * @throws Swift_IoException + * + * @return int + */ + public function write($bytes) + { + $this->writeBuffer .= $bytes; + foreach ($this->filters as $filter) { + if ($filter->shouldBuffer($this->writeBuffer)) { + return; + } + } + $this->doWrite($this->writeBuffer); + + return ++$this->sequence; + } + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + * + * @throws Swift_IoException + */ + public function commit() + { + $this->doWrite($this->writeBuffer); + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + */ + public function bind(Swift_InputByteStream $is) + { + $this->mirrors[] = $is; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + */ + public function unbind(Swift_InputByteStream $is) + { + foreach ($this->mirrors as $k => $stream) { + if ($is === $stream) { + if ('' !== $this->writeBuffer) { + $stream->write($this->writeBuffer); + } + unset($this->mirrors[$k]); + } + } + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + */ + public function flushBuffers() + { + if ('' !== $this->writeBuffer) { + $this->doWrite($this->writeBuffer); + } + $this->flush(); + + foreach ($this->mirrors as $stream) { + $stream->flushBuffers(); + } + } + + /** Run $bytes through all filters */ + private function filter($bytes) + { + foreach ($this->filters as $filter) { + $bytes = $filter->filter($bytes); + } + + return $bytes; + } + + /** Just write the bytes to the stream */ + private function doWrite($bytes) + { + $this->doCommit($this->filter($bytes)); + + foreach ($this->mirrors as $stream) { + $stream->write($bytes); + } + + $this->writeBuffer = ''; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php new file mode 100644 index 0000000..4f3dcc3 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php @@ -0,0 +1,178 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Allows reading and writing of bytes to and from an array. + * + * @author Chris Corbyn + */ +class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_OutputByteStream +{ + /** + * The internal stack of bytes. + * + * @var string[] + */ + private $array = []; + + /** + * The size of the stack. + * + * @var int + */ + private $arraySize = 0; + + /** + * The internal pointer offset. + * + * @var int + */ + private $offset = 0; + + /** + * Bound streams. + * + * @var Swift_InputByteStream[] + */ + private $mirrors = []; + + /** + * Create a new ArrayByteStream. + * + * If $stack is given the stream will be populated with the bytes it contains. + * + * @param mixed $stack of bytes in string or array form, optional + */ + public function __construct($stack = null) + { + if (\is_array($stack)) { + $this->array = $stack; + $this->arraySize = \count($stack); + } elseif (\is_string($stack)) { + $this->write($stack); + } else { + $this->array = []; + } + } + + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the + * remaining bytes are given instead. If no bytes are remaining at all, boolean + * false is returned. + * + * @param int $length + * + * @return string + */ + public function read($length) + { + if ($this->offset == $this->arraySize) { + return false; + } + + // Don't use array slice + $end = $length + $this->offset; + $end = $this->arraySize < $end ? $this->arraySize : $end; + $ret = ''; + for (; $this->offset < $end; ++$this->offset) { + $ret .= $this->array[$this->offset]; + } + + return $ret; + } + + /** + * Writes $bytes to the end of the stream. + * + * @param string $bytes + */ + public function write($bytes) + { + $to_add = str_split($bytes); + foreach ($to_add as $value) { + $this->array[] = $value; + } + $this->arraySize = \count($this->array); + + foreach ($this->mirrors as $stream) { + $stream->write($bytes); + } + } + + /** + * Not used. + */ + public function commit() + { + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + */ + public function bind(Swift_InputByteStream $is) + { + $this->mirrors[] = $is; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + */ + public function unbind(Swift_InputByteStream $is) + { + foreach ($this->mirrors as $k => $stream) { + if ($is === $stream) { + unset($this->mirrors[$k]); + } + } + } + + /** + * Move the internal read pointer to $byteOffset in the stream. + * + * @param int $byteOffset + * + * @return bool + */ + public function setReadPointer($byteOffset) + { + if ($byteOffset > $this->arraySize) { + $byteOffset = $this->arraySize; + } elseif ($byteOffset < 0) { + $byteOffset = 0; + } + + $this->offset = $byteOffset; + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + */ + public function flushBuffers() + { + $this->offset = 0; + $this->array = []; + $this->arraySize = 0; + + foreach ($this->mirrors as $stream) { + $stream->flushBuffers(); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php new file mode 100644 index 0000000..f639121 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php @@ -0,0 +1,214 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Allows reading and writing of bytes to and from a file. + * + * @author Chris Corbyn + */ +class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_FileStream +{ + /** The internal pointer offset */ + private $offset = 0; + + /** The path to the file */ + private $path; + + /** The mode this file is opened in for writing */ + private $mode; + + /** A lazy-loaded resource handle for reading the file */ + private $reader; + + /** A lazy-loaded resource handle for writing the file */ + private $writer; + + /** If stream is seekable true/false, or null if not known */ + private $seekable = null; + + /** + * Create a new FileByteStream for $path. + * + * @param string $path + * @param bool $writable if true + */ + public function __construct($path, $writable = false) + { + if (empty($path)) { + throw new Swift_IoException('The path cannot be empty'); + } + $this->path = $path; + $this->mode = $writable ? 'w+b' : 'rb'; + } + + /** + * Get the complete path to the file. + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the + * remaining bytes are given instead. If no bytes are remaining at all, boolean + * false is returned. + * + * @param int $length + * + * @return string|bool + * + * @throws Swift_IoException + */ + public function read($length) + { + $fp = $this->getReadHandle(); + if (!feof($fp)) { + $bytes = fread($fp, $length); + $this->offset = ftell($fp); + + // If we read one byte after reaching the end of the file + // feof() will return false and an empty string is returned + if ((false === $bytes || '' === $bytes) && feof($fp)) { + $this->resetReadHandle(); + + return false; + } + + return $bytes; + } + + $this->resetReadHandle(); + + return false; + } + + /** + * Move the internal read pointer to $byteOffset in the stream. + * + * @param int $byteOffset + * + * @return bool + */ + public function setReadPointer($byteOffset) + { + if (isset($this->reader)) { + $this->seekReadStreamToPosition($byteOffset); + } + $this->offset = $byteOffset; + } + + /** Just write the bytes to the file */ + protected function doCommit($bytes) + { + fwrite($this->getWriteHandle(), $bytes); + $this->resetReadHandle(); + } + + /** Not used */ + protected function flush() + { + } + + /** Get the resource for reading */ + private function getReadHandle() + { + if (!isset($this->reader)) { + $pointer = @fopen($this->path, 'rb'); + if (!$pointer) { + throw new Swift_IoException('Unable to open file for reading ['.$this->path.']'); + } + $this->reader = $pointer; + if (0 != $this->offset) { + $this->getReadStreamSeekableStatus(); + $this->seekReadStreamToPosition($this->offset); + } + } + + return $this->reader; + } + + /** Get the resource for writing */ + private function getWriteHandle() + { + if (!isset($this->writer)) { + if (!$this->writer = fopen($this->path, $this->mode)) { + throw new Swift_IoException('Unable to open file for writing ['.$this->path.']'); + } + } + + return $this->writer; + } + + /** Force a reload of the resource for reading */ + private function resetReadHandle() + { + if (isset($this->reader)) { + fclose($this->reader); + $this->reader = null; + } + } + + /** Check if ReadOnly Stream is seekable */ + private function getReadStreamSeekableStatus() + { + $metas = stream_get_meta_data($this->reader); + $this->seekable = $metas['seekable']; + } + + /** Streams in a readOnly stream ensuring copy if needed */ + private function seekReadStreamToPosition($offset) + { + if (null === $this->seekable) { + $this->getReadStreamSeekableStatus(); + } + if (false === $this->seekable) { + $currentPos = ftell($this->reader); + if ($currentPos < $offset) { + $toDiscard = $offset - $currentPos; + fread($this->reader, $toDiscard); + + return; + } + $this->copyReadStream(); + } + fseek($this->reader, $offset, SEEK_SET); + } + + /** Copy a readOnly Stream to ensure seekability */ + private function copyReadStream() + { + if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) { + /* We have opened a php:// Stream Should work without problem */ + } elseif (\function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()) && ($tmpFile = tmpfile())) { + /* We have opened a tmpfile */ + } else { + throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available'); + } + $currentPos = ftell($this->reader); + fclose($this->reader); + $source = fopen($this->path, 'rb'); + if (!$source) { + throw new Swift_IoException('Unable to open file for copying ['.$this->path.']'); + } + fseek($tmpFile, 0, SEEK_SET); + while (!feof($source)) { + fwrite($tmpFile, fread($source, 4096)); + } + fseek($tmpFile, $currentPos, SEEK_SET); + fclose($source); + $this->reader = $tmpFile; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php new file mode 100644 index 0000000..0dc6190 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php @@ -0,0 +1,52 @@ +<?php + +/* +* This file is part of SwiftMailer. +* (c) 2004-2009 Chris Corbyn +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +/** + * @author Romain-Geissler + */ +class Swift_ByteStream_TemporaryFileByteStream extends Swift_ByteStream_FileByteStream +{ + public function __construct() + { + $filePath = tempnam(sys_get_temp_dir(), 'FileByteStream'); + + if (false === $filePath) { + throw new Swift_IoException('Failed to retrieve temporary file name.'); + } + + parent::__construct($filePath, true); + } + + public function getContent() + { + if (false === ($content = file_get_contents($this->getPath()))) { + throw new Swift_IoException('Failed to get temporary file content.'); + } + + return $content; + } + + public function __destruct() + { + if (file_exists($this->getPath())) { + @unlink($this->getPath()); + } + } + + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php new file mode 100644 index 0000000..4267adb --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php @@ -0,0 +1,67 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Analyzes characters for a specific character set. + * + * @author Chris Corbyn + * @author Xavier De Cock <xdecock@gmail.com> + */ +interface Swift_CharacterReader +{ + const MAP_TYPE_INVALID = 0x01; + const MAP_TYPE_FIXED_LEN = 0x02; + const MAP_TYPE_POSITIONS = 0x03; + + /** + * Returns the complete character map. + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param mixed $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars); + + /** + * Returns the mapType, see constants. + * + * @return int + */ + public function getMapType(); + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param int[] $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size); + + /** + * Returns the number of bytes which should be read to start each character. + * + * For fixed width character sets this should be the number of octets-per-character. + * For multibyte character sets this will probably be 1. + * + * @return int + */ + public function getInitialByteSize(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php new file mode 100644 index 0000000..3e055af --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php @@ -0,0 +1,97 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Provides fixed-width byte sizes for reading fixed-width character sets. + * + * @author Chris Corbyn + * @author Xavier De Cock <xdecock@gmail.com> + */ +class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader +{ + /** + * The number of bytes in a single character. + * + * @var int + */ + private $width; + + /** + * Creates a new GenericFixedWidthReader using $width bytes per character. + * + * @param int $width + */ + public function __construct($width) + { + $this->width = $width; + } + + /** + * Returns the complete character map. + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param mixed $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) + { + $strlen = \strlen($string); + // % and / are CPU intensive, so, maybe find a better way + $ignored = $strlen % $this->width; + $ignoredChars = $ignored ? substr($string, -$ignored) : ''; + $currentMap = $this->width; + + return ($strlen - $ignored) / $this->width; + } + + /** + * Returns the mapType. + * + * @return int + */ + public function getMapType() + { + return self::MAP_TYPE_FIXED_LEN; + } + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param string $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size) + { + $needed = $this->width - $size; + + return $needed > -1 ? $needed : -1; + } + + /** + * Returns the number of bytes which should be read to start each character. + * + * @return int + */ + public function getInitialByteSize() + { + return $this->width; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php new file mode 100644 index 0000000..ffc05f7 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php @@ -0,0 +1,84 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Analyzes US-ASCII characters. + * + * @author Chris Corbyn + */ +class Swift_CharacterReader_UsAsciiReader implements Swift_CharacterReader +{ + /** + * Returns the complete character map. + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param string $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) + { + $strlen = \strlen($string); + $ignoredChars = ''; + for ($i = 0; $i < $strlen; ++$i) { + if ($string[$i] > "\x07F") { + // Invalid char + $currentMap[$i + $startOffset] = $string[$i]; + } + } + + return $strlen; + } + + /** + * Returns mapType. + * + * @return int mapType + */ + public function getMapType() + { + return self::MAP_TYPE_INVALID; + } + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param string $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size) + { + $byte = reset($bytes); + if (1 == \count($bytes) && $byte >= 0x00 && $byte <= 0x7F) { + return 0; + } + + return -1; + } + + /** + * Returns the number of bytes which should be read to start each character. + * + * @return int + */ + public function getInitialByteSize() + { + return 1; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php new file mode 100644 index 0000000..da37e0d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php @@ -0,0 +1,176 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Analyzes UTF-8 characters. + * + * @author Chris Corbyn + * @author Xavier De Cock <xdecock@gmail.com> + */ +class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader +{ + /** Pre-computed for optimization */ + private static $length_map = [ + // N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x0N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x2N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x4N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x6N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x8N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xAN + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBN + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xCN + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDN + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEN + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // 0xFN + ]; + + private static $s_length_map = [ + "\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1, + "\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1, + "\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1, + "\x18" => 1, "\x19" => 1, "\x1a" => 1, "\x1b" => 1, "\x1c" => 1, "\x1d" => 1, "\x1e" => 1, "\x1f" => 1, + "\x20" => 1, "\x21" => 1, "\x22" => 1, "\x23" => 1, "\x24" => 1, "\x25" => 1, "\x26" => 1, "\x27" => 1, + "\x28" => 1, "\x29" => 1, "\x2a" => 1, "\x2b" => 1, "\x2c" => 1, "\x2d" => 1, "\x2e" => 1, "\x2f" => 1, + "\x30" => 1, "\x31" => 1, "\x32" => 1, "\x33" => 1, "\x34" => 1, "\x35" => 1, "\x36" => 1, "\x37" => 1, + "\x38" => 1, "\x39" => 1, "\x3a" => 1, "\x3b" => 1, "\x3c" => 1, "\x3d" => 1, "\x3e" => 1, "\x3f" => 1, + "\x40" => 1, "\x41" => 1, "\x42" => 1, "\x43" => 1, "\x44" => 1, "\x45" => 1, "\x46" => 1, "\x47" => 1, + "\x48" => 1, "\x49" => 1, "\x4a" => 1, "\x4b" => 1, "\x4c" => 1, "\x4d" => 1, "\x4e" => 1, "\x4f" => 1, + "\x50" => 1, "\x51" => 1, "\x52" => 1, "\x53" => 1, "\x54" => 1, "\x55" => 1, "\x56" => 1, "\x57" => 1, + "\x58" => 1, "\x59" => 1, "\x5a" => 1, "\x5b" => 1, "\x5c" => 1, "\x5d" => 1, "\x5e" => 1, "\x5f" => 1, + "\x60" => 1, "\x61" => 1, "\x62" => 1, "\x63" => 1, "\x64" => 1, "\x65" => 1, "\x66" => 1, "\x67" => 1, + "\x68" => 1, "\x69" => 1, "\x6a" => 1, "\x6b" => 1, "\x6c" => 1, "\x6d" => 1, "\x6e" => 1, "\x6f" => 1, + "\x70" => 1, "\x71" => 1, "\x72" => 1, "\x73" => 1, "\x74" => 1, "\x75" => 1, "\x76" => 1, "\x77" => 1, + "\x78" => 1, "\x79" => 1, "\x7a" => 1, "\x7b" => 1, "\x7c" => 1, "\x7d" => 1, "\x7e" => 1, "\x7f" => 1, + "\x80" => 0, "\x81" => 0, "\x82" => 0, "\x83" => 0, "\x84" => 0, "\x85" => 0, "\x86" => 0, "\x87" => 0, + "\x88" => 0, "\x89" => 0, "\x8a" => 0, "\x8b" => 0, "\x8c" => 0, "\x8d" => 0, "\x8e" => 0, "\x8f" => 0, + "\x90" => 0, "\x91" => 0, "\x92" => 0, "\x93" => 0, "\x94" => 0, "\x95" => 0, "\x96" => 0, "\x97" => 0, + "\x98" => 0, "\x99" => 0, "\x9a" => 0, "\x9b" => 0, "\x9c" => 0, "\x9d" => 0, "\x9e" => 0, "\x9f" => 0, + "\xa0" => 0, "\xa1" => 0, "\xa2" => 0, "\xa3" => 0, "\xa4" => 0, "\xa5" => 0, "\xa6" => 0, "\xa7" => 0, + "\xa8" => 0, "\xa9" => 0, "\xaa" => 0, "\xab" => 0, "\xac" => 0, "\xad" => 0, "\xae" => 0, "\xaf" => 0, + "\xb0" => 0, "\xb1" => 0, "\xb2" => 0, "\xb3" => 0, "\xb4" => 0, "\xb5" => 0, "\xb6" => 0, "\xb7" => 0, + "\xb8" => 0, "\xb9" => 0, "\xba" => 0, "\xbb" => 0, "\xbc" => 0, "\xbd" => 0, "\xbe" => 0, "\xbf" => 0, + "\xc0" => 2, "\xc1" => 2, "\xc2" => 2, "\xc3" => 2, "\xc4" => 2, "\xc5" => 2, "\xc6" => 2, "\xc7" => 2, + "\xc8" => 2, "\xc9" => 2, "\xca" => 2, "\xcb" => 2, "\xcc" => 2, "\xcd" => 2, "\xce" => 2, "\xcf" => 2, + "\xd0" => 2, "\xd1" => 2, "\xd2" => 2, "\xd3" => 2, "\xd4" => 2, "\xd5" => 2, "\xd6" => 2, "\xd7" => 2, + "\xd8" => 2, "\xd9" => 2, "\xda" => 2, "\xdb" => 2, "\xdc" => 2, "\xdd" => 2, "\xde" => 2, "\xdf" => 2, + "\xe0" => 3, "\xe1" => 3, "\xe2" => 3, "\xe3" => 3, "\xe4" => 3, "\xe5" => 3, "\xe6" => 3, "\xe7" => 3, + "\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3, + "\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4, + "\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0, + ]; + + /** + * Returns the complete character map. + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param mixed $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) + { + if (!isset($currentMap['i']) || !isset($currentMap['p'])) { + $currentMap['p'] = $currentMap['i'] = []; + } + + $strlen = \strlen($string); + $charPos = \count($currentMap['p']); + $foundChars = 0; + $invalid = false; + for ($i = 0; $i < $strlen; ++$i) { + $char = $string[$i]; + $size = self::$s_length_map[$char]; + if (0 == $size) { + /* char is invalid, we must wait for a resync */ + $invalid = true; + continue; + } else { + if (true === $invalid) { + /* We mark the chars as invalid and start a new char */ + $currentMap['p'][$charPos + $foundChars] = $startOffset + $i; + $currentMap['i'][$charPos + $foundChars] = true; + ++$foundChars; + $invalid = false; + } + if (($i + $size) > $strlen) { + $ignoredChars = substr($string, $i); + break; + } + for ($j = 1; $j < $size; ++$j) { + $char = $string[$i + $j]; + if ($char > "\x7F" && $char < "\xC0") { + // Valid - continue parsing + } else { + /* char is invalid, we must wait for a resync */ + $invalid = true; + continue 2; + } + } + /* Ok we got a complete char here */ + $currentMap['p'][$charPos + $foundChars] = $startOffset + $i + $size; + $i += $j - 1; + ++$foundChars; + } + } + + return $foundChars; + } + + /** + * Returns mapType. + * + * @return int mapType + */ + public function getMapType() + { + return self::MAP_TYPE_POSITIONS; + } + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param string $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size) + { + if ($size < 1) { + return -1; + } + $needed = self::$length_map[$bytes[0]] - $size; + + return $needed > -1 ? $needed : -1; + } + + /** + * Returns the number of bytes which should be read to start each character. + * + * @return int + */ + public function getInitialByteSize() + { + return 1; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php new file mode 100644 index 0000000..15b6c69 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php @@ -0,0 +1,26 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A factory for creating CharacterReaders. + * + * @author Chris Corbyn + */ +interface Swift_CharacterReaderFactory +{ + /** + * Returns a CharacterReader suitable for the charset applied. + * + * @param string $charset + * + * @return Swift_CharacterReader + */ + public function getReaderFor($charset); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php new file mode 100644 index 0000000..8690089 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php @@ -0,0 +1,124 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Standard factory for creating CharacterReaders. + * + * @author Chris Corbyn + */ +class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift_CharacterReaderFactory +{ + /** + * A map of charset patterns to their implementation classes. + * + * @var array + */ + private static $map = []; + + /** + * Factories which have already been loaded. + * + * @var Swift_CharacterReaderFactory[] + */ + private static $loaded = []; + + /** + * Creates a new CharacterReaderFactory. + */ + public function __construct() + { + $this->init(); + } + + public function __wakeup() + { + $this->init(); + } + + public function init() + { + if (\count(self::$map) > 0) { + return; + } + + $prefix = 'Swift_CharacterReader_'; + + $singleByte = [ + 'class' => $prefix.'GenericFixedWidthReader', + 'constructor' => [1], + ]; + + $doubleByte = [ + 'class' => $prefix.'GenericFixedWidthReader', + 'constructor' => [2], + ]; + + $fourBytes = [ + 'class' => $prefix.'GenericFixedWidthReader', + 'constructor' => [4], + ]; + + // Utf-8 + self::$map['utf-?8'] = [ + 'class' => $prefix.'Utf8Reader', + 'constructor' => [], + ]; + + //7-8 bit charsets + self::$map['(us-)?ascii'] = $singleByte; + self::$map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; + self::$map['windows-?125[0-9]'] = $singleByte; + self::$map['cp-?[0-9]+'] = $singleByte; + self::$map['ansi'] = $singleByte; + self::$map['macintosh'] = $singleByte; + self::$map['koi-?7'] = $singleByte; + self::$map['koi-?8-?.+'] = $singleByte; + self::$map['mik'] = $singleByte; + self::$map['(cork|t1)'] = $singleByte; + self::$map['v?iscii'] = $singleByte; + + //16 bits + self::$map['(ucs-?2|utf-?16)'] = $doubleByte; + + //32 bits + self::$map['(ucs-?4|utf-?32)'] = $fourBytes; + + // Fallback + self::$map['.*'] = $singleByte; + } + + /** + * Returns a CharacterReader suitable for the charset applied. + * + * @param string $charset + * + * @return Swift_CharacterReader + */ + public function getReaderFor($charset) + { + $charset = strtolower(trim($charset ?? '')); + foreach (self::$map as $pattern => $spec) { + $re = '/^'.$pattern.'$/D'; + if (preg_match($re, $charset)) { + if (!\array_key_exists($pattern, self::$loaded)) { + $reflector = new ReflectionClass($spec['class']); + if ($reflector->getConstructor()) { + $reader = $reflector->newInstanceArgs($spec['constructor']); + } else { + $reader = $reflector->newInstance(); + } + self::$loaded[$pattern] = $reader; + } + + return self::$loaded[$pattern]; + } + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php new file mode 100644 index 0000000..c9d8a07 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An abstract means of reading and writing data in terms of characters as opposed + * to bytes. + * + * Classes implementing this interface may use a subsystem which requires less + * memory than working with large strings of data. + * + * @author Chris Corbyn + */ +interface Swift_CharacterStream +{ + /** + * Set the character set used in this CharacterStream. + * + * @param string $charset + */ + public function setCharacterSet($charset); + + /** + * Set the CharacterReaderFactory for multi charset support. + */ + public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory); + + /** + * Overwrite this character stream using the byte sequence in the byte stream. + * + * @param Swift_OutputByteStream $os output stream to read from + */ + public function importByteStream(Swift_OutputByteStream $os); + + /** + * Import a string a bytes into this CharacterStream, overwriting any existing + * data in the stream. + * + * @param string $string + */ + public function importString($string); + + /** + * Read $length characters from the stream and move the internal pointer + * $length further into the stream. + * + * @param int $length + * + * @return string + */ + public function read($length); + + /** + * Read $length characters from the stream and return a 1-dimensional array + * containing there octet values. + * + * @param int $length + * + * @return int[] + */ + public function readBytes($length); + + /** + * Write $chars to the end of the stream. + * + * @param string $chars + */ + public function write($chars); + + /** + * Move the internal pointer to $charOffset in the stream. + * + * @param int $charOffset + */ + public function setPointer($charOffset); + + /** + * Empty the stream and reset the internal pointer. + */ + public function flushContents(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php new file mode 100644 index 0000000..5c28694 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php @@ -0,0 +1,291 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A CharacterStream implementation which stores characters in an internal array. + * + * @author Chris Corbyn + */ +class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStream +{ + /** A map of byte values and their respective characters */ + private static $charMap; + + /** A map of characters and their derivative byte values */ + private static $byteMap; + + /** The char reader (lazy-loaded) for the current charset */ + private $charReader; + + /** A factory for creating CharacterReader instances */ + private $charReaderFactory; + + /** The character set this stream is using */ + private $charset; + + /** Array of characters */ + private $array = []; + + /** Size of the array of character */ + private $array_size = []; + + /** The current character offset in the stream */ + private $offset = 0; + + /** + * Create a new CharacterStream with the given $chars, if set. + * + * @param Swift_CharacterReaderFactory $factory for loading validators + * @param string $charset used in the stream + */ + public function __construct(Swift_CharacterReaderFactory $factory, $charset) + { + self::initializeMaps(); + $this->setCharacterReaderFactory($factory); + $this->setCharacterSet($charset); + } + + /** + * Set the character set used in this CharacterStream. + * + * @param string $charset + */ + public function setCharacterSet($charset) + { + $this->charset = $charset; + $this->charReader = null; + } + + /** + * Set the CharacterReaderFactory for multi charset support. + */ + public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) + { + $this->charReaderFactory = $factory; + } + + /** + * Overwrite this character stream using the byte sequence in the byte stream. + * + * @param Swift_OutputByteStream $os output stream to read from + */ + public function importByteStream(Swift_OutputByteStream $os) + { + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory + ->getReaderFor($this->charset); + } + + $startLength = $this->charReader->getInitialByteSize(); + while (false !== $bytes = $os->read($startLength)) { + $c = []; + for ($i = 0, $len = \strlen($bytes); $i < $len; ++$i) { + $c[] = self::$byteMap[$bytes[$i]]; + } + $size = \count($c); + $need = $this->charReader + ->validateByteSequence($c, $size); + if ($need > 0 && + false !== $bytes = $os->read($need)) { + for ($i = 0, $len = \strlen($bytes); $i < $len; ++$i) { + $c[] = self::$byteMap[$bytes[$i]]; + } + } + $this->array[] = $c; + ++$this->array_size; + } + } + + /** + * Import a string a bytes into this CharacterStream, overwriting any existing + * data in the stream. + * + * @param string $string + */ + public function importString($string) + { + $this->flushContents(); + $this->write($string); + } + + /** + * Read $length characters from the stream and move the internal pointer + * $length further into the stream. + * + * @param int $length + * + * @return string + */ + public function read($length) + { + if ($this->offset == $this->array_size) { + return false; + } + + // Don't use array slice + $arrays = []; + $end = $length + $this->offset; + for ($i = $this->offset; $i < $end; ++$i) { + if (!isset($this->array[$i])) { + break; + } + $arrays[] = $this->array[$i]; + } + $this->offset += $i - $this->offset; // Limit function calls + $chars = false; + foreach ($arrays as $array) { + $chars .= implode('', array_map('chr', $array)); + } + + return $chars; + } + + /** + * Read $length characters from the stream and return a 1-dimensional array + * containing there octet values. + * + * @param int $length + * + * @return int[] + */ + public function readBytes($length) + { + if ($this->offset == $this->array_size) { + return false; + } + $arrays = []; + $end = $length + $this->offset; + for ($i = $this->offset; $i < $end; ++$i) { + if (!isset($this->array[$i])) { + break; + } + $arrays[] = $this->array[$i]; + } + $this->offset += ($i - $this->offset); // Limit function calls + + return array_merge(...$arrays); + } + + /** + * Write $chars to the end of the stream. + * + * @param string $chars + */ + public function write($chars) + { + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory->getReaderFor( + $this->charset); + } + + $startLength = $this->charReader->getInitialByteSize(); + + $fp = fopen('php://memory', 'w+b'); + fwrite($fp, $chars); + unset($chars); + fseek($fp, 0, SEEK_SET); + + $buffer = [0]; + $buf_pos = 1; + $buf_len = 1; + $has_datas = true; + do { + $bytes = []; + // Buffer Filing + if ($buf_len - $buf_pos < $startLength) { + $buf = array_splice($buffer, $buf_pos); + $new = $this->reloadBuffer($fp, 100); + if ($new) { + $buffer = array_merge($buf, $new); + $buf_len = \count($buffer); + $buf_pos = 0; + } else { + $has_datas = false; + } + } + if ($buf_len - $buf_pos > 0) { + $size = 0; + for ($i = 0; $i < $startLength && isset($buffer[$buf_pos]); ++$i) { + ++$size; + $bytes[] = $buffer[$buf_pos++]; + } + $need = $this->charReader->validateByteSequence( + $bytes, $size); + if ($need > 0) { + if ($buf_len - $buf_pos < $need) { + $new = $this->reloadBuffer($fp, $need); + + if ($new) { + $buffer = array_merge($buffer, $new); + $buf_len = \count($buffer); + } + } + for ($i = 0; $i < $need && isset($buffer[$buf_pos]); ++$i) { + $bytes[] = $buffer[$buf_pos++]; + } + } + $this->array[] = $bytes; + ++$this->array_size; + } + } while ($has_datas); + + fclose($fp); + } + + /** + * Move the internal pointer to $charOffset in the stream. + * + * @param int $charOffset + */ + public function setPointer($charOffset) + { + if ($charOffset > $this->array_size) { + $charOffset = $this->array_size; + } elseif ($charOffset < 0) { + $charOffset = 0; + } + $this->offset = $charOffset; + } + + /** + * Empty the stream and reset the internal pointer. + */ + public function flushContents() + { + $this->offset = 0; + $this->array = []; + $this->array_size = 0; + } + + private function reloadBuffer($fp, $len) + { + if (!feof($fp) && false !== ($bytes = fread($fp, $len))) { + $buf = []; + for ($i = 0, $len = \strlen($bytes); $i < $len; ++$i) { + $buf[] = self::$byteMap[$bytes[$i]]; + } + + return $buf; + } + + return false; + } + + private static function initializeMaps() + { + if (!isset(self::$charMap)) { + self::$charMap = []; + for ($byte = 0; $byte < 256; ++$byte) { + self::$charMap[$byte] = \chr($byte); + } + self::$byteMap = array_flip(self::$charMap); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php new file mode 100644 index 0000000..7578dda --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php @@ -0,0 +1,262 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A CharacterStream implementation which stores characters in an internal array. + * + * @author Xavier De Cock <xdecock@gmail.com> + */ +class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream +{ + /** + * The char reader (lazy-loaded) for the current charset. + * + * @var Swift_CharacterReader + */ + private $charReader; + + /** + * A factory for creating CharacterReader instances. + * + * @var Swift_CharacterReaderFactory + */ + private $charReaderFactory; + + /** + * The character set this stream is using. + * + * @var string + */ + private $charset; + + /** + * The data's stored as-is. + * + * @var string + */ + private $datas = ''; + + /** + * Number of bytes in the stream. + * + * @var int + */ + private $datasSize = 0; + + /** + * Map. + * + * @var mixed + */ + private $map; + + /** + * Map Type. + * + * @var int + */ + private $mapType = 0; + + /** + * Number of characters in the stream. + * + * @var int + */ + private $charCount = 0; + + /** + * Position in the stream. + * + * @var int + */ + private $currentPos = 0; + + /** + * Constructor. + * + * @param string $charset + */ + public function __construct(Swift_CharacterReaderFactory $factory, $charset) + { + $this->setCharacterReaderFactory($factory); + $this->setCharacterSet($charset); + } + + /* -- Changing parameters of the stream -- */ + + /** + * Set the character set used in this CharacterStream. + * + * @param string $charset + */ + public function setCharacterSet($charset) + { + $this->charset = $charset; + $this->charReader = null; + $this->mapType = 0; + } + + /** + * Set the CharacterReaderFactory for multi charset support. + */ + public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) + { + $this->charReaderFactory = $factory; + } + + /** + * @see Swift_CharacterStream::flushContents() + */ + public function flushContents() + { + $this->datas = null; + $this->map = null; + $this->charCount = 0; + $this->currentPos = 0; + $this->datasSize = 0; + } + + /** + * @see Swift_CharacterStream::importByteStream() + */ + public function importByteStream(Swift_OutputByteStream $os) + { + $this->flushContents(); + $blocks = 512; + $os->setReadPointer(0); + while (false !== ($read = $os->read($blocks))) { + $this->write($read); + } + } + + /** + * @see Swift_CharacterStream::importString() + * + * @param string $string + */ + public function importString($string) + { + $this->flushContents(); + $this->write($string); + } + + /** + * @see Swift_CharacterStream::read() + * + * @param int $length + * + * @return string + */ + public function read($length) + { + if ($this->currentPos >= $this->charCount) { + return false; + } + $ret = false; + $length = ($this->currentPos + $length > $this->charCount) ? $this->charCount - $this->currentPos : $length; + switch ($this->mapType) { + case Swift_CharacterReader::MAP_TYPE_FIXED_LEN: + $len = $length * $this->map; + $ret = substr($this->datas, + $this->currentPos * $this->map, + $len); + $this->currentPos += $length; + break; + + case Swift_CharacterReader::MAP_TYPE_INVALID: + $ret = ''; + for (; $this->currentPos < $length; ++$this->currentPos) { + if (isset($this->map[$this->currentPos])) { + $ret .= '?'; + } else { + $ret .= $this->datas[$this->currentPos]; + } + } + break; + + case Swift_CharacterReader::MAP_TYPE_POSITIONS: + $end = $this->currentPos + $length; + $end = $end > $this->charCount ? $this->charCount : $end; + $ret = ''; + $start = 0; + if ($this->currentPos > 0) { + $start = $this->map['p'][$this->currentPos - 1]; + } + $to = $start; + for (; $this->currentPos < $end; ++$this->currentPos) { + if (isset($this->map['i'][$this->currentPos])) { + $ret .= substr($this->datas, $start, $to - $start).'?'; + $start = $this->map['p'][$this->currentPos]; + } else { + $to = $this->map['p'][$this->currentPos]; + } + } + $ret .= substr($this->datas, $start, $to - $start); + break; + } + + return $ret; + } + + /** + * @see Swift_CharacterStream::readBytes() + * + * @param int $length + * + * @return int[] + */ + public function readBytes($length) + { + $read = $this->read($length); + if (false !== $read) { + $ret = array_map('ord', str_split($read, 1)); + + return $ret; + } + + return false; + } + + /** + * @see Swift_CharacterStream::setPointer() + * + * @param int $charOffset + */ + public function setPointer($charOffset) + { + if ($this->charCount < $charOffset) { + $charOffset = $this->charCount; + } + $this->currentPos = $charOffset; + } + + /** + * @see Swift_CharacterStream::write() + * + * @param string $chars + */ + public function write($chars) + { + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory->getReaderFor( + $this->charset); + $this->map = []; + $this->mapType = $this->charReader->getMapType(); + } + $ignored = ''; + $this->datas .= $chars; + $this->charCount += $this->charReader->getCharPositions(substr($this->datas, $this->datasSize), $this->datasSize, $this->map, $ignored); + if (false !== $ignored) { + $this->datasSize = \strlen($this->datas) - \strlen($ignored); + } else { + $this->datasSize = \strlen($this->datas); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php new file mode 100644 index 0000000..a711bac --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php @@ -0,0 +1,63 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Base class for Spools (implements time and message limits). + * + * @author Fabien Potencier + */ +abstract class Swift_ConfigurableSpool implements Swift_Spool +{ + /** The maximum number of messages to send per flush */ + private $message_limit; + + /** The time limit per flush */ + private $time_limit; + + /** + * Sets the maximum number of messages to send per flush. + * + * @param int $limit + */ + public function setMessageLimit($limit) + { + $this->message_limit = (int) $limit; + } + + /** + * Gets the maximum number of messages to send per flush. + * + * @return int The limit + */ + public function getMessageLimit() + { + return $this->message_limit; + } + + /** + * Sets the time limit (in seconds) per flush. + * + * @param int $limit The limit + */ + public function setTimeLimit($limit) + { + $this->time_limit = (int) $limit; + } + + /** + * Gets the time limit (in seconds) per flush. + * + * @return int The limit + */ + public function getTimeLimit() + { + return $this->time_limit; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php new file mode 100644 index 0000000..3cc885e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php @@ -0,0 +1,387 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Dependency Injection container. + * + * @author Chris Corbyn + */ +class Swift_DependencyContainer +{ + /** Constant for literal value types */ + const TYPE_VALUE = 0x00001; + + /** Constant for new instance types */ + const TYPE_INSTANCE = 0x00010; + + /** Constant for shared instance types */ + const TYPE_SHARED = 0x00100; + + /** Constant for aliases */ + const TYPE_ALIAS = 0x01000; + + /** Constant for arrays */ + const TYPE_ARRAY = 0x10000; + + /** Singleton instance */ + private static $instance = null; + + /** The data container */ + private $store = []; + + /** The current endpoint in the data container */ + private $endPoint; + + /** + * Constructor should not be used. + * + * Use {@link getInstance()} instead. + */ + public function __construct() + { + } + + /** + * Returns a singleton of the DependencyContainer. + * + * @return self + */ + public static function getInstance() + { + if (!isset(self::$instance)) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * List the names of all items stored in the Container. + * + * @return array + */ + public function listItems() + { + return array_keys($this->store); + } + + /** + * Test if an item is registered in this container with the given name. + * + * @see register() + * + * @param string $itemName + * + * @return bool + */ + public function has($itemName) + { + return \array_key_exists($itemName, $this->store) + && isset($this->store[$itemName]['lookupType']); + } + + /** + * Lookup the item with the given $itemName. + * + * @see register() + * + * @param string $itemName + * + * @return mixed + * + * @throws Swift_DependencyException If the dependency is not found + */ + public function lookup($itemName) + { + if (!$this->has($itemName)) { + throw new Swift_DependencyException('Cannot lookup dependency "'.$itemName.'" since it is not registered.'); + } + + switch ($this->store[$itemName]['lookupType']) { + case self::TYPE_ALIAS: + return $this->createAlias($itemName); + case self::TYPE_VALUE: + return $this->getValue($itemName); + case self::TYPE_INSTANCE: + return $this->createNewInstance($itemName); + case self::TYPE_SHARED: + return $this->createSharedInstance($itemName); + case self::TYPE_ARRAY: + return $this->createDependenciesFor($itemName); + } + } + + /** + * Create an array of arguments passed to the constructor of $itemName. + * + * @param string $itemName + * + * @return array + */ + public function createDependenciesFor($itemName) + { + $args = []; + if (isset($this->store[$itemName]['args'])) { + $args = $this->resolveArgs($this->store[$itemName]['args']); + } + + return $args; + } + + /** + * Register a new dependency with $itemName. + * + * This method returns the current DependencyContainer instance because it + * requires the use of the fluid interface to set the specific details for the + * dependency. + * + * @see asNewInstanceOf(), asSharedInstanceOf(), asValue() + * + * @param string $itemName + * + * @return $this + */ + public function register($itemName) + { + $this->store[$itemName] = []; + $this->endPoint = &$this->store[$itemName]; + + return $this; + } + + /** + * Specify the previously registered item as a literal value. + * + * {@link register()} must be called before this will work. + * + * @param mixed $value + * + * @return $this + */ + public function asValue($value) + { + $endPoint = &$this->getEndPoint(); + $endPoint['lookupType'] = self::TYPE_VALUE; + $endPoint['value'] = $value; + + return $this; + } + + /** + * Specify the previously registered item as an alias of another item. + * + * @param string $lookup + * + * @return $this + */ + public function asAliasOf($lookup) + { + $endPoint = &$this->getEndPoint(); + $endPoint['lookupType'] = self::TYPE_ALIAS; + $endPoint['ref'] = $lookup; + + return $this; + } + + /** + * Specify the previously registered item as a new instance of $className. + * + * {@link register()} must be called before this will work. + * Any arguments can be set with {@link withDependencies()}, + * {@link addConstructorValue()} or {@link addConstructorLookup()}. + * + * @see withDependencies(), addConstructorValue(), addConstructorLookup() + * + * @param string $className + * + * @return $this + */ + public function asNewInstanceOf($className) + { + $endPoint = &$this->getEndPoint(); + $endPoint['lookupType'] = self::TYPE_INSTANCE; + $endPoint['className'] = $className; + + return $this; + } + + /** + * Specify the previously registered item as a shared instance of $className. + * + * {@link register()} must be called before this will work. + * + * @param string $className + * + * @return $this + */ + public function asSharedInstanceOf($className) + { + $endPoint = &$this->getEndPoint(); + $endPoint['lookupType'] = self::TYPE_SHARED; + $endPoint['className'] = $className; + + return $this; + } + + /** + * Specify the previously registered item as array of dependencies. + * + * {@link register()} must be called before this will work. + * + * @return $this + */ + public function asArray() + { + $endPoint = &$this->getEndPoint(); + $endPoint['lookupType'] = self::TYPE_ARRAY; + + return $this; + } + + /** + * Specify a list of injected dependencies for the previously registered item. + * + * This method takes an array of lookup names. + * + * @see addConstructorValue(), addConstructorLookup() + * + * @return $this + */ + public function withDependencies(array $lookups) + { + $endPoint = &$this->getEndPoint(); + $endPoint['args'] = []; + foreach ($lookups as $lookup) { + $this->addConstructorLookup($lookup); + } + + return $this; + } + + /** + * Specify a literal (non looked up) value for the constructor of the + * previously registered item. + * + * @see withDependencies(), addConstructorLookup() + * + * @param mixed $value + * + * @return $this + */ + public function addConstructorValue($value) + { + $endPoint = &$this->getEndPoint(); + if (!isset($endPoint['args'])) { + $endPoint['args'] = []; + } + $endPoint['args'][] = ['type' => 'value', 'item' => $value]; + + return $this; + } + + /** + * Specify a dependency lookup for the constructor of the previously + * registered item. + * + * @see withDependencies(), addConstructorValue() + * + * @param string $lookup + * + * @return $this + */ + public function addConstructorLookup($lookup) + { + $endPoint = &$this->getEndPoint(); + if (!isset($this->endPoint['args'])) { + $endPoint['args'] = []; + } + $endPoint['args'][] = ['type' => 'lookup', 'item' => $lookup]; + + return $this; + } + + /** Get the literal value with $itemName */ + private function getValue($itemName) + { + return $this->store[$itemName]['value']; + } + + /** Resolve an alias to another item */ + private function createAlias($itemName) + { + return $this->lookup($this->store[$itemName]['ref']); + } + + /** Create a fresh instance of $itemName */ + private function createNewInstance($itemName) + { + $reflector = new ReflectionClass($this->store[$itemName]['className']); + if ($reflector->getConstructor()) { + return $reflector->newInstanceArgs( + $this->createDependenciesFor($itemName) + ); + } + + return $reflector->newInstance(); + } + + /** Create and register a shared instance of $itemName */ + private function createSharedInstance($itemName) + { + if (!isset($this->store[$itemName]['instance'])) { + $this->store[$itemName]['instance'] = $this->createNewInstance($itemName); + } + + return $this->store[$itemName]['instance']; + } + + /** Get the current endpoint in the store */ + private function &getEndPoint() + { + if (!isset($this->endPoint)) { + throw new BadMethodCallException('Component must first be registered by calling register()'); + } + + return $this->endPoint; + } + + /** Get an argument list with dependencies resolved */ + private function resolveArgs(array $args) + { + $resolved = []; + foreach ($args as $argDefinition) { + switch ($argDefinition['type']) { + case 'lookup': + $resolved[] = $this->lookupRecursive($argDefinition['item']); + break; + case 'value': + $resolved[] = $argDefinition['item']; + break; + } + } + + return $resolved; + } + + /** Resolve a single dependency with an collections */ + private function lookupRecursive($item) + { + if (\is_array($item)) { + $collection = []; + foreach ($item as $k => $v) { + $collection[$k] = $this->lookupRecursive($v); + } + + return $collection; + } + + return $this->lookup($item); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php new file mode 100644 index 0000000..799d38d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * DependencyException gets thrown when a requested dependency is missing. + * + * @author Chris Corbyn + */ +class Swift_DependencyException extends Swift_SwiftException +{ + /** + * Create a new DependencyException with $message. + * + * @param string $message + */ + public function __construct($message) + { + parent::__construct($message); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/EmbeddedFile.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/EmbeddedFile.php new file mode 100644 index 0000000..30fc68a --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/EmbeddedFile.php @@ -0,0 +1,53 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An embedded file, in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile +{ + /** + * Create a new EmbeddedFile. + * + * Details may be optionally provided to the constructor. + * + * @param string|Swift_OutputByteStream $data + * @param string $filename + * @param string $contentType + */ + public function __construct($data = null, $filename = null, $contentType = null) + { + \call_user_func_array( + [$this, 'Swift_Mime_EmbeddedFile::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('mime.embeddedfile') + ); + + $this->setBody($data); + $this->setFilename($filename); + if ($contentType) { + $this->setContentType($contentType); + } + } + + /** + * Create a new EmbeddedFile from a filesystem path. + * + * @param string $path + * + * @return Swift_Mime_EmbeddedFile + */ + public static function fromPath($path) + { + return (new self())->setFile(new Swift_ByteStream_FileByteStream($path)); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php new file mode 100644 index 0000000..2073abc --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php @@ -0,0 +1,28 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Interface for all Encoder schemes. + * + * @author Chris Corbyn + */ +interface Swift_Encoder extends Swift_Mime_CharsetObserver +{ + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset if first line needs to be shorter + * @param int $maxLineLength - 0 indicates the default length for this encoding + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Base64Encoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Base64Encoder.php new file mode 100644 index 0000000..b1eedaa --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Base64Encoder.php @@ -0,0 +1,58 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Base 64 Encoding in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Encoder_Base64Encoder implements Swift_Encoder +{ + /** + * Takes an unencoded string and produces a Base64 encoded string from it. + * + * Base64 encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + * + * @param string $string to encode + * @param int $firstLineOffset + * @param int $maxLineLength optional, 0 indicates the default of 76 bytes + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if (0 >= $maxLineLength || 76 < $maxLineLength) { + $maxLineLength = 76; + } + + $encodedString = base64_encode($string ?? ''); + $firstLine = ''; + + if (0 != $firstLineOffset) { + $firstLine = substr( + $encodedString, 0, $maxLineLength - $firstLineOffset + )."\r\n"; + $encodedString = substr( + $encodedString, $maxLineLength - $firstLineOffset + ); + } + + return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n")); + } + + /** + * Does nothing. + */ + public function charsetChanged($charset) + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php new file mode 100644 index 0000000..f078d6d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php @@ -0,0 +1,300 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Quoted Printable (QP) Encoding in Swift Mailer. + * + * Possibly the most accurate RFC 2045 QP implementation found in PHP. + * + * @author Chris Corbyn + */ +class Swift_Encoder_QpEncoder implements Swift_Encoder +{ + /** + * The CharacterStream used for reading characters (as opposed to bytes). + * + * @var Swift_CharacterStream + */ + protected $charStream; + + /** + * A filter used if input should be canonicalized. + * + * @var Swift_StreamFilter + */ + protected $filter; + + /** + * Pre-computed QP for HUGE optimization. + * + * @var string[] + */ + protected static $qpMap = [ + 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', + 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', + 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', + 15 => '=0F', 16 => '=10', 17 => '=11', 18 => '=12', 19 => '=13', + 20 => '=14', 21 => '=15', 22 => '=16', 23 => '=17', 24 => '=18', + 25 => '=19', 26 => '=1A', 27 => '=1B', 28 => '=1C', 29 => '=1D', + 30 => '=1E', 31 => '=1F', 32 => '=20', 33 => '=21', 34 => '=22', + 35 => '=23', 36 => '=24', 37 => '=25', 38 => '=26', 39 => '=27', + 40 => '=28', 41 => '=29', 42 => '=2A', 43 => '=2B', 44 => '=2C', + 45 => '=2D', 46 => '=2E', 47 => '=2F', 48 => '=30', 49 => '=31', + 50 => '=32', 51 => '=33', 52 => '=34', 53 => '=35', 54 => '=36', + 55 => '=37', 56 => '=38', 57 => '=39', 58 => '=3A', 59 => '=3B', + 60 => '=3C', 61 => '=3D', 62 => '=3E', 63 => '=3F', 64 => '=40', + 65 => '=41', 66 => '=42', 67 => '=43', 68 => '=44', 69 => '=45', + 70 => '=46', 71 => '=47', 72 => '=48', 73 => '=49', 74 => '=4A', + 75 => '=4B', 76 => '=4C', 77 => '=4D', 78 => '=4E', 79 => '=4F', + 80 => '=50', 81 => '=51', 82 => '=52', 83 => '=53', 84 => '=54', + 85 => '=55', 86 => '=56', 87 => '=57', 88 => '=58', 89 => '=59', + 90 => '=5A', 91 => '=5B', 92 => '=5C', 93 => '=5D', 94 => '=5E', + 95 => '=5F', 96 => '=60', 97 => '=61', 98 => '=62', 99 => '=63', + 100 => '=64', 101 => '=65', 102 => '=66', 103 => '=67', 104 => '=68', + 105 => '=69', 106 => '=6A', 107 => '=6B', 108 => '=6C', 109 => '=6D', + 110 => '=6E', 111 => '=6F', 112 => '=70', 113 => '=71', 114 => '=72', + 115 => '=73', 116 => '=74', 117 => '=75', 118 => '=76', 119 => '=77', + 120 => '=78', 121 => '=79', 122 => '=7A', 123 => '=7B', 124 => '=7C', + 125 => '=7D', 126 => '=7E', 127 => '=7F', 128 => '=80', 129 => '=81', + 130 => '=82', 131 => '=83', 132 => '=84', 133 => '=85', 134 => '=86', + 135 => '=87', 136 => '=88', 137 => '=89', 138 => '=8A', 139 => '=8B', + 140 => '=8C', 141 => '=8D', 142 => '=8E', 143 => '=8F', 144 => '=90', + 145 => '=91', 146 => '=92', 147 => '=93', 148 => '=94', 149 => '=95', + 150 => '=96', 151 => '=97', 152 => '=98', 153 => '=99', 154 => '=9A', + 155 => '=9B', 156 => '=9C', 157 => '=9D', 158 => '=9E', 159 => '=9F', + 160 => '=A0', 161 => '=A1', 162 => '=A2', 163 => '=A3', 164 => '=A4', + 165 => '=A5', 166 => '=A6', 167 => '=A7', 168 => '=A8', 169 => '=A9', + 170 => '=AA', 171 => '=AB', 172 => '=AC', 173 => '=AD', 174 => '=AE', + 175 => '=AF', 176 => '=B0', 177 => '=B1', 178 => '=B2', 179 => '=B3', + 180 => '=B4', 181 => '=B5', 182 => '=B6', 183 => '=B7', 184 => '=B8', + 185 => '=B9', 186 => '=BA', 187 => '=BB', 188 => '=BC', 189 => '=BD', + 190 => '=BE', 191 => '=BF', 192 => '=C0', 193 => '=C1', 194 => '=C2', + 195 => '=C3', 196 => '=C4', 197 => '=C5', 198 => '=C6', 199 => '=C7', + 200 => '=C8', 201 => '=C9', 202 => '=CA', 203 => '=CB', 204 => '=CC', + 205 => '=CD', 206 => '=CE', 207 => '=CF', 208 => '=D0', 209 => '=D1', + 210 => '=D2', 211 => '=D3', 212 => '=D4', 213 => '=D5', 214 => '=D6', + 215 => '=D7', 216 => '=D8', 217 => '=D9', 218 => '=DA', 219 => '=DB', + 220 => '=DC', 221 => '=DD', 222 => '=DE', 223 => '=DF', 224 => '=E0', + 225 => '=E1', 226 => '=E2', 227 => '=E3', 228 => '=E4', 229 => '=E5', + 230 => '=E6', 231 => '=E7', 232 => '=E8', 233 => '=E9', 234 => '=EA', + 235 => '=EB', 236 => '=EC', 237 => '=ED', 238 => '=EE', 239 => '=EF', + 240 => '=F0', 241 => '=F1', 242 => '=F2', 243 => '=F3', 244 => '=F4', + 245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9', + 250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE', + 255 => '=FF', + ]; + + protected static $safeMapShare = []; + + /** + * A map of non-encoded ascii characters. + * + * @var string[] + */ + protected $safeMap = []; + + /** + * Creates a new QpEncoder for the given CharacterStream. + * + * @param Swift_CharacterStream $charStream to use for reading characters + * @param Swift_StreamFilter $filter if input should be canonicalized + */ + public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null) + { + $this->charStream = $charStream; + if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) { + $this->initSafeMap(); + self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap; + } else { + $this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()]; + } + $this->filter = $filter; + } + + public function __sleep() + { + return ['charStream', 'filter']; + } + + public function __wakeup() + { + if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) { + $this->initSafeMap(); + self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap; + } else { + $this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()]; + } + } + + protected function getSafeMapShareId() + { + return static::class; + } + + protected function initSafeMap() + { + foreach (array_merge( + [0x09, 0x20], range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { + $this->safeMap[$byte] = \chr($byte); + } + } + + /** + * Takes an unencoded string and produces a QP encoded string from it. + * + * QP encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + * + * @param string $string to encode + * @param int $firstLineOffset optional + * @param int $maxLineLength optional 0 indicates the default of 76 chars + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($maxLineLength > 76 || $maxLineLength <= 0) { + $maxLineLength = 76; + } + + $thisLineLength = $maxLineLength - $firstLineOffset; + + $lines = []; + $lNo = 0; + $lines[$lNo] = ''; + $currentLine = &$lines[$lNo++]; + $size = $lineLen = 0; + + $this->charStream->flushContents(); + $this->charStream->importString($string); + + // Fetching more than 4 chars at one is slower, as is fetching fewer bytes + // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 + // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes + while (false !== $bytes = $this->nextSequence()) { + // If we're filtering the input + if (isset($this->filter)) { + // If we can't filter because we need more bytes + while ($this->filter->shouldBuffer($bytes)) { + // Then collect bytes into the buffer + if (false === $moreBytes = $this->nextSequence(1)) { + break; + } + + foreach ($moreBytes as $b) { + $bytes[] = $b; + } + } + // And filter them + $bytes = $this->filter->filter($bytes); + } + + $enc = $this->encodeByteSequence($bytes, $size); + + $i = strpos($enc, '=0D=0A'); + $newLineLength = $lineLen + (false === $i ? $size : $i); + + if ($currentLine && $newLineLength >= $thisLineLength) { + $lines[$lNo] = ''; + $currentLine = &$lines[$lNo++]; + $thisLineLength = $maxLineLength; + $lineLen = 0; + } + + $currentLine .= $enc; + + if (false === $i) { + $lineLen += $size; + } else { + // 6 is the length of '=0D=0A'. + $lineLen = $size - strrpos($enc, '=0D=0A') - 6; + } + } + + return $this->standardize(implode("=\r\n", $lines)); + } + + /** + * Updates the charset used. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->charStream->setCharacterSet($charset); + } + + /** + * Encode the given byte array into a verbatim QP form. + * + * @param int[] $bytes + * @param int $size + * + * @return string + */ + protected function encodeByteSequence(array $bytes, &$size) + { + $ret = ''; + $size = 0; + foreach ($bytes as $b) { + if (isset($this->safeMap[$b])) { + $ret .= $this->safeMap[$b]; + ++$size; + } else { + $ret .= self::$qpMap[$b]; + $size += 3; + } + } + + return $ret; + } + + /** + * Get the next sequence of bytes to read from the char stream. + * + * @param int $size number of bytes to read + * + * @return int[] + */ + protected function nextSequence($size = 4) + { + return $this->charStream->readBytes($size); + } + + /** + * Make sure CRLF is correct and HT/SPACE are in valid places. + * + * @param string $string + * + * @return string + */ + protected function standardize($string) + { + $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], + ["=09\r\n", "=20\r\n", "\r\n"], $string + ); + switch ($end = \ord(substr($string, -1))) { + case 0x09: + case 0x20: + $string = substr_replace($string, self::$qpMap[$end], -1); + } + + return $string; + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + $this->charStream = clone $this->charStream; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php new file mode 100644 index 0000000..7eac368 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php @@ -0,0 +1,90 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles RFC 2231 specified Encoding in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder +{ + /** + * A character stream to use when reading a string as characters instead of bytes. + * + * @var Swift_CharacterStream + */ + private $charStream; + + /** + * Creates a new Rfc2231Encoder using the given character stream instance. + */ + public function __construct(Swift_CharacterStream $charStream) + { + $this->charStream = $charStream; + } + + /** + * Takes an unencoded string and produces a string encoded according to + * RFC 2231 from it. + * + * @param string $string + * @param int $firstLineOffset + * @param int $maxLineLength optional, 0 indicates the default of 75 bytes + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + $lines = []; + $lineCount = 0; + $lines[] = ''; + $currentLine = &$lines[$lineCount++]; + + if (0 >= $maxLineLength) { + $maxLineLength = 75; + } + + $this->charStream->flushContents(); + $this->charStream->importString($string); + + $thisLineLength = $maxLineLength - $firstLineOffset; + + while (false !== $char = $this->charStream->read(4)) { + $encodedChar = rawurlencode($char); + if (0 != \strlen($currentLine) + && \strlen($currentLine.$encodedChar) > $thisLineLength) { + $lines[] = ''; + $currentLine = &$lines[$lineCount++]; + $thisLineLength = $maxLineLength; + } + $currentLine .= $encodedChar; + } + + return implode("\r\n", $lines); + } + + /** + * Updates the charset used. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->charStream->setCharacterSet($charset); + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + $this->charStream = clone $this->charStream; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php new file mode 100644 index 0000000..18994c1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php @@ -0,0 +1,64 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Generated when a command is sent over an SMTP connection. + * + * @author Chris Corbyn + */ +class Swift_Events_CommandEvent extends Swift_Events_EventObject +{ + /** + * The command sent to the server. + * + * @var string + */ + private $command; + + /** + * An array of codes which a successful response will contain. + * + * @var int[] + */ + private $successCodes = []; + + /** + * Create a new CommandEvent for $source with $command. + * + * @param string $command + * @param array $successCodes + */ + public function __construct(Swift_Transport $source, $command, $successCodes = []) + { + parent::__construct($source); + $this->command = $command; + $this->successCodes = $successCodes; + } + + /** + * Get the command which was sent to the server. + * + * @return string + */ + public function getCommand() + { + return $this->command; + } + + /** + * Get the numeric response codes which indicate success for this command. + * + * @return int[] + */ + public function getSuccessCodes() + { + return $this->successCodes; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php new file mode 100644 index 0000000..b158eab --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Listens for Transports to send commands to the server. + * + * @author Chris Corbyn + */ +interface Swift_Events_CommandListener extends Swift_Events_EventListener +{ + /** + * Invoked immediately following a command being sent. + */ + public function commandSent(Swift_Events_CommandEvent $evt); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/Event.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/Event.php new file mode 100644 index 0000000..720b156 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/Event.php @@ -0,0 +1,38 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * The minimum interface for an Event. + * + * @author Chris Corbyn + */ +interface Swift_Events_Event +{ + /** + * Get the source object of this event. + * + * @return object + */ + public function getSource(); + + /** + * Prevent this Event from bubbling any further up the stack. + * + * @param bool $cancel, optional + */ + public function cancelBubble($cancel = true); + + /** + * Returns true if this Event will not bubble any further up the stack. + * + * @return bool + */ + public function bubbleCancelled(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php new file mode 100644 index 0000000..df25a12 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php @@ -0,0 +1,70 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Interface for the EventDispatcher which handles the event dispatching layer. + * + * @author Chris Corbyn + */ +interface Swift_Events_EventDispatcher +{ + /** + * Create a new SendEvent for $source and $message. + * + * @return Swift_Events_SendEvent + */ + public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message); + + /** + * Create a new CommandEvent for $source and $command. + * + * @param string $command That will be executed + * @param array $successCodes That are needed + * + * @return Swift_Events_CommandEvent + */ + public function createCommandEvent(Swift_Transport $source, $command, $successCodes = []); + + /** + * Create a new ResponseEvent for $source and $response. + * + * @param string $response + * @param bool $valid If the response is valid + * + * @return Swift_Events_ResponseEvent + */ + public function createResponseEvent(Swift_Transport $source, $response, $valid); + + /** + * Create a new TransportChangeEvent for $source. + * + * @return Swift_Events_TransportChangeEvent + */ + public function createTransportChangeEvent(Swift_Transport $source); + + /** + * Create a new TransportExceptionEvent for $source. + * + * @return Swift_Events_TransportExceptionEvent + */ + public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex); + + /** + * Bind an event listener to this dispatcher. + */ + public function bindEventListener(Swift_Events_EventListener $listener); + + /** + * Dispatch the given Event to all suitable listeners. + * + * @param string $target method + */ + public function dispatchEvent(Swift_Events_EventObject $evt, $target); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventListener.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventListener.php new file mode 100644 index 0000000..5129095 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventListener.php @@ -0,0 +1,18 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An identity interface which all EventListeners must extend. + * + * @author Chris Corbyn + */ +interface Swift_Events_EventListener +{ +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventObject.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventObject.php new file mode 100644 index 0000000..24a11f4 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventObject.php @@ -0,0 +1,61 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A base Event which all Event classes inherit from. + * + * @author Chris Corbyn + */ +class Swift_Events_EventObject implements Swift_Events_Event +{ + /** The source of this Event */ + private $source; + + /** The state of this Event (should it bubble up the stack?) */ + private $bubbleCancelled = false; + + /** + * Create a new EventObject originating at $source. + * + * @param object $source + */ + public function __construct($source) + { + $this->source = $source; + } + + /** + * Get the source object of this event. + * + * @return object + */ + public function getSource() + { + return $this->source; + } + + /** + * Prevent this Event from bubbling any further up the stack. + */ + public function cancelBubble($cancel = true) + { + $this->bubbleCancelled = $cancel; + } + + /** + * Returns true if this Event will not bubble any further up the stack. + * + * @return bool + */ + public function bubbleCancelled() + { + return $this->bubbleCancelled; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php new file mode 100644 index 0000000..ff7c371 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php @@ -0,0 +1,64 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Generated when a response is received on a SMTP connection. + * + * @author Chris Corbyn + */ +class Swift_Events_ResponseEvent extends Swift_Events_EventObject +{ + /** + * The overall result. + * + * @var bool + */ + private $valid; + + /** + * The response received from the server. + * + * @var string + */ + private $response; + + /** + * Create a new ResponseEvent for $source and $response. + * + * @param string $response + * @param bool $valid + */ + public function __construct(Swift_Transport $source, $response, $valid = false) + { + parent::__construct($source); + $this->response = $response; + $this->valid = $valid; + } + + /** + * Get the response which was received from the server. + * + * @return string + */ + public function getResponse() + { + return $this->response; + } + + /** + * Get the success status of this Event. + * + * @return bool + */ + public function isValid() + { + return $this->valid; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php new file mode 100644 index 0000000..85115a3 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Listens for responses from a remote SMTP server. + * + * @author Chris Corbyn + */ +interface Swift_Events_ResponseListener extends Swift_Events_EventListener +{ + /** + * Invoked immediately following a response coming back. + */ + public function responseReceived(Swift_Events_ResponseEvent $evt); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendEvent.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendEvent.php new file mode 100644 index 0000000..a435691 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendEvent.php @@ -0,0 +1,126 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Generated when a message is being sent. + * + * @author Chris Corbyn + */ +class Swift_Events_SendEvent extends Swift_Events_EventObject +{ + /** Sending has yet to occur */ + const RESULT_PENDING = 0x0001; + + /** Email is spooled, ready to be sent */ + const RESULT_SPOOLED = 0x0011; + + /** Sending was successful */ + const RESULT_SUCCESS = 0x0010; + + /** Sending worked, but there were some failures */ + const RESULT_TENTATIVE = 0x0100; + + /** Sending failed */ + const RESULT_FAILED = 0x1000; + + /** + * The Message being sent. + * + * @var Swift_Mime_SimpleMessage + */ + private $message; + + /** + * Any recipients which failed after sending. + * + * @var string[] + */ + private $failedRecipients = []; + + /** + * The overall result as a bitmask from the class constants. + * + * @var int + */ + private $result; + + /** + * Create a new SendEvent for $source and $message. + */ + public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $message) + { + parent::__construct($source); + $this->message = $message; + $this->result = self::RESULT_PENDING; + } + + /** + * Get the Transport used to send the Message. + * + * @return Swift_Transport + */ + public function getTransport() + { + return $this->getSource(); + } + + /** + * Get the Message being sent. + * + * @return Swift_Mime_SimpleMessage + */ + public function getMessage() + { + return $this->message; + } + + /** + * Set the array of addresses that failed in sending. + * + * @param array $recipients + */ + public function setFailedRecipients($recipients) + { + $this->failedRecipients = $recipients; + } + + /** + * Get an recipient addresses which were not accepted for delivery. + * + * @return string[] + */ + public function getFailedRecipients() + { + return $this->failedRecipients; + } + + /** + * Set the result of sending. + * + * @param int $result + */ + public function setResult($result) + { + $this->result = $result; + } + + /** + * Get the result of this Event. + * + * The return value is a bitmask from + * {@see RESULT_PENDING, RESULT_SUCCESS, RESULT_TENTATIVE, RESULT_FAILED} + * + * @return int + */ + public function getResult() + { + return $this->result; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php new file mode 100644 index 0000000..f7bf55e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Listens for Messages being sent from within the Transport system. + * + * @author Chris Corbyn + */ +interface Swift_Events_SendListener extends Swift_Events_EventListener +{ + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt); + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php new file mode 100644 index 0000000..6557103 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php @@ -0,0 +1,142 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * The EventDispatcher which handles the event dispatching layer. + * + * @author Chris Corbyn + */ +class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher +{ + /** A map of event types to their associated listener types */ + private $eventMap = []; + + /** Event listeners bound to this dispatcher */ + private $listeners = []; + + /** + * Create a new EventDispatcher. + */ + public function __construct() + { + $this->eventMap = [ + 'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener', + 'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener', + 'Swift_Events_SendEvent' => 'Swift_Events_SendListener', + 'Swift_Events_TransportChangeEvent' => 'Swift_Events_TransportChangeListener', + 'Swift_Events_TransportExceptionEvent' => 'Swift_Events_TransportExceptionListener', + ]; + } + + /** + * Create a new SendEvent for $source and $message. + * + * @return Swift_Events_SendEvent + */ + public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message) + { + return new Swift_Events_SendEvent($source, $message); + } + + /** + * Create a new CommandEvent for $source and $command. + * + * @param string $command That will be executed + * @param array $successCodes That are needed + * + * @return Swift_Events_CommandEvent + */ + public function createCommandEvent(Swift_Transport $source, $command, $successCodes = []) + { + return new Swift_Events_CommandEvent($source, $command, $successCodes); + } + + /** + * Create a new ResponseEvent for $source and $response. + * + * @param string $response + * @param bool $valid If the response is valid + * + * @return Swift_Events_ResponseEvent + */ + public function createResponseEvent(Swift_Transport $source, $response, $valid) + { + return new Swift_Events_ResponseEvent($source, $response, $valid); + } + + /** + * Create a new TransportChangeEvent for $source. + * + * @return Swift_Events_TransportChangeEvent + */ + public function createTransportChangeEvent(Swift_Transport $source) + { + return new Swift_Events_TransportChangeEvent($source); + } + + /** + * Create a new TransportExceptionEvent for $source. + * + * @return Swift_Events_TransportExceptionEvent + */ + public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex) + { + return new Swift_Events_TransportExceptionEvent($source, $ex); + } + + /** + * Bind an event listener to this dispatcher. + */ + public function bindEventListener(Swift_Events_EventListener $listener) + { + foreach ($this->listeners as $l) { + // Already loaded + if ($l === $listener) { + return; + } + } + $this->listeners[] = $listener; + } + + /** + * Dispatch the given Event to all suitable listeners. + * + * @param string $target method + */ + public function dispatchEvent(Swift_Events_EventObject $evt, $target) + { + $bubbleQueue = $this->prepareBubbleQueue($evt); + $this->bubble($bubbleQueue, $evt, $target); + } + + /** Queue listeners on a stack ready for $evt to be bubbled up it */ + private function prepareBubbleQueue(Swift_Events_EventObject $evt) + { + $bubbleQueue = []; + $evtClass = \get_class($evt); + foreach ($this->listeners as $listener) { + if (\array_key_exists($evtClass, $this->eventMap) + && ($listener instanceof $this->eventMap[$evtClass])) { + $bubbleQueue[] = $listener; + } + } + + return $bubbleQueue; + } + + /** Bubble $evt up the stack calling $target() on each listener */ + private function bubble(array &$bubbleQueue, Swift_Events_EventObject $evt, $target) + { + if (!$evt->bubbleCancelled() && $listener = array_shift($bubbleQueue)) { + $listener->$target($evt); + $this->bubble($bubbleQueue, $evt, $target); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php new file mode 100644 index 0000000..a8972fd --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Generated when the state of a Transport is changed (i.e. stopped/started). + * + * @author Chris Corbyn + */ +class Swift_Events_TransportChangeEvent extends Swift_Events_EventObject +{ + /** + * Get the Transport. + * + * @return Swift_Transport + */ + public function getTransport() + { + return $this->getSource(); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php new file mode 100644 index 0000000..4a7492b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Listens for changes within the Transport system. + * + * @author Chris Corbyn + */ +interface Swift_Events_TransportChangeListener extends Swift_Events_EventListener +{ + /** + * Invoked just before a Transport is started. + */ + public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt); + + /** + * Invoked immediately after the Transport is started. + */ + public function transportStarted(Swift_Events_TransportChangeEvent $evt); + + /** + * Invoked just before a Transport is stopped. + */ + public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt); + + /** + * Invoked immediately after the Transport is stopped. + */ + public function transportStopped(Swift_Events_TransportChangeEvent $evt); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php new file mode 100644 index 0000000..df442cc --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Generated when a TransportException is thrown from the Transport system. + * + * @author Chris Corbyn + */ +class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject +{ + /** + * The Exception thrown. + * + * @var Swift_TransportException + */ + private $exception; + + /** + * Create a new TransportExceptionEvent for $transport. + */ + public function __construct(Swift_Transport $transport, Swift_TransportException $ex) + { + parent::__construct($transport); + $this->exception = $ex; + } + + /** + * Get the TransportException thrown. + * + * @return Swift_TransportException + */ + public function getException() + { + return $this->exception; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php new file mode 100644 index 0000000..ad80eb0 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Listens for Exceptions thrown from within the Transport system. + * + * @author Chris Corbyn + */ +interface Swift_Events_TransportExceptionListener extends Swift_Events_EventListener +{ + /** + * Invoked as a TransportException is thrown in the Transport system. + */ + public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FailoverTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FailoverTransport.php new file mode 100644 index 0000000..af0be91 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FailoverTransport.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Contains a list of redundant Transports so when one fails, the next is used. + * + * @author Chris Corbyn + */ +class Swift_FailoverTransport extends Swift_Transport_FailoverTransport +{ + /** + * Creates a new FailoverTransport with $transports. + * + * @param Swift_Transport[] $transports + */ + public function __construct($transports = []) + { + \call_user_func_array( + [$this, 'Swift_Transport_FailoverTransport::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.failover') + ); + + $this->setTransports($transports); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php new file mode 100644 index 0000000..7af8471 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php @@ -0,0 +1,208 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages on the filesystem. + * + * @author Fabien Potencier + * @author Xavier De Cock <xdecock@gmail.com> + */ +class Swift_FileSpool extends Swift_ConfigurableSpool +{ + /** The spool directory */ + private $path; + + /** + * File WriteRetry Limit. + * + * @var int + */ + private $retryLimit = 10; + + /** + * Create a new FileSpool. + * + * @param string $path + * + * @throws Swift_IoException + */ + public function __construct($path) + { + $this->path = $path; + + if (!file_exists($this->path)) { + if (!mkdir($this->path, 0777, true)) { + throw new Swift_IoException(sprintf('Unable to create path "%s".', $this->path)); + } + } + } + + /** + * Tests if this Spool mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Spool mechanism. + */ + public function start() + { + } + + /** + * Stops this Spool mechanism. + */ + public function stop() + { + } + + /** + * Allow to manage the enqueuing retry limit. + * + * Default, is ten and allows over 64^20 different fileNames + * + * @param int $limit + */ + public function setRetryLimit($limit) + { + $this->retryLimit = $limit; + } + + /** + * Queues a message. + * + * @param Swift_Mime_SimpleMessage $message The message to store + * + * @throws Swift_IoException + * + * @return bool + */ + public function queueMessage(Swift_Mime_SimpleMessage $message) + { + $ser = serialize($message); + $fileName = $this->path.'/'.$this->getRandomString(10); + for ($i = 0; $i < $this->retryLimit; ++$i) { + /* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */ + $fp = @fopen($fileName.'.message', 'xb'); + if (false !== $fp) { + if (false === fwrite($fp, $ser)) { + return false; + } + + return fclose($fp); + } else { + /* The file already exists, we try a longer fileName */ + $fileName .= $this->getRandomString(1); + } + } + + throw new Swift_IoException(sprintf('Unable to create a file for enqueuing Message in "%s".', $this->path)); + } + + /** + * Execute a recovery if for any reason a process is sending for too long. + * + * @param int $timeout in second Defaults is for very slow smtp responses + */ + public function recover($timeout = 900) + { + foreach (new DirectoryIterator($this->path) as $file) { + $file = $file->getRealPath(); + + if ('.message.sending' == substr($file, -16)) { + $lockedtime = filectime($file); + if ((time() - $lockedtime) > $timeout) { + rename($file, substr($file, 0, -8)); + } + } + } + } + + /** + * Sends messages using the given transport instance. + * + * @param Swift_Transport $transport A transport instance + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent e-mail's + */ + public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) + { + $directoryIterator = new DirectoryIterator($this->path); + + /* Start the transport only if there are queued files to send */ + if (!$transport->isStarted()) { + foreach ($directoryIterator as $file) { + if ('.message' == substr($file->getRealPath(), -8)) { + $transport->start(); + break; + } + } + } + + $failedRecipients = (array) $failedRecipients; + $count = 0; + $time = time(); + foreach ($directoryIterator as $file) { + $file = $file->getRealPath(); + + if ('.message' != substr($file, -8)) { + continue; + } + + /* We try a rename, it's an atomic operation, and avoid locking the file */ + if (rename($file, $file.'.sending')) { + $message = unserialize(file_get_contents($file.'.sending')); + + $count += $transport->send($message, $failedRecipients); + + unlink($file.'.sending'); + } else { + /* This message has just been catched by another process */ + continue; + } + + if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) { + break; + } + + if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit()) { + break; + } + } + + return $count; + } + + /** + * Returns a random string needed to generate a fileName for the queue. + * + * @param int $count + * + * @return string + */ + protected function getRandomString($count) + { + // This string MUST stay FS safe, avoid special chars + $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'; + $ret = ''; + $strlen = \strlen($base); + for ($i = 0; $i < $count; ++$i) { + $ret .= $base[random_int(0, $strlen - 1)]; + } + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php new file mode 100644 index 0000000..0b24db1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An OutputByteStream which specifically reads from a file. + * + * @author Chris Corbyn + */ +interface Swift_FileStream extends Swift_OutputByteStream +{ + /** + * Get the complete path to the file. + * + * @return string + */ + public function getPath(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Filterable.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Filterable.php new file mode 100644 index 0000000..efa1b1d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Filterable.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Allows StreamFilters to operate on a stream. + * + * @author Chris Corbyn + */ +interface Swift_Filterable +{ + /** + * Add a new StreamFilter, referenced by $key. + * + * @param string $key + */ + public function addFilter(Swift_StreamFilter $filter, $key); + + /** + * Remove an existing filter using $key. + * + * @param string $key + */ + public function removeFilter($key); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/IdGenerator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/IdGenerator.php new file mode 100644 index 0000000..c845d85 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/IdGenerator.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Message ID generator. + */ +interface Swift_IdGenerator +{ + /** + * Returns a globally unique string to use for Message-ID or Content-ID. + * + * @return string + */ + public function generateId(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Image.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Image.php new file mode 100644 index 0000000..34c2535 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Image.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An image, embedded in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_Image extends Swift_EmbeddedFile +{ + /** + * Create a new EmbeddedFile. + * + * Details may be optionally provided to the constructor. + * + * @param string|Swift_OutputByteStream $data + * @param string $filename + * @param string $contentType + */ + public function __construct($data = null, $filename = null, $contentType = null) + { + parent::__construct($data, $filename, $contentType); + } + + /** + * Create a new Image from a filesystem path. + * + * @param string $path + * + * @return self + */ + public static function fromPath($path) + { + return (new self())->setFile(new Swift_ByteStream_FileByteStream($path)); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php new file mode 100644 index 0000000..379a5a1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php @@ -0,0 +1,75 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An abstract means of writing data. + * + * Classes implementing this interface may use a subsystem which requires less + * memory than working with large strings of data. + * + * @author Chris Corbyn + */ +interface Swift_InputByteStream +{ + /** + * Writes $bytes to the end of the stream. + * + * Writing may not happen immediately if the stream chooses to buffer. If + * you want to write these bytes with immediate effect, call {@link commit()} + * after calling write(). + * + * This method returns the sequence ID of the write (i.e. 1 for first, 2 for + * second, etc etc). + * + * @param string $bytes + * + * @throws Swift_IoException + * + * @return int + */ + public function write($bytes); + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + * + * @throws Swift_IoException + */ + public function commit(); + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @param Swift_InputByteStream $is + */ + public function bind(self $is); + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @param Swift_InputByteStream $is + */ + public function unbind(self $is); + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + */ + public function flushBuffers(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/IoException.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/IoException.php new file mode 100644 index 0000000..5452bd4 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/IoException.php @@ -0,0 +1,28 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * I/O Exception class. + * + * @author Chris Corbyn + */ +class Swift_IoException extends Swift_SwiftException +{ + /** + * Create a new IoException with $message. + * + * @param string $message + * @param int $code + */ + public function __construct($message, $code = 0, Exception $previous = null) + { + parent::__construct($message, $code, $previous); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache.php new file mode 100644 index 0000000..87f6a07 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache.php @@ -0,0 +1,104 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Provides a mechanism for storing data using two keys. + * + * @author Chris Corbyn + */ +interface Swift_KeyCache +{ + /** Mode for replacing existing cached data */ + const MODE_WRITE = 1; + + /** Mode for appending data to the end of existing cached data */ + const MODE_APPEND = 2; + + /** + * Set a string into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param string $string + * @param int $mode + */ + public function setString($nsKey, $itemKey, $string, $mode); + + /** + * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param int $mode + */ + public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode); + + /** + * Provides a ByteStream which when written to, writes data to $itemKey. + * + * NOTE: The stream will always write in append mode. + * If the optional third parameter is passed all writes will go through $is. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is optional input stream + * + * @return Swift_InputByteStream + */ + public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $is = null); + + /** + * Get data back out of the cache as a string. + * + * @param string $nsKey + * @param string $itemKey + * + * @return string + */ + public function getString($nsKey, $itemKey); + + /** + * Get data back out of the cache as a ByteStream. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is stream to write the data to + */ + public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is); + + /** + * Check if the given $itemKey exists in the namespace $nsKey. + * + * @param string $nsKey + * @param string $itemKey + * + * @return bool + */ + public function hasKey($nsKey, $itemKey); + + /** + * Clear data for $itemKey in the namespace $nsKey if it exists. + * + * @param string $nsKey + * @param string $itemKey + */ + public function clearKey($nsKey, $itemKey); + + /** + * Clear all data in the namespace $nsKey if it exists. + * + * @param string $nsKey + */ + public function clearAll($nsKey); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php new file mode 100644 index 0000000..e8fef1c --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php @@ -0,0 +1,197 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A basic KeyCache backed by an array. + * + * @author Chris Corbyn + */ +class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache +{ + /** + * Cache contents. + * + * @var array + */ + private $contents = []; + + /** + * An InputStream for cloning. + * + * @var Swift_KeyCache_KeyCacheInputStream + */ + private $stream; + + /** + * Create a new ArrayKeyCache with the given $stream for cloning to make + * InputByteStreams. + */ + public function __construct(Swift_KeyCache_KeyCacheInputStream $stream) + { + $this->stream = $stream; + } + + /** + * Set a string into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param string $string + * @param int $mode + */ + public function setString($nsKey, $itemKey, $string, $mode) + { + $this->prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $this->contents[$nsKey][$itemKey] = $string; + break; + case self::MODE_APPEND: + if (!$this->hasKey($nsKey, $itemKey)) { + $this->contents[$nsKey][$itemKey] = ''; + } + $this->contents[$nsKey][$itemKey] .= $string; + break; + default: + throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey); + } + } + + /** + * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param int $mode + */ + public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) + { + $this->prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $this->clearKey($nsKey, $itemKey); + // no break + case self::MODE_APPEND: + if (!$this->hasKey($nsKey, $itemKey)) { + $this->contents[$nsKey][$itemKey] = ''; + } + while (false !== $bytes = $os->read(8192)) { + $this->contents[$nsKey][$itemKey] .= $bytes; + } + break; + default: + throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey); + } + } + + /** + * Provides a ByteStream which when written to, writes data to $itemKey. + * + * NOTE: The stream will always write in append mode. + * + * @param string $nsKey + * @param string $itemKey + * + * @return Swift_InputByteStream + */ + public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) + { + $is = clone $this->stream; + $is->setKeyCache($this); + $is->setNsKey($nsKey); + $is->setItemKey($itemKey); + if (isset($writeThrough)) { + $is->setWriteThroughStream($writeThrough); + } + + return $is; + } + + /** + * Get data back out of the cache as a string. + * + * @param string $nsKey + * @param string $itemKey + * + * @return string + */ + public function getString($nsKey, $itemKey) + { + $this->prepareCache($nsKey); + if ($this->hasKey($nsKey, $itemKey)) { + return $this->contents[$nsKey][$itemKey]; + } + } + + /** + * Get data back out of the cache as a ByteStream. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is to write the data to + */ + public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) + { + $this->prepareCache($nsKey); + $is->write($this->getString($nsKey, $itemKey)); + } + + /** + * Check if the given $itemKey exists in the namespace $nsKey. + * + * @param string $nsKey + * @param string $itemKey + * + * @return bool + */ + public function hasKey($nsKey, $itemKey) + { + $this->prepareCache($nsKey); + + return \array_key_exists($itemKey, $this->contents[$nsKey]); + } + + /** + * Clear data for $itemKey in the namespace $nsKey if it exists. + * + * @param string $nsKey + * @param string $itemKey + */ + public function clearKey($nsKey, $itemKey) + { + unset($this->contents[$nsKey][$itemKey]); + } + + /** + * Clear all data in the namespace $nsKey if it exists. + * + * @param string $nsKey + */ + public function clearAll($nsKey) + { + unset($this->contents[$nsKey]); + } + + /** + * Initialize the namespace of $nsKey if needed. + * + * @param string $nsKey + */ + private function prepareCache($nsKey) + { + if (!\array_key_exists($nsKey, $this->contents)) { + $this->contents[$nsKey] = []; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php new file mode 100644 index 0000000..33b6367 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php @@ -0,0 +1,294 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A KeyCache which streams to and from disk. + * + * @author Chris Corbyn + */ +class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache +{ + /** Signal to place pointer at start of file */ + const POSITION_START = 0; + + /** Signal to place pointer at end of file */ + const POSITION_END = 1; + + /** Signal to leave pointer in whatever position it currently is */ + const POSITION_CURRENT = 2; + + /** + * An InputStream for cloning. + * + * @var Swift_KeyCache_KeyCacheInputStream + */ + private $stream; + + /** + * A path to write to. + * + * @var string + */ + private $path; + + /** + * Stored keys. + * + * @var array + */ + private $keys = []; + + /** + * Create a new DiskKeyCache with the given $stream for cloning to make + * InputByteStreams, and the given $path to save to. + * + * @param string $path to save to + */ + public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path) + { + $this->stream = $stream; + $this->path = $path; + } + + /** + * Set a string into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param string $string + * @param int $mode + * + * @throws Swift_IoException + */ + public function setString($nsKey, $itemKey, $string, $mode) + { + $this->prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); + break; + case self::MODE_APPEND: + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); + break; + default: + throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey); + break; + } + fwrite($fp, $string); + $this->freeHandle($nsKey, $itemKey); + } + + /** + * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param int $mode + * + * @throws Swift_IoException + */ + public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) + { + $this->prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); + break; + case self::MODE_APPEND: + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); + break; + default: + throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey); + break; + } + while (false !== $bytes = $os->read(8192)) { + fwrite($fp, $bytes); + } + $this->freeHandle($nsKey, $itemKey); + } + + /** + * Provides a ByteStream which when written to, writes data to $itemKey. + * + * NOTE: The stream will always write in append mode. + * + * @param string $nsKey + * @param string $itemKey + * + * @return Swift_InputByteStream + */ + public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) + { + $is = clone $this->stream; + $is->setKeyCache($this); + $is->setNsKey($nsKey); + $is->setItemKey($itemKey); + if (isset($writeThrough)) { + $is->setWriteThroughStream($writeThrough); + } + + return $is; + } + + /** + * Get data back out of the cache as a string. + * + * @param string $nsKey + * @param string $itemKey + * + * @throws Swift_IoException + * + * @return string + */ + public function getString($nsKey, $itemKey) + { + $this->prepareCache($nsKey); + if ($this->hasKey($nsKey, $itemKey)) { + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); + $str = ''; + while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { + $str .= $bytes; + } + $this->freeHandle($nsKey, $itemKey); + + return $str; + } + } + + /** + * Get data back out of the cache as a ByteStream. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is to write the data to + */ + public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) + { + if ($this->hasKey($nsKey, $itemKey)) { + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); + while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { + $is->write($bytes); + } + $this->freeHandle($nsKey, $itemKey); + } + } + + /** + * Check if the given $itemKey exists in the namespace $nsKey. + * + * @param string $nsKey + * @param string $itemKey + * + * @return bool + */ + public function hasKey($nsKey, $itemKey) + { + return is_file($this->path.'/'.$nsKey.'/'.$itemKey); + } + + /** + * Clear data for $itemKey in the namespace $nsKey if it exists. + * + * @param string $nsKey + * @param string $itemKey + */ + public function clearKey($nsKey, $itemKey) + { + if ($this->hasKey($nsKey, $itemKey)) { + $this->freeHandle($nsKey, $itemKey); + unlink($this->path.'/'.$nsKey.'/'.$itemKey); + } + } + + /** + * Clear all data in the namespace $nsKey if it exists. + * + * @param string $nsKey + */ + public function clearAll($nsKey) + { + if (\array_key_exists($nsKey, $this->keys)) { + foreach ($this->keys[$nsKey] as $itemKey => $null) { + $this->clearKey($nsKey, $itemKey); + } + if (is_dir($this->path.'/'.$nsKey)) { + rmdir($this->path.'/'.$nsKey); + } + unset($this->keys[$nsKey]); + } + } + + /** + * Initialize the namespace of $nsKey if needed. + * + * @param string $nsKey + */ + private function prepareCache($nsKey) + { + $cacheDir = $this->path.'/'.$nsKey; + if (!is_dir($cacheDir)) { + if (!mkdir($cacheDir)) { + throw new Swift_IoException('Failed to create cache directory '.$cacheDir); + } + $this->keys[$nsKey] = []; + } + } + + /** + * Get a file handle on the cache item. + * + * @param string $nsKey + * @param string $itemKey + * @param int $position + * + * @return resource + */ + private function getHandle($nsKey, $itemKey, $position) + { + if (!isset($this->keys[$nsKey][$itemKey])) { + $openMode = $this->hasKey($nsKey, $itemKey) ? 'r+b' : 'w+b'; + $fp = fopen($this->path.'/'.$nsKey.'/'.$itemKey, $openMode); + $this->keys[$nsKey][$itemKey] = $fp; + } + if (self::POSITION_START == $position) { + fseek($this->keys[$nsKey][$itemKey], 0, SEEK_SET); + } elseif (self::POSITION_END == $position) { + fseek($this->keys[$nsKey][$itemKey], 0, SEEK_END); + } + + return $this->keys[$nsKey][$itemKey]; + } + + private function freeHandle($nsKey, $itemKey) + { + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_CURRENT); + fclose($fp); + $this->keys[$nsKey][$itemKey] = null; + } + + /** + * Destructor. + */ + public function __destruct() + { + foreach ($this->keys as $nsKey => $null) { + $this->clearAll($nsKey); + } + } + + public function __wakeup() + { + $this->keys = []; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php new file mode 100644 index 0000000..be2dbba --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php @@ -0,0 +1,47 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Writes data to a KeyCache using a stream. + * + * @author Chris Corbyn + */ +interface Swift_KeyCache_KeyCacheInputStream extends Swift_InputByteStream +{ + /** + * Set the KeyCache to wrap. + */ + public function setKeyCache(Swift_KeyCache $keyCache); + + /** + * Set the nsKey which will be written to. + * + * @param string $nsKey + */ + public function setNsKey($nsKey); + + /** + * Set the itemKey which will be written to. + * + * @param string $itemKey + */ + public function setItemKey($itemKey); + + /** + * Specify a stream to write through for each write(). + */ + public function setWriteThroughStream(Swift_InputByteStream $is); + + /** + * Any implementation should be cloneable, allowing the clone to access a + * separate $nsKey and $itemKey. + */ + public function __clone(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/NullKeyCache.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/NullKeyCache.php new file mode 100644 index 0000000..957b1b2 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/NullKeyCache.php @@ -0,0 +1,113 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A null KeyCache that does not cache at all. + * + * @author Chris Corbyn + */ +class Swift_KeyCache_NullKeyCache implements Swift_KeyCache +{ + /** + * Set a string into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param string $string + * @param int $mode + */ + public function setString($nsKey, $itemKey, $string, $mode) + { + } + + /** + * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param int $mode + */ + public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) + { + } + + /** + * Provides a ByteStream which when written to, writes data to $itemKey. + * + * NOTE: The stream will always write in append mode. + * + * @param string $nsKey + * @param string $itemKey + * + * @return Swift_InputByteStream + */ + public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) + { + } + + /** + * Get data back out of the cache as a string. + * + * @param string $nsKey + * @param string $itemKey + * + * @return string + */ + public function getString($nsKey, $itemKey) + { + } + + /** + * Get data back out of the cache as a ByteStream. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is to write the data to + */ + public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) + { + } + + /** + * Check if the given $itemKey exists in the namespace $nsKey. + * + * @param string $nsKey + * @param string $itemKey + * + * @return bool + */ + public function hasKey($nsKey, $itemKey) + { + return false; + } + + /** + * Clear data for $itemKey in the namespace $nsKey if it exists. + * + * @param string $nsKey + * @param string $itemKey + */ + public function clearKey($nsKey, $itemKey) + { + } + + /** + * Clear all data in the namespace $nsKey if it exists. + * + * @param string $nsKey + */ + public function clearAll($nsKey) + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php new file mode 100644 index 0000000..03bab48 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php @@ -0,0 +1,123 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Writes data to a KeyCache using a stream. + * + * @author Chris Corbyn + */ +class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCacheInputStream +{ + /** The KeyCache being written to */ + private $keyCache; + + /** The nsKey of the KeyCache being written to */ + private $nsKey; + + /** The itemKey of the KeyCache being written to */ + private $itemKey; + + /** A stream to write through on each write() */ + private $writeThrough = null; + + /** + * Set the KeyCache to wrap. + */ + public function setKeyCache(Swift_KeyCache $keyCache) + { + $this->keyCache = $keyCache; + } + + /** + * Specify a stream to write through for each write(). + */ + public function setWriteThroughStream(Swift_InputByteStream $is) + { + $this->writeThrough = $is; + } + + /** + * Writes $bytes to the end of the stream. + * + * @param string $bytes + * @param Swift_InputByteStream $is optional + */ + public function write($bytes, Swift_InputByteStream $is = null) + { + $this->keyCache->setString( + $this->nsKey, $this->itemKey, $bytes, Swift_KeyCache::MODE_APPEND + ); + if (isset($is)) { + $is->write($bytes); + } + if (isset($this->writeThrough)) { + $this->writeThrough->write($bytes); + } + } + + /** + * Not used. + */ + public function commit() + { + } + + /** + * Not used. + */ + public function bind(Swift_InputByteStream $is) + { + } + + /** + * Not used. + */ + public function unbind(Swift_InputByteStream $is) + { + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + */ + public function flushBuffers() + { + $this->keyCache->clearKey($this->nsKey, $this->itemKey); + } + + /** + * Set the nsKey which will be written to. + * + * @param string $nsKey + */ + public function setNsKey($nsKey) + { + $this->nsKey = $nsKey; + } + + /** + * Set the itemKey which will be written to. + * + * @param string $itemKey + */ + public function setItemKey($itemKey) + { + $this->itemKey = $itemKey; + } + + /** + * Any implementation should be cloneable, allowing the clone to access a + * separate $nsKey and $itemKey. + */ + public function __clone() + { + $this->writeThrough = null; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php new file mode 100644 index 0000000..244b5f6 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Redundantly and rotationally uses several Transport implementations when sending. + * + * @author Chris Corbyn + */ +class Swift_LoadBalancedTransport extends Swift_Transport_LoadBalancedTransport +{ + /** + * Creates a new LoadBalancedTransport with $transports. + * + * @param array $transports + */ + public function __construct($transports = []) + { + \call_user_func_array( + [$this, 'Swift_Transport_LoadBalancedTransport::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.loadbalanced') + ); + + $this->setTransports($transports); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php new file mode 100644 index 0000000..5763007 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php @@ -0,0 +1,98 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Swift Mailer class. + * + * @author Chris Corbyn + */ +class Swift_Mailer +{ + /** The Transport used to send messages */ + private $transport; + + /** + * Create a new Mailer using $transport for delivery. + */ + public function __construct(Swift_Transport $transport) + { + $this->transport = $transport; + } + + /** + * Create a new class instance of one of the message services. + * + * For example 'mimepart' would create a 'message.mimepart' instance + * + * @param string $service + * + * @return object + */ + public function createMessage($service = 'message') + { + return Swift_DependencyContainer::getInstance() + ->lookup('message.'.$service); + } + + /** + * Send the given Message like it would be sent in a mail client. + * + * All recipients (with the exception of Bcc) will be able to see the other + * recipients this message was sent to. + * + * Recipient/sender data will be retrieved from the Message object. + * + * The return value is the number of recipients who were accepted for + * delivery. + * + * @param array $failedRecipients An array of failures by-reference + * + * @return int The number of successful recipients. Can be 0 which indicates failure + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $failedRecipients = (array) $failedRecipients; + + // FIXME: to be removed in 7.0 (as transport must now start itself on send) + if (!$this->transport->isStarted()) { + $this->transport->start(); + } + + $sent = 0; + + try { + $sent = $this->transport->send($message, $failedRecipients); + } catch (Swift_RfcComplianceException $e) { + foreach ($message->getTo() as $address => $name) { + $failedRecipients[] = $address; + } + } + + return $sent; + } + + /** + * Register a plugin using a known unique key (e.g. myPlugin). + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->transport->registerPlugin($plugin); + } + + /** + * The Transport used to send messages. + * + * @return Swift_Transport + */ + public function getTransport() + { + return $this->transport; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php new file mode 100644 index 0000000..19aa82a --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php @@ -0,0 +1,53 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Wraps a standard PHP array in an iterator. + * + * @author Chris Corbyn + */ +class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientIterator +{ + /** + * The list of recipients. + * + * @var array + */ + private $recipients = []; + + /** + * Create a new ArrayRecipientIterator from $recipients. + */ + public function __construct(array $recipients) + { + $this->recipients = $recipients; + } + + /** + * Returns true only if there are more recipients to send to. + * + * @return bool + */ + public function hasNext() + { + return !empty($this->recipients); + } + + /** + * Returns an array where the keys are the addresses of recipients and the + * values are the names. e.g. ('foo@bar' => 'Foo') or ('foo@bar' => NULL). + * + * @return array + */ + public function nextRecipient() + { + return array_splice($this->recipients, 0, 1); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php new file mode 100644 index 0000000..650f3ec --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php @@ -0,0 +1,32 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Provides an abstract way of specifying recipients for batch sending. + * + * @author Chris Corbyn + */ +interface Swift_Mailer_RecipientIterator +{ + /** + * Returns true only if there are more recipients to send to. + * + * @return bool + */ + public function hasNext(); + + /** + * Returns an array where the keys are the addresses of recipients and the + * values are the names. e.g. ('foo@bar' => 'Foo') or ('foo@bar' => NULL). + * + * @return array + */ + public function nextRecipient(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php new file mode 100644 index 0000000..e3b0894 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php @@ -0,0 +1,110 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2011 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages in memory. + * + * @author Fabien Potencier + */ +class Swift_MemorySpool implements Swift_Spool +{ + protected $messages = []; + private $flushRetries = 3; + + /** + * Tests if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Transport mechanism. + */ + public function start() + { + } + + /** + * Stops this Transport mechanism. + */ + public function stop() + { + } + + /** + * @param int $retries + */ + public function setFlushRetries($retries) + { + $this->flushRetries = $retries; + } + + /** + * Stores a message in the queue. + * + * @param Swift_Mime_SimpleMessage $message The message to store + * + * @return bool Whether the operation has succeeded + */ + public function queueMessage(Swift_Mime_SimpleMessage $message) + { + //clone the message to make sure it is not changed while in the queue + $this->messages[] = clone $message; + + return true; + } + + /** + * Sends messages using the given transport instance. + * + * @param Swift_Transport $transport A transport instance + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent emails + */ + public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) + { + if (!$this->messages) { + return 0; + } + + if (!$transport->isStarted()) { + $transport->start(); + } + + $count = 0; + $retries = $this->flushRetries; + while ($retries--) { + try { + while ($message = array_pop($this->messages)) { + $count += $transport->send($message, $failedRecipients); + } + } catch (Swift_TransportException $exception) { + if ($retries) { + // re-queue the message at the end of the queue to give a chance + // to the other messages to be sent, in case the failure was due to + // this message and not just the transport failing + array_unshift($this->messages, $message); + + // wait half a second before we try again + usleep(500000); + } else { + throw $exception; + } + } + } + + return $count; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php new file mode 100644 index 0000000..5c5834e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php @@ -0,0 +1,279 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * The Message class for building emails. + * + * @author Chris Corbyn + */ +class Swift_Message extends Swift_Mime_SimpleMessage +{ + /** + * @var Swift_Signers_HeaderSigner[] + */ + private $headerSigners = []; + + /** + * @var Swift_Signers_BodySigner[] + */ + private $bodySigners = []; + + /** + * @var array + */ + private $savedMessage = []; + + /** + * Create a new Message. + * + * Details may be optionally passed into the constructor. + * + * @param string $subject + * @param string $body + * @param string $contentType + * @param string $charset + */ + public function __construct($subject = null, $body = null, $contentType = null, $charset = null) + { + \call_user_func_array( + [$this, 'Swift_Mime_SimpleMessage::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('mime.message') + ); + + if (!isset($charset)) { + $charset = Swift_DependencyContainer::getInstance() + ->lookup('properties.charset'); + } + $this->setSubject($subject); + $this->setBody($body); + $this->setCharset($charset); + if ($contentType) { + $this->setContentType($contentType); + } + } + + /** + * Add a MimePart to this Message. + * + * @param string|Swift_OutputByteStream $body + * @param string $contentType + * @param string $charset + * + * @return $this + */ + public function addPart($body, $contentType = null, $charset = null) + { + return $this->attach((new Swift_MimePart($body, $contentType, $charset))->setEncoder($this->getEncoder())); + } + + /** + * Attach a new signature handler to the message. + * + * @return $this + */ + public function attachSigner(Swift_Signer $signer) + { + if ($signer instanceof Swift_Signers_HeaderSigner) { + $this->headerSigners[] = $signer; + } elseif ($signer instanceof Swift_Signers_BodySigner) { + $this->bodySigners[] = $signer; + } + + return $this; + } + + /** + * Detach a signature handler from a message. + * + * @return $this + */ + public function detachSigner(Swift_Signer $signer) + { + if ($signer instanceof Swift_Signers_HeaderSigner) { + foreach ($this->headerSigners as $k => $headerSigner) { + if ($headerSigner === $signer) { + unset($this->headerSigners[$k]); + + return $this; + } + } + } elseif ($signer instanceof Swift_Signers_BodySigner) { + foreach ($this->bodySigners as $k => $bodySigner) { + if ($bodySigner === $signer) { + unset($this->bodySigners[$k]); + + return $this; + } + } + } + + return $this; + } + + /** + * Clear all signature handlers attached to the message. + * + * @return $this + */ + public function clearSigners() + { + $this->headerSigners = []; + $this->bodySigners = []; + + return $this; + } + + /** + * Get this message as a complete string. + * + * @return string + */ + public function toString() + { + if (empty($this->headerSigners) && empty($this->bodySigners)) { + return parent::toString(); + } + + $this->saveMessage(); + + $this->doSign(); + + $string = parent::toString(); + + $this->restoreMessage(); + + return $string; + } + + /** + * Write this message to a {@link Swift_InputByteStream}. + */ + public function toByteStream(Swift_InputByteStream $is) + { + if (empty($this->headerSigners) && empty($this->bodySigners)) { + parent::toByteStream($is); + + return; + } + + $this->saveMessage(); + + $this->doSign(); + + parent::toByteStream($is); + + $this->restoreMessage(); + } + + public function __wakeup() + { + Swift_DependencyContainer::getInstance()->createDependenciesFor('mime.message'); + } + + /** + * loops through signers and apply the signatures. + */ + protected function doSign() + { + foreach ($this->bodySigners as $signer) { + $altered = $signer->getAlteredHeaders(); + $this->saveHeaders($altered); + $signer->signMessage($this); + } + + foreach ($this->headerSigners as $signer) { + $altered = $signer->getAlteredHeaders(); + $this->saveHeaders($altered); + $signer->reset(); + + $signer->setHeaders($this->getHeaders()); + + $signer->startBody(); + $this->bodyToByteStream($signer); + $signer->endBody(); + + $signer->addSignature($this->getHeaders()); + } + } + + /** + * save the message before any signature is applied. + */ + protected function saveMessage() + { + $this->savedMessage = ['headers' => []]; + $this->savedMessage['body'] = $this->getBody(); + $this->savedMessage['children'] = $this->getChildren(); + if (\count($this->savedMessage['children']) > 0 && '' != $this->getBody()) { + $this->setChildren(array_merge([$this->becomeMimePart()], $this->savedMessage['children'])); + $this->setBody(''); + } + } + + /** + * save the original headers. + */ + protected function saveHeaders(array $altered) + { + foreach ($altered as $head) { + $lc = strtolower($head ?? ''); + + if (!isset($this->savedMessage['headers'][$lc])) { + $this->savedMessage['headers'][$lc] = $this->getHeaders()->getAll($head); + } + } + } + + /** + * Remove or restore altered headers. + */ + protected function restoreHeaders() + { + foreach ($this->savedMessage['headers'] as $name => $savedValue) { + $headers = $this->getHeaders()->getAll($name); + + foreach ($headers as $key => $value) { + if (!isset($savedValue[$key])) { + $this->getHeaders()->remove($name, $key); + } + } + } + } + + /** + * Restore message body. + */ + protected function restoreMessage() + { + $this->setBody($this->savedMessage['body']); + $this->setChildren($this->savedMessage['children']); + + $this->restoreHeaders(); + $this->savedMessage = []; + } + + /** + * Clone Message Signers. + * + * @see Swift_Mime_SimpleMimeEntity::__clone() + */ + public function __clone() + { + parent::__clone(); + foreach ($this->bodySigners as $key => $bodySigner) { + $this->bodySigners[$key] = clone $bodySigner; + } + + foreach ($this->headerSigners as $key => $headerSigner) { + $this->headerSigners[$key] = clone $headerSigner; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php new file mode 100644 index 0000000..d994373 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php @@ -0,0 +1,144 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An attachment, in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity +{ + /** Recognized MIME types */ + private $mimeTypes = []; + + /** + * Create a new Attachment with $headers, $encoder and $cache. + * + * @param array $mimeTypes + */ + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = []) + { + parent::__construct($headers, $encoder, $cache, $idGenerator); + $this->setDisposition('attachment'); + $this->setContentType('application/octet-stream'); + $this->mimeTypes = $mimeTypes; + } + + /** + * Get the nesting level used for this attachment. + * + * Always returns {@link LEVEL_MIXED}. + * + * @return int + */ + public function getNestingLevel() + { + return self::LEVEL_MIXED; + } + + /** + * Get the Content-Disposition of this attachment. + * + * By default attachments have a disposition of "attachment". + * + * @return string + */ + public function getDisposition() + { + return $this->getHeaderFieldModel('Content-Disposition'); + } + + /** + * Set the Content-Disposition of this attachment. + * + * @param string $disposition + * + * @return $this + */ + public function setDisposition($disposition) + { + if (!$this->setHeaderFieldModel('Content-Disposition', $disposition)) { + $this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition); + } + + return $this; + } + + /** + * Get the filename of this attachment when downloaded. + * + * @return string + */ + public function getFilename() + { + return $this->getHeaderParameter('Content-Disposition', 'filename'); + } + + /** + * Set the filename of this attachment. + * + * @param string $filename + * + * @return $this + */ + public function setFilename($filename) + { + $this->setHeaderParameter('Content-Disposition', 'filename', $filename); + $this->setHeaderParameter('Content-Type', 'name', $filename); + + return $this; + } + + /** + * Get the file size of this attachment. + * + * @return int + */ + public function getSize() + { + return $this->getHeaderParameter('Content-Disposition', 'size'); + } + + /** + * Set the file size of this attachment. + * + * @param int $size + * + * @return $this + */ + public function setSize($size) + { + $this->setHeaderParameter('Content-Disposition', 'size', $size); + + return $this; + } + + /** + * Set the file that this attachment is for. + * + * @param string $contentType optional + * + * @return $this + */ + public function setFile(Swift_FileStream $file, $contentType = null) + { + $this->setFilename(basename($file->getPath())); + $this->setBody($file, $contentType); + if (!isset($contentType)) { + $extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1)); + + if (\array_key_exists($extension, $this->mimeTypes)) { + $this->setContentType($this->mimeTypes[$extension]); + } + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php new file mode 100644 index 0000000..b49c3a8 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Observes changes in an Mime entity's character set. + * + * @author Chris Corbyn + */ +interface Swift_Mime_CharsetObserver +{ + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder.php new file mode 100644 index 0000000..d43ea9f --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder.php @@ -0,0 +1,34 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Interface for all Transfer Encoding schemes. + * + * @author Chris Corbyn + */ +interface Swift_Mime_ContentEncoder extends Swift_Encoder +{ + /** + * Encode $in to $out. + * + * @param Swift_OutputByteStream $os to read from + * @param Swift_InputByteStream $is to write to + * @param int $firstLineOffset + * @param int $maxLineLength - 0 indicates the default length for this encoding + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0); + + /** + * Get the MIME name of this content encoding scheme. + * + * @return string + */ + public function getName(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/Base64ContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/Base64ContentEncoder.php new file mode 100644 index 0000000..b7e1e02 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/Base64ContentEncoder.php @@ -0,0 +1,101 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Base 64 Transfer Encoding in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base64Encoder implements Swift_Mime_ContentEncoder +{ + /** + * Encode stream $in to stream $out. + * + * @param int $firstLineOffset + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + if (0 >= $maxLineLength || 76 < $maxLineLength) { + $maxLineLength = 76; + } + + $remainder = 0; + $base64ReadBufferRemainderBytes = ''; + + // To reduce memory usage, the output buffer is streamed to the input buffer like so: + // Output Stream => base64encode => wrap line length => Input Stream + // HOWEVER it's important to note that base64_encode() should only be passed whole triplets of data (except for the final chunk of data) + // otherwise it will assume the input data has *ended* and it will incorrectly pad/terminate the base64 data mid-stream. + // We use $base64ReadBufferRemainderBytes to carry over 1-2 "remainder" bytes from the each chunk from OutputStream and pre-pend those onto the + // chunk of bytes read in the next iteration. + // When the OutputStream is empty, we must flush any remainder bytes. + while (true) { + $readBytes = $os->read(8192); + $atEOF = (false === $readBytes); + + if ($atEOF) { + $streamTheseBytes = $base64ReadBufferRemainderBytes; + } else { + $streamTheseBytes = $base64ReadBufferRemainderBytes.$readBytes; + } + $base64ReadBufferRemainderBytes = ''; + $bytesLength = \strlen($streamTheseBytes); + + if (0 === $bytesLength) { // no data left to encode + break; + } + + // if we're not on the last block of the ouput stream, make sure $streamTheseBytes ends with a complete triplet of data + // and carry over remainder 1-2 bytes to the next loop iteration + if (!$atEOF) { + $excessBytes = $bytesLength % 3; + if (0 !== $excessBytes) { + $base64ReadBufferRemainderBytes = substr($streamTheseBytes, -$excessBytes); + $streamTheseBytes = substr($streamTheseBytes, 0, $bytesLength - $excessBytes); + } + } + + $encoded = base64_encode($streamTheseBytes); + $encodedTransformed = ''; + $thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset; + + while ($thisMaxLineLength < \strlen($encoded)) { + $encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n"; + $firstLineOffset = 0; + $encoded = substr($encoded, $thisMaxLineLength); + $thisMaxLineLength = $maxLineLength; + $remainder = 0; + } + + if (0 < $remainingLength = \strlen($encoded)) { + $remainder += $remainingLength; + $encodedTransformed .= $encoded; + $encoded = null; + } + + $is->write($encodedTransformed); + + if ($atEOF) { + break; + } + } + } + + /** + * Get the name of this encoding scheme. + * Returns the string 'base64'. + * + * @return string + */ + public function getName() + { + return 'base64'; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php new file mode 100644 index 0000000..8dfea60 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php @@ -0,0 +1,121 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer using the PHP core function. + * + * @author Lars Strojny + */ +class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_ContentEncoder +{ + /** + * @var string|null + */ + private $charset; + + /** + * @param string|null $charset + */ + public function __construct($charset = null) + { + $this->charset = $charset ?: 'utf-8'; + } + + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->charset = $charset; + } + + /** + * Encode $in to $out. + * + * @param Swift_OutputByteStream $os to read from + * @param Swift_InputByteStream $is to write to + * @param int $firstLineOffset + * @param int $maxLineLength 0 indicates the default length for this encoding + * + * @throws RuntimeException + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + if ('utf-8' !== $this->charset) { + throw new RuntimeException(sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); + } + + $string = ''; + + while (false !== $bytes = $os->read(8192)) { + $string .= $bytes; + } + + $is->write($this->encodeString($string)); + } + + /** + * Get the MIME name of this content encoding scheme. + * + * @return string + */ + public function getName() + { + return 'quoted-printable'; + } + + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset if first line needs to be shorter + * @param int $maxLineLength 0 indicates the default length for this encoding + * + * @throws RuntimeException + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if ('utf-8' !== $this->charset) { + throw new RuntimeException(sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); + } + + return $this->standardize(quoted_printable_encode($string)); + } + + /** + * Make sure CRLF is correct and HT/SPACE are in valid places. + * + * @param string $string + * + * @return string + */ + protected function standardize($string) + { + // transform CR or LF to CRLF + $string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string); + // transform =0D=0A to CRLF + $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string); + + switch (\ord(substr($string, -1))) { + case 0x09: + $string = substr_replace($string, '=09', -1); + break; + case 0x20: + $string = substr_replace($string, '=20', -1); + break; + } + + return $string; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NullContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NullContentEncoder.php new file mode 100644 index 0000000..6539de7 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NullContentEncoder.php @@ -0,0 +1,79 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles the case where the email body is already encoded and you just need specify the correct + * encoding without actually changing the encoding of the body. + * + * @author Jan Flora <jf@penneo.com> + */ +class Swift_Mime_ContentEncoder_NullContentEncoder implements Swift_Mime_ContentEncoder +{ + /** + * The name of this encoding scheme (probably 7bit or 8bit). + * + * @var string + */ + private $name; + + /** + * Creates a new NullContentEncoder with $name (probably 7bit or 8bit). + * + * @param string $name + */ + public function __construct($name) + { + $this->name = $name; + } + + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset ignored + * @param int $maxLineLength ignored + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return $string; + } + + /** + * Encode stream $in to stream $out. + * + * @param int $firstLineOffset ignored + * @param int $maxLineLength ignored + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + while (false !== ($bytes = $os->read(8192))) { + $is->write($bytes); + } + } + + /** + * Get the name of this encoding scheme. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Not used. + */ + public function charsetChanged($charset) + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/PlainContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/PlainContentEncoder.php new file mode 100644 index 0000000..72592fc --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/PlainContentEncoder.php @@ -0,0 +1,164 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles binary/7/8-bit Transfer Encoding in Swift Mailer. + * + * When sending 8-bit content over SMTP, you should use + * Swift_Transport_Esmtp_EightBitMimeHandler to enable the 8BITMIME SMTP + * extension. + * + * @author Chris Corbyn + */ +class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_ContentEncoder +{ + /** + * The name of this encoding scheme (probably 7bit or 8bit). + * + * @var string + */ + private $name; + + /** + * True if canonical transformations should be done. + * + * @var bool + */ + private $canonical; + + /** + * Creates a new PlainContentEncoder with $name (probably 7bit or 8bit). + * + * @param string $name + * @param bool $canonical if canonicalization transformation should be done + */ + public function __construct($name, $canonical = false) + { + $this->name = $name; + $this->canonical = $canonical; + } + + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset ignored + * @param int $maxLineLength - 0 means no wrapping will occur + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($this->canonical) { + $string = $this->canonicalize($string); + } + + return $this->safeWordwrap($string, $maxLineLength, "\r\n"); + } + + /** + * Encode stream $in to stream $out. + * + * @param int $firstLineOffset ignored + * @param int $maxLineLength optional, 0 means no wrapping will occur + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + $leftOver = ''; + while (false !== $bytes = $os->read(8192)) { + $toencode = $leftOver.$bytes; + if ($this->canonical) { + $toencode = $this->canonicalize($toencode); + } + $wrapped = $this->safeWordwrap($toencode, $maxLineLength, "\r\n"); + $lastLinePos = strrpos($wrapped, "\r\n"); + $leftOver = substr($wrapped, $lastLinePos); + $wrapped = substr($wrapped, 0, $lastLinePos); + + $is->write($wrapped); + } + if (\strlen($leftOver)) { + $is->write($leftOver); + } + } + + /** + * Get the name of this encoding scheme. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Not used. + */ + public function charsetChanged($charset) + { + } + + /** + * A safer (but weaker) wordwrap for unicode. + * + * @param string $string + * @param int $length + * @param string $le + * + * @return string + */ + private function safeWordwrap($string, $length = 75, $le = "\r\n") + { + if (0 >= $length) { + return $string; + } + + $originalLines = explode($le, $string); + + $lines = []; + $lineCount = 0; + + foreach ($originalLines as $originalLine) { + $lines[] = ''; + $currentLine = &$lines[$lineCount++]; + + //$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine); + $chunks = preg_split('/(?<=\s)/', $originalLine); + + foreach ($chunks as $chunk) { + if (0 != \strlen($currentLine) + && \strlen($currentLine.$chunk) > $length) { + $lines[] = ''; + $currentLine = &$lines[$lineCount++]; + } + $currentLine .= $chunk; + } + } + + return implode("\r\n", $lines); + } + + /** + * Canonicalize string input (fix CRLF). + * + * @param string $string + * + * @return string + */ + private function canonicalize($string) + { + return str_replace( + ["\r\n", "\r", "\n"], + ["\n", "\n", "\r\n"], + $string + ); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php new file mode 100644 index 0000000..465ffd8 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php @@ -0,0 +1,134 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder +{ + protected $dotEscape; + + /** + * Creates a new QpContentEncoder for the given CharacterStream. + * + * @param Swift_CharacterStream $charStream to use for reading characters + * @param Swift_StreamFilter $filter if canonicalization should occur + * @param bool $dotEscape if dot stuffing workaround must be enabled + */ + public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false) + { + $this->dotEscape = $dotEscape; + parent::__construct($charStream, $filter); + } + + public function __sleep() + { + return ['charStream', 'filter', 'dotEscape']; + } + + protected function getSafeMapShareId() + { + return static::class.($this->dotEscape ? '.dotEscape' : ''); + } + + protected function initSafeMap() + { + parent::initSafeMap(); + if ($this->dotEscape) { + /* Encode . as =2e for buggy remote servers */ + unset($this->safeMap[0x2e]); + } + } + + /** + * Encode stream $in to stream $out. + * + * QP encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + * + * @param Swift_OutputByteStream $os output stream + * @param Swift_InputByteStream $is input stream + * @param int $firstLineOffset + * @param int $maxLineLength + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($maxLineLength > 76 || $maxLineLength <= 0) { + $maxLineLength = 76; + } + + $thisLineLength = $maxLineLength - $firstLineOffset; + + $this->charStream->flushContents(); + $this->charStream->importByteStream($os); + + $currentLine = ''; + $prepend = ''; + $size = $lineLen = 0; + + while (false !== $bytes = $this->nextSequence()) { + // If we're filtering the input + if (isset($this->filter)) { + // If we can't filter because we need more bytes + while ($this->filter->shouldBuffer($bytes)) { + // Then collect bytes into the buffer + if (false === $moreBytes = $this->nextSequence(1)) { + break; + } + + foreach ($moreBytes as $b) { + $bytes[] = $b; + } + } + // And filter them + $bytes = $this->filter->filter($bytes); + } + + $enc = $this->encodeByteSequence($bytes, $size); + + $i = strpos($enc, '=0D=0A'); + $newLineLength = $lineLen + (false === $i ? $size : $i); + + if ($currentLine && $newLineLength >= $thisLineLength) { + $is->write($prepend.$this->standardize($currentLine)); + $currentLine = ''; + $prepend = "=\r\n"; + $thisLineLength = $maxLineLength; + $lineLen = 0; + } + + $currentLine .= $enc; + + if (false === $i) { + $lineLen += $size; + } else { + // 6 is the length of '=0D=0A'. + $lineLen = $size - strrpos($enc, '=0D=0A') - 6; + } + } + if (\strlen($currentLine)) { + $is->write($prepend.$this->standardize($currentLine)); + } + } + + /** + * Get the name of this encoding scheme. + * Returns the string 'quoted-printable'. + * + * @return string + */ + public function getName() + { + return 'quoted-printable'; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php new file mode 100644 index 0000000..f3ece43 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php @@ -0,0 +1,96 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Proxy for quoted-printable content encoders. + * + * Switches on the best QP encoder implementation for current charset. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + */ +class Swift_Mime_ContentEncoder_QpContentEncoderProxy implements Swift_Mime_ContentEncoder +{ + /** + * @var Swift_Mime_ContentEncoder_QpContentEncoder + */ + private $safeEncoder; + + /** + * @var Swift_Mime_ContentEncoder_NativeQpContentEncoder + */ + private $nativeEncoder; + + /** + * @var string|null + */ + private $charset; + + /** + * Constructor. + * + * @param string|null $charset + */ + public function __construct(Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder, Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder, $charset) + { + $this->safeEncoder = $safeEncoder; + $this->nativeEncoder = $nativeEncoder; + $this->charset = $charset; + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + $this->safeEncoder = clone $this->safeEncoder; + $this->nativeEncoder = clone $this->nativeEncoder; + } + + /** + * {@inheritdoc} + */ + public function charsetChanged($charset) + { + $this->charset = $charset; + $this->safeEncoder->charsetChanged($charset); + } + + /** + * {@inheritdoc} + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + $this->getEncoder()->encodeByteStream($os, $is, $firstLineOffset, $maxLineLength); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'quoted-printable'; + } + + /** + * {@inheritdoc} + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return $this->getEncoder()->encodeString($string, $firstLineOffset, $maxLineLength); + } + + /** + * @return Swift_Mime_ContentEncoder + */ + private function getEncoder() + { + return 'utf-8' === $this->charset ? $this->nativeEncoder : $this->safeEncoder; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php new file mode 100644 index 0000000..870e7f4 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles raw Transfer Encoding in Swift Mailer. + * + * When sending 8-bit content over SMTP, you should use + * Swift_Transport_Esmtp_EightBitMimeHandler to enable the 8BITMIME SMTP + * extension. + * + * @author Sebastiaan Stok <s.stok@rollerscapes.net> + */ +class Swift_Mime_ContentEncoder_RawContentEncoder implements Swift_Mime_ContentEncoder +{ + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset ignored + * @param int $maxLineLength ignored + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return $string; + } + + /** + * Encode stream $in to stream $out. + * + * @param int $firstLineOffset ignored + * @param int $maxLineLength ignored + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + while (false !== ($bytes = $os->read(8192))) { + $is->write($bytes); + } + } + + /** + * Get the name of this encoding scheme. + * + * @return string + */ + public function getName() + { + return 'raw'; + } + + /** + * Not used. + */ + public function charsetChanged($charset) + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php new file mode 100644 index 0000000..42a5177 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php @@ -0,0 +1,41 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An embedded file, in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_Mime_EmbeddedFile extends Swift_Mime_Attachment +{ + /** + * Creates a new Attachment with $headers and $encoder. + * + * @param array $mimeTypes optional + */ + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = []) + { + parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes); + $this->setDisposition('inline'); + $this->setId($this->getId()); + } + + /** + * Get the nesting level of this EmbeddedFile. + * + * Returns {@see LEVEL_RELATED}. + * + * @return int + */ + public function getNestingLevel() + { + return self::LEVEL_RELATED; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php new file mode 100644 index 0000000..1a952ec --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Observes changes for a Mime entity's ContentEncoder. + * + * @author Chris Corbyn + */ +interface Swift_Mime_EncodingObserver +{ + /** + * Notify this observer that the observed entity's ContentEncoder has changed. + */ + public function encoderChanged(Swift_Mime_ContentEncoder $encoder); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php new file mode 100644 index 0000000..ca712f3 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php @@ -0,0 +1,93 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A MIME Header. + * + * @author Chris Corbyn + */ +interface Swift_Mime_Header +{ + /** Text headers */ + const TYPE_TEXT = 2; + + /** headers (text + params) */ + const TYPE_PARAMETERIZED = 6; + + /** Mailbox and address headers */ + const TYPE_MAILBOX = 8; + + /** Date and time headers */ + const TYPE_DATE = 16; + + /** Identification headers */ + const TYPE_ID = 32; + + /** Address path headers */ + const TYPE_PATH = 64; + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType(); + + /** + * Set the model for the field body. + * + * The actual types needed will vary depending upon the type of Header. + * + * @param mixed $model + */ + public function setFieldBodyModel($model); + + /** + * Set the charset used when rendering the Header. + * + * @param string $charset + */ + public function setCharset($charset); + + /** + * Get the model for the field body. + * + * The return type depends on the specifics of the Header. + * + * @return mixed + */ + public function getFieldBodyModel(); + + /** + * Get the name of this header (e.g. Subject). + * + * The name is an identifier and as such will be immutable. + * + * @return string + */ + public function getFieldName(); + + /** + * Get the field body, prepared for folding into a final header value. + * + * @return string + */ + public function getFieldBody(); + + /** + * Get this Header rendered as a compliant string, including trailing CRLF. + * + * @return string + */ + public function toString(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder.php new file mode 100644 index 0000000..08fd453 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Interface for all Header Encoding schemes. + * + * @author Chris Corbyn + */ +interface Swift_Mime_HeaderEncoder extends Swift_Encoder +{ + /** + * Get the MIME name of this content encoding scheme. + * + * @return string + */ + public function getName(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/Base64HeaderEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/Base64HeaderEncoder.php new file mode 100644 index 0000000..21c8aaa --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/Base64HeaderEncoder.php @@ -0,0 +1,55 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Base64 (B) Header Encoding in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Mime_HeaderEncoder_Base64HeaderEncoder extends Swift_Encoder_Base64Encoder implements Swift_Mime_HeaderEncoder +{ + /** + * Get the name of this encoding scheme. + * Returns the string 'B'. + * + * @return string + */ + public function getName() + { + return 'B'; + } + + /** + * Takes an unencoded string and produces a Base64 encoded string from it. + * + * If the charset is iso-2022-jp, it uses mb_encode_mimeheader instead of + * default encodeString, otherwise pass to the parent method. + * + * @param string $string string to encode + * @param int $firstLineOffset + * @param int $maxLineLength optional, 0 indicates the default of 76 bytes + * @param string $charset + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0, $charset = 'utf-8') + { + if ('iso-2022-jp' === strtolower($charset ?? '')) { + $old = mb_internal_encoding(); + mb_internal_encoding('utf-8'); + $newstring = mb_encode_mimeheader($string, $charset, $this->getName(), "\r\n"); + mb_internal_encoding($old); + + return $newstring; + } + + return parent::encodeString($string, $firstLineOffset, $maxLineLength); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php new file mode 100644 index 0000000..378c480 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles Quoted Printable (Q) Header Encoding in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_HeaderEncoder +{ + /** + * Creates a new QpHeaderEncoder for the given CharacterStream. + * + * @param Swift_CharacterStream $charStream to use for reading characters + */ + public function __construct(Swift_CharacterStream $charStream) + { + parent::__construct($charStream); + } + + protected function initSafeMap() + { + foreach (array_merge( + range(0x61, 0x7A), range(0x41, 0x5A), + range(0x30, 0x39), [0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F] + ) as $byte) { + $this->safeMap[$byte] = \chr($byte); + } + } + + /** + * Get the name of this encoding scheme. + * + * Returns the string 'Q'. + * + * @return string + */ + public function getName() + { + return 'Q'; + } + + /** + * Takes an unencoded string and produces a QP encoded string from it. + * + * @param string $string string to encode + * @param int $firstLineOffset optional + * @param int $maxLineLength optional, 0 indicates the default of 76 chars + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return str_replace([' ', '=20', "=\r\n"], ['_', '_', "\r\n"], + parent::encodeString($string, $firstLineOffset, $maxLineLength) + ); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/AbstractHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/AbstractHeader.php new file mode 100644 index 0000000..25740d1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/AbstractHeader.php @@ -0,0 +1,486 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An abstract base MIME Header. + * + * @author Chris Corbyn + */ +abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header +{ + const PHRASE_PATTERN = '(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?"((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*(?:\r\n))?[ \t])?"(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))+?)'; + + /** + * The name of this Header. + * + * @var string + */ + private $name; + + /** + * The Encoder used to encode this Header. + * + * @var Swift_Encoder + */ + private $encoder; + + /** + * The maximum length of a line in the header. + * + * @var int + */ + private $lineLength = 78; + + /** + * The language used in this Header. + * + * @var string + */ + private $lang; + + /** + * The character set of the text in this Header. + * + * @var string + */ + private $charset = 'utf-8'; + + /** + * The value of this Header, cached. + * + * @var string + */ + private $cachedValue = null; + + /** + * Set the character set used in this Header. + * + * @param string $charset + */ + public function setCharset($charset) + { + $this->clearCachedValueIf($charset != $this->charset); + $this->charset = $charset; + if (isset($this->encoder)) { + $this->encoder->charsetChanged($charset); + } + } + + /** + * Get the character set used in this Header. + * + * @return string + */ + public function getCharset() + { + return $this->charset; + } + + /** + * Set the language used in this Header. + * + * For example, for US English, 'en-us'. + * This can be unspecified. + * + * @param string $lang + */ + public function setLanguage($lang) + { + $this->clearCachedValueIf($this->lang != $lang); + $this->lang = $lang; + } + + /** + * Get the language used in this Header. + * + * @return string + */ + public function getLanguage() + { + return $this->lang; + } + + /** + * Set the encoder used for encoding the header. + */ + public function setEncoder(Swift_Mime_HeaderEncoder $encoder) + { + $this->encoder = $encoder; + $this->setCachedValue(null); + } + + /** + * Get the encoder used for encoding this Header. + * + * @return Swift_Mime_HeaderEncoder + */ + public function getEncoder() + { + return $this->encoder; + } + + /** + * Get the name of this header (e.g. charset). + * + * @return string + */ + public function getFieldName() + { + return $this->name; + } + + /** + * Set the maximum length of lines in the header (excluding EOL). + * + * @param int $lineLength + */ + public function setMaxLineLength($lineLength) + { + $this->clearCachedValueIf($this->lineLength != $lineLength); + $this->lineLength = $lineLength; + } + + /** + * Get the maximum permitted length of lines in this Header. + * + * @return int + */ + public function getMaxLineLength() + { + return $this->lineLength; + } + + /** + * Get this Header rendered as a RFC 2822 compliant string. + * + * @return string + * + * @throws Swift_RfcComplianceException + */ + public function toString() + { + return $this->tokensToString($this->toTokens()); + } + + /** + * Returns a string representation of this object. + * + * @return string + * + * @see toString() + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Set the name of this Header field. + * + * @param string $name + */ + protected function setFieldName($name) + { + $this->name = $name; + } + + /** + * Produces a compliant, formatted RFC 2822 'phrase' based on the string given. + * + * @param string $string as displayed + * @param string $charset of the text + * @param bool $shorten the first line to make remove for header name + * + * @return string + */ + protected function createPhrase(Swift_Mime_Header $header, $string, $charset, Swift_Mime_HeaderEncoder $encoder = null, $shorten = false) + { + // Treat token as exactly what was given + $phraseStr = $string; + // If it's not valid + + if (!preg_match('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) { + // .. but it is just ascii text, try escaping some characters + // and make it a quoted-string + if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) { + $phraseStr = $this->escapeSpecials($phraseStr, ['"']); + $phraseStr = '"'.$phraseStr.'"'; + } else { + // ... otherwise it needs encoding + // Determine space remaining on line if first line + if ($shorten) { + $usedLength = \strlen($header->getFieldName().': '); + } else { + $usedLength = 0; + } + $phraseStr = $this->encodeWords($header, $string, $usedLength); + } + } + + return $phraseStr; + } + + /** + * Escape special characters in a string (convert to quoted-pairs). + * + * @param string $token + * @param string[] $include additional chars to escape + * + * @return string + */ + private function escapeSpecials($token, $include = []) + { + foreach (array_merge(['\\'], $include) as $char) { + $token = str_replace($char, '\\'.$char, $token); + } + + return $token; + } + + /** + * Encode needed word tokens within a string of input. + * + * @param string $input + * @param string $usedLength optional + * + * @return string + */ + protected function encodeWords(Swift_Mime_Header $header, $input, $usedLength = -1) + { + $value = ''; + + $tokens = $this->getEncodableWordTokens($input); + + foreach ($tokens as $token) { + // See RFC 2822, Sect 2.2 (really 2.2 ??) + if ($this->tokenNeedsEncoding($token)) { + // Don't encode starting WSP + $firstChar = substr($token, 0, 1); + switch ($firstChar) { + case ' ': + case "\t": + $value .= $firstChar; + $token = substr($token, 1); + } + + if (-1 == $usedLength) { + $usedLength = \strlen($header->getFieldName().': ') + \strlen($value); + } + $value .= $this->getTokenAsEncodedWord($token, $usedLength); + + $header->setMaxLineLength(76); // Forcefully override + } else { + $value .= $token; + } + } + + return $value; + } + + /** + * Test if a token needs to be encoded or not. + * + * @param string $token + * + * @return bool + */ + protected function tokenNeedsEncoding($token) + { + return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token); + } + + /** + * Splits a string into tokens in blocks of words which can be encoded quickly. + * + * @param string $string + * + * @return string[] + */ + protected function getEncodableWordTokens($string) + { + $tokens = []; + + $encodedToken = ''; + // Split at all whitespace boundaries + foreach (preg_split('~(?=[\t ])~', $string ?? '') as $token) { + if ($this->tokenNeedsEncoding($token)) { + $encodedToken .= $token; + } else { + if (\strlen($encodedToken) > 0) { + $tokens[] = $encodedToken; + $encodedToken = ''; + } + $tokens[] = $token; + } + } + if (\strlen($encodedToken)) { + $tokens[] = $encodedToken; + } + + return $tokens; + } + + /** + * Get a token as an encoded word for safe insertion into headers. + * + * @param string $token token to encode + * @param int $firstLineOffset optional + * + * @return string + */ + protected function getTokenAsEncodedWord($token, $firstLineOffset = 0) + { + // Adjust $firstLineOffset to account for space needed for syntax + $charsetDecl = $this->charset; + if (isset($this->lang)) { + $charsetDecl .= '*'.$this->lang; + } + $encodingWrapperLength = \strlen( + '=?'.$charsetDecl.'?'.$this->encoder->getName().'??=' + ); + + if ($firstLineOffset >= 75) { + //Does this logic need to be here? + $firstLineOffset = 0; + } + + $encodedTextLines = explode("\r\n", + $this->encoder->encodeString( + $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset + ) ?? '' + ); + + if ('iso-2022-jp' !== strtolower($this->charset ?? '')) { + // special encoding for iso-2022-jp using mb_encode_mimeheader + foreach ($encodedTextLines as $lineNum => $line) { + $encodedTextLines[$lineNum] = '=?'.$charsetDecl. + '?'.$this->encoder->getName(). + '?'.$line.'?='; + } + } + + return implode("\r\n ", $encodedTextLines); + } + + /** + * Generates tokens from the given string which include CRLF as individual tokens. + * + * @param string $token + * + * @return string[] + */ + protected function generateTokenLines($token) + { + return preg_split('~(\r\n)~', $token ?? '', -1, PREG_SPLIT_DELIM_CAPTURE); + } + + /** + * Set a value into the cache. + * + * @param string $value + */ + protected function setCachedValue($value) + { + $this->cachedValue = $value; + } + + /** + * Get the value in the cache. + * + * @return string + */ + protected function getCachedValue() + { + return $this->cachedValue; + } + + /** + * Clear the cached value if $condition is met. + * + * @param bool $condition + */ + protected function clearCachedValueIf($condition) + { + if ($condition) { + $this->setCachedValue(null); + } + } + + /** + * Generate a list of all tokens in the final header. + * + * @param string $string The string to tokenize + * + * @return array An array of tokens as strings + */ + protected function toTokens($string = null) + { + if (null === $string) { + $string = $this->getFieldBody(); + } + + $tokens = []; + + // Generate atoms; split at all invisible boundaries followed by WSP + foreach (preg_split('~(?=[ \t])~', $string ?? '') as $token) { + $newTokens = $this->generateTokenLines($token); + foreach ($newTokens as $newToken) { + $tokens[] = $newToken; + } + } + + return $tokens; + } + + /** + * Takes an array of tokens which appear in the header and turns them into + * an RFC 2822 compliant string, adding FWSP where needed. + * + * @param string[] $tokens + * + * @return string + */ + private function tokensToString(array $tokens) + { + $lineCount = 0; + $headerLines = []; + $headerLines[] = $this->name.': '; + $currentLine = &$headerLines[$lineCount++]; + + // Build all tokens back into compliant header + foreach ($tokens as $i => $token) { + // Line longer than specified maximum or token was just a new line + if (("\r\n" == $token) || + ($i > 0 && \strlen($currentLine.$token) > $this->lineLength) + && 0 < \strlen($currentLine)) { + $headerLines[] = ''; + $currentLine = &$headerLines[$lineCount++]; + } + + // Append token to the line + if ("\r\n" != $token) { + $currentLine .= $token; + } + } + + // Implode with FWS (RFC 2822, 2.2.3) + return implode("\r\n", $headerLines)."\r\n"; + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + if ($this->encoder) { + $this->encoder = clone $this->encoder; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php new file mode 100644 index 0000000..efe1dad --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php @@ -0,0 +1,113 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A Date MIME Header for Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader +{ + /** + * Date-time value of this Header. + * + * @var DateTimeImmutable + */ + private $dateTime; + + /** + * Creates a new DateHeader with $name. + * + * @param string $name of Header + */ + public function __construct($name) + { + $this->setFieldName($name); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_DATE; + } + + /** + * Set the model for the field body. + * + * @param DateTimeInterface $model + */ + public function setFieldBodyModel($model) + { + $this->setDateTime($model); + } + + /** + * Get the model for the field body. + * + * @return DateTimeImmutable + */ + public function getFieldBodyModel() + { + return $this->getDateTime(); + } + + /** + * Get the date-time representing the Date in this Header. + * + * @return DateTimeImmutable + */ + public function getDateTime() + { + return $this->dateTime; + } + + /** + * Set the date-time of the Date in this Header. + * + * If a DateTime instance is provided, it is converted to DateTimeImmutable. + */ + public function setDateTime(DateTimeInterface $dateTime) + { + $this->clearCachedValueIf($this->getCachedValue() != $dateTime->format(DateTime::RFC2822)); + if ($dateTime instanceof DateTime) { + $immutable = new DateTimeImmutable('@'.$dateTime->getTimestamp()); + $dateTime = $immutable->setTimezone($dateTime->getTimezone()); + } + $this->dateTime = $dateTime; + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@link toString()} for that). + * + * @see toString() + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + if (isset($this->dateTime)) { + $this->setCachedValue($this->dateTime->format(DateTime::RFC2822)); + } + } + + return $this->getCachedValue(); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php new file mode 100644 index 0000000..4fcdff4 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php @@ -0,0 +1,189 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\MessageIDValidation; +use Egulias\EmailValidator\Validation\RFCValidation; + +/** + * An ID MIME Header for something like Message-ID or Content-ID. + * + * @author Chris Corbyn + */ +class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_AbstractHeader +{ + /** + * The IDs used in the value of this Header. + * + * This may hold multiple IDs or just a single ID. + * + * @var string[] + */ + private $ids = []; + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; + + private $addressEncoder; + + /** + * Creates a new IdentificationHeader with the given $name and $id. + * + * @param string $name + */ + public function __construct($name, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null) + { + $this->setFieldName($name); + $this->emailValidator = $emailValidator; + $this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder(); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_ID; + } + + /** + * Set the model for the field body. + * + * This method takes a string ID, or an array of IDs. + * + * @param mixed $model + * + * @throws Swift_RfcComplianceException + */ + public function setFieldBodyModel($model) + { + $this->setId($model); + } + + /** + * Get the model for the field body. + * + * This method returns an array of IDs + * + * @return array + */ + public function getFieldBodyModel() + { + return $this->getIds(); + } + + /** + * Set the ID used in the value of this header. + * + * @param string|array $id + * + * @throws Swift_RfcComplianceException + */ + public function setId($id) + { + $this->setIds(\is_array($id) ? $id : [$id]); + } + + /** + * Get the ID used in the value of this Header. + * + * If multiple IDs are set only the first is returned. + * + * @return string + */ + public function getId() + { + if (\count($this->ids) > 0) { + return $this->ids[0]; + } + } + + /** + * Set a collection of IDs to use in the value of this Header. + * + * @param string[] $ids + * + * @throws Swift_RfcComplianceException + */ + public function setIds(array $ids) + { + $actualIds = []; + + foreach ($ids as $id) { + $this->assertValidId($id); + $actualIds[] = $id; + } + + $this->clearCachedValueIf($this->ids != $actualIds); + $this->ids = $actualIds; + } + + /** + * Get the list of IDs used in this Header. + * + * @return string[] + */ + public function getIds() + { + return $this->ids; + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@see toString()} for that). + * + * @see toString() + * + * @throws Swift_RfcComplianceException + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + $angleAddrs = []; + + foreach ($this->ids as $id) { + $angleAddrs[] = '<'.$this->addressEncoder->encodeString($id).'>'; + } + + $this->setCachedValue(implode(' ', $angleAddrs)); + } + + return $this->getCachedValue(); + } + + /** + * Throws an Exception if the id passed does not comply with RFC 2822. + * + * @param string $id + * + * @throws Swift_RfcComplianceException + */ + private function assertValidId($id) + { + $emailValidation = class_exists(MessageIDValidation::class) ? new MessageIDValidation() : new RFCValidation(); + + if (!$this->emailValidator->isValid($id, $emailValidation)) { + throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>'); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php new file mode 100644 index 0000000..ddd5e8c --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php @@ -0,0 +1,358 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + +/** + * A Mailbox Address MIME Header for something like From or Sender. + * + * @author Chris Corbyn + */ +class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader +{ + /** + * The mailboxes used in this Header. + * + * @var string[] + */ + private $mailboxes = []; + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; + + private $addressEncoder; + + /** + * Creates a new MailboxHeader with $name. + * + * @param string $name of Header + */ + public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null) + { + $this->setFieldName($name); + $this->setEncoder($encoder); + $this->emailValidator = $emailValidator; + $this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder(); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_MAILBOX; + } + + /** + * Set the model for the field body. + * + * This method takes a string, or an array of addresses. + * + * @param mixed $model + * + * @throws Swift_RfcComplianceException + */ + public function setFieldBodyModel($model) + { + $this->setNameAddresses($model); + } + + /** + * Get the model for the field body. + * + * This method returns an associative array like {@link getNameAddresses()} + * + * @throws Swift_RfcComplianceException + * + * @return array + */ + public function getFieldBodyModel() + { + return $this->getNameAddresses(); + } + + /** + * Set a list of mailboxes to be shown in this Header. + * + * The mailboxes can be a simple array of addresses, or an array of + * key=>value pairs where (email => personalName). + * Example: + * <code> + * <?php + * //Sets two mailboxes in the Header, one with a personal name + * $header->setNameAddresses(array( + * 'chris@swiftmailer.org' => 'Chris Corbyn', + * 'mark@swiftmailer.org' //No associated personal name + * )); + * ?> + * </code> + * + * @see __construct() + * @see setAddresses() + * @see setValue() + * + * @param string|string[] $mailboxes + * + * @throws Swift_RfcComplianceException + */ + public function setNameAddresses($mailboxes) + { + $this->mailboxes = $this->normalizeMailboxes((array) $mailboxes); + $this->setCachedValue(null); //Clear any cached value + } + + /** + * Get the full mailbox list of this Header as an array of valid RFC 2822 strings. + * + * Example: + * <code> + * <?php + * $header = new Swift_Mime_Headers_MailboxHeader('From', + * array('chris@swiftmailer.org' => 'Chris Corbyn', + * 'mark@swiftmailer.org' => 'Mark Corbyn') + * ); + * print_r($header->getNameAddressStrings()); + * // array ( + * // 0 => Chris Corbyn <chris@swiftmailer.org>, + * // 1 => Mark Corbyn <mark@swiftmailer.org> + * // ) + * ?> + * </code> + * + * @see getNameAddresses() + * @see toString() + * + * @throws Swift_RfcComplianceException + * + * @return string[] + */ + public function getNameAddressStrings() + { + return $this->createNameAddressStrings($this->getNameAddresses()); + } + + /** + * Get all mailboxes in this Header as key=>value pairs. + * + * The key is the address and the value is the name (or null if none set). + * Example: + * <code> + * <?php + * $header = new Swift_Mime_Headers_MailboxHeader('From', + * array('chris@swiftmailer.org' => 'Chris Corbyn', + * 'mark@swiftmailer.org' => 'Mark Corbyn') + * ); + * print_r($header->getNameAddresses()); + * // array ( + * // chris@swiftmailer.org => Chris Corbyn, + * // mark@swiftmailer.org => Mark Corbyn + * // ) + * ?> + * </code> + * + * @see getAddresses() + * @see getNameAddressStrings() + * + * @return string[] + */ + public function getNameAddresses() + { + return $this->mailboxes; + } + + /** + * Makes this Header represent a list of plain email addresses with no names. + * + * Example: + * <code> + * <?php + * //Sets three email addresses as the Header data + * $header->setAddresses( + * array('one@domain.tld', 'two@domain.tld', 'three@domain.tld') + * ); + * ?> + * </code> + * + * @see setNameAddresses() + * @see setValue() + * + * @param string[] $addresses + * + * @throws Swift_RfcComplianceException + */ + public function setAddresses($addresses) + { + $this->setNameAddresses(array_values((array) $addresses)); + } + + /** + * Get all email addresses in this Header. + * + * @see getNameAddresses() + * + * @return string[] + */ + public function getAddresses() + { + return array_keys($this->mailboxes); + } + + /** + * Remove one or more addresses from this Header. + * + * @param string|string[] $addresses + */ + public function removeAddresses($addresses) + { + $this->setCachedValue(null); + foreach ((array) $addresses as $address) { + unset($this->mailboxes[$address]); + } + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@link toString()} for that). + * + * @see toString() + * + * @throws Swift_RfcComplianceException + * + * @return string + */ + public function getFieldBody() + { + // Compute the string value of the header only if needed + if (null === $this->getCachedValue()) { + $this->setCachedValue($this->createMailboxListString($this->mailboxes)); + } + + return $this->getCachedValue(); + } + + /** + * Normalizes a user-input list of mailboxes into consistent key=>value pairs. + * + * @param string[] $mailboxes + * + * @return string[] + */ + protected function normalizeMailboxes(array $mailboxes) + { + $actualMailboxes = []; + + foreach ($mailboxes as $key => $value) { + if (\is_string($key)) { + //key is email addr + $address = $key; + $name = $value; + } else { + $address = $value; + $name = null; + } + $this->assertValidAddress($address); + $actualMailboxes[$address] = $name; + } + + return $actualMailboxes; + } + + /** + * Produces a compliant, formatted display-name based on the string given. + * + * @param string $displayName as displayed + * @param bool $shorten the first line to make remove for header name + * + * @return string + */ + protected function createDisplayNameString($displayName, $shorten = false) + { + return $this->createPhrase($this, $displayName, $this->getCharset(), $this->getEncoder(), $shorten); + } + + /** + * Creates a string form of all the mailboxes in the passed array. + * + * @param string[] $mailboxes + * + * @throws Swift_RfcComplianceException + * + * @return string + */ + protected function createMailboxListString(array $mailboxes) + { + return implode(', ', $this->createNameAddressStrings($mailboxes)); + } + + /** + * Redefine the encoding requirements for mailboxes. + * + * All "specials" must be encoded as the full header value will not be quoted + * + * @see RFC 2822 3.2.1 + * + * @param string $token + * + * @return bool + */ + protected function tokenNeedsEncoding($token) + { + return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token); + } + + /** + * Return an array of strings conforming the the name-addr spec of RFC 2822. + * + * @param string[] $mailboxes + * + * @return string[] + */ + private function createNameAddressStrings(array $mailboxes) + { + $strings = []; + + foreach ($mailboxes as $email => $name) { + $mailboxStr = $this->addressEncoder->encodeString($email); + if (null !== $name) { + $nameStr = $this->createDisplayNameString($name, empty($strings)); + $mailboxStr = $nameStr.' <'.$mailboxStr.'>'; + } + $strings[] = $mailboxStr; + } + + return $strings; + } + + /** + * Throws an Exception if the address passed does not comply with RFC 2822. + * + * @param string $address + * + * @throws Swift_RfcComplianceException if invalid + */ + private function assertValidAddress($address) + { + if (!$this->emailValidator->isValid($address, new RFCValidation())) { + throw new Swift_RfcComplianceException('Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.'); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php new file mode 100644 index 0000000..fafb5ba --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php @@ -0,0 +1,135 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An OpenDKIM Specific Header using only raw header datas without encoding. + * + * @author De Cock Xavier <xdecock@gmail.com> + * + * @deprecated since SwiftMailer 6.1.0; use Swift_Signers_DKIMSigner instead. + */ +class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header +{ + /** + * The value of this Header. + * + * @var string + */ + private $value; + + /** + * The name of this Header. + * + * @var string + */ + private $fieldName; + + /** + * @param string $name + */ + public function __construct($name) + { + $this->fieldName = $name; + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_TEXT; + } + + /** + * Set the model for the field body. + * + * This method takes a string for the field value. + * + * @param string $model + */ + public function setFieldBodyModel($model) + { + $this->setValue($model); + } + + /** + * Get the model for the field body. + * + * This method returns a string. + * + * @return string + */ + public function getFieldBodyModel() + { + return $this->getValue(); + } + + /** + * Get the (unencoded) value of this header. + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set the (unencoded) value of this header. + * + * @param string $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /** + * Get the value of this header prepared for rendering. + * + * @return string + */ + public function getFieldBody() + { + return $this->value; + } + + /** + * Get this Header rendered as a RFC 2822 compliant string. + * + * @return string + */ + public function toString() + { + return $this->fieldName.': '.$this->value."\r\n"; + } + + /** + * Set the Header FieldName. + * + * @see Swift_Mime_Header::getFieldName() + */ + public function getFieldName() + { + return $this->fieldName; + } + + /** + * Ignored. + */ + public function setCharset($charset) + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php new file mode 100644 index 0000000..47c15e6 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php @@ -0,0 +1,255 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An abstract base MIME Header. + * + * @author Chris Corbyn + */ +class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader +{ + /** + * RFC 2231's definition of a token. + * + * @var string + */ + const TOKEN_REGEX = '(?:[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E]+)'; + + /** + * The Encoder used to encode the parameters. + * + * @var Swift_Encoder + */ + private $paramEncoder; + + /** + * The parameters as an associative array. + * + * @var string[] + */ + private $params = []; + + /** + * Creates a new ParameterizedHeader with $name. + * + * @param string $name + */ + public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null) + { + parent::__construct($name, $encoder); + $this->paramEncoder = $paramEncoder; + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_PARAMETERIZED; + } + + /** + * Set the character set used in this Header. + * + * @param string $charset + */ + public function setCharset($charset) + { + parent::setCharset($charset); + if (isset($this->paramEncoder)) { + $this->paramEncoder->charsetChanged($charset); + } + } + + /** + * Set the value of $parameter. + * + * @param string $parameter + * @param string $value + */ + public function setParameter($parameter, $value) + { + $this->setParameters(array_merge($this->getParameters(), [$parameter => $value])); + } + + /** + * Get the value of $parameter. + * + * @param string $parameter + * + * @return string + */ + public function getParameter($parameter) + { + $params = $this->getParameters(); + + return $params[$parameter] ?? null; + } + + /** + * Set an associative array of parameter names mapped to values. + * + * @param string[] $parameters + */ + public function setParameters(array $parameters) + { + $this->clearCachedValueIf($this->params != $parameters); + $this->params = $parameters; + } + + /** + * Returns an associative array of parameter names mapped to values. + * + * @return string[] + */ + public function getParameters() + { + return $this->params; + } + + /** + * Get the value of this header prepared for rendering. + * + * @return string + */ + public function getFieldBody() //TODO: Check caching here + { + $body = parent::getFieldBody(); + foreach ($this->params as $name => $value) { + if (null !== $value) { + // Add the parameter + $body .= '; '.$this->createParameter($name, $value); + } + } + + return $body; + } + + /** + * Generate a list of all tokens in the final header. + * + * This doesn't need to be overridden in theory, but it is for implementation + * reasons to prevent potential breakage of attributes. + * + * @param string $string The string to tokenize + * + * @return array An array of tokens as strings + */ + protected function toTokens($string = null) + { + $tokens = parent::toTokens(parent::getFieldBody()); + + // Try creating any parameters + foreach ($this->params as $name => $value) { + if (null !== $value) { + // Add the semi-colon separator + $tokens[\count($tokens) - 1] .= ';'; + $tokens = array_merge($tokens, $this->generateTokenLines( + ' '.$this->createParameter($name, $value) + )); + } + } + + return $tokens; + } + + /** + * Render a RFC 2047 compliant header parameter from the $name and $value. + * + * @param string $name + * @param string $value + * + * @return string + */ + private function createParameter($name, $value) + { + $origValue = $value; + + $encoded = false; + // Allow room for parameter name, indices, "=" and DQUOTEs + $maxValueLength = $this->getMaxLineLength() - \strlen($name.'=*N"";') - 1; + $firstLineOffset = 0; + + // If it's not already a valid parameter value... + if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { + // TODO: text, or something else?? + // ... and it's not ascii + if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) { + $encoded = true; + // Allow space for the indices, charset and language + $maxValueLength = $this->getMaxLineLength() - \strlen($name.'*N*="";') - 1; + $firstLineOffset = \strlen( + $this->getCharset()."'".$this->getLanguage()."'" + ); + } + } + + // Encode if we need to + if ($encoded || \strlen($value) > $maxValueLength) { + if (isset($this->paramEncoder)) { + $value = $this->paramEncoder->encodeString( + $origValue, $firstLineOffset, $maxValueLength, $this->getCharset() + ); + } else { + // We have to go against RFC 2183/2231 in some areas for interoperability + $value = $this->getTokenAsEncodedWord($origValue); + $encoded = false; + } + } + + $valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : [$value]; + + // Need to add indices + if (\count($valueLines) > 1) { + $paramLines = []; + foreach ($valueLines as $i => $line) { + $paramLines[] = $name.'*'.$i. + $this->getEndOfParameterValue($line, true, 0 == $i); + } + + return implode(";\r\n ", $paramLines); + } else { + return $name.$this->getEndOfParameterValue( + $valueLines[0], $encoded, true + ); + } + } + + /** + * Returns the parameter value from the "=" and beyond. + * + * @param string $value to append + * @param bool $encoded + * @param bool $firstLine + * + * @return string + */ + private function getEndOfParameterValue($value, $encoded = false, $firstLine = false) + { + if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { + $value = '"'.$value.'"'; + } + $prepend = '='; + if ($encoded) { + $prepend = '*='; + if ($firstLine) { + $prepend = '*='.$this->getCharset()."'".$this->getLanguage(). + "'"; + } + } + + return $prepend.$value; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php new file mode 100644 index 0000000..81b421e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php @@ -0,0 +1,153 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + +/** + * A Path Header in Swift Mailer, such a Return-Path. + * + * @author Chris Corbyn + */ +class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader +{ + /** + * The address in this Header (if specified). + * + * @var string + */ + private $address; + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; + + private $addressEncoder; + + /** + * Creates a new PathHeader with the given $name. + * + * @param string $name + */ + public function __construct($name, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null) + { + $this->setFieldName($name); + $this->emailValidator = $emailValidator; + $this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder(); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_PATH; + } + + /** + * Set the model for the field body. + * This method takes a string for an address. + * + * @param string $model + * + * @throws Swift_RfcComplianceException + */ + public function setFieldBodyModel($model) + { + $this->setAddress($model); + } + + /** + * Get the model for the field body. + * This method returns a string email address. + * + * @return mixed + */ + public function getFieldBodyModel() + { + return $this->getAddress(); + } + + /** + * Set the Address which should appear in this Header. + * + * @param string $address + * + * @throws Swift_RfcComplianceException + */ + public function setAddress($address) + { + if (null === $address) { + $this->address = null; + } elseif ('' == $address) { + $this->address = ''; + } else { + $this->assertValidAddress($address); + $this->address = $address; + } + $this->setCachedValue(null); + } + + /** + * Get the address which is used in this Header (if any). + * + * Null is returned if no address is set. + * + * @return string + */ + public function getAddress() + { + return $this->address; + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@link toString()} for that). + * + * @see toString() + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + if (isset($this->address)) { + $address = $this->addressEncoder->encodeString($this->address); + $this->setCachedValue('<'.$address.'>'); + } + } + + return $this->getCachedValue(); + } + + /** + * Throws an Exception if the address passed does not comply with RFC 2822. + * + * @param string $address + * + * @throws Swift_RfcComplianceException If address is invalid + */ + private function assertValidAddress($address) + { + if (!$this->emailValidator->isValid($address, new RFCValidation())) { + throw new Swift_RfcComplianceException('Address set in PathHeader does not comply with addr-spec of RFC 2822.'); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php new file mode 100644 index 0000000..64f160d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php @@ -0,0 +1,109 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A Simple MIME Header. + * + * @author Chris Corbyn + */ +class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractHeader +{ + /** + * The value of this Header. + * + * @var string + */ + private $value; + + /** + * Creates a new SimpleHeader with $name. + * + * @param string $name + */ + public function __construct($name, Swift_Mime_HeaderEncoder $encoder) + { + $this->setFieldName($name); + $this->setEncoder($encoder); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_TEXT; + } + + /** + * Set the model for the field body. + * + * This method takes a string for the field value. + * + * @param string $model + */ + public function setFieldBodyModel($model) + { + $this->setValue($model); + } + + /** + * Get the model for the field body. + * + * This method returns a string. + * + * @return string + */ + public function getFieldBodyModel() + { + return $this->getValue(); + } + + /** + * Get the (unencoded) value of this header. + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set the (unencoded) value of this header. + * + * @param string $value + */ + public function setValue($value) + { + $this->clearCachedValueIf($this->value != $value); + $this->value = $value; + } + + /** + * Get the value of this header prepared for rendering. + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + $this->setCachedValue( + $this->encodeWords($this, $this->value) + ); + } + + return $this->getCachedValue(); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php new file mode 100644 index 0000000..3ce35f2 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Message ID generator. + */ +class Swift_Mime_IdGenerator implements Swift_IdGenerator +{ + private $idRight; + + /** + * @param string $idRight + */ + public function __construct($idRight) + { + $this->idRight = $idRight; + } + + /** + * Returns the right-hand side of the "@" used in all generated IDs. + * + * @return string + */ + public function getIdRight() + { + return $this->idRight; + } + + /** + * Sets the right-hand side of the "@" to use in all generated IDs. + * + * @param string $idRight + */ + public function setIdRight($idRight) + { + $this->idRight = $idRight; + } + + /** + * @return string + */ + public function generateId() + { + // 32 hex values for the left part + return bin2hex(random_bytes(16)).'@'.$this->idRight; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimePart.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimePart.php new file mode 100644 index 0000000..d0b2e65 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimePart.php @@ -0,0 +1,199 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A MIME part, in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity +{ + /** The format parameter last specified by the user */ + protected $userFormat; + + /** The charset last specified by the user */ + protected $userCharset; + + /** The delsp parameter last specified by the user */ + protected $userDelSp; + + /** The nesting level of this MimePart */ + private $nestingLevel = self::LEVEL_ALTERNATIVE; + + /** + * Create a new MimePart with $headers, $encoder and $cache. + * + * @param string $charset + */ + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null) + { + parent::__construct($headers, $encoder, $cache, $idGenerator); + $this->setContentType('text/plain'); + if (null !== $charset) { + $this->setCharset($charset); + } + } + + /** + * Set the body of this entity, either as a string, or as an instance of + * {@link Swift_OutputByteStream}. + * + * @param mixed $body + * @param string $contentType optional + * @param string $charset optional + * + * @return $this + */ + public function setBody($body, $contentType = null, $charset = null) + { + if (isset($charset)) { + $this->setCharset($charset); + } + $body = $this->convertString($body); + + parent::setBody($body, $contentType); + + return $this; + } + + /** + * Get the character set of this entity. + * + * @return string + */ + public function getCharset() + { + return $this->getHeaderParameter('Content-Type', 'charset'); + } + + /** + * Set the character set of this entity. + * + * @param string $charset + * + * @return $this + */ + public function setCharset($charset) + { + $this->setHeaderParameter('Content-Type', 'charset', $charset); + if ($charset !== $this->userCharset) { + $this->clearCache(); + } + $this->userCharset = $charset; + parent::charsetChanged($charset); + + return $this; + } + + /** + * Get the format of this entity (i.e. flowed or fixed). + * + * @return string + */ + public function getFormat() + { + return $this->getHeaderParameter('Content-Type', 'format'); + } + + /** + * Set the format of this entity (flowed or fixed). + * + * @param string $format + * + * @return $this + */ + public function setFormat($format) + { + $this->setHeaderParameter('Content-Type', 'format', $format); + $this->userFormat = $format; + + return $this; + } + + /** + * Test if delsp is being used for this entity. + * + * @return bool + */ + public function getDelSp() + { + return 'yes' === $this->getHeaderParameter('Content-Type', 'delsp'); + } + + /** + * Turn delsp on or off for this entity. + * + * @param bool $delsp + * + * @return $this + */ + public function setDelSp($delsp = true) + { + $this->setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); + $this->userDelSp = $delsp; + + return $this; + } + + /** + * Get the nesting level of this entity. + * + * @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED + * + * @return int + */ + public function getNestingLevel() + { + return $this->nestingLevel; + } + + /** + * Receive notification that the charset has changed on this document, or a + * parent document. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->setCharset($charset); + } + + /** Fix the content-type and encoding of this entity */ + protected function fixHeaders() + { + parent::fixHeaders(); + if (\count($this->getChildren())) { + $this->setHeaderParameter('Content-Type', 'charset', null); + $this->setHeaderParameter('Content-Type', 'format', null); + $this->setHeaderParameter('Content-Type', 'delsp', null); + } else { + $this->setCharset($this->userCharset); + $this->setFormat($this->userFormat); + $this->setDelSp($this->userDelSp); + } + } + + /** Set the nesting level of this entity */ + protected function setNestingLevel($level) + { + $this->nestingLevel = $level; + } + + /** Encode charset when charset is not utf-8 */ + protected function convertString($string) + { + $charset = strtolower($this->getCharset() ?? ''); + if (!\in_array($charset, ['utf-8', 'iso-8859-1', 'iso-8859-15', ''])) { + return mb_convert_encoding($string, $charset, 'utf-8'); + } + + return $string; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderFactory.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderFactory.php new file mode 100644 index 0000000..ab3ce6b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderFactory.php @@ -0,0 +1,195 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Egulias\EmailValidator\EmailValidator; + +/** + * Creates MIME headers. + * + * @author Chris Corbyn + */ +class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver +{ + /** The HeaderEncoder used by these headers */ + private $encoder; + + /** The Encoder used by parameters */ + private $paramEncoder; + + /** Strict EmailValidator */ + private $emailValidator; + + /** The charset of created Headers */ + private $charset; + + /** Swift_AddressEncoder */ + private $addressEncoder; + + /** + * Creates a new SimpleHeaderFactory using $encoder and $paramEncoder. + * + * @param string|null $charset + */ + public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, EmailValidator $emailValidator, $charset = null, Swift_AddressEncoder $addressEncoder = null) + { + $this->encoder = $encoder; + $this->paramEncoder = $paramEncoder; + $this->emailValidator = $emailValidator; + $this->charset = $charset; + $this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder(); + } + + /** + * Create a new Mailbox Header with a list of $addresses. + * + * @param string $name + * @param array|string|null $addresses + * + * @return Swift_Mime_Header + */ + public function createMailboxHeader($name, $addresses = null) + { + $header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator, $this->addressEncoder); + if (isset($addresses)) { + $header->setFieldBodyModel($addresses); + } + $this->setHeaderCharset($header); + + return $header; + } + + /** + * Create a new Date header using $dateTime. + * + * @param string $name + * + * @return Swift_Mime_Header + */ + public function createDateHeader($name, DateTimeInterface $dateTime = null) + { + $header = new Swift_Mime_Headers_DateHeader($name); + if (isset($dateTime)) { + $header->setFieldBodyModel($dateTime); + } + $this->setHeaderCharset($header); + + return $header; + } + + /** + * Create a new basic text header with $name and $value. + * + * @param string $name + * @param string $value + * + * @return Swift_Mime_Header + */ + public function createTextHeader($name, $value = null) + { + $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->encoder); + if (isset($value)) { + $header->setFieldBodyModel($value); + } + $this->setHeaderCharset($header); + + return $header; + } + + /** + * Create a new ParameterizedHeader with $name, $value and $params. + * + * @param string $name + * @param string $value + * @param array $params + * + * @return Swift_Mime_Headers_ParameterizedHeader + */ + public function createParameterizedHeader($name, $value = null, $params = []) + { + $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, ('content-disposition' == strtolower($name ?? '')) ? $this->paramEncoder : null); + if (isset($value)) { + $header->setFieldBodyModel($value); + } + foreach ($params as $k => $v) { + $header->setParameter($k, $v); + } + $this->setHeaderCharset($header); + + return $header; + } + + /** + * Create a new ID header for Message-ID or Content-ID. + * + * @param string $name + * @param string|array $ids + * + * @return Swift_Mime_Header + */ + public function createIdHeader($name, $ids = null) + { + $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->emailValidator); + if (isset($ids)) { + $header->setFieldBodyModel($ids); + } + $this->setHeaderCharset($header); + + return $header; + } + + /** + * Create a new Path header with an address (path) in it. + * + * @param string $name + * @param string $path + * + * @return Swift_Mime_Header + */ + public function createPathHeader($name, $path = null) + { + $header = new Swift_Mime_Headers_PathHeader($name, $this->emailValidator); + if (isset($path)) { + $header->setFieldBodyModel($path); + } + $this->setHeaderCharset($header); + + return $header; + } + + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->charset = $charset; + $this->encoder->charsetChanged($charset); + $this->paramEncoder->charsetChanged($charset); + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + $this->encoder = clone $this->encoder; + $this->paramEncoder = clone $this->paramEncoder; + $this->addressEncoder = clone $this->addressEncoder; + } + + /** Apply the charset to the Header */ + private function setHeaderCharset(Swift_Mime_Header $header) + { + if (isset($this->charset)) { + $header->setCharset($this->charset); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php new file mode 100644 index 0000000..5195bcf --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php @@ -0,0 +1,399 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A collection of MIME headers. + * + * @author Chris Corbyn + */ +class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver +{ + /** HeaderFactory */ + private $factory; + + /** Collection of set Headers */ + private $headers = []; + + /** Field ordering details */ + private $order = []; + + /** List of fields which are required to be displayed */ + private $required = []; + + /** The charset used by Headers */ + private $charset; + + /** + * Create a new SimpleHeaderSet with the given $factory. + * + * @param string $charset + */ + public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null) + { + $this->factory = $factory; + if (isset($charset)) { + $this->setCharset($charset); + } + } + + public function newInstance() + { + return new self($this->factory); + } + + /** + * Set the charset used by these headers. + * + * @param string $charset + */ + public function setCharset($charset) + { + $this->charset = $charset; + $this->factory->charsetChanged($charset); + $this->notifyHeadersOfCharset($charset); + } + + /** + * Add a new Mailbox Header with a list of $addresses. + * + * @param string $name + * @param array|string $addresses + */ + public function addMailboxHeader($name, $addresses = null) + { + $this->storeHeader($name, $this->factory->createMailboxHeader($name, $addresses)); + } + + /** + * Add a new Date header using $dateTime. + * + * @param string $name + */ + public function addDateHeader($name, DateTimeInterface $dateTime = null) + { + $this->storeHeader($name, $this->factory->createDateHeader($name, $dateTime)); + } + + /** + * Add a new basic text header with $name and $value. + * + * @param string $name + * @param string $value + */ + public function addTextHeader($name, $value = null) + { + $this->storeHeader($name, $this->factory->createTextHeader($name, $value)); + } + + /** + * Add a new ParameterizedHeader with $name, $value and $params. + * + * @param string $name + * @param string $value + * @param array $params + */ + public function addParameterizedHeader($name, $value = null, $params = []) + { + $this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params)); + } + + /** + * Add a new ID header for Message-ID or Content-ID. + * + * @param string $name + * @param string|array $ids + */ + public function addIdHeader($name, $ids = null) + { + $this->storeHeader($name, $this->factory->createIdHeader($name, $ids)); + } + + /** + * Add a new Path header with an address (path) in it. + * + * @param string $name + * @param string $path + */ + public function addPathHeader($name, $path = null) + { + $this->storeHeader($name, $this->factory->createPathHeader($name, $path)); + } + + /** + * Returns true if at least one header with the given $name exists. + * + * If multiple headers match, the actual one may be specified by $index. + * + * @param string $name + * @param int $index + * + * @return bool + */ + public function has($name, $index = 0) + { + $lowerName = strtolower($name ?? ''); + + if (!\array_key_exists($lowerName, $this->headers)) { + return false; + } + + if (\func_num_args() < 2) { + // index was not specified, so we only need to check that there is at least one header value set + return (bool) \count($this->headers[$lowerName]); + } + + return \array_key_exists($index, $this->headers[$lowerName]); + } + + /** + * Set a header in the HeaderSet. + * + * The header may be a previously fetched header via {@link get()} or it may + * be one that has been created separately. + * + * If $index is specified, the header will be inserted into the set at this + * offset. + * + * @param int $index + */ + public function set(Swift_Mime_Header $header, $index = 0) + { + $this->storeHeader($header->getFieldName(), $header, $index); + } + + /** + * Get the header with the given $name. + * + * If multiple headers match, the actual one may be specified by $index. + * Returns NULL if none present. + * + * @param string $name + * @param int $index + * + * @return Swift_Mime_Header|null + */ + public function get($name, $index = 0) + { + $name = strtolower($name ?? ''); + + if (\func_num_args() < 2) { + if ($this->has($name)) { + $values = array_values($this->headers[$name]); + + return array_shift($values); + } + } else { + if ($this->has($name, $index)) { + return $this->headers[$name][$index]; + } + } + } + + /** + * Get all headers with the given $name. + * + * @param string $name + * + * @return array + */ + public function getAll($name = null) + { + if (!isset($name)) { + $headers = []; + foreach ($this->headers as $collection) { + $headers = array_merge($headers, $collection); + } + + return $headers; + } + + $lowerName = strtolower($name ?? ''); + if (!\array_key_exists($lowerName, $this->headers)) { + return []; + } + + return $this->headers[$lowerName]; + } + + /** + * Return the name of all Headers. + * + * @return array + */ + public function listAll() + { + $headers = $this->headers; + if ($this->canSort()) { + uksort($headers, [$this, 'sortHeaders']); + } + + return array_keys($headers); + } + + /** + * Remove the header with the given $name if it's set. + * + * If multiple headers match, the actual one may be specified by $index. + * + * @param string $name + * @param int $index + */ + public function remove($name, $index = 0) + { + $lowerName = strtolower($name ?? ''); + unset($this->headers[$lowerName][$index]); + } + + /** + * Remove all headers with the given $name. + * + * @param string $name + */ + public function removeAll($name) + { + $lowerName = strtolower($name ?? ''); + unset($this->headers[$lowerName]); + } + + /** + * Define a list of Header names as an array in the correct order. + * + * These Headers will be output in the given order where present. + */ + public function defineOrdering(array $sequence) + { + $this->order = array_flip(array_map('strtolower', $sequence)); + } + + /** + * Set a list of header names which must always be displayed when set. + * + * Usually headers without a field value won't be output unless set here. + */ + public function setAlwaysDisplayed(array $names) + { + $this->required = array_flip(array_map('strtolower', $names)); + } + + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->setCharset($charset); + } + + /** + * Returns a string with a representation of all headers. + * + * @return string + */ + public function toString() + { + $string = ''; + $headers = $this->headers; + if ($this->canSort()) { + uksort($headers, [$this, 'sortHeaders']); + } + foreach ($headers as $collection) { + foreach ($collection as $header) { + if ($this->isDisplayed($header) || '' != $header->getFieldBody()) { + $string .= $header->toString(); + } + } + } + + return $string; + } + + /** + * Returns a string representation of this object. + * + * @return string + * + * @see toString() + */ + public function __toString() + { + return $this->toString(); + } + + /** Save a Header to the internal collection */ + private function storeHeader($name, Swift_Mime_Header $header, $offset = null) + { + if (!isset($this->headers[strtolower($name ?? '')])) { + $this->headers[strtolower($name ?? '')] = []; + } + if (!isset($offset)) { + $this->headers[strtolower($name ?? '')][] = $header; + } else { + $this->headers[strtolower($name ?? '')][$offset] = $header; + } + } + + /** Test if the headers can be sorted */ + private function canSort() + { + return \count($this->order) > 0; + } + + /** uksort() algorithm for Header ordering */ + private function sortHeaders($a, $b) + { + $lowerA = strtolower($a ?? ''); + $lowerB = strtolower($b ?? ''); + $aPos = \array_key_exists($lowerA, $this->order) ? $this->order[$lowerA] : -1; + $bPos = \array_key_exists($lowerB, $this->order) ? $this->order[$lowerB] : -1; + + if (-1 === $aPos && -1 === $bPos) { + // just be sure to be determinist here + return $a > $b ? -1 : 1; + } + + if (-1 == $aPos) { + return 1; + } elseif (-1 == $bPos) { + return -1; + } + + return $aPos < $bPos ? -1 : 1; + } + + /** Test if the given Header is always displayed */ + private function isDisplayed(Swift_Mime_Header $header) + { + return \array_key_exists(strtolower($header->getFieldName() ?? ''), $this->required); + } + + /** Notify all Headers of the new charset */ + private function notifyHeadersOfCharset($charset) + { + foreach ($this->headers as $headerGroup) { + foreach ($headerGroup as $header) { + $header->setCharset($charset); + } + } + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + $this->factory = clone $this->factory; + foreach ($this->headers as $groupKey => $headerGroup) { + foreach ($headerGroup as $key => $header) { + $this->headers[$groupKey][$key] = clone $header; + } + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php new file mode 100644 index 0000000..62da165 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php @@ -0,0 +1,642 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * The default email message class. + * + * @author Chris Corbyn + */ +class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart +{ + const PRIORITY_HIGHEST = 1; + const PRIORITY_HIGH = 2; + const PRIORITY_NORMAL = 3; + const PRIORITY_LOW = 4; + const PRIORITY_LOWEST = 5; + + /** + * Create a new SimpleMessage with $headers, $encoder and $cache. + * + * @param string $charset + */ + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null) + { + parent::__construct($headers, $encoder, $cache, $idGenerator, $charset); + $this->getHeaders()->defineOrdering([ + 'Return-Path', + 'Received', + 'DKIM-Signature', + 'DomainKey-Signature', + 'Sender', + 'Message-ID', + 'Date', + 'Subject', + 'From', + 'Reply-To', + 'To', + 'Cc', + 'Bcc', + 'MIME-Version', + 'Content-Type', + 'Content-Transfer-Encoding', + ]); + $this->getHeaders()->setAlwaysDisplayed(['Date', 'Message-ID', 'From']); + $this->getHeaders()->addTextHeader('MIME-Version', '1.0'); + $this->setDate(new DateTimeImmutable()); + $this->setId($this->getId()); + $this->getHeaders()->addMailboxHeader('From'); + } + + /** + * Always returns {@link LEVEL_TOP} for a message instance. + * + * @return int + */ + public function getNestingLevel() + { + return self::LEVEL_TOP; + } + + /** + * Set the subject of this message. + * + * @param string $subject + * + * @return $this + */ + public function setSubject($subject) + { + if (!$this->setHeaderFieldModel('Subject', $subject)) { + $this->getHeaders()->addTextHeader('Subject', $subject); + } + + return $this; + } + + /** + * Get the subject of this message. + * + * @return string + */ + public function getSubject() + { + return $this->getHeaderFieldModel('Subject'); + } + + /** + * Set the date at which this message was created. + * + * @return $this + */ + public function setDate(DateTimeInterface $dateTime) + { + if (!$this->setHeaderFieldModel('Date', $dateTime)) { + $this->getHeaders()->addDateHeader('Date', $dateTime); + } + + return $this; + } + + /** + * Get the date at which this message was created. + * + * @return DateTimeInterface + */ + public function getDate() + { + return $this->getHeaderFieldModel('Date'); + } + + /** + * Set the return-path (the bounce address) of this message. + * + * @param string $address + * + * @return $this + */ + public function setReturnPath($address) + { + if (!$this->setHeaderFieldModel('Return-Path', $address)) { + $this->getHeaders()->addPathHeader('Return-Path', $address); + } + + return $this; + } + + /** + * Get the return-path (bounce address) of this message. + * + * @return string + */ + public function getReturnPath() + { + return $this->getHeaderFieldModel('Return-Path'); + } + + /** + * Set the sender of this message. + * + * This does not override the From field, but it has a higher significance. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + public function setSender($address, $name = null) + { + if (!\is_array($address) && isset($name)) { + $address = [$address => $name]; + } + + if (!$this->setHeaderFieldModel('Sender', (array) $address)) { + $this->getHeaders()->addMailboxHeader('Sender', (array) $address); + } + + return $this; + } + + /** + * Get the sender of this message. + * + * @return string + */ + public function getSender() + { + return $this->getHeaderFieldModel('Sender'); + } + + /** + * Add a From: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + public function addFrom($address, $name = null) + { + $current = $this->getFrom(); + $current[$address] = $name; + + return $this->setFrom($current); + } + + /** + * Set the from address of this message. + * + * You may pass an array of addresses if this message is from multiple people. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param string|array $addresses + * @param string $name optional + * + * @return $this + */ + public function setFrom($addresses, $name = null) + { + if (!\is_array($addresses) && isset($name)) { + $addresses = [$addresses => $name]; + } + + if (!$this->setHeaderFieldModel('From', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('From', (array) $addresses); + } + + return $this; + } + + /** + * Get the from address of this message. + * + * @return mixed + */ + public function getFrom() + { + return $this->getHeaderFieldModel('From'); + } + + /** + * Add a Reply-To: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + public function addReplyTo($address, $name = null) + { + $current = $this->getReplyTo(); + $current[$address] = $name; + + return $this->setReplyTo($current); + } + + /** + * Set the reply-to address of this message. + * + * You may pass an array of addresses if replies will go to multiple people. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return $this + */ + public function setReplyTo($addresses, $name = null) + { + if (!\is_array($addresses) && isset($name)) { + $addresses = [$addresses => $name]; + } + + if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses); + } + + return $this; + } + + /** + * Get the reply-to address of this message. + * + * @return string + */ + public function getReplyTo() + { + return $this->getHeaderFieldModel('Reply-To'); + } + + /** + * Add a To: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + public function addTo($address, $name = null) + { + $current = $this->getTo(); + $current[$address] = $name; + + return $this->setTo($current); + } + + /** + * Set the to addresses of this message. + * + * If multiple recipients will receive the message an array should be used. + * Example: array('receiver@domain.org', 'other@domain.org' => 'A name') + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return $this + */ + public function setTo($addresses, $name = null) + { + if (!\is_array($addresses) && isset($name)) { + $addresses = [$addresses => $name]; + } + + if (!$this->setHeaderFieldModel('To', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('To', (array) $addresses); + } + + return $this; + } + + /** + * Get the To addresses of this message. + * + * @return array + */ + public function getTo() + { + return $this->getHeaderFieldModel('To'); + } + + /** + * Add a Cc: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + public function addCc($address, $name = null) + { + $current = $this->getCc(); + $current[$address] = $name; + + return $this->setCc($current); + } + + /** + * Set the Cc addresses of this message. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return $this + */ + public function setCc($addresses, $name = null) + { + if (!\is_array($addresses) && isset($name)) { + $addresses = [$addresses => $name]; + } + + if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('Cc', (array) $addresses); + } + + return $this; + } + + /** + * Get the Cc address of this message. + * + * @return array + */ + public function getCc() + { + return $this->getHeaderFieldModel('Cc'); + } + + /** + * Add a Bcc: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + public function addBcc($address, $name = null) + { + $current = $this->getBcc(); + $current[$address] = $name; + + return $this->setBcc($current); + } + + /** + * Set the Bcc addresses of this message. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return $this + */ + public function setBcc($addresses, $name = null) + { + if (!\is_array($addresses) && isset($name)) { + $addresses = [$addresses => $name]; + } + + if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses); + } + + return $this; + } + + /** + * Get the Bcc addresses of this message. + * + * @return array + */ + public function getBcc() + { + return $this->getHeaderFieldModel('Bcc'); + } + + /** + * Set the priority of this message. + * + * The value is an integer where 1 is the highest priority and 5 is the lowest. + * + * @param int $priority + * + * @return $this + */ + public function setPriority($priority) + { + $priorityMap = [ + self::PRIORITY_HIGHEST => 'Highest', + self::PRIORITY_HIGH => 'High', + self::PRIORITY_NORMAL => 'Normal', + self::PRIORITY_LOW => 'Low', + self::PRIORITY_LOWEST => 'Lowest', + ]; + $pMapKeys = array_keys($priorityMap); + if ($priority > max($pMapKeys)) { + $priority = max($pMapKeys); + } elseif ($priority < min($pMapKeys)) { + $priority = min($pMapKeys); + } + if (!$this->setHeaderFieldModel('X-Priority', + sprintf('%d (%s)', $priority, $priorityMap[$priority]))) { + $this->getHeaders()->addTextHeader('X-Priority', + sprintf('%d (%s)', $priority, $priorityMap[$priority])); + } + + return $this; + } + + /** + * Get the priority of this message. + * + * The returned value is an integer where 1 is the highest priority and 5 + * is the lowest. + * + * @return int + */ + public function getPriority() + { + list($priority) = sscanf($this->getHeaderFieldModel('X-Priority'), + '%[1-5]' + ); + + return $priority ?? 3; + } + + /** + * Ask for a delivery receipt from the recipient to be sent to $addresses. + * + * @param array $addresses + * + * @return $this + */ + public function setReadReceiptTo($addresses) + { + if (!$this->setHeaderFieldModel('Disposition-Notification-To', $addresses)) { + $this->getHeaders() + ->addMailboxHeader('Disposition-Notification-To', $addresses); + } + + return $this; + } + + /** + * Get the addresses to which a read-receipt will be sent. + * + * @return string + */ + public function getReadReceiptTo() + { + return $this->getHeaderFieldModel('Disposition-Notification-To'); + } + + /** + * Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart. + * + * @return $this + */ + public function attach(Swift_Mime_SimpleMimeEntity $entity) + { + $this->setChildren(array_merge($this->getChildren(), [$entity])); + + return $this; + } + + /** + * Remove an already attached entity. + * + * @return $this + */ + public function detach(Swift_Mime_SimpleMimeEntity $entity) + { + $newChildren = []; + foreach ($this->getChildren() as $child) { + if ($entity !== $child) { + $newChildren[] = $child; + } + } + $this->setChildren($newChildren); + + return $this; + } + + /** + * Attach a {@link Swift_Mime_SimpleMimeEntity} and return it's CID source. + * + * This method should be used when embedding images or other data in a message. + * + * @return string + */ + public function embed(Swift_Mime_SimpleMimeEntity $entity) + { + $this->attach($entity); + + return 'cid:'.$entity->getId(); + } + + /** + * Get this message as a complete string. + * + * @return string + */ + public function toString() + { + if (\count($children = $this->getChildren()) > 0 && '' != $this->getBody()) { + $this->setChildren(array_merge([$this->becomeMimePart()], $children)); + $string = parent::toString(); + $this->setChildren($children); + } else { + $string = parent::toString(); + } + + return $string; + } + + /** + * Returns a string representation of this object. + * + * @see toString() + * + * @return string + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Write this message to a {@link Swift_InputByteStream}. + */ + public function toByteStream(Swift_InputByteStream $is) + { + if (\count($children = $this->getChildren()) > 0 && '' != $this->getBody()) { + $this->setChildren(array_merge([$this->becomeMimePart()], $children)); + parent::toByteStream($is); + $this->setChildren($children); + } else { + parent::toByteStream($is); + } + } + + /** @see Swift_Mime_SimpleMimeEntity::getIdField() */ + protected function getIdField() + { + return 'Message-ID'; + } + + /** Turn the body of this message into a child of itself if needed */ + protected function becomeMimePart() + { + $part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(), + $this->getCache(), $this->getIdGenerator(), $this->userCharset + ); + $part->setContentType($this->userContentType); + $part->setBody($this->getBody()); + $part->setFormat($this->userFormat); + $part->setDelSp($this->userDelSp); + $part->setNestingLevel($this->getTopNestingLevel()); + + return $part; + } + + /** Get the highest nesting level nested inside this message */ + private function getTopNestingLevel() + { + $highestLevel = $this->getNestingLevel(); + foreach ($this->getChildren() as $child) { + $childLevel = $child->getNestingLevel(); + if ($highestLevel < $childLevel) { + $highestLevel = $childLevel; + } + } + + return $highestLevel; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php new file mode 100644 index 0000000..03eaf47 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php @@ -0,0 +1,826 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A MIME entity, in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_Mime_EncodingObserver +{ + /** Main message document; there can only be one of these */ + const LEVEL_TOP = 16; + + /** An entity which nests with the same precedence as an attachment */ + const LEVEL_MIXED = 256; + + /** An entity which nests with the same precedence as a mime part */ + const LEVEL_ALTERNATIVE = 4096; + + /** An entity which nests with the same precedence as embedded content */ + const LEVEL_RELATED = 65536; + + /** A collection of Headers for this mime entity */ + private $headers; + + /** The body as a string, or a stream */ + private $body; + + /** The encoder that encodes the body into a streamable format */ + private $encoder; + + /** Message ID generator */ + private $idGenerator; + + /** A mime boundary, if any is used */ + private $boundary; + + /** Mime types to be used based on the nesting level */ + private $compositeRanges = [ + 'multipart/mixed' => [self::LEVEL_TOP, self::LEVEL_MIXED], + 'multipart/alternative' => [self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE], + 'multipart/related' => [self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED], + ]; + + /** A set of filter rules to define what level an entity should be nested at */ + private $compoundLevelFilters = []; + + /** The nesting level of this entity */ + private $nestingLevel = self::LEVEL_ALTERNATIVE; + + /** A KeyCache instance used during encoding and streaming */ + private $cache; + + /** Direct descendants of this entity */ + private $immediateChildren = []; + + /** All descendants of this entity */ + private $children = []; + + /** The maximum line length of the body of this entity */ + private $maxLineLength = 78; + + /** The order in which alternative mime types should appear */ + private $alternativePartOrder = [ + 'text/plain' => 1, + 'text/html' => 2, + 'multipart/related' => 3, + ]; + + /** The CID of this entity */ + private $id; + + /** The key used for accessing the cache */ + private $cacheKey; + + protected $userContentType; + + /** + * Create a new SimpleMimeEntity with $headers, $encoder and $cache. + */ + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator) + { + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values + $this->cache = $cache; + $this->headers = $headers; + $this->idGenerator = $idGenerator; + $this->setEncoder($encoder); + $this->headers->defineOrdering(['Content-Type', 'Content-Transfer-Encoding']); + + // This array specifies that, when the entire MIME document contains + // $compoundLevel, then for each child within $level, if its Content-Type + // is $contentType then it should be treated as if it's level is + // $neededLevel instead. I tried to write that unambiguously! :-\ + // Data Structure: + // array ( + // $compoundLevel => array( + // $level => array( + // $contentType => $neededLevel + // ) + // ) + // ) + + $this->compoundLevelFilters = [ + (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => [ + self::LEVEL_ALTERNATIVE => [ + 'text/plain' => self::LEVEL_ALTERNATIVE, + 'text/html' => self::LEVEL_RELATED, + ], + ], + ]; + + $this->id = $this->idGenerator->generateId(); + } + + /** + * Generate a new Content-ID or Message-ID for this MIME entity. + * + * @return string + */ + public function generateId() + { + $this->setId($this->idGenerator->generateId()); + + return $this->id; + } + + /** + * Get the {@link Swift_Mime_SimpleHeaderSet} for this entity. + * + * @return Swift_Mime_SimpleHeaderSet + */ + public function getHeaders() + { + return $this->headers; + } + + /** + * Get the nesting level of this entity. + * + * @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE + * + * @return int + */ + public function getNestingLevel() + { + return $this->nestingLevel; + } + + /** + * Get the Content-type of this entity. + * + * @return string + */ + public function getContentType() + { + return $this->getHeaderFieldModel('Content-Type'); + } + + /** + * Get the Body Content-type of this entity. + * + * @return string + */ + public function getBodyContentType() + { + return $this->userContentType; + } + + /** + * Set the Content-type of this entity. + * + * @param string $type + * + * @return $this + */ + public function setContentType($type) + { + $this->setContentTypeInHeaders($type); + // Keep track of the value so that if the content-type changes automatically + // due to added child entities, it can be restored if they are later removed + $this->userContentType = $type; + + return $this; + } + + /** + * Get the CID of this entity. + * + * The CID will only be present in headers if a Content-ID header is present. + * + * @return string + */ + public function getId() + { + $tmp = (array) $this->getHeaderFieldModel($this->getIdField()); + + return $this->headers->has($this->getIdField()) ? current($tmp) : $this->id; + } + + /** + * Set the CID of this entity. + * + * @param string $id + * + * @return $this + */ + public function setId($id) + { + if (!$this->setHeaderFieldModel($this->getIdField(), $id)) { + $this->headers->addIdHeader($this->getIdField(), $id); + } + $this->id = $id; + + return $this; + } + + /** + * Get the description of this entity. + * + * This value comes from the Content-Description header if set. + * + * @return string + */ + public function getDescription() + { + return $this->getHeaderFieldModel('Content-Description'); + } + + /** + * Set the description of this entity. + * + * This method sets a value in the Content-ID header. + * + * @param string $description + * + * @return $this + */ + public function setDescription($description) + { + if (!$this->setHeaderFieldModel('Content-Description', $description)) { + $this->headers->addTextHeader('Content-Description', $description); + } + + return $this; + } + + /** + * Get the maximum line length of the body of this entity. + * + * @return int + */ + public function getMaxLineLength() + { + return $this->maxLineLength; + } + + /** + * Set the maximum line length of lines in this body. + * + * Though not enforced by the library, lines should not exceed 1000 chars. + * + * @param int $length + * + * @return $this + */ + public function setMaxLineLength($length) + { + $this->maxLineLength = $length; + + return $this; + } + + /** + * Get all children added to this entity. + * + * @return Swift_Mime_SimpleMimeEntity[] + */ + public function getChildren() + { + return $this->children; + } + + /** + * Set all children of this entity. + * + * @param Swift_Mime_SimpleMimeEntity[] $children + * @param int $compoundLevel For internal use only + * + * @return $this + */ + public function setChildren(array $children, $compoundLevel = null) + { + // TODO: Try to refactor this logic + $compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children); + $immediateChildren = []; + $grandchildren = []; + $newContentType = $this->userContentType; + + foreach ($children as $child) { + $level = $this->getNeededChildLevel($child, $compoundLevel); + if (empty($immediateChildren)) { + //first iteration + $immediateChildren = [$child]; + } else { + $nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); + if ($nextLevel == $level) { + $immediateChildren[] = $child; + } elseif ($level < $nextLevel) { + // Re-assign immediateChildren to grandchildren + $grandchildren = array_merge($grandchildren, $immediateChildren); + // Set new children + $immediateChildren = [$child]; + } else { + $grandchildren[] = $child; + } + } + } + + if ($immediateChildren) { + $lowestLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); + + // Determine which composite media type is needed to accommodate the + // immediate children + foreach ($this->compositeRanges as $mediaType => $range) { + if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) { + $newContentType = $mediaType; + + break; + } + } + + // Put any grandchildren in a subpart + if (!empty($grandchildren)) { + $subentity = $this->createChild(); + $subentity->setNestingLevel($lowestLevel); + $subentity->setChildren($grandchildren, $compoundLevel); + array_unshift($immediateChildren, $subentity); + } + } + + $this->immediateChildren = $immediateChildren; + $this->children = $children; + $this->setContentTypeInHeaders($newContentType); + $this->fixHeaders(); + $this->sortChildren(); + + return $this; + } + + /** + * Get the body of this entity as a string. + * + * @return string + */ + public function getBody() + { + return $this->body instanceof Swift_OutputByteStream ? $this->readStream($this->body) : $this->body; + } + + /** + * Set the body of this entity, either as a string, or as an instance of + * {@link Swift_OutputByteStream}. + * + * @param mixed $body + * @param string $contentType optional + * + * @return $this + */ + public function setBody($body, $contentType = null) + { + if ($body !== $this->body) { + $this->clearCache(); + } + + $this->body = $body; + if (null !== $contentType) { + $this->setContentType($contentType); + } + + return $this; + } + + /** + * Get the encoder used for the body of this entity. + * + * @return Swift_Mime_ContentEncoder + */ + public function getEncoder() + { + return $this->encoder; + } + + /** + * Set the encoder used for the body of this entity. + * + * @return $this + */ + public function setEncoder(Swift_Mime_ContentEncoder $encoder) + { + if ($encoder !== $this->encoder) { + $this->clearCache(); + } + + $this->encoder = $encoder; + $this->setEncoding($encoder->getName()); + $this->notifyEncoderChanged($encoder); + + return $this; + } + + /** + * Get the boundary used to separate children in this entity. + * + * @return string + */ + public function getBoundary() + { + if (!isset($this->boundary)) { + $this->boundary = '_=_swift_'.time().'_'.bin2hex(random_bytes(16)).'_=_'; + } + + return $this->boundary; + } + + /** + * Set the boundary used to separate children in this entity. + * + * @param string $boundary + * + * @throws Swift_RfcComplianceException + * + * @return $this + */ + public function setBoundary($boundary) + { + $this->assertValidBoundary($boundary); + $this->boundary = $boundary; + + return $this; + } + + /** + * Receive notification that the charset of this entity, or a parent entity + * has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->notifyCharsetChanged($charset); + } + + /** + * Receive notification that the encoder of this entity or a parent entity + * has changed. + */ + public function encoderChanged(Swift_Mime_ContentEncoder $encoder) + { + $this->notifyEncoderChanged($encoder); + } + + /** + * Get this entire entity as a string. + * + * @return string + */ + public function toString() + { + $string = $this->headers->toString(); + $string .= $this->bodyToString(); + + return $string; + } + + /** + * Get this entire entity as a string. + * + * @return string + */ + protected function bodyToString() + { + $string = ''; + + if (isset($this->body) && empty($this->immediateChildren)) { + if ($this->cache->hasKey($this->cacheKey, 'body')) { + $body = $this->cache->getString($this->cacheKey, 'body'); + } else { + $body = "\r\n".$this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()); + $this->cache->setString($this->cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE); + } + $string .= $body; + } + + if (!empty($this->immediateChildren)) { + foreach ($this->immediateChildren as $child) { + $string .= "\r\n\r\n--".$this->getBoundary()."\r\n"; + $string .= $child->toString(); + } + $string .= "\r\n\r\n--".$this->getBoundary()."--\r\n"; + } + + return $string; + } + + /** + * Returns a string representation of this object. + * + * @see toString() + * + * @return string + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Write this entire entity to a {@see Swift_InputByteStream}. + */ + public function toByteStream(Swift_InputByteStream $is) + { + $is->write($this->headers->toString()); + $is->commit(); + + $this->bodyToByteStream($is); + } + + /** + * Write this entire entity to a {@link Swift_InputByteStream}. + */ + protected function bodyToByteStream(Swift_InputByteStream $is) + { + if (empty($this->immediateChildren)) { + if (isset($this->body)) { + if ($this->cache->hasKey($this->cacheKey, 'body')) { + $this->cache->exportToByteStream($this->cacheKey, 'body', $is); + } else { + $cacheIs = $this->cache->getInputByteStream($this->cacheKey, 'body'); + if ($cacheIs) { + $is->bind($cacheIs); + } + + $is->write("\r\n"); + + if ($this->body instanceof Swift_OutputByteStream) { + $this->body->setReadPointer(0); + + $this->encoder->encodeByteStream($this->body, $is, 0, $this->getMaxLineLength()); + } else { + $is->write($this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); + } + + if ($cacheIs) { + $is->unbind($cacheIs); + } + } + } + } + + if (!empty($this->immediateChildren)) { + foreach ($this->immediateChildren as $child) { + $is->write("\r\n\r\n--".$this->getBoundary()."\r\n"); + $child->toByteStream($is); + } + $is->write("\r\n\r\n--".$this->getBoundary()."--\r\n"); + } + } + + /** + * Get the name of the header that provides the ID of this entity. + */ + protected function getIdField() + { + return 'Content-ID'; + } + + /** + * Get the model data (usually an array or a string) for $field. + */ + protected function getHeaderFieldModel($field) + { + if ($this->headers->has($field)) { + return $this->headers->get($field)->getFieldBodyModel(); + } + } + + /** + * Set the model data for $field. + */ + protected function setHeaderFieldModel($field, $model) + { + if ($this->headers->has($field)) { + $this->headers->get($field)->setFieldBodyModel($model); + + return true; + } + + return false; + } + + /** + * Get the parameter value of $parameter on $field header. + */ + protected function getHeaderParameter($field, $parameter) + { + if ($this->headers->has($field)) { + return $this->headers->get($field)->getParameter($parameter); + } + } + + /** + * Set the parameter value of $parameter on $field header. + */ + protected function setHeaderParameter($field, $parameter, $value) + { + if ($this->headers->has($field)) { + $this->headers->get($field)->setParameter($parameter, $value); + + return true; + } + + return false; + } + + /** + * Re-evaluate what content type and encoding should be used on this entity. + */ + protected function fixHeaders() + { + if (\count($this->immediateChildren)) { + $this->setHeaderParameter('Content-Type', 'boundary', + $this->getBoundary() + ); + $this->headers->remove('Content-Transfer-Encoding'); + } else { + $this->setHeaderParameter('Content-Type', 'boundary', null); + $this->setEncoding($this->encoder->getName()); + } + } + + /** + * Get the KeyCache used in this entity. + * + * @return Swift_KeyCache + */ + protected function getCache() + { + return $this->cache; + } + + /** + * Get the ID generator. + * + * @return Swift_IdGenerator + */ + protected function getIdGenerator() + { + return $this->idGenerator; + } + + /** + * Empty the KeyCache for this entity. + */ + protected function clearCache() + { + $this->cache->clearKey($this->cacheKey, 'body'); + } + + private function readStream(Swift_OutputByteStream $os) + { + $string = ''; + while (false !== $bytes = $os->read(8192)) { + $string .= $bytes; + } + + $os->setReadPointer(0); + + return $string; + } + + private function setEncoding($encoding) + { + if (!$this->setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { + $this->headers->addTextHeader('Content-Transfer-Encoding', $encoding); + } + } + + private function assertValidBoundary($boundary) + { + if (!preg_match('/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', $boundary)) { + throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.'); + } + } + + private function setContentTypeInHeaders($type) + { + if (!$this->setHeaderFieldModel('Content-Type', $type)) { + $this->headers->addParameterizedHeader('Content-Type', $type); + } + } + + private function setNestingLevel($level) + { + $this->nestingLevel = $level; + } + + private function getCompoundLevel($children) + { + $level = 0; + foreach ($children as $child) { + $level |= $child->getNestingLevel(); + } + + return $level; + } + + private function getNeededChildLevel($child, $compoundLevel) + { + $filter = []; + foreach ($this->compoundLevelFilters as $bitmask => $rules) { + if (($compoundLevel & $bitmask) === $bitmask) { + $filter = $rules + $filter; + } + } + + $realLevel = $child->getNestingLevel(); + $lowercaseType = strtolower($child->getContentType() ?? ''); + + if (isset($filter[$realLevel]) && isset($filter[$realLevel][$lowercaseType])) { + return $filter[$realLevel][$lowercaseType]; + } + + return $realLevel; + } + + private function createChild() + { + return new self($this->headers->newInstance(), $this->encoder, $this->cache, $this->idGenerator); + } + + private function notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) + { + foreach ($this->immediateChildren as $child) { + $child->encoderChanged($encoder); + } + } + + private function notifyCharsetChanged($charset) + { + $this->encoder->charsetChanged($charset); + $this->headers->charsetChanged($charset); + foreach ($this->immediateChildren as $child) { + $child->charsetChanged($charset); + } + } + + private function sortChildren() + { + $shouldSort = false; + foreach ($this->immediateChildren as $child) { + // NOTE: This include alternative parts moved into a related part + if (self::LEVEL_ALTERNATIVE == $child->getNestingLevel()) { + $shouldSort = true; + break; + } + } + + // Sort in order of preference, if there is one + if ($shouldSort) { + // Group the messages by order of preference + $sorted = []; + foreach ($this->immediateChildren as $child) { + $type = $child->getContentType(); + $level = \array_key_exists($type, $this->alternativePartOrder) ? $this->alternativePartOrder[$type] : max($this->alternativePartOrder) + 1; + + if (empty($sorted[$level])) { + $sorted[$level] = []; + } + + $sorted[$level][] = $child; + } + + ksort($sorted); + + $this->immediateChildren = array_reduce($sorted, 'array_merge', []); + } + } + + /** + * Empties it's own contents from the cache. + */ + public function __destruct() + { + if ($this->cache instanceof Swift_KeyCache) { + $this->cache->clearAll($this->cacheKey); + } + } + + /** + * Make a deep copy of object. + */ + public function __clone() + { + $this->headers = clone $this->headers; + $this->encoder = clone $this->encoder; + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values + $children = []; + foreach ($this->children as $pos => $child) { + $children[$pos] = clone $child; + } + $this->setChildren($children); + } + + public function __wakeup() + { + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values + $this->cache = new Swift_KeyCache_ArrayKeyCache(new Swift_KeyCache_SimpleKeyCacheInputStream()); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php new file mode 100644 index 0000000..ea97619 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php @@ -0,0 +1,45 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A MIME part, in a multipart message. + * + * @author Chris Corbyn + */ +class Swift_MimePart extends Swift_Mime_MimePart +{ + /** + * Create a new MimePart. + * + * Details may be optionally passed into the constructor. + * + * @param string $body + * @param string $contentType + * @param string $charset + */ + public function __construct($body = null, $contentType = null, $charset = null) + { + \call_user_func_array( + [$this, 'Swift_Mime_MimePart::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('mime.part') + ); + + if (!isset($charset)) { + $charset = Swift_DependencyContainer::getInstance() + ->lookup('properties.charset'); + } + $this->setBody($body); + $this->setCharset($charset); + if ($contentType) { + $this->setContentType($contentType); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php new file mode 100644 index 0000000..e44b7af --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php @@ -0,0 +1,26 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Pretends messages have been sent, but just ignores them. + * + * @author Fabien Potencier + */ +class Swift_NullTransport extends Swift_Transport_NullTransport +{ + public function __construct() + { + \call_user_func_array( + [$this, 'Swift_Transport_NullTransport::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.null') + ); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php new file mode 100644 index 0000000..1f26f9b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php @@ -0,0 +1,46 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An abstract means of reading data. + * + * Classes implementing this interface may use a subsystem which requires less + * memory than working with large strings of data. + * + * @author Chris Corbyn + */ +interface Swift_OutputByteStream +{ + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the remaining bytes are given instead. + * If no bytes are remaining at all, boolean false is returned. + * + * @param int $length + * + * @throws Swift_IoException + * + * @return string|bool + */ + public function read($length); + + /** + * Move the internal read pointer to $byteOffset in the stream. + * + * @param int $byteOffset + * + * @throws Swift_IoException + * + * @return bool + */ + public function setReadPointer($byteOffset); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php new file mode 100644 index 0000000..5b1d7de --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php @@ -0,0 +1,137 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Reduces network flooding when sending large amounts of mail. + * + * @author Chris Corbyn + */ +class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_Plugins_Sleeper +{ + /** + * The number of emails to send before restarting Transport. + * + * @var int + */ + private $threshold; + + /** + * The number of seconds to sleep for during a restart. + * + * @var int + */ + private $sleep; + + /** + * The internal counter. + * + * @var int + */ + private $counter = 0; + + /** + * The Sleeper instance for sleeping. + * + * @var Swift_Plugins_Sleeper + */ + private $sleeper; + + /** + * Create a new AntiFloodPlugin with $threshold and $sleep time. + * + * @param int $threshold + * @param int $sleep time + * @param Swift_Plugins_Sleeper $sleeper (not needed really) + */ + public function __construct($threshold = 99, $sleep = 0, Swift_Plugins_Sleeper $sleeper = null) + { + $this->setThreshold($threshold); + $this->setSleepTime($sleep); + $this->sleeper = $sleeper; + } + + /** + * Set the number of emails to send before restarting. + * + * @param int $threshold + */ + public function setThreshold($threshold) + { + $this->threshold = $threshold; + } + + /** + * Get the number of emails to send before restarting. + * + * @return int + */ + public function getThreshold() + { + return $this->threshold; + } + + /** + * Set the number of seconds to sleep for during a restart. + * + * @param int $sleep time + */ + public function setSleepTime($sleep) + { + $this->sleep = $sleep; + } + + /** + * Get the number of seconds to sleep for during a restart. + * + * @return int + */ + public function getSleepTime() + { + return $this->sleep; + } + + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + ++$this->counter; + if ($this->counter >= $this->threshold) { + $transport = $evt->getTransport(); + $transport->stop(); + if ($this->sleep) { + $this->sleep($this->sleep); + } + $transport->start(); + $this->counter = 0; + } + } + + /** + * Sleep for $seconds. + * + * @param int $seconds + */ + public function sleep($seconds) + { + if (isset($this->sleeper)) { + $this->sleeper->sleep($seconds); + } else { + sleep($seconds); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php new file mode 100644 index 0000000..36451f4 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php @@ -0,0 +1,154 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Reduces network flooding when sending large amounts of mail. + * + * @author Chris Corbyn + */ +class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, Swift_Events_CommandListener, Swift_Events_ResponseListener, Swift_InputByteStream +{ + /** + * The outgoing traffic counter. + * + * @var int + */ + private $out = 0; + + /** + * The incoming traffic counter. + * + * @var int + */ + private $in = 0; + + /** Bound byte streams */ + private $mirrors = []; + + /** + * Not used. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $message->toByteStream($this); + } + + /** + * Invoked immediately following a command being sent. + */ + public function commandSent(Swift_Events_CommandEvent $evt) + { + $command = $evt->getCommand(); + $this->out += \strlen($command); + } + + /** + * Invoked immediately following a response coming back. + */ + public function responseReceived(Swift_Events_ResponseEvent $evt) + { + $response = $evt->getResponse(); + $this->in += \strlen($response); + } + + /** + * Called when a message is sent so that the outgoing counter can be increased. + * + * @param string $bytes + */ + public function write($bytes) + { + $this->out += \strlen($bytes); + foreach ($this->mirrors as $stream) { + $stream->write($bytes); + } + } + + /** + * Not used. + */ + public function commit() + { + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + */ + public function bind(Swift_InputByteStream $is) + { + $this->mirrors[] = $is; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + */ + public function unbind(Swift_InputByteStream $is) + { + foreach ($this->mirrors as $k => $stream) { + if ($is === $stream) { + unset($this->mirrors[$k]); + } + } + } + + /** + * Not used. + */ + public function flushBuffers() + { + foreach ($this->mirrors as $stream) { + $stream->flushBuffers(); + } + } + + /** + * Get the total number of bytes sent to the server. + * + * @return int + */ + public function getBytesOut() + { + return $this->out; + } + + /** + * Get the total number of bytes received from the server. + * + * @return int + */ + public function getBytesIn() + { + return $this->in; + } + + /** + * Reset the internal counters to zero. + */ + public function reset() + { + $this->out = 0; + $this->in = 0; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php new file mode 100644 index 0000000..9f9f08b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Allows customization of Messages on-the-fly. + * + * @author Chris Corbyn + */ +interface Swift_Plugins_Decorator_Replacements +{ + /** + * Return the array of replacements for $address. + * + * This method is invoked once for every single recipient of a message. + * + * If no replacements can be found, an empty value (NULL) should be returned + * and no replacements will then be made on the message. + * + * @param string $address + * + * @return array + */ + public function getReplacementsFor($address); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php new file mode 100644 index 0000000..93124c9 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php @@ -0,0 +1,200 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Allows customization of Messages on-the-fly. + * + * @author Chris Corbyn + * @author Fabien Potencier + */ +class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_Plugins_Decorator_Replacements +{ + /** The replacement map */ + private $replacements; + + /** The body as it was before replacements */ + private $originalBody; + + /** The original headers of the message, before replacements */ + private $originalHeaders = []; + + /** Bodies of children before they are replaced */ + private $originalChildBodies = []; + + /** The Message that was last replaced */ + private $lastMessage; + + /** + * Create a new DecoratorPlugin with $replacements. + * + * The $replacements can either be an associative array, or an implementation + * of {@link Swift_Plugins_Decorator_Replacements}. + * + * When using an array, it should be of the form: + * <code> + * $replacements = array( + * "address1@domain.tld" => array("{a}" => "b", "{c}" => "d"), + * "address2@domain.tld" => array("{a}" => "x", "{c}" => "y") + * ) + * </code> + * + * When using an instance of {@link Swift_Plugins_Decorator_Replacements}, + * the object should return just the array of replacements for the address + * given to {@link Swift_Plugins_Decorator_Replacements::getReplacementsFor()}. + * + * @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements + */ + public function __construct($replacements) + { + $this->setReplacements($replacements); + } + + /** + * Sets replacements. + * + * @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements + * + * @see __construct() + */ + public function setReplacements($replacements) + { + if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) { + $this->replacements = (array) $replacements; + } else { + $this->replacements = $replacements; + } + } + + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $this->restoreMessage($message); + $to = array_keys($message->getTo()); + $address = array_shift($to); + if ($replacements = $this->getReplacementsFor($address)) { + $body = $message->getBody(); + $search = array_keys($replacements); + $replace = array_values($replacements); + $bodyReplaced = str_replace( + $search, $replace, $body + ); + if ($body != $bodyReplaced) { + $this->originalBody = $body; + $message->setBody($bodyReplaced); + } + + foreach ($message->getHeaders()->getAll() as $header) { + $body = $header->getFieldBodyModel(); + $count = 0; + if (\is_array($body)) { + $bodyReplaced = []; + foreach ($body as $key => $value) { + $count1 = 0; + $count2 = 0; + $key = \is_string($key) ? str_replace($search, $replace, $key, $count1) : $key; + $value = \is_string($value) ? str_replace($search, $replace, $value, $count2) : $value; + $bodyReplaced[$key] = $value; + + if (!$count && ($count1 || $count2)) { + $count = 1; + } + } + } elseif (\is_string($body)) { + $bodyReplaced = str_replace($search, $replace, $body, $count); + } + + if ($count) { + $this->originalHeaders[$header->getFieldName()] = $body; + $header->setFieldBodyModel($bodyReplaced); + } + } + + $children = (array) $message->getChildren(); + foreach ($children as $child) { + list($type) = sscanf($child->getContentType(), '%[^/]/%s'); + if ('text' == $type) { + $body = $child->getBody(); + $bodyReplaced = str_replace( + $search, $replace, $body + ); + if ($body != $bodyReplaced) { + $child->setBody($bodyReplaced); + $this->originalChildBodies[$child->getId()] = $body; + } + } + } + $this->lastMessage = $message; + } + } + + /** + * Find a map of replacements for the address. + * + * If this plugin was provided with a delegate instance of + * {@link Swift_Plugins_Decorator_Replacements} then the call will be + * delegated to it. Otherwise, it will attempt to find the replacements + * from the array provided in the constructor. + * + * If no replacements can be found, an empty value (NULL) is returned. + * + * @param string $address + * + * @return array + */ + public function getReplacementsFor($address) + { + if ($this->replacements instanceof Swift_Plugins_Decorator_Replacements) { + return $this->replacements->getReplacementsFor($address); + } + + return $this->replacements[$address] ?? null; + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $this->restoreMessage($evt->getMessage()); + } + + /** Restore a changed message back to its original state */ + private function restoreMessage(Swift_Mime_SimpleMessage $message) + { + if ($this->lastMessage === $message) { + if (isset($this->originalBody)) { + $message->setBody($this->originalBody); + $this->originalBody = null; + } + if (!empty($this->originalHeaders)) { + foreach ($message->getHeaders()->getAll() as $header) { + if (\array_key_exists($header->getFieldName(), $this->originalHeaders)) { + $header->setFieldBodyModel($this->originalHeaders[$header->getFieldName()]); + } + } + $this->originalHeaders = []; + } + if (!empty($this->originalChildBodies)) { + $children = (array) $message->getChildren(); + foreach ($children as $child) { + $id = $child->getId(); + if (\array_key_exists($id, $this->originalChildBodies)) { + $child->setBody($this->originalChildBodies[$id]); + } + } + $this->originalChildBodies = []; + } + $this->lastMessage = null; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php new file mode 100644 index 0000000..3f4dbbf --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Replaces the sender of a message. + * + * @author Arjen Brouwer + */ +class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener +{ + /** + * The sender to impersonate. + * + * @var string + */ + private $sender; + + /** + * Create a new ImpersonatePlugin to impersonate $sender. + * + * @param string $sender address + */ + public function __construct($sender) + { + $this->sender = $sender; + } + + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $headers = $message->getHeaders(); + + // save current recipients + $headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath()); + + // replace them with the one to send to + $message->setReturnPath($this->sender); + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + + // restore original headers + $headers = $message->getHeaders(); + + if ($headers->has('X-Swift-Return-Path')) { + $message->setReturnPath($headers->get('X-Swift-Return-Path')->getAddress()); + $headers->removeAll('X-Swift-Return-Path'); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php new file mode 100644 index 0000000..d9bce89 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php @@ -0,0 +1,36 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Logs events in the Transport system. + * + * @author Chris Corbyn + */ +interface Swift_Plugins_Logger +{ + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry); + + /** + * Clear the log contents. + */ + public function clear(); + + /** + * Get this log as a string. + * + * @return string + */ + public function dump(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php new file mode 100644 index 0000000..e183749 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php @@ -0,0 +1,126 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Does real time logging of Transport level information. + * + * @author Chris Corbyn + */ +class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_Events_ResponseListener, Swift_Events_TransportChangeListener, Swift_Events_TransportExceptionListener, Swift_Plugins_Logger +{ + /** The logger which is delegated to */ + private $logger; + + /** + * Create a new LoggerPlugin using $logger. + */ + public function __construct(Swift_Plugins_Logger $logger) + { + $this->logger = $logger; + } + + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry) + { + $this->logger->add($entry); + } + + /** + * Clear the log contents. + */ + public function clear() + { + $this->logger->clear(); + } + + /** + * Get this log as a string. + * + * @return string + */ + public function dump() + { + return $this->logger->dump(); + } + + /** + * Invoked immediately following a command being sent. + */ + public function commandSent(Swift_Events_CommandEvent $evt) + { + $command = $evt->getCommand(); + $this->logger->add(sprintf('>> %s', $command)); + } + + /** + * Invoked immediately following a response coming back. + */ + public function responseReceived(Swift_Events_ResponseEvent $evt) + { + $response = $evt->getResponse(); + $this->logger->add(sprintf('<< %s', $response)); + } + + /** + * Invoked just before a Transport is started. + */ + public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) + { + $transportName = \get_class($evt->getSource()); + $this->logger->add(sprintf('++ Starting %s', $transportName)); + } + + /** + * Invoked immediately after the Transport is started. + */ + public function transportStarted(Swift_Events_TransportChangeEvent $evt) + { + $transportName = \get_class($evt->getSource()); + $this->logger->add(sprintf('++ %s started', $transportName)); + } + + /** + * Invoked just before a Transport is stopped. + */ + public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) + { + $transportName = \get_class($evt->getSource()); + $this->logger->add(sprintf('++ Stopping %s', $transportName)); + } + + /** + * Invoked immediately after the Transport is stopped. + */ + public function transportStopped(Swift_Events_TransportChangeEvent $evt) + { + $transportName = \get_class($evt->getSource()); + $this->logger->add(sprintf('++ %s stopped', $transportName)); + } + + /** + * Invoked as a TransportException is thrown in the Transport system. + */ + public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt) + { + $e = $evt->getException(); + $message = $e->getMessage(); + $code = $e->getCode(); + $this->logger->add(sprintf('!! %s (code: %s)', $message, $code)); + $message .= PHP_EOL; + $message .= 'Log data:'.PHP_EOL; + $message .= $this->logger->dump(); + $evt->cancelBubble(); + throw new Swift_TransportException($message, $code, $e->getPrevious()); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php new file mode 100644 index 0000000..6f595ad --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php @@ -0,0 +1,72 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Logs to an Array backend. + * + * @author Chris Corbyn + */ +class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger +{ + /** + * The log contents. + * + * @var array + */ + private $log = []; + + /** + * Max size of the log. + * + * @var int + */ + private $size = 0; + + /** + * Create a new ArrayLogger with a maximum of $size entries. + * + * @var int + */ + public function __construct($size = 50) + { + $this->size = $size; + } + + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry) + { + $this->log[] = $entry; + while (\count($this->log) > $this->size) { + array_shift($this->log); + } + } + + /** + * Clear the log contents. + */ + public function clear() + { + $this->log = []; + } + + /** + * Get this log as a string. + * + * @return string + */ + public function dump() + { + return implode(PHP_EOL, $this->log); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php new file mode 100644 index 0000000..40a53d2 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php @@ -0,0 +1,58 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Prints all log messages in real time. + * + * @author Chris Corbyn + */ +class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger +{ + /** Whether or not HTML should be output */ + private $isHtml; + + /** + * Create a new EchoLogger. + * + * @param bool $isHtml + */ + public function __construct($isHtml = true) + { + $this->isHtml = $isHtml; + } + + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry) + { + if ($this->isHtml) { + printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), '<br />', PHP_EOL); + } else { + printf('%s%s', $entry, PHP_EOL); + } + } + + /** + * Not implemented. + */ + public function clear() + { + } + + /** + * Not implemented. + */ + public function dump() + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php new file mode 100644 index 0000000..39c48ed --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php @@ -0,0 +1,70 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2011 Fabien Potencier + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores all sent emails for further usage. + * + * @author Fabien Potencier + */ +class Swift_Plugins_MessageLogger implements Swift_Events_SendListener +{ + /** + * @var Swift_Mime_SimpleMessage[] + */ + private $messages; + + public function __construct() + { + $this->messages = []; + } + + /** + * Get the message list. + * + * @return Swift_Mime_SimpleMessage[] + */ + public function getMessages() + { + return $this->messages; + } + + /** + * Get the message count. + * + * @return int count + */ + public function countMessages() + { + return \count($this->messages); + } + + /** + * Empty the message list. + */ + public function clear() + { + $this->messages = []; + } + + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $this->messages[] = clone $evt->getMessage(); + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php new file mode 100644 index 0000000..fb99e4c --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Pop3Connection interface for connecting and disconnecting to a POP3 host. + * + * @author Chris Corbyn + */ +interface Swift_Plugins_Pop_Pop3Connection +{ + /** + * Connect to the POP3 host and throw an Exception if it fails. + * + * @throws Swift_Plugins_Pop_Pop3Exception + */ + public function connect(); + + /** + * Disconnect from the POP3 host and throw an Exception if it fails. + * + * @throws Swift_Plugins_Pop_Pop3Exception + */ + public function disconnect(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Exception.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Exception.php new file mode 100644 index 0000000..dc7be0c --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Exception.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Pop3Exception thrown when an error occurs connecting to a POP3 host. + * + * @author Chris Corbyn + */ +class Swift_Plugins_Pop_Pop3Exception extends Swift_IoException +{ + /** + * Create a new Pop3Exception with $message. + * + * @param string $message + */ + public function __construct($message) + { + parent::__construct($message); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php new file mode 100644 index 0000000..9448594 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php @@ -0,0 +1,242 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Makes sure a connection to a POP3 host has been established prior to connecting to SMTP. + * + * @author Chris Corbyn + */ +class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeListener, Swift_Plugins_Pop_Pop3Connection +{ + /** A delegate connection to use (mostly a test hook) */ + private $connection; + + /** Hostname of the POP3 server */ + private $host; + + /** Port number to connect on */ + private $port; + + /** Encryption type to use (if any) */ + private $crypto; + + /** Username to use (if any) */ + private $username; + + /** Password to use (if any) */ + private $password; + + /** Established connection via TCP socket */ + private $socket; + + /** Connect timeout in seconds */ + private $timeout = 10; + + /** SMTP Transport to bind to */ + private $transport; + + /** + * Create a new PopBeforeSmtpPlugin for $host and $port. + * + * @param string $host Hostname or IP. Literal IPv6 addresses should be + * wrapped in square brackets. + * @param int $port + * @param string $crypto as "tls" or "ssl" + */ + public function __construct($host, $port = 110, $crypto = null) + { + $this->host = $host; + $this->port = $port; + $this->crypto = $crypto; + } + + /** + * Set a Pop3Connection to delegate to instead of connecting directly. + * + * @return $this + */ + public function setConnection(Swift_Plugins_Pop_Pop3Connection $connection) + { + $this->connection = $connection; + + return $this; + } + + /** + * Bind this plugin to a specific SMTP transport instance. + */ + public function bindSmtp(Swift_Transport $smtp) + { + $this->transport = $smtp; + } + + /** + * Set the connection timeout in seconds (default 10). + * + * @param int $timeout + * + * @return $this + */ + public function setTimeout($timeout) + { + $this->timeout = (int) $timeout; + + return $this; + } + + /** + * Set the username to use when connecting (if needed). + * + * @param string $username + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + + return $this; + } + + /** + * Set the password to use when connecting (if needed). + * + * @param string $password + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + + return $this; + } + + /** + * Connect to the POP3 host and authenticate. + * + * @throws Swift_Plugins_Pop_Pop3Exception if connection fails + */ + public function connect() + { + if (isset($this->connection)) { + $this->connection->connect(); + } else { + if (!isset($this->socket)) { + if (!$socket = fsockopen( + $this->getHostString(), $this->port, $errno, $errstr, $this->timeout)) { + throw new Swift_Plugins_Pop_Pop3Exception(sprintf('Failed to connect to POP3 host [%s]: %s', $this->host, $errstr)); + } + $this->socket = $socket; + + if (false === $greeting = fgets($this->socket)) { + throw new Swift_Plugins_Pop_Pop3Exception(sprintf('Failed to connect to POP3 host [%s]', trim($greeting ?? ''))); + } + + $this->assertOk($greeting); + + if ($this->username) { + $this->command(sprintf("USER %s\r\n", $this->username)); + $this->command(sprintf("PASS %s\r\n", $this->password)); + } + } + } + } + + /** + * Disconnect from the POP3 host. + */ + public function disconnect() + { + if (isset($this->connection)) { + $this->connection->disconnect(); + } else { + $this->command("QUIT\r\n"); + if (!fclose($this->socket)) { + throw new Swift_Plugins_Pop_Pop3Exception(sprintf('POP3 host [%s] connection could not be stopped', $this->host)); + } + $this->socket = null; + } + } + + /** + * Invoked just before a Transport is started. + */ + public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) + { + if (isset($this->transport)) { + if ($this->transport !== $evt->getTransport()) { + return; + } + } + + $this->connect(); + $this->disconnect(); + } + + /** + * Not used. + */ + public function transportStarted(Swift_Events_TransportChangeEvent $evt) + { + } + + /** + * Not used. + */ + public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) + { + } + + /** + * Not used. + */ + public function transportStopped(Swift_Events_TransportChangeEvent $evt) + { + } + + private function command($command) + { + if (!fwrite($this->socket, $command)) { + throw new Swift_Plugins_Pop_Pop3Exception(sprintf('Failed to write command [%s] to POP3 host', trim($command ?? ''))); + } + + if (false === $response = fgets($this->socket)) { + throw new Swift_Plugins_Pop_Pop3Exception(sprintf('Failed to read from POP3 host after command [%s]', trim($command ?? ''))); + } + + $this->assertOk($response); + + return $response; + } + + private function assertOk($response) + { + if ('+OK' != substr($response, 0, 3)) { + throw new Swift_Plugins_Pop_Pop3Exception(sprintf('POP3 command failed [%s]', trim($response ?? ''))); + } + } + + private function getHostString() + { + $host = $this->host; + switch (strtolower($this->crypto ?? '')) { + case 'ssl': + $host = 'ssl://'.$host; + break; + + case 'tls': + $host = 'tls://'.$host; + break; + } + + return $host; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php new file mode 100644 index 0000000..f7373b2 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php @@ -0,0 +1,201 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Redirects all email to a single recipient. + * + * @author Fabien Potencier + */ +class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener +{ + /** + * The recipient who will receive all messages. + * + * @var mixed + */ + private $recipient; + + /** + * List of regular expression for recipient whitelisting. + * + * @var array + */ + private $whitelist = []; + + /** + * Create a new RedirectingPlugin. + * + * @param mixed $recipient + */ + public function __construct($recipient, array $whitelist = []) + { + $this->recipient = $recipient; + $this->whitelist = $whitelist; + } + + /** + * Set the recipient of all messages. + * + * @param mixed $recipient + */ + public function setRecipient($recipient) + { + $this->recipient = $recipient; + } + + /** + * Get the recipient of all messages. + * + * @return mixed + */ + public function getRecipient() + { + return $this->recipient; + } + + /** + * Set a list of regular expressions to whitelist certain recipients. + */ + public function setWhitelist(array $whitelist) + { + $this->whitelist = $whitelist; + } + + /** + * Get the whitelist. + * + * @return array + */ + public function getWhitelist() + { + return $this->whitelist; + } + + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $headers = $message->getHeaders(); + + // conditionally save current recipients + + if ($headers->has('to')) { + $headers->addMailboxHeader('X-Swift-To', $message->getTo()); + } + + if ($headers->has('cc')) { + $headers->addMailboxHeader('X-Swift-Cc', $message->getCc()); + } + + if ($headers->has('bcc')) { + $headers->addMailboxHeader('X-Swift-Bcc', $message->getBcc()); + } + + // Filter remaining headers against whitelist + $this->filterHeaderSet($headers, 'To'); + $this->filterHeaderSet($headers, 'Cc'); + $this->filterHeaderSet($headers, 'Bcc'); + + // Add each hard coded recipient + $to = $message->getTo(); + if (null === $to) { + $to = []; + } + + foreach ((array) $this->recipient as $recipient) { + if (!\array_key_exists($recipient, $to)) { + $message->addTo($recipient); + } + } + } + + /** + * Filter header set against a whitelist of regular expressions. + * + * @param string $type + */ + private function filterHeaderSet(Swift_Mime_SimpleHeaderSet $headerSet, $type) + { + foreach ($headerSet->getAll($type) as $headers) { + $headers->setNameAddresses($this->filterNameAddresses($headers->getNameAddresses())); + } + } + + /** + * Filtered list of addresses => name pairs. + * + * @return array + */ + private function filterNameAddresses(array $recipients) + { + $filtered = []; + + foreach ($recipients as $address => $name) { + if ($this->isWhitelisted($address)) { + $filtered[$address] = $name; + } + } + + return $filtered; + } + + /** + * Matches address against whitelist of regular expressions. + * + * @return bool + */ + protected function isWhitelisted($recipient) + { + if (\in_array($recipient, (array) $this->recipient)) { + return true; + } + + foreach ($this->whitelist as $pattern) { + if (preg_match($pattern, $recipient)) { + return true; + } + } + + return false; + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $this->restoreMessage($evt->getMessage()); + } + + private function restoreMessage(Swift_Mime_SimpleMessage $message) + { + // restore original headers + $headers = $message->getHeaders(); + + if ($headers->has('X-Swift-To')) { + $message->setTo($headers->get('X-Swift-To')->getNameAddresses()); + $headers->removeAll('X-Swift-To'); + } else { + $message->setTo(null); + } + + if ($headers->has('X-Swift-Cc')) { + $message->setCc($headers->get('X-Swift-Cc')->getNameAddresses()); + $headers->removeAll('X-Swift-Cc'); + } + + if ($headers->has('X-Swift-Bcc')) { + $message->setBcc($headers->get('X-Swift-Bcc')->getNameAddresses()); + $headers->removeAll('X-Swift-Bcc'); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php new file mode 100644 index 0000000..b881833 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * The Reporter plugin sends pass/fail notification to a Reporter. + * + * @author Chris Corbyn + */ +interface Swift_Plugins_Reporter +{ + /** The recipient was accepted for delivery */ + const RESULT_PASS = 0x01; + + /** The recipient could not be accepted */ + const RESULT_FAIL = 0x10; + + /** + * Notifies this ReportNotifier that $address failed or succeeded. + * + * @param string $address + * @param int $result from {@link RESULT_PASS, RESULT_FAIL} + */ + public function notify(Swift_Mime_SimpleMessage $message, $address, $result); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php new file mode 100644 index 0000000..c4a0165 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Does real time reporting of pass/fail for each recipient. + * + * @author Chris Corbyn + */ +class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener +{ + /** + * The reporter backend which takes notifications. + * + * @var Swift_Plugins_Reporter + */ + private $reporter; + + /** + * Create a new ReporterPlugin using $reporter. + */ + public function __construct(Swift_Plugins_Reporter $reporter) + { + $this->reporter = $reporter; + } + + /** + * Not used. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + } + + /** + * Invoked immediately after the Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $failures = array_flip($evt->getFailedRecipients()); + foreach ((array) $message->getTo() as $address => $null) { + $this->reporter->notify($message, $address, (\array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); + } + foreach ((array) $message->getCc() as $address => $null) { + $this->reporter->notify($message, $address, (\array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); + } + foreach ((array) $message->getBcc() as $address => $null) { + $this->reporter->notify($message, $address, (\array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php new file mode 100644 index 0000000..249cffb --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php @@ -0,0 +1,58 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A reporter which "collects" failures for the Reporter plugin. + * + * @author Chris Corbyn + */ +class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter +{ + /** + * The list of failures. + * + * @var array + */ + private $failures = []; + + private $failures_cache = []; + + /** + * Notifies this ReportNotifier that $address failed or succeeded. + * + * @param string $address + * @param int $result from {@link RESULT_PASS, RESULT_FAIL} + */ + public function notify(Swift_Mime_SimpleMessage $message, $address, $result) + { + if (self::RESULT_FAIL == $result && !isset($this->failures_cache[$address])) { + $this->failures[] = $address; + $this->failures_cache[$address] = true; + } + } + + /** + * Get an array of addresses for which delivery failed. + * + * @return array + */ + public function getFailedRecipients() + { + return $this->failures; + } + + /** + * Clear the buffer (empty the list). + */ + public function clear() + { + $this->failures = $this->failures_cache = []; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php new file mode 100644 index 0000000..1cfc3f9 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php @@ -0,0 +1,38 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A HTML output reporter for the Reporter plugin. + * + * @author Chris Corbyn + */ +class Swift_Plugins_Reporters_HtmlReporter implements Swift_Plugins_Reporter +{ + /** + * Notifies this ReportNotifier that $address failed or succeeded. + * + * @param string $address + * @param int $result from {@see RESULT_PASS, RESULT_FAIL} + */ + public function notify(Swift_Mime_SimpleMessage $message, $address, $result) + { + if (self::RESULT_PASS == $result) { + echo '<div style="color: #fff; background: #006600; padding: 2px; margin: 2px;">'.PHP_EOL; + echo 'PASS '.$address.PHP_EOL; + echo '</div>'.PHP_EOL; + flush(); + } else { + echo '<div style="color: #fff; background: #880000; padding: 2px; margin: 2px;">'.PHP_EOL; + echo 'FAIL '.$address.PHP_EOL; + echo '</div>'.PHP_EOL; + flush(); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php new file mode 100644 index 0000000..595c0f6 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Sleeps for a duration of time. + * + * @author Chris Corbyn + */ +interface Swift_Plugins_Sleeper +{ + /** + * Sleep for $seconds. + * + * @param int $seconds + */ + public function sleep($seconds); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php new file mode 100644 index 0000000..83d3044 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php @@ -0,0 +1,196 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Throttles the rate at which emails are sent. + * + * @author Chris Corbyn + */ +class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin implements Swift_Plugins_Sleeper, Swift_Plugins_Timer +{ + /** Flag for throttling in bytes per minute */ + const BYTES_PER_MINUTE = 0x01; + + /** Flag for throttling in emails per second (Amazon SES) */ + const MESSAGES_PER_SECOND = 0x11; + + /** Flag for throttling in emails per minute */ + const MESSAGES_PER_MINUTE = 0x10; + + /** + * The Sleeper instance for sleeping. + * + * @var Swift_Plugins_Sleeper + */ + private $sleeper; + + /** + * The Timer instance which provides the timestamp. + * + * @var Swift_Plugins_Timer + */ + private $timer; + + /** + * The time at which the first email was sent. + * + * @var int + */ + private $start; + + /** + * The rate at which messages should be sent. + * + * @var int + */ + private $rate; + + /** + * The mode for throttling. + * + * This is {@link BYTES_PER_MINUTE} or {@link MESSAGES_PER_MINUTE} + * + * @var int + */ + private $mode; + + /** + * An internal counter of the number of messages sent. + * + * @var int + */ + private $messages = 0; + + /** + * Create a new ThrottlerPlugin. + * + * @param int $rate + * @param int $mode defaults to {@link BYTES_PER_MINUTE} + * @param Swift_Plugins_Sleeper $sleeper (only needed in testing) + * @param Swift_Plugins_Timer $timer (only needed in testing) + */ + public function __construct($rate, $mode = self::BYTES_PER_MINUTE, Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null) + { + $this->rate = $rate; + $this->mode = $mode; + $this->sleeper = $sleeper; + $this->timer = $timer; + } + + /** + * Invoked immediately before the Message is sent. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $time = $this->getTimestamp(); + if (!isset($this->start)) { + $this->start = $time; + } + $duration = $time - $this->start; + + switch ($this->mode) { + case self::BYTES_PER_MINUTE: + $sleep = $this->throttleBytesPerMinute($duration); + break; + case self::MESSAGES_PER_SECOND: + $sleep = $this->throttleMessagesPerSecond($duration); + break; + case self::MESSAGES_PER_MINUTE: + $sleep = $this->throttleMessagesPerMinute($duration); + break; + default: + $sleep = 0; + break; + } + + if ($sleep > 0) { + $this->sleep($sleep); + } + } + + /** + * Invoked when a Message is sent. + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + parent::sendPerformed($evt); + ++$this->messages; + } + + /** + * Sleep for $seconds. + * + * @param int $seconds + */ + public function sleep($seconds) + { + if (isset($this->sleeper)) { + $this->sleeper->sleep($seconds); + } else { + sleep($seconds); + } + } + + /** + * Get the current UNIX timestamp. + * + * @return int + */ + public function getTimestamp() + { + if (isset($this->timer)) { + return $this->timer->getTimestamp(); + } + + return time(); + } + + /** + * Get a number of seconds to sleep for. + * + * @param int $timePassed + * + * @return int + */ + private function throttleBytesPerMinute($timePassed) + { + $expectedDuration = $this->getBytesOut() / ($this->rate / 60); + + return (int) ceil($expectedDuration - $timePassed); + } + + /** + * Get a number of seconds to sleep for. + * + * @param int $timePassed + * + * @return int + */ + private function throttleMessagesPerSecond($timePassed) + { + $expectedDuration = $this->messages / $this->rate; + + return (int) ceil($expectedDuration - $timePassed); + } + + /** + * Get a number of seconds to sleep for. + * + * @param int $timePassed + * + * @return int + */ + private function throttleMessagesPerMinute($timePassed) + { + $expectedDuration = $this->messages / ($this->rate / 60); + + return (int) ceil($expectedDuration - $timePassed); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php new file mode 100644 index 0000000..9c8deb3 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Provides timestamp data. + * + * @author Chris Corbyn + */ +interface Swift_Plugins_Timer +{ + /** + * Get the current UNIX timestamp. + * + * @return int + */ + public function getTimestamp(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Preferences.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Preferences.php new file mode 100644 index 0000000..16103e1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Preferences.php @@ -0,0 +1,100 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Changes some global preference settings in Swift Mailer. + * + * @author Chris Corbyn + */ +class Swift_Preferences +{ + /** Singleton instance */ + private static $instance = null; + + /** Constructor not to be used */ + private function __construct() + { + } + + /** + * Gets the instance of Preferences. + * + * @return self + */ + public static function getInstance() + { + if (!isset(self::$instance)) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Set the default charset used. + * + * @param string $charset + * + * @return $this + */ + public function setCharset($charset) + { + Swift_DependencyContainer::getInstance()->register('properties.charset')->asValue($charset); + + return $this; + } + + /** + * Set the directory where temporary files can be saved. + * + * @param string $dir + * + * @return $this + */ + public function setTempDir($dir) + { + Swift_DependencyContainer::getInstance()->register('tempdir')->asValue($dir); + + return $this; + } + + /** + * Set the type of cache to use (i.e. "disk" or "array"). + * + * @param string $type + * + * @return $this + */ + public function setCacheType($type) + { + Swift_DependencyContainer::getInstance()->register('cache')->asAliasOf(sprintf('cache.%s', $type)); + + return $this; + } + + /** + * Set the QuotedPrintable dot escaper preference. + * + * @param bool $dotEscape + * + * @return $this + */ + public function setQPDotEscape($dotEscape) + { + $dotEscape = !empty($dotEscape); + Swift_DependencyContainer::getInstance() + ->register('mime.qpcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder') + ->withDependencies(['mime.charstream', 'mime.bytecanonicalizer']) + ->addConstructorValue($dotEscape); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php new file mode 100644 index 0000000..2897474 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Creates StreamFilters. + * + * @author Chris Corbyn + */ +interface Swift_ReplacementFilterFactory +{ + /** + * Create a filter to replace $search with $replace. + * + * @param mixed $search + * @param mixed $replace + * + * @return Swift_StreamFilter + */ + public function createFilter($search, $replace); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/RfcComplianceException.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/RfcComplianceException.php new file mode 100644 index 0000000..81bc403 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/RfcComplianceException.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * RFC Compliance Exception class. + * + * @author Chris Corbyn + */ +class Swift_RfcComplianceException extends Swift_SwiftException +{ + /** + * Create a new RfcComplianceException with $message. + * + * @param string $message + */ + public function __construct($message) + { + parent::__construct($message); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SendmailTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SendmailTransport.php new file mode 100644 index 0000000..3c75643 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SendmailTransport.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * SendmailTransport for sending mail through a Sendmail/Postfix (etc..) binary. + * + * @author Chris Corbyn + */ +class Swift_SendmailTransport extends Swift_Transport_SendmailTransport +{ + /** + * Create a new SendmailTransport, optionally using $command for sending. + * + * @param string $command + */ + public function __construct($command = '/usr/sbin/sendmail -bs') + { + \call_user_func_array( + [$this, 'Swift_Transport_SendmailTransport::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.sendmail') + ); + + $this->setCommand($command); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php new file mode 100644 index 0000000..26c5e28 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Base Class of Signer Infrastructure. + * + * @author Xavier De Cock <xdecock@gmail.com> + */ +interface Swift_Signer +{ + public function reset(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php new file mode 100644 index 0000000..b25c427 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Body Signer Interface used to apply Body-Based Signature to a message. + * + * @author Xavier De Cock <xdecock@gmail.com> + */ +interface Swift_Signers_BodySigner extends Swift_Signer +{ + /** + * Change the Swift_Signed_Message to apply the singing. + * + * @return self + */ + public function signMessage(Swift_Message $message); + + /** + * Return the list of header a signer might tamper. + * + * @return array + */ + public function getAlteredHeaders(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php new file mode 100644 index 0000000..ec82dc0 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php @@ -0,0 +1,682 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * DKIM Signer used to apply DKIM Signature to a message. + * + * @author Xavier De Cock <xdecock@gmail.com> + */ +class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner +{ + /** + * PrivateKey. + * + * @var string + */ + protected $privateKey; + + /** + * DomainName. + * + * @var string + */ + protected $domainName; + + /** + * Selector. + * + * @var string + */ + protected $selector; + + private $passphrase = ''; + + /** + * Hash algorithm used. + * + * @see RFC6376 3.3: Signers MUST implement and SHOULD sign using rsa-sha256. + * + * @var string + */ + protected $hashAlgorithm = 'rsa-sha256'; + + /** + * Body canon method. + * + * @var string + */ + protected $bodyCanon = 'simple'; + + /** + * Header canon method. + * + * @var string + */ + protected $headerCanon = 'simple'; + + /** + * Headers not being signed. + * + * @var array + */ + protected $ignoredHeaders = ['return-path' => true]; + + /** + * Signer identity. + * + * @var string + */ + protected $signerIdentity; + + /** + * BodyLength. + * + * @var int + */ + protected $bodyLen = 0; + + /** + * Maximum signedLen. + * + * @var int + */ + protected $maxLen = PHP_INT_MAX; + + /** + * Embbed bodyLen in signature. + * + * @var bool + */ + protected $showLen = false; + + /** + * When the signature has been applied (true means time()), false means not embedded. + * + * @var mixed + */ + protected $signatureTimestamp = true; + + /** + * When will the signature expires false means not embedded, if sigTimestamp is auto + * Expiration is relative, otherwise it's absolute. + * + * @var int + */ + protected $signatureExpiration = false; + + /** + * Must we embed signed headers? + * + * @var bool + */ + protected $debugHeaders = false; + + // work variables + /** + * Headers used to generate hash. + * + * @var array + */ + protected $signedHeaders = []; + + /** + * If debugHeaders is set store debugData here. + * + * @var string[] + */ + private $debugHeadersData = []; + + /** + * Stores the bodyHash. + * + * @var string + */ + private $bodyHash = ''; + + /** + * Stores the signature header. + * + * @var Swift_Mime_Headers_ParameterizedHeader + */ + protected $dkimHeader; + + private $bodyHashHandler; + + private $headerHash; + + private $headerCanonData = ''; + + private $bodyCanonEmptyCounter = 0; + + private $bodyCanonIgnoreStart = 2; + + private $bodyCanonSpace = false; + + private $bodyCanonLastChar = null; + + private $bodyCanonLine = ''; + + private $bound = []; + + /** + * Constructor. + * + * @param string $privateKey + * @param string $domainName + * @param string $selector + * @param string $passphrase + */ + public function __construct($privateKey, $domainName, $selector, $passphrase = '') + { + $this->privateKey = $privateKey; + $this->domainName = $domainName; + $this->signerIdentity = '@'.$domainName; + $this->selector = $selector; + $this->passphrase = $passphrase; + } + + /** + * Reset the Signer. + * + * @see Swift_Signer::reset() + */ + public function reset() + { + $this->headerHash = null; + $this->signedHeaders = []; + $this->bodyHash = null; + $this->bodyHashHandler = null; + $this->bodyCanonIgnoreStart = 2; + $this->bodyCanonEmptyCounter = 0; + $this->bodyCanonLastChar = null; + $this->bodyCanonSpace = false; + } + + /** + * Writes $bytes to the end of the stream. + * + * Writing may not happen immediately if the stream chooses to buffer. If + * you want to write these bytes with immediate effect, call {@link commit()} + * after calling write(). + * + * This method returns the sequence ID of the write (i.e. 1 for first, 2 for + * second, etc etc). + * + * @param string $bytes + * + * @return int + * + * @throws Swift_IoException + */ + // TODO fix return + public function write($bytes) + { + $this->canonicalizeBody($bytes); + foreach ($this->bound as $is) { + $is->write($bytes); + } + } + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + */ + public function commit() + { + // Nothing to do + return; + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + */ + public function bind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + $this->bound[] = $is; + + return; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + */ + public function unbind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + foreach ($this->bound as $k => $stream) { + if ($stream === $is) { + unset($this->bound[$k]); + + return; + } + } + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + */ + public function flushBuffers() + { + $this->reset(); + } + + /** + * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1. + * + * @param string $hash 'rsa-sha1' or 'rsa-sha256' + * + * @throws Swift_SwiftException + * + * @return $this + */ + public function setHashAlgorithm($hash) + { + switch ($hash) { + case 'rsa-sha1': + $this->hashAlgorithm = 'rsa-sha1'; + break; + case 'rsa-sha256': + $this->hashAlgorithm = 'rsa-sha256'; + if (!\defined('OPENSSL_ALGO_SHA256')) { + throw new Swift_SwiftException('Unable to set sha256 as it is not supported by OpenSSL.'); + } + break; + default: + throw new Swift_SwiftException('Unable to set the hash algorithm, must be one of rsa-sha1 or rsa-sha256 (%s given).', $hash); + } + + return $this; + } + + /** + * Set the body canonicalization algorithm. + * + * @param string $canon + * + * @return $this + */ + public function setBodyCanon($canon) + { + if ('relaxed' == $canon) { + $this->bodyCanon = 'relaxed'; + } else { + $this->bodyCanon = 'simple'; + } + + return $this; + } + + /** + * Set the header canonicalization algorithm. + * + * @param string $canon + * + * @return $this + */ + public function setHeaderCanon($canon) + { + if ('relaxed' == $canon) { + $this->headerCanon = 'relaxed'; + } else { + $this->headerCanon = 'simple'; + } + + return $this; + } + + /** + * Set the signer identity. + * + * @param string $identity + * + * @return $this + */ + public function setSignerIdentity($identity) + { + $this->signerIdentity = $identity; + + return $this; + } + + /** + * Set the length of the body to sign. + * + * @param mixed $len (bool or int) + * + * @return $this + */ + public function setBodySignedLen($len) + { + if (true === $len) { + $this->showLen = true; + $this->maxLen = PHP_INT_MAX; + } elseif (false === $len) { + $this->showLen = false; + $this->maxLen = PHP_INT_MAX; + } else { + $this->showLen = true; + $this->maxLen = (int) $len; + } + + return $this; + } + + /** + * Set the signature timestamp. + * + * @param int $time A timestamp + * + * @return $this + */ + public function setSignatureTimestamp($time) + { + $this->signatureTimestamp = $time; + + return $this; + } + + /** + * Set the signature expiration timestamp. + * + * @param int $time A timestamp + * + * @return $this + */ + public function setSignatureExpiration($time) + { + $this->signatureExpiration = $time; + + return $this; + } + + /** + * Enable / disable the DebugHeaders. + * + * @param bool $debug + * + * @return Swift_Signers_DKIMSigner + */ + public function setDebugHeaders($debug) + { + $this->debugHeaders = (bool) $debug; + + return $this; + } + + /** + * Start Body. + */ + public function startBody() + { + // Init + switch ($this->hashAlgorithm) { + case 'rsa-sha256': + $this->bodyHashHandler = hash_init('sha256'); + break; + case 'rsa-sha1': + $this->bodyHashHandler = hash_init('sha1'); + break; + } + $this->bodyCanonLine = ''; + } + + /** + * End Body. + */ + public function endBody() + { + $this->endOfBody(); + } + + /** + * Returns the list of Headers Tampered by this plugin. + * + * @return array + */ + public function getAlteredHeaders() + { + if ($this->debugHeaders) { + return ['DKIM-Signature', 'X-DebugHash']; + } else { + return ['DKIM-Signature']; + } + } + + /** + * Adds an ignored Header. + * + * @param string $header_name + * + * @return Swift_Signers_DKIMSigner + */ + public function ignoreHeader($header_name) + { + $this->ignoredHeaders[strtolower($header_name ?? '')] = true; + + return $this; + } + + /** + * Set the headers to sign. + * + * @return Swift_Signers_DKIMSigner + */ + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) + { + $this->headerCanonData = ''; + // Loop through Headers + $listHeaders = $headers->listAll(); + foreach ($listHeaders as $hName) { + // Check if we need to ignore Header + if (!isset($this->ignoredHeaders[strtolower($hName ?? '')])) { + if ($headers->has($hName)) { + $tmp = $headers->getAll($hName); + foreach ($tmp as $header) { + if ('' != $header->getFieldBody()) { + $this->addHeader($header->toString()); + $this->signedHeaders[] = $header->getFieldName(); + } + } + } + } + } + + return $this; + } + + /** + * Add the signature to the given Headers. + * + * @return Swift_Signers_DKIMSigner + */ + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) + { + // Prepare the DKIM-Signature + $params = ['v' => '1', 'a' => $this->hashAlgorithm, 'bh' => base64_encode($this->bodyHash ?? ''), 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'i' => $this->signerIdentity, 's' => $this->selector]; + if ('simple' != $this->bodyCanon) { + $params['c'] = $this->headerCanon.'/'.$this->bodyCanon; + } elseif ('simple' != $this->headerCanon) { + $params['c'] = $this->headerCanon; + } + if ($this->showLen) { + $params['l'] = $this->bodyLen; + } + if (true === $this->signatureTimestamp) { + $params['t'] = time(); + if (false !== $this->signatureExpiration) { + $params['x'] = $params['t'] + $this->signatureExpiration; + } + } else { + if (false !== $this->signatureTimestamp) { + $params['t'] = $this->signatureTimestamp; + } + if (false !== $this->signatureExpiration) { + $params['x'] = $this->signatureExpiration; + } + } + if ($this->debugHeaders) { + $params['z'] = implode('|', $this->debugHeadersData); + } + $string = ''; + foreach ($params as $k => $v) { + $string .= $k.'='.$v.'; '; + } + $string = trim($string); + $headers->addTextHeader('DKIM-Signature', $string); + // Add the last DKIM-Signature + $tmp = $headers->getAll('DKIM-Signature'); + $this->dkimHeader = end($tmp); + $this->addHeader(trim($this->dkimHeader->toString() ?? '')."\r\n b=", true); + if ($this->debugHeaders) { + $headers->addTextHeader('X-DebugHash', base64_encode($this->headerHash ?? '')); + } + $this->dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->getEncryptedHash() ?? ''), 73, ' '))); + + return $this; + } + + /* Private helpers */ + + protected function addHeader($header, $is_sig = false) + { + switch ($this->headerCanon) { + case 'relaxed': + // Prepare Header and cascade + $exploded = explode(':', $header, 2); + $name = strtolower(trim($exploded[0])); + $value = str_replace("\r\n", '', $exploded[1]); + $value = preg_replace("/[ \t][ \t]+/", ' ', $value); + $header = $name.':'.trim($value).($is_sig ? '' : "\r\n"); + // no break + case 'simple': + // Nothing to do + } + $this->addToHeaderHash($header); + } + + protected function canonicalizeBody($string) + { + $len = \strlen($string); + $canon = ''; + $method = ('relaxed' == $this->bodyCanon); + for ($i = 0; $i < $len; ++$i) { + if ($this->bodyCanonIgnoreStart > 0) { + --$this->bodyCanonIgnoreStart; + continue; + } + switch ($string[$i]) { + case "\r": + $this->bodyCanonLastChar = "\r"; + break; + case "\n": + if ("\r" == $this->bodyCanonLastChar) { + if ($method) { + $this->bodyCanonSpace = false; + } + if ('' == $this->bodyCanonLine) { + ++$this->bodyCanonEmptyCounter; + } else { + $this->bodyCanonLine = ''; + $canon .= "\r\n"; + } + } else { + // Wooops Error + // todo handle it but should never happen + } + break; + case ' ': + case "\t": + if ($method) { + $this->bodyCanonSpace = true; + break; + } + // no break + default: + if ($this->bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter); + $this->bodyCanonEmptyCounter = 0; + } + if ($this->bodyCanonSpace) { + $this->bodyCanonLine .= ' '; + $canon .= ' '; + $this->bodyCanonSpace = false; + } + $this->bodyCanonLine .= $string[$i]; + $canon .= $string[$i]; + } + } + $this->addToBodyHash($canon); + } + + protected function endOfBody() + { + // Add trailing Line return if last line is non empty + if (\strlen($this->bodyCanonLine) > 0) { + $this->addToBodyHash("\r\n"); + } + $this->bodyHash = hash_final($this->bodyHashHandler, true); + } + + private function addToBodyHash($string) + { + $len = \strlen($string); + if ($len > ($new_len = ($this->maxLen - $this->bodyLen))) { + $string = substr($string, 0, $new_len); + $len = $new_len; + } + hash_update($this->bodyHashHandler, $string); + $this->bodyLen += $len; + } + + private function addToHeaderHash($header) + { + if ($this->debugHeaders) { + $this->debugHeadersData[] = trim($header ?? ''); + } + $this->headerCanonData .= $header; + } + + /** + * @throws Swift_SwiftException + * + * @return string + */ + private function getEncryptedHash() + { + $signature = ''; + switch ($this->hashAlgorithm) { + case 'rsa-sha1': + $algorithm = OPENSSL_ALGO_SHA1; + break; + case 'rsa-sha256': + $algorithm = OPENSSL_ALGO_SHA256; + break; + } + $pkeyId = openssl_get_privatekey($this->privateKey, $this->passphrase); + if (!$pkeyId) { + throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']'); + } + if (openssl_sign($this->headerCanonData, $signature, $pkeyId, $algorithm)) { + return $signature; + } + throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']'); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php new file mode 100644 index 0000000..5e2b67b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php @@ -0,0 +1,504 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * DomainKey Signer used to apply DomainKeys Signature to a message. + * + * @author Xavier De Cock <xdecock@gmail.com> + */ +class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner +{ + /** + * PrivateKey. + * + * @var string + */ + protected $privateKey; + + /** + * DomainName. + * + * @var string + */ + protected $domainName; + + /** + * Selector. + * + * @var string + */ + protected $selector; + + /** + * Hash algorithm used. + * + * @var string + */ + protected $hashAlgorithm = 'rsa-sha1'; + + /** + * Canonisation method. + * + * @var string + */ + protected $canon = 'simple'; + + /** + * Headers not being signed. + * + * @var array + */ + protected $ignoredHeaders = []; + + /** + * Signer identity. + * + * @var string + */ + protected $signerIdentity; + + /** + * Must we embed signed headers? + * + * @var bool + */ + protected $debugHeaders = false; + + // work variables + /** + * Headers used to generate hash. + * + * @var array + */ + private $signedHeaders = []; + + /** + * Stores the signature header. + * + * @var Swift_Mime_Headers_ParameterizedHeader + */ + protected $domainKeyHeader; + + /** + * Hash Handler. + * + * @var resource|null + */ + private $hashHandler; + + private $canonData = ''; + + private $bodyCanonEmptyCounter = 0; + + private $bodyCanonIgnoreStart = 2; + + private $bodyCanonSpace = false; + + private $bodyCanonLastChar = null; + + private $bodyCanonLine = ''; + + private $bound = []; + + /** + * Constructor. + * + * @param string $privateKey + * @param string $domainName + * @param string $selector + */ + public function __construct($privateKey, $domainName, $selector) + { + $this->privateKey = $privateKey; + $this->domainName = $domainName; + $this->signerIdentity = '@'.$domainName; + $this->selector = $selector; + } + + /** + * Resets internal states. + * + * @return $this + */ + public function reset() + { + $this->hashHandler = null; + $this->bodyCanonIgnoreStart = 2; + $this->bodyCanonEmptyCounter = 0; + $this->bodyCanonLastChar = null; + $this->bodyCanonSpace = false; + + return $this; + } + + /** + * Writes $bytes to the end of the stream. + * + * Writing may not happen immediately if the stream chooses to buffer. If + * you want to write these bytes with immediate effect, call {@link commit()} + * after calling write(). + * + * This method returns the sequence ID of the write (i.e. 1 for first, 2 for + * second, etc etc). + * + * @param string $bytes + * + * @return int + * + * @throws Swift_IoException + * + * @return $this + */ + public function write($bytes) + { + $this->canonicalizeBody($bytes); + foreach ($this->bound as $is) { + $is->write($bytes); + } + + return $this; + } + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + * + * @throws Swift_IoException + * + * @return $this + */ + public function commit() + { + // Nothing to do + return $this; + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @return $this + */ + public function bind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + $this->bound[] = $is; + + return $this; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @return $this + */ + public function unbind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + foreach ($this->bound as $k => $stream) { + if ($stream === $is) { + unset($this->bound[$k]); + + break; + } + } + + return $this; + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + * + * @return $this + */ + public function flushBuffers() + { + $this->reset(); + + return $this; + } + + /** + * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256. + * + * @param string $hash + * + * @return $this + */ + public function setHashAlgorithm($hash) + { + $this->hashAlgorithm = 'rsa-sha1'; + + return $this; + } + + /** + * Set the canonicalization algorithm. + * + * @param string $canon simple | nofws defaults to simple + * + * @return $this + */ + public function setCanon($canon) + { + if ('nofws' == $canon) { + $this->canon = 'nofws'; + } else { + $this->canon = 'simple'; + } + + return $this; + } + + /** + * Set the signer identity. + * + * @param string $identity + * + * @return $this + */ + public function setSignerIdentity($identity) + { + $this->signerIdentity = $identity; + + return $this; + } + + /** + * Enable / disable the DebugHeaders. + * + * @param bool $debug + * + * @return $this + */ + public function setDebugHeaders($debug) + { + $this->debugHeaders = (bool) $debug; + + return $this; + } + + /** + * Start Body. + */ + public function startBody() + { + } + + /** + * End Body. + */ + public function endBody() + { + $this->endOfBody(); + } + + /** + * Returns the list of Headers Tampered by this plugin. + * + * @return array + */ + public function getAlteredHeaders() + { + if ($this->debugHeaders) { + return ['DomainKey-Signature', 'X-DebugHash']; + } + + return ['DomainKey-Signature']; + } + + /** + * Adds an ignored Header. + * + * @param string $header_name + * + * @return $this + */ + public function ignoreHeader($header_name) + { + $this->ignoredHeaders[strtolower($header_name ?? '')] = true; + + return $this; + } + + /** + * Set the headers to sign. + * + * @return $this + */ + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) + { + $this->startHash(); + $this->canonData = ''; + // Loop through Headers + $listHeaders = $headers->listAll(); + foreach ($listHeaders as $hName) { + // Check if we need to ignore Header + if (!isset($this->ignoredHeaders[strtolower($hName ?? '')])) { + if ($headers->has($hName)) { + $tmp = $headers->getAll($hName); + foreach ($tmp as $header) { + if ('' != $header->getFieldBody()) { + $this->addHeader($header->toString()); + $this->signedHeaders[] = $header->getFieldName(); + } + } + } + } + } + $this->endOfHeaders(); + + return $this; + } + + /** + * Add the signature to the given Headers. + * + * @return $this + */ + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) + { + // Prepare the DomainKey-Signature Header + $params = ['a' => $this->hashAlgorithm, 'b' => chunk_split(base64_encode($this->getEncryptedHash() ?? ''), 73, ' '), 'c' => $this->canon, 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'q' => 'dns', 's' => $this->selector]; + $string = ''; + foreach ($params as $k => $v) { + $string .= $k.'='.$v.'; '; + } + $string = trim($string); + $headers->addTextHeader('DomainKey-Signature', $string); + + return $this; + } + + /* Private helpers */ + + protected function addHeader($header) + { + switch ($this->canon) { + case 'nofws': + // Prepare Header and cascade + $exploded = explode(':', $header, 2); + $name = strtolower(trim($exploded[0])); + $value = str_replace("\r\n", '', $exploded[1]); + $value = preg_replace("/[ \t][ \t]+/", ' ', $value); + $header = $name.':'.trim($value)."\r\n"; + // no break + case 'simple': + // Nothing to do + } + $this->addToHash($header); + } + + protected function endOfHeaders() + { + $this->bodyCanonEmptyCounter = 1; + } + + protected function canonicalizeBody($string) + { + $len = \strlen($string); + $canon = ''; + $nofws = ('nofws' == $this->canon); + for ($i = 0; $i < $len; ++$i) { + if ($this->bodyCanonIgnoreStart > 0) { + --$this->bodyCanonIgnoreStart; + continue; + } + switch ($string[$i]) { + case "\r": + $this->bodyCanonLastChar = "\r"; + break; + case "\n": + if ("\r" == $this->bodyCanonLastChar) { + if ($nofws) { + $this->bodyCanonSpace = false; + } + if ('' == $this->bodyCanonLine) { + ++$this->bodyCanonEmptyCounter; + } else { + $this->bodyCanonLine = ''; + $canon .= "\r\n"; + } + } else { + // Wooops Error + throw new Swift_SwiftException('Invalid new line sequence in mail found \n without preceding \r'); + } + break; + case ' ': + case "\t": + case "\x09": //HTAB + if ($nofws) { + $this->bodyCanonSpace = true; + break; + } + // no break + default: + if ($this->bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter); + $this->bodyCanonEmptyCounter = 0; + } + $this->bodyCanonLine .= $string[$i]; + $canon .= $string[$i]; + } + } + $this->addToHash($canon); + } + + protected function endOfBody() + { + if (\strlen($this->bodyCanonLine) > 0) { + $this->addToHash("\r\n"); + } + } + + private function addToHash($string) + { + $this->canonData .= $string; + hash_update($this->hashHandler, $string); + } + + private function startHash() + { + // Init + switch ($this->hashAlgorithm) { + case 'rsa-sha1': + $this->hashHandler = hash_init('sha1'); + break; + } + $this->bodyCanonLine = ''; + } + + /** + * @throws Swift_SwiftException + * + * @return string + */ + private function getEncryptedHash() + { + $signature = ''; + $pkeyId = openssl_get_privatekey($this->privateKey); + if (!$pkeyId) { + throw new Swift_SwiftException('Unable to load DomainKey Private Key ['.openssl_error_string().']'); + } + if (openssl_sign($this->canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { + return $signature; + } + throw new Swift_SwiftException('Unable to sign DomainKey Hash ['.openssl_error_string().']'); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php new file mode 100644 index 0000000..6f5c209 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php @@ -0,0 +1,61 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Header Signer Interface used to apply Header-Based Signature to a message. + * + * @author Xavier De Cock <xdecock@gmail.com> + */ +interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream +{ + /** + * Exclude an header from the signed headers. + * + * @param string $header_name + * + * @return self + */ + public function ignoreHeader($header_name); + + /** + * Prepare the Signer to get a new Body. + * + * @return self + */ + public function startBody(); + + /** + * Give the signal that the body has finished streaming. + * + * @return self + */ + public function endBody(); + + /** + * Give the headers already given. + * + * @return self + */ + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers); + + /** + * Add the header(s) to the headerSet. + * + * @return self + */ + public function addSignature(Swift_Mime_SimpleHeaderSet $headers); + + /** + * Return the list of header a signer might tamper. + * + * @return array + */ + public function getAlteredHeaders(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php new file mode 100644 index 0000000..520bcc1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php @@ -0,0 +1,183 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * DKIM Signer used to apply DKIM Signature to a message + * Takes advantage of pecl extension. + * + * @author Xavier De Cock <xdecock@gmail.com> + * + * @deprecated since SwiftMailer 6.1.0; use Swift_Signers_DKIMSigner instead. + */ +class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner +{ + private $peclLoaded = false; + + private $dkimHandler = null; + + private $dropFirstLF = true; + + const CANON_RELAXED = 1; + const CANON_SIMPLE = 2; + const SIG_RSA_SHA1 = 3; + const SIG_RSA_SHA256 = 4; + + public function __construct($privateKey, $domainName, $selector) + { + if (!\extension_loaded('opendkim')) { + throw new Swift_SwiftException('php-opendkim extension not found'); + } + + $this->peclLoaded = true; + + parent::__construct($privateKey, $domainName, $selector); + } + + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) + { + $header = new Swift_Mime_Headers_OpenDKIMHeader('DKIM-Signature'); + $headerVal = $this->dkimHandler->getSignatureHeader(); + if (false === $headerVal || \is_int($headerVal)) { + throw new Swift_SwiftException('OpenDKIM Error: '.$this->dkimHandler->getError()); + } + $header->setValue($headerVal); + $headers->set($header); + + return $this; + } + + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) + { + $hash = 'rsa-sha1' == $this->hashAlgorithm ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; + $bodyCanon = 'simple' == $this->bodyCanon ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $headerCanon = 'simple' == $this->headerCanon ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $this->dkimHandler = new OpenDKIMSign($this->privateKey, $this->selector, $this->domainName, $headerCanon, $bodyCanon, $hash, -1); + // Hardcode signature Margin for now + $this->dkimHandler->setMargin(78); + + if (!is_numeric($this->signatureTimestamp)) { + OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, time()); + } else { + if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->signatureTimestamp)) { + throw new Swift_SwiftException('Unable to force signature timestamp ['.openssl_error_string().']'); + } + } + if (isset($this->signerIdentity)) { + $this->dkimHandler->setSigner($this->signerIdentity); + } + $listHeaders = $headers->listAll(); + foreach ($listHeaders as $hName) { + // Check if we need to ignore Header + if (!isset($this->ignoredHeaders[strtolower($hName ?? '')])) { + $tmp = $headers->getAll($hName); + if ($headers->has($hName)) { + foreach ($tmp as $header) { + if ('' != $header->getFieldBody()) { + $htosign = $header->toString(); + $this->dkimHandler->header($htosign); + $this->signedHeaders[] = $header->getFieldName(); + } + } + } + } + } + + return $this; + } + + public function startBody() + { + if (!$this->peclLoaded) { + return parent::startBody(); + } + $this->dropFirstLF = true; + $this->dkimHandler->eoh(); + + return $this; + } + + public function endBody() + { + if (!$this->peclLoaded) { + return parent::endBody(); + } + $this->dkimHandler->eom(); + + return $this; + } + + public function reset() + { + $this->dkimHandler = null; + parent::reset(); + + return $this; + } + + /** + * Set the signature timestamp. + * + * @param int $time + * + * @return $this + */ + public function setSignatureTimestamp($time) + { + $this->signatureTimestamp = $time; + + return $this; + } + + /** + * Set the signature expiration timestamp. + * + * @param int $time + * + * @return $this + */ + public function setSignatureExpiration($time) + { + $this->signatureExpiration = $time; + + return $this; + } + + /** + * Enable / disable the DebugHeaders. + * + * @param bool $debug + * + * @return $this + */ + public function setDebugHeaders($debug) + { + $this->debugHeaders = (bool) $debug; + + return $this; + } + + // Protected + + protected function canonicalizeBody($string) + { + if (!$this->peclLoaded) { + return parent::canonicalizeBody($string); + } + if (true === $this->dropFirstLF) { + if ("\r" == $string[0] && "\n" == $string[1]) { + $string = substr($string, 2); + } + } + $this->dropFirstLF = false; + if (\strlen($string)) { + $this->dkimHandler->body($string); + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php new file mode 100644 index 0000000..3dd3cd0 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php @@ -0,0 +1,542 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * MIME Message Signer used to apply S/MIME Signature/Encryption to a message. + * + * @author Romain-Geissler + * @author Sebastiaan Stok <s.stok@rollerscapes.net> + * @author Jan Flora <jf@penneo.com> + */ +class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner +{ + protected $signCertificate; + protected $signPrivateKey; + protected $encryptCert; + protected $signThenEncrypt = true; + protected $signLevel; + protected $encryptLevel; + protected $signOptions; + protected $encryptOptions; + protected $encryptCipher; + protected $extraCerts = null; + protected $wrapFullMessage = false; + + /** + * @var Swift_StreamFilters_StringReplacementFilterFactory + */ + protected $replacementFactory; + + /** + * @var Swift_Mime_SimpleHeaderFactory + */ + protected $headerFactory; + + /** + * Constructor. + * + * @param string|null $signCertificate + * @param string|null $signPrivateKey + * @param string|null $encryptCertificate + */ + public function __construct($signCertificate = null, $signPrivateKey = null, $encryptCertificate = null) + { + if (null !== $signPrivateKey) { + $this->setSignCertificate($signCertificate, $signPrivateKey); + } + + if (null !== $encryptCertificate) { + $this->setEncryptCertificate($encryptCertificate); + } + + $this->replacementFactory = Swift_DependencyContainer::getInstance() + ->lookup('transport.replacementfactory'); + + $this->signOptions = PKCS7_DETACHED; + $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; + } + + /** + * Set the certificate location to use for signing. + * + * @see https://secure.php.net/manual/en/openssl.pkcs7.flags.php + * + * @param string $certificate + * @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead + * @param int $signOptions Bitwise operator options for openssl_pkcs7_sign() + * @param string $extraCerts A file containing intermediate certificates needed by the signing certificate + * + * @return $this + */ + public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED, $extraCerts = null) + { + $this->signCertificate = 'file://'.str_replace('\\', '/', realpath($certificate)); + + if (null !== $privateKey) { + if (\is_array($privateKey)) { + $this->signPrivateKey = $privateKey; + $this->signPrivateKey[0] = 'file://'.str_replace('\\', '/', realpath($privateKey[0])); + } else { + $this->signPrivateKey = 'file://'.str_replace('\\', '/', realpath($privateKey)); + } + } + + $this->signOptions = $signOptions; + $this->extraCerts = $extraCerts ? realpath($extraCerts) : null; + + return $this; + } + + /** + * Set the certificate location to use for encryption. + * + * @see https://secure.php.net/manual/en/openssl.pkcs7.flags.php + * @see https://secure.php.net/manual/en/openssl.ciphers.php + * + * @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates. + * @param int $cipher + * + * @return $this + */ + public function setEncryptCertificate($recipientCerts, $cipher = null) + { + if (\is_array($recipientCerts)) { + $this->encryptCert = []; + + foreach ($recipientCerts as $cert) { + $this->encryptCert[] = 'file://'.str_replace('\\', '/', realpath($cert)); + } + } else { + $this->encryptCert = 'file://'.str_replace('\\', '/', realpath($recipientCerts)); + } + + if (null !== $cipher) { + $this->encryptCipher = $cipher; + } + + return $this; + } + + /** + * @return string + */ + public function getSignCertificate() + { + return $this->signCertificate; + } + + /** + * @return string + */ + public function getSignPrivateKey() + { + return $this->signPrivateKey; + } + + /** + * Set perform signing before encryption. + * + * The default is to first sign the message and then encrypt. + * But some older mail clients, namely Microsoft Outlook 2000 will work when the message first encrypted. + * As this goes against the official specs, its recommended to only use 'encryption -> signing' when specifically targeting these 'broken' clients. + * + * @param bool $signThenEncrypt + * + * @return $this + */ + public function setSignThenEncrypt($signThenEncrypt = true) + { + $this->signThenEncrypt = $signThenEncrypt; + + return $this; + } + + /** + * @return bool + */ + public function isSignThenEncrypt() + { + return $this->signThenEncrypt; + } + + /** + * Resets internal states. + * + * @return $this + */ + public function reset() + { + return $this; + } + + /** + * Specify whether to wrap the entire MIME message in the S/MIME message. + * + * According to RFC5751 section 3.1: + * In order to protect outer, non-content-related message header fields + * (for instance, the "Subject", "To", "From", and "Cc" fields), the + * sending client MAY wrap a full MIME message in a message/rfc822 + * wrapper in order to apply S/MIME security services to these header + * fields. It is up to the receiving client to decide how to present + * this "inner" header along with the unprotected "outer" header. + * + * @param bool $wrap + * + * @return $this + */ + public function setWrapFullMessage($wrap) + { + $this->wrapFullMessage = $wrap; + } + + /** + * Change the Swift_Message to apply the signing. + * + * @return $this + */ + public function signMessage(Swift_Message $message) + { + if (null === $this->signCertificate && null === $this->encryptCert) { + return $this; + } + + if ($this->signThenEncrypt) { + $this->smimeSignMessage($message); + $this->smimeEncryptMessage($message); + } else { + $this->smimeEncryptMessage($message); + $this->smimeSignMessage($message); + } + } + + /** + * Return the list of header a signer might tamper. + * + * @return array + */ + public function getAlteredHeaders() + { + return ['Content-Type', 'Content-Transfer-Encoding', 'Content-Disposition']; + } + + /** + * Sign a Swift message. + */ + protected function smimeSignMessage(Swift_Message $message) + { + // If we don't have a certificate we can't sign the message + if (null === $this->signCertificate) { + return; + } + + // Work on a clone of the original message + $signMessage = clone $message; + $signMessage->clearSigners(); + + if ($this->wrapFullMessage) { + // The original message essentially becomes the body of the new + // wrapped message + $signMessage = $this->wrapMimeMessage($signMessage); + } else { + // Only keep header needed to parse the body correctly + $this->clearAllHeaders($signMessage); + $this->copyHeaders( + $message, + $signMessage, + [ + 'Content-Type', + 'Content-Transfer-Encoding', + 'Content-Disposition', + ] + ); + } + + // Copy the cloned message into a temporary file stream + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $signMessage->toByteStream($messageStream); + $messageStream->commit(); + $signedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + // Sign the message using openssl + if (!openssl_pkcs7_sign( + $messageStream->getPath(), + $signedMessageStream->getPath(), + $this->signCertificate, + $this->signPrivateKey, + [], + $this->signOptions, + $this->extraCerts + ) + ) { + throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string())); + } + + // Parse the resulting signed message content back into the Swift message + // preserving the original headers + $this->parseSSLOutput($signedMessageStream, $message); + } + + /** + * Encrypt a Swift message. + */ + protected function smimeEncryptMessage(Swift_Message $message) + { + // If we don't have a certificate we can't encrypt the message + if (null === $this->encryptCert) { + return; + } + + // Work on a clone of the original message + $encryptMessage = clone $message; + $encryptMessage->clearSigners(); + + if ($this->wrapFullMessage) { + // The original message essentially becomes the body of the new + // wrapped message + $encryptMessage = $this->wrapMimeMessage($encryptMessage); + } else { + // Only keep header needed to parse the body correctly + $this->clearAllHeaders($encryptMessage); + $this->copyHeaders( + $message, + $encryptMessage, + [ + 'Content-Type', + 'Content-Transfer-Encoding', + 'Content-Disposition', + ] + ); + } + + // Convert the message content (including headers) to a string + // and place it in a temporary file + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $encryptMessage->toByteStream($messageStream); + $messageStream->commit(); + $encryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + // Encrypt the message + if (!openssl_pkcs7_encrypt( + $messageStream->getPath(), + $encryptedMessageStream->getPath(), + $this->encryptCert, + [], + 0, + $this->encryptCipher + ) + ) { + throw new Swift_IoException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string())); + } + + // Parse the resulting signed message content back into the Swift message + // preserving the original headers + $this->parseSSLOutput($encryptedMessageStream, $message); + } + + /** + * Copy named headers from one Swift message to another. + */ + protected function copyHeaders( + Swift_Message $fromMessage, + Swift_Message $toMessage, + array $headers = [] + ) { + foreach ($headers as $header) { + $this->copyHeader($fromMessage, $toMessage, $header); + } + } + + /** + * Copy a single header from one Swift message to another. + * + * @param string $headerName + */ + protected function copyHeader(Swift_Message $fromMessage, Swift_Message $toMessage, $headerName) + { + $header = $fromMessage->getHeaders()->get($headerName); + if (!$header) { + return; + } + $headers = $toMessage->getHeaders(); + switch ($header->getFieldType()) { + case Swift_Mime_Header::TYPE_TEXT: + $headers->addTextHeader($header->getFieldName(), $header->getValue()); + break; + case Swift_Mime_Header::TYPE_PARAMETERIZED: + $headers->addParameterizedHeader( + $header->getFieldName(), + $header->getValue(), + $header->getParameters() + ); + break; + } + } + + /** + * Remove all headers from a Swift message. + */ + protected function clearAllHeaders(Swift_Message $message) + { + $headers = $message->getHeaders(); + foreach ($headers->listAll() as $header) { + $headers->removeAll($header); + } + } + + /** + * Wraps a Swift_Message in a message/rfc822 MIME part. + * + * @return Swift_MimePart + */ + protected function wrapMimeMessage(Swift_Message $message) + { + // Start by copying the original message into a message stream + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + // Create a new MIME part that wraps the original stream + $wrappedMessage = new Swift_MimePart($messageStream, 'message/rfc822'); + $wrappedMessage->setEncoder(new Swift_Mime_ContentEncoder_PlainContentEncoder('7bit')); + + return $wrappedMessage; + } + + protected function parseSSLOutput(Swift_InputByteStream $inputStream, Swift_Message $message) + { + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $this->copyFromOpenSSLOutput($inputStream, $messageStream); + + $this->streamToMime($messageStream, $message); + } + + /** + * Merges an OutputByteStream from OpenSSL to a Swift_Message. + */ + protected function streamToMime(Swift_OutputByteStream $fromStream, Swift_Message $message) + { + // Parse the stream into headers and body + list($headers, $messageStream) = $this->parseStream($fromStream); + + // Get the original message headers + $messageHeaders = $message->getHeaders(); + + // Let the stream determine the headers describing the body content, + // since the body of the original message is overwritten by the body + // coming from the stream. + // These are all content-* headers. + + // Default transfer encoding is 7bit if not set + $encoding = ''; + // Remove all existing transfer encoding headers + $messageHeaders->removeAll('Content-Transfer-Encoding'); + // See whether the stream sets the transfer encoding + if (isset($headers['content-transfer-encoding'])) { + $encoding = $headers['content-transfer-encoding']; + } + + // We use the null content encoder, since the body is already encoded + // according to the transfer encoding specified in the stream + $message->setEncoder(new Swift_Mime_ContentEncoder_NullContentEncoder($encoding)); + + // Set the disposition, if present + if (isset($headers['content-disposition'])) { + $messageHeaders->addTextHeader('Content-Disposition', $headers['content-disposition']); + } + + // Copy over the body from the stream using the content type dictated + // by the stream content + $message->setChildren([]); + $message->setBody($messageStream, $headers['content-type']); + } + + /** + * This message will parse the headers of a MIME email byte stream + * and return an array that contains the headers as an associative + * array and the email body as a string. + * + * @return array + */ + protected function parseStream(Swift_OutputByteStream $emailStream) + { + $bufferLength = 78; + $headerData = ''; + $headerBodySeparator = "\r\n\r\n"; + + $emailStream->setReadPointer(0); + + // Read out the headers section from the stream to a string + while (false !== ($buffer = $emailStream->read($bufferLength))) { + $headerData .= $buffer; + + $headersPosEnd = strpos($headerData, $headerBodySeparator); + + // Stop reading if we found the end of the headers + if (false !== $headersPosEnd) { + break; + } + } + + // Split the header data into lines + $headerData = trim(substr($headerData, 0, $headersPosEnd)); + $headerLines = explode("\r\n", $headerData); + unset($headerData); + + $headers = []; + $currentHeaderName = ''; + + // Transform header lines into an associative array + foreach ($headerLines as $headerLine) { + // Handle headers that span multiple lines + if (false === strpos($headerLine, ':')) { + $headers[$currentHeaderName] .= ' '.trim($headerLine ?? ''); + continue; + } + + $header = explode(':', $headerLine, 2); + $currentHeaderName = strtolower($header[0] ?? ''); + $headers[$currentHeaderName] = trim($header[1] ?? ''); + } + + // Read the entire email body into a byte stream + $bodyStream = new Swift_ByteStream_TemporaryFileByteStream(); + + // Skip the header and separator and point to the body + $emailStream->setReadPointer($headersPosEnd + \strlen($headerBodySeparator)); + + while (false !== ($buffer = $emailStream->read($bufferLength))) { + $bodyStream->write($buffer); + } + + $bodyStream->commit(); + + return [$headers, $bodyStream]; + } + + protected function copyFromOpenSSLOutput(Swift_OutputByteStream $fromStream, Swift_InputByteStream $toStream) + { + $bufferLength = 4096; + $filteredStream = new Swift_ByteStream_TemporaryFileByteStream(); + $filteredStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF'); + $filteredStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF'); + + while (false !== ($buffer = $fromStream->read($bufferLength))) { + $filteredStream->write($buffer); + } + + $filteredStream->flushBuffers(); + + while (false !== ($buffer = $filteredStream->read($bufferLength))) { + $toStream->write($buffer); + } + + $toStream->commit(); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php new file mode 100644 index 0000000..56b6232 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php @@ -0,0 +1,45 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Sends Messages over SMTP with ESMTP support. + * + * @author Chris Corbyn + * + * @method Swift_SmtpTransport setUsername(string $username) Set the username to authenticate with. + * @method string getUsername() Get the username to authenticate with. + * @method Swift_SmtpTransport setPassword(string $password) Set the password to authenticate with. + * @method string getPassword() Get the password to authenticate with. + * @method Swift_SmtpTransport setAuthMode(string $mode) Set the auth mode to use to authenticate. + * @method string getAuthMode() Get the auth mode to use to authenticate. + */ +class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport +{ + /** + * @param string $host + * @param int $port + * @param string|null $encryption SMTP encryption mode: + * - null for plain SMTP (no encryption), + * - 'tls' for SMTP with STARTTLS (best effort encryption), + * - 'ssl' for SMTPS = SMTP over TLS (always encrypted). + */ + public function __construct($host = 'localhost', $port = 25, $encryption = null) + { + \call_user_func_array( + [$this, 'Swift_Transport_EsmtpTransport::__construct'], + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.smtp') + ); + + $this->setHost($host); + $this->setPort($port); + $this->setEncryption($encryption); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php new file mode 100644 index 0000000..9d0e8fe --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php @@ -0,0 +1,53 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Interface for spools. + * + * @author Fabien Potencier + */ +interface Swift_Spool +{ + /** + * Starts this Spool mechanism. + */ + public function start(); + + /** + * Stops this Spool mechanism. + */ + public function stop(); + + /** + * Tests if this Spool mechanism has started. + * + * @return bool + */ + public function isStarted(); + + /** + * Queues a message. + * + * @param Swift_Mime_SimpleMessage $message The message to store + * + * @return bool Whether the operation has succeeded + */ + public function queueMessage(Swift_Mime_SimpleMessage $message); + + /** + * Sends messages using the given transport instance. + * + * @param Swift_Transport $transport A transport instance + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent emails + */ + public function flushQueue(Swift_Transport $transport, &$failedRecipients = null); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php new file mode 100644 index 0000000..c08e0fb --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages in a queue. + * + * @author Fabien Potencier + */ +class Swift_SpoolTransport extends Swift_Transport_SpoolTransport +{ + /** + * Create a new SpoolTransport. + */ + public function __construct(Swift_Spool $spool) + { + $arguments = Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.spool'); + + $arguments[] = $spool; + + \call_user_func_array( + [$this, 'Swift_Transport_SpoolTransport::__construct'], + $arguments + ); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php new file mode 100644 index 0000000..362be2e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Processes bytes as they pass through a stream and performs filtering. + * + * @author Chris Corbyn + */ +interface Swift_StreamFilter +{ + /** + * Based on the buffer given, this returns true if more buffering is needed. + * + * @param mixed $buffer + * + * @return bool + */ + public function shouldBuffer($buffer); + + /** + * Filters $buffer and returns the changes. + * + * @param mixed $buffer + * + * @return mixed + */ + public function filter($buffer); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php new file mode 100644 index 0000000..7e5ddf1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php @@ -0,0 +1,166 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Processes bytes as they pass through a buffer and replaces sequences in it. + * + * This stream filter deals with Byte arrays rather than simple strings. + * + * @author Chris Corbyn + */ +class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilter +{ + /** The replacement(s) to make */ + private $replace; + + /** The Index for searching */ + private $index; + + /** The Search Tree */ + private $tree = []; + + /** Gives the size of the largest search */ + private $treeMaxLen = 0; + + private $repSize; + + /** + * Create a new ByteArrayReplacementFilter with $search and $replace. + * + * @param array $search + * @param array $replace + */ + public function __construct($search, $replace) + { + $this->index = []; + $this->tree = []; + $this->replace = []; + $this->repSize = []; + + $tree = null; + $i = null; + $last_size = $size = 0; + foreach ($search as $i => $search_element) { + if (null !== $tree) { + $tree[-1] = min(\count($replace) - 1, $i - 1); + $tree[-2] = $last_size; + } + $tree = &$this->tree; + if (\is_array($search_element)) { + foreach ($search_element as $k => $char) { + $this->index[$char] = true; + if (!isset($tree[$char])) { + $tree[$char] = []; + } + $tree = &$tree[$char]; + } + $last_size = $k + 1; + $size = max($size, $last_size); + } else { + $last_size = 1; + if (!isset($tree[$search_element])) { + $tree[$search_element] = []; + } + $tree = &$tree[$search_element]; + $size = max($last_size, $size); + $this->index[$search_element] = true; + } + } + if (null !== $i) { + $tree[-1] = min(\count($replace) - 1, $i); + $tree[-2] = $last_size; + $this->treeMaxLen = $size; + } + foreach ($replace as $rep) { + if (!\is_array($rep)) { + $rep = [$rep]; + } + $this->replace[] = $rep; + } + for ($i = \count($this->replace) - 1; $i >= 0; --$i) { + $this->replace[$i] = $rep = $this->filter($this->replace[$i], $i); + $this->repSize[$i] = \count($rep); + } + } + + /** + * Returns true if based on the buffer passed more bytes should be buffered. + * + * @param array $buffer + * + * @return bool + */ + public function shouldBuffer($buffer) + { + $endOfBuffer = end($buffer); + + return isset($this->index[$endOfBuffer]); + } + + /** + * Perform the actual replacements on $buffer and return the result. + * + * @param array $buffer + * @param int $minReplaces + * + * @return array + */ + public function filter($buffer, $minReplaces = -1) + { + if (0 == $this->treeMaxLen) { + return $buffer; + } + + $newBuffer = []; + $buf_size = \count($buffer); + $last_size = 0; + for ($i = 0; $i < $buf_size; ++$i) { + $search_pos = $this->tree; + $last_found = PHP_INT_MAX; + // We try to find if the next byte is part of a search pattern + for ($j = 0; $j <= $this->treeMaxLen; ++$j) { + // We have a new byte for a search pattern + if (isset($buffer[$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { + $search_pos = $search_pos[$buffer[$p]]; + // We have a complete pattern, save, in case we don't find a better match later + if (isset($search_pos[-1]) && $search_pos[-1] < $last_found + && $search_pos[-1] > $minReplaces) { + $last_found = $search_pos[-1]; + $last_size = $search_pos[-2]; + } + } + // We got a complete pattern + elseif (PHP_INT_MAX !== $last_found) { + // Adding replacement datas to output buffer + $rep_size = $this->repSize[$last_found]; + for ($j = 0; $j < $rep_size; ++$j) { + $newBuffer[] = $this->replace[$last_found][$j]; + } + // We Move cursor forward + $i += $last_size - 1; + // Edge Case, last position in buffer + if ($i >= $buf_size) { + $newBuffer[] = $buffer[$i]; + } + + // We start the next loop + continue 2; + } else { + // this byte is not in a pattern and we haven't found another pattern + break; + } + } + // Normal byte, move it to output buffer + $newBuffer[] = $buffer[$i]; + } + + return $newBuffer; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php new file mode 100644 index 0000000..50a63f1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php @@ -0,0 +1,70 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Processes bytes as they pass through a buffer and replaces sequences in it. + * + * @author Chris Corbyn + */ +class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter +{ + /** The needle(s) to search for */ + private $search; + + /** The replacement(s) to make */ + private $replace; + + /** + * Create a new StringReplacementFilter with $search and $replace. + * + * @param string|array $search + * @param string|array $replace + */ + public function __construct($search, $replace) + { + $this->search = $search; + $this->replace = $replace; + } + + /** + * Returns true if based on the buffer passed more bytes should be buffered. + * + * @param string $buffer + * + * @return bool + */ + public function shouldBuffer($buffer) + { + if ('' === $buffer) { + return false; + } + + $endOfBuffer = substr($buffer, -1); + foreach ((array) $this->search as $needle) { + if (false !== strpos($needle, $endOfBuffer)) { + return true; + } + } + + return false; + } + + /** + * Perform the actual replacements on $buffer and return the result. + * + * @param string $buffer + * + * @return string + */ + public function filter($buffer) + { + return str_replace($this->search, $this->replace, $buffer); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php new file mode 100644 index 0000000..783b889 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php @@ -0,0 +1,45 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Creates filters for replacing needles in a string buffer. + * + * @author Chris Corbyn + */ +class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_ReplacementFilterFactory +{ + /** Lazy-loaded filters */ + private $filters = []; + + /** + * Create a new StreamFilter to replace $search with $replace in a string. + * + * @param string $search + * @param string $replace + * + * @return Swift_StreamFilter + */ + public function createFilter($search, $replace) + { + if (!isset($this->filters[$search][$replace])) { + if (!isset($this->filters[$search])) { + $this->filters[$search] = []; + } + + if (!isset($this->filters[$search][$replace])) { + $this->filters[$search][$replace] = []; + } + + $this->filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); + } + + return $this->filters[$search][$replace]; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php new file mode 100644 index 0000000..15e68b1 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php @@ -0,0 +1,28 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Base Exception class. + * + * @author Chris Corbyn + */ +class Swift_SwiftException extends Exception +{ + /** + * Create a new SwiftException with $message. + * + * @param string $message + * @param int $code + */ + public function __construct($message, $code = 0, Exception $previous = null) + { + parent::__construct($message, $code, $previous); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport.php new file mode 100644 index 0000000..bc324e8 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport.php @@ -0,0 +1,76 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Sends Messages via an abstract Transport subsystem. + * + * @author Chris Corbyn + */ +interface Swift_Transport +{ + /** + * Test if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted(); + + /** + * Start this Transport mechanism. + */ + public function start(); + + /** + * Stop this Transport mechanism. + */ + public function stop(); + + /** + * Check if this Transport mechanism is alive. + * + * If a Transport mechanism session is no longer functional, the method + * returns FALSE. It is the responsibility of the developer to handle this + * case and restart the Transport mechanism manually. + * + * @example + * + * if (!$transport->ping()) { + * $transport->stop(); + * $transport->start(); + * } + * + * The Transport mechanism will be started, if it is not already. + * + * It is undefined if the Transport mechanism attempts to restart as long as + * the return value reflects whether the mechanism is now functional. + * + * @return bool TRUE if the transport is alive + */ + public function ping(); + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * This is the responsibility of the send method to start the transport if needed. + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null); + + /** + * Register a plugin in the Transport. + */ + public function registerPlugin(Swift_Events_EventListener $plugin); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php new file mode 100644 index 0000000..d2dbd7a --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php @@ -0,0 +1,541 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Sends Messages over SMTP. + * + * @author Chris Corbyn + */ +abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport +{ + /** Input-Output buffer for sending/receiving SMTP commands and responses */ + protected $buffer; + + /** Connection status */ + protected $started = false; + + /** The domain name to use in HELO command */ + protected $domain = '[127.0.0.1]'; + + /** The event dispatching layer */ + protected $eventDispatcher; + + protected $addressEncoder; + + /** Whether the PIPELINING SMTP extension is enabled (RFC 2920) */ + protected $pipelining = null; + + /** The pipelined commands waiting for response */ + protected $pipeline = []; + + /** Source Ip */ + protected $sourceIp; + + /** Return an array of params for the Buffer */ + abstract protected function getBufferParams(); + + /** + * Creates a new EsmtpTransport using the given I/O buffer. + * + * @param string $localDomain + */ + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1', Swift_AddressEncoder $addressEncoder = null) + { + $this->buffer = $buf; + $this->eventDispatcher = $dispatcher; + $this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder(); + $this->setLocalDomain($localDomain); + } + + /** + * Set the name of the local domain which Swift will identify itself as. + * + * This should be a fully-qualified domain name and should be truly the domain + * you're using. + * + * If your server does not have a domain name, use the IP address. This will + * automatically be wrapped in square brackets as described in RFC 5321, + * section 4.1.3. + * + * @param string $domain + * + * @return $this + */ + public function setLocalDomain($domain) + { + if ('[' !== substr($domain, 0, 1)) { + if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + $domain = '['.$domain.']'; + } elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + $domain = '[IPv6:'.$domain.']'; + } + } + + $this->domain = $domain; + + return $this; + } + + /** + * Get the name of the domain Swift will identify as. + * + * If an IP address was specified, this will be returned wrapped in square + * brackets as described in RFC 5321, section 4.1.3. + * + * @return string + */ + public function getLocalDomain() + { + return $this->domain; + } + + /** + * Sets the source IP. + * + * @param string $source + */ + public function setSourceIp($source) + { + $this->sourceIp = $source; + } + + /** + * Returns the IP used to connect to the destination. + * + * @return string + */ + public function getSourceIp() + { + return $this->sourceIp; + } + + public function setAddressEncoder(Swift_AddressEncoder $addressEncoder) + { + $this->addressEncoder = $addressEncoder; + } + + public function getAddressEncoder() + { + return $this->addressEncoder; + } + + /** + * Start the SMTP connection. + */ + public function start() + { + if (!$this->started) { + if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); + if ($evt->bubbleCancelled()) { + return; + } + } + + try { + $this->buffer->initialize($this->getBufferParams()); + } catch (Swift_TransportException $e) { + $this->throwException($e); + } + $this->readGreeting(); + $this->doHeloCommand(); + + if ($evt) { + $this->eventDispatcher->dispatchEvent($evt, 'transportStarted'); + } + + $this->started = true; + } + } + + /** + * Test if an SMTP connection has been established. + * + * @return bool + */ + public function isStarted() + { + return $this->started; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + if (!$this->isStarted()) { + $this->start(); + } + + $sent = 0; + $failedRecipients = (array) $failedRecipients; + + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + if (!$reversePath = $this->getReversePath($message)) { + $this->throwException(new Swift_TransportException('Cannot send message without a sender address')); + } + + $to = (array) $message->getTo(); + $cc = (array) $message->getCc(); + $bcc = (array) $message->getBcc(); + $tos = array_merge($to, $cc, $bcc); + + $message->setBcc([]); + + try { + $sent += $this->sendTo($message, $reversePath, $tos, $failedRecipients); + } finally { + $message->setBcc($bcc); + } + + if ($evt) { + if ($sent == \count($to) + \count($cc) + \count($bcc)) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + } elseif ($sent > 0) { + $evt->setResult(Swift_Events_SendEvent::RESULT_TENTATIVE); + } else { + $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); + } + $evt->setFailedRecipients($failedRecipients); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $message->generateId(); //Make sure a new Message ID is used + + return $sent; + } + + /** + * Stop the SMTP connection. + */ + public function stop() + { + if ($this->started) { + if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); + if ($evt->bubbleCancelled()) { + return; + } + } + + try { + $this->executeCommand("QUIT\r\n", [221]); + } catch (Swift_TransportException $e) { + } + + try { + $this->buffer->terminate(); + + if ($evt) { + $this->eventDispatcher->dispatchEvent($evt, 'transportStopped'); + } + } catch (Swift_TransportException $e) { + $this->throwException($e); + } + } + $this->started = false; + } + + /** + * {@inheritdoc} + */ + public function ping() + { + try { + if (!$this->isStarted()) { + $this->start(); + } + + $this->executeCommand("NOOP\r\n", [250]); + } catch (Swift_TransportException $e) { + try { + $this->stop(); + } catch (Swift_TransportException $e) { + } + + return false; + } + + return true; + } + + /** + * Register a plugin. + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->eventDispatcher->bindEventListener($plugin); + } + + /** + * Reset the current mail transaction. + */ + public function reset() + { + $this->executeCommand("RSET\r\n", [250], $failures, true); + } + + /** + * Get the IoBuffer where read/writes are occurring. + * + * @return Swift_Transport_IoBuffer + */ + public function getBuffer() + { + return $this->buffer; + } + + /** + * Run a command against the buffer, expecting the given response codes. + * + * If no response codes are given, the response will not be validated. + * If codes are given, an exception will be thrown on an invalid response. + * If the command is RCPT TO, and the pipeline is non-empty, no exception + * will be thrown; instead the failing address is added to $failures. + * + * @param string $command + * @param int[] $codes + * @param string[] $failures An array of failures by-reference + * @param bool $pipeline Do not wait for response + * @param string $address the address, if command is RCPT TO + * + * @return string|null The server response, or null if pipelining is enabled + */ + public function executeCommand($command, $codes = [], &$failures = null, $pipeline = false, $address = null) + { + $failures = (array) $failures; + $seq = $this->buffer->write($command); + if ($evt = $this->eventDispatcher->createCommandEvent($this, $command, $codes)) { + $this->eventDispatcher->dispatchEvent($evt, 'commandSent'); + } + + $this->pipeline[] = [$command, $seq, $codes, $address]; + + if ($pipeline && $this->pipelining) { + return null; + } + + $response = null; + + while ($this->pipeline) { + list($command, $seq, $codes, $address) = array_shift($this->pipeline); + $response = $this->getFullResponse($seq); + try { + $this->assertResponseCode($response, $codes); + } catch (Swift_TransportException $e) { + if ($this->pipeline && $address) { + $failures[] = $address; + } else { + $this->throwException($e); + } + } + } + + return $response; + } + + /** Read the opening SMTP greeting */ + protected function readGreeting() + { + $this->assertResponseCode($this->getFullResponse(0), [220]); + } + + /** Send the HELO welcome */ + protected function doHeloCommand() + { + $this->executeCommand( + sprintf("HELO %s\r\n", $this->domain), [250] + ); + } + + /** Send the MAIL FROM command */ + protected function doMailFromCommand($address) + { + $address = $this->addressEncoder->encodeString($address); + $this->executeCommand( + sprintf("MAIL FROM:<%s>\r\n", $address), [250], $failures, true + ); + } + + /** Send the RCPT TO command */ + protected function doRcptToCommand($address) + { + $address = $this->addressEncoder->encodeString($address); + $this->executeCommand( + sprintf("RCPT TO:<%s>\r\n", $address), [250, 251, 252], $failures, true, $address + ); + } + + /** Send the DATA command */ + protected function doDataCommand(&$failedRecipients) + { + $this->executeCommand("DATA\r\n", [354], $failedRecipients); + } + + /** Stream the contents of the message over the buffer */ + protected function streamMessage(Swift_Mime_SimpleMessage $message) + { + $this->buffer->setWriteTranslations(["\r\n." => "\r\n.."]); + try { + $message->toByteStream($this->buffer); + $this->buffer->flushBuffers(); + } catch (Swift_TransportException $e) { + $this->throwException($e); + } + $this->buffer->setWriteTranslations([]); + $this->executeCommand("\r\n.\r\n", [250]); + } + + /** Determine the best-use reverse path for this message */ + protected function getReversePath(Swift_Mime_SimpleMessage $message) + { + $return = $message->getReturnPath(); + $sender = $message->getSender(); + $from = $message->getFrom(); + $path = null; + if (!empty($return)) { + $path = $return; + } elseif (!empty($sender)) { + // Don't use array_keys + reset($sender); // Reset Pointer to first pos + $path = key($sender); // Get key + } elseif (!empty($from)) { + reset($from); // Reset Pointer to first pos + $path = key($from); // Get key + } + + return $path; + } + + /** Throw a TransportException, first sending it to any listeners */ + protected function throwException(Swift_TransportException $e) + { + if ($evt = $this->eventDispatcher->createTransportExceptionEvent($this, $e)) { + $this->eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); + if (!$evt->bubbleCancelled()) { + throw $e; + } + } else { + throw $e; + } + } + + /** Throws an Exception if a response code is incorrect */ + protected function assertResponseCode($response, $wanted) + { + if (!$response) { + $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got an empty response')); + } + + list($code) = sscanf($response, '%3d'); + $valid = (empty($wanted) || \in_array($code, $wanted)); + + if ($evt = $this->eventDispatcher->createResponseEvent($this, $response, + $valid)) { + $this->eventDispatcher->dispatchEvent($evt, 'responseReceived'); + } + + if (!$valid) { + $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got code "'.$code.'", with message "'.$response.'"', $code)); + } + } + + /** Get an entire multi-line response using its sequence number */ + protected function getFullResponse($seq) + { + $response = ''; + try { + do { + $line = $this->buffer->readLine($seq); + $response .= $line; + } while (null !== $line && false !== $line && ' ' != $line[3]); + } catch (Swift_TransportException $e) { + $this->throwException($e); + } catch (Swift_IoException $e) { + $this->throwException(new Swift_TransportException($e->getMessage(), 0, $e)); + } + + return $response; + } + + /** Send an email to the given recipients from the given reverse path */ + private function doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) + { + $sent = 0; + $this->doMailFromCommand($reversePath); + foreach ($recipients as $forwardPath) { + try { + $this->doRcptToCommand($forwardPath); + ++$sent; + } catch (Swift_TransportException $e) { + $failedRecipients[] = $forwardPath; + } catch (Swift_AddressEncoderException $e) { + $failedRecipients[] = $forwardPath; + } + } + + if (0 != $sent) { + $sent += \count($failedRecipients); + $this->doDataCommand($failedRecipients); + $sent -= \count($failedRecipients); + + $this->streamMessage($message); + } else { + $this->reset(); + } + + return $sent; + } + + /** Send a message to the given To: recipients */ + private function sendTo(Swift_Mime_SimpleMessage $message, $reversePath, array $to, array &$failedRecipients) + { + if (empty($to)) { + return 0; + } + + return $this->doMailTransaction($message, $reversePath, array_keys($to), + $failedRecipients); + } + + /** + * Destructor. + */ + public function __destruct() + { + try { + $this->stop(); + } catch (Exception $e) { + } + } + + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php new file mode 100644 index 0000000..bb3a161 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php @@ -0,0 +1,75 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles CRAM-MD5 authentication. + * + * @author Chris Corbyn + */ +class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport_Esmtp_Authenticator +{ + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'CRAM-MD5'; + } + + /** + * {@inheritdoc} + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) + { + try { + $challenge = $agent->executeCommand("AUTH CRAM-MD5\r\n", [334]); + $challenge = base64_decode(substr($challenge, 4)); + $message = base64_encode( + $username.' '.$this->getResponse($password, $challenge) + ); + $agent->executeCommand(sprintf("%s\r\n", $message), [235]); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", [250]); + + throw $e; + } + } + + /** + * Generate a CRAM-MD5 response from a server challenge. + * + * @param string $secret + * @param string $challenge + * + * @return string + */ + private function getResponse($secret, $challenge) + { + if (\strlen($secret) > 64) { + $secret = pack('H32', md5($secret)); + } + + if (\strlen($secret) < 64) { + $secret = str_pad($secret, 64, \chr(0)); + } + + $k_ipad = substr($secret, 0, 64) ^ str_repeat(\chr(0x36), 64); + $k_opad = substr($secret, 0, 64) ^ str_repeat(\chr(0x5C), 64); + + $inner = pack('H32', md5($k_ipad.$challenge)); + $digest = md5($k_opad.$inner); + + return $digest; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php new file mode 100644 index 0000000..0b9d81b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php @@ -0,0 +1,45 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles LOGIN authentication. + * + * @author Chris Corbyn + */ +class Swift_Transport_Esmtp_Auth_LoginAuthenticator implements Swift_Transport_Esmtp_Authenticator +{ + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'LOGIN'; + } + + /** + * {@inheritdoc} + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) + { + try { + $agent->executeCommand("AUTH LOGIN\r\n", [334]); + $agent->executeCommand(sprintf("%s\r\n", base64_encode($username ?? '')), [334]); + $agent->executeCommand(sprintf("%s\r\n", base64_encode($password ?? '')), [235]); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", [250]); + + throw $e; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php new file mode 100644 index 0000000..41931fd --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php @@ -0,0 +1,681 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * This authentication is for Exchange servers. We support version 1 & 2. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles NTLM authentication. + * + * @author Ward Peeters <ward@coding-tech.com> + */ +class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Esmtp_Authenticator +{ + const NTLMSIG = "NTLMSSP\x00"; + const DESCONST = 'KGS!@#$%'; + + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'NTLM'; + } + + /** + * {@inheritdoc} + * + * @throws \LogicException + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) + { + if (!\function_exists('openssl_encrypt')) { + throw new LogicException('The OpenSSL extension must be enabled to use the NTLM authenticator.'); + } + + if (!\function_exists('bcmul')) { + throw new LogicException('The BCMath functions must be enabled to use the NTLM authenticator.'); + } + + try { + // execute AUTH command and filter out the code at the beginning + // AUTH NTLM xxxx + $response = base64_decode(substr(trim($this->sendMessage1($agent) ?? ''), 4)); + + // extra parameters for our unit cases + $timestamp = \func_num_args() > 3 ? func_get_arg(3) : $this->getCorrectTimestamp(bcmul(microtime(true), '1000')); + $client = \func_num_args() > 4 ? func_get_arg(4) : random_bytes(8); + + // Message 3 response + $this->sendMessage3($response, $username, $password, $timestamp, $client, $agent); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", [250]); + + throw $e; + } + } + + protected function si2bin($si, $bits = 32) + { + $bin = null; + if ($si >= -2 ** ($bits - 1) && ($si <= 2 ** ($bits - 1))) { + // positive or zero + if ($si >= 0) { + $bin = base_convert($si, 10, 2); + // pad to $bits bit + $bin_length = \strlen($bin); + if ($bin_length < $bits) { + $bin = str_repeat('0', $bits - $bin_length).$bin; + } + } else { + // negative + $si = -$si - 2 ** $bits; + $bin = base_convert($si, 10, 2); + $bin_length = \strlen($bin); + if ($bin_length > $bits) { + $bin = str_repeat('1', $bits - $bin_length).$bin; + } + } + } + + return $bin; + } + + /** + * Send our auth message and returns the response. + * + * @return string SMTP Response + */ + protected function sendMessage1(Swift_Transport_SmtpAgent $agent) + { + $message = $this->createMessage1(); + + return $agent->executeCommand(sprintf("AUTH %s %s\r\n", $this->getAuthKeyword(), base64_encode($message)), [334]); + } + + /** + * Fetch all details of our response (message 2). + * + * @param string $response + * + * @return array our response parsed + */ + protected function parseMessage2($response) + { + $responseHex = bin2hex($response); + $length = floor(hexdec(substr($responseHex, 28, 4)) / 256) * 2; + $offset = floor(hexdec(substr($responseHex, 32, 4)) / 256) * 2; + $challenge = hex2bin(substr($responseHex, 48, 16)); + $context = hex2bin(substr($responseHex, 64, 16)); + $targetInfoH = hex2bin(substr($responseHex, 80, 16)); + $targetName = hex2bin(substr($responseHex, $offset, $length)); + $offset = floor(hexdec(substr($responseHex, 88, 4)) / 256) * 2; + $targetInfoBlock = substr($responseHex, $offset); + list($domainName, $serverName, $DNSDomainName, $DNSServerName, $terminatorByte) = $this->readSubBlock($targetInfoBlock); + + return [ + $challenge, + $context, + $targetInfoH, + $targetName, + $domainName, + $serverName, + $DNSDomainName, + $DNSServerName, + hex2bin($targetInfoBlock), + $terminatorByte, + ]; + } + + /** + * Read the blob information in from message2. + * + * @return array + */ + protected function readSubBlock($block) + { + // remove terminatorByte cause it's always the same + $block = substr($block, 0, -8); + + $length = \strlen($block); + $offset = 0; + $data = []; + while ($offset < $length) { + $blockLength = hexdec(substr(substr($block, $offset, 8), -4)) / 256; + $offset += 8; + $data[] = hex2bin(substr($block, $offset, $blockLength * 2)); + $offset += $blockLength * 2; + } + + if (3 == \count($data)) { + $data[] = $data[2]; + $data[2] = ''; + } + + $data[] = $this->createByte('00'); + + return $data; + } + + /** + * Send our final message with all our data. + * + * @param string $response Message 1 response (message 2) + * @param string $username + * @param string $password + * @param string $timestamp + * @param string $client + * @param bool $v2 Use version2 of the protocol + * + * @return string + */ + protected function sendMessage3($response, $username, $password, $timestamp, $client, Swift_Transport_SmtpAgent $agent, $v2 = true) + { + list($domain, $username) = $this->getDomainAndUsername($username); + //$challenge, $context, $targetInfoH, $targetName, $domainName, $workstation, $DNSDomainName, $DNSServerName, $blob, $ter + list($challenge, , , , , $workstation, , , $blob) = $this->parseMessage2($response); + + if (!$v2) { + // LMv1 + $lmResponse = $this->createLMPassword($password, $challenge); + // NTLMv1 + $ntlmResponse = $this->createNTLMPassword($password, $challenge); + } else { + // LMv2 + $lmResponse = $this->createLMv2Password($password, $username, $domain, $challenge, $client); + // NTLMv2 + $ntlmResponse = $this->createNTLMv2Hash($password, $username, $domain, $challenge, $blob, $timestamp, $client); + } + + $message = $this->createMessage3($domain, $username, $workstation, $lmResponse, $ntlmResponse); + + return $agent->executeCommand(sprintf("%s\r\n", base64_encode($message)), [235]); + } + + /** + * Create our message 1. + * + * @return string + */ + protected function createMessage1() + { + return self::NTLMSIG + .$this->createByte('01') // Message 1 +.$this->createByte('0702'); // Flags + } + + /** + * Create our message 3. + * + * @param string $domain + * @param string $username + * @param string $workstation + * @param string $lmResponse + * @param string $ntlmResponse + * + * @return string + */ + protected function createMessage3($domain, $username, $workstation, $lmResponse, $ntlmResponse) + { + // Create security buffers + $domainSec = $this->createSecurityBuffer($domain, 64); + $domainInfo = $this->readSecurityBuffer(bin2hex($domainSec)); + $userSec = $this->createSecurityBuffer($username, ($domainInfo[0] + $domainInfo[1]) / 2); + $userInfo = $this->readSecurityBuffer(bin2hex($userSec)); + $workSec = $this->createSecurityBuffer($workstation, ($userInfo[0] + $userInfo[1]) / 2); + $workInfo = $this->readSecurityBuffer(bin2hex($workSec)); + $lmSec = $this->createSecurityBuffer($lmResponse, ($workInfo[0] + $workInfo[1]) / 2, true); + $lmInfo = $this->readSecurityBuffer(bin2hex($lmSec)); + $ntlmSec = $this->createSecurityBuffer($ntlmResponse, ($lmInfo[0] + $lmInfo[1]) / 2, true); + + return self::NTLMSIG + .$this->createByte('03') // TYPE 3 message +.$lmSec // LM response header +.$ntlmSec // NTLM response header +.$domainSec // Domain header +.$userSec // User header +.$workSec // Workstation header +.$this->createByte('000000009a', 8) // session key header (empty) +.$this->createByte('01020000') // FLAGS +.$this->convertTo16bit($domain) // domain name +.$this->convertTo16bit($username) // username +.$this->convertTo16bit($workstation) // workstation +.$lmResponse + .$ntlmResponse; + } + + /** + * @param string $timestamp Epoch timestamp in microseconds + * @param string $client Random bytes + * @param string $targetInfo + * + * @return string + */ + protected function createBlob($timestamp, $client, $targetInfo) + { + return $this->createByte('0101') + .$this->createByte('00') + .$timestamp + .$client + .$this->createByte('00') + .$targetInfo + .$this->createByte('00'); + } + + /** + * Get domain and username from our username. + * + * @example DOMAIN\username + * + * @param string $name + * + * @return array + */ + protected function getDomainAndUsername($name) + { + if (false !== strpos($name, '\\')) { + return explode('\\', $name); + } + + if (false !== strpos($name, '@')) { + list($user, $domain) = explode('@', $name); + + return [$domain, $user]; + } + + // no domain passed + return ['', $name]; + } + + /** + * Create LMv1 response. + * + * @param string $password + * @param string $challenge + * + * @return string + */ + protected function createLMPassword($password, $challenge) + { + // FIRST PART + $password = $this->createByte(strtoupper($password), 14, false); + list($key1, $key2) = str_split($password, 7); + + $desKey1 = $this->createDesKey($key1); + $desKey2 = $this->createDesKey($key2); + + $constantDecrypt = $this->createByte($this->desEncrypt(self::DESCONST, $desKey1).$this->desEncrypt(self::DESCONST, $desKey2), 21, false); + + // SECOND PART + list($key1, $key2, $key3) = str_split($constantDecrypt, 7); + + $desKey1 = $this->createDesKey($key1); + $desKey2 = $this->createDesKey($key2); + $desKey3 = $this->createDesKey($key3); + + return $this->desEncrypt($challenge, $desKey1).$this->desEncrypt($challenge, $desKey2).$this->desEncrypt($challenge, $desKey3); + } + + /** + * Create NTLMv1 response. + * + * @param string $password + * @param string $challenge + * + * @return string + */ + protected function createNTLMPassword($password, $challenge) + { + // FIRST PART + $ntlmHash = $this->createByte($this->md4Encrypt($password), 21, false); + list($key1, $key2, $key3) = str_split($ntlmHash, 7); + + $desKey1 = $this->createDesKey($key1); + $desKey2 = $this->createDesKey($key2); + $desKey3 = $this->createDesKey($key3); + + return $this->desEncrypt($challenge, $desKey1).$this->desEncrypt($challenge, $desKey2).$this->desEncrypt($challenge, $desKey3); + } + + /** + * Convert a normal timestamp to a tenth of a microtime epoch time. + * + * @param string $time + * + * @return string + */ + protected function getCorrectTimestamp($time) + { + // Get our timestamp (tricky!) + $time = number_format($time, 0, '.', ''); // save microtime to string + $time = bcadd($time, '11644473600000', 0); // add epoch time + $time = bcmul($time, 10000, 0); // tenths of a microsecond. + + $binary = $this->si2bin($time, 64); // create 64 bit binary string + $timestamp = ''; + for ($i = 0; $i < 8; ++$i) { + $timestamp .= \chr(bindec(substr($binary, -(($i + 1) * 8), 8))); + } + + return $timestamp; + } + + /** + * Create LMv2 response. + * + * @param string $password + * @param string $username + * @param string $domain + * @param string $challenge NTLM Challenge + * @param string $client Random string + * + * @return string + */ + protected function createLMv2Password($password, $username, $domain, $challenge, $client) + { + $lmPass = '00'; // by default 00 + // if $password > 15 than we can't use this method + if (\strlen($password) <= 15) { + $ntlmHash = $this->md4Encrypt($password); + $ntml2Hash = $this->md5Encrypt($ntlmHash, $this->convertTo16bit(strtoupper($username).$domain)); + + $lmPass = bin2hex($this->md5Encrypt($ntml2Hash, $challenge.$client).$client); + } + + return $this->createByte($lmPass, 24); + } + + /** + * Create NTLMv2 response. + * + * @param string $password + * @param string $username + * @param string $domain + * @param string $challenge Hex values + * @param string $targetInfo Hex values + * @param string $timestamp + * @param string $client Random bytes + * + * @return string + * + * @see http://davenport.sourceforge.net/ntlm.html#theNtlmResponse + */ + protected function createNTLMv2Hash($password, $username, $domain, $challenge, $targetInfo, $timestamp, $client) + { + $ntlmHash = $this->md4Encrypt($password); + $ntml2Hash = $this->md5Encrypt($ntlmHash, $this->convertTo16bit(strtoupper($username).$domain)); + + // create blob + $blob = $this->createBlob($timestamp, $client, $targetInfo); + + $ntlmv2Response = $this->md5Encrypt($ntml2Hash, $challenge.$blob); + + return $ntlmv2Response.$blob; + } + + protected function createDesKey($key) + { + $material = [bin2hex($key[0])]; + $len = \strlen($key); + for ($i = 1; $i < $len; ++$i) { + list($high, $low) = str_split(bin2hex($key[$i])); + $v = $this->castToByte(\ord($key[$i - 1]) << (7 + 1 - $i) | $this->uRShift(hexdec(dechex(hexdec($high) & 0xf).dechex(hexdec($low) & 0xf)), $i)); + $material[] = str_pad(substr(dechex($v), -2), 2, '0', STR_PAD_LEFT); // cast to byte + } + $material[] = str_pad(substr(dechex($this->castToByte(\ord($key[6]) << 1)), -2), 2, '0'); + + // odd parity + foreach ($material as $k => $v) { + $b = $this->castToByte(hexdec($v)); + $needsParity = 0 == (($this->uRShift($b, 7) ^ $this->uRShift($b, 6) ^ $this->uRShift($b, 5) + ^ $this->uRShift($b, 4) ^ $this->uRShift($b, 3) ^ $this->uRShift($b, 2) + ^ $this->uRShift($b, 1)) & 0x01); + + list($high, $low) = str_split($v); + if ($needsParity) { + $material[$k] = dechex(hexdec($high) | 0x0).dechex(hexdec($low) | 0x1); + } else { + $material[$k] = dechex(hexdec($high) & 0xf).dechex(hexdec($low) & 0xe); + } + } + + return hex2bin(implode('', $material)); + } + + /** HELPER FUNCTIONS */ + + /** + * Create our security buffer depending on length and offset. + * + * @param string $value Value we want to put in + * @param int $offset start of value + * @param bool $is16 Do we 16bit string or not? + * + * @return string + */ + protected function createSecurityBuffer($value, $offset, $is16 = false) + { + $length = \strlen(bin2hex($value)); + $length = $is16 ? $length / 2 : $length; + $length = $this->createByte(str_pad(dechex($length), 2, '0', STR_PAD_LEFT), 2); + + return $length.$length.$this->createByte(dechex($offset), 4); + } + + /** + * Read our security buffer to fetch length and offset of our value. + * + * @param string $value Securitybuffer in hex + * + * @return array array with length and offset + */ + protected function readSecurityBuffer($value) + { + $length = floor(hexdec(substr($value, 0, 4)) / 256) * 2; + $offset = floor(hexdec(substr($value, 8, 4)) / 256) * 2; + + return [$length, $offset]; + } + + /** + * Cast to byte java equivalent to (byte). + * + * @param int $v + * + * @return int + */ + protected function castToByte($v) + { + return (($v + 128) % 256) - 128; + } + + /** + * Java unsigned right bitwise + * $a >>> $b. + * + * @param int $a + * @param int $b + * + * @return int + */ + protected function uRShift($a, $b) + { + if (0 == $b) { + return $a; + } + + return ($a >> $b) & ~(1 << (8 * PHP_INT_SIZE - 1) >> ($b - 1)); + } + + /** + * Right padding with 0 to certain length. + * + * @param string $input + * @param int $bytes Length of bytes + * @param bool $isHex Did we provided hex value + * + * @return string + */ + protected function createByte($input, $bytes = 4, $isHex = true) + { + if ($isHex) { + $byte = hex2bin(str_pad($input, $bytes * 2, '00')); + } else { + $byte = str_pad($input, $bytes, "\x00"); + } + + return $byte; + } + + /** ENCRYPTION ALGORITHMS */ + + /** + * DES Encryption. + * + * @param string $value An 8-byte string + * @param string $key + * + * @return string + */ + protected function desEncrypt($value, $key) + { + return substr(openssl_encrypt($value, 'DES-ECB', $key, \OPENSSL_RAW_DATA), 0, 8); + } + + /** + * MD5 Encryption. + * + * @param string $key Encryption key + * @param string $msg Message to encrypt + * + * @return string + */ + protected function md5Encrypt($key, $msg) + { + $blocksize = 64; + if (\strlen($key) > $blocksize) { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $blocksize, "\0"); + $ipadk = $key ^ str_repeat("\x36", $blocksize); + $opadk = $key ^ str_repeat("\x5c", $blocksize); + + return pack('H*', md5($opadk.pack('H*', md5($ipadk.$msg)))); + } + + /** + * MD4 Encryption. + * + * @param string $input + * + * @return string + * + * @see https://secure.php.net/manual/en/ref.hash.php + */ + protected function md4Encrypt($input) + { + $input = $this->convertTo16bit($input); + + return \function_exists('hash') ? hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); + } + + /** + * Convert UTF-8 to UTF-16. + * + * @param string $input + * + * @return string + */ + protected function convertTo16bit($input) + { + return iconv('UTF-8', 'UTF-16LE', $input); + } + + /** + * @param string $message + */ + protected function debug($message) + { + $message = bin2hex($message); + $messageId = substr($message, 16, 8); + echo substr($message, 0, 16)." NTLMSSP Signature<br />\n"; + echo $messageId." Type Indicator<br />\n"; + + if ('02000000' == $messageId) { + $map = [ + 'Challenge', + 'Context', + 'Target Information Security Buffer', + 'Target Name Data', + 'NetBIOS Domain Name', + 'NetBIOS Server Name', + 'DNS Domain Name', + 'DNS Server Name', + 'BLOB', + 'Target Information Terminator', + ]; + + $data = $this->parseMessage2(hex2bin($message)); + + foreach ($map as $key => $value) { + echo bin2hex($data[$key]).' - '.$data[$key].' ||| '.$value."<br />\n"; + } + } elseif ('03000000' == $messageId) { + $i = 0; + $data[$i++] = substr($message, 24, 16); + list($lmLength, $lmOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 40, 16); + list($ntmlLength, $ntmlOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 56, 16); + list($targetLength, $targetOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 72, 16); + list($userLength, $userOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 88, 16); + list($workLength, $workOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 104, 16); + $data[$i++] = substr($message, 120, 8); + $data[$i++] = substr($message, $targetOffset, $targetLength); + $data[$i++] = substr($message, $userOffset, $userLength); + $data[$i++] = substr($message, $workOffset, $workLength); + $data[$i++] = substr($message, $lmOffset, $lmLength); + $data[$i] = substr($message, $ntmlOffset, $ntmlLength); + + $map = [ + 'LM Response Security Buffer', + 'NTLM Response Security Buffer', + 'Target Name Security Buffer', + 'User Name Security Buffer', + 'Workstation Name Security Buffer', + 'Session Key Security Buffer', + 'Flags', + 'Target Name Data', + 'User Name Data', + 'Workstation Name Data', + 'LM Response Data', + 'NTLM Response Data', + ]; + + foreach ($map as $key => $value) { + echo $data[$key].' - '.hex2bin($data[$key]).' ||| '.$value."<br />\n"; + } + } + + echo '<br /><br />'; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php new file mode 100644 index 0000000..41d0a50 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php @@ -0,0 +1,44 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles PLAIN authentication. + * + * @author Chris Corbyn + */ +class Swift_Transport_Esmtp_Auth_PlainAuthenticator implements Swift_Transport_Esmtp_Authenticator +{ + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'PLAIN'; + } + + /** + * {@inheritdoc} + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) + { + try { + $message = base64_encode($username.\chr(0).$username.\chr(0).$password); + $agent->executeCommand(sprintf("AUTH PLAIN %s\r\n", $message), [235]); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", [250]); + + throw $e; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php new file mode 100644 index 0000000..859f22f --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php @@ -0,0 +1,64 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Handles XOAUTH2 authentication. + * + * Example: + * <code> + * $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls')) + * ->setAuthMode('XOAUTH2') + * ->setUsername('YOUR_EMAIL_ADDRESS') + * ->setPassword('YOUR_ACCESS_TOKEN'); + * </code> + * + * @author xu.li<AthenaLightenedMyPath@gmail.com> + * + * @see https://developers.google.com/google-apps/gmail/xoauth2_protocol + */ +class Swift_Transport_Esmtp_Auth_XOAuth2Authenticator implements Swift_Transport_Esmtp_Authenticator +{ + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'XOAUTH2'; + } + + /** + * {@inheritdoc} + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $email, $token) + { + try { + $param = $this->constructXOAuth2Params($email, $token); + $agent->executeCommand('AUTH XOAUTH2 '.$param."\r\n", [235]); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", [250]); + + throw $e; + } + } + + /** + * Construct the auth parameter. + * + * @see https://developers.google.com/google-apps/gmail/xoauth2_protocol#the_sasl_xoauth2_mechanism + */ + protected function constructXOAuth2Params($email, $token) + { + return base64_encode("user=$email\1auth=Bearer $token\1\1"); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php new file mode 100644 index 0000000..53a90a8 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php @@ -0,0 +1,268 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An ESMTP handler for AUTH support (RFC 5248). + * + * @author Chris Corbyn + */ +class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler +{ + /** + * Authenticators available to process the request. + * + * @var Swift_Transport_Esmtp_Authenticator[] + */ + private $authenticators = []; + + /** + * The username for authentication. + * + * @var string + */ + private $username; + + /** + * The password for authentication. + * + * @var string + */ + private $password; + + /** + * The auth mode for authentication. + * + * @var string + */ + private $auth_mode; + + /** + * The ESMTP AUTH parameters available. + * + * @var string[] + */ + private $esmtpParams = []; + + /** + * Create a new AuthHandler with $authenticators for support. + * + * @param Swift_Transport_Esmtp_Authenticator[] $authenticators + */ + public function __construct(array $authenticators) + { + $this->setAuthenticators($authenticators); + } + + /** + * Set the Authenticators which can process a login request. + * + * @param Swift_Transport_Esmtp_Authenticator[] $authenticators + */ + public function setAuthenticators(array $authenticators) + { + $this->authenticators = $authenticators; + } + + /** + * Get the Authenticators which can process a login request. + * + * @return Swift_Transport_Esmtp_Authenticator[] + */ + public function getAuthenticators() + { + return $this->authenticators; + } + + /** + * Set the username to authenticate with. + * + * @param string $username + */ + public function setUsername($username) + { + $this->username = $username; + } + + /** + * Get the username to authenticate with. + * + * @return string + */ + public function getUsername() + { + return $this->username; + } + + /** + * Set the password to authenticate with. + * + * @param string $password + */ + public function setPassword($password) + { + $this->password = $password; + } + + /** + * Get the password to authenticate with. + * + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * Set the auth mode to use to authenticate. + * + * @param string $mode + */ + public function setAuthMode($mode) + { + $this->auth_mode = $mode; + } + + /** + * Get the auth mode to use to authenticate. + * + * @return string + */ + public function getAuthMode() + { + return $this->auth_mode; + } + + /** + * Get the name of the ESMTP extension this handles. + * + * @return string + */ + public function getHandledKeyword() + { + return 'AUTH'; + } + + /** + * Set the parameters which the EHLO greeting indicated. + * + * @param string[] $parameters + */ + public function setKeywordParams(array $parameters) + { + $this->esmtpParams = $parameters; + } + + /** + * Runs immediately after a EHLO has been issued. + * + * @param Swift_Transport_SmtpAgent $agent to read/write + */ + public function afterEhlo(Swift_Transport_SmtpAgent $agent) + { + if ($this->username) { + $count = 0; + $errors = []; + foreach ($this->getAuthenticatorsForAgent() as $authenticator) { + if (\in_array(strtolower($authenticator->getAuthKeyword() ?? ''), array_map('strtolower', $this->esmtpParams))) { + ++$count; + try { + if ($authenticator->authenticate($agent, $this->username, $this->password)) { + return; + } + } catch (Swift_TransportException $e) { + // keep the error message, but tries the other authenticators + $errors[] = [$authenticator->getAuthKeyword(), $e->getMessage()]; + } + } + } + + $message = 'Failed to authenticate on SMTP server with username "'.$this->username.'" using '.$count.' possible authenticators.'; + foreach ($errors as $error) { + $message .= ' Authenticator '.$error[0].' returned '.$error[1].'.'; + } + throw new Swift_TransportException($message); + } + } + + /** + * Not used. + */ + public function getMailParams() + { + return []; + } + + /** + * Not used. + */ + public function getRcptParams() + { + return []; + } + + /** + * Not used. + */ + public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = [], &$failedRecipients = null, &$stop = false) + { + } + + /** + * Returns +1, -1 or 0 according to the rules for usort(). + * + * This method is called to ensure extensions can be execute in an appropriate order. + * + * @param string $esmtpKeyword to compare with + * + * @return int + */ + public function getPriorityOver($esmtpKeyword) + { + return 0; + } + + /** + * Returns an array of method names which are exposed to the Esmtp class. + * + * @return string[] + */ + public function exposeMixinMethods() + { + return ['setUsername', 'getUsername', 'setPassword', 'getPassword', 'setAuthMode', 'getAuthMode']; + } + + /** + * Not used. + */ + public function resetState() + { + } + + /** + * Returns the authenticator list for the given agent. + * + * @return array + */ + protected function getAuthenticatorsForAgent() + { + if (!$mode = strtolower($this->auth_mode ?? '')) { + return $this->authenticators; + } + + foreach ($this->authenticators as $authenticator) { + if (strtolower($authenticator->getAuthKeyword() ?? '') == $mode) { + return [$authenticator]; + } + } + + throw new Swift_TransportException('Auth mode '.$mode.' is invalid'); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php new file mode 100644 index 0000000..f692a6f --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php @@ -0,0 +1,36 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An Authentication mechanism. + * + * @author Chris Corbyn + */ +interface Swift_Transport_Esmtp_Authenticator +{ + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword(); + + /** + * Try to authenticate the user with $username and $password. + * + * @param string $username + * @param string $password + * + * @return bool true if authentication worked (returning false is deprecated, throw a Swift_TransportException instead) + * + * @throws Swift_TransportException Allows the message to bubble up when authentication was not successful + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/EightBitMimeHandler.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/EightBitMimeHandler.php new file mode 100644 index 0000000..63f7086 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/EightBitMimeHandler.php @@ -0,0 +1,113 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2018 Christian Schmidt + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An ESMTP handler for 8BITMIME support (RFC 6152). + * + * 8BITMIME is required when sending 8-bit content to over SMTP, e.g. when using + * Swift_Mime_ContentEncoder_PlainContentEncoder in "8bit" mode. + * + * 8BITMIME mode is enabled unconditionally, even when sending ASCII-only + * messages, so it should only be used with an outbound SMTP server that will + * convert the message to 7-bit MIME if the next hop does not support 8BITMIME. + * + * @author Christian Schmidt + */ +class Swift_Transport_Esmtp_EightBitMimeHandler implements Swift_Transport_EsmtpHandler +{ + protected $encoding; + + /** + * @param string $encoding The parameter so send with the MAIL FROM command; + * either "8BITMIME" or "7BIT" + */ + public function __construct(string $encoding = '8BITMIME') + { + $this->encoding = $encoding; + } + + /** + * Get the name of the ESMTP extension this handles. + * + * @return string + */ + public function getHandledKeyword() + { + return '8BITMIME'; + } + + /** + * Not used. + */ + public function setKeywordParams(array $parameters) + { + } + + /** + * Not used. + */ + public function afterEhlo(Swift_Transport_SmtpAgent $agent) + { + } + + /** + * Get params which are appended to MAIL FROM:<>. + * + * @return string[] + */ + public function getMailParams() + { + return ['BODY='.$this->encoding]; + } + + /** + * Not used. + */ + public function getRcptParams() + { + return []; + } + + /** + * Not used. + */ + public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = [], &$failedRecipients = null, &$stop = false) + { + } + + /** + * Returns +1, -1 or 0 according to the rules for usort(). + * + * This method is called to ensure extensions can be execute in an appropriate order. + * + * @param string $esmtpKeyword to compare with + * + * @return int + */ + public function getPriorityOver($esmtpKeyword) + { + return 0; + } + + /** + * Not used. + */ + public function exposeMixinMethods() + { + return []; + } + + /** + * Not used. + */ + public function resetState() + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/SmtpUtf8Handler.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/SmtpUtf8Handler.php new file mode 100644 index 0000000..7d0252a --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/SmtpUtf8Handler.php @@ -0,0 +1,107 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2018 Christian Schmidt + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An ESMTP handler for SMTPUTF8 support (RFC 6531). + * + * SMTPUTF8 is required when sending to email addresses containing non-ASCII + * characters in local-part (the substring before @). This handler should be + * used together with Swift_AddressEncoder_Utf8AddressEncoder. + * + * SMTPUTF8 mode is enabled unconditionally, even when sending to ASCII-only + * addresses, so it should only be used with an outbound SMTP server that will + * deliver ASCII-only messages even if the next hop does not support SMTPUTF8. + * + * @author Christian Schmidt + */ +class Swift_Transport_Esmtp_SmtpUtf8Handler implements Swift_Transport_EsmtpHandler +{ + public function __construct() + { + } + + /** + * Get the name of the ESMTP extension this handles. + * + * @return string + */ + public function getHandledKeyword() + { + return 'SMTPUTF8'; + } + + /** + * Not used. + */ + public function setKeywordParams(array $parameters) + { + } + + /** + * Not used. + */ + public function afterEhlo(Swift_Transport_SmtpAgent $agent) + { + } + + /** + * Get params which are appended to MAIL FROM:<>. + * + * @return string[] + */ + public function getMailParams() + { + return ['SMTPUTF8']; + } + + /** + * Not used. + */ + public function getRcptParams() + { + return []; + } + + /** + * Not used. + */ + public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = [], &$failedRecipients = null, &$stop = false) + { + } + + /** + * Returns +1, -1 or 0 according to the rules for usort(). + * + * This method is called to ensure extensions can be execute in an appropriate order. + * + * @param string $esmtpKeyword to compare with + * + * @return int + */ + public function getPriorityOver($esmtpKeyword) + { + return 0; + } + + /** + * Not used. + */ + public function exposeMixinMethods() + { + return []; + } + + /** + * Not used. + */ + public function resetState() + { + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpHandler.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpHandler.php new file mode 100644 index 0000000..b8ea36e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpHandler.php @@ -0,0 +1,86 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * An ESMTP handler. + * + * @author Chris Corbyn + */ +interface Swift_Transport_EsmtpHandler +{ + /** + * Get the name of the ESMTP extension this handles. + * + * @return string + */ + public function getHandledKeyword(); + + /** + * Set the parameters which the EHLO greeting indicated. + * + * @param string[] $parameters + */ + public function setKeywordParams(array $parameters); + + /** + * Runs immediately after a EHLO has been issued. + * + * @param Swift_Transport_SmtpAgent $agent to read/write + */ + public function afterEhlo(Swift_Transport_SmtpAgent $agent); + + /** + * Get params which are appended to MAIL FROM:<>. + * + * @return string[] + */ + public function getMailParams(); + + /** + * Get params which are appended to RCPT TO:<>. + * + * @return string[] + */ + public function getRcptParams(); + + /** + * Runs when a command is due to be sent. + * + * @param Swift_Transport_SmtpAgent $agent to read/write + * @param string $command to send + * @param int[] $codes expected in response + * @param string[] $failedRecipients to collect failures + * @param bool $stop to be set true by-reference if the command is now sent + */ + public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = [], &$failedRecipients = null, &$stop = false); + + /** + * Returns +1, -1 or 0 according to the rules for usort(). + * + * This method is called to ensure extensions can be execute in an appropriate order. + * + * @param string $esmtpKeyword to compare with + * + * @return int + */ + public function getPriorityOver($esmtpKeyword); + + /** + * Returns an array of method names which are exposed to the Esmtp class. + * + * @return string[] + */ + public function exposeMixinMethods(); + + /** + * Tells this handler to clear any buffers and reset its state. + */ + public function resetState(); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php new file mode 100644 index 0000000..36545f5 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php @@ -0,0 +1,446 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Sends Messages over SMTP with ESMTP support. + * + * @author Chris Corbyn + */ +class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTransport implements Swift_Transport_SmtpAgent +{ + /** + * ESMTP extension handlers. + * + * @var Swift_Transport_EsmtpHandler[] + */ + private $handlers = []; + + /** + * ESMTP capabilities. + * + * @var string[] + */ + private $capabilities = []; + + /** + * Connection buffer parameters. + * + * @var array + */ + private $params = [ + 'protocol' => 'tcp', + 'host' => 'localhost', + 'port' => 25, + 'timeout' => 30, + 'blocking' => 1, + 'tls' => false, + 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, + 'stream_context_options' => [], + ]; + + /** + * Creates a new EsmtpTransport using the given I/O buffer. + * + * @param Swift_Transport_EsmtpHandler[] $extensionHandlers + * @param string $localDomain + */ + public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1', Swift_AddressEncoder $addressEncoder = null) + { + parent::__construct($buf, $dispatcher, $localDomain, $addressEncoder); + $this->setExtensionHandlers($extensionHandlers); + } + + /** + * Set the host to connect to. + * + * Literal IPv6 addresses should be wrapped in square brackets. + * + * @param string $host + * + * @return $this + */ + public function setHost($host) + { + $this->params['host'] = $host; + + return $this; + } + + /** + * Get the host to connect to. + * + * @return string + */ + public function getHost() + { + return $this->params['host']; + } + + /** + * Set the port to connect to. + * + * @param int $port + * + * @return $this + */ + public function setPort($port) + { + $this->params['port'] = (int) $port; + + return $this; + } + + /** + * Get the port to connect to. + * + * @return int + */ + public function getPort() + { + return $this->params['port']; + } + + /** + * Set the connection timeout. + * + * @param int $timeout seconds + * + * @return $this + */ + public function setTimeout($timeout) + { + $this->params['timeout'] = (int) $timeout; + $this->buffer->setParam('timeout', (int) $timeout); + + return $this; + } + + /** + * Get the connection timeout. + * + * @return int + */ + public function getTimeout() + { + return $this->params['timeout']; + } + + /** + * Set the encryption type (tls or ssl). + * + * @param string $encryption + * + * @return $this + */ + public function setEncryption($encryption) + { + $encryption = strtolower($encryption ?? ''); + if ('tls' == $encryption) { + $this->params['protocol'] = 'tcp'; + $this->params['tls'] = true; + } else { + $this->params['protocol'] = $encryption; + $this->params['tls'] = false; + } + + return $this; + } + + /** + * Get the encryption type. + * + * @return string + */ + public function getEncryption() + { + return $this->params['tls'] ? 'tls' : $this->params['protocol']; + } + + /** + * Sets the stream context options. + * + * @param array $options + * + * @return $this + */ + public function setStreamOptions($options) + { + $this->params['stream_context_options'] = $options; + + return $this; + } + + /** + * Returns the stream context options. + * + * @return array + */ + public function getStreamOptions() + { + return $this->params['stream_context_options']; + } + + /** + * Sets the source IP. + * + * IPv6 addresses should be wrapped in square brackets. + * + * @param string $source + * + * @return $this + */ + public function setSourceIp($source) + { + $this->params['sourceIp'] = $source; + + return $this; + } + + /** + * Returns the IP used to connect to the destination. + * + * @return string + */ + public function getSourceIp() + { + return $this->params['sourceIp'] ?? null; + } + + /** + * Sets whether SMTP pipelining is enabled. + * + * By default, support is auto-detected using the PIPELINING SMTP extension. + * Use this function to override that in the unlikely event of compatibility + * issues. + * + * @param bool $enabled + * + * @return $this + */ + public function setPipelining($enabled) + { + $this->pipelining = $enabled; + + return $this; + } + + /** + * Returns whether SMTP pipelining is enabled. + * + * @return bool|null a boolean if pipelining is explicitly enabled or disabled, + * or null if support is auto-detected + */ + public function getPipelining() + { + return $this->pipelining; + } + + /** + * Set ESMTP extension handlers. + * + * @param Swift_Transport_EsmtpHandler[] $handlers + * + * @return $this + */ + public function setExtensionHandlers(array $handlers) + { + $assoc = []; + foreach ($handlers as $handler) { + $assoc[$handler->getHandledKeyword()] = $handler; + } + uasort($assoc, function ($a, $b) { + return $a->getPriorityOver($b->getHandledKeyword()); + }); + $this->handlers = $assoc; + $this->setHandlerParams(); + + return $this; + } + + /** + * Get ESMTP extension handlers. + * + * @return Swift_Transport_EsmtpHandler[] + */ + public function getExtensionHandlers() + { + return array_values($this->handlers); + } + + /** + * Run a command against the buffer, expecting the given response codes. + * + * If no response codes are given, the response will not be validated. + * If codes are given, an exception will be thrown on an invalid response. + * + * @param string $command + * @param int[] $codes + * @param string[] $failures An array of failures by-reference + * @param bool $pipeline Do not wait for response + * @param string $address the address, if command is RCPT TO + * + * @return string|null The server response, or null if pipelining is enabled + */ + public function executeCommand($command, $codes = [], &$failures = null, $pipeline = false, $address = null) + { + $failures = (array) $failures; + $stopSignal = false; + $response = null; + foreach ($this->getActiveHandlers() as $handler) { + $response = $handler->onCommand( + $this, $command, $codes, $failures, $stopSignal + ); + if ($stopSignal) { + return $response; + } + } + + return parent::executeCommand($command, $codes, $failures, $pipeline, $address); + } + + /** Mixin handling method for ESMTP handlers */ + public function __call($method, $args) + { + foreach ($this->handlers as $handler) { + if (\in_array(strtolower($method), + array_map('strtolower', (array) $handler->exposeMixinMethods()) + )) { + $return = \call_user_func_array([$handler, $method], $args); + // Allow fluid method calls + if (null === $return && 'set' == substr($method, 0, 3)) { + return $this; + } else { + return $return; + } + } + } + trigger_error('Call to undefined method '.$method, E_USER_ERROR); + } + + /** Get the params to initialize the buffer */ + protected function getBufferParams() + { + return $this->params; + } + + /** Overridden to perform EHLO instead */ + protected function doHeloCommand() + { + try { + $response = $this->executeCommand( + sprintf("EHLO %s\r\n", $this->domain), [250] + ); + } catch (Swift_TransportException $e) { + return parent::doHeloCommand(); + } + + if ($this->params['tls']) { + try { + $this->executeCommand("STARTTLS\r\n", [220]); + + if (!$this->buffer->startTLS()) { + throw new Swift_TransportException('Unable to connect with TLS encryption'); + } + + try { + $response = $this->executeCommand( + sprintf("EHLO %s\r\n", $this->domain), [250] + ); + } catch (Swift_TransportException $e) { + return parent::doHeloCommand(); + } + } catch (Swift_TransportException $e) { + $this->throwException($e); + } + } + + $this->capabilities = $this->getCapabilities($response); + if (!isset($this->pipelining)) { + $this->pipelining = isset($this->capabilities['PIPELINING']); + } + + $this->setHandlerParams(); + foreach ($this->getActiveHandlers() as $handler) { + $handler->afterEhlo($this); + } + } + + /** Overridden to add Extension support */ + protected function doMailFromCommand($address) + { + $address = $this->addressEncoder->encodeString($address); + $handlers = $this->getActiveHandlers(); + $params = []; + foreach ($handlers as $handler) { + $params = array_merge($params, (array) $handler->getMailParams()); + } + $paramStr = !empty($params) ? ' '.implode(' ', $params) : ''; + $this->executeCommand( + sprintf("MAIL FROM:<%s>%s\r\n", $address, $paramStr), [250], $failures, true + ); + } + + /** Overridden to add Extension support */ + protected function doRcptToCommand($address) + { + $address = $this->addressEncoder->encodeString($address); + $handlers = $this->getActiveHandlers(); + $params = []; + foreach ($handlers as $handler) { + $params = array_merge($params, (array) $handler->getRcptParams()); + } + $paramStr = !empty($params) ? ' '.implode(' ', $params) : ''; + $this->executeCommand( + sprintf("RCPT TO:<%s>%s\r\n", $address, $paramStr), [250, 251, 252], $failures, true, $address + ); + } + + /** Determine ESMTP capabilities by function group */ + private function getCapabilities($ehloResponse) + { + $capabilities = []; + $ehloResponse = trim($ehloResponse ?? ''); + $lines = explode("\r\n", $ehloResponse); + array_shift($lines); + foreach ($lines as $line) { + if (preg_match('/^[0-9]{3}[ -]([A-Z0-9-]+)((?:[ =].*)?)$/Di', $line, $matches)) { + $keyword = strtoupper($matches[1]); + $paramStr = strtoupper(ltrim($matches[2], ' =')); + $params = !empty($paramStr) ? explode(' ', $paramStr) : []; + $capabilities[$keyword] = $params; + } + } + + return $capabilities; + } + + /** Set parameters which are used by each extension handler */ + private function setHandlerParams() + { + foreach ($this->handlers as $keyword => $handler) { + if (\array_key_exists($keyword, $this->capabilities)) { + $handler->setKeywordParams($this->capabilities[$keyword]); + } + } + } + + /** Get ESMTP handlers which are currently ok to use */ + private function getActiveHandlers() + { + $handlers = []; + foreach ($this->handlers as $keyword => $handler) { + if (\array_key_exists($keyword, $this->capabilities)) { + $handlers[] = $handler; + } + } + + return $handlers; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php new file mode 100644 index 0000000..1a4b475 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php @@ -0,0 +1,103 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Contains a list of redundant Transports so when one fails, the next is used. + * + * @author Chris Corbyn + */ +class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTransport +{ + /** + * Registered transport currently used. + * + * @var Swift_Transport + */ + private $currentTransport; + + // needed as __construct is called from elsewhere explicitly + public function __construct() + { + parent::__construct(); + } + + /** + * {@inheritdoc} + */ + public function ping() + { + $maxTransports = \count($this->transports); + for ($i = 0; $i < $maxTransports + && $transport = $this->getNextTransport(); ++$i) { + if ($transport->ping()) { + return true; + } else { + $this->killCurrentTransport(); + } + } + + return \count($this->transports) > 0; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $maxTransports = \count($this->transports); + $sent = 0; + $this->lastUsedTransport = null; + + for ($i = 0; $i < $maxTransports + && $transport = $this->getNextTransport(); ++$i) { + try { + if (!$transport->isStarted()) { + $transport->start(); + } + + if ($sent = $transport->send($message, $failedRecipients)) { + $this->lastUsedTransport = $transport; + + return $sent; + } + } catch (Swift_TransportException $e) { + $this->killCurrentTransport(); + } + } + + if (0 == \count($this->transports)) { + throw new Swift_TransportException('All Transports in FailoverTransport failed, or no Transports available'); + } + + return $sent; + } + + protected function getNextTransport() + { + if (!isset($this->currentTransport)) { + $this->currentTransport = parent::getNextTransport(); + } + + return $this->currentTransport; + } + + protected function killCurrentTransport() + { + $this->currentTransport = null; + parent::killCurrentTransport(); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php new file mode 100644 index 0000000..50f1e5e --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Buffers input and output to a resource. + * + * @author Chris Corbyn + */ +interface Swift_Transport_IoBuffer extends Swift_InputByteStream, Swift_OutputByteStream +{ + /** A socket buffer over TCP */ + const TYPE_SOCKET = 0x0001; + + /** A process buffer with I/O support */ + const TYPE_PROCESS = 0x0010; + + /** + * Perform any initialization needed, using the given $params. + * + * Parameters will vary depending upon the type of IoBuffer used. + */ + public function initialize(array $params); + + /** + * Set an individual param on the buffer (e.g. switching to SSL). + * + * @param string $param + * @param mixed $value + */ + public function setParam($param, $value); + + /** + * Perform any shutdown logic needed. + */ + public function terminate(); + + /** + * Set an array of string replacements which should be made on data written + * to the buffer. + * + * This could replace LF with CRLF for example. + * + * @param string[] $replacements + */ + public function setWriteTranslations(array $replacements); + + /** + * Get a line of output (including any CRLF). + * + * The $sequence number comes from any writes and may or may not be used + * depending upon the implementation. + * + * @param int $sequence of last write to scan from + * + * @return string + */ + public function readLine($sequence); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php new file mode 100644 index 0000000..0b5ba9d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php @@ -0,0 +1,192 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Redundantly and rotationally uses several Transports when sending. + * + * @author Chris Corbyn + */ +class Swift_Transport_LoadBalancedTransport implements Swift_Transport +{ + /** + * Transports which are deemed useless. + * + * @var Swift_Transport[] + */ + private $deadTransports = []; + + /** + * The Transports which are used in rotation. + * + * @var Swift_Transport[] + */ + protected $transports = []; + + /** + * The Transport used in the last successful send operation. + * + * @var Swift_Transport + */ + protected $lastUsedTransport = null; + + // needed as __construct is called from elsewhere explicitly + public function __construct() + { + } + + /** + * Set $transports to delegate to. + * + * @param Swift_Transport[] $transports + */ + public function setTransports(array $transports) + { + $this->transports = $transports; + $this->deadTransports = []; + } + + /** + * Get $transports to delegate to. + * + * @return Swift_Transport[] + */ + public function getTransports() + { + return array_merge($this->transports, $this->deadTransports); + } + + /** + * Get the Transport used in the last successful send operation. + * + * @return Swift_Transport + */ + public function getLastUsedTransport() + { + return $this->lastUsedTransport; + } + + /** + * Test if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return \count($this->transports) > 0; + } + + /** + * Start this Transport mechanism. + */ + public function start() + { + $this->transports = array_merge($this->transports, $this->deadTransports); + } + + /** + * Stop this Transport mechanism. + */ + public function stop() + { + foreach ($this->transports as $transport) { + $transport->stop(); + } + } + + /** + * {@inheritdoc} + */ + public function ping() + { + foreach ($this->transports as $transport) { + if (!$transport->ping()) { + $this->killCurrentTransport(); + } + } + + return \count($this->transports) > 0; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $maxTransports = \count($this->transports); + $sent = 0; + $this->lastUsedTransport = null; + + for ($i = 0; $i < $maxTransports + && $transport = $this->getNextTransport(); ++$i) { + try { + if (!$transport->isStarted()) { + $transport->start(); + } + if ($sent = $transport->send($message, $failedRecipients)) { + $this->lastUsedTransport = $transport; + break; + } + } catch (Swift_TransportException $e) { + $this->killCurrentTransport(); + } + } + + if (0 == \count($this->transports)) { + throw new Swift_TransportException('All Transports in LoadBalancedTransport failed, or no Transports available'); + } + + return $sent; + } + + /** + * Register a plugin. + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + foreach ($this->transports as $transport) { + $transport->registerPlugin($plugin); + } + } + + /** + * Rotates the transport list around and returns the first instance. + * + * @return Swift_Transport + */ + protected function getNextTransport() + { + if ($next = array_shift($this->transports)) { + $this->transports[] = $next; + } + + return $next; + } + + /** + * Tag the currently used (top of stack) transport as dead/useless. + */ + protected function killCurrentTransport() + { + if ($transport = array_pop($this->transports)) { + try { + $transport->stop(); + } catch (Exception $e) { + } + $this->deadTransports[] = $transport; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php new file mode 100644 index 0000000..7d910db --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php @@ -0,0 +1,98 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Pretends messages have been sent, but just ignores them. + * + * @author Fabien Potencier + */ +class Swift_Transport_NullTransport implements Swift_Transport +{ + /** The event dispatcher from the plugin API */ + private $eventDispatcher; + + /** + * Constructor. + */ + public function __construct(Swift_Events_EventDispatcher $eventDispatcher) + { + $this->eventDispatcher = $eventDispatcher; + } + + /** + * Tests if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Transport mechanism. + */ + public function start() + { + } + + /** + * Stops this Transport mechanism. + */ + public function stop() + { + } + + /** + * {@inheritdoc} + */ + public function ping() + { + return true; + } + + /** + * Sends the given message. + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent emails + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + if ($evt) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $count = ( + \count((array) $message->getTo()) + + \count((array) $message->getCc()) + + \count((array) $message->getBcc()) + ); + + return $count; + } + + /** + * Register a plugin. + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->eventDispatcher->bindEventListener($plugin); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php new file mode 100644 index 0000000..65a434d --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php @@ -0,0 +1,158 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * SendmailTransport for sending mail through a Sendmail/Postfix (etc..) binary. + * + * Supported modes are -bs and -t, with any additional flags desired. + * It is advised to use -bs mode since error reporting with -t mode is not + * possible. + * + * @author Chris Corbyn + */ +class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTransport +{ + /** + * Connection buffer parameters. + * + * @var array + */ + private $params = [ + 'timeout' => 30, + 'blocking' => 1, + 'command' => '/usr/sbin/sendmail -bs', + 'type' => Swift_Transport_IoBuffer::TYPE_PROCESS, + ]; + + /** + * Create a new SendmailTransport with $buf for I/O. + * + * @param string $localDomain + */ + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1', Swift_AddressEncoder $addressEncoder = null) + { + parent::__construct($buf, $dispatcher, $localDomain, $addressEncoder); + } + + /** + * Start the standalone SMTP session if running in -bs mode. + */ + public function start() + { + if (false !== strpos($this->getCommand(), ' -bs')) { + parent::start(); + } + } + + /** + * Set the command to invoke. + * + * If using -t mode you are strongly advised to include -oi or -i in the flags. + * For example: /usr/sbin/sendmail -oi -t + * Swift will append a -f<sender> flag if one is not present. + * + * The recommended mode is "-bs" since it is interactive and failure notifications + * are hence possible. + * + * @param string $command + * + * @return $this + */ + public function setCommand($command) + { + $this->params['command'] = $command; + + return $this; + } + + /** + * Get the sendmail command which will be invoked. + * + * @return string + */ + public function getCommand() + { + return $this->params['command']; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * + * The return value is the number of recipients who were accepted for delivery. + * NOTE: If using 'sendmail -t' you will not be aware of any failures until + * they bounce (i.e. send() will always return 100% success). + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + $failedRecipients = (array) $failedRecipients; + $command = $this->getCommand(); + $buffer = $this->getBuffer(); + $count = 0; + + if (false !== strpos($command, ' -t')) { + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + if (false === strpos($command, ' -f')) { + $command .= ' -f'.escapeshellarg($this->getReversePath($message) ?? ''); + } + + $buffer->initialize(array_merge($this->params, ['command' => $command])); + + if (false === strpos($command, ' -i') && false === strpos($command, ' -oi')) { + $buffer->setWriteTranslations(["\r\n" => "\n", "\n." => "\n.."]); + } else { + $buffer->setWriteTranslations(["\r\n" => "\n"]); + } + + $count = \count((array) $message->getTo()) + + \count((array) $message->getCc()) + + \count((array) $message->getBcc()) + ; + $message->toByteStream($buffer); + $buffer->flushBuffers(); + $buffer->setWriteTranslations([]); + $buffer->terminate(); + + if ($evt) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + $evt->setFailedRecipients($failedRecipients); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $message->generateId(); + } elseif (false !== strpos($command, ' -bs')) { + $count = parent::send($message, $failedRecipients); + } else { + $this->throwException(new Swift_TransportException( + 'Unsupported sendmail command flags ['.$command.']. '. + 'Must be one of "-bs" or "-t" but can include additional flags.' + )); + } + + return $count; + } + + /** Get the params to initialize the buffer */ + protected function getBufferParams() + { + return $this->params; + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SmtpAgent.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SmtpAgent.php new file mode 100644 index 0000000..e8ce65c --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SmtpAgent.php @@ -0,0 +1,36 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Wraps an IoBuffer to send/receive SMTP commands/responses. + * + * @author Chris Corbyn + */ +interface Swift_Transport_SmtpAgent +{ + /** + * Get the IoBuffer where read/writes are occurring. + * + * @return Swift_Transport_IoBuffer + */ + public function getBuffer(); + + /** + * Run a command against the buffer, expecting the given response codes. + * + * If no response codes are given, the response will not be validated. + * If codes are given, an exception will be thrown on an invalid response. + * + * @param string $command + * @param int[] $codes + * @param string[] $failures An array of failures by-reference + */ + public function executeCommand($command, $codes = [], &$failures = null); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SpoolTransport.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SpoolTransport.php new file mode 100644 index 0000000..0cb6a5b --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SpoolTransport.php @@ -0,0 +1,120 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2009 Fabien Potencier <fabien.potencier@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages in a queue. + * + * @author Fabien Potencier + */ +class Swift_Transport_SpoolTransport implements Swift_Transport +{ + /** The spool instance */ + private $spool; + + /** The event dispatcher from the plugin API */ + private $eventDispatcher; + + /** + * Constructor. + */ + public function __construct(Swift_Events_EventDispatcher $eventDispatcher, Swift_Spool $spool = null) + { + $this->eventDispatcher = $eventDispatcher; + $this->spool = $spool; + } + + /** + * Sets the spool object. + * + * @return $this + */ + public function setSpool(Swift_Spool $spool) + { + $this->spool = $spool; + + return $this; + } + + /** + * Get the spool object. + * + * @return Swift_Spool + */ + public function getSpool() + { + return $this->spool; + } + + /** + * Tests if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Transport mechanism. + */ + public function start() + { + } + + /** + * Stops this Transport mechanism. + */ + public function stop() + { + } + + /** + * {@inheritdoc} + */ + public function ping() + { + return true; + } + + /** + * Sends the given message. + * + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent e-mail's + */ + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) + { + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + $success = $this->spool->queueMessage($message); + + if ($evt) { + $evt->setResult($success ? Swift_Events_SendEvent::RESULT_SPOOLED : Swift_Events_SendEvent::RESULT_FAILED); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + return 1; + } + + /** + * Register a plugin. + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->eventDispatcher->bindEventListener($plugin); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php new file mode 100644 index 0000000..70782ad --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php @@ -0,0 +1,319 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * A generic IoBuffer implementation supporting remote sockets and local processes. + * + * @author Chris Corbyn + */ +class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_Transport_IoBuffer +{ + /** A primary socket */ + private $stream; + + /** The input stream */ + private $in; + + /** The output stream */ + private $out; + + /** Buffer initialization parameters */ + private $params = []; + + /** The ReplacementFilterFactory */ + private $replacementFactory; + + /** Translations performed on data being streamed into the buffer */ + private $translations = []; + + /** + * Create a new StreamBuffer using $replacementFactory for transformations. + */ + public function __construct(Swift_ReplacementFilterFactory $replacementFactory) + { + $this->replacementFactory = $replacementFactory; + } + + /** + * Perform any initialization needed, using the given $params. + * + * Parameters will vary depending upon the type of IoBuffer used. + */ + public function initialize(array $params) + { + $this->params = $params; + switch ($params['type']) { + case self::TYPE_PROCESS: + $this->establishProcessConnection(); + break; + case self::TYPE_SOCKET: + default: + $this->establishSocketConnection(); + break; + } + } + + /** + * Set an individual param on the buffer (e.g. switching to SSL). + * + * @param string $param + * @param mixed $value + */ + public function setParam($param, $value) + { + if (isset($this->stream)) { + switch ($param) { + case 'timeout': + if ($this->stream) { + stream_set_timeout($this->stream, $value); + } + break; + + case 'blocking': + if ($this->stream) { + stream_set_blocking($this->stream, 1); + } + } + } + $this->params[$param] = $value; + } + + public function startTLS() + { + // STREAM_CRYPTO_METHOD_TLS_CLIENT only allow tls1.0 connections (some php versions) + // To support modern tls we allow explicit tls1.0, tls1.1, tls1.2 + // Ssl3 and older are not allowed because they are vulnerable + // @TODO make tls arguments configurable + return stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT); + } + + /** + * Perform any shutdown logic needed. + */ + public function terminate() + { + if (isset($this->stream)) { + switch ($this->params['type']) { + case self::TYPE_PROCESS: + fclose($this->in); + fclose($this->out); + proc_close($this->stream); + break; + case self::TYPE_SOCKET: + default: + fclose($this->stream); + break; + } + } + $this->stream = null; + $this->out = null; + $this->in = null; + } + + /** + * Set an array of string replacements which should be made on data written + * to the buffer. + * + * This could replace LF with CRLF for example. + * + * @param string[] $replacements + */ + public function setWriteTranslations(array $replacements) + { + foreach ($this->translations as $search => $replace) { + if (!isset($replacements[$search])) { + $this->removeFilter($search); + unset($this->translations[$search]); + } + } + + foreach ($replacements as $search => $replace) { + if (!isset($this->translations[$search])) { + $this->addFilter( + $this->replacementFactory->createFilter($search, $replace), $search + ); + $this->translations[$search] = true; + } + } + } + + /** + * Get a line of output (including any CRLF). + * + * The $sequence number comes from any writes and may or may not be used + * depending upon the implementation. + * + * @param int $sequence of last write to scan from + * + * @return string + * + * @throws Swift_IoException + */ + public function readLine($sequence) + { + if (isset($this->out) && !feof($this->out)) { + $line = fgets($this->out); + if (0 == \strlen($line)) { + $metas = stream_get_meta_data($this->out); + if ($metas['timed_out']) { + throw new Swift_IoException('Connection to '.$this->getReadConnectionDescription().' Timed Out'); + } + } + + return $line; + } + } + + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the remaining bytes are given instead. + * If no bytes are remaining at all, boolean false is returned. + * + * @param int $length + * + * @return string|bool + * + * @throws Swift_IoException + */ + public function read($length) + { + if (isset($this->out) && !feof($this->out)) { + $ret = fread($this->out, $length); + if (0 == \strlen($ret)) { + $metas = stream_get_meta_data($this->out); + if ($metas['timed_out']) { + throw new Swift_IoException('Connection to '.$this->getReadConnectionDescription().' Timed Out'); + } + } + + return $ret; + } + } + + /** Not implemented */ + public function setReadPointer($byteOffset) + { + } + + /** Flush the stream contents */ + protected function flush() + { + if (isset($this->in)) { + fflush($this->in); + } + } + + /** Write this bytes to the stream */ + protected function doCommit($bytes) + { + if (isset($this->in)) { + $bytesToWrite = \strlen($bytes); + $totalBytesWritten = 0; + + while ($totalBytesWritten < $bytesToWrite) { + $bytesWritten = fwrite($this->in, substr($bytes, $totalBytesWritten)); + if (false === $bytesWritten || 0 === $bytesWritten) { + break; + } + + $totalBytesWritten += $bytesWritten; + } + + if ($totalBytesWritten > 0) { + return ++$this->sequence; + } + } + } + + /** + * Establishes a connection to a remote server. + */ + private function establishSocketConnection() + { + $host = $this->params['host']; + if (!empty($this->params['protocol'])) { + $host = $this->params['protocol'].'://'.$host; + } + $timeout = 15; + if (!empty($this->params['timeout'])) { + $timeout = $this->params['timeout']; + } + $options = []; + if (!empty($this->params['sourceIp'])) { + $options['socket']['bindto'] = $this->params['sourceIp'].':0'; + } + + if (isset($this->params['stream_context_options'])) { + $options = array_merge($options, $this->params['stream_context_options']); + } + $streamContext = stream_context_create($options); + + set_error_handler(function ($type, $msg) { + throw new Swift_TransportException('Connection could not be established with host '.$this->params['host'].' :'.$msg); + }); + try { + $this->stream = stream_socket_client($host.':'.$this->params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext); + } finally { + restore_error_handler(); + } + + if (!empty($this->params['blocking'])) { + stream_set_blocking($this->stream, 1); + } else { + stream_set_blocking($this->stream, 0); + } + stream_set_timeout($this->stream, $timeout); + $this->in = &$this->stream; + $this->out = &$this->stream; + } + + /** + * Opens a process for input/output. + */ + private function establishProcessConnection() + { + $command = $this->params['command']; + $descriptorSpec = [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ]; + $pipes = []; + $this->stream = proc_open($command, $descriptorSpec, $pipes); + stream_set_blocking($pipes[2], 0); + if ($err = stream_get_contents($pipes[2])) { + throw new Swift_TransportException('Process could not be started ['.$err.']'); + } + $this->in = &$pipes[0]; + $this->out = &$pipes[1]; + } + + private function getReadConnectionDescription() + { + switch ($this->params['type']) { + case self::TYPE_PROCESS: + return 'Process '.$this->params['command']; + break; + + case self::TYPE_SOCKET: + default: + $host = $this->params['host']; + if (!empty($this->params['protocol'])) { + $host = $this->params['protocol'].'://'.$host; + } + $host .= ':'.$this->params['port']; + + return $host; + break; + } + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php new file mode 100644 index 0000000..c741745 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php @@ -0,0 +1,28 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * TransportException thrown when an error occurs in the Transport subsystem. + * + * @author Chris Corbyn + */ +class Swift_TransportException extends Swift_IoException +{ + /** + * Create a new TransportException with $message. + * + * @param string $message + * @param int $code + */ + public function __construct($message, $code = 0, Exception $previous = null) + { + parent::__construct($message, $code, $previous); + } +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php new file mode 100644 index 0000000..9d94d77 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php @@ -0,0 +1,23 @@ +<?php + +Swift_DependencyContainer::getInstance() + ->register('cache') + ->asAliasOf('cache.array') + + ->register('tempdir') + ->asValue('/tmp') + + ->register('cache.null') + ->asSharedInstanceOf('Swift_KeyCache_NullKeyCache') + + ->register('cache.array') + ->asSharedInstanceOf('Swift_KeyCache_ArrayKeyCache') + ->withDependencies(['cache.inputstream']) + + ->register('cache.disk') + ->asSharedInstanceOf('Swift_KeyCache_DiskKeyCache') + ->withDependencies(['cache.inputstream', 'tempdir']) + + ->register('cache.inputstream') + ->asNewInstanceOf('Swift_KeyCache_SimpleKeyCacheInputStream') +; diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php new file mode 100644 index 0000000..64d69d2 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php @@ -0,0 +1,9 @@ +<?php + +Swift_DependencyContainer::getInstance() + ->register('message.message') + ->asNewInstanceOf('Swift_Message') + + ->register('message.mimepart') + ->asNewInstanceOf('Swift_MimePart') +; diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php new file mode 100644 index 0000000..307756c --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php @@ -0,0 +1,134 @@ +<?php + +require __DIR__.'/../mime_types.php'; + +Swift_DependencyContainer::getInstance() + ->register('properties.charset') + ->asValue('utf-8') + + ->register('email.validator') + ->asSharedInstanceOf('Egulias\EmailValidator\EmailValidator') + + ->register('mime.idgenerator.idright') + // As SERVER_NAME can come from the user in certain configurations, check that + // it does not contain forbidden characters (see RFC 952 and RFC 2181). Use + // preg_replace() instead of preg_match() to prevent DoS attacks with long host names. + ->asValue(!empty($_SERVER['SERVER_NAME']) && '' === preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated') + + ->register('mime.idgenerator') + ->asSharedInstanceOf('Swift_Mime_IdGenerator') + ->withDependencies([ + 'mime.idgenerator.idright', + ]) + + ->register('mime.message') + ->asNewInstanceOf('Swift_Mime_SimpleMessage') + ->withDependencies([ + 'mime.headerset', + 'mime.textcontentencoder', + 'cache', + 'mime.idgenerator', + 'properties.charset', + ]) + + ->register('mime.part') + ->asNewInstanceOf('Swift_Mime_MimePart') + ->withDependencies([ + 'mime.headerset', + 'mime.textcontentencoder', + 'cache', + 'mime.idgenerator', + 'properties.charset', + ]) + + ->register('mime.attachment') + ->asNewInstanceOf('Swift_Mime_Attachment') + ->withDependencies([ + 'mime.headerset', + 'mime.base64contentencoder', + 'cache', + 'mime.idgenerator', + ]) + ->addConstructorValue($swift_mime_types) + + ->register('mime.embeddedfile') + ->asNewInstanceOf('Swift_Mime_EmbeddedFile') + ->withDependencies([ + 'mime.headerset', + 'mime.base64contentencoder', + 'cache', + 'mime.idgenerator', + ]) + ->addConstructorValue($swift_mime_types) + + ->register('mime.headerfactory') + ->asNewInstanceOf('Swift_Mime_SimpleHeaderFactory') + ->withDependencies([ + 'mime.qpheaderencoder', + 'mime.rfc2231encoder', + 'email.validator', + 'properties.charset', + 'address.idnaddressencoder', + ]) + + ->register('mime.headerset') + ->asNewInstanceOf('Swift_Mime_SimpleHeaderSet') + ->withDependencies(['mime.headerfactory', 'properties.charset']) + + ->register('mime.qpheaderencoder') + ->asNewInstanceOf('Swift_Mime_HeaderEncoder_QpHeaderEncoder') + ->withDependencies(['mime.charstream']) + + ->register('mime.base64headerencoder') + ->asNewInstanceOf('Swift_Mime_HeaderEncoder_Base64HeaderEncoder') + ->withDependencies(['mime.charstream']) + + ->register('mime.charstream') + ->asNewInstanceOf('Swift_CharacterStream_NgCharacterStream') + ->withDependencies(['mime.characterreaderfactory', 'properties.charset']) + + ->register('mime.bytecanonicalizer') + ->asSharedInstanceOf('Swift_StreamFilters_ByteArrayReplacementFilter') + ->addConstructorValue([[0x0D, 0x0A], [0x0D], [0x0A]]) + ->addConstructorValue([[0x0A], [0x0A], [0x0D, 0x0A]]) + + ->register('mime.characterreaderfactory') + ->asSharedInstanceOf('Swift_CharacterReaderFactory_SimpleCharacterReaderFactory') + + ->register('mime.textcontentencoder') + ->asAliasOf('mime.qpcontentencoder') + + ->register('mime.safeqpcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder') + ->withDependencies(['mime.charstream', 'mime.bytecanonicalizer']) + + ->register('mime.rawcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_RawContentEncoder') + + ->register('mime.nativeqpcontentencoder') + ->withDependencies(['properties.charset']) + ->asNewInstanceOf('Swift_Mime_ContentEncoder_NativeQpContentEncoder') + + ->register('mime.qpcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoderProxy') + ->withDependencies(['mime.safeqpcontentencoder', 'mime.nativeqpcontentencoder', 'properties.charset']) + + ->register('mime.7bitcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_PlainContentEncoder') + ->addConstructorValue('7bit') + ->addConstructorValue(true) + + ->register('mime.8bitcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_PlainContentEncoder') + ->addConstructorValue('8bit') + ->addConstructorValue(true) + + ->register('mime.base64contentencoder') + ->asSharedInstanceOf('Swift_Mime_ContentEncoder_Base64ContentEncoder') + + ->register('mime.rfc2231encoder') + ->asNewInstanceOf('Swift_Encoder_Rfc2231Encoder') + ->withDependencies(['mime.charstream']) +; + +unset($swift_mime_types); diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php new file mode 100644 index 0000000..34a63c7 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php @@ -0,0 +1,97 @@ +<?php + +Swift_DependencyContainer::getInstance() + ->register('transport.localdomain') + // As SERVER_NAME can come from the user in certain configurations, check that + // it does not contain forbidden characters (see RFC 952 and RFC 2181). Use + // preg_replace() instead of preg_match() to prevent DoS attacks with long host names. + ->asValue(!empty($_SERVER['SERVER_NAME']) && '' === preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $_SERVER['SERVER_NAME']) ? trim($_SERVER['SERVER_NAME'], '[]') : '127.0.0.1') + + ->register('transport.smtp') + ->asNewInstanceOf('Swift_Transport_EsmtpTransport') + ->withDependencies([ + 'transport.buffer', + 'transport.smtphandlers', + 'transport.eventdispatcher', + 'transport.localdomain', + 'address.idnaddressencoder', + ]) + + ->register('transport.sendmail') + ->asNewInstanceOf('Swift_Transport_SendmailTransport') + ->withDependencies([ + 'transport.buffer', + 'transport.eventdispatcher', + 'transport.localdomain', + ]) + + ->register('transport.loadbalanced') + ->asNewInstanceOf('Swift_Transport_LoadBalancedTransport') + + ->register('transport.failover') + ->asNewInstanceOf('Swift_Transport_FailoverTransport') + + ->register('transport.spool') + ->asNewInstanceOf('Swift_Transport_SpoolTransport') + ->withDependencies(['transport.eventdispatcher']) + + ->register('transport.null') + ->asNewInstanceOf('Swift_Transport_NullTransport') + ->withDependencies(['transport.eventdispatcher']) + + ->register('transport.buffer') + ->asNewInstanceOf('Swift_Transport_StreamBuffer') + ->withDependencies(['transport.replacementfactory']) + + ->register('transport.smtphandlers') + ->asArray() + ->withDependencies(['transport.authhandler']) + + ->register('transport.authhandler') + ->asNewInstanceOf('Swift_Transport_Esmtp_AuthHandler') + ->withDependencies(['transport.authhandlers']) + + ->register('transport.authhandlers') + ->asArray() + ->withDependencies([ + 'transport.crammd5auth', + 'transport.loginauth', + 'transport.plainauth', + 'transport.ntlmauth', + 'transport.xoauth2auth', + ]) + + ->register('transport.smtputf8handler') + ->asNewInstanceOf('Swift_Transport_Esmtp_SmtpUtf8Handler') + + ->register('transport.8bitmimehandler') + ->asNewInstanceOf('Swift_Transport_Esmtp_EightBitMimeHandler') + ->addConstructorValue('8BITMIME') + + ->register('transport.crammd5auth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_CramMd5Authenticator') + + ->register('transport.loginauth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_LoginAuthenticator') + + ->register('transport.plainauth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_PlainAuthenticator') + + ->register('transport.xoauth2auth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_XOAuth2Authenticator') + + ->register('transport.ntlmauth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_NTLMAuthenticator') + + ->register('transport.eventdispatcher') + ->asNewInstanceOf('Swift_Events_SimpleEventDispatcher') + + ->register('transport.replacementfactory') + ->asSharedInstanceOf('Swift_StreamFilters_StringReplacementFilterFactory') + + ->register('address.idnaddressencoder') + ->asNewInstanceOf('Swift_AddressEncoder_IdnAddressEncoder') + + ->register('address.utf8addressencoder') + ->asNewInstanceOf('Swift_AddressEncoder_Utf8AddressEncoder') +; diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/mime_types.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/mime_types.php new file mode 100644 index 0000000..72c6fd2 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/mime_types.php @@ -0,0 +1,1007 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * autogenerated using https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types + * and https://raw.github.com/minad/mimemagic/master/script/freedesktop.org.xml + */ + +/* + * List of MIME type automatically detected in Swift Mailer. + */ + +// You may add or take away what you like (lowercase required) + +$swift_mime_types = [ + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gpp', + '7z' => 'application/x-7z-compressed', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/x-aac', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/pkix-attr-cert', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'apk' => 'application/vnd.android.package-archive', + 'appcache' => 'text/cache-manifest', + 'apr' => 'application/vnd.lotus-approach', + 'aps' => 'application/postscript', + 'arc' => 'application/x-freearc', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/basic', + 'avi' => 'video/x-msvideo', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azw' => 'application/vnd.amazon.ebook', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'btif' => 'image/prs.btif', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/java-vm', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'csh' => 'application/x-csh', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/x-msdownload', + 'dmg' => 'application/x-apple-diskimage', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.document.macroenabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dra' => 'audio/vnd.dra', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'application/x-msmetafile', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/x-msdownload', + 'exi' => 'application/exi', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/x-f4v', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'geo' => 'application/vnd.dynageo', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/x-gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hdf' => 'application/x-hdf', + 'hh' => 'text/x-c', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'java' => 'text/x-java-source', + 'jisp' => 'application/vnd.jisp', + 'jlt' => 'application/vnd.hp-jlyt', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jpm' => 'video/jpm', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'jsonml' => 'application/jsonml+json', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'lha' => 'application/x-lzh-compressed', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/x-lzh-compressed', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm1v' => 'video/mpeg', + 'm21' => 'application/mp21', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'audio/x-mpegurl', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/mp4', + 'm4u' => 'video/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'mar' => 'application/octet-stream', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp21' => 'application/mp21', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msl' => 'application/vnd.mobius.msl', + 'msty' => 'application/vnd.muvee.style', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'ntf' => 'application/vnd.nitf', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obj' => 'application/x-tgif', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'org' => 'application/vnd.lotus-organizer', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'application/x-font-otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p10' => 'application/pkcs10', + 'p12' => 'application/x-pkcs12', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/vnd.palm', + 'pdf' => 'application/pdf', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp-encrypted', + 'php' => 'application/x-php', + 'php3' => 'application/x-php', + 'php4' => 'application/x-php', + 'php5' => 'application/x-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'application/x-mobipocket-ebook', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'image/vnd.adobe.photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-pn-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'application/vnd.rn-realmedia', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsd' => 'application/rsd+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'rtx' => 'text/richtext', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shf' => 'application/shf+xml', + 'sid' => 'image/x-mrsid-image', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil+xml', + 'smil' => 'application/smil+xml', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'application/vnd.ms-pki.stl', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tga' => 'image/x-tga', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tmo' => 'application/vnd.tmobile-livetv', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trm' => 'application/x-msterminal', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'application/x-font-ttf', + 'ttf' => 'application/x-font-ttf', + 'ttl' => 'text/turtle', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u32' => 'application/x-authorware-bin', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webm' => 'video/webm', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgt' => 'application/widget', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'application/x-msmetafile', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'application/font-woff', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x32' => 'application/x-authorware-bin', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+binary', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d+vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/vnd.adobe.xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/x-xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + '123' => 'application/vnd.lotus-1-2-3', +]; diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/preferences.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/preferences.php new file mode 100644 index 0000000..27b7065 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/preferences.php @@ -0,0 +1,19 @@ +<?php + +/****************************************************************************/ +/* */ +/* YOU MAY WISH TO MODIFY OR REMOVE THE FOLLOWING LINES WHICH SET DEFAULTS */ +/* */ +/****************************************************************************/ + +$preferences = Swift_Preferences::getInstance(); + +// Sets the default charset so that setCharset() is not needed elsewhere +$preferences->setCharset('utf-8'); + +// Without these lines the default caching mechanism is "array" but this uses a lot of memory. +// If possible, use a disk cache to enable attaching large attachments etc. +// You can override the default temporary directory by setting the TMPDIR environment variable. +if (@is_writable($tmpDir = sys_get_temp_dir())) { + $preferences->setTempDir($tmpDir)->setCacheType('disk'); +} diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/swift_required.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/swift_required.php new file mode 100644 index 0000000..d696056 --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/swift_required.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of SwiftMailer. + * (c) 2004-2009 Chris Corbyn + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +require __DIR__.'/classes/Swift.php'; + +Swift::registerAutoload(function () { + // Load in dependency maps + require __DIR__.'/dependency_maps/cache_deps.php'; + require __DIR__.'/dependency_maps/mime_deps.php'; + require __DIR__.'/dependency_maps/message_deps.php'; + require __DIR__.'/dependency_maps/transport_deps.php'; + + // Load in global library preferences + require __DIR__.'/preferences.php'; +}); diff --git a/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/swiftmailer_generate_mimes_config.php b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/swiftmailer_generate_mimes_config.php new file mode 100644 index 0000000..ad8fd2a --- /dev/null +++ b/php/libraries/composer/vendor/swiftmailer/swiftmailer/lib/swiftmailer_generate_mimes_config.php @@ -0,0 +1,182 @@ +#!/usr/bin/php + +<?php +\define('APACHE_MIME_TYPES_URL', 'https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types'); +\define('FREEDESKTOP_XML_URL', 'https://raw.github.com/minad/mimemagic/master/script/freedesktop.org.xml'); + +function generateUpToDateMimeArray() +{ + $preamble = "<?php\n\n"; + $preamble .= "/*\n"; + $preamble .= " * This file is part of SwiftMailer.\n"; + $preamble .= " * (c) 2004-2009 Chris Corbyn\n *\n"; + $preamble .= " * For the full copyright and license information, please view the LICENSE\n"; + $preamble .= " * file that was distributed with this source code.\n *\n"; + $preamble .= " * autogenerated using https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types\n"; + $preamble .= " * and https://raw.github.com/minad/mimemagic/master/script/freedesktop.org.xml\n"; + $preamble .= " */\n\n"; + $preamble .= "/*\n"; + $preamble .= " * List of MIME type automatically detected in Swift Mailer.\n"; + $preamble .= " */\n\n"; + $preamble .= "// You may add or take away what you like (lowercase required)\n\n"; + + // get current mime types files + $mime_types = @file_get_contents(APACHE_MIME_TYPES_URL); + $mime_xml = @file_get_contents(FREEDESKTOP_XML_URL); + + // prepare valid mime types + $valid_mime_types = []; + + // split mime type and extensions eg. "video/x-matroska mkv mk3d mks" + if (false !== preg_match_all('/^#?([a-z0-9\-\+\/\.]+)[\t]+(.*)$/miu', $mime_types, $matches)) { + // collection of predefined mimetypes (bugfix for wrong resolved or missing mime types) + $valid_mime_types_preset = [ + 'php' => 'application/x-php', + 'php3' => 'application/x-php', + 'php4' => 'application/x-php', + 'php5' => 'application/x-php', + 'zip' => 'application/zip', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'css' => 'text/css', + 'js' => 'text/javascript', + 'txt' => 'text/plain', + 'aif' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'avi' => 'video/avi', + 'bmp' => 'image/bmp', + 'bz2' => 'application/x-bz2', + 'csv' => 'text/csv', + 'dmg' => 'application/x-apple-diskimage', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eml' => 'message/rfc822', + 'aps' => 'application/postscript', + 'exe' => 'application/x-ms-dos-executable', + 'flv' => 'video/x-flv', + 'gz' => 'application/x-gzip', + 'hqx' => 'application/stuffit', + 'htm' => 'text/html', + 'html' => 'text/html', + 'jar' => 'application/x-java-archive', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'm3u' => 'audio/x-mpegurl', + 'm4a' => 'audio/mp4', + 'mdb' => 'application/x-msaccess', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'odg' => 'vnd.oasis.opendocument.graphics', + 'odp' => 'vnd.oasis.opendocument.presentation', + 'odt' => 'vnd.oasis.opendocument.text', + 'ods' => 'vnd.oasis.opendocument.spreadsheet', + 'ogg' => 'audio/ogg', + 'pdf' => 'application/pdf', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'ps' => 'application/postscript', + 'rar' => 'application/x-rar-compressed', + 'rtf' => 'application/rtf', + 'tar' => 'application/x-tar', + 'sit' => 'application/x-stuffit', + 'svg' => 'image/svg+xml', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'ttf' => 'application/x-font-truetype', + 'vcf' => 'text/x-vcard', + 'wav' => 'audio/wav', + 'wma' => 'audio/x-ms-wma', + 'wmv' => 'audio/x-ms-wmv', + 'xls' => 'application/vnd.ms-excel', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml' => 'application/xml', + ]; + + // wrap array for generating file + foreach ($valid_mime_types_preset as $extension => $mime_type) { + // generate array for mimetype to extension resolver (only first match) + $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; + } + + // all extensions from second match + foreach ($matches[2] as $i => $extensions) { + // explode multiple extensions from string + $extensions = explode(' ', strtolower($extensions ?? '')); + + // force array for foreach + if (!\is_array($extensions)) { + $extensions = [$extensions]; + } + + foreach ($extensions as $extension) { + // get mime type + $mime_type = $matches[1][$i]; + + // check if string length lower than 10 + if (\strlen($extension) < 10) { + if (!isset($valid_mime_types[$mime_type])) { + // generate array for mimetype to extension resolver (only first match) + $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; + } + } + } + } + } + + $xml = simplexml_load_string($mime_xml); + + foreach ($xml as $node) { + // check if there is no pattern + if (!isset($node->glob['pattern'])) { + continue; + } + + // get all matching extensions from match + foreach ((array) $node->glob['pattern'] as $extension) { + // skip none glob extensions + if (false === strpos($extension ?? '', '.')) { + continue; + } + + // remove get only last part + $extension = explode('.', strtolower($extension ?? '')); + $extension = end($extension); + } + + if (isset($node->glob['pattern'][0])) { + // mime type + $mime_type = strtolower((string) $node['type'] ?? ''); + + // get first extension + $extension = strtolower(trim($node->glob['ddpattern'][0] ?? '', '*.')); + + // skip none glob extensions and check if string length between 1 and 10 + if (false !== strpos($extension, '.') || \strlen($extension) < 1 || \strlen($extension) > 9) { + continue; + } + + // check if string length lower than 10 + if (!isset($valid_mime_types[$mime_type])) { + // generate array for mimetype to extension resolver (only first match) + $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; + } + } + } + + // full list of valid extensions only + $valid_mime_types = array_unique($valid_mime_types); + ksort($valid_mime_types); + + // combine mime types and extensions array + $output = "$preamble\$swift_mime_types = array(\n ".implode(",\n ", $valid_mime_types)."\n);"; + + // write mime_types.php config file + @file_put_contents('./mime_types.php', $output); +} + +generateUpToDateMimeArray(); diff --git a/php/libraries/composer/vendor/symfony/console/Application.php b/php/libraries/composer/vendor/symfony/console/Application.php new file mode 100644 index 0000000..bb53418 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Application.php @@ -0,0 +1,1301 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\CompleteCommand; +use Symfony\Component\Console\Command\DumpCompletionCommand; +use Symfony\Component\Console\Command\HelpCommand; +use Symfony\Component\Console\Command\LazyCommand; +use Symfony\Component\Console\Command\ListCommand; +use Symfony\Component\Console\Command\SignalableCommandInterface; +use Symfony\Component\Console\CommandLoader\CommandLoaderInterface; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\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\FormatterHelper; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Helper\ProcessHelper; +use Symfony\Component\Console\Helper\QuestionHelper; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputAwareInterface; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\SignalRegistry\SignalRegistry; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\ErrorHandler\ErrorHandler; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; +use Symfony\Contracts\Service\ResetInterface; + +/** + * An Application is the container for a collection of commands. + * + * It is the main entry point of a Console application. + * + * This class is optimized for a standard CLI environment. + * + * Usage: + * + * $app = new Application('myapp', '1.0 (stable)'); + * $app->add(new SimpleCommand()); + * $app->run(); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class Application implements ResetInterface +{ + private $commands = []; + private $wantHelps = false; + private $runningCommand; + private $name; + private $version; + private $commandLoader; + private $catchExceptions = true; + private $autoExit = true; + private $definition; + private $helperSet; + private $dispatcher; + private $terminal; + private $defaultCommand; + private $singleCommand = false; + private $initialized; + private $signalRegistry; + private $signalsToDispatchEvent = []; + + public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN') + { + $this->name = $name; + $this->version = $version; + $this->terminal = new Terminal(); + $this->defaultCommand = 'list'; + if (\defined('SIGINT') && SignalRegistry::isSupported()) { + $this->signalRegistry = new SignalRegistry(); + $this->signalsToDispatchEvent = [\SIGINT, \SIGTERM, \SIGUSR1, \SIGUSR2]; + } + } + + /** + * @final + */ + public function setDispatcher(EventDispatcherInterface $dispatcher) + { + $this->dispatcher = $dispatcher; + } + + public function setCommandLoader(CommandLoaderInterface $commandLoader) + { + $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) + { + $this->signalsToDispatchEvent = $signalsToDispatchEvent; + } + + /** + * Runs the current application. + * + * @return int 0 if everything went fine, or an error code + * + * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}. + */ + public function run(?InputInterface $input = null, ?OutputInterface $output = null) + { + if (\function_exists('putenv')) { + @putenv('LINES='.$this->terminal->getHeight()); + @putenv('COLUMNS='.$this->terminal->getWidth()); + } + + if (null === $input) { + $input = new ArgvInput(); + } + + if (null === $output) { + $output = new ConsoleOutput(); + } + + $renderException = function (\Throwable $e) use ($output) { + if ($output instanceof ConsoleOutputInterface) { + $this->renderThrowable($e, $output->getErrorOutput()); + } else { + $this->renderThrowable($e, $output); + } + }; + if ($phpHandler = set_exception_handler($renderException)) { + restore_exception_handler(); + if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) { + $errorHandler = true; + } elseif ($errorHandler = $phpHandler[0]->setExceptionHandler($renderException)) { + $phpHandler[0]->setExceptionHandler($errorHandler); + } + } + + $this->configureIO($input, $output); + + try { + $exitCode = $this->doRun($input, $output); + } catch (\Exception $e) { + if (!$this->catchExceptions) { + throw $e; + } + + $renderException($e); + + $exitCode = $e->getCode(); + if (is_numeric($exitCode)) { + $exitCode = (int) $exitCode; + if ($exitCode <= 0) { + $exitCode = 1; + } + } else { + $exitCode = 1; + } + } finally { + // if the exception handler changed, keep it + // otherwise, unregister $renderException + if (!$phpHandler) { + if (set_exception_handler($renderException) === $renderException) { + restore_exception_handler(); + } + restore_exception_handler(); + } elseif (!$errorHandler) { + $finalHandler = $phpHandler[0]->setExceptionHandler(null); + if ($finalHandler !== $renderException) { + $phpHandler[0]->setExceptionHandler($finalHandler); + } + } + } + + if ($this->autoExit) { + if ($exitCode > 255) { + $exitCode = 255; + } + + exit($exitCode); + } + + return $exitCode; + } + + /** + * Runs the current application. + * + * @return int 0 if everything went fine, or an error code + */ + public function doRun(InputInterface $input, OutputInterface $output) + { + 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 $e) { + // 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()) { + 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(); + } + + throw $e; + } + + $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); + } + + if ($command instanceof LazyCommand) { + $command = $command->getCommand(); + } + + $this->runningCommand = $command; + $exitCode = $this->doRunCommand($command, $input, $output); + $this->runningCommand = null; + + return $exitCode; + } + + /** + * {@inheritdoc} + */ + public function reset() + { + } + + public function setHelperSet(HelperSet $helperSet) + { + $this->helperSet = $helperSet; + } + + /** + * Get the helper set associated with the command. + * + * @return HelperSet + */ + public function getHelperSet() + { + if (!$this->helperSet) { + $this->helperSet = $this->getDefaultHelperSet(); + } + + return $this->helperSet; + } + + public function setDefinition(InputDefinition $definition) + { + $this->definition = $definition; + } + + /** + * Gets the InputDefinition related to this Application. + * + * @return InputDefinition + */ + public function getDefinition() + { + if (!$this->definition) { + $this->definition = $this->getDefaultInputDefinition(); + } + + if ($this->singleCommand) { + $inputDefinition = $this->definition; + $inputDefinition->setArguments(); + + return $inputDefinition; + } + + return $this->definition; + } + + /** + * Adds suggestions to $suggestions for the current completion input (e.g. option or argument). + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ( + CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() + && 'command' === $input->getCompletionName() + ) { + $commandNames = []; + 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; + } + $commandNames[] = $command->getName(); + foreach ($command->getAliases() as $name) { + $commandNames[] = $name; + } + } + $suggestions->suggestValues(array_filter($commandNames)); + + return; + } + + if (CompletionInput::TYPE_OPTION_NAME === $input->getCompletionType()) { + $suggestions->suggestOptions($this->getDefinition()->getOptions()); + + return; + } + } + + /** + * Gets the help message. + * + * @return string + */ + public function getHelp() + { + return $this->getLongVersion(); + } + + /** + * Gets whether to catch exceptions or not during commands execution. + * + * @return bool + */ + public function areExceptionsCaught() + { + return $this->catchExceptions; + } + + /** + * Sets whether to catch exceptions or not during commands execution. + */ + public function setCatchExceptions(bool $boolean) + { + $this->catchExceptions = $boolean; + } + + /** + * Gets whether to automatically exit after a command execution or not. + * + * @return bool + */ + public function isAutoExitEnabled() + { + return $this->autoExit; + } + + /** + * Sets whether to automatically exit after a command execution or not. + */ + public function setAutoExit(bool $boolean) + { + $this->autoExit = $boolean; + } + + /** + * Gets the name of the application. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Sets the application name. + **/ + public function setName(string $name) + { + $this->name = $name; + } + + /** + * Gets the application version. + * + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * Sets the application version. + */ + public function setVersion(string $version) + { + $this->version = $version; + } + + /** + * Returns the long version of the application. + * + * @return string + */ + public function getLongVersion() + { + if ('UNKNOWN' !== $this->getName()) { + if ('UNKNOWN' !== $this->getVersion()) { + return sprintf('%s <info>%s</info>', $this->getName(), $this->getVersion()); + } + + return $this->getName(); + } + + return 'Console Tool'; + } + + /** + * Registers a new command. + * + * @return Command + */ + public function register(string $name) + { + return $this->add(new Command($name)); + } + + /** + * Adds an array of command objects. + * + * If a Command is not enabled it will not be added. + * + * @param Command[] $commands An array of commands + */ + public function addCommands(array $commands) + { + foreach ($commands as $command) { + $this->add($command); + } + } + + /** + * Adds a command object. + * + * If a command with the same name already exists, it will be overridden. + * If the command is not enabled it will not be added. + * + * @return Command|null + */ + public function add(Command $command) + { + $this->init(); + + $command->setApplication($this); + + if (!$command->isEnabled()) { + $command->setApplication(null); + + return null; + } + + if (!$command instanceof LazyCommand) { + // Will throw if the command is not correctly initialized. + $command->getDefinition(); + } + + if (!$command->getName()) { + throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_debug_type($command))); + } + + $this->commands[$command->getName()] = $command; + + foreach ($command->getAliases() as $alias) { + $this->commands[$alias] = $command; + } + + return $command; + } + + /** + * Returns a registered command by name or alias. + * + * @return Command + * + * @throws CommandNotFoundException When given command name does not exist + */ + public function get(string $name) + { + $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. + * + * @return bool + */ + public function has(string $name) + { + $this->init(); + + return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name))); + } + + /** + * Returns an array of all unique namespaces used by currently registered commands. + * + * It does not return the global namespace which always exists. + * + * @return string[] + */ + public function getNamespaces() + { + $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. + * + * @return string + * + * @throws NamespaceNotFoundException When namespace is incorrect or ambiguous + */ + public function findNamespace(string $namespace) + { + $allNamespaces = $this->getNamespaces(); + $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*'; + $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces); + + if (empty($namespaces)) { + $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace); + + if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) { + if (1 == \count($alternatives)) { + $message .= "\n\nDid you mean this?\n "; + } else { + $message .= "\n\nDid you mean one of these?\n "; + } + + $message .= implode("\n ", $alternatives); + } + + throw new NamespaceNotFoundException($message, $alternatives); + } + + $exact = \in_array($namespace, $namespaces, true); + if (\count($namespaces) > 1 && !$exact) { + throw new NamespaceNotFoundException(sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces)); + } + + return $exact ? $namespace : reset($namespaces); + } + + /** + * Finds a command by name or alias. + * + * Contrary to get, this command tries to find the best + * match if you give it an abbreviation of a name or alias. + * + * @return Command + * + * @throws CommandNotFoundException When command name is incorrect or ambiguous + */ + public function find(string $name) + { + $this->init(); + + $aliases = []; + + foreach ($this->commands as $command) { + foreach ($command->getAliases() as $alias) { + if (!$this->has($alias)) { + $this->commands[$alias] = $command; + } + } + } + + if ($this->has($name)) { + return $this->get($name); + } + + $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands); + $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))).'[^:]*'; + $commands = preg_grep('{^'.$expr.'}', $allCommands); + + if (empty($commands)) { + $commands = preg_grep('{^'.$expr.'}i', $allCommands); + } + + // if no commands matched or we just matched namespaces + if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) { + if (false !== $pos = strrpos($name, ':')) { + // check if a namespace exists and contains commands + $this->findNamespace(substr($name, 0, $pos)); + } + + $message = sprintf('Command "%s" is not defined.', $name); + + if ($alternatives = $this->findAlternatives($name, $allCommands)) { + // remove hidden commands + $alternatives = array_filter($alternatives, function ($name) { + return !$this->get($name)->isHidden(); + }); + + if (1 == \count($alternatives)) { + $message .= "\n\nDid you mean this?\n "; + } else { + $message .= "\n\nDid you mean one of these?\n "; + } + $message .= implode("\n ", $alternatives); + } + + throw new CommandNotFoundException($message, array_values($alternatives)); + } + + // filter out aliases for commands which are already on the list + if (\count($commands) > 1) { + $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands; + $commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) { + if (!$commandList[$nameOrAlias] instanceof Command) { + $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias); + } + + $commandName = $commandList[$nameOrAlias]->getName(); + + $aliases[$nameOrAlias] = $commandName; + + return $commandName === $nameOrAlias || !\in_array($commandName, $commands); + })); + } + + if (\count($commands) > 1) { + $usableWidth = $this->terminal->getWidth() - 10; + $abbrevs = array_values($commands); + $maxLen = 0; + foreach ($abbrevs as $abbrev) { + $maxLen = max(Helper::width($abbrev), $maxLen); + } + $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) { + if ($commandList[$cmd]->isHidden()) { + unset($commands[array_search($cmd, $commands)]); + + return false; + } + + $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription(); + + return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev; + }, array_values($commands)); + + if (\count($commands) > 1) { + $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs)); + + throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $name, $suggestions), array_values($commands)); + } + } + + $command = $this->get(reset($commands)); + + if ($command->isHidden()) { + throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name)); + } + + return $command; + } + + /** + * Gets the commands (registered in the given namespace if provided). + * + * The array keys are the full names and the values the command instances. + * + * @return Command[] + */ + public function all(?string $namespace = null) + { + $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) + { + $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('<info>%s</info>', 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]++/', function ($m) { + return 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('<comment>%s</comment>', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a'))); + } + $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len)); + if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::width($title)))); + } + foreach ($lines as $line) { + $messages[] = sprintf('<error> %s %s</error>', 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('<comment>Exception trace:</comment>', 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 <info>%s:%s</info>', $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) + { + if (true === $input->hasParameterOption(['--ansi'], true)) { + $output->setDecorated(true); + } elseif (true === $input->hasParameterOption(['--no-ansi'], true)) { + $output->setDecorated(false); + } + + if (true === $input->hasParameterOption(['--no-interaction', '-n'], true)) { + $input->setInteractive(false); + } + + switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) { + case -1: + $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); + break; + case 1: + $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); + break; + case 2: + $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); + break; + case 3: + $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); + break; + default: + $shellVerbosity = 0; + break; + } + + if (true === $input->hasParameterOption(['--quiet', '-q'], true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); + $shellVerbosity = -1; + } else { + if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); + $shellVerbosity = 3; + } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); + $shellVerbosity = 2; + } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); + $shellVerbosity = 1; + } + } + + if (-1 === $shellVerbosity) { + $input->setInteractive(false); + } + + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY='.$shellVerbosity); + } + $_ENV['SHELL_VERBOSITY'] = $shellVerbosity; + $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity; + } + + /** + * Runs the current command. + * + * If an event dispatcher has been attached to the application, + * events are also dispatched during the life-cycle of the command. + * + * @return int 0 if everything went fine, or an error code + */ + protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output) + { + foreach ($command->getHelperSet() as $helper) { + if ($helper instanceof InputAwareInterface) { + $helper->setInput($input); + } + } + + if ($this->signalsToDispatchEvent) { + $commandSignals = $command instanceof SignalableCommandInterface ? $command->getSubscribedSignals() : []; + + if ($commandSignals || null !== $this->dispatcher) { + if (!$this->signalRegistry) { + throw new RuntimeException('Unable to subscribe to signal events. Make sure that the `pcntl` extension is installed and that "pcntl_*" functions are not disabled by your php.ini\'s "disable_functions" directive.'); + } + + if (Terminal::hasSttyAvailable()) { + $sttyMode = shell_exec('stty -g'); + + foreach ([\SIGINT, \SIGTERM] as $signal) { + $this->signalRegistry->register($signal, static function () use ($sttyMode) { + shell_exec('stty '.$sttyMode); + }); + } + } + } + + if (null !== $this->dispatcher) { + foreach ($this->signalsToDispatchEvent as $signal) { + $event = new ConsoleSignalEvent($command, $input, $output, $signal); + + $this->signalRegistry->register($signal, function ($signal, $hasNext) use ($event) { + $this->dispatcher->dispatch($event, ConsoleEvents::SIGNAL); + + // No more handlers, we try to simulate PHP default behavior + if (!$hasNext) { + if (!\in_array($signal, [\SIGUSR1, \SIGUSR2], true)) { + exit(0); + } + } + }); + } + } + + foreach ($commandSignals as $signal) { + $this->signalRegistry->register($signal, [$command, 'handleSignal']); + } + } + + if (null === $this->dispatcher) { + return $command->run($input, $output); + } + + // bind before the console.command event, so the listeners have access to input options/arguments + try { + $command->mergeApplicationDefinition(); + $input->bind($command->getDefinition()); + } catch (ExceptionInterface $e) { + // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition + } + + $event = new ConsoleCommandEvent($command, $input, $output); + $e = null; + + try { + $this->dispatcher->dispatch($event, ConsoleEvents::COMMAND); + + if ($event->commandShouldRun()) { + $exitCode = $command->run($input, $output); + } else { + $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED; + } + } catch (\Throwable $e) { + $event = new ConsoleErrorEvent($input, $output, $e, $command); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + $e = $event->getError(); + + if (0 === $exitCode = $event->getExitCode()) { + $e = null; + } + } + + $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode); + $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE); + + if (null !== $e) { + throw $e; + } + + return $event->getExitCode(); + } + + /** + * Gets the name of the command based on input. + * + * @return string|null + */ + protected function getCommandName(InputInterface $input) + { + return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument(); + } + + /** + * Gets the default input definition. + * + * @return InputDefinition + */ + protected function getDefaultInputDefinition() + { + 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 <info>'.$this->defaultCommand.'</info> command'), + new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'), + new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'), + new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'), + new InputOption('--ansi', '', InputOption::VALUE_NEGATABLE, 'Force (or disable --no-ansi) ANSI output', null), + new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'), + ]); + } + + /** + * Gets the default commands that should always be available. + * + * @return Command[] + */ + protected function getDefaultCommands() + { + return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()]; + } + + /** + * Gets the default helper set with the helpers that should always be available. + * + * @return HelperSet + */ + protected function getDefaultHelperSet() + { + 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. + * + * @return string + */ + public function extractNamespace(string $name, ?int $limit = null) + { + $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, function ($lev) use ($threshold) { return $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) + { + $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0]; + + if ($isSingleCommand) { + // Ensure the command exist + $this->find($commandName); + + $this->singleCommand = true; + } + + return $this; + } + + /** + * @internal + */ + public function isSingleCommand(): bool + { + return $this->singleCommand; + } + + private function splitStringByWidth(string $string, int $width): array + { + // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly. + // additionally, array_slice() is not enough as some character has doubled width. + // we need a function to split string not by character count but by string width + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return str_split($string, $width); + } + + $utf8String = mb_convert_encoding($string, 'utf8', $encoding); + $lines = []; + $line = ''; + + $offset = 0; + while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) { + $offset += \strlen($m[0]); + + foreach (preg_split('//u', $m[0]) as $char) { + // test if $char could be appended to current line + if (mb_strwidth($line.$char, 'utf8') <= $width) { + $line .= $char; + continue; + } + // if not, push current line to array and make new line + $lines[] = str_pad($line, $width); + $line = $char; + } + } + + $lines[] = \count($lines) ? str_pad($line, $width) : $line; + + mb_convert_variables($encoding, 'utf8', $lines); + + return $lines; + } + + /** + * Returns all namespaces of the command name. + * + * @return string[] + */ + private function extractAllNamespaces(string $name): array + { + // -1 as third argument is needed to skip the command short name when exploding + $parts = explode(':', $name, -1); + $namespaces = []; + + foreach ($parts as $part) { + if (\count($namespaces)) { + $namespaces[] = end($namespaces).':'.$part; + } else { + $namespaces[] = $part; + } + } + + return $namespaces; + } + + private function init() + { + if ($this->initialized) { + return; + } + $this->initialized = true; + + foreach ($this->getDefaultCommands() as $command) { + $this->add($command); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Attribute/AsCommand.php b/php/libraries/composer/vendor/symfony/console/Attribute/AsCommand.php new file mode 100644 index 0000000..b337f54 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Attribute/AsCommand.php @@ -0,0 +1,39 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +/** + * Service tag to autoconfigure commands. + */ +#[\Attribute(\Attribute::TARGET_CLASS)] +class AsCommand +{ + public function __construct( + public string $name, + public ?string $description = null, + array $aliases = [], + bool $hidden = false, + ) { + if (!$hidden && !$aliases) { + return; + } + + $name = explode('|', $name); + $name = array_merge($name, $aliases); + + if ($hidden && '' !== $name[0]) { + array_unshift($name, ''); + } + + $this->name = implode('|', $name); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/CHANGELOG.md b/php/libraries/composer/vendor/symfony/console/CHANGELOG.md new file mode 100644 index 0000000..6662dd1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/CHANGELOG.md @@ -0,0 +1,217 @@ +CHANGELOG +========= + +5.4 +--- + + * Add `TesterTrait::assertCommandIsSuccessful()` to test command + * Deprecate `HelperSet::setCommand()` and `getCommand()` without replacement + +5.3 +--- + + * Add `GithubActionReporter` to render annotations in a Github Action + * Add `InputOption::VALUE_NEGATABLE` flag to handle `--foo`/`--no-foo` options + * Add the `Command::$defaultDescription` static property and the `description` attribute + on the `console.command` tag to allow the `list` command to instantiate commands lazily + * Add option `--short` to the `list` command + * Add support for bright colors + * Add `#[AsCommand]` attribute for declaring commands on PHP 8 + * Add `Helper::width()` and `Helper::length()` + * The `--ansi` and `--no-ansi` options now default to `null`. + +5.2.0 +----- + + * Added `SingleCommandApplication::setAutoExit()` to allow testing via `CommandTester` + * added support for multiline responses to questions through `Question::setMultiline()` + and `Question::isMultiline()` + * Added `SignalRegistry` class to stack signals handlers + * Added support for signals: + * Added `Application::getSignalRegistry()` and `Application::setSignalsToDispatchEvent()` methods + * Added `SignalableCommandInterface` interface + * Added `TableCellStyle` class to customize table cell + * Removed `php ` prefix invocation from help messages. + +5.1.0 +----- + + * `Command::setHidden()` is final since Symfony 5.1 + * Add `SingleCommandApplication` + * Add `Cursor` class + +5.0.0 +----- + + * removed support for finding hidden commands using an abbreviation, use the full name instead + * removed `TableStyle::setCrossingChar()` method in favor of `TableStyle::setDefaultCrossingChar()` + * removed `TableStyle::setHorizontalBorderChar()` method in favor of `TableStyle::setDefaultCrossingChars()` + * removed `TableStyle::getHorizontalBorderChar()` method in favor of `TableStyle::getBorderChars()` + * removed `TableStyle::setVerticalBorderChar()` method in favor of `TableStyle::setVerticalBorderChars()` + * removed `TableStyle::getVerticalBorderChar()` method in favor of `TableStyle::getBorderChars()` + * removed support for returning `null` from `Command::execute()`, return `0` instead + * `ProcessHelper::run()` accepts only `array|Symfony\Component\Process\Process` for its `command` argument + * `Application::setDispatcher` accepts only `Symfony\Contracts\EventDispatcher\EventDispatcherInterface` + for its `dispatcher` argument + * renamed `Application::renderException()` and `Application::doRenderException()` + to `renderThrowable()` and `doRenderThrowable()` respectively. + +4.4.0 +----- + + * deprecated finding hidden commands using an abbreviation, use the full name instead + * added `Question::setTrimmable` default to true to allow the answer to be trimmed + * added method `minSecondsBetweenRedraws()` and `maxSecondsBetweenRedraws()` on `ProgressBar` + * `Application` implements `ResetInterface` + * marked all dispatched event classes as `@final` + * added support for displaying table horizontally + * deprecated returning `null` from `Command::execute()`, return `0` instead + * Deprecated the `Application::renderException()` and `Application::doRenderException()` methods, + use `renderThrowable()` and `doRenderThrowable()` instead. + * added support for the `NO_COLOR` env var (https://no-color.org/) + +4.3.0 +----- + + * added support for hyperlinks + * added `ProgressBar::iterate()` method that simplify updating the progress bar when iterating + * added `Question::setAutocompleterCallback()` to provide a callback function + that dynamically generates suggestions as the user types + +4.2.0 +----- + + * allowed passing commands as `[$process, 'ENV_VAR' => 'value']` to + `ProcessHelper::run()` to pass environment variables + * deprecated passing a command as a string to `ProcessHelper::run()`, + pass it the command as an array of its arguments instead + * made the `ProcessHelper` class final + * added `WrappableOutputFormatterInterface::formatAndWrap()` (implemented in `OutputFormatter`) + * added `capture_stderr_separately` option to `CommandTester::execute()` + +4.1.0 +----- + + * added option to run suggested command if command is not found and only 1 alternative is available + * added option to modify console output and print multiple modifiable sections + * added support for iterable messages in output `write` and `writeln` methods + +4.0.0 +----- + + * `OutputFormatter` throws an exception when unknown options are used + * removed `QuestionHelper::setInputStream()/getInputStream()` + * removed `Application::getTerminalWidth()/getTerminalHeight()` and + `Application::setTerminalDimensions()/getTerminalDimensions()` + * removed `ConsoleExceptionEvent` + * removed `ConsoleEvents::EXCEPTION` + +3.4.0 +----- + + * added `SHELL_VERBOSITY` env var to control verbosity + * added `CommandLoaderInterface`, `FactoryCommandLoader` and PSR-11 + `ContainerCommandLoader` for commands lazy-loading + * added a case-insensitive command name matching fallback + * added static `Command::$defaultName/getDefaultName()`, allowing for + commands to be registered at compile time in the application command loader. + Setting the `$defaultName` property avoids the need for filling the `command` + attribute on the `console.command` tag when using `AddConsoleCommandPass`. + +3.3.0 +----- + + * added `ExceptionListener` + * added `AddConsoleCommandPass` (originally in FrameworkBundle) + * [BC BREAK] `Input::getOption()` no longer returns the default value for options + with value optional explicitly passed empty + * added console.error event to catch exceptions thrown by other listeners + * deprecated console.exception event in favor of console.error + * added ability to handle `CommandNotFoundException` through the + `console.error` event + * deprecated default validation in `SymfonyQuestionHelper::ask` + +3.2.0 +------ + + * added `setInputs()` method to CommandTester for ease testing of commands expecting inputs + * added `setStream()` and `getStream()` methods to Input (implement StreamableInputInterface) + * added StreamableInputInterface + * added LockableTrait + +3.1.0 +----- + + * added truncate method to FormatterHelper + * added setColumnWidth(s) method to Table + +2.8.3 +----- + + * remove readline support from the question helper as it caused issues + +2.8.0 +----- + + * use readline for user input in the question helper when available to allow + the use of arrow keys + +2.6.0 +----- + + * added a Process helper + * added a DebugFormatter helper + +2.5.0 +----- + + * deprecated the dialog helper (use the question helper instead) + * deprecated TableHelper in favor of Table + * deprecated ProgressHelper in favor of ProgressBar + * added ConsoleLogger + * added a question helper + * added a way to set the process name of a command + * added a way to set a default command instead of `ListCommand` + +2.4.0 +----- + + * added a way to force terminal dimensions + * added a convenient method to detect verbosity level + * [BC BREAK] made descriptors use output instead of returning a string + +2.3.0 +----- + + * added multiselect support to the select dialog helper + * added Table Helper for tabular data rendering + * added support for events in `Application` + * added a way to normalize EOLs in `ApplicationTester::getDisplay()` and `CommandTester::getDisplay()` + * added a way to set the progress bar progress via the `setCurrent` method + * added support for multiple InputOption shortcuts, written as `'-a|-b|-c'` + * added two additional verbosity levels, VERBOSITY_VERY_VERBOSE and VERBOSITY_DEBUG + +2.2.0 +----- + + * added support for colorization on Windows via ConEmu + * add a method to Dialog Helper to ask for a question and hide the response + * added support for interactive selections in console (DialogHelper::select()) + * added support for autocompletion as you type in Dialog Helper + +2.1.0 +----- + + * added ConsoleOutputInterface + * added the possibility to disable a command (Command::isEnabled()) + * added suggestions when a command does not exist + * added a --raw option to the list command + * added support for STDERR in the console output class (errors are now sent + to STDERR) + * made the defaults (helper set, commands, input definition) in Application + more easily customizable + * added support for the shell even if readline is not available + * added support for process isolation in Symfony shell via + `--process-isolation` switch + * added support for `--`, which disables options parsing after that point + (tokens will be parsed as arguments) diff --git a/php/libraries/composer/vendor/symfony/console/CI/GithubActionReporter.php b/php/libraries/composer/vendor/symfony/console/CI/GithubActionReporter.php new file mode 100644 index 0000000..0657178 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/CI/GithubActionReporter.php @@ -0,0 +1,99 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CI; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Utility class for Github actions. + * + * @author Maxime Steinhausser <maxime.steinhausser@gmail.com> + */ +class GithubActionReporter +{ + private $output; + + /** + * @see https://github.com/actions/toolkit/blob/5e5e1b7aacba68a53836a34db4a288c3c1c1585b/packages/core/src/command.ts#L80-L85 + */ + private const ESCAPED_DATA = [ + '%' => '%25', + "\r" => '%0D', + "\n" => '%0A', + ]; + + /** + * @see https://github.com/actions/toolkit/blob/5e5e1b7aacba68a53836a34db4a288c3c1c1585b/packages/core/src/command.ts#L87-L94 + */ + private const ESCAPED_PROPERTIES = [ + '%' => '%25', + "\r" => '%0D', + "\n" => '%0A', + ':' => '%3A', + ',' => '%2C', + ]; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + } + + public static function isGithubActionEnvironment(): bool + { + return false !== getenv('GITHUB_ACTIONS'); + } + + /** + * Output an error using the Github annotations format. + * + * @see https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-error-message + */ + public function error(string $message, ?string $file = null, ?int $line = null, ?int $col = null): void + { + $this->log('error', $message, $file, $line, $col); + } + + /** + * Output a warning using the Github annotations format. + * + * @see https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-a-warning-message + */ + public function warning(string $message, ?string $file = null, ?int $line = null, ?int $col = null): void + { + $this->log('warning', $message, $file, $line, $col); + } + + /** + * Output a debug log using the Github annotations format. + * + * @see https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-a-debug-message + */ + public function debug(string $message, ?string $file = null, ?int $line = null, ?int $col = null): void + { + $this->log('debug', $message, $file, $line, $col); + } + + private function log(string $type, string $message, ?string $file = null, ?int $line = null, ?int $col = null): void + { + // Some values must be encoded. + $message = strtr($message, self::ESCAPED_DATA); + + if (!$file) { + // No file provided, output the message solely: + $this->output->writeln(sprintf('::%s::%s', $type, $message)); + + return; + } + + $this->output->writeln(sprintf('::%s file=%s,line=%s,col=%s::%s', $type, strtr($file, self::ESCAPED_PROPERTIES), strtr($line ?? 1, self::ESCAPED_PROPERTIES), strtr($col ?? 0, self::ESCAPED_PROPERTIES), $message)); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Color.php b/php/libraries/composer/vendor/symfony/console/Color.php new file mode 100644 index 0000000..22a4ce9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Color.php @@ -0,0 +1,180 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Fabien Potencier <fabien@symfony.com> + */ +final class Color +{ + private const COLORS = [ + 'black' => 0, + 'red' => 1, + 'green' => 2, + 'yellow' => 3, + 'blue' => 4, + 'magenta' => 5, + 'cyan' => 6, + 'white' => 7, + 'default' => 9, + ]; + + private const BRIGHT_COLORS = [ + 'gray' => 0, + 'bright-red' => 1, + 'bright-green' => 2, + 'bright-yellow' => 3, + 'bright-blue' => 4, + 'bright-magenta' => 5, + 'bright-cyan' => 6, + 'bright-white' => 7, + ]; + + private const AVAILABLE_OPTIONS = [ + 'bold' => ['set' => 1, 'unset' => 22], + 'underscore' => ['set' => 4, 'unset' => 24], + 'blink' => ['set' => 5, 'unset' => 25], + 'reverse' => ['set' => 7, 'unset' => 27], + 'conceal' => ['set' => 8, 'unset' => 28], + ]; + + private $foreground; + private $background; + private $options = []; + + public function __construct(string $foreground = '', string $background = '', array $options = []) + { + $this->foreground = $this->parseColor($foreground); + $this->background = $this->parseColor($background, true); + + foreach ($options as $option) { + if (!isset(self::AVAILABLE_OPTIONS[$option])) { + throw new InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s).', $option, implode(', ', array_keys(self::AVAILABLE_OPTIONS)))); + } + + $this->options[$option] = self::AVAILABLE_OPTIONS[$option]; + } + } + + public function apply(string $text): string + { + return $this->set().$text.$this->unset(); + } + + public function set(): string + { + $setCodes = []; + if ('' !== $this->foreground) { + $setCodes[] = $this->foreground; + } + if ('' !== $this->background) { + $setCodes[] = $this->background; + } + foreach ($this->options as $option) { + $setCodes[] = $option['set']; + } + if (0 === \count($setCodes)) { + return ''; + } + + return sprintf("\033[%sm", implode(';', $setCodes)); + } + + public function unset(): string + { + $unsetCodes = []; + if ('' !== $this->foreground) { + $unsetCodes[] = 39; + } + if ('' !== $this->background) { + $unsetCodes[] = 49; + } + foreach ($this->options as $option) { + $unsetCodes[] = $option['unset']; + } + if (0 === \count($unsetCodes)) { + return ''; + } + + return sprintf("\033[%sm", implode(';', $unsetCodes)); + } + + private function parseColor(string $color, bool $background = false): string + { + if ('' === $color) { + return ''; + } + + if ('#' === $color[0]) { + $color = substr($color, 1); + + if (3 === \strlen($color)) { + $color = $color[0].$color[0].$color[1].$color[1].$color[2].$color[2]; + } + + if (6 !== \strlen($color)) { + throw new InvalidArgumentException(sprintf('Invalid "%s" color.', $color)); + } + + return ($background ? '4' : '3').$this->convertHexColorToAnsi(hexdec($color)); + } + + if (isset(self::COLORS[$color])) { + return ($background ? '4' : '3').self::COLORS[$color]; + } + + if (isset(self::BRIGHT_COLORS[$color])) { + return ($background ? '10' : '9').self::BRIGHT_COLORS[$color]; + } + + throw new InvalidArgumentException(sprintf('Invalid "%s" color; expected one of (%s).', $color, implode(', ', array_merge(array_keys(self::COLORS), array_keys(self::BRIGHT_COLORS))))); + } + + private function convertHexColorToAnsi(int $color): string + { + $r = ($color >> 16) & 255; + $g = ($color >> 8) & 255; + $b = $color & 255; + + // see https://github.com/termstandard/colors/ for more information about true color support + if ('truecolor' !== getenv('COLORTERM')) { + return (string) $this->degradeHexColorToAnsi($r, $g, $b); + } + + return sprintf('8;2;%d;%d;%d', $r, $g, $b); + } + + private function degradeHexColorToAnsi(int $r, int $g, int $b): int + { + if (0 === round($this->getSaturation($r, $g, $b) / 50)) { + return 0; + } + + return (round($b / 255) << 2) | (round($g / 255) << 1) | round($r / 255); + } + + private function getSaturation(int $r, int $g, int $b): int + { + $r = $r / 255; + $g = $g / 255; + $b = $b / 255; + $v = max($r, $g, $b); + + if (0 === $diff = $v - min($r, $g, $b)) { + return 0; + } + + return (int) $diff * 100 / $v; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/Command.php b/php/libraries/composer/vendor/symfony/console/Command/Command.php new file mode 100644 index 0000000..d181036 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/Command.php @@ -0,0 +1,710 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Base class for all commands. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class Command +{ + // see https://tldp.org/LDP/abs/html/exitcodes.html + public const SUCCESS = 0; + public const FAILURE = 1; + public const INVALID = 2; + + /** + * @var string|null The default command name + */ + protected static $defaultName; + + /** + * @var string|null The default command description + */ + protected static $defaultDescription; + + private $application; + private $name; + private $processTitle; + private $aliases = []; + private $definition; + private $hidden = false; + private $help = ''; + private $description = ''; + private $fullDefinition; + private $ignoreValidationErrors = false; + private $code; + private $synopsis = []; + private $usages = []; + private $helperSet; + + /** + * @return string|null + */ + public static function getDefaultName() + { + $class = static::class; + + if (\PHP_VERSION_ID >= 80000 && $attribute = (new \ReflectionClass($class))->getAttributes(AsCommand::class)) { + return $attribute[0]->newInstance()->name; + } + + $r = new \ReflectionProperty($class, 'defaultName'); + + return $class === $r->class ? static::$defaultName : null; + } + + public static function getDefaultDescription(): ?string + { + $class = static::class; + + if (\PHP_VERSION_ID >= 80000 && $attribute = (new \ReflectionClass($class))->getAttributes(AsCommand::class)) { + return $attribute[0]->newInstance()->description; + } + + $r = new \ReflectionProperty($class, 'defaultDescription'); + + return $class === $r->class ? static::$defaultDescription : null; + } + + /** + * @param string|null $name The name of the command; passing null means it must be set in configure() + * + * @throws LogicException When the command name is empty + */ + public function __construct(?string $name = null) + { + $this->definition = new InputDefinition(); + + if (null === $name && null !== $name = static::getDefaultName()) { + $aliases = explode('|', $name); + + if ('' === $name = array_shift($aliases)) { + $this->setHidden(true); + $name = array_shift($aliases); + } + + $this->setAliases($aliases); + } + + if (null !== $name) { + $this->setName($name); + } + + if ('' === $this->description) { + $this->setDescription(static::getDefaultDescription() ?? ''); + } + + $this->configure(); + } + + /** + * Ignores validation errors. + * + * This is mainly useful for the help command. + */ + public function ignoreValidationErrors() + { + $this->ignoreValidationErrors = true; + } + + public function setApplication(?Application $application = null) + { + $this->application = $application; + if ($application) { + $this->setHelperSet($application->getHelperSet()); + } else { + $this->helperSet = null; + } + + $this->fullDefinition = null; + } + + public function setHelperSet(HelperSet $helperSet) + { + $this->helperSet = $helperSet; + } + + /** + * Gets the helper set. + * + * @return HelperSet|null + */ + public function getHelperSet() + { + return $this->helperSet; + } + + /** + * Gets the application instance for this command. + * + * @return Application|null + */ + public function getApplication() + { + return $this->application; + } + + /** + * Checks whether the command is enabled or not in the current environment. + * + * Override this to check for x or y and return false if the command cannot + * run properly under the current conditions. + * + * @return bool + */ + public function isEnabled() + { + return true; + } + + /** + * Configures the current command. + */ + protected function configure() + { + } + + /** + * Executes the current command. + * + * This method is not abstract because you can use this class + * as a concrete class. In this case, instead of defining the + * execute() method, you set the code to execute by passing + * a Closure to the setCode() method. + * + * @return int 0 if everything went fine, or an exit code + * + * @throws LogicException When this abstract method is not implemented + * + * @see setCode() + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + throw new LogicException('You must override the execute() method in the concrete command class.'); + } + + /** + * Interacts with the user. + * + * This method is executed before the InputDefinition is validated. + * This means that this is the only place where the command can + * interactively ask for values of missing required arguments. + */ + protected function interact(InputInterface $input, OutputInterface $output) + { + } + + /** + * Initializes the command after the input has been bound and before the input + * is validated. + * + * This is mainly useful when a lot of commands extends one main command + * where some things need to be initialized based on the input arguments and options. + * + * @see InputInterface::bind() + * @see InputInterface::validate() + */ + protected function initialize(InputInterface $input, OutputInterface $output) + { + } + + /** + * Runs the command. + * + * The code to execute is either defined directly with the + * setCode() method or by overriding the execute() method + * in a sub-class. + * + * @return int The command exit code + * + * @throws ExceptionInterface When input binding fails. Bypass this by calling {@link ignoreValidationErrors()}. + * + * @see setCode() + * @see execute() + */ + public function run(InputInterface $input, OutputInterface $output) + { + // add the application arguments and options + $this->mergeApplicationDefinition(); + + // bind the input against the command specific arguments/options + try { + $input->bind($this->getDefinition()); + } catch (ExceptionInterface $e) { + if (!$this->ignoreValidationErrors) { + throw $e; + } + } + + $this->initialize($input, $output); + + if (null !== $this->processTitle) { + if (\function_exists('cli_set_process_title')) { + if (!@cli_set_process_title($this->processTitle)) { + if ('Darwin' === \PHP_OS) { + $output->writeln('<comment>Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.</comment>', OutputInterface::VERBOSITY_VERY_VERBOSE); + } else { + cli_set_process_title($this->processTitle); + } + } + } elseif (\function_exists('setproctitle')) { + setproctitle($this->processTitle); + } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) { + $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>'); + } + } + + if ($input->isInteractive()) { + $this->interact($input, $output); + } + + // The command name argument is often omitted when a command is executed directly with its run() method. + // It would fail the validation if we didn't make sure the command argument is present, + // since it's required by the application. + if ($input->hasArgument('command') && null === $input->getArgument('command')) { + $input->setArgument('command', $this->getName()); + } + + $input->validate(); + + if ($this->code) { + $statusCode = ($this->code)($input, $output); + } else { + $statusCode = $this->execute($input, $output); + + if (!\is_int($statusCode)) { + throw new \TypeError(sprintf('Return value of "%s::execute()" must be of the type int, "%s" returned.', static::class, get_debug_type($statusCode))); + } + } + + return is_numeric($statusCode) ? (int) $statusCode : 0; + } + + /** + * Adds suggestions to $suggestions for the current completion input (e.g. option or argument). + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + } + + /** + * Sets the code to execute when running this command. + * + * If this method is used, it overrides the code defined + * in the execute() method. + * + * @param callable $code A callable(InputInterface $input, OutputInterface $output) + * + * @return $this + * + * @throws InvalidArgumentException + * + * @see execute() + */ + public function setCode(callable $code) + { + if ($code instanceof \Closure) { + $r = new \ReflectionFunction($code); + if (null === $r->getClosureThis()) { + set_error_handler(static function () {}); + try { + if ($c = \Closure::bind($code, $this)) { + $code = $c; + } + } finally { + restore_error_handler(); + } + } + } + + $this->code = $code; + + return $this; + } + + /** + * Merges the application definition with the command definition. + * + * This method is not part of public API and should not be used directly. + * + * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments + * + * @internal + */ + public function mergeApplicationDefinition(bool $mergeArgs = true) + { + if (null === $this->application) { + return; + } + + $this->fullDefinition = new InputDefinition(); + $this->fullDefinition->setOptions($this->definition->getOptions()); + $this->fullDefinition->addOptions($this->application->getDefinition()->getOptions()); + + if ($mergeArgs) { + $this->fullDefinition->setArguments($this->application->getDefinition()->getArguments()); + $this->fullDefinition->addArguments($this->definition->getArguments()); + } else { + $this->fullDefinition->setArguments($this->definition->getArguments()); + } + } + + /** + * Sets an array of argument and option instances. + * + * @param array|InputDefinition $definition An array of argument and option instances or a definition instance + * + * @return $this + */ + public function setDefinition($definition) + { + if ($definition instanceof InputDefinition) { + $this->definition = $definition; + } else { + $this->definition->setDefinition($definition); + } + + $this->fullDefinition = null; + + return $this; + } + + /** + * Gets the InputDefinition attached to this Command. + * + * @return InputDefinition + */ + public function getDefinition() + { + return $this->fullDefinition ?? $this->getNativeDefinition(); + } + + /** + * Gets the InputDefinition to be used to create representations of this Command. + * + * Can be overridden to provide the original command representation when it would otherwise + * be changed by merging with the application InputDefinition. + * + * This method is not part of public API and should not be used directly. + * + * @return InputDefinition + */ + public function getNativeDefinition() + { + if (null === $this->definition) { + throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', static::class)); + } + + return $this->definition; + } + + /** + * Adds an argument. + * + * @param int|null $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL + * @param mixed $default The default value (for InputArgument::OPTIONAL mode only) + * + * @return $this + * + * @throws InvalidArgumentException When argument mode is not valid + */ + public function addArgument(string $name, ?int $mode = null, string $description = '', $default = null) + { + $this->definition->addArgument(new InputArgument($name, $mode, $description, $default)); + if (null !== $this->fullDefinition) { + $this->fullDefinition->addArgument(new InputArgument($name, $mode, $description, $default)); + } + + return $this; + } + + /** + * Adds an option. + * + * @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts + * @param int|null $mode The option mode: One of the InputOption::VALUE_* constants + * @param mixed $default The default value (must be null for InputOption::VALUE_NONE) + * + * @return $this + * + * @throws InvalidArgumentException If option mode is invalid or incompatible + */ + public function addOption(string $name, $shortcut = null, ?int $mode = null, string $description = '', $default = null) + { + $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default)); + if (null !== $this->fullDefinition) { + $this->fullDefinition->addOption(new InputOption($name, $shortcut, $mode, $description, $default)); + } + + return $this; + } + + /** + * Sets the name of the command. + * + * This method can set both the namespace and the name if + * you separate them by a colon (:) + * + * $command->setName('foo:bar'); + * + * @return $this + * + * @throws InvalidArgumentException When the name is invalid + */ + public function setName(string $name) + { + $this->validateName($name); + + $this->name = $name; + + return $this; + } + + /** + * Sets the process title of the command. + * + * This feature should be used only when creating a long process command, + * like a daemon. + * + * @return $this + */ + public function setProcessTitle(string $title) + { + $this->processTitle = $title; + + return $this; + } + + /** + * Returns the command name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * @param bool $hidden Whether or not the command should be hidden from the list of commands + * The default value will be true in Symfony 6.0 + * + * @return $this + * + * @final since Symfony 5.1 + */ + public function setHidden(bool $hidden /* = true */) + { + $this->hidden = $hidden; + + return $this; + } + + /** + * @return bool whether the command should be publicly shown or not + */ + public function isHidden() + { + return $this->hidden; + } + + /** + * Sets the description for the command. + * + * @return $this + */ + public function setDescription(string $description) + { + $this->description = $description; + + return $this; + } + + /** + * Returns the description for the command. + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Sets the help for the command. + * + * @return $this + */ + public function setHelp(string $help) + { + $this->help = $help; + + return $this; + } + + /** + * Returns the help for the command. + * + * @return string + */ + public function getHelp() + { + return $this->help; + } + + /** + * Returns the processed help for the command replacing the %command.name% and + * %command.full_name% patterns with the real values dynamically. + * + * @return string + */ + public function getProcessedHelp() + { + $name = $this->name; + $isSingleCommand = $this->application && $this->application->isSingleCommand(); + + $placeholders = [ + '%command.name%', + '%command.full_name%', + ]; + $replacements = [ + $name, + $isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name, + ]; + + return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription()); + } + + /** + * Sets the aliases for the command. + * + * @param string[] $aliases An array of aliases for the command + * + * @return $this + * + * @throws InvalidArgumentException When an alias is invalid + */ + public function setAliases(iterable $aliases) + { + $list = []; + + foreach ($aliases as $alias) { + $this->validateName($alias); + $list[] = $alias; + } + + $this->aliases = \is_array($aliases) ? $aliases : $list; + + return $this; + } + + /** + * Returns the aliases for the command. + * + * @return array + */ + public function getAliases() + { + return $this->aliases; + } + + /** + * Returns the synopsis for the command. + * + * @param bool $short Whether to show the short version of the synopsis (with options folded) or not + * + * @return string + */ + public function getSynopsis(bool $short = false) + { + $key = $short ? 'short' : 'long'; + + if (!isset($this->synopsis[$key])) { + $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short))); + } + + return $this->synopsis[$key]; + } + + /** + * Add a command usage example, it'll be prefixed with the command name. + * + * @return $this + */ + public function addUsage(string $usage) + { + if (!str_starts_with($usage, $this->name)) { + $usage = sprintf('%s %s', $this->name, $usage); + } + + $this->usages[] = $usage; + + return $this; + } + + /** + * Returns alternative usages of the command. + * + * @return array + */ + public function getUsages() + { + return $this->usages; + } + + /** + * Gets a helper instance by name. + * + * @return mixed + * + * @throws LogicException if no HelperSet is defined + * @throws InvalidArgumentException if the helper is not defined + */ + public function getHelper(string $name) + { + if (null === $this->helperSet) { + throw new LogicException(sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', $name)); + } + + return $this->helperSet->get($name); + } + + /** + * Validates a command name. + * + * It must be non-empty and parts can optionally be separated by ":". + * + * @throws InvalidArgumentException When the name is invalid + */ + private function validateName(string $name) + { + if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) { + throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name)); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/CompleteCommand.php b/php/libraries/composer/vendor/symfony/console/Command/CompleteCommand.php new file mode 100644 index 0000000..0e35143 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/CompleteCommand.php @@ -0,0 +1,205 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Output\BashCompletionOutput; +use Symfony\Component\Console\Completion\Output\CompletionOutputInterface; +use Symfony\Component\Console\Exception\CommandNotFoundException; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Responsible for providing the values to the shell completion. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +final class CompleteCommand extends Command +{ + protected static $defaultName = '|_complete'; + protected static $defaultDescription = 'Internal command to provide shell completion suggestions'; + + private $completionOutputs; + + private $isDebug = false; + + /** + * @param array<string, class-string<CompletionOutputInterface>> $completionOutputs A list of additional completion outputs, with shell name as key and FQCN as value + */ + public function __construct(array $completionOutputs = []) + { + // must be set before the parent constructor, as the property value is used in configure() + $this->completionOutputs = $completionOutputs + ['bash' => BashCompletionOutput::class]; + + parent::__construct(); + } + + protected function configure(): void + { + $this + ->addOption('shell', 's', InputOption::VALUE_REQUIRED, 'The shell type ("'.implode('", "', array_keys($this->completionOutputs)).'")') + ->addOption('input', 'i', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'An array of input tokens (e.g. COMP_WORDS or argv)') + ->addOption('current', 'c', InputOption::VALUE_REQUIRED, 'The index of the "input" array that the cursor is in (e.g. COMP_CWORD)') + ->addOption('symfony', 'S', InputOption::VALUE_REQUIRED, 'The version of the completion script') + ; + } + + protected function initialize(InputInterface $input, OutputInterface $output) + { + $this->isDebug = filter_var(getenv('SYMFONY_COMPLETION_DEBUG'), \FILTER_VALIDATE_BOOLEAN); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + try { + // uncomment when a bugfix or BC break has been introduced in the shell completion scripts + // $version = $input->getOption('symfony'); + // if ($version && version_compare($version, 'x.y', '>=')) { + // $message = sprintf('Completion script version is not supported ("%s" given, ">=x.y" required).', $version); + // $this->log($message); + + // $output->writeln($message.' Install the Symfony completion script again by using the "completion" command.'); + + // return 126; + // } + + $shell = $input->getOption('shell'); + if (!$shell) { + throw new \RuntimeException('The "--shell" option must be set.'); + } + + if (!$completionOutput = $this->completionOutputs[$shell] ?? false) { + throw new \RuntimeException(sprintf('Shell completion is not supported for your shell: "%s" (supported: "%s").', $shell, implode('", "', array_keys($this->completionOutputs)))); + } + + $completionInput = $this->createCompletionInput($input); + $suggestions = new CompletionSuggestions(); + + $this->log([ + '', + '<comment>'.date('Y-m-d H:i:s').'</>', + '<info>Input:</> <comment>("|" indicates the cursor position)</>', + ' '.(string) $completionInput, + '<info>Command:</>', + ' '.(string) implode(' ', $_SERVER['argv']), + '<info>Messages:</>', + ]); + + $command = $this->findCommand($completionInput, $output); + if (null === $command) { + $this->log(' No command found, completing using the Application class.'); + + $this->getApplication()->complete($completionInput, $suggestions); + } elseif ( + $completionInput->mustSuggestArgumentValuesFor('command') + && $command->getName() !== $completionInput->getCompletionValue() + && !\in_array($completionInput->getCompletionValue(), $command->getAliases(), true) + ) { + $this->log(' No command found, completing using the Application class.'); + + // expand shortcut names ("cache:cl<TAB>") into their full name ("cache:clear") + $suggestions->suggestValues(array_filter(array_merge([$command->getName()], $command->getAliases()))); + } else { + $command->mergeApplicationDefinition(); + $completionInput->bind($command->getDefinition()); + + if (CompletionInput::TYPE_OPTION_NAME === $completionInput->getCompletionType()) { + $this->log(' Completing option names for the <comment>'.\get_class($command instanceof LazyCommand ? $command->getCommand() : $command).'</> command.'); + + $suggestions->suggestOptions($command->getDefinition()->getOptions()); + } else { + $this->log([ + ' Completing using the <comment>'.\get_class($command instanceof LazyCommand ? $command->getCommand() : $command).'</> class.', + ' Completing <comment>'.$completionInput->getCompletionType().'</> for <comment>'.$completionInput->getCompletionName().'</>', + ]); + if (null !== $compval = $completionInput->getCompletionValue()) { + $this->log(' Current value: <comment>'.$compval.'</>'); + } + + $command->complete($completionInput, $suggestions); + } + } + + /** @var CompletionOutputInterface $completionOutput */ + $completionOutput = new $completionOutput(); + + $this->log('<info>Suggestions:</>'); + if ($options = $suggestions->getOptionSuggestions()) { + $this->log(' --'.implode(' --', array_map(function ($o) { return $o->getName(); }, $options))); + } elseif ($values = $suggestions->getValueSuggestions()) { + $this->log(' '.implode(' ', $values)); + } else { + $this->log(' <comment>No suggestions were provided</>'); + } + + $completionOutput->write($suggestions, $output); + } catch (\Throwable $e) { + $this->log([ + '<error>Error!</error>', + (string) $e, + ]); + + if ($output->isDebug()) { + throw $e; + } + + return 2; + } + + return 0; + } + + private function createCompletionInput(InputInterface $input): CompletionInput + { + $currentIndex = $input->getOption('current'); + if (!$currentIndex || !ctype_digit($currentIndex)) { + throw new \RuntimeException('The "--current" option must be set and it must be an integer.'); + } + + $completionInput = CompletionInput::fromTokens($input->getOption('input'), (int) $currentIndex); + + try { + $completionInput->bind($this->getApplication()->getDefinition()); + } catch (ExceptionInterface $e) { + } + + return $completionInput; + } + + private function findCommand(CompletionInput $completionInput, OutputInterface $output): ?Command + { + try { + $inputName = $completionInput->getFirstArgument(); + if (null === $inputName) { + return null; + } + + return $this->getApplication()->find($inputName); + } catch (CommandNotFoundException $e) { + } + + return null; + } + + private function log($messages): void + { + if (!$this->isDebug) { + return; + } + + $commandName = basename($_SERVER['argv'][0]); + file_put_contents(sys_get_temp_dir().'/sf_'.$commandName.'.log', implode(\PHP_EOL, (array) $messages).\PHP_EOL, \FILE_APPEND); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/DumpCompletionCommand.php b/php/libraries/composer/vendor/symfony/console/Command/DumpCompletionCommand.php new file mode 100644 index 0000000..eaf22be --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/DumpCompletionCommand.php @@ -0,0 +1,145 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Process\Process; + +/** + * Dumps the completion script for the current shell. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +final class DumpCompletionCommand extends Command +{ + protected static $defaultName = 'completion'; + protected static $defaultDescription = 'Dump the shell completion script'; + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestArgumentValuesFor('shell')) { + $suggestions->suggestValues($this->getSupportedShells()); + } + } + + protected function configure() + { + $fullCommand = $_SERVER['PHP_SELF']; + $commandName = basename($fullCommand); + $fullCommand = @realpath($fullCommand) ?: $fullCommand; + + $this + ->setHelp(<<<EOH +The <info>%command.name%</> command dumps the shell completion script required +to use shell autocompletion (currently only bash completion is supported). + +<comment>Static installation +-------------------</> + +Dump the script to a global completion file and restart your shell: + + <info>%command.full_name% bash | sudo tee /etc/bash_completion.d/{$commandName}</> + +Or dump the script to a local file and source it: + + <info>%command.full_name% bash > completion.sh</> + + <comment># source the file whenever you use the project</> + <info>source completion.sh</> + + <comment># or add this line at the end of your "~/.bashrc" file:</> + <info>source /path/to/completion.sh</> + +<comment>Dynamic installation +--------------------</> + +Add this to the end of your shell configuration file (e.g. <info>"~/.bashrc"</>): + + <info>eval "$({$fullCommand} completion bash)"</> +EOH + ) + ->addArgument('shell', InputArgument::OPTIONAL, 'The shell type (e.g. "bash"), the value of the "$SHELL" env var will be used if this is not given') + ->addOption('debug', null, InputOption::VALUE_NONE, 'Tail the completion debug log') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $commandName = basename($_SERVER['argv'][0]); + + if ($input->getOption('debug')) { + $this->tailDebugLog($commandName, $output); + + return 0; + } + + $shell = $input->getArgument('shell') ?? self::guessShell(); + $completionFile = __DIR__.'/../Resources/completion.'.$shell; + if (!file_exists($completionFile)) { + $supportedShells = $this->getSupportedShells(); + + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + if ($shell) { + $output->writeln(sprintf('<error>Detected shell "%s", which is not supported by Symfony shell completion (supported shells: "%s").</>', $shell, implode('", "', $supportedShells))); + } else { + $output->writeln(sprintf('<error>Shell not detected, Symfony shell completion only supports "%s").</>', implode('", "', $supportedShells))); + } + + return 2; + } + + $output->write(str_replace(['{{ COMMAND_NAME }}', '{{ VERSION }}'], [$commandName, $this->getApplication()->getVersion()], file_get_contents($completionFile))); + + return 0; + } + + private static function guessShell(): string + { + return basename($_SERVER['SHELL'] ?? ''); + } + + private function tailDebugLog(string $commandName, OutputInterface $output): void + { + $debugFile = sys_get_temp_dir().'/sf_'.$commandName.'.log'; + if (!file_exists($debugFile)) { + touch($debugFile); + } + $process = new Process(['tail', '-f', $debugFile], null, null, null, 0); + $process->run(function (string $type, string $line) use ($output): void { + $output->write($line); + }); + } + + /** + * @return string[] + */ + private function getSupportedShells(): array + { + $shells = []; + + foreach (new \DirectoryIterator(__DIR__.'/../Resources/') as $file) { + if (str_starts_with($file->getBasename(), 'completion.') && $file->isFile()) { + $shells[] = $file->getExtension(); + } + } + + return $shells; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/HelpCommand.php b/php/libraries/composer/vendor/symfony/console/Command/HelpCommand.php new file mode 100644 index 0000000..c66ef46 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/HelpCommand.php @@ -0,0 +1,101 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Descriptor\ApplicationDescription; +use Symfony\Component\Console\Helper\DescriptorHelper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * HelpCommand displays the help for a given command. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class HelpCommand extends Command +{ + private $command; + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this->ignoreValidationErrors(); + + $this + ->setName('help') + ->setDefinition([ + new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help'), + new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'), + new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'), + ]) + ->setDescription('Display help for a command') + ->setHelp(<<<'EOF' +The <info>%command.name%</info> command displays help for a given command: + + <info>%command.full_name% list</info> + +You can also output the help in other formats by using the <comment>--format</comment> option: + + <info>%command.full_name% --format=xml list</info> + +To display the list of available commands, please use the <info>list</info> command. +EOF + ) + ; + } + + public function setCommand(Command $command) + { + $this->command = $command; + } + + /** + * {@inheritdoc} + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + if (null === $this->command) { + $this->command = $this->getApplication()->find($input->getArgument('command_name')); + } + + $helper = new DescriptorHelper(); + $helper->describe($output, $this->command, [ + 'format' => $input->getOption('format'), + 'raw_text' => $input->getOption('raw'), + ]); + + $this->command = null; + + return 0; + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestArgumentValuesFor('command_name')) { + $descriptor = new ApplicationDescription($this->getApplication()); + $suggestions->suggestValues(array_keys($descriptor->getCommands())); + + return; + } + + if ($input->mustSuggestOptionValuesFor('format')) { + $helper = new DescriptorHelper(); + $suggestions->suggestValues($helper->getFormats()); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/LazyCommand.php b/php/libraries/composer/vendor/symfony/console/Command/LazyCommand.php new file mode 100644 index 0000000..302a080 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/LazyCommand.php @@ -0,0 +1,218 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Nicolas Grekas <p@tchwork.com> + */ +final class LazyCommand extends Command +{ + private $command; + private $isEnabled; + + public function __construct(string $name, array $aliases, string $description, bool $isHidden, \Closure $commandFactory, ?bool $isEnabled = true) + { + $this->setName($name) + ->setAliases($aliases) + ->setHidden($isHidden) + ->setDescription($description); + + $this->command = $commandFactory; + $this->isEnabled = $isEnabled; + } + + public function ignoreValidationErrors(): void + { + $this->getCommand()->ignoreValidationErrors(); + } + + public function setApplication(?Application $application = null): void + { + if ($this->command instanceof parent) { + $this->command->setApplication($application); + } + + parent::setApplication($application); + } + + public function setHelperSet(HelperSet $helperSet): void + { + if ($this->command instanceof parent) { + $this->command->setHelperSet($helperSet); + } + + parent::setHelperSet($helperSet); + } + + public function isEnabled(): bool + { + return $this->isEnabled ?? $this->getCommand()->isEnabled(); + } + + public function run(InputInterface $input, OutputInterface $output): int + { + return $this->getCommand()->run($input, $output); + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + $this->getCommand()->complete($input, $suggestions); + } + + /** + * @return $this + */ + public function setCode(callable $code): self + { + $this->getCommand()->setCode($code); + + return $this; + } + + /** + * @internal + */ + public function mergeApplicationDefinition(bool $mergeArgs = true): void + { + $this->getCommand()->mergeApplicationDefinition($mergeArgs); + } + + /** + * @return $this + */ + public function setDefinition($definition): self + { + $this->getCommand()->setDefinition($definition); + + return $this; + } + + public function getDefinition(): InputDefinition + { + return $this->getCommand()->getDefinition(); + } + + public function getNativeDefinition(): InputDefinition + { + return $this->getCommand()->getNativeDefinition(); + } + + /** + * @return $this + */ + public function addArgument(string $name, ?int $mode = null, string $description = '', $default = null): self + { + $this->getCommand()->addArgument($name, $mode, $description, $default); + + return $this; + } + + /** + * @return $this + */ + public function addOption(string $name, $shortcut = null, ?int $mode = null, string $description = '', $default = null): self + { + $this->getCommand()->addOption($name, $shortcut, $mode, $description, $default); + + return $this; + } + + /** + * @return $this + */ + public function setProcessTitle(string $title): self + { + $this->getCommand()->setProcessTitle($title); + + return $this; + } + + /** + * @return $this + */ + public function setHelp(string $help): self + { + $this->getCommand()->setHelp($help); + + return $this; + } + + public function getHelp(): string + { + return $this->getCommand()->getHelp(); + } + + public function getProcessedHelp(): string + { + return $this->getCommand()->getProcessedHelp(); + } + + public function getSynopsis(bool $short = false): string + { + return $this->getCommand()->getSynopsis($short); + } + + /** + * @return $this + */ + public function addUsage(string $usage): self + { + $this->getCommand()->addUsage($usage); + + return $this; + } + + public function getUsages(): array + { + return $this->getCommand()->getUsages(); + } + + /** + * @return mixed + */ + public function getHelper(string $name) + { + return $this->getCommand()->getHelper($name); + } + + public function getCommand(): parent + { + if (!$this->command instanceof \Closure) { + return $this->command; + } + + $command = $this->command = ($this->command)(); + $command->setApplication($this->getApplication()); + + if (null !== $this->getHelperSet()) { + $command->setHelperSet($this->getHelperSet()); + } + + $command->setName($this->getName()) + ->setAliases($this->getAliases()) + ->setHidden($this->isHidden()) + ->setDescription($this->getDescription()); + + // Will throw if the command is not correctly initialized. + $command->getDefinition(); + + return $command; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/ListCommand.php b/php/libraries/composer/vendor/symfony/console/Command/ListCommand.php new file mode 100644 index 0000000..f04a4ef --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/ListCommand.php @@ -0,0 +1,95 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Descriptor\ApplicationDescription; +use Symfony\Component\Console\Helper\DescriptorHelper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * ListCommand displays the list of all available commands for the application. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ListCommand extends Command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('list') + ->setDefinition([ + new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'), + new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'), + new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'), + new InputOption('short', null, InputOption::VALUE_NONE, 'To skip describing commands\' arguments'), + ]) + ->setDescription('List commands') + ->setHelp(<<<'EOF' +The <info>%command.name%</info> command lists all commands: + + <info>%command.full_name%</info> + +You can also display the commands for a specific namespace: + + <info>%command.full_name% test</info> + +You can also output the information in other formats by using the <comment>--format</comment> option: + + <info>%command.full_name% --format=xml</info> + +It's also possible to get raw list of commands (useful for embedding command runner): + + <info>%command.full_name% --raw</info> +EOF + ) + ; + } + + /** + * {@inheritdoc} + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $helper = new DescriptorHelper(); + $helper->describe($output, $this->getApplication(), [ + 'format' => $input->getOption('format'), + 'raw_text' => $input->getOption('raw'), + 'namespace' => $input->getArgument('namespace'), + 'short' => $input->getOption('short'), + ]); + + return 0; + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestArgumentValuesFor('namespace')) { + $descriptor = new ApplicationDescription($this->getApplication()); + $suggestions->suggestValues(array_keys($descriptor->getNamespaces())); + + return; + } + + if ($input->mustSuggestOptionValuesFor('format')) { + $helper = new DescriptorHelper(); + $suggestions->suggestValues($helper->getFormats()); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/LockableTrait.php b/php/libraries/composer/vendor/symfony/console/Command/LockableTrait.php new file mode 100644 index 0000000..d21edc2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/LockableTrait.php @@ -0,0 +1,69 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Lock\LockFactory; +use Symfony\Component\Lock\LockInterface; +use Symfony\Component\Lock\Store\FlockStore; +use Symfony\Component\Lock\Store\SemaphoreStore; + +/** + * Basic lock feature for commands. + * + * @author Geoffrey Brier <geoffrey.brier@gmail.com> + */ +trait LockableTrait +{ + /** @var LockInterface|null */ + private $lock; + + /** + * Locks a command. + */ + private function lock(?string $name = null, bool $blocking = false): bool + { + if (!class_exists(SemaphoreStore::class)) { + throw new LogicException('To enable the locking feature you must install the symfony/lock component.'); + } + + if (null !== $this->lock) { + throw new LogicException('A lock is already in place.'); + } + + if (SemaphoreStore::isSupported()) { + $store = new SemaphoreStore(); + } else { + $store = new FlockStore(); + } + + $this->lock = (new LockFactory($store))->createLock($name ?: $this->getName()); + if (!$this->lock->acquire($blocking)) { + $this->lock = null; + + return false; + } + + return true; + } + + /** + * Releases the command lock if there is one. + */ + private function release() + { + if ($this->lock) { + $this->lock->release(); + $this->lock = null; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Command/SignalableCommandInterface.php b/php/libraries/composer/vendor/symfony/console/Command/SignalableCommandInterface.php new file mode 100644 index 0000000..d439728 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Command/SignalableCommandInterface.php @@ -0,0 +1,30 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +/** + * Interface for command reacting to signal. + * + * @author Grégoire Pineau <lyrixx@lyrix.info> + */ +interface SignalableCommandInterface +{ + /** + * Returns the list of signals to subscribe. + */ + public function getSubscribedSignals(): array; + + /** + * The method will be called when the application is signaled. + */ + public function handleSignal(int $signal): void; +} diff --git a/php/libraries/composer/vendor/symfony/console/CommandLoader/CommandLoaderInterface.php b/php/libraries/composer/vendor/symfony/console/CommandLoader/CommandLoaderInterface.php new file mode 100644 index 0000000..0adaf88 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/CommandLoader/CommandLoaderInterface.php @@ -0,0 +1,42 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CommandLoader; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * @author Robin Chalas <robin.chalas@gmail.com> + */ +interface CommandLoaderInterface +{ + /** + * Loads a command. + * + * @return Command + * + * @throws CommandNotFoundException + */ + public function get(string $name); + + /** + * Checks if a command exists. + * + * @return bool + */ + public function has(string $name); + + /** + * @return string[] + */ + public function getNames(); +} diff --git a/php/libraries/composer/vendor/symfony/console/CommandLoader/ContainerCommandLoader.php b/php/libraries/composer/vendor/symfony/console/CommandLoader/ContainerCommandLoader.php new file mode 100644 index 0000000..ddccb3d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/CommandLoader/ContainerCommandLoader.php @@ -0,0 +1,63 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CommandLoader; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * Loads commands from a PSR-11 container. + * + * @author Robin Chalas <robin.chalas@gmail.com> + */ +class ContainerCommandLoader implements CommandLoaderInterface +{ + private $container; + private $commandMap; + + /** + * @param array $commandMap An array with command names as keys and service ids as values + */ + public function __construct(ContainerInterface $container, array $commandMap) + { + $this->container = $container; + $this->commandMap = $commandMap; + } + + /** + * {@inheritdoc} + */ + public function get(string $name) + { + if (!$this->has($name)) { + throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); + } + + return $this->container->get($this->commandMap[$name]); + } + + /** + * {@inheritdoc} + */ + public function has(string $name) + { + return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]); + } + + /** + * {@inheritdoc} + */ + public function getNames() + { + return array_keys($this->commandMap); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/CommandLoader/FactoryCommandLoader.php b/php/libraries/composer/vendor/symfony/console/CommandLoader/FactoryCommandLoader.php new file mode 100644 index 0000000..7e2db34 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/CommandLoader/FactoryCommandLoader.php @@ -0,0 +1,62 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CommandLoader; + +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * A simple command loader using factories to instantiate commands lazily. + * + * @author Maxime Steinhausser <maxime.steinhausser@gmail.com> + */ +class FactoryCommandLoader implements CommandLoaderInterface +{ + private $factories; + + /** + * @param callable[] $factories Indexed by command names + */ + public function __construct(array $factories) + { + $this->factories = $factories; + } + + /** + * {@inheritdoc} + */ + public function has(string $name) + { + return isset($this->factories[$name]); + } + + /** + * {@inheritdoc} + */ + public function get(string $name) + { + if (!isset($this->factories[$name])) { + throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); + } + + $factory = $this->factories[$name]; + + return $factory(); + } + + /** + * {@inheritdoc} + */ + public function getNames() + { + return array_keys($this->factories); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Completion/CompletionInput.php b/php/libraries/composer/vendor/symfony/console/Completion/CompletionInput.php new file mode 100644 index 0000000..368b945 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Completion/CompletionInput.php @@ -0,0 +1,249 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion; + +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * An input specialized for shell completion. + * + * This input allows unfinished option names or values and exposes what kind of + * completion is expected. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +final class CompletionInput extends ArgvInput +{ + public const TYPE_ARGUMENT_VALUE = 'argument_value'; + public const TYPE_OPTION_VALUE = 'option_value'; + public const TYPE_OPTION_NAME = 'option_name'; + public const TYPE_NONE = 'none'; + + private $tokens; + private $currentIndex; + private $completionType; + private $completionName = null; + private $completionValue = ''; + + /** + * Converts a terminal string into tokens. + * + * This is required for shell completions without COMP_WORDS support. + */ + public static function fromString(string $inputStr, int $currentIndex): self + { + preg_match_all('/(?<=^|\s)([\'"]?)(.+?)(?<!\\\\)\1(?=$|\s)/', $inputStr, $tokens); + + return self::fromTokens($tokens[0], $currentIndex); + } + + /** + * Create an input based on an COMP_WORDS token list. + * + * @param string[] $tokens the set of split tokens (e.g. COMP_WORDS or argv) + * @param $currentIndex the index of the cursor (e.g. COMP_CWORD) + */ + public static function fromTokens(array $tokens, int $currentIndex): self + { + $input = new self($tokens); + $input->tokens = $tokens; + $input->currentIndex = $currentIndex; + + return $input; + } + + /** + * {@inheritdoc} + */ + public function bind(InputDefinition $definition): void + { + parent::bind($definition); + + $relevantToken = $this->getRelevantToken(); + if ('-' === $relevantToken[0]) { + // the current token is an input option: complete either option name or option value + [$optionToken, $optionValue] = explode('=', $relevantToken, 2) + ['', '']; + + $option = $this->getOptionFromToken($optionToken); + if (null === $option && !$this->isCursorFree()) { + $this->completionType = self::TYPE_OPTION_NAME; + $this->completionValue = $relevantToken; + + return; + } + + if (null !== $option && $option->acceptValue()) { + $this->completionType = self::TYPE_OPTION_VALUE; + $this->completionName = $option->getName(); + $this->completionValue = $optionValue ?: (!str_starts_with($optionToken, '--') ? substr($optionToken, 2) : ''); + + return; + } + } + + $previousToken = $this->tokens[$this->currentIndex - 1]; + if ('-' === $previousToken[0] && '' !== trim($previousToken, '-')) { + // check if previous option accepted a value + $previousOption = $this->getOptionFromToken($previousToken); + if (null !== $previousOption && $previousOption->acceptValue()) { + $this->completionType = self::TYPE_OPTION_VALUE; + $this->completionName = $previousOption->getName(); + $this->completionValue = $relevantToken; + + return; + } + } + + // complete argument value + $this->completionType = self::TYPE_ARGUMENT_VALUE; + + foreach ($this->definition->getArguments() as $argumentName => $argument) { + if (!isset($this->arguments[$argumentName])) { + break; + } + + $argumentValue = $this->arguments[$argumentName]; + $this->completionName = $argumentName; + if (\is_array($argumentValue)) { + $this->completionValue = $argumentValue ? $argumentValue[array_key_last($argumentValue)] : null; + } else { + $this->completionValue = $argumentValue; + } + } + + if ($this->currentIndex >= \count($this->tokens)) { + if (!isset($this->arguments[$argumentName]) || $this->definition->getArgument($argumentName)->isArray()) { + $this->completionName = $argumentName; + $this->completionValue = ''; + } else { + // we've reached the end + $this->completionType = self::TYPE_NONE; + $this->completionName = null; + $this->completionValue = ''; + } + } + } + + /** + * Returns the type of completion required. + * + * TYPE_ARGUMENT_VALUE when completing the value of an input argument + * TYPE_OPTION_VALUE when completing the value of an input option + * TYPE_OPTION_NAME when completing the name of an input option + * TYPE_NONE when nothing should be completed + * + * @return string One of self::TYPE_* constants. TYPE_OPTION_NAME and TYPE_NONE are already implemented by the Console component + */ + public function getCompletionType(): string + { + return $this->completionType; + } + + /** + * The name of the input option or argument when completing a value. + * + * @return string|null returns null when completing an option name + */ + public function getCompletionName(): ?string + { + return $this->completionName; + } + + /** + * The value already typed by the user (or empty string). + */ + public function getCompletionValue(): string + { + return $this->completionValue; + } + + public function mustSuggestOptionValuesFor(string $optionName): bool + { + return self::TYPE_OPTION_VALUE === $this->getCompletionType() && $optionName === $this->getCompletionName(); + } + + public function mustSuggestArgumentValuesFor(string $argumentName): bool + { + return self::TYPE_ARGUMENT_VALUE === $this->getCompletionType() && $argumentName === $this->getCompletionName(); + } + + protected function parseToken(string $token, bool $parseOptions): bool + { + try { + return parent::parseToken($token, $parseOptions); + } catch (RuntimeException $e) { + // suppress errors, completed input is almost never valid + } + + return $parseOptions; + } + + private function getOptionFromToken(string $optionToken): ?InputOption + { + $optionName = ltrim($optionToken, '-'); + if (!$optionName) { + return null; + } + + if ('-' === ($optionToken[1] ?? ' ')) { + // long option name + return $this->definition->hasOption($optionName) ? $this->definition->getOption($optionName) : null; + } + + // short option name + return $this->definition->hasShortcut($optionName[0]) ? $this->definition->getOptionForShortcut($optionName[0]) : null; + } + + /** + * The token of the cursor, or the last token if the cursor is at the end of the input. + */ + private function getRelevantToken(): string + { + return $this->tokens[$this->isCursorFree() ? $this->currentIndex - 1 : $this->currentIndex]; + } + + /** + * Whether the cursor is "free" (i.e. at the end of the input preceded by a space). + */ + private function isCursorFree(): bool + { + $nrOfTokens = \count($this->tokens); + if ($this->currentIndex > $nrOfTokens) { + throw new \LogicException('Current index is invalid, it must be the number of input tokens or one more.'); + } + + return $this->currentIndex >= $nrOfTokens; + } + + public function __toString() + { + $str = ''; + foreach ($this->tokens as $i => $token) { + $str .= $token; + + if ($this->currentIndex === $i) { + $str .= '|'; + } + + $str .= ' '; + } + + if ($this->currentIndex > $i) { + $str .= '|'; + } + + return rtrim($str); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Completion/CompletionSuggestions.php b/php/libraries/composer/vendor/symfony/console/Completion/CompletionSuggestions.php new file mode 100644 index 0000000..d8905e5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Completion/CompletionSuggestions.php @@ -0,0 +1,99 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion; + +use Symfony\Component\Console\Input\InputOption; + +/** + * Stores all completion suggestions for the current input. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +final class CompletionSuggestions +{ + private $valueSuggestions = []; + private $optionSuggestions = []; + + /** + * Add a suggested value for an input option or argument. + * + * @param string|Suggestion $value + * + * @return $this + */ + public function suggestValue($value): self + { + $this->valueSuggestions[] = !$value instanceof Suggestion ? new Suggestion($value) : $value; + + return $this; + } + + /** + * Add multiple suggested values at once for an input option or argument. + * + * @param list<string|Suggestion> $values + * + * @return $this + */ + public function suggestValues(array $values): self + { + foreach ($values as $value) { + $this->suggestValue($value); + } + + return $this; + } + + /** + * Add a suggestion for an input option name. + * + * @return $this + */ + public function suggestOption(InputOption $option): self + { + $this->optionSuggestions[] = $option; + + return $this; + } + + /** + * Add multiple suggestions for input option names at once. + * + * @param InputOption[] $options + * + * @return $this + */ + public function suggestOptions(array $options): self + { + foreach ($options as $option) { + $this->suggestOption($option); + } + + return $this; + } + + /** + * @return InputOption[] + */ + public function getOptionSuggestions(): array + { + return $this->optionSuggestions; + } + + /** + * @return Suggestion[] + */ + public function getValueSuggestions(): array + { + return $this->valueSuggestions; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Completion/Output/BashCompletionOutput.php b/php/libraries/composer/vendor/symfony/console/Completion/Output/BashCompletionOutput.php new file mode 100644 index 0000000..c6f76eb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Completion/Output/BashCompletionOutput.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion\Output; + +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Wouter de Jong <wouter@wouterj.nl> + */ +class BashCompletionOutput implements CompletionOutputInterface +{ + public function write(CompletionSuggestions $suggestions, OutputInterface $output): void + { + $values = $suggestions->getValueSuggestions(); + foreach ($suggestions->getOptionSuggestions() as $option) { + $values[] = '--'.$option->getName(); + if ($option->isNegatable()) { + $values[] = '--no-'.$option->getName(); + } + } + $output->writeln(implode("\n", $values)); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Completion/Output/CompletionOutputInterface.php b/php/libraries/composer/vendor/symfony/console/Completion/Output/CompletionOutputInterface.php new file mode 100644 index 0000000..659e596 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Completion/Output/CompletionOutputInterface.php @@ -0,0 +1,25 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion\Output; + +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Transforms the {@see CompletionSuggestions} object into output readable by the shell completion. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +interface CompletionOutputInterface +{ + public function write(CompletionSuggestions $suggestions, OutputInterface $output): void; +} diff --git a/php/libraries/composer/vendor/symfony/console/Completion/Suggestion.php b/php/libraries/composer/vendor/symfony/console/Completion/Suggestion.php new file mode 100644 index 0000000..6c7bc4d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Completion/Suggestion.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion; + +/** + * Represents a single suggested value. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +class Suggestion +{ + private $value; + + public function __construct(string $value) + { + $this->value = $value; + } + + public function getValue(): string + { + return $this->value; + } + + public function __toString(): string + { + return $this->getValue(); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/ConsoleEvents.php b/php/libraries/composer/vendor/symfony/console/ConsoleEvents.php new file mode 100644 index 0000000..6ae8f32 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/ConsoleEvents.php @@ -0,0 +1,72 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Event\ConsoleCommandEvent; +use Symfony\Component\Console\Event\ConsoleErrorEvent; +use Symfony\Component\Console\Event\ConsoleSignalEvent; +use Symfony\Component\Console\Event\ConsoleTerminateEvent; + +/** + * Contains all events dispatched by an Application. + * + * @author Francesco Levorato <git@flevour.net> + */ +final class ConsoleEvents +{ + /** + * The COMMAND event allows you to attach listeners before any command is + * executed by the console. It also allows you to modify the command, input and output + * before they are handed to the command. + * + * @Event("Symfony\Component\Console\Event\ConsoleCommandEvent") + */ + public const COMMAND = 'console.command'; + + /** + * The SIGNAL event allows you to perform some actions + * after the command execution was interrupted. + * + * @Event("Symfony\Component\Console\Event\ConsoleSignalEvent") + */ + public const SIGNAL = 'console.signal'; + + /** + * The TERMINATE event allows you to attach listeners after a command is + * executed by the console. + * + * @Event("Symfony\Component\Console\Event\ConsoleTerminateEvent") + */ + public const TERMINATE = 'console.terminate'; + + /** + * The ERROR event occurs when an uncaught exception or error appears. + * + * This event allows you to deal with the exception/error or + * to modify the thrown exception. + * + * @Event("Symfony\Component\Console\Event\ConsoleErrorEvent") + */ + public const ERROR = 'console.error'; + + /** + * Event aliases. + * + * These aliases can be consumed by RegisterListenersPass. + */ + public const ALIASES = [ + ConsoleCommandEvent::class => self::COMMAND, + ConsoleErrorEvent::class => self::ERROR, + ConsoleSignalEvent::class => self::SIGNAL, + ConsoleTerminateEvent::class => self::TERMINATE, + ]; +} diff --git a/php/libraries/composer/vendor/symfony/console/Cursor.php b/php/libraries/composer/vendor/symfony/console/Cursor.php new file mode 100644 index 0000000..0c4dafb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Cursor.php @@ -0,0 +1,207 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Pierre du Plessis <pdples@gmail.com> + */ +final class Cursor +{ + private $output; + private $input; + + /** + * @param resource|null $input + */ + public function __construct(OutputInterface $output, $input = null) + { + $this->output = $output; + $this->input = $input ?? (\defined('STDIN') ? \STDIN : fopen('php://input', 'r+')); + } + + /** + * @return $this + */ + public function moveUp(int $lines = 1): self + { + $this->output->write(sprintf("\x1b[%dA", $lines)); + + return $this; + } + + /** + * @return $this + */ + public function moveDown(int $lines = 1): self + { + $this->output->write(sprintf("\x1b[%dB", $lines)); + + return $this; + } + + /** + * @return $this + */ + public function moveRight(int $columns = 1): self + { + $this->output->write(sprintf("\x1b[%dC", $columns)); + + return $this; + } + + /** + * @return $this + */ + public function moveLeft(int $columns = 1): self + { + $this->output->write(sprintf("\x1b[%dD", $columns)); + + return $this; + } + + /** + * @return $this + */ + public function moveToColumn(int $column): self + { + $this->output->write(sprintf("\x1b[%dG", $column)); + + return $this; + } + + /** + * @return $this + */ + public function moveToPosition(int $column, int $row): self + { + $this->output->write(sprintf("\x1b[%d;%dH", $row + 1, $column)); + + return $this; + } + + /** + * @return $this + */ + public function savePosition(): self + { + $this->output->write("\x1b7"); + + return $this; + } + + /** + * @return $this + */ + public function restorePosition(): self + { + $this->output->write("\x1b8"); + + return $this; + } + + /** + * @return $this + */ + public function hide(): self + { + $this->output->write("\x1b[?25l"); + + return $this; + } + + /** + * @return $this + */ + public function show(): self + { + $this->output->write("\x1b[?25h\x1b[?0c"); + + return $this; + } + + /** + * Clears all the output from the current line. + * + * @return $this + */ + public function clearLine(): self + { + $this->output->write("\x1b[2K"); + + return $this; + } + + /** + * Clears all the output from the current line after the current position. + */ + public function clearLineAfter(): self + { + $this->output->write("\x1b[K"); + + return $this; + } + + /** + * Clears all the output from the cursors' current position to the end of the screen. + * + * @return $this + */ + public function clearOutput(): self + { + $this->output->write("\x1b[0J"); + + return $this; + } + + /** + * Clears the entire screen. + * + * @return $this + */ + public function clearScreen(): self + { + $this->output->write("\x1b[2J"); + + return $this; + } + + /** + * Returns the current cursor position as x,y coordinates. + */ + public function getCurrentPosition(): array + { + static $isTtySupported; + + if (null === $isTtySupported && \function_exists('proc_open')) { + $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes); + } + + if (!$isTtySupported) { + return [1, 1]; + } + + $sttyMode = shell_exec('stty -g'); + shell_exec('stty -icanon -echo'); + + @fwrite($this->input, "\033[6n"); + + $code = trim(fread($this->input, 1024)); + + shell_exec(sprintf('stty %s', $sttyMode)); + + sscanf($code, "\033[%d;%dR", $row, $col); + + return [$col, $row]; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php b/php/libraries/composer/vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php new file mode 100644 index 0000000..1fbb212 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php @@ -0,0 +1,148 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\DependencyInjection; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\LazyCommand; +use Symfony\Component\Console\CommandLoader\ContainerCommandLoader; +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\TypedReference; + +/** + * Registers console commands. + * + * @author Grégoire Pineau <lyrixx@lyrixx.info> + */ +class AddConsoleCommandPass implements CompilerPassInterface +{ + private $commandLoaderServiceId; + private $commandTag; + private $noPreloadTag; + private $privateTagName; + + public function __construct(string $commandLoaderServiceId = 'console.command_loader', string $commandTag = 'console.command', string $noPreloadTag = 'container.no_preload', string $privateTagName = 'container.private') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/console', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->commandLoaderServiceId = $commandLoaderServiceId; + $this->commandTag = $commandTag; + $this->noPreloadTag = $noPreloadTag; + $this->privateTagName = $privateTagName; + } + + public function process(ContainerBuilder $container) + { + $commandServices = $container->findTaggedServiceIds($this->commandTag, true); + $lazyCommandMap = []; + $lazyCommandRefs = []; + $serviceIds = []; + + foreach ($commandServices as $id => $tags) { + $definition = $container->getDefinition($id); + $definition->addTag($this->noPreloadTag); + $class = $container->getParameterBag()->resolveValue($definition->getClass()); + + if (isset($tags[0]['command'])) { + $aliases = $tags[0]['command']; + } else { + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(Command::class)) { + throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, $this->commandTag, Command::class)); + } + $aliases = str_replace('%', '%%', $class::getDefaultName() ?? ''); + } + + $aliases = explode('|', $aliases ?? ''); + $commandName = array_shift($aliases); + + if ($isHidden = '' === $commandName) { + $commandName = array_shift($aliases); + } + + if (null === $commandName) { + if (!$definition->isPublic() || $definition->isPrivate() || $definition->hasTag($this->privateTagName)) { + $commandId = 'console.command.public_alias.'.$id; + $container->setAlias($commandId, $id)->setPublic(true); + $id = $commandId; + } + $serviceIds[] = $id; + + continue; + } + + $description = $tags[0]['description'] ?? null; + + unset($tags[0]); + $lazyCommandMap[$commandName] = $id; + $lazyCommandRefs[$id] = new TypedReference($id, $class); + + foreach ($aliases as $alias) { + $lazyCommandMap[$alias] = $id; + } + + foreach ($tags as $tag) { + if (isset($tag['command'])) { + $aliases[] = $tag['command']; + $lazyCommandMap[$tag['command']] = $id; + } + + $description = $description ?? $tag['description'] ?? null; + } + + $definition->addMethodCall('setName', [$commandName]); + + if ($aliases) { + $definition->addMethodCall('setAliases', [$aliases]); + } + + if ($isHidden) { + $definition->addMethodCall('setHidden', [true]); + } + + if (!$description) { + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(Command::class)) { + throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, $this->commandTag, Command::class)); + } + $description = str_replace('%', '%%', $class::getDefaultDescription() ?? ''); + } + + if ($description) { + $definition->addMethodCall('setDescription', [$description]); + + $container->register('.'.$id.'.lazy', LazyCommand::class) + ->setArguments([$commandName, $aliases, $description, $isHidden, new ServiceClosureArgument($lazyCommandRefs[$id])]); + + $lazyCommandRefs[$id] = new Reference('.'.$id.'.lazy'); + } + } + + $container + ->register($this->commandLoaderServiceId, ContainerCommandLoader::class) + ->setPublic(true) + ->addTag($this->noPreloadTag) + ->setArguments([ServiceLocatorTagPass::register($container, $lazyCommandRefs), $lazyCommandMap]); + + $container->setParameter('console.command.ids', $serviceIds); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/ApplicationDescription.php b/php/libraries/composer/vendor/symfony/console/Descriptor/ApplicationDescription.php new file mode 100644 index 0000000..eb11b4f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/ApplicationDescription.php @@ -0,0 +1,143 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class ApplicationDescription +{ + public const GLOBAL_NAMESPACE = '_global'; + + private $application; + private $namespace; + private $showHidden; + + /** + * @var array + */ + private $namespaces; + + /** + * @var array<string, Command> + */ + private $commands; + + /** + * @var array<string, Command> + */ + private $aliases; + + public function __construct(Application $application, ?string $namespace = null, bool $showHidden = false) + { + $this->application = $application; + $this->namespace = $namespace; + $this->showHidden = $showHidden; + } + + public function getNamespaces(): array + { + if (null === $this->namespaces) { + $this->inspectApplication(); + } + + return $this->namespaces; + } + + /** + * @return Command[] + */ + public function getCommands(): array + { + if (null === $this->commands) { + $this->inspectApplication(); + } + + return $this->commands; + } + + /** + * @throws CommandNotFoundException + */ + public function getCommand(string $name): Command + { + if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) { + throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); + } + + return $this->commands[$name] ?? $this->aliases[$name]; + } + + private function inspectApplication() + { + $this->commands = []; + $this->namespaces = []; + + $all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null); + foreach ($this->sortCommands($all) as $namespace => $commands) { + $names = []; + + /** @var Command $command */ + foreach ($commands as $name => $command) { + if (!$command->getName() || (!$this->showHidden && $command->isHidden())) { + continue; + } + + if ($command->getName() === $name) { + $this->commands[$name] = $command; + } else { + $this->aliases[$name] = $command; + } + + $names[] = $name; + } + + $this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names]; + } + } + + private function sortCommands(array $commands): array + { + $namespacedCommands = []; + $globalCommands = []; + $sortedCommands = []; + foreach ($commands as $name => $command) { + $key = $this->application->extractNamespace($name, 1); + if (\in_array($key, ['', self::GLOBAL_NAMESPACE], true)) { + $globalCommands[$name] = $command; + } else { + $namespacedCommands[$key][$name] = $command; + } + } + + if ($globalCommands) { + ksort($globalCommands); + $sortedCommands[self::GLOBAL_NAMESPACE] = $globalCommands; + } + + if ($namespacedCommands) { + ksort($namespacedCommands, \SORT_STRING); + foreach ($namespacedCommands as $key => $commandsSet) { + ksort($commandsSet); + $sortedCommands[$key] = $commandsSet; + } + } + + return $sortedCommands; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/Descriptor.php b/php/libraries/composer/vendor/symfony/console/Descriptor/Descriptor.php new file mode 100644 index 0000000..a364830 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/Descriptor.php @@ -0,0 +1,94 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +abstract class Descriptor implements DescriptorInterface +{ + /** + * @var OutputInterface + */ + protected $output; + + /** + * {@inheritdoc} + */ + public function describe(OutputInterface $output, object $object, array $options = []) + { + $this->output = $output; + + switch (true) { + case $object instanceof InputArgument: + $this->describeInputArgument($object, $options); + break; + case $object instanceof InputOption: + $this->describeInputOption($object, $options); + break; + case $object instanceof InputDefinition: + $this->describeInputDefinition($object, $options); + break; + case $object instanceof Command: + $this->describeCommand($object, $options); + break; + case $object instanceof Application: + $this->describeApplication($object, $options); + break; + default: + throw new InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))); + } + } + + /** + * Writes content to output. + */ + protected function write(string $content, bool $decorated = false) + { + $this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW); + } + + /** + * Describes an InputArgument instance. + */ + abstract protected function describeInputArgument(InputArgument $argument, array $options = []); + + /** + * Describes an InputOption instance. + */ + abstract protected function describeInputOption(InputOption $option, array $options = []); + + /** + * Describes an InputDefinition instance. + */ + abstract protected function describeInputDefinition(InputDefinition $definition, array $options = []); + + /** + * Describes a Command instance. + */ + abstract protected function describeCommand(Command $command, array $options = []); + + /** + * Describes an Application instance. + */ + abstract protected function describeApplication(Application $application, array $options = []); +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/DescriptorInterface.php b/php/libraries/composer/vendor/symfony/console/Descriptor/DescriptorInterface.php new file mode 100644 index 0000000..ebea303 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/DescriptorInterface.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Descriptor interface. + * + * @author Jean-François Simon <contact@jfsimon.fr> + */ +interface DescriptorInterface +{ + public function describe(OutputInterface $output, object $object, array $options = []); +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/JsonDescriptor.php b/php/libraries/composer/vendor/symfony/console/Descriptor/JsonDescriptor.php new file mode 100644 index 0000000..1d28659 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/JsonDescriptor.php @@ -0,0 +1,181 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * JSON descriptor. + * + * @author Jean-François Simon <contact@jfsimon.fr> + * + * @internal + */ +class JsonDescriptor extends Descriptor +{ + /** + * {@inheritdoc} + */ + protected function describeInputArgument(InputArgument $argument, array $options = []) + { + $this->writeData($this->getInputArgumentData($argument), $options); + } + + /** + * {@inheritdoc} + */ + protected function describeInputOption(InputOption $option, array $options = []) + { + $this->writeData($this->getInputOptionData($option), $options); + if ($option->isNegatable()) { + $this->writeData($this->getInputOptionData($option, true), $options); + } + } + + /** + * {@inheritdoc} + */ + protected function describeInputDefinition(InputDefinition $definition, array $options = []) + { + $this->writeData($this->getInputDefinitionData($definition), $options); + } + + /** + * {@inheritdoc} + */ + protected function describeCommand(Command $command, array $options = []) + { + $this->writeData($this->getCommandData($command, $options['short'] ?? false), $options); + } + + /** + * {@inheritdoc} + */ + protected function describeApplication(Application $application, array $options = []) + { + $describedNamespace = $options['namespace'] ?? null; + $description = new ApplicationDescription($application, $describedNamespace, true); + $commands = []; + + foreach ($description->getCommands() as $command) { + $commands[] = $this->getCommandData($command, $options['short'] ?? false); + } + + $data = []; + if ('UNKNOWN' !== $application->getName()) { + $data['application']['name'] = $application->getName(); + if ('UNKNOWN' !== $application->getVersion()) { + $data['application']['version'] = $application->getVersion(); + } + } + + $data['commands'] = $commands; + + if ($describedNamespace) { + $data['namespace'] = $describedNamespace; + } else { + $data['namespaces'] = array_values($description->getNamespaces()); + } + + $this->writeData($data, $options); + } + + /** + * Writes data as json. + */ + private function writeData(array $data, array $options) + { + $flags = $options['json_encoding'] ?? 0; + + $this->write(json_encode($data, $flags)); + } + + private function getInputArgumentData(InputArgument $argument): array + { + return [ + 'name' => $argument->getName(), + 'is_required' => $argument->isRequired(), + 'is_array' => $argument->isArray(), + 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()), + 'default' => \INF === $argument->getDefault() ? 'INF' : $argument->getDefault(), + ]; + } + + private function getInputOptionData(InputOption $option, bool $negated = false): array + { + return $negated ? [ + 'name' => '--no-'.$option->getName(), + 'shortcut' => '', + 'accept_value' => false, + 'is_value_required' => false, + 'is_multiple' => false, + 'description' => 'Negate the "--'.$option->getName().'" option', + 'default' => false, + ] : [ + 'name' => '--'.$option->getName(), + 'shortcut' => $option->getShortcut() ? '-'.str_replace('|', '|-', $option->getShortcut()) : '', + 'accept_value' => $option->acceptValue(), + 'is_value_required' => $option->isValueRequired(), + 'is_multiple' => $option->isArray(), + 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()), + 'default' => \INF === $option->getDefault() ? 'INF' : $option->getDefault(), + ]; + } + + private function getInputDefinitionData(InputDefinition $definition): array + { + $inputArguments = []; + foreach ($definition->getArguments() as $name => $argument) { + $inputArguments[$name] = $this->getInputArgumentData($argument); + } + + $inputOptions = []; + foreach ($definition->getOptions() as $name => $option) { + $inputOptions[$name] = $this->getInputOptionData($option); + if ($option->isNegatable()) { + $inputOptions['no-'.$name] = $this->getInputOptionData($option, true); + } + } + + return ['arguments' => $inputArguments, 'options' => $inputOptions]; + } + + private function getCommandData(Command $command, bool $short = false): array + { + $data = [ + 'name' => $command->getName(), + 'description' => $command->getDescription(), + ]; + + if ($short) { + $data += [ + 'usage' => $command->getAliases(), + ]; + } else { + $command->mergeApplicationDefinition(false); + + $data += [ + 'usage' => array_merge([$command->getSynopsis()], $command->getUsages(), $command->getAliases()), + 'help' => $command->getProcessedHelp(), + 'definition' => $this->getInputDefinitionData($command->getDefinition()), + ]; + } + + $data['hidden'] = $command->isHidden(); + + return $data; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/MarkdownDescriptor.php b/php/libraries/composer/vendor/symfony/console/Descriptor/MarkdownDescriptor.php new file mode 100644 index 0000000..21ceca6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/MarkdownDescriptor.php @@ -0,0 +1,206 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Markdown descriptor. + * + * @author Jean-François Simon <contact@jfsimon.fr> + * + * @internal + */ +class MarkdownDescriptor extends Descriptor +{ + /** + * {@inheritdoc} + */ + public function describe(OutputInterface $output, object $object, array $options = []) + { + $decorated = $output->isDecorated(); + $output->setDecorated(false); + + parent::describe($output, $object, $options); + + $output->setDecorated($decorated); + } + + /** + * {@inheritdoc} + */ + protected function write(string $content, bool $decorated = true) + { + parent::write($content, $decorated); + } + + /** + * {@inheritdoc} + */ + protected function describeInputArgument(InputArgument $argument, array $options = []) + { + $this->write( + '#### `'.($argument->getName() ?: '<none>')."`\n\n" + .($argument->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $argument->getDescription())."\n\n" : '') + .'* Is required: '.($argument->isRequired() ? 'yes' : 'no')."\n" + .'* Is array: '.($argument->isArray() ? 'yes' : 'no')."\n" + .'* Default: `'.str_replace("\n", '', var_export($argument->getDefault(), true)).'`' + ); + } + + /** + * {@inheritdoc} + */ + protected function describeInputOption(InputOption $option, array $options = []) + { + $name = '--'.$option->getName(); + if ($option->isNegatable()) { + $name .= '|--no-'.$option->getName(); + } + if ($option->getShortcut()) { + $name .= '|-'.str_replace('|', '|-', $option->getShortcut()).''; + } + + $this->write( + '#### `'.$name.'`'."\n\n" + .($option->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $option->getDescription())."\n\n" : '') + .'* Accept value: '.($option->acceptValue() ? 'yes' : 'no')."\n" + .'* Is value required: '.($option->isValueRequired() ? 'yes' : 'no')."\n" + .'* Is multiple: '.($option->isArray() ? 'yes' : 'no')."\n" + .'* Is negatable: '.($option->isNegatable() ? 'yes' : 'no')."\n" + .'* Default: `'.str_replace("\n", '', var_export($option->getDefault(), true)).'`' + ); + } + + /** + * {@inheritdoc} + */ + protected function describeInputDefinition(InputDefinition $definition, array $options = []) + { + if ($showArguments = \count($definition->getArguments()) > 0) { + $this->write('### Arguments'); + foreach ($definition->getArguments() as $argument) { + $this->write("\n\n"); + if (null !== $describeInputArgument = $this->describeInputArgument($argument)) { + $this->write($describeInputArgument); + } + } + } + + if (\count($definition->getOptions()) > 0) { + if ($showArguments) { + $this->write("\n\n"); + } + + $this->write('### Options'); + foreach ($definition->getOptions() as $option) { + $this->write("\n\n"); + if (null !== $describeInputOption = $this->describeInputOption($option)) { + $this->write($describeInputOption); + } + } + } + } + + /** + * {@inheritdoc} + */ + protected function describeCommand(Command $command, array $options = []) + { + if ($options['short'] ?? false) { + $this->write( + '`'.$command->getName()."`\n" + .str_repeat('-', Helper::width($command->getName()) + 2)."\n\n" + .($command->getDescription() ? $command->getDescription()."\n\n" : '') + .'### Usage'."\n\n" + .array_reduce($command->getAliases(), function ($carry, $usage) { + return $carry.'* `'.$usage.'`'."\n"; + }) + ); + + return; + } + + $command->mergeApplicationDefinition(false); + + $this->write( + '`'.$command->getName()."`\n" + .str_repeat('-', Helper::width($command->getName()) + 2)."\n\n" + .($command->getDescription() ? $command->getDescription()."\n\n" : '') + .'### Usage'."\n\n" + .array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), function ($carry, $usage) { + return $carry.'* `'.$usage.'`'."\n"; + }) + ); + + if ($help = $command->getProcessedHelp()) { + $this->write("\n"); + $this->write($help); + } + + $definition = $command->getDefinition(); + if ($definition->getOptions() || $definition->getArguments()) { + $this->write("\n\n"); + $this->describeInputDefinition($definition); + } + } + + /** + * {@inheritdoc} + */ + protected function describeApplication(Application $application, array $options = []) + { + $describedNamespace = $options['namespace'] ?? null; + $description = new ApplicationDescription($application, $describedNamespace); + $title = $this->getApplicationTitle($application); + + $this->write($title."\n".str_repeat('=', Helper::width($title))); + + foreach ($description->getNamespaces() as $namespace) { + if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) { + $this->write("\n\n"); + $this->write('**'.$namespace['id'].':**'); + } + + $this->write("\n\n"); + $this->write(implode("\n", array_map(function ($commandName) use ($description) { + return sprintf('* [`%s`](#%s)', $commandName, str_replace(':', '', $description->getCommand($commandName)->getName())); + }, $namespace['commands']))); + } + + foreach ($description->getCommands() as $command) { + $this->write("\n\n"); + if (null !== $describeCommand = $this->describeCommand($command, $options)) { + $this->write($describeCommand); + } + } + } + + private function getApplicationTitle(Application $application): string + { + if ('UNKNOWN' !== $application->getName()) { + if ('UNKNOWN' !== $application->getVersion()) { + return sprintf('%s %s', $application->getName(), $application->getVersion()); + } + + return $application->getName(); + } + + return 'Console Tool'; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/TextDescriptor.php b/php/libraries/composer/vendor/symfony/console/Descriptor/TextDescriptor.php new file mode 100644 index 0000000..fbb140a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/TextDescriptor.php @@ -0,0 +1,341 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * Text descriptor. + * + * @author Jean-François Simon <contact@jfsimon.fr> + * + * @internal + */ +class TextDescriptor extends Descriptor +{ + /** + * {@inheritdoc} + */ + protected function describeInputArgument(InputArgument $argument, array $options = []) + { + if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) { + $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault())); + } else { + $default = ''; + } + + $totalWidth = $options['total_width'] ?? Helper::width($argument->getName()); + $spacingWidth = $totalWidth - \strlen($argument->getName()); + + $this->writeText(sprintf(' <info>%s</info> %s%s%s', + $argument->getName(), + str_repeat(' ', $spacingWidth), + // + 4 = 2 spaces before <info>, 2 spaces after </info> + preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $argument->getDescription()), + $default + ), $options); + } + + /** + * {@inheritdoc} + */ + protected function describeInputOption(InputOption $option, array $options = []) + { + if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) { + $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault())); + } else { + $default = ''; + } + + $value = ''; + if ($option->acceptValue()) { + $value = '='.strtoupper($option->getName()); + + if ($option->isValueOptional()) { + $value = '['.$value.']'; + } + } + + $totalWidth = $options['total_width'] ?? $this->calculateTotalWidthForOptions([$option]); + $synopsis = sprintf('%s%s', + $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ', + sprintf($option->isNegatable() ? '--%1$s|--no-%1$s' : '--%1$s%2$s', $option->getName(), $value) + ); + + $spacingWidth = $totalWidth - Helper::width($synopsis); + + $this->writeText(sprintf(' <info>%s</info> %s%s%s%s', + $synopsis, + str_repeat(' ', $spacingWidth), + // + 4 = 2 spaces before <info>, 2 spaces after </info> + preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $option->getDescription()), + $default, + $option->isArray() ? '<comment> (multiple values allowed)</comment>' : '' + ), $options); + } + + /** + * {@inheritdoc} + */ + protected function describeInputDefinition(InputDefinition $definition, array $options = []) + { + $totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions()); + foreach ($definition->getArguments() as $argument) { + $totalWidth = max($totalWidth, Helper::width($argument->getName())); + } + + if ($definition->getArguments()) { + $this->writeText('<comment>Arguments:</comment>', $options); + $this->writeText("\n"); + foreach ($definition->getArguments() as $argument) { + $this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth])); + $this->writeText("\n"); + } + } + + if ($definition->getArguments() && $definition->getOptions()) { + $this->writeText("\n"); + } + + if ($definition->getOptions()) { + $laterOptions = []; + + $this->writeText('<comment>Options:</comment>', $options); + foreach ($definition->getOptions() as $option) { + if (\strlen($option->getShortcut() ?? '') > 1) { + $laterOptions[] = $option; + continue; + } + $this->writeText("\n"); + $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth])); + } + foreach ($laterOptions as $option) { + $this->writeText("\n"); + $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth])); + } + } + } + + /** + * {@inheritdoc} + */ + protected function describeCommand(Command $command, array $options = []) + { + $command->mergeApplicationDefinition(false); + + if ($description = $command->getDescription()) { + $this->writeText('<comment>Description:</comment>', $options); + $this->writeText("\n"); + $this->writeText(' '.$description); + $this->writeText("\n\n"); + } + + $this->writeText('<comment>Usage:</comment>', $options); + foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) { + $this->writeText("\n"); + $this->writeText(' '.OutputFormatter::escape($usage), $options); + } + $this->writeText("\n"); + + $definition = $command->getDefinition(); + if ($definition->getOptions() || $definition->getArguments()) { + $this->writeText("\n"); + $this->describeInputDefinition($definition, $options); + $this->writeText("\n"); + } + + $help = $command->getProcessedHelp(); + if ($help && $help !== $description) { + $this->writeText("\n"); + $this->writeText('<comment>Help:</comment>', $options); + $this->writeText("\n"); + $this->writeText(' '.str_replace("\n", "\n ", $help), $options); + $this->writeText("\n"); + } + } + + /** + * {@inheritdoc} + */ + protected function describeApplication(Application $application, array $options = []) + { + $describedNamespace = $options['namespace'] ?? null; + $description = new ApplicationDescription($application, $describedNamespace); + + if (isset($options['raw_text']) && $options['raw_text']) { + $width = $this->getColumnWidth($description->getCommands()); + + foreach ($description->getCommands() as $command) { + $this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options); + $this->writeText("\n"); + } + } else { + if ('' != $help = $application->getHelp()) { + $this->writeText("$help\n\n", $options); + } + + $this->writeText("<comment>Usage:</comment>\n", $options); + $this->writeText(" command [options] [arguments]\n\n", $options); + + $this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options); + + $this->writeText("\n"); + $this->writeText("\n"); + + $commands = $description->getCommands(); + $namespaces = $description->getNamespaces(); + if ($describedNamespace && $namespaces) { + // make sure all alias commands are included when describing a specific namespace + $describedNamespaceInfo = reset($namespaces); + foreach ($describedNamespaceInfo['commands'] as $name) { + $commands[$name] = $description->getCommand($name); + } + } + + // calculate max. width based on available commands per namespace + $width = $this->getColumnWidth(array_merge(...array_values(array_map(function ($namespace) use ($commands) { + return array_intersect($namespace['commands'], array_keys($commands)); + }, array_values($namespaces))))); + + if ($describedNamespace) { + $this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options); + } else { + $this->writeText('<comment>Available commands:</comment>', $options); + } + + foreach ($namespaces as $namespace) { + $namespace['commands'] = array_filter($namespace['commands'], function ($name) use ($commands) { + return isset($commands[$name]); + }); + + if (!$namespace['commands']) { + continue; + } + + if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) { + $this->writeText("\n"); + $this->writeText(' <comment>'.$namespace['id'].'</comment>', $options); + } + + foreach ($namespace['commands'] as $name) { + $this->writeText("\n"); + $spacingWidth = $width - Helper::width($name); + $command = $commands[$name]; + $commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : ''; + $this->writeText(sprintf(' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options); + } + } + + $this->writeText("\n"); + } + } + + /** + * {@inheritdoc} + */ + private function writeText(string $content, array $options = []) + { + $this->write( + isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content, + isset($options['raw_output']) ? !$options['raw_output'] : true + ); + } + + /** + * Formats command aliases to show them in the command description. + */ + private function getCommandAliasesText(Command $command): string + { + $text = ''; + $aliases = $command->getAliases(); + + if ($aliases) { + $text = '['.implode('|', $aliases).'] '; + } + + return $text; + } + + /** + * Formats input option/argument default value. + * + * @param mixed $default + */ + private function formatDefaultValue($default): string + { + if (\INF === $default) { + return 'INF'; + } + + if (\is_string($default)) { + $default = OutputFormatter::escape($default); + } elseif (\is_array($default)) { + foreach ($default as $key => $value) { + if (\is_string($value)) { + $default[$key] = OutputFormatter::escape($value); + } + } + } + + return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE)); + } + + /** + * @param array<Command|string> $commands + */ + private function getColumnWidth(array $commands): int + { + $widths = []; + + foreach ($commands as $command) { + if ($command instanceof Command) { + $widths[] = Helper::width($command->getName()); + foreach ($command->getAliases() as $alias) { + $widths[] = Helper::width($alias); + } + } else { + $widths[] = Helper::width($command); + } + } + + return $widths ? max($widths) + 2 : 0; + } + + /** + * @param InputOption[] $options + */ + private function calculateTotalWidthForOptions(array $options): int + { + $totalWidth = 0; + foreach ($options as $option) { + // "-" + shortcut + ", --" + name + $nameLength = 1 + max(Helper::width($option->getShortcut()), 1) + 4 + Helper::width($option->getName()); + if ($option->isNegatable()) { + $nameLength += 6 + Helper::width($option->getName()); // |--no- + name + } elseif ($option->acceptValue()) { + $valueLength = 1 + Helper::width($option->getName()); // = + value + $valueLength += $option->isValueOptional() ? 2 : 0; // [ + ] + + $nameLength += $valueLength; + } + $totalWidth = max($totalWidth, $nameLength); + } + + return $totalWidth; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Descriptor/XmlDescriptor.php b/php/libraries/composer/vendor/symfony/console/Descriptor/XmlDescriptor.php new file mode 100644 index 0000000..f17e5f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Descriptor/XmlDescriptor.php @@ -0,0 +1,247 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * XML descriptor. + * + * @author Jean-François Simon <contact@jfsimon.fr> + * + * @internal + */ +class XmlDescriptor extends Descriptor +{ + public function getInputDefinitionDocument(InputDefinition $definition): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->appendChild($definitionXML = $dom->createElement('definition')); + + $definitionXML->appendChild($argumentsXML = $dom->createElement('arguments')); + foreach ($definition->getArguments() as $argument) { + $this->appendDocument($argumentsXML, $this->getInputArgumentDocument($argument)); + } + + $definitionXML->appendChild($optionsXML = $dom->createElement('options')); + foreach ($definition->getOptions() as $option) { + $this->appendDocument($optionsXML, $this->getInputOptionDocument($option)); + } + + return $dom; + } + + public function getCommandDocument(Command $command, bool $short = false): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->appendChild($commandXML = $dom->createElement('command')); + + $commandXML->setAttribute('id', $command->getName()); + $commandXML->setAttribute('name', $command->getName()); + $commandXML->setAttribute('hidden', $command->isHidden() ? 1 : 0); + + $commandXML->appendChild($usagesXML = $dom->createElement('usages')); + + $commandXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getDescription()))); + + if ($short) { + foreach ($command->getAliases() as $usage) { + $usagesXML->appendChild($dom->createElement('usage', $usage)); + } + } else { + $command->mergeApplicationDefinition(false); + + foreach (array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()) as $usage) { + $usagesXML->appendChild($dom->createElement('usage', $usage)); + } + + $commandXML->appendChild($helpXML = $dom->createElement('help')); + $helpXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getProcessedHelp()))); + + $definitionXML = $this->getInputDefinitionDocument($command->getDefinition()); + $this->appendDocument($commandXML, $definitionXML->getElementsByTagName('definition')->item(0)); + } + + return $dom; + } + + public function getApplicationDocument(Application $application, ?string $namespace = null, bool $short = false): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->appendChild($rootXml = $dom->createElement('symfony')); + + if ('UNKNOWN' !== $application->getName()) { + $rootXml->setAttribute('name', $application->getName()); + if ('UNKNOWN' !== $application->getVersion()) { + $rootXml->setAttribute('version', $application->getVersion()); + } + } + + $rootXml->appendChild($commandsXML = $dom->createElement('commands')); + + $description = new ApplicationDescription($application, $namespace, true); + + if ($namespace) { + $commandsXML->setAttribute('namespace', $namespace); + } + + foreach ($description->getCommands() as $command) { + $this->appendDocument($commandsXML, $this->getCommandDocument($command, $short)); + } + + if (!$namespace) { + $rootXml->appendChild($namespacesXML = $dom->createElement('namespaces')); + + foreach ($description->getNamespaces() as $namespaceDescription) { + $namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace')); + $namespaceArrayXML->setAttribute('id', $namespaceDescription['id']); + + foreach ($namespaceDescription['commands'] as $name) { + $namespaceArrayXML->appendChild($commandXML = $dom->createElement('command')); + $commandXML->appendChild($dom->createTextNode($name)); + } + } + } + + return $dom; + } + + /** + * {@inheritdoc} + */ + protected function describeInputArgument(InputArgument $argument, array $options = []) + { + $this->writeDocument($this->getInputArgumentDocument($argument)); + } + + /** + * {@inheritdoc} + */ + protected function describeInputOption(InputOption $option, array $options = []) + { + $this->writeDocument($this->getInputOptionDocument($option)); + } + + /** + * {@inheritdoc} + */ + protected function describeInputDefinition(InputDefinition $definition, array $options = []) + { + $this->writeDocument($this->getInputDefinitionDocument($definition)); + } + + /** + * {@inheritdoc} + */ + protected function describeCommand(Command $command, array $options = []) + { + $this->writeDocument($this->getCommandDocument($command, $options['short'] ?? false)); + } + + /** + * {@inheritdoc} + */ + protected function describeApplication(Application $application, array $options = []) + { + $this->writeDocument($this->getApplicationDocument($application, $options['namespace'] ?? null, $options['short'] ?? false)); + } + + /** + * Appends document children to parent node. + */ + private function appendDocument(\DOMNode $parentNode, \DOMNode $importedParent) + { + foreach ($importedParent->childNodes as $childNode) { + $parentNode->appendChild($parentNode->ownerDocument->importNode($childNode, true)); + } + } + + /** + * Writes DOM document. + */ + private function writeDocument(\DOMDocument $dom) + { + $dom->formatOutput = true; + $this->write($dom->saveXML()); + } + + private function getInputArgumentDocument(InputArgument $argument): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + + $dom->appendChild($objectXML = $dom->createElement('argument')); + $objectXML->setAttribute('name', $argument->getName()); + $objectXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0); + $objectXML->setAttribute('is_array', $argument->isArray() ? 1 : 0); + $objectXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode($argument->getDescription())); + + $objectXML->appendChild($defaultsXML = $dom->createElement('defaults')); + $defaults = \is_array($argument->getDefault()) ? $argument->getDefault() : (\is_bool($argument->getDefault()) ? [var_export($argument->getDefault(), true)] : ($argument->getDefault() ? [$argument->getDefault()] : [])); + foreach ($defaults as $default) { + $defaultsXML->appendChild($defaultXML = $dom->createElement('default')); + $defaultXML->appendChild($dom->createTextNode($default)); + } + + return $dom; + } + + private function getInputOptionDocument(InputOption $option): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + + $dom->appendChild($objectXML = $dom->createElement('option')); + $objectXML->setAttribute('name', '--'.$option->getName()); + $pos = strpos($option->getShortcut() ?? '', '|'); + if (false !== $pos) { + $objectXML->setAttribute('shortcut', '-'.substr($option->getShortcut(), 0, $pos)); + $objectXML->setAttribute('shortcuts', '-'.str_replace('|', '|-', $option->getShortcut())); + } else { + $objectXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : ''); + } + $objectXML->setAttribute('accept_value', $option->acceptValue() ? 1 : 0); + $objectXML->setAttribute('is_value_required', $option->isValueRequired() ? 1 : 0); + $objectXML->setAttribute('is_multiple', $option->isArray() ? 1 : 0); + $objectXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode($option->getDescription())); + + if ($option->acceptValue()) { + $defaults = \is_array($option->getDefault()) ? $option->getDefault() : (\is_bool($option->getDefault()) ? [var_export($option->getDefault(), true)] : ($option->getDefault() ? [$option->getDefault()] : [])); + $objectXML->appendChild($defaultsXML = $dom->createElement('defaults')); + + if (!empty($defaults)) { + foreach ($defaults as $default) { + $defaultsXML->appendChild($defaultXML = $dom->createElement('default')); + $defaultXML->appendChild($dom->createTextNode($default)); + } + } + } + + if ($option->isNegatable()) { + $dom->appendChild($objectXML = $dom->createElement('option')); + $objectXML->setAttribute('name', '--no-'.$option->getName()); + $objectXML->setAttribute('shortcut', ''); + $objectXML->setAttribute('accept_value', 0); + $objectXML->setAttribute('is_value_required', 0); + $objectXML->setAttribute('is_multiple', 0); + $objectXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode('Negate the "--'.$option->getName().'" option')); + } + + return $dom; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Event/ConsoleCommandEvent.php b/php/libraries/composer/vendor/symfony/console/Event/ConsoleCommandEvent.php new file mode 100644 index 0000000..1b4f9f9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Event/ConsoleCommandEvent.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +/** + * Allows to do things before the command is executed, like skipping the command or executing code before the command is + * going to be executed. + * + * Changing the input arguments will have no effect. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +final class ConsoleCommandEvent extends ConsoleEvent +{ + /** + * The return code for skipped commands, this will also be passed into the terminate event. + */ + public const RETURN_CODE_DISABLED = 113; + + /** + * Indicates if the command should be run or skipped. + */ + private $commandShouldRun = true; + + /** + * Disables the command, so it won't be run. + */ + public function disableCommand(): bool + { + return $this->commandShouldRun = false; + } + + public function enableCommand(): bool + { + return $this->commandShouldRun = true; + } + + /** + * Returns true if the command is runnable, false otherwise. + */ + public function commandShouldRun(): bool + { + return $this->commandShouldRun; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Event/ConsoleErrorEvent.php b/php/libraries/composer/vendor/symfony/console/Event/ConsoleErrorEvent.php new file mode 100644 index 0000000..d4c2649 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Event/ConsoleErrorEvent.php @@ -0,0 +1,58 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Allows to handle throwables thrown while running a command. + * + * @author Wouter de Jong <wouter@wouterj.nl> + */ +final class ConsoleErrorEvent extends ConsoleEvent +{ + private $error; + private $exitCode; + + public function __construct(InputInterface $input, OutputInterface $output, \Throwable $error, ?Command $command = null) + { + parent::__construct($command, $input, $output); + + $this->error = $error; + } + + public function getError(): \Throwable + { + return $this->error; + } + + public function setError(\Throwable $error): void + { + $this->error = $error; + } + + public function setExitCode(int $exitCode): void + { + $this->exitCode = $exitCode; + + $r = new \ReflectionProperty($this->error, 'code'); + $r->setAccessible(true); + $r->setValue($this->error, $this->exitCode); + } + + public function getExitCode(): int + { + return $this->exitCode ?? (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Event/ConsoleEvent.php b/php/libraries/composer/vendor/symfony/console/Event/ConsoleEvent.php new file mode 100644 index 0000000..be7937d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Event/ConsoleEvent.php @@ -0,0 +1,67 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Allows to inspect input and output of a command. + * + * @author Francesco Levorato <git@flevour.net> + */ +class ConsoleEvent extends Event +{ + protected $command; + + private $input; + private $output; + + public function __construct(?Command $command, InputInterface $input, OutputInterface $output) + { + $this->command = $command; + $this->input = $input; + $this->output = $output; + } + + /** + * Gets the command that is executed. + * + * @return Command|null + */ + public function getCommand() + { + return $this->command; + } + + /** + * Gets the input instance. + * + * @return InputInterface + */ + public function getInput() + { + return $this->input; + } + + /** + * Gets the output instance. + * + * @return OutputInterface + */ + public function getOutput() + { + return $this->output; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Event/ConsoleSignalEvent.php b/php/libraries/composer/vendor/symfony/console/Event/ConsoleSignalEvent.php new file mode 100644 index 0000000..ef13ed2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Event/ConsoleSignalEvent.php @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author marie <marie@users.noreply.github.com> + */ +final class ConsoleSignalEvent extends ConsoleEvent +{ + private $handlingSignal; + + public function __construct(Command $command, InputInterface $input, OutputInterface $output, int $handlingSignal) + { + parent::__construct($command, $input, $output); + $this->handlingSignal = $handlingSignal; + } + + public function getHandlingSignal(): int + { + return $this->handlingSignal; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Event/ConsoleTerminateEvent.php b/php/libraries/composer/vendor/symfony/console/Event/ConsoleTerminateEvent.php new file mode 100644 index 0000000..190038d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Event/ConsoleTerminateEvent.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Allows to manipulate the exit code of a command after its execution. + * + * @author Francesco Levorato <git@flevour.net> + */ +final class ConsoleTerminateEvent extends ConsoleEvent +{ + private $exitCode; + + public function __construct(Command $command, InputInterface $input, OutputInterface $output, int $exitCode) + { + parent::__construct($command, $input, $output); + + $this->setExitCode($exitCode); + } + + public function setExitCode(int $exitCode): void + { + $this->exitCode = $exitCode; + } + + public function getExitCode(): int + { + return $this->exitCode; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/EventListener/ErrorListener.php b/php/libraries/composer/vendor/symfony/console/EventListener/ErrorListener.php new file mode 100644 index 0000000..e9c9e3e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/EventListener/ErrorListener.php @@ -0,0 +1,95 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\EventListener; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Console\ConsoleEvents; +use Symfony\Component\Console\Event\ConsoleErrorEvent; +use Symfony\Component\Console\Event\ConsoleEvent; +use Symfony\Component\Console\Event\ConsoleTerminateEvent; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +/** + * @author James Halsall <james.t.halsall@googlemail.com> + * @author Robin Chalas <robin.chalas@gmail.com> + */ +class ErrorListener implements EventSubscriberInterface +{ + private $logger; + + public function __construct(?LoggerInterface $logger = null) + { + $this->logger = $logger; + } + + public function onConsoleError(ConsoleErrorEvent $event) + { + if (null === $this->logger) { + return; + } + + $error = $event->getError(); + + if (!$inputString = $this->getInputString($event)) { + $this->logger->critical('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]); + + return; + } + + $this->logger->critical('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]); + } + + public function onConsoleTerminate(ConsoleTerminateEvent $event) + { + if (null === $this->logger) { + return; + } + + $exitCode = $event->getExitCode(); + + if (0 === $exitCode) { + return; + } + + if (!$inputString = $this->getInputString($event)) { + $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]); + + return; + } + + $this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]); + } + + public static function getSubscribedEvents() + { + return [ + ConsoleEvents::ERROR => ['onConsoleError', -128], + ConsoleEvents::TERMINATE => ['onConsoleTerminate', -128], + ]; + } + + private static function getInputString(ConsoleEvent $event): ?string + { + $commandName = $event->getCommand() ? $event->getCommand()->getName() : null; + $input = $event->getInput(); + + if (method_exists($input, '__toString')) { + if ($commandName) { + return str_replace(["'$commandName'", "\"$commandName\""], $commandName, (string) $input); + } + + return (string) $input; + } + + return $commandName; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/CommandNotFoundException.php b/php/libraries/composer/vendor/symfony/console/Exception/CommandNotFoundException.php new file mode 100644 index 0000000..81ec318 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/CommandNotFoundException.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents an incorrect command name typed in the console. + * + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +class CommandNotFoundException extends \InvalidArgumentException implements ExceptionInterface +{ + private $alternatives; + + /** + * @param string $message Exception message to throw + * @param string[] $alternatives List of similar defined names + * @param int $code Exception code + * @param \Throwable|null $previous Previous exception used for the exception chaining + */ + public function __construct(string $message, array $alternatives = [], int $code = 0, ?\Throwable $previous = null) + { + parent::__construct($message, $code, $previous); + + $this->alternatives = $alternatives; + } + + /** + * @return string[] + */ + public function getAlternatives() + { + return $this->alternatives; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/console/Exception/ExceptionInterface.php new file mode 100644 index 0000000..1624e13 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * ExceptionInterface. + * + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/symfony/console/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..07cc0b6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/InvalidArgumentException.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/InvalidOptionException.php b/php/libraries/composer/vendor/symfony/console/Exception/InvalidOptionException.php new file mode 100644 index 0000000..5cf6279 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/InvalidOptionException.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents an incorrect option name or value typed in the console. + * + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +class InvalidOptionException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/LogicException.php b/php/libraries/composer/vendor/symfony/console/Exception/LogicException.php new file mode 100644 index 0000000..fc37b8d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/LogicException.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +class LogicException extends \LogicException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/MissingInputException.php b/php/libraries/composer/vendor/symfony/console/Exception/MissingInputException.php new file mode 100644 index 0000000..04f02ad --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/MissingInputException.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents failure to read input from stdin. + * + * @author Gabriel Ostrolucký <gabriel.ostrolucky@gmail.com> + */ +class MissingInputException extends RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/NamespaceNotFoundException.php b/php/libraries/composer/vendor/symfony/console/Exception/NamespaceNotFoundException.php new file mode 100644 index 0000000..dd16e45 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/NamespaceNotFoundException.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents an incorrect namespace typed in the console. + * + * @author Pierre du Plessis <pdples@gmail.com> + */ +class NamespaceNotFoundException extends CommandNotFoundException +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Exception/RuntimeException.php b/php/libraries/composer/vendor/symfony/console/Exception/RuntimeException.php new file mode 100644 index 0000000..51d7d80 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Exception/RuntimeException.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/NullOutputFormatter.php b/php/libraries/composer/vendor/symfony/console/Formatter/NullOutputFormatter.php new file mode 100644 index 0000000..d770e14 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/NullOutputFormatter.php @@ -0,0 +1,69 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * @author Tien Xuan Vo <tien.xuan.vo@gmail.com> + */ +final class NullOutputFormatter implements OutputFormatterInterface +{ + private $style; + + /** + * {@inheritdoc} + */ + public function format(?string $message): ?string + { + return null; + } + + /** + * {@inheritdoc} + */ + public function getStyle(string $name): OutputFormatterStyleInterface + { + // to comply with the interface we must return a OutputFormatterStyleInterface + return $this->style ?? $this->style = new NullOutputFormatterStyle(); + } + + /** + * {@inheritdoc} + */ + public function hasStyle(string $name): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isDecorated(): bool + { + return false; + } + + /** + * {@inheritdoc} + */ + public function setDecorated(bool $decorated): void + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function setStyle(string $name, OutputFormatterStyleInterface $style): void + { + // do nothing + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/NullOutputFormatterStyle.php b/php/libraries/composer/vendor/symfony/console/Formatter/NullOutputFormatterStyle.php new file mode 100644 index 0000000..afd3d00 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/NullOutputFormatterStyle.php @@ -0,0 +1,66 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * @author Tien Xuan Vo <tien.xuan.vo@gmail.com> + */ +final class NullOutputFormatterStyle implements OutputFormatterStyleInterface +{ + /** + * {@inheritdoc} + */ + public function apply(string $text): string + { + return $text; + } + + /** + * {@inheritdoc} + */ + public function setBackground(?string $color = null): void + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function setForeground(?string $color = null): void + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function setOption(string $option): void + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function setOptions(array $options): void + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function unsetOption(string $option): void + { + // do nothing + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatter.php b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatter.php new file mode 100644 index 0000000..4ec6002 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatter.php @@ -0,0 +1,294 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +use function Symfony\Component\String\b; + +/** + * Formatter class for console output. + * + * @author Konstantin Kudryashov <ever.zet@gmail.com> + * @author Roland Franssen <franssen.roland@gmail.com> + */ +class OutputFormatter implements WrappableOutputFormatterInterface +{ + private $decorated; + private $styles = []; + private $styleStack; + + public function __clone() + { + $this->styleStack = clone $this->styleStack; + foreach ($this->styles as $key => $value) { + $this->styles[$key] = clone $value; + } + } + + /** + * Escapes "<" and ">" special chars in given text. + * + * @return string + */ + public static function escape(string $text) + { + $text = preg_replace('/([^\\\\]|^)([<>])/', '$1\\\\$2', $text); + + return self::escapeTrailingBackslash($text); + } + + /** + * Escapes trailing "\" in given text. + * + * @internal + */ + public static function escapeTrailingBackslash(string $text): string + { + if (str_ends_with($text, '\\')) { + $len = \strlen($text); + $text = rtrim($text, '\\'); + $text = str_replace("\0", '', $text); + $text .= str_repeat("\0", $len - \strlen($text)); + } + + return $text; + } + + /** + * Initializes console output formatter. + * + * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances + */ + public function __construct(bool $decorated = false, array $styles = []) + { + $this->decorated = $decorated; + + $this->setStyle('error', new OutputFormatterStyle('white', 'red')); + $this->setStyle('info', new OutputFormatterStyle('green')); + $this->setStyle('comment', new OutputFormatterStyle('yellow')); + $this->setStyle('question', new OutputFormatterStyle('black', 'cyan')); + + foreach ($styles as $name => $style) { + $this->setStyle($name, $style); + } + + $this->styleStack = new OutputFormatterStyleStack(); + } + + /** + * {@inheritdoc} + */ + public function setDecorated(bool $decorated) + { + $this->decorated = $decorated; + } + + /** + * {@inheritdoc} + */ + public function isDecorated() + { + return $this->decorated; + } + + /** + * {@inheritdoc} + */ + public function setStyle(string $name, OutputFormatterStyleInterface $style) + { + $this->styles[strtolower($name)] = $style; + } + + /** + * {@inheritdoc} + */ + public function hasStyle(string $name) + { + return isset($this->styles[strtolower($name)]); + } + + /** + * {@inheritdoc} + */ + public function getStyle(string $name) + { + if (!$this->hasStyle($name)) { + throw new InvalidArgumentException(sprintf('Undefined style: "%s".', $name)); + } + + return $this->styles[strtolower($name)]; + } + + /** + * {@inheritdoc} + */ + public function format(?string $message) + { + return $this->formatAndWrap($message, 0); + } + + /** + * {@inheritdoc} + */ + public function formatAndWrap(?string $message, int $width) + { + if (null === $message) { + return ''; + } + + $offset = 0; + $output = ''; + $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*'; + $closeTagRegex = '[a-z][^<>]*+'; + $currentLineLength = 0; + preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE); + foreach ($matches[0] as $i => $match) { + $pos = $match[1]; + $text = $match[0]; + + if (0 != $pos && '\\' == $message[$pos - 1]) { + continue; + } + + // add the text up to the next tag + $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength); + $offset = $pos + \strlen($text); + + // opening tag? + if ($open = '/' != $text[1]) { + $tag = $matches[1][$i][0]; + } else { + $tag = $matches[3][$i][0] ?? ''; + } + + if (!$open && !$tag) { + // </> + $this->styleStack->pop(); + } elseif (null === $style = $this->createStyleFromString($tag)) { + $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength); + } elseif ($open) { + $this->styleStack->push($style); + } else { + $this->styleStack->pop($style); + } + } + + $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength); + + return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']); + } + + /** + * @return OutputFormatterStyleStack + */ + public function getStyleStack() + { + return $this->styleStack; + } + + /** + * Tries to create new style instance from string. + */ + private function createStyleFromString(string $string): ?OutputFormatterStyleInterface + { + if (isset($this->styles[$string])) { + return $this->styles[$string]; + } + + if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) { + return null; + } + + $style = new OutputFormatterStyle(); + foreach ($matches as $match) { + array_shift($match); + $match[0] = strtolower($match[0]); + + if ('fg' == $match[0]) { + $style->setForeground(strtolower($match[1])); + } elseif ('bg' == $match[0]) { + $style->setBackground(strtolower($match[1])); + } elseif ('href' === $match[0]) { + $url = preg_replace('{\\\\([<>])}', '$1', $match[1]); + $style->setHref($url); + } elseif ('options' === $match[0]) { + preg_match_all('([^,;]+)', strtolower($match[1]), $options); + $options = array_shift($options); + foreach ($options as $option) { + $style->setOption($option); + } + } else { + return null; + } + } + + return $style; + } + + /** + * Applies current style from stack to text, if must be applied. + */ + private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string + { + if ('' === $text) { + return ''; + } + + if (!$width) { + return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text; + } + + if (!$currentLineLength && '' !== $current) { + $text = ltrim($text); + } + + if ($currentLineLength) { + $prefix = substr($text, 0, $i = $width - $currentLineLength)."\n"; + $text = substr($text, $i); + } else { + $prefix = ''; + } + + preg_match('~(\\n)$~', $text, $matches); + $text = $prefix.$this->addLineBreaks($text, $width); + $text = rtrim($text, "\n").($matches[1] ?? ''); + + if (!$currentLineLength && '' !== $current && "\n" !== substr($current, -1)) { + $text = "\n".$text; + } + + $lines = explode("\n", $text); + + foreach ($lines as $line) { + $currentLineLength += \strlen($line); + if ($width <= $currentLineLength) { + $currentLineLength = 0; + } + } + + if ($this->isDecorated()) { + foreach ($lines as $i => $line) { + $lines[$i] = $this->styleStack->getCurrent()->apply($line); + } + } + + return implode("\n", $lines); + } + + private function addLineBreaks(string $text, int $width): string + { + $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8'; + + return b($text)->toCodePointString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterInterface.php b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterInterface.php new file mode 100644 index 0000000..0b5f839 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterInterface.php @@ -0,0 +1,60 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * Formatter interface for console output. + * + * @author Konstantin Kudryashov <ever.zet@gmail.com> + */ +interface OutputFormatterInterface +{ + /** + * Sets the decorated flag. + */ + public function setDecorated(bool $decorated); + + /** + * Whether the output will decorate messages. + * + * @return bool + */ + public function isDecorated(); + + /** + * Sets a new style. + */ + public function setStyle(string $name, OutputFormatterStyleInterface $style); + + /** + * Checks if output formatter has style with specified name. + * + * @return bool + */ + public function hasStyle(string $name); + + /** + * Gets style options from style with specified name. + * + * @return OutputFormatterStyleInterface + * + * @throws \InvalidArgumentException When style isn't defined + */ + public function getStyle(string $name); + + /** + * Formats a message according to the given styles. + * + * @return string|null + */ + public function format(?string $message); +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyle.php b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyle.php new file mode 100644 index 0000000..d7ae664 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyle.php @@ -0,0 +1,109 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +use Symfony\Component\Console\Color; + +/** + * Formatter style class for defining styles. + * + * @author Konstantin Kudryashov <ever.zet@gmail.com> + */ +class OutputFormatterStyle implements OutputFormatterStyleInterface +{ + private $color; + private $foreground; + private $background; + private $options; + private $href; + private $handlesHrefGracefully; + + /** + * Initializes output formatter style. + * + * @param string|null $foreground The style foreground color name + * @param string|null $background The style background color name + */ + public function __construct(?string $foreground = null, ?string $background = null, array $options = []) + { + $this->color = new Color($this->foreground = $foreground ?: '', $this->background = $background ?: '', $this->options = $options); + } + + /** + * {@inheritdoc} + */ + public function setForeground(?string $color = null) + { + $this->color = new Color($this->foreground = $color ?: '', $this->background, $this->options); + } + + /** + * {@inheritdoc} + */ + public function setBackground(?string $color = null) + { + $this->color = new Color($this->foreground, $this->background = $color ?: '', $this->options); + } + + public function setHref(string $url): void + { + $this->href = $url; + } + + /** + * {@inheritdoc} + */ + public function setOption(string $option) + { + $this->options[] = $option; + $this->color = new Color($this->foreground, $this->background, $this->options); + } + + /** + * {@inheritdoc} + */ + public function unsetOption(string $option) + { + $pos = array_search($option, $this->options); + if (false !== $pos) { + unset($this->options[$pos]); + } + + $this->color = new Color($this->foreground, $this->background, $this->options); + } + + /** + * {@inheritdoc} + */ + public function setOptions(array $options) + { + $this->color = new Color($this->foreground, $this->background, $this->options = $options); + } + + /** + * {@inheritdoc} + */ + public function apply(string $text) + { + if (null === $this->handlesHrefGracefully) { + $this->handlesHrefGracefully = 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR') + && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100) + && !isset($_SERVER['IDEA_INITIAL_DIRECTORY']); + } + + if (null !== $this->href && $this->handlesHrefGracefully) { + $text = "\033]8;;$this->href\033\\$text\033]8;;\033\\"; + } + + return $this->color->apply($text); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php new file mode 100644 index 0000000..89e4d24 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php @@ -0,0 +1,52 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * Formatter style interface for defining styles. + * + * @author Konstantin Kudryashov <ever.zet@gmail.com> + */ +interface OutputFormatterStyleInterface +{ + /** + * Sets style foreground color. + */ + public function setForeground(?string $color = null); + + /** + * Sets style background color. + */ + public function setBackground(?string $color = null); + + /** + * Sets some specific style option. + */ + public function setOption(string $option); + + /** + * Unsets some specific style option. + */ + public function unsetOption(string $option); + + /** + * Sets multiple style options at once. + */ + public function setOptions(array $options); + + /** + * Applies the style to a given text. + * + * @return string + */ + public function apply(string $text); +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyleStack.php b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyleStack.php new file mode 100644 index 0000000..1b93563 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/OutputFormatterStyleStack.php @@ -0,0 +1,110 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Contracts\Service\ResetInterface; + +/** + * @author Jean-François Simon <contact@jfsimon.fr> + */ +class OutputFormatterStyleStack implements ResetInterface +{ + /** + * @var OutputFormatterStyleInterface[] + */ + private $styles; + + private $emptyStyle; + + public function __construct(?OutputFormatterStyleInterface $emptyStyle = null) + { + $this->emptyStyle = $emptyStyle ?? new OutputFormatterStyle(); + $this->reset(); + } + + /** + * Resets stack (ie. empty internal arrays). + */ + public function reset() + { + $this->styles = []; + } + + /** + * Pushes a style in the stack. + */ + public function push(OutputFormatterStyleInterface $style) + { + $this->styles[] = $style; + } + + /** + * Pops a style from the stack. + * + * @return OutputFormatterStyleInterface + * + * @throws InvalidArgumentException When style tags incorrectly nested + */ + public function pop(?OutputFormatterStyleInterface $style = null) + { + if (empty($this->styles)) { + return $this->emptyStyle; + } + + if (null === $style) { + return array_pop($this->styles); + } + + foreach (array_reverse($this->styles, true) as $index => $stackedStyle) { + if ($style->apply('') === $stackedStyle->apply('')) { + $this->styles = \array_slice($this->styles, 0, $index); + + return $stackedStyle; + } + } + + throw new InvalidArgumentException('Incorrectly nested style tag found.'); + } + + /** + * Computes current style with stacks top codes. + * + * @return OutputFormatterStyle + */ + public function getCurrent() + { + if (empty($this->styles)) { + return $this->emptyStyle; + } + + return $this->styles[\count($this->styles) - 1]; + } + + /** + * @return $this + */ + public function setEmptyStyle(OutputFormatterStyleInterface $emptyStyle) + { + $this->emptyStyle = $emptyStyle; + + return $this; + } + + /** + * @return OutputFormatterStyleInterface + */ + public function getEmptyStyle() + { + return $this->emptyStyle; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php b/php/libraries/composer/vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php new file mode 100644 index 0000000..42319ee --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php @@ -0,0 +1,25 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * Formatter interface for console output that supports word wrapping. + * + * @author Roland Franssen <franssen.roland@gmail.com> + */ +interface WrappableOutputFormatterInterface extends OutputFormatterInterface +{ + /** + * Formats a message according to the given styles, wrapping at `$width` (0 means no wrapping). + */ + public function formatAndWrap(?string $message, int $width); +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/DebugFormatterHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/DebugFormatterHelper.php new file mode 100644 index 0000000..e258ba0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/DebugFormatterHelper.php @@ -0,0 +1,107 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * Helps outputting debug information when running an external program from a command. + * + * An external program can be a Process, an HTTP request, or anything else. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class DebugFormatterHelper extends Helper +{ + private const COLORS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default']; + private $started = []; + private $count = -1; + + /** + * Starts a debug formatting session. + * + * @return string + */ + public function start(string $id, string $message, string $prefix = 'RUN') + { + $this->started[$id] = ['border' => ++$this->count % \count(self::COLORS)]; + + return sprintf("%s<bg=blue;fg=white> %s </> <fg=blue>%s</>\n", $this->getBorder($id), $prefix, $message); + } + + /** + * Adds progress to a formatting session. + * + * @return string + */ + public function progress(string $id, string $buffer, bool $error = false, string $prefix = 'OUT', string $errorPrefix = 'ERR') + { + $message = ''; + + if ($error) { + if (isset($this->started[$id]['out'])) { + $message .= "\n"; + unset($this->started[$id]['out']); + } + if (!isset($this->started[$id]['err'])) { + $message .= sprintf('%s<bg=red;fg=white> %s </> ', $this->getBorder($id), $errorPrefix); + $this->started[$id]['err'] = true; + } + + $message .= str_replace("\n", sprintf("\n%s<bg=red;fg=white> %s </> ", $this->getBorder($id), $errorPrefix), $buffer); + } else { + if (isset($this->started[$id]['err'])) { + $message .= "\n"; + unset($this->started[$id]['err']); + } + if (!isset($this->started[$id]['out'])) { + $message .= sprintf('%s<bg=green;fg=white> %s </> ', $this->getBorder($id), $prefix); + $this->started[$id]['out'] = true; + } + + $message .= str_replace("\n", sprintf("\n%s<bg=green;fg=white> %s </> ", $this->getBorder($id), $prefix), $buffer); + } + + return $message; + } + + /** + * Stops a formatting session. + * + * @return string + */ + public function stop(string $id, string $message, bool $successful, string $prefix = 'RES') + { + $trailingEOL = isset($this->started[$id]['out']) || isset($this->started[$id]['err']) ? "\n" : ''; + + if ($successful) { + return sprintf("%s%s<bg=green;fg=white> %s </> <fg=green>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message); + } + + $message = sprintf("%s%s<bg=red;fg=white> %s </> <fg=red>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message); + + unset($this->started[$id]['out'], $this->started[$id]['err']); + + return $message; + } + + private function getBorder(string $id): string + { + return sprintf('<bg=%s> </>', self::COLORS[$this->started[$id]['border']]); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'debug_formatter'; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/DescriptorHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/DescriptorHelper.php new file mode 100644 index 0000000..af85e9c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/DescriptorHelper.php @@ -0,0 +1,92 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Descriptor\DescriptorInterface; +use Symfony\Component\Console\Descriptor\JsonDescriptor; +use Symfony\Component\Console\Descriptor\MarkdownDescriptor; +use Symfony\Component\Console\Descriptor\TextDescriptor; +use Symfony\Component\Console\Descriptor\XmlDescriptor; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * This class adds helper method to describe objects in various formats. + * + * @author Jean-François Simon <contact@jfsimon.fr> + */ +class DescriptorHelper extends Helper +{ + /** + * @var DescriptorInterface[] + */ + private $descriptors = []; + + public function __construct() + { + $this + ->register('txt', new TextDescriptor()) + ->register('xml', new XmlDescriptor()) + ->register('json', new JsonDescriptor()) + ->register('md', new MarkdownDescriptor()) + ; + } + + /** + * Describes an object if supported. + * + * Available options are: + * * format: string, the output format name + * * raw_text: boolean, sets output type as raw + * + * @throws InvalidArgumentException when the given format is not supported + */ + public function describe(OutputInterface $output, ?object $object, array $options = []) + { + $options = array_merge([ + 'raw_text' => false, + 'format' => 'txt', + ], $options); + + if (!isset($this->descriptors[$options['format']])) { + throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format'])); + } + + $descriptor = $this->descriptors[$options['format']]; + $descriptor->describe($output, $object, $options); + } + + /** + * Registers a descriptor. + * + * @return $this + */ + public function register(string $format, DescriptorInterface $descriptor) + { + $this->descriptors[$format] = $descriptor; + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'descriptor'; + } + + public function getFormats(): array + { + return array_keys($this->descriptors); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/Dumper.php b/php/libraries/composer/vendor/symfony/console/Helper/Dumper.php new file mode 100644 index 0000000..605e4d7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/Dumper.php @@ -0,0 +1,64 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\VarDumper\Cloner\ClonerInterface; +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\CliDumper; + +/** + * @author Roland Franssen <franssen.roland@gmail.com> + */ +final class Dumper +{ + private $output; + private $dumper; + private $cloner; + private $handler; + + public function __construct(OutputInterface $output, ?CliDumper $dumper = null, ?ClonerInterface $cloner = null) + { + $this->output = $output; + $this->dumper = $dumper; + $this->cloner = $cloner; + + if (class_exists(CliDumper::class)) { + $this->handler = function ($var): string { + $dumper = $this->dumper ?? $this->dumper = new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR); + $dumper->setColors($this->output->isDecorated()); + + return rtrim($dumper->dump(($this->cloner ?? $this->cloner = new VarCloner())->cloneVar($var)->withRefHandles(false), true)); + }; + } else { + $this->handler = function ($var): string { + switch (true) { + case null === $var: + return 'null'; + case true === $var: + return 'true'; + case false === $var: + return 'false'; + case \is_string($var): + return '"'.$var.'"'; + default: + return rtrim(print_r($var, true)); + } + }; + } + } + + public function __invoke($var): string + { + return ($this->handler)($var); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/FormatterHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/FormatterHelper.php new file mode 100644 index 0000000..92d8dc7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/FormatterHelper.php @@ -0,0 +1,92 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * The Formatter class provides helpers to format messages. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class FormatterHelper extends Helper +{ + /** + * Formats a message within a section. + * + * @return string + */ + public function formatSection(string $section, string $message, string $style = 'info') + { + return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message); + } + + /** + * Formats a message as a block of text. + * + * @param string|array $messages The message to write in the block + * + * @return string + */ + public function formatBlock($messages, string $style, bool $large = false) + { + if (!\is_array($messages)) { + $messages = [$messages]; + } + + $len = 0; + $lines = []; + foreach ($messages as $message) { + $message = OutputFormatter::escape($message); + $lines[] = sprintf($large ? ' %s ' : ' %s ', $message); + $len = max(self::width($message) + ($large ? 4 : 2), $len); + } + + $messages = $large ? [str_repeat(' ', $len)] : []; + for ($i = 0; isset($lines[$i]); ++$i) { + $messages[] = $lines[$i].str_repeat(' ', $len - self::width($lines[$i])); + } + if ($large) { + $messages[] = str_repeat(' ', $len); + } + + for ($i = 0; isset($messages[$i]); ++$i) { + $messages[$i] = sprintf('<%s>%s</%s>', $style, $messages[$i], $style); + } + + return implode("\n", $messages); + } + + /** + * Truncates a message to the given length. + * + * @return string + */ + public function truncate(string $message, int $length, string $suffix = '...') + { + $computedLength = $length - self::width($suffix); + + if ($computedLength > self::width($message)) { + return $message; + } + + return self::substr($message, 0, $length).$suffix; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'formatter'; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/Helper.php b/php/libraries/composer/vendor/symfony/console/Helper/Helper.php new file mode 100644 index 0000000..6b3f7f4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/Helper.php @@ -0,0 +1,180 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\String\UnicodeString; + +/** + * Helper is the base class for all helper classes. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +abstract class Helper implements HelperInterface +{ + protected $helperSet = null; + + /** + * {@inheritdoc} + */ + public function setHelperSet(?HelperSet $helperSet = null) + { + $this->helperSet = $helperSet; + } + + /** + * {@inheritdoc} + */ + public function getHelperSet() + { + return $this->helperSet; + } + + /** + * Returns the length of a string, using mb_strwidth if it is available. + * + * @deprecated since Symfony 5.3 + * + * @return int + */ + public static function strlen(?string $string) + { + trigger_deprecation('symfony/console', '5.3', 'Method "%s()" is deprecated and will be removed in Symfony 6.0. Use Helper::width() or Helper::length() instead.', __METHOD__); + + return self::width($string); + } + + /** + * Returns the width of a string, using mb_strwidth if it is available. + * The width is how many characters positions the string will use. + */ + public static function width(?string $string): int + { + $string ?? $string = ''; + + if (preg_match('//u', $string)) { + return (new UnicodeString($string))->width(false); + } + + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return \strlen($string); + } + + return mb_strwidth($string, $encoding); + } + + /** + * Returns the length of a string, using mb_strlen if it is available. + * The length is related to how many bytes the string will use. + */ + public static function length(?string $string): int + { + $string ?? $string = ''; + + if (preg_match('//u', $string)) { + return (new UnicodeString($string))->length(); + } + + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return \strlen($string); + } + + return mb_strlen($string, $encoding); + } + + /** + * Returns the subset of a string, using mb_substr if it is available. + * + * @return string + */ + public static function substr(?string $string, int $from, ?int $length = null) + { + $string ?? $string = ''; + + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return substr($string, $from, $length); + } + + return mb_substr($string, $from, $length, $encoding); + } + + public static function formatTime($secs) + { + static $timeFormats = [ + [0, '< 1 sec'], + [1, '1 sec'], + [2, 'secs', 1], + [60, '1 min'], + [120, 'mins', 60], + [3600, '1 hr'], + [7200, 'hrs', 3600], + [86400, '1 day'], + [172800, 'days', 86400], + ]; + + foreach ($timeFormats as $index => $format) { + if ($secs >= $format[0]) { + if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0]) + || $index == \count($timeFormats) - 1 + ) { + if (2 == \count($format)) { + return $format[1]; + } + + return floor($secs / $format[2]).' '.$format[1]; + } + } + } + } + + public static function formatMemory(int $memory) + { + if ($memory >= 1024 * 1024 * 1024) { + return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024); + } + + if ($memory >= 1024 * 1024) { + return sprintf('%.1f MiB', $memory / 1024 / 1024); + } + + if ($memory >= 1024) { + return sprintf('%d KiB', $memory / 1024); + } + + return sprintf('%d B', $memory); + } + + /** + * @deprecated since Symfony 5.3 + */ + public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, ?string $string) + { + trigger_deprecation('symfony/console', '5.3', 'Method "%s()" is deprecated and will be removed in Symfony 6.0. Use Helper::removeDecoration() instead.', __METHOD__); + + return self::width(self::removeDecoration($formatter, $string)); + } + + public static function removeDecoration(OutputFormatterInterface $formatter, ?string $string) + { + $isDecorated = $formatter->isDecorated(); + $formatter->setDecorated(false); + // remove <...> formatting + $string = $formatter->format($string ?? ''); + // remove already formatted characters + $string = preg_replace("/\033\[[^m]*m/", '', $string ?? ''); + // remove terminal hyperlinks + $string = preg_replace('/\\033]8;[^;]*;[^\\033]*\\033\\\\/', '', $string ?? ''); + $formatter->setDecorated($isDecorated); + + return $string; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/HelperInterface.php b/php/libraries/composer/vendor/symfony/console/Helper/HelperInterface.php new file mode 100644 index 0000000..5bf4d63 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/HelperInterface.php @@ -0,0 +1,39 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * HelperInterface is the interface all helpers must implement. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +interface HelperInterface +{ + /** + * Sets the helper set associated with this helper. + */ + public function setHelperSet(?HelperSet $helperSet = null); + + /** + * Gets the helper set associated with this helper. + * + * @return HelperSet|null + */ + public function getHelperSet(); + + /** + * Returns the canonical name of this helper. + * + * @return string + */ + public function getName(); +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/HelperSet.php b/php/libraries/composer/vendor/symfony/console/Helper/HelperSet.php new file mode 100644 index 0000000..c870ab9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/HelperSet.php @@ -0,0 +1,108 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * HelperSet represents a set of helpers to be used with a command. + * + * @author Fabien Potencier <fabien@symfony.com> + * + * @implements \IteratorAggregate<string, Helper> + */ +class HelperSet implements \IteratorAggregate +{ + /** @var array<string, Helper> */ + private $helpers = []; + private $command; + + /** + * @param Helper[] $helpers An array of helper + */ + public function __construct(array $helpers = []) + { + foreach ($helpers as $alias => $helper) { + $this->set($helper, \is_int($alias) ? null : $alias); + } + } + + public function set(HelperInterface $helper, ?string $alias = null) + { + $this->helpers[$helper->getName()] = $helper; + if (null !== $alias) { + $this->helpers[$alias] = $helper; + } + + $helper->setHelperSet($this); + } + + /** + * Returns true if the helper if defined. + * + * @return bool + */ + public function has(string $name) + { + return isset($this->helpers[$name]); + } + + /** + * Gets a helper value. + * + * @return HelperInterface + * + * @throws InvalidArgumentException if the helper is not defined + */ + public function get(string $name) + { + if (!$this->has($name)) { + throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name)); + } + + return $this->helpers[$name]; + } + + /** + * @deprecated since Symfony 5.4 + */ + public function setCommand(?Command $command = null) + { + trigger_deprecation('symfony/console', '5.4', 'Method "%s()" is deprecated.', __METHOD__); + + $this->command = $command; + } + + /** + * Gets the command associated with this helper set. + * + * @return Command + * + * @deprecated since Symfony 5.4 + */ + public function getCommand() + { + trigger_deprecation('symfony/console', '5.4', 'Method "%s()" is deprecated.', __METHOD__); + + return $this->command; + } + + /** + * @return \Traversable<string, Helper> + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new \ArrayIterator($this->helpers); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/InputAwareHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/InputAwareHelper.php new file mode 100644 index 0000000..0d0dba2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/InputAwareHelper.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Input\InputAwareInterface; +use Symfony\Component\Console\Input\InputInterface; + +/** + * An implementation of InputAwareInterface for Helpers. + * + * @author Wouter J <waldio.webdesign@gmail.com> + */ +abstract class InputAwareHelper extends Helper implements InputAwareInterface +{ + protected $input; + + /** + * {@inheritdoc} + */ + public function setInput(InputInterface $input) + { + $this->input = $input; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/ProcessHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/ProcessHelper.php new file mode 100644 index 0000000..86a250b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/ProcessHelper.php @@ -0,0 +1,144 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Process; + +/** + * The ProcessHelper class provides helpers to run external processes. + * + * @author Fabien Potencier <fabien@symfony.com> + * + * @final + */ +class ProcessHelper extends Helper +{ + /** + * Runs an external process. + * + * @param array|Process $cmd An instance of Process or an array of the command and arguments + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + */ + public function run(OutputInterface $output, $cmd, ?string $error = null, ?callable $callback = null, int $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE): Process + { + if (!class_exists(Process::class)) { + throw new \LogicException('The ProcessHelper cannot be run as the Process component is not installed. Try running "compose require symfony/process".'); + } + + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + $formatter = $this->getHelperSet()->get('debug_formatter'); + + if ($cmd instanceof Process) { + $cmd = [$cmd]; + } + + if (!\is_array($cmd)) { + throw new \TypeError(sprintf('The "command" argument of "%s()" must be an array or a "%s" instance, "%s" given.', __METHOD__, Process::class, get_debug_type($cmd))); + } + + if (\is_string($cmd[0] ?? null)) { + $process = new Process($cmd); + $cmd = []; + } elseif (($cmd[0] ?? null) instanceof Process) { + $process = $cmd[0]; + unset($cmd[0]); + } else { + throw new \InvalidArgumentException(sprintf('Invalid command provided to "%s()": the command should be an array whose first element is either the path to the binary to run or a "Process" object.', __METHOD__)); + } + + if ($verbosity <= $output->getVerbosity()) { + $output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine()))); + } + + if ($output->isDebug()) { + $callback = $this->wrapCallback($output, $process, $callback); + } + + $process->run($callback, $cmd); + + if ($verbosity <= $output->getVerbosity()) { + $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode()); + $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful())); + } + + if (!$process->isSuccessful() && null !== $error) { + $output->writeln(sprintf('<error>%s</error>', $this->escapeString($error))); + } + + return $process; + } + + /** + * Runs the process. + * + * This is identical to run() except that an exception is thrown if the process + * exits with a non-zero exit code. + * + * @param array|Process $cmd An instance of Process or a command to run + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @throws ProcessFailedException + * + * @see run() + */ + public function mustRun(OutputInterface $output, $cmd, ?string $error = null, ?callable $callback = null): Process + { + $process = $this->run($output, $cmd, $error, $callback); + + if (!$process->isSuccessful()) { + throw new ProcessFailedException($process); + } + + return $process; + } + + /** + * Wraps a Process callback to add debugging output. + */ + public function wrapCallback(OutputInterface $output, Process $process, ?callable $callback = null): callable + { + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + $formatter = $this->getHelperSet()->get('debug_formatter'); + + return function ($type, $buffer) use ($output, $process, $callback, $formatter) { + $output->write($formatter->progress(spl_object_hash($process), $this->escapeString($buffer), Process::ERR === $type)); + + if (null !== $callback) { + $callback($type, $buffer); + } + }; + } + + private function escapeString(string $str): string + { + return str_replace('<', '\\<', $str); + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'process'; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/ProgressBar.php b/php/libraries/composer/vendor/symfony/console/Helper/ProgressBar.php new file mode 100644 index 0000000..1d7b8d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/ProgressBar.php @@ -0,0 +1,609 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Cursor; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Terminal; + +/** + * The ProgressBar provides helpers to display progress output. + * + * @author Fabien Potencier <fabien@symfony.com> + * @author Chris Jones <leeked@gmail.com> + */ +final class ProgressBar +{ + public const FORMAT_VERBOSE = 'verbose'; + public const FORMAT_VERY_VERBOSE = 'very_verbose'; + public const FORMAT_DEBUG = 'debug'; + public const FORMAT_NORMAL = 'normal'; + + private const FORMAT_VERBOSE_NOMAX = 'verbose_nomax'; + private const FORMAT_VERY_VERBOSE_NOMAX = 'very_verbose_nomax'; + private const FORMAT_DEBUG_NOMAX = 'debug_nomax'; + private const FORMAT_NORMAL_NOMAX = 'normal_nomax'; + + private $barWidth = 28; + private $barChar; + private $emptyBarChar = '-'; + private $progressChar = '>'; + private $format; + private $internalFormat; + private $redrawFreq = 1; + private $writeCount; + private $lastWriteTime; + private $minSecondsBetweenRedraws = 0; + private $maxSecondsBetweenRedraws = 1; + private $output; + private $step = 0; + private $max; + private $startTime; + private $stepWidth; + private $percent = 0.0; + private $messages = []; + private $overwrite = true; + private $terminal; + private $previousMessage; + private $cursor; + + private static $formatters; + private static $formats; + + /** + * @param int $max Maximum steps (0 if unknown) + */ + public function __construct(OutputInterface $output, int $max = 0, float $minSecondsBetweenRedraws = 1 / 25) + { + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + $this->output = $output; + $this->setMaxSteps($max); + $this->terminal = new Terminal(); + + if (0 < $minSecondsBetweenRedraws) { + $this->redrawFreq = null; + $this->minSecondsBetweenRedraws = $minSecondsBetweenRedraws; + } + + if (!$this->output->isDecorated()) { + // disable overwrite when output does not support ANSI codes. + $this->overwrite = false; + + // set a reasonable redraw frequency so output isn't flooded + $this->redrawFreq = null; + } + + $this->startTime = time(); + $this->cursor = new Cursor($output); + } + + /** + * Sets a placeholder formatter for a given name. + * + * This method also allow you to override an existing placeholder. + * + * @param string $name The placeholder name (including the delimiter char like %) + * @param callable $callable A PHP callable + */ + public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void + { + if (!self::$formatters) { + self::$formatters = self::initPlaceholderFormatters(); + } + + self::$formatters[$name] = $callable; + } + + /** + * Gets the placeholder formatter for a given name. + * + * @param string $name The placeholder name (including the delimiter char like %) + */ + public static function getPlaceholderFormatterDefinition(string $name): ?callable + { + if (!self::$formatters) { + self::$formatters = self::initPlaceholderFormatters(); + } + + return self::$formatters[$name] ?? null; + } + + /** + * Sets a format for a given name. + * + * This method also allow you to override an existing format. + * + * @param string $name The format name + * @param string $format A format string + */ + public static function setFormatDefinition(string $name, string $format): void + { + if (!self::$formats) { + self::$formats = self::initFormats(); + } + + self::$formats[$name] = $format; + } + + /** + * Gets the format for a given name. + * + * @param string $name The format name + */ + public static function getFormatDefinition(string $name): ?string + { + if (!self::$formats) { + self::$formats = self::initFormats(); + } + + return self::$formats[$name] ?? null; + } + + /** + * Associates a text with a named placeholder. + * + * The text is displayed when the progress bar is rendered but only + * when the corresponding placeholder is part of the custom format line + * (by wrapping the name with %). + * + * @param string $message The text to associate with the placeholder + * @param string $name The name of the placeholder + */ + public function setMessage(string $message, string $name = 'message') + { + $this->messages[$name] = $message; + } + + public function getMessage(string $name = 'message') + { + return $this->messages[$name]; + } + + public function getStartTime(): int + { + return $this->startTime; + } + + public function getMaxSteps(): int + { + return $this->max; + } + + public function getProgress(): int + { + return $this->step; + } + + private function getStepWidth(): int + { + return $this->stepWidth; + } + + public function getProgressPercent(): float + { + return $this->percent; + } + + public function getBarOffset(): float + { + return floor($this->max ? $this->percent * $this->barWidth : (null === $this->redrawFreq ? (int) (min(5, $this->barWidth / 15) * $this->writeCount) : $this->step) % $this->barWidth); + } + + public function getEstimated(): float + { + if (!$this->step) { + return 0; + } + + return round((time() - $this->startTime) / $this->step * $this->max); + } + + public function getRemaining(): float + { + if (!$this->step) { + return 0; + } + + return round((time() - $this->startTime) / $this->step * ($this->max - $this->step)); + } + + public function setBarWidth(int $size) + { + $this->barWidth = max(1, $size); + } + + public function getBarWidth(): int + { + return $this->barWidth; + } + + public function setBarCharacter(string $char) + { + $this->barChar = $char; + } + + public function getBarCharacter(): string + { + return $this->barChar ?? ($this->max ? '=' : $this->emptyBarChar); + } + + public function setEmptyBarCharacter(string $char) + { + $this->emptyBarChar = $char; + } + + public function getEmptyBarCharacter(): string + { + return $this->emptyBarChar; + } + + public function setProgressCharacter(string $char) + { + $this->progressChar = $char; + } + + public function getProgressCharacter(): string + { + return $this->progressChar; + } + + public function setFormat(string $format) + { + $this->format = null; + $this->internalFormat = $format; + } + + /** + * Sets the redraw frequency. + * + * @param int|null $freq The frequency in steps + */ + public function setRedrawFrequency(?int $freq) + { + $this->redrawFreq = null !== $freq ? max(1, $freq) : null; + } + + public function minSecondsBetweenRedraws(float $seconds): void + { + $this->minSecondsBetweenRedraws = $seconds; + } + + public function maxSecondsBetweenRedraws(float $seconds): void + { + $this->maxSecondsBetweenRedraws = $seconds; + } + + /** + * Returns an iterator that will automatically update the progress bar when iterated. + * + * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable + */ + public function iterate(iterable $iterable, ?int $max = null): iterable + { + $this->start($max ?? (is_countable($iterable) ? \count($iterable) : 0)); + + foreach ($iterable as $key => $value) { + yield $key => $value; + + $this->advance(); + } + + $this->finish(); + } + + /** + * Starts the progress output. + * + * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged + */ + public function start(?int $max = null) + { + $this->startTime = time(); + $this->step = 0; + $this->percent = 0.0; + + if (null !== $max) { + $this->setMaxSteps($max); + } + + $this->display(); + } + + /** + * Advances the progress output X steps. + * + * @param int $step Number of steps to advance + */ + public function advance(int $step = 1) + { + $this->setProgress($this->step + $step); + } + + /** + * Sets whether to overwrite the progressbar, false for new line. + */ + public function setOverwrite(bool $overwrite) + { + $this->overwrite = $overwrite; + } + + public function setProgress(int $step) + { + if ($this->max && $step > $this->max) { + $this->max = $step; + } elseif ($step < 0) { + $step = 0; + } + + $redrawFreq = $this->redrawFreq ?? (($this->max ?: 10) / 10); + $prevPeriod = (int) ($this->step / $redrawFreq); + $currPeriod = (int) ($step / $redrawFreq); + $this->step = $step; + $this->percent = $this->max ? (float) $this->step / $this->max : 0; + $timeInterval = microtime(true) - $this->lastWriteTime; + + // Draw regardless of other limits + if ($this->max === $step) { + $this->display(); + + return; + } + + // Throttling + if ($timeInterval < $this->minSecondsBetweenRedraws) { + return; + } + + // Draw each step period, but not too late + if ($prevPeriod !== $currPeriod || $timeInterval >= $this->maxSecondsBetweenRedraws) { + $this->display(); + } + } + + public function setMaxSteps(int $max) + { + $this->format = null; + $this->max = max(0, $max); + $this->stepWidth = $this->max ? Helper::width((string) $this->max) : 4; + } + + /** + * Finishes the progress output. + */ + public function finish(): void + { + if (!$this->max) { + $this->max = $this->step; + } + + if ($this->step === $this->max && !$this->overwrite) { + // prevent double 100% output + return; + } + + $this->setProgress($this->max); + } + + /** + * Outputs the current progress string. + */ + public function display(): void + { + if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) { + return; + } + + if (null === $this->format) { + $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat()); + } + + $this->overwrite($this->buildLine()); + } + + /** + * Removes the progress bar from the current line. + * + * This is useful if you wish to write some output + * while a progress bar is running. + * Call display() to show the progress bar again. + */ + public function clear(): void + { + if (!$this->overwrite) { + return; + } + + if (null === $this->format) { + $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat()); + } + + $this->overwrite(''); + } + + private function setRealFormat(string $format) + { + // try to use the _nomax variant if available + if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) { + $this->format = self::getFormatDefinition($format.'_nomax'); + } elseif (null !== self::getFormatDefinition($format)) { + $this->format = self::getFormatDefinition($format); + } else { + $this->format = $format; + } + } + + /** + * Overwrites a previous message to the output. + */ + private function overwrite(string $message): void + { + if ($this->previousMessage === $message) { + return; + } + + $originalMessage = $message; + + if ($this->overwrite) { + if (null !== $this->previousMessage) { + if ($this->output instanceof ConsoleSectionOutput) { + $messageLines = explode("\n", $this->previousMessage); + $lineCount = \count($messageLines); + foreach ($messageLines as $messageLine) { + $messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $messageLine)); + if ($messageLineLength > $this->terminal->getWidth()) { + $lineCount += floor($messageLineLength / $this->terminal->getWidth()); + } + } + $this->output->clear($lineCount); + } else { + $lineCount = substr_count($this->previousMessage, "\n"); + for ($i = 0; $i < $lineCount; ++$i) { + $this->cursor->moveToColumn(1); + $this->cursor->clearLine(); + $this->cursor->moveUp(); + } + + $this->cursor->moveToColumn(1); + $this->cursor->clearLine(); + } + } + } elseif ($this->step > 0) { + $message = \PHP_EOL.$message; + } + + $this->previousMessage = $originalMessage; + $this->lastWriteTime = microtime(true); + + $this->output->write($message); + ++$this->writeCount; + } + + private function determineBestFormat(): string + { + switch ($this->output->getVerbosity()) { + // OutputInterface::VERBOSITY_QUIET: display is disabled anyway + case OutputInterface::VERBOSITY_VERBOSE: + return $this->max ? self::FORMAT_VERBOSE : self::FORMAT_VERBOSE_NOMAX; + case OutputInterface::VERBOSITY_VERY_VERBOSE: + return $this->max ? self::FORMAT_VERY_VERBOSE : self::FORMAT_VERY_VERBOSE_NOMAX; + case OutputInterface::VERBOSITY_DEBUG: + return $this->max ? self::FORMAT_DEBUG : self::FORMAT_DEBUG_NOMAX; + default: + return $this->max ? self::FORMAT_NORMAL : self::FORMAT_NORMAL_NOMAX; + } + } + + private static function initPlaceholderFormatters(): array + { + return [ + 'bar' => function (self $bar, OutputInterface $output) { + $completeBars = $bar->getBarOffset(); + $display = str_repeat($bar->getBarCharacter(), $completeBars); + if ($completeBars < $bar->getBarWidth()) { + $emptyBars = $bar->getBarWidth() - $completeBars - Helper::length(Helper::removeDecoration($output->getFormatter(), $bar->getProgressCharacter())); + $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars); + } + + return $display; + }, + 'elapsed' => function (self $bar) { + return Helper::formatTime(time() - $bar->getStartTime()); + }, + 'remaining' => function (self $bar) { + if (!$bar->getMaxSteps()) { + throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.'); + } + + return Helper::formatTime($bar->getRemaining()); + }, + 'estimated' => function (self $bar) { + if (!$bar->getMaxSteps()) { + throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.'); + } + + return Helper::formatTime($bar->getEstimated()); + }, + 'memory' => function (self $bar) { + return Helper::formatMemory(memory_get_usage(true)); + }, + 'current' => function (self $bar) { + return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', \STR_PAD_LEFT); + }, + 'max' => function (self $bar) { + return $bar->getMaxSteps(); + }, + 'percent' => function (self $bar) { + return floor($bar->getProgressPercent() * 100); + }, + ]; + } + + private static function initFormats(): array + { + return [ + self::FORMAT_NORMAL => ' %current%/%max% [%bar%] %percent:3s%%', + self::FORMAT_NORMAL_NOMAX => ' %current% [%bar%]', + + self::FORMAT_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%', + self::FORMAT_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%', + + self::FORMAT_VERY_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%', + self::FORMAT_VERY_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%', + + self::FORMAT_DEBUG => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%', + self::FORMAT_DEBUG_NOMAX => ' %current% [%bar%] %elapsed:6s% %memory:6s%', + ]; + } + + private function buildLine(): string + { + $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i"; + $callback = function ($matches) { + if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) { + $text = $formatter($this, $this->output); + } elseif (isset($this->messages[$matches[1]])) { + $text = $this->messages[$matches[1]]; + } else { + return $matches[0]; + } + + if (isset($matches[2])) { + $text = sprintf('%'.$matches[2], $text); + } + + return $text; + }; + $line = preg_replace_callback($regex, $callback, $this->format); + + // gets string length for each sub line with multiline format + $linesLength = array_map(function ($subLine) { + return Helper::width(Helper::removeDecoration($this->output->getFormatter(), rtrim($subLine, "\r"))); + }, explode("\n", $line)); + + $linesWidth = max($linesLength); + + $terminalWidth = $this->terminal->getWidth(); + if ($linesWidth <= $terminalWidth) { + return $line; + } + + $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth); + + return preg_replace_callback($regex, $callback, $this->format); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/ProgressIndicator.php b/php/libraries/composer/vendor/symfony/console/Helper/ProgressIndicator.php new file mode 100644 index 0000000..3cc0e14 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/ProgressIndicator.php @@ -0,0 +1,247 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Kevin Bond <kevinbond@gmail.com> + */ +class ProgressIndicator +{ + private const FORMATS = [ + 'normal' => ' %indicator% %message%', + 'normal_no_ansi' => ' %message%', + + 'verbose' => ' %indicator% %message% (%elapsed:6s%)', + 'verbose_no_ansi' => ' %message% (%elapsed:6s%)', + + 'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)', + 'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)', + ]; + + private $output; + private $startTime; + private $format; + private $message; + private $indicatorValues; + private $indicatorCurrent; + private $indicatorChangeInterval; + private $indicatorUpdateTime; + private $started = false; + + /** + * @var array<string, callable> + */ + private static $formatters; + + /** + * @param int $indicatorChangeInterval Change interval in milliseconds + * @param array|null $indicatorValues Animated indicator characters + */ + public function __construct(OutputInterface $output, ?string $format = null, int $indicatorChangeInterval = 100, ?array $indicatorValues = null) + { + $this->output = $output; + + if (null === $format) { + $format = $this->determineBestFormat(); + } + + if (null === $indicatorValues) { + $indicatorValues = ['-', '\\', '|', '/']; + } + + $indicatorValues = array_values($indicatorValues); + + if (2 > \count($indicatorValues)) { + throw new InvalidArgumentException('Must have at least 2 indicator value characters.'); + } + + $this->format = self::getFormatDefinition($format); + $this->indicatorChangeInterval = $indicatorChangeInterval; + $this->indicatorValues = $indicatorValues; + $this->startTime = time(); + } + + /** + * Sets the current indicator message. + */ + public function setMessage(?string $message) + { + $this->message = $message; + + $this->display(); + } + + /** + * Starts the indicator output. + */ + public function start(string $message) + { + if ($this->started) { + throw new LogicException('Progress indicator already started.'); + } + + $this->message = $message; + $this->started = true; + $this->startTime = time(); + $this->indicatorUpdateTime = $this->getCurrentTimeInMilliseconds() + $this->indicatorChangeInterval; + $this->indicatorCurrent = 0; + + $this->display(); + } + + /** + * Advances the indicator. + */ + public function advance() + { + if (!$this->started) { + throw new LogicException('Progress indicator has not yet been started.'); + } + + if (!$this->output->isDecorated()) { + return; + } + + $currentTime = $this->getCurrentTimeInMilliseconds(); + + if ($currentTime < $this->indicatorUpdateTime) { + return; + } + + $this->indicatorUpdateTime = $currentTime + $this->indicatorChangeInterval; + ++$this->indicatorCurrent; + + $this->display(); + } + + /** + * Finish the indicator with message. + */ + public function finish(string $message) + { + if (!$this->started) { + throw new LogicException('Progress indicator has not yet been started.'); + } + + $this->message = $message; + $this->display(); + $this->output->writeln(''); + $this->started = false; + } + + /** + * Gets the format for a given name. + * + * @return string|null + */ + public static function getFormatDefinition(string $name) + { + return self::FORMATS[$name] ?? null; + } + + /** + * Sets a placeholder formatter for a given name. + * + * This method also allow you to override an existing placeholder. + */ + public static function setPlaceholderFormatterDefinition(string $name, callable $callable) + { + if (!self::$formatters) { + self::$formatters = self::initPlaceholderFormatters(); + } + + self::$formatters[$name] = $callable; + } + + /** + * Gets the placeholder formatter for a given name (including the delimiter char like %). + * + * @return callable|null + */ + public static function getPlaceholderFormatterDefinition(string $name) + { + if (!self::$formatters) { + self::$formatters = self::initPlaceholderFormatters(); + } + + return self::$formatters[$name] ?? null; + } + + private function display() + { + if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) { + return; + } + + $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) { + if ($formatter = self::getPlaceholderFormatterDefinition($matches[1])) { + return $formatter($this); + } + + return $matches[0]; + }, $this->format ?? '')); + } + + private function determineBestFormat(): string + { + switch ($this->output->getVerbosity()) { + // OutputInterface::VERBOSITY_QUIET: display is disabled anyway + case OutputInterface::VERBOSITY_VERBOSE: + return $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi'; + case OutputInterface::VERBOSITY_VERY_VERBOSE: + case OutputInterface::VERBOSITY_DEBUG: + return $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi'; + default: + return $this->output->isDecorated() ? 'normal' : 'normal_no_ansi'; + } + } + + /** + * Overwrites a previous message to the output. + */ + private function overwrite(string $message) + { + if ($this->output->isDecorated()) { + $this->output->write("\x0D\x1B[2K"); + $this->output->write($message); + } else { + $this->output->writeln($message); + } + } + + private function getCurrentTimeInMilliseconds(): float + { + return round(microtime(true) * 1000); + } + + private static function initPlaceholderFormatters(): array + { + return [ + 'indicator' => function (self $indicator) { + return $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)]; + }, + 'message' => function (self $indicator) { + return $indicator->message; + }, + 'elapsed' => function (self $indicator) { + return Helper::formatTime(time() - $indicator->startTime); + }, + 'memory' => function () { + return Helper::formatMemory(memory_get_usage(true)); + }, + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/QuestionHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/QuestionHelper.php new file mode 100644 index 0000000..7b9de92 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/QuestionHelper.php @@ -0,0 +1,613 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Cursor; +use Symfony\Component\Console\Exception\MissingInputException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterStyle; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\StreamableInputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Terminal; + +use function Symfony\Component\String\s; + +/** + * The QuestionHelper class provides helpers to interact with the user. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class QuestionHelper extends Helper +{ + /** + * @var resource|null + */ + private $inputStream; + + private static $stty = true; + private static $stdinIsInteractive; + + /** + * Asks a question to the user. + * + * @return mixed The user answer + * + * @throws RuntimeException If there is no data to read in the input stream + */ + public function ask(InputInterface $input, OutputInterface $output, Question $question) + { + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + if (!$input->isInteractive()) { + return $this->getDefaultAnswer($question); + } + + if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) { + $this->inputStream = $stream; + } + + try { + if (!$question->getValidator()) { + return $this->doAsk($output, $question); + } + + $interviewer = function () use ($output, $question) { + return $this->doAsk($output, $question); + }; + + return $this->validateAttempts($interviewer, $output, $question); + } catch (MissingInputException $exception) { + $input->setInteractive(false); + + if (null === $fallbackOutput = $this->getDefaultAnswer($question)) { + throw $exception; + } + + return $fallbackOutput; + } + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'question'; + } + + /** + * Prevents usage of stty. + */ + public static function disableStty() + { + self::$stty = false; + } + + /** + * Asks the question to the user. + * + * @return mixed + * + * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden + */ + private function doAsk(OutputInterface $output, Question $question) + { + $this->writePrompt($output, $question); + + $inputStream = $this->inputStream ?: \STDIN; + $autocomplete = $question->getAutocompleterCallback(); + + if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) { + $ret = false; + if ($question->isHidden()) { + try { + $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable()); + $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse; + } catch (RuntimeException $e) { + if (!$question->isHiddenFallback()) { + throw $e; + } + } + } + + if (false === $ret) { + $isBlocked = stream_get_meta_data($inputStream)['blocked'] ?? true; + + if (!$isBlocked) { + stream_set_blocking($inputStream, true); + } + + $ret = $this->readInput($inputStream, $question); + + if (!$isBlocked) { + stream_set_blocking($inputStream, false); + } + + if (false === $ret) { + throw new MissingInputException('Aborted.'); + } + if ($question->isTrimmable()) { + $ret = trim($ret); + } + } + } else { + $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete); + $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete; + } + + if ($output instanceof ConsoleSectionOutput) { + $output->addContent($ret); + } + + $ret = \strlen($ret) > 0 ? $ret : $question->getDefault(); + + if ($normalizer = $question->getNormalizer()) { + return $normalizer($ret); + } + + return $ret; + } + + /** + * @return mixed + */ + private function getDefaultAnswer(Question $question) + { + $default = $question->getDefault(); + + if (null === $default) { + return $default; + } + + if ($validator = $question->getValidator()) { + return \call_user_func($question->getValidator(), $default); + } elseif ($question instanceof ChoiceQuestion) { + $choices = $question->getChoices(); + + if (!$question->isMultiselect()) { + return $choices[$default] ?? $default; + } + + $default = explode(',', $default); + foreach ($default as $k => $v) { + $v = $question->isTrimmable() ? trim($v) : $v; + $default[$k] = $choices[$v] ?? $v; + } + } + + return $default; + } + + /** + * Outputs the question prompt. + */ + protected function writePrompt(OutputInterface $output, Question $question) + { + $message = $question->getQuestion(); + + if ($question instanceof ChoiceQuestion) { + $output->writeln(array_merge([ + $question->getQuestion(), + ], $this->formatChoiceQuestionChoices($question, 'info'))); + + $message = $question->getPrompt(); + } + + $output->write($message); + } + + /** + * @return string[] + */ + protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag) + { + $messages = []; + + $maxWidth = max(array_map([__CLASS__, 'width'], array_keys($choices = $question->getChoices()))); + + foreach ($choices as $key => $value) { + $padding = str_repeat(' ', $maxWidth - self::width($key)); + + $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value); + } + + return $messages; + } + + /** + * Outputs an error message. + */ + protected function writeError(OutputInterface $output, \Exception $error) + { + if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) { + $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'); + } else { + $message = '<error>'.$error->getMessage().'</error>'; + } + + $output->writeln($message); + } + + /** + * Autocompletes a question. + * + * @param resource $inputStream + */ + private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string + { + $cursor = new Cursor($output, $inputStream); + + $fullChoice = ''; + $ret = ''; + + $i = 0; + $ofs = -1; + $matches = $autocomplete($ret); + $numMatches = \count($matches); + + $sttyMode = shell_exec('stty -g'); + $isStdin = 'php://stdin' === (stream_get_meta_data($inputStream)['uri'] ?? null); + $r = [$inputStream]; + $w = []; + + // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead) + shell_exec('stty -icanon -echo'); + + // Add highlighted text style + $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white')); + + // Read a keypress + while (!feof($inputStream)) { + while ($isStdin && 0 === @stream_select($r, $w, $w, 0, 100)) { + // Give signal handlers a chance to run + $r = [$inputStream]; + } + $c = fread($inputStream, 1); + + // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false. + if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) { + shell_exec('stty '.$sttyMode); + throw new MissingInputException('Aborted.'); + } elseif ("\177" === $c) { // Backspace Character + if (0 === $numMatches && 0 !== $i) { + --$i; + $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false)); + + $fullChoice = self::substr($fullChoice, 0, $i); + } + + if (0 === $i) { + $ofs = -1; + $matches = $autocomplete($ret); + $numMatches = \count($matches); + } else { + $numMatches = 0; + } + + // Pop the last character off the end of our string + $ret = self::substr($ret, 0, $i); + } elseif ("\033" === $c) { + // Did we read an escape sequence? + $c .= fread($inputStream, 2); + + // A = Up Arrow. B = Down Arrow + if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) { + if ('A' === $c[2] && -1 === $ofs) { + $ofs = 0; + } + + if (0 === $numMatches) { + continue; + } + + $ofs += ('A' === $c[2]) ? -1 : 1; + $ofs = ($numMatches + $ofs) % $numMatches; + } + } elseif (\ord($c) < 32) { + if ("\t" === $c || "\n" === $c) { + if ($numMatches > 0 && -1 !== $ofs) { + $ret = (string) $matches[$ofs]; + // Echo out remaining chars for current match + $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)))); + $output->write($remainingCharacters); + $fullChoice .= $remainingCharacters; + $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding); + + $matches = array_filter( + $autocomplete($ret), + function ($match) use ($ret) { + return '' === $ret || str_starts_with($match, $ret); + } + ); + $numMatches = \count($matches); + $ofs = -1; + } + + if ("\n" === $c) { + $output->write($c); + break; + } + + $numMatches = 0; + } + + continue; + } else { + if ("\x80" <= $c) { + $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]); + } + + $output->write($c); + $ret .= $c; + $fullChoice .= $c; + ++$i; + + $tempRet = $ret; + + if ($question instanceof ChoiceQuestion && $question->isMultiselect()) { + $tempRet = $this->mostRecentlyEnteredValue($fullChoice); + } + + $numMatches = 0; + $ofs = 0; + + foreach ($autocomplete($ret) as $value) { + // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle) + if (str_starts_with($value, $tempRet)) { + $matches[$numMatches++] = $value; + } + } + } + + $cursor->clearLineAfter(); + + if ($numMatches > 0 && -1 !== $ofs) { + $cursor->savePosition(); + // Write highlighted text, complete the partially entered response + $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))); + $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>'); + $cursor->restorePosition(); + } + } + + // Reset stty so it behaves normally again + shell_exec('stty '.$sttyMode); + + return $fullChoice; + } + + private function mostRecentlyEnteredValue(string $entered): string + { + // Determine the most recent value that the user entered + if (!str_contains($entered, ',')) { + return $entered; + } + + $choices = explode(',', $entered); + if ('' !== $lastChoice = trim($choices[\count($choices) - 1])) { + return $lastChoice; + } + + return $entered; + } + + /** + * Gets a hidden response from user. + * + * @param resource $inputStream The handler resource + * @param bool $trimmable Is the answer trimmable + * + * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden + */ + private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $exe = __DIR__.'/../Resources/bin/hiddeninput.exe'; + + // handle code running from a phar + if ('phar:' === substr(__FILE__, 0, 5)) { + $tmpExe = sys_get_temp_dir().'/hiddeninput.exe'; + copy($exe, $tmpExe); + $exe = $tmpExe; + } + + $sExec = shell_exec('"'.$exe.'"'); + $value = $trimmable ? rtrim($sExec) : $sExec; + $output->writeln(''); + + if (isset($tmpExe)) { + unlink($tmpExe); + } + + return $value; + } + + if (self::$stty && Terminal::hasSttyAvailable()) { + $sttyMode = shell_exec('stty -g'); + shell_exec('stty -echo'); + } elseif ($this->isInteractiveInput($inputStream)) { + throw new RuntimeException('Unable to hide the response.'); + } + + $value = fgets($inputStream, 4096); + + if (self::$stty && Terminal::hasSttyAvailable()) { + shell_exec('stty '.$sttyMode); + } + + if (false === $value) { + throw new MissingInputException('Aborted.'); + } + if ($trimmable) { + $value = trim($value); + } + $output->writeln(''); + + return $value; + } + + /** + * Validates an attempt. + * + * @param callable $interviewer A callable that will ask for a question and return the result + * + * @return mixed The validated response + * + * @throws \Exception In case the max number of attempts has been reached and no valid response has been given + */ + private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question) + { + $error = null; + $attempts = $question->getMaxAttempts(); + + while (null === $attempts || $attempts--) { + if (null !== $error) { + $this->writeError($output, $error); + } + + try { + return $question->getValidator()($interviewer()); + } catch (RuntimeException $e) { + throw $e; + } catch (\Exception $error) { + } + } + + throw $error; + } + + private function isInteractiveInput($inputStream): bool + { + if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) { + return false; + } + + if (null !== self::$stdinIsInteractive) { + return self::$stdinIsInteractive; + } + + return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r')); + } + + /** + * Reads one or more lines of input and returns what is read. + * + * @param resource $inputStream The handler resource + * @param Question $question The question being asked + * + * @return string|false The input received, false in case input could not be read + */ + private function readInput($inputStream, Question $question) + { + if (!$question->isMultiline()) { + $cp = $this->setIOCodepage(); + $ret = fgets($inputStream, 4096); + + return $this->resetIOCodepage($cp, $ret); + } + + $multiLineStreamReader = $this->cloneInputStream($inputStream); + if (null === $multiLineStreamReader) { + return false; + } + + $ret = ''; + $cp = $this->setIOCodepage(); + while (false !== ($char = fgetc($multiLineStreamReader))) { + if (\PHP_EOL === "{$ret}{$char}") { + break; + } + $ret .= $char; + } + + return $this->resetIOCodepage($cp, $ret); + } + + /** + * Sets console I/O to the host code page. + * + * @return int Previous code page in IBM/EBCDIC format + */ + private function setIOCodepage(): int + { + if (\function_exists('sapi_windows_cp_set')) { + $cp = sapi_windows_cp_get(); + sapi_windows_cp_set(sapi_windows_cp_get('oem')); + + return $cp; + } + + return 0; + } + + /** + * Sets console I/O to the specified code page and converts the user input. + * + * @param string|false $input + * + * @return string|false + */ + private function resetIOCodepage(int $cp, $input) + { + if (0 !== $cp) { + sapi_windows_cp_set($cp); + + if (false !== $input && '' !== $input) { + $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input); + } + } + + return $input; + } + + /** + * Clones an input stream in order to act on one instance of the same + * stream without affecting the other instance. + * + * @param resource $inputStream The handler resource + * + * @return resource|null The cloned resource, null in case it could not be cloned + */ + private function cloneInputStream($inputStream) + { + $streamMetaData = stream_get_meta_data($inputStream); + $seekable = $streamMetaData['seekable'] ?? false; + $mode = $streamMetaData['mode'] ?? 'rb'; + $uri = $streamMetaData['uri'] ?? null; + + if (null === $uri) { + return null; + } + + $cloneStream = fopen($uri, $mode); + + // For seekable and writable streams, add all the same data to the + // cloned stream and then seek to the same offset. + if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'])) { + $offset = ftell($inputStream); + rewind($inputStream); + stream_copy_to_stream($inputStream, $cloneStream); + fseek($inputStream, $offset); + fseek($cloneStream, $offset); + } + + return $cloneStream; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/SymfonyQuestionHelper.php b/php/libraries/composer/vendor/symfony/console/Helper/SymfonyQuestionHelper.php new file mode 100644 index 0000000..01f94ab --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/SymfonyQuestionHelper.php @@ -0,0 +1,109 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Question\ConfirmationQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Style\SymfonyStyle; + +/** + * Symfony Style Guide compliant question helper. + * + * @author Kevin Bond <kevinbond@gmail.com> + */ +class SymfonyQuestionHelper extends QuestionHelper +{ + /** + * {@inheritdoc} + */ + protected function writePrompt(OutputInterface $output, Question $question) + { + $text = OutputFormatter::escapeTrailingBackslash($question->getQuestion()); + $default = $question->getDefault(); + + if ($question->isMultiline()) { + $text .= sprintf(' (press %s to continue)', $this->getEofShortcut()); + } + + switch (true) { + case null === $default: + $text = sprintf(' <info>%s</info>:', $text); + + break; + + case $question instanceof ConfirmationQuestion: + $text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no'); + + break; + + case $question instanceof ChoiceQuestion && $question->isMultiselect(): + $choices = $question->getChoices(); + $default = explode(',', $default); + + foreach ($default as $key => $value) { + $default[$key] = $choices[trim($value)]; + } + + $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape(implode(', ', $default))); + + break; + + case $question instanceof ChoiceQuestion: + $choices = $question->getChoices(); + $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($choices[$default] ?? $default)); + + break; + + default: + $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($default)); + } + + $output->writeln($text); + + $prompt = ' > '; + + if ($question instanceof ChoiceQuestion) { + $output->writeln($this->formatChoiceQuestionChoices($question, 'comment')); + + $prompt = $question->getPrompt(); + } + + $output->write($prompt); + } + + /** + * {@inheritdoc} + */ + protected function writeError(OutputInterface $output, \Exception $error) + { + if ($output instanceof SymfonyStyle) { + $output->newLine(); + $output->error($error->getMessage()); + + return; + } + + parent::writeError($output, $error); + } + + private function getEofShortcut(): string + { + if ('Windows' === \PHP_OS_FAMILY) { + return '<comment>Ctrl+Z</comment> then <comment>Enter</comment>'; + } + + return '<comment>Ctrl+D</comment>'; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/Table.php b/php/libraries/composer/vendor/symfony/console/Helper/Table.php new file mode 100644 index 0000000..698f969 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/Table.php @@ -0,0 +1,917 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Provides helpers to display a table. + * + * @author Fabien Potencier <fabien@symfony.com> + * @author Саша Стаменковић <umpirsky@gmail.com> + * @author Abdellatif Ait boudad <a.aitboudad@gmail.com> + * @author Max Grigorian <maxakawizard@gmail.com> + * @author Dany Maillard <danymaillard93b@gmail.com> + */ +class Table +{ + private const SEPARATOR_TOP = 0; + private const SEPARATOR_TOP_BOTTOM = 1; + private const SEPARATOR_MID = 2; + private const SEPARATOR_BOTTOM = 3; + private const BORDER_OUTSIDE = 0; + private const BORDER_INSIDE = 1; + + private $headerTitle; + private $footerTitle; + + /** + * Table headers. + */ + private $headers = []; + + /** + * Table rows. + */ + private $rows = []; + private $horizontal = false; + + /** + * Column widths cache. + */ + private $effectiveColumnWidths = []; + + /** + * Number of columns cache. + * + * @var int + */ + private $numberOfColumns; + + /** + * @var OutputInterface + */ + private $output; + + /** + * @var TableStyle + */ + private $style; + + /** + * @var array + */ + private $columnStyles = []; + + /** + * User set column widths. + * + * @var array + */ + private $columnWidths = []; + private $columnMaxWidths = []; + + /** + * @var array<string, TableStyle>|null + */ + private static $styles; + + private $rendered = false; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + + if (!self::$styles) { + self::$styles = self::initStyles(); + } + + $this->setStyle('default'); + } + + /** + * Sets a style definition. + */ + public static function setStyleDefinition(string $name, TableStyle $style) + { + if (!self::$styles) { + self::$styles = self::initStyles(); + } + + self::$styles[$name] = $style; + } + + /** + * Gets a style definition by name. + * + * @return TableStyle + */ + public static function getStyleDefinition(string $name) + { + if (!self::$styles) { + self::$styles = self::initStyles(); + } + + if (isset(self::$styles[$name])) { + return self::$styles[$name]; + } + + throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name)); + } + + /** + * Sets table style. + * + * @param TableStyle|string $name The style name or a TableStyle instance + * + * @return $this + */ + public function setStyle($name) + { + $this->style = $this->resolveStyle($name); + + return $this; + } + + /** + * Gets the current table style. + * + * @return TableStyle + */ + public function getStyle() + { + return $this->style; + } + + /** + * Sets table column style. + * + * @param TableStyle|string $name The style name or a TableStyle instance + * + * @return $this + */ + public function setColumnStyle(int $columnIndex, $name) + { + $this->columnStyles[$columnIndex] = $this->resolveStyle($name); + + return $this; + } + + /** + * Gets the current style for a column. + * + * If style was not set, it returns the global table style. + * + * @return TableStyle + */ + public function getColumnStyle(int $columnIndex) + { + return $this->columnStyles[$columnIndex] ?? $this->getStyle(); + } + + /** + * Sets the minimum width of a column. + * + * @return $this + */ + public function setColumnWidth(int $columnIndex, int $width) + { + $this->columnWidths[$columnIndex] = $width; + + return $this; + } + + /** + * Sets the minimum width of all columns. + * + * @return $this + */ + public function setColumnWidths(array $widths) + { + $this->columnWidths = []; + foreach ($widths as $index => $width) { + $this->setColumnWidth($index, $width); + } + + return $this; + } + + /** + * Sets the maximum width of a column. + * + * Any cell within this column which contents exceeds the specified width will be wrapped into multiple lines, while + * formatted strings are preserved. + * + * @return $this + */ + public function setColumnMaxWidth(int $columnIndex, int $width): self + { + if (!$this->output->getFormatter() instanceof WrappableOutputFormatterInterface) { + throw new \LogicException(sprintf('Setting a maximum column width is only supported when using a "%s" formatter, got "%s".', WrappableOutputFormatterInterface::class, get_debug_type($this->output->getFormatter()))); + } + + $this->columnMaxWidths[$columnIndex] = $width; + + return $this; + } + + /** + * @return $this + */ + public function setHeaders(array $headers) + { + $headers = array_values($headers); + if (!empty($headers) && !\is_array($headers[0])) { + $headers = [$headers]; + } + + $this->headers = $headers; + + return $this; + } + + public function setRows(array $rows) + { + $this->rows = []; + + return $this->addRows($rows); + } + + /** + * @return $this + */ + public function addRows(array $rows) + { + foreach ($rows as $row) { + $this->addRow($row); + } + + return $this; + } + + /** + * @return $this + */ + public function addRow($row) + { + if ($row instanceof TableSeparator) { + $this->rows[] = $row; + + return $this; + } + + if (!\is_array($row)) { + throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.'); + } + + $this->rows[] = array_values($row); + + return $this; + } + + /** + * Adds a row to the table, and re-renders the table. + * + * @return $this + */ + public function appendRow($row): self + { + if (!$this->output instanceof ConsoleSectionOutput) { + throw new RuntimeException(sprintf('Output should be an instance of "%s" when calling "%s".', ConsoleSectionOutput::class, __METHOD__)); + } + + if ($this->rendered) { + $this->output->clear($this->calculateRowCount()); + } + + $this->addRow($row); + $this->render(); + + return $this; + } + + /** + * @return $this + */ + public function setRow($column, array $row) + { + $this->rows[$column] = $row; + + return $this; + } + + /** + * @return $this + */ + public function setHeaderTitle(?string $title): self + { + $this->headerTitle = $title; + + return $this; + } + + /** + * @return $this + */ + public function setFooterTitle(?string $title): self + { + $this->footerTitle = $title; + + return $this; + } + + /** + * @return $this + */ + public function setHorizontal(bool $horizontal = true): self + { + $this->horizontal = $horizontal; + + return $this; + } + + /** + * Renders table to output. + * + * Example: + * + * +---------------+-----------------------+------------------+ + * | ISBN | Title | Author | + * +---------------+-----------------------+------------------+ + * | 99921-58-10-7 | Divine Comedy | Dante Alighieri | + * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | + * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien | + * +---------------+-----------------------+------------------+ + */ + public function render() + { + $divider = new TableSeparator(); + if ($this->horizontal) { + $rows = []; + foreach ($this->headers[0] ?? [] as $i => $header) { + $rows[$i] = [$header]; + foreach ($this->rows as $row) { + if ($row instanceof TableSeparator) { + continue; + } + if (isset($row[$i])) { + $rows[$i][] = $row[$i]; + } elseif ($rows[$i][0] instanceof TableCell && $rows[$i][0]->getColspan() >= 2) { + // Noop, there is a "title" + } else { + $rows[$i][] = null; + } + } + } + } else { + $rows = array_merge($this->headers, [$divider], $this->rows); + } + + $this->calculateNumberOfColumns($rows); + + $rowGroups = $this->buildTableRows($rows); + $this->calculateColumnsWidth($rowGroups); + + $isHeader = !$this->horizontal; + $isFirstRow = $this->horizontal; + $hasTitle = (bool) $this->headerTitle; + + foreach ($rowGroups as $rowGroup) { + $isHeaderSeparatorRendered = false; + + foreach ($rowGroup as $row) { + if ($divider === $row) { + $isHeader = false; + $isFirstRow = true; + + continue; + } + + if ($row instanceof TableSeparator) { + $this->renderRowSeparator(); + + continue; + } + + if (!$row) { + continue; + } + + if ($isHeader && !$isHeaderSeparatorRendered) { + $this->renderRowSeparator( + $isHeader ? self::SEPARATOR_TOP : self::SEPARATOR_TOP_BOTTOM, + $hasTitle ? $this->headerTitle : null, + $hasTitle ? $this->style->getHeaderTitleFormat() : null + ); + $hasTitle = false; + $isHeaderSeparatorRendered = true; + } + + if ($isFirstRow) { + $this->renderRowSeparator( + $isHeader ? self::SEPARATOR_TOP : self::SEPARATOR_TOP_BOTTOM, + $hasTitle ? $this->headerTitle : null, + $hasTitle ? $this->style->getHeaderTitleFormat() : null + ); + $isFirstRow = false; + $hasTitle = false; + } + + if ($this->horizontal) { + $this->renderRow($row, $this->style->getCellRowFormat(), $this->style->getCellHeaderFormat()); + } else { + $this->renderRow($row, $isHeader ? $this->style->getCellHeaderFormat() : $this->style->getCellRowFormat()); + } + } + } + $this->renderRowSeparator(self::SEPARATOR_BOTTOM, $this->footerTitle, $this->style->getFooterTitleFormat()); + + $this->cleanup(); + $this->rendered = true; + } + + /** + * Renders horizontal header separator. + * + * Example: + * + * +-----+-----------+-------+ + */ + private function renderRowSeparator(int $type = self::SEPARATOR_MID, ?string $title = null, ?string $titleFormat = null) + { + if (0 === $count = $this->numberOfColumns) { + return; + } + + $borders = $this->style->getBorderChars(); + if (!$borders[0] && !$borders[2] && !$this->style->getCrossingChar()) { + return; + } + + $crossings = $this->style->getCrossingChars(); + if (self::SEPARATOR_MID === $type) { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[2], $crossings[8], $crossings[0], $crossings[4]]; + } elseif (self::SEPARATOR_TOP === $type) { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[1], $crossings[2], $crossings[3]]; + } elseif (self::SEPARATOR_TOP_BOTTOM === $type) { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[9], $crossings[10], $crossings[11]]; + } else { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[7], $crossings[6], $crossings[5]]; + } + + $markup = $leftChar; + for ($column = 0; $column < $count; ++$column) { + $markup .= str_repeat($horizontal, $this->effectiveColumnWidths[$column]); + $markup .= $column === $count - 1 ? $rightChar : $midChar; + } + + if (null !== $title) { + $titleLength = Helper::width(Helper::removeDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title))); + $markupLength = Helper::width($markup); + if ($titleLength > $limit = $markupLength - 4) { + $titleLength = $limit; + $formatLength = Helper::width(Helper::removeDecoration($formatter, sprintf($titleFormat, ''))); + $formattedTitle = sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...'); + } + + $titleStart = intdiv($markupLength - $titleLength, 2); + if (false === mb_detect_encoding($markup, null, true)) { + $markup = substr_replace($markup, $formattedTitle, $titleStart, $titleLength); + } else { + $markup = mb_substr($markup, 0, $titleStart).$formattedTitle.mb_substr($markup, $titleStart + $titleLength); + } + } + + $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup)); + } + + /** + * Renders vertical column separator. + */ + private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE): string + { + $borders = $this->style->getBorderChars(); + + return sprintf($this->style->getBorderFormat(), self::BORDER_OUTSIDE === $type ? $borders[1] : $borders[3]); + } + + /** + * Renders table row. + * + * Example: + * + * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | + */ + private function renderRow(array $row, string $cellFormat, ?string $firstCellFormat = null) + { + $rowContent = $this->renderColumnSeparator(self::BORDER_OUTSIDE); + $columns = $this->getRowColumns($row); + $last = \count($columns) - 1; + foreach ($columns as $i => $column) { + if ($firstCellFormat && 0 === $i) { + $rowContent .= $this->renderCell($row, $column, $firstCellFormat); + } else { + $rowContent .= $this->renderCell($row, $column, $cellFormat); + } + $rowContent .= $this->renderColumnSeparator($last === $i ? self::BORDER_OUTSIDE : self::BORDER_INSIDE); + } + $this->output->writeln($rowContent); + } + + /** + * Renders table cell with padding. + */ + private function renderCell(array $row, int $column, string $cellFormat): string + { + $cell = $row[$column] ?? ''; + $width = $this->effectiveColumnWidths[$column]; + if ($cell instanceof TableCell && $cell->getColspan() > 1) { + // add the width of the following columns(numbers of colspan). + foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) { + $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn]; + } + } + + // str_pad won't work properly with multi-byte strings, we need to fix the padding + if (false !== $encoding = mb_detect_encoding($cell, null, true)) { + $width += \strlen($cell) - mb_strwidth($cell, $encoding); + } + + $style = $this->getColumnStyle($column); + + if ($cell instanceof TableSeparator) { + return sprintf($style->getBorderFormat(), str_repeat($style->getBorderChars()[2], $width)); + } + + $width += Helper::length($cell) - Helper::length(Helper::removeDecoration($this->output->getFormatter(), $cell)); + $content = sprintf($style->getCellRowContentFormat(), $cell); + + $padType = $style->getPadType(); + if ($cell instanceof TableCell && $cell->getStyle() instanceof TableCellStyle) { + $isNotStyledByTag = !preg_match('/^<(\w+|(\w+=[\w,]+;?)*)>.+<\/(\w+|(\w+=\w+;?)*)?>$/', $cell); + if ($isNotStyledByTag) { + $cellFormat = $cell->getStyle()->getCellFormat(); + if (!\is_string($cellFormat)) { + $tag = http_build_query($cell->getStyle()->getTagOptions(), '', ';'); + $cellFormat = '<'.$tag.'>%s</>'; + } + + if (strstr($content, '</>')) { + $content = str_replace('</>', '', $content); + $width -= 3; + } + if (strstr($content, '<fg=default;bg=default>')) { + $content = str_replace('<fg=default;bg=default>', '', $content); + $width -= \strlen('<fg=default;bg=default>'); + } + } + + $padType = $cell->getStyle()->getPadByAlign(); + } + + return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $padType)); + } + + /** + * Calculate number of columns for this table. + */ + private function calculateNumberOfColumns(array $rows) + { + $columns = [0]; + foreach ($rows as $row) { + if ($row instanceof TableSeparator) { + continue; + } + + $columns[] = $this->getNumberOfColumns($row); + } + + $this->numberOfColumns = max($columns); + } + + private function buildTableRows(array $rows): TableRows + { + /** @var WrappableOutputFormatterInterface $formatter */ + $formatter = $this->output->getFormatter(); + $unmergedRows = []; + for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) { + $rows = $this->fillNextRows($rows, $rowKey); + + // Remove any new line breaks and replace it with a new line + foreach ($rows[$rowKey] as $column => $cell) { + $colspan = $cell instanceof TableCell ? $cell->getColspan() : 1; + + if (isset($this->columnMaxWidths[$column]) && Helper::width(Helper::removeDecoration($formatter, $cell)) > $this->columnMaxWidths[$column]) { + $cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan); + } + if (!strstr($cell ?? '', "\n")) { + continue; + } + $eol = str_contains($cell ?? '', "\r\n") ? "\r\n" : "\n"; + $escaped = implode($eol, array_map([OutputFormatter::class, 'escapeTrailingBackslash'], explode($eol, $cell))); + $cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped; + $lines = explode($eol, str_replace($eol, '<fg=default;bg=default></>'.$eol, $cell)); + foreach ($lines as $lineKey => $line) { + if ($colspan > 1) { + $line = new TableCell($line, ['colspan' => $colspan]); + } + if (0 === $lineKey) { + $rows[$rowKey][$column] = $line; + } else { + if (!\array_key_exists($rowKey, $unmergedRows) || !\array_key_exists($lineKey, $unmergedRows[$rowKey])) { + $unmergedRows[$rowKey][$lineKey] = $this->copyRow($rows, $rowKey); + } + $unmergedRows[$rowKey][$lineKey][$column] = $line; + } + } + } + } + + return new TableRows(function () use ($rows, $unmergedRows): \Traversable { + foreach ($rows as $rowKey => $row) { + $rowGroup = [$row instanceof TableSeparator ? $row : $this->fillCells($row)]; + + if (isset($unmergedRows[$rowKey])) { + foreach ($unmergedRows[$rowKey] as $row) { + $rowGroup[] = $row instanceof TableSeparator ? $row : $this->fillCells($row); + } + } + yield $rowGroup; + } + }); + } + + private function calculateRowCount(): int + { + $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows)))); + + if ($this->headers) { + ++$numberOfRows; // Add row for header separator + } + + if (\count($this->rows) > 0) { + ++$numberOfRows; // Add row for footer separator + } + + return $numberOfRows; + } + + /** + * fill rows that contains rowspan > 1. + * + * @throws InvalidArgumentException + */ + private function fillNextRows(array $rows, int $line): array + { + $unmergedRows = []; + foreach ($rows[$line] as $column => $cell) { + if (null !== $cell && !$cell instanceof TableCell && !\is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) { + throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', get_debug_type($cell))); + } + if ($cell instanceof TableCell && $cell->getRowspan() > 1) { + $nbLines = $cell->getRowspan() - 1; + $lines = [$cell]; + if (strstr($cell, "\n")) { + $eol = str_contains($cell, "\r\n") ? "\r\n" : "\n"; + $lines = explode($eol, str_replace($eol, '<fg=default;bg=default>'.$eol.'</>', $cell)); + $nbLines = \count($lines) > $nbLines ? substr_count($cell, $eol) : $nbLines; + + $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + unset($lines[0]); + } + + // create a two dimensional array (rowspan x colspan) + $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows); + foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) { + $value = $lines[$unmergedRowKey - $line] ?? ''; + $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + if ($nbLines === $unmergedRowKey - $line) { + break; + } + } + } + } + + foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) { + // we need to know if $unmergedRow will be merged or inserted into $rows + if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) { + foreach ($unmergedRow as $cellKey => $cell) { + // insert cell into row at cellKey position + array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]); + } + } else { + $row = $this->copyRow($rows, $unmergedRowKey - 1); + foreach ($unmergedRow as $column => $cell) { + if (!empty($cell)) { + $row[$column] = $unmergedRow[$column]; + } + } + array_splice($rows, $unmergedRowKey, 0, [$row]); + } + } + + return $rows; + } + + /** + * fill cells for a row that contains colspan > 1. + */ + private function fillCells(iterable $row) + { + $newRow = []; + + foreach ($row as $column => $cell) { + $newRow[] = $cell; + if ($cell instanceof TableCell && $cell->getColspan() > 1) { + foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) { + // insert empty value at column position + $newRow[] = ''; + } + } + } + + return $newRow ?: $row; + } + + private function copyRow(array $rows, int $line): array + { + $row = $rows[$line]; + foreach ($row as $cellKey => $cellValue) { + $row[$cellKey] = ''; + if ($cellValue instanceof TableCell) { + $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]); + } + } + + return $row; + } + + /** + * Gets number of columns by row. + */ + private function getNumberOfColumns(array $row): int + { + $columns = \count($row); + foreach ($row as $column) { + $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0; + } + + return $columns; + } + + /** + * Gets list of columns for the given row. + */ + private function getRowColumns(array $row): array + { + $columns = range(0, $this->numberOfColumns - 1); + foreach ($row as $cellKey => $cell) { + if ($cell instanceof TableCell && $cell->getColspan() > 1) { + // exclude grouped columns. + $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1)); + } + } + + return $columns; + } + + /** + * Calculates columns widths. + */ + private function calculateColumnsWidth(iterable $groups) + { + for ($column = 0; $column < $this->numberOfColumns; ++$column) { + $lengths = []; + foreach ($groups as $group) { + foreach ($group as $row) { + if ($row instanceof TableSeparator) { + continue; + } + + foreach ($row as $i => $cell) { + if ($cell instanceof TableCell) { + $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell); + $textLength = Helper::width($textContent); + if ($textLength > 0) { + $contentColumns = mb_str_split($textContent, ceil($textLength / $cell->getColspan())); + foreach ($contentColumns as $position => $content) { + $row[$i + $position] = $content; + } + } + } + } + + $lengths[] = $this->getCellWidth($row, $column); + } + } + + $this->effectiveColumnWidths[$column] = max($lengths) + Helper::width($this->style->getCellRowContentFormat()) - 2; + } + } + + private function getColumnSeparatorWidth(): int + { + return Helper::width(sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3])); + } + + private function getCellWidth(array $row, int $column): int + { + $cellWidth = 0; + + if (isset($row[$column])) { + $cell = $row[$column]; + $cellWidth = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $cell)); + } + + $columnWidth = $this->columnWidths[$column] ?? 0; + $cellWidth = max($cellWidth, $columnWidth); + + return isset($this->columnMaxWidths[$column]) ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth; + } + + /** + * Called after rendering to cleanup cache data. + */ + private function cleanup() + { + $this->effectiveColumnWidths = []; + $this->numberOfColumns = null; + } + + /** + * @return array<string, TableStyle> + */ + private static function initStyles(): array + { + $borderless = new TableStyle(); + $borderless + ->setHorizontalBorderChars('=') + ->setVerticalBorderChars(' ') + ->setDefaultCrossingChar(' ') + ; + + $compact = new TableStyle(); + $compact + ->setHorizontalBorderChars('') + ->setVerticalBorderChars('') + ->setDefaultCrossingChar('') + ->setCellRowContentFormat('%s ') + ; + + $styleGuide = new TableStyle(); + $styleGuide + ->setHorizontalBorderChars('-') + ->setVerticalBorderChars(' ') + ->setDefaultCrossingChar(' ') + ->setCellHeaderFormat('%s') + ; + + $box = (new TableStyle()) + ->setHorizontalBorderChars('─') + ->setVerticalBorderChars('│') + ->setCrossingChars('┼', '┌', '┬', '┐', '┤', '┘', '┴', '└', '├') + ; + + $boxDouble = (new TableStyle()) + ->setHorizontalBorderChars('═', '─') + ->setVerticalBorderChars('║', '│') + ->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣') + ; + + return [ + 'default' => new TableStyle(), + 'borderless' => $borderless, + 'compact' => $compact, + 'symfony-style-guide' => $styleGuide, + 'box' => $box, + 'box-double' => $boxDouble, + ]; + } + + private function resolveStyle($name): TableStyle + { + if ($name instanceof TableStyle) { + return $name; + } + + if (isset(self::$styles[$name])) { + return self::$styles[$name]; + } + + throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name)); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/TableCell.php b/php/libraries/composer/vendor/symfony/console/Helper/TableCell.php new file mode 100644 index 0000000..1a7bc6e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/TableCell.php @@ -0,0 +1,78 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Abdellatif Ait boudad <a.aitboudad@gmail.com> + */ +class TableCell +{ + private $value; + private $options = [ + 'rowspan' => 1, + 'colspan' => 1, + 'style' => null, + ]; + + public function __construct(string $value = '', array $options = []) + { + $this->value = $value; + + // check option names + if ($diff = array_diff(array_keys($options), array_keys($this->options))) { + throw new InvalidArgumentException(sprintf('The TableCell does not support the following options: \'%s\'.', implode('\', \'', $diff))); + } + + if (isset($options['style']) && !$options['style'] instanceof TableCellStyle) { + throw new InvalidArgumentException('The style option must be an instance of "TableCellStyle".'); + } + + $this->options = array_merge($this->options, $options); + } + + /** + * Returns the cell value. + * + * @return string + */ + public function __toString() + { + return $this->value; + } + + /** + * Gets number of colspan. + * + * @return int + */ + public function getColspan() + { + return (int) $this->options['colspan']; + } + + /** + * Gets number of rowspan. + * + * @return int + */ + public function getRowspan() + { + return (int) $this->options['rowspan']; + } + + public function getStyle(): ?TableCellStyle + { + return $this->options['style']; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/TableCellStyle.php b/php/libraries/composer/vendor/symfony/console/Helper/TableCellStyle.php new file mode 100644 index 0000000..19cd0ff --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/TableCellStyle.php @@ -0,0 +1,89 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Yewhen Khoptynskyi <khoptynskyi@gmail.com> + */ +class TableCellStyle +{ + public const DEFAULT_ALIGN = 'left'; + + private const TAG_OPTIONS = [ + 'fg', + 'bg', + 'options', + ]; + + private const ALIGN_MAP = [ + 'left' => \STR_PAD_RIGHT, + 'center' => \STR_PAD_BOTH, + 'right' => \STR_PAD_LEFT, + ]; + + private $options = [ + 'fg' => 'default', + 'bg' => 'default', + 'options' => null, + 'align' => self::DEFAULT_ALIGN, + 'cellFormat' => null, + ]; + + public function __construct(array $options = []) + { + if ($diff = array_diff(array_keys($options), array_keys($this->options))) { + throw new InvalidArgumentException(sprintf('The TableCellStyle does not support the following options: \'%s\'.', implode('\', \'', $diff))); + } + + if (isset($options['align']) && !\array_key_exists($options['align'], self::ALIGN_MAP)) { + throw new InvalidArgumentException(sprintf('Wrong align value. Value must be following: \'%s\'.', implode('\', \'', array_keys(self::ALIGN_MAP)))); + } + + $this->options = array_merge($this->options, $options); + } + + public function getOptions(): array + { + return $this->options; + } + + /** + * Gets options we need for tag for example fg, bg. + * + * @return string[] + */ + public function getTagOptions() + { + return array_filter( + $this->getOptions(), + function ($key) { + return \in_array($key, self::TAG_OPTIONS) && isset($this->options[$key]); + }, + \ARRAY_FILTER_USE_KEY + ); + } + + /** + * @return int + */ + public function getPadByAlign() + { + return self::ALIGN_MAP[$this->getOptions()['align']]; + } + + public function getCellFormat(): ?string + { + return $this->getOptions()['cellFormat']; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/TableRows.php b/php/libraries/composer/vendor/symfony/console/Helper/TableRows.php new file mode 100644 index 0000000..cbc07d2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/TableRows.php @@ -0,0 +1,30 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * @internal + */ +class TableRows implements \IteratorAggregate +{ + private $generator; + + public function __construct(\Closure $generator) + { + $this->generator = $generator; + } + + public function getIterator(): \Traversable + { + return ($this->generator)(); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/TableSeparator.php b/php/libraries/composer/vendor/symfony/console/Helper/TableSeparator.php new file mode 100644 index 0000000..e541c53 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/TableSeparator.php @@ -0,0 +1,25 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * Marks a row as being a separator. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class TableSeparator extends TableCell +{ + public function __construct(array $options = []) + { + parent::__construct('', $options); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Helper/TableStyle.php b/php/libraries/composer/vendor/symfony/console/Helper/TableStyle.php new file mode 100644 index 0000000..0643c79 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Helper/TableStyle.php @@ -0,0 +1,376 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Defines the styles for a Table. + * + * @author Fabien Potencier <fabien@symfony.com> + * @author Саша Стаменковић <umpirsky@gmail.com> + * @author Dany Maillard <danymaillard93b@gmail.com> + */ +class TableStyle +{ + private $paddingChar = ' '; + private $horizontalOutsideBorderChar = '-'; + private $horizontalInsideBorderChar = '-'; + private $verticalOutsideBorderChar = '|'; + private $verticalInsideBorderChar = '|'; + private $crossingChar = '+'; + private $crossingTopRightChar = '+'; + private $crossingTopMidChar = '+'; + private $crossingTopLeftChar = '+'; + private $crossingMidRightChar = '+'; + private $crossingBottomRightChar = '+'; + private $crossingBottomMidChar = '+'; + private $crossingBottomLeftChar = '+'; + private $crossingMidLeftChar = '+'; + private $crossingTopLeftBottomChar = '+'; + private $crossingTopMidBottomChar = '+'; + private $crossingTopRightBottomChar = '+'; + private $headerTitleFormat = '<fg=black;bg=white;options=bold> %s </>'; + private $footerTitleFormat = '<fg=black;bg=white;options=bold> %s </>'; + private $cellHeaderFormat = '<info>%s</info>'; + private $cellRowFormat = '%s'; + private $cellRowContentFormat = ' %s '; + private $borderFormat = '%s'; + private $padType = \STR_PAD_RIGHT; + + /** + * Sets padding character, used for cell padding. + * + * @return $this + */ + public function setPaddingChar(string $paddingChar) + { + if (!$paddingChar) { + throw new LogicException('The padding char must not be empty.'); + } + + $this->paddingChar = $paddingChar; + + return $this; + } + + /** + * Gets padding character, used for cell padding. + * + * @return string + */ + public function getPaddingChar() + { + return $this->paddingChar; + } + + /** + * Sets horizontal border characters. + * + * <code> + * ╔═══════════════╤══════════════════════════╤══════════════════╗ + * 1 ISBN 2 Title │ Author ║ + * ╠═══════════════╪══════════════════════════╪══════════════════╣ + * ║ 99921-58-10-7 │ Divine Comedy │ Dante Alighieri ║ + * ║ 9971-5-0210-0 │ A Tale of Two Cities │ Charles Dickens ║ + * ║ 960-425-059-0 │ The Lord of the Rings │ J. R. R. Tolkien ║ + * ║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║ + * ╚═══════════════╧══════════════════════════╧══════════════════╝ + * </code> + * + * @return $this + */ + public function setHorizontalBorderChars(string $outside, ?string $inside = null): self + { + $this->horizontalOutsideBorderChar = $outside; + $this->horizontalInsideBorderChar = $inside ?? $outside; + + return $this; + } + + /** + * Sets vertical border characters. + * + * <code> + * ╔═══════════════╤══════════════════════════╤══════════════════╗ + * ║ ISBN │ Title │ Author ║ + * ╠═══════1═══════╪══════════════════════════╪══════════════════╣ + * ║ 99921-58-10-7 │ Divine Comedy │ Dante Alighieri ║ + * ║ 9971-5-0210-0 │ A Tale of Two Cities │ Charles Dickens ║ + * ╟───────2───────┼──────────────────────────┼──────────────────╢ + * ║ 960-425-059-0 │ The Lord of the Rings │ J. R. R. Tolkien ║ + * ║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║ + * ╚═══════════════╧══════════════════════════╧══════════════════╝ + * </code> + * + * @return $this + */ + public function setVerticalBorderChars(string $outside, ?string $inside = null): self + { + $this->verticalOutsideBorderChar = $outside; + $this->verticalInsideBorderChar = $inside ?? $outside; + + return $this; + } + + /** + * Gets border characters. + * + * @internal + */ + public function getBorderChars(): array + { + return [ + $this->horizontalOutsideBorderChar, + $this->verticalOutsideBorderChar, + $this->horizontalInsideBorderChar, + $this->verticalInsideBorderChar, + ]; + } + + /** + * Sets crossing characters. + * + * Example: + * <code> + * 1═══════════════2══════════════════════════2══════════════════3 + * ║ ISBN │ Title │ Author ║ + * 8'══════════════0'═════════════════════════0'═════════════════4' + * ║ 99921-58-10-7 │ Divine Comedy │ Dante Alighieri ║ + * ║ 9971-5-0210-0 │ A Tale of Two Cities │ Charles Dickens ║ + * 8───────────────0──────────────────────────0──────────────────4 + * ║ 960-425-059-0 │ The Lord of the Rings │ J. R. R. Tolkien ║ + * ║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║ + * 7═══════════════6══════════════════════════6══════════════════5 + * </code> + * + * @param string $cross Crossing char (see #0 of example) + * @param string $topLeft Top left char (see #1 of example) + * @param string $topMid Top mid char (see #2 of example) + * @param string $topRight Top right char (see #3 of example) + * @param string $midRight Mid right char (see #4 of example) + * @param string $bottomRight Bottom right char (see #5 of example) + * @param string $bottomMid Bottom mid char (see #6 of example) + * @param string $bottomLeft Bottom left char (see #7 of example) + * @param string $midLeft Mid left char (see #8 of example) + * @param string|null $topLeftBottom Top left bottom char (see #8' of example), equals to $midLeft if null + * @param string|null $topMidBottom Top mid bottom char (see #0' of example), equals to $cross if null + * @param string|null $topRightBottom Top right bottom char (see #4' of example), equals to $midRight if null + * + * @return $this + */ + public function setCrossingChars(string $cross, string $topLeft, string $topMid, string $topRight, string $midRight, string $bottomRight, string $bottomMid, string $bottomLeft, string $midLeft, ?string $topLeftBottom = null, ?string $topMidBottom = null, ?string $topRightBottom = null): self + { + $this->crossingChar = $cross; + $this->crossingTopLeftChar = $topLeft; + $this->crossingTopMidChar = $topMid; + $this->crossingTopRightChar = $topRight; + $this->crossingMidRightChar = $midRight; + $this->crossingBottomRightChar = $bottomRight; + $this->crossingBottomMidChar = $bottomMid; + $this->crossingBottomLeftChar = $bottomLeft; + $this->crossingMidLeftChar = $midLeft; + $this->crossingTopLeftBottomChar = $topLeftBottom ?? $midLeft; + $this->crossingTopMidBottomChar = $topMidBottom ?? $cross; + $this->crossingTopRightBottomChar = $topRightBottom ?? $midRight; + + return $this; + } + + /** + * Sets default crossing character used for each cross. + * + * @see {@link setCrossingChars()} for setting each crossing individually. + */ + public function setDefaultCrossingChar(string $char): self + { + return $this->setCrossingChars($char, $char, $char, $char, $char, $char, $char, $char, $char); + } + + /** + * Gets crossing character. + * + * @return string + */ + public function getCrossingChar() + { + return $this->crossingChar; + } + + /** + * Gets crossing characters. + * + * @internal + */ + public function getCrossingChars(): array + { + return [ + $this->crossingChar, + $this->crossingTopLeftChar, + $this->crossingTopMidChar, + $this->crossingTopRightChar, + $this->crossingMidRightChar, + $this->crossingBottomRightChar, + $this->crossingBottomMidChar, + $this->crossingBottomLeftChar, + $this->crossingMidLeftChar, + $this->crossingTopLeftBottomChar, + $this->crossingTopMidBottomChar, + $this->crossingTopRightBottomChar, + ]; + } + + /** + * Sets header cell format. + * + * @return $this + */ + public function setCellHeaderFormat(string $cellHeaderFormat) + { + $this->cellHeaderFormat = $cellHeaderFormat; + + return $this; + } + + /** + * Gets header cell format. + * + * @return string + */ + public function getCellHeaderFormat() + { + return $this->cellHeaderFormat; + } + + /** + * Sets row cell format. + * + * @return $this + */ + public function setCellRowFormat(string $cellRowFormat) + { + $this->cellRowFormat = $cellRowFormat; + + return $this; + } + + /** + * Gets row cell format. + * + * @return string + */ + public function getCellRowFormat() + { + return $this->cellRowFormat; + } + + /** + * Sets row cell content format. + * + * @return $this + */ + public function setCellRowContentFormat(string $cellRowContentFormat) + { + $this->cellRowContentFormat = $cellRowContentFormat; + + return $this; + } + + /** + * Gets row cell content format. + * + * @return string + */ + public function getCellRowContentFormat() + { + return $this->cellRowContentFormat; + } + + /** + * Sets table border format. + * + * @return $this + */ + public function setBorderFormat(string $borderFormat) + { + $this->borderFormat = $borderFormat; + + return $this; + } + + /** + * Gets table border format. + * + * @return string + */ + public function getBorderFormat() + { + return $this->borderFormat; + } + + /** + * Sets cell padding type. + * + * @return $this + */ + public function setPadType(int $padType) + { + if (!\in_array($padType, [\STR_PAD_LEFT, \STR_PAD_RIGHT, \STR_PAD_BOTH], true)) { + throw new InvalidArgumentException('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).'); + } + + $this->padType = $padType; + + return $this; + } + + /** + * Gets cell padding type. + * + * @return int + */ + public function getPadType() + { + return $this->padType; + } + + public function getHeaderTitleFormat(): string + { + return $this->headerTitleFormat; + } + + /** + * @return $this + */ + public function setHeaderTitleFormat(string $format): self + { + $this->headerTitleFormat = $format; + + return $this; + } + + public function getFooterTitleFormat(): string + { + return $this->footerTitleFormat; + } + + /** + * @return $this + */ + public function setFooterTitleFormat(string $format): self + { + $this->footerTitleFormat = $format; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/ArgvInput.php b/php/libraries/composer/vendor/symfony/console/Input/ArgvInput.php new file mode 100644 index 0000000..0c4b2d2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/ArgvInput.php @@ -0,0 +1,378 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\RuntimeException; + +/** + * ArgvInput represents an input coming from the CLI arguments. + * + * Usage: + * + * $input = new ArgvInput(); + * + * By default, the `$_SERVER['argv']` array is used for the input values. + * + * This can be overridden by explicitly passing the input values in the constructor: + * + * $input = new ArgvInput($_SERVER['argv']); + * + * If you pass it yourself, don't forget that the first element of the array + * is the name of the running application. + * + * When passing an argument to the constructor, be sure that it respects + * the same rules as the argv one. It's almost always better to use the + * `StringInput` when you want to provide your own input. + * + * @author Fabien Potencier <fabien@symfony.com> + * + * @see http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + * @see http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html#tag_12_02 + */ +class ArgvInput extends Input +{ + private $tokens; + private $parsed; + + public function __construct(?array $argv = null, ?InputDefinition $definition = null) + { + $argv = $argv ?? $_SERVER['argv'] ?? []; + + // strip the application name + array_shift($argv); + + $this->tokens = $argv; + + parent::__construct($definition); + } + + protected function setTokens(array $tokens) + { + $this->tokens = $tokens; + } + + /** + * {@inheritdoc} + */ + protected function parse() + { + $parseOptions = true; + $this->parsed = $this->tokens; + while (null !== $token = array_shift($this->parsed)) { + $parseOptions = $this->parseToken($token, $parseOptions); + } + } + + protected function parseToken(string $token, bool $parseOptions): bool + { + if ($parseOptions && '' == $token) { + $this->parseArgument($token); + } elseif ($parseOptions && '--' == $token) { + return false; + } elseif ($parseOptions && str_starts_with($token, '--')) { + $this->parseLongOption($token); + } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) { + $this->parseShortOption($token); + } else { + $this->parseArgument($token); + } + + return $parseOptions; + } + + /** + * Parses a short option. + */ + private function parseShortOption(string $token) + { + $name = substr($token, 1); + + if (\strlen($name) > 1) { + if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) { + // an option with a value (with no space) + $this->addShortOption($name[0], substr($name, 1)); + } else { + $this->parseShortOptionSet($name); + } + } else { + $this->addShortOption($name, null); + } + } + + /** + * Parses a short option set. + * + * @throws RuntimeException When option given doesn't exist + */ + private function parseShortOptionSet(string $name) + { + $len = \strlen($name); + for ($i = 0; $i < $len; ++$i) { + if (!$this->definition->hasShortcut($name[$i])) { + $encoding = mb_detect_encoding($name, null, true); + throw new RuntimeException(sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding))); + } + + $option = $this->definition->getOptionForShortcut($name[$i]); + if ($option->acceptValue()) { + $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1)); + + break; + } else { + $this->addLongOption($option->getName(), null); + } + } + } + + /** + * Parses a long option. + */ + private function parseLongOption(string $token) + { + $name = substr($token, 2); + + if (false !== $pos = strpos($name, '=')) { + if ('' === $value = substr($name, $pos + 1)) { + array_unshift($this->parsed, $value); + } + $this->addLongOption(substr($name, 0, $pos), $value); + } else { + $this->addLongOption($name, null); + } + } + + /** + * Parses an argument. + * + * @throws RuntimeException When too many arguments are given + */ + private function parseArgument(string $token) + { + $c = \count($this->arguments); + + // if input is expecting another argument, add it + if ($this->definition->hasArgument($c)) { + $arg = $this->definition->getArgument($c); + $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token; + + // if last argument isArray(), append token to last argument + } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) { + $arg = $this->definition->getArgument($c - 1); + $this->arguments[$arg->getName()][] = $token; + + // unexpected argument + } else { + $all = $this->definition->getArguments(); + $symfonyCommandName = null; + if (($inputArgument = $all[$key = array_key_first($all)] ?? null) && 'command' === $inputArgument->getName()) { + $symfonyCommandName = $this->arguments['command'] ?? null; + unset($all[$key]); + } + + if (\count($all)) { + if ($symfonyCommandName) { + $message = sprintf('Too many arguments to "%s" command, expected arguments "%s".', $symfonyCommandName, implode('" "', array_keys($all))); + } else { + $message = sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))); + } + } elseif ($symfonyCommandName) { + $message = sprintf('No arguments expected for "%s" command, got "%s".', $symfonyCommandName, $token); + } else { + $message = sprintf('No arguments expected, got "%s".', $token); + } + + throw new RuntimeException($message); + } + } + + /** + * Adds a short option value. + * + * @throws RuntimeException When option given doesn't exist + */ + private function addShortOption(string $shortcut, $value) + { + if (!$this->definition->hasShortcut($shortcut)) { + throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut)); + } + + $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value); + } + + /** + * Adds a long option value. + * + * @throws RuntimeException When option given doesn't exist + */ + private function addLongOption(string $name, $value) + { + if (!$this->definition->hasOption($name)) { + if (!$this->definition->hasNegation($name)) { + throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name)); + } + + $optionName = $this->definition->negationToName($name); + if (null !== $value) { + throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name)); + } + $this->options[$optionName] = false; + + return; + } + + $option = $this->definition->getOption($name); + + if (null !== $value && !$option->acceptValue()) { + throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name)); + } + + if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) { + // if option accepts an optional or mandatory argument + // let's see if there is one provided + $next = array_shift($this->parsed); + if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) { + $value = $next; + } else { + array_unshift($this->parsed, $next); + } + } + + if (null === $value) { + if ($option->isValueRequired()) { + throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name)); + } + + if (!$option->isArray() && !$option->isValueOptional()) { + $value = true; + } + } + + if ($option->isArray()) { + $this->options[$name][] = $value; + } else { + $this->options[$name] = $value; + } + } + + /** + * {@inheritdoc} + */ + public function getFirstArgument() + { + $isOption = false; + foreach ($this->tokens as $i => $token) { + if ($token && '-' === $token[0]) { + if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) { + continue; + } + + // If it's a long option, consider that everything after "--" is the option name. + // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator) + $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1); + if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) { + // noop + } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) { + $isOption = true; + } + + continue; + } + + if ($isOption) { + $isOption = false; + continue; + } + + return $token; + } + + return null; + } + + /** + * {@inheritdoc} + */ + public function hasParameterOption($values, bool $onlyParams = false) + { + $values = (array) $values; + + foreach ($this->tokens as $token) { + if ($onlyParams && '--' === $token) { + return false; + } + foreach ($values as $value) { + // Options with values: + // For long options, test for '--option=' at beginning + // For short options, test for '-o' at beginning + $leading = str_starts_with($value, '--') ? $value.'=' : $value; + if ($token === $value || '' !== $leading && str_starts_with($token, $leading)) { + return true; + } + } + } + + return false; + } + + /** + * {@inheritdoc} + */ + public function getParameterOption($values, $default = false, bool $onlyParams = false) + { + $values = (array) $values; + $tokens = $this->tokens; + + while (0 < \count($tokens)) { + $token = array_shift($tokens); + if ($onlyParams && '--' === $token) { + return $default; + } + + foreach ($values as $value) { + if ($token === $value) { + return array_shift($tokens); + } + // Options with values: + // For long options, test for '--option=' at beginning + // For short options, test for '-o' at beginning + $leading = str_starts_with($value, '--') ? $value.'=' : $value; + if ('' !== $leading && str_starts_with($token, $leading)) { + return substr($token, \strlen($leading)); + } + } + } + + return $default; + } + + /** + * Returns a stringified representation of the args passed to the command. + * + * @return string + */ + public function __toString() + { + $tokens = array_map(function ($token) { + if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) { + return $match[1].$this->escapeToken($match[2]); + } + + if ($token && '-' !== $token[0]) { + return $this->escapeToken($token); + } + + return $token; + }, $this->tokens); + + return implode(' ', $tokens); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/ArrayInput.php b/php/libraries/composer/vendor/symfony/console/Input/ArrayInput.php new file mode 100644 index 0000000..21a517c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/ArrayInput.php @@ -0,0 +1,210 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\InvalidOptionException; + +/** + * ArrayInput represents an input provided as an array. + * + * Usage: + * + * $input = new ArrayInput(['command' => 'foo:bar', 'foo' => 'bar', '--bar' => 'foobar']); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ArrayInput extends Input +{ + private $parameters; + + public function __construct(array $parameters, ?InputDefinition $definition = null) + { + $this->parameters = $parameters; + + parent::__construct($definition); + } + + /** + * {@inheritdoc} + */ + public function getFirstArgument() + { + foreach ($this->parameters as $param => $value) { + if ($param && \is_string($param) && '-' === $param[0]) { + continue; + } + + return $value; + } + + return null; + } + + /** + * {@inheritdoc} + */ + public function hasParameterOption($values, bool $onlyParams = false) + { + $values = (array) $values; + + foreach ($this->parameters as $k => $v) { + if (!\is_int($k)) { + $v = $k; + } + + if ($onlyParams && '--' === $v) { + return false; + } + + if (\in_array($v, $values)) { + return true; + } + } + + return false; + } + + /** + * {@inheritdoc} + */ + public function getParameterOption($values, $default = false, bool $onlyParams = false) + { + $values = (array) $values; + + foreach ($this->parameters as $k => $v) { + if ($onlyParams && ('--' === $k || (\is_int($k) && '--' === $v))) { + return $default; + } + + if (\is_int($k)) { + if (\in_array($v, $values)) { + return true; + } + } elseif (\in_array($k, $values)) { + return $v; + } + } + + return $default; + } + + /** + * Returns a stringified representation of the args passed to the command. + * + * @return string + */ + public function __toString() + { + $params = []; + foreach ($this->parameters as $param => $val) { + if ($param && \is_string($param) && '-' === $param[0]) { + $glue = ('-' === $param[1]) ? '=' : ' '; + if (\is_array($val)) { + foreach ($val as $v) { + $params[] = $param.('' != $v ? $glue.$this->escapeToken($v) : ''); + } + } else { + $params[] = $param.('' != $val ? $glue.$this->escapeToken($val) : ''); + } + } else { + $params[] = \is_array($val) ? implode(' ', array_map([$this, 'escapeToken'], $val)) : $this->escapeToken($val); + } + } + + return implode(' ', $params); + } + + /** + * {@inheritdoc} + */ + protected function parse() + { + foreach ($this->parameters as $key => $value) { + if ('--' === $key) { + return; + } + if (str_starts_with($key, '--')) { + $this->addLongOption(substr($key, 2), $value); + } elseif (str_starts_with($key, '-')) { + $this->addShortOption(substr($key, 1), $value); + } else { + $this->addArgument($key, $value); + } + } + } + + /** + * Adds a short option value. + * + * @throws InvalidOptionException When option given doesn't exist + */ + private function addShortOption(string $shortcut, $value) + { + if (!$this->definition->hasShortcut($shortcut)) { + throw new InvalidOptionException(sprintf('The "-%s" option does not exist.', $shortcut)); + } + + $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value); + } + + /** + * Adds a long option value. + * + * @throws InvalidOptionException When option given doesn't exist + * @throws InvalidOptionException When a required value is missing + */ + private function addLongOption(string $name, $value) + { + if (!$this->definition->hasOption($name)) { + if (!$this->definition->hasNegation($name)) { + throw new InvalidOptionException(sprintf('The "--%s" option does not exist.', $name)); + } + + $optionName = $this->definition->negationToName($name); + $this->options[$optionName] = false; + + return; + } + + $option = $this->definition->getOption($name); + + if (null === $value) { + if ($option->isValueRequired()) { + throw new InvalidOptionException(sprintf('The "--%s" option requires a value.', $name)); + } + + if (!$option->isValueOptional()) { + $value = true; + } + } + + $this->options[$name] = $value; + } + + /** + * Adds an argument value. + * + * @param string|int $name The argument name + * @param mixed $value The value for the argument + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + private function addArgument($name, $value) + { + if (!$this->definition->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + $this->arguments[$name] = $value; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/Input.php b/php/libraries/composer/vendor/symfony/console/Input/Input.php new file mode 100644 index 0000000..0faab2c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/Input.php @@ -0,0 +1,213 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; + +/** + * Input is the base class for all concrete Input classes. + * + * Three concrete classes are provided by default: + * + * * `ArgvInput`: The input comes from the CLI arguments (argv) + * * `StringInput`: The input is provided as a string + * * `ArrayInput`: The input is provided as an array + * + * @author Fabien Potencier <fabien@symfony.com> + */ +abstract class Input implements InputInterface, StreamableInputInterface +{ + protected $definition; + protected $stream; + protected $options = []; + protected $arguments = []; + protected $interactive = true; + + public function __construct(?InputDefinition $definition = null) + { + if (null === $definition) { + $this->definition = new InputDefinition(); + } else { + $this->bind($definition); + $this->validate(); + } + } + + /** + * {@inheritdoc} + */ + public function bind(InputDefinition $definition) + { + $this->arguments = []; + $this->options = []; + $this->definition = $definition; + + $this->parse(); + } + + /** + * Processes command line arguments. + */ + abstract protected function parse(); + + /** + * {@inheritdoc} + */ + public function validate() + { + $definition = $this->definition; + $givenArguments = $this->arguments; + + $missingArguments = array_filter(array_keys($definition->getArguments()), function ($argument) use ($definition, $givenArguments) { + return !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired(); + }); + + if (\count($missingArguments) > 0) { + throw new RuntimeException(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArguments))); + } + } + + /** + * {@inheritdoc} + */ + public function isInteractive() + { + return $this->interactive; + } + + /** + * {@inheritdoc} + */ + public function setInteractive(bool $interactive) + { + $this->interactive = $interactive; + } + + /** + * {@inheritdoc} + */ + public function getArguments() + { + return array_merge($this->definition->getArgumentDefaults(), $this->arguments); + } + + /** + * {@inheritdoc} + */ + public function getArgument(string $name) + { + if (!$this->definition->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + return $this->arguments[$name] ?? $this->definition->getArgument($name)->getDefault(); + } + + /** + * {@inheritdoc} + */ + public function setArgument(string $name, $value) + { + if (!$this->definition->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + $this->arguments[$name] = $value; + } + + /** + * {@inheritdoc} + */ + public function hasArgument(string $name) + { + return $this->definition->hasArgument($name); + } + + /** + * {@inheritdoc} + */ + public function getOptions() + { + return array_merge($this->definition->getOptionDefaults(), $this->options); + } + + /** + * {@inheritdoc} + */ + public function getOption(string $name) + { + if ($this->definition->hasNegation($name)) { + if (null === $value = $this->getOption($this->definition->negationToName($name))) { + return $value; + } + + return !$value; + } + + if (!$this->definition->hasOption($name)) { + throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); + } + + return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault(); + } + + /** + * {@inheritdoc} + */ + public function setOption(string $name, $value) + { + if ($this->definition->hasNegation($name)) { + $this->options[$this->definition->negationToName($name)] = !$value; + + return; + } elseif (!$this->definition->hasOption($name)) { + throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); + } + + $this->options[$name] = $value; + } + + /** + * {@inheritdoc} + */ + public function hasOption(string $name) + { + return $this->definition->hasOption($name) || $this->definition->hasNegation($name); + } + + /** + * Escapes a token through escapeshellarg if it contains unsafe chars. + * + * @return string + */ + public function escapeToken(string $token) + { + return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token); + } + + /** + * {@inheritdoc} + */ + public function setStream($stream) + { + $this->stream = $stream; + } + + /** + * {@inheritdoc} + */ + public function getStream() + { + return $this->stream; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/InputArgument.php b/php/libraries/composer/vendor/symfony/console/Input/InputArgument.php new file mode 100644 index 0000000..1a8bf44 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/InputArgument.php @@ -0,0 +1,129 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Represents a command line argument. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class InputArgument +{ + public const REQUIRED = 1; + public const OPTIONAL = 2; + public const IS_ARRAY = 4; + + private $name; + private $mode; + private $default; + private $description; + + /** + * @param string $name The argument name + * @param int|null $mode The argument mode: a bit mask of self::REQUIRED, self::OPTIONAL and self::IS_ARRAY + * @param string $description A description text + * @param string|bool|int|float|array|null $default The default value (for self::OPTIONAL mode only) + * + * @throws InvalidArgumentException When argument mode is not valid + */ + public function __construct(string $name, ?int $mode = null, string $description = '', $default = null) + { + if (null === $mode) { + $mode = self::OPTIONAL; + } elseif ($mode > 7 || $mode < 1) { + throw new InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode)); + } + + $this->name = $name; + $this->mode = $mode; + $this->description = $description; + + $this->setDefault($default); + } + + /** + * Returns the argument name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Returns true if the argument is required. + * + * @return bool true if parameter mode is self::REQUIRED, false otherwise + */ + public function isRequired() + { + return self::REQUIRED === (self::REQUIRED & $this->mode); + } + + /** + * Returns true if the argument can take multiple values. + * + * @return bool true if mode is self::IS_ARRAY, false otherwise + */ + public function isArray() + { + return self::IS_ARRAY === (self::IS_ARRAY & $this->mode); + } + + /** + * Sets the default value. + * + * @param string|bool|int|float|array|null $default + * + * @throws LogicException When incorrect default value is given + */ + public function setDefault($default = null) + { + if ($this->isRequired() && null !== $default) { + throw new LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.'); + } + + if ($this->isArray()) { + if (null === $default) { + $default = []; + } elseif (!\is_array($default)) { + throw new LogicException('A default value for an array argument must be an array.'); + } + } + + $this->default = $default; + } + + /** + * Returns the default value. + * + * @return string|bool|int|float|array|null + */ + public function getDefault() + { + return $this->default; + } + + /** + * Returns the description text. + * + * @return string + */ + public function getDescription() + { + return $this->description; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/InputAwareInterface.php b/php/libraries/composer/vendor/symfony/console/Input/InputAwareInterface.php new file mode 100644 index 0000000..5a288de --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/InputAwareInterface.php @@ -0,0 +1,26 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +/** + * InputAwareInterface should be implemented by classes that depends on the + * Console Input. + * + * @author Wouter J <waldio.webdesign@gmail.com> + */ +interface InputAwareInterface +{ + /** + * Sets the Console Input. + */ + public function setInput(InputInterface $input); +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/InputDefinition.php b/php/libraries/composer/vendor/symfony/console/Input/InputDefinition.php new file mode 100644 index 0000000..11f704f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/InputDefinition.php @@ -0,0 +1,424 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * A InputDefinition represents a set of valid command line arguments and options. + * + * Usage: + * + * $definition = new InputDefinition([ + * new InputArgument('name', InputArgument::REQUIRED), + * new InputOption('foo', 'f', InputOption::VALUE_REQUIRED), + * ]); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class InputDefinition +{ + private $arguments; + private $requiredCount; + private $lastArrayArgument; + private $lastOptionalArgument; + private $options; + private $negations; + private $shortcuts; + + /** + * @param array $definition An array of InputArgument and InputOption instance + */ + public function __construct(array $definition = []) + { + $this->setDefinition($definition); + } + + /** + * Sets the definition of the input. + */ + public function setDefinition(array $definition) + { + $arguments = []; + $options = []; + foreach ($definition as $item) { + if ($item instanceof InputOption) { + $options[] = $item; + } else { + $arguments[] = $item; + } + } + + $this->setArguments($arguments); + $this->setOptions($options); + } + + /** + * Sets the InputArgument objects. + * + * @param InputArgument[] $arguments An array of InputArgument objects + */ + public function setArguments(array $arguments = []) + { + $this->arguments = []; + $this->requiredCount = 0; + $this->lastOptionalArgument = null; + $this->lastArrayArgument = null; + $this->addArguments($arguments); + } + + /** + * Adds an array of InputArgument objects. + * + * @param InputArgument[] $arguments An array of InputArgument objects + */ + public function addArguments(?array $arguments = []) + { + if (null !== $arguments) { + foreach ($arguments as $argument) { + $this->addArgument($argument); + } + } + } + + /** + * @throws LogicException When incorrect argument is given + */ + public function addArgument(InputArgument $argument) + { + if (isset($this->arguments[$argument->getName()])) { + throw new LogicException(sprintf('An argument with name "%s" already exists.', $argument->getName())); + } + + if (null !== $this->lastArrayArgument) { + throw new LogicException(sprintf('Cannot add a required argument "%s" after an array argument "%s".', $argument->getName(), $this->lastArrayArgument->getName())); + } + + if ($argument->isRequired() && null !== $this->lastOptionalArgument) { + throw new LogicException(sprintf('Cannot add a required argument "%s" after an optional one "%s".', $argument->getName(), $this->lastOptionalArgument->getName())); + } + + if ($argument->isArray()) { + $this->lastArrayArgument = $argument; + } + + if ($argument->isRequired()) { + ++$this->requiredCount; + } else { + $this->lastOptionalArgument = $argument; + } + + $this->arguments[$argument->getName()] = $argument; + } + + /** + * Returns an InputArgument by name or by position. + * + * @param string|int $name The InputArgument name or position + * + * @return InputArgument + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + public function getArgument($name) + { + if (!$this->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + $arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments; + + return $arguments[$name]; + } + + /** + * Returns true if an InputArgument object exists by name or position. + * + * @param string|int $name The InputArgument name or position + * + * @return bool + */ + public function hasArgument($name) + { + $arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments; + + return isset($arguments[$name]); + } + + /** + * Gets the array of InputArgument objects. + * + * @return InputArgument[] + */ + public function getArguments() + { + return $this->arguments; + } + + /** + * Returns the number of InputArguments. + * + * @return int + */ + public function getArgumentCount() + { + return null !== $this->lastArrayArgument ? \PHP_INT_MAX : \count($this->arguments); + } + + /** + * Returns the number of required InputArguments. + * + * @return int + */ + public function getArgumentRequiredCount() + { + return $this->requiredCount; + } + + /** + * @return array<string|bool|int|float|array|null> + */ + public function getArgumentDefaults() + { + $values = []; + foreach ($this->arguments as $argument) { + $values[$argument->getName()] = $argument->getDefault(); + } + + return $values; + } + + /** + * Sets the InputOption objects. + * + * @param InputOption[] $options An array of InputOption objects + */ + public function setOptions(array $options = []) + { + $this->options = []; + $this->shortcuts = []; + $this->negations = []; + $this->addOptions($options); + } + + /** + * Adds an array of InputOption objects. + * + * @param InputOption[] $options An array of InputOption objects + */ + public function addOptions(array $options = []) + { + foreach ($options as $option) { + $this->addOption($option); + } + } + + /** + * @throws LogicException When option given already exist + */ + public function addOption(InputOption $option) + { + if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) { + throw new LogicException(sprintf('An option named "%s" already exists.', $option->getName())); + } + if (isset($this->negations[$option->getName()])) { + throw new LogicException(sprintf('An option named "%s" already exists.', $option->getName())); + } + + if ($option->getShortcut()) { + foreach (explode('|', $option->getShortcut()) as $shortcut) { + if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]])) { + throw new LogicException(sprintf('An option with shortcut "%s" already exists.', $shortcut)); + } + } + } + + $this->options[$option->getName()] = $option; + if ($option->getShortcut()) { + foreach (explode('|', $option->getShortcut()) as $shortcut) { + $this->shortcuts[$shortcut] = $option->getName(); + } + } + + if ($option->isNegatable()) { + $negatedName = 'no-'.$option->getName(); + if (isset($this->options[$negatedName])) { + throw new LogicException(sprintf('An option named "%s" already exists.', $negatedName)); + } + $this->negations[$negatedName] = $option->getName(); + } + } + + /** + * Returns an InputOption by name. + * + * @return InputOption + * + * @throws InvalidArgumentException When option given doesn't exist + */ + public function getOption(string $name) + { + if (!$this->hasOption($name)) { + throw new InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name)); + } + + return $this->options[$name]; + } + + /** + * Returns true if an InputOption object exists by name. + * + * This method can't be used to check if the user included the option when + * executing the command (use getOption() instead). + * + * @return bool + */ + public function hasOption(string $name) + { + return isset($this->options[$name]); + } + + /** + * Gets the array of InputOption objects. + * + * @return InputOption[] + */ + public function getOptions() + { + return $this->options; + } + + /** + * Returns true if an InputOption object exists by shortcut. + * + * @return bool + */ + public function hasShortcut(string $name) + { + return isset($this->shortcuts[$name]); + } + + /** + * Returns true if an InputOption object exists by negated name. + */ + public function hasNegation(string $name): bool + { + return isset($this->negations[$name]); + } + + /** + * Gets an InputOption by shortcut. + * + * @return InputOption + */ + public function getOptionForShortcut(string $shortcut) + { + return $this->getOption($this->shortcutToName($shortcut)); + } + + /** + * @return array<string|bool|int|float|array|null> + */ + public function getOptionDefaults() + { + $values = []; + foreach ($this->options as $option) { + $values[$option->getName()] = $option->getDefault(); + } + + return $values; + } + + /** + * Returns the InputOption name given a shortcut. + * + * @throws InvalidArgumentException When option given does not exist + * + * @internal + */ + public function shortcutToName(string $shortcut): string + { + if (!isset($this->shortcuts[$shortcut])) { + throw new InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut)); + } + + return $this->shortcuts[$shortcut]; + } + + /** + * Returns the InputOption name given a negation. + * + * @throws InvalidArgumentException When option given does not exist + * + * @internal + */ + public function negationToName(string $negation): string + { + if (!isset($this->negations[$negation])) { + throw new InvalidArgumentException(sprintf('The "--%s" option does not exist.', $negation)); + } + + return $this->negations[$negation]; + } + + /** + * Gets the synopsis. + * + * @return string + */ + public function getSynopsis(bool $short = false) + { + $elements = []; + + if ($short && $this->getOptions()) { + $elements[] = '[options]'; + } elseif (!$short) { + foreach ($this->getOptions() as $option) { + $value = ''; + if ($option->acceptValue()) { + $value = sprintf( + ' %s%s%s', + $option->isValueOptional() ? '[' : '', + strtoupper($option->getName()), + $option->isValueOptional() ? ']' : '' + ); + } + + $shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : ''; + $negation = $option->isNegatable() ? sprintf('|--no-%s', $option->getName()) : ''; + $elements[] = sprintf('[%s--%s%s%s]', $shortcut, $option->getName(), $value, $negation); + } + } + + if (\count($elements) && $this->getArguments()) { + $elements[] = '[--]'; + } + + $tail = ''; + foreach ($this->getArguments() as $argument) { + $element = '<'.$argument->getName().'>'; + if ($argument->isArray()) { + $element .= '...'; + } + + if (!$argument->isRequired()) { + $element = '['.$element; + $tail .= ']'; + } + + $elements[] = $element; + } + + return implode(' ', $elements).$tail; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/InputInterface.php b/php/libraries/composer/vendor/symfony/console/Input/InputInterface.php new file mode 100644 index 0000000..628b603 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/InputInterface.php @@ -0,0 +1,151 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; + +/** + * InputInterface is the interface implemented by all input classes. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +interface InputInterface +{ + /** + * Returns the first argument from the raw parameters (not parsed). + * + * @return string|null + */ + public function getFirstArgument(); + + /** + * Returns true if the raw parameters (not parsed) contain a value. + * + * This method is to be used to introspect the input parameters + * before they have been validated. It must be used carefully. + * Does not necessarily return the correct result for short options + * when multiple flags are combined in the same option. + * + * @param string|array $values The values to look for in the raw parameters (can be an array) + * @param bool $onlyParams Only check real parameters, skip those following an end of options (--) signal + * + * @return bool + */ + public function hasParameterOption($values, bool $onlyParams = false); + + /** + * Returns the value of a raw option (not parsed). + * + * This method is to be used to introspect the input parameters + * before they have been validated. It must be used carefully. + * Does not necessarily return the correct result for short options + * when multiple flags are combined in the same option. + * + * @param string|array $values The value(s) to look for in the raw parameters (can be an array) + * @param string|bool|int|float|array|null $default The default value to return if no result is found + * @param bool $onlyParams Only check real parameters, skip those following an end of options (--) signal + * + * @return mixed + */ + public function getParameterOption($values, $default = false, bool $onlyParams = false); + + /** + * Binds the current Input instance with the given arguments and options. + * + * @throws RuntimeException + */ + public function bind(InputDefinition $definition); + + /** + * Validates the input. + * + * @throws RuntimeException When not enough arguments are given + */ + public function validate(); + + /** + * Returns all the given arguments merged with the default values. + * + * @return array<string|bool|int|float|array|null> + */ + public function getArguments(); + + /** + * Returns the argument value for a given argument name. + * + * @return mixed + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + public function getArgument(string $name); + + /** + * Sets an argument value by name. + * + * @param mixed $value The argument value + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + public function setArgument(string $name, $value); + + /** + * Returns true if an InputArgument object exists by name or position. + * + * @return bool + */ + public function hasArgument(string $name); + + /** + * Returns all the given options merged with the default values. + * + * @return array<string|bool|int|float|array|null> + */ + public function getOptions(); + + /** + * Returns the option value for a given option name. + * + * @return mixed + * + * @throws InvalidArgumentException When option given doesn't exist + */ + public function getOption(string $name); + + /** + * Sets an option value by name. + * + * @param mixed $value The option value + * + * @throws InvalidArgumentException When option given doesn't exist + */ + public function setOption(string $name, $value); + + /** + * Returns true if an InputOption object exists by name. + * + * @return bool + */ + public function hasOption(string $name); + + /** + * Is this input means interactive? + * + * @return bool + */ + public function isInteractive(); + + /** + * Sets the input interactivity. + */ + public function setInteractive(bool $interactive); +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/InputOption.php b/php/libraries/composer/vendor/symfony/console/Input/InputOption.php new file mode 100644 index 0000000..99807f5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/InputOption.php @@ -0,0 +1,231 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Represents a command line option. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class InputOption +{ + /** + * Do not accept input for the option (e.g. --yell). This is the default behavior of options. + */ + public const VALUE_NONE = 1; + + /** + * A value must be passed when the option is used (e.g. --iterations=5 or -i5). + */ + public const VALUE_REQUIRED = 2; + + /** + * The option may or may not have a value (e.g. --yell or --yell=loud). + */ + public const VALUE_OPTIONAL = 4; + + /** + * The option accepts multiple values (e.g. --dir=/foo --dir=/bar). + */ + public const VALUE_IS_ARRAY = 8; + + /** + * The option may have either positive or negative value (e.g. --ansi or --no-ansi). + */ + public const VALUE_NEGATABLE = 16; + + private $name; + private $shortcut; + private $mode; + private $default; + private $description; + + /** + * @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts + * @param int|null $mode The option mode: One of the VALUE_* constants + * @param string|bool|int|float|array|null $default The default value (must be null for self::VALUE_NONE) + * + * @throws InvalidArgumentException If option mode is invalid or incompatible + */ + public function __construct(string $name, $shortcut = null, ?int $mode = null, string $description = '', $default = null) + { + if (str_starts_with($name, '--')) { + $name = substr($name, 2); + } + + if (empty($name)) { + throw new InvalidArgumentException('An option name cannot be empty.'); + } + + if ('' === $shortcut || [] === $shortcut || false === $shortcut) { + $shortcut = null; + } + + if (null !== $shortcut) { + if (\is_array($shortcut)) { + $shortcut = implode('|', $shortcut); + } + $shortcuts = preg_split('{(\|)-?}', ltrim($shortcut, '-')); + $shortcuts = array_filter($shortcuts, 'strlen'); + $shortcut = implode('|', $shortcuts); + + if ('' === $shortcut) { + throw new InvalidArgumentException('An option shortcut cannot be empty.'); + } + } + + if (null === $mode) { + $mode = self::VALUE_NONE; + } elseif ($mode >= (self::VALUE_NEGATABLE << 1) || $mode < 1) { + throw new InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode)); + } + + $this->name = $name; + $this->shortcut = $shortcut; + $this->mode = $mode; + $this->description = $description; + + if ($this->isArray() && !$this->acceptValue()) { + throw new InvalidArgumentException('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.'); + } + if ($this->isNegatable() && $this->acceptValue()) { + throw new InvalidArgumentException('Impossible to have an option mode VALUE_NEGATABLE if the option also accepts a value.'); + } + + $this->setDefault($default); + } + + /** + * Returns the option shortcut. + * + * @return string|null + */ + public function getShortcut() + { + return $this->shortcut; + } + + /** + * Returns the option name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Returns true if the option accepts a value. + * + * @return bool true if value mode is not self::VALUE_NONE, false otherwise + */ + public function acceptValue() + { + return $this->isValueRequired() || $this->isValueOptional(); + } + + /** + * Returns true if the option requires a value. + * + * @return bool true if value mode is self::VALUE_REQUIRED, false otherwise + */ + public function isValueRequired() + { + return self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $this->mode); + } + + /** + * Returns true if the option takes an optional value. + * + * @return bool true if value mode is self::VALUE_OPTIONAL, false otherwise + */ + public function isValueOptional() + { + return self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $this->mode); + } + + /** + * Returns true if the option can take multiple values. + * + * @return bool true if mode is self::VALUE_IS_ARRAY, false otherwise + */ + public function isArray() + { + return self::VALUE_IS_ARRAY === (self::VALUE_IS_ARRAY & $this->mode); + } + + public function isNegatable(): bool + { + return self::VALUE_NEGATABLE === (self::VALUE_NEGATABLE & $this->mode); + } + + /** + * @param string|bool|int|float|array|null $default + */ + public function setDefault($default = null) + { + if (self::VALUE_NONE === (self::VALUE_NONE & $this->mode) && null !== $default) { + throw new LogicException('Cannot set a default value when using InputOption::VALUE_NONE mode.'); + } + + if ($this->isArray()) { + if (null === $default) { + $default = []; + } elseif (!\is_array($default)) { + throw new LogicException('A default value for an array option must be an array.'); + } + } + + $this->default = $this->acceptValue() || $this->isNegatable() ? $default : false; + } + + /** + * Returns the default value. + * + * @return string|bool|int|float|array|null + */ + public function getDefault() + { + return $this->default; + } + + /** + * Returns the description text. + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Checks whether the given option equals this one. + * + * @return bool + */ + public function equals(self $option) + { + return $option->getName() === $this->getName() + && $option->getShortcut() === $this->getShortcut() + && $option->getDefault() === $this->getDefault() + && $option->isNegatable() === $this->isNegatable() + && $option->isArray() === $this->isArray() + && $option->isValueRequired() === $this->isValueRequired() + && $option->isValueOptional() === $this->isValueOptional() + ; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/StreamableInputInterface.php b/php/libraries/composer/vendor/symfony/console/Input/StreamableInputInterface.php new file mode 100644 index 0000000..d7e462f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/StreamableInputInterface.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +/** + * StreamableInputInterface is the interface implemented by all input classes + * that have an input stream. + * + * @author Robin Chalas <robin.chalas@gmail.com> + */ +interface StreamableInputInterface extends InputInterface +{ + /** + * Sets the input stream to read from when interacting with the user. + * + * This is mainly useful for testing purpose. + * + * @param resource $stream The input stream + */ + public function setStream($stream); + + /** + * Returns the input stream. + * + * @return resource|null + */ + public function getStream(); +} diff --git a/php/libraries/composer/vendor/symfony/console/Input/StringInput.php b/php/libraries/composer/vendor/symfony/console/Input/StringInput.php new file mode 100644 index 0000000..56bb66c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Input/StringInput.php @@ -0,0 +1,84 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * StringInput represents an input provided as a string. + * + * Usage: + * + * $input = new StringInput('foo --bar="foobar"'); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class StringInput extends ArgvInput +{ + public const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)'; + public const REGEX_UNQUOTED_STRING = '([^\s\\\\]+?)'; + public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')'; + + /** + * @param string $input A string representing the parameters from the CLI + */ + public function __construct(string $input) + { + parent::__construct([]); + + $this->setTokens($this->tokenize($input)); + } + + /** + * Tokenizes a string. + * + * @throws InvalidArgumentException When unable to parse input (should never happen) + */ + private function tokenize(string $input): array + { + $tokens = []; + $length = \strlen($input); + $cursor = 0; + $token = null; + while ($cursor < $length) { + if ('\\' === $input[$cursor]) { + $token .= $input[++$cursor] ?? ''; + ++$cursor; + continue; + } + + if (preg_match('/\s+/A', $input, $match, 0, $cursor)) { + if (null !== $token) { + $tokens[] = $token; + $token = null; + } + } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) { + $token .= $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, -1))); + } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) { + $token .= stripcslashes(substr($match[0], 1, -1)); + } elseif (preg_match('/'.self::REGEX_UNQUOTED_STRING.'/A', $input, $match, 0, $cursor)) { + $token .= $match[1]; + } else { + // should never happen + throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10))); + } + + $cursor += \strlen($match[0]); + } + + if (null !== $token) { + $tokens[] = $token; + } + + return $tokens; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/LICENSE b/php/libraries/composer/vendor/symfony/console/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/console/Logger/ConsoleLogger.php b/php/libraries/composer/vendor/symfony/console/Logger/ConsoleLogger.php new file mode 100644 index 0000000..4a10fa1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Logger/ConsoleLogger.php @@ -0,0 +1,126 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Logger; + +use Psr\Log\AbstractLogger; +use Psr\Log\InvalidArgumentException; +use Psr\Log\LogLevel; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * PSR-3 compliant console logger. + * + * @author Kévin Dunglas <dunglas@gmail.com> + * + * @see https://www.php-fig.org/psr/psr-3/ + */ +class ConsoleLogger extends AbstractLogger +{ + public const INFO = 'info'; + public const ERROR = 'error'; + + private $output; + private $verbosityLevelMap = [ + LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL, + LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL, + LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL, + LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL, + LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL, + LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE, + LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE, + LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG, + ]; + private $formatLevelMap = [ + LogLevel::EMERGENCY => self::ERROR, + LogLevel::ALERT => self::ERROR, + LogLevel::CRITICAL => self::ERROR, + LogLevel::ERROR => self::ERROR, + LogLevel::WARNING => self::INFO, + LogLevel::NOTICE => self::INFO, + LogLevel::INFO => self::INFO, + LogLevel::DEBUG => self::INFO, + ]; + private $errored = false; + + public function __construct(OutputInterface $output, array $verbosityLevelMap = [], array $formatLevelMap = []) + { + $this->output = $output; + $this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap; + $this->formatLevelMap = $formatLevelMap + $this->formatLevelMap; + } + + /** + * {@inheritdoc} + * + * @return void + */ + public function log($level, $message, array $context = []) + { + if (!isset($this->verbosityLevelMap[$level])) { + throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level)); + } + + $output = $this->output; + + // Write to the error output if necessary and available + if (self::ERROR === $this->formatLevelMap[$level]) { + if ($this->output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + $this->errored = true; + } + + // the if condition check isn't necessary -- it's the same one that $output will do internally anyway. + // We only do it for efficiency here as the message formatting is relatively expensive. + if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) { + $output->writeln(sprintf('<%1$s>[%2$s] %3$s</%1$s>', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)), $this->verbosityLevelMap[$level]); + } + } + + /** + * Returns true when any messages have been logged at error levels. + * + * @return bool + */ + public function hasErrored() + { + return $this->errored; + } + + /** + * Interpolates context values into the message placeholders. + * + * @author PHP Framework Interoperability Group + */ + private function interpolate(string $message, array $context): string + { + if (!str_contains($message, '{')) { + return $message; + } + + $replacements = []; + foreach ($context as $key => $val) { + if (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) { + $replacements["{{$key}}"] = $val; + } elseif ($val instanceof \DateTimeInterface) { + $replacements["{{$key}}"] = $val->format(\DateTime::RFC3339); + } elseif (\is_object($val)) { + $replacements["{{$key}}"] = '[object '.\get_class($val).']'; + } else { + $replacements["{{$key}}"] = '['.\gettype($val).']'; + } + } + + return strtr($message, $replacements); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/BufferedOutput.php b/php/libraries/composer/vendor/symfony/console/Output/BufferedOutput.php new file mode 100644 index 0000000..d37c6e3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/BufferedOutput.php @@ -0,0 +1,45 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +/** + * @author Jean-François Simon <contact@jfsimon.fr> + */ +class BufferedOutput extends Output +{ + private $buffer = ''; + + /** + * Empties buffer and returns its content. + * + * @return string + */ + public function fetch() + { + $content = $this->buffer; + $this->buffer = ''; + + return $content; + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $message, bool $newline) + { + $this->buffer .= $message; + + if ($newline) { + $this->buffer .= \PHP_EOL; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/ConsoleOutput.php b/php/libraries/composer/vendor/symfony/console/Output/ConsoleOutput.php new file mode 100644 index 0000000..560aeb5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/ConsoleOutput.php @@ -0,0 +1,172 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * ConsoleOutput is the default class for all CLI output. It uses STDOUT and STDERR. + * + * This class is a convenient wrapper around `StreamOutput` for both STDOUT and STDERR. + * + * $output = new ConsoleOutput(); + * + * This is equivalent to: + * + * $output = new StreamOutput(fopen('php://stdout', 'w')); + * $stdErr = new StreamOutput(fopen('php://stderr', 'w')); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface +{ + private $stderr; + private $consoleSectionOutputs = []; + + /** + * @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface) + * @param bool|null $decorated Whether to decorate messages (null for auto-guessing) + * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter) + */ + public function __construct(int $verbosity = self::VERBOSITY_NORMAL, ?bool $decorated = null, ?OutputFormatterInterface $formatter = null) + { + parent::__construct($this->openOutputStream(), $verbosity, $decorated, $formatter); + + if (null === $formatter) { + // for BC reasons, stdErr has it own Formatter only when user don't inject a specific formatter. + $this->stderr = new StreamOutput($this->openErrorStream(), $verbosity, $decorated); + + return; + } + + $actualDecorated = $this->isDecorated(); + $this->stderr = new StreamOutput($this->openErrorStream(), $verbosity, $decorated, $this->getFormatter()); + + if (null === $decorated) { + $this->setDecorated($actualDecorated && $this->stderr->isDecorated()); + } + } + + /** + * Creates a new output section. + */ + public function section(): ConsoleSectionOutput + { + return new ConsoleSectionOutput($this->getStream(), $this->consoleSectionOutputs, $this->getVerbosity(), $this->isDecorated(), $this->getFormatter()); + } + + /** + * {@inheritdoc} + */ + public function setDecorated(bool $decorated) + { + parent::setDecorated($decorated); + $this->stderr->setDecorated($decorated); + } + + /** + * {@inheritdoc} + */ + public function setFormatter(OutputFormatterInterface $formatter) + { + parent::setFormatter($formatter); + $this->stderr->setFormatter($formatter); + } + + /** + * {@inheritdoc} + */ + public function setVerbosity(int $level) + { + parent::setVerbosity($level); + $this->stderr->setVerbosity($level); + } + + /** + * {@inheritdoc} + */ + public function getErrorOutput() + { + return $this->stderr; + } + + /** + * {@inheritdoc} + */ + public function setErrorOutput(OutputInterface $error) + { + $this->stderr = $error; + } + + /** + * Returns true if current environment supports writing console output to + * STDOUT. + * + * @return bool + */ + protected function hasStdoutSupport() + { + return false === $this->isRunningOS400(); + } + + /** + * Returns true if current environment supports writing console output to + * STDERR. + * + * @return bool + */ + protected function hasStderrSupport() + { + return false === $this->isRunningOS400(); + } + + /** + * Checks if current executing environment is IBM iSeries (OS400), which + * doesn't properly convert character-encodings between ASCII to EBCDIC. + */ + private function isRunningOS400(): bool + { + $checks = [ + \function_exists('php_uname') ? php_uname('s') : '', + getenv('OSTYPE'), + \PHP_OS, + ]; + + return false !== stripos(implode(';', $checks), 'OS400'); + } + + /** + * @return resource + */ + private function openOutputStream() + { + if (!$this->hasStdoutSupport()) { + return fopen('php://output', 'w'); + } + + // Use STDOUT when possible to prevent from opening too many file descriptors + return \defined('STDOUT') ? \STDOUT : (@fopen('php://stdout', 'w') ?: fopen('php://output', 'w')); + } + + /** + * @return resource + */ + private function openErrorStream() + { + if (!$this->hasStderrSupport()) { + return fopen('php://output', 'w'); + } + + // Use STDERR when possible to prevent from opening too many file descriptors + return \defined('STDERR') ? \STDERR : (@fopen('php://stderr', 'w') ?: fopen('php://output', 'w')); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/ConsoleOutputInterface.php b/php/libraries/composer/vendor/symfony/console/Output/ConsoleOutputInterface.php new file mode 100644 index 0000000..6b6635f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/ConsoleOutputInterface.php @@ -0,0 +1,32 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +/** + * ConsoleOutputInterface is the interface implemented by ConsoleOutput class. + * This adds information about stderr and section output stream. + * + * @author Dariusz Górecki <darek.krk@gmail.com> + */ +interface ConsoleOutputInterface extends OutputInterface +{ + /** + * Gets the OutputInterface for errors. + * + * @return OutputInterface + */ + public function getErrorOutput(); + + public function setErrorOutput(OutputInterface $error); + + public function section(): ConsoleSectionOutput; +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/ConsoleSectionOutput.php b/php/libraries/composer/vendor/symfony/console/Output/ConsoleSectionOutput.php new file mode 100644 index 0000000..70d70c5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/ConsoleSectionOutput.php @@ -0,0 +1,143 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Terminal; + +/** + * @author Pierre du Plessis <pdples@gmail.com> + * @author Gabriel Ostrolucký <gabriel.ostrolucky@gmail.com> + */ +class ConsoleSectionOutput extends StreamOutput +{ + private $content = []; + private $lines = 0; + private $sections; + private $terminal; + + /** + * @param resource $stream + * @param ConsoleSectionOutput[] $sections + */ + public function __construct($stream, array &$sections, int $verbosity, bool $decorated, OutputFormatterInterface $formatter) + { + parent::__construct($stream, $verbosity, $decorated, $formatter); + array_unshift($sections, $this); + $this->sections = &$sections; + $this->terminal = new Terminal(); + } + + /** + * Clears previous output for this section. + * + * @param int $lines Number of lines to clear. If null, then the entire output of this section is cleared + */ + public function clear(?int $lines = null) + { + if (empty($this->content) || !$this->isDecorated()) { + return; + } + + if ($lines) { + array_splice($this->content, -($lines * 2)); // Multiply lines by 2 to cater for each new line added between content + } else { + $lines = $this->lines; + $this->content = []; + } + + $this->lines -= $lines; + + parent::doWrite($this->popStreamContentUntilCurrentSection($lines), false); + } + + /** + * Overwrites the previous output with a new message. + * + * @param array|string $message + */ + public function overwrite($message) + { + $this->clear(); + $this->writeln($message); + } + + public function getContent(): string + { + return implode('', $this->content); + } + + /** + * @internal + */ + public function addContent(string $input) + { + foreach (explode(\PHP_EOL, $input) as $lineContent) { + $this->lines += ceil($this->getDisplayLength($lineContent) / $this->terminal->getWidth()) ?: 1; + $this->content[] = $lineContent; + $this->content[] = \PHP_EOL; + } + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $message, bool $newline) + { + if (!$this->isDecorated()) { + parent::doWrite($message, $newline); + + return; + } + + $erasedContent = $this->popStreamContentUntilCurrentSection(); + + $this->addContent($message); + + parent::doWrite($message, true); + parent::doWrite($erasedContent, false); + } + + /** + * At initial stage, cursor is at the end of stream output. This method makes cursor crawl upwards until it hits + * current section. Then it erases content it crawled through. Optionally, it erases part of current section too. + */ + private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFromCurrentSection = 0): string + { + $numberOfLinesToClear = $numberOfLinesToClearFromCurrentSection; + $erasedContent = []; + + foreach ($this->sections as $section) { + if ($section === $this) { + break; + } + + $numberOfLinesToClear += $section->lines; + $erasedContent[] = $section->getContent(); + } + + if ($numberOfLinesToClear > 0) { + // move cursor up n lines + parent::doWrite(sprintf("\x1b[%dA", $numberOfLinesToClear), false); + // erase to end of screen + parent::doWrite("\x1b[0J", false); + } + + return implode('', array_reverse($erasedContent)); + } + + private function getDisplayLength(string $text): int + { + return Helper::width(Helper::removeDecoration($this->getFormatter(), str_replace("\t", ' ', $text))); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/NullOutput.php b/php/libraries/composer/vendor/symfony/console/Output/NullOutput.php new file mode 100644 index 0000000..3bbe63e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/NullOutput.php @@ -0,0 +1,128 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\NullOutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * NullOutput suppresses all output. + * + * $output = new NullOutput(); + * + * @author Fabien Potencier <fabien@symfony.com> + * @author Tobias Schultze <http://tobion.de> + */ +class NullOutput implements OutputInterface +{ + private $formatter; + + /** + * {@inheritdoc} + */ + public function setFormatter(OutputFormatterInterface $formatter) + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function getFormatter() + { + if ($this->formatter) { + return $this->formatter; + } + // to comply with the interface we must return a OutputFormatterInterface + return $this->formatter = new NullOutputFormatter(); + } + + /** + * {@inheritdoc} + */ + public function setDecorated(bool $decorated) + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function isDecorated() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function setVerbosity(int $level) + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function getVerbosity() + { + return self::VERBOSITY_QUIET; + } + + /** + * {@inheritdoc} + */ + public function isQuiet() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function isVerbose() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isVeryVerbose() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function isDebug() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function writeln($messages, int $options = self::OUTPUT_NORMAL) + { + // do nothing + } + + /** + * {@inheritdoc} + */ + public function write($messages, bool $newline = false, int $options = self::OUTPUT_NORMAL) + { + // do nothing + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/Output.php b/php/libraries/composer/vendor/symfony/console/Output/Output.php new file mode 100644 index 0000000..28c40bb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/Output.php @@ -0,0 +1,174 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * Base class for output classes. + * + * There are five levels of verbosity: + * + * * normal: no option passed (normal output) + * * verbose: -v (more output) + * * very verbose: -vv (highly extended output) + * * debug: -vvv (all debug output) + * * quiet: -q (no output) + * + * @author Fabien Potencier <fabien@symfony.com> + */ +abstract class Output implements OutputInterface +{ + private $verbosity; + private $formatter; + + /** + * @param int|null $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface) + * @param bool $decorated Whether to decorate messages + * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter) + */ + public function __construct(?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, ?OutputFormatterInterface $formatter = null) + { + $this->verbosity = $verbosity ?? self::VERBOSITY_NORMAL; + $this->formatter = $formatter ?? new OutputFormatter(); + $this->formatter->setDecorated($decorated); + } + + /** + * {@inheritdoc} + */ + public function setFormatter(OutputFormatterInterface $formatter) + { + $this->formatter = $formatter; + } + + /** + * {@inheritdoc} + */ + public function getFormatter() + { + return $this->formatter; + } + + /** + * {@inheritdoc} + */ + public function setDecorated(bool $decorated) + { + $this->formatter->setDecorated($decorated); + } + + /** + * {@inheritdoc} + */ + public function isDecorated() + { + return $this->formatter->isDecorated(); + } + + /** + * {@inheritdoc} + */ + public function setVerbosity(int $level) + { + $this->verbosity = $level; + } + + /** + * {@inheritdoc} + */ + public function getVerbosity() + { + return $this->verbosity; + } + + /** + * {@inheritdoc} + */ + public function isQuiet() + { + return self::VERBOSITY_QUIET === $this->verbosity; + } + + /** + * {@inheritdoc} + */ + public function isVerbose() + { + return self::VERBOSITY_VERBOSE <= $this->verbosity; + } + + /** + * {@inheritdoc} + */ + public function isVeryVerbose() + { + return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity; + } + + /** + * {@inheritdoc} + */ + public function isDebug() + { + return self::VERBOSITY_DEBUG <= $this->verbosity; + } + + /** + * {@inheritdoc} + */ + public function writeln($messages, int $options = self::OUTPUT_NORMAL) + { + $this->write($messages, true, $options); + } + + /** + * {@inheritdoc} + */ + public function write($messages, bool $newline = false, int $options = self::OUTPUT_NORMAL) + { + if (!is_iterable($messages)) { + $messages = [$messages]; + } + + $types = self::OUTPUT_NORMAL | self::OUTPUT_RAW | self::OUTPUT_PLAIN; + $type = $types & $options ?: self::OUTPUT_NORMAL; + + $verbosities = self::VERBOSITY_QUIET | self::VERBOSITY_NORMAL | self::VERBOSITY_VERBOSE | self::VERBOSITY_VERY_VERBOSE | self::VERBOSITY_DEBUG; + $verbosity = $verbosities & $options ?: self::VERBOSITY_NORMAL; + + if ($verbosity > $this->getVerbosity()) { + return; + } + + foreach ($messages as $message) { + switch ($type) { + case OutputInterface::OUTPUT_NORMAL: + $message = $this->formatter->format($message); + break; + case OutputInterface::OUTPUT_RAW: + break; + case OutputInterface::OUTPUT_PLAIN: + $message = strip_tags($this->formatter->format($message)); + break; + } + + $this->doWrite($message ?? '', $newline); + } + } + + /** + * Writes a message to the output. + */ + abstract protected function doWrite(string $message, bool $newline); +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/OutputInterface.php b/php/libraries/composer/vendor/symfony/console/Output/OutputInterface.php new file mode 100644 index 0000000..55caab8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/OutputInterface.php @@ -0,0 +1,110 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * OutputInterface is the interface implemented by all Output classes. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +interface OutputInterface +{ + public const VERBOSITY_QUIET = 16; + public const VERBOSITY_NORMAL = 32; + public const VERBOSITY_VERBOSE = 64; + public const VERBOSITY_VERY_VERBOSE = 128; + public const VERBOSITY_DEBUG = 256; + + public const OUTPUT_NORMAL = 1; + public const OUTPUT_RAW = 2; + public const OUTPUT_PLAIN = 4; + + /** + * Writes a message to the output. + * + * @param string|iterable $messages The message as an iterable of strings or a single string + * @param bool $newline Whether to add a newline + * @param int $options A bitmask of options (one of the OUTPUT or VERBOSITY constants), 0 is considered the same as self::OUTPUT_NORMAL | self::VERBOSITY_NORMAL + */ + public function write($messages, bool $newline = false, int $options = 0); + + /** + * Writes a message to the output and adds a newline at the end. + * + * @param string|iterable $messages The message as an iterable of strings or a single string + * @param int $options A bitmask of options (one of the OUTPUT or VERBOSITY constants), 0 is considered the same as self::OUTPUT_NORMAL | self::VERBOSITY_NORMAL + */ + public function writeln($messages, int $options = 0); + + /** + * Sets the verbosity of the output. + */ + public function setVerbosity(int $level); + + /** + * Gets the current verbosity of the output. + * + * @return int + */ + public function getVerbosity(); + + /** + * Returns whether verbosity is quiet (-q). + * + * @return bool + */ + public function isQuiet(); + + /** + * Returns whether verbosity is verbose (-v). + * + * @return bool + */ + public function isVerbose(); + + /** + * Returns whether verbosity is very verbose (-vv). + * + * @return bool + */ + public function isVeryVerbose(); + + /** + * Returns whether verbosity is debug (-vvv). + * + * @return bool + */ + public function isDebug(); + + /** + * Sets the decorated flag. + */ + public function setDecorated(bool $decorated); + + /** + * Gets the decorated flag. + * + * @return bool + */ + public function isDecorated(); + + public function setFormatter(OutputFormatterInterface $formatter); + + /** + * Returns current output formatter instance. + * + * @return OutputFormatterInterface + */ + public function getFormatter(); +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/StreamOutput.php b/php/libraries/composer/vendor/symfony/console/Output/StreamOutput.php new file mode 100644 index 0000000..5f5ffce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/StreamOutput.php @@ -0,0 +1,123 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * StreamOutput writes the output to a given stream. + * + * Usage: + * + * $output = new StreamOutput(fopen('php://stdout', 'w')); + * + * As `StreamOutput` can use any stream, you can also use a file: + * + * $output = new StreamOutput(fopen('/path/to/output.log', 'a', false)); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class StreamOutput extends Output +{ + private $stream; + + /** + * @param resource $stream A stream resource + * @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface) + * @param bool|null $decorated Whether to decorate messages (null for auto-guessing) + * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter) + * + * @throws InvalidArgumentException When first argument is not a real stream + */ + public function __construct($stream, int $verbosity = self::VERBOSITY_NORMAL, ?bool $decorated = null, ?OutputFormatterInterface $formatter = null) + { + if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) { + throw new InvalidArgumentException('The StreamOutput class needs a stream as its first argument.'); + } + + $this->stream = $stream; + + if (null === $decorated) { + $decorated = $this->hasColorSupport(); + } + + parent::__construct($verbosity, $decorated, $formatter); + } + + /** + * Gets the stream attached to this StreamOutput instance. + * + * @return resource + */ + public function getStream() + { + return $this->stream; + } + + protected function doWrite(string $message, bool $newline) + { + if ($newline) { + $message .= \PHP_EOL; + } + + @fwrite($this->stream, $message); + + fflush($this->stream); + } + + /** + * Returns true if the stream supports colorization. + * + * Colorization is disabled if not supported by the stream: + * + * This is tricky on Windows, because Cygwin, Msys2 etc emulate pseudo + * terminals via named pipes, so we can only check the environment. + * + * Reference: Composer\XdebugHandler\Process::supportsColor + * https://github.com/composer/xdebug-handler + * + * @return bool true if the stream supports colorization, false otherwise + */ + protected function hasColorSupport() + { + // Follow https://no-color.org/ + if (isset($_SERVER['NO_COLOR']) || false !== getenv('NO_COLOR')) { + return false; + } + + // Detect msysgit/mingw and assume this is a tty because detection + // does not work correctly, see https://github.com/composer/composer/issues/9690 + if (!@stream_isatty($this->stream) && !\in_array(strtoupper((string) getenv('MSYSTEM')), ['MINGW32', 'MINGW64'], true)) { + return false; + } + + if ('\\' === \DIRECTORY_SEPARATOR && @sapi_windows_vt100_support($this->stream)) { + return true; + } + + if ('Hyper' === getenv('TERM_PROGRAM') + || false !== getenv('COLORTERM') + || false !== getenv('ANSICON') + || 'ON' === getenv('ConEmuANSI') + ) { + return true; + } + + if ('dumb' === $term = (string) getenv('TERM')) { + return false; + } + + // See https://github.com/chalk/supports-color/blob/d4f413efaf8da045c5ab440ed418ef02dbb28bf1/index.js#L157 + return preg_match('/^((screen|xterm|vt100|vt220|putty|rxvt|ansi|cygwin|linux).*)|(.*-256(color)?(-bce)?)$/', $term); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Output/TrimmedBufferOutput.php b/php/libraries/composer/vendor/symfony/console/Output/TrimmedBufferOutput.php new file mode 100644 index 0000000..b08503b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Output/TrimmedBufferOutput.php @@ -0,0 +1,63 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * A BufferedOutput that keeps only the last N chars. + * + * @author Jérémy Derussé <jeremy@derusse.com> + */ +class TrimmedBufferOutput extends Output +{ + private $maxLength; + private $buffer = ''; + + public function __construct(int $maxLength, ?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, ?OutputFormatterInterface $formatter = null) + { + if ($maxLength <= 0) { + throw new InvalidArgumentException(sprintf('"%s()" expects a strictly positive maxLength. Got %d.', __METHOD__, $maxLength)); + } + + parent::__construct($verbosity, $decorated, $formatter); + $this->maxLength = $maxLength; + } + + /** + * Empties buffer and returns its content. + * + * @return string + */ + public function fetch() + { + $content = $this->buffer; + $this->buffer = ''; + + return $content; + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $message, bool $newline) + { + $this->buffer .= $message; + + if ($newline) { + $this->buffer .= \PHP_EOL; + } + + $this->buffer = substr($this->buffer, 0 - $this->maxLength); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Question/ChoiceQuestion.php b/php/libraries/composer/vendor/symfony/console/Question/ChoiceQuestion.php new file mode 100644 index 0000000..bf1f904 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Question/ChoiceQuestion.php @@ -0,0 +1,183 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Question; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * Represents a choice question. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ChoiceQuestion extends Question +{ + private $choices; + private $multiselect = false; + private $prompt = ' > '; + private $errorMessage = 'Value "%s" is invalid'; + + /** + * @param string $question The question to ask to the user + * @param array $choices The list of available choices + * @param mixed $default The default answer to return + */ + public function __construct(string $question, array $choices, $default = null) + { + if (!$choices) { + throw new \LogicException('Choice question must have at least 1 choice available.'); + } + + parent::__construct($question, $default); + + $this->choices = $choices; + $this->setValidator($this->getDefaultValidator()); + $this->setAutocompleterValues($choices); + } + + /** + * Returns available choices. + * + * @return array + */ + public function getChoices() + { + return $this->choices; + } + + /** + * Sets multiselect option. + * + * When multiselect is set to true, multiple choices can be answered. + * + * @return $this + */ + public function setMultiselect(bool $multiselect) + { + $this->multiselect = $multiselect; + $this->setValidator($this->getDefaultValidator()); + + return $this; + } + + /** + * Returns whether the choices are multiselect. + * + * @return bool + */ + public function isMultiselect() + { + return $this->multiselect; + } + + /** + * Gets the prompt for choices. + * + * @return string + */ + public function getPrompt() + { + return $this->prompt; + } + + /** + * Sets the prompt for choices. + * + * @return $this + */ + public function setPrompt(string $prompt) + { + $this->prompt = $prompt; + + return $this; + } + + /** + * Sets the error message for invalid values. + * + * The error message has a string placeholder (%s) for the invalid value. + * + * @return $this + */ + public function setErrorMessage(string $errorMessage) + { + $this->errorMessage = $errorMessage; + $this->setValidator($this->getDefaultValidator()); + + return $this; + } + + private function getDefaultValidator(): callable + { + $choices = $this->choices; + $errorMessage = $this->errorMessage; + $multiselect = $this->multiselect; + $isAssoc = $this->isAssoc($choices); + + return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) { + if ($multiselect) { + // Check for a separated comma values + if (!preg_match('/^[^,]+(?:,[^,]+)*$/', (string) $selected, $matches)) { + throw new InvalidArgumentException(sprintf($errorMessage, $selected)); + } + + $selectedChoices = explode(',', (string) $selected); + } else { + $selectedChoices = [$selected]; + } + + if ($this->isTrimmable()) { + foreach ($selectedChoices as $k => $v) { + $selectedChoices[$k] = trim((string) $v); + } + } + + $multiselectChoices = []; + foreach ($selectedChoices as $value) { + $results = []; + foreach ($choices as $key => $choice) { + if ($choice === $value) { + $results[] = $key; + } + } + + if (\count($results) > 1) { + throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of "%s".', implode('" or "', $results))); + } + + $result = array_search($value, $choices); + + if (!$isAssoc) { + if (false !== $result) { + $result = $choices[$result]; + } elseif (isset($choices[$value])) { + $result = $choices[$value]; + } + } elseif (false === $result && isset($choices[$value])) { + $result = $value; + } + + if (false === $result) { + throw new InvalidArgumentException(sprintf($errorMessage, $value)); + } + + // For associative choices, consistently return the key as string: + $multiselectChoices[] = $isAssoc ? (string) $result : $result; + } + + if ($multiselect) { + return $multiselectChoices; + } + + return current($multiselectChoices); + }; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Question/ConfirmationQuestion.php b/php/libraries/composer/vendor/symfony/console/Question/ConfirmationQuestion.php new file mode 100644 index 0000000..4228521 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Question/ConfirmationQuestion.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Question; + +/** + * Represents a yes/no question. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ConfirmationQuestion extends Question +{ + private $trueAnswerRegex; + + /** + * @param string $question The question to ask to the user + * @param bool $default The default answer to return, true or false + * @param string $trueAnswerRegex A regex to match the "yes" answer + */ + public function __construct(string $question, bool $default = true, string $trueAnswerRegex = '/^y/i') + { + parent::__construct($question, $default); + + $this->trueAnswerRegex = $trueAnswerRegex; + $this->setNormalizer($this->getDefaultNormalizer()); + } + + /** + * Returns the default answer normalizer. + */ + private function getDefaultNormalizer(): callable + { + $default = $this->getDefault(); + $regex = $this->trueAnswerRegex; + + return function ($answer) use ($default, $regex) { + if (\is_bool($answer)) { + return $answer; + } + + $answerIsTrue = (bool) preg_match($regex, $answer); + if (false === $default) { + return $answer && $answerIsTrue; + } + + return '' === $answer || $answerIsTrue; + }; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Question/Question.php b/php/libraries/composer/vendor/symfony/console/Question/Question.php new file mode 100644 index 0000000..ba57442 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Question/Question.php @@ -0,0 +1,299 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Question; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Represents a Question. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class Question +{ + private $question; + private $attempts; + private $hidden = false; + private $hiddenFallback = true; + private $autocompleterCallback; + private $validator; + private $default; + private $normalizer; + private $trimmable = true; + private $multiline = false; + + /** + * @param string $question The question to ask to the user + * @param string|bool|int|float|null $default The default answer to return if the user enters nothing + */ + public function __construct(string $question, $default = null) + { + $this->question = $question; + $this->default = $default; + } + + /** + * Returns the question. + * + * @return string + */ + public function getQuestion() + { + return $this->question; + } + + /** + * Returns the default answer. + * + * @return string|bool|int|float|null + */ + public function getDefault() + { + return $this->default; + } + + /** + * Returns whether the user response accepts newline characters. + */ + public function isMultiline(): bool + { + return $this->multiline; + } + + /** + * Sets whether the user response should accept newline characters. + * + * @return $this + */ + public function setMultiline(bool $multiline): self + { + $this->multiline = $multiline; + + return $this; + } + + /** + * Returns whether the user response must be hidden. + * + * @return bool + */ + public function isHidden() + { + return $this->hidden; + } + + /** + * Sets whether the user response must be hidden or not. + * + * @return $this + * + * @throws LogicException In case the autocompleter is also used + */ + public function setHidden(bool $hidden) + { + if ($this->autocompleterCallback) { + throw new LogicException('A hidden question cannot use the autocompleter.'); + } + + $this->hidden = $hidden; + + return $this; + } + + /** + * In case the response cannot be hidden, whether to fallback on non-hidden question or not. + * + * @return bool + */ + public function isHiddenFallback() + { + return $this->hiddenFallback; + } + + /** + * Sets whether to fallback on non-hidden question if the response cannot be hidden. + * + * @return $this + */ + public function setHiddenFallback(bool $fallback) + { + $this->hiddenFallback = $fallback; + + return $this; + } + + /** + * Gets values for the autocompleter. + * + * @return iterable|null + */ + public function getAutocompleterValues() + { + $callback = $this->getAutocompleterCallback(); + + return $callback ? $callback('') : null; + } + + /** + * Sets values for the autocompleter. + * + * @return $this + * + * @throws LogicException + */ + public function setAutocompleterValues(?iterable $values) + { + if (\is_array($values)) { + $values = $this->isAssoc($values) ? array_merge(array_keys($values), array_values($values)) : array_values($values); + + $callback = static function () use ($values) { + return $values; + }; + } elseif ($values instanceof \Traversable) { + $valueCache = null; + $callback = static function () use ($values, &$valueCache) { + return $valueCache ?? $valueCache = iterator_to_array($values, false); + }; + } else { + $callback = null; + } + + return $this->setAutocompleterCallback($callback); + } + + /** + * Gets the callback function used for the autocompleter. + */ + public function getAutocompleterCallback(): ?callable + { + return $this->autocompleterCallback; + } + + /** + * Sets the callback function used for the autocompleter. + * + * The callback is passed the user input as argument and should return an iterable of corresponding suggestions. + * + * @return $this + */ + public function setAutocompleterCallback(?callable $callback = null): self + { + if ($this->hidden && null !== $callback) { + throw new LogicException('A hidden question cannot use the autocompleter.'); + } + + $this->autocompleterCallback = $callback; + + return $this; + } + + /** + * Sets a validator for the question. + * + * @return $this + */ + public function setValidator(?callable $validator = null) + { + $this->validator = $validator; + + return $this; + } + + /** + * Gets the validator for the question. + * + * @return callable|null + */ + public function getValidator() + { + return $this->validator; + } + + /** + * Sets the maximum number of attempts. + * + * Null means an unlimited number of attempts. + * + * @return $this + * + * @throws InvalidArgumentException in case the number of attempts is invalid + */ + public function setMaxAttempts(?int $attempts) + { + if (null !== $attempts && $attempts < 1) { + throw new InvalidArgumentException('Maximum number of attempts must be a positive value.'); + } + + $this->attempts = $attempts; + + return $this; + } + + /** + * Gets the maximum number of attempts. + * + * Null means an unlimited number of attempts. + * + * @return int|null + */ + public function getMaxAttempts() + { + return $this->attempts; + } + + /** + * Sets a normalizer for the response. + * + * The normalizer can be a callable (a string), a closure or a class implementing __invoke. + * + * @return $this + */ + public function setNormalizer(callable $normalizer) + { + $this->normalizer = $normalizer; + + return $this; + } + + /** + * Gets the normalizer for the response. + * + * The normalizer can ba a callable (a string), a closure or a class implementing __invoke. + * + * @return callable|null + */ + public function getNormalizer() + { + return $this->normalizer; + } + + protected function isAssoc(array $array) + { + return (bool) \count(array_filter(array_keys($array), 'is_string')); + } + + public function isTrimmable(): bool + { + return $this->trimmable; + } + + /** + * @return $this + */ + public function setTrimmable(bool $trimmable): self + { + $this->trimmable = $trimmable; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/README.md b/php/libraries/composer/vendor/symfony/console/README.md new file mode 100644 index 0000000..c4c1299 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/README.md @@ -0,0 +1,36 @@ +Console Component +================= + +The Console component eases the creation of beautiful and testable command line +interfaces. + +Sponsor +------- + +The Console component for Symfony 5.4/6.0 is [backed][1] by [Les-Tilleuls.coop][2]. + +Les-Tilleuls.coop is a team of 50+ Symfony experts who can help you design, develop and +fix your projects. We provide a wide range of professional services including development, +consulting, coaching, training and audits. We also are highly skilled in JS, Go and DevOps. +We are a worker cooperative! + +Help Symfony by [sponsoring][3] its development! + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/console.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +Credits +------- + +`Resources/bin/hiddeninput.exe` is a third party binary provided within this +component. Find sources and license at https://github.com/Seldaek/hidden-input. + +[1]: https://symfony.com/backers +[2]: https://les-tilleuls.coop +[3]: https://symfony.com/sponsor diff --git a/php/libraries/composer/vendor/symfony/console/Resources/bin/hiddeninput.exe b/php/libraries/composer/vendor/symfony/console/Resources/bin/hiddeninput.exe new file mode 100644 index 0000000..c8cf65e Binary files /dev/null and b/php/libraries/composer/vendor/symfony/console/Resources/bin/hiddeninput.exe differ diff --git a/php/libraries/composer/vendor/symfony/console/Resources/completion.bash b/php/libraries/composer/vendor/symfony/console/Resources/completion.bash new file mode 100644 index 0000000..64b87cc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Resources/completion.bash @@ -0,0 +1,84 @@ +# This file is part of the Symfony package. +# +# (c) Fabien Potencier <fabien@symfony.com> +# +# For the full copyright and license information, please view +# https://symfony.com/doc/current/contributing/code/license.html + +_sf_{{ COMMAND_NAME }}() { + # Use newline as only separator to allow space in completion values + IFS=$'\n' + local sf_cmd="${COMP_WORDS[0]}" + + # for an alias, get the real script behind it + sf_cmd_type=$(type -t $sf_cmd) + if [[ $sf_cmd_type == "alias" ]]; then + sf_cmd=$(alias $sf_cmd | sed -E "s/alias $sf_cmd='(.*)'/\1/") + elif [[ $sf_cmd_type == "file" ]]; then + sf_cmd=$(type -p $sf_cmd) + fi + + if [[ $sf_cmd_type != "function" && ! -x $sf_cmd ]]; then + return 1 + fi + + local cur prev words cword + _get_comp_words_by_ref -n := cur prev words cword + + local completecmd=("$sf_cmd" "_complete" "--no-interaction" "-sbash" "-c$cword" "-S{{ VERSION }}") + for w in ${words[@]}; do + w=$(printf -- '%b' "$w") + # remove quotes from typed values + quote="${w:0:1}" + if [ "$quote" == \' ]; then + w="${w%\'}" + w="${w#\'}" + elif [ "$quote" == \" ]; then + w="${w%\"}" + w="${w#\"}" + fi + # empty values are ignored + if [ ! -z "$w" ]; then + completecmd+=("-i$w") + fi + done + + local sfcomplete + if sfcomplete=$(${completecmd[@]} 2>&1); then + local quote suggestions + quote=${cur:0:1} + + # Use single quotes by default if suggestions contains backslash (FQCN) + if [ "$quote" == '' ] && [[ "$sfcomplete" =~ \\ ]]; then + quote=\' + fi + + if [ "$quote" == \' ]; then + # single quotes: no additional escaping (does not accept ' in values) + suggestions=$(for s in $sfcomplete; do printf $'%q%q%q\n' "$quote" "$s" "$quote"; done) + elif [ "$quote" == \" ]; then + # double quotes: double escaping for \ $ ` " + suggestions=$(for s in $sfcomplete; do + s=${s//\\/\\\\} + s=${s//\$/\\\$} + s=${s//\`/\\\`} + s=${s//\"/\\\"} + printf $'%q%q%q\n' "$quote" "$s" "$quote"; + done) + else + # no quotes: double escaping + suggestions=$(for s in $sfcomplete; do printf $'%q\n' $(printf '%q' "$s"); done) + fi + COMPREPLY=($(IFS=$'\n' compgen -W "$suggestions" -- $(printf -- "%q" "$cur"))) + __ltrim_colon_completions "$cur" + else + if [[ "$sfcomplete" != *"Command \"_complete\" is not defined."* ]]; then + >&2 echo + >&2 echo $sfcomplete + fi + + return 1 + fi +} + +complete -F _sf_{{ COMMAND_NAME }} {{ COMMAND_NAME }} diff --git a/php/libraries/composer/vendor/symfony/console/SignalRegistry/SignalRegistry.php b/php/libraries/composer/vendor/symfony/console/SignalRegistry/SignalRegistry.php new file mode 100644 index 0000000..6bee24a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/SignalRegistry/SignalRegistry.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\SignalRegistry; + +final class SignalRegistry +{ + private $signalHandlers = []; + + public function __construct() + { + if (\function_exists('pcntl_async_signals')) { + pcntl_async_signals(true); + } + } + + public function register(int $signal, callable $signalHandler): void + { + if (!isset($this->signalHandlers[$signal])) { + $previousCallback = pcntl_signal_get_handler($signal); + + if (\is_callable($previousCallback)) { + $this->signalHandlers[$signal][] = $previousCallback; + } + } + + $this->signalHandlers[$signal][] = $signalHandler; + + pcntl_signal($signal, [$this, 'handle']); + } + + public static function isSupported(): bool + { + if (!\function_exists('pcntl_signal')) { + return false; + } + + if (\in_array('pcntl_signal', explode(',', \ini_get('disable_functions')))) { + return false; + } + + return true; + } + + /** + * @internal + */ + public function handle(int $signal): void + { + $count = \count($this->signalHandlers[$signal]); + + foreach ($this->signalHandlers[$signal] as $i => $signalHandler) { + $hasNext = $i !== $count - 1; + $signalHandler($signal, $hasNext); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/SingleCommandApplication.php b/php/libraries/composer/vendor/symfony/console/SingleCommandApplication.php new file mode 100644 index 0000000..774e5d8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/SingleCommandApplication.php @@ -0,0 +1,72 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Grégoire Pineau <lyrixx@lyrixx.info> + */ +class SingleCommandApplication extends Command +{ + private $version = 'UNKNOWN'; + private $autoExit = true; + private $running = false; + + /** + * @return $this + */ + public function setVersion(string $version): self + { + $this->version = $version; + + return $this; + } + + /** + * @final + * + * @return $this + */ + public function setAutoExit(bool $autoExit): self + { + $this->autoExit = $autoExit; + + return $this; + } + + public function run(?InputInterface $input = null, ?OutputInterface $output = null): int + { + if ($this->running) { + return parent::run($input, $output); + } + + // We use the command name as the application name + $application = new Application($this->getName() ?: 'UNKNOWN', $this->version); + $application->setAutoExit($this->autoExit); + // Fix the usage of the command displayed with "--help" + $this->setName($_SERVER['argv'][0]); + $application->add($this); + $application->setDefaultCommand($this->getName(), true); + + $this->running = true; + try { + $ret = $application->run($input, $output); + } finally { + $this->running = false; + } + + return $ret ?? 1; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Style/OutputStyle.php b/php/libraries/composer/vendor/symfony/console/Style/OutputStyle.php new file mode 100644 index 0000000..67a98ff --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Style/OutputStyle.php @@ -0,0 +1,153 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Style; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Helper\ProgressBar; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Decorates output to add console style guide helpers. + * + * @author Kevin Bond <kevinbond@gmail.com> + */ +abstract class OutputStyle implements OutputInterface, StyleInterface +{ + private $output; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + } + + /** + * {@inheritdoc} + */ + public function newLine(int $count = 1) + { + $this->output->write(str_repeat(\PHP_EOL, $count)); + } + + /** + * @return ProgressBar + */ + public function createProgressBar(int $max = 0) + { + return new ProgressBar($this->output, $max); + } + + /** + * {@inheritdoc} + */ + public function write($messages, bool $newline = false, int $type = self::OUTPUT_NORMAL) + { + $this->output->write($messages, $newline, $type); + } + + /** + * {@inheritdoc} + */ + public function writeln($messages, int $type = self::OUTPUT_NORMAL) + { + $this->output->writeln($messages, $type); + } + + /** + * {@inheritdoc} + */ + public function setVerbosity(int $level) + { + $this->output->setVerbosity($level); + } + + /** + * {@inheritdoc} + */ + public function getVerbosity() + { + return $this->output->getVerbosity(); + } + + /** + * {@inheritdoc} + */ + public function setDecorated(bool $decorated) + { + $this->output->setDecorated($decorated); + } + + /** + * {@inheritdoc} + */ + public function isDecorated() + { + return $this->output->isDecorated(); + } + + /** + * {@inheritdoc} + */ + public function setFormatter(OutputFormatterInterface $formatter) + { + $this->output->setFormatter($formatter); + } + + /** + * {@inheritdoc} + */ + public function getFormatter() + { + return $this->output->getFormatter(); + } + + /** + * {@inheritdoc} + */ + public function isQuiet() + { + return $this->output->isQuiet(); + } + + /** + * {@inheritdoc} + */ + public function isVerbose() + { + return $this->output->isVerbose(); + } + + /** + * {@inheritdoc} + */ + public function isVeryVerbose() + { + return $this->output->isVeryVerbose(); + } + + /** + * {@inheritdoc} + */ + public function isDebug() + { + return $this->output->isDebug(); + } + + protected function getErrorOutput() + { + if (!$this->output instanceof ConsoleOutputInterface) { + return $this->output; + } + + return $this->output->getErrorOutput(); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Style/StyleInterface.php b/php/libraries/composer/vendor/symfony/console/Style/StyleInterface.php new file mode 100644 index 0000000..9f25a43 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Style/StyleInterface.php @@ -0,0 +1,132 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Style; + +/** + * Output style helpers. + * + * @author Kevin Bond <kevinbond@gmail.com> + */ +interface StyleInterface +{ + /** + * Formats a command title. + */ + public function title(string $message); + + /** + * Formats a section title. + */ + public function section(string $message); + + /** + * Formats a list. + */ + public function listing(array $elements); + + /** + * Formats informational text. + * + * @param string|array $message + */ + public function text($message); + + /** + * Formats a success result bar. + * + * @param string|array $message + */ + public function success($message); + + /** + * Formats an error result bar. + * + * @param string|array $message + */ + public function error($message); + + /** + * Formats an warning result bar. + * + * @param string|array $message + */ + public function warning($message); + + /** + * Formats a note admonition. + * + * @param string|array $message + */ + public function note($message); + + /** + * Formats a caution admonition. + * + * @param string|array $message + */ + public function caution($message); + + /** + * Formats a table. + */ + public function table(array $headers, array $rows); + + /** + * Asks a question. + * + * @return mixed + */ + public function ask(string $question, ?string $default = null, ?callable $validator = null); + + /** + * Asks a question with the user input hidden. + * + * @return mixed + */ + public function askHidden(string $question, ?callable $validator = null); + + /** + * Asks for confirmation. + * + * @return bool + */ + public function confirm(string $question, bool $default = true); + + /** + * Asks a choice question. + * + * @param string|int|null $default + * + * @return mixed + */ + public function choice(string $question, array $choices, $default = null); + + /** + * Add newline(s). + */ + public function newLine(int $count = 1); + + /** + * Starts the progress output. + */ + public function progressStart(int $max = 0); + + /** + * Advances the progress output X steps. + */ + public function progressAdvance(int $step = 1); + + /** + * Finishes the progress output. + */ + public function progressFinish(); +} diff --git a/php/libraries/composer/vendor/symfony/console/Style/SymfonyStyle.php b/php/libraries/composer/vendor/symfony/console/Style/SymfonyStyle.php new file mode 100644 index 0000000..00edf38 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Style/SymfonyStyle.php @@ -0,0 +1,518 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Style; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Helper\ProgressBar; +use Symfony\Component\Console\Helper\SymfonyQuestionHelper; +use Symfony\Component\Console\Helper\Table; +use Symfony\Component\Console\Helper\TableCell; +use Symfony\Component\Console\Helper\TableSeparator; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Output\TrimmedBufferOutput; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Question\ConfirmationQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Terminal; + +/** + * Output decorator helpers for the Symfony Style Guide. + * + * @author Kevin Bond <kevinbond@gmail.com> + */ +class SymfonyStyle extends OutputStyle +{ + public const MAX_LINE_LENGTH = 120; + + private $input; + private $output; + private $questionHelper; + private $progressBar; + private $lineLength; + private $bufferedOutput; + + public function __construct(InputInterface $input, OutputInterface $output) + { + $this->input = $input; + $this->bufferedOutput = new TrimmedBufferOutput(\DIRECTORY_SEPARATOR === '\\' ? 4 : 2, $output->getVerbosity(), false, clone $output->getFormatter()); + // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not. + $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH; + $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH); + + parent::__construct($this->output = $output); + } + + /** + * Formats a message as a block of text. + * + * @param string|array $messages The message to write in the block + */ + public function block($messages, ?string $type = null, ?string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = true) + { + $messages = \is_array($messages) ? array_values($messages) : [$messages]; + + $this->autoPrependBlock(); + $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape)); + $this->newLine(); + } + + /** + * {@inheritdoc} + */ + public function title(string $message) + { + $this->autoPrependBlock(); + $this->writeln([ + sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)), + sprintf('<comment>%s</>', str_repeat('=', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))), + ]); + $this->newLine(); + } + + /** + * {@inheritdoc} + */ + public function section(string $message) + { + $this->autoPrependBlock(); + $this->writeln([ + sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)), + sprintf('<comment>%s</>', str_repeat('-', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))), + ]); + $this->newLine(); + } + + /** + * {@inheritdoc} + */ + public function listing(array $elements) + { + $this->autoPrependText(); + $elements = array_map(function ($element) { + return sprintf(' * %s', $element); + }, $elements); + + $this->writeln($elements); + $this->newLine(); + } + + /** + * {@inheritdoc} + */ + public function text($message) + { + $this->autoPrependText(); + + $messages = \is_array($message) ? array_values($message) : [$message]; + foreach ($messages as $message) { + $this->writeln(sprintf(' %s', $message)); + } + } + + /** + * Formats a command comment. + * + * @param string|array $message + */ + public function comment($message) + { + $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false); + } + + /** + * {@inheritdoc} + */ + public function success($message) + { + $this->block($message, 'OK', 'fg=black;bg=green', ' ', true); + } + + /** + * {@inheritdoc} + */ + public function error($message) + { + $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true); + } + + /** + * {@inheritdoc} + */ + public function warning($message) + { + $this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ', true); + } + + /** + * {@inheritdoc} + */ + public function note($message) + { + $this->block($message, 'NOTE', 'fg=yellow', ' ! '); + } + + /** + * Formats an info message. + * + * @param string|array $message + */ + public function info($message) + { + $this->block($message, 'INFO', 'fg=green', ' ', true); + } + + /** + * {@inheritdoc} + */ + public function caution($message) + { + $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true); + } + + /** + * {@inheritdoc} + */ + public function table(array $headers, array $rows) + { + $this->createTable() + ->setHeaders($headers) + ->setRows($rows) + ->render() + ; + + $this->newLine(); + } + + /** + * Formats a horizontal table. + */ + public function horizontalTable(array $headers, array $rows) + { + $this->createTable() + ->setHorizontal(true) + ->setHeaders($headers) + ->setRows($rows) + ->render() + ; + + $this->newLine(); + } + + /** + * Formats a list of key/value horizontally. + * + * Each row can be one of: + * * 'A title' + * * ['key' => 'value'] + * * new TableSeparator() + * + * @param string|array|TableSeparator ...$list + */ + public function definitionList(...$list) + { + $headers = []; + $row = []; + foreach ($list as $value) { + if ($value instanceof TableSeparator) { + $headers[] = $value; + $row[] = $value; + continue; + } + if (\is_string($value)) { + $headers[] = new TableCell($value, ['colspan' => 2]); + $row[] = null; + continue; + } + if (!\is_array($value)) { + throw new InvalidArgumentException('Value should be an array, string, or an instance of TableSeparator.'); + } + $headers[] = key($value); + $row[] = current($value); + } + + $this->horizontalTable($headers, [$row]); + } + + /** + * {@inheritdoc} + */ + public function ask(string $question, ?string $default = null, ?callable $validator = null) + { + $question = new Question($question, $default); + $question->setValidator($validator); + + return $this->askQuestion($question); + } + + /** + * {@inheritdoc} + */ + public function askHidden(string $question, ?callable $validator = null) + { + $question = new Question($question); + + $question->setHidden(true); + $question->setValidator($validator); + + return $this->askQuestion($question); + } + + /** + * {@inheritdoc} + */ + public function confirm(string $question, bool $default = true) + { + return $this->askQuestion(new ConfirmationQuestion($question, $default)); + } + + /** + * {@inheritdoc} + */ + public function choice(string $question, array $choices, $default = null) + { + if (null !== $default) { + $values = array_flip($choices); + $default = $values[$default] ?? $default; + } + + return $this->askQuestion(new ChoiceQuestion($question, $choices, $default)); + } + + /** + * {@inheritdoc} + */ + public function progressStart(int $max = 0) + { + $this->progressBar = $this->createProgressBar($max); + $this->progressBar->start(); + } + + /** + * {@inheritdoc} + */ + public function progressAdvance(int $step = 1) + { + $this->getProgressBar()->advance($step); + } + + /** + * {@inheritdoc} + */ + public function progressFinish() + { + $this->getProgressBar()->finish(); + $this->newLine(2); + $this->progressBar = null; + } + + /** + * {@inheritdoc} + */ + public function createProgressBar(int $max = 0) + { + $progressBar = parent::createProgressBar($max); + + if ('\\' !== \DIRECTORY_SEPARATOR || 'Hyper' === getenv('TERM_PROGRAM')) { + $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591 + $progressBar->setProgressCharacter(''); + $progressBar->setBarCharacter('▓'); // dark shade character \u2593 + } + + return $progressBar; + } + + /** + * @see ProgressBar::iterate() + */ + public function progressIterate(iterable $iterable, ?int $max = null): iterable + { + yield from $this->createProgressBar()->iterate($iterable, $max); + + $this->newLine(2); + } + + /** + * @return mixed + */ + public function askQuestion(Question $question) + { + if ($this->input->isInteractive()) { + $this->autoPrependBlock(); + } + + if (!$this->questionHelper) { + $this->questionHelper = new SymfonyQuestionHelper(); + } + + $answer = $this->questionHelper->ask($this->input, $this, $question); + + if ($this->input->isInteractive()) { + $this->newLine(); + $this->bufferedOutput->write("\n"); + } + + return $answer; + } + + /** + * {@inheritdoc} + */ + public function writeln($messages, int $type = self::OUTPUT_NORMAL) + { + if (!is_iterable($messages)) { + $messages = [$messages]; + } + + foreach ($messages as $message) { + parent::writeln($message, $type); + $this->writeBuffer($message, true, $type); + } + } + + /** + * {@inheritdoc} + */ + public function write($messages, bool $newline = false, int $type = self::OUTPUT_NORMAL) + { + if (!is_iterable($messages)) { + $messages = [$messages]; + } + + foreach ($messages as $message) { + parent::write($message, $newline, $type); + $this->writeBuffer($message, $newline, $type); + } + } + + /** + * {@inheritdoc} + */ + public function newLine(int $count = 1) + { + parent::newLine($count); + $this->bufferedOutput->write(str_repeat("\n", $count)); + } + + /** + * Returns a new instance which makes use of stderr if available. + * + * @return self + */ + public function getErrorStyle() + { + return new self($this->input, $this->getErrorOutput()); + } + + public function createTable(): Table + { + $output = $this->output instanceof ConsoleOutputInterface ? $this->output->section() : $this->output; + $style = clone Table::getStyleDefinition('symfony-style-guide'); + $style->setCellHeaderFormat('<info>%s</info>'); + + return (new Table($output))->setStyle($style); + } + + private function getProgressBar(): ProgressBar + { + if (!$this->progressBar) { + throw new RuntimeException('The ProgressBar is not started.'); + } + + return $this->progressBar; + } + + private function autoPrependBlock(): void + { + $chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2); + + if (!isset($chars[0])) { + $this->newLine(); // empty history, so we should start with a new line. + + return; + } + // Prepend new line for each non LF chars (This means no blank line was output before) + $this->newLine(2 - substr_count($chars, "\n")); + } + + private function autoPrependText(): void + { + $fetched = $this->bufferedOutput->fetch(); + // Prepend new line if last char isn't EOL: + if (!str_ends_with($fetched, "\n")) { + $this->newLine(); + } + } + + private function writeBuffer(string $message, bool $newLine, int $type): void + { + // We need to know if the last chars are PHP_EOL + $this->bufferedOutput->write($message, $newLine, $type); + } + + private function createBlock(iterable $messages, ?string $type = null, ?string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false): array + { + $indentLength = 0; + $prefixLength = Helper::width(Helper::removeDecoration($this->getFormatter(), $prefix)); + $lines = []; + + if (null !== $type) { + $type = sprintf('[%s] ', $type); + $indentLength = \strlen($type); + $lineIndentation = str_repeat(' ', $indentLength); + } + + // wrap and add newlines for each element + foreach ($messages as $key => $message) { + if ($escape) { + $message = OutputFormatter::escape($message); + } + + $decorationLength = Helper::width($message) - Helper::width(Helper::removeDecoration($this->getFormatter(), $message)); + $messageLineLength = min($this->lineLength - $prefixLength - $indentLength + $decorationLength, $this->lineLength); + $messageLines = explode(\PHP_EOL, wordwrap($message, $messageLineLength, \PHP_EOL, true)); + foreach ($messageLines as $messageLine) { + $lines[] = $messageLine; + } + + if (\count($messages) > 1 && $key < \count($messages) - 1) { + $lines[] = ''; + } + } + + $firstLineIndex = 0; + if ($padding && $this->isDecorated()) { + $firstLineIndex = 1; + array_unshift($lines, ''); + $lines[] = ''; + } + + foreach ($lines as $i => &$line) { + if (null !== $type) { + $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line; + } + + $line = $prefix.$line; + $line .= str_repeat(' ', max($this->lineLength - Helper::width(Helper::removeDecoration($this->getFormatter(), $line)), 0)); + + if ($style) { + $line = sprintf('<%s>%s</>', $style, $line); + } + } + + return $lines; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Terminal.php b/php/libraries/composer/vendor/symfony/console/Terminal.php new file mode 100644 index 0000000..b91e8af --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Terminal.php @@ -0,0 +1,177 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +class Terminal +{ + private static $width; + private static $height; + private static $stty; + + /** + * Gets the terminal width. + * + * @return int + */ + public function getWidth() + { + $width = getenv('COLUMNS'); + if (false !== $width) { + return (int) trim($width); + } + + if (null === self::$width) { + self::initDimensions(); + } + + return self::$width ?: 80; + } + + /** + * Gets the terminal height. + * + * @return int + */ + public function getHeight() + { + $height = getenv('LINES'); + if (false !== $height) { + return (int) trim($height); + } + + if (null === self::$height) { + self::initDimensions(); + } + + return self::$height ?: 50; + } + + /** + * @internal + */ + public static function hasSttyAvailable(): bool + { + if (null !== self::$stty) { + return self::$stty; + } + + // skip check if shell_exec function is disabled + if (!\function_exists('shell_exec')) { + return false; + } + + return self::$stty = (bool) shell_exec('stty 2> '.('\\' === \DIRECTORY_SEPARATOR ? 'NUL' : '/dev/null')); + } + + private static function initDimensions() + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $ansicon = getenv('ANSICON'); + if (false !== $ansicon && preg_match('/^(\d+)x(\d+)(?: \((\d+)x(\d+)\))?$/', trim($ansicon), $matches)) { + // extract [w, H] from "wxh (WxH)" + // or [w, h] from "wxh" + self::$width = (int) $matches[1]; + self::$height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2]; + } elseif (!self::hasVt100Support() && self::hasSttyAvailable()) { + // only use stty on Windows if the terminal does not support vt100 (e.g. Windows 7 + git-bash) + // testing for stty in a Windows 10 vt100-enabled console will implicitly disable vt100 support on STDOUT + self::initDimensionsUsingStty(); + } elseif (null !== $dimensions = self::getConsoleMode()) { + // extract [w, h] from "wxh" + self::$width = (int) $dimensions[0]; + self::$height = (int) $dimensions[1]; + } + } else { + self::initDimensionsUsingStty(); + } + } + + /** + * Returns whether STDOUT has vt100 support (some Windows 10+ configurations). + */ + private static function hasVt100Support(): bool + { + return \function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support(fopen('php://stdout', 'w')); + } + + /** + * Initializes dimensions using the output of an stty columns line. + */ + private static function initDimensionsUsingStty() + { + if ($sttyString = self::getSttyColumns()) { + if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) { + // extract [w, h] from "rows h; columns w;" + self::$width = (int) $matches[2]; + self::$height = (int) $matches[1]; + } elseif (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) { + // extract [w, h] from "; h rows; w columns" + self::$width = (int) $matches[2]; + self::$height = (int) $matches[1]; + } + } + } + + /** + * Runs and parses mode CON if it's available, suppressing any error output. + * + * @return int[]|null An array composed of the width and the height or null if it could not be parsed + */ + private static function getConsoleMode(): ?array + { + $info = self::readFromProcess('mode CON'); + + if (null === $info || !preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) { + return null; + } + + return [(int) $matches[2], (int) $matches[1]]; + } + + /** + * Runs and parses stty -a if it's available, suppressing any error output. + */ + private static function getSttyColumns(): ?string + { + return self::readFromProcess('stty -a | grep columns'); + } + + private static function readFromProcess(string $command): ?string + { + if (!\function_exists('proc_open')) { + return null; + } + + $descriptorspec = [ + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ]; + + $cp = \function_exists('sapi_windows_cp_set') ? sapi_windows_cp_get() : 0; + + $process = proc_open($command, $descriptorspec, $pipes, null, null, ['suppress_errors' => true]); + if (!\is_resource($process)) { + return null; + } + + $info = stream_get_contents($pipes[1]); + fclose($pipes[1]); + fclose($pipes[2]); + proc_close($process); + + if ($cp) { + sapi_windows_cp_set($cp); + } + + return $info; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Tester/ApplicationTester.php b/php/libraries/composer/vendor/symfony/console/Tester/ApplicationTester.php new file mode 100644 index 0000000..3a262e8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Tester/ApplicationTester.php @@ -0,0 +1,85 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Input\ArrayInput; + +/** + * Eases the testing of console applications. + * + * When testing an application, don't forget to disable the auto exit flag: + * + * $application = new Application(); + * $application->setAutoExit(false); + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ApplicationTester +{ + use TesterTrait; + + private $application; + + public function __construct(Application $application) + { + $this->application = $application; + } + + /** + * Executes the application. + * + * Available options: + * + * * interactive: Sets the input interactive flag + * * decorated: Sets the output decorated flag + * * verbosity: Sets the output verbosity flag + * * capture_stderr_separately: Make output of stdOut and stdErr separately available + * + * @return int The command exit code + */ + public function run(array $input, array $options = []) + { + $prevShellVerbosity = getenv('SHELL_VERBOSITY'); + + try { + $this->input = new ArrayInput($input); + if (isset($options['interactive'])) { + $this->input->setInteractive($options['interactive']); + } + + if ($this->inputs) { + $this->input->setStream(self::createStream($this->inputs)); + } + + $this->initOutput($options); + + return $this->statusCode = $this->application->run($this->input, $this->output); + } finally { + // SHELL_VERBOSITY is set by Application::configureIO so we need to unset/reset it + // to its previous value to avoid one test's verbosity to spread to the following tests + if (false === $prevShellVerbosity) { + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY'); + } + unset($_ENV['SHELL_VERBOSITY']); + unset($_SERVER['SHELL_VERBOSITY']); + } else { + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY='.$prevShellVerbosity); + } + $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity; + $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity; + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Tester/CommandCompletionTester.php b/php/libraries/composer/vendor/symfony/console/Tester/CommandCompletionTester.php new file mode 100644 index 0000000..ade7327 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Tester/CommandCompletionTester.php @@ -0,0 +1,56 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; + +/** + * Eases the testing of command completion. + * + * @author Jérôme Tamarelle <jerome@tamarelle.net> + */ +class CommandCompletionTester +{ + private $command; + + public function __construct(Command $command) + { + $this->command = $command; + } + + /** + * Create completion suggestions from input tokens. + */ + public function complete(array $input): array + { + $currentIndex = \count($input); + if ('' === end($input)) { + array_pop($input); + } + array_unshift($input, $this->command->getName()); + + $completionInput = CompletionInput::fromTokens($input, $currentIndex); + $completionInput->bind($this->command->getDefinition()); + $suggestions = new CompletionSuggestions(); + + $this->command->complete($completionInput, $suggestions); + + $options = []; + foreach ($suggestions->getOptionSuggestions() as $option) { + $options[] = '--'.$option->getName(); + } + + return array_map('strval', array_merge($options, $suggestions->getValueSuggestions())); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Tester/CommandTester.php b/php/libraries/composer/vendor/symfony/console/Tester/CommandTester.php new file mode 100644 index 0000000..6c15c25 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Tester/CommandTester.php @@ -0,0 +1,76 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\ArrayInput; + +/** + * Eases the testing of console commands. + * + * @author Fabien Potencier <fabien@symfony.com> + * @author Robin Chalas <robin.chalas@gmail.com> + */ +class CommandTester +{ + use TesterTrait; + + private $command; + + public function __construct(Command $command) + { + $this->command = $command; + } + + /** + * Executes the command. + * + * Available execution options: + * + * * interactive: Sets the input interactive flag + * * decorated: Sets the output decorated flag + * * verbosity: Sets the output verbosity flag + * * capture_stderr_separately: Make output of stdOut and stdErr separately available + * + * @param array $input An array of command arguments and options + * @param array $options An array of execution options + * + * @return int The command exit code + */ + public function execute(array $input, array $options = []) + { + // set the command name automatically if the application requires + // this argument and no command name was passed + if (!isset($input['command']) + && (null !== $application = $this->command->getApplication()) + && $application->getDefinition()->hasArgument('command') + ) { + $input = array_merge(['command' => $this->command->getName()], $input); + } + + $this->input = new ArrayInput($input); + // Use an in-memory input stream even if no inputs are set so that QuestionHelper::ask() does not rely on the blocking STDIN. + $this->input->setStream(self::createStream($this->inputs)); + + if (isset($options['interactive'])) { + $this->input->setInteractive($options['interactive']); + } + + if (!isset($options['decorated'])) { + $options['decorated'] = false; + } + + $this->initOutput($options); + + return $this->statusCode = $this->command->run($this->input, $this->output); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php b/php/libraries/composer/vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php new file mode 100644 index 0000000..a473242 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php @@ -0,0 +1,55 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Console\Command\Command; + +final class CommandIsSuccessful extends Constraint +{ + /** + * {@inheritdoc} + */ + public function toString(): string + { + return 'is successful'; + } + + /** + * {@inheritdoc} + */ + protected function matches($other): bool + { + return Command::SUCCESS === $other; + } + + /** + * {@inheritdoc} + */ + protected function failureDescription($other): string + { + return 'the command '.$this->toString(); + } + + /** + * {@inheritdoc} + */ + protected function additionalFailureDescription($other): string + { + $mapping = [ + Command::FAILURE => 'Command failed.', + Command::INVALID => 'Command was invalid.', + ]; + + return $mapping[$other] ?? sprintf('Command returned exit status %d.', $other); + } +} diff --git a/php/libraries/composer/vendor/symfony/console/Tester/TesterTrait.php b/php/libraries/composer/vendor/symfony/console/Tester/TesterTrait.php new file mode 100644 index 0000000..f454bbf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/Tester/TesterTrait.php @@ -0,0 +1,197 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use PHPUnit\Framework\Assert; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Output\StreamOutput; +use Symfony\Component\Console\Tester\Constraint\CommandIsSuccessful; + +/** + * @author Amrouche Hamza <hamza.simperfit@gmail.com> + */ +trait TesterTrait +{ + /** @var StreamOutput */ + private $output; + private $inputs = []; + private $captureStreamsIndependently = false; + /** @var InputInterface */ + private $input; + /** @var int */ + private $statusCode; + + /** + * Gets the display returned by the last execution of the command or application. + * + * @return string + * + * @throws \RuntimeException If it's called before the execute method + */ + public function getDisplay(bool $normalize = false) + { + if (null === $this->output) { + throw new \RuntimeException('Output not initialized, did you execute the command before requesting the display?'); + } + + rewind($this->output->getStream()); + + $display = stream_get_contents($this->output->getStream()); + + if ($normalize) { + $display = str_replace(\PHP_EOL, "\n", $display); + } + + return $display; + } + + /** + * Gets the output written to STDERR by the application. + * + * @param bool $normalize Whether to normalize end of lines to \n or not + * + * @return string + */ + public function getErrorOutput(bool $normalize = false) + { + if (!$this->captureStreamsIndependently) { + throw new \LogicException('The error output is not available when the tester is run without "capture_stderr_separately" option set.'); + } + + rewind($this->output->getErrorOutput()->getStream()); + + $display = stream_get_contents($this->output->getErrorOutput()->getStream()); + + if ($normalize) { + $display = str_replace(\PHP_EOL, "\n", $display); + } + + return $display; + } + + /** + * Gets the input instance used by the last execution of the command or application. + * + * @return InputInterface + */ + public function getInput() + { + return $this->input; + } + + /** + * Gets the output instance used by the last execution of the command or application. + * + * @return OutputInterface + */ + public function getOutput() + { + return $this->output; + } + + /** + * Gets the status code returned by the last execution of the command or application. + * + * @return int + * + * @throws \RuntimeException If it's called before the execute method + */ + public function getStatusCode() + { + if (null === $this->statusCode) { + throw new \RuntimeException('Status code not initialized, did you execute the command before requesting the status code?'); + } + + return $this->statusCode; + } + + public function assertCommandIsSuccessful(string $message = ''): void + { + Assert::assertThat($this->statusCode, new CommandIsSuccessful(), $message); + } + + /** + * Sets the user inputs. + * + * @param array $inputs An array of strings representing each input + * passed to the command input stream + * + * @return $this + */ + public function setInputs(array $inputs) + { + $this->inputs = $inputs; + + return $this; + } + + /** + * Initializes the output property. + * + * Available options: + * + * * decorated: Sets the output decorated flag + * * verbosity: Sets the output verbosity flag + * * capture_stderr_separately: Make output of stdOut and stdErr separately available + */ + private function initOutput(array $options) + { + $this->captureStreamsIndependently = \array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately']; + if (!$this->captureStreamsIndependently) { + $this->output = new StreamOutput(fopen('php://memory', 'w', false)); + if (isset($options['decorated'])) { + $this->output->setDecorated($options['decorated']); + } + if (isset($options['verbosity'])) { + $this->output->setVerbosity($options['verbosity']); + } + } else { + $this->output = new ConsoleOutput( + $options['verbosity'] ?? ConsoleOutput::VERBOSITY_NORMAL, + $options['decorated'] ?? null + ); + + $errorOutput = new StreamOutput(fopen('php://memory', 'w', false)); + $errorOutput->setFormatter($this->output->getFormatter()); + $errorOutput->setVerbosity($this->output->getVerbosity()); + $errorOutput->setDecorated($this->output->isDecorated()); + + $reflectedOutput = new \ReflectionObject($this->output); + $strErrProperty = $reflectedOutput->getProperty('stderr'); + $strErrProperty->setAccessible(true); + $strErrProperty->setValue($this->output, $errorOutput); + + $reflectedParent = $reflectedOutput->getParentClass(); + $streamProperty = $reflectedParent->getProperty('stream'); + $streamProperty->setAccessible(true); + $streamProperty->setValue($this->output, fopen('php://memory', 'w', false)); + } + } + + /** + * @return resource + */ + private static function createStream(array $inputs) + { + $stream = fopen('php://memory', 'r+', false); + + foreach ($inputs as $input) { + fwrite($stream, $input.\PHP_EOL); + } + + rewind($stream); + + return $stream; + } +} diff --git a/php/libraries/composer/vendor/symfony/console/composer.json b/php/libraries/composer/vendor/symfony/console/composer.json new file mode 100644 index 0000000..4fa4964 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/console/composer.json @@ -0,0 +1,60 @@ +{ + "name": "symfony/console", + "type": "library", + "description": "Eases the creation of beautiful and testable command line interfaces", + "keywords": ["console", "cli", "command-line", "terminal"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.16", + "symfony/service-contracts": "^1.1|^2|^3", + "symfony/string": "^5.1|^6.0" + }, + "require-dev": { + "symfony/config": "^4.4|^5.0|^6.0", + "symfony/event-dispatcher": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/lock": "^4.4|^5.0|^6.0", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/var-dumper": "^4.4|^5.0|^6.0", + "psr/log": "^1|^2" + }, + "provide": { + "psr/log-implementation": "1.0|2.0" + }, + "suggest": { + "symfony/event-dispatcher": "", + "symfony/lock": "", + "symfony/process": "", + "psr/log": "For using the console logger" + }, + "conflict": { + "psr/log": ">=3", + "symfony/dependency-injection": "<4.4", + "symfony/dotenv": "<5.1", + "symfony/event-dispatcher": "<4.4", + "symfony/lock": "<4.4", + "symfony/process": "<4.4" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Console\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/CHANGELOG.md b/php/libraries/composer/vendor/symfony/css-selector/CHANGELOG.md new file mode 100644 index 0000000..c035d6b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/CHANGELOG.md @@ -0,0 +1,23 @@ +CHANGELOG +========= + +6.3 +----- + + * Add support for `:scope` + +4.4.0 +----- + + * Added support for `*:only-of-type` + +2.8.0 +----- + + * Added the `CssSelectorConverter` class as a non-static API for the component. + * Deprecated the `CssSelector` static API of the component. + +2.1.0 +----- + + * none diff --git a/php/libraries/composer/vendor/symfony/css-selector/CssSelectorConverter.php b/php/libraries/composer/vendor/symfony/css-selector/CssSelectorConverter.php new file mode 100644 index 0000000..7120a29 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/CssSelectorConverter.php @@ -0,0 +1,67 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector; + +use Symfony\Component\CssSelector\Parser\Shortcut\ClassParser; +use Symfony\Component\CssSelector\Parser\Shortcut\ElementParser; +use Symfony\Component\CssSelector\Parser\Shortcut\EmptyStringParser; +use Symfony\Component\CssSelector\Parser\Shortcut\HashParser; +use Symfony\Component\CssSelector\XPath\Extension\HtmlExtension; +use Symfony\Component\CssSelector\XPath\Translator; + +/** + * CssSelectorConverter is the main entry point of the component and can convert CSS + * selectors to XPath expressions. + * + * @author Christophe Coevoet <stof@notk.org> + */ +class CssSelectorConverter +{ + private Translator $translator; + private array $cache; + + private static array $xmlCache = []; + private static array $htmlCache = []; + + /** + * @param bool $html Whether HTML support should be enabled. Disable it for XML documents + */ + public function __construct(bool $html = true) + { + $this->translator = new Translator(); + + if ($html) { + $this->translator->registerExtension(new HtmlExtension($this->translator)); + $this->cache = &self::$htmlCache; + } else { + $this->cache = &self::$xmlCache; + } + + $this->translator + ->registerParserShortcut(new EmptyStringParser()) + ->registerParserShortcut(new ElementParser()) + ->registerParserShortcut(new ClassParser()) + ->registerParserShortcut(new HashParser()) + ; + } + + /** + * Translates a CSS expression to its XPath equivalent. + * + * Optionally, a prefix can be added to the resulting XPath + * expression with the $prefix parameter. + */ + public function toXPath(string $cssExpr, string $prefix = 'descendant-or-self::'): string + { + return $this->cache[$prefix][$cssExpr] ??= $this->translator->cssToXPath($cssExpr, $prefix); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/css-selector/Exception/ExceptionInterface.php new file mode 100644 index 0000000..9e25900 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Exception/ExceptionInterface.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Exception; + +/** + * Interface for exceptions. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Exception/ExpressionErrorException.php b/php/libraries/composer/vendor/symfony/css-selector/Exception/ExpressionErrorException.php new file mode 100644 index 0000000..fd5deea --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Exception/ExpressionErrorException.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Exception; + +/** + * ParseException is thrown when a CSS selector syntax is not valid. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + */ +class ExpressionErrorException extends ParseException +{ +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Exception/InternalErrorException.php b/php/libraries/composer/vendor/symfony/css-selector/Exception/InternalErrorException.php new file mode 100644 index 0000000..e60e5ed --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Exception/InternalErrorException.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Exception; + +/** + * ParseException is thrown when a CSS selector syntax is not valid. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + */ +class InternalErrorException extends ParseException +{ +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Exception/ParseException.php b/php/libraries/composer/vendor/symfony/css-selector/Exception/ParseException.php new file mode 100644 index 0000000..3b0b0ee --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Exception/ParseException.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Exception; + +/** + * ParseException is thrown when a CSS selector syntax is not valid. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class ParseException extends \Exception implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Exception/SyntaxErrorException.php b/php/libraries/composer/vendor/symfony/css-selector/Exception/SyntaxErrorException.php new file mode 100644 index 0000000..5a9d807 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Exception/SyntaxErrorException.php @@ -0,0 +1,55 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Exception; + +use Symfony\Component\CssSelector\Parser\Token; + +/** + * ParseException is thrown when a CSS selector syntax is not valid. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + */ +class SyntaxErrorException extends ParseException +{ + public static function unexpectedToken(string $expectedValue, Token $foundToken): self + { + return new self(sprintf('Expected %s, but %s found.', $expectedValue, $foundToken)); + } + + public static function pseudoElementFound(string $pseudoElement, string $unexpectedLocation): self + { + return new self(sprintf('Unexpected pseudo-element "::%s" found %s.', $pseudoElement, $unexpectedLocation)); + } + + public static function unclosedString(int $position): self + { + return new self(sprintf('Unclosed/invalid string at %s.', $position)); + } + + public static function nestedNot(): self + { + return new self('Got nested ::not().'); + } + + public static function notAtTheStartOfASelector(string $pseudoElement): self + { + return new self(sprintf('Got immediate child pseudo-element ":%s" not at the start of a selector', $pseudoElement)); + } + + public static function stringAsFunctionArgument(): self + { + return new self('String not allowed as function argument.'); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/LICENSE b/php/libraries/composer/vendor/symfony/css-selector/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/AbstractNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/AbstractNode.php new file mode 100644 index 0000000..d99e80a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/AbstractNode.php @@ -0,0 +1,32 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Abstract base node class. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +abstract class AbstractNode implements NodeInterface +{ + private string $nodeName; + + public function getNodeName(): string + { + return $this->nodeName ??= preg_replace('~.*\\\\([^\\\\]+)Node$~', '$1', static::class); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/AttributeNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/AttributeNode.php new file mode 100644 index 0000000..ba4df31 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/AttributeNode.php @@ -0,0 +1,79 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<selector>[<namespace>|<attribute> <operator> <value>]" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class AttributeNode extends AbstractNode +{ + private NodeInterface $selector; + private ?string $namespace; + private string $attribute; + private string $operator; + private ?string $value; + + public function __construct(NodeInterface $selector, ?string $namespace, string $attribute, string $operator, ?string $value) + { + $this->selector = $selector; + $this->namespace = $namespace; + $this->attribute = $attribute; + $this->operator = $operator; + $this->value = $value; + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getNamespace(): ?string + { + return $this->namespace; + } + + public function getAttribute(): string + { + return $this->attribute; + } + + public function getOperator(): string + { + return $this->operator; + } + + public function getValue(): ?string + { + return $this->value; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); + } + + public function __toString(): string + { + $attribute = $this->namespace ? $this->namespace.'|'.$this->attribute : $this->attribute; + + return 'exists' === $this->operator + ? sprintf('%s[%s[%s]]', $this->getNodeName(), $this->selector, $attribute) + : sprintf("%s[%s[%s %s '%s']]", $this->getNodeName(), $this->selector, $attribute, $this->operator, $this->value); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/ClassNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/ClassNode.php new file mode 100644 index 0000000..7174458 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/ClassNode.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<selector>.<name>" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class ClassNode extends AbstractNode +{ + private NodeInterface $selector; + private string $name; + + public function __construct(NodeInterface $selector, string $name) + { + $this->selector = $selector; + $this->name = $name; + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getName(): string + { + return $this->name; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); + } + + public function __toString(): string + { + return sprintf('%s[%s.%s]', $this->getNodeName(), $this->selector, $this->name); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/CombinedSelectorNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/CombinedSelectorNode.php new file mode 100644 index 0000000..19fecb7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/CombinedSelectorNode.php @@ -0,0 +1,63 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a combined node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class CombinedSelectorNode extends AbstractNode +{ + private NodeInterface $selector; + private string $combinator; + private NodeInterface $subSelector; + + public function __construct(NodeInterface $selector, string $combinator, NodeInterface $subSelector) + { + $this->selector = $selector; + $this->combinator = $combinator; + $this->subSelector = $subSelector; + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getCombinator(): string + { + return $this->combinator; + } + + public function getSubSelector(): NodeInterface + { + return $this->subSelector; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus($this->subSelector->getSpecificity()); + } + + public function __toString(): string + { + $combinator = ' ' === $this->combinator ? '<followed>' : $this->combinator; + + return sprintf('%s[%s %s %s]', $this->getNodeName(), $this->selector, $combinator, $this->subSelector); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/ElementNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/ElementNode.php new file mode 100644 index 0000000..76d2078 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/ElementNode.php @@ -0,0 +1,56 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<namespace>|<element>" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class ElementNode extends AbstractNode +{ + private ?string $namespace; + private ?string $element; + + public function __construct(?string $namespace = null, ?string $element = null) + { + $this->namespace = $namespace; + $this->element = $element; + } + + public function getNamespace(): ?string + { + return $this->namespace; + } + + public function getElement(): ?string + { + return $this->element; + } + + public function getSpecificity(): Specificity + { + return new Specificity(0, 0, $this->element ? 1 : 0); + } + + public function __toString(): string + { + $element = $this->element ?: '*'; + + return sprintf('%s[%s]', $this->getNodeName(), $this->namespace ? $this->namespace.'|'.$element : $element); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/FunctionNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/FunctionNode.php new file mode 100644 index 0000000..938a82b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/FunctionNode.php @@ -0,0 +1,71 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +use Symfony\Component\CssSelector\Parser\Token; + +/** + * Represents a "<selector>:<name>(<arguments>)" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class FunctionNode extends AbstractNode +{ + private NodeInterface $selector; + private string $name; + private array $arguments; + + /** + * @param Token[] $arguments + */ + public function __construct(NodeInterface $selector, string $name, array $arguments = []) + { + $this->selector = $selector; + $this->name = strtolower($name); + $this->arguments = $arguments; + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getName(): string + { + return $this->name; + } + + /** + * @return Token[] + */ + public function getArguments(): array + { + return $this->arguments; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); + } + + public function __toString(): string + { + $arguments = implode(', ', array_map(fn (Token $token) => "'".$token->getValue()."'", $this->arguments)); + + return sprintf('%s[%s:%s(%s)]', $this->getNodeName(), $this->selector, $this->name, $arguments ? '['.$arguments.']' : ''); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/HashNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/HashNode.php new file mode 100644 index 0000000..3af8e84 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/HashNode.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<selector>#<id>" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class HashNode extends AbstractNode +{ + private NodeInterface $selector; + private string $id; + + public function __construct(NodeInterface $selector, string $id) + { + $this->selector = $selector; + $this->id = $id; + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getId(): string + { + return $this->id; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus(new Specificity(1, 0, 0)); + } + + public function __toString(): string + { + return sprintf('%s[%s#%s]', $this->getNodeName(), $this->selector, $this->id); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/NegationNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/NegationNode.php new file mode 100644 index 0000000..f806758 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/NegationNode.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<selector>:not(<identifier>)" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class NegationNode extends AbstractNode +{ + private NodeInterface $selector; + private NodeInterface $subSelector; + + public function __construct(NodeInterface $selector, NodeInterface $subSelector) + { + $this->selector = $selector; + $this->subSelector = $subSelector; + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getSubSelector(): NodeInterface + { + return $this->subSelector; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus($this->subSelector->getSpecificity()); + } + + public function __toString(): string + { + return sprintf('%s[%s:not(%s)]', $this->getNodeName(), $this->selector, $this->subSelector); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/NodeInterface.php b/php/libraries/composer/vendor/symfony/css-selector/Node/NodeInterface.php new file mode 100644 index 0000000..7d541f9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/NodeInterface.php @@ -0,0 +1,29 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Interface for nodes. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +interface NodeInterface extends \Stringable +{ + public function getNodeName(): string; + + public function getSpecificity(): Specificity; +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/PseudoNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/PseudoNode.php new file mode 100644 index 0000000..c21cd6e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/PseudoNode.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<selector>:<identifier>" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class PseudoNode extends AbstractNode +{ + private NodeInterface $selector; + private string $identifier; + + public function __construct(NodeInterface $selector, string $identifier) + { + $this->selector = $selector; + $this->identifier = strtolower($identifier); + } + + public function getSelector(): NodeInterface + { + return $this->selector; + } + + public function getIdentifier(): string + { + return $this->identifier; + } + + public function getSpecificity(): Specificity + { + return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); + } + + public function __toString(): string + { + return sprintf('%s[%s:%s]', $this->getNodeName(), $this->selector, $this->identifier); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/SelectorNode.php b/php/libraries/composer/vendor/symfony/css-selector/Node/SelectorNode.php new file mode 100644 index 0000000..2318b2b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/SelectorNode.php @@ -0,0 +1,54 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a "<selector>(::|:)<pseudoElement>" node. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class SelectorNode extends AbstractNode +{ + private NodeInterface $tree; + private ?string $pseudoElement; + + public function __construct(NodeInterface $tree, ?string $pseudoElement = null) + { + $this->tree = $tree; + $this->pseudoElement = $pseudoElement ? strtolower($pseudoElement) : null; + } + + public function getTree(): NodeInterface + { + return $this->tree; + } + + public function getPseudoElement(): ?string + { + return $this->pseudoElement; + } + + public function getSpecificity(): Specificity + { + return $this->tree->getSpecificity()->plus(new Specificity(0, 0, $this->pseudoElement ? 1 : 0)); + } + + public function __toString(): string + { + return sprintf('%s[%s%s]', $this->getNodeName(), $this->tree, $this->pseudoElement ? '::'.$this->pseudoElement : ''); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Node/Specificity.php b/php/libraries/composer/vendor/symfony/css-selector/Node/Specificity.php new file mode 100644 index 0000000..bb8e5e3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Node/Specificity.php @@ -0,0 +1,73 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Node; + +/** + * Represents a node specificity. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @see http://www.w3.org/TR/selectors/#specificity + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class Specificity +{ + public const A_FACTOR = 100; + public const B_FACTOR = 10; + public const C_FACTOR = 1; + + private int $a; + private int $b; + private int $c; + + public function __construct(int $a, int $b, int $c) + { + $this->a = $a; + $this->b = $b; + $this->c = $c; + } + + public function plus(self $specificity): self + { + return new self($this->a + $specificity->a, $this->b + $specificity->b, $this->c + $specificity->c); + } + + public function getValue(): int + { + return $this->a * self::A_FACTOR + $this->b * self::B_FACTOR + $this->c * self::C_FACTOR; + } + + /** + * Returns -1 if the object specificity is lower than the argument, + * 0 if they are equal, and 1 if the argument is lower. + */ + public function compareTo(self $specificity): int + { + if ($this->a !== $specificity->a) { + return $this->a > $specificity->a ? 1 : -1; + } + + if ($this->b !== $specificity->b) { + return $this->b > $specificity->b ? 1 : -1; + } + + if ($this->c !== $specificity->c) { + return $this->c > $specificity->c ? 1 : -1; + } + + return 0; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/CommentHandler.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/CommentHandler.php new file mode 100644 index 0000000..cc01d1e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/CommentHandler.php @@ -0,0 +1,45 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector comment handler. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class CommentHandler implements HandlerInterface +{ + public function handle(Reader $reader, TokenStream $stream): bool + { + if ('/*' !== $reader->getSubstring(2)) { + return false; + } + + $offset = $reader->getOffset('*/'); + + if (false === $offset) { + $reader->moveToEnd(); + } else { + $reader->moveForward($offset + 2); + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/HandlerInterface.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/HandlerInterface.php new file mode 100644 index 0000000..9ec714d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/HandlerInterface.php @@ -0,0 +1,30 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector handler interface. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +interface HandlerInterface +{ + public function handle(Reader $reader, TokenStream $stream): bool; +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/HashHandler.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/HashHandler.php new file mode 100644 index 0000000..b29042f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/HashHandler.php @@ -0,0 +1,55 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\Token; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector comment handler. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class HashHandler implements HandlerInterface +{ + private TokenizerPatterns $patterns; + private TokenizerEscaping $escaping; + + public function __construct(TokenizerPatterns $patterns, TokenizerEscaping $escaping) + { + $this->patterns = $patterns; + $this->escaping = $escaping; + } + + public function handle(Reader $reader, TokenStream $stream): bool + { + $match = $reader->findPattern($this->patterns->getHashPattern()); + + if (!$match) { + return false; + } + + $value = $this->escaping->escapeUnicode($match[1]); + $stream->push(new Token(Token::TYPE_HASH, $value, $reader->getPosition())); + $reader->moveForward(\strlen($match[0])); + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/IdentifierHandler.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/IdentifierHandler.php new file mode 100644 index 0000000..25c0761 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/IdentifierHandler.php @@ -0,0 +1,55 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\Token; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector comment handler. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class IdentifierHandler implements HandlerInterface +{ + private TokenizerPatterns $patterns; + private TokenizerEscaping $escaping; + + public function __construct(TokenizerPatterns $patterns, TokenizerEscaping $escaping) + { + $this->patterns = $patterns; + $this->escaping = $escaping; + } + + public function handle(Reader $reader, TokenStream $stream): bool + { + $match = $reader->findPattern($this->patterns->getIdentifierPattern()); + + if (!$match) { + return false; + } + + $value = $this->escaping->escapeUnicode($match[0]); + $stream->push(new Token(Token::TYPE_IDENTIFIER, $value, $reader->getPosition())); + $reader->moveForward(\strlen($match[0])); + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/NumberHandler.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/NumberHandler.php new file mode 100644 index 0000000..e3eb7af --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/NumberHandler.php @@ -0,0 +1,51 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\Token; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector comment handler. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class NumberHandler implements HandlerInterface +{ + private TokenizerPatterns $patterns; + + public function __construct(TokenizerPatterns $patterns) + { + $this->patterns = $patterns; + } + + public function handle(Reader $reader, TokenStream $stream): bool + { + $match = $reader->findPattern($this->patterns->getNumberPattern()); + + if (!$match) { + return false; + } + + $stream->push(new Token(Token::TYPE_NUMBER, $match[0], $reader->getPosition())); + $reader->moveForward(\strlen($match[0])); + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/StringHandler.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/StringHandler.php new file mode 100644 index 0000000..5fd44df --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/StringHandler.php @@ -0,0 +1,74 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Exception\InternalErrorException; +use Symfony\Component\CssSelector\Exception\SyntaxErrorException; +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\Token; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping; +use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector comment handler. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class StringHandler implements HandlerInterface +{ + private TokenizerPatterns $patterns; + private TokenizerEscaping $escaping; + + public function __construct(TokenizerPatterns $patterns, TokenizerEscaping $escaping) + { + $this->patterns = $patterns; + $this->escaping = $escaping; + } + + public function handle(Reader $reader, TokenStream $stream): bool + { + $quote = $reader->getSubstring(1); + + if (!\in_array($quote, ["'", '"'])) { + return false; + } + + $reader->moveForward(1); + $match = $reader->findPattern($this->patterns->getQuotedStringPattern($quote)); + + if (!$match) { + throw new InternalErrorException(sprintf('Should have found at least an empty match at %d.', $reader->getPosition())); + } + + // check unclosed strings + if (\strlen($match[0]) === $reader->getRemainingLength()) { + throw SyntaxErrorException::unclosedString($reader->getPosition() - 1); + } + + // check quotes pairs validity + if ($quote !== $reader->getSubstring(1, \strlen($match[0]))) { + throw SyntaxErrorException::unclosedString($reader->getPosition() - 1); + } + + $string = $this->escaping->escapeUnicodeAndNewLine($match[0]); + $stream->push(new Token(Token::TYPE_STRING, $string, $reader->getPosition())); + $reader->moveForward(\strlen($match[0]) + 1); + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/WhitespaceHandler.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/WhitespaceHandler.php new file mode 100644 index 0000000..eb41c3f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Handler/WhitespaceHandler.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Handler; + +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\Token; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector whitespace handler. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class WhitespaceHandler implements HandlerInterface +{ + public function handle(Reader $reader, TokenStream $stream): bool + { + $match = $reader->findPattern('~^[ \t\r\n\f]+~'); + + if (false === $match) { + return false; + } + + $stream->push(new Token(Token::TYPE_WHITESPACE, $match[0], $reader->getPosition())); + $reader->moveForward(\strlen($match[0])); + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Parser.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Parser.php new file mode 100644 index 0000000..309c9b5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Parser.php @@ -0,0 +1,359 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser; + +use Symfony\Component\CssSelector\Exception\SyntaxErrorException; +use Symfony\Component\CssSelector\Node; +use Symfony\Component\CssSelector\Parser\Tokenizer\Tokenizer; + +/** + * CSS selector parser. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/scrapy/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class Parser implements ParserInterface +{ + private Tokenizer $tokenizer; + + public function __construct(?Tokenizer $tokenizer = null) + { + $this->tokenizer = $tokenizer ?? new Tokenizer(); + } + + public function parse(string $source): array + { + $reader = new Reader($source); + $stream = $this->tokenizer->tokenize($reader); + + return $this->parseSelectorList($stream); + } + + /** + * Parses the arguments for ":nth-child()" and friends. + * + * @param Token[] $tokens + * + * @throws SyntaxErrorException + */ + public static function parseSeries(array $tokens): array + { + foreach ($tokens as $token) { + if ($token->isString()) { + throw SyntaxErrorException::stringAsFunctionArgument(); + } + } + + $joined = trim(implode('', array_map(fn (Token $token) => $token->getValue(), $tokens))); + + $int = function ($string) { + if (!is_numeric($string)) { + throw SyntaxErrorException::stringAsFunctionArgument(); + } + + return (int) $string; + }; + + switch (true) { + case 'odd' === $joined: + return [2, 1]; + case 'even' === $joined: + return [2, 0]; + case 'n' === $joined: + return [1, 0]; + case !str_contains($joined, 'n'): + return [0, $int($joined)]; + } + + $split = explode('n', $joined); + $first = $split[0] ?? null; + + return [ + $first ? ('-' === $first || '+' === $first ? $int($first.'1') : $int($first)) : 1, + isset($split[1]) && $split[1] ? $int($split[1]) : 0, + ]; + } + + private function parseSelectorList(TokenStream $stream): array + { + $stream->skipWhitespace(); + $selectors = []; + + while (true) { + $selectors[] = $this->parserSelectorNode($stream); + + if ($stream->getPeek()->isDelimiter([','])) { + $stream->getNext(); + $stream->skipWhitespace(); + } else { + break; + } + } + + return $selectors; + } + + private function parserSelectorNode(TokenStream $stream): Node\SelectorNode + { + [$result, $pseudoElement] = $this->parseSimpleSelector($stream); + + while (true) { + $stream->skipWhitespace(); + $peek = $stream->getPeek(); + + if ($peek->isFileEnd() || $peek->isDelimiter([','])) { + break; + } + + if (null !== $pseudoElement) { + throw SyntaxErrorException::pseudoElementFound($pseudoElement, 'not at the end of a selector'); + } + + if ($peek->isDelimiter(['+', '>', '~'])) { + $combinator = $stream->getNext()->getValue(); + $stream->skipWhitespace(); + } else { + $combinator = ' '; + } + + [$nextSelector, $pseudoElement] = $this->parseSimpleSelector($stream); + $result = new Node\CombinedSelectorNode($result, $combinator, $nextSelector); + } + + return new Node\SelectorNode($result, $pseudoElement); + } + + /** + * Parses next simple node (hash, class, pseudo, negation). + * + * @throws SyntaxErrorException + */ + private function parseSimpleSelector(TokenStream $stream, bool $insideNegation = false): array + { + $stream->skipWhitespace(); + + $selectorStart = \count($stream->getUsed()); + $result = $this->parseElementNode($stream); + $pseudoElement = null; + + while (true) { + $peek = $stream->getPeek(); + if ($peek->isWhitespace() + || $peek->isFileEnd() + || $peek->isDelimiter([',', '+', '>', '~']) + || ($insideNegation && $peek->isDelimiter([')'])) + ) { + break; + } + + if (null !== $pseudoElement) { + throw SyntaxErrorException::pseudoElementFound($pseudoElement, 'not at the end of a selector'); + } + + if ($peek->isHash()) { + $result = new Node\HashNode($result, $stream->getNext()->getValue()); + } elseif ($peek->isDelimiter(['.'])) { + $stream->getNext(); + $result = new Node\ClassNode($result, $stream->getNextIdentifier()); + } elseif ($peek->isDelimiter(['['])) { + $stream->getNext(); + $result = $this->parseAttributeNode($result, $stream); + } elseif ($peek->isDelimiter([':'])) { + $stream->getNext(); + + if ($stream->getPeek()->isDelimiter([':'])) { + $stream->getNext(); + $pseudoElement = $stream->getNextIdentifier(); + + continue; + } + + $identifier = $stream->getNextIdentifier(); + if (\in_array(strtolower($identifier), ['first-line', 'first-letter', 'before', 'after'])) { + // Special case: CSS 2.1 pseudo-elements can have a single ':'. + // Any new pseudo-element must have two. + $pseudoElement = $identifier; + + continue; + } + + if (!$stream->getPeek()->isDelimiter(['('])) { + $result = new Node\PseudoNode($result, $identifier); + if ('Pseudo[Element[*]:scope]' === $result->__toString()) { + $used = \count($stream->getUsed()); + if (!(2 === $used + || 3 === $used && $stream->getUsed()[0]->isWhiteSpace() + || $used >= 3 && $stream->getUsed()[$used - 3]->isDelimiter([',']) + || $used >= 4 + && $stream->getUsed()[$used - 3]->isWhiteSpace() + && $stream->getUsed()[$used - 4]->isDelimiter([',']) + )) { + throw SyntaxErrorException::notAtTheStartOfASelector('scope'); + } + } + continue; + } + + $stream->getNext(); + $stream->skipWhitespace(); + + if ('not' === strtolower($identifier)) { + if ($insideNegation) { + throw SyntaxErrorException::nestedNot(); + } + + [$argument, $argumentPseudoElement] = $this->parseSimpleSelector($stream, true); + $next = $stream->getNext(); + + if (null !== $argumentPseudoElement) { + throw SyntaxErrorException::pseudoElementFound($argumentPseudoElement, 'inside ::not()'); + } + + if (!$next->isDelimiter([')'])) { + throw SyntaxErrorException::unexpectedToken('")"', $next); + } + + $result = new Node\NegationNode($result, $argument); + } else { + $arguments = []; + $next = null; + + while (true) { + $stream->skipWhitespace(); + $next = $stream->getNext(); + + if ($next->isIdentifier() + || $next->isString() + || $next->isNumber() + || $next->isDelimiter(['+', '-']) + ) { + $arguments[] = $next; + } elseif ($next->isDelimiter([')'])) { + break; + } else { + throw SyntaxErrorException::unexpectedToken('an argument', $next); + } + } + + if (!$arguments) { + throw SyntaxErrorException::unexpectedToken('at least one argument', $next); + } + + $result = new Node\FunctionNode($result, $identifier, $arguments); + } + } else { + throw SyntaxErrorException::unexpectedToken('selector', $peek); + } + } + + if (\count($stream->getUsed()) === $selectorStart) { + throw SyntaxErrorException::unexpectedToken('selector', $stream->getPeek()); + } + + return [$result, $pseudoElement]; + } + + private function parseElementNode(TokenStream $stream): Node\ElementNode + { + $peek = $stream->getPeek(); + + if ($peek->isIdentifier() || $peek->isDelimiter(['*'])) { + if ($peek->isIdentifier()) { + $namespace = $stream->getNext()->getValue(); + } else { + $stream->getNext(); + $namespace = null; + } + + if ($stream->getPeek()->isDelimiter(['|'])) { + $stream->getNext(); + $element = $stream->getNextIdentifierOrStar(); + } else { + $element = $namespace; + $namespace = null; + } + } else { + $element = $namespace = null; + } + + return new Node\ElementNode($namespace, $element); + } + + private function parseAttributeNode(Node\NodeInterface $selector, TokenStream $stream): Node\AttributeNode + { + $stream->skipWhitespace(); + $attribute = $stream->getNextIdentifierOrStar(); + + if (null === $attribute && !$stream->getPeek()->isDelimiter(['|'])) { + throw SyntaxErrorException::unexpectedToken('"|"', $stream->getPeek()); + } + + if ($stream->getPeek()->isDelimiter(['|'])) { + $stream->getNext(); + + if ($stream->getPeek()->isDelimiter(['='])) { + $namespace = null; + $stream->getNext(); + $operator = '|='; + } else { + $namespace = $attribute; + $attribute = $stream->getNextIdentifier(); + $operator = null; + } + } else { + $namespace = $operator = null; + } + + if (null === $operator) { + $stream->skipWhitespace(); + $next = $stream->getNext(); + + if ($next->isDelimiter([']'])) { + return new Node\AttributeNode($selector, $namespace, $attribute, 'exists', null); + } elseif ($next->isDelimiter(['='])) { + $operator = '='; + } elseif ($next->isDelimiter(['^', '$', '*', '~', '|', '!']) + && $stream->getPeek()->isDelimiter(['=']) + ) { + $operator = $next->getValue().'='; + $stream->getNext(); + } else { + throw SyntaxErrorException::unexpectedToken('operator', $next); + } + } + + $stream->skipWhitespace(); + $value = $stream->getNext(); + + if ($value->isNumber()) { + // if the value is a number, it's casted into a string + $value = new Token(Token::TYPE_STRING, (string) $value->getValue(), $value->getPosition()); + } + + if (!($value->isIdentifier() || $value->isString())) { + throw SyntaxErrorException::unexpectedToken('string or identifier', $value); + } + + $stream->skipWhitespace(); + $next = $stream->getNext(); + + if (!$next->isDelimiter([']'])) { + throw SyntaxErrorException::unexpectedToken('"]"', $next); + } + + return new Node\AttributeNode($selector, $namespace, $attribute, $operator, $value->getValue()); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/ParserInterface.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/ParserInterface.php new file mode 100644 index 0000000..51c3d93 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/ParserInterface.php @@ -0,0 +1,34 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser; + +use Symfony\Component\CssSelector\Node\SelectorNode; + +/** + * CSS selector parser interface. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +interface ParserInterface +{ + /** + * Parses given selector source into an array of tokens. + * + * @return SelectorNode[] + */ + public function parse(string $source): array; +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Reader.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Reader.php new file mode 100644 index 0000000..a280a48 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Reader.php @@ -0,0 +1,83 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser; + +/** + * CSS selector reader. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class Reader +{ + private string $source; + private int $length; + private int $position = 0; + + public function __construct(string $source) + { + $this->source = $source; + $this->length = \strlen($source); + } + + public function isEOF(): bool + { + return $this->position >= $this->length; + } + + public function getPosition(): int + { + return $this->position; + } + + public function getRemainingLength(): int + { + return $this->length - $this->position; + } + + public function getSubstring(int $length, int $offset = 0): string + { + return substr($this->source, $this->position + $offset, $length); + } + + public function getOffset(string $string): int|false + { + $position = strpos($this->source, $string, $this->position); + + return false === $position ? false : $position - $this->position; + } + + public function findPattern(string $pattern): array|false + { + $source = substr($this->source, $this->position); + + if (preg_match($pattern, $source, $matches)) { + return $matches; + } + + return false; + } + + public function moveForward(int $length): void + { + $this->position += $length; + } + + public function moveToEnd(): void + { + $this->position = $this->length; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/ClassParser.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/ClassParser.php new file mode 100644 index 0000000..f0ce611 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/ClassParser.php @@ -0,0 +1,48 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Shortcut; + +use Symfony\Component\CssSelector\Node\ClassNode; +use Symfony\Component\CssSelector\Node\ElementNode; +use Symfony\Component\CssSelector\Node\SelectorNode; +use Symfony\Component\CssSelector\Parser\ParserInterface; + +/** + * CSS selector class parser shortcut. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class ClassParser implements ParserInterface +{ + public function parse(string $source): array + { + // Matches an optional namespace, optional element, and required class + // $source = 'test|input.ab6bd_field'; + // $matches = array (size=4) + // 0 => string 'test|input.ab6bd_field' (length=22) + // 1 => string 'test' (length=4) + // 2 => string 'input' (length=5) + // 3 => string 'ab6bd_field' (length=11) + if (preg_match('/^(?:([a-z]++)\|)?+([\w-]++|\*)?+\.([\w-]++)$/i', trim($source), $matches)) { + return [ + new SelectorNode(new ClassNode(new ElementNode($matches[1] ?: null, $matches[2] ?: null), $matches[3])), + ]; + } + + return []; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/ElementParser.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/ElementParser.php new file mode 100644 index 0000000..a448e4a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/ElementParser.php @@ -0,0 +1,44 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Shortcut; + +use Symfony\Component\CssSelector\Node\ElementNode; +use Symfony\Component\CssSelector\Node\SelectorNode; +use Symfony\Component\CssSelector\Parser\ParserInterface; + +/** + * CSS selector element parser shortcut. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class ElementParser implements ParserInterface +{ + public function parse(string $source): array + { + // Matches an optional namespace, required element or `*` + // $source = 'testns|testel'; + // $matches = array (size=3) + // 0 => string 'testns|testel' (length=13) + // 1 => string 'testns' (length=6) + // 2 => string 'testel' (length=6) + if (preg_match('/^(?:([a-z]++)\|)?([\w-]++|\*)$/i', trim($source), $matches)) { + return [new SelectorNode(new ElementNode($matches[1] ?: null, $matches[2]))]; + } + + return []; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/EmptyStringParser.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/EmptyStringParser.php new file mode 100644 index 0000000..a639191 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/EmptyStringParser.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Shortcut; + +use Symfony\Component\CssSelector\Node\ElementNode; +use Symfony\Component\CssSelector\Node\SelectorNode; +use Symfony\Component\CssSelector\Parser\ParserInterface; + +/** + * CSS selector class parser shortcut. + * + * This shortcut ensure compatibility with previous version. + * - The parser fails to parse an empty string. + * - In the previous version, an empty string matches each tags. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class EmptyStringParser implements ParserInterface +{ + public function parse(string $source): array + { + // Matches an empty string + if ('' == $source) { + return [new SelectorNode(new ElementNode(null, '*'))]; + } + + return []; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/HashParser.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/HashParser.php new file mode 100644 index 0000000..6683126 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Shortcut/HashParser.php @@ -0,0 +1,48 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Shortcut; + +use Symfony\Component\CssSelector\Node\ElementNode; +use Symfony\Component\CssSelector\Node\HashNode; +use Symfony\Component\CssSelector\Node\SelectorNode; +use Symfony\Component\CssSelector\Parser\ParserInterface; + +/** + * CSS selector hash parser shortcut. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class HashParser implements ParserInterface +{ + public function parse(string $source): array + { + // Matches an optional namespace, optional element, and required id + // $source = 'test|input#ab6bd_field'; + // $matches = array (size=4) + // 0 => string 'test|input#ab6bd_field' (length=22) + // 1 => string 'test' (length=4) + // 2 => string 'input' (length=5) + // 3 => string 'ab6bd_field' (length=11) + if (preg_match('/^(?:([a-z]++)\|)?+([\w-]++|\*)?+#([\w-]++)$/i', trim($source), $matches)) { + return [ + new SelectorNode(new HashNode(new ElementNode($matches[1] ?: null, $matches[2] ?: null), $matches[3])), + ]; + } + + return []; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Token.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Token.php new file mode 100644 index 0000000..b50441a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Token.php @@ -0,0 +1,111 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser; + +/** + * CSS selector token. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class Token +{ + public const TYPE_FILE_END = 'eof'; + public const TYPE_DELIMITER = 'delimiter'; + public const TYPE_WHITESPACE = 'whitespace'; + public const TYPE_IDENTIFIER = 'identifier'; + public const TYPE_HASH = 'hash'; + public const TYPE_NUMBER = 'number'; + public const TYPE_STRING = 'string'; + + private ?string $type; + private ?string $value; + private ?int $position; + + public function __construct(?string $type, ?string $value, ?int $position) + { + $this->type = $type; + $this->value = $value; + $this->position = $position; + } + + public function getType(): ?int + { + return $this->type; + } + + public function getValue(): ?string + { + return $this->value; + } + + public function getPosition(): ?int + { + return $this->position; + } + + public function isFileEnd(): bool + { + return self::TYPE_FILE_END === $this->type; + } + + public function isDelimiter(array $values = []): bool + { + if (self::TYPE_DELIMITER !== $this->type) { + return false; + } + + if (!$values) { + return true; + } + + return \in_array($this->value, $values); + } + + public function isWhitespace(): bool + { + return self::TYPE_WHITESPACE === $this->type; + } + + public function isIdentifier(): bool + { + return self::TYPE_IDENTIFIER === $this->type; + } + + public function isHash(): bool + { + return self::TYPE_HASH === $this->type; + } + + public function isNumber(): bool + { + return self::TYPE_NUMBER === $this->type; + } + + public function isString(): bool + { + return self::TYPE_STRING === $this->type; + } + + public function __toString(): string + { + if ($this->value) { + return sprintf('<%s "%s" at %s>', $this->type, $this->value, $this->position); + } + + return sprintf('<%s at %s>', $this->type, $this->position); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/TokenStream.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/TokenStream.php new file mode 100644 index 0000000..8b72d5d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/TokenStream.php @@ -0,0 +1,156 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser; + +use Symfony\Component\CssSelector\Exception\InternalErrorException; +use Symfony\Component\CssSelector\Exception\SyntaxErrorException; + +/** + * CSS selector token stream. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class TokenStream +{ + /** + * @var Token[] + */ + private array $tokens = []; + + /** + * @var Token[] + */ + private array $used = []; + + private int $cursor = 0; + private ?Token $peeked; + private bool $peeking = false; + + /** + * Pushes a token. + * + * @return $this + */ + public function push(Token $token): static + { + $this->tokens[] = $token; + + return $this; + } + + /** + * Freezes stream. + * + * @return $this + */ + public function freeze(): static + { + return $this; + } + + /** + * Returns next token. + * + * @throws InternalErrorException If there is no more token + */ + public function getNext(): Token + { + if ($this->peeking) { + $this->peeking = false; + $this->used[] = $this->peeked; + + return $this->peeked; + } + + if (!isset($this->tokens[$this->cursor])) { + throw new InternalErrorException('Unexpected token stream end.'); + } + + return $this->tokens[$this->cursor++]; + } + + /** + * Returns peeked token. + */ + public function getPeek(): Token + { + if (!$this->peeking) { + $this->peeked = $this->getNext(); + $this->peeking = true; + } + + return $this->peeked; + } + + /** + * Returns used tokens. + * + * @return Token[] + */ + public function getUsed(): array + { + return $this->used; + } + + /** + * Returns next identifier token. + * + * @throws SyntaxErrorException If next token is not an identifier + */ + public function getNextIdentifier(): string + { + $next = $this->getNext(); + + if (!$next->isIdentifier()) { + throw SyntaxErrorException::unexpectedToken('identifier', $next); + } + + return $next->getValue(); + } + + /** + * Returns next identifier or null if star delimiter token is found. + * + * @throws SyntaxErrorException If next token is not an identifier or a star delimiter + */ + public function getNextIdentifierOrStar(): ?string + { + $next = $this->getNext(); + + if ($next->isIdentifier()) { + return $next->getValue(); + } + + if ($next->isDelimiter(['*'])) { + return null; + } + + throw SyntaxErrorException::unexpectedToken('identifier or "*"', $next); + } + + /** + * Skips next whitespace if any. + */ + public function skipWhitespace(): void + { + $peek = $this->getPeek(); + + if ($peek->isWhitespace()) { + $this->getNext(); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/Tokenizer.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/Tokenizer.php new file mode 100644 index 0000000..35c96a4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/Tokenizer.php @@ -0,0 +1,73 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Tokenizer; + +use Symfony\Component\CssSelector\Parser\Handler; +use Symfony\Component\CssSelector\Parser\Reader; +use Symfony\Component\CssSelector\Parser\Token; +use Symfony\Component\CssSelector\Parser\TokenStream; + +/** + * CSS selector tokenizer. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class Tokenizer +{ + /** + * @var Handler\HandlerInterface[] + */ + private array $handlers; + + public function __construct() + { + $patterns = new TokenizerPatterns(); + $escaping = new TokenizerEscaping($patterns); + + $this->handlers = [ + new Handler\WhitespaceHandler(), + new Handler\IdentifierHandler($patterns, $escaping), + new Handler\HashHandler($patterns, $escaping), + new Handler\StringHandler($patterns, $escaping), + new Handler\NumberHandler($patterns), + new Handler\CommentHandler(), + ]; + } + + /** + * Tokenize selector source code. + */ + public function tokenize(Reader $reader): TokenStream + { + $stream = new TokenStream(); + + while (!$reader->isEOF()) { + foreach ($this->handlers as $handler) { + if ($handler->handle($reader, $stream)) { + continue 2; + } + } + + $stream->push(new Token(Token::TYPE_DELIMITER, $reader->getSubstring(1), $reader->getPosition())); + $reader->moveForward(1); + } + + return $stream + ->push(new Token(Token::TYPE_FILE_END, null, $reader->getPosition())) + ->freeze(); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php new file mode 100644 index 0000000..8c4b9f7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Tokenizer; + +/** + * CSS selector tokenizer escaping applier. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class TokenizerEscaping +{ + private TokenizerPatterns $patterns; + + public function __construct(TokenizerPatterns $patterns) + { + $this->patterns = $patterns; + } + + public function escapeUnicode(string $value): string + { + $value = $this->replaceUnicodeSequences($value); + + return preg_replace($this->patterns->getSimpleEscapePattern(), '$1', $value); + } + + public function escapeUnicodeAndNewLine(string $value): string + { + $value = preg_replace($this->patterns->getNewLineEscapePattern(), '', $value); + + return $this->escapeUnicode($value); + } + + private function replaceUnicodeSequences(string $value): string + { + return preg_replace_callback($this->patterns->getUnicodeEscapePattern(), function ($match) { + $c = hexdec($match[1]); + + if (0x80 > $c %= 0x200000) { + return \chr($c); + } + if (0x800 > $c) { + return \chr(0xC0 | $c >> 6).\chr(0x80 | $c & 0x3F); + } + if (0x10000 > $c) { + return \chr(0xE0 | $c >> 12).\chr(0x80 | $c >> 6 & 0x3F).\chr(0x80 | $c & 0x3F); + } + + return ''; + }, $value); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/TokenizerPatterns.php b/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/TokenizerPatterns.php new file mode 100644 index 0000000..3c77cf0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/Parser/Tokenizer/TokenizerPatterns.php @@ -0,0 +1,89 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\Parser\Tokenizer; + +/** + * CSS selector tokenizer patterns builder. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class TokenizerPatterns +{ + private string $unicodeEscapePattern; + private string $simpleEscapePattern; + private string $newLineEscapePattern; + private string $escapePattern; + private string $stringEscapePattern; + private string $nonAsciiPattern; + private string $nmCharPattern; + private string $nmStartPattern; + private string $identifierPattern; + private string $hashPattern; + private string $numberPattern; + private string $quotedStringPattern; + + public function __construct() + { + $this->unicodeEscapePattern = '\\\\([0-9a-f]{1,6})(?:\r\n|[ \n\r\t\f])?'; + $this->simpleEscapePattern = '\\\\(.)'; + $this->newLineEscapePattern = '\\\\(?:\n|\r\n|\r|\f)'; + $this->escapePattern = $this->unicodeEscapePattern.'|\\\\[^\n\r\f0-9a-f]'; + $this->stringEscapePattern = $this->newLineEscapePattern.'|'.$this->escapePattern; + $this->nonAsciiPattern = '[^\x00-\x7F]'; + $this->nmCharPattern = '[_a-z0-9-]|'.$this->escapePattern.'|'.$this->nonAsciiPattern; + $this->nmStartPattern = '[_a-z]|'.$this->escapePattern.'|'.$this->nonAsciiPattern; + $this->identifierPattern = '-?(?:'.$this->nmStartPattern.')(?:'.$this->nmCharPattern.')*'; + $this->hashPattern = '#((?:'.$this->nmCharPattern.')+)'; + $this->numberPattern = '[+-]?(?:[0-9]*\.[0-9]+|[0-9]+)'; + $this->quotedStringPattern = '([^\n\r\f\\\\%s]|'.$this->stringEscapePattern.')*'; + } + + public function getNewLineEscapePattern(): string + { + return '~'.$this->newLineEscapePattern.'~'; + } + + public function getSimpleEscapePattern(): string + { + return '~'.$this->simpleEscapePattern.'~'; + } + + public function getUnicodeEscapePattern(): string + { + return '~'.$this->unicodeEscapePattern.'~i'; + } + + public function getIdentifierPattern(): string + { + return '~^'.$this->identifierPattern.'~i'; + } + + public function getHashPattern(): string + { + return '~^'.$this->hashPattern.'~i'; + } + + public function getNumberPattern(): string + { + return '~^'.$this->numberPattern.'~'; + } + + public function getQuotedStringPattern(string $quote): string + { + return '~^'.sprintf($this->quotedStringPattern, $quote).'~i'; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/README.md b/php/libraries/composer/vendor/symfony/css-selector/README.md new file mode 100644 index 0000000..ede4a3a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/README.md @@ -0,0 +1,20 @@ +CssSelector Component +===================== + +The CssSelector component converts CSS selectors to XPath expressions. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/css_selector.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +Credits +------- + +This component is a port of the Python cssselect library +[v0.7.1](https://github.com/SimonSapin/cssselect/releases/tag/v0.7.1), +which is distributed under the BSD license. diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/AbstractExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/AbstractExtension.php new file mode 100644 index 0000000..495f882 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/AbstractExtension.php @@ -0,0 +1,50 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +/** + * XPath expression translator abstract extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +abstract class AbstractExtension implements ExtensionInterface +{ + public function getNodeTranslators(): array + { + return []; + } + + public function getCombinationTranslators(): array + { + return []; + } + + public function getFunctionTranslators(): array + { + return []; + } + + public function getPseudoClassTranslators(): array + { + return []; + } + + public function getAttributeMatchingTranslators(): array + { + return []; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php new file mode 100644 index 0000000..3c785e9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php @@ -0,0 +1,113 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +use Symfony\Component\CssSelector\XPath\Translator; +use Symfony\Component\CssSelector\XPath\XPathExpr; + +/** + * XPath expression translator attribute extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class AttributeMatchingExtension extends AbstractExtension +{ + public function getAttributeMatchingTranslators(): array + { + return [ + 'exists' => $this->translateExists(...), + '=' => $this->translateEquals(...), + '~=' => $this->translateIncludes(...), + '|=' => $this->translateDashMatch(...), + '^=' => $this->translatePrefixMatch(...), + '$=' => $this->translateSuffixMatch(...), + '*=' => $this->translateSubstringMatch(...), + '!=' => $this->translateDifferent(...), + ]; + } + + public function translateExists(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition($attribute); + } + + public function translateEquals(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition(sprintf('%s = %s', $attribute, Translator::getXpathLiteral($value))); + } + + public function translateIncludes(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition($value ? sprintf( + '%1$s and contains(concat(\' \', normalize-space(%1$s), \' \'), %2$s)', + $attribute, + Translator::getXpathLiteral(' '.$value.' ') + ) : '0'); + } + + public function translateDashMatch(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition(sprintf( + '%1$s and (%1$s = %2$s or starts-with(%1$s, %3$s))', + $attribute, + Translator::getXpathLiteral($value), + Translator::getXpathLiteral($value.'-') + )); + } + + public function translatePrefixMatch(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition($value ? sprintf( + '%1$s and starts-with(%1$s, %2$s)', + $attribute, + Translator::getXpathLiteral($value) + ) : '0'); + } + + public function translateSuffixMatch(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition($value ? sprintf( + '%1$s and substring(%1$s, string-length(%1$s)-%2$s) = %3$s', + $attribute, + \strlen($value) - 1, + Translator::getXpathLiteral($value) + ) : '0'); + } + + public function translateSubstringMatch(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition($value ? sprintf( + '%1$s and contains(%1$s, %2$s)', + $attribute, + Translator::getXpathLiteral($value) + ) : '0'); + } + + public function translateDifferent(XPathExpr $xpath, string $attribute, ?string $value): XPathExpr + { + return $xpath->addCondition(sprintf( + $value ? 'not(%1$s) or %1$s != %2$s' : '%s != %s', + $attribute, + Translator::getXpathLiteral($value) + )); + } + + public function getName(): string + { + return 'attribute-matching'; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/CombinationExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/CombinationExtension.php new file mode 100644 index 0000000..f78d488 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/CombinationExtension.php @@ -0,0 +1,65 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +use Symfony\Component\CssSelector\XPath\XPathExpr; + +/** + * XPath expression translator combination extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class CombinationExtension extends AbstractExtension +{ + public function getCombinationTranslators(): array + { + return [ + ' ' => $this->translateDescendant(...), + '>' => $this->translateChild(...), + '+' => $this->translateDirectAdjacent(...), + '~' => $this->translateIndirectAdjacent(...), + ]; + } + + public function translateDescendant(XPathExpr $xpath, XPathExpr $combinedXpath): XPathExpr + { + return $xpath->join('/descendant-or-self::*/', $combinedXpath); + } + + public function translateChild(XPathExpr $xpath, XPathExpr $combinedXpath): XPathExpr + { + return $xpath->join('/', $combinedXpath); + } + + public function translateDirectAdjacent(XPathExpr $xpath, XPathExpr $combinedXpath): XPathExpr + { + return $xpath + ->join('/following-sibling::', $combinedXpath) + ->addNameTest() + ->addCondition('position() = 1'); + } + + public function translateIndirectAdjacent(XPathExpr $xpath, XPathExpr $combinedXpath): XPathExpr + { + return $xpath->join('/following-sibling::', $combinedXpath); + } + + public function getName(): string + { + return 'combination'; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/ExtensionInterface.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/ExtensionInterface.php new file mode 100644 index 0000000..1a74b90 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/ExtensionInterface.php @@ -0,0 +1,67 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +/** + * XPath expression translator extension interface. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +interface ExtensionInterface +{ + /** + * Returns node translators. + * + * These callables will receive the node as first argument and the translator as second argument. + * + * @return callable[] + */ + public function getNodeTranslators(): array; + + /** + * Returns combination translators. + * + * @return callable[] + */ + public function getCombinationTranslators(): array; + + /** + * Returns function translators. + * + * @return callable[] + */ + public function getFunctionTranslators(): array; + + /** + * Returns pseudo-class translators. + * + * @return callable[] + */ + public function getPseudoClassTranslators(): array; + + /** + * Returns attribute operation translators. + * + * @return callable[] + */ + public function getAttributeMatchingTranslators(): array; + + /** + * Returns extension name. + */ + public function getName(): string; +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/FunctionExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/FunctionExtension.php new file mode 100644 index 0000000..4b9d7bc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/FunctionExtension.php @@ -0,0 +1,165 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +use Symfony\Component\CssSelector\Exception\ExpressionErrorException; +use Symfony\Component\CssSelector\Exception\SyntaxErrorException; +use Symfony\Component\CssSelector\Node\FunctionNode; +use Symfony\Component\CssSelector\Parser\Parser; +use Symfony\Component\CssSelector\XPath\Translator; +use Symfony\Component\CssSelector\XPath\XPathExpr; + +/** + * XPath expression translator function extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class FunctionExtension extends AbstractExtension +{ + public function getFunctionTranslators(): array + { + return [ + 'nth-child' => $this->translateNthChild(...), + 'nth-last-child' => $this->translateNthLastChild(...), + 'nth-of-type' => $this->translateNthOfType(...), + 'nth-last-of-type' => $this->translateNthLastOfType(...), + 'contains' => $this->translateContains(...), + 'lang' => $this->translateLang(...), + ]; + } + + /** + * @throws ExpressionErrorException + */ + public function translateNthChild(XPathExpr $xpath, FunctionNode $function, bool $last = false, bool $addNameTest = true): XPathExpr + { + try { + [$a, $b] = Parser::parseSeries($function->getArguments()); + } catch (SyntaxErrorException $e) { + throw new ExpressionErrorException(sprintf('Invalid series: "%s".', implode('", "', $function->getArguments())), 0, $e); + } + + $xpath->addStarPrefix(); + if ($addNameTest) { + $xpath->addNameTest(); + } + + if (0 === $a) { + return $xpath->addCondition('position() = '.($last ? 'last() - '.($b - 1) : $b)); + } + + if ($a < 0) { + if ($b < 1) { + return $xpath->addCondition('false()'); + } + + $sign = '<='; + } else { + $sign = '>='; + } + + $expr = 'position()'; + + if ($last) { + $expr = 'last() - '.$expr; + --$b; + } + + if (0 !== $b) { + $expr .= ' - '.$b; + } + + $conditions = [sprintf('%s %s 0', $expr, $sign)]; + + if (1 !== $a && -1 !== $a) { + $conditions[] = sprintf('(%s) mod %d = 0', $expr, $a); + } + + return $xpath->addCondition(implode(' and ', $conditions)); + + // todo: handle an+b, odd, even + // an+b means every-a, plus b, e.g., 2n+1 means odd + // 0n+b means b + // n+0 means a=1, i.e., all elements + // an means every a elements, i.e., 2n means even + // -n means -1n + // -1n+6 means elements 6 and previous + } + + public function translateNthLastChild(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + return $this->translateNthChild($xpath, $function, true); + } + + public function translateNthOfType(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + return $this->translateNthChild($xpath, $function, false, false); + } + + /** + * @throws ExpressionErrorException + */ + public function translateNthLastOfType(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + if ('*' === $xpath->getElement()) { + throw new ExpressionErrorException('"*:nth-of-type()" is not implemented.'); + } + + return $this->translateNthChild($xpath, $function, true, false); + } + + /** + * @throws ExpressionErrorException + */ + public function translateContains(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + $arguments = $function->getArguments(); + foreach ($arguments as $token) { + if (!($token->isString() || $token->isIdentifier())) { + throw new ExpressionErrorException('Expected a single string or identifier for :contains(), got '.implode(', ', $arguments)); + } + } + + return $xpath->addCondition(sprintf( + 'contains(string(.), %s)', + Translator::getXpathLiteral($arguments[0]->getValue()) + )); + } + + /** + * @throws ExpressionErrorException + */ + public function translateLang(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + $arguments = $function->getArguments(); + foreach ($arguments as $token) { + if (!($token->isString() || $token->isIdentifier())) { + throw new ExpressionErrorException('Expected a single string or identifier for :lang(), got '.implode(', ', $arguments)); + } + } + + return $xpath->addCondition(sprintf( + 'lang(%s)', + Translator::getXpathLiteral($arguments[0]->getValue()) + )); + } + + public function getName(): string + { + return 'function'; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/HtmlExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/HtmlExtension.php new file mode 100644 index 0000000..4653add --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/HtmlExtension.php @@ -0,0 +1,178 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +use Symfony\Component\CssSelector\Exception\ExpressionErrorException; +use Symfony\Component\CssSelector\Node\FunctionNode; +use Symfony\Component\CssSelector\XPath\Translator; +use Symfony\Component\CssSelector\XPath\XPathExpr; + +/** + * XPath expression translator HTML extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class HtmlExtension extends AbstractExtension +{ + public function __construct(Translator $translator) + { + $translator + ->getExtension('node') + ->setFlag(NodeExtension::ELEMENT_NAME_IN_LOWER_CASE, true) + ->setFlag(NodeExtension::ATTRIBUTE_NAME_IN_LOWER_CASE, true); + } + + public function getPseudoClassTranslators(): array + { + return [ + 'checked' => $this->translateChecked(...), + 'link' => $this->translateLink(...), + 'disabled' => $this->translateDisabled(...), + 'enabled' => $this->translateEnabled(...), + 'selected' => $this->translateSelected(...), + 'invalid' => $this->translateInvalid(...), + 'hover' => $this->translateHover(...), + 'visited' => $this->translateVisited(...), + ]; + } + + public function getFunctionTranslators(): array + { + return [ + 'lang' => $this->translateLang(...), + ]; + } + + public function translateChecked(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition( + '(@checked ' + ."and (name(.) = 'input' or name(.) = 'command')" + ."and (@type = 'checkbox' or @type = 'radio'))" + ); + } + + public function translateLink(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition("@href and (name(.) = 'a' or name(.) = 'link' or name(.) = 'area')"); + } + + public function translateDisabled(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition( + '(' + .'@disabled and' + .'(' + ."(name(.) = 'input' and @type != 'hidden')" + ." or name(.) = 'button'" + ." or name(.) = 'select'" + ." or name(.) = 'textarea'" + ." or name(.) = 'command'" + ." or name(.) = 'fieldset'" + ." or name(.) = 'optgroup'" + ." or name(.) = 'option'" + .')' + .') or (' + ."(name(.) = 'input' and @type != 'hidden')" + ." or name(.) = 'button'" + ." or name(.) = 'select'" + ." or name(.) = 'textarea'" + .')' + .' and ancestor::fieldset[@disabled]' + ); + // todo: in the second half, add "and is not a descendant of that fieldset element's first legend element child, if any." + } + + public function translateEnabled(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition( + '(' + .'@href and (' + ."name(.) = 'a'" + ." or name(.) = 'link'" + ." or name(.) = 'area'" + .')' + .') or (' + .'(' + ."name(.) = 'command'" + ." or name(.) = 'fieldset'" + ." or name(.) = 'optgroup'" + .')' + .' and not(@disabled)' + .') or (' + .'(' + ."(name(.) = 'input' and @type != 'hidden')" + ." or name(.) = 'button'" + ." or name(.) = 'select'" + ." or name(.) = 'textarea'" + ." or name(.) = 'keygen'" + .')' + .' and not (@disabled or ancestor::fieldset[@disabled])' + .') or (' + ."name(.) = 'option' and not(" + .'@disabled or ancestor::optgroup[@disabled]' + .')' + .')' + ); + } + + /** + * @throws ExpressionErrorException + */ + public function translateLang(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + $arguments = $function->getArguments(); + foreach ($arguments as $token) { + if (!($token->isString() || $token->isIdentifier())) { + throw new ExpressionErrorException('Expected a single string or identifier for :lang(), got '.implode(', ', $arguments)); + } + } + + return $xpath->addCondition(sprintf( + 'ancestor-or-self::*[@lang][1][starts-with(concat(' + ."translate(@%s, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '-')" + .', %s)]', + 'lang', + Translator::getXpathLiteral(strtolower($arguments[0]->getValue()).'-') + )); + } + + public function translateSelected(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition("(@selected and name(.) = 'option')"); + } + + public function translateInvalid(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition('0'); + } + + public function translateHover(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition('0'); + } + + public function translateVisited(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition('0'); + } + + public function getName(): string + { + return 'html'; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/NodeExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/NodeExtension.php new file mode 100644 index 0000000..49e894a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/NodeExtension.php @@ -0,0 +1,191 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +use Symfony\Component\CssSelector\Node; +use Symfony\Component\CssSelector\XPath\Translator; +use Symfony\Component\CssSelector\XPath\XPathExpr; + +/** + * XPath expression translator node extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class NodeExtension extends AbstractExtension +{ + public const ELEMENT_NAME_IN_LOWER_CASE = 1; + public const ATTRIBUTE_NAME_IN_LOWER_CASE = 2; + public const ATTRIBUTE_VALUE_IN_LOWER_CASE = 4; + + private int $flags; + + public function __construct(int $flags = 0) + { + $this->flags = $flags; + } + + /** + * @return $this + */ + public function setFlag(int $flag, bool $on): static + { + if ($on && !$this->hasFlag($flag)) { + $this->flags += $flag; + } + + if (!$on && $this->hasFlag($flag)) { + $this->flags -= $flag; + } + + return $this; + } + + public function hasFlag(int $flag): bool + { + return (bool) ($this->flags & $flag); + } + + public function getNodeTranslators(): array + { + return [ + 'Selector' => $this->translateSelector(...), + 'CombinedSelector' => $this->translateCombinedSelector(...), + 'Negation' => $this->translateNegation(...), + 'Function' => $this->translateFunction(...), + 'Pseudo' => $this->translatePseudo(...), + 'Attribute' => $this->translateAttribute(...), + 'Class' => $this->translateClass(...), + 'Hash' => $this->translateHash(...), + 'Element' => $this->translateElement(...), + ]; + } + + public function translateSelector(Node\SelectorNode $node, Translator $translator): XPathExpr + { + return $translator->nodeToXPath($node->getTree()); + } + + public function translateCombinedSelector(Node\CombinedSelectorNode $node, Translator $translator): XPathExpr + { + return $translator->addCombination($node->getCombinator(), $node->getSelector(), $node->getSubSelector()); + } + + public function translateNegation(Node\NegationNode $node, Translator $translator): XPathExpr + { + $xpath = $translator->nodeToXPath($node->getSelector()); + $subXpath = $translator->nodeToXPath($node->getSubSelector()); + $subXpath->addNameTest(); + + if ($subXpath->getCondition()) { + return $xpath->addCondition(sprintf('not(%s)', $subXpath->getCondition())); + } + + return $xpath->addCondition('0'); + } + + public function translateFunction(Node\FunctionNode $node, Translator $translator): XPathExpr + { + $xpath = $translator->nodeToXPath($node->getSelector()); + + return $translator->addFunction($xpath, $node); + } + + public function translatePseudo(Node\PseudoNode $node, Translator $translator): XPathExpr + { + $xpath = $translator->nodeToXPath($node->getSelector()); + + return $translator->addPseudoClass($xpath, $node->getIdentifier()); + } + + public function translateAttribute(Node\AttributeNode $node, Translator $translator): XPathExpr + { + $name = $node->getAttribute(); + $safe = $this->isSafeName($name); + + if ($this->hasFlag(self::ATTRIBUTE_NAME_IN_LOWER_CASE)) { + $name = strtolower($name); + } + + if ($node->getNamespace()) { + $name = sprintf('%s:%s', $node->getNamespace(), $name); + $safe = $safe && $this->isSafeName($node->getNamespace()); + } + + $attribute = $safe ? '@'.$name : sprintf('attribute::*[name() = %s]', Translator::getXpathLiteral($name)); + $value = $node->getValue(); + $xpath = $translator->nodeToXPath($node->getSelector()); + + if ($this->hasFlag(self::ATTRIBUTE_VALUE_IN_LOWER_CASE)) { + $value = strtolower($value); + } + + return $translator->addAttributeMatching($xpath, $node->getOperator(), $attribute, $value); + } + + public function translateClass(Node\ClassNode $node, Translator $translator): XPathExpr + { + $xpath = $translator->nodeToXPath($node->getSelector()); + + return $translator->addAttributeMatching($xpath, '~=', '@class', $node->getName()); + } + + public function translateHash(Node\HashNode $node, Translator $translator): XPathExpr + { + $xpath = $translator->nodeToXPath($node->getSelector()); + + return $translator->addAttributeMatching($xpath, '=', '@id', $node->getId()); + } + + public function translateElement(Node\ElementNode $node): XPathExpr + { + $element = $node->getElement(); + + if ($element && $this->hasFlag(self::ELEMENT_NAME_IN_LOWER_CASE)) { + $element = strtolower($element); + } + + if ($element) { + $safe = $this->isSafeName($element); + } else { + $element = '*'; + $safe = true; + } + + if ($node->getNamespace()) { + $element = sprintf('%s:%s', $node->getNamespace(), $element); + $safe = $safe && $this->isSafeName($node->getNamespace()); + } + + $xpath = new XPathExpr('', $element); + + if (!$safe) { + $xpath->addNameTest(); + } + + return $xpath; + } + + public function getName(): string + { + return 'node'; + } + + private function isSafeName(string $name): bool + { + return 0 < preg_match('~^[a-zA-Z_][a-zA-Z0-9_.-]*$~', $name); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/PseudoClassExtension.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/PseudoClassExtension.php new file mode 100644 index 0000000..aada832 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Extension/PseudoClassExtension.php @@ -0,0 +1,122 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath\Extension; + +use Symfony\Component\CssSelector\Exception\ExpressionErrorException; +use Symfony\Component\CssSelector\XPath\XPathExpr; + +/** + * XPath expression translator pseudo-class extension. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class PseudoClassExtension extends AbstractExtension +{ + public function getPseudoClassTranslators(): array + { + return [ + 'root' => $this->translateRoot(...), + 'scope' => $this->translateScopePseudo(...), + 'first-child' => $this->translateFirstChild(...), + 'last-child' => $this->translateLastChild(...), + 'first-of-type' => $this->translateFirstOfType(...), + 'last-of-type' => $this->translateLastOfType(...), + 'only-child' => $this->translateOnlyChild(...), + 'only-of-type' => $this->translateOnlyOfType(...), + 'empty' => $this->translateEmpty(...), + ]; + } + + public function translateRoot(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition('not(parent::*)'); + } + + public function translateScopePseudo(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition('1'); + } + + public function translateFirstChild(XPathExpr $xpath): XPathExpr + { + return $xpath + ->addStarPrefix() + ->addNameTest() + ->addCondition('position() = 1'); + } + + public function translateLastChild(XPathExpr $xpath): XPathExpr + { + return $xpath + ->addStarPrefix() + ->addNameTest() + ->addCondition('position() = last()'); + } + + /** + * @throws ExpressionErrorException + */ + public function translateFirstOfType(XPathExpr $xpath): XPathExpr + { + if ('*' === $xpath->getElement()) { + throw new ExpressionErrorException('"*:first-of-type" is not implemented.'); + } + + return $xpath + ->addStarPrefix() + ->addCondition('position() = 1'); + } + + /** + * @throws ExpressionErrorException + */ + public function translateLastOfType(XPathExpr $xpath): XPathExpr + { + if ('*' === $xpath->getElement()) { + throw new ExpressionErrorException('"*:last-of-type" is not implemented.'); + } + + return $xpath + ->addStarPrefix() + ->addCondition('position() = last()'); + } + + public function translateOnlyChild(XPathExpr $xpath): XPathExpr + { + return $xpath + ->addStarPrefix() + ->addNameTest() + ->addCondition('last() = 1'); + } + + public function translateOnlyOfType(XPathExpr $xpath): XPathExpr + { + $element = $xpath->getElement(); + + return $xpath->addCondition(sprintf('count(preceding-sibling::%s)=0 and count(following-sibling::%s)=0', $element, $element)); + } + + public function translateEmpty(XPathExpr $xpath): XPathExpr + { + return $xpath->addCondition('not(*) and not(string-length())'); + } + + public function getName(): string + { + return 'pseudo-class'; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/Translator.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/Translator.php new file mode 100644 index 0000000..9e66ce7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/Translator.php @@ -0,0 +1,224 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath; + +use Symfony\Component\CssSelector\Exception\ExpressionErrorException; +use Symfony\Component\CssSelector\Node\FunctionNode; +use Symfony\Component\CssSelector\Node\NodeInterface; +use Symfony\Component\CssSelector\Node\SelectorNode; +use Symfony\Component\CssSelector\Parser\Parser; +use Symfony\Component\CssSelector\Parser\ParserInterface; + +/** + * XPath expression translator interface. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class Translator implements TranslatorInterface +{ + private ParserInterface $mainParser; + + /** + * @var ParserInterface[] + */ + private array $shortcutParsers = []; + + /** + * @var Extension\ExtensionInterface[] + */ + private array $extensions = []; + + private array $nodeTranslators = []; + private array $combinationTranslators = []; + private array $functionTranslators = []; + private array $pseudoClassTranslators = []; + private array $attributeMatchingTranslators = []; + + public function __construct(?ParserInterface $parser = null) + { + $this->mainParser = $parser ?? new Parser(); + + $this + ->registerExtension(new Extension\NodeExtension()) + ->registerExtension(new Extension\CombinationExtension()) + ->registerExtension(new Extension\FunctionExtension()) + ->registerExtension(new Extension\PseudoClassExtension()) + ->registerExtension(new Extension\AttributeMatchingExtension()) + ; + } + + public static function getXpathLiteral(string $element): string + { + if (!str_contains($element, "'")) { + return "'".$element."'"; + } + + if (!str_contains($element, '"')) { + return '"'.$element.'"'; + } + + $string = $element; + $parts = []; + while (true) { + if (false !== $pos = strpos($string, "'")) { + $parts[] = sprintf("'%s'", substr($string, 0, $pos)); + $parts[] = "\"'\""; + $string = substr($string, $pos + 1); + } else { + $parts[] = "'$string'"; + break; + } + } + + return sprintf('concat(%s)', implode(', ', $parts)); + } + + public function cssToXPath(string $cssExpr, string $prefix = 'descendant-or-self::'): string + { + $selectors = $this->parseSelectors($cssExpr); + + /** @var SelectorNode $selector */ + foreach ($selectors as $index => $selector) { + if (null !== $selector->getPseudoElement()) { + throw new ExpressionErrorException('Pseudo-elements are not supported.'); + } + + $selectors[$index] = $this->selectorToXPath($selector, $prefix); + } + + return implode(' | ', $selectors); + } + + public function selectorToXPath(SelectorNode $selector, string $prefix = 'descendant-or-self::'): string + { + return ($prefix ?: '').$this->nodeToXPath($selector); + } + + /** + * @return $this + */ + public function registerExtension(Extension\ExtensionInterface $extension): static + { + $this->extensions[$extension->getName()] = $extension; + + $this->nodeTranslators = array_merge($this->nodeTranslators, $extension->getNodeTranslators()); + $this->combinationTranslators = array_merge($this->combinationTranslators, $extension->getCombinationTranslators()); + $this->functionTranslators = array_merge($this->functionTranslators, $extension->getFunctionTranslators()); + $this->pseudoClassTranslators = array_merge($this->pseudoClassTranslators, $extension->getPseudoClassTranslators()); + $this->attributeMatchingTranslators = array_merge($this->attributeMatchingTranslators, $extension->getAttributeMatchingTranslators()); + + return $this; + } + + /** + * @throws ExpressionErrorException + */ + public function getExtension(string $name): Extension\ExtensionInterface + { + if (!isset($this->extensions[$name])) { + throw new ExpressionErrorException(sprintf('Extension "%s" not registered.', $name)); + } + + return $this->extensions[$name]; + } + + /** + * @return $this + */ + public function registerParserShortcut(ParserInterface $shortcut): static + { + $this->shortcutParsers[] = $shortcut; + + return $this; + } + + /** + * @throws ExpressionErrorException + */ + public function nodeToXPath(NodeInterface $node): XPathExpr + { + if (!isset($this->nodeTranslators[$node->getNodeName()])) { + throw new ExpressionErrorException(sprintf('Node "%s" not supported.', $node->getNodeName())); + } + + return $this->nodeTranslators[$node->getNodeName()]($node, $this); + } + + /** + * @throws ExpressionErrorException + */ + public function addCombination(string $combiner, NodeInterface $xpath, NodeInterface $combinedXpath): XPathExpr + { + if (!isset($this->combinationTranslators[$combiner])) { + throw new ExpressionErrorException(sprintf('Combiner "%s" not supported.', $combiner)); + } + + return $this->combinationTranslators[$combiner]($this->nodeToXPath($xpath), $this->nodeToXPath($combinedXpath)); + } + + /** + * @throws ExpressionErrorException + */ + public function addFunction(XPathExpr $xpath, FunctionNode $function): XPathExpr + { + if (!isset($this->functionTranslators[$function->getName()])) { + throw new ExpressionErrorException(sprintf('Function "%s" not supported.', $function->getName())); + } + + return $this->functionTranslators[$function->getName()]($xpath, $function); + } + + /** + * @throws ExpressionErrorException + */ + public function addPseudoClass(XPathExpr $xpath, string $pseudoClass): XPathExpr + { + if (!isset($this->pseudoClassTranslators[$pseudoClass])) { + throw new ExpressionErrorException(sprintf('Pseudo-class "%s" not supported.', $pseudoClass)); + } + + return $this->pseudoClassTranslators[$pseudoClass]($xpath); + } + + /** + * @throws ExpressionErrorException + */ + public function addAttributeMatching(XPathExpr $xpath, string $operator, string $attribute, ?string $value): XPathExpr + { + if (!isset($this->attributeMatchingTranslators[$operator])) { + throw new ExpressionErrorException(sprintf('Attribute matcher operator "%s" not supported.', $operator)); + } + + return $this->attributeMatchingTranslators[$operator]($xpath, $attribute, $value); + } + + /** + * @return SelectorNode[] + */ + private function parseSelectors(string $css): array + { + foreach ($this->shortcutParsers as $shortcut) { + $tokens = $shortcut->parse($css); + + if ($tokens) { + return $tokens; + } + } + + return $this->mainParser->parse($css); + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/TranslatorInterface.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/TranslatorInterface.php new file mode 100644 index 0000000..c19eefb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/TranslatorInterface.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath; + +use Symfony\Component\CssSelector\Node\SelectorNode; + +/** + * XPath expression translator interface. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +interface TranslatorInterface +{ + /** + * Translates a CSS selector to an XPath expression. + */ + public function cssToXPath(string $cssExpr, string $prefix = 'descendant-or-self::'): string; + + /** + * Translates a parsed selector node to an XPath expression. + */ + public function selectorToXPath(SelectorNode $selector, string $prefix = 'descendant-or-self::'): string; +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/XPath/XPathExpr.php b/php/libraries/composer/vendor/symfony/css-selector/XPath/XPathExpr.php new file mode 100644 index 0000000..a76e30b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/XPath/XPathExpr.php @@ -0,0 +1,111 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\CssSelector\XPath; + +/** + * XPath expression translator interface. + * + * This component is a port of the Python cssselect library, + * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect. + * + * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com> + * + * @internal + */ +class XPathExpr +{ + private string $path; + private string $element; + private string $condition; + + public function __construct(string $path = '', string $element = '*', string $condition = '', bool $starPrefix = false) + { + $this->path = $path; + $this->element = $element; + $this->condition = $condition; + + if ($starPrefix) { + $this->addStarPrefix(); + } + } + + public function getElement(): string + { + return $this->element; + } + + /** + * @return $this + */ + public function addCondition(string $condition): static + { + $this->condition = $this->condition ? sprintf('(%s) and (%s)', $this->condition, $condition) : $condition; + + return $this; + } + + public function getCondition(): string + { + return $this->condition; + } + + /** + * @return $this + */ + public function addNameTest(): static + { + if ('*' !== $this->element) { + $this->addCondition('name() = '.Translator::getXpathLiteral($this->element)); + $this->element = '*'; + } + + return $this; + } + + /** + * @return $this + */ + public function addStarPrefix(): static + { + $this->path .= '*/'; + + return $this; + } + + /** + * Joins another XPathExpr with a combiner. + * + * @return $this + */ + public function join(string $combiner, self $expr): static + { + $path = $this->__toString().$combiner; + + if ('*/' !== $expr->path) { + $path .= $expr->path; + } + + $this->path = $path; + $this->element = $expr->element; + $this->condition = $expr->condition; + + return $this; + } + + public function __toString(): string + { + $path = $this->path.$this->element; + $condition = null === $this->condition || '' === $this->condition ? '' : '['.$this->condition.']'; + + return $path.$condition; + } +} diff --git a/php/libraries/composer/vendor/symfony/css-selector/composer.json b/php/libraries/composer/vendor/symfony/css-selector/composer.json new file mode 100644 index 0000000..a753a1a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/css-selector/composer.json @@ -0,0 +1,32 @@ +{ + "name": "symfony/css-selector", + "type": "library", + "description": "Converts CSS selectors to XPath expressions", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\CssSelector\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/deprecation-contracts/CHANGELOG.md b/php/libraries/composer/vendor/symfony/deprecation-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/deprecation-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/php/libraries/composer/vendor/symfony/deprecation-contracts/LICENSE b/php/libraries/composer/vendor/symfony/deprecation-contracts/LICENSE new file mode 100644 index 0000000..0ed3a24 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/deprecation-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/deprecation-contracts/README.md b/php/libraries/composer/vendor/symfony/deprecation-contracts/README.md new file mode 100644 index 0000000..9814864 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/deprecation-contracts/README.md @@ -0,0 +1,26 @@ +Symfony Deprecation Contracts +============================= + +A generic function and convention to trigger deprecation notices. + +This package provides a single global function named `trigger_deprecation()` that triggers silenced deprecation notices. + +By using a custom PHP error handler such as the one provided by the Symfony ErrorHandler component, +the triggered deprecations can be caught and logged for later discovery, both on dev and prod environments. + +The function requires at least 3 arguments: + - the name of the Composer package that is triggering the deprecation + - the version of the package that introduced the deprecation + - the message of the deprecation + - more arguments can be provided: they will be inserted in the message using `printf()` formatting + +Example: +```php +trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use "%s" instead.', 'bitcoin', 'fabcoin'); +``` + +This will generate the following message: +`Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.` + +While not recommended, the deprecation notices can be completely ignored by declaring an empty +`function trigger_deprecation() {}` in your application. diff --git a/php/libraries/composer/vendor/symfony/deprecation-contracts/composer.json b/php/libraries/composer/vendor/symfony/deprecation-contracts/composer.json new file mode 100644 index 0000000..c6d02d8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/deprecation-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/deprecation-contracts", + "type": "library", + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1" + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/deprecation-contracts/function.php b/php/libraries/composer/vendor/symfony/deprecation-contracts/function.php new file mode 100644 index 0000000..2d56512 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/deprecation-contracts/function.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (!function_exists('trigger_deprecation')) { + /** + * Triggers a silenced deprecation notice. + * + * @param string $package The name of the Composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The message of the deprecation + * @param mixed ...$args Values to insert in the message using printf() formatting + * + * @author Nicolas Grekas <p@tchwork.com> + */ + function trigger_deprecation(string $package, string $version, string $message, mixed ...$args): void + { + @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/BufferingLogger.php b/php/libraries/composer/vendor/symfony/error-handler/BufferingLogger.php new file mode 100644 index 0000000..cfd55c6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/BufferingLogger.php @@ -0,0 +1,71 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler; + +use Psr\Log\AbstractLogger; + +/** + * A buffering logger that stacks logs for later. + * + * @author Nicolas Grekas <p@tchwork.com> + */ +class BufferingLogger extends AbstractLogger +{ + private $logs = []; + + public function log($level, $message, array $context = []): void + { + $this->logs[] = [$level, $message, $context]; + } + + public function cleanLogs(): array + { + $logs = $this->logs; + $this->logs = []; + + return $logs; + } + + /** + * @return array + */ + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + foreach ($this->logs as [$level, $message, $context]) { + if (false !== strpos($message, '{')) { + foreach ($context as $key => $val) { + if (null === $val || \is_scalar($val) || (\is_object($val) && \is_callable([$val, '__toString']))) { + $message = str_replace("{{$key}}", $val, $message); + } elseif ($val instanceof \DateTimeInterface) { + $message = str_replace("{{$key}}", $val->format(\DateTime::RFC3339), $message); + } elseif (\is_object($val)) { + $message = str_replace("{{$key}}", '[object '.\get_class($val).']', $message); + } else { + $message = str_replace("{{$key}}", '['.\gettype($val).']', $message); + } + } + } + + error_log(sprintf('%s [%s] %s', date(\DateTime::RFC3339), $level, $message)); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/CHANGELOG.md b/php/libraries/composer/vendor/symfony/error-handler/CHANGELOG.md new file mode 100644 index 0000000..2976566 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/CHANGELOG.md @@ -0,0 +1,24 @@ +CHANGELOG +========= + +5.4 +--- + + * Make `DebugClassLoader` trigger deprecation notices on missing return types + * Add `SYMFONY_PATCH_TYPE_DECLARATIONS='force=2'` mode to `DebugClassLoader` to turn annotations into native return types + +5.2.0 +----- + + * added the ability to set `HtmlErrorRenderer::$template` to a custom template to render when not in debug mode. + +5.1.0 +----- + + * The `HtmlErrorRenderer` and `SerializerErrorRenderer` add `X-Debug-Exception` and `X-Debug-Exception-File` headers in debug mode. + +4.4.0 +----- + + * added the component + * added `ErrorHandler::call()` method utility to turn any PHP error into `\ErrorException` diff --git a/php/libraries/composer/vendor/symfony/error-handler/Debug.php b/php/libraries/composer/vendor/symfony/error-handler/Debug.php new file mode 100644 index 0000000..60ddb45 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Debug.php @@ -0,0 +1,40 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler; + +/** + * Registers all the debug tools. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class Debug +{ + public static function enable(): ErrorHandler + { + error_reporting(-1); + + if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { + ini_set('display_errors', 0); + } elseif (!filter_var(\ini_get('log_errors'), \FILTER_VALIDATE_BOOLEAN) || \ini_get('error_log')) { + // CLI - display errors only if they're not already logged to STDERR + ini_set('display_errors', 1); + } + + @ini_set('zend.assertions', 1); + ini_set('assert.active', 1); + ini_set('assert.exception', 1); + + DebugClassLoader::enable(); + + return ErrorHandler::register(new ErrorHandler(new BufferingLogger(), true)); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/DebugClassLoader.php b/php/libraries/composer/vendor/symfony/error-handler/DebugClassLoader.php new file mode 100644 index 0000000..5db2f30 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/DebugClassLoader.php @@ -0,0 +1,1237 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler; + +use Composer\InstalledVersions; +use Doctrine\Common\Persistence\Proxy as LegacyProxy; +use Doctrine\Persistence\Proxy; +use Mockery\MockInterface; +use Phake\IMock; +use PHPUnit\Framework\MockObject\Matcher\StatelessInvocation; +use PHPUnit\Framework\MockObject\MockObject; +use Prophecy\Prophecy\ProphecySubjectInterface; +use ProxyManager\Proxy\ProxyInterface; +use Symfony\Component\ErrorHandler\Internal\TentativeTypes; +use Symfony\Component\HttpClient\HttplugClient; + +/** + * Autoloader checking if the class is really defined in the file found. + * + * The ClassLoader will wrap all registered autoloaders + * and will throw an exception if a file is found but does + * not declare the class. + * + * It can also patch classes to turn docblocks into actual return types. + * This behavior is controlled by the SYMFONY_PATCH_TYPE_DECLARATIONS env var, + * which is a url-encoded array with the follow parameters: + * - "force": any value enables deprecation notices - can be any of: + * - "phpdoc" to patch only docblock annotations + * - "2" to add all possible return types + * - "1" to add return types but only to tests/final/internal/private methods + * - "php": the target version of PHP - e.g. "7.1" doesn't generate "object" types + * - "deprecations": "1" to trigger a deprecation notice when a child class misses a + * return type while the parent declares an "@return" annotation + * + * Note that patching doesn't care about any coding style so you'd better to run + * php-cs-fixer after, with rules "phpdoc_trim_consecutive_blank_line_separation" + * and "no_superfluous_phpdoc_tags" enabled typically. + * + * @author Fabien Potencier <fabien@symfony.com> + * @author Christophe Coevoet <stof@notk.org> + * @author Nicolas Grekas <p@tchwork.com> + * @author Guilhem Niot <guilhem.niot@gmail.com> + */ +class DebugClassLoader +{ + private const SPECIAL_RETURN_TYPES = [ + 'void' => 'void', + 'null' => 'null', + 'resource' => 'resource', + 'boolean' => 'bool', + 'true' => 'true', + 'false' => 'false', + 'integer' => 'int', + 'array' => 'array', + 'bool' => 'bool', + 'callable' => 'callable', + 'float' => 'float', + 'int' => 'int', + 'iterable' => 'iterable', + 'object' => 'object', + 'string' => 'string', + 'self' => 'self', + 'parent' => 'parent', + 'mixed' => 'mixed', + 'static' => 'static', + '$this' => 'static', + 'list' => 'array', + 'class-string' => 'string', + 'never' => 'never', + ]; + + private const BUILTIN_RETURN_TYPES = [ + 'void' => true, + 'array' => true, + 'false' => true, + 'bool' => true, + 'callable' => true, + 'float' => true, + 'int' => true, + 'iterable' => true, + 'object' => true, + 'string' => true, + 'self' => true, + 'parent' => true, + 'mixed' => true, + 'static' => true, + 'null' => true, + 'true' => true, + 'never' => true, + ]; + + private const MAGIC_METHODS = [ + '__isset' => 'bool', + '__sleep' => 'array', + '__toString' => 'string', + '__debugInfo' => 'array', + '__serialize' => 'array', + ]; + + private $classLoader; + private $isFinder; + private $loaded = []; + private $patchTypes; + + private static $caseCheck; + private static $checkedClasses = []; + private static $final = []; + private static $finalMethods = []; + private static $deprecated = []; + private static $internal = []; + private static $internalMethods = []; + private static $annotatedParameters = []; + private static $darwinCache = ['/' => ['/', []]]; + private static $method = []; + private static $returnTypes = []; + private static $methodTraits = []; + private static $fileOffsets = []; + + public function __construct(callable $classLoader) + { + $this->classLoader = $classLoader; + $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile'); + parse_str(getenv('SYMFONY_PATCH_TYPE_DECLARATIONS') ?: '', $this->patchTypes); + $this->patchTypes += [ + 'force' => null, + 'php' => \PHP_MAJOR_VERSION.'.'.\PHP_MINOR_VERSION, + 'deprecations' => \PHP_VERSION_ID >= 70400, + ]; + + if ('phpdoc' === $this->patchTypes['force']) { + $this->patchTypes['force'] = 'docblock'; + } + + if (!isset(self::$caseCheck)) { + $file = is_file(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR); + $i = strrpos($file, \DIRECTORY_SEPARATOR); + $dir = substr($file, 0, 1 + $i); + $file = substr($file, 1 + $i); + $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file); + $test = realpath($dir.$test); + + if (false === $test || false === $i) { + // filesystem is case sensitive + self::$caseCheck = 0; + } elseif (substr($test, -\strlen($file)) === $file) { + // filesystem is case insensitive and realpath() normalizes the case of characters + self::$caseCheck = 1; + } elseif ('Darwin' === \PHP_OS_FAMILY) { + // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters + self::$caseCheck = 2; + } else { + // filesystem case checks failed, fallback to disabling them + self::$caseCheck = 0; + } + } + } + + public function getClassLoader(): callable + { + return $this->classLoader; + } + + /** + * Wraps all autoloaders. + */ + public static function enable(): void + { + // Ensures we don't hit https://bugs.php.net/42098 + class_exists(\Symfony\Component\ErrorHandler\ErrorHandler::class); + class_exists(\Psr\Log\LogLevel::class); + + if (!\is_array($functions = spl_autoload_functions())) { + return; + } + + foreach ($functions as $function) { + spl_autoload_unregister($function); + } + + foreach ($functions as $function) { + if (!\is_array($function) || !$function[0] instanceof self) { + $function = [new static($function), 'loadClass']; + } + + spl_autoload_register($function); + } + } + + /** + * Disables the wrapping. + */ + public static function disable(): void + { + if (!\is_array($functions = spl_autoload_functions())) { + return; + } + + foreach ($functions as $function) { + spl_autoload_unregister($function); + } + + foreach ($functions as $function) { + if (\is_array($function) && $function[0] instanceof self) { + $function = $function[0]->getClassLoader(); + } + + spl_autoload_register($function); + } + } + + public static function checkClasses(): bool + { + if (!\is_array($functions = spl_autoload_functions())) { + return false; + } + + $loader = null; + + foreach ($functions as $function) { + if (\is_array($function) && $function[0] instanceof self) { + $loader = $function[0]; + break; + } + } + + if (null === $loader) { + return false; + } + + static $offsets = [ + 'get_declared_interfaces' => 0, + 'get_declared_traits' => 0, + 'get_declared_classes' => 0, + ]; + + foreach ($offsets as $getSymbols => $i) { + $symbols = $getSymbols(); + + for (; $i < \count($symbols); ++$i) { + if (!is_subclass_of($symbols[$i], MockObject::class) + && !is_subclass_of($symbols[$i], ProphecySubjectInterface::class) + && !is_subclass_of($symbols[$i], Proxy::class) + && !is_subclass_of($symbols[$i], ProxyInterface::class) + && !is_subclass_of($symbols[$i], LegacyProxy::class) + && !is_subclass_of($symbols[$i], MockInterface::class) + && !is_subclass_of($symbols[$i], IMock::class) + ) { + $loader->checkClass($symbols[$i]); + } + } + + $offsets[$getSymbols] = $i; + } + + return true; + } + + public function findFile(string $class): ?string + { + return $this->isFinder ? ($this->classLoader[0]->findFile($class) ?: null) : null; + } + + /** + * Loads the given class or interface. + * + * @throws \RuntimeException + */ + public function loadClass(string $class): void + { + $e = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR); + + try { + if ($this->isFinder && !isset($this->loaded[$class])) { + $this->loaded[$class] = true; + if (!$file = $this->classLoader[0]->findFile($class) ?: '') { + // no-op + } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) { + include $file; + + return; + } elseif (false === include $file) { + return; + } + } else { + ($this->classLoader)($class); + $file = ''; + } + } finally { + error_reporting($e); + } + + $this->checkClass($class, $file); + } + + private function checkClass(string $class, ?string $file = null): void + { + $exists = null === $file || class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false); + + if (null !== $file && $class && '\\' === $class[0]) { + $class = substr($class, 1); + } + + if ($exists) { + if (isset(self::$checkedClasses[$class])) { + return; + } + self::$checkedClasses[$class] = true; + + $refl = new \ReflectionClass($class); + if (null === $file && $refl->isInternal()) { + return; + } + $name = $refl->getName(); + + if ($name !== $class && 0 === strcasecmp($name, $class)) { + throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name)); + } + + $deprecations = $this->checkAnnotations($refl, $name); + + foreach ($deprecations as $message) { + @trigger_error($message, \E_USER_DEPRECATED); + } + } + + if (!$file) { + return; + } + + if (!$exists) { + if (false !== strpos($class, '/')) { + throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class)); + } + + throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file)); + } + + if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) { + throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2])); + } + } + + public function checkAnnotations(\ReflectionClass $refl, string $class): array + { + if ( + 'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV7' === $class + || 'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV6' === $class + ) { + return []; + } + $deprecations = []; + + $className = false !== strpos($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class; + + // Don't trigger deprecations for classes in the same vendor + if ($class !== $className) { + $vendor = preg_match('/^namespace ([^;\\\\\s]++)[;\\\\]/m', @file_get_contents($refl->getFileName()), $vendor) ? $vendor[1].'\\' : ''; + $vendorLen = \strlen($vendor); + } elseif (2 > $vendorLen = 1 + (strpos($class, '\\') ?: strpos($class, '_'))) { + $vendorLen = 0; + $vendor = ''; + } else { + $vendor = str_replace('_', '\\', substr($class, 0, $vendorLen)); + } + + $parent = get_parent_class($class) ?: null; + self::$returnTypes[$class] = []; + $classIsTemplate = false; + + // Detect annotations on the class + if ($doc = $this->parsePhpDoc($refl)) { + $classIsTemplate = isset($doc['template']); + + foreach (['final', 'deprecated', 'internal'] as $annotation) { + if (null !== $description = $doc[$annotation][0] ?? null) { + self::${$annotation}[$class] = '' !== $description ? ' '.$description.(preg_match('/[.!]$/', $description) ? '' : '.') : '.'; + } + } + + if ($refl->isInterface() && isset($doc['method'])) { + foreach ($doc['method'] as $name => [$static, $returnType, $signature, $description]) { + self::$method[$class][] = [$class, $static, $returnType, $name.$signature, $description]; + + if ('' !== $returnType) { + $this->setReturnType($returnType, $refl->name, $name, $refl->getFileName(), $parent); + } + } + } + } + + $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent); + if ($parent) { + $parentAndOwnInterfaces[$parent] = $parent; + + if (!isset(self::$checkedClasses[$parent])) { + $this->checkClass($parent); + } + + if (isset(self::$final[$parent])) { + $deprecations[] = sprintf('The "%s" class is considered final%s It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $className); + } + } + + // Detect if the parent is annotated + foreach ($parentAndOwnInterfaces + class_uses($class, false) as $use) { + if (!isset(self::$checkedClasses[$use])) { + $this->checkClass($use); + } + if (isset(self::$deprecated[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen) && !isset(self::$deprecated[$class]) + && !(HttplugClient::class === $class && \in_array($use, [\Http\Client\HttpClient::class, \Http\Message\RequestFactory::class, \Http\Message\StreamFactory::class, \Http\Message\UriFactory::class], true)) + ) { + $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait'); + $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses'); + + $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s', $className, $type, $verb, $use, self::$deprecated[$use]); + } + if (isset(self::$internal[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)) { + $deprecations[] = sprintf('The "%s" %s is considered internal%s It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $className); + } + if (isset(self::$method[$use])) { + if ($refl->isAbstract()) { + if (isset(self::$method[$class])) { + self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]); + } else { + self::$method[$class] = self::$method[$use]; + } + } elseif (!$refl->isInterface()) { + if (!strncmp($vendor, str_replace('_', '\\', $use), $vendorLen) + && 0 === strpos($className, 'Symfony\\') + && (!class_exists(InstalledVersions::class) + || 'symfony/symfony' !== InstalledVersions::getRootPackage()['name']) + ) { + // skip "same vendor" @method deprecations for Symfony\* classes unless symfony/symfony is being tested + continue; + } + $hasCall = $refl->hasMethod('__call'); + $hasStaticCall = $refl->hasMethod('__callStatic'); + foreach (self::$method[$use] as [$interface, $static, $returnType, $name, $description]) { + if ($static ? $hasStaticCall : $hasCall) { + continue; + } + $realName = substr($name, 0, strpos($name, '(')); + if (!$refl->hasMethod($realName) || !($methodRefl = $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) { + $deprecations[] = sprintf('Class "%s" should implement method "%s::%s%s"%s', $className, ($static ? 'static ' : '').$interface, $name, $returnType ? ': '.$returnType : '', null === $description ? '.' : ': '.$description); + } + } + } + } + } + + if (trait_exists($class)) { + $file = $refl->getFileName(); + + foreach ($refl->getMethods() as $method) { + if ($method->getFileName() === $file) { + self::$methodTraits[$file][$method->getStartLine()] = $class; + } + } + + return $deprecations; + } + + // Inherit @final, @internal, @param and @return annotations for methods + self::$finalMethods[$class] = []; + self::$internalMethods[$class] = []; + self::$annotatedParameters[$class] = []; + foreach ($parentAndOwnInterfaces as $use) { + foreach (['finalMethods', 'internalMethods', 'annotatedParameters', 'returnTypes'] as $property) { + if (isset(self::${$property}[$use])) { + self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use]; + } + } + + if (null !== (TentativeTypes::RETURN_TYPES[$use] ?? null)) { + foreach (TentativeTypes::RETURN_TYPES[$use] as $method => $returnType) { + $returnType = explode('|', $returnType); + foreach ($returnType as $i => $t) { + if ('?' !== $t && !isset(self::BUILTIN_RETURN_TYPES[$t])) { + $returnType[$i] = '\\'.$t; + } + } + $returnType = implode('|', $returnType); + + self::$returnTypes[$class] += [$method => [$returnType, 0 === strpos($returnType, '?') ? substr($returnType, 1).'|null' : $returnType, $use, '']]; + } + } + } + + foreach ($refl->getMethods() as $method) { + if ($method->class !== $class) { + continue; + } + + if (null === $ns = self::$methodTraits[$method->getFileName()][$method->getStartLine()] ?? null) { + $ns = $vendor; + $len = $vendorLen; + } elseif (2 > $len = 1 + (strpos($ns, '\\') ?: strpos($ns, '_'))) { + $len = 0; + $ns = ''; + } else { + $ns = str_replace('_', '\\', substr($ns, 0, $len)); + } + + if ($parent && isset(self::$finalMethods[$parent][$method->name])) { + [$declaringClass, $message] = self::$finalMethods[$parent][$method->name]; + $deprecations[] = sprintf('The "%s::%s()" method is considered final%s It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className); + } + + if (isset(self::$internalMethods[$class][$method->name])) { + [$declaringClass, $message] = self::$internalMethods[$class][$method->name]; + if (strncmp($ns, $declaringClass, $len)) { + $deprecations[] = sprintf('The "%s::%s()" method is considered internal%s It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className); + } + } + + // To read method annotations + $doc = $this->parsePhpDoc($method); + + if (($classIsTemplate || isset($doc['template'])) && $method->hasReturnType()) { + unset($doc['return']); + } + + if (isset(self::$annotatedParameters[$class][$method->name])) { + $definedParameters = []; + foreach ($method->getParameters() as $parameter) { + $definedParameters[$parameter->name] = true; + } + + foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) { + if (!isset($definedParameters[$parameterName]) && !isset($doc['param'][$parameterName])) { + $deprecations[] = sprintf($deprecation, $className); + } + } + } + + $forcePatchTypes = $this->patchTypes['force']; + + if ($canAddReturnType = null !== $forcePatchTypes && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) { + if ('void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) { + $this->patchTypes['force'] = $forcePatchTypes ?: 'docblock'; + } + + $canAddReturnType = 2 === (int) $forcePatchTypes + || false !== stripos($method->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR) + || $refl->isFinal() + || $method->isFinal() + || $method->isPrivate() + || ('.' === (self::$internal[$class] ?? null) && !$refl->isAbstract()) + || '.' === (self::$final[$class] ?? null) + || '' === ($doc['final'][0] ?? null) + || '' === ($doc['internal'][0] ?? null) + ; + } + + if (null !== ($returnType = self::$returnTypes[$class][$method->name] ?? null) && 'docblock' === $this->patchTypes['force'] && !$method->hasReturnType() && isset(TentativeTypes::RETURN_TYPES[$returnType[2]][$method->name])) { + $this->patchReturnTypeWillChange($method); + } + + if (null !== ($returnType ?? $returnType = self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !isset($doc['return'])) { + [$normalizedType, $returnType, $declaringClass, $declaringFile] = \is_string($returnType) ? [$returnType, $returnType, '', ''] : $returnType; + + if ($canAddReturnType && 'docblock' !== $this->patchTypes['force']) { + $this->patchMethod($method, $returnType, $declaringFile, $normalizedType); + } + if (!isset($doc['deprecated']) && strncmp($ns, $declaringClass, $len)) { + if ('docblock' === $this->patchTypes['force']) { + $this->patchMethod($method, $returnType, $declaringFile, $normalizedType); + } elseif ('' !== $declaringClass && $this->patchTypes['deprecations']) { + $deprecations[] = sprintf('Method "%s::%s()" might add "%s" as a native return type declaration in the future. Do the same in %s "%s" now to avoid errors or add an explicit @return annotation to suppress this message.', $declaringClass, $method->name, $normalizedType, interface_exists($declaringClass) ? 'implementation' : 'child class', $className); + } + } + } + + if (!$doc) { + $this->patchTypes['force'] = $forcePatchTypes; + + continue; + } + + if (isset($doc['return']) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) { + $this->setReturnType($doc['return'] ?? self::MAGIC_METHODS[$method->name], $method->class, $method->name, $method->getFileName(), $parent, $method->getReturnType()); + + if (isset(self::$returnTypes[$class][$method->name][0]) && $canAddReturnType) { + $this->fixReturnStatements($method, self::$returnTypes[$class][$method->name][0]); + } + + if ($method->isPrivate()) { + unset(self::$returnTypes[$class][$method->name]); + } + } + + $this->patchTypes['force'] = $forcePatchTypes; + + if ($method->isPrivate()) { + continue; + } + + $finalOrInternal = false; + + foreach (['final', 'internal'] as $annotation) { + if (null !== $description = $doc[$annotation][0] ?? null) { + self::${$annotation.'Methods'}[$class][$method->name] = [$class, '' !== $description ? ' '.$description.(preg_match('/[[:punct:]]$/', $description) ? '' : '.') : '.']; + $finalOrInternal = true; + } + } + + if ($finalOrInternal || $method->isConstructor() || !isset($doc['param']) || StatelessInvocation::class === $class) { + continue; + } + if (!isset(self::$annotatedParameters[$class][$method->name])) { + $definedParameters = []; + foreach ($method->getParameters() as $parameter) { + $definedParameters[$parameter->name] = true; + } + } + foreach ($doc['param'] as $parameterName => $parameterType) { + if (!isset($definedParameters[$parameterName])) { + self::$annotatedParameters[$class][$method->name][$parameterName] = sprintf('The "%%s::%s()" method will require a new "%s$%s" argument in the next major version of its %s "%s", not defining it is deprecated.', $method->name, $parameterType ? $parameterType.' ' : '', $parameterName, interface_exists($className) ? 'interface' : 'parent class', $className); + } + } + } + + return $deprecations; + } + + public function checkCase(\ReflectionClass $refl, string $file, string $class): ?array + { + $real = explode('\\', $class.strrchr($file, '.')); + $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file)); + + $i = \count($tail) - 1; + $j = \count($real) - 1; + + while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) { + --$i; + --$j; + } + + array_splice($tail, 0, $i + 1); + + if (!$tail) { + return null; + } + + $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail); + $tailLen = \strlen($tail); + $real = $refl->getFileName(); + + if (2 === self::$caseCheck) { + $real = $this->darwinRealpath($real); + } + + if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true) + && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false) + ) { + return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)]; + } + + return null; + } + + /** + * `realpath` on MacOSX doesn't normalize the case of characters. + */ + private function darwinRealpath(string $real): string + { + $i = 1 + strrpos($real, '/'); + $file = substr($real, $i); + $real = substr($real, 0, $i); + + if (isset(self::$darwinCache[$real])) { + $kDir = $real; + } else { + $kDir = strtolower($real); + + if (isset(self::$darwinCache[$kDir])) { + $real = self::$darwinCache[$kDir][0]; + } else { + $dir = getcwd(); + + if (!@chdir($real)) { + return $real.$file; + } + + $real = getcwd().'/'; + chdir($dir); + + $dir = $real; + $k = $kDir; + $i = \strlen($dir) - 1; + while (!isset(self::$darwinCache[$k])) { + self::$darwinCache[$k] = [$dir, []]; + self::$darwinCache[$dir] = &self::$darwinCache[$k]; + + while ('/' !== $dir[--$i]) { + } + $k = substr($k, 0, ++$i); + $dir = substr($dir, 0, $i--); + } + } + } + + $dirFiles = self::$darwinCache[$kDir][1]; + + if (!isset($dirFiles[$file]) && ') : eval()\'d code' === substr($file, -17)) { + // Get the file name from "file_name.php(123) : eval()'d code" + $file = substr($file, 0, strrpos($file, '(', -17)); + } + + if (isset($dirFiles[$file])) { + return $real.$dirFiles[$file]; + } + + $kFile = strtolower($file); + + if (!isset($dirFiles[$kFile])) { + foreach (scandir($real, 2) as $f) { + if ('.' !== $f[0]) { + $dirFiles[$f] = $f; + if ($f === $file) { + $kFile = $k = $file; + } elseif ($f !== $k = strtolower($f)) { + $dirFiles[$k] = $f; + } + } + } + self::$darwinCache[$kDir][1] = $dirFiles; + } + + return $real.$dirFiles[$kFile]; + } + + /** + * `class_implements` includes interfaces from the parents so we have to manually exclude them. + * + * @return string[] + */ + private function getOwnInterfaces(string $class, ?string $parent): array + { + $ownInterfaces = class_implements($class, false); + + if ($parent) { + foreach (class_implements($parent, false) as $interface) { + unset($ownInterfaces[$interface]); + } + } + + foreach ($ownInterfaces as $interface) { + foreach (class_implements($interface) as $interface) { + unset($ownInterfaces[$interface]); + } + } + + return $ownInterfaces; + } + + private function setReturnType(string $types, string $class, string $method, string $filename, ?string $parent, ?\ReflectionType $returnType = null): void + { + if ('__construct' === $method) { + return; + } + + if ('null' === $types) { + self::$returnTypes[$class][$method] = ['null', 'null', $class, $filename]; + + return; + } + + if ($nullable = 0 === strpos($types, 'null|')) { + $types = substr($types, 5); + } elseif ($nullable = '|null' === substr($types, -5)) { + $types = substr($types, 0, -5); + } + $arrayType = ['array' => 'array']; + $typesMap = []; + $glue = false !== strpos($types, '&') ? '&' : '|'; + foreach (explode($glue, $types) as $t) { + $t = self::SPECIAL_RETURN_TYPES[strtolower($t)] ?? $t; + $typesMap[$this->normalizeType($t, $class, $parent, $returnType)][$t] = $t; + } + + if (isset($typesMap['array'])) { + if (isset($typesMap['Traversable']) || isset($typesMap['\Traversable'])) { + $typesMap['iterable'] = $arrayType !== $typesMap['array'] ? $typesMap['array'] : ['iterable']; + unset($typesMap['array'], $typesMap['Traversable'], $typesMap['\Traversable']); + } elseif ($arrayType !== $typesMap['array'] && isset(self::$returnTypes[$class][$method]) && !$returnType) { + return; + } + } + + if (isset($typesMap['array']) && isset($typesMap['iterable'])) { + if ($arrayType !== $typesMap['array']) { + $typesMap['iterable'] = $typesMap['array']; + } + unset($typesMap['array']); + } + + $iterable = $object = true; + foreach ($typesMap as $n => $t) { + if ('null' !== $n) { + $iterable = $iterable && (\in_array($n, ['array', 'iterable']) || false !== strpos($n, 'Iterator')); + $object = $object && (\in_array($n, ['callable', 'object', '$this', 'static']) || !isset(self::SPECIAL_RETURN_TYPES[$n])); + } + } + + $phpTypes = []; + $docTypes = []; + + foreach ($typesMap as $n => $t) { + if ('null' === $n) { + $nullable = true; + continue; + } + + $docTypes[] = $t; + + if ('mixed' === $n || 'void' === $n) { + $nullable = false; + $phpTypes = ['' => $n]; + continue; + } + + if ('resource' === $n) { + // there is no native type for "resource" + return; + } + + if (!isset($phpTypes[''])) { + $phpTypes[] = $n; + } + } + $docTypes = array_merge([], ...$docTypes); + + if (!$phpTypes) { + return; + } + + if (1 < \count($phpTypes)) { + if ($iterable && '8.0' > $this->patchTypes['php']) { + $phpTypes = $docTypes = ['iterable']; + } elseif ($object && 'object' === $this->patchTypes['force']) { + $phpTypes = $docTypes = ['object']; + } elseif ('8.0' > $this->patchTypes['php']) { + // ignore multi-types return declarations + return; + } + } + + $phpType = sprintf($nullable ? (1 < \count($phpTypes) ? '%s|null' : '?%s') : '%s', implode($glue, $phpTypes)); + $docType = sprintf($nullable ? '%s|null' : '%s', implode($glue, $docTypes)); + + self::$returnTypes[$class][$method] = [$phpType, $docType, $class, $filename]; + } + + private function normalizeType(string $type, string $class, ?string $parent, ?\ReflectionType $returnType): string + { + if (isset(self::SPECIAL_RETURN_TYPES[$lcType = strtolower($type)])) { + if ('parent' === $lcType = self::SPECIAL_RETURN_TYPES[$lcType]) { + $lcType = null !== $parent ? '\\'.$parent : 'parent'; + } elseif ('self' === $lcType) { + $lcType = '\\'.$class; + } + + return $lcType; + } + + // We could resolve "use" statements to return the FQDN + // but this would be too expensive for a runtime checker + + if ('[]' !== substr($type, -2)) { + return $type; + } + + if ($returnType instanceof \ReflectionNamedType) { + $type = $returnType->getName(); + + if ('mixed' !== $type) { + return isset(self::SPECIAL_RETURN_TYPES[$type]) ? $type : '\\'.$type; + } + } + + return 'array'; + } + + /** + * Utility method to add #[ReturnTypeWillChange] where php triggers deprecations. + */ + private function patchReturnTypeWillChange(\ReflectionMethod $method) + { + if (\PHP_VERSION_ID >= 80000 && \count($method->getAttributes(\ReturnTypeWillChange::class))) { + return; + } + + if (!is_file($file = $method->getFileName())) { + return; + } + + $fileOffset = self::$fileOffsets[$file] ?? 0; + + $code = file($file); + + $startLine = $method->getStartLine() + $fileOffset - 2; + + if (false !== stripos($code[$startLine], 'ReturnTypeWillChange')) { + return; + } + + $code[$startLine] .= " #[\\ReturnTypeWillChange]\n"; + self::$fileOffsets[$file] = 1 + $fileOffset; + file_put_contents($file, $code); + } + + /** + * Utility method to add @return annotations to the Symfony code-base where it triggers self-deprecations. + */ + private function patchMethod(\ReflectionMethod $method, string $returnType, string $declaringFile, string $normalizedType) + { + static $patchedMethods = []; + static $useStatements = []; + + if (!is_file($file = $method->getFileName()) || isset($patchedMethods[$file][$startLine = $method->getStartLine()])) { + return; + } + + $patchedMethods[$file][$startLine] = true; + $fileOffset = self::$fileOffsets[$file] ?? 0; + $startLine += $fileOffset - 2; + if ($nullable = '|null' === substr($returnType, -5)) { + $returnType = substr($returnType, 0, -5); + } + $glue = false !== strpos($returnType, '&') ? '&' : '|'; + $returnType = explode($glue, $returnType); + $code = file($file); + + foreach ($returnType as $i => $type) { + if (preg_match('/((?:\[\])+)$/', $type, $m)) { + $type = substr($type, 0, -\strlen($m[1])); + $format = '%s'.$m[1]; + } else { + $format = null; + } + + if (isset(self::SPECIAL_RETURN_TYPES[$type]) || ('\\' === $type[0] && !$p = strrpos($type, '\\', 1))) { + continue; + } + + [$namespace, $useOffset, $useMap] = $useStatements[$file] ?? $useStatements[$file] = self::getUseStatements($file); + + if ('\\' !== $type[0]) { + [$declaringNamespace, , $declaringUseMap] = $useStatements[$declaringFile] ?? $useStatements[$declaringFile] = self::getUseStatements($declaringFile); + + $p = strpos($type, '\\', 1); + $alias = $p ? substr($type, 0, $p) : $type; + + if (isset($declaringUseMap[$alias])) { + $type = '\\'.$declaringUseMap[$alias].($p ? substr($type, $p) : ''); + } else { + $type = '\\'.$declaringNamespace.$type; + } + + $p = strrpos($type, '\\', 1); + } + + $alias = substr($type, 1 + $p); + $type = substr($type, 1); + + if (!isset($useMap[$alias]) && (class_exists($c = $namespace.$alias) || interface_exists($c) || trait_exists($c))) { + $useMap[$alias] = $c; + } + + if (!isset($useMap[$alias])) { + $useStatements[$file][2][$alias] = $type; + $code[$useOffset] = "use $type;\n".$code[$useOffset]; + ++$fileOffset; + } elseif ($useMap[$alias] !== $type) { + $alias .= 'FIXME'; + $useStatements[$file][2][$alias] = $type; + $code[$useOffset] = "use $type as $alias;\n".$code[$useOffset]; + ++$fileOffset; + } + + $returnType[$i] = null !== $format ? sprintf($format, $alias) : $alias; + } + + if ('docblock' === $this->patchTypes['force'] || ('object' === $normalizedType && '7.1' === $this->patchTypes['php'])) { + $returnType = implode($glue, $returnType).($nullable ? '|null' : ''); + + if (false !== strpos($code[$startLine], '#[')) { + --$startLine; + } + + if ($method->getDocComment()) { + $code[$startLine] = " * @return $returnType\n".$code[$startLine]; + } else { + $code[$startLine] .= <<<EOTXT + /** + * @return $returnType + */ + +EOTXT; + } + + $fileOffset += substr_count($code[$startLine], "\n") - 1; + } + + self::$fileOffsets[$file] = $fileOffset; + file_put_contents($file, $code); + + $this->fixReturnStatements($method, $normalizedType); + } + + private static function getUseStatements(string $file): array + { + $namespace = ''; + $useMap = []; + $useOffset = 0; + + if (!is_file($file)) { + return [$namespace, $useOffset, $useMap]; + } + + $file = file($file); + + for ($i = 0; $i < \count($file); ++$i) { + if (preg_match('/^(class|interface|trait|abstract) /', $file[$i])) { + break; + } + + if (0 === strpos($file[$i], 'namespace ')) { + $namespace = substr($file[$i], \strlen('namespace '), -2).'\\'; + $useOffset = $i + 2; + } + + if (0 === strpos($file[$i], 'use ')) { + $useOffset = $i; + + for (; 0 === strpos($file[$i], 'use '); ++$i) { + $u = explode(' as ', substr($file[$i], 4, -2), 2); + + if (1 === \count($u)) { + $p = strrpos($u[0], '\\'); + $useMap[substr($u[0], false !== $p ? 1 + $p : 0)] = $u[0]; + } else { + $useMap[$u[1]] = $u[0]; + } + } + + break; + } + } + + return [$namespace, $useOffset, $useMap]; + } + + private function fixReturnStatements(\ReflectionMethod $method, string $returnType) + { + if ('docblock' !== $this->patchTypes['force']) { + if ('7.1' === $this->patchTypes['php'] && 'object' === ltrim($returnType, '?')) { + return; + } + + if ('7.4' > $this->patchTypes['php'] && $method->hasReturnType()) { + return; + } + + if ('8.0' > $this->patchTypes['php'] && (false !== strpos($returnType, '|') || \in_array($returnType, ['mixed', 'static'], true))) { + return; + } + + if ('8.1' > $this->patchTypes['php'] && false !== strpos($returnType, '&')) { + return; + } + } + + if (!is_file($file = $method->getFileName())) { + return; + } + + $fixedCode = $code = file($file); + $i = (self::$fileOffsets[$file] ?? 0) + $method->getStartLine(); + + if ('?' !== $returnType && 'docblock' !== $this->patchTypes['force']) { + $fixedCode[$i - 1] = preg_replace('/\)(?::[^;\n]++)?(;?\n)/', "): $returnType\\1", $code[$i - 1]); + } + + $end = $method->isGenerator() ? $i : $method->getEndLine(); + $inClosure = false; + $braces = 0; + for (; $i < $end; ++$i) { + if (!$inClosure) { + $inClosure = false !== strpos($code[$i], 'function ('); + } + + if ($inClosure) { + $braces += substr_count($code[$i], '{') - substr_count($code[$i], '}'); + $inClosure = $braces > 0; + + continue; + } + + if ('void' === $returnType) { + $fixedCode[$i] = str_replace(' return null;', ' return;', $code[$i]); + } elseif ('mixed' === $returnType || '?' === $returnType[0]) { + $fixedCode[$i] = str_replace(' return;', ' return null;', $code[$i]); + } else { + $fixedCode[$i] = str_replace(' return;', " return $returnType!?;", $code[$i]); + } + } + + if ($fixedCode !== $code) { + file_put_contents($file, $fixedCode); + } + } + + /** + * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflector + */ + private function parsePhpDoc(\Reflector $reflector): array + { + if (!$doc = $reflector->getDocComment()) { + return []; + } + + $tagName = ''; + $tagContent = ''; + + $tags = []; + + foreach (explode("\n", substr($doc, 3, -2)) as $line) { + $line = ltrim($line); + $line = ltrim($line, '*'); + + if ('' === $line = trim($line)) { + if ('' !== $tagName) { + $tags[$tagName][] = $tagContent; + } + $tagName = $tagContent = ''; + continue; + } + + if ('@' === $line[0]) { + if ('' !== $tagName) { + $tags[$tagName][] = $tagContent; + $tagContent = ''; + } + + if (preg_match('{^@([-a-zA-Z0-9_:]++)(\s|$)}', $line, $m)) { + $tagName = $m[1]; + $tagContent = str_replace("\t", ' ', ltrim(substr($line, 2 + \strlen($tagName)))); + } else { + $tagName = ''; + } + } elseif ('' !== $tagName) { + $tagContent .= ' '.str_replace("\t", ' ', $line); + } + } + + if ('' !== $tagName) { + $tags[$tagName][] = $tagContent; + } + + foreach ($tags['method'] ?? [] as $i => $method) { + unset($tags['method'][$i]); + + $parts = preg_split('{(\s++|\((?:[^()]*+|(?R))*\)(?: *: *[^ ]++)?|<(?:[^<>]*+|(?R))*>|\{(?:[^{}]*+|(?R))*\})}', $method, -1, \PREG_SPLIT_DELIM_CAPTURE); + $returnType = ''; + $static = 'static' === $parts[0]; + + for ($i = $static ? 2 : 0; null !== $p = $parts[$i] ?? null; $i += 2) { + if (\in_array($p, ['', '|', '&', 'callable'], true) || \in_array(substr($returnType, -1), ['|', '&'], true)) { + $returnType .= trim($parts[$i - 1] ?? '').$p; + continue; + } + + $signature = '(' === ($parts[$i + 1][0] ?? '(') ? $parts[$i + 1] ?? '()' : null; + + if (null === $signature && '' === $returnType) { + $returnType = $p; + continue; + } + + if ($static && 2 === $i) { + $static = false; + $returnType = 'static'; + } + + if (\in_array($description = trim(implode('', \array_slice($parts, 2 + $i))), ['', '.'], true)) { + $description = null; + } elseif (!preg_match('/[.!]$/', $description)) { + $description .= '.'; + } + + $tags['method'][$p] = [$static, $returnType, $signature ?? '()', $description]; + break; + } + } + + foreach ($tags['param'] ?? [] as $i => $param) { + unset($tags['param'][$i]); + + if (\strlen($param) !== strcspn($param, '<{(')) { + $param = preg_replace('{\(([^()]*+|(?R))*\)(?: *: *[^ ]++)?|<([^<>]*+|(?R))*>|\{([^{}]*+|(?R))*\}}', '', $param); + } + + if (false === $i = strpos($param, '$')) { + continue; + } + + $type = 0 === $i ? '' : rtrim(substr($param, 0, $i), ' &'); + $param = substr($param, 1 + $i, (strpos($param, ' ', $i) ?: (1 + $i + \strlen($param))) - $i - 1); + + $tags['param'][$param] = $type; + } + + foreach (['var', 'return'] as $k) { + if (null === $v = $tags[$k][0] ?? null) { + continue; + } + if (\strlen($v) !== strcspn($v, '<{(')) { + $v = preg_replace('{\(([^()]*+|(?R))*\)(?: *: *[^ ]++)?|<([^<>]*+|(?R))*>|\{([^{}]*+|(?R))*\}}', '', $v); + } + + $tags[$k] = substr($v, 0, strpos($v, ' ') ?: \strlen($v)) ?: null; + } + + return $tags; + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Error/ClassNotFoundError.php b/php/libraries/composer/vendor/symfony/error-handler/Error/ClassNotFoundError.php new file mode 100644 index 0000000..443fba2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Error/ClassNotFoundError.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Error; + +class ClassNotFoundError extends \Error +{ + /** + * {@inheritdoc} + */ + public function __construct(string $message, \Throwable $previous) + { + parent::__construct($message, $previous->getCode(), $previous->getPrevious()); + + foreach ([ + 'file' => $previous->getFile(), + 'line' => $previous->getLine(), + 'trace' => $previous->getTrace(), + ] as $property => $value) { + $refl = new \ReflectionProperty(\Error::class, $property); + $refl->setAccessible(true); + $refl->setValue($this, $value); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Error/FatalError.php b/php/libraries/composer/vendor/symfony/error-handler/Error/FatalError.php new file mode 100644 index 0000000..73fa3aa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Error/FatalError.php @@ -0,0 +1,89 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Error; + +class FatalError extends \Error +{ + private $error; + + /** + * {@inheritdoc} + * + * @param array $error An array as returned by error_get_last() + */ + public function __construct(string $message, int $code, array $error, ?int $traceOffset = null, bool $traceArgs = true, ?array $trace = null) + { + parent::__construct($message, $code); + + $this->error = $error; + + if (null !== $trace) { + if (!$traceArgs) { + foreach ($trace as &$frame) { + unset($frame['args'], $frame['this'], $frame); + } + } + } elseif (null !== $traceOffset) { + if (\function_exists('xdebug_get_function_stack') && $trace = @xdebug_get_function_stack()) { + if (0 < $traceOffset) { + array_splice($trace, -$traceOffset); + } + + foreach ($trace as &$frame) { + if (!isset($frame['type'])) { + // XDebug pre 2.1.1 doesn't currently set the call type key http://bugs.xdebug.org/view.php?id=695 + if (isset($frame['class'])) { + $frame['type'] = '::'; + } + } elseif ('dynamic' === $frame['type']) { + $frame['type'] = '->'; + } elseif ('static' === $frame['type']) { + $frame['type'] = '::'; + } + + // XDebug also has a different name for the parameters array + if (!$traceArgs) { + unset($frame['params'], $frame['args']); + } elseif (isset($frame['params']) && !isset($frame['args'])) { + $frame['args'] = $frame['params']; + unset($frame['params']); + } + } + + unset($frame); + $trace = array_reverse($trace); + } else { + $trace = []; + } + } + + foreach ([ + 'file' => $error['file'], + 'line' => $error['line'], + 'trace' => $trace, + ] as $property => $value) { + if (null !== $value) { + $refl = new \ReflectionProperty(\Error::class, $property); + $refl->setAccessible(true); + $refl->setValue($this, $value); + } + } + } + + /** + * {@inheritdoc} + */ + public function getError(): array + { + return $this->error; + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Error/OutOfMemoryError.php b/php/libraries/composer/vendor/symfony/error-handler/Error/OutOfMemoryError.php new file mode 100644 index 0000000..d685c3d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Error/OutOfMemoryError.php @@ -0,0 +1,16 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Error; + +class OutOfMemoryError extends FatalError +{ +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Error/UndefinedFunctionError.php b/php/libraries/composer/vendor/symfony/error-handler/Error/UndefinedFunctionError.php new file mode 100644 index 0000000..b57dd15 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Error/UndefinedFunctionError.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Error; + +class UndefinedFunctionError extends \Error +{ + /** + * {@inheritdoc} + */ + public function __construct(string $message, \Throwable $previous) + { + parent::__construct($message, $previous->getCode(), $previous->getPrevious()); + + foreach ([ + 'file' => $previous->getFile(), + 'line' => $previous->getLine(), + 'trace' => $previous->getTrace(), + ] as $property => $value) { + $refl = new \ReflectionProperty(\Error::class, $property); + $refl->setAccessible(true); + $refl->setValue($this, $value); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Error/UndefinedMethodError.php b/php/libraries/composer/vendor/symfony/error-handler/Error/UndefinedMethodError.php new file mode 100644 index 0000000..adc8731 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Error/UndefinedMethodError.php @@ -0,0 +1,33 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Error; + +class UndefinedMethodError extends \Error +{ + /** + * {@inheritdoc} + */ + public function __construct(string $message, \Throwable $previous) + { + parent::__construct($message, $previous->getCode(), $previous->getPrevious()); + + foreach ([ + 'file' => $previous->getFile(), + 'line' => $previous->getLine(), + 'trace' => $previous->getTrace(), + ] as $property => $value) { + $refl = new \ReflectionProperty(\Error::class, $property); + $refl->setAccessible(true); + $refl->setValue($this, $value); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php new file mode 100644 index 0000000..4e1ae8e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php @@ -0,0 +1,175 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorEnhancer; + +use Composer\Autoload\ClassLoader; +use Symfony\Component\ErrorHandler\DebugClassLoader; +use Symfony\Component\ErrorHandler\Error\ClassNotFoundError; +use Symfony\Component\ErrorHandler\Error\FatalError; + +/** + * @author Fabien Potencier <fabien@symfony.com> + */ +class ClassNotFoundErrorEnhancer implements ErrorEnhancerInterface +{ + public function enhance(\Throwable $error): ?\Throwable + { + // Some specific versions of PHP produce a fatal error when extending a not found class. + $message = !$error instanceof FatalError ? $error->getMessage() : $error->getError()['message']; + if (!preg_match('/^(Class|Interface|Trait) [\'"]([^\'"]+)[\'"] not found$/', $message, $matches)) { + return null; + } + $typeName = strtolower($matches[1]); + $fullyQualifiedClassName = $matches[2]; + + if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) { + $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1); + $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex); + $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix); + $tail = ' for another namespace?'; + } else { + $className = $fullyQualifiedClassName; + $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className); + $tail = '?'; + } + + if ($candidates = $this->getClassCandidates($className)) { + $tail = array_pop($candidates).'"?'; + if ($candidates) { + $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail; + } else { + $tail = ' for "'.$tail; + } + } + $message .= "\nDid you forget a \"use\" statement".$tail; + + return new ClassNotFoundError($message, $error); + } + + /** + * Tries to guess the full namespace for a given class name. + * + * By default, it looks for PSR-0 and PSR-4 classes registered via a Symfony or a Composer + * autoloader (that should cover all common cases). + * + * @param string $class A class name (without its namespace) + * + * Returns an array of possible fully qualified class names + */ + private function getClassCandidates(string $class): array + { + if (!\is_array($functions = spl_autoload_functions())) { + return []; + } + + // find Symfony and Composer autoloaders + $classes = []; + + foreach ($functions as $function) { + if (!\is_array($function)) { + continue; + } + // get class loaders wrapped by DebugClassLoader + if ($function[0] instanceof DebugClassLoader) { + $function = $function[0]->getClassLoader(); + + if (!\is_array($function)) { + continue; + } + } + + if ($function[0] instanceof ClassLoader) { + foreach ($function[0]->getPrefixes() as $prefix => $paths) { + foreach ($paths as $path) { + $classes[] = $this->findClassInPath($path, $class, $prefix); + } + } + + foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) { + foreach ($paths as $path) { + $classes[] = $this->findClassInPath($path, $class, $prefix); + } + } + } + } + + return array_unique(array_merge([], ...$classes)); + } + + private function findClassInPath(string $path, string $class, string $prefix): array + { + $path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path); + if (!$path || !is_dir($path)) { + return []; + } + + $classes = []; + $filename = $class.'.php'; + foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) { + $classes[] = $class; + } + } + + return $classes; + } + + private function convertFileToClass(string $path, string $file, string $prefix): ?string + { + $candidates = [ + // namespaced class + $namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file), + // namespaced class (with target dir) + $prefix.$namespacedClass, + // namespaced class (with target dir and separator) + $prefix.'\\'.$namespacedClass, + // PEAR class + str_replace('\\', '_', $namespacedClass), + // PEAR class (with target dir) + str_replace('\\', '_', $prefix.$namespacedClass), + // PEAR class (with target dir and separator) + str_replace('\\', '_', $prefix.'\\'.$namespacedClass), + ]; + + if ($prefix) { + $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); }); + } + + // We cannot use the autoloader here as most of them use require; but if the class + // is not found, the new autoloader call will require the file again leading to a + // "cannot redeclare class" error. + foreach ($candidates as $candidate) { + if ($this->classExists($candidate)) { + return $candidate; + } + } + + try { + require_once $file; + } catch (\Throwable $e) { + return null; + } + + foreach ($candidates as $candidate) { + if ($this->classExists($candidate)) { + return $candidate; + } + } + + return null; + } + + private function classExists(string $class): bool + { + return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/ErrorEnhancerInterface.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/ErrorEnhancerInterface.php new file mode 100644 index 0000000..7c3f4ef --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/ErrorEnhancerInterface.php @@ -0,0 +1,20 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorEnhancer; + +interface ErrorEnhancerInterface +{ + /** + * Returns an \Throwable instance if the class is able to improve the error, null otherwise. + */ + public function enhance(\Throwable $error): ?\Throwable; +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php new file mode 100644 index 0000000..f4c49c2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorEnhancer; + +use Symfony\Component\ErrorHandler\Error\FatalError; +use Symfony\Component\ErrorHandler\Error\UndefinedFunctionError; + +/** + * @author Fabien Potencier <fabien@symfony.com> + */ +class UndefinedFunctionErrorEnhancer implements ErrorEnhancerInterface +{ + /** + * {@inheritdoc} + */ + public function enhance(\Throwable $error): ?\Throwable + { + if ($error instanceof FatalError) { + return null; + } + + $message = $error->getMessage(); + $messageLen = \strlen($message); + $notFoundSuffix = '()'; + $notFoundSuffixLen = \strlen($notFoundSuffix); + if ($notFoundSuffixLen > $messageLen) { + return null; + } + + if (0 !== substr_compare($message, $notFoundSuffix, -$notFoundSuffixLen)) { + return null; + } + + $prefix = 'Call to undefined function '; + $prefixLen = \strlen($prefix); + if (0 !== strpos($message, $prefix)) { + return null; + } + + $fullyQualifiedFunctionName = substr($message, $prefixLen, -$notFoundSuffixLen); + if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedFunctionName, '\\')) { + $functionName = substr($fullyQualifiedFunctionName, $namespaceSeparatorIndex + 1); + $namespacePrefix = substr($fullyQualifiedFunctionName, 0, $namespaceSeparatorIndex); + $message = sprintf('Attempted to call function "%s" from namespace "%s".', $functionName, $namespacePrefix); + } else { + $functionName = $fullyQualifiedFunctionName; + $message = sprintf('Attempted to call function "%s" from the global namespace.', $functionName); + } + + $candidates = []; + foreach (get_defined_functions() as $type => $definedFunctionNames) { + foreach ($definedFunctionNames as $definedFunctionName) { + if (false !== $namespaceSeparatorIndex = strrpos($definedFunctionName, '\\')) { + $definedFunctionNameBasename = substr($definedFunctionName, $namespaceSeparatorIndex + 1); + } else { + $definedFunctionNameBasename = $definedFunctionName; + } + + if ($definedFunctionNameBasename === $functionName) { + $candidates[] = '\\'.$definedFunctionName; + } + } + } + + if ($candidates) { + sort($candidates); + $last = array_pop($candidates).'"?'; + if ($candidates) { + $candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last; + } else { + $candidates = '"'.$last; + } + $message .= "\nDid you mean to call ".$candidates; + } + + return new UndefinedFunctionError($message, $error); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php new file mode 100644 index 0000000..c4355f9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php @@ -0,0 +1,69 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorEnhancer; + +use Symfony\Component\ErrorHandler\Error\FatalError; +use Symfony\Component\ErrorHandler\Error\UndefinedMethodError; + +/** + * @author Grégoire Pineau <lyrixx@lyrixx.info> + */ +class UndefinedMethodErrorEnhancer implements ErrorEnhancerInterface +{ + /** + * {@inheritdoc} + */ + public function enhance(\Throwable $error): ?\Throwable + { + if ($error instanceof FatalError) { + return null; + } + + $message = $error->getMessage(); + preg_match('/^Call to undefined method (.*)::(.*)\(\)$/', $message, $matches); + if (!$matches) { + return null; + } + + $className = $matches[1]; + $methodName = $matches[2]; + + $message = sprintf('Attempted to call an undefined method named "%s" of class "%s".', $methodName, $className); + + if ('' === $methodName || !class_exists($className) || null === $methods = get_class_methods($className)) { + // failed to get the class or its methods on which an unknown method was called (for example on an anonymous class) + return new UndefinedMethodError($message, $error); + } + + $candidates = []; + foreach ($methods as $definedMethodName) { + $lev = levenshtein($methodName, $definedMethodName); + if ($lev <= \strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) { + $candidates[] = $definedMethodName; + } + } + + if ($candidates) { + sort($candidates); + $last = array_pop($candidates).'"?'; + if ($candidates) { + $candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last; + } else { + $candidates = '"'.$last; + } + + $message .= "\nDid you mean to call ".$candidates; + } + + return new UndefinedMethodError($message, $error); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorHandler.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorHandler.php new file mode 100644 index 0000000..28b93c2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorHandler.php @@ -0,0 +1,802 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; +use Symfony\Component\ErrorHandler\Error\FatalError; +use Symfony\Component\ErrorHandler\Error\OutOfMemoryError; +use Symfony\Component\ErrorHandler\ErrorEnhancer\ClassNotFoundErrorEnhancer; +use Symfony\Component\ErrorHandler\ErrorEnhancer\ErrorEnhancerInterface; +use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedFunctionErrorEnhancer; +use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedMethodErrorEnhancer; +use Symfony\Component\ErrorHandler\ErrorRenderer\CliErrorRenderer; +use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer; +use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext; + +/** + * A generic ErrorHandler for the PHP engine. + * + * Provides five bit fields that control how errors are handled: + * - thrownErrors: errors thrown as \ErrorException + * - loggedErrors: logged errors, when not @-silenced + * - scopedErrors: errors thrown or logged with their local context + * - tracedErrors: errors logged with their stack trace + * - screamedErrors: never @-silenced errors + * + * Each error level can be logged by a dedicated PSR-3 logger object. + * Screaming only applies to logging. + * Throwing takes precedence over logging. + * Uncaught exceptions are logged as E_ERROR. + * E_DEPRECATED and E_USER_DEPRECATED levels never throw. + * E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw. + * Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so. + * As errors have a performance cost, repeated errors are all logged, so that the developer + * can see them and weight them as more important to fix than others of the same level. + * + * @author Nicolas Grekas <p@tchwork.com> + * @author Grégoire Pineau <lyrixx@lyrixx.info> + * + * @final + */ +class ErrorHandler +{ + private $levels = [ + \E_DEPRECATED => 'Deprecated', + \E_USER_DEPRECATED => 'User Deprecated', + \E_NOTICE => 'Notice', + \E_USER_NOTICE => 'User Notice', + \E_STRICT => 'Runtime Notice', + \E_WARNING => 'Warning', + \E_USER_WARNING => 'User Warning', + \E_COMPILE_WARNING => 'Compile Warning', + \E_CORE_WARNING => 'Core Warning', + \E_USER_ERROR => 'User Error', + \E_RECOVERABLE_ERROR => 'Catchable Fatal Error', + \E_COMPILE_ERROR => 'Compile Error', + \E_PARSE => 'Parse Error', + \E_ERROR => 'Error', + \E_CORE_ERROR => 'Core Error', + ]; + + private $loggers = [ + \E_DEPRECATED => [null, LogLevel::INFO], + \E_USER_DEPRECATED => [null, LogLevel::INFO], + \E_NOTICE => [null, LogLevel::WARNING], + \E_USER_NOTICE => [null, LogLevel::WARNING], + \E_STRICT => [null, LogLevel::WARNING], + \E_WARNING => [null, LogLevel::WARNING], + \E_USER_WARNING => [null, LogLevel::WARNING], + \E_COMPILE_WARNING => [null, LogLevel::WARNING], + \E_CORE_WARNING => [null, LogLevel::WARNING], + \E_USER_ERROR => [null, LogLevel::CRITICAL], + \E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL], + \E_COMPILE_ERROR => [null, LogLevel::CRITICAL], + \E_PARSE => [null, LogLevel::CRITICAL], + \E_ERROR => [null, LogLevel::CRITICAL], + \E_CORE_ERROR => [null, LogLevel::CRITICAL], + ]; + + private $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED + private $scopedErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED + private $tracedErrors = 0x77FB; // E_ALL - E_STRICT - E_PARSE + private $screamedErrors = 0x55; // E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE + private $loggedErrors = 0; + private $configureException; + private $debug; + + private $isRecursive = 0; + private $isRoot = false; + private $exceptionHandler; + private $bootstrappingLogger; + + private static $reservedMemory; + private static $toStringException; + private static $silencedErrorCache = []; + private static $silencedErrorCount = 0; + private static $exitCode = 0; + + /** + * Registers the error handler. + */ + public static function register(?self $handler = null, bool $replace = true): self + { + if (null === self::$reservedMemory) { + self::$reservedMemory = str_repeat('x', 32768); + register_shutdown_function(__CLASS__.'::handleFatalError'); + } + + if ($handlerIsNew = null === $handler) { + $handler = new static(); + } + + if (null === $prev = set_error_handler([$handler, 'handleError'])) { + restore_error_handler(); + // Specifying the error types earlier would expose us to https://bugs.php.net/63206 + set_error_handler([$handler, 'handleError'], $handler->thrownErrors | $handler->loggedErrors); + $handler->isRoot = true; + } + + if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) { + $handler = $prev[0]; + $replace = false; + } + if (!$replace && $prev) { + restore_error_handler(); + $handlerIsRegistered = \is_array($prev) && $handler === $prev[0]; + } else { + $handlerIsRegistered = true; + } + if (\is_array($prev = set_exception_handler([$handler, 'handleException'])) && $prev[0] instanceof self) { + restore_exception_handler(); + if (!$handlerIsRegistered) { + $handler = $prev[0]; + } elseif ($handler !== $prev[0] && $replace) { + set_exception_handler([$handler, 'handleException']); + $p = $prev[0]->setExceptionHandler(null); + $handler->setExceptionHandler($p); + $prev[0]->setExceptionHandler($p); + } + } else { + $handler->setExceptionHandler($prev ?? [$handler, 'renderException']); + } + + $handler->throwAt(\E_ALL & $handler->thrownErrors, true); + + return $handler; + } + + /** + * Calls a function and turns any PHP error into \ErrorException. + * + * @return mixed What $function(...$arguments) returns + * + * @throws \ErrorException When $function(...$arguments) triggers a PHP error + */ + public static function call(callable $function, ...$arguments) + { + set_error_handler(static function (int $type, string $message, string $file, int $line) { + if (__FILE__ === $file) { + $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3); + $file = $trace[2]['file'] ?? $file; + $line = $trace[2]['line'] ?? $line; + } + + throw new \ErrorException($message, 0, $type, $file, $line); + }); + + try { + return $function(...$arguments); + } finally { + restore_error_handler(); + } + } + + public function __construct(?BufferingLogger $bootstrappingLogger = null, bool $debug = false) + { + if ($bootstrappingLogger) { + $this->bootstrappingLogger = $bootstrappingLogger; + $this->setDefaultLogger($bootstrappingLogger); + } + $traceReflector = new \ReflectionProperty(\Exception::class, 'trace'); + $traceReflector->setAccessible(true); + $this->configureException = \Closure::bind(static function ($e, $trace, $file = null, $line = null) use ($traceReflector) { + $traceReflector->setValue($e, $trace); + $e->file = $file ?? $e->file; + $e->line = $line ?? $e->line; + }, null, new class() extends \Exception { + }); + $this->debug = $debug; + } + + /** + * Sets a logger to non assigned errors levels. + * + * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels + * @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants + * @param bool $replace Whether to replace or not any existing logger + */ + public function setDefaultLogger(LoggerInterface $logger, $levels = \E_ALL, bool $replace = false): void + { + $loggers = []; + + if (\is_array($levels)) { + foreach ($levels as $type => $logLevel) { + if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) { + $loggers[$type] = [$logger, $logLevel]; + } + } + } else { + if (null === $levels) { + $levels = \E_ALL; + } + foreach ($this->loggers as $type => $log) { + if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) { + $log[0] = $logger; + $loggers[$type] = $log; + } + } + } + + $this->setLoggers($loggers); + } + + /** + * Sets a logger for each error level. + * + * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map + * + * @return array The previous map + * + * @throws \InvalidArgumentException + */ + public function setLoggers(array $loggers): array + { + $prevLogged = $this->loggedErrors; + $prev = $this->loggers; + $flush = []; + + foreach ($loggers as $type => $log) { + if (!isset($prev[$type])) { + throw new \InvalidArgumentException('Unknown error type: '.$type); + } + if (!\is_array($log)) { + $log = [$log]; + } elseif (!\array_key_exists(0, $log)) { + throw new \InvalidArgumentException('No logger provided.'); + } + if (null === $log[0]) { + $this->loggedErrors &= ~$type; + } elseif ($log[0] instanceof LoggerInterface) { + $this->loggedErrors |= $type; + } else { + throw new \InvalidArgumentException('Invalid logger provided.'); + } + $this->loggers[$type] = $log + $prev[$type]; + + if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) { + $flush[$type] = $type; + } + } + $this->reRegister($prevLogged | $this->thrownErrors); + + if ($flush) { + foreach ($this->bootstrappingLogger->cleanLogs() as $log) { + $type = ThrowableUtils::getSeverity($log[2]['exception']); + if (!isset($flush[$type])) { + $this->bootstrappingLogger->log($log[0], $log[1], $log[2]); + } elseif ($this->loggers[$type][0]) { + $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]); + } + } + } + + return $prev; + } + + /** + * Sets a user exception handler. + * + * @param callable(\Throwable $e)|null $handler + * + * @return callable|null The previous exception handler + */ + public function setExceptionHandler(?callable $handler): ?callable + { + $prev = $this->exceptionHandler; + $this->exceptionHandler = $handler; + + return $prev; + } + + /** + * Sets the PHP error levels that throw an exception when a PHP error occurs. + * + * @param int $levels A bit field of E_* constants for thrown errors + * @param bool $replace Replace or amend the previous value + * + * @return int The previous value + */ + public function throwAt(int $levels, bool $replace = false): int + { + $prev = $this->thrownErrors; + $this->thrownErrors = ($levels | \E_RECOVERABLE_ERROR | \E_USER_ERROR) & ~\E_USER_DEPRECATED & ~\E_DEPRECATED; + if (!$replace) { + $this->thrownErrors |= $prev; + } + $this->reRegister($prev | $this->loggedErrors); + + return $prev; + } + + /** + * Sets the PHP error levels for which local variables are preserved. + * + * @param int $levels A bit field of E_* constants for scoped errors + * @param bool $replace Replace or amend the previous value + * + * @return int The previous value + */ + public function scopeAt(int $levels, bool $replace = false): int + { + $prev = $this->scopedErrors; + $this->scopedErrors = $levels; + if (!$replace) { + $this->scopedErrors |= $prev; + } + + return $prev; + } + + /** + * Sets the PHP error levels for which the stack trace is preserved. + * + * @param int $levels A bit field of E_* constants for traced errors + * @param bool $replace Replace or amend the previous value + * + * @return int The previous value + */ + public function traceAt(int $levels, bool $replace = false): int + { + $prev = $this->tracedErrors; + $this->tracedErrors = $levels; + if (!$replace) { + $this->tracedErrors |= $prev; + } + + return $prev; + } + + /** + * Sets the error levels where the @-operator is ignored. + * + * @param int $levels A bit field of E_* constants for screamed errors + * @param bool $replace Replace or amend the previous value + * + * @return int The previous value + */ + public function screamAt(int $levels, bool $replace = false): int + { + $prev = $this->screamedErrors; + $this->screamedErrors = $levels; + if (!$replace) { + $this->screamedErrors |= $prev; + } + + return $prev; + } + + /** + * Re-registers as a PHP error handler if levels changed. + */ + private function reRegister(int $prev): void + { + if ($prev !== ($this->thrownErrors | $this->loggedErrors)) { + $handler = set_error_handler('is_int'); + $handler = \is_array($handler) ? $handler[0] : null; + restore_error_handler(); + if ($handler === $this) { + restore_error_handler(); + if ($this->isRoot) { + set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors); + } else { + set_error_handler([$this, 'handleError']); + } + } + } + } + + /** + * Handles errors by filtering then logging them according to the configured bit fields. + * + * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself + * + * @throws \ErrorException When $this->thrownErrors requests so + * + * @internal + */ + public function handleError(int $type, string $message, string $file, int $line): bool + { + if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) { + $type = \E_DEPRECATED; + } + + // Level is the current error reporting level to manage silent error. + $level = error_reporting(); + $silenced = 0 === ($level & $type); + // Strong errors are not authorized to be silenced. + $level |= \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED; + $log = $this->loggedErrors & $type; + $throw = $this->thrownErrors & $type & $level; + $type &= $level | $this->screamedErrors; + + // Never throw on warnings triggered by assert() + if (\E_WARNING === $type && 'a' === $message[0] && 0 === strncmp($message, 'assert(): ', 10)) { + $throw = 0; + } + + if (!$type || (!$log && !$throw)) { + return false; + } + + $logMessage = $this->levels[$type].': '.$message; + + if (null !== self::$toStringException) { + $errorAsException = self::$toStringException; + self::$toStringException = null; + } elseif (!$throw && !($type & $level)) { + if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) { + $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : []; + $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace); + } elseif (isset(self::$silencedErrorCache[$id][$message])) { + $lightTrace = null; + $errorAsException = self::$silencedErrorCache[$id][$message]; + ++$errorAsException->count; + } else { + $lightTrace = []; + $errorAsException = null; + } + + if (100 < ++self::$silencedErrorCount) { + self::$silencedErrorCache = $lightTrace = []; + self::$silencedErrorCount = 1; + } + if ($errorAsException) { + self::$silencedErrorCache[$id][$message] = $errorAsException; + } + if (null === $lightTrace) { + return true; + } + } else { + if (PHP_VERSION_ID < 80303 && false !== strpos($message, '@anonymous')) { + $backtrace = debug_backtrace(false, 5); + + for ($i = 1; isset($backtrace[$i]); ++$i) { + if (isset($backtrace[$i]['function'], $backtrace[$i]['args'][0]) + && ('trigger_error' === $backtrace[$i]['function'] || 'user_error' === $backtrace[$i]['function']) + ) { + if ($backtrace[$i]['args'][0] !== $message) { + $message = $backtrace[$i]['args'][0]; + } + + break; + } + } + } + + if (false !== strpos($message, "@anonymous\0")) { + $message = $this->parseAnonymousClass($message); + $logMessage = $this->levels[$type].': '.$message; + } + + $errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line); + + if ($throw || $this->tracedErrors & $type) { + $backtrace = $errorAsException->getTrace(); + $lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw); + ($this->configureException)($errorAsException, $lightTrace, $file, $line); + } else { + ($this->configureException)($errorAsException, []); + $backtrace = []; + } + } + + if ($throw) { + if (\PHP_VERSION_ID < 70400 && \E_USER_ERROR & $type) { + for ($i = 1; isset($backtrace[$i]); ++$i) { + if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function']) + && '__toString' === $backtrace[$i]['function'] + && '->' === $backtrace[$i]['type'] + && !isset($backtrace[$i - 1]['class']) + && ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function']) + ) { + // Here, we know trigger_error() has been called from __toString(). + // PHP triggers a fatal error when throwing from __toString(). + // A small convention allows working around the limitation: + // given a caught $e exception in __toString(), quitting the method with + // `return trigger_error($e, E_USER_ERROR);` allows this error handler + // to make $e get through the __toString() barrier. + + $context = 4 < \func_num_args() ? (func_get_arg(4) ?: []) : []; + + foreach ($context as $e) { + if ($e instanceof \Throwable && $e->__toString() === $message) { + self::$toStringException = $e; + + return true; + } + } + + // Display the original error message instead of the default one. + $this->handleException($errorAsException); + + // Stop the process by giving back the error to the native handler. + return false; + } + } + } + + throw $errorAsException; + } + + if ($this->isRecursive) { + $log = 0; + } else { + if (\PHP_VERSION_ID < (\PHP_VERSION_ID < 70400 ? 70316 : 70404)) { + $currentErrorHandler = set_error_handler('is_int'); + restore_error_handler(); + } + + try { + $this->isRecursive = true; + $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG; + $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []); + } finally { + $this->isRecursive = false; + + if (\PHP_VERSION_ID < (\PHP_VERSION_ID < 70400 ? 70316 : 70404)) { + set_error_handler($currentErrorHandler); + } + } + } + + return !$silenced && $type && $log; + } + + /** + * Handles an exception by logging then forwarding it to another handler. + * + * @internal + */ + public function handleException(\Throwable $exception) + { + $handlerException = null; + + if (!$exception instanceof FatalError) { + self::$exitCode = 255; + + $type = ThrowableUtils::getSeverity($exception); + } else { + $type = $exception->getError()['type']; + } + + if ($this->loggedErrors & $type) { + if (false !== strpos($message = $exception->getMessage(), "@anonymous\0")) { + $message = $this->parseAnonymousClass($message); + } + + if ($exception instanceof FatalError) { + $message = 'Fatal '.$message; + } elseif ($exception instanceof \Error) { + $message = 'Uncaught Error: '.$message; + } elseif ($exception instanceof \ErrorException) { + $message = 'Uncaught '.$message; + } else { + $message = 'Uncaught Exception: '.$message; + } + + try { + $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]); + } catch (\Throwable $handlerException) { + } + } + + if (!$exception instanceof OutOfMemoryError) { + foreach ($this->getErrorEnhancers() as $errorEnhancer) { + if ($e = $errorEnhancer->enhance($exception)) { + $exception = $e; + break; + } + } + } + + $exceptionHandler = $this->exceptionHandler; + $this->exceptionHandler = [$this, 'renderException']; + + if (null === $exceptionHandler || $exceptionHandler === $this->exceptionHandler) { + $this->exceptionHandler = null; + } + + try { + if (null !== $exceptionHandler) { + return $exceptionHandler($exception); + } + $handlerException = $handlerException ?: $exception; + } catch (\Throwable $handlerException) { + } + if ($exception === $handlerException && null === $this->exceptionHandler) { + self::$reservedMemory = null; // Disable the fatal error handler + throw $exception; // Give back $exception to the native handler + } + + $loggedErrors = $this->loggedErrors; + if ($exception === $handlerException) { + $this->loggedErrors &= ~$type; + } + + try { + $this->handleException($handlerException); + } finally { + $this->loggedErrors = $loggedErrors; + } + } + + /** + * Shutdown registered function for handling PHP fatal errors. + * + * @param array|null $error An array as returned by error_get_last() + * + * @internal + */ + public static function handleFatalError(?array $error = null): void + { + if (null === self::$reservedMemory) { + return; + } + + $handler = self::$reservedMemory = null; + $handlers = []; + $previousHandler = null; + $sameHandlerLimit = 10; + + while (!\is_array($handler) || !$handler[0] instanceof self) { + $handler = set_exception_handler('is_int'); + restore_exception_handler(); + + if (!$handler) { + break; + } + restore_exception_handler(); + + if ($handler !== $previousHandler) { + array_unshift($handlers, $handler); + $previousHandler = $handler; + } elseif (0 === --$sameHandlerLimit) { + $handler = null; + break; + } + } + foreach ($handlers as $h) { + set_exception_handler($h); + } + if (!$handler) { + return; + } + if ($handler !== $h) { + $handler[0]->setExceptionHandler($h); + } + $handler = $handler[0]; + $handlers = []; + + if ($exit = null === $error) { + $error = error_get_last(); + } + + if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) { + // Let's not throw anymore but keep logging + $handler->throwAt(0, true); + $trace = $error['backtrace'] ?? null; + + if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) { + $fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, false, $trace); + } else { + $fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, true, $trace); + } + } else { + $fatalError = null; + } + + try { + if (null !== $fatalError) { + self::$exitCode = 255; + $handler->handleException($fatalError); + } + } catch (FatalError $e) { + // Ignore this re-throw + } + + if ($exit && self::$exitCode) { + $exitCode = self::$exitCode; + register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); }); + } + } + + /** + * Renders the given exception. + * + * As this method is mainly called during boot where nothing is yet available, + * the output is always either HTML or CLI depending where PHP runs. + */ + private function renderException(\Throwable $exception): void + { + $renderer = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliErrorRenderer() : new HtmlErrorRenderer($this->debug); + + $exception = $renderer->render($exception); + + if (!headers_sent()) { + http_response_code($exception->getStatusCode()); + + foreach ($exception->getHeaders() as $name => $value) { + header($name.': '.$value, false); + } + } + + echo $exception->getAsString(); + } + + /** + * Override this method if you want to define more error enhancers. + * + * @return ErrorEnhancerInterface[] + */ + protected function getErrorEnhancers(): iterable + { + return [ + new UndefinedFunctionErrorEnhancer(), + new UndefinedMethodErrorEnhancer(), + new ClassNotFoundErrorEnhancer(), + ]; + } + + /** + * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader. + */ + private function cleanTrace(array $backtrace, int $type, string &$file, int &$line, bool $throw): array + { + $lightTrace = $backtrace; + + for ($i = 0; isset($backtrace[$i]); ++$i) { + if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) { + $lightTrace = \array_slice($lightTrace, 1 + $i); + break; + } + } + if (\E_USER_DEPRECATED === $type) { + for ($i = 0; isset($lightTrace[$i]); ++$i) { + if (!isset($lightTrace[$i]['file'], $lightTrace[$i]['line'], $lightTrace[$i]['function'])) { + continue; + } + if (!isset($lightTrace[$i]['class']) && 'trigger_deprecation' === $lightTrace[$i]['function']) { + $file = $lightTrace[$i]['file']; + $line = $lightTrace[$i]['line']; + $lightTrace = \array_slice($lightTrace, 1 + $i); + break; + } + } + } + if (class_exists(DebugClassLoader::class, false)) { + for ($i = \count($lightTrace) - 2; 0 < $i; --$i) { + if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) { + array_splice($lightTrace, --$i, 2); + } + } + } + if (!($throw || $this->scopedErrors & $type)) { + for ($i = 0; isset($lightTrace[$i]); ++$i) { + unset($lightTrace[$i]['args'], $lightTrace[$i]['object']); + } + } + + return $lightTrace; + } + + /** + * Parse the error message by removing the anonymous class notation + * and using the parent class instead if possible. + */ + private function parseAnonymousClass(string $message): string + { + return 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 function ($m) { + return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0]; + }, $message); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/CliErrorRenderer.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/CliErrorRenderer.php new file mode 100644 index 0000000..5c0f6a7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/CliErrorRenderer.php @@ -0,0 +1,49 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorRenderer; + +use Symfony\Component\ErrorHandler\Exception\FlattenException; +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\CliDumper; + +// Help opcache.preload discover always-needed symbols +class_exists(CliDumper::class); + +/** + * @author Nicolas Grekas <p@tchwork.com> + */ +class CliErrorRenderer implements ErrorRendererInterface +{ + /** + * {@inheritdoc} + */ + public function render(\Throwable $exception): FlattenException + { + $cloner = new VarCloner(); + $dumper = new class() extends CliDumper { + protected function supportsColors(): bool + { + $outputStream = $this->outputStream; + $this->outputStream = fopen('php://stdout', 'w'); + + try { + return parent::supportsColors(); + } finally { + $this->outputStream = $outputStream; + } + } + }; + + return FlattenException::createFromThrowable($exception) + ->setAsString($dumper->dump($cloner->cloneVar($exception), true)); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/ErrorRendererInterface.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/ErrorRendererInterface.php new file mode 100644 index 0000000..aba1966 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/ErrorRendererInterface.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorRenderer; + +use Symfony\Component\ErrorHandler\Exception\FlattenException; + +/** + * Formats an exception to be used as response content. + * + * @author Yonel Ceruto <yonelceruto@gmail.com> + */ +interface ErrorRendererInterface +{ + /** + * Renders a Throwable as a FlattenException. + */ + public function render(\Throwable $exception): FlattenException; +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/HtmlErrorRenderer.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/HtmlErrorRenderer.php new file mode 100644 index 0000000..5b264fa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/HtmlErrorRenderer.php @@ -0,0 +1,381 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorRenderer; + +use Psr\Log\LoggerInterface; +use Symfony\Component\ErrorHandler\Exception\FlattenException; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; + +/** + * @author Yonel Ceruto <yonelceruto@gmail.com> + */ +class HtmlErrorRenderer implements ErrorRendererInterface +{ + private const GHOST_ADDONS = [ + '02-14' => self::GHOST_HEART, + '02-29' => self::GHOST_PLUS, + '10-18' => self::GHOST_GIFT, + ]; + + private const GHOST_GIFT = 'M124.00534057617188,5.3606138080358505 C124.40059661865234,4.644828304648399 125.1237564086914,3.712414965033531 123.88127899169922,3.487462028861046 C123.53517150878906,3.3097832053899765 123.18894958496094,2.9953975528478622 122.8432846069336,3.345616325736046 C122.07421112060547,3.649444565176964 121.40750122070312,4.074306473135948 122.2164306640625,4.869479164481163 C122.57514953613281,5.3830065578222275 122.90142822265625,6.503447040915489 123.3077621459961,6.626829609274864 C123.55027770996094,6.210384353995323 123.7774658203125,5.785196766257286 124.00534057617188,5.3606138080358505 zM122.30630493164062,7.336987480521202 C121.60028076171875,6.076864704489708 121.03211975097656,4.72498320043087 120.16796875,3.562500938773155 C119.11695098876953,2.44033907353878 117.04605865478516,2.940566048026085 116.57544708251953,4.387995228171349 C115.95028686523438,5.819030746817589 117.2991714477539,7.527640804648399 118.826171875,7.348545059561729 C119.98493194580078,7.367936596274376 121.15027618408203,7.420116886496544 122.30630493164062,7.336987480521202 zM128.1732177734375,7.379541382193565 C129.67486572265625,7.17823551595211 130.53842163085938,5.287807449698448 129.68344116210938,4.032590612769127 C128.92578125,2.693056806921959 126.74605560302734,2.6463639587163925 125.98509216308594,4.007616028189659 C125.32617950439453,5.108129009604454 124.75428009033203,6.258124336600304 124.14962768554688,7.388818249106407 C125.48638916015625,7.465229496359825 126.8357162475586,7.447416767477989 128.1732177734375,7.379541382193565 zM130.6601104736328,8.991325363516808 C131.17202758789062,8.540884003043175 133.1543731689453,8.009847149252892 131.65304565429688,7.582054600119591 C131.2811279296875,7.476506695151329 130.84751892089844,6.99234913289547 130.5132598876953,7.124847874045372 C129.78744506835938,8.02728746831417 128.67140197753906,8.55669592320919 127.50616455078125,8.501235947012901 C127.27806091308594,8.576229080557823 126.11459350585938,8.38720129430294 126.428955078125,8.601900085806847 C127.25099182128906,9.070617660880089 128.0523223876953,9.579657539725304 128.902587890625,9.995706543326378 C129.49813842773438,9.678531631827354 130.0761260986328,9.329126343131065 130.6601104736328,8.991325363516808 zM118.96446990966797,9.246344551444054 C119.4022445678711,8.991325363516808 119.84001922607422,8.736305221915245 120.27779388427734,8.481284126639366 C118.93965911865234,8.414779648184776 117.40827941894531,8.607666000723839 116.39698791503906,7.531384453177452 C116.11186981201172,7.212117180228233 115.83845520019531,6.846597656607628 115.44329071044922,7.248530372977257 C114.96995544433594,7.574637398123741 113.5140609741211,7.908811077475548 114.63501739501953,8.306883797049522 C115.61112976074219,8.883499130606651 116.58037567138672,9.474181160330772 117.58061218261719,10.008124336600304 C118.05723571777344,9.784612640738487 118.50651550292969,9.5052699893713 118.96446990966797,9.246344551444054 zM125.38018035888672,12.091858848929405 C125.9474868774414,11.636047348380089 127.32159423828125,11.201767906546593 127.36749267578125,10.712632164359093 C126.08487701416016,9.974547371268272 124.83960723876953,9.152772888541222 123.49772644042969,8.528907760977745 C123.03594207763672,8.353693947196007 122.66152954101562,8.623294815421104 122.28982543945312,8.857431396842003 C121.19065856933594,9.51122473180294 120.06505584716797,10.12446115911007 119.00167083740234,10.835315689444542 C120.39238739013672,11.69529627263546 121.79983520507812,12.529837593436241 123.22095489501953,13.338589653372765 C123.94580841064453,12.932025894522667 124.66128540039062,12.508862480521202 125.38018035888672,12.091858848929405 zM131.07164001464844,13.514615997672081 C131.66018676757812,13.143282875418663 132.2487335205078,12.771927818655968 132.8372802734375,12.400571808218956 C132.8324737548828,11.156818374991417 132.8523406982422,9.912529930472374 132.81829833984375,8.669195160269737 C131.63046264648438,9.332009300589561 130.45948791503906,10.027913078665733 129.30828857421875,10.752535805106163 C129.182373046875,12.035354599356651 129.24623107910156,13.33940313756466 129.27359008789062,14.628684982657433 C129.88104248046875,14.27079389989376 130.4737548828125,13.888019546866417 131.07164001464844,13.514640793204308 zM117.26847839355469,12.731024727225304 C117.32825469970703,11.67083452641964 117.45709991455078,10.46224020421505 116.17853546142578,10.148179039359093 C115.37110900878906,9.77159021794796 114.25194549560547,8.806716904044151 113.62991333007812,8.81639002263546 C113.61052703857422,10.0110072940588 113.62078857421875,11.20585821568966 113.61869049072266,12.400571808218956 C114.81139373779297,13.144886955618858 115.98292541503906,13.925040230154991 117.20137023925781,14.626662239432335 C117.31951141357422,14.010867103934288 117.24227905273438,13.35805033147335 117.26847839355469,12.731024727225304 zM125.80937957763672,16.836034759879112 C126.51483917236328,16.390663132071495 127.22030639648438,15.945291504263878 127.92576599121094,15.49991987645626 C127.92250061035156,14.215868934988976 127.97560119628906,12.929980263113976 127.91757202148438,11.647302612662315 C127.14225769042969,11.869626984000206 126.25550079345703,12.556857094168663 125.43866729736328,12.983742699027061 C124.82704162597656,13.342005714774132 124.21542358398438,13.700271591544151 123.60379028320312,14.05853746831417 C123.61585235595703,15.429577812552452 123.57081604003906,16.803131088614464 123.64839172363281,18.172149643301964 C124.37957000732422,17.744937881827354 125.09130859375,17.284801468253136 125.80937957763672,16.836034759879112 zM122.8521499633789,16.115344032645226 C122.8521499633789,15.429741844534874 122.8521499633789,14.744139656424522 122.8521499633789,14.05853746831417 C121.43595123291016,13.230924591422081 120.02428436279297,12.395455345511436 118.60256958007812,11.577354416251183 C118.52394104003906,12.888403877615929 118.56887817382812,14.204405769705772 118.55702209472656,15.517732605338097 C119.97289276123047,16.4041957706213 121.37410736083984,17.314891800284386 122.80789947509766,18.172149643301964 C122.86368560791016,17.488990768790245 122.84332275390625,16.800363525748253 122.8521499633789,16.115344032645226 zM131.10684204101562,18.871450409293175 C131.68399047851562,18.48711584508419 132.2611541748047,18.10278509557247 132.8383026123047,17.718475326895714 C132.81423950195312,16.499977096915245 132.89776611328125,15.264989838004112 132.77627563476562,14.05993078649044 C131.5760040283203,14.744719490408897 130.41763305664062,15.524359688162804 129.23875427246094,16.255397781729698 C129.26707458496094,17.516149505972862 129.18060302734375,18.791316971182823 129.3108367919922,20.041303619742393 C129.91973876953125,19.667551025748253 130.51010131835938,19.264152511954308 131.10684204101562,18.871450409293175 zM117.2557373046875,18.188333496451378 C117.25104522705078,17.549470886588097 117.24633026123047,16.91058538854122 117.24163055419922,16.271720871329308 C116.04924774169922,15.525708183646202 114.87187957763672,14.75476549565792 113.66158294677734,14.038097366690636 C113.5858383178711,15.262084946036339 113.62901306152344,16.49083898961544 113.61761474609375,17.717010483145714 C114.82051086425781,18.513254150748253 116.00987243652344,19.330610260367393 117.22888946533203,20.101993545889854 C117.27559661865234,19.466014847159386 117.25241088867188,18.825733169913292 117.2557373046875,18.188333496451378 zM125.8398666381836,22.38675306737423 C126.54049682617188,21.921453461050987 127.24110412597656,21.456151947379112 127.94172668457031,20.99083136022091 C127.94009399414062,19.693386062979698 127.96646118164062,18.395381912589073 127.93160247802734,17.098379120230675 C126.50540924072266,17.97775076329708 125.08877563476562,18.873308166861534 123.68258666992188,19.78428266942501 C123.52366638183594,21.03710363805294 123.626708984375,22.32878302037716 123.62647247314453,23.595300659537315 C124.06291198730469,23.86113165318966 125.1788101196289,22.68297766149044 125.8398666381836,22.38675306737423 zM122.8521499633789,21.83134649693966 C122.76741790771484,20.936696991324425 123.21651458740234,19.67745779454708 122.0794677734375,19.330633148550987 C120.93280029296875,18.604360565543175 119.7907485961914,17.870157226920128 118.62899780273438,17.16818617284298 C118.45966339111328,18.396427139639854 118.63676452636719,19.675991043448448 118.50668334960938,20.919256195425987 C119.89984130859375,21.92635916173458 121.32942199707031,22.88914106786251 122.78502655029297,23.803510650992393 C122.90177917480469,23.1627406924963 122.82917022705078,22.48402212560177 122.8521499633789,21.83134649693966 zM117.9798355102539,21.59483526647091 C116.28416442871094,20.46288488805294 114.58848571777344,19.330957397818565 112.892822265625,18.199007019400597 C112.89473724365234,14.705654129385948 112.84647369384766,11.211485847830772 112.90847778320312,7.718807205557823 C113.7575912475586,7.194885239005089 114.66117858886719,6.765397056937218 115.5350341796875,6.284702762961388 C114.97061157226562,4.668964847922325 115.78496551513672,2.7054970115423203 117.42159271240234,2.1007001250982285 C118.79354095458984,1.537783369421959 120.44731903076172,2.0457767099142075 121.32200622558594,3.23083733022213 C121.95732116699219,2.9050118774175644 122.59264373779297,2.5791852325201035 123.22796630859375,2.253336176276207 C123.86669921875,2.5821153968572617 124.50543975830078,2.9108948558568954 125.1441650390625,3.23967407643795 C126.05941009521484,2.154020771384239 127.62747192382812,1.5344576686620712 128.986328125,2.1429056972265244 C130.61741638183594,2.716217741370201 131.50650024414062,4.675290569663048 130.9215545654297,6.2884936183691025 C131.8018341064453,6.78548763692379 132.7589111328125,7.1738648265600204 133.5660400390625,7.780336365103722 C133.60182189941406,11.252970680594444 133.56637573242188,14.726140961050987 133.5631103515625,18.199007019400597 C130.18914794921875,20.431867584586143 126.86984252929688,22.74994657933712 123.44108581542969,24.897907242178917 C122.44406127929688,24.897628769278526 121.5834732055664,23.815067276358604 120.65831756591797,23.37616156041622 C119.76387023925781,22.784828171133995 118.87168884277344,22.19007681310177 117.9798355102539,21.59483526647091 z'; + private const GHOST_HEART = 'M125.91386369681868,8.305165958366445 C128.95033202169043,-0.40540639102854037 140.8469835342744,8.305165958366445 125.91386369681868,19.504526138305664 C110.98208663272044,8.305165958366445 122.87795231771452,-0.40540639102854037 125.91386369681868,8.305165958366445 z'; + private const GHOST_PLUS = 'M111.36824226379395,8.969108581542969 L118.69175148010254,8.969108581542969 L118.69175148010254,1.6455793380737305 L126.20429420471191,1.6455793380737305 L126.20429420471191,8.969108581542969 L133.52781105041504,8.969108581542969 L133.52781105041504,16.481630325317383 L126.20429420471191,16.481630325317383 L126.20429420471191,23.805158615112305 L118.69175148010254,23.805158615112305 L118.69175148010254,16.481630325317383 L111.36824226379395,16.481630325317383 z'; + + private $debug; + private $charset; + private $fileLinkFormat; + private $projectDir; + private $outputBuffer; + private $logger; + + private static $template = 'views/error.html.php'; + + /** + * @param bool|callable $debug The debugging mode as a boolean or a callable that should return it + * @param string|FileLinkFormatter|null $fileLinkFormat + * @param bool|callable $outputBuffer The output buffer as a string or a callable that should return it + */ + public function __construct($debug = false, ?string $charset = null, $fileLinkFormat = null, ?string $projectDir = null, $outputBuffer = '', ?LoggerInterface $logger = null) + { + if (!\is_bool($debug) && !\is_callable($debug)) { + throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a boolean or a callable, "%s" given.', __METHOD__, \gettype($debug))); + } + + if (!\is_string($outputBuffer) && !\is_callable($outputBuffer)) { + throw new \TypeError(sprintf('Argument 5 passed to "%s()" must be a string or a callable, "%s" given.', __METHOD__, \gettype($outputBuffer))); + } + + $this->debug = $debug; + $this->charset = $charset ?: (\ini_get('default_charset') ?: 'UTF-8'); + $this->fileLinkFormat = $fileLinkFormat ?: (\ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')); + $this->projectDir = $projectDir; + $this->outputBuffer = $outputBuffer; + $this->logger = $logger; + } + + /** + * {@inheritdoc} + */ + public function render(\Throwable $exception): FlattenException + { + $headers = ['Content-Type' => 'text/html; charset='.$this->charset]; + if (\is_bool($this->debug) ? $this->debug : ($this->debug)($exception)) { + $headers['X-Debug-Exception'] = rawurlencode($exception->getMessage()); + $headers['X-Debug-Exception-File'] = rawurlencode($exception->getFile()).':'.$exception->getLine(); + } + + $exception = FlattenException::createFromThrowable($exception, null, $headers); + + return $exception->setAsString($this->renderException($exception)); + } + + /** + * Gets the HTML content associated with the given exception. + */ + public function getBody(FlattenException $exception): string + { + return $this->renderException($exception, 'views/exception.html.php'); + } + + /** + * Gets the stylesheet associated with the given exception. + */ + public function getStylesheet(): string + { + if (!$this->debug) { + return $this->include('assets/css/error.css'); + } + + return $this->include('assets/css/exception.css'); + } + + public static function isDebug(RequestStack $requestStack, bool $debug): \Closure + { + return static function () use ($requestStack, $debug): bool { + if (!$request = $requestStack->getCurrentRequest()) { + return $debug; + } + + return $debug && $request->attributes->getBoolean('showException', true); + }; + } + + public static function getAndCleanOutputBuffer(RequestStack $requestStack): \Closure + { + return static function () use ($requestStack): string { + if (!$request = $requestStack->getCurrentRequest()) { + return ''; + } + + $startObLevel = $request->headers->get('X-Php-Ob-Level', -1); + + if (ob_get_level() <= $startObLevel) { + return ''; + } + + Response::closeOutputBuffers($startObLevel + 1, true); + + return ob_get_clean(); + }; + } + + private function renderException(FlattenException $exception, string $debugTemplate = 'views/exception_full.html.php'): string + { + $debug = \is_bool($this->debug) ? $this->debug : ($this->debug)($exception); + $statusText = $this->escape($exception->getStatusText()); + $statusCode = $this->escape($exception->getStatusCode()); + + if (!$debug) { + return $this->include(self::$template, [ + 'statusText' => $statusText, + 'statusCode' => $statusCode, + ]); + } + + $exceptionMessage = $this->escape($exception->getMessage()); + + return $this->include($debugTemplate, [ + 'exception' => $exception, + 'exceptionMessage' => $exceptionMessage, + 'statusText' => $statusText, + 'statusCode' => $statusCode, + 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, + 'currentContent' => \is_string($this->outputBuffer) ? $this->outputBuffer : ($this->outputBuffer)(), + ]); + } + + /** + * Formats an array as a string. + */ + private function formatArgs(array $args): string + { + $result = []; + foreach ($args as $key => $item) { + if ('object' === $item[0]) { + $formattedValue = sprintf('<em>object</em>(%s)', $this->abbrClass($item[1])); + } elseif ('array' === $item[0]) { + $formattedValue = sprintf('<em>array</em>(%s)', \is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]); + } elseif ('null' === $item[0]) { + $formattedValue = '<em>null</em>'; + } elseif ('boolean' === $item[0]) { + $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>'; + } elseif ('resource' === $item[0]) { + $formattedValue = '<em>resource</em>'; + } elseif (preg_match('/[^\x07-\x0D\x1B\x20-\xFF]/', $item[1])) { + $formattedValue = '<em>binary string</em>'; + } else { + $formattedValue = str_replace("\n", '', $this->escape(var_export($item[1], true))); + } + + $result[] = \is_int($key) ? $formattedValue : sprintf("'%s' => %s", $this->escape($key), $formattedValue); + } + + return implode(', ', $result); + } + + private function formatArgsAsText(array $args) + { + return strip_tags($this->formatArgs($args)); + } + + private function escape(string $string): string + { + return htmlspecialchars($string, \ENT_COMPAT | \ENT_SUBSTITUTE, $this->charset); + } + + private function abbrClass(string $class): string + { + $parts = explode('\\', $class); + $short = array_pop($parts); + + return sprintf('<abbr title="%s">%s</abbr>', $class, $short); + } + + private function getFileRelative(string $file): ?string + { + $file = str_replace('\\', '/', $file); + + if (null !== $this->projectDir && 0 === strpos($file, $this->projectDir)) { + return ltrim(substr($file, \strlen($this->projectDir)), '/'); + } + + return null; + } + + /** + * Returns the link for a given file/line pair. + * + * @return string|false + */ + private function getFileLink(string $file, int $line) + { + if ($fmt = $this->fileLinkFormat) { + return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line); + } + + return false; + } + + /** + * Formats a file path. + * + * @param string $file An absolute file path + * @param int $line The line number + * @param string $text Use this text for the link rather than the file path + */ + private function formatFile(string $file, int $line, ?string $text = null): string + { + $file = trim($file); + + if (null === $text) { + $text = $file; + if (null !== $rel = $this->getFileRelative($text)) { + $rel = explode('/', $rel, 2); + $text = sprintf('<abbr title="%s%2$s">%s</abbr>%s', $this->projectDir, $rel[0], '/'.($rel[1] ?? '')); + } + } + + if (0 < $line) { + $text .= ' at line '.$line; + } + + if (false !== $link = $this->getFileLink($file, $line)) { + return sprintf('<a href="%s" title="Click to open this file" class="file_link">%s</a>', $this->escape($link), $text); + } + + return $text; + } + + /** + * Returns an excerpt of a code file around the given line number. + * + * @param string $file A file path + * @param int $line The selected line number + * @param int $srcContext The number of displayed lines around or -1 for the whole file + */ + private function fileExcerpt(string $file, int $line, int $srcContext = 3): string + { + if (is_file($file) && is_readable($file)) { + // highlight_file could throw warnings + // see https://bugs.php.net/25725 + $code = @highlight_file($file, true); + if (\PHP_VERSION_ID >= 80300) { + // remove main pre/code tags + $code = preg_replace('#^<pre.*?>\s*<code.*?>(.*)</code>\s*</pre>#s', '\\1', $code); + // split multiline code tags + $code = preg_replace_callback('#<code ([^>]++)>((?:[^<]*+\\n)++[^<]*+)</code>#', function ($m) { + return "<code $m[1]>".str_replace("\n", "</code>\n<code $m[1]>", $m[2]).'</code>'; + }, $code); + // Convert spaces to html entities to preserve indentation when rendered + $code = str_replace(' ', ' ', $code); + $content = explode("\n", $code); + } else { + // remove main code/span tags + $code = preg_replace('#^<code.*?>\s*<span.*?>(.*)</span>\s*</code>#s', '\\1', $code); + // split multiline spans + $code = preg_replace_callback('#<span ([^>]++)>((?:[^<]*+<br \/>)++[^<]*+)</span>#', function ($m) { + return "<span $m[1]>".str_replace('<br />', "</span><br /><span $m[1]>", $m[2]).'</span>'; + }, $code); + $content = explode('<br />', $code); + } + + $lines = []; + if (0 > $srcContext) { + $srcContext = \count($content); + } + + for ($i = max($line - $srcContext, 1), $max = min($line + $srcContext, \count($content)); $i <= $max; ++$i) { + $lines[] = '<li'.($i == $line ? ' class="selected"' : '').'><code>'.$this->fixCodeMarkup($content[$i - 1]).'</code></li>'; + } + + return '<ol start="'.max($line - $srcContext, 1).'">'.implode("\n", $lines).'</ol>'; + } + + return ''; + } + + private function fixCodeMarkup(string $line) + { + // </span> ending tag from previous line + $opening = strpos($line, '<span'); + $closing = strpos($line, '</span>'); + if (false !== $closing && (false === $opening || $closing < $opening)) { + $line = substr_replace($line, '', $closing, 7); + } + + // missing </span> tag at the end of line + $opening = strrpos($line, '<span'); + $closing = strrpos($line, '</span>'); + if (false !== $opening && (false === $closing || $closing < $opening)) { + $line .= '</span>'; + } + + return trim($line); + } + + private function formatFileFromText(string $text) + { + return preg_replace_callback('/in ("|")?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) { + return 'in '.$this->formatFile($match[2], $match[3]); + }, $text) ?? $text; + } + + private function formatLogMessage(string $message, array $context) + { + if ($context && false !== strpos($message, '{')) { + $replacements = []; + foreach ($context as $key => $val) { + if (\is_scalar($val)) { + $replacements['{'.$key.'}'] = $val; + } + } + + if ($replacements) { + $message = strtr($message, $replacements); + } + } + + return $this->escape($message); + } + + private function addElementToGhost(): string + { + if (!isset(self::GHOST_ADDONS[date('m-d')])) { + return ''; + } + + return '<path d="'.self::GHOST_ADDONS[date('m-d')].'" fill="#fff" fill-opacity="0.6"></path>'; + } + + private function include(string $name, array $context = []): string + { + extract($context, \EXTR_SKIP); + ob_start(); + + include is_file(\dirname(__DIR__).'/Resources/'.$name) ? \dirname(__DIR__).'/Resources/'.$name : $name; + + return trim(ob_get_clean()); + } + + /** + * Allows overriding the default non-debug template. + * + * @param string $template path to the custom template file to render + */ + public static function setTemplate(string $template): void + { + self::$template = $template; + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/SerializerErrorRenderer.php b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/SerializerErrorRenderer.php new file mode 100644 index 0000000..e6c4c89 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ErrorRenderer/SerializerErrorRenderer.php @@ -0,0 +1,92 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\ErrorRenderer; + +use Symfony\Component\ErrorHandler\Exception\FlattenException; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\Serializer\Exception\NotEncodableValueException; +use Symfony\Component\Serializer\SerializerInterface; + +/** + * Formats an exception using Serializer for rendering. + * + * @author Nicolas Grekas <p@tchwork.com> + */ +class SerializerErrorRenderer implements ErrorRendererInterface +{ + private $serializer; + private $format; + private $fallbackErrorRenderer; + private $debug; + + /** + * @param string|callable(FlattenException) $format The format as a string or a callable that should return it + * formats not supported by Request::getMimeTypes() should be given as mime types + * @param bool|callable $debug The debugging mode as a boolean or a callable that should return it + */ + public function __construct(SerializerInterface $serializer, $format, ?ErrorRendererInterface $fallbackErrorRenderer = null, $debug = false) + { + if (!\is_string($format) && !\is_callable($format)) { + throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be a string or a callable, "%s" given.', __METHOD__, \gettype($format))); + } + + if (!\is_bool($debug) && !\is_callable($debug)) { + throw new \TypeError(sprintf('Argument 4 passed to "%s()" must be a boolean or a callable, "%s" given.', __METHOD__, \gettype($debug))); + } + + $this->serializer = $serializer; + $this->format = $format; + $this->fallbackErrorRenderer = $fallbackErrorRenderer ?? new HtmlErrorRenderer(); + $this->debug = $debug; + } + + /** + * {@inheritdoc} + */ + public function render(\Throwable $exception): FlattenException + { + $headers = ['Vary' => 'Accept']; + $debug = \is_bool($this->debug) ? $this->debug : ($this->debug)($exception); + if ($debug) { + $headers['X-Debug-Exception'] = rawurlencode($exception->getMessage()); + $headers['X-Debug-Exception-File'] = rawurlencode($exception->getFile()).':'.$exception->getLine(); + } + + $flattenException = FlattenException::createFromThrowable($exception, null, $headers); + + try { + $format = \is_string($this->format) ? $this->format : ($this->format)($flattenException); + $headers['Content-Type'] = Request::getMimeTypes($format)[0] ?? $format; + + $flattenException->setAsString($this->serializer->serialize($flattenException, $format, [ + 'exception' => $exception, + 'debug' => $debug, + ])); + } catch (NotEncodableValueException $e) { + $flattenException = $this->fallbackErrorRenderer->render($exception); + } + + return $flattenException->setHeaders($flattenException->getHeaders() + $headers); + } + + public static function getPreferredFormat(RequestStack $requestStack): \Closure + { + return static function () use ($requestStack) { + if (!$request = $requestStack->getCurrentRequest()) { + throw new NotEncodableValueException(); + } + + return $request->getPreferredFormat(); + }; + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Exception/FlattenException.php b/php/libraries/composer/vendor/symfony/error-handler/Exception/FlattenException.php new file mode 100644 index 0000000..f73842a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Exception/FlattenException.php @@ -0,0 +1,427 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Exception; + +use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; + +/** + * FlattenException wraps a PHP Error or Exception to be able to serialize it. + * + * Basically, this class removes all objects from the trace. + * + * @author Fabien Potencier <fabien@symfony.com> + */ +class FlattenException +{ + /** @var string */ + private $message; + + /** @var int|string */ + private $code; + + /** @var self|null */ + private $previous; + + /** @var array */ + private $trace; + + /** @var string */ + private $traceAsString; + + /** @var string */ + private $class; + + /** @var int */ + private $statusCode; + + /** @var string */ + private $statusText; + + /** @var array */ + private $headers; + + /** @var string */ + private $file; + + /** @var int */ + private $line; + + /** @var string|null */ + private $asString; + + /** + * @return static + */ + public static function create(\Exception $exception, ?int $statusCode = null, array $headers = []): self + { + return static::createFromThrowable($exception, $statusCode, $headers); + } + + /** + * @return static + */ + public static function createFromThrowable(\Throwable $exception, ?int $statusCode = null, array $headers = []): self + { + $e = new static(); + $e->setMessage($exception->getMessage()); + $e->setCode($exception->getCode()); + + if ($exception instanceof HttpExceptionInterface) { + $statusCode = $exception->getStatusCode(); + $headers = array_merge($headers, $exception->getHeaders()); + } elseif ($exception instanceof RequestExceptionInterface) { + $statusCode = 400; + } + + if (null === $statusCode) { + $statusCode = 500; + } + + if (class_exists(Response::class) && isset(Response::$statusTexts[$statusCode])) { + $statusText = Response::$statusTexts[$statusCode]; + } else { + $statusText = 'Whoops, looks like something went wrong.'; + } + + $e->setStatusText($statusText); + $e->setStatusCode($statusCode); + $e->setHeaders($headers); + $e->setTraceFromThrowable($exception); + $e->setClass(\get_class($exception)); + $e->setFile($exception->getFile()); + $e->setLine($exception->getLine()); + + $previous = $exception->getPrevious(); + + if ($previous instanceof \Throwable) { + $e->setPrevious(static::createFromThrowable($previous)); + } + + return $e; + } + + public function toArray(): array + { + $exceptions = []; + foreach (array_merge([$this], $this->getAllPrevious()) as $exception) { + $exceptions[] = [ + 'message' => $exception->getMessage(), + 'class' => $exception->getClass(), + 'trace' => $exception->getTrace(), + ]; + } + + return $exceptions; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + /** + * @return $this + */ + public function setStatusCode(int $code): self + { + $this->statusCode = $code; + + return $this; + } + + public function getHeaders(): array + { + return $this->headers; + } + + /** + * @return $this + */ + public function setHeaders(array $headers): self + { + $this->headers = $headers; + + return $this; + } + + public function getClass(): string + { + return $this->class; + } + + /** + * @return $this + */ + public function setClass(string $class): self + { + $this->class = false !== strpos($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class; + + return $this; + } + + public function getFile(): string + { + return $this->file; + } + + /** + * @return $this + */ + public function setFile(string $file): self + { + $this->file = $file; + + return $this; + } + + public function getLine(): int + { + return $this->line; + } + + /** + * @return $this + */ + public function setLine(int $line): self + { + $this->line = $line; + + return $this; + } + + public function getStatusText(): string + { + return $this->statusText; + } + + /** + * @return $this + */ + public function setStatusText(string $statusText): self + { + $this->statusText = $statusText; + + return $this; + } + + public function getMessage(): string + { + return $this->message; + } + + /** + * @return $this + */ + public function setMessage(string $message): self + { + if (false !== strpos($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]++/', function ($m) { + return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0]; + }, $message); + } + + $this->message = $message; + + return $this; + } + + /** + * @return int|string int most of the time (might be a string with PDOException) + */ + public function getCode() + { + return $this->code; + } + + /** + * @param int|string $code + * + * @return $this + */ + public function setCode($code): self + { + $this->code = $code; + + return $this; + } + + public function getPrevious(): ?self + { + return $this->previous; + } + + /** + * @return $this + */ + public function setPrevious(?self $previous): self + { + $this->previous = $previous; + + return $this; + } + + /** + * @return self[] + */ + public function getAllPrevious(): array + { + $exceptions = []; + $e = $this; + while ($e = $e->getPrevious()) { + $exceptions[] = $e; + } + + return $exceptions; + } + + public function getTrace(): array + { + return $this->trace; + } + + /** + * @return $this + */ + public function setTraceFromThrowable(\Throwable $throwable): self + { + $this->traceAsString = $throwable->getTraceAsString(); + + return $this->setTrace($throwable->getTrace(), $throwable->getFile(), $throwable->getLine()); + } + + /** + * @return $this + */ + public function setTrace(array $trace, ?string $file, ?int $line): self + { + $this->trace = []; + $this->trace[] = [ + 'namespace' => '', + 'short_class' => '', + 'class' => '', + 'type' => '', + 'function' => '', + 'file' => $file, + 'line' => $line, + 'args' => [], + ]; + foreach ($trace as $entry) { + $class = ''; + $namespace = ''; + if (isset($entry['class'])) { + $parts = explode('\\', $entry['class']); + $class = array_pop($parts); + $namespace = implode('\\', $parts); + } + + $this->trace[] = [ + 'namespace' => $namespace, + 'short_class' => $class, + 'class' => $entry['class'] ?? '', + 'type' => $entry['type'] ?? '', + 'function' => $entry['function'] ?? null, + 'file' => $entry['file'] ?? null, + 'line' => $entry['line'] ?? null, + 'args' => isset($entry['args']) ? $this->flattenArgs($entry['args']) : [], + ]; + } + + return $this; + } + + private function flattenArgs(array $args, int $level = 0, int &$count = 0): array + { + $result = []; + foreach ($args as $key => $value) { + if (++$count > 1e4) { + return ['array', '*SKIPPED over 10000 entries*']; + } + if ($value instanceof \__PHP_Incomplete_Class) { + $result[$key] = ['incomplete-object', $this->getClassNameFromIncomplete($value)]; + } elseif (\is_object($value)) { + $result[$key] = ['object', \get_class($value)]; + } elseif (\is_array($value)) { + if ($level > 10) { + $result[$key] = ['array', '*DEEP NESTED ARRAY*']; + } else { + $result[$key] = ['array', $this->flattenArgs($value, $level + 1, $count)]; + } + } elseif (null === $value) { + $result[$key] = ['null', null]; + } elseif (\is_bool($value)) { + $result[$key] = ['boolean', $value]; + } elseif (\is_int($value)) { + $result[$key] = ['integer', $value]; + } elseif (\is_float($value)) { + $result[$key] = ['float', $value]; + } elseif (\is_resource($value)) { + $result[$key] = ['resource', get_resource_type($value)]; + } else { + $result[$key] = ['string', (string) $value]; + } + } + + return $result; + } + + private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value): string + { + $array = new \ArrayObject($value); + + return $array['__PHP_Incomplete_Class_Name']; + } + + public function getTraceAsString(): string + { + return $this->traceAsString; + } + + /** + * @return $this + */ + public function setAsString(?string $asString): self + { + $this->asString = $asString; + + return $this; + } + + public function getAsString(): string + { + if (null !== $this->asString) { + return $this->asString; + } + + $message = ''; + $next = false; + + foreach (array_reverse(array_merge([$this], $this->getAllPrevious())) as $exception) { + if ($next) { + $message .= 'Next '; + } else { + $next = true; + } + $message .= $exception->getClass(); + + if ('' != $exception->getMessage()) { + $message .= ': '.$exception->getMessage(); + } + + $message .= ' in '.$exception->getFile().':'.$exception->getLine(). + "\nStack trace:\n".$exception->getTraceAsString()."\n\n"; + } + + return rtrim($message); + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Exception/SilencedErrorContext.php b/php/libraries/composer/vendor/symfony/error-handler/Exception/SilencedErrorContext.php new file mode 100644 index 0000000..18defc7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Exception/SilencedErrorContext.php @@ -0,0 +1,67 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Exception; + +/** + * Data Object that represents a Silenced Error. + * + * @author Grégoire Pineau <lyrixx@lyrixx.info> + */ +class SilencedErrorContext implements \JsonSerializable +{ + public $count = 1; + + private $severity; + private $file; + private $line; + private $trace; + + public function __construct(int $severity, string $file, int $line, array $trace = [], int $count = 1) + { + $this->severity = $severity; + $this->file = $file; + $this->line = $line; + $this->trace = $trace; + $this->count = $count; + } + + public function getSeverity(): int + { + return $this->severity; + } + + public function getFile(): string + { + return $this->file; + } + + public function getLine(): int + { + return $this->line; + } + + public function getTrace(): array + { + return $this->trace; + } + + public function jsonSerialize(): array + { + return [ + 'severity' => $this->severity, + 'file' => $this->file, + 'line' => $this->line, + 'trace' => $this->trace, + 'count' => $this->count, + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Internal/TentativeTypes.php b/php/libraries/composer/vendor/symfony/error-handler/Internal/TentativeTypes.php new file mode 100644 index 0000000..1e8afe3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Internal/TentativeTypes.php @@ -0,0 +1,1643 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Internal; + +/** + * This class has been generated by extract-tentative-return-types.php. + * + * @internal + */ +class TentativeTypes +{ + public const RETURN_TYPES = [ + 'CURLFile' => [ + 'getFilename' => 'string', + 'getMimeType' => 'string', + 'getPostFilename' => 'string', + 'setMimeType' => 'void', + 'setPostFilename' => 'void', + ], + 'DateTimeInterface' => [ + 'format' => 'string', + 'getTimezone' => 'DateTimeZone|false', + 'getOffset' => 'int', + 'getTimestamp' => 'int', + 'diff' => 'DateInterval', + '__wakeup' => 'void', + ], + 'DateTime' => [ + '__wakeup' => 'void', + '__set_state' => 'DateTime', + 'createFromImmutable' => 'static', + 'createFromFormat' => 'DateTime|false', + 'getLastErrors' => 'array|false', + 'format' => 'string', + 'modify' => 'DateTime|false', + 'add' => 'DateTime', + 'sub' => 'DateTime', + 'getTimezone' => 'DateTimeZone|false', + 'setTimezone' => 'DateTime', + 'getOffset' => 'int', + 'setTime' => 'DateTime', + 'setDate' => 'DateTime', + 'setISODate' => 'DateTime', + 'setTimestamp' => 'DateTime', + 'getTimestamp' => 'int', + 'diff' => 'DateInterval', + ], + 'DateTimeImmutable' => [ + '__wakeup' => 'void', + '__set_state' => 'DateTimeImmutable', + 'createFromFormat' => 'DateTimeImmutable|false', + 'getLastErrors' => 'array|false', + 'format' => 'string', + 'getTimezone' => 'DateTimeZone|false', + 'getOffset' => 'int', + 'getTimestamp' => 'int', + 'diff' => 'DateInterval', + 'modify' => 'DateTimeImmutable|false', + 'add' => 'DateTimeImmutable', + 'sub' => 'DateTimeImmutable', + 'setTimezone' => 'DateTimeImmutable', + 'setTime' => 'DateTimeImmutable', + 'setDate' => 'DateTimeImmutable', + 'setISODate' => 'DateTimeImmutable', + 'setTimestamp' => 'DateTimeImmutable', + 'createFromMutable' => 'static', + ], + 'DateTimeZone' => [ + 'getName' => 'string', + 'getOffset' => 'int', + 'getTransitions' => 'array|false', + 'getLocation' => 'array|false', + 'listAbbreviations' => 'array', + 'listIdentifiers' => 'array', + '__wakeup' => 'void', + '__set_state' => 'DateTimeZone', + ], + 'DateInterval' => [ + 'createFromDateString' => 'DateInterval|false', + 'format' => 'string', + '__wakeup' => 'void', + '__set_state' => 'DateInterval', + ], + 'DatePeriod' => [ + 'getStartDate' => 'DateTimeInterface', + 'getEndDate' => '?DateTimeInterface', + 'getDateInterval' => 'DateInterval', + 'getRecurrences' => '?int', + '__wakeup' => 'void', + '__set_state' => 'DatePeriod', + ], + 'DOMNode' => [ + 'C14N' => 'string|false', + 'C14NFile' => 'int|false', + 'getLineNo' => 'int', + 'getNodePath' => '?string', + 'hasAttributes' => 'bool', + 'hasChildNodes' => 'bool', + 'isDefaultNamespace' => 'bool', + 'isSameNode' => 'bool', + 'isSupported' => 'bool', + 'lookupNamespaceURI' => '?string', + 'lookupPrefix' => '?string', + 'normalize' => 'void', + ], + 'DOMImplementation' => [ + 'getFeature' => 'never', + 'hasFeature' => 'bool', + ], + 'DOMDocumentFragment' => [ + 'appendXML' => 'bool', + ], + 'DOMNodeList' => [ + 'count' => 'int', + ], + 'DOMCharacterData' => [ + 'appendData' => 'bool', + 'insertData' => 'bool', + 'deleteData' => 'bool', + 'replaceData' => 'bool', + ], + 'DOMAttr' => [ + 'isId' => 'bool', + ], + 'DOMElement' => [ + 'getAttribute' => 'string', + 'getAttributeNS' => 'string', + 'getElementsByTagName' => 'DOMNodeList', + 'getElementsByTagNameNS' => 'DOMNodeList', + 'hasAttribute' => 'bool', + 'hasAttributeNS' => 'bool', + 'removeAttribute' => 'bool', + 'removeAttributeNS' => 'void', + 'setAttributeNS' => 'void', + 'setIdAttribute' => 'void', + 'setIdAttributeNS' => 'void', + 'setIdAttributeNode' => 'void', + ], + 'DOMDocument' => [ + 'createComment' => 'DOMComment', + 'createDocumentFragment' => 'DOMDocumentFragment', + 'createTextNode' => 'DOMText', + 'getElementById' => '?DOMElement', + 'getElementsByTagName' => 'DOMNodeList', + 'getElementsByTagNameNS' => 'DOMNodeList', + 'normalizeDocument' => 'void', + 'registerNodeClass' => 'bool', + 'save' => 'int|false', + 'saveHTML' => 'string|false', + 'saveHTMLFile' => 'int|false', + 'saveXML' => 'string|false', + 'schemaValidate' => 'bool', + 'schemaValidateSource' => 'bool', + 'relaxNGValidate' => 'bool', + 'relaxNGValidateSource' => 'bool', + 'validate' => 'bool', + 'xinclude' => 'int|false', + ], + 'DOMText' => [ + 'isWhitespaceInElementContent' => 'bool', + 'isElementContentWhitespace' => 'bool', + ], + 'DOMNamedNodeMap' => [ + 'getNamedItem' => '?DOMNode', + 'getNamedItemNS' => '?DOMNode', + 'item' => '?DOMNode', + 'count' => 'int', + ], + 'DOMXPath' => [ + 'evaluate' => 'mixed', + 'query' => 'mixed', + 'registerNamespace' => 'bool', + 'registerPhpFunctions' => 'void', + ], + 'finfo' => [ + 'file' => 'string|false', + 'buffer' => 'string|false', + ], + 'IntlPartsIterator' => [ + 'getBreakIterator' => 'IntlBreakIterator', + 'getRuleStatus' => 'int', + ], + 'IntlBreakIterator' => [ + 'createCharacterInstance' => '?IntlBreakIterator', + 'createCodePointInstance' => 'IntlCodePointBreakIterator', + 'createLineInstance' => '?IntlBreakIterator', + 'createSentenceInstance' => '?IntlBreakIterator', + 'createTitleInstance' => '?IntlBreakIterator', + 'createWordInstance' => '?IntlBreakIterator', + 'current' => 'int', + 'first' => 'int', + 'following' => 'int', + 'getErrorCode' => 'int', + 'getErrorMessage' => 'string', + 'getLocale' => 'string|false', + 'getPartsIterator' => 'IntlPartsIterator', + 'getText' => '?string', + 'isBoundary' => 'bool', + 'last' => 'int', + 'next' => 'int', + 'preceding' => 'int', + 'previous' => 'int', + 'setText' => '?bool', + ], + 'IntlRuleBasedBreakIterator' => [ + 'getBinaryRules' => 'string|false', + 'getRules' => 'string|false', + 'getRuleStatus' => 'int', + 'getRuleStatusVec' => 'array|false', + ], + 'IntlCodePointBreakIterator' => [ + 'getLastCodePoint' => 'int', + ], + 'IntlCalendar' => [ + 'createInstance' => '?IntlCalendar', + 'equals' => 'bool', + 'fieldDifference' => 'int|false', + 'add' => 'bool', + 'after' => 'bool', + 'before' => 'bool', + 'fromDateTime' => '?IntlCalendar', + 'get' => 'int|false', + 'getActualMaximum' => 'int|false', + 'getActualMinimum' => 'int|false', + 'getAvailableLocales' => 'array', + 'getDayOfWeekType' => 'int|false', + 'getErrorCode' => 'int|false', + 'getErrorMessage' => 'string|false', + 'getFirstDayOfWeek' => 'int|false', + 'getGreatestMinimum' => 'int|false', + 'getKeywordValuesForLocale' => 'IntlIterator|false', + 'getLeastMaximum' => 'int|false', + 'getLocale' => 'string|false', + 'getMaximum' => 'int|false', + 'getMinimalDaysInFirstWeek' => 'int|false', + 'getMinimum' => 'int|false', + 'getNow' => 'float', + 'getRepeatedWallTimeOption' => 'int', + 'getSkippedWallTimeOption' => 'int', + 'getTime' => 'float|false', + 'getTimeZone' => 'IntlTimeZone|false', + 'getType' => 'string', + 'getWeekendTransition' => 'int|false', + 'inDaylightTime' => 'bool', + 'isEquivalentTo' => 'bool', + 'isLenient' => 'bool', + 'isWeekend' => 'bool', + 'roll' => 'bool', + 'isSet' => 'bool', + 'setTime' => 'bool', + 'setTimeZone' => 'bool', + 'toDateTime' => 'DateTime|false', + ], + 'IntlGregorianCalendar' => [ + 'setGregorianChange' => 'bool', + 'getGregorianChange' => 'float', + 'isLeapYear' => 'bool', + ], + 'Collator' => [ + 'create' => '?Collator', + 'compare' => 'int|false', + 'sort' => 'bool', + 'sortWithSortKeys' => 'bool', + 'asort' => 'bool', + 'getAttribute' => 'int|false', + 'setAttribute' => 'bool', + 'getStrength' => 'int', + 'getLocale' => 'string|false', + 'getErrorCode' => 'int|false', + 'getErrorMessage' => 'string|false', + 'getSortKey' => 'string|false', + ], + 'IntlIterator' => [ + 'current' => 'mixed', + 'key' => 'mixed', + 'next' => 'void', + 'rewind' => 'void', + 'valid' => 'bool', + ], + 'UConverter' => [ + 'convert' => 'string|false', + 'fromUCallback' => 'string|int|array|null', + 'getAliases' => 'array|false|null', + 'getAvailable' => 'array', + 'getDestinationEncoding' => 'string|false|null', + 'getDestinationType' => 'int|false|null', + 'getErrorCode' => 'int', + 'getErrorMessage' => '?string', + 'getSourceEncoding' => 'string|false|null', + 'getSourceType' => 'int|false|null', + 'getStandards' => '?array', + 'getSubstChars' => 'string|false|null', + 'reasonText' => 'string', + 'setDestinationEncoding' => 'bool', + 'setSourceEncoding' => 'bool', + 'setSubstChars' => 'bool', + 'toUCallback' => 'string|int|array|null', + 'transcode' => 'string|false', + ], + 'IntlDateFormatter' => [ + 'create' => '?IntlDateFormatter', + 'getDateType' => 'int|false', + 'getTimeType' => 'int|false', + 'getCalendar' => 'int|false', + 'setCalendar' => 'bool', + 'getTimeZoneId' => 'string|false', + 'getCalendarObject' => 'IntlCalendar|false|null', + 'getTimeZone' => 'IntlTimeZone|false', + 'setTimeZone' => '?bool', + 'setPattern' => 'bool', + 'getPattern' => 'string|false', + 'getLocale' => 'string|false', + 'setLenient' => 'void', + 'isLenient' => 'bool', + 'format' => 'string|false', + 'formatObject' => 'string|false', + 'parse' => 'int|float|false', + 'localtime' => 'array|false', + 'getErrorCode' => 'int', + 'getErrorMessage' => 'string', + ], + 'NumberFormatter' => [ + 'create' => '?NumberFormatter', + 'format' => 'string|false', + 'parse' => 'int|float|false', + 'formatCurrency' => 'string|false', + 'parseCurrency' => 'float|false', + 'setAttribute' => 'bool', + 'getAttribute' => 'int|float|false', + 'setTextAttribute' => 'bool', + 'getTextAttribute' => 'string|false', + 'setSymbol' => 'bool', + 'getSymbol' => 'string|false', + 'setPattern' => 'bool', + 'getPattern' => 'string|false', + 'getLocale' => 'string|false', + 'getErrorCode' => 'int', + 'getErrorMessage' => 'string', + ], + 'Locale' => [ + 'getDefault' => 'string', + 'getPrimaryLanguage' => '?string', + 'getScript' => '?string', + 'getRegion' => '?string', + 'getKeywords' => 'array|false|null', + 'getDisplayScript' => 'string|false', + 'getDisplayRegion' => 'string|false', + 'getDisplayName' => 'string|false', + 'getDisplayLanguage' => 'string|false', + 'getDisplayVariant' => 'string|false', + 'composeLocale' => 'string|false', + 'parseLocale' => '?array', + 'getAllVariants' => '?array', + 'filterMatches' => '?bool', + 'lookup' => '?string', + 'canonicalize' => '?string', + 'acceptFromHttp' => 'string|false', + ], + 'MessageFormatter' => [ + 'create' => '?MessageFormatter', + 'format' => 'string|false', + 'formatMessage' => 'string|false', + 'parse' => 'array|false', + 'parseMessage' => 'array|false', + 'setPattern' => 'bool', + 'getPattern' => 'string|false', + 'getLocale' => 'string', + 'getErrorCode' => 'int', + 'getErrorMessage' => 'string', + ], + 'Normalizer' => [ + 'normalize' => 'string|false', + 'isNormalized' => 'bool', + 'getRawDecomposition' => '?string', + ], + 'ResourceBundle' => [ + 'create' => '?ResourceBundle', + 'get' => 'mixed', + 'count' => 'int', + 'getLocales' => 'array|false', + 'getErrorCode' => 'int', + 'getErrorMessage' => 'string', + ], + 'Spoofchecker' => [ + 'isSuspicious' => 'bool', + 'areConfusable' => 'bool', + 'setAllowedLocales' => 'void', + 'setChecks' => 'void', + 'setRestrictionLevel' => 'void', + ], + 'IntlTimeZone' => [ + 'countEquivalentIDs' => 'int|false', + 'createDefault' => 'IntlTimeZone', + 'createEnumeration' => 'IntlIterator|false', + 'createTimeZone' => '?IntlTimeZone', + 'createTimeZoneIDEnumeration' => 'IntlIterator|false', + 'fromDateTimeZone' => '?IntlTimeZone', + 'getCanonicalID' => 'string|false', + 'getDisplayName' => 'string|false', + 'getDSTSavings' => 'int', + 'getEquivalentID' => 'string|false', + 'getErrorCode' => 'int|false', + 'getErrorMessage' => 'string|false', + 'getGMT' => 'IntlTimeZone', + 'getID' => 'string|false', + 'getOffset' => 'bool', + 'getRawOffset' => 'int', + 'getRegion' => 'string|false', + 'getTZDataVersion' => 'string|false', + 'getUnknown' => 'IntlTimeZone', + 'getWindowsID' => 'string|false', + 'getIDForWindowsID' => 'string|false', + 'hasSameRules' => 'bool', + 'toDateTimeZone' => 'DateTimeZone|false', + 'useDaylightTime' => 'bool', + ], + 'Transliterator' => [ + 'create' => '?Transliterator', + 'createFromRules' => '?Transliterator', + 'createInverse' => '?Transliterator', + 'listIDs' => 'array|false', + 'transliterate' => 'string|false', + 'getErrorCode' => 'int|false', + 'getErrorMessage' => 'string|false', + ], + 'IntlChar' => [ + 'hasBinaryProperty' => '?bool', + 'charAge' => '?array', + 'charDigitValue' => '?int', + 'charDirection' => '?int', + 'charFromName' => '?int', + 'charMirror' => 'int|string|null', + 'charName' => '?string', + 'charType' => '?int', + 'chr' => '?string', + 'digit' => 'int|false|null', + 'enumCharNames' => '?bool', + 'enumCharTypes' => 'void', + 'foldCase' => 'int|string|null', + 'forDigit' => 'int', + 'getBidiPairedBracket' => 'int|string|null', + 'getBlockCode' => '?int', + 'getCombiningClass' => '?int', + 'getFC_NFKC_Closure' => 'string|false|null', + 'getIntPropertyMaxValue' => 'int', + 'getIntPropertyMinValue' => 'int', + 'getIntPropertyValue' => '?int', + 'getNumericValue' => '?float', + 'getPropertyEnum' => 'int', + 'getPropertyName' => 'string|false', + 'getPropertyValueEnum' => 'int', + 'getPropertyValueName' => 'string|false', + 'getUnicodeVersion' => 'array', + 'isalnum' => '?bool', + 'isalpha' => '?bool', + 'isbase' => '?bool', + 'isblank' => '?bool', + 'iscntrl' => '?bool', + 'isdefined' => '?bool', + 'isdigit' => '?bool', + 'isgraph' => '?bool', + 'isIDIgnorable' => '?bool', + 'isIDPart' => '?bool', + 'isIDStart' => '?bool', + 'isISOControl' => '?bool', + 'isJavaIDPart' => '?bool', + 'isJavaIDStart' => '?bool', + 'isJavaSpaceChar' => '?bool', + 'islower' => '?bool', + 'isMirrored' => '?bool', + 'isprint' => '?bool', + 'ispunct' => '?bool', + 'isspace' => '?bool', + 'istitle' => '?bool', + 'isUAlphabetic' => '?bool', + 'isULowercase' => '?bool', + 'isupper' => '?bool', + 'isUUppercase' => '?bool', + 'isUWhiteSpace' => '?bool', + 'isWhitespace' => '?bool', + 'isxdigit' => '?bool', + 'ord' => '?int', + 'tolower' => 'int|string|null', + 'totitle' => 'int|string|null', + 'toupper' => 'int|string|null', + ], + 'JsonSerializable' => [ + 'jsonSerialize' => 'mixed', + ], + 'mysqli' => [ + 'autocommit' => 'bool', + 'begin_transaction' => 'bool', + 'change_user' => 'bool', + 'character_set_name' => 'string', + 'commit' => 'bool', + 'connect' => 'bool', + 'dump_debug_info' => 'bool', + 'get_charset' => '?object', + 'get_client_info' => 'string', + 'get_connection_stats' => 'array', + 'get_server_info' => 'string', + 'get_warnings' => 'mysqli_warning|false', + 'kill' => 'bool', + 'multi_query' => 'bool', + 'more_results' => 'bool', + 'next_result' => 'bool', + 'ping' => 'bool', + 'poll' => 'int|false', + 'prepare' => 'mysqli_stmt|false', + 'query' => 'mysqli_result|bool', + 'real_connect' => 'bool', + 'real_escape_string' => 'string', + 'reap_async_query' => 'mysqli_result|bool', + 'escape_string' => 'string', + 'real_query' => 'bool', + 'release_savepoint' => 'bool', + 'rollback' => 'bool', + 'savepoint' => 'bool', + 'select_db' => 'bool', + 'set_charset' => 'bool', + 'options' => 'bool', + 'set_opt' => 'bool', + 'stat' => 'string|false', + 'stmt_init' => 'mysqli_stmt|false', + 'store_result' => 'mysqli_result|false', + 'thread_safe' => 'bool', + 'use_result' => 'mysqli_result|false', + 'refresh' => 'bool', + ], + 'mysqli_result' => [ + 'close' => 'void', + 'free' => 'void', + 'data_seek' => 'bool', + 'fetch_field' => 'object|false', + 'fetch_fields' => 'array', + 'fetch_field_direct' => 'object|false', + 'fetch_all' => 'array', + 'fetch_array' => 'array|null|false', + 'fetch_assoc' => 'array|null|false', + 'fetch_object' => 'object|null|false', + 'fetch_row' => 'array|null|false', + 'field_seek' => 'bool', + 'free_result' => 'void', + ], + 'mysqli_stmt' => [ + 'attr_get' => 'int', + 'attr_set' => 'bool', + 'bind_param' => 'bool', + 'bind_result' => 'bool', + 'data_seek' => 'void', + 'execute' => 'bool', + 'fetch' => '?bool', + 'get_warnings' => 'mysqli_warning|false', + 'result_metadata' => 'mysqli_result|false', + 'more_results' => 'bool', + 'next_result' => 'bool', + 'num_rows' => 'int|string', + 'send_long_data' => 'bool', + 'free_result' => 'void', + 'reset' => 'bool', + 'prepare' => 'bool', + 'store_result' => 'bool', + 'get_result' => 'mysqli_result|false', + ], + 'OCILob' => [ + 'save' => 'bool', + 'import' => 'bool', + 'saveFile' => 'bool', + 'load' => 'string|false', + 'read' => 'string|false', + 'eof' => 'bool', + 'tell' => 'int|false', + 'rewind' => 'bool', + 'seek' => 'bool', + 'size' => 'int|false', + 'write' => 'int|false', + 'append' => 'bool', + 'truncate' => 'bool', + 'erase' => 'int|false', + 'flush' => 'bool', + 'setBuffering' => 'bool', + 'getBuffering' => 'bool', + 'writeToFile' => 'bool', + 'export' => 'bool', + 'writeTemporary' => 'bool', + 'close' => 'bool', + 'free' => 'bool', + ], + 'OCICollection' => [ + 'free' => 'bool', + 'append' => 'bool', + 'getElem' => 'string|float|null|false', + 'assign' => 'bool', + 'assignElem' => 'bool', + 'size' => 'int|false', + 'max' => 'int|false', + 'trim' => 'bool', + ], + 'PDO' => [ + 'beginTransaction' => 'bool', + 'commit' => 'bool', + 'errorCode' => '?string', + 'errorInfo' => 'array', + 'exec' => 'int|false', + 'getAttribute' => 'mixed', + 'getAvailableDrivers' => 'array', + 'inTransaction' => 'bool', + 'lastInsertId' => 'string|false', + 'prepare' => 'PDOStatement|false', + 'query' => 'PDOStatement|false', + 'quote' => 'string|false', + 'rollBack' => 'bool', + 'setAttribute' => 'bool', + ], + 'PDOStatement' => [ + 'bindColumn' => 'bool', + 'bindParam' => 'bool', + 'bindValue' => 'bool', + 'closeCursor' => 'bool', + 'columnCount' => 'int', + 'debugDumpParams' => '?bool', + 'errorCode' => '?string', + 'errorInfo' => 'array', + 'execute' => 'bool', + 'fetch' => 'mixed', + 'fetchAll' => 'array', + 'fetchColumn' => 'mixed', + 'fetchObject' => 'object|false', + 'getAttribute' => 'mixed', + 'getColumnMeta' => 'array|false', + 'nextRowset' => 'bool', + 'rowCount' => 'int', + 'setAttribute' => 'bool', + ], + 'PDO_PGSql_Ext' => [ + 'pgsqlCopyFromArray' => 'bool', + 'pgsqlCopyFromFile' => 'bool', + 'pgsqlCopyToArray' => 'array|false', + 'pgsqlCopyToFile' => 'bool', + 'pgsqlLOBCreate' => 'string|false', + 'pgsqlLOBUnlink' => 'bool', + 'pgsqlGetNotify' => 'array|false', + 'pgsqlGetPid' => 'int', + ], + 'PDO_SQLite_Ext' => [ + 'sqliteCreateFunction' => 'bool', + 'sqliteCreateAggregate' => 'bool', + 'sqliteCreateCollation' => 'bool', + ], + 'Phar' => [ + 'addEmptyDir' => 'void', + 'addFile' => 'void', + 'addFromString' => 'void', + 'buildFromDirectory' => 'array', + 'buildFromIterator' => 'array', + 'compressFiles' => 'void', + 'compress' => '?Phar', + 'decompress' => '?Phar', + 'convertToExecutable' => '?Phar', + 'convertToData' => '?PharData', + 'count' => 'int', + 'extractTo' => 'bool', + 'getAlias' => '?string', + 'getPath' => 'string', + 'getMetadata' => 'mixed', + 'getModified' => 'bool', + 'getSignature' => 'array|false', + 'getStub' => 'string', + 'getVersion' => 'string', + 'hasMetadata' => 'bool', + 'isBuffering' => 'bool', + 'isCompressed' => 'int|false', + 'isFileFormat' => 'bool', + 'isWritable' => 'bool', + 'offsetExists' => 'bool', + 'offsetGet' => 'SplFileInfo', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'setAlias' => 'bool', + 'setDefaultStub' => 'bool', + 'setMetadata' => 'void', + 'setSignatureAlgorithm' => 'void', + 'startBuffering' => 'void', + 'stopBuffering' => 'void', + ], + 'PharData' => [ + 'addEmptyDir' => 'void', + 'addFile' => 'void', + 'addFromString' => 'void', + 'buildFromDirectory' => 'array', + 'buildFromIterator' => 'array', + 'compressFiles' => 'void', + 'compress' => '?PharData', + 'decompress' => '?PharData', + 'convertToExecutable' => '?Phar', + 'convertToData' => '?PharData', + 'count' => 'int', + 'extractTo' => 'bool', + 'getAlias' => '?string', + 'getPath' => 'string', + 'getMetadata' => 'mixed', + 'getModified' => 'bool', + 'getSignature' => 'array|false', + 'getStub' => 'string', + 'getVersion' => 'string', + 'hasMetadata' => 'bool', + 'isBuffering' => 'bool', + 'isCompressed' => 'int|false', + 'isFileFormat' => 'bool', + 'isWritable' => 'bool', + 'offsetExists' => 'bool', + 'offsetGet' => 'SplFileInfo', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'setAlias' => 'bool', + 'setDefaultStub' => 'bool', + 'setMetadata' => 'void', + 'setSignatureAlgorithm' => 'void', + 'startBuffering' => 'void', + 'stopBuffering' => 'void', + ], + 'PharFileInfo' => [ + 'chmod' => 'void', + 'getCompressedSize' => 'int', + 'getCRC32' => 'int', + 'getContent' => 'string', + 'getMetadata' => 'mixed', + 'getPharFlags' => 'int', + 'hasMetadata' => 'bool', + 'isCompressed' => 'bool', + 'isCRCChecked' => 'bool', + 'setMetadata' => 'void', + ], + 'Reflection' => [ + 'getModifierNames' => 'array', + ], + 'ReflectionFunctionAbstract' => [ + 'inNamespace' => 'bool', + 'isClosure' => 'bool', + 'isDeprecated' => 'bool', + 'isInternal' => 'bool', + 'isUserDefined' => 'bool', + 'isGenerator' => 'bool', + 'isVariadic' => 'bool', + 'isStatic' => 'bool', + 'getClosureThis' => '?object', + 'getClosureCalledClass' => '?ReflectionClass', + 'getClosureScopeClass' => '?ReflectionClass', + 'getDocComment' => 'string|false', + 'getEndLine' => 'int|false', + 'getExtension' => '?ReflectionExtension', + 'getExtensionName' => 'string|false', + 'getFileName' => 'string|false', + 'getName' => 'string', + 'getNamespaceName' => 'string', + 'getNumberOfParameters' => 'int', + 'getNumberOfRequiredParameters' => 'int', + 'getParameters' => 'array', + 'getShortName' => 'string', + 'getStartLine' => 'int|false', + 'getStaticVariables' => 'array', + 'returnsReference' => 'bool', + 'hasReturnType' => 'bool', + 'getReturnType' => '?ReflectionType', + ], + 'ReflectionFunction' => [ + 'isDisabled' => 'bool', + 'invoke' => 'mixed', + 'invokeArgs' => 'mixed', + 'getClosure' => 'Closure', + 'getExecutingLine' => 'int', + 'getExecutingFile' => 'string', + 'getTrace' => 'array', + 'getFunction' => 'ReflectionFunctionAbstract', + 'getThis' => '?object', + 'getExecutingGenerator' => 'Generator', + ], + 'ReflectionMethod' => [ + 'isPublic' => 'bool', + 'isPrivate' => 'bool', + 'isProtected' => 'bool', + 'isAbstract' => 'bool', + 'isFinal' => 'bool', + 'isConstructor' => 'bool', + 'isDestructor' => 'bool', + 'getClosure' => 'Closure', + 'getModifiers' => 'int', + 'invoke' => 'mixed', + 'invokeArgs' => 'mixed', + 'getDeclaringClass' => 'ReflectionClass', + 'getPrototype' => 'ReflectionMethod', + 'setAccessible' => 'void', + ], + 'ReflectionClass' => [ + 'getName' => 'string', + 'isInternal' => 'bool', + 'isUserDefined' => 'bool', + 'isAnonymous' => 'bool', + 'isInstantiable' => 'bool', + 'isCloneable' => 'bool', + 'getFileName' => 'string|false', + 'getStartLine' => 'int|false', + 'getEndLine' => 'int|false', + 'getDocComment' => 'string|false', + 'getConstructor' => '?ReflectionMethod', + 'hasMethod' => 'bool', + 'getMethod' => 'ReflectionMethod', + 'getMethods' => 'array', + 'hasProperty' => 'bool', + 'getProperty' => 'ReflectionProperty', + 'getProperties' => 'array', + 'hasConstant' => 'bool', + 'getConstants' => 'array', + 'getReflectionConstants' => 'array', + 'getConstant' => 'mixed', + 'getReflectionConstant' => 'ReflectionClassConstant|false', + 'getInterfaces' => 'array', + 'getInterfaceNames' => 'array', + 'isInterface' => 'bool', + 'getTraits' => 'array', + 'getTraitNames' => 'array', + 'getTraitAliases' => 'array', + 'isTrait' => 'bool', + 'isAbstract' => 'bool', + 'isFinal' => 'bool', + 'getModifiers' => 'int', + 'isInstance' => 'bool', + 'newInstance' => 'object', + 'newInstanceWithoutConstructor' => 'object', + 'newInstanceArgs' => '?object', + 'getParentClass' => 'ReflectionClass|false', + 'isSubclassOf' => 'bool', + 'getStaticProperties' => '?array', + 'getStaticPropertyValue' => 'mixed', + 'setStaticPropertyValue' => 'void', + 'getDefaultProperties' => 'array', + 'isIterable' => 'bool', + 'isIterateable' => 'bool', + 'implementsInterface' => 'bool', + 'getExtension' => '?ReflectionExtension', + 'getExtensionName' => 'string|false', + 'inNamespace' => 'bool', + 'getNamespaceName' => 'string', + 'getShortName' => 'string', + ], + 'ReflectionProperty' => [ + 'getName' => 'string', + 'getValue' => 'mixed', + 'setValue' => 'void', + 'isInitialized' => 'bool', + 'isPublic' => 'bool', + 'isPrivate' => 'bool', + 'isProtected' => 'bool', + 'isStatic' => 'bool', + 'isDefault' => 'bool', + 'getModifiers' => 'int', + 'getDeclaringClass' => 'ReflectionClass', + 'getDocComment' => 'string|false', + 'setAccessible' => 'void', + 'getType' => '?ReflectionType', + 'hasType' => 'bool', + 'getDefaultValue' => 'mixed', + ], + 'ReflectionClassConstant' => [ + 'getName' => 'string', + 'getValue' => 'mixed', + 'isPublic' => 'bool', + 'isPrivate' => 'bool', + 'isProtected' => 'bool', + 'getModifiers' => 'int', + 'getDeclaringClass' => 'ReflectionClass', + 'getDocComment' => 'string|false', + ], + 'ReflectionParameter' => [ + 'getName' => 'string', + 'isPassedByReference' => 'bool', + 'canBePassedByValue' => 'bool', + 'getDeclaringFunction' => 'ReflectionFunctionAbstract', + 'getDeclaringClass' => '?ReflectionClass', + 'getClass' => '?ReflectionClass', + 'hasType' => 'bool', + 'getType' => '?ReflectionType', + 'isArray' => 'bool', + 'isCallable' => 'bool', + 'allowsNull' => 'bool', + 'getPosition' => 'int', + 'isOptional' => 'bool', + 'isDefaultValueAvailable' => 'bool', + 'getDefaultValue' => 'mixed', + 'isDefaultValueConstant' => 'bool', + 'getDefaultValueConstantName' => '?string', + 'isVariadic' => 'bool', + ], + 'ReflectionType' => [ + 'allowsNull' => 'bool', + ], + 'ReflectionNamedType' => [ + 'getName' => 'string', + 'isBuiltin' => 'bool', + ], + 'ReflectionExtension' => [ + 'getName' => 'string', + 'getVersion' => '?string', + 'getFunctions' => 'array', + 'getConstants' => 'array', + 'getINIEntries' => 'array', + 'getClasses' => 'array', + 'getClassNames' => 'array', + 'getDependencies' => 'array', + 'info' => 'void', + 'isPersistent' => 'bool', + 'isTemporary' => 'bool', + ], + 'ReflectionZendExtension' => [ + 'getName' => 'string', + 'getVersion' => 'string', + 'getAuthor' => 'string', + 'getURL' => 'string', + 'getCopyright' => 'string', + ], + 'SessionHandlerInterface' => [ + 'open' => 'bool', + 'close' => 'bool', + 'read' => 'string|false', + 'write' => 'bool', + 'destroy' => 'bool', + 'gc' => 'int|false', + ], + 'SessionIdInterface' => [ + 'create_sid' => 'string', + ], + 'SessionUpdateTimestampHandlerInterface' => [ + 'validateId' => 'bool', + 'updateTimestamp' => 'bool', + ], + 'SessionHandler' => [ + 'open' => 'bool', + 'close' => 'bool', + 'read' => 'string|false', + 'write' => 'bool', + 'destroy' => 'bool', + 'gc' => 'int|false', + 'create_sid' => 'string', + ], + 'SimpleXMLElement' => [ + 'xpath' => 'array|null|false', + 'registerXPathNamespace' => 'bool', + 'asXML' => 'string|bool', + 'saveXML' => 'string|bool', + 'getNamespaces' => 'array', + 'getDocNamespaces' => 'array|false', + 'children' => '?SimpleXMLElement', + 'attributes' => '?SimpleXMLElement', + 'addChild' => '?SimpleXMLElement', + 'addAttribute' => 'void', + 'getName' => 'string', + 'count' => 'int', + 'rewind' => 'void', + 'valid' => 'bool', + 'current' => 'SimpleXMLElement', + 'key' => 'string', + 'next' => 'void', + 'hasChildren' => 'bool', + 'getChildren' => '?SimpleXMLElement', + ], + 'SNMP' => [ + 'close' => 'bool', + 'setSecurity' => 'bool', + 'get' => 'mixed', + 'getnext' => 'mixed', + 'walk' => 'array|false', + 'set' => 'bool', + 'getErrno' => 'int', + 'getError' => 'string', + ], + 'SoapServer' => [ + 'fault' => 'void', + 'addSoapHeader' => 'void', + 'setPersistence' => 'void', + 'setClass' => 'void', + 'setObject' => 'void', + 'getFunctions' => 'array', + 'addFunction' => 'void', + 'handle' => 'void', + ], + 'SoapClient' => [ + '__call' => 'mixed', + '__soapCall' => 'mixed', + '__getFunctions' => '?array', + '__getTypes' => '?array', + '__getLastRequest' => '?string', + '__getLastResponse' => '?string', + '__getLastRequestHeaders' => '?string', + '__getLastResponseHeaders' => '?string', + '__doRequest' => '?string', + '__setCookie' => 'void', + '__getCookies' => 'array', + '__setSoapHeaders' => 'bool', + '__setLocation' => '?string', + ], + 'ArrayObject' => [ + 'offsetExists' => 'bool', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'append' => 'void', + 'getArrayCopy' => 'array', + 'count' => 'int', + 'getFlags' => 'int', + 'setFlags' => 'void', + 'asort' => 'bool', + 'ksort' => 'bool', + 'uasort' => 'bool', + 'uksort' => 'bool', + 'natsort' => 'bool', + 'natcasesort' => 'bool', + 'unserialize' => 'void', + 'serialize' => 'string', + '__serialize' => 'array', + '__unserialize' => 'void', + 'getIterator' => 'Iterator', + 'exchangeArray' => 'array', + 'setIteratorClass' => 'void', + 'getIteratorClass' => 'string', + '__debugInfo' => 'array', + ], + 'ArrayIterator' => [ + 'offsetExists' => 'bool', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'append' => 'void', + 'getArrayCopy' => 'array', + 'count' => 'int', + 'getFlags' => 'int', + 'setFlags' => 'void', + 'asort' => 'bool', + 'ksort' => 'bool', + 'uasort' => 'bool', + 'uksort' => 'bool', + 'natsort' => 'bool', + 'natcasesort' => 'bool', + 'unserialize' => 'void', + 'serialize' => 'string', + '__serialize' => 'array', + '__unserialize' => 'void', + 'rewind' => 'void', + 'current' => 'mixed', + 'key' => 'string|int|null', + 'next' => 'void', + 'valid' => 'bool', + 'seek' => 'void', + '__debugInfo' => 'array', + ], + 'RecursiveArrayIterator' => [ + 'hasChildren' => 'bool', + 'getChildren' => '?RecursiveArrayIterator', + ], + 'SplFileInfo' => [ + 'getPath' => 'string', + 'getFilename' => 'string', + 'getExtension' => 'string', + 'getBasename' => 'string', + 'getPathname' => 'string', + 'getPerms' => 'int|false', + 'getInode' => 'int|false', + 'getSize' => 'int|false', + 'getOwner' => 'int|false', + 'getGroup' => 'int|false', + 'getATime' => 'int|false', + 'getMTime' => 'int|false', + 'getCTime' => 'int|false', + 'getType' => 'string|false', + 'isWritable' => 'bool', + 'isReadable' => 'bool', + 'isExecutable' => 'bool', + 'isFile' => 'bool', + 'isDir' => 'bool', + 'isLink' => 'bool', + 'getLinkTarget' => 'string|false', + 'getRealPath' => 'string|false', + 'getFileInfo' => 'SplFileInfo', + 'getPathInfo' => '?SplFileInfo', + 'openFile' => 'SplFileObject', + 'setFileClass' => 'void', + 'setInfoClass' => 'void', + '__debugInfo' => 'array', + '_bad_state_ex' => 'void', + ], + 'DirectoryIterator' => [ + 'getFilename' => 'string', + 'getExtension' => 'string', + 'getBasename' => 'string', + 'isDot' => 'bool', + 'rewind' => 'void', + 'valid' => 'bool', + 'key' => 'mixed', + 'current' => 'mixed', + 'next' => 'void', + 'seek' => 'void', + ], + 'FilesystemIterator' => [ + 'rewind' => 'void', + 'key' => 'string', + 'current' => 'string|SplFileInfo|FilesystemIterator', + 'getFlags' => 'int', + 'setFlags' => 'void', + ], + 'RecursiveDirectoryIterator' => [ + 'hasChildren' => 'bool', + 'getChildren' => 'RecursiveDirectoryIterator', + 'getSubPath' => 'string', + 'getSubPathname' => 'string', + ], + 'GlobIterator' => [ + 'count' => 'int', + ], + 'SplFileObject' => [ + 'rewind' => 'void', + 'eof' => 'bool', + 'valid' => 'bool', + 'fgets' => 'string', + 'fread' => 'string|false', + 'fgetcsv' => 'array|false', + 'fputcsv' => 'int|false', + 'setCsvControl' => 'void', + 'getCsvControl' => 'array', + 'flock' => 'bool', + 'fflush' => 'bool', + 'ftell' => 'int|false', + 'fseek' => 'int', + 'fgetc' => 'string|false', + 'fpassthru' => 'int', + 'fscanf' => 'array|int|null', + 'fwrite' => 'int|false', + 'fstat' => 'array', + 'ftruncate' => 'bool', + 'current' => 'string|array|false', + 'key' => 'int', + 'next' => 'void', + 'setFlags' => 'void', + 'getFlags' => 'int', + 'setMaxLineLen' => 'void', + 'getMaxLineLen' => 'int', + 'hasChildren' => 'false', + 'getChildren' => 'null', + 'seek' => 'void', + 'getCurrentLine' => 'string', + ], + 'SplDoublyLinkedList' => [ + 'add' => 'void', + 'pop' => 'mixed', + 'shift' => 'mixed', + 'push' => 'void', + 'unshift' => 'void', + 'top' => 'mixed', + 'bottom' => 'mixed', + '__debugInfo' => 'array', + 'count' => 'int', + 'isEmpty' => 'bool', + 'setIteratorMode' => 'int', + 'getIteratorMode' => 'int', + 'offsetExists' => 'bool', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'rewind' => 'void', + 'current' => 'mixed', + 'key' => 'int', + 'prev' => 'void', + 'next' => 'void', + 'valid' => 'bool', + 'unserialize' => 'void', + 'serialize' => 'string', + '__serialize' => 'array', + '__unserialize' => 'void', + ], + 'SplQueue' => [ + 'enqueue' => 'void', + 'dequeue' => 'mixed', + ], + 'SplFixedArray' => [ + '__wakeup' => 'void', + 'count' => 'int', + 'toArray' => 'array', + 'fromArray' => 'SplFixedArray', + 'getSize' => 'int', + 'offsetExists' => 'bool', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + ], + 'SplPriorityQueue' => [ + 'compare' => 'int', + 'setExtractFlags' => 'int', + 'top' => 'mixed', + 'extract' => 'mixed', + 'count' => 'int', + 'isEmpty' => 'bool', + 'rewind' => 'void', + 'current' => 'mixed', + 'key' => 'int', + 'next' => 'void', + 'valid' => 'bool', + 'isCorrupted' => 'bool', + 'getExtractFlags' => 'int', + '__debugInfo' => 'array', + ], + 'SplHeap' => [ + 'extract' => 'mixed', + 'insert' => 'bool', + 'top' => 'mixed', + 'count' => 'int', + 'isEmpty' => 'bool', + 'rewind' => 'void', + 'current' => 'mixed', + 'key' => 'int', + 'next' => 'void', + 'valid' => 'bool', + 'recoverFromCorruption' => 'bool', + 'compare' => 'int', + 'isCorrupted' => 'bool', + '__debugInfo' => 'array', + ], + 'SplMinHeap' => [ + 'compare' => 'int', + ], + 'SplMaxHeap' => [ + 'compare' => 'int', + ], + 'EmptyIterator' => [ + 'current' => 'never', + 'next' => 'void', + 'key' => 'never', + 'valid' => 'false', + 'rewind' => 'void', + ], + 'CallbackFilterIterator' => [ + 'accept' => 'bool', + ], + 'RecursiveCallbackFilterIterator' => [ + 'hasChildren' => 'bool', + 'getChildren' => 'RecursiveCallbackFilterIterator', + ], + 'RecursiveIterator' => [ + 'hasChildren' => 'bool', + 'getChildren' => '?RecursiveIterator', + ], + 'RecursiveIteratorIterator' => [ + 'rewind' => 'void', + 'valid' => 'bool', + 'key' => 'mixed', + 'current' => 'mixed', + 'next' => 'void', + 'getDepth' => 'int', + 'getSubIterator' => '?RecursiveIterator', + 'getInnerIterator' => 'RecursiveIterator', + 'beginIteration' => 'void', + 'endIteration' => 'void', + 'callHasChildren' => 'bool', + 'callGetChildren' => '?RecursiveIterator', + 'beginChildren' => 'void', + 'endChildren' => 'void', + 'nextElement' => 'void', + 'setMaxDepth' => 'void', + 'getMaxDepth' => 'int|false', + ], + 'OuterIterator' => [ + 'getInnerIterator' => '?Iterator', + ], + 'IteratorIterator' => [ + 'getInnerIterator' => '?Iterator', + 'rewind' => 'void', + 'valid' => 'bool', + 'key' => 'mixed', + 'current' => 'mixed', + 'next' => 'void', + ], + 'FilterIterator' => [ + 'accept' => 'bool', + 'rewind' => 'void', + 'next' => 'void', + ], + 'RecursiveFilterIterator' => [ + 'hasChildren' => 'bool', + 'getChildren' => '?RecursiveFilterIterator', + ], + 'ParentIterator' => [ + 'accept' => 'bool', + ], + 'SeekableIterator' => [ + 'seek' => 'void', + ], + 'LimitIterator' => [ + 'rewind' => 'void', + 'valid' => 'bool', + 'next' => 'void', + 'seek' => 'int', + 'getPosition' => 'int', + ], + 'CachingIterator' => [ + 'rewind' => 'void', + 'valid' => 'bool', + 'next' => 'void', + 'hasNext' => 'bool', + 'getFlags' => 'int', + 'setFlags' => 'void', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'offsetExists' => 'bool', + 'getCache' => 'array', + 'count' => 'int', + ], + 'RecursiveCachingIterator' => [ + 'hasChildren' => 'bool', + 'getChildren' => '?RecursiveCachingIterator', + ], + 'NoRewindIterator' => [ + 'rewind' => 'void', + 'valid' => 'bool', + 'key' => 'mixed', + 'current' => 'mixed', + 'next' => 'void', + ], + 'AppendIterator' => [ + 'append' => 'void', + 'rewind' => 'void', + 'valid' => 'bool', + 'current' => 'mixed', + 'next' => 'void', + 'getIteratorIndex' => '?int', + 'getArrayIterator' => 'ArrayIterator', + ], + 'InfiniteIterator' => [ + 'next' => 'void', + ], + 'RegexIterator' => [ + 'accept' => 'bool', + 'getMode' => 'int', + 'setMode' => 'void', + 'getFlags' => 'int', + 'setFlags' => 'void', + 'getRegex' => 'string', + 'getPregFlags' => 'int', + 'setPregFlags' => 'void', + ], + 'RecursiveRegexIterator' => [ + 'accept' => 'bool', + 'hasChildren' => 'bool', + 'getChildren' => 'RecursiveRegexIterator', + ], + 'RecursiveTreeIterator' => [ + 'key' => 'mixed', + 'current' => 'mixed', + 'getPrefix' => 'string', + 'setPostfix' => 'void', + 'setPrefixPart' => 'void', + 'getEntry' => 'string', + 'getPostfix' => 'string', + ], + 'SplObserver' => [ + 'update' => 'void', + ], + 'SplSubject' => [ + 'attach' => 'void', + 'detach' => 'void', + 'notify' => 'void', + ], + 'SplObjectStorage' => [ + 'attach' => 'void', + 'detach' => 'void', + 'contains' => 'bool', + 'addAll' => 'int', + 'removeAll' => 'int', + 'removeAllExcept' => 'int', + 'getInfo' => 'mixed', + 'setInfo' => 'void', + 'count' => 'int', + 'rewind' => 'void', + 'valid' => 'bool', + 'key' => 'int', + 'current' => 'object', + 'next' => 'void', + 'unserialize' => 'void', + 'serialize' => 'string', + 'offsetExists' => 'bool', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + 'getHash' => 'string', + '__serialize' => 'array', + '__unserialize' => 'void', + '__debugInfo' => 'array', + ], + 'MultipleIterator' => [ + 'getFlags' => 'int', + 'setFlags' => 'void', + 'attachIterator' => 'void', + 'detachIterator' => 'void', + 'containsIterator' => 'bool', + 'countIterators' => 'int', + 'rewind' => 'void', + 'valid' => 'bool', + 'key' => 'array', + 'current' => 'array', + 'next' => 'void', + '__debugInfo' => 'array', + ], + 'SQLite3' => [ + 'open' => 'void', + 'version' => 'array', + 'lastInsertRowID' => 'int', + 'lastErrorCode' => 'int', + 'lastExtendedErrorCode' => 'int', + 'lastErrorMsg' => 'string', + 'changes' => 'int', + 'busyTimeout' => 'bool', + 'loadExtension' => 'bool', + 'backup' => 'bool', + 'escapeString' => 'string', + 'prepare' => 'SQLite3Stmt|false', + 'exec' => 'bool', + 'query' => 'SQLite3Result|false', + 'querySingle' => 'mixed', + 'createFunction' => 'bool', + 'createAggregate' => 'bool', + 'createCollation' => 'bool', + 'enableExceptions' => 'bool', + 'enableExtendedResultCodes' => 'bool', + 'setAuthorizer' => 'bool', + ], + 'SQLite3Stmt' => [ + 'bindParam' => 'bool', + 'bindValue' => 'bool', + 'clear' => 'bool', + 'close' => 'bool', + 'execute' => 'SQLite3Result|false', + 'getSQL' => 'string|false', + 'paramCount' => 'int', + 'readOnly' => 'bool', + 'reset' => 'bool', + ], + 'SQLite3Result' => [ + 'numColumns' => 'int', + 'columnName' => 'string|false', + 'columnType' => 'int|false', + 'fetchArray' => 'array|false', + 'reset' => 'bool', + ], + 'Directory' => [ + 'close' => 'void', + 'rewind' => 'void', + 'read' => 'string|false', + ], + 'php_user_filter' => [ + 'filter' => 'int', + 'onCreate' => 'bool', + 'onClose' => 'void', + ], + 'tidy' => [ + 'getOpt' => 'string|int|bool', + 'cleanRepair' => 'bool', + 'parseFile' => 'bool', + 'parseString' => 'bool', + 'repairString' => 'string|false', + 'repairFile' => 'string|false', + 'diagnose' => 'bool', + 'getRelease' => 'string', + 'getConfig' => 'array', + 'getStatus' => 'int', + 'getHtmlVer' => 'int', + 'getOptDoc' => 'string|false', + 'isXhtml' => 'bool', + 'isXml' => 'bool', + 'root' => '?tidyNode', + 'head' => '?tidyNode', + 'html' => '?tidyNode', + 'body' => '?tidyNode', + ], + 'XMLReader' => [ + 'getAttribute' => '?string', + 'getAttributeNo' => '?string', + 'getAttributeNs' => '?string', + 'getParserProperty' => 'bool', + 'isValid' => 'bool', + 'lookupNamespace' => '?string', + 'moveToAttribute' => 'bool', + 'moveToAttributeNo' => 'bool', + 'moveToAttributeNs' => 'bool', + 'moveToElement' => 'bool', + 'moveToFirstAttribute' => 'bool', + 'moveToNextAttribute' => 'bool', + 'read' => 'bool', + 'next' => 'bool', + 'readInnerXml' => 'string', + 'readOuterXml' => 'string', + 'readString' => 'string', + 'setSchema' => 'bool', + 'setParserProperty' => 'bool', + 'setRelaxNGSchema' => 'bool', + 'setRelaxNGSchemaSource' => 'bool', + 'expand' => 'DOMNode|false', + ], + 'XMLWriter' => [ + 'openUri' => 'bool', + 'openMemory' => 'bool', + 'setIndent' => 'bool', + 'setIndentString' => 'bool', + 'startComment' => 'bool', + 'endComment' => 'bool', + 'startAttribute' => 'bool', + 'endAttribute' => 'bool', + 'writeAttribute' => 'bool', + 'startAttributeNs' => 'bool', + 'writeAttributeNs' => 'bool', + 'startElement' => 'bool', + 'endElement' => 'bool', + 'fullEndElement' => 'bool', + 'startElementNs' => 'bool', + 'writeElement' => 'bool', + 'writeElementNs' => 'bool', + 'startPi' => 'bool', + 'endPi' => 'bool', + 'writePi' => 'bool', + 'startCdata' => 'bool', + 'endCdata' => 'bool', + 'writeCdata' => 'bool', + 'text' => 'bool', + 'writeRaw' => 'bool', + 'startDocument' => 'bool', + 'endDocument' => 'bool', + 'writeComment' => 'bool', + 'startDtd' => 'bool', + 'endDtd' => 'bool', + 'writeDtd' => 'bool', + 'startDtdElement' => 'bool', + 'endDtdElement' => 'bool', + 'writeDtdElement' => 'bool', + 'startDtdAttlist' => 'bool', + 'endDtdAttlist' => 'bool', + 'writeDtdAttlist' => 'bool', + 'startDtdEntity' => 'bool', + 'endDtdEntity' => 'bool', + 'writeDtdEntity' => 'bool', + 'outputMemory' => 'string', + 'flush' => 'string|int', + ], + 'XSLTProcessor' => [ + 'importStylesheet' => 'bool', + 'transformToDoc' => 'DOMDocument|false', + 'transformToUri' => 'int', + 'transformToXml' => 'string|null|false', + 'setParameter' => 'bool', + 'getParameter' => 'string|false', + 'removeParameter' => 'bool', + 'hasExsltSupport' => 'bool', + 'registerPHPFunctions' => 'void', + 'setSecurityPrefs' => 'int', + 'getSecurityPrefs' => 'int', + ], + 'ZipArchive' => [ + 'open' => 'bool|int', + 'setPassword' => 'bool', + 'close' => 'bool', + 'count' => 'int', + 'getStatusString' => 'string', + 'addEmptyDir' => 'bool', + 'addFromString' => 'bool', + 'addFile' => 'bool', + 'replaceFile' => 'bool', + 'addGlob' => 'array|false', + 'addPattern' => 'array|false', + 'renameIndex' => 'bool', + 'renameName' => 'bool', + 'setArchiveComment' => 'bool', + 'getArchiveComment' => 'string|false', + 'setCommentIndex' => 'bool', + 'setCommentName' => 'bool', + 'setMtimeIndex' => 'bool', + 'setMtimeName' => 'bool', + 'getCommentIndex' => 'string|false', + 'getCommentName' => 'string|false', + 'deleteIndex' => 'bool', + 'deleteName' => 'bool', + 'statName' => 'array|false', + 'statIndex' => 'array|false', + 'locateName' => 'int|false', + 'getNameIndex' => 'string|false', + 'unchangeArchive' => 'bool', + 'unchangeAll' => 'bool', + 'unchangeIndex' => 'bool', + 'unchangeName' => 'bool', + 'extractTo' => 'bool', + 'getFromName' => 'string|false', + 'getFromIndex' => 'string|false', + 'setExternalAttributesName' => 'bool', + 'setExternalAttributesIndex' => 'bool', + 'getExternalAttributesName' => 'bool', + 'getExternalAttributesIndex' => 'bool', + 'setCompressionName' => 'bool', + 'setCompressionIndex' => 'bool', + 'setEncryptionName' => 'bool', + 'setEncryptionIndex' => 'bool', + 'registerProgressCallback' => 'bool', + 'registerCancelCallback' => 'bool', + ], + 'Exception' => [ + '__wakeup' => 'void', + ], + 'Error' => [ + '__wakeup' => 'void', + ], + 'IteratorAggregate' => [ + 'getIterator' => 'Traversable', + ], + 'Iterator' => [ + 'current' => 'mixed', + 'next' => 'void', + 'key' => 'mixed', + 'valid' => 'bool', + 'rewind' => 'void', + ], + 'ArrayAccess' => [ + 'offsetExists' => 'bool', + 'offsetGet' => 'mixed', + 'offsetSet' => 'void', + 'offsetUnset' => 'void', + ], + 'Countable' => [ + 'count' => 'int', + ], + ]; +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/LICENSE b/php/libraries/composer/vendor/symfony/error-handler/LICENSE new file mode 100644 index 0000000..f37c76b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2019-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/error-handler/README.md b/php/libraries/composer/vendor/symfony/error-handler/README.md new file mode 100644 index 0000000..12c0bfa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/README.md @@ -0,0 +1,44 @@ +ErrorHandler Component +====================== + +The ErrorHandler component provides tools to manage errors and ease debugging PHP code. + +Getting Started +--------------- + +``` +$ composer require symfony/error-handler +``` + +```php +use Symfony\Component\ErrorHandler\Debug; +use Symfony\Component\ErrorHandler\ErrorHandler; +use Symfony\Component\ErrorHandler\DebugClassLoader; + +Debug::enable(); + +// or enable only one feature +//ErrorHandler::register(); +//DebugClassLoader::enable(); + +// If you want a custom generic template when debug is not enabled +// HtmlErrorRenderer::setTemplate('/path/to/custom/error.html.php'); + +$data = ErrorHandler::call(static function () use ($filename, $datetimeFormat) { + // if any code executed inside this anonymous function fails, a PHP exception + // will be thrown, even if the code uses the '@' PHP silence operator + $data = json_decode(file_get_contents($filename), true); + $data['read_at'] = date($datetimeFormat); + file_put_contents($filename, json_encode($data)); + + return $data; +}); +``` + +Resources +--------- + + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/error.css b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/error.css new file mode 100644 index 0000000..332d818 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/error.css @@ -0,0 +1,4 @@ +body { background-color: #fff; color: #222; font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; } +.container { margin: 30px; max-width: 600px; } +h1 { color: #dc3545; font-size: 24px; } +h2 { font-size: 18px; } diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/exception.css b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/exception.css new file mode 100644 index 0000000..7cb3206 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/exception.css @@ -0,0 +1,252 @@ +/* This file is based on WebProfilerBundle/Resources/views/Profiler/profiler.css.twig. + If you make any change in this file, verify the same change is needed in the other file. */ +:root { + --font-sans-serif: Helvetica, Arial, sans-serif; + --page-background: #f9f9f9; + --color-text: #222; + /* when updating any of these colors, do the same in toolbar.css.twig */ + --color-success: #4f805d; + --color-warning: #a46a1f; + --color-error: #b0413e; + --color-muted: #999; + --tab-background: #fff; + --tab-color: #444; + --tab-active-background: #666; + --tab-active-color: #fafafa; + --tab-disabled-background: #f5f5f5; + --tab-disabled-color: #999; + --metric-value-background: #fff; + --metric-value-color: inherit; + --metric-unit-color: #999; + --metric-label-background: #e0e0e0; + --metric-label-color: inherit; + --table-border: #e0e0e0; + --table-background: #fff; + --table-header: #e0e0e0; + --trace-selected-background: #F7E5A1; + --tree-active-background: #F7E5A1; + --exception-title-color: var(--base-2); + --shadow: 0px 0px 1px rgba(128, 128, 128, .2); + --border: 1px solid #e0e0e0; + --background-error: var(--color-error); + --highlight-comment: #969896; + --highlight-default: #222222; + --highlight-keyword: #a71d5d; + --highlight-string: #183691; + --base-0: #fff; + --base-1: #f5f5f5; + --base-2: #e0e0e0; + --base-3: #ccc; + --base-4: #666; + --base-5: #444; + --base-6: #222; +} + +.theme-dark { + --page-background: #36393e; + --color-text: #e0e0e0; + --color-muted: #777; + --color-error: #d43934; + --tab-background: #555; + --tab-color: #ccc; + --tab-active-background: #888; + --tab-active-color: #fafafa; + --tab-disabled-background: var(--page-background); + --tab-disabled-color: #777; + --metric-value-background: #555; + --metric-value-color: inherit; + --metric-unit-color: #999; + --metric-label-background: #777; + --metric-label-color: #e0e0e0; + --trace-selected-background: #71663acc; + --table-border: #444; + --table-background: #333; + --table-header: #555; + --info-background: rgba(79, 148, 195, 0.5); + --tree-active-background: var(--metric-label-background); + --exception-title-color: var(--base-2); + --shadow: 0px 0px 1px rgba(32, 32, 32, .2); + --border: 1px solid #666; + --background-error: #b0413e; + --highlight-comment: #dedede; + --highlight-default: var(--base-6); + --highlight-keyword: #ff413c; + --highlight-string: #70a6fd; + --base-0: #2e3136; + --base-1: #444; + --base-2: #666; + --base-3: #666; + --base-4: #666; + --base-5: #e0e0e0; + --base-6: #f5f5f5; + --card-label-background: var(--tab-active-background); + --card-label-color: var(--tab-active-color); +} + +html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0} + +html { + /* always display the vertical scrollbar to avoid jumps when toggling contents */ + overflow-y: scroll; +} +body { background-color: var(--page-background); color: var(--base-6); font: 14px/1.4 Helvetica, Arial, sans-serif; padding-bottom: 45px; } + +a { cursor: pointer; text-decoration: none; } +a:hover { text-decoration: underline; } +abbr[title] { border-bottom: none; cursor: help; text-decoration: none; } + +code, pre { font: 13px/1.5 Consolas, Monaco, Menlo, "Ubuntu Mono", "Liberation Mono", monospace; } + +table, tr, th, td { background: var(--base-0); border-collapse: collapse; vertical-align: top; } +table { background: var(--base-0); border: var(--border); box-shadow: 0px 0px 1px rgba(128, 128, 128, .2); margin: 1em 0; width: 100%; } +table th, table td { border: solid var(--base-2); border-width: 1px 0; padding: 8px 10px; } +table th { background-color: var(--base-2); font-weight: bold; text-align: left; } + +.m-t-5 { margin-top: 5px; } +.hidden-xs-down { display: none; } +.block { display: block; } +.full-width { width: 100%; } +.hidden { display: none; } +.prewrap { white-space: pre-wrap; } +.nowrap { white-space: nowrap; } +.newline { display: block; } +.break-long-words { word-wrap: break-word; overflow-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; min-width: 0; } +.text-small { font-size: 12px !important; } +.text-muted { color: #999; } +.text-bold { font-weight: bold; } +.empty { border: 4px dashed var(--base-2); color: #999; margin: 1em 0; padding: .5em 2em; } + +.status-success { background: rgba(94, 151, 110, 0.3); } +.status-warning { background: rgba(240, 181, 24, 0.3); } +.status-error { background: rgba(176, 65, 62, 0.2); } +.status-success td, .status-warning td, .status-error td { background: transparent; } +tr.status-error td, tr.status-warning td { border-bottom: 1px solid var(--base-2); border-top: 1px solid var(--base-2); } +.status-warning .colored { color: #A46A1F; } +.status-error .colored { color: var(--color-error); } + +.sf-toggle { cursor: pointer; position: relative; } +.sf-toggle-content { -moz-transition: display .25s ease; -webkit-transition: display .25s ease; transition: display .25s ease; } +.sf-toggle-content.sf-toggle-hidden { display: none; } +.sf-toggle-content.sf-toggle-visible { display: block; } +thead.sf-toggle-content.sf-toggle-visible, tbody.sf-toggle-content.sf-toggle-visible { display: table-row-group; } +.sf-toggle-off .icon-close, .sf-toggle-on .icon-open { display: none; } +.sf-toggle-off .icon-open, .sf-toggle-on .icon-close { display: block; } + +.tab-navigation { margin: 0 0 1em 0; padding: 0; } +.tab-navigation li { background: var(--tab-background); border: 1px solid var(--table-border); color: var(--tab-color); cursor: pointer; display: inline-block; font-size: 16px; margin: 0 0 0 -1px; padding: .5em .75em; z-index: 1; } +.tab-navigation li .badge { background-color: var(--base-1); color: var(--base-4); display: inline-block; font-size: 14px; font-weight: bold; margin-left: 8px; min-width: 10px; padding: 1px 6px; text-align: center; white-space: nowrap; } +.tab-navigation li.disabled { background: var(--tab-disabled-background); color: var(--tab-disabled-color); } +.tab-navigation li.active { background: var(--tab-active-background); color: var(--tab-active-color); z-index: 1100; } +.tab-navigation li.active .badge { background-color: var(--base-5); color: var(--base-2); } +.tab-content > *:first-child { margin-top: 0; } +.tab-navigation li .badge.status-warning { background: var(--color-warning); color: #FFF; } +.tab-navigation li .badge.status-error { background: var(--background-error); color: #FFF; } +.sf-tabs .tab:not(:first-child) { display: none; } + +[data-filters] { position: relative; } +[data-filtered] { cursor: pointer; } +[data-filtered]:after { content: '\00a0\25BE'; } +[data-filtered]:hover .filter-list li { display: inline-flex; } +[class*="filter-hidden-"] { display: none; } +.filter-list { position: absolute; border: var(--border); box-shadow: var(--shadow); margin: 0; padding: 0; display: flex; flex-direction: column; } +.filter-list :after { content: ''; } +.filter-list li { + background: var(--tab-disabled-background); + border-bottom: var(--border); + color: var(--tab-disabled-color); + display: none; + list-style: none; + margin: 0; + padding: 5px 10px; + text-align: left; + font-weight: normal; +} +.filter-list li.active { + background: var(--tab-background); + color: var(--tab-color); +} +.filter-list li.last-active { + background: var(--tab-active-background); + color: var(--tab-active-color); +} + +.filter-list-level li { cursor: s-resize; } +.filter-list-level li.active { cursor: n-resize; } +.filter-list-level li.last-active { cursor: default; } +.filter-list-level li.last-active:before { content: '\2714\00a0'; } +.filter-list-choice li:before { content: '\2714\00a0'; color: transparent; } +.filter-list-choice li.active:before { color: unset; } + +.container { max-width: 1024px; margin: 0 auto; padding: 0 15px; } +.container::after { content: ""; display: table; clear: both; } + +header { background-color: #222; color: rgba(255, 255, 255, 0.75); font-size: 13px; height: 33px; line-height: 33px; padding: 0; } +header .container { display: flex; justify-content: space-between; } +.logo { flex: 1; font-size: 13px; font-weight: normal; margin: 0; padding: 0; } +.logo svg { height: 18px; width: 18px; opacity: .8; vertical-align: -5px; } + +.help-link { margin-left: 15px; } +.help-link a { color: inherit; } +.help-link .icon svg { height: 15px; width: 15px; opacity: .7; vertical-align: -2px; } +.help-link a:hover { color: #EEE; text-decoration: none; } +.help-link a:hover svg { opacity: .9; } + +.exception-summary { background: var(--background-error); border-bottom: 2px solid rgba(0, 0, 0, 0.1); border-top: 1px solid rgba(0, 0, 0, .3); flex: 0 0 auto; margin-bottom: 15px; } +.exception-metadata { background: rgba(0, 0, 0, 0.1); padding: 7px 0; } +.exception-metadata .container { display: flex; flex-direction: row; justify-content: space-between; } +.exception-metadata h2, .exception-metadata h2 > a { color: rgba(255, 255, 255, 0.8); font-size: 13px; font-weight: 400; margin: 0; } +.exception-http small { font-size: 13px; opacity: .7; } +.exception-hierarchy { flex: 1; } +.exception-hierarchy .icon { margin: 0 3px; opacity: .7; } +.exception-hierarchy .icon svg { height: 13px; width: 13px; vertical-align: -2px; } + +.exception-without-message .exception-message-wrapper { display: none; } +.exception-message-wrapper .container { display: flex; align-items: flex-start; min-height: 70px; padding: 10px 15px 8px; } +.exception-message { flex-grow: 1; } +.exception-message, .exception-message a { color: #FFF; font-size: 21px; font-weight: 400; margin: 0; } +.exception-message.long { font-size: 18px; } +.exception-message a { border-bottom: 1px solid rgba(255, 255, 255, 0.5); font-size: inherit; text-decoration: none; } +.exception-message a:hover { border-bottom-color: #ffffff; } + +.exception-illustration { flex-basis: 111px; flex-shrink: 0; height: 66px; margin-left: 15px; opacity: .7; } + +.trace + .trace { margin-top: 30px; } +.trace-head { background-color: var(--base-2); padding: 10px; position: relative; } +.trace-head .trace-class { color: var(--base-6); font-size: 18px; font-weight: bold; line-height: 1.3; margin: 0; position: relative; } +.trace-head .trace-namespace { color: #999; display: block; font-size: 13px; } +.trace-head .icon { position: absolute; right: 0; top: 0; } +.trace-head .icon svg { fill: var(--base-5); height: 24px; width: 24px; } + +.trace-details { background: var(--base-0); border: var(--border); box-shadow: 0px 0px 1px rgba(128, 128, 128, .2); margin: 1em 0; table-layout: fixed; } + +.trace-message { font-size: 14px; font-weight: normal; margin: .5em 0 0; } + +.trace-line { position: relative; padding-top: 8px; padding-bottom: 8px; } +.trace-line + .trace-line { border-top: var(--border); } +.trace-line:hover { background: var(--base-1); } +.trace-line a { color: var(--base-6); } +.trace-line .icon { opacity: .4; position: absolute; left: 10px; } +.trace-line .icon svg { fill: var(--base-5); height: 16px; width: 16px; } +.trace-line .icon.icon-copy { left: auto; top: auto; padding-left: 5px; display: none } +.trace-line:hover .icon.icon-copy:not(.hidden) { display: inline-block } +.trace-line-header { padding-left: 36px; padding-right: 10px; } + +.trace-file-path, .trace-file-path a { color: var(--base-6); font-size: 13px; } +.trace-class { color: var(--color-error); } +.trace-type { padding: 0 2px; } +.trace-method { color: var(--color-error); font-weight: bold; } +.trace-arguments { color: #777; font-weight: normal; padding-left: 2px; } + +.trace-code { background: var(--base-0); font-size: 12px; margin: 10px 10px 2px 10px; padding: 10px; overflow-x: auto; white-space: nowrap; } +.trace-code ol { margin: 0; float: left; } +.trace-code li { color: #969896; margin: 0; padding-left: 10px; float: left; width: 100%; } +.trace-code li + li { margin-top: 5px; } +.trace-code li.selected { background: var(--trace-selected-background); margin-top: 2px; } +.trace-code li code { color: var(--base-6); white-space: nowrap; } + +.trace-as-text .stacktrace { line-height: 1.8; margin: 0 0 15px; white-space: pre-wrap; } + +@media (min-width: 575px) { + .hidden-xs-down { display: initial; } + .help-link { margin-left: 30px; } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/exception_full.css b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/exception_full.css new file mode 100644 index 0000000..fa77cb3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/css/exception_full.css @@ -0,0 +1,128 @@ +.sf-reset .traces { + padding-bottom: 14px; +} +.sf-reset .traces li { + font-size: 12px; + color: #868686; + padding: 5px 4px; + list-style-type: decimal; + margin-left: 20px; +} +.sf-reset #logs .traces li.error { + font-style: normal; + color: #AA3333; + background: #f9ecec; +} +.sf-reset #logs .traces li.warning { + font-style: normal; + background: #ffcc00; +} +/* fix for Opera not liking empty <li> */ +.sf-reset .traces li:after { + content: "\00A0"; +} +.sf-reset .trace { + border: 1px solid #D3D3D3; + padding: 10px; + overflow: auto; + margin: 10px 0 20px; +} +.sf-reset .block-exception { + -moz-border-radius: 16px; + -webkit-border-radius: 16px; + border-radius: 16px; + margin-bottom: 20px; + background-color: #f6f6f6; + border: 1px solid #dfdfdf; + padding: 30px 28px; + word-wrap: break-word; + overflow: hidden; +} +.sf-reset .block-exception div { + color: #313131; + font-size: 10px; +} +.sf-reset .block-exception-detected .illustration-exception, +.sf-reset .block-exception-detected .text-exception { + float: left; +} +.sf-reset .block-exception-detected .illustration-exception { + width: 152px; +} +.sf-reset .block-exception-detected .text-exception { + width: 670px; + padding: 30px 44px 24px 46px; + position: relative; +} +.sf-reset .text-exception .open-quote, +.sf-reset .text-exception .close-quote { + font-family: Arial, Helvetica, sans-serif; + position: absolute; + color: #C9C9C9; + font-size: 8em; +} +.sf-reset .open-quote { + top: 0; + left: 0; +} +.sf-reset .close-quote { + bottom: -0.5em; + right: 50px; +} +.sf-reset .block-exception p { + font-family: Arial, Helvetica, sans-serif; +} +.sf-reset .block-exception p a, +.sf-reset .block-exception p a:hover { + color: #565656; +} +.sf-reset .logs h2 { + float: left; + width: 654px; +} +.sf-reset .error-count, .sf-reset .support { + float: right; + width: 170px; + text-align: right; +} +.sf-reset .error-count span { + display: inline-block; + background-color: #aacd4e; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 4px; + color: white; + margin-right: 2px; + font-size: 11px; + font-weight: bold; +} + +.sf-reset .support a { + display: inline-block; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 4px; + color: #000000; + margin-right: 2px; + font-size: 11px; + font-weight: bold; +} + +.sf-reset .toggle { + vertical-align: middle; +} +.sf-reset .linked ul, +.sf-reset .linked li { + display: inline; +} +.sf-reset #output-content { + color: #000; + font-size: 12px; +} +.sf-reset #traces-text pre { + white-space: pre; + font-size: 12px; + font-family: monospace; +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/chevron-right.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/chevron-right.svg new file mode 100644 index 0000000..6837aff --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/chevron-right.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path fill="#FFF" d="M1363 877l-742 742q-19 19-45 19t-45-19l-166-166q-19-19-19-45t19-45l531-531-531-531q-19-19-19-45t19-45L531 45q19-19 45-19t45 19l742 742q19 19 19 45t-19 45z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/favicon.png.base64 b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/favicon.png.base64 new file mode 100644 index 0000000..fb076ed --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/favicon.png.base64 @@ -0,0 +1 @@ +data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAADVUlEQVRIx82XX0jTURTHLYPyqZdefQx66CEo80+aYpoIkqzUikz6Z5klQoWUWYRIJYEUGpQ+lIr9U5dOTLdCtkmWZis3rbnC5fw/neYW002307mX/cZvP3/7o1PwwOdh95x7vnf39zvnd29AgBer2xO6DclAXiMqZAqxIiNIN/IYSUS2BPhjmGATchUxI+ADWiRhpWK7HKuHFVBFdmU5YvnI4grFGCaReF/EBH4KsZlGgj2JBTuCYBWRIYF8YoEOJ6wBt/gEs7mBbyOjQXruPLSdOgPCiEiPSUUHDoL8Ug5IUo9B/d5wrt+G7OAKNrODPuVdB6vRCIzN6SdBlpW9RIgk/1FeAXabzRlrUPVCS/JhbmwudztnGeeH9AyXBIwtmM3wLinZJZHifjHw2V+NBoRh+9ixQrbgbnaSIcl7cGea6hoXQbNe7za241oeO5Z0p42M4BV2EqP2D50wo+6HzvwC6C4sApNOR8cmOrtcnhtj2kYRyC9eBvXzKrBZrXSs72kFd1t3MoKVbMekQkEnSNKOO8fac3LpmK6l1TlGtsxmsdKFsecPYgwxst0cwROMYDXboSotg0WLBRqjY51jLYcENElXwW2XJKPydvoI2GN9T8rBtrAArYIUruBJXkFheCQYlCpQP6uk5dAQFQNaUROMSGVQFxLmkoQsxDJrhLbTZ+nvVsERME9MgPJRKV/58AsyomTSzE813WLFvWK++qI0xSfQl8k8Pg46sYRuv5t6dS+4RqxDwaa4BGjYH+NTQvKScIp9+YL/hoZh3jDtLRHtt2C3g6bmhX+CpsFBWg7ilDSPgj0lD2ncr5ev/BP8VvyAJhqVyZeUhPOrEhEFxgEtjft846Z/guQTNT89Q5P9flMLoth4F7808wKtWWKzAwNQHxrh/1vaid2F+XpYTSbQf1XA2McOmOpROnvpvMEA4tSjq1cW0sws2gCYxswY6TKkvzYnJq1NHZLnRU4BX+4U0uburvusu8Kv8iHY7qefkM4IFngJHEOUXmLEPgiGsI8YnlZILit3vSSLRTQe/MPIZva5pshNIEmyFQlCvruJKXPkCEfmePzkphXHdzZNQdoRI9KPlBAxlj/I8U97ERPS5bjGbWDFbEdqHVe5caTBeZZx2H/IMvzeN15yoQAAAABJRU5ErkJggg== diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-book.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-book.svg new file mode 100644 index 0000000..498a74f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-book.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path fill="#FFF" d="M1703 478q40 57 18 129l-275 906q-19 64-76.5 107.5T1247 1664H324q-77 0-148.5-53.5T76 1479q-24-67-2-127 0-4 3-27t4-37q1-8-3-21.5t-3-19.5q2-11 8-21t16.5-23.5T116 1179q23-38 45-91.5t30-91.5q3-10 .5-30t-.5-28q3-11 17-28t17-23q21-36 42-92t25-90q1-9-2.5-32t.5-28q4-13 22-30.5t22-22.5q19-26 42.5-84.5T404 411q1-8-3-25.5t-2-26.5q2-8 9-18t18-23 17-21q8-12 16.5-30.5t15-35 16-36 19.5-32 26.5-23.5 36-11.5T620 134l-1 3q38-9 51-9h761q74 0 114 56t18 130l-274 906q-36 119-71.5 153.5T1089 1408H220q-27 0-38 15-11 16-1 43 24 70 144 70h923q29 0 56-15.5t35-41.5l300-987q7-22 5-57 38 15 59 43zm-1064 2q-4 13 2 22.5t20 9.5h608q13 0 25.5-9.5T1311 480l21-64q4-13-2-22.5t-20-9.5H702q-13 0-25.5 9.5T660 416zm-83 256q-4 13 2 22.5t20 9.5h608q13 0 25.5-9.5T1228 736l21-64q4-13-2-22.5t-20-9.5H619q-13 0-25.5 9.5T577 672z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-copy.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-copy.svg new file mode 100644 index 0000000..844a4f9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-copy.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg> \ No newline at end of file diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-minus-square-o.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-minus-square-o.svg new file mode 100644 index 0000000..be534ad --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-minus-square-o.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1344 800v64q0 14-9 23t-23 9H480q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h832q14 0 23 9t9 23zm128 448V416q0-66-47-113t-113-47H480q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113zm128-832v832q0 119-84.5 203.5T1312 1536H480q-119 0-203.5-84.5T192 1248V416q0-119 84.5-203.5T480 128h832q119 0 203.5 84.5T1600 416z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-minus-square.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-minus-square.svg new file mode 100644 index 0000000..471c274 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-minus-square.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1408 960V832q0-26-19-45t-45-19H448q-26 0-45 19t-19 45v128q0 26 19 45t45 19h896q26 0 45-19t19-45zm256-544v960q0 119-84.5 203.5T1376 1664H416q-119 0-203.5-84.5T128 1376V416q0-119 84.5-203.5T416 128h960q119 0 203.5 84.5T1664 416z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-plus-square-o.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-plus-square-o.svg new file mode 100644 index 0000000..b2593a9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-plus-square-o.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1344 800v64q0 14-9 23t-23 9H960v352q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23V896H480q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h352V416q0-14 9-23t23-9h64q14 0 23 9t9 23v352h352q14 0 23 9t9 23zm128 448V416q0-66-47-113t-113-47H480q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113zm128-832v832q0 119-84.5 203.5T1312 1536H480q-119 0-203.5-84.5T192 1248V416q0-119 84.5-203.5T480 128h832q119 0 203.5 84.5T1600 416z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-plus-square.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-plus-square.svg new file mode 100644 index 0000000..2f5c3b3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-plus-square.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1408 960V832q0-26-19-45t-45-19h-320V448q0-26-19-45t-45-19H832q-26 0-45 19t-19 45v320H448q-26 0-45 19t-19 45v128q0 26 19 45t45 19h320v320q0 26 19 45t45 19h128q26 0 45-19t19-45v-320h320q26 0 45-19t19-45zm256-544v960q0 119-84.5 203.5T1376 1664H416q-119 0-203.5-84.5T128 1376V416q0-119 84.5-203.5T416 128h960q119 0 203.5 84.5T1664 416z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-support.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-support.svg new file mode 100644 index 0000000..03fd8e7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/icon-support.svg @@ -0,0 +1 @@ +<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path fill="#FFF" d="M896 0q182 0 348 71t286 191 191 286 71 348-71 348-191 286-286 191-348 71-348-71-286-191-191-286T0 896t71-348 191-286T548 71 896 0zm0 128q-190 0-361 90l194 194q82-28 167-28t167 28l194-194q-171-90-361-90zM218 1257l194-194q-28-82-28-167t28-167L218 535q-90 171-90 361t90 361zm678 407q190 0 361-90l-194-194q-82 28-167 28t-167-28l-194 194q171 90 361 90zm0-384q159 0 271.5-112.5T1280 896t-112.5-271.5T896 512 624.5 624.5 512 896t112.5 271.5T896 1280zm484-217l194 194q90-171 90-361t-90-361l-194 194q28 82 28 167t-28 167z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/symfony-ghost.svg.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/symfony-ghost.svg.php new file mode 100644 index 0000000..4b2f9c1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/symfony-ghost.svg.php @@ -0,0 +1 @@ +<svg viewBox="0 0 136 81" xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.4"><path d="M92.4 20.4a23.2 23.2 0 0 1 9 1.9 23.7 23.7 0 0 1 5.2 3 24.3 24.3 0 0 1 3.4 3.4 24.8 24.8 0 0 1 5 9.4c.5 1.7.8 3.4 1 5.2v14.5h.4l.5.2a7.4 7.4 0 0 0 2.5.2l.2-.2.6-.8.8-1.3-.2-.1a5.5 5.5 0 0 1-.8-.3 5.6 5.6 0 0 1-2.3-1.8 5.7 5.7 0 0 1-.9-1.6 6.5 6.5 0 0 1-.2-2.8 7.3 7.3 0 0 1 .5-2l.3-.3.8-.9.3-.3c.2-.2.5-.3.8-.3H120.7c.2 0 .3-.1.4 0h.4l.2.1.3.2.2-.4.3-.4.1-.1 1.2-1 .3-.2.4-.1.4-.1h.3l1.5.1.4.1.8.5.1.2 1 1.1v.2H129.4l.4-.2 1.4-.5h1.1c.3 0 .7.2 1 .4.2 0 .3.2.5.3l.2.2.5.3.4.6.1.3.4 1.4.1.4v.6a7.8 7.8 0 0 1-.1.6 9.9 9.9 0 0 1-.8 2.4 7.8 7.8 0 0 1-3 3.3 6.4 6.4 0 0 1-1 .5 6.1 6.1 0 0 1-.6.2l-.7.1h-.1a23.4 23.4 0 0 1-.2 1.7 14.3 14.3 0 0 1-.6 2.1l-.8 2a9.2 9.2 0 0 1-.4.6l-.7 1a9.1 9.1 0 0 1-2.3 2.2c-.9.5-2 .6-3 .7l-1.4.1h-.5l-.4.1a15.8 15.8 0 0 1-2.8-.1v4.2a9.7 9.7 0 0 1-.7 3.5 9.6 9.6 0 0 1-1.7 2.8 9.3 9.3 0 0 1-3 2.3 9 9 0 0 1-5.4.7 9 9 0 0 1-3-1 9.4 9.4 0 0 1-2.7-2.5 10 10 0 0 1-1 1.2 9.3 9.3 0 0 1-2 1.3 9 9 0 0 1-2.4 1 9 9 0 0 1-6.5-1.1A9.4 9.4 0 0 1 85 77V77a10.9 10.9 0 0 1-.6.6 9.3 9.3 0 0 1-2.7 2 9 9 0 0 1-6 .8 9 9 0 0 1-2.4-1 9.3 9.3 0 0 1-2.3-1.7 9.6 9.6 0 0 1-1.8-2.8 9.7 9.7 0 0 1-.8-3.7v-4a18.5 18.5 0 0 1-2.9.2l-1.2-.1c-1.9-.3-3.7-1-5.1-2.2a8.2 8.2 0 0 1-1.1-1 10.2 10.2 0 0 1-.9-1.2 15.3 15.3 0 0 1-.7-1.3 20.8 20.8 0 0 1-1.9-6.2v-.2a6.5 6.5 0 0 1-1-.3 6.1 6.1 0 0 1-.6-.3 6.6 6.6 0 0 1-.9-.6 8.2 8.2 0 0 1-2.7-3.7 10 10 0 0 1-.3-1 10.3 10.3 0 0 1-.3-1.9V47v-.4l.1-.4.6-1.4.1-.2a2 2 0 0 1 .8-.8l.3-.2.3-.2a3.2 3.2 0 0 1 1.8-.5h.4l.3.2 1.4.6.2.2.4.3.3.4.7-.7.2-.2.4-.2.6-.2h2.1l.4.2.4.2.3.2.8 1 .2-.1h.1v-.1H63l1.1.1h.3l.8.5.3.4.7 1 .2.3.1.5a11 11 0 0 1 .2 1.5c0 .8 0 1.6-.3 2.3a6 6 0 0 1-.5 1.2 5.5 5.5 0 0 1-3.3 2.5 12.3 12.3 0 0 0 1.4 3h.1l.2.1 1 .2h1.5l.5-.2H67.8l.5-.2h.1V44v-.4a26.7 26.7 0 0 1 .3-2.3 24.7 24.7 0 0 1 5.7-12.5 24.2 24.2 0 0 1 3.5-3.3 23.7 23.7 0 0 1 4.9-3 23.2 23.2 0 0 1 5.6-1.7 23.7 23.7 0 0 1 4-.3zm-.3 2a21.2 21.2 0 0 0-8 1.7 21.6 21.6 0 0 0-4.8 2.7 22.2 22.2 0 0 0-3.2 3 22.7 22.7 0 0 0-5 9.2 23.4 23.4 0 0 0-.7 4.9v15.7l-.5.1a34.3 34.3 0 0 1-1.5.3h-.2l-.4.1h-.4l-.9.2a10 10 0 0 1-1.9 0c-.5 0-1-.2-1.5-.4a1.8 1.8 0 0 1-.3-.2 2 2 0 0 1-.3-.3 5.2 5.2 0 0 1-.1-.2 9 9 0 0 1-.6-.9 13.8 13.8 0 0 1-1-2 14.3 14.3 0 0 1-.6-2 14 14 0 0 1-.1-.8v-.2h.3a12.8 12.8 0 0 0 1.4-.2 4.4 4.4 0 0 0 .3 0 3.6 3.6 0 0 0 1.1-.7 3.4 3.4 0 0 0 1.2-1.7l.2-1.2a5.1 5.1 0 0 0 0-.8 7.2 7.2 0 0 0-.1-.8l-.7-1-1.2-.2-1 .7-.1 1.3a5 5 0 0 1 .1.4v.6a1 1 0 0 1 0 .3c-.1.3-.4.4-.7.5l-1.2.4v-.7A9.9 9.9 0 0 1 60 49l.3-.6v-.2l.1-.1v-1.6l-1-1.2h-1.5l-1 1.1v.4a5.3 5.3 0 0 0-.2.6 5.5 5.5 0 0 0 0 .5c0 .7 0 1.4.3 2 0 .4.2.8.4 1.2L57 51a9.5 9.5 0 0 1-1.1-.5h-.2a2 2 0 0 1-.4-.3c-.4-.4-.5-1-.6-1.6a5.6 5.6 0 0 1 0-.5v-.5-.5l-.6-1.5-1.4-.6-.9.3s-.2 0-.3.2a2 2 0 0 1-.1 0l-.6 1.4v.7a8.5 8.5 0 0 0 .5 2c.4 1.1 1 2.1 2 2.8a4.7 4.7 0 0 0 2.1.9h1a22.8 22.8 0 0 0 .1 1 18.1 18.1 0 0 0 .8 3.8 18.2 18.2 0 0 0 1.6 3.7l1 1.3c1 1 2.3 1.6 3.7 2a11.7 11.7 0 0 0 4.8 0h.4l.5-.2.5-.1.6-.2v6.6a8 8 0 0 0 .1 1.3 7.5 7.5 0 0 0 2.4 4.3 7.2 7.2 0 0 0 2.3 1.3 7 7 0 0 0 7-1.1 7.5 7.5 0 0 0 2-2.6A7.7 7.7 0 0 0 85 72V71a8.2 8.2 0 0 0 .2 1.3c0 .7.3 1.4.6 2a7.5 7.5 0 0 0 1.7 2.3 7.3 7.3 0 0 0 2.2 1.4 7.1 7.1 0 0 0 4.6.2 7.2 7.2 0 0 0 2.4-1.2 7.5 7.5 0 0 0 2.1-2.7 7.8 7.8 0 0 0 .7-2.4V71a9.3 9.3 0 0 0 .1.6 7.6 7.6 0 0 0 .6 2.5 7.5 7.5 0 0 0 2.4 3 7.1 7.1 0 0 0 7 .8 7.3 7.3 0 0 0 2.3-1.5 7.5 7.5 0 0 0 1.6-2.3 7.6 7.6 0 0 0 .5-2l.1-1.1v-6.7l.4.1a12.2 12.2 0 0 0 2 .5 11.1 11.1 0 0 0 2.5 0h.8l1.2-.1a9.5 9.5 0 0 0 1.4-.2l.9-.3a3.5 3.5 0 0 0 .6-.4l1.2-1.4a12.2 12.2 0 0 0 .8-1.2c0-.3.2-.5.3-.7a15.9 15.9 0 0 0 .7-2l.3-1.6v-1.3l.2-.9V54.6a15.5 15.5 0 0 0 1.8 0 4.5 4.5 0 0 0 1.4-.5 5.7 5.7 0 0 0 2.5-3.2 7.6 7.6 0 0 0 .4-1.5v-.3l-.4-1.4a5.2 5.2 0 0 1-.2-.1l-.4-.4a3.8 3.8 0 0 0-.2 0 1.4 1.4 0 0 0-.5-.2l-1.4.4-.7 1.3v.7a5.7 5.7 0 0 1-.1.8l-.7 1.4a1.9 1.9 0 0 1-.5.3h-.3a9.6 9.6 0 0 1-.8.3 8.8 8.8 0 0 1-.6 0l.2-.4.2-.5.2-.3v-.4l.1-.2V50l.1-1 .1-.6v-.6a4.8 4.8 0 0 0 0-.8v-.2l-1-1.1-1.5-.2-1.1 1-.2 1.4v.1l.2.4.2.3v.4l.1 1.1v.3l.1.5v.8a9.6 9.6 0 0 1-.8-.3l-.2-.1h-.3l-.8-.1h-.2a1.6 1.6 0 0 1-.2-.2.9.9 0 0 1-.2-.2 1 1 0 0 1-.1-.5l.2-.9v-1.2l-.9-.8h-1.2l-.8.9v.3a4.8 4.8 0 0 0-.3 2l.3.9a3.5 3.5 0 0 0 1.2 1.6l1 .5.8.2 1.4.1h.4l.2.1a12.1 12.1 0 0 1-1 2.6 13.2 13.2 0 0 1-.8 1.5 9.5 9.5 0 0 1-1 1.2l-.2.3a1.7 1.7 0 0 1-.4.3 2.4 2.4 0 0 1-.7.2h-2.5a7.8 7.8 0 0 1-.6-.2l-.7-.2h-.2a14.8 14.8 0 0 1-.6-.2 23.4 23.4 0 0 1-.4-.1l-.4-.1-.3-.1V43.9a34.6 34.6 0 0 0 0-.6 23.6 23.6 0 0 0-.4-3 22.7 22.7 0 0 0-1.5-4.7 22.6 22.6 0 0 0-4.6-6.7 21.9 21.9 0 0 0-6.9-4.7 21.2 21.2 0 0 0-8.1-1.8H92zm9.1 33.7l.3.1a1 1 0 0 1 .6.8v.4a8.4 8.4 0 0 1 0 .5 8.8 8.8 0 0 1-1.6 4.2l-1 1.3A10 10 0 0 1 95 66c-1.3.3-2.7.4-4 .3a10.4 10.4 0 0 1-2.7-.8 10 10 0 0 1-3.6-2.5 9.3 9.3 0 0 1-.8-1 9 9 0 0 1-.7-1.2 8.6 8.6 0 0 1-.8-3.4V57a1 1 0 0 1 .3-.6 1 1 0 0 1 1.3-.2 1 1 0 0 1 .4.8v.4a6.5 6.5 0 0 0 .5 2.2 7 7 0 0 0 2.1 2.8l1 .6c2.6 1.6 6 1.6 8.5 0a8 8 0 0 0 1.1-.6 7.6 7.6 0 0 0 1.2-1.2 7 7 0 0 0 1-1.7 6.5 6.5 0 0 0 .4-2.5 1 1 0 0 1 .7-1h.4zM30.7 43.7c-15.5 1-28.5-6-30.1-16.4C-1.2 15.7 11.6 4 29 1.3 46.6-1.7 62.3 5.5 64 17.1c1.6 10.4-8.7 21-23.7 25a31.2 31.2 0 0 0 0 .9v.3a19 19 0 0 0 .1 1l.1.4.1.9a4.7 4.7 0 0 0 .5 1l.7 1a9.2 9.2 0 0 0 1.2 1l1.5.8.6.8-.7.6-1.1.3a11.2 11.2 0 0 1-2.6.4 8.6 8.6 0 0 1-3-.5 8.5 8.5 0 0 1-1-.4 11.2 11.2 0 0 1-1.8-1.2 13.3 13.3 0 0 1-1-1 18 18 0 0 1-.7-.6l-.4-.4a23.4 23.4 0 0 1-1.3-1.8l-.1-.1-.3-.5V45l-.3-.6v-.7zM83.1 36c3.6 0 6.5 3.2 6.5 7.1 0 4-3 7.2-6.5 7.2S76.7 47 76.7 43 79.6 36 83 36zm18 0c3.6 0 6.5 3.2 6.5 7.1 0 4-2.9 7.2-6.4 7.2S94.7 47 94.7 43s3-7.1 6.5-7.1zm-18 6.1c2 0 3.5 1.6 3.5 3.6S85 49.2 83 49.2s-3.4-1.6-3.4-3.6S81.2 42 83 42zm17.9 0c1.9 0 3.4 1.6 3.4 3.6s-1.5 3.6-3.4 3.6c-2 0-3.5-1.6-3.5-3.6S99.1 42 101 42zM17 28c-.3 1.6-1.8 5-5.2 5.8-2.5.6-4.1-.8-4.5-2.6-.4-1.9.7-3.5 2.1-4.5A3.5 3.5 0 0 1 8 24.6c-.4-2 .8-3.7 3.2-4.2 1.9-.5 3.1.2 3.4 1.5.3 1.1-.5 2.2-1.8 2.5-.9.3-1.6 0-1.7-.6a1.4 1.4 0 0 1 0-.7s.3.2 1 0c.7-.1 1-.7.9-1.2-.2-.6-1-.8-1.8-.6-1 .2-2 1-1.7 2.6.3 1 .9 1.6 1.5 1.8l.7-.2c1-.2 1.5 0 1.6.5 0 .4-.2 1-1.2 1.2a3.3 3.3 0 0 1-1.5 0c-.9.7-1.6 1.9-1.3 3.2.3 1.3 1.3 2.2 3 1.8 2.5-.7 3.8-3.7 4.2-5-.3-.5-.6-1-.7-1.6-.1-.5.1-1 .9-1.2.4 0 .7.2.8.8a2.8 2.8 0 0 1 0 1l.7 1c.6-2 1.4-4 1.7-4 .6-.2 1.5.6 1.5.6-.8.7-1.7 2.4-2.3 4.2.8.6 1.6 1 2.1 1 .5-.1.8-.6 1-1.2-.3-2.2 1-4.3 2.3-4.6.7-.2 1.3.2 1.4.8.1.5 0 1.3-.9 1.7-.2-1-.6-1.3-1-1.3-.4.1-.7 1.4-.4 2.8.2 1 .7 1.5 1.3 1.4.8-.2 1.3-1.2 1.7-2.1-.3-2.1.9-4.2 2.2-4.5.7-.2 1.2.1 1.4 1 .4 1.4-1 2.8-2.2 3.4.3.7.7 1 1.3.9 1-.3 1.6-1.5 2-2.5l-.5-3v-.3s1.6-.3 1.8.6v.1c.2-.6.7-1.2 1.3-1.4.8-.1 1.5.6 1.7 1.6.5 2.2-.5 4.4-1.8 4.7H33a31.9 31.9 0 0 0 1 5.2c-.4.1-1.8.4-2-.4l-.5-5.6c-.5 1-1.3 2.2-2.5 2.4-1 .3-1.6-.3-2-1.1-.5 1-1.3 2.1-2.4 2.4-.8.2-1.5-.1-2-1-.3.8-.9 1.5-1.5 1.7-.7.1-1.5-.3-2.4-1-.3.8-.4 1.6-.4 2.2 0 0-.7 0-.8-.4-.1-.5 0-1.5.3-2.7a10.3 10.3 0 0 1-.7-.8zm38.2-17.8l.2.9c.5 1.9.4 4.4.8 6.4 0 .6-.4 3-1.4 3.3-.2 0-.3 0-.4-.4-.1-.7 0-1.6-.3-2.6-.2-1.1-.8-1.6-1.5-1.5-.8.2-1.3 1-1.6 2l-.1-.5c-.2-1-1.8-.6-1.8-.6a6.2 6.2 0 0 1 .4 1.3l.2 1c-.2.5-.6 1-1.2 1l-.2.1a7 7 0 0 0-.1-.8c-.3-1.1-1-2-1.6-1.8a.7.7 0 0 0-.4.3c-1.3.3-2.4 2-2.1 3.9-.2.9-.6 1.7-1 1.9-.5 0-.8-.5-1.1-1.8l-.1-1.2a4 4 0 0 0 0-1.7c0-.4-.4-.7-.8-.6-.7.2-.9 1.7-.5 3.8-.2 1-.6 2-1.3 2-.4.2-.8-.2-1-1l-.2-3c1.2-.5 2-1 1.8-1.7-.1-.5-.8-.7-.8-.7s0 .7-1 1.2l-.2-1.4c-.1-.6-.4-1-1.7-.6l.4 1 .2 1.5h-1v.8c0 .3.4.3 1 .2 0 1.3 0 2.7.2 3.6.3 1.4 1.2 2 2 1.7 1-.2 1.6-1.3 2-2.3.3 1.2 1 2 1.9 1.7.7-.2 1.2-1.1 1.6-2.2.4.8 1.1 1.1 2 1 1.2-.4 1.7-1.6 1.8-2.8h.2c.6-.2 1-.6 1.3-1 0 .8 0 1.5.2 2.1.1.5.3.7.6.6.5-.1 1-.9 1-.9a4 4 0 0 1-.3-1c-.3-1.3.3-3.6 1-3.7.2 0 .3.2.5.7v.8l.2 1.5v.7c.2.7.7 1.3 1.5 1 1.3-.2 2-2.6 2.1-3.9.3.2.6.2 1 .1-.6-2.2 0-6.1-.3-7.9-.1-.4-1-.5-1.7-.5h-.4zm-21.5 12c.4 0 .7.3 1 1.1.2 1.3-.3 2.6-.9 2.8-.2 0-.7 0-1-1.2v-.4c0-1.3.4-2 1-2.2zm-5.2 1c.3 0 .6.2.6.5.2.6-.3 1.3-1.2 2-.3-1.4.1-2.3.6-2.5zm18-.4c-.5.2-1-.4-1.2-1.2-.2-1 0-2.1.7-2.5v.5c.2.7.6 1.5 1.3 1.9 0 .7-.2 1.2-.7 1.3zm10-1.6c0 .5.4.7 1 .6.8-.2 1-1 .8-1.6 0-.5-.4-1-1-.8-.5.1-1 .9-.8 1.8zm-14.3-5.5c0-.4-.5-.7-1-.5-.8.2-1 1-.9 1.5.2.6.5 1 1 .8.5 0 1.1-1 1-1.8z" fill="#fff" fill-opacity=".6"/><?= $this->addElementToGhost(); ?></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/symfony-logo.svg b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/symfony-logo.svg new file mode 100644 index 0000000..f10824a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/images/symfony-logo.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#FFF" d="M12 .9C5.8.9.9 5.8.9 12a11 11 0 1 0 22.2 0A11 11 0 0 0 12 .9zm6.5 6c-.6 0-.9-.3-.9-.8 0-.2 0-.4.2-.6l.2-.4c0-.3-.5-.4-.6-.4-1.8.1-2.3 2.5-2.7 4.4l-.2 1c1 .2 1.8 0 2.2-.3.6-.4-.2-.7-.1-1.2.1-.3.5-.5.7-.6.5 0 .7.5.7.9 0 .7-1 1.8-3 1.8l-.6-.1-.6 2.4c-.4 1.6-.8 3.8-2.4 5.7-1.4 1.7-2.9 1.9-3.5 1.9-1.2 0-1.9-.6-2-1.5 0-.8.7-1.3 1.2-1.3.6 0 1.1.5 1.1 1s-.2.6-.4.6c-.1.1-.3.2-.3.4 0 .1.1.3.4.3.5 0 .8-.3 1.1-.5 1.2-.9 1.6-2.7 2.2-5.7l.1-.7.7-3.2c-.8-.6-1.3-1.4-2.4-1.7-.6-.1-1.1.1-1.5.5-.4.5-.2 1.1.2 1.5l.7.6c.7.8 1.2 1.6 1 2.5-.3 1.5-2 2.6-4 1.9-1.8-.6-2-1.8-1.8-2.5.2-.6.6-.7 1.1-.6.5.2.6.7.6 1.2l-.1.3c-.2.1-.3.3-.3.4-.1.4.4.6.7.7.7.3 1.6-.2 1.8-.8a1 1 0 0 0-.4-1.1l-.7-.8c-.4-.4-1.1-1.4-.7-2.6.1-.5.4-.9.7-1.3a4 4 0 0 1 2.8-.6c1.2.4 1.8 1.1 2.6 1.8.5-1.2 1-2.4 1.8-3.5.9-.9 1.9-1.6 3.1-1.7 1.3.2 2.2.7 2.2 1.6 0 .4-.2 1.1-.9 1.1z"/></svg> diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/js/exception.js b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/js/exception.js new file mode 100644 index 0000000..95b8ea1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/assets/js/exception.js @@ -0,0 +1,285 @@ +/* This file is based on WebProfilerBundle/Resources/views/Profiler/base_js.html.twig. + If you make any change in this file, verify the same change is needed in the other file. */ +/*<![CDATA[*/ +(function() { + "use strict"; + + if ('classList' in document.documentElement) { + var hasClass = function (el, cssClass) { return el.classList.contains(cssClass); }; + var removeClass = function(el, cssClass) { el.classList.remove(cssClass); }; + var addClass = function(el, cssClass) { el.classList.add(cssClass); }; + var toggleClass = function(el, cssClass) { el.classList.toggle(cssClass); }; + } else { + var hasClass = function (el, cssClass) { return el.className.match(new RegExp('\\b' + cssClass + '\\b')); }; + var removeClass = function(el, cssClass) { el.className = el.className.replace(new RegExp('\\b' + cssClass + '\\b'), ' '); }; + var addClass = function(el, cssClass) { if (!hasClass(el, cssClass)) { el.className += " " + cssClass; } }; + var toggleClass = function(el, cssClass) { hasClass(el, cssClass) ? removeClass(el, cssClass) : addClass(el, cssClass); }; + } + + var addEventListener; + + var el = document.createElement('div'); + if (!('addEventListener' in el)) { + addEventListener = function (element, eventName, callback) { + element.attachEvent('on' + eventName, callback); + }; + } else { + addEventListener = function (element, eventName, callback) { + element.addEventListener(eventName, callback, false); + }; + } + + if (navigator.clipboard) { + document.querySelectorAll('[data-clipboard-text]').forEach(function(element) { + removeClass(element, 'hidden'); + element.addEventListener('click', function() { + navigator.clipboard.writeText(element.getAttribute('data-clipboard-text')); + }) + }); + } + + (function createTabs() { + var tabGroups = document.querySelectorAll('.sf-tabs:not([data-processed=true])'); + + /* create the tab navigation for each group of tabs */ + for (var i = 0; i < tabGroups.length; i++) { + var tabs = tabGroups[i].querySelectorAll(':scope > .tab'); + var tabNavigation = document.createElement('ul'); + tabNavigation.className = 'tab-navigation'; + + var selectedTabId = 'tab-' + i + '-0'; /* select the first tab by default */ + for (var j = 0; j < tabs.length; j++) { + var tabId = 'tab-' + i + '-' + j; + var tabTitle = tabs[j].querySelector('.tab-title').innerHTML; + + var tabNavigationItem = document.createElement('li'); + tabNavigationItem.setAttribute('data-tab-id', tabId); + if (hasClass(tabs[j], 'active')) { selectedTabId = tabId; } + if (hasClass(tabs[j], 'disabled')) { addClass(tabNavigationItem, 'disabled'); } + tabNavigationItem.innerHTML = tabTitle; + tabNavigation.appendChild(tabNavigationItem); + + var tabContent = tabs[j].querySelector('.tab-content'); + tabContent.parentElement.setAttribute('id', tabId); + } + + tabGroups[i].insertBefore(tabNavigation, tabGroups[i].firstChild); + addClass(document.querySelector('[data-tab-id="' + selectedTabId + '"]'), 'active'); + } + + /* display the active tab and add the 'click' event listeners */ + for (i = 0; i < tabGroups.length; i++) { + tabNavigation = tabGroups[i].querySelectorAll(':scope >.tab-navigation li'); + + for (j = 0; j < tabNavigation.length; j++) { + tabId = tabNavigation[j].getAttribute('data-tab-id'); + document.getElementById(tabId).querySelector('.tab-title').className = 'hidden'; + + if (hasClass(tabNavigation[j], 'active')) { + document.getElementById(tabId).className = 'block'; + } else { + document.getElementById(tabId).className = 'hidden'; + } + + tabNavigation[j].addEventListener('click', function(e) { + var activeTab = e.target || e.srcElement; + + /* needed because when the tab contains HTML contents, user can click */ + /* on any of those elements instead of their parent '<li>' element */ + while (activeTab.tagName.toLowerCase() !== 'li') { + activeTab = activeTab.parentNode; + } + + /* get the full list of tabs through the parent of the active tab element */ + var tabNavigation = activeTab.parentNode.children; + for (var k = 0; k < tabNavigation.length; k++) { + var tabId = tabNavigation[k].getAttribute('data-tab-id'); + document.getElementById(tabId).className = 'hidden'; + removeClass(tabNavigation[k], 'active'); + } + + addClass(activeTab, 'active'); + var activeTabId = activeTab.getAttribute('data-tab-id'); + document.getElementById(activeTabId).className = 'block'; + }); + } + + tabGroups[i].setAttribute('data-processed', 'true'); + } + })(); + + (function createToggles() { + var toggles = document.querySelectorAll('.sf-toggle:not([data-processed=true])'); + + for (var i = 0; i < toggles.length; i++) { + var elementSelector = toggles[i].getAttribute('data-toggle-selector'); + var element = document.querySelector(elementSelector); + + addClass(element, 'sf-toggle-content'); + + if (toggles[i].hasAttribute('data-toggle-initial') && toggles[i].getAttribute('data-toggle-initial') == 'display') { + addClass(toggles[i], 'sf-toggle-on'); + addClass(element, 'sf-toggle-visible'); + } else { + addClass(toggles[i], 'sf-toggle-off'); + addClass(element, 'sf-toggle-hidden'); + } + + addEventListener(toggles[i], 'click', function(e) { + e.preventDefault(); + + if ('' !== window.getSelection().toString()) { + /* Don't do anything on text selection */ + return; + } + + var toggle = e.target || e.srcElement; + + /* needed because when the toggle contains HTML contents, user can click */ + /* on any of those elements instead of their parent '.sf-toggle' element */ + while (!hasClass(toggle, 'sf-toggle')) { + toggle = toggle.parentNode; + } + + var element = document.querySelector(toggle.getAttribute('data-toggle-selector')); + + toggleClass(toggle, 'sf-toggle-on'); + toggleClass(toggle, 'sf-toggle-off'); + toggleClass(element, 'sf-toggle-hidden'); + toggleClass(element, 'sf-toggle-visible'); + + /* the toggle doesn't change its contents when clicking on it */ + if (!toggle.hasAttribute('data-toggle-alt-content')) { + return; + } + + if (!toggle.hasAttribute('data-toggle-original-content')) { + toggle.setAttribute('data-toggle-original-content', toggle.innerHTML); + } + + var currentContent = toggle.innerHTML; + var originalContent = toggle.getAttribute('data-toggle-original-content'); + var altContent = toggle.getAttribute('data-toggle-alt-content'); + toggle.innerHTML = currentContent !== altContent ? altContent : originalContent; + }); + + /* Prevents from disallowing clicks on links inside toggles */ + var toggleLinks = toggles[i].querySelectorAll('a'); + for (var j = 0; j < toggleLinks.length; j++) { + addEventListener(toggleLinks[j], 'click', function(e) { + e.stopPropagation(); + }); + } + + /* Prevents from disallowing clicks on "copy to clipboard" elements inside toggles */ + var copyToClipboardElements = toggles[i].querySelectorAll('span[data-clipboard-text]'); + for (var k = 0; k < copyToClipboardElements.length; k++) { + addEventListener(copyToClipboardElements[k], 'click', function(e) { + e.stopPropagation(); + }); + } + + toggles[i].setAttribute('data-processed', 'true'); + } + })(); + + (function createFilters() { + document.querySelectorAll('[data-filters] [data-filter]').forEach(function (filter) { + var filters = filter.closest('[data-filters]'), + type = 'choice', + name = filter.dataset.filter, + ucName = name.charAt(0).toUpperCase()+name.slice(1), + list = document.createElement('ul'), + values = filters.dataset['filter'+ucName] || filters.querySelectorAll('[data-filter-'+name+']'), + labels = {}, + defaults = null, + indexed = {}, + processed = {}; + if (typeof values === 'string') { + type = 'level'; + labels = values.split(','); + values = values.toLowerCase().split(','); + defaults = values.length - 1; + } + addClass(list, 'filter-list'); + addClass(list, 'filter-list-'+type); + values.forEach(function (value, i) { + if (value instanceof HTMLElement) { + value = value.dataset['filter'+ucName]; + } + if (value in processed) { + return; + } + var option = document.createElement('li'), + label = i in labels ? labels[i] : value, + active = false, + matches; + if ('' === label) { + option.innerHTML = '<em>(none)</em>'; + } else { + option.innerText = label; + } + option.dataset.filter = value; + option.setAttribute('title', 1 === (matches = filters.querySelectorAll('[data-filter-'+name+'="'+value+'"]').length) ? 'Matches 1 row' : 'Matches '+matches+' rows'); + indexed[value] = i; + list.appendChild(option); + addEventListener(option, 'click', function () { + if ('choice' === type) { + filters.querySelectorAll('[data-filter-'+name+']').forEach(function (row) { + if (option.dataset.filter === row.dataset['filter'+ucName]) { + toggleClass(row, 'filter-hidden-'+name); + } + }); + toggleClass(option, 'active'); + } else if ('level' === type) { + if (i === this.parentNode.querySelectorAll('.active').length - 1) { + return; + } + this.parentNode.querySelectorAll('li').forEach(function (currentOption, j) { + if (j <= i) { + addClass(currentOption, 'active'); + if (i === j) { + addClass(currentOption, 'last-active'); + } else { + removeClass(currentOption, 'last-active'); + } + } else { + removeClass(currentOption, 'active'); + removeClass(currentOption, 'last-active'); + } + }); + filters.querySelectorAll('[data-filter-'+name+']').forEach(function (row) { + if (i < indexed[row.dataset['filter'+ucName]]) { + addClass(row, 'filter-hidden-'+name); + } else { + removeClass(row, 'filter-hidden-'+name); + } + }); + } + }); + if ('choice' === type) { + active = null === defaults || 0 <= defaults.indexOf(value); + } else if ('level' === type) { + active = i <= defaults; + if (active && i === defaults) { + addClass(option, 'last-active'); + } + } + if (active) { + addClass(option, 'active'); + } else { + filters.querySelectorAll('[data-filter-'+name+'="'+value+'"]').forEach(function (row) { + toggleClass(row, 'filter-hidden-'+name); + }); + } + processed[value] = true; + }); + + if (1 < list.childNodes.length) { + filter.appendChild(list); + filter.dataset.filtered = ''; + } + }); + })(); +})(); +/*]]>*/ diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/bin/extract-tentative-return-types.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/bin/extract-tentative-return-types.php new file mode 100755 index 0000000..ae2c703 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/bin/extract-tentative-return-types.php @@ -0,0 +1,84 @@ +#!/usr/bin/env php +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if ('cli' !== \PHP_SAPI) { + throw new Exception('This script must be run from the command line.'); +} + +// Run from the root of the php-src repository, this script generates +// a table with all the methods that have a tentative return type. +// +// Usage: find -name *.stub.php | sort | /path/to/extract-tentative-return-types.php > /path/to/TentativeTypes.php + +echo <<<EOPHP +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\ErrorHandler\Internal; + +/** + * This class has been generated by extract-tentative-return-types.php. + * + * @internal + */ +class TentativeTypes +{ + public const RETURN_TYPES = [ + +EOPHP; + +while (false !== $file = fgets(\STDIN)) { + $code = file_get_contents(substr($file, 0, -1)); + + if (!str_contains($code, '@tentative-return-type')) { + continue; + } + + $code = preg_split('{^\s*(?:(?:abstract )?class|interface|trait) ([^\s]++)}m', $code, -1, \PREG_SPLIT_DELIM_CAPTURE); + + if (1 === count($code)) { + continue; + } + + for ($i = 1; null !== $class = $code[$i] ?? null; $i += 2) { + $methods = $code[1 + $i]; + + if (!str_contains($methods, '@tentative-return-type')) { + continue; + } + + echo " '$class' => [\n"; + + preg_replace_callback('{@tentative-return-type.*?[\s]function ([^(]++)[^)]++\)\s*+:\s*+([^\n;\{]++)}s', function ($m) { + $m[2] = str_replace(' ', '', $m[2]); + echo " '$m[1]' => '$m[2]',\n"; + + return ''; + }, $methods); + + echo " ],\n"; + } +} + +echo <<<EOPHP + ]; +} + +EOPHP; diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/bin/patch-type-declarations b/php/libraries/composer/vendor/symfony/error-handler/Resources/bin/patch-type-declarations new file mode 100755 index 0000000..824ef67 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/bin/patch-type-declarations @@ -0,0 +1,98 @@ +#!/usr/bin/env php +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if ('cli' !== \PHP_SAPI) { + throw new Exception('This script must be run from the command line.'); +} + +if (\in_array('-h', $argv) || \in_array('--help', $argv)) { + echo implode(PHP_EOL, [ + ' Patches type declarations based on "@return" PHPDoc and triggers deprecations for', + ' incompatible method declarations.', + '', + ' This assists you to make your package compatible with Symfony 6, but it can be used', + ' for any class/package.', + '', + ' Available configuration via environment variables:', + ' SYMFONY_PATCH_TYPE_DECLARATIONS', + ' An url-encoded string to change the behavior of the script. Available parameters:', + ' - "force": any value enables deprecation notices - can be any of:', + ' - "phpdoc" to patch only docblock annotations', + ' - "2" to add all possible return types', + ' - "1" to add return types but only to tests/final/internal/private methods', + ' - "php": the target version of PHP - e.g. "7.1" doesn\'t generate "object" types', + ' - "deprecations": "1" to trigger a deprecation notice when a child class misses a', + ' return type while the parent declares an "@return" annotation', + '', + ' SYMFONY_PATCH_TYPE_EXCLUDE', + ' A regex matched against the full path to the class - any match will be excluded', + '', + ' Example: "SYMFONY_PATCH_TYPE_DECLARATIONS=php=7.4 ./patch-type-declarations"', + ]); + exit; +} + +if (false === getenv('SYMFONY_PATCH_TYPE_DECLARATIONS')) { + putenv('SYMFONY_PATCH_TYPE_DECLARATIONS=force=2'); + echo 'No SYMFONY_PATCH_TYPE_DECLARATIONS env var set, patching type declarations in all methods (run the command with "-h" for more information).'.PHP_EOL; +} + +if (is_file($autoload = __DIR__.'/../../../../autoload.php')) { + // noop +} elseif (is_file($autoload = __DIR__.'/../../../../../../../autoload.php')) { + // noop +} else { + echo PHP_EOL.' /!\ Cannot find the Composer autoloader, did you forget to run "composer install"?'.PHP_EOL; + exit(1); +} + +if (is_file($phpunitAutoload = dirname($autoload).'/bin/.phpunit/phpunit/vendor/autoload.php')) { + require $phpunitAutoload; +} + +$loader = require $autoload; + +Symfony\Component\ErrorHandler\DebugClassLoader::enable(); + +$deprecations = []; +set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$deprecations) { + if (\E_USER_DEPRECATED !== $type) { + return; + } + + [,,,,, $class,] = explode('"', $msg); + $deprecations[$class][] = $msg; +}); + +$exclude = getenv('SYMFONY_PATCH_TYPE_EXCLUDE') ?: null; +foreach ($loader->getClassMap() as $class => $file) { + if (false !== strpos($file = realpath($file), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) { + continue; + } + + if ($exclude && preg_match($exclude, $file)) { + continue; + } + + class_exists($class); +} + +Symfony\Component\ErrorHandler\DebugClassLoader::checkClasses(); + +foreach ($deprecations as $class => $classDeprecations) { + echo $class.' ('.\count($classDeprecations).')'.PHP_EOL; + echo implode(PHP_EOL, $classDeprecations).PHP_EOL.PHP_EOL; +} + +if ($deprecations && false !== strpos(getenv('SYMFONY_PATCH_TYPE_DECLARATIONS') ?? '', 'force')) { + echo 'These deprecations might be fixed by the patch script, run this again to check for type deprecations.'.PHP_EOL; +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/error.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/error.html.php new file mode 100644 index 0000000..dcd30c2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/error.html.php @@ -0,0 +1,20 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="<?= $this->charset; ?>" /> + <meta name="robots" content="noindex,nofollow,noarchive" /> + <title>An Error Occurred: <?= $statusText; ?> + + + +
+

Oops! An Error Occurred

+

The server returned a " ".

+ +

+ Something is broken. Please let us know what you were doing when this error occurred. + We will fix it as soon as possible. Sorry for any inconvenience caused. +

+
+ + diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/exception.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/exception.html.php new file mode 100644 index 0000000..c3e7a86 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/exception.html.php @@ -0,0 +1,116 @@ +
+ + +
+
+

formatFileFromText(nl2br($exceptionMessage)); ?>

+ +
+ include('assets/images/symfony-ghost.svg.php'); ?> +
+
+
+
+ +
+
+
+ toArray(); + $exceptionWithUserCode = []; + $exceptionAsArrayCount = count($exceptionAsArray); + $last = $exceptionAsArrayCount - 1; + foreach ($exceptionAsArray as $i => $e) { + foreach ($e['trace'] as $trace) { + if ($trace['file'] && false === mb_strpos($trace['file'], '/vendor/') && false === mb_strpos($trace['file'], '/var/cache/') && $i < $last) { + $exceptionWithUserCode[] = $i; + } + } + } + ?> +

+ 1) { ?> + Exceptions + + Exception + +

+ +
+ $e) { + echo $this->include('views/traces.html.php', [ + 'exception' => $e, + 'index' => $i + 1, + 'expand' => in_array($i, $exceptionWithUserCode, true) || ([] === $exceptionWithUserCode && 0 === $i), + ]); + } + ?> +
+
+ + +
+

+ Logs + countErrors()) { ?>countErrors(); ?> +

+ +
+ getLogs()) { ?> + include('views/logs.html.php', ['logs' => $logger->getLogs()]); ?> + +
+

No log messages

+
+ +
+
+ + +
+

+ 1) { ?> + Stack Traces + + Stack Trace + +

+ +
+ $e) { + echo $this->include('views/traces_text.html.php', [ + 'exception' => $e, + 'index' => $i + 1, + 'numExceptions' => $exceptionAsArrayCount, + ]); + } + ?> +
+
+ + +
+

Output content

+ +
+ +
+
+ +
+
diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/exception_full.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/exception_full.html.php new file mode 100644 index 0000000..04f0fd5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/exception_full.html.php @@ -0,0 +1,42 @@ + + + + + + + + <?= $_message; ?> + + + + + + + + +
+
+

include('assets/images/symfony-logo.svg'); ?> Symfony Exception

+ + +
+
+ + + include('views/exception.html.php', $context); ?> + + + + + diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/logs.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/logs.html.php new file mode 100644 index 0000000..ea6e727 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/logs.html.php @@ -0,0 +1,45 @@ + + + + + + + + + + + + = 400) { + $status = 'error'; + } elseif ($log['priority'] >= 300) { + $status = 'warning'; + } else { + $severity = 0; + if (($exception = $log['context']['exception'] ?? null) instanceof \ErrorException || $exception instanceof \Symfony\Component\ErrorHandler\Exception\SilencedErrorContext) { + $severity = $exception->getSeverity(); + } + $status = \E_DEPRECATED === $severity || \E_USER_DEPRECATED === $severity ? 'warning' : 'normal'; + } ?> + data-filter-channel="escape($log['channel']); ?>"> + + + + + + + + +
LevelChannelMessage
+ escape($log['priorityName']); ?> + + + escape($log['channel']); ?> + + formatLogMessage($log['message'], $log['context']); ?> + +
escape(json_encode($log['context'], \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); ?>
+ +
diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/trace.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/trace.html.php new file mode 100644 index 0000000..8dfdb4e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/trace.html.php @@ -0,0 +1,43 @@ +
+ + include('assets/images/icon-minus-square.svg'); ?> + include('assets/images/icon-plus-square.svg'); ?> + + + + abbrClass($trace['class']); ?>(formatArgs($trace['args']); ?>) + + + + getFileLink($trace['file'], $lineNumber); + $filePath = strtr(strip_tags($this->formatFile($trace['file'], $lineNumber)), [' at line '.$lineNumber => '']); + $filePathParts = explode(\DIRECTORY_SEPARATOR, $filePath); + ?> + + in + + + + + + + + (line ) + + + +
+ +
+ fileExcerpt($trace['file'], $trace['line'], 5), [ + '#DD0000' => 'var(--highlight-string)', + '#007700' => 'var(--highlight-keyword)', + '#0000BB' => 'var(--highlight-default)', + '#FF8000' => 'var(--highlight-comment)', + ]); ?> +
+ diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/traces.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/traces.html.php new file mode 100644 index 0000000..4eef59a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/traces.html.php @@ -0,0 +1,51 @@ +
+
+
+
+ include('assets/images/icon-minus-square-o.svg'); ?> + include('assets/images/icon-plus-square-o.svg'); ?> + + +
+ +

+ + + + +

+ + 1) { ?> +

escape($exception['message']); ?>

+ +
+
+ +
+ $trace) { + $isVendorTrace = $trace['file'] && (false !== mb_strpos($trace['file'], '/vendor/') || false !== mb_strpos($trace['file'], '/var/cache/')); + $displayCodeSnippet = $isFirstUserCode && !$isVendorTrace; + if ($displayCodeSnippet) { + $isFirstUserCode = false; + } ?> +
+ include('views/trace.html.php', [ + 'prefix' => $index, + 'i' => $i, + 'trace' => $trace, + 'style' => $isVendorTrace ? 'compact' : ($displayCodeSnippet ? 'expanded' : ''), + ]); ?> +
+ +
+
+
diff --git a/php/libraries/composer/vendor/symfony/error-handler/Resources/views/traces_text.html.php b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/traces_text.html.php new file mode 100644 index 0000000..6b47840 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/Resources/views/traces_text.html.php @@ -0,0 +1,43 @@ + + + + + + + + + + + + +
+
+ 1) { ?> + [/] + + + include('assets/images/icon-minus-square-o.svg'); ?> + include('assets/images/icon-plus-square-o.svg'); ?> +
+
+ +
+escape($exception['class']).":\n";
+                    if ($exception['message']) {
+                        echo $this->escape($exception['message'])."\n";
+                    }
+
+                    foreach ($exception['trace'] as $trace) {
+                        echo "\n  ";
+                        if ($trace['function']) {
+                            echo $this->escape('at '.$trace['class'].$trace['type'].$trace['function']).'('.(isset($trace['args']) ? $this->formatArgsAsText($trace['args']) : '').')';
+                        }
+                        if ($trace['file'] && $trace['line']) {
+                            echo($trace['function'] ? "\n     (" : 'at ').strtr(strip_tags($this->formatFile($trace['file'], $trace['line'])), [' at line '.$trace['line'] => '']).':'.$trace['line'].($trace['function'] ? ')' : '');
+                        }
+                    }
+?>
+                
+ +
diff --git a/php/libraries/composer/vendor/symfony/error-handler/ThrowableUtils.php b/php/libraries/composer/vendor/symfony/error-handler/ThrowableUtils.php new file mode 100644 index 0000000..18d0498 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/ThrowableUtils.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\ErrorHandler; + +use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext; + +/** + * @internal + */ +class ThrowableUtils +{ + /** + * @param SilencedErrorContext|\Throwable + */ + public static function getSeverity($throwable): int + { + if ($throwable instanceof \ErrorException || $throwable instanceof SilencedErrorContext) { + return $throwable->getSeverity(); + } + + if ($throwable instanceof \ParseError) { + return \E_PARSE; + } + + if ($throwable instanceof \TypeError) { + return \E_RECOVERABLE_ERROR; + } + + return \E_ERROR; + } +} diff --git a/php/libraries/composer/vendor/symfony/error-handler/composer.json b/php/libraries/composer/vendor/symfony/error-handler/composer.json new file mode 100644 index 0000000..bc0d88e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/error-handler/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/error-handler", + "type": "library", + "description": "Provides tools to manage errors and ease debugging PHP code", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "psr/log": "^1|^2|^3", + "symfony/var-dumper": "^4.4|^5.0|^6.0" + }, + "require-dev": { + "symfony/http-kernel": "^4.4|^5.0|^6.0", + "symfony/serializer": "^4.4|^5.0|^6.0", + "symfony/deprecation-contracts": "^2.1|^3" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\ErrorHandler\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "bin": [ + "Resources/bin/patch-type-declarations" + ], + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/CHANGELOG.md b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/Event.php b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/Event.php new file mode 100644 index 0000000..2e7f998 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/Event.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\EventDispatcher; + +use Psr\EventDispatcher\StoppableEventInterface; + +/** + * Event is the base class for classes containing event data. + * + * This class contains no event data. It is used by events that do not pass + * state information to an event handler when an event is raised. + * + * You can call the method stopPropagation() to abort the execution of + * further listeners in your event listener. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + * @author Nicolas Grekas + */ +class Event implements StoppableEventInterface +{ + private bool $propagationStopped = false; + + public function isPropagationStopped(): bool + { + return $this->propagationStopped; + } + + /** + * Stops the propagation of the event to further event listeners. + * + * If multiple event listeners are connected to the same event, no + * further event listener will be triggered once any trigger calls + * stopPropagation(). + */ + public function stopPropagation(): void + { + $this->propagationStopped = true; + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/EventDispatcherInterface.php b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/EventDispatcherInterface.php new file mode 100644 index 0000000..610d6ac --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/EventDispatcherInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\EventDispatcher; + +use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface; + +/** + * Allows providing hooks on domain-specific lifecycles by dispatching events. + */ +interface EventDispatcherInterface extends PsrEventDispatcherInterface +{ + /** + * Dispatches an event to all registered listeners. + * + * @template T of object + * + * @param T $event The event to pass to the event handlers/listeners + * @param string|null $eventName The name of the event to dispatch. If not supplied, + * the class of $event should be used instead. + * + * @return T The passed $event MUST be returned + */ + public function dispatch(object $event, string $eventName = null): object; +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/LICENSE b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/LICENSE new file mode 100644 index 0000000..7536cae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/README.md b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/README.md new file mode 100644 index 0000000..332b961 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/README.md @@ -0,0 +1,9 @@ +Symfony EventDispatcher Contracts +================================= + +A set of abstractions extracted out of the Symfony components. + +Can be used to build on semantics that the Symfony components proved useful and +that already have battle tested implementations. + +See https://github.com/symfony/contracts/blob/main/README.md for more information. diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/composer.json b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/composer.json new file mode 100644 index 0000000..3618d53 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/event-dispatcher-contracts", + "type": "library", + "description": "Generic abstractions related to dispatching event", + "keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "autoload": { + "psr-4": { "Symfony\\Contracts\\EventDispatcher\\": "" } + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/Attribute/AsEventListener.php b/php/libraries/composer/vendor/symfony/event-dispatcher/Attribute/AsEventListener.php new file mode 100644 index 0000000..bb931b8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/Attribute/AsEventListener.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Attribute; + +/** + * Service tag to autoconfigure event listeners. + * + * @author Alexander M. Turek + */ +#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +class AsEventListener +{ + public function __construct( + public ?string $event = null, + public ?string $method = null, + public int $priority = 0, + public ?string $dispatcher = null, + ) { + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/CHANGELOG.md b/php/libraries/composer/vendor/symfony/event-dispatcher/CHANGELOG.md new file mode 100644 index 0000000..76b2eab --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/CHANGELOG.md @@ -0,0 +1,96 @@ +CHANGELOG +========= + +6.0 +--- + + * Remove `LegacyEventDispatcherProxy` + +5.4 +--- + + * Allow `#[AsEventListener]` attribute on methods + +5.3 +--- + + * Add `#[AsEventListener]` attribute for declaring listeners on PHP 8 + +5.1.0 +----- + + * The `LegacyEventDispatcherProxy` class has been deprecated. + * Added an optional `dispatcher` attribute to the listener and subscriber tags in `RegisterListenerPass`. + +5.0.0 +----- + + * The signature of the `EventDispatcherInterface::dispatch()` method has been changed to `dispatch($event, string $eventName = null): object`. + * The `Event` class has been removed in favor of `Symfony\Contracts\EventDispatcher\Event`. + * The `TraceableEventDispatcherInterface` has been removed. + * The `WrappedListener` class is now final. + +4.4.0 +----- + + * `AddEventAliasesPass` has been added, allowing applications and bundles to extend the event alias mapping used by `RegisterListenersPass`. + * Made the `event` attribute of the `kernel.event_listener` tag optional for FQCN events. + +4.3.0 +----- + + * The signature of the `EventDispatcherInterface::dispatch()` method should be updated to `dispatch($event, string $eventName = null)`, not doing so is deprecated + * deprecated the `Event` class, use `Symfony\Contracts\EventDispatcher\Event` instead + +4.1.0 +----- + + * added support for invokable event listeners tagged with `kernel.event_listener` by default + * The `TraceableEventDispatcher::getOrphanedEvents()` method has been added. + * The `TraceableEventDispatcherInterface` has been deprecated. + +4.0.0 +----- + + * removed the `ContainerAwareEventDispatcher` class + * added the `reset()` method to the `TraceableEventDispatcherInterface` + +3.4.0 +----- + + * Implementing `TraceableEventDispatcherInterface` without the `reset()` method has been deprecated. + +3.3.0 +----- + + * The ContainerAwareEventDispatcher class has been deprecated. Use EventDispatcher with closure factories instead. + +3.0.0 +----- + + * The method `getListenerPriority($eventName, $listener)` has been added to the + `EventDispatcherInterface`. + * The methods `Event::setDispatcher()`, `Event::getDispatcher()`, `Event::setName()` + and `Event::getName()` have been removed. + The event dispatcher and the event name are passed to the listener call. + +2.5.0 +----- + + * added Debug\TraceableEventDispatcher (originally in HttpKernel) + * changed Debug\TraceableEventDispatcherInterface to extend EventDispatcherInterface + * added RegisterListenersPass (originally in HttpKernel) + +2.1.0 +----- + + * added TraceableEventDispatcherInterface + * added ContainerAwareEventDispatcher + * added a reference to the EventDispatcher on the Event + * added a reference to the Event name on the event + * added fluid interface to the dispatch() method which now returns the Event + object + * added GenericEvent event class + * added the possibility for subscribers to subscribe several times for the + same event + * added ImmutableEventDispatcher diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php b/php/libraries/composer/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php new file mode 100644 index 0000000..5ba83da --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php @@ -0,0 +1,375 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Psr\EventDispatcher\StoppableEventInterface; +use Psr\Log\LoggerInterface; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Contracts\Service\ResetInterface; + +/** + * Collects some data about event listeners. + * + * This event dispatcher delegates the dispatching to another one. + * + * @author Fabien Potencier + */ +class TraceableEventDispatcher implements EventDispatcherInterface, ResetInterface +{ + protected $logger; + protected $stopwatch; + + /** + * @var \SplObjectStorage|null + */ + private ?\SplObjectStorage $callStack = null; + private EventDispatcherInterface $dispatcher; + private array $wrappedListeners = []; + private array $orphanedEvents = []; + private ?RequestStack $requestStack; + private string $currentRequestHash = ''; + + public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, ?LoggerInterface $logger = null, ?RequestStack $requestStack = null) + { + $this->dispatcher = $dispatcher; + $this->stopwatch = $stopwatch; + $this->logger = $logger; + $this->requestStack = $requestStack; + } + + /** + * @return void + */ + public function addListener(string $eventName, callable|array $listener, int $priority = 0) + { + $this->dispatcher->addListener($eventName, $listener, $priority); + } + + /** + * @return void + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + $this->dispatcher->addSubscriber($subscriber); + } + + /** + * @return void + */ + public function removeListener(string $eventName, callable|array $listener) + { + if (isset($this->wrappedListeners[$eventName])) { + foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) { + if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) { + $listener = $wrappedListener; + unset($this->wrappedListeners[$eventName][$index]); + break; + } + } + } + + $this->dispatcher->removeListener($eventName, $listener); + } + + /** + * @return void + */ + public function removeSubscriber(EventSubscriberInterface $subscriber) + { + $this->dispatcher->removeSubscriber($subscriber); + } + + public function getListeners(?string $eventName = null): array + { + return $this->dispatcher->getListeners($eventName); + } + + public function getListenerPriority(string $eventName, callable|array $listener): ?int + { + // we might have wrapped listeners for the event (if called while dispatching) + // in that case get the priority by wrapper + if (isset($this->wrappedListeners[$eventName])) { + foreach ($this->wrappedListeners[$eventName] as $wrappedListener) { + if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) { + return $this->dispatcher->getListenerPriority($eventName, $wrappedListener); + } + } + } + + return $this->dispatcher->getListenerPriority($eventName, $listener); + } + + public function hasListeners(?string $eventName = null): bool + { + return $this->dispatcher->hasListeners($eventName); + } + + public function dispatch(object $event, ?string $eventName = null): object + { + $eventName ??= $event::class; + + $this->callStack ??= new \SplObjectStorage(); + + $currentRequestHash = $this->currentRequestHash = $this->requestStack && ($request = $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : ''; + + if (null !== $this->logger && $event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + $this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName)); + } + + $this->preProcess($eventName); + try { + $this->beforeDispatch($eventName, $event); + try { + $e = $this->stopwatch->start($eventName, 'section'); + try { + $this->dispatcher->dispatch($event, $eventName); + } finally { + if ($e->isStarted()) { + $e->stop(); + } + } + } finally { + $this->afterDispatch($eventName, $event); + } + } finally { + $this->currentRequestHash = $currentRequestHash; + $this->postProcess($eventName); + } + + return $event; + } + + public function getCalledListeners(?Request $request = null): array + { + if (null === $this->callStack) { + return []; + } + + $hash = $request ? spl_object_hash($request) : null; + $called = []; + foreach ($this->callStack as $listener) { + [$eventName, $requestHash] = $this->callStack->getInfo(); + if (null === $hash || $hash === $requestHash) { + $called[] = $listener->getInfo($eventName); + } + } + + return $called; + } + + public function getNotCalledListeners(?Request $request = null): array + { + try { + $allListeners = $this->dispatcher instanceof EventDispatcher ? $this->getListenersWithPriority() : $this->getListenersWithoutPriority(); + } catch (\Exception $e) { + $this->logger?->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]); + + // unable to retrieve the uncalled listeners + return []; + } + + $hash = $request ? spl_object_hash($request) : null; + $calledListeners = []; + + if (null !== $this->callStack) { + foreach ($this->callStack as $calledListener) { + [, $requestHash] = $this->callStack->getInfo(); + + if (null === $hash || $hash === $requestHash) { + $calledListeners[] = $calledListener->getWrappedListener(); + } + } + } + + $notCalled = []; + + foreach ($allListeners as $eventName => $listeners) { + foreach ($listeners as [$listener, $priority]) { + if (!\in_array($listener, $calledListeners, true)) { + if (!$listener instanceof WrappedListener) { + $listener = new WrappedListener($listener, null, $this->stopwatch, $this, $priority); + } + $notCalled[] = $listener->getInfo($eventName); + } + } + } + + uasort($notCalled, $this->sortNotCalledListeners(...)); + + return $notCalled; + } + + public function getOrphanedEvents(?Request $request = null): array + { + if ($request) { + return $this->orphanedEvents[spl_object_hash($request)] ?? []; + } + + if (!$this->orphanedEvents) { + return []; + } + + return array_merge(...array_values($this->orphanedEvents)); + } + + /** + * @return void + */ + public function reset() + { + $this->callStack = null; + $this->orphanedEvents = []; + $this->currentRequestHash = ''; + } + + /** + * Proxies all method calls to the original event dispatcher. + * + * @param string $method The method name + * @param array $arguments The method arguments + */ + public function __call(string $method, array $arguments): mixed + { + return $this->dispatcher->{$method}(...$arguments); + } + + /** + * Called before dispatching the event. + * + * @return void + */ + protected function beforeDispatch(string $eventName, object $event) + { + } + + /** + * Called after dispatching the event. + * + * @return void + */ + protected function afterDispatch(string $eventName, object $event) + { + } + + private function preProcess(string $eventName): void + { + if (!$this->dispatcher->hasListeners($eventName)) { + $this->orphanedEvents[$this->currentRequestHash][] = $eventName; + + return; + } + + foreach ($this->dispatcher->getListeners($eventName) as $listener) { + $priority = $this->getListenerPriority($eventName, $listener); + $wrappedListener = new WrappedListener($listener instanceof WrappedListener ? $listener->getWrappedListener() : $listener, null, $this->stopwatch, $this); + $this->wrappedListeners[$eventName][] = $wrappedListener; + $this->dispatcher->removeListener($eventName, $listener); + $this->dispatcher->addListener($eventName, $wrappedListener, $priority); + $this->callStack->attach($wrappedListener, [$eventName, $this->currentRequestHash]); + } + } + + private function postProcess(string $eventName): void + { + unset($this->wrappedListeners[$eventName]); + $skipped = false; + foreach ($this->dispatcher->getListeners($eventName) as $listener) { + if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch. + continue; + } + // Unwrap listener + $priority = $this->getListenerPriority($eventName, $listener); + $this->dispatcher->removeListener($eventName, $listener); + $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority); + + if (null !== $this->logger) { + $context = ['event' => $eventName, 'listener' => $listener->getPretty()]; + } + + if ($listener->wasCalled()) { + $this->logger?->debug('Notified event "{event}" to listener "{listener}".', $context); + } else { + $this->callStack->detach($listener); + } + + if (null !== $this->logger && $skipped) { + $this->logger->debug('Listener "{listener}" was not called for event "{event}".', $context); + } + + if ($listener->stoppedPropagation()) { + $this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context); + + $skipped = true; + } + } + } + + private function sortNotCalledListeners(array $a, array $b): int + { + if (0 !== $cmp = strcmp($a['event'], $b['event'])) { + return $cmp; + } + + if (\is_int($a['priority']) && !\is_int($b['priority'])) { + return 1; + } + + if (!\is_int($a['priority']) && \is_int($b['priority'])) { + return -1; + } + + if ($a['priority'] === $b['priority']) { + return 0; + } + + if ($a['priority'] > $b['priority']) { + return -1; + } + + return 1; + } + + private function getListenersWithPriority(): array + { + $result = []; + + $allListeners = new \ReflectionProperty(EventDispatcher::class, 'listeners'); + + foreach ($allListeners->getValue($this->dispatcher) as $eventName => $listenersByPriority) { + foreach ($listenersByPriority as $priority => $listeners) { + foreach ($listeners as $listener) { + $result[$eventName][] = [$listener, $priority]; + } + } + } + + return $result; + } + + private function getListenersWithoutPriority(): array + { + $result = []; + + foreach ($this->getListeners() as $eventName => $listeners) { + foreach ($listeners as $listener) { + $result[$eventName][] = [$listener, null]; + } + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/Debug/WrappedListener.php b/php/libraries/composer/vendor/symfony/event-dispatcher/Debug/WrappedListener.php new file mode 100644 index 0000000..4dba883 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/Debug/WrappedListener.php @@ -0,0 +1,144 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Psr\EventDispatcher\StoppableEventInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\VarDumper\Caster\ClassStub; + +/** + * @author Fabien Potencier + */ +final class WrappedListener +{ + private string|array|object $listener; + private ?\Closure $optimizedListener; + private string $name; + private bool $called = false; + private bool $stoppedPropagation = false; + private Stopwatch $stopwatch; + private ?EventDispatcherInterface $dispatcher; + private string $pretty; + private string $callableRef; + private ClassStub|string $stub; + private ?int $priority = null; + private static bool $hasClassStub; + + public function __construct(callable|array $listener, ?string $name, Stopwatch $stopwatch, ?EventDispatcherInterface $dispatcher = null, ?int $priority = null) + { + $this->listener = $listener; + $this->optimizedListener = $listener instanceof \Closure ? $listener : (\is_callable($listener) ? $listener(...) : null); + $this->stopwatch = $stopwatch; + $this->dispatcher = $dispatcher; + $this->priority = $priority; + + if (\is_array($listener)) { + [$this->name, $this->callableRef] = $this->parseListener($listener); + $this->pretty = $this->name.'::'.$listener[1]; + $this->callableRef .= '::'.$listener[1]; + } elseif ($listener instanceof \Closure) { + $r = new \ReflectionFunction($listener); + if (str_contains($r->name, '{closure}')) { + $this->pretty = $this->name = 'closure'; + } elseif ($class = \PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass()) { + $this->name = $class->name; + $this->pretty = $this->name.'::'.$r->name; + } else { + $this->pretty = $this->name = $r->name; + } + } elseif (\is_string($listener)) { + $this->pretty = $this->name = $listener; + } else { + $this->name = get_debug_type($listener); + $this->pretty = $this->name.'::__invoke'; + $this->callableRef = $listener::class.'::__invoke'; + } + + if (null !== $name) { + $this->name = $name; + } + + self::$hasClassStub ??= class_exists(ClassStub::class); + } + + public function getWrappedListener(): callable|array + { + return $this->listener; + } + + public function wasCalled(): bool + { + return $this->called; + } + + public function stoppedPropagation(): bool + { + return $this->stoppedPropagation; + } + + public function getPretty(): string + { + return $this->pretty; + } + + public function getInfo(string $eventName): array + { + $this->stub ??= self::$hasClassStub ? new ClassStub($this->pretty.'()', $this->callableRef ?? $this->listener) : $this->pretty.'()'; + + return [ + 'event' => $eventName, + 'priority' => $this->priority ??= $this->dispatcher?->getListenerPriority($eventName, $this->listener), + 'pretty' => $this->pretty, + 'stub' => $this->stub, + ]; + } + + public function __invoke(object $event, string $eventName, EventDispatcherInterface $dispatcher): void + { + $dispatcher = $this->dispatcher ?: $dispatcher; + + $this->called = true; + $this->priority ??= $dispatcher->getListenerPriority($eventName, $this->listener); + + $e = $this->stopwatch->start($this->name, 'event_listener'); + + try { + ($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher); + } finally { + if ($e->isStarted()) { + $e->stop(); + } + } + + if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + $this->stoppedPropagation = true; + } + } + + private function parseListener(array $listener): array + { + if ($listener[0] instanceof \Closure) { + foreach ((new \ReflectionFunction($listener[0]))->getAttributes(\Closure::class) as $attribute) { + if ($name = $attribute->getArguments()['name'] ?? false) { + return [$name, $attribute->getArguments()['class'] ?? $name]; + } + } + } + + if (\is_object($listener[0])) { + return [get_debug_type($listener[0]), $listener[0]::class]; + } + + return [$listener[0], $listener[0]]; + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/DependencyInjection/AddEventAliasesPass.php b/php/libraries/composer/vendor/symfony/event-dispatcher/DependencyInjection/AddEventAliasesPass.php new file mode 100644 index 0000000..13b4336 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/DependencyInjection/AddEventAliasesPass.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * This pass allows bundles to extend the list of event aliases. + * + * @author Alexander M. Turek + */ +class AddEventAliasesPass implements CompilerPassInterface +{ + private array $eventAliases; + + public function __construct(array $eventAliases) + { + $this->eventAliases = $eventAliases; + } + + public function process(ContainerBuilder $container): void + { + $eventAliases = $container->hasParameter('event_dispatcher.event_aliases') ? $container->getParameter('event_dispatcher.event_aliases') : []; + + $container->setParameter( + 'event_dispatcher.event_aliases', + array_merge($eventAliases, $this->eventAliases) + ); + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php b/php/libraries/composer/vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php new file mode 100644 index 0000000..866f4e6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php @@ -0,0 +1,216 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\DependencyInjection; + +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Compiler pass to register tagged services for an event dispatcher. + */ +class RegisterListenersPass implements CompilerPassInterface +{ + private array $hotPathEvents = []; + private array $noPreloadEvents = []; + + /** + * @return $this + */ + public function setHotPathEvents(array $hotPathEvents): static + { + $this->hotPathEvents = array_flip($hotPathEvents); + + return $this; + } + + /** + * @return $this + */ + public function setNoPreloadEvents(array $noPreloadEvents): static + { + $this->noPreloadEvents = array_flip($noPreloadEvents); + + return $this; + } + + /** + * @return void + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition('event_dispatcher') && !$container->hasAlias('event_dispatcher')) { + return; + } + + $aliases = []; + + if ($container->hasParameter('event_dispatcher.event_aliases')) { + $aliases = $container->getParameter('event_dispatcher.event_aliases'); + } + + $globalDispatcherDefinition = $container->findDefinition('event_dispatcher'); + + foreach ($container->findTaggedServiceIds('kernel.event_listener', true) as $id => $events) { + $noPreload = 0; + + foreach ($events as $event) { + $priority = $event['priority'] ?? 0; + + if (!isset($event['event'])) { + if ($container->getDefinition($id)->hasTag('kernel.event_subscriber')) { + continue; + } + + $event['method'] ??= '__invoke'; + $event['event'] = $this->getEventFromTypeDeclaration($container, $id, $event['method']); + } + + $event['event'] = $aliases[$event['event']] ?? $event['event']; + + if (!isset($event['method'])) { + $event['method'] = 'on'.preg_replace_callback([ + '/(?<=\b|_)[a-z]/i', + '/[^a-z0-9]/i', + ], fn ($matches) => strtoupper($matches[0]), $event['event']); + $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']); + + if (null !== ($class = $container->getDefinition($id)->getClass()) && ($r = $container->getReflectionClass($class, false)) && !$r->hasMethod($event['method'])) { + if (!$r->hasMethod('__invoke')) { + throw new InvalidArgumentException(sprintf('None of the "%s" or "__invoke" methods exist for the service "%s". Please define the "method" attribute on "kernel.event_listener" tags.', $event['method'], $id)); + } + + $event['method'] = '__invoke'; + } + } + + $dispatcherDefinition = $globalDispatcherDefinition; + if (isset($event['dispatcher'])) { + $dispatcherDefinition = $container->findDefinition($event['dispatcher']); + } + + $dispatcherDefinition->addMethodCall('addListener', [$event['event'], [new ServiceClosureArgument(new Reference($id)), $event['method']], $priority]); + + if (isset($this->hotPathEvents[$event['event']])) { + $container->getDefinition($id)->addTag('container.hot_path'); + } elseif (isset($this->noPreloadEvents[$event['event']])) { + ++$noPreload; + } + } + + if ($noPreload && \count($events) === $noPreload) { + $container->getDefinition($id)->addTag('container.no_preload'); + } + } + + $extractingDispatcher = new ExtractingEventDispatcher(); + + foreach ($container->findTaggedServiceIds('kernel.event_subscriber', true) as $id => $tags) { + $def = $container->getDefinition($id); + + // We must assume that the class value has been correctly filled, even if the service is created by a factory + $class = $def->getClass(); + + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(EventSubscriberInterface::class)) { + throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, EventSubscriberInterface::class)); + } + $class = $r->name; + + $dispatcherDefinitions = []; + foreach ($tags as $attributes) { + if (!isset($attributes['dispatcher']) || isset($dispatcherDefinitions[$attributes['dispatcher']])) { + continue; + } + + $dispatcherDefinitions[$attributes['dispatcher']] = $container->findDefinition($attributes['dispatcher']); + } + + if (!$dispatcherDefinitions) { + $dispatcherDefinitions = [$globalDispatcherDefinition]; + } + + $noPreload = 0; + ExtractingEventDispatcher::$aliases = $aliases; + ExtractingEventDispatcher::$subscriber = $class; + $extractingDispatcher->addSubscriber($extractingDispatcher); + foreach ($extractingDispatcher->listeners as $args) { + $args[1] = [new ServiceClosureArgument(new Reference($id)), $args[1]]; + foreach ($dispatcherDefinitions as $dispatcherDefinition) { + $dispatcherDefinition->addMethodCall('addListener', $args); + } + + if (isset($this->hotPathEvents[$args[0]])) { + $container->getDefinition($id)->addTag('container.hot_path'); + } elseif (isset($this->noPreloadEvents[$args[0]])) { + ++$noPreload; + } + } + if ($noPreload && \count($extractingDispatcher->listeners) === $noPreload) { + $container->getDefinition($id)->addTag('container.no_preload'); + } + $extractingDispatcher->listeners = []; + ExtractingEventDispatcher::$aliases = []; + } + } + + private function getEventFromTypeDeclaration(ContainerBuilder $container, string $id, string $method): string + { + if ( + null === ($class = $container->getDefinition($id)->getClass()) + || !($r = $container->getReflectionClass($class, false)) + || !$r->hasMethod($method) + || 1 > ($m = $r->getMethod($method))->getNumberOfParameters() + || !($type = $m->getParameters()[0]->getType()) instanceof \ReflectionNamedType + || $type->isBuiltin() + || Event::class === ($name = $type->getName()) + ) { + throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "kernel.event_listener" tags.', $id)); + } + + return $name; + } +} + +/** + * @internal + */ +class ExtractingEventDispatcher extends EventDispatcher implements EventSubscriberInterface +{ + public array $listeners = []; + + public static array $aliases = []; + public static string $subscriber; + + public function addListener(string $eventName, callable|array $listener, int $priority = 0): void + { + $this->listeners[] = [$eventName, $listener[1], $priority]; + } + + public static function getSubscribedEvents(): array + { + $events = []; + + foreach ([self::$subscriber, 'getSubscribedEvents']() as $eventName => $params) { + $events[self::$aliases[$eventName] ?? $eventName] = $params; + } + + return $events; + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/EventDispatcher.php b/php/libraries/composer/vendor/symfony/event-dispatcher/EventDispatcher.php new file mode 100644 index 0000000..6052989 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/EventDispatcher.php @@ -0,0 +1,270 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +use Psr\EventDispatcher\StoppableEventInterface; +use Symfony\Component\EventDispatcher\Debug\WrappedListener; + +/** + * The EventDispatcherInterface is the central point of Symfony's event listener system. + * + * Listeners are registered on the manager and events are dispatched through the + * manager. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + * @author Fabien Potencier + * @author Jordi Boggiano + * @author Jordan Alliot + * @author Nicolas Grekas + */ +class EventDispatcher implements EventDispatcherInterface +{ + private array $listeners = []; + private array $sorted = []; + private array $optimized; + + public function __construct() + { + if (__CLASS__ === static::class) { + $this->optimized = []; + } + } + + public function dispatch(object $event, ?string $eventName = null): object + { + $eventName ??= $event::class; + + if (isset($this->optimized)) { + $listeners = $this->optimized[$eventName] ?? (empty($this->listeners[$eventName]) ? [] : $this->optimizeListeners($eventName)); + } else { + $listeners = $this->getListeners($eventName); + } + + if ($listeners) { + $this->callListeners($listeners, $eventName, $event); + } + + return $event; + } + + public function getListeners(?string $eventName = null): array + { + if (null !== $eventName) { + if (empty($this->listeners[$eventName])) { + return []; + } + + if (!isset($this->sorted[$eventName])) { + $this->sortListeners($eventName); + } + + return $this->sorted[$eventName]; + } + + foreach ($this->listeners as $eventName => $eventListeners) { + if (!isset($this->sorted[$eventName])) { + $this->sortListeners($eventName); + } + } + + return array_filter($this->sorted); + } + + public function getListenerPriority(string $eventName, callable|array $listener): ?int + { + if (empty($this->listeners[$eventName])) { + return null; + } + + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + + foreach ($this->listeners[$eventName] as $priority => &$listeners) { + foreach ($listeners as &$v) { + if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure && 2 >= \count($v)) { + $v[0] = $v[0](); + $v[1] ??= '__invoke'; + } + if ($v === $listener || ($listener instanceof \Closure && $v == $listener)) { + return $priority; + } + } + } + + return null; + } + + public function hasListeners(?string $eventName = null): bool + { + if (null !== $eventName) { + return !empty($this->listeners[$eventName]); + } + + foreach ($this->listeners as $eventListeners) { + if ($eventListeners) { + return true; + } + } + + return false; + } + + /** + * @return void + */ + public function addListener(string $eventName, callable|array $listener, int $priority = 0) + { + $this->listeners[$eventName][$priority][] = $listener; + unset($this->sorted[$eventName], $this->optimized[$eventName]); + } + + /** + * @return void + */ + public function removeListener(string $eventName, callable|array $listener) + { + if (empty($this->listeners[$eventName])) { + return; + } + + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + + foreach ($this->listeners[$eventName] as $priority => &$listeners) { + foreach ($listeners as $k => &$v) { + if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure && 2 >= \count($v)) { + $v[0] = $v[0](); + $v[1] ??= '__invoke'; + } + if ($v === $listener || ($listener instanceof \Closure && $v == $listener)) { + unset($listeners[$k], $this->sorted[$eventName], $this->optimized[$eventName]); + } + } + + if (!$listeners) { + unset($this->listeners[$eventName][$priority]); + } + } + } + + /** + * @return void + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { + if (\is_string($params)) { + $this->addListener($eventName, [$subscriber, $params]); + } elseif (\is_string($params[0])) { + $this->addListener($eventName, [$subscriber, $params[0]], $params[1] ?? 0); + } else { + foreach ($params as $listener) { + $this->addListener($eventName, [$subscriber, $listener[0]], $listener[1] ?? 0); + } + } + } + } + + /** + * @return void + */ + public function removeSubscriber(EventSubscriberInterface $subscriber) + { + foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { + if (\is_array($params) && \is_array($params[0])) { + foreach ($params as $listener) { + $this->removeListener($eventName, [$subscriber, $listener[0]]); + } + } else { + $this->removeListener($eventName, [$subscriber, \is_string($params) ? $params : $params[0]]); + } + } + } + + /** + * Triggers the listeners of an event. + * + * This method can be overridden to add functionality that is executed + * for each listener. + * + * @param callable[] $listeners The event listeners + * @param string $eventName The name of the event to dispatch + * @param object $event The event object to pass to the event handlers/listeners + * + * @return void + */ + protected function callListeners(iterable $listeners, string $eventName, object $event) + { + $stoppable = $event instanceof StoppableEventInterface; + + foreach ($listeners as $listener) { + if ($stoppable && $event->isPropagationStopped()) { + break; + } + $listener($event, $eventName, $this); + } + } + + /** + * Sorts the internal list of listeners for the given event by priority. + */ + private function sortListeners(string $eventName): void + { + krsort($this->listeners[$eventName]); + $this->sorted[$eventName] = []; + + foreach ($this->listeners[$eventName] as &$listeners) { + foreach ($listeners as &$listener) { + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + $this->sorted[$eventName][] = $listener; + } + } + } + + /** + * Optimizes the internal list of listeners for the given event by priority. + */ + private function optimizeListeners(string $eventName): array + { + krsort($this->listeners[$eventName]); + $this->optimized[$eventName] = []; + + foreach ($this->listeners[$eventName] as &$listeners) { + foreach ($listeners as &$listener) { + $closure = &$this->optimized[$eventName][]; + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $closure = static function (...$args) use (&$listener, &$closure) { + if ($listener[0] instanceof \Closure) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + ($closure = $listener(...))(...$args); + }; + } else { + $closure = $listener instanceof WrappedListener ? $listener : $listener(...); + } + } + } + + return $this->optimized[$eventName]; + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/EventDispatcherInterface.php b/php/libraries/composer/vendor/symfony/event-dispatcher/EventDispatcherInterface.php new file mode 100644 index 0000000..e95a7b1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/EventDispatcherInterface.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\EventDispatcher; + +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; + +/** + * The EventDispatcherInterface is the central point of Symfony's event listener system. + * Listeners are registered on the manager and events are dispatched through the + * manager. + * + * @author Bernhard Schussek + */ +interface EventDispatcherInterface extends ContractsEventDispatcherInterface +{ + /** + * Adds an event listener that listens on the specified events. + * + * @param int $priority The higher this value, the earlier an event + * listener will be triggered in the chain (defaults to 0) + * + * @return void + */ + public function addListener(string $eventName, callable $listener, int $priority = 0); + + /** + * Adds an event subscriber. + * + * The subscriber is asked for all the events it is + * interested in and added as a listener for these events. + * + * @return void + */ + public function addSubscriber(EventSubscriberInterface $subscriber); + + /** + * Removes an event listener from the specified events. + * + * @return void + */ + public function removeListener(string $eventName, callable $listener); + + /** + * @return void + */ + public function removeSubscriber(EventSubscriberInterface $subscriber); + + /** + * Gets the listeners of a specific event or all listeners sorted by descending priority. + * + * @return array + */ + public function getListeners(?string $eventName = null): array; + + /** + * Gets the listener priority for a specific event. + * + * Returns null if the event or the listener does not exist. + */ + public function getListenerPriority(string $eventName, callable $listener): ?int; + + /** + * Checks whether an event has any registered listeners. + */ + public function hasListeners(?string $eventName = null): bool; +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/EventSubscriberInterface.php b/php/libraries/composer/vendor/symfony/event-dispatcher/EventSubscriberInterface.php new file mode 100644 index 0000000..2085e42 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/EventSubscriberInterface.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * An EventSubscriber knows itself what events it is interested in. + * If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes + * {@link getSubscribedEvents} and registers the subscriber as a listener for all + * returned events. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + */ +interface EventSubscriberInterface +{ + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * ['eventName' => 'methodName'] + * * ['eventName' => ['methodName', $priority]] + * * ['eventName' => [['methodName1', $priority], ['methodName2']]] + * + * The code must not depend on runtime state as it will only be called at compile time. + * All logic depending on runtime state must be put into the individual methods handling the events. + * + * @return array> + */ + public static function getSubscribedEvents(); +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/GenericEvent.php b/php/libraries/composer/vendor/symfony/event-dispatcher/GenericEvent.php new file mode 100644 index 0000000..0ccbbd8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/GenericEvent.php @@ -0,0 +1,158 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Event encapsulation class. + * + * Encapsulates events thus decoupling the observer from the subject they encapsulate. + * + * @author Drak + * + * @implements \ArrayAccess + * @implements \IteratorAggregate + */ +class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate +{ + protected $subject; + protected $arguments; + + /** + * Encapsulate an event with $subject and $arguments. + * + * @param mixed $subject The subject of the event, usually an object or a callable + * @param array $arguments Arguments to store in the event + */ + public function __construct(mixed $subject = null, array $arguments = []) + { + $this->subject = $subject; + $this->arguments = $arguments; + } + + /** + * Getter for subject property. + */ + public function getSubject(): mixed + { + return $this->subject; + } + + /** + * Get argument by key. + * + * @throws \InvalidArgumentException if key is not found + */ + public function getArgument(string $key): mixed + { + if ($this->hasArgument($key)) { + return $this->arguments[$key]; + } + + throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key)); + } + + /** + * Add argument to event. + * + * @return $this + */ + public function setArgument(string $key, mixed $value): static + { + $this->arguments[$key] = $value; + + return $this; + } + + /** + * Getter for all arguments. + */ + public function getArguments(): array + { + return $this->arguments; + } + + /** + * Set args property. + * + * @return $this + */ + public function setArguments(array $args = []): static + { + $this->arguments = $args; + + return $this; + } + + /** + * Has argument. + */ + public function hasArgument(string $key): bool + { + return \array_key_exists($key, $this->arguments); + } + + /** + * ArrayAccess for argument getter. + * + * @param string $key Array key + * + * @throws \InvalidArgumentException if key does not exist in $this->args + */ + public function offsetGet(mixed $key): mixed + { + return $this->getArgument($key); + } + + /** + * ArrayAccess for argument setter. + * + * @param string $key Array key to set + */ + public function offsetSet(mixed $key, mixed $value): void + { + $this->setArgument($key, $value); + } + + /** + * ArrayAccess for unset argument. + * + * @param string $key Array key + */ + public function offsetUnset(mixed $key): void + { + if ($this->hasArgument($key)) { + unset($this->arguments[$key]); + } + } + + /** + * ArrayAccess has argument. + * + * @param string $key Array key + */ + public function offsetExists(mixed $key): bool + { + return $this->hasArgument($key); + } + + /** + * IteratorAggregate for iterating over the object like an array. + * + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->arguments); + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php b/php/libraries/composer/vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php new file mode 100644 index 0000000..301a805 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * A read-only proxy for an event dispatcher. + * + * @author Bernhard Schussek + */ +class ImmutableEventDispatcher implements EventDispatcherInterface +{ + private EventDispatcherInterface $dispatcher; + + public function __construct(EventDispatcherInterface $dispatcher) + { + $this->dispatcher = $dispatcher; + } + + public function dispatch(object $event, ?string $eventName = null): object + { + return $this->dispatcher->dispatch($event, $eventName); + } + + /** + * @return never + */ + public function addListener(string $eventName, callable|array $listener, int $priority = 0) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * @return never + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * @return never + */ + public function removeListener(string $eventName, callable|array $listener) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * @return never + */ + public function removeSubscriber(EventSubscriberInterface $subscriber) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + public function getListeners(?string $eventName = null): array + { + return $this->dispatcher->getListeners($eventName); + } + + public function getListenerPriority(string $eventName, callable|array $listener): ?int + { + return $this->dispatcher->getListenerPriority($eventName, $listener); + } + + public function hasListeners(?string $eventName = null): bool + { + return $this->dispatcher->hasListeners($eventName); + } +} diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/LICENSE b/php/libraries/composer/vendor/symfony/event-dispatcher/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/README.md b/php/libraries/composer/vendor/symfony/event-dispatcher/README.md new file mode 100644 index 0000000..dcdb68d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/README.md @@ -0,0 +1,15 @@ +EventDispatcher Component +========================= + +The EventDispatcher component provides tools that allow your application +components to communicate with each other by dispatching events and listening to +them. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/event_dispatcher.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/event-dispatcher/composer.json b/php/libraries/composer/vendor/symfony/event-dispatcher/composer.json new file mode 100644 index 0000000..ff281af --- /dev/null +++ b/php/libraries/composer/vendor/symfony/event-dispatcher/composer.json @@ -0,0 +1,47 @@ +{ + "name": "symfony/event-dispatcher", + "type": "library", + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "require-dev": { + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/expression-language": "^5.4|^6.0|^7.0", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/http-foundation": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^5.4|^6.0|^7.0", + "psr/log": "^1|^2|^3" + }, + "conflict": { + "symfony/dependency-injection": "<5.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\EventDispatcher\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/finder/CHANGELOG.md b/php/libraries/composer/vendor/symfony/finder/CHANGELOG.md new file mode 100644 index 0000000..6a44e87 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/CHANGELOG.md @@ -0,0 +1,87 @@ +CHANGELOG +========= + +5.4.0 +----- + + * Deprecate `Comparator::setTarget()` and `Comparator::setOperator()` + * Add a constructor to `Comparator` that allows setting target and operator + * Finder's iterator has now `Symfony\Component\Finder\SplFileInfo` inner type specified + * Add recursive .gitignore files support + +5.0.0 +----- + + * added `$useNaturalSort` argument to `Finder::sortByName()` + +4.3.0 +----- + + * added Finder::ignoreVCSIgnored() to ignore files based on rules listed in .gitignore + +4.2.0 +----- + + * added $useNaturalSort option to Finder::sortByName() method + * the `Finder::sortByName()` method will have a new `$useNaturalSort` + argument in version 5.0, not defining it is deprecated + * added `Finder::reverseSorting()` to reverse the sorting + +4.0.0 +----- + + * removed `ExceptionInterface` + * removed `Symfony\Component\Finder\Iterator\FilterIterator` + +3.4.0 +----- + + * deprecated `Symfony\Component\Finder\Iterator\FilterIterator` + * added Finder::hasResults() method to check if any results were found + +3.3.0 +----- + + * added double-star matching to Glob::toRegex() + +3.0.0 +----- + + * removed deprecated classes + +2.8.0 +----- + + * deprecated adapters and related classes + +2.5.0 +----- + * added support for GLOB_BRACE in the paths passed to Finder::in() + +2.3.0 +----- + + * added a way to ignore unreadable directories (via Finder::ignoreUnreadableDirs()) + * unified the way subfolders that are not executable are handled by always throwing an AccessDeniedException exception + +2.2.0 +----- + + * added Finder::path() and Finder::notPath() methods + * added finder adapters to improve performance on specific platforms + * added support for wildcard characters (glob patterns) in the paths passed + to Finder::in() + +2.1.0 +----- + + * added Finder::sortByAccessedTime(), Finder::sortByChangedTime(), and + Finder::sortByModifiedTime() + * added Countable to Finder + * added support for an array of directories as an argument to + Finder::exclude() + * added searching based on the file content via Finder::contains() and + Finder::notContains() + * added support for the != operator in the Comparator + * [BC BREAK] filter expressions (used for file name and content) are no more + considered as regexps but glob patterns when they are enclosed in '*' or '?' diff --git a/php/libraries/composer/vendor/symfony/finder/Comparator/Comparator.php b/php/libraries/composer/vendor/symfony/finder/Comparator/Comparator.php new file mode 100644 index 0000000..23cf94e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Comparator/Comparator.php @@ -0,0 +1,117 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Comparator; + +/** + * @author Fabien Potencier + */ +class Comparator +{ + private $target; + private $operator = '=='; + + public function __construct(?string $target = null, string $operator = '==') + { + if (null === $target) { + trigger_deprecation('symfony/finder', '5.4', 'Constructing a "%s" without setting "$target" is deprecated.', __CLASS__); + } + + $this->target = $target; + $this->doSetOperator($operator); + } + + /** + * Gets the target value. + * + * @return string + */ + public function getTarget() + { + if (null === $this->target) { + trigger_deprecation('symfony/finder', '5.4', 'Calling "%s" without initializing the target is deprecated.', __METHOD__); + } + + return $this->target; + } + + /** + * @deprecated set the target via the constructor instead + */ + public function setTarget(string $target) + { + trigger_deprecation('symfony/finder', '5.4', '"%s" is deprecated. Set the target via the constructor instead.', __METHOD__); + + $this->target = $target; + } + + /** + * Gets the comparison operator. + * + * @return string + */ + public function getOperator() + { + return $this->operator; + } + + /** + * Sets the comparison operator. + * + * @throws \InvalidArgumentException + * + * @deprecated set the operator via the constructor instead + */ + public function setOperator(string $operator) + { + trigger_deprecation('symfony/finder', '5.4', '"%s" is deprecated. Set the operator via the constructor instead.', __METHOD__); + + $this->doSetOperator('' === $operator ? '==' : $operator); + } + + /** + * Tests against the target. + * + * @param mixed $test A test value + * + * @return bool + */ + public function test($test) + { + if (null === $this->target) { + trigger_deprecation('symfony/finder', '5.4', 'Calling "%s" without initializing the target is deprecated.', __METHOD__); + } + + switch ($this->operator) { + case '>': + return $test > $this->target; + case '>=': + return $test >= $this->target; + case '<': + return $test < $this->target; + case '<=': + return $test <= $this->target; + case '!=': + return $test != $this->target; + } + + return $test == $this->target; + } + + private function doSetOperator(string $operator): void + { + if (!\in_array($operator, ['>', '<', '>=', '<=', '==', '!='])) { + throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator)); + } + + $this->operator = $operator; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Comparator/DateComparator.php b/php/libraries/composer/vendor/symfony/finder/Comparator/DateComparator.php new file mode 100644 index 0000000..8f651e1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Comparator/DateComparator.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Comparator; + +/** + * DateCompare compiles date comparisons. + * + * @author Fabien Potencier + */ +class DateComparator extends Comparator +{ + /** + * @param string $test A comparison string + * + * @throws \InvalidArgumentException If the test is not understood + */ + public function __construct(string $test) + { + if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) { + throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test)); + } + + try { + $date = new \DateTime($matches[2]); + $target = $date->format('U'); + } catch (\Exception $e) { + throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2])); + } + + $operator = $matches[1] ?? '=='; + if ('since' === $operator || 'after' === $operator) { + $operator = '>'; + } + + if ('until' === $operator || 'before' === $operator) { + $operator = '<'; + } + + parent::__construct($target, $operator); + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Comparator/NumberComparator.php b/php/libraries/composer/vendor/symfony/finder/Comparator/NumberComparator.php new file mode 100644 index 0000000..dd30820 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Comparator/NumberComparator.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Comparator; + +/** + * NumberComparator compiles a simple comparison to an anonymous + * subroutine, which you can call with a value to be tested again. + * + * Now this would be very pointless, if NumberCompare didn't understand + * magnitudes. + * + * The target value may use magnitudes of kilobytes (k, ki), + * megabytes (m, mi), or gigabytes (g, gi). Those suffixed + * with an i use the appropriate 2**n version in accordance with the + * IEC standard: http://physics.nist.gov/cuu/Units/binary.html + * + * Based on the Perl Number::Compare module. + * + * @author Fabien Potencier PHP port + * @author Richard Clamp Perl version + * @copyright 2004-2005 Fabien Potencier + * @copyright 2002 Richard Clamp + * + * @see http://physics.nist.gov/cuu/Units/binary.html + */ +class NumberComparator extends Comparator +{ + /** + * @param string|null $test A comparison string or null + * + * @throws \InvalidArgumentException If the test is not understood + */ + public function __construct(?string $test) + { + if (null === $test || !preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) { + throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test ?? 'null')); + } + + $target = $matches[2]; + if (!is_numeric($target)) { + throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target)); + } + if (isset($matches[3])) { + // magnitude + switch (strtolower($matches[3])) { + case 'k': + $target *= 1000; + break; + case 'ki': + $target *= 1024; + break; + case 'm': + $target *= 1000000; + break; + case 'mi': + $target *= 1024 * 1024; + break; + case 'g': + $target *= 1000000000; + break; + case 'gi': + $target *= 1024 * 1024 * 1024; + break; + } + } + + parent::__construct($target, $matches[1] ?: '=='); + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Exception/AccessDeniedException.php b/php/libraries/composer/vendor/symfony/finder/Exception/AccessDeniedException.php new file mode 100644 index 0000000..ee195ea --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Exception/AccessDeniedException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Exception; + +/** + * @author Jean-François Simon + */ +class AccessDeniedException extends \UnexpectedValueException +{ +} diff --git a/php/libraries/composer/vendor/symfony/finder/Exception/DirectoryNotFoundException.php b/php/libraries/composer/vendor/symfony/finder/Exception/DirectoryNotFoundException.php new file mode 100644 index 0000000..c6cc0f2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Exception/DirectoryNotFoundException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Exception; + +/** + * @author Andreas Erhard + */ +class DirectoryNotFoundException extends \InvalidArgumentException +{ +} diff --git a/php/libraries/composer/vendor/symfony/finder/Finder.php b/php/libraries/composer/vendor/symfony/finder/Finder.php new file mode 100644 index 0000000..0b56965 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Finder.php @@ -0,0 +1,806 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +use Symfony\Component\Finder\Comparator\DateComparator; +use Symfony\Component\Finder\Comparator\NumberComparator; +use Symfony\Component\Finder\Exception\DirectoryNotFoundException; +use Symfony\Component\Finder\Iterator\CustomFilterIterator; +use Symfony\Component\Finder\Iterator\DateRangeFilterIterator; +use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator; +use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator; +use Symfony\Component\Finder\Iterator\FilecontentFilterIterator; +use Symfony\Component\Finder\Iterator\FilenameFilterIterator; +use Symfony\Component\Finder\Iterator\LazyIterator; +use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator; +use Symfony\Component\Finder\Iterator\SortableIterator; + +/** + * Finder allows to build rules to find files and directories. + * + * It is a thin wrapper around several specialized iterator classes. + * + * All rules may be invoked several times. + * + * All methods return the current Finder object to allow chaining: + * + * $finder = Finder::create()->files()->name('*.php')->in(__DIR__); + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate + */ +class Finder implements \IteratorAggregate, \Countable +{ + public const IGNORE_VCS_FILES = 1; + public const IGNORE_DOT_FILES = 2; + public const IGNORE_VCS_IGNORED_FILES = 4; + + private $mode = 0; + private $names = []; + private $notNames = []; + private $exclude = []; + private $filters = []; + private $depths = []; + private $sizes = []; + private $followLinks = false; + private $reverseSorting = false; + private $sort = false; + private $ignore = 0; + private $dirs = []; + private $dates = []; + private $iterators = []; + private $contains = []; + private $notContains = []; + private $paths = []; + private $notPaths = []; + private $ignoreUnreadableDirs = false; + + private static $vcsPatterns = ['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg']; + + public function __construct() + { + $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES; + } + + /** + * Creates a new Finder. + * + * @return static + */ + public static function create() + { + return new static(); + } + + /** + * Restricts the matching to directories only. + * + * @return $this + */ + public function directories() + { + $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES; + + return $this; + } + + /** + * Restricts the matching to files only. + * + * @return $this + */ + public function files() + { + $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES; + + return $this; + } + + /** + * Adds tests for the directory depth. + * + * Usage: + * + * $finder->depth('> 1') // the Finder will start matching at level 1. + * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point. + * $finder->depth(['>= 1', '< 3']) + * + * @param string|int|string[]|int[] $levels The depth level expression or an array of depth levels + * + * @return $this + * + * @see DepthRangeFilterIterator + * @see NumberComparator + */ + public function depth($levels) + { + foreach ((array) $levels as $level) { + $this->depths[] = new Comparator\NumberComparator($level); + } + + return $this; + } + + /** + * Adds tests for file dates (last modified). + * + * The date must be something that strtotime() is able to parse: + * + * $finder->date('since yesterday'); + * $finder->date('until 2 days ago'); + * $finder->date('> now - 2 hours'); + * $finder->date('>= 2005-10-15'); + * $finder->date(['>= 2005-10-15', '<= 2006-05-27']); + * + * @param string|string[] $dates A date range string or an array of date ranges + * + * @return $this + * + * @see strtotime + * @see DateRangeFilterIterator + * @see DateComparator + */ + public function date($dates) + { + foreach ((array) $dates as $date) { + $this->dates[] = new Comparator\DateComparator($date); + } + + return $this; + } + + /** + * Adds rules that files must match. + * + * You can use patterns (delimited with / sign), globs or simple strings. + * + * $finder->name('/\.php$/') + * $finder->name('*.php') // same as above, without dot files + * $finder->name('test.php') + * $finder->name(['test.py', 'test.php']) + * + * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function name($patterns) + { + $this->names = array_merge($this->names, (array) $patterns); + + return $this; + } + + /** + * Adds rules that files must not match. + * + * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function notName($patterns) + { + $this->notNames = array_merge($this->notNames, (array) $patterns); + + return $this; + } + + /** + * Adds tests that file contents must match. + * + * Strings or PCRE patterns can be used: + * + * $finder->contains('Lorem ipsum') + * $finder->contains('/Lorem ipsum/i') + * $finder->contains(['dolor', '/ipsum/i']) + * + * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns + * + * @return $this + * + * @see FilecontentFilterIterator + */ + public function contains($patterns) + { + $this->contains = array_merge($this->contains, (array) $patterns); + + return $this; + } + + /** + * Adds tests that file contents must not match. + * + * Strings or PCRE patterns can be used: + * + * $finder->notContains('Lorem ipsum') + * $finder->notContains('/Lorem ipsum/i') + * $finder->notContains(['lorem', '/dolor/i']) + * + * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns + * + * @return $this + * + * @see FilecontentFilterIterator + */ + public function notContains($patterns) + { + $this->notContains = array_merge($this->notContains, (array) $patterns); + + return $this; + } + + /** + * Adds rules that filenames must match. + * + * You can use patterns (delimited with / sign) or simple strings. + * + * $finder->path('some/special/dir') + * $finder->path('/some\/special\/dir/') // same as above + * $finder->path(['some dir', 'another/dir']) + * + * Use only / as dirname separator. + * + * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function path($patterns) + { + $this->paths = array_merge($this->paths, (array) $patterns); + + return $this; + } + + /** + * Adds rules that filenames must not match. + * + * You can use patterns (delimited with / sign) or simple strings. + * + * $finder->notPath('some/special/dir') + * $finder->notPath('/some\/special\/dir/') // same as above + * $finder->notPath(['some/file.txt', 'another/file.log']) + * + * Use only / as dirname separator. + * + * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function notPath($patterns) + { + $this->notPaths = array_merge($this->notPaths, (array) $patterns); + + return $this; + } + + /** + * Adds tests for file sizes. + * + * $finder->size('> 10K'); + * $finder->size('<= 1Ki'); + * $finder->size(4); + * $finder->size(['> 10K', '< 20K']) + * + * @param string|int|string[]|int[] $sizes A size range string or an integer or an array of size ranges + * + * @return $this + * + * @see SizeRangeFilterIterator + * @see NumberComparator + */ + public function size($sizes) + { + foreach ((array) $sizes as $size) { + $this->sizes[] = new Comparator\NumberComparator($size); + } + + return $this; + } + + /** + * Excludes directories. + * + * Directories passed as argument must be relative to the ones defined with the `in()` method. For example: + * + * $finder->in(__DIR__)->exclude('ruby'); + * + * @param string|array $dirs A directory path or an array of directories + * + * @return $this + * + * @see ExcludeDirectoryFilterIterator + */ + public function exclude($dirs) + { + $this->exclude = array_merge($this->exclude, (array) $dirs); + + return $this; + } + + /** + * Excludes "hidden" directories and files (starting with a dot). + * + * This option is enabled by default. + * + * @return $this + * + * @see ExcludeDirectoryFilterIterator + */ + public function ignoreDotFiles(bool $ignoreDotFiles) + { + if ($ignoreDotFiles) { + $this->ignore |= static::IGNORE_DOT_FILES; + } else { + $this->ignore &= ~static::IGNORE_DOT_FILES; + } + + return $this; + } + + /** + * Forces the finder to ignore version control directories. + * + * This option is enabled by default. + * + * @return $this + * + * @see ExcludeDirectoryFilterIterator + */ + public function ignoreVCS(bool $ignoreVCS) + { + if ($ignoreVCS) { + $this->ignore |= static::IGNORE_VCS_FILES; + } else { + $this->ignore &= ~static::IGNORE_VCS_FILES; + } + + return $this; + } + + /** + * Forces Finder to obey .gitignore and ignore files based on rules listed there. + * + * This option is disabled by default. + * + * @return $this + */ + public function ignoreVCSIgnored(bool $ignoreVCSIgnored) + { + if ($ignoreVCSIgnored) { + $this->ignore |= static::IGNORE_VCS_IGNORED_FILES; + } else { + $this->ignore &= ~static::IGNORE_VCS_IGNORED_FILES; + } + + return $this; + } + + /** + * Adds VCS patterns. + * + * @see ignoreVCS() + * + * @param string|string[] $pattern VCS patterns to ignore + */ + public static function addVCSPattern($pattern) + { + foreach ((array) $pattern as $p) { + self::$vcsPatterns[] = $p; + } + + self::$vcsPatterns = array_unique(self::$vcsPatterns); + } + + /** + * Sorts files and directories by an anonymous function. + * + * The anonymous function receives two \SplFileInfo instances to compare. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sort(\Closure $closure) + { + $this->sort = $closure; + + return $this; + } + + /** + * Sorts files and directories by name. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByName(bool $useNaturalSort = false) + { + $this->sort = $useNaturalSort ? Iterator\SortableIterator::SORT_BY_NAME_NATURAL : Iterator\SortableIterator::SORT_BY_NAME; + + return $this; + } + + /** + * Sorts files and directories by type (directories before files), then by name. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByType() + { + $this->sort = Iterator\SortableIterator::SORT_BY_TYPE; + + return $this; + } + + /** + * Sorts files and directories by the last accessed time. + * + * This is the time that the file was last accessed, read or written to. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByAccessedTime() + { + $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME; + + return $this; + } + + /** + * Reverses the sorting. + * + * @return $this + */ + public function reverseSorting() + { + $this->reverseSorting = true; + + return $this; + } + + /** + * Sorts files and directories by the last inode changed time. + * + * This is the time that the inode information was last modified (permissions, owner, group or other metadata). + * + * On Windows, since inode is not available, changed time is actually the file creation time. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByChangedTime() + { + $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME; + + return $this; + } + + /** + * Sorts files and directories by the last modified time. + * + * This is the last time the actual contents of the file were last modified. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByModifiedTime() + { + $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME; + + return $this; + } + + /** + * Filters the iterator with an anonymous function. + * + * The anonymous function receives a \SplFileInfo and must return false + * to remove files. + * + * @return $this + * + * @see CustomFilterIterator + */ + public function filter(\Closure $closure) + { + $this->filters[] = $closure; + + return $this; + } + + /** + * Forces the following of symlinks. + * + * @return $this + */ + public function followLinks() + { + $this->followLinks = true; + + return $this; + } + + /** + * Tells finder to ignore unreadable directories. + * + * By default, scanning unreadable directories content throws an AccessDeniedException. + * + * @return $this + */ + public function ignoreUnreadableDirs(bool $ignore = true) + { + $this->ignoreUnreadableDirs = $ignore; + + return $this; + } + + /** + * Searches files and directories which match defined rules. + * + * @param string|string[] $dirs A directory path or an array of directories + * + * @return $this + * + * @throws DirectoryNotFoundException if one of the directories does not exist + */ + public function in($dirs) + { + $resolvedDirs = []; + + foreach ((array) $dirs as $dir) { + if (is_dir($dir)) { + $resolvedDirs[] = [$this->normalizeDir($dir)]; + } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) { + sort($glob); + $resolvedDirs[] = array_map([$this, 'normalizeDir'], $glob); + } else { + throw new DirectoryNotFoundException(sprintf('The "%s" directory does not exist.', $dir)); + } + } + + $this->dirs = array_merge($this->dirs, ...$resolvedDirs); + + return $this; + } + + /** + * Returns an Iterator for the current Finder configuration. + * + * This method implements the IteratorAggregate interface. + * + * @return \Iterator + * + * @throws \LogicException if the in() method has not been called + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + if (0 === \count($this->dirs) && 0 === \count($this->iterators)) { + throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.'); + } + + if (1 === \count($this->dirs) && 0 === \count($this->iterators)) { + $iterator = $this->searchInDirectory($this->dirs[0]); + + if ($this->sort || $this->reverseSorting) { + $iterator = (new Iterator\SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator(); + } + + return $iterator; + } + + $iterator = new \AppendIterator(); + foreach ($this->dirs as $dir) { + $iterator->append(new \IteratorIterator(new LazyIterator(function () use ($dir) { + return $this->searchInDirectory($dir); + }))); + } + + foreach ($this->iterators as $it) { + $iterator->append($it); + } + + if ($this->sort || $this->reverseSorting) { + $iterator = (new Iterator\SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator(); + } + + return $iterator; + } + + /** + * Appends an existing set of files/directories to the finder. + * + * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array. + * + * @return $this + * + * @throws \InvalidArgumentException when the given argument is not iterable + */ + public function append(iterable $iterator) + { + if ($iterator instanceof \IteratorAggregate) { + $this->iterators[] = $iterator->getIterator(); + } elseif ($iterator instanceof \Iterator) { + $this->iterators[] = $iterator; + } elseif (is_iterable($iterator)) { + $it = new \ArrayIterator(); + foreach ($iterator as $file) { + $file = $file instanceof \SplFileInfo ? $file : new \SplFileInfo($file); + $it[$file->getPathname()] = $file; + } + $this->iterators[] = $it; + } else { + throw new \InvalidArgumentException('Finder::append() method wrong argument type.'); + } + + return $this; + } + + /** + * Check if any results were found. + * + * @return bool + */ + public function hasResults() + { + foreach ($this->getIterator() as $_) { + return true; + } + + return false; + } + + /** + * Counts all the results collected by the iterators. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return iterator_count($this->getIterator()); + } + + private function searchInDirectory(string $dir): \Iterator + { + $exclude = $this->exclude; + $notPaths = $this->notPaths; + + if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) { + $exclude = array_merge($exclude, self::$vcsPatterns); + } + + if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) { + $notPaths[] = '#(^|/)\..+(/|$)#'; + } + + $minDepth = 0; + $maxDepth = \PHP_INT_MAX; + + foreach ($this->depths as $comparator) { + switch ($comparator->getOperator()) { + case '>': + $minDepth = $comparator->getTarget() + 1; + break; + case '>=': + $minDepth = $comparator->getTarget(); + break; + case '<': + $maxDepth = $comparator->getTarget() - 1; + break; + case '<=': + $maxDepth = $comparator->getTarget(); + break; + default: + $minDepth = $maxDepth = $comparator->getTarget(); + } + } + + $flags = \RecursiveDirectoryIterator::SKIP_DOTS; + + if ($this->followLinks) { + $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS; + } + + $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs); + + if ($exclude) { + $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $exclude); + } + + $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); + + if ($minDepth > 0 || $maxDepth < \PHP_INT_MAX) { + $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth); + } + + if ($this->mode) { + $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode); + } + + if ($this->names || $this->notNames) { + $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames); + } + + if ($this->contains || $this->notContains) { + $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains); + } + + if ($this->sizes) { + $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes); + } + + if ($this->dates) { + $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates); + } + + if ($this->filters) { + $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); + } + + if ($this->paths || $notPaths) { + $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $notPaths); + } + + if (static::IGNORE_VCS_IGNORED_FILES === (static::IGNORE_VCS_IGNORED_FILES & $this->ignore)) { + $iterator = new Iterator\VcsIgnoredFilterIterator($iterator, $dir); + } + + return $iterator; + } + + /** + * Normalizes given directory names by removing trailing slashes. + * + * Excluding: (s)ftp:// or ssh2.(s)ftp:// wrapper + */ + private function normalizeDir(string $dir): string + { + if ('/' === $dir) { + return $dir; + } + + $dir = rtrim($dir, '/'.\DIRECTORY_SEPARATOR); + + if (preg_match('#^(ssh2\.)?s?ftp://#', $dir)) { + $dir .= '/'; + } + + return $dir; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Gitignore.php b/php/libraries/composer/vendor/symfony/finder/Gitignore.php new file mode 100644 index 0000000..d42cca1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Gitignore.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +/** + * Gitignore matches against text. + * + * @author Michael Voříšek + * @author Ahmed Abdou + */ +class Gitignore +{ + /** + * Returns a regexp which is the equivalent of the gitignore pattern. + * + * Format specification: https://git-scm.com/docs/gitignore#_pattern_format + */ + public static function toRegex(string $gitignoreFileContent): string + { + return self::buildRegex($gitignoreFileContent, false); + } + + public static function toRegexMatchingNegatedPatterns(string $gitignoreFileContent): string + { + return self::buildRegex($gitignoreFileContent, true); + } + + private static function buildRegex(string $gitignoreFileContent, bool $inverted): string + { + $gitignoreFileContent = preg_replace('~(? + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +/** + * Glob matches globbing patterns against text. + * + * if match_glob("foo.*", "foo.bar") echo "matched\n"; + * + * // prints foo.bar and foo.baz + * $regex = glob_to_regex("foo.*"); + * for (['foo.bar', 'foo.baz', 'foo', 'bar'] as $t) + * { + * if (/$regex/) echo "matched: $car\n"; + * } + * + * Glob implements glob(3) style matching that can be used to match + * against text, rather than fetching names from a filesystem. + * + * Based on the Perl Text::Glob module. + * + * @author Fabien Potencier PHP port + * @author Richard Clamp Perl version + * @copyright 2004-2005 Fabien Potencier + * @copyright 2002 Richard Clamp + */ +class Glob +{ + /** + * Returns a regexp which is the equivalent of the glob pattern. + * + * @return string + */ + public static function toRegex(string $glob, bool $strictLeadingDot = true, bool $strictWildcardSlash = true, string $delimiter = '#') + { + $firstByte = true; + $escaping = false; + $inCurlies = 0; + $regex = ''; + $sizeGlob = \strlen($glob); + for ($i = 0; $i < $sizeGlob; ++$i) { + $car = $glob[$i]; + if ($firstByte && $strictLeadingDot && '.' !== $car) { + $regex .= '(?=[^\.])'; + } + + $firstByte = '/' === $car; + + if ($firstByte && $strictWildcardSlash && isset($glob[$i + 2]) && '**' === $glob[$i + 1].$glob[$i + 2] && (!isset($glob[$i + 3]) || '/' === $glob[$i + 3])) { + $car = '[^/]++/'; + if (!isset($glob[$i + 3])) { + $car .= '?'; + } + + if ($strictLeadingDot) { + $car = '(?=[^\.])'.$car; + } + + $car = '/(?:'.$car.')*'; + $i += 2 + isset($glob[$i + 3]); + + if ('/' === $delimiter) { + $car = str_replace('/', '\\/', $car); + } + } + + if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) { + $regex .= "\\$car"; + } elseif ('*' === $car) { + $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*'); + } elseif ('?' === $car) { + $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.'); + } elseif ('{' === $car) { + $regex .= $escaping ? '\\{' : '('; + if (!$escaping) { + ++$inCurlies; + } + } elseif ('}' === $car && $inCurlies) { + $regex .= $escaping ? '}' : ')'; + if (!$escaping) { + --$inCurlies; + } + } elseif (',' === $car && $inCurlies) { + $regex .= $escaping ? ',' : '|'; + } elseif ('\\' === $car) { + if ($escaping) { + $regex .= '\\\\'; + $escaping = false; + } else { + $escaping = true; + } + + continue; + } else { + $regex .= $car; + } + $escaping = false; + } + + return $delimiter.'^'.$regex.'$'.$delimiter; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/CustomFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/CustomFilterIterator.php new file mode 100644 index 0000000..f7bf19b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/CustomFilterIterator.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * CustomFilterIterator filters files by applying anonymous functions. + * + * The anonymous function receives a \SplFileInfo and must return false + * to remove files. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class CustomFilterIterator extends \FilterIterator +{ + private $filters = []; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param callable[] $filters An array of PHP callbacks + * + * @throws \InvalidArgumentException + */ + public function __construct(\Iterator $iterator, array $filters) + { + foreach ($filters as $filter) { + if (!\is_callable($filter)) { + throw new \InvalidArgumentException('Invalid PHP callback.'); + } + } + $this->filters = $filters; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + $fileinfo = $this->current(); + + foreach ($this->filters as $filter) { + if (false === $filter($fileinfo)) { + return false; + } + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/DateRangeFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/DateRangeFilterIterator.php new file mode 100644 index 0000000..f592e19 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/DateRangeFilterIterator.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Comparator\DateComparator; + +/** + * DateRangeFilterIterator filters out files that are not in the given date range (last modified dates). + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class DateRangeFilterIterator extends \FilterIterator +{ + private $comparators = []; + + /** + * @param \Iterator $iterator + * @param DateComparator[] $comparators + */ + public function __construct(\Iterator $iterator, array $comparators) + { + $this->comparators = $comparators; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + $fileinfo = $this->current(); + + if (!file_exists($fileinfo->getPathname())) { + return false; + } + + $filedate = $fileinfo->getMTime(); + foreach ($this->comparators as $compare) { + if (!$compare->test($filedate)) { + return false; + } + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php new file mode 100644 index 0000000..f593a3f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/DepthRangeFilterIterator.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\Finder\Iterator; + +/** + * DepthRangeFilterIterator limits the directory depth. + * + * @author Fabien Potencier + * + * @template-covariant TKey + * @template-covariant TValue + * + * @extends \FilterIterator + */ +class DepthRangeFilterIterator extends \FilterIterator +{ + private $minDepth = 0; + + /** + * @param \RecursiveIteratorIterator<\RecursiveIterator> $iterator The Iterator to filter + * @param int $minDepth The min depth + * @param int $maxDepth The max depth + */ + public function __construct(\RecursiveIteratorIterator $iterator, int $minDepth = 0, int $maxDepth = \PHP_INT_MAX) + { + $this->minDepth = $minDepth; + $iterator->setMaxDepth(\PHP_INT_MAX === $maxDepth ? -1 : $maxDepth); + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + return $this->getInnerIterator()->getDepth() >= $this->minDepth; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php new file mode 100644 index 0000000..39797c8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * ExcludeDirectoryFilterIterator filters out directories. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + * + * @implements \RecursiveIterator + */ +class ExcludeDirectoryFilterIterator extends \FilterIterator implements \RecursiveIterator +{ + private $iterator; + private $isRecursive; + private $excludedDirs = []; + private $excludedPattern; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param string[] $directories An array of directories to exclude + */ + public function __construct(\Iterator $iterator, array $directories) + { + $this->iterator = $iterator; + $this->isRecursive = $iterator instanceof \RecursiveIterator; + $patterns = []; + foreach ($directories as $directory) { + $directory = rtrim($directory, '/'); + if (!$this->isRecursive || str_contains($directory, '/')) { + $patterns[] = preg_quote($directory, '#'); + } else { + $this->excludedDirs[$directory] = true; + } + } + if ($patterns) { + $this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#'; + } + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) { + return false; + } + + if ($this->excludedPattern) { + $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath(); + $path = str_replace('\\', '/', $path); + + return !preg_match($this->excludedPattern, $path); + } + + return true; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function hasChildren() + { + return $this->isRecursive && $this->iterator->hasChildren(); + } + + /** + * @return self + */ + #[\ReturnTypeWillChange] + public function getChildren() + { + $children = new self($this->iterator->getChildren(), []); + $children->excludedDirs = $this->excludedDirs; + $children->excludedPattern = $this->excludedPattern; + + return $children; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/FileTypeFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/FileTypeFilterIterator.php new file mode 100644 index 0000000..793ae35 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/FileTypeFilterIterator.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * FileTypeFilterIterator only keeps files, directories, or both. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class FileTypeFilterIterator extends \FilterIterator +{ + public const ONLY_FILES = 1; + public const ONLY_DIRECTORIES = 2; + + private $mode; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param int $mode The mode (self::ONLY_FILES or self::ONLY_DIRECTORIES) + */ + public function __construct(\Iterator $iterator, int $mode) + { + $this->mode = $mode; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + $fileinfo = $this->current(); + if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) { + return false; + } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) { + return false; + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/FilecontentFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/FilecontentFilterIterator.php new file mode 100644 index 0000000..79f8c29 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/FilecontentFilterIterator.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * FilecontentFilterIterator filters files by their contents using patterns (regexps or strings). + * + * @author Fabien Potencier + * @author Włodzimierz Gajda + * + * @extends MultiplePcreFilterIterator + */ +class FilecontentFilterIterator extends MultiplePcreFilterIterator +{ + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + if (!$this->matchRegexps && !$this->noMatchRegexps) { + return true; + } + + $fileinfo = $this->current(); + + if ($fileinfo->isDir() || !$fileinfo->isReadable()) { + return false; + } + + $content = $fileinfo->getContents(); + if (!$content) { + return false; + } + + return $this->isAccepted($content); + } + + /** + * Converts string to regexp if necessary. + * + * @param string $str Pattern: string or regexp + * + * @return string + */ + protected function toRegex(string $str) + { + return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/'; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/FilenameFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/FilenameFilterIterator.php new file mode 100644 index 0000000..77b3b24 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/FilenameFilterIterator.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Glob; + +/** + * FilenameFilterIterator filters files by patterns (a regexp, a glob, or a string). + * + * @author Fabien Potencier + * + * @extends MultiplePcreFilterIterator + */ +class FilenameFilterIterator extends MultiplePcreFilterIterator +{ + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + return $this->isAccepted($this->current()->getFilename()); + } + + /** + * Converts glob to regexp. + * + * PCRE patterns are left unchanged. + * Glob strings are transformed with Glob::toRegex(). + * + * @param string $str Pattern: glob or regexp + * + * @return string + */ + protected function toRegex(string $str) + { + return $this->isRegex($str) ? $str : Glob::toRegex($str); + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/LazyIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/LazyIterator.php new file mode 100644 index 0000000..32cc37f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/LazyIterator.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * @author Jérémy Derussé + * + * @internal + */ +class LazyIterator implements \IteratorAggregate +{ + private $iteratorFactory; + + public function __construct(callable $iteratorFactory) + { + $this->iteratorFactory = $iteratorFactory; + } + + public function getIterator(): \Traversable + { + yield from ($this->iteratorFactory)(); + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php new file mode 100644 index 0000000..564765d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php @@ -0,0 +1,117 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * MultiplePcreFilterIterator filters files using patterns (regexps, globs or strings). + * + * @author Fabien Potencier + * + * @template-covariant TKey + * @template-covariant TValue + * + * @extends \FilterIterator + */ +abstract class MultiplePcreFilterIterator extends \FilterIterator +{ + protected $matchRegexps = []; + protected $noMatchRegexps = []; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param string[] $matchPatterns An array of patterns that need to match + * @param string[] $noMatchPatterns An array of patterns that need to not match + */ + public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns) + { + foreach ($matchPatterns as $pattern) { + $this->matchRegexps[] = $this->toRegex($pattern); + } + + foreach ($noMatchPatterns as $pattern) { + $this->noMatchRegexps[] = $this->toRegex($pattern); + } + + parent::__construct($iterator); + } + + /** + * Checks whether the string is accepted by the regex filters. + * + * If there is no regexps defined in the class, this method will accept the string. + * Such case can be handled by child classes before calling the method if they want to + * apply a different behavior. + * + * @return bool + */ + protected function isAccepted(string $string) + { + // should at least not match one rule to exclude + foreach ($this->noMatchRegexps as $regex) { + if (preg_match($regex, $string)) { + return false; + } + } + + // should at least match one rule + if ($this->matchRegexps) { + foreach ($this->matchRegexps as $regex) { + if (preg_match($regex, $string)) { + return true; + } + } + + return false; + } + + // If there is no match rules, the file is accepted + return true; + } + + /** + * Checks whether the string is a regex. + * + * @return bool + */ + protected function isRegex(string $str) + { + $availableModifiers = 'imsxuADU'; + + if (\PHP_VERSION_ID >= 80200) { + $availableModifiers .= 'n'; + } + + if (preg_match('/^(.{3,}?)['.$availableModifiers.']*$/', $str, $m)) { + $start = substr($m[1], 0, 1); + $end = substr($m[1], -1); + + if ($start === $end) { + return !preg_match('/[*?[:alnum:] \\\\]/', $start); + } + + foreach ([['{', '}'], ['(', ')'], ['[', ']'], ['<', '>']] as $delimiters) { + if ($start === $delimiters[0] && $end === $delimiters[1]) { + return true; + } + } + } + + return false; + } + + /** + * Converts string into regexp. + * + * @return string + */ + abstract protected function toRegex(string $str); +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/PathFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/PathFilterIterator.php new file mode 100644 index 0000000..7974c4e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/PathFilterIterator.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * PathFilterIterator filters files by path patterns (e.g. some/special/dir). + * + * @author Fabien Potencier + * @author Włodzimierz Gajda + * + * @extends MultiplePcreFilterIterator + */ +class PathFilterIterator extends MultiplePcreFilterIterator +{ + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + $filename = $this->current()->getRelativePathname(); + + if ('\\' === \DIRECTORY_SEPARATOR) { + $filename = str_replace('\\', '/', $filename); + } + + return $this->isAccepted($filename); + } + + /** + * Converts strings to regexp. + * + * PCRE patterns are left unchanged. + * + * Default conversion: + * 'lorem/ipsum/dolor' ==> 'lorem\/ipsum\/dolor/' + * + * Use only / as directory separator (on Windows also). + * + * @param string $str Pattern: regexp or dirname + * + * @return string + */ + protected function toRegex(string $str) + { + return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/'; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php new file mode 100644 index 0000000..886dae5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php @@ -0,0 +1,157 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Exception\AccessDeniedException; +use Symfony\Component\Finder\SplFileInfo; + +/** + * Extends the \RecursiveDirectoryIterator to support relative paths. + * + * @author Victor Berchet + */ +class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator +{ + /** + * @var bool + */ + private $ignoreUnreadableDirs; + + /** + * @var bool + */ + private $ignoreFirstRewind = true; + + // these 3 properties take part of the performance optimization to avoid redoing the same work in all iterations + private $rootPath; + private $subPath; + private $directorySeparator = '/'; + + /** + * @throws \RuntimeException + */ + public function __construct(string $path, int $flags, bool $ignoreUnreadableDirs = false) + { + if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) { + throw new \RuntimeException('This iterator only support returning current as fileinfo.'); + } + + parent::__construct($path, $flags); + $this->ignoreUnreadableDirs = $ignoreUnreadableDirs; + $this->rootPath = $path; + if ('/' !== \DIRECTORY_SEPARATOR && !($flags & self::UNIX_PATHS)) { + $this->directorySeparator = \DIRECTORY_SEPARATOR; + } + } + + /** + * Return an instance of SplFileInfo with support for relative paths. + * + * @return SplFileInfo + */ + #[\ReturnTypeWillChange] + public function current() + { + // the logic here avoids redoing the same work in all iterations + + if (null === $subPathname = $this->subPath) { + $subPathname = $this->subPath = $this->getSubPath(); + } + if ('' !== $subPathname) { + $subPathname .= $this->directorySeparator; + } + $subPathname .= $this->getFilename(); + + if ('/' !== $basePath = $this->rootPath) { + $basePath .= $this->directorySeparator; + } + + return new SplFileInfo($basePath.$subPathname, $this->subPath, $subPathname); + } + + /** + * @param bool $allowLinks + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function hasChildren($allowLinks = false) + { + $hasChildren = parent::hasChildren($allowLinks); + + if (!$hasChildren || !$this->ignoreUnreadableDirs) { + return $hasChildren; + } + + try { + parent::getChildren(); + + return true; + } catch (\UnexpectedValueException $e) { + // If directory is unreadable and finder is set to ignore it, skip children + return false; + } + } + + /** + * @return \RecursiveDirectoryIterator + * + * @throws AccessDeniedException + */ + #[\ReturnTypeWillChange] + public function getChildren() + { + try { + $children = parent::getChildren(); + + if ($children instanceof self) { + // parent method will call the constructor with default arguments, so unreadable dirs won't be ignored anymore + $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs; + + // performance optimization to avoid redoing the same work in all children + $children->rootPath = $this->rootPath; + } + + return $children; + } catch (\UnexpectedValueException $e) { + throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * @return void + */ + #[\ReturnTypeWillChange] + public function next() + { + $this->ignoreFirstRewind = false; + + parent::next(); + } + + /** + * @return void + */ + #[\ReturnTypeWillChange] + public function rewind() + { + // some streams like FTP are not rewindable, ignore the first rewind after creation, + // as newly created DirectoryIterator does not need to be rewound + if ($this->ignoreFirstRewind) { + $this->ignoreFirstRewind = false; + + return; + } + + parent::rewind(); + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php new file mode 100644 index 0000000..575bf29 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/SizeRangeFilterIterator.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\Finder\Iterator; + +use Symfony\Component\Finder\Comparator\NumberComparator; + +/** + * SizeRangeFilterIterator filters out files that are not in the given size range. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class SizeRangeFilterIterator extends \FilterIterator +{ + private $comparators = []; + + /** + * @param \Iterator $iterator + * @param NumberComparator[] $comparators + */ + public function __construct(\Iterator $iterator, array $comparators) + { + $this->comparators = $comparators; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + $fileinfo = $this->current(); + if (!$fileinfo->isFile()) { + return true; + } + + $filesize = $fileinfo->getSize(); + foreach ($this->comparators as $compare) { + if (!$compare->test($filesize)) { + return false; + } + } + + return true; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/SortableIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/SortableIterator.php new file mode 100644 index 0000000..9afde5c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/SortableIterator.php @@ -0,0 +1,104 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * SortableIterator applies a sort on a given Iterator. + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate + */ +class SortableIterator implements \IteratorAggregate +{ + public const SORT_BY_NONE = 0; + public const SORT_BY_NAME = 1; + public const SORT_BY_TYPE = 2; + public const SORT_BY_ACCESSED_TIME = 3; + public const SORT_BY_CHANGED_TIME = 4; + public const SORT_BY_MODIFIED_TIME = 5; + public const SORT_BY_NAME_NATURAL = 6; + + private $iterator; + private $sort; + + /** + * @param \Traversable $iterator + * @param int|callable $sort The sort type (SORT_BY_NAME, SORT_BY_TYPE, or a PHP callback) + * + * @throws \InvalidArgumentException + */ + public function __construct(\Traversable $iterator, $sort, bool $reverseOrder = false) + { + $this->iterator = $iterator; + $order = $reverseOrder ? -1 : 1; + + if (self::SORT_BY_NAME === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + }; + } elseif (self::SORT_BY_NAME_NATURAL === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * strnatcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + }; + } elseif (self::SORT_BY_TYPE === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + if ($a->isDir() && $b->isFile()) { + return -$order; + } elseif ($a->isFile() && $b->isDir()) { + return $order; + } + + return $order * strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + }; + } elseif (self::SORT_BY_ACCESSED_TIME === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * ($a->getATime() - $b->getATime()); + }; + } elseif (self::SORT_BY_CHANGED_TIME === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * ($a->getCTime() - $b->getCTime()); + }; + } elseif (self::SORT_BY_MODIFIED_TIME === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * ($a->getMTime() - $b->getMTime()); + }; + } elseif (self::SORT_BY_NONE === $sort) { + $this->sort = $order; + } elseif (\is_callable($sort)) { + $this->sort = $reverseOrder ? static function (\SplFileInfo $a, \SplFileInfo $b) use ($sort) { return -$sort($a, $b); } : $sort; + } else { + throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.'); + } + } + + /** + * @return \Traversable + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + if (1 === $this->sort) { + return $this->iterator; + } + + $array = iterator_to_array($this->iterator, true); + + if (-1 === $this->sort) { + $array = array_reverse($array); + } else { + uasort($array, $this->sort); + } + + return new \ArrayIterator($array); + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php b/php/libraries/composer/vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php new file mode 100644 index 0000000..e27158c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Gitignore; + +final class VcsIgnoredFilterIterator extends \FilterIterator +{ + /** + * @var string + */ + private $baseDir; + + /** + * @var array + */ + private $gitignoreFilesCache = []; + + /** + * @var array + */ + private $ignoredPathsCache = []; + + public function __construct(\Iterator $iterator, string $baseDir) + { + $this->baseDir = $this->normalizePath($baseDir); + + parent::__construct($iterator); + } + + public function accept(): bool + { + $file = $this->current(); + + $fileRealPath = $this->normalizePath($file->getRealPath()); + + return !$this->isIgnored($fileRealPath); + } + + private function isIgnored(string $fileRealPath): bool + { + if (is_dir($fileRealPath) && !str_ends_with($fileRealPath, '/')) { + $fileRealPath .= '/'; + } + + if (isset($this->ignoredPathsCache[$fileRealPath])) { + return $this->ignoredPathsCache[$fileRealPath]; + } + + $ignored = false; + + foreach ($this->parentsDirectoryDownward($fileRealPath) as $parentDirectory) { + if ($this->isIgnored($parentDirectory)) { + // rules in ignored directories are ignored, no need to check further. + break; + } + + $fileRelativePath = substr($fileRealPath, \strlen($parentDirectory) + 1); + + if (null === $regexps = $this->readGitignoreFile("{$parentDirectory}/.gitignore")) { + continue; + } + + [$exclusionRegex, $inclusionRegex] = $regexps; + + if (preg_match($exclusionRegex, $fileRelativePath)) { + $ignored = true; + + continue; + } + + if (preg_match($inclusionRegex, $fileRelativePath)) { + $ignored = false; + } + } + + return $this->ignoredPathsCache[$fileRealPath] = $ignored; + } + + /** + * @return list + */ + private function parentsDirectoryDownward(string $fileRealPath): array + { + $parentDirectories = []; + + $parentDirectory = $fileRealPath; + + while (true) { + $newParentDirectory = \dirname($parentDirectory); + + // dirname('/') = '/' + if ($newParentDirectory === $parentDirectory) { + break; + } + + $parentDirectory = $newParentDirectory; + + if (0 !== strpos($parentDirectory, $this->baseDir)) { + break; + } + + $parentDirectories[] = $parentDirectory; + } + + return array_reverse($parentDirectories); + } + + /** + * @return array{0: string, 1: string}|null + */ + private function readGitignoreFile(string $path): ?array + { + if (\array_key_exists($path, $this->gitignoreFilesCache)) { + return $this->gitignoreFilesCache[$path]; + } + + if (!file_exists($path)) { + return $this->gitignoreFilesCache[$path] = null; + } + + if (!is_file($path) || !is_readable($path)) { + throw new \RuntimeException("The \"ignoreVCSIgnored\" option cannot be used by the Finder as the \"{$path}\" file is not readable."); + } + + $gitignoreFileContent = file_get_contents($path); + + return $this->gitignoreFilesCache[$path] = [ + Gitignore::toRegex($gitignoreFileContent), + Gitignore::toRegexMatchingNegatedPatterns($gitignoreFileContent), + ]; + } + + private function normalizePath(string $path): string + { + if ('\\' === \DIRECTORY_SEPARATOR) { + return str_replace('\\', '/', $path); + } + + return $path; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/LICENSE b/php/libraries/composer/vendor/symfony/finder/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/finder/README.md b/php/libraries/composer/vendor/symfony/finder/README.md new file mode 100644 index 0000000..22bdeb9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/README.md @@ -0,0 +1,14 @@ +Finder Component +================ + +The Finder component finds files and directories via an intuitive fluent +interface. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/finder.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/finder/SplFileInfo.php b/php/libraries/composer/vendor/symfony/finder/SplFileInfo.php new file mode 100644 index 0000000..11604a2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/SplFileInfo.php @@ -0,0 +1,88 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +/** + * Extends \SplFileInfo to support relative paths. + * + * @author Fabien Potencier + */ +class SplFileInfo extends \SplFileInfo +{ + private $relativePath; + private $relativePathname; + + /** + * @param string $file The file name + * @param string $relativePath The relative path + * @param string $relativePathname The relative path name + */ + public function __construct(string $file, string $relativePath, string $relativePathname) + { + parent::__construct($file); + $this->relativePath = $relativePath; + $this->relativePathname = $relativePathname; + } + + /** + * Returns the relative path. + * + * This path does not contain the file name. + * + * @return string + */ + public function getRelativePath() + { + return $this->relativePath; + } + + /** + * Returns the relative path name. + * + * This path contains the file name. + * + * @return string + */ + public function getRelativePathname() + { + return $this->relativePathname; + } + + public function getFilenameWithoutExtension(): string + { + $filename = $this->getFilename(); + + return pathinfo($filename, \PATHINFO_FILENAME); + } + + /** + * Returns the contents of the file. + * + * @return string + * + * @throws \RuntimeException + */ + public function getContents() + { + set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); + try { + $content = file_get_contents($this->getPathname()); + } finally { + restore_error_handler(); + } + if (false === $content) { + throw new \RuntimeException($error); + } + + return $content; + } +} diff --git a/php/libraries/composer/vendor/symfony/finder/composer.json b/php/libraries/composer/vendor/symfony/finder/composer.json new file mode 100644 index 0000000..ef19911 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/finder/composer.json @@ -0,0 +1,30 @@ +{ + "name": "symfony/finder", + "type": "library", + "description": "Finds files and directories via an intuitive fluent interface", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Finder\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/AcceptHeader.php b/php/libraries/composer/vendor/symfony/http-foundation/AcceptHeader.php new file mode 100644 index 0000000..057c6b5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/AcceptHeader.php @@ -0,0 +1,168 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +// Help opcache.preload discover always-needed symbols +class_exists(AcceptHeaderItem::class); + +/** + * Represents an Accept-* header. + * + * An accept header is compound with a list of items, + * sorted by descending quality. + * + * @author Jean-François Simon + */ +class AcceptHeader +{ + /** + * @var AcceptHeaderItem[] + */ + private $items = []; + + /** + * @var bool + */ + private $sorted = true; + + /** + * @param AcceptHeaderItem[] $items + */ + public function __construct(array $items) + { + foreach ($items as $item) { + $this->add($item); + } + } + + /** + * Builds an AcceptHeader instance from a string. + * + * @return self + */ + public static function fromString(?string $headerValue) + { + $index = 0; + + $parts = HeaderUtils::split($headerValue ?? '', ',;='); + + return new self(array_map(function ($subParts) use (&$index) { + $part = array_shift($subParts); + $attributes = HeaderUtils::combine($subParts); + + $item = new AcceptHeaderItem($part[0], $attributes); + $item->setIndex($index++); + + return $item; + }, $parts)); + } + + /** + * Returns header value's string representation. + * + * @return string + */ + public function __toString() + { + return implode(',', $this->items); + } + + /** + * Tests if header has given value. + * + * @return bool + */ + public function has(string $value) + { + return isset($this->items[$value]); + } + + /** + * Returns given value's item, if exists. + * + * @return AcceptHeaderItem|null + */ + public function get(string $value) + { + return $this->items[$value] ?? $this->items[explode('/', $value)[0].'/*'] ?? $this->items['*/*'] ?? $this->items['*'] ?? null; + } + + /** + * Adds an item. + * + * @return $this + */ + public function add(AcceptHeaderItem $item) + { + $this->items[$item->getValue()] = $item; + $this->sorted = false; + + return $this; + } + + /** + * Returns all items. + * + * @return AcceptHeaderItem[] + */ + public function all() + { + $this->sort(); + + return $this->items; + } + + /** + * Filters items on their value using given regex. + * + * @return self + */ + public function filter(string $pattern) + { + return new self(array_filter($this->items, function (AcceptHeaderItem $item) use ($pattern) { + return preg_match($pattern, $item->getValue()); + })); + } + + /** + * Returns first item. + * + * @return AcceptHeaderItem|null + */ + public function first() + { + $this->sort(); + + return !empty($this->items) ? reset($this->items) : null; + } + + /** + * Sorts items by descending quality. + */ + private function sort(): void + { + if (!$this->sorted) { + uasort($this->items, function (AcceptHeaderItem $a, AcceptHeaderItem $b) { + $qA = $a->getQuality(); + $qB = $b->getQuality(); + + if ($qA === $qB) { + return $a->getIndex() > $b->getIndex() ? 1 : -1; + } + + return $qA > $qB ? -1 : 1; + }); + + $this->sorted = true; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/AcceptHeaderItem.php b/php/libraries/composer/vendor/symfony/http-foundation/AcceptHeaderItem.php new file mode 100644 index 0000000..8b86eee --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/AcceptHeaderItem.php @@ -0,0 +1,177 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * Represents an Accept-* header item. + * + * @author Jean-François Simon + */ +class AcceptHeaderItem +{ + private $value; + private $quality = 1.0; + private $index = 0; + private $attributes = []; + + public function __construct(string $value, array $attributes = []) + { + $this->value = $value; + foreach ($attributes as $name => $value) { + $this->setAttribute($name, $value); + } + } + + /** + * Builds an AcceptHeaderInstance instance from a string. + * + * @return self + */ + public static function fromString(?string $itemValue) + { + $parts = HeaderUtils::split($itemValue ?? '', ';='); + + $part = array_shift($parts); + $attributes = HeaderUtils::combine($parts); + + return new self($part[0], $attributes); + } + + /** + * Returns header value's string representation. + * + * @return string + */ + public function __toString() + { + $string = $this->value.($this->quality < 1 ? ';q='.$this->quality : ''); + if (\count($this->attributes) > 0) { + $string .= '; '.HeaderUtils::toString($this->attributes, ';'); + } + + return $string; + } + + /** + * Set the item value. + * + * @return $this + */ + public function setValue(string $value) + { + $this->value = $value; + + return $this; + } + + /** + * Returns the item value. + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set the item quality. + * + * @return $this + */ + public function setQuality(float $quality) + { + $this->quality = $quality; + + return $this; + } + + /** + * Returns the item quality. + * + * @return float + */ + public function getQuality() + { + return $this->quality; + } + + /** + * Set the item index. + * + * @return $this + */ + public function setIndex(int $index) + { + $this->index = $index; + + return $this; + } + + /** + * Returns the item index. + * + * @return int + */ + public function getIndex() + { + return $this->index; + } + + /** + * Tests if an attribute exists. + * + * @return bool + */ + public function hasAttribute(string $name) + { + return isset($this->attributes[$name]); + } + + /** + * Returns an attribute by its name. + * + * @param mixed $default + * + * @return mixed + */ + public function getAttribute(string $name, $default = null) + { + return $this->attributes[$name] ?? $default; + } + + /** + * Returns all attributes. + * + * @return array + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Set an attribute. + * + * @return $this + */ + public function setAttribute(string $name, string $value) + { + if ('q' === $name) { + $this->quality = (float) $value; + } else { + $this->attributes[$name] = $value; + } + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/BinaryFileResponse.php b/php/libraries/composer/vendor/symfony/http-foundation/BinaryFileResponse.php new file mode 100644 index 0000000..1878caa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/BinaryFileResponse.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 Symfony\Component\HttpFoundation; + +use Symfony\Component\HttpFoundation\File\Exception\FileException; +use Symfony\Component\HttpFoundation\File\File; + +/** + * BinaryFileResponse represents an HTTP response delivering a file. + * + * @author Niklas Fiekas + * @author stealth35 + * @author Igor Wiedler + * @author Jordan Alliot + * @author Sergey Linnik + */ +class BinaryFileResponse extends Response +{ + protected static $trustXSendfileTypeHeader = false; + + /** + * @var File + */ + protected $file; + protected $offset = 0; + protected $maxlen = -1; + protected $deleteFileAfterSend = false; + protected $chunkSize = 16 * 1024; + + /** + * @param \SplFileInfo|string $file The file to stream + * @param int $status The response status code + * @param array $headers An array of response headers + * @param bool $public Files are public by default + * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename + * @param bool $autoEtag Whether the ETag header should be automatically set + * @param bool $autoLastModified Whether the Last-Modified header should be automatically set + */ + public function __construct($file, int $status = 200, array $headers = [], bool $public = true, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true) + { + parent::__construct(null, $status, $headers); + + $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified); + + if ($public) { + $this->setPublic(); + } + } + + /** + * @param \SplFileInfo|string $file The file to stream + * @param int $status The response status code + * @param array $headers An array of response headers + * @param bool $public Files are public by default + * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename + * @param bool $autoEtag Whether the ETag header should be automatically set + * @param bool $autoLastModified Whether the Last-Modified header should be automatically set + * + * @return static + * + * @deprecated since Symfony 5.2, use __construct() instead. + */ + public static function create($file = null, int $status = 200, array $headers = [], bool $public = true, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true) + { + trigger_deprecation('symfony/http-foundation', '5.2', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class); + + return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified); + } + + /** + * Sets the file to stream. + * + * @param \SplFileInfo|string $file The file to stream + * + * @return $this + * + * @throws FileException + */ + public function setFile($file, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true) + { + if (!$file instanceof File) { + if ($file instanceof \SplFileInfo) { + $file = new File($file->getPathname()); + } else { + $file = new File((string) $file); + } + } + + if (!$file->isReadable()) { + throw new FileException('File must be readable.'); + } + + $this->file = $file; + + if ($autoEtag) { + $this->setAutoEtag(); + } + + if ($autoLastModified) { + $this->setAutoLastModified(); + } + + if ($contentDisposition) { + $this->setContentDisposition($contentDisposition); + } + + return $this; + } + + /** + * Gets the file. + * + * @return File + */ + public function getFile() + { + return $this->file; + } + + /** + * Sets the response stream chunk size. + * + * @return $this + */ + public function setChunkSize(int $chunkSize): self + { + if ($chunkSize < 1 || $chunkSize > \PHP_INT_MAX) { + throw new \LogicException('The chunk size of a BinaryFileResponse cannot be less than 1 or greater than PHP_INT_MAX.'); + } + + $this->chunkSize = $chunkSize; + + return $this; + } + + /** + * Automatically sets the Last-Modified header according the file modification date. + * + * @return $this + */ + public function setAutoLastModified() + { + $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime())); + + return $this; + } + + /** + * Automatically sets the ETag header according to the checksum of the file. + * + * @return $this + */ + public function setAutoEtag() + { + $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true))); + + return $this; + } + + /** + * Sets the Content-Disposition header with the given filename. + * + * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT + * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file + * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename + * + * @return $this + */ + public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '') + { + if ('' === $filename) { + $filename = $this->file->getFilename(); + } + + if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) { + $encoding = mb_detect_encoding($filename, null, true) ?: '8bit'; + + for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) { + $char = mb_substr($filename, $i, 1, $encoding); + + if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) { + $filenameFallback .= '_'; + } else { + $filenameFallback .= $char; + } + } + } + + $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback); + $this->headers->set('Content-Disposition', $dispositionHeader); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function prepare(Request $request) + { + if ($this->isInformational() || $this->isEmpty()) { + parent::prepare($request); + + $this->maxlen = 0; + + return $this; + } + + if (!$this->headers->has('Content-Type')) { + $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream'); + } + + parent::prepare($request); + + $this->offset = 0; + $this->maxlen = -1; + + if (false === $fileSize = $this->file->getSize()) { + return $this; + } + $this->headers->remove('Transfer-Encoding'); + $this->headers->set('Content-Length', $fileSize); + + if (!$this->headers->has('Accept-Ranges')) { + // Only accept ranges on safe HTTP methods + $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none'); + } + + if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) { + // Use X-Sendfile, do not send any content. + $type = $request->headers->get('X-Sendfile-Type'); + $path = $this->file->getRealPath(); + // Fall back to scheme://path for stream wrapped locations. + if (false === $path) { + $path = $this->file->getPathname(); + } + if ('x-accel-redirect' === strtolower($type)) { + // Do X-Accel-Mapping substitutions. + // @link https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect + $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',='); + foreach ($parts as $part) { + [$pathPrefix, $location] = $part; + if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) { + $path = $location.substr($path, \strlen($pathPrefix)); + // Only set X-Accel-Redirect header if a valid URI can be produced + // as nginx does not serve arbitrary file paths. + $this->headers->set($type, $path); + $this->maxlen = 0; + break; + } + } + } else { + $this->headers->set($type, $path); + $this->maxlen = 0; + } + } elseif ($request->headers->has('Range') && $request->isMethod('GET')) { + // Process the range headers. + if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) { + $range = $request->headers->get('Range'); + + if (str_starts_with($range, 'bytes=')) { + [$start, $end] = explode('-', substr($range, 6), 2) + [1 => 0]; + + $end = ('' === $end) ? $fileSize - 1 : (int) $end; + + if ('' === $start) { + $start = $fileSize - $end; + $end = $fileSize - 1; + } else { + $start = (int) $start; + } + + if ($start <= $end) { + $end = min($end, $fileSize - 1); + if ($start < 0 || $start > $end) { + $this->setStatusCode(416); + $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize)); + } elseif ($end - $start < $fileSize - 1) { + $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1; + $this->offset = $start; + + $this->setStatusCode(206); + $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize)); + $this->headers->set('Content-Length', $end - $start + 1); + } + } + } + } + } + + if ($request->isMethod('HEAD')) { + $this->maxlen = 0; + } + + return $this; + } + + private function hasValidIfRangeHeader(?string $header): bool + { + if ($this->getEtag() === $header) { + return true; + } + + if (null === $lastModified = $this->getLastModified()) { + return false; + } + + return $lastModified->format('D, d M Y H:i:s').' GMT' === $header; + } + + /** + * {@inheritdoc} + */ + public function sendContent() + { + try { + if (!$this->isSuccessful()) { + return parent::sendContent(); + } + + if (0 === $this->maxlen) { + return $this; + } + + $out = fopen('php://output', 'w'); + $file = fopen($this->file->getPathname(), 'r'); + + ignore_user_abort(true); + + if (0 !== $this->offset) { + fseek($file, $this->offset); + } + + $length = $this->maxlen; + while ($length && !feof($file)) { + $read = $length > $this->chunkSize || 0 > $length ? $this->chunkSize : $length; + + if (false === $data = fread($file, $read)) { + break; + } + while ('' !== $data) { + $read = fwrite($out, $data); + if (false === $read || connection_aborted()) { + break 2; + } + if (0 < $length) { + $length -= $read; + } + $data = substr($data, $read); + } + } + + fclose($out); + fclose($file); + } finally { + if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) { + unlink($this->file->getPathname()); + } + } + + return $this; + } + + /** + * {@inheritdoc} + * + * @throws \LogicException when the content is not null + */ + public function setContent(?string $content) + { + if (null !== $content) { + throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.'); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getContent() + { + return false; + } + + /** + * Trust X-Sendfile-Type header. + */ + public static function trustXSendfileTypeHeader() + { + self::$trustXSendfileTypeHeader = true; + } + + /** + * If this is set to true, the file will be unlinked after the request is sent + * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used. + * + * @return $this + */ + public function deleteFileAfterSend(bool $shouldDelete = true) + { + $this->deleteFileAfterSend = $shouldDelete; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/CHANGELOG.md b/php/libraries/composer/vendor/symfony/http-foundation/CHANGELOG.md new file mode 100644 index 0000000..ad7607a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/CHANGELOG.md @@ -0,0 +1,296 @@ +CHANGELOG +========= + +5.4 +--- + + * Deprecate passing `null` as `$requestIp` to `IpUtils::__checkIp()`, `IpUtils::__checkIp4()` or `IpUtils::__checkIp6()`, pass an empty string instead. + * Add the `litespeed_finish_request` method to work with Litespeed + * Deprecate `upload_progress.*` and `url_rewriter.tags` session options + * Allow setting session options via DSN + +5.3 +--- + + * Add the `SessionFactory`, `NativeSessionStorageFactory`, `PhpBridgeSessionStorageFactory` and `MockFileSessionStorageFactory` classes + * Calling `Request::getSession()` when there is no available session throws a `SessionNotFoundException` + * Add the `RequestStack::getSession` method + * Deprecate the `NamespacedAttributeBag` class + * Add `ResponseFormatSame` PHPUnit constraint + * Deprecate the `RequestStack::getMasterRequest()` method and add `getMainRequest()` as replacement + +5.2.0 +----- + + * added support for `X-Forwarded-Prefix` header + * added `HeaderUtils::parseQuery()`: it does the same as `parse_str()` but preserves dots in variable names + * added `File::getContent()` + * added ability to use comma separated ip addresses for `RequestMatcher::matchIps()` + * added `Request::toArray()` to parse a JSON request body to an array + * added `RateLimiter\RequestRateLimiterInterface` and `RateLimiter\AbstractRequestRateLimiter` + * deprecated not passing a `Closure` together with `FILTER_CALLBACK` to `ParameterBag::filter()`; wrap your filter in a closure instead. + * Deprecated the `Request::HEADER_X_FORWARDED_ALL` constant, use either `HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO` or `HEADER_X_FORWARDED_AWS_ELB` or `HEADER_X_FORWARDED_TRAEFIK` constants instead. + * Deprecated `BinaryFileResponse::create()`, use `__construct()` instead + +5.1.0 +----- + + * added `Cookie::withValue`, `Cookie::withDomain`, `Cookie::withExpires`, + `Cookie::withPath`, `Cookie::withSecure`, `Cookie::withHttpOnly`, + `Cookie::withRaw`, `Cookie::withSameSite` + * Deprecate `Response::create()`, `JsonResponse::create()`, + `RedirectResponse::create()`, and `StreamedResponse::create()` methods (use + `__construct()` instead) + * added `Request::preferSafeContent()` and `Response::setContentSafe()` to handle "safe" HTTP preference + according to [RFC 8674](https://tools.ietf.org/html/rfc8674) + * made the Mime component an optional dependency + * added `MarshallingSessionHandler`, `IdentityMarshaller` + * made `Session` accept a callback to report when the session is being used + * Add support for all core cache control directives + * Added `Symfony\Component\HttpFoundation\InputBag` + * Deprecated retrieving non-string values using `InputBag::get()`, use `InputBag::all()` if you need access to the collection of values + +5.0.0 +----- + + * made `Cookie` auto-secure and lax by default + * removed classes in the `MimeType` namespace, use the Symfony Mime component instead + * removed method `UploadedFile::getClientSize()` and the related constructor argument + * made `Request::getSession()` throw if the session has not been set before + * removed `Response::HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL` + * passing a null url when instantiating a `RedirectResponse` is not allowed + +4.4.0 +----- + + * passing arguments to `Request::isMethodSafe()` is deprecated. + * `ApacheRequest` is deprecated, use the `Request` class instead. + * passing a third argument to `HeaderBag::get()` is deprecated, use method `all()` instead + * [BC BREAK] `PdoSessionHandler` with MySQL changed the type of the lifetime column, + make sure to run `ALTER TABLE sessions MODIFY sess_lifetime INTEGER UNSIGNED NOT NULL` to + update your database. + * `PdoSessionHandler` now precalculates the expiry timestamp in the lifetime column, + make sure to run `CREATE INDEX EXPIRY ON sessions (sess_lifetime)` to update your database + to speed up garbage collection of expired sessions. + * added `SessionHandlerFactory` to create session handlers with a DSN + * added `IpUtils::anonymize()` to help with GDPR compliance. + +4.3.0 +----- + + * added PHPUnit constraints: `RequestAttributeValueSame`, `ResponseCookieValueSame`, `ResponseHasCookie`, + `ResponseHasHeader`, `ResponseHeaderSame`, `ResponseIsRedirected`, `ResponseIsSuccessful`, and `ResponseStatusCodeSame` + * deprecated `MimeTypeGuesserInterface` and `ExtensionGuesserInterface` in favor of `Symfony\Component\Mime\MimeTypesInterface`. + * deprecated `MimeType` and `MimeTypeExtensionGuesser` in favor of `Symfony\Component\Mime\MimeTypes`. + * deprecated `FileBinaryMimeTypeGuesser` in favor of `Symfony\Component\Mime\FileBinaryMimeTypeGuesser`. + * deprecated `FileinfoMimeTypeGuesser` in favor of `Symfony\Component\Mime\FileinfoMimeTypeGuesser`. + * added `UrlHelper` that allows to get an absolute URL and a relative path for a given path + +4.2.0 +----- + + * the default value of the "$secure" and "$samesite" arguments of Cookie's constructor + will respectively change from "false" to "null" and from "null" to "lax" in Symfony + 5.0, you should define their values explicitly or use "Cookie::create()" instead. + * added `matchPort()` in RequestMatcher + +4.1.3 +----- + + * [BC BREAK] Support for the IIS-only `X_ORIGINAL_URL` and `X_REWRITE_URL` + HTTP headers has been dropped for security reasons. + +4.1.0 +----- + + * Query string normalization uses `parse_str()` instead of custom parsing logic. + * Passing the file size to the constructor of the `UploadedFile` class is deprecated. + * The `getClientSize()` method of the `UploadedFile` class is deprecated. Use `getSize()` instead. + * added `RedisSessionHandler` to use Redis as a session storage + * The `get()` method of the `AcceptHeader` class now takes into account the + `*` and `*/*` default values (if they are present in the Accept HTTP header) + when looking for items. + * deprecated `Request::getSession()` when no session has been set. Use `Request::hasSession()` instead. + * added `CannotWriteFileException`, `ExtensionFileException`, `FormSizeFileException`, + `IniSizeFileException`, `NoFileException`, `NoTmpDirFileException`, `PartialFileException` to + handle failed `UploadedFile`. + * added `MigratingSessionHandler` for migrating between two session handlers without losing sessions + * added `HeaderUtils`. + +4.0.0 +----- + + * the `Request::setTrustedHeaderName()` and `Request::getTrustedHeaderName()` + methods have been removed + * the `Request::HEADER_CLIENT_IP` constant has been removed, use + `Request::HEADER_X_FORWARDED_FOR` instead + * the `Request::HEADER_CLIENT_HOST` constant has been removed, use + `Request::HEADER_X_FORWARDED_HOST` instead + * the `Request::HEADER_CLIENT_PROTO` constant has been removed, use + `Request::HEADER_X_FORWARDED_PROTO` instead + * the `Request::HEADER_CLIENT_PORT` constant has been removed, use + `Request::HEADER_X_FORWARDED_PORT` instead + * checking for cacheable HTTP methods using the `Request::isMethodSafe()` + method (by not passing `false` as its argument) is not supported anymore and + throws a `\BadMethodCallException` + * the `WriteCheckSessionHandler`, `NativeSessionHandler` and `NativeProxy` classes have been removed + * setting session save handlers that do not implement `\SessionHandlerInterface` in + `NativeSessionStorage::setSaveHandler()` is not supported anymore and throws a + `\TypeError` + +3.4.0 +----- + + * implemented PHP 7.0's `SessionUpdateTimestampHandlerInterface` with a new + `AbstractSessionHandler` base class and a new `StrictSessionHandler` wrapper + * deprecated the `WriteCheckSessionHandler`, `NativeSessionHandler` and `NativeProxy` classes + * deprecated setting session save handlers that do not implement `\SessionHandlerInterface` in `NativeSessionStorage::setSaveHandler()` + * deprecated using `MongoDbSessionHandler` with the legacy mongo extension; use it with the mongodb/mongodb package and ext-mongodb instead + * deprecated `MemcacheSessionHandler`; use `MemcachedSessionHandler` instead + +3.3.0 +----- + + * the `Request::setTrustedProxies()` method takes a new `$trustedHeaderSet` argument, + see https://symfony.com/doc/current/deployment/proxies.html for more info, + * deprecated the `Request::setTrustedHeaderName()` and `Request::getTrustedHeaderName()` methods, + * added `File\Stream`, to be passed to `BinaryFileResponse` when the size of the served file is unknown, + disabling `Range` and `Content-Length` handling, switching to chunked encoding instead + * added the `Cookie::fromString()` method that allows to create a cookie from a + raw header string + +3.1.0 +----- + + * Added support for creating `JsonResponse` with a string of JSON data + +3.0.0 +----- + + * The precedence of parameters returned from `Request::get()` changed from "GET, PATH, BODY" to "PATH, GET, BODY" + +2.8.0 +----- + + * Finding deep items in `ParameterBag::get()` is deprecated since version 2.8 and + will be removed in 3.0. + +2.6.0 +----- + + * PdoSessionHandler changes + - implemented different session locking strategies to prevent loss of data by concurrent access to the same session + - [BC BREAK] save session data in a binary column without base64_encode + - [BC BREAK] added lifetime column to the session table which allows to have different lifetimes for each session + - implemented lazy connections that are only opened when a session is used by either passing a dsn string + explicitly or falling back to session.save_path ini setting + - added a createTable method that initializes a correctly defined table depending on the database vendor + +2.5.0 +----- + + * added `JsonResponse::setEncodingOptions()` & `JsonResponse::getEncodingOptions()` for easier manipulation + of the options used while encoding data to JSON format. + +2.4.0 +----- + + * added RequestStack + * added Request::getEncodings() + * added accessors methods to session handlers + +2.3.0 +----- + + * added support for ranges of IPs in trusted proxies + * `UploadedFile::isValid` now returns false if the file was not uploaded via HTTP (in a non-test mode) + * Improved error-handling of `\Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler` + to ensure the supplied PDO handler throws Exceptions on error (as the class expects). Added related test cases + to verify that Exceptions are properly thrown when the PDO queries fail. + +2.2.0 +----- + + * fixed the Request::create() precedence (URI information always take precedence now) + * added Request::getTrustedProxies() + * deprecated Request::isProxyTrusted() + * [BC BREAK] JsonResponse does not turn a top level empty array to an object anymore, use an ArrayObject to enforce objects + * added a IpUtils class to check if an IP belongs to a CIDR + * added Request::getRealMethod() to get the "real" HTTP method (getMethod() returns the "intended" HTTP method) + * disabled _method request parameter support by default (call Request::enableHttpMethodParameterOverride() to + enable it, and Request::getHttpMethodParameterOverride() to check if it is supported) + * Request::splitHttpAcceptHeader() method is deprecated and will be removed in 2.3 + * Deprecated Flashbag::count() and \Countable interface, will be removed in 2.3 + +2.1.0 +----- + + * added Request::getSchemeAndHttpHost() and Request::getUserInfo() + * added a fluent interface to the Response class + * added Request::isProxyTrusted() + * added JsonResponse + * added a getTargetUrl method to RedirectResponse + * added support for streamed responses + * made Response::prepare() method the place to enforce HTTP specification + * [BC BREAK] moved management of the locale from the Session class to the Request class + * added a generic access to the PHP built-in filter mechanism: ParameterBag::filter() + * made FileBinaryMimeTypeGuesser command configurable + * added Request::getUser() and Request::getPassword() + * added support for the PATCH method in Request + * removed the ContentTypeMimeTypeGuesser class as it is deprecated and never used on PHP 5.3 + * added ResponseHeaderBag::makeDisposition() (implements RFC 6266) + * made mimetype to extension conversion configurable + * [BC BREAK] Moved all session related classes and interfaces into own namespace, as + `Symfony\Component\HttpFoundation\Session` and renamed classes accordingly. + Session handlers are located in the subnamespace `Symfony\Component\HttpFoundation\Session\Handler`. + * SessionHandlers must implement `\SessionHandlerInterface` or extend from the + `Symfony\Component\HttpFoundation\Storage\Handler\NativeSessionHandler` base class. + * Added internal storage driver proxy mechanism for forward compatibility with + PHP 5.4 `\SessionHandler` class. + * Added session handlers for custom Memcache, Memcached and Null session save handlers. + * [BC BREAK] Removed `NativeSessionStorage` and replaced with `NativeFileSessionHandler`. + * [BC BREAK] `SessionStorageInterface` methods removed: `write()`, `read()` and + `remove()`. Added `getBag()`, `registerBag()`. The `NativeSessionStorage` class + is a mediator for the session storage internals including the session handlers + which do the real work of participating in the internal PHP session workflow. + * [BC BREAK] Introduced mock implementations of `SessionStorage` to enable unit + and functional testing without starting real PHP sessions. Removed + `ArraySessionStorage`, and replaced with `MockArraySessionStorage` for unit + tests; removed `FilesystemSessionStorage`, and replaced with`MockFileSessionStorage` + for functional tests. These do not interact with global session ini + configuration values, session functions or `$_SESSION` superglobal. This means + they can be configured directly allowing multiple instances to work without + conflicting in the same PHP process. + * [BC BREAK] Removed the `close()` method from the `Session` class, as this is + now redundant. + * Deprecated the following methods from the Session class: `setFlash()`, `setFlashes()` + `getFlash()`, `hasFlash()`, and `removeFlash()`. Use `getFlashBag()` instead + which returns a `FlashBagInterface`. + * `Session->clear()` now only clears session attributes as before it cleared + flash messages and attributes. `Session->getFlashBag()->all()` clears flashes now. + * Session data is now managed by `SessionBagInterface` to better encapsulate + session data. + * Refactored session attribute and flash messages system to their own + `SessionBagInterface` implementations. + * Added `FlashBag`. Flashes expire when retrieved by `get()` or `all()`. This + implementation is ESI compatible. + * Added `AutoExpireFlashBag` (default) to replicate Symfony 2.0.x auto expire + behavior of messages auto expiring after one page page load. Messages must + be retrieved by `get()` or `all()`. + * Added `Symfony\Component\HttpFoundation\Attribute\AttributeBag` to replicate + attributes storage behavior from 2.0.x (default). + * Added `Symfony\Component\HttpFoundation\Attribute\NamespacedAttributeBag` for + namespace session attributes. + * Flash API can stores messages in an array so there may be multiple messages + per flash type. The old `Session` class API remains without BC break as it + will allow single messages as before. + * Added basic session meta-data to the session to record session create time, + last updated time, and the lifetime of the session cookie that was provided + to the client. + * Request::getClientIp() method doesn't take a parameter anymore but bases + itself on the trustProxy parameter. + * Added isMethod() to Request object. + * [BC BREAK] The methods `getPathInfo()`, `getBaseUrl()` and `getBasePath()` of + a `Request` now all return a raw value (vs a urldecoded value before). Any call + to one of these methods must be checked and wrapped in a `rawurldecode()` if + needed. diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Cookie.php b/php/libraries/composer/vendor/symfony/http-foundation/Cookie.php new file mode 100644 index 0000000..3ff93b9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Cookie.php @@ -0,0 +1,422 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * Represents a cookie. + * + * @author Johannes M. Schmitt + */ +class Cookie +{ + public const SAMESITE_NONE = 'none'; + public const SAMESITE_LAX = 'lax'; + public const SAMESITE_STRICT = 'strict'; + + protected $name; + protected $value; + protected $domain; + protected $expire; + protected $path; + protected $secure; + protected $httpOnly; + + private $raw; + private $sameSite; + private $secureDefault = false; + + private const RESERVED_CHARS_LIST = "=,; \t\r\n\v\f"; + private const RESERVED_CHARS_FROM = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"]; + private const RESERVED_CHARS_TO = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C']; + + /** + * Creates cookie from raw header string. + * + * @return static + */ + public static function fromString(string $cookie, bool $decode = false) + { + $data = [ + 'expires' => 0, + 'path' => '/', + 'domain' => null, + 'secure' => false, + 'httponly' => false, + 'raw' => !$decode, + 'samesite' => null, + ]; + + $parts = HeaderUtils::split($cookie, ';='); + $part = array_shift($parts); + + $name = $decode ? urldecode($part[0]) : $part[0]; + $value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null; + + $data = HeaderUtils::combine($parts) + $data; + $data['expires'] = self::expiresTimestamp($data['expires']); + + if (isset($data['max-age']) && ($data['max-age'] > 0 || $data['expires'] > time())) { + $data['expires'] = time() + (int) $data['max-age']; + } + + return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']); + } + + public static function create(string $name, ?string $value = null, $expire = 0, ?string $path = '/', ?string $domain = null, ?bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX): self + { + return new self($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite); + } + + /** + * @param string $name The name of the cookie + * @param string|null $value The value of the cookie + * @param int|string|\DateTimeInterface $expire The time the cookie expires + * @param string|null $path The path on the server in which the cookie will be available on + * @param string|null $domain The domain that the cookie is available to + * @param bool|null $secure Whether the client should send back the cookie only over HTTPS or null to auto-enable this when the request is already using HTTPS + * @param bool $httpOnly Whether the cookie will be made accessible only through the HTTP protocol + * @param bool $raw Whether the cookie value should be sent with no url encoding + * @param string|null $sameSite Whether the cookie will be available for cross-site requests + * + * @throws \InvalidArgumentException + */ + public function __construct(string $name, ?string $value = null, $expire = 0, ?string $path = '/', ?string $domain = null, ?bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = 'lax') + { + // from PHP source code + if ($raw && false !== strpbrk($name, self::RESERVED_CHARS_LIST)) { + throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name)); + } + + if (empty($name)) { + throw new \InvalidArgumentException('The cookie name cannot be empty.'); + } + + $this->name = $name; + $this->value = $value; + $this->domain = $domain; + $this->expire = self::expiresTimestamp($expire); + $this->path = empty($path) ? '/' : $path; + $this->secure = $secure; + $this->httpOnly = $httpOnly; + $this->raw = $raw; + $this->sameSite = $this->withSameSite($sameSite)->sameSite; + } + + /** + * Creates a cookie copy with a new value. + * + * @return static + */ + public function withValue(?string $value): self + { + $cookie = clone $this; + $cookie->value = $value; + + return $cookie; + } + + /** + * Creates a cookie copy with a new domain that the cookie is available to. + * + * @return static + */ + public function withDomain(?string $domain): self + { + $cookie = clone $this; + $cookie->domain = $domain; + + return $cookie; + } + + /** + * Creates a cookie copy with a new time the cookie expires. + * + * @param int|string|\DateTimeInterface $expire + * + * @return static + */ + public function withExpires($expire = 0): self + { + $cookie = clone $this; + $cookie->expire = self::expiresTimestamp($expire); + + return $cookie; + } + + /** + * Converts expires formats to a unix timestamp. + * + * @param int|string|\DateTimeInterface $expire + */ + private static function expiresTimestamp($expire = 0): int + { + // convert expiration time to a Unix timestamp + if ($expire instanceof \DateTimeInterface) { + $expire = $expire->format('U'); + } elseif (!is_numeric($expire)) { + $expire = strtotime($expire); + + if (false === $expire) { + throw new \InvalidArgumentException('The cookie expiration time is not valid.'); + } + } + + return 0 < $expire ? (int) $expire : 0; + } + + /** + * Creates a cookie copy with a new path on the server in which the cookie will be available on. + * + * @return static + */ + public function withPath(string $path): self + { + $cookie = clone $this; + $cookie->path = '' === $path ? '/' : $path; + + return $cookie; + } + + /** + * Creates a cookie copy that only be transmitted over a secure HTTPS connection from the client. + * + * @return static + */ + public function withSecure(bool $secure = true): self + { + $cookie = clone $this; + $cookie->secure = $secure; + + return $cookie; + } + + /** + * Creates a cookie copy that be accessible only through the HTTP protocol. + * + * @return static + */ + public function withHttpOnly(bool $httpOnly = true): self + { + $cookie = clone $this; + $cookie->httpOnly = $httpOnly; + + return $cookie; + } + + /** + * Creates a cookie copy that uses no url encoding. + * + * @return static + */ + public function withRaw(bool $raw = true): self + { + if ($raw && false !== strpbrk($this->name, self::RESERVED_CHARS_LIST)) { + throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $this->name)); + } + + $cookie = clone $this; + $cookie->raw = $raw; + + return $cookie; + } + + /** + * Creates a cookie copy with SameSite attribute. + * + * @return static + */ + public function withSameSite(?string $sameSite): self + { + if ('' === $sameSite) { + $sameSite = null; + } elseif (null !== $sameSite) { + $sameSite = strtolower($sameSite); + } + + if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) { + throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.'); + } + + $cookie = clone $this; + $cookie->sameSite = $sameSite; + + return $cookie; + } + + /** + * Returns the cookie as a string. + * + * @return string + */ + public function __toString() + { + if ($this->isRaw()) { + $str = $this->getName(); + } else { + $str = str_replace(self::RESERVED_CHARS_FROM, self::RESERVED_CHARS_TO, $this->getName()); + } + + $str .= '='; + + if ('' === (string) $this->getValue()) { + $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0'; + } else { + $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue()); + + if (0 !== $this->getExpiresTime()) { + $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge(); + } + } + + if ($this->getPath()) { + $str .= '; path='.$this->getPath(); + } + + if ($this->getDomain()) { + $str .= '; domain='.$this->getDomain(); + } + + if (true === $this->isSecure()) { + $str .= '; secure'; + } + + if (true === $this->isHttpOnly()) { + $str .= '; httponly'; + } + + if (null !== $this->getSameSite()) { + $str .= '; samesite='.$this->getSameSite(); + } + + return $str; + } + + /** + * Gets the name of the cookie. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Gets the value of the cookie. + * + * @return string|null + */ + public function getValue() + { + return $this->value; + } + + /** + * Gets the domain that the cookie is available to. + * + * @return string|null + */ + public function getDomain() + { + return $this->domain; + } + + /** + * Gets the time the cookie expires. + * + * @return int + */ + public function getExpiresTime() + { + return $this->expire; + } + + /** + * Gets the max-age attribute. + * + * @return int + */ + public function getMaxAge() + { + $maxAge = $this->expire - time(); + + return 0 >= $maxAge ? 0 : $maxAge; + } + + /** + * Gets the path on the server in which the cookie will be available on. + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client. + * + * @return bool + */ + public function isSecure() + { + return $this->secure ?? $this->secureDefault; + } + + /** + * Checks whether the cookie will be made accessible only through the HTTP protocol. + * + * @return bool + */ + public function isHttpOnly() + { + return $this->httpOnly; + } + + /** + * Whether this cookie is about to be cleared. + * + * @return bool + */ + public function isCleared() + { + return 0 !== $this->expire && $this->expire < time(); + } + + /** + * Checks if the cookie value should be sent with no url encoding. + * + * @return bool + */ + public function isRaw() + { + return $this->raw; + } + + /** + * Gets the SameSite attribute. + * + * @return string|null + */ + public function getSameSite() + { + return $this->sameSite; + } + + /** + * @param bool $default The default value of the "secure" flag when it is set to null + */ + public function setSecureDefault(bool $default): void + { + $this->secureDefault = $default; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Exception/BadRequestException.php b/php/libraries/composer/vendor/symfony/http-foundation/Exception/BadRequestException.php new file mode 100644 index 0000000..e4bb309 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Exception/BadRequestException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Exception; + +/** + * Raised when a user sends a malformed request. + */ +class BadRequestException extends \UnexpectedValueException implements RequestExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Exception/ConflictingHeadersException.php b/php/libraries/composer/vendor/symfony/http-foundation/Exception/ConflictingHeadersException.php new file mode 100644 index 0000000..5fcf5b4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Exception/ConflictingHeadersException.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\HttpFoundation\Exception; + +/** + * The HTTP request contains headers with conflicting information. + * + * @author Magnus Nordlander + */ +class ConflictingHeadersException extends \UnexpectedValueException implements RequestExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Exception/JsonException.php b/php/libraries/composer/vendor/symfony/http-foundation/Exception/JsonException.php new file mode 100644 index 0000000..5990e76 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Exception/JsonException.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\HttpFoundation\Exception; + +/** + * Thrown by Request::toArray() when the content cannot be JSON-decoded. + * + * @author Tobias Nyholm + */ +final class JsonException extends \UnexpectedValueException implements RequestExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Exception/RequestExceptionInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Exception/RequestExceptionInterface.php new file mode 100644 index 0000000..478d0dc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Exception/RequestExceptionInterface.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\HttpFoundation\Exception; + +/** + * Interface for Request exceptions. + * + * Exceptions implementing this interface should trigger an HTTP 400 response in the application code. + */ +interface RequestExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Exception/SessionNotFoundException.php b/php/libraries/composer/vendor/symfony/http-foundation/Exception/SessionNotFoundException.php new file mode 100644 index 0000000..80a21bf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Exception/SessionNotFoundException.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Exception; + +/** + * Raised when a session does not exist. This happens in the following cases: + * - the session is not enabled + * - attempt to read a session outside a request context (ie. cli script). + * + * @author Jérémy Derussé + */ +class SessionNotFoundException extends \LogicException implements RequestExceptionInterface +{ + public function __construct(string $message = 'There is currently no session available.', int $code = 0, ?\Throwable $previous = null) + { + parent::__construct($message, $code, $previous); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Exception/SuspiciousOperationException.php b/php/libraries/composer/vendor/symfony/http-foundation/Exception/SuspiciousOperationException.php new file mode 100644 index 0000000..ae7a5f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Exception/SuspiciousOperationException.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\HttpFoundation\Exception; + +/** + * Raised when a user has performed an operation that should be considered + * suspicious from a security perspective. + */ +class SuspiciousOperationException extends \UnexpectedValueException implements RequestExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/ExpressionRequestMatcher.php b/php/libraries/composer/vendor/symfony/http-foundation/ExpressionRequestMatcher.php new file mode 100644 index 0000000..26bed7d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/ExpressionRequestMatcher.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +use Symfony\Component\ExpressionLanguage\ExpressionLanguage; + +/** + * ExpressionRequestMatcher uses an expression to match a Request. + * + * @author Fabien Potencier + */ +class ExpressionRequestMatcher extends RequestMatcher +{ + private $language; + private $expression; + + public function setExpression(ExpressionLanguage $language, $expression) + { + $this->language = $language; + $this->expression = $expression; + } + + public function matches(Request $request) + { + if (!$this->language) { + throw new \LogicException('Unable to match the request as the expression language is not available.'); + } + + return $this->language->evaluate($this->expression, [ + 'request' => $request, + 'method' => $request->getMethod(), + 'path' => rawurldecode($request->getPathInfo()), + 'host' => $request->getHost(), + 'ip' => $request->getClientIp(), + 'attributes' => $request->attributes->all(), + ]) && parent::matches($request); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/AccessDeniedException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/AccessDeniedException.php new file mode 100644 index 0000000..136d2a9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/AccessDeniedException.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\File\Exception; + +/** + * Thrown when the access on a file was denied. + * + * @author Bernhard Schussek + */ +class AccessDeniedException extends FileException +{ + public function __construct(string $path) + { + parent::__construct(sprintf('The file %s could not be accessed', $path)); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/CannotWriteFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/CannotWriteFileException.php new file mode 100644 index 0000000..c49f53a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/CannotWriteFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_CANT_WRITE error occurred with UploadedFile. + * + * @author Florent Mata + */ +class CannotWriteFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/ExtensionFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/ExtensionFileException.php new file mode 100644 index 0000000..ed83499 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/ExtensionFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_EXTENSION error occurred with UploadedFile. + * + * @author Florent Mata + */ +class ExtensionFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FileException.php new file mode 100644 index 0000000..fad5133 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an error occurred in the component File. + * + * @author Bernhard Schussek + */ +class FileException extends \RuntimeException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FileNotFoundException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FileNotFoundException.php new file mode 100644 index 0000000..31bdf68 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FileNotFoundException.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\File\Exception; + +/** + * Thrown when a file was not found. + * + * @author Bernhard Schussek + */ +class FileNotFoundException extends FileException +{ + public function __construct(string $path) + { + parent::__construct(sprintf('The file "%s" does not exist', $path)); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FormSizeFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FormSizeFileException.php new file mode 100644 index 0000000..8741be0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/FormSizeFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_FORM_SIZE error occurred with UploadedFile. + * + * @author Florent Mata + */ +class FormSizeFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/IniSizeFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/IniSizeFileException.php new file mode 100644 index 0000000..c8fde61 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/IniSizeFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_INI_SIZE error occurred with UploadedFile. + * + * @author Florent Mata + */ +class IniSizeFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/NoFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/NoFileException.php new file mode 100644 index 0000000..4b48cc7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/NoFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_NO_FILE error occurred with UploadedFile. + * + * @author Florent Mata + */ +class NoFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/NoTmpDirFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/NoTmpDirFileException.php new file mode 100644 index 0000000..bdead2d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/NoTmpDirFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_NO_TMP_DIR error occurred with UploadedFile. + * + * @author Florent Mata + */ +class NoTmpDirFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/PartialFileException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/PartialFileException.php new file mode 100644 index 0000000..4641efb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/PartialFileException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an UPLOAD_ERR_PARTIAL error occurred with UploadedFile. + * + * @author Florent Mata + */ +class PartialFileException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/UnexpectedTypeException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/UnexpectedTypeException.php new file mode 100644 index 0000000..8533f99 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/UnexpectedTypeException.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\HttpFoundation\File\Exception; + +class UnexpectedTypeException extends FileException +{ + public function __construct($value, string $expectedType) + { + parent::__construct(sprintf('Expected argument of type %s, %s given', $expectedType, get_debug_type($value))); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/UploadException.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/UploadException.php new file mode 100644 index 0000000..7074e76 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Exception/UploadException.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\HttpFoundation\File\Exception; + +/** + * Thrown when an error occurred during file upload. + * + * @author Bernhard Schussek + */ +class UploadException extends FileException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/File.php b/php/libraries/composer/vendor/symfony/http-foundation/File/File.php new file mode 100644 index 0000000..2deb53d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/File.php @@ -0,0 +1,152 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\File; + +use Symfony\Component\HttpFoundation\File\Exception\FileException; +use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException; +use Symfony\Component\Mime\MimeTypes; + +/** + * A file in the file system. + * + * @author Bernhard Schussek + */ +class File extends \SplFileInfo +{ + /** + * Constructs a new file from the given path. + * + * @param string $path The path to the file + * @param bool $checkPath Whether to check the path or not + * + * @throws FileNotFoundException If the given path is not a file + */ + public function __construct(string $path, bool $checkPath = true) + { + if ($checkPath && !is_file($path)) { + throw new FileNotFoundException($path); + } + + parent::__construct($path); + } + + /** + * Returns the extension based on the mime type. + * + * If the mime type is unknown, returns null. + * + * This method uses the mime type as guessed by getMimeType() + * to guess the file extension. + * + * @return string|null + * + * @see MimeTypes + * @see getMimeType() + */ + public function guessExtension() + { + if (!class_exists(MimeTypes::class)) { + throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".'); + } + + return MimeTypes::getDefault()->getExtensions($this->getMimeType())[0] ?? null; + } + + /** + * Returns the mime type of the file. + * + * The mime type is guessed using a MimeTypeGuesserInterface instance, + * which uses finfo_file() then the "file" system binary, + * depending on which of those are available. + * + * @return string|null + * + * @see MimeTypes + */ + public function getMimeType() + { + if (!class_exists(MimeTypes::class)) { + throw new \LogicException('You cannot guess the mime type as the Mime component is not installed. Try running "composer require symfony/mime".'); + } + + return MimeTypes::getDefault()->guessMimeType($this->getPathname()); + } + + /** + * Moves the file to a new location. + * + * @return self + * + * @throws FileException if the target file could not be created + */ + public function move(string $directory, ?string $name = null) + { + $target = $this->getTargetFile($directory, $name); + + set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); + try { + $renamed = rename($this->getPathname(), $target); + } finally { + restore_error_handler(); + } + if (!$renamed) { + throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s).', $this->getPathname(), $target, strip_tags($error))); + } + + @chmod($target, 0666 & ~umask()); + + return $target; + } + + public function getContent(): string + { + $content = file_get_contents($this->getPathname()); + + if (false === $content) { + throw new FileException(sprintf('Could not get the content of the file "%s".', $this->getPathname())); + } + + return $content; + } + + /** + * @return self + */ + protected function getTargetFile(string $directory, ?string $name = null) + { + if (!is_dir($directory)) { + if (false === @mkdir($directory, 0777, true) && !is_dir($directory)) { + throw new FileException(sprintf('Unable to create the "%s" directory.', $directory)); + } + } elseif (!is_writable($directory)) { + throw new FileException(sprintf('Unable to write in the "%s" directory.', $directory)); + } + + $target = rtrim($directory, '/\\').\DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name)); + + return new self($target, false); + } + + /** + * Returns locale independent base name of the given path. + * + * @return string + */ + protected function getName(string $name) + { + $originalName = str_replace('\\', '/', $name); + $pos = strrpos($originalName, '/'); + $originalName = false === $pos ? $originalName : substr($originalName, $pos + 1); + + return $originalName; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/Stream.php b/php/libraries/composer/vendor/symfony/http-foundation/File/Stream.php new file mode 100644 index 0000000..cef3e03 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/Stream.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\File; + +/** + * A PHP stream of unknown size. + * + * @author Nicolas Grekas + */ +class Stream extends File +{ + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function getSize() + { + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/File/UploadedFile.php b/php/libraries/composer/vendor/symfony/http-foundation/File/UploadedFile.php new file mode 100644 index 0000000..6ff6e51 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/File/UploadedFile.php @@ -0,0 +1,290 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\File; + +use Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException; +use Symfony\Component\HttpFoundation\File\Exception\ExtensionFileException; +use Symfony\Component\HttpFoundation\File\Exception\FileException; +use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException; +use Symfony\Component\HttpFoundation\File\Exception\FormSizeFileException; +use Symfony\Component\HttpFoundation\File\Exception\IniSizeFileException; +use Symfony\Component\HttpFoundation\File\Exception\NoFileException; +use Symfony\Component\HttpFoundation\File\Exception\NoTmpDirFileException; +use Symfony\Component\HttpFoundation\File\Exception\PartialFileException; +use Symfony\Component\Mime\MimeTypes; + +/** + * A file uploaded through a form. + * + * @author Bernhard Schussek + * @author Florian Eckerstorfer + * @author Fabien Potencier + */ +class UploadedFile extends File +{ + private $test; + private $originalName; + private $mimeType; + private $error; + + /** + * Accepts the information of the uploaded file as provided by the PHP global $_FILES. + * + * The file object is only created when the uploaded file is valid (i.e. when the + * isValid() method returns true). Otherwise the only methods that could be called + * on an UploadedFile instance are: + * + * * getClientOriginalName, + * * getClientMimeType, + * * isValid, + * * getError. + * + * Calling any other method on an non-valid instance will cause an unpredictable result. + * + * @param string $path The full temporary path to the file + * @param string $originalName The original file name of the uploaded file + * @param string|null $mimeType The type of the file as provided by PHP; null defaults to application/octet-stream + * @param int|null $error The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK + * @param bool $test Whether the test mode is active + * Local files are used in test mode hence the code should not enforce HTTP uploads + * + * @throws FileException If file_uploads is disabled + * @throws FileNotFoundException If the file does not exist + */ + public function __construct(string $path, string $originalName, ?string $mimeType = null, ?int $error = null, bool $test = false) + { + $this->originalName = $this->getName($originalName); + $this->mimeType = $mimeType ?: 'application/octet-stream'; + $this->error = $error ?: \UPLOAD_ERR_OK; + $this->test = $test; + + parent::__construct($path, \UPLOAD_ERR_OK === $this->error); + } + + /** + * Returns the original file name. + * + * It is extracted from the request from which the file has been uploaded. + * This should not be considered as a safe value to use for a file name on your servers. + * + * @return string + */ + public function getClientOriginalName() + { + return $this->originalName; + } + + /** + * Returns the original file extension. + * + * It is extracted from the original file name that was uploaded. + * This should not be considered as a safe value to use for a file name on your servers. + * + * @return string + */ + public function getClientOriginalExtension() + { + return pathinfo($this->originalName, \PATHINFO_EXTENSION); + } + + /** + * Returns the file mime type. + * + * The client mime type is extracted from the request from which the file + * was uploaded, so it should not be considered as a safe value. + * + * For a trusted mime type, use getMimeType() instead (which guesses the mime + * type based on the file content). + * + * @return string + * + * @see getMimeType() + */ + public function getClientMimeType() + { + return $this->mimeType; + } + + /** + * Returns the extension based on the client mime type. + * + * If the mime type is unknown, returns null. + * + * This method uses the mime type as guessed by getClientMimeType() + * to guess the file extension. As such, the extension returned + * by this method cannot be trusted. + * + * For a trusted extension, use guessExtension() instead (which guesses + * the extension based on the guessed mime type for the file). + * + * @return string|null + * + * @see guessExtension() + * @see getClientMimeType() + */ + public function guessClientExtension() + { + if (!class_exists(MimeTypes::class)) { + throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".'); + } + + return MimeTypes::getDefault()->getExtensions($this->getClientMimeType())[0] ?? null; + } + + /** + * Returns the upload error. + * + * If the upload was successful, the constant UPLOAD_ERR_OK is returned. + * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. + * + * @return int + */ + public function getError() + { + return $this->error; + } + + /** + * Returns whether the file has been uploaded with HTTP and no error occurred. + * + * @return bool + */ + public function isValid() + { + $isOk = \UPLOAD_ERR_OK === $this->error; + + return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname()); + } + + /** + * Moves the file to a new location. + * + * @return File + * + * @throws FileException if, for any reason, the file could not have been moved + */ + public function move(string $directory, ?string $name = null) + { + if ($this->isValid()) { + if ($this->test) { + return parent::move($directory, $name); + } + + $target = $this->getTargetFile($directory, $name); + + set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); + try { + $moved = move_uploaded_file($this->getPathname(), $target); + } finally { + restore_error_handler(); + } + if (!$moved) { + throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s).', $this->getPathname(), $target, strip_tags($error))); + } + + @chmod($target, 0666 & ~umask()); + + return $target; + } + + switch ($this->error) { + case \UPLOAD_ERR_INI_SIZE: + throw new IniSizeFileException($this->getErrorMessage()); + case \UPLOAD_ERR_FORM_SIZE: + throw new FormSizeFileException($this->getErrorMessage()); + case \UPLOAD_ERR_PARTIAL: + throw new PartialFileException($this->getErrorMessage()); + case \UPLOAD_ERR_NO_FILE: + throw new NoFileException($this->getErrorMessage()); + case \UPLOAD_ERR_CANT_WRITE: + throw new CannotWriteFileException($this->getErrorMessage()); + case \UPLOAD_ERR_NO_TMP_DIR: + throw new NoTmpDirFileException($this->getErrorMessage()); + case \UPLOAD_ERR_EXTENSION: + throw new ExtensionFileException($this->getErrorMessage()); + } + + throw new FileException($this->getErrorMessage()); + } + + /** + * Returns the maximum size of an uploaded file as configured in php.ini. + * + * @return int|float The maximum size of an uploaded file in bytes (returns float if size > PHP_INT_MAX) + */ + public static function getMaxFilesize() + { + $sizePostMax = self::parseFilesize(\ini_get('post_max_size')); + $sizeUploadMax = self::parseFilesize(\ini_get('upload_max_filesize')); + + return min($sizePostMax ?: \PHP_INT_MAX, $sizeUploadMax ?: \PHP_INT_MAX); + } + + /** + * Returns the given size from an ini value in bytes. + * + * @return int|float Returns float if size > PHP_INT_MAX + */ + private static function parseFilesize(string $size) + { + if ('' === $size) { + return 0; + } + + $size = strtolower($size); + + $max = ltrim($size, '+'); + if (str_starts_with($max, '0x')) { + $max = \intval($max, 16); + } elseif (str_starts_with($max, '0')) { + $max = \intval($max, 8); + } else { + $max = (int) $max; + } + + switch (substr($size, -1)) { + case 't': $max *= 1024; + // no break + case 'g': $max *= 1024; + // no break + case 'm': $max *= 1024; + // no break + case 'k': $max *= 1024; + } + + return $max; + } + + /** + * Returns an informative upload error message. + * + * @return string + */ + public function getErrorMessage() + { + static $errors = [ + \UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).', + \UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', + \UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', + \UPLOAD_ERR_NO_FILE => 'No file was uploaded.', + \UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', + \UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', + \UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.', + ]; + + $errorCode = $this->error; + $maxFilesize = \UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0; + $message = $errors[$errorCode] ?? 'The file "%s" was not uploaded due to an unknown error.'; + + return sprintf($message, $this->getClientOriginalName(), $maxFilesize); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/FileBag.php b/php/libraries/composer/vendor/symfony/http-foundation/FileBag.php new file mode 100644 index 0000000..ff5ab77 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/FileBag.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\HttpFoundation; + +use Symfony\Component\HttpFoundation\File\UploadedFile; + +/** + * FileBag is a container for uploaded files. + * + * @author Fabien Potencier + * @author Bulat Shakirzyanov + */ +class FileBag extends ParameterBag +{ + private const FILE_KEYS = ['error', 'name', 'size', 'tmp_name', 'type']; + + /** + * @param array|UploadedFile[] $parameters An array of HTTP files + */ + public function __construct(array $parameters = []) + { + $this->replace($parameters); + } + + /** + * {@inheritdoc} + */ + public function replace(array $files = []) + { + $this->parameters = []; + $this->add($files); + } + + /** + * {@inheritdoc} + */ + public function set(string $key, $value) + { + if (!\is_array($value) && !$value instanceof UploadedFile) { + throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.'); + } + + parent::set($key, $this->convertFileInformation($value)); + } + + /** + * {@inheritdoc} + */ + public function add(array $files = []) + { + foreach ($files as $key => $file) { + $this->set($key, $file); + } + } + + /** + * Converts uploaded files to UploadedFile instances. + * + * @param array|UploadedFile $file A (multi-dimensional) array of uploaded file information + * + * @return UploadedFile[]|UploadedFile|null + */ + protected function convertFileInformation($file) + { + if ($file instanceof UploadedFile) { + return $file; + } + + $file = $this->fixPhpFilesArray($file); + $keys = array_keys($file); + sort($keys); + + if (self::FILE_KEYS == $keys) { + if (\UPLOAD_ERR_NO_FILE == $file['error']) { + $file = null; + } else { + $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error'], false); + } + } else { + $file = array_map(function ($v) { return $v instanceof UploadedFile || \is_array($v) ? $this->convertFileInformation($v) : $v; }, $file); + if (array_keys($keys) === $keys) { + $file = array_filter($file); + } + } + + return $file; + } + + /** + * Fixes a malformed PHP $_FILES array. + * + * PHP has a bug that the format of the $_FILES array differs, depending on + * whether the uploaded file fields had normal field names or array-like + * field names ("normal" vs. "parent[child]"). + * + * This method fixes the array to look like the "normal" $_FILES array. + * + * It's safe to pass an already converted array, in which case this method + * just returns the original array unmodified. + * + * @return array + */ + protected function fixPhpFilesArray(array $data) + { + // Remove extra key added by PHP 8.1. + unset($data['full_path']); + $keys = array_keys($data); + sort($keys); + + if (self::FILE_KEYS != $keys || !isset($data['name']) || !\is_array($data['name'])) { + return $data; + } + + $files = $data; + foreach (self::FILE_KEYS as $k) { + unset($files[$k]); + } + + foreach ($data['name'] as $key => $name) { + $files[$key] = $this->fixPhpFilesArray([ + 'error' => $data['error'][$key], + 'name' => $name, + 'type' => $data['type'][$key], + 'tmp_name' => $data['tmp_name'][$key], + 'size' => $data['size'][$key], + ]); + } + + return $files; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/HeaderBag.php b/php/libraries/composer/vendor/symfony/http-foundation/HeaderBag.php new file mode 100644 index 0000000..43d5f63 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/HeaderBag.php @@ -0,0 +1,295 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * HeaderBag is a container for HTTP headers. + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate> + */ +class HeaderBag implements \IteratorAggregate, \Countable +{ + protected const UPPER = '_ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + protected const LOWER = '-abcdefghijklmnopqrstuvwxyz'; + + /** + * @var array> + */ + protected $headers = []; + protected $cacheControl = []; + + public function __construct(array $headers = []) + { + foreach ($headers as $key => $values) { + $this->set($key, $values); + } + } + + /** + * Returns the headers as a string. + * + * @return string + */ + public function __toString() + { + if (!$headers = $this->all()) { + return ''; + } + + ksort($headers); + $max = max(array_map('strlen', array_keys($headers))) + 1; + $content = ''; + foreach ($headers as $name => $values) { + $name = ucwords($name, '-'); + foreach ($values as $value) { + $content .= sprintf("%-{$max}s %s\r\n", $name.':', $value); + } + } + + return $content; + } + + /** + * Returns the headers. + * + * @param string|null $key The name of the headers to return or null to get them all + * + * @return array>|array + */ + public function all(?string $key = null) + { + if (null !== $key) { + return $this->headers[strtr($key, self::UPPER, self::LOWER)] ?? []; + } + + return $this->headers; + } + + /** + * Returns the parameter keys. + * + * @return string[] + */ + public function keys() + { + return array_keys($this->all()); + } + + /** + * Replaces the current HTTP headers by a new set. + */ + public function replace(array $headers = []) + { + $this->headers = []; + $this->add($headers); + } + + /** + * Adds new headers the current HTTP headers set. + */ + public function add(array $headers) + { + foreach ($headers as $key => $values) { + $this->set($key, $values); + } + } + + /** + * Returns the first header by name or the default one. + * + * @return string|null + */ + public function get(string $key, ?string $default = null) + { + $headers = $this->all($key); + + if (!$headers) { + return $default; + } + + if (null === $headers[0]) { + return null; + } + + return (string) $headers[0]; + } + + /** + * Sets a header by name. + * + * @param string|string[]|null $values The value or an array of values + * @param bool $replace Whether to replace the actual value or not (true by default) + */ + public function set(string $key, $values, bool $replace = true) + { + $key = strtr($key, self::UPPER, self::LOWER); + + if (\is_array($values)) { + $values = array_values($values); + + if (true === $replace || !isset($this->headers[$key])) { + $this->headers[$key] = $values; + } else { + $this->headers[$key] = array_merge($this->headers[$key], $values); + } + } else { + if (true === $replace || !isset($this->headers[$key])) { + $this->headers[$key] = [$values]; + } else { + $this->headers[$key][] = $values; + } + } + + if ('cache-control' === $key) { + $this->cacheControl = $this->parseCacheControl(implode(', ', $this->headers[$key])); + } + } + + /** + * Returns true if the HTTP header is defined. + * + * @return bool + */ + public function has(string $key) + { + return \array_key_exists(strtr($key, self::UPPER, self::LOWER), $this->all()); + } + + /** + * Returns true if the given HTTP header contains the given value. + * + * @return bool + */ + public function contains(string $key, string $value) + { + return \in_array($value, $this->all($key)); + } + + /** + * Removes a header. + */ + public function remove(string $key) + { + $key = strtr($key, self::UPPER, self::LOWER); + + unset($this->headers[$key]); + + if ('cache-control' === $key) { + $this->cacheControl = []; + } + } + + /** + * Returns the HTTP header value converted to a date. + * + * @return \DateTimeInterface|null + * + * @throws \RuntimeException When the HTTP header is not parseable + */ + public function getDate(string $key, ?\DateTime $default = null) + { + if (null === $value = $this->get($key)) { + return $default; + } + + if (false === $date = \DateTime::createFromFormat(\DATE_RFC2822, $value)) { + throw new \RuntimeException(sprintf('The "%s" HTTP header is not parseable (%s).', $key, $value)); + } + + return $date; + } + + /** + * Adds a custom Cache-Control directive. + * + * @param bool|string $value The Cache-Control directive value + */ + public function addCacheControlDirective(string $key, $value = true) + { + $this->cacheControl[$key] = $value; + + $this->set('Cache-Control', $this->getCacheControlHeader()); + } + + /** + * Returns true if the Cache-Control directive is defined. + * + * @return bool + */ + public function hasCacheControlDirective(string $key) + { + return \array_key_exists($key, $this->cacheControl); + } + + /** + * Returns a Cache-Control directive value by name. + * + * @return bool|string|null + */ + public function getCacheControlDirective(string $key) + { + return $this->cacheControl[$key] ?? null; + } + + /** + * Removes a Cache-Control directive. + */ + public function removeCacheControlDirective(string $key) + { + unset($this->cacheControl[$key]); + + $this->set('Cache-Control', $this->getCacheControlHeader()); + } + + /** + * Returns an iterator for headers. + * + * @return \ArrayIterator> + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new \ArrayIterator($this->headers); + } + + /** + * Returns the number of headers. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return \count($this->headers); + } + + protected function getCacheControlHeader() + { + ksort($this->cacheControl); + + return HeaderUtils::toString($this->cacheControl, ','); + } + + /** + * Parses a Cache-Control HTTP header. + * + * @return array + */ + protected function parseCacheControl(string $header) + { + $parts = HeaderUtils::split($header, ',='); + + return HeaderUtils::combine($parts); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/HeaderUtils.php b/php/libraries/composer/vendor/symfony/http-foundation/HeaderUtils.php new file mode 100644 index 0000000..3456eda --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/HeaderUtils.php @@ -0,0 +1,294 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * HTTP header utility functions. + * + * @author Christian Schmidt + */ +class HeaderUtils +{ + public const DISPOSITION_ATTACHMENT = 'attachment'; + public const DISPOSITION_INLINE = 'inline'; + + /** + * This class should not be instantiated. + */ + private function __construct() + { + } + + /** + * Splits an HTTP header by one or more separators. + * + * Example: + * + * HeaderUtils::split('da, en-gb;q=0.8', ',;') + * // => ['da'], ['en-gb', 'q=0.8']] + * + * @param string $separators List of characters to split on, ordered by + * precedence, e.g. ',', ';=', or ',;=' + * + * @return array Nested array with as many levels as there are characters in + * $separators + */ + public static function split(string $header, string $separators): array + { + if ('' === $separators) { + throw new \InvalidArgumentException('At least one separator must be specified.'); + } + + $quotedSeparators = preg_quote($separators, '/'); + + preg_match_all(' + / + (?!\s) + (?: + # quoted-string + "(?:[^"\\\\]|\\\\.)*(?:"|\\\\|$) + | + # token + [^"'.$quotedSeparators.']+ + )+ + (?['.$quotedSeparators.']) + \s* + /x', trim($header), $matches, \PREG_SET_ORDER); + + return self::groupParts($matches, $separators); + } + + /** + * Combines an array of arrays into one associative array. + * + * Each of the nested arrays should have one or two elements. The first + * value will be used as the keys in the associative array, and the second + * will be used as the values, or true if the nested array only contains one + * element. Array keys are lowercased. + * + * Example: + * + * HeaderUtils::combine([['foo', 'abc'], ['bar']]) + * // => ['foo' => 'abc', 'bar' => true] + */ + public static function combine(array $parts): array + { + $assoc = []; + foreach ($parts as $part) { + $name = strtolower($part[0]); + $value = $part[1] ?? true; + $assoc[$name] = $value; + } + + return $assoc; + } + + /** + * Joins an associative array into a string for use in an HTTP header. + * + * The key and value of each entry are joined with '=', and all entries + * are joined with the specified separator and an additional space (for + * readability). Values are quoted if necessary. + * + * Example: + * + * HeaderUtils::toString(['foo' => 'abc', 'bar' => true, 'baz' => 'a b c'], ',') + * // => 'foo=abc, bar, baz="a b c"' + */ + public static function toString(array $assoc, string $separator): string + { + $parts = []; + foreach ($assoc as $name => $value) { + if (true === $value) { + $parts[] = $name; + } else { + $parts[] = $name.'='.self::quote($value); + } + } + + return implode($separator.' ', $parts); + } + + /** + * Encodes a string as a quoted string, if necessary. + * + * If a string contains characters not allowed by the "token" construct in + * the HTTP specification, it is backslash-escaped and enclosed in quotes + * to match the "quoted-string" construct. + */ + public static function quote(string $s): string + { + if (preg_match('/^[a-z0-9!#$%&\'*.^_`|~-]+$/i', $s)) { + return $s; + } + + return '"'.addcslashes($s, '"\\"').'"'; + } + + /** + * Decodes a quoted string. + * + * If passed an unquoted string that matches the "token" construct (as + * defined in the HTTP specification), it is passed through verbatim. + */ + public static function unquote(string $s): string + { + return preg_replace('/\\\\(.)|"/', '$1', $s); + } + + /** + * Generates an HTTP Content-Disposition field-value. + * + * @param string $disposition One of "inline" or "attachment" + * @param string $filename A unicode string + * @param string $filenameFallback A string containing only ASCII characters that + * is semantically equivalent to $filename. If the filename is already ASCII, + * it can be omitted, or just copied from $filename + * + * @throws \InvalidArgumentException + * + * @see RFC 6266 + */ + public static function makeDisposition(string $disposition, string $filename, string $filenameFallback = ''): string + { + if (!\in_array($disposition, [self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE])) { + throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE)); + } + + if ('' === $filenameFallback) { + $filenameFallback = $filename; + } + + // filenameFallback is not ASCII. + if (!preg_match('/^[\x20-\x7e]*$/', $filenameFallback)) { + throw new \InvalidArgumentException('The filename fallback must only contain ASCII characters.'); + } + + // percent characters aren't safe in fallback. + if (str_contains($filenameFallback, '%')) { + throw new \InvalidArgumentException('The filename fallback cannot contain the "%" character.'); + } + + // path separators aren't allowed in either. + if (str_contains($filename, '/') || str_contains($filename, '\\') || str_contains($filenameFallback, '/') || str_contains($filenameFallback, '\\')) { + throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.'); + } + + $params = ['filename' => $filenameFallback]; + if ($filename !== $filenameFallback) { + $params['filename*'] = "utf-8''".rawurlencode($filename); + } + + return $disposition.'; '.self::toString($params, ';'); + } + + /** + * Like parse_str(), but preserves dots in variable names. + */ + public static function parseQuery(string $query, bool $ignoreBrackets = false, string $separator = '&'): array + { + $q = []; + + foreach (explode($separator, $query) as $v) { + if (false !== $i = strpos($v, "\0")) { + $v = substr($v, 0, $i); + } + + if (false === $i = strpos($v, '=')) { + $k = urldecode($v); + $v = ''; + } else { + $k = urldecode(substr($v, 0, $i)); + $v = substr($v, $i); + } + + if (false !== $i = strpos($k, "\0")) { + $k = substr($k, 0, $i); + } + + $k = ltrim($k, ' '); + + if ($ignoreBrackets) { + $q[$k][] = urldecode(substr($v, 1)); + + continue; + } + + if (false === $i = strpos($k, '[')) { + $q[] = bin2hex($k).$v; + } else { + $q[] = bin2hex(substr($k, 0, $i)).rawurlencode(substr($k, $i)).$v; + } + } + + if ($ignoreBrackets) { + return $q; + } + + parse_str(implode('&', $q), $q); + + $query = []; + + foreach ($q as $k => $v) { + if (false !== $i = strpos($k, '_')) { + $query[substr_replace($k, hex2bin(substr($k, 0, $i)).'[', 0, 1 + $i)] = $v; + } else { + $query[hex2bin($k)] = $v; + } + } + + return $query; + } + + private static function groupParts(array $matches, string $separators, bool $first = true): array + { + $separator = $separators[0]; + $separators = substr($separators, 1) ?: ''; + $i = 0; + + if ('' === $separators && !$first) { + $parts = ['']; + + foreach ($matches as $match) { + if (!$i && isset($match['separator'])) { + $i = 1; + $parts[1] = ''; + } else { + $parts[$i] .= self::unquote($match[0]); + } + } + + return $parts; + } + + $parts = []; + $partMatches = []; + + foreach ($matches as $match) { + if (($match['separator'] ?? null) === $separator) { + ++$i; + } else { + $partMatches[$i][] = $match; + } + } + + foreach ($partMatches as $matches) { + $parts[] = '' === $separators ? self::unquote($matches[0][0]) : self::groupParts($matches, $separators, false); + } + + return $parts; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/InputBag.php b/php/libraries/composer/vendor/symfony/http-foundation/InputBag.php new file mode 100644 index 0000000..356fbbc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/InputBag.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 Symfony\Component\HttpFoundation; + +use Symfony\Component\HttpFoundation\Exception\BadRequestException; + +/** + * InputBag is a container for user input values such as $_GET, $_POST, $_REQUEST, and $_COOKIE. + * + * @author Saif Eddin Gmati + */ +final class InputBag extends ParameterBag +{ + /** + * Returns a scalar input value by name. + * + * @param string|int|float|bool|null $default The default value if the input key does not exist + * + * @return string|int|float|bool|null + */ + public function get(string $key, $default = null) + { + if (null !== $default && !\is_scalar($default) && !(\is_object($default) && method_exists($default, '__toString'))) { + trigger_deprecation('symfony/http-foundation', '5.1', 'Passing a non-scalar value as 2nd argument to "%s()" is deprecated, pass a scalar or null instead.', __METHOD__); + } + + $value = parent::get($key, $this); + + if (null !== $value && $this !== $value && !\is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { + trigger_deprecation('symfony/http-foundation', '5.1', 'Retrieving a non-scalar value from "%s()" is deprecated, and will throw a "%s" exception in Symfony 6.0, use "%s::all($key)" instead.', __METHOD__, BadRequestException::class, __CLASS__); + } + + return $this === $value ? $default : $value; + } + + /** + * {@inheritdoc} + */ + public function all(?string $key = null): array + { + return parent::all($key); + } + + /** + * Replaces the current input values by a new set. + */ + public function replace(array $inputs = []) + { + $this->parameters = []; + $this->add($inputs); + } + + /** + * Adds input values. + */ + public function add(array $inputs = []) + { + foreach ($inputs as $input => $value) { + $this->set($input, $value); + } + } + + /** + * Sets an input by name. + * + * @param string|int|float|bool|array|null $value + */ + public function set(string $key, $value) + { + if (null !== $value && !\is_scalar($value) && !\is_array($value) && !method_exists($value, '__toString')) { + trigger_deprecation('symfony/http-foundation', '5.1', 'Passing "%s" as a 2nd Argument to "%s()" is deprecated, pass a scalar, array, or null instead.', get_debug_type($value), __METHOD__); + } + + $this->parameters[$key] = $value; + } + + /** + * {@inheritdoc} + */ + public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = []) + { + $value = $this->has($key) ? $this->all()[$key] : $default; + + // Always turn $options into an array - this allows filter_var option shortcuts. + if (!\is_array($options) && $options) { + $options = ['flags' => $options]; + } + + if (\is_array($value) && !(($options['flags'] ?? 0) & (\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY))) { + trigger_deprecation('symfony/http-foundation', '5.1', 'Filtering an array value with "%s()" without passing the FILTER_REQUIRE_ARRAY or FILTER_FORCE_ARRAY flag is deprecated', __METHOD__); + + if (!isset($options['flags'])) { + $options['flags'] = \FILTER_REQUIRE_ARRAY; + } + } + + if ((\FILTER_CALLBACK & $filter) && !(($options['options'] ?? null) instanceof \Closure)) { + trigger_deprecation('symfony/http-foundation', '5.2', 'Not passing a Closure together with FILTER_CALLBACK to "%s()" is deprecated. Wrap your filter in a closure instead.', __METHOD__); + // throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null))); + } + + return filter_var($value, $filter, $options); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/IpUtils.php b/php/libraries/composer/vendor/symfony/http-foundation/IpUtils.php new file mode 100644 index 0000000..49d9a9d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/IpUtils.php @@ -0,0 +1,216 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * Http utility functions. + * + * @author Fabien Potencier + */ +class IpUtils +{ + private static $checkedIps = []; + + /** + * This class should not be instantiated. + */ + private function __construct() + { + } + + /** + * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets. + * + * @param string|array $ips List of IPs or subnets (can be a string if only a single one) + * + * @return bool + */ + public static function checkIp(?string $requestIp, $ips) + { + if (null === $requestIp) { + trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + return false; + } + + if (!\is_array($ips)) { + $ips = [$ips]; + } + + $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4'; + + foreach ($ips as $ip) { + if (self::$method($requestIp, $ip)) { + return true; + } + } + + return false; + } + + /** + * Compares two IPv4 addresses. + * In case a subnet is given, it checks if it contains the request IP. + * + * @param string $ip IPv4 address or subnet in CIDR notation + * + * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet + */ + public static function checkIp4(?string $requestIp, string $ip) + { + if (null === $requestIp) { + trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + return false; + } + + $cacheKey = $requestIp.'-'.$ip.'-v4'; + if (isset(self::$checkedIps[$cacheKey])) { + return self::$checkedIps[$cacheKey]; + } + + if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) { + return self::$checkedIps[$cacheKey] = false; + } + + if (str_contains($ip, '/')) { + [$address, $netmask] = explode('/', $ip, 2); + + if ('0' === $netmask) { + return self::$checkedIps[$cacheKey] = false !== filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4); + } + + if ($netmask < 0 || $netmask > 32) { + return self::$checkedIps[$cacheKey] = false; + } + } else { + $address = $ip; + $netmask = 32; + } + + if (false === ip2long($address)) { + return self::$checkedIps[$cacheKey] = false; + } + + return self::$checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask); + } + + /** + * Compares two IPv6 addresses. + * In case a subnet is given, it checks if it contains the request IP. + * + * @author David Soria Parra + * + * @see https://github.com/dsp/v6tools + * + * @param string $ip IPv6 address or subnet in CIDR notation + * + * @return bool + * + * @throws \RuntimeException When IPV6 support is not enabled + */ + public static function checkIp6(?string $requestIp, string $ip) + { + if (null === $requestIp) { + trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + return false; + } + + $cacheKey = $requestIp.'-'.$ip.'-v6'; + if (isset(self::$checkedIps[$cacheKey])) { + return self::$checkedIps[$cacheKey]; + } + + if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) { + throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".'); + } + + // Check to see if we were given a IP4 $requestIp or $ip by mistake + if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { + return self::$checkedIps[$cacheKey] = false; + } + + if (str_contains($ip, '/')) { + [$address, $netmask] = explode('/', $ip, 2); + + if (!filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { + return self::$checkedIps[$cacheKey] = false; + } + + if ('0' === $netmask) { + return (bool) unpack('n*', @inet_pton($address)); + } + + if ($netmask < 1 || $netmask > 128) { + return self::$checkedIps[$cacheKey] = false; + } + } else { + if (!filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { + return self::$checkedIps[$cacheKey] = false; + } + + $address = $ip; + $netmask = 128; + } + + $bytesAddr = unpack('n*', @inet_pton($address)); + $bytesTest = unpack('n*', @inet_pton($requestIp)); + + if (!$bytesAddr || !$bytesTest) { + return self::$checkedIps[$cacheKey] = false; + } + + for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) { + $left = $netmask - 16 * ($i - 1); + $left = ($left <= 16) ? $left : 16; + $mask = ~(0xFFFF >> $left) & 0xFFFF; + if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) { + return self::$checkedIps[$cacheKey] = false; + } + } + + return self::$checkedIps[$cacheKey] = true; + } + + /** + * Anonymizes an IP/IPv6. + * + * Removes the last byte for v4 and the last 8 bytes for v6 IPs + */ + public static function anonymize(string $ip): string + { + $wrappedIPv6 = false; + if ('[' === substr($ip, 0, 1) && ']' === substr($ip, -1, 1)) { + $wrappedIPv6 = true; + $ip = substr($ip, 1, -1); + } + + $packedAddress = inet_pton($ip); + if (4 === \strlen($packedAddress)) { + $mask = '255.255.255.0'; + } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) { + $mask = '::ffff:ffff:ff00'; + } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) { + $mask = '::ffff:ff00'; + } else { + $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000'; + } + $ip = inet_ntop($packedAddress & inet_pton($mask)); + + if ($wrappedIPv6) { + $ip = '['.$ip.']'; + } + + return $ip; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/JsonResponse.php b/php/libraries/composer/vendor/symfony/http-foundation/JsonResponse.php new file mode 100644 index 0000000..51bdf19 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/JsonResponse.php @@ -0,0 +1,221 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * Response represents an HTTP response in JSON format. + * + * Note that this class does not force the returned JSON content to be an + * object. It is however recommended that you do return an object as it + * protects yourself against XSSI and JSON-JavaScript Hijacking. + * + * @see https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/AJAX_Security_Cheat_Sheet.md#always-return-json-with-an-object-on-the-outside + * + * @author Igor Wiedler + */ +class JsonResponse extends Response +{ + protected $data; + protected $callback; + + // Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML. + // 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT + public const DEFAULT_ENCODING_OPTIONS = 15; + + protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS; + + /** + * @param mixed $data The response data + * @param int $status The response status code + * @param array $headers An array of response headers + * @param bool $json If the data is already a JSON string + */ + public function __construct($data = null, int $status = 200, array $headers = [], bool $json = false) + { + parent::__construct('', $status, $headers); + + if ($json && !\is_string($data) && !is_numeric($data) && !\is_callable([$data, '__toString'])) { + throw new \TypeError(sprintf('"%s": If $json is set to true, argument $data must be a string or object implementing __toString(), "%s" given.', __METHOD__, get_debug_type($data))); + } + + if (null === $data) { + $data = new \ArrayObject(); + } + + $json ? $this->setJson($data) : $this->setData($data); + } + + /** + * Factory method for chainability. + * + * Example: + * + * return JsonResponse::create(['key' => 'value']) + * ->setSharedMaxAge(300); + * + * @param mixed $data The JSON response data + * @param int $status The response status code + * @param array $headers An array of response headers + * + * @return static + * + * @deprecated since Symfony 5.1, use __construct() instead. + */ + public static function create($data = null, int $status = 200, array $headers = []) + { + trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class); + + return new static($data, $status, $headers); + } + + /** + * Factory method for chainability. + * + * Example: + * + * return JsonResponse::fromJsonString('{"key": "value"}') + * ->setSharedMaxAge(300); + * + * @param string $data The JSON response string + * @param int $status The response status code + * @param array $headers An array of response headers + * + * @return static + */ + public static function fromJsonString(string $data, int $status = 200, array $headers = []) + { + return new static($data, $status, $headers, true); + } + + /** + * Sets the JSONP callback. + * + * @param string|null $callback The JSONP callback or null to use none + * + * @return $this + * + * @throws \InvalidArgumentException When the callback name is not valid + */ + public function setCallback(?string $callback = null) + { + if (null !== $callback) { + // partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/ + // partially taken from https://github.com/willdurand/JsonpCallbackValidator + // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details. + // (c) William Durand + $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u'; + $reserved = [ + 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while', + 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export', + 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false', + ]; + $parts = explode('.', $callback); + foreach ($parts as $part) { + if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) { + throw new \InvalidArgumentException('The callback name is not valid.'); + } + } + } + + $this->callback = $callback; + + return $this->update(); + } + + /** + * Sets a raw string containing a JSON document to be sent. + * + * @return $this + */ + public function setJson(string $json) + { + $this->data = $json; + + return $this->update(); + } + + /** + * Sets the data to be sent as JSON. + * + * @param mixed $data + * + * @return $this + * + * @throws \InvalidArgumentException + */ + public function setData($data = []) + { + try { + $data = json_encode($data, $this->encodingOptions); + } catch (\Exception $e) { + if ('Exception' === \get_class($e) && str_starts_with($e->getMessage(), 'Failed calling ')) { + throw $e->getPrevious() ?: $e; + } + throw $e; + } + + if (\PHP_VERSION_ID >= 70300 && (\JSON_THROW_ON_ERROR & $this->encodingOptions)) { + return $this->setJson($data); + } + + if (\JSON_ERROR_NONE !== json_last_error()) { + throw new \InvalidArgumentException(json_last_error_msg()); + } + + return $this->setJson($data); + } + + /** + * Returns options used while encoding data to JSON. + * + * @return int + */ + public function getEncodingOptions() + { + return $this->encodingOptions; + } + + /** + * Sets options used while encoding data to JSON. + * + * @return $this + */ + public function setEncodingOptions(int $encodingOptions) + { + $this->encodingOptions = $encodingOptions; + + return $this->setData(json_decode($this->data)); + } + + /** + * Updates the content and headers according to the JSON data and callback. + * + * @return $this + */ + protected function update() + { + if (null !== $this->callback) { + // Not using application/javascript for compatibility reasons with older browsers. + $this->headers->set('Content-Type', 'text/javascript'); + + return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data)); + } + + // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback) + // in order to not overwrite a custom definition. + if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) { + $this->headers->set('Content-Type', 'application/json'); + } + + return $this->setContent($this->data); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/LICENSE b/php/libraries/composer/vendor/symfony/http-foundation/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/http-foundation/ParameterBag.php b/php/libraries/composer/vendor/symfony/http-foundation/ParameterBag.php new file mode 100644 index 0000000..e1f89d6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/ParameterBag.php @@ -0,0 +1,228 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +use Symfony\Component\HttpFoundation\Exception\BadRequestException; + +/** + * ParameterBag is a container for key/value pairs. + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate + */ +class ParameterBag implements \IteratorAggregate, \Countable +{ + /** + * Parameter storage. + */ + protected $parameters; + + public function __construct(array $parameters = []) + { + $this->parameters = $parameters; + } + + /** + * Returns the parameters. + * + * @param string|null $key The name of the parameter to return or null to get them all + * + * @return array + */ + public function all(/* string $key = null */) + { + $key = \func_num_args() > 0 ? func_get_arg(0) : null; + + if (null === $key) { + return $this->parameters; + } + + if (!\is_array($value = $this->parameters[$key] ?? [])) { + throw new BadRequestException(sprintf('Unexpected value for parameter "%s": expecting "array", got "%s".', $key, get_debug_type($value))); + } + + return $value; + } + + /** + * Returns the parameter keys. + * + * @return array + */ + public function keys() + { + return array_keys($this->parameters); + } + + /** + * Replaces the current parameters by a new set. + */ + public function replace(array $parameters = []) + { + $this->parameters = $parameters; + } + + /** + * Adds parameters. + */ + public function add(array $parameters = []) + { + $this->parameters = array_replace($this->parameters, $parameters); + } + + /** + * Returns a parameter by name. + * + * @param mixed $default The default value if the parameter key does not exist + * + * @return mixed + */ + public function get(string $key, $default = null) + { + return \array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default; + } + + /** + * Sets a parameter by name. + * + * @param mixed $value The value + */ + public function set(string $key, $value) + { + $this->parameters[$key] = $value; + } + + /** + * Returns true if the parameter is defined. + * + * @return bool + */ + public function has(string $key) + { + return \array_key_exists($key, $this->parameters); + } + + /** + * Removes a parameter. + */ + public function remove(string $key) + { + unset($this->parameters[$key]); + } + + /** + * Returns the alphabetic characters of the parameter value. + * + * @return string + */ + public function getAlpha(string $key, string $default = '') + { + return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default)); + } + + /** + * Returns the alphabetic characters and digits of the parameter value. + * + * @return string + */ + public function getAlnum(string $key, string $default = '') + { + return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default)); + } + + /** + * Returns the digits of the parameter value. + * + * @return string + */ + public function getDigits(string $key, string $default = '') + { + // we need to remove - and + because they're allowed in the filter + return str_replace(['-', '+'], '', $this->filter($key, $default, \FILTER_SANITIZE_NUMBER_INT)); + } + + /** + * Returns the parameter value converted to integer. + * + * @return int + */ + public function getInt(string $key, int $default = 0) + { + return (int) $this->get($key, $default); + } + + /** + * Returns the parameter value converted to boolean. + * + * @return bool + */ + public function getBoolean(string $key, bool $default = false) + { + return $this->filter($key, $default, \FILTER_VALIDATE_BOOLEAN); + } + + /** + * Filter key. + * + * @param mixed $default Default = null + * @param int $filter FILTER_* constant + * @param mixed $options Filter options + * + * @see https://php.net/filter-var + * + * @return mixed + */ + public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = []) + { + $value = $this->get($key, $default); + + // Always turn $options into an array - this allows filter_var option shortcuts. + if (!\is_array($options) && $options) { + $options = ['flags' => $options]; + } + + // Add a convenience check for arrays. + if (\is_array($value) && !isset($options['flags'])) { + $options['flags'] = \FILTER_REQUIRE_ARRAY; + } + + if ((\FILTER_CALLBACK & $filter) && !(($options['options'] ?? null) instanceof \Closure)) { + trigger_deprecation('symfony/http-foundation', '5.2', 'Not passing a Closure together with FILTER_CALLBACK to "%s()" is deprecated. Wrap your filter in a closure instead.', __METHOD__); + // throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null))); + } + + return filter_var($value, $filter, $options); + } + + /** + * Returns an iterator for parameters. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new \ArrayIterator($this->parameters); + } + + /** + * Returns the number of parameters. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return \count($this->parameters); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/README.md b/php/libraries/composer/vendor/symfony/http-foundation/README.md new file mode 100644 index 0000000..424f2c4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/README.md @@ -0,0 +1,28 @@ +HttpFoundation Component +======================== + +The HttpFoundation component defines an object-oriented layer for the HTTP +specification. + +Sponsor +------- + +The HttpFoundation component for Symfony 5.4/6.0 is [backed][1] by [Laravel][2]. + +Laravel is a PHP web development framework that is passionate about maximum developer +happiness. Laravel is built using a variety of bespoke and Symfony based components. + +Help Symfony by [sponsoring][3] its development! + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/http_foundation.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +[1]: https://symfony.com/backers +[2]: https://laravel.com/ +[3]: https://symfony.com/sponsor diff --git a/php/libraries/composer/vendor/symfony/http-foundation/RateLimiter/AbstractRequestRateLimiter.php b/php/libraries/composer/vendor/symfony/http-foundation/RateLimiter/AbstractRequestRateLimiter.php new file mode 100644 index 0000000..a6dd993 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/RateLimiter/AbstractRequestRateLimiter.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\RateLimiter; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\RateLimiter\LimiterInterface; +use Symfony\Component\RateLimiter\Policy\NoLimiter; +use Symfony\Component\RateLimiter\RateLimit; + +/** + * An implementation of RequestRateLimiterInterface that + * fits most use-cases. + * + * @author Wouter de Jong + */ +abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface +{ + public function consume(Request $request): RateLimit + { + $limiters = $this->getLimiters($request); + if (0 === \count($limiters)) { + $limiters = [new NoLimiter()]; + } + + $minimalRateLimit = null; + foreach ($limiters as $limiter) { + $rateLimit = $limiter->consume(1); + + $minimalRateLimit = $minimalRateLimit ? self::getMinimalRateLimit($minimalRateLimit, $rateLimit) : $rateLimit; + } + + return $minimalRateLimit; + } + + public function reset(Request $request): void + { + foreach ($this->getLimiters($request) as $limiter) { + $limiter->reset(); + } + } + + /** + * @return LimiterInterface[] a set of limiters using keys extracted from the request + */ + abstract protected function getLimiters(Request $request): array; + + private static function getMinimalRateLimit(RateLimit $first, RateLimit $second): RateLimit + { + if ($first->isAccepted() !== $second->isAccepted()) { + return $first->isAccepted() ? $second : $first; + } + + $firstRemainingTokens = $first->getRemainingTokens(); + $secondRemainingTokens = $second->getRemainingTokens(); + + if ($firstRemainingTokens === $secondRemainingTokens) { + return $first->getRetryAfter() < $second->getRetryAfter() ? $second : $first; + } + + return $firstRemainingTokens > $secondRemainingTokens ? $second : $first; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/RateLimiter/RequestRateLimiterInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/RateLimiter/RequestRateLimiterInterface.php new file mode 100644 index 0000000..4c87a40 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/RateLimiter/RequestRateLimiterInterface.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\HttpFoundation\RateLimiter; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\RateLimiter\RateLimit; + +/** + * A special type of limiter that deals with requests. + * + * This allows to limit on different types of information + * from the requests. + * + * @author Wouter de Jong + */ +interface RequestRateLimiterInterface +{ + public function consume(Request $request): RateLimit; + + public function reset(Request $request): void; +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/RedirectResponse.php b/php/libraries/composer/vendor/symfony/http-foundation/RedirectResponse.php new file mode 100644 index 0000000..2103280 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/RedirectResponse.php @@ -0,0 +1,109 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * RedirectResponse represents an HTTP response doing a redirect. + * + * @author Fabien Potencier + */ +class RedirectResponse extends Response +{ + protected $targetUrl; + + /** + * Creates a redirect response so that it conforms to the rules defined for a redirect status code. + * + * @param string $url The URL to redirect to. The URL should be a full URL, with schema etc., + * but practically every browser redirects on paths only as well + * @param int $status The status code (302 by default) + * @param array $headers The headers (Location is always set to the given URL) + * + * @throws \InvalidArgumentException + * + * @see https://tools.ietf.org/html/rfc2616#section-10.3 + */ + public function __construct(string $url, int $status = 302, array $headers = []) + { + parent::__construct('', $status, $headers); + + $this->setTargetUrl($url); + + if (!$this->isRedirect()) { + throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status)); + } + + if (301 == $status && !\array_key_exists('cache-control', array_change_key_case($headers, \CASE_LOWER))) { + $this->headers->remove('cache-control'); + } + } + + /** + * Factory method for chainability. + * + * @param string $url The URL to redirect to + * + * @return static + * + * @deprecated since Symfony 5.1, use __construct() instead. + */ + public static function create($url = '', int $status = 302, array $headers = []) + { + trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class); + + return new static($url, $status, $headers); + } + + /** + * Returns the target URL. + * + * @return string + */ + public function getTargetUrl() + { + return $this->targetUrl; + } + + /** + * Sets the redirect target of this response. + * + * @return $this + * + * @throws \InvalidArgumentException + */ + public function setTargetUrl(string $url) + { + if ('' === $url) { + throw new \InvalidArgumentException('Cannot redirect to an empty URL.'); + } + + $this->targetUrl = $url; + + $this->setContent( + sprintf(' + + + + + + Redirecting to %1$s + + + Redirecting to %1$s. + +', htmlspecialchars($url, \ENT_QUOTES, 'UTF-8'))); + + $this->headers->set('Location', $url); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Request.php b/php/libraries/composer/vendor/symfony/http-foundation/Request.php new file mode 100644 index 0000000..75db030 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Request.php @@ -0,0 +1,2172 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; +use Symfony\Component\HttpFoundation\Exception\JsonException; +use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException; +use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(AcceptHeader::class); +class_exists(FileBag::class); +class_exists(HeaderBag::class); +class_exists(HeaderUtils::class); +class_exists(InputBag::class); +class_exists(ParameterBag::class); +class_exists(ServerBag::class); + +/** + * Request represents an HTTP request. + * + * The methods dealing with URL accept / return a raw path (% encoded): + * * getBasePath + * * getBaseUrl + * * getPathInfo + * * getRequestUri + * * getUri + * * getUriForPath + * + * @author Fabien Potencier + */ +class Request +{ + public const HEADER_FORWARDED = 0b000001; // When using RFC 7239 + public const HEADER_X_FORWARDED_FOR = 0b000010; + public const HEADER_X_FORWARDED_HOST = 0b000100; + public const HEADER_X_FORWARDED_PROTO = 0b001000; + public const HEADER_X_FORWARDED_PORT = 0b010000; + public const HEADER_X_FORWARDED_PREFIX = 0b100000; + + /** @deprecated since Symfony 5.2, use either "HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO" or "HEADER_X_FORWARDED_AWS_ELB" or "HEADER_X_FORWARDED_TRAEFIK" constants instead. */ + public const HEADER_X_FORWARDED_ALL = 0b1011110; // All "X-Forwarded-*" headers sent by "usual" reverse proxy + public const HEADER_X_FORWARDED_AWS_ELB = 0b0011010; // AWS ELB doesn't send X-Forwarded-Host + public const HEADER_X_FORWARDED_TRAEFIK = 0b0111110; // All "X-Forwarded-*" headers sent by Traefik reverse proxy + + public const METHOD_HEAD = 'HEAD'; + public const METHOD_GET = 'GET'; + public const METHOD_POST = 'POST'; + public const METHOD_PUT = 'PUT'; + public const METHOD_PATCH = 'PATCH'; + public const METHOD_DELETE = 'DELETE'; + public const METHOD_PURGE = 'PURGE'; + public const METHOD_OPTIONS = 'OPTIONS'; + public const METHOD_TRACE = 'TRACE'; + public const METHOD_CONNECT = 'CONNECT'; + + /** + * @var string[] + */ + protected static $trustedProxies = []; + + /** + * @var string[] + */ + protected static $trustedHostPatterns = []; + + /** + * @var string[] + */ + protected static $trustedHosts = []; + + protected static $httpMethodParameterOverride = false; + + /** + * Custom parameters. + * + * @var ParameterBag + */ + public $attributes; + + /** + * Request body parameters ($_POST). + * + * @var InputBag + */ + public $request; + + /** + * Query string parameters ($_GET). + * + * @var InputBag + */ + public $query; + + /** + * Server and execution environment parameters ($_SERVER). + * + * @var ServerBag + */ + public $server; + + /** + * Uploaded files ($_FILES). + * + * @var FileBag + */ + public $files; + + /** + * Cookies ($_COOKIE). + * + * @var InputBag + */ + public $cookies; + + /** + * Headers (taken from the $_SERVER). + * + * @var HeaderBag + */ + public $headers; + + /** + * @var string|resource|false|null + */ + protected $content; + + /** + * @var array + */ + protected $languages; + + /** + * @var array + */ + protected $charsets; + + /** + * @var array + */ + protected $encodings; + + /** + * @var array + */ + protected $acceptableContentTypes; + + /** + * @var string + */ + protected $pathInfo; + + /** + * @var string + */ + protected $requestUri; + + /** + * @var string + */ + protected $baseUrl; + + /** + * @var string + */ + protected $basePath; + + /** + * @var string + */ + protected $method; + + /** + * @var string + */ + protected $format; + + /** + * @var SessionInterface|callable(): SessionInterface + */ + protected $session; + + /** + * @var string|null + */ + protected $locale; + + /** + * @var string + */ + protected $defaultLocale = 'en'; + + /** + * @var array + */ + protected static $formats; + + protected static $requestFactory; + + /** + * @var string|null + */ + private $preferredFormat; + private $isHostValid = true; + private $isForwardedValid = true; + + /** + * @var bool|null + */ + private $isSafeContentPreferred; + + private static $trustedHeaderSet = -1; + + private const FORWARDED_PARAMS = [ + self::HEADER_X_FORWARDED_FOR => 'for', + self::HEADER_X_FORWARDED_HOST => 'host', + self::HEADER_X_FORWARDED_PROTO => 'proto', + self::HEADER_X_FORWARDED_PORT => 'host', + ]; + + /** + * Names for headers that can be trusted when + * using trusted proxies. + * + * The FORWARDED header is the standard as of rfc7239. + * + * The other headers are non-standard, but widely used + * by popular reverse proxies (like Apache mod_proxy or Amazon EC2). + */ + private const TRUSTED_HEADERS = [ + self::HEADER_FORWARDED => 'FORWARDED', + self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR', + self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST', + self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO', + self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT', + self::HEADER_X_FORWARDED_PREFIX => 'X_FORWARDED_PREFIX', + ]; + + /** @var bool */ + private $isIisRewrite = false; + + /** + * @param array $query The GET parameters + * @param array $request The POST parameters + * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array $cookies The COOKIE parameters + * @param array $files The FILES parameters + * @param array $server The SERVER parameters + * @param string|resource|null $content The raw body data + */ + public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) + { + $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content); + } + + /** + * Sets the parameters for this request. + * + * This method also re-initializes all properties. + * + * @param array $query The GET parameters + * @param array $request The POST parameters + * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array $cookies The COOKIE parameters + * @param array $files The FILES parameters + * @param array $server The SERVER parameters + * @param string|resource|null $content The raw body data + */ + public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) + { + $this->request = new InputBag($request); + $this->query = new InputBag($query); + $this->attributes = new ParameterBag($attributes); + $this->cookies = new InputBag($cookies); + $this->files = new FileBag($files); + $this->server = new ServerBag($server); + $this->headers = new HeaderBag($this->server->getHeaders()); + + $this->content = $content; + $this->languages = null; + $this->charsets = null; + $this->encodings = null; + $this->acceptableContentTypes = null; + $this->pathInfo = null; + $this->requestUri = null; + $this->baseUrl = null; + $this->basePath = null; + $this->method = null; + $this->format = null; + } + + /** + * Creates a new request with values from PHP's super globals. + * + * @return static + */ + public static function createFromGlobals() + { + $request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER); + + if (str_starts_with($request->headers->get('CONTENT_TYPE', ''), 'application/x-www-form-urlencoded') + && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH']) + ) { + parse_str($request->getContent(), $data); + $request->request = new InputBag($data); + } + + return $request; + } + + /** + * Creates a Request based on a given URI and configuration. + * + * The information contained in the URI always take precedence + * over the other information (server and parameters). + * + * @param string $uri The URI + * @param string $method The HTTP method + * @param array $parameters The query (GET) or request (POST) parameters + * @param array $cookies The request cookies ($_COOKIE) + * @param array $files The request files ($_FILES) + * @param array $server The server parameters ($_SERVER) + * @param string|resource|null $content The raw body data + * + * @return static + */ + public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null) + { + $server = array_replace([ + 'SERVER_NAME' => 'localhost', + 'SERVER_PORT' => 80, + 'HTTP_HOST' => 'localhost', + 'HTTP_USER_AGENT' => 'Symfony', + 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5', + 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', + 'REMOTE_ADDR' => '127.0.0.1', + 'SCRIPT_NAME' => '', + 'SCRIPT_FILENAME' => '', + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'REQUEST_TIME' => time(), + 'REQUEST_TIME_FLOAT' => microtime(true), + ], $server); + + $server['PATH_INFO'] = ''; + $server['REQUEST_METHOD'] = strtoupper($method); + + $components = parse_url($uri); + if (isset($components['host'])) { + $server['SERVER_NAME'] = $components['host']; + $server['HTTP_HOST'] = $components['host']; + } + + if (isset($components['scheme'])) { + if ('https' === $components['scheme']) { + $server['HTTPS'] = 'on'; + $server['SERVER_PORT'] = 443; + } else { + unset($server['HTTPS']); + $server['SERVER_PORT'] = 80; + } + } + + if (isset($components['port'])) { + $server['SERVER_PORT'] = $components['port']; + $server['HTTP_HOST'] .= ':'.$components['port']; + } + + if (isset($components['user'])) { + $server['PHP_AUTH_USER'] = $components['user']; + } + + if (isset($components['pass'])) { + $server['PHP_AUTH_PW'] = $components['pass']; + } + + if (!isset($components['path'])) { + $components['path'] = '/'; + } + + switch (strtoupper($method)) { + case 'POST': + case 'PUT': + case 'DELETE': + if (!isset($server['CONTENT_TYPE'])) { + $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + } + // no break + case 'PATCH': + $request = $parameters; + $query = []; + break; + default: + $request = []; + $query = $parameters; + break; + } + + $queryString = ''; + if (isset($components['query'])) { + parse_str(html_entity_decode($components['query']), $qs); + + if ($query) { + $query = array_replace($qs, $query); + $queryString = http_build_query($query, '', '&'); + } else { + $query = $qs; + $queryString = $components['query']; + } + } elseif ($query) { + $queryString = http_build_query($query, '', '&'); + } + + $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : ''); + $server['QUERY_STRING'] = $queryString; + + return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content); + } + + /** + * Sets a callable able to create a Request instance. + * + * This is mainly useful when you need to override the Request class + * to keep BC with an existing system. It should not be used for any + * other purpose. + */ + public static function setFactory(?callable $callable) + { + self::$requestFactory = $callable; + } + + /** + * Clones a request and overrides some of its parameters. + * + * @param array|null $query The GET parameters + * @param array|null $request The POST parameters + * @param array|null $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array|null $cookies The COOKIE parameters + * @param array|null $files The FILES parameters + * @param array|null $server The SERVER parameters + * + * @return static + */ + public function duplicate(?array $query = null, ?array $request = null, ?array $attributes = null, ?array $cookies = null, ?array $files = null, ?array $server = null) + { + $dup = clone $this; + if (null !== $query) { + $dup->query = new InputBag($query); + } + if (null !== $request) { + $dup->request = new InputBag($request); + } + if (null !== $attributes) { + $dup->attributes = new ParameterBag($attributes); + } + if (null !== $cookies) { + $dup->cookies = new InputBag($cookies); + } + if (null !== $files) { + $dup->files = new FileBag($files); + } + if (null !== $server) { + $dup->server = new ServerBag($server); + $dup->headers = new HeaderBag($dup->server->getHeaders()); + } + $dup->languages = null; + $dup->charsets = null; + $dup->encodings = null; + $dup->acceptableContentTypes = null; + $dup->pathInfo = null; + $dup->requestUri = null; + $dup->baseUrl = null; + $dup->basePath = null; + $dup->method = null; + $dup->format = null; + + if (!$dup->get('_format') && $this->get('_format')) { + $dup->attributes->set('_format', $this->get('_format')); + } + + if (!$dup->getRequestFormat(null)) { + $dup->setRequestFormat($this->getRequestFormat(null)); + } + + return $dup; + } + + /** + * Clones the current request. + * + * Note that the session is not cloned as duplicated requests + * are most of the time sub-requests of the main one. + */ + public function __clone() + { + $this->query = clone $this->query; + $this->request = clone $this->request; + $this->attributes = clone $this->attributes; + $this->cookies = clone $this->cookies; + $this->files = clone $this->files; + $this->server = clone $this->server; + $this->headers = clone $this->headers; + } + + /** + * Returns the request as a string. + * + * @return string + */ + public function __toString() + { + $content = $this->getContent(); + + $cookieHeader = ''; + $cookies = []; + + foreach ($this->cookies as $k => $v) { + $cookies[] = \is_array($v) ? http_build_query([$k => $v], '', '; ', \PHP_QUERY_RFC3986) : "$k=$v"; + } + + if ($cookies) { + $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n"; + } + + return + sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n". + $this->headers. + $cookieHeader."\r\n". + $content; + } + + /** + * Overrides the PHP global variables according to this request instance. + * + * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE. + * $_FILES is never overridden, see rfc1867 + */ + public function overrideGlobals() + { + $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&'))); + + $_GET = $this->query->all(); + $_POST = $this->request->all(); + $_SERVER = $this->server->all(); + $_COOKIE = $this->cookies->all(); + + foreach ($this->headers->all() as $key => $value) { + $key = strtoupper(str_replace('-', '_', $key)); + if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true)) { + $_SERVER[$key] = implode(', ', $value); + } else { + $_SERVER['HTTP_'.$key] = implode(', ', $value); + } + } + + $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE]; + + $requestOrder = \ini_get('request_order') ?: \ini_get('variables_order'); + $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp'; + + $_REQUEST = [[]]; + + foreach (str_split($requestOrder) as $order) { + $_REQUEST[] = $request[$order]; + } + + $_REQUEST = array_merge(...$_REQUEST); + } + + /** + * Sets a list of trusted proxies. + * + * You should only list the reverse proxies that you manage directly. + * + * @param array $proxies A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR'] + * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies + */ + public static function setTrustedProxies(array $proxies, int $trustedHeaderSet) + { + if (self::HEADER_X_FORWARDED_ALL === $trustedHeaderSet) { + trigger_deprecation('symfony/http-foundation', '5.2', 'The "HEADER_X_FORWARDED_ALL" constant is deprecated, use either "HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO" or "HEADER_X_FORWARDED_AWS_ELB" or "HEADER_X_FORWARDED_TRAEFIK" constants instead.'); + } + self::$trustedProxies = array_reduce($proxies, function ($proxies, $proxy) { + if ('REMOTE_ADDR' !== $proxy) { + $proxies[] = $proxy; + } elseif (isset($_SERVER['REMOTE_ADDR'])) { + $proxies[] = $_SERVER['REMOTE_ADDR']; + } + + return $proxies; + }, []); + self::$trustedHeaderSet = $trustedHeaderSet; + } + + /** + * Gets the list of trusted proxies. + * + * @return array + */ + public static function getTrustedProxies() + { + return self::$trustedProxies; + } + + /** + * Gets the set of trusted headers from trusted proxies. + * + * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies + */ + public static function getTrustedHeaderSet() + { + return self::$trustedHeaderSet; + } + + /** + * Sets a list of trusted host patterns. + * + * You should only list the hosts you manage using regexs. + * + * @param array $hostPatterns A list of trusted host patterns + */ + public static function setTrustedHosts(array $hostPatterns) + { + self::$trustedHostPatterns = array_map(function ($hostPattern) { + return sprintf('{%s}i', $hostPattern); + }, $hostPatterns); + // we need to reset trusted hosts on trusted host patterns change + self::$trustedHosts = []; + } + + /** + * Gets the list of trusted host patterns. + * + * @return array + */ + public static function getTrustedHosts() + { + return self::$trustedHostPatterns; + } + + /** + * Normalizes a query string. + * + * It builds a normalized query string, where keys/value pairs are alphabetized, + * have consistent escaping and unneeded delimiters are removed. + * + * @return string + */ + public static function normalizeQueryString(?string $qs) + { + if ('' === ($qs ?? '')) { + return ''; + } + + $qs = HeaderUtils::parseQuery($qs); + ksort($qs); + + return http_build_query($qs, '', '&', \PHP_QUERY_RFC3986); + } + + /** + * Enables support for the _method request parameter to determine the intended HTTP method. + * + * Be warned that enabling this feature might lead to CSRF issues in your code. + * Check that you are using CSRF tokens when required. + * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered + * and used to send a "PUT" or "DELETE" request via the _method request parameter. + * If these methods are not protected against CSRF, this presents a possible vulnerability. + * + * The HTTP method can only be overridden when the real HTTP method is POST. + */ + public static function enableHttpMethodParameterOverride() + { + self::$httpMethodParameterOverride = true; + } + + /** + * Checks whether support for the _method request parameter is enabled. + * + * @return bool + */ + public static function getHttpMethodParameterOverride() + { + return self::$httpMethodParameterOverride; + } + + /** + * Gets a "parameter" value from any bag. + * + * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the + * flexibility in controllers, it is better to explicitly get request parameters from the appropriate + * public property instead (attributes, query, request). + * + * Order of precedence: PATH (routing placeholders or custom attributes), GET, POST + * + * @param mixed $default The default value if the parameter key does not exist + * + * @return mixed + * + * @internal since Symfony 5.4, use explicit input sources instead + */ + public function get(string $key, $default = null) + { + if ($this !== $result = $this->attributes->get($key, $this)) { + return $result; + } + + if ($this->query->has($key)) { + return $this->query->all()[$key]; + } + + if ($this->request->has($key)) { + return $this->request->all()[$key]; + } + + return $default; + } + + /** + * Gets the Session. + * + * @return SessionInterface + */ + public function getSession() + { + $session = $this->session; + if (!$session instanceof SessionInterface && null !== $session) { + $this->setSession($session = $session()); + } + + if (null === $session) { + throw new SessionNotFoundException('Session has not been set.'); + } + + return $session; + } + + /** + * Whether the request contains a Session which was started in one of the + * previous requests. + * + * @return bool + */ + public function hasPreviousSession() + { + // the check for $this->session avoids malicious users trying to fake a session cookie with proper name + return $this->hasSession() && $this->cookies->has($this->getSession()->getName()); + } + + /** + * Whether the request contains a Session object. + * + * This method does not give any information about the state of the session object, + * like whether the session is started or not. It is just a way to check if this Request + * is associated with a Session instance. + * + * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory` + * + * @return bool + */ + public function hasSession(/* bool $skipIfUninitialized = false */) + { + $skipIfUninitialized = \func_num_args() > 0 ? func_get_arg(0) : false; + + return null !== $this->session && (!$skipIfUninitialized || $this->session instanceof SessionInterface); + } + + public function setSession(SessionInterface $session) + { + $this->session = $session; + } + + /** + * @internal + * + * @param callable(): SessionInterface $factory + */ + public function setSessionFactory(callable $factory) + { + $this->session = $factory; + } + + /** + * Returns the client IP addresses. + * + * In the returned array the most trusted IP address is first, and the + * least trusted one last. The "real" client IP address is the last one, + * but this is also the least trusted one. Trusted proxies are stripped. + * + * Use this method carefully; you should use getClientIp() instead. + * + * @return array + * + * @see getClientIp() + */ + public function getClientIps() + { + $ip = $this->server->get('REMOTE_ADDR'); + + if (!$this->isFromTrustedProxy()) { + return [$ip]; + } + + return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: [$ip]; + } + + /** + * Returns the client IP address. + * + * This method can read the client IP address from the "X-Forwarded-For" header + * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" + * header value is a comma+space separated list of IP addresses, the left-most + * being the original client, and each successive proxy that passed the request + * adding the IP address where it received the request from. + * + * If your reverse proxy uses a different header name than "X-Forwarded-For", + * ("Client-Ip" for instance), configure it via the $trustedHeaderSet + * argument of the Request::setTrustedProxies() method instead. + * + * @return string|null + * + * @see getClientIps() + * @see https://wikipedia.org/wiki/X-Forwarded-For + */ + public function getClientIp() + { + $ipAddresses = $this->getClientIps(); + + return $ipAddresses[0]; + } + + /** + * Returns current script name. + * + * @return string + */ + public function getScriptName() + { + return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', '')); + } + + /** + * Returns the path being requested relative to the executed script. + * + * The path info always starts with a /. + * + * Suppose this request is instantiated from /mysite on localhost: + * + * * http://localhost/mysite returns an empty string + * * http://localhost/mysite/about returns '/about' + * * http://localhost/mysite/enco%20ded returns '/enco%20ded' + * * http://localhost/mysite/about?var=1 returns '/about' + * + * @return string The raw path (i.e. not urldecoded) + */ + public function getPathInfo() + { + if (null === $this->pathInfo) { + $this->pathInfo = $this->preparePathInfo(); + } + + return $this->pathInfo; + } + + /** + * Returns the root path from which this request is executed. + * + * Suppose that an index.php file instantiates this request object: + * + * * http://localhost/index.php returns an empty string + * * http://localhost/index.php/page returns an empty string + * * http://localhost/web/index.php returns '/web' + * * http://localhost/we%20b/index.php returns '/we%20b' + * + * @return string The raw path (i.e. not urldecoded) + */ + public function getBasePath() + { + if (null === $this->basePath) { + $this->basePath = $this->prepareBasePath(); + } + + return $this->basePath; + } + + /** + * Returns the root URL from which this request is executed. + * + * The base URL never ends with a /. + * + * This is similar to getBasePath(), except that it also includes the + * script filename (e.g. index.php) if one exists. + * + * @return string The raw URL (i.e. not urldecoded) + */ + public function getBaseUrl() + { + $trustedPrefix = ''; + + // the proxy prefix must be prepended to any prefix being needed at the webserver level + if ($this->isFromTrustedProxy() && $trustedPrefixValues = $this->getTrustedValues(self::HEADER_X_FORWARDED_PREFIX)) { + $trustedPrefix = rtrim($trustedPrefixValues[0], '/'); + } + + return $trustedPrefix.$this->getBaseUrlReal(); + } + + /** + * Returns the real base URL received by the webserver from which this request is executed. + * The URL does not include trusted reverse proxy prefix. + * + * @return string The raw URL (i.e. not urldecoded) + */ + private function getBaseUrlReal(): string + { + if (null === $this->baseUrl) { + $this->baseUrl = $this->prepareBaseUrl(); + } + + return $this->baseUrl; + } + + /** + * Gets the request's scheme. + * + * @return string + */ + public function getScheme() + { + return $this->isSecure() ? 'https' : 'http'; + } + + /** + * Returns the port on which the request is made. + * + * This method can read the client port from the "X-Forwarded-Port" header + * when trusted proxies were set via "setTrustedProxies()". + * + * The "X-Forwarded-Port" header must contain the client port. + * + * @return int|string|null Can be a string if fetched from the server bag + */ + public function getPort() + { + if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) { + $host = $host[0]; + } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) { + $host = $host[0]; + } elseif (!$host = $this->headers->get('HOST')) { + return $this->server->get('SERVER_PORT'); + } + + if ('[' === $host[0]) { + $pos = strpos($host, ':', strrpos($host, ']')); + } else { + $pos = strrpos($host, ':'); + } + + if (false !== $pos && $port = substr($host, $pos + 1)) { + return (int) $port; + } + + return 'https' === $this->getScheme() ? 443 : 80; + } + + /** + * Returns the user. + * + * @return string|null + */ + public function getUser() + { + return $this->headers->get('PHP_AUTH_USER'); + } + + /** + * Returns the password. + * + * @return string|null + */ + public function getPassword() + { + return $this->headers->get('PHP_AUTH_PW'); + } + + /** + * Gets the user info. + * + * @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server + */ + public function getUserInfo() + { + $userinfo = $this->getUser(); + + $pass = $this->getPassword(); + if ('' != $pass) { + $userinfo .= ":$pass"; + } + + return $userinfo; + } + + /** + * Returns the HTTP host being requested. + * + * The port name will be appended to the host if it's non-standard. + * + * @return string + */ + public function getHttpHost() + { + $scheme = $this->getScheme(); + $port = $this->getPort(); + + if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) { + return $this->getHost(); + } + + return $this->getHost().':'.$port; + } + + /** + * Returns the requested URI (path and query string). + * + * @return string The raw URI (i.e. not URI decoded) + */ + public function getRequestUri() + { + if (null === $this->requestUri) { + $this->requestUri = $this->prepareRequestUri(); + } + + return $this->requestUri; + } + + /** + * Gets the scheme and HTTP host. + * + * If the URL was called with basic authentication, the user + * and the password are not added to the generated string. + * + * @return string + */ + public function getSchemeAndHttpHost() + { + return $this->getScheme().'://'.$this->getHttpHost(); + } + + /** + * Generates a normalized URI (URL) for the Request. + * + * @return string + * + * @see getQueryString() + */ + public function getUri() + { + if (null !== $qs = $this->getQueryString()) { + $qs = '?'.$qs; + } + + return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs; + } + + /** + * Generates a normalized URI for the given path. + * + * @param string $path A path to use instead of the current one + * + * @return string + */ + public function getUriForPath(string $path) + { + return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path; + } + + /** + * Returns the path as relative reference from the current Request path. + * + * Only the URIs path component (no schema, host etc.) is relevant and must be given. + * Both paths must be absolute and not contain relative parts. + * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. + * Furthermore, they can be used to reduce the link size in documents. + * + * Example target paths, given a base path of "/a/b/c/d": + * - "/a/b/c/d" -> "" + * - "/a/b/c/" -> "./" + * - "/a/b/" -> "../" + * - "/a/b/c/other" -> "other" + * - "/a/x/y" -> "../../x/y" + * + * @return string + */ + public function getRelativeUriForPath(string $path) + { + // be sure that we are dealing with an absolute path + if (!isset($path[0]) || '/' !== $path[0]) { + return $path; + } + + if ($path === $basePath = $this->getPathInfo()) { + return ''; + } + + $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath); + $targetDirs = explode('/', substr($path, 1)); + array_pop($sourceDirs); + $targetFile = array_pop($targetDirs); + + foreach ($sourceDirs as $i => $dir) { + if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) { + unset($sourceDirs[$i], $targetDirs[$i]); + } else { + break; + } + } + + $targetDirs[] = $targetFile; + $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs); + + // A reference to the same base directory or an empty subdirectory must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name + // (see https://tools.ietf.org/html/rfc3986#section-4.2). + return !isset($path[0]) || '/' === $path[0] + || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) + ? "./$path" : $path; + } + + /** + * Generates the normalized query string for the Request. + * + * It builds a normalized query string, where keys/value pairs are alphabetized + * and have consistent escaping. + * + * @return string|null + */ + public function getQueryString() + { + $qs = static::normalizeQueryString($this->server->get('QUERY_STRING')); + + return '' === $qs ? null : $qs; + } + + /** + * Checks whether the request is secure or not. + * + * This method can read the client protocol from the "X-Forwarded-Proto" header + * when trusted proxies were set via "setTrustedProxies()". + * + * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". + * + * @return bool + */ + public function isSecure() + { + if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) { + return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true); + } + + $https = $this->server->get('HTTPS'); + + return !empty($https) && 'off' !== strtolower($https); + } + + /** + * Returns the host name. + * + * This method can read the client host name from the "X-Forwarded-Host" header + * when trusted proxies were set via "setTrustedProxies()". + * + * The "X-Forwarded-Host" header must contain the client host name. + * + * @return string + * + * @throws SuspiciousOperationException when the host name is invalid or not trusted + */ + public function getHost() + { + if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) { + $host = $host[0]; + } elseif (!$host = $this->headers->get('HOST')) { + if (!$host = $this->server->get('SERVER_NAME')) { + $host = $this->server->get('SERVER_ADDR', ''); + } + } + + // trim and remove port number from host + // host is lowercase as per RFC 952/2181 + $host = strtolower(preg_replace('/:\d+$/', '', trim($host))); + + // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user) + // check that it does not contain forbidden characters (see RFC 952 and RFC 2181) + // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names + if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) { + if (!$this->isHostValid) { + return ''; + } + $this->isHostValid = false; + + throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host)); + } + + if (\count(self::$trustedHostPatterns) > 0) { + // to avoid host header injection attacks, you should provide a list of trusted host patterns + + if (\in_array($host, self::$trustedHosts)) { + return $host; + } + + foreach (self::$trustedHostPatterns as $pattern) { + if (preg_match($pattern, $host)) { + self::$trustedHosts[] = $host; + + return $host; + } + } + + if (!$this->isHostValid) { + return ''; + } + $this->isHostValid = false; + + throw new SuspiciousOperationException(sprintf('Untrusted Host "%s".', $host)); + } + + return $host; + } + + /** + * Sets the request method. + */ + public function setMethod(string $method) + { + $this->method = null; + $this->server->set('REQUEST_METHOD', $method); + } + + /** + * Gets the request "intended" method. + * + * If the X-HTTP-Method-Override header is set, and if the method is a POST, + * then it is used to determine the "real" intended HTTP method. + * + * The _method request parameter can also be used to determine the HTTP method, + * but only if enableHttpMethodParameterOverride() has been called. + * + * The method is always an uppercased string. + * + * @return string + * + * @see getRealMethod() + */ + public function getMethod() + { + if (null !== $this->method) { + return $this->method; + } + + $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET')); + + if ('POST' !== $this->method) { + return $this->method; + } + + $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE'); + + if (!$method && self::$httpMethodParameterOverride) { + $method = $this->request->get('_method', $this->query->get('_method', 'POST')); + } + + if (!\is_string($method)) { + return $this->method; + } + + $method = strtoupper($method); + + if (\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) { + return $this->method = $method; + } + + if (!preg_match('/^[A-Z]++$/D', $method)) { + throw new SuspiciousOperationException(sprintf('Invalid method override "%s".', $method)); + } + + return $this->method = $method; + } + + /** + * Gets the "real" request method. + * + * @return string + * + * @see getMethod() + */ + public function getRealMethod() + { + return strtoupper($this->server->get('REQUEST_METHOD', 'GET')); + } + + /** + * Gets the mime type associated with the format. + * + * @return string|null + */ + public function getMimeType(string $format) + { + if (null === static::$formats) { + static::initializeFormats(); + } + + return isset(static::$formats[$format]) ? static::$formats[$format][0] : null; + } + + /** + * Gets the mime types associated with the format. + * + * @return array + */ + public static function getMimeTypes(string $format) + { + if (null === static::$formats) { + static::initializeFormats(); + } + + return static::$formats[$format] ?? []; + } + + /** + * Gets the format associated with the mime type. + * + * @return string|null + */ + public function getFormat(?string $mimeType) + { + $canonicalMimeType = null; + if ($mimeType && false !== $pos = strpos($mimeType, ';')) { + $canonicalMimeType = trim(substr($mimeType, 0, $pos)); + } + + if (null === static::$formats) { + static::initializeFormats(); + } + + foreach (static::$formats as $format => $mimeTypes) { + if (\in_array($mimeType, (array) $mimeTypes)) { + return $format; + } + if (null !== $canonicalMimeType && \in_array($canonicalMimeType, (array) $mimeTypes)) { + return $format; + } + } + + return null; + } + + /** + * Associates a format with mime types. + * + * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type) + */ + public function setFormat(?string $format, $mimeTypes) + { + if (null === static::$formats) { + static::initializeFormats(); + } + + static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes]; + } + + /** + * Gets the request format. + * + * Here is the process to determine the format: + * + * * format defined by the user (with setRequestFormat()) + * * _format request attribute + * * $default + * + * @see getPreferredFormat + * + * @return string|null + */ + public function getRequestFormat(?string $default = 'html') + { + if (null === $this->format) { + $this->format = $this->attributes->get('_format'); + } + + return $this->format ?? $default; + } + + /** + * Sets the request format. + */ + public function setRequestFormat(?string $format) + { + $this->format = $format; + } + + /** + * Gets the format associated with the request. + * + * @return string|null + */ + public function getContentType() + { + return $this->getFormat($this->headers->get('CONTENT_TYPE', '')); + } + + /** + * Sets the default locale. + */ + public function setDefaultLocale(string $locale) + { + $this->defaultLocale = $locale; + + if (null === $this->locale) { + $this->setPhpDefaultLocale($locale); + } + } + + /** + * Get the default locale. + * + * @return string + */ + public function getDefaultLocale() + { + return $this->defaultLocale; + } + + /** + * Sets the locale. + */ + public function setLocale(string $locale) + { + $this->setPhpDefaultLocale($this->locale = $locale); + } + + /** + * Get the locale. + * + * @return string + */ + public function getLocale() + { + return $this->locale ?? $this->defaultLocale; + } + + /** + * Checks if the request method is of specified type. + * + * @param string $method Uppercase request method (GET, POST etc) + * + * @return bool + */ + public function isMethod(string $method) + { + return $this->getMethod() === strtoupper($method); + } + + /** + * Checks whether or not the method is safe. + * + * @see https://tools.ietf.org/html/rfc7231#section-4.2.1 + * + * @return bool + */ + public function isMethodSafe() + { + return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']); + } + + /** + * Checks whether or not the method is idempotent. + * + * @return bool + */ + public function isMethodIdempotent() + { + return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']); + } + + /** + * Checks whether the method is cacheable or not. + * + * @see https://tools.ietf.org/html/rfc7231#section-4.2.3 + * + * @return bool + */ + public function isMethodCacheable() + { + return \in_array($this->getMethod(), ['GET', 'HEAD']); + } + + /** + * Returns the protocol version. + * + * If the application is behind a proxy, the protocol version used in the + * requests between the client and the proxy and between the proxy and the + * server might be different. This returns the former (from the "Via" header) + * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns + * the latter (from the "SERVER_PROTOCOL" server parameter). + * + * @return string|null + */ + public function getProtocolVersion() + { + if ($this->isFromTrustedProxy()) { + preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via') ?? '', $matches); + + if ($matches) { + return 'HTTP/'.$matches[2]; + } + } + + return $this->server->get('SERVER_PROTOCOL'); + } + + /** + * Returns the request body content. + * + * @param bool $asResource If true, a resource will be returned + * + * @return string|resource + */ + public function getContent(bool $asResource = false) + { + $currentContentIsResource = \is_resource($this->content); + + if (true === $asResource) { + if ($currentContentIsResource) { + rewind($this->content); + + return $this->content; + } + + // Content passed in parameter (test) + if (\is_string($this->content)) { + $resource = fopen('php://temp', 'r+'); + fwrite($resource, $this->content); + rewind($resource); + + return $resource; + } + + $this->content = false; + + return fopen('php://input', 'r'); + } + + if ($currentContentIsResource) { + rewind($this->content); + + return stream_get_contents($this->content); + } + + if (null === $this->content || false === $this->content) { + $this->content = file_get_contents('php://input'); + } + + return $this->content; + } + + /** + * Gets the request body decoded as array, typically from a JSON payload. + * + * @return array + * + * @throws JsonException When the body cannot be decoded to an array + */ + public function toArray() + { + if ('' === $content = $this->getContent()) { + throw new JsonException('Request body is empty.'); + } + + try { + $content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0)); + } catch (\JsonException $e) { + throw new JsonException('Could not decode request body.', $e->getCode(), $e); + } + + if (\PHP_VERSION_ID < 70300 && \JSON_ERROR_NONE !== json_last_error()) { + throw new JsonException('Could not decode request body: '.json_last_error_msg(), json_last_error()); + } + + if (!\is_array($content)) { + throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned.', get_debug_type($content))); + } + + return $content; + } + + /** + * Gets the Etags. + * + * @return array + */ + public function getETags() + { + return preg_split('/\s*,\s*/', $this->headers->get('If-None-Match', ''), -1, \PREG_SPLIT_NO_EMPTY); + } + + /** + * @return bool + */ + public function isNoCache() + { + return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma'); + } + + /** + * Gets the preferred format for the response by inspecting, in the following order: + * * the request format set using setRequestFormat; + * * the values of the Accept HTTP header. + * + * Note that if you use this method, you should send the "Vary: Accept" header + * in the response to prevent any issues with intermediary HTTP caches. + */ + public function getPreferredFormat(?string $default = 'html'): ?string + { + if (null !== $this->preferredFormat || null !== $this->preferredFormat = $this->getRequestFormat(null)) { + return $this->preferredFormat; + } + + foreach ($this->getAcceptableContentTypes() as $mimeType) { + if ($this->preferredFormat = $this->getFormat($mimeType)) { + return $this->preferredFormat; + } + } + + return $default; + } + + /** + * Returns the preferred language. + * + * @param string[] $locales An array of ordered available locales + * + * @return string|null + */ + public function getPreferredLanguage(?array $locales = null) + { + $preferredLanguages = $this->getLanguages(); + + if (empty($locales)) { + return $preferredLanguages[0] ?? null; + } + + if (!$preferredLanguages) { + return $locales[0]; + } + + $extendedPreferredLanguages = []; + foreach ($preferredLanguages as $language) { + $extendedPreferredLanguages[] = $language; + if (false !== $position = strpos($language, '_')) { + $superLanguage = substr($language, 0, $position); + if (!\in_array($superLanguage, $preferredLanguages)) { + $extendedPreferredLanguages[] = $superLanguage; + } + } + } + + $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales)); + + return $preferredLanguages[0] ?? $locales[0]; + } + + /** + * Gets a list of languages acceptable by the client browser ordered in the user browser preferences. + * + * @return array + */ + public function getLanguages() + { + if (null !== $this->languages) { + return $this->languages; + } + + $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all(); + $this->languages = []; + foreach ($languages as $acceptHeaderItem) { + $lang = $acceptHeaderItem->getValue(); + if (str_contains($lang, '-')) { + $codes = explode('-', $lang); + if ('i' === $codes[0]) { + // Language not listed in ISO 639 that are not variants + // of any listed language, which can be registered with the + // i-prefix, such as i-cherokee + if (\count($codes) > 1) { + $lang = $codes[1]; + } + } else { + for ($i = 0, $max = \count($codes); $i < $max; ++$i) { + if (0 === $i) { + $lang = strtolower($codes[0]); + } else { + $lang .= '_'.strtoupper($codes[$i]); + } + } + } + } + + $this->languages[] = $lang; + } + + return $this->languages; + } + + /** + * Gets a list of charsets acceptable by the client browser in preferable order. + * + * @return array + */ + public function getCharsets() + { + if (null !== $this->charsets) { + return $this->charsets; + } + + return $this->charsets = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all())); + } + + /** + * Gets a list of encodings acceptable by the client browser in preferable order. + * + * @return array + */ + public function getEncodings() + { + if (null !== $this->encodings) { + return $this->encodings; + } + + return $this->encodings = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all())); + } + + /** + * Gets a list of content types acceptable by the client browser in preferable order. + * + * @return array + */ + public function getAcceptableContentTypes() + { + if (null !== $this->acceptableContentTypes) { + return $this->acceptableContentTypes; + } + + return $this->acceptableContentTypes = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all())); + } + + /** + * Returns true if the request is an XMLHttpRequest. + * + * It works if your JavaScript library sets an X-Requested-With HTTP header. + * It is known to work with common JavaScript frameworks: + * + * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript + * + * @return bool + */ + public function isXmlHttpRequest() + { + return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); + } + + /** + * Checks whether the client browser prefers safe content or not according to RFC8674. + * + * @see https://tools.ietf.org/html/rfc8674 + */ + public function preferSafeContent(): bool + { + if (null !== $this->isSafeContentPreferred) { + return $this->isSafeContentPreferred; + } + + if (!$this->isSecure()) { + // see https://tools.ietf.org/html/rfc8674#section-3 + return $this->isSafeContentPreferred = false; + } + + return $this->isSafeContentPreferred = AcceptHeader::fromString($this->headers->get('Prefer'))->has('safe'); + } + + /* + * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24) + * + * Code subject to the new BSD license (https://framework.zend.com/license). + * + * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/) + */ + + protected function prepareRequestUri() + { + $requestUri = ''; + + if ($this->isIisRewrite() && '' != $this->server->get('UNENCODED_URL')) { + // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem) + $requestUri = $this->server->get('UNENCODED_URL'); + $this->server->remove('UNENCODED_URL'); + } elseif ($this->server->has('REQUEST_URI')) { + $requestUri = $this->server->get('REQUEST_URI'); + + if ('' !== $requestUri && '/' === $requestUri[0]) { + // To only use path and query remove the fragment. + if (false !== $pos = strpos($requestUri, '#')) { + $requestUri = substr($requestUri, 0, $pos); + } + } else { + // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, + // only use URL path. + $uriComponents = parse_url($requestUri); + + if (isset($uriComponents['path'])) { + $requestUri = $uriComponents['path']; + } + + if (isset($uriComponents['query'])) { + $requestUri .= '?'.$uriComponents['query']; + } + } + } elseif ($this->server->has('ORIG_PATH_INFO')) { + // IIS 5.0, PHP as CGI + $requestUri = $this->server->get('ORIG_PATH_INFO'); + if ('' != $this->server->get('QUERY_STRING')) { + $requestUri .= '?'.$this->server->get('QUERY_STRING'); + } + $this->server->remove('ORIG_PATH_INFO'); + } + + // normalize the request URI to ease creating sub-requests from this request + $this->server->set('REQUEST_URI', $requestUri); + + return $requestUri; + } + + /** + * Prepares the base URL. + * + * @return string + */ + protected function prepareBaseUrl() + { + $filename = basename($this->server->get('SCRIPT_FILENAME', '')); + + if (basename($this->server->get('SCRIPT_NAME', '')) === $filename) { + $baseUrl = $this->server->get('SCRIPT_NAME'); + } elseif (basename($this->server->get('PHP_SELF', '')) === $filename) { + $baseUrl = $this->server->get('PHP_SELF'); + } elseif (basename($this->server->get('ORIG_SCRIPT_NAME', '')) === $filename) { + $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility + } else { + // Backtrack up the script_filename to find the portion matching + // php_self + $path = $this->server->get('PHP_SELF', ''); + $file = $this->server->get('SCRIPT_FILENAME', ''); + $segs = explode('/', trim($file, '/')); + $segs = array_reverse($segs); + $index = 0; + $last = \count($segs); + $baseUrl = ''; + do { + $seg = $segs[$index]; + $baseUrl = '/'.$seg.$baseUrl; + ++$index; + } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos); + } + + // Does the baseUrl have anything in common with the request_uri? + $requestUri = $this->getRequestUri(); + if ('' !== $requestUri && '/' !== $requestUri[0]) { + $requestUri = '/'.$requestUri; + } + + if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { + // full $baseUrl matches + return $prefix; + } + + if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) { + // directory portion of $baseUrl matches + return rtrim($prefix, '/'.\DIRECTORY_SEPARATOR); + } + + $truncatedRequestUri = $requestUri; + if (false !== $pos = strpos($requestUri, '?')) { + $truncatedRequestUri = substr($requestUri, 0, $pos); + } + + $basename = basename($baseUrl ?? ''); + if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) { + // no match whatsoever; set it blank + return ''; + } + + // If using mod_rewrite or ISAPI_Rewrite strip the script filename + // out of baseUrl. $pos !== 0 makes sure it is not matching a value + // from PATH_INFO or QUERY_STRING + if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) { + $baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl)); + } + + return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR); + } + + /** + * Prepares the base path. + * + * @return string + */ + protected function prepareBasePath() + { + $baseUrl = $this->getBaseUrl(); + if (empty($baseUrl)) { + return ''; + } + + $filename = basename($this->server->get('SCRIPT_FILENAME')); + if (basename($baseUrl) === $filename) { + $basePath = \dirname($baseUrl); + } else { + $basePath = $baseUrl; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + $basePath = str_replace('\\', '/', $basePath); + } + + return rtrim($basePath, '/'); + } + + /** + * Prepares the path info. + * + * @return string + */ + protected function preparePathInfo() + { + if (null === ($requestUri = $this->getRequestUri())) { + return '/'; + } + + // Remove the query string from REQUEST_URI + if (false !== $pos = strpos($requestUri, '?')) { + $requestUri = substr($requestUri, 0, $pos); + } + if ('' !== $requestUri && '/' !== $requestUri[0]) { + $requestUri = '/'.$requestUri; + } + + if (null === ($baseUrl = $this->getBaseUrlReal())) { + return $requestUri; + } + + $pathInfo = substr($requestUri, \strlen($baseUrl)); + if (false === $pathInfo || '' === $pathInfo) { + // If substr() returns false then PATH_INFO is set to an empty string + return '/'; + } + + return $pathInfo; + } + + /** + * Initializes HTTP request formats. + */ + protected static function initializeFormats() + { + static::$formats = [ + 'html' => ['text/html', 'application/xhtml+xml'], + 'txt' => ['text/plain'], + 'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'], + 'css' => ['text/css'], + 'json' => ['application/json', 'application/x-json'], + 'jsonld' => ['application/ld+json'], + 'xml' => ['text/xml', 'application/xml', 'application/x-xml'], + 'rdf' => ['application/rdf+xml'], + 'atom' => ['application/atom+xml'], + 'rss' => ['application/rss+xml'], + 'form' => ['application/x-www-form-urlencoded', 'multipart/form-data'], + ]; + } + + private function setPhpDefaultLocale(string $locale): void + { + // if either the class Locale doesn't exist, or an exception is thrown when + // setting the default locale, the intl module is not installed, and + // the call can be ignored: + try { + if (class_exists(\Locale::class, false)) { + \Locale::setDefault($locale); + } + } catch (\Exception $e) { + } + } + + /** + * Returns the prefix as encoded in the string when the string starts with + * the given prefix, null otherwise. + */ + private function getUrlencodedPrefix(string $string, string $prefix): ?string + { + if ($this->isIisRewrite()) { + // ISS with UrlRewriteModule might report SCRIPT_NAME/PHP_SELF with wrong case + // see https://github.com/php/php-src/issues/11981 + if (0 !== stripos(rawurldecode($string), $prefix)) { + return null; + } + } elseif (!str_starts_with(rawurldecode($string), $prefix)) { + return null; + } + + $len = \strlen($prefix); + + if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) { + return $match[0]; + } + + return null; + } + + private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): self + { + if (self::$requestFactory) { + $request = (self::$requestFactory)($query, $request, $attributes, $cookies, $files, $server, $content); + + if (!$request instanceof self) { + throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.'); + } + + return $request; + } + + return new static($query, $request, $attributes, $cookies, $files, $server, $content); + } + + /** + * Indicates whether this request originated from a trusted proxy. + * + * This can be useful to determine whether or not to trust the + * contents of a proxy-specific header. + * + * @return bool + */ + public function isFromTrustedProxy() + { + return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR', ''), self::$trustedProxies); + } + + private function getTrustedValues(int $type, ?string $ip = null): array + { + $clientValues = []; + $forwardedValues = []; + + if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) { + foreach (explode(',', $this->headers->get(self::TRUSTED_HEADERS[$type])) as $v) { + $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v); + } + } + + if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && (isset(self::FORWARDED_PARAMS[$type])) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) { + $forwarded = $this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]); + $parts = HeaderUtils::split($forwarded, ',;='); + $forwardedValues = []; + $param = self::FORWARDED_PARAMS[$type]; + foreach ($parts as $subParts) { + if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) { + continue; + } + if (self::HEADER_X_FORWARDED_PORT === $type) { + if (str_ends_with($v, ']') || false === $v = strrchr($v, ':')) { + $v = $this->isSecure() ? ':443' : ':80'; + } + $v = '0.0.0.0'.$v; + } + $forwardedValues[] = $v; + } + } + + if (null !== $ip) { + $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip); + $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip); + } + + if ($forwardedValues === $clientValues || !$clientValues) { + return $forwardedValues; + } + + if (!$forwardedValues) { + return $clientValues; + } + + if (!$this->isForwardedValid) { + return null !== $ip ? ['0.0.0.0', $ip] : []; + } + $this->isForwardedValid = false; + + throw new ConflictingHeadersException(sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.', self::TRUSTED_HEADERS[self::HEADER_FORWARDED], self::TRUSTED_HEADERS[$type])); + } + + private function normalizeAndFilterClientIps(array $clientIps, string $ip): array + { + if (!$clientIps) { + return []; + } + $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from + $firstTrustedIp = null; + + foreach ($clientIps as $key => $clientIp) { + if (strpos($clientIp, '.')) { + // Strip :port from IPv4 addresses. This is allowed in Forwarded + // and may occur in X-Forwarded-For. + $i = strpos($clientIp, ':'); + if ($i) { + $clientIps[$key] = $clientIp = substr($clientIp, 0, $i); + } + } elseif (str_starts_with($clientIp, '[')) { + // Strip brackets and :port from IPv6 addresses. + $i = strpos($clientIp, ']', 1); + $clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1); + } + + if (!filter_var($clientIp, \FILTER_VALIDATE_IP)) { + unset($clientIps[$key]); + + continue; + } + + if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { + unset($clientIps[$key]); + + // Fallback to this when the client IP falls into the range of trusted proxies + if (null === $firstTrustedIp) { + $firstTrustedIp = $clientIp; + } + } + } + + // Now the IP chain contains only untrusted proxies and the client IP + return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp]; + } + + /** + * Is this IIS with UrlRewriteModule? + * + * This method consumes, caches and removed the IIS_WasUrlRewritten env var, + * so we don't inherit it to sub-requests. + */ + private function isIisRewrite(): bool + { + if (1 === $this->server->getInt('IIS_WasUrlRewritten')) { + $this->isIisRewrite = true; + $this->server->remove('IIS_WasUrlRewritten'); + } + + return $this->isIisRewrite; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/RequestMatcher.php b/php/libraries/composer/vendor/symfony/http-foundation/RequestMatcher.php new file mode 100644 index 0000000..03ccee9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/RequestMatcher.php @@ -0,0 +1,196 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * RequestMatcher compares a pre-defined set of checks against a Request instance. + * + * @author Fabien Potencier + */ +class RequestMatcher implements RequestMatcherInterface +{ + /** + * @var string|null + */ + private $path; + + /** + * @var string|null + */ + private $host; + + /** + * @var int|null + */ + private $port; + + /** + * @var string[] + */ + private $methods = []; + + /** + * @var string[] + */ + private $ips = []; + + /** + * @var array + */ + private $attributes = []; + + /** + * @var string[] + */ + private $schemes = []; + + /** + * @param string|string[]|null $methods + * @param string|string[]|null $ips + * @param string|string[]|null $schemes + */ + public function __construct(?string $path = null, ?string $host = null, $methods = null, $ips = null, array $attributes = [], $schemes = null, ?int $port = null) + { + $this->matchPath($path); + $this->matchHost($host); + $this->matchMethod($methods); + $this->matchIps($ips); + $this->matchScheme($schemes); + $this->matchPort($port); + + foreach ($attributes as $k => $v) { + $this->matchAttribute($k, $v); + } + } + + /** + * Adds a check for the HTTP scheme. + * + * @param string|string[]|null $scheme An HTTP scheme or an array of HTTP schemes + */ + public function matchScheme($scheme) + { + $this->schemes = null !== $scheme ? array_map('strtolower', (array) $scheme) : []; + } + + /** + * Adds a check for the URL host name. + */ + public function matchHost(?string $regexp) + { + $this->host = $regexp; + } + + /** + * Adds a check for the URL port. + * + * @param int|null $port The port number to connect to + */ + public function matchPort(?int $port) + { + $this->port = $port; + } + + /** + * Adds a check for the URL path info. + */ + public function matchPath(?string $regexp) + { + $this->path = $regexp; + } + + /** + * Adds a check for the client IP. + * + * @param string $ip A specific IP address or a range specified using IP/netmask like 192.168.1.0/24 + */ + public function matchIp(string $ip) + { + $this->matchIps($ip); + } + + /** + * Adds a check for the client IP. + * + * @param string|string[]|null $ips A specific IP address or a range specified using IP/netmask like 192.168.1.0/24 + */ + public function matchIps($ips) + { + $ips = null !== $ips ? (array) $ips : []; + + $this->ips = array_reduce($ips, static function (array $ips, string $ip) { + return array_merge($ips, preg_split('/\s*,\s*/', $ip)); + }, []); + } + + /** + * Adds a check for the HTTP method. + * + * @param string|string[]|null $method An HTTP method or an array of HTTP methods + */ + public function matchMethod($method) + { + $this->methods = null !== $method ? array_map('strtoupper', (array) $method) : []; + } + + /** + * Adds a check for request attribute. + */ + public function matchAttribute(string $key, string $regexp) + { + $this->attributes[$key] = $regexp; + } + + /** + * {@inheritdoc} + */ + public function matches(Request $request) + { + if ($this->schemes && !\in_array($request->getScheme(), $this->schemes, true)) { + return false; + } + + if ($this->methods && !\in_array($request->getMethod(), $this->methods, true)) { + return false; + } + + foreach ($this->attributes as $key => $pattern) { + $requestAttribute = $request->attributes->get($key); + if (!\is_string($requestAttribute)) { + return false; + } + if (!preg_match('{'.$pattern.'}', $requestAttribute)) { + return false; + } + } + + if (null !== $this->path && !preg_match('{'.$this->path.'}', rawurldecode($request->getPathInfo()))) { + return false; + } + + if (null !== $this->host && !preg_match('{'.$this->host.'}i', $request->getHost())) { + return false; + } + + if (null !== $this->port && 0 < $this->port && $request->getPort() !== $this->port) { + return false; + } + + if (IpUtils::checkIp($request->getClientIp() ?? '', $this->ips)) { + return true; + } + + // Note to future implementors: add additional checks above the + // foreach above or else your check might not be run! + return 0 === \count($this->ips); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/RequestMatcherInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/RequestMatcherInterface.php new file mode 100644 index 0000000..c2e1478 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/RequestMatcherInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * RequestMatcherInterface is an interface for strategies to match a Request. + * + * @author Fabien Potencier + */ +interface RequestMatcherInterface +{ + /** + * Decides whether the rule(s) implemented by the strategy matches the supplied request. + * + * @return bool + */ + public function matches(Request $request); +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/RequestStack.php b/php/libraries/composer/vendor/symfony/http-foundation/RequestStack.php new file mode 100644 index 0000000..855b518 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/RequestStack.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\HttpFoundation; + +use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +/** + * Request stack that controls the lifecycle of requests. + * + * @author Benjamin Eberlei + */ +class RequestStack +{ + /** + * @var Request[] + */ + private $requests = []; + + /** + * Pushes a Request on the stack. + * + * This method should generally not be called directly as the stack + * management should be taken care of by the application itself. + */ + public function push(Request $request) + { + $this->requests[] = $request; + } + + /** + * Pops the current request from the stack. + * + * This operation lets the current request go out of scope. + * + * This method should generally not be called directly as the stack + * management should be taken care of by the application itself. + * + * @return Request|null + */ + public function pop() + { + if (!$this->requests) { + return null; + } + + return array_pop($this->requests); + } + + /** + * @return Request|null + */ + public function getCurrentRequest() + { + return end($this->requests) ?: null; + } + + /** + * Gets the main request. + * + * Be warned that making your code aware of the main request + * might make it un-compatible with other features of your framework + * like ESI support. + */ + public function getMainRequest(): ?Request + { + if (!$this->requests) { + return null; + } + + return $this->requests[0]; + } + + /** + * Gets the master request. + * + * @return Request|null + * + * @deprecated since symfony/http-foundation 5.3, use getMainRequest() instead + */ + public function getMasterRequest() + { + trigger_deprecation('symfony/http-foundation', '5.3', '"%s()" is deprecated, use "getMainRequest()" instead.', __METHOD__); + + return $this->getMainRequest(); + } + + /** + * Returns the parent request of the current. + * + * Be warned that making your code aware of the parent request + * might make it un-compatible with other features of your framework + * like ESI support. + * + * If current Request is the main request, it returns null. + * + * @return Request|null + */ + public function getParentRequest() + { + $pos = \count($this->requests) - 2; + + return $this->requests[$pos] ?? null; + } + + /** + * Gets the current session. + * + * @throws SessionNotFoundException + */ + public function getSession(): SessionInterface + { + if ((null !== $request = end($this->requests) ?: null) && $request->hasSession()) { + return $request->getSession(); + } + + throw new SessionNotFoundException(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Response.php b/php/libraries/composer/vendor/symfony/http-foundation/Response.php new file mode 100644 index 0000000..6798a04 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Response.php @@ -0,0 +1,1288 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +// Help opcache.preload discover always-needed symbols +class_exists(ResponseHeaderBag::class); + +/** + * Response represents an HTTP response. + * + * @author Fabien Potencier + */ +class Response +{ + public const HTTP_CONTINUE = 100; + public const HTTP_SWITCHING_PROTOCOLS = 101; + public const HTTP_PROCESSING = 102; // RFC2518 + public const HTTP_EARLY_HINTS = 103; // RFC8297 + public const HTTP_OK = 200; + public const HTTP_CREATED = 201; + public const HTTP_ACCEPTED = 202; + public const HTTP_NON_AUTHORITATIVE_INFORMATION = 203; + public const HTTP_NO_CONTENT = 204; + public const HTTP_RESET_CONTENT = 205; + public const HTTP_PARTIAL_CONTENT = 206; + public const HTTP_MULTI_STATUS = 207; // RFC4918 + public const HTTP_ALREADY_REPORTED = 208; // RFC5842 + public const HTTP_IM_USED = 226; // RFC3229 + public const HTTP_MULTIPLE_CHOICES = 300; + public const HTTP_MOVED_PERMANENTLY = 301; + public const HTTP_FOUND = 302; + public const HTTP_SEE_OTHER = 303; + public const HTTP_NOT_MODIFIED = 304; + public const HTTP_USE_PROXY = 305; + public const HTTP_RESERVED = 306; + public const HTTP_TEMPORARY_REDIRECT = 307; + public const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238 + public const HTTP_BAD_REQUEST = 400; + public const HTTP_UNAUTHORIZED = 401; + public const HTTP_PAYMENT_REQUIRED = 402; + public const HTTP_FORBIDDEN = 403; + public const HTTP_NOT_FOUND = 404; + public const HTTP_METHOD_NOT_ALLOWED = 405; + public const HTTP_NOT_ACCEPTABLE = 406; + public const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; + public const HTTP_REQUEST_TIMEOUT = 408; + public const HTTP_CONFLICT = 409; + public const HTTP_GONE = 410; + public const HTTP_LENGTH_REQUIRED = 411; + public const HTTP_PRECONDITION_FAILED = 412; + public const HTTP_REQUEST_ENTITY_TOO_LARGE = 413; + public const HTTP_REQUEST_URI_TOO_LONG = 414; + public const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; + public const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; + public const HTTP_EXPECTATION_FAILED = 417; + public const HTTP_I_AM_A_TEAPOT = 418; // RFC2324 + public const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540 + public const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918 + public const HTTP_LOCKED = 423; // RFC4918 + public const HTTP_FAILED_DEPENDENCY = 424; // RFC4918 + public const HTTP_TOO_EARLY = 425; // RFC-ietf-httpbis-replay-04 + public const HTTP_UPGRADE_REQUIRED = 426; // RFC2817 + public const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585 + public const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585 + public const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585 + public const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; // RFC7725 + public const HTTP_INTERNAL_SERVER_ERROR = 500; + public const HTTP_NOT_IMPLEMENTED = 501; + public const HTTP_BAD_GATEWAY = 502; + public const HTTP_SERVICE_UNAVAILABLE = 503; + public const HTTP_GATEWAY_TIMEOUT = 504; + public const HTTP_VERSION_NOT_SUPPORTED = 505; + public const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295 + public const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918 + public const HTTP_LOOP_DETECTED = 508; // RFC5842 + public const HTTP_NOT_EXTENDED = 510; // RFC2774 + public const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585 + + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + */ + private const HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES = [ + 'must_revalidate' => false, + 'no_cache' => false, + 'no_store' => false, + 'no_transform' => false, + 'public' => false, + 'private' => false, + 'proxy_revalidate' => false, + 'max_age' => true, + 's_maxage' => true, + 'immutable' => false, + 'last_modified' => true, + 'etag' => true, + ]; + + /** + * @var ResponseHeaderBag + */ + public $headers; + + /** + * @var string + */ + protected $content; + + /** + * @var string + */ + protected $version; + + /** + * @var int + */ + protected $statusCode; + + /** + * @var string + */ + protected $statusText; + + /** + * @var string + */ + protected $charset; + + /** + * Status codes translation table. + * + * The list of codes is complete according to the + * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry} + * (last updated 2021-10-01). + * + * Unless otherwise noted, the status code is defined in RFC2616. + * + * @var array + */ + public static $statusTexts = [ + 100 => 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', // RFC2518 + 103 => 'Early Hints', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', // RFC4918 + 208 => 'Already Reported', // RFC5842 + 226 => 'IM Used', // RFC3229 + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', // RFC7238 + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Content Too Large', // RFC-ietf-httpbis-semantics + 414 => 'URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Range Not Satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', // RFC2324 + 421 => 'Misdirected Request', // RFC7540 + 422 => 'Unprocessable Content', // RFC-ietf-httpbis-semantics + 423 => 'Locked', // RFC4918 + 424 => 'Failed Dependency', // RFC4918 + 425 => 'Too Early', // RFC-ietf-httpbis-replay-04 + 426 => 'Upgrade Required', // RFC2817 + 428 => 'Precondition Required', // RFC6585 + 429 => 'Too Many Requests', // RFC6585 + 431 => 'Request Header Fields Too Large', // RFC6585 + 451 => 'Unavailable For Legal Reasons', // RFC7725 + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates', // RFC2295 + 507 => 'Insufficient Storage', // RFC4918 + 508 => 'Loop Detected', // RFC5842 + 510 => 'Not Extended', // RFC2774 + 511 => 'Network Authentication Required', // RFC6585 + ]; + + /** + * @throws \InvalidArgumentException When the HTTP status code is not valid + */ + public function __construct(?string $content = '', int $status = 200, array $headers = []) + { + $this->headers = new ResponseHeaderBag($headers); + $this->setContent($content); + $this->setStatusCode($status); + $this->setProtocolVersion('1.0'); + } + + /** + * Factory method for chainability. + * + * Example: + * + * return Response::create($body, 200) + * ->setSharedMaxAge(300); + * + * @return static + * + * @deprecated since Symfony 5.1, use __construct() instead. + */ + public static function create(?string $content = '', int $status = 200, array $headers = []) + { + trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class); + + return new static($content, $status, $headers); + } + + /** + * Returns the Response as an HTTP string. + * + * The string representation of the Response is the same as the + * one that will be sent to the client only if the prepare() method + * has been called before. + * + * @return string + * + * @see prepare() + */ + public function __toString() + { + return + sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n". + $this->headers."\r\n". + $this->getContent(); + } + + /** + * Clones the current Response instance. + */ + public function __clone() + { + $this->headers = clone $this->headers; + } + + /** + * Prepares the Response before it is sent to the client. + * + * This method tweaks the Response to ensure that it is + * compliant with RFC 2616. Most of the changes are based on + * the Request that is "associated" with this Response. + * + * @return $this + */ + public function prepare(Request $request) + { + $headers = $this->headers; + + if ($this->isInformational() || $this->isEmpty()) { + $this->setContent(null); + $headers->remove('Content-Type'); + $headers->remove('Content-Length'); + // prevent PHP from sending the Content-Type header based on default_mimetype + ini_set('default_mimetype', ''); + } else { + // Content-type based on the Request + if (!$headers->has('Content-Type')) { + $format = $request->getRequestFormat(null); + if (null !== $format && $mimeType = $request->getMimeType($format)) { + $headers->set('Content-Type', $mimeType); + } + } + + // Fix Content-Type + $charset = $this->charset ?: 'UTF-8'; + if (!$headers->has('Content-Type')) { + $headers->set('Content-Type', 'text/html; charset='.$charset); + } elseif (0 === stripos($headers->get('Content-Type') ?? '', 'text/') && false === stripos($headers->get('Content-Type') ?? '', 'charset')) { + // add the charset + $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset); + } + + // Fix Content-Length + if ($headers->has('Transfer-Encoding')) { + $headers->remove('Content-Length'); + } + + if ($request->isMethod('HEAD')) { + // cf. RFC2616 14.13 + $length = $headers->get('Content-Length'); + $this->setContent(null); + if ($length) { + $headers->set('Content-Length', $length); + } + } + } + + // Fix protocol + if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) { + $this->setProtocolVersion('1.1'); + } + + // Check if we need to send extra expire info headers + if ('1.0' == $this->getProtocolVersion() && str_contains($headers->get('Cache-Control', ''), 'no-cache')) { + $headers->set('pragma', 'no-cache'); + $headers->set('expires', -1); + } + + $this->ensureIEOverSSLCompatibility($request); + + if ($request->isSecure()) { + foreach ($headers->getCookies() as $cookie) { + $cookie->setSecureDefault(true); + } + } + + return $this; + } + + /** + * Sends HTTP headers. + * + * @return $this + */ + public function sendHeaders() + { + // headers have already been sent by the developer + if (headers_sent()) { + return $this; + } + + // headers + foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) { + $replace = 0 === strcasecmp($name, 'Content-Type'); + foreach ($values as $value) { + header($name.': '.$value, $replace, $this->statusCode); + } + } + + // cookies + foreach ($this->headers->getCookies() as $cookie) { + header('Set-Cookie: '.$cookie, false, $this->statusCode); + } + + // status + header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode); + + return $this; + } + + /** + * Sends content for the current web response. + * + * @return $this + */ + public function sendContent() + { + echo $this->content; + + return $this; + } + + /** + * Sends HTTP headers and content. + * + * @return $this + */ + public function send() + { + $this->sendHeaders(); + $this->sendContent(); + + if (\function_exists('fastcgi_finish_request')) { + fastcgi_finish_request(); + } elseif (\function_exists('litespeed_finish_request')) { + litespeed_finish_request(); + } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { + static::closeOutputBuffers(0, true); + flush(); + } + + return $this; + } + + /** + * Sets the response content. + * + * @return $this + */ + public function setContent(?string $content) + { + $this->content = $content ?? ''; + + return $this; + } + + /** + * Gets the current response content. + * + * @return string|false + */ + public function getContent() + { + return $this->content; + } + + /** + * Sets the HTTP protocol version (1.0 or 1.1). + * + * @return $this + * + * @final + */ + public function setProtocolVersion(string $version): object + { + $this->version = $version; + + return $this; + } + + /** + * Gets the HTTP protocol version. + * + * @final + */ + public function getProtocolVersion(): string + { + return $this->version; + } + + /** + * Sets the response status code. + * + * If the status text is null it will be automatically populated for the known + * status codes and left empty otherwise. + * + * @return $this + * + * @throws \InvalidArgumentException When the HTTP status code is not valid + * + * @final + */ + public function setStatusCode(int $code, ?string $text = null): object + { + $this->statusCode = $code; + if ($this->isInvalid()) { + throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code)); + } + + if (null === $text) { + $this->statusText = self::$statusTexts[$code] ?? 'unknown status'; + + return $this; + } + + if (false === $text) { + $this->statusText = ''; + + return $this; + } + + $this->statusText = $text; + + return $this; + } + + /** + * Retrieves the status code for the current web response. + * + * @final + */ + public function getStatusCode(): int + { + return $this->statusCode; + } + + /** + * Sets the response charset. + * + * @return $this + * + * @final + */ + public function setCharset(string $charset): object + { + $this->charset = $charset; + + return $this; + } + + /** + * Retrieves the response charset. + * + * @final + */ + public function getCharset(): ?string + { + return $this->charset; + } + + /** + * Returns true if the response may safely be kept in a shared (surrogate) cache. + * + * Responses marked "private" with an explicit Cache-Control directive are + * considered uncacheable. + * + * Responses with neither a freshness lifetime (Expires, max-age) nor cache + * validator (Last-Modified, ETag) are considered uncacheable because there is + * no way to tell when or how to remove them from the cache. + * + * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation, + * for example "status codes that are defined as cacheable by default [...] + * can be reused by a cache with heuristic expiration unless otherwise indicated" + * (https://tools.ietf.org/html/rfc7231#section-6.1) + * + * @final + */ + public function isCacheable(): bool + { + if (!\in_array($this->statusCode, [200, 203, 300, 301, 302, 404, 410])) { + return false; + } + + if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) { + return false; + } + + return $this->isValidateable() || $this->isFresh(); + } + + /** + * Returns true if the response is "fresh". + * + * Fresh responses may be served from cache without any interaction with the + * origin. A response is considered fresh when it includes a Cache-Control/max-age + * indicator or Expires header and the calculated age is less than the freshness lifetime. + * + * @final + */ + public function isFresh(): bool + { + return $this->getTtl() > 0; + } + + /** + * Returns true if the response includes headers that can be used to validate + * the response with the origin server using a conditional GET request. + * + * @final + */ + public function isValidateable(): bool + { + return $this->headers->has('Last-Modified') || $this->headers->has('ETag'); + } + + /** + * Marks the response as "private". + * + * It makes the response ineligible for serving other clients. + * + * @return $this + * + * @final + */ + public function setPrivate(): object + { + $this->headers->removeCacheControlDirective('public'); + $this->headers->addCacheControlDirective('private'); + + return $this; + } + + /** + * Marks the response as "public". + * + * It makes the response eligible for serving other clients. + * + * @return $this + * + * @final + */ + public function setPublic(): object + { + $this->headers->addCacheControlDirective('public'); + $this->headers->removeCacheControlDirective('private'); + + return $this; + } + + /** + * Marks the response as "immutable". + * + * @return $this + * + * @final + */ + public function setImmutable(bool $immutable = true): object + { + if ($immutable) { + $this->headers->addCacheControlDirective('immutable'); + } else { + $this->headers->removeCacheControlDirective('immutable'); + } + + return $this; + } + + /** + * Returns true if the response is marked as "immutable". + * + * @final + */ + public function isImmutable(): bool + { + return $this->headers->hasCacheControlDirective('immutable'); + } + + /** + * Returns true if the response must be revalidated by shared caches once it has become stale. + * + * This method indicates that the response must not be served stale by a + * cache in any circumstance without first revalidating with the origin. + * When present, the TTL of the response should not be overridden to be + * greater than the value provided by the origin. + * + * @final + */ + public function mustRevalidate(): bool + { + return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate'); + } + + /** + * Returns the Date header as a DateTime instance. + * + * @throws \RuntimeException When the header is not parseable + * + * @final + */ + public function getDate(): ?\DateTimeInterface + { + return $this->headers->getDate('Date'); + } + + /** + * Sets the Date header. + * + * @return $this + * + * @final + */ + public function setDate(\DateTimeInterface $date): object + { + if ($date instanceof \DateTime) { + $date = \DateTimeImmutable::createFromMutable($date); + } + + $date = $date->setTimezone(new \DateTimeZone('UTC')); + $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT'); + + return $this; + } + + /** + * Returns the age of the response in seconds. + * + * @final + */ + public function getAge(): int + { + if (null !== $age = $this->headers->get('Age')) { + return (int) $age; + } + + return max(time() - (int) $this->getDate()->format('U'), 0); + } + + /** + * Marks the response stale by setting the Age header to be equal to the maximum age of the response. + * + * @return $this + */ + public function expire() + { + if ($this->isFresh()) { + $this->headers->set('Age', $this->getMaxAge()); + $this->headers->remove('Expires'); + } + + return $this; + } + + /** + * Returns the value of the Expires header as a DateTime instance. + * + * @final + */ + public function getExpires(): ?\DateTimeInterface + { + try { + return $this->headers->getDate('Expires'); + } catch (\RuntimeException $e) { + // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past + return \DateTime::createFromFormat('U', time() - 172800); + } + } + + /** + * Sets the Expires HTTP header with a DateTime instance. + * + * Passing null as value will remove the header. + * + * @return $this + * + * @final + */ + public function setExpires(?\DateTimeInterface $date = null): object + { + if (null === $date) { + $this->headers->remove('Expires'); + + return $this; + } + + if ($date instanceof \DateTime) { + $date = \DateTimeImmutable::createFromMutable($date); + } + + $date = $date->setTimezone(new \DateTimeZone('UTC')); + $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT'); + + return $this; + } + + /** + * Returns the number of seconds after the time specified in the response's Date + * header when the response should no longer be considered fresh. + * + * First, it checks for a s-maxage directive, then a max-age directive, and then it falls + * back on an expires header. It returns null when no maximum age can be established. + * + * @final + */ + public function getMaxAge(): ?int + { + if ($this->headers->hasCacheControlDirective('s-maxage')) { + return (int) $this->headers->getCacheControlDirective('s-maxage'); + } + + if ($this->headers->hasCacheControlDirective('max-age')) { + return (int) $this->headers->getCacheControlDirective('max-age'); + } + + if (null !== $expires = $this->getExpires()) { + $maxAge = (int) $expires->format('U') - (int) $this->getDate()->format('U'); + + return max($maxAge, 0); + } + + return null; + } + + /** + * Sets the number of seconds after which the response should no longer be considered fresh. + * + * This methods sets the Cache-Control max-age directive. + * + * @return $this + * + * @final + */ + public function setMaxAge(int $value): object + { + $this->headers->addCacheControlDirective('max-age', $value); + + return $this; + } + + /** + * Sets the number of seconds after which the response should no longer be considered fresh by shared caches. + * + * This methods sets the Cache-Control s-maxage directive. + * + * @return $this + * + * @final + */ + public function setSharedMaxAge(int $value): object + { + $this->setPublic(); + $this->headers->addCacheControlDirective('s-maxage', $value); + + return $this; + } + + /** + * Returns the response's time-to-live in seconds. + * + * It returns null when no freshness information is present in the response. + * + * When the response's TTL is 0, the response may not be served from cache without first + * revalidating with the origin. + * + * @final + */ + public function getTtl(): ?int + { + $maxAge = $this->getMaxAge(); + + return null !== $maxAge ? max($maxAge - $this->getAge(), 0) : null; + } + + /** + * Sets the response's time-to-live for shared caches in seconds. + * + * This method adjusts the Cache-Control/s-maxage directive. + * + * @return $this + * + * @final + */ + public function setTtl(int $seconds): object + { + $this->setSharedMaxAge($this->getAge() + $seconds); + + return $this; + } + + /** + * Sets the response's time-to-live for private/client caches in seconds. + * + * This method adjusts the Cache-Control/max-age directive. + * + * @return $this + * + * @final + */ + public function setClientTtl(int $seconds): object + { + $this->setMaxAge($this->getAge() + $seconds); + + return $this; + } + + /** + * Returns the Last-Modified HTTP header as a DateTime instance. + * + * @throws \RuntimeException When the HTTP header is not parseable + * + * @final + */ + public function getLastModified(): ?\DateTimeInterface + { + return $this->headers->getDate('Last-Modified'); + } + + /** + * Sets the Last-Modified HTTP header with a DateTime instance. + * + * Passing null as value will remove the header. + * + * @return $this + * + * @final + */ + public function setLastModified(?\DateTimeInterface $date = null): object + { + if (null === $date) { + $this->headers->remove('Last-Modified'); + + return $this; + } + + if ($date instanceof \DateTime) { + $date = \DateTimeImmutable::createFromMutable($date); + } + + $date = $date->setTimezone(new \DateTimeZone('UTC')); + $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT'); + + return $this; + } + + /** + * Returns the literal value of the ETag HTTP header. + * + * @final + */ + public function getEtag(): ?string + { + return $this->headers->get('ETag'); + } + + /** + * Sets the ETag value. + * + * @param string|null $etag The ETag unique identifier or null to remove the header + * @param bool $weak Whether you want a weak ETag or not + * + * @return $this + * + * @final + */ + public function setEtag(?string $etag = null, bool $weak = false): object + { + if (null === $etag) { + $this->headers->remove('Etag'); + } else { + if (!str_starts_with($etag, '"')) { + $etag = '"'.$etag.'"'; + } + + $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag); + } + + return $this; + } + + /** + * Sets the response's cache headers (validation and/or expiration). + * + * Available options are: must_revalidate, no_cache, no_store, no_transform, public, private, proxy_revalidate, max_age, s_maxage, immutable, last_modified and etag. + * + * @return $this + * + * @throws \InvalidArgumentException + * + * @final + */ + public function setCache(array $options): object + { + if ($diff = array_diff(array_keys($options), array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) { + throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff))); + } + + if (isset($options['etag'])) { + $this->setEtag($options['etag']); + } + + if (isset($options['last_modified'])) { + $this->setLastModified($options['last_modified']); + } + + if (isset($options['max_age'])) { + $this->setMaxAge($options['max_age']); + } + + if (isset($options['s_maxage'])) { + $this->setSharedMaxAge($options['s_maxage']); + } + + foreach (self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES as $directive => $hasValue) { + if (!$hasValue && isset($options[$directive])) { + if ($options[$directive]) { + $this->headers->addCacheControlDirective(str_replace('_', '-', $directive)); + } else { + $this->headers->removeCacheControlDirective(str_replace('_', '-', $directive)); + } + } + } + + if (isset($options['public'])) { + if ($options['public']) { + $this->setPublic(); + } else { + $this->setPrivate(); + } + } + + if (isset($options['private'])) { + if ($options['private']) { + $this->setPrivate(); + } else { + $this->setPublic(); + } + } + + return $this; + } + + /** + * Modifies the response so that it conforms to the rules defined for a 304 status code. + * + * This sets the status, removes the body, and discards any headers + * that MUST NOT be included in 304 responses. + * + * @return $this + * + * @see https://tools.ietf.org/html/rfc2616#section-10.3.5 + * + * @final + */ + public function setNotModified(): object + { + $this->setStatusCode(304); + $this->setContent(null); + + // remove headers that MUST NOT be included with 304 Not Modified responses + foreach (['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'] as $header) { + $this->headers->remove($header); + } + + return $this; + } + + /** + * Returns true if the response includes a Vary header. + * + * @final + */ + public function hasVary(): bool + { + return null !== $this->headers->get('Vary'); + } + + /** + * Returns an array of header names given in the Vary header. + * + * @final + */ + public function getVary(): array + { + if (!$vary = $this->headers->all('Vary')) { + return []; + } + + $ret = []; + foreach ($vary as $item) { + $ret[] = preg_split('/[\s,]+/', $item); + } + + return array_merge([], ...$ret); + } + + /** + * Sets the Vary header. + * + * @param string|array $headers + * @param bool $replace Whether to replace the actual value or not (true by default) + * + * @return $this + * + * @final + */ + public function setVary($headers, bool $replace = true): object + { + $this->headers->set('Vary', $headers, $replace); + + return $this; + } + + /** + * Determines if the Response validators (ETag, Last-Modified) match + * a conditional value specified in the Request. + * + * If the Response is not modified, it sets the status code to 304 and + * removes the actual content by calling the setNotModified() method. + * + * @final + */ + public function isNotModified(Request $request): bool + { + if (!$request->isMethodCacheable()) { + return false; + } + + $notModified = false; + $lastModified = $this->headers->get('Last-Modified'); + $modifiedSince = $request->headers->get('If-Modified-Since'); + + if (($ifNoneMatchEtags = $request->getETags()) && (null !== $etag = $this->getEtag())) { + if (0 == strncmp($etag, 'W/', 2)) { + $etag = substr($etag, 2); + } + + // Use weak comparison as per https://tools.ietf.org/html/rfc7232#section-3.2. + foreach ($ifNoneMatchEtags as $ifNoneMatchEtag) { + if (0 == strncmp($ifNoneMatchEtag, 'W/', 2)) { + $ifNoneMatchEtag = substr($ifNoneMatchEtag, 2); + } + + if ($ifNoneMatchEtag === $etag || '*' === $ifNoneMatchEtag) { + $notModified = true; + break; + } + } + } + // Only do If-Modified-Since date comparison when If-None-Match is not present as per https://tools.ietf.org/html/rfc7232#section-3.3. + elseif ($modifiedSince && $lastModified) { + $notModified = strtotime($modifiedSince) >= strtotime($lastModified); + } + + if ($notModified) { + $this->setNotModified(); + } + + return $notModified; + } + + /** + * Is response invalid? + * + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + * + * @final + */ + public function isInvalid(): bool + { + return $this->statusCode < 100 || $this->statusCode >= 600; + } + + /** + * Is response informative? + * + * @final + */ + public function isInformational(): bool + { + return $this->statusCode >= 100 && $this->statusCode < 200; + } + + /** + * Is response successful? + * + * @final + */ + public function isSuccessful(): bool + { + return $this->statusCode >= 200 && $this->statusCode < 300; + } + + /** + * Is the response a redirect? + * + * @final + */ + public function isRedirection(): bool + { + return $this->statusCode >= 300 && $this->statusCode < 400; + } + + /** + * Is there a client error? + * + * @final + */ + public function isClientError(): bool + { + return $this->statusCode >= 400 && $this->statusCode < 500; + } + + /** + * Was there a server side error? + * + * @final + */ + public function isServerError(): bool + { + return $this->statusCode >= 500 && $this->statusCode < 600; + } + + /** + * Is the response OK? + * + * @final + */ + public function isOk(): bool + { + return 200 === $this->statusCode; + } + + /** + * Is the response forbidden? + * + * @final + */ + public function isForbidden(): bool + { + return 403 === $this->statusCode; + } + + /** + * Is the response a not found error? + * + * @final + */ + public function isNotFound(): bool + { + return 404 === $this->statusCode; + } + + /** + * Is the response a redirect of some form? + * + * @final + */ + public function isRedirect(?string $location = null): bool + { + return \in_array($this->statusCode, [201, 301, 302, 303, 307, 308]) && (null === $location ?: $location == $this->headers->get('Location')); + } + + /** + * Is the response empty? + * + * @final + */ + public function isEmpty(): bool + { + return \in_array($this->statusCode, [204, 304]); + } + + /** + * Cleans or flushes output buffers up to target level. + * + * Resulting level can be greater than target level if a non-removable buffer has been encountered. + * + * @final + */ + public static function closeOutputBuffers(int $targetLevel, bool $flush): void + { + $status = ob_get_status(true); + $level = \count($status); + $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE); + + while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) { + if ($flush) { + ob_end_flush(); + } else { + ob_end_clean(); + } + } + } + + /** + * Marks a response as safe according to RFC8674. + * + * @see https://tools.ietf.org/html/rfc8674 + */ + public function setContentSafe(bool $safe = true): void + { + if ($safe) { + $this->headers->set('Preference-Applied', 'safe'); + } elseif ('safe' === $this->headers->get('Preference-Applied')) { + $this->headers->remove('Preference-Applied'); + } + + $this->setVary('Prefer', false); + } + + /** + * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9. + * + * @see http://support.microsoft.com/kb/323308 + * + * @final + */ + protected function ensureIEOverSSLCompatibility(Request $request): void + { + if (false !== stripos($this->headers->get('Content-Disposition') ?? '', 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT') ?? '', $match) && true === $request->isSecure()) { + if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) { + $this->headers->remove('Cache-Control'); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/ResponseHeaderBag.php b/php/libraries/composer/vendor/symfony/http-foundation/ResponseHeaderBag.php new file mode 100644 index 0000000..d4c4f39 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/ResponseHeaderBag.php @@ -0,0 +1,291 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * ResponseHeaderBag is a container for Response HTTP headers. + * + * @author Fabien Potencier + */ +class ResponseHeaderBag extends HeaderBag +{ + public const COOKIES_FLAT = 'flat'; + public const COOKIES_ARRAY = 'array'; + + public const DISPOSITION_ATTACHMENT = 'attachment'; + public const DISPOSITION_INLINE = 'inline'; + + protected $computedCacheControl = []; + protected $cookies = []; + protected $headerNames = []; + + public function __construct(array $headers = []) + { + parent::__construct($headers); + + if (!isset($this->headers['cache-control'])) { + $this->set('Cache-Control', ''); + } + + /* RFC2616 - 14.18 says all Responses need to have a Date */ + if (!isset($this->headers['date'])) { + $this->initDate(); + } + } + + /** + * Returns the headers, with original capitalizations. + * + * @return array + */ + public function allPreserveCase() + { + $headers = []; + foreach ($this->all() as $name => $value) { + $headers[$this->headerNames[$name] ?? $name] = $value; + } + + return $headers; + } + + public function allPreserveCaseWithoutCookies() + { + $headers = $this->allPreserveCase(); + if (isset($this->headerNames['set-cookie'])) { + unset($headers[$this->headerNames['set-cookie']]); + } + + return $headers; + } + + /** + * {@inheritdoc} + */ + public function replace(array $headers = []) + { + $this->headerNames = []; + + parent::replace($headers); + + if (!isset($this->headers['cache-control'])) { + $this->set('Cache-Control', ''); + } + + if (!isset($this->headers['date'])) { + $this->initDate(); + } + } + + /** + * {@inheritdoc} + */ + public function all(?string $key = null) + { + $headers = parent::all(); + + if (null !== $key) { + $key = strtr($key, self::UPPER, self::LOWER); + + return 'set-cookie' !== $key ? $headers[$key] ?? [] : array_map('strval', $this->getCookies()); + } + + foreach ($this->getCookies() as $cookie) { + $headers['set-cookie'][] = (string) $cookie; + } + + return $headers; + } + + /** + * {@inheritdoc} + */ + public function set(string $key, $values, bool $replace = true) + { + $uniqueKey = strtr($key, self::UPPER, self::LOWER); + + if ('set-cookie' === $uniqueKey) { + if ($replace) { + $this->cookies = []; + } + foreach ((array) $values as $cookie) { + $this->setCookie(Cookie::fromString($cookie)); + } + $this->headerNames[$uniqueKey] = $key; + + return; + } + + $this->headerNames[$uniqueKey] = $key; + + parent::set($key, $values, $replace); + + // ensure the cache-control header has sensible defaults + if (\in_array($uniqueKey, ['cache-control', 'etag', 'last-modified', 'expires'], true) && '' !== $computed = $this->computeCacheControlValue()) { + $this->headers['cache-control'] = [$computed]; + $this->headerNames['cache-control'] = 'Cache-Control'; + $this->computedCacheControl = $this->parseCacheControl($computed); + } + } + + /** + * {@inheritdoc} + */ + public function remove(string $key) + { + $uniqueKey = strtr($key, self::UPPER, self::LOWER); + unset($this->headerNames[$uniqueKey]); + + if ('set-cookie' === $uniqueKey) { + $this->cookies = []; + + return; + } + + parent::remove($key); + + if ('cache-control' === $uniqueKey) { + $this->computedCacheControl = []; + } + + if ('date' === $uniqueKey) { + $this->initDate(); + } + } + + /** + * {@inheritdoc} + */ + public function hasCacheControlDirective(string $key) + { + return \array_key_exists($key, $this->computedCacheControl); + } + + /** + * {@inheritdoc} + */ + public function getCacheControlDirective(string $key) + { + return $this->computedCacheControl[$key] ?? null; + } + + public function setCookie(Cookie $cookie) + { + $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie; + $this->headerNames['set-cookie'] = 'Set-Cookie'; + } + + /** + * Removes a cookie from the array, but does not unset it in the browser. + */ + public function removeCookie(string $name, ?string $path = '/', ?string $domain = null) + { + if (null === $path) { + $path = '/'; + } + + unset($this->cookies[$domain][$path][$name]); + + if (empty($this->cookies[$domain][$path])) { + unset($this->cookies[$domain][$path]); + + if (empty($this->cookies[$domain])) { + unset($this->cookies[$domain]); + } + } + + if (empty($this->cookies)) { + unset($this->headerNames['set-cookie']); + } + } + + /** + * Returns an array with all cookies. + * + * @return Cookie[] + * + * @throws \InvalidArgumentException When the $format is invalid + */ + public function getCookies(string $format = self::COOKIES_FLAT) + { + if (!\in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) { + throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', [self::COOKIES_FLAT, self::COOKIES_ARRAY]))); + } + + if (self::COOKIES_ARRAY === $format) { + return $this->cookies; + } + + $flattenedCookies = []; + foreach ($this->cookies as $path) { + foreach ($path as $cookies) { + foreach ($cookies as $cookie) { + $flattenedCookies[] = $cookie; + } + } + } + + return $flattenedCookies; + } + + /** + * Clears a cookie in the browser. + */ + public function clearCookie(string $name, ?string $path = '/', ?string $domain = null, bool $secure = false, bool $httpOnly = true, ?string $sameSite = null) + { + $this->setCookie(new Cookie($name, null, 1, $path, $domain, $secure, $httpOnly, false, $sameSite)); + } + + /** + * @see HeaderUtils::makeDisposition() + */ + public function makeDisposition(string $disposition, string $filename, string $filenameFallback = '') + { + return HeaderUtils::makeDisposition($disposition, $filename, $filenameFallback); + } + + /** + * Returns the calculated value of the cache-control header. + * + * This considers several other headers and calculates or modifies the + * cache-control header to a sensible, conservative value. + * + * @return string + */ + protected function computeCacheControlValue() + { + if (!$this->cacheControl) { + if ($this->has('Last-Modified') || $this->has('Expires')) { + return 'private, must-revalidate'; // allows for heuristic expiration (RFC 7234 Section 4.2.2) in the case of "Last-Modified" + } + + // conservative by default + return 'no-cache, private'; + } + + $header = $this->getCacheControlHeader(); + if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) { + return $header; + } + + // public if s-maxage is defined, private otherwise + if (!isset($this->cacheControl['s-maxage'])) { + return $header.', private'; + } + + return $header; + } + + private function initDate(): void + { + $this->set('Date', gmdate('D, d M Y H:i:s').' GMT'); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/ServerBag.php b/php/libraries/composer/vendor/symfony/http-foundation/ServerBag.php new file mode 100644 index 0000000..831caa6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/ServerBag.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * ServerBag is a container for HTTP headers from the $_SERVER variable. + * + * @author Fabien Potencier + * @author Bulat Shakirzyanov + * @author Robert Kiss + */ +class ServerBag extends ParameterBag +{ + /** + * Gets the HTTP headers. + * + * @return array + */ + public function getHeaders() + { + $headers = []; + foreach ($this->parameters as $key => $value) { + if (str_starts_with($key, 'HTTP_')) { + $headers[substr($key, 5)] = $value; + } elseif (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true) && '' !== $value) { + $headers[$key] = $value; + } + } + + if (isset($this->parameters['PHP_AUTH_USER'])) { + $headers['PHP_AUTH_USER'] = $this->parameters['PHP_AUTH_USER']; + $headers['PHP_AUTH_PW'] = $this->parameters['PHP_AUTH_PW'] ?? ''; + } else { + /* + * php-cgi under Apache does not pass HTTP Basic user/pass to PHP by default + * For this workaround to work, add these lines to your .htaccess file: + * RewriteCond %{HTTP:Authorization} .+ + * RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0] + * + * A sample .htaccess file: + * RewriteEngine On + * RewriteCond %{HTTP:Authorization} .+ + * RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0] + * RewriteCond %{REQUEST_FILENAME} !-f + * RewriteRule ^(.*)$ index.php [QSA,L] + */ + + $authorizationHeader = null; + if (isset($this->parameters['HTTP_AUTHORIZATION'])) { + $authorizationHeader = $this->parameters['HTTP_AUTHORIZATION']; + } elseif (isset($this->parameters['REDIRECT_HTTP_AUTHORIZATION'])) { + $authorizationHeader = $this->parameters['REDIRECT_HTTP_AUTHORIZATION']; + } + + if (null !== $authorizationHeader) { + if (0 === stripos($authorizationHeader, 'basic ')) { + // Decode AUTHORIZATION header into PHP_AUTH_USER and PHP_AUTH_PW when authorization header is basic + $exploded = explode(':', base64_decode(substr($authorizationHeader, 6)), 2); + if (2 == \count($exploded)) { + [$headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']] = $exploded; + } + } elseif (empty($this->parameters['PHP_AUTH_DIGEST']) && (0 === stripos($authorizationHeader, 'digest '))) { + // In some circumstances PHP_AUTH_DIGEST needs to be set + $headers['PHP_AUTH_DIGEST'] = $authorizationHeader; + $this->parameters['PHP_AUTH_DIGEST'] = $authorizationHeader; + } elseif (0 === stripos($authorizationHeader, 'bearer ')) { + /* + * XXX: Since there is no PHP_AUTH_BEARER in PHP predefined variables, + * I'll just set $headers['AUTHORIZATION'] here. + * https://php.net/reserved.variables.server + */ + $headers['AUTHORIZATION'] = $authorizationHeader; + } + } + } + + if (isset($headers['AUTHORIZATION'])) { + return $headers; + } + + // PHP_AUTH_USER/PHP_AUTH_PW + if (isset($headers['PHP_AUTH_USER'])) { + $headers['AUTHORIZATION'] = 'Basic '.base64_encode($headers['PHP_AUTH_USER'].':'.($headers['PHP_AUTH_PW'] ?? '')); + } elseif (isset($headers['PHP_AUTH_DIGEST'])) { + $headers['AUTHORIZATION'] = $headers['PHP_AUTH_DIGEST']; + } + + return $headers; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/AttributeBag.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/AttributeBag.php new file mode 100644 index 0000000..f4f051c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/AttributeBag.php @@ -0,0 +1,152 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Attribute; + +/** + * This class relates to session attribute storage. + * + * @implements \IteratorAggregate + */ +class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Countable +{ + private $name = 'attributes'; + private $storageKey; + + protected $attributes = []; + + /** + * @param string $storageKey The key used to store attributes in the session + */ + public function __construct(string $storageKey = '_sf2_attributes') + { + $this->storageKey = $storageKey; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function initialize(array &$attributes) + { + $this->attributes = &$attributes; + } + + /** + * {@inheritdoc} + */ + public function getStorageKey() + { + return $this->storageKey; + } + + /** + * {@inheritdoc} + */ + public function has(string $name) + { + return \array_key_exists($name, $this->attributes); + } + + /** + * {@inheritdoc} + */ + public function get(string $name, $default = null) + { + return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; + } + + /** + * {@inheritdoc} + */ + public function set(string $name, $value) + { + $this->attributes[$name] = $value; + } + + /** + * {@inheritdoc} + */ + public function all() + { + return $this->attributes; + } + + /** + * {@inheritdoc} + */ + public function replace(array $attributes) + { + $this->attributes = []; + foreach ($attributes as $key => $value) { + $this->set($key, $value); + } + } + + /** + * {@inheritdoc} + */ + public function remove(string $name) + { + $retval = null; + if (\array_key_exists($name, $this->attributes)) { + $retval = $this->attributes[$name]; + unset($this->attributes[$name]); + } + + return $retval; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + $return = $this->attributes; + $this->attributes = []; + + return $return; + } + + /** + * Returns an iterator for attributes. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new \ArrayIterator($this->attributes); + } + + /** + * Returns the number of attributes. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return \count($this->attributes); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/AttributeBagInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/AttributeBagInterface.php new file mode 100644 index 0000000..cb50696 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/AttributeBagInterface.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Attribute; + +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; + +/** + * Attributes store. + * + * @author Drak + */ +interface AttributeBagInterface extends SessionBagInterface +{ + /** + * Checks if an attribute is defined. + * + * @return bool + */ + public function has(string $name); + + /** + * Returns an attribute. + * + * @param mixed $default The default value if not found + * + * @return mixed + */ + public function get(string $name, $default = null); + + /** + * Sets an attribute. + * + * @param mixed $value + */ + public function set(string $name, $value); + + /** + * Returns attributes. + * + * @return array + */ + public function all(); + + public function replace(array $attributes); + + /** + * Removes an attribute. + * + * @return mixed The removed value or null when it does not exist + */ + public function remove(string $name); +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php new file mode 100644 index 0000000..864b35f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php @@ -0,0 +1,161 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Attribute; + +trigger_deprecation('symfony/http-foundation', '5.3', 'The "%s" class is deprecated.', NamespacedAttributeBag::class); + +/** + * This class provides structured storage of session attributes using + * a name spacing character in the key. + * + * @author Drak + * + * @deprecated since Symfony 5.3 + */ +class NamespacedAttributeBag extends AttributeBag +{ + private $namespaceCharacter; + + /** + * @param string $storageKey Session storage key + * @param string $namespaceCharacter Namespace character to use in keys + */ + public function __construct(string $storageKey = '_sf2_attributes', string $namespaceCharacter = '/') + { + $this->namespaceCharacter = $namespaceCharacter; + parent::__construct($storageKey); + } + + /** + * {@inheritdoc} + */ + public function has(string $name) + { + // reference mismatch: if fixed, re-introduced in array_key_exists; keep as it is + $attributes = $this->resolveAttributePath($name); + $name = $this->resolveKey($name); + + if (null === $attributes) { + return false; + } + + return \array_key_exists($name, $attributes); + } + + /** + * {@inheritdoc} + */ + public function get(string $name, $default = null) + { + // reference mismatch: if fixed, re-introduced in array_key_exists; keep as it is + $attributes = $this->resolveAttributePath($name); + $name = $this->resolveKey($name); + + if (null === $attributes) { + return $default; + } + + return \array_key_exists($name, $attributes) ? $attributes[$name] : $default; + } + + /** + * {@inheritdoc} + */ + public function set(string $name, $value) + { + $attributes = &$this->resolveAttributePath($name, true); + $name = $this->resolveKey($name); + $attributes[$name] = $value; + } + + /** + * {@inheritdoc} + */ + public function remove(string $name) + { + $retval = null; + $attributes = &$this->resolveAttributePath($name); + $name = $this->resolveKey($name); + if (null !== $attributes && \array_key_exists($name, $attributes)) { + $retval = $attributes[$name]; + unset($attributes[$name]); + } + + return $retval; + } + + /** + * Resolves a path in attributes property and returns it as a reference. + * + * This method allows structured namespacing of session attributes. + * + * @param string $name Key name + * @param bool $writeContext Write context, default false + * + * @return array|null + */ + protected function &resolveAttributePath(string $name, bool $writeContext = false) + { + $array = &$this->attributes; + $name = (str_starts_with($name, $this->namespaceCharacter)) ? substr($name, 1) : $name; + + // Check if there is anything to do, else return + if (!$name) { + return $array; + } + + $parts = explode($this->namespaceCharacter, $name); + if (\count($parts) < 2) { + if (!$writeContext) { + return $array; + } + + $array[$parts[0]] = []; + + return $array; + } + + unset($parts[\count($parts) - 1]); + + foreach ($parts as $part) { + if (null !== $array && !\array_key_exists($part, $array)) { + if (!$writeContext) { + $null = null; + + return $null; + } + + $array[$part] = []; + } + + $array = &$array[$part]; + } + + return $array; + } + + /** + * Resolves the key from the name. + * + * This is the last part in a dot separated string. + * + * @return string + */ + protected function resolveKey(string $name) + { + if (false !== $pos = strrpos($name, $this->namespaceCharacter)) { + $name = substr($name, $pos + 1); + } + + return $name; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/AutoExpireFlashBag.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/AutoExpireFlashBag.php new file mode 100644 index 0000000..8aab3a1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/AutoExpireFlashBag.php @@ -0,0 +1,161 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Flash; + +/** + * AutoExpireFlashBag flash message container. + * + * @author Drak + */ +class AutoExpireFlashBag implements FlashBagInterface +{ + private $name = 'flashes'; + private $flashes = ['display' => [], 'new' => []]; + private $storageKey; + + /** + * @param string $storageKey The key used to store flashes in the session + */ + public function __construct(string $storageKey = '_symfony_flashes') + { + $this->storageKey = $storageKey; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function initialize(array &$flashes) + { + $this->flashes = &$flashes; + + // The logic: messages from the last request will be stored in new, so we move them to previous + // This request we will show what is in 'display'. What is placed into 'new' this time round will + // be moved to display next time round. + $this->flashes['display'] = \array_key_exists('new', $this->flashes) ? $this->flashes['new'] : []; + $this->flashes['new'] = []; + } + + /** + * {@inheritdoc} + */ + public function add(string $type, $message) + { + $this->flashes['new'][$type][] = $message; + } + + /** + * {@inheritdoc} + */ + public function peek(string $type, array $default = []) + { + return $this->has($type) ? $this->flashes['display'][$type] : $default; + } + + /** + * {@inheritdoc} + */ + public function peekAll() + { + return \array_key_exists('display', $this->flashes) ? $this->flashes['display'] : []; + } + + /** + * {@inheritdoc} + */ + public function get(string $type, array $default = []) + { + $return = $default; + + if (!$this->has($type)) { + return $return; + } + + if (isset($this->flashes['display'][$type])) { + $return = $this->flashes['display'][$type]; + unset($this->flashes['display'][$type]); + } + + return $return; + } + + /** + * {@inheritdoc} + */ + public function all() + { + $return = $this->flashes['display']; + $this->flashes['display'] = []; + + return $return; + } + + /** + * {@inheritdoc} + */ + public function setAll(array $messages) + { + $this->flashes['new'] = $messages; + } + + /** + * {@inheritdoc} + */ + public function set(string $type, $messages) + { + $this->flashes['new'][$type] = (array) $messages; + } + + /** + * {@inheritdoc} + */ + public function has(string $type) + { + return \array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type]; + } + + /** + * {@inheritdoc} + */ + public function keys() + { + return array_keys($this->flashes['display']); + } + + /** + * {@inheritdoc} + */ + public function getStorageKey() + { + return $this->storageKey; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + return $this->all(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/FlashBag.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/FlashBag.php new file mode 100644 index 0000000..88df750 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/FlashBag.php @@ -0,0 +1,152 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Flash; + +/** + * FlashBag flash message container. + * + * @author Drak + */ +class FlashBag implements FlashBagInterface +{ + private $name = 'flashes'; + private $flashes = []; + private $storageKey; + + /** + * @param string $storageKey The key used to store flashes in the session + */ + public function __construct(string $storageKey = '_symfony_flashes') + { + $this->storageKey = $storageKey; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function initialize(array &$flashes) + { + $this->flashes = &$flashes; + } + + /** + * {@inheritdoc} + */ + public function add(string $type, $message) + { + $this->flashes[$type][] = $message; + } + + /** + * {@inheritdoc} + */ + public function peek(string $type, array $default = []) + { + return $this->has($type) ? $this->flashes[$type] : $default; + } + + /** + * {@inheritdoc} + */ + public function peekAll() + { + return $this->flashes; + } + + /** + * {@inheritdoc} + */ + public function get(string $type, array $default = []) + { + if (!$this->has($type)) { + return $default; + } + + $return = $this->flashes[$type]; + + unset($this->flashes[$type]); + + return $return; + } + + /** + * {@inheritdoc} + */ + public function all() + { + $return = $this->peekAll(); + $this->flashes = []; + + return $return; + } + + /** + * {@inheritdoc} + */ + public function set(string $type, $messages) + { + $this->flashes[$type] = (array) $messages; + } + + /** + * {@inheritdoc} + */ + public function setAll(array $messages) + { + $this->flashes = $messages; + } + + /** + * {@inheritdoc} + */ + public function has(string $type) + { + return \array_key_exists($type, $this->flashes) && $this->flashes[$type]; + } + + /** + * {@inheritdoc} + */ + public function keys() + { + return array_keys($this->flashes); + } + + /** + * {@inheritdoc} + */ + public function getStorageKey() + { + return $this->storageKey; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + return $this->all(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/FlashBagInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/FlashBagInterface.php new file mode 100644 index 0000000..8713e71 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Flash/FlashBagInterface.php @@ -0,0 +1,88 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Flash; + +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; + +/** + * FlashBagInterface. + * + * @author Drak + */ +interface FlashBagInterface extends SessionBagInterface +{ + /** + * Adds a flash message for the given type. + * + * @param mixed $message + */ + public function add(string $type, $message); + + /** + * Registers one or more messages for a given type. + * + * @param string|array $messages + */ + public function set(string $type, $messages); + + /** + * Gets flash messages for a given type. + * + * @param string $type Message category type + * @param array $default Default value if $type does not exist + * + * @return array + */ + public function peek(string $type, array $default = []); + + /** + * Gets all flash messages. + * + * @return array + */ + public function peekAll(); + + /** + * Gets and clears flash from the stack. + * + * @param array $default Default value if $type does not exist + * + * @return array + */ + public function get(string $type, array $default = []); + + /** + * Gets and clears flashes from the stack. + * + * @return array + */ + public function all(); + + /** + * Sets all flash messages. + */ + public function setAll(array $messages); + + /** + * Has flash messages for a given type? + * + * @return bool + */ + public function has(string $type); + + /** + * Returns a list of all defined types. + * + * @return array + */ + public function keys(); +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Session.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Session.php new file mode 100644 index 0000000..917920a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Session.php @@ -0,0 +1,285 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session; + +use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; +use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface; +use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; +use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; +use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; +use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(AttributeBag::class); +class_exists(FlashBag::class); +class_exists(SessionBagProxy::class); + +/** + * @author Fabien Potencier + * @author Drak + * + * @implements \IteratorAggregate + */ +class Session implements SessionInterface, \IteratorAggregate, \Countable +{ + protected $storage; + + private $flashName; + private $attributeName; + private $data = []; + private $usageIndex = 0; + private $usageReporter; + + public function __construct(?SessionStorageInterface $storage = null, ?AttributeBagInterface $attributes = null, ?FlashBagInterface $flashes = null, ?callable $usageReporter = null) + { + $this->storage = $storage ?? new NativeSessionStorage(); + $this->usageReporter = $usageReporter; + + $attributes = $attributes ?? new AttributeBag(); + $this->attributeName = $attributes->getName(); + $this->registerBag($attributes); + + $flashes = $flashes ?? new FlashBag(); + $this->flashName = $flashes->getName(); + $this->registerBag($flashes); + } + + /** + * {@inheritdoc} + */ + public function start() + { + return $this->storage->start(); + } + + /** + * {@inheritdoc} + */ + public function has(string $name) + { + return $this->getAttributeBag()->has($name); + } + + /** + * {@inheritdoc} + */ + public function get(string $name, $default = null) + { + return $this->getAttributeBag()->get($name, $default); + } + + /** + * {@inheritdoc} + */ + public function set(string $name, $value) + { + $this->getAttributeBag()->set($name, $value); + } + + /** + * {@inheritdoc} + */ + public function all() + { + return $this->getAttributeBag()->all(); + } + + /** + * {@inheritdoc} + */ + public function replace(array $attributes) + { + $this->getAttributeBag()->replace($attributes); + } + + /** + * {@inheritdoc} + */ + public function remove(string $name) + { + return $this->getAttributeBag()->remove($name); + } + + /** + * {@inheritdoc} + */ + public function clear() + { + $this->getAttributeBag()->clear(); + } + + /** + * {@inheritdoc} + */ + public function isStarted() + { + return $this->storage->isStarted(); + } + + /** + * Returns an iterator for attributes. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new \ArrayIterator($this->getAttributeBag()->all()); + } + + /** + * Returns the number of attributes. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return \count($this->getAttributeBag()->all()); + } + + public function &getUsageIndex(): int + { + return $this->usageIndex; + } + + /** + * @internal + */ + public function isEmpty(): bool + { + if ($this->isStarted()) { + ++$this->usageIndex; + if ($this->usageReporter && 0 <= $this->usageIndex) { + ($this->usageReporter)(); + } + } + foreach ($this->data as &$data) { + if (!empty($data)) { + return false; + } + } + + return true; + } + + /** + * {@inheritdoc} + */ + public function invalidate(?int $lifetime = null) + { + $this->storage->clear(); + + return $this->migrate(true, $lifetime); + } + + /** + * {@inheritdoc} + */ + public function migrate(bool $destroy = false, ?int $lifetime = null) + { + return $this->storage->regenerate($destroy, $lifetime); + } + + /** + * {@inheritdoc} + */ + public function save() + { + $this->storage->save(); + } + + /** + * {@inheritdoc} + */ + public function getId() + { + return $this->storage->getId(); + } + + /** + * {@inheritdoc} + */ + public function setId(string $id) + { + if ($this->storage->getId() !== $id) { + $this->storage->setId($id); + } + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->storage->getName(); + } + + /** + * {@inheritdoc} + */ + public function setName(string $name) + { + $this->storage->setName($name); + } + + /** + * {@inheritdoc} + */ + public function getMetadataBag() + { + ++$this->usageIndex; + if ($this->usageReporter && 0 <= $this->usageIndex) { + ($this->usageReporter)(); + } + + return $this->storage->getMetadataBag(); + } + + /** + * {@inheritdoc} + */ + public function registerBag(SessionBagInterface $bag) + { + $this->storage->registerBag(new SessionBagProxy($bag, $this->data, $this->usageIndex, $this->usageReporter)); + } + + /** + * {@inheritdoc} + */ + public function getBag(string $name) + { + $bag = $this->storage->getBag($name); + + return method_exists($bag, 'getBag') ? $bag->getBag() : $bag; + } + + /** + * Gets the flashbag interface. + * + * @return FlashBagInterface + */ + public function getFlashBag() + { + return $this->getBag($this->flashName); + } + + /** + * Gets the attributebag interface. + * + * Note that this method was added to help with IDE autocompletion. + */ + private function getAttributeBag(): AttributeBagInterface + { + return $this->getBag($this->attributeName); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionBagInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionBagInterface.php new file mode 100644 index 0000000..8e37d06 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionBagInterface.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 Symfony\Component\HttpFoundation\Session; + +/** + * Session Bag store. + * + * @author Drak + */ +interface SessionBagInterface +{ + /** + * Gets this bag's name. + * + * @return string + */ + public function getName(); + + /** + * Initializes the Bag. + */ + public function initialize(array &$array); + + /** + * Gets the storage key for this bag. + * + * @return string + */ + public function getStorageKey(); + + /** + * Clears out data from bag. + * + * @return mixed Whatever data was contained + */ + public function clear(); +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionBagProxy.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionBagProxy.php new file mode 100644 index 0000000..90aa010 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionBagProxy.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session; + +/** + * @author Nicolas Grekas + * + * @internal + */ +final class SessionBagProxy implements SessionBagInterface +{ + private $bag; + private $data; + private $usageIndex; + private $usageReporter; + + public function __construct(SessionBagInterface $bag, array &$data, ?int &$usageIndex, ?callable $usageReporter) + { + $this->bag = $bag; + $this->data = &$data; + $this->usageIndex = &$usageIndex; + $this->usageReporter = $usageReporter; + } + + public function getBag(): SessionBagInterface + { + ++$this->usageIndex; + if ($this->usageReporter && 0 <= $this->usageIndex) { + ($this->usageReporter)(); + } + + return $this->bag; + } + + public function isEmpty(): bool + { + if (!isset($this->data[$this->bag->getStorageKey()])) { + return true; + } + ++$this->usageIndex; + if ($this->usageReporter && 0 <= $this->usageIndex) { + ($this->usageReporter)(); + } + + return empty($this->data[$this->bag->getStorageKey()]); + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return $this->bag->getName(); + } + + /** + * {@inheritdoc} + */ + public function initialize(array &$array): void + { + ++$this->usageIndex; + if ($this->usageReporter && 0 <= $this->usageIndex) { + ($this->usageReporter)(); + } + + $this->data[$this->bag->getStorageKey()] = &$array; + + $this->bag->initialize($array); + } + + /** + * {@inheritdoc} + */ + public function getStorageKey(): string + { + return $this->bag->getStorageKey(); + } + + /** + * {@inheritdoc} + */ + public function clear() + { + return $this->bag->clear(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionFactory.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionFactory.php new file mode 100644 index 0000000..bd79282 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionFactory.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\HttpFoundation\Session; + +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageFactoryInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(Session::class); + +/** + * @author Jérémy Derussé + */ +class SessionFactory implements SessionFactoryInterface +{ + private $requestStack; + private $storageFactory; + private $usageReporter; + + public function __construct(RequestStack $requestStack, SessionStorageFactoryInterface $storageFactory, ?callable $usageReporter = null) + { + $this->requestStack = $requestStack; + $this->storageFactory = $storageFactory; + $this->usageReporter = $usageReporter; + } + + public function createSession(): SessionInterface + { + return new Session($this->storageFactory->createStorage($this->requestStack->getMainRequest()), null, null, $this->usageReporter); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionFactoryInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionFactoryInterface.php new file mode 100644 index 0000000..b24fdc4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionFactoryInterface.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\HttpFoundation\Session; + +/** + * @author Kevin Bond + */ +interface SessionFactoryInterface +{ + public function createSession(): SessionInterface; +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionInterface.php new file mode 100644 index 0000000..b73dfd0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionInterface.php @@ -0,0 +1,166 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session; + +use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag; + +/** + * Interface for the session. + * + * @author Drak + */ +interface SessionInterface +{ + /** + * Starts the session storage. + * + * @return bool + * + * @throws \RuntimeException if session fails to start + */ + public function start(); + + /** + * Returns the session ID. + * + * @return string + */ + public function getId(); + + /** + * Sets the session ID. + */ + public function setId(string $id); + + /** + * Returns the session name. + * + * @return string + */ + public function getName(); + + /** + * Sets the session name. + */ + public function setName(string $name); + + /** + * Invalidates the current session. + * + * Clears all session attributes and flashes and regenerates the + * session and deletes the old session from persistence. + * + * @param int|null $lifetime Sets the cookie lifetime for the session cookie. A null value + * will leave the system settings unchanged, 0 sets the cookie + * to expire with browser session. Time is in seconds, and is + * not a Unix timestamp. + * + * @return bool + */ + public function invalidate(?int $lifetime = null); + + /** + * Migrates the current session to a new session id while maintaining all + * session attributes. + * + * @param bool $destroy Whether to delete the old session or leave it to garbage collection + * @param int|null $lifetime Sets the cookie lifetime for the session cookie. A null value + * will leave the system settings unchanged, 0 sets the cookie + * to expire with browser session. Time is in seconds, and is + * not a Unix timestamp. + * + * @return bool + */ + public function migrate(bool $destroy = false, ?int $lifetime = null); + + /** + * Force the session to be saved and closed. + * + * This method is generally not required for real sessions as + * the session will be automatically saved at the end of + * code execution. + */ + public function save(); + + /** + * Checks if an attribute is defined. + * + * @return bool + */ + public function has(string $name); + + /** + * Returns an attribute. + * + * @param mixed $default The default value if not found + * + * @return mixed + */ + public function get(string $name, $default = null); + + /** + * Sets an attribute. + * + * @param mixed $value + */ + public function set(string $name, $value); + + /** + * Returns attributes. + * + * @return array + */ + public function all(); + + /** + * Sets attributes. + */ + public function replace(array $attributes); + + /** + * Removes an attribute. + * + * @return mixed The removed value or null when it does not exist + */ + public function remove(string $name); + + /** + * Clears all attributes. + */ + public function clear(); + + /** + * Checks if the session was started. + * + * @return bool + */ + public function isStarted(); + + /** + * Registers a SessionBagInterface with the session. + */ + public function registerBag(SessionBagInterface $bag); + + /** + * Gets a bag instance by name. + * + * @return SessionBagInterface + */ + public function getBag(string $name); + + /** + * Gets session meta. + * + * @return MetadataBag + */ + public function getMetadataBag(); +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionUtils.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionUtils.php new file mode 100644 index 0000000..b5bce4a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/SessionUtils.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session; + +/** + * Session utility functions. + * + * @author Nicolas Grekas + * @author Rémon van de Kamp + * + * @internal + */ +final class SessionUtils +{ + /** + * Finds the session header amongst the headers that are to be sent, removes it, and returns + * it so the caller can process it further. + */ + public static function popSessionCookie(string $sessionName, string $sessionId): ?string + { + $sessionCookie = null; + $sessionCookiePrefix = sprintf(' %s=', urlencode($sessionName)); + $sessionCookieWithId = sprintf('%s%s;', $sessionCookiePrefix, urlencode($sessionId)); + $otherCookies = []; + foreach (headers_list() as $h) { + if (0 !== stripos($h, 'Set-Cookie:')) { + continue; + } + if (11 === strpos($h, $sessionCookiePrefix, 11)) { + $sessionCookie = $h; + + if (11 !== strpos($h, $sessionCookieWithId, 11)) { + $otherCookies[] = $h; + } + } else { + $otherCookies[] = $h; + } + } + if (null === $sessionCookie) { + return null; + } + + header_remove('Set-Cookie'); + foreach ($otherCookies as $h) { + header($h, false); + } + + return $sessionCookie; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php new file mode 100644 index 0000000..35d7b4b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php @@ -0,0 +1,155 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +use Symfony\Component\HttpFoundation\Session\SessionUtils; + +/** + * This abstract session handler provides a generic implementation + * of the PHP 7.0 SessionUpdateTimestampHandlerInterface, + * enabling strict and lazy session handling. + * + * @author Nicolas Grekas + */ +abstract class AbstractSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface +{ + private $sessionName; + private $prefetchId; + private $prefetchData; + private $newSessionId; + private $igbinaryEmptyData; + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + $this->sessionName = $sessionName; + if (!headers_sent() && !\ini_get('session.cache_limiter') && '0' !== \ini_get('session.cache_limiter')) { + header(sprintf('Cache-Control: max-age=%d, private, must-revalidate', 60 * (int) \ini_get('session.cache_expire'))); + } + + return true; + } + + /** + * @return string + */ + abstract protected function doRead(string $sessionId); + + /** + * @return bool + */ + abstract protected function doWrite(string $sessionId, string $data); + + /** + * @return bool + */ + abstract protected function doDestroy(string $sessionId); + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function validateId($sessionId) + { + $this->prefetchData = $this->read($sessionId); + $this->prefetchId = $sessionId; + + if (\PHP_VERSION_ID < 70317 || (70400 <= \PHP_VERSION_ID && \PHP_VERSION_ID < 70405)) { + // work around https://bugs.php.net/79413 + foreach (debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) { + if (!isset($frame['class']) && isset($frame['function']) && \in_array($frame['function'], ['session_regenerate_id', 'session_create_id'], true)) { + return '' === $this->prefetchData; + } + } + } + + return '' !== $this->prefetchData; + } + + /** + * @return string + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + if (null !== $this->prefetchId) { + $prefetchId = $this->prefetchId; + $prefetchData = $this->prefetchData; + $this->prefetchId = $this->prefetchData = null; + + if ($prefetchId === $sessionId || '' === $prefetchData) { + $this->newSessionId = '' === $prefetchData ? $sessionId : null; + + return $prefetchData; + } + } + + $data = $this->doRead($sessionId); + $this->newSessionId = '' === $data ? $sessionId : null; + + return $data; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + if (null === $this->igbinaryEmptyData) { + // see https://github.com/igbinary/igbinary/issues/146 + $this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize([]) : ''; + } + if ('' === $data || $this->igbinaryEmptyData === $data) { + return $this->destroy($sessionId); + } + $this->newSessionId = null; + + return $this->doWrite($sessionId, $data); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN)) { + if (!$this->sessionName) { + throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', static::class)); + } + $cookie = SessionUtils::popSessionCookie($this->sessionName, $sessionId); + + /* + * We send an invalidation Set-Cookie header (zero lifetime) + * when either the session was started or a cookie with + * the session name was sent by the client (in which case + * we know it's invalid as a valid session cookie would've + * started the session). + */ + if (null === $cookie || isset($_COOKIE[$this->sessionName])) { + if (\PHP_VERSION_ID < 70300) { + setcookie($this->sessionName, '', 0, \ini_get('session.cookie_path'), \ini_get('session.cookie_domain'), filter_var(\ini_get('session.cookie_secure'), \FILTER_VALIDATE_BOOLEAN), filter_var(\ini_get('session.cookie_httponly'), \FILTER_VALIDATE_BOOLEAN)); + } else { + $params = session_get_cookie_params(); + unset($params['lifetime']); + setcookie($this->sessionName, '', $params); + } + } + } + + return $this->newSessionId === $sessionId || $this->doDestroy($sessionId); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/IdentityMarshaller.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/IdentityMarshaller.php new file mode 100644 index 0000000..bea3a32 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/IdentityMarshaller.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +use Symfony\Component\Cache\Marshaller\MarshallerInterface; + +/** + * @author Ahmed TAILOULOUTE + */ +class IdentityMarshaller implements MarshallerInterface +{ + /** + * {@inheritdoc} + */ + public function marshall(array $values, ?array &$failed): array + { + foreach ($values as $key => $value) { + if (!\is_string($value)) { + throw new \LogicException(sprintf('%s accepts only string as data.', __METHOD__)); + } + } + + return $values; + } + + /** + * {@inheritdoc} + */ + public function unmarshall(string $value): string + { + return $value; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php new file mode 100644 index 0000000..c321c8c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +use Symfony\Component\Cache\Marshaller\MarshallerInterface; + +/** + * @author Ahmed TAILOULOUTE + */ +class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface +{ + private $handler; + private $marshaller; + + public function __construct(AbstractSessionHandler $handler, MarshallerInterface $marshaller) + { + $this->handler = $handler; + $this->marshaller = $marshaller; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $name) + { + return $this->handler->open($savePath, $name); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return $this->handler->close(); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + return $this->handler->destroy($sessionId); + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + return $this->handler->gc($maxlifetime); + } + + /** + * @return string + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + return $this->marshaller->unmarshall($this->handler->read($sessionId)); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + $failed = []; + $marshalledData = $this->marshaller->marshall(['data' => $data], $failed); + + if (isset($failed['data'])) { + return false; + } + + return $this->handler->write($sessionId, $marshalledData['data']); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function validateId($sessionId) + { + return $this->handler->validateId($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + return $this->handler->updateTimestamp($sessionId, $data); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php new file mode 100644 index 0000000..e0ec4d2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php @@ -0,0 +1,135 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Memcached based session storage handler based on the Memcached class + * provided by the PHP memcached extension. + * + * @see https://php.net/memcached + * + * @author Drak + */ +class MemcachedSessionHandler extends AbstractSessionHandler +{ + private $memcached; + + /** + * @var int Time to live in seconds + */ + private $ttl; + + /** + * @var string Key prefix for shared environments + */ + private $prefix; + + /** + * Constructor. + * + * List of available options: + * * prefix: The prefix to use for the memcached keys in order to avoid collision + * * ttl: The time to live in seconds. + * + * @throws \InvalidArgumentException When unsupported options are passed + */ + public function __construct(\Memcached $memcached, array $options = []) + { + $this->memcached = $memcached; + + if ($diff = array_diff(array_keys($options), ['prefix', 'expiretime', 'ttl'])) { + throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff))); + } + + $this->ttl = $options['expiretime'] ?? $options['ttl'] ?? null; + $this->prefix = $options['prefix'] ?? 'sf2s'; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return $this->memcached->quit(); + } + + /** + * {@inheritdoc} + */ + protected function doRead(string $sessionId) + { + return $this->memcached->get($this->prefix.$sessionId) ?: ''; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + $this->memcached->touch($this->prefix.$sessionId, $this->getCompatibleTtl()); + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $sessionId, string $data) + { + return $this->memcached->set($this->prefix.$sessionId, $data, $this->getCompatibleTtl()); + } + + private function getCompatibleTtl(): int + { + $ttl = (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')); + + // If the relative TTL that is used exceeds 30 days, memcached will treat the value as Unix time. + // We have to convert it to an absolute Unix time at this point, to make sure the TTL is correct. + if ($ttl > 60 * 60 * 24 * 30) { + $ttl += time(); + } + + return $ttl; + } + + /** + * {@inheritdoc} + */ + protected function doDestroy(string $sessionId) + { + $result = $this->memcached->delete($this->prefix.$sessionId); + + return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode(); + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + // not required here because memcached will auto expire the records anyhow. + return 0; + } + + /** + * Return a Memcached instance. + * + * @return \Memcached + */ + protected function getMemcached() + { + return $this->memcached; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MigratingSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MigratingSessionHandler.php new file mode 100644 index 0000000..bf27ca6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MigratingSessionHandler.php @@ -0,0 +1,139 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Migrating session handler for migrating from one handler to another. It reads + * from the current handler and writes both the current and new ones. + * + * It ignores errors from the new handler. + * + * @author Ross Motley + * @author Oliver Radwell + */ +class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface +{ + /** + * @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface + */ + private $currentHandler; + + /** + * @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface + */ + private $writeOnlyHandler; + + public function __construct(\SessionHandlerInterface $currentHandler, \SessionHandlerInterface $writeOnlyHandler) + { + if (!$currentHandler instanceof \SessionUpdateTimestampHandlerInterface) { + $currentHandler = new StrictSessionHandler($currentHandler); + } + if (!$writeOnlyHandler instanceof \SessionUpdateTimestampHandlerInterface) { + $writeOnlyHandler = new StrictSessionHandler($writeOnlyHandler); + } + + $this->currentHandler = $currentHandler; + $this->writeOnlyHandler = $writeOnlyHandler; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + $result = $this->currentHandler->close(); + $this->writeOnlyHandler->close(); + + return $result; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + $result = $this->currentHandler->destroy($sessionId); + $this->writeOnlyHandler->destroy($sessionId); + + return $result; + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + $result = $this->currentHandler->gc($maxlifetime); + $this->writeOnlyHandler->gc($maxlifetime); + + return $result; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + $result = $this->currentHandler->open($savePath, $sessionName); + $this->writeOnlyHandler->open($savePath, $sessionName); + + return $result; + } + + /** + * @return string + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + // No reading from new handler until switch-over + return $this->currentHandler->read($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $sessionData) + { + $result = $this->currentHandler->write($sessionId, $sessionData); + $this->writeOnlyHandler->write($sessionId, $sessionData); + + return $result; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function validateId($sessionId) + { + // No reading from new handler until switch-over + return $this->currentHandler->validateId($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $sessionData) + { + $result = $this->currentHandler->updateTimestamp($sessionId, $sessionData); + $this->writeOnlyHandler->updateTimestamp($sessionId, $sessionData); + + return $result; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php new file mode 100644 index 0000000..ef8f719 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php @@ -0,0 +1,193 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +use MongoDB\BSON\Binary; +use MongoDB\BSON\UTCDateTime; +use MongoDB\Client; +use MongoDB\Collection; + +/** + * Session handler using the mongodb/mongodb package and MongoDB driver extension. + * + * @author Markus Bachmann + * + * @see https://packagist.org/packages/mongodb/mongodb + * @see https://php.net/mongodb + */ +class MongoDbSessionHandler extends AbstractSessionHandler +{ + private $mongo; + + /** + * @var Collection + */ + private $collection; + + /** + * @var array + */ + private $options; + + /** + * Constructor. + * + * List of available options: + * * database: The name of the database [required] + * * collection: The name of the collection [required] + * * id_field: The field name for storing the session id [default: _id] + * * data_field: The field name for storing the session data [default: data] + * * time_field: The field name for storing the timestamp [default: time] + * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]. + * + * It is strongly recommended to put an index on the `expiry_field` for + * garbage-collection. Alternatively it's possible to automatically expire + * the sessions in the database as described below: + * + * A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions + * automatically. Such an index can for example look like this: + * + * db..createIndex( + * { "": 1 }, + * { "expireAfterSeconds": 0 } + * ) + * + * More details on: https://docs.mongodb.org/manual/tutorial/expire-data/ + * + * If you use such an index, you can drop `gc_probability` to 0 since + * no garbage-collection is required. + * + * @throws \InvalidArgumentException When "database" or "collection" not provided + */ + public function __construct(Client $mongo, array $options) + { + if (!isset($options['database']) || !isset($options['collection'])) { + throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler.'); + } + + $this->mongo = $mongo; + + $this->options = array_merge([ + 'id_field' => '_id', + 'data_field' => 'data', + 'time_field' => 'time', + 'expiry_field' => 'expires_at', + ], $options); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * {@inheritdoc} + */ + protected function doDestroy(string $sessionId) + { + $this->getCollection()->deleteOne([ + $this->options['id_field'] => $sessionId, + ]); + + return true; + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + return $this->getCollection()->deleteMany([ + $this->options['expiry_field'] => ['$lt' => new UTCDateTime()], + ])->getDeletedCount(); + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $sessionId, string $data) + { + $expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000); + + $fields = [ + $this->options['time_field'] => new UTCDateTime(), + $this->options['expiry_field'] => $expiry, + $this->options['data_field'] => new Binary($data, Binary::TYPE_OLD_BINARY), + ]; + + $this->getCollection()->updateOne( + [$this->options['id_field'] => $sessionId], + ['$set' => $fields], + ['upsert' => true] + ); + + return true; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + $expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000); + + $this->getCollection()->updateOne( + [$this->options['id_field'] => $sessionId], + ['$set' => [ + $this->options['time_field'] => new UTCDateTime(), + $this->options['expiry_field'] => $expiry, + ]] + ); + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doRead(string $sessionId) + { + $dbData = $this->getCollection()->findOne([ + $this->options['id_field'] => $sessionId, + $this->options['expiry_field'] => ['$gte' => new UTCDateTime()], + ]); + + if (null === $dbData) { + return ''; + } + + return $dbData[$this->options['data_field']]->getData(); + } + + private function getCollection(): Collection + { + if (null === $this->collection) { + $this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']); + } + + return $this->collection; + } + + /** + * @return Client + */ + protected function getMongo() + { + return $this->mongo; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php new file mode 100644 index 0000000..570d4f4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Native session handler using PHP's built in file storage. + * + * @author Drak + */ +class NativeFileSessionHandler extends \SessionHandler +{ + /** + * @param string|null $savePath Path of directory to save session files + * Default null will leave setting as defined by PHP. + * '/path', 'N;/path', or 'N;octal-mode;/path + * + * @see https://php.net/session.configuration#ini.session.save-path for further details. + * + * @throws \InvalidArgumentException On invalid $savePath + * @throws \RuntimeException When failing to create the save directory + */ + public function __construct(?string $savePath = null) + { + if (null === $savePath) { + $savePath = \ini_get('session.save_path'); + } + + $baseDir = $savePath; + + if ($count = substr_count($savePath, ';')) { + if ($count > 2) { + throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'.', $savePath)); + } + + // characters after last ';' are the path + $baseDir = ltrim(strrchr($savePath, ';'), ';'); + } + + if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) { + throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s".', $baseDir)); + } + + if ($savePath !== \ini_get('session.save_path')) { + ini_set('session.save_path', $savePath); + } + if ('files' !== \ini_get('session.save_handler')) { + ini_set('session.save_handler', 'files'); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php new file mode 100644 index 0000000..4331dbe --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Can be used in unit testing or in a situations where persisted sessions are not desired. + * + * @author Drak + */ +class NullSessionHandler extends AbstractSessionHandler +{ + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return true; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function validateId($sessionId) + { + return true; + } + + /** + * {@inheritdoc} + */ + protected function doRead(string $sessionId) + { + return ''; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + return true; + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $sessionId, string $data) + { + return true; + } + + /** + * {@inheritdoc} + */ + protected function doDestroy(string $sessionId) + { + return true; + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + return 0; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php new file mode 100644 index 0000000..f9c5d9b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php @@ -0,0 +1,943 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Session handler using a PDO connection to read and write data. + * + * It works with MySQL, PostgreSQL, Oracle, SQL Server and SQLite and implements + * different locking strategies to handle concurrent access to the same session. + * Locking is necessary to prevent loss of data due to race conditions and to keep + * the session data consistent between read() and write(). With locking, requests + * for the same session will wait until the other one finished writing. For this + * reason it's best practice to close a session as early as possible to improve + * concurrency. PHPs internal files session handler also implements locking. + * + * Attention: Since SQLite does not support row level locks but locks the whole database, + * it means only one session can be accessed at a time. Even different sessions would wait + * for another to finish. So saving session in SQLite should only be considered for + * development or prototypes. + * + * Session data is a binary string that can contain non-printable characters like the null byte. + * For this reason it must be saved in a binary column in the database like BLOB in MySQL. + * Saving it in a character column could corrupt the data. You can use createTable() + * to initialize a correctly defined table. + * + * @see https://php.net/sessionhandlerinterface + * + * @author Fabien Potencier + * @author Michael Williams + * @author Tobias Schultze + */ +class PdoSessionHandler extends AbstractSessionHandler +{ + /** + * No locking is done. This means sessions are prone to loss of data due to + * race conditions of concurrent requests to the same session. The last session + * write will win in this case. It might be useful when you implement your own + * logic to deal with this like an optimistic approach. + */ + public const LOCK_NONE = 0; + + /** + * Creates an application-level lock on a session. The disadvantage is that the + * lock is not enforced by the database and thus other, unaware parts of the + * application could still concurrently modify the session. The advantage is it + * does not require a transaction. + * This mode is not available for SQLite and not yet implemented for oci and sqlsrv. + */ + public const LOCK_ADVISORY = 1; + + /** + * Issues a real row lock. Since it uses a transaction between opening and + * closing a session, you have to be careful when you use same database connection + * that you also use for your application logic. This mode is the default because + * it's the only reliable solution across DBMSs. + */ + public const LOCK_TRANSACTIONAL = 2; + + private const MAX_LIFETIME = 315576000; + + /** + * @var \PDO|null PDO instance or null when not connected yet + */ + private $pdo; + + /** + * DSN string or null for session.save_path or false when lazy connection disabled. + * + * @var string|false|null + */ + private $dsn = false; + + /** + * @var string|null + */ + private $driver; + + /** + * @var string + */ + private $table = 'sessions'; + + /** + * @var string + */ + private $idCol = 'sess_id'; + + /** + * @var string + */ + private $dataCol = 'sess_data'; + + /** + * @var string + */ + private $lifetimeCol = 'sess_lifetime'; + + /** + * @var string + */ + private $timeCol = 'sess_time'; + + /** + * Username when lazy-connect. + * + * @var string|null + */ + private $username = null; + + /** + * Password when lazy-connect. + * + * @var string|null + */ + private $password = null; + + /** + * Connection options when lazy-connect. + * + * @var array + */ + private $connectionOptions = []; + + /** + * The strategy for locking, see constants. + * + * @var int + */ + private $lockMode = self::LOCK_TRANSACTIONAL; + + /** + * It's an array to support multiple reads before closing which is manual, non-standard usage. + * + * @var \PDOStatement[] An array of statements to release advisory locks + */ + private $unlockStatements = []; + + /** + * True when the current session exists but expired according to session.gc_maxlifetime. + * + * @var bool + */ + private $sessionExpired = false; + + /** + * Whether a transaction is active. + * + * @var bool + */ + private $inTransaction = false; + + /** + * Whether gc() has been called. + * + * @var bool + */ + private $gcCalled = false; + + /** + * You can either pass an existing database connection as PDO instance or + * pass a DSN string that will be used to lazy-connect to the database + * when the session is actually used. Furthermore it's possible to pass null + * which will then use the session.save_path ini setting as PDO DSN parameter. + * + * List of available options: + * * db_table: The name of the table [default: sessions] + * * db_id_col: The column where to store the session id [default: sess_id] + * * db_data_col: The column where to store the session data [default: sess_data] + * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime] + * * db_time_col: The column where to store the timestamp [default: sess_time] + * * db_username: The username when lazy-connect [default: ''] + * * db_password: The password when lazy-connect [default: ''] + * * db_connection_options: An array of driver-specific connection options [default: []] + * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL] + * + * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null + * + * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION + */ + public function __construct($pdoOrDsn = null, array $options = []) + { + if ($pdoOrDsn instanceof \PDO) { + if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) { + throw new \InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__)); + } + + $this->pdo = $pdoOrDsn; + $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); + } elseif (\is_string($pdoOrDsn) && str_contains($pdoOrDsn, '://')) { + $this->dsn = $this->buildDsnFromUrl($pdoOrDsn); + } else { + $this->dsn = $pdoOrDsn; + } + + $this->table = $options['db_table'] ?? $this->table; + $this->idCol = $options['db_id_col'] ?? $this->idCol; + $this->dataCol = $options['db_data_col'] ?? $this->dataCol; + $this->lifetimeCol = $options['db_lifetime_col'] ?? $this->lifetimeCol; + $this->timeCol = $options['db_time_col'] ?? $this->timeCol; + $this->username = $options['db_username'] ?? $this->username; + $this->password = $options['db_password'] ?? $this->password; + $this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions; + $this->lockMode = $options['lock_mode'] ?? $this->lockMode; + } + + /** + * Creates the table to store sessions which can be called once for setup. + * + * Session ID is saved in a column of maximum length 128 because that is enough even + * for a 512 bit configured session.hash_function like Whirlpool. Session data is + * saved in a BLOB. One could also use a shorter inlined varbinary column + * if one was sure the data fits into it. + * + * @throws \PDOException When the table already exists + * @throws \DomainException When an unsupported PDO driver is used + */ + public function createTable() + { + // connect if we are not yet + $this->getConnection(); + + switch ($this->driver) { + case 'mysql': + // We use varbinary for the ID column because it prevents unwanted conversions: + // - character set conversions between server and client + // - trailing space removal + // - case-insensitivity + // - language processing like é == e + $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB"; + break; + case 'sqlite': + $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; + break; + case 'pgsql': + $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; + break; + case 'oci': + $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; + break; + case 'sqlsrv': + $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; + break; + default: + throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)); + } + + try { + $this->pdo->exec($sql); + $this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)"); + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + } + + /** + * Returns true when the current session exists but expired according to session.gc_maxlifetime. + * + * Can be used to distinguish between a new session and one that expired due to inactivity. + * + * @return bool + */ + public function isSessionExpired() + { + return $this->sessionExpired; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + $this->sessionExpired = false; + + if (null === $this->pdo) { + $this->connect($this->dsn ?: $savePath); + } + + return parent::open($savePath, $sessionName); + } + + /** + * @return string + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + try { + return parent::read($sessionId); + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process. + // This way, pruning expired sessions does not block them from being started while the current session is used. + $this->gcCalled = true; + + return 0; + } + + /** + * {@inheritdoc} + */ + protected function doDestroy(string $sessionId) + { + // delete the record associated with this id + $sql = "DELETE FROM $this->table WHERE $this->idCol = :id"; + + try { + $stmt = $this->pdo->prepare($sql); + $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $stmt->execute(); + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $sessionId, string $data) + { + $maxlifetime = (int) \ini_get('session.gc_maxlifetime'); + + try { + // We use a single MERGE SQL query when supported by the database. + $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime); + if (null !== $mergeStmt) { + $mergeStmt->execute(); + + return true; + } + + $updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime); + $updateStmt->execute(); + + // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in + // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior). + // We can just catch such an error and re-execute the update. This is similar to a serializable + // transaction with retry logic on serialization failures but without the overhead and without possible + // false positives due to longer gap locking. + if (!$updateStmt->rowCount()) { + try { + $insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime); + $insertStmt->execute(); + } catch (\PDOException $e) { + // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys + if (str_starts_with($e->getCode(), '23')) { + $updateStmt->execute(); + } else { + throw $e; + } + } + } + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + + return true; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + $expiry = time() + (int) \ini_get('session.gc_maxlifetime'); + + try { + $updateStmt = $this->pdo->prepare( + "UPDATE $this->table SET $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id" + ); + $updateStmt->bindValue(':id', $sessionId, \PDO::PARAM_STR); + $updateStmt->bindValue(':expiry', $expiry, \PDO::PARAM_INT); + $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $updateStmt->execute(); + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + + return true; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + $this->commit(); + + while ($unlockStmt = array_shift($this->unlockStatements)) { + $unlockStmt->execute(); + } + + if ($this->gcCalled) { + $this->gcCalled = false; + + // delete the session records that have expired + $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time AND $this->lifetimeCol > :min"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':time', time(), \PDO::PARAM_INT); + $stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT); + $stmt->execute(); + // to be removed in 6.0 + if ('mysql' === $this->driver) { + $legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol + $this->timeCol < :time"; + } else { + $legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol < :time - $this->timeCol"; + } + + $stmt = $this->pdo->prepare($legacySql); + $stmt->bindValue(':time', time(), \PDO::PARAM_INT); + $stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT); + $stmt->execute(); + } + + if (false !== $this->dsn) { + $this->pdo = null; // only close lazy-connection + $this->driver = null; + } + + return true; + } + + /** + * Lazy-connects to the database. + */ + private function connect(string $dsn): void + { + $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions); + $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); + } + + /** + * Builds a PDO DSN from a URL-like connection string. + * + * @todo implement missing support for oci DSN (which look totally different from other PDO ones) + */ + private function buildDsnFromUrl(string $dsnOrUrl): string + { + // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid + $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl); + + $params = parse_url($url); + + if (false === $params) { + return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already. + } + + $params = array_map('rawurldecode', $params); + + // Override the default username and password. Values passed through options will still win over these in the constructor. + if (isset($params['user'])) { + $this->username = $params['user']; + } + + if (isset($params['pass'])) { + $this->password = $params['pass']; + } + + if (!isset($params['scheme'])) { + throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler.'); + } + + $driverAliasMap = [ + 'mssql' => 'sqlsrv', + 'mysql2' => 'mysql', // Amazon RDS, for some weird reason + 'postgres' => 'pgsql', + 'postgresql' => 'pgsql', + 'sqlite3' => 'sqlite', + ]; + + $driver = $driverAliasMap[$params['scheme']] ?? $params['scheme']; + + // Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here. + if (str_starts_with($driver, 'pdo_') || str_starts_with($driver, 'pdo-')) { + $driver = substr($driver, 4); + } + + $dsn = null; + switch ($driver) { + case 'mysql': + $dsn = 'mysql:'; + if ('' !== ($params['query'] ?? '')) { + $queryParams = []; + parse_str($params['query'], $queryParams); + if ('' !== ($queryParams['charset'] ?? '')) { + $dsn .= 'charset='.$queryParams['charset'].';'; + } + + if ('' !== ($queryParams['unix_socket'] ?? '')) { + $dsn .= 'unix_socket='.$queryParams['unix_socket'].';'; + + if (isset($params['path'])) { + $dbName = substr($params['path'], 1); // Remove the leading slash + $dsn .= 'dbname='.$dbName.';'; + } + + return $dsn; + } + } + // If "unix_socket" is not in the query, we continue with the same process as pgsql + // no break + case 'pgsql': + $dsn ?? $dsn = 'pgsql:'; + + if (isset($params['host']) && '' !== $params['host']) { + $dsn .= 'host='.$params['host'].';'; + } + + if (isset($params['port']) && '' !== $params['port']) { + $dsn .= 'port='.$params['port'].';'; + } + + if (isset($params['path'])) { + $dbName = substr($params['path'], 1); // Remove the leading slash + $dsn .= 'dbname='.$dbName.';'; + } + + return $dsn; + + case 'sqlite': + return 'sqlite:'.substr($params['path'], 1); + + case 'sqlsrv': + $dsn = 'sqlsrv:server='; + + if (isset($params['host'])) { + $dsn .= $params['host']; + } + + if (isset($params['port']) && '' !== $params['port']) { + $dsn .= ','.$params['port']; + } + + if (isset($params['path'])) { + $dbName = substr($params['path'], 1); // Remove the leading slash + $dsn .= ';Database='.$dbName; + } + + return $dsn; + + default: + throw new \InvalidArgumentException(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme'])); + } + } + + /** + * Helper method to begin a transaction. + * + * Since SQLite does not support row level locks, we have to acquire a reserved lock + * on the database immediately. Because of https://bugs.php.net/42766 we have to create + * such a transaction manually which also means we cannot use PDO::commit or + * PDO::rollback or PDO::inTransaction for SQLite. + * + * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions + * due to https://percona.com/blog/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . + * So we change it to READ COMMITTED. + */ + private function beginTransaction(): void + { + if (!$this->inTransaction) { + if ('sqlite' === $this->driver) { + $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION'); + } else { + if ('mysql' === $this->driver) { + $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED'); + } + $this->pdo->beginTransaction(); + } + $this->inTransaction = true; + } + } + + /** + * Helper method to commit a transaction. + */ + private function commit(): void + { + if ($this->inTransaction) { + try { + // commit read-write transaction which also releases the lock + if ('sqlite' === $this->driver) { + $this->pdo->exec('COMMIT'); + } else { + $this->pdo->commit(); + } + $this->inTransaction = false; + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + } + } + + /** + * Helper method to rollback a transaction. + */ + private function rollback(): void + { + // We only need to rollback if we are in a transaction. Otherwise the resulting + // error would hide the real problem why rollback was called. We might not be + // in a transaction when not using the transactional locking behavior or when + // two callbacks (e.g. destroy and write) are invoked that both fail. + if ($this->inTransaction) { + if ('sqlite' === $this->driver) { + $this->pdo->exec('ROLLBACK'); + } else { + $this->pdo->rollBack(); + } + $this->inTransaction = false; + } + } + + /** + * Reads the session data in respect to the different locking strategies. + * + * We need to make sure we do not return session data that is already considered garbage according + * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes. + * + * @return string + */ + protected function doRead(string $sessionId) + { + if (self::LOCK_ADVISORY === $this->lockMode) { + $this->unlockStatements[] = $this->doAdvisoryLock($sessionId); + } + + $selectSql = $this->getSelectSql(); + $selectStmt = $this->pdo->prepare($selectSql); + $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $insertStmt = null; + + while (true) { + $selectStmt->execute(); + $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); + + if ($sessionRows) { + $expiry = (int) $sessionRows[0][1]; + if ($expiry <= self::MAX_LIFETIME) { + $expiry += $sessionRows[0][2]; + } + + if ($expiry < time()) { + $this->sessionExpired = true; + + return ''; + } + + return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; + } + + if (null !== $insertStmt) { + $this->rollback(); + throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.'); + } + + if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { + // In strict mode, session fixation is not possible: new sessions always start with a unique + // random id, so that concurrency is not possible and this code path can be skipped. + // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block + // until other connections to the session are committed. + try { + $insertStmt = $this->getInsertStatement($sessionId, '', 0); + $insertStmt->execute(); + } catch (\PDOException $e) { + // Catch duplicate key error because other connection created the session already. + // It would only not be the case when the other connection destroyed the session. + if (str_starts_with($e->getCode(), '23')) { + // Retrieve finished session data written by concurrent connection by restarting the loop. + // We have to start a new transaction as a failed query will mark the current transaction as + // aborted in PostgreSQL and disallow further queries within it. + $this->rollback(); + $this->beginTransaction(); + continue; + } + + throw $e; + } + } + + return ''; + } + } + + /** + * Executes an application-level lock on the database. + * + * @return \PDOStatement The statement that needs to be executed later to release the lock + * + * @throws \DomainException When an unsupported PDO driver is used + * + * @todo implement missing advisory locks + * - for oci using DBMS_LOCK.REQUEST + * - for sqlsrv using sp_getapplock with LockOwner = Session + */ + private function doAdvisoryLock(string $sessionId): \PDOStatement + { + switch ($this->driver) { + case 'mysql': + // MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced. + $lockId = substr($sessionId, 0, 64); + // should we handle the return value? 0 on timeout, null on error + // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout + $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)'); + $stmt->bindValue(':key', $lockId, \PDO::PARAM_STR); + $stmt->execute(); + + $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)'); + $releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR); + + return $releaseStmt; + case 'pgsql': + // Obtaining an exclusive session level advisory lock requires an integer key. + // When session.sid_bits_per_character > 4, the session id can contain non-hex-characters. + // So we cannot just use hexdec(). + if (4 === \PHP_INT_SIZE) { + $sessionInt1 = $this->convertStringToInt($sessionId); + $sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4)); + + $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)'); + $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); + $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); + $stmt->execute(); + + $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)'); + $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); + $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); + } else { + $sessionBigInt = $this->convertStringToInt($sessionId); + + $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)'); + $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); + $stmt->execute(); + + $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)'); + $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); + } + + return $releaseStmt; + case 'sqlite': + throw new \DomainException('SQLite does not support advisory locks.'); + default: + throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver)); + } + } + + /** + * Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer. + * + * Keep in mind, PHP integers are signed. + */ + private function convertStringToInt(string $string): int + { + if (4 === \PHP_INT_SIZE) { + return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]); + } + + $int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]); + $int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]); + + return $int2 + ($int1 << 32); + } + + /** + * Return a locking or nonlocking SQL query to read session information. + * + * @throws \DomainException When an unsupported PDO driver is used + */ + private function getSelectSql(): string + { + if (self::LOCK_TRANSACTIONAL === $this->lockMode) { + $this->beginTransaction(); + + // selecting the time column should be removed in 6.0 + switch ($this->driver) { + case 'mysql': + case 'oci': + case 'pgsql': + return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE"; + case 'sqlsrv': + return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id"; + case 'sqlite': + // we already locked when starting transaction + break; + default: + throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver)); + } + } + + return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id"; + } + + /** + * Returns an insert statement supported by the database for writing session data. + */ + private function getInsertStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement + { + switch ($this->driver) { + case 'oci': + $data = fopen('php://memory', 'r+'); + fwrite($data, $sessionData); + rewind($data); + $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :expiry, :time) RETURNING $this->dataCol into :data"; + break; + default: + $data = $sessionData; + $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)"; + break; + } + + $stmt = $this->pdo->prepare($sql); + $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $stmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT); + $stmt->bindValue(':time', time(), \PDO::PARAM_INT); + + return $stmt; + } + + /** + * Returns an update statement supported by the database for writing session data. + */ + private function getUpdateStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement + { + switch ($this->driver) { + case 'oci': + $data = fopen('php://memory', 'r+'); + fwrite($data, $sessionData); + rewind($data); + $sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data"; + break; + default: + $data = $sessionData; + $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id"; + break; + } + + $stmt = $this->pdo->prepare($sql); + $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $stmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT); + $stmt->bindValue(':time', time(), \PDO::PARAM_INT); + + return $stmt; + } + + /** + * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data. + */ + private function getMergeStatement(string $sessionId, string $data, int $maxlifetime): ?\PDOStatement + { + switch (true) { + case 'mysql' === $this->driver: + $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ". + "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)"; + break; + case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): + // MERGE is only available since SQL Server 2008 and must be terminated by semicolon + // It also requires HOLDLOCK according to https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/ + $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ". + "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". + "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;"; + break; + case 'sqlite' === $this->driver: + $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)"; + break; + case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='): + $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ". + "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; + break; + default: + // MERGE is not supported with LOBs: https://oracle.com/technetwork/articles/fuecks-lobs-095315.html + return null; + } + + $mergeStmt = $this->pdo->prepare($mergeSql); + + if ('sqlsrv' === $this->driver) { + $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB); + $mergeStmt->bindValue(4, time() + $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT); + $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB); + $mergeStmt->bindValue(7, time() + $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT); + } else { + $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $mergeStmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); + } + + return $mergeStmt; + } + + /** + * Return a PDO instance. + * + * @return \PDO + */ + protected function getConnection() + { + if (null === $this->pdo) { + $this->connect($this->dsn ?: \ini_get('session.save_path')); + } + + return $this->pdo; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php new file mode 100644 index 0000000..31954e6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php @@ -0,0 +1,137 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +use Predis\Response\ErrorInterface; +use Symfony\Component\Cache\Traits\RedisClusterProxy; +use Symfony\Component\Cache\Traits\RedisProxy; + +/** + * Redis based session storage handler based on the Redis class + * provided by the PHP redis extension. + * + * @author Dalibor Karlović + */ +class RedisSessionHandler extends AbstractSessionHandler +{ + private $redis; + + /** + * @var string Key prefix for shared environments + */ + private $prefix; + + /** + * @var int Time to live in seconds + */ + private $ttl; + + /** + * List of available options: + * * prefix: The prefix to use for the keys in order to avoid collision on the Redis server + * * ttl: The time to live in seconds. + * + * @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis + * + * @throws \InvalidArgumentException When unsupported client or options are passed + */ + public function __construct($redis, array $options = []) + { + if ( + !$redis instanceof \Redis && + !$redis instanceof \RedisArray && + !$redis instanceof \RedisCluster && + !$redis instanceof \Predis\ClientInterface && + !$redis instanceof RedisProxy && + !$redis instanceof RedisClusterProxy + ) { + throw new \InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($redis))); + } + + if ($diff = array_diff(array_keys($options), ['prefix', 'ttl'])) { + throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff))); + } + + $this->redis = $redis; + $this->prefix = $options['prefix'] ?? 'sf_s'; + $this->ttl = $options['ttl'] ?? null; + } + + /** + * {@inheritdoc} + */ + protected function doRead(string $sessionId): string + { + return $this->redis->get($this->prefix.$sessionId) ?: ''; + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $sessionId, string $data): bool + { + $result = $this->redis->setEx($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')), $data); + + return $result && !$result instanceof ErrorInterface; + } + + /** + * {@inheritdoc} + */ + protected function doDestroy(string $sessionId): bool + { + static $unlink = true; + + if ($unlink) { + try { + $unlink = false !== $this->redis->unlink($this->prefix.$sessionId); + } catch (\Throwable $e) { + $unlink = false; + } + } + + if (!$unlink) { + $this->redis->del($this->prefix.$sessionId); + } + + return true; + } + + /** + * {@inheritdoc} + */ + #[\ReturnTypeWillChange] + public function close(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + return 0; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + return (bool) $this->redis->expire($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime'))); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php new file mode 100644 index 0000000..76e4373 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +use Doctrine\DBAL\Configuration; +use Doctrine\DBAL\DriverManager; +use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory; +use Doctrine\DBAL\Tools\DsnParser; +use Symfony\Component\Cache\Adapter\AbstractAdapter; +use Symfony\Component\Cache\Traits\RedisClusterProxy; +use Symfony\Component\Cache\Traits\RedisProxy; + +/** + * @author Nicolas Grekas + */ +class SessionHandlerFactory +{ + /** + * @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy|\Memcached|\PDO|string $connection Connection or DSN + */ + public static function createHandler($connection): AbstractSessionHandler + { + if (!\is_string($connection) && !\is_object($connection)) { + throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a string or a connection object, "%s" given.', __METHOD__, get_debug_type($connection))); + } + + if ($options = \is_string($connection) ? parse_url($connection) : false) { + parse_str($options['query'] ?? '', $options); + } + + switch (true) { + case $connection instanceof \Redis: + case $connection instanceof \RedisArray: + case $connection instanceof \RedisCluster: + case $connection instanceof \Predis\ClientInterface: + case $connection instanceof RedisProxy: + case $connection instanceof RedisClusterProxy: + return new RedisSessionHandler($connection); + + case $connection instanceof \Memcached: + return new MemcachedSessionHandler($connection); + + case $connection instanceof \PDO: + return new PdoSessionHandler($connection); + + case !\is_string($connection): + throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', get_debug_type($connection))); + case str_starts_with($connection, 'file://'): + $savePath = substr($connection, 7); + + return new StrictSessionHandler(new NativeFileSessionHandler('' === $savePath ? null : $savePath)); + + case str_starts_with($connection, 'redis:'): + case str_starts_with($connection, 'rediss:'): + case str_starts_with($connection, 'memcached:'): + if (!class_exists(AbstractAdapter::class)) { + throw new \InvalidArgumentException('Unsupported Redis or Memcached DSN. Try running "composer require symfony/cache".'); + } + $handlerClass = str_starts_with($connection, 'memcached:') ? MemcachedSessionHandler::class : RedisSessionHandler::class; + $connection = AbstractAdapter::createConnection($connection, ['lazy' => true]); + + return new $handlerClass($connection, array_intersect_key($options ?: [], ['prefix' => 1, 'ttl' => 1])); + + case str_starts_with($connection, 'pdo_oci://'): + if (!class_exists(DriverManager::class)) { + throw new \InvalidArgumentException('Unsupported PDO OCI DSN. Try running "composer require doctrine/dbal".'); + } + $connection[3] = '-'; + $params = class_exists(DsnParser::class) ? (new DsnParser())->parse($connection) : ['url' => $connection]; + $config = new Configuration(); + if (class_exists(DefaultSchemaManagerFactory::class)) { + $config->setSchemaManagerFactory(new DefaultSchemaManagerFactory()); + } + + $connection = DriverManager::getConnection($params, $config); + // The condition should be removed once support for DBAL <3.3 is dropped + $connection = method_exists($connection, 'getNativeConnection') ? $connection->getNativeConnection() : $connection->getWrappedConnection(); + // no break; + + case str_starts_with($connection, 'mssql://'): + case str_starts_with($connection, 'mysql://'): + case str_starts_with($connection, 'mysql2://'): + case str_starts_with($connection, 'pgsql://'): + case str_starts_with($connection, 'postgres://'): + case str_starts_with($connection, 'postgresql://'): + case str_starts_with($connection, 'sqlsrv://'): + case str_starts_with($connection, 'sqlite://'): + case str_starts_with($connection, 'sqlite3://'): + return new PdoSessionHandler($connection, $options ?: []); + } + + throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', $connection)); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php new file mode 100644 index 0000000..f7c385f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php @@ -0,0 +1,118 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Adds basic `SessionUpdateTimestampHandlerInterface` behaviors to another `SessionHandlerInterface`. + * + * @author Nicolas Grekas + */ +class StrictSessionHandler extends AbstractSessionHandler +{ + private $handler; + private $doDestroy; + + public function __construct(\SessionHandlerInterface $handler) + { + if ($handler instanceof \SessionUpdateTimestampHandlerInterface) { + throw new \LogicException(sprintf('"%s" is already an instance of "SessionUpdateTimestampHandlerInterface", you cannot wrap it with "%s".', get_debug_type($handler), self::class)); + } + + $this->handler = $handler; + } + + /** + * Returns true if this handler wraps an internal PHP session save handler using \SessionHandler. + * + * @internal + */ + public function isWrapper(): bool + { + return $this->handler instanceof \SessionHandler; + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + parent::open($savePath, $sessionName); + + return $this->handler->open($savePath, $sessionName); + } + + /** + * {@inheritdoc} + */ + protected function doRead(string $sessionId) + { + return $this->handler->read($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + return $this->write($sessionId, $data); + } + + /** + * {@inheritdoc} + */ + protected function doWrite(string $sessionId, string $data) + { + return $this->handler->write($sessionId, $data); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + $this->doDestroy = true; + $destroyed = parent::destroy($sessionId); + + return $this->doDestroy ? $this->doDestroy($sessionId) : $destroyed; + } + + /** + * {@inheritdoc} + */ + protected function doDestroy(string $sessionId) + { + $this->doDestroy = false; + + return $this->handler->destroy($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return $this->handler->close(); + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + return $this->handler->gc($maxlifetime); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MetadataBag.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MetadataBag.php new file mode 100644 index 0000000..3e10f6d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MetadataBag.php @@ -0,0 +1,167 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; + +/** + * Metadata container. + * + * Adds metadata to the session. + * + * @author Drak + */ +class MetadataBag implements SessionBagInterface +{ + public const CREATED = 'c'; + public const UPDATED = 'u'; + public const LIFETIME = 'l'; + + /** + * @var string + */ + private $name = '__metadata'; + + /** + * @var string + */ + private $storageKey; + + /** + * @var array + */ + protected $meta = [self::CREATED => 0, self::UPDATED => 0, self::LIFETIME => 0]; + + /** + * Unix timestamp. + * + * @var int + */ + private $lastUsed; + + /** + * @var int + */ + private $updateThreshold; + + /** + * @param string $storageKey The key used to store bag in the session + * @param int $updateThreshold The time to wait between two UPDATED updates + */ + public function __construct(string $storageKey = '_sf2_meta', int $updateThreshold = 0) + { + $this->storageKey = $storageKey; + $this->updateThreshold = $updateThreshold; + } + + /** + * {@inheritdoc} + */ + public function initialize(array &$array) + { + $this->meta = &$array; + + if (isset($array[self::CREATED])) { + $this->lastUsed = $this->meta[self::UPDATED]; + + $timeStamp = time(); + if ($timeStamp - $array[self::UPDATED] >= $this->updateThreshold) { + $this->meta[self::UPDATED] = $timeStamp; + } + } else { + $this->stampCreated(); + } + } + + /** + * Gets the lifetime that the session cookie was set with. + * + * @return int + */ + public function getLifetime() + { + return $this->meta[self::LIFETIME]; + } + + /** + * Stamps a new session's metadata. + * + * @param int|null $lifetime Sets the cookie lifetime for the session cookie. A null value + * will leave the system settings unchanged, 0 sets the cookie + * to expire with browser session. Time is in seconds, and is + * not a Unix timestamp. + */ + public function stampNew(?int $lifetime = null) + { + $this->stampCreated($lifetime); + } + + /** + * {@inheritdoc} + */ + public function getStorageKey() + { + return $this->storageKey; + } + + /** + * Gets the created timestamp metadata. + * + * @return int Unix timestamp + */ + public function getCreated() + { + return $this->meta[self::CREATED]; + } + + /** + * Gets the last used metadata. + * + * @return int Unix timestamp + */ + public function getLastUsed() + { + return $this->lastUsed; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + // nothing to do + return null; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + */ + public function setName(string $name) + { + $this->name = $name; + } + + private function stampCreated(?int $lifetime = null): void + { + $timeStamp = time(); + $this->meta[self::CREATED] = $this->meta[self::UPDATED] = $this->lastUsed = $timeStamp; + $this->meta[self::LIFETIME] = $lifetime ?? (int) \ini_get('session.cookie_lifetime'); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockArraySessionStorage.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockArraySessionStorage.php new file mode 100644 index 0000000..77bb38f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockArraySessionStorage.php @@ -0,0 +1,252 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; + +/** + * MockArraySessionStorage mocks the session for unit tests. + * + * No PHP session is actually started since a session can be initialized + * and shutdown only once per PHP execution cycle. + * + * When doing functional testing, you should use MockFileSessionStorage instead. + * + * @author Fabien Potencier + * @author Bulat Shakirzyanov + * @author Drak + */ +class MockArraySessionStorage implements SessionStorageInterface +{ + /** + * @var string + */ + protected $id = ''; + + /** + * @var string + */ + protected $name; + + /** + * @var bool + */ + protected $started = false; + + /** + * @var bool + */ + protected $closed = false; + + /** + * @var array + */ + protected $data = []; + + /** + * @var MetadataBag + */ + protected $metadataBag; + + /** + * @var array|SessionBagInterface[] + */ + protected $bags = []; + + public function __construct(string $name = 'MOCKSESSID', ?MetadataBag $metaBag = null) + { + $this->name = $name; + $this->setMetadataBag($metaBag); + } + + public function setSessionData(array $array) + { + $this->data = $array; + } + + /** + * {@inheritdoc} + */ + public function start() + { + if ($this->started) { + return true; + } + + if (empty($this->id)) { + $this->id = $this->generateId(); + } + + $this->loadSession(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function regenerate(bool $destroy = false, ?int $lifetime = null) + { + if (!$this->started) { + $this->start(); + } + + $this->metadataBag->stampNew($lifetime); + $this->id = $this->generateId(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function getId() + { + return $this->id; + } + + /** + * {@inheritdoc} + */ + public function setId(string $id) + { + if ($this->started) { + throw new \LogicException('Cannot set session ID after the session has started.'); + } + + $this->id = $id; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function setName(string $name) + { + $this->name = $name; + } + + /** + * {@inheritdoc} + */ + public function save() + { + if (!$this->started || $this->closed) { + throw new \RuntimeException('Trying to save a session that was not started yet or was already closed.'); + } + // nothing to do since we don't persist the session data + $this->closed = false; + $this->started = false; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + // clear out the bags + foreach ($this->bags as $bag) { + $bag->clear(); + } + + // clear out the session + $this->data = []; + + // reconnect the bags to the session + $this->loadSession(); + } + + /** + * {@inheritdoc} + */ + public function registerBag(SessionBagInterface $bag) + { + $this->bags[$bag->getName()] = $bag; + } + + /** + * {@inheritdoc} + */ + public function getBag(string $name) + { + if (!isset($this->bags[$name])) { + throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name)); + } + + if (!$this->started) { + $this->start(); + } + + return $this->bags[$name]; + } + + /** + * {@inheritdoc} + */ + public function isStarted() + { + return $this->started; + } + + public function setMetadataBag(?MetadataBag $bag = null) + { + if (null === $bag) { + $bag = new MetadataBag(); + } + + $this->metadataBag = $bag; + } + + /** + * Gets the MetadataBag. + * + * @return MetadataBag + */ + public function getMetadataBag() + { + return $this->metadataBag; + } + + /** + * Generates a session ID. + * + * This doesn't need to be particularly cryptographically secure since this is just + * a mock. + * + * @return string + */ + protected function generateId() + { + return hash('sha256', uniqid('ss_mock_', true)); + } + + protected function loadSession() + { + $bags = array_merge($this->bags, [$this->metadataBag]); + + foreach ($bags as $bag) { + $key = $bag->getStorageKey(); + $this->data[$key] = $this->data[$key] ?? []; + $bag->initialize($this->data[$key]); + } + + $this->started = true; + $this->closed = false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockFileSessionStorage.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockFileSessionStorage.php new file mode 100644 index 0000000..8aeb972 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockFileSessionStorage.php @@ -0,0 +1,160 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +/** + * MockFileSessionStorage is used to mock sessions for + * functional testing where you may need to persist session data + * across separate PHP processes. + * + * No PHP session is actually started since a session can be initialized + * and shutdown only once per PHP execution cycle and this class does + * not pollute any session related globals, including session_*() functions + * or session.* PHP ini directives. + * + * @author Drak + */ +class MockFileSessionStorage extends MockArraySessionStorage +{ + private $savePath; + + /** + * @param string|null $savePath Path of directory to save session files + */ + public function __construct(?string $savePath = null, string $name = 'MOCKSESSID', ?MetadataBag $metaBag = null) + { + if (null === $savePath) { + $savePath = sys_get_temp_dir(); + } + + if (!is_dir($savePath) && !@mkdir($savePath, 0777, true) && !is_dir($savePath)) { + throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s".', $savePath)); + } + + $this->savePath = $savePath; + + parent::__construct($name, $metaBag); + } + + /** + * {@inheritdoc} + */ + public function start() + { + if ($this->started) { + return true; + } + + if (!$this->id) { + $this->id = $this->generateId(); + } + + $this->read(); + + $this->started = true; + + return true; + } + + /** + * {@inheritdoc} + */ + public function regenerate(bool $destroy = false, ?int $lifetime = null) + { + if (!$this->started) { + $this->start(); + } + + if ($destroy) { + $this->destroy(); + } + + return parent::regenerate($destroy, $lifetime); + } + + /** + * {@inheritdoc} + */ + public function save() + { + if (!$this->started) { + throw new \RuntimeException('Trying to save a session that was not started yet or was already closed.'); + } + + $data = $this->data; + + foreach ($this->bags as $bag) { + if (empty($data[$key = $bag->getStorageKey()])) { + unset($data[$key]); + } + } + if ([$key = $this->metadataBag->getStorageKey()] === array_keys($data)) { + unset($data[$key]); + } + + try { + if ($data) { + $path = $this->getFilePath(); + $tmp = $path.bin2hex(random_bytes(6)); + file_put_contents($tmp, serialize($data)); + rename($tmp, $path); + } else { + $this->destroy(); + } + } finally { + $this->data = $data; + } + + // this is needed when the session object is re-used across multiple requests + // in functional tests. + $this->started = false; + } + + /** + * Deletes a session from persistent storage. + * Deliberately leaves session data in memory intact. + */ + private function destroy(): void + { + set_error_handler(static function () {}); + try { + unlink($this->getFilePath()); + } finally { + restore_error_handler(); + } + } + + /** + * Calculate path to file. + */ + private function getFilePath(): string + { + return $this->savePath.'/'.$this->id.'.mocksess'; + } + + /** + * Reads session from storage and loads session. + */ + private function read(): void + { + set_error_handler(static function () {}); + try { + $data = file_get_contents($this->getFilePath()); + } finally { + restore_error_handler(); + } + + $this->data = $data ? unserialize($data) : []; + + $this->loadSession(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockFileSessionStorageFactory.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockFileSessionStorageFactory.php new file mode 100644 index 0000000..900fa7c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/MockFileSessionStorageFactory.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Request; + +// Help opcache.preload discover always-needed symbols +class_exists(MockFileSessionStorage::class); + +/** + * @author Jérémy Derussé + */ +class MockFileSessionStorageFactory implements SessionStorageFactoryInterface +{ + private $savePath; + private $name; + private $metaBag; + + /** + * @see MockFileSessionStorage constructor. + */ + public function __construct(?string $savePath = null, string $name = 'MOCKSESSID', ?MetadataBag $metaBag = null) + { + $this->savePath = $savePath; + $this->name = $name; + $this->metaBag = $metaBag; + } + + public function createStorage(?Request $request): SessionStorageInterface + { + return new MockFileSessionStorage($this->savePath, $this->name, $this->metaBag); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php new file mode 100644 index 0000000..e7b42ed --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php @@ -0,0 +1,507 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; +use Symfony\Component\HttpFoundation\Session\SessionUtils; +use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler; +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; + +// Help opcache.preload discover always-needed symbols +class_exists(MetadataBag::class); +class_exists(StrictSessionHandler::class); +class_exists(SessionHandlerProxy::class); + +/** + * This provides a base class for session attribute storage. + * + * @author Drak + */ +class NativeSessionStorage implements SessionStorageInterface +{ + /** + * @var SessionBagInterface[] + */ + protected $bags = []; + + /** + * @var bool + */ + protected $started = false; + + /** + * @var bool + */ + protected $closed = false; + + /** + * @var AbstractProxy|\SessionHandlerInterface + */ + protected $saveHandler; + + /** + * @var MetadataBag + */ + protected $metadataBag; + + /** + * @var string|null + */ + private $emulateSameSite; + + /** + * Depending on how you want the storage driver to behave you probably + * want to override this constructor entirely. + * + * List of options for $options array with their defaults. + * + * @see https://php.net/session.configuration for options + * but we omit 'session.' from the beginning of the keys for convenience. + * + * ("auto_start", is not supported as it tells PHP to start a session before + * PHP starts to execute user-land code. Setting during runtime has no effect). + * + * cache_limiter, "" (use "0" to prevent headers from being sent entirely). + * cache_expire, "0" + * cookie_domain, "" + * cookie_httponly, "" + * cookie_lifetime, "0" + * cookie_path, "/" + * cookie_secure, "" + * cookie_samesite, null + * gc_divisor, "100" + * gc_maxlifetime, "1440" + * gc_probability, "1" + * lazy_write, "1" + * name, "PHPSESSID" + * referer_check, "" + * serialize_handler, "php" + * use_strict_mode, "1" + * use_cookies, "1" + * use_only_cookies, "1" + * use_trans_sid, "0" + * sid_length, "32" + * sid_bits_per_character, "5" + * trans_sid_hosts, $_SERVER['HTTP_HOST'] + * trans_sid_tags, "a=href,area=href,frame=src,form=" + * + * @param AbstractProxy|\SessionHandlerInterface|null $handler + */ + public function __construct(array $options = [], $handler = null, ?MetadataBag $metaBag = null) + { + if (!\extension_loaded('session')) { + throw new \LogicException('PHP extension "session" is required.'); + } + + $options += [ + 'cache_limiter' => '', + 'cache_expire' => 0, + 'use_cookies' => 1, + 'lazy_write' => 1, + 'use_strict_mode' => 1, + ]; + + session_register_shutdown(); + + $this->setMetadataBag($metaBag); + $this->setOptions($options); + $this->setSaveHandler($handler); + } + + /** + * Gets the save handler instance. + * + * @return AbstractProxy|\SessionHandlerInterface + */ + public function getSaveHandler() + { + return $this->saveHandler; + } + + /** + * {@inheritdoc} + */ + public function start() + { + if ($this->started) { + return true; + } + + if (\PHP_SESSION_ACTIVE === session_status()) { + throw new \RuntimeException('Failed to start the session: already started by PHP.'); + } + + if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) { + throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line)); + } + + $sessionId = $_COOKIE[session_name()] ?? null; + /* + * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`. + * + * ---------- Part 1 + * + * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6. + * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character. + * Allowed values are integers such as: + * - 4 for range `a-f0-9` + * - 5 for range `a-v0-9` + * - 6 for range `a-zA-Z0-9,-` + * + * ---------- Part 2 + * + * The part `{22,250}` is related to the PHP ini directive `session.sid_length`. + * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length. + * Allowed values are integers between 22 and 256, but we use 250 for the max. + * + * Where does the 250 come from? + * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255. + * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250. + * + * ---------- Conclusion + * + * The parts 1 and 2 prevent the warning below: + * `PHP Warning: SessionHandler::read(): Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, "-", and "," characters are allowed.` + * + * The part 2 prevents the warning below: + * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).` + */ + if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,250}$/', $sessionId)) { + // the session ID in the header is invalid, create a new one + session_id(session_create_id()); + } + + // ok to try and start the session + if (!session_start()) { + throw new \RuntimeException('Failed to start the session.'); + } + + if (null !== $this->emulateSameSite) { + $originalCookie = SessionUtils::popSessionCookie(session_name(), session_id()); + if (null !== $originalCookie) { + header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false); + } + } + + $this->loadSession(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function getId() + { + return $this->saveHandler->getId(); + } + + /** + * {@inheritdoc} + */ + public function setId(string $id) + { + $this->saveHandler->setId($id); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->saveHandler->getName(); + } + + /** + * {@inheritdoc} + */ + public function setName(string $name) + { + $this->saveHandler->setName($name); + } + + /** + * {@inheritdoc} + */ + public function regenerate(bool $destroy = false, ?int $lifetime = null) + { + // Cannot regenerate the session ID for non-active sessions. + if (\PHP_SESSION_ACTIVE !== session_status()) { + return false; + } + + if (headers_sent()) { + return false; + } + + if (null !== $lifetime && $lifetime != \ini_get('session.cookie_lifetime')) { + $this->save(); + ini_set('session.cookie_lifetime', $lifetime); + $this->start(); + } + + if ($destroy) { + $this->metadataBag->stampNew(); + } + + $isRegenerated = session_regenerate_id($destroy); + + if (null !== $this->emulateSameSite) { + $originalCookie = SessionUtils::popSessionCookie(session_name(), session_id()); + if (null !== $originalCookie) { + header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false); + } + } + + return $isRegenerated; + } + + /** + * {@inheritdoc} + */ + public function save() + { + // Store a copy so we can restore the bags in case the session was not left empty + $session = $_SESSION; + + foreach ($this->bags as $bag) { + if (empty($_SESSION[$key = $bag->getStorageKey()])) { + unset($_SESSION[$key]); + } + } + if ($_SESSION && [$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) { + unset($_SESSION[$key]); + } + + // Register error handler to add information about the current save handler + $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) { + if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) { + $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler; + $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler)); + } + + return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false; + }); + + try { + session_write_close(); + } finally { + restore_error_handler(); + + // Restore only if not empty + if ($_SESSION) { + $_SESSION = $session; + } + } + + $this->closed = true; + $this->started = false; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + // clear out the bags + foreach ($this->bags as $bag) { + $bag->clear(); + } + + // clear out the session + $_SESSION = []; + + // reconnect the bags to the session + $this->loadSession(); + } + + /** + * {@inheritdoc} + */ + public function registerBag(SessionBagInterface $bag) + { + if ($this->started) { + throw new \LogicException('Cannot register a bag when the session is already started.'); + } + + $this->bags[$bag->getName()] = $bag; + } + + /** + * {@inheritdoc} + */ + public function getBag(string $name) + { + if (!isset($this->bags[$name])) { + throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name)); + } + + if (!$this->started && $this->saveHandler->isActive()) { + $this->loadSession(); + } elseif (!$this->started) { + $this->start(); + } + + return $this->bags[$name]; + } + + public function setMetadataBag(?MetadataBag $metaBag = null) + { + if (null === $metaBag) { + $metaBag = new MetadataBag(); + } + + $this->metadataBag = $metaBag; + } + + /** + * Gets the MetadataBag. + * + * @return MetadataBag + */ + public function getMetadataBag() + { + return $this->metadataBag; + } + + /** + * {@inheritdoc} + */ + public function isStarted() + { + return $this->started; + } + + /** + * Sets session.* ini variables. + * + * For convenience we omit 'session.' from the beginning of the keys. + * Explicitly ignores other ini keys. + * + * @param array $options Session ini directives [key => value] + * + * @see https://php.net/session.configuration + */ + public function setOptions(array $options) + { + if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) { + return; + } + + $validOptions = array_flip([ + 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly', + 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'cookie_samesite', + 'gc_divisor', 'gc_maxlifetime', 'gc_probability', + 'lazy_write', 'name', 'referer_check', + 'serialize_handler', 'use_strict_mode', 'use_cookies', + 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled', + 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name', + 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags', + 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', + ]); + + foreach ($options as $key => $value) { + if (isset($validOptions[$key])) { + if (str_starts_with($key, 'upload_progress.')) { + trigger_deprecation('symfony/http-foundation', '5.4', 'Support for the "%s" session option is deprecated. The settings prefixed with "session.upload_progress." can not be changed at runtime.', $key); + continue; + } + if ('url_rewriter.tags' === $key) { + trigger_deprecation('symfony/http-foundation', '5.4', 'Support for the "%s" session option is deprecated. Use "trans_sid_tags" instead.', $key); + } + if ('cookie_samesite' === $key && \PHP_VERSION_ID < 70300) { + // PHP < 7.3 does not support same_site cookies. We will emulate it in + // the start() method instead. + $this->emulateSameSite = $value; + continue; + } + if ('cookie_secure' === $key && 'auto' === $value) { + continue; + } + ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value); + } + } + } + + /** + * Registers session save handler as a PHP session handler. + * + * To use internal PHP session save handlers, override this method using ini_set with + * session.save_handler and session.save_path e.g. + * + * ini_set('session.save_handler', 'files'); + * ini_set('session.save_path', '/tmp'); + * + * or pass in a \SessionHandler instance which configures session.save_handler in the + * constructor, for a template see NativeFileSessionHandler. + * + * @see https://php.net/session-set-save-handler + * @see https://php.net/sessionhandlerinterface + * @see https://php.net/sessionhandler + * + * @param AbstractProxy|\SessionHandlerInterface|null $saveHandler + * + * @throws \InvalidArgumentException + */ + public function setSaveHandler($saveHandler = null) + { + if (!$saveHandler instanceof AbstractProxy + && !$saveHandler instanceof \SessionHandlerInterface + && null !== $saveHandler + ) { + throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.'); + } + + // Wrap $saveHandler in proxy and prevent double wrapping of proxy + if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) { + $saveHandler = new SessionHandlerProxy($saveHandler); + } elseif (!$saveHandler instanceof AbstractProxy) { + $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler())); + } + $this->saveHandler = $saveHandler; + + if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) { + return; + } + + if ($this->saveHandler instanceof SessionHandlerProxy) { + session_set_save_handler($this->saveHandler, false); + } + } + + /** + * Load the session with attributes. + * + * After starting the session, PHP retrieves the session from whatever handlers + * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()). + * PHP takes the return value from the read() handler, unserializes it + * and populates $_SESSION with the result automatically. + */ + protected function loadSession(?array &$session = null) + { + if (null === $session) { + $session = &$_SESSION; + } + + $bags = array_merge($this->bags, [$this->metadataBag]); + + foreach ($bags as $bag) { + $key = $bag->getStorageKey(); + $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : []; + $bag->initialize($session[$key]); + } + + $this->started = true; + $this->closed = false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorageFactory.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorageFactory.php new file mode 100644 index 0000000..48e6526 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorageFactory.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\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Request; + +// Help opcache.preload discover always-needed symbols +class_exists(NativeSessionStorage::class); + +/** + * @author Jérémy Derussé + */ +class NativeSessionStorageFactory implements SessionStorageFactoryInterface +{ + private $options; + private $handler; + private $metaBag; + private $secure; + + /** + * @see NativeSessionStorage constructor. + */ + public function __construct(array $options = [], $handler = null, ?MetadataBag $metaBag = null, bool $secure = false) + { + $this->options = $options; + $this->handler = $handler; + $this->metaBag = $metaBag; + $this->secure = $secure; + } + + public function createStorage(?Request $request): SessionStorageInterface + { + $storage = new NativeSessionStorage($this->options, $this->handler, $this->metaBag); + if ($this->secure && $request && $request->isSecure()) { + $storage->setOptions(['cookie_secure' => true]); + } + + return $storage; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/PhpBridgeSessionStorage.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/PhpBridgeSessionStorage.php new file mode 100644 index 0000000..855d5e1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/PhpBridgeSessionStorage.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; + +/** + * Allows session to be started by PHP and managed by Symfony. + * + * @author Drak + */ +class PhpBridgeSessionStorage extends NativeSessionStorage +{ + /** + * @param AbstractProxy|\SessionHandlerInterface|null $handler + */ + public function __construct($handler = null, ?MetadataBag $metaBag = null) + { + if (!\extension_loaded('session')) { + throw new \LogicException('PHP extension "session" is required.'); + } + + $this->setMetadataBag($metaBag); + $this->setSaveHandler($handler); + } + + /** + * {@inheritdoc} + */ + public function start() + { + if ($this->started) { + return true; + } + + $this->loadSession(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function clear() + { + // clear out the bags and nothing else that may be set + // since the purpose of this driver is to share a handler + foreach ($this->bags as $bag) { + $bag->clear(); + } + + // reconnect the bags to the session + $this->loadSession(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/PhpBridgeSessionStorageFactory.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/PhpBridgeSessionStorageFactory.php new file mode 100644 index 0000000..aa93263 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/PhpBridgeSessionStorageFactory.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Request; + +// Help opcache.preload discover always-needed symbols +class_exists(PhpBridgeSessionStorage::class); + +/** + * @author Jérémy Derussé + */ +class PhpBridgeSessionStorageFactory implements SessionStorageFactoryInterface +{ + private $handler; + private $metaBag; + private $secure; + + /** + * @see PhpBridgeSessionStorage constructor. + */ + public function __construct($handler = null, ?MetadataBag $metaBag = null, bool $secure = false) + { + $this->handler = $handler; + $this->metaBag = $metaBag; + $this->secure = $secure; + } + + public function createStorage(?Request $request): SessionStorageInterface + { + $storage = new PhpBridgeSessionStorage($this->handler, $this->metaBag); + if ($this->secure && $request && $request->isSecure()) { + $storage->setOptions(['cookie_secure' => true]); + } + + return $storage; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php new file mode 100644 index 0000000..edd04df --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php @@ -0,0 +1,118 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; + +/** + * @author Drak + */ +abstract class AbstractProxy +{ + /** + * Flag if handler wraps an internal PHP session handler (using \SessionHandler). + * + * @var bool + */ + protected $wrapper = false; + + /** + * @var string + */ + protected $saveHandlerName; + + /** + * Gets the session.save_handler name. + * + * @return string|null + */ + public function getSaveHandlerName() + { + return $this->saveHandlerName; + } + + /** + * Is this proxy handler and instance of \SessionHandlerInterface. + * + * @return bool + */ + public function isSessionHandlerInterface() + { + return $this instanceof \SessionHandlerInterface; + } + + /** + * Returns true if this handler wraps an internal PHP session save handler using \SessionHandler. + * + * @return bool + */ + public function isWrapper() + { + return $this->wrapper; + } + + /** + * Has a session started? + * + * @return bool + */ + public function isActive() + { + return \PHP_SESSION_ACTIVE === session_status(); + } + + /** + * Gets the session ID. + * + * @return string + */ + public function getId() + { + return session_id(); + } + + /** + * Sets the session ID. + * + * @throws \LogicException + */ + public function setId(string $id) + { + if ($this->isActive()) { + throw new \LogicException('Cannot change the ID of an active session.'); + } + + session_id($id); + } + + /** + * Gets the session name. + * + * @return string + */ + public function getName() + { + return session_name(); + } + + /** + * Sets the session name. + * + * @throws \LogicException + */ + public function setName(string $name) + { + if ($this->isActive()) { + throw new \LogicException('Cannot change the name of an active session.'); + } + + session_name($name); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php new file mode 100644 index 0000000..0defa4a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; + +use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler; + +/** + * @author Drak + */ +class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface +{ + protected $handler; + + public function __construct(\SessionHandlerInterface $handler) + { + $this->handler = $handler; + $this->wrapper = $handler instanceof \SessionHandler; + $this->saveHandlerName = $this->wrapper || ($handler instanceof StrictSessionHandler && $handler->isWrapper()) ? \ini_get('session.save_handler') : 'user'; + } + + /** + * @return \SessionHandlerInterface + */ + public function getHandler() + { + return $this->handler; + } + + // \SessionHandlerInterface + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function open($savePath, $sessionName) + { + return $this->handler->open($savePath, $sessionName); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function close() + { + return $this->handler->close(); + } + + /** + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($sessionId) + { + return $this->handler->read($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function write($sessionId, $data) + { + return $this->handler->write($sessionId, $data); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function destroy($sessionId) + { + return $this->handler->destroy($sessionId); + } + + /** + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($maxlifetime) + { + return $this->handler->gc($maxlifetime); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function validateId($sessionId) + { + return !$this->handler instanceof \SessionUpdateTimestampHandlerInterface || $this->handler->validateId($sessionId); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function updateTimestamp($sessionId, $data) + { + return $this->handler instanceof \SessionUpdateTimestampHandlerInterface ? $this->handler->updateTimestamp($sessionId, $data) : $this->write($sessionId, $data); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/ServiceSessionFactory.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/ServiceSessionFactory.php new file mode 100644 index 0000000..d17c60a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/ServiceSessionFactory.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\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Request; + +/** + * @author Jérémy Derussé + * + * @internal to be removed in Symfony 6 + */ +final class ServiceSessionFactory implements SessionStorageFactoryInterface +{ + private $storage; + + public function __construct(SessionStorageInterface $storage) + { + $this->storage = $storage; + } + + public function createStorage(?Request $request): SessionStorageInterface + { + if ($this->storage instanceof NativeSessionStorage && $request && $request->isSecure()) { + $this->storage->setOptions(['cookie_secure' => true]); + } + + return $this->storage; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/SessionStorageFactoryInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/SessionStorageFactoryInterface.php new file mode 100644 index 0000000..d03f0da --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/SessionStorageFactoryInterface.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Request; + +/** + * @author Jérémy Derussé + */ +interface SessionStorageFactoryInterface +{ + /** + * Creates a new instance of SessionStorageInterface. + */ + public function createStorage(?Request $request): SessionStorageInterface; +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/SessionStorageInterface.php b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/SessionStorageInterface.php new file mode 100644 index 0000000..70b7c6a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Session/Storage/SessionStorageInterface.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage; + +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; + +/** + * StorageInterface. + * + * @author Fabien Potencier + * @author Drak + */ +interface SessionStorageInterface +{ + /** + * Starts the session. + * + * @return bool + * + * @throws \RuntimeException if something goes wrong starting the session + */ + public function start(); + + /** + * Checks if the session is started. + * + * @return bool + */ + public function isStarted(); + + /** + * Returns the session ID. + * + * @return string + */ + public function getId(); + + /** + * Sets the session ID. + */ + public function setId(string $id); + + /** + * Returns the session name. + * + * @return string + */ + public function getName(); + + /** + * Sets the session name. + */ + public function setName(string $name); + + /** + * Regenerates id that represents this storage. + * + * This method must invoke session_regenerate_id($destroy) unless + * this interface is used for a storage object designed for unit + * or functional testing where a real PHP session would interfere + * with testing. + * + * Note regenerate+destroy should not clear the session data in memory + * only delete the session data from persistent storage. + * + * Care: When regenerating the session ID no locking is involved in PHP's + * session design. See https://bugs.php.net/61470 for a discussion. + * So you must make sure the regenerated session is saved BEFORE sending the + * headers with the new ID. Symfony's HttpKernel offers a listener for this. + * See Symfony\Component\HttpKernel\EventListener\SaveSessionListener. + * Otherwise session data could get lost again for concurrent requests with the + * new ID. One result could be that you get logged out after just logging in. + * + * @param bool $destroy Destroy session when regenerating? + * @param int|null $lifetime Sets the cookie lifetime for the session cookie. A null value + * will leave the system settings unchanged, 0 sets the cookie + * to expire with browser session. Time is in seconds, and is + * not a Unix timestamp. + * + * @return bool + * + * @throws \RuntimeException If an error occurs while regenerating this storage + */ + public function regenerate(bool $destroy = false, ?int $lifetime = null); + + /** + * Force the session to be saved and closed. + * + * This method must invoke session_write_close() unless this interface is + * used for a storage object design for unit or functional testing where + * a real PHP session would interfere with testing, in which case + * it should actually persist the session data if required. + * + * @throws \RuntimeException if the session is saved without being started, or if the session + * is already closed + */ + public function save(); + + /** + * Clear all session data in memory. + */ + public function clear(); + + /** + * Gets a SessionBagInterface by name. + * + * @return SessionBagInterface + * + * @throws \InvalidArgumentException If the bag does not exist + */ + public function getBag(string $name); + + /** + * Registers a SessionBagInterface for use. + */ + public function registerBag(SessionBagInterface $bag); + + /** + * @return MetadataBag + */ + public function getMetadataBag(); +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/StreamedResponse.php b/php/libraries/composer/vendor/symfony/http-foundation/StreamedResponse.php new file mode 100644 index 0000000..b42330d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/StreamedResponse.php @@ -0,0 +1,139 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +/** + * StreamedResponse represents a streamed HTTP response. + * + * A StreamedResponse uses a callback for its content. + * + * The callback should use the standard PHP functions like echo + * to stream the response back to the client. The flush() function + * can also be used if needed. + * + * @see flush() + * + * @author Fabien Potencier + */ +class StreamedResponse extends Response +{ + protected $callback; + protected $streamed; + private $headersSent; + + public function __construct(?callable $callback = null, int $status = 200, array $headers = []) + { + parent::__construct(null, $status, $headers); + + if (null !== $callback) { + $this->setCallback($callback); + } + $this->streamed = false; + $this->headersSent = false; + } + + /** + * Factory method for chainability. + * + * @param callable|null $callback A valid PHP callback or null to set it later + * + * @return static + * + * @deprecated since Symfony 5.1, use __construct() instead. + */ + public static function create($callback = null, int $status = 200, array $headers = []) + { + trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class); + + return new static($callback, $status, $headers); + } + + /** + * Sets the PHP callback associated with this Response. + * + * @return $this + */ + public function setCallback(callable $callback) + { + $this->callback = $callback; + + return $this; + } + + /** + * {@inheritdoc} + * + * This method only sends the headers once. + * + * @return $this + */ + public function sendHeaders() + { + if ($this->headersSent) { + return $this; + } + + $this->headersSent = true; + + return parent::sendHeaders(); + } + + /** + * {@inheritdoc} + * + * This method only sends the content once. + * + * @return $this + */ + public function sendContent() + { + if ($this->streamed) { + return $this; + } + + $this->streamed = true; + + if (null === $this->callback) { + throw new \LogicException('The Response callback must not be null.'); + } + + ($this->callback)(); + + return $this; + } + + /** + * {@inheritdoc} + * + * @return $this + * + * @throws \LogicException when the content is not null + */ + public function setContent(?string $content) + { + if (null !== $content) { + throw new \LogicException('The content cannot be set on a StreamedResponse instance.'); + } + + $this->streamed = true; + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getContent() + { + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/RequestAttributeValueSame.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/RequestAttributeValueSame.php new file mode 100644 index 0000000..cb216ea --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/RequestAttributeValueSame.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Request; + +final class RequestAttributeValueSame extends Constraint +{ + private $name; + private $value; + + public function __construct(string $name, string $value) + { + $this->name = $name; + $this->value = $value; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('has attribute "%s" with value "%s"', $this->name, $this->value); + } + + /** + * @param Request $request + * + * {@inheritdoc} + */ + protected function matches($request): bool + { + return $this->value === $request->attributes->get($this->name); + } + + /** + * @param Request $request + * + * {@inheritdoc} + */ + protected function failureDescription($request): string + { + return 'the Request '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseCookieValueSame.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseCookieValueSame.php new file mode 100644 index 0000000..939925b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseCookieValueSame.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Cookie; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseCookieValueSame extends Constraint +{ + private $name; + private $value; + private $path; + private $domain; + + public function __construct(string $name, string $value, string $path = '/', ?string $domain = null) + { + $this->name = $name; + $this->value = $value; + $this->path = $path; + $this->domain = $domain; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + $str = sprintf('has cookie "%s"', $this->name); + if ('/' !== $this->path) { + $str .= sprintf(' with path "%s"', $this->path); + } + if ($this->domain) { + $str .= sprintf(' for domain "%s"', $this->domain); + } + $str .= sprintf(' with value "%s"', $this->value); + + return $str; + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + $cookie = $this->getCookie($response); + if (!$cookie) { + return false; + } + + return $this->value === (string) $cookie->getValue(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } + + protected function getCookie(Response $response): ?Cookie + { + $cookies = $response->headers->getCookies(); + + $filteredCookies = array_filter($cookies, function (Cookie $cookie) { + return $cookie->getName() === $this->name && $cookie->getPath() === $this->path && $cookie->getDomain() === $this->domain; + }); + + return reset($filteredCookies) ?: null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseFormatSame.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseFormatSame.php new file mode 100644 index 0000000..f73aedf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseFormatSame.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Asserts that the response is in the given format. + * + * @author Kévin Dunglas + */ +final class ResponseFormatSame extends Constraint +{ + private $request; + private $format; + + public function __construct(Request $request, ?string $format) + { + $this->request = $request; + $this->format = $format; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return 'format is '.($this->format ?? 'null'); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return $this->format === $this->request->getFormat($response->headers->get('Content-Type')); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function additionalFailureDescription($response): string + { + return (string) $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHasCookie.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHasCookie.php new file mode 100644 index 0000000..9d6e58c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHasCookie.php @@ -0,0 +1,77 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Cookie; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseHasCookie extends Constraint +{ + private $name; + private $path; + private $domain; + + public function __construct(string $name, string $path = '/', ?string $domain = null) + { + $this->name = $name; + $this->path = $path; + $this->domain = $domain; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + $str = sprintf('has cookie "%s"', $this->name); + if ('/' !== $this->path) { + $str .= sprintf(' with path "%s"', $this->path); + } + if ($this->domain) { + $str .= sprintf(' for domain "%s"', $this->domain); + } + + return $str; + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return null !== $this->getCookie($response); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } + + private function getCookie(Response $response): ?Cookie + { + $cookies = $response->headers->getCookies(); + + $filteredCookies = array_filter($cookies, function (Cookie $cookie) { + return $cookie->getName() === $this->name && $cookie->getPath() === $this->path && $cookie->getDomain() === $this->domain; + }); + + return reset($filteredCookies) ?: null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHasHeader.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHasHeader.php new file mode 100644 index 0000000..68ad827 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHasHeader.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseHasHeader extends Constraint +{ + private $headerName; + + public function __construct(string $headerName) + { + $this->headerName = $headerName; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('has header "%s"', $this->headerName); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return $response->headers->has($this->headerName); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHeaderSame.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHeaderSame.php new file mode 100644 index 0000000..a27d0c7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseHeaderSame.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseHeaderSame extends Constraint +{ + private $headerName; + private $expectedValue; + + public function __construct(string $headerName, string $expectedValue) + { + $this->headerName = $headerName; + $this->expectedValue = $expectedValue; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('has header "%s" with value "%s"', $this->headerName, $this->expectedValue); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return $this->expectedValue === $response->headers->get($this->headerName, null); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsRedirected.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsRedirected.php new file mode 100644 index 0000000..8c4b883 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsRedirected.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseIsRedirected extends Constraint +{ + /** + * {@inheritdoc} + */ + public function toString(): string + { + return 'is redirected'; + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return $response->isRedirect(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function additionalFailureDescription($response): string + { + return (string) $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsSuccessful.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsSuccessful.php new file mode 100644 index 0000000..9c66558 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsSuccessful.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseIsSuccessful extends Constraint +{ + /** + * {@inheritdoc} + */ + public function toString(): string + { + return 'is successful'; + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return $response->isSuccessful(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function additionalFailureDescription($response): string + { + return (string) $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsUnprocessable.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsUnprocessable.php new file mode 100644 index 0000000..880c781 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseIsUnprocessable.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseIsUnprocessable extends Constraint +{ + /** + * {@inheritdoc} + */ + public function toString(): string + { + return 'is unprocessable'; + } + + /** + * @param Response $other + * + * {@inheritdoc} + */ + protected function matches($other): bool + { + return Response::HTTP_UNPROCESSABLE_ENTITY === $other->getStatusCode(); + } + + /** + * @param Response $other + * + * {@inheritdoc} + */ + protected function failureDescription($other): string + { + return 'the Response '.$this->toString(); + } + + /** + * @param Response $other + * + * {@inheritdoc} + */ + protected function additionalFailureDescription($other): string + { + return (string) $other; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseStatusCodeSame.php b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseStatusCodeSame.php new file mode 100644 index 0000000..72bb000 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/Test/Constraint/ResponseStatusCodeSame.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\HttpFoundation\Response; + +final class ResponseStatusCodeSame extends Constraint +{ + private $statusCode; + + public function __construct(int $statusCode) + { + $this->statusCode = $statusCode; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return 'status code is '.$this->statusCode; + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function matches($response): bool + { + return $this->statusCode === $response->getStatusCode(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function failureDescription($response): string + { + return 'the Response '.$this->toString(); + } + + /** + * @param Response $response + * + * {@inheritdoc} + */ + protected function additionalFailureDescription($response): string + { + return (string) $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/UrlHelper.php b/php/libraries/composer/vendor/symfony/http-foundation/UrlHelper.php new file mode 100644 index 0000000..9065994 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/UrlHelper.php @@ -0,0 +1,118 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation; + +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\RequestContextAwareInterface; + +/** + * A helper service for manipulating URLs within and outside the request scope. + * + * @author Valentin Udaltsov + */ +final class UrlHelper +{ + private $requestStack; + private $requestContext; + + /** + * @param RequestContextAwareInterface|RequestContext|null $requestContext + */ + public function __construct(RequestStack $requestStack, $requestContext = null) + { + if (null !== $requestContext && !$requestContext instanceof RequestContext && !$requestContext instanceof RequestContextAwareInterface) { + throw new \TypeError(__METHOD__.': Argument #2 ($requestContext) must of type Symfony\Component\Routing\RequestContextAwareInterface|Symfony\Component\Routing\RequestContext|null, '.get_debug_type($requestContext).' given.'); + } + + $this->requestStack = $requestStack; + $this->requestContext = $requestContext; + } + + public function getAbsoluteUrl(string $path): string + { + if (str_contains($path, '://') || '//' === substr($path, 0, 2)) { + return $path; + } + + if (null === $request = $this->requestStack->getMainRequest()) { + return $this->getAbsoluteUrlFromContext($path); + } + + if ('#' === $path[0]) { + $path = $request->getRequestUri().$path; + } elseif ('?' === $path[0]) { + $path = $request->getPathInfo().$path; + } + + if (!$path || '/' !== $path[0]) { + $prefix = $request->getPathInfo(); + $last = \strlen($prefix) - 1; + if ($last !== $pos = strrpos($prefix, '/')) { + $prefix = substr($prefix, 0, $pos).'/'; + } + + return $request->getUriForPath($prefix.$path); + } + + return $request->getSchemeAndHttpHost().$path; + } + + public function getRelativePath(string $path): string + { + if (str_contains($path, '://') || '//' === substr($path, 0, 2)) { + return $path; + } + + if (null === $request = $this->requestStack->getMainRequest()) { + return $path; + } + + return $request->getRelativeUriForPath($path); + } + + private function getAbsoluteUrlFromContext(string $path): string + { + if (null === $context = $this->requestContext) { + return $path; + } + + if ($context instanceof RequestContextAwareInterface) { + $context = $context->getContext(); + } + + if ('' === $host = $context->getHost()) { + return $path; + } + + $scheme = $context->getScheme(); + $port = ''; + + if ('http' === $scheme && 80 !== $context->getHttpPort()) { + $port = ':'.$context->getHttpPort(); + } elseif ('https' === $scheme && 443 !== $context->getHttpsPort()) { + $port = ':'.$context->getHttpsPort(); + } + + if ('#' === $path[0]) { + $queryString = $context->getQueryString(); + $path = $context->getPathInfo().($queryString ? '?'.$queryString : '').$path; + } elseif ('?' === $path[0]) { + $path = $context->getPathInfo().$path; + } + + if ('/' !== $path[0]) { + $path = rtrim($context->getBaseUrl(), '/').'/'.$path; + } + + return $scheme.'://'.$host.$port.$path; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-foundation/composer.json b/php/libraries/composer/vendor/symfony/http-foundation/composer.json new file mode 100644 index 0000000..cb8d59f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-foundation/composer.json @@ -0,0 +1,43 @@ +{ + "name": "symfony/http-foundation", + "type": "library", + "description": "Defines an object-oriented layer for the HTTP specification", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "predis/predis": "~1.0", + "symfony/cache": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/http-kernel": "^5.4.12|^6.0.12|^6.1.4", + "symfony/mime": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/rate-limiter": "^5.2|^6.0" + }, + "suggest" : { + "symfony/mime": "To use the file extension guesser" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\HttpFoundation\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Attribute/ArgumentInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Attribute/ArgumentInterface.php new file mode 100644 index 0000000..78769f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Attribute/ArgumentInterface.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Attribute; + +trigger_deprecation('symfony/http-kernel', '5.3', 'The "%s" interface is deprecated.', ArgumentInterface::class); + +/** + * Marker interface for controller argument attributes. + * + * @deprecated since Symfony 5.3 + */ +interface ArgumentInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Attribute/AsController.php b/php/libraries/composer/vendor/symfony/http-kernel/Attribute/AsController.php new file mode 100644 index 0000000..ef37104 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Attribute/AsController.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Attribute; + +/** + * Service tag to autoconfigure controllers. + */ +#[\Attribute(\Attribute::TARGET_CLASS)] +class AsController +{ + public function __construct() + { + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Bundle/Bundle.php b/php/libraries/composer/vendor/symfony/http-kernel/Bundle/Bundle.php new file mode 100644 index 0000000..54a1d10 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Bundle/Bundle.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\HttpKernel\Bundle; + +use Symfony\Component\Console\Application; +use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\ContainerAwareTrait; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; + +/** + * An implementation of BundleInterface that adds a few conventions for DependencyInjection extensions. + * + * @author Fabien Potencier + */ +abstract class Bundle implements BundleInterface +{ + use ContainerAwareTrait; + + protected $name; + protected $extension; + protected $path; + private $namespace; + + /** + * {@inheritdoc} + */ + public function boot() + { + } + + /** + * {@inheritdoc} + */ + public function shutdown() + { + } + + /** + * {@inheritdoc} + * + * This method can be overridden to register compilation passes, + * other extensions, ... + */ + public function build(ContainerBuilder $container) + { + } + + /** + * Returns the bundle's container extension. + * + * @return ExtensionInterface|null + * + * @throws \LogicException + */ + public function getContainerExtension() + { + if (null === $this->extension) { + $extension = $this->createContainerExtension(); + + if (null !== $extension) { + if (!$extension instanceof ExtensionInterface) { + throw new \LogicException(sprintf('Extension "%s" must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface.', get_debug_type($extension))); + } + + // check naming convention + $basename = preg_replace('/Bundle$/', '', $this->getName()); + $expectedAlias = Container::underscore($basename); + + if ($expectedAlias != $extension->getAlias()) { + throw new \LogicException(sprintf('Users will expect the alias of the default extension of a bundle to be the underscored version of the bundle name ("%s"). You can override "Bundle::getContainerExtension()" if you want to use "%s" or another alias.', $expectedAlias, $extension->getAlias())); + } + + $this->extension = $extension; + } else { + $this->extension = false; + } + } + + return $this->extension ?: null; + } + + /** + * {@inheritdoc} + */ + public function getNamespace() + { + if (null === $this->namespace) { + $this->parseClassName(); + } + + return $this->namespace; + } + + /** + * {@inheritdoc} + */ + public function getPath() + { + if (null === $this->path) { + $reflected = new \ReflectionObject($this); + $this->path = \dirname($reflected->getFileName()); + } + + return $this->path; + } + + /** + * Returns the bundle name (the class short name). + */ + final public function getName(): string + { + if (null === $this->name) { + $this->parseClassName(); + } + + return $this->name; + } + + public function registerCommands(Application $application) + { + } + + /** + * Returns the bundle's container extension class. + * + * @return string + */ + protected function getContainerExtensionClass() + { + $basename = preg_replace('/Bundle$/', '', $this->getName()); + + return $this->getNamespace().'\\DependencyInjection\\'.$basename.'Extension'; + } + + /** + * Creates the bundle's container extension. + * + * @return ExtensionInterface|null + */ + protected function createContainerExtension() + { + return class_exists($class = $this->getContainerExtensionClass()) ? new $class() : null; + } + + private function parseClassName() + { + $pos = strrpos(static::class, '\\'); + $this->namespace = false === $pos ? '' : substr(static::class, 0, $pos); + if (null === $this->name) { + $this->name = false === $pos ? static::class : substr(static::class, $pos + 1); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Bundle/BundleInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Bundle/BundleInterface.php new file mode 100644 index 0000000..fdc13e0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Bundle/BundleInterface.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Bundle; + +use Symfony\Component\DependencyInjection\ContainerAwareInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; + +/** + * BundleInterface. + * + * @author Fabien Potencier + */ +interface BundleInterface extends ContainerAwareInterface +{ + /** + * Boots the Bundle. + */ + public function boot(); + + /** + * Shutdowns the Bundle. + */ + public function shutdown(); + + /** + * Builds the bundle. + * + * It is only ever called once when the cache is empty. + */ + public function build(ContainerBuilder $container); + + /** + * Returns the container extension that should be implicitly loaded. + * + * @return ExtensionInterface|null + */ + public function getContainerExtension(); + + /** + * Returns the bundle name (the class short name). + * + * @return string + */ + public function getName(); + + /** + * Gets the Bundle namespace. + * + * @return string + */ + public function getNamespace(); + + /** + * Gets the Bundle directory path. + * + * The path should always be returned as a Unix path (with /). + * + * @return string + */ + public function getPath(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CHANGELOG.md b/php/libraries/composer/vendor/symfony/http-kernel/CHANGELOG.md new file mode 100644 index 0000000..d0dc207 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CHANGELOG.md @@ -0,0 +1,317 @@ +CHANGELOG +========= + +5.4 +--- + + * Add the ability to enable the profiler using a request query parameter, body parameter or attribute + * Deprecate `AbstractTestSessionListener` and `TestSessionListener`, use `AbstractSessionListener` and `SessionListener` instead + * Deprecate the `fileLinkFormat` parameter of `DebugHandlersListener` + * Add support for configuring log level, and status code by exception class + * Allow ignoring "kernel.reset" methods that don't exist with "on_invalid" attribute + +5.3 +--- + + * Deprecate `ArgumentInterface` + * Add `ArgumentMetadata::getAttributes()` + * Deprecate `ArgumentMetadata::getAttribute()`, use `getAttributes()` instead + * Mark the class `Symfony\Component\HttpKernel\EventListener\DebugHandlersListener` as internal + * Deprecate returning a `ContainerBuilder` from `KernelInterface::registerContainerConfiguration()` + * Deprecate `HttpKernelInterface::MASTER_REQUEST` and add `HttpKernelInterface::MAIN_REQUEST` as replacement + * Deprecate `KernelEvent::isMasterRequest()` and add `isMainRequest()` as replacement + * Add `#[AsController]` attribute for declaring standalone controllers on PHP 8 + * Add `FragmentUriGeneratorInterface` and `FragmentUriGenerator` to generate the URI of a fragment + +5.2.0 +----- + + * added session usage + * made the public `http_cache` service handle requests when available + * allowed enabling trusted hosts and proxies using new `kernel.trusted_hosts`, + `kernel.trusted_proxies` and `kernel.trusted_headers` parameters + * content of request parameter `_password` is now also hidden + in the request profiler raw content section + * Allowed adding attributes on controller arguments that will be passed to argument resolvers. + * kernels implementing the `ExtensionInterface` will now be auto-registered to the container + * added parameter `kernel.runtime_environment`, defined as `%env(default:kernel.environment:APP_RUNTIME_ENV)%` + * do not set a default `Accept` HTTP header when using `HttpKernelBrowser` + +5.1.0 +----- + + * allowed to use a specific logger channel for deprecations + * made `WarmableInterface::warmUp()` return a list of classes or files to preload on PHP 7.4+; + not returning an array is deprecated + * made kernels implementing `WarmableInterface` be part of the cache warmup stage + * deprecated support for `service:action` syntax to reference controllers, use `serviceOrFqcn::method` instead + * allowed using public aliases to reference controllers + * added session usage reporting when the `_stateless` attribute of the request is set to `true` + * added `AbstractSessionListener::onSessionUsage()` to report when the session is used while a request is stateless + +5.0.0 +----- + + * removed support for getting the container from a non-booted kernel + * removed the first and second constructor argument of `ConfigDataCollector` + * removed `ConfigDataCollector::getApplicationName()` + * removed `ConfigDataCollector::getApplicationVersion()` + * removed support for `Symfony\Component\Templating\EngineInterface` in `HIncludeFragmentRenderer`, use a `Twig\Environment` only + * removed `TranslatorListener` in favor of `LocaleAwareListener` + * removed `getRootDir()` and `getName()` from `Kernel` and `KernelInterface` + * removed `FilterControllerArgumentsEvent`, use `ControllerArgumentsEvent` instead + * removed `FilterControllerEvent`, use `ControllerEvent` instead + * removed `FilterResponseEvent`, use `ResponseEvent` instead + * removed `GetResponseEvent`, use `RequestEvent` instead + * removed `GetResponseForControllerResultEvent`, use `ViewEvent` instead + * removed `GetResponseForExceptionEvent`, use `ExceptionEvent` instead + * removed `PostResponseEvent`, use `TerminateEvent` instead + * removed `SaveSessionListener` in favor of `AbstractSessionListener` + * removed `Client`, use `HttpKernelBrowser` instead + * added method `getProjectDir()` to `KernelInterface` + * removed methods `serialize` and `unserialize` from `DataCollector`, store the serialized state in the data property instead + * made `ProfilerStorageInterface` internal + * removed the second and third argument of `KernelInterface::locateResource` + * removed the second and third argument of `FileLocator::__construct` + * removed loading resources from `%kernel.root_dir%/Resources` and `%kernel.root_dir%` as + fallback directories. + * removed class `ExceptionListener`, use `ErrorListener` instead + +4.4.0 +----- + + * The `DebugHandlersListener` class has been marked as `final` + * Added new Bundle directory convention consistent with standard skeletons + * Deprecated the second and third argument of `KernelInterface::locateResource` + * Deprecated the second and third argument of `FileLocator::__construct` + * Deprecated loading resources from `%kernel.root_dir%/Resources` and `%kernel.root_dir%` as + fallback directories. Resources like service definitions are usually loaded relative to the + current directory or with a glob pattern. The fallback directories have never been advocated + so you likely do not use those in any app based on the SF Standard or Flex edition. + * Marked all dispatched event classes as `@final` + * Added `ErrorController` to enable the preview and error rendering mechanism + * Getting the container from a non-booted kernel is deprecated. + * Marked the `AjaxDataCollector`, `ConfigDataCollector`, `EventDataCollector`, + `ExceptionDataCollector`, `LoggerDataCollector`, `MemoryDataCollector`, + `RequestDataCollector` and `TimeDataCollector` classes as `@final`. + * Marked the `RouterDataCollector::collect()` method as `@final`. + * The `DataCollectorInterface::collect()` and `Profiler::collect()` methods third parameter signature + will be `\Throwable $exception = null` instead of `\Exception $exception = null` in Symfony 5.0. + * Deprecated methods `ExceptionEvent::get/setException()`, use `get/setThrowable()` instead + * Deprecated class `ExceptionListener`, use `ErrorListener` instead + +4.3.0 +----- + + * renamed `Client` to `HttpKernelBrowser` + * `KernelInterface` doesn't extend `Serializable` anymore + * deprecated the `Kernel::serialize()` and `unserialize()` methods + * increased the priority of `Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener` + * made `Symfony\Component\HttpKernel\EventListener\LocaleListener` set the default locale early + * deprecated `TranslatorListener` in favor of `LocaleAwareListener` + * added the registration of all `LocaleAwareInterface` implementations into the `LocaleAwareListener` + * made `FileLinkFormatter` final and not implement `Serializable` anymore + * the base `DataCollector` doesn't implement `Serializable` anymore, you should + store all the serialized state in the data property instead + * `DumpDataCollector` has been marked as `final` + * added an event listener to prevent search engines from indexing applications in debug mode. + * renamed `FilterControllerArgumentsEvent` to `ControllerArgumentsEvent` + * renamed `FilterControllerEvent` to `ControllerEvent` + * renamed `FilterResponseEvent` to `ResponseEvent` + * renamed `GetResponseEvent` to `RequestEvent` + * renamed `GetResponseForControllerResultEvent` to `ViewEvent` + * renamed `GetResponseForExceptionEvent` to `ExceptionEvent` + * renamed `PostResponseEvent` to `TerminateEvent` + * added `HttpClientKernel` for handling requests with an `HttpClientInterface` instance + * added `trace_header` and `trace_level` configuration options to `HttpCache` + +4.2.0 +----- + + * deprecated `KernelInterface::getRootDir()` and the `kernel.root_dir` parameter + * deprecated `KernelInterface::getName()` and the `kernel.name` parameter + * deprecated the first and second constructor argument of `ConfigDataCollector` + * deprecated `ConfigDataCollector::getApplicationName()` + * deprecated `ConfigDataCollector::getApplicationVersion()` + +4.1.0 +----- + + * added orphaned events support to `EventDataCollector` + * `ExceptionListener` now logs exceptions at priority `0` (previously logged at `-128`) + * Added support for using `service::method` to reference controllers, making it consistent with other cases. It is recommended over the `service:action` syntax with a single colon, which will be deprecated in the future. + * Added the ability to profile individual argument value resolvers via the + `Symfony\Component\HttpKernel\Controller\ArgumentResolver\TraceableValueResolver` + +4.0.0 +----- + + * removed the `DataCollector::varToString()` method, use `DataCollector::cloneVar()` + instead + * using the `DataCollector::cloneVar()` method requires the VarDumper component + * removed the `ValueExporter` class + * removed `ControllerResolverInterface::getArguments()` + * removed `TraceableControllerResolver::getArguments()` + * removed `ControllerResolver::getArguments()` and the ability to resolve arguments + * removed the `argument_resolver` service dependency from the `debug.controller_resolver` + * removed `LazyLoadingFragmentHandler::addRendererService()` + * removed `Psr6CacheClearer::addPool()` + * removed `Extension::addClassesToCompile()` and `Extension::getClassesToCompile()` + * removed `Kernel::loadClassCache()`, `Kernel::doLoadClassCache()`, `Kernel::setClassCache()`, + and `Kernel::getEnvParameters()` + * support for the `X-Status-Code` when handling exceptions in the `HttpKernel` + has been dropped, use the `HttpKernel::allowCustomResponseCode()` method + instead + * removed convention-based commands registration + * removed the `ChainCacheClearer::add()` method + * removed the `CacheaWarmerAggregate::add()` and `setWarmers()` methods + * made `CacheWarmerAggregate` and `ChainCacheClearer` classes final + +3.4.0 +----- + + * added a minimalist PSR-3 `Logger` class that writes in `stderr` + * made kernels implementing `CompilerPassInterface` able to process the container + * deprecated bundle inheritance + * added `RebootableInterface` and implemented it in `Kernel` + * deprecated commands auto registration + * deprecated `EnvParametersResource` + * added `Symfony\Component\HttpKernel\Client::catchExceptions()` + * deprecated the `ChainCacheClearer::add()` method + * deprecated the `CacheaWarmerAggregate::add()` and `setWarmers()` methods + * made `CacheWarmerAggregate` and `ChainCacheClearer` classes final + * added the possibility to reset the profiler to its initial state + * deprecated data collectors without a `reset()` method + * deprecated implementing `DebugLoggerInterface` without a `clear()` method + +3.3.0 +----- + + * added `kernel.project_dir` and `Kernel::getProjectDir()` + * deprecated `kernel.root_dir` and `Kernel::getRootDir()` + * deprecated `Kernel::getEnvParameters()` + * deprecated the special `SYMFONY__` environment variables + * added the possibility to change the query string parameter used by `UriSigner` + * deprecated `LazyLoadingFragmentHandler::addRendererService()` + * deprecated `Extension::addClassesToCompile()` and `Extension::getClassesToCompile()` + * deprecated `Psr6CacheClearer::addPool()` + +3.2.0 +----- + + * deprecated `DataCollector::varToString()`, use `cloneVar()` instead + * changed surrogate capability name in `AbstractSurrogate::addSurrogateCapability` to 'symfony' + * Added `ControllerArgumentValueResolverPass` + +3.1.0 +----- + * deprecated passing objects as URI attributes to the ESI and SSI renderers + * deprecated `ControllerResolver::getArguments()` + * added `Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface` + * added `Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface` as argument to `HttpKernel` + * added `Symfony\Component\HttpKernel\Controller\ArgumentResolver` + * added `Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::getMethod()` + * added `Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::getRedirect()` + * added the `kernel.controller_arguments` event, triggered after controller arguments have been resolved + +3.0.0 +----- + + * removed `Symfony\Component\HttpKernel\Kernel::init()` + * removed `Symfony\Component\HttpKernel\Kernel::isClassInActiveBundle()` and `Symfony\Component\HttpKernel\KernelInterface::isClassInActiveBundle()` + * removed `Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher::setProfiler()` + * removed `Symfony\Component\HttpKernel\EventListener\FragmentListener::getLocalIpAddresses()` + * removed `Symfony\Component\HttpKernel\EventListener\LocaleListener::setRequest()` + * removed `Symfony\Component\HttpKernel\EventListener\RouterListener::setRequest()` + * removed `Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest()` + * removed `Symfony\Component\HttpKernel\Fragment\FragmentHandler::setRequest()` + * removed `Symfony\Component\HttpKernel\HttpCache\Esi::hasSurrogateEsiCapability()` + * removed `Symfony\Component\HttpKernel\HttpCache\Esi::addSurrogateEsiCapability()` + * removed `Symfony\Component\HttpKernel\HttpCache\Esi::needsEsiParsing()` + * removed `Symfony\Component\HttpKernel\HttpCache\HttpCache::getEsi()` + * removed `Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel` + * removed `Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass` + * removed `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener` + * removed `Symfony\Component\HttpKernel\EventListener\EsiListener` + * removed `Symfony\Component\HttpKernel\HttpCache\EsiResponseCacheStrategy` + * removed `Symfony\Component\HttpKernel\HttpCache\EsiResponseCacheStrategyInterface` + * removed `Symfony\Component\HttpKernel\Log\LoggerInterface` + * removed `Symfony\Component\HttpKernel\Log\NullLogger` + * removed `Symfony\Component\HttpKernel\Profiler::import()` + * removed `Symfony\Component\HttpKernel\Profiler::export()` + +2.8.0 +----- + + * deprecated `Profiler::import` and `Profiler::export` + +2.7.0 +----- + + * added the HTTP status code to profiles + +2.6.0 +----- + + * deprecated `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener`, use `Symfony\Component\HttpKernel\EventListener\DebugHandlersListener` instead + * deprecated unused method `Symfony\Component\HttpKernel\Kernel::isClassInActiveBundle` and `Symfony\Component\HttpKernel\KernelInterface::isClassInActiveBundle` + +2.5.0 +----- + + * deprecated `Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass`, use `Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass` instead + +2.4.0 +----- + + * added event listeners for the session + * added the KernelEvents::FINISH_REQUEST event + +2.3.0 +----- + + * [BC BREAK] renamed `Symfony\Component\HttpKernel\EventListener\DeprecationLoggerListener` to `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener` and changed its constructor + * deprecated `Symfony\Component\HttpKernel\Debug\ErrorHandler`, `Symfony\Component\HttpKernel\Debug\ExceptionHandler`, + `Symfony\Component\HttpKernel\Exception\FatalErrorException` and `Symfony\Component\HttpKernel\Exception\FlattenException` + * deprecated `Symfony\Component\HttpKernel\Kernel::init()` + * added the possibility to specify an id an extra attributes to hinclude tags + * added the collect of data if a controller is a Closure in the Request collector + * pass exceptions from the ExceptionListener to the logger using the logging context to allow for more + detailed messages + +2.2.0 +----- + + * [BC BREAK] the path info for sub-request is now always _fragment (or whatever you configured instead of the default) + * added Symfony\Component\HttpKernel\EventListener\FragmentListener + * added Symfony\Component\HttpKernel\UriSigner + * added Symfony\Component\HttpKernel\FragmentRenderer and rendering strategies (in Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface) + * added Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel + * added ControllerReference to create reference of Controllers (used in the FragmentRenderer class) + * [BC BREAK] renamed TimeDataCollector::getTotalTime() to + TimeDataCollector::getDuration() + * updated the MemoryDataCollector to include the memory used in the + kernel.terminate event listeners + * moved the Stopwatch classes to a new component + * added TraceableControllerResolver + * added TraceableEventDispatcher (removed ContainerAwareTraceableEventDispatcher) + * added support for WinCache opcode cache in ConfigDataCollector + +2.1.0 +----- + + * [BC BREAK] the charset is now configured via the Kernel::getCharset() method + * [BC BREAK] the current locale for the user is not stored anymore in the session + * added the HTTP method to the profiler storage + * updated all listeners to implement EventSubscriberInterface + * added TimeDataCollector + * added ContainerAwareTraceableEventDispatcher + * moved TraceableEventDispatcherInterface to the EventDispatcher component + * added RouterListener, LocaleListener, and StreamedResponseListener + * added CacheClearerInterface (and ChainCacheClearer) + * added a kernel.terminate event (via TerminableInterface and PostResponseEvent) + * added a Stopwatch class + * added WarmableInterface + * improved extensibility between bundles + * added profiler storages for Memcache(d), File-based, MongoDB, Redis + * moved Filesystem class to its own component diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/CacheClearerInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/CacheClearerInterface.php new file mode 100644 index 0000000..270f690 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/CacheClearerInterface.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\CacheClearer; + +/** + * CacheClearerInterface. + * + * @author Dustin Dobervich + */ +interface CacheClearerInterface +{ + /** + * Clears any caches necessary. + */ + public function clear(string $cacheDir); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/ChainCacheClearer.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/ChainCacheClearer.php new file mode 100644 index 0000000..a875d89 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/ChainCacheClearer.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\CacheClearer; + +/** + * ChainCacheClearer. + * + * @author Dustin Dobervich + * + * @final + */ +class ChainCacheClearer implements CacheClearerInterface +{ + private $clearers; + + /** + * @param iterable $clearers + */ + public function __construct(iterable $clearers = []) + { + $this->clearers = $clearers; + } + + /** + * {@inheritdoc} + */ + public function clear(string $cacheDir) + { + foreach ($this->clearers as $clearer) { + $clearer->clear($cacheDir); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/Psr6CacheClearer.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/Psr6CacheClearer.php new file mode 100644 index 0000000..a074060 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheClearer/Psr6CacheClearer.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\CacheClearer; + +use Psr\Cache\CacheItemPoolInterface; + +/** + * @author Nicolas Grekas + */ +class Psr6CacheClearer implements CacheClearerInterface +{ + private $pools = []; + + /** + * @param array $pools + */ + public function __construct(array $pools = []) + { + $this->pools = $pools; + } + + /** + * @return bool + */ + public function hasPool(string $name) + { + return isset($this->pools[$name]); + } + + /** + * @return CacheItemPoolInterface + * + * @throws \InvalidArgumentException If the cache pool with the given name does not exist + */ + public function getPool(string $name) + { + if (!$this->hasPool($name)) { + throw new \InvalidArgumentException(sprintf('Cache pool not found: "%s".', $name)); + } + + return $this->pools[$name]; + } + + /** + * @return bool + * + * @throws \InvalidArgumentException If the cache pool with the given name does not exist + */ + public function clearPool(string $name) + { + if (!isset($this->pools[$name])) { + throw new \InvalidArgumentException(sprintf('Cache pool not found: "%s".', $name)); + } + + return $this->pools[$name]->clear(); + } + + /** + * {@inheritdoc} + */ + public function clear(string $cacheDir) + { + foreach ($this->pools as $pool) { + $pool->clear(); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmer.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmer.php new file mode 100644 index 0000000..aef42d6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmer.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\CacheWarmer; + +/** + * Abstract cache warmer that knows how to write a file to the cache. + * + * @author Fabien Potencier + */ +abstract class CacheWarmer implements CacheWarmerInterface +{ + protected function writeCacheFile(string $file, $content) + { + $tmpFile = @tempnam(\dirname($file), basename($file)); + if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) { + @chmod($file, 0666 & ~umask()); + + return; + } + + throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file)); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmerAggregate.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmerAggregate.php new file mode 100644 index 0000000..730f0f7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmerAggregate.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 Symfony\Component\HttpKernel\CacheWarmer; + +/** + * Aggregates several cache warmers into a single one. + * + * @author Fabien Potencier + * + * @final + */ +class CacheWarmerAggregate implements CacheWarmerInterface +{ + private $warmers; + private $debug; + private $deprecationLogsFilepath; + private $optionalsEnabled = false; + private $onlyOptionalsEnabled = false; + + /** + * @param iterable $warmers + */ + public function __construct(iterable $warmers = [], bool $debug = false, ?string $deprecationLogsFilepath = null) + { + $this->warmers = $warmers; + $this->debug = $debug; + $this->deprecationLogsFilepath = $deprecationLogsFilepath; + } + + public function enableOptionalWarmers() + { + $this->optionalsEnabled = true; + } + + public function enableOnlyOptionalWarmers() + { + $this->onlyOptionalsEnabled = $this->optionalsEnabled = true; + } + + /** + * {@inheritdoc} + */ + public function warmUp(string $cacheDir): array + { + if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) { + $collectedLogs = []; + $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { + if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) { + return $previousHandler ? $previousHandler($type, $message, $file, $line) : false; + } + + if (isset($collectedLogs[$message])) { + ++$collectedLogs[$message]['count']; + + return null; + } + + $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3); + // Clean the trace by removing first frames added by the error handler itself. + for ($i = 0; isset($backtrace[$i]); ++$i) { + if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) { + $backtrace = \array_slice($backtrace, 1 + $i); + break; + } + } + + $collectedLogs[$message] = [ + 'type' => $type, + 'message' => $message, + 'file' => $file, + 'line' => $line, + 'trace' => $backtrace, + 'count' => 1, + ]; + + return null; + }); + } + + $preload = []; + try { + foreach ($this->warmers as $warmer) { + if (!$this->optionalsEnabled && $warmer->isOptional()) { + continue; + } + if ($this->onlyOptionalsEnabled && !$warmer->isOptional()) { + continue; + } + + $preload[] = array_values((array) $warmer->warmUp($cacheDir)); + } + } finally { + if ($collectDeprecations) { + restore_error_handler(); + + if (is_file($this->deprecationLogsFilepath)) { + $previousLogs = unserialize(file_get_contents($this->deprecationLogsFilepath)); + if (\is_array($previousLogs)) { + $collectedLogs = array_merge($previousLogs, $collectedLogs); + } + } + + file_put_contents($this->deprecationLogsFilepath, serialize(array_values($collectedLogs))); + } + } + + return array_values(array_unique(array_merge([], ...$preload))); + } + + /** + * {@inheritdoc} + */ + public function isOptional(): bool + { + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmerInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmerInterface.php new file mode 100644 index 0000000..1f1740b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/CacheWarmerInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\CacheWarmer; + +/** + * Interface for classes able to warm up the cache. + * + * @author Fabien Potencier + */ +interface CacheWarmerInterface extends WarmableInterface +{ + /** + * Checks whether this warmer is optional or not. + * + * Optional warmers can be ignored on certain conditions. + * + * A warmer should return true if the cache can be + * generated incrementally and on-demand. + * + * @return bool + */ + public function isOptional(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/WarmableInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/WarmableInterface.php new file mode 100644 index 0000000..2f442cb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/CacheWarmer/WarmableInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\CacheWarmer; + +/** + * Interface for classes that support warming their cache. + * + * @author Fabien Potencier + */ +interface WarmableInterface +{ + /** + * Warms up the cache. + * + * @return string[] A list of classes or files to preload on PHP 7.4+ + */ + public function warmUp(string $cacheDir); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Config/FileLocator.php b/php/libraries/composer/vendor/symfony/http-kernel/Config/FileLocator.php new file mode 100644 index 0000000..4b98437 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Config/FileLocator.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 Symfony\Component\HttpKernel\Config; + +use Symfony\Component\Config\FileLocator as BaseFileLocator; +use Symfony\Component\HttpKernel\KernelInterface; + +/** + * FileLocator uses the KernelInterface to locate resources in bundles. + * + * @author Fabien Potencier + */ +class FileLocator extends BaseFileLocator +{ + private $kernel; + + public function __construct(KernelInterface $kernel) + { + $this->kernel = $kernel; + + parent::__construct(); + } + + /** + * {@inheritdoc} + */ + public function locate(string $file, ?string $currentPath = null, bool $first = true) + { + if (isset($file[0]) && '@' === $file[0]) { + $resource = $this->kernel->locateResource($file); + + return $first ? $resource : [$resource]; + } + + return parent::locate($file, $currentPath, $first); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver.php new file mode 100644 index 0000000..76ef797 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DefaultValueResolver; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestAttributeValueResolver; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestValueResolver; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\SessionValueResolver; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface; + +/** + * Responsible for resolving the arguments passed to an action. + * + * @author Iltar van der Berg + */ +final class ArgumentResolver implements ArgumentResolverInterface +{ + private $argumentMetadataFactory; + private $argumentValueResolvers; + + /** + * @param iterable $argumentValueResolvers + */ + public function __construct(?ArgumentMetadataFactoryInterface $argumentMetadataFactory = null, iterable $argumentValueResolvers = []) + { + $this->argumentMetadataFactory = $argumentMetadataFactory ?? new ArgumentMetadataFactory(); + $this->argumentValueResolvers = $argumentValueResolvers ?: self::getDefaultArgumentValueResolvers(); + } + + /** + * {@inheritdoc} + */ + public function getArguments(Request $request, callable $controller): array + { + $arguments = []; + + foreach ($this->argumentMetadataFactory->createArgumentMetadata($controller) as $metadata) { + foreach ($this->argumentValueResolvers as $resolver) { + if (!$resolver->supports($request, $metadata)) { + continue; + } + + $resolved = $resolver->resolve($request, $metadata); + + $atLeastOne = false; + foreach ($resolved as $append) { + $atLeastOne = true; + $arguments[] = $append; + } + + if (!$atLeastOne) { + throw new \InvalidArgumentException(sprintf('"%s::resolve()" must yield at least one value.', get_debug_type($resolver))); + } + + // continue to the next controller argument + continue 2; + } + + $representative = $controller; + + if (\is_array($representative)) { + $representative = sprintf('%s::%s()', \get_class($representative[0]), $representative[1]); + } elseif (\is_object($representative)) { + $representative = \get_class($representative); + } + + throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.', $representative, $metadata->getName())); + } + + return $arguments; + } + + /** + * @return iterable + */ + public static function getDefaultArgumentValueResolvers(): iterable + { + return [ + new RequestAttributeValueResolver(), + new RequestValueResolver(), + new SessionValueResolver(), + new DefaultValueResolver(), + new VariadicValueResolver(), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/DefaultValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/DefaultValueResolver.php new file mode 100644 index 0000000..32a0e07 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/DefaultValueResolver.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\HttpKernel\Controller\ArgumentResolver; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Yields the default value defined in the action signature when no value has been given. + * + * @author Iltar van der Berg + */ +final class DefaultValueResolver implements ArgumentValueResolverInterface +{ + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + return $argument->hasDefaultValue() || (null !== $argument->getType() && $argument->isNullable() && !$argument->isVariadic()); + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + yield $argument->hasDefaultValue() ? $argument->getDefaultValue() : null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/NotTaggedControllerValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/NotTaggedControllerValueResolver.php new file mode 100644 index 0000000..48ea6e7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/NotTaggedControllerValueResolver.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver; + +use Psr\Container\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Provides an intuitive error message when controller fails because it is not registered as a service. + * + * @author Simeon Kolev + */ +final class NotTaggedControllerValueResolver implements ArgumentValueResolverInterface +{ + private $container; + + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + $controller = $request->attributes->get('_controller'); + + if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) { + $controller = $controller[0].'::'.$controller[1]; + } elseif (!\is_string($controller) || '' === $controller) { + return false; + } + + if ('\\' === $controller[0]) { + $controller = ltrim($controller, '\\'); + } + + if (!$this->container->has($controller) && false !== $i = strrpos($controller, ':')) { + $controller = substr($controller, 0, $i).strtolower(substr($controller, $i)); + } + + return false === $this->container->has($controller); + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + if (\is_array($controller = $request->attributes->get('_controller'))) { + $controller = $controller[0].'::'.$controller[1]; + } + + if ('\\' === $controller[0]) { + $controller = ltrim($controller, '\\'); + } + + if (!$this->container->has($controller)) { + $controller = (false !== $i = strrpos($controller, ':')) + ? substr($controller, 0, $i).strtolower(substr($controller, $i)) + : $controller.'::__invoke'; + } + + $what = sprintf('argument $%s of "%s()"', $argument->getName(), $controller); + $message = sprintf('Could not resolve %s, maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?', $what); + + throw new RuntimeException($message); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/RequestAttributeValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/RequestAttributeValueResolver.php new file mode 100644 index 0000000..c62d327 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/RequestAttributeValueResolver.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\HttpKernel\Controller\ArgumentResolver; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Yields a non-variadic argument's value from the request attributes. + * + * @author Iltar van der Berg + */ +final class RequestAttributeValueResolver implements ArgumentValueResolverInterface +{ + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + return !$argument->isVariadic() && $request->attributes->has($argument->getName()); + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + yield $request->attributes->get($argument->getName()); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/RequestValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/RequestValueResolver.php new file mode 100644 index 0000000..75cbd97 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/RequestValueResolver.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\HttpKernel\Controller\ArgumentResolver; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Yields the same instance as the request object passed along. + * + * @author Iltar van der Berg + */ +final class RequestValueResolver implements ArgumentValueResolverInterface +{ + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + return Request::class === $argument->getType() || is_subclass_of($argument->getType(), Request::class); + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + yield $request; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/ServiceValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/ServiceValueResolver.php new file mode 100644 index 0000000..4ffb8c9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/ServiceValueResolver.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver; + +use Psr\Container\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Yields a service keyed by _controller and argument name. + * + * @author Nicolas Grekas + */ +final class ServiceValueResolver implements ArgumentValueResolverInterface +{ + private $container; + + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + $controller = $request->attributes->get('_controller'); + + if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) { + $controller = $controller[0].'::'.$controller[1]; + } elseif (!\is_string($controller) || '' === $controller) { + return false; + } + + if ('\\' === $controller[0]) { + $controller = ltrim($controller, '\\'); + } + + if (!$this->container->has($controller) && false !== $i = strrpos($controller, ':')) { + $controller = substr($controller, 0, $i).strtolower(substr($controller, $i)); + } + + return $this->container->has($controller) && $this->container->get($controller)->has($argument->getName()); + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + if (\is_array($controller = $request->attributes->get('_controller'))) { + $controller = $controller[0].'::'.$controller[1]; + } + + if ('\\' === $controller[0]) { + $controller = ltrim($controller, '\\'); + } + + if (!$this->container->has($controller)) { + $i = strrpos($controller, ':'); + $controller = substr($controller, 0, $i).strtolower(substr($controller, $i)); + } + + try { + yield $this->container->get($controller)->get($argument->getName()); + } catch (RuntimeException $e) { + $what = sprintf('argument $%s of "%s()"', $argument->getName(), $controller); + $message = preg_replace('/service "\.service_locator\.[^"]++"/', $what, $e->getMessage()); + + if ($e->getMessage() === $message) { + $message = sprintf('Cannot resolve %s: %s', $what, $message); + } + + $r = new \ReflectionProperty($e, 'message'); + $r->setAccessible(true); + $r->setValue($e, $message); + + throw $e; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/SessionValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/SessionValueResolver.php new file mode 100644 index 0000000..a1e6b43 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/SessionValueResolver.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Yields the Session. + * + * @author Iltar van der Berg + */ +final class SessionValueResolver implements ArgumentValueResolverInterface +{ + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + if (!$request->hasSession()) { + return false; + } + + $type = $argument->getType(); + if (SessionInterface::class !== $type && !is_subclass_of($type, SessionInterface::class)) { + return false; + } + + return $request->getSession() instanceof $type; + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + yield $request->getSession(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/TraceableValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/TraceableValueResolver.php new file mode 100644 index 0000000..bde3c90 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/TraceableValueResolver.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * Provides timing information via the stopwatch. + * + * @author Iltar van der Berg + */ +final class TraceableValueResolver implements ArgumentValueResolverInterface +{ + private $inner; + private $stopwatch; + + public function __construct(ArgumentValueResolverInterface $inner, Stopwatch $stopwatch) + { + $this->inner = $inner; + $this->stopwatch = $stopwatch; + } + + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + $method = \get_class($this->inner).'::'.__FUNCTION__; + $this->stopwatch->start($method, 'controller.argument_value_resolver'); + + $return = $this->inner->supports($request, $argument); + + $this->stopwatch->stop($method); + + return $return; + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + $method = \get_class($this->inner).'::'.__FUNCTION__; + $this->stopwatch->start($method, 'controller.argument_value_resolver'); + + yield from $this->inner->resolve($request, $argument); + + $this->stopwatch->stop($method); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/VariadicValueResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/VariadicValueResolver.php new file mode 100644 index 0000000..a8f7e0f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolver/VariadicValueResolver.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 Symfony\Component\HttpKernel\Controller\ArgumentResolver; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Yields a variadic argument's values from the request attributes. + * + * @author Iltar van der Berg + */ +final class VariadicValueResolver implements ArgumentValueResolverInterface +{ + /** + * {@inheritdoc} + */ + public function supports(Request $request, ArgumentMetadata $argument): bool + { + return $argument->isVariadic() && $request->attributes->has($argument->getName()); + } + + /** + * {@inheritdoc} + */ + public function resolve(Request $request, ArgumentMetadata $argument): iterable + { + $values = $request->attributes->get($argument->getName()); + + if (!\is_array($values)) { + throw new \InvalidArgumentException(sprintf('The action argument "...$%1$s" is required to be an array, the request attribute "%1$s" contains a type of "%2$s" instead.', $argument->getName(), get_debug_type($values))); + } + + yield from $values; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolverInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolverInterface.php new file mode 100644 index 0000000..30e4783 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentResolverInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\HttpFoundation\Request; + +/** + * An ArgumentResolverInterface instance knows how to determine the + * arguments for a specific action. + * + * @author Fabien Potencier + */ +interface ArgumentResolverInterface +{ + /** + * Returns the arguments to pass to the controller. + * + * @return array + * + * @throws \RuntimeException When no value could be provided for a required argument + */ + public function getArguments(Request $request, callable $controller); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentValueResolverInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentValueResolverInterface.php new file mode 100644 index 0000000..1317707 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ArgumentValueResolverInterface.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\HttpKernel\Controller; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; + +/** + * Responsible for resolving the value of an argument based on its metadata. + * + * @author Iltar van der Berg + */ +interface ArgumentValueResolverInterface +{ + /** + * Whether this resolver can resolve the value for the given ArgumentMetadata. + * + * @return bool + */ + public function supports(Request $request, ArgumentMetadata $argument); + + /** + * Returns the possible value(s). + * + * @return iterable + */ + public function resolve(Request $request, ArgumentMetadata $argument); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ContainerControllerResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ContainerControllerResolver.php new file mode 100644 index 0000000..b7f77d0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ContainerControllerResolver.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Psr\Container\ContainerInterface; +use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\Container; + +/** + * A controller resolver searching for a controller in a psr-11 container when using the "service::method" notation. + * + * @author Fabien Potencier + * @author Maxime Steinhausser + */ +class ContainerControllerResolver extends ControllerResolver +{ + protected $container; + + public function __construct(ContainerInterface $container, ?LoggerInterface $logger = null) + { + $this->container = $container; + + parent::__construct($logger); + } + + protected function createController(string $controller) + { + if (1 === substr_count($controller, ':')) { + $controller = str_replace(':', '::', $controller); + trigger_deprecation('symfony/http-kernel', '5.1', 'Referencing controllers with a single colon is deprecated. Use "%s" instead.', $controller); + } + + return parent::createController($controller); + } + + /** + * {@inheritdoc} + */ + protected function instantiateController(string $class) + { + $class = ltrim($class, '\\'); + + if ($this->container->has($class)) { + return $this->container->get($class); + } + + try { + return parent::instantiateController($class); + } catch (\Error $e) { + } + + $this->throwExceptionIfControllerWasRemoved($class, $e); + + if ($e instanceof \ArgumentCountError) { + throw new \InvalidArgumentException(sprintf('Controller "%s" has required constructor arguments and does not exist in the container. Did you forget to define the controller as a service?', $class), 0, $e); + } + + throw new \InvalidArgumentException(sprintf('Controller "%s" does neither exist as service nor as class.', $class), 0, $e); + } + + private function throwExceptionIfControllerWasRemoved(string $controller, \Throwable $previous) + { + if ($this->container instanceof Container && isset($this->container->getRemovedIds()[$controller])) { + throw new \InvalidArgumentException(sprintf('Controller "%s" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?', $controller), 0, $previous); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerReference.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerReference.php new file mode 100644 index 0000000..b4fdadd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerReference.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; + +/** + * Acts as a marker and a data holder for a Controller. + * + * Some methods in Symfony accept both a URI (as a string) or a controller as + * an argument. In the latter case, instead of passing an array representing + * the controller, you can use an instance of this class. + * + * @author Fabien Potencier + * + * @see FragmentRendererInterface + */ +class ControllerReference +{ + public $controller; + public $attributes = []; + public $query = []; + + /** + * @param string $controller The controller name + * @param array $attributes An array of parameters to add to the Request attributes + * @param array $query An array of parameters to add to the Request query string + */ + public function __construct(string $controller, array $attributes = [], array $query = []) + { + $this->controller = $controller; + $this->attributes = $attributes; + $this->query = $query; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerResolver.php new file mode 100644 index 0000000..e6b4b80 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerResolver.php @@ -0,0 +1,220 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Psr\Log\LoggerInterface; +use Symfony\Component\HttpFoundation\Request; + +/** + * This implementation uses the '_controller' request attribute to determine + * the controller to execute. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class ControllerResolver implements ControllerResolverInterface +{ + private $logger; + + public function __construct(?LoggerInterface $logger = null) + { + $this->logger = $logger; + } + + /** + * {@inheritdoc} + */ + public function getController(Request $request) + { + if (!$controller = $request->attributes->get('_controller')) { + if (null !== $this->logger) { + $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.'); + } + + return false; + } + + if (\is_array($controller)) { + if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) { + try { + $controller[0] = $this->instantiateController($controller[0]); + } catch (\Error|\LogicException $e) { + try { + // We cannot just check is_callable but have to use reflection because a non-static method + // can still be called statically in PHP but we don't want that. This is deprecated in PHP 7, so we + // could simplify this with PHP 8. + if ((new \ReflectionMethod($controller[0], $controller[1]))->isStatic()) { + return $controller; + } + } catch (\ReflectionException $reflectionException) { + throw $e; + } + + throw $e; + } + } + + if (!\is_callable($controller)) { + throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller)); + } + + return $controller; + } + + if (\is_object($controller)) { + if (!\is_callable($controller)) { + throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller)); + } + + return $controller; + } + + if (\function_exists($controller)) { + return $controller; + } + + try { + $callable = $this->createController($controller); + } catch (\InvalidArgumentException $e) { + throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e); + } + + if (!\is_callable($callable)) { + throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable)); + } + + return $callable; + } + + /** + * Returns a callable for the given controller. + * + * @return callable + * + * @throws \InvalidArgumentException When the controller cannot be created + */ + protected function createController(string $controller) + { + if (!str_contains($controller, '::')) { + $controller = $this->instantiateController($controller); + + if (!\is_callable($controller)) { + throw new \InvalidArgumentException($this->getControllerError($controller)); + } + + return $controller; + } + + [$class, $method] = explode('::', $controller, 2); + + try { + $controller = [$this->instantiateController($class), $method]; + } catch (\Error|\LogicException $e) { + try { + if ((new \ReflectionMethod($class, $method))->isStatic()) { + return $class.'::'.$method; + } + } catch (\ReflectionException $reflectionException) { + throw $e; + } + + throw $e; + } + + if (!\is_callable($controller)) { + throw new \InvalidArgumentException($this->getControllerError($controller)); + } + + return $controller; + } + + /** + * Returns an instantiated controller. + * + * @return object + */ + protected function instantiateController(string $class) + { + return new $class(); + } + + private function getControllerError($callable): string + { + if (\is_string($callable)) { + if (str_contains($callable, '::')) { + $callable = explode('::', $callable, 2); + } else { + return sprintf('Function "%s" does not exist.', $callable); + } + } + + if (\is_object($callable)) { + $availableMethods = $this->getClassMethodsWithoutMagicMethods($callable); + $alternativeMsg = $availableMethods ? sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : ''; + + return sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg); + } + + if (!\is_array($callable)) { + return sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable)); + } + + if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) { + return 'Invalid array callable, expected [controller, method].'; + } + + [$controller, $method] = $callable; + + if (\is_string($controller) && !class_exists($controller)) { + return sprintf('Class "%s" does not exist.', $controller); + } + + $className = \is_object($controller) ? get_debug_type($controller) : $controller; + + if (method_exists($controller, $method)) { + return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className); + } + + $collection = $this->getClassMethodsWithoutMagicMethods($controller); + + $alternatives = []; + + foreach ($collection as $item) { + $lev = levenshtein($method, $item); + + if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) { + $alternatives[] = $item; + } + } + + asort($alternatives); + + $message = sprintf('Expected method "%s" on class "%s"', $method, $className); + + if (\count($alternatives) > 0) { + $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives)); + } else { + $message .= sprintf('. Available methods: "%s".', implode('", "', $collection)); + } + + return $message; + } + + private function getClassMethodsWithoutMagicMethods($classOrObject): array + { + $methods = get_class_methods($classOrObject); + + return array_filter($methods, function (string $method) { + return 0 !== strncmp($method, '__', 2); + }); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerResolverInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerResolverInterface.php new file mode 100644 index 0000000..8b70a88 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ControllerResolverInterface.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\HttpFoundation\Request; + +/** + * A ControllerResolverInterface implementation knows how to determine the + * controller to execute based on a Request object. + * + * A Controller can be any valid PHP callable. + * + * @author Fabien Potencier + */ +interface ControllerResolverInterface +{ + /** + * Returns the Controller instance associated with a Request. + * + * As several resolvers can exist for a single application, a resolver must + * return false when it is not able to determine the controller. + * + * The resolver must only throw an exception when it should be able to load a + * controller but cannot because of some errors made by the developer. + * + * @return callable|false A PHP callable representing the Controller, + * or false if this resolver is not able to determine the controller + * + * @throws \LogicException If a controller was found based on the request but it is not callable + */ + public function getController(Request $request); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/ErrorController.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ErrorController.php new file mode 100644 index 0000000..b6c4401 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/ErrorController.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\HttpException; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Renders error or exception pages from a given FlattenException. + * + * @author Yonel Ceruto + * @author Matthias Pigulla + */ +class ErrorController +{ + private $kernel; + private $controller; + private $errorRenderer; + + public function __construct(HttpKernelInterface $kernel, $controller, ErrorRendererInterface $errorRenderer) + { + $this->kernel = $kernel; + $this->controller = $controller; + $this->errorRenderer = $errorRenderer; + } + + public function __invoke(\Throwable $exception): Response + { + $exception = $this->errorRenderer->render($exception); + + return new Response($exception->getAsString(), $exception->getStatusCode(), $exception->getHeaders()); + } + + public function preview(Request $request, int $code): Response + { + /* + * This Request mimics the parameters set by + * \Symfony\Component\HttpKernel\EventListener\ErrorListener::duplicateRequest, with + * the additional "showException" flag. + */ + $subRequest = $request->duplicate(null, null, [ + '_controller' => $this->controller, + 'exception' => new HttpException($code, 'This is a sample exception.'), + 'logger' => null, + 'showException' => false, + ]); + + return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/TraceableArgumentResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/TraceableArgumentResolver.php new file mode 100644 index 0000000..859cf3a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/TraceableArgumentResolver.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Fabien Potencier + */ +class TraceableArgumentResolver implements ArgumentResolverInterface +{ + private $resolver; + private $stopwatch; + + public function __construct(ArgumentResolverInterface $resolver, Stopwatch $stopwatch) + { + $this->resolver = $resolver; + $this->stopwatch = $stopwatch; + } + + /** + * {@inheritdoc} + */ + public function getArguments(Request $request, callable $controller) + { + $e = $this->stopwatch->start('controller.get_arguments'); + + try { + return $this->resolver->getArguments($request, $controller); + } finally { + $e->stop(); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Controller/TraceableControllerResolver.php b/php/libraries/composer/vendor/symfony/http-kernel/Controller/TraceableControllerResolver.php new file mode 100644 index 0000000..013dfe2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Controller/TraceableControllerResolver.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Controller; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Fabien Potencier + */ +class TraceableControllerResolver implements ControllerResolverInterface +{ + private $resolver; + private $stopwatch; + + public function __construct(ControllerResolverInterface $resolver, Stopwatch $stopwatch) + { + $this->resolver = $resolver; + $this->stopwatch = $stopwatch; + } + + /** + * {@inheritdoc} + */ + public function getController(Request $request) + { + $e = $this->stopwatch->start('controller.get_callable'); + + try { + return $this->resolver->getController($request); + } finally { + $e->stop(); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.php b/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.php new file mode 100644 index 0000000..5046c84 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.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\HttpKernel\ControllerMetadata; + +use Symfony\Component\HttpKernel\Attribute\ArgumentInterface; + +/** + * Responsible for storing metadata of an argument. + * + * @author Iltar van der Berg + */ +class ArgumentMetadata +{ + public const IS_INSTANCEOF = 2; + + private $name; + private $type; + private $isVariadic; + private $hasDefaultValue; + private $defaultValue; + private $isNullable; + private $attributes; + + /** + * @param object[] $attributes + */ + public function __construct(string $name, ?string $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false, $attributes = []) + { + $this->name = $name; + $this->type = $type; + $this->isVariadic = $isVariadic; + $this->hasDefaultValue = $hasDefaultValue; + $this->defaultValue = $defaultValue; + $this->isNullable = $isNullable || null === $type || ($hasDefaultValue && null === $defaultValue); + + if (null === $attributes || $attributes instanceof ArgumentInterface) { + trigger_deprecation('symfony/http-kernel', '5.3', 'The "%s" constructor expects an array of PHP attributes as last argument, %s given.', __CLASS__, get_debug_type($attributes)); + $attributes = $attributes ? [$attributes] : []; + } + + $this->attributes = $attributes; + } + + /** + * Returns the name as given in PHP, $foo would yield "foo". + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Returns the type of the argument. + * + * The type is the PHP class in 5.5+ and additionally the basic type in PHP 7.0+. + * + * @return string|null + */ + public function getType() + { + return $this->type; + } + + /** + * Returns whether the argument is defined as "...$variadic". + * + * @return bool + */ + public function isVariadic() + { + return $this->isVariadic; + } + + /** + * Returns whether the argument has a default value. + * + * Implies whether an argument is optional. + * + * @return bool + */ + public function hasDefaultValue() + { + return $this->hasDefaultValue; + } + + /** + * Returns whether the argument accepts null values. + * + * @return bool + */ + public function isNullable() + { + return $this->isNullable; + } + + /** + * Returns the default value of the argument. + * + * @return mixed + * + * @throws \LogicException if no default value is present; {@see self::hasDefaultValue()} + */ + public function getDefaultValue() + { + if (!$this->hasDefaultValue) { + throw new \LogicException(sprintf('Argument $%s does not have a default value. Use "%s::hasDefaultValue()" to avoid this exception.', $this->name, __CLASS__)); + } + + return $this->defaultValue; + } + + /** + * Returns the attribute (if any) that was set on the argument. + */ + public function getAttribute(): ?ArgumentInterface + { + trigger_deprecation('symfony/http-kernel', '5.3', 'Method "%s()" is deprecated, use "getAttributes()" instead.', __METHOD__); + + if (!$this->attributes) { + return null; + } + + return $this->attributes[0] instanceof ArgumentInterface ? $this->attributes[0] : null; + } + + /** + * @return object[] + */ + public function getAttributes(?string $name = null, int $flags = 0): array + { + if (!$name) { + return $this->attributes; + } + + $attributes = []; + if ($flags & self::IS_INSTANCEOF) { + foreach ($this->attributes as $attribute) { + if ($attribute instanceof $name) { + $attributes[] = $attribute; + } + } + } else { + foreach ($this->attributes as $attribute) { + if (\get_class($attribute) === $name) { + $attributes[] = $attribute; + } + } + } + + return $attributes; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php b/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php new file mode 100644 index 0000000..85bb805 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\ControllerMetadata; + +/** + * Builds {@see ArgumentMetadata} objects based on the given Controller. + * + * @author Iltar van der Berg + */ +final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface +{ + /** + * {@inheritdoc} + */ + public function createArgumentMetadata($controller): array + { + $arguments = []; + + if (\is_array($controller)) { + $reflection = new \ReflectionMethod($controller[0], $controller[1]); + $class = $reflection->class; + } elseif (\is_object($controller) && !$controller instanceof \Closure) { + $reflection = new \ReflectionMethod($controller, '__invoke'); + $class = $reflection->class; + } else { + $reflection = new \ReflectionFunction($controller); + if ($class = str_contains($reflection->name, '{closure}') ? null : (\PHP_VERSION_ID >= 80111 ? $reflection->getClosureCalledClass() : $reflection->getClosureScopeClass())) { + $class = $class->name; + } + } + + foreach ($reflection->getParameters() as $param) { + $attributes = []; + if (\PHP_VERSION_ID >= 80000) { + foreach ($param->getAttributes() as $reflectionAttribute) { + if (class_exists($reflectionAttribute->getName())) { + $attributes[] = $reflectionAttribute->newInstance(); + } + } + } + + $arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $class), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull(), $attributes); + } + + return $arguments; + } + + /** + * Returns an associated type to the given parameter if available. + */ + private function getType(\ReflectionParameter $parameter, ?string $class): ?string + { + if (!$type = $parameter->getType()) { + return null; + } + $name = $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type; + + if (null !== $class) { + switch (strtolower($name)) { + case 'self': + return $class; + case 'parent': + return get_parent_class($class) ?: null; + } + } + + return $name; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactoryInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactoryInterface.php new file mode 100644 index 0000000..a34befc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactoryInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\ControllerMetadata; + +/** + * Builds method argument data. + * + * @author Iltar van der Berg + */ +interface ArgumentMetadataFactoryInterface +{ + /** + * @param string|object|array $controller The controller to resolve the arguments for + * + * @return ArgumentMetadata[] + */ + public function createArgumentMetadata($controller); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/AjaxDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/AjaxDataCollector.php new file mode 100644 index 0000000..31764f0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/AjaxDataCollector.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\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * @author Bart van den Burg + * + * @final + */ +class AjaxDataCollector extends DataCollector +{ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + // all collecting is done client side + } + + public function reset() + { + // all collecting is done client side + } + + public function getName(): string + { + return 'ajax'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/ConfigDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/ConfigDataCollector.php new file mode 100644 index 0000000..72f79c5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/ConfigDataCollector.php @@ -0,0 +1,275 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Kernel; +use Symfony\Component\HttpKernel\KernelInterface; +use Symfony\Component\VarDumper\Caster\ClassStub; + +/** + * @author Fabien Potencier + * + * @final + */ +class ConfigDataCollector extends DataCollector implements LateDataCollectorInterface +{ + /** + * @var KernelInterface + */ + private $kernel; + + /** + * Sets the Kernel associated with this Request. + */ + public function setKernel(?KernelInterface $kernel = null) + { + $this->kernel = $kernel; + } + + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + $eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE); + $eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE); + + $this->data = [ + 'token' => $response->headers->get('X-Debug-Token'), + 'symfony_version' => Kernel::VERSION, + 'symfony_minor_version' => sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION), + 'symfony_lts' => 4 === Kernel::MINOR_VERSION, + 'symfony_state' => $this->determineSymfonyState(), + 'symfony_eom' => $eom->format('F Y'), + 'symfony_eol' => $eol->format('F Y'), + 'env' => isset($this->kernel) ? $this->kernel->getEnvironment() : 'n/a', + 'debug' => isset($this->kernel) ? $this->kernel->isDebug() : 'n/a', + 'php_version' => \PHP_VERSION, + 'php_architecture' => \PHP_INT_SIZE * 8, + 'php_intl_locale' => class_exists(\Locale::class, false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a', + 'php_timezone' => date_default_timezone_get(), + 'xdebug_enabled' => \extension_loaded('xdebug'), + 'apcu_enabled' => \extension_loaded('apcu') && filter_var(\ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN), + 'zend_opcache_enabled' => \extension_loaded('Zend OPcache') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN), + 'bundles' => [], + 'sapi_name' => \PHP_SAPI, + ]; + + if (isset($this->kernel)) { + foreach ($this->kernel->getBundles() as $name => $bundle) { + $this->data['bundles'][$name] = new ClassStub(\get_class($bundle)); + } + } + + if (preg_match('~^(\d+(?:\.\d+)*)(.+)?$~', $this->data['php_version'], $matches) && isset($matches[2])) { + $this->data['php_version'] = $matches[1]; + $this->data['php_version_extra'] = $matches[2]; + } + } + + /** + * {@inheritdoc} + */ + public function reset() + { + $this->data = []; + } + + public function lateCollect() + { + $this->data = $this->cloneVar($this->data); + } + + /** + * Gets the token. + */ + public function getToken(): ?string + { + return $this->data['token']; + } + + /** + * Gets the Symfony version. + */ + public function getSymfonyVersion(): string + { + return $this->data['symfony_version']; + } + + /** + * Returns the state of the current Symfony release. + * + * @return string One of: unknown, dev, stable, eom, eol + */ + public function getSymfonyState(): string + { + return $this->data['symfony_state']; + } + + /** + * Returns the minor Symfony version used (without patch numbers of extra + * suffix like "RC", "beta", etc.). + */ + public function getSymfonyMinorVersion(): string + { + return $this->data['symfony_minor_version']; + } + + /** + * Returns if the current Symfony version is a Long-Term Support one. + */ + public function isSymfonyLts(): bool + { + return $this->data['symfony_lts']; + } + + /** + * Returns the human readable date when this Symfony version ends its + * maintenance period. + */ + public function getSymfonyEom(): string + { + return $this->data['symfony_eom']; + } + + /** + * Returns the human readable date when this Symfony version reaches its + * "end of life" and won't receive bugs or security fixes. + */ + public function getSymfonyEol(): string + { + return $this->data['symfony_eol']; + } + + /** + * Gets the PHP version. + */ + public function getPhpVersion(): string + { + return $this->data['php_version']; + } + + /** + * Gets the PHP version extra part. + */ + public function getPhpVersionExtra(): ?string + { + return $this->data['php_version_extra'] ?? null; + } + + /** + * @return int The PHP architecture as number of bits (e.g. 32 or 64) + */ + public function getPhpArchitecture(): int + { + return $this->data['php_architecture']; + } + + public function getPhpIntlLocale(): string + { + return $this->data['php_intl_locale']; + } + + public function getPhpTimezone(): string + { + return $this->data['php_timezone']; + } + + /** + * Gets the environment. + */ + public function getEnv(): string + { + return $this->data['env']; + } + + /** + * Returns true if the debug is enabled. + * + * @return bool|string true if debug is enabled, false otherwise or a string if no kernel was set + */ + public function isDebug() + { + return $this->data['debug']; + } + + /** + * Returns true if the XDebug is enabled. + */ + public function hasXDebug(): bool + { + return $this->data['xdebug_enabled']; + } + + /** + * Returns true if APCu is enabled. + */ + public function hasApcu(): bool + { + return $this->data['apcu_enabled']; + } + + /** + * Returns true if Zend OPcache is enabled. + */ + public function hasZendOpcache(): bool + { + return $this->data['zend_opcache_enabled']; + } + + public function getBundles() + { + return $this->data['bundles']; + } + + /** + * Gets the PHP SAPI name. + */ + public function getSapiName(): string + { + return $this->data['sapi_name']; + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'config'; + } + + /** + * Tries to retrieve information about the current Symfony version. + * + * @return string One of: dev, stable, eom, eol + */ + private function determineSymfonyState(): string + { + $now = new \DateTime(); + $eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->modify('last day of this month'); + $eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->modify('last day of this month'); + + if ($now > $eol) { + $versionState = 'eol'; + } elseif ($now > $eom) { + $versionState = 'eom'; + } elseif ('' !== Kernel::EXTRA_VERSION) { + $versionState = 'dev'; + } else { + $versionState = 'stable'; + } + + return $versionState; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DataCollector.php new file mode 100644 index 0000000..ccaf66d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DataCollector.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\VarDumper\Caster\CutStub; +use Symfony\Component\VarDumper\Caster\ReflectionCaster; +use Symfony\Component\VarDumper\Cloner\ClonerInterface; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Cloner\Stub; +use Symfony\Component\VarDumper\Cloner\VarCloner; + +/** + * DataCollector. + * + * Children of this class must store the collected data in the data property. + * + * @author Fabien Potencier + * @author Bernhard Schussek + */ +abstract class DataCollector implements DataCollectorInterface +{ + /** + * @var array|Data + */ + protected $data = []; + + /** + * @var ClonerInterface + */ + private $cloner; + + /** + * Converts the variable into a serializable Data instance. + * + * This array can be displayed in the template using + * the VarDumper component. + * + * @param mixed $var + * + * @return Data + */ + protected function cloneVar($var) + { + if ($var instanceof Data) { + return $var; + } + if (null === $this->cloner) { + $this->cloner = new VarCloner(); + $this->cloner->setMaxItems(-1); + $this->cloner->addCasters($this->getCasters()); + } + + return $this->cloner->cloneVar($var); + } + + /** + * @return callable[] The casters to add to the cloner + */ + protected function getCasters() + { + $casters = [ + '*' => function ($v, array $a, Stub $s, $isNested) { + if (!$v instanceof Stub) { + foreach ($a as $k => $v) { + if (\is_object($v) && !$v instanceof \DateTimeInterface && !$v instanceof Stub) { + $a[$k] = new CutStub($v); + } + } + } + + return $a; + }, + ] + ReflectionCaster::UNSET_CLOSURE_FILE_INFO; + + return $casters; + } + + /** + * @return array + */ + public function __sleep() + { + return ['data']; + } + + public function __wakeup() + { + } + + /** + * @internal to prevent implementing \Serializable + */ + final protected function serialize() + { + } + + /** + * @internal to prevent implementing \Serializable + */ + final protected function unserialize($data) + { + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DataCollectorInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DataCollectorInterface.php new file mode 100644 index 0000000..8aca948 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DataCollectorInterface.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\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Contracts\Service\ResetInterface; + +/** + * DataCollectorInterface. + * + * @author Fabien Potencier + */ +interface DataCollectorInterface extends ResetInterface +{ + /** + * Collects data for the given Request and Response. + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null); + + /** + * Returns the name of the collector. + * + * @return string + */ + public function getName(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DumpDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DumpDataCollector.php new file mode 100644 index 0000000..3311bd4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/DumpDataCollector.php @@ -0,0 +1,292 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\CliDumper; +use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider; +use Symfony\Component\VarDumper\Dumper\DataDumperInterface; +use Symfony\Component\VarDumper\Dumper\HtmlDumper; +use Symfony\Component\VarDumper\Server\Connection; + +/** + * @author Nicolas Grekas + * + * @final + */ +class DumpDataCollector extends DataCollector implements DataDumperInterface +{ + private $stopwatch; + private $fileLinkFormat; + private $dataCount = 0; + private $isCollected = true; + private $clonesCount = 0; + private $clonesIndex = 0; + private $rootRefs; + private $charset; + private $requestStack; + private $dumper; + private $sourceContextProvider; + + /** + * @param string|FileLinkFormatter|null $fileLinkFormat + * @param DataDumperInterface|Connection|null $dumper + */ + public function __construct(?Stopwatch $stopwatch = null, $fileLinkFormat = null, ?string $charset = null, ?RequestStack $requestStack = null, $dumper = null) + { + $fileLinkFormat = $fileLinkFormat ?: \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'); + $this->stopwatch = $stopwatch; + $this->fileLinkFormat = $fileLinkFormat instanceof FileLinkFormatter && false === $fileLinkFormat->format('', 0) ? false : $fileLinkFormat; + $this->charset = $charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8'; + $this->requestStack = $requestStack; + $this->dumper = $dumper; + + // All clones share these properties by reference: + $this->rootRefs = [ + &$this->data, + &$this->dataCount, + &$this->isCollected, + &$this->clonesCount, + ]; + + $this->sourceContextProvider = $dumper instanceof Connection && isset($dumper->getContextProviders()['source']) ? $dumper->getContextProviders()['source'] : new SourceContextProvider($this->charset); + } + + public function __clone() + { + $this->clonesIndex = ++$this->clonesCount; + } + + public function dump(Data $data) + { + if ($this->stopwatch) { + $this->stopwatch->start('dump'); + } + + ['name' => $name, 'file' => $file, 'line' => $line, 'file_excerpt' => $fileExcerpt] = $this->sourceContextProvider->getContext(); + + if ($this->dumper instanceof Connection) { + if (!$this->dumper->write($data)) { + $this->isCollected = false; + } + } elseif ($this->dumper) { + $this->doDump($this->dumper, $data, $name, $file, $line); + } else { + $this->isCollected = false; + } + + if (!$this->dataCount) { + $this->data = []; + } + $this->data[] = compact('data', 'name', 'file', 'line', 'fileExcerpt'); + ++$this->dataCount; + + if ($this->stopwatch) { + $this->stopwatch->stop('dump'); + } + } + + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + if (!$this->dataCount) { + $this->data = []; + } + + // Sub-requests and programmatic calls stay in the collected profile. + if ($this->dumper || ($this->requestStack && $this->requestStack->getMainRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) { + return; + } + + // In all other conditions that remove the web debug toolbar, dumps are written on the output. + if (!$this->requestStack + || !$response->headers->has('X-Debug-Token') + || $response->isRedirection() + || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type') ?? '', 'html')) + || 'html' !== $request->getRequestFormat() + || false === strripos($response->getContent(), '') + ) { + if ($response->headers->has('Content-Type') && str_contains($response->headers->get('Content-Type') ?? '', 'html')) { + $dumper = new HtmlDumper('php://output', $this->charset); + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); + } else { + $dumper = new CliDumper('php://output', $this->charset); + if (method_exists($dumper, 'setDisplayOptions')) { + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); + } + } + + foreach ($this->data as $dump) { + $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line']); + } + } + } + + public function reset() + { + if ($this->stopwatch) { + $this->stopwatch->reset(); + } + $this->data = []; + $this->dataCount = 0; + $this->isCollected = true; + $this->clonesCount = 0; + $this->clonesIndex = 0; + } + + /** + * @internal + */ + public function __sleep(): array + { + if (!$this->dataCount) { + $this->data = []; + } + + if ($this->clonesCount !== $this->clonesIndex) { + return []; + } + + $this->data[] = $this->fileLinkFormat; + $this->data[] = $this->charset; + $this->dataCount = 0; + $this->isCollected = true; + + return parent::__sleep(); + } + + /** + * @internal + */ + public function __wakeup() + { + parent::__wakeup(); + + $charset = array_pop($this->data); + $fileLinkFormat = array_pop($this->data); + $this->dataCount = \count($this->data); + foreach ($this->data as $dump) { + if (!\is_string($dump['name']) || !\is_string($dump['file']) || !\is_int($dump['line'])) { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + } + + self::__construct($this->stopwatch, \is_string($fileLinkFormat) || $fileLinkFormat instanceof FileLinkFormatter ? $fileLinkFormat : null, \is_string($charset) ? $charset : null); + } + + public function getDumpsCount(): int + { + return $this->dataCount; + } + + public function getDumps(string $format, int $maxDepthLimit = -1, int $maxItemsPerDepth = -1): array + { + $data = fopen('php://memory', 'r+'); + + if ('html' === $format) { + $dumper = new HtmlDumper($data, $this->charset); + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); + } else { + throw new \InvalidArgumentException(sprintf('Invalid dump format: "%s".', $format)); + } + $dumps = []; + + if (!$this->dataCount) { + return $this->data = []; + } + + foreach ($this->data as $dump) { + $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth)); + $dump['data'] = stream_get_contents($data, -1, 0); + ftruncate($data, 0); + rewind($data); + $dumps[] = $dump; + } + + return $dumps; + } + + public function getName(): string + { + return 'dump'; + } + + public function __destruct() + { + if (0 === $this->clonesCount-- && !$this->isCollected && $this->dataCount) { + $this->clonesCount = 0; + $this->isCollected = true; + + $h = headers_list(); + $i = \count($h); + array_unshift($h, 'Content-Type: '.\ini_get('default_mimetype')); + while (0 !== stripos($h[$i], 'Content-Type:')) { + --$i; + } + + if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && stripos($h[$i], 'html')) { + $dumper = new HtmlDumper('php://output', $this->charset); + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); + } else { + $dumper = new CliDumper('php://output', $this->charset); + if (method_exists($dumper, 'setDisplayOptions')) { + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); + } + } + + foreach ($this->data as $i => $dump) { + $this->data[$i] = null; + $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line']); + } + + $this->data = []; + $this->dataCount = 0; + } + } + + private function doDump(DataDumperInterface $dumper, Data $data, string $name, string $file, int $line) + { + if ($dumper instanceof CliDumper) { + $contextDumper = function ($name, $file, $line, $fmt) { + if ($this instanceof HtmlDumper) { + if ($file) { + $s = $this->style('meta', '%s'); + $f = strip_tags($this->style('', $file)); + $name = strip_tags($this->style('', $name)); + if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) { + $name = sprintf(''.$s.'', strip_tags($this->style('', $link)), $f, $name); + } else { + $name = sprintf(''.$s.'', $f, $name); + } + } else { + $name = $this->style('meta', $name); + } + $this->line = $name.' on line '.$this->style('meta', $line).':'; + } else { + $this->line = $this->style('meta', $name).' on line '.$this->style('meta', $line).':'; + } + $this->dumpLine(0); + }; + $contextDumper = $contextDumper->bindTo($dumper, $dumper); + $contextDumper($name, $file, $line, $this->fileLinkFormat); + } else { + $cloner = new VarCloner(); + $dumper->dump($cloner->cloneVar($name.' on line '.$line.':')); + } + $dumper->dump($data); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/EventDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/EventDataCollector.php new file mode 100644 index 0000000..3f6ef4f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/EventDataCollector.php @@ -0,0 +1,137 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; +use Symfony\Contracts\Service\ResetInterface; + +/** + * @author Fabien Potencier + * + * @final + */ +class EventDataCollector extends DataCollector implements LateDataCollectorInterface +{ + protected $dispatcher; + private $requestStack; + private $currentRequest; + + public function __construct(?EventDispatcherInterface $dispatcher = null, ?RequestStack $requestStack = null) + { + $this->dispatcher = $dispatcher; + $this->requestStack = $requestStack; + } + + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + $this->currentRequest = $this->requestStack && $this->requestStack->getMainRequest() !== $request ? $request : null; + $this->data = [ + 'called_listeners' => [], + 'not_called_listeners' => [], + 'orphaned_events' => [], + ]; + } + + public function reset() + { + $this->data = []; + + if ($this->dispatcher instanceof ResetInterface) { + $this->dispatcher->reset(); + } + } + + public function lateCollect() + { + if ($this->dispatcher instanceof TraceableEventDispatcher) { + $this->setCalledListeners($this->dispatcher->getCalledListeners($this->currentRequest)); + $this->setNotCalledListeners($this->dispatcher->getNotCalledListeners($this->currentRequest)); + $this->setOrphanedEvents($this->dispatcher->getOrphanedEvents($this->currentRequest)); + } + + $this->data = $this->cloneVar($this->data); + } + + /** + * @param array $listeners An array of called listeners + * + * @see TraceableEventDispatcher + */ + public function setCalledListeners(array $listeners) + { + $this->data['called_listeners'] = $listeners; + } + + /** + * @see TraceableEventDispatcher + * + * @return array|Data + */ + public function getCalledListeners() + { + return $this->data['called_listeners']; + } + + /** + * @see TraceableEventDispatcher + */ + public function setNotCalledListeners(array $listeners) + { + $this->data['not_called_listeners'] = $listeners; + } + + /** + * @see TraceableEventDispatcher + * + * @return array|Data + */ + public function getNotCalledListeners() + { + return $this->data['not_called_listeners']; + } + + /** + * @param array $events An array of orphaned events + * + * @see TraceableEventDispatcher + */ + public function setOrphanedEvents(array $events) + { + $this->data['orphaned_events'] = $events; + } + + /** + * @see TraceableEventDispatcher + * + * @return array|Data + */ + public function getOrphanedEvents() + { + return $this->data['orphaned_events']; + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'events'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/ExceptionDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/ExceptionDataCollector.php new file mode 100644 index 0000000..d93b813 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/ExceptionDataCollector.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\ErrorHandler\Exception\FlattenException; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * @author Fabien Potencier + * + * @final + */ +class ExceptionDataCollector extends DataCollector +{ + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + if (null !== $exception) { + $this->data = [ + 'exception' => FlattenException::createFromThrowable($exception), + ]; + } + } + + /** + * {@inheritdoc} + */ + public function reset() + { + $this->data = []; + } + + public function hasException(): bool + { + return isset($this->data['exception']); + } + + /** + * @return \Exception|FlattenException + */ + public function getException() + { + return $this->data['exception']; + } + + public function getMessage(): string + { + return $this->data['exception']->getMessage(); + } + + public function getCode(): int + { + return $this->data['exception']->getCode(); + } + + public function getStatusCode(): int + { + return $this->data['exception']->getStatusCode(); + } + + public function getTrace(): array + { + return $this->data['exception']->getTrace(); + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'exception'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/LateDataCollectorInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/LateDataCollectorInterface.php new file mode 100644 index 0000000..012332d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/LateDataCollectorInterface.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +/** + * LateDataCollectorInterface. + * + * @author Fabien Potencier + */ +interface LateDataCollectorInterface +{ + /** + * Collects data as late as possible. + */ + public function lateCollect(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/LoggerDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/LoggerDataCollector.php new file mode 100644 index 0000000..0d6df48 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/LoggerDataCollector.php @@ -0,0 +1,358 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; + +/** + * @author Fabien Potencier + * + * @final + */ +class LoggerDataCollector extends DataCollector implements LateDataCollectorInterface +{ + private $logger; + private $containerPathPrefix; + private $currentRequest; + private $requestStack; + private $processedLogs; + + public function __construct(?object $logger = null, ?string $containerPathPrefix = null, ?RequestStack $requestStack = null) + { + if (null !== $logger && $logger instanceof DebugLoggerInterface) { + $this->logger = $logger; + } + + $this->containerPathPrefix = $containerPathPrefix; + $this->requestStack = $requestStack; + } + + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + $this->currentRequest = $this->requestStack && $this->requestStack->getMainRequest() !== $request ? $request : null; + } + + /** + * {@inheritdoc} + */ + public function reset() + { + if ($this->logger instanceof DebugLoggerInterface) { + $this->logger->clear(); + } + $this->data = []; + } + + /** + * {@inheritdoc} + */ + public function lateCollect() + { + if (null !== $this->logger) { + $containerDeprecationLogs = $this->getContainerDeprecationLogs(); + $this->data = $this->computeErrorsCount($containerDeprecationLogs); + // get compiler logs later (only when they are needed) to improve performance + $this->data['compiler_logs'] = []; + $this->data['compiler_logs_filepath'] = $this->containerPathPrefix.'Compiler.log'; + $this->data['logs'] = $this->sanitizeLogs(array_merge($this->logger->getLogs($this->currentRequest), $containerDeprecationLogs)); + $this->data = $this->cloneVar($this->data); + } + $this->currentRequest = null; + } + + public function getLogs() + { + return $this->data['logs'] ?? []; + } + + public function getProcessedLogs() + { + if (null !== $this->processedLogs) { + return $this->processedLogs; + } + + $rawLogs = $this->getLogs(); + if ([] === $rawLogs) { + return $this->processedLogs = $rawLogs; + } + + $logs = []; + foreach ($this->getLogs()->getValue() as $rawLog) { + $rawLogData = $rawLog->getValue(); + + if ($rawLogData['priority']->getValue() > 300) { + $logType = 'error'; + } elseif (isset($rawLogData['scream']) && false === $rawLogData['scream']->getValue()) { + $logType = 'deprecation'; + } elseif (isset($rawLogData['scream']) && true === $rawLogData['scream']->getValue()) { + $logType = 'silenced'; + } else { + $logType = 'regular'; + } + + $logs[] = [ + 'type' => $logType, + 'errorCount' => $rawLog['errorCount'] ?? 1, + 'timestamp' => $rawLogData['timestamp_rfc3339']->getValue(), + 'priority' => $rawLogData['priority']->getValue(), + 'priorityName' => $rawLogData['priorityName']->getValue(), + 'channel' => $rawLogData['channel']->getValue(), + 'message' => $rawLogData['message'], + 'context' => $rawLogData['context'], + ]; + } + + // sort logs from oldest to newest + usort($logs, static function ($logA, $logB) { + return $logA['timestamp'] <=> $logB['timestamp']; + }); + + return $this->processedLogs = $logs; + } + + public function getFilters() + { + $filters = [ + 'channel' => [], + 'priority' => [ + 'Debug' => 100, + 'Info' => 200, + 'Notice' => 250, + 'Warning' => 300, + 'Error' => 400, + 'Critical' => 500, + 'Alert' => 550, + 'Emergency' => 600, + ], + ]; + + $allChannels = []; + foreach ($this->getProcessedLogs() as $log) { + if ('' === trim($log['channel'] ?? '')) { + continue; + } + + $allChannels[] = $log['channel']; + } + $channels = array_unique($allChannels); + sort($channels); + $filters['channel'] = $channels; + + return $filters; + } + + public function getPriorities() + { + return $this->data['priorities'] ?? []; + } + + public function countErrors() + { + return $this->data['error_count'] ?? 0; + } + + public function countDeprecations() + { + return $this->data['deprecation_count'] ?? 0; + } + + public function countWarnings() + { + return $this->data['warning_count'] ?? 0; + } + + public function countScreams() + { + return $this->data['scream_count'] ?? 0; + } + + public function getCompilerLogs() + { + return $this->cloneVar($this->getContainerCompilerLogs($this->data['compiler_logs_filepath'] ?? null)); + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'logger'; + } + + private function getContainerDeprecationLogs(): array + { + if (null === $this->containerPathPrefix || !is_file($file = $this->containerPathPrefix.'Deprecations.log')) { + return []; + } + + if ('' === $logContent = trim(file_get_contents($file))) { + return []; + } + + $bootTime = filemtime($file); + $logs = []; + foreach (unserialize($logContent) as $log) { + $log['context'] = ['exception' => new SilencedErrorContext($log['type'], $log['file'], $log['line'], $log['trace'], $log['count'])]; + $log['timestamp'] = $bootTime; + $log['timestamp_rfc3339'] = (new \DateTimeImmutable())->setTimestamp($bootTime)->format(\DateTimeInterface::RFC3339_EXTENDED); + $log['priority'] = 100; + $log['priorityName'] = 'DEBUG'; + $log['channel'] = null; + $log['scream'] = false; + unset($log['type'], $log['file'], $log['line'], $log['trace'], $log['trace'], $log['count']); + $logs[] = $log; + } + + return $logs; + } + + private function getContainerCompilerLogs(?string $compilerLogsFilepath = null): array + { + if (!$compilerLogsFilepath || !is_file($compilerLogsFilepath)) { + return []; + } + + $logs = []; + foreach (file($compilerLogsFilepath, \FILE_IGNORE_NEW_LINES) as $log) { + $log = explode(': ', $log, 2); + if (!isset($log[1]) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)++$/', $log[0])) { + $log = ['Unknown Compiler Pass', implode(': ', $log)]; + } + + $logs[$log[0]][] = ['message' => $log[1]]; + } + + return $logs; + } + + private function sanitizeLogs(array $logs) + { + $sanitizedLogs = []; + $silencedLogs = []; + + foreach ($logs as $log) { + if (!$this->isSilencedOrDeprecationErrorLog($log)) { + $sanitizedLogs[] = $log; + + continue; + } + + $message = '_'.$log['message']; + $exception = $log['context']['exception']; + + if ($exception instanceof SilencedErrorContext) { + if (isset($silencedLogs[$h = spl_object_hash($exception)])) { + continue; + } + $silencedLogs[$h] = true; + + if (!isset($sanitizedLogs[$message])) { + $sanitizedLogs[$message] = $log + [ + 'errorCount' => 0, + 'scream' => true, + ]; + } + $sanitizedLogs[$message]['errorCount'] += $exception->count; + + continue; + } + + $errorId = md5("{$exception->getSeverity()}/{$exception->getLine()}/{$exception->getFile()}\0{$message}", true); + + if (isset($sanitizedLogs[$errorId])) { + ++$sanitizedLogs[$errorId]['errorCount']; + } else { + $log += [ + 'errorCount' => 1, + 'scream' => false, + ]; + + $sanitizedLogs[$errorId] = $log; + } + } + + return array_values($sanitizedLogs); + } + + private function isSilencedOrDeprecationErrorLog(array $log): bool + { + if (!isset($log['context']['exception'])) { + return false; + } + + $exception = $log['context']['exception']; + + if ($exception instanceof SilencedErrorContext) { + return true; + } + + if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), [\E_DEPRECATED, \E_USER_DEPRECATED], true)) { + return true; + } + + return false; + } + + private function computeErrorsCount(array $containerDeprecationLogs): array + { + $silencedLogs = []; + $count = [ + 'error_count' => $this->logger->countErrors($this->currentRequest), + 'deprecation_count' => 0, + 'warning_count' => 0, + 'scream_count' => 0, + 'priorities' => [], + ]; + + foreach ($this->logger->getLogs($this->currentRequest) as $log) { + if (isset($count['priorities'][$log['priority']])) { + ++$count['priorities'][$log['priority']]['count']; + } else { + $count['priorities'][$log['priority']] = [ + 'count' => 1, + 'name' => $log['priorityName'], + ]; + } + if ('WARNING' === $log['priorityName']) { + ++$count['warning_count']; + } + + if ($this->isSilencedOrDeprecationErrorLog($log)) { + $exception = $log['context']['exception']; + if ($exception instanceof SilencedErrorContext) { + if (isset($silencedLogs[$h = spl_object_hash($exception)])) { + continue; + } + $silencedLogs[$h] = true; + $count['scream_count'] += $exception->count; + } else { + ++$count['deprecation_count']; + } + } + } + + foreach ($containerDeprecationLogs as $deprecationLog) { + $count['deprecation_count'] += $deprecationLog['context']['exception']->count; + } + + ksort($count['priorities']); + + return $count; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/MemoryDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/MemoryDataCollector.php new file mode 100644 index 0000000..62d048a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/MemoryDataCollector.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 Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * @author Fabien Potencier + * + * @final + */ +class MemoryDataCollector extends DataCollector implements LateDataCollectorInterface +{ + public function __construct() + { + $this->reset(); + } + + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + $this->updateMemoryUsage(); + } + + /** + * {@inheritdoc} + */ + public function reset() + { + $this->data = [ + 'memory' => 0, + 'memory_limit' => $this->convertToBytes(\ini_get('memory_limit')), + ]; + } + + /** + * {@inheritdoc} + */ + public function lateCollect() + { + $this->updateMemoryUsage(); + } + + public function getMemory(): int + { + return $this->data['memory']; + } + + /** + * @return int|float + */ + public function getMemoryLimit() + { + return $this->data['memory_limit']; + } + + public function updateMemoryUsage() + { + $this->data['memory'] = memory_get_peak_usage(true); + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'memory'; + } + + /** + * @return int|float + */ + private function convertToBytes(string $memoryLimit) + { + if ('-1' === $memoryLimit) { + return -1; + } + + $memoryLimit = strtolower($memoryLimit); + $max = strtolower(ltrim($memoryLimit, '+')); + if (str_starts_with($max, '0x')) { + $max = \intval($max, 16); + } elseif (str_starts_with($max, '0')) { + $max = \intval($max, 8); + } else { + $max = (int) $max; + } + + switch (substr($memoryLimit, -1)) { + case 't': $max *= 1024; + // no break + case 'g': $max *= 1024; + // no break + case 'm': $max *= 1024; + // no break + case 'k': $max *= 1024; + } + + return $max; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/RequestDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/RequestDataCollector.php new file mode 100644 index 0000000..c56013c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/RequestDataCollector.php @@ -0,0 +1,504 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Cookie; +use Symfony\Component\HttpFoundation\ParameterBag; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionBagInterface; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpKernel\Event\ControllerEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\VarDumper\Cloner\Data; + +/** + * @author Fabien Potencier + * + * @final + */ +class RequestDataCollector extends DataCollector implements EventSubscriberInterface, LateDataCollectorInterface +{ + /** + * @var \SplObjectStorage + */ + private $controllers; + private $sessionUsages = []; + private $requestStack; + + public function __construct(?RequestStack $requestStack = null) + { + $this->controllers = new \SplObjectStorage(); + $this->requestStack = $requestStack; + } + + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + // attributes are serialized and as they can be anything, they need to be converted to strings. + $attributes = []; + $route = ''; + foreach ($request->attributes->all() as $key => $value) { + if ('_route' === $key) { + $route = \is_object($value) ? $value->getPath() : $value; + $attributes[$key] = $route; + } else { + $attributes[$key] = $value; + } + } + + $content = $request->getContent(); + + $sessionMetadata = []; + $sessionAttributes = []; + $flashes = []; + if ($request->hasSession()) { + $session = $request->getSession(); + if ($session->isStarted()) { + $sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated()); + $sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed()); + $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime(); + $sessionAttributes = $session->all(); + $flashes = $session->getFlashBag()->peekAll(); + } + } + + $statusCode = $response->getStatusCode(); + + $responseCookies = []; + foreach ($response->headers->getCookies() as $cookie) { + $responseCookies[$cookie->getName()] = $cookie; + } + + $dotenvVars = []; + foreach (explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? $_ENV['SYMFONY_DOTENV_VARS'] ?? '') as $name) { + if ('' !== $name && isset($_ENV[$name])) { + $dotenvVars[$name] = $_ENV[$name]; + } + } + + $this->data = [ + 'method' => $request->getMethod(), + 'format' => $request->getRequestFormat(), + 'content_type' => $response->headers->get('Content-Type', 'text/html'), + 'status_text' => Response::$statusTexts[$statusCode] ?? '', + 'status_code' => $statusCode, + 'request_query' => $request->query->all(), + 'request_request' => $request->request->all(), + 'request_files' => $request->files->all(), + 'request_headers' => $request->headers->all(), + 'request_server' => $request->server->all(), + 'request_cookies' => $request->cookies->all(), + 'request_attributes' => $attributes, + 'route' => $route, + 'response_headers' => $response->headers->all(), + 'response_cookies' => $responseCookies, + 'session_metadata' => $sessionMetadata, + 'session_attributes' => $sessionAttributes, + 'session_usages' => array_values($this->sessionUsages), + 'stateless_check' => $this->requestStack && ($mainRequest = $this->requestStack->getMainRequest()) && $mainRequest->attributes->get('_stateless', false), + 'flashes' => $flashes, + 'path_info' => $request->getPathInfo(), + 'controller' => 'n/a', + 'locale' => $request->getLocale(), + 'dotenv_vars' => $dotenvVars, + ]; + + if (isset($this->data['request_headers']['php-auth-pw'])) { + $this->data['request_headers']['php-auth-pw'] = '******'; + } + + if (isset($this->data['request_server']['PHP_AUTH_PW'])) { + $this->data['request_server']['PHP_AUTH_PW'] = '******'; + } + + if (isset($this->data['request_request']['_password'])) { + $encodedPassword = rawurlencode($this->data['request_request']['_password']); + $content = str_replace('_password='.$encodedPassword, '_password=******', $content); + $this->data['request_request']['_password'] = '******'; + } + + $this->data['content'] = $content; + + foreach ($this->data as $key => $value) { + if (!\is_array($value)) { + continue; + } + if ('request_headers' === $key || 'response_headers' === $key) { + $this->data[$key] = array_map(function ($v) { return isset($v[0]) && !isset($v[1]) ? $v[0] : $v; }, $value); + } + } + + if (isset($this->controllers[$request])) { + $this->data['controller'] = $this->parseController($this->controllers[$request]); + unset($this->controllers[$request]); + } + + if ($request->attributes->has('_redirected') && $redirectCookie = $request->cookies->get('sf_redirect')) { + $this->data['redirect'] = json_decode($redirectCookie, true); + + $response->headers->clearCookie('sf_redirect'); + } + + if ($response->isRedirect()) { + $response->headers->setCookie(new Cookie( + 'sf_redirect', + json_encode([ + 'token' => $response->headers->get('x-debug-token'), + 'route' => $request->attributes->get('_route', 'n/a'), + 'method' => $request->getMethod(), + 'controller' => $this->parseController($request->attributes->get('_controller')), + 'status_code' => $statusCode, + 'status_text' => Response::$statusTexts[$statusCode], + ]), + 0, '/', null, $request->isSecure(), true, false, 'lax' + )); + } + + $this->data['identifier'] = $this->data['route'] ?: (\is_array($this->data['controller']) ? $this->data['controller']['class'].'::'.$this->data['controller']['method'].'()' : $this->data['controller']); + + if ($response->headers->has('x-previous-debug-token')) { + $this->data['forward_token'] = $response->headers->get('x-previous-debug-token'); + } + } + + public function lateCollect() + { + $this->data = $this->cloneVar($this->data); + } + + public function reset() + { + $this->data = []; + $this->controllers = new \SplObjectStorage(); + $this->sessionUsages = []; + } + + public function getMethod() + { + return $this->data['method']; + } + + public function getPathInfo() + { + return $this->data['path_info']; + } + + public function getRequestRequest() + { + return new ParameterBag($this->data['request_request']->getValue()); + } + + public function getRequestQuery() + { + return new ParameterBag($this->data['request_query']->getValue()); + } + + public function getRequestFiles() + { + return new ParameterBag($this->data['request_files']->getValue()); + } + + public function getRequestHeaders() + { + return new ParameterBag($this->data['request_headers']->getValue()); + } + + public function getRequestServer(bool $raw = false) + { + return new ParameterBag($this->data['request_server']->getValue($raw)); + } + + public function getRequestCookies(bool $raw = false) + { + return new ParameterBag($this->data['request_cookies']->getValue($raw)); + } + + public function getRequestAttributes() + { + return new ParameterBag($this->data['request_attributes']->getValue()); + } + + public function getResponseHeaders() + { + return new ParameterBag($this->data['response_headers']->getValue()); + } + + public function getResponseCookies() + { + return new ParameterBag($this->data['response_cookies']->getValue()); + } + + public function getSessionMetadata() + { + return $this->data['session_metadata']->getValue(); + } + + public function getSessionAttributes() + { + return $this->data['session_attributes']->getValue(); + } + + public function getStatelessCheck() + { + return $this->data['stateless_check']; + } + + public function getSessionUsages() + { + return $this->data['session_usages']; + } + + public function getFlashes() + { + return $this->data['flashes']->getValue(); + } + + public function getContent() + { + return $this->data['content']; + } + + public function isJsonRequest() + { + return 1 === preg_match('{^application/(?:\w+\++)*json$}i', $this->data['request_headers']['content-type']); + } + + public function getPrettyJson() + { + $decoded = json_decode($this->getContent()); + + return \JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, \JSON_PRETTY_PRINT) : null; + } + + public function getContentType() + { + return $this->data['content_type']; + } + + public function getStatusText() + { + return $this->data['status_text']; + } + + public function getStatusCode() + { + return $this->data['status_code']; + } + + public function getFormat() + { + return $this->data['format']; + } + + public function getLocale() + { + return $this->data['locale']; + } + + public function getDotenvVars() + { + return new ParameterBag($this->data['dotenv_vars']->getValue()); + } + + /** + * Gets the route name. + * + * The _route request attributes is automatically set by the Router Matcher. + */ + public function getRoute(): string + { + return $this->data['route']; + } + + public function getIdentifier() + { + return $this->data['identifier']; + } + + /** + * Gets the route parameters. + * + * The _route_params request attributes is automatically set by the RouterListener. + */ + public function getRouteParams(): array + { + return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : []; + } + + /** + * Gets the parsed controller. + * + * @return array|string|Data The controller as a string or array of data + * with keys 'class', 'method', 'file' and 'line' + */ + public function getController() + { + return $this->data['controller']; + } + + /** + * Gets the previous request attributes. + * + * @return array|Data|false A legacy array of data from the previous redirection response + * or false otherwise + */ + public function getRedirect() + { + return $this->data['redirect'] ?? false; + } + + public function getForwardToken() + { + return $this->data['forward_token'] ?? null; + } + + public function onKernelController(ControllerEvent $event) + { + $this->controllers[$event->getRequest()] = $event->getController(); + } + + public function onKernelResponse(ResponseEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + if ($event->getRequest()->cookies->has('sf_redirect')) { + $event->getRequest()->attributes->set('_redirected', true); + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::CONTROLLER => 'onKernelController', + KernelEvents::RESPONSE => 'onKernelResponse', + ]; + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'request'; + } + + public function collectSessionUsage(): void + { + $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + + $traceEndIndex = \count($trace) - 1; + for ($i = $traceEndIndex; $i > 0; --$i) { + if (null !== ($class = $trace[$i]['class'] ?? null) && (is_subclass_of($class, SessionInterface::class) || is_subclass_of($class, SessionBagInterface::class))) { + $traceEndIndex = $i; + break; + } + } + + if ((\count($trace) - 1) === $traceEndIndex) { + return; + } + + // Remove part of the backtrace that belongs to session only + array_splice($trace, 0, $traceEndIndex); + + // Merge identical backtraces generated by internal call reports + $name = sprintf('%s:%s', $trace[1]['class'] ?? $trace[0]['file'], $trace[0]['line']); + if (!\array_key_exists($name, $this->sessionUsages)) { + $this->sessionUsages[$name] = [ + 'name' => $name, + 'file' => $trace[0]['file'], + 'line' => $trace[0]['line'], + 'trace' => $trace, + ]; + } + } + + /** + * @param string|object|array|null $controller The controller to parse + * + * @return array|string An array of controller data or a simple string + */ + private function parseController($controller) + { + if (\is_string($controller) && str_contains($controller, '::')) { + $controller = explode('::', $controller); + } + + if (\is_array($controller)) { + try { + $r = new \ReflectionMethod($controller[0], $controller[1]); + + return [ + 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0], + 'method' => $controller[1], + 'file' => $r->getFileName(), + 'line' => $r->getStartLine(), + ]; + } catch (\ReflectionException $e) { + if (\is_callable($controller)) { + // using __call or __callStatic + return [ + 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0], + 'method' => $controller[1], + 'file' => 'n/a', + 'line' => 'n/a', + ]; + } + } + } + + if ($controller instanceof \Closure) { + $r = new \ReflectionFunction($controller); + + $controller = [ + 'class' => $r->getName(), + 'method' => null, + 'file' => $r->getFileName(), + 'line' => $r->getStartLine(), + ]; + + if (str_contains($r->name, '{closure}')) { + return $controller; + } + $controller['method'] = $r->name; + + if ($class = \PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass()) { + $controller['class'] = $class->name; + } else { + return $r->name; + } + + return $controller; + } + + if (\is_object($controller)) { + $r = new \ReflectionClass($controller); + + return [ + 'class' => $r->getName(), + 'method' => null, + 'file' => $r->getFileName(), + 'line' => $r->getStartLine(), + ]; + } + + return \is_string($controller) ? $controller : 'n/a'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/RouterDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/RouterDataCollector.php new file mode 100644 index 0000000..f3735fe --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/RouterDataCollector.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\RedirectResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Event\ControllerEvent; + +/** + * @author Fabien Potencier + */ +class RouterDataCollector extends DataCollector +{ + /** + * @var \SplObjectStorage + */ + protected $controllers; + + public function __construct() + { + $this->reset(); + } + + /** + * {@inheritdoc} + * + * @final + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + if ($response instanceof RedirectResponse) { + $this->data['redirect'] = true; + $this->data['url'] = $response->getTargetUrl(); + + if ($this->controllers->contains($request)) { + $this->data['route'] = $this->guessRoute($request, $this->controllers[$request]); + } + } + + unset($this->controllers[$request]); + } + + public function reset() + { + $this->controllers = new \SplObjectStorage(); + + $this->data = [ + 'redirect' => false, + 'url' => null, + 'route' => null, + ]; + } + + protected function guessRoute(Request $request, $controller) + { + return 'n/a'; + } + + /** + * Remembers the controller associated to each request. + */ + public function onKernelController(ControllerEvent $event) + { + $this->controllers[$event->getRequest()] = $event->getController(); + } + + /** + * @return bool Whether this request will result in a redirect + */ + public function getRedirect() + { + return $this->data['redirect']; + } + + /** + * @return string|null + */ + public function getTargetUrl() + { + return $this->data['url']; + } + + /** + * @return string|null + */ + public function getTargetRoute() + { + return $this->data['route']; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'router'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/TimeDataCollector.php b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/TimeDataCollector.php new file mode 100644 index 0000000..13a62e6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DataCollector/TimeDataCollector.php @@ -0,0 +1,144 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\KernelInterface; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\Stopwatch\StopwatchEvent; + +/** + * @author Fabien Potencier + * + * @final + */ +class TimeDataCollector extends DataCollector implements LateDataCollectorInterface +{ + private $kernel; + private $stopwatch; + + public function __construct(?KernelInterface $kernel = null, ?Stopwatch $stopwatch = null) + { + $this->kernel = $kernel; + $this->stopwatch = $stopwatch; + $this->data = ['events' => [], 'stopwatch_installed' => false, 'start_time' => 0]; + } + + /** + * {@inheritdoc} + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + if (null !== $this->kernel) { + $startTime = $this->kernel->getStartTime(); + } else { + $startTime = $request->server->get('REQUEST_TIME_FLOAT'); + } + + $this->data = [ + 'token' => $request->attributes->get('_stopwatch_token'), + 'start_time' => $startTime * 1000, + 'events' => [], + 'stopwatch_installed' => class_exists(Stopwatch::class, false), + ]; + } + + /** + * {@inheritdoc} + */ + public function reset() + { + $this->data = ['events' => [], 'stopwatch_installed' => false, 'start_time' => 0]; + + if (null !== $this->stopwatch) { + $this->stopwatch->reset(); + } + } + + /** + * {@inheritdoc} + */ + public function lateCollect() + { + if (null !== $this->stopwatch && isset($this->data['token'])) { + $this->setEvents($this->stopwatch->getSectionEvents($this->data['token'])); + } + unset($this->data['token']); + } + + /** + * @param StopwatchEvent[] $events The request events + */ + public function setEvents(array $events) + { + foreach ($events as $event) { + $event->ensureStopped(); + } + + $this->data['events'] = $events; + } + + /** + * @return StopwatchEvent[] + */ + public function getEvents(): array + { + return $this->data['events']; + } + + /** + * Gets the request elapsed time. + */ + public function getDuration(): float + { + if (!isset($this->data['events']['__section__'])) { + return 0; + } + + $lastEvent = $this->data['events']['__section__']; + + return $lastEvent->getOrigin() + $lastEvent->getDuration() - $this->getStartTime(); + } + + /** + * Gets the initialization time. + * + * This is the time spent until the beginning of the request handling. + */ + public function getInitTime(): float + { + if (!isset($this->data['events']['__section__'])) { + return 0; + } + + return $this->data['events']['__section__']->getOrigin() - $this->getStartTime(); + } + + public function getStartTime(): float + { + return $this->data['start_time']; + } + + public function isStopwatchInstalled(): bool + { + return $this->data['stopwatch_installed']; + } + + /** + * {@inheritdoc} + */ + public function getName(): string + { + return 'time'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Debug/FileLinkFormatter.php b/php/libraries/composer/vendor/symfony/http-kernel/Debug/FileLinkFormatter.php new file mode 100644 index 0000000..8ec7e38 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Debug/FileLinkFormatter.php @@ -0,0 +1,116 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Debug; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; + +/** + * Formats debug file links. + * + * @author Jérémy Romey + * + * @final + */ +class FileLinkFormatter +{ + private const FORMATS = [ + 'textmate' => 'txmt://open?url=file://%f&line=%l', + 'macvim' => 'mvim://open?url=file://%f&line=%l', + 'emacs' => 'emacs://open?url=file://%f&line=%l', + 'sublime' => 'subl://open?url=file://%f&line=%l', + 'phpstorm' => 'phpstorm://open?file=%f&line=%l', + 'atom' => 'atom://core/open/file?filename=%f&line=%l', + 'vscode' => 'vscode://file/%f:%l', + ]; + + private $fileLinkFormat; + private $requestStack; + private $baseDir; + private $urlFormat; + + /** + * @param string|array|null $fileLinkFormat + * @param string|\Closure $urlFormat the URL format, or a closure that returns it on-demand + */ + public function __construct($fileLinkFormat = null, ?RequestStack $requestStack = null, ?string $baseDir = null, $urlFormat = null) + { + if (!\is_array($fileLinkFormat) && $fileLinkFormat = (self::FORMATS[$fileLinkFormat] ?? $fileLinkFormat) ?: \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')) { + $i = strpos($f = $fileLinkFormat, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: \strlen($f); + $fileLinkFormat = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, \PREG_SPLIT_DELIM_CAPTURE); + } + + $this->fileLinkFormat = $fileLinkFormat; + $this->requestStack = $requestStack; + $this->baseDir = $baseDir; + $this->urlFormat = $urlFormat; + } + + public function format(string $file, int $line) + { + if ($fmt = $this->getFileLinkFormat()) { + for ($i = 1; isset($fmt[$i]); ++$i) { + if (str_starts_with($file, $k = $fmt[$i++])) { + $file = substr_replace($file, $fmt[$i], 0, \strlen($k)); + break; + } + } + + return strtr($fmt[0], ['%f' => $file, '%l' => $line]); + } + + return false; + } + + /** + * @internal + */ + public function __sleep(): array + { + $this->fileLinkFormat = $this->getFileLinkFormat(); + + return ['fileLinkFormat']; + } + + /** + * @internal + */ + public static function generateUrlFormat(UrlGeneratorInterface $router, string $routeName, string $queryString): ?string + { + try { + return $router->generate($routeName).$queryString; + } catch (\Throwable $e) { + return null; + } + } + + private function getFileLinkFormat() + { + if ($this->fileLinkFormat) { + return $this->fileLinkFormat; + } + + if ($this->requestStack && $this->baseDir && $this->urlFormat) { + $request = $this->requestStack->getMainRequest(); + + if ($request instanceof Request && (!$this->urlFormat instanceof \Closure || $this->urlFormat = ($this->urlFormat)())) { + return [ + $request->getSchemeAndHttpHost().$this->urlFormat, + $this->baseDir.\DIRECTORY_SEPARATOR, '', + ]; + } + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Debug/TraceableEventDispatcher.php b/php/libraries/composer/vendor/symfony/http-kernel/Debug/TraceableEventDispatcher.php new file mode 100644 index 0000000..fd1cf9e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Debug/TraceableEventDispatcher.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Debug; + +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher as BaseTraceableEventDispatcher; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Collects some data about event listeners. + * + * This event dispatcher delegates the dispatching to another one. + * + * @author Fabien Potencier + */ +class TraceableEventDispatcher extends BaseTraceableEventDispatcher +{ + /** + * {@inheritdoc} + */ + protected function beforeDispatch(string $eventName, object $event) + { + switch ($eventName) { + case KernelEvents::REQUEST: + $event->getRequest()->attributes->set('_stopwatch_token', substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6)); + $this->stopwatch->openSection(); + break; + case KernelEvents::VIEW: + case KernelEvents::RESPONSE: + // stop only if a controller has been executed + if ($this->stopwatch->isStarted('controller')) { + $this->stopwatch->stop('controller'); + } + break; + case KernelEvents::TERMINATE: + $sectionId = $event->getRequest()->attributes->get('_stopwatch_token'); + if (null === $sectionId) { + break; + } + // There is a very special case when using built-in AppCache class as kernel wrapper, in the case + // of an ESI request leading to a `stale` response [B] inside a `fresh` cached response [A]. + // In this case, `$token` contains the [B] debug token, but the open `stopwatch` section ID + // is equal to the [A] debug token. Trying to reopen section with the [B] token throws an exception + // which must be caught. + try { + $this->stopwatch->openSection($sectionId); + } catch (\LogicException $e) { + } + break; + } + } + + /** + * {@inheritdoc} + */ + protected function afterDispatch(string $eventName, object $event) + { + switch ($eventName) { + case KernelEvents::CONTROLLER_ARGUMENTS: + $this->stopwatch->start('controller', 'section'); + break; + case KernelEvents::RESPONSE: + $sectionId = $event->getRequest()->attributes->get('_stopwatch_token'); + if (null === $sectionId) { + break; + } + $this->stopwatch->stopSection($sectionId); + break; + case KernelEvents::TERMINATE: + // In the special case described in the `preDispatch` method above, the `$token` section + // does not exist, then closing it throws an exception which must be caught. + $sectionId = $event->getRequest()->attributes->get('_stopwatch_token'); + if (null === $sectionId) { + break; + } + try { + $this->stopwatch->stopSection($sectionId); + } catch (\LogicException $e) { + } + break; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/AddAnnotatedClassesToCachePass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/AddAnnotatedClassesToCachePass.php new file mode 100644 index 0000000..4bb60b4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/AddAnnotatedClassesToCachePass.php @@ -0,0 +1,146 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Composer\Autoload\ClassLoader; +use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\ErrorHandler\DebugClassLoader; +use Symfony\Component\HttpKernel\Kernel; + +/** + * Sets the classes to compile in the cache for the container. + * + * @author Fabien Potencier + */ +class AddAnnotatedClassesToCachePass implements CompilerPassInterface +{ + private $kernel; + + public function __construct(Kernel $kernel) + { + $this->kernel = $kernel; + } + + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + $annotatedClasses = []; + foreach ($container->getExtensions() as $extension) { + if ($extension instanceof Extension) { + $annotatedClasses[] = $extension->getAnnotatedClassesToCompile(); + } + } + + $annotatedClasses = array_merge($this->kernel->getAnnotatedClassesToCompile(), ...$annotatedClasses); + + $existingClasses = $this->getClassesInComposerClassMaps(); + + $annotatedClasses = $container->getParameterBag()->resolveValue($annotatedClasses); + $this->kernel->setAnnotatedClassCache($this->expandClasses($annotatedClasses, $existingClasses)); + } + + /** + * Expands the given class patterns using a list of existing classes. + * + * @param array $patterns The class patterns to expand + * @param array $classes The existing classes to match against the patterns + */ + private function expandClasses(array $patterns, array $classes): array + { + $expanded = []; + + // Explicit classes declared in the patterns are returned directly + foreach ($patterns as $key => $pattern) { + if (!str_ends_with($pattern, '\\') && !str_contains($pattern, '*')) { + unset($patterns[$key]); + $expanded[] = ltrim($pattern, '\\'); + } + } + + // Match patterns with the classes list + $regexps = $this->patternsToRegexps($patterns); + + foreach ($classes as $class) { + $class = ltrim($class, '\\'); + + if ($this->matchAnyRegexps($class, $regexps)) { + $expanded[] = $class; + } + } + + return array_unique($expanded); + } + + private function getClassesInComposerClassMaps(): array + { + $classes = []; + + foreach (spl_autoload_functions() as $function) { + if (!\is_array($function)) { + continue; + } + + if ($function[0] instanceof DebugClassLoader || $function[0] instanceof LegacyDebugClassLoader) { + $function = $function[0]->getClassLoader(); + } + + if (\is_array($function) && $function[0] instanceof ClassLoader) { + $classes += array_filter($function[0]->getClassMap()); + } + } + + return array_keys($classes); + } + + private function patternsToRegexps(array $patterns): array + { + $regexps = []; + + foreach ($patterns as $pattern) { + // Escape user input + $regex = preg_quote(ltrim($pattern, '\\')); + + // Wildcards * and ** + $regex = strtr($regex, ['\\*\\*' => '.*?', '\\*' => '[^\\\\]*?']); + + // If this class does not end by a slash, anchor the end + if ('\\' !== substr($regex, -1)) { + $regex .= '$'; + } + + $regexps[] = '{^\\\\'.$regex.'}'; + } + + return $regexps; + } + + private function matchAnyRegexps(string $class, array $regexps): bool + { + $isTest = str_contains($class, 'Test'); + + foreach ($regexps as $regex) { + if ($isTest && !str_contains($regex, 'Test')) { + continue; + } + + if (preg_match($regex, '\\'.$class)) { + return true; + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ConfigurableExtension.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ConfigurableExtension.php new file mode 100644 index 0000000..072c35f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ConfigurableExtension.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * This extension sub-class provides first-class integration with the + * Config/Definition Component. + * + * You can use this as base class if + * + * a) you use the Config/Definition component for configuration, + * b) your configuration class is named "Configuration", and + * c) the configuration class resides in the DependencyInjection sub-folder. + * + * @author Johannes M. Schmitt + */ +abstract class ConfigurableExtension extends Extension +{ + /** + * {@inheritdoc} + */ + final public function load(array $configs, ContainerBuilder $container) + { + $this->loadInternal($this->processConfiguration($this->getConfiguration($configs, $container), $configs), $container); + } + + /** + * Configures the passed container according to the merged configuration. + */ + abstract protected function loadInternal(array $mergedConfig, ContainerBuilder $container); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ControllerArgumentValueResolverPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ControllerArgumentValueResolverPass.php new file mode 100644 index 0000000..d925ed6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ControllerArgumentValueResolverPass.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Argument\IteratorArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\TraceableValueResolver; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * Gathers and configures the argument value resolvers. + * + * @author Iltar van der Berg + */ +class ControllerArgumentValueResolverPass implements CompilerPassInterface +{ + use PriorityTaggedServiceTrait; + + private $argumentResolverService; + private $argumentValueResolverTag; + private $traceableResolverStopwatch; + + public function __construct(string $argumentResolverService = 'argument_resolver', string $argumentValueResolverTag = 'controller.argument_value_resolver', string $traceableResolverStopwatch = 'debug.stopwatch') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->argumentResolverService = $argumentResolverService; + $this->argumentValueResolverTag = $argumentValueResolverTag; + $this->traceableResolverStopwatch = $traceableResolverStopwatch; + } + + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition($this->argumentResolverService)) { + return; + } + + $resolvers = $this->findAndSortTaggedServices($this->argumentValueResolverTag, $container); + + if ($container->getParameter('kernel.debug') && class_exists(Stopwatch::class) && $container->has($this->traceableResolverStopwatch)) { + foreach ($resolvers as $resolverReference) { + $id = (string) $resolverReference; + $container->register("debug.$id", TraceableValueResolver::class) + ->setDecoratedService($id) + ->setArguments([new Reference("debug.$id.inner"), new Reference($this->traceableResolverStopwatch)]); + } + } + + $container + ->getDefinition($this->argumentResolverService) + ->replaceArgument(1, new IteratorArgument($resolvers)) + ; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/Extension.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/Extension.php new file mode 100644 index 0000000..4090fd8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/Extension.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Extension\Extension as BaseExtension; + +/** + * Allow adding classes to the class cache. + * + * @author Fabien Potencier + */ +abstract class Extension extends BaseExtension +{ + private $annotatedClasses = []; + + /** + * Gets the annotated classes to cache. + * + * @return array + */ + public function getAnnotatedClassesToCompile() + { + return $this->annotatedClasses; + } + + /** + * Adds annotated classes to the class cache. + * + * @param array $annotatedClasses An array of class patterns + */ + public function addAnnotatedClassesToCompile(array $annotatedClasses) + { + $this->annotatedClasses = array_merge($this->annotatedClasses, $annotatedClasses); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/FragmentRendererPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/FragmentRendererPass.php new file mode 100644 index 0000000..f26baec --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/FragmentRendererPass.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; + +/** + * Adds services tagged kernel.fragment_renderer as HTTP content rendering strategies. + * + * @author Fabien Potencier + */ +class FragmentRendererPass implements CompilerPassInterface +{ + private $handlerService; + private $rendererTag; + + public function __construct(string $handlerService = 'fragment.handler', string $rendererTag = 'kernel.fragment_renderer') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->handlerService = $handlerService; + $this->rendererTag = $rendererTag; + } + + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition($this->handlerService)) { + return; + } + + $definition = $container->getDefinition($this->handlerService); + $renderers = []; + foreach ($container->findTaggedServiceIds($this->rendererTag, true) as $id => $tags) { + $def = $container->getDefinition($id); + $class = $container->getParameterBag()->resolveValue($def->getClass()); + + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(FragmentRendererInterface::class)) { + throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, FragmentRendererInterface::class)); + } + + foreach ($tags as $tag) { + $renderers[$tag['alias']] = new Reference($id); + } + } + + $definition->replaceArgument(0, ServiceLocatorTagPass::register($container, $renderers)); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/LazyLoadingFragmentHandler.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/LazyLoadingFragmentHandler.php new file mode 100644 index 0000000..f253287 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/LazyLoadingFragmentHandler.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\HttpKernel\DependencyInjection; + +use Psr\Container\ContainerInterface; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpKernel\Fragment\FragmentHandler; + +/** + * Lazily loads fragment renderers from the dependency injection container. + * + * @author Fabien Potencier + */ +class LazyLoadingFragmentHandler extends FragmentHandler +{ + private $container; + + /** + * @var array + */ + private $initialized = []; + + public function __construct(ContainerInterface $container, RequestStack $requestStack, bool $debug = false) + { + $this->container = $container; + + parent::__construct($requestStack, [], $debug); + } + + /** + * {@inheritdoc} + */ + public function render($uri, string $renderer = 'inline', array $options = []) + { + if (!isset($this->initialized[$renderer]) && $this->container->has($renderer)) { + $this->addRenderer($this->container->get($renderer)); + $this->initialized[$renderer] = true; + } + + return parent::render($uri, $renderer, $options); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/LoggerPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/LoggerPass.php new file mode 100644 index 0000000..b6df1f6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/LoggerPass.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\Log\Logger; + +/** + * Registers the default logger if necessary. + * + * @author Kévin Dunglas + */ +class LoggerPass implements CompilerPassInterface +{ + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + $container->setAlias(LoggerInterface::class, 'logger') + ->setPublic(false); + + if ($container->has('logger')) { + return; + } + + $container->register('logger', Logger::class) + ->setPublic(false); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/MergeExtensionConfigurationPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/MergeExtensionConfigurationPass.php new file mode 100644 index 0000000..5f0f0d8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/MergeExtensionConfigurationPass.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass as BaseMergeExtensionConfigurationPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * Ensures certain extensions are always loaded. + * + * @author Kris Wallsmith + */ +class MergeExtensionConfigurationPass extends BaseMergeExtensionConfigurationPass +{ + private $extensions; + + /** + * @param string[] $extensions + */ + public function __construct(array $extensions) + { + $this->extensions = $extensions; + } + + public function process(ContainerBuilder $container) + { + foreach ($this->extensions as $extension) { + if (!\count($container->getExtensionConfig($extension))) { + $container->loadFromExtension($extension, []); + } + } + + parent::process($container); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php new file mode 100644 index 0000000..3dbaff5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php @@ -0,0 +1,224 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\DependencyInjection\Attribute\Target; +use Symfony\Component\DependencyInjection\ChildDefinition; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; +use Symfony\Component\DependencyInjection\ContainerAwareInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\TypedReference; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +/** + * Creates the service-locators required by ServiceValueResolver. + * + * @author Nicolas Grekas + */ +class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface +{ + private $resolverServiceId; + private $controllerTag; + private $controllerLocator; + private $notTaggedControllerResolverServiceId; + + public function __construct(string $resolverServiceId = 'argument_resolver.service', string $controllerTag = 'controller.service_arguments', string $controllerLocator = 'argument_resolver.controller_locator', string $notTaggedControllerResolverServiceId = 'argument_resolver.not_tagged_controller') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->resolverServiceId = $resolverServiceId; + $this->controllerTag = $controllerTag; + $this->controllerLocator = $controllerLocator; + $this->notTaggedControllerResolverServiceId = $notTaggedControllerResolverServiceId; + } + + public function process(ContainerBuilder $container) + { + if (false === $container->hasDefinition($this->resolverServiceId) && false === $container->hasDefinition($this->notTaggedControllerResolverServiceId)) { + return; + } + + $parameterBag = $container->getParameterBag(); + $controllers = []; + + $publicAliases = []; + foreach ($container->getAliases() as $id => $alias) { + if ($alias->isPublic() && !$alias->isPrivate()) { + $publicAliases[(string) $alias][] = $id; + } + } + + foreach ($container->findTaggedServiceIds($this->controllerTag, true) as $id => $tags) { + $def = $container->getDefinition($id); + $def->setPublic(true); + $class = $def->getClass(); + $autowire = $def->isAutowired(); + $bindings = $def->getBindings(); + + // resolve service class, taking parent definitions into account + while ($def instanceof ChildDefinition) { + $def = $container->findDefinition($def->getParent()); + $class = $class ?: $def->getClass(); + $bindings += $def->getBindings(); + } + $class = $parameterBag->resolveValue($class); + + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + $isContainerAware = $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($class, AbstractController::class); + + // get regular public methods + $methods = []; + $arguments = []; + foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) { + if ('setContainer' === $r->name && $isContainerAware) { + continue; + } + if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) { + $methods[strtolower($r->name)] = [$r, $r->getParameters()]; + } + } + + // validate and collect explicit per-actions and per-arguments service references + foreach ($tags as $attributes) { + if (!isset($attributes['action']) && !isset($attributes['argument']) && !isset($attributes['id'])) { + $autowire = true; + continue; + } + foreach (['action', 'argument', 'id'] as $k) { + if (!isset($attributes[$k][0])) { + throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, \JSON_UNESCAPED_UNICODE), $id)); + } + } + if (!isset($methods[$action = strtolower($attributes['action'])])) { + throw new InvalidArgumentException(sprintf('Invalid "action" attribute on tag "%s" for service "%s": no public "%s()" method found on class "%s".', $this->controllerTag, $id, $attributes['action'], $class)); + } + [$r, $parameters] = $methods[$action]; + $found = false; + + foreach ($parameters as $p) { + if ($attributes['argument'] === $p->name) { + if (!isset($arguments[$r->name][$p->name])) { + $arguments[$r->name][$p->name] = $attributes['id']; + } + $found = true; + break; + } + } + + if (!$found) { + throw new InvalidArgumentException(sprintf('Invalid "%s" tag for service "%s": method "%s()" has no "%s" argument on class "%s".', $this->controllerTag, $id, $r->name, $attributes['argument'], $class)); + } + } + + foreach ($methods as [$r, $parameters]) { + /** @var \ReflectionMethod $r */ + + // create a per-method map of argument-names to service/type-references + $args = []; + foreach ($parameters as $p) { + /** @var \ReflectionParameter $p */ + $type = ltrim($target = (string) ProxyHelper::getTypeHint($r, $p), '\\'); + $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE; + + if (isset($arguments[$r->name][$p->name])) { + $target = $arguments[$r->name][$p->name]; + if ('?' !== $target[0]) { + $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE; + } elseif ('' === $target = (string) substr($target, 1)) { + throw new InvalidArgumentException(sprintf('A "%s" tag must have non-empty "id" attributes for service "%s".', $this->controllerTag, $id)); + } elseif ($p->allowsNull() && !$p->isOptional()) { + $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE; + } + } elseif (isset($bindings[$bindingName = $type.' $'.$name = Target::parseName($p)]) || isset($bindings[$bindingName = '$'.$name]) || isset($bindings[$bindingName = $type])) { + $binding = $bindings[$bindingName]; + + [$bindingValue, $bindingId, , $bindingType, $bindingFile] = $binding->getValues(); + $binding->setValues([$bindingValue, $bindingId, true, $bindingType, $bindingFile]); + + if (!$bindingValue instanceof Reference) { + $args[$p->name] = new Reference('.value.'.$container->hash($bindingValue)); + $container->register((string) $args[$p->name], 'mixed') + ->setFactory('current') + ->addArgument([$bindingValue]); + } else { + $args[$p->name] = $bindingValue; + } + + continue; + } elseif (!$type || !$autowire || '\\' !== $target[0]) { + continue; + } elseif (is_subclass_of($type, \UnitEnum::class)) { + // do not attempt to register enum typed arguments if not already present in bindings + continue; + } elseif (!$p->allowsNull()) { + $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE; + } + + if (Request::class === $type || SessionInterface::class === $type || Response::class === $type) { + continue; + } + + if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) { + $message = sprintf('Cannot determine controller argument for "%s::%s()": the $%s argument is type-hinted with the non-existent class or interface: "%s".', $class, $r->name, $p->name, $type); + + // see if the type-hint lives in the same namespace as the controller + if (0 === strncmp($type, $class, strrpos($class, '\\'))) { + $message .= ' Did you forget to add a use statement?'; + } + + $container->register($erroredId = '.errored.'.$container->hash($message), $type) + ->addError($message); + + $args[$p->name] = new Reference($erroredId, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE); + } else { + $target = ltrim($target, '\\'); + $args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, Target::parseName($p)) : new Reference($target, $invalidBehavior); + } + } + // register the maps as a per-method service-locators + if ($args) { + $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args); + + foreach ($publicAliases[$id] ?? [] as $alias) { + $controllers[$alias.'::'.$r->name] = clone $controllers[$id.'::'.$r->name]; + } + } + } + } + + $controllerLocatorRef = ServiceLocatorTagPass::register($container, $controllers); + + if ($container->hasDefinition($this->resolverServiceId)) { + $container->getDefinition($this->resolverServiceId) + ->replaceArgument(0, $controllerLocatorRef); + } + + if ($container->hasDefinition($this->notTaggedControllerResolverServiceId)) { + $container->getDefinition($this->notTaggedControllerResolverServiceId) + ->replaceArgument(0, $controllerLocatorRef); + } + + $container->setAlias($this->controllerLocator, (string) $controllerLocatorRef); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RegisterLocaleAwareServicesPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RegisterLocaleAwareServicesPass.php new file mode 100644 index 0000000..f0b801b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RegisterLocaleAwareServicesPass.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Argument\IteratorArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Register all services that have the "kernel.locale_aware" tag into the listener. + * + * @author Pierre Bobiet + */ +class RegisterLocaleAwareServicesPass implements CompilerPassInterface +{ + private $listenerServiceId; + private $localeAwareTag; + + public function __construct(string $listenerServiceId = 'locale_aware_listener', string $localeAwareTag = 'kernel.locale_aware') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->listenerServiceId = $listenerServiceId; + $this->localeAwareTag = $localeAwareTag; + } + + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition($this->listenerServiceId)) { + return; + } + + $services = []; + + foreach ($container->findTaggedServiceIds($this->localeAwareTag) as $id => $tags) { + $services[] = new Reference($id); + } + + if (!$services) { + $container->removeDefinition($this->listenerServiceId); + + return; + } + + $container + ->getDefinition($this->listenerServiceId) + ->setArgument(0, new IteratorArgument($services)) + ; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPass.php new file mode 100644 index 0000000..2d077a0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPass.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * Removes empty service-locators registered for ServiceValueResolver. + * + * @author Nicolas Grekas + */ +class RemoveEmptyControllerArgumentLocatorsPass implements CompilerPassInterface +{ + private $controllerLocator; + + public function __construct(string $controllerLocator = 'argument_resolver.controller_locator') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->controllerLocator = $controllerLocator; + } + + public function process(ContainerBuilder $container) + { + $controllerLocator = $container->findDefinition($this->controllerLocator); + $controllers = $controllerLocator->getArgument(0); + + foreach ($controllers as $controller => $argumentRef) { + $argumentLocator = $container->getDefinition((string) $argumentRef->getValues()[0]); + + if (!$argumentLocator->getArgument(0)) { + // remove empty argument locators + $reason = sprintf('Removing service-argument resolver for controller "%s": no corresponding services exist for the referenced types.', $controller); + } else { + // any methods listed for call-at-instantiation cannot be actions + $reason = false; + [$id, $action] = explode('::', $controller); + + if ($container->hasAlias($id)) { + continue; + } + + $controllerDef = $container->getDefinition($id); + foreach ($controllerDef->getMethodCalls() as [$method]) { + if (0 === strcasecmp($action, $method)) { + $reason = sprintf('Removing method "%s" of service "%s" from controller candidates: the method is called at instantiation, thus cannot be an action.', $action, $id); + break; + } + } + if (!$reason) { + // see Symfony\Component\HttpKernel\Controller\ContainerControllerResolver + $controllers[$id.':'.$action] = $argumentRef; + + if ('__invoke' === $action) { + $controllers[$id] = $argumentRef; + } + continue; + } + } + + unset($controllers[$controller]); + $container->log($this, $reason); + } + + $controllerLocator->replaceArgument(0, $controllers); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ResettableServicePass.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ResettableServicePass.php new file mode 100644 index 0000000..2e4cd69 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ResettableServicePass.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\DependencyInjection; + +use Symfony\Component\DependencyInjection\Argument\IteratorArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\Reference; + +/** + * @author Alexander M. Turek + */ +class ResettableServicePass implements CompilerPassInterface +{ + private $tagName; + + public function __construct(string $tagName = 'kernel.reset') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->tagName = $tagName; + } + + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + if (!$container->has('services_resetter')) { + return; + } + + $services = $methods = []; + + foreach ($container->findTaggedServiceIds($this->tagName, true) as $id => $tags) { + $services[$id] = new Reference($id, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE); + + foreach ($tags as $attributes) { + if (!isset($attributes['method'])) { + throw new RuntimeException(sprintf('Tag "%s" requires the "method" attribute to be set.', $this->tagName)); + } + + if (!isset($methods[$id])) { + $methods[$id] = []; + } + + if ('ignore' === ($attributes['on_invalid'] ?? null)) { + $attributes['method'] = '?'.$attributes['method']; + } + + $methods[$id][] = $attributes['method']; + } + } + + if (!$services) { + $container->removeAlias('services_resetter'); + $container->removeDefinition('services_resetter'); + + return; + } + + $container->findDefinition('services_resetter') + ->setArgument(0, new IteratorArgument($services)) + ->setArgument(1, $methods); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ServicesResetter.php b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ServicesResetter.php new file mode 100644 index 0000000..0063dec --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/DependencyInjection/ServicesResetter.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\HttpKernel\DependencyInjection; + +use Symfony\Contracts\Service\ResetInterface; + +/** + * Resets provided services. + * + * @author Alexander M. Turek + * @author Nicolas Grekas + * + * @internal + */ +class ServicesResetter implements ResetInterface +{ + private $resettableServices; + private $resetMethods; + + /** + * @param \Traversable $resettableServices + * @param array $resetMethods + */ + public function __construct(\Traversable $resettableServices, array $resetMethods) + { + $this->resettableServices = $resettableServices; + $this->resetMethods = $resetMethods; + } + + public function reset() + { + foreach ($this->resettableServices as $id => $service) { + foreach ((array) $this->resetMethods[$id] as $resetMethod) { + if ('?' === $resetMethod[0] && !method_exists($service, $resetMethod = substr($resetMethod, 1))) { + continue; + } + + $service->$resetMethod(); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/ControllerArgumentsEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/ControllerArgumentsEvent.php new file mode 100644 index 0000000..d075ee9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/ControllerArgumentsEvent.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Allows filtering of controller arguments. + * + * You can call getController() to retrieve the controller and getArguments + * to retrieve the current arguments. With setArguments() you can replace + * arguments that are used to call the controller. + * + * Arguments set in the event must be compatible with the signature of the + * controller. + * + * @author Christophe Coevoet + */ +final class ControllerArgumentsEvent extends KernelEvent +{ + private $controller; + private $arguments; + + public function __construct(HttpKernelInterface $kernel, callable $controller, array $arguments, Request $request, ?int $requestType) + { + parent::__construct($kernel, $request, $requestType); + + $this->controller = $controller; + $this->arguments = $arguments; + } + + public function getController(): callable + { + return $this->controller; + } + + public function setController(callable $controller) + { + $this->controller = $controller; + } + + public function getArguments(): array + { + return $this->arguments; + } + + public function setArguments(array $arguments) + { + $this->arguments = $arguments; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/ControllerEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/ControllerEvent.php new file mode 100644 index 0000000..da88800 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/ControllerEvent.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Allows filtering of a controller callable. + * + * You can call getController() to retrieve the current controller. With + * setController() you can set a new controller that is used in the processing + * of the request. + * + * Controllers should be callables. + * + * @author Bernhard Schussek + */ +final class ControllerEvent extends KernelEvent +{ + private $controller; + + public function __construct(HttpKernelInterface $kernel, callable $controller, Request $request, ?int $requestType) + { + parent::__construct($kernel, $request, $requestType); + + $this->setController($controller); + } + + public function getController(): callable + { + return $this->controller; + } + + public function setController(callable $controller): void + { + $this->controller = $controller; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/ExceptionEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/ExceptionEvent.php new file mode 100644 index 0000000..a18fbd3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/ExceptionEvent.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Allows to create a response for a thrown exception. + * + * Call setResponse() to set the response that will be returned for the + * current request. The propagation of this event is stopped as soon as a + * response is set. + * + * You can also call setThrowable() to replace the thrown exception. This + * exception will be thrown if no response is set during processing of this + * event. + * + * @author Bernhard Schussek + */ +final class ExceptionEvent extends RequestEvent +{ + private $throwable; + + /** + * @var bool + */ + private $allowCustomResponseCode = false; + + public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, \Throwable $e) + { + parent::__construct($kernel, $request, $requestType); + + $this->setThrowable($e); + } + + public function getThrowable(): \Throwable + { + return $this->throwable; + } + + /** + * Replaces the thrown exception. + * + * This exception will be thrown if no response is set in the event. + */ + public function setThrowable(\Throwable $exception): void + { + $this->throwable = $exception; + } + + /** + * Mark the event as allowing a custom response code. + */ + public function allowCustomResponseCode(): void + { + $this->allowCustomResponseCode = true; + } + + /** + * Returns true if the event allows a custom response code. + */ + public function isAllowingCustomResponseCode(): bool + { + return $this->allowCustomResponseCode; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/FinishRequestEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/FinishRequestEvent.php new file mode 100644 index 0000000..306a7ad --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/FinishRequestEvent.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\HttpKernel\Event; + +/** + * Triggered whenever a request is fully processed. + * + * @author Benjamin Eberlei + */ +final class FinishRequestEvent extends KernelEvent +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/KernelEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/KernelEvent.php new file mode 100644 index 0000000..d9d425e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/KernelEvent.php @@ -0,0 +1,92 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Base class for events thrown in the HttpKernel component. + * + * @author Bernhard Schussek + */ +class KernelEvent extends Event +{ + private $kernel; + private $request; + private $requestType; + + /** + * @param int $requestType The request type the kernel is currently processing; one of + * HttpKernelInterface::MAIN_REQUEST or HttpKernelInterface::SUB_REQUEST + */ + public function __construct(HttpKernelInterface $kernel, Request $request, ?int $requestType) + { + $this->kernel = $kernel; + $this->request = $request; + $this->requestType = $requestType; + } + + /** + * Returns the kernel in which this event was thrown. + * + * @return HttpKernelInterface + */ + public function getKernel() + { + return $this->kernel; + } + + /** + * Returns the request the kernel is currently processing. + * + * @return Request + */ + public function getRequest() + { + return $this->request; + } + + /** + * Returns the request type the kernel is currently processing. + * + * @return int One of HttpKernelInterface::MAIN_REQUEST and + * HttpKernelInterface::SUB_REQUEST + */ + public function getRequestType() + { + return $this->requestType; + } + + /** + * Checks if this is the main request. + */ + public function isMainRequest(): bool + { + return HttpKernelInterface::MAIN_REQUEST === $this->requestType; + } + + /** + * Checks if this is a master request. + * + * @return bool + * + * @deprecated since symfony/http-kernel 5.3, use isMainRequest() instead + */ + public function isMasterRequest() + { + trigger_deprecation('symfony/http-kernel', '5.3', '"%s()" is deprecated, use "isMainRequest()" instead.', __METHOD__); + + return $this->isMainRequest(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/RequestEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/RequestEvent.php new file mode 100644 index 0000000..30ffcdc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/RequestEvent.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Response; + +/** + * Allows to create a response for a request. + * + * Call setResponse() to set the response that will be returned for the + * current request. The propagation of this event is stopped as soon as a + * response is set. + * + * @author Bernhard Schussek + */ +class RequestEvent extends KernelEvent +{ + private $response; + + /** + * Returns the response object. + * + * @return Response|null + */ + public function getResponse() + { + return $this->response; + } + + /** + * Sets a response and stops event propagation. + */ + public function setResponse(Response $response) + { + $this->response = $response; + + $this->stopPropagation(); + } + + /** + * Returns whether a response was set. + * + * @return bool + */ + public function hasResponse() + { + return null !== $this->response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/ResponseEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/ResponseEvent.php new file mode 100644 index 0000000..1e56ebe --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/ResponseEvent.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Allows to filter a Response object. + * + * You can call getResponse() to retrieve the current response. With + * setResponse() you can set a new response that will be returned to the + * browser. + * + * @author Bernhard Schussek + */ +final class ResponseEvent extends KernelEvent +{ + private $response; + + public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, Response $response) + { + parent::__construct($kernel, $request, $requestType); + + $this->setResponse($response); + } + + public function getResponse(): Response + { + return $this->response; + } + + public function setResponse(Response $response): void + { + $this->response = $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/TerminateEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/TerminateEvent.php new file mode 100644 index 0000000..014ca53 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/TerminateEvent.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Allows to execute logic after a response was sent. + * + * Since it's only triggered on main requests, the `getRequestType()` method + * will always return the value of `HttpKernelInterface::MAIN_REQUEST`. + * + * @author Jordi Boggiano + */ +final class TerminateEvent extends KernelEvent +{ + private $response; + + public function __construct(HttpKernelInterface $kernel, Request $request, Response $response) + { + parent::__construct($kernel, $request, HttpKernelInterface::MAIN_REQUEST); + + $this->response = $response; + } + + public function getResponse(): Response + { + return $this->response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Event/ViewEvent.php b/php/libraries/composer/vendor/symfony/http-kernel/Event/ViewEvent.php new file mode 100644 index 0000000..88211da --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Event/ViewEvent.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Allows to create a response for the return value of a controller. + * + * Call setResponse() to set the response that will be returned for the + * current request. The propagation of this event is stopped as soon as a + * response is set. + * + * @author Bernhard Schussek + */ +final class ViewEvent extends RequestEvent +{ + /** + * The return value of the controller. + * + * @var mixed + */ + private $controllerResult; + + public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, $controllerResult) + { + parent::__construct($kernel, $request, $requestType); + + $this->controllerResult = $controllerResult; + } + + /** + * Returns the return value of the controller. + * + * @return mixed + */ + public function getControllerResult() + { + return $this->controllerResult; + } + + /** + * Assigns the return value of the controller. + * + * @param mixed $controllerResult The controller return value + */ + public function setControllerResult($controllerResult): void + { + $this->controllerResult = $controllerResult; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AbstractSessionListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AbstractSessionListener.php new file mode 100644 index 0000000..a339f44 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AbstractSessionListener.php @@ -0,0 +1,341 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Psr\Container\ContainerInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Cookie; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpFoundation\Session\SessionUtils; +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageException; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Contracts\Service\ResetInterface; + +/** + * Sets the session onto the request on the "kernel.request" event and saves + * it on the "kernel.response" event. + * + * In addition, if the session has been started it overrides the Cache-Control + * header in such a way that all caching is disabled in that case. + * If you have a scenario where caching responses with session information in + * them makes sense, you can disable this behaviour by setting the header + * AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER on the response. + * + * @author Johannes M. Schmitt + * @author Tobias Schultze + */ +abstract class AbstractSessionListener implements EventSubscriberInterface, ResetInterface +{ + public const NO_AUTO_CACHE_CONTROL_HEADER = 'Symfony-Session-NoAutoCacheControl'; + + + /** + * @internal + */ + protected $container; + private $sessionUsageStack = []; + private $debug; + + /** + * @var array + */ + private $sessionOptions; + + /** + * @internal + */ + public function __construct(?ContainerInterface $container = null, bool $debug = false, array $sessionOptions = []) + { + $this->container = $container; + $this->debug = $debug; + $this->sessionOptions = $sessionOptions; + } + + /** + * @internal + */ + public function onKernelRequest(RequestEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + $request = $event->getRequest(); + if (!$request->hasSession()) { + // This variable prevents calling `$this->getSession()` twice in case the Request (and the below factory) is cloned + $sess = null; + $request->setSessionFactory(function () use (&$sess, $request) { + if (!$sess) { + $sess = $this->getSession(); + $request->setSession($sess); + + /* + * For supporting sessions in php runtime with runners like roadrunner or swoole, the session + * cookie needs to be read from the cookie bag and set on the session storage. + * + * Do not set it when a native php session is active. + */ + if ($sess && !$sess->isStarted() && \PHP_SESSION_ACTIVE !== session_status()) { + $sessionId = $sess->getId() ?: $request->cookies->get($sess->getName(), ''); + $sess->setId($sessionId); + } + } + + return $sess; + }); + } + + $session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : null; + $this->sessionUsageStack[] = $session instanceof Session ? $session->getUsageIndex() : 0; + } + + /** + * @internal + */ + public function onKernelResponse(ResponseEvent $event) + { + if (!$event->isMainRequest() || (!$this->container->has('initialized_session') && !$event->getRequest()->hasSession())) { + return; + } + + $response = $event->getResponse(); + $autoCacheControl = !$response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER); + // Always remove the internal header if present + $response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER); + + if (!$session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : ($event->getRequest()->hasSession() ? $event->getRequest()->getSession() : null)) { + return; + } + + if ($session->isStarted()) { + /* + * Saves the session, in case it is still open, before sending the response/headers. + * + * This ensures several things in case the developer did not save the session explicitly: + * + * * If a session save handler without locking is used, it ensures the data is available + * on the next request, e.g. after a redirect. PHPs auto-save at script end via + * session_register_shutdown is executed after fastcgi_finish_request. So in this case + * the data could be missing the next request because it might not be saved the moment + * the new request is processed. + * * A locking save handler (e.g. the native 'files') circumvents concurrency problems like + * the one above. But by saving the session before long-running things in the terminate event, + * we ensure the session is not blocked longer than needed. + * * When regenerating the session ID no locking is involved in PHPs session design. See + * https://bugs.php.net/61470 for a discussion. So in this case, the session must + * be saved anyway before sending the headers with the new session ID. Otherwise session + * data could get lost again for concurrent requests with the new ID. One result could be + * that you get logged out after just logging in. + * + * This listener should be executed as one of the last listeners, so that previous listeners + * can still operate on the open session. This prevents the overhead of restarting it. + * Listeners after closing the session can still work with the session as usual because + * Symfonys session implementation starts the session on demand. So writing to it after + * it is saved will just restart it. + */ + $session->save(); + + /* + * For supporting sessions in php runtime with runners like roadrunner or swoole the session + * cookie need to be written on the response object and should not be written by PHP itself. + */ + $sessionName = $session->getName(); + $sessionId = $session->getId(); + $sessionOptions = $this->getSessionOptions($this->sessionOptions); + $sessionCookiePath = $sessionOptions['cookie_path'] ?? '/'; + $sessionCookieDomain = $sessionOptions['cookie_domain'] ?? null; + $sessionCookieSecure = $sessionOptions['cookie_secure'] ?? false; + $sessionCookieHttpOnly = $sessionOptions['cookie_httponly'] ?? true; + $sessionCookieSameSite = $sessionOptions['cookie_samesite'] ?? Cookie::SAMESITE_LAX; + $sessionUseCookies = $sessionOptions['use_cookies'] ?? true; + + SessionUtils::popSessionCookie($sessionName, $sessionId); + + if ($sessionUseCookies) { + $request = $event->getRequest(); + $requestSessionCookieId = $request->cookies->get($sessionName); + + $isSessionEmpty = $session->isEmpty() && empty($_SESSION); // checking $_SESSION to keep compatibility with native sessions + if ($requestSessionCookieId && $isSessionEmpty) { + // PHP internally sets the session cookie value to "deleted" when setcookie() is called with empty string $value argument + // which happens in \Symfony\Component\HttpFoundation\Session\Storage\Handler\AbstractSessionHandler::destroy + // when the session gets invalidated (for example on logout) so we must handle this case here too + // otherwise we would send two Set-Cookie headers back with the response + SessionUtils::popSessionCookie($sessionName, 'deleted'); + $response->headers->clearCookie( + $sessionName, + $sessionCookiePath, + $sessionCookieDomain, + $sessionCookieSecure, + $sessionCookieHttpOnly, + $sessionCookieSameSite + ); + } elseif ($sessionId !== $requestSessionCookieId && !$isSessionEmpty) { + $expire = 0; + $lifetime = $sessionOptions['cookie_lifetime'] ?? null; + if ($lifetime) { + $expire = time() + $lifetime; + } + + $response->headers->setCookie( + Cookie::create( + $sessionName, + $sessionId, + $expire, + $sessionCookiePath, + $sessionCookieDomain, + $sessionCookieSecure, + $sessionCookieHttpOnly, + false, + $sessionCookieSameSite + ) + ); + } + } + } + + if ($session instanceof Session ? $session->getUsageIndex() === end($this->sessionUsageStack) : !$session->isStarted()) { + return; + } + + if ($autoCacheControl) { + $maxAge = $response->headers->hasCacheControlDirective('public') ? 0 : (int) $response->getMaxAge(); + $response + ->setExpires(new \DateTimeImmutable('+'.$maxAge.' seconds')) + ->setPrivate() + ->setMaxAge($maxAge) + ->headers->addCacheControlDirective('must-revalidate'); + } + + if (!$event->getRequest()->attributes->get('_stateless', false)) { + return; + } + + if ($this->debug) { + throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.'); + } + + if ($this->container->has('logger')) { + $this->container->get('logger')->warning('Session was used while the request was declared stateless.'); + } + } + + /** + * @internal + */ + public function onFinishRequest(FinishRequestEvent $event) + { + if ($event->isMainRequest()) { + array_pop($this->sessionUsageStack); + } + } + + /** + * @internal + */ + public function onSessionUsage(): void + { + if (!$this->debug) { + return; + } + + if ($this->container && $this->container->has('session_collector')) { + $this->container->get('session_collector')(); + } + + if (!$requestStack = $this->container && $this->container->has('request_stack') ? $this->container->get('request_stack') : null) { + return; + } + + $stateless = false; + $clonedRequestStack = clone $requestStack; + while (null !== ($request = $clonedRequestStack->pop()) && !$stateless) { + $stateless = $request->attributes->get('_stateless'); + } + + if (!$stateless) { + return; + } + + if (!$session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $requestStack->getCurrentRequest()->getSession()) { + return; + } + + if ($session->isStarted()) { + $session->save(); + } + + throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.'); + } + + /** + * @internal + */ + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::REQUEST => ['onKernelRequest', 128], + // low priority to come after regular response listeners, but higher than StreamedResponseListener + KernelEvents::RESPONSE => ['onKernelResponse', -1000], + KernelEvents::FINISH_REQUEST => ['onFinishRequest'], + ]; + } + + /** + * @internal + */ + public function reset(): void + { + if (\PHP_SESSION_ACTIVE === session_status()) { + session_abort(); + } + + session_unset(); + $_SESSION = []; + + if (!headers_sent()) { // session id can only be reset when no headers were so we check for headers_sent first + session_id(''); + } + } + + /** + * Gets the session object. + * + * @internal + * + * @return SessionInterface|null + */ + abstract protected function getSession(); + + private function getSessionOptions(array $sessionOptions): array + { + $mergedSessionOptions = []; + + foreach (session_get_cookie_params() as $key => $value) { + $mergedSessionOptions['cookie_'.$key] = $value; + } + + foreach ($sessionOptions as $key => $value) { + // do the same logic as in the NativeSessionStorage + if ('cookie_secure' === $key && 'auto' === $value) { + continue; + } + $mergedSessionOptions[$key] = $value; + } + + return $mergedSessionOptions; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AbstractTestSessionListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AbstractTestSessionListener.php new file mode 100644 index 0000000..838c294 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AbstractTestSessionListener.php @@ -0,0 +1,120 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Cookie; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +trigger_deprecation('symfony/http-kernel', '5.4', '"%s" is deprecated use "%s" instead.', AbstractTestSessionListener::class, AbstractSessionListener::class); + +/** + * TestSessionListener. + * + * Saves session in test environment. + * + * @author Bulat Shakirzyanov + * @author Fabien Potencier + * + * @internal + * + * @deprecated since Symfony 5.4, use AbstractSessionListener instead + */ +abstract class AbstractTestSessionListener implements EventSubscriberInterface +{ + private $sessionId; + private $sessionOptions; + + public function __construct(array $sessionOptions = []) + { + $this->sessionOptions = $sessionOptions; + } + + public function onKernelRequest(RequestEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + // bootstrap the session + if ($event->getRequest()->hasSession()) { + $session = $event->getRequest()->getSession(); + } elseif (!$session = $this->getSession()) { + return; + } + + $cookies = $event->getRequest()->cookies; + + if ($cookies->has($session->getName())) { + $this->sessionId = $cookies->get($session->getName()); + $session->setId($this->sessionId); + } + } + + /** + * Checks if session was initialized and saves if current request is the main request + * Runs on 'kernel.response' in test environment. + */ + public function onKernelResponse(ResponseEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + $request = $event->getRequest(); + if (!$request->hasSession()) { + return; + } + + $session = $request->getSession(); + if ($wasStarted = $session->isStarted()) { + $session->save(); + } + + if ($session instanceof Session ? !$session->isEmpty() || (null !== $this->sessionId && $session->getId() !== $this->sessionId) : $wasStarted) { + $params = session_get_cookie_params() + ['samesite' => null]; + foreach ($this->sessionOptions as $k => $v) { + if (str_starts_with($k, 'cookie_')) { + $params[substr($k, 7)] = $v; + } + } + + foreach ($event->getResponse()->headers->getCookies() as $cookie) { + if ($session->getName() === $cookie->getName() && $params['path'] === $cookie->getPath() && $params['domain'] == $cookie->getDomain()) { + return; + } + } + + $event->getResponse()->headers->setCookie(new Cookie($session->getName(), $session->getId(), 0 === $params['lifetime'] ? 0 : time() + $params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly'], false, $params['samesite'] ?: null)); + $this->sessionId = $session->getId(); + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::REQUEST => ['onKernelRequest', 127], // AFTER SessionListener + KernelEvents::RESPONSE => ['onKernelResponse', -128], + ]; + } + + /** + * Gets the session object. + * + * @return SessionInterface|null + */ + abstract protected function getSession(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AddRequestFormatsListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AddRequestFormatsListener.php new file mode 100644 index 0000000..9e896ad --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/AddRequestFormatsListener.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Adds configured formats to each request. + * + * @author Gildas Quemener + * + * @final + */ +class AddRequestFormatsListener implements EventSubscriberInterface +{ + protected $formats; + + public function __construct(array $formats) + { + $this->formats = $formats; + } + + /** + * Adds request formats. + */ + public function onKernelRequest(RequestEvent $event) + { + $request = $event->getRequest(); + foreach ($this->formats as $format => $mimeTypes) { + $request->setFormat($format, $mimeTypes); + } + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents(): array + { + return [KernelEvents::REQUEST => ['onKernelRequest', 100]]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DebugHandlersListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DebugHandlersListener.php new file mode 100644 index 0000000..da71d08 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DebugHandlersListener.php @@ -0,0 +1,190 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Console\ConsoleEvents; +use Symfony\Component\Console\Event\ConsoleEvent; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\ErrorHandler\ErrorHandler; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\KernelEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Configures errors and exceptions handlers. + * + * @author Nicolas Grekas + * + * @final + * + * @internal since Symfony 5.3 + */ +class DebugHandlersListener implements EventSubscriberInterface +{ + private $earlyHandler; + private $exceptionHandler; + private $logger; + private $deprecationLogger; + private $levels; + private $throwAt; + private $scream; + private $scope; + private $firstCall = true; + private $hasTerminatedWithException; + + /** + * @param callable|null $exceptionHandler A handler that must support \Throwable instances that will be called on Exception + * @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants + * @param int|null $throwAt Thrown errors in a bit field of E_* constants, or null to keep the current value + * @param bool $scream Enables/disables screaming mode, where even silenced errors are logged + * @param bool $scope Enables/disables scoping mode + */ + public function __construct(?callable $exceptionHandler = null, ?LoggerInterface $logger = null, $levels = \E_ALL, ?int $throwAt = \E_ALL, bool $scream = true, $scope = true, $deprecationLogger = null, $fileLinkFormat = null) + { + if (!\is_bool($scope)) { + trigger_deprecation('symfony/http-kernel', '5.4', 'Passing a $fileLinkFormat is deprecated.'); + $scope = $deprecationLogger; + $deprecationLogger = $fileLinkFormat; + } + + $handler = set_exception_handler('is_int'); + $this->earlyHandler = \is_array($handler) ? $handler[0] : null; + restore_exception_handler(); + + $this->exceptionHandler = $exceptionHandler; + $this->logger = $logger; + $this->levels = $levels ?? \E_ALL; + $this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null)); + $this->scream = $scream; + $this->scope = $scope; + $this->deprecationLogger = $deprecationLogger; + } + + /** + * Configures the error handler. + */ + public function configure(?object $event = null) + { + if ($event instanceof ConsoleEvent && !\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { + return; + } + if (!$event instanceof KernelEvent ? !$this->firstCall : !$event->isMainRequest()) { + return; + } + $this->firstCall = $this->hasTerminatedWithException = false; + + $handler = set_exception_handler('is_int'); + $handler = \is_array($handler) ? $handler[0] : null; + restore_exception_handler(); + + if (!$handler instanceof ErrorHandler) { + $handler = $this->earlyHandler; + } + + if ($handler instanceof ErrorHandler) { + if ($this->logger || $this->deprecationLogger) { + $this->setDefaultLoggers($handler); + if (\is_array($this->levels)) { + $levels = 0; + foreach ($this->levels as $type => $log) { + $levels |= $type; + } + } else { + $levels = $this->levels; + } + + if ($this->scream) { + $handler->screamAt($levels); + } + if ($this->scope) { + $handler->scopeAt($levels & ~\E_USER_DEPRECATED & ~\E_DEPRECATED); + } else { + $handler->scopeAt(0, true); + } + $this->logger = $this->deprecationLogger = $this->levels = null; + } + if (null !== $this->throwAt) { + $handler->throwAt($this->throwAt, true); + } + } + if (!$this->exceptionHandler) { + if ($event instanceof KernelEvent) { + if (method_exists($kernel = $event->getKernel(), 'terminateWithException')) { + $request = $event->getRequest(); + $hasRun = &$this->hasTerminatedWithException; + $this->exceptionHandler = static function (\Throwable $e) use ($kernel, $request, &$hasRun) { + if ($hasRun) { + throw $e; + } + + $hasRun = true; + $kernel->terminateWithException($e, $request); + }; + } + } elseif ($event instanceof ConsoleEvent && $app = $event->getCommand()->getApplication()) { + $output = $event->getOutput(); + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + $this->exceptionHandler = static function (\Throwable $e) use ($app, $output) { + $app->renderThrowable($e, $output); + }; + } + } + if ($this->exceptionHandler) { + if ($handler instanceof ErrorHandler) { + $handler->setExceptionHandler($this->exceptionHandler); + } + $this->exceptionHandler = null; + } + } + + private function setDefaultLoggers(ErrorHandler $handler): void + { + if (\is_array($this->levels)) { + $levelsDeprecatedOnly = []; + $levelsWithoutDeprecated = []; + foreach ($this->levels as $type => $log) { + if (\E_DEPRECATED == $type || \E_USER_DEPRECATED == $type) { + $levelsDeprecatedOnly[$type] = $log; + } else { + $levelsWithoutDeprecated[$type] = $log; + } + } + } else { + $levelsDeprecatedOnly = $this->levels & (\E_DEPRECATED | \E_USER_DEPRECATED); + $levelsWithoutDeprecated = $this->levels & ~\E_DEPRECATED & ~\E_USER_DEPRECATED; + } + + $defaultLoggerLevels = $this->levels; + if ($this->deprecationLogger && $levelsDeprecatedOnly) { + $handler->setDefaultLogger($this->deprecationLogger, $levelsDeprecatedOnly); + $defaultLoggerLevels = $levelsWithoutDeprecated; + } + + if ($this->logger && $defaultLoggerLevels) { + $handler->setDefaultLogger($this->logger, $defaultLoggerLevels); + } + } + + public static function getSubscribedEvents(): array + { + $events = [KernelEvents::REQUEST => ['configure', 2048]]; + + if (\defined('Symfony\Component\Console\ConsoleEvents::COMMAND')) { + $events[ConsoleEvents::COMMAND] = ['configure', 2048]; + } + + return $events; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DisallowRobotsIndexingListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DisallowRobotsIndexingListener.php new file mode 100644 index 0000000..6607e49 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DisallowRobotsIndexingListener.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Ensures that the application is not indexed by search engines. + * + * @author Gary PEGEOT + */ +class DisallowRobotsIndexingListener implements EventSubscriberInterface +{ + private const HEADER_NAME = 'X-Robots-Tag'; + + public function onResponse(ResponseEvent $event): void + { + if (!$event->getResponse()->headers->has(static::HEADER_NAME)) { + $event->getResponse()->headers->set(static::HEADER_NAME, 'noindex'); + } + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents() + { + return [ + KernelEvents::RESPONSE => ['onResponse', -255], + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DumpListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DumpListener.php new file mode 100644 index 0000000..f7f9bd6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/DumpListener.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\Console\ConsoleEvents; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\VarDumper\Cloner\ClonerInterface; +use Symfony\Component\VarDumper\Dumper\DataDumperInterface; +use Symfony\Component\VarDumper\Server\Connection; +use Symfony\Component\VarDumper\VarDumper; + +/** + * Configures dump() handler. + * + * @author Nicolas Grekas + */ +class DumpListener implements EventSubscriberInterface +{ + private $cloner; + private $dumper; + private $connection; + + public function __construct(ClonerInterface $cloner, DataDumperInterface $dumper, ?Connection $connection = null) + { + $this->cloner = $cloner; + $this->dumper = $dumper; + $this->connection = $connection; + } + + public function configure() + { + $cloner = $this->cloner; + $dumper = $this->dumper; + $connection = $this->connection; + + VarDumper::setHandler(static function ($var) use ($cloner, $dumper, $connection) { + $data = $cloner->cloneVar($var); + + if (!$connection || !$connection->write($data)) { + $dumper->dump($data); + } + }); + } + + public static function getSubscribedEvents() + { + if (!class_exists(ConsoleEvents::class)) { + return []; + } + + // Register early to have a working dump() as early as possible + return [ConsoleEvents::COMMAND => ['configure', 1024]]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ErrorListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ErrorListener.php new file mode 100644 index 0000000..668a908 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ErrorListener.php @@ -0,0 +1,186 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Debug\Exception\FlattenException as LegacyFlattenException; +use Symfony\Component\ErrorHandler\Exception\FlattenException; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\Exception\HttpException; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; + +/** + * @author Fabien Potencier + */ +class ErrorListener implements EventSubscriberInterface +{ + protected $controller; + protected $logger; + protected $debug; + /** + * @var array|null}> + */ + protected $exceptionsMapping; + + /** + * @param array|null}> $exceptionsMapping + */ + public function __construct($controller, ?LoggerInterface $logger = null, bool $debug = false, array $exceptionsMapping = []) + { + $this->controller = $controller; + $this->logger = $logger; + $this->debug = $debug; + $this->exceptionsMapping = $exceptionsMapping; + } + + public function logKernelException(ExceptionEvent $event) + { + $throwable = $event->getThrowable(); + $logLevel = null; + + foreach ($this->exceptionsMapping as $class => $config) { + if ($throwable instanceof $class && $config['log_level']) { + $logLevel = $config['log_level']; + break; + } + } + + foreach ($this->exceptionsMapping as $class => $config) { + if (!$throwable instanceof $class || !$config['status_code']) { + continue; + } + if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() !== $config['status_code']) { + $headers = $throwable instanceof HttpExceptionInterface ? $throwable->getHeaders() : []; + $throwable = new HttpException($config['status_code'], $throwable->getMessage(), $throwable, $headers); + $event->setThrowable($throwable); + } + break; + } + + $e = FlattenException::createFromThrowable($throwable); + + $this->logException($throwable, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass(), $e->getMessage(), $e->getFile(), $e->getLine()), $logLevel); + } + + public function onKernelException(ExceptionEvent $event) + { + if (null === $this->controller) { + return; + } + + $throwable = $event->getThrowable(); + $request = $this->duplicateRequest($throwable, $event->getRequest()); + + try { + $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false); + } catch (\Exception $e) { + $f = FlattenException::createFromThrowable($e); + + $this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', $f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine())); + + $prev = $e; + do { + if ($throwable === $wrapper = $prev) { + throw $e; + } + } while ($prev = $wrapper->getPrevious()); + + $prev = new \ReflectionProperty($wrapper instanceof \Exception ? \Exception::class : \Error::class, 'previous'); + $prev->setAccessible(true); + $prev->setValue($wrapper, $throwable); + + throw $e; + } + + $event->setResponse($response); + + if ($this->debug) { + $event->getRequest()->attributes->set('_remove_csp_headers', true); + } + } + + public function removeCspHeader(ResponseEvent $event): void + { + if ($this->debug && $event->getRequest()->attributes->get('_remove_csp_headers', false)) { + $event->getResponse()->headers->remove('Content-Security-Policy'); + } + } + + public function onControllerArguments(ControllerArgumentsEvent $event) + { + $e = $event->getRequest()->attributes->get('exception'); + + if (!$e instanceof \Throwable || false === $k = array_search($e, $event->getArguments(), true)) { + return; + } + + $r = new \ReflectionFunction(\Closure::fromCallable($event->getController())); + $r = $r->getParameters()[$k] ?? null; + + if ($r && (!($r = $r->getType()) instanceof \ReflectionNamedType || \in_array($r->getName(), [FlattenException::class, LegacyFlattenException::class], true))) { + $arguments = $event->getArguments(); + $arguments[$k] = FlattenException::createFromThrowable($e); + $event->setArguments($arguments); + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::CONTROLLER_ARGUMENTS => 'onControllerArguments', + KernelEvents::EXCEPTION => [ + ['logKernelException', 0], + ['onKernelException', -128], + ], + KernelEvents::RESPONSE => ['removeCspHeader', -128], + ]; + } + + /** + * Logs an exception. + */ + protected function logException(\Throwable $exception, string $message, ?string $logLevel = null): void + { + if (null !== $this->logger) { + if (null !== $logLevel) { + $this->logger->log($logLevel, $message, ['exception' => $exception]); + } elseif (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) { + $this->logger->critical($message, ['exception' => $exception]); + } else { + $this->logger->error($message, ['exception' => $exception]); + } + } + } + + /** + * Clones the request for the exception. + */ + protected function duplicateRequest(\Throwable $exception, Request $request): Request + { + $attributes = [ + '_controller' => $this->controller, + 'exception' => $exception, + 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, + ]; + $request = $request->duplicate(null, null, $attributes); + $request->setMethod('GET'); + + return $request; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/FragmentListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/FragmentListener.php new file mode 100644 index 0000000..c01d9ad --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/FragmentListener.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\HttpKernel\UriSigner; + +/** + * Handles content fragments represented by special URIs. + * + * All URL paths starting with /_fragment are handled as + * content fragments by this listener. + * + * Throws an AccessDeniedHttpException exception if the request + * is not signed or if it is not an internal sub-request. + * + * @author Fabien Potencier + * + * @final + */ +class FragmentListener implements EventSubscriberInterface +{ + private $signer; + private $fragmentPath; + + /** + * @param string $fragmentPath The path that triggers this listener + */ + public function __construct(UriSigner $signer, string $fragmentPath = '/_fragment') + { + $this->signer = $signer; + $this->fragmentPath = $fragmentPath; + } + + /** + * Fixes request attributes when the path is '/_fragment'. + * + * @throws AccessDeniedHttpException if the request does not come from a trusted IP + */ + public function onKernelRequest(RequestEvent $event) + { + $request = $event->getRequest(); + + if ($this->fragmentPath !== rawurldecode($request->getPathInfo())) { + return; + } + + if ($request->attributes->has('_controller')) { + // Is a sub-request: no need to parse _path but it should still be removed from query parameters as below. + $request->query->remove('_path'); + + return; + } + + if ($event->isMainRequest()) { + $this->validateRequest($request); + } + + parse_str($request->query->get('_path', ''), $attributes); + $request->attributes->add($attributes); + $request->attributes->set('_route_params', array_replace($request->attributes->get('_route_params', []), $attributes)); + $request->query->remove('_path'); + } + + protected function validateRequest(Request $request) + { + // is the Request safe? + if (!$request->isMethodSafe()) { + throw new AccessDeniedHttpException(); + } + + // is the Request signed? + if ($this->signer->checkRequest($request)) { + return; + } + + throw new AccessDeniedHttpException(); + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::REQUEST => [['onKernelRequest', 48]], + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/LocaleAwareListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/LocaleAwareListener.php new file mode 100644 index 0000000..a126f06 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/LocaleAwareListener.php @@ -0,0 +1,77 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Contracts\Translation\LocaleAwareInterface; + +/** + * Pass the current locale to the provided services. + * + * @author Pierre Bobiet + */ +class LocaleAwareListener implements EventSubscriberInterface +{ + private $localeAwareServices; + private $requestStack; + + /** + * @param iterable $localeAwareServices + */ + public function __construct(iterable $localeAwareServices, RequestStack $requestStack) + { + $this->localeAwareServices = $localeAwareServices; + $this->requestStack = $requestStack; + } + + public function onKernelRequest(RequestEvent $event): void + { + $this->setLocale($event->getRequest()->getLocale(), $event->getRequest()->getDefaultLocale()); + } + + public function onKernelFinishRequest(FinishRequestEvent $event): void + { + if (null === $parentRequest = $this->requestStack->getParentRequest()) { + foreach ($this->localeAwareServices as $service) { + $service->setLocale($event->getRequest()->getDefaultLocale()); + } + + return; + } + + $this->setLocale($parentRequest->getLocale(), $parentRequest->getDefaultLocale()); + } + + public static function getSubscribedEvents() + { + return [ + // must be registered after the Locale listener + KernelEvents::REQUEST => [['onKernelRequest', 15]], + KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', -15]], + ]; + } + + private function setLocale(string $locale, string $defaultLocale): void + { + foreach ($this->localeAwareServices as $service) { + try { + $service->setLocale($locale); + } catch (\InvalidArgumentException $e) { + $service->setLocale($defaultLocale); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/LocaleListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/LocaleListener.php new file mode 100644 index 0000000..a4073ea --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/LocaleListener.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; +use Symfony\Component\HttpKernel\Event\KernelEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\Routing\RequestContextAwareInterface; + +/** + * Initializes the locale based on the current request. + * + * @author Fabien Potencier + * + * @final + */ +class LocaleListener implements EventSubscriberInterface +{ + private $router; + private $defaultLocale; + private $requestStack; + private $useAcceptLanguageHeader; + private $enabledLocales; + + public function __construct(RequestStack $requestStack, string $defaultLocale = 'en', ?RequestContextAwareInterface $router = null, bool $useAcceptLanguageHeader = false, array $enabledLocales = []) + { + $this->defaultLocale = $defaultLocale; + $this->requestStack = $requestStack; + $this->router = $router; + $this->useAcceptLanguageHeader = $useAcceptLanguageHeader; + $this->enabledLocales = $enabledLocales; + } + + public function setDefaultLocale(KernelEvent $event) + { + $event->getRequest()->setDefaultLocale($this->defaultLocale); + } + + public function onKernelRequest(RequestEvent $event) + { + $request = $event->getRequest(); + + $this->setLocale($request); + $this->setRouterContext($request); + } + + public function onKernelFinishRequest(FinishRequestEvent $event) + { + if (null !== $parentRequest = $this->requestStack->getParentRequest()) { + $this->setRouterContext($parentRequest); + } + } + + private function setLocale(Request $request) + { + if ($locale = $request->attributes->get('_locale')) { + $request->setLocale($locale); + } elseif ($this->useAcceptLanguageHeader && $this->enabledLocales) { + if ($request->getLanguages() && $preferredLanguage = $request->getPreferredLanguage($this->enabledLocales)) { + $request->setLocale($preferredLanguage); + } + $request->attributes->set('_vary_by_language', true); + } + } + + private function setRouterContext(Request $request) + { + if (null !== $this->router) { + $this->router->getContext()->setParameter('_locale', $request->getLocale()); + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::REQUEST => [ + ['setDefaultLocale', 100], + // must be registered after the Router to have access to the _locale + ['onKernelRequest', 16], + ], + KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]], + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ProfilerListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ProfilerListener.php new file mode 100644 index 0000000..e426187 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ProfilerListener.php @@ -0,0 +1,150 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestMatcherInterface; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\Event\TerminateEvent; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\HttpKernel\Profiler\Profile; +use Symfony\Component\HttpKernel\Profiler\Profiler; + +/** + * ProfilerListener collects data for the current request by listening to the kernel events. + * + * @author Fabien Potencier + * + * @final + */ +class ProfilerListener implements EventSubscriberInterface +{ + protected $profiler; + protected $matcher; + protected $onlyException; + protected $onlyMainRequests; + protected $exception; + /** @var \SplObjectStorage */ + protected $profiles; + protected $requestStack; + protected $collectParameter; + /** @var \SplObjectStorage */ + protected $parents; + + /** + * @param bool $onlyException True if the profiler only collects data when an exception occurs, false otherwise + * @param bool $onlyMainRequests True if the profiler only collects data when the request is the main request, false otherwise + */ + public function __construct(Profiler $profiler, RequestStack $requestStack, ?RequestMatcherInterface $matcher = null, bool $onlyException = false, bool $onlyMainRequests = false, ?string $collectParameter = null) + { + $this->profiler = $profiler; + $this->matcher = $matcher; + $this->onlyException = $onlyException; + $this->onlyMainRequests = $onlyMainRequests; + $this->profiles = new \SplObjectStorage(); + $this->parents = new \SplObjectStorage(); + $this->requestStack = $requestStack; + $this->collectParameter = $collectParameter; + } + + /** + * Handles the onKernelException event. + */ + public function onKernelException(ExceptionEvent $event) + { + if ($this->onlyMainRequests && !$event->isMainRequest()) { + return; + } + + $this->exception = $event->getThrowable(); + } + + /** + * Handles the onKernelResponse event. + */ + public function onKernelResponse(ResponseEvent $event) + { + if ($this->onlyMainRequests && !$event->isMainRequest()) { + return; + } + + if ($this->onlyException && null === $this->exception) { + return; + } + + $request = $event->getRequest(); + if (null !== $this->collectParameter && null !== $collectParameterValue = $request->get($this->collectParameter)) { + true === $collectParameterValue || filter_var($collectParameterValue, \FILTER_VALIDATE_BOOLEAN) ? $this->profiler->enable() : $this->profiler->disable(); + } + + $exception = $this->exception; + $this->exception = null; + + if (null !== $this->matcher && !$this->matcher->matches($request)) { + return; + } + + $session = $request->hasPreviousSession() && $request->hasSession() ? $request->getSession() : null; + + if ($session instanceof Session) { + $usageIndexValue = $usageIndexReference = &$session->getUsageIndex(); + $usageIndexReference = \PHP_INT_MIN; + } + + try { + if (!$profile = $this->profiler->collect($request, $event->getResponse(), $exception)) { + return; + } + } finally { + if ($session instanceof Session) { + $usageIndexReference = $usageIndexValue; + } + } + + $this->profiles[$request] = $profile; + + $this->parents[$request] = $this->requestStack->getParentRequest(); + } + + public function onKernelTerminate(TerminateEvent $event) + { + // attach children to parents + foreach ($this->profiles as $request) { + if (null !== $parentRequest = $this->parents[$request]) { + if (isset($this->profiles[$parentRequest])) { + $this->profiles[$parentRequest]->addChild($this->profiles[$request]); + } + } + } + + // save profiles + foreach ($this->profiles as $request) { + $this->profiler->saveProfile($this->profiles[$request]); + } + + $this->profiles = new \SplObjectStorage(); + $this->parents = new \SplObjectStorage(); + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::RESPONSE => ['onKernelResponse', -100], + KernelEvents::EXCEPTION => ['onKernelException', 0], + KernelEvents::TERMINATE => ['onKernelTerminate', -1024], + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ResponseListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ResponseListener.php new file mode 100644 index 0000000..a409015 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ResponseListener.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * ResponseListener fixes the Response headers based on the Request. + * + * @author Fabien Potencier + * + * @final + */ +class ResponseListener implements EventSubscriberInterface +{ + private $charset; + private $addContentLanguageHeader; + + public function __construct(string $charset, bool $addContentLanguageHeader = false) + { + $this->charset = $charset; + $this->addContentLanguageHeader = $addContentLanguageHeader; + } + + /** + * Filters the Response. + */ + public function onKernelResponse(ResponseEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + $response = $event->getResponse(); + + if (null === $response->getCharset()) { + $response->setCharset($this->charset); + } + + if ($this->addContentLanguageHeader && !$response->isInformational() && !$response->isEmpty() && !$response->headers->has('Content-Language')) { + $response->headers->set('Content-Language', $event->getRequest()->getLocale()); + } + + if ($event->getRequest()->attributes->get('_vary_by_language')) { + $response->setVary('Accept-Language', false); + } + + $response->prepare($event->getRequest()); + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::RESPONSE => 'onKernelResponse', + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/RouterListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/RouterListener.php new file mode 100644 index 0000000..8c1bc0a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/RouterListener.php @@ -0,0 +1,174 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Psr\Log\LoggerInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; +use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Symfony\Component\HttpKernel\Kernel; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\Routing\Exception\MethodNotAllowedException; +use Symfony\Component\Routing\Exception\NoConfigurationException; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\Matcher\RequestMatcherInterface; +use Symfony\Component\Routing\Matcher\UrlMatcherInterface; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\RequestContextAwareInterface; + +/** + * Initializes the context from the request and sets request attributes based on a matching route. + * + * @author Fabien Potencier + * @author Yonel Ceruto + * + * @final + */ +class RouterListener implements EventSubscriberInterface +{ + private $matcher; + private $context; + private $logger; + private $requestStack; + private $projectDir; + private $debug; + + /** + * @param UrlMatcherInterface|RequestMatcherInterface $matcher The Url or Request matcher + * @param RequestContext|null $context The RequestContext (can be null when $matcher implements RequestContextAwareInterface) + * + * @throws \InvalidArgumentException + */ + public function __construct($matcher, RequestStack $requestStack, ?RequestContext $context = null, ?LoggerInterface $logger = null, ?string $projectDir = null, bool $debug = true) + { + if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) { + throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.'); + } + + if (null === $context && !$matcher instanceof RequestContextAwareInterface) { + throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.'); + } + + $this->matcher = $matcher; + $this->context = $context ?? $matcher->getContext(); + $this->requestStack = $requestStack; + $this->logger = $logger; + $this->projectDir = $projectDir; + $this->debug = $debug; + } + + private function setCurrentRequest(?Request $request = null) + { + if (null !== $request) { + try { + $this->context->fromRequest($request); + } catch (\UnexpectedValueException $e) { + throw new BadRequestHttpException($e->getMessage(), $e, $e->getCode()); + } + } + } + + /** + * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator + * operates on the correct context again. + */ + public function onKernelFinishRequest(FinishRequestEvent $event) + { + $this->setCurrentRequest($this->requestStack->getParentRequest()); + } + + public function onKernelRequest(RequestEvent $event) + { + $request = $event->getRequest(); + + $this->setCurrentRequest($request); + + if ($request->attributes->has('_controller')) { + // routing is already done + return; + } + + // add attributes based on the request (routing) + try { + // matching a request is more powerful than matching a URL path + context, so try that first + if ($this->matcher instanceof RequestMatcherInterface) { + $parameters = $this->matcher->matchRequest($request); + } else { + $parameters = $this->matcher->match($request->getPathInfo()); + } + + if (null !== $this->logger) { + $this->logger->info('Matched route "{route}".', [ + 'route' => $parameters['_route'] ?? 'n/a', + 'route_parameters' => $parameters, + 'request_uri' => $request->getUri(), + 'method' => $request->getMethod(), + ]); + } + + $request->attributes->add($parameters); + unset($parameters['_route'], $parameters['_controller']); + $request->attributes->set('_route_params', $parameters); + } catch (ResourceNotFoundException $e) { + $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getUriForPath($request->getPathInfo())); + + if ($referer = $request->headers->get('referer')) { + $message .= sprintf(' (from "%s")', $referer); + } + + throw new NotFoundHttpException($message, $e); + } catch (MethodNotAllowedException $e) { + $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getUriForPath($request->getPathInfo()), implode(', ', $e->getAllowedMethods())); + + throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e); + } + } + + public function onKernelException(ExceptionEvent $event) + { + if (!$this->debug || !($e = $event->getThrowable()) instanceof NotFoundHttpException) { + return; + } + + if ($e->getPrevious() instanceof NoConfigurationException) { + $event->setResponse($this->createWelcomeResponse()); + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::REQUEST => [['onKernelRequest', 32]], + KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]], + KernelEvents::EXCEPTION => ['onKernelException', -64], + ]; + } + + private function createWelcomeResponse(): Response + { + $version = Kernel::VERSION; + $projectDir = realpath((string) $this->projectDir).\DIRECTORY_SEPARATOR; + $docVersion = substr(Kernel::VERSION, 0, 3); + + ob_start(); + include \dirname(__DIR__).'/Resources/welcome.html.php'; + + return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/SessionListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/SessionListener.php new file mode 100644 index 0000000..61887fd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/SessionListener.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\HttpKernel\EventListener; + +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; +use Symfony\Component\HttpKernel\Event\RequestEvent; + +/** + * Sets the session in the request. + * + * When the passed container contains a "session_storage" entry which + * holds a NativeSessionStorage instance, the "cookie_secure" option + * will be set to true whenever the current main request is secure. + * + * @author Fabien Potencier + * + * @final + */ +class SessionListener extends AbstractSessionListener +{ + public function onKernelRequest(RequestEvent $event) + { + parent::onKernelRequest($event); + + if (!$event->isMainRequest() || (!$this->container->has('session') && !$this->container->has('session_factory'))) { + return; + } + + if ($this->container->has('session_storage') + && ($storage = $this->container->get('session_storage')) instanceof NativeSessionStorage + && ($mainRequest = $this->container->get('request_stack')->getMainRequest()) + && $mainRequest->isSecure() + ) { + $storage->setOptions(['cookie_secure' => true]); + } + } + + protected function getSession(): ?SessionInterface + { + if ($this->container->has('session')) { + return $this->container->get('session'); + } + + if ($this->container->has('session_factory')) { + return $this->container->get('session_factory')->createSession(); + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/StreamedResponseListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/StreamedResponseListener.php new file mode 100644 index 0000000..b3f7ca4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/StreamedResponseListener.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\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * StreamedResponseListener is responsible for sending the Response + * to the client. + * + * @author Fabien Potencier + * + * @final + */ +class StreamedResponseListener implements EventSubscriberInterface +{ + /** + * Filters the Response. + */ + public function onKernelResponse(ResponseEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + $response = $event->getResponse(); + + if ($response instanceof StreamedResponse) { + $response->send(); + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::RESPONSE => ['onKernelResponse', -1024], + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/SurrogateListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/SurrogateListener.php new file mode 100644 index 0000000..dbf3846 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/SurrogateListener.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\HttpCache\HttpCache; +use Symfony\Component\HttpKernel\HttpCache\SurrogateInterface; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * SurrogateListener adds a Surrogate-Control HTTP header when the Response needs to be parsed for Surrogates. + * + * @author Fabien Potencier + * + * @final + */ +class SurrogateListener implements EventSubscriberInterface +{ + private $surrogate; + + public function __construct(?SurrogateInterface $surrogate = null) + { + $this->surrogate = $surrogate; + } + + /** + * Filters the Response. + */ + public function onKernelResponse(ResponseEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + + $kernel = $event->getKernel(); + $surrogate = $this->surrogate; + if ($kernel instanceof HttpCache) { + $surrogate = $kernel->getSurrogate(); + if (null !== $this->surrogate && $this->surrogate->getName() !== $surrogate->getName()) { + $surrogate = $this->surrogate; + } + } + + if (null === $surrogate) { + return; + } + + $surrogate->addSurrogateControl($event->getResponse()); + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::RESPONSE => 'onKernelResponse', + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/TestSessionListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/TestSessionListener.php new file mode 100644 index 0000000..45fa312 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/TestSessionListener.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 Symfony\Component\HttpKernel\EventListener; + +use Psr\Container\ContainerInterface; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +trigger_deprecation('symfony/http-kernel', '5.4', '"%s" is deprecated, use "%s" instead.', TestSessionListener::class, SessionListener::class); + +/** + * Sets the session in the request. + * + * @author Fabien Potencier + * + * @final + * + * @deprecated since Symfony 5.4, use SessionListener instead + */ +class TestSessionListener extends AbstractTestSessionListener +{ + private $container; + + public function __construct(ContainerInterface $container, array $sessionOptions = []) + { + $this->container = $container; + parent::__construct($sessionOptions); + } + + protected function getSession(): ?SessionInterface + { + if ($this->container->has('session')) { + return $this->container->get('session'); + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ValidateRequestListener.php b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ValidateRequestListener.php new file mode 100644 index 0000000..caa0f32 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/EventListener/ValidateRequestListener.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Validates Requests. + * + * @author Magnus Nordlander + * + * @final + */ +class ValidateRequestListener implements EventSubscriberInterface +{ + /** + * Performs the validation. + */ + public function onKernelRequest(RequestEvent $event) + { + if (!$event->isMainRequest()) { + return; + } + $request = $event->getRequest(); + + if ($request::getTrustedProxies()) { + $request->getClientIps(); + } + + $request->getHost(); + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::REQUEST => [ + ['onKernelRequest', 256], + ], + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/AccessDeniedHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/AccessDeniedHttpException.php new file mode 100644 index 0000000..a93954a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/AccessDeniedHttpException.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Fabien Potencier + * @author Christophe Coevoet + */ +class AccessDeniedHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(403, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/BadRequestHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/BadRequestHttpException.php new file mode 100644 index 0000000..343769c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/BadRequestHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class BadRequestHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(400, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/ConflictHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/ConflictHttpException.php new file mode 100644 index 0000000..541e9f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/ConflictHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class ConflictHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(409, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/ControllerDoesNotReturnResponseException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/ControllerDoesNotReturnResponseException.php new file mode 100644 index 0000000..54c80be --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/ControllerDoesNotReturnResponseException.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Grégoire Pineau + */ +class ControllerDoesNotReturnResponseException extends \LogicException +{ + public function __construct(string $message, callable $controller, string $file, int $line) + { + parent::__construct($message); + + if (!$controllerDefinition = $this->parseControllerDefinition($controller)) { + return; + } + + $this->file = $controllerDefinition['file']; + $this->line = $controllerDefinition['line']; + $r = new \ReflectionProperty(\Exception::class, 'trace'); + $r->setAccessible(true); + $r->setValue($this, array_merge([ + [ + 'line' => $line, + 'file' => $file, + ], + ], $this->getTrace())); + } + + private function parseControllerDefinition(callable $controller): ?array + { + if (\is_string($controller) && str_contains($controller, '::')) { + $controller = explode('::', $controller); + } + + if (\is_array($controller)) { + try { + $r = new \ReflectionMethod($controller[0], $controller[1]); + + return [ + 'file' => $r->getFileName(), + 'line' => $r->getEndLine(), + ]; + } catch (\ReflectionException $e) { + return null; + } + } + + if ($controller instanceof \Closure) { + $r = new \ReflectionFunction($controller); + + return [ + 'file' => $r->getFileName(), + 'line' => $r->getEndLine(), + ]; + } + + if (\is_object($controller)) { + $r = new \ReflectionClass($controller); + + try { + $line = $r->getMethod('__invoke')->getEndLine(); + } catch (\ReflectionException $e) { + $line = $r->getEndLine(); + } + + return [ + 'file' => $r->getFileName(), + 'line' => $line, + ]; + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/GoneHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/GoneHttpException.php new file mode 100644 index 0000000..1a36a53 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/GoneHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class GoneHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(410, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/HttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/HttpException.php new file mode 100644 index 0000000..c308893 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/HttpException.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * HttpException. + * + * @author Kris Wallsmith + */ +class HttpException extends \RuntimeException implements HttpExceptionInterface +{ + private $statusCode; + private $headers; + + public function __construct(int $statusCode, ?string $message = '', ?\Throwable $previous = null, array $headers = [], ?int $code = 0) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + if (null === $code) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__); + + $code = 0; + } + + $this->statusCode = $statusCode; + $this->headers = $headers; + + parent::__construct($message, $code, $previous); + } + + public function getStatusCode() + { + return $this->statusCode; + } + + public function getHeaders() + { + return $this->headers; + } + + /** + * Set response headers. + * + * @param array $headers Response headers + */ + public function setHeaders(array $headers) + { + $this->headers = $headers; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/HttpExceptionInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/HttpExceptionInterface.php new file mode 100644 index 0000000..4ae0509 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/HttpExceptionInterface.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * Interface for HTTP error exceptions. + * + * @author Kris Wallsmith + */ +interface HttpExceptionInterface extends \Throwable +{ + /** + * Returns the status code. + * + * @return int + */ + public function getStatusCode(); + + /** + * Returns response headers. + * + * @return array + */ + public function getHeaders(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/InvalidMetadataException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/InvalidMetadataException.php new file mode 100644 index 0000000..129267a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/InvalidMetadataException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +class InvalidMetadataException extends \LogicException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/LengthRequiredHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/LengthRequiredHttpException.php new file mode 100644 index 0000000..7531ecf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/LengthRequiredHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class LengthRequiredHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(411, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/MethodNotAllowedHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/MethodNotAllowedHttpException.php new file mode 100644 index 0000000..e3dc841 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/MethodNotAllowedHttpException.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Kris Wallsmith + */ +class MethodNotAllowedHttpException extends HttpException +{ + /** + * @param string[] $allow An array of allowed methods + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int|null $code The internal exception code + */ + public function __construct(array $allow, ?string $message = '', ?\Throwable $previous = null, ?int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + if (null === $code) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__); + + $code = 0; + } + + $headers['Allow'] = strtoupper(implode(', ', $allow)); + + parent::__construct(405, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/NotAcceptableHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/NotAcceptableHttpException.php new file mode 100644 index 0000000..9283dcd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/NotAcceptableHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class NotAcceptableHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(406, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/NotFoundHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/NotFoundHttpException.php new file mode 100644 index 0000000..d0adb03 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/NotFoundHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Fabien Potencier + */ +class NotFoundHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(404, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/PreconditionFailedHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/PreconditionFailedHttpException.php new file mode 100644 index 0000000..30ce081 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/PreconditionFailedHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class PreconditionFailedHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(412, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/PreconditionRequiredHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/PreconditionRequiredHttpException.php new file mode 100644 index 0000000..4f8a484 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/PreconditionRequiredHttpException.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\HttpKernel\Exception; + +/** + * @author Ben Ramsey + * + * @see http://tools.ietf.org/html/rfc6585 + */ +class PreconditionRequiredHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(428, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/ServiceUnavailableHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/ServiceUnavailableHttpException.php new file mode 100644 index 0000000..16efd93 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/ServiceUnavailableHttpException.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class ServiceUnavailableHttpException extends HttpException +{ + /** + * @param int|string|null $retryAfter The number of seconds or HTTP-date after which the request may be retried + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int|null $code The internal exception code + */ + public function __construct($retryAfter = null, ?string $message = '', ?\Throwable $previous = null, ?int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + if (null === $code) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__); + + $code = 0; + } + + if ($retryAfter) { + $headers['Retry-After'] = $retryAfter; + } + + parent::__construct(503, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/TooManyRequestsHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/TooManyRequestsHttpException.php new file mode 100644 index 0000000..81148f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/TooManyRequestsHttpException.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 Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + * + * @see http://tools.ietf.org/html/rfc6585 + */ +class TooManyRequestsHttpException extends HttpException +{ + /** + * @param int|string|null $retryAfter The number of seconds or HTTP-date after which the request may be retried + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int|null $code The internal exception code + */ + public function __construct($retryAfter = null, ?string $message = '', ?\Throwable $previous = null, ?int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + if (null === $code) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__); + + $code = 0; + } + + if ($retryAfter) { + $headers['Retry-After'] = $retryAfter; + } + + parent::__construct(429, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnauthorizedHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnauthorizedHttpException.php new file mode 100644 index 0000000..e1b8ace --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnauthorizedHttpException.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class UnauthorizedHttpException extends HttpException +{ + /** + * @param string $challenge WWW-Authenticate challenge string + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int|null $code The internal exception code + */ + public function __construct(string $challenge, ?string $message = '', ?\Throwable $previous = null, ?int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + if (null === $code) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__); + + $code = 0; + } + + $headers['WWW-Authenticate'] = $challenge; + + parent::__construct(401, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnexpectedSessionUsageException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnexpectedSessionUsageException.php new file mode 100644 index 0000000..0145b16 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnexpectedSessionUsageException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Mathias Arlaud + */ +class UnexpectedSessionUsageException extends \LogicException +{ +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnprocessableEntityHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnprocessableEntityHttpException.php new file mode 100644 index 0000000..5dc7b98 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnprocessableEntityHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Steve Hutchins + */ +class UnprocessableEntityHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(422, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnsupportedMediaTypeHttpException.php b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnsupportedMediaTypeHttpException.php new file mode 100644 index 0000000..35e20a0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Exception/UnsupportedMediaTypeHttpException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Exception; + +/** + * @author Ben Ramsey + */ +class UnsupportedMediaTypeHttpException extends HttpException +{ + /** + * @param string|null $message The internal exception message + * @param \Throwable|null $previous The previous exception + * @param int $code The internal exception code + */ + public function __construct(?string $message = '', ?\Throwable $previous = null, int $code = 0, array $headers = []) + { + if (null === $message) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + parent::__construct(415, $message, $previous, $headers, $code); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/AbstractSurrogateFragmentRenderer.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/AbstractSurrogateFragmentRenderer.php new file mode 100644 index 0000000..8a21f6b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/AbstractSurrogateFragmentRenderer.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\HttpCache\SurrogateInterface; +use Symfony\Component\HttpKernel\UriSigner; + +/** + * Implements Surrogate rendering strategy. + * + * @author Fabien Potencier + */ +abstract class AbstractSurrogateFragmentRenderer extends RoutableFragmentRenderer +{ + private $surrogate; + private $inlineStrategy; + private $signer; + + /** + * The "fallback" strategy when surrogate is not available should always be an + * instance of InlineFragmentRenderer. + * + * @param FragmentRendererInterface $inlineStrategy The inline strategy to use when the surrogate is not supported + */ + public function __construct(?SurrogateInterface $surrogate, FragmentRendererInterface $inlineStrategy, ?UriSigner $signer = null) + { + $this->surrogate = $surrogate; + $this->inlineStrategy = $inlineStrategy; + $this->signer = $signer; + } + + /** + * {@inheritdoc} + * + * Note that if the current Request has no surrogate capability, this method + * falls back to use the inline rendering strategy. + * + * Additional available options: + * + * * alt: an alternative URI to render in case of an error + * * comment: a comment to add when returning the surrogate tag + * + * Note, that not all surrogate strategies support all options. For now + * 'alt' and 'comment' are only supported by ESI. + * + * @see Symfony\Component\HttpKernel\HttpCache\SurrogateInterface + */ + public function render($uri, Request $request, array $options = []) + { + if (!$this->surrogate || !$this->surrogate->hasSurrogateCapability($request)) { + if ($uri instanceof ControllerReference && $this->containsNonScalars($uri->attributes)) { + throw new \InvalidArgumentException('Passing non-scalar values as part of URI attributes to the ESI and SSI rendering strategies is not supported. Use a different rendering strategy or pass scalar values.'); + } + + return $this->inlineStrategy->render($uri, $request, $options); + } + + if ($uri instanceof ControllerReference) { + $uri = $this->generateSignedFragmentUri($uri, $request); + } + + $alt = $options['alt'] ?? null; + if ($alt instanceof ControllerReference) { + $alt = $this->generateSignedFragmentUri($alt, $request); + } + + $tag = $this->surrogate->renderIncludeTag($uri, $alt, $options['ignore_errors'] ?? false, $options['comment'] ?? ''); + + return new Response($tag); + } + + private function generateSignedFragmentUri(ControllerReference $uri, Request $request): string + { + return (new FragmentUriGenerator($this->fragmentPath, $this->signer))->generate($uri, $request); + } + + private function containsNonScalars(array $values): bool + { + foreach ($values as $value) { + if (\is_scalar($value) || null === $value) { + continue; + } + + if (!\is_array($value) || $this->containsNonScalars($value)) { + return true; + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/EsiFragmentRenderer.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/EsiFragmentRenderer.php new file mode 100644 index 0000000..a4570e3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/EsiFragmentRenderer.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +/** + * Implements the ESI rendering strategy. + * + * @author Fabien Potencier + */ +class EsiFragmentRenderer extends AbstractSurrogateFragmentRenderer +{ + /** + * {@inheritdoc} + */ + public function getName() + { + return 'esi'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentHandler.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentHandler.php new file mode 100644 index 0000000..1ecaaef --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentHandler.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 Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\Exception\HttpException; + +/** + * Renders a URI that represents a resource fragment. + * + * This class handles the rendering of resource fragments that are included into + * a main resource. The handling of the rendering is managed by specialized renderers. + * + * @author Fabien Potencier + * + * @see FragmentRendererInterface + */ +class FragmentHandler +{ + private $debug; + private $renderers = []; + private $requestStack; + + /** + * @param FragmentRendererInterface[] $renderers An array of FragmentRendererInterface instances + * @param bool $debug Whether the debug mode is enabled or not + */ + public function __construct(RequestStack $requestStack, array $renderers = [], bool $debug = false) + { + $this->requestStack = $requestStack; + foreach ($renderers as $renderer) { + $this->addRenderer($renderer); + } + $this->debug = $debug; + } + + /** + * Adds a renderer. + */ + public function addRenderer(FragmentRendererInterface $renderer) + { + $this->renderers[$renderer->getName()] = $renderer; + } + + /** + * Renders a URI and returns the Response content. + * + * Available options: + * + * * ignore_errors: true to return an empty string in case of an error + * + * @param string|ControllerReference $uri A URI as a string or a ControllerReference instance + * + * @return string|null + * + * @throws \InvalidArgumentException when the renderer does not exist + * @throws \LogicException when no main request is being handled + */ + public function render($uri, string $renderer = 'inline', array $options = []) + { + if (!isset($options['ignore_errors'])) { + $options['ignore_errors'] = !$this->debug; + } + + if (!isset($this->renderers[$renderer])) { + throw new \InvalidArgumentException(sprintf('The "%s" renderer does not exist.', $renderer)); + } + + if (!$request = $this->requestStack->getCurrentRequest()) { + throw new \LogicException('Rendering a fragment can only be done when handling a Request.'); + } + + return $this->deliver($this->renderers[$renderer]->render($uri, $request, $options)); + } + + /** + * Delivers the Response as a string. + * + * When the Response is a StreamedResponse, the content is streamed immediately + * instead of being returned. + * + * @return string|null The Response content or null when the Response is streamed + * + * @throws \RuntimeException when the Response is not successful + */ + protected function deliver(Response $response) + { + if (!$response->isSuccessful()) { + $responseStatusCode = $response->getStatusCode(); + throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %d).', $this->requestStack->getCurrentRequest()->getUri(), $responseStatusCode), 0, new HttpException($responseStatusCode)); + } + + if (!$response instanceof StreamedResponse) { + return $response->getContent(); + } + + $response->sendContent(); + + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentRendererInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentRendererInterface.php new file mode 100644 index 0000000..568b178 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentRendererInterface.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\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ControllerReference; + +/** + * Interface implemented by all rendering strategies. + * + * @author Fabien Potencier + */ +interface FragmentRendererInterface +{ + /** + * Renders a URI and returns the Response content. + * + * @param string|ControllerReference $uri A URI as a string or a ControllerReference instance + * + * @return Response + */ + public function render($uri, Request $request, array $options = []); + + /** + * Gets the name of the strategy. + * + * @return string + */ + public function getName(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentUriGenerator.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentUriGenerator.php new file mode 100644 index 0000000..6ab0b81 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentUriGenerator.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\UriSigner; + +/** + * Generates a fragment URI. + * + * @author Kévin Dunglas + * @author Fabien Potencier + */ +final class FragmentUriGenerator implements FragmentUriGeneratorInterface +{ + private $fragmentPath; + private $signer; + private $requestStack; + + public function __construct(string $fragmentPath, ?UriSigner $signer = null, ?RequestStack $requestStack = null) + { + $this->fragmentPath = $fragmentPath; + $this->signer = $signer; + $this->requestStack = $requestStack; + } + + /** + * {@inheritDoc} + */ + public function generate(ControllerReference $controller, ?Request $request = null, bool $absolute = false, bool $strict = true, bool $sign = true): string + { + if (null === $request && (null === $this->requestStack || null === $request = $this->requestStack->getCurrentRequest())) { + throw new \LogicException('Generating a fragment URL can only be done when handling a Request.'); + } + + if ($sign && null === $this->signer) { + throw new \LogicException('You must use a URI when using the ESI rendering strategy or set a URL signer.'); + } + + if ($strict) { + $this->checkNonScalar($controller->attributes); + } + + // We need to forward the current _format and _locale values as we don't have + // a proper routing pattern to do the job for us. + // This makes things inconsistent if you switch from rendering a controller + // to rendering a route if the route pattern does not contain the special + // _format and _locale placeholders. + if (!isset($controller->attributes['_format'])) { + $controller->attributes['_format'] = $request->getRequestFormat(); + } + if (!isset($controller->attributes['_locale'])) { + $controller->attributes['_locale'] = $request->getLocale(); + } + + $controller->attributes['_controller'] = $controller->controller; + $controller->query['_path'] = http_build_query($controller->attributes, '', '&'); + $path = $this->fragmentPath.'?'.http_build_query($controller->query, '', '&'); + + // we need to sign the absolute URI, but want to return the path only. + $fragmentUri = $sign || $absolute ? $request->getUriForPath($path) : $request->getBaseUrl().$path; + + if (!$sign) { + return $fragmentUri; + } + + $fragmentUri = $this->signer->sign($fragmentUri); + + return $absolute ? $fragmentUri : substr($fragmentUri, \strlen($request->getSchemeAndHttpHost())); + } + + private function checkNonScalar(array $values): void + { + foreach ($values as $key => $value) { + if (\is_array($value)) { + $this->checkNonScalar($value); + } elseif (!\is_scalar($value) && null !== $value) { + throw new \LogicException(sprintf('Controller attributes cannot contain non-scalar/non-null values (value for key "%s" is not a scalar or null).', $key)); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentUriGeneratorInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentUriGeneratorInterface.php new file mode 100644 index 0000000..040011b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/FragmentUriGeneratorInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ControllerReference; + +/** + * Interface implemented by rendering strategies able to generate an URL for a fragment. + * + * @author Kévin Dunglas + */ +interface FragmentUriGeneratorInterface +{ + /** + * Generates a fragment URI for a given controller. + * + * @param bool $absolute Whether to generate an absolute URL or not + * @param bool $strict Whether to allow non-scalar attributes or not + * @param bool $sign Whether to sign the URL or not + */ + public function generate(ControllerReference $controller, ?Request $request = null, bool $absolute = false, bool $strict = true, bool $sign = true): string; +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php new file mode 100644 index 0000000..a23ffcc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php @@ -0,0 +1,104 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\UriSigner; +use Twig\Environment; + +/** + * Implements the Hinclude rendering strategy. + * + * @author Fabien Potencier + */ +class HIncludeFragmentRenderer extends RoutableFragmentRenderer +{ + private $globalDefaultTemplate; + private $signer; + private $twig; + private $charset; + + /** + * @param string|null $globalDefaultTemplate The global default content (it can be a template name or the content) + */ + public function __construct(?Environment $twig = null, ?UriSigner $signer = null, ?string $globalDefaultTemplate = null, string $charset = 'utf-8') + { + $this->twig = $twig; + $this->globalDefaultTemplate = $globalDefaultTemplate; + $this->signer = $signer; + $this->charset = $charset; + } + + /** + * Checks if a templating engine has been set. + * + * @return bool + */ + public function hasTemplating() + { + return null !== $this->twig; + } + + /** + * {@inheritdoc} + * + * Additional available options: + * + * * default: The default content (it can be a template name or the content) + * * id: An optional hx:include tag id attribute + * * attributes: An optional array of hx:include tag attributes + */ + public function render($uri, Request $request, array $options = []) + { + if ($uri instanceof ControllerReference) { + $uri = (new FragmentUriGenerator($this->fragmentPath, $this->signer))->generate($uri, $request); + } + + // We need to replace ampersands in the URI with the encoded form in order to return valid html/xml content. + $uri = str_replace('&', '&', $uri); + + $template = $options['default'] ?? $this->globalDefaultTemplate; + if (null !== $this->twig && $template && $this->twig->getLoader()->exists($template)) { + $content = $this->twig->render($template); + } else { + $content = $template; + } + + $attributes = isset($options['attributes']) && \is_array($options['attributes']) ? $options['attributes'] : []; + if (isset($options['id']) && $options['id']) { + $attributes['id'] = $options['id']; + } + $renderedAttributes = ''; + if (\count($attributes) > 0) { + $flags = \ENT_QUOTES | \ENT_SUBSTITUTE; + foreach ($attributes as $attribute => $value) { + $renderedAttributes .= sprintf( + ' %s="%s"', + htmlspecialchars($attribute, $flags, $this->charset, false), + htmlspecialchars($value, $flags, $this->charset, false) + ); + } + } + + return new Response(sprintf('%s', $uri, $renderedAttributes, $content)); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'hinclude'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/InlineFragmentRenderer.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/InlineFragmentRenderer.php new file mode 100644 index 0000000..60421f0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/InlineFragmentRenderer.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\HttpCache\SubRequestHandler; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; + +/** + * Implements the inline rendering strategy where the Request is rendered by the current HTTP kernel. + * + * @author Fabien Potencier + */ +class InlineFragmentRenderer extends RoutableFragmentRenderer +{ + private $kernel; + private $dispatcher; + + public function __construct(HttpKernelInterface $kernel, ?EventDispatcherInterface $dispatcher = null) + { + $this->kernel = $kernel; + $this->dispatcher = $dispatcher; + } + + /** + * {@inheritdoc} + * + * Additional available options: + * + * * alt: an alternative URI to render in case of an error + */ + public function render($uri, Request $request, array $options = []) + { + $reference = null; + if ($uri instanceof ControllerReference) { + $reference = $uri; + + // Remove attributes from the generated URI because if not, the Symfony + // routing system will use them to populate the Request attributes. We don't + // want that as we want to preserve objects (so we manually set Request attributes + // below instead) + $attributes = $reference->attributes; + $reference->attributes = []; + + // The request format and locale might have been overridden by the user + foreach (['_format', '_locale'] as $key) { + if (isset($attributes[$key])) { + $reference->attributes[$key] = $attributes[$key]; + } + } + + $uri = $this->generateFragmentUri($uri, $request, false, false); + + $reference->attributes = array_merge($attributes, $reference->attributes); + } + + $subRequest = $this->createSubRequest($uri, $request); + + // override Request attributes as they can be objects (which are not supported by the generated URI) + if (null !== $reference) { + $subRequest->attributes->add($reference->attributes); + } + + $level = ob_get_level(); + try { + return SubRequestHandler::handle($this->kernel, $subRequest, HttpKernelInterface::SUB_REQUEST, false); + } catch (\Exception $e) { + // we dispatch the exception event to trigger the logging + // the response that comes back is ignored + if (isset($options['ignore_errors']) && $options['ignore_errors'] && $this->dispatcher) { + $event = new ExceptionEvent($this->kernel, $request, HttpKernelInterface::SUB_REQUEST, $e); + + $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION); + } + + // let's clean up the output buffers that were created by the sub-request + Response::closeOutputBuffers($level, false); + + if (isset($options['alt'])) { + $alt = $options['alt']; + unset($options['alt']); + + return $this->render($alt, $request, $options); + } + + if (!isset($options['ignore_errors']) || !$options['ignore_errors']) { + throw $e; + } + + return new Response(); + } + } + + protected function createSubRequest(string $uri, Request $request) + { + $cookies = $request->cookies->all(); + $server = $request->server->all(); + + unset($server['HTTP_IF_MODIFIED_SINCE']); + unset($server['HTTP_IF_NONE_MATCH']); + + $subRequest = Request::create($uri, 'get', [], $cookies, [], $server); + if ($request->headers->has('Surrogate-Capability')) { + $subRequest->headers->set('Surrogate-Capability', $request->headers->get('Surrogate-Capability')); + } + + static $setSession; + + if (null === $setSession) { + $setSession = \Closure::bind(static function ($subRequest, $request) { $subRequest->session = $request->session; }, null, Request::class); + } + $setSession($subRequest, $request); + + if ($request->get('_format')) { + $subRequest->attributes->set('_format', $request->get('_format')); + } + if ($request->getDefaultLocale() !== $request->getLocale()) { + $subRequest->setLocale($request->getLocale()); + } + + return $subRequest; + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'inline'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/RoutableFragmentRenderer.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/RoutableFragmentRenderer.php new file mode 100644 index 0000000..e922ffb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/RoutableFragmentRenderer.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\EventListener\FragmentListener; + +/** + * Adds the possibility to generate a fragment URI for a given Controller. + * + * @author Fabien Potencier + */ +abstract class RoutableFragmentRenderer implements FragmentRendererInterface +{ + /** + * @internal + */ + protected $fragmentPath = '/_fragment'; + + /** + * Sets the fragment path that triggers the fragment listener. + * + * @see FragmentListener + */ + public function setFragmentPath(string $path) + { + $this->fragmentPath = $path; + } + + /** + * Generates a fragment URI for a given controller. + * + * @param bool $absolute Whether to generate an absolute URL or not + * @param bool $strict Whether to allow non-scalar attributes or not + * + * @return string + */ + protected function generateFragmentUri(ControllerReference $reference, Request $request, bool $absolute = false, bool $strict = true) + { + return (new FragmentUriGenerator($this->fragmentPath))->generate($reference, $request, $absolute, $strict, false); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Fragment/SsiFragmentRenderer.php b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/SsiFragmentRenderer.php new file mode 100644 index 0000000..45e7122 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Fragment/SsiFragmentRenderer.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Fragment; + +/** + * Implements the SSI rendering strategy. + * + * @author Sebastian Krebs + */ +class SsiFragmentRenderer extends AbstractSurrogateFragmentRenderer +{ + /** + * {@inheritdoc} + */ + public function getName() + { + return 'ssi'; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/AbstractSurrogate.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/AbstractSurrogate.php new file mode 100644 index 0000000..e1d73dc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/AbstractSurrogate.php @@ -0,0 +1,147 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * Abstract class implementing Surrogate capabilities to Request and Response instances. + * + * @author Fabien Potencier + * @author Robin Chalas + */ +abstract class AbstractSurrogate implements SurrogateInterface +{ + protected $contentTypes; + protected $phpEscapeMap = [ + ['', '', '', ''], + ]; + + /** + * @param array $contentTypes An array of content-type that should be parsed for Surrogate information + * (default: text/html, text/xml, application/xhtml+xml, and application/xml) + */ + public function __construct(array $contentTypes = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml']) + { + $this->contentTypes = $contentTypes; + } + + /** + * Returns a new cache strategy instance. + * + * @return ResponseCacheStrategyInterface + */ + public function createCacheStrategy() + { + return new ResponseCacheStrategy(); + } + + /** + * {@inheritdoc} + */ + public function hasSurrogateCapability(Request $request) + { + if (null === $value = $request->headers->get('Surrogate-Capability')) { + return false; + } + + return str_contains($value, sprintf('%s/1.0', strtoupper($this->getName()))); + } + + /** + * {@inheritdoc} + */ + public function addSurrogateCapability(Request $request) + { + $current = $request->headers->get('Surrogate-Capability'); + $new = sprintf('symfony="%s/1.0"', strtoupper($this->getName())); + + $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new); + } + + /** + * {@inheritdoc} + */ + public function needsParsing(Response $response) + { + if (!$control = $response->headers->get('Surrogate-Control')) { + return false; + } + + $pattern = sprintf('#content="[^"]*%s/1.0[^"]*"#', strtoupper($this->getName())); + + return (bool) preg_match($pattern, $control); + } + + /** + * {@inheritdoc} + */ + public function handle(HttpCache $cache, string $uri, string $alt, bool $ignoreErrors) + { + $subRequest = Request::create($uri, Request::METHOD_GET, [], $cache->getRequest()->cookies->all(), [], $cache->getRequest()->server->all()); + + try { + $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true); + + if (!$response->isSuccessful() && Response::HTTP_NOT_MODIFIED !== $response->getStatusCode()) { + throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %d).', $subRequest->getUri(), $response->getStatusCode())); + } + + return $response->getContent(); + } catch (\Exception $e) { + if ($alt) { + return $this->handle($cache, $alt, '', $ignoreErrors); + } + + if (!$ignoreErrors) { + throw $e; + } + } + + return ''; + } + + /** + * Remove the Surrogate from the Surrogate-Control header. + */ + protected function removeFromControl(Response $response) + { + if (!$response->headers->has('Surrogate-Control')) { + return; + } + + $value = $response->headers->get('Surrogate-Control'); + $upperName = strtoupper($this->getName()); + + if (sprintf('content="%s/1.0"', $upperName) == $value) { + $response->headers->remove('Surrogate-Control'); + } elseif (preg_match(sprintf('#,\s*content="%s/1.0"#', $upperName), $value)) { + $response->headers->set('Surrogate-Control', preg_replace(sprintf('#,\s*content="%s/1.0"#', $upperName), '', $value)); + } elseif (preg_match(sprintf('#content="%s/1.0",\s*#', $upperName), $value)) { + $response->headers->set('Surrogate-Control', preg_replace(sprintf('#content="%s/1.0",\s*#', $upperName), '', $value)); + } + } + + protected static function generateBodyEvalBoundary(): string + { + static $cookie; + $cookie = hash('md5', $cookie ?? $cookie = random_bytes(16), true); + $boundary = base64_encode($cookie); + + \assert(HttpCache::BODY_EVAL_BOUNDARY_LENGTH === \strlen($boundary)); + + return $boundary; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Esi.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Esi.php new file mode 100644 index 0000000..5e7d17a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Esi.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Esi implements the ESI capabilities to Request and Response instances. + * + * For more information, read the following W3C notes: + * + * * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang) + * + * * Edge Architecture Specification (http://www.w3.org/TR/edge-arch) + * + * @author Fabien Potencier + */ +class Esi extends AbstractSurrogate +{ + public function getName() + { + return 'esi'; + } + + /** + * {@inheritdoc} + */ + public function addSurrogateControl(Response $response) + { + if (str_contains($response->getContent(), 'headers->set('Surrogate-Control', 'content="ESI/1.0"'); + } + } + + /** + * {@inheritdoc} + */ + public function renderIncludeTag(string $uri, ?string $alt = null, bool $ignoreErrors = true, string $comment = '') + { + $html = sprintf('', + $uri, + $ignoreErrors ? ' onerror="continue"' : '', + $alt ? sprintf(' alt="%s"', $alt) : '' + ); + + if (!empty($comment)) { + return sprintf("\n%s", $comment, $html); + } + + return $html; + } + + /** + * {@inheritdoc} + */ + public function process(Request $request, Response $response) + { + $type = $response->headers->get('Content-Type'); + if (empty($type)) { + $type = 'text/html'; + } + + $parts = explode(';', $type); + if (!\in_array($parts[0], $this->contentTypes)) { + return $response; + } + + // we don't use a proper XML parser here as we can have ESI tags in a plain text response + $content = $response->getContent(); + $content = preg_replace('#.*?#s', '', $content); + $content = preg_replace('#]+>#s', '', $content); + + $boundary = self::generateBodyEvalBoundary(); + $chunks = preg_split('##', $content, -1, \PREG_SPLIT_DELIM_CAPTURE); + + $i = 1; + while (isset($chunks[$i])) { + $options = []; + preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER); + foreach ($matches as $set) { + $options[$set[1]] = $set[2]; + } + + if (!isset($options['src'])) { + throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.'); + } + + $chunks[$i] = $boundary.$options['src']."\n".($options['alt'] ?? '')."\n".('continue' === ($options['onerror'] ?? ''))."\n"; + $i += 2; + } + $content = $boundary.implode('', $chunks).$boundary; + + $response->setContent($content); + $response->headers->set('X-Body-Eval', 'ESI'); + + // remove ESI/1.0 from the Surrogate-Control header + $this->removeFromControl($response); + + return $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/HttpCache.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/HttpCache.php new file mode 100644 index 0000000..9bffc8a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/HttpCache.php @@ -0,0 +1,753 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * This code is partially based on the Rack-Cache library by Ryan Tomayko, + * which is released under the MIT license. + * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\TerminableInterface; + +/** + * Cache provides HTTP caching. + * + * @author Fabien Potencier + */ +class HttpCache implements HttpKernelInterface, TerminableInterface +{ + public const BODY_EVAL_BOUNDARY_LENGTH = 24; + + private $kernel; + private $store; + private $request; + private $surrogate; + private $surrogateCacheStrategy; + private $options = []; + private $traces = []; + + /** + * Constructor. + * + * The available options are: + * + * * debug If true, exceptions are thrown when things go wrong. Otherwise, the cache + * will try to carry on and deliver a meaningful response. + * + * * trace_level May be one of 'none', 'short' and 'full'. For 'short', a concise trace of the + * main request will be added as an HTTP header. 'full' will add traces for all + * requests (including ESI subrequests). (default: 'full' if in debug; 'none' otherwise) + * + * * trace_header Header name to use for traces. (default: X-Symfony-Cache) + * + * * default_ttl The number of seconds that a cache entry should be considered + * fresh when no explicit freshness information is provided in + * a response. Explicit Cache-Control or Expires headers + * override this value. (default: 0) + * + * * private_headers Set of request headers that trigger "private" cache-control behavior + * on responses that don't explicitly state whether the response is + * public or private via a Cache-Control directive. (default: Authorization and Cookie) + * + * * allow_reload Specifies whether the client can force a cache reload by including a + * Cache-Control "no-cache" directive in the request. Set it to ``true`` + * for compliance with RFC 2616. (default: false) + * + * * allow_revalidate Specifies whether the client can force a cache revalidate by including + * a Cache-Control "max-age=0" directive in the request. Set it to ``true`` + * for compliance with RFC 2616. (default: false) + * + * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the + * Response TTL precision is a second) during which the cache can immediately return + * a stale response while it revalidates it in the background (default: 2). + * This setting is overridden by the stale-while-revalidate HTTP Cache-Control + * extension (see RFC 5861). + * + * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which + * the cache can serve a stale response when an error is encountered (default: 60). + * This setting is overridden by the stale-if-error HTTP Cache-Control extension + * (see RFC 5861). + */ + public function __construct(HttpKernelInterface $kernel, StoreInterface $store, ?SurrogateInterface $surrogate = null, array $options = []) + { + $this->store = $store; + $this->kernel = $kernel; + $this->surrogate = $surrogate; + + // needed in case there is a fatal error because the backend is too slow to respond + register_shutdown_function([$this->store, 'cleanup']); + + $this->options = array_merge([ + 'debug' => false, + 'default_ttl' => 0, + 'private_headers' => ['Authorization', 'Cookie'], + 'allow_reload' => false, + 'allow_revalidate' => false, + 'stale_while_revalidate' => 2, + 'stale_if_error' => 60, + 'trace_level' => 'none', + 'trace_header' => 'X-Symfony-Cache', + ], $options); + + if (!isset($options['trace_level'])) { + $this->options['trace_level'] = $this->options['debug'] ? 'full' : 'none'; + } + } + + /** + * Gets the current store. + * + * @return StoreInterface + */ + public function getStore() + { + return $this->store; + } + + /** + * Returns an array of events that took place during processing of the last request. + * + * @return array + */ + public function getTraces() + { + return $this->traces; + } + + private function addTraces(Response $response) + { + $traceString = null; + + if ('full' === $this->options['trace_level']) { + $traceString = $this->getLog(); + } + + if ('short' === $this->options['trace_level'] && $masterId = array_key_first($this->traces)) { + $traceString = implode('/', $this->traces[$masterId]); + } + + if (null !== $traceString) { + $response->headers->add([$this->options['trace_header'] => $traceString]); + } + } + + /** + * Returns a log message for the events of the last request processing. + * + * @return string + */ + public function getLog() + { + $log = []; + foreach ($this->traces as $request => $traces) { + $log[] = sprintf('%s: %s', $request, implode(', ', $traces)); + } + + return implode('; ', $log); + } + + /** + * Gets the Request instance associated with the main request. + * + * @return Request + */ + public function getRequest() + { + return $this->request; + } + + /** + * Gets the Kernel instance. + * + * @return HttpKernelInterface + */ + public function getKernel() + { + return $this->kernel; + } + + /** + * Gets the Surrogate instance. + * + * @return SurrogateInterface + * + * @throws \LogicException + */ + public function getSurrogate() + { + return $this->surrogate; + } + + /** + * {@inheritdoc} + */ + public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true) + { + // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism + if (HttpKernelInterface::MAIN_REQUEST === $type) { + $this->traces = []; + // Keep a clone of the original request for surrogates so they can access it. + // We must clone here to get a separate instance because the application will modify the request during + // the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1 + // and adding the X-Forwarded-For header, see HttpCache::forward()). + $this->request = clone $request; + if (null !== $this->surrogate) { + $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy(); + } + } + + $this->traces[$this->getTraceKey($request)] = []; + + if (!$request->isMethodSafe()) { + $response = $this->invalidate($request, $catch); + } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) { + $response = $this->pass($request, $catch); + } elseif ($this->options['allow_reload'] && $request->isNoCache()) { + /* + If allow_reload is configured and the client requests "Cache-Control: no-cache", + reload the cache by fetching a fresh response and caching it (if possible). + */ + $this->record($request, 'reload'); + $response = $this->fetch($request, $catch); + } else { + $response = $this->lookup($request, $catch); + } + + $this->restoreResponseBody($request, $response); + + if (HttpKernelInterface::MAIN_REQUEST === $type) { + $this->addTraces($response); + } + + if (null !== $this->surrogate) { + if (HttpKernelInterface::MAIN_REQUEST === $type) { + $this->surrogateCacheStrategy->update($response); + } else { + $this->surrogateCacheStrategy->add($response); + } + } + + $response->prepare($request); + + $response->isNotModified($request); + + return $response; + } + + /** + * {@inheritdoc} + */ + public function terminate(Request $request, Response $response) + { + if ($this->getKernel() instanceof TerminableInterface) { + $this->getKernel()->terminate($request, $response); + } + } + + /** + * Forwards the Request to the backend without storing the Response in the cache. + * + * @param bool $catch Whether to process exceptions + * + * @return Response + */ + protected function pass(Request $request, bool $catch = false) + { + $this->record($request, 'pass'); + + return $this->forward($request, $catch); + } + + /** + * Invalidates non-safe methods (like POST, PUT, and DELETE). + * + * @param bool $catch Whether to process exceptions + * + * @return Response + * + * @throws \Exception + * + * @see RFC2616 13.10 + */ + protected function invalidate(Request $request, bool $catch = false) + { + $response = $this->pass($request, $catch); + + // invalidate only when the response is successful + if ($response->isSuccessful() || $response->isRedirect()) { + try { + $this->store->invalidate($request); + + // As per the RFC, invalidate Location and Content-Location URLs if present + foreach (['Location', 'Content-Location'] as $header) { + if ($uri = $response->headers->get($header)) { + $subRequest = Request::create($uri, 'get', [], [], [], $request->server->all()); + + $this->store->invalidate($subRequest); + } + } + + $this->record($request, 'invalidate'); + } catch (\Exception $e) { + $this->record($request, 'invalidate-failed'); + + if ($this->options['debug']) { + throw $e; + } + } + } + + return $response; + } + + /** + * Lookups a Response from the cache for the given Request. + * + * When a matching cache entry is found and is fresh, it uses it as the + * response without forwarding any request to the backend. When a matching + * cache entry is found but is stale, it attempts to "validate" the entry with + * the backend using conditional GET. When no matching cache entry is found, + * it triggers "miss" processing. + * + * @param bool $catch Whether to process exceptions + * + * @return Response + * + * @throws \Exception + */ + protected function lookup(Request $request, bool $catch = false) + { + try { + $entry = $this->store->lookup($request); + } catch (\Exception $e) { + $this->record($request, 'lookup-failed'); + + if ($this->options['debug']) { + throw $e; + } + + return $this->pass($request, $catch); + } + + if (null === $entry) { + $this->record($request, 'miss'); + + return $this->fetch($request, $catch); + } + + if (!$this->isFreshEnough($request, $entry)) { + $this->record($request, 'stale'); + + return $this->validate($request, $entry, $catch); + } + + if ($entry->headers->hasCacheControlDirective('no-cache')) { + return $this->validate($request, $entry, $catch); + } + + $this->record($request, 'fresh'); + + $entry->headers->set('Age', $entry->getAge()); + + return $entry; + } + + /** + * Validates that a cache entry is fresh. + * + * The original request is used as a template for a conditional + * GET request with the backend. + * + * @param bool $catch Whether to process exceptions + * + * @return Response + */ + protected function validate(Request $request, Response $entry, bool $catch = false) + { + $subRequest = clone $request; + + // send no head requests because we want content + if ('HEAD' === $request->getMethod()) { + $subRequest->setMethod('GET'); + } + + // add our cached last-modified validator + if ($entry->headers->has('Last-Modified')) { + $subRequest->headers->set('If-Modified-Since', $entry->headers->get('Last-Modified')); + } + + // Add our cached etag validator to the environment. + // We keep the etags from the client to handle the case when the client + // has a different private valid entry which is not cached here. + $cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : []; + $requestEtags = $request->getETags(); + if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) { + $subRequest->headers->set('If-None-Match', implode(', ', $etags)); + } + + $response = $this->forward($subRequest, $catch, $entry); + + if (304 == $response->getStatusCode()) { + $this->record($request, 'valid'); + + // return the response and not the cache entry if the response is valid but not cached + $etag = $response->getEtag(); + if ($etag && \in_array($etag, $requestEtags) && !\in_array($etag, $cachedEtags)) { + return $response; + } + + $entry = clone $entry; + $entry->headers->remove('Date'); + + foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) { + if ($response->headers->has($name)) { + $entry->headers->set($name, $response->headers->get($name)); + } + } + + $response = $entry; + } else { + $this->record($request, 'invalid'); + } + + if ($response->isCacheable()) { + $this->store($request, $response); + } + + return $response; + } + + /** + * Unconditionally fetches a fresh response from the backend and + * stores it in the cache if is cacheable. + * + * @param bool $catch Whether to process exceptions + * + * @return Response + */ + protected function fetch(Request $request, bool $catch = false) + { + $subRequest = clone $request; + + // send no head requests because we want content + if ('HEAD' === $request->getMethod()) { + $subRequest->setMethod('GET'); + } + + // avoid that the backend sends no content + $subRequest->headers->remove('If-Modified-Since'); + $subRequest->headers->remove('If-None-Match'); + + $response = $this->forward($subRequest, $catch); + + if ($response->isCacheable()) { + $this->store($request, $response); + } + + return $response; + } + + /** + * Forwards the Request to the backend and returns the Response. + * + * All backend requests (cache passes, fetches, cache validations) + * run through this method. + * + * @param bool $catch Whether to catch exceptions or not + * @param Response|null $entry A Response instance (the stale entry if present, null otherwise) + * + * @return Response + */ + protected function forward(Request $request, bool $catch = false, ?Response $entry = null) + { + if ($this->surrogate) { + $this->surrogate->addSurrogateCapability($request); + } + + // always a "master" request (as the real master request can be in cache) + $response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST, $catch); + + /* + * Support stale-if-error given on Responses or as a config option. + * RFC 7234 summarizes in Section 4.2.4 (but also mentions with the individual + * Cache-Control directives) that + * + * A cache MUST NOT generate a stale response if it is prohibited by an + * explicit in-protocol directive (e.g., by a "no-store" or "no-cache" + * cache directive, a "must-revalidate" cache-response-directive, or an + * applicable "s-maxage" or "proxy-revalidate" cache-response-directive; + * see Section 5.2.2). + * + * https://tools.ietf.org/html/rfc7234#section-4.2.4 + * + * We deviate from this in one detail, namely that we *do* serve entries in the + * stale-if-error case even if they have a `s-maxage` Cache-Control directive. + */ + if (null !== $entry + && \in_array($response->getStatusCode(), [500, 502, 503, 504]) + && !$entry->headers->hasCacheControlDirective('no-cache') + && !$entry->mustRevalidate() + ) { + if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) { + $age = $this->options['stale_if_error']; + } + + /* + * stale-if-error gives the (extra) time that the Response may be used *after* it has become stale. + * So we compare the time the $entry has been sitting in the cache already with the + * time it was fresh plus the allowed grace period. + */ + if ($entry->getAge() <= $entry->getMaxAge() + $age) { + $this->record($request, 'stale-if-error'); + + return $entry; + } + } + + /* + RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate + clock MUST NOT send a "Date" header, although it MUST send one in most other cases + except for 1xx or 5xx responses where it MAY do so. + + Anyway, a client that received a message without a "Date" header MUST add it. + */ + if (!$response->headers->has('Date')) { + $response->setDate(\DateTime::createFromFormat('U', time())); + } + + $this->processResponseBody($request, $response); + + if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) { + $response->setPrivate(); + } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) { + $response->setTtl($this->options['default_ttl']); + } + + return $response; + } + + /** + * Checks whether the cache entry is "fresh enough" to satisfy the Request. + * + * @return bool + */ + protected function isFreshEnough(Request $request, Response $entry) + { + if (!$entry->isFresh()) { + return $this->lock($request, $entry); + } + + if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) { + return $maxAge > 0 && $maxAge >= $entry->getAge(); + } + + return true; + } + + /** + * Locks a Request during the call to the backend. + * + * @return bool true if the cache entry can be returned even if it is staled, false otherwise + */ + protected function lock(Request $request, Response $entry) + { + // try to acquire a lock to call the backend + $lock = $this->store->lock($request); + + if (true === $lock) { + // we have the lock, call the backend + return false; + } + + // there is already another process calling the backend + + // May we serve a stale response? + if ($this->mayServeStaleWhileRevalidate($entry)) { + $this->record($request, 'stale-while-revalidate'); + + return true; + } + + // wait for the lock to be released + if ($this->waitForLock($request)) { + // replace the current entry with the fresh one + $new = $this->lookup($request); + $entry->headers = $new->headers; + $entry->setContent($new->getContent()); + $entry->setStatusCode($new->getStatusCode()); + $entry->setProtocolVersion($new->getProtocolVersion()); + foreach ($new->headers->getCookies() as $cookie) { + $entry->headers->setCookie($cookie); + } + } else { + // backend is slow as hell, send a 503 response (to avoid the dog pile effect) + $entry->setStatusCode(503); + $entry->setContent('503 Service Unavailable'); + $entry->headers->set('Retry-After', 10); + } + + return true; + } + + /** + * Writes the Response to the cache. + * + * @throws \Exception + */ + protected function store(Request $request, Response $response) + { + try { + $this->store->write($request, $response); + + $this->record($request, 'store'); + + $response->headers->set('Age', $response->getAge()); + } catch (\Exception $e) { + $this->record($request, 'store-failed'); + + if ($this->options['debug']) { + throw $e; + } + } + + // now that the response is cached, release the lock + $this->store->unlock($request); + } + + /** + * Restores the Response body. + */ + private function restoreResponseBody(Request $request, Response $response) + { + if ($response->headers->has('X-Body-Eval')) { + \assert(self::BODY_EVAL_BOUNDARY_LENGTH === 24); + + ob_start(); + + $content = $response->getContent(); + $boundary = substr($content, 0, 24); + $j = strpos($content, $boundary, 24); + echo substr($content, 24, $j - 24); + $i = $j + 24; + + while (false !== $j = strpos($content, $boundary, $i)) { + [$uri, $alt, $ignoreErrors, $part] = explode("\n", substr($content, $i, $j - $i), 4); + $i = $j + 24; + + echo $this->surrogate->handle($this, $uri, $alt, $ignoreErrors); + echo $part; + } + + $response->setContent(ob_get_clean()); + $response->headers->remove('X-Body-Eval'); + if (!$response->headers->has('Transfer-Encoding')) { + $response->headers->set('Content-Length', \strlen($response->getContent())); + } + } elseif ($response->headers->has('X-Body-File')) { + // Response does not include possibly dynamic content (ESI, SSI), so we need + // not handle the content for HEAD requests + if (!$request->isMethod('HEAD')) { + $response->setContent(file_get_contents($response->headers->get('X-Body-File'))); + } + } else { + return; + } + + $response->headers->remove('X-Body-File'); + } + + protected function processResponseBody(Request $request, Response $response) + { + if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) { + $this->surrogate->process($request, $response); + } + } + + /** + * Checks if the Request includes authorization or other sensitive information + * that should cause the Response to be considered private by default. + */ + private function isPrivateRequest(Request $request): bool + { + foreach ($this->options['private_headers'] as $key) { + $key = strtolower(str_replace('HTTP_', '', $key)); + + if ('cookie' === $key) { + if (\count($request->cookies->all())) { + return true; + } + } elseif ($request->headers->has($key)) { + return true; + } + } + + return false; + } + + /** + * Records that an event took place. + */ + private function record(Request $request, string $event) + { + $this->traces[$this->getTraceKey($request)][] = $event; + } + + /** + * Calculates the key we use in the "trace" array for a given request. + */ + private function getTraceKey(Request $request): string + { + $path = $request->getPathInfo(); + if ($qs = $request->getQueryString()) { + $path .= '?'.$qs; + } + + return $request->getMethod().' '.$path; + } + + /** + * Checks whether the given (cached) response may be served as "stale" when a revalidation + * is currently in progress. + */ + private function mayServeStaleWhileRevalidate(Response $entry): bool + { + $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate'); + + if (null === $timeout) { + $timeout = $this->options['stale_while_revalidate']; + } + + $age = $entry->getAge(); + $maxAge = $entry->getMaxAge() ?? 0; + $ttl = $maxAge - $age; + + return abs($ttl) < $timeout; + } + + /** + * Waits for the store to release a locked entry. + */ + private function waitForLock(Request $request): bool + { + $wait = 0; + while ($this->store->isLocked($request) && $wait < 100) { + usleep(50000); + ++$wait; + } + + return $wait < 100; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php new file mode 100644 index 0000000..5f372c5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php @@ -0,0 +1,234 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Response; + +/** + * ResponseCacheStrategy knows how to compute the Response cache HTTP header + * based on the different response cache headers. + * + * This implementation changes the main response TTL to the smallest TTL received + * or force validation if one of the surrogates has validation cache strategy. + * + * @author Fabien Potencier + */ +class ResponseCacheStrategy implements ResponseCacheStrategyInterface +{ + /** + * Cache-Control headers that are sent to the final response if they appear in ANY of the responses. + */ + private const OVERRIDE_DIRECTIVES = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate']; + + /** + * Cache-Control headers that are sent to the final response if they appear in ALL of the responses. + */ + private const INHERIT_DIRECTIVES = ['public', 'immutable']; + + private $embeddedResponses = 0; + private $isNotCacheableResponseEmbedded = false; + private $age = 0; + private $flagDirectives = [ + 'no-cache' => null, + 'no-store' => null, + 'no-transform' => null, + 'must-revalidate' => null, + 'proxy-revalidate' => null, + 'public' => null, + 'private' => null, + 'immutable' => null, + ]; + private $ageDirectives = [ + 'max-age' => null, + 's-maxage' => null, + 'expires' => null, + ]; + + /** + * {@inheritdoc} + */ + public function add(Response $response) + { + ++$this->embeddedResponses; + + foreach (self::OVERRIDE_DIRECTIVES as $directive) { + if ($response->headers->hasCacheControlDirective($directive)) { + $this->flagDirectives[$directive] = true; + } + } + + foreach (self::INHERIT_DIRECTIVES as $directive) { + if (false !== $this->flagDirectives[$directive]) { + $this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive); + } + } + + $age = $response->getAge(); + $this->age = max($this->age, $age); + + if ($this->willMakeFinalResponseUncacheable($response)) { + $this->isNotCacheableResponseEmbedded = true; + + return; + } + + $isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public'); + $maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null; + $this->storeRelativeAgeDirective('max-age', $maxAge, $age, $isHeuristicallyCacheable); + $sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge; + $this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $age, $isHeuristicallyCacheable); + + $expires = $response->getExpires(); + $expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null; + $this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable); + } + + /** + * {@inheritdoc} + */ + public function update(Response $response) + { + // if we have no embedded Response, do nothing + if (0 === $this->embeddedResponses) { + return; + } + + // Remove validation related headers of the master response, + // because some of the response content comes from at least + // one embedded response (which likely has a different caching strategy). + $response->setEtag(null); + $response->setLastModified(null); + + $this->add($response); + + $response->headers->set('Age', $this->age); + + if ($this->isNotCacheableResponseEmbedded) { + if ($this->flagDirectives['no-store']) { + $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate'); + } else { + $response->headers->set('Cache-Control', 'no-cache, must-revalidate'); + } + + return; + } + + $flags = array_filter($this->flagDirectives); + + if (isset($flags['must-revalidate'])) { + $flags['no-cache'] = true; + } + + $response->headers->set('Cache-Control', implode(', ', array_keys($flags))); + + $maxAge = null; + + if (is_numeric($this->ageDirectives['max-age'])) { + $maxAge = $this->ageDirectives['max-age'] + $this->age; + $response->headers->addCacheControlDirective('max-age', $maxAge); + } + + if (is_numeric($this->ageDirectives['s-maxage'])) { + $sMaxage = $this->ageDirectives['s-maxage'] + $this->age; + + if ($maxAge !== $sMaxage) { + $response->headers->addCacheControlDirective('s-maxage', $sMaxage); + } + } + + if (is_numeric($this->ageDirectives['expires'])) { + $date = clone $response->getDate(); + $date = $date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds'); + $response->setExpires($date); + } + } + + /** + * RFC2616, Section 13.4. + * + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4 + */ + private function willMakeFinalResponseUncacheable(Response $response): bool + { + // RFC2616: A response received with a status code of 200, 203, 300, 301 or 410 + // MAY be stored by a cache […] unless a cache-control directive prohibits caching. + if ($response->headers->hasCacheControlDirective('no-cache') + || $response->headers->getCacheControlDirective('no-store') + ) { + return true; + } + + // Last-Modified and Etag headers cannot be merged, they render the response uncacheable + // by default (except if the response also has max-age etc.). + if (\in_array($response->getStatusCode(), [200, 203, 300, 301, 410]) + && null === $response->getLastModified() + && null === $response->getEtag() + ) { + return false; + } + + // RFC2616: A response received with any other status code (e.g. status codes 302 and 307) + // MUST NOT be returned in a reply to a subsequent request unless there are + // cache-control directives or another header(s) that explicitly allow it. + $cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private']; + foreach ($cacheControl as $key) { + if ($response->headers->hasCacheControlDirective($key)) { + return false; + } + } + + if ($response->headers->has('Expires')) { + return false; + } + + return true; + } + + /** + * Store lowest max-age/s-maxage/expires for the final response. + * + * The response might have been stored in cache a while ago. To keep things comparable, + * we have to subtract the age so that the value is normalized for an age of 0. + * + * If the value is lower than the currently stored value, we update the value, to keep a rolling + * minimal value of each instruction. + * + * If the value is NULL and the isHeuristicallyCacheable parameter is false, the directive will + * not be set on the final response. In this case, not all responses had the directive set and no + * value can be found that satisfies the requirements of all responses. The directive will be dropped + * from the final response. + * + * If the isHeuristicallyCacheable parameter is true, however, the current response has been marked + * as cacheable in a public (shared) cache, but did not provide an explicit lifetime that would serve + * as an upper bound. In this case, we can proceed and possibly keep the directive on the final response. + */ + private function storeRelativeAgeDirective(string $directive, ?int $value, int $age, bool $isHeuristicallyCacheable) + { + if (null === $value) { + if ($isHeuristicallyCacheable) { + /* + * See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2 + * This particular response does not require maximum lifetime; heuristics might be applied. + * Other responses, however, might have more stringent requirements on maximum lifetime. + * So, return early here so that the final response can have the more limiting value set. + */ + return; + } + $this->ageDirectives[$directive] = false; + } + + if (false !== $this->ageDirectives[$directive]) { + $value -= $age; + $this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/ResponseCacheStrategyInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/ResponseCacheStrategyInterface.php new file mode 100644 index 0000000..e282299 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/ResponseCacheStrategyInterface.php @@ -0,0 +1,37 @@ + + * + * This code is partially based on the Rack-Cache library by Ryan Tomayko, + * which is released under the MIT license. + * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Response; + +/** + * ResponseCacheStrategyInterface implementations know how to compute the + * Response cache HTTP header based on the different response cache headers. + * + * @author Fabien Potencier + */ +interface ResponseCacheStrategyInterface +{ + /** + * Adds a Response. + */ + public function add(Response $response); + + /** + * Updates the Response HTTP headers based on the embedded Responses. + */ + public function update(Response $response); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Ssi.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Ssi.php new file mode 100644 index 0000000..d7903ff --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Ssi.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Ssi implements the SSI capabilities to Request and Response instances. + * + * @author Sebastian Krebs + */ +class Ssi extends AbstractSurrogate +{ + /** + * {@inheritdoc} + */ + public function getName() + { + return 'ssi'; + } + + /** + * {@inheritdoc} + */ + public function addSurrogateControl(Response $response) + { + if (str_contains($response->getContent(), '', $uri); + } + + /** + * {@inheritdoc} + */ + public function process(Request $request, Response $response) + { + $type = $response->headers->get('Content-Type'); + if (empty($type)) { + $type = 'text/html'; + } + + $parts = explode(';', $type); + if (!\in_array($parts[0], $this->contentTypes)) { + return $response; + } + + // we don't use a proper XML parser here as we can have SSI tags in a plain text response + $content = $response->getContent(); + $boundary = self::generateBodyEvalBoundary(); + $chunks = preg_split('##', $content, -1, \PREG_SPLIT_DELIM_CAPTURE); + + $i = 1; + while (isset($chunks[$i])) { + $options = []; + preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER); + foreach ($matches as $set) { + $options[$set[1]] = $set[2]; + } + + if (!isset($options['virtual'])) { + throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.'); + } + + $chunks[$i] = $boundary.$options['virtual']."\n\n\n"; + $i += 2; + } + $content = $boundary.implode('', $chunks).$boundary; + + $response->setContent($content); + $response->headers->set('X-Body-Eval', 'SSI'); + + // remove SSI/1.0 from the Surrogate-Control header + $this->removeFromControl($response); + + return $response; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Store.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Store.php new file mode 100644 index 0000000..f4810b2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/Store.php @@ -0,0 +1,499 @@ + + * + * This code is partially based on the Rack-Cache library by Ryan Tomayko, + * which is released under the MIT license. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Store implements all the logic for storing cache metadata (Request and Response headers). + * + * @author Fabien Potencier + */ +class Store implements StoreInterface +{ + protected $root; + /** @var \SplObjectStorage */ + private $keyCache; + /** @var array */ + private $locks = []; + private $options; + + /** + * Constructor. + * + * The available options are: + * + * * private_headers Set of response headers that should not be stored + * when a response is cached. (default: Set-Cookie) + * + * @throws \RuntimeException + */ + public function __construct(string $root, array $options = []) + { + $this->root = $root; + if (!is_dir($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) { + throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root)); + } + $this->keyCache = new \SplObjectStorage(); + $this->options = array_merge([ + 'private_headers' => ['Set-Cookie'], + ], $options); + } + + /** + * Cleanups storage. + */ + public function cleanup() + { + // unlock everything + foreach ($this->locks as $lock) { + flock($lock, \LOCK_UN); + fclose($lock); + } + + $this->locks = []; + } + + /** + * Tries to lock the cache for a given Request, without blocking. + * + * @return bool|string true if the lock is acquired, the path to the current lock otherwise + */ + public function lock(Request $request) + { + $key = $this->getCacheKey($request); + + if (!isset($this->locks[$key])) { + $path = $this->getPath($key); + if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) { + return $path; + } + $h = fopen($path, 'c'); + if (!flock($h, \LOCK_EX | \LOCK_NB)) { + fclose($h); + + return $path; + } + + $this->locks[$key] = $h; + } + + return true; + } + + /** + * Releases the lock for the given Request. + * + * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise + */ + public function unlock(Request $request) + { + $key = $this->getCacheKey($request); + + if (isset($this->locks[$key])) { + flock($this->locks[$key], \LOCK_UN); + fclose($this->locks[$key]); + unset($this->locks[$key]); + + return true; + } + + return false; + } + + public function isLocked(Request $request) + { + $key = $this->getCacheKey($request); + + if (isset($this->locks[$key])) { + return true; // shortcut if lock held by this process + } + + if (!is_file($path = $this->getPath($key))) { + return false; + } + + $h = fopen($path, 'r'); + flock($h, \LOCK_EX | \LOCK_NB, $wouldBlock); + flock($h, \LOCK_UN); // release the lock we just acquired + fclose($h); + + return (bool) $wouldBlock; + } + + /** + * Locates a cached Response for the Request provided. + * + * @return Response|null + */ + public function lookup(Request $request) + { + $key = $this->getCacheKey($request); + + if (!$entries = $this->getMetadata($key)) { + return null; + } + + // find a cached entry that matches the request. + $match = null; + foreach ($entries as $entry) { + if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) { + $match = $entry; + + break; + } + } + + if (null === $match) { + return null; + } + + $headers = $match[1]; + if (file_exists($path = $this->getPath($headers['x-content-digest'][0]))) { + return $this->restoreResponse($headers, $path); + } + + // TODO the metaStore referenced an entity that doesn't exist in + // the entityStore. We definitely want to return nil but we should + // also purge the entry from the meta-store when this is detected. + return null; + } + + /** + * Writes a cache entry to the store for the given Request and Response. + * + * Existing entries are read and any that match the response are removed. This + * method calls write with the new list of cache entries. + * + * @return string + * + * @throws \RuntimeException + */ + public function write(Request $request, Response $response) + { + $key = $this->getCacheKey($request); + $storedEnv = $this->persistRequest($request); + + if ($response->headers->has('X-Body-File')) { + // Assume the response came from disk, but at least perform some safeguard checks + if (!$response->headers->has('X-Content-Digest')) { + throw new \RuntimeException('A restored response must have the X-Content-Digest header.'); + } + + $digest = $response->headers->get('X-Content-Digest'); + if ($this->getPath($digest) !== $response->headers->get('X-Body-File')) { + throw new \RuntimeException('X-Body-File and X-Content-Digest do not match.'); + } + // Everything seems ok, omit writing content to disk + } else { + $digest = $this->generateContentDigest($response); + $response->headers->set('X-Content-Digest', $digest); + + if (!$this->save($digest, $response->getContent(), false)) { + throw new \RuntimeException('Unable to store the entity.'); + } + + if (!$response->headers->has('Transfer-Encoding')) { + $response->headers->set('Content-Length', \strlen($response->getContent())); + } + } + + // read existing cache entries, remove non-varying, and add this one to the list + $entries = []; + $vary = $response->headers->get('vary'); + foreach ($this->getMetadata($key) as $entry) { + if (!isset($entry[1]['vary'][0])) { + $entry[1]['vary'] = ['']; + } + + if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary ?? '', $entry[0], $storedEnv)) { + $entries[] = $entry; + } + } + + $headers = $this->persistResponse($response); + unset($headers['age']); + + foreach ($this->options['private_headers'] as $h) { + unset($headers[strtolower($h)]); + } + + array_unshift($entries, [$storedEnv, $headers]); + + if (!$this->save($key, serialize($entries))) { + throw new \RuntimeException('Unable to store the metadata.'); + } + + return $key; + } + + /** + * Returns content digest for $response. + * + * @return string + */ + protected function generateContentDigest(Response $response) + { + return 'en'.hash('sha256', $response->getContent()); + } + + /** + * Invalidates all cache entries that match the request. + * + * @throws \RuntimeException + */ + public function invalidate(Request $request) + { + $modified = false; + $key = $this->getCacheKey($request); + + $entries = []; + foreach ($this->getMetadata($key) as $entry) { + $response = $this->restoreResponse($entry[1]); + if ($response->isFresh()) { + $response->expire(); + $modified = true; + $entries[] = [$entry[0], $this->persistResponse($response)]; + } else { + $entries[] = $entry; + } + } + + if ($modified && !$this->save($key, serialize($entries))) { + throw new \RuntimeException('Unable to store the metadata.'); + } + } + + /** + * Determines whether two Request HTTP header sets are non-varying based on + * the vary response header value provided. + * + * @param string|null $vary A Response vary header + * @param array $env1 A Request HTTP header array + * @param array $env2 A Request HTTP header array + */ + private function requestsMatch(?string $vary, array $env1, array $env2): bool + { + if (empty($vary)) { + return true; + } + + foreach (preg_split('/[\s,]+/', $vary) as $header) { + $key = str_replace('_', '-', strtolower($header)); + $v1 = $env1[$key] ?? null; + $v2 = $env2[$key] ?? null; + if ($v1 !== $v2) { + return false; + } + } + + return true; + } + + /** + * Gets all data associated with the given key. + * + * Use this method only if you know what you are doing. + */ + private function getMetadata(string $key): array + { + if (!$entries = $this->load($key)) { + return []; + } + + return unserialize($entries) ?: []; + } + + /** + * Purges data for the given URL. + * + * This method purges both the HTTP and the HTTPS version of the cache entry. + * + * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise + */ + public function purge(string $url) + { + $http = preg_replace('#^https:#', 'http:', $url); + $https = preg_replace('#^http:#', 'https:', $url); + + $purgedHttp = $this->doPurge($http); + $purgedHttps = $this->doPurge($https); + + return $purgedHttp || $purgedHttps; + } + + /** + * Purges data for the given URL. + */ + private function doPurge(string $url): bool + { + $key = $this->getCacheKey(Request::create($url)); + if (isset($this->locks[$key])) { + flock($this->locks[$key], \LOCK_UN); + fclose($this->locks[$key]); + unset($this->locks[$key]); + } + + if (is_file($path = $this->getPath($key))) { + unlink($path); + + return true; + } + + return false; + } + + /** + * Loads data for the given key. + */ + private function load(string $key): ?string + { + $path = $this->getPath($key); + + return is_file($path) && false !== ($contents = @file_get_contents($path)) ? $contents : null; + } + + /** + * Save data for the given key. + */ + private function save(string $key, string $data, bool $overwrite = true): bool + { + $path = $this->getPath($key); + + if (!$overwrite && file_exists($path)) { + return true; + } + + if (isset($this->locks[$key])) { + $fp = $this->locks[$key]; + @ftruncate($fp, 0); + @fseek($fp, 0); + $len = @fwrite($fp, $data); + if (\strlen($data) !== $len) { + @ftruncate($fp, 0); + + return false; + } + } else { + if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) { + return false; + } + + $tmpFile = tempnam(\dirname($path), basename($path)); + if (false === $fp = @fopen($tmpFile, 'w')) { + @unlink($tmpFile); + + return false; + } + @fwrite($fp, $data); + @fclose($fp); + + if ($data != file_get_contents($tmpFile)) { + @unlink($tmpFile); + + return false; + } + + if (false === @rename($tmpFile, $path)) { + @unlink($tmpFile); + + return false; + } + } + + @chmod($path, 0666 & ~umask()); + + return true; + } + + public function getPath(string $key) + { + return $this->root.\DIRECTORY_SEPARATOR.substr($key, 0, 2).\DIRECTORY_SEPARATOR.substr($key, 2, 2).\DIRECTORY_SEPARATOR.substr($key, 4, 2).\DIRECTORY_SEPARATOR.substr($key, 6); + } + + /** + * Generates a cache key for the given Request. + * + * This method should return a key that must only depend on a + * normalized version of the request URI. + * + * If the same URI can have more than one representation, based on some + * headers, use a Vary header to indicate them, and each representation will + * be stored independently under the same cache key. + * + * @return string + */ + protected function generateCacheKey(Request $request) + { + return 'md'.hash('sha256', $request->getUri()); + } + + /** + * Returns a cache key for the given Request. + */ + private function getCacheKey(Request $request): string + { + if (isset($this->keyCache[$request])) { + return $this->keyCache[$request]; + } + + return $this->keyCache[$request] = $this->generateCacheKey($request); + } + + /** + * Persists the Request HTTP headers. + */ + private function persistRequest(Request $request): array + { + return $request->headers->all(); + } + + /** + * Persists the Response HTTP headers. + */ + private function persistResponse(Response $response): array + { + $headers = $response->headers->all(); + $headers['X-Status'] = [$response->getStatusCode()]; + + return $headers; + } + + /** + * Restores a Response from the HTTP headers and body. + */ + private function restoreResponse(array $headers, ?string $path = null): ?Response + { + $status = $headers['X-Status'][0]; + unset($headers['X-Status']); + $content = null; + + if (null !== $path) { + $headers['X-Body-File'] = [$path]; + unset($headers['x-body-file']); + + if ($headers['X-Body-Eval'] ?? $headers['x-body-eval'] ?? false) { + $content = file_get_contents($path); + \assert(HttpCache::BODY_EVAL_BOUNDARY_LENGTH === 24); + if (48 > \strlen($content) || substr($content, -24) !== substr($content, 0, 24)) { + return null; + } + } + } + + return new Response($content, $status, $headers); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/StoreInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/StoreInterface.php new file mode 100644 index 0000000..3d07ef3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/StoreInterface.php @@ -0,0 +1,81 @@ + + * + * This code is partially based on the Rack-Cache library by Ryan Tomayko, + * which is released under the MIT license. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Interface implemented by HTTP cache stores. + * + * @author Fabien Potencier + */ +interface StoreInterface +{ + /** + * Locates a cached Response for the Request provided. + * + * @return Response|null + */ + public function lookup(Request $request); + + /** + * Writes a cache entry to the store for the given Request and Response. + * + * Existing entries are read and any that match the response are removed. This + * method calls write with the new list of cache entries. + * + * @return string The key under which the response is stored + */ + public function write(Request $request, Response $response); + + /** + * Invalidates all cache entries that match the request. + */ + public function invalidate(Request $request); + + /** + * Locks the cache for a given Request. + * + * @return bool|string true if the lock is acquired, the path to the current lock otherwise + */ + public function lock(Request $request); + + /** + * Releases the lock for the given Request. + * + * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise + */ + public function unlock(Request $request); + + /** + * Returns whether or not a lock exists. + * + * @return bool true if lock exists, false otherwise + */ + public function isLocked(Request $request); + + /** + * Purges data for the given URL. + * + * @return bool true if the URL exists and has been purged, false otherwise + */ + public function purge(string $url); + + /** + * Cleanups storage. + */ + public function cleanup(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/SubRequestHandler.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/SubRequestHandler.php new file mode 100644 index 0000000..253071f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/SubRequestHandler.php @@ -0,0 +1,92 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\IpUtils; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +/** + * @author Nicolas Grekas + * + * @internal + */ +class SubRequestHandler +{ + public static function handle(HttpKernelInterface $kernel, Request $request, int $type, bool $catch): Response + { + // save global state related to trusted headers and proxies + $trustedProxies = Request::getTrustedProxies(); + $trustedHeaderSet = Request::getTrustedHeaderSet(); + + // remove untrusted values + $remoteAddr = $request->server->get('REMOTE_ADDR'); + if (!$remoteAddr || !IpUtils::checkIp($remoteAddr, $trustedProxies)) { + $trustedHeaders = [ + 'FORWARDED' => $trustedHeaderSet & Request::HEADER_FORWARDED, + 'X_FORWARDED_FOR' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_FOR, + 'X_FORWARDED_HOST' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_HOST, + 'X_FORWARDED_PROTO' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PROTO, + 'X_FORWARDED_PORT' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PORT, + 'X_FORWARDED_PREFIX' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PREFIX, + ]; + foreach (array_filter($trustedHeaders) as $name => $key) { + $request->headers->remove($name); + $request->server->remove('HTTP_'.$name); + } + } + + // compute trusted values, taking any trusted proxies into account + $trustedIps = []; + $trustedValues = []; + foreach (array_reverse($request->getClientIps()) as $ip) { + $trustedIps[] = $ip; + $trustedValues[] = sprintf('for="%s"', $ip); + } + if ($ip !== $remoteAddr) { + $trustedIps[] = $remoteAddr; + $trustedValues[] = sprintf('for="%s"', $remoteAddr); + } + + // set trusted values, reusing as much as possible the global trusted settings + if (Request::HEADER_FORWARDED & $trustedHeaderSet) { + $trustedValues[0] .= sprintf(';host="%s";proto=%s', $request->getHttpHost(), $request->getScheme()); + $request->headers->set('Forwarded', $v = implode(', ', $trustedValues)); + $request->server->set('HTTP_FORWARDED', $v); + } + if (Request::HEADER_X_FORWARDED_FOR & $trustedHeaderSet) { + $request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps)); + $request->server->set('HTTP_X_FORWARDED_FOR', $v); + } elseif (!(Request::HEADER_FORWARDED & $trustedHeaderSet)) { + Request::setTrustedProxies($trustedProxies, $trustedHeaderSet | Request::HEADER_X_FORWARDED_FOR); + $request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps)); + $request->server->set('HTTP_X_FORWARDED_FOR', $v); + } + + // fix the client IP address by setting it to 127.0.0.1, + // which is the core responsibility of this method + $request->server->set('REMOTE_ADDR', '127.0.0.1'); + + // ensure 127.0.0.1 is set as trusted proxy + if (!IpUtils::checkIp('127.0.0.1', $trustedProxies)) { + Request::setTrustedProxies(array_merge($trustedProxies, ['127.0.0.1']), Request::getTrustedHeaderSet()); + } + + try { + return $kernel->handle($request, $type, $catch); + } finally { + // restore global state + Request::setTrustedProxies($trustedProxies, $trustedHeaderSet); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/SurrogateInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/SurrogateInterface.php new file mode 100644 index 0000000..12ed055 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpCache/SurrogateInterface.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\HttpKernel\HttpCache; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +interface SurrogateInterface +{ + /** + * Returns surrogate name. + * + * @return string + */ + public function getName(); + + /** + * Returns a new cache strategy instance. + * + * @return ResponseCacheStrategyInterface + */ + public function createCacheStrategy(); + + /** + * Checks that at least one surrogate has Surrogate capability. + * + * @return bool + */ + public function hasSurrogateCapability(Request $request); + + /** + * Adds Surrogate-capability to the given Request. + */ + public function addSurrogateCapability(Request $request); + + /** + * Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. + * + * This method only adds an Surrogate HTTP header if the Response has some Surrogate tags. + */ + public function addSurrogateControl(Response $response); + + /** + * Checks that the Response needs to be parsed for Surrogate tags. + * + * @return bool + */ + public function needsParsing(Response $response); + + /** + * Renders a Surrogate tag. + * + * @param string|null $alt An alternate URI + * @param string $comment A comment to add as an esi:include tag + * + * @return string + */ + public function renderIncludeTag(string $uri, ?string $alt = null, bool $ignoreErrors = true, string $comment = ''); + + /** + * Replaces a Response Surrogate tags with the included resource content. + * + * @return Response + */ + public function process(Request $request, Response $response); + + /** + * Handles a Surrogate from the cache. + * + * @param string $alt An alternative URI + * + * @return string + * + * @throws \RuntimeException + * @throws \Exception + */ + public function handle(HttpCache $cache, string $uri, string $alt, bool $ignoreErrors); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpClientKernel.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpClientKernel.php new file mode 100644 index 0000000..2b4620b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpClientKernel.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Component\HttpClient\HttpClient; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\ResponseHeaderBag; +use Symfony\Component\Mime\Part\AbstractPart; +use Symfony\Component\Mime\Part\DataPart; +use Symfony\Component\Mime\Part\Multipart\FormDataPart; +use Symfony\Component\Mime\Part\TextPart; +use Symfony\Contracts\HttpClient\HttpClientInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(ResponseHeaderBag::class); + +/** + * An implementation of a Symfony HTTP kernel using a "real" HTTP client. + * + * @author Fabien Potencier + */ +final class HttpClientKernel implements HttpKernelInterface +{ + private $client; + + public function __construct(?HttpClientInterface $client = null) + { + if (null === $client && !class_exists(HttpClient::class)) { + throw new \LogicException(sprintf('You cannot use "%s" as the HttpClient component is not installed. Try running "composer require symfony/http-client".', __CLASS__)); + } + + $this->client = $client ?? HttpClient::create(); + } + + public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response + { + $headers = $this->getHeaders($request); + $body = ''; + if (null !== $part = $this->getBody($request)) { + $headers = array_merge($headers, $part->getPreparedHeaders()->toArray()); + $body = $part->bodyToIterable(); + } + $response = $this->client->request($request->getMethod(), $request->getUri(), [ + 'headers' => $headers, + 'body' => $body, + ] + $request->attributes->get('http_client_options', [])); + + $response = new Response($response->getContent(!$catch), $response->getStatusCode(), $response->getHeaders(!$catch)); + + $response->headers->remove('X-Body-File'); + $response->headers->remove('X-Body-Eval'); + $response->headers->remove('X-Content-Digest'); + + $response->headers = new class($response->headers->all()) extends ResponseHeaderBag { + protected function computeCacheControlValue(): string + { + return $this->getCacheControlHeader(); // preserve the original value + } + }; + + return $response; + } + + private function getBody(Request $request): ?AbstractPart + { + if (\in_array($request->getMethod(), ['GET', 'HEAD'])) { + return null; + } + + if (!class_exists(AbstractPart::class)) { + throw new \LogicException('You cannot pass non-empty bodies as the Mime component is not installed. Try running "composer require symfony/mime".'); + } + + if ($content = $request->getContent()) { + return new TextPart($content, 'utf-8', 'plain', '8bit'); + } + + $fields = $request->request->all(); + foreach ($request->files->all() as $name => $file) { + $fields[$name] = DataPart::fromPath($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType()); + } + + return new FormDataPart($fields); + } + + private function getHeaders(Request $request): array + { + $headers = []; + foreach ($request->headers as $key => $value) { + $headers[$key] = $value; + } + $cookies = []; + foreach ($request->cookies->all() as $name => $value) { + $cookies[] = $name.'='.$value; + } + if ($cookies) { + $headers['cookie'] = implode('; ', $cookies); + } + + return $headers; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpKernel.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpKernel.php new file mode 100644 index 0000000..f4b4b8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpKernel.php @@ -0,0 +1,299 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver; +use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; +use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; +use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; +use Symfony\Component\HttpKernel\Event\ControllerEvent; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\Event\TerminateEvent; +use Symfony\Component\HttpKernel\Event\ViewEvent; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; +use Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(ControllerArgumentsEvent::class); +class_exists(ControllerEvent::class); +class_exists(ExceptionEvent::class); +class_exists(FinishRequestEvent::class); +class_exists(RequestEvent::class); +class_exists(ResponseEvent::class); +class_exists(TerminateEvent::class); +class_exists(ViewEvent::class); +class_exists(KernelEvents::class); + +/** + * HttpKernel notifies events to convert a Request object to a Response one. + * + * @author Fabien Potencier + */ +class HttpKernel implements HttpKernelInterface, TerminableInterface +{ + protected $dispatcher; + protected $resolver; + protected $requestStack; + private $argumentResolver; + + public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, ?RequestStack $requestStack = null, ?ArgumentResolverInterface $argumentResolver = null) + { + $this->dispatcher = $dispatcher; + $this->resolver = $resolver; + $this->requestStack = $requestStack ?? new RequestStack(); + $this->argumentResolver = $argumentResolver ?? new ArgumentResolver(); + } + + /** + * {@inheritdoc} + */ + public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true) + { + $request->headers->set('X-Php-Ob-Level', (string) ob_get_level()); + + $this->requestStack->push($request); + try { + return $this->handleRaw($request, $type); + } catch (\Exception $e) { + if ($e instanceof RequestExceptionInterface) { + $e = new BadRequestHttpException($e->getMessage(), $e); + } + if (false === $catch) { + $this->finishRequest($request, $type); + + throw $e; + } + + return $this->handleThrowable($e, $request, $type); + } finally { + $this->requestStack->pop(); + } + } + + /** + * {@inheritdoc} + */ + public function terminate(Request $request, Response $response) + { + $this->dispatcher->dispatch(new TerminateEvent($this, $request, $response), KernelEvents::TERMINATE); + } + + /** + * @internal + */ + public function terminateWithException(\Throwable $exception, ?Request $request = null) + { + if (!$request = $request ?: $this->requestStack->getMainRequest()) { + throw $exception; + } + + if ($pop = $request !== $this->requestStack->getMainRequest()) { + $this->requestStack->push($request); + } + + try { + $response = $this->handleThrowable($exception, $request, self::MAIN_REQUEST); + } finally { + if ($pop) { + $this->requestStack->pop(); + } + } + + $response->sendHeaders(); + $response->sendContent(); + + $this->terminate($request, $response); + } + + /** + * Handles a request to convert it to a response. + * + * Exceptions are not caught. + * + * @throws \LogicException If one of the listener does not behave as expected + * @throws NotFoundHttpException When controller cannot be found + */ + private function handleRaw(Request $request, int $type = self::MAIN_REQUEST): Response + { + // request + $event = new RequestEvent($this, $request, $type); + $this->dispatcher->dispatch($event, KernelEvents::REQUEST); + + if ($event->hasResponse()) { + return $this->filterResponse($event->getResponse(), $request, $type); + } + + // load controller + if (false === $controller = $this->resolver->getController($request)) { + throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo())); + } + + $event = new ControllerEvent($this, $controller, $request, $type); + $this->dispatcher->dispatch($event, KernelEvents::CONTROLLER); + $controller = $event->getController(); + + // controller arguments + $arguments = $this->argumentResolver->getArguments($request, $controller); + + $event = new ControllerArgumentsEvent($this, $controller, $arguments, $request, $type); + $this->dispatcher->dispatch($event, KernelEvents::CONTROLLER_ARGUMENTS); + $controller = $event->getController(); + $arguments = $event->getArguments(); + + // call controller + $response = $controller(...$arguments); + + // view + if (!$response instanceof Response) { + $event = new ViewEvent($this, $request, $type, $response); + $this->dispatcher->dispatch($event, KernelEvents::VIEW); + + if ($event->hasResponse()) { + $response = $event->getResponse(); + } else { + $msg = sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.', $this->varToString($response)); + + // the user may have forgotten to return something + if (null === $response) { + $msg .= ' Did you forget to add a return statement somewhere in your controller?'; + } + + throw new ControllerDoesNotReturnResponseException($msg, $controller, __FILE__, __LINE__ - 17); + } + } + + return $this->filterResponse($response, $request, $type); + } + + /** + * Filters a response object. + * + * @throws \RuntimeException if the passed object is not a Response instance + */ + private function filterResponse(Response $response, Request $request, int $type): Response + { + $event = new ResponseEvent($this, $request, $type, $response); + + $this->dispatcher->dispatch($event, KernelEvents::RESPONSE); + + $this->finishRequest($request, $type); + + return $event->getResponse(); + } + + /** + * Publishes the finish request event, then pop the request from the stack. + * + * Note that the order of the operations is important here, otherwise + * operations such as {@link RequestStack::getParentRequest()} can lead to + * weird results. + */ + private function finishRequest(Request $request, int $type) + { + $this->dispatcher->dispatch(new FinishRequestEvent($this, $request, $type), KernelEvents::FINISH_REQUEST); + } + + /** + * Handles a throwable by trying to convert it to a Response. + * + * @throws \Exception + */ + private function handleThrowable(\Throwable $e, Request $request, int $type): Response + { + $event = new ExceptionEvent($this, $request, $type, $e); + $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION); + + // a listener might have replaced the exception + $e = $event->getThrowable(); + + if (!$event->hasResponse()) { + $this->finishRequest($request, $type); + + throw $e; + } + + $response = $event->getResponse(); + + // the developer asked for a specific status code + if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) { + // ensure that we actually have an error response + if ($e instanceof HttpExceptionInterface) { + // keep the HTTP status code and headers + $response->setStatusCode($e->getStatusCode()); + $response->headers->add($e->getHeaders()); + } else { + $response->setStatusCode(500); + } + } + + try { + return $this->filterResponse($response, $request, $type); + } catch (\Exception $e) { + return $response; + } + } + + /** + * Returns a human-readable string for the specified variable. + */ + private function varToString($var): string + { + if (\is_object($var)) { + return sprintf('an object of type %s', \get_class($var)); + } + + if (\is_array($var)) { + $a = []; + foreach ($var as $k => $v) { + $a[] = sprintf('%s => ...', $k); + } + + return sprintf('an array ([%s])', mb_substr(implode(', ', $a), 0, 255)); + } + + if (\is_resource($var)) { + return sprintf('a resource (%s)', get_resource_type($var)); + } + + if (null === $var) { + return 'null'; + } + + if (false === $var) { + return 'a boolean value (false)'; + } + + if (true === $var) { + return 'a boolean value (true)'; + } + + if (\is_string($var)) { + return sprintf('a string ("%s%s")', mb_substr($var, 0, 255), mb_strlen($var) > 255 ? '...' : ''); + } + + if (is_numeric($var)) { + return sprintf('a number (%s)', (string) $var); + } + + return (string) $var; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpKernelBrowser.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpKernelBrowser.php new file mode 100644 index 0000000..5c6506c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpKernelBrowser.php @@ -0,0 +1,208 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Component\BrowserKit\AbstractBrowser; +use Symfony\Component\BrowserKit\CookieJar; +use Symfony\Component\BrowserKit\History; +use Symfony\Component\BrowserKit\Request as DomRequest; +use Symfony\Component\BrowserKit\Response as DomResponse; +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Simulates a browser and makes requests to an HttpKernel instance. + * + * @author Fabien Potencier + * + * @method Request getRequest() + * @method Response getResponse() + */ +class HttpKernelBrowser extends AbstractBrowser +{ + protected $kernel; + private $catchExceptions = true; + + /** + * @param array $server The server parameters (equivalent of $_SERVER) + */ + public function __construct(HttpKernelInterface $kernel, array $server = [], ?History $history = null, ?CookieJar $cookieJar = null) + { + // These class properties must be set before calling the parent constructor, as it may depend on it. + $this->kernel = $kernel; + $this->followRedirects = false; + + parent::__construct($server, $history, $cookieJar); + } + + /** + * Sets whether to catch exceptions when the kernel is handling a request. + */ + public function catchExceptions(bool $catchExceptions) + { + $this->catchExceptions = $catchExceptions; + } + + /** + * {@inheritdoc} + * + * @param Request $request + * + * @return Response + */ + protected function doRequest(object $request) + { + $response = $this->kernel->handle($request, HttpKernelInterface::MAIN_REQUEST, $this->catchExceptions); + + if ($this->kernel instanceof TerminableInterface) { + $this->kernel->terminate($request, $response); + } + + return $response; + } + + /** + * {@inheritdoc} + * + * @param Request $request + * + * @return string + */ + protected function getScript(object $request) + { + $kernel = var_export(serialize($this->kernel), true); + $request = var_export(serialize($request), true); + + $errorReporting = error_reporting(); + + $requires = ''; + foreach (get_declared_classes() as $class) { + if (0 === strpos($class, 'ComposerAutoloaderInit')) { + $r = new \ReflectionClass($class); + $file = \dirname($r->getFileName(), 2).'/autoload.php'; + if (file_exists($file)) { + $requires .= 'require_once '.var_export($file, true).";\n"; + } + } + } + + if (!$requires) { + throw new \RuntimeException('Composer autoloader not found.'); + } + + $code = <<getHandleScript(); + } + + protected function getHandleScript() + { + return <<<'EOF' +$response = $kernel->handle($request); + +if ($kernel instanceof Symfony\Component\HttpKernel\TerminableInterface) { + $kernel->terminate($request, $response); +} + +echo serialize($response); +EOF; + } + + /** + * {@inheritdoc} + * + * @return Request + */ + protected function filterRequest(DomRequest $request) + { + $httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $server = $request->getServer(), $request->getContent()); + if (!isset($server['HTTP_ACCEPT'])) { + $httpRequest->headers->remove('Accept'); + } + + foreach ($this->filterFiles($httpRequest->files->all()) as $key => $value) { + $httpRequest->files->set($key, $value); + } + + return $httpRequest; + } + + /** + * Filters an array of files. + * + * This method created test instances of UploadedFile so that the move() + * method can be called on those instances. + * + * If the size of a file is greater than the allowed size (from php.ini) then + * an invalid UploadedFile is returned with an error set to UPLOAD_ERR_INI_SIZE. + * + * @see UploadedFile + * + * @return array + */ + protected function filterFiles(array $files) + { + $filtered = []; + foreach ($files as $key => $value) { + if (\is_array($value)) { + $filtered[$key] = $this->filterFiles($value); + } elseif ($value instanceof UploadedFile) { + if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) { + $filtered[$key] = new UploadedFile( + '', + $value->getClientOriginalName(), + $value->getClientMimeType(), + \UPLOAD_ERR_INI_SIZE, + true + ); + } else { + $filtered[$key] = new UploadedFile( + $value->getPathname(), + $value->getClientOriginalName(), + $value->getClientMimeType(), + $value->getError(), + true + ); + } + } + } + + return $filtered; + } + + /** + * {@inheritdoc} + * + * @param Response $response + * + * @return DomResponse + */ + protected function filterResponse(object $response) + { + // this is needed to support StreamedResponse + ob_start(); + $response->sendContent(); + $content = ob_get_clean(); + + return new DomResponse($content, $response->getStatusCode(), $response->headers->all()); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/HttpKernelInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/HttpKernelInterface.php new file mode 100644 index 0000000..0449240 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/HttpKernelInterface.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * HttpKernelInterface handles a Request to convert it to a Response. + * + * @author Fabien Potencier + */ +interface HttpKernelInterface +{ + public const MAIN_REQUEST = 1; + public const SUB_REQUEST = 2; + + /** + * @deprecated since symfony/http-kernel 5.3, use MAIN_REQUEST instead. + * To ease the migration, this constant won't be removed until Symfony 7.0. + */ + public const MASTER_REQUEST = self::MAIN_REQUEST; + + /** + * Handles a Request to convert it to a Response. + * + * When $catch is true, the implementation must catch all exceptions + * and do its best to convert them to a Response instance. + * + * @param int $type The type of the request + * (one of HttpKernelInterface::MAIN_REQUEST or HttpKernelInterface::SUB_REQUEST) + * @param bool $catch Whether to catch exceptions or not + * + * @return Response + * + * @throws \Exception When an Exception occurs during processing + */ + public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Kernel.php b/php/libraries/composer/vendor/symfony/http-kernel/Kernel.php new file mode 100644 index 0000000..27d505f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Kernel.php @@ -0,0 +1,883 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator; +use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper; +use Symfony\Component\Config\Builder\ConfigBuilderGenerator; +use Symfony\Component\Config\ConfigCache; +use Symfony\Component\Config\Loader\DelegatingLoader; +use Symfony\Component\Config\Loader\LoaderResolver; +use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\PassConfig; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Dumper\PhpDumper; +use Symfony\Component\DependencyInjection\Dumper\Preloader; +use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; +use Symfony\Component\DependencyInjection\Loader\ClosureLoader; +use Symfony\Component\DependencyInjection\Loader\DirectoryLoader; +use Symfony\Component\DependencyInjection\Loader\GlobFileLoader; +use Symfony\Component\DependencyInjection\Loader\IniFileLoader; +use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; +use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; +use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; +use Symfony\Component\ErrorHandler\DebugClassLoader; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; +use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface; +use Symfony\Component\HttpKernel\Config\FileLocator; +use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass; +use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass; + +// Help opcache.preload discover always-needed symbols +class_exists(ConfigCache::class); + +/** + * The Kernel is the heart of the Symfony system. + * + * It manages an environment made of bundles. + * + * Environment names must always start with a letter and + * they must only contain letters and numbers. + * + * @author Fabien Potencier + */ +abstract class Kernel implements KernelInterface, RebootableInterface, TerminableInterface +{ + /** + * @var array + */ + protected $bundles = []; + + protected $container; + protected $environment; + protected $debug; + protected $booted = false; + protected $startTime; + + private $projectDir; + private $warmupDir; + private $requestStackSize = 0; + private $resetServices = false; + + /** + * @var array + */ + private static $freshCache = []; + + public const VERSION = '5.4.37'; + public const VERSION_ID = 50437; + public const MAJOR_VERSION = 5; + public const MINOR_VERSION = 4; + public const RELEASE_VERSION = 37; + public const EXTRA_VERSION = ''; + + public const END_OF_MAINTENANCE = '11/2024'; + public const END_OF_LIFE = '11/2025'; + + public function __construct(string $environment, bool $debug) + { + if (!$this->environment = $environment) { + throw new \InvalidArgumentException(sprintf('Invalid environment provided to "%s": the environment cannot be empty.', get_debug_type($this))); + } + + $this->debug = $debug; + } + + public function __clone() + { + $this->booted = false; + $this->container = null; + $this->requestStackSize = 0; + $this->resetServices = false; + } + + /** + * {@inheritdoc} + */ + public function boot() + { + if (true === $this->booted) { + if (!$this->requestStackSize && $this->resetServices) { + if ($this->container->has('services_resetter')) { + $this->container->get('services_resetter')->reset(); + } + $this->resetServices = false; + if ($this->debug) { + $this->startTime = microtime(true); + } + } + + return; + } + + if (null === $this->container) { + $this->preBoot(); + } + + foreach ($this->getBundles() as $bundle) { + $bundle->setContainer($this->container); + $bundle->boot(); + } + + $this->booted = true; + } + + /** + * {@inheritdoc} + */ + public function reboot(?string $warmupDir) + { + $this->shutdown(); + $this->warmupDir = $warmupDir; + $this->boot(); + } + + /** + * {@inheritdoc} + */ + public function terminate(Request $request, Response $response) + { + if (false === $this->booted) { + return; + } + + if ($this->getHttpKernel() instanceof TerminableInterface) { + $this->getHttpKernel()->terminate($request, $response); + } + } + + /** + * {@inheritdoc} + */ + public function shutdown() + { + if (false === $this->booted) { + return; + } + + $this->booted = false; + + foreach ($this->getBundles() as $bundle) { + $bundle->shutdown(); + $bundle->setContainer(null); + } + + $this->container = null; + $this->requestStackSize = 0; + $this->resetServices = false; + } + + /** + * {@inheritdoc} + */ + public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true) + { + if (!$this->booted) { + $container = $this->container ?? $this->preBoot(); + + if ($container->has('http_cache')) { + return $container->get('http_cache')->handle($request, $type, $catch); + } + } + + $this->boot(); + ++$this->requestStackSize; + $this->resetServices = true; + + try { + return $this->getHttpKernel()->handle($request, $type, $catch); + } finally { + --$this->requestStackSize; + } + } + + /** + * Gets an HTTP kernel from the container. + * + * @return HttpKernelInterface + */ + protected function getHttpKernel() + { + return $this->container->get('http_kernel'); + } + + /** + * {@inheritdoc} + */ + public function getBundles() + { + return $this->bundles; + } + + /** + * {@inheritdoc} + */ + public function getBundle(string $name) + { + if (!isset($this->bundles[$name])) { + throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled. Maybe you forgot to add it in the "registerBundles()" method of your "%s.php" file?', $name, get_debug_type($this))); + } + + return $this->bundles[$name]; + } + + /** + * {@inheritdoc} + */ + public function locateResource(string $name) + { + if ('@' !== $name[0]) { + throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name)); + } + + if (str_contains($name, '..')) { + throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name)); + } + + $bundleName = substr($name, 1); + $path = ''; + if (str_contains($bundleName, '/')) { + [$bundleName, $path] = explode('/', $bundleName, 2); + } + + $bundle = $this->getBundle($bundleName); + if (file_exists($file = $bundle->getPath().'/'.$path)) { + return $file; + } + + throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name)); + } + + /** + * {@inheritdoc} + */ + public function getEnvironment() + { + return $this->environment; + } + + /** + * {@inheritdoc} + */ + public function isDebug() + { + return $this->debug; + } + + /** + * Gets the application root dir (path of the project's composer file). + * + * @return string + */ + public function getProjectDir() + { + if (null === $this->projectDir) { + $r = new \ReflectionObject($this); + + if (!is_file($dir = $r->getFileName())) { + throw new \LogicException(sprintf('Cannot auto-detect project dir for kernel of class "%s".', $r->name)); + } + + $dir = $rootDir = \dirname($dir); + while (!is_file($dir.'/composer.json')) { + if ($dir === \dirname($dir)) { + return $this->projectDir = $rootDir; + } + $dir = \dirname($dir); + } + $this->projectDir = $dir; + } + + return $this->projectDir; + } + + /** + * {@inheritdoc} + */ + public function getContainer() + { + if (!$this->container) { + throw new \LogicException('Cannot retrieve the container from a non-booted kernel.'); + } + + return $this->container; + } + + /** + * @internal + */ + public function setAnnotatedClassCache(array $annotatedClasses) + { + file_put_contents(($this->warmupDir ?: $this->getBuildDir()).'/annotations.map', sprintf('debug && null !== $this->startTime ? $this->startTime : -\INF; + } + + /** + * {@inheritdoc} + */ + public function getCacheDir() + { + return $this->getProjectDir().'/var/cache/'.$this->environment; + } + + /** + * {@inheritdoc} + */ + public function getBuildDir(): string + { + // Returns $this->getCacheDir() for backward compatibility + return $this->getCacheDir(); + } + + /** + * {@inheritdoc} + */ + public function getLogDir() + { + return $this->getProjectDir().'/var/log'; + } + + /** + * {@inheritdoc} + */ + public function getCharset() + { + return 'UTF-8'; + } + + /** + * Gets the patterns defining the classes to parse and cache for annotations. + */ + public function getAnnotatedClassesToCompile(): array + { + return []; + } + + /** + * Initializes bundles. + * + * @throws \LogicException if two bundles share a common name + */ + protected function initializeBundles() + { + // init bundles + $this->bundles = []; + foreach ($this->registerBundles() as $bundle) { + $name = $bundle->getName(); + if (isset($this->bundles[$name])) { + throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s".', $name)); + } + $this->bundles[$name] = $bundle; + } + } + + /** + * The extension point similar to the Bundle::build() method. + * + * Use this method to register compiler passes and manipulate the container during the building process. + */ + protected function build(ContainerBuilder $container) + { + } + + /** + * Gets the container class. + * + * @return string + * + * @throws \InvalidArgumentException If the generated classname is invalid + */ + protected function getContainerClass() + { + $class = static::class; + $class = str_contains($class, "@anonymous\0") ? get_parent_class($class).str_replace('.', '_', ContainerBuilder::hash($class)) : $class; + $class = str_replace('\\', '_', $class).ucfirst($this->environment).($this->debug ? 'Debug' : '').'Container'; + + if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $class)) { + throw new \InvalidArgumentException(sprintf('The environment "%s" contains invalid characters, it can only contain characters allowed in PHP class names.', $this->environment)); + } + + return $class; + } + + /** + * Gets the container's base class. + * + * All names except Container must be fully qualified. + * + * @return string + */ + protected function getContainerBaseClass() + { + return 'Container'; + } + + /** + * Initializes the service container. + * + * The built version of the service container is used when fresh, otherwise the + * container is built. + */ + protected function initializeContainer() + { + $class = $this->getContainerClass(); + $buildDir = $this->warmupDir ?: $this->getBuildDir(); + $cache = new ConfigCache($buildDir.'/'.$class.'.php', $this->debug); + $cachePath = $cache->getPath(); + + // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors + $errorLevel = error_reporting(\E_ALL ^ \E_WARNING); + + try { + if (is_file($cachePath) && \is_object($this->container = include $cachePath) + && (!$this->debug || (self::$freshCache[$cachePath] ?? $cache->isFresh())) + ) { + self::$freshCache[$cachePath] = true; + $this->container->set('kernel', $this); + error_reporting($errorLevel); + + return; + } + } catch (\Throwable $e) { + } + + $oldContainer = \is_object($this->container) ? new \ReflectionClass($this->container) : $this->container = null; + + try { + is_dir($buildDir) ?: mkdir($buildDir, 0777, true); + + if ($lock = fopen($cachePath.'.lock', 'w+')) { + if (!flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock) && !flock($lock, $wouldBlock ? \LOCK_SH : \LOCK_EX)) { + fclose($lock); + $lock = null; + } elseif (!is_file($cachePath) || !\is_object($this->container = include $cachePath)) { + $this->container = null; + } elseif (!$oldContainer || \get_class($this->container) !== $oldContainer->name) { + flock($lock, \LOCK_UN); + fclose($lock); + $this->container->set('kernel', $this); + + return; + } + } + } catch (\Throwable $e) { + } finally { + error_reporting($errorLevel); + } + + if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) { + $collectedLogs = []; + $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { + if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) { + return $previousHandler ? $previousHandler($type, $message, $file, $line) : false; + } + + if (isset($collectedLogs[$message])) { + ++$collectedLogs[$message]['count']; + + return null; + } + + $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5); + // Clean the trace by removing first frames added by the error handler itself. + for ($i = 0; isset($backtrace[$i]); ++$i) { + if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) { + $backtrace = \array_slice($backtrace, 1 + $i); + break; + } + } + for ($i = 0; isset($backtrace[$i]); ++$i) { + if (!isset($backtrace[$i]['file'], $backtrace[$i]['line'], $backtrace[$i]['function'])) { + continue; + } + if (!isset($backtrace[$i]['class']) && 'trigger_deprecation' === $backtrace[$i]['function']) { + $file = $backtrace[$i]['file']; + $line = $backtrace[$i]['line']; + $backtrace = \array_slice($backtrace, 1 + $i); + break; + } + } + + // Remove frames added by DebugClassLoader. + for ($i = \count($backtrace) - 2; 0 < $i; --$i) { + if (\in_array($backtrace[$i]['class'] ?? null, [DebugClassLoader::class, LegacyDebugClassLoader::class], true)) { + $backtrace = [$backtrace[$i + 1]]; + break; + } + } + + $collectedLogs[$message] = [ + 'type' => $type, + 'message' => $message, + 'file' => $file, + 'line' => $line, + 'trace' => [$backtrace[0]], + 'count' => 1, + ]; + + return null; + }); + } + + try { + $container = null; + $container = $this->buildContainer(); + $container->compile(); + } finally { + if ($collectDeprecations) { + restore_error_handler(); + + @file_put_contents($buildDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs))); + @file_put_contents($buildDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : ''); + } + } + + $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass()); + + if ($lock) { + flock($lock, \LOCK_UN); + fclose($lock); + } + + $this->container = require $cachePath; + $this->container->set('kernel', $this); + + if ($oldContainer && \get_class($this->container) !== $oldContainer->name) { + // Because concurrent requests might still be using them, + // old container files are not removed immediately, + // but on a next dump of the container. + static $legacyContainers = []; + $oldContainerDir = \dirname($oldContainer->getFileName()); + $legacyContainers[$oldContainerDir.'.legacy'] = true; + foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy', \GLOB_NOSORT) as $legacyContainer) { + if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) { + (new Filesystem())->remove(substr($legacyContainer, 0, -7)); + } + } + + touch($oldContainerDir.'.legacy'); + } + + $preload = $this instanceof WarmableInterface ? (array) $this->warmUp($this->container->getParameter('kernel.cache_dir')) : []; + + if ($this->container->has('cache_warmer')) { + $preload = array_merge($preload, (array) $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'))); + } + + if ($preload && method_exists(Preloader::class, 'append') && file_exists($preloadFile = $buildDir.'/'.$class.'.preload.php')) { + Preloader::append($preloadFile, $preload); + } + } + + /** + * Returns the kernel parameters. + * + * @return array + */ + protected function getKernelParameters() + { + $bundles = []; + $bundlesMetadata = []; + + foreach ($this->bundles as $name => $bundle) { + $bundles[$name] = \get_class($bundle); + $bundlesMetadata[$name] = [ + 'path' => $bundle->getPath(), + 'namespace' => $bundle->getNamespace(), + ]; + } + + return [ + 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(), + 'kernel.environment' => $this->environment, + 'kernel.runtime_environment' => '%env(default:kernel.environment:APP_RUNTIME_ENV)%', + 'kernel.debug' => $this->debug, + 'kernel.build_dir' => realpath($buildDir = $this->warmupDir ?: $this->getBuildDir()) ?: $buildDir, + 'kernel.cache_dir' => realpath($cacheDir = ($this->getCacheDir() === $this->getBuildDir() ? ($this->warmupDir ?: $this->getCacheDir()) : $this->getCacheDir())) ?: $cacheDir, + 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(), + 'kernel.bundles' => $bundles, + 'kernel.bundles_metadata' => $bundlesMetadata, + 'kernel.charset' => $this->getCharset(), + 'kernel.container_class' => $this->getContainerClass(), + ]; + } + + /** + * Builds the service container. + * + * @return ContainerBuilder + * + * @throws \RuntimeException + */ + protected function buildContainer() + { + foreach (['cache' => $this->getCacheDir(), 'build' => $this->warmupDir ?: $this->getBuildDir(), 'logs' => $this->getLogDir()] as $name => $dir) { + if (!is_dir($dir)) { + if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new \RuntimeException(sprintf('Unable to create the "%s" directory (%s).', $name, $dir)); + } + } elseif (!is_writable($dir)) { + throw new \RuntimeException(sprintf('Unable to write in the "%s" directory (%s).', $name, $dir)); + } + } + + $container = $this->getContainerBuilder(); + $container->addObjectResource($this); + $this->prepareContainer($container); + + if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) { + trigger_deprecation('symfony/http-kernel', '5.3', 'Returning a ContainerBuilder from "%s::registerContainerConfiguration()" is deprecated.', get_debug_type($this)); + $container->merge($cont); + } + + $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this)); + + return $container; + } + + /** + * Prepares the ContainerBuilder before it is compiled. + */ + protected function prepareContainer(ContainerBuilder $container) + { + $extensions = []; + foreach ($this->bundles as $bundle) { + if ($extension = $bundle->getContainerExtension()) { + $container->registerExtension($extension); + } + + if ($this->debug) { + $container->addObjectResource($bundle); + } + } + + foreach ($this->bundles as $bundle) { + $bundle->build($container); + } + + $this->build($container); + + foreach ($container->getExtensions() as $extension) { + $extensions[] = $extension->getAlias(); + } + + // ensure these extensions are implicitly loaded + $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions)); + } + + /** + * Gets a new ContainerBuilder instance used to build the service container. + * + * @return ContainerBuilder + */ + protected function getContainerBuilder() + { + $container = new ContainerBuilder(); + $container->getParameterBag()->add($this->getKernelParameters()); + + if ($this instanceof ExtensionInterface) { + $container->registerExtension($this); + } + if ($this instanceof CompilerPassInterface) { + $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000); + } + if (class_exists(\ProxyManager\Configuration::class) && class_exists(RuntimeInstantiator::class)) { + $container->setProxyInstantiator(new RuntimeInstantiator()); + } + + return $container; + } + + /** + * Dumps the service container to PHP code in the cache. + * + * @param string $class The name of the class to generate + * @param string $baseClass The name of the container's base class + */ + protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, string $class, string $baseClass) + { + // cache the container + $dumper = new PhpDumper($container); + + if (class_exists(\ProxyManager\Configuration::class) && class_exists(ProxyDumper::class)) { + $dumper->setProxyDumper(new ProxyDumper()); + } + + $content = $dumper->dump([ + 'class' => $class, + 'base_class' => $baseClass, + 'file' => $cache->getPath(), + 'as_files' => true, + 'debug' => $this->debug, + 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(), + 'preload_classes' => array_map('get_class', $this->bundles), + ]); + + $rootCode = array_pop($content); + $dir = \dirname($cache->getPath()).'/'; + $fs = new Filesystem(); + + foreach ($content as $file => $code) { + $fs->dumpFile($dir.$file, $code); + @chmod($dir.$file, 0666 & ~umask()); + } + $legacyFile = \dirname($dir.key($content)).'.legacy'; + if (is_file($legacyFile)) { + @unlink($legacyFile); + } + + $cache->write($rootCode, $container->getResources()); + } + + /** + * Returns a loader for the container. + * + * @return DelegatingLoader + */ + protected function getContainerLoader(ContainerInterface $container) + { + $env = $this->getEnvironment(); + $locator = new FileLocator($this); + $resolver = new LoaderResolver([ + new XmlFileLoader($container, $locator, $env), + new YamlFileLoader($container, $locator, $env), + new IniFileLoader($container, $locator, $env), + new PhpFileLoader($container, $locator, $env, class_exists(ConfigBuilderGenerator::class) ? new ConfigBuilderGenerator($this->getBuildDir()) : null), + new GlobFileLoader($container, $locator, $env), + new DirectoryLoader($container, $locator, $env), + new ClosureLoader($container, $env), + ]); + + return new DelegatingLoader($resolver); + } + + private function preBoot(): ContainerInterface + { + if ($this->debug) { + $this->startTime = microtime(true); + } + if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) { + if (\function_exists('putenv')) { + putenv('SHELL_VERBOSITY=3'); + } + $_ENV['SHELL_VERBOSITY'] = 3; + $_SERVER['SHELL_VERBOSITY'] = 3; + } + + $this->initializeBundles(); + $this->initializeContainer(); + + $container = $this->container; + + if ($container->hasParameter('kernel.trusted_hosts') && $trustedHosts = $container->getParameter('kernel.trusted_hosts')) { + Request::setTrustedHosts($trustedHosts); + } + + if ($container->hasParameter('kernel.trusted_proxies') && $container->hasParameter('kernel.trusted_headers') && $trustedProxies = $container->getParameter('kernel.trusted_proxies')) { + Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies : array_map('trim', explode(',', $trustedProxies)), $container->getParameter('kernel.trusted_headers')); + } + + return $container; + } + + /** + * Removes comments from a PHP source string. + * + * We don't use the PHP php_strip_whitespace() function + * as we want the content to be readable and well-formatted. + * + * @return string + */ + public static function stripComments(string $source) + { + if (!\function_exists('token_get_all')) { + return $source; + } + + $rawChunk = ''; + $output = ''; + $tokens = token_get_all($source); + $ignoreSpace = false; + for ($i = 0; isset($tokens[$i]); ++$i) { + $token = $tokens[$i]; + if (!isset($token[1]) || 'b"' === $token) { + $rawChunk .= $token; + } elseif (\T_START_HEREDOC === $token[0]) { + $output .= $rawChunk.$token[1]; + do { + $token = $tokens[++$i]; + $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token; + } while (\T_END_HEREDOC !== $token[0]); + $rawChunk = ''; + } elseif (\T_WHITESPACE === $token[0]) { + if ($ignoreSpace) { + $ignoreSpace = false; + + continue; + } + + // replace multiple new lines with a single newline + $rawChunk .= preg_replace(['/\n{2,}/S'], "\n", $token[1]); + } elseif (\in_array($token[0], [\T_COMMENT, \T_DOC_COMMENT])) { + if (!\in_array($rawChunk[\strlen($rawChunk) - 1], [' ', "\n", "\r", "\t"], true)) { + $rawChunk .= ' '; + } + $ignoreSpace = true; + } else { + $rawChunk .= $token[1]; + + // The PHP-open tag already has a new-line + if (\T_OPEN_TAG === $token[0]) { + $ignoreSpace = true; + } else { + $ignoreSpace = false; + } + } + } + + $output .= $rawChunk; + + unset($tokens, $rawChunk); + gc_mem_caches(); + + return $output; + } + + /** + * @return array + */ + public function __sleep() + { + return ['environment', 'debug']; + } + + public function __wakeup() + { + if (\is_object($this->environment) || \is_object($this->debug)) { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + $this->__construct($this->environment, $this->debug); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/KernelEvents.php b/php/libraries/composer/vendor/symfony/http-kernel/KernelEvents.php new file mode 100644 index 0000000..3d47f60 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/KernelEvents.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\HttpKernel; + +use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; +use Symfony\Component\HttpKernel\Event\ControllerEvent; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\Event\TerminateEvent; +use Symfony\Component\HttpKernel\Event\ViewEvent; + +/** + * Contains all events thrown in the HttpKernel component. + * + * @author Bernhard Schussek + */ +final class KernelEvents +{ + /** + * The REQUEST event occurs at the very beginning of request + * dispatching. + * + * This event allows you to create a response for a request before any + * other code in the framework is executed. + * + * @Event("Symfony\Component\HttpKernel\Event\RequestEvent") + */ + public const REQUEST = 'kernel.request'; + + /** + * The EXCEPTION event occurs when an uncaught exception appears. + * + * This event allows you to create a response for a thrown exception or + * to modify the thrown exception. + * + * @Event("Symfony\Component\HttpKernel\Event\ExceptionEvent") + */ + public const EXCEPTION = 'kernel.exception'; + + /** + * The CONTROLLER event occurs once a controller was found for + * handling a request. + * + * This event allows you to change the controller that will handle the + * request. + * + * @Event("Symfony\Component\HttpKernel\Event\ControllerEvent") + */ + public const CONTROLLER = 'kernel.controller'; + + /** + * The CONTROLLER_ARGUMENTS event occurs once controller arguments have been resolved. + * + * This event allows you to change the arguments that will be passed to + * the controller. + * + * @Event("Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent") + */ + public const CONTROLLER_ARGUMENTS = 'kernel.controller_arguments'; + + /** + * The VIEW event occurs when the return value of a controller + * is not a Response instance. + * + * This event allows you to create a response for the return value of the + * controller. + * + * @Event("Symfony\Component\HttpKernel\Event\ViewEvent") + */ + public const VIEW = 'kernel.view'; + + /** + * The RESPONSE event occurs once a response was created for + * replying to a request. + * + * This event allows you to modify or replace the response that will be + * replied. + * + * @Event("Symfony\Component\HttpKernel\Event\ResponseEvent") + */ + public const RESPONSE = 'kernel.response'; + + /** + * The FINISH_REQUEST event occurs when a response was generated for a request. + * + * This event allows you to reset the global and environmental state of + * the application, when it was changed during the request. + * + * @Event("Symfony\Component\HttpKernel\Event\FinishRequestEvent") + */ + public const FINISH_REQUEST = 'kernel.finish_request'; + + /** + * The TERMINATE event occurs once a response was sent. + * + * This event allows you to run expensive post-response jobs. + * + * @Event("Symfony\Component\HttpKernel\Event\TerminateEvent") + */ + public const TERMINATE = 'kernel.terminate'; + + /** + * Event aliases. + * + * These aliases can be consumed by RegisterListenersPass. + */ + public const ALIASES = [ + ControllerArgumentsEvent::class => self::CONTROLLER_ARGUMENTS, + ControllerEvent::class => self::CONTROLLER, + ResponseEvent::class => self::RESPONSE, + FinishRequestEvent::class => self::FINISH_REQUEST, + RequestEvent::class => self::REQUEST, + ViewEvent::class => self::VIEW, + ExceptionEvent::class => self::EXCEPTION, + TerminateEvent::class => self::TERMINATE, + ]; +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/KernelInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/KernelInterface.php new file mode 100644 index 0000000..41135a6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/KernelInterface.php @@ -0,0 +1,149 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; + +/** + * The Kernel is the heart of the Symfony system. + * + * It manages an environment made of application kernel and bundles. + * + * @method string getBuildDir() Returns the build directory - not implementing it is deprecated since Symfony 5.2. + * This directory should be used to store build artifacts, and can be read-only at runtime. + * Caches written at runtime should be stored in the "cache directory" ({@see KernelInterface::getCacheDir()}). + * + * @author Fabien Potencier + */ +interface KernelInterface extends HttpKernelInterface +{ + /** + * Returns an array of bundles to register. + * + * @return iterable + */ + public function registerBundles(); + + /** + * Loads the container configuration. + */ + public function registerContainerConfiguration(LoaderInterface $loader); + + /** + * Boots the current kernel. + */ + public function boot(); + + /** + * Shutdowns the kernel. + * + * This method is mainly useful when doing functional testing. + */ + public function shutdown(); + + /** + * Gets the registered bundle instances. + * + * @return array + */ + public function getBundles(); + + /** + * Returns a bundle. + * + * @return BundleInterface + * + * @throws \InvalidArgumentException when the bundle is not enabled + */ + public function getBundle(string $name); + + /** + * Returns the file path for a given bundle resource. + * + * A Resource can be a file or a directory. + * + * The resource name must follow the following pattern: + * + * "@BundleName/path/to/a/file.something" + * + * where BundleName is the name of the bundle + * and the remaining part is the relative path in the bundle. + * + * @return string + * + * @throws \InvalidArgumentException if the file cannot be found or the name is not valid + * @throws \RuntimeException if the name contains invalid/unsafe characters + */ + public function locateResource(string $name); + + /** + * Gets the environment. + * + * @return string + */ + public function getEnvironment(); + + /** + * Checks if debug mode is enabled. + * + * @return bool + */ + public function isDebug(); + + /** + * Gets the project dir (path of the project's composer file). + * + * @return string + */ + public function getProjectDir(); + + /** + * Gets the current container. + * + * @return ContainerInterface + */ + public function getContainer(); + + /** + * Gets the request start time (not available if debug is disabled). + * + * @return float + */ + public function getStartTime(); + + /** + * Gets the cache directory. + * + * Since Symfony 5.2, the cache directory should be used for caches that are written at runtime. + * For caches and artifacts that can be warmed at compile-time and deployed as read-only, + * use the new "build directory" returned by the {@see getBuildDir()} method. + * + * @return string + */ + public function getCacheDir(); + + /** + * Gets the log directory. + * + * @return string + */ + public function getLogDir(); + + /** + * Gets the charset of the application. + * + * @return string + */ + public function getCharset(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/LICENSE b/php/libraries/composer/vendor/symfony/http-kernel/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Log/DebugLoggerInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Log/DebugLoggerInterface.php new file mode 100644 index 0000000..d5167fc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Log/DebugLoggerInterface.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Log; + +use Symfony\Component\HttpFoundation\Request; + +/** + * DebugLoggerInterface. + * + * @author Fabien Potencier + */ +interface DebugLoggerInterface +{ + /** + * Returns an array of logs. + * + * A log is an array with the following mandatory keys: + * timestamp, message, priority, and priorityName. + * It can also have an optional context key containing an array. + * + * @return array + */ + public function getLogs(?Request $request = null); + + /** + * Returns the number of errors. + * + * @return int + */ + public function countErrors(?Request $request = null); + + /** + * Removes all log records. + */ + public function clear(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Log/Logger.php b/php/libraries/composer/vendor/symfony/http-kernel/Log/Logger.php new file mode 100644 index 0000000..a37c0cf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Log/Logger.php @@ -0,0 +1,124 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Log; + +use Psr\Log\AbstractLogger; +use Psr\Log\InvalidArgumentException; +use Psr\Log\LogLevel; + +/** + * Minimalist PSR-3 logger designed to write in stderr or any other stream. + * + * @author Kévin Dunglas + */ +class Logger extends AbstractLogger +{ + private const LEVELS = [ + LogLevel::DEBUG => 0, + LogLevel::INFO => 1, + LogLevel::NOTICE => 2, + LogLevel::WARNING => 3, + LogLevel::ERROR => 4, + LogLevel::CRITICAL => 5, + LogLevel::ALERT => 6, + LogLevel::EMERGENCY => 7, + ]; + + private $minLevelIndex; + private $formatter; + + /** @var resource|null */ + private $handle; + + /** + * @param string|resource|null $output + */ + public function __construct(?string $minLevel = null, $output = null, ?callable $formatter = null) + { + if (null === $minLevel) { + $minLevel = null === $output || 'php://stdout' === $output || 'php://stderr' === $output ? LogLevel::ERROR : LogLevel::WARNING; + + if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) { + switch ((int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'])) { + case -1: $minLevel = LogLevel::ERROR; + break; + case 1: $minLevel = LogLevel::NOTICE; + break; + case 2: $minLevel = LogLevel::INFO; + break; + case 3: $minLevel = LogLevel::DEBUG; + break; + } + } + } + + if (!isset(self::LEVELS[$minLevel])) { + throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel)); + } + + $this->minLevelIndex = self::LEVELS[$minLevel]; + $this->formatter = $formatter ?: [$this, 'format']; + if ($output && false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) { + throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output)); + } + } + + /** + * {@inheritdoc} + * + * @return void + */ + public function log($level, $message, array $context = []) + { + if (!isset(self::LEVELS[$level])) { + throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level)); + } + + if (self::LEVELS[$level] < $this->minLevelIndex) { + return; + } + + $formatter = $this->formatter; + if ($this->handle) { + @fwrite($this->handle, $formatter($level, $message, $context).\PHP_EOL); + } else { + error_log($formatter($level, $message, $context, false)); + } + } + + private function format(string $level, string $message, array $context, bool $prefixDate = true): string + { + if (str_contains($message, '{')) { + $replacements = []; + foreach ($context as $key => $val) { + if (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) { + $replacements["{{$key}}"] = $val; + } elseif ($val instanceof \DateTimeInterface) { + $replacements["{{$key}}"] = $val->format(\DateTime::RFC3339); + } elseif (\is_object($val)) { + $replacements["{{$key}}"] = '[object '.\get_class($val).']'; + } else { + $replacements["{{$key}}"] = '['.\gettype($val).']'; + } + } + + $message = strtr($message, $replacements); + } + + $log = sprintf('[%s] %s', $level, $message); + if ($prefixDate) { + $log = date(\DateTime::RFC3339).' '.$log; + } + + return $log; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Profiler/FileProfilerStorage.php b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/FileProfilerStorage.php new file mode 100644 index 0000000..6fa24f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/FileProfilerStorage.php @@ -0,0 +1,317 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Profiler; + +/** + * Storage for profiler using files. + * + * @author Alexandre Salomé + */ +class FileProfilerStorage implements ProfilerStorageInterface +{ + /** + * Folder where profiler data are stored. + * + * @var string + */ + private $folder; + + /** + * Constructs the file storage using a "dsn-like" path. + * + * Example : "file:/path/to/the/storage/folder" + * + * @throws \RuntimeException + */ + public function __construct(string $dsn) + { + if (!str_starts_with($dsn, 'file:')) { + throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use FileStorage with an invalid dsn "%s". The expected format is "file:/path/to/the/storage/folder".', $dsn)); + } + $this->folder = substr($dsn, 5); + + if (!is_dir($this->folder) && false === @mkdir($this->folder, 0777, true) && !is_dir($this->folder)) { + throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $this->folder)); + } + } + + /** + * {@inheritdoc} + */ + public function find(?string $ip, ?string $url, ?int $limit, ?string $method, ?int $start = null, ?int $end = null, ?string $statusCode = null): array + { + $file = $this->getIndexFilename(); + + if (!file_exists($file)) { + return []; + } + + $file = fopen($file, 'r'); + fseek($file, 0, \SEEK_END); + + $result = []; + while (\count($result) < $limit && $line = $this->readLineFromFile($file)) { + $values = str_getcsv($line); + + if (7 !== \count($values)) { + // skip invalid lines + continue; + } + + [$csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode] = $values; + $csvTime = (int) $csvTime; + + if ($ip && !str_contains($csvIp, $ip) || $url && !str_contains($csvUrl, $url) || $method && !str_contains($csvMethod, $method) || $statusCode && !str_contains($csvStatusCode, $statusCode)) { + continue; + } + + if (!empty($start) && $csvTime < $start) { + continue; + } + + if (!empty($end) && $csvTime > $end) { + continue; + } + + $result[$csvToken] = [ + 'token' => $csvToken, + 'ip' => $csvIp, + 'method' => $csvMethod, + 'url' => $csvUrl, + 'time' => $csvTime, + 'parent' => $csvParent, + 'status_code' => $csvStatusCode, + ]; + } + + fclose($file); + + return array_values($result); + } + + /** + * {@inheritdoc} + */ + public function purge() + { + $flags = \FilesystemIterator::SKIP_DOTS; + $iterator = new \RecursiveDirectoryIterator($this->folder, $flags); + $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST); + + foreach ($iterator as $file) { + if (is_file($file)) { + unlink($file); + } else { + rmdir($file); + } + } + } + + /** + * {@inheritdoc} + */ + public function read(string $token): ?Profile + { + return $this->doRead($token); + } + + /** + * {@inheritdoc} + * + * @throws \RuntimeException + */ + public function write(Profile $profile): bool + { + $file = $this->getFilename($profile->getToken()); + + $profileIndexed = is_file($file); + if (!$profileIndexed) { + // Create directory + $dir = \dirname($file); + if (!is_dir($dir) && false === @mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir)); + } + } + + $profileToken = $profile->getToken(); + // when there are errors in sub-requests, the parent and/or children tokens + // may equal the profile token, resulting in infinite loops + $parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null; + $childrenToken = array_filter(array_map(function (Profile $p) use ($profileToken) { + return $profileToken !== $p->getToken() ? $p->getToken() : null; + }, $profile->getChildren())); + + // Store profile + $data = [ + 'token' => $profileToken, + 'parent' => $parentToken, + 'children' => $childrenToken, + 'data' => $profile->getCollectors(), + 'ip' => $profile->getIp(), + 'method' => $profile->getMethod(), + 'url' => $profile->getUrl(), + 'time' => $profile->getTime(), + 'status_code' => $profile->getStatusCode(), + ]; + + $data = serialize($data); + + if (\function_exists('gzencode')) { + $data = gzencode($data, 3); + } + + if (false === file_put_contents($file, $data, \LOCK_EX)) { + return false; + } + + if (!$profileIndexed) { + // Add to index + if (false === $file = fopen($this->getIndexFilename(), 'a')) { + return false; + } + + fputcsv($file, [ + $profile->getToken(), + $profile->getIp(), + $profile->getMethod(), + $profile->getUrl(), + $profile->getTime(), + $profile->getParentToken(), + $profile->getStatusCode(), + ]); + fclose($file); + } + + return true; + } + + /** + * Gets filename to store data, associated to the token. + * + * @return string + */ + protected function getFilename(string $token) + { + // Uses 4 last characters, because first are mostly the same. + $folderA = substr($token, -2, 2); + $folderB = substr($token, -4, 2); + + return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token; + } + + /** + * Gets the index filename. + * + * @return string + */ + protected function getIndexFilename() + { + return $this->folder.'/index.csv'; + } + + /** + * Reads a line in the file, backward. + * + * This function automatically skips the empty lines and do not include the line return in result value. + * + * @param resource $file The file resource, with the pointer placed at the end of the line to read + * + * @return mixed + */ + protected function readLineFromFile($file) + { + $line = ''; + $position = ftell($file); + + if (0 === $position) { + return null; + } + + while (true) { + $chunkSize = min($position, 1024); + $position -= $chunkSize; + fseek($file, $position); + + if (0 === $chunkSize) { + // bof reached + break; + } + + $buffer = fread($file, $chunkSize); + + if (false === ($upTo = strrpos($buffer, "\n"))) { + $line = $buffer.$line; + continue; + } + + $position += $upTo; + $line = substr($buffer, $upTo + 1).$line; + fseek($file, max(0, $position), \SEEK_SET); + + if ('' !== $line) { + break; + } + } + + return '' === $line ? null : $line; + } + + protected function createProfileFromData(string $token, array $data, ?Profile $parent = null) + { + $profile = new Profile($token); + $profile->setIp($data['ip']); + $profile->setMethod($data['method']); + $profile->setUrl($data['url']); + $profile->setTime($data['time']); + $profile->setStatusCode($data['status_code']); + $profile->setCollectors($data['data']); + + if (!$parent && $data['parent']) { + $parent = $this->read($data['parent']); + } + + if ($parent) { + $profile->setParent($parent); + } + + foreach ($data['children'] as $token) { + if (null !== $childProfile = $this->doRead($token, $profile)) { + $profile->addChild($childProfile); + } + } + + return $profile; + } + + private function doRead($token, ?Profile $profile = null): ?Profile + { + if (!$token || !file_exists($file = $this->getFilename($token))) { + return null; + } + + $h = fopen($file, 'r'); + flock($h, \LOCK_SH); + $data = stream_get_contents($h); + flock($h, \LOCK_UN); + fclose($h); + + if (\function_exists('gzdecode')) { + $data = @gzdecode($data) ?: $data; + } + + if (!$data = unserialize($data)) { + return null; + } + + return $this->createProfileFromData($token, $data, $profile); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Profiler/Profile.php b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/Profile.php new file mode 100644 index 0000000..a622403 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/Profile.php @@ -0,0 +1,270 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Profiler; + +use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; + +/** + * Profile. + * + * @author Fabien Potencier + */ +class Profile +{ + private $token; + + /** + * @var DataCollectorInterface[] + */ + private $collectors = []; + + private $ip; + private $method; + private $url; + private $time; + private $statusCode; + + /** + * @var Profile + */ + private $parent; + + /** + * @var Profile[] + */ + private $children = []; + + public function __construct(string $token) + { + $this->token = $token; + } + + public function setToken(string $token) + { + $this->token = $token; + } + + /** + * Gets the token. + * + * @return string + */ + public function getToken() + { + return $this->token; + } + + /** + * Sets the parent token. + */ + public function setParent(self $parent) + { + $this->parent = $parent; + } + + /** + * Returns the parent profile. + * + * @return self|null + */ + public function getParent() + { + return $this->parent; + } + + /** + * Returns the parent token. + * + * @return string|null + */ + public function getParentToken() + { + return $this->parent ? $this->parent->getToken() : null; + } + + /** + * Returns the IP. + * + * @return string|null + */ + public function getIp() + { + return $this->ip; + } + + public function setIp(?string $ip) + { + $this->ip = $ip; + } + + /** + * Returns the request method. + * + * @return string|null + */ + public function getMethod() + { + return $this->method; + } + + public function setMethod(string $method) + { + $this->method = $method; + } + + /** + * Returns the URL. + * + * @return string|null + */ + public function getUrl() + { + return $this->url; + } + + public function setUrl(?string $url) + { + $this->url = $url; + } + + /** + * @return int + */ + public function getTime() + { + return $this->time ?? 0; + } + + public function setTime(int $time) + { + $this->time = $time; + } + + public function setStatusCode(int $statusCode) + { + $this->statusCode = $statusCode; + } + + /** + * @return int|null + */ + public function getStatusCode() + { + return $this->statusCode; + } + + /** + * Finds children profilers. + * + * @return self[] + */ + public function getChildren() + { + return $this->children; + } + + /** + * Sets children profiler. + * + * @param Profile[] $children + */ + public function setChildren(array $children) + { + $this->children = []; + foreach ($children as $child) { + $this->addChild($child); + } + } + + /** + * Adds the child token. + */ + public function addChild(self $child) + { + $this->children[] = $child; + $child->setParent($this); + } + + public function getChildByToken(string $token): ?self + { + foreach ($this->children as $child) { + if ($token === $child->getToken()) { + return $child; + } + } + + return null; + } + + /** + * Gets a Collector by name. + * + * @return DataCollectorInterface + * + * @throws \InvalidArgumentException if the collector does not exist + */ + public function getCollector(string $name) + { + if (!isset($this->collectors[$name])) { + throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.', $name)); + } + + return $this->collectors[$name]; + } + + /** + * Gets the Collectors associated with this profile. + * + * @return DataCollectorInterface[] + */ + public function getCollectors() + { + return $this->collectors; + } + + /** + * Sets the Collectors associated with this profile. + * + * @param DataCollectorInterface[] $collectors + */ + public function setCollectors(array $collectors) + { + $this->collectors = []; + foreach ($collectors as $collector) { + $this->addCollector($collector); + } + } + + /** + * Adds a Collector. + */ + public function addCollector(DataCollectorInterface $collector) + { + $this->collectors[$collector->getName()] = $collector; + } + + /** + * @return bool + */ + public function hasCollector(string $name) + { + return isset($this->collectors[$name]); + } + + /** + * @return array + */ + public function __sleep() + { + return ['token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time', 'statusCode']; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Profiler/Profiler.php b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/Profiler.php new file mode 100644 index 0000000..412a859 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/Profiler.php @@ -0,0 +1,253 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Profiler; + +use Psr\Log\LoggerInterface; +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; +use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface; +use Symfony\Contracts\Service\ResetInterface; + +/** + * Profiler. + * + * @author Fabien Potencier + */ +class Profiler implements ResetInterface +{ + private $storage; + + /** + * @var DataCollectorInterface[] + */ + private $collectors = []; + + private $logger; + private $initiallyEnabled = true; + private $enabled = true; + + public function __construct(ProfilerStorageInterface $storage, ?LoggerInterface $logger = null, bool $enable = true) + { + $this->storage = $storage; + $this->logger = $logger; + $this->initiallyEnabled = $this->enabled = $enable; + } + + /** + * Disables the profiler. + */ + public function disable() + { + $this->enabled = false; + } + + /** + * Enables the profiler. + */ + public function enable() + { + $this->enabled = true; + } + + /** + * Loads the Profile for the given Response. + * + * @return Profile|null + */ + public function loadProfileFromResponse(Response $response) + { + if (!$token = $response->headers->get('X-Debug-Token')) { + return null; + } + + return $this->loadProfile($token); + } + + /** + * Loads the Profile for the given token. + * + * @return Profile|null + */ + public function loadProfile(string $token) + { + return $this->storage->read($token); + } + + /** + * Saves a Profile. + * + * @return bool + */ + public function saveProfile(Profile $profile) + { + // late collect + foreach ($profile->getCollectors() as $collector) { + if ($collector instanceof LateDataCollectorInterface) { + $collector->lateCollect(); + } + } + + if (!($ret = $this->storage->write($profile)) && null !== $this->logger) { + $this->logger->warning('Unable to store the profiler information.', ['configured_storage' => \get_class($this->storage)]); + } + + return $ret; + } + + /** + * Purges all data from the storage. + */ + public function purge() + { + $this->storage->purge(); + } + + /** + * Finds profiler tokens for the given criteria. + * + * @param int|null $limit The maximum number of tokens to return + * @param string|null $start The start date to search from + * @param string|null $end The end date to search to + * + * @return array + * + * @see https://php.net/datetime.formats for the supported date/time formats + */ + public function find(?string $ip, ?string $url, ?int $limit, ?string $method, ?string $start, ?string $end, ?string $statusCode = null) + { + return $this->storage->find($ip, $url, $limit, $method, $this->getTimestamp($start), $this->getTimestamp($end), $statusCode); + } + + /** + * Collects data for the given Response. + * + * @return Profile|null + */ + public function collect(Request $request, Response $response, ?\Throwable $exception = null) + { + if (false === $this->enabled) { + return null; + } + + $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6)); + $profile->setTime(time()); + $profile->setUrl($request->getUri()); + $profile->setMethod($request->getMethod()); + $profile->setStatusCode($response->getStatusCode()); + try { + $profile->setIp($request->getClientIp()); + } catch (ConflictingHeadersException $e) { + $profile->setIp('Unknown'); + } + + if ($prevToken = $response->headers->get('X-Debug-Token')) { + $response->headers->set('X-Previous-Debug-Token', $prevToken); + } + + $response->headers->set('X-Debug-Token', $profile->getToken()); + + foreach ($this->collectors as $collector) { + $collector->collect($request, $response, $exception); + + // we need to clone for sub-requests + $profile->addCollector(clone $collector); + } + + return $profile; + } + + public function reset() + { + foreach ($this->collectors as $collector) { + $collector->reset(); + } + $this->enabled = $this->initiallyEnabled; + } + + /** + * Gets the Collectors associated with this profiler. + * + * @return array + */ + public function all() + { + return $this->collectors; + } + + /** + * Sets the Collectors associated with this profiler. + * + * @param DataCollectorInterface[] $collectors An array of collectors + */ + public function set(array $collectors = []) + { + $this->collectors = []; + foreach ($collectors as $collector) { + $this->add($collector); + } + } + + /** + * Adds a Collector. + */ + public function add(DataCollectorInterface $collector) + { + $this->collectors[$collector->getName()] = $collector; + } + + /** + * Returns true if a Collector for the given name exists. + * + * @param string $name A collector name + * + * @return bool + */ + public function has(string $name) + { + return isset($this->collectors[$name]); + } + + /** + * Gets a Collector by name. + * + * @param string $name A collector name + * + * @return DataCollectorInterface + * + * @throws \InvalidArgumentException if the collector does not exist + */ + public function get(string $name) + { + if (!isset($this->collectors[$name])) { + throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.', $name)); + } + + return $this->collectors[$name]; + } + + private function getTimestamp(?string $value): ?int + { + if (null === $value || '' === $value) { + return null; + } + + try { + $value = new \DateTime(is_numeric($value) ? '@'.$value : $value); + } catch (\Exception $e) { + return null; + } + + return $value->getTimestamp(); + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Profiler/ProfilerStorageInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/ProfilerStorageInterface.php new file mode 100644 index 0000000..6b23c1a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Profiler/ProfilerStorageInterface.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\HttpKernel\Profiler; + +/** + * ProfilerStorageInterface. + * + * This interface exists for historical reasons. The only supported + * implementation is FileProfilerStorage. + * + * As the profiler must only be used on non-production servers, the file storage + * is more than enough and no other implementations will ever be supported. + * + * @internal + * + * @author Fabien Potencier + */ +interface ProfilerStorageInterface +{ + /** + * Finds profiler tokens for the given criteria. + * + * @param int|null $limit The maximum number of tokens to return + * @param int|null $start The start date to search from + * @param int|null $end The end date to search to + */ + public function find(?string $ip, ?string $url, ?int $limit, ?string $method, ?int $start = null, ?int $end = null): array; + + /** + * Reads data associated with the given token. + * + * The method returns false if the token does not exist in the storage. + */ + public function read(string $token): ?Profile; + + /** + * Saves a Profile. + */ + public function write(Profile $profile): bool; + + /** + * Purges all data from the database. + */ + public function purge(); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/README.md b/php/libraries/composer/vendor/symfony/http-kernel/README.md new file mode 100644 index 0000000..ca50417 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/README.md @@ -0,0 +1,31 @@ +HttpKernel Component +==================== + +The HttpKernel component provides a structured process for converting a Request +into a Response by making use of the EventDispatcher component. It's flexible +enough to create full-stack frameworks, micro-frameworks or advanced CMS systems like Drupal. + +Sponsor +------- + +The HttpKernel component for Symfony 5.4/6.0 is [backed][1] by [Les-Tilleuls.coop][2]. + +Les-Tilleuls.coop is a team of 50+ Symfony experts who can help you design, develop and +fix your projects. We provide a wide range of professional services including development, +consulting, coaching, training and audits. We also are highly skilled in JS, Go and DevOps. +We are a worker cooperative! + +Help Symfony by [sponsoring][3] its development! + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/http_kernel.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +[1]: https://symfony.com/backers +[2]: https://les-tilleuls.coop +[3]: https://symfony.com/sponsor diff --git a/php/libraries/composer/vendor/symfony/http-kernel/RebootableInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/RebootableInterface.php new file mode 100644 index 0000000..e257237 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/RebootableInterface.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\HttpKernel; + +/** + * Allows the Kernel to be rebooted using a temporary cache directory. + * + * @author Nicolas Grekas + */ +interface RebootableInterface +{ + /** + * Reboots a kernel. + * + * The getBuildDir() method of a rebootable kernel should not be called + * while building the container. Use the %kernel.build_dir% parameter instead. + * + * @param string|null $warmupDir pass null to reboot in the regular build directory + */ + public function reboot(?string $warmupDir); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/Resources/welcome.html.php b/php/libraries/composer/vendor/symfony/http-kernel/Resources/welcome.html.php new file mode 100644 index 0000000..b25f99b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/Resources/welcome.html.php @@ -0,0 +1,123 @@ + + + + + + Welcome to Symfony! + + + +
+
+ +

+ You're seeing this page because you haven't configured any homepage URL and debug mode is enabled. +

+
+ +
+
+ +

Welcome to Symfony

+
+ +
+ + + + + + +

Your application is now ready and you can start working on it.

+
+ + +
+ +
+ +
+
+ + diff --git a/php/libraries/composer/vendor/symfony/http-kernel/TerminableInterface.php b/php/libraries/composer/vendor/symfony/http-kernel/TerminableInterface.php new file mode 100644 index 0000000..8aa3319 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/TerminableInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * Terminable extends the Kernel request/response cycle with dispatching a post + * response event after sending the response and before shutting down the kernel. + * + * @author Jordi Boggiano + * @author Pierre Minnieur + */ +interface TerminableInterface +{ + /** + * Terminates a request/response cycle. + * + * Should be called after sending the response and before shutting down the kernel. + */ + public function terminate(Request $request, Response $response); +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/UriSigner.php b/php/libraries/composer/vendor/symfony/http-kernel/UriSigner.php new file mode 100644 index 0000000..38931ce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/UriSigner.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 Symfony\Component\HttpKernel; + +use Symfony\Component\HttpFoundation\Request; + +/** + * Signs URIs. + * + * @author Fabien Potencier + */ +class UriSigner +{ + private $secret; + private $parameter; + + /** + * @param string $secret A secret + * @param string $parameter Query string parameter to use + */ + public function __construct(string $secret, string $parameter = '_hash') + { + $this->secret = $secret; + $this->parameter = $parameter; + } + + /** + * Signs a URI. + * + * The given URI is signed by adding the query string parameter + * which value depends on the URI and the secret. + * + * @return string + */ + public function sign(string $uri) + { + $url = parse_url($uri); + if (isset($url['query'])) { + parse_str($url['query'], $params); + } else { + $params = []; + } + + $uri = $this->buildUrl($url, $params); + $params[$this->parameter] = $this->computeHash($uri); + + return $this->buildUrl($url, $params); + } + + /** + * Checks that a URI contains the correct hash. + * + * @return bool + */ + public function check(string $uri) + { + $url = parse_url($uri); + if (isset($url['query'])) { + parse_str($url['query'], $params); + } else { + $params = []; + } + + if (empty($params[$this->parameter])) { + return false; + } + + $hash = $params[$this->parameter]; + unset($params[$this->parameter]); + + return hash_equals($this->computeHash($this->buildUrl($url, $params)), $hash); + } + + public function checkRequest(Request $request): bool + { + $qs = ($qs = $request->server->get('QUERY_STRING')) ? '?'.$qs : ''; + + // we cannot use $request->getUri() here as we want to work with the original URI (no query string reordering) + return $this->check($request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo().$qs); + } + + private function computeHash(string $uri): string + { + return base64_encode(hash_hmac('sha256', $uri, $this->secret, true)); + } + + private function buildUrl(array $url, array $params = []): string + { + ksort($params, \SORT_STRING); + $url['query'] = http_build_query($params, '', '&'); + + $scheme = isset($url['scheme']) ? $url['scheme'].'://' : ''; + $host = $url['host'] ?? ''; + $port = isset($url['port']) ? ':'.$url['port'] : ''; + $user = $url['user'] ?? ''; + $pass = isset($url['pass']) ? ':'.$url['pass'] : ''; + $pass = ($user || $pass) ? "$pass@" : ''; + $path = $url['path'] ?? ''; + $query = isset($url['query']) && $url['query'] ? '?'.$url['query'] : ''; + $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : ''; + + return $scheme.$user.$pass.$host.$port.$path.$query.$fragment; + } +} diff --git a/php/libraries/composer/vendor/symfony/http-kernel/composer.json b/php/libraries/composer/vendor/symfony/http-kernel/composer.json new file mode 100644 index 0000000..180a79b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/http-kernel/composer.json @@ -0,0 +1,79 @@ +{ + "name": "symfony/http-kernel", + "type": "library", + "description": "Provides a structured process for converting a Request into a Response", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/error-handler": "^4.4|^5.0|^6.0", + "symfony/event-dispatcher": "^5.0|^6.0", + "symfony/http-foundation": "^5.4.21|^6.2.7", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.16", + "psr/log": "^1|^2" + }, + "require-dev": { + "symfony/browser-kit": "^5.4|^6.0", + "symfony/config": "^5.0|^6.0", + "symfony/console": "^4.4|^5.0|^6.0", + "symfony/css-selector": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.3|^6.0", + "symfony/dom-crawler": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/finder": "^4.4|^5.0|^6.0", + "symfony/http-client-contracts": "^1.1|^2|^3", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/routing": "^4.4|^5.0|^6.0", + "symfony/stopwatch": "^4.4|^5.0|^6.0", + "symfony/translation": "^4.4|^5.0|^6.0", + "symfony/translation-contracts": "^1.1|^2|^3", + "psr/cache": "^1.0|^2.0|^3.0", + "twig/twig": "^2.13|^3.0.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0" + }, + "conflict": { + "symfony/browser-kit": "<5.4", + "symfony/cache": "<5.0", + "symfony/config": "<5.0", + "symfony/console": "<4.4", + "symfony/form": "<5.0", + "symfony/dependency-injection": "<5.3", + "symfony/doctrine-bridge": "<5.0", + "symfony/http-client": "<5.0", + "symfony/mailer": "<5.0", + "symfony/messenger": "<5.0", + "symfony/translation": "<5.0", + "symfony/twig-bridge": "<5.0", + "symfony/validator": "<5.0", + "twig/twig": "<2.13" + }, + "suggest": { + "symfony/browser-kit": "", + "symfony/config": "", + "symfony/console": "", + "symfony/dependency-injection": "" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\HttpKernel\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/mime/Address.php b/php/libraries/composer/vendor/symfony/mime/Address.php new file mode 100644 index 0000000..ae83efd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Address.php @@ -0,0 +1,149 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\MessageIDValidation; +use Egulias\EmailValidator\Validation\RFCValidation; +use Symfony\Component\Mime\Encoder\IdnAddressEncoder; +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Exception\LogicException; +use Symfony\Component\Mime\Exception\RfcComplianceException; + +/** + * @author Fabien Potencier + */ +final class Address +{ + /** + * A regex that matches a structure like 'Name '. + * It matches anything between the first < and last > as email address. + * This allows to use a single string to construct an Address, which can be convenient to use in + * config, and allows to have more readable config. + * This does not try to cover all edge cases for address. + */ + private const FROM_STRING_PATTERN = '~(?[^<]*)<(?.*)>[^>]*~'; + + private static $validator; + private static $encoder; + + private $address; + private $name; + + public function __construct(string $address, string $name = '') + { + if (!class_exists(EmailValidator::class)) { + throw new LogicException(sprintf('The "%s" class cannot be used as it needs "%s"; try running "composer require egulias/email-validator".', __CLASS__, EmailValidator::class)); + } + + if (null === self::$validator) { + self::$validator = new EmailValidator(); + } + + $this->address = trim($address); + $this->name = trim(str_replace(["\n", "\r"], '', $name)); + + if (!self::$validator->isValid($this->address, class_exists(MessageIDValidation::class) ? new MessageIDValidation() : new RFCValidation())) { + throw new RfcComplianceException(sprintf('Email "%s" does not comply with addr-spec of RFC 2822.', $address)); + } + } + + public function getAddress(): string + { + return $this->address; + } + + public function getName(): string + { + return $this->name; + } + + public function getEncodedAddress(): string + { + if (null === self::$encoder) { + self::$encoder = new IdnAddressEncoder(); + } + + return self::$encoder->encodeString($this->address); + } + + public function toString(): string + { + return ($n = $this->getEncodedName()) ? $n.' <'.$this->getEncodedAddress().'>' : $this->getEncodedAddress(); + } + + public function getEncodedName(): string + { + if ('' === $this->getName()) { + return ''; + } + + return sprintf('"%s"', preg_replace('/"/u', '\"', $this->getName())); + } + + /** + * @param Address|string $address + */ + public static function create($address): self + { + if ($address instanceof self) { + return $address; + } + + if (!\is_string($address)) { + throw new InvalidArgumentException(sprintf('An address can be an instance of Address or a string ("%s" given).', get_debug_type($address))); + } + + if (false === strpos($address, '<')) { + return new self($address); + } + + if (!preg_match(self::FROM_STRING_PATTERN, $address, $matches)) { + throw new InvalidArgumentException(sprintf('Could not parse "%s" to a "%s" instance.', $address, self::class)); + } + + return new self($matches['addrSpec'], trim($matches['displayName'], ' \'"')); + } + + /** + * @param array $addresses + * + * @return Address[] + */ + public static function createArray(array $addresses): array + { + $addrs = []; + foreach ($addresses as $address) { + $addrs[] = self::create($address); + } + + return $addrs; + } + + /** + * @deprecated since Symfony 5.2, use "create()" instead. + */ + public static function fromString(string $string): self + { + trigger_deprecation('symfony/mime', '5.2', '"%s()" is deprecated, use "%s::create()" instead.', __METHOD__, __CLASS__); + + if (!str_contains($string, '<')) { + return new self($string, ''); + } + + if (!preg_match(self::FROM_STRING_PATTERN, $string, $matches)) { + throw new InvalidArgumentException(sprintf('Could not parse "%s" to a "%s" instance.', $string, self::class)); + } + + return new self($matches['addrSpec'], trim($matches['displayName'], ' \'"')); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/BodyRendererInterface.php b/php/libraries/composer/vendor/symfony/mime/BodyRendererInterface.php new file mode 100644 index 0000000..d692172 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/BodyRendererInterface.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\Mime; + +/** + * @author Fabien Potencier + */ +interface BodyRendererInterface +{ + public function render(Message $message): void; +} diff --git a/php/libraries/composer/vendor/symfony/mime/CHANGELOG.md b/php/libraries/composer/vendor/symfony/mime/CHANGELOG.md new file mode 100644 index 0000000..f272346 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/CHANGELOG.md @@ -0,0 +1,26 @@ +CHANGELOG +========= + +5.2.0 +----- + + * Add support for DKIM + * Deprecated `Address::fromString()`, use `Address::create()` instead + +4.4.0 +----- + + * [BC BREAK] Removed `NamedAddress` (`Address` now supports a name) + * Added PHPUnit constraints + * Added `AbstractPart::asDebugString()` + * Added `Address::fromString()` + +4.3.3 +----- + + * [BC BREAK] Renamed method `Headers::getAll()` to `Headers::all()`. + +4.3.0 +----- + + * Introduced the component as experimental diff --git a/php/libraries/composer/vendor/symfony/mime/CharacterStream.php b/php/libraries/composer/vendor/symfony/mime/CharacterStream.php new file mode 100644 index 0000000..238debd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/CharacterStream.php @@ -0,0 +1,218 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +/** + * @author Fabien Potencier + * @author Xavier De Cock + * + * @internal + */ +final class CharacterStream +{ + /** Pre-computed for optimization */ + private const UTF8_LENGTH_MAP = [ + "\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1, + "\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1, + "\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1, + "\x18" => 1, "\x19" => 1, "\x1a" => 1, "\x1b" => 1, "\x1c" => 1, "\x1d" => 1, "\x1e" => 1, "\x1f" => 1, + "\x20" => 1, "\x21" => 1, "\x22" => 1, "\x23" => 1, "\x24" => 1, "\x25" => 1, "\x26" => 1, "\x27" => 1, + "\x28" => 1, "\x29" => 1, "\x2a" => 1, "\x2b" => 1, "\x2c" => 1, "\x2d" => 1, "\x2e" => 1, "\x2f" => 1, + "\x30" => 1, "\x31" => 1, "\x32" => 1, "\x33" => 1, "\x34" => 1, "\x35" => 1, "\x36" => 1, "\x37" => 1, + "\x38" => 1, "\x39" => 1, "\x3a" => 1, "\x3b" => 1, "\x3c" => 1, "\x3d" => 1, "\x3e" => 1, "\x3f" => 1, + "\x40" => 1, "\x41" => 1, "\x42" => 1, "\x43" => 1, "\x44" => 1, "\x45" => 1, "\x46" => 1, "\x47" => 1, + "\x48" => 1, "\x49" => 1, "\x4a" => 1, "\x4b" => 1, "\x4c" => 1, "\x4d" => 1, "\x4e" => 1, "\x4f" => 1, + "\x50" => 1, "\x51" => 1, "\x52" => 1, "\x53" => 1, "\x54" => 1, "\x55" => 1, "\x56" => 1, "\x57" => 1, + "\x58" => 1, "\x59" => 1, "\x5a" => 1, "\x5b" => 1, "\x5c" => 1, "\x5d" => 1, "\x5e" => 1, "\x5f" => 1, + "\x60" => 1, "\x61" => 1, "\x62" => 1, "\x63" => 1, "\x64" => 1, "\x65" => 1, "\x66" => 1, "\x67" => 1, + "\x68" => 1, "\x69" => 1, "\x6a" => 1, "\x6b" => 1, "\x6c" => 1, "\x6d" => 1, "\x6e" => 1, "\x6f" => 1, + "\x70" => 1, "\x71" => 1, "\x72" => 1, "\x73" => 1, "\x74" => 1, "\x75" => 1, "\x76" => 1, "\x77" => 1, + "\x78" => 1, "\x79" => 1, "\x7a" => 1, "\x7b" => 1, "\x7c" => 1, "\x7d" => 1, "\x7e" => 1, "\x7f" => 1, + "\x80" => 0, "\x81" => 0, "\x82" => 0, "\x83" => 0, "\x84" => 0, "\x85" => 0, "\x86" => 0, "\x87" => 0, + "\x88" => 0, "\x89" => 0, "\x8a" => 0, "\x8b" => 0, "\x8c" => 0, "\x8d" => 0, "\x8e" => 0, "\x8f" => 0, + "\x90" => 0, "\x91" => 0, "\x92" => 0, "\x93" => 0, "\x94" => 0, "\x95" => 0, "\x96" => 0, "\x97" => 0, + "\x98" => 0, "\x99" => 0, "\x9a" => 0, "\x9b" => 0, "\x9c" => 0, "\x9d" => 0, "\x9e" => 0, "\x9f" => 0, + "\xa0" => 0, "\xa1" => 0, "\xa2" => 0, "\xa3" => 0, "\xa4" => 0, "\xa5" => 0, "\xa6" => 0, "\xa7" => 0, + "\xa8" => 0, "\xa9" => 0, "\xaa" => 0, "\xab" => 0, "\xac" => 0, "\xad" => 0, "\xae" => 0, "\xaf" => 0, + "\xb0" => 0, "\xb1" => 0, "\xb2" => 0, "\xb3" => 0, "\xb4" => 0, "\xb5" => 0, "\xb6" => 0, "\xb7" => 0, + "\xb8" => 0, "\xb9" => 0, "\xba" => 0, "\xbb" => 0, "\xbc" => 0, "\xbd" => 0, "\xbe" => 0, "\xbf" => 0, + "\xc0" => 2, "\xc1" => 2, "\xc2" => 2, "\xc3" => 2, "\xc4" => 2, "\xc5" => 2, "\xc6" => 2, "\xc7" => 2, + "\xc8" => 2, "\xc9" => 2, "\xca" => 2, "\xcb" => 2, "\xcc" => 2, "\xcd" => 2, "\xce" => 2, "\xcf" => 2, + "\xd0" => 2, "\xd1" => 2, "\xd2" => 2, "\xd3" => 2, "\xd4" => 2, "\xd5" => 2, "\xd6" => 2, "\xd7" => 2, + "\xd8" => 2, "\xd9" => 2, "\xda" => 2, "\xdb" => 2, "\xdc" => 2, "\xdd" => 2, "\xde" => 2, "\xdf" => 2, + "\xe0" => 3, "\xe1" => 3, "\xe2" => 3, "\xe3" => 3, "\xe4" => 3, "\xe5" => 3, "\xe6" => 3, "\xe7" => 3, + "\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3, + "\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4, + "\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0, + ]; + + private $data = ''; + private $dataSize = 0; + private $map = []; + private $charCount = 0; + private $currentPos = 0; + private $fixedWidth = 0; + + /** + * @param resource|string $input + */ + public function __construct($input, ?string $charset = 'utf-8') + { + $charset = strtolower(trim($charset)) ?: 'utf-8'; + if ('utf-8' === $charset || 'utf8' === $charset) { + $this->fixedWidth = 0; + $this->map = ['p' => [], 'i' => []]; + } else { + switch ($charset) { + // 16 bits + case 'ucs2': + case 'ucs-2': + case 'utf16': + case 'utf-16': + $this->fixedWidth = 2; + break; + + // 32 bits + case 'ucs4': + case 'ucs-4': + case 'utf32': + case 'utf-32': + $this->fixedWidth = 4; + break; + + // 7-8 bit charsets: (us-)?ascii, (iso|iec)-?8859-?[0-9]+, windows-?125[0-9], cp-?[0-9]+, ansi, macintosh, + // koi-?7, koi-?8-?.+, mik, (cork|t1), v?iscii + // and fallback + default: + $this->fixedWidth = 1; + } + } + if (\is_resource($input)) { + $blocks = 16372; + while (false !== $read = fread($input, $blocks)) { + $this->write($read); + } + } else { + $this->write($input); + } + } + + public function read(int $length): ?string + { + if ($this->currentPos >= $this->charCount) { + return null; + } + $length = ($this->currentPos + $length > $this->charCount) ? $this->charCount - $this->currentPos : $length; + if ($this->fixedWidth > 0) { + $len = $length * $this->fixedWidth; + $ret = substr($this->data, $this->currentPos * $this->fixedWidth, $len); + $this->currentPos += $length; + } else { + $end = $this->currentPos + $length; + $end = $end > $this->charCount ? $this->charCount : $end; + $ret = ''; + $start = 0; + if ($this->currentPos > 0) { + $start = $this->map['p'][$this->currentPos - 1]; + } + $to = $start; + for (; $this->currentPos < $end; ++$this->currentPos) { + if (isset($this->map['i'][$this->currentPos])) { + $ret .= substr($this->data, $start, $to - $start).'?'; + $start = $this->map['p'][$this->currentPos]; + } else { + $to = $this->map['p'][$this->currentPos]; + } + } + $ret .= substr($this->data, $start, $to - $start); + } + + return $ret; + } + + public function readBytes(int $length): ?array + { + if (null !== $read = $this->read($length)) { + return array_map('ord', str_split($read, 1)); + } + + return null; + } + + public function setPointer(int $charOffset): void + { + if ($this->charCount < $charOffset) { + $charOffset = $this->charCount; + } + $this->currentPos = $charOffset; + } + + public function write(string $chars): void + { + $ignored = ''; + $this->data .= $chars; + if ($this->fixedWidth > 0) { + $strlen = \strlen($chars); + $ignoredL = $strlen % $this->fixedWidth; + $ignored = $ignoredL ? substr($chars, -$ignoredL) : ''; + $this->charCount += ($strlen - $ignoredL) / $this->fixedWidth; + } else { + $this->charCount += $this->getUtf8CharPositions($chars, $this->dataSize, $ignored); + } + $this->dataSize = \strlen($this->data) - \strlen($ignored); + } + + private function getUtf8CharPositions(string $string, int $startOffset, string &$ignoredChars): int + { + $strlen = \strlen($string); + $charPos = \count($this->map['p']); + $foundChars = 0; + $invalid = false; + for ($i = 0; $i < $strlen; ++$i) { + $char = $string[$i]; + $size = self::UTF8_LENGTH_MAP[$char]; + if (0 == $size) { + /* char is invalid, we must wait for a resync */ + $invalid = true; + continue; + } + + if ($invalid) { + /* We mark the chars as invalid and start a new char */ + $this->map['p'][$charPos + $foundChars] = $startOffset + $i; + $this->map['i'][$charPos + $foundChars] = true; + ++$foundChars; + $invalid = false; + } + if (($i + $size) > $strlen) { + $ignoredChars = substr($string, $i); + break; + } + for ($j = 1; $j < $size; ++$j) { + $char = $string[$i + $j]; + if ($char > "\x7F" && $char < "\xC0") { + // Valid - continue parsing + } else { + /* char is invalid, we must wait for a resync */ + $invalid = true; + continue 2; + } + } + /* Ok we got a complete char here */ + $this->map['p'][$charPos + $foundChars] = $startOffset + $i + $size; + $i += $j - 1; + ++$foundChars; + } + + return $foundChars; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Crypto/DkimOptions.php b/php/libraries/composer/vendor/symfony/mime/Crypto/DkimOptions.php new file mode 100644 index 0000000..171bb25 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Crypto/DkimOptions.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Crypto; + +/** + * A helper providing autocompletion for available DkimSigner options. + * + * @author Fabien Potencier + */ +final class DkimOptions +{ + private $options = []; + + public function toArray(): array + { + return $this->options; + } + + /** + * @return $this + */ + public function algorithm(string $algo): self + { + $this->options['algorithm'] = $algo; + + return $this; + } + + /** + * @return $this + */ + public function signatureExpirationDelay(int $show): self + { + $this->options['signature_expiration_delay'] = $show; + + return $this; + } + + /** + * @return $this + */ + public function bodyMaxLength(int $max): self + { + $this->options['body_max_length'] = $max; + + return $this; + } + + /** + * @return $this + */ + public function bodyShowLength(bool $show): self + { + $this->options['body_show_length'] = $show; + + return $this; + } + + /** + * @return $this + */ + public function headerCanon(string $canon): self + { + $this->options['header_canon'] = $canon; + + return $this; + } + + /** + * @return $this + */ + public function bodyCanon(string $canon): self + { + $this->options['body_canon'] = $canon; + + return $this; + } + + /** + * @return $this + */ + public function headersToIgnore(array $headers): self + { + $this->options['headers_to_ignore'] = $headers; + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Crypto/DkimSigner.php b/php/libraries/composer/vendor/symfony/mime/Crypto/DkimSigner.php new file mode 100644 index 0000000..f0f7091 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Crypto/DkimSigner.php @@ -0,0 +1,220 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Crypto; + +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Exception\RuntimeException; +use Symfony\Component\Mime\Header\UnstructuredHeader; +use Symfony\Component\Mime\Message; +use Symfony\Component\Mime\Part\AbstractPart; + +/** + * @author Fabien Potencier + * + * RFC 6376 and 8301 + */ +final class DkimSigner +{ + public const CANON_SIMPLE = 'simple'; + public const CANON_RELAXED = 'relaxed'; + + public const ALGO_SHA256 = 'rsa-sha256'; + public const ALGO_ED25519 = 'ed25519-sha256'; // RFC 8463 + + private $key; + private $domainName; + private $selector; + private $defaultOptions; + + /** + * @param string $pk The private key as a string or the path to the file containing the private key, should be prefixed with file:// (in PEM format) + * @param string $passphrase A passphrase of the private key (if any) + */ + public function __construct(string $pk, string $domainName, string $selector, array $defaultOptions = [], string $passphrase = '') + { + if (!\extension_loaded('openssl')) { + throw new \LogicException('PHP extension "openssl" is required to use DKIM.'); + } + if (!$this->key = openssl_pkey_get_private($pk, $passphrase)) { + throw new InvalidArgumentException('Unable to load DKIM private key: '.openssl_error_string()); + } + + $this->domainName = $domainName; + $this->selector = $selector; + $this->defaultOptions = $defaultOptions + [ + 'algorithm' => self::ALGO_SHA256, + 'signature_expiration_delay' => 0, + 'body_max_length' => \PHP_INT_MAX, + 'body_show_length' => false, + 'header_canon' => self::CANON_RELAXED, + 'body_canon' => self::CANON_RELAXED, + 'headers_to_ignore' => [], + ]; + } + + public function sign(Message $message, array $options = []): Message + { + $options += $this->defaultOptions; + if (!\in_array($options['algorithm'], [self::ALGO_SHA256, self::ALGO_ED25519], true)) { + throw new InvalidArgumentException(sprintf('Invalid DKIM signing algorithm "%s".', $options['algorithm'])); + } + $headersToIgnore['return-path'] = true; + $headersToIgnore['x-transport'] = true; + foreach ($options['headers_to_ignore'] as $name) { + $headersToIgnore[strtolower($name)] = true; + } + unset($headersToIgnore['from']); + $signedHeaderNames = []; + $headerCanonData = ''; + $headers = $message->getPreparedHeaders(); + foreach ($headers->getNames() as $name) { + foreach ($headers->all($name) as $header) { + if (isset($headersToIgnore[strtolower($header->getName())])) { + continue; + } + + if ('' !== $header->getBodyAsString()) { + $headerCanonData .= $this->canonicalizeHeader($header->toString(), $options['header_canon']); + $signedHeaderNames[] = $header->getName(); + } + } + } + + [$bodyHash, $bodyLength] = $this->hashBody($message->getBody(), $options['body_canon'], $options['body_max_length']); + + $params = [ + 'v' => '1', + 'q' => 'dns/txt', + 'a' => $options['algorithm'], + 'bh' => base64_encode($bodyHash), + 'd' => $this->domainName, + 'h' => implode(': ', $signedHeaderNames), + 'i' => '@'.$this->domainName, + 's' => $this->selector, + 't' => time(), + 'c' => $options['header_canon'].'/'.$options['body_canon'], + ]; + + if ($options['body_show_length']) { + $params['l'] = $bodyLength; + } + if ($options['signature_expiration_delay']) { + $params['x'] = $params['t'] + $options['signature_expiration_delay']; + } + $value = ''; + foreach ($params as $k => $v) { + $value .= $k.'='.$v.'; '; + } + $value = trim($value); + $header = new UnstructuredHeader('DKIM-Signature', $value); + $headerCanonData .= rtrim($this->canonicalizeHeader($header->toString()."\r\n b=", $options['header_canon'])); + if (self::ALGO_SHA256 === $options['algorithm']) { + if (!openssl_sign($headerCanonData, $signature, $this->key, \OPENSSL_ALGO_SHA256)) { + throw new RuntimeException('Unable to sign DKIM hash: '.openssl_error_string()); + } + } else { + throw new \RuntimeException(sprintf('The "%s" DKIM signing algorithm is not supported yet.', self::ALGO_ED25519)); + } + $header->setValue($value.' b='.trim(chunk_split(base64_encode($signature), 73, ' '))); + $headers->add($header); + + return new Message($headers, $message->getBody()); + } + + private function canonicalizeHeader(string $header, string $headerCanon): string + { + if (self::CANON_RELAXED !== $headerCanon) { + return $header."\r\n"; + } + + $exploded = explode(':', $header, 2); + $name = strtolower(trim($exploded[0])); + $value = str_replace("\r\n", '', $exploded[1]); + $value = trim(preg_replace("/[ \t][ \t]+/", ' ', $value)); + + return $name.':'.$value."\r\n"; + } + + private function hashBody(AbstractPart $body, string $bodyCanon, int $maxLength): array + { + $hash = hash_init('sha256'); + $relaxed = self::CANON_RELAXED === $bodyCanon; + $currentLine = ''; + $emptyCounter = 0; + $isSpaceSequence = false; + $length = 0; + foreach ($body->bodyToIterable() as $chunk) { + $canon = ''; + for ($i = 0, $len = \strlen($chunk); $i < $len; ++$i) { + switch ($chunk[$i]) { + case "\r": + break; + case "\n": + // previous char is always \r + if ($relaxed) { + $isSpaceSequence = false; + } + if ('' === $currentLine) { + ++$emptyCounter; + } else { + $currentLine = ''; + $canon .= "\r\n"; + } + break; + case ' ': + case "\t": + if ($relaxed) { + $isSpaceSequence = true; + break; + } + // no break + default: + if ($emptyCounter > 0) { + $canon .= str_repeat("\r\n", $emptyCounter); + $emptyCounter = 0; + } + if ($isSpaceSequence) { + $currentLine .= ' '; + $canon .= ' '; + $isSpaceSequence = false; + } + $currentLine .= $chunk[$i]; + $canon .= $chunk[$i]; + } + } + + if ($length + \strlen($canon) >= $maxLength) { + $canon = substr($canon, 0, $maxLength - $length); + $length += \strlen($canon); + hash_update($hash, $canon); + + break; + } + + $length += \strlen($canon); + hash_update($hash, $canon); + } + + // Add trailing Line return if last line is non empty + if ('' !== $currentLine) { + hash_update($hash, "\r\n"); + $length += \strlen("\r\n"); + } + + if (!$relaxed && 0 === $length) { + hash_update($hash, "\r\n"); + $length = 2; + } + + return [hash_final($hash, true), $length]; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Crypto/SMime.php b/php/libraries/composer/vendor/symfony/mime/Crypto/SMime.php new file mode 100644 index 0000000..cba95f2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Crypto/SMime.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Crypto; + +use Symfony\Component\Mime\Exception\RuntimeException; +use Symfony\Component\Mime\Part\SMimePart; + +/** + * @author Sebastiaan Stok + * + * @internal + */ +abstract class SMime +{ + protected function normalizeFilePath(string $path): string + { + if (!file_exists($path)) { + throw new RuntimeException(sprintf('File does not exist: "%s".', $path)); + } + + return 'file://'.str_replace('\\', '/', realpath($path)); + } + + protected function iteratorToFile(iterable $iterator, $stream): void + { + foreach ($iterator as $chunk) { + fwrite($stream, $chunk); + } + } + + protected function convertMessageToSMimePart($stream, string $type, string $subtype): SMimePart + { + rewind($stream); + + $headers = ''; + + while (!feof($stream)) { + $buffer = fread($stream, 78); + $headers .= $buffer; + + // Detect ending of header list + if (preg_match('/(\r\n\r\n|\n\n)/', $headers, $match)) { + $headersPosEnd = strpos($headers, $headerBodySeparator = $match[0]); + + break; + } + } + + $headers = $this->getMessageHeaders(trim(substr($headers, 0, $headersPosEnd))); + + fseek($stream, $headersPosEnd + \strlen($headerBodySeparator)); + + return new SMimePart($this->getStreamIterator($stream), $type, $subtype, $this->getParametersFromHeader($headers['content-type'])); + } + + protected function getStreamIterator($stream): iterable + { + while (!feof($stream)) { + yield str_replace("\n", "\r\n", str_replace("\r\n", "\n", fread($stream, 16372))); + } + } + + private function getMessageHeaders(string $headerData): array + { + $headers = []; + $headerLines = explode("\r\n", str_replace("\n", "\r\n", str_replace("\r\n", "\n", $headerData))); + $currentHeaderName = ''; + + // Transform header lines into an associative array + foreach ($headerLines as $headerLine) { + // Empty lines between headers indicate a new mime-entity + if ('' === $headerLine) { + break; + } + + // Handle headers that span multiple lines + if (!str_contains($headerLine, ':')) { + $headers[$currentHeaderName] .= ' '.trim($headerLine); + continue; + } + + $header = explode(':', $headerLine, 2); + $currentHeaderName = strtolower($header[0]); + $headers[$currentHeaderName] = trim($header[1]); + } + + return $headers; + } + + private function getParametersFromHeader(string $header): array + { + $params = []; + + preg_match_all('/(?P[a-z-0-9]+)=(?P"[^"]+"|(?:[^\s;]+|$))(?:\s+;)?/i', $header, $matches); + + foreach ($matches['value'] as $pos => $paramValue) { + $params[$matches['name'][$pos]] = trim($paramValue, '"'); + } + + return $params; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Crypto/SMimeEncrypter.php b/php/libraries/composer/vendor/symfony/mime/Crypto/SMimeEncrypter.php new file mode 100644 index 0000000..e92b37b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Crypto/SMimeEncrypter.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Crypto; + +use Symfony\Component\Mime\Exception\RuntimeException; +use Symfony\Component\Mime\Message; + +/** + * @author Sebastiaan Stok + */ +final class SMimeEncrypter extends SMime +{ + private $certs; + private $cipher; + + /** + * @param string|string[] $certificate The path (or array of paths) of the file(s) containing the X.509 certificate(s) + * @param int|null $cipher A set of algorithms used to encrypt the message. Must be one of these PHP constants: https://www.php.net/manual/en/openssl.ciphers.php + */ + public function __construct($certificate, ?int $cipher = null) + { + if (!\extension_loaded('openssl')) { + throw new \LogicException('PHP extension "openssl" is required to use SMime.'); + } + + if (\is_array($certificate)) { + $this->certs = array_map([$this, 'normalizeFilePath'], $certificate); + } else { + $this->certs = $this->normalizeFilePath($certificate); + } + + $this->cipher = $cipher ?? \OPENSSL_CIPHER_AES_256_CBC; + } + + public function encrypt(Message $message): Message + { + $bufferFile = tmpfile(); + $outputFile = tmpfile(); + + $this->iteratorToFile($message->toIterable(), $bufferFile); + + if (!@openssl_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->certs, [], 0, $this->cipher)) { + throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string())); + } + + $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime'); + $mimePart->getHeaders() + ->addTextHeader('Content-Transfer-Encoding', 'base64') + ->addParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'smime.p7m']) + ; + + return new Message($message->getHeaders(), $mimePart); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Crypto/SMimeSigner.php b/php/libraries/composer/vendor/symfony/mime/Crypto/SMimeSigner.php new file mode 100644 index 0000000..94c2bbd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Crypto/SMimeSigner.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Crypto; + +use Symfony\Component\Mime\Exception\RuntimeException; +use Symfony\Component\Mime\Message; + +/** + * @author Sebastiaan Stok + */ +final class SMimeSigner extends SMime +{ + private $signCertificate; + private $signPrivateKey; + private $signOptions; + private $extraCerts; + + /** + * @param string $certificate The path of the file containing the signing certificate (in PEM format) + * @param string $privateKey The path of the file containing the private key (in PEM format) + * @param string|null $privateKeyPassphrase A passphrase of the private key (if any) + * @param string|null $extraCerts The path of the file containing intermediate certificates (in PEM format) needed by the signing certificate + * @param int|null $signOptions Bitwise operator options for openssl_pkcs7_sign() (@see https://secure.php.net/manual/en/openssl.pkcs7.flags.php) + */ + public function __construct(string $certificate, string $privateKey, ?string $privateKeyPassphrase = null, ?string $extraCerts = null, ?int $signOptions = null) + { + if (!\extension_loaded('openssl')) { + throw new \LogicException('PHP extension "openssl" is required to use SMime.'); + } + + $this->signCertificate = $this->normalizeFilePath($certificate); + + if (null !== $privateKeyPassphrase) { + $this->signPrivateKey = [$this->normalizeFilePath($privateKey), $privateKeyPassphrase]; + } else { + $this->signPrivateKey = $this->normalizeFilePath($privateKey); + } + + $this->signOptions = $signOptions ?? \PKCS7_DETACHED; + $this->extraCerts = $extraCerts ? realpath($extraCerts) : null; + } + + public function sign(Message $message): Message + { + $bufferFile = tmpfile(); + $outputFile = tmpfile(); + + $this->iteratorToFile($message->getBody()->toIterable(), $bufferFile); + + if (!@openssl_pkcs7_sign(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->signCertificate, $this->signPrivateKey, [], $this->signOptions, $this->extraCerts)) { + throw new RuntimeException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string())); + } + + return new Message($message->getHeaders(), $this->convertMessageToSMimePart($outputFile, 'multipart', 'signed')); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/DependencyInjection/AddMimeTypeGuesserPass.php b/php/libraries/composer/vendor/symfony/mime/DependencyInjection/AddMimeTypeGuesserPass.php new file mode 100644 index 0000000..00eef94 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/DependencyInjection/AddMimeTypeGuesserPass.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Registers custom mime types guessers. + * + * @author Fabien Potencier + */ +class AddMimeTypeGuesserPass implements CompilerPassInterface +{ + private $mimeTypesService; + private $mimeTypeGuesserTag; + + public function __construct(string $mimeTypesService = 'mime_types', string $mimeTypeGuesserTag = 'mime.mime_type_guesser') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/mime', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->mimeTypesService = $mimeTypesService; + $this->mimeTypeGuesserTag = $mimeTypeGuesserTag; + } + + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + if ($container->has($this->mimeTypesService)) { + $definition = $container->findDefinition($this->mimeTypesService); + foreach ($container->findTaggedServiceIds($this->mimeTypeGuesserTag, true) as $id => $attributes) { + $definition->addMethodCall('registerGuesser', [new Reference($id)]); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Email.php b/php/libraries/composer/vendor/symfony/mime/Email.php new file mode 100644 index 0000000..5365294 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Email.php @@ -0,0 +1,634 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +use Symfony\Component\Mime\Exception\LogicException; +use Symfony\Component\Mime\Part\AbstractPart; +use Symfony\Component\Mime\Part\DataPart; +use Symfony\Component\Mime\Part\Multipart\AlternativePart; +use Symfony\Component\Mime\Part\Multipart\MixedPart; +use Symfony\Component\Mime\Part\Multipart\RelatedPart; +use Symfony\Component\Mime\Part\TextPart; + +/** + * @author Fabien Potencier + */ +class Email extends Message +{ + public const PRIORITY_HIGHEST = 1; + public const PRIORITY_HIGH = 2; + public const PRIORITY_NORMAL = 3; + public const PRIORITY_LOW = 4; + public const PRIORITY_LOWEST = 5; + + private const PRIORITY_MAP = [ + self::PRIORITY_HIGHEST => 'Highest', + self::PRIORITY_HIGH => 'High', + self::PRIORITY_NORMAL => 'Normal', + self::PRIORITY_LOW => 'Low', + self::PRIORITY_LOWEST => 'Lowest', + ]; + + private $text; + private $textCharset; + private $html; + private $htmlCharset; + private $attachments = []; + /** + * @var AbstractPart|null + */ + private $cachedBody; // Used to avoid wrong body hash in DKIM signatures with multiple parts (e.g. HTML + TEXT) due to multiple boundaries. + + /** + * @return $this + */ + public function subject(string $subject) + { + return $this->setHeaderBody('Text', 'Subject', $subject); + } + + public function getSubject(): ?string + { + return $this->getHeaders()->getHeaderBody('Subject'); + } + + /** + * @return $this + */ + public function date(\DateTimeInterface $dateTime) + { + return $this->setHeaderBody('Date', 'Date', $dateTime); + } + + public function getDate(): ?\DateTimeImmutable + { + return $this->getHeaders()->getHeaderBody('Date'); + } + + /** + * @param Address|string $address + * + * @return $this + */ + public function returnPath($address) + { + return $this->setHeaderBody('Path', 'Return-Path', Address::create($address)); + } + + public function getReturnPath(): ?Address + { + return $this->getHeaders()->getHeaderBody('Return-Path'); + } + + /** + * @param Address|string $address + * + * @return $this + */ + public function sender($address) + { + return $this->setHeaderBody('Mailbox', 'Sender', Address::create($address)); + } + + public function getSender(): ?Address + { + return $this->getHeaders()->getHeaderBody('Sender'); + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function addFrom(...$addresses) + { + return $this->addListAddressHeaderBody('From', $addresses); + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function from(...$addresses) + { + if (!$addresses) { + throw new LogicException('"from()" must be called with at least one address.'); + } + + return $this->setListAddressHeaderBody('From', $addresses); + } + + /** + * @return Address[] + */ + public function getFrom(): array + { + return $this->getHeaders()->getHeaderBody('From') ?: []; + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function addReplyTo(...$addresses) + { + return $this->addListAddressHeaderBody('Reply-To', $addresses); + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function replyTo(...$addresses) + { + return $this->setListAddressHeaderBody('Reply-To', $addresses); + } + + /** + * @return Address[] + */ + public function getReplyTo(): array + { + return $this->getHeaders()->getHeaderBody('Reply-To') ?: []; + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function addTo(...$addresses) + { + return $this->addListAddressHeaderBody('To', $addresses); + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function to(...$addresses) + { + return $this->setListAddressHeaderBody('To', $addresses); + } + + /** + * @return Address[] + */ + public function getTo(): array + { + return $this->getHeaders()->getHeaderBody('To') ?: []; + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function addCc(...$addresses) + { + return $this->addListAddressHeaderBody('Cc', $addresses); + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function cc(...$addresses) + { + return $this->setListAddressHeaderBody('Cc', $addresses); + } + + /** + * @return Address[] + */ + public function getCc(): array + { + return $this->getHeaders()->getHeaderBody('Cc') ?: []; + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function addBcc(...$addresses) + { + return $this->addListAddressHeaderBody('Bcc', $addresses); + } + + /** + * @param Address|string ...$addresses + * + * @return $this + */ + public function bcc(...$addresses) + { + return $this->setListAddressHeaderBody('Bcc', $addresses); + } + + /** + * @return Address[] + */ + public function getBcc(): array + { + return $this->getHeaders()->getHeaderBody('Bcc') ?: []; + } + + /** + * Sets the priority of this message. + * + * The value is an integer where 1 is the highest priority and 5 is the lowest. + * + * @return $this + */ + public function priority(int $priority) + { + if ($priority > 5) { + $priority = 5; + } elseif ($priority < 1) { + $priority = 1; + } + + return $this->setHeaderBody('Text', 'X-Priority', sprintf('%d (%s)', $priority, self::PRIORITY_MAP[$priority])); + } + + /** + * Get the priority of this message. + * + * The returned value is an integer where 1 is the highest priority and 5 + * is the lowest. + */ + public function getPriority(): int + { + [$priority] = sscanf($this->getHeaders()->getHeaderBody('X-Priority') ?? '', '%[1-5]'); + + return $priority ?? 3; + } + + /** + * @param resource|string|null $body + * + * @return $this + */ + public function text($body, string $charset = 'utf-8') + { + if (null !== $body && !\is_string($body) && !\is_resource($body)) { + throw new \TypeError(sprintf('The body must be a string, a resource or null (got "%s").', get_debug_type($body))); + } + + $this->cachedBody = null; + $this->text = $body; + $this->textCharset = $charset; + + return $this; + } + + /** + * @return resource|string|null + */ + public function getTextBody() + { + return $this->text; + } + + public function getTextCharset(): ?string + { + return $this->textCharset; + } + + /** + * @param resource|string|null $body + * + * @return $this + */ + public function html($body, string $charset = 'utf-8') + { + if (null !== $body && !\is_string($body) && !\is_resource($body)) { + throw new \TypeError(sprintf('The body must be a string, a resource or null (got "%s").', get_debug_type($body))); + } + + $this->cachedBody = null; + $this->html = $body; + $this->htmlCharset = $charset; + + return $this; + } + + /** + * @return resource|string|null + */ + public function getHtmlBody() + { + return $this->html; + } + + public function getHtmlCharset(): ?string + { + return $this->htmlCharset; + } + + /** + * @param resource|string $body + * + * @return $this + */ + public function attach($body, ?string $name = null, ?string $contentType = null) + { + if (!\is_string($body) && !\is_resource($body)) { + throw new \TypeError(sprintf('The body must be a string or a resource (got "%s").', get_debug_type($body))); + } + + $this->cachedBody = null; + $this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => false]; + + return $this; + } + + /** + * @return $this + */ + public function attachFromPath(string $path, ?string $name = null, ?string $contentType = null) + { + $this->cachedBody = null; + $this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => false]; + + return $this; + } + + /** + * @param resource|string $body + * + * @return $this + */ + public function embed($body, ?string $name = null, ?string $contentType = null) + { + if (!\is_string($body) && !\is_resource($body)) { + throw new \TypeError(sprintf('The body must be a string or a resource (got "%s").', get_debug_type($body))); + } + + $this->cachedBody = null; + $this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => true]; + + return $this; + } + + /** + * @return $this + */ + public function embedFromPath(string $path, ?string $name = null, ?string $contentType = null) + { + $this->cachedBody = null; + $this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => true]; + + return $this; + } + + /** + * @return $this + */ + public function attachPart(DataPart $part) + { + $this->cachedBody = null; + $this->attachments[] = ['part' => $part]; + + return $this; + } + + /** + * @return array|DataPart[] + */ + public function getAttachments(): array + { + $parts = []; + foreach ($this->attachments as $attachment) { + $parts[] = $this->createDataPart($attachment); + } + + return $parts; + } + + public function getBody(): AbstractPart + { + if (null !== $body = parent::getBody()) { + return $body; + } + + return $this->generateBody(); + } + + public function ensureValidity() + { + if (null === $this->text && null === $this->html && !$this->attachments) { + throw new LogicException('A message must have a text or an HTML part or attachments.'); + } + + parent::ensureValidity(); + } + + /** + * Generates an AbstractPart based on the raw body of a message. + * + * The most "complex" part generated by this method is when there is text and HTML bodies + * with related images for the HTML part and some attachments: + * + * multipart/mixed + * | + * |------------> multipart/related + * | | + * | |------------> multipart/alternative + * | | | + * | | ------------> text/plain (with content) + * | | | + * | | ------------> text/html (with content) + * | | + * | ------------> image/png (with content) + * | + * ------------> application/pdf (with content) + */ + private function generateBody(): AbstractPart + { + if (null !== $this->cachedBody) { + return $this->cachedBody; + } + + $this->ensureValidity(); + + [$htmlPart, $otherParts, $relatedParts] = $this->prepareParts(); + + $part = null === $this->text ? null : new TextPart($this->text, $this->textCharset); + if (null !== $htmlPart) { + if (null !== $part) { + $part = new AlternativePart($part, $htmlPart); + } else { + $part = $htmlPart; + } + } + + if ($relatedParts) { + $part = new RelatedPart($part, ...$relatedParts); + } + + if ($otherParts) { + if ($part) { + $part = new MixedPart($part, ...$otherParts); + } else { + $part = new MixedPart(...$otherParts); + } + } + + return $this->cachedBody = $part; + } + + private function prepareParts(): ?array + { + $names = []; + $htmlPart = null; + $html = $this->html; + if (null !== $html) { + $htmlPart = new TextPart($html, $this->htmlCharset, 'html'); + $html = $htmlPart->getBody(); + preg_match_all('(]*src\s*=\s*(?:([\'"])cid:(.+?)\\1|cid:([^>\s]+)))i', $html, $names); + $names = array_filter(array_unique(array_merge($names[2], $names[3]))); + } + + // usage of reflection is a temporary workaround for missing getters that will be added in 6.2 + $nameRef = new \ReflectionProperty(TextPart::class, 'name'); + $nameRef->setAccessible(true); + $otherParts = $relatedParts = []; + foreach ($this->attachments as $attachment) { + $part = $this->createDataPart($attachment); + if (isset($attachment['part'])) { + $attachment['name'] = $nameRef->getValue($part); + } + + $related = false; + foreach ($names as $name) { + if ($name !== $attachment['name']) { + continue; + } + if (isset($relatedParts[$name])) { + continue 2; + } + $part->setDisposition('inline'); + $html = str_replace('cid:'.$name, 'cid:'.$part->getContentId(), $html, $count); + if ($count) { + $related = true; + } + $part->setName($part->getContentId()); + + break; + } + + if ($related) { + $relatedParts[$attachment['name']] = $part; + } else { + $otherParts[] = $part; + } + } + if (null !== $htmlPart) { + $htmlPart = new TextPart($html, $this->htmlCharset, 'html'); + } + + return [$htmlPart, $otherParts, array_values($relatedParts)]; + } + + private function createDataPart(array $attachment): DataPart + { + if (isset($attachment['part'])) { + return $attachment['part']; + } + + if (isset($attachment['body'])) { + $part = new DataPart($attachment['body'], $attachment['name'] ?? null, $attachment['content-type'] ?? null); + } else { + $part = DataPart::fromPath($attachment['path'] ?? '', $attachment['name'] ?? null, $attachment['content-type'] ?? null); + } + if ($attachment['inline']) { + $part->asInline(); + } + + return $part; + } + + /** + * @return $this + */ + private function setHeaderBody(string $type, string $name, $body): object + { + $this->getHeaders()->setHeaderBody($type, $name, $body); + + return $this; + } + + private function addListAddressHeaderBody(string $name, array $addresses) + { + if (!$header = $this->getHeaders()->get($name)) { + return $this->setListAddressHeaderBody($name, $addresses); + } + $header->addAddresses(Address::createArray($addresses)); + + return $this; + } + + /** + * @return $this + */ + private function setListAddressHeaderBody(string $name, array $addresses) + { + $addresses = Address::createArray($addresses); + $headers = $this->getHeaders(); + if ($header = $headers->get($name)) { + $header->setAddresses($addresses); + } else { + $headers->addMailboxListHeader($name, $addresses); + } + + return $this; + } + + /** + * @internal + */ + public function __serialize(): array + { + if (\is_resource($this->text)) { + $this->text = (new TextPart($this->text))->getBody(); + } + + if (\is_resource($this->html)) { + $this->html = (new TextPart($this->html))->getBody(); + } + + foreach ($this->attachments as $i => $attachment) { + if (isset($attachment['body']) && \is_resource($attachment['body'])) { + $this->attachments[$i]['body'] = (new TextPart($attachment['body']))->getBody(); + } + } + + return [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, parent::__serialize()]; + } + + /** + * @internal + */ + public function __unserialize(array $data): void + { + [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, $parentData] = $data; + + parent::__unserialize($parentData); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/AddressEncoderInterface.php b/php/libraries/composer/vendor/symfony/mime/Encoder/AddressEncoderInterface.php new file mode 100644 index 0000000..de477d8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/AddressEncoderInterface.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +use Symfony\Component\Mime\Exception\AddressEncoderException; + +/** + * @author Christian Schmidt + */ +interface AddressEncoderInterface +{ + /** + * Encodes an email address. + * + * @throws AddressEncoderException if the email cannot be represented in + * the encoding implemented by this class + */ + public function encodeString(string $address): string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/Base64ContentEncoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/Base64ContentEncoder.php new file mode 100644 index 0000000..440868a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/Base64ContentEncoder.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +use Symfony\Component\Mime\Exception\RuntimeException; + +/** + * @author Fabien Potencier + */ +final class Base64ContentEncoder extends Base64Encoder implements ContentEncoderInterface +{ + public function encodeByteStream($stream, int $maxLineLength = 0): iterable + { + if (!\is_resource($stream)) { + throw new \TypeError(sprintf('Method "%s" takes a stream as a first argument.', __METHOD__)); + } + + $filter = stream_filter_append($stream, 'convert.base64-encode', \STREAM_FILTER_READ, [ + 'line-length' => 0 >= $maxLineLength || 76 < $maxLineLength ? 76 : $maxLineLength, + 'line-break-chars' => "\r\n", + ]); + if (!\is_resource($filter)) { + throw new RuntimeException('Unable to set the base64 content encoder to the filter.'); + } + + while (!feof($stream)) { + yield fread($stream, 16372); + } + stream_filter_remove($filter); + } + + public function getName(): string + { + return 'base64'; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/Base64Encoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/Base64Encoder.php new file mode 100644 index 0000000..7106478 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/Base64Encoder.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +/** + * @author Chris Corbyn + */ +class Base64Encoder implements EncoderInterface +{ + /** + * Takes an unencoded string and produces a Base64 encoded string from it. + * + * Base64 encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + */ + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + if (0 >= $maxLineLength || 76 < $maxLineLength) { + $maxLineLength = 76; + } + + $encodedString = base64_encode($string); + $firstLine = ''; + if (0 !== $firstLineOffset) { + $firstLine = substr($encodedString, 0, $maxLineLength - $firstLineOffset)."\r\n"; + $encodedString = substr($encodedString, $maxLineLength - $firstLineOffset); + } + + return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n")); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/Base64MimeHeaderEncoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/Base64MimeHeaderEncoder.php new file mode 100644 index 0000000..5c06f6d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/Base64MimeHeaderEncoder.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +/** + * @author Chris Corbyn + */ +final class Base64MimeHeaderEncoder extends Base64Encoder implements MimeHeaderEncoderInterface +{ + public function getName(): string + { + return 'B'; + } + + /** + * Takes an unencoded string and produces a Base64 encoded string from it. + * + * If the charset is iso-2022-jp, it uses mb_encode_mimeheader instead of + * default encodeString, otherwise pass to the parent method. + */ + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + if ('iso-2022-jp' === strtolower($charset)) { + $old = mb_internal_encoding(); + mb_internal_encoding('utf-8'); + $newstring = mb_encode_mimeheader($string, 'iso-2022-jp', $this->getName(), "\r\n"); + mb_internal_encoding($old); + + return $newstring; + } + + return parent::encodeString($string, $charset, $firstLineOffset, $maxLineLength); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/ContentEncoderInterface.php b/php/libraries/composer/vendor/symfony/mime/Encoder/ContentEncoderInterface.php new file mode 100644 index 0000000..a45ad04 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/ContentEncoderInterface.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\Mime\Encoder; + +/** + * @author Chris Corbyn + */ +interface ContentEncoderInterface extends EncoderInterface +{ + /** + * Encodes the stream to a Generator. + * + * @param resource $stream + */ + public function encodeByteStream($stream, int $maxLineLength = 0): iterable; + + /** + * Gets the MIME name of this content encoding scheme. + */ + public function getName(): string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/EightBitContentEncoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/EightBitContentEncoder.php new file mode 100644 index 0000000..8283120 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/EightBitContentEncoder.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +/** + * @author Fabien Potencier + */ +final class EightBitContentEncoder implements ContentEncoderInterface +{ + public function encodeByteStream($stream, int $maxLineLength = 0): iterable + { + while (!feof($stream)) { + yield fread($stream, 16372); + } + } + + public function getName(): string + { + return '8bit'; + } + + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + return $string; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/EncoderInterface.php b/php/libraries/composer/vendor/symfony/mime/Encoder/EncoderInterface.php new file mode 100644 index 0000000..bbf6d48 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/EncoderInterface.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\Mime\Encoder; + +/** + * @author Chris Corbyn + */ +interface EncoderInterface +{ + /** + * Encode a given string to produce an encoded string. + * + * @param int $firstLineOffset if first line needs to be shorter + * @param int $maxLineLength - 0 indicates the default length for this encoding + */ + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/IdnAddressEncoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/IdnAddressEncoder.php new file mode 100644 index 0000000..b56e7e3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/IdnAddressEncoder.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +/** + * An IDN email address encoder. + * + * Encodes the domain part of an address using IDN. This is compatible will all + * SMTP servers. + * + * Note: It leaves the local part as is. In case there are non-ASCII characters + * in the local part then it depends on the SMTP Server if this is supported. + * + * @author Christian Schmidt + */ +final class IdnAddressEncoder implements AddressEncoderInterface +{ + /** + * Encodes the domain part of an address using IDN. + */ + public function encodeString(string $address): string + { + $i = strrpos($address, '@'); + if (false !== $i) { + $local = substr($address, 0, $i); + $domain = substr($address, $i + 1); + + if (preg_match('/[^\x00-\x7F]/', $domain)) { + $address = sprintf('%s@%s', $local, idn_to_ascii($domain, \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46)); + } + } + + return $address; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/MimeHeaderEncoderInterface.php b/php/libraries/composer/vendor/symfony/mime/Encoder/MimeHeaderEncoderInterface.php new file mode 100644 index 0000000..fff2c78 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/MimeHeaderEncoderInterface.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +/** + * @author Chris Corbyn + */ +interface MimeHeaderEncoderInterface +{ + /** + * Get the MIME name of this content encoding scheme. + */ + public function getName(): string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/QpContentEncoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/QpContentEncoder.php new file mode 100644 index 0000000..4703cc2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/QpContentEncoder.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\Mime\Encoder; + +/** + * @author Lars Strojny + */ +final class QpContentEncoder implements ContentEncoderInterface +{ + public function encodeByteStream($stream, int $maxLineLength = 0): iterable + { + if (!\is_resource($stream)) { + throw new \TypeError(sprintf('Method "%s" takes a stream as a first argument.', __METHOD__)); + } + + // we don't use PHP stream filters here as the content should be small enough + yield $this->encodeString(stream_get_contents($stream), 'utf-8', 0, $maxLineLength); + } + + public function getName(): string + { + return 'quoted-printable'; + } + + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + return $this->standardize(quoted_printable_encode($string)); + } + + /** + * Make sure CRLF is correct and HT/SPACE are in valid places. + */ + private function standardize(string $string): string + { + // transform CR or LF to CRLF + $string = preg_replace('~=0D(?!=0A)|(? + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +use Symfony\Component\Mime\CharacterStream; + +/** + * @author Chris Corbyn + */ +class QpEncoder implements EncoderInterface +{ + /** + * Pre-computed QP for HUGE optimization. + */ + private const QP_MAP = [ + 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', + 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', + 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', + 15 => '=0F', 16 => '=10', 17 => '=11', 18 => '=12', 19 => '=13', + 20 => '=14', 21 => '=15', 22 => '=16', 23 => '=17', 24 => '=18', + 25 => '=19', 26 => '=1A', 27 => '=1B', 28 => '=1C', 29 => '=1D', + 30 => '=1E', 31 => '=1F', 32 => '=20', 33 => '=21', 34 => '=22', + 35 => '=23', 36 => '=24', 37 => '=25', 38 => '=26', 39 => '=27', + 40 => '=28', 41 => '=29', 42 => '=2A', 43 => '=2B', 44 => '=2C', + 45 => '=2D', 46 => '=2E', 47 => '=2F', 48 => '=30', 49 => '=31', + 50 => '=32', 51 => '=33', 52 => '=34', 53 => '=35', 54 => '=36', + 55 => '=37', 56 => '=38', 57 => '=39', 58 => '=3A', 59 => '=3B', + 60 => '=3C', 61 => '=3D', 62 => '=3E', 63 => '=3F', 64 => '=40', + 65 => '=41', 66 => '=42', 67 => '=43', 68 => '=44', 69 => '=45', + 70 => '=46', 71 => '=47', 72 => '=48', 73 => '=49', 74 => '=4A', + 75 => '=4B', 76 => '=4C', 77 => '=4D', 78 => '=4E', 79 => '=4F', + 80 => '=50', 81 => '=51', 82 => '=52', 83 => '=53', 84 => '=54', + 85 => '=55', 86 => '=56', 87 => '=57', 88 => '=58', 89 => '=59', + 90 => '=5A', 91 => '=5B', 92 => '=5C', 93 => '=5D', 94 => '=5E', + 95 => '=5F', 96 => '=60', 97 => '=61', 98 => '=62', 99 => '=63', + 100 => '=64', 101 => '=65', 102 => '=66', 103 => '=67', 104 => '=68', + 105 => '=69', 106 => '=6A', 107 => '=6B', 108 => '=6C', 109 => '=6D', + 110 => '=6E', 111 => '=6F', 112 => '=70', 113 => '=71', 114 => '=72', + 115 => '=73', 116 => '=74', 117 => '=75', 118 => '=76', 119 => '=77', + 120 => '=78', 121 => '=79', 122 => '=7A', 123 => '=7B', 124 => '=7C', + 125 => '=7D', 126 => '=7E', 127 => '=7F', 128 => '=80', 129 => '=81', + 130 => '=82', 131 => '=83', 132 => '=84', 133 => '=85', 134 => '=86', + 135 => '=87', 136 => '=88', 137 => '=89', 138 => '=8A', 139 => '=8B', + 140 => '=8C', 141 => '=8D', 142 => '=8E', 143 => '=8F', 144 => '=90', + 145 => '=91', 146 => '=92', 147 => '=93', 148 => '=94', 149 => '=95', + 150 => '=96', 151 => '=97', 152 => '=98', 153 => '=99', 154 => '=9A', + 155 => '=9B', 156 => '=9C', 157 => '=9D', 158 => '=9E', 159 => '=9F', + 160 => '=A0', 161 => '=A1', 162 => '=A2', 163 => '=A3', 164 => '=A4', + 165 => '=A5', 166 => '=A6', 167 => '=A7', 168 => '=A8', 169 => '=A9', + 170 => '=AA', 171 => '=AB', 172 => '=AC', 173 => '=AD', 174 => '=AE', + 175 => '=AF', 176 => '=B0', 177 => '=B1', 178 => '=B2', 179 => '=B3', + 180 => '=B4', 181 => '=B5', 182 => '=B6', 183 => '=B7', 184 => '=B8', + 185 => '=B9', 186 => '=BA', 187 => '=BB', 188 => '=BC', 189 => '=BD', + 190 => '=BE', 191 => '=BF', 192 => '=C0', 193 => '=C1', 194 => '=C2', + 195 => '=C3', 196 => '=C4', 197 => '=C5', 198 => '=C6', 199 => '=C7', + 200 => '=C8', 201 => '=C9', 202 => '=CA', 203 => '=CB', 204 => '=CC', + 205 => '=CD', 206 => '=CE', 207 => '=CF', 208 => '=D0', 209 => '=D1', + 210 => '=D2', 211 => '=D3', 212 => '=D4', 213 => '=D5', 214 => '=D6', + 215 => '=D7', 216 => '=D8', 217 => '=D9', 218 => '=DA', 219 => '=DB', + 220 => '=DC', 221 => '=DD', 222 => '=DE', 223 => '=DF', 224 => '=E0', + 225 => '=E1', 226 => '=E2', 227 => '=E3', 228 => '=E4', 229 => '=E5', + 230 => '=E6', 231 => '=E7', 232 => '=E8', 233 => '=E9', 234 => '=EA', + 235 => '=EB', 236 => '=EC', 237 => '=ED', 238 => '=EE', 239 => '=EF', + 240 => '=F0', 241 => '=F1', 242 => '=F2', 243 => '=F3', 244 => '=F4', + 245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9', + 250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE', + 255 => '=FF', + ]; + + private static $safeMapShare = []; + + /** + * A map of non-encoded ascii characters. + * + * @var string[] + * + * @internal + */ + protected $safeMap = []; + + public function __construct() + { + $id = static::class; + if (!isset(self::$safeMapShare[$id])) { + $this->initSafeMap(); + self::$safeMapShare[$id] = $this->safeMap; + } else { + $this->safeMap = self::$safeMapShare[$id]; + } + } + + protected function initSafeMap(): void + { + foreach (array_merge([0x09, 0x20], range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { + $this->safeMap[$byte] = \chr($byte); + } + } + + /** + * {@inheritdoc} + * + * Takes an unencoded string and produces a QP encoded string from it. + * + * QP encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + */ + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + if ($maxLineLength > 76 || $maxLineLength <= 0) { + $maxLineLength = 76; + } + + $thisLineLength = $maxLineLength - $firstLineOffset; + + $lines = []; + $lNo = 0; + $lines[$lNo] = ''; + $currentLine = &$lines[$lNo++]; + $size = $lineLen = 0; + $charStream = new CharacterStream($string, $charset); + + // Fetching more than 4 chars at one is slower, as is fetching fewer bytes + // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 + // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes + while (null !== $bytes = $charStream->readBytes(4)) { + $enc = $this->encodeByteSequence($bytes, $size); + + $i = strpos($enc, '=0D=0A'); + $newLineLength = $lineLen + (false === $i ? $size : $i); + + if ($currentLine && $newLineLength >= $thisLineLength) { + $lines[$lNo] = ''; + $currentLine = &$lines[$lNo++]; + $thisLineLength = $maxLineLength; + $lineLen = 0; + } + + $currentLine .= $enc; + + if (false === $i) { + $lineLen += $size; + } else { + // 6 is the length of '=0D=0A'. + $lineLen = $size - strrpos($enc, '=0D=0A') - 6; + } + } + + return $this->standardize(implode("=\r\n", $lines)); + } + + /** + * Encode the given byte array into a verbatim QP form. + */ + private function encodeByteSequence(array $bytes, int &$size): string + { + $ret = ''; + $size = 0; + foreach ($bytes as $b) { + if (isset($this->safeMap[$b])) { + $ret .= $this->safeMap[$b]; + ++$size; + } else { + $ret .= self::QP_MAP[$b]; + $size += 3; + } + } + + return $ret; + } + + /** + * Make sure CRLF is correct and HT/SPACE are in valid places. + */ + private function standardize(string $string): string + { + $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string); + switch ($end = \ord(substr($string, -1))) { + case 0x09: + case 0x20: + $string = substr_replace($string, self::QP_MAP[$end], -1); + } + + return $string; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/QpMimeHeaderEncoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/QpMimeHeaderEncoder.php new file mode 100644 index 0000000..d1d3837 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/QpMimeHeaderEncoder.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\Mime\Encoder; + +/** + * @author Chris Corbyn + */ +final class QpMimeHeaderEncoder extends QpEncoder implements MimeHeaderEncoderInterface +{ + protected function initSafeMap(): void + { + foreach (array_merge( + range(0x61, 0x7A), range(0x41, 0x5A), + range(0x30, 0x39), [0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F] + ) as $byte) { + $this->safeMap[$byte] = \chr($byte); + } + } + + public function getName(): string + { + return 'Q'; + } + + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + return str_replace([' ', '=20', "=\r\n"], ['_', '_', "\r\n"], + parent::encodeString($string, $charset, $firstLineOffset, $maxLineLength) + ); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Encoder/Rfc2231Encoder.php b/php/libraries/composer/vendor/symfony/mime/Encoder/Rfc2231Encoder.php new file mode 100644 index 0000000..4d93dc6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Encoder/Rfc2231Encoder.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Encoder; + +use Symfony\Component\Mime\CharacterStream; + +/** + * @author Chris Corbyn + */ +final class Rfc2231Encoder implements EncoderInterface +{ + /** + * Takes an unencoded string and produces a string encoded according to RFC 2231 from it. + */ + public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string + { + $lines = []; + $lineCount = 0; + $lines[] = ''; + $currentLine = &$lines[$lineCount++]; + + if (0 >= $maxLineLength) { + $maxLineLength = 75; + } + + $charStream = new CharacterStream($string, $charset); + $thisLineLength = $maxLineLength - $firstLineOffset; + + while (null !== $char = $charStream->read(4)) { + $encodedChar = rawurlencode($char); + if ('' !== $currentLine && \strlen($currentLine.$encodedChar) > $thisLineLength) { + $lines[] = ''; + $currentLine = &$lines[$lineCount++]; + $thisLineLength = $maxLineLength; + } + $currentLine .= $encodedChar; + } + + return implode("\r\n", $lines); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Exception/AddressEncoderException.php b/php/libraries/composer/vendor/symfony/mime/Exception/AddressEncoderException.php new file mode 100644 index 0000000..51ee2e0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Exception/AddressEncoderException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Exception; + +/** + * @author Fabien Potencier + */ +class AddressEncoderException extends RfcComplianceException +{ +} diff --git a/php/libraries/composer/vendor/symfony/mime/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/mime/Exception/ExceptionInterface.php new file mode 100644 index 0000000..1193390 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Exception/ExceptionInterface.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Exception; + +/** + * @author Fabien Potencier + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/mime/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/symfony/mime/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..e89ebae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Exception/InvalidArgumentException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Exception; + +/** + * @author Fabien Potencier + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/mime/Exception/LogicException.php b/php/libraries/composer/vendor/symfony/mime/Exception/LogicException.php new file mode 100644 index 0000000..0508ee7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Exception/LogicException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Exception; + +/** + * @author Fabien Potencier + */ +class LogicException extends \LogicException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/mime/Exception/RfcComplianceException.php b/php/libraries/composer/vendor/symfony/mime/Exception/RfcComplianceException.php new file mode 100644 index 0000000..26e4a50 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Exception/RfcComplianceException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Exception; + +/** + * @author Fabien Potencier + */ +class RfcComplianceException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/mime/Exception/RuntimeException.php b/php/libraries/composer/vendor/symfony/mime/Exception/RuntimeException.php new file mode 100644 index 0000000..fb018b0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Exception/RuntimeException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Exception; + +/** + * @author Fabien Potencier + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/mime/FileBinaryMimeTypeGuesser.php b/php/libraries/composer/vendor/symfony/mime/FileBinaryMimeTypeGuesser.php new file mode 100644 index 0000000..3acf4d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/FileBinaryMimeTypeGuesser.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Exception\LogicException; + +/** + * Guesses the MIME type with the binary "file" (only available on *nix). + * + * @author Bernhard Schussek + */ +class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface +{ + private $cmd; + + /** + * The $cmd pattern must contain a "%s" string that will be replaced + * with the file name to guess. + * + * The command output must start with the MIME type of the file. + * + * @param string $cmd The command to run to get the MIME type of a file + */ + public function __construct(string $cmd = 'file -b --mime -- %s 2>/dev/null') + { + $this->cmd = $cmd; + } + + /** + * {@inheritdoc} + */ + public function isGuesserSupported(): bool + { + static $supported = null; + + if (null !== $supported) { + return $supported; + } + + if ('\\' === \DIRECTORY_SEPARATOR || !\function_exists('passthru') || !\function_exists('escapeshellarg')) { + return $supported = false; + } + + ob_start(); + passthru('command -v file', $exitStatus); + $binPath = trim(ob_get_clean()); + + return $supported = 0 === $exitStatus && '' !== $binPath; + } + + /** + * {@inheritdoc} + */ + public function guessMimeType(string $path): ?string + { + if (!is_file($path) || !is_readable($path)) { + throw new InvalidArgumentException(sprintf('The "%s" file does not exist or is not readable.', $path)); + } + + if (!$this->isGuesserSupported()) { + throw new LogicException(sprintf('The "%s" guesser is not supported.', __CLASS__)); + } + + ob_start(); + + // need to use --mime instead of -i. see #6641 + passthru(sprintf($this->cmd, escapeshellarg((str_starts_with($path, '-') ? './' : '').$path)), $return); + if ($return > 0) { + ob_end_clean(); + + return null; + } + + $type = trim(ob_get_clean()); + + if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\+\.]+)#i', $type, $match)) { + // it's not a type, but an error message + return null; + } + + return $match[1]; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/FileinfoMimeTypeGuesser.php b/php/libraries/composer/vendor/symfony/mime/FileinfoMimeTypeGuesser.php new file mode 100644 index 0000000..1208976 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/FileinfoMimeTypeGuesser.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Exception\LogicException; + +/** + * Guesses the MIME type using the PECL extension FileInfo. + * + * @author Bernhard Schussek + */ +class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface +{ + private $magicFile; + + /** + * @param string|null $magicFile A magic file to use with the finfo instance + * + * @see http://www.php.net/manual/en/function.finfo-open.php + */ + public function __construct(?string $magicFile = null) + { + $this->magicFile = $magicFile; + } + + /** + * {@inheritdoc} + */ + public function isGuesserSupported(): bool + { + return \function_exists('finfo_open'); + } + + /** + * {@inheritdoc} + */ + public function guessMimeType(string $path): ?string + { + if (!is_file($path) || !is_readable($path)) { + throw new InvalidArgumentException(sprintf('The "%s" file does not exist or is not readable.', $path)); + } + + if (!$this->isGuesserSupported()) { + throw new LogicException(sprintf('The "%s" guesser is not supported.', __CLASS__)); + } + + if (false === $finfo = new \finfo(\FILEINFO_MIME_TYPE, $this->magicFile)) { + return null; + } + $mimeType = $finfo->file($path); + + if ($mimeType && 0 === (\strlen($mimeType) % 2)) { + $mimeStart = substr($mimeType, 0, \strlen($mimeType) >> 1); + $mimeType = $mimeStart.$mimeStart === $mimeType ? $mimeStart : $mimeType; + } + + return $mimeType; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/AbstractHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/AbstractHeader.php new file mode 100644 index 0000000..d61df57 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/AbstractHeader.php @@ -0,0 +1,284 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Encoder\QpMimeHeaderEncoder; + +/** + * An abstract base MIME Header. + * + * @author Chris Corbyn + */ +abstract class AbstractHeader implements HeaderInterface +{ + public const PHRASE_PATTERN = '(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?"((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*(?:\r\n))?[ \t])?"(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))+?)'; + + private static $encoder; + + private $name; + private $lineLength = 76; + private $lang; + private $charset = 'utf-8'; + + public function __construct(string $name) + { + $this->name = $name; + } + + public function setCharset(string $charset) + { + $this->charset = $charset; + } + + public function getCharset(): ?string + { + return $this->charset; + } + + /** + * Set the language used in this Header. + * + * For example, for US English, 'en-us'. + */ + public function setLanguage(string $lang) + { + $this->lang = $lang; + } + + public function getLanguage(): ?string + { + return $this->lang; + } + + public function getName(): string + { + return $this->name; + } + + public function setMaxLineLength(int $lineLength) + { + $this->lineLength = $lineLength; + } + + public function getMaxLineLength(): int + { + return $this->lineLength; + } + + public function toString(): string + { + return $this->tokensToString($this->toTokens()); + } + + /** + * Produces a compliant, formatted RFC 2822 'phrase' based on the string given. + * + * @param string $string as displayed + * @param bool $shorten the first line to make remove for header name + */ + protected function createPhrase(HeaderInterface $header, string $string, string $charset, bool $shorten = false): string + { + // Treat token as exactly what was given + $phraseStr = $string; + + // If it's not valid + if (!preg_match('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) { + // .. but it is just ascii text, try escaping some characters + // and make it a quoted-string + if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) { + foreach (['\\', '"'] as $char) { + $phraseStr = str_replace($char, '\\'.$char, $phraseStr); + } + $phraseStr = '"'.$phraseStr.'"'; + } else { + // ... otherwise it needs encoding + // Determine space remaining on line if first line + if ($shorten) { + $usedLength = \strlen($header->getName().': '); + } else { + $usedLength = 0; + } + $phraseStr = $this->encodeWords($header, $string, $usedLength); + } + } elseif (str_contains($phraseStr, '(')) { + foreach (['\\', '"'] as $char) { + $phraseStr = str_replace($char, '\\'.$char, $phraseStr); + } + $phraseStr = '"'.$phraseStr.'"'; + } + + return $phraseStr; + } + + /** + * Encode needed word tokens within a string of input. + */ + protected function encodeWords(HeaderInterface $header, string $input, int $usedLength = -1): string + { + $value = ''; + $tokens = $this->getEncodableWordTokens($input); + foreach ($tokens as $token) { + // See RFC 2822, Sect 2.2 (really 2.2 ??) + if ($this->tokenNeedsEncoding($token)) { + // Don't encode starting WSP + $firstChar = substr($token, 0, 1); + switch ($firstChar) { + case ' ': + case "\t": + $value .= $firstChar; + $token = substr($token, 1); + } + + if (-1 == $usedLength) { + $usedLength = \strlen($header->getName().': ') + \strlen($value); + } + $value .= $this->getTokenAsEncodedWord($token, $usedLength); + } else { + $value .= $token; + } + } + + return $value; + } + + protected function tokenNeedsEncoding(string $token): bool + { + return (bool) preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token); + } + + /** + * Splits a string into tokens in blocks of words which can be encoded quickly. + * + * @return string[] + */ + protected function getEncodableWordTokens(string $string): array + { + $tokens = []; + $encodedToken = ''; + // Split at all whitespace boundaries + foreach (preg_split('~(?=[\t ])~', $string) as $token) { + if ($this->tokenNeedsEncoding($token)) { + $encodedToken .= $token; + } else { + if ('' !== $encodedToken) { + $tokens[] = $encodedToken; + $encodedToken = ''; + } + $tokens[] = $token; + } + } + if ('' !== $encodedToken) { + $tokens[] = $encodedToken; + } + + return $tokens; + } + + /** + * Get a token as an encoded word for safe insertion into headers. + */ + protected function getTokenAsEncodedWord(string $token, int $firstLineOffset = 0): string + { + if (null === self::$encoder) { + self::$encoder = new QpMimeHeaderEncoder(); + } + + // Adjust $firstLineOffset to account for space needed for syntax + $charsetDecl = $this->charset; + if (null !== $this->lang) { + $charsetDecl .= '*'.$this->lang; + } + $encodingWrapperLength = \strlen('=?'.$charsetDecl.'?'.self::$encoder->getName().'??='); + + if ($firstLineOffset >= 75) { + // Does this logic need to be here? + $firstLineOffset = 0; + } + + $encodedTextLines = explode("\r\n", + self::$encoder->encodeString($token, $this->charset, $firstLineOffset, 75 - $encodingWrapperLength) + ); + + if ('iso-2022-jp' !== strtolower($this->charset)) { + // special encoding for iso-2022-jp using mb_encode_mimeheader + foreach ($encodedTextLines as $lineNum => $line) { + $encodedTextLines[$lineNum] = '=?'.$charsetDecl.'?'.self::$encoder->getName().'?'.$line.'?='; + } + } + + return implode("\r\n ", $encodedTextLines); + } + + /** + * Generates tokens from the given string which include CRLF as individual tokens. + * + * @return string[] + */ + protected function generateTokenLines(string $token): array + { + return preg_split('~(\r\n)~', $token, -1, \PREG_SPLIT_DELIM_CAPTURE); + } + + /** + * Generate a list of all tokens in the final header. + */ + protected function toTokens(?string $string = null): array + { + if (null === $string) { + $string = $this->getBodyAsString(); + } + + $tokens = []; + // Generate atoms; split at all invisible boundaries followed by WSP + foreach (preg_split('~(?=[ \t])~', $string) as $token) { + $newTokens = $this->generateTokenLines($token); + foreach ($newTokens as $newToken) { + $tokens[] = $newToken; + } + } + + return $tokens; + } + + /** + * Takes an array of tokens which appear in the header and turns them into + * an RFC 2822 compliant string, adding FWSP where needed. + * + * @param string[] $tokens + */ + private function tokensToString(array $tokens): string + { + $lineCount = 0; + $headerLines = []; + $headerLines[] = $this->name.': '; + $currentLine = &$headerLines[$lineCount++]; + + // Build all tokens back into compliant header + foreach ($tokens as $i => $token) { + // Line longer than specified maximum or token was just a new line + if (("\r\n" === $token) || + ($i > 0 && \strlen($currentLine.$token) > $this->lineLength) + && '' !== $currentLine) { + $headerLines[] = ''; + $currentLine = &$headerLines[$lineCount++]; + } + + // Append token to the line + if ("\r\n" !== $token) { + $currentLine .= $token; + } + } + + // Implode with FWS (RFC 2822, 2.2.3) + return implode("\r\n", $headerLines); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/DateHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/DateHeader.php new file mode 100644 index 0000000..a7385d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/DateHeader.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +/** + * A Date MIME Header. + * + * @author Chris Corbyn + */ +final class DateHeader extends AbstractHeader +{ + private $dateTime; + + public function __construct(string $name, \DateTimeInterface $date) + { + parent::__construct($name); + + $this->setDateTime($date); + } + + /** + * @param \DateTimeInterface $body + */ + public function setBody($body) + { + $this->setDateTime($body); + } + + public function getBody(): \DateTimeImmutable + { + return $this->getDateTime(); + } + + public function getDateTime(): \DateTimeImmutable + { + return $this->dateTime; + } + + /** + * Set the date-time of the Date in this Header. + * + * If a DateTime instance is provided, it is converted to DateTimeImmutable. + */ + public function setDateTime(\DateTimeInterface $dateTime) + { + if ($dateTime instanceof \DateTime) { + $immutable = new \DateTimeImmutable('@'.$dateTime->getTimestamp()); + $dateTime = $immutable->setTimezone($dateTime->getTimezone()); + } + $this->dateTime = $dateTime; + } + + public function getBodyAsString(): string + { + return $this->dateTime->format(\DateTime::RFC2822); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/HeaderInterface.php b/php/libraries/composer/vendor/symfony/mime/Header/HeaderInterface.php new file mode 100644 index 0000000..4546947 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/HeaderInterface.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +/** + * A MIME Header. + * + * @author Chris Corbyn + */ +interface HeaderInterface +{ + /** + * Sets the body. + * + * The type depends on the Header concrete class. + * + * @param mixed $body + */ + public function setBody($body); + + /** + * Gets the body. + * + * The return type depends on the Header concrete class. + * + * @return mixed + */ + public function getBody(); + + public function setCharset(string $charset); + + public function getCharset(): ?string; + + public function setLanguage(string $lang); + + public function getLanguage(): ?string; + + public function getName(): string; + + public function setMaxLineLength(int $lineLength); + + public function getMaxLineLength(): int; + + /** + * Gets this Header rendered as a compliant string. + */ + public function toString(): string; + + /** + * Gets the header's body, prepared for folding into a final header value. + * + * This is not necessarily RFC 2822 compliant since folding white space is + * not added at this stage (see {@link toString()} for that). + */ + public function getBodyAsString(): string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/Headers.php b/php/libraries/composer/vendor/symfony/mime/Header/Headers.php new file mode 100644 index 0000000..b1ebf9a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/Headers.php @@ -0,0 +1,307 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\LogicException; + +/** + * A collection of headers. + * + * @author Fabien Potencier + */ +final class Headers +{ + private const UNIQUE_HEADERS = [ + 'date', 'from', 'sender', 'reply-to', 'to', 'cc', 'bcc', + 'message-id', 'in-reply-to', 'references', 'subject', + ]; + private const HEADER_CLASS_MAP = [ + 'date' => DateHeader::class, + 'from' => MailboxListHeader::class, + 'sender' => MailboxHeader::class, + 'reply-to' => MailboxListHeader::class, + 'to' => MailboxListHeader::class, + 'cc' => MailboxListHeader::class, + 'bcc' => MailboxListHeader::class, + 'message-id' => IdentificationHeader::class, + 'in-reply-to' => UnstructuredHeader::class, // `In-Reply-To` and `References` are less strict than RFC 2822 (3.6.4) to allow users entering the original email's ... + 'references' => UnstructuredHeader::class, // ... `Message-ID`, even if that is no valid `msg-id` + 'return-path' => PathHeader::class, + ]; + + /** + * @var HeaderInterface[][] + */ + private $headers = []; + private $lineLength = 76; + + public function __construct(HeaderInterface ...$headers) + { + foreach ($headers as $header) { + $this->add($header); + } + } + + public function __clone() + { + foreach ($this->headers as $name => $collection) { + foreach ($collection as $i => $header) { + $this->headers[$name][$i] = clone $header; + } + } + } + + public function setMaxLineLength(int $lineLength) + { + $this->lineLength = $lineLength; + foreach ($this->all() as $header) { + $header->setMaxLineLength($lineLength); + } + } + + public function getMaxLineLength(): int + { + return $this->lineLength; + } + + /** + * @param array $addresses + * + * @return $this + */ + public function addMailboxListHeader(string $name, array $addresses): self + { + return $this->add(new MailboxListHeader($name, Address::createArray($addresses))); + } + + /** + * @param Address|string $address + * + * @return $this + */ + public function addMailboxHeader(string $name, $address): self + { + return $this->add(new MailboxHeader($name, Address::create($address))); + } + + /** + * @param string|array $ids + * + * @return $this + */ + public function addIdHeader(string $name, $ids): self + { + return $this->add(new IdentificationHeader($name, $ids)); + } + + /** + * @param Address|string $path + * + * @return $this + */ + public function addPathHeader(string $name, $path): self + { + return $this->add(new PathHeader($name, $path instanceof Address ? $path : new Address($path))); + } + + /** + * @return $this + */ + public function addDateHeader(string $name, \DateTimeInterface $dateTime): self + { + return $this->add(new DateHeader($name, $dateTime)); + } + + /** + * @return $this + */ + public function addTextHeader(string $name, string $value): self + { + return $this->add(new UnstructuredHeader($name, $value)); + } + + /** + * @return $this + */ + public function addParameterizedHeader(string $name, string $value, array $params = []): self + { + return $this->add(new ParameterizedHeader($name, $value, $params)); + } + + /** + * @return $this + */ + public function addHeader(string $name, $argument, array $more = []): self + { + $parts = explode('\\', self::HEADER_CLASS_MAP[strtolower($name)] ?? UnstructuredHeader::class); + $method = 'add'.ucfirst(array_pop($parts)); + if ('addUnstructuredHeader' === $method) { + $method = 'addTextHeader'; + } elseif ('addIdentificationHeader' === $method) { + $method = 'addIdHeader'; + } + + return $this->$method($name, $argument, $more); + } + + public function has(string $name): bool + { + return isset($this->headers[strtolower($name)]); + } + + /** + * @return $this + */ + public function add(HeaderInterface $header): self + { + self::checkHeaderClass($header); + + $header->setMaxLineLength($this->lineLength); + $name = strtolower($header->getName()); + + if (\in_array($name, self::UNIQUE_HEADERS, true) && isset($this->headers[$name]) && \count($this->headers[$name]) > 0) { + throw new LogicException(sprintf('Impossible to set header "%s" as it\'s already defined and must be unique.', $header->getName())); + } + + $this->headers[$name][] = $header; + + return $this; + } + + public function get(string $name): ?HeaderInterface + { + $name = strtolower($name); + if (!isset($this->headers[$name])) { + return null; + } + + $values = array_values($this->headers[$name]); + + return array_shift($values); + } + + public function all(?string $name = null): iterable + { + if (null === $name) { + foreach ($this->headers as $name => $collection) { + foreach ($collection as $header) { + yield $name => $header; + } + } + } elseif (isset($this->headers[strtolower($name)])) { + foreach ($this->headers[strtolower($name)] as $header) { + yield $header; + } + } + } + + public function getNames(): array + { + return array_keys($this->headers); + } + + public function remove(string $name): void + { + unset($this->headers[strtolower($name)]); + } + + public static function isUniqueHeader(string $name): bool + { + return \in_array(strtolower($name), self::UNIQUE_HEADERS, true); + } + + /** + * @throws LogicException if the header name and class are not compatible + */ + public static function checkHeaderClass(HeaderInterface $header): void + { + $name = strtolower($header->getName()); + + if (($c = self::HEADER_CLASS_MAP[$name] ?? null) && !$header instanceof $c) { + throw new LogicException(sprintf('The "%s" header must be an instance of "%s" (got "%s").', $header->getName(), $c, get_debug_type($header))); + } + } + + public function toString(): string + { + $string = ''; + foreach ($this->toArray() as $str) { + $string .= $str."\r\n"; + } + + return $string; + } + + public function toArray(): array + { + $arr = []; + foreach ($this->all() as $header) { + if ('' !== $header->getBodyAsString()) { + $arr[] = $header->toString(); + } + } + + return $arr; + } + + /** + * @internal + */ + public function getHeaderBody(string $name) + { + return $this->has($name) ? $this->get($name)->getBody() : null; + } + + /** + * @internal + */ + public function setHeaderBody(string $type, string $name, $body): void + { + if ($this->has($name)) { + $this->get($name)->setBody($body); + } else { + $this->{'add'.$type.'Header'}($name, $body); + } + } + + public function getHeaderParameter(string $name, string $parameter): ?string + { + if (!$this->has($name)) { + return null; + } + + $header = $this->get($name); + if (!$header instanceof ParameterizedHeader) { + throw new LogicException(sprintf('Unable to get parameter "%s" on header "%s" as the header is not of class "%s".', $parameter, $name, ParameterizedHeader::class)); + } + + return $header->getParameter($parameter); + } + + /** + * @internal + */ + public function setHeaderParameter(string $name, string $parameter, ?string $value): void + { + if (!$this->has($name)) { + throw new LogicException(sprintf('Unable to set parameter "%s" on header "%s" as the header is not defined.', $parameter, $name)); + } + + $header = $this->get($name); + if (!$header instanceof ParameterizedHeader) { + throw new LogicException(sprintf('Unable to set parameter "%s" on header "%s" as the header is not of class "%s".', $parameter, $name, ParameterizedHeader::class)); + } + + $header->setParameter($parameter, $value); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/IdentificationHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/IdentificationHeader.php new file mode 100644 index 0000000..8a94574 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/IdentificationHeader.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\RfcComplianceException; + +/** + * An ID MIME Header for something like Message-ID or Content-ID (one or more addresses). + * + * @author Chris Corbyn + */ +final class IdentificationHeader extends AbstractHeader +{ + private $ids = []; + private $idsAsAddresses = []; + + /** + * @param string|array $ids + */ + public function __construct(string $name, $ids) + { + parent::__construct($name); + + $this->setId($ids); + } + + /** + * @param string|array $body a string ID or an array of IDs + * + * @throws RfcComplianceException + */ + public function setBody($body) + { + $this->setId($body); + } + + public function getBody(): array + { + return $this->getIds(); + } + + /** + * Set the ID used in the value of this header. + * + * @param string|array $id + * + * @throws RfcComplianceException + */ + public function setId($id) + { + $this->setIds(\is_array($id) ? $id : [$id]); + } + + /** + * Get the ID used in the value of this Header. + * + * If multiple IDs are set only the first is returned. + */ + public function getId(): ?string + { + return $this->ids[0] ?? null; + } + + /** + * Set a collection of IDs to use in the value of this Header. + * + * @param string[] $ids + * + * @throws RfcComplianceException + */ + public function setIds(array $ids) + { + $this->ids = []; + $this->idsAsAddresses = []; + foreach ($ids as $id) { + $this->idsAsAddresses[] = new Address($id); + $this->ids[] = $id; + } + } + + /** + * Get the list of IDs used in this Header. + * + * @return string[] + */ + public function getIds(): array + { + return $this->ids; + } + + public function getBodyAsString(): string + { + $addrs = []; + foreach ($this->idsAsAddresses as $address) { + $addrs[] = '<'.$address->toString().'>'; + } + + return implode(' ', $addrs); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/MailboxHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/MailboxHeader.php new file mode 100644 index 0000000..b58c825 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/MailboxHeader.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\RfcComplianceException; + +/** + * A Mailbox MIME Header for something like Sender (one named address). + * + * @author Fabien Potencier + */ +final class MailboxHeader extends AbstractHeader +{ + private $address; + + public function __construct(string $name, Address $address) + { + parent::__construct($name); + + $this->setAddress($address); + } + + /** + * @param Address $body + * + * @throws RfcComplianceException + */ + public function setBody($body) + { + $this->setAddress($body); + } + + /** + * @throws RfcComplianceException + */ + public function getBody(): Address + { + return $this->getAddress(); + } + + /** + * @throws RfcComplianceException + */ + public function setAddress(Address $address) + { + $this->address = $address; + } + + public function getAddress(): Address + { + return $this->address; + } + + public function getBodyAsString(): string + { + $str = $this->address->getEncodedAddress(); + if ($name = $this->address->getName()) { + $str = $this->createPhrase($this, $name, $this->getCharset(), true).' <'.$str.'>'; + } + + return $str; + } + + /** + * Redefine the encoding requirements for an address. + * + * All "specials" must be encoded as the full header value will not be quoted + * + * @see RFC 2822 3.2.1 + */ + protected function tokenNeedsEncoding(string $token): bool + { + return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/MailboxListHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/MailboxListHeader.php new file mode 100644 index 0000000..ee2a26c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/MailboxListHeader.php @@ -0,0 +1,136 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\RfcComplianceException; + +/** + * A Mailbox list MIME Header for something like From, To, Cc, and Bcc (one or more named addresses). + * + * @author Chris Corbyn + */ +final class MailboxListHeader extends AbstractHeader +{ + private $addresses = []; + + /** + * @param Address[] $addresses + */ + public function __construct(string $name, array $addresses) + { + parent::__construct($name); + + $this->setAddresses($addresses); + } + + /** + * @param Address[] $body + * + * @throws RfcComplianceException + */ + public function setBody($body) + { + $this->setAddresses($body); + } + + /** + * @return Address[] + * + * @throws RfcComplianceException + */ + public function getBody(): array + { + return $this->getAddresses(); + } + + /** + * Sets a list of addresses to be shown in this Header. + * + * @param Address[] $addresses + * + * @throws RfcComplianceException + */ + public function setAddresses(array $addresses) + { + $this->addresses = []; + $this->addAddresses($addresses); + } + + /** + * Sets a list of addresses to be shown in this Header. + * + * @param Address[] $addresses + * + * @throws RfcComplianceException + */ + public function addAddresses(array $addresses) + { + foreach ($addresses as $address) { + $this->addAddress($address); + } + } + + /** + * @throws RfcComplianceException + */ + public function addAddress(Address $address) + { + $this->addresses[] = $address; + } + + /** + * @return Address[] + */ + public function getAddresses(): array + { + return $this->addresses; + } + + /** + * Gets the full mailbox list of this Header as an array of valid RFC 2822 strings. + * + * @return string[] + * + * @throws RfcComplianceException + */ + public function getAddressStrings(): array + { + $strings = []; + foreach ($this->addresses as $address) { + $str = $address->getEncodedAddress(); + if ($name = $address->getName()) { + $str = $this->createPhrase($this, $name, $this->getCharset(), !$strings).' <'.$str.'>'; + } + $strings[] = $str; + } + + return $strings; + } + + public function getBodyAsString(): string + { + return implode(', ', $this->getAddressStrings()); + } + + /** + * Redefine the encoding requirements for addresses. + * + * All "specials" must be encoded as the full header value will not be quoted + * + * @see RFC 2822 3.2.1 + */ + protected function tokenNeedsEncoding(string $token): bool + { + return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/ParameterizedHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/ParameterizedHeader.php new file mode 100644 index 0000000..22f46a8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/ParameterizedHeader.php @@ -0,0 +1,191 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Encoder\Rfc2231Encoder; + +/** + * @author Chris Corbyn + */ +final class ParameterizedHeader extends UnstructuredHeader +{ + /** + * RFC 2231's definition of a token. + * + * @var string + */ + public const TOKEN_REGEX = '(?:[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E]+)'; + + private $encoder; + private $parameters = []; + + public function __construct(string $name, string $value, array $parameters = []) + { + parent::__construct($name, $value); + + foreach ($parameters as $k => $v) { + $this->setParameter($k, $v); + } + + if ('content-type' !== strtolower($name)) { + $this->encoder = new Rfc2231Encoder(); + } + } + + public function setParameter(string $parameter, ?string $value) + { + $this->setParameters(array_merge($this->getParameters(), [$parameter => $value])); + } + + public function getParameter(string $parameter): string + { + return $this->getParameters()[$parameter] ?? ''; + } + + /** + * @param string[] $parameters + */ + public function setParameters(array $parameters) + { + $this->parameters = $parameters; + } + + /** + * @return string[] + */ + public function getParameters(): array + { + return $this->parameters; + } + + public function getBodyAsString(): string + { + $body = parent::getBodyAsString(); + foreach ($this->parameters as $name => $value) { + if (null !== $value) { + $body .= '; '.$this->createParameter($name, $value); + } + } + + return $body; + } + + /** + * Generate a list of all tokens in the final header. + * + * This doesn't need to be overridden in theory, but it is for implementation + * reasons to prevent potential breakage of attributes. + */ + protected function toTokens(?string $string = null): array + { + $tokens = parent::toTokens(parent::getBodyAsString()); + + // Try creating any parameters + foreach ($this->parameters as $name => $value) { + if (null !== $value) { + // Add the semi-colon separator + $tokens[\count($tokens) - 1] .= ';'; + $tokens = array_merge($tokens, $this->generateTokenLines(' '.$this->createParameter($name, $value))); + } + } + + return $tokens; + } + + /** + * Render an RFC 2047 compliant header parameter from the $name and $value. + */ + private function createParameter(string $name, string $value): string + { + $origValue = $value; + + $encoded = false; + // Allow room for parameter name, indices, "=" and DQUOTEs + $maxValueLength = $this->getMaxLineLength() - \strlen($name.'=*N"";') - 1; + $firstLineOffset = 0; + + // If it's not already a valid parameter value... + if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { + // TODO: text, or something else?? + // ... and it's not ascii + if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) { + $encoded = true; + // Allow space for the indices, charset and language + $maxValueLength = $this->getMaxLineLength() - \strlen($name.'*N*="";') - 1; + $firstLineOffset = \strlen($this->getCharset()."'".$this->getLanguage()."'"); + } + + if (\in_array($name, ['name', 'filename'], true) && 'form-data' === $this->getValue() && 'content-disposition' === strtolower($this->getName()) && preg_match('//u', $value)) { + // WHATWG HTML living standard 4.10.21.8 2 specifies: + // For field names and filenames for file fields, the result of the + // encoding in the previous bullet point must be escaped by replacing + // any 0x0A (LF) bytes with the byte sequence `%0A`, 0x0D (CR) with `%0D` + // and 0x22 (") with `%22`. + // The user agent must not perform any other escapes. + $value = str_replace(['"', "\r", "\n"], ['%22', '%0D', '%0A'], $value); + + if (\strlen($value) <= $maxValueLength) { + return $name.'="'.$value.'"'; + } + + $value = $origValue; + } + } + + // Encode if we need to + if ($encoded || \strlen($value) > $maxValueLength) { + if (null !== $this->encoder) { + $value = $this->encoder->encodeString($origValue, $this->getCharset(), $firstLineOffset, $maxValueLength); + } else { + // We have to go against RFC 2183/2231 in some areas for interoperability + $value = $this->getTokenAsEncodedWord($origValue); + $encoded = false; + } + } + + $valueLines = $this->encoder ? explode("\r\n", $value) : [$value]; + + // Need to add indices + if (\count($valueLines) > 1) { + $paramLines = []; + foreach ($valueLines as $i => $line) { + $paramLines[] = $name.'*'.$i.$this->getEndOfParameterValue($line, true, 0 === $i); + } + + return implode(";\r\n ", $paramLines); + } else { + return $name.$this->getEndOfParameterValue($valueLines[0], $encoded, true); + } + } + + /** + * Returns the parameter value from the "=" and beyond. + * + * @param string $value to append + */ + private function getEndOfParameterValue(string $value, bool $encoded = false, bool $firstLine = false): string + { + $forceHttpQuoting = 'form-data' === $this->getValue() && 'content-disposition' === strtolower($this->getName()); + if ($forceHttpQuoting || !preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { + $value = '"'.$value.'"'; + } + $prepend = '='; + if ($encoded) { + $prepend = '*='; + if ($firstLine) { + $prepend = '*='.$this->getCharset()."'".$this->getLanguage()."'"; + } + } + + return $prepend.$value; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/PathHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/PathHeader.php new file mode 100644 index 0000000..5101ad0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/PathHeader.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\RfcComplianceException; + +/** + * A Path Header, such a Return-Path (one address). + * + * @author Chris Corbyn + */ +final class PathHeader extends AbstractHeader +{ + private $address; + + public function __construct(string $name, Address $address) + { + parent::__construct($name); + + $this->setAddress($address); + } + + /** + * @param Address $body + * + * @throws RfcComplianceException + */ + public function setBody($body) + { + $this->setAddress($body); + } + + public function getBody(): Address + { + return $this->getAddress(); + } + + public function setAddress(Address $address) + { + $this->address = $address; + } + + public function getAddress(): Address + { + return $this->address; + } + + public function getBodyAsString(): string + { + return '<'.$this->address->toString().'>'; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Header/UnstructuredHeader.php b/php/libraries/composer/vendor/symfony/mime/Header/UnstructuredHeader.php new file mode 100644 index 0000000..2085ddf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Header/UnstructuredHeader.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Header; + +/** + * A Simple MIME Header. + * + * @author Chris Corbyn + */ +class UnstructuredHeader extends AbstractHeader +{ + private $value; + + public function __construct(string $name, string $value) + { + parent::__construct($name); + + $this->setValue($value); + } + + /** + * @param string $body + */ + public function setBody($body) + { + $this->setValue($body); + } + + /** + * @return string + */ + public function getBody() + { + return $this->getValue(); + } + + /** + * Get the (unencoded) value of this header. + */ + public function getValue(): string + { + return $this->value; + } + + /** + * Set the (unencoded) value of this header. + */ + public function setValue(string $value) + { + $this->value = $value; + } + + /** + * Get the value of this header prepared for rendering. + */ + public function getBodyAsString(): string + { + return $this->encodeWords($this, $this->value); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/LICENSE b/php/libraries/composer/vendor/symfony/mime/LICENSE new file mode 100644 index 0000000..4dd83ce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/mime/Message.php b/php/libraries/composer/vendor/symfony/mime/Message.php new file mode 100644 index 0000000..639b26b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Message.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\Mime; + +use Symfony\Component\Mime\Exception\LogicException; +use Symfony\Component\Mime\Header\Headers; +use Symfony\Component\Mime\Part\AbstractPart; +use Symfony\Component\Mime\Part\TextPart; + +/** + * @author Fabien Potencier + */ +class Message extends RawMessage +{ + private $headers; + private $body; + + public function __construct(?Headers $headers = null, ?AbstractPart $body = null) + { + $this->headers = $headers ? clone $headers : new Headers(); + $this->body = $body; + } + + public function __clone() + { + $this->headers = clone $this->headers; + + if (null !== $this->body) { + $this->body = clone $this->body; + } + } + + /** + * @return $this + */ + public function setBody(?AbstractPart $body = null) + { + $this->body = $body; + + return $this; + } + + public function getBody(): ?AbstractPart + { + return $this->body; + } + + /** + * @return $this + */ + public function setHeaders(Headers $headers) + { + $this->headers = $headers; + + return $this; + } + + public function getHeaders(): Headers + { + return $this->headers; + } + + public function getPreparedHeaders(): Headers + { + $headers = clone $this->headers; + + if (!$headers->has('From')) { + if (!$headers->has('Sender')) { + throw new LogicException('An email must have a "From" or a "Sender" header.'); + } + $headers->addMailboxListHeader('From', [$headers->get('Sender')->getAddress()]); + } + + if (!$headers->has('MIME-Version')) { + $headers->addTextHeader('MIME-Version', '1.0'); + } + + if (!$headers->has('Date')) { + $headers->addDateHeader('Date', new \DateTimeImmutable()); + } + + // determine the "real" sender + if (!$headers->has('Sender') && \count($froms = $headers->get('From')->getAddresses()) > 1) { + $headers->addMailboxHeader('Sender', $froms[0]); + } + + if (!$headers->has('Message-ID')) { + $headers->addIdHeader('Message-ID', $this->generateMessageId()); + } + + // remove the Bcc field which should NOT be part of the sent message + $headers->remove('Bcc'); + + return $headers; + } + + public function toString(): string + { + if (null === $body = $this->getBody()) { + $body = new TextPart(''); + } + + return $this->getPreparedHeaders()->toString().$body->toString(); + } + + public function toIterable(): iterable + { + if (null === $body = $this->getBody()) { + $body = new TextPart(''); + } + + yield $this->getPreparedHeaders()->toString(); + yield from $body->toIterable(); + } + + public function ensureValidity() + { + if (!$this->headers->has('To') && !$this->headers->has('Cc') && !$this->headers->has('Bcc')) { + throw new LogicException('An email must have a "To", "Cc", or "Bcc" header.'); + } + + if (!$this->headers->has('From') && !$this->headers->has('Sender')) { + throw new LogicException('An email must have a "From" or a "Sender" header.'); + } + + parent::ensureValidity(); + } + + public function generateMessageId(): string + { + if ($this->headers->has('Sender')) { + $sender = $this->headers->get('Sender')->getAddress(); + } elseif ($this->headers->has('From')) { + if (!$froms = $this->headers->get('From')->getAddresses()) { + throw new LogicException('A "From" header must have at least one email address.'); + } + $sender = $froms[0]; + } else { + throw new LogicException('An email must have a "From" or a "Sender" header.'); + } + + return bin2hex(random_bytes(16)).strstr($sender->getAddress(), '@'); + } + + public function __serialize(): array + { + return [$this->headers, $this->body]; + } + + public function __unserialize(array $data): void + { + [$this->headers, $this->body] = $data; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/MessageConverter.php b/php/libraries/composer/vendor/symfony/mime/MessageConverter.php new file mode 100644 index 0000000..0539eac --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/MessageConverter.php @@ -0,0 +1,125 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +use Symfony\Component\Mime\Exception\RuntimeException; +use Symfony\Component\Mime\Part\DataPart; +use Symfony\Component\Mime\Part\Multipart\AlternativePart; +use Symfony\Component\Mime\Part\Multipart\MixedPart; +use Symfony\Component\Mime\Part\Multipart\RelatedPart; +use Symfony\Component\Mime\Part\TextPart; + +/** + * @author Fabien Potencier + */ +final class MessageConverter +{ + /** + * @throws RuntimeException when unable to convert the message to an email + */ + public static function toEmail(Message $message): Email + { + if ($message instanceof Email) { + return $message; + } + + // try to convert to a "simple" Email instance + $body = $message->getBody(); + if ($body instanceof TextPart) { + return self::createEmailFromTextPart($message, $body); + } + + if ($body instanceof AlternativePart) { + return self::createEmailFromAlternativePart($message, $body); + } + + if ($body instanceof RelatedPart) { + return self::createEmailFromRelatedPart($message, $body); + } + + if ($body instanceof MixedPart) { + $parts = $body->getParts(); + if ($parts[0] instanceof RelatedPart) { + $email = self::createEmailFromRelatedPart($message, $parts[0]); + } elseif ($parts[0] instanceof AlternativePart) { + $email = self::createEmailFromAlternativePart($message, $parts[0]); + } elseif ($parts[0] instanceof TextPart) { + $email = self::createEmailFromTextPart($message, $parts[0]); + } else { + throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message))); + } + + return self::attachParts($email, \array_slice($parts, 1)); + } + + throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message))); + } + + private static function createEmailFromTextPart(Message $message, TextPart $part): Email + { + if ('text' === $part->getMediaType() && 'plain' === $part->getMediaSubtype()) { + return (new Email(clone $message->getHeaders()))->text($part->getBody(), $part->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8'); + } + if ('text' === $part->getMediaType() && 'html' === $part->getMediaSubtype()) { + return (new Email(clone $message->getHeaders()))->html($part->getBody(), $part->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8'); + } + + throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message))); + } + + private static function createEmailFromAlternativePart(Message $message, AlternativePart $part): Email + { + $parts = $part->getParts(); + if ( + 2 === \count($parts) && + $parts[0] instanceof TextPart && 'text' === $parts[0]->getMediaType() && 'plain' === $parts[0]->getMediaSubtype() && + $parts[1] instanceof TextPart && 'text' === $parts[1]->getMediaType() && 'html' === $parts[1]->getMediaSubtype() + ) { + return (new Email(clone $message->getHeaders())) + ->text($parts[0]->getBody(), $parts[0]->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8') + ->html($parts[1]->getBody(), $parts[1]->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8') + ; + } + + throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message))); + } + + private static function createEmailFromRelatedPart(Message $message, RelatedPart $part): Email + { + $parts = $part->getParts(); + if ($parts[0] instanceof AlternativePart) { + $email = self::createEmailFromAlternativePart($message, $parts[0]); + } elseif ($parts[0] instanceof TextPart) { + $email = self::createEmailFromTextPart($message, $parts[0]); + } else { + throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message))); + } + + return self::attachParts($email, \array_slice($parts, 1)); + } + + private static function attachParts(Email $email, array $parts): Email + { + foreach ($parts as $part) { + if (!$part instanceof DataPart) { + throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($email))); + } + + $headers = $part->getPreparedHeaders(); + $method = 'inline' === $headers->getHeaderBody('Content-Disposition') ? 'embed' : 'attach'; + $name = $headers->getHeaderParameter('Content-Disposition', 'filename'); + $email->$method($part->getBody(), $name, $part->getMediaType().'/'.$part->getMediaSubtype()); + } + + return $email; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/MimeTypeGuesserInterface.php b/php/libraries/composer/vendor/symfony/mime/MimeTypeGuesserInterface.php new file mode 100644 index 0000000..30ee3b6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/MimeTypeGuesserInterface.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\Mime; + +/** + * Guesses the MIME type of a file. + * + * @author Fabien Potencier + */ +interface MimeTypeGuesserInterface +{ + /** + * Returns true if this guesser is supported. + */ + public function isGuesserSupported(): bool; + + /** + * Guesses the MIME type of the file with the given path. + * + * @throws \LogicException If the guesser is not supported + * @throws \InvalidArgumentException If the file does not exist or is not readable + */ + public function guessMimeType(string $path): ?string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/MimeTypes.php b/php/libraries/composer/vendor/symfony/mime/MimeTypes.php new file mode 100644 index 0000000..bdea994 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/MimeTypes.php @@ -0,0 +1,3537 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +use Symfony\Component\Mime\Exception\LogicException; + +/** + * Manages MIME types and file extensions. + * + * For MIME type guessing, you can register custom guessers + * by calling the registerGuesser() method. + * Custom guessers are always called before any default ones: + * + * $guesser = new MimeTypes(); + * $guesser->registerGuesser(new MyCustomMimeTypeGuesser()); + * + * If you want to change the order of the default guessers, just re-register your + * preferred one as a custom one. The last registered guesser is preferred over + * previously registered ones. + * + * Re-registering a built-in guesser also allows you to configure it: + * + * $guesser = new MimeTypes(); + * $guesser->registerGuesser(new FileinfoMimeTypeGuesser('/path/to/magic/file')); + * + * @author Fabien Potencier + */ +final class MimeTypes implements MimeTypesInterface +{ + private $extensions = []; + private $mimeTypes = []; + + /** + * @var MimeTypeGuesserInterface[] + */ + private $guessers = []; + private static $default; + + public function __construct(array $map = []) + { + foreach ($map as $mimeType => $extensions) { + $this->extensions[$mimeType] = $extensions; + + foreach ($extensions as $extension) { + $this->mimeTypes[$extension][] = $mimeType; + } + } + $this->registerGuesser(new FileBinaryMimeTypeGuesser()); + $this->registerGuesser(new FileinfoMimeTypeGuesser()); + } + + public static function setDefault(self $default) + { + self::$default = $default; + } + + public static function getDefault(): self + { + return self::$default ?? self::$default = new self(); + } + + /** + * Registers a MIME type guesser. + * + * The last registered guesser has precedence over the other ones. + */ + public function registerGuesser(MimeTypeGuesserInterface $guesser) + { + array_unshift($this->guessers, $guesser); + } + + /** + * {@inheritdoc} + */ + public function getExtensions(string $mimeType): array + { + if ($this->extensions) { + $extensions = $this->extensions[$mimeType] ?? $this->extensions[$lcMimeType = strtolower($mimeType)] ?? null; + } + + return $extensions ?? self::MAP[$mimeType] ?? self::MAP[$lcMimeType ?? strtolower($mimeType)] ?? []; + } + + /** + * {@inheritdoc} + */ + public function getMimeTypes(string $ext): array + { + if ($this->mimeTypes) { + $mimeTypes = $this->mimeTypes[$ext] ?? $this->mimeTypes[$lcExt = strtolower($ext)] ?? null; + } + + return $mimeTypes ?? self::REVERSE_MAP[$ext] ?? self::REVERSE_MAP[$lcExt ?? strtolower($ext)] ?? []; + } + + /** + * {@inheritdoc} + */ + public function isGuesserSupported(): bool + { + foreach ($this->guessers as $guesser) { + if ($guesser->isGuesserSupported()) { + return true; + } + } + + return false; + } + + /** + * {@inheritdoc} + * + * The file is passed to each registered MIME type guesser in reverse order + * of their registration (last registered is queried first). Once a guesser + * returns a value that is not null, this method terminates and returns the + * value. + */ + public function guessMimeType(string $path): ?string + { + foreach ($this->guessers as $guesser) { + if (!$guesser->isGuesserSupported()) { + continue; + } + + if (null !== $mimeType = $guesser->guessMimeType($path)) { + return $mimeType; + } + } + + if (!$this->isGuesserSupported()) { + throw new LogicException('Unable to guess the MIME type as no guessers are available (have you enabled the php_fileinfo extension?).'); + } + + return null; + } + + /** + * A map of MIME types and their default extensions. + * + * Updated from upstream on 2021-09-03 + * + * @see Resources/bin/update_mime_types.php + */ + private const MAP = [ + 'application/acrobat' => ['pdf'], + 'application/andrew-inset' => ['ez'], + 'application/annodex' => ['anx'], + 'application/applixware' => ['aw'], + 'application/atom+xml' => ['atom'], + 'application/atomcat+xml' => ['atomcat'], + 'application/atomdeleted+xml' => ['atomdeleted'], + 'application/atomsvc+xml' => ['atomsvc'], + 'application/atsc-dwd+xml' => ['dwd'], + 'application/atsc-held+xml' => ['held'], + 'application/atsc-rsat+xml' => ['rsat'], + 'application/bdoc' => ['bdoc'], + 'application/bzip2' => ['bz2', 'bz'], + 'application/calendar+xml' => ['xcs'], + 'application/ccxml+xml' => ['ccxml'], + 'application/cdfx+xml' => ['cdfx'], + 'application/cdmi-capability' => ['cdmia'], + 'application/cdmi-container' => ['cdmic'], + 'application/cdmi-domain' => ['cdmid'], + 'application/cdmi-object' => ['cdmio'], + 'application/cdmi-queue' => ['cdmiq'], + 'application/cdr' => ['cdr'], + 'application/coreldraw' => ['cdr'], + 'application/csv' => ['csv'], + 'application/cu-seeme' => ['cu'], + 'application/dash+xml' => ['mpd'], + 'application/davmount+xml' => ['davmount'], + 'application/dbase' => ['dbf'], + 'application/dbf' => ['dbf'], + 'application/dicom' => ['dcm'], + 'application/docbook+xml' => ['dbk', 'docbook'], + 'application/dssc+der' => ['dssc'], + 'application/dssc+xml' => ['xdssc'], + 'application/ecmascript' => ['ecma', 'es'], + 'application/emf' => ['emf'], + 'application/emma+xml' => ['emma'], + 'application/emotionml+xml' => ['emotionml'], + 'application/epub+zip' => ['epub'], + 'application/exi' => ['exi'], + 'application/fdt+xml' => ['fdt'], + 'application/font-tdpfr' => ['pfr'], + 'application/font-woff' => ['woff'], + 'application/futuresplash' => ['swf', 'spl'], + 'application/geo+json' => ['geojson', 'geo.json'], + 'application/gml+xml' => ['gml'], + 'application/gnunet-directory' => ['gnd'], + 'application/gpx' => ['gpx'], + 'application/gpx+xml' => ['gpx'], + 'application/gxf' => ['gxf'], + 'application/gzip' => ['gz'], + 'application/hjson' => ['hjson'], + 'application/hyperstudio' => ['stk'], + 'application/ico' => ['ico'], + 'application/ics' => ['vcs', 'ics'], + 'application/illustrator' => ['ai'], + 'application/inkml+xml' => ['ink', 'inkml'], + 'application/ipfix' => ['ipfix'], + 'application/its+xml' => ['its'], + 'application/java' => ['class'], + 'application/java-archive' => ['jar', 'war', 'ear'], + 'application/java-byte-code' => ['class'], + 'application/java-serialized-object' => ['ser'], + 'application/java-vm' => ['class'], + 'application/javascript' => ['js', 'mjs', 'jsm'], + 'application/jrd+json' => ['jrd'], + 'application/json' => ['json', 'map'], + 'application/json-patch+json' => ['json-patch'], + 'application/json5' => ['json5'], + 'application/jsonml+json' => ['jsonml'], + 'application/ld+json' => ['jsonld'], + 'application/lgr+xml' => ['lgr'], + 'application/lost+xml' => ['lostxml'], + 'application/lotus123' => ['123', 'wk1', 'wk3', 'wk4', 'wks'], + 'application/m3u' => ['m3u', 'm3u8', 'vlc'], + 'application/mac-binhex40' => ['hqx'], + 'application/mac-compactpro' => ['cpt'], + 'application/mads+xml' => ['mads'], + 'application/manifest+json' => ['webmanifest'], + 'application/marc' => ['mrc'], + 'application/marcxml+xml' => ['mrcx'], + 'application/mathematica' => ['ma', 'nb', 'mb'], + 'application/mathml+xml' => ['mathml', 'mml'], + 'application/mbox' => ['mbox'], + 'application/mdb' => ['mdb'], + 'application/mediaservercontrol+xml' => ['mscml'], + 'application/metalink+xml' => ['metalink'], + 'application/metalink4+xml' => ['meta4'], + 'application/mets+xml' => ['mets'], + 'application/mmt-aei+xml' => ['maei'], + 'application/mmt-usd+xml' => ['musd'], + 'application/mods+xml' => ['mods'], + 'application/mp21' => ['m21', 'mp21'], + 'application/mp4' => ['mp4s', 'm4p'], + 'application/mrb-consumer+xml' => ['xdf'], + 'application/mrb-publish+xml' => ['xdf'], + 'application/ms-tnef' => ['tnef', 'tnf'], + 'application/msaccess' => ['mdb'], + 'application/msexcel' => ['xls', 'xlc', 'xll', 'xlm', 'xlw', 'xla', 'xlt', 'xld'], + 'application/mspowerpoint' => ['ppz', 'ppt', 'pps', 'pot'], + 'application/msword' => ['doc', 'dot'], + 'application/msword-template' => ['dot'], + 'application/mxf' => ['mxf'], + 'application/n-quads' => ['nq'], + 'application/n-triples' => ['nt'], + 'application/nappdf' => ['pdf'], + 'application/node' => ['cjs'], + 'application/octet-stream' => ['bin', 'dms', 'lrf', 'mar', 'so', 'dist', 'distz', 'pkg', 'bpk', 'dump', 'elc', 'deploy', 'exe', 'dll', 'deb', 'dmg', 'iso', 'img', 'msi', 'msp', 'msm', 'buffer'], + 'application/oda' => ['oda'], + 'application/oebps-package+xml' => ['opf'], + 'application/ogg' => ['ogx'], + 'application/omdoc+xml' => ['omdoc'], + 'application/onenote' => ['onetoc', 'onetoc2', 'onetmp', 'onepkg'], + 'application/ovf' => ['ova'], + 'application/owl+xml' => ['owx'], + 'application/oxps' => ['oxps'], + 'application/p2p-overlay+xml' => ['relo'], + 'application/patch-ops-error+xml' => ['xer'], + 'application/pcap' => ['pcap', 'cap', 'dmp'], + 'application/pdf' => ['pdf'], + 'application/pgp' => ['pgp', 'gpg', 'asc'], + 'application/pgp-encrypted' => ['pgp', 'gpg', 'asc'], + 'application/pgp-keys' => ['skr', 'pkr', 'asc', 'pgp', 'gpg', 'key'], + 'application/pgp-signature' => ['asc', 'sig', 'pgp', 'gpg'], + 'application/photoshop' => ['psd'], + 'application/pics-rules' => ['prf'], + 'application/pkcs10' => ['p10'], + 'application/pkcs12' => ['p12', 'pfx'], + 'application/pkcs7-mime' => ['p7m', 'p7c'], + 'application/pkcs7-signature' => ['p7s'], + 'application/pkcs8' => ['p8'], + 'application/pkcs8-encrypted' => ['p8e'], + 'application/pkix-attr-cert' => ['ac'], + 'application/pkix-cert' => ['cer'], + 'application/pkix-crl' => ['crl'], + 'application/pkix-pkipath' => ['pkipath'], + 'application/pkixcmp' => ['pki'], + 'application/pls' => ['pls'], + 'application/pls+xml' => ['pls'], + 'application/postscript' => ['ai', 'eps', 'ps'], + 'application/powerpoint' => ['ppz', 'ppt', 'pps', 'pot'], + 'application/provenance+xml' => ['provx'], + 'application/prs.cww' => ['cww'], + 'application/pskc+xml' => ['pskcxml'], + 'application/ram' => ['ram'], + 'application/raml+yaml' => ['raml'], + 'application/rdf+xml' => ['rdf', 'owl', 'rdfs'], + 'application/reginfo+xml' => ['rif'], + 'application/relax-ng-compact-syntax' => ['rnc'], + 'application/resource-lists+xml' => ['rl'], + 'application/resource-lists-diff+xml' => ['rld'], + 'application/rls-services+xml' => ['rs'], + 'application/route-apd+xml' => ['rapd'], + 'application/route-s-tsid+xml' => ['sls'], + 'application/route-usd+xml' => ['rusd'], + 'application/rpki-ghostbusters' => ['gbr'], + 'application/rpki-manifest' => ['mft'], + 'application/rpki-roa' => ['roa'], + 'application/rsd+xml' => ['rsd'], + 'application/rss+xml' => ['rss'], + 'application/rtf' => ['rtf'], + 'application/sbml+xml' => ['sbml'], + 'application/schema+json' => ['json'], + 'application/scvp-cv-request' => ['scq'], + 'application/scvp-cv-response' => ['scs'], + 'application/scvp-vp-request' => ['spq'], + 'application/scvp-vp-response' => ['spp'], + 'application/sdp' => ['sdp'], + 'application/senml+xml' => ['senmlx'], + 'application/sensml+xml' => ['sensmlx'], + 'application/set-payment-initiation' => ['setpay'], + 'application/set-registration-initiation' => ['setreg'], + 'application/shf+xml' => ['shf'], + 'application/sieve' => ['siv', 'sieve'], + 'application/smil' => ['smil', 'smi', 'sml', 'kino'], + 'application/smil+xml' => ['smi', 'smil', 'sml', 'kino'], + 'application/sparql-query' => ['rq'], + 'application/sparql-results+xml' => ['srx'], + 'application/sql' => ['sql'], + 'application/srgs' => ['gram'], + 'application/srgs+xml' => ['grxml'], + 'application/sru+xml' => ['sru'], + 'application/ssdl+xml' => ['ssdl'], + 'application/ssml+xml' => ['ssml'], + 'application/stuffit' => ['sit', 'hqx'], + 'application/swid+xml' => ['swidtag'], + 'application/tei+xml' => ['tei', 'teicorpus'], + 'application/tga' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'application/thraud+xml' => ['tfi'], + 'application/timestamped-data' => ['tsd'], + 'application/toml' => ['toml'], + 'application/trig' => ['trig'], + 'application/ttml+xml' => ['ttml'], + 'application/ubjson' => ['ubj'], + 'application/urc-ressheet+xml' => ['rsheet'], + 'application/urc-targetdesc+xml' => ['td'], + 'application/vnd.1000minds.decision-model+xml' => ['1km'], + 'application/vnd.3gpp.pic-bw-large' => ['plb'], + 'application/vnd.3gpp.pic-bw-small' => ['psb'], + 'application/vnd.3gpp.pic-bw-var' => ['pvb'], + 'application/vnd.3gpp2.tcap' => ['tcap'], + 'application/vnd.3m.post-it-notes' => ['pwn'], + 'application/vnd.accpac.simply.aso' => ['aso'], + 'application/vnd.accpac.simply.imp' => ['imp'], + 'application/vnd.acucobol' => ['acu'], + 'application/vnd.acucorp' => ['atc', 'acutc'], + 'application/vnd.adobe.air-application-installer-package+zip' => ['air'], + 'application/vnd.adobe.flash.movie' => ['swf', 'spl'], + 'application/vnd.adobe.formscentral.fcdt' => ['fcdt'], + 'application/vnd.adobe.fxp' => ['fxp', 'fxpl'], + 'application/vnd.adobe.illustrator' => ['ai'], + 'application/vnd.adobe.xdp+xml' => ['xdp'], + 'application/vnd.adobe.xfdf' => ['xfdf'], + 'application/vnd.ahead.space' => ['ahead'], + 'application/vnd.airzip.filesecure.azf' => ['azf'], + 'application/vnd.airzip.filesecure.azs' => ['azs'], + 'application/vnd.amazon.ebook' => ['azw'], + 'application/vnd.amazon.mobi8-ebook' => ['azw3', 'kfx'], + 'application/vnd.americandynamics.acc' => ['acc'], + 'application/vnd.amiga.ami' => ['ami'], + 'application/vnd.android.package-archive' => ['apk'], + 'application/vnd.anser-web-certificate-issue-initiation' => ['cii'], + 'application/vnd.anser-web-funds-transfer-initiation' => ['fti'], + 'application/vnd.antix.game-component' => ['atx'], + 'application/vnd.appimage' => ['appimage'], + 'application/vnd.apple.installer+xml' => ['mpkg'], + 'application/vnd.apple.keynote' => ['key', 'keynote'], + 'application/vnd.apple.mpegurl' => ['m3u8', 'm3u'], + 'application/vnd.apple.numbers' => ['numbers'], + 'application/vnd.apple.pages' => ['pages'], + 'application/vnd.apple.pkpass' => ['pkpass'], + 'application/vnd.aristanetworks.swi' => ['swi'], + 'application/vnd.astraea-software.iota' => ['iota'], + 'application/vnd.audiograph' => ['aep'], + 'application/vnd.balsamiq.bmml+xml' => ['bmml'], + 'application/vnd.blueice.multipass' => ['mpm'], + 'application/vnd.bmi' => ['bmi'], + 'application/vnd.businessobjects' => ['rep'], + 'application/vnd.chemdraw+xml' => ['cdxml'], + 'application/vnd.chess-pgn' => ['pgn'], + 'application/vnd.chipnuts.karaoke-mmd' => ['mmd'], + 'application/vnd.cinderella' => ['cdy'], + 'application/vnd.citationstyles.style+xml' => ['csl'], + 'application/vnd.claymore' => ['cla'], + 'application/vnd.cloanto.rp9' => ['rp9'], + 'application/vnd.clonk.c4group' => ['c4g', 'c4d', 'c4f', 'c4p', 'c4u'], + 'application/vnd.cluetrust.cartomobile-config' => ['c11amc'], + 'application/vnd.cluetrust.cartomobile-config-pkg' => ['c11amz'], + 'application/vnd.coffeescript' => ['coffee'], + 'application/vnd.comicbook+zip' => ['cbz'], + 'application/vnd.comicbook-rar' => ['cbr'], + 'application/vnd.commonspace' => ['csp'], + 'application/vnd.contact.cmsg' => ['cdbcmsg'], + 'application/vnd.corel-draw' => ['cdr'], + 'application/vnd.cosmocaller' => ['cmc'], + 'application/vnd.crick.clicker' => ['clkx'], + 'application/vnd.crick.clicker.keyboard' => ['clkk'], + 'application/vnd.crick.clicker.palette' => ['clkp'], + 'application/vnd.crick.clicker.template' => ['clkt'], + 'application/vnd.crick.clicker.wordbank' => ['clkw'], + 'application/vnd.criticaltools.wbs+xml' => ['wbs'], + 'application/vnd.ctc-posml' => ['pml'], + 'application/vnd.cups-ppd' => ['ppd'], + 'application/vnd.curl.car' => ['car'], + 'application/vnd.curl.pcurl' => ['pcurl'], + 'application/vnd.dart' => ['dart'], + 'application/vnd.data-vision.rdz' => ['rdz'], + 'application/vnd.dbf' => ['dbf'], + 'application/vnd.debian.binary-package' => ['deb', 'udeb'], + 'application/vnd.dece.data' => ['uvf', 'uvvf', 'uvd', 'uvvd'], + 'application/vnd.dece.ttml+xml' => ['uvt', 'uvvt'], + 'application/vnd.dece.unspecified' => ['uvx', 'uvvx'], + 'application/vnd.dece.zip' => ['uvz', 'uvvz'], + 'application/vnd.denovo.fcselayout-link' => ['fe_launch'], + 'application/vnd.dna' => ['dna'], + 'application/vnd.dolby.mlp' => ['mlp'], + 'application/vnd.dpgraph' => ['dpg'], + 'application/vnd.dreamfactory' => ['dfac'], + 'application/vnd.ds-keypoint' => ['kpxx'], + 'application/vnd.dvb.ait' => ['ait'], + 'application/vnd.dvb.service' => ['svc'], + 'application/vnd.dynageo' => ['geo'], + 'application/vnd.ecowin.chart' => ['mag'], + 'application/vnd.emusic-emusic_package' => ['emp'], + 'application/vnd.enliven' => ['nml'], + 'application/vnd.epson.esf' => ['esf'], + 'application/vnd.epson.msf' => ['msf'], + 'application/vnd.epson.quickanime' => ['qam'], + 'application/vnd.epson.salt' => ['slt'], + 'application/vnd.epson.ssf' => ['ssf'], + 'application/vnd.eszigno3+xml' => ['es3', 'et3'], + 'application/vnd.etsi.asic-e+zip' => ['asice'], + 'application/vnd.ezpix-album' => ['ez2'], + 'application/vnd.ezpix-package' => ['ez3'], + 'application/vnd.fdf' => ['fdf'], + 'application/vnd.fdsn.mseed' => ['mseed'], + 'application/vnd.fdsn.seed' => ['seed', 'dataless'], + 'application/vnd.flatpak' => ['flatpak', 'xdgapp'], + 'application/vnd.flatpak.ref' => ['flatpakref'], + 'application/vnd.flatpak.repo' => ['flatpakrepo'], + 'application/vnd.flographit' => ['gph'], + 'application/vnd.fluxtime.clip' => ['ftc'], + 'application/vnd.framemaker' => ['fm', 'frame', 'maker', 'book'], + 'application/vnd.frogans.fnc' => ['fnc'], + 'application/vnd.frogans.ltf' => ['ltf'], + 'application/vnd.fsc.weblaunch' => ['fsc'], + 'application/vnd.fujitsu.oasys' => ['oas'], + 'application/vnd.fujitsu.oasys2' => ['oa2'], + 'application/vnd.fujitsu.oasys3' => ['oa3'], + 'application/vnd.fujitsu.oasysgp' => ['fg5'], + 'application/vnd.fujitsu.oasysprs' => ['bh2'], + 'application/vnd.fujixerox.ddd' => ['ddd'], + 'application/vnd.fujixerox.docuworks' => ['xdw'], + 'application/vnd.fujixerox.docuworks.binder' => ['xbd'], + 'application/vnd.fuzzysheet' => ['fzs'], + 'application/vnd.genomatix.tuxedo' => ['txd'], + 'application/vnd.geo+json' => ['geojson', 'geo.json'], + 'application/vnd.geogebra.file' => ['ggb'], + 'application/vnd.geogebra.tool' => ['ggt'], + 'application/vnd.geometry-explorer' => ['gex', 'gre'], + 'application/vnd.geonext' => ['gxt'], + 'application/vnd.geoplan' => ['g2w'], + 'application/vnd.geospace' => ['g3w'], + 'application/vnd.gmx' => ['gmx'], + 'application/vnd.google-apps.document' => ['gdoc'], + 'application/vnd.google-apps.presentation' => ['gslides'], + 'application/vnd.google-apps.spreadsheet' => ['gsheet'], + 'application/vnd.google-earth.kml+xml' => ['kml'], + 'application/vnd.google-earth.kmz' => ['kmz'], + 'application/vnd.grafeq' => ['gqf', 'gqs'], + 'application/vnd.groove-account' => ['gac'], + 'application/vnd.groove-help' => ['ghf'], + 'application/vnd.groove-identity-message' => ['gim'], + 'application/vnd.groove-injector' => ['grv'], + 'application/vnd.groove-tool-message' => ['gtm'], + 'application/vnd.groove-tool-template' => ['tpl'], + 'application/vnd.groove-vcard' => ['vcg'], + 'application/vnd.haansoft-hwp' => ['hwp'], + 'application/vnd.haansoft-hwt' => ['hwt'], + 'application/vnd.hal+xml' => ['hal'], + 'application/vnd.handheld-entertainment+xml' => ['zmm'], + 'application/vnd.hbci' => ['hbci'], + 'application/vnd.hhe.lesson-player' => ['les'], + 'application/vnd.hp-hpgl' => ['hpgl'], + 'application/vnd.hp-hpid' => ['hpid'], + 'application/vnd.hp-hps' => ['hps'], + 'application/vnd.hp-jlyt' => ['jlt'], + 'application/vnd.hp-pcl' => ['pcl'], + 'application/vnd.hp-pclxl' => ['pclxl'], + 'application/vnd.hydrostatix.sof-data' => ['sfd-hdstx'], + 'application/vnd.ibm.minipay' => ['mpy'], + 'application/vnd.ibm.modcap' => ['afp', 'listafp', 'list3820'], + 'application/vnd.ibm.rights-management' => ['irm'], + 'application/vnd.ibm.secure-container' => ['sc'], + 'application/vnd.iccprofile' => ['icc', 'icm'], + 'application/vnd.igloader' => ['igl'], + 'application/vnd.immervision-ivp' => ['ivp'], + 'application/vnd.immervision-ivu' => ['ivu'], + 'application/vnd.insors.igm' => ['igm'], + 'application/vnd.intercon.formnet' => ['xpw', 'xpx'], + 'application/vnd.intergeo' => ['i2g'], + 'application/vnd.intu.qbo' => ['qbo'], + 'application/vnd.intu.qfx' => ['qfx'], + 'application/vnd.ipunplugged.rcprofile' => ['rcprofile'], + 'application/vnd.irepository.package+xml' => ['irp'], + 'application/vnd.is-xpr' => ['xpr'], + 'application/vnd.isac.fcs' => ['fcs'], + 'application/vnd.jam' => ['jam'], + 'application/vnd.jcp.javame.midlet-rms' => ['rms'], + 'application/vnd.jisp' => ['jisp'], + 'application/vnd.joost.joda-archive' => ['joda'], + 'application/vnd.kahootz' => ['ktz', 'ktr'], + 'application/vnd.kde.karbon' => ['karbon'], + 'application/vnd.kde.kchart' => ['chrt'], + 'application/vnd.kde.kformula' => ['kfo'], + 'application/vnd.kde.kivio' => ['flw'], + 'application/vnd.kde.kontour' => ['kon'], + 'application/vnd.kde.kpresenter' => ['kpr', 'kpt'], + 'application/vnd.kde.kspread' => ['ksp'], + 'application/vnd.kde.kword' => ['kwd', 'kwt'], + 'application/vnd.kenameaapp' => ['htke'], + 'application/vnd.kidspiration' => ['kia'], + 'application/vnd.kinar' => ['kne', 'knp'], + 'application/vnd.koan' => ['skp', 'skd', 'skt', 'skm'], + 'application/vnd.kodak-descriptor' => ['sse'], + 'application/vnd.las.las+xml' => ['lasxml'], + 'application/vnd.llamagraphics.life-balance.desktop' => ['lbd'], + 'application/vnd.llamagraphics.life-balance.exchange+xml' => ['lbe'], + 'application/vnd.lotus-1-2-3' => ['123', 'wk1', 'wk3', 'wk4', 'wks'], + 'application/vnd.lotus-approach' => ['apr'], + 'application/vnd.lotus-freelance' => ['pre'], + 'application/vnd.lotus-notes' => ['nsf'], + 'application/vnd.lotus-organizer' => ['org'], + 'application/vnd.lotus-screencam' => ['scm'], + 'application/vnd.lotus-wordpro' => ['lwp'], + 'application/vnd.macports.portpkg' => ['portpkg'], + 'application/vnd.mapbox-vector-tile' => ['mvt'], + 'application/vnd.mcd' => ['mcd'], + 'application/vnd.medcalcdata' => ['mc1'], + 'application/vnd.mediastation.cdkey' => ['cdkey'], + 'application/vnd.mfer' => ['mwf'], + 'application/vnd.mfmp' => ['mfm'], + 'application/vnd.micrografx.flo' => ['flo'], + 'application/vnd.micrografx.igx' => ['igx'], + 'application/vnd.mif' => ['mif'], + 'application/vnd.mobius.daf' => ['daf'], + 'application/vnd.mobius.dis' => ['dis'], + 'application/vnd.mobius.mbk' => ['mbk'], + 'application/vnd.mobius.mqy' => ['mqy'], + 'application/vnd.mobius.msl' => ['msl'], + 'application/vnd.mobius.plc' => ['plc'], + 'application/vnd.mobius.txf' => ['txf'], + 'application/vnd.mophun.application' => ['mpn'], + 'application/vnd.mophun.certificate' => ['mpc'], + 'application/vnd.mozilla.xul+xml' => ['xul'], + 'application/vnd.ms-access' => ['mdb'], + 'application/vnd.ms-artgalry' => ['cil'], + 'application/vnd.ms-asf' => ['asf'], + 'application/vnd.ms-cab-compressed' => ['cab'], + 'application/vnd.ms-excel' => ['xls', 'xlm', 'xla', 'xlc', 'xlt', 'xlw', 'xll', 'xld'], + 'application/vnd.ms-excel.addin.macroenabled.12' => ['xlam'], + 'application/vnd.ms-excel.sheet.binary.macroenabled.12' => ['xlsb'], + 'application/vnd.ms-excel.sheet.macroenabled.12' => ['xlsm'], + 'application/vnd.ms-excel.template.macroenabled.12' => ['xltm'], + 'application/vnd.ms-fontobject' => ['eot'], + 'application/vnd.ms-htmlhelp' => ['chm'], + 'application/vnd.ms-ims' => ['ims'], + 'application/vnd.ms-lrm' => ['lrm'], + 'application/vnd.ms-officetheme' => ['thmx'], + 'application/vnd.ms-outlook' => ['msg'], + 'application/vnd.ms-pki.seccat' => ['cat'], + 'application/vnd.ms-pki.stl' => ['stl'], + 'application/vnd.ms-powerpoint' => ['ppt', 'pps', 'pot', 'ppz'], + 'application/vnd.ms-powerpoint.addin.macroenabled.12' => ['ppam'], + 'application/vnd.ms-powerpoint.presentation.macroenabled.12' => ['pptm'], + 'application/vnd.ms-powerpoint.slide.macroenabled.12' => ['sldm'], + 'application/vnd.ms-powerpoint.slideshow.macroenabled.12' => ['ppsm'], + 'application/vnd.ms-powerpoint.template.macroenabled.12' => ['potm'], + 'application/vnd.ms-project' => ['mpp', 'mpt'], + 'application/vnd.ms-publisher' => ['pub'], + 'application/vnd.ms-tnef' => ['tnef', 'tnf'], + 'application/vnd.ms-visio.drawing.macroenabled.main+xml' => ['vsdm'], + 'application/vnd.ms-visio.drawing.main+xml' => ['vsdx'], + 'application/vnd.ms-visio.stencil.macroenabled.main+xml' => ['vssm'], + 'application/vnd.ms-visio.stencil.main+xml' => ['vssx'], + 'application/vnd.ms-visio.template.macroenabled.main+xml' => ['vstm'], + 'application/vnd.ms-visio.template.main+xml' => ['vstx'], + 'application/vnd.ms-word' => ['doc'], + 'application/vnd.ms-word.document.macroenabled.12' => ['docm'], + 'application/vnd.ms-word.template.macroenabled.12' => ['dotm'], + 'application/vnd.ms-works' => ['wps', 'wks', 'wcm', 'wdb', 'xlr'], + 'application/vnd.ms-wpl' => ['wpl'], + 'application/vnd.ms-xpsdocument' => ['xps'], + 'application/vnd.msaccess' => ['mdb'], + 'application/vnd.mseq' => ['mseq'], + 'application/vnd.musician' => ['mus'], + 'application/vnd.muvee.style' => ['msty'], + 'application/vnd.mynfc' => ['taglet'], + 'application/vnd.neurolanguage.nlu' => ['nlu'], + 'application/vnd.nintendo.snes.rom' => ['sfc', 'smc'], + 'application/vnd.nitf' => ['ntf', 'nitf'], + 'application/vnd.noblenet-directory' => ['nnd'], + 'application/vnd.noblenet-sealer' => ['nns'], + 'application/vnd.noblenet-web' => ['nnw'], + 'application/vnd.nokia.n-gage.ac+xml' => ['ac'], + 'application/vnd.nokia.n-gage.data' => ['ngdat'], + 'application/vnd.nokia.n-gage.symbian.install' => ['n-gage'], + 'application/vnd.nokia.radio-preset' => ['rpst'], + 'application/vnd.nokia.radio-presets' => ['rpss'], + 'application/vnd.novadigm.edm' => ['edm'], + 'application/vnd.novadigm.edx' => ['edx'], + 'application/vnd.novadigm.ext' => ['ext'], + 'application/vnd.oasis.docbook+xml' => ['dbk', 'docbook'], + 'application/vnd.oasis.opendocument.chart' => ['odc'], + 'application/vnd.oasis.opendocument.chart-template' => ['otc'], + 'application/vnd.oasis.opendocument.database' => ['odb'], + 'application/vnd.oasis.opendocument.formula' => ['odf'], + 'application/vnd.oasis.opendocument.formula-template' => ['odft', 'otf'], + 'application/vnd.oasis.opendocument.graphics' => ['odg'], + 'application/vnd.oasis.opendocument.graphics-flat-xml' => ['fodg'], + 'application/vnd.oasis.opendocument.graphics-template' => ['otg'], + 'application/vnd.oasis.opendocument.image' => ['odi'], + 'application/vnd.oasis.opendocument.image-template' => ['oti'], + 'application/vnd.oasis.opendocument.presentation' => ['odp'], + 'application/vnd.oasis.opendocument.presentation-flat-xml' => ['fodp'], + 'application/vnd.oasis.opendocument.presentation-template' => ['otp'], + 'application/vnd.oasis.opendocument.spreadsheet' => ['ods'], + 'application/vnd.oasis.opendocument.spreadsheet-flat-xml' => ['fods'], + 'application/vnd.oasis.opendocument.spreadsheet-template' => ['ots'], + 'application/vnd.oasis.opendocument.text' => ['odt'], + 'application/vnd.oasis.opendocument.text-flat-xml' => ['fodt'], + 'application/vnd.oasis.opendocument.text-master' => ['odm'], + 'application/vnd.oasis.opendocument.text-template' => ['ott'], + 'application/vnd.oasis.opendocument.text-web' => ['oth'], + 'application/vnd.olpc-sugar' => ['xo'], + 'application/vnd.oma.dd2+xml' => ['dd2'], + 'application/vnd.openblox.game+xml' => ['obgx'], + 'application/vnd.openofficeorg.extension' => ['oxt'], + 'application/vnd.openstreetmap.data+xml' => ['osm'], + 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => ['pptx'], + 'application/vnd.openxmlformats-officedocument.presentationml.slide' => ['sldx'], + 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' => ['ppsx'], + 'application/vnd.openxmlformats-officedocument.presentationml.template' => ['potx'], + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx'], + 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' => ['xltx'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => ['dotx'], + 'application/vnd.osgeo.mapguide.package' => ['mgp'], + 'application/vnd.osgi.dp' => ['dp'], + 'application/vnd.osgi.subsystem' => ['esa'], + 'application/vnd.palm' => ['pdb', 'pqa', 'oprc', 'prc'], + 'application/vnd.pawaafile' => ['paw'], + 'application/vnd.pg.format' => ['str'], + 'application/vnd.pg.osasli' => ['ei6'], + 'application/vnd.picsel' => ['efif'], + 'application/vnd.pmi.widget' => ['wg'], + 'application/vnd.pocketlearn' => ['plf'], + 'application/vnd.powerbuilder6' => ['pbd'], + 'application/vnd.previewsystems.box' => ['box'], + 'application/vnd.proteus.magazine' => ['mgz'], + 'application/vnd.publishare-delta-tree' => ['qps'], + 'application/vnd.pvi.ptid1' => ['ptid'], + 'application/vnd.quark.quarkxpress' => ['qxd', 'qxt', 'qwd', 'qwt', 'qxl', 'qxb'], + 'application/vnd.rar' => ['rar'], + 'application/vnd.realvnc.bed' => ['bed'], + 'application/vnd.recordare.musicxml' => ['mxl'], + 'application/vnd.recordare.musicxml+xml' => ['musicxml'], + 'application/vnd.rig.cryptonote' => ['cryptonote'], + 'application/vnd.rim.cod' => ['cod'], + 'application/vnd.rn-realmedia' => ['rm', 'rmj', 'rmm', 'rms', 'rmx', 'rmvb'], + 'application/vnd.rn-realmedia-vbr' => ['rmvb', 'rm', 'rmj', 'rmm', 'rms', 'rmx'], + 'application/vnd.route66.link66+xml' => ['link66'], + 'application/vnd.sailingtracker.track' => ['st'], + 'application/vnd.sdp' => ['sdp'], + 'application/vnd.seemail' => ['see'], + 'application/vnd.sema' => ['sema'], + 'application/vnd.semd' => ['semd'], + 'application/vnd.semf' => ['semf'], + 'application/vnd.shana.informed.formdata' => ['ifm'], + 'application/vnd.shana.informed.formtemplate' => ['itp'], + 'application/vnd.shana.informed.interchange' => ['iif'], + 'application/vnd.shana.informed.package' => ['ipk'], + 'application/vnd.simtech-mindmapper' => ['twd', 'twds'], + 'application/vnd.smaf' => ['mmf', 'smaf'], + 'application/vnd.smart.teacher' => ['teacher'], + 'application/vnd.snap' => ['snap'], + 'application/vnd.software602.filler.form+xml' => ['fo'], + 'application/vnd.solent.sdkm+xml' => ['sdkm', 'sdkd'], + 'application/vnd.spotfire.dxp' => ['dxp'], + 'application/vnd.spotfire.sfs' => ['sfs'], + 'application/vnd.sqlite3' => ['sqlite3'], + 'application/vnd.squashfs' => ['sqsh'], + 'application/vnd.stardivision.calc' => ['sdc'], + 'application/vnd.stardivision.chart' => ['sds'], + 'application/vnd.stardivision.draw' => ['sda'], + 'application/vnd.stardivision.impress' => ['sdd', 'sdp'], + 'application/vnd.stardivision.mail' => ['smd'], + 'application/vnd.stardivision.math' => ['smf'], + 'application/vnd.stardivision.writer' => ['sdw', 'vor', 'sgl'], + 'application/vnd.stardivision.writer-global' => ['sgl', 'sdw', 'vor'], + 'application/vnd.stepmania.package' => ['smzip'], + 'application/vnd.stepmania.stepchart' => ['sm'], + 'application/vnd.sun.wadl+xml' => ['wadl'], + 'application/vnd.sun.xml.base' => ['odb'], + 'application/vnd.sun.xml.calc' => ['sxc'], + 'application/vnd.sun.xml.calc.template' => ['stc'], + 'application/vnd.sun.xml.draw' => ['sxd'], + 'application/vnd.sun.xml.draw.template' => ['std'], + 'application/vnd.sun.xml.impress' => ['sxi'], + 'application/vnd.sun.xml.impress.template' => ['sti'], + 'application/vnd.sun.xml.math' => ['sxm'], + 'application/vnd.sun.xml.writer' => ['sxw'], + 'application/vnd.sun.xml.writer.global' => ['sxg'], + 'application/vnd.sun.xml.writer.template' => ['stw'], + 'application/vnd.sus-calendar' => ['sus', 'susp'], + 'application/vnd.svd' => ['svd'], + 'application/vnd.symbian.install' => ['sis', 'sisx'], + 'application/vnd.syncml+xml' => ['xsm'], + 'application/vnd.syncml.dm+wbxml' => ['bdm'], + 'application/vnd.syncml.dm+xml' => ['xdm'], + 'application/vnd.syncml.dmddf+xml' => ['ddf'], + 'application/vnd.tao.intent-module-archive' => ['tao'], + 'application/vnd.tcpdump.pcap' => ['pcap', 'cap', 'dmp'], + 'application/vnd.tmobile-livetv' => ['tmo'], + 'application/vnd.trid.tpt' => ['tpt'], + 'application/vnd.triscape.mxs' => ['mxs'], + 'application/vnd.trueapp' => ['tra'], + 'application/vnd.ufdl' => ['ufd', 'ufdl'], + 'application/vnd.uiq.theme' => ['utz'], + 'application/vnd.umajin' => ['umj'], + 'application/vnd.unity' => ['unityweb'], + 'application/vnd.uoml+xml' => ['uoml'], + 'application/vnd.vcx' => ['vcx'], + 'application/vnd.visio' => ['vsd', 'vst', 'vss', 'vsw'], + 'application/vnd.visionary' => ['vis'], + 'application/vnd.vsf' => ['vsf'], + 'application/vnd.wap.wbxml' => ['wbxml'], + 'application/vnd.wap.wmlc' => ['wmlc'], + 'application/vnd.wap.wmlscriptc' => ['wmlsc'], + 'application/vnd.webturbo' => ['wtb'], + 'application/vnd.wolfram.player' => ['nbp'], + 'application/vnd.wordperfect' => ['wpd', 'wp', 'wp4', 'wp5', 'wp6', 'wpp'], + 'application/vnd.wqd' => ['wqd'], + 'application/vnd.wt.stf' => ['stf'], + 'application/vnd.xara' => ['xar'], + 'application/vnd.xdgapp' => ['flatpak', 'xdgapp'], + 'application/vnd.xfdl' => ['xfdl'], + 'application/vnd.yamaha.hv-dic' => ['hvd'], + 'application/vnd.yamaha.hv-script' => ['hvs'], + 'application/vnd.yamaha.hv-voice' => ['hvp'], + 'application/vnd.yamaha.openscoreformat' => ['osf'], + 'application/vnd.yamaha.openscoreformat.osfpvg+xml' => ['osfpvg'], + 'application/vnd.yamaha.smaf-audio' => ['saf'], + 'application/vnd.yamaha.smaf-phrase' => ['spf'], + 'application/vnd.yellowriver-custom-menu' => ['cmp'], + 'application/vnd.youtube.yt' => ['yt'], + 'application/vnd.zul' => ['zir', 'zirz'], + 'application/vnd.zzazz.deck+xml' => ['zaz'], + 'application/voicexml+xml' => ['vxml'], + 'application/wasm' => ['wasm'], + 'application/widget' => ['wgt'], + 'application/winhlp' => ['hlp'], + 'application/wk1' => ['123', 'wk1', 'wk3', 'wk4', 'wks'], + 'application/wmf' => ['wmf'], + 'application/wordperfect' => ['wp', 'wp4', 'wp5', 'wp6', 'wpd', 'wpp'], + 'application/wsdl+xml' => ['wsdl'], + 'application/wspolicy+xml' => ['wspolicy'], + 'application/wwf' => ['wwf'], + 'application/x-123' => ['123', 'wk1', 'wk3', 'wk4', 'wks'], + 'application/x-7z-compressed' => ['7z', '7z.001'], + 'application/x-abiword' => ['abw', 'abw.CRASHED', 'abw.gz', 'zabw'], + 'application/x-ace' => ['ace'], + 'application/x-ace-compressed' => ['ace'], + 'application/x-alz' => ['alz'], + 'application/x-amiga-disk-format' => ['adf'], + 'application/x-amipro' => ['sam'], + 'application/x-annodex' => ['anx'], + 'application/x-aportisdoc' => ['pdb', 'pdc'], + 'application/x-apple-diskimage' => ['dmg'], + 'application/x-apple-systemprofiler+xml' => ['spx'], + 'application/x-appleworks-document' => ['cwk'], + 'application/x-applix-spreadsheet' => ['as'], + 'application/x-applix-word' => ['aw'], + 'application/x-archive' => ['a', 'ar'], + 'application/x-arj' => ['arj'], + 'application/x-asp' => ['asp'], + 'application/x-atari-2600-rom' => ['a26'], + 'application/x-atari-7800-rom' => ['a78'], + 'application/x-atari-lynx-rom' => ['lnx'], + 'application/x-authorware-bin' => ['aab', 'x32', 'u32', 'vox'], + 'application/x-authorware-map' => ['aam'], + 'application/x-authorware-seg' => ['aas'], + 'application/x-awk' => ['awk'], + 'application/x-bcpio' => ['bcpio'], + 'application/x-bdoc' => ['bdoc'], + 'application/x-bittorrent' => ['torrent'], + 'application/x-blender' => ['blender', 'blend', 'BLEND'], + 'application/x-blorb' => ['blb', 'blorb'], + 'application/x-bps-patch' => ['bps'], + 'application/x-bsdiff' => ['bsdiff'], + 'application/x-bz2' => ['bz2'], + 'application/x-bzdvi' => ['dvi.bz2'], + 'application/x-bzip' => ['bz', 'bz2'], + 'application/x-bzip-compressed-tar' => ['tar.bz2', 'tar.bz', 'tbz2', 'tbz', 'tb2'], + 'application/x-bzip2' => ['bz2', 'boz', 'bz'], + 'application/x-bzpdf' => ['pdf.bz2'], + 'application/x-bzpostscript' => ['ps.bz2'], + 'application/x-cb7' => ['cb7'], + 'application/x-cbr' => ['cbr', 'cba', 'cbt', 'cbz', 'cb7'], + 'application/x-cbt' => ['cbt'], + 'application/x-cbz' => ['cbz'], + 'application/x-ccmx' => ['ccmx'], + 'application/x-cd-image' => ['iso', 'iso9660'], + 'application/x-cdlink' => ['vcd'], + 'application/x-cdr' => ['cdr'], + 'application/x-cdrdao-toc' => ['toc'], + 'application/x-cfs-compressed' => ['cfs'], + 'application/x-chat' => ['chat'], + 'application/x-chess-pgn' => ['pgn'], + 'application/x-chm' => ['chm'], + 'application/x-chrome-extension' => ['crx'], + 'application/x-cisco-vpn-settings' => ['pcf'], + 'application/x-cocoa' => ['cco'], + 'application/x-compress' => ['Z'], + 'application/x-compressed-iso' => ['cso'], + 'application/x-compressed-tar' => ['tar.gz', 'tgz'], + 'application/x-conference' => ['nsc'], + 'application/x-coreldraw' => ['cdr'], + 'application/x-cpio' => ['cpio'], + 'application/x-cpio-compressed' => ['cpio.gz'], + 'application/x-csh' => ['csh'], + 'application/x-cue' => ['cue'], + 'application/x-dar' => ['dar'], + 'application/x-dbase' => ['dbf'], + 'application/x-dbf' => ['dbf'], + 'application/x-dc-rom' => ['dc'], + 'application/x-deb' => ['deb', 'udeb'], + 'application/x-debian-package' => ['deb', 'udeb'], + 'application/x-designer' => ['ui'], + 'application/x-desktop' => ['desktop', 'kdelnk'], + 'application/x-dgc-compressed' => ['dgc'], + 'application/x-dia-diagram' => ['dia'], + 'application/x-dia-shape' => ['shape'], + 'application/x-director' => ['dir', 'dcr', 'dxr', 'cst', 'cct', 'cxt', 'w3d', 'fgd', 'swa'], + 'application/x-discjuggler-cd-image' => ['cdi'], + 'application/x-docbook+xml' => ['dbk', 'docbook'], + 'application/x-doom' => ['wad'], + 'application/x-doom-wad' => ['wad'], + 'application/x-dreamcast-rom' => ['iso'], + 'application/x-dtbncx+xml' => ['ncx'], + 'application/x-dtbook+xml' => ['dtb'], + 'application/x-dtbresource+xml' => ['res'], + 'application/x-dvi' => ['dvi'], + 'application/x-e-theme' => ['etheme'], + 'application/x-egon' => ['egon'], + 'application/x-emf' => ['emf'], + 'application/x-envoy' => ['evy'], + 'application/x-eva' => ['eva'], + 'application/x-fd-file' => ['fd', 'qd'], + 'application/x-fds-disk' => ['fds'], + 'application/x-fictionbook' => ['fb2'], + 'application/x-fictionbook+xml' => ['fb2'], + 'application/x-flash-video' => ['flv'], + 'application/x-fluid' => ['fl'], + 'application/x-font-afm' => ['afm'], + 'application/x-font-bdf' => ['bdf'], + 'application/x-font-ghostscript' => ['gsf'], + 'application/x-font-linux-psf' => ['psf'], + 'application/x-font-otf' => ['otf'], + 'application/x-font-pcf' => ['pcf', 'pcf.Z', 'pcf.gz'], + 'application/x-font-snf' => ['snf'], + 'application/x-font-speedo' => ['spd'], + 'application/x-font-truetype' => ['ttf'], + 'application/x-font-ttf' => ['ttf'], + 'application/x-font-ttx' => ['ttx'], + 'application/x-font-type1' => ['pfa', 'pfb', 'pfm', 'afm', 'gsf'], + 'application/x-font-woff' => ['woff'], + 'application/x-frame' => ['fm'], + 'application/x-freearc' => ['arc'], + 'application/x-futuresplash' => ['spl'], + 'application/x-gameboy-color-rom' => ['gbc', 'cgb'], + 'application/x-gameboy-rom' => ['gb', 'sgb'], + 'application/x-gamecube-iso-image' => ['iso'], + 'application/x-gamecube-rom' => ['iso'], + 'application/x-gamegear-rom' => ['gg'], + 'application/x-gba-rom' => ['gba', 'agb'], + 'application/x-gca-compressed' => ['gca'], + 'application/x-gd-rom-cue' => ['gdi'], + 'application/x-gedcom' => ['ged', 'gedcom'], + 'application/x-genesis-32x-rom' => ['32x', 'mdx'], + 'application/x-genesis-rom' => ['gen', 'smd', 'sgd'], + 'application/x-gettext' => ['po'], + 'application/x-gettext-translation' => ['gmo', 'mo'], + 'application/x-glade' => ['glade'], + 'application/x-glulx' => ['ulx'], + 'application/x-gnome-app-info' => ['desktop', 'kdelnk'], + 'application/x-gnucash' => ['gnucash', 'gnc', 'xac'], + 'application/x-gnumeric' => ['gnumeric'], + 'application/x-gnuplot' => ['gp', 'gplt', 'gnuplot'], + 'application/x-go-sgf' => ['sgf'], + 'application/x-gpx' => ['gpx'], + 'application/x-gpx+xml' => ['gpx'], + 'application/x-gramps-xml' => ['gramps'], + 'application/x-graphite' => ['gra'], + 'application/x-gtar' => ['gtar', 'tar', 'gem'], + 'application/x-gtk-builder' => ['ui'], + 'application/x-gz-font-linux-psf' => ['psf.gz'], + 'application/x-gzdvi' => ['dvi.gz'], + 'application/x-gzip' => ['gz'], + 'application/x-gzpdf' => ['pdf.gz'], + 'application/x-gzpostscript' => ['ps.gz'], + 'application/x-hdf' => ['hdf', 'hdf4', 'h4', 'hdf5', 'h5'], + 'application/x-hfe-file' => ['hfe'], + 'application/x-hfe-floppy-image' => ['hfe'], + 'application/x-httpd-php' => ['php'], + 'application/x-hwp' => ['hwp'], + 'application/x-hwt' => ['hwt'], + 'application/x-ica' => ['ica'], + 'application/x-install-instructions' => ['install'], + 'application/x-ips-patch' => ['ips'], + 'application/x-ipynb+json' => ['ipynb'], + 'application/x-iso9660-appimage' => ['appimage'], + 'application/x-iso9660-image' => ['iso', 'iso9660'], + 'application/x-it87' => ['it87'], + 'application/x-iwork-keynote-sffkey' => ['key'], + 'application/x-iwork-numbers-sffnumbers' => ['numbers'], + 'application/x-iwork-pages-sffpages' => ['pages'], + 'application/x-jar' => ['jar'], + 'application/x-java' => ['class'], + 'application/x-java-archive' => ['jar'], + 'application/x-java-archive-diff' => ['jardiff'], + 'application/x-java-class' => ['class'], + 'application/x-java-jce-keystore' => ['jceks'], + 'application/x-java-jnlp-file' => ['jnlp'], + 'application/x-java-keystore' => ['jks', 'ks'], + 'application/x-java-pack200' => ['pack'], + 'application/x-java-vm' => ['class'], + 'application/x-javascript' => ['js', 'jsm', 'mjs'], + 'application/x-jbuilder-project' => ['jpr', 'jpx'], + 'application/x-karbon' => ['karbon'], + 'application/x-kchart' => ['chrt'], + 'application/x-keepass2' => ['kdbx'], + 'application/x-kexi-connectiondata' => ['kexic'], + 'application/x-kexiproject-shortcut' => ['kexis'], + 'application/x-kexiproject-sqlite' => ['kexi'], + 'application/x-kexiproject-sqlite2' => ['kexi'], + 'application/x-kexiproject-sqlite3' => ['kexi'], + 'application/x-kformula' => ['kfo'], + 'application/x-killustrator' => ['kil'], + 'application/x-kivio' => ['flw'], + 'application/x-kontour' => ['kon'], + 'application/x-kpovmodeler' => ['kpm'], + 'application/x-kpresenter' => ['kpr', 'kpt'], + 'application/x-krita' => ['kra', 'krz'], + 'application/x-kspread' => ['ksp'], + 'application/x-kugar' => ['kud'], + 'application/x-kword' => ['kwd', 'kwt'], + 'application/x-latex' => ['latex'], + 'application/x-lha' => ['lha', 'lzh'], + 'application/x-lhz' => ['lhz'], + 'application/x-linguist' => ['ts'], + 'application/x-lotus123' => ['123', 'wk1', 'wk3', 'wk4', 'wks'], + 'application/x-lrzip' => ['lrz'], + 'application/x-lrzip-compressed-tar' => ['tar.lrz', 'tlrz'], + 'application/x-lua-bytecode' => ['luac'], + 'application/x-lyx' => ['lyx'], + 'application/x-lz4' => ['lz4'], + 'application/x-lz4-compressed-tar' => ['tar.lz4'], + 'application/x-lzh-compressed' => ['lzh', 'lha'], + 'application/x-lzip' => ['lz'], + 'application/x-lzip-compressed-tar' => ['tar.lz'], + 'application/x-lzma' => ['lzma'], + 'application/x-lzma-compressed-tar' => ['tar.lzma', 'tlz'], + 'application/x-lzop' => ['lzo'], + 'application/x-lzpdf' => ['pdf.lz'], + 'application/x-m4' => ['m4'], + 'application/x-magicpoint' => ['mgp'], + 'application/x-makeself' => ['run'], + 'application/x-mame-chd' => ['chd'], + 'application/x-markaby' => ['mab'], + 'application/x-mathematica' => ['nb'], + 'application/x-mdb' => ['mdb'], + 'application/x-mie' => ['mie'], + 'application/x-mif' => ['mif'], + 'application/x-mimearchive' => ['mhtml', 'mht'], + 'application/x-mobi8-ebook' => ['azw3', 'kfx'], + 'application/x-mobipocket-ebook' => ['prc', 'mobi'], + 'application/x-ms-application' => ['application'], + 'application/x-ms-asx' => ['asx', 'wax', 'wvx', 'wmx'], + 'application/x-ms-dos-executable' => ['exe'], + 'application/x-ms-shortcut' => ['lnk'], + 'application/x-ms-wim' => ['wim', 'swm'], + 'application/x-ms-wmd' => ['wmd'], + 'application/x-ms-wmz' => ['wmz'], + 'application/x-ms-xbap' => ['xbap'], + 'application/x-msaccess' => ['mdb'], + 'application/x-msbinder' => ['obd'], + 'application/x-mscardfile' => ['crd'], + 'application/x-msclip' => ['clp'], + 'application/x-msdos-program' => ['exe'], + 'application/x-msdownload' => ['exe', 'dll', 'com', 'bat', 'msi'], + 'application/x-msexcel' => ['xls', 'xlc', 'xll', 'xlm', 'xlw', 'xla', 'xlt', 'xld'], + 'application/x-msi' => ['msi'], + 'application/x-msmediaview' => ['mvb', 'm13', 'm14'], + 'application/x-msmetafile' => ['wmf', 'wmz', 'emf', 'emz'], + 'application/x-msmoney' => ['mny'], + 'application/x-mspowerpoint' => ['ppz', 'ppt', 'pps', 'pot'], + 'application/x-mspublisher' => ['pub'], + 'application/x-msschedule' => ['scd'], + 'application/x-msterminal' => ['trm'], + 'application/x-mswinurl' => ['url'], + 'application/x-msword' => ['doc'], + 'application/x-mswrite' => ['wri'], + 'application/x-msx-rom' => ['msx'], + 'application/x-n64-rom' => ['n64', 'z64', 'v64'], + 'application/x-navi-animation' => ['ani'], + 'application/x-neo-geo-pocket-color-rom' => ['ngc'], + 'application/x-neo-geo-pocket-rom' => ['ngp'], + 'application/x-nes-rom' => ['nes', 'nez', 'unf', 'unif'], + 'application/x-netcdf' => ['nc', 'cdf'], + 'application/x-netshow-channel' => ['nsc'], + 'application/x-nintendo-3ds-executable' => ['3dsx'], + 'application/x-nintendo-3ds-rom' => ['3ds', 'cci'], + 'application/x-nintendo-ds-rom' => ['nds'], + 'application/x-ns-proxy-autoconfig' => ['pac'], + 'application/x-nzb' => ['nzb'], + 'application/x-object' => ['o', 'mod'], + 'application/x-ogg' => ['ogx'], + 'application/x-oleo' => ['oleo'], + 'application/x-pagemaker' => ['p65', 'pm', 'pm6', 'pmd'], + 'application/x-pak' => ['pak'], + 'application/x-palm-database' => ['prc', 'pdb', 'pqa', 'oprc'], + 'application/x-par2' => ['PAR2', 'par2'], + 'application/x-partial-download' => ['wkdownload', 'crdownload', 'part'], + 'application/x-pc-engine-rom' => ['pce'], + 'application/x-pcap' => ['pcap', 'cap', 'dmp'], + 'application/x-pdf' => ['pdf'], + 'application/x-perl' => ['pl', 'pm', 'PL', 'al', 'perl', 'pod', 't'], + 'application/x-photoshop' => ['psd'], + 'application/x-php' => ['php', 'php3', 'php4', 'php5', 'phps'], + 'application/x-pilot' => ['prc', 'pdb'], + 'application/x-pkcs12' => ['p12', 'pfx'], + 'application/x-pkcs7-certificates' => ['p7b', 'spc'], + 'application/x-pkcs7-certreqresp' => ['p7r'], + 'application/x-planperfect' => ['pln'], + 'application/x-pocket-word' => ['psw'], + 'application/x-pw' => ['pw'], + 'application/x-pyspread-bz-spreadsheet' => ['pys'], + 'application/x-pyspread-spreadsheet' => ['pysu'], + 'application/x-python-bytecode' => ['pyc', 'pyo'], + 'application/x-qed-disk' => ['qed'], + 'application/x-qemu-disk' => ['qcow2', 'qcow'], + 'application/x-qpress' => ['qp'], + 'application/x-qtiplot' => ['qti', 'qti.gz'], + 'application/x-quattropro' => ['wb1', 'wb2', 'wb3'], + 'application/x-quicktime-media-link' => ['qtl'], + 'application/x-quicktimeplayer' => ['qtl'], + 'application/x-qw' => ['qif'], + 'application/x-rar' => ['rar'], + 'application/x-rar-compressed' => ['rar'], + 'application/x-raw-disk-image' => ['raw-disk-image', 'img'], + 'application/x-raw-disk-image-xz-compressed' => ['raw-disk-image.xz', 'img.xz'], + 'application/x-raw-floppy-disk-image' => ['fd', 'qd'], + 'application/x-redhat-package-manager' => ['rpm'], + 'application/x-reject' => ['rej'], + 'application/x-research-info-systems' => ['ris'], + 'application/x-rnc' => ['rnc'], + 'application/x-rpm' => ['rpm'], + 'application/x-ruby' => ['rb'], + 'application/x-sami' => ['smi', 'sami'], + 'application/x-sap-file' => ['sap'], + 'application/x-saturn-rom' => ['iso'], + 'application/x-sdp' => ['sdp'], + 'application/x-sea' => ['sea'], + 'application/x-sega-cd-rom' => ['iso'], + 'application/x-sega-pico-rom' => ['iso'], + 'application/x-sg1000-rom' => ['sg'], + 'application/x-sh' => ['sh'], + 'application/x-shar' => ['shar'], + 'application/x-shared-library-la' => ['la'], + 'application/x-sharedlib' => ['so'], + 'application/x-shellscript' => ['sh'], + 'application/x-shockwave-flash' => ['swf', 'spl'], + 'application/x-shorten' => ['shn'], + 'application/x-siag' => ['siag'], + 'application/x-silverlight-app' => ['xap'], + 'application/x-sit' => ['sit'], + 'application/x-smaf' => ['mmf', 'smaf'], + 'application/x-sms-rom' => ['sms'], + 'application/x-snes-rom' => ['sfc', 'smc'], + 'application/x-source-rpm' => ['src.rpm', 'spm'], + 'application/x-spss-por' => ['por'], + 'application/x-spss-sav' => ['sav', 'zsav'], + 'application/x-spss-savefile' => ['sav', 'zsav'], + 'application/x-sql' => ['sql'], + 'application/x-sqlite2' => ['sqlite2'], + 'application/x-sqlite3' => ['sqlite3'], + 'application/x-srt' => ['srt'], + 'application/x-stuffit' => ['sit'], + 'application/x-stuffitx' => ['sitx'], + 'application/x-subrip' => ['srt'], + 'application/x-sv4cpio' => ['sv4cpio'], + 'application/x-sv4crc' => ['sv4crc'], + 'application/x-t3vm-image' => ['t3'], + 'application/x-t602' => ['602'], + 'application/x-tads' => ['gam'], + 'application/x-tar' => ['tar', 'gtar', 'gem'], + 'application/x-targa' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'application/x-tarz' => ['tar.Z', 'taz'], + 'application/x-tcl' => ['tcl', 'tk'], + 'application/x-tex' => ['tex', 'ltx', 'sty', 'cls', 'dtx', 'ins', 'latex'], + 'application/x-tex-gf' => ['gf'], + 'application/x-tex-pk' => ['pk'], + 'application/x-tex-tfm' => ['tfm'], + 'application/x-texinfo' => ['texinfo', 'texi'], + 'application/x-tga' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'application/x-tgif' => ['obj'], + 'application/x-theme' => ['theme'], + 'application/x-thomson-cartridge-memo7' => ['m7'], + 'application/x-thomson-cassette' => ['k7'], + 'application/x-thomson-sap-image' => ['sap'], + 'application/x-trash' => ['bak', 'old', 'sik'], + 'application/x-trig' => ['trig'], + 'application/x-troff' => ['tr', 'roff', 't'], + 'application/x-troff-man' => ['man'], + 'application/x-tzo' => ['tar.lzo', 'tzo'], + 'application/x-ufraw' => ['ufraw'], + 'application/x-ustar' => ['ustar'], + 'application/x-vdi-disk' => ['vdi'], + 'application/x-vhd-disk' => ['vhd', 'vpc'], + 'application/x-vhdx-disk' => ['vhdx'], + 'application/x-virtual-boy-rom' => ['vb'], + 'application/x-virtualbox-hdd' => ['hdd'], + 'application/x-virtualbox-ova' => ['ova'], + 'application/x-virtualbox-ovf' => ['ovf'], + 'application/x-virtualbox-vbox' => ['vbox'], + 'application/x-virtualbox-vbox-extpack' => ['vbox-extpack'], + 'application/x-virtualbox-vdi' => ['vdi'], + 'application/x-virtualbox-vhd' => ['vhd', 'vpc'], + 'application/x-virtualbox-vhdx' => ['vhdx'], + 'application/x-virtualbox-vmdk' => ['vmdk'], + 'application/x-vmdk-disk' => ['vmdk'], + 'application/x-vnd.kde.kexi' => ['kexi'], + 'application/x-wais-source' => ['src'], + 'application/x-wbfs' => ['iso'], + 'application/x-web-app-manifest+json' => ['webapp'], + 'application/x-wia' => ['iso'], + 'application/x-wii-iso-image' => ['iso'], + 'application/x-wii-rom' => ['iso'], + 'application/x-wii-wad' => ['wad'], + 'application/x-windows-themepack' => ['themepack'], + 'application/x-wmf' => ['wmf'], + 'application/x-wonderswan-color-rom' => ['wsc'], + 'application/x-wonderswan-rom' => ['ws'], + 'application/x-wordperfect' => ['wp', 'wp4', 'wp5', 'wp6', 'wpd', 'wpp'], + 'application/x-wpg' => ['wpg'], + 'application/x-wwf' => ['wwf'], + 'application/x-x509-ca-cert' => ['der', 'crt', 'pem', 'cert'], + 'application/x-xar' => ['xar', 'pkg'], + 'application/x-xbel' => ['xbel'], + 'application/x-xfig' => ['fig'], + 'application/x-xliff' => ['xlf', 'xliff'], + 'application/x-xliff+xml' => ['xlf'], + 'application/x-xpinstall' => ['xpi'], + 'application/x-xspf+xml' => ['xspf'], + 'application/x-xz' => ['xz'], + 'application/x-xz-compressed-tar' => ['tar.xz', 'txz'], + 'application/x-xzpdf' => ['pdf.xz'], + 'application/x-yaml' => ['yaml', 'yml'], + 'application/x-zip' => ['zip'], + 'application/x-zip-compressed' => ['zip'], + 'application/x-zip-compressed-fb2' => ['fb2.zip'], + 'application/x-zmachine' => ['z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7', 'z8'], + 'application/x-zoo' => ['zoo'], + 'application/x-zstd-compressed-tar' => ['tar.zst', 'tzst'], + 'application/xaml+xml' => ['xaml'], + 'application/xcap-att+xml' => ['xav'], + 'application/xcap-caps+xml' => ['xca'], + 'application/xcap-diff+xml' => ['xdf'], + 'application/xcap-el+xml' => ['xel'], + 'application/xcap-error+xml' => ['xer'], + 'application/xcap-ns+xml' => ['xns'], + 'application/xenc+xml' => ['xenc'], + 'application/xhtml+xml' => ['xhtml', 'xht', 'html', 'htm'], + 'application/xliff+xml' => ['xlf', 'xliff'], + 'application/xml' => ['xml', 'xsl', 'xsd', 'rng', 'xbl'], + 'application/xml-dtd' => ['dtd'], + 'application/xml-external-parsed-entity' => ['ent'], + 'application/xop+xml' => ['xop'], + 'application/xproc+xml' => ['xpl'], + 'application/xps' => ['xps'], + 'application/xslt+xml' => ['xsl', 'xslt'], + 'application/xspf+xml' => ['xspf'], + 'application/xv+xml' => ['mxml', 'xhvml', 'xvml', 'xvm'], + 'application/yang' => ['yang'], + 'application/yin+xml' => ['yin'], + 'application/zip' => ['zip'], + 'application/zlib' => ['zz'], + 'application/zstd' => ['zst'], + 'audio/3gpp' => ['3gpp', '3gp', '3ga'], + 'audio/3gpp-encrypted' => ['3gp', '3gpp', '3ga'], + 'audio/3gpp2' => ['3g2', '3gp2', '3gpp2'], + 'audio/aac' => ['aac', 'adts', 'ass'], + 'audio/ac3' => ['ac3'], + 'audio/adpcm' => ['adp'], + 'audio/amr' => ['amr'], + 'audio/amr-encrypted' => ['amr'], + 'audio/amr-wb' => ['awb'], + 'audio/amr-wb-encrypted' => ['awb'], + 'audio/annodex' => ['axa'], + 'audio/basic' => ['au', 'snd'], + 'audio/flac' => ['flac'], + 'audio/imelody' => ['imy', 'ime'], + 'audio/m3u' => ['m3u', 'm3u8', 'vlc'], + 'audio/m4a' => ['m4a', 'f4a'], + 'audio/midi' => ['mid', 'midi', 'kar', 'rmi'], + 'audio/mobile-xmf' => ['mxmf', 'xmf'], + 'audio/mp2' => ['mp2'], + 'audio/mp3' => ['mp3', 'mpga'], + 'audio/mp4' => ['m4a', 'mp4a', 'f4a'], + 'audio/mpeg' => ['mp3', 'mpga', 'mp2', 'mp2a', 'm2a', 'm3a'], + 'audio/mpegurl' => ['m3u', 'm3u8', 'vlc'], + 'audio/ogg' => ['ogg', 'oga', 'spx', 'opus'], + 'audio/prs.sid' => ['sid', 'psid'], + 'audio/s3m' => ['s3m'], + 'audio/scpls' => ['pls'], + 'audio/silk' => ['sil'], + 'audio/tta' => ['tta'], + 'audio/usac' => ['loas', 'xhe'], + 'audio/vnd.audible' => ['aa', 'aax'], + 'audio/vnd.audible.aax' => ['aax'], + 'audio/vnd.dece.audio' => ['uva', 'uvva'], + 'audio/vnd.digital-winds' => ['eol'], + 'audio/vnd.dra' => ['dra'], + 'audio/vnd.dts' => ['dts'], + 'audio/vnd.dts.hd' => ['dtshd'], + 'audio/vnd.lucent.voice' => ['lvp'], + 'audio/vnd.m-realaudio' => ['ra', 'rax'], + 'audio/vnd.ms-playready.media.pya' => ['pya'], + 'audio/vnd.nuera.ecelp4800' => ['ecelp4800'], + 'audio/vnd.nuera.ecelp7470' => ['ecelp7470'], + 'audio/vnd.nuera.ecelp9600' => ['ecelp9600'], + 'audio/vnd.rip' => ['rip'], + 'audio/vnd.rn-realaudio' => ['ra', 'rax'], + 'audio/vnd.wave' => ['wav'], + 'audio/vorbis' => ['oga', 'ogg'], + 'audio/wav' => ['wav'], + 'audio/wave' => ['wav'], + 'audio/webm' => ['weba'], + 'audio/wma' => ['wma'], + 'audio/x-aac' => ['aac', 'adts', 'ass'], + 'audio/x-aifc' => ['aifc', 'aiffc'], + 'audio/x-aiff' => ['aif', 'aiff', 'aifc'], + 'audio/x-aiffc' => ['aifc', 'aiffc'], + 'audio/x-amzxml' => ['amz'], + 'audio/x-annodex' => ['axa'], + 'audio/x-ape' => ['ape'], + 'audio/x-caf' => ['caf'], + 'audio/x-dts' => ['dts'], + 'audio/x-dtshd' => ['dtshd'], + 'audio/x-flac' => ['flac'], + 'audio/x-flac+ogg' => ['oga', 'ogg'], + 'audio/x-gsm' => ['gsm'], + 'audio/x-hx-aac-adts' => ['aac', 'adts', 'ass'], + 'audio/x-imelody' => ['imy', 'ime'], + 'audio/x-iriver-pla' => ['pla'], + 'audio/x-it' => ['it'], + 'audio/x-m3u' => ['m3u', 'm3u8', 'vlc'], + 'audio/x-m4a' => ['m4a', 'f4a'], + 'audio/x-m4b' => ['m4b', 'f4b'], + 'audio/x-m4r' => ['m4r'], + 'audio/x-matroska' => ['mka'], + 'audio/x-midi' => ['mid', 'midi', 'kar'], + 'audio/x-minipsf' => ['minipsf'], + 'audio/x-mo3' => ['mo3'], + 'audio/x-mod' => ['mod', 'ult', 'uni', 'm15', 'mtm', '669', 'med'], + 'audio/x-mp2' => ['mp2'], + 'audio/x-mp3' => ['mp3', 'mpga'], + 'audio/x-mp3-playlist' => ['m3u', 'm3u8', 'vlc'], + 'audio/x-mpeg' => ['mp3', 'mpga'], + 'audio/x-mpegurl' => ['m3u', 'm3u8', 'vlc'], + 'audio/x-mpg' => ['mp3', 'mpga'], + 'audio/x-ms-asx' => ['asx', 'wax', 'wvx', 'wmx'], + 'audio/x-ms-wax' => ['wax'], + 'audio/x-ms-wma' => ['wma'], + 'audio/x-ms-wmv' => ['wmv'], + 'audio/x-musepack' => ['mpc', 'mpp', 'mp+'], + 'audio/x-ogg' => ['oga', 'ogg', 'opus'], + 'audio/x-oggflac' => ['oga', 'ogg'], + 'audio/x-opus+ogg' => ['opus'], + 'audio/x-pn-audibleaudio' => ['aa', 'aax'], + 'audio/x-pn-realaudio' => ['ram', 'ra', 'rax'], + 'audio/x-pn-realaudio-plugin' => ['rmp'], + 'audio/x-psf' => ['psf'], + 'audio/x-psflib' => ['psflib'], + 'audio/x-realaudio' => ['ra'], + 'audio/x-rn-3gpp-amr' => ['3gp', '3gpp', '3ga'], + 'audio/x-rn-3gpp-amr-encrypted' => ['3gp', '3gpp', '3ga'], + 'audio/x-rn-3gpp-amr-wb' => ['3gp', '3gpp', '3ga'], + 'audio/x-rn-3gpp-amr-wb-encrypted' => ['3gp', '3gpp', '3ga'], + 'audio/x-s3m' => ['s3m'], + 'audio/x-scpls' => ['pls'], + 'audio/x-shorten' => ['shn'], + 'audio/x-speex' => ['spx'], + 'audio/x-speex+ogg' => ['oga', 'ogg', 'spx'], + 'audio/x-stm' => ['stm'], + 'audio/x-tta' => ['tta'], + 'audio/x-voc' => ['voc'], + 'audio/x-vorbis' => ['oga', 'ogg'], + 'audio/x-vorbis+ogg' => ['oga', 'ogg'], + 'audio/x-wav' => ['wav'], + 'audio/x-wavpack' => ['wv', 'wvp'], + 'audio/x-wavpack-correction' => ['wvc'], + 'audio/x-xi' => ['xi'], + 'audio/x-xm' => ['xm'], + 'audio/x-xmf' => ['xmf'], + 'audio/xm' => ['xm'], + 'audio/xmf' => ['xmf'], + 'chemical/x-cdx' => ['cdx'], + 'chemical/x-cif' => ['cif'], + 'chemical/x-cmdf' => ['cmdf'], + 'chemical/x-cml' => ['cml'], + 'chemical/x-csml' => ['csml'], + 'chemical/x-xyz' => ['xyz'], + 'flv-application/octet-stream' => ['flv'], + 'font/collection' => ['ttc'], + 'font/otf' => ['otf'], + 'font/ttf' => ['ttf'], + 'font/woff' => ['woff'], + 'font/woff2' => ['woff2'], + 'image/aces' => ['exr'], + 'image/apng' => ['apng'], + 'image/astc' => ['astc'], + 'image/avif' => ['avif', 'avifs'], + 'image/avif-sequence' => ['avif', 'avifs'], + 'image/bmp' => ['bmp', 'dib'], + 'image/cdr' => ['cdr'], + 'image/cgm' => ['cgm'], + 'image/dicom-rle' => ['drle'], + 'image/emf' => ['emf'], + 'image/fax-g3' => ['g3'], + 'image/fits' => ['fits'], + 'image/g3fax' => ['g3'], + 'image/gif' => ['gif'], + 'image/heic' => ['heic', 'heif'], + 'image/heic-sequence' => ['heics', 'heic', 'heif'], + 'image/heif' => ['heif', 'heic'], + 'image/heif-sequence' => ['heifs', 'heic', 'heif'], + 'image/hej2k' => ['hej2'], + 'image/hsj2' => ['hsj2'], + 'image/ico' => ['ico'], + 'image/icon' => ['ico'], + 'image/ief' => ['ief'], + 'image/jls' => ['jls'], + 'image/jp2' => ['jp2', 'jpg2'], + 'image/jpeg' => ['jpg', 'jpeg', 'jpe'], + 'image/jpeg2000' => ['jp2', 'jpg2'], + 'image/jpeg2000-image' => ['jp2', 'jpg2'], + 'image/jph' => ['jph'], + 'image/jphc' => ['jhc'], + 'image/jpm' => ['jpm', 'jpgm'], + 'image/jpx' => ['jpx', 'jpf'], + 'image/jxl' => ['jxl'], + 'image/jxr' => ['jxr'], + 'image/jxra' => ['jxra'], + 'image/jxrs' => ['jxrs'], + 'image/jxs' => ['jxs'], + 'image/jxsc' => ['jxsc'], + 'image/jxsi' => ['jxsi'], + 'image/jxss' => ['jxss'], + 'image/ktx' => ['ktx'], + 'image/ktx2' => ['ktx2'], + 'image/openraster' => ['ora'], + 'image/pdf' => ['pdf'], + 'image/photoshop' => ['psd'], + 'image/pjpeg' => ['jpg', 'jpeg', 'jpe'], + 'image/png' => ['png'], + 'image/prs.btif' => ['btif'], + 'image/prs.pti' => ['pti'], + 'image/psd' => ['psd'], + 'image/rle' => ['rle'], + 'image/sgi' => ['sgi'], + 'image/svg' => ['svg'], + 'image/svg+xml' => ['svg', 'svgz'], + 'image/svg+xml-compressed' => ['svgz'], + 'image/t38' => ['t38'], + 'image/targa' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'image/tga' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'image/tiff' => ['tif', 'tiff'], + 'image/tiff-fx' => ['tfx'], + 'image/vnd.adobe.photoshop' => ['psd'], + 'image/vnd.airzip.accelerator.azv' => ['azv'], + 'image/vnd.dece.graphic' => ['uvi', 'uvvi', 'uvg', 'uvvg'], + 'image/vnd.djvu' => ['djvu', 'djv'], + 'image/vnd.djvu+multipage' => ['djvu', 'djv'], + 'image/vnd.dvb.subtitle' => ['sub'], + 'image/vnd.dwg' => ['dwg'], + 'image/vnd.dxf' => ['dxf'], + 'image/vnd.fastbidsheet' => ['fbs'], + 'image/vnd.fpx' => ['fpx'], + 'image/vnd.fst' => ['fst'], + 'image/vnd.fujixerox.edmics-mmr' => ['mmr'], + 'image/vnd.fujixerox.edmics-rlc' => ['rlc'], + 'image/vnd.microsoft.icon' => ['ico'], + 'image/vnd.ms-dds' => ['dds'], + 'image/vnd.ms-modi' => ['mdi'], + 'image/vnd.ms-photo' => ['wdp'], + 'image/vnd.net-fpx' => ['npx'], + 'image/vnd.pco.b16' => ['b16'], + 'image/vnd.rn-realpix' => ['rp'], + 'image/vnd.tencent.tap' => ['tap'], + 'image/vnd.valve.source.texture' => ['vtf'], + 'image/vnd.wap.wbmp' => ['wbmp'], + 'image/vnd.xiff' => ['xif'], + 'image/vnd.zbrush.pcx' => ['pcx'], + 'image/webp' => ['webp'], + 'image/wmf' => ['wmf'], + 'image/x-3ds' => ['3ds'], + 'image/x-adobe-dng' => ['dng'], + 'image/x-applix-graphics' => ['ag'], + 'image/x-bmp' => ['bmp', 'dib'], + 'image/x-bzeps' => ['eps.bz2', 'epsi.bz2', 'epsf.bz2'], + 'image/x-canon-cr2' => ['cr2'], + 'image/x-canon-cr3' => ['cr3'], + 'image/x-canon-crw' => ['crw'], + 'image/x-cdr' => ['cdr'], + 'image/x-cmu-raster' => ['ras'], + 'image/x-cmx' => ['cmx'], + 'image/x-compressed-xcf' => ['xcf.gz', 'xcf.bz2'], + 'image/x-dds' => ['dds'], + 'image/x-djvu' => ['djvu', 'djv'], + 'image/x-emf' => ['emf'], + 'image/x-eps' => ['eps', 'epsi', 'epsf'], + 'image/x-exr' => ['exr'], + 'image/x-fits' => ['fits'], + 'image/x-freehand' => ['fh', 'fhc', 'fh4', 'fh5', 'fh7'], + 'image/x-fuji-raf' => ['raf'], + 'image/x-gimp-gbr' => ['gbr'], + 'image/x-gimp-gih' => ['gih'], + 'image/x-gimp-pat' => ['pat'], + 'image/x-gzeps' => ['eps.gz', 'epsi.gz', 'epsf.gz'], + 'image/x-icb' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'image/x-icns' => ['icns'], + 'image/x-ico' => ['ico'], + 'image/x-icon' => ['ico'], + 'image/x-iff' => ['iff', 'ilbm', 'lbm'], + 'image/x-ilbm' => ['iff', 'ilbm', 'lbm'], + 'image/x-jng' => ['jng'], + 'image/x-jp2-codestream' => ['j2c', 'j2k', 'jpc'], + 'image/x-jpeg2000-image' => ['jp2', 'jpg2'], + 'image/x-kodak-dcr' => ['dcr'], + 'image/x-kodak-k25' => ['k25'], + 'image/x-kodak-kdc' => ['kdc'], + 'image/x-lwo' => ['lwo', 'lwob'], + 'image/x-lws' => ['lws'], + 'image/x-macpaint' => ['pntg'], + 'image/x-minolta-mrw' => ['mrw'], + 'image/x-mrsid-image' => ['sid'], + 'image/x-ms-bmp' => ['bmp', 'dib'], + 'image/x-msod' => ['msod'], + 'image/x-nikon-nef' => ['nef'], + 'image/x-nikon-nrw' => ['nrw'], + 'image/x-olympus-orf' => ['orf'], + 'image/x-panasonic-raw' => ['raw'], + 'image/x-panasonic-raw2' => ['rw2'], + 'image/x-panasonic-rw' => ['raw'], + 'image/x-panasonic-rw2' => ['rw2'], + 'image/x-pcx' => ['pcx'], + 'image/x-pentax-pef' => ['pef'], + 'image/x-photo-cd' => ['pcd'], + 'image/x-photoshop' => ['psd'], + 'image/x-pict' => ['pic', 'pct', 'pict', 'pict1', 'pict2'], + 'image/x-portable-anymap' => ['pnm'], + 'image/x-portable-bitmap' => ['pbm'], + 'image/x-portable-graymap' => ['pgm'], + 'image/x-portable-pixmap' => ['ppm'], + 'image/x-psd' => ['psd'], + 'image/x-quicktime' => ['qtif', 'qif'], + 'image/x-rgb' => ['rgb'], + 'image/x-sgi' => ['sgi'], + 'image/x-sigma-x3f' => ['x3f'], + 'image/x-skencil' => ['sk', 'sk1'], + 'image/x-sony-arw' => ['arw'], + 'image/x-sony-sr2' => ['sr2'], + 'image/x-sony-srf' => ['srf'], + 'image/x-sun-raster' => ['sun'], + 'image/x-targa' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'image/x-tga' => ['tga', 'icb', 'tpic', 'vda', 'vst'], + 'image/x-win-bitmap' => ['cur'], + 'image/x-win-metafile' => ['wmf'], + 'image/x-wmf' => ['wmf'], + 'image/x-xbitmap' => ['xbm'], + 'image/x-xcf' => ['xcf'], + 'image/x-xfig' => ['fig'], + 'image/x-xpixmap' => ['xpm'], + 'image/x-xpm' => ['xpm'], + 'image/x-xwindowdump' => ['xwd'], + 'image/x.djvu' => ['djvu', 'djv'], + 'message/disposition-notification' => ['disposition-notification'], + 'message/global' => ['u8msg'], + 'message/global-delivery-status' => ['u8dsn'], + 'message/global-disposition-notification' => ['u8mdn'], + 'message/global-headers' => ['u8hdr'], + 'message/rfc822' => ['eml', 'mime'], + 'message/vnd.wfa.wsc' => ['wsc'], + 'model/3mf' => ['3mf'], + 'model/gltf+json' => ['gltf'], + 'model/gltf-binary' => ['glb'], + 'model/iges' => ['igs', 'iges'], + 'model/mesh' => ['msh', 'mesh', 'silo'], + 'model/mtl' => ['mtl'], + 'model/obj' => ['obj'], + 'model/step+zip' => ['stpz'], + 'model/step-xml+zip' => ['stpxz'], + 'model/stl' => ['stl'], + 'model/vnd.collada+xml' => ['dae'], + 'model/vnd.dwf' => ['dwf'], + 'model/vnd.gdl' => ['gdl'], + 'model/vnd.gtw' => ['gtw'], + 'model/vnd.mts' => ['mts'], + 'model/vnd.opengex' => ['ogex'], + 'model/vnd.parasolid.transmit.binary' => ['x_b'], + 'model/vnd.parasolid.transmit.text' => ['x_t'], + 'model/vnd.sap.vds' => ['vds'], + 'model/vnd.usdz+zip' => ['usdz'], + 'model/vnd.valve.source.compiled-map' => ['bsp'], + 'model/vnd.vtu' => ['vtu'], + 'model/vrml' => ['wrl', 'vrml', 'vrm'], + 'model/x.stl-ascii' => ['stl'], + 'model/x.stl-binary' => ['stl'], + 'model/x3d+binary' => ['x3db', 'x3dbz'], + 'model/x3d+fastinfoset' => ['x3db'], + 'model/x3d+vrml' => ['x3dv', 'x3dvz'], + 'model/x3d+xml' => ['x3d', 'x3dz'], + 'model/x3d-vrml' => ['x3dv'], + 'text/cache-manifest' => ['appcache', 'manifest'], + 'text/calendar' => ['ics', 'ifb', 'vcs'], + 'text/coffeescript' => ['coffee', 'litcoffee'], + 'text/crystal' => ['cr'], + 'text/css' => ['css'], + 'text/csv' => ['csv'], + 'text/csv-schema' => ['csvs'], + 'text/directory' => ['vcard', 'vcf', 'vct', 'gcrd'], + 'text/ecmascript' => ['es'], + 'text/gedcom' => ['ged', 'gedcom'], + 'text/google-video-pointer' => ['gvp'], + 'text/html' => ['html', 'htm', 'shtml'], + 'text/ico' => ['ico'], + 'text/jade' => ['jade'], + 'text/javascript' => ['js', 'jsm', 'mjs'], + 'text/jsx' => ['jsx'], + 'text/less' => ['less'], + 'text/markdown' => ['md', 'markdown', 'mkd'], + 'text/mathml' => ['mml'], + 'text/mdx' => ['mdx'], + 'text/n3' => ['n3'], + 'text/org' => ['org'], + 'text/plain' => ['txt', 'text', 'conf', 'def', 'list', 'log', 'in', 'ini', 'asc'], + 'text/prs.lines.tag' => ['dsc'], + 'text/rdf' => ['rdf', 'rdfs', 'owl'], + 'text/richtext' => ['rtx'], + 'text/rss' => ['rss'], + 'text/rtf' => ['rtf'], + 'text/rust' => ['rs'], + 'text/sgml' => ['sgml', 'sgm'], + 'text/shex' => ['shex'], + 'text/slim' => ['slim', 'slm'], + 'text/spdx' => ['spdx'], + 'text/spreadsheet' => ['sylk', 'slk'], + 'text/stylus' => ['stylus', 'styl'], + 'text/tab-separated-values' => ['tsv'], + 'text/tcl' => ['tcl', 'tk'], + 'text/troff' => ['t', 'tr', 'roff', 'man', 'me', 'ms'], + 'text/turtle' => ['ttl'], + 'text/uri-list' => ['uri', 'uris', 'urls'], + 'text/vbs' => ['vbs'], + 'text/vbscript' => ['vbs'], + 'text/vcard' => ['vcard', 'vcf', 'vct', 'gcrd'], + 'text/vnd.curl' => ['curl'], + 'text/vnd.curl.dcurl' => ['dcurl'], + 'text/vnd.curl.mcurl' => ['mcurl'], + 'text/vnd.curl.scurl' => ['scurl'], + 'text/vnd.dvb.subtitle' => ['sub'], + 'text/vnd.fly' => ['fly'], + 'text/vnd.fmi.flexstor' => ['flx'], + 'text/vnd.graphviz' => ['gv', 'dot'], + 'text/vnd.in3d.3dml' => ['3dml'], + 'text/vnd.in3d.spot' => ['spot'], + 'text/vnd.qt.linguist' => ['ts'], + 'text/vnd.rn-realtext' => ['rt'], + 'text/vnd.senx.warpscript' => ['mc2'], + 'text/vnd.sun.j2me.app-descriptor' => ['jad'], + 'text/vnd.trolltech.linguist' => ['ts'], + 'text/vnd.wap.wml' => ['wml'], + 'text/vnd.wap.wmlscript' => ['wmls'], + 'text/vtt' => ['vtt'], + 'text/x-adasrc' => ['adb', 'ads'], + 'text/x-asm' => ['s', 'asm'], + 'text/x-bibtex' => ['bib'], + 'text/x-c' => ['c', 'cc', 'cxx', 'cpp', 'h', 'hh', 'dic'], + 'text/x-c++hdr' => ['hh', 'hp', 'hpp', 'h++', 'hxx'], + 'text/x-c++src' => ['cpp', 'cxx', 'cc', 'C', 'c++'], + 'text/x-chdr' => ['h'], + 'text/x-cmake' => ['cmake'], + 'text/x-cobol' => ['cbl', 'cob'], + 'text/x-comma-separated-values' => ['csv'], + 'text/x-common-lisp' => ['asd', 'fasl', 'lisp', 'ros'], + 'text/x-component' => ['htc'], + 'text/x-crystal' => ['cr'], + 'text/x-csharp' => ['cs'], + 'text/x-csrc' => ['c'], + 'text/x-csv' => ['csv'], + 'text/x-dart' => ['dart'], + 'text/x-dbus-service' => ['service'], + 'text/x-dcl' => ['dcl'], + 'text/x-diff' => ['diff', 'patch'], + 'text/x-dsl' => ['dsl'], + 'text/x-dsrc' => ['d', 'di'], + 'text/x-dtd' => ['dtd'], + 'text/x-eiffel' => ['e', 'eif'], + 'text/x-elixir' => ['ex', 'exs'], + 'text/x-emacs-lisp' => ['el'], + 'text/x-erlang' => ['erl'], + 'text/x-fortran' => ['f', 'for', 'f77', 'f90', 'f95'], + 'text/x-genie' => ['gs'], + 'text/x-gettext-translation' => ['po'], + 'text/x-gettext-translation-template' => ['pot'], + 'text/x-gherkin' => ['feature'], + 'text/x-go' => ['go'], + 'text/x-google-video-pointer' => ['gvp'], + 'text/x-gradle' => ['gradle'], + 'text/x-groovy' => ['groovy', 'gvy', 'gy', 'gsh'], + 'text/x-handlebars-template' => ['hbs'], + 'text/x-haskell' => ['hs'], + 'text/x-idl' => ['idl'], + 'text/x-imelody' => ['imy', 'ime'], + 'text/x-iptables' => ['iptables'], + 'text/x-java' => ['java'], + 'text/x-java-source' => ['java'], + 'text/x-kaitai-struct' => ['ksy'], + 'text/x-kotlin' => ['kt'], + 'text/x-ldif' => ['ldif'], + 'text/x-lilypond' => ['ly'], + 'text/x-literate-haskell' => ['lhs'], + 'text/x-log' => ['log'], + 'text/x-lua' => ['lua'], + 'text/x-lyx' => ['lyx'], + 'text/x-makefile' => ['mk', 'mak'], + 'text/x-markdown' => ['md', 'mkd', 'markdown'], + 'text/x-matlab' => ['m'], + 'text/x-microdvd' => ['sub'], + 'text/x-moc' => ['moc'], + 'text/x-modelica' => ['mo'], + 'text/x-mof' => ['mof'], + 'text/x-mpsub' => ['sub'], + 'text/x-mrml' => ['mrml', 'mrl'], + 'text/x-ms-regedit' => ['reg'], + 'text/x-mup' => ['mup', 'not'], + 'text/x-nfo' => ['nfo'], + 'text/x-objcsrc' => ['m'], + 'text/x-ocaml' => ['ml', 'mli'], + 'text/x-ocl' => ['ocl'], + 'text/x-octave' => ['m'], + 'text/x-ooc' => ['ooc'], + 'text/x-opencl-src' => ['cl'], + 'text/x-opml' => ['opml'], + 'text/x-opml+xml' => ['opml'], + 'text/x-org' => ['org'], + 'text/x-pascal' => ['p', 'pas'], + 'text/x-patch' => ['diff', 'patch'], + 'text/x-perl' => ['pl', 'PL', 'pm', 'al', 'perl', 'pod', 't'], + 'text/x-po' => ['po'], + 'text/x-pot' => ['pot'], + 'text/x-processing' => ['pde'], + 'text/x-python' => ['py', 'pyx', 'wsgi'], + 'text/x-python3' => ['py', 'py3', 'py3x', 'pyi'], + 'text/x-qml' => ['qml', 'qmltypes', 'qmlproject'], + 'text/x-reject' => ['rej'], + 'text/x-rpm-spec' => ['spec'], + 'text/x-rst' => ['rst'], + 'text/x-sagemath' => ['sage'], + 'text/x-sass' => ['sass'], + 'text/x-scala' => ['scala', 'sc'], + 'text/x-scheme' => ['scm', 'ss'], + 'text/x-scss' => ['scss'], + 'text/x-setext' => ['etx'], + 'text/x-sfv' => ['sfv'], + 'text/x-sh' => ['sh'], + 'text/x-sql' => ['sql'], + 'text/x-ssa' => ['ssa', 'ass'], + 'text/x-subviewer' => ['sub'], + 'text/x-suse-ymp' => ['ymp'], + 'text/x-svhdr' => ['svh'], + 'text/x-svsrc' => ['sv'], + 'text/x-systemd-unit' => ['automount', 'device', 'mount', 'path', 'scope', 'service', 'slice', 'socket', 'swap', 'target', 'timer'], + 'text/x-tcl' => ['tcl', 'tk'], + 'text/x-tex' => ['tex', 'ltx', 'sty', 'cls', 'dtx', 'ins', 'latex'], + 'text/x-texinfo' => ['texi', 'texinfo'], + 'text/x-troff' => ['tr', 'roff', 't'], + 'text/x-troff-me' => ['me'], + 'text/x-troff-mm' => ['mm'], + 'text/x-troff-ms' => ['ms'], + 'text/x-twig' => ['twig'], + 'text/x-txt2tags' => ['t2t'], + 'text/x-uil' => ['uil'], + 'text/x-uuencode' => ['uu', 'uue'], + 'text/x-vala' => ['vala', 'vapi'], + 'text/x-vcalendar' => ['vcs', 'ics'], + 'text/x-vcard' => ['vcf', 'vcard', 'vct', 'gcrd'], + 'text/x-verilog' => ['v'], + 'text/x-vhdl' => ['vhd', 'vhdl'], + 'text/x-xmi' => ['xmi'], + 'text/x-xslfo' => ['fo', 'xslfo'], + 'text/x-yaml' => ['yaml', 'yml'], + 'text/x.gcode' => ['gcode'], + 'text/xml' => ['xml', 'xbl', 'xsd', 'rng'], + 'text/xml-external-parsed-entity' => ['ent'], + 'text/yaml' => ['yaml', 'yml'], + 'video/3gp' => ['3gp', '3gpp', '3ga'], + 'video/3gpp' => ['3gp', '3gpp', '3ga'], + 'video/3gpp-encrypted' => ['3gp', '3gpp', '3ga'], + 'video/3gpp2' => ['3g2', '3gp2', '3gpp2'], + 'video/annodex' => ['axv'], + 'video/avi' => ['avi', 'avf', 'divx'], + 'video/divx' => ['avi', 'avf', 'divx'], + 'video/dv' => ['dv'], + 'video/fli' => ['fli', 'flc'], + 'video/flv' => ['flv'], + 'video/h261' => ['h261'], + 'video/h263' => ['h263'], + 'video/h264' => ['h264'], + 'video/iso.segment' => ['m4s'], + 'video/jpeg' => ['jpgv'], + 'video/jpm' => ['jpm', 'jpgm'], + 'video/mj2' => ['mj2', 'mjp2'], + 'video/mp2t' => ['ts', 'm2t', 'm2ts', 'mts', 'cpi', 'clpi', 'mpl', 'mpls', 'bdm', 'bdmv'], + 'video/mp4' => ['mp4', 'mp4v', 'mpg4', 'm4v', 'f4v', 'lrv'], + 'video/mp4v-es' => ['mp4', 'm4v', 'f4v', 'lrv'], + 'video/mpeg' => ['mpeg', 'mpg', 'mpe', 'm1v', 'm2v', 'mp2', 'vob'], + 'video/mpeg-system' => ['mpeg', 'mpg', 'mp2', 'mpe', 'vob'], + 'video/msvideo' => ['avi', 'avf', 'divx'], + 'video/ogg' => ['ogv', 'ogg'], + 'video/quicktime' => ['mov', 'qt', 'moov', 'qtvr'], + 'video/vivo' => ['viv', 'vivo'], + 'video/vnd.dece.hd' => ['uvh', 'uvvh'], + 'video/vnd.dece.mobile' => ['uvm', 'uvvm'], + 'video/vnd.dece.pd' => ['uvp', 'uvvp'], + 'video/vnd.dece.sd' => ['uvs', 'uvvs'], + 'video/vnd.dece.video' => ['uvv', 'uvvv'], + 'video/vnd.divx' => ['avi', 'avf', 'divx'], + 'video/vnd.dvb.file' => ['dvb'], + 'video/vnd.fvt' => ['fvt'], + 'video/vnd.mpegurl' => ['mxu', 'm4u', 'm1u'], + 'video/vnd.ms-playready.media.pyv' => ['pyv'], + 'video/vnd.radgamettools.bink' => ['bik', 'bk2'], + 'video/vnd.radgamettools.smacker' => ['smk'], + 'video/vnd.rn-realvideo' => ['rv', 'rvx'], + 'video/vnd.uvvu.mp4' => ['uvu', 'uvvu'], + 'video/vnd.vivo' => ['viv', 'vivo'], + 'video/webm' => ['webm'], + 'video/x-anim' => ['anim[1-9j]'], + 'video/x-annodex' => ['axv'], + 'video/x-avi' => ['avi', 'avf', 'divx'], + 'video/x-f4v' => ['f4v'], + 'video/x-fli' => ['fli', 'flc'], + 'video/x-flic' => ['fli', 'flc'], + 'video/x-flv' => ['flv'], + 'video/x-javafx' => ['fxm'], + 'video/x-m4v' => ['m4v', 'mp4', 'f4v', 'lrv'], + 'video/x-matroska' => ['mkv', 'mk3d', 'mks'], + 'video/x-matroska-3d' => ['mk3d'], + 'video/x-mjpeg' => ['mjpeg', 'mjpg'], + 'video/x-mng' => ['mng'], + 'video/x-mpeg' => ['mpeg', 'mpg', 'mp2', 'mpe', 'vob'], + 'video/x-mpeg-system' => ['mpeg', 'mpg', 'mp2', 'mpe', 'vob'], + 'video/x-mpeg2' => ['mpeg', 'mpg', 'mp2', 'mpe', 'vob'], + 'video/x-mpegurl' => ['m1u', 'm4u', 'mxu'], + 'video/x-ms-asf' => ['asf', 'asx'], + 'video/x-ms-asf-plugin' => ['asf'], + 'video/x-ms-vob' => ['vob'], + 'video/x-ms-wax' => ['asx', 'wax', 'wvx', 'wmx'], + 'video/x-ms-wm' => ['wm', 'asf'], + 'video/x-ms-wmv' => ['wmv'], + 'video/x-ms-wmx' => ['wmx', 'asx', 'wax', 'wvx'], + 'video/x-ms-wvx' => ['wvx', 'asx', 'wax', 'wmx'], + 'video/x-msvideo' => ['avi', 'avf', 'divx'], + 'video/x-nsv' => ['nsv'], + 'video/x-ogg' => ['ogv', 'ogg'], + 'video/x-ogm' => ['ogm'], + 'video/x-ogm+ogg' => ['ogm'], + 'video/x-real-video' => ['rv', 'rvx'], + 'video/x-sgi-movie' => ['movie'], + 'video/x-smv' => ['smv'], + 'video/x-theora' => ['ogg'], + 'video/x-theora+ogg' => ['ogg'], + 'x-conference/x-cooltalk' => ['ice'], + 'x-epoc/x-sisx-app' => ['sisx'], + 'zz-application/zz-winassoc-123' => ['123', 'wk1', 'wk3', 'wk4', 'wks'], + 'zz-application/zz-winassoc-cab' => ['cab'], + 'zz-application/zz-winassoc-cdr' => ['cdr'], + 'zz-application/zz-winassoc-doc' => ['doc'], + 'zz-application/zz-winassoc-hlp' => ['hlp'], + 'zz-application/zz-winassoc-mdb' => ['mdb'], + 'zz-application/zz-winassoc-uu' => ['uue'], + 'zz-application/zz-winassoc-xls' => ['xls', 'xlc', 'xll', 'xlm', 'xlw', 'xla', 'xlt', 'xld'], + ]; + + private const REVERSE_MAP = [ + '1km' => ['application/vnd.1000minds.decision-model+xml'], + '32x' => ['application/x-genesis-32x-rom'], + '3dml' => ['text/vnd.in3d.3dml'], + '3ds' => ['application/x-nintendo-3ds-rom', 'image/x-3ds'], + '3dsx' => ['application/x-nintendo-3ds-executable'], + '3g2' => ['audio/3gpp2', 'video/3gpp2'], + '3ga' => ['audio/3gpp', 'audio/3gpp-encrypted', 'audio/x-rn-3gpp-amr', 'audio/x-rn-3gpp-amr-encrypted', 'audio/x-rn-3gpp-amr-wb', 'audio/x-rn-3gpp-amr-wb-encrypted', 'video/3gp', 'video/3gpp', 'video/3gpp-encrypted'], + '3gp' => ['audio/3gpp', 'audio/3gpp-encrypted', 'audio/x-rn-3gpp-amr', 'audio/x-rn-3gpp-amr-encrypted', 'audio/x-rn-3gpp-amr-wb', 'audio/x-rn-3gpp-amr-wb-encrypted', 'video/3gp', 'video/3gpp', 'video/3gpp-encrypted'], + '3gp2' => ['audio/3gpp2', 'video/3gpp2'], + '3gpp' => ['audio/3gpp', 'audio/3gpp-encrypted', 'audio/x-rn-3gpp-amr', 'audio/x-rn-3gpp-amr-encrypted', 'audio/x-rn-3gpp-amr-wb', 'audio/x-rn-3gpp-amr-wb-encrypted', 'video/3gp', 'video/3gpp', 'video/3gpp-encrypted'], + '3gpp2' => ['audio/3gpp2', 'video/3gpp2'], + '3mf' => ['model/3mf'], + '7z' => ['application/x-7z-compressed'], + '7z.001' => ['application/x-7z-compressed'], + 'BLEND' => ['application/x-blender'], + 'C' => ['text/x-c++src'], + 'PAR2' => ['application/x-par2'], + 'PL' => ['application/x-perl', 'text/x-perl'], + 'Z' => ['application/x-compress'], + 'a' => ['application/x-archive'], + 'a26' => ['application/x-atari-2600-rom'], + 'a78' => ['application/x-atari-7800-rom'], + 'aa' => ['audio/vnd.audible', 'audio/x-pn-audibleaudio'], + 'aab' => ['application/x-authorware-bin'], + 'aac' => ['audio/aac', 'audio/x-aac', 'audio/x-hx-aac-adts'], + 'aam' => ['application/x-authorware-map'], + 'aas' => ['application/x-authorware-seg'], + 'aax' => ['audio/vnd.audible', 'audio/vnd.audible.aax', 'audio/x-pn-audibleaudio'], + 'abw' => ['application/x-abiword'], + 'abw.CRASHED' => ['application/x-abiword'], + 'abw.gz' => ['application/x-abiword'], + 'ac' => ['application/pkix-attr-cert', 'application/vnd.nokia.n-gage.ac+xml'], + 'ac3' => ['audio/ac3'], + 'acc' => ['application/vnd.americandynamics.acc'], + 'ace' => ['application/x-ace', 'application/x-ace-compressed'], + 'acu' => ['application/vnd.acucobol'], + 'acutc' => ['application/vnd.acucorp'], + 'adb' => ['text/x-adasrc'], + 'adf' => ['application/x-amiga-disk-format'], + 'adp' => ['audio/adpcm'], + 'ads' => ['text/x-adasrc'], + 'adts' => ['audio/aac', 'audio/x-aac', 'audio/x-hx-aac-adts'], + 'aep' => ['application/vnd.audiograph'], + 'afm' => ['application/x-font-afm', 'application/x-font-type1'], + 'afp' => ['application/vnd.ibm.modcap'], + 'ag' => ['image/x-applix-graphics'], + 'agb' => ['application/x-gba-rom'], + 'ahead' => ['application/vnd.ahead.space'], + 'ai' => ['application/illustrator', 'application/postscript', 'application/vnd.adobe.illustrator'], + 'aif' => ['audio/x-aiff'], + 'aifc' => ['audio/x-aifc', 'audio/x-aiff', 'audio/x-aiffc'], + 'aiff' => ['audio/x-aiff'], + 'aiffc' => ['audio/x-aifc', 'audio/x-aiffc'], + 'air' => ['application/vnd.adobe.air-application-installer-package+zip'], + 'ait' => ['application/vnd.dvb.ait'], + 'al' => ['application/x-perl', 'text/x-perl'], + 'alz' => ['application/x-alz'], + 'ami' => ['application/vnd.amiga.ami'], + 'amr' => ['audio/amr', 'audio/amr-encrypted'], + 'amz' => ['audio/x-amzxml'], + 'ani' => ['application/x-navi-animation'], + 'anim[1-9j]' => ['video/x-anim'], + 'anx' => ['application/annodex', 'application/x-annodex'], + 'ape' => ['audio/x-ape'], + 'apk' => ['application/vnd.android.package-archive'], + 'apng' => ['image/apng'], + 'appcache' => ['text/cache-manifest'], + 'appimage' => ['application/vnd.appimage', 'application/x-iso9660-appimage'], + 'application' => ['application/x-ms-application'], + 'apr' => ['application/vnd.lotus-approach'], + 'ar' => ['application/x-archive'], + 'arc' => ['application/x-freearc'], + 'arj' => ['application/x-arj'], + 'arw' => ['image/x-sony-arw'], + 'as' => ['application/x-applix-spreadsheet'], + 'asc' => ['application/pgp', 'application/pgp-encrypted', 'application/pgp-keys', 'application/pgp-signature', 'text/plain'], + 'asd' => ['text/x-common-lisp'], + 'asf' => ['application/vnd.ms-asf', 'video/x-ms-asf', 'video/x-ms-asf-plugin', 'video/x-ms-wm'], + 'asice' => ['application/vnd.etsi.asic-e+zip'], + 'asm' => ['text/x-asm'], + 'aso' => ['application/vnd.accpac.simply.aso'], + 'asp' => ['application/x-asp'], + 'ass' => ['audio/aac', 'audio/x-aac', 'audio/x-hx-aac-adts', 'text/x-ssa'], + 'astc' => ['image/astc'], + 'asx' => ['application/x-ms-asx', 'audio/x-ms-asx', 'video/x-ms-asf', 'video/x-ms-wax', 'video/x-ms-wmx', 'video/x-ms-wvx'], + 'atc' => ['application/vnd.acucorp'], + 'atom' => ['application/atom+xml'], + 'atomcat' => ['application/atomcat+xml'], + 'atomdeleted' => ['application/atomdeleted+xml'], + 'atomsvc' => ['application/atomsvc+xml'], + 'atx' => ['application/vnd.antix.game-component'], + 'au' => ['audio/basic'], + 'automount' => ['text/x-systemd-unit'], + 'avf' => ['video/avi', 'video/divx', 'video/msvideo', 'video/vnd.divx', 'video/x-avi', 'video/x-msvideo'], + 'avi' => ['video/avi', 'video/divx', 'video/msvideo', 'video/vnd.divx', 'video/x-avi', 'video/x-msvideo'], + 'avif' => ['image/avif', 'image/avif-sequence'], + 'avifs' => ['image/avif', 'image/avif-sequence'], + 'aw' => ['application/applixware', 'application/x-applix-word'], + 'awb' => ['audio/amr-wb', 'audio/amr-wb-encrypted'], + 'awk' => ['application/x-awk'], + 'axa' => ['audio/annodex', 'audio/x-annodex'], + 'axv' => ['video/annodex', 'video/x-annodex'], + 'azf' => ['application/vnd.airzip.filesecure.azf'], + 'azs' => ['application/vnd.airzip.filesecure.azs'], + 'azv' => ['image/vnd.airzip.accelerator.azv'], + 'azw' => ['application/vnd.amazon.ebook'], + 'azw3' => ['application/vnd.amazon.mobi8-ebook', 'application/x-mobi8-ebook'], + 'b16' => ['image/vnd.pco.b16'], + 'bak' => ['application/x-trash'], + 'bat' => ['application/x-msdownload'], + 'bcpio' => ['application/x-bcpio'], + 'bdf' => ['application/x-font-bdf'], + 'bdm' => ['application/vnd.syncml.dm+wbxml', 'video/mp2t'], + 'bdmv' => ['video/mp2t'], + 'bdoc' => ['application/bdoc', 'application/x-bdoc'], + 'bed' => ['application/vnd.realvnc.bed'], + 'bh2' => ['application/vnd.fujitsu.oasysprs'], + 'bib' => ['text/x-bibtex'], + 'bik' => ['video/vnd.radgamettools.bink'], + 'bin' => ['application/octet-stream'], + 'bk2' => ['video/vnd.radgamettools.bink'], + 'blb' => ['application/x-blorb'], + 'blend' => ['application/x-blender'], + 'blender' => ['application/x-blender'], + 'blorb' => ['application/x-blorb'], + 'bmi' => ['application/vnd.bmi'], + 'bmml' => ['application/vnd.balsamiq.bmml+xml'], + 'bmp' => ['image/bmp', 'image/x-bmp', 'image/x-ms-bmp'], + 'book' => ['application/vnd.framemaker'], + 'box' => ['application/vnd.previewsystems.box'], + 'boz' => ['application/x-bzip2'], + 'bps' => ['application/x-bps-patch'], + 'bsdiff' => ['application/x-bsdiff'], + 'bsp' => ['model/vnd.valve.source.compiled-map'], + 'btif' => ['image/prs.btif'], + 'bz' => ['application/bzip2', 'application/x-bzip', 'application/x-bzip2'], + 'bz2' => ['application/x-bz2', 'application/bzip2', 'application/x-bzip', 'application/x-bzip2'], + 'c' => ['text/x-c', 'text/x-csrc'], + 'c++' => ['text/x-c++src'], + 'c11amc' => ['application/vnd.cluetrust.cartomobile-config'], + 'c11amz' => ['application/vnd.cluetrust.cartomobile-config-pkg'], + 'c4d' => ['application/vnd.clonk.c4group'], + 'c4f' => ['application/vnd.clonk.c4group'], + 'c4g' => ['application/vnd.clonk.c4group'], + 'c4p' => ['application/vnd.clonk.c4group'], + 'c4u' => ['application/vnd.clonk.c4group'], + 'cab' => ['application/vnd.ms-cab-compressed', 'zz-application/zz-winassoc-cab'], + 'caf' => ['audio/x-caf'], + 'cap' => ['application/pcap', 'application/vnd.tcpdump.pcap', 'application/x-pcap'], + 'car' => ['application/vnd.curl.car'], + 'cat' => ['application/vnd.ms-pki.seccat'], + 'cb7' => ['application/x-cb7', 'application/x-cbr'], + 'cba' => ['application/x-cbr'], + 'cbl' => ['text/x-cobol'], + 'cbr' => ['application/vnd.comicbook-rar', 'application/x-cbr'], + 'cbt' => ['application/x-cbr', 'application/x-cbt'], + 'cbz' => ['application/vnd.comicbook+zip', 'application/x-cbr', 'application/x-cbz'], + 'cc' => ['text/x-c', 'text/x-c++src'], + 'cci' => ['application/x-nintendo-3ds-rom'], + 'ccmx' => ['application/x-ccmx'], + 'cco' => ['application/x-cocoa'], + 'cct' => ['application/x-director'], + 'ccxml' => ['application/ccxml+xml'], + 'cdbcmsg' => ['application/vnd.contact.cmsg'], + 'cdf' => ['application/x-netcdf'], + 'cdfx' => ['application/cdfx+xml'], + 'cdi' => ['application/x-discjuggler-cd-image'], + 'cdkey' => ['application/vnd.mediastation.cdkey'], + 'cdmia' => ['application/cdmi-capability'], + 'cdmic' => ['application/cdmi-container'], + 'cdmid' => ['application/cdmi-domain'], + 'cdmio' => ['application/cdmi-object'], + 'cdmiq' => ['application/cdmi-queue'], + 'cdr' => ['application/cdr', 'application/coreldraw', 'application/vnd.corel-draw', 'application/x-cdr', 'application/x-coreldraw', 'image/cdr', 'image/x-cdr', 'zz-application/zz-winassoc-cdr'], + 'cdx' => ['chemical/x-cdx'], + 'cdxml' => ['application/vnd.chemdraw+xml'], + 'cdy' => ['application/vnd.cinderella'], + 'cer' => ['application/pkix-cert'], + 'cert' => ['application/x-x509-ca-cert'], + 'cfs' => ['application/x-cfs-compressed'], + 'cgb' => ['application/x-gameboy-color-rom'], + 'cgm' => ['image/cgm'], + 'chat' => ['application/x-chat'], + 'chd' => ['application/x-mame-chd'], + 'chm' => ['application/vnd.ms-htmlhelp', 'application/x-chm'], + 'chrt' => ['application/vnd.kde.kchart', 'application/x-kchart'], + 'cif' => ['chemical/x-cif'], + 'cii' => ['application/vnd.anser-web-certificate-issue-initiation'], + 'cil' => ['application/vnd.ms-artgalry'], + 'cjs' => ['application/node'], + 'cl' => ['text/x-opencl-src'], + 'cla' => ['application/vnd.claymore'], + 'class' => ['application/java', 'application/java-byte-code', 'application/java-vm', 'application/x-java', 'application/x-java-class', 'application/x-java-vm'], + 'clkk' => ['application/vnd.crick.clicker.keyboard'], + 'clkp' => ['application/vnd.crick.clicker.palette'], + 'clkt' => ['application/vnd.crick.clicker.template'], + 'clkw' => ['application/vnd.crick.clicker.wordbank'], + 'clkx' => ['application/vnd.crick.clicker'], + 'clp' => ['application/x-msclip'], + 'clpi' => ['video/mp2t'], + 'cls' => ['application/x-tex', 'text/x-tex'], + 'cmake' => ['text/x-cmake'], + 'cmc' => ['application/vnd.cosmocaller'], + 'cmdf' => ['chemical/x-cmdf'], + 'cml' => ['chemical/x-cml'], + 'cmp' => ['application/vnd.yellowriver-custom-menu'], + 'cmx' => ['image/x-cmx'], + 'cob' => ['text/x-cobol'], + 'cod' => ['application/vnd.rim.cod'], + 'coffee' => ['application/vnd.coffeescript', 'text/coffeescript'], + 'com' => ['application/x-msdownload'], + 'conf' => ['text/plain'], + 'cpi' => ['video/mp2t'], + 'cpio' => ['application/x-cpio'], + 'cpio.gz' => ['application/x-cpio-compressed'], + 'cpp' => ['text/x-c', 'text/x-c++src'], + 'cpt' => ['application/mac-compactpro'], + 'cr' => ['text/crystal', 'text/x-crystal'], + 'cr2' => ['image/x-canon-cr2'], + 'cr3' => ['image/x-canon-cr3'], + 'crd' => ['application/x-mscardfile'], + 'crdownload' => ['application/x-partial-download'], + 'crl' => ['application/pkix-crl'], + 'crt' => ['application/x-x509-ca-cert'], + 'crw' => ['image/x-canon-crw'], + 'crx' => ['application/x-chrome-extension'], + 'cryptonote' => ['application/vnd.rig.cryptonote'], + 'cs' => ['text/x-csharp'], + 'csh' => ['application/x-csh'], + 'csl' => ['application/vnd.citationstyles.style+xml'], + 'csml' => ['chemical/x-csml'], + 'cso' => ['application/x-compressed-iso'], + 'csp' => ['application/vnd.commonspace'], + 'css' => ['text/css'], + 'cst' => ['application/x-director'], + 'csv' => ['text/csv', 'application/csv', 'text/x-comma-separated-values', 'text/x-csv'], + 'csvs' => ['text/csv-schema'], + 'cu' => ['application/cu-seeme'], + 'cue' => ['application/x-cue'], + 'cur' => ['image/x-win-bitmap'], + 'curl' => ['text/vnd.curl'], + 'cwk' => ['application/x-appleworks-document'], + 'cww' => ['application/prs.cww'], + 'cxt' => ['application/x-director'], + 'cxx' => ['text/x-c', 'text/x-c++src'], + 'd' => ['text/x-dsrc'], + 'dae' => ['model/vnd.collada+xml'], + 'daf' => ['application/vnd.mobius.daf'], + 'dar' => ['application/x-dar'], + 'dart' => ['application/vnd.dart', 'text/x-dart'], + 'dataless' => ['application/vnd.fdsn.seed'], + 'davmount' => ['application/davmount+xml'], + 'dbf' => ['application/dbase', 'application/dbf', 'application/vnd.dbf', 'application/x-dbase', 'application/x-dbf'], + 'dbk' => ['application/docbook+xml', 'application/vnd.oasis.docbook+xml', 'application/x-docbook+xml'], + 'dc' => ['application/x-dc-rom'], + 'dcl' => ['text/x-dcl'], + 'dcm' => ['application/dicom'], + 'dcr' => ['application/x-director', 'image/x-kodak-dcr'], + 'dcurl' => ['text/vnd.curl.dcurl'], + 'dd2' => ['application/vnd.oma.dd2+xml'], + 'ddd' => ['application/vnd.fujixerox.ddd'], + 'ddf' => ['application/vnd.syncml.dmddf+xml'], + 'dds' => ['image/vnd.ms-dds', 'image/x-dds'], + 'deb' => ['application/vnd.debian.binary-package', 'application/x-deb', 'application/x-debian-package'], + 'def' => ['text/plain'], + 'der' => ['application/x-x509-ca-cert'], + 'desktop' => ['application/x-desktop', 'application/x-gnome-app-info'], + 'device' => ['text/x-systemd-unit'], + 'dfac' => ['application/vnd.dreamfactory'], + 'dgc' => ['application/x-dgc-compressed'], + 'di' => ['text/x-dsrc'], + 'dia' => ['application/x-dia-diagram'], + 'dib' => ['image/bmp', 'image/x-bmp', 'image/x-ms-bmp'], + 'dic' => ['text/x-c'], + 'diff' => ['text/x-diff', 'text/x-patch'], + 'dir' => ['application/x-director'], + 'dis' => ['application/vnd.mobius.dis'], + 'disposition-notification' => ['message/disposition-notification'], + 'divx' => ['video/avi', 'video/divx', 'video/msvideo', 'video/vnd.divx', 'video/x-avi', 'video/x-msvideo'], + 'djv' => ['image/vnd.djvu', 'image/vnd.djvu+multipage', 'image/x-djvu', 'image/x.djvu'], + 'djvu' => ['image/vnd.djvu', 'image/vnd.djvu+multipage', 'image/x-djvu', 'image/x.djvu'], + 'dll' => ['application/x-msdownload'], + 'dmg' => ['application/x-apple-diskimage'], + 'dmp' => ['application/pcap', 'application/vnd.tcpdump.pcap', 'application/x-pcap'], + 'dna' => ['application/vnd.dna'], + 'dng' => ['image/x-adobe-dng'], + 'doc' => ['application/msword', 'application/vnd.ms-word', 'application/x-msword', 'zz-application/zz-winassoc-doc'], + 'docbook' => ['application/docbook+xml', 'application/vnd.oasis.docbook+xml', 'application/x-docbook+xml'], + 'docm' => ['application/vnd.ms-word.document.macroenabled.12'], + 'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'], + 'dot' => ['application/msword', 'application/msword-template', 'text/vnd.graphviz'], + 'dotm' => ['application/vnd.ms-word.template.macroenabled.12'], + 'dotx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.template'], + 'dp' => ['application/vnd.osgi.dp'], + 'dpg' => ['application/vnd.dpgraph'], + 'dra' => ['audio/vnd.dra'], + 'drle' => ['image/dicom-rle'], + 'dsc' => ['text/prs.lines.tag'], + 'dsl' => ['text/x-dsl'], + 'dssc' => ['application/dssc+der'], + 'dtb' => ['application/x-dtbook+xml'], + 'dtd' => ['application/xml-dtd', 'text/x-dtd'], + 'dts' => ['audio/vnd.dts', 'audio/x-dts'], + 'dtshd' => ['audio/vnd.dts.hd', 'audio/x-dtshd'], + 'dtx' => ['application/x-tex', 'text/x-tex'], + 'dv' => ['video/dv'], + 'dvb' => ['video/vnd.dvb.file'], + 'dvi' => ['application/x-dvi'], + 'dvi.bz2' => ['application/x-bzdvi'], + 'dvi.gz' => ['application/x-gzdvi'], + 'dwd' => ['application/atsc-dwd+xml'], + 'dwf' => ['model/vnd.dwf'], + 'dwg' => ['image/vnd.dwg'], + 'dxf' => ['image/vnd.dxf'], + 'dxp' => ['application/vnd.spotfire.dxp'], + 'dxr' => ['application/x-director'], + 'e' => ['text/x-eiffel'], + 'ear' => ['application/java-archive'], + 'ecelp4800' => ['audio/vnd.nuera.ecelp4800'], + 'ecelp7470' => ['audio/vnd.nuera.ecelp7470'], + 'ecelp9600' => ['audio/vnd.nuera.ecelp9600'], + 'ecma' => ['application/ecmascript'], + 'edm' => ['application/vnd.novadigm.edm'], + 'edx' => ['application/vnd.novadigm.edx'], + 'efif' => ['application/vnd.picsel'], + 'egon' => ['application/x-egon'], + 'ei6' => ['application/vnd.pg.osasli'], + 'eif' => ['text/x-eiffel'], + 'el' => ['text/x-emacs-lisp'], + 'emf' => ['application/emf', 'application/x-emf', 'application/x-msmetafile', 'image/emf', 'image/x-emf'], + 'eml' => ['message/rfc822'], + 'emma' => ['application/emma+xml'], + 'emotionml' => ['application/emotionml+xml'], + 'emp' => ['application/vnd.emusic-emusic_package'], + 'emz' => ['application/x-msmetafile'], + 'ent' => ['application/xml-external-parsed-entity', 'text/xml-external-parsed-entity'], + 'eol' => ['audio/vnd.digital-winds'], + 'eot' => ['application/vnd.ms-fontobject'], + 'eps' => ['application/postscript', 'image/x-eps'], + 'eps.bz2' => ['image/x-bzeps'], + 'eps.gz' => ['image/x-gzeps'], + 'epsf' => ['image/x-eps'], + 'epsf.bz2' => ['image/x-bzeps'], + 'epsf.gz' => ['image/x-gzeps'], + 'epsi' => ['image/x-eps'], + 'epsi.bz2' => ['image/x-bzeps'], + 'epsi.gz' => ['image/x-gzeps'], + 'epub' => ['application/epub+zip'], + 'erl' => ['text/x-erlang'], + 'es' => ['application/ecmascript', 'text/ecmascript'], + 'es3' => ['application/vnd.eszigno3+xml'], + 'esa' => ['application/vnd.osgi.subsystem'], + 'esf' => ['application/vnd.epson.esf'], + 'et3' => ['application/vnd.eszigno3+xml'], + 'etheme' => ['application/x-e-theme'], + 'etx' => ['text/x-setext'], + 'eva' => ['application/x-eva'], + 'evy' => ['application/x-envoy'], + 'ex' => ['text/x-elixir'], + 'exe' => ['application/x-ms-dos-executable', 'application/x-msdos-program', 'application/x-msdownload'], + 'exi' => ['application/exi'], + 'exr' => ['image/aces', 'image/x-exr'], + 'exs' => ['text/x-elixir'], + 'ext' => ['application/vnd.novadigm.ext'], + 'ez' => ['application/andrew-inset'], + 'ez2' => ['application/vnd.ezpix-album'], + 'ez3' => ['application/vnd.ezpix-package'], + 'f' => ['text/x-fortran'], + 'f4a' => ['audio/m4a', 'audio/mp4', 'audio/x-m4a'], + 'f4b' => ['audio/x-m4b'], + 'f4v' => ['video/mp4', 'video/mp4v-es', 'video/x-f4v', 'video/x-m4v'], + 'f77' => ['text/x-fortran'], + 'f90' => ['text/x-fortran'], + 'f95' => ['text/x-fortran'], + 'fasl' => ['text/x-common-lisp'], + 'fb2' => ['application/x-fictionbook', 'application/x-fictionbook+xml'], + 'fb2.zip' => ['application/x-zip-compressed-fb2'], + 'fbs' => ['image/vnd.fastbidsheet'], + 'fcdt' => ['application/vnd.adobe.formscentral.fcdt'], + 'fcs' => ['application/vnd.isac.fcs'], + 'fd' => ['application/x-fd-file', 'application/x-raw-floppy-disk-image'], + 'fdf' => ['application/vnd.fdf'], + 'fds' => ['application/x-fds-disk'], + 'fdt' => ['application/fdt+xml'], + 'fe_launch' => ['application/vnd.denovo.fcselayout-link'], + 'feature' => ['text/x-gherkin'], + 'fg5' => ['application/vnd.fujitsu.oasysgp'], + 'fgd' => ['application/x-director'], + 'fh' => ['image/x-freehand'], + 'fh4' => ['image/x-freehand'], + 'fh5' => ['image/x-freehand'], + 'fh7' => ['image/x-freehand'], + 'fhc' => ['image/x-freehand'], + 'fig' => ['application/x-xfig', 'image/x-xfig'], + 'fits' => ['image/fits', 'image/x-fits'], + 'fl' => ['application/x-fluid'], + 'flac' => ['audio/flac', 'audio/x-flac'], + 'flatpak' => ['application/vnd.flatpak', 'application/vnd.xdgapp'], + 'flatpakref' => ['application/vnd.flatpak.ref'], + 'flatpakrepo' => ['application/vnd.flatpak.repo'], + 'flc' => ['video/fli', 'video/x-fli', 'video/x-flic'], + 'fli' => ['video/fli', 'video/x-fli', 'video/x-flic'], + 'flo' => ['application/vnd.micrografx.flo'], + 'flv' => ['video/x-flv', 'application/x-flash-video', 'flv-application/octet-stream', 'video/flv'], + 'flw' => ['application/vnd.kde.kivio', 'application/x-kivio'], + 'flx' => ['text/vnd.fmi.flexstor'], + 'fly' => ['text/vnd.fly'], + 'fm' => ['application/vnd.framemaker', 'application/x-frame'], + 'fnc' => ['application/vnd.frogans.fnc'], + 'fo' => ['application/vnd.software602.filler.form+xml', 'text/x-xslfo'], + 'fodg' => ['application/vnd.oasis.opendocument.graphics-flat-xml'], + 'fodp' => ['application/vnd.oasis.opendocument.presentation-flat-xml'], + 'fods' => ['application/vnd.oasis.opendocument.spreadsheet-flat-xml'], + 'fodt' => ['application/vnd.oasis.opendocument.text-flat-xml'], + 'for' => ['text/x-fortran'], + 'fpx' => ['image/vnd.fpx'], + 'frame' => ['application/vnd.framemaker'], + 'fsc' => ['application/vnd.fsc.weblaunch'], + 'fst' => ['image/vnd.fst'], + 'ftc' => ['application/vnd.fluxtime.clip'], + 'fti' => ['application/vnd.anser-web-funds-transfer-initiation'], + 'fvt' => ['video/vnd.fvt'], + 'fxm' => ['video/x-javafx'], + 'fxp' => ['application/vnd.adobe.fxp'], + 'fxpl' => ['application/vnd.adobe.fxp'], + 'fzs' => ['application/vnd.fuzzysheet'], + 'g2w' => ['application/vnd.geoplan'], + 'g3' => ['image/fax-g3', 'image/g3fax'], + 'g3w' => ['application/vnd.geospace'], + 'gac' => ['application/vnd.groove-account'], + 'gam' => ['application/x-tads'], + 'gb' => ['application/x-gameboy-rom'], + 'gba' => ['application/x-gba-rom'], + 'gbc' => ['application/x-gameboy-color-rom'], + 'gbr' => ['application/rpki-ghostbusters', 'image/x-gimp-gbr'], + 'gca' => ['application/x-gca-compressed'], + 'gcode' => ['text/x.gcode'], + 'gcrd' => ['text/directory', 'text/vcard', 'text/x-vcard'], + 'gdi' => ['application/x-gd-rom-cue'], + 'gdl' => ['model/vnd.gdl'], + 'gdoc' => ['application/vnd.google-apps.document'], + 'ged' => ['application/x-gedcom', 'text/gedcom'], + 'gedcom' => ['application/x-gedcom', 'text/gedcom'], + 'gem' => ['application/x-gtar', 'application/x-tar'], + 'gen' => ['application/x-genesis-rom'], + 'geo' => ['application/vnd.dynageo'], + 'geo.json' => ['application/geo+json', 'application/vnd.geo+json'], + 'geojson' => ['application/geo+json', 'application/vnd.geo+json'], + 'gex' => ['application/vnd.geometry-explorer'], + 'gf' => ['application/x-tex-gf'], + 'gg' => ['application/x-gamegear-rom'], + 'ggb' => ['application/vnd.geogebra.file'], + 'ggt' => ['application/vnd.geogebra.tool'], + 'ghf' => ['application/vnd.groove-help'], + 'gif' => ['image/gif'], + 'gih' => ['image/x-gimp-gih'], + 'gim' => ['application/vnd.groove-identity-message'], + 'glade' => ['application/x-glade'], + 'glb' => ['model/gltf-binary'], + 'gltf' => ['model/gltf+json'], + 'gml' => ['application/gml+xml'], + 'gmo' => ['application/x-gettext-translation'], + 'gmx' => ['application/vnd.gmx'], + 'gnc' => ['application/x-gnucash'], + 'gnd' => ['application/gnunet-directory'], + 'gnucash' => ['application/x-gnucash'], + 'gnumeric' => ['application/x-gnumeric'], + 'gnuplot' => ['application/x-gnuplot'], + 'go' => ['text/x-go'], + 'gp' => ['application/x-gnuplot'], + 'gpg' => ['application/pgp', 'application/pgp-encrypted', 'application/pgp-keys', 'application/pgp-signature'], + 'gph' => ['application/vnd.flographit'], + 'gplt' => ['application/x-gnuplot'], + 'gpx' => ['application/gpx', 'application/gpx+xml', 'application/x-gpx', 'application/x-gpx+xml'], + 'gqf' => ['application/vnd.grafeq'], + 'gqs' => ['application/vnd.grafeq'], + 'gra' => ['application/x-graphite'], + 'gradle' => ['text/x-gradle'], + 'gram' => ['application/srgs'], + 'gramps' => ['application/x-gramps-xml'], + 'gre' => ['application/vnd.geometry-explorer'], + 'groovy' => ['text/x-groovy'], + 'grv' => ['application/vnd.groove-injector'], + 'grxml' => ['application/srgs+xml'], + 'gs' => ['text/x-genie'], + 'gsf' => ['application/x-font-ghostscript', 'application/x-font-type1'], + 'gsh' => ['text/x-groovy'], + 'gsheet' => ['application/vnd.google-apps.spreadsheet'], + 'gslides' => ['application/vnd.google-apps.presentation'], + 'gsm' => ['audio/x-gsm'], + 'gtar' => ['application/x-gtar', 'application/x-tar'], + 'gtm' => ['application/vnd.groove-tool-message'], + 'gtw' => ['model/vnd.gtw'], + 'gv' => ['text/vnd.graphviz'], + 'gvp' => ['text/google-video-pointer', 'text/x-google-video-pointer'], + 'gvy' => ['text/x-groovy'], + 'gxf' => ['application/gxf'], + 'gxt' => ['application/vnd.geonext'], + 'gy' => ['text/x-groovy'], + 'gz' => ['application/x-gzip', 'application/gzip'], + 'h' => ['text/x-c', 'text/x-chdr'], + 'h++' => ['text/x-c++hdr'], + 'h261' => ['video/h261'], + 'h263' => ['video/h263'], + 'h264' => ['video/h264'], + 'h4' => ['application/x-hdf'], + 'h5' => ['application/x-hdf'], + 'hal' => ['application/vnd.hal+xml'], + 'hbci' => ['application/vnd.hbci'], + 'hbs' => ['text/x-handlebars-template'], + 'hdd' => ['application/x-virtualbox-hdd'], + 'hdf' => ['application/x-hdf'], + 'hdf4' => ['application/x-hdf'], + 'hdf5' => ['application/x-hdf'], + 'heic' => ['image/heic', 'image/heic-sequence', 'image/heif', 'image/heif-sequence'], + 'heics' => ['image/heic-sequence'], + 'heif' => ['image/heic', 'image/heic-sequence', 'image/heif', 'image/heif-sequence'], + 'heifs' => ['image/heif-sequence'], + 'hej2' => ['image/hej2k'], + 'held' => ['application/atsc-held+xml'], + 'hfe' => ['application/x-hfe-file', 'application/x-hfe-floppy-image'], + 'hh' => ['text/x-c', 'text/x-c++hdr'], + 'hjson' => ['application/hjson'], + 'hlp' => ['application/winhlp', 'zz-application/zz-winassoc-hlp'], + 'hp' => ['text/x-c++hdr'], + 'hpgl' => ['application/vnd.hp-hpgl'], + 'hpid' => ['application/vnd.hp-hpid'], + 'hpp' => ['text/x-c++hdr'], + 'hps' => ['application/vnd.hp-hps'], + 'hqx' => ['application/stuffit', 'application/mac-binhex40'], + 'hs' => ['text/x-haskell'], + 'hsj2' => ['image/hsj2'], + 'htc' => ['text/x-component'], + 'htke' => ['application/vnd.kenameaapp'], + 'htm' => ['text/html', 'application/xhtml+xml'], + 'html' => ['text/html', 'application/xhtml+xml'], + 'hvd' => ['application/vnd.yamaha.hv-dic'], + 'hvp' => ['application/vnd.yamaha.hv-voice'], + 'hvs' => ['application/vnd.yamaha.hv-script'], + 'hwp' => ['application/vnd.haansoft-hwp', 'application/x-hwp'], + 'hwt' => ['application/vnd.haansoft-hwt', 'application/x-hwt'], + 'hxx' => ['text/x-c++hdr'], + 'i2g' => ['application/vnd.intergeo'], + 'ica' => ['application/x-ica'], + 'icb' => ['application/tga', 'application/x-targa', 'application/x-tga', 'image/targa', 'image/tga', 'image/x-icb', 'image/x-targa', 'image/x-tga'], + 'icc' => ['application/vnd.iccprofile'], + 'ice' => ['x-conference/x-cooltalk'], + 'icm' => ['application/vnd.iccprofile'], + 'icns' => ['image/x-icns'], + 'ico' => ['application/ico', 'image/ico', 'image/icon', 'image/vnd.microsoft.icon', 'image/x-ico', 'image/x-icon', 'text/ico'], + 'ics' => ['application/ics', 'text/calendar', 'text/x-vcalendar'], + 'idl' => ['text/x-idl'], + 'ief' => ['image/ief'], + 'ifb' => ['text/calendar'], + 'iff' => ['image/x-iff', 'image/x-ilbm'], + 'ifm' => ['application/vnd.shana.informed.formdata'], + 'iges' => ['model/iges'], + 'igl' => ['application/vnd.igloader'], + 'igm' => ['application/vnd.insors.igm'], + 'igs' => ['model/iges'], + 'igx' => ['application/vnd.micrografx.igx'], + 'iif' => ['application/vnd.shana.informed.interchange'], + 'ilbm' => ['image/x-iff', 'image/x-ilbm'], + 'ime' => ['audio/imelody', 'audio/x-imelody', 'text/x-imelody'], + 'img' => ['application/x-raw-disk-image'], + 'img.xz' => ['application/x-raw-disk-image-xz-compressed'], + 'imp' => ['application/vnd.accpac.simply.imp'], + 'ims' => ['application/vnd.ms-ims'], + 'imy' => ['audio/imelody', 'audio/x-imelody', 'text/x-imelody'], + 'in' => ['text/plain'], + 'ini' => ['text/plain'], + 'ink' => ['application/inkml+xml'], + 'inkml' => ['application/inkml+xml'], + 'ins' => ['application/x-tex', 'text/x-tex'], + 'install' => ['application/x-install-instructions'], + 'iota' => ['application/vnd.astraea-software.iota'], + 'ipfix' => ['application/ipfix'], + 'ipk' => ['application/vnd.shana.informed.package'], + 'ips' => ['application/x-ips-patch'], + 'iptables' => ['text/x-iptables'], + 'ipynb' => ['application/x-ipynb+json'], + 'irm' => ['application/vnd.ibm.rights-management'], + 'irp' => ['application/vnd.irepository.package+xml'], + 'iso' => ['application/x-cd-image', 'application/x-dreamcast-rom', 'application/x-gamecube-iso-image', 'application/x-gamecube-rom', 'application/x-iso9660-image', 'application/x-saturn-rom', 'application/x-sega-cd-rom', 'application/x-sega-pico-rom', 'application/x-wbfs', 'application/x-wia', 'application/x-wii-iso-image', 'application/x-wii-rom'], + 'iso9660' => ['application/x-cd-image', 'application/x-iso9660-image'], + 'it' => ['audio/x-it'], + 'it87' => ['application/x-it87'], + 'itp' => ['application/vnd.shana.informed.formtemplate'], + 'its' => ['application/its+xml'], + 'ivp' => ['application/vnd.immervision-ivp'], + 'ivu' => ['application/vnd.immervision-ivu'], + 'j2c' => ['image/x-jp2-codestream'], + 'j2k' => ['image/x-jp2-codestream'], + 'jad' => ['text/vnd.sun.j2me.app-descriptor'], + 'jade' => ['text/jade'], + 'jam' => ['application/vnd.jam'], + 'jar' => ['application/x-java-archive', 'application/java-archive', 'application/x-jar'], + 'jardiff' => ['application/x-java-archive-diff'], + 'java' => ['text/x-java', 'text/x-java-source'], + 'jceks' => ['application/x-java-jce-keystore'], + 'jhc' => ['image/jphc'], + 'jisp' => ['application/vnd.jisp'], + 'jks' => ['application/x-java-keystore'], + 'jls' => ['image/jls'], + 'jlt' => ['application/vnd.hp-jlyt'], + 'jng' => ['image/x-jng'], + 'jnlp' => ['application/x-java-jnlp-file'], + 'joda' => ['application/vnd.joost.joda-archive'], + 'jp2' => ['image/jp2', 'image/jpeg2000', 'image/jpeg2000-image', 'image/x-jpeg2000-image'], + 'jpc' => ['image/x-jp2-codestream'], + 'jpe' => ['image/jpeg', 'image/pjpeg'], + 'jpeg' => ['image/jpeg', 'image/pjpeg'], + 'jpf' => ['image/jpx'], + 'jpg' => ['image/jpeg', 'image/pjpeg'], + 'jpg2' => ['image/jp2', 'image/jpeg2000', 'image/jpeg2000-image', 'image/x-jpeg2000-image'], + 'jpgm' => ['image/jpm', 'video/jpm'], + 'jpgv' => ['video/jpeg'], + 'jph' => ['image/jph'], + 'jpm' => ['image/jpm', 'video/jpm'], + 'jpr' => ['application/x-jbuilder-project'], + 'jpx' => ['application/x-jbuilder-project', 'image/jpx'], + 'jrd' => ['application/jrd+json'], + 'js' => ['text/javascript', 'application/javascript', 'application/x-javascript'], + 'jsm' => ['application/javascript', 'application/x-javascript', 'text/javascript'], + 'json' => ['application/json', 'application/schema+json'], + 'json-patch' => ['application/json-patch+json'], + 'json5' => ['application/json5'], + 'jsonld' => ['application/ld+json'], + 'jsonml' => ['application/jsonml+json'], + 'jsx' => ['text/jsx'], + 'jxl' => ['image/jxl'], + 'jxr' => ['image/jxr'], + 'jxra' => ['image/jxra'], + 'jxrs' => ['image/jxrs'], + 'jxs' => ['image/jxs'], + 'jxsc' => ['image/jxsc'], + 'jxsi' => ['image/jxsi'], + 'jxss' => ['image/jxss'], + 'k25' => ['image/x-kodak-k25'], + 'k7' => ['application/x-thomson-cassette'], + 'kar' => ['audio/midi', 'audio/x-midi'], + 'karbon' => ['application/vnd.kde.karbon', 'application/x-karbon'], + 'kdbx' => ['application/x-keepass2'], + 'kdc' => ['image/x-kodak-kdc'], + 'kdelnk' => ['application/x-desktop', 'application/x-gnome-app-info'], + 'kexi' => ['application/x-kexiproject-sqlite', 'application/x-kexiproject-sqlite2', 'application/x-kexiproject-sqlite3', 'application/x-vnd.kde.kexi'], + 'kexic' => ['application/x-kexi-connectiondata'], + 'kexis' => ['application/x-kexiproject-shortcut'], + 'key' => ['application/vnd.apple.keynote', 'application/pgp-keys', 'application/x-iwork-keynote-sffkey'], + 'keynote' => ['application/vnd.apple.keynote'], + 'kfo' => ['application/vnd.kde.kformula', 'application/x-kformula'], + 'kfx' => ['application/vnd.amazon.mobi8-ebook', 'application/x-mobi8-ebook'], + 'kia' => ['application/vnd.kidspiration'], + 'kil' => ['application/x-killustrator'], + 'kino' => ['application/smil', 'application/smil+xml'], + 'kml' => ['application/vnd.google-earth.kml+xml'], + 'kmz' => ['application/vnd.google-earth.kmz'], + 'kne' => ['application/vnd.kinar'], + 'knp' => ['application/vnd.kinar'], + 'kon' => ['application/vnd.kde.kontour', 'application/x-kontour'], + 'kpm' => ['application/x-kpovmodeler'], + 'kpr' => ['application/vnd.kde.kpresenter', 'application/x-kpresenter'], + 'kpt' => ['application/vnd.kde.kpresenter', 'application/x-kpresenter'], + 'kpxx' => ['application/vnd.ds-keypoint'], + 'kra' => ['application/x-krita'], + 'krz' => ['application/x-krita'], + 'ks' => ['application/x-java-keystore'], + 'ksp' => ['application/vnd.kde.kspread', 'application/x-kspread'], + 'ksy' => ['text/x-kaitai-struct'], + 'kt' => ['text/x-kotlin'], + 'ktr' => ['application/vnd.kahootz'], + 'ktx' => ['image/ktx'], + 'ktx2' => ['image/ktx2'], + 'ktz' => ['application/vnd.kahootz'], + 'kud' => ['application/x-kugar'], + 'kwd' => ['application/vnd.kde.kword', 'application/x-kword'], + 'kwt' => ['application/vnd.kde.kword', 'application/x-kword'], + 'la' => ['application/x-shared-library-la'], + 'lasxml' => ['application/vnd.las.las+xml'], + 'latex' => ['application/x-latex', 'application/x-tex', 'text/x-tex'], + 'lbd' => ['application/vnd.llamagraphics.life-balance.desktop'], + 'lbe' => ['application/vnd.llamagraphics.life-balance.exchange+xml'], + 'lbm' => ['image/x-iff', 'image/x-ilbm'], + 'ldif' => ['text/x-ldif'], + 'les' => ['application/vnd.hhe.lesson-player'], + 'less' => ['text/less'], + 'lgr' => ['application/lgr+xml'], + 'lha' => ['application/x-lha', 'application/x-lzh-compressed'], + 'lhs' => ['text/x-literate-haskell'], + 'lhz' => ['application/x-lhz'], + 'link66' => ['application/vnd.route66.link66+xml'], + 'lisp' => ['text/x-common-lisp'], + 'list' => ['text/plain'], + 'list3820' => ['application/vnd.ibm.modcap'], + 'listafp' => ['application/vnd.ibm.modcap'], + 'litcoffee' => ['text/coffeescript'], + 'lnk' => ['application/x-ms-shortcut'], + 'lnx' => ['application/x-atari-lynx-rom'], + 'loas' => ['audio/usac'], + 'log' => ['text/plain', 'text/x-log'], + 'lostxml' => ['application/lost+xml'], + 'lrm' => ['application/vnd.ms-lrm'], + 'lrv' => ['video/mp4', 'video/mp4v-es', 'video/x-m4v'], + 'lrz' => ['application/x-lrzip'], + 'ltf' => ['application/vnd.frogans.ltf'], + 'ltx' => ['application/x-tex', 'text/x-tex'], + 'lua' => ['text/x-lua'], + 'luac' => ['application/x-lua-bytecode'], + 'lvp' => ['audio/vnd.lucent.voice'], + 'lwo' => ['image/x-lwo'], + 'lwob' => ['image/x-lwo'], + 'lwp' => ['application/vnd.lotus-wordpro'], + 'lws' => ['image/x-lws'], + 'ly' => ['text/x-lilypond'], + 'lyx' => ['application/x-lyx', 'text/x-lyx'], + 'lz' => ['application/x-lzip'], + 'lz4' => ['application/x-lz4'], + 'lzh' => ['application/x-lha', 'application/x-lzh-compressed'], + 'lzma' => ['application/x-lzma'], + 'lzo' => ['application/x-lzop'], + 'm' => ['text/x-matlab', 'text/x-objcsrc', 'text/x-octave'], + 'm13' => ['application/x-msmediaview'], + 'm14' => ['application/x-msmediaview'], + 'm15' => ['audio/x-mod'], + 'm1u' => ['video/vnd.mpegurl', 'video/x-mpegurl'], + 'm1v' => ['video/mpeg'], + 'm21' => ['application/mp21'], + 'm2a' => ['audio/mpeg'], + 'm2t' => ['video/mp2t'], + 'm2ts' => ['video/mp2t'], + 'm2v' => ['video/mpeg'], + 'm3a' => ['audio/mpeg'], + 'm3u' => ['audio/x-mpegurl', 'application/m3u', 'application/vnd.apple.mpegurl', 'audio/m3u', 'audio/mpegurl', 'audio/x-m3u', 'audio/x-mp3-playlist'], + 'm3u8' => ['application/m3u', 'application/vnd.apple.mpegurl', 'audio/m3u', 'audio/mpegurl', 'audio/x-m3u', 'audio/x-mp3-playlist', 'audio/x-mpegurl'], + 'm4' => ['application/x-m4'], + 'm4a' => ['audio/mp4', 'audio/m4a', 'audio/x-m4a'], + 'm4b' => ['audio/x-m4b'], + 'm4p' => ['application/mp4'], + 'm4r' => ['audio/x-m4r'], + 'm4s' => ['video/iso.segment'], + 'm4u' => ['video/vnd.mpegurl', 'video/x-mpegurl'], + 'm4v' => ['video/mp4', 'video/mp4v-es', 'video/x-m4v'], + 'm7' => ['application/x-thomson-cartridge-memo7'], + 'ma' => ['application/mathematica'], + 'mab' => ['application/x-markaby'], + 'mads' => ['application/mads+xml'], + 'maei' => ['application/mmt-aei+xml'], + 'mag' => ['application/vnd.ecowin.chart'], + 'mak' => ['text/x-makefile'], + 'maker' => ['application/vnd.framemaker'], + 'man' => ['application/x-troff-man', 'text/troff'], + 'manifest' => ['text/cache-manifest'], + 'map' => ['application/json'], + 'markdown' => ['text/markdown', 'text/x-markdown'], + 'mathml' => ['application/mathml+xml'], + 'mb' => ['application/mathematica'], + 'mbk' => ['application/vnd.mobius.mbk'], + 'mbox' => ['application/mbox'], + 'mc1' => ['application/vnd.medcalcdata'], + 'mc2' => ['text/vnd.senx.warpscript'], + 'mcd' => ['application/vnd.mcd'], + 'mcurl' => ['text/vnd.curl.mcurl'], + 'md' => ['text/markdown', 'text/x-markdown'], + 'mdb' => ['application/x-msaccess', 'application/mdb', 'application/msaccess', 'application/vnd.ms-access', 'application/vnd.msaccess', 'application/x-mdb', 'zz-application/zz-winassoc-mdb'], + 'mdi' => ['image/vnd.ms-modi'], + 'mdx' => ['application/x-genesis-32x-rom', 'text/mdx'], + 'me' => ['text/troff', 'text/x-troff-me'], + 'med' => ['audio/x-mod'], + 'mesh' => ['model/mesh'], + 'meta4' => ['application/metalink4+xml'], + 'metalink' => ['application/metalink+xml'], + 'mets' => ['application/mets+xml'], + 'mfm' => ['application/vnd.mfmp'], + 'mft' => ['application/rpki-manifest'], + 'mgp' => ['application/vnd.osgeo.mapguide.package', 'application/x-magicpoint'], + 'mgz' => ['application/vnd.proteus.magazine'], + 'mht' => ['application/x-mimearchive'], + 'mhtml' => ['application/x-mimearchive'], + 'mid' => ['audio/midi', 'audio/x-midi'], + 'midi' => ['audio/midi', 'audio/x-midi'], + 'mie' => ['application/x-mie'], + 'mif' => ['application/vnd.mif', 'application/x-mif'], + 'mime' => ['message/rfc822'], + 'minipsf' => ['audio/x-minipsf'], + 'mj2' => ['video/mj2'], + 'mjp2' => ['video/mj2'], + 'mjpeg' => ['video/x-mjpeg'], + 'mjpg' => ['video/x-mjpeg'], + 'mjs' => ['application/javascript', 'application/x-javascript', 'text/javascript'], + 'mk' => ['text/x-makefile'], + 'mk3d' => ['video/x-matroska', 'video/x-matroska-3d'], + 'mka' => ['audio/x-matroska'], + 'mkd' => ['text/markdown', 'text/x-markdown'], + 'mks' => ['video/x-matroska'], + 'mkv' => ['video/x-matroska'], + 'ml' => ['text/x-ocaml'], + 'mli' => ['text/x-ocaml'], + 'mlp' => ['application/vnd.dolby.mlp'], + 'mm' => ['text/x-troff-mm'], + 'mmd' => ['application/vnd.chipnuts.karaoke-mmd'], + 'mmf' => ['application/vnd.smaf', 'application/x-smaf'], + 'mml' => ['application/mathml+xml', 'text/mathml'], + 'mmr' => ['image/vnd.fujixerox.edmics-mmr'], + 'mng' => ['video/x-mng'], + 'mny' => ['application/x-msmoney'], + 'mo' => ['application/x-gettext-translation', 'text/x-modelica'], + 'mo3' => ['audio/x-mo3'], + 'mobi' => ['application/x-mobipocket-ebook'], + 'moc' => ['text/x-moc'], + 'mod' => ['application/x-object', 'audio/x-mod'], + 'mods' => ['application/mods+xml'], + 'mof' => ['text/x-mof'], + 'moov' => ['video/quicktime'], + 'mount' => ['text/x-systemd-unit'], + 'mov' => ['video/quicktime'], + 'movie' => ['video/x-sgi-movie'], + 'mp+' => ['audio/x-musepack'], + 'mp2' => ['audio/mp2', 'audio/mpeg', 'audio/x-mp2', 'video/mpeg', 'video/mpeg-system', 'video/x-mpeg', 'video/x-mpeg-system', 'video/x-mpeg2'], + 'mp21' => ['application/mp21'], + 'mp2a' => ['audio/mpeg'], + 'mp3' => ['audio/mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/x-mpeg', 'audio/x-mpg'], + 'mp4' => ['video/mp4', 'video/mp4v-es', 'video/x-m4v'], + 'mp4a' => ['audio/mp4'], + 'mp4s' => ['application/mp4'], + 'mp4v' => ['video/mp4'], + 'mpc' => ['application/vnd.mophun.certificate', 'audio/x-musepack'], + 'mpd' => ['application/dash+xml'], + 'mpe' => ['video/mpeg', 'video/mpeg-system', 'video/x-mpeg', 'video/x-mpeg-system', 'video/x-mpeg2'], + 'mpeg' => ['video/mpeg', 'video/mpeg-system', 'video/x-mpeg', 'video/x-mpeg-system', 'video/x-mpeg2'], + 'mpg' => ['video/mpeg', 'video/mpeg-system', 'video/x-mpeg', 'video/x-mpeg-system', 'video/x-mpeg2'], + 'mpg4' => ['video/mp4'], + 'mpga' => ['audio/mp3', 'audio/mpeg', 'audio/x-mp3', 'audio/x-mpeg', 'audio/x-mpg'], + 'mpkg' => ['application/vnd.apple.installer+xml'], + 'mpl' => ['video/mp2t'], + 'mpls' => ['video/mp2t'], + 'mpm' => ['application/vnd.blueice.multipass'], + 'mpn' => ['application/vnd.mophun.application'], + 'mpp' => ['application/vnd.ms-project', 'audio/x-musepack'], + 'mpt' => ['application/vnd.ms-project'], + 'mpy' => ['application/vnd.ibm.minipay'], + 'mqy' => ['application/vnd.mobius.mqy'], + 'mrc' => ['application/marc'], + 'mrcx' => ['application/marcxml+xml'], + 'mrl' => ['text/x-mrml'], + 'mrml' => ['text/x-mrml'], + 'mrw' => ['image/x-minolta-mrw'], + 'ms' => ['text/troff', 'text/x-troff-ms'], + 'mscml' => ['application/mediaservercontrol+xml'], + 'mseed' => ['application/vnd.fdsn.mseed'], + 'mseq' => ['application/vnd.mseq'], + 'msf' => ['application/vnd.epson.msf'], + 'msg' => ['application/vnd.ms-outlook'], + 'msh' => ['model/mesh'], + 'msi' => ['application/x-msdownload', 'application/x-msi'], + 'msl' => ['application/vnd.mobius.msl'], + 'msod' => ['image/x-msod'], + 'msty' => ['application/vnd.muvee.style'], + 'msx' => ['application/x-msx-rom'], + 'mtl' => ['model/mtl'], + 'mtm' => ['audio/x-mod'], + 'mts' => ['model/vnd.mts', 'video/mp2t'], + 'mup' => ['text/x-mup'], + 'mus' => ['application/vnd.musician'], + 'musd' => ['application/mmt-usd+xml'], + 'musicxml' => ['application/vnd.recordare.musicxml+xml'], + 'mvb' => ['application/x-msmediaview'], + 'mvt' => ['application/vnd.mapbox-vector-tile'], + 'mwf' => ['application/vnd.mfer'], + 'mxf' => ['application/mxf'], + 'mxl' => ['application/vnd.recordare.musicxml'], + 'mxmf' => ['audio/mobile-xmf'], + 'mxml' => ['application/xv+xml'], + 'mxs' => ['application/vnd.triscape.mxs'], + 'mxu' => ['video/vnd.mpegurl', 'video/x-mpegurl'], + 'n-gage' => ['application/vnd.nokia.n-gage.symbian.install'], + 'n3' => ['text/n3'], + 'n64' => ['application/x-n64-rom'], + 'nb' => ['application/mathematica', 'application/x-mathematica'], + 'nbp' => ['application/vnd.wolfram.player'], + 'nc' => ['application/x-netcdf'], + 'ncx' => ['application/x-dtbncx+xml'], + 'nds' => ['application/x-nintendo-ds-rom'], + 'nef' => ['image/x-nikon-nef'], + 'nes' => ['application/x-nes-rom'], + 'nez' => ['application/x-nes-rom'], + 'nfo' => ['text/x-nfo'], + 'ngc' => ['application/x-neo-geo-pocket-color-rom'], + 'ngdat' => ['application/vnd.nokia.n-gage.data'], + 'ngp' => ['application/x-neo-geo-pocket-rom'], + 'nitf' => ['application/vnd.nitf'], + 'nlu' => ['application/vnd.neurolanguage.nlu'], + 'nml' => ['application/vnd.enliven'], + 'nnd' => ['application/vnd.noblenet-directory'], + 'nns' => ['application/vnd.noblenet-sealer'], + 'nnw' => ['application/vnd.noblenet-web'], + 'not' => ['text/x-mup'], + 'npx' => ['image/vnd.net-fpx'], + 'nq' => ['application/n-quads'], + 'nrw' => ['image/x-nikon-nrw'], + 'nsc' => ['application/x-conference', 'application/x-netshow-channel'], + 'nsf' => ['application/vnd.lotus-notes'], + 'nsv' => ['video/x-nsv'], + 'nt' => ['application/n-triples'], + 'ntf' => ['application/vnd.nitf'], + 'numbers' => ['application/vnd.apple.numbers', 'application/x-iwork-numbers-sffnumbers'], + 'nzb' => ['application/x-nzb'], + 'o' => ['application/x-object'], + 'oa2' => ['application/vnd.fujitsu.oasys2'], + 'oa3' => ['application/vnd.fujitsu.oasys3'], + 'oas' => ['application/vnd.fujitsu.oasys'], + 'obd' => ['application/x-msbinder'], + 'obgx' => ['application/vnd.openblox.game+xml'], + 'obj' => ['application/x-tgif', 'model/obj'], + 'ocl' => ['text/x-ocl'], + 'oda' => ['application/oda'], + 'odb' => ['application/vnd.oasis.opendocument.database', 'application/vnd.sun.xml.base'], + 'odc' => ['application/vnd.oasis.opendocument.chart'], + 'odf' => ['application/vnd.oasis.opendocument.formula'], + 'odft' => ['application/vnd.oasis.opendocument.formula-template'], + 'odg' => ['application/vnd.oasis.opendocument.graphics'], + 'odi' => ['application/vnd.oasis.opendocument.image'], + 'odm' => ['application/vnd.oasis.opendocument.text-master'], + 'odp' => ['application/vnd.oasis.opendocument.presentation'], + 'ods' => ['application/vnd.oasis.opendocument.spreadsheet'], + 'odt' => ['application/vnd.oasis.opendocument.text'], + 'oga' => ['audio/ogg', 'audio/vorbis', 'audio/x-flac+ogg', 'audio/x-ogg', 'audio/x-oggflac', 'audio/x-speex+ogg', 'audio/x-vorbis', 'audio/x-vorbis+ogg'], + 'ogex' => ['model/vnd.opengex'], + 'ogg' => ['audio/ogg', 'audio/vorbis', 'audio/x-flac+ogg', 'audio/x-ogg', 'audio/x-oggflac', 'audio/x-speex+ogg', 'audio/x-vorbis', 'audio/x-vorbis+ogg', 'video/ogg', 'video/x-ogg', 'video/x-theora', 'video/x-theora+ogg'], + 'ogm' => ['video/x-ogm', 'video/x-ogm+ogg'], + 'ogv' => ['video/ogg', 'video/x-ogg'], + 'ogx' => ['application/ogg', 'application/x-ogg'], + 'old' => ['application/x-trash'], + 'oleo' => ['application/x-oleo'], + 'omdoc' => ['application/omdoc+xml'], + 'onepkg' => ['application/onenote'], + 'onetmp' => ['application/onenote'], + 'onetoc' => ['application/onenote'], + 'onetoc2' => ['application/onenote'], + 'ooc' => ['text/x-ooc'], + 'opf' => ['application/oebps-package+xml'], + 'opml' => ['text/x-opml', 'text/x-opml+xml'], + 'oprc' => ['application/vnd.palm', 'application/x-palm-database'], + 'opus' => ['audio/ogg', 'audio/x-ogg', 'audio/x-opus+ogg'], + 'ora' => ['image/openraster'], + 'orf' => ['image/x-olympus-orf'], + 'org' => ['application/vnd.lotus-organizer', 'text/org', 'text/x-org'], + 'osf' => ['application/vnd.yamaha.openscoreformat'], + 'osfpvg' => ['application/vnd.yamaha.openscoreformat.osfpvg+xml'], + 'osm' => ['application/vnd.openstreetmap.data+xml'], + 'otc' => ['application/vnd.oasis.opendocument.chart-template'], + 'otf' => ['application/vnd.oasis.opendocument.formula-template', 'application/x-font-otf', 'font/otf'], + 'otg' => ['application/vnd.oasis.opendocument.graphics-template'], + 'oth' => ['application/vnd.oasis.opendocument.text-web'], + 'oti' => ['application/vnd.oasis.opendocument.image-template'], + 'otp' => ['application/vnd.oasis.opendocument.presentation-template'], + 'ots' => ['application/vnd.oasis.opendocument.spreadsheet-template'], + 'ott' => ['application/vnd.oasis.opendocument.text-template'], + 'ova' => ['application/ovf', 'application/x-virtualbox-ova'], + 'ovf' => ['application/x-virtualbox-ovf'], + 'owl' => ['application/rdf+xml', 'text/rdf'], + 'owx' => ['application/owl+xml'], + 'oxps' => ['application/oxps'], + 'oxt' => ['application/vnd.openofficeorg.extension'], + 'p' => ['text/x-pascal'], + 'p10' => ['application/pkcs10'], + 'p12' => ['application/pkcs12', 'application/x-pkcs12'], + 'p65' => ['application/x-pagemaker'], + 'p7b' => ['application/x-pkcs7-certificates'], + 'p7c' => ['application/pkcs7-mime'], + 'p7m' => ['application/pkcs7-mime'], + 'p7r' => ['application/x-pkcs7-certreqresp'], + 'p7s' => ['application/pkcs7-signature'], + 'p8' => ['application/pkcs8'], + 'p8e' => ['application/pkcs8-encrypted'], + 'pac' => ['application/x-ns-proxy-autoconfig'], + 'pack' => ['application/x-java-pack200'], + 'pages' => ['application/vnd.apple.pages', 'application/x-iwork-pages-sffpages'], + 'pak' => ['application/x-pak'], + 'par2' => ['application/x-par2'], + 'part' => ['application/x-partial-download'], + 'pas' => ['text/x-pascal'], + 'pat' => ['image/x-gimp-pat'], + 'patch' => ['text/x-diff', 'text/x-patch'], + 'path' => ['text/x-systemd-unit'], + 'paw' => ['application/vnd.pawaafile'], + 'pbd' => ['application/vnd.powerbuilder6'], + 'pbm' => ['image/x-portable-bitmap'], + 'pcap' => ['application/pcap', 'application/vnd.tcpdump.pcap', 'application/x-pcap'], + 'pcd' => ['image/x-photo-cd'], + 'pce' => ['application/x-pc-engine-rom'], + 'pcf' => ['application/x-cisco-vpn-settings', 'application/x-font-pcf'], + 'pcf.Z' => ['application/x-font-pcf'], + 'pcf.gz' => ['application/x-font-pcf'], + 'pcl' => ['application/vnd.hp-pcl'], + 'pclxl' => ['application/vnd.hp-pclxl'], + 'pct' => ['image/x-pict'], + 'pcurl' => ['application/vnd.curl.pcurl'], + 'pcx' => ['image/vnd.zbrush.pcx', 'image/x-pcx'], + 'pdb' => ['application/vnd.palm', 'application/x-aportisdoc', 'application/x-palm-database', 'application/x-pilot'], + 'pdc' => ['application/x-aportisdoc'], + 'pde' => ['text/x-processing'], + 'pdf' => ['application/pdf', 'application/acrobat', 'application/nappdf', 'application/x-pdf', 'image/pdf'], + 'pdf.bz2' => ['application/x-bzpdf'], + 'pdf.gz' => ['application/x-gzpdf'], + 'pdf.lz' => ['application/x-lzpdf'], + 'pdf.xz' => ['application/x-xzpdf'], + 'pef' => ['image/x-pentax-pef'], + 'pem' => ['application/x-x509-ca-cert'], + 'perl' => ['application/x-perl', 'text/x-perl'], + 'pfa' => ['application/x-font-type1'], + 'pfb' => ['application/x-font-type1'], + 'pfm' => ['application/x-font-type1'], + 'pfr' => ['application/font-tdpfr'], + 'pfx' => ['application/pkcs12', 'application/x-pkcs12'], + 'pgm' => ['image/x-portable-graymap'], + 'pgn' => ['application/vnd.chess-pgn', 'application/x-chess-pgn'], + 'pgp' => ['application/pgp', 'application/pgp-encrypted', 'application/pgp-keys', 'application/pgp-signature'], + 'php' => ['application/x-php', 'application/x-httpd-php'], + 'php3' => ['application/x-php'], + 'php4' => ['application/x-php'], + 'php5' => ['application/x-php'], + 'phps' => ['application/x-php'], + 'pic' => ['image/x-pict'], + 'pict' => ['image/x-pict'], + 'pict1' => ['image/x-pict'], + 'pict2' => ['image/x-pict'], + 'pk' => ['application/x-tex-pk'], + 'pkg' => ['application/x-xar'], + 'pki' => ['application/pkixcmp'], + 'pkipath' => ['application/pkix-pkipath'], + 'pkpass' => ['application/vnd.apple.pkpass'], + 'pkr' => ['application/pgp-keys'], + 'pl' => ['application/x-perl', 'text/x-perl'], + 'pla' => ['audio/x-iriver-pla'], + 'plb' => ['application/vnd.3gpp.pic-bw-large'], + 'plc' => ['application/vnd.mobius.plc'], + 'plf' => ['application/vnd.pocketlearn'], + 'pln' => ['application/x-planperfect'], + 'pls' => ['application/pls', 'application/pls+xml', 'audio/scpls', 'audio/x-scpls'], + 'pm' => ['application/x-pagemaker', 'application/x-perl', 'text/x-perl'], + 'pm6' => ['application/x-pagemaker'], + 'pmd' => ['application/x-pagemaker'], + 'pml' => ['application/vnd.ctc-posml'], + 'png' => ['image/png'], + 'pnm' => ['image/x-portable-anymap'], + 'pntg' => ['image/x-macpaint'], + 'po' => ['application/x-gettext', 'text/x-gettext-translation', 'text/x-po'], + 'pod' => ['application/x-perl', 'text/x-perl'], + 'por' => ['application/x-spss-por'], + 'portpkg' => ['application/vnd.macports.portpkg'], + 'pot' => ['application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint', 'application/x-mspowerpoint', 'text/x-gettext-translation-template', 'text/x-pot'], + 'potm' => ['application/vnd.ms-powerpoint.template.macroenabled.12'], + 'potx' => ['application/vnd.openxmlformats-officedocument.presentationml.template'], + 'ppam' => ['application/vnd.ms-powerpoint.addin.macroenabled.12'], + 'ppd' => ['application/vnd.cups-ppd'], + 'ppm' => ['image/x-portable-pixmap'], + 'pps' => ['application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint', 'application/x-mspowerpoint'], + 'ppsm' => ['application/vnd.ms-powerpoint.slideshow.macroenabled.12'], + 'ppsx' => ['application/vnd.openxmlformats-officedocument.presentationml.slideshow'], + 'ppt' => ['application/vnd.ms-powerpoint', 'application/mspowerpoint', 'application/powerpoint', 'application/x-mspowerpoint'], + 'pptm' => ['application/vnd.ms-powerpoint.presentation.macroenabled.12'], + 'pptx' => ['application/vnd.openxmlformats-officedocument.presentationml.presentation'], + 'ppz' => ['application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint', 'application/x-mspowerpoint'], + 'pqa' => ['application/vnd.palm', 'application/x-palm-database'], + 'prc' => ['application/vnd.palm', 'application/x-mobipocket-ebook', 'application/x-palm-database', 'application/x-pilot'], + 'pre' => ['application/vnd.lotus-freelance'], + 'prf' => ['application/pics-rules'], + 'provx' => ['application/provenance+xml'], + 'ps' => ['application/postscript'], + 'ps.bz2' => ['application/x-bzpostscript'], + 'ps.gz' => ['application/x-gzpostscript'], + 'psb' => ['application/vnd.3gpp.pic-bw-small'], + 'psd' => ['application/photoshop', 'application/x-photoshop', 'image/photoshop', 'image/psd', 'image/vnd.adobe.photoshop', 'image/x-photoshop', 'image/x-psd'], + 'psf' => ['application/x-font-linux-psf', 'audio/x-psf'], + 'psf.gz' => ['application/x-gz-font-linux-psf'], + 'psflib' => ['audio/x-psflib'], + 'psid' => ['audio/prs.sid'], + 'pskcxml' => ['application/pskc+xml'], + 'psw' => ['application/x-pocket-word'], + 'pti' => ['image/prs.pti'], + 'ptid' => ['application/vnd.pvi.ptid1'], + 'pub' => ['application/vnd.ms-publisher', 'application/x-mspublisher'], + 'pvb' => ['application/vnd.3gpp.pic-bw-var'], + 'pw' => ['application/x-pw'], + 'pwn' => ['application/vnd.3m.post-it-notes'], + 'py' => ['text/x-python', 'text/x-python3'], + 'py3' => ['text/x-python3'], + 'py3x' => ['text/x-python3'], + 'pya' => ['audio/vnd.ms-playready.media.pya'], + 'pyc' => ['application/x-python-bytecode'], + 'pyi' => ['text/x-python3'], + 'pyo' => ['application/x-python-bytecode'], + 'pys' => ['application/x-pyspread-bz-spreadsheet'], + 'pysu' => ['application/x-pyspread-spreadsheet'], + 'pyv' => ['video/vnd.ms-playready.media.pyv'], + 'pyx' => ['text/x-python'], + 'qam' => ['application/vnd.epson.quickanime'], + 'qbo' => ['application/vnd.intu.qbo'], + 'qcow' => ['application/x-qemu-disk'], + 'qcow2' => ['application/x-qemu-disk'], + 'qd' => ['application/x-fd-file', 'application/x-raw-floppy-disk-image'], + 'qed' => ['application/x-qed-disk'], + 'qfx' => ['application/vnd.intu.qfx'], + 'qif' => ['application/x-qw', 'image/x-quicktime'], + 'qml' => ['text/x-qml'], + 'qmlproject' => ['text/x-qml'], + 'qmltypes' => ['text/x-qml'], + 'qp' => ['application/x-qpress'], + 'qps' => ['application/vnd.publishare-delta-tree'], + 'qt' => ['video/quicktime'], + 'qti' => ['application/x-qtiplot'], + 'qti.gz' => ['application/x-qtiplot'], + 'qtif' => ['image/x-quicktime'], + 'qtl' => ['application/x-quicktime-media-link', 'application/x-quicktimeplayer'], + 'qtvr' => ['video/quicktime'], + 'qwd' => ['application/vnd.quark.quarkxpress'], + 'qwt' => ['application/vnd.quark.quarkxpress'], + 'qxb' => ['application/vnd.quark.quarkxpress'], + 'qxd' => ['application/vnd.quark.quarkxpress'], + 'qxl' => ['application/vnd.quark.quarkxpress'], + 'qxt' => ['application/vnd.quark.quarkxpress'], + 'ra' => ['audio/vnd.m-realaudio', 'audio/vnd.rn-realaudio', 'audio/x-pn-realaudio', 'audio/x-realaudio'], + 'raf' => ['image/x-fuji-raf'], + 'ram' => ['application/ram', 'audio/x-pn-realaudio'], + 'raml' => ['application/raml+yaml'], + 'rapd' => ['application/route-apd+xml'], + 'rar' => ['application/x-rar-compressed', 'application/vnd.rar', 'application/x-rar'], + 'ras' => ['image/x-cmu-raster'], + 'raw' => ['image/x-panasonic-raw', 'image/x-panasonic-rw'], + 'raw-disk-image' => ['application/x-raw-disk-image'], + 'raw-disk-image.xz' => ['application/x-raw-disk-image-xz-compressed'], + 'rax' => ['audio/vnd.m-realaudio', 'audio/vnd.rn-realaudio', 'audio/x-pn-realaudio'], + 'rb' => ['application/x-ruby'], + 'rcprofile' => ['application/vnd.ipunplugged.rcprofile'], + 'rdf' => ['application/rdf+xml', 'text/rdf'], + 'rdfs' => ['application/rdf+xml', 'text/rdf'], + 'rdz' => ['application/vnd.data-vision.rdz'], + 'reg' => ['text/x-ms-regedit'], + 'rej' => ['application/x-reject', 'text/x-reject'], + 'relo' => ['application/p2p-overlay+xml'], + 'rep' => ['application/vnd.businessobjects'], + 'res' => ['application/x-dtbresource+xml'], + 'rgb' => ['image/x-rgb'], + 'rif' => ['application/reginfo+xml'], + 'rip' => ['audio/vnd.rip'], + 'ris' => ['application/x-research-info-systems'], + 'rl' => ['application/resource-lists+xml'], + 'rlc' => ['image/vnd.fujixerox.edmics-rlc'], + 'rld' => ['application/resource-lists-diff+xml'], + 'rle' => ['image/rle'], + 'rm' => ['application/vnd.rn-realmedia', 'application/vnd.rn-realmedia-vbr'], + 'rmi' => ['audio/midi'], + 'rmj' => ['application/vnd.rn-realmedia', 'application/vnd.rn-realmedia-vbr'], + 'rmm' => ['application/vnd.rn-realmedia', 'application/vnd.rn-realmedia-vbr'], + 'rmp' => ['audio/x-pn-realaudio-plugin'], + 'rms' => ['application/vnd.jcp.javame.midlet-rms', 'application/vnd.rn-realmedia', 'application/vnd.rn-realmedia-vbr'], + 'rmvb' => ['application/vnd.rn-realmedia', 'application/vnd.rn-realmedia-vbr'], + 'rmx' => ['application/vnd.rn-realmedia', 'application/vnd.rn-realmedia-vbr'], + 'rnc' => ['application/relax-ng-compact-syntax', 'application/x-rnc'], + 'rng' => ['application/xml', 'text/xml'], + 'roa' => ['application/rpki-roa'], + 'roff' => ['application/x-troff', 'text/troff', 'text/x-troff'], + 'ros' => ['text/x-common-lisp'], + 'rp' => ['image/vnd.rn-realpix'], + 'rp9' => ['application/vnd.cloanto.rp9'], + 'rpm' => ['application/x-redhat-package-manager', 'application/x-rpm'], + 'rpss' => ['application/vnd.nokia.radio-presets'], + 'rpst' => ['application/vnd.nokia.radio-preset'], + 'rq' => ['application/sparql-query'], + 'rs' => ['application/rls-services+xml', 'text/rust'], + 'rsat' => ['application/atsc-rsat+xml'], + 'rsd' => ['application/rsd+xml'], + 'rsheet' => ['application/urc-ressheet+xml'], + 'rss' => ['application/rss+xml', 'text/rss'], + 'rst' => ['text/x-rst'], + 'rt' => ['text/vnd.rn-realtext'], + 'rtf' => ['application/rtf', 'text/rtf'], + 'rtx' => ['text/richtext'], + 'run' => ['application/x-makeself'], + 'rusd' => ['application/route-usd+xml'], + 'rv' => ['video/vnd.rn-realvideo', 'video/x-real-video'], + 'rvx' => ['video/vnd.rn-realvideo', 'video/x-real-video'], + 'rw2' => ['image/x-panasonic-raw2', 'image/x-panasonic-rw2'], + 's' => ['text/x-asm'], + 's3m' => ['audio/s3m', 'audio/x-s3m'], + 'saf' => ['application/vnd.yamaha.smaf-audio'], + 'sage' => ['text/x-sagemath'], + 'sam' => ['application/x-amipro'], + 'sami' => ['application/x-sami'], + 'sap' => ['application/x-sap-file', 'application/x-thomson-sap-image'], + 'sass' => ['text/x-sass'], + 'sav' => ['application/x-spss-sav', 'application/x-spss-savefile'], + 'sbml' => ['application/sbml+xml'], + 'sc' => ['application/vnd.ibm.secure-container', 'text/x-scala'], + 'scala' => ['text/x-scala'], + 'scd' => ['application/x-msschedule'], + 'scm' => ['application/vnd.lotus-screencam', 'text/x-scheme'], + 'scope' => ['text/x-systemd-unit'], + 'scq' => ['application/scvp-cv-request'], + 'scs' => ['application/scvp-cv-response'], + 'scss' => ['text/x-scss'], + 'scurl' => ['text/vnd.curl.scurl'], + 'sda' => ['application/vnd.stardivision.draw'], + 'sdc' => ['application/vnd.stardivision.calc'], + 'sdd' => ['application/vnd.stardivision.impress'], + 'sdkd' => ['application/vnd.solent.sdkm+xml'], + 'sdkm' => ['application/vnd.solent.sdkm+xml'], + 'sdp' => ['application/sdp', 'application/vnd.sdp', 'application/vnd.stardivision.impress', 'application/x-sdp'], + 'sds' => ['application/vnd.stardivision.chart'], + 'sdw' => ['application/vnd.stardivision.writer', 'application/vnd.stardivision.writer-global'], + 'sea' => ['application/x-sea'], + 'see' => ['application/vnd.seemail'], + 'seed' => ['application/vnd.fdsn.seed'], + 'sema' => ['application/vnd.sema'], + 'semd' => ['application/vnd.semd'], + 'semf' => ['application/vnd.semf'], + 'senmlx' => ['application/senml+xml'], + 'sensmlx' => ['application/sensml+xml'], + 'ser' => ['application/java-serialized-object'], + 'service' => ['text/x-dbus-service', 'text/x-systemd-unit'], + 'setpay' => ['application/set-payment-initiation'], + 'setreg' => ['application/set-registration-initiation'], + 'sfc' => ['application/vnd.nintendo.snes.rom', 'application/x-snes-rom'], + 'sfd-hdstx' => ['application/vnd.hydrostatix.sof-data'], + 'sfs' => ['application/vnd.spotfire.sfs'], + 'sfv' => ['text/x-sfv'], + 'sg' => ['application/x-sg1000-rom'], + 'sgb' => ['application/x-gameboy-rom'], + 'sgd' => ['application/x-genesis-rom'], + 'sgf' => ['application/x-go-sgf'], + 'sgi' => ['image/sgi', 'image/x-sgi'], + 'sgl' => ['application/vnd.stardivision.writer', 'application/vnd.stardivision.writer-global'], + 'sgm' => ['text/sgml'], + 'sgml' => ['text/sgml'], + 'sh' => ['application/x-sh', 'application/x-shellscript', 'text/x-sh'], + 'shape' => ['application/x-dia-shape'], + 'shar' => ['application/x-shar'], + 'shex' => ['text/shex'], + 'shf' => ['application/shf+xml'], + 'shn' => ['application/x-shorten', 'audio/x-shorten'], + 'shtml' => ['text/html'], + 'siag' => ['application/x-siag'], + 'sid' => ['audio/prs.sid', 'image/x-mrsid-image'], + 'sieve' => ['application/sieve'], + 'sig' => ['application/pgp-signature'], + 'sik' => ['application/x-trash'], + 'sil' => ['audio/silk'], + 'silo' => ['model/mesh'], + 'sis' => ['application/vnd.symbian.install'], + 'sisx' => ['application/vnd.symbian.install', 'x-epoc/x-sisx-app'], + 'sit' => ['application/x-stuffit', 'application/stuffit', 'application/x-sit'], + 'sitx' => ['application/x-stuffitx'], + 'siv' => ['application/sieve'], + 'sk' => ['image/x-skencil'], + 'sk1' => ['image/x-skencil'], + 'skd' => ['application/vnd.koan'], + 'skm' => ['application/vnd.koan'], + 'skp' => ['application/vnd.koan'], + 'skr' => ['application/pgp-keys'], + 'skt' => ['application/vnd.koan'], + 'sldm' => ['application/vnd.ms-powerpoint.slide.macroenabled.12'], + 'sldx' => ['application/vnd.openxmlformats-officedocument.presentationml.slide'], + 'slice' => ['text/x-systemd-unit'], + 'slim' => ['text/slim'], + 'slk' => ['text/spreadsheet'], + 'slm' => ['text/slim'], + 'sls' => ['application/route-s-tsid+xml'], + 'slt' => ['application/vnd.epson.salt'], + 'sm' => ['application/vnd.stepmania.stepchart'], + 'smaf' => ['application/vnd.smaf', 'application/x-smaf'], + 'smc' => ['application/vnd.nintendo.snes.rom', 'application/x-snes-rom'], + 'smd' => ['application/vnd.stardivision.mail', 'application/x-genesis-rom'], + 'smf' => ['application/vnd.stardivision.math'], + 'smi' => ['application/smil', 'application/smil+xml', 'application/x-sami'], + 'smil' => ['application/smil', 'application/smil+xml'], + 'smk' => ['video/vnd.radgamettools.smacker'], + 'sml' => ['application/smil', 'application/smil+xml'], + 'sms' => ['application/x-sms-rom'], + 'smv' => ['video/x-smv'], + 'smzip' => ['application/vnd.stepmania.package'], + 'snap' => ['application/vnd.snap'], + 'snd' => ['audio/basic'], + 'snf' => ['application/x-font-snf'], + 'so' => ['application/x-sharedlib'], + 'socket' => ['text/x-systemd-unit'], + 'spc' => ['application/x-pkcs7-certificates'], + 'spd' => ['application/x-font-speedo'], + 'spdx' => ['text/spdx'], + 'spec' => ['text/x-rpm-spec'], + 'spf' => ['application/vnd.yamaha.smaf-phrase'], + 'spl' => ['application/futuresplash', 'application/vnd.adobe.flash.movie', 'application/x-futuresplash', 'application/x-shockwave-flash'], + 'spm' => ['application/x-source-rpm'], + 'spot' => ['text/vnd.in3d.spot'], + 'spp' => ['application/scvp-vp-response'], + 'spq' => ['application/scvp-vp-request'], + 'spx' => ['application/x-apple-systemprofiler+xml', 'audio/ogg', 'audio/x-speex', 'audio/x-speex+ogg'], + 'sql' => ['application/sql', 'application/x-sql', 'text/x-sql'], + 'sqlite2' => ['application/x-sqlite2'], + 'sqlite3' => ['application/vnd.sqlite3', 'application/x-sqlite3'], + 'sqsh' => ['application/vnd.squashfs'], + 'sr2' => ['image/x-sony-sr2'], + 'src' => ['application/x-wais-source'], + 'src.rpm' => ['application/x-source-rpm'], + 'srf' => ['image/x-sony-srf'], + 'srt' => ['application/x-srt', 'application/x-subrip'], + 'sru' => ['application/sru+xml'], + 'srx' => ['application/sparql-results+xml'], + 'ss' => ['text/x-scheme'], + 'ssa' => ['text/x-ssa'], + 'ssdl' => ['application/ssdl+xml'], + 'sse' => ['application/vnd.kodak-descriptor'], + 'ssf' => ['application/vnd.epson.ssf'], + 'ssml' => ['application/ssml+xml'], + 'st' => ['application/vnd.sailingtracker.track'], + 'stc' => ['application/vnd.sun.xml.calc.template'], + 'std' => ['application/vnd.sun.xml.draw.template'], + 'stf' => ['application/vnd.wt.stf'], + 'sti' => ['application/vnd.sun.xml.impress.template'], + 'stk' => ['application/hyperstudio'], + 'stl' => ['application/vnd.ms-pki.stl', 'model/stl', 'model/x.stl-ascii', 'model/x.stl-binary'], + 'stm' => ['audio/x-stm'], + 'stpxz' => ['model/step-xml+zip'], + 'stpz' => ['model/step+zip'], + 'str' => ['application/vnd.pg.format'], + 'stw' => ['application/vnd.sun.xml.writer.template'], + 'sty' => ['application/x-tex', 'text/x-tex'], + 'styl' => ['text/stylus'], + 'stylus' => ['text/stylus'], + 'sub' => ['image/vnd.dvb.subtitle', 'text/vnd.dvb.subtitle', 'text/x-microdvd', 'text/x-mpsub', 'text/x-subviewer'], + 'sun' => ['image/x-sun-raster'], + 'sus' => ['application/vnd.sus-calendar'], + 'susp' => ['application/vnd.sus-calendar'], + 'sv' => ['text/x-svsrc'], + 'sv4cpio' => ['application/x-sv4cpio'], + 'sv4crc' => ['application/x-sv4crc'], + 'svc' => ['application/vnd.dvb.service'], + 'svd' => ['application/vnd.svd'], + 'svg' => ['image/svg+xml', 'image/svg'], + 'svgz' => ['image/svg+xml', 'image/svg+xml-compressed'], + 'svh' => ['text/x-svhdr'], + 'swa' => ['application/x-director'], + 'swap' => ['text/x-systemd-unit'], + 'swf' => ['application/futuresplash', 'application/vnd.adobe.flash.movie', 'application/x-shockwave-flash'], + 'swi' => ['application/vnd.aristanetworks.swi'], + 'swidtag' => ['application/swid+xml'], + 'swm' => ['application/x-ms-wim'], + 'sxc' => ['application/vnd.sun.xml.calc'], + 'sxd' => ['application/vnd.sun.xml.draw'], + 'sxg' => ['application/vnd.sun.xml.writer.global'], + 'sxi' => ['application/vnd.sun.xml.impress'], + 'sxm' => ['application/vnd.sun.xml.math'], + 'sxw' => ['application/vnd.sun.xml.writer'], + 'sylk' => ['text/spreadsheet'], + 't' => ['application/x-perl', 'application/x-troff', 'text/troff', 'text/x-perl', 'text/x-troff'], + 't2t' => ['text/x-txt2tags'], + 't3' => ['application/x-t3vm-image'], + 't38' => ['image/t38'], + 'taglet' => ['application/vnd.mynfc'], + 'tao' => ['application/vnd.tao.intent-module-archive'], + 'tap' => ['image/vnd.tencent.tap'], + 'tar' => ['application/x-tar', 'application/x-gtar'], + 'tar.Z' => ['application/x-tarz'], + 'tar.bz' => ['application/x-bzip-compressed-tar'], + 'tar.bz2' => ['application/x-bzip-compressed-tar'], + 'tar.gz' => ['application/x-compressed-tar'], + 'tar.lrz' => ['application/x-lrzip-compressed-tar'], + 'tar.lz' => ['application/x-lzip-compressed-tar'], + 'tar.lz4' => ['application/x-lz4-compressed-tar'], + 'tar.lzma' => ['application/x-lzma-compressed-tar'], + 'tar.lzo' => ['application/x-tzo'], + 'tar.xz' => ['application/x-xz-compressed-tar'], + 'tar.zst' => ['application/x-zstd-compressed-tar'], + 'target' => ['text/x-systemd-unit'], + 'taz' => ['application/x-tarz'], + 'tb2' => ['application/x-bzip-compressed-tar'], + 'tbz' => ['application/x-bzip-compressed-tar'], + 'tbz2' => ['application/x-bzip-compressed-tar'], + 'tcap' => ['application/vnd.3gpp2.tcap'], + 'tcl' => ['application/x-tcl', 'text/tcl', 'text/x-tcl'], + 'td' => ['application/urc-targetdesc+xml'], + 'teacher' => ['application/vnd.smart.teacher'], + 'tei' => ['application/tei+xml'], + 'teicorpus' => ['application/tei+xml'], + 'tex' => ['application/x-tex', 'text/x-tex'], + 'texi' => ['application/x-texinfo', 'text/x-texinfo'], + 'texinfo' => ['application/x-texinfo', 'text/x-texinfo'], + 'text' => ['text/plain'], + 'tfi' => ['application/thraud+xml'], + 'tfm' => ['application/x-tex-tfm'], + 'tfx' => ['image/tiff-fx'], + 'tga' => ['application/tga', 'application/x-targa', 'application/x-tga', 'image/targa', 'image/tga', 'image/x-icb', 'image/x-targa', 'image/x-tga'], + 'tgz' => ['application/x-compressed-tar'], + 'theme' => ['application/x-theme'], + 'themepack' => ['application/x-windows-themepack'], + 'thmx' => ['application/vnd.ms-officetheme'], + 'tif' => ['image/tiff'], + 'tiff' => ['image/tiff'], + 'timer' => ['text/x-systemd-unit'], + 'tk' => ['application/x-tcl', 'text/tcl', 'text/x-tcl'], + 'tlrz' => ['application/x-lrzip-compressed-tar'], + 'tlz' => ['application/x-lzma-compressed-tar'], + 'tmo' => ['application/vnd.tmobile-livetv'], + 'tnef' => ['application/ms-tnef', 'application/vnd.ms-tnef'], + 'tnf' => ['application/ms-tnef', 'application/vnd.ms-tnef'], + 'toc' => ['application/x-cdrdao-toc'], + 'toml' => ['application/toml'], + 'torrent' => ['application/x-bittorrent'], + 'tpic' => ['application/tga', 'application/x-targa', 'application/x-tga', 'image/targa', 'image/tga', 'image/x-icb', 'image/x-targa', 'image/x-tga'], + 'tpl' => ['application/vnd.groove-tool-template'], + 'tpt' => ['application/vnd.trid.tpt'], + 'tr' => ['application/x-troff', 'text/troff', 'text/x-troff'], + 'tra' => ['application/vnd.trueapp'], + 'trig' => ['application/trig', 'application/x-trig'], + 'trm' => ['application/x-msterminal'], + 'ts' => ['application/x-linguist', 'text/vnd.qt.linguist', 'text/vnd.trolltech.linguist', 'video/mp2t'], + 'tsd' => ['application/timestamped-data'], + 'tsv' => ['text/tab-separated-values'], + 'tta' => ['audio/tta', 'audio/x-tta'], + 'ttc' => ['font/collection'], + 'ttf' => ['application/x-font-truetype', 'application/x-font-ttf', 'font/ttf'], + 'ttl' => ['text/turtle'], + 'ttml' => ['application/ttml+xml'], + 'ttx' => ['application/x-font-ttx'], + 'twd' => ['application/vnd.simtech-mindmapper'], + 'twds' => ['application/vnd.simtech-mindmapper'], + 'twig' => ['text/x-twig'], + 'txd' => ['application/vnd.genomatix.tuxedo'], + 'txf' => ['application/vnd.mobius.txf'], + 'txt' => ['text/plain'], + 'txz' => ['application/x-xz-compressed-tar'], + 'tzo' => ['application/x-tzo'], + 'tzst' => ['application/x-zstd-compressed-tar'], + 'u32' => ['application/x-authorware-bin'], + 'u8dsn' => ['message/global-delivery-status'], + 'u8hdr' => ['message/global-headers'], + 'u8mdn' => ['message/global-disposition-notification'], + 'u8msg' => ['message/global'], + 'ubj' => ['application/ubjson'], + 'udeb' => ['application/vnd.debian.binary-package', 'application/x-deb', 'application/x-debian-package'], + 'ufd' => ['application/vnd.ufdl'], + 'ufdl' => ['application/vnd.ufdl'], + 'ufraw' => ['application/x-ufraw'], + 'ui' => ['application/x-designer', 'application/x-gtk-builder'], + 'uil' => ['text/x-uil'], + 'ult' => ['audio/x-mod'], + 'ulx' => ['application/x-glulx'], + 'umj' => ['application/vnd.umajin'], + 'unf' => ['application/x-nes-rom'], + 'uni' => ['audio/x-mod'], + 'unif' => ['application/x-nes-rom'], + 'unityweb' => ['application/vnd.unity'], + 'uoml' => ['application/vnd.uoml+xml'], + 'uri' => ['text/uri-list'], + 'uris' => ['text/uri-list'], + 'url' => ['application/x-mswinurl'], + 'urls' => ['text/uri-list'], + 'usdz' => ['model/vnd.usdz+zip'], + 'ustar' => ['application/x-ustar'], + 'utz' => ['application/vnd.uiq.theme'], + 'uu' => ['text/x-uuencode'], + 'uue' => ['text/x-uuencode', 'zz-application/zz-winassoc-uu'], + 'uva' => ['audio/vnd.dece.audio'], + 'uvd' => ['application/vnd.dece.data'], + 'uvf' => ['application/vnd.dece.data'], + 'uvg' => ['image/vnd.dece.graphic'], + 'uvh' => ['video/vnd.dece.hd'], + 'uvi' => ['image/vnd.dece.graphic'], + 'uvm' => ['video/vnd.dece.mobile'], + 'uvp' => ['video/vnd.dece.pd'], + 'uvs' => ['video/vnd.dece.sd'], + 'uvt' => ['application/vnd.dece.ttml+xml'], + 'uvu' => ['video/vnd.uvvu.mp4'], + 'uvv' => ['video/vnd.dece.video'], + 'uvva' => ['audio/vnd.dece.audio'], + 'uvvd' => ['application/vnd.dece.data'], + 'uvvf' => ['application/vnd.dece.data'], + 'uvvg' => ['image/vnd.dece.graphic'], + 'uvvh' => ['video/vnd.dece.hd'], + 'uvvi' => ['image/vnd.dece.graphic'], + 'uvvm' => ['video/vnd.dece.mobile'], + 'uvvp' => ['video/vnd.dece.pd'], + 'uvvs' => ['video/vnd.dece.sd'], + 'uvvt' => ['application/vnd.dece.ttml+xml'], + 'uvvu' => ['video/vnd.uvvu.mp4'], + 'uvvv' => ['video/vnd.dece.video'], + 'uvvx' => ['application/vnd.dece.unspecified'], + 'uvvz' => ['application/vnd.dece.zip'], + 'uvx' => ['application/vnd.dece.unspecified'], + 'uvz' => ['application/vnd.dece.zip'], + 'v' => ['text/x-verilog'], + 'v64' => ['application/x-n64-rom'], + 'vala' => ['text/x-vala'], + 'vapi' => ['text/x-vala'], + 'vb' => ['application/x-virtual-boy-rom'], + 'vbox' => ['application/x-virtualbox-vbox'], + 'vbox-extpack' => ['application/x-virtualbox-vbox-extpack'], + 'vbs' => ['text/vbs', 'text/vbscript'], + 'vcard' => ['text/directory', 'text/vcard', 'text/x-vcard'], + 'vcd' => ['application/x-cdlink'], + 'vcf' => ['text/x-vcard', 'text/directory', 'text/vcard'], + 'vcg' => ['application/vnd.groove-vcard'], + 'vcs' => ['application/ics', 'text/calendar', 'text/x-vcalendar'], + 'vct' => ['text/directory', 'text/vcard', 'text/x-vcard'], + 'vcx' => ['application/vnd.vcx'], + 'vda' => ['application/tga', 'application/x-targa', 'application/x-tga', 'image/targa', 'image/tga', 'image/x-icb', 'image/x-targa', 'image/x-tga'], + 'vdi' => ['application/x-vdi-disk', 'application/x-virtualbox-vdi'], + 'vds' => ['model/vnd.sap.vds'], + 'vhd' => ['application/x-vhd-disk', 'application/x-virtualbox-vhd', 'text/x-vhdl'], + 'vhdl' => ['text/x-vhdl'], + 'vhdx' => ['application/x-vhdx-disk', 'application/x-virtualbox-vhdx'], + 'vis' => ['application/vnd.visionary'], + 'viv' => ['video/vivo', 'video/vnd.vivo'], + 'vivo' => ['video/vivo', 'video/vnd.vivo'], + 'vlc' => ['application/m3u', 'audio/m3u', 'audio/mpegurl', 'audio/x-m3u', 'audio/x-mp3-playlist', 'audio/x-mpegurl'], + 'vmdk' => ['application/x-virtualbox-vmdk', 'application/x-vmdk-disk'], + 'vob' => ['video/mpeg', 'video/mpeg-system', 'video/x-mpeg', 'video/x-mpeg-system', 'video/x-mpeg2', 'video/x-ms-vob'], + 'voc' => ['audio/x-voc'], + 'vor' => ['application/vnd.stardivision.writer', 'application/vnd.stardivision.writer-global'], + 'vox' => ['application/x-authorware-bin'], + 'vpc' => ['application/x-vhd-disk', 'application/x-virtualbox-vhd'], + 'vrm' => ['model/vrml'], + 'vrml' => ['model/vrml'], + 'vsd' => ['application/vnd.visio'], + 'vsdm' => ['application/vnd.ms-visio.drawing.macroenabled.main+xml'], + 'vsdx' => ['application/vnd.ms-visio.drawing.main+xml'], + 'vsf' => ['application/vnd.vsf'], + 'vss' => ['application/vnd.visio'], + 'vssm' => ['application/vnd.ms-visio.stencil.macroenabled.main+xml'], + 'vssx' => ['application/vnd.ms-visio.stencil.main+xml'], + 'vst' => ['application/tga', 'application/vnd.visio', 'application/x-targa', 'application/x-tga', 'image/targa', 'image/tga', 'image/x-icb', 'image/x-targa', 'image/x-tga'], + 'vstm' => ['application/vnd.ms-visio.template.macroenabled.main+xml'], + 'vstx' => ['application/vnd.ms-visio.template.main+xml'], + 'vsw' => ['application/vnd.visio'], + 'vtf' => ['image/vnd.valve.source.texture'], + 'vtt' => ['text/vtt'], + 'vtu' => ['model/vnd.vtu'], + 'vxml' => ['application/voicexml+xml'], + 'w3d' => ['application/x-director'], + 'wad' => ['application/x-doom', 'application/x-doom-wad', 'application/x-wii-wad'], + 'wadl' => ['application/vnd.sun.wadl+xml'], + 'war' => ['application/java-archive'], + 'wasm' => ['application/wasm'], + 'wav' => ['audio/wav', 'audio/vnd.wave', 'audio/wave', 'audio/x-wav'], + 'wax' => ['application/x-ms-asx', 'audio/x-ms-asx', 'audio/x-ms-wax', 'video/x-ms-wax', 'video/x-ms-wmx', 'video/x-ms-wvx'], + 'wb1' => ['application/x-quattropro'], + 'wb2' => ['application/x-quattropro'], + 'wb3' => ['application/x-quattropro'], + 'wbmp' => ['image/vnd.wap.wbmp'], + 'wbs' => ['application/vnd.criticaltools.wbs+xml'], + 'wbxml' => ['application/vnd.wap.wbxml'], + 'wcm' => ['application/vnd.ms-works'], + 'wdb' => ['application/vnd.ms-works'], + 'wdp' => ['image/vnd.ms-photo'], + 'weba' => ['audio/webm'], + 'webapp' => ['application/x-web-app-manifest+json'], + 'webm' => ['video/webm'], + 'webmanifest' => ['application/manifest+json'], + 'webp' => ['image/webp'], + 'wg' => ['application/vnd.pmi.widget'], + 'wgt' => ['application/widget'], + 'wim' => ['application/x-ms-wim'], + 'wk1' => ['application/lotus123', 'application/vnd.lotus-1-2-3', 'application/wk1', 'application/x-123', 'application/x-lotus123', 'zz-application/zz-winassoc-123'], + 'wk3' => ['application/lotus123', 'application/vnd.lotus-1-2-3', 'application/wk1', 'application/x-123', 'application/x-lotus123', 'zz-application/zz-winassoc-123'], + 'wk4' => ['application/lotus123', 'application/vnd.lotus-1-2-3', 'application/wk1', 'application/x-123', 'application/x-lotus123', 'zz-application/zz-winassoc-123'], + 'wkdownload' => ['application/x-partial-download'], + 'wks' => ['application/lotus123', 'application/vnd.lotus-1-2-3', 'application/vnd.ms-works', 'application/wk1', 'application/x-123', 'application/x-lotus123', 'zz-application/zz-winassoc-123'], + 'wm' => ['video/x-ms-wm'], + 'wma' => ['audio/x-ms-wma', 'audio/wma'], + 'wmd' => ['application/x-ms-wmd'], + 'wmf' => ['application/wmf', 'application/x-msmetafile', 'application/x-wmf', 'image/wmf', 'image/x-win-metafile', 'image/x-wmf'], + 'wml' => ['text/vnd.wap.wml'], + 'wmlc' => ['application/vnd.wap.wmlc'], + 'wmls' => ['text/vnd.wap.wmlscript'], + 'wmlsc' => ['application/vnd.wap.wmlscriptc'], + 'wmv' => ['audio/x-ms-wmv', 'video/x-ms-wmv'], + 'wmx' => ['application/x-ms-asx', 'audio/x-ms-asx', 'video/x-ms-wax', 'video/x-ms-wmx', 'video/x-ms-wvx'], + 'wmz' => ['application/x-ms-wmz', 'application/x-msmetafile'], + 'woff' => ['application/font-woff', 'application/x-font-woff', 'font/woff'], + 'woff2' => ['font/woff2'], + 'wp' => ['application/vnd.wordperfect', 'application/wordperfect', 'application/x-wordperfect'], + 'wp4' => ['application/vnd.wordperfect', 'application/wordperfect', 'application/x-wordperfect'], + 'wp5' => ['application/vnd.wordperfect', 'application/wordperfect', 'application/x-wordperfect'], + 'wp6' => ['application/vnd.wordperfect', 'application/wordperfect', 'application/x-wordperfect'], + 'wpd' => ['application/vnd.wordperfect', 'application/wordperfect', 'application/x-wordperfect'], + 'wpg' => ['application/x-wpg'], + 'wpl' => ['application/vnd.ms-wpl'], + 'wpp' => ['application/vnd.wordperfect', 'application/wordperfect', 'application/x-wordperfect'], + 'wps' => ['application/vnd.ms-works'], + 'wqd' => ['application/vnd.wqd'], + 'wri' => ['application/x-mswrite'], + 'wrl' => ['model/vrml'], + 'ws' => ['application/x-wonderswan-rom'], + 'wsc' => ['application/x-wonderswan-color-rom', 'message/vnd.wfa.wsc'], + 'wsdl' => ['application/wsdl+xml'], + 'wsgi' => ['text/x-python'], + 'wspolicy' => ['application/wspolicy+xml'], + 'wtb' => ['application/vnd.webturbo'], + 'wv' => ['audio/x-wavpack'], + 'wvc' => ['audio/x-wavpack-correction'], + 'wvp' => ['audio/x-wavpack'], + 'wvx' => ['application/x-ms-asx', 'audio/x-ms-asx', 'video/x-ms-wax', 'video/x-ms-wmx', 'video/x-ms-wvx'], + 'wwf' => ['application/wwf', 'application/x-wwf'], + 'x32' => ['application/x-authorware-bin'], + 'x3d' => ['model/x3d+xml'], + 'x3db' => ['model/x3d+binary', 'model/x3d+fastinfoset'], + 'x3dbz' => ['model/x3d+binary'], + 'x3dv' => ['model/x3d+vrml', 'model/x3d-vrml'], + 'x3dvz' => ['model/x3d+vrml'], + 'x3dz' => ['model/x3d+xml'], + 'x3f' => ['image/x-sigma-x3f'], + 'x_b' => ['model/vnd.parasolid.transmit.binary'], + 'x_t' => ['model/vnd.parasolid.transmit.text'], + 'xac' => ['application/x-gnucash'], + 'xaml' => ['application/xaml+xml'], + 'xap' => ['application/x-silverlight-app'], + 'xar' => ['application/vnd.xara', 'application/x-xar'], + 'xav' => ['application/xcap-att+xml'], + 'xbap' => ['application/x-ms-xbap'], + 'xbd' => ['application/vnd.fujixerox.docuworks.binder'], + 'xbel' => ['application/x-xbel'], + 'xbl' => ['application/xml', 'text/xml'], + 'xbm' => ['image/x-xbitmap'], + 'xca' => ['application/xcap-caps+xml'], + 'xcf' => ['image/x-xcf'], + 'xcf.bz2' => ['image/x-compressed-xcf'], + 'xcf.gz' => ['image/x-compressed-xcf'], + 'xcs' => ['application/calendar+xml'], + 'xdf' => ['application/mrb-consumer+xml', 'application/mrb-publish+xml', 'application/xcap-diff+xml'], + 'xdgapp' => ['application/vnd.flatpak', 'application/vnd.xdgapp'], + 'xdm' => ['application/vnd.syncml.dm+xml'], + 'xdp' => ['application/vnd.adobe.xdp+xml'], + 'xdssc' => ['application/dssc+xml'], + 'xdw' => ['application/vnd.fujixerox.docuworks'], + 'xel' => ['application/xcap-el+xml'], + 'xenc' => ['application/xenc+xml'], + 'xer' => ['application/patch-ops-error+xml', 'application/xcap-error+xml'], + 'xfdf' => ['application/vnd.adobe.xfdf'], + 'xfdl' => ['application/vnd.xfdl'], + 'xhe' => ['audio/usac'], + 'xht' => ['application/xhtml+xml'], + 'xhtml' => ['application/xhtml+xml'], + 'xhvml' => ['application/xv+xml'], + 'xi' => ['audio/x-xi'], + 'xif' => ['image/vnd.xiff'], + 'xla' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xlam' => ['application/vnd.ms-excel.addin.macroenabled.12'], + 'xlc' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xld' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xlf' => ['application/x-xliff', 'application/x-xliff+xml', 'application/xliff+xml'], + 'xliff' => ['application/x-xliff', 'application/xliff+xml'], + 'xll' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xlm' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xlr' => ['application/vnd.ms-works'], + 'xls' => ['application/vnd.ms-excel', 'application/msexcel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xlsb' => ['application/vnd.ms-excel.sheet.binary.macroenabled.12'], + 'xlsm' => ['application/vnd.ms-excel.sheet.macroenabled.12'], + 'xlsx' => ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], + 'xlt' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xltm' => ['application/vnd.ms-excel.template.macroenabled.12'], + 'xltx' => ['application/vnd.openxmlformats-officedocument.spreadsheetml.template'], + 'xlw' => ['application/msexcel', 'application/vnd.ms-excel', 'application/x-msexcel', 'zz-application/zz-winassoc-xls'], + 'xm' => ['audio/x-xm', 'audio/xm'], + 'xmf' => ['audio/mobile-xmf', 'audio/x-xmf', 'audio/xmf'], + 'xmi' => ['text/x-xmi'], + 'xml' => ['application/xml', 'text/xml'], + 'xns' => ['application/xcap-ns+xml'], + 'xo' => ['application/vnd.olpc-sugar'], + 'xop' => ['application/xop+xml'], + 'xpi' => ['application/x-xpinstall'], + 'xpl' => ['application/xproc+xml'], + 'xpm' => ['image/x-xpixmap', 'image/x-xpm'], + 'xpr' => ['application/vnd.is-xpr'], + 'xps' => ['application/vnd.ms-xpsdocument', 'application/xps'], + 'xpw' => ['application/vnd.intercon.formnet'], + 'xpx' => ['application/vnd.intercon.formnet'], + 'xsd' => ['application/xml', 'text/xml'], + 'xsl' => ['application/xml', 'application/xslt+xml'], + 'xslfo' => ['text/x-xslfo'], + 'xslt' => ['application/xslt+xml'], + 'xsm' => ['application/vnd.syncml+xml'], + 'xspf' => ['application/x-xspf+xml', 'application/xspf+xml'], + 'xul' => ['application/vnd.mozilla.xul+xml'], + 'xvm' => ['application/xv+xml'], + 'xvml' => ['application/xv+xml'], + 'xwd' => ['image/x-xwindowdump'], + 'xyz' => ['chemical/x-xyz'], + 'xz' => ['application/x-xz'], + 'yaml' => ['application/x-yaml', 'text/x-yaml', 'text/yaml'], + 'yang' => ['application/yang'], + 'yin' => ['application/yin+xml'], + 'yml' => ['application/x-yaml', 'text/x-yaml', 'text/yaml'], + 'ymp' => ['text/x-suse-ymp'], + 'yt' => ['application/vnd.youtube.yt'], + 'z1' => ['application/x-zmachine'], + 'z2' => ['application/x-zmachine'], + 'z3' => ['application/x-zmachine'], + 'z4' => ['application/x-zmachine'], + 'z5' => ['application/x-zmachine'], + 'z6' => ['application/x-zmachine'], + 'z64' => ['application/x-n64-rom'], + 'z7' => ['application/x-zmachine'], + 'z8' => ['application/x-zmachine'], + 'zabw' => ['application/x-abiword'], + 'zaz' => ['application/vnd.zzazz.deck+xml'], + 'zip' => ['application/zip', 'application/x-zip', 'application/x-zip-compressed'], + 'zir' => ['application/vnd.zul'], + 'zirz' => ['application/vnd.zul'], + 'zmm' => ['application/vnd.handheld-entertainment+xml'], + 'zoo' => ['application/x-zoo'], + 'zsav' => ['application/x-spss-sav', 'application/x-spss-savefile'], + 'zst' => ['application/zstd'], + 'zz' => ['application/zlib'], + '123' => ['application/lotus123', 'application/vnd.lotus-1-2-3', 'application/wk1', 'application/x-123', 'application/x-lotus123', 'zz-application/zz-winassoc-123'], + '602' => ['application/x-t602'], + '669' => ['audio/x-mod'], + ]; +} diff --git a/php/libraries/composer/vendor/symfony/mime/MimeTypesInterface.php b/php/libraries/composer/vendor/symfony/mime/MimeTypesInterface.php new file mode 100644 index 0000000..17d45ad --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/MimeTypesInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime; + +/** + * @author Fabien Potencier + */ +interface MimeTypesInterface extends MimeTypeGuesserInterface +{ + /** + * Gets the extensions for the given MIME type in decreasing order of preference. + * + * @return string[] + */ + public function getExtensions(string $mimeType): array; + + /** + * Gets the MIME types for the given extension in decreasing order of preference. + * + * @return string[] + */ + public function getMimeTypes(string $ext): array; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/AbstractMultipartPart.php b/php/libraries/composer/vendor/symfony/mime/Part/AbstractMultipartPart.php new file mode 100644 index 0000000..685d250 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/AbstractMultipartPart.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part; + +use Symfony\Component\Mime\Header\Headers; + +/** + * @author Fabien Potencier + */ +abstract class AbstractMultipartPart extends AbstractPart +{ + private $boundary; + private $parts = []; + + public function __construct(AbstractPart ...$parts) + { + parent::__construct(); + + foreach ($parts as $part) { + $this->parts[] = $part; + } + } + + /** + * @return AbstractPart[] + */ + public function getParts(): array + { + return $this->parts; + } + + public function getMediaType(): string + { + return 'multipart'; + } + + public function getPreparedHeaders(): Headers + { + $headers = parent::getPreparedHeaders(); + $headers->setHeaderParameter('Content-Type', 'boundary', $this->getBoundary()); + + return $headers; + } + + public function bodyToString(): string + { + $parts = $this->getParts(); + $string = ''; + foreach ($parts as $part) { + $string .= '--'.$this->getBoundary()."\r\n".$part->toString()."\r\n"; + } + $string .= '--'.$this->getBoundary()."--\r\n"; + + return $string; + } + + public function bodyToIterable(): iterable + { + $parts = $this->getParts(); + foreach ($parts as $part) { + yield '--'.$this->getBoundary()."\r\n"; + yield from $part->toIterable(); + yield "\r\n"; + } + yield '--'.$this->getBoundary()."--\r\n"; + } + + public function asDebugString(): string + { + $str = parent::asDebugString(); + foreach ($this->getParts() as $part) { + $lines = explode("\n", $part->asDebugString()); + $str .= "\n └ ".array_shift($lines); + foreach ($lines as $line) { + $str .= "\n |".$line; + } + } + + return $str; + } + + private function getBoundary(): string + { + if (null === $this->boundary) { + $this->boundary = strtr(base64_encode(random_bytes(6)), '+/', '-_'); + } + + return $this->boundary; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/AbstractPart.php b/php/libraries/composer/vendor/symfony/mime/Part/AbstractPart.php new file mode 100644 index 0000000..93892d9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/AbstractPart.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part; + +use Symfony\Component\Mime\Header\Headers; + +/** + * @author Fabien Potencier + */ +abstract class AbstractPart +{ + private $headers; + + public function __construct() + { + $this->headers = new Headers(); + } + + public function getHeaders(): Headers + { + return $this->headers; + } + + public function getPreparedHeaders(): Headers + { + $headers = clone $this->headers; + $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype()); + + return $headers; + } + + public function toString(): string + { + return $this->getPreparedHeaders()->toString()."\r\n".$this->bodyToString(); + } + + public function toIterable(): iterable + { + yield $this->getPreparedHeaders()->toString(); + yield "\r\n"; + yield from $this->bodyToIterable(); + } + + public function asDebugString(): string + { + return $this->getMediaType().'/'.$this->getMediaSubtype(); + } + + abstract public function bodyToString(): string; + + abstract public function bodyToIterable(): iterable; + + abstract public function getMediaType(): string; + + abstract public function getMediaSubtype(): string; +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/DataPart.php b/php/libraries/composer/vendor/symfony/mime/Part/DataPart.php new file mode 100644 index 0000000..3219df4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/DataPart.php @@ -0,0 +1,183 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part; + +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Header\Headers; +use Symfony\Component\Mime\MimeTypes; + +/** + * @author Fabien Potencier + */ +class DataPart extends TextPart +{ + /** @internal */ + protected $_parent; + + private static $mimeTypes; + + private $filename; + private $mediaType; + private $cid; + private $handle; + + /** + * @param resource|string $body + */ + public function __construct($body, ?string $filename = null, ?string $contentType = null, ?string $encoding = null) + { + unset($this->_parent); + + if (null === $contentType) { + $contentType = 'application/octet-stream'; + } + [$this->mediaType, $subtype] = explode('/', $contentType); + + parent::__construct($body, null, $subtype, $encoding); + + if (null !== $filename) { + $this->filename = $filename; + $this->setName($filename); + } + $this->setDisposition('attachment'); + } + + public static function fromPath(string $path, ?string $name = null, ?string $contentType = null): self + { + if (null === $contentType) { + $ext = strtolower(substr($path, strrpos($path, '.') + 1)); + if (null === self::$mimeTypes) { + self::$mimeTypes = new MimeTypes(); + } + $contentType = self::$mimeTypes->getMimeTypes($ext)[0] ?? 'application/octet-stream'; + } + + if ((is_file($path) && !is_readable($path)) || is_dir($path)) { + throw new InvalidArgumentException(sprintf('Path "%s" is not readable.', $path)); + } + + if (false === $handle = @fopen($path, 'r', false)) { + throw new InvalidArgumentException(sprintf('Unable to open path "%s".', $path)); + } + + if (!is_file($path)) { + $cache = fopen('php://temp', 'r+'); + stream_copy_to_stream($handle, $cache); + $handle = $cache; + } + + $p = new self($handle, $name ?: basename($path), $contentType); + $p->handle = $handle; + + return $p; + } + + /** + * @return $this + */ + public function asInline() + { + return $this->setDisposition('inline'); + } + + public function getContentId(): string + { + return $this->cid ?: $this->cid = $this->generateContentId(); + } + + public function hasContentId(): bool + { + return null !== $this->cid; + } + + public function getMediaType(): string + { + return $this->mediaType; + } + + public function getPreparedHeaders(): Headers + { + $headers = parent::getPreparedHeaders(); + + if (null !== $this->cid) { + $headers->setHeaderBody('Id', 'Content-ID', $this->cid); + } + + if (null !== $this->filename) { + $headers->setHeaderParameter('Content-Disposition', 'filename', $this->filename); + } + + return $headers; + } + + public function asDebugString(): string + { + $str = parent::asDebugString(); + if (null !== $this->filename) { + $str .= ' filename: '.$this->filename; + } + + return $str; + } + + private function generateContentId(): string + { + return bin2hex(random_bytes(16)).'@symfony'; + } + + public function __destruct() + { + if (null !== $this->handle && \is_resource($this->handle)) { + fclose($this->handle); + } + } + + /** + * @return array + */ + public function __sleep() + { + // converts the body to a string + parent::__sleep(); + + $this->_parent = []; + foreach (['body', 'charset', 'subtype', 'disposition', 'name', 'encoding'] as $name) { + $r = new \ReflectionProperty(TextPart::class, $name); + $r->setAccessible(true); + $this->_parent[$name] = $r->getValue($this); + } + $this->_headers = $this->getHeaders(); + + return ['_headers', '_parent', 'filename', 'mediaType']; + } + + public function __wakeup() + { + $r = new \ReflectionProperty(AbstractPart::class, 'headers'); + $r->setAccessible(true); + $r->setValue($this, $this->_headers); + unset($this->_headers); + + if (!\is_array($this->_parent)) { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + foreach (['body', 'charset', 'subtype', 'disposition', 'name', 'encoding'] as $name) { + if (null !== $this->_parent[$name] && !\is_string($this->_parent[$name])) { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + $r = new \ReflectionProperty(TextPart::class, $name); + $r->setAccessible(true); + $r->setValue($this, $this->_parent[$name]); + } + unset($this->_parent); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/MessagePart.php b/php/libraries/composer/vendor/symfony/mime/Part/MessagePart.php new file mode 100644 index 0000000..00129b4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/MessagePart.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\Mime\Part; + +use Symfony\Component\Mime\Message; +use Symfony\Component\Mime\RawMessage; + +/** + * @final + * + * @author Fabien Potencier + */ +class MessagePart extends DataPart +{ + private $message; + + public function __construct(RawMessage $message) + { + if ($message instanceof Message) { + $name = $message->getHeaders()->getHeaderBody('Subject').'.eml'; + } else { + $name = 'email.eml'; + } + parent::__construct('', $name); + + $this->message = $message; + } + + public function getMediaType(): string + { + return 'message'; + } + + public function getMediaSubtype(): string + { + return 'rfc822'; + } + + public function getBody(): string + { + return $this->message->toString(); + } + + public function bodyToString(): string + { + return $this->getBody(); + } + + public function bodyToIterable(): iterable + { + return $this->message->toIterable(); + } + + /** + * @return array + */ + public function __sleep() + { + return ['message']; + } + + public function __wakeup() + { + $this->__construct($this->message); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/Multipart/AlternativePart.php b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/AlternativePart.php new file mode 100644 index 0000000..fd75423 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/AlternativePart.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part\Multipart; + +use Symfony\Component\Mime\Part\AbstractMultipartPart; + +/** + * @author Fabien Potencier + */ +final class AlternativePart extends AbstractMultipartPart +{ + public function getMediaSubtype(): string + { + return 'alternative'; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/Multipart/DigestPart.php b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/DigestPart.php new file mode 100644 index 0000000..27537f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/DigestPart.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part\Multipart; + +use Symfony\Component\Mime\Part\AbstractMultipartPart; +use Symfony\Component\Mime\Part\MessagePart; + +/** + * @author Fabien Potencier + */ +final class DigestPart extends AbstractMultipartPart +{ + public function __construct(MessagePart ...$parts) + { + parent::__construct(...$parts); + } + + public function getMediaSubtype(): string + { + return 'digest'; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/Multipart/FormDataPart.php b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/FormDataPart.php new file mode 100644 index 0000000..e3c9afc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/FormDataPart.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part\Multipart; + +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Part\AbstractMultipartPart; +use Symfony\Component\Mime\Part\DataPart; +use Symfony\Component\Mime\Part\TextPart; + +/** + * Implements RFC 7578. + * + * @author Fabien Potencier + */ +final class FormDataPart extends AbstractMultipartPart +{ + private $fields = []; + + /** + * @param array $fields + */ + public function __construct(array $fields = []) + { + parent::__construct(); + + foreach ($fields as $name => $value) { + if (!\is_string($value) && !\is_array($value) && !$value instanceof TextPart) { + throw new InvalidArgumentException(sprintf('A form field value can only be a string, an array, or an instance of TextPart ("%s" given).', get_debug_type($value))); + } + + $this->fields[$name] = $value; + } + // HTTP does not support \r\n in header values + $this->getHeaders()->setMaxLineLength(\PHP_INT_MAX); + } + + public function getMediaSubtype(): string + { + return 'form-data'; + } + + public function getParts(): array + { + return $this->prepareFields($this->fields); + } + + private function prepareFields(array $fields): array + { + $values = []; + + $prepare = function ($item, $key, $root = null) use (&$values, &$prepare) { + if (null === $root && \is_int($key) && \is_array($item)) { + if (1 !== \count($item)) { + throw new InvalidArgumentException(sprintf('Form field values with integer keys can only have one array element, the key being the field name and the value being the field value, %d provided.', \count($item))); + } + + $key = key($item); + $item = $item[$key]; + } + + $fieldName = null !== $root ? sprintf('%s[%s]', $root, $key) : $key; + + if (\is_array($item)) { + array_walk($item, $prepare, $fieldName); + + return; + } + + $values[] = $this->preparePart($fieldName, $item); + }; + + array_walk($fields, $prepare); + + return $values; + } + + private function preparePart(string $name, $value): TextPart + { + if (\is_string($value)) { + return $this->configurePart($name, new TextPart($value, 'utf-8', 'plain', '8bit')); + } + + return $this->configurePart($name, $value); + } + + private function configurePart(string $name, TextPart $part): TextPart + { + static $r; + + if (null === $r) { + $r = new \ReflectionProperty(TextPart::class, 'encoding'); + $r->setAccessible(true); + } + + $part->setDisposition('form-data'); + $part->setName($name); + // HTTP does not support \r\n in header values + $part->getHeaders()->setMaxLineLength(\PHP_INT_MAX); + $r->setValue($part, '8bit'); + + return $part; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/Multipart/MixedPart.php b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/MixedPart.php new file mode 100644 index 0000000..c8d7028 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/MixedPart.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part\Multipart; + +use Symfony\Component\Mime\Part\AbstractMultipartPart; + +/** + * @author Fabien Potencier + */ +final class MixedPart extends AbstractMultipartPart +{ + public function getMediaSubtype(): string + { + return 'mixed'; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/Multipart/RelatedPart.php b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/RelatedPart.php new file mode 100644 index 0000000..08fdd5f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/Multipart/RelatedPart.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part\Multipart; + +use Symfony\Component\Mime\Part\AbstractMultipartPart; +use Symfony\Component\Mime\Part\AbstractPart; + +/** + * @author Fabien Potencier + */ +final class RelatedPart extends AbstractMultipartPart +{ + private $mainPart; + + public function __construct(AbstractPart $mainPart, AbstractPart $part, AbstractPart ...$parts) + { + $this->mainPart = $mainPart; + $this->prepareParts($part, ...$parts); + + parent::__construct($part, ...$parts); + } + + public function getParts(): array + { + return array_merge([$this->mainPart], parent::getParts()); + } + + public function getMediaSubtype(): string + { + return 'related'; + } + + private function generateContentId(): string + { + return bin2hex(random_bytes(16)).'@symfony'; + } + + private function prepareParts(AbstractPart ...$parts): void + { + foreach ($parts as $part) { + if (!$part->getHeaders()->has('Content-ID')) { + $part->getHeaders()->setHeaderBody('Id', 'Content-ID', $this->generateContentId()); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/SMimePart.php b/php/libraries/composer/vendor/symfony/mime/Part/SMimePart.php new file mode 100644 index 0000000..cb619c2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/SMimePart.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part; + +use Symfony\Component\Mime\Header\Headers; + +/** + * @author Sebastiaan Stok + */ +class SMimePart extends AbstractPart +{ + /** @internal */ + protected $_headers; + + private $body; + private $type; + private $subtype; + private $parameters; + + /** + * @param iterable|string $body + */ + public function __construct($body, string $type, string $subtype, array $parameters) + { + unset($this->_headers); + + parent::__construct(); + + if (!\is_string($body) && !is_iterable($body)) { + throw new \TypeError(sprintf('The body of "%s" must be a string or a iterable (got "%s").', self::class, get_debug_type($body))); + } + + $this->body = $body; + $this->type = $type; + $this->subtype = $subtype; + $this->parameters = $parameters; + } + + public function getMediaType(): string + { + return $this->type; + } + + public function getMediaSubtype(): string + { + return $this->subtype; + } + + public function bodyToString(): string + { + if (\is_string($this->body)) { + return $this->body; + } + + $body = ''; + foreach ($this->body as $chunk) { + $body .= $chunk; + } + $this->body = $body; + + return $body; + } + + public function bodyToIterable(): iterable + { + if (\is_string($this->body)) { + yield $this->body; + + return; + } + + $body = ''; + foreach ($this->body as $chunk) { + $body .= $chunk; + yield $chunk; + } + $this->body = $body; + } + + public function getPreparedHeaders(): Headers + { + $headers = clone parent::getHeaders(); + + $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype()); + + foreach ($this->parameters as $name => $value) { + $headers->setHeaderParameter('Content-Type', $name, $value); + } + + return $headers; + } + + public function __sleep(): array + { + // convert iterables to strings for serialization + if (is_iterable($this->body)) { + $this->body = $this->bodyToString(); + } + + $this->_headers = $this->getHeaders(); + + return ['_headers', 'body', 'type', 'subtype', 'parameters']; + } + + public function __wakeup(): void + { + $r = new \ReflectionProperty(AbstractPart::class, 'headers'); + $r->setAccessible(true); + $r->setValue($this, $this->_headers); + unset($this->_headers); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Part/TextPart.php b/php/libraries/composer/vendor/symfony/mime/Part/TextPart.php new file mode 100644 index 0000000..fe9ca02 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Part/TextPart.php @@ -0,0 +1,215 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Part; + +use Symfony\Component\Mime\Encoder\Base64ContentEncoder; +use Symfony\Component\Mime\Encoder\ContentEncoderInterface; +use Symfony\Component\Mime\Encoder\EightBitContentEncoder; +use Symfony\Component\Mime\Encoder\QpContentEncoder; +use Symfony\Component\Mime\Exception\InvalidArgumentException; +use Symfony\Component\Mime\Header\Headers; + +/** + * @author Fabien Potencier + */ +class TextPart extends AbstractPart +{ + /** @internal */ + protected $_headers; + + private static $encoders = []; + + private $body; + private $charset; + private $subtype; + /** + * @var ?string + */ + private $disposition; + private $name; + private $encoding; + private $seekable; + + /** + * @param resource|string $body + */ + public function __construct($body, ?string $charset = 'utf-8', string $subtype = 'plain', ?string $encoding = null) + { + unset($this->_headers); + + parent::__construct(); + + if (!\is_string($body) && !\is_resource($body)) { + throw new \TypeError(sprintf('The body of "%s" must be a string or a resource (got "%s").', self::class, get_debug_type($body))); + } + + $this->body = $body; + $this->charset = $charset; + $this->subtype = $subtype; + $this->seekable = \is_resource($body) ? stream_get_meta_data($body)['seekable'] && 0 === fseek($body, 0, \SEEK_CUR) : null; + + if (null === $encoding) { + $this->encoding = $this->chooseEncoding(); + } else { + if ('quoted-printable' !== $encoding && 'base64' !== $encoding && '8bit' !== $encoding) { + throw new InvalidArgumentException(sprintf('The encoding must be one of "quoted-printable", "base64", or "8bit" ("%s" given).', $encoding)); + } + $this->encoding = $encoding; + } + } + + public function getMediaType(): string + { + return 'text'; + } + + public function getMediaSubtype(): string + { + return $this->subtype; + } + + /** + * @param string $disposition one of attachment, inline, or form-data + * + * @return $this + */ + public function setDisposition(string $disposition) + { + $this->disposition = $disposition; + + return $this; + } + + /** + * Sets the name of the file (used by FormDataPart). + * + * @return $this + */ + public function setName(string $name) + { + $this->name = $name; + + return $this; + } + + public function getBody(): string + { + if (null === $this->seekable) { + return $this->body; + } + + if ($this->seekable) { + rewind($this->body); + } + + return stream_get_contents($this->body) ?: ''; + } + + public function bodyToString(): string + { + return $this->getEncoder()->encodeString($this->getBody(), $this->charset); + } + + public function bodyToIterable(): iterable + { + if (null !== $this->seekable) { + if ($this->seekable) { + rewind($this->body); + } + yield from $this->getEncoder()->encodeByteStream($this->body); + } else { + yield $this->getEncoder()->encodeString($this->body); + } + } + + public function getPreparedHeaders(): Headers + { + $headers = parent::getPreparedHeaders(); + + $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype()); + if ($this->charset) { + $headers->setHeaderParameter('Content-Type', 'charset', $this->charset); + } + if ($this->name && 'form-data' !== $this->disposition) { + $headers->setHeaderParameter('Content-Type', 'name', $this->name); + } + $headers->setHeaderBody('Text', 'Content-Transfer-Encoding', $this->encoding); + + if (!$headers->has('Content-Disposition') && null !== $this->disposition) { + $headers->setHeaderBody('Parameterized', 'Content-Disposition', $this->disposition); + if ($this->name) { + $headers->setHeaderParameter('Content-Disposition', 'name', $this->name); + } + } + + return $headers; + } + + public function asDebugString(): string + { + $str = parent::asDebugString(); + if (null !== $this->charset) { + $str .= ' charset: '.$this->charset; + } + if (null !== $this->disposition) { + $str .= ' disposition: '.$this->disposition; + } + + return $str; + } + + private function getEncoder(): ContentEncoderInterface + { + if ('8bit' === $this->encoding) { + return self::$encoders[$this->encoding] ?? (self::$encoders[$this->encoding] = new EightBitContentEncoder()); + } + + if ('quoted-printable' === $this->encoding) { + return self::$encoders[$this->encoding] ?? (self::$encoders[$this->encoding] = new QpContentEncoder()); + } + + return self::$encoders[$this->encoding] ?? (self::$encoders[$this->encoding] = new Base64ContentEncoder()); + } + + private function chooseEncoding(): string + { + if (null === $this->charset) { + return 'base64'; + } + + return 'quoted-printable'; + } + + /** + * @return array + */ + public function __sleep() + { + // convert resources to strings for serialization + if (null !== $this->seekable) { + $this->body = $this->getBody(); + $this->seekable = null; + } + + $this->_headers = $this->getHeaders(); + + return ['_headers', 'body', 'charset', 'subtype', 'disposition', 'name', 'encoding']; + } + + public function __wakeup() + { + $r = new \ReflectionProperty(AbstractPart::class, 'headers'); + $r->setAccessible(true); + $r->setValue($this, $this->_headers); + unset($this->_headers); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/README.md b/php/libraries/composer/vendor/symfony/mime/README.md new file mode 100644 index 0000000..8e4d5c7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/README.md @@ -0,0 +1,13 @@ +MIME Component +============== + +The MIME component allows manipulating MIME messages. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/mime.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/mime/RawMessage.php b/php/libraries/composer/vendor/symfony/mime/RawMessage.php new file mode 100644 index 0000000..ace1960 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/RawMessage.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 Symfony\Component\Mime; + +use Symfony\Component\Mime\Exception\LogicException; + +/** + * @author Fabien Potencier + */ +class RawMessage implements \Serializable +{ + /** + * @var iterable|string + */ + private $message; + + /** + * @param iterable|string $message + */ + public function __construct($message) + { + $this->message = $message; + } + + public function toString(): string + { + if (\is_string($this->message)) { + return $this->message; + } + if ($this->message instanceof \Traversable) { + $this->message = iterator_to_array($this->message, false); + } + + return $this->message = implode('', $this->message); + } + + public function toIterable(): iterable + { + if (\is_string($this->message)) { + yield $this->message; + + return; + } + + $message = ''; + foreach ($this->message as $chunk) { + $message .= $chunk; + yield $chunk; + } + $this->message = $message; + } + + /** + * @throws LogicException if the message is not valid + */ + public function ensureValidity() + { + } + + /** + * @internal + */ + final public function serialize(): string + { + return serialize($this->__serialize()); + } + + /** + * @internal + */ + final public function unserialize($serialized) + { + $this->__unserialize(unserialize($serialized)); + } + + public function __serialize(): array + { + return [$this->toString()]; + } + + public function __unserialize(array $data): void + { + [$this->message] = $data; + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Resources/bin/update_mime_types.php b/php/libraries/composer/vendor/symfony/mime/Resources/bin/update_mime_types.php new file mode 100644 index 0000000..5586f09 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Resources/bin/update_mime_types.php @@ -0,0 +1,165 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if ('cli' !== \PHP_SAPI) { + throw new Exception('This script must be run from the command line.'); +} + +// load new map +$data = json_decode(file_get_contents('https://cdn.jsdelivr.net/gh/jshttp/mime-db@v1.49.0/db.json'), true); +$new = []; +foreach ($data as $mimeType => $mimeTypeInformation) { + if (!array_key_exists('extensions', $mimeTypeInformation)) { + continue; + } + $new[$mimeType] = $mimeTypeInformation['extensions']; +} + +$xml = simplexml_load_string(file_get_contents('https://gitlab.freedesktop.org/xdg/shared-mime-info/-/raw/master/data/freedesktop.org.xml.in')); +foreach ($xml as $node) { + $exts = []; + foreach ($node->glob as $glob) { + $pattern = (string) $glob['pattern']; + if ('*' != $pattern[0] || '.' != $pattern[1]) { + continue; + } + + $exts[] = substr($pattern, 2); + } + + if (!$exts) { + continue; + } + + $mt = strtolower((string) $node['type']); + $new[$mt] = array_merge($new[$mt] ?? [], $exts); + foreach ($node->alias as $alias) { + $mt = strtolower((string) $alias['type']); + $new[$mt] = array_merge($new[$mt] ?? [], $exts); + } +} + +// load current map +$data = file_get_contents($output = __DIR__.'/../../MimeTypes.php'); +$current = []; +$pre = ''; +$post = ''; +foreach (explode("\n", $data) as $line) { + if (!preg_match("{^ '([^']+/[^']+)' => \['(.+)'\],$}", $line, $matches)) { + if (!$current) { + $pre .= $line."\n"; + } else { + $post .= $line."\n"; + } + continue; + } + $current[$matches[1]] = explode("', '", $matches[2]); +} + +$data = $pre; + +// reverse map +// we prefill the extensions with some preferences for content-types +$exts = [ + 'asice' => ['application/vnd.etsi.asic-e+zip'], + 'bz2' => ['application/x-bz2'], + 'csv' => ['text/csv'], + 'ecma' => ['application/ecmascript'], + 'flv' => ['video/x-flv'], + 'gif' => ['image/gif'], + 'gz' => ['application/x-gzip'], + 'htm' => ['text/html'], + 'html' => ['text/html'], + 'jar' => ['application/x-java-archive'], + 'jpg' => ['image/jpeg'], + 'js' => ['text/javascript'], + 'keynote' => ['application/vnd.apple.keynote'], + 'key' => ['application/vnd.apple.keynote'], + 'm3u' => ['audio/x-mpegurl'], + 'm4a' => ['audio/mp4'], + 'md' => ['text/markdown', 'text/x-markdown'], + 'mdb' => ['application/x-msaccess'], + 'mid' => ['audio/midi'], + 'mov' => ['video/quicktime'], + 'mp3' => ['audio/mpeg'], + 'ogg' => ['audio/ogg'], + 'pdf' => ['application/pdf'], + 'php' => ['application/x-php'], + 'ppt' => ['application/vnd.ms-powerpoint'], + 'rar' => ['application/x-rar-compressed'], + 'hqx' => ['application/stuffit'], + 'sit' => ['application/x-stuffit', 'application/stuffit'], + 'svg' => ['image/svg+xml'], + 'tar' => ['application/x-tar'], + 'tif' => ['image/tiff'], + 'ttf' => ['application/x-font-truetype'], + 'vcf' => ['text/x-vcard'], + 'wav' => ['audio/wav'], + 'wma' => ['audio/x-ms-wma'], + 'wmv' => ['audio/x-ms-wmv'], + 'xls' => ['application/vnd.ms-excel'], + 'zip' => ['application/zip'], +]; + +// we merge the 2 maps (we never remove old mime types) +$map = array_replace_recursive($current, $new); + +foreach ($exts as $ext => $types) { + foreach ($types as $mt) { + if (!isset($map[$mt])) { + $map += [$mt => [$ext]]; + } + } +} +ksort($map); + +foreach ($map as $mimeType => $extensions) { + foreach ($exts as $ext => $types) { + if (in_array($mimeType, $types, true)) { + array_unshift($extensions, $ext); + } + } + $data .= sprintf(" '%s' => ['%s'],\n", $mimeType, implode("', '", array_unique($extensions))); +} +$data .= $post; + +foreach ($map as $mimeType => $extensions) { + foreach ($extensions as $extension) { + if ('application/octet-stream' === $mimeType && 'bin' !== $extension) { + continue; + } + + $exts[$extension][] = $mimeType; + } +} +ksort($exts); + +$updated = ''; +$state = 0; +foreach (explode("\n", $data) as $line) { + if (!preg_match("{^ '([^'/]+)' => \['(.+)'\],$}", $line, $matches)) { + if (1 === $state) { + $state = 2; + foreach ($exts as $ext => $mimeTypes) { + $updated .= sprintf(" '%s' => ['%s'],\n", $ext, implode("', '", array_unique($mimeTypes))); + } + } + $updated .= $line."\n"; + continue; + } + $state = 1; +} + +$updated = preg_replace('{Updated from upstream on .+?\.}', 'Updated from upstream on '.date('Y-m-d'), $updated, -1); + +file_put_contents($output, rtrim($updated, "\n")."\n"); + +echo "Done.\n"; diff --git a/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailAddressContains.php b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailAddressContains.php new file mode 100644 index 0000000..827e141 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailAddressContains.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Mime\Header\MailboxHeader; +use Symfony\Component\Mime\Header\MailboxListHeader; +use Symfony\Component\Mime\RawMessage; + +final class EmailAddressContains extends Constraint +{ + private $headerName; + private $expectedValue; + + public function __construct(string $headerName, string $expectedValue) + { + $this->headerName = $headerName; + $this->expectedValue = $expectedValue; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('contains address "%s" with value "%s"', $this->headerName, $this->expectedValue); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function matches($message): bool + { + if (RawMessage::class === \get_class($message)) { + throw new \LogicException('Unable to test a message address on a RawMessage instance.'); + } + + $header = $message->getHeaders()->get($this->headerName); + if ($header instanceof MailboxHeader) { + return $this->expectedValue === $header->getAddress()->getAddress(); + } elseif ($header instanceof MailboxListHeader) { + foreach ($header->getAddresses() as $address) { + if ($this->expectedValue === $address->getAddress()) { + return true; + } + } + + return false; + } + + throw new \LogicException('Unable to test a message address on a non-address header.'); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function failureDescription($message): string + { + return sprintf('the Email %s (value is %s)', $this->toString(), $message->getHeaders()->get($this->headerName)->getBodyAsString()); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailAttachmentCount.php b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailAttachmentCount.php new file mode 100644 index 0000000..3243ec6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailAttachmentCount.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\Mime\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Mime\Message; +use Symfony\Component\Mime\RawMessage; + +final class EmailAttachmentCount extends Constraint +{ + private $expectedValue; + private $transport; + + public function __construct(int $expectedValue, ?string $transport = null) + { + $this->expectedValue = $expectedValue; + $this->transport = $transport; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('has sent "%d" attachment(s)', $this->expectedValue); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function matches($message): bool + { + if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) { + throw new \LogicException('Unable to test a message attachment on a RawMessage or Message instance.'); + } + + return $this->expectedValue === \count($message->getAttachments()); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function failureDescription($message): string + { + return 'the Email '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHasHeader.php b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHasHeader.php new file mode 100644 index 0000000..a29f835 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHasHeader.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Mime\RawMessage; + +final class EmailHasHeader extends Constraint +{ + private $headerName; + + public function __construct(string $headerName) + { + $this->headerName = $headerName; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('has header "%s"', $this->headerName); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function matches($message): bool + { + if (RawMessage::class === \get_class($message)) { + throw new \LogicException('Unable to test a message header on a RawMessage instance.'); + } + + return $message->getHeaders()->has($this->headerName); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function failureDescription($message): string + { + return 'the Email '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHeaderSame.php b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHeaderSame.php new file mode 100644 index 0000000..74b4121 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHeaderSame.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Mime\Header\UnstructuredHeader; +use Symfony\Component\Mime\RawMessage; + +final class EmailHeaderSame extends Constraint +{ + private $headerName; + private $expectedValue; + + public function __construct(string $headerName, string $expectedValue) + { + $this->headerName = $headerName; + $this->expectedValue = $expectedValue; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('has header "%s" with value "%s"', $this->headerName, $this->expectedValue); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function matches($message): bool + { + if (RawMessage::class === \get_class($message)) { + throw new \LogicException('Unable to test a message header on a RawMessage instance.'); + } + + return $this->expectedValue === $this->getHeaderValue($message); + } + + /** + * @param RawMessage $message + * + * {@inheritdoc} + */ + protected function failureDescription($message): string + { + return sprintf('the Email %s (value is %s)', $this->toString(), $this->getHeaderValue($message) ?? 'null'); + } + + private function getHeaderValue($message): ?string + { + if (null === $header = $message->getHeaders()->get($this->headerName)) { + return null; + } + + return $header instanceof UnstructuredHeader ? $header->getValue() : $header->getBodyAsString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHtmlBodyContains.php b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHtmlBodyContains.php new file mode 100644 index 0000000..3c61376 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailHtmlBodyContains.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Mime\Message; +use Symfony\Component\Mime\RawMessage; + +final class EmailHtmlBodyContains extends Constraint +{ + private $expectedText; + + public function __construct(string $expectedText) + { + $this->expectedText = $expectedText; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('contains "%s"', $this->expectedText); + } + + /** + * {@inheritdoc} + * + * @param RawMessage $message + */ + protected function matches($message): bool + { + if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) { + throw new \LogicException('Unable to test a message HTML body on a RawMessage or Message instance.'); + } + + return false !== mb_strpos($message->getHtmlBody(), $this->expectedText); + } + + /** + * {@inheritdoc} + * + * @param RawMessage $message + */ + protected function failureDescription($message): string + { + return 'the Email HTML body '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailTextBodyContains.php b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailTextBodyContains.php new file mode 100644 index 0000000..063d963 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/Test/Constraint/EmailTextBodyContains.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Mime\Test\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Mime\Message; +use Symfony\Component\Mime\RawMessage; + +final class EmailTextBodyContains extends Constraint +{ + private $expectedText; + + public function __construct(string $expectedText) + { + $this->expectedText = $expectedText; + } + + /** + * {@inheritdoc} + */ + public function toString(): string + { + return sprintf('contains "%s"', $this->expectedText); + } + + /** + * {@inheritdoc} + * + * @param RawMessage $message + */ + protected function matches($message): bool + { + if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) { + throw new \LogicException('Unable to test a message text body on a RawMessage or Message instance.'); + } + + return false !== mb_strpos($message->getTextBody(), $this->expectedText); + } + + /** + * {@inheritdoc} + * + * @param RawMessage $message + */ + protected function failureDescription($message): string + { + return 'the Email text body '.$this->toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/mime/composer.json b/php/libraries/composer/vendor/symfony/mime/composer.json new file mode 100644 index 0000000..11823ef --- /dev/null +++ b/php/libraries/composer/vendor/symfony/mime/composer.json @@ -0,0 +1,47 @@ +{ + "name": "symfony/mime", + "type": "library", + "description": "Allows manipulating MIME messages", + "keywords": ["mime", "mime-type"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "egulias/email-validator": "^2.1.10|^3.1|^4", + "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "symfony/property-access": "^4.4|^5.1|^6.0", + "symfony/property-info": "^4.4|^5.1|^6.0", + "symfony/serializer": "^5.4.35|~6.3.12|^6.4.3" + }, + "conflict": { + "egulias/email-validator": "~3.0.0", + "phpdocumentor/reflection-docblock": "<3.2.2", + "phpdocumentor/type-resolver": "<1.4.0", + "symfony/mailer": "<4.4", + "symfony/serializer": "<5.4.35|>=6,<6.3.12|>=6.4,<6.4.3" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Mime\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-ctype/Ctype.php b/php/libraries/composer/vendor/symfony/polyfill-ctype/Ctype.php new file mode 100644 index 0000000..ba75a2c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-ctype/Ctype.php @@ -0,0 +1,232 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Ctype; + +/** + * Ctype implementation through regex. + * + * @internal + * + * @author Gert de Pagter + */ +final class Ctype +{ + /** + * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. + * + * @see https://php.net/ctype-alnum + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_alnum($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is a letter, FALSE otherwise. + * + * @see https://php.net/ctype-alpha + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_alpha($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); + } + + /** + * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. + * + * @see https://php.net/ctype-cntrl + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_cntrl($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); + } + + /** + * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. + * + * @see https://php.net/ctype-digit + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_digit($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. + * + * @see https://php.net/ctype-graph + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_graph($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); + } + + /** + * Returns TRUE if every character in text is a lowercase letter. + * + * @see https://php.net/ctype-lower + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_lower($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); + } + + /** + * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. + * + * @see https://php.net/ctype-print + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_print($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); + } + + /** + * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. + * + * @see https://php.net/ctype-punct + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_punct($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); + } + + /** + * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. + * + * @see https://php.net/ctype-space + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_space($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); + } + + /** + * Returns TRUE if every character in text is an uppercase letter. + * + * @see https://php.net/ctype-upper + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_upper($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); + } + + /** + * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. + * + * @see https://php.net/ctype-xdigit + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_xdigit($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); + } + + /** + * Converts integers to their char versions according to normal ctype behaviour, if needed. + * + * If an integer between -128 and 255 inclusive is provided, + * it is interpreted as the ASCII value of a single character + * (negative values have 256 added in order to allow characters in the Extended ASCII range). + * Any other integer is interpreted as a string containing the decimal digits of the integer. + * + * @param mixed $int + * @param string $function + * + * @return mixed + */ + private static function convert_int_to_char_for_ctype($int, $function) + { + if (!\is_int($int)) { + return $int; + } + + if ($int < -128 || $int > 255) { + return (string) $int; + } + + if (\PHP_VERSION_ID >= 80100) { + @trigger_error($function.'(): Argument of type int will be interpreted as string in the future', \E_USER_DEPRECATED); + } + + if ($int < 0) { + $int += 256; + } + + return \chr($int); + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-ctype/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-ctype/LICENSE new file mode 100644 index 0000000..7536cae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-ctype/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-ctype/README.md b/php/libraries/composer/vendor/symfony/polyfill-ctype/README.md new file mode 100644 index 0000000..b144d03 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-ctype/README.md @@ -0,0 +1,12 @@ +Symfony Polyfill / Ctype +======================== + +This component provides `ctype_*` functions to users who run php versions without the ctype extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-ctype/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-ctype/bootstrap.php new file mode 100644 index 0000000..d54524b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-ctype/bootstrap.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('ctype_alnum')) { + function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit($text) { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph($text) { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower($text) { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print($text) { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct($text) { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space($text) { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper($text) { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-ctype/bootstrap80.php b/php/libraries/composer/vendor/symfony/polyfill-ctype/bootstrap80.php new file mode 100644 index 0000000..ab2f861 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-ctype/bootstrap80.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (!function_exists('ctype_alnum')) { + function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-ctype/composer.json b/php/libraries/composer/vendor/symfony/polyfill-ctype/composer.json new file mode 100644 index 0000000..b222fda --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-ctype/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/polyfill-ctype", + "type": "library", + "description": "Symfony polyfill for ctype functions", + "keywords": ["polyfill", "compatibility", "portable", "ctype"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Ctype\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Iconv.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Iconv.php new file mode 100644 index 0000000..c17a70d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/Iconv.php @@ -0,0 +1,744 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Iconv; + +/** + * iconv implementation in pure PHP, UTF-8 centric. + * + * Implemented: + * - iconv - Convert string to requested character encoding + * - iconv_mime_decode - Decodes a MIME header field + * - iconv_mime_decode_headers - Decodes multiple MIME header fields at once + * - iconv_get_encoding - Retrieve internal configuration variables of iconv extension + * - iconv_set_encoding - Set current setting for character encoding conversion + * - iconv_mime_encode - Composes a MIME header field + * - iconv_strlen - Returns the character count of string + * - iconv_strpos - Finds position of first occurrence of a needle within a haystack + * - iconv_strrpos - Finds the last occurrence of a needle within a haystack + * - iconv_substr - Cut out part of a string + * + * Charsets available for conversion are defined by files + * in the charset/ directory and by Iconv::$alias below. + * You're welcome to send back any addition you make. + * + * @author Nicolas Grekas + * + * @internal + */ +final class Iconv +{ + public const ERROR_ILLEGAL_CHARACTER = 'iconv(): Detected an illegal character in input string'; + public const ERROR_WRONG_CHARSET = 'iconv(): Wrong charset, conversion from `%s\' to `%s\' is not allowed'; + + public static $inputEncoding = 'utf-8'; + public static $outputEncoding = 'utf-8'; + public static $internalEncoding = 'utf-8'; + + private static $alias = [ + 'utf8' => 'utf-8', + 'ascii' => 'us-ascii', + 'tis-620' => 'iso-8859-11', + 'cp1250' => 'windows-1250', + 'cp1251' => 'windows-1251', + 'cp1252' => 'windows-1252', + 'cp1253' => 'windows-1253', + 'cp1254' => 'windows-1254', + 'cp1255' => 'windows-1255', + 'cp1256' => 'windows-1256', + 'cp1257' => 'windows-1257', + 'cp1258' => 'windows-1258', + 'shift-jis' => 'cp932', + 'shift_jis' => 'cp932', + 'latin1' => 'iso-8859-1', + 'latin2' => 'iso-8859-2', + 'latin3' => 'iso-8859-3', + 'latin4' => 'iso-8859-4', + 'latin5' => 'iso-8859-9', + 'latin6' => 'iso-8859-10', + 'latin7' => 'iso-8859-13', + 'latin8' => 'iso-8859-14', + 'latin9' => 'iso-8859-15', + 'latin10' => 'iso-8859-16', + 'iso8859-1' => 'iso-8859-1', + 'iso8859-2' => 'iso-8859-2', + 'iso8859-3' => 'iso-8859-3', + 'iso8859-4' => 'iso-8859-4', + 'iso8859-5' => 'iso-8859-5', + 'iso8859-6' => 'iso-8859-6', + 'iso8859-7' => 'iso-8859-7', + 'iso8859-8' => 'iso-8859-8', + 'iso8859-9' => 'iso-8859-9', + 'iso8859-10' => 'iso-8859-10', + 'iso8859-11' => 'iso-8859-11', + 'iso8859-12' => 'iso-8859-12', + 'iso8859-13' => 'iso-8859-13', + 'iso8859-14' => 'iso-8859-14', + 'iso8859-15' => 'iso-8859-15', + 'iso8859-16' => 'iso-8859-16', + 'iso_8859-1' => 'iso-8859-1', + 'iso_8859-2' => 'iso-8859-2', + 'iso_8859-3' => 'iso-8859-3', + 'iso_8859-4' => 'iso-8859-4', + 'iso_8859-5' => 'iso-8859-5', + 'iso_8859-6' => 'iso-8859-6', + 'iso_8859-7' => 'iso-8859-7', + 'iso_8859-8' => 'iso-8859-8', + 'iso_8859-9' => 'iso-8859-9', + 'iso_8859-10' => 'iso-8859-10', + 'iso_8859-11' => 'iso-8859-11', + 'iso_8859-12' => 'iso-8859-12', + 'iso_8859-13' => 'iso-8859-13', + 'iso_8859-14' => 'iso-8859-14', + 'iso_8859-15' => 'iso-8859-15', + 'iso_8859-16' => 'iso-8859-16', + 'iso88591' => 'iso-8859-1', + 'iso88592' => 'iso-8859-2', + 'iso88593' => 'iso-8859-3', + 'iso88594' => 'iso-8859-4', + 'iso88595' => 'iso-8859-5', + 'iso88596' => 'iso-8859-6', + 'iso88597' => 'iso-8859-7', + 'iso88598' => 'iso-8859-8', + 'iso88599' => 'iso-8859-9', + 'iso885910' => 'iso-8859-10', + 'iso885911' => 'iso-8859-11', + 'iso885912' => 'iso-8859-12', + 'iso885913' => 'iso-8859-13', + 'iso885914' => 'iso-8859-14', + 'iso885915' => 'iso-8859-15', + 'iso885916' => 'iso-8859-16', + ]; + private static $translitMap = []; + private static $convertMap = []; + private static $errorHandler; + private static $lastError; + + private static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + private static $isValidUtf8; + + public static function iconv($inCharset, $outCharset, $str) + { + $str = (string) $str; + if ('' === $str) { + return ''; + } + + // Prepare for //IGNORE and //TRANSLIT + + $translit = $ignore = ''; + + $outCharset = strtolower($outCharset); + $inCharset = strtolower($inCharset); + + if ('' === $outCharset) { + $outCharset = 'iso-8859-1'; + } + if ('' === $inCharset) { + $inCharset = 'iso-8859-1'; + } + + do { + $loop = false; + + if ('//translit' === substr($outCharset, -10)) { + $loop = $translit = true; + $outCharset = substr($outCharset, 0, -10); + } + + if ('//ignore' === substr($outCharset, -8)) { + $loop = $ignore = true; + $outCharset = substr($outCharset, 0, -8); + } + } while ($loop); + + do { + $loop = false; + + if ('//translit' === substr($inCharset, -10)) { + $loop = true; + $inCharset = substr($inCharset, 0, -10); + } + + if ('//ignore' === substr($inCharset, -8)) { + $loop = true; + $inCharset = substr($inCharset, 0, -8); + } + } while ($loop); + + if (isset(self::$alias[$inCharset])) { + $inCharset = self::$alias[$inCharset]; + } + if (isset(self::$alias[$outCharset])) { + $outCharset = self::$alias[$outCharset]; + } + + // Load charset maps + + if (('utf-8' !== $inCharset && !self::loadMap('from.', $inCharset, $inMap)) + || ('utf-8' !== $outCharset && !self::loadMap('to.', $outCharset, $outMap))) { + trigger_error(sprintf(self::ERROR_WRONG_CHARSET, $inCharset, $outCharset)); + + return false; + } + + if ('utf-8' !== $inCharset) { + // Convert input to UTF-8 + $result = ''; + if (self::mapToUtf8($result, $inMap, $str, $ignore)) { + $str = $result; + } else { + $str = false; + } + self::$isValidUtf8 = true; + } else { + self::$isValidUtf8 = preg_match('//u', $str); + + if (!self::$isValidUtf8 && !$ignore) { + trigger_error(self::ERROR_ILLEGAL_CHARACTER); + + return false; + } + + if ('utf-8' === $outCharset) { + // UTF-8 validation + $str = self::utf8ToUtf8($str, $ignore); + } + } + + if ('utf-8' !== $outCharset && false !== $str) { + // Convert output to UTF-8 + $result = ''; + if (self::mapFromUtf8($result, $outMap, $str, $ignore, $translit)) { + return $result; + } + + return false; + } + + return $str; + } + + public static function iconv_mime_decode_headers($str, $mode = 0, $charset = null) + { + if (null === $charset) { + $charset = self::$internalEncoding; + } + + if (false !== strpos($str, "\r")) { + $str = strtr(str_replace("\r\n", "\n", $str), "\r", "\n"); + } + $str = explode("\n\n", $str, 2); + + $headers = []; + + $str = preg_split('/\n(?![ \t])/', $str[0]); + foreach ($str as $str) { + $str = self::iconv_mime_decode($str, $mode, $charset); + if (false === $str) { + return false; + } + $str = explode(':', $str, 2); + + if (2 === \count($str)) { + if (isset($headers[$str[0]])) { + if (!\is_array($headers[$str[0]])) { + $headers[$str[0]] = [$headers[$str[0]]]; + } + $headers[$str[0]][] = ltrim($str[1]); + } else { + $headers[$str[0]] = ltrim($str[1]); + } + } + } + + return $headers; + } + + public static function iconv_mime_decode($str, $mode = 0, $charset = null) + { + if (null === $charset) { + $charset = self::$internalEncoding; + } + if (\ICONV_MIME_DECODE_CONTINUE_ON_ERROR & $mode) { + $charset .= '//IGNORE'; + } + + if (false !== strpos($str, "\r")) { + $str = strtr(str_replace("\r\n", "\n", $str), "\r", "\n"); + } + $str = preg_split('/\n(?![ \t])/', rtrim($str), 2); + $str = preg_replace('/[ \t]*\n[ \t]+/', ' ', rtrim($str[0])); + $str = preg_split('/=\?([^?]+)\?([bqBQ])\?(.*?)\?=/', $str, -1, \PREG_SPLIT_DELIM_CAPTURE); + + $result = self::iconv('utf-8', $charset, $str[0]); + if (false === $result) { + return false; + } + + $i = 1; + $len = \count($str); + + while ($i < $len) { + $c = strtolower($str[$i]); + if ((\ICONV_MIME_DECODE_CONTINUE_ON_ERROR & $mode) + && 'utf-8' !== $c + && !isset(self::$alias[$c]) + && !self::loadMap('from.', $c, $d)) { + $d = false; + } elseif ('B' === strtoupper($str[$i + 1])) { + $d = base64_decode($str[$i + 2]); + } else { + $d = rawurldecode(strtr(str_replace('%', '%25', $str[$i + 2]), '=_', '% ')); + } + + if (false !== $d) { + if ('' !== $d) { + if ('' === $d = self::iconv($c, $charset, $d)) { + $str[$i + 3] = substr($str[$i + 3], 1); + } else { + $result .= $d; + } + } + $d = self::iconv('utf-8', $charset, $str[$i + 3]); + if ('' !== trim($d)) { + $result .= $d; + } + } elseif (\ICONV_MIME_DECODE_CONTINUE_ON_ERROR & $mode) { + $result .= "=?{$str[$i]}?{$str[$i + 1]}?{$str[$i + 2]}?={$str[$i + 3]}"; + } else { + $result = false; + break; + } + + $i += 4; + } + + return $result; + } + + public static function iconv_get_encoding($type = 'all') + { + switch ($type) { + case 'input_encoding': return self::$inputEncoding; + case 'output_encoding': return self::$outputEncoding; + case 'internal_encoding': return self::$internalEncoding; + } + + return [ + 'input_encoding' => self::$inputEncoding, + 'output_encoding' => self::$outputEncoding, + 'internal_encoding' => self::$internalEncoding, + ]; + } + + public static function iconv_set_encoding($type, $charset) + { + switch ($type) { + case 'input_encoding': self::$inputEncoding = $charset; break; + case 'output_encoding': self::$outputEncoding = $charset; break; + case 'internal_encoding': self::$internalEncoding = $charset; break; + default: return false; + } + + return true; + } + + public static function iconv_mime_encode($fieldName, $fieldValue, $pref = null) + { + if (!\is_array($pref)) { + $pref = []; + } + + $pref += [ + 'scheme' => 'B', + 'input-charset' => self::$internalEncoding, + 'output-charset' => self::$internalEncoding, + 'line-length' => 76, + 'line-break-chars' => "\r\n", + ]; + + if (preg_match('/[\x80-\xFF]/', $fieldName)) { + $fieldName = ''; + } + + $scheme = strtoupper(substr($pref['scheme'], 0, 1)); + $in = strtolower($pref['input-charset']); + $out = strtolower($pref['output-charset']); + + if ('utf-8' !== $in && false === $fieldValue = self::iconv($in, 'utf-8', $fieldValue)) { + return false; + } + + preg_match_all('/./us', $fieldValue, $chars); + + $chars = $chars[0] ?? []; + + $lineBreak = (int) $pref['line-length']; + $lineStart = "=?{$pref['output-charset']}?{$scheme}?"; + $lineLength = \strlen($fieldName) + 2 + \strlen($lineStart) + 2; + $lineOffset = \strlen($lineStart) + 3; + $lineData = ''; + + $fieldValue = []; + + $Q = 'Q' === $scheme; + + foreach ($chars as $c) { + if ('utf-8' !== $out && false === $c = self::iconv('utf-8', $out, $c)) { + return false; + } + + $o = $Q + ? $c = preg_replace_callback( + '/[=_\?\x00-\x1F\x80-\xFF]/', + [__CLASS__, 'qpByteCallback'], + $c + ) + : base64_encode($lineData.$c); + + if (isset($o[$lineBreak - $lineLength])) { + if (!$Q) { + $lineData = base64_encode($lineData); + } + $fieldValue[] = $lineStart.$lineData.'?='; + $lineLength = $lineOffset; + $lineData = ''; + } + + $lineData .= $c; + $Q && $lineLength += \strlen($c); + } + + if ('' !== $lineData) { + if (!$Q) { + $lineData = base64_encode($lineData); + } + $fieldValue[] = $lineStart.$lineData.'?='; + } + + return $fieldName.': '.implode($pref['line-break-chars'].' ', $fieldValue); + } + + public static function iconv_strlen($s, $encoding = null) + { + static $hasXml = null; + if (null === $hasXml) { + $hasXml = \extension_loaded('xml'); + } + + if ($hasXml) { + return self::strlen1($s, $encoding); + } + + return self::strlen2($s, $encoding); + } + + public static function strlen1($s, $encoding = null) + { + if (null === $encoding) { + $encoding = self::$internalEncoding; + } + if (0 !== stripos($encoding, 'utf-8') && false === $s = self::iconv($encoding, 'utf-8', $s)) { + return false; + } + + return \strlen(utf8_decode($s)); + } + + public static function strlen2($s, $encoding = null) + { + if (null === $encoding) { + $encoding = self::$internalEncoding; + } + if (0 !== stripos($encoding, 'utf-8') && false === $s = self::iconv($encoding, 'utf-8', $s)) { + return false; + } + + $ulenMask = self::$ulenMask; + + $i = 0; + $j = 0; + $len = \strlen($s); + + while ($i < $len) { + $u = $s[$i] & "\xF0"; + $i += $ulenMask[$u] ?? 1; + ++$j; + } + + return $j; + } + + public static function iconv_strpos($haystack, $needle, $offset = 0, $encoding = null) + { + if (null === $encoding) { + $encoding = self::$internalEncoding; + } + + if (0 !== stripos($encoding, 'utf-8')) { + if (false === $haystack = self::iconv($encoding, 'utf-8', $haystack)) { + return false; + } + if (false === $needle = self::iconv($encoding, 'utf-8', $needle)) { + return false; + } + } + + if ($offset = (int) $offset) { + $haystack = self::iconv_substr($haystack, $offset, 2147483647, 'utf-8'); + } + $pos = strpos($haystack, $needle); + + return false === $pos ? false : ($offset + ($pos ? self::iconv_strlen(substr($haystack, 0, $pos), 'utf-8') : 0)); + } + + public static function iconv_strrpos($haystack, $needle, $encoding = null) + { + if (null === $encoding) { + $encoding = self::$internalEncoding; + } + + if (0 !== stripos($encoding, 'utf-8')) { + if (false === $haystack = self::iconv($encoding, 'utf-8', $haystack)) { + return false; + } + if (false === $needle = self::iconv($encoding, 'utf-8', $needle)) { + return false; + } + } + + $pos = isset($needle[0]) ? strrpos($haystack, $needle) : false; + + return false === $pos ? false : self::iconv_strlen($pos ? substr($haystack, 0, $pos) : $haystack, 'utf-8'); + } + + public static function iconv_substr($s, $start, $length = 2147483647, $encoding = null) + { + if (null === $encoding) { + $encoding = self::$internalEncoding; + } + if (0 !== stripos($encoding, 'utf-8')) { + $encoding = null; + } elseif (false === $s = self::iconv($encoding, 'utf-8', $s)) { + return false; + } + + $s = (string) $s; + $slen = self::iconv_strlen($s, 'utf-8'); + $start = (int) $start; + + if (0 > $start) { + $start += $slen; + } + if (0 > $start) { + if (\PHP_VERSION_ID < 80000) { + return false; + } + + $start = 0; + } + if ($start >= $slen) { + return \PHP_VERSION_ID >= 80000 ? '' : false; + } + + $rx = $slen - $start; + + if (0 > $length) { + $length += $rx; + } + if (0 === $length) { + return ''; + } + if (0 > $length) { + return \PHP_VERSION_ID >= 80000 ? '' : false; + } + + if ($length > $rx) { + $length = $rx; + } + + $rx = '/^'.($start ? self::pregOffset($start) : '').'('.self::pregOffset($length).')/u'; + + $s = preg_match($rx, $s, $s) ? $s[1] : ''; + + if (null === $encoding) { + return $s; + } + + return self::iconv('utf-8', $encoding, $s); + } + + private static function loadMap($type, $charset, &$map) + { + if (!isset(self::$convertMap[$type.$charset])) { + if (false === $map = self::getData($type.$charset)) { + if ('to.' === $type && self::loadMap('from.', $charset, $map)) { + $map = array_flip($map); + } else { + return false; + } + } + + self::$convertMap[$type.$charset] = $map; + } else { + $map = self::$convertMap[$type.$charset]; + } + + return true; + } + + private static function utf8ToUtf8($str, $ignore) + { + $ulenMask = self::$ulenMask; + $valid = self::$isValidUtf8; + + $u = $str; + $i = $j = 0; + $len = \strlen($str); + + while ($i < $len) { + if ($str[$i] < "\x80") { + $u[$j++] = $str[$i++]; + } else { + $ulen = $str[$i] & "\xF0"; + $ulen = $ulenMask[$ulen] ?? 1; + $uchr = substr($str, $i, $ulen); + + if (1 === $ulen || !($valid || preg_match('/^.$/us', $uchr))) { + if ($ignore) { + ++$i; + continue; + } + + trigger_error(self::ERROR_ILLEGAL_CHARACTER); + + return false; + } + + $i += $ulen; + + $u[$j++] = $uchr[0]; + + isset($uchr[1]) && 0 !== ($u[$j++] = $uchr[1]) + && isset($uchr[2]) && 0 !== ($u[$j++] = $uchr[2]) + && isset($uchr[3]) && 0 !== ($u[$j++] = $uchr[3]); + } + } + + return substr($u, 0, $j); + } + + private static function mapToUtf8(&$result, array $map, $str, $ignore) + { + $len = \strlen($str); + for ($i = 0; $i < $len; ++$i) { + if (isset($str[$i + 1], $map[$str[$i].$str[$i + 1]])) { + $result .= $map[$str[$i].$str[++$i]]; + } elseif (isset($map[$str[$i]])) { + $result .= $map[$str[$i]]; + } elseif (!$ignore) { + trigger_error(self::ERROR_ILLEGAL_CHARACTER); + + return false; + } + } + + return true; + } + + private static function mapFromUtf8(&$result, array $map, $str, $ignore, $translit) + { + $ulenMask = self::$ulenMask; + $valid = self::$isValidUtf8; + + if ($translit && !self::$translitMap) { + self::$translitMap = self::getData('translit'); + } + + $i = 0; + $len = \strlen($str); + + while ($i < $len) { + if ($str[$i] < "\x80") { + $uchr = $str[$i++]; + } else { + $ulen = $str[$i] & "\xF0"; + $ulen = $ulenMask[$ulen] ?? 1; + $uchr = substr($str, $i, $ulen); + + if ($ignore && (1 === $ulen || !($valid || preg_match('/^.$/us', $uchr)))) { + ++$i; + continue; + } + + $i += $ulen; + } + + if (isset($map[$uchr])) { + $result .= $map[$uchr]; + } elseif ($translit) { + if (isset(self::$translitMap[$uchr])) { + $uchr = self::$translitMap[$uchr]; + } elseif ($uchr >= "\xC3\x80") { + $uchr = \Normalizer::normalize($uchr, \Normalizer::NFD); + + if ($uchr[0] < "\x80") { + $uchr = $uchr[0]; + } elseif ($ignore) { + continue; + } else { + return false; + } + } elseif ($ignore) { + continue; + } else { + return false; + } + + $str = $uchr.substr($str, $i); + $len = \strlen($str); + $i = 0; + } elseif (!$ignore) { + return false; + } + } + + return true; + } + + private static function qpByteCallback(array $m) + { + return '='.strtoupper(dechex(\ord($m[0]))); + } + + private static function pregOffset($offset) + { + $rx = []; + $offset = (int) $offset; + + while ($offset > 65535) { + $rx[] = '.{65535}'; + $offset -= 65535; + } + + return implode('', $rx).'.{'.$offset.'}'; + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/charset/'.$file.'.php')) { + return require $file; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-iconv/LICENSE new file mode 100644 index 0000000..6e3afce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/README.md b/php/libraries/composer/vendor/symfony/polyfill-iconv/README.md new file mode 100644 index 0000000..b089088 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/README.md @@ -0,0 +1,14 @@ +Symfony Polyfill / Iconv +======================== + +This component provides a native PHP implementation of the +[php.net/iconv](https://php.net/iconv) functions +(short of [`ob_iconv_handler`](https://php.net/ob-iconv-handler)). + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.big5.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.big5.php new file mode 100644 index 0000000..b119854 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.big5.php @@ -0,0 +1,13719 @@ + ' ', + 'A' => ',', + 'B' => '、', + 'C' => '。', + 'D' => '.', + 'E' => '•', + 'F' => ';', + 'G' => ':', + 'H' => '?', + 'I' => '!', + 'J' => '︰', + 'K' => '…', + 'L' => '‥', + 'M' => '﹐', + 'N' => '、', + 'O' => '﹒', + 'P' => '·', + 'Q' => '﹔', + 'R' => '﹕', + 'S' => '﹖', + 'T' => '﹗', + 'U' => '|', + 'V' => '–', + 'W' => '︱', + 'X' => '—', + 'Y' => '︳', + 'Z' => '�', + '[' => '︴', + '\\' => '﹏', + ']' => '(', + '^' => ')', + '_' => '︵', + '`' => '︶', + 'a' => '{', + 'b' => '}', + 'c' => '︷', + 'd' => '︸', + 'e' => '〔', + 'f' => '〕', + 'g' => '︹', + 'h' => '︺', + 'i' => '【', + 'j' => '】', + 'k' => '︻', + 'l' => '︼', + 'm' => '《', + 'n' => '》', + 'o' => '︽', + 'p' => '︾', + 'q' => '〈', + 'r' => '〉', + 's' => '︿', + 't' => '﹀', + 'u' => '「', + 'v' => '」', + 'w' => '﹁', + 'x' => '﹂', + 'y' => '『', + 'z' => '』', + '{' => '﹃', + '|' => '﹄', + '}' => '﹙', + '~' => '﹚', + '' => '﹛', + '' => '﹜', + '' => '﹝', + '' => '﹞', + '' => '‘', + '' => '’', + '' => '“', + '' => '”', + '' => '〝', + '' => '〞', + '' => '‵', + '' => '′', + '' => '#', + '' => '&', + '' => '*', + '' => '※', + '' => '§', + '' => '〃', + '' => '○', + '' => '●', + '' => '△', + '' => '▲', + '' => '◎', + '' => '☆', + '' => '★', + '' => '◇', + '' => '◆', + '' => '□', + '' => '■', + '' => '▽', + '' => '▼', + '' => '㊣', + '' => '℅', + '' => '‾', + '' => '�', + '' => '_', + '' => '�', + '' => '﹉', + '' => '﹊', + '' => '﹍', + '' => '﹎', + '' => '﹋', + '' => '﹌', + '' => '﹟', + '' => '﹠', + '' => '﹡', + '' => '+', + '' => '-', + '' => '×', + '' => '÷', + '' => '±', + '' => '√', + '' => '<', + '' => '>', + '' => '=', + '' => '≦', + '' => '≧', + '' => '≠', + '' => '∞', + '' => '≒', + '' => '≡', + '' => '﹢', + '' => '﹣', + '' => '﹤', + '' => '﹥', + '' => '﹦', + '' => '∼', + '' => '∩', + '' => '∪', + '' => '⊥', + '' => '∠', + '' => '∟', + '' => '⊿', + '' => '㏒', + '' => '㏑', + '' => '∫', + '' => '∮', + '' => '∵', + '' => '∴', + '' => '♀', + '' => '♂', + '' => '♁', + '' => '☉', + '' => '↑', + '' => '↓', + '' => '←', + '' => '→', + '' => '↖', + '' => '↗', + '' => '↙', + '' => '↘', + '' => '∥', + '' => '∣', + '' => '�', + '@' => '�', + 'A' => '/', + 'B' => '\', + 'C' => '$', + 'D' => '¥', + 'E' => '〒', + 'F' => '¢', + 'G' => '£', + 'H' => '%', + 'I' => '@', + 'J' => '℃', + 'K' => '℉', + 'L' => '﹩', + 'M' => '﹪', + 'N' => '﹫', + 'O' => '㏕', + 'P' => '㎜', + 'Q' => '㎝', + 'R' => '㎞', + 'S' => '㏎', + 'T' => '㎡', + 'U' => '㎎', + 'V' => '㎏', + 'W' => '㏄', + 'X' => '°', + 'Y' => '兙', + 'Z' => '兛', + '[' => '兞', + '\\' => '兝', + ']' => '兡', + '^' => '兣', + '_' => '嗧', + '`' => '瓩', + 'a' => '糎', + 'b' => '▁', + 'c' => '▂', + 'd' => '▃', + 'e' => '▄', + 'f' => '▅', + 'g' => '▆', + 'h' => '▇', + 'i' => '█', + 'j' => '▏', + 'k' => '▎', + 'l' => '▍', + 'm' => '▌', + 'n' => '▋', + 'o' => '▊', + 'p' => '▉', + 'q' => '┼', + 'r' => '┴', + 's' => '┬', + 't' => '┤', + 'u' => '├', + 'v' => '▔', + 'w' => '─', + 'x' => '│', + 'y' => '▕', + 'z' => '┌', + '{' => '┐', + '|' => '└', + '}' => '┘', + '~' => '╭', + '' => '╮', + '' => '╰', + '' => '╯', + '' => '═', + '' => '╞', + '' => '╪', + '' => '╡', + '' => '◢', + '' => '◣', + '' => '◥', + '' => '◤', + '' => '╱', + '' => '╲', + '' => '╳', + '' => '0', + '' => '1', + '' => '2', + '' => '3', + '' => '4', + '' => '5', + '' => '6', + '' => '7', + '' => '8', + '' => '9', + '' => 'Ⅰ', + '' => 'Ⅱ', + '' => 'Ⅲ', + '' => 'Ⅳ', + '' => 'Ⅴ', + '' => 'Ⅵ', + '' => 'Ⅶ', + '' => 'Ⅷ', + '' => 'Ⅸ', + '' => 'Ⅹ', + '' => '〡', + '' => '〢', + '' => '〣', + '' => '〤', + '' => '〥', + '' => '〦', + '' => '〧', + '' => '〨', + '' => '〩', + '' => '�', + '' => '卄', + '' => '�', + '' => 'A', + '' => 'B', + '' => 'C', + '' => 'D', + '' => 'E', + '' => 'F', + '' => 'G', + '' => 'H', + '' => 'I', + '' => 'J', + '' => 'K', + '' => 'L', + '' => 'M', + '' => 'N', + '' => 'O', + '' => 'P', + '' => 'Q', + '' => 'R', + '' => 'S', + '' => 'T', + '' => 'U', + '' => 'V', + '' => 'W', + '' => 'X', + '' => 'Y', + '' => 'Z', + '' => 'a', + '' => 'b', + '' => 'c', + '' => 'd', + '' => 'e', + '' => 'f', + '' => 'g', + '' => 'h', + '' => 'i', + '' => 'j', + '' => 'k', + '' => 'l', + '' => 'm', + '' => 'n', + '' => 'o', + '' => 'p', + '' => 'q', + '' => 'r', + '' => 's', + '' => 't', + '' => 'u', + '' => 'v', + '@' => 'w', + 'A' => 'x', + 'B' => 'y', + 'C' => 'z', + 'D' => 'Α', + 'E' => 'Β', + 'F' => 'Γ', + 'G' => 'Δ', + 'H' => 'Ε', + 'I' => 'Ζ', + 'J' => 'Η', + 'K' => 'Θ', + 'L' => 'Ι', + 'M' => 'Κ', + 'N' => 'Λ', + 'O' => 'Μ', + 'P' => 'Ν', + 'Q' => 'Ξ', + 'R' => 'Ο', + 'S' => 'Π', + 'T' => 'Ρ', + 'U' => 'Σ', + 'V' => 'Τ', + 'W' => 'Υ', + 'X' => 'Φ', + 'Y' => 'Χ', + 'Z' => 'Ψ', + '[' => 'Ω', + '\\' => 'α', + ']' => 'β', + '^' => 'γ', + '_' => 'δ', + '`' => 'ε', + 'a' => 'ζ', + 'b' => 'η', + 'c' => 'θ', + 'd' => 'ι', + 'e' => 'κ', + 'f' => 'λ', + 'g' => 'μ', + 'h' => 'ν', + 'i' => 'ξ', + 'j' => 'ο', + 'k' => 'π', + 'l' => 'ρ', + 'm' => 'σ', + 'n' => 'τ', + 'o' => 'υ', + 'p' => 'φ', + 'q' => 'χ', + 'r' => 'ψ', + 's' => 'ω', + 't' => 'ㄅ', + 'u' => 'ㄆ', + 'v' => 'ㄇ', + 'w' => 'ㄈ', + 'x' => 'ㄉ', + 'y' => 'ㄊ', + 'z' => 'ㄋ', + '{' => 'ㄌ', + '|' => 'ㄍ', + '}' => 'ㄎ', + '~' => 'ㄏ', + '' => 'ㄐ', + '' => 'ㄑ', + '' => 'ㄒ', + '' => 'ㄓ', + '' => 'ㄔ', + '' => 'ㄕ', + '' => 'ㄖ', + '' => 'ㄗ', + '' => 'ㄘ', + '' => 'ㄙ', + '' => 'ㄚ', + '' => 'ㄛ', + '' => 'ㄜ', + '' => 'ㄝ', + '' => 'ㄞ', + '' => 'ㄟ', + '' => 'ㄠ', + '' => 'ㄡ', + '' => 'ㄢ', + '' => 'ㄣ', + '' => 'ㄤ', + '' => 'ㄥ', + '' => 'ㄦ', + '' => 'ㄧ', + '' => 'ㄨ', + '' => 'ㄩ', + '' => '˙', + '' => 'ˉ', + '' => 'ˊ', + '' => 'ˇ', + '' => 'ˋ', + '@' => '一', + 'A' => '乙', + 'B' => '丁', + 'C' => '七', + 'D' => '乃', + 'E' => '九', + 'F' => '了', + 'G' => '二', + 'H' => '人', + 'I' => '儿', + 'J' => '入', + 'K' => '八', + 'L' => '几', + 'M' => '刀', + 'N' => '刁', + 'O' => '力', + 'P' => '匕', + 'Q' => '十', + 'R' => '卜', + 'S' => '又', + 'T' => '三', + 'U' => '下', + 'V' => '丈', + 'W' => '上', + 'X' => '丫', + 'Y' => '丸', + 'Z' => '凡', + '[' => '久', + '\\' => '么', + ']' => '也', + '^' => '乞', + '_' => '于', + '`' => '亡', + 'a' => '兀', + 'b' => '刃', + 'c' => '勺', + 'd' => '千', + 'e' => '叉', + 'f' => '口', + 'g' => '土', + 'h' => '士', + 'i' => '夕', + 'j' => '大', + 'k' => '女', + 'l' => '子', + 'm' => '孑', + 'n' => '孓', + 'o' => '寸', + 'p' => '小', + 'q' => '尢', + 'r' => '尸', + 's' => '山', + 't' => '川', + 'u' => '工', + 'v' => '己', + 'w' => '已', + 'x' => '巳', + 'y' => '巾', + 'z' => '干', + '{' => '廾', + '|' => '弋', + '}' => '弓', + '~' => '才', + '' => '丑', + '' => '丐', + '' => '不', + '' => '中', + '' => '丰', + '' => '丹', + '' => '之', + '' => '尹', + '' => '予', + '' => '云', + '' => '井', + '' => '互', + '' => '五', + '' => '亢', + '' => '仁', + '' => '什', + '' => '仃', + '' => '仆', + '' => '仇', + '' => '仍', + '' => '今', + '' => '介', + '' => '仄', + '' => '元', + '' => '允', + '' => '內', + '' => '六', + '' => '兮', + '' => '公', + '' => '冗', + '' => '凶', + '' => '分', + '' => '切', + '' => '刈', + '' => '勻', + '' => '勾', + '' => '勿', + '' => '化', + '' => '匹', + '' => '午', + '' => '升', + '' => '卅', + '' => '卞', + '' => '厄', + '' => '友', + '' => '及', + '' => '反', + '' => '壬', + '' => '天', + '' => '夫', + '' => '太', + '' => '夭', + '' => '孔', + '' => '少', + '' => '尤', + '' => '尺', + '' => '屯', + '' => '巴', + '' => '幻', + '' => '廿', + '' => '弔', + '' => '引', + '' => '心', + '' => '戈', + '' => '戶', + '' => '手', + '' => '扎', + '' => '支', + '' => '文', + '' => '斗', + '' => '斤', + '' => '方', + '' => '日', + '' => '曰', + '' => '月', + '' => '木', + '' => '欠', + '' => '止', + '' => '歹', + '' => '毋', + '' => '比', + '' => '毛', + '' => '氏', + '' => '水', + '' => '火', + '' => '爪', + '' => '父', + '' => '爻', + '' => '片', + '' => '牙', + '' => '牛', + '' => '犬', + '' => '王', + '' => '丙', + '@' => '世', + 'A' => '丕', + 'B' => '且', + 'C' => '丘', + 'D' => '主', + 'E' => '乍', + 'F' => '乏', + 'G' => '乎', + 'H' => '以', + 'I' => '付', + 'J' => '仔', + 'K' => '仕', + 'L' => '他', + 'M' => '仗', + 'N' => '代', + 'O' => '令', + 'P' => '仙', + 'Q' => '仞', + 'R' => '充', + 'S' => '兄', + 'T' => '冉', + 'U' => '冊', + 'V' => '冬', + 'W' => '凹', + 'X' => '出', + 'Y' => '凸', + 'Z' => '刊', + '[' => '加', + '\\' => '功', + ']' => '包', + '^' => '匆', + '_' => '北', + '`' => '匝', + 'a' => '仟', + 'b' => '半', + 'c' => '卉', + 'd' => '卡', + 'e' => '占', + 'f' => '卯', + 'g' => '卮', + 'h' => '去', + 'i' => '可', + 'j' => '古', + 'k' => '右', + 'l' => '召', + 'm' => '叮', + 'n' => '叩', + 'o' => '叨', + 'p' => '叼', + 'q' => '司', + 'r' => '叵', + 's' => '叫', + 't' => '另', + 'u' => '只', + 'v' => '史', + 'w' => '叱', + 'x' => '台', + 'y' => '句', + 'z' => '叭', + '{' => '叻', + '|' => '四', + '}' => '囚', + '~' => '外', + '' => '央', + '' => '失', + '' => '奴', + '' => '奶', + '' => '孕', + '' => '它', + '' => '尼', + '' => '巨', + '' => '巧', + '' => '左', + '' => '市', + '' => '布', + '' => '平', + '' => '幼', + '' => '弁', + '' => '弘', + '' => '弗', + '' => '必', + '' => '戊', + '' => '打', + '' => '扔', + '' => '扒', + '' => '扑', + '' => '斥', + '' => '旦', + '' => '朮', + '' => '本', + '' => '未', + '' => '末', + '' => '札', + '' => '正', + '' => '母', + '' => '民', + '' => '氐', + '' => '永', + '' => '汁', + '' => '汀', + '' => '氾', + '' => '犯', + '' => '玄', + '' => '玉', + '' => '瓜', + '' => '瓦', + '' => '甘', + '' => '生', + '' => '用', + '' => '甩', + '' => '田', + '' => '由', + '' => '甲', + '' => '申', + '' => '疋', + '' => '白', + '' => '皮', + '' => '皿', + '' => '目', + '' => '矛', + '' => '矢', + '' => '石', + '' => '示', + '' => '禾', + '' => '穴', + '' => '立', + '' => '丞', + '' => '丟', + '' => '乒', + '' => '乓', + '' => '乩', + '' => '亙', + '' => '交', + '' => '亦', + '' => '亥', + '' => '仿', + '' => '伉', + '' => '伙', + '' => '伊', + '' => '伕', + '' => '伍', + '' => '伐', + '' => '休', + '' => '伏', + '' => '仲', + '' => '件', + '' => '任', + '' => '仰', + '' => '仳', + '' => '份', + '' => '企', + '' => '伋', + '' => '光', + '' => '兇', + '' => '兆', + '' => '先', + '' => '全', + '@' => '共', + 'A' => '再', + 'B' => '冰', + 'C' => '列', + 'D' => '刑', + 'E' => '划', + 'F' => '刎', + 'G' => '刖', + 'H' => '劣', + 'I' => '匈', + 'J' => '匡', + 'K' => '匠', + 'L' => '印', + 'M' => '危', + 'N' => '吉', + 'O' => '吏', + 'P' => '同', + 'Q' => '吊', + 'R' => '吐', + 'S' => '吁', + 'T' => '吋', + 'U' => '各', + 'V' => '向', + 'W' => '名', + 'X' => '合', + 'Y' => '吃', + 'Z' => '后', + '[' => '吆', + '\\' => '吒', + ']' => '因', + '^' => '回', + '_' => '囝', + '`' => '圳', + 'a' => '地', + 'b' => '在', + 'c' => '圭', + 'd' => '圬', + 'e' => '圯', + 'f' => '圩', + 'g' => '夙', + 'h' => '多', + 'i' => '夷', + 'j' => '夸', + 'k' => '妄', + 'l' => '奸', + 'm' => '妃', + 'n' => '好', + 'o' => '她', + 'p' => '如', + 'q' => '妁', + 'r' => '字', + 's' => '存', + 't' => '宇', + 'u' => '守', + 'v' => '宅', + 'w' => '安', + 'x' => '寺', + 'y' => '尖', + 'z' => '屹', + '{' => '州', + '|' => '帆', + '}' => '并', + '~' => '年', + '' => '式', + '' => '弛', + '' => '忙', + '' => '忖', + '' => '戎', + '' => '戌', + '' => '戍', + '' => '成', + '' => '扣', + '' => '扛', + '' => '托', + '' => '收', + '' => '早', + '' => '旨', + '' => '旬', + '' => '旭', + '' => '曲', + '' => '曳', + '' => '有', + '' => '朽', + '' => '朴', + '' => '朱', + '' => '朵', + '' => '次', + '' => '此', + '' => '死', + '' => '氖', + '' => '汝', + '' => '汗', + '' => '汙', + '' => '江', + '' => '池', + '' => '汐', + '' => '汕', + '' => '污', + '' => '汛', + '' => '汍', + '' => '汎', + '' => '灰', + '' => '牟', + '' => '牝', + '' => '百', + '' => '竹', + '' => '米', + '' => '糸', + '' => '缶', + '' => '羊', + '' => '羽', + '' => '老', + '' => '考', + '' => '而', + '' => '耒', + '' => '耳', + '' => '聿', + '' => '肉', + '' => '肋', + '' => '肌', + '' => '臣', + '' => '自', + '' => '至', + '' => '臼', + '' => '舌', + '' => '舛', + '' => '舟', + '' => '艮', + '' => '色', + '' => '艾', + '' => '虫', + '' => '血', + '' => '行', + '' => '衣', + '' => '西', + '' => '阡', + '' => '串', + '' => '亨', + '' => '位', + '' => '住', + '' => '佇', + '' => '佗', + '' => '佞', + '' => '伴', + '' => '佛', + '' => '何', + '' => '估', + '' => '佐', + '' => '佑', + '' => '伽', + '' => '伺', + '' => '伸', + '' => '佃', + '' => '佔', + '' => '似', + '' => '但', + '' => '佣', + '@' => '作', + 'A' => '你', + 'B' => '伯', + 'C' => '低', + 'D' => '伶', + 'E' => '余', + 'F' => '佝', + 'G' => '佈', + 'H' => '佚', + 'I' => '兌', + 'J' => '克', + 'K' => '免', + 'L' => '兵', + 'M' => '冶', + 'N' => '冷', + 'O' => '別', + 'P' => '判', + 'Q' => '利', + 'R' => '刪', + 'S' => '刨', + 'T' => '劫', + 'U' => '助', + 'V' => '努', + 'W' => '劬', + 'X' => '匣', + 'Y' => '即', + 'Z' => '卵', + '[' => '吝', + '\\' => '吭', + ']' => '吞', + '^' => '吾', + '_' => '否', + '`' => '呎', + 'a' => '吧', + 'b' => '呆', + 'c' => '呃', + 'd' => '吳', + 'e' => '呈', + 'f' => '呂', + 'g' => '君', + 'h' => '吩', + 'i' => '告', + 'j' => '吹', + 'k' => '吻', + 'l' => '吸', + 'm' => '吮', + 'n' => '吵', + 'o' => '吶', + 'p' => '吠', + 'q' => '吼', + 'r' => '呀', + 's' => '吱', + 't' => '含', + 'u' => '吟', + 'v' => '听', + 'w' => '囪', + 'x' => '困', + 'y' => '囤', + 'z' => '囫', + '{' => '坊', + '|' => '坑', + '}' => '址', + '~' => '坍', + '' => '均', + '' => '坎', + '' => '圾', + '' => '坐', + '' => '坏', + '' => '圻', + '' => '壯', + '' => '夾', + '' => '妝', + '' => '妒', + '' => '妨', + '' => '妞', + '' => '妣', + '' => '妙', + '' => '妖', + '' => '妍', + '' => '妤', + '' => '妓', + '' => '妊', + '' => '妥', + '' => '孝', + '' => '孜', + '' => '孚', + '' => '孛', + '' => '完', + '' => '宋', + '' => '宏', + '' => '尬', + '' => '局', + '' => '屁', + '' => '尿', + '' => '尾', + '' => '岐', + '' => '岑', + '' => '岔', + '' => '岌', + '' => '巫', + '' => '希', + '' => '序', + '' => '庇', + '' => '床', + '' => '廷', + '' => '弄', + '' => '弟', + '' => '彤', + '' => '形', + '' => '彷', + '' => '役', + '' => '忘', + '' => '忌', + '' => '志', + '' => '忍', + '' => '忱', + '' => '快', + '' => '忸', + '' => '忪', + '' => '戒', + '' => '我', + '' => '抄', + '' => '抗', + '' => '抖', + '' => '技', + '' => '扶', + '' => '抉', + '' => '扭', + '' => '把', + '' => '扼', + '' => '找', + '' => '批', + '' => '扳', + '' => '抒', + '' => '扯', + '' => '折', + '' => '扮', + '' => '投', + '' => '抓', + '' => '抑', + '' => '抆', + '' => '改', + '' => '攻', + '' => '攸', + '' => '旱', + '' => '更', + '' => '束', + '' => '李', + '' => '杏', + '' => '材', + '' => '村', + '' => '杜', + '' => '杖', + '' => '杞', + '' => '杉', + '' => '杆', + '' => '杠', + '@' => '杓', + 'A' => '杗', + 'B' => '步', + 'C' => '每', + 'D' => '求', + 'E' => '汞', + 'F' => '沙', + 'G' => '沁', + 'H' => '沈', + 'I' => '沉', + 'J' => '沅', + 'K' => '沛', + 'L' => '汪', + 'M' => '決', + 'N' => '沐', + 'O' => '汰', + 'P' => '沌', + 'Q' => '汨', + 'R' => '沖', + 'S' => '沒', + 'T' => '汽', + 'U' => '沃', + 'V' => '汲', + 'W' => '汾', + 'X' => '汴', + 'Y' => '沆', + 'Z' => '汶', + '[' => '沍', + '\\' => '沔', + ']' => '沘', + '^' => '沂', + '_' => '灶', + '`' => '灼', + 'a' => '災', + 'b' => '灸', + 'c' => '牢', + 'd' => '牡', + 'e' => '牠', + 'f' => '狄', + 'g' => '狂', + 'h' => '玖', + 'i' => '甬', + 'j' => '甫', + 'k' => '男', + 'l' => '甸', + 'm' => '皂', + 'n' => '盯', + 'o' => '矣', + 'p' => '私', + 'q' => '秀', + 'r' => '禿', + 's' => '究', + 't' => '系', + 'u' => '罕', + 'v' => '肖', + 'w' => '肓', + 'x' => '肝', + 'y' => '肘', + 'z' => '肛', + '{' => '肚', + '|' => '育', + '}' => '良', + '~' => '芒', + '' => '芋', + '' => '芍', + '' => '見', + '' => '角', + '' => '言', + '' => '谷', + '' => '豆', + '' => '豕', + '' => '貝', + '' => '赤', + '' => '走', + '' => '足', + '' => '身', + '' => '車', + '' => '辛', + '' => '辰', + '' => '迂', + '' => '迆', + '' => '迅', + '' => '迄', + '' => '巡', + '' => '邑', + '' => '邢', + '' => '邪', + '' => '邦', + '' => '那', + '' => '酉', + '' => '釆', + '' => '里', + '' => '防', + '' => '阮', + '' => '阱', + '' => '阪', + '' => '阬', + '' => '並', + '' => '乖', + '' => '乳', + '' => '事', + '' => '些', + '' => '亞', + '' => '享', + '' => '京', + '' => '佯', + '' => '依', + '' => '侍', + '' => '佳', + '' => '使', + '' => '佬', + '' => '供', + '' => '例', + '' => '來', + '' => '侃', + '' => '佰', + '' => '併', + '' => '侈', + '' => '佩', + '' => '佻', + '' => '侖', + '' => '佾', + '' => '侏', + '' => '侑', + '' => '佺', + '' => '兔', + '' => '兒', + '' => '兕', + '' => '兩', + '' => '具', + '' => '其', + '' => '典', + '' => '冽', + '' => '函', + '' => '刻', + '' => '券', + '' => '刷', + '' => '刺', + '' => '到', + '' => '刮', + '' => '制', + '' => '剁', + '' => '劾', + '' => '劻', + '' => '卒', + '' => '協', + '' => '卓', + '' => '卑', + '' => '卦', + '' => '卷', + '' => '卸', + '' => '卹', + '' => '取', + '' => '叔', + '' => '受', + '' => '味', + '' => '呵', + '@' => '咖', + 'A' => '呸', + 'B' => '咕', + 'C' => '咀', + 'D' => '呻', + 'E' => '呷', + 'F' => '咄', + 'G' => '咒', + 'H' => '咆', + 'I' => '呼', + 'J' => '咐', + 'K' => '呱', + 'L' => '呶', + 'M' => '和', + 'N' => '咚', + 'O' => '呢', + 'P' => '周', + 'Q' => '咋', + 'R' => '命', + 'S' => '咎', + 'T' => '固', + 'U' => '垃', + 'V' => '坷', + 'W' => '坪', + 'X' => '坩', + 'Y' => '坡', + 'Z' => '坦', + '[' => '坤', + '\\' => '坼', + ']' => '夜', + '^' => '奉', + '_' => '奇', + '`' => '奈', + 'a' => '奄', + 'b' => '奔', + 'c' => '妾', + 'd' => '妻', + 'e' => '委', + 'f' => '妹', + 'g' => '妮', + 'h' => '姑', + 'i' => '姆', + 'j' => '姐', + 'k' => '姍', + 'l' => '始', + 'm' => '姓', + 'n' => '姊', + 'o' => '妯', + 'p' => '妳', + 'q' => '姒', + 'r' => '姅', + 's' => '孟', + 't' => '孤', + 'u' => '季', + 'v' => '宗', + 'w' => '定', + 'x' => '官', + 'y' => '宜', + 'z' => '宙', + '{' => '宛', + '|' => '尚', + '}' => '屈', + '~' => '居', + '' => '屆', + '' => '岷', + '' => '岡', + '' => '岸', + '' => '岩', + '' => '岫', + '' => '岱', + '' => '岳', + '' => '帘', + '' => '帚', + '' => '帖', + '' => '帕', + '' => '帛', + '' => '帑', + '' => '幸', + '' => '庚', + '' => '店', + '' => '府', + '' => '底', + '' => '庖', + '' => '延', + '' => '弦', + '' => '弧', + '' => '弩', + '' => '往', + '' => '征', + '' => '彿', + '' => '彼', + '' => '忝', + '' => '忠', + '' => '忽', + '' => '念', + '' => '忿', + '' => '怏', + '' => '怔', + '' => '怯', + '' => '怵', + '' => '怖', + '' => '怪', + '' => '怕', + '' => '怡', + '' => '性', + '' => '怩', + '' => '怫', + '' => '怛', + '' => '或', + '' => '戕', + '' => '房', + '' => '戾', + '' => '所', + '' => '承', + '' => '拉', + '' => '拌', + '' => '拄', + '' => '抿', + '' => '拂', + '' => '抹', + '' => '拒', + '' => '招', + '' => '披', + '' => '拓', + '' => '拔', + '' => '拋', + '' => '拈', + '' => '抨', + '' => '抽', + '' => '押', + '' => '拐', + '' => '拙', + '' => '拇', + '' => '拍', + '' => '抵', + '' => '拚', + '' => '抱', + '' => '拘', + '' => '拖', + '' => '拗', + '' => '拆', + '' => '抬', + '' => '拎', + '' => '放', + '' => '斧', + '' => '於', + '' => '旺', + '' => '昔', + '' => '易', + '' => '昌', + '' => '昆', + '' => '昂', + '' => '明', + '' => '昀', + '' => '昏', + '' => '昕', + '' => '昊', + '@' => '昇', + 'A' => '服', + 'B' => '朋', + 'C' => '杭', + 'D' => '枋', + 'E' => '枕', + 'F' => '東', + 'G' => '果', + 'H' => '杳', + 'I' => '杷', + 'J' => '枇', + 'K' => '枝', + 'L' => '林', + 'M' => '杯', + 'N' => '杰', + 'O' => '板', + 'P' => '枉', + 'Q' => '松', + 'R' => '析', + 'S' => '杵', + 'T' => '枚', + 'U' => '枓', + 'V' => '杼', + 'W' => '杪', + 'X' => '杲', + 'Y' => '欣', + 'Z' => '武', + '[' => '歧', + '\\' => '歿', + ']' => '氓', + '^' => '氛', + '_' => '泣', + '`' => '注', + 'a' => '泳', + 'b' => '沱', + 'c' => '泌', + 'd' => '泥', + 'e' => '河', + 'f' => '沽', + 'g' => '沾', + 'h' => '沼', + 'i' => '波', + 'j' => '沫', + 'k' => '法', + 'l' => '泓', + 'm' => '沸', + 'n' => '泄', + 'o' => '油', + 'p' => '況', + 'q' => '沮', + 'r' => '泗', + 's' => '泅', + 't' => '泱', + 'u' => '沿', + 'v' => '治', + 'w' => '泡', + 'x' => '泛', + 'y' => '泊', + 'z' => '沬', + '{' => '泯', + '|' => '泜', + '}' => '泖', + '~' => '泠', + '' => '炕', + '' => '炎', + '' => '炒', + '' => '炊', + '' => '炙', + '' => '爬', + '' => '爭', + '' => '爸', + '' => '版', + '' => '牧', + '' => '物', + '' => '狀', + '' => '狎', + '' => '狙', + '' => '狗', + '' => '狐', + '' => '玩', + '' => '玨', + '' => '玟', + '' => '玫', + '' => '玥', + '' => '甽', + '' => '疝', + '' => '疙', + '' => '疚', + '' => '的', + '' => '盂', + '' => '盲', + '' => '直', + '' => '知', + '' => '矽', + '' => '社', + '' => '祀', + '' => '祁', + '' => '秉', + '' => '秈', + '' => '空', + '' => '穹', + '' => '竺', + '' => '糾', + '' => '罔', + '' => '羌', + '' => '羋', + '' => '者', + '' => '肺', + '' => '肥', + '' => '肢', + '' => '肱', + '' => '股', + '' => '肫', + '' => '肩', + '' => '肴', + '' => '肪', + '' => '肯', + '' => '臥', + '' => '臾', + '' => '舍', + '' => '芳', + '' => '芝', + '' => '芙', + '' => '芭', + '' => '芽', + '' => '芟', + '' => '芹', + '' => '花', + '' => '芬', + '' => '芥', + '' => '芯', + '' => '芸', + '' => '芣', + '' => '芰', + '' => '芾', + '' => '芷', + '' => '虎', + '' => '虱', + '' => '初', + '' => '表', + '' => '軋', + '' => '迎', + '' => '返', + '' => '近', + '' => '邵', + '' => '邸', + '' => '邱', + '' => '邶', + '' => '采', + '' => '金', + '' => '長', + '' => '門', + '' => '阜', + '' => '陀', + '' => '阿', + '' => '阻', + '' => '附', + '@' => '陂', + 'A' => '隹', + 'B' => '雨', + 'C' => '青', + 'D' => '非', + 'E' => '亟', + 'F' => '亭', + 'G' => '亮', + 'H' => '信', + 'I' => '侵', + 'J' => '侯', + 'K' => '便', + 'L' => '俠', + 'M' => '俑', + 'N' => '俏', + 'O' => '保', + 'P' => '促', + 'Q' => '侶', + 'R' => '俘', + 'S' => '俟', + 'T' => '俊', + 'U' => '俗', + 'V' => '侮', + 'W' => '俐', + 'X' => '俄', + 'Y' => '係', + 'Z' => '俚', + '[' => '俎', + '\\' => '俞', + ']' => '侷', + '^' => '兗', + '_' => '冒', + '`' => '冑', + 'a' => '冠', + 'b' => '剎', + 'c' => '剃', + 'd' => '削', + 'e' => '前', + 'f' => '剌', + 'g' => '剋', + 'h' => '則', + 'i' => '勇', + 'j' => '勉', + 'k' => '勃', + 'l' => '勁', + 'm' => '匍', + 'n' => '南', + 'o' => '卻', + 'p' => '厚', + 'q' => '叛', + 'r' => '咬', + 's' => '哀', + 't' => '咨', + 'u' => '哎', + 'v' => '哉', + 'w' => '咸', + 'x' => '咦', + 'y' => '咳', + 'z' => '哇', + '{' => '哂', + '|' => '咽', + '}' => '咪', + '~' => '品', + '' => '哄', + '' => '哈', + '' => '咯', + '' => '咫', + '' => '咱', + '' => '咻', + '' => '咩', + '' => '咧', + '' => '咿', + '' => '囿', + '' => '垂', + '' => '型', + '' => '垠', + '' => '垣', + '' => '垢', + '' => '城', + '' => '垮', + '' => '垓', + '' => '奕', + '' => '契', + '' => '奏', + '' => '奎', + '' => '奐', + '' => '姜', + '' => '姘', + '' => '姿', + '' => '姣', + '' => '姨', + '' => '娃', + '' => '姥', + '' => '姪', + '' => '姚', + '' => '姦', + '' => '威', + '' => '姻', + '' => '孩', + '' => '宣', + '' => '宦', + '' => '室', + '' => '客', + '' => '宥', + '' => '封', + '' => '屎', + '' => '屏', + '' => '屍', + '' => '屋', + '' => '峙', + '' => '峒', + '' => '巷', + '' => '帝', + '' => '帥', + '' => '帟', + '' => '幽', + '' => '庠', + '' => '度', + '' => '建', + '' => '弈', + '' => '弭', + '' => '彥', + '' => '很', + '' => '待', + '' => '徊', + '' => '律', + '' => '徇', + '' => '後', + '' => '徉', + '' => '怒', + '' => '思', + '' => '怠', + '' => '急', + '' => '怎', + '' => '怨', + '' => '恍', + '' => '恰', + '' => '恨', + '' => '恢', + '' => '恆', + '' => '恃', + '' => '恬', + '' => '恫', + '' => '恪', + '' => '恤', + '' => '扁', + '' => '拜', + '' => '挖', + '' => '按', + '' => '拼', + '' => '拭', + '' => '持', + '' => '拮', + '' => '拽', + '' => '指', + '' => '拱', + '' => '拷', + '@' => '拯', + 'A' => '括', + 'B' => '拾', + 'C' => '拴', + 'D' => '挑', + 'E' => '挂', + 'F' => '政', + 'G' => '故', + 'H' => '斫', + 'I' => '施', + 'J' => '既', + 'K' => '春', + 'L' => '昭', + 'M' => '映', + 'N' => '昧', + 'O' => '是', + 'P' => '星', + 'Q' => '昨', + 'R' => '昱', + 'S' => '昤', + 'T' => '曷', + 'U' => '柿', + 'V' => '染', + 'W' => '柱', + 'X' => '柔', + 'Y' => '某', + 'Z' => '柬', + '[' => '架', + '\\' => '枯', + ']' => '柵', + '^' => '柩', + '_' => '柯', + '`' => '柄', + 'a' => '柑', + 'b' => '枴', + 'c' => '柚', + 'd' => '查', + 'e' => '枸', + 'f' => '柏', + 'g' => '柞', + 'h' => '柳', + 'i' => '枰', + 'j' => '柙', + 'k' => '柢', + 'l' => '柝', + 'm' => '柒', + 'n' => '歪', + 'o' => '殃', + 'p' => '殆', + 'q' => '段', + 'r' => '毒', + 's' => '毗', + 't' => '氟', + 'u' => '泉', + 'v' => '洋', + 'w' => '洲', + 'x' => '洪', + 'y' => '流', + 'z' => '津', + '{' => '洌', + '|' => '洱', + '}' => '洞', + '~' => '洗', + '' => '活', + '' => '洽', + '' => '派', + '' => '洶', + '' => '洛', + '' => '泵', + '' => '洹', + '' => '洧', + '' => '洸', + '' => '洩', + '' => '洮', + '' => '洵', + '' => '洎', + '' => '洫', + '' => '炫', + '' => '為', + '' => '炳', + '' => '炬', + '' => '炯', + '' => '炭', + '' => '炸', + '' => '炮', + '' => '炤', + '' => '爰', + '' => '牲', + '' => '牯', + '' => '牴', + '' => '狩', + '' => '狠', + '' => '狡', + '' => '玷', + '' => '珊', + '' => '玻', + '' => '玲', + '' => '珍', + '' => '珀', + '' => '玳', + '' => '甚', + '' => '甭', + '' => '畏', + '' => '界', + '' => '畎', + '' => '畋', + '' => '疫', + '' => '疤', + '' => '疥', + '' => '疢', + '' => '疣', + '' => '癸', + '' => '皆', + '' => '皇', + '' => '皈', + '' => '盈', + '' => '盆', + '' => '盃', + '' => '盅', + '' => '省', + '' => '盹', + '' => '相', + '' => '眉', + '' => '看', + '' => '盾', + '' => '盼', + '' => '眇', + '' => '矜', + '' => '砂', + '' => '研', + '' => '砌', + '' => '砍', + '' => '祆', + '' => '祉', + '' => '祈', + '' => '祇', + '' => '禹', + '' => '禺', + '' => '科', + '' => '秒', + '' => '秋', + '' => '穿', + '' => '突', + '' => '竿', + '' => '竽', + '' => '籽', + '' => '紂', + '' => '紅', + '' => '紀', + '' => '紉', + '' => '紇', + '' => '約', + '' => '紆', + '' => '缸', + '' => '美', + '' => '羿', + '' => '耄', + '@' => '耐', + 'A' => '耍', + 'B' => '耑', + 'C' => '耶', + 'D' => '胖', + 'E' => '胥', + 'F' => '胚', + 'G' => '胃', + 'H' => '胄', + 'I' => '背', + 'J' => '胡', + 'K' => '胛', + 'L' => '胎', + 'M' => '胞', + 'N' => '胤', + 'O' => '胝', + 'P' => '致', + 'Q' => '舢', + 'R' => '苧', + 'S' => '范', + 'T' => '茅', + 'U' => '苣', + 'V' => '苛', + 'W' => '苦', + 'X' => '茄', + 'Y' => '若', + 'Z' => '茂', + '[' => '茉', + '\\' => '苒', + ']' => '苗', + '^' => '英', + '_' => '茁', + '`' => '苜', + 'a' => '苔', + 'b' => '苑', + 'c' => '苞', + 'd' => '苓', + 'e' => '苟', + 'f' => '苯', + 'g' => '茆', + 'h' => '虐', + 'i' => '虹', + 'j' => '虻', + 'k' => '虺', + 'l' => '衍', + 'm' => '衫', + 'n' => '要', + 'o' => '觔', + 'p' => '計', + 'q' => '訂', + 'r' => '訃', + 's' => '貞', + 't' => '負', + 'u' => '赴', + 'v' => '赳', + 'w' => '趴', + 'x' => '軍', + 'y' => '軌', + 'z' => '述', + '{' => '迦', + '|' => '迢', + '}' => '迪', + '~' => '迥', + '' => '迭', + '' => '迫', + '' => '迤', + '' => '迨', + '' => '郊', + '' => '郎', + '' => '郁', + '' => '郃', + '' => '酋', + '' => '酊', + '' => '重', + '' => '閂', + '' => '限', + '' => '陋', + '' => '陌', + '' => '降', + '' => '面', + '' => '革', + '' => '韋', + '' => '韭', + '' => '音', + '' => '頁', + '' => '風', + '' => '飛', + '' => '食', + '' => '首', + '' => '香', + '' => '乘', + '' => '亳', + '' => '倌', + '' => '倍', + '' => '倣', + '' => '俯', + '' => '倦', + '' => '倥', + '' => '俸', + '' => '倩', + '' => '倖', + '' => '倆', + '' => '值', + '' => '借', + '' => '倚', + '' => '倒', + '' => '們', + '' => '俺', + '' => '倀', + '' => '倔', + '' => '倨', + '' => '俱', + '' => '倡', + '' => '個', + '' => '候', + '' => '倘', + '' => '俳', + '' => '修', + '' => '倭', + '' => '倪', + '' => '俾', + '' => '倫', + '' => '倉', + '' => '兼', + '' => '冤', + '' => '冥', + '' => '冢', + '' => '凍', + '' => '凌', + '' => '准', + '' => '凋', + '' => '剖', + '' => '剜', + '' => '剔', + '' => '剛', + '' => '剝', + '' => '匪', + '' => '卿', + '' => '原', + '' => '厝', + '' => '叟', + '' => '哨', + '' => '唐', + '' => '唁', + '' => '唷', + '' => '哼', + '' => '哥', + '' => '哲', + '' => '唆', + '' => '哺', + '' => '唔', + '' => '哩', + '' => '哭', + '' => '員', + '' => '唉', + '' => '哮', + '' => '哪', + '@' => '哦', + 'A' => '唧', + 'B' => '唇', + 'C' => '哽', + 'D' => '唏', + 'E' => '圃', + 'F' => '圄', + 'G' => '埂', + 'H' => '埔', + 'I' => '埋', + 'J' => '埃', + 'K' => '堉', + 'L' => '夏', + 'M' => '套', + 'N' => '奘', + 'O' => '奚', + 'P' => '娑', + 'Q' => '娘', + 'R' => '娜', + 'S' => '娟', + 'T' => '娛', + 'U' => '娓', + 'V' => '姬', + 'W' => '娠', + 'X' => '娣', + 'Y' => '娩', + 'Z' => '娥', + '[' => '娌', + '\\' => '娉', + ']' => '孫', + '^' => '屘', + '_' => '宰', + '`' => '害', + 'a' => '家', + 'b' => '宴', + 'c' => '宮', + 'd' => '宵', + 'e' => '容', + 'f' => '宸', + 'g' => '射', + 'h' => '屑', + 'i' => '展', + 'j' => '屐', + 'k' => '峭', + 'l' => '峽', + 'm' => '峻', + 'n' => '峪', + 'o' => '峨', + 'p' => '峰', + 'q' => '島', + 'r' => '崁', + 's' => '峴', + 't' => '差', + 'u' => '席', + 'v' => '師', + 'w' => '庫', + 'x' => '庭', + 'y' => '座', + 'z' => '弱', + '{' => '徒', + '|' => '徑', + '}' => '徐', + '~' => '恙', + '' => '恣', + '' => '恥', + '' => '恐', + '' => '恕', + '' => '恭', + '' => '恩', + '' => '息', + '' => '悄', + '' => '悟', + '' => '悚', + '' => '悍', + '' => '悔', + '' => '悌', + '' => '悅', + '' => '悖', + '' => '扇', + '' => '拳', + '' => '挈', + '' => '拿', + '' => '捎', + '' => '挾', + '' => '振', + '' => '捕', + '' => '捂', + '' => '捆', + '' => '捏', + '' => '捉', + '' => '挺', + '' => '捐', + '' => '挽', + '' => '挪', + '' => '挫', + '' => '挨', + '' => '捍', + '' => '捌', + '' => '效', + '' => '敉', + '' => '料', + '' => '旁', + '' => '旅', + '' => '時', + '' => '晉', + '' => '晏', + '' => '晃', + '' => '晒', + '' => '晌', + '' => '晅', + '' => '晁', + '' => '書', + '' => '朔', + '' => '朕', + '' => '朗', + '' => '校', + '' => '核', + '' => '案', + '' => '框', + '' => '桓', + '' => '根', + '' => '桂', + '' => '桔', + '' => '栩', + '' => '梳', + '' => '栗', + '' => '桌', + '' => '桑', + '' => '栽', + '' => '柴', + '' => '桐', + '' => '桀', + '' => '格', + '' => '桃', + '' => '株', + '' => '桅', + '' => '栓', + '' => '栘', + '' => '桁', + '' => '殊', + '' => '殉', + '' => '殷', + '' => '氣', + '' => '氧', + '' => '氨', + '' => '氦', + '' => '氤', + '' => '泰', + '' => '浪', + '' => '涕', + '' => '消', + '' => '涇', + '' => '浦', + '' => '浸', + '' => '海', + '' => '浙', + '' => '涓', + '@' => '浬', + 'A' => '涉', + 'B' => '浮', + 'C' => '浚', + 'D' => '浴', + 'E' => '浩', + 'F' => '涌', + 'G' => '涊', + 'H' => '浹', + 'I' => '涅', + 'J' => '浥', + 'K' => '涔', + 'L' => '烊', + 'M' => '烘', + 'N' => '烤', + 'O' => '烙', + 'P' => '烈', + 'Q' => '烏', + 'R' => '爹', + 'S' => '特', + 'T' => '狼', + 'U' => '狹', + 'V' => '狽', + 'W' => '狸', + 'X' => '狷', + 'Y' => '玆', + 'Z' => '班', + '[' => '琉', + '\\' => '珮', + ']' => '珠', + '^' => '珪', + '_' => '珞', + '`' => '畔', + 'a' => '畝', + 'b' => '畜', + 'c' => '畚', + 'd' => '留', + 'e' => '疾', + 'f' => '病', + 'g' => '症', + 'h' => '疲', + 'i' => '疳', + 'j' => '疽', + 'k' => '疼', + 'l' => '疹', + 'm' => '痂', + 'n' => '疸', + 'o' => '皋', + 'p' => '皰', + 'q' => '益', + 'r' => '盍', + 's' => '盎', + 't' => '眩', + 'u' => '真', + 'v' => '眠', + 'w' => '眨', + 'x' => '矩', + 'y' => '砰', + 'z' => '砧', + '{' => '砸', + '|' => '砝', + '}' => '破', + '~' => '砷', + '' => '砥', + '' => '砭', + '' => '砠', + '' => '砟', + '' => '砲', + '' => '祕', + '' => '祐', + '' => '祠', + '' => '祟', + '' => '祖', + '' => '神', + '' => '祝', + '' => '祗', + '' => '祚', + '' => '秤', + '' => '秣', + '' => '秧', + '' => '租', + '' => '秦', + '' => '秩', + '' => '秘', + '' => '窄', + '' => '窈', + '' => '站', + '' => '笆', + '' => '笑', + '' => '粉', + '' => '紡', + '' => '紗', + '' => '紋', + '' => '紊', + '' => '素', + '' => '索', + '' => '純', + '' => '紐', + '' => '紕', + '' => '級', + '' => '紜', + '' => '納', + '' => '紙', + '' => '紛', + '' => '缺', + '' => '罟', + '' => '羔', + '' => '翅', + '' => '翁', + '' => '耆', + '' => '耘', + '' => '耕', + '' => '耙', + '' => '耗', + '' => '耽', + '' => '耿', + '' => '胱', + '' => '脂', + '' => '胰', + '' => '脅', + '' => '胭', + '' => '胴', + '' => '脆', + '' => '胸', + '' => '胳', + '' => '脈', + '' => '能', + '' => '脊', + '' => '胼', + '' => '胯', + '' => '臭', + '' => '臬', + '' => '舀', + '' => '舐', + '' => '航', + '' => '舫', + '' => '舨', + '' => '般', + '' => '芻', + '' => '茫', + '' => '荒', + '' => '荔', + '' => '荊', + '' => '茸', + '' => '荐', + '' => '草', + '' => '茵', + '' => '茴', + '' => '荏', + '' => '茲', + '' => '茹', + '' => '茶', + '' => '茗', + '' => '荀', + '' => '茱', + '' => '茨', + '' => '荃', + '@' => '虔', + 'A' => '蚊', + 'B' => '蚪', + 'C' => '蚓', + 'D' => '蚤', + 'E' => '蚩', + 'F' => '蚌', + 'G' => '蚣', + 'H' => '蚜', + 'I' => '衰', + 'J' => '衷', + 'K' => '袁', + 'L' => '袂', + 'M' => '衽', + 'N' => '衹', + 'O' => '記', + 'P' => '訐', + 'Q' => '討', + 'R' => '訌', + 'S' => '訕', + 'T' => '訊', + 'U' => '託', + 'V' => '訓', + 'W' => '訖', + 'X' => '訏', + 'Y' => '訑', + 'Z' => '豈', + '[' => '豺', + '\\' => '豹', + ']' => '財', + '^' => '貢', + '_' => '起', + '`' => '躬', + 'a' => '軒', + 'b' => '軔', + 'c' => '軏', + 'd' => '辱', + 'e' => '送', + 'f' => '逆', + 'g' => '迷', + 'h' => '退', + 'i' => '迺', + 'j' => '迴', + 'k' => '逃', + 'l' => '追', + 'm' => '逅', + 'n' => '迸', + 'o' => '邕', + 'p' => '郡', + 'q' => '郝', + 'r' => '郢', + 's' => '酒', + 't' => '配', + 'u' => '酌', + 'v' => '釘', + 'w' => '針', + 'x' => '釗', + 'y' => '釜', + 'z' => '釙', + '{' => '閃', + '|' => '院', + '}' => '陣', + '~' => '陡', + '' => '陛', + '' => '陝', + '' => '除', + '' => '陘', + '' => '陞', + '' => '隻', + '' => '飢', + '' => '馬', + '' => '骨', + '' => '高', + '' => '鬥', + '' => '鬲', + '' => '鬼', + '' => '乾', + '' => '偺', + '' => '偽', + '' => '停', + '' => '假', + '' => '偃', + '' => '偌', + '' => '做', + '' => '偉', + '' => '健', + '' => '偶', + '' => '偎', + '' => '偕', + '' => '偵', + '' => '側', + '' => '偷', + '' => '偏', + '' => '倏', + '' => '偯', + '' => '偭', + '' => '兜', + '' => '冕', + '' => '凰', + '' => '剪', + '' => '副', + '' => '勒', + '' => '務', + '' => '勘', + '' => '動', + '' => '匐', + '' => '匏', + '' => '匙', + '' => '匿', + '' => '區', + '' => '匾', + '' => '參', + '' => '曼', + '' => '商', + '' => '啪', + '' => '啦', + '' => '啄', + '' => '啞', + '' => '啡', + '' => '啃', + '' => '啊', + '' => '唱', + '' => '啖', + '' => '問', + '' => '啕', + '' => '唯', + '' => '啤', + '' => '唸', + '' => '售', + '' => '啜', + '' => '唬', + '' => '啣', + '' => '唳', + '' => '啁', + '' => '啗', + '' => '圈', + '' => '國', + '' => '圉', + '' => '域', + '' => '堅', + '' => '堊', + '' => '堆', + '' => '埠', + '' => '埤', + '' => '基', + '' => '堂', + '' => '堵', + '' => '執', + '' => '培', + '' => '夠', + '' => '奢', + '' => '娶', + '' => '婁', + '' => '婉', + '' => '婦', + '' => '婪', + '' => '婀', + '@' => '娼', + 'A' => '婢', + 'B' => '婚', + 'C' => '婆', + 'D' => '婊', + 'E' => '孰', + 'F' => '寇', + 'G' => '寅', + 'H' => '寄', + 'I' => '寂', + 'J' => '宿', + 'K' => '密', + 'L' => '尉', + 'M' => '專', + 'N' => '將', + 'O' => '屠', + 'P' => '屜', + 'Q' => '屝', + 'R' => '崇', + 'S' => '崆', + 'T' => '崎', + 'U' => '崛', + 'V' => '崖', + 'W' => '崢', + 'X' => '崑', + 'Y' => '崩', + 'Z' => '崔', + '[' => '崙', + '\\' => '崤', + ']' => '崧', + '^' => '崗', + '_' => '巢', + '`' => '常', + 'a' => '帶', + 'b' => '帳', + 'c' => '帷', + 'd' => '康', + 'e' => '庸', + 'f' => '庶', + 'g' => '庵', + 'h' => '庾', + 'i' => '張', + 'j' => '強', + 'k' => '彗', + 'l' => '彬', + 'm' => '彩', + 'n' => '彫', + 'o' => '得', + 'p' => '徙', + 'q' => '從', + 'r' => '徘', + 's' => '御', + 't' => '徠', + 'u' => '徜', + 'v' => '恿', + 'w' => '患', + 'x' => '悉', + 'y' => '悠', + 'z' => '您', + '{' => '惋', + '|' => '悴', + '}' => '惦', + '~' => '悽', + '' => '情', + '' => '悻', + '' => '悵', + '' => '惜', + '' => '悼', + '' => '惘', + '' => '惕', + '' => '惆', + '' => '惟', + '' => '悸', + '' => '惚', + '' => '惇', + '' => '戚', + '' => '戛', + '' => '扈', + '' => '掠', + '' => '控', + '' => '捲', + '' => '掖', + '' => '探', + '' => '接', + '' => '捷', + '' => '捧', + '' => '掘', + '' => '措', + '' => '捱', + '' => '掩', + '' => '掉', + '' => '掃', + '' => '掛', + '' => '捫', + '' => '推', + '' => '掄', + '' => '授', + '' => '掙', + '' => '採', + '' => '掬', + '' => '排', + '' => '掏', + '' => '掀', + '' => '捻', + '' => '捩', + '' => '捨', + '' => '捺', + '' => '敝', + '' => '敖', + '' => '救', + '' => '教', + '' => '敗', + '' => '啟', + '' => '敏', + '' => '敘', + '' => '敕', + '' => '敔', + '' => '斜', + '' => '斛', + '' => '斬', + '' => '族', + '' => '旋', + '' => '旌', + '' => '旎', + '' => '晝', + '' => '晚', + '' => '晤', + '' => '晨', + '' => '晦', + '' => '晞', + '' => '曹', + '' => '勗', + '' => '望', + '' => '梁', + '' => '梯', + '' => '梢', + '' => '梓', + '' => '梵', + '' => '桿', + '' => '桶', + '' => '梱', + '' => '梧', + '' => '梗', + '' => '械', + '' => '梃', + '' => '棄', + '' => '梭', + '' => '梆', + '' => '梅', + '' => '梔', + '' => '條', + '' => '梨', + '' => '梟', + '' => '梡', + '' => '梂', + '' => '欲', + '' => '殺', + '@' => '毫', + 'A' => '毬', + 'B' => '氫', + 'C' => '涎', + 'D' => '涼', + 'E' => '淳', + 'F' => '淙', + 'G' => '液', + 'H' => '淡', + 'I' => '淌', + 'J' => '淤', + 'K' => '添', + 'L' => '淺', + 'M' => '清', + 'N' => '淇', + 'O' => '淋', + 'P' => '涯', + 'Q' => '淑', + 'R' => '涮', + 'S' => '淞', + 'T' => '淹', + 'U' => '涸', + 'V' => '混', + 'W' => '淵', + 'X' => '淅', + 'Y' => '淒', + 'Z' => '渚', + '[' => '涵', + '\\' => '淚', + ']' => '淫', + '^' => '淘', + '_' => '淪', + '`' => '深', + 'a' => '淮', + 'b' => '淨', + 'c' => '淆', + 'd' => '淄', + 'e' => '涪', + 'f' => '淬', + 'g' => '涿', + 'h' => '淦', + 'i' => '烹', + 'j' => '焉', + 'k' => '焊', + 'l' => '烽', + 'm' => '烯', + 'n' => '爽', + 'o' => '牽', + 'p' => '犁', + 'q' => '猜', + 'r' => '猛', + 's' => '猖', + 't' => '猓', + 'u' => '猙', + 'v' => '率', + 'w' => '琅', + 'x' => '琊', + 'y' => '球', + 'z' => '理', + '{' => '現', + '|' => '琍', + '}' => '瓠', + '~' => '瓶', + '' => '瓷', + '' => '甜', + '' => '產', + '' => '略', + '' => '畦', + '' => '畢', + '' => '異', + '' => '疏', + '' => '痔', + '' => '痕', + '' => '疵', + '' => '痊', + '' => '痍', + '' => '皎', + '' => '盔', + '' => '盒', + '' => '盛', + '' => '眷', + '' => '眾', + '' => '眼', + '' => '眶', + '' => '眸', + '' => '眺', + '' => '硫', + '' => '硃', + '' => '硎', + '' => '祥', + '' => '票', + '' => '祭', + '' => '移', + '' => '窒', + '' => '窕', + '' => '笠', + '' => '笨', + '' => '笛', + '' => '第', + '' => '符', + '' => '笙', + '' => '笞', + '' => '笮', + '' => '粒', + '' => '粗', + '' => '粕', + '' => '絆', + '' => '絃', + '' => '統', + '' => '紮', + '' => '紹', + '' => '紼', + '' => '絀', + '' => '細', + '' => '紳', + '' => '組', + '' => '累', + '' => '終', + '' => '紲', + '' => '紱', + '' => '缽', + '' => '羞', + '' => '羚', + '' => '翌', + '' => '翎', + '' => '習', + '' => '耜', + '' => '聊', + '' => '聆', + '' => '脯', + '' => '脖', + '' => '脣', + '' => '脫', + '' => '脩', + '' => '脰', + '' => '脤', + '' => '舂', + '' => '舵', + '' => '舷', + '' => '舶', + '' => '船', + '' => '莎', + '' => '莞', + '' => '莘', + '' => '荸', + '' => '莢', + '' => '莖', + '' => '莽', + '' => '莫', + '' => '莒', + '' => '莊', + '' => '莓', + '' => '莉', + '' => '莠', + '' => '荷', + '' => '荻', + '' => '荼', + '@' => '莆', + 'A' => '莧', + 'B' => '處', + 'C' => '彪', + 'D' => '蛇', + 'E' => '蛀', + 'F' => '蚶', + 'G' => '蛄', + 'H' => '蚵', + 'I' => '蛆', + 'J' => '蛋', + 'K' => '蚱', + 'L' => '蚯', + 'M' => '蛉', + 'N' => '術', + 'O' => '袞', + 'P' => '袈', + 'Q' => '被', + 'R' => '袒', + 'S' => '袖', + 'T' => '袍', + 'U' => '袋', + 'V' => '覓', + 'W' => '規', + 'X' => '訪', + 'Y' => '訝', + 'Z' => '訣', + '[' => '訥', + '\\' => '許', + ']' => '設', + '^' => '訟', + '_' => '訛', + '`' => '訢', + 'a' => '豉', + 'b' => '豚', + 'c' => '販', + 'd' => '責', + 'e' => '貫', + 'f' => '貨', + 'g' => '貪', + 'h' => '貧', + 'i' => '赧', + 'j' => '赦', + 'k' => '趾', + 'l' => '趺', + 'm' => '軛', + 'n' => '軟', + 'o' => '這', + 'p' => '逍', + 'q' => '通', + 'r' => '逗', + 's' => '連', + 't' => '速', + 'u' => '逝', + 'v' => '逐', + 'w' => '逕', + 'x' => '逞', + 'y' => '造', + 'z' => '透', + '{' => '逢', + '|' => '逖', + '}' => '逛', + '~' => '途', + '' => '部', + '' => '郭', + '' => '都', + '' => '酗', + '' => '野', + '' => '釵', + '' => '釦', + '' => '釣', + '' => '釧', + '' => '釭', + '' => '釩', + '' => '閉', + '' => '陪', + '' => '陵', + '' => '陳', + '' => '陸', + '' => '陰', + '' => '陴', + '' => '陶', + '' => '陷', + '' => '陬', + '' => '雀', + '' => '雪', + '' => '雩', + '' => '章', + '' => '竟', + '' => '頂', + '' => '頃', + '' => '魚', + '' => '鳥', + '' => '鹵', + '' => '鹿', + '' => '麥', + '' => '麻', + '' => '傢', + '' => '傍', + '' => '傅', + '' => '備', + '' => '傑', + '' => '傀', + '' => '傖', + '' => '傘', + '' => '傚', + '' => '最', + '' => '凱', + '' => '割', + '' => '剴', + '' => '創', + '' => '剩', + '' => '勞', + '' => '勝', + '' => '勛', + '' => '博', + '' => '厥', + '' => '啻', + '' => '喀', + '' => '喧', + '' => '啼', + '' => '喊', + '' => '喝', + '' => '喘', + '' => '喂', + '' => '喜', + '' => '喪', + '' => '喔', + '' => '喇', + '' => '喋', + '' => '喃', + '' => '喳', + '' => '單', + '' => '喟', + '' => '唾', + '' => '喲', + '' => '喚', + '' => '喻', + '' => '喬', + '' => '喱', + '' => '啾', + '' => '喉', + '' => '喫', + '' => '喙', + '' => '圍', + '' => '堯', + '' => '堪', + '' => '場', + '' => '堤', + '' => '堰', + '' => '報', + '' => '堡', + '' => '堝', + '' => '堠', + '' => '壹', + '' => '壺', + '' => '奠', + '@' => '婷', + 'A' => '媚', + 'B' => '婿', + 'C' => '媒', + 'D' => '媛', + 'E' => '媧', + 'F' => '孳', + 'G' => '孱', + 'H' => '寒', + 'I' => '富', + 'J' => '寓', + 'K' => '寐', + 'L' => '尊', + 'M' => '尋', + 'N' => '就', + 'O' => '嵌', + 'P' => '嵐', + 'Q' => '崴', + 'R' => '嵇', + 'S' => '巽', + 'T' => '幅', + 'U' => '帽', + 'V' => '幀', + 'W' => '幃', + 'X' => '幾', + 'Y' => '廊', + 'Z' => '廁', + '[' => '廂', + '\\' => '廄', + ']' => '弼', + '^' => '彭', + '_' => '復', + '`' => '循', + 'a' => '徨', + 'b' => '惑', + 'c' => '惡', + 'd' => '悲', + 'e' => '悶', + 'f' => '惠', + 'g' => '愜', + 'h' => '愣', + 'i' => '惺', + 'j' => '愕', + 'k' => '惰', + 'l' => '惻', + 'm' => '惴', + 'n' => '慨', + 'o' => '惱', + 'p' => '愎', + 'q' => '惶', + 'r' => '愉', + 's' => '愀', + 't' => '愒', + 'u' => '戟', + 'v' => '扉', + 'w' => '掣', + 'x' => '掌', + 'y' => '描', + 'z' => '揀', + '{' => '揩', + '|' => '揉', + '}' => '揆', + '~' => '揍', + '' => '插', + '' => '揣', + '' => '提', + '' => '握', + '' => '揖', + '' => '揭', + '' => '揮', + '' => '捶', + '' => '援', + '' => '揪', + '' => '換', + '' => '摒', + '' => '揚', + '' => '揹', + '' => '敞', + '' => '敦', + '' => '敢', + '' => '散', + '' => '斑', + '' => '斐', + '' => '斯', + '' => '普', + '' => '晰', + '' => '晴', + '' => '晶', + '' => '景', + '' => '暑', + '' => '智', + '' => '晾', + '' => '晷', + '' => '曾', + '' => '替', + '' => '期', + '' => '朝', + '' => '棺', + '' => '棕', + '' => '棠', + '' => '棘', + '' => '棗', + '' => '椅', + '' => '棟', + '' => '棵', + '' => '森', + '' => '棧', + '' => '棹', + '' => '棒', + '' => '棲', + '' => '棣', + '' => '棋', + '' => '棍', + '' => '植', + '' => '椒', + '' => '椎', + '' => '棉', + '' => '棚', + '' => '楮', + '' => '棻', + '' => '款', + '' => '欺', + '' => '欽', + '' => '殘', + '' => '殖', + '' => '殼', + '' => '毯', + '' => '氮', + '' => '氯', + '' => '氬', + '' => '港', + '' => '游', + '' => '湔', + '' => '渡', + '' => '渲', + '' => '湧', + '' => '湊', + '' => '渠', + '' => '渥', + '' => '渣', + '' => '減', + '' => '湛', + '' => '湘', + '' => '渤', + '' => '湖', + '' => '湮', + '' => '渭', + '' => '渦', + '' => '湯', + '' => '渴', + '' => '湍', + '' => '渺', + '' => '測', + '' => '湃', + '' => '渝', + '' => '渾', + '' => '滋', + '@' => '溉', + 'A' => '渙', + 'B' => '湎', + 'C' => '湣', + 'D' => '湄', + 'E' => '湲', + 'F' => '湩', + 'G' => '湟', + 'H' => '焙', + 'I' => '焚', + 'J' => '焦', + 'K' => '焰', + 'L' => '無', + 'M' => '然', + 'N' => '煮', + 'O' => '焜', + 'P' => '牌', + 'Q' => '犄', + 'R' => '犀', + 'S' => '猶', + 'T' => '猥', + 'U' => '猴', + 'V' => '猩', + 'W' => '琺', + 'X' => '琪', + 'Y' => '琳', + 'Z' => '琢', + '[' => '琥', + '\\' => '琵', + ']' => '琶', + '^' => '琴', + '_' => '琯', + '`' => '琛', + 'a' => '琦', + 'b' => '琨', + 'c' => '甥', + 'd' => '甦', + 'e' => '畫', + 'f' => '番', + 'g' => '痢', + 'h' => '痛', + 'i' => '痣', + 'j' => '痙', + 'k' => '痘', + 'l' => '痞', + 'm' => '痠', + 'n' => '登', + 'o' => '發', + 'p' => '皖', + 'q' => '皓', + 'r' => '皴', + 's' => '盜', + 't' => '睏', + 'u' => '短', + 'v' => '硝', + 'w' => '硬', + 'x' => '硯', + 'y' => '稍', + 'z' => '稈', + '{' => '程', + '|' => '稅', + '}' => '稀', + '~' => '窘', + '' => '窗', + '' => '窖', + '' => '童', + '' => '竣', + '' => '等', + '' => '策', + '' => '筆', + '' => '筐', + '' => '筒', + '' => '答', + '' => '筍', + '' => '筋', + '' => '筏', + '' => '筑', + '' => '粟', + '' => '粥', + '' => '絞', + '' => '結', + '' => '絨', + '' => '絕', + '' => '紫', + '' => '絮', + '' => '絲', + '' => '絡', + '' => '給', + '' => '絢', + '' => '絰', + '' => '絳', + '' => '善', + '' => '翔', + '' => '翕', + '' => '耋', + '' => '聒', + '' => '肅', + '' => '腕', + '' => '腔', + '' => '腋', + '' => '腑', + '' => '腎', + '' => '脹', + '' => '腆', + '' => '脾', + '' => '腌', + '' => '腓', + '' => '腴', + '' => '舒', + '' => '舜', + '' => '菩', + '' => '萃', + '' => '菸', + '' => '萍', + '' => '菠', + '' => '菅', + '' => '萋', + '' => '菁', + '' => '華', + '' => '菱', + '' => '菴', + '' => '著', + '' => '萊', + '' => '菰', + '' => '萌', + '' => '菌', + '' => '菽', + '' => '菲', + '' => '菊', + '' => '萸', + '' => '萎', + '' => '萄', + '' => '菜', + '' => '萇', + '' => '菔', + '' => '菟', + '' => '虛', + '' => '蛟', + '' => '蛙', + '' => '蛭', + '' => '蛔', + '' => '蛛', + '' => '蛤', + '' => '蛐', + '' => '蛞', + '' => '街', + '' => '裁', + '' => '裂', + '' => '袱', + '' => '覃', + '' => '視', + '' => '註', + '' => '詠', + '' => '評', + '' => '詞', + '' => '証', + '' => '詁', + '@' => '詔', + 'A' => '詛', + 'B' => '詐', + 'C' => '詆', + 'D' => '訴', + 'E' => '診', + 'F' => '訶', + 'G' => '詖', + 'H' => '象', + 'I' => '貂', + 'J' => '貯', + 'K' => '貼', + 'L' => '貳', + 'M' => '貽', + 'N' => '賁', + 'O' => '費', + 'P' => '賀', + 'Q' => '貴', + 'R' => '買', + 'S' => '貶', + 'T' => '貿', + 'U' => '貸', + 'V' => '越', + 'W' => '超', + 'X' => '趁', + 'Y' => '跎', + 'Z' => '距', + '[' => '跋', + '\\' => '跚', + ']' => '跑', + '^' => '跌', + '_' => '跛', + '`' => '跆', + 'a' => '軻', + 'b' => '軸', + 'c' => '軼', + 'd' => '辜', + 'e' => '逮', + 'f' => '逵', + 'g' => '週', + 'h' => '逸', + 'i' => '進', + 'j' => '逶', + 'k' => '鄂', + 'l' => '郵', + 'm' => '鄉', + 'n' => '郾', + 'o' => '酣', + 'p' => '酥', + 'q' => '量', + 'r' => '鈔', + 's' => '鈕', + 't' => '鈣', + 'u' => '鈉', + 'v' => '鈞', + 'w' => '鈍', + 'x' => '鈐', + 'y' => '鈇', + 'z' => '鈑', + '{' => '閔', + '|' => '閏', + '}' => '開', + '~' => '閑', + '' => '間', + '' => '閒', + '' => '閎', + '' => '隊', + '' => '階', + '' => '隋', + '' => '陽', + '' => '隅', + '' => '隆', + '' => '隍', + '' => '陲', + '' => '隄', + '' => '雁', + '' => '雅', + '' => '雄', + '' => '集', + '' => '雇', + '' => '雯', + '' => '雲', + '' => '韌', + '' => '項', + '' => '順', + '' => '須', + '' => '飧', + '' => '飪', + '' => '飯', + '' => '飩', + '' => '飲', + '' => '飭', + '' => '馮', + '' => '馭', + '' => '黃', + '' => '黍', + '' => '黑', + '' => '亂', + '' => '傭', + '' => '債', + '' => '傲', + '' => '傳', + '' => '僅', + '' => '傾', + '' => '催', + '' => '傷', + '' => '傻', + '' => '傯', + '' => '僇', + '' => '剿', + '' => '剷', + '' => '剽', + '' => '募', + '' => '勦', + '' => '勤', + '' => '勢', + '' => '勣', + '' => '匯', + '' => '嗟', + '' => '嗨', + '' => '嗓', + '' => '嗦', + '' => '嗎', + '' => '嗜', + '' => '嗇', + '' => '嗑', + '' => '嗣', + '' => '嗤', + '' => '嗯', + '' => '嗚', + '' => '嗡', + '' => '嗅', + '' => '嗆', + '' => '嗥', + '' => '嗉', + '' => '園', + '' => '圓', + '' => '塞', + '' => '塑', + '' => '塘', + '' => '塗', + '' => '塚', + '' => '塔', + '' => '填', + '' => '塌', + '' => '塭', + '' => '塊', + '' => '塢', + '' => '塒', + '' => '塋', + '' => '奧', + '' => '嫁', + '' => '嫉', + '' => '嫌', + '' => '媾', + '' => '媽', + '' => '媼', + '@' => '媳', + 'A' => '嫂', + 'B' => '媲', + 'C' => '嵩', + 'D' => '嵯', + 'E' => '幌', + 'F' => '幹', + 'G' => '廉', + 'H' => '廈', + 'I' => '弒', + 'J' => '彙', + 'K' => '徬', + 'L' => '微', + 'M' => '愚', + 'N' => '意', + 'O' => '慈', + 'P' => '感', + 'Q' => '想', + 'R' => '愛', + 'S' => '惹', + 'T' => '愁', + 'U' => '愈', + 'V' => '慎', + 'W' => '慌', + 'X' => '慄', + 'Y' => '慍', + 'Z' => '愾', + '[' => '愴', + '\\' => '愧', + ']' => '愍', + '^' => '愆', + '_' => '愷', + '`' => '戡', + 'a' => '戢', + 'b' => '搓', + 'c' => '搾', + 'd' => '搞', + 'e' => '搪', + 'f' => '搭', + 'g' => '搽', + 'h' => '搬', + 'i' => '搏', + 'j' => '搜', + 'k' => '搔', + 'l' => '損', + 'm' => '搶', + 'n' => '搖', + 'o' => '搗', + 'p' => '搆', + 'q' => '敬', + 'r' => '斟', + 's' => '新', + 't' => '暗', + 'u' => '暉', + 'v' => '暇', + 'w' => '暈', + 'x' => '暖', + 'y' => '暄', + 'z' => '暘', + '{' => '暍', + '|' => '會', + '}' => '榔', + '~' => '業', + '' => '楚', + '' => '楷', + '' => '楠', + '' => '楔', + '' => '極', + '' => '椰', + '' => '概', + '' => '楊', + '' => '楨', + '' => '楫', + '' => '楞', + '' => '楓', + '' => '楹', + '' => '榆', + '' => '楝', + '' => '楣', + '' => '楛', + '' => '歇', + '' => '歲', + '' => '毀', + '' => '殿', + '' => '毓', + '' => '毽', + '' => '溢', + '' => '溯', + '' => '滓', + '' => '溶', + '' => '滂', + '' => '源', + '' => '溝', + '' => '滇', + '' => '滅', + '' => '溥', + '' => '溘', + '' => '溼', + '' => '溺', + '' => '溫', + '' => '滑', + '' => '準', + '' => '溜', + '' => '滄', + '' => '滔', + '' => '溪', + '' => '溧', + '' => '溴', + '' => '煎', + '' => '煙', + '' => '煩', + '' => '煤', + '' => '煉', + '' => '照', + '' => '煜', + '' => '煬', + '' => '煦', + '' => '煌', + '' => '煥', + '' => '煞', + '' => '煆', + '' => '煨', + '' => '煖', + '' => '爺', + '' => '牒', + '' => '猷', + '' => '獅', + '' => '猿', + '' => '猾', + '' => '瑯', + '' => '瑚', + '' => '瑕', + '' => '瑟', + '' => '瑞', + '' => '瑁', + '' => '琿', + '' => '瑙', + '' => '瑛', + '' => '瑜', + '' => '當', + '' => '畸', + '' => '瘀', + '' => '痰', + '' => '瘁', + '' => '痲', + '' => '痱', + '' => '痺', + '' => '痿', + '' => '痴', + '' => '痳', + '' => '盞', + '' => '盟', + '' => '睛', + '' => '睫', + '' => '睦', + '' => '睞', + '' => '督', + '@' => '睹', + 'A' => '睪', + 'B' => '睬', + 'C' => '睜', + 'D' => '睥', + 'E' => '睨', + 'F' => '睢', + 'G' => '矮', + 'H' => '碎', + 'I' => '碰', + 'J' => '碗', + 'K' => '碘', + 'L' => '碌', + 'M' => '碉', + 'N' => '硼', + 'O' => '碑', + 'P' => '碓', + 'Q' => '硿', + 'R' => '祺', + 'S' => '祿', + 'T' => '禁', + 'U' => '萬', + 'V' => '禽', + 'W' => '稜', + 'X' => '稚', + 'Y' => '稠', + 'Z' => '稔', + '[' => '稟', + '\\' => '稞', + ']' => '窟', + '^' => '窠', + '_' => '筷', + '`' => '節', + 'a' => '筠', + 'b' => '筮', + 'c' => '筧', + 'd' => '粱', + 'e' => '粳', + 'f' => '粵', + 'g' => '經', + 'h' => '絹', + 'i' => '綑', + 'j' => '綁', + 'k' => '綏', + 'l' => '絛', + 'm' => '置', + 'n' => '罩', + 'o' => '罪', + 'p' => '署', + 'q' => '義', + 'r' => '羨', + 's' => '群', + 't' => '聖', + 'u' => '聘', + 'v' => '肆', + 'w' => '肄', + 'x' => '腱', + 'y' => '腰', + 'z' => '腸', + '{' => '腥', + '|' => '腮', + '}' => '腳', + '~' => '腫', + '' => '腹', + '' => '腺', + '' => '腦', + '' => '舅', + '' => '艇', + '' => '蒂', + '' => '葷', + '' => '落', + '' => '萱', + '' => '葵', + '' => '葦', + '' => '葫', + '' => '葉', + '' => '葬', + '' => '葛', + '' => '萼', + '' => '萵', + '' => '葡', + '' => '董', + '' => '葩', + '' => '葭', + '' => '葆', + '' => '虞', + '' => '虜', + '' => '號', + '' => '蛹', + '' => '蜓', + '' => '蜈', + '' => '蜇', + '' => '蜀', + '' => '蛾', + '' => '蛻', + '' => '蜂', + '' => '蜃', + '' => '蜆', + '' => '蜊', + '' => '衙', + '' => '裟', + '' => '裔', + '' => '裙', + '' => '補', + '' => '裘', + '' => '裝', + '' => '裡', + '' => '裊', + '' => '裕', + '' => '裒', + '' => '覜', + '' => '解', + '' => '詫', + '' => '該', + '' => '詳', + '' => '試', + '' => '詩', + '' => '詰', + '' => '誇', + '' => '詼', + '' => '詣', + '' => '誠', + '' => '話', + '' => '誅', + '' => '詭', + '' => '詢', + '' => '詮', + '' => '詬', + '' => '詹', + '' => '詻', + '' => '訾', + '' => '詨', + '' => '豢', + '' => '貊', + '' => '貉', + '' => '賊', + '' => '資', + '' => '賈', + '' => '賄', + '' => '貲', + '' => '賃', + '' => '賂', + '' => '賅', + '' => '跡', + '' => '跟', + '' => '跨', + '' => '路', + '' => '跳', + '' => '跺', + '' => '跪', + '' => '跤', + '' => '跦', + '' => '躲', + '' => '較', + '' => '載', + '' => '軾', + '' => '輊', + '@' => '辟', + 'A' => '農', + 'B' => '運', + 'C' => '遊', + 'D' => '道', + 'E' => '遂', + 'F' => '達', + 'G' => '逼', + 'H' => '違', + 'I' => '遐', + 'J' => '遇', + 'K' => '遏', + 'L' => '過', + 'M' => '遍', + 'N' => '遑', + 'O' => '逾', + 'P' => '遁', + 'Q' => '鄒', + 'R' => '鄗', + 'S' => '酬', + 'T' => '酪', + 'U' => '酩', + 'V' => '釉', + 'W' => '鈷', + 'X' => '鉗', + 'Y' => '鈸', + 'Z' => '鈽', + '[' => '鉀', + '\\' => '鈾', + ']' => '鉛', + '^' => '鉋', + '_' => '鉤', + '`' => '鉑', + 'a' => '鈴', + 'b' => '鉉', + 'c' => '鉍', + 'd' => '鉅', + 'e' => '鈹', + 'f' => '鈿', + 'g' => '鉚', + 'h' => '閘', + 'i' => '隘', + 'j' => '隔', + 'k' => '隕', + 'l' => '雍', + 'm' => '雋', + 'n' => '雉', + 'o' => '雊', + 'p' => '雷', + 'q' => '電', + 'r' => '雹', + 's' => '零', + 't' => '靖', + 'u' => '靴', + 'v' => '靶', + 'w' => '預', + 'x' => '頑', + 'y' => '頓', + 'z' => '頊', + '{' => '頒', + '|' => '頌', + '}' => '飼', + '~' => '飴', + '' => '飽', + '' => '飾', + '' => '馳', + '' => '馱', + '' => '馴', + '' => '髡', + '' => '鳩', + '' => '麂', + '' => '鼎', + '' => '鼓', + '' => '鼠', + '' => '僧', + '' => '僮', + '' => '僥', + '' => '僖', + '' => '僭', + '' => '僚', + '' => '僕', + '' => '像', + '' => '僑', + '' => '僱', + '' => '僎', + '' => '僩', + '' => '兢', + '' => '凳', + '' => '劃', + '' => '劂', + '' => '匱', + '' => '厭', + '' => '嗾', + '' => '嘀', + '' => '嘛', + '' => '嘗', + '' => '嗽', + '' => '嘔', + '' => '嘆', + '' => '嘉', + '' => '嘍', + '' => '嘎', + '' => '嗷', + '' => '嘖', + '' => '嘟', + '' => '嘈', + '' => '嘐', + '' => '嗶', + '' => '團', + '' => '圖', + '' => '塵', + '' => '塾', + '' => '境', + '' => '墓', + '' => '墊', + '' => '塹', + '' => '墅', + '' => '塽', + '' => '壽', + '' => '夥', + '' => '夢', + '' => '夤', + '' => '奪', + '' => '奩', + '' => '嫡', + '' => '嫦', + '' => '嫩', + '' => '嫗', + '' => '嫖', + '' => '嫘', + '' => '嫣', + '' => '孵', + '' => '寞', + '' => '寧', + '' => '寡', + '' => '寥', + '' => '實', + '' => '寨', + '' => '寢', + '' => '寤', + '' => '察', + '' => '對', + '' => '屢', + '' => '嶄', + '' => '嶇', + '' => '幛', + '' => '幣', + '' => '幕', + '' => '幗', + '' => '幔', + '' => '廓', + '' => '廖', + '' => '弊', + '' => '彆', + '' => '彰', + '' => '徹', + '' => '慇', + '@' => '愿', + 'A' => '態', + 'B' => '慷', + 'C' => '慢', + 'D' => '慣', + 'E' => '慟', + 'F' => '慚', + 'G' => '慘', + 'H' => '慵', + 'I' => '截', + 'J' => '撇', + 'K' => '摘', + 'L' => '摔', + 'M' => '撤', + 'N' => '摸', + 'O' => '摟', + 'P' => '摺', + 'Q' => '摑', + 'R' => '摧', + 'S' => '搴', + 'T' => '摭', + 'U' => '摻', + 'V' => '敲', + 'W' => '斡', + 'X' => '旗', + 'Y' => '旖', + 'Z' => '暢', + '[' => '暨', + '\\' => '暝', + ']' => '榜', + '^' => '榨', + '_' => '榕', + '`' => '槁', + 'a' => '榮', + 'b' => '槓', + 'c' => '構', + 'd' => '榛', + 'e' => '榷', + 'f' => '榻', + 'g' => '榫', + 'h' => '榴', + 'i' => '槐', + 'j' => '槍', + 'k' => '榭', + 'l' => '槌', + 'm' => '榦', + 'n' => '槃', + 'o' => '榣', + 'p' => '歉', + 'q' => '歌', + 'r' => '氳', + 's' => '漳', + 't' => '演', + 'u' => '滾', + 'v' => '漓', + 'w' => '滴', + 'x' => '漩', + 'y' => '漾', + 'z' => '漠', + '{' => '漬', + '|' => '漏', + '}' => '漂', + '~' => '漢', + '' => '滿', + '' => '滯', + '' => '漆', + '' => '漱', + '' => '漸', + '' => '漲', + '' => '漣', + '' => '漕', + '' => '漫', + '' => '漯', + '' => '澈', + '' => '漪', + '' => '滬', + '' => '漁', + '' => '滲', + '' => '滌', + '' => '滷', + '' => '熔', + '' => '熙', + '' => '煽', + '' => '熊', + '' => '熄', + '' => '熒', + '' => '爾', + '' => '犒', + '' => '犖', + '' => '獄', + '' => '獐', + '' => '瑤', + '' => '瑣', + '' => '瑪', + '' => '瑰', + '' => '瑭', + '' => '甄', + '' => '疑', + '' => '瘧', + '' => '瘍', + '' => '瘋', + '' => '瘉', + '' => '瘓', + '' => '盡', + '' => '監', + '' => '瞄', + '' => '睽', + '' => '睿', + '' => '睡', + '' => '磁', + '' => '碟', + '' => '碧', + '' => '碳', + '' => '碩', + '' => '碣', + '' => '禎', + '' => '福', + '' => '禍', + '' => '種', + '' => '稱', + '' => '窪', + '' => '窩', + '' => '竭', + '' => '端', + '' => '管', + '' => '箕', + '' => '箋', + '' => '筵', + '' => '算', + '' => '箝', + '' => '箔', + '' => '箏', + '' => '箸', + '' => '箇', + '' => '箄', + '' => '粹', + '' => '粽', + '' => '精', + '' => '綻', + '' => '綰', + '' => '綜', + '' => '綽', + '' => '綾', + '' => '綠', + '' => '緊', + '' => '綴', + '' => '網', + '' => '綱', + '' => '綺', + '' => '綢', + '' => '綿', + '' => '綵', + '' => '綸', + '' => '維', + '' => '緒', + '' => '緇', + '' => '綬', + '@' => '罰', + 'A' => '翠', + 'B' => '翡', + 'C' => '翟', + 'D' => '聞', + 'E' => '聚', + 'F' => '肇', + 'G' => '腐', + 'H' => '膀', + 'I' => '膏', + 'J' => '膈', + 'K' => '膊', + 'L' => '腿', + 'M' => '膂', + 'N' => '臧', + 'O' => '臺', + 'P' => '與', + 'Q' => '舔', + 'R' => '舞', + 'S' => '艋', + 'T' => '蓉', + 'U' => '蒿', + 'V' => '蓆', + 'W' => '蓄', + 'X' => '蒙', + 'Y' => '蒞', + 'Z' => '蒲', + '[' => '蒜', + '\\' => '蓋', + ']' => '蒸', + '^' => '蓀', + '_' => '蓓', + '`' => '蒐', + 'a' => '蒼', + 'b' => '蓑', + 'c' => '蓊', + 'd' => '蜿', + 'e' => '蜜', + 'f' => '蜻', + 'g' => '蜢', + 'h' => '蜥', + 'i' => '蜴', + 'j' => '蜘', + 'k' => '蝕', + 'l' => '蜷', + 'm' => '蜩', + 'n' => '裳', + 'o' => '褂', + 'p' => '裴', + 'q' => '裹', + 'r' => '裸', + 's' => '製', + 't' => '裨', + 'u' => '褚', + 'v' => '裯', + 'w' => '誦', + 'x' => '誌', + 'y' => '語', + 'z' => '誣', + '{' => '認', + '|' => '誡', + '}' => '誓', + '~' => '誤', + '' => '說', + '' => '誥', + '' => '誨', + '' => '誘', + '' => '誑', + '' => '誚', + '' => '誧', + '' => '豪', + '' => '貍', + '' => '貌', + '' => '賓', + '' => '賑', + '' => '賒', + '' => '赫', + '' => '趙', + '' => '趕', + '' => '跼', + '' => '輔', + '' => '輒', + '' => '輕', + '' => '輓', + '' => '辣', + '' => '遠', + '' => '遘', + '' => '遜', + '' => '遣', + '' => '遙', + '' => '遞', + '' => '遢', + '' => '遝', + '' => '遛', + '' => '鄙', + '' => '鄘', + '' => '鄞', + '' => '酵', + '' => '酸', + '' => '酷', + '' => '酴', + '' => '鉸', + '' => '銀', + '' => '銅', + '' => '銘', + '' => '銖', + '' => '鉻', + '' => '銓', + '' => '銜', + '' => '銨', + '' => '鉼', + '' => '銑', + '' => '閡', + '' => '閨', + '' => '閩', + '' => '閣', + '' => '閥', + '' => '閤', + '' => '隙', + '' => '障', + '' => '際', + '' => '雌', + '' => '雒', + '' => '需', + '' => '靼', + '' => '鞅', + '' => '韶', + '' => '頗', + '' => '領', + '' => '颯', + '' => '颱', + '' => '餃', + '' => '餅', + '' => '餌', + '' => '餉', + '' => '駁', + '' => '骯', + '' => '骰', + '' => '髦', + '' => '魁', + '' => '魂', + '' => '鳴', + '' => '鳶', + '' => '鳳', + '' => '麼', + '' => '鼻', + '' => '齊', + '' => '億', + '' => '儀', + '' => '僻', + '' => '僵', + '' => '價', + '' => '儂', + '' => '儈', + '' => '儉', + '' => '儅', + '' => '凜', + '@' => '劇', + 'A' => '劈', + 'B' => '劉', + 'C' => '劍', + 'D' => '劊', + 'E' => '勰', + 'F' => '厲', + 'G' => '嘮', + 'H' => '嘻', + 'I' => '嘹', + 'J' => '嘲', + 'K' => '嘿', + 'L' => '嘴', + 'M' => '嘩', + 'N' => '噓', + 'O' => '噎', + 'P' => '噗', + 'Q' => '噴', + 'R' => '嘶', + 'S' => '嘯', + 'T' => '嘰', + 'U' => '墀', + 'V' => '墟', + 'W' => '增', + 'X' => '墳', + 'Y' => '墜', + 'Z' => '墮', + '[' => '墩', + '\\' => '墦', + ']' => '奭', + '^' => '嬉', + '_' => '嫻', + '`' => '嬋', + 'a' => '嫵', + 'b' => '嬌', + 'c' => '嬈', + 'd' => '寮', + 'e' => '寬', + 'f' => '審', + 'g' => '寫', + 'h' => '層', + 'i' => '履', + 'j' => '嶝', + 'k' => '嶔', + 'l' => '幢', + 'm' => '幟', + 'n' => '幡', + 'o' => '廢', + 'p' => '廚', + 'q' => '廟', + 'r' => '廝', + 's' => '廣', + 't' => '廠', + 'u' => '彈', + 'v' => '影', + 'w' => '德', + 'x' => '徵', + 'y' => '慶', + 'z' => '慧', + '{' => '慮', + '|' => '慝', + '}' => '慕', + '~' => '憂', + '' => '慼', + '' => '慰', + '' => '慫', + '' => '慾', + '' => '憧', + '' => '憐', + '' => '憫', + '' => '憎', + '' => '憬', + '' => '憚', + '' => '憤', + '' => '憔', + '' => '憮', + '' => '戮', + '' => '摩', + '' => '摯', + '' => '摹', + '' => '撞', + '' => '撲', + '' => '撈', + '' => '撐', + '' => '撰', + '' => '撥', + '' => '撓', + '' => '撕', + '' => '撩', + '' => '撒', + '' => '撮', + '' => '播', + '' => '撫', + '' => '撚', + '' => '撬', + '' => '撙', + '' => '撢', + '' => '撳', + '' => '敵', + '' => '敷', + '' => '數', + '' => '暮', + '' => '暫', + '' => '暴', + '' => '暱', + '' => '樣', + '' => '樟', + '' => '槨', + '' => '樁', + '' => '樞', + '' => '標', + '' => '槽', + '' => '模', + '' => '樓', + '' => '樊', + '' => '槳', + '' => '樂', + '' => '樅', + '' => '槭', + '' => '樑', + '' => '歐', + '' => '歎', + '' => '殤', + '' => '毅', + '' => '毆', + '' => '漿', + '' => '潼', + '' => '澄', + '' => '潑', + '' => '潦', + '' => '潔', + '' => '澆', + '' => '潭', + '' => '潛', + '' => '潸', + '' => '潮', + '' => '澎', + '' => '潺', + '' => '潰', + '' => '潤', + '' => '澗', + '' => '潘', + '' => '滕', + '' => '潯', + '' => '潠', + '' => '潟', + '' => '熟', + '' => '熬', + '' => '熱', + '' => '熨', + '' => '牖', + '' => '犛', + '' => '獎', + '' => '獗', + '' => '瑩', + '' => '璋', + '' => '璃', + '@' => '瑾', + 'A' => '璀', + 'B' => '畿', + 'C' => '瘠', + 'D' => '瘩', + 'E' => '瘟', + 'F' => '瘤', + 'G' => '瘦', + 'H' => '瘡', + 'I' => '瘢', + 'J' => '皚', + 'K' => '皺', + 'L' => '盤', + 'M' => '瞎', + 'N' => '瞇', + 'O' => '瞌', + 'P' => '瞑', + 'Q' => '瞋', + 'R' => '磋', + 'S' => '磅', + 'T' => '確', + 'U' => '磊', + 'V' => '碾', + 'W' => '磕', + 'X' => '碼', + 'Y' => '磐', + 'Z' => '稿', + '[' => '稼', + '\\' => '穀', + ']' => '稽', + '^' => '稷', + '_' => '稻', + '`' => '窯', + 'a' => '窮', + 'b' => '箭', + 'c' => '箱', + 'd' => '範', + 'e' => '箴', + 'f' => '篆', + 'g' => '篇', + 'h' => '篁', + 'i' => '箠', + 'j' => '篌', + 'k' => '糊', + 'l' => '締', + 'm' => '練', + 'n' => '緯', + 'o' => '緻', + 'p' => '緘', + 'q' => '緬', + 'r' => '緝', + 's' => '編', + 't' => '緣', + 'u' => '線', + 'v' => '緞', + 'w' => '緩', + 'x' => '綞', + 'y' => '緙', + 'z' => '緲', + '{' => '緹', + '|' => '罵', + '}' => '罷', + '~' => '羯', + '' => '翩', + '' => '耦', + '' => '膛', + '' => '膜', + '' => '膝', + '' => '膠', + '' => '膚', + '' => '膘', + '' => '蔗', + '' => '蔽', + '' => '蔚', + '' => '蓮', + '' => '蔬', + '' => '蔭', + '' => '蔓', + '' => '蔑', + '' => '蔣', + '' => '蔡', + '' => '蔔', + '' => '蓬', + '' => '蔥', + '' => '蓿', + '' => '蔆', + '' => '螂', + '' => '蝴', + '' => '蝶', + '' => '蝠', + '' => '蝦', + '' => '蝸', + '' => '蝨', + '' => '蝙', + '' => '蝗', + '' => '蝌', + '' => '蝓', + '' => '衛', + '' => '衝', + '' => '褐', + '' => '複', + '' => '褒', + '' => '褓', + '' => '褕', + '' => '褊', + '' => '誼', + '' => '諒', + '' => '談', + '' => '諄', + '' => '誕', + '' => '請', + '' => '諸', + '' => '課', + '' => '諉', + '' => '諂', + '' => '調', + '' => '誰', + '' => '論', + '' => '諍', + '' => '誶', + '' => '誹', + '' => '諛', + '' => '豌', + '' => '豎', + '' => '豬', + '' => '賠', + '' => '賞', + '' => '賦', + '' => '賤', + '' => '賬', + '' => '賭', + '' => '賢', + '' => '賣', + '' => '賜', + '' => '質', + '' => '賡', + '' => '赭', + '' => '趟', + '' => '趣', + '' => '踫', + '' => '踐', + '' => '踝', + '' => '踢', + '' => '踏', + '' => '踩', + '' => '踟', + '' => '踡', + '' => '踞', + '' => '躺', + '' => '輝', + '' => '輛', + '' => '輟', + '' => '輩', + '' => '輦', + '' => '輪', + '' => '輜', + '' => '輞', + '@' => '輥', + 'A' => '適', + 'B' => '遮', + 'C' => '遨', + 'D' => '遭', + 'E' => '遷', + 'F' => '鄰', + 'G' => '鄭', + 'H' => '鄧', + 'I' => '鄱', + 'J' => '醇', + 'K' => '醉', + 'L' => '醋', + 'M' => '醃', + 'N' => '鋅', + 'O' => '銻', + 'P' => '銷', + 'Q' => '鋪', + 'R' => '銬', + 'S' => '鋤', + 'T' => '鋁', + 'U' => '銳', + 'V' => '銼', + 'W' => '鋒', + 'X' => '鋇', + 'Y' => '鋰', + 'Z' => '銲', + '[' => '閭', + '\\' => '閱', + ']' => '霄', + '^' => '霆', + '_' => '震', + '`' => '霉', + 'a' => '靠', + 'b' => '鞍', + 'c' => '鞋', + 'd' => '鞏', + 'e' => '頡', + 'f' => '頫', + 'g' => '頜', + 'h' => '颳', + 'i' => '養', + 'j' => '餓', + 'k' => '餒', + 'l' => '餘', + 'm' => '駝', + 'n' => '駐', + 'o' => '駟', + 'p' => '駛', + 'q' => '駑', + 'r' => '駕', + 's' => '駒', + 't' => '駙', + 'u' => '骷', + 'v' => '髮', + 'w' => '髯', + 'x' => '鬧', + 'y' => '魅', + 'z' => '魄', + '{' => '魷', + '|' => '魯', + '}' => '鴆', + '~' => '鴉', + '' => '鴃', + '' => '麩', + '' => '麾', + '' => '黎', + '' => '墨', + '' => '齒', + '' => '儒', + '' => '儘', + '' => '儔', + '' => '儐', + '' => '儕', + '' => '冀', + '' => '冪', + '' => '凝', + '' => '劑', + '' => '劓', + '' => '勳', + '' => '噙', + '' => '噫', + '' => '噹', + '' => '噩', + '' => '噤', + '' => '噸', + '' => '噪', + '' => '器', + '' => '噥', + '' => '噱', + '' => '噯', + '' => '噬', + '' => '噢', + '' => '噶', + '' => '壁', + '' => '墾', + '' => '壇', + '' => '壅', + '' => '奮', + '' => '嬝', + '' => '嬴', + '' => '學', + '' => '寰', + '' => '導', + '' => '彊', + '' => '憲', + '' => '憑', + '' => '憩', + '' => '憊', + '' => '懍', + '' => '憶', + '' => '憾', + '' => '懊', + '' => '懈', + '' => '戰', + '' => '擅', + '' => '擁', + '' => '擋', + '' => '撻', + '' => '撼', + '' => '據', + '' => '擄', + '' => '擇', + '' => '擂', + '' => '操', + '' => '撿', + '' => '擒', + '' => '擔', + '' => '撾', + '' => '整', + '' => '曆', + '' => '曉', + '' => '暹', + '' => '曄', + '' => '曇', + '' => '暸', + '' => '樽', + '' => '樸', + '' => '樺', + '' => '橙', + '' => '橫', + '' => '橘', + '' => '樹', + '' => '橄', + '' => '橢', + '' => '橡', + '' => '橋', + '' => '橇', + '' => '樵', + '' => '機', + '' => '橈', + '' => '歙', + '' => '歷', + '' => '氅', + '' => '濂', + '' => '澱', + '' => '澡', + '@' => '濃', + 'A' => '澤', + 'B' => '濁', + 'C' => '澧', + 'D' => '澳', + 'E' => '激', + 'F' => '澹', + 'G' => '澶', + 'H' => '澦', + 'I' => '澠', + 'J' => '澴', + 'K' => '熾', + 'L' => '燉', + 'M' => '燐', + 'N' => '燒', + 'O' => '燈', + 'P' => '燕', + 'Q' => '熹', + 'R' => '燎', + 'S' => '燙', + 'T' => '燜', + 'U' => '燃', + 'V' => '燄', + 'W' => '獨', + 'X' => '璜', + 'Y' => '璣', + 'Z' => '璘', + '[' => '璟', + '\\' => '璞', + ']' => '瓢', + '^' => '甌', + '_' => '甍', + '`' => '瘴', + 'a' => '瘸', + 'b' => '瘺', + 'c' => '盧', + 'd' => '盥', + 'e' => '瞠', + 'f' => '瞞', + 'g' => '瞟', + 'h' => '瞥', + 'i' => '磨', + 'j' => '磚', + 'k' => '磬', + 'l' => '磧', + 'm' => '禦', + 'n' => '積', + 'o' => '穎', + 'p' => '穆', + 'q' => '穌', + 'r' => '穋', + 's' => '窺', + 't' => '篙', + 'u' => '簑', + 'v' => '築', + 'w' => '篤', + 'x' => '篛', + 'y' => '篡', + 'z' => '篩', + '{' => '篦', + '|' => '糕', + '}' => '糖', + '~' => '縊', + '' => '縑', + '' => '縈', + '' => '縛', + '' => '縣', + '' => '縞', + '' => '縝', + '' => '縉', + '' => '縐', + '' => '罹', + '' => '羲', + '' => '翰', + '' => '翱', + '' => '翮', + '' => '耨', + '' => '膳', + '' => '膩', + '' => '膨', + '' => '臻', + '' => '興', + '' => '艘', + '' => '艙', + '' => '蕊', + '' => '蕙', + '' => '蕈', + '' => '蕨', + '' => '蕩', + '' => '蕃', + '' => '蕉', + '' => '蕭', + '' => '蕪', + '' => '蕞', + '' => '螃', + '' => '螟', + '' => '螞', + '' => '螢', + '' => '融', + '' => '衡', + '' => '褪', + '' => '褲', + '' => '褥', + '' => '褫', + '' => '褡', + '' => '親', + '' => '覦', + '' => '諦', + '' => '諺', + '' => '諫', + '' => '諱', + '' => '謀', + '' => '諜', + '' => '諧', + '' => '諮', + '' => '諾', + '' => '謁', + '' => '謂', + '' => '諷', + '' => '諭', + '' => '諳', + '' => '諶', + '' => '諼', + '' => '豫', + '' => '豭', + '' => '貓', + '' => '賴', + '' => '蹄', + '' => '踱', + '' => '踴', + '' => '蹂', + '' => '踹', + '' => '踵', + '' => '輻', + '' => '輯', + '' => '輸', + '' => '輳', + '' => '辨', + '' => '辦', + '' => '遵', + '' => '遴', + '' => '選', + '' => '遲', + '' => '遼', + '' => '遺', + '' => '鄴', + '' => '醒', + '' => '錠', + '' => '錶', + '' => '鋸', + '' => '錳', + '' => '錯', + '' => '錢', + '' => '鋼', + '' => '錫', + '' => '錄', + '' => '錚', + '@' => '錐', + 'A' => '錦', + 'B' => '錡', + 'C' => '錕', + 'D' => '錮', + 'E' => '錙', + 'F' => '閻', + 'G' => '隧', + 'H' => '隨', + 'I' => '險', + 'J' => '雕', + 'K' => '霎', + 'L' => '霑', + 'M' => '霖', + 'N' => '霍', + 'O' => '霓', + 'P' => '霏', + 'Q' => '靛', + 'R' => '靜', + 'S' => '靦', + 'T' => '鞘', + 'U' => '頰', + 'V' => '頸', + 'W' => '頻', + 'X' => '頷', + 'Y' => '頭', + 'Z' => '頹', + '[' => '頤', + '\\' => '餐', + ']' => '館', + '^' => '餞', + '_' => '餛', + '`' => '餡', + 'a' => '餚', + 'b' => '駭', + 'c' => '駢', + 'd' => '駱', + 'e' => '骸', + 'f' => '骼', + 'g' => '髻', + 'h' => '髭', + 'i' => '鬨', + 'j' => '鮑', + 'k' => '鴕', + 'l' => '鴣', + 'm' => '鴦', + 'n' => '鴨', + 'o' => '鴒', + 'p' => '鴛', + 'q' => '默', + 'r' => '黔', + 's' => '龍', + 't' => '龜', + 'u' => '優', + 'v' => '償', + 'w' => '儡', + 'x' => '儲', + 'y' => '勵', + 'z' => '嚎', + '{' => '嚀', + '|' => '嚐', + '}' => '嚅', + '~' => '嚇', + '' => '嚏', + '' => '壕', + '' => '壓', + '' => '壑', + '' => '壎', + '' => '嬰', + '' => '嬪', + '' => '嬤', + '' => '孺', + '' => '尷', + '' => '屨', + '' => '嶼', + '' => '嶺', + '' => '嶽', + '' => '嶸', + '' => '幫', + '' => '彌', + '' => '徽', + '' => '應', + '' => '懂', + '' => '懇', + '' => '懦', + '' => '懋', + '' => '戲', + '' => '戴', + '' => '擎', + '' => '擊', + '' => '擘', + '' => '擠', + '' => '擰', + '' => '擦', + '' => '擬', + '' => '擱', + '' => '擢', + '' => '擭', + '' => '斂', + '' => '斃', + '' => '曙', + '' => '曖', + '' => '檀', + '' => '檔', + '' => '檄', + '' => '檢', + '' => '檜', + '' => '櫛', + '' => '檣', + '' => '橾', + '' => '檗', + '' => '檐', + '' => '檠', + '' => '歜', + '' => '殮', + '' => '毚', + '' => '氈', + '' => '濘', + '' => '濱', + '' => '濟', + '' => '濠', + '' => '濛', + '' => '濤', + '' => '濫', + '' => '濯', + '' => '澀', + '' => '濬', + '' => '濡', + '' => '濩', + '' => '濕', + '' => '濮', + '' => '濰', + '' => '燧', + '' => '營', + '' => '燮', + '' => '燦', + '' => '燥', + '' => '燭', + '' => '燬', + '' => '燴', + '' => '燠', + '' => '爵', + '' => '牆', + '' => '獰', + '' => '獲', + '' => '璩', + '' => '環', + '' => '璦', + '' => '璨', + '' => '癆', + '' => '療', + '' => '癌', + '' => '盪', + '' => '瞳', + '' => '瞪', + '' => '瞰', + '' => '瞬', + '@' => '瞧', + 'A' => '瞭', + 'B' => '矯', + 'C' => '磷', + 'D' => '磺', + 'E' => '磴', + 'F' => '磯', + 'G' => '礁', + 'H' => '禧', + 'I' => '禪', + 'J' => '穗', + 'K' => '窿', + 'L' => '簇', + 'M' => '簍', + 'N' => '篾', + 'O' => '篷', + 'P' => '簌', + 'Q' => '篠', + 'R' => '糠', + 'S' => '糜', + 'T' => '糞', + 'U' => '糢', + 'V' => '糟', + 'W' => '糙', + 'X' => '糝', + 'Y' => '縮', + 'Z' => '績', + '[' => '繆', + '\\' => '縷', + ']' => '縲', + '^' => '繃', + '_' => '縫', + '`' => '總', + 'a' => '縱', + 'b' => '繅', + 'c' => '繁', + 'd' => '縴', + 'e' => '縹', + 'f' => '繈', + 'g' => '縵', + 'h' => '縿', + 'i' => '縯', + 'j' => '罄', + 'k' => '翳', + 'l' => '翼', + 'm' => '聱', + 'n' => '聲', + 'o' => '聰', + 'p' => '聯', + 'q' => '聳', + 'r' => '臆', + 's' => '臃', + 't' => '膺', + 'u' => '臂', + 'v' => '臀', + 'w' => '膿', + 'x' => '膽', + 'y' => '臉', + 'z' => '膾', + '{' => '臨', + '|' => '舉', + '}' => '艱', + '~' => '薪', + '' => '薄', + '' => '蕾', + '' => '薜', + '' => '薑', + '' => '薔', + '' => '薯', + '' => '薛', + '' => '薇', + '' => '薨', + '' => '薊', + '' => '虧', + '' => '蟀', + '' => '蟑', + '' => '螳', + '' => '蟒', + '' => '蟆', + '' => '螫', + '' => '螻', + '' => '螺', + '' => '蟈', + '' => '蟋', + '' => '褻', + '' => '褶', + '' => '襄', + '' => '褸', + '' => '褽', + '' => '覬', + '' => '謎', + '' => '謗', + '' => '謙', + '' => '講', + '' => '謊', + '' => '謠', + '' => '謝', + '' => '謄', + '' => '謐', + '' => '豁', + '' => '谿', + '' => '豳', + '' => '賺', + '' => '賽', + '' => '購', + '' => '賸', + '' => '賻', + '' => '趨', + '' => '蹉', + '' => '蹋', + '' => '蹈', + '' => '蹊', + '' => '轄', + '' => '輾', + '' => '轂', + '' => '轅', + '' => '輿', + '' => '避', + '' => '遽', + '' => '還', + '' => '邁', + '' => '邂', + '' => '邀', + '' => '鄹', + '' => '醣', + '' => '醞', + '' => '醜', + '' => '鍍', + '' => '鎂', + '' => '錨', + '' => '鍵', + '' => '鍊', + '' => '鍥', + '' => '鍋', + '' => '錘', + '' => '鍾', + '' => '鍬', + '' => '鍛', + '' => '鍰', + '' => '鍚', + '' => '鍔', + '' => '闊', + '' => '闋', + '' => '闌', + '' => '闈', + '' => '闆', + '' => '隱', + '' => '隸', + '' => '雖', + '' => '霜', + '' => '霞', + '' => '鞠', + '' => '韓', + '' => '顆', + '' => '颶', + '' => '餵', + '' => '騁', + '@' => '駿', + 'A' => '鮮', + 'B' => '鮫', + 'C' => '鮪', + 'D' => '鮭', + 'E' => '鴻', + 'F' => '鴿', + 'G' => '麋', + 'H' => '黏', + 'I' => '點', + 'J' => '黜', + 'K' => '黝', + 'L' => '黛', + 'M' => '鼾', + 'N' => '齋', + 'O' => '叢', + 'P' => '嚕', + 'Q' => '嚮', + 'R' => '壙', + 'S' => '壘', + 'T' => '嬸', + 'U' => '彝', + 'V' => '懣', + 'W' => '戳', + 'X' => '擴', + 'Y' => '擲', + 'Z' => '擾', + '[' => '攆', + '\\' => '擺', + ']' => '擻', + '^' => '擷', + '_' => '斷', + '`' => '曜', + 'a' => '朦', + 'b' => '檳', + 'c' => '檬', + 'd' => '櫃', + 'e' => '檻', + 'f' => '檸', + 'g' => '櫂', + 'h' => '檮', + 'i' => '檯', + 'j' => '歟', + 'k' => '歸', + 'l' => '殯', + 'm' => '瀉', + 'n' => '瀋', + 'o' => '濾', + 'p' => '瀆', + 'q' => '濺', + 'r' => '瀑', + 's' => '瀏', + 't' => '燻', + 'u' => '燼', + 'v' => '燾', + 'w' => '燸', + 'x' => '獷', + 'y' => '獵', + 'z' => '璧', + '{' => '璿', + '|' => '甕', + '}' => '癖', + '~' => '癘', + '¡' => '癒', + '¢' => '瞽', + '£' => '瞿', + '¤' => '瞻', + '¥' => '瞼', + '¦' => '礎', + '§' => '禮', + '¨' => '穡', + '©' => '穢', + 'ª' => '穠', + '«' => '竄', + '¬' => '竅', + '­' => '簫', + '®' => '簧', + '¯' => '簪', + '°' => '簞', + '±' => '簣', + '²' => '簡', + '³' => '糧', + '´' => '織', + 'µ' => '繕', + '¶' => '繞', + '·' => '繚', + '¸' => '繡', + '¹' => '繒', + 'º' => '繙', + '»' => '罈', + '¼' => '翹', + '½' => '翻', + '¾' => '職', + '¿' => '聶', + '' => '臍', + '' => '臏', + '' => '舊', + '' => '藏', + '' => '薩', + '' => '藍', + '' => '藐', + '' => '藉', + '' => '薰', + '' => '薺', + '' => '薹', + '' => '薦', + '' => '蟯', + '' => '蟬', + '' => '蟲', + '' => '蟠', + '' => '覆', + '' => '覲', + '' => '觴', + '' => '謨', + '' => '謹', + '' => '謬', + '' => '謫', + '' => '豐', + '' => '贅', + '' => '蹙', + '' => '蹣', + '' => '蹦', + '' => '蹤', + '' => '蹟', + '' => '蹕', + '' => '軀', + '' => '轉', + '' => '轍', + '' => '邇', + '' => '邃', + '' => '邈', + '' => '醫', + '' => '醬', + '' => '釐', + '' => '鎔', + '' => '鎊', + '' => '鎖', + '' => '鎢', + '' => '鎳', + '' => '鎮', + '' => '鎬', + '' => '鎰', + '' => '鎘', + '' => '鎚', + '' => '鎗', + '' => '闔', + '' => '闖', + '' => '闐', + '' => '闕', + '' => '離', + '' => '雜', + '' => '雙', + '' => '雛', + '' => '雞', + '' => '霤', + '' => '鞣', + '' => '鞦', + '@' => '鞭', + 'A' => '韹', + 'B' => '額', + 'C' => '顏', + 'D' => '題', + 'E' => '顎', + 'F' => '顓', + 'G' => '颺', + 'H' => '餾', + 'I' => '餿', + 'J' => '餽', + 'K' => '餮', + 'L' => '馥', + 'M' => '騎', + 'N' => '髁', + 'O' => '鬃', + 'P' => '鬆', + 'Q' => '魏', + 'R' => '魎', + 'S' => '魍', + 'T' => '鯊', + 'U' => '鯉', + 'V' => '鯽', + 'W' => '鯈', + 'X' => '鯀', + 'Y' => '鵑', + 'Z' => '鵝', + '[' => '鵠', + '\\' => '黠', + ']' => '鼕', + '^' => '鼬', + '_' => '儳', + '`' => '嚥', + 'a' => '壞', + 'b' => '壟', + 'c' => '壢', + 'd' => '寵', + 'e' => '龐', + 'f' => '廬', + 'g' => '懲', + 'h' => '懷', + 'i' => '懶', + 'j' => '懵', + 'k' => '攀', + 'l' => '攏', + 'm' => '曠', + 'n' => '曝', + 'o' => '櫥', + 'p' => '櫝', + 'q' => '櫚', + 'r' => '櫓', + 's' => '瀛', + 't' => '瀟', + 'u' => '瀨', + 'v' => '瀚', + 'w' => '瀝', + 'x' => '瀕', + 'y' => '瀘', + 'z' => '爆', + '{' => '爍', + '|' => '牘', + '}' => '犢', + '~' => '獸', + 'á' => '獺', + 'â' => '璽', + 'ã' => '瓊', + 'ä' => '瓣', + 'å' => '疇', + 'æ' => '疆', + 'ç' => '癟', + 'è' => '癡', + 'é' => '矇', + 'ê' => '礙', + 'ë' => '禱', + 'ì' => '穫', + 'í' => '穩', + 'î' => '簾', + 'ï' => '簿', + 'ð' => '簸', + 'ñ' => '簽', + 'ò' => '簷', + 'ó' => '籀', + 'ô' => '繫', + 'õ' => '繭', + 'ö' => '繹', + '÷' => '繩', + 'ø' => '繪', + 'ù' => '羅', + 'ú' => '繳', + 'û' => '羶', + 'ü' => '羹', + 'ý' => '羸', + 'þ' => '臘', + 'ÿ' => '藩', + '' => '藝', + '' => '藪', + '' => '藕', + '' => '藤', + '' => '藥', + '' => '藷', + '' => '蟻', + '' => '蠅', + '' => '蠍', + '' => '蟹', + '' => '蟾', + '' => '襠', + '' => '襟', + '' => '襖', + '' => '襞', + '' => '譁', + '' => '譜', + '' => '識', + '' => '證', + '' => '譚', + '' => '譎', + '' => '譏', + '' => '譆', + '' => '譙', + '' => '贈', + '' => '贊', + '' => '蹼', + '' => '蹲', + '' => '躇', + '' => '蹶', + '' => '蹬', + '' => '蹺', + '' => '蹴', + '' => '轔', + '' => '轎', + '' => '辭', + '' => '邊', + '' => '邋', + '' => '醱', + '' => '醮', + '' => '鏡', + '' => '鏑', + '' => '鏟', + '' => '鏃', + '' => '鏈', + '' => '鏜', + '' => '鏝', + '' => '鏖', + '' => '鏢', + '' => '鏍', + '' => '鏘', + '' => '鏤', + '' => '鏗', + '' => '鏨', + '' => '關', + '' => '隴', + '' => '難', + '' => '霪', + '' => '霧', + '' => '靡', + '' => '韜', + '' => '韻', + '' => '類', + '@' => '願', + 'A' => '顛', + 'B' => '颼', + 'C' => '饅', + 'D' => '饉', + 'E' => '騖', + 'F' => '騙', + 'G' => '鬍', + 'H' => '鯨', + 'I' => '鯧', + 'J' => '鯖', + 'K' => '鯛', + 'L' => '鶉', + 'M' => '鵡', + 'N' => '鵲', + 'O' => '鵪', + 'P' => '鵬', + 'Q' => '麒', + 'R' => '麗', + 'S' => '麓', + 'T' => '麴', + 'U' => '勸', + 'V' => '嚨', + 'W' => '嚷', + 'X' => '嚶', + 'Y' => '嚴', + 'Z' => '嚼', + '[' => '壤', + '\\' => '孀', + ']' => '孃', + '^' => '孽', + '_' => '寶', + '`' => '巉', + 'a' => '懸', + 'b' => '懺', + 'c' => '攘', + 'd' => '攔', + 'e' => '攙', + 'f' => '曦', + 'g' => '朧', + 'h' => '櫬', + 'i' => '瀾', + 'j' => '瀰', + 'k' => '瀲', + 'l' => '爐', + 'm' => '獻', + 'n' => '瓏', + 'o' => '癢', + 'p' => '癥', + 'q' => '礦', + 'r' => '礪', + 's' => '礬', + 't' => '礫', + 'u' => '竇', + 'v' => '競', + 'w' => '籌', + 'x' => '籃', + 'y' => '籍', + 'z' => '糯', + '{' => '糰', + '|' => '辮', + '}' => '繽', + '~' => '繼', + 'ġ' => '纂', + 'Ģ' => '罌', + 'ģ' => '耀', + 'Ĥ' => '臚', + 'ĥ' => '艦', + 'Ħ' => '藻', + 'ħ' => '藹', + 'Ĩ' => '蘑', + 'ĩ' => '藺', + 'Ī' => '蘆', + 'ī' => '蘋', + 'Ĭ' => '蘇', + 'ĭ' => '蘊', + 'Į' => '蠔', + 'į' => '蠕', + 'İ' => '襤', + 'ı' => '覺', + 'IJ' => '觸', + 'ij' => '議', + 'Ĵ' => '譬', + 'ĵ' => '警', + 'Ķ' => '譯', + 'ķ' => '譟', + 'ĸ' => '譫', + 'Ĺ' => '贏', + 'ĺ' => '贍', + 'Ļ' => '躉', + 'ļ' => '躁', + 'Ľ' => '躅', + 'ľ' => '躂', + 'Ŀ' => '醴', + '' => '釋', + '' => '鐘', + '' => '鐃', + '' => '鏽', + '' => '闡', + '' => '霰', + '' => '飄', + '' => '饒', + '' => '饑', + '' => '馨', + '' => '騫', + '' => '騰', + '' => '騷', + '' => '騵', + '' => '鰓', + '' => '鰍', + '' => '鹹', + '' => '麵', + '' => '黨', + '' => '鼯', + '' => '齟', + '' => '齣', + '' => '齡', + '' => '儷', + '' => '儸', + '' => '囁', + '' => '囀', + '' => '囂', + '' => '夔', + '' => '屬', + '' => '巍', + '' => '懼', + '' => '懾', + '' => '攝', + '' => '攜', + '' => '斕', + '' => '曩', + '' => '櫻', + '' => '欄', + '' => '櫺', + '' => '殲', + '' => '灌', + '' => '爛', + '' => '犧', + '' => '瓖', + '' => '瓔', + '' => '癩', + '' => '矓', + '' => '籐', + '' => '纏', + '' => '續', + '' => '羼', + '' => '蘗', + '' => '蘭', + '' => '蘚', + '' => '蠣', + '' => '蠢', + '' => '蠡', + '' => '蠟', + '' => '襪', + '' => '襬', + '' => '覽', + '' => '譴', + '@' => '護', + 'A' => '譽', + 'B' => '贓', + 'C' => '躊', + 'D' => '躍', + 'E' => '躋', + 'F' => '轟', + 'G' => '辯', + 'H' => '醺', + 'I' => '鐮', + 'J' => '鐳', + 'K' => '鐵', + 'L' => '鐺', + 'M' => '鐸', + 'N' => '鐲', + 'O' => '鐫', + 'P' => '闢', + 'Q' => '霸', + 'R' => '霹', + 'S' => '露', + 'T' => '響', + 'U' => '顧', + 'V' => '顥', + 'W' => '饗', + 'X' => '驅', + 'Y' => '驃', + 'Z' => '驀', + '[' => '騾', + '\\' => '髏', + ']' => '魔', + '^' => '魑', + '_' => '鰭', + '`' => '鰥', + 'a' => '鶯', + 'b' => '鶴', + 'c' => '鷂', + 'd' => '鶸', + 'e' => '麝', + 'f' => '黯', + 'g' => '鼙', + 'h' => '齜', + 'i' => '齦', + 'j' => '齧', + 'k' => '儼', + 'l' => '儻', + 'm' => '囈', + 'n' => '囊', + 'o' => '囉', + 'p' => '孿', + 'q' => '巔', + 'r' => '巒', + 's' => '彎', + 't' => '懿', + 'u' => '攤', + 'v' => '權', + 'w' => '歡', + 'x' => '灑', + 'y' => '灘', + 'z' => '玀', + '{' => '瓤', + '|' => '疊', + '}' => '癮', + '~' => '癬', + 'š' => '禳', + 'Ţ' => '籠', + 'ţ' => '籟', + 'Ť' => '聾', + 'ť' => '聽', + 'Ŧ' => '臟', + 'ŧ' => '襲', + 'Ũ' => '襯', + 'ũ' => '觼', + 'Ū' => '讀', + 'ū' => '贖', + 'Ŭ' => '贗', + 'ŭ' => '躑', + 'Ů' => '躓', + 'ů' => '轡', + 'Ű' => '酈', + 'ű' => '鑄', + 'Ų' => '鑑', + 'ų' => '鑒', + 'Ŵ' => '霽', + 'ŵ' => '霾', + 'Ŷ' => '韃', + 'ŷ' => '韁', + 'Ÿ' => '顫', + 'Ź' => '饕', + 'ź' => '驕', + 'Ż' => '驍', + 'ż' => '髒', + 'Ž' => '鬚', + 'ž' => '鱉', + 'ſ' => '鰱', + '' => '鰾', + '' => '鰻', + '' => '鷓', + '' => '鷗', + '' => '鼴', + '' => '齬', + '' => '齪', + '' => '龔', + '' => '囌', + '' => '巖', + '' => '戀', + '' => '攣', + '' => '攫', + '' => '攪', + '' => '曬', + '' => '欐', + '' => '瓚', + '' => '竊', + '' => '籤', + '' => '籣', + '' => '籥', + '' => '纓', + '' => '纖', + '' => '纔', + '' => '臢', + '' => '蘸', + '' => '蘿', + '' => '蠱', + '' => '變', + '' => '邐', + '' => '邏', + '' => '鑣', + '' => '鑠', + '' => '鑤', + '' => '靨', + '' => '顯', + '' => '饜', + '' => '驚', + '' => '驛', + '' => '驗', + '' => '髓', + '' => '體', + '' => '髑', + '' => '鱔', + '' => '鱗', + '' => '鱖', + '' => '鷥', + '' => '麟', + '' => '黴', + '' => '囑', + '' => '壩', + '' => '攬', + '' => '灞', + '' => '癱', + '' => '癲', + '' => '矗', + '' => '罐', + '' => '羈', + '' => '蠶', + '' => '蠹', + '' => '衢', + '' => '讓', + '' => '讒', + '@' => '讖', + 'A' => '艷', + 'B' => '贛', + 'C' => '釀', + 'D' => '鑪', + 'E' => '靂', + 'F' => '靈', + 'G' => '靄', + 'H' => '韆', + 'I' => '顰', + 'J' => '驟', + 'K' => '鬢', + 'L' => '魘', + 'M' => '鱟', + 'N' => '鷹', + 'O' => '鷺', + 'P' => '鹼', + 'Q' => '鹽', + 'R' => '鼇', + 'S' => '齷', + 'T' => '齲', + 'U' => '廳', + 'V' => '欖', + 'W' => '灣', + 'X' => '籬', + 'Y' => '籮', + 'Z' => '蠻', + '[' => '觀', + '\\' => '躡', + ']' => '釁', + '^' => '鑲', + '_' => '鑰', + '`' => '顱', + 'a' => '饞', + 'b' => '髖', + 'c' => '鬣', + 'd' => '黌', + 'e' => '灤', + 'f' => '矚', + 'g' => '讚', + 'h' => '鑷', + 'i' => '韉', + 'j' => '驢', + 'k' => '驥', + 'l' => '纜', + 'm' => '讜', + 'n' => '躪', + 'o' => '釅', + 'p' => '鑽', + 'q' => '鑾', + 'r' => '鑼', + 's' => '鱷', + 't' => '鱸', + 'u' => '黷', + 'v' => '豔', + 'w' => '鑿', + 'x' => '鸚', + 'y' => '爨', + 'z' => '驪', + '{' => '鬱', + '|' => '鸛', + '}' => '鸞', + '~' => '籲', + 'ơ' => 'ヾ', + 'Ƣ' => 'ゝ', + 'ƣ' => 'ゞ', + 'Ƥ' => '々', + 'ƥ' => 'ぁ', + 'Ʀ' => 'あ', + 'Ƨ' => 'ぃ', + 'ƨ' => 'い', + 'Ʃ' => 'ぅ', + 'ƪ' => 'う', + 'ƫ' => 'ぇ', + 'Ƭ' => 'え', + 'ƭ' => 'ぉ', + 'Ʈ' => 'お', + 'Ư' => 'か', + 'ư' => 'が', + 'Ʊ' => 'き', + 'Ʋ' => 'ぎ', + 'Ƴ' => 'く', + 'ƴ' => 'ぐ', + 'Ƶ' => 'け', + 'ƶ' => 'げ', + 'Ʒ' => 'こ', + 'Ƹ' => 'ご', + 'ƹ' => 'さ', + 'ƺ' => 'ざ', + 'ƻ' => 'し', + 'Ƽ' => 'じ', + 'ƽ' => 'す', + 'ƾ' => 'ず', + 'ƿ' => 'せ', + '' => 'ぜ', + '' => 'そ', + '' => 'ぞ', + '' => 'た', + '' => 'だ', + '' => 'ち', + '' => 'ぢ', + '' => 'っ', + '' => 'つ', + '' => 'づ', + '' => 'て', + '' => 'で', + '' => 'と', + '' => 'ど', + '' => 'な', + '' => 'に', + '' => 'ぬ', + '' => 'ね', + '' => 'の', + '' => 'は', + '' => 'ば', + '' => 'ぱ', + '' => 'ひ', + '' => 'び', + '' => 'ぴ', + '' => 'ふ', + '' => 'ぶ', + '' => 'ぷ', + '' => 'へ', + '' => 'べ', + '' => 'ぺ', + '' => 'ほ', + '' => 'ぼ', + '' => 'ぽ', + '' => 'ま', + '' => 'み', + '' => 'む', + '' => 'め', + '' => 'も', + '' => 'ゃ', + '' => 'や', + '' => 'ゅ', + '' => 'ゆ', + '' => 'ょ', + '' => 'よ', + '' => 'ら', + '' => 'り', + '' => 'る', + '' => 'れ', + '' => 'ろ', + '' => 'ゎ', + '' => 'わ', + '' => 'ゐ', + '' => 'ゑ', + '' => 'を', + '' => 'ん', + '' => 'ァ', + '' => 'ア', + '' => 'ィ', + '' => 'イ', + '' => 'ゥ', + '' => 'ウ', + '' => 'ェ', + '@' => 'エ', + 'A' => 'ォ', + 'B' => 'オ', + 'C' => 'カ', + 'D' => 'ガ', + 'E' => 'キ', + 'F' => 'ギ', + 'G' => 'ク', + 'H' => 'グ', + 'I' => 'ケ', + 'J' => 'ゲ', + 'K' => 'コ', + 'L' => 'ゴ', + 'M' => 'サ', + 'N' => 'ザ', + 'O' => 'シ', + 'P' => 'ジ', + 'Q' => 'ス', + 'R' => 'ズ', + 'S' => 'セ', + 'T' => 'ゼ', + 'U' => 'ソ', + 'V' => 'ゾ', + 'W' => 'タ', + 'X' => 'ダ', + 'Y' => 'チ', + 'Z' => 'ヂ', + '[' => 'ッ', + '\\' => 'ツ', + ']' => 'ヅ', + '^' => 'テ', + '_' => 'デ', + '`' => 'ト', + 'a' => 'ド', + 'b' => 'ナ', + 'c' => 'ニ', + 'd' => 'ヌ', + 'e' => 'ネ', + 'f' => 'ノ', + 'g' => 'ハ', + 'h' => 'バ', + 'i' => 'パ', + 'j' => 'ヒ', + 'k' => 'ビ', + 'l' => 'ピ', + 'm' => 'フ', + 'n' => 'ブ', + 'o' => 'プ', + 'p' => 'ヘ', + 'q' => 'ベ', + 'r' => 'ペ', + 's' => 'ホ', + 't' => 'ボ', + 'u' => 'ポ', + 'v' => 'マ', + 'w' => 'ミ', + 'x' => 'ム', + 'y' => 'メ', + 'z' => 'モ', + '{' => 'ャ', + '|' => 'ヤ', + '}' => 'ュ', + '~' => 'ユ', + 'ǡ' => 'ョ', + 'Ǣ' => 'ヨ', + 'ǣ' => 'ラ', + 'Ǥ' => 'リ', + 'ǥ' => 'ル', + 'Ǧ' => 'レ', + 'ǧ' => 'ロ', + 'Ǩ' => 'ヮ', + 'ǩ' => 'ワ', + 'Ǫ' => 'ヰ', + 'ǫ' => 'ヱ', + 'Ǭ' => 'ヲ', + 'ǭ' => 'ン', + 'Ǯ' => 'ヴ', + 'ǯ' => 'ヵ', + 'ǰ' => 'ヶ', + 'DZ' => 'Д', + 'Dz' => 'Е', + 'dz' => 'Ё', + 'Ǵ' => 'Ж', + 'ǵ' => 'З', + 'Ƕ' => 'И', + 'Ƿ' => 'Й', + 'Ǹ' => 'К', + 'ǹ' => 'Л', + 'Ǻ' => 'М', + 'ǻ' => 'У', + 'Ǽ' => 'Ф', + 'ǽ' => 'Х', + 'Ǿ' => 'Ц', + 'ǿ' => 'Ч', + '' => 'Ш', + '' => 'Щ', + '' => 'Ъ', + '' => 'Ы', + '' => 'Ь', + '' => 'Э', + '' => 'Ю', + '' => 'Я', + '' => 'а', + '' => 'б', + '' => 'в', + '' => 'г', + '' => 'д', + '' => 'е', + '' => 'ё', + '' => 'ж', + '' => 'з', + '' => 'и', + '' => 'й', + '' => 'к', + '' => 'л', + '' => 'м', + '' => 'н', + '' => 'о', + '' => 'п', + '' => 'р', + '' => 'с', + '' => 'т', + '' => 'у', + '' => 'ф', + '' => 'х', + '' => 'ц', + '' => 'ч', + '' => 'ш', + '' => 'щ', + '' => 'ъ', + '' => 'ы', + '' => 'ь', + '' => 'э', + '' => 'ю', + '' => 'я', + '' => '①', + '' => '②', + '' => '③', + '' => '④', + '' => '⑤', + '' => '⑥', + '' => '⑦', + '' => '⑧', + '' => '⑨', + '' => '⑩', + '' => '⑴', + '' => '⑵', + '' => '⑶', + '' => '⑷', + '' => '⑸', + '' => '⑹', + '' => '⑺', + '' => '⑻', + '' => '⑼', + '' => '⑽', + '@' => '乂', + 'A' => '乜', + 'B' => '凵', + 'C' => '匚', + 'D' => '厂', + 'E' => '万', + 'F' => '丌', + 'G' => '乇', + 'H' => '亍', + 'I' => '囗', + 'J' => '兀', + 'K' => '屮', + 'L' => '彳', + 'M' => '丏', + 'N' => '冇', + 'O' => '与', + 'P' => '丮', + 'Q' => '亓', + 'R' => '仂', + 'S' => '仉', + 'T' => '仈', + 'U' => '冘', + 'V' => '勼', + 'W' => '卬', + 'X' => '厹', + 'Y' => '圠', + 'Z' => '夃', + '[' => '夬', + '\\' => '尐', + ']' => '巿', + '^' => '旡', + '_' => '殳', + '`' => '毌', + 'a' => '气', + 'b' => '爿', + 'c' => '丱', + 'd' => '丼', + 'e' => '仨', + 'f' => '仜', + 'g' => '仩', + 'h' => '仡', + 'i' => '仝', + 'j' => '仚', + 'k' => '刌', + 'l' => '匜', + 'm' => '卌', + 'n' => '圢', + 'o' => '圣', + 'p' => '夗', + 'q' => '夯', + 'r' => '宁', + 's' => '宄', + 't' => '尒', + 'u' => '尻', + 'v' => '屴', + 'w' => '屳', + 'x' => '帄', + 'y' => '庀', + 'z' => '庂', + '{' => '忉', + '|' => '戉', + '}' => '扐', + '~' => '氕', + 'ɡ' => '氶', + 'ɢ' => '汃', + 'ɣ' => '氿', + 'ɤ' => '氻', + 'ɥ' => '犮', + 'ɦ' => '犰', + 'ɧ' => '玊', + 'ɨ' => '禸', + 'ɩ' => '肊', + 'ɪ' => '阞', + 'ɫ' => '伎', + 'ɬ' => '优', + 'ɭ' => '伬', + 'ɮ' => '仵', + 'ɯ' => '伔', + 'ɰ' => '仱', + 'ɱ' => '伀', + 'ɲ' => '价', + 'ɳ' => '伈', + 'ɴ' => '伝', + 'ɵ' => '伂', + 'ɶ' => '伅', + 'ɷ' => '伢', + 'ɸ' => '伓', + 'ɹ' => '伄', + 'ɺ' => '仴', + 'ɻ' => '伒', + 'ɼ' => '冱', + 'ɽ' => '刓', + 'ɾ' => '刉', + 'ɿ' => '刐', + '' => '劦', + '' => '匢', + '' => '匟', + '' => '卍', + '' => '厊', + '' => '吇', + '' => '囡', + '' => '囟', + '' => '圮', + '' => '圪', + '' => '圴', + '' => '夼', + '' => '妀', + '' => '奼', + '' => '妅', + '' => '奻', + '' => '奾', + '' => '奷', + '' => '奿', + '' => '孖', + '' => '尕', + '' => '尥', + '' => '屼', + '' => '屺', + '' => '屻', + '' => '屾', + '' => '巟', + '' => '幵', + '' => '庄', + '' => '异', + '' => '弚', + '' => '彴', + '' => '忕', + '' => '忔', + '' => '忏', + '' => '扜', + '' => '扞', + '' => '扤', + '' => '扡', + '' => '扦', + '' => '扢', + '' => '扙', + '' => '扠', + '' => '扚', + '' => '扥', + '' => '旯', + '' => '旮', + '' => '朾', + '' => '朹', + '' => '朸', + '' => '朻', + '' => '机', + '' => '朿', + '' => '朼', + '' => '朳', + '' => '氘', + '' => '汆', + '' => '汒', + '' => '汜', + '' => '汏', + '' => '汊', + '' => '汔', + '' => '汋', + '@' => '汌', + 'A' => '灱', + 'B' => '牞', + 'C' => '犴', + 'D' => '犵', + 'E' => '玎', + 'F' => '甪', + 'G' => '癿', + 'H' => '穵', + 'I' => '网', + 'J' => '艸', + 'K' => '艼', + 'L' => '芀', + 'M' => '艽', + 'N' => '艿', + 'O' => '虍', + 'P' => '襾', + 'Q' => '邙', + 'R' => '邗', + 'S' => '邘', + 'T' => '邛', + 'U' => '邔', + 'V' => '阢', + 'W' => '阤', + 'X' => '阠', + 'Y' => '阣', + 'Z' => '佖', + '[' => '伻', + '\\' => '佢', + ']' => '佉', + '^' => '体', + '_' => '佤', + '`' => '伾', + 'a' => '佧', + 'b' => '佒', + 'c' => '佟', + 'd' => '佁', + 'e' => '佘', + 'f' => '伭', + 'g' => '伳', + 'h' => '伿', + 'i' => '佡', + 'j' => '冏', + 'k' => '冹', + 'l' => '刜', + 'm' => '刞', + 'n' => '刡', + 'o' => '劭', + 'p' => '劮', + 'q' => '匉', + 'r' => '卣', + 's' => '卲', + 't' => '厎', + 'u' => '厏', + 'v' => '吰', + 'w' => '吷', + 'x' => '吪', + 'y' => '呔', + 'z' => '呅', + '{' => '吙', + '|' => '吜', + '}' => '吥', + '~' => '吘', + 'ʡ' => '吽', + 'ʢ' => '呏', + 'ʣ' => '呁', + 'ʤ' => '吨', + 'ʥ' => '吤', + 'ʦ' => '呇', + 'ʧ' => '囮', + 'ʨ' => '囧', + 'ʩ' => '囥', + 'ʪ' => '坁', + 'ʫ' => '坅', + 'ʬ' => '坌', + 'ʭ' => '坉', + 'ʮ' => '坋', + 'ʯ' => '坒', + 'ʰ' => '夆', + 'ʱ' => '奀', + 'ʲ' => '妦', + 'ʳ' => '妘', + 'ʴ' => '妠', + 'ʵ' => '妗', + 'ʶ' => '妎', + 'ʷ' => '妢', + 'ʸ' => '妐', + 'ʹ' => '妏', + 'ʺ' => '妧', + 'ʻ' => '妡', + 'ʼ' => '宎', + 'ʽ' => '宒', + 'ʾ' => '尨', + 'ʿ' => '尪', + '' => '岍', + '' => '岏', + '' => '岈', + '' => '岋', + '' => '岉', + '' => '岒', + '' => '岊', + '' => '岆', + '' => '岓', + '' => '岕', + '' => '巠', + '' => '帊', + '' => '帎', + '' => '庋', + '' => '庉', + '' => '庌', + '' => '庈', + '' => '庍', + '' => '弅', + '' => '弝', + '' => '彸', + '' => '彶', + '' => '忒', + '' => '忑', + '' => '忐', + '' => '忭', + '' => '忨', + '' => '忮', + '' => '忳', + '' => '忡', + '' => '忤', + '' => '忣', + '' => '忺', + '' => '忯', + '' => '忷', + '' => '忻', + '' => '怀', + '' => '忴', + '' => '戺', + '' => '抃', + '' => '抌', + '' => '抎', + '' => '抏', + '' => '抔', + '' => '抇', + '' => '扱', + '' => '扻', + '' => '扺', + '' => '扰', + '' => '抁', + '' => '抈', + '' => '扷', + '' => '扽', + '' => '扲', + '' => '扴', + '' => '攷', + '' => '旰', + '' => '旴', + '' => '旳', + '' => '旲', + '' => '旵', + '' => '杅', + '' => '杇', + '@' => '杙', + 'A' => '杕', + 'B' => '杌', + 'C' => '杈', + 'D' => '杝', + 'E' => '杍', + 'F' => '杚', + 'G' => '杋', + 'H' => '毐', + 'I' => '氙', + 'J' => '氚', + 'K' => '汸', + 'L' => '汧', + 'M' => '汫', + 'N' => '沄', + 'O' => '沋', + 'P' => '沏', + 'Q' => '汱', + 'R' => '汯', + 'S' => '汩', + 'T' => '沚', + 'U' => '汭', + 'V' => '沇', + 'W' => '沕', + 'X' => '沜', + 'Y' => '汦', + 'Z' => '汳', + '[' => '汥', + '\\' => '汻', + ']' => '沎', + '^' => '灴', + '_' => '灺', + '`' => '牣', + 'a' => '犿', + 'b' => '犽', + 'c' => '狃', + 'd' => '狆', + 'e' => '狁', + 'f' => '犺', + 'g' => '狅', + 'h' => '玕', + 'i' => '玗', + 'j' => '玓', + 'k' => '玔', + 'l' => '玒', + 'm' => '町', + 'n' => '甹', + 'o' => '疔', + 'p' => '疕', + 'q' => '皁', + 'r' => '礽', + 's' => '耴', + 't' => '肕', + 'u' => '肙', + 'v' => '肐', + 'w' => '肒', + 'x' => '肜', + 'y' => '芐', + 'z' => '芏', + '{' => '芅', + '|' => '芎', + '}' => '芑', + '~' => '芓', + 'ˡ' => '芊', + 'ˢ' => '芃', + 'ˣ' => '芄', + 'ˤ' => '豸', + '˥' => '迉', + '˦' => '辿', + '˧' => '邟', + '˨' => '邡', + '˩' => '邥', + '˪' => '邞', + '˫' => '邧', + 'ˬ' => '邠', + '˭' => '阰', + 'ˮ' => '阨', + '˯' => '阯', + '˰' => '阭', + '˱' => '丳', + '˲' => '侘', + '˳' => '佼', + '˴' => '侅', + '˵' => '佽', + '˶' => '侀', + '˷' => '侇', + '˸' => '佶', + '˹' => '佴', + '˺' => '侉', + '˻' => '侄', + '˼' => '佷', + '˽' => '佌', + '˾' => '侗', + '˿' => '佪', + '' => '侚', + '' => '佹', + '' => '侁', + '' => '佸', + '' => '侐', + '' => '侜', + '' => '侔', + '' => '侞', + '' => '侒', + '' => '侂', + '' => '侕', + '' => '佫', + '' => '佮', + '' => '冞', + '' => '冼', + '' => '冾', + '' => '刵', + '' => '刲', + '' => '刳', + '' => '剆', + '' => '刱', + '' => '劼', + '' => '匊', + '' => '匋', + '' => '匼', + '' => '厒', + '' => '厔', + '' => '咇', + '' => '呿', + '' => '咁', + '' => '咑', + '' => '咂', + '' => '咈', + '' => '呫', + '' => '呺', + '' => '呾', + '' => '呥', + '' => '呬', + '' => '呴', + '' => '呦', + '' => '咍', + '' => '呯', + '' => '呡', + '' => '呠', + '' => '咘', + '' => '呣', + '' => '呧', + '' => '呤', + '' => '囷', + '' => '囹', + '' => '坯', + '' => '坲', + '' => '坭', + '' => '坫', + '' => '坱', + '' => '坰', + '' => '坶', + '' => '垀', + '' => '坵', + '' => '坻', + '' => '坳', + '' => '坴', + '' => '坢', + '@' => '坨', + 'A' => '坽', + 'B' => '夌', + 'C' => '奅', + 'D' => '妵', + 'E' => '妺', + 'F' => '姏', + 'G' => '姎', + 'H' => '妲', + 'I' => '姌', + 'J' => '姁', + 'K' => '妶', + 'L' => '妼', + 'M' => '姃', + 'N' => '姖', + 'O' => '妱', + 'P' => '妽', + 'Q' => '姀', + 'R' => '姈', + 'S' => '妴', + 'T' => '姇', + 'U' => '孢', + 'V' => '孥', + 'W' => '宓', + 'X' => '宕', + 'Y' => '屄', + 'Z' => '屇', + '[' => '岮', + '\\' => '岤', + ']' => '岠', + '^' => '岵', + '_' => '岯', + '`' => '岨', + 'a' => '岬', + 'b' => '岟', + 'c' => '岣', + 'd' => '岭', + 'e' => '岢', + 'f' => '岪', + 'g' => '岧', + 'h' => '岝', + 'i' => '岥', + 'j' => '岶', + 'k' => '岰', + 'l' => '岦', + 'm' => '帗', + 'n' => '帔', + 'o' => '帙', + 'p' => '弨', + 'q' => '弢', + 'r' => '弣', + 's' => '弤', + 't' => '彔', + 'u' => '徂', + 'v' => '彾', + 'w' => '彽', + 'x' => '忞', + 'y' => '忥', + 'z' => '怭', + '{' => '怦', + '|' => '怙', + '}' => '怲', + '~' => '怋', + '̡' => '怴', + '̢' => '怊', + '̣' => '怗', + '̤' => '怳', + '̥' => '怚', + '̦' => '怞', + '̧' => '怬', + '̨' => '怢', + '̩' => '怍', + '̪' => '怐', + '̫' => '怮', + '̬' => '怓', + '̭' => '怑', + '̮' => '怌', + '̯' => '怉', + '̰' => '怜', + '̱' => '戔', + '̲' => '戽', + '̳' => '抭', + '̴' => '抴', + '̵' => '拑', + '̶' => '抾', + '̷' => '抪', + '̸' => '抶', + '̹' => '拊', + '̺' => '抮', + '̻' => '抳', + '̼' => '抯', + '̽' => '抻', + '̾' => '抩', + '̿' => '抰', + '' => '抸', + '' => '攽', + '' => '斨', + '' => '斻', + '' => '昉', + '' => '旼', + '' => '昄', + '' => '昒', + '' => '昈', + '' => '旻', + '' => '昃', + '' => '昋', + '' => '昍', + '' => '昅', + '' => '旽', + '' => '昑', + '' => '昐', + '' => '曶', + '' => '朊', + '' => '枅', + '' => '杬', + '' => '枎', + '' => '枒', + '' => '杶', + '' => '杻', + '' => '枘', + '' => '枆', + '' => '构', + '' => '杴', + '' => '枍', + '' => '枌', + '' => '杺', + '' => '枟', + '' => '枑', + '' => '枙', + '' => '枃', + '' => '杽', + '' => '极', + '' => '杸', + '' => '杹', + '' => '枔', + '' => '欥', + '' => '殀', + '' => '歾', + '' => '毞', + '' => '氝', + '' => '沓', + '' => '泬', + '' => '泫', + '' => '泮', + '' => '泙', + '' => '沶', + '' => '泔', + '' => '沭', + '' => '泧', + '' => '沷', + '' => '泐', + '' => '泂', + '' => '沺', + '' => '泃', + '' => '泆', + '' => '泭', + '' => '泲', + '@' => '泒', + 'A' => '泝', + 'B' => '沴', + 'C' => '沊', + 'D' => '沝', + 'E' => '沀', + 'F' => '泞', + 'G' => '泀', + 'H' => '洰', + 'I' => '泍', + 'J' => '泇', + 'K' => '沰', + 'L' => '泹', + 'M' => '泏', + 'N' => '泩', + 'O' => '泑', + 'P' => '炔', + 'Q' => '炘', + 'R' => '炅', + 'S' => '炓', + 'T' => '炆', + 'U' => '炄', + 'V' => '炑', + 'W' => '炖', + 'X' => '炂', + 'Y' => '炚', + 'Z' => '炃', + '[' => '牪', + '\\' => '狖', + ']' => '狋', + '^' => '狘', + '_' => '狉', + '`' => '狜', + 'a' => '狒', + 'b' => '狔', + 'c' => '狚', + 'd' => '狌', + 'e' => '狑', + 'f' => '玤', + 'g' => '玡', + 'h' => '玭', + 'i' => '玦', + 'j' => '玢', + 'k' => '玠', + 'l' => '玬', + 'm' => '玝', + 'n' => '瓝', + 'o' => '瓨', + 'p' => '甿', + 'q' => '畀', + 'r' => '甾', + 's' => '疌', + 't' => '疘', + 'u' => '皯', + 'v' => '盳', + 'w' => '盱', + 'x' => '盰', + 'y' => '盵', + 'z' => '矸', + '{' => '矼', + '|' => '矹', + '}' => '矻', + '~' => '矺', + '͡' => '矷', + '͢' => '祂', + 'ͣ' => '礿', + 'ͤ' => '秅', + 'ͥ' => '穸', + 'ͦ' => '穻', + 'ͧ' => '竻', + 'ͨ' => '籵', + 'ͩ' => '糽', + 'ͪ' => '耵', + 'ͫ' => '肏', + 'ͬ' => '肮', + 'ͭ' => '肣', + 'ͮ' => '肸', + 'ͯ' => '肵', + 'Ͱ' => '肭', + 'ͱ' => '舠', + 'Ͳ' => '芠', + 'ͳ' => '苀', + 'ʹ' => '芫', + '͵' => '芚', + 'Ͷ' => '芘', + 'ͷ' => '芛', + '͸' => '芵', + '͹' => '芧', + 'ͺ' => '芮', + 'ͻ' => '芼', + 'ͼ' => '芞', + 'ͽ' => '芺', + ';' => '芴', + 'Ϳ' => '芨', + '' => '芡', + '' => '芩', + '' => '苂', + '' => '芤', + '' => '苃', + '' => '芶', + '' => '芢', + '' => '虰', + '' => '虯', + '' => '虭', + '' => '虮', + '' => '豖', + '' => '迒', + '' => '迋', + '' => '迓', + '' => '迍', + '' => '迖', + '' => '迕', + '' => '迗', + '' => '邲', + '' => '邴', + '' => '邯', + '' => '邳', + '' => '邰', + '' => '阹', + '' => '阽', + '' => '阼', + '' => '阺', + '' => '陃', + '' => '俍', + '' => '俅', + '' => '俓', + '' => '侲', + '' => '俉', + '' => '俋', + '' => '俁', + '' => '俔', + '' => '俜', + '' => '俙', + '' => '侻', + '' => '侳', + '' => '俛', + '' => '俇', + '' => '俖', + '' => '侺', + '' => '俀', + '' => '侹', + '' => '俬', + '' => '剄', + '' => '剉', + '' => '勀', + '' => '勂', + '' => '匽', + '' => '卼', + '' => '厗', + '' => '厖', + '' => '厙', + '' => '厘', + '' => '咺', + '' => '咡', + '' => '咭', + '' => '咥', + '' => '哏', + '@' => '哃', + 'A' => '茍', + 'B' => '咷', + 'C' => '咮', + 'D' => '哖', + 'E' => '咶', + 'F' => '哅', + 'G' => '哆', + 'H' => '咠', + 'I' => '呰', + 'J' => '咼', + 'K' => '咢', + 'L' => '咾', + 'M' => '呲', + 'N' => '哞', + 'O' => '咰', + 'P' => '垵', + 'Q' => '垞', + 'R' => '垟', + 'S' => '垤', + 'T' => '垌', + 'U' => '垗', + 'V' => '垝', + 'W' => '垛', + 'X' => '垔', + 'Y' => '垘', + 'Z' => '垏', + '[' => '垙', + '\\' => '垥', + ']' => '垚', + '^' => '垕', + '_' => '壴', + '`' => '复', + 'a' => '奓', + 'b' => '姡', + 'c' => '姞', + 'd' => '姮', + 'e' => '娀', + 'f' => '姱', + 'g' => '姝', + 'h' => '姺', + 'i' => '姽', + 'j' => '姼', + 'k' => '姶', + 'l' => '姤', + 'm' => '姲', + 'n' => '姷', + 'o' => '姛', + 'p' => '姩', + 'q' => '姳', + 'r' => '姵', + 's' => '姠', + 't' => '姾', + 'u' => '姴', + 'v' => '姭', + 'w' => '宨', + 'x' => '屌', + 'y' => '峐', + 'z' => '峘', + '{' => '峌', + '|' => '峗', + '}' => '峋', + '~' => '峛', + 'Ρ' => '峞', + '΢' => '峚', + 'Σ' => '峉', + 'Τ' => '峇', + 'Υ' => '峊', + 'Φ' => '峖', + 'Χ' => '峓', + 'Ψ' => '峔', + 'Ω' => '峏', + 'Ϊ' => '峈', + 'Ϋ' => '峆', + 'ά' => '峎', + 'έ' => '峟', + 'ή' => '峸', + 'ί' => '巹', + 'ΰ' => '帡', + 'α' => '帢', + 'β' => '帣', + 'γ' => '帠', + 'δ' => '帤', + 'ε' => '庰', + 'ζ' => '庤', + 'η' => '庢', + 'θ' => '庛', + 'ι' => '庣', + 'κ' => '庥', + 'λ' => '弇', + 'μ' => '弮', + 'ν' => '彖', + 'ξ' => '徆', + 'ο' => '怷', + '' => '怹', + '' => '恔', + '' => '恲', + '' => '恞', + '' => '恅', + '' => '恓', + '' => '恇', + '' => '恉', + '' => '恛', + '' => '恌', + '' => '恀', + '' => '恂', + '' => '恟', + '' => '怤', + '' => '恄', + '' => '恘', + '' => '恦', + '' => '恮', + '' => '扂', + '' => '扃', + '' => '拏', + '' => '挍', + '' => '挋', + '' => '拵', + '' => '挎', + '' => '挃', + '' => '拫', + '' => '拹', + '' => '挏', + '' => '挌', + '' => '拸', + '' => '拶', + '' => '挀', + '' => '挓', + '' => '挔', + '' => '拺', + '' => '挕', + '' => '拻', + '' => '拰', + '' => '敁', + '' => '敃', + '' => '斪', + '' => '斿', + '' => '昶', + '' => '昡', + '' => '昲', + '' => '昵', + '' => '昜', + '' => '昦', + '' => '昢', + '' => '昳', + '' => '昫', + '' => '昺', + '' => '昝', + '' => '昴', + '' => '昹', + '' => '昮', + '' => '朏', + '' => '朐', + '' => '柁', + '' => '柲', + '' => '柈', + '' => '枺', + '@' => '柜', + 'A' => '枻', + 'B' => '柸', + 'C' => '柘', + 'D' => '柀', + 'E' => '枷', + 'F' => '柅', + 'G' => '柫', + 'H' => '柤', + 'I' => '柟', + 'J' => '枵', + 'K' => '柍', + 'L' => '枳', + 'M' => '柷', + 'N' => '柶', + 'O' => '柮', + 'P' => '柣', + 'Q' => '柂', + 'R' => '枹', + 'S' => '柎', + 'T' => '柧', + 'U' => '柰', + 'V' => '枲', + 'W' => '柼', + 'X' => '柆', + 'Y' => '柭', + 'Z' => '柌', + '[' => '枮', + '\\' => '柦', + ']' => '柛', + '^' => '柺', + '_' => '柉', + '`' => '柊', + 'a' => '柃', + 'b' => '柪', + 'c' => '柋', + 'd' => '欨', + 'e' => '殂', + 'f' => '殄', + 'g' => '殶', + 'h' => '毖', + 'i' => '毘', + 'j' => '毠', + 'k' => '氠', + 'l' => '氡', + 'm' => '洨', + 'n' => '洴', + 'o' => '洭', + 'p' => '洟', + 'q' => '洼', + 'r' => '洿', + 's' => '洒', + 't' => '洊', + 'u' => '泚', + 'v' => '洳', + 'w' => '洄', + 'x' => '洙', + 'y' => '洺', + 'z' => '洚', + '{' => '洑', + '|' => '洀', + '}' => '洝', + '~' => '浂', + 'ϡ' => '洁', + 'Ϣ' => '洘', + 'ϣ' => '洷', + 'Ϥ' => '洃', + 'ϥ' => '洏', + 'Ϧ' => '浀', + 'ϧ' => '洇', + 'Ϩ' => '洠', + 'ϩ' => '洬', + 'Ϫ' => '洈', + 'ϫ' => '洢', + 'Ϭ' => '洉', + 'ϭ' => '洐', + 'Ϯ' => '炷', + 'ϯ' => '炟', + 'ϰ' => '炾', + 'ϱ' => '炱', + 'ϲ' => '炰', + 'ϳ' => '炡', + 'ϴ' => '炴', + 'ϵ' => '炵', + '϶' => '炩', + 'Ϸ' => '牁', + 'ϸ' => '牉', + 'Ϲ' => '牊', + 'Ϻ' => '牬', + 'ϻ' => '牰', + 'ϼ' => '牳', + 'Ͻ' => '牮', + 'Ͼ' => '狊', + 'Ͽ' => '狤', + '' => '狨', + '' => '狫', + '' => '狟', + '' => '狪', + '' => '狦', + '' => '狣', + '' => '玅', + '' => '珌', + '' => '珂', + '' => '珈', + '' => '珅', + '' => '玹', + '' => '玶', + '' => '玵', + '' => '玴', + '' => '珫', + '' => '玿', + '' => '珇', + '' => '玾', + '' => '珃', + '' => '珆', + '' => '玸', + '' => '珋', + '' => '瓬', + '' => '瓮', + '' => '甮', + '' => '畇', + '' => '畈', + '' => '疧', + '' => '疪', + '' => '癹', + '' => '盄', + '' => '眈', + '' => '眃', + '' => '眄', + '' => '眅', + '' => '眊', + '' => '盷', + '' => '盻', + '' => '盺', + '' => '矧', + '' => '矨', + '' => '砆', + '' => '砑', + '' => '砒', + '' => '砅', + '' => '砐', + '' => '砏', + '' => '砎', + '' => '砉', + '' => '砃', + '' => '砓', + '' => '祊', + '' => '祌', + '' => '祋', + '' => '祅', + '' => '祄', + '' => '秕', + '' => '种', + '' => '秏', + '' => '秖', + '' => '秎', + '' => '窀', + '@' => '穾', + 'A' => '竑', + 'B' => '笀', + 'C' => '笁', + 'D' => '籺', + 'E' => '籸', + 'F' => '籹', + 'G' => '籿', + 'H' => '粀', + 'I' => '粁', + 'J' => '紃', + 'K' => '紈', + 'L' => '紁', + 'M' => '罘', + 'N' => '羑', + 'O' => '羍', + 'P' => '羾', + 'Q' => '耇', + 'R' => '耎', + 'S' => '耏', + 'T' => '耔', + 'U' => '耷', + 'V' => '胘', + 'W' => '胇', + 'X' => '胠', + 'Y' => '胑', + 'Z' => '胈', + '[' => '胂', + '\\' => '胐', + ']' => '胅', + '^' => '胣', + '_' => '胙', + '`' => '胜', + 'a' => '胊', + 'b' => '胕', + 'c' => '胉', + 'd' => '胏', + 'e' => '胗', + 'f' => '胦', + 'g' => '胍', + 'h' => '臿', + 'i' => '舡', + 'j' => '芔', + 'k' => '苙', + 'l' => '苾', + 'm' => '苹', + 'n' => '茇', + 'o' => '苨', + 'p' => '茀', + 'q' => '苕', + 'r' => '茺', + 's' => '苫', + 't' => '苖', + 'u' => '苴', + 'v' => '苬', + 'w' => '苡', + 'x' => '苲', + 'y' => '苵', + 'z' => '茌', + '{' => '苻', + '|' => '苶', + '}' => '苰', + '~' => '苪', + 'С' => '苤', + 'Т' => '苠', + 'У' => '苺', + 'Ф' => '苳', + 'Х' => '苭', + 'Ц' => '虷', + 'Ч' => '虴', + 'Ш' => '虼', + 'Щ' => '虳', + 'Ъ' => '衁', + 'Ы' => '衎', + 'Ь' => '衧', + 'Э' => '衪', + 'Ю' => '衩', + 'Я' => '觓', + 'а' => '訄', + 'б' => '訇', + 'в' => '赲', + 'г' => '迣', + 'д' => '迡', + 'е' => '迮', + 'ж' => '迠', + 'з' => '郱', + 'и' => '邽', + 'й' => '邿', + 'к' => '郕', + 'л' => '郅', + 'м' => '邾', + 'н' => '郇', + 'о' => '郋', + 'п' => '郈', + '' => '釔', + '' => '釓', + '' => '陔', + '' => '陏', + '' => '陑', + '' => '陓', + '' => '陊', + '' => '陎', + '' => '倞', + '' => '倅', + '' => '倇', + '' => '倓', + '' => '倢', + '' => '倰', + '' => '倛', + '' => '俵', + '' => '俴', + '' => '倳', + '' => '倷', + '' => '倬', + '' => '俶', + '' => '俷', + '' => '倗', + '' => '倜', + '' => '倠', + '' => '倧', + '' => '倵', + '' => '倯', + '' => '倱', + '' => '倎', + '' => '党', + '' => '冔', + '' => '冓', + '' => '凊', + '' => '凄', + '' => '凅', + '' => '凈', + '' => '凎', + '' => '剡', + '' => '剚', + '' => '剒', + '' => '剞', + '' => '剟', + '' => '剕', + '' => '剢', + '' => '勍', + '' => '匎', + '' => '厞', + '' => '唦', + '' => '哢', + '' => '唗', + '' => '唒', + '' => '哧', + '' => '哳', + '' => '哤', + '' => '唚', + '' => '哿', + '' => '唄', + '' => '唈', + '' => '哫', + '' => '唑', + '' => '唅', + '' => '哱', + '@' => '唊', + 'A' => '哻', + 'B' => '哷', + 'C' => '哸', + 'D' => '哠', + 'E' => '唎', + 'F' => '唃', + 'G' => '唋', + 'H' => '圁', + 'I' => '圂', + 'J' => '埌', + 'K' => '堲', + 'L' => '埕', + 'M' => '埒', + 'N' => '垺', + 'O' => '埆', + 'P' => '垽', + 'Q' => '垼', + 'R' => '垸', + 'S' => '垶', + 'T' => '垿', + 'U' => '埇', + 'V' => '埐', + 'W' => '垹', + 'X' => '埁', + 'Y' => '夎', + 'Z' => '奊', + '[' => '娙', + '\\' => '娖', + ']' => '娭', + '^' => '娮', + '_' => '娕', + '`' => '娏', + 'a' => '娗', + 'b' => '娊', + 'c' => '娞', + 'd' => '娳', + 'e' => '孬', + 'f' => '宧', + 'g' => '宭', + 'h' => '宬', + 'i' => '尃', + 'j' => '屖', + 'k' => '屔', + 'l' => '峬', + 'm' => '峿', + 'n' => '峮', + 'o' => '峱', + 'p' => '峷', + 'q' => '崀', + 'r' => '峹', + 's' => '帩', + 't' => '帨', + 'u' => '庨', + 'v' => '庮', + 'w' => '庪', + 'x' => '庬', + 'y' => '弳', + 'z' => '弰', + '{' => '彧', + '|' => '恝', + '}' => '恚', + '~' => '恧', + 'ѡ' => '恁', + 'Ѣ' => '悢', + 'ѣ' => '悈', + 'Ѥ' => '悀', + 'ѥ' => '悒', + 'Ѧ' => '悁', + 'ѧ' => '悝', + 'Ѩ' => '悃', + 'ѩ' => '悕', + 'Ѫ' => '悛', + 'ѫ' => '悗', + 'Ѭ' => '悇', + 'ѭ' => '悜', + 'Ѯ' => '悎', + 'ѯ' => '戙', + 'Ѱ' => '扆', + 'ѱ' => '拲', + 'Ѳ' => '挐', + 'ѳ' => '捖', + 'Ѵ' => '挬', + 'ѵ' => '捄', + 'Ѷ' => '捅', + 'ѷ' => '挶', + 'Ѹ' => '捃', + 'ѹ' => '揤', + 'Ѻ' => '挹', + 'ѻ' => '捋', + 'Ѽ' => '捊', + 'ѽ' => '挼', + 'Ѿ' => '挩', + 'ѿ' => '捁', + '' => '挴', + '' => '捘', + '' => '捔', + '' => '捙', + '' => '挭', + '' => '捇', + '' => '挳', + '' => '捚', + '' => '捑', + '' => '挸', + '' => '捗', + '' => '捀', + '' => '捈', + '' => '敊', + '' => '敆', + '' => '旆', + '' => '旃', + '' => '旄', + '' => '旂', + '' => '晊', + '' => '晟', + '' => '晇', + '' => '晑', + '' => '朒', + '' => '朓', + '' => '栟', + '' => '栚', + '' => '桉', + '' => '栲', + '' => '栳', + '' => '栻', + '' => '桋', + '' => '桏', + '' => '栖', + '' => '栱', + '' => '栜', + '' => '栵', + '' => '栫', + '' => '栭', + '' => '栯', + '' => '桎', + '' => '桄', + '' => '栴', + '' => '栝', + '' => '栒', + '' => '栔', + '' => '栦', + '' => '栨', + '' => '栮', + '' => '桍', + '' => '栺', + '' => '栥', + '' => '栠', + '' => '欬', + '' => '欯', + '' => '欭', + '' => '欱', + '' => '欴', + '' => '歭', + '' => '肂', + '' => '殈', + '' => '毦', + '' => '毤', + '@' => '毨', + 'A' => '毣', + 'B' => '毢', + 'C' => '毧', + 'D' => '氥', + 'E' => '浺', + 'F' => '浣', + 'G' => '浤', + 'H' => '浶', + 'I' => '洍', + 'J' => '浡', + 'K' => '涒', + 'L' => '浘', + 'M' => '浢', + 'N' => '浭', + 'O' => '浯', + 'P' => '涑', + 'Q' => '涍', + 'R' => '淯', + 'S' => '浿', + 'T' => '涆', + 'U' => '浞', + 'V' => '浧', + 'W' => '浠', + 'X' => '涗', + 'Y' => '浰', + 'Z' => '浼', + '[' => '浟', + '\\' => '涂', + ']' => '涘', + '^' => '洯', + '_' => '浨', + '`' => '涋', + 'a' => '浾', + 'b' => '涀', + 'c' => '涄', + 'd' => '洖', + 'e' => '涃', + 'f' => '浻', + 'g' => '浽', + 'h' => '浵', + 'i' => '涐', + 'j' => '烜', + 'k' => '烓', + 'l' => '烑', + 'm' => '烝', + 'n' => '烋', + 'o' => '缹', + 'p' => '烢', + 'q' => '烗', + 'r' => '烒', + 's' => '烞', + 't' => '烠', + 'u' => '烔', + 'v' => '烍', + 'w' => '烅', + 'x' => '烆', + 'y' => '烇', + 'z' => '烚', + '{' => '烎', + '|' => '烡', + '}' => '牂', + '~' => '牸', + 'ҡ' => '牷', + 'Ң' => '牶', + 'ң' => '猀', + 'Ҥ' => '狺', + 'ҥ' => '狴', + 'Ҧ' => '狾', + 'ҧ' => '狶', + 'Ҩ' => '狳', + 'ҩ' => '狻', + 'Ҫ' => '猁', + 'ҫ' => '珓', + 'Ҭ' => '珙', + 'ҭ' => '珥', + 'Ү' => '珖', + 'ү' => '玼', + 'Ұ' => '珧', + 'ұ' => '珣', + 'Ҳ' => '珩', + 'ҳ' => '珜', + 'Ҵ' => '珒', + 'ҵ' => '珛', + 'Ҷ' => '珔', + 'ҷ' => '珝', + 'Ҹ' => '珚', + 'ҹ' => '珗', + 'Һ' => '珘', + 'һ' => '珨', + 'Ҽ' => '瓞', + 'ҽ' => '瓟', + 'Ҿ' => '瓴', + 'ҿ' => '瓵', + '' => '甡', + '' => '畛', + '' => '畟', + '' => '疰', + '' => '痁', + '' => '疻', + '' => '痄', + '' => '痀', + '' => '疿', + '' => '疶', + '' => '疺', + '' => '皊', + '' => '盉', + '' => '眝', + '' => '眛', + '' => '眐', + '' => '眓', + '' => '眒', + '' => '眣', + '' => '眑', + '' => '眕', + '' => '眙', + '' => '眚', + '' => '眢', + '' => '眧', + '' => '砣', + '' => '砬', + '' => '砢', + '' => '砵', + '' => '砯', + '' => '砨', + '' => '砮', + '' => '砫', + '' => '砡', + '' => '砩', + '' => '砳', + '' => '砪', + '' => '砱', + '' => '祔', + '' => '祛', + '' => '祏', + '' => '祜', + '' => '祓', + '' => '祒', + '' => '祑', + '' => '秫', + '' => '秬', + '' => '秠', + '' => '秮', + '' => '秭', + '' => '秪', + '' => '秜', + '' => '秞', + '' => '秝', + '' => '窆', + '' => '窉', + '' => '窅', + '' => '窋', + '' => '窌', + '' => '窊', + '' => '窇', + '' => '竘', + '' => '笐', + '@' => '笄', + 'A' => '笓', + 'B' => '笅', + 'C' => '笏', + 'D' => '笈', + 'E' => '笊', + 'F' => '笎', + 'G' => '笉', + 'H' => '笒', + 'I' => '粄', + 'J' => '粑', + 'K' => '粊', + 'L' => '粌', + 'M' => '粈', + 'N' => '粍', + 'O' => '粅', + 'P' => '紞', + 'Q' => '紝', + 'R' => '紑', + 'S' => '紎', + 'T' => '紘', + 'U' => '紖', + 'V' => '紓', + 'W' => '紟', + 'X' => '紒', + 'Y' => '紏', + 'Z' => '紌', + '[' => '罜', + '\\' => '罡', + ']' => '罞', + '^' => '罠', + '_' => '罝', + '`' => '罛', + 'a' => '羖', + 'b' => '羒', + 'c' => '翃', + 'd' => '翂', + 'e' => '翀', + 'f' => '耖', + 'g' => '耾', + 'h' => '耹', + 'i' => '胺', + 'j' => '胲', + 'k' => '胹', + 'l' => '胵', + 'm' => '脁', + 'n' => '胻', + 'o' => '脀', + 'p' => '舁', + 'q' => '舯', + 'r' => '舥', + 's' => '茳', + 't' => '茭', + 'u' => '荄', + 'v' => '茙', + 'w' => '荑', + 'x' => '茥', + 'y' => '荖', + 'z' => '茿', + '{' => '荁', + '|' => '茦', + '}' => '茜', + '~' => '茢', + 'ӡ' => '荂', + 'Ӣ' => '荎', + 'ӣ' => '茛', + 'Ӥ' => '茪', + 'ӥ' => '茈', + 'Ӧ' => '茼', + 'ӧ' => '荍', + 'Ө' => '茖', + 'ө' => '茤', + 'Ӫ' => '茠', + 'ӫ' => '茷', + 'Ӭ' => '茯', + 'ӭ' => '茩', + 'Ӯ' => '荇', + 'ӯ' => '荅', + 'Ӱ' => '荌', + 'ӱ' => '荓', + 'Ӳ' => '茞', + 'ӳ' => '茬', + 'Ӵ' => '荋', + 'ӵ' => '茧', + 'Ӷ' => '荈', + 'ӷ' => '虓', + 'Ӹ' => '虒', + 'ӹ' => '蚢', + 'Ӻ' => '蚨', + 'ӻ' => '蚖', + 'Ӽ' => '蚍', + 'ӽ' => '蚑', + 'Ӿ' => '蚞', + 'ӿ' => '蚇', + '' => '蚗', + '' => '蚆', + '' => '蚋', + '' => '蚚', + '' => '蚅', + '' => '蚥', + '' => '蚙', + '' => '蚡', + '' => '蚧', + '' => '蚕', + '' => '蚘', + '' => '蚎', + '' => '蚝', + '' => '蚐', + '' => '蚔', + '' => '衃', + '' => '衄', + '' => '衭', + '' => '衵', + '' => '衶', + '' => '衲', + '' => '袀', + '' => '衱', + '' => '衿', + '' => '衯', + '' => '袃', + '' => '衾', + '' => '衴', + '' => '衼', + '' => '訒', + '' => '豇', + '' => '豗', + '' => '豻', + '' => '貤', + '' => '貣', + '' => '赶', + '' => '赸', + '' => '趵', + '' => '趷', + '' => '趶', + '' => '軑', + '' => '軓', + '' => '迾', + '' => '迵', + '' => '适', + '' => '迿', + '' => '迻', + '' => '逄', + '' => '迼', + '' => '迶', + '' => '郖', + '' => '郠', + '' => '郙', + '' => '郚', + '' => '郣', + '' => '郟', + '' => '郥', + '' => '郘', + '' => '郛', + '' => '郗', + '' => '郜', + '' => '郤', + '' => '酐', + '@' => '酎', + 'A' => '酏', + 'B' => '釕', + 'C' => '釢', + 'D' => '釚', + 'E' => '陜', + 'F' => '陟', + 'G' => '隼', + 'H' => '飣', + 'I' => '髟', + 'J' => '鬯', + 'K' => '乿', + 'L' => '偰', + 'M' => '偪', + 'N' => '偡', + 'O' => '偞', + 'P' => '偠', + 'Q' => '偓', + 'R' => '偋', + 'S' => '偝', + 'T' => '偲', + 'U' => '偈', + 'V' => '偍', + 'W' => '偁', + 'X' => '偛', + 'Y' => '偊', + 'Z' => '偢', + '[' => '倕', + '\\' => '偅', + ']' => '偟', + '^' => '偩', + '_' => '偫', + '`' => '偣', + 'a' => '偤', + 'b' => '偆', + 'c' => '偀', + 'd' => '偮', + 'e' => '偳', + 'f' => '偗', + 'g' => '偑', + 'h' => '凐', + 'i' => '剫', + 'j' => '剭', + 'k' => '剬', + 'l' => '剮', + 'm' => '勖', + 'n' => '勓', + 'o' => '匭', + 'p' => '厜', + 'q' => '啵', + 'r' => '啶', + 's' => '唼', + 't' => '啍', + 'u' => '啐', + 'v' => '唴', + 'w' => '唪', + 'x' => '啑', + 'y' => '啢', + 'z' => '唶', + '{' => '唵', + '|' => '唰', + '}' => '啒', + '~' => '啅', + 'ԡ' => '唌', + 'Ԣ' => '唲', + 'ԣ' => '啥', + 'Ԥ' => '啎', + 'ԥ' => '唹', + 'Ԧ' => '啈', + 'ԧ' => '唭', + 'Ԩ' => '唻', + 'ԩ' => '啀', + 'Ԫ' => '啋', + 'ԫ' => '圊', + 'Ԭ' => '圇', + 'ԭ' => '埻', + 'Ԯ' => '堔', + 'ԯ' => '埢', + '԰' => '埶', + 'Ա' => '埜', + 'Բ' => '埴', + 'Գ' => '堀', + 'Դ' => '埭', + 'Ե' => '埽', + 'Զ' => '堈', + 'Է' => '埸', + 'Ը' => '堋', + 'Թ' => '埳', + 'Ժ' => '埏', + 'Ի' => '堇', + 'Լ' => '埮', + 'Խ' => '埣', + 'Ծ' => '埲', + 'Կ' => '埥', + '' => '埬', + '' => '埡', + '' => '堎', + '' => '埼', + '' => '堐', + '' => '埧', + '' => '堁', + '' => '堌', + '' => '埱', + '' => '埩', + '' => '埰', + '' => '堍', + '' => '堄', + '' => '奜', + '' => '婠', + '' => '婘', + '' => '婕', + '' => '婧', + '' => '婞', + '' => '娸', + '' => '娵', + '' => '婭', + '' => '婐', + '' => '婟', + '' => '婥', + '' => '婬', + '' => '婓', + '' => '婤', + '' => '婗', + '' => '婃', + '' => '婝', + '' => '婒', + '' => '婄', + '' => '婛', + '' => '婈', + '' => '媎', + '' => '娾', + '' => '婍', + '' => '娹', + '' => '婌', + '' => '婰', + '' => '婩', + '' => '婇', + '' => '婑', + '' => '婖', + '' => '婂', + '' => '婜', + '' => '孲', + '' => '孮', + '' => '寁', + '' => '寀', + '' => '屙', + '' => '崞', + '' => '崋', + '' => '崝', + '' => '崚', + '' => '崠', + '' => '崌', + '' => '崨', + '' => '崍', + '' => '崦', + '' => '崥', + '' => '崏', + '@' => '崰', + 'A' => '崒', + 'B' => '崣', + 'C' => '崟', + 'D' => '崮', + 'E' => '帾', + 'F' => '帴', + 'G' => '庱', + 'H' => '庴', + 'I' => '庹', + 'J' => '庲', + 'K' => '庳', + 'L' => '弶', + 'M' => '弸', + 'N' => '徛', + 'O' => '徖', + 'P' => '徟', + 'Q' => '悊', + 'R' => '悐', + 'S' => '悆', + 'T' => '悾', + 'U' => '悰', + 'V' => '悺', + 'W' => '惓', + 'X' => '惔', + 'Y' => '惏', + 'Z' => '惤', + '[' => '惙', + '\\' => '惝', + ']' => '惈', + '^' => '悱', + '_' => '惛', + '`' => '悷', + 'a' => '惊', + 'b' => '悿', + 'c' => '惃', + 'd' => '惍', + 'e' => '惀', + 'f' => '挲', + 'g' => '捥', + 'h' => '掊', + 'i' => '掂', + 'j' => '捽', + 'k' => '掽', + 'l' => '掞', + 'm' => '掭', + 'n' => '掝', + 'o' => '掗', + 'p' => '掫', + 'q' => '掎', + 'r' => '捯', + 's' => '掇', + 't' => '掐', + 'u' => '据', + 'v' => '掯', + 'w' => '捵', + 'x' => '掜', + 'y' => '捭', + 'z' => '掮', + '{' => '捼', + '|' => '掤', + '}' => '挻', + '~' => '掟', + 'ա' => '捸', + 'բ' => '掅', + 'գ' => '掁', + 'դ' => '掑', + 'ե' => '掍', + 'զ' => '捰', + 'է' => '敓', + 'ը' => '旍', + 'թ' => '晥', + 'ժ' => '晡', + 'ի' => '晛', + 'լ' => '晙', + 'խ' => '晜', + 'ծ' => '晢', + 'կ' => '朘', + 'հ' => '桹', + 'ձ' => '梇', + 'ղ' => '梐', + 'ճ' => '梜', + 'մ' => '桭', + 'յ' => '桮', + 'ն' => '梮', + 'շ' => '梫', + 'ո' => '楖', + 'չ' => '桯', + 'պ' => '梣', + 'ջ' => '梬', + 'ռ' => '梩', + 'ս' => '桵', + 'վ' => '桴', + 'տ' => '梲', + '' => '梏', + '' => '桷', + '' => '梒', + '' => '桼', + '' => '桫', + '' => '桲', + '' => '梪', + '' => '梀', + '' => '桱', + '' => '桾', + '' => '梛', + '' => '梖', + '' => '梋', + '' => '梠', + '' => '梉', + '' => '梤', + '' => '桸', + '' => '桻', + '' => '梑', + '' => '梌', + '' => '梊', + '' => '桽', + '' => '欶', + '' => '欳', + '' => '欷', + '' => '欸', + '' => '殑', + '' => '殏', + '' => '殍', + '' => '殎', + '' => '殌', + '' => '氪', + '' => '淀', + '' => '涫', + '' => '涴', + '' => '涳', + '' => '湴', + '' => '涬', + '' => '淩', + '' => '淢', + '' => '涷', + '' => '淶', + '' => '淔', + '' => '渀', + '' => '淈', + '' => '淠', + '' => '淟', + '' => '淖', + '' => '涾', + '' => '淥', + '' => '淜', + '' => '淝', + '' => '淛', + '' => '淴', + '' => '淊', + '' => '涽', + '' => '淭', + '' => '淰', + '' => '涺', + '' => '淕', + '' => '淂', + '' => '淏', + '' => '淉', + '@' => '淐', + 'A' => '淲', + 'B' => '淓', + 'C' => '淽', + 'D' => '淗', + 'E' => '淍', + 'F' => '淣', + 'G' => '涻', + 'H' => '烺', + 'I' => '焍', + 'J' => '烷', + 'K' => '焗', + 'L' => '烴', + 'M' => '焌', + 'N' => '烰', + 'O' => '焄', + 'P' => '烳', + 'Q' => '焐', + 'R' => '烼', + 'S' => '烿', + 'T' => '焆', + 'U' => '焓', + 'V' => '焀', + 'W' => '烸', + 'X' => '烶', + 'Y' => '焋', + 'Z' => '焂', + '[' => '焎', + '\\' => '牾', + ']' => '牻', + '^' => '牼', + '_' => '牿', + '`' => '猝', + 'a' => '猗', + 'b' => '猇', + 'c' => '猑', + 'd' => '猘', + 'e' => '猊', + 'f' => '猈', + 'g' => '狿', + 'h' => '猏', + 'i' => '猞', + 'j' => '玈', + 'k' => '珶', + 'l' => '珸', + 'm' => '珵', + 'n' => '琄', + 'o' => '琁', + 'p' => '珽', + 'q' => '琇', + 'r' => '琀', + 's' => '珺', + 't' => '珼', + 'u' => '珿', + 'v' => '琌', + 'w' => '琋', + 'x' => '珴', + 'y' => '琈', + 'z' => '畤', + '{' => '畣', + '|' => '痎', + '}' => '痒', + '~' => '痏', + '֡' => '痋', + '֢' => '痌', + '֣' => '痑', + '֤' => '痐', + '֥' => '皏', + '֦' => '皉', + '֧' => '盓', + '֨' => '眹', + '֩' => '眯', + '֪' => '眭', + '֫' => '眱', + '֬' => '眲', + '֭' => '眴', + '֮' => '眳', + '֯' => '眽', + 'ְ' => '眥', + 'ֱ' => '眻', + 'ֲ' => '眵', + 'ֳ' => '硈', + 'ִ' => '硒', + 'ֵ' => '硉', + 'ֶ' => '硍', + 'ַ' => '硊', + 'ָ' => '硌', + 'ֹ' => '砦', + 'ֺ' => '硅', + 'ֻ' => '硐', + 'ּ' => '祤', + 'ֽ' => '祧', + '־' => '祩', + 'ֿ' => '祪', + '' => '祣', + '' => '祫', + '' => '祡', + '' => '离', + '' => '秺', + '' => '秸', + '' => '秶', + '' => '秷', + '' => '窏', + '' => '窔', + '' => '窐', + '' => '笵', + '' => '筇', + '' => '笴', + '' => '笥', + '' => '笰', + '' => '笢', + '' => '笤', + '' => '笳', + '' => '笘', + '' => '笪', + '' => '笝', + '' => '笱', + '' => '笫', + '' => '笭', + '' => '笯', + '' => '笲', + '' => '笸', + '' => '笚', + '' => '笣', + '' => '粔', + '' => '粘', + '' => '粖', + '' => '粣', + '' => '紵', + '' => '紽', + '' => '紸', + '' => '紶', + '' => '紺', + '' => '絅', + '' => '紬', + '' => '紩', + '' => '絁', + '' => '絇', + '' => '紾', + '' => '紿', + '' => '絊', + '' => '紻', + '' => '紨', + '' => '罣', + '' => '羕', + '' => '羜', + '' => '羝', + '' => '羛', + '' => '翊', + '' => '翋', + '' => '翍', + '' => '翐', + '' => '翑', + '' => '翇', + '' => '翏', + '' => '翉', + '' => '耟', + '@' => '耞', + 'A' => '耛', + 'B' => '聇', + 'C' => '聃', + 'D' => '聈', + 'E' => '脘', + 'F' => '脥', + 'G' => '脙', + 'H' => '脛', + 'I' => '脭', + 'J' => '脟', + 'K' => '脬', + 'L' => '脞', + 'M' => '脡', + 'N' => '脕', + 'O' => '脧', + 'P' => '脝', + 'Q' => '脢', + 'R' => '舑', + 'S' => '舸', + 'T' => '舳', + 'U' => '舺', + 'V' => '舴', + 'W' => '舲', + 'X' => '艴', + 'Y' => '莐', + 'Z' => '莣', + '[' => '莨', + '\\' => '莍', + ']' => '荺', + '^' => '荳', + '_' => '莤', + '`' => '荴', + 'a' => '莏', + 'b' => '莁', + 'c' => '莕', + 'd' => '莙', + 'e' => '荵', + 'f' => '莔', + 'g' => '莩', + 'h' => '荽', + 'i' => '莃', + 'j' => '莌', + 'k' => '莝', + 'l' => '莛', + 'm' => '莪', + 'n' => '莋', + 'o' => '荾', + 'p' => '莥', + 'q' => '莯', + 'r' => '莈', + 's' => '莗', + 't' => '莰', + 'u' => '荿', + 'v' => '莦', + 'w' => '莇', + 'x' => '莮', + 'y' => '荶', + 'z' => '莚', + '{' => '虙', + '|' => '虖', + '}' => '蚿', + '~' => '蚷', + 'ס' => '蛂', + 'ע' => '蛁', + 'ף' => '蛅', + 'פ' => '蚺', + 'ץ' => '蚰', + 'צ' => '蛈', + 'ק' => '蚹', + 'ר' => '蚳', + 'ש' => '蚸', + 'ת' => '蛌', + '׫' => '蚴', + '׬' => '蚻', + '׭' => '蚼', + '׮' => '蛃', + 'ׯ' => '蚽', + 'װ' => '蚾', + 'ױ' => '衒', + 'ײ' => '袉', + '׳' => '袕', + '״' => '袨', + '׵' => '袢', + '׶' => '袪', + '׷' => '袚', + '׸' => '袑', + '׹' => '袡', + '׺' => '袟', + '׻' => '袘', + '׼' => '袧', + '׽' => '袙', + '׾' => '袛', + '׿' => '袗', + '' => '袤', + '' => '袬', + '' => '袌', + '' => '袓', + '' => '袎', + '' => '覂', + '' => '觖', + '' => '觙', + '' => '觕', + '' => '訰', + '' => '訧', + '' => '訬', + '' => '訞', + '' => '谹', + '' => '谻', + '' => '豜', + '' => '豝', + '' => '豽', + '' => '貥', + '' => '赽', + '' => '赻', + '' => '赹', + '' => '趼', + '' => '跂', + '' => '趹', + '' => '趿', + '' => '跁', + '' => '軘', + '' => '軞', + '' => '軝', + '' => '軜', + '' => '軗', + '' => '軠', + '' => '軡', + '' => '逤', + '' => '逋', + '' => '逑', + '' => '逜', + '' => '逌', + '' => '逡', + '' => '郯', + '' => '郪', + '' => '郰', + '' => '郴', + '' => '郲', + '' => '郳', + '' => '郔', + '' => '郫', + '' => '郬', + '' => '郩', + '' => '酖', + '' => '酘', + '' => '酚', + '' => '酓', + '' => '酕', + '' => '釬', + '' => '釴', + '' => '釱', + '' => '釳', + '' => '釸', + '' => '釤', + '' => '釹', + '' => '釪', + '@' => '釫', + 'A' => '釷', + 'B' => '釨', + 'C' => '釮', + 'D' => '镺', + 'E' => '閆', + 'F' => '閈', + 'G' => '陼', + 'H' => '陭', + 'I' => '陫', + 'J' => '陱', + 'K' => '陯', + 'L' => '隿', + 'M' => '靪', + 'N' => '頄', + 'O' => '飥', + 'P' => '馗', + 'Q' => '傛', + 'R' => '傕', + 'S' => '傔', + 'T' => '傞', + 'U' => '傋', + 'V' => '傣', + 'W' => '傃', + 'X' => '傌', + 'Y' => '傎', + 'Z' => '傝', + '[' => '偨', + '\\' => '傜', + ']' => '傒', + '^' => '傂', + '_' => '傇', + '`' => '兟', + 'a' => '凔', + 'b' => '匒', + 'c' => '匑', + 'd' => '厤', + 'e' => '厧', + 'f' => '喑', + 'g' => '喨', + 'h' => '喥', + 'i' => '喭', + 'j' => '啷', + 'k' => '噅', + 'l' => '喢', + 'm' => '喓', + 'n' => '喈', + 'o' => '喏', + 'p' => '喵', + 'q' => '喁', + 'r' => '喣', + 's' => '喒', + 't' => '喤', + 'u' => '啽', + 'v' => '喌', + 'w' => '喦', + 'x' => '啿', + 'y' => '喕', + 'z' => '喡', + '{' => '喎', + '|' => '圌', + '}' => '堩', + '~' => '堷', + 'ء' => '堙', + 'آ' => '堞', + 'أ' => '堧', + 'ؤ' => '堣', + 'إ' => '堨', + 'ئ' => '埵', + 'ا' => '塈', + 'ب' => '堥', + 'ة' => '堜', + 'ت' => '堛', + 'ث' => '堳', + 'ج' => '堿', + 'ح' => '堶', + 'خ' => '堮', + 'د' => '堹', + 'ذ' => '堸', + 'ر' => '堭', + 'ز' => '堬', + 'س' => '堻', + 'ش' => '奡', + 'ص' => '媯', + 'ض' => '媔', + 'ط' => '媟', + 'ظ' => '婺', + 'ع' => '媢', + 'غ' => '媞', + 'ػ' => '婸', + 'ؼ' => '媦', + 'ؽ' => '婼', + 'ؾ' => '媥', + 'ؿ' => '媬', + '' => '媕', + '' => '媮', + '' => '娷', + '' => '媄', + '' => '媊', + '' => '媗', + '' => '媃', + '' => '媋', + '' => '媩', + '' => '婻', + '' => '婽', + '' => '媌', + '' => '媜', + '' => '媏', + '' => '媓', + '' => '媝', + '' => '寪', + '' => '寍', + '' => '寋', + '' => '寔', + '' => '寑', + '' => '寊', + '' => '寎', + '' => '尌', + '' => '尰', + '' => '崷', + '' => '嵃', + '' => '嵫', + '' => '嵁', + '' => '嵋', + '' => '崿', + '' => '崵', + '' => '嵑', + '' => '嵎', + '' => '嵕', + '' => '崳', + '' => '崺', + '' => '嵒', + '' => '崽', + '' => '崱', + '' => '嵙', + '' => '嵂', + '' => '崹', + '' => '嵉', + '' => '崸', + '' => '崼', + '' => '崲', + '' => '崶', + '' => '嵀', + '' => '嵅', + '' => '幄', + '' => '幁', + '' => '彘', + '' => '徦', + '' => '徥', + '' => '徫', + '' => '惉', + '' => '悹', + '' => '惌', + '' => '惢', + '' => '惎', + '' => '惄', + '' => '愔', + '@' => '惲', + 'A' => '愊', + 'B' => '愖', + 'C' => '愅', + 'D' => '惵', + 'E' => '愓', + 'F' => '惸', + 'G' => '惼', + 'H' => '惾', + 'I' => '惁', + 'J' => '愃', + 'K' => '愘', + 'L' => '愝', + 'M' => '愐', + 'N' => '惿', + 'O' => '愄', + 'P' => '愋', + 'Q' => '扊', + 'R' => '掔', + 'S' => '掱', + 'T' => '掰', + 'U' => '揎', + 'V' => '揥', + 'W' => '揨', + 'X' => '揯', + 'Y' => '揃', + 'Z' => '撝', + '[' => '揳', + '\\' => '揊', + ']' => '揠', + '^' => '揶', + '_' => '揕', + '`' => '揲', + 'a' => '揵', + 'b' => '摡', + 'c' => '揟', + 'd' => '掾', + 'e' => '揝', + 'f' => '揜', + 'g' => '揄', + 'h' => '揘', + 'i' => '揓', + 'j' => '揂', + 'k' => '揇', + 'l' => '揌', + 'm' => '揋', + 'n' => '揈', + 'o' => '揰', + 'p' => '揗', + 'q' => '揙', + 'r' => '攲', + 's' => '敧', + 't' => '敪', + 'u' => '敤', + 'v' => '敜', + 'w' => '敨', + 'x' => '敥', + 'y' => '斌', + 'z' => '斝', + '{' => '斞', + '|' => '斮', + '}' => '旐', + '~' => '旒', + '١' => '晼', + '٢' => '晬', + '٣' => '晻', + '٤' => '暀', + '٥' => '晱', + '٦' => '晹', + '٧' => '晪', + '٨' => '晲', + '٩' => '朁', + '٪' => '椌', + '٫' => '棓', + '٬' => '椄', + '٭' => '棜', + 'ٮ' => '椪', + 'ٯ' => '棬', + 'ٰ' => '棪', + 'ٱ' => '棱', + 'ٲ' => '椏', + 'ٳ' => '棖', + 'ٴ' => '棷', + 'ٵ' => '棫', + 'ٶ' => '棤', + 'ٷ' => '棶', + 'ٸ' => '椓', + 'ٹ' => '椐', + 'ٺ' => '棳', + 'ٻ' => '棡', + 'ټ' => '椇', + 'ٽ' => '棌', + 'پ' => '椈', + 'ٿ' => '楰', + '' => '梴', + '' => '椑', + '' => '棯', + '' => '棆', + '' => '椔', + '' => '棸', + '' => '棐', + '' => '棽', + '' => '棼', + '' => '棨', + '' => '椋', + '' => '椊', + '' => '椗', + '' => '棎', + '' => '棈', + '' => '棝', + '' => '棞', + '' => '棦', + '' => '棴', + '' => '棑', + '' => '椆', + '' => '棔', + '' => '棩', + '' => '椕', + '' => '椥', + '' => '棇', + '' => '欹', + '' => '欻', + '' => '欿', + '' => '欼', + '' => '殔', + '' => '殗', + '' => '殙', + '' => '殕', + '' => '殽', + '' => '毰', + '' => '毲', + '' => '毳', + '' => '氰', + '' => '淼', + '' => '湆', + '' => '湇', + '' => '渟', + '' => '湉', + '' => '溈', + '' => '渼', + '' => '渽', + '' => '湅', + '' => '湢', + '' => '渫', + '' => '渿', + '' => '湁', + '' => '湝', + '' => '湳', + '' => '渜', + '' => '渳', + '' => '湋', + '' => '湀', + '' => '湑', + '' => '渻', + '' => '渃', + '' => '渮', + '' => '湞', + '@' => '湨', + 'A' => '湜', + 'B' => '湡', + 'C' => '渱', + 'D' => '渨', + 'E' => '湠', + 'F' => '湱', + 'G' => '湫', + 'H' => '渹', + 'I' => '渢', + 'J' => '渰', + 'K' => '湓', + 'L' => '湥', + 'M' => '渧', + 'N' => '湸', + 'O' => '湤', + 'P' => '湷', + 'Q' => '湕', + 'R' => '湹', + 'S' => '湒', + 'T' => '湦', + 'U' => '渵', + 'V' => '渶', + 'W' => '湚', + 'X' => '焠', + 'Y' => '焞', + 'Z' => '焯', + '[' => '烻', + '\\' => '焮', + ']' => '焱', + '^' => '焣', + '_' => '焥', + '`' => '焢', + 'a' => '焲', + 'b' => '焟', + 'c' => '焨', + 'd' => '焺', + 'e' => '焛', + 'f' => '牋', + 'g' => '牚', + 'h' => '犈', + 'i' => '犉', + 'j' => '犆', + 'k' => '犅', + 'l' => '犋', + 'm' => '猒', + 'n' => '猋', + 'o' => '猰', + 'p' => '猢', + 'q' => '猱', + 'r' => '猳', + 's' => '猧', + 't' => '猲', + 'u' => '猭', + 'v' => '猦', + 'w' => '猣', + 'x' => '猵', + 'y' => '猌', + 'z' => '琮', + '{' => '琬', + '|' => '琰', + '}' => '琫', + '~' => '琖', + 'ڡ' => '琚', + 'ڢ' => '琡', + 'ڣ' => '琭', + 'ڤ' => '琱', + 'ڥ' => '琤', + 'ڦ' => '琣', + 'ڧ' => '琝', + 'ڨ' => '琩', + 'ک' => '琠', + 'ڪ' => '琲', + 'ګ' => '瓻', + 'ڬ' => '甯', + 'ڭ' => '畯', + 'ڮ' => '畬', + 'گ' => '痧', + 'ڰ' => '痚', + 'ڱ' => '痡', + 'ڲ' => '痦', + 'ڳ' => '痝', + 'ڴ' => '痟', + 'ڵ' => '痤', + 'ڶ' => '痗', + 'ڷ' => '皕', + 'ڸ' => '皒', + 'ڹ' => '盚', + 'ں' => '睆', + 'ڻ' => '睇', + 'ڼ' => '睄', + 'ڽ' => '睍', + 'ھ' => '睅', + 'ڿ' => '睊', + '' => '睎', + '' => '睋', + '' => '睌', + '' => '矞', + '' => '矬', + '' => '硠', + '' => '硤', + '' => '硥', + '' => '硜', + '' => '硭', + '' => '硱', + '' => '硪', + '' => '确', + '' => '硰', + '' => '硩', + '' => '硨', + '' => '硞', + '' => '硢', + '' => '祴', + '' => '祳', + '' => '祲', + '' => '祰', + '' => '稂', + '' => '稊', + '' => '稃', + '' => '稌', + '' => '稄', + '' => '窙', + '' => '竦', + '' => '竤', + '' => '筊', + '' => '笻', + '' => '筄', + '' => '筈', + '' => '筌', + '' => '筎', + '' => '筀', + '' => '筘', + '' => '筅', + '' => '粢', + '' => '粞', + '' => '粨', + '' => '粡', + '' => '絘', + '' => '絯', + '' => '絣', + '' => '絓', + '' => '絖', + '' => '絧', + '' => '絪', + '' => '絏', + '' => '絭', + '' => '絜', + '' => '絫', + '' => '絒', + '' => '絔', + '' => '絩', + '' => '絑', + '' => '絟', + '' => '絎', + '' => '缾', + '' => '缿', + '' => '罥', + '@' => '罦', + 'A' => '羢', + 'B' => '羠', + 'C' => '羡', + 'D' => '翗', + 'E' => '聑', + 'F' => '聏', + 'G' => '聐', + 'H' => '胾', + 'I' => '胔', + 'J' => '腃', + 'K' => '腊', + 'L' => '腒', + 'M' => '腏', + 'N' => '腇', + 'O' => '脽', + 'P' => '腍', + 'Q' => '脺', + 'R' => '臦', + 'S' => '臮', + 'T' => '臷', + 'U' => '臸', + 'V' => '臹', + 'W' => '舄', + 'X' => '舼', + 'Y' => '舽', + 'Z' => '舿', + '[' => '艵', + '\\' => '茻', + ']' => '菏', + '^' => '菹', + '_' => '萣', + '`' => '菀', + 'a' => '菨', + 'b' => '萒', + 'c' => '菧', + 'd' => '菤', + 'e' => '菼', + 'f' => '菶', + 'g' => '萐', + 'h' => '菆', + 'i' => '菈', + 'j' => '菫', + 'k' => '菣', + 'l' => '莿', + 'm' => '萁', + 'n' => '菝', + 'o' => '菥', + 'p' => '菘', + 'q' => '菿', + 'r' => '菡', + 's' => '菋', + 't' => '菎', + 'u' => '菖', + 'v' => '菵', + 'w' => '菉', + 'x' => '萉', + 'y' => '萏', + 'z' => '菞', + '{' => '萑', + '|' => '萆', + '}' => '菂', + '~' => '菳', + 'ۡ' => '菕', + 'ۢ' => '菺', + 'ۣ' => '菇', + 'ۤ' => '菑', + 'ۥ' => '菪', + 'ۦ' => '萓', + 'ۧ' => '菃', + 'ۨ' => '菬', + '۩' => '菮', + '۪' => '菄', + '۫' => '菻', + '۬' => '菗', + 'ۭ' => '菢', + 'ۮ' => '萛', + 'ۯ' => '菛', + '۰' => '菾', + '۱' => '蛘', + '۲' => '蛢', + '۳' => '蛦', + '۴' => '蛓', + '۵' => '蛣', + '۶' => '蛚', + '۷' => '蛪', + '۸' => '蛝', + '۹' => '蛫', + 'ۺ' => '蛜', + 'ۻ' => '蛬', + 'ۼ' => '蛩', + '۽' => '蛗', + '۾' => '蛨', + 'ۿ' => '蛑', + '' => '衈', + '' => '衖', + '' => '衕', + '' => '袺', + '' => '裗', + '' => '袹', + '' => '袸', + '' => '裀', + '' => '袾', + '' => '袶', + '' => '袼', + '' => '袷', + '' => '袽', + '' => '袲', + '' => '褁', + '' => '裉', + '' => '覕', + '' => '覘', + '' => '覗', + '' => '觝', + '' => '觚', + '' => '觛', + '' => '詎', + '' => '詍', + '' => '訹', + '' => '詙', + '' => '詀', + '' => '詗', + '' => '詘', + '' => '詄', + '' => '詅', + '' => '詒', + '' => '詈', + '' => '詑', + '' => '詊', + '' => '詌', + '' => '詏', + '' => '豟', + '' => '貁', + '' => '貀', + '' => '貺', + '' => '貾', + '' => '貰', + '' => '貹', + '' => '貵', + '' => '趄', + '' => '趀', + '' => '趉', + '' => '跘', + '' => '跓', + '' => '跍', + '' => '跇', + '' => '跖', + '' => '跜', + '' => '跏', + '' => '跕', + '' => '跙', + '' => '跈', + '' => '跗', + '' => '跅', + '' => '軯', + '' => '軷', + '' => '軺', + '@' => '軹', + 'A' => '軦', + 'B' => '軮', + 'C' => '軥', + 'D' => '軵', + 'E' => '軧', + 'F' => '軨', + 'G' => '軶', + 'H' => '軫', + 'I' => '軱', + 'J' => '軬', + 'K' => '軴', + 'L' => '軩', + 'M' => '逭', + 'N' => '逴', + 'O' => '逯', + 'P' => '鄆', + 'Q' => '鄬', + 'R' => '鄄', + 'S' => '郿', + 'T' => '郼', + 'U' => '鄈', + 'V' => '郹', + 'W' => '郻', + 'X' => '鄁', + 'Y' => '鄀', + 'Z' => '鄇', + '[' => '鄅', + '\\' => '鄃', + ']' => '酡', + '^' => '酤', + '_' => '酟', + '`' => '酢', + 'a' => '酠', + 'b' => '鈁', + 'c' => '鈊', + 'd' => '鈥', + 'e' => '鈃', + 'f' => '鈚', + 'g' => '鈦', + 'h' => '鈏', + 'i' => '鈌', + 'j' => '鈀', + 'k' => '鈒', + 'l' => '釿', + 'm' => '釽', + 'n' => '鈆', + 'o' => '鈄', + 'p' => '鈧', + 'q' => '鈂', + 'r' => '鈜', + 's' => '鈤', + 't' => '鈙', + 'u' => '鈗', + 'v' => '鈅', + 'w' => '鈖', + 'x' => '镻', + 'y' => '閍', + 'z' => '閌', + '{' => '閐', + '|' => '隇', + '}' => '陾', + '~' => '隈', + 'ܡ' => '隉', + 'ܢ' => '隃', + 'ܣ' => '隀', + 'ܤ' => '雂', + 'ܥ' => '雈', + 'ܦ' => '雃', + 'ܧ' => '雱', + 'ܨ' => '雰', + 'ܩ' => '靬', + 'ܪ' => '靰', + 'ܫ' => '靮', + 'ܬ' => '頇', + 'ܭ' => '颩', + 'ܮ' => '飫', + 'ܯ' => '鳦', + 'ܰ' => '黹', + 'ܱ' => '亃', + 'ܲ' => '亄', + 'ܳ' => '亶', + 'ܴ' => '傽', + 'ܵ' => '傿', + 'ܶ' => '僆', + 'ܷ' => '傮', + 'ܸ' => '僄', + 'ܹ' => '僊', + 'ܺ' => '傴', + 'ܻ' => '僈', + 'ܼ' => '僂', + 'ܽ' => '傰', + 'ܾ' => '僁', + 'ܿ' => '傺', + '' => '傱', + '' => '僋', + '' => '僉', + '' => '傶', + '' => '傸', + '' => '凗', + '' => '剺', + '' => '剸', + '' => '剻', + '' => '剼', + '' => '嗃', + '' => '嗛', + '' => '嗌', + '' => '嗐', + '' => '嗋', + '' => '嗊', + '' => '嗝', + '' => '嗀', + '' => '嗔', + '' => '嗄', + '' => '嗩', + '' => '喿', + '' => '嗒', + '' => '喍', + '' => '嗏', + '' => '嗕', + '' => '嗢', + '' => '嗖', + '' => '嗈', + '' => '嗲', + '' => '嗍', + '' => '嗙', + '' => '嗂', + '' => '圔', + '' => '塓', + '' => '塨', + '' => '塤', + '' => '塏', + '' => '塍', + '' => '塉', + '' => '塯', + '' => '塕', + '' => '塎', + '' => '塝', + '' => '塙', + '' => '塥', + '' => '塛', + '' => '堽', + '' => '塣', + '' => '塱', + '' => '壼', + '' => '嫇', + '' => '嫄', + '' => '嫋', + '' => '媺', + '' => '媸', + '' => '媱', + '' => '媵', + '' => '媰', + '' => '媿', + '' => '嫈', + '' => '媻', + '' => '嫆', + '@' => '媷', + 'A' => '嫀', + 'B' => '嫊', + 'C' => '媴', + 'D' => '媶', + 'E' => '嫍', + 'F' => '媹', + 'G' => '媐', + 'H' => '寖', + 'I' => '寘', + 'J' => '寙', + 'K' => '尟', + 'L' => '尳', + 'M' => '嵱', + 'N' => '嵣', + 'O' => '嵊', + 'P' => '嵥', + 'Q' => '嵲', + 'R' => '嵬', + 'S' => '嵞', + 'T' => '嵨', + 'U' => '嵧', + 'V' => '嵢', + 'W' => '巰', + 'X' => '幏', + 'Y' => '幎', + 'Z' => '幊', + '[' => '幍', + '\\' => '幋', + ']' => '廅', + '^' => '廌', + '_' => '廆', + '`' => '廋', + 'a' => '廇', + 'b' => '彀', + 'c' => '徯', + 'd' => '徭', + 'e' => '惷', + 'f' => '慉', + 'g' => '慊', + 'h' => '愫', + 'i' => '慅', + 'j' => '愶', + 'k' => '愲', + 'l' => '愮', + 'm' => '慆', + 'n' => '愯', + 'o' => '慏', + 'p' => '愩', + 'q' => '慀', + 'r' => '戠', + 's' => '酨', + 't' => '戣', + 'u' => '戥', + 'v' => '戤', + 'w' => '揅', + 'x' => '揱', + 'y' => '揫', + 'z' => '搐', + '{' => '搒', + '|' => '搉', + '}' => '搠', + '~' => '搤', + 'ݡ' => '搳', + 'ݢ' => '摃', + 'ݣ' => '搟', + 'ݤ' => '搕', + 'ݥ' => '搘', + 'ݦ' => '搹', + 'ݧ' => '搷', + 'ݨ' => '搢', + 'ݩ' => '搣', + 'ݪ' => '搌', + 'ݫ' => '搦', + 'ݬ' => '搰', + 'ݭ' => '搨', + 'ݮ' => '摁', + 'ݯ' => '搵', + 'ݰ' => '搯', + 'ݱ' => '搊', + 'ݲ' => '搚', + 'ݳ' => '摀', + 'ݴ' => '搥', + 'ݵ' => '搧', + 'ݶ' => '搋', + 'ݷ' => '揧', + 'ݸ' => '搛', + 'ݹ' => '搮', + 'ݺ' => '搡', + 'ݻ' => '搎', + 'ݼ' => '敯', + 'ݽ' => '斒', + 'ݾ' => '旓', + 'ݿ' => '暆', + '' => '暌', + '' => '暕', + '' => '暐', + '' => '暋', + '' => '暊', + '' => '暙', + '' => '暔', + '' => '晸', + '' => '朠', + '' => '楦', + '' => '楟', + '' => '椸', + '' => '楎', + '' => '楢', + '' => '楱', + '' => '椿', + '' => '楅', + '' => '楪', + '' => '椹', + '' => '楂', + '' => '楗', + '' => '楙', + '' => '楺', + '' => '楈', + '' => '楉', + '' => '椵', + '' => '楬', + '' => '椳', + '' => '椽', + '' => '楥', + '' => '棰', + '' => '楸', + '' => '椴', + '' => '楩', + '' => '楀', + '' => '楯', + '' => '楄', + '' => '楶', + '' => '楘', + '' => '楁', + '' => '楴', + '' => '楌', + '' => '椻', + '' => '楋', + '' => '椷', + '' => '楜', + '' => '楏', + '' => '楑', + '' => '椲', + '' => '楒', + '' => '椯', + '' => '楻', + '' => '椼', + '' => '歆', + '' => '歅', + '' => '歃', + '' => '歂', + '' => '歈', + '' => '歁', + '' => '殛', + '' => '嗀', + '' => '毻', + '' => '毼', + '@' => '毹', + 'A' => '毷', + 'B' => '毸', + 'C' => '溛', + 'D' => '滖', + 'E' => '滈', + 'F' => '溏', + 'G' => '滀', + 'H' => '溟', + 'I' => '溓', + 'J' => '溔', + 'K' => '溠', + 'L' => '溱', + 'M' => '溹', + 'N' => '滆', + 'O' => '滒', + 'P' => '溽', + 'Q' => '滁', + 'R' => '溞', + 'S' => '滉', + 'T' => '溷', + 'U' => '溰', + 'V' => '滍', + 'W' => '溦', + 'X' => '滏', + 'Y' => '溲', + 'Z' => '溾', + '[' => '滃', + '\\' => '滜', + ']' => '滘', + '^' => '溙', + '_' => '溒', + '`' => '溎', + 'a' => '溍', + 'b' => '溤', + 'c' => '溡', + 'd' => '溿', + 'e' => '溳', + 'f' => '滐', + 'g' => '滊', + 'h' => '溗', + 'i' => '溮', + 'j' => '溣', + 'k' => '煇', + 'l' => '煔', + 'm' => '煒', + 'n' => '煣', + 'o' => '煠', + 'p' => '煁', + 'q' => '煝', + 'r' => '煢', + 's' => '煲', + 't' => '煸', + 'u' => '煪', + 'v' => '煡', + 'w' => '煂', + 'x' => '煘', + 'y' => '煃', + 'z' => '煋', + '{' => '煰', + '|' => '煟', + '}' => '煐', + '~' => '煓', + 'ޡ' => '煄', + 'ޢ' => '煍', + 'ޣ' => '煚', + 'ޤ' => '牏', + 'ޥ' => '犍', + 'ަ' => '犌', + 'ާ' => '犑', + 'ި' => '犐', + 'ީ' => '犎', + 'ު' => '猼', + 'ޫ' => '獂', + 'ެ' => '猻', + 'ޭ' => '猺', + 'ޮ' => '獀', + 'ޯ' => '獊', + 'ް' => '獉', + 'ޱ' => '瑄', + '޲' => '瑊', + '޳' => '瑋', + '޴' => '瑒', + '޵' => '瑑', + '޶' => '瑗', + '޷' => '瑀', + '޸' => '瑏', + '޹' => '瑐', + '޺' => '瑎', + '޻' => '瑂', + '޼' => '瑆', + '޽' => '瑍', + '޾' => '瑔', + '޿' => '瓡', + '' => '瓿', + '' => '瓾', + '' => '瓽', + '' => '甝', + '' => '畹', + '' => '畷', + '' => '榃', + '' => '痯', + '' => '瘏', + '' => '瘃', + '' => '痷', + '' => '痾', + '' => '痼', + '' => '痹', + '' => '痸', + '' => '瘐', + '' => '痻', + '' => '痶', + '' => '痭', + '' => '痵', + '' => '痽', + '' => '皙', + '' => '皵', + '' => '盝', + '' => '睕', + '' => '睟', + '' => '睠', + '' => '睒', + '' => '睖', + '' => '睚', + '' => '睩', + '' => '睧', + '' => '睔', + '' => '睙', + '' => '睭', + '' => '矠', + '' => '碇', + '' => '碚', + '' => '碔', + '' => '碏', + '' => '碄', + '' => '碕', + '' => '碅', + '' => '碆', + '' => '碡', + '' => '碃', + '' => '硹', + '' => '碙', + '' => '碀', + '' => '碖', + '' => '硻', + '' => '祼', + '' => '禂', + '' => '祽', + '' => '祹', + '' => '稑', + '' => '稘', + '' => '稙', + '' => '稒', + '' => '稗', + '' => '稕', + '' => '稢', + '' => '稓', + '@' => '稛', + 'A' => '稐', + 'B' => '窣', + 'C' => '窢', + 'D' => '窞', + 'E' => '竫', + 'F' => '筦', + 'G' => '筤', + 'H' => '筭', + 'I' => '筴', + 'J' => '筩', + 'K' => '筲', + 'L' => '筥', + 'M' => '筳', + 'N' => '筱', + 'O' => '筰', + 'P' => '筡', + 'Q' => '筸', + 'R' => '筶', + 'S' => '筣', + 'T' => '粲', + 'U' => '粴', + 'V' => '粯', + 'W' => '綈', + 'X' => '綆', + 'Y' => '綀', + 'Z' => '綍', + '[' => '絿', + '\\' => '綅', + ']' => '絺', + '^' => '綎', + '_' => '絻', + '`' => '綃', + 'a' => '絼', + 'b' => '綌', + 'c' => '綔', + 'd' => '綄', + 'e' => '絽', + 'f' => '綒', + 'g' => '罭', + 'h' => '罫', + 'i' => '罧', + 'j' => '罨', + 'k' => '罬', + 'l' => '羦', + 'm' => '羥', + 'n' => '羧', + 'o' => '翛', + 'p' => '翜', + 'q' => '耡', + 'r' => '腤', + 's' => '腠', + 't' => '腷', + 'u' => '腜', + 'v' => '腩', + 'w' => '腛', + 'x' => '腢', + 'y' => '腲', + 'z' => '朡', + '{' => '腞', + '|' => '腶', + '}' => '腧', + '~' => '腯', + 'ߡ' => '腄', + 'ߢ' => '腡', + 'ߣ' => '舝', + 'ߤ' => '艉', + 'ߥ' => '艄', + 'ߦ' => '艀', + 'ߧ' => '艂', + 'ߨ' => '艅', + 'ߩ' => '蓱', + 'ߪ' => '萿', + '߫' => '葖', + '߬' => '葶', + '߭' => '葹', + '߮' => '蒏', + '߯' => '蒍', + '߰' => '葥', + '߱' => '葑', + '߲' => '葀', + '߳' => '蒆', + 'ߴ' => '葧', + 'ߵ' => '萰', + '߶' => '葍', + '߷' => '葽', + '߸' => '葚', + '߹' => '葙', + 'ߺ' => '葴', + '߻' => '葳', + '߼' => '葝', + '߽' => '蔇', + '߾' => '葞', + '߿' => '萷', + '' => '萺', + '' => '萴', + '' => '葺', + '' => '葃', + '' => '葸', + '' => '萲', + '' => '葅', + '' => '萩', + '' => '菙', + '' => '葋', + '' => '萯', + '' => '葂', + '' => '萭', + '' => '葟', + '' => '葰', + '' => '萹', + '' => '葎', + '' => '葌', + '' => '葒', + '' => '葯', + '' => '蓅', + '' => '蒎', + '' => '萻', + '' => '葇', + '' => '萶', + '' => '萳', + '' => '葨', + '' => '葾', + '' => '葄', + '' => '萫', + '' => '葠', + '' => '葔', + '' => '葮', + '' => '葐', + '' => '蜋', + '' => '蜄', + '' => '蛷', + '' => '蜌', + '' => '蛺', + '' => '蛖', + '' => '蛵', + '' => '蝍', + '' => '蛸', + '' => '蜎', + '' => '蜉', + '' => '蜁', + '' => '蛶', + '' => '蜍', + '' => '蜅', + '' => '裖', + '' => '裋', + '' => '裍', + '' => '裎', + '' => '裞', + '' => '裛', + '' => '裚', + '' => '裌', + '' => '裐', + '' => '覅', + '' => '覛', + '' => '觟', + '' => '觥', + '' => '觤', + '@' => '觡', + 'A' => '觠', + 'B' => '觢', + 'C' => '觜', + 'D' => '触', + 'E' => '詶', + 'F' => '誆', + 'G' => '詿', + 'H' => '詡', + 'I' => '訿', + 'J' => '詷', + 'K' => '誂', + 'L' => '誄', + 'M' => '詵', + 'N' => '誃', + 'O' => '誁', + 'P' => '詴', + 'Q' => '詺', + 'R' => '谼', + 'S' => '豋', + 'T' => '豊', + 'U' => '豥', + 'V' => '豤', + 'W' => '豦', + 'X' => '貆', + 'Y' => '貄', + 'Z' => '貅', + '[' => '賌', + '\\' => '赨', + ']' => '赩', + '^' => '趑', + '_' => '趌', + '`' => '趎', + 'a' => '趏', + 'b' => '趍', + 'c' => '趓', + 'd' => '趔', + 'e' => '趐', + 'f' => '趒', + 'g' => '跰', + 'h' => '跠', + 'i' => '跬', + 'j' => '跱', + 'k' => '跮', + 'l' => '跐', + 'm' => '跩', + 'n' => '跣', + 'o' => '跢', + 'p' => '跧', + 'q' => '跲', + 'r' => '跫', + 's' => '跴', + 't' => '輆', + 'u' => '軿', + 'v' => '輁', + 'w' => '輀', + 'x' => '輅', + 'y' => '輇', + 'z' => '輈', + '{' => '輂', + '|' => '輋', + '}' => '遒', + '~' => '逿', + '' => '遄', + '' => '遉', + '' => '逽', + '' => '鄐', + '' => '鄍', + '' => '鄏', + '' => '鄑', + '' => '鄖', + '' => '鄔', + '' => '鄋', + '' => '鄎', + '' => '酮', + '' => '酯', + '' => '鉈', + '' => '鉒', + '' => '鈰', + '' => '鈺', + '' => '鉦', + '' => '鈳', + '' => '鉥', + '' => '鉞', + '' => '銃', + '' => '鈮', + '' => '鉊', + '' => '鉆', + '' => '鉭', + '' => '鉬', + '' => '鉏', + '' => '鉠', + '' => '鉧', + '' => '鉯', + '' => '鈶', + '' => '鉡', + '' => '鉰', + '' => '鈱', + '' => '鉔', + '' => '鉣', + '' => '鉐', + '' => '鉲', + '' => '鉎', + '' => '鉓', + '' => '鉌', + '' => '鉖', + '' => '鈲', + '' => '閟', + '' => '閜', + '' => '閞', + '' => '閛', + '' => '隒', + '' => '隓', + '' => '隑', + '' => '隗', + '' => '雎', + '' => '雺', + '' => '雽', + '' => '雸', + '' => '雵', + '' => '靳', + '' => '靷', + '' => '靸', + '' => '靲', + '' => '頏', + '' => '頍', + '' => '頎', + '' => '颬', + '' => '飶', + '' => '飹', + '' => '馯', + '' => '馲', + '' => '馰', + '' => '馵', + '' => '骭', + '' => '骫', + '' => '魛', + '' => '鳪', + '' => '鳭', + '' => '鳧', + '' => '麀', + '' => '黽', + '' => '僦', + '' => '僔', + '' => '僗', + '' => '僨', + '' => '僳', + '' => '僛', + '' => '僪', + '' => '僝', + '' => '僤', + '' => '僓', + '' => '僬', + '' => '僰', + '' => '僯', + '' => '僣', + '' => '僠', + '@' => '凘', + 'A' => '劀', + 'B' => '劁', + 'C' => '勩', + 'D' => '勫', + 'E' => '匰', + 'F' => '厬', + 'G' => '嘧', + 'H' => '嘕', + 'I' => '嘌', + 'J' => '嘒', + 'K' => '嗼', + 'L' => '嘏', + 'M' => '嘜', + 'N' => '嘁', + 'O' => '嘓', + 'P' => '嘂', + 'Q' => '嗺', + 'R' => '嘝', + 'S' => '嘄', + 'T' => '嗿', + 'U' => '嗹', + 'V' => '墉', + 'W' => '塼', + 'X' => '墐', + 'Y' => '墘', + 'Z' => '墆', + '[' => '墁', + '\\' => '塿', + ']' => '塴', + '^' => '墋', + '_' => '塺', + '`' => '墇', + 'a' => '墑', + 'b' => '墎', + 'c' => '塶', + 'd' => '墂', + 'e' => '墈', + 'f' => '塻', + 'g' => '墔', + 'h' => '墏', + 'i' => '壾', + 'j' => '奫', + 'k' => '嫜', + 'l' => '嫮', + 'm' => '嫥', + 'n' => '嫕', + 'o' => '嫪', + 'p' => '嫚', + 'q' => '嫭', + 'r' => '嫫', + 's' => '嫳', + 't' => '嫢', + 'u' => '嫠', + 'v' => '嫛', + 'w' => '嫬', + 'x' => '嫞', + 'y' => '嫝', + 'z' => '嫙', + '{' => '嫨', + '|' => '嫟', + '}' => '孷', + '~' => '寠', + '' => '寣', + '' => '屣', + '' => '嶂', + '' => '嶀', + '' => '嵽', + '' => '嶆', + '' => '嵺', + '' => '嶁', + '' => '嵷', + '' => '嶊', + '' => '嶉', + '' => '嶈', + '' => '嵾', + '' => '嵼', + '' => '嶍', + '' => '嵹', + '' => '嵿', + '' => '幘', + '' => '幙', + '' => '幓', + '' => '廘', + '' => '廑', + '' => '廗', + '' => '廎', + '' => '廜', + '' => '廕', + '' => '廙', + '' => '廒', + '' => '廔', + '' => '彄', + '' => '彃', + '' => '彯', + '' => '徶', + '' => '愬', + '' => '愨', + '' => '慁', + '' => '慞', + '' => '慱', + '' => '慳', + '' => '慒', + '' => '慓', + '' => '慲', + '' => '慬', + '' => '憀', + '' => '慴', + '' => '慔', + '' => '慺', + '' => '慛', + '' => '慥', + '' => '愻', + '' => '慪', + '' => '慡', + '' => '慖', + '' => '戩', + '' => '戧', + '' => '戫', + '' => '搫', + '' => '摍', + '' => '摛', + '' => '摝', + '' => '摴', + '' => '摶', + '' => '摲', + '' => '摳', + '' => '摽', + '' => '摵', + '' => '摦', + '' => '撦', + '' => '摎', + '' => '撂', + '' => '摞', + '' => '摜', + '' => '摋', + '' => '摓', + '' => '摠', + '' => '摐', + '' => '摿', + '' => '搿', + '' => '摬', + '' => '摫', + '' => '摙', + '' => '摥', + '' => '摷', + '' => '敳', + '' => '斠', + '' => '暡', + '' => '暠', + '' => '暟', + '' => '朅', + '' => '朄', + '' => '朢', + '' => '榱', + '' => '榶', + '' => '槉', + '@' => '榠', + 'A' => '槎', + 'B' => '榖', + 'C' => '榰', + 'D' => '榬', + 'E' => '榼', + 'F' => '榑', + 'G' => '榙', + 'H' => '榎', + 'I' => '榧', + 'J' => '榍', + 'K' => '榩', + 'L' => '榾', + 'M' => '榯', + 'N' => '榿', + 'O' => '槄', + 'P' => '榽', + 'Q' => '榤', + 'R' => '槔', + 'S' => '榹', + 'T' => '槊', + 'U' => '榚', + 'V' => '槏', + 'W' => '榳', + 'X' => '榓', + 'Y' => '榪', + 'Z' => '榡', + '[' => '榞', + '\\' => '槙', + ']' => '榗', + '^' => '榐', + '_' => '槂', + '`' => '榵', + 'a' => '榥', + 'b' => '槆', + 'c' => '歊', + 'd' => '歍', + 'e' => '歋', + 'f' => '殞', + 'g' => '殟', + 'h' => '殠', + 'i' => '毃', + 'j' => '毄', + 'k' => '毾', + 'l' => '滎', + 'm' => '滵', + 'n' => '滱', + 'o' => '漃', + 'p' => '漥', + 'q' => '滸', + 'r' => '漷', + 's' => '滻', + 't' => '漮', + 'u' => '漉', + 'v' => '潎', + 'w' => '漙', + 'x' => '漚', + 'y' => '漧', + 'z' => '漘', + '{' => '漻', + '|' => '漒', + '}' => '滭', + '~' => '漊', + '' => '漶', + '' => '潳', + '' => '滹', + '' => '滮', + '' => '漭', + '' => '潀', + '' => '漰', + '' => '漼', + '' => '漵', + '' => '滫', + '' => '漇', + '' => '漎', + '' => '潃', + '' => '漅', + '' => '滽', + '' => '滶', + '' => '漹', + '' => '漜', + '' => '滼', + '' => '漺', + '' => '漟', + '' => '漍', + '' => '漞', + '' => '漈', + '' => '漡', + '' => '熇', + '' => '熐', + '' => '熉', + '' => '熀', + '' => '熅', + '' => '熂', + '' => '熏', + '' => '煻', + '' => '熆', + '' => '熁', + '' => '熗', + '' => '牄', + '' => '牓', + '' => '犗', + '' => '犕', + '' => '犓', + '' => '獃', + '' => '獍', + '' => '獑', + '' => '獌', + '' => '瑢', + '' => '瑳', + '' => '瑱', + '' => '瑵', + '' => '瑲', + '' => '瑧', + '' => '瑮', + '' => '甀', + '' => '甂', + '' => '甃', + '' => '畽', + '' => '疐', + '' => '瘖', + '' => '瘈', + '' => '瘌', + '' => '瘕', + '' => '瘑', + '' => '瘊', + '' => '瘔', + '' => '皸', + '' => '瞁', + '' => '睼', + '' => '瞅', + '' => '瞂', + '' => '睮', + '' => '瞀', + '' => '睯', + '' => '睾', + '' => '瞃', + '' => '碲', + '' => '碪', + '' => '碴', + '' => '碭', + '' => '碨', + '' => '硾', + '' => '碫', + '' => '碞', + '' => '碥', + '' => '碠', + '' => '碬', + '' => '碢', + '' => '碤', + '' => '禘', + '' => '禊', + '' => '禋', + '' => '禖', + '' => '禕', + '' => '禔', + '' => '禓', + '@' => '禗', + 'A' => '禈', + 'B' => '禒', + 'C' => '禐', + 'D' => '稫', + 'E' => '穊', + 'F' => '稰', + 'G' => '稯', + 'H' => '稨', + 'I' => '稦', + 'J' => '窨', + 'K' => '窫', + 'L' => '窬', + 'M' => '竮', + 'N' => '箈', + 'O' => '箜', + 'P' => '箊', + 'Q' => '箑', + 'R' => '箐', + 'S' => '箖', + 'T' => '箍', + 'U' => '箌', + 'V' => '箛', + 'W' => '箎', + 'X' => '箅', + 'Y' => '箘', + 'Z' => '劄', + '[' => '箙', + '\\' => '箤', + ']' => '箂', + '^' => '粻', + '_' => '粿', + '`' => '粼', + 'a' => '粺', + 'b' => '綧', + 'c' => '綷', + 'd' => '緂', + 'e' => '綣', + 'f' => '綪', + 'g' => '緁', + 'h' => '緀', + 'i' => '緅', + 'j' => '綝', + 'k' => '緎', + 'l' => '緄', + 'm' => '緆', + 'n' => '緋', + 'o' => '緌', + 'p' => '綯', + 'q' => '綹', + 'r' => '綖', + 's' => '綼', + 't' => '綟', + 'u' => '綦', + 'v' => '綮', + 'w' => '綩', + 'x' => '綡', + 'y' => '緉', + 'z' => '罳', + '{' => '翢', + '|' => '翣', + '}' => '翥', + '~' => '翞', + '' => '耤', + '' => '聝', + '' => '聜', + '' => '膉', + '' => '膆', + '' => '膃', + '' => '膇', + '' => '膍', + '' => '膌', + '' => '膋', + '' => '舕', + '' => '蒗', + '' => '蒤', + '' => '蒡', + '' => '蒟', + '' => '蒺', + '' => '蓎', + '' => '蓂', + '' => '蒬', + '' => '蒮', + '' => '蒫', + '' => '蒹', + '' => '蒴', + '' => '蓁', + '' => '蓍', + '' => '蒪', + '' => '蒚', + '' => '蒱', + '' => '蓐', + '' => '蒝', + '' => '蒧', + '' => '蒻', + '' => '蒢', + '' => '蒔', + '' => '蓇', + '' => '蓌', + '' => '蒛', + '' => '蒩', + '' => '蒯', + '' => '蒨', + '' => '蓖', + '' => '蒘', + '' => '蒶', + '' => '蓏', + '' => '蒠', + '' => '蓗', + '' => '蓔', + '' => '蓒', + '' => '蓛', + '' => '蒰', + '' => '蒑', + '' => '虡', + '' => '蜳', + '' => '蜣', + '' => '蜨', + '' => '蝫', + '' => '蝀', + '' => '蜮', + '' => '蜞', + '' => '蜡', + '' => '蜙', + '' => '蜛', + '' => '蝃', + '' => '蜬', + '' => '蝁', + '' => '蜾', + '' => '蝆', + '' => '蜠', + '' => '蜲', + '' => '蜪', + '' => '蜭', + '' => '蜼', + '' => '蜒', + '' => '蜺', + '' => '蜱', + '' => '蜵', + '' => '蝂', + '' => '蜦', + '' => '蜧', + '' => '蜸', + '' => '蜤', + '' => '蜚', + '' => '蜰', + '' => '蜑', + '' => '裷', + '' => '裧', + '' => '裱', + '' => '裲', + '' => '裺', + '' => '裾', + '' => '裮', + '' => '裼', + '' => '裶', + '' => '裻', + '@' => '裰', + 'A' => '裬', + 'B' => '裫', + 'C' => '覝', + 'D' => '覡', + 'E' => '覟', + 'F' => '覞', + 'G' => '觩', + 'H' => '觫', + 'I' => '觨', + 'J' => '誫', + 'K' => '誙', + 'L' => '誋', + 'M' => '誒', + 'N' => '誏', + 'O' => '誖', + 'P' => '谽', + 'Q' => '豨', + 'R' => '豩', + 'S' => '賕', + 'T' => '賏', + 'U' => '賗', + 'V' => '趖', + 'W' => '踉', + 'X' => '踂', + 'Y' => '跿', + 'Z' => '踍', + '[' => '跽', + '\\' => '踊', + ']' => '踃', + '^' => '踇', + '_' => '踆', + '`' => '踅', + 'a' => '跾', + 'b' => '踀', + 'c' => '踄', + 'd' => '輐', + 'e' => '輑', + 'f' => '輎', + 'g' => '輍', + 'h' => '鄣', + 'i' => '鄜', + 'j' => '鄠', + 'k' => '鄢', + 'l' => '鄟', + 'm' => '鄝', + 'n' => '鄚', + 'o' => '鄤', + 'p' => '鄡', + 'q' => '鄛', + 'r' => '酺', + 's' => '酲', + 't' => '酹', + 'u' => '酳', + 'v' => '銥', + 'w' => '銤', + 'x' => '鉶', + 'y' => '銛', + 'z' => '鉺', + '{' => '銠', + '|' => '銔', + '}' => '銪', + '~' => '銍', + '' => '銦', + '' => '銚', + '' => '銫', + '' => '鉹', + '' => '銗', + '' => '鉿', + '' => '銣', + '' => '鋮', + '' => '銎', + '' => '銂', + '' => '銕', + '' => '銢', + '' => '鉽', + '' => '銈', + '' => '銡', + '' => '銊', + '' => '銆', + '' => '銌', + '' => '銙', + '' => '銧', + '' => '鉾', + '' => '銇', + '' => '銩', + '' => '銝', + '' => '銋', + '' => '鈭', + '' => '隞', + '' => '隡', + '' => '雿', + '' => '靘', + '' => '靽', + '' => '靺', + '' => '靾', + '' => '鞃', + '' => '鞀', + '' => '鞂', + '' => '靻', + '' => '鞄', + '' => '鞁', + '' => '靿', + '' => '韎', + '' => '韍', + '' => '頖', + '' => '颭', + '' => '颮', + '' => '餂', + '' => '餀', + '' => '餇', + '' => '馝', + '' => '馜', + '' => '駃', + '' => '馹', + '' => '馻', + '' => '馺', + '' => '駂', + '' => '馽', + '' => '駇', + '' => '骱', + '' => '髣', + '' => '髧', + '' => '鬾', + '' => '鬿', + '' => '魠', + '' => '魡', + '' => '魟', + '' => '鳱', + '' => '鳲', + '' => '鳵', + '' => '麧', + '' => '僿', + '' => '儃', + '' => '儰', + '' => '僸', + '' => '儆', + '' => '儇', + '' => '僶', + '' => '僾', + '' => '儋', + '' => '儌', + '' => '僽', + '' => '儊', + '' => '劋', + '' => '劌', + '' => '勱', + '' => '勯', + '' => '噈', + '' => '噂', + '' => '噌', + '' => '嘵', + '' => '噁', + '' => '噊', + '' => '噉', + '' => '噆', + '' => '噘', + '@' => '噚', + 'A' => '噀', + 'B' => '嘳', + 'C' => '嘽', + 'D' => '嘬', + 'E' => '嘾', + 'F' => '嘸', + 'G' => '嘪', + 'H' => '嘺', + 'I' => '圚', + 'J' => '墫', + 'K' => '墝', + 'L' => '墱', + 'M' => '墠', + 'N' => '墣', + 'O' => '墯', + 'P' => '墬', + 'Q' => '墥', + 'R' => '墡', + 'S' => '壿', + 'T' => '嫿', + 'U' => '嫴', + 'V' => '嫽', + 'W' => '嫷', + 'X' => '嫶', + 'Y' => '嬃', + 'Z' => '嫸', + '[' => '嬂', + '\\' => '嫹', + ']' => '嬁', + '^' => '嬇', + '_' => '嬅', + '`' => '嬏', + 'a' => '屧', + 'b' => '嶙', + 'c' => '嶗', + 'd' => '嶟', + 'e' => '嶒', + 'f' => '嶢', + 'g' => '嶓', + 'h' => '嶕', + 'i' => '嶠', + 'j' => '嶜', + 'k' => '嶡', + 'l' => '嶚', + 'm' => '嶞', + 'n' => '幩', + 'o' => '幝', + 'p' => '幠', + 'q' => '幜', + 'r' => '緳', + 's' => '廛', + 't' => '廞', + 'u' => '廡', + 'v' => '彉', + 'w' => '徲', + 'x' => '憋', + 'y' => '憃', + 'z' => '慹', + '{' => '憱', + '|' => '憰', + '}' => '憢', + '~' => '憉', + '' => '憛', + '' => '憓', + '' => '憯', + '' => '憭', + '' => '憟', + '' => '憒', + '' => '憪', + '' => '憡', + '' => '憍', + '' => '慦', + '' => '憳', + '' => '戭', + '' => '摮', + '' => '摰', + '' => '撖', + '' => '撠', + '' => '撅', + '' => '撗', + '' => '撜', + '' => '撏', + '' => '撋', + '' => '撊', + '' => '撌', + '' => '撣', + '' => '撟', + '' => '摨', + '' => '撱', + '' => '撘', + '' => '敶', + '' => '敺', + '' => '敹', + '' => '敻', + '' => '斲', + '' => '斳', + '' => '暵', + '' => '暰', + '' => '暩', + '' => '暲', + '' => '暷', + '' => '暪', + '' => '暯', + '' => '樀', + '' => '樆', + '' => '樗', + '' => '槥', + '' => '槸', + '' => '樕', + '' => '槱', + '' => '槤', + '' => '樠', + '' => '槿', + '' => '槬', + '' => '槢', + '' => '樛', + '' => '樝', + '' => '槾', + '' => '樧', + '' => '槲', + '' => '槮', + '' => '樔', + '' => '槷', + '' => '槧', + '' => '橀', + '' => '樈', + '' => '槦', + '' => '槻', + '' => '樍', + '' => '槼', + '' => '槫', + '' => '樉', + '' => '樄', + '' => '樘', + '' => '樥', + '' => '樏', + '' => '槶', + '' => '樦', + '' => '樇', + '' => '槴', + '' => '樖', + '' => '歑', + '' => '殥', + '' => '殣', + '' => '殢', + '' => '殦', + '' => '氁', + '' => '氀', + '' => '毿', + '' => '氂', + '' => '潁', + '' => '漦', + '' => '潾', + '' => '澇', + '' => '濆', + '' => '澒', + '@' => '澍', + 'A' => '澉', + 'B' => '澌', + 'C' => '潢', + 'D' => '潏', + 'E' => '澅', + 'F' => '潚', + 'G' => '澖', + 'H' => '潶', + 'I' => '潬', + 'J' => '澂', + 'K' => '潕', + 'L' => '潲', + 'M' => '潒', + 'N' => '潐', + 'O' => '潗', + 'P' => '澔', + 'Q' => '澓', + 'R' => '潝', + 'S' => '漀', + 'T' => '潡', + 'U' => '潫', + 'V' => '潽', + 'W' => '潧', + 'X' => '澐', + 'Y' => '潓', + 'Z' => '澋', + '[' => '潩', + '\\' => '潿', + ']' => '澕', + '^' => '潣', + '_' => '潷', + '`' => '潪', + 'a' => '潻', + 'b' => '熲', + 'c' => '熯', + 'd' => '熛', + 'e' => '熰', + 'f' => '熠', + 'g' => '熚', + 'h' => '熩', + 'i' => '熵', + 'j' => '熝', + 'k' => '熥', + 'l' => '熞', + 'm' => '熤', + 'n' => '熡', + 'o' => '熪', + 'p' => '熜', + 'q' => '熧', + 'r' => '熳', + 's' => '犘', + 't' => '犚', + 'u' => '獘', + 'v' => '獒', + 'w' => '獞', + 'x' => '獟', + 'y' => '獠', + 'z' => '獝', + '{' => '獛', + '|' => '獡', + '}' => '獚', + '~' => '獙', + '' => '獢', + '' => '璇', + '' => '璉', + '' => '璊', + '' => '璆', + '' => '璁', + '' => '瑽', + '' => '璅', + '' => '璈', + '' => '瑼', + '' => '瑹', + '' => '甈', + '' => '甇', + '' => '畾', + '' => '瘥', + '' => '瘞', + '' => '瘙', + '' => '瘝', + '' => '瘜', + '' => '瘣', + '' => '瘚', + '' => '瘨', + '' => '瘛', + '' => '皜', + '' => '皝', + '' => '皞', + '' => '皛', + '' => '瞍', + '' => '瞏', + '' => '瞉', + '' => '瞈', + '' => '磍', + '' => '碻', + '' => '磏', + '' => '磌', + '' => '磑', + '' => '磎', + '' => '磔', + '' => '磈', + '' => '磃', + '' => '磄', + '' => '磉', + '' => '禚', + '' => '禡', + '' => '禠', + '' => '禜', + '' => '禢', + '' => '禛', + '' => '歶', + '' => '稹', + '' => '窲', + '' => '窴', + '' => '窳', + '' => '箷', + '' => '篋', + '' => '箾', + '' => '箬', + '' => '篎', + '' => '箯', + '' => '箹', + '' => '篊', + '' => '箵', + '' => '糅', + '' => '糈', + '' => '糌', + '' => '糋', + '' => '緷', + '' => '緛', + '' => '緪', + '' => '緧', + '' => '緗', + '' => '緡', + '' => '縃', + '' => '緺', + '' => '緦', + '' => '緶', + '' => '緱', + '' => '緰', + '' => '緮', + '' => '緟', + '' => '罶', + '' => '羬', + '' => '羰', + '' => '羭', + '' => '翭', + '' => '翫', + '' => '翪', + '' => '翬', + '' => '翦', + '' => '翨', + '' => '聤', + '' => '聧', + '' => '膣', + '' => '膟', + '@' => '膞', + 'A' => '膕', + 'B' => '膢', + 'C' => '膙', + 'D' => '膗', + 'E' => '舖', + 'F' => '艏', + 'G' => '艓', + 'H' => '艒', + 'I' => '艐', + 'J' => '艎', + 'K' => '艑', + 'L' => '蔤', + 'M' => '蔻', + 'N' => '蔏', + 'O' => '蔀', + 'P' => '蔩', + 'Q' => '蔎', + 'R' => '蔉', + 'S' => '蔍', + 'T' => '蔟', + 'U' => '蔊', + 'V' => '蔧', + 'W' => '蔜', + 'X' => '蓻', + 'Y' => '蔫', + 'Z' => '蓺', + '[' => '蔈', + '\\' => '蔌', + ']' => '蓴', + '^' => '蔪', + '_' => '蓲', + '`' => '蔕', + 'a' => '蓷', + 'b' => '蓫', + 'c' => '蓳', + 'd' => '蓼', + 'e' => '蔒', + 'f' => '蓪', + 'g' => '蓩', + 'h' => '蔖', + 'i' => '蓾', + 'j' => '蔨', + 'k' => '蔝', + 'l' => '蔮', + 'm' => '蔂', + 'n' => '蓽', + 'o' => '蔞', + 'p' => '蓶', + 'q' => '蔱', + 'r' => '蔦', + 's' => '蓧', + 't' => '蓨', + 'u' => '蓰', + 'v' => '蓯', + 'w' => '蓹', + 'x' => '蔘', + 'y' => '蔠', + 'z' => '蔰', + '{' => '蔋', + '|' => '蔙', + '}' => '蔯', + '~' => '虢', + '' => '蝖', + '' => '蝣', + '' => '蝤', + '' => '蝷', + '' => '蟡', + '' => '蝳', + '' => '蝘', + '' => '蝔', + '' => '蝛', + '' => '蝒', + '' => '蝡', + '' => '蝚', + '' => '蝑', + '' => '蝞', + '' => '蝭', + '' => '蝪', + '' => '蝐', + '' => '蝎', + '' => '蝟', + '' => '蝝', + '' => '蝯', + '' => '蝬', + '' => '蝺', + '' => '蝮', + '' => '蝜', + '' => '蝥', + '' => '蝏', + '' => '蝻', + '' => '蝵', + '' => '蝢', + '' => '蝧', + '' => '蝩', + '' => '衚', + '' => '褅', + '' => '褌', + '' => '褔', + '' => '褋', + '' => '褗', + '' => '褘', + '' => '褙', + '' => '褆', + '' => '褖', + '' => '褑', + '' => '褎', + '' => '褉', + '' => '覢', + '' => '覤', + '' => '覣', + '' => '觭', + '' => '觰', + '' => '觬', + '' => '諏', + '' => '諆', + '' => '誸', + '' => '諓', + '' => '諑', + '' => '諔', + '' => '諕', + '' => '誻', + '' => '諗', + '' => '誾', + '' => '諀', + '' => '諅', + '' => '諘', + '' => '諃', + '' => '誺', + '' => '誽', + '' => '諙', + '' => '谾', + '' => '豍', + '' => '貏', + '' => '賥', + '' => '賟', + '' => '賙', + '' => '賨', + '' => '賚', + '' => '賝', + '' => '賧', + '' => '趠', + '' => '趜', + '' => '趡', + '' => '趛', + '' => '踠', + '' => '踣', + '' => '踥', + '' => '踤', + '' => '踮', + '' => '踕', + '' => '踛', + '' => '踖', + '' => '踑', + '' => '踙', + '' => '踦', + '' => '踧', + '@' => '踔', + 'A' => '踒', + 'B' => '踘', + 'C' => '踓', + 'D' => '踜', + 'E' => '踗', + 'F' => '踚', + 'G' => '輬', + 'H' => '輤', + 'I' => '輘', + 'J' => '輚', + 'K' => '輠', + 'L' => '輣', + 'M' => '輖', + 'N' => '輗', + 'O' => '遳', + 'P' => '遰', + 'Q' => '遯', + 'R' => '遧', + 'S' => '遫', + 'T' => '鄯', + 'U' => '鄫', + 'V' => '鄩', + 'W' => '鄪', + 'X' => '鄲', + 'Y' => '鄦', + 'Z' => '鄮', + '[' => '醅', + '\\' => '醆', + ']' => '醊', + '^' => '醁', + '_' => '醂', + '`' => '醄', + 'a' => '醀', + 'b' => '鋐', + 'c' => '鋃', + 'd' => '鋄', + 'e' => '鋀', + 'f' => '鋙', + 'g' => '銶', + 'h' => '鋏', + 'i' => '鋱', + 'j' => '鋟', + 'k' => '鋘', + 'l' => '鋩', + 'm' => '鋗', + 'n' => '鋝', + 'o' => '鋌', + 'p' => '鋯', + 'q' => '鋂', + 'r' => '鋨', + 's' => '鋊', + 't' => '鋈', + 'u' => '鋎', + 'v' => '鋦', + 'w' => '鋍', + 'x' => '鋕', + 'y' => '鋉', + 'z' => '鋠', + '{' => '鋞', + '|' => '鋧', + '}' => '鋑', + '~' => '鋓', + '' => '銵', + '' => '鋡', + '' => '鋆', + '' => '銴', + '' => '镼', + '' => '閬', + '' => '閫', + '' => '閮', + '' => '閰', + '' => '隤', + '' => '隢', + '' => '雓', + '' => '霅', + '' => '霈', + '' => '霂', + '' => '靚', + '' => '鞊', + '' => '鞎', + '' => '鞈', + '' => '韐', + '' => '韏', + '' => '頞', + '' => '頝', + '' => '頦', + '' => '頩', + '' => '頨', + '' => '頠', + '' => '頛', + '' => '頧', + '' => '颲', + '' => '餈', + '' => '飺', + '' => '餑', + '' => '餔', + '' => '餖', + '' => '餗', + '' => '餕', + '' => '駜', + '' => '駍', + '' => '駏', + '' => '駓', + '' => '駔', + '' => '駎', + '' => '駉', + '' => '駖', + '' => '駘', + '' => '駋', + '' => '駗', + '' => '駌', + '' => '骳', + '' => '髬', + '' => '髫', + '' => '髳', + '' => '髲', + '' => '髱', + '' => '魆', + '' => '魃', + '' => '魧', + '' => '魴', + '' => '魱', + '' => '魦', + '' => '魶', + '' => '魵', + '' => '魰', + '' => '魨', + '' => '魤', + '' => '魬', + '' => '鳼', + '' => '鳺', + '' => '鳽', + '' => '鳿', + '' => '鳷', + '' => '鴇', + '' => '鴀', + '' => '鳹', + '' => '鳻', + '' => '鴈', + '' => '鴅', + '' => '鴄', + '' => '麃', + '' => '黓', + '' => '鼏', + '' => '鼐', + '' => '儜', + '' => '儓', + '' => '儗', + '' => '儚', + '' => '儑', + '' => '凞', + '' => '匴', + '' => '叡', + '' => '噰', + '' => '噠', + '' => '噮', + '@' => '噳', + 'A' => '噦', + 'B' => '噣', + 'C' => '噭', + 'D' => '噲', + 'E' => '噞', + 'F' => '噷', + 'G' => '圜', + 'H' => '圛', + 'I' => '壈', + 'J' => '墽', + 'K' => '壉', + 'L' => '墿', + 'M' => '墺', + 'N' => '壂', + 'O' => '墼', + 'P' => '壆', + 'Q' => '嬗', + 'R' => '嬙', + 'S' => '嬛', + 'T' => '嬡', + 'U' => '嬔', + 'V' => '嬓', + 'W' => '嬐', + 'X' => '嬖', + 'Y' => '嬨', + 'Z' => '嬚', + '[' => '嬠', + '\\' => '嬞', + ']' => '寯', + '^' => '嶬', + '_' => '嶱', + '`' => '嶩', + 'a' => '嶧', + 'b' => '嶵', + 'c' => '嶰', + 'd' => '嶮', + 'e' => '嶪', + 'f' => '嶨', + 'g' => '嶲', + 'h' => '嶭', + 'i' => '嶯', + 'j' => '嶴', + 'k' => '幧', + 'l' => '幨', + 'm' => '幦', + 'n' => '幯', + 'o' => '廩', + 'p' => '廧', + 'q' => '廦', + 'r' => '廨', + 's' => '廥', + 't' => '彋', + 'u' => '徼', + 'v' => '憝', + 'w' => '憨', + 'x' => '憖', + 'y' => '懅', + 'z' => '憴', + '{' => '懆', + '|' => '懁', + '}' => '懌', + '~' => '憺', + '' => '憿', + '' => '憸', + '' => '憌', + '' => '擗', + '' => '擖', + '' => '擐', + '' => '擏', + '' => '擉', + '' => '撽', + '' => '撉', + '' => '擃', + '' => '擛', + '' => '擳', + '' => '擙', + '' => '攳', + '' => '敿', + '' => '敼', + '' => '斢', + '' => '曈', + '' => '暾', + '' => '曀', + '' => '曊', + '' => '曋', + '' => '曏', + '' => '暽', + '' => '暻', + '' => '暺', + '' => '曌', + '' => '朣', + '' => '樴', + '' => '橦', + '' => '橉', + '' => '橧', + '' => '樲', + '' => '橨', + '' => '樾', + '' => '橝', + '' => '橭', + '' => '橶', + '' => '橛', + '' => '橑', + '' => '樨', + '' => '橚', + '' => '樻', + '' => '樿', + '' => '橁', + '' => '橪', + '' => '橤', + '' => '橐', + '' => '橏', + '' => '橔', + '' => '橯', + '' => '橩', + '' => '橠', + '' => '樼', + '' => '橞', + '' => '橖', + '' => '橕', + '' => '橍', + '' => '橎', + '' => '橆', + '' => '歕', + '' => '歔', + '' => '歖', + '' => '殧', + '' => '殪', + '' => '殫', + '' => '毈', + '' => '毇', + '' => '氄', + '' => '氃', + '' => '氆', + '' => '澭', + '' => '濋', + '' => '澣', + '' => '濇', + '' => '澼', + '' => '濎', + '' => '濈', + '' => '潞', + '' => '濄', + '' => '澽', + '' => '澞', + '' => '濊', + '' => '澨', + '' => '瀄', + '' => '澥', + '' => '澮', + '' => '澺', + '' => '澬', + '' => '澪', + '' => '濏', + '' => '澿', + '' => '澸', + '@' => '澢', + 'A' => '濉', + 'B' => '澫', + 'C' => '濍', + 'D' => '澯', + 'E' => '澲', + 'F' => '澰', + 'G' => '燅', + 'H' => '燂', + 'I' => '熿', + 'J' => '熸', + 'K' => '燖', + 'L' => '燀', + 'M' => '燁', + 'N' => '燋', + 'O' => '燔', + 'P' => '燊', + 'Q' => '燇', + 'R' => '燏', + 'S' => '熽', + 'T' => '燘', + 'U' => '熼', + 'V' => '燆', + 'W' => '燚', + 'X' => '燛', + 'Y' => '犝', + 'Z' => '犞', + '[' => '獩', + '\\' => '獦', + ']' => '獧', + '^' => '獬', + '_' => '獥', + '`' => '獫', + 'a' => '獪', + 'b' => '瑿', + 'c' => '璚', + 'd' => '璠', + 'e' => '璔', + 'f' => '璒', + 'g' => '璕', + 'h' => '璡', + 'i' => '甋', + 'j' => '疀', + 'k' => '瘯', + 'l' => '瘭', + 'm' => '瘱', + 'n' => '瘽', + 'o' => '瘳', + 'p' => '瘼', + 'q' => '瘵', + 'r' => '瘲', + 's' => '瘰', + 't' => '皻', + 'u' => '盦', + 'v' => '瞚', + 'w' => '瞝', + 'x' => '瞡', + 'y' => '瞜', + 'z' => '瞛', + '{' => '瞢', + '|' => '瞣', + '}' => '瞕', + '~' => '瞙', + '' => '瞗', + '' => '磝', + '' => '磩', + '' => '磥', + '' => '磪', + '' => '磞', + '' => '磣', + '' => '磛', + '' => '磡', + '' => '磢', + '' => '磭', + '' => '磟', + '' => '磠', + '' => '禤', + '' => '穄', + '' => '穈', + '' => '穇', + '' => '窶', + '' => '窸', + '' => '窵', + '' => '窱', + '' => '窷', + '' => '篞', + '' => '篣', + '' => '篧', + '' => '篝', + '' => '篕', + '' => '篥', + '' => '篚', + '' => '篨', + '' => '篹', + '' => '篔', + '' => '篪', + '' => '篢', + '' => '篜', + '' => '篫', + '' => '篘', + '' => '篟', + '' => '糒', + '' => '糔', + '' => '糗', + '' => '糐', + '' => '糑', + '' => '縒', + '' => '縡', + '' => '縗', + '' => '縌', + '' => '縟', + '' => '縠', + '' => '縓', + '' => '縎', + '' => '縜', + '' => '縕', + '' => '縚', + '' => '縢', + '' => '縋', + '' => '縏', + '' => '縖', + '' => '縍', + '' => '縔', + '' => '縥', + '' => '縤', + '' => '罃', + '' => '罻', + '' => '罼', + '' => '罺', + '' => '羱', + '' => '翯', + '' => '耪', + '' => '耩', + '' => '聬', + '' => '膱', + '' => '膦', + '' => '膮', + '' => '膹', + '' => '膵', + '' => '膫', + '' => '膰', + '' => '膬', + '' => '膴', + '' => '膲', + '' => '膷', + '' => '膧', + '' => '臲', + '' => '艕', + '' => '艖', + '' => '艗', + '' => '蕖', + '' => '蕅', + '' => '蕫', + '' => '蕍', + '' => '蕓', + '' => '蕡', + '' => '蕘', + '@' => '蕀', + 'A' => '蕆', + 'B' => '蕤', + 'C' => '蕁', + 'D' => '蕢', + 'E' => '蕄', + 'F' => '蕑', + 'G' => '蕇', + 'H' => '蕣', + 'I' => '蔾', + 'J' => '蕛', + 'K' => '蕱', + 'L' => '蕎', + 'M' => '蕮', + 'N' => '蕵', + 'O' => '蕕', + 'P' => '蕧', + 'Q' => '蕠', + 'R' => '薌', + 'S' => '蕦', + 'T' => '蕝', + 'U' => '蕔', + 'V' => '蕥', + 'W' => '蕬', + 'X' => '虣', + 'Y' => '虥', + 'Z' => '虤', + '[' => '螛', + '\\' => '螏', + ']' => '螗', + '^' => '螓', + '_' => '螒', + '`' => '螈', + 'a' => '螁', + 'b' => '螖', + 'c' => '螘', + 'd' => '蝹', + 'e' => '螇', + 'f' => '螣', + 'g' => '螅', + 'h' => '螐', + 'i' => '螑', + 'j' => '螝', + 'k' => '螄', + 'l' => '螔', + 'm' => '螜', + 'n' => '螚', + 'o' => '螉', + 'p' => '褞', + 'q' => '褦', + 'r' => '褰', + 's' => '褭', + 't' => '褮', + 'u' => '褧', + 'v' => '褱', + 'w' => '褢', + 'x' => '褩', + 'y' => '褣', + 'z' => '褯', + '{' => '褬', + '|' => '褟', + '}' => '觱', + '~' => '諠', + '' => '諢', + '' => '諲', + '' => '諴', + '' => '諵', + '' => '諝', + '' => '謔', + '' => '諤', + '' => '諟', + '' => '諰', + '' => '諈', + '' => '諞', + '' => '諡', + '' => '諨', + '' => '諿', + '' => '諯', + '' => '諻', + '' => '貑', + '' => '貒', + '' => '貐', + '' => '賵', + '' => '賮', + '' => '賱', + '' => '賰', + '' => '賳', + '' => '赬', + '' => '赮', + '' => '趥', + '' => '趧', + '' => '踳', + '' => '踾', + '' => '踸', + '' => '蹀', + '' => '蹅', + '' => '踶', + '' => '踼', + '' => '踽', + '' => '蹁', + '' => '踰', + '' => '踿', + '' => '躽', + '' => '輶', + '' => '輮', + '' => '輵', + '' => '輲', + '' => '輹', + '' => '輷', + '' => '輴', + '' => '遶', + '' => '遹', + '' => '遻', + '' => '邆', + '' => '郺', + '' => '鄳', + '' => '鄵', + '' => '鄶', + '' => '醓', + '' => '醐', + '' => '醑', + '' => '醍', + '' => '醏', + '' => '錧', + '' => '錞', + '' => '錈', + '' => '錟', + '' => '錆', + '' => '錏', + '' => '鍺', + '' => '錸', + '' => '錼', + '' => '錛', + '' => '錣', + '' => '錒', + '' => '錁', + '' => '鍆', + '' => '錭', + '' => '錎', + '' => '錍', + '' => '鋋', + '' => '錝', + '' => '鋺', + '' => '錥', + '' => '錓', + '' => '鋹', + '' => '鋷', + '' => '錴', + '' => '錂', + '' => '錤', + '' => '鋿', + '' => '錩', + '' => '錹', + '' => '錵', + '' => '錪', + '' => '錔', + '' => '錌', + '@' => '錋', + 'A' => '鋾', + 'B' => '錉', + 'C' => '錀', + 'D' => '鋻', + 'E' => '錖', + 'F' => '閼', + 'G' => '闍', + 'H' => '閾', + 'I' => '閹', + 'J' => '閺', + 'K' => '閶', + 'L' => '閿', + 'M' => '閵', + 'N' => '閽', + 'O' => '隩', + 'P' => '雔', + 'Q' => '霋', + 'R' => '霒', + 'S' => '霐', + 'T' => '鞙', + 'U' => '鞗', + 'V' => '鞔', + 'W' => '韰', + 'X' => '韸', + 'Y' => '頵', + 'Z' => '頯', + '[' => '頲', + '\\' => '餤', + ']' => '餟', + '^' => '餧', + '_' => '餩', + '`' => '馞', + 'a' => '駮', + 'b' => '駬', + 'c' => '駥', + 'd' => '駤', + 'e' => '駰', + 'f' => '駣', + 'g' => '駪', + 'h' => '駩', + 'i' => '駧', + 'j' => '骹', + 'k' => '骿', + 'l' => '骴', + 'm' => '骻', + 'n' => '髶', + 'o' => '髺', + 'p' => '髹', + 'q' => '髷', + 'r' => '鬳', + 's' => '鮀', + 't' => '鮅', + 'u' => '鮇', + 'v' => '魼', + 'w' => '魾', + 'x' => '魻', + 'y' => '鮂', + 'z' => '鮓', + '{' => '鮒', + '|' => '鮐', + '}' => '魺', + '~' => '鮕', + '' => '魽', + '' => '鮈', + '' => '鴥', + '' => '鴗', + '' => '鴠', + '' => '鴞', + '' => '鴔', + '' => '鴩', + '' => '鴝', + '' => '鴘', + '' => '鴢', + '' => '鴐', + '' => '鴙', + '' => '鴟', + '' => '麈', + '' => '麆', + '' => '麇', + '' => '麮', + '' => '麭', + '' => '黕', + '' => '黖', + '' => '黺', + '' => '鼒', + '' => '鼽', + '' => '儦', + '' => '儥', + '' => '儢', + '' => '儤', + '' => '儠', + '' => '儩', + '' => '勴', + '' => '嚓', + '' => '嚌', + '' => '嚍', + '' => '嚆', + '' => '嚄', + '' => '嚃', + '' => '噾', + '' => '嚂', + '' => '噿', + '' => '嚁', + '' => '壖', + '' => '壔', + '' => '壏', + '' => '壒', + '' => '嬭', + '' => '嬥', + '' => '嬲', + '' => '嬣', + '' => '嬬', + '' => '嬧', + '' => '嬦', + '' => '嬯', + '' => '嬮', + '' => '孻', + '' => '寱', + '' => '寲', + '' => '嶷', + '' => '幬', + '' => '幪', + '' => '徾', + '' => '徻', + '' => '懃', + '' => '憵', + '' => '憼', + '' => '懧', + '' => '懠', + '' => '懥', + '' => '懤', + '' => '懨', + '' => '懞', + '' => '擯', + '' => '擩', + '' => '擣', + '' => '擫', + '' => '擤', + '' => '擨', + '' => '斁', + '' => '斀', + '' => '斶', + '' => '旚', + '' => '曒', + '' => '檍', + '' => '檖', + '' => '檁', + '' => '檥', + '' => '檉', + '' => '檟', + '' => '檛', + '' => '檡', + '' => '檞', + '' => '檇', + '' => '檓', + '' => '檎', + '@' => '檕', + 'A' => '檃', + 'B' => '檨', + 'C' => '檤', + 'D' => '檑', + 'E' => '橿', + 'F' => '檦', + 'G' => '檚', + 'H' => '檅', + 'I' => '檌', + 'J' => '檒', + 'K' => '歛', + 'L' => '殭', + 'M' => '氉', + 'N' => '濌', + 'O' => '澩', + 'P' => '濴', + 'Q' => '濔', + 'R' => '濣', + 'S' => '濜', + 'T' => '濭', + 'U' => '濧', + 'V' => '濦', + 'W' => '濞', + 'X' => '濲', + 'Y' => '濝', + 'Z' => '濢', + '[' => '濨', + '\\' => '燡', + ']' => '燱', + '^' => '燨', + '_' => '燲', + '`' => '燤', + 'a' => '燰', + 'b' => '燢', + 'c' => '獳', + 'd' => '獮', + 'e' => '獯', + 'f' => '璗', + 'g' => '璲', + 'h' => '璫', + 'i' => '璐', + 'j' => '璪', + 'k' => '璭', + 'l' => '璱', + 'm' => '璥', + 'n' => '璯', + 'o' => '甐', + 'p' => '甑', + 'q' => '甒', + 'r' => '甏', + 's' => '疄', + 't' => '癃', + 'u' => '癈', + 'v' => '癉', + 'w' => '癇', + 'x' => '皤', + 'y' => '盩', + 'z' => '瞵', + '{' => '瞫', + '|' => '瞲', + '}' => '瞷', + '~' => '瞶', + '' => '瞴', + '' => '瞱', + '' => '瞨', + '' => '矰', + '' => '磳', + '' => '磽', + '' => '礂', + '' => '磻', + '' => '磼', + '' => '磲', + '' => '礅', + '' => '磹', + '' => '磾', + '' => '礄', + '' => '禫', + '' => '禨', + '' => '穜', + '' => '穛', + '' => '穖', + '' => '穘', + '' => '穔', + '' => '穚', + '' => '窾', + '' => '竀', + '' => '竁', + '' => '簅', + '' => '簏', + '' => '篲', + '' => '簀', + '' => '篿', + '' => '篻', + '' => '簎', + '' => '篴', + '' => '簋', + '' => '篳', + '' => '簂', + '' => '簉', + '' => '簃', + '' => '簁', + '' => '篸', + '' => '篽', + '' => '簆', + '' => '篰', + '' => '篱', + '' => '簐', + '' => '簊', + '' => '糨', + '' => '縭', + '' => '縼', + '' => '繂', + '' => '縳', + '' => '顈', + '' => '縸', + '' => '縪', + '' => '繉', + '' => '繀', + '' => '繇', + '' => '縩', + '' => '繌', + '' => '縰', + '' => '縻', + '' => '縶', + '' => '繄', + '' => '縺', + '' => '罅', + '' => '罿', + '' => '罾', + '' => '罽', + '' => '翴', + '' => '翲', + '' => '耬', + '' => '膻', + '' => '臄', + '' => '臌', + '' => '臊', + '' => '臅', + '' => '臇', + '' => '膼', + '' => '臩', + '' => '艛', + '' => '艚', + '' => '艜', + '' => '薃', + '' => '薀', + '' => '薏', + '' => '薧', + '' => '薕', + '' => '薠', + '' => '薋', + '' => '薣', + '' => '蕻', + '' => '薤', + '' => '薚', + '' => '薞', + '@' => '蕷', + 'A' => '蕼', + 'B' => '薉', + 'C' => '薡', + 'D' => '蕺', + 'E' => '蕸', + 'F' => '蕗', + 'G' => '薎', + 'H' => '薖', + 'I' => '薆', + 'J' => '薍', + 'K' => '薙', + 'L' => '薝', + 'M' => '薁', + 'N' => '薢', + 'O' => '薂', + 'P' => '薈', + 'Q' => '薅', + 'R' => '蕹', + 'S' => '蕶', + 'T' => '薘', + 'U' => '薐', + 'V' => '薟', + 'W' => '虨', + 'X' => '螾', + 'Y' => '螪', + 'Z' => '螭', + '[' => '蟅', + '\\' => '螰', + ']' => '螬', + '^' => '螹', + '_' => '螵', + '`' => '螼', + 'a' => '螮', + 'b' => '蟉', + 'c' => '蟃', + 'd' => '蟂', + 'e' => '蟌', + 'f' => '螷', + 'g' => '螯', + 'h' => '蟄', + 'i' => '蟊', + 'j' => '螴', + 'k' => '螶', + 'l' => '螿', + 'm' => '螸', + 'n' => '螽', + 'o' => '蟞', + 'p' => '螲', + 'q' => '褵', + 'r' => '褳', + 's' => '褼', + 't' => '褾', + 'u' => '襁', + 'v' => '襒', + 'w' => '褷', + 'x' => '襂', + 'y' => '覭', + 'z' => '覯', + '{' => '覮', + '|' => '觲', + '}' => '觳', + '~' => '謞', + '' => '謘', + '' => '謖', + '' => '謑', + '' => '謅', + '' => '謋', + '' => '謢', + '' => '謏', + '' => '謒', + '' => '謕', + '' => '謇', + '' => '謍', + '' => '謈', + '' => '謆', + '' => '謜', + '' => '謓', + '' => '謚', + '' => '豏', + '' => '豰', + '' => '豲', + '' => '豱', + '' => '豯', + '' => '貕', + '' => '貔', + '' => '賹', + '' => '赯', + '' => '蹎', + '' => '蹍', + '' => '蹓', + '' => '蹐', + '' => '蹌', + '' => '蹇', + '' => '轃', + '' => '轀', + '' => '邅', + '' => '遾', + '' => '鄸', + '' => '醚', + '' => '醢', + '' => '醛', + '' => '醙', + '' => '醟', + '' => '醡', + '' => '醝', + '' => '醠', + '' => '鎡', + '' => '鎃', + '' => '鎯', + '' => '鍤', + '' => '鍖', + '' => '鍇', + '' => '鍼', + '' => '鍘', + '' => '鍜', + '' => '鍶', + '' => '鍉', + '' => '鍐', + '' => '鍑', + '' => '鍠', + '' => '鍭', + '' => '鎏', + '' => '鍌', + '' => '鍪', + '' => '鍹', + '' => '鍗', + '' => '鍕', + '' => '鍒', + '' => '鍏', + '' => '鍱', + '' => '鍷', + '' => '鍻', + '' => '鍡', + '' => '鍞', + '' => '鍣', + '' => '鍧', + '' => '鎀', + '' => '鍎', + '' => '鍙', + '' => '闇', + '' => '闀', + '' => '闉', + '' => '闃', + '' => '闅', + '' => '閷', + '' => '隮', + '' => '隰', + '' => '隬', + '' => '霠', + '' => '霟', + '' => '霘', + '' => '霝', + '' => '霙', + '' => '鞚', + '' => '鞡', + '' => '鞜', + '@' => '鞞', + 'A' => '鞝', + 'B' => '韕', + 'C' => '韔', + 'D' => '韱', + 'E' => '顁', + 'F' => '顄', + 'G' => '顊', + 'H' => '顉', + 'I' => '顅', + 'J' => '顃', + 'K' => '餥', + 'L' => '餫', + 'M' => '餬', + 'N' => '餪', + 'O' => '餳', + 'P' => '餲', + 'Q' => '餯', + 'R' => '餭', + 'S' => '餱', + 'T' => '餰', + 'U' => '馘', + 'V' => '馣', + 'W' => '馡', + 'X' => '騂', + 'Y' => '駺', + 'Z' => '駴', + '[' => '駷', + '\\' => '駹', + ']' => '駸', + '^' => '駶', + '_' => '駻', + '`' => '駽', + 'a' => '駾', + 'b' => '駼', + 'c' => '騃', + 'd' => '骾', + 'e' => '髾', + 'f' => '髽', + 'g' => '鬁', + 'h' => '髼', + 'i' => '魈', + 'j' => '鮚', + 'k' => '鮨', + 'l' => '鮞', + 'm' => '鮛', + 'n' => '鮦', + 'o' => '鮡', + 'p' => '鮥', + 'q' => '鮤', + 'r' => '鮆', + 's' => '鮢', + 't' => '鮠', + 'u' => '鮯', + 'v' => '鴳', + 'w' => '鵁', + 'x' => '鵧', + 'y' => '鴶', + 'z' => '鴮', + '{' => '鴯', + '|' => '鴱', + '}' => '鴸', + '~' => '鴰', + '' => '鵅', + '' => '鵂', + '' => '鵃', + '' => '鴾', + '' => '鴷', + '' => '鵀', + '' => '鴽', + '' => '翵', + '' => '鴭', + '' => '麊', + '' => '麉', + '' => '麍', + '' => '麰', + '' => '黈', + '' => '黚', + '' => '黻', + '' => '黿', + '' => '鼤', + '' => '鼣', + '' => '鼢', + '' => '齔', + '' => '龠', + '' => '儱', + '' => '儭', + '' => '儮', + '' => '嚘', + '' => '嚜', + '' => '嚗', + '' => '嚚', + '' => '嚝', + '' => '嚙', + '' => '奰', + '' => '嬼', + '' => '屩', + '' => '屪', + '' => '巀', + '' => '幭', + '' => '幮', + '' => '懘', + '' => '懟', + '' => '懭', + '' => '懮', + '' => '懱', + '' => '懪', + '' => '懰', + '' => '懫', + '' => '懖', + '' => '懩', + '' => '擿', + '' => '攄', + '' => '擽', + '' => '擸', + '' => '攁', + '' => '攃', + '' => '擼', + '' => '斔', + '' => '旛', + '' => '曚', + '' => '曛', + '' => '曘', + '' => '櫅', + '' => '檹', + '' => '檽', + '' => '櫡', + '' => '櫆', + '' => '檺', + '' => '檶', + '' => '檷', + '' => '櫇', + '' => '檴', + '' => '檭', + '' => '歞', + '' => '毉', + '' => '氋', + '' => '瀇', + '' => '瀌', + '' => '瀍', + '' => '瀁', + '' => '瀅', + '' => '瀔', + '' => '瀎', + '' => '濿', + '' => '瀀', + '' => '濻', + '' => '瀦', + '' => '濼', + '' => '濷', + '' => '瀊', + '' => '爁', + '' => '燿', + '' => '燹', + '' => '爃', + '' => '燽', + '' => '獶', + '@' => '璸', + 'A' => '瓀', + 'B' => '璵', + 'C' => '瓁', + 'D' => '璾', + 'E' => '璶', + 'F' => '璻', + 'G' => '瓂', + 'H' => '甔', + 'I' => '甓', + 'J' => '癜', + 'K' => '癤', + 'L' => '癙', + 'M' => '癐', + 'N' => '癓', + 'O' => '癗', + 'P' => '癚', + 'Q' => '皦', + 'R' => '皽', + 'S' => '盬', + 'T' => '矂', + 'U' => '瞺', + 'V' => '磿', + 'W' => '礌', + 'X' => '礓', + 'Y' => '礔', + 'Z' => '礉', + '[' => '礐', + '\\' => '礒', + ']' => '礑', + '^' => '禭', + '_' => '禬', + '`' => '穟', + 'a' => '簜', + 'b' => '簩', + 'c' => '簙', + 'd' => '簠', + 'e' => '簟', + 'f' => '簭', + 'g' => '簝', + 'h' => '簦', + 'i' => '簨', + 'j' => '簢', + 'k' => '簥', + 'l' => '簰', + 'm' => '繜', + 'n' => '繐', + 'o' => '繖', + 'p' => '繣', + 'q' => '繘', + 'r' => '繢', + 's' => '繟', + 't' => '繑', + 'u' => '繠', + 'v' => '繗', + 'w' => '繓', + 'x' => '羵', + 'y' => '羳', + 'z' => '翷', + '{' => '翸', + '|' => '聵', + '}' => '臑', + '~' => '臒', + '' => '臐', + '' => '艟', + '' => '艞', + '' => '薴', + '' => '藆', + '' => '藀', + '' => '藃', + '' => '藂', + '' => '薳', + '' => '薵', + '' => '薽', + '' => '藇', + '' => '藄', + '' => '薿', + '' => '藋', + '' => '藎', + '' => '藈', + '' => '藅', + '' => '薱', + '' => '薶', + '' => '藒', + '' => '蘤', + '' => '薸', + '' => '薷', + '' => '薾', + '' => '虩', + '' => '蟧', + '' => '蟦', + '' => '蟢', + '' => '蟛', + '' => '蟫', + '' => '蟪', + '' => '蟥', + '' => '蟟', + '' => '蟳', + '' => '蟤', + '' => '蟔', + '' => '蟜', + '' => '蟓', + '' => '蟭', + '' => '蟘', + '' => '蟣', + '' => '螤', + '' => '蟗', + '' => '蟙', + '' => '蠁', + '' => '蟴', + '' => '蟨', + '' => '蟝', + '' => '襓', + '' => '襋', + '' => '襏', + '' => '襌', + '' => '襆', + '' => '襐', + '' => '襑', + '' => '襉', + '' => '謪', + '' => '謧', + '' => '謣', + '' => '謳', + '' => '謰', + '' => '謵', + '' => '譇', + '' => '謯', + '' => '謼', + '' => '謾', + '' => '謱', + '' => '謥', + '' => '謷', + '' => '謦', + '' => '謶', + '' => '謮', + '' => '謤', + '' => '謻', + '' => '謽', + '' => '謺', + '' => '豂', + '' => '豵', + '' => '貙', + '' => '貘', + '' => '貗', + '' => '賾', + '' => '贄', + '' => '贂', + '' => '贀', + '' => '蹜', + '' => '蹢', + '' => '蹠', + '' => '蹗', + '' => '蹖', + '' => '蹞', + '' => '蹥', + '' => '蹧', + '@' => '蹛', + 'A' => '蹚', + 'B' => '蹡', + 'C' => '蹝', + 'D' => '蹩', + 'E' => '蹔', + 'F' => '轆', + 'G' => '轇', + 'H' => '轈', + 'I' => '轋', + 'J' => '鄨', + 'K' => '鄺', + 'L' => '鄻', + 'M' => '鄾', + 'N' => '醨', + 'O' => '醥', + 'P' => '醧', + 'Q' => '醯', + 'R' => '醪', + 'S' => '鎵', + 'T' => '鎌', + 'U' => '鎒', + 'V' => '鎷', + 'W' => '鎛', + 'X' => '鎝', + 'Y' => '鎉', + 'Z' => '鎧', + '[' => '鎎', + '\\' => '鎪', + ']' => '鎞', + '^' => '鎦', + '_' => '鎕', + '`' => '鎈', + 'a' => '鎙', + 'b' => '鎟', + 'c' => '鎍', + 'd' => '鎱', + 'e' => '鎑', + 'f' => '鎲', + 'g' => '鎤', + 'h' => '鎨', + 'i' => '鎴', + 'j' => '鎣', + 'k' => '鎥', + 'l' => '闒', + 'm' => '闓', + 'n' => '闑', + 'o' => '隳', + 'p' => '雗', + 'q' => '雚', + 'r' => '巂', + 's' => '雟', + 't' => '雘', + 'u' => '雝', + 'v' => '霣', + 'w' => '霢', + 'x' => '霥', + 'y' => '鞬', + 'z' => '鞮', + '{' => '鞨', + '|' => '鞫', + '}' => '鞤', + '~' => '鞪', + '' => '鞢', + '' => '鞥', + '' => '韗', + '' => '韙', + '' => '韖', + '' => '韘', + '' => '韺', + '' => '顐', + '' => '顑', + '' => '顒', + '' => '颸', + '' => '饁', + '' => '餼', + '' => '餺', + '' => '騏', + '' => '騋', + '' => '騉', + '' => '騍', + '' => '騄', + '' => '騑', + '' => '騊', + '' => '騅', + '' => '騇', + '' => '騆', + '' => '髀', + '' => '髜', + '' => '鬈', + '' => '鬄', + '' => '鬅', + '' => '鬩', + '' => '鬵', + '' => '魊', + '' => '魌', + '' => '魋', + '' => '鯇', + '' => '鯆', + '' => '鯃', + '' => '鮿', + '' => '鯁', + '' => '鮵', + '' => '鮸', + '' => '鯓', + '' => '鮶', + '' => '鯄', + '' => '鮹', + '' => '鮽', + '' => '鵜', + '' => '鵓', + '' => '鵏', + '' => '鵊', + '' => '鵛', + '' => '鵋', + '' => '鵙', + '' => '鵖', + '' => '鵌', + '' => '鵗', + '' => '鵒', + '' => '鵔', + '' => '鵟', + '' => '鵘', + '' => '鵚', + '' => '麎', + '' => '麌', + '' => '黟', + '' => '鼁', + '' => '鼀', + '' => '鼖', + '' => '鼥', + '' => '鼫', + '' => '鼪', + '' => '鼩', + '' => '鼨', + '' => '齌', + '' => '齕', + '' => '儴', + '' => '儵', + '' => '劖', + '' => '勷', + '' => '厴', + '' => '嚫', + '' => '嚭', + '' => '嚦', + '' => '嚧', + '' => '嚪', + '' => '嚬', + '' => '壚', + '' => '壝', + '' => '壛', + '' => '夒', + '' => '嬽', + '' => '嬾', + '' => '嬿', + '' => '巃', + '' => '幰', + '@' => '徿', + 'A' => '懻', + 'B' => '攇', + 'C' => '攐', + 'D' => '攍', + 'E' => '攉', + 'F' => '攌', + 'G' => '攎', + 'H' => '斄', + 'I' => '旞', + 'J' => '旝', + 'K' => '曞', + 'L' => '櫧', + 'M' => '櫠', + 'N' => '櫌', + 'O' => '櫑', + 'P' => '櫙', + 'Q' => '櫋', + 'R' => '櫟', + 'S' => '櫜', + 'T' => '櫐', + 'U' => '櫫', + 'V' => '櫏', + 'W' => '櫍', + 'X' => '櫞', + 'Y' => '歠', + 'Z' => '殰', + '[' => '氌', + '\\' => '瀙', + ']' => '瀧', + '^' => '瀠', + '_' => '瀖', + '`' => '瀫', + 'a' => '瀡', + 'b' => '瀢', + 'c' => '瀣', + 'd' => '瀩', + 'e' => '瀗', + 'f' => '瀤', + 'g' => '瀜', + 'h' => '瀪', + 'i' => '爌', + 'j' => '爊', + 'k' => '爇', + 'l' => '爂', + 'm' => '爅', + 'n' => '犥', + 'o' => '犦', + 'p' => '犤', + 'q' => '犣', + 'r' => '犡', + 's' => '瓋', + 't' => '瓅', + 'u' => '璷', + 'v' => '瓃', + 'w' => '甖', + 'x' => '癠', + 'y' => '矉', + 'z' => '矊', + '{' => '矄', + '|' => '矱', + '}' => '礝', + '~' => '礛', + '' => '礡', + '' => '礜', + '' => '礗', + '' => '礞', + '' => '禰', + '' => '穧', + '' => '穨', + '' => '簳', + '' => '簼', + '' => '簹', + '' => '簬', + '' => '簻', + '' => '糬', + '' => '糪', + '' => '繶', + '' => '繵', + '' => '繸', + '' => '繰', + '' => '繷', + '' => '繯', + '' => '繺', + '' => '繲', + '' => '繴', + '' => '繨', + '' => '罋', + '' => '罊', + '' => '羃', + '' => '羆', + '' => '羷', + '' => '翽', + '' => '翾', + '' => '聸', + '' => '臗', + '' => '臕', + '' => '艤', + '' => '艡', + '' => '艣', + '' => '藫', + '' => '藱', + '' => '藭', + '' => '藙', + '' => '藡', + '' => '藨', + '' => '藚', + '' => '藗', + '' => '藬', + '' => '藲', + '' => '藸', + '' => '藘', + '' => '藟', + '' => '藣', + '' => '藜', + '' => '藑', + '' => '藰', + '' => '藦', + '' => '藯', + '' => '藞', + '' => '藢', + '' => '蠀', + '' => '蟺', + '' => '蠃', + '' => '蟶', + '' => '蟷', + '' => '蠉', + '' => '蠌', + '' => '蠋', + '' => '蠆', + '' => '蟼', + '' => '蠈', + '' => '蟿', + '' => '蠊', + '' => '蠂', + '' => '襢', + '' => '襚', + '' => '襛', + '' => '襗', + '' => '襡', + '' => '襜', + '' => '襘', + '' => '襝', + '' => '襙', + '' => '覈', + '' => '覷', + '' => '覶', + '' => '觶', + '' => '譐', + '' => '譈', + '' => '譊', + '' => '譀', + '' => '譓', + '' => '譖', + '' => '譔', + '' => '譋', + '' => '譕', + '@' => '譑', + 'A' => '譂', + 'B' => '譒', + 'C' => '譗', + 'D' => '豃', + 'E' => '豷', + 'F' => '豶', + 'G' => '貚', + 'H' => '贆', + 'I' => '贇', + 'J' => '贉', + 'K' => '趬', + 'L' => '趪', + 'M' => '趭', + 'N' => '趫', + 'O' => '蹭', + 'P' => '蹸', + 'Q' => '蹳', + 'R' => '蹪', + 'S' => '蹯', + 'T' => '蹻', + 'U' => '軂', + 'V' => '轒', + 'W' => '轑', + 'X' => '轏', + 'Y' => '轐', + 'Z' => '轓', + '[' => '辴', + '\\' => '酀', + ']' => '鄿', + '^' => '醰', + '_' => '醭', + '`' => '鏞', + 'a' => '鏇', + 'b' => '鏏', + 'c' => '鏂', + 'd' => '鏚', + 'e' => '鏐', + 'f' => '鏹', + 'g' => '鏬', + 'h' => '鏌', + 'i' => '鏙', + 'j' => '鎩', + 'k' => '鏦', + 'l' => '鏊', + 'm' => '鏔', + 'n' => '鏮', + 'o' => '鏣', + 'p' => '鏕', + 'q' => '鏄', + 'r' => '鏎', + 's' => '鏀', + 't' => '鏒', + 'u' => '鏧', + 'v' => '镽', + 'w' => '闚', + 'x' => '闛', + 'y' => '雡', + 'z' => '霩', + '{' => '霫', + '|' => '霬', + '}' => '霨', + '~' => '霦', + '' => '鞳', + '' => '鞷', + '' => '鞶', + '' => '韝', + '' => '韞', + '' => '韟', + '' => '顜', + '' => '顙', + '' => '顝', + '' => '顗', + '' => '颿', + '' => '颽', + '' => '颻', + '' => '颾', + '' => '饈', + '' => '饇', + '' => '饃', + '' => '馦', + '' => '馧', + '' => '騚', + '' => '騕', + '' => '騥', + '' => '騝', + '' => '騤', + '' => '騛', + '' => '騢', + '' => '騠', + '' => '騧', + '' => '騣', + '' => '騞', + '' => '騜', + '' => '騔', + '' => '髂', + '' => '鬋', + '' => '鬊', + '' => '鬎', + '' => '鬌', + '' => '鬷', + '' => '鯪', + '' => '鯫', + '' => '鯠', + '' => '鯞', + '' => '鯤', + '' => '鯦', + '' => '鯢', + '' => '鯰', + '' => '鯔', + '' => '鯗', + '' => '鯬', + '' => '鯜', + '' => '鯙', + '' => '鯥', + '' => '鯕', + '' => '鯡', + '' => '鯚', + '' => '鵷', + '' => '鶁', + '' => '鶊', + '' => '鶄', + '' => '鶈', + '' => '鵱', + '' => '鶀', + '' => '鵸', + '' => '鶆', + '' => '鶋', + '' => '鶌', + '' => '鵽', + '' => '鵫', + '' => '鵴', + '' => '鵵', + '' => '鵰', + '' => '鵩', + '' => '鶅', + '' => '鵳', + '' => '鵻', + '' => '鶂', + '' => '鵯', + '' => '鵹', + '' => '鵿', + '' => '鶇', + '' => '鵨', + '' => '麔', + '' => '麑', + '' => '黀', + '' => '黼', + '' => '鼭', + '' => '齀', + '' => '齁', + '' => '齍', + '' => '齖', + '' => '齗', + '' => '齘', + '' => '匷', + '' => '嚲', + '@' => '嚵', + 'A' => '嚳', + 'B' => '壣', + 'C' => '孅', + 'D' => '巆', + 'E' => '巇', + 'F' => '廮', + 'G' => '廯', + 'H' => '忀', + 'I' => '忁', + 'J' => '懹', + 'K' => '攗', + 'L' => '攖', + 'M' => '攕', + 'N' => '攓', + 'O' => '旟', + 'P' => '曨', + 'Q' => '曣', + 'R' => '曤', + 'S' => '櫳', + 'T' => '櫰', + 'U' => '櫪', + 'V' => '櫨', + 'W' => '櫹', + 'X' => '櫱', + 'Y' => '櫮', + 'Z' => '櫯', + '[' => '瀼', + '\\' => '瀵', + ']' => '瀯', + '^' => '瀷', + '_' => '瀴', + '`' => '瀱', + 'a' => '灂', + 'b' => '瀸', + 'c' => '瀿', + 'd' => '瀺', + 'e' => '瀹', + 'f' => '灀', + 'g' => '瀻', + 'h' => '瀳', + 'i' => '灁', + 'j' => '爓', + 'k' => '爔', + 'l' => '犨', + 'm' => '獽', + 'n' => '獼', + 'o' => '璺', + 'p' => '皫', + 'q' => '皪', + 'r' => '皾', + 's' => '盭', + 't' => '矌', + 'u' => '矎', + 'v' => '矏', + 'w' => '矍', + 'x' => '矲', + 'y' => '礥', + 'z' => '礣', + '{' => '礧', + '|' => '礨', + '}' => '礤', + '~' => '礩', + '' => '禲', + '' => '穮', + '' => '穬', + '' => '穭', + '' => '竷', + '' => '籉', + '' => '籈', + '' => '籊', + '' => '籇', + '' => '籅', + '' => '糮', + '' => '繻', + '' => '繾', + '' => '纁', + '' => '纀', + '' => '羺', + '' => '翿', + '' => '聹', + '' => '臛', + '' => '臙', + '' => '舋', + '' => '艨', + '' => '艩', + '' => '蘢', + '' => '藿', + '' => '蘁', + '' => '藾', + '' => '蘛', + '' => '蘀', + '' => '藶', + '' => '蘄', + '' => '蘉', + '' => '蘅', + '' => '蘌', + '' => '藽', + '' => '蠙', + '' => '蠐', + '' => '蠑', + '' => '蠗', + '' => '蠓', + '' => '蠖', + '' => '襣', + '' => '襦', + '' => '覹', + '' => '觷', + '' => '譠', + '' => '譪', + '' => '譝', + '' => '譨', + '' => '譣', + '' => '譥', + '' => '譧', + '' => '譭', + '' => '趮', + '' => '躆', + '' => '躈', + '' => '躄', + '' => '轙', + '' => '轖', + '' => '轗', + '' => '轕', + '' => '轘', + '' => '轚', + '' => '邍', + '' => '酃', + '' => '酁', + '' => '醷', + '' => '醵', + '' => '醲', + '' => '醳', + '' => '鐋', + '' => '鐓', + '' => '鏻', + '' => '鐠', + '' => '鐏', + '' => '鐔', + '' => '鏾', + '' => '鐕', + '' => '鐐', + '' => '鐨', + '' => '鐙', + '' => '鐍', + '' => '鏵', + '' => '鐀', + '' => '鏷', + '' => '鐇', + '' => '鐎', + '' => '鐖', + '' => '鐒', + '' => '鏺', + '' => '鐉', + '' => '鏸', + '' => '鐊', + '' => '鏿', + '@' => '鏼', + 'A' => '鐌', + 'B' => '鏶', + 'C' => '鐑', + 'D' => '鐆', + 'E' => '闞', + 'F' => '闠', + 'G' => '闟', + 'H' => '霮', + 'I' => '霯', + 'J' => '鞹', + 'K' => '鞻', + 'L' => '韽', + 'M' => '韾', + 'N' => '顠', + 'O' => '顢', + 'P' => '顣', + 'Q' => '顟', + 'R' => '飁', + 'S' => '飂', + 'T' => '饐', + 'U' => '饎', + 'V' => '饙', + 'W' => '饌', + 'X' => '饋', + 'Y' => '饓', + 'Z' => '騲', + '[' => '騴', + '\\' => '騱', + ']' => '騬', + '^' => '騪', + '_' => '騶', + '`' => '騩', + 'a' => '騮', + 'b' => '騸', + 'c' => '騭', + 'd' => '髇', + 'e' => '髊', + 'f' => '髆', + 'g' => '鬐', + 'h' => '鬒', + 'i' => '鬑', + 'j' => '鰋', + 'k' => '鰈', + 'l' => '鯷', + 'm' => '鰅', + 'n' => '鰒', + 'o' => '鯸', + 'p' => '鱀', + 'q' => '鰇', + 'r' => '鰎', + 's' => '鰆', + 't' => '鰗', + 'u' => '鰔', + 'v' => '鰉', + 'w' => '鶟', + 'x' => '鶙', + 'y' => '鶤', + 'z' => '鶝', + '{' => '鶒', + '|' => '鶘', + '}' => '鶐', + '~' => '鶛', + '' => '鶠', + '' => '鶔', + '' => '鶜', + '' => '鶪', + '' => '鶗', + '' => '鶡', + '' => '鶚', + '' => '鶢', + '' => '鶨', + '' => '鶞', + '' => '鶣', + '' => '鶿', + '' => '鶩', + '' => '鶖', + '' => '鶦', + '' => '鶧', + '' => '麙', + '' => '麛', + '' => '麚', + '' => '黥', + '' => '黤', + '' => '黧', + '' => '黦', + '' => '鼰', + '' => '鼮', + '' => '齛', + '' => '齠', + '' => '齞', + '' => '齝', + '' => '齙', + '' => '龑', + '' => '儺', + '' => '儹', + '' => '劘', + '' => '劗', + '' => '囃', + '' => '嚽', + '' => '嚾', + '' => '孈', + '' => '孇', + '' => '巋', + '' => '巏', + '' => '廱', + '' => '懽', + '' => '攛', + '' => '欂', + '' => '櫼', + '' => '欃', + '' => '櫸', + '' => '欀', + '' => '灃', + '' => '灄', + '' => '灊', + '' => '灈', + '' => '灉', + '' => '灅', + '' => '灆', + '' => '爝', + '' => '爚', + '' => '爙', + '' => '獾', + '' => '甗', + '' => '癪', + '' => '矐', + '' => '礭', + '' => '礱', + '' => '礯', + '' => '籔', + '' => '籓', + '' => '糲', + '' => '纊', + '' => '纇', + '' => '纈', + '' => '纋', + '' => '纆', + '' => '纍', + '' => '罍', + '' => '羻', + '' => '耰', + '' => '臝', + '' => '蘘', + '' => '蘪', + '' => '蘦', + '' => '蘟', + '' => '蘣', + '' => '蘜', + '' => '蘙', + '' => '蘧', + '' => '蘮', + '' => '蘡', + '' => '蘠', + '' => '蘩', + '' => '蘞', + '' => '蘥', + '@' => '蠩', + 'A' => '蠝', + 'B' => '蠛', + 'C' => '蠠', + 'D' => '蠤', + 'E' => '蠜', + 'F' => '蠫', + 'G' => '衊', + 'H' => '襭', + 'I' => '襩', + 'J' => '襮', + 'K' => '襫', + 'L' => '觺', + 'M' => '譹', + 'N' => '譸', + 'O' => '譅', + 'P' => '譺', + 'Q' => '譻', + 'R' => '贐', + 'S' => '贔', + 'T' => '趯', + 'U' => '躎', + 'V' => '躌', + 'W' => '轞', + 'X' => '轛', + 'Y' => '轝', + 'Z' => '酆', + '[' => '酄', + '\\' => '酅', + ']' => '醹', + '^' => '鐿', + '_' => '鐻', + '`' => '鐶', + 'a' => '鐩', + 'b' => '鐽', + 'c' => '鐼', + 'd' => '鐰', + 'e' => '鐹', + 'f' => '鐪', + 'g' => '鐷', + 'h' => '鐬', + 'i' => '鑀', + 'j' => '鐱', + 'k' => '闥', + 'l' => '闤', + 'm' => '闣', + 'n' => '霵', + 'o' => '霺', + 'p' => '鞿', + 'q' => '韡', + 'r' => '顤', + 's' => '飉', + 't' => '飆', + 'u' => '飀', + 'v' => '饘', + 'w' => '饖', + 'x' => '騹', + 'y' => '騽', + 'z' => '驆', + '{' => '驄', + '|' => '驂', + '}' => '驁', + '~' => '騺', + '' => '騿', + '' => '髍', + '' => '鬕', + '' => '鬗', + '' => '鬘', + '' => '鬖', + '' => '鬺', + '' => '魒', + '' => '鰫', + '' => '鰝', + '' => '鰜', + '' => '鰬', + '' => '鰣', + '' => '鰨', + '' => '鰩', + '' => '鰤', + '' => '鰡', + '' => '鶷', + '' => '鶶', + '' => '鶼', + '' => '鷁', + '' => '鷇', + '' => '鷊', + '' => '鷏', + '' => '鶾', + '' => '鷅', + '' => '鷃', + '' => '鶻', + '' => '鶵', + '' => '鷎', + '' => '鶹', + '' => '鶺', + '' => '鶬', + '' => '鷈', + '' => '鶱', + '' => '鶭', + '' => '鷌', + '' => '鶳', + '' => '鷍', + '' => '鶲', + '' => '鹺', + '' => '麜', + '' => '黫', + '' => '黮', + '' => '黭', + '' => '鼛', + '' => '鼘', + '' => '鼚', + '' => '鼱', + '' => '齎', + '' => '齥', + '' => '齤', + '' => '龒', + '' => '亹', + '' => '囆', + '' => '囅', + '' => '囋', + '' => '奱', + '' => '孋', + '' => '孌', + '' => '巕', + '' => '巑', + '' => '廲', + '' => '攡', + '' => '攠', + '' => '攦', + '' => '攢', + '' => '欋', + '' => '欈', + '' => '欉', + '' => '氍', + '' => '灕', + '' => '灖', + '' => '灗', + '' => '灒', + '' => '爞', + '' => '爟', + '' => '犩', + '' => '獿', + '' => '瓘', + '' => '瓕', + '' => '瓙', + '' => '瓗', + '' => '癭', + '' => '皭', + '' => '礵', + '' => '禴', + '' => '穰', + '' => '穱', + '' => '籗', + '' => '籜', + '' => '籙', + '' => '籛', + '' => '籚', + '@' => '糴', + 'A' => '糱', + 'B' => '纑', + 'C' => '罏', + 'D' => '羇', + 'E' => '臞', + 'F' => '艫', + 'G' => '蘴', + 'H' => '蘵', + 'I' => '蘳', + 'J' => '蘬', + 'K' => '蘲', + 'L' => '蘶', + 'M' => '蠬', + 'N' => '蠨', + 'O' => '蠦', + 'P' => '蠪', + 'Q' => '蠥', + 'R' => '襱', + 'S' => '覿', + 'T' => '覾', + 'U' => '觻', + 'V' => '譾', + 'W' => '讄', + 'X' => '讂', + 'Y' => '讆', + 'Z' => '讅', + '[' => '譿', + '\\' => '贕', + ']' => '躕', + '^' => '躔', + '_' => '躚', + '`' => '躒', + 'a' => '躐', + 'b' => '躖', + 'c' => '躗', + 'd' => '轠', + 'e' => '轢', + 'f' => '酇', + 'g' => '鑌', + 'h' => '鑐', + 'i' => '鑊', + 'j' => '鑋', + 'k' => '鑏', + 'l' => '鑇', + 'm' => '鑅', + 'n' => '鑈', + 'o' => '鑉', + 'p' => '鑆', + 'q' => '霿', + 'r' => '韣', + 's' => '顪', + 't' => '顩', + 'u' => '飋', + 'v' => '饔', + 'w' => '饛', + 'x' => '驎', + 'y' => '驓', + 'z' => '驔', + '{' => '驌', + '|' => '驏', + '}' => '驈', + '~' => '驊', + '' => '驉', + '' => '驒', + '' => '驐', + '' => '髐', + '' => '鬙', + '' => '鬫', + '' => '鬻', + '' => '魖', + '' => '魕', + '' => '鱆', + '' => '鱈', + '' => '鰿', + '' => '鱄', + '' => '鰹', + '' => '鰳', + '' => '鱁', + '' => '鰼', + '' => '鰷', + '' => '鰴', + '' => '鰲', + '' => '鰽', + '' => '鰶', + '' => '鷛', + '' => '鷒', + '' => '鷞', + '' => '鷚', + '' => '鷋', + '' => '鷐', + '' => '鷜', + '' => '鷑', + '' => '鷟', + '' => '鷩', + '' => '鷙', + '' => '鷘', + '' => '鷖', + '' => '鷵', + '' => '鷕', + '' => '鷝', + '' => '麶', + '' => '黰', + '' => '鼵', + '' => '鼳', + '' => '鼲', + '' => '齂', + '' => '齫', + '' => '龕', + '' => '龢', + '' => '儽', + '' => '劙', + '' => '壨', + '' => '壧', + '' => '奲', + '' => '孍', + '' => '巘', + '' => '蠯', + '' => '彏', + '' => '戁', + '' => '戃', + '' => '戄', + '' => '攩', + '' => '攥', + '' => '斖', + '' => '曫', + '' => '欑', + '' => '欒', + '' => '欏', + '' => '毊', + '' => '灛', + '' => '灚', + '' => '爢', + '' => '玂', + '' => '玁', + '' => '玃', + '' => '癰', + '' => '矔', + '' => '籧', + '' => '籦', + '' => '纕', + '' => '艬', + '' => '蘺', + '' => '虀', + '' => '蘹', + '' => '蘼', + '' => '蘱', + '' => '蘻', + '' => '蘾', + '' => '蠰', + '' => '蠲', + '' => '蠮', + '' => '蠳', + '' => '襶', + '' => '襴', + '' => '襳', + '' => '觾', + '@' => '讌', + 'A' => '讎', + 'B' => '讋', + 'C' => '讈', + 'D' => '豅', + 'E' => '贙', + 'F' => '躘', + 'G' => '轤', + 'H' => '轣', + 'I' => '醼', + 'J' => '鑢', + 'K' => '鑕', + 'L' => '鑝', + 'M' => '鑗', + 'N' => '鑞', + 'O' => '韄', + 'P' => '韅', + 'Q' => '頀', + 'R' => '驖', + 'S' => '驙', + 'T' => '鬞', + 'U' => '鬟', + 'V' => '鬠', + 'W' => '鱒', + 'X' => '鱘', + 'Y' => '鱐', + 'Z' => '鱊', + '[' => '鱍', + '\\' => '鱋', + ']' => '鱕', + '^' => '鱙', + '_' => '鱌', + '`' => '鱎', + 'a' => '鷻', + 'b' => '鷷', + 'c' => '鷯', + 'd' => '鷣', + 'e' => '鷫', + 'f' => '鷸', + 'g' => '鷤', + 'h' => '鷶', + 'i' => '鷡', + 'j' => '鷮', + 'k' => '鷦', + 'l' => '鷲', + 'm' => '鷰', + 'n' => '鷢', + 'o' => '鷬', + 'p' => '鷴', + 'q' => '鷳', + 'r' => '鷨', + 's' => '鷭', + 't' => '黂', + 'u' => '黐', + 'v' => '黲', + 'w' => '黳', + 'x' => '鼆', + 'y' => '鼜', + 'z' => '鼸', + '{' => '鼷', + '|' => '鼶', + '}' => '齃', + '~' => '齏', + '' => '齱', + '' => '齰', + '' => '齮', + '' => '齯', + '' => '囓', + '' => '囍', + '' => '孎', + '' => '屭', + '' => '攭', + '' => '曭', + '' => '曮', + '' => '欓', + '' => '灟', + '' => '灡', + '' => '灝', + '' => '灠', + '' => '爣', + '' => '瓛', + '' => '瓥', + '' => '矕', + '' => '礸', + '' => '禷', + '' => '禶', + '' => '籪', + '' => '纗', + '' => '羉', + '' => '艭', + '' => '虃', + '' => '蠸', + '' => '蠷', + '' => '蠵', + '' => '衋', + '' => '讔', + '' => '讕', + '' => '躞', + '' => '躟', + '' => '躠', + '' => '躝', + '' => '醾', + '' => '醽', + '' => '釂', + '' => '鑫', + '' => '鑨', + '' => '鑩', + '' => '雥', + '' => '靆', + '' => '靃', + '' => '靇', + '' => '韇', + '' => '韥', + '' => '驞', + '' => '髕', + '' => '魙', + '' => '鱣', + '' => '鱧', + '' => '鱦', + '' => '鱢', + '' => '鱞', + '' => '鱠', + '' => '鸂', + '' => '鷾', + '' => '鸇', + '' => '鸃', + '' => '鸆', + '' => '鸅', + '' => '鸀', + '' => '鸁', + '' => '鸉', + '' => '鷿', + '' => '鷽', + '' => '鸄', + '' => '麠', + '' => '鼞', + '' => '齆', + '' => '齴', + '' => '齵', + '' => '齶', + '' => '囔', + '' => '攮', + '' => '斸', + '' => '欘', + '' => '欙', + '' => '欗', + '' => '欚', + '' => '灢', + '' => '爦', + '' => '犪', + '' => '矘', + '' => '矙', + '' => '礹', + '' => '籩', + '' => '籫', + '' => '糶', + '' => '纚', + '@' => '纘', + 'A' => '纛', + 'B' => '纙', + 'C' => '臠', + 'D' => '臡', + 'E' => '虆', + 'F' => '虇', + 'G' => '虈', + 'H' => '襹', + 'I' => '襺', + 'J' => '襼', + 'K' => '襻', + 'L' => '觿', + 'M' => '讘', + 'N' => '讙', + 'O' => '躥', + 'P' => '躤', + 'Q' => '躣', + 'R' => '鑮', + 'S' => '鑭', + 'T' => '鑯', + 'U' => '鑱', + 'V' => '鑳', + 'W' => '靉', + 'X' => '顲', + 'Y' => '饟', + 'Z' => '鱨', + '[' => '鱮', + '\\' => '鱭', + ']' => '鸋', + '^' => '鸍', + '_' => '鸐', + '`' => '鸏', + 'a' => '鸒', + 'b' => '鸑', + 'c' => '麡', + 'd' => '黵', + 'e' => '鼉', + 'f' => '齇', + 'g' => '齸', + 'h' => '齻', + 'i' => '齺', + 'j' => '齹', + 'k' => '圞', + 'l' => '灦', + 'm' => '籯', + 'n' => '蠼', + 'o' => '趲', + 'p' => '躦', + 'q' => '釃', + 'r' => '鑴', + 's' => '鑸', + 't' => '鑶', + 'u' => '鑵', + 'v' => '驠', + 'w' => '鱴', + 'x' => '鱳', + 'y' => '鱱', + 'z' => '鱵', + '{' => '鸔', + '|' => '鸓', + '}' => '黶', + '~' => '鼊', + '' => '龤', + '' => '灨', + '' => '灥', + '' => '糷', + '' => '虪', + '' => '蠾', + '' => '蠽', + '' => '蠿', + '' => '讞', + '' => '貜', + '' => '躩', + '' => '軉', + '' => '靋', + '' => '顳', + '' => '顴', + '' => '飌', + '' => '饡', + '' => '馫', + '' => '驤', + '' => '驦', + '' => '驧', + '' => '鬤', + '' => '鸕', + '' => '鸗', + '' => '齈', + '' => '戇', + '' => '欞', + '' => '爧', + '' => '虌', + '' => '躨', + '' => '钂', + '' => '钀', + '' => '钁', + '' => '驩', + '' => '驨', + '' => '鬮', + '' => '鸙', + '' => '爩', + '' => '虋', + '' => '讟', + '' => '钃', + '' => '鱹', + '' => '麷', + '' => '癵', + '' => '驫', + '' => '鱺', + '' => '鸝', + '' => '灩', + '' => '灪', + '' => '麤', + '' => '齾', + '' => '齉', + '' => '龘', +); + +$result =& $data; +unset($data); + +return $result; diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp037.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp037.php new file mode 100644 index 0000000..a014e4b Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp037.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp1006.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp1006.php new file mode 100644 index 0000000..2b5e7be Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp1006.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp1026.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp1026.php new file mode 100644 index 0000000..aba455b Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp1026.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp424.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp424.php new file mode 100644 index 0000000..e8e2370 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp424.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp437.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp437.php new file mode 100644 index 0000000..e3ebb45 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp437.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp500.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp500.php new file mode 100644 index 0000000..3771c8f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp500.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp737.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp737.php new file mode 100644 index 0000000..2d67d33 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp737.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp775.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp775.php new file mode 100644 index 0000000..1fbc4cd Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp775.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp850.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp850.php new file mode 100644 index 0000000..0b314c8 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp850.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp852.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp852.php new file mode 100644 index 0000000..f8c318c Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp852.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp855.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp855.php new file mode 100644 index 0000000..48440ba Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp855.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp856.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp856.php new file mode 100644 index 0000000..c9cac0c Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp856.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp857.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp857.php new file mode 100644 index 0000000..3e7770a Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp857.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp860.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp860.php new file mode 100644 index 0000000..2a52d47 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp860.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp861.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp861.php new file mode 100644 index 0000000..4ba6573 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp861.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp862.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp862.php new file mode 100644 index 0000000..d2a29a2 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp862.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp863.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp863.php new file mode 100644 index 0000000..1f36b9a Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp863.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp864.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp864.php new file mode 100644 index 0000000..953e463 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp864.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp865.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp865.php new file mode 100644 index 0000000..2668bcc Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp865.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp866.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp866.php new file mode 100644 index 0000000..a7b47f8 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp866.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp869.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp869.php new file mode 100644 index 0000000..0f04054 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp869.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp874.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp874.php new file mode 100644 index 0000000..4799456 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp874.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp875.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp875.php new file mode 100644 index 0000000..8561645 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp875.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp932.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp932.php new file mode 100644 index 0000000..0bf828f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp932.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp936.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp936.php new file mode 100644 index 0000000..a593d05 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp936.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp949.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp949.php new file mode 100644 index 0000000..d4e99f1 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp949.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp950.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp950.php new file mode 100644 index 0000000..267b190 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.cp950.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-1.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-1.php new file mode 100644 index 0000000..d7a217c Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-1.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-10.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-10.php new file mode 100644 index 0000000..d60f647 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-10.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-11.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-11.php new file mode 100644 index 0000000..d69220b Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-11.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-13.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-13.php new file mode 100644 index 0000000..838783f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-13.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-14.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-14.php new file mode 100644 index 0000000..65a48ee Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-14.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-15.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-15.php new file mode 100644 index 0000000..42e50e0 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-15.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-16.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-16.php new file mode 100644 index 0000000..46758a6 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-16.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-2.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-2.php new file mode 100644 index 0000000..5f23f51 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-2.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-3.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-3.php new file mode 100644 index 0000000..b31bb83 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-3.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-4.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-4.php new file mode 100644 index 0000000..9cbf9f3 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-4.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-5.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-5.php new file mode 100644 index 0000000..fd03882 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-5.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-6.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-6.php new file mode 100644 index 0000000..ed6f72f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-6.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-7.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-7.php new file mode 100644 index 0000000..cf723ac Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-7.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-8.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-8.php new file mode 100644 index 0000000..c978731 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-8.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-9.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-9.php new file mode 100644 index 0000000..2a3e36a Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.iso-8859-9.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.koi8-r.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.koi8-r.php new file mode 100644 index 0000000..d83c212 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.koi8-r.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.koi8-u.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.koi8-u.php new file mode 100644 index 0000000..dbbf96b Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.koi8-u.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.us-ascii.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.us-ascii.php new file mode 100644 index 0000000..94a93b2 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.us-ascii.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1250.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1250.php new file mode 100644 index 0000000..d1d5e6f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1250.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1251.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1251.php new file mode 100644 index 0000000..f422a71 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1251.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1252.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1252.php new file mode 100644 index 0000000..ba6d203 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1252.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1253.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1253.php new file mode 100644 index 0000000..c04dc8f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1253.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1254.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1254.php new file mode 100644 index 0000000..1cfadcf Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1254.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1255.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1255.php new file mode 100644 index 0000000..f73cbb6 Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1255.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1256.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1256.php new file mode 100644 index 0000000..953704f Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1256.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1257.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1257.php new file mode 100644 index 0000000..78580ec Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1257.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1258.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1258.php new file mode 100644 index 0000000..de1609d Binary files /dev/null and b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/from.windows-1258.php differ diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/translit.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/translit.php new file mode 100644 index 0000000..f322ff0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/Resources/charset/translit.php @@ -0,0 +1,4106 @@ + 'μ', + '¼' => ' 1⁄4 ', + '½' => ' 1⁄2 ', + '¾' => ' 3⁄4 ', + 'IJ' => 'IJ', + 'ij' => 'ij', + 'Ŀ' => 'L·', + 'ŀ' => 'l·', + 'ʼn' => 'ʼn', + 'ſ' => 's', + 'DŽ' => 'DŽ', + 'Dž' => 'Dž', + 'dž' => 'dž', + 'LJ' => 'LJ', + 'Lj' => 'Lj', + 'lj' => 'lj', + 'NJ' => 'NJ', + 'Nj' => 'Nj', + 'nj' => 'nj', + 'DZ' => 'DZ', + 'Dz' => 'Dz', + 'dz' => 'dz', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϒ' => 'Υ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϲ' => 'ς', + 'ϴ' => 'Θ', + 'ϵ' => 'ε', + 'Ϲ' => 'Σ', + 'և' => 'եւ', + 'ٵ' => 'اٴ', + 'ٶ' => 'وٴ', + 'ٷ' => 'ۇٴ', + 'ٸ' => 'يٴ', + 'ำ' => 'ํา', + 'ຳ' => 'ໍາ', + 'ໜ' => 'ຫນ', + 'ໝ' => 'ຫມ', + 'ཷ' => 'ྲཱྀ', + 'ཹ' => 'ླཱྀ', + 'ẚ' => 'aʾ', + '․' => '.', + '‥' => '..', + '…' => '...', + '″' => '′′', + '‴' => '′′′', + '‶' => '‵‵', + '‷' => '‵‵‵', + '‼' => '!!', + '⁇' => '??', + '⁈' => '?!', + '⁉' => '!?', + '⁗' => '′′′′', + '₨' => 'Rs', + '℀' => 'a/c', + '℁' => 'a/s', + 'ℂ' => 'C', + '℃' => '°C', + '℅' => 'c/o', + '℆' => 'c/u', + 'ℇ' => 'Ɛ', + '℉' => '°F', + 'ℊ' => 'g', + 'ℋ' => 'H', + 'ℌ' => 'H', + 'ℍ' => 'H', + 'ℎ' => 'h', + 'ℏ' => 'ħ', + 'ℐ' => 'I', + 'ℑ' => 'I', + 'ℒ' => 'L', + 'ℓ' => 'l', + 'ℕ' => 'N', + '№' => 'No', + 'ℙ' => 'P', + 'ℚ' => 'Q', + 'ℛ' => 'R', + 'ℜ' => 'R', + 'ℝ' => 'R', + '℡' => 'TEL', + 'ℤ' => 'Z', + 'ℨ' => 'Z', + 'ℬ' => 'B', + 'ℭ' => 'C', + 'ℯ' => 'e', + 'ℰ' => 'E', + 'ℱ' => 'F', + 'ℳ' => 'M', + 'ℴ' => 'o', + 'ℵ' => 'א', + 'ℶ' => 'ב', + 'ℷ' => 'ג', + 'ℸ' => 'ד', + 'ℹ' => 'i', + '℻' => 'FAX', + 'ℼ' => 'π', + 'ℽ' => 'γ', + 'ℾ' => 'Γ', + 'ℿ' => 'Π', + '⅀' => '∑', + 'ⅅ' => 'D', + 'ⅆ' => 'd', + 'ⅇ' => 'e', + 'ⅈ' => 'i', + 'ⅉ' => 'j', + '⅐' => ' 1⁄7 ', + '⅑' => ' 1⁄9 ', + '⅒' => ' 1⁄10 ', + '⅓' => ' 1⁄3 ', + '⅔' => ' 2⁄3 ', + '⅕' => ' 1⁄5 ', + '⅖' => ' 2⁄5 ', + '⅗' => ' 3⁄5 ', + '⅘' => ' 4⁄5 ', + '⅙' => ' 1⁄6 ', + '⅚' => ' 5⁄6 ', + '⅛' => ' 1⁄8 ', + '⅜' => ' 3⁄8 ', + '⅝' => ' 5⁄8 ', + '⅞' => ' 7⁄8 ', + '⅟' => ' 1⁄ ', + 'Ⅰ' => 'I', + 'Ⅱ' => 'II', + 'Ⅲ' => 'III', + 'Ⅳ' => 'IV', + 'Ⅴ' => 'V', + 'Ⅵ' => 'VI', + 'Ⅶ' => 'VII', + 'Ⅷ' => 'VIII', + 'Ⅸ' => 'IX', + 'Ⅹ' => 'X', + 'Ⅺ' => 'XI', + 'Ⅻ' => 'XII', + 'Ⅼ' => 'L', + 'Ⅽ' => 'C', + 'Ⅾ' => 'D', + 'Ⅿ' => 'M', + 'ⅰ' => 'i', + 'ⅱ' => 'ii', + 'ⅲ' => 'iii', + 'ⅳ' => 'iv', + 'ⅴ' => 'v', + 'ⅵ' => 'vi', + 'ⅶ' => 'vii', + 'ⅷ' => 'viii', + 'ⅸ' => 'ix', + 'ⅹ' => 'x', + 'ⅺ' => 'xi', + 'ⅻ' => 'xii', + 'ⅼ' => 'l', + 'ⅽ' => 'c', + 'ⅾ' => 'd', + 'ⅿ' => 'm', + '↉' => ' 0⁄3 ', + '∬' => '∫∫', + '∭' => '∫∫∫', + '∯' => '∮∮', + '∰' => '∮∮∮', + '①' => '(1)', + '②' => '(2)', + '③' => '(3)', + '④' => '(4)', + '⑤' => '(5)', + '⑥' => '(6)', + '⑦' => '(7)', + '⑧' => '(8)', + '⑨' => '(9)', + '⑩' => '(10)', + '⑪' => '(11)', + '⑫' => '(12)', + '⑬' => '(13)', + '⑭' => '(14)', + '⑮' => '(15)', + '⑯' => '(16)', + '⑰' => '(17)', + '⑱' => '(18)', + '⑲' => '(19)', + '⑳' => '(20)', + '⑴' => '(1)', + '⑵' => '(2)', + '⑶' => '(3)', + '⑷' => '(4)', + '⑸' => '(5)', + '⑹' => '(6)', + '⑺' => '(7)', + '⑻' => '(8)', + '⑼' => '(9)', + '⑽' => '(10)', + '⑾' => '(11)', + '⑿' => '(12)', + '⒀' => '(13)', + '⒁' => '(14)', + '⒂' => '(15)', + '⒃' => '(16)', + '⒄' => '(17)', + '⒅' => '(18)', + '⒆' => '(19)', + '⒇' => '(20)', + '⒈' => '1.', + '⒉' => '2.', + '⒊' => '3.', + '⒋' => '4.', + '⒌' => '5.', + '⒍' => '6.', + '⒎' => '7.', + '⒏' => '8.', + '⒐' => '9.', + '⒑' => '10.', + '⒒' => '11.', + '⒓' => '12.', + '⒔' => '13.', + '⒕' => '14.', + '⒖' => '15.', + '⒗' => '16.', + '⒘' => '17.', + '⒙' => '18.', + '⒚' => '19.', + '⒛' => '20.', + '⒜' => '(a)', + '⒝' => '(b)', + '⒞' => '(c)', + '⒟' => '(d)', + '⒠' => '(e)', + '⒡' => '(f)', + '⒢' => '(g)', + '⒣' => '(h)', + '⒤' => '(i)', + '⒥' => '(j)', + '⒦' => '(k)', + '⒧' => '(l)', + '⒨' => '(m)', + '⒩' => '(n)', + '⒪' => '(o)', + '⒫' => '(p)', + '⒬' => '(q)', + '⒭' => '(r)', + '⒮' => '(s)', + '⒯' => '(t)', + '⒰' => '(u)', + '⒱' => '(v)', + '⒲' => '(w)', + '⒳' => '(x)', + '⒴' => '(y)', + '⒵' => '(z)', + 'Ⓐ' => '(A)', + 'Ⓑ' => '(B)', + 'Ⓒ' => '(C)', + 'Ⓓ' => '(D)', + 'Ⓔ' => '(E)', + 'Ⓕ' => '(F)', + 'Ⓖ' => '(G)', + 'Ⓗ' => '(H)', + 'Ⓘ' => '(I)', + 'Ⓙ' => '(J)', + 'Ⓚ' => '(K)', + 'Ⓛ' => '(L)', + 'Ⓜ' => '(M)', + 'Ⓝ' => '(N)', + 'Ⓞ' => '(O)', + 'Ⓟ' => '(P)', + 'Ⓠ' => '(Q)', + 'Ⓡ' => '(R)', + 'Ⓢ' => '(S)', + 'Ⓣ' => '(T)', + 'Ⓤ' => '(U)', + 'Ⓥ' => '(V)', + 'Ⓦ' => '(W)', + 'Ⓧ' => '(X)', + 'Ⓨ' => '(Y)', + 'Ⓩ' => '(Z)', + 'ⓐ' => '(a)', + 'ⓑ' => '(b)', + 'ⓒ' => '(c)', + 'ⓓ' => '(d)', + 'ⓔ' => '(e)', + 'ⓕ' => '(f)', + 'ⓖ' => '(g)', + 'ⓗ' => '(h)', + 'ⓘ' => '(i)', + 'ⓙ' => '(j)', + 'ⓚ' => '(k)', + 'ⓛ' => '(l)', + 'ⓜ' => '(m)', + 'ⓝ' => '(n)', + 'ⓞ' => '(o)', + 'ⓟ' => '(p)', + 'ⓠ' => '(q)', + 'ⓡ' => '(r)', + 'ⓢ' => '(s)', + 'ⓣ' => '(t)', + 'ⓤ' => '(u)', + 'ⓥ' => '(v)', + 'ⓦ' => '(w)', + 'ⓧ' => '(x)', + 'ⓨ' => '(y)', + 'ⓩ' => '(z)', + '⓪' => '(0)', + '⨌' => '∫∫∫∫', + '⩴' => '::=', + '⩵' => '==', + '⩶' => '===', + '⺟' => '母', + '⻳' => '龟', + '⼀' => '一', + '⼁' => '丨', + '⼂' => '丶', + '⼃' => '丿', + '⼄' => '乙', + '⼅' => '亅', + '⼆' => '二', + '⼇' => '亠', + '⼈' => '人', + '⼉' => '儿', + '⼊' => '入', + '⼋' => '八', + '⼌' => '冂', + '⼍' => '冖', + '⼎' => '冫', + '⼏' => '几', + '⼐' => '凵', + '⼑' => '刀', + '⼒' => '力', + '⼓' => '勹', + '⼔' => '匕', + '⼕' => '匚', + '⼖' => '匸', + '⼗' => '十', + '⼘' => '卜', + '⼙' => '卩', + '⼚' => '厂', + '⼛' => '厶', + '⼜' => '又', + '⼝' => '口', + '⼞' => '囗', + '⼟' => '土', + '⼠' => '士', + '⼡' => '夂', + '⼢' => '夊', + '⼣' => '夕', + '⼤' => '大', + '⼥' => '女', + '⼦' => '子', + '⼧' => '宀', + '⼨' => '寸', + '⼩' => '小', + '⼪' => '尢', + '⼫' => '尸', + '⼬' => '屮', + '⼭' => '山', + '⼮' => '巛', + '⼯' => '工', + '⼰' => '己', + '⼱' => '巾', + '⼲' => '干', + '⼳' => '幺', + '⼴' => '广', + '⼵' => '廴', + '⼶' => '廾', + '⼷' => '弋', + '⼸' => '弓', + '⼹' => '彐', + '⼺' => '彡', + '⼻' => '彳', + '⼼' => '心', + '⼽' => '戈', + '⼾' => '戶', + '⼿' => '手', + '⽀' => '支', + '⽁' => '攴', + '⽂' => '文', + '⽃' => '斗', + '⽄' => '斤', + '⽅' => '方', + '⽆' => '无', + '⽇' => '日', + '⽈' => '曰', + '⽉' => '月', + '⽊' => '木', + '⽋' => '欠', + '⽌' => '止', + '⽍' => '歹', + '⽎' => '殳', + '⽏' => '毋', + '⽐' => '比', + '⽑' => '毛', + '⽒' => '氏', + '⽓' => '气', + '⽔' => '水', + '⽕' => '火', + '⽖' => '爪', + '⽗' => '父', + '⽘' => '爻', + '⽙' => '爿', + '⽚' => '片', + '⽛' => '牙', + '⽜' => '牛', + '⽝' => '犬', + '⽞' => '玄', + '⽟' => '玉', + '⽠' => '瓜', + '⽡' => '瓦', + '⽢' => '甘', + '⽣' => '生', + '⽤' => '用', + '⽥' => '田', + '⽦' => '疋', + '⽧' => '疒', + '⽨' => '癶', + '⽩' => '白', + '⽪' => '皮', + '⽫' => '皿', + '⽬' => '目', + '⽭' => '矛', + '⽮' => '矢', + '⽯' => '石', + '⽰' => '示', + '⽱' => '禸', + '⽲' => '禾', + '⽳' => '穴', + '⽴' => '立', + '⽵' => '竹', + '⽶' => '米', + '⽷' => '糸', + '⽸' => '缶', + '⽹' => '网', + '⽺' => '羊', + '⽻' => '羽', + '⽼' => '老', + '⽽' => '而', + '⽾' => '耒', + '⽿' => '耳', + '⾀' => '聿', + '⾁' => '肉', + '⾂' => '臣', + '⾃' => '自', + '⾄' => '至', + '⾅' => '臼', + '⾆' => '舌', + '⾇' => '舛', + '⾈' => '舟', + '⾉' => '艮', + '⾊' => '色', + '⾋' => '艸', + '⾌' => '虍', + '⾍' => '虫', + '⾎' => '血', + '⾏' => '行', + '⾐' => '衣', + '⾑' => '襾', + '⾒' => '見', + '⾓' => '角', + '⾔' => '言', + '⾕' => '谷', + '⾖' => '豆', + '⾗' => '豕', + '⾘' => '豸', + '⾙' => '貝', + '⾚' => '赤', + '⾛' => '走', + '⾜' => '足', + '⾝' => '身', + '⾞' => '車', + '⾟' => '辛', + '⾠' => '辰', + '⾡' => '辵', + '⾢' => '邑', + '⾣' => '酉', + '⾤' => '釆', + '⾥' => '里', + '⾦' => '金', + '⾧' => '長', + '⾨' => '門', + '⾩' => '阜', + '⾪' => '隶', + '⾫' => '隹', + '⾬' => '雨', + '⾭' => '靑', + '⾮' => '非', + '⾯' => '面', + '⾰' => '革', + '⾱' => '韋', + '⾲' => '韭', + '⾳' => '音', + '⾴' => '頁', + '⾵' => '風', + '⾶' => '飛', + '⾷' => '食', + '⾸' => '首', + '⾹' => '香', + '⾺' => '馬', + '⾻' => '骨', + '⾼' => '高', + '⾽' => '髟', + '⾾' => '鬥', + '⾿' => '鬯', + '⿀' => '鬲', + '⿁' => '鬼', + '⿂' => '魚', + '⿃' => '鳥', + '⿄' => '鹵', + '⿅' => '鹿', + '⿆' => '麥', + '⿇' => '麻', + '⿈' => '黃', + '⿉' => '黍', + '⿊' => '黑', + '⿋' => '黹', + '⿌' => '黽', + '⿍' => '鼎', + '⿎' => '鼓', + '⿏' => '鼠', + '⿐' => '鼻', + '⿑' => '齊', + '⿒' => '齒', + '⿓' => '龍', + '⿔' => '龜', + '⿕' => '龠', + ' ' => ' ', + '〶' => '〒', + '〸' => '十', + '〹' => '卄', + '〺' => '卅', + 'ㄱ' => 'ᄀ', + 'ㄲ' => 'ᄁ', + 'ㄳ' => 'ᆪ', + 'ㄴ' => 'ᄂ', + 'ㄵ' => 'ᆬ', + 'ㄶ' => 'ᆭ', + 'ㄷ' => 'ᄃ', + 'ㄸ' => 'ᄄ', + 'ㄹ' => 'ᄅ', + 'ㄺ' => 'ᆰ', + 'ㄻ' => 'ᆱ', + 'ㄼ' => 'ᆲ', + 'ㄽ' => 'ᆳ', + 'ㄾ' => 'ᆴ', + 'ㄿ' => 'ᆵ', + 'ㅀ' => 'ᄚ', + 'ㅁ' => 'ᄆ', + 'ㅂ' => 'ᄇ', + 'ㅃ' => 'ᄈ', + 'ㅄ' => 'ᄡ', + 'ㅅ' => 'ᄉ', + 'ㅆ' => 'ᄊ', + 'ㅇ' => 'ᄋ', + 'ㅈ' => 'ᄌ', + 'ㅉ' => 'ᄍ', + 'ㅊ' => 'ᄎ', + 'ㅋ' => 'ᄏ', + 'ㅌ' => 'ᄐ', + 'ㅍ' => 'ᄑ', + 'ㅎ' => 'ᄒ', + 'ㅏ' => 'ᅡ', + 'ㅐ' => 'ᅢ', + 'ㅑ' => 'ᅣ', + 'ㅒ' => 'ᅤ', + 'ㅓ' => 'ᅥ', + 'ㅔ' => 'ᅦ', + 'ㅕ' => 'ᅧ', + 'ㅖ' => 'ᅨ', + 'ㅗ' => 'ᅩ', + 'ㅘ' => 'ᅪ', + 'ㅙ' => 'ᅫ', + 'ㅚ' => 'ᅬ', + 'ㅛ' => 'ᅭ', + 'ㅜ' => 'ᅮ', + 'ㅝ' => 'ᅯ', + 'ㅞ' => 'ᅰ', + 'ㅟ' => 'ᅱ', + 'ㅠ' => 'ᅲ', + 'ㅡ' => 'ᅳ', + 'ㅢ' => 'ᅴ', + 'ㅣ' => 'ᅵ', + 'ㅤ' => 'ᅠ', + 'ㅥ' => 'ᄔ', + 'ㅦ' => 'ᄕ', + 'ㅧ' => 'ᇇ', + 'ㅨ' => 'ᇈ', + 'ㅩ' => 'ᇌ', + 'ㅪ' => 'ᇎ', + 'ㅫ' => 'ᇓ', + 'ㅬ' => 'ᇗ', + 'ㅭ' => 'ᇙ', + 'ㅮ' => 'ᄜ', + 'ㅯ' => 'ᇝ', + 'ㅰ' => 'ᇟ', + 'ㅱ' => 'ᄝ', + 'ㅲ' => 'ᄞ', + 'ㅳ' => 'ᄠ', + 'ㅴ' => 'ᄢ', + 'ㅵ' => 'ᄣ', + 'ㅶ' => 'ᄧ', + 'ㅷ' => 'ᄩ', + 'ㅸ' => 'ᄫ', + 'ㅹ' => 'ᄬ', + 'ㅺ' => 'ᄭ', + 'ㅻ' => 'ᄮ', + 'ㅼ' => 'ᄯ', + 'ㅽ' => 'ᄲ', + 'ㅾ' => 'ᄶ', + 'ㅿ' => 'ᅀ', + 'ㆀ' => 'ᅇ', + 'ㆁ' => 'ᅌ', + 'ㆂ' => 'ᇱ', + 'ㆃ' => 'ᇲ', + 'ㆄ' => 'ᅗ', + 'ㆅ' => 'ᅘ', + 'ㆆ' => 'ᅙ', + 'ㆇ' => 'ᆄ', + 'ㆈ' => 'ᆅ', + 'ㆉ' => 'ᆈ', + 'ㆊ' => 'ᆑ', + 'ㆋ' => 'ᆒ', + 'ㆌ' => 'ᆔ', + 'ㆍ' => 'ᆞ', + 'ㆎ' => 'ᆡ', + '㈀' => '(ᄀ)', + '㈁' => '(ᄂ)', + '㈂' => '(ᄃ)', + '㈃' => '(ᄅ)', + '㈄' => '(ᄆ)', + '㈅' => '(ᄇ)', + '㈆' => '(ᄉ)', + '㈇' => '(ᄋ)', + '㈈' => '(ᄌ)', + '㈉' => '(ᄎ)', + '㈊' => '(ᄏ)', + '㈋' => '(ᄐ)', + '㈌' => '(ᄑ)', + '㈍' => '(ᄒ)', + '㈎' => '(가)', + '㈏' => '(나)', + '㈐' => '(다)', + '㈑' => '(라)', + '㈒' => '(마)', + '㈓' => '(바)', + '㈔' => '(사)', + '㈕' => '(아)', + '㈖' => '(자)', + '㈗' => '(차)', + '㈘' => '(카)', + '㈙' => '(타)', + '㈚' => '(파)', + '㈛' => '(하)', + '㈜' => '(주)', + '㈝' => '(오전)', + '㈞' => '(오후)', + '㈠' => '(一)', + '㈡' => '(二)', + '㈢' => '(三)', + '㈣' => '(四)', + '㈤' => '(五)', + '㈥' => '(六)', + '㈦' => '(七)', + '㈧' => '(八)', + '㈨' => '(九)', + '㈩' => '(十)', + '㈪' => '(月)', + '㈫' => '(火)', + '㈬' => '(水)', + '㈭' => '(木)', + '㈮' => '(金)', + '㈯' => '(土)', + '㈰' => '(日)', + '㈱' => '(株)', + '㈲' => '(有)', + '㈳' => '(社)', + '㈴' => '(名)', + '㈵' => '(特)', + '㈶' => '(財)', + '㈷' => '(祝)', + '㈸' => '(労)', + '㈹' => '(代)', + '㈺' => '(呼)', + '㈻' => '(学)', + '㈼' => '(監)', + '㈽' => '(企)', + '㈾' => '(資)', + '㈿' => '(協)', + '㉀' => '(祭)', + '㉁' => '(休)', + '㉂' => '(自)', + '㉃' => '(至)', + '㉄' => '(問)', + '㉅' => '(幼)', + '㉆' => '(文)', + '㉇' => '(箏)', + '㉐' => 'PTE', + '㉑' => '(21)', + '㉒' => '(22)', + '㉓' => '(23)', + '㉔' => '(24)', + '㉕' => '(25)', + '㉖' => '(26)', + '㉗' => '(27)', + '㉘' => '(28)', + '㉙' => '(29)', + '㉚' => '(30)', + '㉛' => '(31)', + '㉜' => '(32)', + '㉝' => '(33)', + '㉞' => '(34)', + '㉟' => '(35)', + '㉠' => '(ᄀ)', + '㉡' => '(ᄂ)', + '㉢' => '(ᄃ)', + '㉣' => '(ᄅ)', + '㉤' => '(ᄆ)', + '㉥' => '(ᄇ)', + '㉦' => '(ᄉ)', + '㉧' => '(ᄋ)', + '㉨' => '(ᄌ)', + '㉩' => '(ᄎ)', + '㉪' => '(ᄏ)', + '㉫' => '(ᄐ)', + '㉬' => '(ᄑ)', + '㉭' => '(ᄒ)', + '㉮' => '(가)', + '㉯' => '(나)', + '㉰' => '(다)', + '㉱' => '(라)', + '㉲' => '(마)', + '㉳' => '(바)', + '㉴' => '(사)', + '㉵' => '(아)', + '㉶' => '(자)', + '㉷' => '(차)', + '㉸' => '(카)', + '㉹' => '(타)', + '㉺' => '(파)', + '㉻' => '(하)', + '㉼' => '(참고)', + '㉽' => '(주의)', + '㉾' => '(우)', + '㊀' => '(一)', + '㊁' => '(二)', + '㊂' => '(三)', + '㊃' => '(四)', + '㊄' => '(五)', + '㊅' => '(六)', + '㊆' => '(七)', + '㊇' => '(八)', + '㊈' => '(九)', + '㊉' => '(十)', + '㊊' => '(月)', + '㊋' => '(火)', + '㊌' => '(水)', + '㊍' => '(木)', + '㊎' => '(金)', + '㊏' => '(土)', + '㊐' => '(日)', + '㊑' => '(株)', + '㊒' => '(有)', + '㊓' => '(社)', + '㊔' => '(名)', + '㊕' => '(特)', + '㊖' => '(財)', + '㊗' => '(祝)', + '㊘' => '(労)', + '㊙' => '(秘)', + '㊚' => '(男)', + '㊛' => '(女)', + '㊜' => '(適)', + '㊝' => '(優)', + '㊞' => '(印)', + '㊟' => '(注)', + '㊠' => '(項)', + '㊡' => '(休)', + '㊢' => '(写)', + '㊣' => '(正)', + '㊤' => '(上)', + '㊥' => '(中)', + '㊦' => '(下)', + '㊧' => '(左)', + '㊨' => '(右)', + '㊩' => '(医)', + '㊪' => '(宗)', + '㊫' => '(学)', + '㊬' => '(監)', + '㊭' => '(企)', + '㊮' => '(資)', + '㊯' => '(協)', + '㊰' => '(夜)', + '㊱' => '(36)', + '㊲' => '(37)', + '㊳' => '(38)', + '㊴' => '(39)', + '㊵' => '(40)', + '㊶' => '(41)', + '㊷' => '(42)', + '㊸' => '(43)', + '㊹' => '(44)', + '㊺' => '(45)', + '㊻' => '(46)', + '㊼' => '(47)', + '㊽' => '(48)', + '㊾' => '(49)', + '㊿' => '(50)', + '㋀' => '1月', + '㋁' => '2月', + '㋂' => '3月', + '㋃' => '4月', + '㋄' => '5月', + '㋅' => '6月', + '㋆' => '7月', + '㋇' => '8月', + '㋈' => '9月', + '㋉' => '10月', + '㋊' => '11月', + '㋋' => '12月', + '㋌' => 'Hg', + '㋍' => 'erg', + '㋎' => 'eV', + '㋏' => 'LTD', + '㋐' => '(ア)', + '㋑' => '(イ)', + '㋒' => '(ウ)', + '㋓' => '(エ)', + '㋔' => '(オ)', + '㋕' => '(カ)', + '㋖' => '(キ)', + '㋗' => '(ク)', + '㋘' => '(ケ)', + '㋙' => '(コ)', + '㋚' => '(サ)', + '㋛' => '(シ)', + '㋜' => '(ス)', + '㋝' => '(セ)', + '㋞' => '(ソ)', + '㋟' => '(タ)', + '㋠' => '(チ)', + '㋡' => '(ツ)', + '㋢' => '(テ)', + '㋣' => '(ト)', + '㋤' => '(ナ)', + '㋥' => '(ニ)', + '㋦' => '(ヌ)', + '㋧' => '(ネ)', + '㋨' => '(ノ)', + '㋩' => '(ハ)', + '㋪' => '(ヒ)', + '㋫' => '(フ)', + '㋬' => '(ヘ)', + '㋭' => '(ホ)', + '㋮' => '(マ)', + '㋯' => '(ミ)', + '㋰' => '(ム)', + '㋱' => '(メ)', + '㋲' => '(モ)', + '㋳' => '(ヤ)', + '㋴' => '(ユ)', + '㋵' => '(ヨ)', + '㋶' => '(ラ)', + '㋷' => '(リ)', + '㋸' => '(ル)', + '㋹' => '(レ)', + '㋺' => '(ロ)', + '㋻' => '(ワ)', + '㋼' => '(ヰ)', + '㋽' => '(ヱ)', + '㋾' => '(ヲ)', + '㋿' => '令和', + '㌀' => 'アパート', + '㌁' => 'アルファ', + '㌂' => 'アンペア', + '㌃' => 'アール', + '㌄' => 'イニング', + '㌅' => 'インチ', + '㌆' => 'ウォン', + '㌇' => 'エスクード', + '㌈' => 'エーカー', + '㌉' => 'オンス', + '㌊' => 'オーム', + '㌋' => 'カイリ', + '㌌' => 'カラット', + '㌍' => 'カロリー', + '㌎' => 'ガロン', + '㌏' => 'ガンマ', + '㌐' => 'ギガ', + '㌑' => 'ギニー', + '㌒' => 'キュリー', + '㌓' => 'ギルダー', + '㌔' => 'キロ', + '㌕' => 'キログラム', + '㌖' => 'キロメートル', + '㌗' => 'キロワット', + '㌘' => 'グラム', + '㌙' => 'グラムトン', + '㌚' => 'クルゼイロ', + '㌛' => 'クローネ', + '㌜' => 'ケース', + '㌝' => 'コルナ', + '㌞' => 'コーポ', + '㌟' => 'サイクル', + '㌠' => 'サンチーム', + '㌡' => 'シリング', + '㌢' => 'センチ', + '㌣' => 'セント', + '㌤' => 'ダース', + '㌥' => 'デシ', + '㌦' => 'ドル', + '㌧' => 'トン', + '㌨' => 'ナノ', + '㌩' => 'ノット', + '㌪' => 'ハイツ', + '㌫' => 'パーセント', + '㌬' => 'パーツ', + '㌭' => 'バーレル', + '㌮' => 'ピアストル', + '㌯' => 'ピクル', + '㌰' => 'ピコ', + '㌱' => 'ビル', + '㌲' => 'ファラッド', + '㌳' => 'フィート', + '㌴' => 'ブッシェル', + '㌵' => 'フラン', + '㌶' => 'ヘクタール', + '㌷' => 'ペソ', + '㌸' => 'ペニヒ', + '㌹' => 'ヘルツ', + '㌺' => 'ペンス', + '㌻' => 'ページ', + '㌼' => 'ベータ', + '㌽' => 'ポイント', + '㌾' => 'ボルト', + '㌿' => 'ホン', + '㍀' => 'ポンド', + '㍁' => 'ホール', + '㍂' => 'ホーン', + '㍃' => 'マイクロ', + '㍄' => 'マイル', + '㍅' => 'マッハ', + '㍆' => 'マルク', + '㍇' => 'マンション', + '㍈' => 'ミクロン', + '㍉' => 'ミリ', + '㍊' => 'ミリバール', + '㍋' => 'メガ', + '㍌' => 'メガトン', + '㍍' => 'メートル', + '㍎' => 'ヤード', + '㍏' => 'ヤール', + '㍐' => 'ユアン', + '㍑' => 'リットル', + '㍒' => 'リラ', + '㍓' => 'ルピー', + '㍔' => 'ルーブル', + '㍕' => 'レム', + '㍖' => 'レントゲン', + '㍗' => 'ワット', + '㍘' => '0点', + '㍙' => '1点', + '㍚' => '2点', + '㍛' => '3点', + '㍜' => '4点', + '㍝' => '5点', + '㍞' => '6点', + '㍟' => '7点', + '㍠' => '8点', + '㍡' => '9点', + '㍢' => '10点', + '㍣' => '11点', + '㍤' => '12点', + '㍥' => '13点', + '㍦' => '14点', + '㍧' => '15点', + '㍨' => '16点', + '㍩' => '17点', + '㍪' => '18点', + '㍫' => '19点', + '㍬' => '20点', + '㍭' => '21点', + '㍮' => '22点', + '㍯' => '23点', + '㍰' => '24点', + '㍱' => 'hPa', + '㍲' => 'da', + '㍳' => 'AU', + '㍴' => 'bar', + '㍵' => 'oV', + '㍶' => 'pc', + '㍷' => 'dm', + '㍸' => 'dm²', + '㍹' => 'dm³', + '㍺' => 'IU', + '㍻' => '平成', + '㍼' => '昭和', + '㍽' => '大正', + '㍾' => '明治', + '㍿' => '株式会社', + '㎀' => 'pA', + '㎁' => 'nA', + '㎂' => 'μA', + '㎃' => 'mA', + '㎄' => 'kA', + '㎅' => 'KB', + '㎆' => 'MB', + '㎇' => 'GB', + '㎈' => 'cal', + '㎉' => 'kcal', + '㎊' => 'pF', + '㎋' => 'nF', + '㎌' => 'μF', + '㎍' => 'μg', + '㎎' => 'mg', + '㎏' => 'kg', + '㎐' => 'Hz', + '㎑' => 'kHz', + '㎒' => 'MHz', + '㎓' => 'GHz', + '㎔' => 'THz', + '㎕' => 'μℓ', + '㎖' => 'mℓ', + '㎗' => 'dℓ', + '㎘' => 'kℓ', + '㎙' => 'fm', + '㎚' => 'nm', + '㎛' => 'μm', + '㎜' => 'mm', + '㎝' => 'cm', + '㎞' => 'km', + '㎟' => 'mm²', + '㎠' => 'cm²', + '㎡' => 'm²', + '㎢' => 'km²', + '㎣' => 'mm³', + '㎤' => 'cm³', + '㎥' => 'm³', + '㎦' => 'km³', + '㎧' => 'm∕s', + '㎨' => 'm∕s²', + '㎩' => 'Pa', + '㎪' => 'kPa', + '㎫' => 'MPa', + '㎬' => 'GPa', + '㎭' => 'rad', + '㎮' => 'rad∕s', + '㎯' => 'rad∕s²', + '㎰' => 'ps', + '㎱' => 'ns', + '㎲' => 'μs', + '㎳' => 'ms', + '㎴' => 'pV', + '㎵' => 'nV', + '㎶' => 'μV', + '㎷' => 'mV', + '㎸' => 'kV', + '㎹' => 'MV', + '㎺' => 'pW', + '㎻' => 'nW', + '㎼' => 'μW', + '㎽' => 'mW', + '㎾' => 'kW', + '㎿' => 'MW', + '㏀' => 'kΩ', + '㏁' => 'MΩ', + '㏂' => 'a.m.', + '㏃' => 'Bq', + '㏄' => 'cc', + '㏅' => 'cd', + '㏆' => 'C∕kg', + '㏇' => 'Co.', + '㏈' => 'dB', + '㏉' => 'Gy', + '㏊' => 'ha', + '㏋' => 'HP', + '㏌' => 'in', + '㏍' => 'KK', + '㏎' => 'KM', + '㏏' => 'kt', + '㏐' => 'lm', + '㏑' => 'ln', + '㏒' => 'log', + '㏓' => 'lx', + '㏔' => 'mb', + '㏕' => 'mil', + '㏖' => 'mol', + '㏗' => 'PH', + '㏘' => 'p.m.', + '㏙' => 'PPM', + '㏚' => 'PR', + '㏛' => 'sr', + '㏜' => 'Sv', + '㏝' => 'Wb', + '㏞' => 'V∕m', + '㏟' => 'A∕m', + '㏠' => '1日', + '㏡' => '2日', + '㏢' => '3日', + '㏣' => '4日', + '㏤' => '5日', + '㏥' => '6日', + '㏦' => '7日', + '㏧' => '8日', + '㏨' => '9日', + '㏩' => '10日', + '㏪' => '11日', + '㏫' => '12日', + '㏬' => '13日', + '㏭' => '14日', + '㏮' => '15日', + '㏯' => '16日', + '㏰' => '17日', + '㏱' => '18日', + '㏲' => '19日', + '㏳' => '20日', + '㏴' => '21日', + '㏵' => '22日', + '㏶' => '23日', + '㏷' => '24日', + '㏸' => '25日', + '㏹' => '26日', + '㏺' => '27日', + '㏻' => '28日', + '㏼' => '29日', + '㏽' => '30日', + '㏾' => '31日', + '㏿' => 'gal', + '豈' => '豈', + '更' => '更', + '車' => '車', + '賈' => '賈', + '滑' => '滑', + '串' => '串', + '句' => '句', + '龜' => '龜', + '龜' => '龜', + '契' => '契', + '金' => '金', + '喇' => '喇', + '奈' => '奈', + '懶' => '懶', + '癩' => '癩', + '羅' => '羅', + '蘿' => '蘿', + '螺' => '螺', + '裸' => '裸', + '邏' => '邏', + '樂' => '樂', + '洛' => '洛', + '烙' => '烙', + '珞' => '珞', + '落' => '落', + '酪' => '酪', + '駱' => '駱', + '亂' => '亂', + '卵' => '卵', + '欄' => '欄', + '爛' => '爛', + '蘭' => '蘭', + '鸞' => '鸞', + '嵐' => '嵐', + '濫' => '濫', + '藍' => '藍', + '襤' => '襤', + '拉' => '拉', + '臘' => '臘', + '蠟' => '蠟', + '廊' => '廊', + '朗' => '朗', + '浪' => '浪', + '狼' => '狼', + '郎' => '郎', + '來' => '來', + '冷' => '冷', + '勞' => '勞', + '擄' => '擄', + '櫓' => '櫓', + '爐' => '爐', + '盧' => '盧', + '老' => '老', + '蘆' => '蘆', + '虜' => '虜', + '路' => '路', + '露' => '露', + '魯' => '魯', + '鷺' => '鷺', + '碌' => '碌', + '祿' => '祿', + '綠' => '綠', + '菉' => '菉', + '錄' => '錄', + '鹿' => '鹿', + '論' => '論', + '壟' => '壟', + '弄' => '弄', + '籠' => '籠', + '聾' => '聾', + '牢' => '牢', + '磊' => '磊', + '賂' => '賂', + '雷' => '雷', + '壘' => '壘', + '屢' => '屢', + '樓' => '樓', + '淚' => '淚', + '漏' => '漏', + '累' => '累', + '縷' => '縷', + '陋' => '陋', + '勒' => '勒', + '肋' => '肋', + '凜' => '凜', + '凌' => '凌', + '稜' => '稜', + '綾' => '綾', + '菱' => '菱', + '陵' => '陵', + '讀' => '讀', + '拏' => '拏', + '樂' => '樂', + '諾' => '諾', + '丹' => '丹', + '寧' => '寧', + '怒' => '怒', + '率' => '率', + '異' => '異', + '北' => '北', + '磻' => '磻', + '便' => '便', + '復' => '復', + '不' => '不', + '泌' => '泌', + '數' => '數', + '索' => '索', + '參' => '參', + '塞' => '塞', + '省' => '省', + '葉' => '葉', + '說' => '說', + '殺' => '殺', + '辰' => '辰', + '沈' => '沈', + '拾' => '拾', + '若' => '若', + '掠' => '掠', + '略' => '略', + '亮' => '亮', + '兩' => '兩', + '凉' => '凉', + '梁' => '梁', + '糧' => '糧', + '良' => '良', + '諒' => '諒', + '量' => '量', + '勵' => '勵', + '呂' => '呂', + '女' => '女', + '廬' => '廬', + '旅' => '旅', + '濾' => '濾', + '礪' => '礪', + '閭' => '閭', + '驪' => '驪', + '麗' => '麗', + '黎' => '黎', + '力' => '力', + '曆' => '曆', + '歷' => '歷', + '轢' => '轢', + '年' => '年', + '憐' => '憐', + '戀' => '戀', + '撚' => '撚', + '漣' => '漣', + '煉' => '煉', + '璉' => '璉', + '秊' => '秊', + '練' => '練', + '聯' => '聯', + '輦' => '輦', + '蓮' => '蓮', + '連' => '連', + '鍊' => '鍊', + '列' => '列', + '劣' => '劣', + '咽' => '咽', + '烈' => '烈', + '裂' => '裂', + '說' => '說', + '廉' => '廉', + '念' => '念', + '捻' => '捻', + '殮' => '殮', + '簾' => '簾', + '獵' => '獵', + '令' => '令', + '囹' => '囹', + '寧' => '寧', + '嶺' => '嶺', + '怜' => '怜', + '玲' => '玲', + '瑩' => '瑩', + '羚' => '羚', + '聆' => '聆', + '鈴' => '鈴', + '零' => '零', + '靈' => '靈', + '領' => '領', + '例' => '例', + '禮' => '禮', + '醴' => '醴', + '隸' => '隸', + '惡' => '惡', + '了' => '了', + '僚' => '僚', + '寮' => '寮', + '尿' => '尿', + '料' => '料', + '樂' => '樂', + '燎' => '燎', + '療' => '療', + '蓼' => '蓼', + '遼' => '遼', + '龍' => '龍', + '暈' => '暈', + '阮' => '阮', + '劉' => '劉', + '杻' => '杻', + '柳' => '柳', + '流' => '流', + '溜' => '溜', + '琉' => '琉', + '留' => '留', + '硫' => '硫', + '紐' => '紐', + '類' => '類', + '六' => '六', + '戮' => '戮', + '陸' => '陸', + '倫' => '倫', + '崙' => '崙', + '淪' => '淪', + '輪' => '輪', + '律' => '律', + '慄' => '慄', + '栗' => '栗', + '率' => '率', + '隆' => '隆', + '利' => '利', + '吏' => '吏', + '履' => '履', + '易' => '易', + '李' => '李', + '梨' => '梨', + '泥' => '泥', + '理' => '理', + '痢' => '痢', + '罹' => '罹', + '裏' => '裏', + '裡' => '裡', + '里' => '里', + '離' => '離', + '匿' => '匿', + '溺' => '溺', + '吝' => '吝', + '燐' => '燐', + '璘' => '璘', + '藺' => '藺', + '隣' => '隣', + '鱗' => '鱗', + '麟' => '麟', + '林' => '林', + '淋' => '淋', + '臨' => '臨', + '立' => '立', + '笠' => '笠', + '粒' => '粒', + '狀' => '狀', + '炙' => '炙', + '識' => '識', + '什' => '什', + '茶' => '茶', + '刺' => '刺', + '切' => '切', + '度' => '度', + '拓' => '拓', + '糖' => '糖', + '宅' => '宅', + '洞' => '洞', + '暴' => '暴', + '輻' => '輻', + '行' => '行', + '降' => '降', + '見' => '見', + '廓' => '廓', + '兀' => '兀', + '嗀' => '嗀', + '﨎' => '' . "\0" . '', + '﨏' => '' . "\0" . '', + '塚' => '塚', + '﨑' => '' . "\0" . '', + '晴' => '晴', + '﨓' => '' . "\0" . '', + '﨔' => '' . "\0" . '', + '凞' => '凞', + '猪' => '猪', + '益' => '益', + '礼' => '礼', + '神' => '神', + '祥' => '祥', + '福' => '福', + '靖' => '靖', + '精' => '精', + '羽' => '羽', + '﨟' => '' . "\0" . '', + '蘒' => '蘒', + '﨡' => '' . "\0" . '', + '諸' => '諸', + '﨣' => '' . "\0" . '', + '﨤' => '' . "\0" . '', + '逸' => '逸', + '都' => '都', + '﨧' => '' . "\0" . '', + '﨨' => '' . "\0" . '', + '﨩' => '' . "\0" . '', + '飯' => '飯', + '飼' => '飼', + '館' => '館', + '鶴' => '鶴', + '郞' => '郞', + '隷' => '隷', + '侮' => '侮', + '僧' => '僧', + '免' => '免', + '勉' => '勉', + '勤' => '勤', + '卑' => '卑', + '喝' => '喝', + '嘆' => '嘆', + '器' => '器', + '塀' => '塀', + '墨' => '墨', + '層' => '層', + '屮' => '屮', + '悔' => '悔', + '慨' => '慨', + '憎' => '憎', + '懲' => '懲', + '敏' => '敏', + '既' => '既', + '暑' => '暑', + '梅' => '梅', + '海' => '海', + '渚' => '渚', + '漢' => '漢', + '煮' => '煮', + '爫' => '爫', + '琢' => '琢', + '碑' => '碑', + '社' => '社', + '祉' => '祉', + '祈' => '祈', + '祐' => '祐', + '祖' => '祖', + '祝' => '祝', + '禍' => '禍', + '禎' => '禎', + '穀' => '穀', + '突' => '突', + '節' => '節', + '練' => '練', + '縉' => '縉', + '繁' => '繁', + '署' => '署', + '者' => '者', + '臭' => '臭', + '艹' => '艹', + '艹' => '艹', + '著' => '著', + '褐' => '褐', + '視' => '視', + '謁' => '謁', + '謹' => '謹', + '賓' => '賓', + '贈' => '贈', + '辶' => '辶', + '逸' => '逸', + '難' => '難', + '響' => '響', + '頻' => '頻', + '恵' => '恵', + '𤋮' => '𤋮', + '舘' => '舘', + '並' => '並', + '况' => '况', + '全' => '全', + '侀' => '侀', + '充' => '充', + '冀' => '冀', + '勇' => '勇', + '勺' => '勺', + '喝' => '喝', + '啕' => '啕', + '喙' => '喙', + '嗢' => '嗢', + '塚' => '塚', + '墳' => '墳', + '奄' => '奄', + '奔' => '奔', + '婢' => '婢', + '嬨' => '嬨', + '廒' => '廒', + '廙' => '廙', + '彩' => '彩', + '徭' => '徭', + '惘' => '惘', + '慎' => '慎', + '愈' => '愈', + '憎' => '憎', + '慠' => '慠', + '懲' => '懲', + '戴' => '戴', + '揄' => '揄', + '搜' => '搜', + '摒' => '摒', + '敖' => '敖', + '晴' => '晴', + '朗' => '朗', + '望' => '望', + '杖' => '杖', + '歹' => '歹', + '殺' => '殺', + '流' => '流', + '滛' => '滛', + '滋' => '滋', + '漢' => '漢', + '瀞' => '瀞', + '煮' => '煮', + '瞧' => '瞧', + '爵' => '爵', + '犯' => '犯', + '猪' => '猪', + '瑱' => '瑱', + '甆' => '甆', + '画' => '画', + '瘝' => '瘝', + '瘟' => '瘟', + '益' => '益', + '盛' => '盛', + '直' => '直', + '睊' => '睊', + '着' => '着', + '磌' => '磌', + '窱' => '窱', + '節' => '節', + '类' => '类', + '絛' => '絛', + '練' => '練', + '缾' => '缾', + '者' => '者', + '荒' => '荒', + '華' => '華', + '蝹' => '蝹', + '襁' => '襁', + '覆' => '覆', + '視' => '視', + '調' => '調', + '諸' => '諸', + '請' => '請', + '謁' => '謁', + '諾' => '諾', + '諭' => '諭', + '謹' => '謹', + '變' => '變', + '贈' => '贈', + '輸' => '輸', + '遲' => '遲', + '醙' => '醙', + '鉶' => '鉶', + '陼' => '陼', + '難' => '難', + '靖' => '靖', + '韛' => '韛', + '響' => '響', + '頋' => '頋', + '頻' => '頻', + '鬒' => '鬒', + '龜' => '龜', + '𢡊' => '𢡊', + '𢡄' => '𢡄', + '𣏕' => '𣏕', + '㮝' => '㮝', + '䀘' => '䀘', + '䀹' => '䀹', + '𥉉' => '𥉉', + '𥳐' => '𥳐', + '𧻓' => '𧻓', + '齃' => '齃', + '龎' => '龎', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'ſt', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', + 'ﬠ' => 'ע', + 'ﬡ' => 'א', + 'ﬢ' => 'ד', + 'ﬣ' => 'ה', + 'ﬤ' => 'כ', + 'ﬥ' => 'ל', + 'ﬦ' => 'ם', + 'ﬧ' => 'ר', + 'ﬨ' => 'ת', + '﬩' => '+', + 'ﭏ' => 'אל', + '﹉' => '‾', + '﹊' => '‾', + '﹋' => '‾', + '﹌' => '‾', + '﹍' => '_', + '﹎' => '_', + '﹏' => '_', + '﹐' => ',', + '﹑' => '、', + '﹒' => '.', + '﹔' => ';', + '﹕' => ':', + '﹖' => '?', + '﹗' => '!', + '﹘' => '—', + '﹙' => '(', + '﹚' => ')', + '﹛' => '{', + '﹜' => '}', + '﹝' => '〔', + '﹞' => '〕', + '﹟' => '#', + '﹠' => '&', + '﹡' => '*', + '﹢' => '+', + '﹣' => '-', + '﹤' => '<', + '﹥' => '>', + '﹦' => '=', + '﹨' => '\\', + '﹩' => '$', + '﹪' => '%', + '﹫' => '@', + '!' => '!', + '"' => '"', + '#' => '#', + '$' => '$', + '%' => '%', + '&' => '&', + ''' => '\'', + '(' => '(', + ')' => ')', + '*' => '*', + '+' => '+', + ',' => ',', + '-' => '-', + '.' => '.', + '/' => '/', + '0' => '0', + '1' => '1', + '2' => '2', + '3' => '3', + '4' => '4', + '5' => '5', + '6' => '6', + '7' => '7', + '8' => '8', + '9' => '9', + ':' => ':', + ';' => ';', + '<' => '<', + '=' => '=', + '>' => '>', + '?' => '?', + '@' => '@', + 'A' => 'A', + 'B' => 'B', + 'C' => 'C', + 'D' => 'D', + 'E' => 'E', + 'F' => 'F', + 'G' => 'G', + 'H' => 'H', + 'I' => 'I', + 'J' => 'J', + 'K' => 'K', + 'L' => 'L', + 'M' => 'M', + 'N' => 'N', + 'O' => 'O', + 'P' => 'P', + 'Q' => 'Q', + 'R' => 'R', + 'S' => 'S', + 'T' => 'T', + 'U' => 'U', + 'V' => 'V', + 'W' => 'W', + 'X' => 'X', + 'Y' => 'Y', + 'Z' => 'Z', + '[' => '[', + '\' => '\\', + ']' => ']', + '^' => '^', + '_' => '_', + '`' => '`', + 'a' => 'a', + 'b' => 'b', + 'c' => 'c', + 'd' => 'd', + 'e' => 'e', + 'f' => 'f', + 'g' => 'g', + 'h' => 'h', + 'i' => 'i', + 'j' => 'j', + 'k' => 'k', + 'l' => 'l', + 'm' => 'm', + 'n' => 'n', + 'o' => 'o', + 'p' => 'p', + 'q' => 'q', + 'r' => 'r', + 's' => 's', + 't' => 't', + 'u' => 'u', + 'v' => 'v', + 'w' => 'w', + 'x' => 'x', + 'y' => 'y', + 'z' => 'z', + '{' => '{', + '|' => '|', + '}' => '}', + '~' => '~', + '⦅' => '⦅', + '⦆' => '⦆', + '。' => '。', + '「' => '「', + '」' => '」', + '、' => '、', + '・' => '・', + 'ヲ' => 'ヲ', + 'ァ' => 'ァ', + 'ィ' => 'ィ', + 'ゥ' => 'ゥ', + 'ェ' => 'ェ', + 'ォ' => 'ォ', + 'ャ' => 'ャ', + 'ュ' => 'ュ', + 'ョ' => 'ョ', + 'ッ' => 'ッ', + 'ー' => 'ー', + 'ア' => 'ア', + 'イ' => 'イ', + 'ウ' => 'ウ', + 'エ' => 'エ', + 'オ' => 'オ', + 'カ' => 'カ', + 'キ' => 'キ', + 'ク' => 'ク', + 'ケ' => 'ケ', + 'コ' => 'コ', + 'サ' => 'サ', + 'シ' => 'シ', + 'ス' => 'ス', + 'セ' => 'セ', + 'ソ' => 'ソ', + 'タ' => 'タ', + 'チ' => 'チ', + 'ツ' => 'ツ', + 'テ' => 'テ', + 'ト' => 'ト', + 'ナ' => 'ナ', + 'ニ' => 'ニ', + 'ヌ' => 'ヌ', + 'ネ' => 'ネ', + 'ノ' => 'ノ', + 'ハ' => 'ハ', + 'ヒ' => 'ヒ', + 'フ' => 'フ', + 'ヘ' => 'ヘ', + 'ホ' => 'ホ', + 'マ' => 'マ', + 'ミ' => 'ミ', + 'ム' => 'ム', + 'メ' => 'メ', + 'モ' => 'モ', + 'ヤ' => 'ヤ', + 'ユ' => 'ユ', + 'ヨ' => 'ヨ', + 'ラ' => 'ラ', + 'リ' => 'リ', + 'ル' => 'ル', + 'レ' => 'レ', + 'ロ' => 'ロ', + 'ワ' => 'ワ', + 'ン' => 'ン', + '゙' => '゙', + '゚' => '゚', + 'ᅠ' => 'ㅤ', + 'ᄀ' => 'ㄱ', + 'ᄁ' => 'ㄲ', + 'ᆪ' => 'ㄳ', + 'ᄂ' => 'ㄴ', + 'ᆬ' => 'ㄵ', + 'ᆭ' => 'ㄶ', + 'ᄃ' => 'ㄷ', + 'ᄄ' => 'ㄸ', + 'ᄅ' => 'ㄹ', + 'ᆰ' => 'ㄺ', + 'ᆱ' => 'ㄻ', + 'ᆲ' => 'ㄼ', + 'ᆳ' => 'ㄽ', + 'ᆴ' => 'ㄾ', + 'ᆵ' => 'ㄿ', + 'ᄚ' => 'ㅀ', + 'ᄆ' => 'ㅁ', + 'ᄇ' => 'ㅂ', + 'ᄈ' => 'ㅃ', + 'ᄡ' => 'ㅄ', + 'ᄉ' => 'ㅅ', + 'ᄊ' => 'ㅆ', + 'ᄋ' => 'ㅇ', + 'ᄌ' => 'ㅈ', + 'ᄍ' => 'ㅉ', + 'ᄎ' => 'ㅊ', + 'ᄏ' => 'ㅋ', + 'ᄐ' => 'ㅌ', + 'ᄑ' => 'ㅍ', + 'ᄒ' => 'ㅎ', + 'ᅡ' => 'ㅏ', + 'ᅢ' => 'ㅐ', + 'ᅣ' => 'ㅑ', + 'ᅤ' => 'ㅒ', + 'ᅥ' => 'ㅓ', + 'ᅦ' => 'ㅔ', + 'ᅧ' => 'ㅕ', + 'ᅨ' => 'ㅖ', + 'ᅩ' => 'ㅗ', + 'ᅪ' => 'ㅘ', + 'ᅫ' => 'ㅙ', + 'ᅬ' => 'ㅚ', + 'ᅭ' => 'ㅛ', + 'ᅮ' => 'ㅜ', + 'ᅯ' => 'ㅝ', + 'ᅰ' => 'ㅞ', + 'ᅱ' => 'ㅟ', + 'ᅲ' => 'ㅠ', + 'ᅳ' => 'ㅡ', + 'ᅴ' => 'ㅢ', + 'ᅵ' => 'ㅣ', + '¢' => '¢', + '£' => '£', + '¬' => '¬', + ' ̄' => '¯', + '¦' => '¦', + '¥' => '¥', + '₩' => '₩', + '│' => '│', + '←' => '←', + '↑' => '↑', + '→' => '→', + '↓' => '↓', + '■' => '■', + '○' => '○', + '𝐀' => 'A', + '𝐁' => 'B', + '𝐂' => 'C', + '𝐃' => 'D', + '𝐄' => 'E', + '𝐅' => 'F', + '𝐆' => 'G', + '𝐇' => 'H', + '𝐈' => 'I', + '𝐉' => 'J', + '𝐊' => 'K', + '𝐋' => 'L', + '𝐌' => 'M', + '𝐍' => 'N', + '𝐎' => 'O', + '𝐏' => 'P', + '𝐐' => 'Q', + '𝐑' => 'R', + '𝐒' => 'S', + '𝐓' => 'T', + '𝐔' => 'U', + '𝐕' => 'V', + '𝐖' => 'W', + '𝐗' => 'X', + '𝐘' => 'Y', + '𝐙' => 'Z', + '𝐚' => 'a', + '𝐛' => 'b', + '𝐜' => 'c', + '𝐝' => 'd', + '𝐞' => 'e', + '𝐟' => 'f', + '𝐠' => 'g', + '𝐡' => 'h', + '𝐢' => 'i', + '𝐣' => 'j', + '𝐤' => 'k', + '𝐥' => 'l', + '𝐦' => 'm', + '𝐧' => 'n', + '𝐨' => 'o', + '𝐩' => 'p', + '𝐪' => 'q', + '𝐫' => 'r', + '𝐬' => 's', + '𝐭' => 't', + '𝐮' => 'u', + '𝐯' => 'v', + '𝐰' => 'w', + '𝐱' => 'x', + '𝐲' => 'y', + '𝐳' => 'z', + '𝐴' => 'A', + '𝐵' => 'B', + '𝐶' => 'C', + '𝐷' => 'D', + '𝐸' => 'E', + '𝐹' => 'F', + '𝐺' => 'G', + '𝐻' => 'H', + '𝐼' => 'I', + '𝐽' => 'J', + '𝐾' => 'K', + '𝐿' => 'L', + '𝑀' => 'M', + '𝑁' => 'N', + '𝑂' => 'O', + '𝑃' => 'P', + '𝑄' => 'Q', + '𝑅' => 'R', + '𝑆' => 'S', + '𝑇' => 'T', + '𝑈' => 'U', + '𝑉' => 'V', + '𝑊' => 'W', + '𝑋' => 'X', + '𝑌' => 'Y', + '𝑍' => 'Z', + '𝑎' => 'a', + '𝑏' => 'b', + '𝑐' => 'c', + '𝑑' => 'd', + '𝑒' => 'e', + '𝑓' => 'f', + '𝑔' => 'g', + '𝑖' => 'i', + '𝑗' => 'j', + '𝑘' => 'k', + '𝑙' => 'l', + '𝑚' => 'm', + '𝑛' => 'n', + '𝑜' => 'o', + '𝑝' => 'p', + '𝑞' => 'q', + '𝑟' => 'r', + '𝑠' => 's', + '𝑡' => 't', + '𝑢' => 'u', + '𝑣' => 'v', + '𝑤' => 'w', + '𝑥' => 'x', + '𝑦' => 'y', + '𝑧' => 'z', + '𝑨' => 'A', + '𝑩' => 'B', + '𝑪' => 'C', + '𝑫' => 'D', + '𝑬' => 'E', + '𝑭' => 'F', + '𝑮' => 'G', + '𝑯' => 'H', + '𝑰' => 'I', + '𝑱' => 'J', + '𝑲' => 'K', + '𝑳' => 'L', + '𝑴' => 'M', + '𝑵' => 'N', + '𝑶' => 'O', + '𝑷' => 'P', + '𝑸' => 'Q', + '𝑹' => 'R', + '𝑺' => 'S', + '𝑻' => 'T', + '𝑼' => 'U', + '𝑽' => 'V', + '𝑾' => 'W', + '𝑿' => 'X', + '𝒀' => 'Y', + '𝒁' => 'Z', + '𝒂' => 'a', + '𝒃' => 'b', + '𝒄' => 'c', + '𝒅' => 'd', + '𝒆' => 'e', + '𝒇' => 'f', + '𝒈' => 'g', + '𝒉' => 'h', + '𝒊' => 'i', + '𝒋' => 'j', + '𝒌' => 'k', + '𝒍' => 'l', + '𝒎' => 'm', + '𝒏' => 'n', + '𝒐' => 'o', + '𝒑' => 'p', + '𝒒' => 'q', + '𝒓' => 'r', + '𝒔' => 's', + '𝒕' => 't', + '𝒖' => 'u', + '𝒗' => 'v', + '𝒘' => 'w', + '𝒙' => 'x', + '𝒚' => 'y', + '𝒛' => 'z', + '𝒜' => 'A', + '𝒞' => 'C', + '𝒟' => 'D', + '𝒢' => 'G', + '𝒥' => 'J', + '𝒦' => 'K', + '𝒩' => 'N', + '𝒪' => 'O', + '𝒫' => 'P', + '𝒬' => 'Q', + '𝒮' => 'S', + '𝒯' => 'T', + '𝒰' => 'U', + '𝒱' => 'V', + '𝒲' => 'W', + '𝒳' => 'X', + '𝒴' => 'Y', + '𝒵' => 'Z', + '𝒶' => 'a', + '𝒷' => 'b', + '𝒸' => 'c', + '𝒹' => 'd', + '𝒻' => 'f', + '𝒽' => 'h', + '𝒾' => 'i', + '𝒿' => 'j', + '𝓀' => 'k', + '𝓁' => 'l', + '𝓂' => 'm', + '𝓃' => 'n', + '𝓅' => 'p', + '𝓆' => 'q', + '𝓇' => 'r', + '𝓈' => 's', + '𝓉' => 't', + '𝓊' => 'u', + '𝓋' => 'v', + '𝓌' => 'w', + '𝓍' => 'x', + '𝓎' => 'y', + '𝓏' => 'z', + '𝓐' => 'A', + '𝓑' => 'B', + '𝓒' => 'C', + '𝓓' => 'D', + '𝓔' => 'E', + '𝓕' => 'F', + '𝓖' => 'G', + '𝓗' => 'H', + '𝓘' => 'I', + '𝓙' => 'J', + '𝓚' => 'K', + '𝓛' => 'L', + '𝓜' => 'M', + '𝓝' => 'N', + '𝓞' => 'O', + '𝓟' => 'P', + '𝓠' => 'Q', + '𝓡' => 'R', + '𝓢' => 'S', + '𝓣' => 'T', + '𝓤' => 'U', + '𝓥' => 'V', + '𝓦' => 'W', + '𝓧' => 'X', + '𝓨' => 'Y', + '𝓩' => 'Z', + '𝓪' => 'a', + '𝓫' => 'b', + '𝓬' => 'c', + '𝓭' => 'd', + '𝓮' => 'e', + '𝓯' => 'f', + '𝓰' => 'g', + '𝓱' => 'h', + '𝓲' => 'i', + '𝓳' => 'j', + '𝓴' => 'k', + '𝓵' => 'l', + '𝓶' => 'm', + '𝓷' => 'n', + '𝓸' => 'o', + '𝓹' => 'p', + '𝓺' => 'q', + '𝓻' => 'r', + '𝓼' => 's', + '𝓽' => 't', + '𝓾' => 'u', + '𝓿' => 'v', + '𝔀' => 'w', + '𝔁' => 'x', + '𝔂' => 'y', + '𝔃' => 'z', + '𝔄' => 'A', + '𝔅' => 'B', + '𝔇' => 'D', + '𝔈' => 'E', + '𝔉' => 'F', + '𝔊' => 'G', + '𝔍' => 'J', + '𝔎' => 'K', + '𝔏' => 'L', + '𝔐' => 'M', + '𝔑' => 'N', + '𝔒' => 'O', + '𝔓' => 'P', + '𝔔' => 'Q', + '𝔖' => 'S', + '𝔗' => 'T', + '𝔘' => 'U', + '𝔙' => 'V', + '𝔚' => 'W', + '𝔛' => 'X', + '𝔜' => 'Y', + '𝔞' => 'a', + '𝔟' => 'b', + '𝔠' => 'c', + '𝔡' => 'd', + '𝔢' => 'e', + '𝔣' => 'f', + '𝔤' => 'g', + '𝔥' => 'h', + '𝔦' => 'i', + '𝔧' => 'j', + '𝔨' => 'k', + '𝔩' => 'l', + '𝔪' => 'm', + '𝔫' => 'n', + '𝔬' => 'o', + '𝔭' => 'p', + '𝔮' => 'q', + '𝔯' => 'r', + '𝔰' => 's', + '𝔱' => 't', + '𝔲' => 'u', + '𝔳' => 'v', + '𝔴' => 'w', + '𝔵' => 'x', + '𝔶' => 'y', + '𝔷' => 'z', + '𝔸' => 'A', + '𝔹' => 'B', + '𝔻' => 'D', + '𝔼' => 'E', + '𝔽' => 'F', + '𝔾' => 'G', + '𝕀' => 'I', + '𝕁' => 'J', + '𝕂' => 'K', + '𝕃' => 'L', + '𝕄' => 'M', + '𝕆' => 'O', + '𝕊' => 'S', + '𝕋' => 'T', + '𝕌' => 'U', + '𝕍' => 'V', + '𝕎' => 'W', + '𝕏' => 'X', + '𝕐' => 'Y', + '𝕒' => 'a', + '𝕓' => 'b', + '𝕔' => 'c', + '𝕕' => 'd', + '𝕖' => 'e', + '𝕗' => 'f', + '𝕘' => 'g', + '𝕙' => 'h', + '𝕚' => 'i', + '𝕛' => 'j', + '𝕜' => 'k', + '𝕝' => 'l', + '𝕞' => 'm', + '𝕟' => 'n', + '𝕠' => 'o', + '𝕡' => 'p', + '𝕢' => 'q', + '𝕣' => 'r', + '𝕤' => 's', + '𝕥' => 't', + '𝕦' => 'u', + '𝕧' => 'v', + '𝕨' => 'w', + '𝕩' => 'x', + '𝕪' => 'y', + '𝕫' => 'z', + '𝕬' => 'A', + '𝕭' => 'B', + '𝕮' => 'C', + '𝕯' => 'D', + '𝕰' => 'E', + '𝕱' => 'F', + '𝕲' => 'G', + '𝕳' => 'H', + '𝕴' => 'I', + '𝕵' => 'J', + '𝕶' => 'K', + '𝕷' => 'L', + '𝕸' => 'M', + '𝕹' => 'N', + '𝕺' => 'O', + '𝕻' => 'P', + '𝕼' => 'Q', + '𝕽' => 'R', + '𝕾' => 'S', + '𝕿' => 'T', + '𝖀' => 'U', + '𝖁' => 'V', + '𝖂' => 'W', + '𝖃' => 'X', + '𝖄' => 'Y', + '𝖅' => 'Z', + '𝖆' => 'a', + '𝖇' => 'b', + '𝖈' => 'c', + '𝖉' => 'd', + '𝖊' => 'e', + '𝖋' => 'f', + '𝖌' => 'g', + '𝖍' => 'h', + '𝖎' => 'i', + '𝖏' => 'j', + '𝖐' => 'k', + '𝖑' => 'l', + '𝖒' => 'm', + '𝖓' => 'n', + '𝖔' => 'o', + '𝖕' => 'p', + '𝖖' => 'q', + '𝖗' => 'r', + '𝖘' => 's', + '𝖙' => 't', + '𝖚' => 'u', + '𝖛' => 'v', + '𝖜' => 'w', + '𝖝' => 'x', + '𝖞' => 'y', + '𝖟' => 'z', + '𝖠' => 'A', + '𝖡' => 'B', + '𝖢' => 'C', + '𝖣' => 'D', + '𝖤' => 'E', + '𝖥' => 'F', + '𝖦' => 'G', + '𝖧' => 'H', + '𝖨' => 'I', + '𝖩' => 'J', + '𝖪' => 'K', + '𝖫' => 'L', + '𝖬' => 'M', + '𝖭' => 'N', + '𝖮' => 'O', + '𝖯' => 'P', + '𝖰' => 'Q', + '𝖱' => 'R', + '𝖲' => 'S', + '𝖳' => 'T', + '𝖴' => 'U', + '𝖵' => 'V', + '𝖶' => 'W', + '𝖷' => 'X', + '𝖸' => 'Y', + '𝖹' => 'Z', + '𝖺' => 'a', + '𝖻' => 'b', + '𝖼' => 'c', + '𝖽' => 'd', + '𝖾' => 'e', + '𝖿' => 'f', + '𝗀' => 'g', + '𝗁' => 'h', + '𝗂' => 'i', + '𝗃' => 'j', + '𝗄' => 'k', + '𝗅' => 'l', + '𝗆' => 'm', + '𝗇' => 'n', + '𝗈' => 'o', + '𝗉' => 'p', + '𝗊' => 'q', + '𝗋' => 'r', + '𝗌' => 's', + '𝗍' => 't', + '𝗎' => 'u', + '𝗏' => 'v', + '𝗐' => 'w', + '𝗑' => 'x', + '𝗒' => 'y', + '𝗓' => 'z', + '𝗔' => 'A', + '𝗕' => 'B', + '𝗖' => 'C', + '𝗗' => 'D', + '𝗘' => 'E', + '𝗙' => 'F', + '𝗚' => 'G', + '𝗛' => 'H', + '𝗜' => 'I', + '𝗝' => 'J', + '𝗞' => 'K', + '𝗟' => 'L', + '𝗠' => 'M', + '𝗡' => 'N', + '𝗢' => 'O', + '𝗣' => 'P', + '𝗤' => 'Q', + '𝗥' => 'R', + '𝗦' => 'S', + '𝗧' => 'T', + '𝗨' => 'U', + '𝗩' => 'V', + '𝗪' => 'W', + '𝗫' => 'X', + '𝗬' => 'Y', + '𝗭' => 'Z', + '𝗮' => 'a', + '𝗯' => 'b', + '𝗰' => 'c', + '𝗱' => 'd', + '𝗲' => 'e', + '𝗳' => 'f', + '𝗴' => 'g', + '𝗵' => 'h', + '𝗶' => 'i', + '𝗷' => 'j', + '𝗸' => 'k', + '𝗹' => 'l', + '𝗺' => 'm', + '𝗻' => 'n', + '𝗼' => 'o', + '𝗽' => 'p', + '𝗾' => 'q', + '𝗿' => 'r', + '𝘀' => 's', + '𝘁' => 't', + '𝘂' => 'u', + '𝘃' => 'v', + '𝘄' => 'w', + '𝘅' => 'x', + '𝘆' => 'y', + '𝘇' => 'z', + '𝘈' => 'A', + '𝘉' => 'B', + '𝘊' => 'C', + '𝘋' => 'D', + '𝘌' => 'E', + '𝘍' => 'F', + '𝘎' => 'G', + '𝘏' => 'H', + '𝘐' => 'I', + '𝘑' => 'J', + '𝘒' => 'K', + '𝘓' => 'L', + '𝘔' => 'M', + '𝘕' => 'N', + '𝘖' => 'O', + '𝘗' => 'P', + '𝘘' => 'Q', + '𝘙' => 'R', + '𝘚' => 'S', + '𝘛' => 'T', + '𝘜' => 'U', + '𝘝' => 'V', + '𝘞' => 'W', + '𝘟' => 'X', + '𝘠' => 'Y', + '𝘡' => 'Z', + '𝘢' => 'a', + '𝘣' => 'b', + '𝘤' => 'c', + '𝘥' => 'd', + '𝘦' => 'e', + '𝘧' => 'f', + '𝘨' => 'g', + '𝘩' => 'h', + '𝘪' => 'i', + '𝘫' => 'j', + '𝘬' => 'k', + '𝘭' => 'l', + '𝘮' => 'm', + '𝘯' => 'n', + '𝘰' => 'o', + '𝘱' => 'p', + '𝘲' => 'q', + '𝘳' => 'r', + '𝘴' => 's', + '𝘵' => 't', + '𝘶' => 'u', + '𝘷' => 'v', + '𝘸' => 'w', + '𝘹' => 'x', + '𝘺' => 'y', + '𝘻' => 'z', + '𝘼' => 'A', + '𝘽' => 'B', + '𝘾' => 'C', + '𝘿' => 'D', + '𝙀' => 'E', + '𝙁' => 'F', + '𝙂' => 'G', + '𝙃' => 'H', + '𝙄' => 'I', + '𝙅' => 'J', + '𝙆' => 'K', + '𝙇' => 'L', + '𝙈' => 'M', + '𝙉' => 'N', + '𝙊' => 'O', + '𝙋' => 'P', + '𝙌' => 'Q', + '𝙍' => 'R', + '𝙎' => 'S', + '𝙏' => 'T', + '𝙐' => 'U', + '𝙑' => 'V', + '𝙒' => 'W', + '𝙓' => 'X', + '𝙔' => 'Y', + '𝙕' => 'Z', + '𝙖' => 'a', + '𝙗' => 'b', + '𝙘' => 'c', + '𝙙' => 'd', + '𝙚' => 'e', + '𝙛' => 'f', + '𝙜' => 'g', + '𝙝' => 'h', + '𝙞' => 'i', + '𝙟' => 'j', + '𝙠' => 'k', + '𝙡' => 'l', + '𝙢' => 'm', + '𝙣' => 'n', + '𝙤' => 'o', + '𝙥' => 'p', + '𝙦' => 'q', + '𝙧' => 'r', + '𝙨' => 's', + '𝙩' => 't', + '𝙪' => 'u', + '𝙫' => 'v', + '𝙬' => 'w', + '𝙭' => 'x', + '𝙮' => 'y', + '𝙯' => 'z', + '𝙰' => 'A', + '𝙱' => 'B', + '𝙲' => 'C', + '𝙳' => 'D', + '𝙴' => 'E', + '𝙵' => 'F', + '𝙶' => 'G', + '𝙷' => 'H', + '𝙸' => 'I', + '𝙹' => 'J', + '𝙺' => 'K', + '𝙻' => 'L', + '𝙼' => 'M', + '𝙽' => 'N', + '𝙾' => 'O', + '𝙿' => 'P', + '𝚀' => 'Q', + '𝚁' => 'R', + '𝚂' => 'S', + '𝚃' => 'T', + '𝚄' => 'U', + '𝚅' => 'V', + '𝚆' => 'W', + '𝚇' => 'X', + '𝚈' => 'Y', + '𝚉' => 'Z', + '𝚊' => 'a', + '𝚋' => 'b', + '𝚌' => 'c', + '𝚍' => 'd', + '𝚎' => 'e', + '𝚏' => 'f', + '𝚐' => 'g', + '𝚑' => 'h', + '𝚒' => 'i', + '𝚓' => 'j', + '𝚔' => 'k', + '𝚕' => 'l', + '𝚖' => 'm', + '𝚗' => 'n', + '𝚘' => 'o', + '𝚙' => 'p', + '𝚚' => 'q', + '𝚛' => 'r', + '𝚜' => 's', + '𝚝' => 't', + '𝚞' => 'u', + '𝚟' => 'v', + '𝚠' => 'w', + '𝚡' => 'x', + '𝚢' => 'y', + '𝚣' => 'z', + '𝚤' => 'ı', + '𝚥' => 'ȷ', + '𝚨' => 'Α', + '𝚩' => 'Β', + '𝚪' => 'Γ', + '𝚫' => 'Δ', + '𝚬' => 'Ε', + '𝚭' => 'Ζ', + '𝚮' => 'Η', + '𝚯' => 'Θ', + '𝚰' => 'Ι', + '𝚱' => 'Κ', + '𝚲' => 'Λ', + '𝚳' => 'Μ', + '𝚴' => 'Ν', + '𝚵' => 'Ξ', + '𝚶' => 'Ο', + '𝚷' => 'Π', + '𝚸' => 'Ρ', + '𝚹' => 'ϴ', + '𝚺' => 'Σ', + '𝚻' => 'Τ', + '𝚼' => 'Υ', + '𝚽' => 'Φ', + '𝚾' => 'Χ', + '𝚿' => 'Ψ', + '𝛀' => 'Ω', + '𝛁' => '∇', + '𝛂' => 'α', + '𝛃' => 'β', + '𝛄' => 'γ', + '𝛅' => 'δ', + '𝛆' => 'ε', + '𝛇' => 'ζ', + '𝛈' => 'η', + '𝛉' => 'θ', + '𝛊' => 'ι', + '𝛋' => 'κ', + '𝛌' => 'λ', + '𝛍' => 'μ', + '𝛎' => 'ν', + '𝛏' => 'ξ', + '𝛐' => 'ο', + '𝛑' => 'π', + '𝛒' => 'ρ', + '𝛓' => 'ς', + '𝛔' => 'σ', + '𝛕' => 'τ', + '𝛖' => 'υ', + '𝛗' => 'φ', + '𝛘' => 'χ', + '𝛙' => 'ψ', + '𝛚' => 'ω', + '𝛛' => '∂', + '𝛜' => 'ϵ', + '𝛝' => 'ϑ', + '𝛞' => 'ϰ', + '𝛟' => 'ϕ', + '𝛠' => 'ϱ', + '𝛡' => 'ϖ', + '𝛢' => 'Α', + '𝛣' => 'Β', + '𝛤' => 'Γ', + '𝛥' => 'Δ', + '𝛦' => 'Ε', + '𝛧' => 'Ζ', + '𝛨' => 'Η', + '𝛩' => 'Θ', + '𝛪' => 'Ι', + '𝛫' => 'Κ', + '𝛬' => 'Λ', + '𝛭' => 'Μ', + '𝛮' => 'Ν', + '𝛯' => 'Ξ', + '𝛰' => 'Ο', + '𝛱' => 'Π', + '𝛲' => 'Ρ', + '𝛳' => 'ϴ', + '𝛴' => 'Σ', + '𝛵' => 'Τ', + '𝛶' => 'Υ', + '𝛷' => 'Φ', + '𝛸' => 'Χ', + '𝛹' => 'Ψ', + '𝛺' => 'Ω', + '𝛻' => '∇', + '𝛼' => 'α', + '𝛽' => 'β', + '𝛾' => 'γ', + '𝛿' => 'δ', + '𝜀' => 'ε', + '𝜁' => 'ζ', + '𝜂' => 'η', + '𝜃' => 'θ', + '𝜄' => 'ι', + '𝜅' => 'κ', + '𝜆' => 'λ', + '𝜇' => 'μ', + '𝜈' => 'ν', + '𝜉' => 'ξ', + '𝜊' => 'ο', + '𝜋' => 'π', + '𝜌' => 'ρ', + '𝜍' => 'ς', + '𝜎' => 'σ', + '𝜏' => 'τ', + '𝜐' => 'υ', + '𝜑' => 'φ', + '𝜒' => 'χ', + '𝜓' => 'ψ', + '𝜔' => 'ω', + '𝜕' => '∂', + '𝜖' => 'ϵ', + '𝜗' => 'ϑ', + '𝜘' => 'ϰ', + '𝜙' => 'ϕ', + '𝜚' => 'ϱ', + '𝜛' => 'ϖ', + '𝜜' => 'Α', + '𝜝' => 'Β', + '𝜞' => 'Γ', + '𝜟' => 'Δ', + '𝜠' => 'Ε', + '𝜡' => 'Ζ', + '𝜢' => 'Η', + '𝜣' => 'Θ', + '𝜤' => 'Ι', + '𝜥' => 'Κ', + '𝜦' => 'Λ', + '𝜧' => 'Μ', + '𝜨' => 'Ν', + '𝜩' => 'Ξ', + '𝜪' => 'Ο', + '𝜫' => 'Π', + '𝜬' => 'Ρ', + '𝜭' => 'ϴ', + '𝜮' => 'Σ', + '𝜯' => 'Τ', + '𝜰' => 'Υ', + '𝜱' => 'Φ', + '𝜲' => 'Χ', + '𝜳' => 'Ψ', + '𝜴' => 'Ω', + '𝜵' => '∇', + '𝜶' => 'α', + '𝜷' => 'β', + '𝜸' => 'γ', + '𝜹' => 'δ', + '𝜺' => 'ε', + '𝜻' => 'ζ', + '𝜼' => 'η', + '𝜽' => 'θ', + '𝜾' => 'ι', + '𝜿' => 'κ', + '𝝀' => 'λ', + '𝝁' => 'μ', + '𝝂' => 'ν', + '𝝃' => 'ξ', + '𝝄' => 'ο', + '𝝅' => 'π', + '𝝆' => 'ρ', + '𝝇' => 'ς', + '𝝈' => 'σ', + '𝝉' => 'τ', + '𝝊' => 'υ', + '𝝋' => 'φ', + '𝝌' => 'χ', + '𝝍' => 'ψ', + '𝝎' => 'ω', + '𝝏' => '∂', + '𝝐' => 'ϵ', + '𝝑' => 'ϑ', + '𝝒' => 'ϰ', + '𝝓' => 'ϕ', + '𝝔' => 'ϱ', + '𝝕' => 'ϖ', + '𝝖' => 'Α', + '𝝗' => 'Β', + '𝝘' => 'Γ', + '𝝙' => 'Δ', + '𝝚' => 'Ε', + '𝝛' => 'Ζ', + '𝝜' => 'Η', + '𝝝' => 'Θ', + '𝝞' => 'Ι', + '𝝟' => 'Κ', + '𝝠' => 'Λ', + '𝝡' => 'Μ', + '𝝢' => 'Ν', + '𝝣' => 'Ξ', + '𝝤' => 'Ο', + '𝝥' => 'Π', + '𝝦' => 'Ρ', + '𝝧' => 'ϴ', + '𝝨' => 'Σ', + '𝝩' => 'Τ', + '𝝪' => 'Υ', + '𝝫' => 'Φ', + '𝝬' => 'Χ', + '𝝭' => 'Ψ', + '𝝮' => 'Ω', + '𝝯' => '∇', + '𝝰' => 'α', + '𝝱' => 'β', + '𝝲' => 'γ', + '𝝳' => 'δ', + '𝝴' => 'ε', + '𝝵' => 'ζ', + '𝝶' => 'η', + '𝝷' => 'θ', + '𝝸' => 'ι', + '𝝹' => 'κ', + '𝝺' => 'λ', + '𝝻' => 'μ', + '𝝼' => 'ν', + '𝝽' => 'ξ', + '𝝾' => 'ο', + '𝝿' => 'π', + '𝞀' => 'ρ', + '𝞁' => 'ς', + '𝞂' => 'σ', + '𝞃' => 'τ', + '𝞄' => 'υ', + '𝞅' => 'φ', + '𝞆' => 'χ', + '𝞇' => 'ψ', + '𝞈' => 'ω', + '𝞉' => '∂', + '𝞊' => 'ϵ', + '𝞋' => 'ϑ', + '𝞌' => 'ϰ', + '𝞍' => 'ϕ', + '𝞎' => 'ϱ', + '𝞏' => 'ϖ', + '𝞐' => 'Α', + '𝞑' => 'Β', + '𝞒' => 'Γ', + '𝞓' => 'Δ', + '𝞔' => 'Ε', + '𝞕' => 'Ζ', + '𝞖' => 'Η', + '𝞗' => 'Θ', + '𝞘' => 'Ι', + '𝞙' => 'Κ', + '𝞚' => 'Λ', + '𝞛' => 'Μ', + '𝞜' => 'Ν', + '𝞝' => 'Ξ', + '𝞞' => 'Ο', + '𝞟' => 'Π', + '𝞠' => 'Ρ', + '𝞡' => 'ϴ', + '𝞢' => 'Σ', + '𝞣' => 'Τ', + '𝞤' => 'Υ', + '𝞥' => 'Φ', + '𝞦' => 'Χ', + '𝞧' => 'Ψ', + '𝞨' => 'Ω', + '𝞩' => '∇', + '𝞪' => 'α', + '𝞫' => 'β', + '𝞬' => 'γ', + '𝞭' => 'δ', + '𝞮' => 'ε', + '𝞯' => 'ζ', + '𝞰' => 'η', + '𝞱' => 'θ', + '𝞲' => 'ι', + '𝞳' => 'κ', + '𝞴' => 'λ', + '𝞵' => 'μ', + '𝞶' => 'ν', + '𝞷' => 'ξ', + '𝞸' => 'ο', + '𝞹' => 'π', + '𝞺' => 'ρ', + '𝞻' => 'ς', + '𝞼' => 'σ', + '𝞽' => 'τ', + '𝞾' => 'υ', + '𝞿' => 'φ', + '𝟀' => 'χ', + '𝟁' => 'ψ', + '𝟂' => 'ω', + '𝟃' => '∂', + '𝟄' => 'ϵ', + '𝟅' => 'ϑ', + '𝟆' => 'ϰ', + '𝟇' => 'ϕ', + '𝟈' => 'ϱ', + '𝟉' => 'ϖ', + '𝟊' => 'Ϝ', + '𝟋' => 'ϝ', + '𝟎' => '0', + '𝟏' => '1', + '𝟐' => '2', + '𝟑' => '3', + '𝟒' => '4', + '𝟓' => '5', + '𝟔' => '6', + '𝟕' => '7', + '𝟖' => '8', + '𝟗' => '9', + '𝟘' => '0', + '𝟙' => '1', + '𝟚' => '2', + '𝟛' => '3', + '𝟜' => '4', + '𝟝' => '5', + '𝟞' => '6', + '𝟟' => '7', + '𝟠' => '8', + '𝟡' => '9', + '𝟢' => '0', + '𝟣' => '1', + '𝟤' => '2', + '𝟥' => '3', + '𝟦' => '4', + '𝟧' => '5', + '𝟨' => '6', + '𝟩' => '7', + '𝟪' => '8', + '𝟫' => '9', + '𝟬' => '0', + '𝟭' => '1', + '𝟮' => '2', + '𝟯' => '3', + '𝟰' => '4', + '𝟱' => '5', + '𝟲' => '6', + '𝟳' => '7', + '𝟴' => '8', + '𝟵' => '9', + '𝟶' => '0', + '𝟷' => '1', + '𝟸' => '2', + '𝟹' => '3', + '𝟺' => '4', + '𝟻' => '5', + '𝟼' => '6', + '𝟽' => '7', + '𝟾' => '8', + '𝟿' => '9', + '𞸀' => 'ا', + '𞸁' => 'ب', + '𞸂' => 'ج', + '𞸃' => 'د', + '𞸅' => 'و', + '𞸆' => 'ز', + '𞸇' => 'ح', + '𞸈' => 'ط', + '𞸉' => 'ي', + '𞸊' => 'ك', + '𞸋' => 'ل', + '𞸌' => 'م', + '𞸍' => 'ن', + '𞸎' => 'س', + '𞸏' => 'ع', + '𞸐' => 'ف', + '𞸑' => 'ص', + '𞸒' => 'ق', + '𞸓' => 'ر', + '𞸔' => 'ش', + '𞸕' => 'ت', + '𞸖' => 'ث', + '𞸗' => 'خ', + '𞸘' => 'ذ', + '𞸙' => 'ض', + '𞸚' => 'ظ', + '𞸛' => 'غ', + '𞸜' => 'ٮ', + '𞸝' => 'ں', + '𞸞' => 'ڡ', + '𞸟' => 'ٯ', + '𞸡' => 'ب', + '𞸢' => 'ج', + '𞸤' => 'ه', + '𞸧' => 'ح', + '𞸩' => 'ي', + '𞸪' => 'ك', + '𞸫' => 'ل', + '𞸬' => 'م', + '𞸭' => 'ن', + '𞸮' => 'س', + '𞸯' => 'ع', + '𞸰' => 'ف', + '𞸱' => 'ص', + '𞸲' => 'ق', + '𞸴' => 'ش', + '𞸵' => 'ت', + '𞸶' => 'ث', + '𞸷' => 'خ', + '𞸹' => 'ض', + '𞸻' => 'غ', + '𞹂' => 'ج', + '𞹇' => 'ح', + '𞹉' => 'ي', + '𞹋' => 'ل', + '𞹍' => 'ن', + '𞹎' => 'س', + '𞹏' => 'ع', + '𞹑' => 'ص', + '𞹒' => 'ق', + '𞹔' => 'ش', + '𞹗' => 'خ', + '𞹙' => 'ض', + '𞹛' => 'غ', + '𞹝' => 'ں', + '𞹟' => 'ٯ', + '𞹡' => 'ب', + '𞹢' => 'ج', + '𞹤' => 'ه', + '𞹧' => 'ح', + '𞹨' => 'ط', + '𞹩' => 'ي', + '𞹪' => 'ك', + '𞹬' => 'م', + '𞹭' => 'ن', + '𞹮' => 'س', + '𞹯' => 'ع', + '𞹰' => 'ف', + '𞹱' => 'ص', + '𞹲' => 'ق', + '𞹴' => 'ش', + '𞹵' => 'ت', + '𞹶' => 'ث', + '𞹷' => 'خ', + '𞹹' => 'ض', + '𞹺' => 'ظ', + '𞹻' => 'غ', + '𞹼' => 'ٮ', + '𞹾' => 'ڡ', + '𞺀' => 'ا', + '𞺁' => 'ب', + '𞺂' => 'ج', + '𞺃' => 'د', + '𞺄' => 'ه', + '𞺅' => 'و', + '𞺆' => 'ز', + '𞺇' => 'ح', + '𞺈' => 'ط', + '𞺉' => 'ي', + '𞺋' => 'ل', + '𞺌' => 'م', + '𞺍' => 'ن', + '𞺎' => 'س', + '𞺏' => 'ع', + '𞺐' => 'ف', + '𞺑' => 'ص', + '𞺒' => 'ق', + '𞺓' => 'ر', + '𞺔' => 'ش', + '𞺕' => 'ت', + '𞺖' => 'ث', + '𞺗' => 'خ', + '𞺘' => 'ذ', + '𞺙' => 'ض', + '𞺚' => 'ظ', + '𞺛' => 'غ', + '𞺡' => 'ب', + '𞺢' => 'ج', + '𞺣' => 'د', + '𞺥' => 'و', + '𞺦' => 'ز', + '𞺧' => 'ح', + '𞺨' => 'ط', + '𞺩' => 'ي', + '𞺫' => 'ل', + '𞺬' => 'م', + '𞺭' => 'ن', + '𞺮' => 'س', + '𞺯' => 'ع', + '𞺰' => 'ف', + '𞺱' => 'ص', + '𞺲' => 'ق', + '𞺳' => 'ر', + '𞺴' => 'ش', + '𞺵' => 'ت', + '𞺶' => 'ث', + '𞺷' => 'خ', + '𞺸' => 'ذ', + '𞺹' => 'ض', + '𞺺' => 'ظ', + '𞺻' => 'غ', + '🄀' => '0.', + '🄁' => '0,', + '🄂' => '1,', + '🄃' => '2,', + '🄄' => '3,', + '🄅' => '4,', + '🄆' => '5,', + '🄇' => '6,', + '🄈' => '7,', + '🄉' => '8,', + '🄊' => '9,', + '🄐' => '(A)', + '🄑' => '(B)', + '🄒' => '(C)', + '🄓' => '(D)', + '🄔' => '(E)', + '🄕' => '(F)', + '🄖' => '(G)', + '🄗' => '(H)', + '🄘' => '(I)', + '🄙' => '(J)', + '🄚' => '(K)', + '🄛' => '(L)', + '🄜' => '(M)', + '🄝' => '(N)', + '🄞' => '(O)', + '🄟' => '(P)', + '🄠' => '(Q)', + '🄡' => '(R)', + '🄢' => '(S)', + '🄣' => '(T)', + '🄤' => '(U)', + '🄥' => '(V)', + '🄦' => '(W)', + '🄧' => '(X)', + '🄨' => '(Y)', + '🄩' => '(Z)', + '🄪' => '〔S〕', + '🄫' => '(C)', + '🄬' => '(R)', + '🄭' => '(CD)', + '🄮' => '(WZ)', + '🄰' => 'A', + '🄱' => 'B', + '🄲' => 'C', + '🄳' => 'D', + '🄴' => 'E', + '🄵' => 'F', + '🄶' => 'G', + '🄷' => 'H', + '🄸' => 'I', + '🄹' => 'J', + '🄺' => 'K', + '🄻' => 'L', + '🄼' => 'M', + '🄽' => 'N', + '🄾' => 'O', + '🄿' => 'P', + '🅀' => 'Q', + '🅁' => 'R', + '🅂' => 'S', + '🅃' => 'T', + '🅄' => 'U', + '🅅' => 'V', + '🅆' => 'W', + '🅇' => 'X', + '🅈' => 'Y', + '🅉' => 'Z', + '🅊' => 'HV', + '🅋' => 'MV', + '🅌' => 'SD', + '🅍' => 'SS', + '🅎' => 'PPV', + '🅏' => 'WC', + '🆐' => 'DJ', + '🈀' => 'ほか', + '🈁' => 'ココ', + '🈂' => 'サ', + '🈐' => '手', + '🈑' => '字', + '🈒' => '双', + '🈓' => 'デ', + '🈔' => '二', + '🈕' => '多', + '🈖' => '解', + '🈗' => '天', + '🈘' => '交', + '🈙' => '映', + '🈚' => '無', + '🈛' => '料', + '🈜' => '前', + '🈝' => '後', + '🈞' => '再', + '🈟' => '新', + '🈠' => '初', + '🈡' => '終', + '🈢' => '生', + '🈣' => '販', + '🈤' => '声', + '🈥' => '吹', + '🈦' => '演', + '🈧' => '投', + '🈨' => '捕', + '🈩' => '一', + '🈪' => '三', + '🈫' => '遊', + '🈬' => '左', + '🈭' => '中', + '🈮' => '右', + '🈯' => '指', + '🈰' => '走', + '🈱' => '打', + '🈲' => '禁', + '🈳' => '空', + '🈴' => '合', + '🈵' => '満', + '🈶' => '有', + '🈷' => '月', + '🈸' => '申', + '🈹' => '割', + '🈺' => '営', + '🈻' => '配', + '🉀' => '〔本〕', + '🉁' => '〔三〕', + '🉂' => '〔二〕', + '🉃' => '〔安〕', + '🉄' => '〔点〕', + '🉅' => '〔打〕', + '🉆' => '〔盗〕', + '🉇' => '〔勝〕', + '🉈' => '〔敗〕', + '🉐' => '(得)', + '🉑' => '(可)', + '🯰' => '0', + '🯱' => '1', + '🯲' => '2', + '🯳' => '3', + '🯴' => '4', + '🯵' => '5', + '🯶' => '6', + '🯷' => '7', + '🯸' => '8', + '🯹' => '9', + '丽' => '丽', + '丸' => '丸', + '乁' => '乁', + '𠄢' => '𠄢', + '你' => '你', + '侮' => '侮', + '侻' => '侻', + '倂' => '倂', + '偺' => '偺', + '備' => '備', + '僧' => '僧', + '像' => '像', + '㒞' => '㒞', + '𠘺' => '𠘺', + '免' => '免', + '兔' => '兔', + '兤' => '兤', + '具' => '具', + '𠔜' => '𠔜', + '㒹' => '㒹', + '內' => '內', + '再' => '再', + '𠕋' => '𠕋', + '冗' => '冗', + '冤' => '冤', + '仌' => '仌', + '冬' => '冬', + '况' => '况', + '𩇟' => '𩇟', + '凵' => '凵', + '刃' => '刃', + '㓟' => '㓟', + '刻' => '刻', + '剆' => '剆', + '割' => '割', + '剷' => '剷', + '㔕' => '㔕', + '勇' => '勇', + '勉' => '勉', + '勤' => '勤', + '勺' => '勺', + '包' => '包', + '匆' => '匆', + '北' => '北', + '卉' => '卉', + '卑' => '卑', + '博' => '博', + '即' => '即', + '卽' => '卽', + '卿' => '卿', + '卿' => '卿', + '卿' => '卿', + '𠨬' => '𠨬', + '灰' => '灰', + '及' => '及', + '叟' => '叟', + '𠭣' => '𠭣', + '叫' => '叫', + '叱' => '叱', + '吆' => '吆', + '咞' => '咞', + '吸' => '吸', + '呈' => '呈', + '周' => '周', + '咢' => '咢', + '哶' => '哶', + '唐' => '唐', + '啓' => '啓', + '啣' => '啣', + '善' => '善', + '善' => '善', + '喙' => '喙', + '喫' => '喫', + '喳' => '喳', + '嗂' => '嗂', + '圖' => '圖', + '嘆' => '嘆', + '圗' => '圗', + '噑' => '噑', + '噴' => '噴', + '切' => '切', + '壮' => '壮', + '城' => '城', + '埴' => '埴', + '堍' => '堍', + '型' => '型', + '堲' => '堲', + '報' => '報', + '墬' => '墬', + '𡓤' => '𡓤', + '売' => '売', + '壷' => '壷', + '夆' => '夆', + '多' => '多', + '夢' => '夢', + '奢' => '奢', + '𡚨' => '𡚨', + '𡛪' => '𡛪', + '姬' => '姬', + '娛' => '娛', + '娧' => '娧', + '姘' => '姘', + '婦' => '婦', + '㛮' => '㛮', + '㛼' => '㛼', + '嬈' => '嬈', + '嬾' => '嬾', + '嬾' => '嬾', + '𡧈' => '𡧈', + '寃' => '寃', + '寘' => '寘', + '寧' => '寧', + '寳' => '寳', + '𡬘' => '𡬘', + '寿' => '寿', + '将' => '将', + '当' => '当', + '尢' => '尢', + '㞁' => '㞁', + '屠' => '屠', + '屮' => '屮', + '峀' => '峀', + '岍' => '岍', + '𡷤' => '𡷤', + '嵃' => '嵃', + '𡷦' => '𡷦', + '嵮' => '嵮', + '嵫' => '嵫', + '嵼' => '嵼', + '巡' => '巡', + '巢' => '巢', + '㠯' => '㠯', + '巽' => '巽', + '帨' => '帨', + '帽' => '帽', + '幩' => '幩', + '㡢' => '㡢', + '𢆃' => '𢆃', + '㡼' => '㡼', + '庰' => '庰', + '庳' => '庳', + '庶' => '庶', + '廊' => '廊', + '𪎒' => '𪎒', + '廾' => '廾', + '𢌱' => '𢌱', + '𢌱' => '𢌱', + '舁' => '舁', + '弢' => '弢', + '弢' => '弢', + '㣇' => '㣇', + '𣊸' => '𣊸', + '𦇚' => '𦇚', + '形' => '形', + '彫' => '彫', + '㣣' => '㣣', + '徚' => '徚', + '忍' => '忍', + '志' => '志', + '忹' => '忹', + '悁' => '悁', + '㤺' => '㤺', + '㤜' => '㤜', + '悔' => '悔', + '𢛔' => '𢛔', + '惇' => '惇', + '慈' => '慈', + '慌' => '慌', + '慎' => '慎', + '慌' => '慌', + '慺' => '慺', + '憎' => '憎', + '憲' => '憲', + '憤' => '憤', + '憯' => '憯', + '懞' => '懞', + '懲' => '懲', + '懶' => '懶', + '成' => '成', + '戛' => '戛', + '扝' => '扝', + '抱' => '抱', + '拔' => '拔', + '捐' => '捐', + '𢬌' => '𢬌', + '挽' => '挽', + '拼' => '拼', + '捨' => '捨', + '掃' => '掃', + '揤' => '揤', + '𢯱' => '𢯱', + '搢' => '搢', + '揅' => '揅', + '掩' => '掩', + '㨮' => '㨮', + '摩' => '摩', + '摾' => '摾', + '撝' => '撝', + '摷' => '摷', + '㩬' => '㩬', + '敏' => '敏', + '敬' => '敬', + '𣀊' => '𣀊', + '旣' => '旣', + '書' => '書', + '晉' => '晉', + '㬙' => '㬙', + '暑' => '暑', + '㬈' => '㬈', + '㫤' => '㫤', + '冒' => '冒', + '冕' => '冕', + '最' => '最', + '暜' => '暜', + '肭' => '肭', + '䏙' => '䏙', + '朗' => '朗', + '望' => '望', + '朡' => '朡', + '杞' => '杞', + '杓' => '杓', + '𣏃' => '𣏃', + '㭉' => '㭉', + '柺' => '柺', + '枅' => '枅', + '桒' => '桒', + '梅' => '梅', + '𣑭' => '𣑭', + '梎' => '梎', + '栟' => '栟', + '椔' => '椔', + '㮝' => '㮝', + '楂' => '楂', + '榣' => '榣', + '槪' => '槪', + '檨' => '檨', + '𣚣' => '𣚣', + '櫛' => '櫛', + '㰘' => '㰘', + '次' => '次', + '𣢧' => '𣢧', + '歔' => '歔', + '㱎' => '㱎', + '歲' => '歲', + '殟' => '殟', + '殺' => '殺', + '殻' => '殻', + '𣪍' => '𣪍', + '𡴋' => '𡴋', + '𣫺' => '𣫺', + '汎' => '汎', + '𣲼' => '𣲼', + '沿' => '沿', + '泍' => '泍', + '汧' => '汧', + '洖' => '洖', + '派' => '派', + '海' => '海', + '流' => '流', + '浩' => '浩', + '浸' => '浸', + '涅' => '涅', + '𣴞' => '𣴞', + '洴' => '洴', + '港' => '港', + '湮' => '湮', + '㴳' => '㴳', + '滋' => '滋', + '滇' => '滇', + '𣻑' => '𣻑', + '淹' => '淹', + '潮' => '潮', + '𣽞' => '𣽞', + '𣾎' => '𣾎', + '濆' => '濆', + '瀹' => '瀹', + '瀞' => '瀞', + '瀛' => '瀛', + '㶖' => '㶖', + '灊' => '灊', + '災' => '災', + '灷' => '灷', + '炭' => '炭', + '𠔥' => '𠔥', + '煅' => '煅', + '𤉣' => '𤉣', + '熜' => '熜', + '𤎫' => '𤎫', + '爨' => '爨', + '爵' => '爵', + '牐' => '牐', + '𤘈' => '𤘈', + '犀' => '犀', + '犕' => '犕', + '𤜵' => '𤜵', + '𤠔' => '𤠔', + '獺' => '獺', + '王' => '王', + '㺬' => '㺬', + '玥' => '玥', + '㺸' => '㺸', + '㺸' => '㺸', + '瑇' => '瑇', + '瑜' => '瑜', + '瑱' => '瑱', + '璅' => '璅', + '瓊' => '瓊', + '㼛' => '㼛', + '甤' => '甤', + '𤰶' => '𤰶', + '甾' => '甾', + '𤲒' => '𤲒', + '異' => '異', + '𢆟' => '𢆟', + '瘐' => '瘐', + '𤾡' => '𤾡', + '𤾸' => '𤾸', + '𥁄' => '𥁄', + '㿼' => '㿼', + '䀈' => '䀈', + '直' => '直', + '𥃳' => '𥃳', + '𥃲' => '𥃲', + '𥄙' => '𥄙', + '𥄳' => '𥄳', + '眞' => '眞', + '真' => '真', + '真' => '真', + '睊' => '睊', + '䀹' => '䀹', + '瞋' => '瞋', + '䁆' => '䁆', + '䂖' => '䂖', + '𥐝' => '𥐝', + '硎' => '硎', + '碌' => '碌', + '磌' => '磌', + '䃣' => '䃣', + '𥘦' => '𥘦', + '祖' => '祖', + '𥚚' => '𥚚', + '𥛅' => '𥛅', + '福' => '福', + '秫' => '秫', + '䄯' => '䄯', + '穀' => '穀', + '穊' => '穊', + '穏' => '穏', + '𥥼' => '𥥼', + '𥪧' => '𥪧', + '𥪧' => '𥪧', + '竮' => '竮', + '䈂' => '䈂', + '𥮫' => '𥮫', + '篆' => '篆', + '築' => '築', + '䈧' => '䈧', + '𥲀' => '𥲀', + '糒' => '糒', + '䊠' => '䊠', + '糨' => '糨', + '糣' => '糣', + '紀' => '紀', + '𥾆' => '𥾆', + '絣' => '絣', + '䌁' => '䌁', + '緇' => '緇', + '縂' => '縂', + '繅' => '繅', + '䌴' => '䌴', + '𦈨' => '𦈨', + '𦉇' => '𦉇', + '䍙' => '䍙', + '𦋙' => '𦋙', + '罺' => '罺', + '𦌾' => '𦌾', + '羕' => '羕', + '翺' => '翺', + '者' => '者', + '𦓚' => '𦓚', + '𦔣' => '𦔣', + '聠' => '聠', + '𦖨' => '𦖨', + '聰' => '聰', + '𣍟' => '𣍟', + '䏕' => '䏕', + '育' => '育', + '脃' => '脃', + '䐋' => '䐋', + '脾' => '脾', + '媵' => '媵', + '𦞧' => '𦞧', + '𦞵' => '𦞵', + '𣎓' => '𣎓', + '𣎜' => '𣎜', + '舁' => '舁', + '舄' => '舄', + '辞' => '辞', + '䑫' => '䑫', + '芑' => '芑', + '芋' => '芋', + '芝' => '芝', + '劳' => '劳', + '花' => '花', + '芳' => '芳', + '芽' => '芽', + '苦' => '苦', + '𦬼' => '𦬼', + '若' => '若', + '茝' => '茝', + '荣' => '荣', + '莭' => '莭', + '茣' => '茣', + '莽' => '莽', + '菧' => '菧', + '著' => '著', + '荓' => '荓', + '菊' => '菊', + '菌' => '菌', + '菜' => '菜', + '𦰶' => '𦰶', + '𦵫' => '𦵫', + '𦳕' => '𦳕', + '䔫' => '䔫', + '蓱' => '蓱', + '蓳' => '蓳', + '蔖' => '蔖', + '𧏊' => '𧏊', + '蕤' => '蕤', + '𦼬' => '𦼬', + '䕝' => '䕝', + '䕡' => '䕡', + '𦾱' => '𦾱', + '𧃒' => '𧃒', + '䕫' => '䕫', + '虐' => '虐', + '虜' => '虜', + '虧' => '虧', + '虩' => '虩', + '蚩' => '蚩', + '蚈' => '蚈', + '蜎' => '蜎', + '蛢' => '蛢', + '蝹' => '蝹', + '蜨' => '蜨', + '蝫' => '蝫', + '螆' => '螆', + '䗗' => '䗗', + '蟡' => '蟡', + '蠁' => '蠁', + '䗹' => '䗹', + '衠' => '衠', + '衣' => '衣', + '𧙧' => '𧙧', + '裗' => '裗', + '裞' => '裞', + '䘵' => '䘵', + '裺' => '裺', + '㒻' => '㒻', + '𧢮' => '𧢮', + '𧥦' => '𧥦', + '䚾' => '䚾', + '䛇' => '䛇', + '誠' => '誠', + '諭' => '諭', + '變' => '變', + '豕' => '豕', + '𧲨' => '𧲨', + '貫' => '貫', + '賁' => '賁', + '贛' => '贛', + '起' => '起', + '𧼯' => '𧼯', + '𠠄' => '𠠄', + '跋' => '跋', + '趼' => '趼', + '跰' => '跰', + '𠣞' => '𠣞', + '軔' => '軔', + '輸' => '輸', + '𨗒' => '𨗒', + '𨗭' => '𨗭', + '邔' => '邔', + '郱' => '郱', + '鄑' => '鄑', + '𨜮' => '𨜮', + '鄛' => '鄛', + '鈸' => '鈸', + '鋗' => '鋗', + '鋘' => '鋘', + '鉼' => '鉼', + '鏹' => '鏹', + '鐕' => '鐕', + '𨯺' => '𨯺', + '開' => '開', + '䦕' => '䦕', + '閷' => '閷', + '𨵷' => '𨵷', + '䧦' => '䧦', + '雃' => '雃', + '嶲' => '嶲', + '霣' => '霣', + '𩅅' => '𩅅', + '𩈚' => '𩈚', + '䩮' => '䩮', + '䩶' => '䩶', + '韠' => '韠', + '𩐊' => '𩐊', + '䪲' => '䪲', + '𩒖' => '𩒖', + '頋' => '頋', + '頋' => '頋', + '頩' => '頩', + '𩖶' => '𩖶', + '飢' => '飢', + '䬳' => '䬳', + '餩' => '餩', + '馧' => '馧', + '駂' => '駂', + '駾' => '駾', + '䯎' => '䯎', + '𩬰' => '𩬰', + '鬒' => '鬒', + '鱀' => '鱀', + '鳽' => '鳽', + '䳎' => '䳎', + '䳭' => '䳭', + '鵧' => '鵧', + '𪃎' => '𪃎', + '䳸' => '䳸', + '𪄅' => '𪄅', + '𪈎' => '𪈎', + '𪊑' => '𪊑', + '麻' => '麻', + '䵖' => '䵖', + '黹' => '黹', + '黾' => '黾', + '鼅' => '鼅', + '鼏' => '鼏', + '鼖' => '鼖', + '鼻' => '鼻', + '𪘀' => '𪘀', + 'Æ' => 'AE', + 'Ð' => 'D', + 'Ø' => 'O', + 'Þ' => 'TH', + 'ß' => 'ss', + 'æ' => 'ae', + 'ð' => 'd', + 'ø' => 'o', + 'þ' => 'th', + 'Đ' => 'D', + 'đ' => 'd', + 'Ħ' => 'H', + 'ħ' => 'h', + 'ı' => 'i', + 'ĸ' => 'q', + 'Ł' => 'L', + 'ł' => 'l', + 'Ŋ' => 'N', + 'ŋ' => 'n', + 'Œ' => 'OE', + 'œ' => 'oe', + 'Ŧ' => 'T', + 'ŧ' => 't', + 'ƀ' => 'b', + 'Ɓ' => 'B', + 'Ƃ' => 'B', + 'ƃ' => 'b', + 'Ƈ' => 'C', + 'ƈ' => 'c', + 'Ɖ' => 'D', + 'Ɗ' => 'D', + 'Ƌ' => 'D', + 'ƌ' => 'd', + 'Ɛ' => 'E', + 'Ƒ' => 'F', + 'ƒ' => 'f', + 'Ɠ' => 'G', + 'ƕ' => 'hv', + 'Ɩ' => 'I', + 'Ɨ' => 'I', + 'Ƙ' => 'K', + 'ƙ' => 'k', + 'ƚ' => 'l', + 'Ɲ' => 'N', + 'ƞ' => 'n', + 'Ƣ' => 'OI', + 'ƣ' => 'oi', + 'Ƥ' => 'P', + 'ƥ' => 'p', + 'ƫ' => 't', + 'Ƭ' => 'T', + 'ƭ' => 't', + 'Ʈ' => 'T', + 'Ʋ' => 'V', + 'Ƴ' => 'Y', + 'ƴ' => 'y', + 'Ƶ' => 'Z', + 'ƶ' => 'z', + 'Ǥ' => 'G', + 'ǥ' => 'g', + 'ȡ' => 'd', + 'Ȥ' => 'Z', + 'ȥ' => 'z', + 'ȴ' => 'l', + 'ȵ' => 'n', + 'ȶ' => 't', + 'ȷ' => 'j', + 'ȸ' => 'db', + 'ȹ' => 'qp', + 'Ⱥ' => 'A', + 'Ȼ' => 'C', + 'ȼ' => 'c', + 'Ƚ' => 'L', + 'Ⱦ' => 'T', + 'ȿ' => 's', + 'ɀ' => 'z', + 'Ƀ' => 'B', + 'Ʉ' => 'U', + 'Ɇ' => 'E', + 'ɇ' => 'e', + 'Ɉ' => 'J', + 'ɉ' => 'j', + 'Ɍ' => 'R', + 'ɍ' => 'r', + 'Ɏ' => 'Y', + 'ɏ' => 'y', + 'ɓ' => 'b', + 'ɕ' => 'c', + 'ɖ' => 'd', + 'ɗ' => 'd', + 'ɛ' => 'e', + 'ɟ' => 'j', + 'ɠ' => 'g', + 'ɡ' => 'g', + 'ɢ' => 'G', + 'ɦ' => 'h', + 'ɧ' => 'h', + 'ɨ' => 'i', + 'ɪ' => 'I', + 'ɫ' => 'l', + 'ɬ' => 'l', + 'ɭ' => 'l', + 'ɱ' => 'm', + 'ɲ' => 'n', + 'ɳ' => 'n', + 'ɴ' => 'N', + 'ɶ' => 'OE', + 'ɼ' => 'r', + 'ɽ' => 'r', + 'ɾ' => 'r', + 'ʀ' => 'R', + 'ʂ' => 's', + 'ʈ' => 't', + 'ʉ' => 'u', + 'ʋ' => 'v', + 'ʏ' => 'Y', + 'ʐ' => 'z', + 'ʑ' => 'z', + 'ʙ' => 'B', + 'ʛ' => 'G', + 'ʜ' => 'H', + 'ʝ' => 'j', + 'ʟ' => 'L', + 'ʠ' => 'q', + 'ʣ' => 'dz', + 'ʥ' => 'dz', + 'ʦ' => 'ts', + 'ʪ' => 'ls', + 'ʫ' => 'lz', + 'ᴀ' => 'A', + 'ᴁ' => 'AE', + 'ᴃ' => 'B', + 'ᴄ' => 'C', + 'ᴅ' => 'D', + 'ᴆ' => 'D', + 'ᴇ' => 'E', + 'ᴊ' => 'J', + 'ᴋ' => 'K', + 'ᴌ' => 'L', + 'ᴍ' => 'M', + 'ᴏ' => 'O', + 'ᴘ' => 'P', + 'ᴛ' => 'T', + 'ᴜ' => 'U', + 'ᴠ' => 'V', + 'ᴡ' => 'W', + 'ᴢ' => 'Z', + 'ᵫ' => 'ue', + 'ᵬ' => 'b', + 'ᵭ' => 'd', + 'ᵮ' => 'f', + 'ᵯ' => 'm', + 'ᵰ' => 'n', + 'ᵱ' => 'p', + 'ᵲ' => 'r', + 'ᵳ' => 'r', + 'ᵴ' => 's', + 'ᵵ' => 't', + 'ᵶ' => 'z', + 'ᵺ' => 'th', + 'ᵻ' => 'I', + 'ᵽ' => 'p', + 'ᵾ' => 'U', + 'ᶀ' => 'b', + 'ᶁ' => 'd', + 'ᶂ' => 'f', + 'ᶃ' => 'g', + 'ᶄ' => 'k', + 'ᶅ' => 'l', + 'ᶆ' => 'm', + 'ᶇ' => 'n', + 'ᶈ' => 'p', + 'ᶉ' => 'r', + 'ᶊ' => 's', + 'ᶌ' => 'v', + 'ᶍ' => 'x', + 'ᶎ' => 'z', + 'ᶏ' => 'a', + 'ᶑ' => 'd', + 'ᶒ' => 'e', + 'ᶓ' => 'e', + 'ᶖ' => 'i', + 'ᶙ' => 'u', + 'ẜ' => 's', + 'ẝ' => 's', + 'ẞ' => 'SS', + 'Ỻ' => 'LL', + 'ỻ' => 'll', + 'Ỽ' => 'V', + 'ỽ' => 'v', + 'Ỿ' => 'Y', + 'ỿ' => 'y', + 'Ⱡ' => 'L', + 'ⱡ' => 'l', + 'Ɫ' => 'L', + 'Ᵽ' => 'P', + 'Ɽ' => 'R', + 'ⱥ' => 'a', + 'ⱦ' => 't', + 'Ⱨ' => 'H', + 'ⱨ' => 'h', + 'Ⱪ' => 'K', + 'ⱪ' => 'k', + 'Ⱬ' => 'Z', + 'ⱬ' => 'z', + 'Ɱ' => 'M', + 'ⱱ' => 'v', + 'Ⱳ' => 'W', + 'ⱳ' => 'w', + 'ⱴ' => 'v', + 'ⱸ' => 'e', + 'ⱺ' => 'o', + 'Ȿ' => 'S', + 'Ɀ' => 'Z', + 'ꜰ' => 'F', + 'ꜱ' => 'S', + 'Ꜳ' => 'AA', + 'ꜳ' => 'aa', + 'Ꜵ' => 'AO', + 'ꜵ' => 'ao', + 'Ꜷ' => 'AU', + 'ꜷ' => 'au', + 'Ꜹ' => 'AV', + 'ꜹ' => 'av', + 'Ꜻ' => 'AV', + 'ꜻ' => 'av', + 'Ꜽ' => 'AY', + 'ꜽ' => 'ay', + 'Ꝁ' => 'K', + 'ꝁ' => 'k', + 'Ꝃ' => 'K', + 'ꝃ' => 'k', + 'Ꝅ' => 'K', + 'ꝅ' => 'k', + 'Ꝇ' => 'L', + 'ꝇ' => 'l', + 'Ꝉ' => 'L', + 'ꝉ' => 'l', + 'Ꝋ' => 'O', + 'ꝋ' => 'o', + 'Ꝍ' => 'O', + 'ꝍ' => 'o', + 'Ꝏ' => 'OO', + 'ꝏ' => 'oo', + 'Ꝑ' => 'P', + 'ꝑ' => 'p', + 'Ꝓ' => 'P', + 'ꝓ' => 'p', + 'Ꝕ' => 'P', + 'ꝕ' => 'p', + 'Ꝗ' => 'Q', + 'ꝗ' => 'q', + 'Ꝙ' => 'Q', + 'ꝙ' => 'q', + 'Ꝟ' => 'V', + 'ꝟ' => 'v', + 'Ꝡ' => 'VY', + 'ꝡ' => 'vy', + 'Ꝥ' => 'TH', + 'ꝥ' => 'th', + 'Ꝧ' => 'TH', + 'ꝧ' => 'th', + 'ꝱ' => 'd', + 'ꝲ' => 'l', + 'ꝳ' => 'm', + 'ꝴ' => 'n', + 'ꝵ' => 'r', + 'ꝶ' => 'R', + 'ꝷ' => 't', + 'Ꝺ' => 'D', + 'ꝺ' => 'd', + 'Ꝼ' => 'F', + 'ꝼ' => 'f', + 'Ꞇ' => 'T', + 'ꞇ' => 't', + 'Ꞑ' => 'N', + 'ꞑ' => 'n', + 'Ꞓ' => 'C', + 'ꞓ' => 'c', + 'Ꞡ' => 'G', + 'ꞡ' => 'g', + 'Ꞣ' => 'K', + 'ꞣ' => 'k', + 'Ꞥ' => 'N', + 'ꞥ' => 'n', + 'Ꞧ' => 'R', + 'ꞧ' => 'r', + 'Ꞩ' => 'S', + 'ꞩ' => 's', + 'Ɦ' => 'H', + '©' => '(C)', + '®' => '(R)', + '₠' => 'CE', + '₢' => 'Cr', + '₣' => 'Fr.', + '₤' => 'L.', + '₧' => 'Pts', + '₹' => 'Rs', + '₺' => 'TL', + '℗' => '(P)', + '℘' => 'P', + '℞' => 'Rx', + '〇' => '0', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + 'ʹ' => '\'', + 'ʺ' => '"', + 'ʻ' => '\'', + 'ʼ' => '\'', + 'ʽ' => '\'', + 'ˈ' => '\'', + 'ˋ' => '`', + '‘' => '\'', + '’' => '\'', + '‚' => ',', + '‛' => '\'', + '“' => '"', + '”' => '"', + '„' => ',,', + '‟' => '"', + '′' => '\'', + '〝' => '"', + '〞' => '"', + '«' => '<<', + '»' => '>>', + '‹' => '<', + '›' => '>', + '­' => '-', + '‐' => '-', + '‑' => '-', + '‒' => '-', + '–' => '-', + '—' => '-', + '―' => '-', + '︱' => '-', + '︲' => '-', + '¡' => '!', + '¿' => '?', + '˂' => '<', + '˃' => '>', + '˄' => '^', + 'ˆ' => '^', + 'ː' => ':', + '˜' => '~', + '‖' => '||', + '⁄' => '/', + '⁅' => '[', + '⁆' => ']', + '⁎' => '*', + '、' => ',', + '。' => '.', + '〈' => '<', + '〉' => '>', + '《' => '<<', + '》' => '>>', + '〔' => '[', + '〕' => ']', + '〘' => '[', + '〙' => ']', + '〚' => '[', + '〛' => ']', + '︐' => ',', + '︑' => ',', + '︒' => '.', + '︓' => ':', + '︔' => ';', + '︕' => '!', + '︖' => '?', + '︙' => '...', + '︰' => '..', + '︵' => '(', + '︶' => ')', + '︷' => '{', + '︸' => '}', + '︹' => '[', + '︺' => ']', + '︽' => '<<', + '︾' => '>>', + '︿' => '<', + '﹀' => '>', + '﹇' => '[', + '﹈' => ']', + '±' => '+/-', + '×' => '*', + '÷' => '/', + '˖' => '+', + '˗' => '-', + '−' => '-', + '∕' => '/', + '∖' => '\\', + '∣' => '|', + '∥' => '||', + '≪' => '<<', + '≫' => '>>', + '⦅' => '((', + '⦆' => '))', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/bootstrap.php new file mode 100644 index 0000000..c11df3b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/bootstrap.php @@ -0,0 +1,88 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Iconv as p; + +if (extension_loaded('iconv')) { + return; +} + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!defined('ICONV_IMPL')) { + define('ICONV_IMPL', 'Symfony'); +} +if (!defined('ICONV_VERSION')) { + define('ICONV_VERSION', '1.0'); +} +if (!defined('ICONV_MIME_DECODE_STRICT')) { + define('ICONV_MIME_DECODE_STRICT', 1); +} +if (!defined('ICONV_MIME_DECODE_CONTINUE_ON_ERROR')) { + define('ICONV_MIME_DECODE_CONTINUE_ON_ERROR', 2); +} + +if (!function_exists('iconv')) { + function iconv($from_encoding, $to_encoding, $string) { return p\Iconv::iconv($from_encoding, $to_encoding, $string); } +} +if (!function_exists('iconv_get_encoding')) { + function iconv_get_encoding($type = 'all') { return p\Iconv::iconv_get_encoding($type); } +} +if (!function_exists('iconv_set_encoding')) { + function iconv_set_encoding($type, $encoding) { return p\Iconv::iconv_set_encoding($type, $encoding); } +} +if (!function_exists('iconv_mime_encode')) { + function iconv_mime_encode($field_name, $field_value, $options = []) { return p\Iconv::iconv_mime_encode($field_name, $field_value, $options); } +} +if (!function_exists('iconv_mime_decode_headers')) { + function iconv_mime_decode_headers($headers, $mode = 0, $encoding = null) { return p\Iconv::iconv_mime_decode_headers($headers, $mode, $encoding); } +} + +if (extension_loaded('mbstring')) { + if (!function_exists('iconv_strlen')) { + function iconv_strlen($string, $encoding = null) { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_strlen($string, $encoding); } + } + if (!function_exists('iconv_strpos')) { + function iconv_strpos($haystack, $needle, $offset = 0, $encoding = null) { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_strpos($haystack, $needle, $offset, $encoding); } + } + if (!function_exists('iconv_strrpos')) { + function iconv_strrpos($haystack, $needle, $encoding = null) { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_strrpos($haystack, $needle, 0, $encoding); } + } + if (!function_exists('iconv_substr')) { + function iconv_substr($string, $offset, $length = 2147483647, $encoding = null) { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_substr($string, $offset, $length, $encoding); } + } + if (!function_exists('iconv_mime_decode')) { + function iconv_mime_decode($string, $mode = 0, $encoding = null) { $currentMbEncoding = mb_internal_encoding(); null === $encoding && $encoding = p\Iconv::$internalEncoding; mb_internal_encoding($encoding); $decoded = mb_decode_mimeheader($string); mb_internal_encoding($currentMbEncoding); return $decoded; } + } +} else { + if (!function_exists('iconv_strlen')) { + if (extension_loaded('xml')) { + function iconv_strlen($string, $encoding = null) { return p\Iconv::strlen1($string, $encoding); } + } else { + function iconv_strlen($string, $encoding = null) { return p\Iconv::strlen2($string, $encoding); } + } + } + + if (!function_exists('iconv_strpos')) { + function iconv_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Iconv::iconv_strpos($haystack, $needle, $offset, $encoding); } + } + if (!function_exists('iconv_strrpos')) { + function iconv_strrpos($haystack, $needle, $encoding = null) { return p\Iconv::iconv_strrpos($haystack, $needle, $encoding); } + } + if (!function_exists('iconv_substr')) { + function iconv_substr($string, $offset, $length = 2147483647, $encoding = null) { return p\Iconv::iconv_substr($string, $offset, $length, $encoding); } + } + if (!function_exists('iconv_mime_decode')) { + function iconv_mime_decode($string, $mode = 0, $encoding = null) { return p\Iconv::iconv_mime_decode($string, $mode, $encoding); } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/bootstrap80.php b/php/libraries/composer/vendor/symfony/polyfill-iconv/bootstrap80.php new file mode 100644 index 0000000..04b1473 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/bootstrap80.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Iconv as p; + +if (!defined('ICONV_IMPL')) { + define('ICONV_IMPL', 'Symfony'); +} +if (!defined('ICONV_VERSION')) { + define('ICONV_VERSION', '1.0'); +} +if (!defined('ICONV_MIME_DECODE_STRICT')) { + define('ICONV_MIME_DECODE_STRICT', 1); +} +if (!defined('ICONV_MIME_DECODE_CONTINUE_ON_ERROR')) { + define('ICONV_MIME_DECODE_CONTINUE_ON_ERROR', 2); +} + +if (!function_exists('iconv')) { + function iconv(?string $from_encoding, ?string $to_encoding, ?string $string): string|false { return p\Iconv::iconv((string) $from_encoding, (string) $to_encoding, (string) $string); } +} +if (!function_exists('iconv_get_encoding')) { + function iconv_get_encoding(?string $type = 'all'): array|string|false { return p\Iconv::iconv_get_encoding((string) $type); } +} +if (!function_exists('iconv_set_encoding')) { + function iconv_set_encoding(?string $type, ?string $encoding): bool { return p\Iconv::iconv_set_encoding((string) $type, (string) $encoding); } +} +if (!function_exists('iconv_mime_encode')) { + function iconv_mime_encode(?string $field_name, ?string $field_value, ?array $options = []): string|false { return p\Iconv::iconv_mime_encode((string) $field_name, (string) $field_value, (array) $options); } +} +if (!function_exists('iconv_mime_decode_headers')) { + function iconv_mime_decode_headers(?string $headers, ?int $mode = 0, ?string $encoding = null): array|false { return p\Iconv::iconv_mime_decode_headers((string) $headers, (int) $mode, $encoding); } +} + +if (extension_loaded('mbstring')) { + if (!function_exists('iconv_strlen')) { + function iconv_strlen(?string $string, ?string $encoding = null): int|false { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_strlen((string) $string, $encoding); } + } + if (!function_exists('iconv_strpos')) { + function iconv_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } + } + if (!function_exists('iconv_strrpos')) { + function iconv_strrpos(?string $haystack, ?string $needle, ?string $encoding = null): int|false { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_strrpos((string) $haystack, (string) $needle, 0, $encoding); } + } + if (!function_exists('iconv_substr')) { + function iconv_substr(?string $string, ?int $offset, ?int $length = null, ?string $encoding = null): string|false { null === $encoding && $encoding = p\Iconv::$internalEncoding; return mb_substr((string) $string, (int) $offset, $length, $encoding); } + } + if (!function_exists('iconv_mime_decode')) { + function iconv_mime_decode($string, $mode = 0, $encoding = null) { $currentMbEncoding = mb_internal_encoding(); null === $encoding && $encoding = p\Iconv::$internalEncoding; mb_internal_encoding($encoding); $decoded = mb_decode_mimeheader($string); mb_internal_encoding($currentMbEncoding); return $decoded; } + } +} else { + if (!function_exists('iconv_strlen')) { + if (extension_loaded('xml')) { + function iconv_strlen(?string $string, ?string $encoding = null): int|false { return p\Iconv::strlen1((string) $string, $encoding); } + } else { + function iconv_strlen(?string $string, ?string $encoding = null): int|false { return p\Iconv::strlen2((string) $string, $encoding); } + } + } + + if (!function_exists('iconv_strpos')) { + function iconv_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Iconv::iconv_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } + } + if (!function_exists('iconv_strrpos')) { + function iconv_strrpos(?string $haystack, ?string $needle, ?string $encoding = null): int|false { return p\Iconv::iconv_strrpos((string) $haystack, (string) $needle, $encoding); } + } + if (!function_exists('iconv_substr')) { + function iconv_substr(?string $string, ?int $offset, ?int $length = null, ?string $encoding = null): string|false { return p\Iconv::iconv_substr((string) $string, (string) $offset, $length, $encoding); } + } + if (!function_exists('iconv_mime_decode')) { + function iconv_mime_decode(?string $string, ?int $mode = 0, ?string $encoding = null): string|false { return p\Iconv::iconv_mime_decode((string) $string, (int) $mode, $encoding); } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-iconv/composer.json b/php/libraries/composer/vendor/symfony/polyfill-iconv/composer.json new file mode 100644 index 0000000..2044a16 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-iconv/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/polyfill-iconv", + "type": "library", + "description": "Symfony polyfill for the Iconv extension", + "keywords": ["polyfill", "shim", "compatibility", "portable", "iconv"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-iconv": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Iconv\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-iconv": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/Grapheme.php b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/Grapheme.php new file mode 100644 index 0000000..5373f16 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/Grapheme.php @@ -0,0 +1,247 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Grapheme; + +\define('SYMFONY_GRAPHEME_CLUSTER_RX', ((float) \PCRE_VERSION < 10 ? (float) \PCRE_VERSION >= 8.32 : (float) \PCRE_VERSION >= 10.39) ? '\X' : Grapheme::GRAPHEME_CLUSTER_RX); + +/** + * Partial intl implementation in pure PHP. + * + * Implemented: + * - grapheme_extract - Extract a sequence of grapheme clusters from a text buffer, which must be encoded in UTF-8 + * - grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string + * - grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack + * - grapheme_strlen - Get string length in grapheme units + * - grapheme_strpos - Find position (in grapheme units) of first occurrence of a string + * - grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string + * - grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string + * - grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack + * - grapheme_substr - Return part of a string + * + * @author Nicolas Grekas + * + * @internal + */ +final class Grapheme +{ + // (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control]) + // This regular expression is a work around for http://bugs.exim.org/1279 + public const GRAPHEME_CLUSTER_RX = '(?:\r\n|(?:[ -~\x{200C}\x{200D}]|[ᆨ-ᇹ]+|[ᄀ-ᅟ]*(?:[가개갸걔거게겨계고과괘괴교구궈궤귀규그긔기까깨꺄꺠꺼께껴꼐꼬꽈꽤꾀꾜꾸꿔꿰뀌뀨끄끠끼나내냐냬너네녀녜노놔놰뇌뇨누눠눼뉘뉴느늬니다대댜댸더데뎌뎨도돠돼되됴두둬뒈뒤듀드듸디따때땨떄떠떼뗘뗴또똬뙈뙤뚀뚜뚸뛔뛰뜌뜨띄띠라래랴럐러레려례로롸뢔뢰료루뤄뤠뤼류르릐리마매먀먜머메며몌모뫄뫠뫼묘무뭐뭬뮈뮤므믜미바배뱌뱨버베벼볘보봐봬뵈뵤부붜붸뷔뷰브븨비빠빼뺘뺴뻐뻬뼈뼤뽀뽜뽸뾔뾰뿌뿨쀄쀠쀼쁘쁴삐사새샤섀서세셔셰소솨쇄쇠쇼수숴쉐쉬슈스싀시싸쌔쌰썌써쎄쎠쎼쏘쏴쐐쐬쑈쑤쒀쒜쒸쓔쓰씌씨아애야얘어에여예오와왜외요우워웨위유으의이자재쟈쟤저제져졔조좌좨죄죠주줘줴쥐쥬즈즤지짜째쨔쨰쩌쩨쪄쪠쪼쫘쫴쬐쬬쭈쭤쮀쮜쮸쯔쯰찌차채챠챼처체쳐쳬초촤쵀최쵸추춰췌취츄츠츼치카캐캬컈커케켜켸코콰쾌쾨쿄쿠쿼퀘퀴큐크킈키타태탸턔터테텨톄토톼퇘퇴툐투퉈퉤튀튜트틔티파패퍄퍠퍼페펴폐포퐈퐤푀표푸풔풰퓌퓨프픠피하해햐햬허헤혀혜호화홰회효후훠훼휘휴흐희히]?[ᅠ-ᆢ]+|[가-힣])[ᆨ-ᇹ]*|[ᄀ-ᅟ]+|[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}])[\p{Mn}\p{Me}\x{09BE}\x{09D7}\x{0B3E}\x{0B57}\x{0BBE}\x{0BD7}\x{0CC2}\x{0CD5}\x{0CD6}\x{0D3E}\x{0D57}\x{0DCF}\x{0DDF}\x{200C}\x{200D}\x{1D165}\x{1D16E}-\x{1D172}]*|[\p{Cc}\p{Cf}\p{Zl}\p{Zp}])'; + + private const CASE_FOLD = [ + ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], + ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], + ]; + + public static function grapheme_extract($s, $size, $type = \GRAPHEME_EXTR_COUNT, $start = 0, &$next = 0) + { + if (0 > $start) { + $start = \strlen($s) + $start; + } + + if (!\is_scalar($s)) { + $hasError = false; + set_error_handler(function () use (&$hasError) { $hasError = true; }); + $next = substr($s, $start); + restore_error_handler(); + if ($hasError) { + substr($s, $start); + $s = ''; + } else { + $s = $next; + } + } else { + $s = substr($s, $start); + } + $size = (int) $size; + $type = (int) $type; + $start = (int) $start; + + if (\GRAPHEME_EXTR_COUNT !== $type && \GRAPHEME_EXTR_MAXBYTES !== $type && \GRAPHEME_EXTR_MAXCHARS !== $type) { + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError('grapheme_extract(): Argument #3 ($type) must be one of GRAPHEME_EXTR_COUNT, GRAPHEME_EXTR_MAXBYTES, or GRAPHEME_EXTR_MAXCHARS'); + } + + if (!isset($s[0]) || 0 > $size || 0 > $start) { + return false; + } + if (0 === $size) { + return ''; + } + + $next = $start; + + $s = preg_split('/('.SYMFONY_GRAPHEME_CLUSTER_RX.')/u', "\r\n".$s, $size + 1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); + + if (!isset($s[1])) { + return false; + } + + $i = 1; + $ret = ''; + + do { + if (\GRAPHEME_EXTR_COUNT === $type) { + --$size; + } elseif (\GRAPHEME_EXTR_MAXBYTES === $type) { + $size -= \strlen($s[$i]); + } else { + $size -= iconv_strlen($s[$i], 'UTF-8//IGNORE'); + } + + if ($size >= 0) { + $ret .= $s[$i]; + } + } while (isset($s[++$i]) && $size > 0); + + $next += \strlen($ret); + + return $ret; + } + + public static function grapheme_strlen($s) + { + preg_replace('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', '', $s, -1, $len); + + return 0 === $len && '' !== $s ? null : $len; + } + + public static function grapheme_substr($s, $start, $len = null) + { + if (null === $len) { + $len = 2147483647; + } + + preg_match_all('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', $s, $s); + + $slen = \count($s[0]); + $start = (int) $start; + + if (0 > $start) { + $start += $slen; + } + if (0 > $start) { + if (\PHP_VERSION_ID < 80000) { + return false; + } + + $start = 0; + } + if ($start >= $slen) { + return \PHP_VERSION_ID >= 80000 ? '' : false; + } + + $rem = $slen - $start; + + if (0 > $len) { + $len += $rem; + } + if (0 === $len) { + return ''; + } + if (0 > $len) { + return \PHP_VERSION_ID >= 80000 ? '' : false; + } + if ($len > $rem) { + $len = $rem; + } + + return implode('', \array_slice($s[0], $start, $len)); + } + + public static function grapheme_strpos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 0); + } + + public static function grapheme_stripos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 1); + } + + public static function grapheme_strrpos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 2); + } + + public static function grapheme_strripos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 3); + } + + public static function grapheme_stristr($s, $needle, $beforeNeedle = false) + { + return mb_stristr($s, $needle, $beforeNeedle, 'UTF-8'); + } + + public static function grapheme_strstr($s, $needle, $beforeNeedle = false) + { + return mb_strstr($s, $needle, $beforeNeedle, 'UTF-8'); + } + + private static function grapheme_position($s, $needle, $offset, $mode) + { + $needle = (string) $needle; + if (80000 > \PHP_VERSION_ID && !preg_match('/./us', $needle)) { + return false; + } + $s = (string) $s; + if (!preg_match('/./us', $s)) { + return false; + } + if ($offset > 0) { + $s = self::grapheme_substr($s, $offset); + } elseif ($offset < 0) { + if (2 > $mode) { + $offset += self::grapheme_strlen($s); + $s = self::grapheme_substr($s, $offset); + if (0 > $offset) { + $offset = 0; + } + } elseif (0 > $offset += self::grapheme_strlen($needle)) { + $s = self::grapheme_substr($s, 0, $offset); + $offset = 0; + } else { + $offset = 0; + } + } + + // As UTF-8 is self-synchronizing, and we have ensured the strings are valid UTF-8, + // we can use normal binary string functions here. For case-insensitive searches, + // case fold the strings first. + $caseInsensitive = $mode & 1; + $reverse = $mode & 2; + if ($caseInsensitive) { + // Use the same case folding mode as mbstring does for mb_stripos(). + // Stick to SIMPLE case folding to avoid changing the length of the string, which + // might result in offsets being shifted. + $mode = \defined('MB_CASE_FOLD_SIMPLE') ? \MB_CASE_FOLD_SIMPLE : \MB_CASE_LOWER; + $s = mb_convert_case($s, $mode, 'UTF-8'); + $needle = mb_convert_case($needle, $mode, 'UTF-8'); + + if (!\defined('MB_CASE_FOLD_SIMPLE')) { + $s = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $s); + $needle = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $needle); + } + } + if ($reverse) { + $needlePos = strrpos($s, $needle); + } else { + $needlePos = strpos($s, $needle); + } + + return false !== $needlePos ? self::grapheme_strlen(substr($s, 0, $needlePos)) + $offset : false; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/LICENSE new file mode 100644 index 0000000..6e3afce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/README.md b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/README.md new file mode 100644 index 0000000..f55d92c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/README.md @@ -0,0 +1,31 @@ +Symfony Polyfill / Intl: Grapheme +================================= + +This component provides a partial, native PHP implementation of the +[Grapheme functions](https://php.net/intl.grapheme) from the +[Intl](https://php.net/intl) extension. + +- [`grapheme_extract`](https://php.net/grapheme_extract): Extract a sequence of grapheme + clusters from a text buffer, which must be encoded in UTF-8 +- [`grapheme_stripos`](https://php.net/grapheme_stripos): Find position (in grapheme units) + of first occurrence of a case-insensitive string +- [`grapheme_stristr`](https://php.net/grapheme_stristr): Returns part of haystack string + from the first occurrence of case-insensitive needle to the end of haystack +- [`grapheme_strlen`](https://php.net/grapheme_strlen): Get string length in grapheme units +- [`grapheme_strpos`](https://php.net/grapheme_strpos): Find position (in grapheme units) + of first occurrence of a string +- [`grapheme_strripos`](https://php.net/grapheme_strripos): Find position (in grapheme units) + of last occurrence of a case-insensitive string +- [`grapheme_strrpos`](https://php.net/grapheme_strrpos): Find position (in grapheme units) + of last occurrence of a string +- [`grapheme_strstr`](https://php.net/grapheme_strstr): Returns part of haystack string from + the first occurrence of needle to the end of haystack +- [`grapheme_substr`](https://php.net/grapheme_substr): Return part of a string + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/bootstrap.php new file mode 100644 index 0000000..a9ea03c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/bootstrap.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Grapheme as p; + +if (extension_loaded('intl')) { + return; +} + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!defined('GRAPHEME_EXTR_COUNT')) { + define('GRAPHEME_EXTR_COUNT', 0); +} +if (!defined('GRAPHEME_EXTR_MAXBYTES')) { + define('GRAPHEME_EXTR_MAXBYTES', 1); +} +if (!defined('GRAPHEME_EXTR_MAXCHARS')) { + define('GRAPHEME_EXTR_MAXCHARS', 2); +} + +if (!function_exists('grapheme_extract')) { + function grapheme_extract($haystack, $size, $type = 0, $start = 0, &$next = 0) { return p\Grapheme::grapheme_extract($haystack, $size, $type, $start, $next); } +} +if (!function_exists('grapheme_stripos')) { + function grapheme_stripos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_stripos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_stristr')) { + function grapheme_stristr($haystack, $needle, $beforeNeedle = false) { return p\Grapheme::grapheme_stristr($haystack, $needle, $beforeNeedle); } +} +if (!function_exists('grapheme_strlen')) { + function grapheme_strlen($input) { return p\Grapheme::grapheme_strlen($input); } +} +if (!function_exists('grapheme_strpos')) { + function grapheme_strpos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_strpos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_strripos')) { + function grapheme_strripos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_strripos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_strrpos')) { + function grapheme_strrpos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_strrpos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_strstr')) { + function grapheme_strstr($haystack, $needle, $beforeNeedle = false) { return p\Grapheme::grapheme_strstr($haystack, $needle, $beforeNeedle); } +} +if (!function_exists('grapheme_substr')) { + function grapheme_substr($string, $offset, $length = null) { return p\Grapheme::grapheme_substr($string, $offset, $length); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/bootstrap80.php b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/bootstrap80.php new file mode 100644 index 0000000..b8c0786 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/bootstrap80.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Grapheme as p; + +if (!defined('GRAPHEME_EXTR_COUNT')) { + define('GRAPHEME_EXTR_COUNT', 0); +} +if (!defined('GRAPHEME_EXTR_MAXBYTES')) { + define('GRAPHEME_EXTR_MAXBYTES', 1); +} +if (!defined('GRAPHEME_EXTR_MAXCHARS')) { + define('GRAPHEME_EXTR_MAXCHARS', 2); +} + +if (!function_exists('grapheme_extract')) { + function grapheme_extract(?string $haystack, ?int $size, ?int $type = GRAPHEME_EXTR_COUNT, ?int $offset = 0, &$next = null): string|false { return p\Grapheme::grapheme_extract((string) $haystack, (int) $size, (int) $type, (int) $offset, $next); } +} +if (!function_exists('grapheme_stripos')) { + function grapheme_stripos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_stripos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_stristr')) { + function grapheme_stristr(?string $haystack, ?string $needle, ?bool $beforeNeedle = false): string|false { return p\Grapheme::grapheme_stristr((string) $haystack, (string) $needle, (bool) $beforeNeedle); } +} +if (!function_exists('grapheme_strlen')) { + function grapheme_strlen(?string $string): int|false|null { return p\Grapheme::grapheme_strlen((string) $string); } +} +if (!function_exists('grapheme_strpos')) { + function grapheme_strpos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_strpos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_strripos')) { + function grapheme_strripos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_strripos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_strrpos')) { + function grapheme_strrpos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_strrpos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_strstr')) { + function grapheme_strstr(?string $haystack, ?string $needle, ?bool $beforeNeedle = false): string|false { return p\Grapheme::grapheme_strstr((string) $haystack, (string) $needle, (bool) $beforeNeedle); } +} +if (!function_exists('grapheme_substr')) { + function grapheme_substr(?string $string, ?int $offset, ?int $length = null): string|false { return p\Grapheme::grapheme_substr((string) $string, (int) $offset, $length); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/composer.json b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/composer.json new file mode 100644 index 0000000..a20d3fa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-grapheme/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/polyfill-intl-grapheme", + "type": "library", + "description": "Symfony polyfill for intl's grapheme_* functions", + "keywords": ["polyfill", "shim", "compatibility", "portable", "intl", "grapheme"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Intl\\Grapheme\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-intl": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Idn.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Idn.php new file mode 100644 index 0000000..3dc0612 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Idn.php @@ -0,0 +1,923 @@ + and Trevor Rowbotham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Idn; + +use Symfony\Polyfill\Intl\Idn\Resources\unidata\DisallowedRanges; +use Symfony\Polyfill\Intl\Idn\Resources\unidata\Regex; + +/** + * @see https://www.unicode.org/reports/tr46/ + * + * @internal + */ +final class Idn +{ + public const ERROR_EMPTY_LABEL = 1; + public const ERROR_LABEL_TOO_LONG = 2; + public const ERROR_DOMAIN_NAME_TOO_LONG = 4; + public const ERROR_LEADING_HYPHEN = 8; + public const ERROR_TRAILING_HYPHEN = 0x10; + public const ERROR_HYPHEN_3_4 = 0x20; + public const ERROR_LEADING_COMBINING_MARK = 0x40; + public const ERROR_DISALLOWED = 0x80; + public const ERROR_PUNYCODE = 0x100; + public const ERROR_LABEL_HAS_DOT = 0x200; + public const ERROR_INVALID_ACE_LABEL = 0x400; + public const ERROR_BIDI = 0x800; + public const ERROR_CONTEXTJ = 0x1000; + public const ERROR_CONTEXTO_PUNCTUATION = 0x2000; + public const ERROR_CONTEXTO_DIGITS = 0x4000; + + public const INTL_IDNA_VARIANT_2003 = 0; + public const INTL_IDNA_VARIANT_UTS46 = 1; + + public const IDNA_DEFAULT = 0; + public const IDNA_ALLOW_UNASSIGNED = 1; + public const IDNA_USE_STD3_RULES = 2; + public const IDNA_CHECK_BIDI = 4; + public const IDNA_CHECK_CONTEXTJ = 8; + public const IDNA_NONTRANSITIONAL_TO_ASCII = 16; + public const IDNA_NONTRANSITIONAL_TO_UNICODE = 32; + + public const MAX_DOMAIN_SIZE = 253; + public const MAX_LABEL_SIZE = 63; + + public const BASE = 36; + public const TMIN = 1; + public const TMAX = 26; + public const SKEW = 38; + public const DAMP = 700; + public const INITIAL_BIAS = 72; + public const INITIAL_N = 128; + public const DELIMITER = '-'; + public const MAX_INT = 2147483647; + + /** + * Contains the numeric value of a basic code point (for use in representing integers) in the + * range 0 to BASE-1, or -1 if b is does not represent a value. + * + * @var array + */ + private static $basicToDigit = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, -1, + + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + ]; + + /** + * @var array + */ + private static $virama; + + /** + * @var array + */ + private static $mapped; + + /** + * @var array + */ + private static $ignored; + + /** + * @var array + */ + private static $deviation; + + /** + * @var array + */ + private static $disallowed; + + /** + * @var array + */ + private static $disallowed_STD3_mapped; + + /** + * @var array + */ + private static $disallowed_STD3_valid; + + /** + * @var bool + */ + private static $mappingTableLoaded = false; + + /** + * @see https://www.unicode.org/reports/tr46/#ToASCII + * + * @param string $domainName + * @param int $options + * @param int $variant + * @param array $idna_info + * + * @return string|false + */ + public static function idn_to_ascii($domainName, $options = self::IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = []) + { + if (\PHP_VERSION_ID >= 70200 && self::INTL_IDNA_VARIANT_2003 === $variant) { + @trigger_error('idn_to_ascii(): INTL_IDNA_VARIANT_2003 is deprecated', \E_USER_DEPRECATED); + } + + $options = [ + 'CheckHyphens' => true, + 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & self::IDNA_CHECK_BIDI), + 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & self::IDNA_CHECK_CONTEXTJ), + 'UseSTD3ASCIIRules' => 0 !== ($options & self::IDNA_USE_STD3_RULES), + 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & self::IDNA_NONTRANSITIONAL_TO_ASCII), + 'VerifyDnsLength' => true, + ]; + $info = new Info(); + $labels = self::process((string) $domainName, $options, $info); + + foreach ($labels as $i => $label) { + // Only convert labels to punycode that contain non-ASCII code points + if (1 === preg_match('/[^\x00-\x7F]/', $label)) { + try { + $label = 'xn--'.self::punycodeEncode($label); + } catch (\Exception $e) { + $info->errors |= self::ERROR_PUNYCODE; + } + + $labels[$i] = $label; + } + } + + if ($options['VerifyDnsLength']) { + self::validateDomainAndLabelLength($labels, $info); + } + + $idna_info = [ + 'result' => implode('.', $labels), + 'isTransitionalDifferent' => $info->transitionalDifferent, + 'errors' => $info->errors, + ]; + + return 0 === $info->errors ? $idna_info['result'] : false; + } + + /** + * @see https://www.unicode.org/reports/tr46/#ToUnicode + * + * @param string $domainName + * @param int $options + * @param int $variant + * @param array $idna_info + * + * @return string|false + */ + public static function idn_to_utf8($domainName, $options = self::IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = []) + { + if (\PHP_VERSION_ID >= 70200 && self::INTL_IDNA_VARIANT_2003 === $variant) { + @trigger_error('idn_to_utf8(): INTL_IDNA_VARIANT_2003 is deprecated', \E_USER_DEPRECATED); + } + + $info = new Info(); + $labels = self::process((string) $domainName, [ + 'CheckHyphens' => true, + 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & self::IDNA_CHECK_BIDI), + 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & self::IDNA_CHECK_CONTEXTJ), + 'UseSTD3ASCIIRules' => 0 !== ($options & self::IDNA_USE_STD3_RULES), + 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & self::IDNA_NONTRANSITIONAL_TO_UNICODE), + ], $info); + $idna_info = [ + 'result' => implode('.', $labels), + 'isTransitionalDifferent' => $info->transitionalDifferent, + 'errors' => $info->errors, + ]; + + return 0 === $info->errors ? $idna_info['result'] : false; + } + + /** + * @param string $label + * + * @return bool + */ + private static function isValidContextJ(array $codePoints, $label) + { + if (!isset(self::$virama)) { + self::$virama = require __DIR__.\DIRECTORY_SEPARATOR.'Resources'.\DIRECTORY_SEPARATOR.'unidata'.\DIRECTORY_SEPARATOR.'virama.php'; + } + + $offset = 0; + + foreach ($codePoints as $i => $codePoint) { + if (0x200C !== $codePoint && 0x200D !== $codePoint) { + continue; + } + + if (!isset($codePoints[$i - 1])) { + return false; + } + + // If Canonical_Combining_Class(Before(cp)) .eq. Virama Then True; + if (isset(self::$virama[$codePoints[$i - 1]])) { + continue; + } + + // If RegExpMatch((Joining_Type:{L,D})(Joining_Type:T)*\u200C(Joining_Type:T)*(Joining_Type:{R,D})) Then + // True; + // Generated RegExp = ([Joining_Type:{L,D}][Joining_Type:T]*\u200C[Joining_Type:T]*)[Joining_Type:{R,D}] + if (0x200C === $codePoint && 1 === preg_match(Regex::ZWNJ, $label, $matches, \PREG_OFFSET_CAPTURE, $offset)) { + $offset += \strlen($matches[1][0]); + + continue; + } + + return false; + } + + return true; + } + + /** + * @see https://www.unicode.org/reports/tr46/#ProcessingStepMap + * + * @param string $input + * @param array $options + * + * @return string + */ + private static function mapCodePoints($input, array $options, Info $info) + { + $str = ''; + $useSTD3ASCIIRules = $options['UseSTD3ASCIIRules']; + $transitional = $options['Transitional_Processing']; + + foreach (self::utf8Decode($input) as $codePoint) { + $data = self::lookupCodePointStatus($codePoint, $useSTD3ASCIIRules); + + switch ($data['status']) { + case 'disallowed': + $info->errors |= self::ERROR_DISALLOWED; + + // no break. + + case 'valid': + $str .= mb_chr($codePoint, 'utf-8'); + + break; + + case 'ignored': + // Do nothing. + break; + + case 'mapped': + $str .= $data['mapping']; + + break; + + case 'deviation': + $info->transitionalDifferent = true; + $str .= ($transitional ? $data['mapping'] : mb_chr($codePoint, 'utf-8')); + + break; + } + } + + return $str; + } + + /** + * @see https://www.unicode.org/reports/tr46/#Processing + * + * @param string $domain + * @param array $options + * + * @return array + */ + private static function process($domain, array $options, Info $info) + { + // If VerifyDnsLength is not set, we are doing ToUnicode otherwise we are doing ToASCII and + // we need to respect the VerifyDnsLength option. + $checkForEmptyLabels = !isset($options['VerifyDnsLength']) || $options['VerifyDnsLength']; + + if ($checkForEmptyLabels && '' === $domain) { + $info->errors |= self::ERROR_EMPTY_LABEL; + + return [$domain]; + } + + // Step 1. Map each code point in the domain name string + $domain = self::mapCodePoints($domain, $options, $info); + + // Step 2. Normalize the domain name string to Unicode Normalization Form C. + if (!\Normalizer::isNormalized($domain, \Normalizer::FORM_C)) { + $domain = \Normalizer::normalize($domain, \Normalizer::FORM_C); + } + + // Step 3. Break the string into labels at U+002E (.) FULL STOP. + $labels = explode('.', $domain); + $lastLabelIndex = \count($labels) - 1; + + // Step 4. Convert and validate each label in the domain name string. + foreach ($labels as $i => $label) { + $validationOptions = $options; + + if ('xn--' === substr($label, 0, 4)) { + try { + $label = self::punycodeDecode(substr($label, 4)); + } catch (\Exception $e) { + $info->errors |= self::ERROR_PUNYCODE; + + continue; + } + + $validationOptions['Transitional_Processing'] = false; + $labels[$i] = $label; + } + + self::validateLabel($label, $info, $validationOptions, $i > 0 && $i === $lastLabelIndex); + } + + if ($info->bidiDomain && !$info->validBidiDomain) { + $info->errors |= self::ERROR_BIDI; + } + + // Any input domain name string that does not record an error has been successfully + // processed according to this specification. Conversely, if an input domain_name string + // causes an error, then the processing of the input domain_name string fails. Determining + // what to do with error input is up to the caller, and not in the scope of this document. + return $labels; + } + + /** + * @see https://tools.ietf.org/html/rfc5893#section-2 + * + * @param string $label + */ + private static function validateBidiLabel($label, Info $info) + { + if (1 === preg_match(Regex::RTL_LABEL, $label)) { + $info->bidiDomain = true; + + // Step 1. The first character must be a character with Bidi property L, R, or AL. + // If it has the R or AL property, it is an RTL label + if (1 !== preg_match(Regex::BIDI_STEP_1_RTL, $label)) { + $info->validBidiDomain = false; + + return; + } + + // Step 2. In an RTL label, only characters with the Bidi properties R, AL, AN, EN, ES, + // CS, ET, ON, BN, or NSM are allowed. + if (1 === preg_match(Regex::BIDI_STEP_2, $label)) { + $info->validBidiDomain = false; + + return; + } + + // Step 3. In an RTL label, the end of the label must be a character with Bidi property + // R, AL, EN, or AN, followed by zero or more characters with Bidi property NSM. + if (1 !== preg_match(Regex::BIDI_STEP_3, $label)) { + $info->validBidiDomain = false; + + return; + } + + // Step 4. In an RTL label, if an EN is present, no AN may be present, and vice versa. + if (1 === preg_match(Regex::BIDI_STEP_4_AN, $label) && 1 === preg_match(Regex::BIDI_STEP_4_EN, $label)) { + $info->validBidiDomain = false; + + return; + } + + return; + } + + // We are a LTR label + // Step 1. The first character must be a character with Bidi property L, R, or AL. + // If it has the L property, it is an LTR label. + if (1 !== preg_match(Regex::BIDI_STEP_1_LTR, $label)) { + $info->validBidiDomain = false; + + return; + } + + // Step 5. In an LTR label, only characters with the Bidi properties L, EN, + // ES, CS, ET, ON, BN, or NSM are allowed. + if (1 === preg_match(Regex::BIDI_STEP_5, $label)) { + $info->validBidiDomain = false; + + return; + } + + // Step 6.In an LTR label, the end of the label must be a character with Bidi property L or + // EN, followed by zero or more characters with Bidi property NSM. + if (1 !== preg_match(Regex::BIDI_STEP_6, $label)) { + $info->validBidiDomain = false; + + return; + } + } + + /** + * @param array $labels + */ + private static function validateDomainAndLabelLength(array $labels, Info $info) + { + $maxDomainSize = self::MAX_DOMAIN_SIZE; + $length = \count($labels); + + // Number of "." delimiters. + $domainLength = $length - 1; + + // If the last label is empty and it is not the first label, then it is the root label. + // Increase the max size by 1, making it 254, to account for the root label's "." + // delimiter. This also means we don't need to check the last label's length for being too + // long. + if ($length > 1 && '' === $labels[$length - 1]) { + ++$maxDomainSize; + --$length; + } + + for ($i = 0; $i < $length; ++$i) { + $bytes = \strlen($labels[$i]); + $domainLength += $bytes; + + if ($bytes > self::MAX_LABEL_SIZE) { + $info->errors |= self::ERROR_LABEL_TOO_LONG; + } + } + + if ($domainLength > $maxDomainSize) { + $info->errors |= self::ERROR_DOMAIN_NAME_TOO_LONG; + } + } + + /** + * @see https://www.unicode.org/reports/tr46/#Validity_Criteria + * + * @param string $label + * @param array $options + * @param bool $canBeEmpty + */ + private static function validateLabel($label, Info $info, array $options, $canBeEmpty) + { + if ('' === $label) { + if (!$canBeEmpty && (!isset($options['VerifyDnsLength']) || $options['VerifyDnsLength'])) { + $info->errors |= self::ERROR_EMPTY_LABEL; + } + + return; + } + + // Step 1. The label must be in Unicode Normalization Form C. + if (!\Normalizer::isNormalized($label, \Normalizer::FORM_C)) { + $info->errors |= self::ERROR_INVALID_ACE_LABEL; + } + + $codePoints = self::utf8Decode($label); + + if ($options['CheckHyphens']) { + // Step 2. If CheckHyphens, the label must not contain a U+002D HYPHEN-MINUS character + // in both the thrid and fourth positions. + if (isset($codePoints[2], $codePoints[3]) && 0x002D === $codePoints[2] && 0x002D === $codePoints[3]) { + $info->errors |= self::ERROR_HYPHEN_3_4; + } + + // Step 3. If CheckHyphens, the label must neither begin nor end with a U+002D + // HYPHEN-MINUS character. + if ('-' === substr($label, 0, 1)) { + $info->errors |= self::ERROR_LEADING_HYPHEN; + } + + if ('-' === substr($label, -1, 1)) { + $info->errors |= self::ERROR_TRAILING_HYPHEN; + } + } + + // Step 4. The label must not contain a U+002E (.) FULL STOP. + if (false !== strpos($label, '.')) { + $info->errors |= self::ERROR_LABEL_HAS_DOT; + } + + // Step 5. The label must not begin with a combining mark, that is: General_Category=Mark. + if (1 === preg_match(Regex::COMBINING_MARK, $label)) { + $info->errors |= self::ERROR_LEADING_COMBINING_MARK; + } + + // Step 6. Each code point in the label must only have certain status values according to + // Section 5, IDNA Mapping Table: + $transitional = $options['Transitional_Processing']; + $useSTD3ASCIIRules = $options['UseSTD3ASCIIRules']; + + foreach ($codePoints as $codePoint) { + $data = self::lookupCodePointStatus($codePoint, $useSTD3ASCIIRules); + $status = $data['status']; + + if ('valid' === $status || (!$transitional && 'deviation' === $status)) { + continue; + } + + $info->errors |= self::ERROR_DISALLOWED; + + break; + } + + // Step 7. If CheckJoiners, the label must satisify the ContextJ rules from Appendix A, in + // The Unicode Code Points and Internationalized Domain Names for Applications (IDNA) + // [IDNA2008]. + if ($options['CheckJoiners'] && !self::isValidContextJ($codePoints, $label)) { + $info->errors |= self::ERROR_CONTEXTJ; + } + + // Step 8. If CheckBidi, and if the domain name is a Bidi domain name, then the label must + // satisfy all six of the numbered conditions in [IDNA2008] RFC 5893, Section 2. + if ($options['CheckBidi'] && (!$info->bidiDomain || $info->validBidiDomain)) { + self::validateBidiLabel($label, $info); + } + } + + /** + * @see https://tools.ietf.org/html/rfc3492#section-6.2 + * + * @param string $input + * + * @return string + */ + private static function punycodeDecode($input) + { + $n = self::INITIAL_N; + $out = 0; + $i = 0; + $bias = self::INITIAL_BIAS; + $lastDelimIndex = strrpos($input, self::DELIMITER); + $b = false === $lastDelimIndex ? 0 : $lastDelimIndex; + $inputLength = \strlen($input); + $output = []; + $bytes = array_map('ord', str_split($input)); + + for ($j = 0; $j < $b; ++$j) { + if ($bytes[$j] > 0x7F) { + throw new \Exception('Invalid input'); + } + + $output[$out++] = $input[$j]; + } + + if ($b > 0) { + ++$b; + } + + for ($in = $b; $in < $inputLength; ++$out) { + $oldi = $i; + $w = 1; + + for ($k = self::BASE; /* no condition */; $k += self::BASE) { + if ($in >= $inputLength) { + throw new \Exception('Invalid input'); + } + + $digit = self::$basicToDigit[$bytes[$in++] & 0xFF]; + + if ($digit < 0) { + throw new \Exception('Invalid input'); + } + + if ($digit > intdiv(self::MAX_INT - $i, $w)) { + throw new \Exception('Integer overflow'); + } + + $i += $digit * $w; + + if ($k <= $bias) { + $t = self::TMIN; + } elseif ($k >= $bias + self::TMAX) { + $t = self::TMAX; + } else { + $t = $k - $bias; + } + + if ($digit < $t) { + break; + } + + $baseMinusT = self::BASE - $t; + + if ($w > intdiv(self::MAX_INT, $baseMinusT)) { + throw new \Exception('Integer overflow'); + } + + $w *= $baseMinusT; + } + + $outPlusOne = $out + 1; + $bias = self::adaptBias($i - $oldi, $outPlusOne, 0 === $oldi); + + if (intdiv($i, $outPlusOne) > self::MAX_INT - $n) { + throw new \Exception('Integer overflow'); + } + + $n += intdiv($i, $outPlusOne); + $i %= $outPlusOne; + array_splice($output, $i++, 0, [mb_chr($n, 'utf-8')]); + } + + return implode('', $output); + } + + /** + * @see https://tools.ietf.org/html/rfc3492#section-6.3 + * + * @param string $input + * + * @return string + */ + private static function punycodeEncode($input) + { + $n = self::INITIAL_N; + $delta = 0; + $out = 0; + $bias = self::INITIAL_BIAS; + $inputLength = 0; + $output = ''; + $iter = self::utf8Decode($input); + + foreach ($iter as $codePoint) { + ++$inputLength; + + if ($codePoint < 0x80) { + $output .= \chr($codePoint); + ++$out; + } + } + + $h = $out; + $b = $out; + + if ($b > 0) { + $output .= self::DELIMITER; + ++$out; + } + + while ($h < $inputLength) { + $m = self::MAX_INT; + + foreach ($iter as $codePoint) { + if ($codePoint >= $n && $codePoint < $m) { + $m = $codePoint; + } + } + + if ($m - $n > intdiv(self::MAX_INT - $delta, $h + 1)) { + throw new \Exception('Integer overflow'); + } + + $delta += ($m - $n) * ($h + 1); + $n = $m; + + foreach ($iter as $codePoint) { + if ($codePoint < $n && 0 === ++$delta) { + throw new \Exception('Integer overflow'); + } + + if ($codePoint === $n) { + $q = $delta; + + for ($k = self::BASE; /* no condition */; $k += self::BASE) { + if ($k <= $bias) { + $t = self::TMIN; + } elseif ($k >= $bias + self::TMAX) { + $t = self::TMAX; + } else { + $t = $k - $bias; + } + + if ($q < $t) { + break; + } + + $qMinusT = $q - $t; + $baseMinusT = self::BASE - $t; + $output .= self::encodeDigit($t + $qMinusT % $baseMinusT, false); + ++$out; + $q = intdiv($qMinusT, $baseMinusT); + } + + $output .= self::encodeDigit($q, false); + ++$out; + $bias = self::adaptBias($delta, $h + 1, $h === $b); + $delta = 0; + ++$h; + } + } + + ++$delta; + ++$n; + } + + return $output; + } + + /** + * @see https://tools.ietf.org/html/rfc3492#section-6.1 + * + * @param int $delta + * @param int $numPoints + * @param bool $firstTime + * + * @return int + */ + private static function adaptBias($delta, $numPoints, $firstTime) + { + // xxx >> 1 is a faster way of doing intdiv(xxx, 2) + $delta = $firstTime ? intdiv($delta, self::DAMP) : $delta >> 1; + $delta += intdiv($delta, $numPoints); + $k = 0; + + while ($delta > ((self::BASE - self::TMIN) * self::TMAX) >> 1) { + $delta = intdiv($delta, self::BASE - self::TMIN); + $k += self::BASE; + } + + return $k + intdiv((self::BASE - self::TMIN + 1) * $delta, $delta + self::SKEW); + } + + /** + * @param int $d + * @param bool $flag + * + * @return string + */ + private static function encodeDigit($d, $flag) + { + return \chr($d + 22 + 75 * ($d < 26 ? 1 : 0) - (($flag ? 1 : 0) << 5)); + } + + /** + * Takes a UTF-8 encoded string and converts it into a series of integer code points. Any + * invalid byte sequences will be replaced by a U+FFFD replacement code point. + * + * @see https://encoding.spec.whatwg.org/#utf-8-decoder + * + * @param string $input + * + * @return array + */ + private static function utf8Decode($input) + { + $bytesSeen = 0; + $bytesNeeded = 0; + $lowerBoundary = 0x80; + $upperBoundary = 0xBF; + $codePoint = 0; + $codePoints = []; + $length = \strlen($input); + + for ($i = 0; $i < $length; ++$i) { + $byte = \ord($input[$i]); + + if (0 === $bytesNeeded) { + if ($byte >= 0x00 && $byte <= 0x7F) { + $codePoints[] = $byte; + + continue; + } + + if ($byte >= 0xC2 && $byte <= 0xDF) { + $bytesNeeded = 1; + $codePoint = $byte & 0x1F; + } elseif ($byte >= 0xE0 && $byte <= 0xEF) { + if (0xE0 === $byte) { + $lowerBoundary = 0xA0; + } elseif (0xED === $byte) { + $upperBoundary = 0x9F; + } + + $bytesNeeded = 2; + $codePoint = $byte & 0xF; + } elseif ($byte >= 0xF0 && $byte <= 0xF4) { + if (0xF0 === $byte) { + $lowerBoundary = 0x90; + } elseif (0xF4 === $byte) { + $upperBoundary = 0x8F; + } + + $bytesNeeded = 3; + $codePoint = $byte & 0x7; + } else { + $codePoints[] = 0xFFFD; + } + + continue; + } + + if ($byte < $lowerBoundary || $byte > $upperBoundary) { + $codePoint = 0; + $bytesNeeded = 0; + $bytesSeen = 0; + $lowerBoundary = 0x80; + $upperBoundary = 0xBF; + --$i; + $codePoints[] = 0xFFFD; + + continue; + } + + $lowerBoundary = 0x80; + $upperBoundary = 0xBF; + $codePoint = ($codePoint << 6) | ($byte & 0x3F); + + if (++$bytesSeen !== $bytesNeeded) { + continue; + } + + $codePoints[] = $codePoint; + $codePoint = 0; + $bytesNeeded = 0; + $bytesSeen = 0; + } + + // String unexpectedly ended, so append a U+FFFD code point. + if (0 !== $bytesNeeded) { + $codePoints[] = 0xFFFD; + } + + return $codePoints; + } + + /** + * @param int $codePoint + * @param bool $useSTD3ASCIIRules + * + * @return array{status: string, mapping?: string} + */ + private static function lookupCodePointStatus($codePoint, $useSTD3ASCIIRules) + { + if (!self::$mappingTableLoaded) { + self::$mappingTableLoaded = true; + self::$mapped = require __DIR__.'/Resources/unidata/mapped.php'; + self::$ignored = require __DIR__.'/Resources/unidata/ignored.php'; + self::$deviation = require __DIR__.'/Resources/unidata/deviation.php'; + self::$disallowed = require __DIR__.'/Resources/unidata/disallowed.php'; + self::$disallowed_STD3_mapped = require __DIR__.'/Resources/unidata/disallowed_STD3_mapped.php'; + self::$disallowed_STD3_valid = require __DIR__.'/Resources/unidata/disallowed_STD3_valid.php'; + } + + if (isset(self::$mapped[$codePoint])) { + return ['status' => 'mapped', 'mapping' => self::$mapped[$codePoint]]; + } + + if (isset(self::$ignored[$codePoint])) { + return ['status' => 'ignored']; + } + + if (isset(self::$deviation[$codePoint])) { + return ['status' => 'deviation', 'mapping' => self::$deviation[$codePoint]]; + } + + if (isset(self::$disallowed[$codePoint]) || DisallowedRanges::inRange($codePoint)) { + return ['status' => 'disallowed']; + } + + $isDisallowedMapped = isset(self::$disallowed_STD3_mapped[$codePoint]); + + if ($isDisallowedMapped || isset(self::$disallowed_STD3_valid[$codePoint])) { + $status = 'disallowed'; + + if (!$useSTD3ASCIIRules) { + $status = $isDisallowedMapped ? 'mapped' : 'valid'; + } + + if ($isDisallowedMapped) { + return ['status' => $status, 'mapping' => self::$disallowed_STD3_mapped[$codePoint]]; + } + + return ['status' => $status]; + } + + return ['status' => 'valid']; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Info.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Info.php new file mode 100644 index 0000000..25c3582 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Info.php @@ -0,0 +1,23 @@ + and Trevor Rowbotham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Idn; + +/** + * @internal + */ +class Info +{ + public $bidiDomain = false; + public $errors = 0; + public $validBidiDomain = true; + public $transitionalDifferent = false; +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/LICENSE new file mode 100644 index 0000000..fd0a062 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier and Trevor Rowbotham + +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/php/libraries/composer/vendor/symfony/polyfill-intl-idn/README.md b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/README.md new file mode 100644 index 0000000..cae5517 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/README.md @@ -0,0 +1,12 @@ +Symfony Polyfill / Intl: Idn +============================ + +This component provides [`idn_to_ascii`](https://php.net/idn-to-ascii) and [`idn_to_utf8`](https://php.net/idn-to-utf8) functions to users who run php versions without the [Intl](https://php.net/intl) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/DisallowedRanges.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/DisallowedRanges.php new file mode 100644 index 0000000..d285acd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/DisallowedRanges.php @@ -0,0 +1,384 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Idn\Resources\unidata; + +/** + * @internal + */ +final class DisallowedRanges +{ + /** + * @param int $codePoint + * + * @return bool + */ + public static function inRange($codePoint) + { + if ($codePoint >= 128 && $codePoint <= 159) { + return true; + } + + if ($codePoint >= 2155 && $codePoint <= 2207) { + return true; + } + + if ($codePoint >= 3676 && $codePoint <= 3712) { + return true; + } + + if ($codePoint >= 3808 && $codePoint <= 3839) { + return true; + } + + if ($codePoint >= 4059 && $codePoint <= 4095) { + return true; + } + + if ($codePoint >= 4256 && $codePoint <= 4293) { + return true; + } + + if ($codePoint >= 6849 && $codePoint <= 6911) { + return true; + } + + if ($codePoint >= 11859 && $codePoint <= 11903) { + return true; + } + + if ($codePoint >= 42955 && $codePoint <= 42996) { + return true; + } + + if ($codePoint >= 55296 && $codePoint <= 57343) { + return true; + } + + if ($codePoint >= 57344 && $codePoint <= 63743) { + return true; + } + + if ($codePoint >= 64218 && $codePoint <= 64255) { + return true; + } + + if ($codePoint >= 64976 && $codePoint <= 65007) { + return true; + } + + if ($codePoint >= 65630 && $codePoint <= 65663) { + return true; + } + + if ($codePoint >= 65953 && $codePoint <= 65999) { + return true; + } + + if ($codePoint >= 66046 && $codePoint <= 66175) { + return true; + } + + if ($codePoint >= 66518 && $codePoint <= 66559) { + return true; + } + + if ($codePoint >= 66928 && $codePoint <= 67071) { + return true; + } + + if ($codePoint >= 67432 && $codePoint <= 67583) { + return true; + } + + if ($codePoint >= 67760 && $codePoint <= 67807) { + return true; + } + + if ($codePoint >= 67904 && $codePoint <= 67967) { + return true; + } + + if ($codePoint >= 68256 && $codePoint <= 68287) { + return true; + } + + if ($codePoint >= 68528 && $codePoint <= 68607) { + return true; + } + + if ($codePoint >= 68681 && $codePoint <= 68735) { + return true; + } + + if ($codePoint >= 68922 && $codePoint <= 69215) { + return true; + } + + if ($codePoint >= 69298 && $codePoint <= 69375) { + return true; + } + + if ($codePoint >= 69466 && $codePoint <= 69551) { + return true; + } + + if ($codePoint >= 70207 && $codePoint <= 70271) { + return true; + } + + if ($codePoint >= 70517 && $codePoint <= 70655) { + return true; + } + + if ($codePoint >= 70874 && $codePoint <= 71039) { + return true; + } + + if ($codePoint >= 71134 && $codePoint <= 71167) { + return true; + } + + if ($codePoint >= 71370 && $codePoint <= 71423) { + return true; + } + + if ($codePoint >= 71488 && $codePoint <= 71679) { + return true; + } + + if ($codePoint >= 71740 && $codePoint <= 71839) { + return true; + } + + if ($codePoint >= 72026 && $codePoint <= 72095) { + return true; + } + + if ($codePoint >= 72441 && $codePoint <= 72703) { + return true; + } + + if ($codePoint >= 72887 && $codePoint <= 72959) { + return true; + } + + if ($codePoint >= 73130 && $codePoint <= 73439) { + return true; + } + + if ($codePoint >= 73465 && $codePoint <= 73647) { + return true; + } + + if ($codePoint >= 74650 && $codePoint <= 74751) { + return true; + } + + if ($codePoint >= 75076 && $codePoint <= 77823) { + return true; + } + + if ($codePoint >= 78905 && $codePoint <= 82943) { + return true; + } + + if ($codePoint >= 83527 && $codePoint <= 92159) { + return true; + } + + if ($codePoint >= 92784 && $codePoint <= 92879) { + return true; + } + + if ($codePoint >= 93072 && $codePoint <= 93759) { + return true; + } + + if ($codePoint >= 93851 && $codePoint <= 93951) { + return true; + } + + if ($codePoint >= 94112 && $codePoint <= 94175) { + return true; + } + + if ($codePoint >= 101590 && $codePoint <= 101631) { + return true; + } + + if ($codePoint >= 101641 && $codePoint <= 110591) { + return true; + } + + if ($codePoint >= 110879 && $codePoint <= 110927) { + return true; + } + + if ($codePoint >= 111356 && $codePoint <= 113663) { + return true; + } + + if ($codePoint >= 113828 && $codePoint <= 118783) { + return true; + } + + if ($codePoint >= 119366 && $codePoint <= 119519) { + return true; + } + + if ($codePoint >= 119673 && $codePoint <= 119807) { + return true; + } + + if ($codePoint >= 121520 && $codePoint <= 122879) { + return true; + } + + if ($codePoint >= 122923 && $codePoint <= 123135) { + return true; + } + + if ($codePoint >= 123216 && $codePoint <= 123583) { + return true; + } + + if ($codePoint >= 123648 && $codePoint <= 124927) { + return true; + } + + if ($codePoint >= 125143 && $codePoint <= 125183) { + return true; + } + + if ($codePoint >= 125280 && $codePoint <= 126064) { + return true; + } + + if ($codePoint >= 126133 && $codePoint <= 126208) { + return true; + } + + if ($codePoint >= 126270 && $codePoint <= 126463) { + return true; + } + + if ($codePoint >= 126652 && $codePoint <= 126703) { + return true; + } + + if ($codePoint >= 126706 && $codePoint <= 126975) { + return true; + } + + if ($codePoint >= 127406 && $codePoint <= 127461) { + return true; + } + + if ($codePoint >= 127590 && $codePoint <= 127743) { + return true; + } + + if ($codePoint >= 129202 && $codePoint <= 129279) { + return true; + } + + if ($codePoint >= 129751 && $codePoint <= 129791) { + return true; + } + + if ($codePoint >= 129995 && $codePoint <= 130031) { + return true; + } + + if ($codePoint >= 130042 && $codePoint <= 131069) { + return true; + } + + if ($codePoint >= 173790 && $codePoint <= 173823) { + return true; + } + + if ($codePoint >= 191457 && $codePoint <= 194559) { + return true; + } + + if ($codePoint >= 195102 && $codePoint <= 196605) { + return true; + } + + if ($codePoint >= 201547 && $codePoint <= 262141) { + return true; + } + + if ($codePoint >= 262144 && $codePoint <= 327677) { + return true; + } + + if ($codePoint >= 327680 && $codePoint <= 393213) { + return true; + } + + if ($codePoint >= 393216 && $codePoint <= 458749) { + return true; + } + + if ($codePoint >= 458752 && $codePoint <= 524285) { + return true; + } + + if ($codePoint >= 524288 && $codePoint <= 589821) { + return true; + } + + if ($codePoint >= 589824 && $codePoint <= 655357) { + return true; + } + + if ($codePoint >= 655360 && $codePoint <= 720893) { + return true; + } + + if ($codePoint >= 720896 && $codePoint <= 786429) { + return true; + } + + if ($codePoint >= 786432 && $codePoint <= 851965) { + return true; + } + + if ($codePoint >= 851968 && $codePoint <= 917501) { + return true; + } + + if ($codePoint >= 917536 && $codePoint <= 917631) { + return true; + } + + if ($codePoint >= 917632 && $codePoint <= 917759) { + return true; + } + + if ($codePoint >= 918000 && $codePoint <= 983037) { + return true; + } + + if ($codePoint >= 983040 && $codePoint <= 1048573) { + return true; + } + + if ($codePoint >= 1048576 && $codePoint <= 1114109) { + return true; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/Regex.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/Regex.php new file mode 100644 index 0000000..3c6af0c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/Regex.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\Polyfill\Intl\Idn\Resources\unidata; + +/** + * @internal + */ +final class Regex +{ + const COMBINING_MARK = '/^[\x{0300}-\x{036F}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{0610}-\x{061A}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DF}-\x{06E4}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07FD}\x{0816}-\x{0819}\x{081B}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E3}-\x{0902}\x{0903}\x{093A}\x{093B}\x{093C}\x{093E}-\x{0940}\x{0941}-\x{0948}\x{0949}-\x{094C}\x{094D}\x{094E}-\x{094F}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{0982}-\x{0983}\x{09BC}\x{09BE}-\x{09C0}\x{09C1}-\x{09C4}\x{09C7}-\x{09C8}\x{09CB}-\x{09CC}\x{09CD}\x{09D7}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A03}\x{0A3C}\x{0A3E}-\x{0A40}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0A83}\x{0ABC}\x{0ABE}-\x{0AC0}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0AC9}\x{0ACB}-\x{0ACC}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B02}-\x{0B03}\x{0B3C}\x{0B3E}\x{0B3F}\x{0B40}\x{0B41}-\x{0B44}\x{0B47}-\x{0B48}\x{0B4B}-\x{0B4C}\x{0B4D}\x{0B55}-\x{0B56}\x{0B57}\x{0B62}-\x{0B63}\x{0B82}\x{0BBE}-\x{0BBF}\x{0BC0}\x{0BC1}-\x{0BC2}\x{0BC6}-\x{0BC8}\x{0BCA}-\x{0BCC}\x{0BCD}\x{0BD7}\x{0C00}\x{0C01}-\x{0C03}\x{0C04}\x{0C3E}-\x{0C40}\x{0C41}-\x{0C44}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0C82}-\x{0C83}\x{0CBC}\x{0CBE}\x{0CBF}\x{0CC0}-\x{0CC4}\x{0CC6}\x{0CC7}-\x{0CC8}\x{0CCA}-\x{0CCB}\x{0CCC}-\x{0CCD}\x{0CD5}-\x{0CD6}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D02}-\x{0D03}\x{0D3B}-\x{0D3C}\x{0D3E}-\x{0D40}\x{0D41}-\x{0D44}\x{0D46}-\x{0D48}\x{0D4A}-\x{0D4C}\x{0D4D}\x{0D57}\x{0D62}-\x{0D63}\x{0D81}\x{0D82}-\x{0D83}\x{0DCA}\x{0DCF}-\x{0DD1}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0DD8}-\x{0DDF}\x{0DF2}-\x{0DF3}\x{0E31}\x{0E34}-\x{0E3A}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F3E}-\x{0F3F}\x{0F71}-\x{0F7E}\x{0F7F}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102B}-\x{102C}\x{102D}-\x{1030}\x{1031}\x{1032}-\x{1037}\x{1038}\x{1039}-\x{103A}\x{103B}-\x{103C}\x{103D}-\x{103E}\x{1056}-\x{1057}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1062}-\x{1064}\x{1067}-\x{106D}\x{1071}-\x{1074}\x{1082}\x{1083}-\x{1084}\x{1085}-\x{1086}\x{1087}-\x{108C}\x{108D}\x{108F}\x{109A}-\x{109C}\x{109D}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B6}\x{17B7}-\x{17BD}\x{17BE}-\x{17C5}\x{17C6}\x{17C7}-\x{17C8}\x{17C9}-\x{17D3}\x{17DD}\x{180B}-\x{180D}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1923}-\x{1926}\x{1927}-\x{1928}\x{1929}-\x{192B}\x{1930}-\x{1931}\x{1932}\x{1933}-\x{1938}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A19}-\x{1A1A}\x{1A1B}\x{1A55}\x{1A56}\x{1A57}\x{1A58}-\x{1A5E}\x{1A60}\x{1A61}\x{1A62}\x{1A63}-\x{1A64}\x{1A65}-\x{1A6C}\x{1A6D}-\x{1A72}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B04}\x{1B34}\x{1B35}\x{1B36}-\x{1B3A}\x{1B3B}\x{1B3C}\x{1B3D}-\x{1B41}\x{1B42}\x{1B43}-\x{1B44}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1B82}\x{1BA1}\x{1BA2}-\x{1BA5}\x{1BA6}-\x{1BA7}\x{1BA8}-\x{1BA9}\x{1BAA}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE7}\x{1BE8}-\x{1BE9}\x{1BEA}-\x{1BEC}\x{1BED}\x{1BEE}\x{1BEF}-\x{1BF1}\x{1BF2}-\x{1BF3}\x{1C24}-\x{1C2B}\x{1C2C}-\x{1C33}\x{1C34}-\x{1C35}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE1}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF7}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2CEF}-\x{2CF1}\x{2D7F}\x{2DE0}-\x{2DFF}\x{302A}-\x{302D}\x{302E}-\x{302F}\x{3099}-\x{309A}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A802}\x{A806}\x{A80B}\x{A823}-\x{A824}\x{A825}-\x{A826}\x{A827}\x{A82C}\x{A880}-\x{A881}\x{A8B4}-\x{A8C3}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A952}-\x{A953}\x{A980}-\x{A982}\x{A983}\x{A9B3}\x{A9B4}-\x{A9B5}\x{A9B6}-\x{A9B9}\x{A9BA}-\x{A9BB}\x{A9BC}-\x{A9BD}\x{A9BE}-\x{A9C0}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA2F}-\x{AA30}\x{AA31}-\x{AA32}\x{AA33}-\x{AA34}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA4D}\x{AA7B}\x{AA7C}\x{AA7D}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEB}\x{AAEC}-\x{AAED}\x{AAEE}-\x{AAEF}\x{AAF5}\x{AAF6}\x{ABE3}-\x{ABE4}\x{ABE5}\x{ABE6}-\x{ABE7}\x{ABE8}\x{ABE9}-\x{ABEA}\x{ABEC}\x{ABED}\x{FB1E}\x{FE00}-\x{FE0F}\x{FE20}-\x{FE2F}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10EAB}-\x{10EAC}\x{10F46}-\x{10F50}\x{11000}\x{11001}\x{11002}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{11082}\x{110B0}-\x{110B2}\x{110B3}-\x{110B6}\x{110B7}-\x{110B8}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112C}\x{1112D}-\x{11134}\x{11145}-\x{11146}\x{11173}\x{11180}-\x{11181}\x{11182}\x{111B3}-\x{111B5}\x{111B6}-\x{111BE}\x{111BF}-\x{111C0}\x{111C9}-\x{111CC}\x{111CE}\x{111CF}\x{1122C}-\x{1122E}\x{1122F}-\x{11231}\x{11232}-\x{11233}\x{11234}\x{11235}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E0}-\x{112E2}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{11302}-\x{11303}\x{1133B}-\x{1133C}\x{1133E}-\x{1133F}\x{11340}\x{11341}-\x{11344}\x{11347}-\x{11348}\x{1134B}-\x{1134D}\x{11357}\x{11362}-\x{11363}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11435}-\x{11437}\x{11438}-\x{1143F}\x{11440}-\x{11441}\x{11442}-\x{11444}\x{11445}\x{11446}\x{1145E}\x{114B0}-\x{114B2}\x{114B3}-\x{114B8}\x{114B9}\x{114BA}\x{114BB}-\x{114BE}\x{114BF}-\x{114C0}\x{114C1}\x{114C2}-\x{114C3}\x{115AF}-\x{115B1}\x{115B2}-\x{115B5}\x{115B8}-\x{115BB}\x{115BC}-\x{115BD}\x{115BE}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11630}-\x{11632}\x{11633}-\x{1163A}\x{1163B}-\x{1163C}\x{1163D}\x{1163E}\x{1163F}-\x{11640}\x{116AB}\x{116AC}\x{116AD}\x{116AE}-\x{116AF}\x{116B0}-\x{116B5}\x{116B6}\x{116B7}\x{1171D}-\x{1171F}\x{11720}-\x{11721}\x{11722}-\x{11725}\x{11726}\x{11727}-\x{1172B}\x{1182C}-\x{1182E}\x{1182F}-\x{11837}\x{11838}\x{11839}-\x{1183A}\x{11930}-\x{11935}\x{11937}-\x{11938}\x{1193B}-\x{1193C}\x{1193D}\x{1193E}\x{11940}\x{11942}\x{11943}\x{119D1}-\x{119D3}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119DC}-\x{119DF}\x{119E0}\x{119E4}\x{11A01}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A39}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A57}-\x{11A58}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A97}\x{11A98}-\x{11A99}\x{11C2F}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C3E}\x{11C3F}\x{11C92}-\x{11CA7}\x{11CA9}\x{11CAA}-\x{11CB0}\x{11CB1}\x{11CB2}-\x{11CB3}\x{11CB4}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D8A}-\x{11D8E}\x{11D90}-\x{11D91}\x{11D93}-\x{11D94}\x{11D95}\x{11D96}\x{11D97}\x{11EF3}-\x{11EF4}\x{11EF5}-\x{11EF6}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F51}-\x{16F87}\x{16F8F}-\x{16F92}\x{16FE4}\x{16FF0}-\x{16FF1}\x{1BC9D}-\x{1BC9E}\x{1D165}-\x{1D166}\x{1D167}-\x{1D169}\x{1D16D}-\x{1D172}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{E0100}-\x{E01EF}]/u'; + + const RTL_LABEL = '/[\x{0590}\x{05BE}\x{05C0}\x{05C3}\x{05C6}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0600}-\x{0605}\x{0608}\x{060B}\x{060D}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{0660}-\x{0669}\x{066B}-\x{066C}\x{066D}\x{066E}-\x{066F}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06DD}\x{06E5}-\x{06E6}\x{06EE}-\x{06EF}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0712}-\x{072F}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07F4}-\x{07F5}\x{07FA}\x{07FB}-\x{07FC}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{081A}\x{0824}\x{0828}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{08E2}\x{200F}\x{FB1D}\x{FB1F}-\x{FB28}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFE}-\x{FDFF}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A04}\x{10A07}-\x{10A0B}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A3B}-\x{10A3E}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D28}-\x{10D2F}\x{10D30}-\x{10D39}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E60}-\x{10E7E}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}]/u'; + + const BIDI_STEP_1_LTR = '/^[^\x{0000}-\x{0008}\x{0009}\x{000A}\x{000B}\x{000C}\x{000D}\x{000E}-\x{001B}\x{001C}-\x{001E}\x{001F}\x{0020}\x{0021}-\x{0022}\x{0023}\x{0024}\x{0025}\x{0026}-\x{0027}\x{0028}\x{0029}\x{002A}\x{002B}\x{002C}\x{002D}\x{002E}-\x{002F}\x{0030}-\x{0039}\x{003A}\x{003B}\x{003C}-\x{003E}\x{003F}-\x{0040}\x{005B}\x{005C}\x{005D}\x{005E}\x{005F}\x{0060}\x{007B}\x{007C}\x{007D}\x{007E}\x{007F}-\x{0084}\x{0085}\x{0086}-\x{009F}\x{00A0}\x{00A1}\x{00A2}-\x{00A5}\x{00A6}\x{00A7}\x{00A8}\x{00A9}\x{00AB}\x{00AC}\x{00AD}\x{00AE}\x{00AF}\x{00B0}\x{00B1}\x{00B2}-\x{00B3}\x{00B4}\x{00B6}-\x{00B7}\x{00B8}\x{00B9}\x{00BB}\x{00BC}-\x{00BE}\x{00BF}\x{00D7}\x{00F7}\x{02B9}-\x{02BA}\x{02C2}-\x{02C5}\x{02C6}-\x{02CF}\x{02D2}-\x{02DF}\x{02E5}-\x{02EB}\x{02EC}\x{02ED}\x{02EF}-\x{02FF}\x{0300}-\x{036F}\x{0374}\x{0375}\x{037E}\x{0384}-\x{0385}\x{0387}\x{03F6}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{058A}\x{058D}-\x{058E}\x{058F}\x{0590}\x{0591}-\x{05BD}\x{05BE}\x{05BF}\x{05C0}\x{05C1}-\x{05C2}\x{05C3}\x{05C4}-\x{05C5}\x{05C6}\x{05C7}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0600}-\x{0605}\x{0606}-\x{0607}\x{0608}\x{0609}-\x{060A}\x{060B}\x{060C}\x{060D}\x{060E}-\x{060F}\x{0610}-\x{061A}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{064B}-\x{065F}\x{0660}-\x{0669}\x{066A}\x{066B}-\x{066C}\x{066D}\x{066E}-\x{066F}\x{0670}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06D6}-\x{06DC}\x{06DD}\x{06DE}\x{06DF}-\x{06E4}\x{06E5}-\x{06E6}\x{06E7}-\x{06E8}\x{06E9}\x{06EA}-\x{06ED}\x{06EE}-\x{06EF}\x{06F0}-\x{06F9}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0711}\x{0712}-\x{072F}\x{0730}-\x{074A}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07A6}-\x{07B0}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07EB}-\x{07F3}\x{07F4}-\x{07F5}\x{07F6}\x{07F7}-\x{07F9}\x{07FA}\x{07FB}-\x{07FC}\x{07FD}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{0816}-\x{0819}\x{081A}\x{081B}-\x{0823}\x{0824}\x{0825}-\x{0827}\x{0828}\x{0829}-\x{082D}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{0859}-\x{085B}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{08D3}-\x{08E1}\x{08E2}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09F2}-\x{09F3}\x{09FB}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AF1}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0BF3}-\x{0BF8}\x{0BF9}\x{0BFA}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C78}-\x{0C7E}\x{0C81}\x{0CBC}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E3F}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F3A}\x{0F3B}\x{0F3C}\x{0F3D}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1390}-\x{1399}\x{1400}\x{1680}\x{169B}\x{169C}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DB}\x{17DD}\x{17F0}-\x{17F9}\x{1800}-\x{1805}\x{1806}\x{1807}-\x{180A}\x{180B}-\x{180D}\x{180E}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1940}\x{1944}-\x{1945}\x{19DE}-\x{19FF}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{1FBD}\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}\x{1FFD}-\x{1FFE}\x{2000}-\x{200A}\x{200B}-\x{200D}\x{200F}\x{2010}-\x{2015}\x{2016}-\x{2017}\x{2018}\x{2019}\x{201A}\x{201B}-\x{201C}\x{201D}\x{201E}\x{201F}\x{2020}-\x{2027}\x{2028}\x{2029}\x{202A}\x{202B}\x{202C}\x{202D}\x{202E}\x{202F}\x{2030}-\x{2034}\x{2035}-\x{2038}\x{2039}\x{203A}\x{203B}-\x{203E}\x{203F}-\x{2040}\x{2041}-\x{2043}\x{2044}\x{2045}\x{2046}\x{2047}-\x{2051}\x{2052}\x{2053}\x{2054}\x{2055}-\x{205E}\x{205F}\x{2060}-\x{2064}\x{2065}\x{2066}\x{2067}\x{2068}\x{2069}\x{206A}-\x{206F}\x{2070}\x{2074}-\x{2079}\x{207A}-\x{207B}\x{207C}\x{207D}\x{207E}\x{2080}-\x{2089}\x{208A}-\x{208B}\x{208C}\x{208D}\x{208E}\x{20A0}-\x{20BF}\x{20C0}-\x{20CF}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2100}-\x{2101}\x{2103}-\x{2106}\x{2108}-\x{2109}\x{2114}\x{2116}-\x{2117}\x{2118}\x{211E}-\x{2123}\x{2125}\x{2127}\x{2129}\x{212E}\x{213A}-\x{213B}\x{2140}-\x{2144}\x{214A}\x{214B}\x{214C}-\x{214D}\x{2150}-\x{215F}\x{2189}\x{218A}-\x{218B}\x{2190}-\x{2194}\x{2195}-\x{2199}\x{219A}-\x{219B}\x{219C}-\x{219F}\x{21A0}\x{21A1}-\x{21A2}\x{21A3}\x{21A4}-\x{21A5}\x{21A6}\x{21A7}-\x{21AD}\x{21AE}\x{21AF}-\x{21CD}\x{21CE}-\x{21CF}\x{21D0}-\x{21D1}\x{21D2}\x{21D3}\x{21D4}\x{21D5}-\x{21F3}\x{21F4}-\x{2211}\x{2212}\x{2213}\x{2214}-\x{22FF}\x{2300}-\x{2307}\x{2308}\x{2309}\x{230A}\x{230B}\x{230C}-\x{231F}\x{2320}-\x{2321}\x{2322}-\x{2328}\x{2329}\x{232A}\x{232B}-\x{2335}\x{237B}\x{237C}\x{237D}-\x{2394}\x{2396}-\x{239A}\x{239B}-\x{23B3}\x{23B4}-\x{23DB}\x{23DC}-\x{23E1}\x{23E2}-\x{2426}\x{2440}-\x{244A}\x{2460}-\x{2487}\x{2488}-\x{249B}\x{24EA}-\x{24FF}\x{2500}-\x{25B6}\x{25B7}\x{25B8}-\x{25C0}\x{25C1}\x{25C2}-\x{25F7}\x{25F8}-\x{25FF}\x{2600}-\x{266E}\x{266F}\x{2670}-\x{26AB}\x{26AD}-\x{2767}\x{2768}\x{2769}\x{276A}\x{276B}\x{276C}\x{276D}\x{276E}\x{276F}\x{2770}\x{2771}\x{2772}\x{2773}\x{2774}\x{2775}\x{2776}-\x{2793}\x{2794}-\x{27BF}\x{27C0}-\x{27C4}\x{27C5}\x{27C6}\x{27C7}-\x{27E5}\x{27E6}\x{27E7}\x{27E8}\x{27E9}\x{27EA}\x{27EB}\x{27EC}\x{27ED}\x{27EE}\x{27EF}\x{27F0}-\x{27FF}\x{2900}-\x{2982}\x{2983}\x{2984}\x{2985}\x{2986}\x{2987}\x{2988}\x{2989}\x{298A}\x{298B}\x{298C}\x{298D}\x{298E}\x{298F}\x{2990}\x{2991}\x{2992}\x{2993}\x{2994}\x{2995}\x{2996}\x{2997}\x{2998}\x{2999}-\x{29D7}\x{29D8}\x{29D9}\x{29DA}\x{29DB}\x{29DC}-\x{29FB}\x{29FC}\x{29FD}\x{29FE}-\x{2AFF}\x{2B00}-\x{2B2F}\x{2B30}-\x{2B44}\x{2B45}-\x{2B46}\x{2B47}-\x{2B4C}\x{2B4D}-\x{2B73}\x{2B76}-\x{2B95}\x{2B97}-\x{2BFF}\x{2CE5}-\x{2CEA}\x{2CEF}-\x{2CF1}\x{2CF9}-\x{2CFC}\x{2CFD}\x{2CFE}-\x{2CFF}\x{2D7F}\x{2DE0}-\x{2DFF}\x{2E00}-\x{2E01}\x{2E02}\x{2E03}\x{2E04}\x{2E05}\x{2E06}-\x{2E08}\x{2E09}\x{2E0A}\x{2E0B}\x{2E0C}\x{2E0D}\x{2E0E}-\x{2E16}\x{2E17}\x{2E18}-\x{2E19}\x{2E1A}\x{2E1B}\x{2E1C}\x{2E1D}\x{2E1E}-\x{2E1F}\x{2E20}\x{2E21}\x{2E22}\x{2E23}\x{2E24}\x{2E25}\x{2E26}\x{2E27}\x{2E28}\x{2E29}\x{2E2A}-\x{2E2E}\x{2E2F}\x{2E30}-\x{2E39}\x{2E3A}-\x{2E3B}\x{2E3C}-\x{2E3F}\x{2E40}\x{2E41}\x{2E42}\x{2E43}-\x{2E4F}\x{2E50}-\x{2E51}\x{2E52}\x{2E80}-\x{2E99}\x{2E9B}-\x{2EF3}\x{2F00}-\x{2FD5}\x{2FF0}-\x{2FFB}\x{3000}\x{3001}-\x{3003}\x{3004}\x{3008}\x{3009}\x{300A}\x{300B}\x{300C}\x{300D}\x{300E}\x{300F}\x{3010}\x{3011}\x{3012}-\x{3013}\x{3014}\x{3015}\x{3016}\x{3017}\x{3018}\x{3019}\x{301A}\x{301B}\x{301C}\x{301D}\x{301E}-\x{301F}\x{3020}\x{302A}-\x{302D}\x{3030}\x{3036}-\x{3037}\x{303D}\x{303E}-\x{303F}\x{3099}-\x{309A}\x{309B}-\x{309C}\x{30A0}\x{30FB}\x{31C0}-\x{31E3}\x{321D}-\x{321E}\x{3250}\x{3251}-\x{325F}\x{327C}-\x{327E}\x{32B1}-\x{32BF}\x{32CC}-\x{32CF}\x{3377}-\x{337A}\x{33DE}-\x{33DF}\x{33FF}\x{4DC0}-\x{4DFF}\x{A490}-\x{A4C6}\x{A60D}-\x{A60F}\x{A66F}\x{A670}-\x{A672}\x{A673}\x{A674}-\x{A67D}\x{A67E}\x{A67F}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A700}-\x{A716}\x{A717}-\x{A71F}\x{A720}-\x{A721}\x{A788}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A828}-\x{A82B}\x{A82C}\x{A838}\x{A839}\x{A874}-\x{A877}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{AB6A}-\x{AB6B}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1D}\x{FB1E}\x{FB1F}-\x{FB28}\x{FB29}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD3E}\x{FD3F}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDD0}-\x{FDEF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFD}\x{FDFE}-\x{FDFF}\x{FE00}-\x{FE0F}\x{FE10}-\x{FE16}\x{FE17}\x{FE18}\x{FE19}\x{FE20}-\x{FE2F}\x{FE30}\x{FE31}-\x{FE32}\x{FE33}-\x{FE34}\x{FE35}\x{FE36}\x{FE37}\x{FE38}\x{FE39}\x{FE3A}\x{FE3B}\x{FE3C}\x{FE3D}\x{FE3E}\x{FE3F}\x{FE40}\x{FE41}\x{FE42}\x{FE43}\x{FE44}\x{FE45}-\x{FE46}\x{FE47}\x{FE48}\x{FE49}-\x{FE4C}\x{FE4D}-\x{FE4F}\x{FE50}\x{FE51}\x{FE52}\x{FE54}\x{FE55}\x{FE56}-\x{FE57}\x{FE58}\x{FE59}\x{FE5A}\x{FE5B}\x{FE5C}\x{FE5D}\x{FE5E}\x{FE5F}\x{FE60}-\x{FE61}\x{FE62}\x{FE63}\x{FE64}-\x{FE66}\x{FE68}\x{FE69}\x{FE6A}\x{FE6B}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{FEFF}\x{FF01}-\x{FF02}\x{FF03}\x{FF04}\x{FF05}\x{FF06}-\x{FF07}\x{FF08}\x{FF09}\x{FF0A}\x{FF0B}\x{FF0C}\x{FF0D}\x{FF0E}-\x{FF0F}\x{FF10}-\x{FF19}\x{FF1A}\x{FF1B}\x{FF1C}-\x{FF1E}\x{FF1F}-\x{FF20}\x{FF3B}\x{FF3C}\x{FF3D}\x{FF3E}\x{FF3F}\x{FF40}\x{FF5B}\x{FF5C}\x{FF5D}\x{FF5E}\x{FF5F}\x{FF60}\x{FF61}\x{FF62}\x{FF63}\x{FF64}-\x{FF65}\x{FFE0}-\x{FFE1}\x{FFE2}\x{FFE3}\x{FFE4}\x{FFE5}-\x{FFE6}\x{FFE8}\x{FFE9}-\x{FFEC}\x{FFED}-\x{FFEE}\x{FFF0}-\x{FFF8}\x{FFF9}-\x{FFFB}\x{FFFC}-\x{FFFD}\x{FFFE}-\x{FFFF}\x{10101}\x{10140}-\x{10174}\x{10175}-\x{10178}\x{10179}-\x{10189}\x{1018A}-\x{1018B}\x{1018C}\x{10190}-\x{1019C}\x{101A0}\x{101FD}\x{102E0}\x{102E1}-\x{102FB}\x{10376}-\x{1037A}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{1091F}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A01}-\x{10A03}\x{10A04}\x{10A05}-\x{10A06}\x{10A07}-\x{10A0B}\x{10A0C}-\x{10A0F}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A38}-\x{10A3A}\x{10A3B}-\x{10A3E}\x{10A3F}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE5}-\x{10AE6}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B39}-\x{10B3F}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D24}-\x{10D27}\x{10D28}-\x{10D2F}\x{10D30}-\x{10D39}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E60}-\x{10E7E}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAB}-\x{10EAC}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F46}-\x{10F50}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{11001}\x{11038}-\x{11046}\x{11052}-\x{11065}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{11660}-\x{1166C}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A06}\x{11A09}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{11FD5}-\x{11FDC}\x{11FDD}-\x{11FE0}\x{11FE1}-\x{11FF1}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE2}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D200}-\x{1D241}\x{1D242}-\x{1D244}\x{1D245}\x{1D300}-\x{1D356}\x{1D6DB}\x{1D715}\x{1D74F}\x{1D789}\x{1D7C3}\x{1D7CE}-\x{1D7FF}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E2FF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D0}-\x{1E8D6}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E944}-\x{1E94A}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF0}-\x{1EEF1}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}\x{1F000}-\x{1F02B}\x{1F030}-\x{1F093}\x{1F0A0}-\x{1F0AE}\x{1F0B1}-\x{1F0BF}\x{1F0C1}-\x{1F0CF}\x{1F0D1}-\x{1F0F5}\x{1F100}-\x{1F10A}\x{1F10B}-\x{1F10C}\x{1F10D}-\x{1F10F}\x{1F12F}\x{1F16A}-\x{1F16F}\x{1F1AD}\x{1F260}-\x{1F265}\x{1F300}-\x{1F3FA}\x{1F3FB}-\x{1F3FF}\x{1F400}-\x{1F6D7}\x{1F6E0}-\x{1F6EC}\x{1F6F0}-\x{1F6FC}\x{1F700}-\x{1F773}\x{1F780}-\x{1F7D8}\x{1F7E0}-\x{1F7EB}\x{1F800}-\x{1F80B}\x{1F810}-\x{1F847}\x{1F850}-\x{1F859}\x{1F860}-\x{1F887}\x{1F890}-\x{1F8AD}\x{1F8B0}-\x{1F8B1}\x{1F900}-\x{1F978}\x{1F97A}-\x{1F9CB}\x{1F9CD}-\x{1FA53}\x{1FA60}-\x{1FA6D}\x{1FA70}-\x{1FA74}\x{1FA78}-\x{1FA7A}\x{1FA80}-\x{1FA86}\x{1FA90}-\x{1FAA8}\x{1FAB0}-\x{1FAB6}\x{1FAC0}-\x{1FAC2}\x{1FAD0}-\x{1FAD6}\x{1FB00}-\x{1FB92}\x{1FB94}-\x{1FBCA}\x{1FBF0}-\x{1FBF9}\x{1FFFE}-\x{1FFFF}\x{2FFFE}-\x{2FFFF}\x{3FFFE}-\x{3FFFF}\x{4FFFE}-\x{4FFFF}\x{5FFFE}-\x{5FFFF}\x{6FFFE}-\x{6FFFF}\x{7FFFE}-\x{7FFFF}\x{8FFFE}-\x{8FFFF}\x{9FFFE}-\x{9FFFF}\x{AFFFE}-\x{AFFFF}\x{BFFFE}-\x{BFFFF}\x{CFFFE}-\x{CFFFF}\x{DFFFE}-\x{E0000}\x{E0001}\x{E0002}-\x{E001F}\x{E0020}-\x{E007F}\x{E0080}-\x{E00FF}\x{E0100}-\x{E01EF}\x{E01F0}-\x{E0FFF}\x{EFFFE}-\x{EFFFF}\x{FFFFE}-\x{FFFFF}\x{10FFFE}-\x{10FFFF}]/u'; + const BIDI_STEP_1_RTL = '/^[\x{0590}\x{05BE}\x{05C0}\x{05C3}\x{05C6}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0608}\x{060B}\x{060D}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{066D}\x{066E}-\x{066F}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06E5}-\x{06E6}\x{06EE}-\x{06EF}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0712}-\x{072F}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07F4}-\x{07F5}\x{07FA}\x{07FB}-\x{07FC}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{081A}\x{0824}\x{0828}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{200F}\x{FB1D}\x{FB1F}-\x{FB28}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFE}-\x{FDFF}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A04}\x{10A07}-\x{10A0B}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A3B}-\x{10A3E}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D28}-\x{10D2F}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}]/u'; + const BIDI_STEP_2 = '/[^\x{0000}-\x{0008}\x{000E}-\x{001B}\x{0021}-\x{0022}\x{0023}\x{0024}\x{0025}\x{0026}-\x{0027}\x{0028}\x{0029}\x{002A}\x{002B}\x{002C}\x{002D}\x{002E}-\x{002F}\x{0030}-\x{0039}\x{003A}\x{003B}\x{003C}-\x{003E}\x{003F}-\x{0040}\x{005B}\x{005C}\x{005D}\x{005E}\x{005F}\x{0060}\x{007B}\x{007C}\x{007D}\x{007E}\x{007F}-\x{0084}\x{0086}-\x{009F}\x{00A0}\x{00A1}\x{00A2}-\x{00A5}\x{00A6}\x{00A7}\x{00A8}\x{00A9}\x{00AB}\x{00AC}\x{00AD}\x{00AE}\x{00AF}\x{00B0}\x{00B1}\x{00B2}-\x{00B3}\x{00B4}\x{00B6}-\x{00B7}\x{00B8}\x{00B9}\x{00BB}\x{00BC}-\x{00BE}\x{00BF}\x{00D7}\x{00F7}\x{02B9}-\x{02BA}\x{02C2}-\x{02C5}\x{02C6}-\x{02CF}\x{02D2}-\x{02DF}\x{02E5}-\x{02EB}\x{02EC}\x{02ED}\x{02EF}-\x{02FF}\x{0300}-\x{036F}\x{0374}\x{0375}\x{037E}\x{0384}-\x{0385}\x{0387}\x{03F6}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{058A}\x{058D}-\x{058E}\x{058F}\x{0590}\x{0591}-\x{05BD}\x{05BE}\x{05BF}\x{05C0}\x{05C1}-\x{05C2}\x{05C3}\x{05C4}-\x{05C5}\x{05C6}\x{05C7}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0600}-\x{0605}\x{0606}-\x{0607}\x{0608}\x{0609}-\x{060A}\x{060B}\x{060C}\x{060D}\x{060E}-\x{060F}\x{0610}-\x{061A}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{064B}-\x{065F}\x{0660}-\x{0669}\x{066A}\x{066B}-\x{066C}\x{066D}\x{066E}-\x{066F}\x{0670}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06D6}-\x{06DC}\x{06DD}\x{06DE}\x{06DF}-\x{06E4}\x{06E5}-\x{06E6}\x{06E7}-\x{06E8}\x{06E9}\x{06EA}-\x{06ED}\x{06EE}-\x{06EF}\x{06F0}-\x{06F9}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0711}\x{0712}-\x{072F}\x{0730}-\x{074A}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07A6}-\x{07B0}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07EB}-\x{07F3}\x{07F4}-\x{07F5}\x{07F6}\x{07F7}-\x{07F9}\x{07FA}\x{07FB}-\x{07FC}\x{07FD}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{0816}-\x{0819}\x{081A}\x{081B}-\x{0823}\x{0824}\x{0825}-\x{0827}\x{0828}\x{0829}-\x{082D}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{0859}-\x{085B}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{08D3}-\x{08E1}\x{08E2}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09F2}-\x{09F3}\x{09FB}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AF1}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0BF3}-\x{0BF8}\x{0BF9}\x{0BFA}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C78}-\x{0C7E}\x{0C81}\x{0CBC}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E3F}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F3A}\x{0F3B}\x{0F3C}\x{0F3D}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1390}-\x{1399}\x{1400}\x{169B}\x{169C}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DB}\x{17DD}\x{17F0}-\x{17F9}\x{1800}-\x{1805}\x{1806}\x{1807}-\x{180A}\x{180B}-\x{180D}\x{180E}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1940}\x{1944}-\x{1945}\x{19DE}-\x{19FF}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{1FBD}\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}\x{1FFD}-\x{1FFE}\x{200B}-\x{200D}\x{200F}\x{2010}-\x{2015}\x{2016}-\x{2017}\x{2018}\x{2019}\x{201A}\x{201B}-\x{201C}\x{201D}\x{201E}\x{201F}\x{2020}-\x{2027}\x{202F}\x{2030}-\x{2034}\x{2035}-\x{2038}\x{2039}\x{203A}\x{203B}-\x{203E}\x{203F}-\x{2040}\x{2041}-\x{2043}\x{2044}\x{2045}\x{2046}\x{2047}-\x{2051}\x{2052}\x{2053}\x{2054}\x{2055}-\x{205E}\x{2060}-\x{2064}\x{2065}\x{206A}-\x{206F}\x{2070}\x{2074}-\x{2079}\x{207A}-\x{207B}\x{207C}\x{207D}\x{207E}\x{2080}-\x{2089}\x{208A}-\x{208B}\x{208C}\x{208D}\x{208E}\x{20A0}-\x{20BF}\x{20C0}-\x{20CF}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2100}-\x{2101}\x{2103}-\x{2106}\x{2108}-\x{2109}\x{2114}\x{2116}-\x{2117}\x{2118}\x{211E}-\x{2123}\x{2125}\x{2127}\x{2129}\x{212E}\x{213A}-\x{213B}\x{2140}-\x{2144}\x{214A}\x{214B}\x{214C}-\x{214D}\x{2150}-\x{215F}\x{2189}\x{218A}-\x{218B}\x{2190}-\x{2194}\x{2195}-\x{2199}\x{219A}-\x{219B}\x{219C}-\x{219F}\x{21A0}\x{21A1}-\x{21A2}\x{21A3}\x{21A4}-\x{21A5}\x{21A6}\x{21A7}-\x{21AD}\x{21AE}\x{21AF}-\x{21CD}\x{21CE}-\x{21CF}\x{21D0}-\x{21D1}\x{21D2}\x{21D3}\x{21D4}\x{21D5}-\x{21F3}\x{21F4}-\x{2211}\x{2212}\x{2213}\x{2214}-\x{22FF}\x{2300}-\x{2307}\x{2308}\x{2309}\x{230A}\x{230B}\x{230C}-\x{231F}\x{2320}-\x{2321}\x{2322}-\x{2328}\x{2329}\x{232A}\x{232B}-\x{2335}\x{237B}\x{237C}\x{237D}-\x{2394}\x{2396}-\x{239A}\x{239B}-\x{23B3}\x{23B4}-\x{23DB}\x{23DC}-\x{23E1}\x{23E2}-\x{2426}\x{2440}-\x{244A}\x{2460}-\x{2487}\x{2488}-\x{249B}\x{24EA}-\x{24FF}\x{2500}-\x{25B6}\x{25B7}\x{25B8}-\x{25C0}\x{25C1}\x{25C2}-\x{25F7}\x{25F8}-\x{25FF}\x{2600}-\x{266E}\x{266F}\x{2670}-\x{26AB}\x{26AD}-\x{2767}\x{2768}\x{2769}\x{276A}\x{276B}\x{276C}\x{276D}\x{276E}\x{276F}\x{2770}\x{2771}\x{2772}\x{2773}\x{2774}\x{2775}\x{2776}-\x{2793}\x{2794}-\x{27BF}\x{27C0}-\x{27C4}\x{27C5}\x{27C6}\x{27C7}-\x{27E5}\x{27E6}\x{27E7}\x{27E8}\x{27E9}\x{27EA}\x{27EB}\x{27EC}\x{27ED}\x{27EE}\x{27EF}\x{27F0}-\x{27FF}\x{2900}-\x{2982}\x{2983}\x{2984}\x{2985}\x{2986}\x{2987}\x{2988}\x{2989}\x{298A}\x{298B}\x{298C}\x{298D}\x{298E}\x{298F}\x{2990}\x{2991}\x{2992}\x{2993}\x{2994}\x{2995}\x{2996}\x{2997}\x{2998}\x{2999}-\x{29D7}\x{29D8}\x{29D9}\x{29DA}\x{29DB}\x{29DC}-\x{29FB}\x{29FC}\x{29FD}\x{29FE}-\x{2AFF}\x{2B00}-\x{2B2F}\x{2B30}-\x{2B44}\x{2B45}-\x{2B46}\x{2B47}-\x{2B4C}\x{2B4D}-\x{2B73}\x{2B76}-\x{2B95}\x{2B97}-\x{2BFF}\x{2CE5}-\x{2CEA}\x{2CEF}-\x{2CF1}\x{2CF9}-\x{2CFC}\x{2CFD}\x{2CFE}-\x{2CFF}\x{2D7F}\x{2DE0}-\x{2DFF}\x{2E00}-\x{2E01}\x{2E02}\x{2E03}\x{2E04}\x{2E05}\x{2E06}-\x{2E08}\x{2E09}\x{2E0A}\x{2E0B}\x{2E0C}\x{2E0D}\x{2E0E}-\x{2E16}\x{2E17}\x{2E18}-\x{2E19}\x{2E1A}\x{2E1B}\x{2E1C}\x{2E1D}\x{2E1E}-\x{2E1F}\x{2E20}\x{2E21}\x{2E22}\x{2E23}\x{2E24}\x{2E25}\x{2E26}\x{2E27}\x{2E28}\x{2E29}\x{2E2A}-\x{2E2E}\x{2E2F}\x{2E30}-\x{2E39}\x{2E3A}-\x{2E3B}\x{2E3C}-\x{2E3F}\x{2E40}\x{2E41}\x{2E42}\x{2E43}-\x{2E4F}\x{2E50}-\x{2E51}\x{2E52}\x{2E80}-\x{2E99}\x{2E9B}-\x{2EF3}\x{2F00}-\x{2FD5}\x{2FF0}-\x{2FFB}\x{3001}-\x{3003}\x{3004}\x{3008}\x{3009}\x{300A}\x{300B}\x{300C}\x{300D}\x{300E}\x{300F}\x{3010}\x{3011}\x{3012}-\x{3013}\x{3014}\x{3015}\x{3016}\x{3017}\x{3018}\x{3019}\x{301A}\x{301B}\x{301C}\x{301D}\x{301E}-\x{301F}\x{3020}\x{302A}-\x{302D}\x{3030}\x{3036}-\x{3037}\x{303D}\x{303E}-\x{303F}\x{3099}-\x{309A}\x{309B}-\x{309C}\x{30A0}\x{30FB}\x{31C0}-\x{31E3}\x{321D}-\x{321E}\x{3250}\x{3251}-\x{325F}\x{327C}-\x{327E}\x{32B1}-\x{32BF}\x{32CC}-\x{32CF}\x{3377}-\x{337A}\x{33DE}-\x{33DF}\x{33FF}\x{4DC0}-\x{4DFF}\x{A490}-\x{A4C6}\x{A60D}-\x{A60F}\x{A66F}\x{A670}-\x{A672}\x{A673}\x{A674}-\x{A67D}\x{A67E}\x{A67F}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A700}-\x{A716}\x{A717}-\x{A71F}\x{A720}-\x{A721}\x{A788}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A828}-\x{A82B}\x{A82C}\x{A838}\x{A839}\x{A874}-\x{A877}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{AB6A}-\x{AB6B}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1D}\x{FB1E}\x{FB1F}-\x{FB28}\x{FB29}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD3E}\x{FD3F}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDD0}-\x{FDEF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFD}\x{FDFE}-\x{FDFF}\x{FE00}-\x{FE0F}\x{FE10}-\x{FE16}\x{FE17}\x{FE18}\x{FE19}\x{FE20}-\x{FE2F}\x{FE30}\x{FE31}-\x{FE32}\x{FE33}-\x{FE34}\x{FE35}\x{FE36}\x{FE37}\x{FE38}\x{FE39}\x{FE3A}\x{FE3B}\x{FE3C}\x{FE3D}\x{FE3E}\x{FE3F}\x{FE40}\x{FE41}\x{FE42}\x{FE43}\x{FE44}\x{FE45}-\x{FE46}\x{FE47}\x{FE48}\x{FE49}-\x{FE4C}\x{FE4D}-\x{FE4F}\x{FE50}\x{FE51}\x{FE52}\x{FE54}\x{FE55}\x{FE56}-\x{FE57}\x{FE58}\x{FE59}\x{FE5A}\x{FE5B}\x{FE5C}\x{FE5D}\x{FE5E}\x{FE5F}\x{FE60}-\x{FE61}\x{FE62}\x{FE63}\x{FE64}-\x{FE66}\x{FE68}\x{FE69}\x{FE6A}\x{FE6B}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{FEFF}\x{FF01}-\x{FF02}\x{FF03}\x{FF04}\x{FF05}\x{FF06}-\x{FF07}\x{FF08}\x{FF09}\x{FF0A}\x{FF0B}\x{FF0C}\x{FF0D}\x{FF0E}-\x{FF0F}\x{FF10}-\x{FF19}\x{FF1A}\x{FF1B}\x{FF1C}-\x{FF1E}\x{FF1F}-\x{FF20}\x{FF3B}\x{FF3C}\x{FF3D}\x{FF3E}\x{FF3F}\x{FF40}\x{FF5B}\x{FF5C}\x{FF5D}\x{FF5E}\x{FF5F}\x{FF60}\x{FF61}\x{FF62}\x{FF63}\x{FF64}-\x{FF65}\x{FFE0}-\x{FFE1}\x{FFE2}\x{FFE3}\x{FFE4}\x{FFE5}-\x{FFE6}\x{FFE8}\x{FFE9}-\x{FFEC}\x{FFED}-\x{FFEE}\x{FFF0}-\x{FFF8}\x{FFF9}-\x{FFFB}\x{FFFC}-\x{FFFD}\x{FFFE}-\x{FFFF}\x{10101}\x{10140}-\x{10174}\x{10175}-\x{10178}\x{10179}-\x{10189}\x{1018A}-\x{1018B}\x{1018C}\x{10190}-\x{1019C}\x{101A0}\x{101FD}\x{102E0}\x{102E1}-\x{102FB}\x{10376}-\x{1037A}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{1091F}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A01}-\x{10A03}\x{10A04}\x{10A05}-\x{10A06}\x{10A07}-\x{10A0B}\x{10A0C}-\x{10A0F}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A38}-\x{10A3A}\x{10A3B}-\x{10A3E}\x{10A3F}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE5}-\x{10AE6}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B39}-\x{10B3F}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D24}-\x{10D27}\x{10D28}-\x{10D2F}\x{10D30}-\x{10D39}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E60}-\x{10E7E}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAB}-\x{10EAC}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F46}-\x{10F50}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{11001}\x{11038}-\x{11046}\x{11052}-\x{11065}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{11660}-\x{1166C}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A06}\x{11A09}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{11FD5}-\x{11FDC}\x{11FDD}-\x{11FE0}\x{11FE1}-\x{11FF1}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE2}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D200}-\x{1D241}\x{1D242}-\x{1D244}\x{1D245}\x{1D300}-\x{1D356}\x{1D6DB}\x{1D715}\x{1D74F}\x{1D789}\x{1D7C3}\x{1D7CE}-\x{1D7FF}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E2FF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D0}-\x{1E8D6}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E944}-\x{1E94A}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF0}-\x{1EEF1}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}\x{1F000}-\x{1F02B}\x{1F030}-\x{1F093}\x{1F0A0}-\x{1F0AE}\x{1F0B1}-\x{1F0BF}\x{1F0C1}-\x{1F0CF}\x{1F0D1}-\x{1F0F5}\x{1F100}-\x{1F10A}\x{1F10B}-\x{1F10C}\x{1F10D}-\x{1F10F}\x{1F12F}\x{1F16A}-\x{1F16F}\x{1F1AD}\x{1F260}-\x{1F265}\x{1F300}-\x{1F3FA}\x{1F3FB}-\x{1F3FF}\x{1F400}-\x{1F6D7}\x{1F6E0}-\x{1F6EC}\x{1F6F0}-\x{1F6FC}\x{1F700}-\x{1F773}\x{1F780}-\x{1F7D8}\x{1F7E0}-\x{1F7EB}\x{1F800}-\x{1F80B}\x{1F810}-\x{1F847}\x{1F850}-\x{1F859}\x{1F860}-\x{1F887}\x{1F890}-\x{1F8AD}\x{1F8B0}-\x{1F8B1}\x{1F900}-\x{1F978}\x{1F97A}-\x{1F9CB}\x{1F9CD}-\x{1FA53}\x{1FA60}-\x{1FA6D}\x{1FA70}-\x{1FA74}\x{1FA78}-\x{1FA7A}\x{1FA80}-\x{1FA86}\x{1FA90}-\x{1FAA8}\x{1FAB0}-\x{1FAB6}\x{1FAC0}-\x{1FAC2}\x{1FAD0}-\x{1FAD6}\x{1FB00}-\x{1FB92}\x{1FB94}-\x{1FBCA}\x{1FBF0}-\x{1FBF9}\x{1FFFE}-\x{1FFFF}\x{2FFFE}-\x{2FFFF}\x{3FFFE}-\x{3FFFF}\x{4FFFE}-\x{4FFFF}\x{5FFFE}-\x{5FFFF}\x{6FFFE}-\x{6FFFF}\x{7FFFE}-\x{7FFFF}\x{8FFFE}-\x{8FFFF}\x{9FFFE}-\x{9FFFF}\x{AFFFE}-\x{AFFFF}\x{BFFFE}-\x{BFFFF}\x{CFFFE}-\x{CFFFF}\x{DFFFE}-\x{E0000}\x{E0001}\x{E0002}-\x{E001F}\x{E0020}-\x{E007F}\x{E0080}-\x{E00FF}\x{E0100}-\x{E01EF}\x{E01F0}-\x{E0FFF}\x{EFFFE}-\x{EFFFF}\x{FFFFE}-\x{FFFFF}\x{10FFFE}-\x{10FFFF}]/u'; + const BIDI_STEP_3 = '/[\x{0030}-\x{0039}\x{00B2}-\x{00B3}\x{00B9}\x{0590}\x{05BE}\x{05C0}\x{05C3}\x{05C6}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0600}-\x{0605}\x{0608}\x{060B}\x{060D}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{0660}-\x{0669}\x{066B}-\x{066C}\x{066D}\x{066E}-\x{066F}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06DD}\x{06E5}-\x{06E6}\x{06EE}-\x{06EF}\x{06F0}-\x{06F9}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0712}-\x{072F}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07F4}-\x{07F5}\x{07FA}\x{07FB}-\x{07FC}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{081A}\x{0824}\x{0828}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{08E2}\x{200F}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2488}-\x{249B}\x{FB1D}\x{FB1F}-\x{FB28}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFE}-\x{FDFF}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{FF10}-\x{FF19}\x{102E1}-\x{102FB}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A04}\x{10A07}-\x{10A0B}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A3B}-\x{10A3E}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D28}-\x{10D2F}\x{10D30}-\x{10D39}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E60}-\x{10E7E}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{1D7CE}-\x{1D7FF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}\x{1F100}-\x{1F10A}\x{1FBF0}-\x{1FBF9}][\x{0300}-\x{036F}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{0610}-\x{061A}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DF}-\x{06E4}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07FD}\x{0816}-\x{0819}\x{081B}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DD}\x{180B}-\x{180D}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2CEF}-\x{2CF1}\x{2D7F}\x{2DE0}-\x{2DFF}\x{302A}-\x{302D}\x{3099}-\x{309A}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A82C}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FE00}-\x{FE0F}\x{FE20}-\x{FE2F}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10EAB}-\x{10EAC}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A06}\x{11A09}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1D167}-\x{1D169}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{E0100}-\x{E01EF}]*$/u'; + const BIDI_STEP_4_AN = '/[\x{0600}-\x{0605}\x{0660}-\x{0669}\x{066B}-\x{066C}\x{06DD}\x{08E2}\x{10D30}-\x{10D39}\x{10E60}-\x{10E7E}]/u'; + const BIDI_STEP_4_EN = '/[\x{0030}-\x{0039}\x{00B2}-\x{00B3}\x{00B9}\x{06F0}-\x{06F9}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2488}-\x{249B}\x{FF10}-\x{FF19}\x{102E1}-\x{102FB}\x{1D7CE}-\x{1D7FF}\x{1F100}-\x{1F10A}\x{1FBF0}-\x{1FBF9}]/u'; + const BIDI_STEP_5 = '/[\x{0009}\x{000A}\x{000B}\x{000C}\x{000D}\x{001C}-\x{001E}\x{001F}\x{0020}\x{0085}\x{0590}\x{05BE}\x{05C0}\x{05C3}\x{05C6}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0600}-\x{0605}\x{0608}\x{060B}\x{060D}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{0660}-\x{0669}\x{066B}-\x{066C}\x{066D}\x{066E}-\x{066F}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06DD}\x{06E5}-\x{06E6}\x{06EE}-\x{06EF}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0712}-\x{072F}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07F4}-\x{07F5}\x{07FA}\x{07FB}-\x{07FC}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{081A}\x{0824}\x{0828}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{08E2}\x{1680}\x{2000}-\x{200A}\x{200F}\x{2028}\x{2029}\x{202A}\x{202B}\x{202C}\x{202D}\x{202E}\x{205F}\x{2066}\x{2067}\x{2068}\x{2069}\x{3000}\x{FB1D}\x{FB1F}-\x{FB28}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFE}-\x{FDFF}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A04}\x{10A07}-\x{10A0B}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A3B}-\x{10A3E}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D28}-\x{10D2F}\x{10D30}-\x{10D39}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E60}-\x{10E7E}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}]/u'; + const BIDI_STEP_6 = '/[^\x{0000}-\x{0008}\x{0009}\x{000A}\x{000B}\x{000C}\x{000D}\x{000E}-\x{001B}\x{001C}-\x{001E}\x{001F}\x{0020}\x{0021}-\x{0022}\x{0023}\x{0024}\x{0025}\x{0026}-\x{0027}\x{0028}\x{0029}\x{002A}\x{002B}\x{002C}\x{002D}\x{002E}-\x{002F}\x{003A}\x{003B}\x{003C}-\x{003E}\x{003F}-\x{0040}\x{005B}\x{005C}\x{005D}\x{005E}\x{005F}\x{0060}\x{007B}\x{007C}\x{007D}\x{007E}\x{007F}-\x{0084}\x{0085}\x{0086}-\x{009F}\x{00A0}\x{00A1}\x{00A2}-\x{00A5}\x{00A6}\x{00A7}\x{00A8}\x{00A9}\x{00AB}\x{00AC}\x{00AD}\x{00AE}\x{00AF}\x{00B0}\x{00B1}\x{00B4}\x{00B6}-\x{00B7}\x{00B8}\x{00BB}\x{00BC}-\x{00BE}\x{00BF}\x{00D7}\x{00F7}\x{02B9}-\x{02BA}\x{02C2}-\x{02C5}\x{02C6}-\x{02CF}\x{02D2}-\x{02DF}\x{02E5}-\x{02EB}\x{02EC}\x{02ED}\x{02EF}-\x{02FF}\x{0300}-\x{036F}\x{0374}\x{0375}\x{037E}\x{0384}-\x{0385}\x{0387}\x{03F6}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{058A}\x{058D}-\x{058E}\x{058F}\x{0590}\x{0591}-\x{05BD}\x{05BE}\x{05BF}\x{05C0}\x{05C1}-\x{05C2}\x{05C3}\x{05C4}-\x{05C5}\x{05C6}\x{05C7}\x{05C8}-\x{05CF}\x{05D0}-\x{05EA}\x{05EB}-\x{05EE}\x{05EF}-\x{05F2}\x{05F3}-\x{05F4}\x{05F5}-\x{05FF}\x{0600}-\x{0605}\x{0606}-\x{0607}\x{0608}\x{0609}-\x{060A}\x{060B}\x{060C}\x{060D}\x{060E}-\x{060F}\x{0610}-\x{061A}\x{061B}\x{061C}\x{061D}\x{061E}-\x{061F}\x{0620}-\x{063F}\x{0640}\x{0641}-\x{064A}\x{064B}-\x{065F}\x{0660}-\x{0669}\x{066A}\x{066B}-\x{066C}\x{066D}\x{066E}-\x{066F}\x{0670}\x{0671}-\x{06D3}\x{06D4}\x{06D5}\x{06D6}-\x{06DC}\x{06DD}\x{06DE}\x{06DF}-\x{06E4}\x{06E5}-\x{06E6}\x{06E7}-\x{06E8}\x{06E9}\x{06EA}-\x{06ED}\x{06EE}-\x{06EF}\x{06FA}-\x{06FC}\x{06FD}-\x{06FE}\x{06FF}\x{0700}-\x{070D}\x{070E}\x{070F}\x{0710}\x{0711}\x{0712}-\x{072F}\x{0730}-\x{074A}\x{074B}-\x{074C}\x{074D}-\x{07A5}\x{07A6}-\x{07B0}\x{07B1}\x{07B2}-\x{07BF}\x{07C0}-\x{07C9}\x{07CA}-\x{07EA}\x{07EB}-\x{07F3}\x{07F4}-\x{07F5}\x{07F6}\x{07F7}-\x{07F9}\x{07FA}\x{07FB}-\x{07FC}\x{07FD}\x{07FE}-\x{07FF}\x{0800}-\x{0815}\x{0816}-\x{0819}\x{081A}\x{081B}-\x{0823}\x{0824}\x{0825}-\x{0827}\x{0828}\x{0829}-\x{082D}\x{082E}-\x{082F}\x{0830}-\x{083E}\x{083F}\x{0840}-\x{0858}\x{0859}-\x{085B}\x{085C}-\x{085D}\x{085E}\x{085F}\x{0860}-\x{086A}\x{086B}-\x{086F}\x{0870}-\x{089F}\x{08A0}-\x{08B4}\x{08B5}\x{08B6}-\x{08C7}\x{08C8}-\x{08D2}\x{08D3}-\x{08E1}\x{08E2}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09F2}-\x{09F3}\x{09FB}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AF1}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0BF3}-\x{0BF8}\x{0BF9}\x{0BFA}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C78}-\x{0C7E}\x{0C81}\x{0CBC}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E3F}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F3A}\x{0F3B}\x{0F3C}\x{0F3D}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1390}-\x{1399}\x{1400}\x{1680}\x{169B}\x{169C}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DB}\x{17DD}\x{17F0}-\x{17F9}\x{1800}-\x{1805}\x{1806}\x{1807}-\x{180A}\x{180B}-\x{180D}\x{180E}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1940}\x{1944}-\x{1945}\x{19DE}-\x{19FF}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{1FBD}\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}\x{1FFD}-\x{1FFE}\x{2000}-\x{200A}\x{200B}-\x{200D}\x{200F}\x{2010}-\x{2015}\x{2016}-\x{2017}\x{2018}\x{2019}\x{201A}\x{201B}-\x{201C}\x{201D}\x{201E}\x{201F}\x{2020}-\x{2027}\x{2028}\x{2029}\x{202A}\x{202B}\x{202C}\x{202D}\x{202E}\x{202F}\x{2030}-\x{2034}\x{2035}-\x{2038}\x{2039}\x{203A}\x{203B}-\x{203E}\x{203F}-\x{2040}\x{2041}-\x{2043}\x{2044}\x{2045}\x{2046}\x{2047}-\x{2051}\x{2052}\x{2053}\x{2054}\x{2055}-\x{205E}\x{205F}\x{2060}-\x{2064}\x{2065}\x{2066}\x{2067}\x{2068}\x{2069}\x{206A}-\x{206F}\x{207A}-\x{207B}\x{207C}\x{207D}\x{207E}\x{208A}-\x{208B}\x{208C}\x{208D}\x{208E}\x{20A0}-\x{20BF}\x{20C0}-\x{20CF}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2100}-\x{2101}\x{2103}-\x{2106}\x{2108}-\x{2109}\x{2114}\x{2116}-\x{2117}\x{2118}\x{211E}-\x{2123}\x{2125}\x{2127}\x{2129}\x{212E}\x{213A}-\x{213B}\x{2140}-\x{2144}\x{214A}\x{214B}\x{214C}-\x{214D}\x{2150}-\x{215F}\x{2189}\x{218A}-\x{218B}\x{2190}-\x{2194}\x{2195}-\x{2199}\x{219A}-\x{219B}\x{219C}-\x{219F}\x{21A0}\x{21A1}-\x{21A2}\x{21A3}\x{21A4}-\x{21A5}\x{21A6}\x{21A7}-\x{21AD}\x{21AE}\x{21AF}-\x{21CD}\x{21CE}-\x{21CF}\x{21D0}-\x{21D1}\x{21D2}\x{21D3}\x{21D4}\x{21D5}-\x{21F3}\x{21F4}-\x{2211}\x{2212}\x{2213}\x{2214}-\x{22FF}\x{2300}-\x{2307}\x{2308}\x{2309}\x{230A}\x{230B}\x{230C}-\x{231F}\x{2320}-\x{2321}\x{2322}-\x{2328}\x{2329}\x{232A}\x{232B}-\x{2335}\x{237B}\x{237C}\x{237D}-\x{2394}\x{2396}-\x{239A}\x{239B}-\x{23B3}\x{23B4}-\x{23DB}\x{23DC}-\x{23E1}\x{23E2}-\x{2426}\x{2440}-\x{244A}\x{2460}-\x{2487}\x{24EA}-\x{24FF}\x{2500}-\x{25B6}\x{25B7}\x{25B8}-\x{25C0}\x{25C1}\x{25C2}-\x{25F7}\x{25F8}-\x{25FF}\x{2600}-\x{266E}\x{266F}\x{2670}-\x{26AB}\x{26AD}-\x{2767}\x{2768}\x{2769}\x{276A}\x{276B}\x{276C}\x{276D}\x{276E}\x{276F}\x{2770}\x{2771}\x{2772}\x{2773}\x{2774}\x{2775}\x{2776}-\x{2793}\x{2794}-\x{27BF}\x{27C0}-\x{27C4}\x{27C5}\x{27C6}\x{27C7}-\x{27E5}\x{27E6}\x{27E7}\x{27E8}\x{27E9}\x{27EA}\x{27EB}\x{27EC}\x{27ED}\x{27EE}\x{27EF}\x{27F0}-\x{27FF}\x{2900}-\x{2982}\x{2983}\x{2984}\x{2985}\x{2986}\x{2987}\x{2988}\x{2989}\x{298A}\x{298B}\x{298C}\x{298D}\x{298E}\x{298F}\x{2990}\x{2991}\x{2992}\x{2993}\x{2994}\x{2995}\x{2996}\x{2997}\x{2998}\x{2999}-\x{29D7}\x{29D8}\x{29D9}\x{29DA}\x{29DB}\x{29DC}-\x{29FB}\x{29FC}\x{29FD}\x{29FE}-\x{2AFF}\x{2B00}-\x{2B2F}\x{2B30}-\x{2B44}\x{2B45}-\x{2B46}\x{2B47}-\x{2B4C}\x{2B4D}-\x{2B73}\x{2B76}-\x{2B95}\x{2B97}-\x{2BFF}\x{2CE5}-\x{2CEA}\x{2CEF}-\x{2CF1}\x{2CF9}-\x{2CFC}\x{2CFD}\x{2CFE}-\x{2CFF}\x{2D7F}\x{2DE0}-\x{2DFF}\x{2E00}-\x{2E01}\x{2E02}\x{2E03}\x{2E04}\x{2E05}\x{2E06}-\x{2E08}\x{2E09}\x{2E0A}\x{2E0B}\x{2E0C}\x{2E0D}\x{2E0E}-\x{2E16}\x{2E17}\x{2E18}-\x{2E19}\x{2E1A}\x{2E1B}\x{2E1C}\x{2E1D}\x{2E1E}-\x{2E1F}\x{2E20}\x{2E21}\x{2E22}\x{2E23}\x{2E24}\x{2E25}\x{2E26}\x{2E27}\x{2E28}\x{2E29}\x{2E2A}-\x{2E2E}\x{2E2F}\x{2E30}-\x{2E39}\x{2E3A}-\x{2E3B}\x{2E3C}-\x{2E3F}\x{2E40}\x{2E41}\x{2E42}\x{2E43}-\x{2E4F}\x{2E50}-\x{2E51}\x{2E52}\x{2E80}-\x{2E99}\x{2E9B}-\x{2EF3}\x{2F00}-\x{2FD5}\x{2FF0}-\x{2FFB}\x{3000}\x{3001}-\x{3003}\x{3004}\x{3008}\x{3009}\x{300A}\x{300B}\x{300C}\x{300D}\x{300E}\x{300F}\x{3010}\x{3011}\x{3012}-\x{3013}\x{3014}\x{3015}\x{3016}\x{3017}\x{3018}\x{3019}\x{301A}\x{301B}\x{301C}\x{301D}\x{301E}-\x{301F}\x{3020}\x{302A}-\x{302D}\x{3030}\x{3036}-\x{3037}\x{303D}\x{303E}-\x{303F}\x{3099}-\x{309A}\x{309B}-\x{309C}\x{30A0}\x{30FB}\x{31C0}-\x{31E3}\x{321D}-\x{321E}\x{3250}\x{3251}-\x{325F}\x{327C}-\x{327E}\x{32B1}-\x{32BF}\x{32CC}-\x{32CF}\x{3377}-\x{337A}\x{33DE}-\x{33DF}\x{33FF}\x{4DC0}-\x{4DFF}\x{A490}-\x{A4C6}\x{A60D}-\x{A60F}\x{A66F}\x{A670}-\x{A672}\x{A673}\x{A674}-\x{A67D}\x{A67E}\x{A67F}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A700}-\x{A716}\x{A717}-\x{A71F}\x{A720}-\x{A721}\x{A788}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A828}-\x{A82B}\x{A82C}\x{A838}\x{A839}\x{A874}-\x{A877}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{AB6A}-\x{AB6B}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1D}\x{FB1E}\x{FB1F}-\x{FB28}\x{FB29}\x{FB2A}-\x{FB36}\x{FB37}\x{FB38}-\x{FB3C}\x{FB3D}\x{FB3E}\x{FB3F}\x{FB40}-\x{FB41}\x{FB42}\x{FB43}-\x{FB44}\x{FB45}\x{FB46}-\x{FB4F}\x{FB50}-\x{FBB1}\x{FBB2}-\x{FBC1}\x{FBC2}-\x{FBD2}\x{FBD3}-\x{FD3D}\x{FD3E}\x{FD3F}\x{FD40}-\x{FD4F}\x{FD50}-\x{FD8F}\x{FD90}-\x{FD91}\x{FD92}-\x{FDC7}\x{FDC8}-\x{FDCF}\x{FDD0}-\x{FDEF}\x{FDF0}-\x{FDFB}\x{FDFC}\x{FDFD}\x{FDFE}-\x{FDFF}\x{FE00}-\x{FE0F}\x{FE10}-\x{FE16}\x{FE17}\x{FE18}\x{FE19}\x{FE20}-\x{FE2F}\x{FE30}\x{FE31}-\x{FE32}\x{FE33}-\x{FE34}\x{FE35}\x{FE36}\x{FE37}\x{FE38}\x{FE39}\x{FE3A}\x{FE3B}\x{FE3C}\x{FE3D}\x{FE3E}\x{FE3F}\x{FE40}\x{FE41}\x{FE42}\x{FE43}\x{FE44}\x{FE45}-\x{FE46}\x{FE47}\x{FE48}\x{FE49}-\x{FE4C}\x{FE4D}-\x{FE4F}\x{FE50}\x{FE51}\x{FE52}\x{FE54}\x{FE55}\x{FE56}-\x{FE57}\x{FE58}\x{FE59}\x{FE5A}\x{FE5B}\x{FE5C}\x{FE5D}\x{FE5E}\x{FE5F}\x{FE60}-\x{FE61}\x{FE62}\x{FE63}\x{FE64}-\x{FE66}\x{FE68}\x{FE69}\x{FE6A}\x{FE6B}\x{FE70}-\x{FE74}\x{FE75}\x{FE76}-\x{FEFC}\x{FEFD}-\x{FEFE}\x{FEFF}\x{FF01}-\x{FF02}\x{FF03}\x{FF04}\x{FF05}\x{FF06}-\x{FF07}\x{FF08}\x{FF09}\x{FF0A}\x{FF0B}\x{FF0C}\x{FF0D}\x{FF0E}-\x{FF0F}\x{FF1A}\x{FF1B}\x{FF1C}-\x{FF1E}\x{FF1F}-\x{FF20}\x{FF3B}\x{FF3C}\x{FF3D}\x{FF3E}\x{FF3F}\x{FF40}\x{FF5B}\x{FF5C}\x{FF5D}\x{FF5E}\x{FF5F}\x{FF60}\x{FF61}\x{FF62}\x{FF63}\x{FF64}-\x{FF65}\x{FFE0}-\x{FFE1}\x{FFE2}\x{FFE3}\x{FFE4}\x{FFE5}-\x{FFE6}\x{FFE8}\x{FFE9}-\x{FFEC}\x{FFED}-\x{FFEE}\x{FFF0}-\x{FFF8}\x{FFF9}-\x{FFFB}\x{FFFC}-\x{FFFD}\x{FFFE}-\x{FFFF}\x{10101}\x{10140}-\x{10174}\x{10175}-\x{10178}\x{10179}-\x{10189}\x{1018A}-\x{1018B}\x{1018C}\x{10190}-\x{1019C}\x{101A0}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10800}-\x{10805}\x{10806}-\x{10807}\x{10808}\x{10809}\x{1080A}-\x{10835}\x{10836}\x{10837}-\x{10838}\x{10839}-\x{1083B}\x{1083C}\x{1083D}-\x{1083E}\x{1083F}-\x{10855}\x{10856}\x{10857}\x{10858}-\x{1085F}\x{10860}-\x{10876}\x{10877}-\x{10878}\x{10879}-\x{1087F}\x{10880}-\x{1089E}\x{1089F}-\x{108A6}\x{108A7}-\x{108AF}\x{108B0}-\x{108DF}\x{108E0}-\x{108F2}\x{108F3}\x{108F4}-\x{108F5}\x{108F6}-\x{108FA}\x{108FB}-\x{108FF}\x{10900}-\x{10915}\x{10916}-\x{1091B}\x{1091C}-\x{1091E}\x{1091F}\x{10920}-\x{10939}\x{1093A}-\x{1093E}\x{1093F}\x{10940}-\x{1097F}\x{10980}-\x{109B7}\x{109B8}-\x{109BB}\x{109BC}-\x{109BD}\x{109BE}-\x{109BF}\x{109C0}-\x{109CF}\x{109D0}-\x{109D1}\x{109D2}-\x{109FF}\x{10A00}\x{10A01}-\x{10A03}\x{10A04}\x{10A05}-\x{10A06}\x{10A07}-\x{10A0B}\x{10A0C}-\x{10A0F}\x{10A10}-\x{10A13}\x{10A14}\x{10A15}-\x{10A17}\x{10A18}\x{10A19}-\x{10A35}\x{10A36}-\x{10A37}\x{10A38}-\x{10A3A}\x{10A3B}-\x{10A3E}\x{10A3F}\x{10A40}-\x{10A48}\x{10A49}-\x{10A4F}\x{10A50}-\x{10A58}\x{10A59}-\x{10A5F}\x{10A60}-\x{10A7C}\x{10A7D}-\x{10A7E}\x{10A7F}\x{10A80}-\x{10A9C}\x{10A9D}-\x{10A9F}\x{10AA0}-\x{10ABF}\x{10AC0}-\x{10AC7}\x{10AC8}\x{10AC9}-\x{10AE4}\x{10AE5}-\x{10AE6}\x{10AE7}-\x{10AEA}\x{10AEB}-\x{10AEF}\x{10AF0}-\x{10AF6}\x{10AF7}-\x{10AFF}\x{10B00}-\x{10B35}\x{10B36}-\x{10B38}\x{10B39}-\x{10B3F}\x{10B40}-\x{10B55}\x{10B56}-\x{10B57}\x{10B58}-\x{10B5F}\x{10B60}-\x{10B72}\x{10B73}-\x{10B77}\x{10B78}-\x{10B7F}\x{10B80}-\x{10B91}\x{10B92}-\x{10B98}\x{10B99}-\x{10B9C}\x{10B9D}-\x{10BA8}\x{10BA9}-\x{10BAF}\x{10BB0}-\x{10BFF}\x{10C00}-\x{10C48}\x{10C49}-\x{10C7F}\x{10C80}-\x{10CB2}\x{10CB3}-\x{10CBF}\x{10CC0}-\x{10CF2}\x{10CF3}-\x{10CF9}\x{10CFA}-\x{10CFF}\x{10D00}-\x{10D23}\x{10D24}-\x{10D27}\x{10D28}-\x{10D2F}\x{10D30}-\x{10D39}\x{10D3A}-\x{10D3F}\x{10D40}-\x{10E5F}\x{10E60}-\x{10E7E}\x{10E7F}\x{10E80}-\x{10EA9}\x{10EAA}\x{10EAB}-\x{10EAC}\x{10EAD}\x{10EAE}-\x{10EAF}\x{10EB0}-\x{10EB1}\x{10EB2}-\x{10EFF}\x{10F00}-\x{10F1C}\x{10F1D}-\x{10F26}\x{10F27}\x{10F28}-\x{10F2F}\x{10F30}-\x{10F45}\x{10F46}-\x{10F50}\x{10F51}-\x{10F54}\x{10F55}-\x{10F59}\x{10F5A}-\x{10F6F}\x{10F70}-\x{10FAF}\x{10FB0}-\x{10FC4}\x{10FC5}-\x{10FCB}\x{10FCC}-\x{10FDF}\x{10FE0}-\x{10FF6}\x{10FF7}-\x{10FFF}\x{11001}\x{11038}-\x{11046}\x{11052}-\x{11065}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{11660}-\x{1166C}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A06}\x{11A09}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{11FD5}-\x{11FDC}\x{11FDD}-\x{11FE0}\x{11FE1}-\x{11FF1}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE2}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D200}-\x{1D241}\x{1D242}-\x{1D244}\x{1D245}\x{1D300}-\x{1D356}\x{1D6DB}\x{1D715}\x{1D74F}\x{1D789}\x{1D7C3}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E2FF}\x{1E800}-\x{1E8C4}\x{1E8C5}-\x{1E8C6}\x{1E8C7}-\x{1E8CF}\x{1E8D0}-\x{1E8D6}\x{1E8D7}-\x{1E8FF}\x{1E900}-\x{1E943}\x{1E944}-\x{1E94A}\x{1E94B}\x{1E94C}-\x{1E94F}\x{1E950}-\x{1E959}\x{1E95A}-\x{1E95D}\x{1E95E}-\x{1E95F}\x{1E960}-\x{1EC6F}\x{1EC70}\x{1EC71}-\x{1ECAB}\x{1ECAC}\x{1ECAD}-\x{1ECAF}\x{1ECB0}\x{1ECB1}-\x{1ECB4}\x{1ECB5}-\x{1ECBF}\x{1ECC0}-\x{1ECFF}\x{1ED00}\x{1ED01}-\x{1ED2D}\x{1ED2E}\x{1ED2F}-\x{1ED3D}\x{1ED3E}-\x{1ED4F}\x{1ED50}-\x{1EDFF}\x{1EE00}-\x{1EE03}\x{1EE04}\x{1EE05}-\x{1EE1F}\x{1EE20}\x{1EE21}-\x{1EE22}\x{1EE23}\x{1EE24}\x{1EE25}-\x{1EE26}\x{1EE27}\x{1EE28}\x{1EE29}-\x{1EE32}\x{1EE33}\x{1EE34}-\x{1EE37}\x{1EE38}\x{1EE39}\x{1EE3A}\x{1EE3B}\x{1EE3C}-\x{1EE41}\x{1EE42}\x{1EE43}-\x{1EE46}\x{1EE47}\x{1EE48}\x{1EE49}\x{1EE4A}\x{1EE4B}\x{1EE4C}\x{1EE4D}-\x{1EE4F}\x{1EE50}\x{1EE51}-\x{1EE52}\x{1EE53}\x{1EE54}\x{1EE55}-\x{1EE56}\x{1EE57}\x{1EE58}\x{1EE59}\x{1EE5A}\x{1EE5B}\x{1EE5C}\x{1EE5D}\x{1EE5E}\x{1EE5F}\x{1EE60}\x{1EE61}-\x{1EE62}\x{1EE63}\x{1EE64}\x{1EE65}-\x{1EE66}\x{1EE67}-\x{1EE6A}\x{1EE6B}\x{1EE6C}-\x{1EE72}\x{1EE73}\x{1EE74}-\x{1EE77}\x{1EE78}\x{1EE79}-\x{1EE7C}\x{1EE7D}\x{1EE7E}\x{1EE7F}\x{1EE80}-\x{1EE89}\x{1EE8A}\x{1EE8B}-\x{1EE9B}\x{1EE9C}-\x{1EEA0}\x{1EEA1}-\x{1EEA3}\x{1EEA4}\x{1EEA5}-\x{1EEA9}\x{1EEAA}\x{1EEAB}-\x{1EEBB}\x{1EEBC}-\x{1EEEF}\x{1EEF0}-\x{1EEF1}\x{1EEF2}-\x{1EEFF}\x{1EF00}-\x{1EFFF}\x{1F000}-\x{1F02B}\x{1F030}-\x{1F093}\x{1F0A0}-\x{1F0AE}\x{1F0B1}-\x{1F0BF}\x{1F0C1}-\x{1F0CF}\x{1F0D1}-\x{1F0F5}\x{1F10B}-\x{1F10C}\x{1F10D}-\x{1F10F}\x{1F12F}\x{1F16A}-\x{1F16F}\x{1F1AD}\x{1F260}-\x{1F265}\x{1F300}-\x{1F3FA}\x{1F3FB}-\x{1F3FF}\x{1F400}-\x{1F6D7}\x{1F6E0}-\x{1F6EC}\x{1F6F0}-\x{1F6FC}\x{1F700}-\x{1F773}\x{1F780}-\x{1F7D8}\x{1F7E0}-\x{1F7EB}\x{1F800}-\x{1F80B}\x{1F810}-\x{1F847}\x{1F850}-\x{1F859}\x{1F860}-\x{1F887}\x{1F890}-\x{1F8AD}\x{1F8B0}-\x{1F8B1}\x{1F900}-\x{1F978}\x{1F97A}-\x{1F9CB}\x{1F9CD}-\x{1FA53}\x{1FA60}-\x{1FA6D}\x{1FA70}-\x{1FA74}\x{1FA78}-\x{1FA7A}\x{1FA80}-\x{1FA86}\x{1FA90}-\x{1FAA8}\x{1FAB0}-\x{1FAB6}\x{1FAC0}-\x{1FAC2}\x{1FAD0}-\x{1FAD6}\x{1FB00}-\x{1FB92}\x{1FB94}-\x{1FBCA}\x{1FFFE}-\x{1FFFF}\x{2FFFE}-\x{2FFFF}\x{3FFFE}-\x{3FFFF}\x{4FFFE}-\x{4FFFF}\x{5FFFE}-\x{5FFFF}\x{6FFFE}-\x{6FFFF}\x{7FFFE}-\x{7FFFF}\x{8FFFE}-\x{8FFFF}\x{9FFFE}-\x{9FFFF}\x{AFFFE}-\x{AFFFF}\x{BFFFE}-\x{BFFFF}\x{CFFFE}-\x{CFFFF}\x{DFFFE}-\x{E0000}\x{E0001}\x{E0002}-\x{E001F}\x{E0020}-\x{E007F}\x{E0080}-\x{E00FF}\x{E0100}-\x{E01EF}\x{E01F0}-\x{E0FFF}\x{EFFFE}-\x{EFFFF}\x{FFFFE}-\x{FFFFF}\x{10FFFE}-\x{10FFFF}][\x{0300}-\x{036F}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{0610}-\x{061A}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DF}-\x{06E4}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07FD}\x{0816}-\x{0819}\x{081B}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DD}\x{180B}-\x{180D}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2CEF}-\x{2CF1}\x{2D7F}\x{2DE0}-\x{2DFF}\x{302A}-\x{302D}\x{3099}-\x{309A}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A82C}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FE00}-\x{FE0F}\x{FE20}-\x{FE2F}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10EAB}-\x{10EAC}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A06}\x{11A09}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1D167}-\x{1D169}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{E0100}-\x{E01EF}]*$/u'; + + const ZWNJ = '/([\x{A872}\x{10ACD}\x{10AD7}\x{10D00}\x{10FCB}\x{0620}\x{0626}\x{0628}\x{062A}-\x{062E}\x{0633}-\x{063F}\x{0641}-\x{0647}\x{0649}-\x{064A}\x{066E}-\x{066F}\x{0678}-\x{0687}\x{069A}-\x{06BF}\x{06C1}-\x{06C2}\x{06CC}\x{06CE}\x{06D0}-\x{06D1}\x{06FA}-\x{06FC}\x{06FF}\x{0712}-\x{0714}\x{071A}-\x{071D}\x{071F}-\x{0727}\x{0729}\x{072B}\x{072D}-\x{072E}\x{074E}-\x{0758}\x{075C}-\x{076A}\x{076D}-\x{0770}\x{0772}\x{0775}-\x{0777}\x{077A}-\x{077F}\x{07CA}-\x{07EA}\x{0841}-\x{0845}\x{0848}\x{084A}-\x{0853}\x{0855}\x{0860}\x{0862}-\x{0865}\x{0868}\x{08A0}-\x{08A9}\x{08AF}-\x{08B0}\x{08B3}-\x{08B4}\x{08B6}-\x{08B8}\x{08BA}-\x{08C7}\x{1807}\x{1820}-\x{1842}\x{1843}\x{1844}-\x{1878}\x{1887}-\x{18A8}\x{18AA}\x{A840}-\x{A871}\x{10AC0}-\x{10AC4}\x{10AD3}-\x{10AD6}\x{10AD8}-\x{10ADC}\x{10ADE}-\x{10AE0}\x{10AEB}-\x{10AEE}\x{10B80}\x{10B82}\x{10B86}-\x{10B88}\x{10B8A}-\x{10B8B}\x{10B8D}\x{10B90}\x{10BAD}-\x{10BAE}\x{10D01}-\x{10D21}\x{10D23}\x{10F30}-\x{10F32}\x{10F34}-\x{10F44}\x{10F51}-\x{10F53}\x{10FB0}\x{10FB2}-\x{10FB3}\x{10FB8}\x{10FBB}-\x{10FBC}\x{10FBE}-\x{10FBF}\x{10FC1}\x{10FC4}\x{10FCA}\x{1E900}-\x{1E943}][\x{00AD}\x{0300}-\x{036F}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{0610}-\x{061A}\x{061C}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DF}-\x{06E4}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{070F}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07FD}\x{0816}-\x{0819}\x{081B}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CBF}\x{0CC6}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DD}\x{180B}-\x{180D}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{200B}\x{200E}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{206A}-\x{206F}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2CEF}-\x{2CF1}\x{2D7F}\x{2DE0}-\x{2DFF}\x{302A}-\x{302D}\x{3099}-\x{309A}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A82C}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FE00}-\x{FE0F}\x{FE20}-\x{FE2F}\x{FEFF}\x{FFF9}-\x{FFFB}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10EAB}-\x{10EAC}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C3F}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{13430}-\x{13438}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{1E94B}\x{E0001}\x{E0020}-\x{E007F}\x{E0100}-\x{E01EF}]*\x{200C}[\x{00AD}\x{0300}-\x{036F}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{0610}-\x{061A}\x{061C}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DF}-\x{06E4}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{070F}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07FD}\x{0816}-\x{0819}\x{081B}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B55}-\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CBF}\x{0CC6}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0D81}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EBC}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17DD}\x{180B}-\x{180D}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1ABF}-\x{1AC0}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{200B}\x{200E}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{206A}-\x{206F}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2CEF}-\x{2CF1}\x{2D7F}\x{2DE0}-\x{2DFF}\x{302A}-\x{302D}\x{3099}-\x{309A}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A82C}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}-\x{A9BD}\x{A9E5}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AAEC}-\x{AAED}\x{AAF6}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FE00}-\x{FE0F}\x{FE20}-\x{FE2F}\x{FEFF}\x{FFF9}-\x{FFFB}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10EAB}-\x{10EAC}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{111CF}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{1193B}-\x{1193C}\x{1193E}\x{11943}\x{119D4}-\x{119D7}\x{119DA}-\x{119DB}\x{119E0}\x{11A01}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C3F}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{13430}-\x{13438}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16F4F}\x{16F8F}-\x{16F92}\x{16FE4}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E130}-\x{1E136}\x{1E2EC}-\x{1E2EF}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{1E94B}\x{E0001}\x{E0020}-\x{E007F}\x{E0100}-\x{E01EF}]*)[\x{0622}-\x{0625}\x{0627}\x{0629}\x{062F}-\x{0632}\x{0648}\x{0671}-\x{0673}\x{0675}-\x{0677}\x{0688}-\x{0699}\x{06C0}\x{06C3}-\x{06CB}\x{06CD}\x{06CF}\x{06D2}-\x{06D3}\x{06D5}\x{06EE}-\x{06EF}\x{0710}\x{0715}-\x{0719}\x{071E}\x{0728}\x{072A}\x{072C}\x{072F}\x{074D}\x{0759}-\x{075B}\x{076B}-\x{076C}\x{0771}\x{0773}-\x{0774}\x{0778}-\x{0779}\x{0840}\x{0846}-\x{0847}\x{0849}\x{0854}\x{0856}-\x{0858}\x{0867}\x{0869}-\x{086A}\x{08AA}-\x{08AC}\x{08AE}\x{08B1}-\x{08B2}\x{08B9}\x{10AC5}\x{10AC7}\x{10AC9}-\x{10ACA}\x{10ACE}-\x{10AD2}\x{10ADD}\x{10AE1}\x{10AE4}\x{10AEF}\x{10B81}\x{10B83}-\x{10B85}\x{10B89}\x{10B8C}\x{10B8E}-\x{10B8F}\x{10B91}\x{10BA9}-\x{10BAC}\x{10D22}\x{10F33}\x{10F54}\x{10FB4}-\x{10FB6}\x{10FB9}-\x{10FBA}\x{10FBD}\x{10FC2}-\x{10FC3}\x{10FC9}\x{0620}\x{0626}\x{0628}\x{062A}-\x{062E}\x{0633}-\x{063F}\x{0641}-\x{0647}\x{0649}-\x{064A}\x{066E}-\x{066F}\x{0678}-\x{0687}\x{069A}-\x{06BF}\x{06C1}-\x{06C2}\x{06CC}\x{06CE}\x{06D0}-\x{06D1}\x{06FA}-\x{06FC}\x{06FF}\x{0712}-\x{0714}\x{071A}-\x{071D}\x{071F}-\x{0727}\x{0729}\x{072B}\x{072D}-\x{072E}\x{074E}-\x{0758}\x{075C}-\x{076A}\x{076D}-\x{0770}\x{0772}\x{0775}-\x{0777}\x{077A}-\x{077F}\x{07CA}-\x{07EA}\x{0841}-\x{0845}\x{0848}\x{084A}-\x{0853}\x{0855}\x{0860}\x{0862}-\x{0865}\x{0868}\x{08A0}-\x{08A9}\x{08AF}-\x{08B0}\x{08B3}-\x{08B4}\x{08B6}-\x{08B8}\x{08BA}-\x{08C7}\x{1807}\x{1820}-\x{1842}\x{1843}\x{1844}-\x{1878}\x{1887}-\x{18A8}\x{18AA}\x{A840}-\x{A871}\x{10AC0}-\x{10AC4}\x{10AD3}-\x{10AD6}\x{10AD8}-\x{10ADC}\x{10ADE}-\x{10AE0}\x{10AEB}-\x{10AEE}\x{10B80}\x{10B82}\x{10B86}-\x{10B88}\x{10B8A}-\x{10B8B}\x{10B8D}\x{10B90}\x{10BAD}-\x{10BAE}\x{10D01}-\x{10D21}\x{10D23}\x{10F30}-\x{10F32}\x{10F34}-\x{10F44}\x{10F51}-\x{10F53}\x{10FB0}\x{10FB2}-\x{10FB3}\x{10FB8}\x{10FBB}-\x{10FBC}\x{10FBE}-\x{10FBF}\x{10FC1}\x{10FC4}\x{10FCA}\x{1E900}-\x{1E943}]/u'; +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/deviation.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/deviation.php new file mode 100644 index 0000000..0bbd335 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/deviation.php @@ -0,0 +1,8 @@ + 'ss', + 962 => 'σ', + 8204 => '', + 8205 => '', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed.php new file mode 100644 index 0000000..25a5f56 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed.php @@ -0,0 +1,2638 @@ + true, + 889 => true, + 896 => true, + 897 => true, + 898 => true, + 899 => true, + 907 => true, + 909 => true, + 930 => true, + 1216 => true, + 1328 => true, + 1367 => true, + 1368 => true, + 1419 => true, + 1420 => true, + 1424 => true, + 1480 => true, + 1481 => true, + 1482 => true, + 1483 => true, + 1484 => true, + 1485 => true, + 1486 => true, + 1487 => true, + 1515 => true, + 1516 => true, + 1517 => true, + 1518 => true, + 1525 => true, + 1526 => true, + 1527 => true, + 1528 => true, + 1529 => true, + 1530 => true, + 1531 => true, + 1532 => true, + 1533 => true, + 1534 => true, + 1535 => true, + 1536 => true, + 1537 => true, + 1538 => true, + 1539 => true, + 1540 => true, + 1541 => true, + 1564 => true, + 1565 => true, + 1757 => true, + 1806 => true, + 1807 => true, + 1867 => true, + 1868 => true, + 1970 => true, + 1971 => true, + 1972 => true, + 1973 => true, + 1974 => true, + 1975 => true, + 1976 => true, + 1977 => true, + 1978 => true, + 1979 => true, + 1980 => true, + 1981 => true, + 1982 => true, + 1983 => true, + 2043 => true, + 2044 => true, + 2094 => true, + 2095 => true, + 2111 => true, + 2140 => true, + 2141 => true, + 2143 => true, + 2229 => true, + 2248 => true, + 2249 => true, + 2250 => true, + 2251 => true, + 2252 => true, + 2253 => true, + 2254 => true, + 2255 => true, + 2256 => true, + 2257 => true, + 2258 => true, + 2274 => true, + 2436 => true, + 2445 => true, + 2446 => true, + 2449 => true, + 2450 => true, + 2473 => true, + 2481 => true, + 2483 => true, + 2484 => true, + 2485 => true, + 2490 => true, + 2491 => true, + 2501 => true, + 2502 => true, + 2505 => true, + 2506 => true, + 2511 => true, + 2512 => true, + 2513 => true, + 2514 => true, + 2515 => true, + 2516 => true, + 2517 => true, + 2518 => true, + 2520 => true, + 2521 => true, + 2522 => true, + 2523 => true, + 2526 => true, + 2532 => true, + 2533 => true, + 2559 => true, + 2560 => true, + 2564 => true, + 2571 => true, + 2572 => true, + 2573 => true, + 2574 => true, + 2577 => true, + 2578 => true, + 2601 => true, + 2609 => true, + 2612 => true, + 2615 => true, + 2618 => true, + 2619 => true, + 2621 => true, + 2627 => true, + 2628 => true, + 2629 => true, + 2630 => true, + 2633 => true, + 2634 => true, + 2638 => true, + 2639 => true, + 2640 => true, + 2642 => true, + 2643 => true, + 2644 => true, + 2645 => true, + 2646 => true, + 2647 => true, + 2648 => true, + 2653 => true, + 2655 => true, + 2656 => true, + 2657 => true, + 2658 => true, + 2659 => true, + 2660 => true, + 2661 => true, + 2679 => true, + 2680 => true, + 2681 => true, + 2682 => true, + 2683 => true, + 2684 => true, + 2685 => true, + 2686 => true, + 2687 => true, + 2688 => true, + 2692 => true, + 2702 => true, + 2706 => true, + 2729 => true, + 2737 => true, + 2740 => true, + 2746 => true, + 2747 => true, + 2758 => true, + 2762 => true, + 2766 => true, + 2767 => true, + 2769 => true, + 2770 => true, + 2771 => true, + 2772 => true, + 2773 => true, + 2774 => true, + 2775 => true, + 2776 => true, + 2777 => true, + 2778 => true, + 2779 => true, + 2780 => true, + 2781 => true, + 2782 => true, + 2783 => true, + 2788 => true, + 2789 => true, + 2802 => true, + 2803 => true, + 2804 => true, + 2805 => true, + 2806 => true, + 2807 => true, + 2808 => true, + 2816 => true, + 2820 => true, + 2829 => true, + 2830 => true, + 2833 => true, + 2834 => true, + 2857 => true, + 2865 => true, + 2868 => true, + 2874 => true, + 2875 => true, + 2885 => true, + 2886 => true, + 2889 => true, + 2890 => true, + 2894 => true, + 2895 => true, + 2896 => true, + 2897 => true, + 2898 => true, + 2899 => true, + 2900 => true, + 2904 => true, + 2905 => true, + 2906 => true, + 2907 => true, + 2910 => true, + 2916 => true, + 2917 => true, + 2936 => true, + 2937 => true, + 2938 => true, + 2939 => true, + 2940 => true, + 2941 => true, + 2942 => true, + 2943 => true, + 2944 => true, + 2945 => true, + 2948 => true, + 2955 => true, + 2956 => true, + 2957 => true, + 2961 => true, + 2966 => true, + 2967 => true, + 2968 => true, + 2971 => true, + 2973 => true, + 2976 => true, + 2977 => true, + 2978 => true, + 2981 => true, + 2982 => true, + 2983 => true, + 2987 => true, + 2988 => true, + 2989 => true, + 3002 => true, + 3003 => true, + 3004 => true, + 3005 => true, + 3011 => true, + 3012 => true, + 3013 => true, + 3017 => true, + 3022 => true, + 3023 => true, + 3025 => true, + 3026 => true, + 3027 => true, + 3028 => true, + 3029 => true, + 3030 => true, + 3032 => true, + 3033 => true, + 3034 => true, + 3035 => true, + 3036 => true, + 3037 => true, + 3038 => true, + 3039 => true, + 3040 => true, + 3041 => true, + 3042 => true, + 3043 => true, + 3044 => true, + 3045 => true, + 3067 => true, + 3068 => true, + 3069 => true, + 3070 => true, + 3071 => true, + 3085 => true, + 3089 => true, + 3113 => true, + 3130 => true, + 3131 => true, + 3132 => true, + 3141 => true, + 3145 => true, + 3150 => true, + 3151 => true, + 3152 => true, + 3153 => true, + 3154 => true, + 3155 => true, + 3156 => true, + 3159 => true, + 3163 => true, + 3164 => true, + 3165 => true, + 3166 => true, + 3167 => true, + 3172 => true, + 3173 => true, + 3184 => true, + 3185 => true, + 3186 => true, + 3187 => true, + 3188 => true, + 3189 => true, + 3190 => true, + 3213 => true, + 3217 => true, + 3241 => true, + 3252 => true, + 3258 => true, + 3259 => true, + 3269 => true, + 3273 => true, + 3278 => true, + 3279 => true, + 3280 => true, + 3281 => true, + 3282 => true, + 3283 => true, + 3284 => true, + 3287 => true, + 3288 => true, + 3289 => true, + 3290 => true, + 3291 => true, + 3292 => true, + 3293 => true, + 3295 => true, + 3300 => true, + 3301 => true, + 3312 => true, + 3315 => true, + 3316 => true, + 3317 => true, + 3318 => true, + 3319 => true, + 3320 => true, + 3321 => true, + 3322 => true, + 3323 => true, + 3324 => true, + 3325 => true, + 3326 => true, + 3327 => true, + 3341 => true, + 3345 => true, + 3397 => true, + 3401 => true, + 3408 => true, + 3409 => true, + 3410 => true, + 3411 => true, + 3428 => true, + 3429 => true, + 3456 => true, + 3460 => true, + 3479 => true, + 3480 => true, + 3481 => true, + 3506 => true, + 3516 => true, + 3518 => true, + 3519 => true, + 3527 => true, + 3528 => true, + 3529 => true, + 3531 => true, + 3532 => true, + 3533 => true, + 3534 => true, + 3541 => true, + 3543 => true, + 3552 => true, + 3553 => true, + 3554 => true, + 3555 => true, + 3556 => true, + 3557 => true, + 3568 => true, + 3569 => true, + 3573 => true, + 3574 => true, + 3575 => true, + 3576 => true, + 3577 => true, + 3578 => true, + 3579 => true, + 3580 => true, + 3581 => true, + 3582 => true, + 3583 => true, + 3584 => true, + 3643 => true, + 3644 => true, + 3645 => true, + 3646 => true, + 3715 => true, + 3717 => true, + 3723 => true, + 3748 => true, + 3750 => true, + 3774 => true, + 3775 => true, + 3781 => true, + 3783 => true, + 3790 => true, + 3791 => true, + 3802 => true, + 3803 => true, + 3912 => true, + 3949 => true, + 3950 => true, + 3951 => true, + 3952 => true, + 3992 => true, + 4029 => true, + 4045 => true, + 4294 => true, + 4296 => true, + 4297 => true, + 4298 => true, + 4299 => true, + 4300 => true, + 4302 => true, + 4303 => true, + 4447 => true, + 4448 => true, + 4681 => true, + 4686 => true, + 4687 => true, + 4695 => true, + 4697 => true, + 4702 => true, + 4703 => true, + 4745 => true, + 4750 => true, + 4751 => true, + 4785 => true, + 4790 => true, + 4791 => true, + 4799 => true, + 4801 => true, + 4806 => true, + 4807 => true, + 4823 => true, + 4881 => true, + 4886 => true, + 4887 => true, + 4955 => true, + 4956 => true, + 4989 => true, + 4990 => true, + 4991 => true, + 5018 => true, + 5019 => true, + 5020 => true, + 5021 => true, + 5022 => true, + 5023 => true, + 5110 => true, + 5111 => true, + 5118 => true, + 5119 => true, + 5760 => true, + 5789 => true, + 5790 => true, + 5791 => true, + 5881 => true, + 5882 => true, + 5883 => true, + 5884 => true, + 5885 => true, + 5886 => true, + 5887 => true, + 5901 => true, + 5909 => true, + 5910 => true, + 5911 => true, + 5912 => true, + 5913 => true, + 5914 => true, + 5915 => true, + 5916 => true, + 5917 => true, + 5918 => true, + 5919 => true, + 5943 => true, + 5944 => true, + 5945 => true, + 5946 => true, + 5947 => true, + 5948 => true, + 5949 => true, + 5950 => true, + 5951 => true, + 5972 => true, + 5973 => true, + 5974 => true, + 5975 => true, + 5976 => true, + 5977 => true, + 5978 => true, + 5979 => true, + 5980 => true, + 5981 => true, + 5982 => true, + 5983 => true, + 5997 => true, + 6001 => true, + 6004 => true, + 6005 => true, + 6006 => true, + 6007 => true, + 6008 => true, + 6009 => true, + 6010 => true, + 6011 => true, + 6012 => true, + 6013 => true, + 6014 => true, + 6015 => true, + 6068 => true, + 6069 => true, + 6110 => true, + 6111 => true, + 6122 => true, + 6123 => true, + 6124 => true, + 6125 => true, + 6126 => true, + 6127 => true, + 6138 => true, + 6139 => true, + 6140 => true, + 6141 => true, + 6142 => true, + 6143 => true, + 6150 => true, + 6158 => true, + 6159 => true, + 6170 => true, + 6171 => true, + 6172 => true, + 6173 => true, + 6174 => true, + 6175 => true, + 6265 => true, + 6266 => true, + 6267 => true, + 6268 => true, + 6269 => true, + 6270 => true, + 6271 => true, + 6315 => true, + 6316 => true, + 6317 => true, + 6318 => true, + 6319 => true, + 6390 => true, + 6391 => true, + 6392 => true, + 6393 => true, + 6394 => true, + 6395 => true, + 6396 => true, + 6397 => true, + 6398 => true, + 6399 => true, + 6431 => true, + 6444 => true, + 6445 => true, + 6446 => true, + 6447 => true, + 6460 => true, + 6461 => true, + 6462 => true, + 6463 => true, + 6465 => true, + 6466 => true, + 6467 => true, + 6510 => true, + 6511 => true, + 6517 => true, + 6518 => true, + 6519 => true, + 6520 => true, + 6521 => true, + 6522 => true, + 6523 => true, + 6524 => true, + 6525 => true, + 6526 => true, + 6527 => true, + 6572 => true, + 6573 => true, + 6574 => true, + 6575 => true, + 6602 => true, + 6603 => true, + 6604 => true, + 6605 => true, + 6606 => true, + 6607 => true, + 6619 => true, + 6620 => true, + 6621 => true, + 6684 => true, + 6685 => true, + 6751 => true, + 6781 => true, + 6782 => true, + 6794 => true, + 6795 => true, + 6796 => true, + 6797 => true, + 6798 => true, + 6799 => true, + 6810 => true, + 6811 => true, + 6812 => true, + 6813 => true, + 6814 => true, + 6815 => true, + 6830 => true, + 6831 => true, + 6988 => true, + 6989 => true, + 6990 => true, + 6991 => true, + 7037 => true, + 7038 => true, + 7039 => true, + 7156 => true, + 7157 => true, + 7158 => true, + 7159 => true, + 7160 => true, + 7161 => true, + 7162 => true, + 7163 => true, + 7224 => true, + 7225 => true, + 7226 => true, + 7242 => true, + 7243 => true, + 7244 => true, + 7305 => true, + 7306 => true, + 7307 => true, + 7308 => true, + 7309 => true, + 7310 => true, + 7311 => true, + 7355 => true, + 7356 => true, + 7368 => true, + 7369 => true, + 7370 => true, + 7371 => true, + 7372 => true, + 7373 => true, + 7374 => true, + 7375 => true, + 7419 => true, + 7420 => true, + 7421 => true, + 7422 => true, + 7423 => true, + 7674 => true, + 7958 => true, + 7959 => true, + 7966 => true, + 7967 => true, + 8006 => true, + 8007 => true, + 8014 => true, + 8015 => true, + 8024 => true, + 8026 => true, + 8028 => true, + 8030 => true, + 8062 => true, + 8063 => true, + 8117 => true, + 8133 => true, + 8148 => true, + 8149 => true, + 8156 => true, + 8176 => true, + 8177 => true, + 8181 => true, + 8191 => true, + 8206 => true, + 8207 => true, + 8228 => true, + 8229 => true, + 8230 => true, + 8232 => true, + 8233 => true, + 8234 => true, + 8235 => true, + 8236 => true, + 8237 => true, + 8238 => true, + 8289 => true, + 8290 => true, + 8291 => true, + 8293 => true, + 8294 => true, + 8295 => true, + 8296 => true, + 8297 => true, + 8298 => true, + 8299 => true, + 8300 => true, + 8301 => true, + 8302 => true, + 8303 => true, + 8306 => true, + 8307 => true, + 8335 => true, + 8349 => true, + 8350 => true, + 8351 => true, + 8384 => true, + 8385 => true, + 8386 => true, + 8387 => true, + 8388 => true, + 8389 => true, + 8390 => true, + 8391 => true, + 8392 => true, + 8393 => true, + 8394 => true, + 8395 => true, + 8396 => true, + 8397 => true, + 8398 => true, + 8399 => true, + 8433 => true, + 8434 => true, + 8435 => true, + 8436 => true, + 8437 => true, + 8438 => true, + 8439 => true, + 8440 => true, + 8441 => true, + 8442 => true, + 8443 => true, + 8444 => true, + 8445 => true, + 8446 => true, + 8447 => true, + 8498 => true, + 8579 => true, + 8588 => true, + 8589 => true, + 8590 => true, + 8591 => true, + 9255 => true, + 9256 => true, + 9257 => true, + 9258 => true, + 9259 => true, + 9260 => true, + 9261 => true, + 9262 => true, + 9263 => true, + 9264 => true, + 9265 => true, + 9266 => true, + 9267 => true, + 9268 => true, + 9269 => true, + 9270 => true, + 9271 => true, + 9272 => true, + 9273 => true, + 9274 => true, + 9275 => true, + 9276 => true, + 9277 => true, + 9278 => true, + 9279 => true, + 9291 => true, + 9292 => true, + 9293 => true, + 9294 => true, + 9295 => true, + 9296 => true, + 9297 => true, + 9298 => true, + 9299 => true, + 9300 => true, + 9301 => true, + 9302 => true, + 9303 => true, + 9304 => true, + 9305 => true, + 9306 => true, + 9307 => true, + 9308 => true, + 9309 => true, + 9310 => true, + 9311 => true, + 9352 => true, + 9353 => true, + 9354 => true, + 9355 => true, + 9356 => true, + 9357 => true, + 9358 => true, + 9359 => true, + 9360 => true, + 9361 => true, + 9362 => true, + 9363 => true, + 9364 => true, + 9365 => true, + 9366 => true, + 9367 => true, + 9368 => true, + 9369 => true, + 9370 => true, + 9371 => true, + 11124 => true, + 11125 => true, + 11158 => true, + 11311 => true, + 11359 => true, + 11508 => true, + 11509 => true, + 11510 => true, + 11511 => true, + 11512 => true, + 11558 => true, + 11560 => true, + 11561 => true, + 11562 => true, + 11563 => true, + 11564 => true, + 11566 => true, + 11567 => true, + 11624 => true, + 11625 => true, + 11626 => true, + 11627 => true, + 11628 => true, + 11629 => true, + 11630 => true, + 11633 => true, + 11634 => true, + 11635 => true, + 11636 => true, + 11637 => true, + 11638 => true, + 11639 => true, + 11640 => true, + 11641 => true, + 11642 => true, + 11643 => true, + 11644 => true, + 11645 => true, + 11646 => true, + 11671 => true, + 11672 => true, + 11673 => true, + 11674 => true, + 11675 => true, + 11676 => true, + 11677 => true, + 11678 => true, + 11679 => true, + 11687 => true, + 11695 => true, + 11703 => true, + 11711 => true, + 11719 => true, + 11727 => true, + 11735 => true, + 11743 => true, + 11930 => true, + 12020 => true, + 12021 => true, + 12022 => true, + 12023 => true, + 12024 => true, + 12025 => true, + 12026 => true, + 12027 => true, + 12028 => true, + 12029 => true, + 12030 => true, + 12031 => true, + 12246 => true, + 12247 => true, + 12248 => true, + 12249 => true, + 12250 => true, + 12251 => true, + 12252 => true, + 12253 => true, + 12254 => true, + 12255 => true, + 12256 => true, + 12257 => true, + 12258 => true, + 12259 => true, + 12260 => true, + 12261 => true, + 12262 => true, + 12263 => true, + 12264 => true, + 12265 => true, + 12266 => true, + 12267 => true, + 12268 => true, + 12269 => true, + 12270 => true, + 12271 => true, + 12272 => true, + 12273 => true, + 12274 => true, + 12275 => true, + 12276 => true, + 12277 => true, + 12278 => true, + 12279 => true, + 12280 => true, + 12281 => true, + 12282 => true, + 12283 => true, + 12284 => true, + 12285 => true, + 12286 => true, + 12287 => true, + 12352 => true, + 12439 => true, + 12440 => true, + 12544 => true, + 12545 => true, + 12546 => true, + 12547 => true, + 12548 => true, + 12592 => true, + 12644 => true, + 12687 => true, + 12772 => true, + 12773 => true, + 12774 => true, + 12775 => true, + 12776 => true, + 12777 => true, + 12778 => true, + 12779 => true, + 12780 => true, + 12781 => true, + 12782 => true, + 12783 => true, + 12831 => true, + 13250 => true, + 13255 => true, + 13272 => true, + 40957 => true, + 40958 => true, + 40959 => true, + 42125 => true, + 42126 => true, + 42127 => true, + 42183 => true, + 42184 => true, + 42185 => true, + 42186 => true, + 42187 => true, + 42188 => true, + 42189 => true, + 42190 => true, + 42191 => true, + 42540 => true, + 42541 => true, + 42542 => true, + 42543 => true, + 42544 => true, + 42545 => true, + 42546 => true, + 42547 => true, + 42548 => true, + 42549 => true, + 42550 => true, + 42551 => true, + 42552 => true, + 42553 => true, + 42554 => true, + 42555 => true, + 42556 => true, + 42557 => true, + 42558 => true, + 42559 => true, + 42744 => true, + 42745 => true, + 42746 => true, + 42747 => true, + 42748 => true, + 42749 => true, + 42750 => true, + 42751 => true, + 42944 => true, + 42945 => true, + 43053 => true, + 43054 => true, + 43055 => true, + 43066 => true, + 43067 => true, + 43068 => true, + 43069 => true, + 43070 => true, + 43071 => true, + 43128 => true, + 43129 => true, + 43130 => true, + 43131 => true, + 43132 => true, + 43133 => true, + 43134 => true, + 43135 => true, + 43206 => true, + 43207 => true, + 43208 => true, + 43209 => true, + 43210 => true, + 43211 => true, + 43212 => true, + 43213 => true, + 43226 => true, + 43227 => true, + 43228 => true, + 43229 => true, + 43230 => true, + 43231 => true, + 43348 => true, + 43349 => true, + 43350 => true, + 43351 => true, + 43352 => true, + 43353 => true, + 43354 => true, + 43355 => true, + 43356 => true, + 43357 => true, + 43358 => true, + 43389 => true, + 43390 => true, + 43391 => true, + 43470 => true, + 43482 => true, + 43483 => true, + 43484 => true, + 43485 => true, + 43519 => true, + 43575 => true, + 43576 => true, + 43577 => true, + 43578 => true, + 43579 => true, + 43580 => true, + 43581 => true, + 43582 => true, + 43583 => true, + 43598 => true, + 43599 => true, + 43610 => true, + 43611 => true, + 43715 => true, + 43716 => true, + 43717 => true, + 43718 => true, + 43719 => true, + 43720 => true, + 43721 => true, + 43722 => true, + 43723 => true, + 43724 => true, + 43725 => true, + 43726 => true, + 43727 => true, + 43728 => true, + 43729 => true, + 43730 => true, + 43731 => true, + 43732 => true, + 43733 => true, + 43734 => true, + 43735 => true, + 43736 => true, + 43737 => true, + 43738 => true, + 43767 => true, + 43768 => true, + 43769 => true, + 43770 => true, + 43771 => true, + 43772 => true, + 43773 => true, + 43774 => true, + 43775 => true, + 43776 => true, + 43783 => true, + 43784 => true, + 43791 => true, + 43792 => true, + 43799 => true, + 43800 => true, + 43801 => true, + 43802 => true, + 43803 => true, + 43804 => true, + 43805 => true, + 43806 => true, + 43807 => true, + 43815 => true, + 43823 => true, + 43884 => true, + 43885 => true, + 43886 => true, + 43887 => true, + 44014 => true, + 44015 => true, + 44026 => true, + 44027 => true, + 44028 => true, + 44029 => true, + 44030 => true, + 44031 => true, + 55204 => true, + 55205 => true, + 55206 => true, + 55207 => true, + 55208 => true, + 55209 => true, + 55210 => true, + 55211 => true, + 55212 => true, + 55213 => true, + 55214 => true, + 55215 => true, + 55239 => true, + 55240 => true, + 55241 => true, + 55242 => true, + 55292 => true, + 55293 => true, + 55294 => true, + 55295 => true, + 64110 => true, + 64111 => true, + 64263 => true, + 64264 => true, + 64265 => true, + 64266 => true, + 64267 => true, + 64268 => true, + 64269 => true, + 64270 => true, + 64271 => true, + 64272 => true, + 64273 => true, + 64274 => true, + 64280 => true, + 64281 => true, + 64282 => true, + 64283 => true, + 64284 => true, + 64311 => true, + 64317 => true, + 64319 => true, + 64322 => true, + 64325 => true, + 64450 => true, + 64451 => true, + 64452 => true, + 64453 => true, + 64454 => true, + 64455 => true, + 64456 => true, + 64457 => true, + 64458 => true, + 64459 => true, + 64460 => true, + 64461 => true, + 64462 => true, + 64463 => true, + 64464 => true, + 64465 => true, + 64466 => true, + 64832 => true, + 64833 => true, + 64834 => true, + 64835 => true, + 64836 => true, + 64837 => true, + 64838 => true, + 64839 => true, + 64840 => true, + 64841 => true, + 64842 => true, + 64843 => true, + 64844 => true, + 64845 => true, + 64846 => true, + 64847 => true, + 64912 => true, + 64913 => true, + 64968 => true, + 64969 => true, + 64970 => true, + 64971 => true, + 64972 => true, + 64973 => true, + 64974 => true, + 64975 => true, + 65022 => true, + 65023 => true, + 65042 => true, + 65049 => true, + 65050 => true, + 65051 => true, + 65052 => true, + 65053 => true, + 65054 => true, + 65055 => true, + 65072 => true, + 65106 => true, + 65107 => true, + 65127 => true, + 65132 => true, + 65133 => true, + 65134 => true, + 65135 => true, + 65141 => true, + 65277 => true, + 65278 => true, + 65280 => true, + 65440 => true, + 65471 => true, + 65472 => true, + 65473 => true, + 65480 => true, + 65481 => true, + 65488 => true, + 65489 => true, + 65496 => true, + 65497 => true, + 65501 => true, + 65502 => true, + 65503 => true, + 65511 => true, + 65519 => true, + 65520 => true, + 65521 => true, + 65522 => true, + 65523 => true, + 65524 => true, + 65525 => true, + 65526 => true, + 65527 => true, + 65528 => true, + 65529 => true, + 65530 => true, + 65531 => true, + 65532 => true, + 65533 => true, + 65534 => true, + 65535 => true, + 65548 => true, + 65575 => true, + 65595 => true, + 65598 => true, + 65614 => true, + 65615 => true, + 65787 => true, + 65788 => true, + 65789 => true, + 65790 => true, + 65791 => true, + 65795 => true, + 65796 => true, + 65797 => true, + 65798 => true, + 65844 => true, + 65845 => true, + 65846 => true, + 65935 => true, + 65949 => true, + 65950 => true, + 65951 => true, + 66205 => true, + 66206 => true, + 66207 => true, + 66257 => true, + 66258 => true, + 66259 => true, + 66260 => true, + 66261 => true, + 66262 => true, + 66263 => true, + 66264 => true, + 66265 => true, + 66266 => true, + 66267 => true, + 66268 => true, + 66269 => true, + 66270 => true, + 66271 => true, + 66300 => true, + 66301 => true, + 66302 => true, + 66303 => true, + 66340 => true, + 66341 => true, + 66342 => true, + 66343 => true, + 66344 => true, + 66345 => true, + 66346 => true, + 66347 => true, + 66348 => true, + 66379 => true, + 66380 => true, + 66381 => true, + 66382 => true, + 66383 => true, + 66427 => true, + 66428 => true, + 66429 => true, + 66430 => true, + 66431 => true, + 66462 => true, + 66500 => true, + 66501 => true, + 66502 => true, + 66503 => true, + 66718 => true, + 66719 => true, + 66730 => true, + 66731 => true, + 66732 => true, + 66733 => true, + 66734 => true, + 66735 => true, + 66772 => true, + 66773 => true, + 66774 => true, + 66775 => true, + 66812 => true, + 66813 => true, + 66814 => true, + 66815 => true, + 66856 => true, + 66857 => true, + 66858 => true, + 66859 => true, + 66860 => true, + 66861 => true, + 66862 => true, + 66863 => true, + 66916 => true, + 66917 => true, + 66918 => true, + 66919 => true, + 66920 => true, + 66921 => true, + 66922 => true, + 66923 => true, + 66924 => true, + 66925 => true, + 66926 => true, + 67383 => true, + 67384 => true, + 67385 => true, + 67386 => true, + 67387 => true, + 67388 => true, + 67389 => true, + 67390 => true, + 67391 => true, + 67414 => true, + 67415 => true, + 67416 => true, + 67417 => true, + 67418 => true, + 67419 => true, + 67420 => true, + 67421 => true, + 67422 => true, + 67423 => true, + 67590 => true, + 67591 => true, + 67593 => true, + 67638 => true, + 67641 => true, + 67642 => true, + 67643 => true, + 67645 => true, + 67646 => true, + 67670 => true, + 67743 => true, + 67744 => true, + 67745 => true, + 67746 => true, + 67747 => true, + 67748 => true, + 67749 => true, + 67750 => true, + 67827 => true, + 67830 => true, + 67831 => true, + 67832 => true, + 67833 => true, + 67834 => true, + 67868 => true, + 67869 => true, + 67870 => true, + 67898 => true, + 67899 => true, + 67900 => true, + 67901 => true, + 67902 => true, + 68024 => true, + 68025 => true, + 68026 => true, + 68027 => true, + 68048 => true, + 68049 => true, + 68100 => true, + 68103 => true, + 68104 => true, + 68105 => true, + 68106 => true, + 68107 => true, + 68116 => true, + 68120 => true, + 68150 => true, + 68151 => true, + 68155 => true, + 68156 => true, + 68157 => true, + 68158 => true, + 68169 => true, + 68170 => true, + 68171 => true, + 68172 => true, + 68173 => true, + 68174 => true, + 68175 => true, + 68185 => true, + 68186 => true, + 68187 => true, + 68188 => true, + 68189 => true, + 68190 => true, + 68191 => true, + 68327 => true, + 68328 => true, + 68329 => true, + 68330 => true, + 68343 => true, + 68344 => true, + 68345 => true, + 68346 => true, + 68347 => true, + 68348 => true, + 68349 => true, + 68350 => true, + 68351 => true, + 68406 => true, + 68407 => true, + 68408 => true, + 68438 => true, + 68439 => true, + 68467 => true, + 68468 => true, + 68469 => true, + 68470 => true, + 68471 => true, + 68498 => true, + 68499 => true, + 68500 => true, + 68501 => true, + 68502 => true, + 68503 => true, + 68504 => true, + 68509 => true, + 68510 => true, + 68511 => true, + 68512 => true, + 68513 => true, + 68514 => true, + 68515 => true, + 68516 => true, + 68517 => true, + 68518 => true, + 68519 => true, + 68520 => true, + 68787 => true, + 68788 => true, + 68789 => true, + 68790 => true, + 68791 => true, + 68792 => true, + 68793 => true, + 68794 => true, + 68795 => true, + 68796 => true, + 68797 => true, + 68798 => true, + 68799 => true, + 68851 => true, + 68852 => true, + 68853 => true, + 68854 => true, + 68855 => true, + 68856 => true, + 68857 => true, + 68904 => true, + 68905 => true, + 68906 => true, + 68907 => true, + 68908 => true, + 68909 => true, + 68910 => true, + 68911 => true, + 69247 => true, + 69290 => true, + 69294 => true, + 69295 => true, + 69416 => true, + 69417 => true, + 69418 => true, + 69419 => true, + 69420 => true, + 69421 => true, + 69422 => true, + 69423 => true, + 69580 => true, + 69581 => true, + 69582 => true, + 69583 => true, + 69584 => true, + 69585 => true, + 69586 => true, + 69587 => true, + 69588 => true, + 69589 => true, + 69590 => true, + 69591 => true, + 69592 => true, + 69593 => true, + 69594 => true, + 69595 => true, + 69596 => true, + 69597 => true, + 69598 => true, + 69599 => true, + 69623 => true, + 69624 => true, + 69625 => true, + 69626 => true, + 69627 => true, + 69628 => true, + 69629 => true, + 69630 => true, + 69631 => true, + 69710 => true, + 69711 => true, + 69712 => true, + 69713 => true, + 69744 => true, + 69745 => true, + 69746 => true, + 69747 => true, + 69748 => true, + 69749 => true, + 69750 => true, + 69751 => true, + 69752 => true, + 69753 => true, + 69754 => true, + 69755 => true, + 69756 => true, + 69757 => true, + 69758 => true, + 69821 => true, + 69826 => true, + 69827 => true, + 69828 => true, + 69829 => true, + 69830 => true, + 69831 => true, + 69832 => true, + 69833 => true, + 69834 => true, + 69835 => true, + 69836 => true, + 69837 => true, + 69838 => true, + 69839 => true, + 69865 => true, + 69866 => true, + 69867 => true, + 69868 => true, + 69869 => true, + 69870 => true, + 69871 => true, + 69882 => true, + 69883 => true, + 69884 => true, + 69885 => true, + 69886 => true, + 69887 => true, + 69941 => true, + 69960 => true, + 69961 => true, + 69962 => true, + 69963 => true, + 69964 => true, + 69965 => true, + 69966 => true, + 69967 => true, + 70007 => true, + 70008 => true, + 70009 => true, + 70010 => true, + 70011 => true, + 70012 => true, + 70013 => true, + 70014 => true, + 70015 => true, + 70112 => true, + 70133 => true, + 70134 => true, + 70135 => true, + 70136 => true, + 70137 => true, + 70138 => true, + 70139 => true, + 70140 => true, + 70141 => true, + 70142 => true, + 70143 => true, + 70162 => true, + 70279 => true, + 70281 => true, + 70286 => true, + 70302 => true, + 70314 => true, + 70315 => true, + 70316 => true, + 70317 => true, + 70318 => true, + 70319 => true, + 70379 => true, + 70380 => true, + 70381 => true, + 70382 => true, + 70383 => true, + 70394 => true, + 70395 => true, + 70396 => true, + 70397 => true, + 70398 => true, + 70399 => true, + 70404 => true, + 70413 => true, + 70414 => true, + 70417 => true, + 70418 => true, + 70441 => true, + 70449 => true, + 70452 => true, + 70458 => true, + 70469 => true, + 70470 => true, + 70473 => true, + 70474 => true, + 70478 => true, + 70479 => true, + 70481 => true, + 70482 => true, + 70483 => true, + 70484 => true, + 70485 => true, + 70486 => true, + 70488 => true, + 70489 => true, + 70490 => true, + 70491 => true, + 70492 => true, + 70500 => true, + 70501 => true, + 70509 => true, + 70510 => true, + 70511 => true, + 70748 => true, + 70754 => true, + 70755 => true, + 70756 => true, + 70757 => true, + 70758 => true, + 70759 => true, + 70760 => true, + 70761 => true, + 70762 => true, + 70763 => true, + 70764 => true, + 70765 => true, + 70766 => true, + 70767 => true, + 70768 => true, + 70769 => true, + 70770 => true, + 70771 => true, + 70772 => true, + 70773 => true, + 70774 => true, + 70775 => true, + 70776 => true, + 70777 => true, + 70778 => true, + 70779 => true, + 70780 => true, + 70781 => true, + 70782 => true, + 70783 => true, + 70856 => true, + 70857 => true, + 70858 => true, + 70859 => true, + 70860 => true, + 70861 => true, + 70862 => true, + 70863 => true, + 71094 => true, + 71095 => true, + 71237 => true, + 71238 => true, + 71239 => true, + 71240 => true, + 71241 => true, + 71242 => true, + 71243 => true, + 71244 => true, + 71245 => true, + 71246 => true, + 71247 => true, + 71258 => true, + 71259 => true, + 71260 => true, + 71261 => true, + 71262 => true, + 71263 => true, + 71277 => true, + 71278 => true, + 71279 => true, + 71280 => true, + 71281 => true, + 71282 => true, + 71283 => true, + 71284 => true, + 71285 => true, + 71286 => true, + 71287 => true, + 71288 => true, + 71289 => true, + 71290 => true, + 71291 => true, + 71292 => true, + 71293 => true, + 71294 => true, + 71295 => true, + 71353 => true, + 71354 => true, + 71355 => true, + 71356 => true, + 71357 => true, + 71358 => true, + 71359 => true, + 71451 => true, + 71452 => true, + 71468 => true, + 71469 => true, + 71470 => true, + 71471 => true, + 71923 => true, + 71924 => true, + 71925 => true, + 71926 => true, + 71927 => true, + 71928 => true, + 71929 => true, + 71930 => true, + 71931 => true, + 71932 => true, + 71933 => true, + 71934 => true, + 71943 => true, + 71944 => true, + 71946 => true, + 71947 => true, + 71956 => true, + 71959 => true, + 71990 => true, + 71993 => true, + 71994 => true, + 72007 => true, + 72008 => true, + 72009 => true, + 72010 => true, + 72011 => true, + 72012 => true, + 72013 => true, + 72014 => true, + 72015 => true, + 72104 => true, + 72105 => true, + 72152 => true, + 72153 => true, + 72165 => true, + 72166 => true, + 72167 => true, + 72168 => true, + 72169 => true, + 72170 => true, + 72171 => true, + 72172 => true, + 72173 => true, + 72174 => true, + 72175 => true, + 72176 => true, + 72177 => true, + 72178 => true, + 72179 => true, + 72180 => true, + 72181 => true, + 72182 => true, + 72183 => true, + 72184 => true, + 72185 => true, + 72186 => true, + 72187 => true, + 72188 => true, + 72189 => true, + 72190 => true, + 72191 => true, + 72264 => true, + 72265 => true, + 72266 => true, + 72267 => true, + 72268 => true, + 72269 => true, + 72270 => true, + 72271 => true, + 72355 => true, + 72356 => true, + 72357 => true, + 72358 => true, + 72359 => true, + 72360 => true, + 72361 => true, + 72362 => true, + 72363 => true, + 72364 => true, + 72365 => true, + 72366 => true, + 72367 => true, + 72368 => true, + 72369 => true, + 72370 => true, + 72371 => true, + 72372 => true, + 72373 => true, + 72374 => true, + 72375 => true, + 72376 => true, + 72377 => true, + 72378 => true, + 72379 => true, + 72380 => true, + 72381 => true, + 72382 => true, + 72383 => true, + 72713 => true, + 72759 => true, + 72774 => true, + 72775 => true, + 72776 => true, + 72777 => true, + 72778 => true, + 72779 => true, + 72780 => true, + 72781 => true, + 72782 => true, + 72783 => true, + 72813 => true, + 72814 => true, + 72815 => true, + 72848 => true, + 72849 => true, + 72872 => true, + 72967 => true, + 72970 => true, + 73015 => true, + 73016 => true, + 73017 => true, + 73019 => true, + 73022 => true, + 73032 => true, + 73033 => true, + 73034 => true, + 73035 => true, + 73036 => true, + 73037 => true, + 73038 => true, + 73039 => true, + 73050 => true, + 73051 => true, + 73052 => true, + 73053 => true, + 73054 => true, + 73055 => true, + 73062 => true, + 73065 => true, + 73103 => true, + 73106 => true, + 73113 => true, + 73114 => true, + 73115 => true, + 73116 => true, + 73117 => true, + 73118 => true, + 73119 => true, + 73649 => true, + 73650 => true, + 73651 => true, + 73652 => true, + 73653 => true, + 73654 => true, + 73655 => true, + 73656 => true, + 73657 => true, + 73658 => true, + 73659 => true, + 73660 => true, + 73661 => true, + 73662 => true, + 73663 => true, + 73714 => true, + 73715 => true, + 73716 => true, + 73717 => true, + 73718 => true, + 73719 => true, + 73720 => true, + 73721 => true, + 73722 => true, + 73723 => true, + 73724 => true, + 73725 => true, + 73726 => true, + 74863 => true, + 74869 => true, + 74870 => true, + 74871 => true, + 74872 => true, + 74873 => true, + 74874 => true, + 74875 => true, + 74876 => true, + 74877 => true, + 74878 => true, + 74879 => true, + 78895 => true, + 78896 => true, + 78897 => true, + 78898 => true, + 78899 => true, + 78900 => true, + 78901 => true, + 78902 => true, + 78903 => true, + 78904 => true, + 92729 => true, + 92730 => true, + 92731 => true, + 92732 => true, + 92733 => true, + 92734 => true, + 92735 => true, + 92767 => true, + 92778 => true, + 92779 => true, + 92780 => true, + 92781 => true, + 92910 => true, + 92911 => true, + 92918 => true, + 92919 => true, + 92920 => true, + 92921 => true, + 92922 => true, + 92923 => true, + 92924 => true, + 92925 => true, + 92926 => true, + 92927 => true, + 92998 => true, + 92999 => true, + 93000 => true, + 93001 => true, + 93002 => true, + 93003 => true, + 93004 => true, + 93005 => true, + 93006 => true, + 93007 => true, + 93018 => true, + 93026 => true, + 93048 => true, + 93049 => true, + 93050 => true, + 93051 => true, + 93052 => true, + 94027 => true, + 94028 => true, + 94029 => true, + 94030 => true, + 94088 => true, + 94089 => true, + 94090 => true, + 94091 => true, + 94092 => true, + 94093 => true, + 94094 => true, + 94181 => true, + 94182 => true, + 94183 => true, + 94184 => true, + 94185 => true, + 94186 => true, + 94187 => true, + 94188 => true, + 94189 => true, + 94190 => true, + 94191 => true, + 94194 => true, + 94195 => true, + 94196 => true, + 94197 => true, + 94198 => true, + 94199 => true, + 94200 => true, + 94201 => true, + 94202 => true, + 94203 => true, + 94204 => true, + 94205 => true, + 94206 => true, + 94207 => true, + 100344 => true, + 100345 => true, + 100346 => true, + 100347 => true, + 100348 => true, + 100349 => true, + 100350 => true, + 100351 => true, + 110931 => true, + 110932 => true, + 110933 => true, + 110934 => true, + 110935 => true, + 110936 => true, + 110937 => true, + 110938 => true, + 110939 => true, + 110940 => true, + 110941 => true, + 110942 => true, + 110943 => true, + 110944 => true, + 110945 => true, + 110946 => true, + 110947 => true, + 110952 => true, + 110953 => true, + 110954 => true, + 110955 => true, + 110956 => true, + 110957 => true, + 110958 => true, + 110959 => true, + 113771 => true, + 113772 => true, + 113773 => true, + 113774 => true, + 113775 => true, + 113789 => true, + 113790 => true, + 113791 => true, + 113801 => true, + 113802 => true, + 113803 => true, + 113804 => true, + 113805 => true, + 113806 => true, + 113807 => true, + 113818 => true, + 113819 => true, + 119030 => true, + 119031 => true, + 119032 => true, + 119033 => true, + 119034 => true, + 119035 => true, + 119036 => true, + 119037 => true, + 119038 => true, + 119039 => true, + 119079 => true, + 119080 => true, + 119155 => true, + 119156 => true, + 119157 => true, + 119158 => true, + 119159 => true, + 119160 => true, + 119161 => true, + 119162 => true, + 119273 => true, + 119274 => true, + 119275 => true, + 119276 => true, + 119277 => true, + 119278 => true, + 119279 => true, + 119280 => true, + 119281 => true, + 119282 => true, + 119283 => true, + 119284 => true, + 119285 => true, + 119286 => true, + 119287 => true, + 119288 => true, + 119289 => true, + 119290 => true, + 119291 => true, + 119292 => true, + 119293 => true, + 119294 => true, + 119295 => true, + 119540 => true, + 119541 => true, + 119542 => true, + 119543 => true, + 119544 => true, + 119545 => true, + 119546 => true, + 119547 => true, + 119548 => true, + 119549 => true, + 119550 => true, + 119551 => true, + 119639 => true, + 119640 => true, + 119641 => true, + 119642 => true, + 119643 => true, + 119644 => true, + 119645 => true, + 119646 => true, + 119647 => true, + 119893 => true, + 119965 => true, + 119968 => true, + 119969 => true, + 119971 => true, + 119972 => true, + 119975 => true, + 119976 => true, + 119981 => true, + 119994 => true, + 119996 => true, + 120004 => true, + 120070 => true, + 120075 => true, + 120076 => true, + 120085 => true, + 120093 => true, + 120122 => true, + 120127 => true, + 120133 => true, + 120135 => true, + 120136 => true, + 120137 => true, + 120145 => true, + 120486 => true, + 120487 => true, + 120780 => true, + 120781 => true, + 121484 => true, + 121485 => true, + 121486 => true, + 121487 => true, + 121488 => true, + 121489 => true, + 121490 => true, + 121491 => true, + 121492 => true, + 121493 => true, + 121494 => true, + 121495 => true, + 121496 => true, + 121497 => true, + 121498 => true, + 121504 => true, + 122887 => true, + 122905 => true, + 122906 => true, + 122914 => true, + 122917 => true, + 123181 => true, + 123182 => true, + 123183 => true, + 123198 => true, + 123199 => true, + 123210 => true, + 123211 => true, + 123212 => true, + 123213 => true, + 123642 => true, + 123643 => true, + 123644 => true, + 123645 => true, + 123646 => true, + 125125 => true, + 125126 => true, + 125260 => true, + 125261 => true, + 125262 => true, + 125263 => true, + 125274 => true, + 125275 => true, + 125276 => true, + 125277 => true, + 126468 => true, + 126496 => true, + 126499 => true, + 126501 => true, + 126502 => true, + 126504 => true, + 126515 => true, + 126520 => true, + 126522 => true, + 126524 => true, + 126525 => true, + 126526 => true, + 126527 => true, + 126528 => true, + 126529 => true, + 126531 => true, + 126532 => true, + 126533 => true, + 126534 => true, + 126536 => true, + 126538 => true, + 126540 => true, + 126544 => true, + 126547 => true, + 126549 => true, + 126550 => true, + 126552 => true, + 126554 => true, + 126556 => true, + 126558 => true, + 126560 => true, + 126563 => true, + 126565 => true, + 126566 => true, + 126571 => true, + 126579 => true, + 126584 => true, + 126589 => true, + 126591 => true, + 126602 => true, + 126620 => true, + 126621 => true, + 126622 => true, + 126623 => true, + 126624 => true, + 126628 => true, + 126634 => true, + 127020 => true, + 127021 => true, + 127022 => true, + 127023 => true, + 127124 => true, + 127125 => true, + 127126 => true, + 127127 => true, + 127128 => true, + 127129 => true, + 127130 => true, + 127131 => true, + 127132 => true, + 127133 => true, + 127134 => true, + 127135 => true, + 127151 => true, + 127152 => true, + 127168 => true, + 127184 => true, + 127222 => true, + 127223 => true, + 127224 => true, + 127225 => true, + 127226 => true, + 127227 => true, + 127228 => true, + 127229 => true, + 127230 => true, + 127231 => true, + 127232 => true, + 127491 => true, + 127492 => true, + 127493 => true, + 127494 => true, + 127495 => true, + 127496 => true, + 127497 => true, + 127498 => true, + 127499 => true, + 127500 => true, + 127501 => true, + 127502 => true, + 127503 => true, + 127548 => true, + 127549 => true, + 127550 => true, + 127551 => true, + 127561 => true, + 127562 => true, + 127563 => true, + 127564 => true, + 127565 => true, + 127566 => true, + 127567 => true, + 127570 => true, + 127571 => true, + 127572 => true, + 127573 => true, + 127574 => true, + 127575 => true, + 127576 => true, + 127577 => true, + 127578 => true, + 127579 => true, + 127580 => true, + 127581 => true, + 127582 => true, + 127583 => true, + 128728 => true, + 128729 => true, + 128730 => true, + 128731 => true, + 128732 => true, + 128733 => true, + 128734 => true, + 128735 => true, + 128749 => true, + 128750 => true, + 128751 => true, + 128765 => true, + 128766 => true, + 128767 => true, + 128884 => true, + 128885 => true, + 128886 => true, + 128887 => true, + 128888 => true, + 128889 => true, + 128890 => true, + 128891 => true, + 128892 => true, + 128893 => true, + 128894 => true, + 128895 => true, + 128985 => true, + 128986 => true, + 128987 => true, + 128988 => true, + 128989 => true, + 128990 => true, + 128991 => true, + 129004 => true, + 129005 => true, + 129006 => true, + 129007 => true, + 129008 => true, + 129009 => true, + 129010 => true, + 129011 => true, + 129012 => true, + 129013 => true, + 129014 => true, + 129015 => true, + 129016 => true, + 129017 => true, + 129018 => true, + 129019 => true, + 129020 => true, + 129021 => true, + 129022 => true, + 129023 => true, + 129036 => true, + 129037 => true, + 129038 => true, + 129039 => true, + 129096 => true, + 129097 => true, + 129098 => true, + 129099 => true, + 129100 => true, + 129101 => true, + 129102 => true, + 129103 => true, + 129114 => true, + 129115 => true, + 129116 => true, + 129117 => true, + 129118 => true, + 129119 => true, + 129160 => true, + 129161 => true, + 129162 => true, + 129163 => true, + 129164 => true, + 129165 => true, + 129166 => true, + 129167 => true, + 129198 => true, + 129199 => true, + 129401 => true, + 129484 => true, + 129620 => true, + 129621 => true, + 129622 => true, + 129623 => true, + 129624 => true, + 129625 => true, + 129626 => true, + 129627 => true, + 129628 => true, + 129629 => true, + 129630 => true, + 129631 => true, + 129646 => true, + 129647 => true, + 129653 => true, + 129654 => true, + 129655 => true, + 129659 => true, + 129660 => true, + 129661 => true, + 129662 => true, + 129663 => true, + 129671 => true, + 129672 => true, + 129673 => true, + 129674 => true, + 129675 => true, + 129676 => true, + 129677 => true, + 129678 => true, + 129679 => true, + 129705 => true, + 129706 => true, + 129707 => true, + 129708 => true, + 129709 => true, + 129710 => true, + 129711 => true, + 129719 => true, + 129720 => true, + 129721 => true, + 129722 => true, + 129723 => true, + 129724 => true, + 129725 => true, + 129726 => true, + 129727 => true, + 129731 => true, + 129732 => true, + 129733 => true, + 129734 => true, + 129735 => true, + 129736 => true, + 129737 => true, + 129738 => true, + 129739 => true, + 129740 => true, + 129741 => true, + 129742 => true, + 129743 => true, + 129939 => true, + 131070 => true, + 131071 => true, + 177973 => true, + 177974 => true, + 177975 => true, + 177976 => true, + 177977 => true, + 177978 => true, + 177979 => true, + 177980 => true, + 177981 => true, + 177982 => true, + 177983 => true, + 178206 => true, + 178207 => true, + 183970 => true, + 183971 => true, + 183972 => true, + 183973 => true, + 183974 => true, + 183975 => true, + 183976 => true, + 183977 => true, + 183978 => true, + 183979 => true, + 183980 => true, + 183981 => true, + 183982 => true, + 183983 => true, + 194664 => true, + 194676 => true, + 194847 => true, + 194911 => true, + 195007 => true, + 196606 => true, + 196607 => true, + 262142 => true, + 262143 => true, + 327678 => true, + 327679 => true, + 393214 => true, + 393215 => true, + 458750 => true, + 458751 => true, + 524286 => true, + 524287 => true, + 589822 => true, + 589823 => true, + 655358 => true, + 655359 => true, + 720894 => true, + 720895 => true, + 786430 => true, + 786431 => true, + 851966 => true, + 851967 => true, + 917502 => true, + 917503 => true, + 917504 => true, + 917505 => true, + 917506 => true, + 917507 => true, + 917508 => true, + 917509 => true, + 917510 => true, + 917511 => true, + 917512 => true, + 917513 => true, + 917514 => true, + 917515 => true, + 917516 => true, + 917517 => true, + 917518 => true, + 917519 => true, + 917520 => true, + 917521 => true, + 917522 => true, + 917523 => true, + 917524 => true, + 917525 => true, + 917526 => true, + 917527 => true, + 917528 => true, + 917529 => true, + 917530 => true, + 917531 => true, + 917532 => true, + 917533 => true, + 917534 => true, + 917535 => true, + 983038 => true, + 983039 => true, + 1048574 => true, + 1048575 => true, + 1114110 => true, + 1114111 => true, +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed_STD3_mapped.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed_STD3_mapped.php new file mode 100644 index 0000000..54f21cc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed_STD3_mapped.php @@ -0,0 +1,308 @@ + ' ', + 168 => ' ̈', + 175 => ' ̄', + 180 => ' ́', + 184 => ' ̧', + 728 => ' ̆', + 729 => ' ̇', + 730 => ' ̊', + 731 => ' ̨', + 732 => ' ̃', + 733 => ' ̋', + 890 => ' ι', + 894 => ';', + 900 => ' ́', + 901 => ' ̈́', + 8125 => ' ̓', + 8127 => ' ̓', + 8128 => ' ͂', + 8129 => ' ̈͂', + 8141 => ' ̓̀', + 8142 => ' ̓́', + 8143 => ' ̓͂', + 8157 => ' ̔̀', + 8158 => ' ̔́', + 8159 => ' ̔͂', + 8173 => ' ̈̀', + 8174 => ' ̈́', + 8175 => '`', + 8189 => ' ́', + 8190 => ' ̔', + 8192 => ' ', + 8193 => ' ', + 8194 => ' ', + 8195 => ' ', + 8196 => ' ', + 8197 => ' ', + 8198 => ' ', + 8199 => ' ', + 8200 => ' ', + 8201 => ' ', + 8202 => ' ', + 8215 => ' ̳', + 8239 => ' ', + 8252 => '!!', + 8254 => ' ̅', + 8263 => '??', + 8264 => '?!', + 8265 => '!?', + 8287 => ' ', + 8314 => '+', + 8316 => '=', + 8317 => '(', + 8318 => ')', + 8330 => '+', + 8332 => '=', + 8333 => '(', + 8334 => ')', + 8448 => 'a/c', + 8449 => 'a/s', + 8453 => 'c/o', + 8454 => 'c/u', + 9332 => '(1)', + 9333 => '(2)', + 9334 => '(3)', + 9335 => '(4)', + 9336 => '(5)', + 9337 => '(6)', + 9338 => '(7)', + 9339 => '(8)', + 9340 => '(9)', + 9341 => '(10)', + 9342 => '(11)', + 9343 => '(12)', + 9344 => '(13)', + 9345 => '(14)', + 9346 => '(15)', + 9347 => '(16)', + 9348 => '(17)', + 9349 => '(18)', + 9350 => '(19)', + 9351 => '(20)', + 9372 => '(a)', + 9373 => '(b)', + 9374 => '(c)', + 9375 => '(d)', + 9376 => '(e)', + 9377 => '(f)', + 9378 => '(g)', + 9379 => '(h)', + 9380 => '(i)', + 9381 => '(j)', + 9382 => '(k)', + 9383 => '(l)', + 9384 => '(m)', + 9385 => '(n)', + 9386 => '(o)', + 9387 => '(p)', + 9388 => '(q)', + 9389 => '(r)', + 9390 => '(s)', + 9391 => '(t)', + 9392 => '(u)', + 9393 => '(v)', + 9394 => '(w)', + 9395 => '(x)', + 9396 => '(y)', + 9397 => '(z)', + 10868 => '::=', + 10869 => '==', + 10870 => '===', + 12288 => ' ', + 12443 => ' ゙', + 12444 => ' ゚', + 12800 => '(ᄀ)', + 12801 => '(ᄂ)', + 12802 => '(ᄃ)', + 12803 => '(ᄅ)', + 12804 => '(ᄆ)', + 12805 => '(ᄇ)', + 12806 => '(ᄉ)', + 12807 => '(ᄋ)', + 12808 => '(ᄌ)', + 12809 => '(ᄎ)', + 12810 => '(ᄏ)', + 12811 => '(ᄐ)', + 12812 => '(ᄑ)', + 12813 => '(ᄒ)', + 12814 => '(가)', + 12815 => '(나)', + 12816 => '(다)', + 12817 => '(라)', + 12818 => '(마)', + 12819 => '(바)', + 12820 => '(사)', + 12821 => '(아)', + 12822 => '(자)', + 12823 => '(차)', + 12824 => '(카)', + 12825 => '(타)', + 12826 => '(파)', + 12827 => '(하)', + 12828 => '(주)', + 12829 => '(오전)', + 12830 => '(오후)', + 12832 => '(一)', + 12833 => '(二)', + 12834 => '(三)', + 12835 => '(四)', + 12836 => '(五)', + 12837 => '(六)', + 12838 => '(七)', + 12839 => '(八)', + 12840 => '(九)', + 12841 => '(十)', + 12842 => '(月)', + 12843 => '(火)', + 12844 => '(水)', + 12845 => '(木)', + 12846 => '(金)', + 12847 => '(土)', + 12848 => '(日)', + 12849 => '(株)', + 12850 => '(有)', + 12851 => '(社)', + 12852 => '(名)', + 12853 => '(特)', + 12854 => '(財)', + 12855 => '(祝)', + 12856 => '(労)', + 12857 => '(代)', + 12858 => '(呼)', + 12859 => '(学)', + 12860 => '(監)', + 12861 => '(企)', + 12862 => '(資)', + 12863 => '(協)', + 12864 => '(祭)', + 12865 => '(休)', + 12866 => '(自)', + 12867 => '(至)', + 64297 => '+', + 64606 => ' ٌّ', + 64607 => ' ٍّ', + 64608 => ' َّ', + 64609 => ' ُّ', + 64610 => ' ِّ', + 64611 => ' ّٰ', + 65018 => 'صلى الله عليه وسلم', + 65019 => 'جل جلاله', + 65040 => ',', + 65043 => ':', + 65044 => ';', + 65045 => '!', + 65046 => '?', + 65075 => '_', + 65076 => '_', + 65077 => '(', + 65078 => ')', + 65079 => '{', + 65080 => '}', + 65095 => '[', + 65096 => ']', + 65097 => ' ̅', + 65098 => ' ̅', + 65099 => ' ̅', + 65100 => ' ̅', + 65101 => '_', + 65102 => '_', + 65103 => '_', + 65104 => ',', + 65108 => ';', + 65109 => ':', + 65110 => '?', + 65111 => '!', + 65113 => '(', + 65114 => ')', + 65115 => '{', + 65116 => '}', + 65119 => '#', + 65120 => '&', + 65121 => '*', + 65122 => '+', + 65124 => '<', + 65125 => '>', + 65126 => '=', + 65128 => '\\', + 65129 => '$', + 65130 => '%', + 65131 => '@', + 65136 => ' ً', + 65138 => ' ٌ', + 65140 => ' ٍ', + 65142 => ' َ', + 65144 => ' ُ', + 65146 => ' ِ', + 65148 => ' ّ', + 65150 => ' ْ', + 65281 => '!', + 65282 => '"', + 65283 => '#', + 65284 => '$', + 65285 => '%', + 65286 => '&', + 65287 => '\'', + 65288 => '(', + 65289 => ')', + 65290 => '*', + 65291 => '+', + 65292 => ',', + 65295 => '/', + 65306 => ':', + 65307 => ';', + 65308 => '<', + 65309 => '=', + 65310 => '>', + 65311 => '?', + 65312 => '@', + 65339 => '[', + 65340 => '\\', + 65341 => ']', + 65342 => '^', + 65343 => '_', + 65344 => '`', + 65371 => '{', + 65372 => '|', + 65373 => '}', + 65374 => '~', + 65507 => ' ̄', + 127233 => '0,', + 127234 => '1,', + 127235 => '2,', + 127236 => '3,', + 127237 => '4,', + 127238 => '5,', + 127239 => '6,', + 127240 => '7,', + 127241 => '8,', + 127242 => '9,', + 127248 => '(a)', + 127249 => '(b)', + 127250 => '(c)', + 127251 => '(d)', + 127252 => '(e)', + 127253 => '(f)', + 127254 => '(g)', + 127255 => '(h)', + 127256 => '(i)', + 127257 => '(j)', + 127258 => '(k)', + 127259 => '(l)', + 127260 => '(m)', + 127261 => '(n)', + 127262 => '(o)', + 127263 => '(p)', + 127264 => '(q)', + 127265 => '(r)', + 127266 => '(s)', + 127267 => '(t)', + 127268 => '(u)', + 127269 => '(v)', + 127270 => '(w)', + 127271 => '(x)', + 127272 => '(y)', + 127273 => '(z)', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed_STD3_valid.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed_STD3_valid.php new file mode 100644 index 0000000..223396e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/disallowed_STD3_valid.php @@ -0,0 +1,71 @@ + true, + 1 => true, + 2 => true, + 3 => true, + 4 => true, + 5 => true, + 6 => true, + 7 => true, + 8 => true, + 9 => true, + 10 => true, + 11 => true, + 12 => true, + 13 => true, + 14 => true, + 15 => true, + 16 => true, + 17 => true, + 18 => true, + 19 => true, + 20 => true, + 21 => true, + 22 => true, + 23 => true, + 24 => true, + 25 => true, + 26 => true, + 27 => true, + 28 => true, + 29 => true, + 30 => true, + 31 => true, + 32 => true, + 33 => true, + 34 => true, + 35 => true, + 36 => true, + 37 => true, + 38 => true, + 39 => true, + 40 => true, + 41 => true, + 42 => true, + 43 => true, + 44 => true, + 47 => true, + 58 => true, + 59 => true, + 60 => true, + 61 => true, + 62 => true, + 63 => true, + 64 => true, + 91 => true, + 92 => true, + 93 => true, + 94 => true, + 95 => true, + 96 => true, + 123 => true, + 124 => true, + 125 => true, + 126 => true, + 127 => true, + 8800 => true, + 8814 => true, + 8815 => true, +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/ignored.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/ignored.php new file mode 100644 index 0000000..b377844 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/ignored.php @@ -0,0 +1,273 @@ + true, + 847 => true, + 6155 => true, + 6156 => true, + 6157 => true, + 8203 => true, + 8288 => true, + 8292 => true, + 65024 => true, + 65025 => true, + 65026 => true, + 65027 => true, + 65028 => true, + 65029 => true, + 65030 => true, + 65031 => true, + 65032 => true, + 65033 => true, + 65034 => true, + 65035 => true, + 65036 => true, + 65037 => true, + 65038 => true, + 65039 => true, + 65279 => true, + 113824 => true, + 113825 => true, + 113826 => true, + 113827 => true, + 917760 => true, + 917761 => true, + 917762 => true, + 917763 => true, + 917764 => true, + 917765 => true, + 917766 => true, + 917767 => true, + 917768 => true, + 917769 => true, + 917770 => true, + 917771 => true, + 917772 => true, + 917773 => true, + 917774 => true, + 917775 => true, + 917776 => true, + 917777 => true, + 917778 => true, + 917779 => true, + 917780 => true, + 917781 => true, + 917782 => true, + 917783 => true, + 917784 => true, + 917785 => true, + 917786 => true, + 917787 => true, + 917788 => true, + 917789 => true, + 917790 => true, + 917791 => true, + 917792 => true, + 917793 => true, + 917794 => true, + 917795 => true, + 917796 => true, + 917797 => true, + 917798 => true, + 917799 => true, + 917800 => true, + 917801 => true, + 917802 => true, + 917803 => true, + 917804 => true, + 917805 => true, + 917806 => true, + 917807 => true, + 917808 => true, + 917809 => true, + 917810 => true, + 917811 => true, + 917812 => true, + 917813 => true, + 917814 => true, + 917815 => true, + 917816 => true, + 917817 => true, + 917818 => true, + 917819 => true, + 917820 => true, + 917821 => true, + 917822 => true, + 917823 => true, + 917824 => true, + 917825 => true, + 917826 => true, + 917827 => true, + 917828 => true, + 917829 => true, + 917830 => true, + 917831 => true, + 917832 => true, + 917833 => true, + 917834 => true, + 917835 => true, + 917836 => true, + 917837 => true, + 917838 => true, + 917839 => true, + 917840 => true, + 917841 => true, + 917842 => true, + 917843 => true, + 917844 => true, + 917845 => true, + 917846 => true, + 917847 => true, + 917848 => true, + 917849 => true, + 917850 => true, + 917851 => true, + 917852 => true, + 917853 => true, + 917854 => true, + 917855 => true, + 917856 => true, + 917857 => true, + 917858 => true, + 917859 => true, + 917860 => true, + 917861 => true, + 917862 => true, + 917863 => true, + 917864 => true, + 917865 => true, + 917866 => true, + 917867 => true, + 917868 => true, + 917869 => true, + 917870 => true, + 917871 => true, + 917872 => true, + 917873 => true, + 917874 => true, + 917875 => true, + 917876 => true, + 917877 => true, + 917878 => true, + 917879 => true, + 917880 => true, + 917881 => true, + 917882 => true, + 917883 => true, + 917884 => true, + 917885 => true, + 917886 => true, + 917887 => true, + 917888 => true, + 917889 => true, + 917890 => true, + 917891 => true, + 917892 => true, + 917893 => true, + 917894 => true, + 917895 => true, + 917896 => true, + 917897 => true, + 917898 => true, + 917899 => true, + 917900 => true, + 917901 => true, + 917902 => true, + 917903 => true, + 917904 => true, + 917905 => true, + 917906 => true, + 917907 => true, + 917908 => true, + 917909 => true, + 917910 => true, + 917911 => true, + 917912 => true, + 917913 => true, + 917914 => true, + 917915 => true, + 917916 => true, + 917917 => true, + 917918 => true, + 917919 => true, + 917920 => true, + 917921 => true, + 917922 => true, + 917923 => true, + 917924 => true, + 917925 => true, + 917926 => true, + 917927 => true, + 917928 => true, + 917929 => true, + 917930 => true, + 917931 => true, + 917932 => true, + 917933 => true, + 917934 => true, + 917935 => true, + 917936 => true, + 917937 => true, + 917938 => true, + 917939 => true, + 917940 => true, + 917941 => true, + 917942 => true, + 917943 => true, + 917944 => true, + 917945 => true, + 917946 => true, + 917947 => true, + 917948 => true, + 917949 => true, + 917950 => true, + 917951 => true, + 917952 => true, + 917953 => true, + 917954 => true, + 917955 => true, + 917956 => true, + 917957 => true, + 917958 => true, + 917959 => true, + 917960 => true, + 917961 => true, + 917962 => true, + 917963 => true, + 917964 => true, + 917965 => true, + 917966 => true, + 917967 => true, + 917968 => true, + 917969 => true, + 917970 => true, + 917971 => true, + 917972 => true, + 917973 => true, + 917974 => true, + 917975 => true, + 917976 => true, + 917977 => true, + 917978 => true, + 917979 => true, + 917980 => true, + 917981 => true, + 917982 => true, + 917983 => true, + 917984 => true, + 917985 => true, + 917986 => true, + 917987 => true, + 917988 => true, + 917989 => true, + 917990 => true, + 917991 => true, + 917992 => true, + 917993 => true, + 917994 => true, + 917995 => true, + 917996 => true, + 917997 => true, + 917998 => true, + 917999 => true, +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/mapped.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/mapped.php new file mode 100644 index 0000000..9b85fe9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/mapped.php @@ -0,0 +1,5778 @@ + 'a', + 66 => 'b', + 67 => 'c', + 68 => 'd', + 69 => 'e', + 70 => 'f', + 71 => 'g', + 72 => 'h', + 73 => 'i', + 74 => 'j', + 75 => 'k', + 76 => 'l', + 77 => 'm', + 78 => 'n', + 79 => 'o', + 80 => 'p', + 81 => 'q', + 82 => 'r', + 83 => 's', + 84 => 't', + 85 => 'u', + 86 => 'v', + 87 => 'w', + 88 => 'x', + 89 => 'y', + 90 => 'z', + 170 => 'a', + 178 => '2', + 179 => '3', + 181 => 'μ', + 185 => '1', + 186 => 'o', + 188 => '1⁄4', + 189 => '1⁄2', + 190 => '3⁄4', + 192 => 'à', + 193 => 'á', + 194 => 'â', + 195 => 'ã', + 196 => 'ä', + 197 => 'å', + 198 => 'æ', + 199 => 'ç', + 200 => 'è', + 201 => 'é', + 202 => 'ê', + 203 => 'ë', + 204 => 'ì', + 205 => 'í', + 206 => 'î', + 207 => 'ï', + 208 => 'ð', + 209 => 'ñ', + 210 => 'ò', + 211 => 'ó', + 212 => 'ô', + 213 => 'õ', + 214 => 'ö', + 216 => 'ø', + 217 => 'ù', + 218 => 'ú', + 219 => 'û', + 220 => 'ü', + 221 => 'ý', + 222 => 'þ', + 256 => 'ā', + 258 => 'ă', + 260 => 'ą', + 262 => 'ć', + 264 => 'ĉ', + 266 => 'ċ', + 268 => 'č', + 270 => 'ď', + 272 => 'đ', + 274 => 'ē', + 276 => 'ĕ', + 278 => 'ė', + 280 => 'ę', + 282 => 'ě', + 284 => 'ĝ', + 286 => 'ğ', + 288 => 'ġ', + 290 => 'ģ', + 292 => 'ĥ', + 294 => 'ħ', + 296 => 'ĩ', + 298 => 'ī', + 300 => 'ĭ', + 302 => 'į', + 304 => 'i̇', + 306 => 'ij', + 307 => 'ij', + 308 => 'ĵ', + 310 => 'ķ', + 313 => 'ĺ', + 315 => 'ļ', + 317 => 'ľ', + 319 => 'l·', + 320 => 'l·', + 321 => 'ł', + 323 => 'ń', + 325 => 'ņ', + 327 => 'ň', + 329 => 'ʼn', + 330 => 'ŋ', + 332 => 'ō', + 334 => 'ŏ', + 336 => 'ő', + 338 => 'œ', + 340 => 'ŕ', + 342 => 'ŗ', + 344 => 'ř', + 346 => 'ś', + 348 => 'ŝ', + 350 => 'ş', + 352 => 'š', + 354 => 'ţ', + 356 => 'ť', + 358 => 'ŧ', + 360 => 'ũ', + 362 => 'ū', + 364 => 'ŭ', + 366 => 'ů', + 368 => 'ű', + 370 => 'ų', + 372 => 'ŵ', + 374 => 'ŷ', + 376 => 'ÿ', + 377 => 'ź', + 379 => 'ż', + 381 => 'ž', + 383 => 's', + 385 => 'ɓ', + 386 => 'ƃ', + 388 => 'ƅ', + 390 => 'ɔ', + 391 => 'ƈ', + 393 => 'ɖ', + 394 => 'ɗ', + 395 => 'ƌ', + 398 => 'ǝ', + 399 => 'ə', + 400 => 'ɛ', + 401 => 'ƒ', + 403 => 'ɠ', + 404 => 'ɣ', + 406 => 'ɩ', + 407 => 'ɨ', + 408 => 'ƙ', + 412 => 'ɯ', + 413 => 'ɲ', + 415 => 'ɵ', + 416 => 'ơ', + 418 => 'ƣ', + 420 => 'ƥ', + 422 => 'ʀ', + 423 => 'ƨ', + 425 => 'ʃ', + 428 => 'ƭ', + 430 => 'ʈ', + 431 => 'ư', + 433 => 'ʊ', + 434 => 'ʋ', + 435 => 'ƴ', + 437 => 'ƶ', + 439 => 'ʒ', + 440 => 'ƹ', + 444 => 'ƽ', + 452 => 'dž', + 453 => 'dž', + 454 => 'dž', + 455 => 'lj', + 456 => 'lj', + 457 => 'lj', + 458 => 'nj', + 459 => 'nj', + 460 => 'nj', + 461 => 'ǎ', + 463 => 'ǐ', + 465 => 'ǒ', + 467 => 'ǔ', + 469 => 'ǖ', + 471 => 'ǘ', + 473 => 'ǚ', + 475 => 'ǜ', + 478 => 'ǟ', + 480 => 'ǡ', + 482 => 'ǣ', + 484 => 'ǥ', + 486 => 'ǧ', + 488 => 'ǩ', + 490 => 'ǫ', + 492 => 'ǭ', + 494 => 'ǯ', + 497 => 'dz', + 498 => 'dz', + 499 => 'dz', + 500 => 'ǵ', + 502 => 'ƕ', + 503 => 'ƿ', + 504 => 'ǹ', + 506 => 'ǻ', + 508 => 'ǽ', + 510 => 'ǿ', + 512 => 'ȁ', + 514 => 'ȃ', + 516 => 'ȅ', + 518 => 'ȇ', + 520 => 'ȉ', + 522 => 'ȋ', + 524 => 'ȍ', + 526 => 'ȏ', + 528 => 'ȑ', + 530 => 'ȓ', + 532 => 'ȕ', + 534 => 'ȗ', + 536 => 'ș', + 538 => 'ț', + 540 => 'ȝ', + 542 => 'ȟ', + 544 => 'ƞ', + 546 => 'ȣ', + 548 => 'ȥ', + 550 => 'ȧ', + 552 => 'ȩ', + 554 => 'ȫ', + 556 => 'ȭ', + 558 => 'ȯ', + 560 => 'ȱ', + 562 => 'ȳ', + 570 => 'ⱥ', + 571 => 'ȼ', + 573 => 'ƚ', + 574 => 'ⱦ', + 577 => 'ɂ', + 579 => 'ƀ', + 580 => 'ʉ', + 581 => 'ʌ', + 582 => 'ɇ', + 584 => 'ɉ', + 586 => 'ɋ', + 588 => 'ɍ', + 590 => 'ɏ', + 688 => 'h', + 689 => 'ɦ', + 690 => 'j', + 691 => 'r', + 692 => 'ɹ', + 693 => 'ɻ', + 694 => 'ʁ', + 695 => 'w', + 696 => 'y', + 736 => 'ɣ', + 737 => 'l', + 738 => 's', + 739 => 'x', + 740 => 'ʕ', + 832 => '̀', + 833 => '́', + 835 => '̓', + 836 => '̈́', + 837 => 'ι', + 880 => 'ͱ', + 882 => 'ͳ', + 884 => 'ʹ', + 886 => 'ͷ', + 895 => 'ϳ', + 902 => 'ά', + 903 => '·', + 904 => 'έ', + 905 => 'ή', + 906 => 'ί', + 908 => 'ό', + 910 => 'ύ', + 911 => 'ώ', + 913 => 'α', + 914 => 'β', + 915 => 'γ', + 916 => 'δ', + 917 => 'ε', + 918 => 'ζ', + 919 => 'η', + 920 => 'θ', + 921 => 'ι', + 922 => 'κ', + 923 => 'λ', + 924 => 'μ', + 925 => 'ν', + 926 => 'ξ', + 927 => 'ο', + 928 => 'π', + 929 => 'ρ', + 931 => 'σ', + 932 => 'τ', + 933 => 'υ', + 934 => 'φ', + 935 => 'χ', + 936 => 'ψ', + 937 => 'ω', + 938 => 'ϊ', + 939 => 'ϋ', + 975 => 'ϗ', + 976 => 'β', + 977 => 'θ', + 978 => 'υ', + 979 => 'ύ', + 980 => 'ϋ', + 981 => 'φ', + 982 => 'π', + 984 => 'ϙ', + 986 => 'ϛ', + 988 => 'ϝ', + 990 => 'ϟ', + 992 => 'ϡ', + 994 => 'ϣ', + 996 => 'ϥ', + 998 => 'ϧ', + 1000 => 'ϩ', + 1002 => 'ϫ', + 1004 => 'ϭ', + 1006 => 'ϯ', + 1008 => 'κ', + 1009 => 'ρ', + 1010 => 'σ', + 1012 => 'θ', + 1013 => 'ε', + 1015 => 'ϸ', + 1017 => 'σ', + 1018 => 'ϻ', + 1021 => 'ͻ', + 1022 => 'ͼ', + 1023 => 'ͽ', + 1024 => 'ѐ', + 1025 => 'ё', + 1026 => 'ђ', + 1027 => 'ѓ', + 1028 => 'є', + 1029 => 'ѕ', + 1030 => 'і', + 1031 => 'ї', + 1032 => 'ј', + 1033 => 'љ', + 1034 => 'њ', + 1035 => 'ћ', + 1036 => 'ќ', + 1037 => 'ѝ', + 1038 => 'ў', + 1039 => 'џ', + 1040 => 'а', + 1041 => 'б', + 1042 => 'в', + 1043 => 'г', + 1044 => 'д', + 1045 => 'е', + 1046 => 'ж', + 1047 => 'з', + 1048 => 'и', + 1049 => 'й', + 1050 => 'к', + 1051 => 'л', + 1052 => 'м', + 1053 => 'н', + 1054 => 'о', + 1055 => 'п', + 1056 => 'р', + 1057 => 'с', + 1058 => 'т', + 1059 => 'у', + 1060 => 'ф', + 1061 => 'х', + 1062 => 'ц', + 1063 => 'ч', + 1064 => 'ш', + 1065 => 'щ', + 1066 => 'ъ', + 1067 => 'ы', + 1068 => 'ь', + 1069 => 'э', + 1070 => 'ю', + 1071 => 'я', + 1120 => 'ѡ', + 1122 => 'ѣ', + 1124 => 'ѥ', + 1126 => 'ѧ', + 1128 => 'ѩ', + 1130 => 'ѫ', + 1132 => 'ѭ', + 1134 => 'ѯ', + 1136 => 'ѱ', + 1138 => 'ѳ', + 1140 => 'ѵ', + 1142 => 'ѷ', + 1144 => 'ѹ', + 1146 => 'ѻ', + 1148 => 'ѽ', + 1150 => 'ѿ', + 1152 => 'ҁ', + 1162 => 'ҋ', + 1164 => 'ҍ', + 1166 => 'ҏ', + 1168 => 'ґ', + 1170 => 'ғ', + 1172 => 'ҕ', + 1174 => 'җ', + 1176 => 'ҙ', + 1178 => 'қ', + 1180 => 'ҝ', + 1182 => 'ҟ', + 1184 => 'ҡ', + 1186 => 'ң', + 1188 => 'ҥ', + 1190 => 'ҧ', + 1192 => 'ҩ', + 1194 => 'ҫ', + 1196 => 'ҭ', + 1198 => 'ү', + 1200 => 'ұ', + 1202 => 'ҳ', + 1204 => 'ҵ', + 1206 => 'ҷ', + 1208 => 'ҹ', + 1210 => 'һ', + 1212 => 'ҽ', + 1214 => 'ҿ', + 1217 => 'ӂ', + 1219 => 'ӄ', + 1221 => 'ӆ', + 1223 => 'ӈ', + 1225 => 'ӊ', + 1227 => 'ӌ', + 1229 => 'ӎ', + 1232 => 'ӑ', + 1234 => 'ӓ', + 1236 => 'ӕ', + 1238 => 'ӗ', + 1240 => 'ә', + 1242 => 'ӛ', + 1244 => 'ӝ', + 1246 => 'ӟ', + 1248 => 'ӡ', + 1250 => 'ӣ', + 1252 => 'ӥ', + 1254 => 'ӧ', + 1256 => 'ө', + 1258 => 'ӫ', + 1260 => 'ӭ', + 1262 => 'ӯ', + 1264 => 'ӱ', + 1266 => 'ӳ', + 1268 => 'ӵ', + 1270 => 'ӷ', + 1272 => 'ӹ', + 1274 => 'ӻ', + 1276 => 'ӽ', + 1278 => 'ӿ', + 1280 => 'ԁ', + 1282 => 'ԃ', + 1284 => 'ԅ', + 1286 => 'ԇ', + 1288 => 'ԉ', + 1290 => 'ԋ', + 1292 => 'ԍ', + 1294 => 'ԏ', + 1296 => 'ԑ', + 1298 => 'ԓ', + 1300 => 'ԕ', + 1302 => 'ԗ', + 1304 => 'ԙ', + 1306 => 'ԛ', + 1308 => 'ԝ', + 1310 => 'ԟ', + 1312 => 'ԡ', + 1314 => 'ԣ', + 1316 => 'ԥ', + 1318 => 'ԧ', + 1320 => 'ԩ', + 1322 => 'ԫ', + 1324 => 'ԭ', + 1326 => 'ԯ', + 1329 => 'ա', + 1330 => 'բ', + 1331 => 'գ', + 1332 => 'դ', + 1333 => 'ե', + 1334 => 'զ', + 1335 => 'է', + 1336 => 'ը', + 1337 => 'թ', + 1338 => 'ժ', + 1339 => 'ի', + 1340 => 'լ', + 1341 => 'խ', + 1342 => 'ծ', + 1343 => 'կ', + 1344 => 'հ', + 1345 => 'ձ', + 1346 => 'ղ', + 1347 => 'ճ', + 1348 => 'մ', + 1349 => 'յ', + 1350 => 'ն', + 1351 => 'շ', + 1352 => 'ո', + 1353 => 'չ', + 1354 => 'պ', + 1355 => 'ջ', + 1356 => 'ռ', + 1357 => 'ս', + 1358 => 'վ', + 1359 => 'տ', + 1360 => 'ր', + 1361 => 'ց', + 1362 => 'ւ', + 1363 => 'փ', + 1364 => 'ք', + 1365 => 'օ', + 1366 => 'ֆ', + 1415 => 'եւ', + 1653 => 'اٴ', + 1654 => 'وٴ', + 1655 => 'ۇٴ', + 1656 => 'يٴ', + 2392 => 'क़', + 2393 => 'ख़', + 2394 => 'ग़', + 2395 => 'ज़', + 2396 => 'ड़', + 2397 => 'ढ़', + 2398 => 'फ़', + 2399 => 'य़', + 2524 => 'ড়', + 2525 => 'ঢ়', + 2527 => 'য়', + 2611 => 'ਲ਼', + 2614 => 'ਸ਼', + 2649 => 'ਖ਼', + 2650 => 'ਗ਼', + 2651 => 'ਜ਼', + 2654 => 'ਫ਼', + 2908 => 'ଡ଼', + 2909 => 'ଢ଼', + 3635 => 'ํา', + 3763 => 'ໍາ', + 3804 => 'ຫນ', + 3805 => 'ຫມ', + 3852 => '་', + 3907 => 'གྷ', + 3917 => 'ཌྷ', + 3922 => 'དྷ', + 3927 => 'བྷ', + 3932 => 'ཛྷ', + 3945 => 'ཀྵ', + 3955 => 'ཱི', + 3957 => 'ཱུ', + 3958 => 'ྲྀ', + 3959 => 'ྲཱྀ', + 3960 => 'ླྀ', + 3961 => 'ླཱྀ', + 3969 => 'ཱྀ', + 3987 => 'ྒྷ', + 3997 => 'ྜྷ', + 4002 => 'ྡྷ', + 4007 => 'ྦྷ', + 4012 => 'ྫྷ', + 4025 => 'ྐྵ', + 4295 => 'ⴧ', + 4301 => 'ⴭ', + 4348 => 'ნ', + 5112 => 'Ᏸ', + 5113 => 'Ᏹ', + 5114 => 'Ᏺ', + 5115 => 'Ᏻ', + 5116 => 'Ᏼ', + 5117 => 'Ᏽ', + 7296 => 'в', + 7297 => 'д', + 7298 => 'о', + 7299 => 'с', + 7300 => 'т', + 7301 => 'т', + 7302 => 'ъ', + 7303 => 'ѣ', + 7304 => 'ꙋ', + 7312 => 'ა', + 7313 => 'ბ', + 7314 => 'გ', + 7315 => 'დ', + 7316 => 'ე', + 7317 => 'ვ', + 7318 => 'ზ', + 7319 => 'თ', + 7320 => 'ი', + 7321 => 'კ', + 7322 => 'ლ', + 7323 => 'მ', + 7324 => 'ნ', + 7325 => 'ო', + 7326 => 'პ', + 7327 => 'ჟ', + 7328 => 'რ', + 7329 => 'ს', + 7330 => 'ტ', + 7331 => 'უ', + 7332 => 'ფ', + 7333 => 'ქ', + 7334 => 'ღ', + 7335 => 'ყ', + 7336 => 'შ', + 7337 => 'ჩ', + 7338 => 'ც', + 7339 => 'ძ', + 7340 => 'წ', + 7341 => 'ჭ', + 7342 => 'ხ', + 7343 => 'ჯ', + 7344 => 'ჰ', + 7345 => 'ჱ', + 7346 => 'ჲ', + 7347 => 'ჳ', + 7348 => 'ჴ', + 7349 => 'ჵ', + 7350 => 'ჶ', + 7351 => 'ჷ', + 7352 => 'ჸ', + 7353 => 'ჹ', + 7354 => 'ჺ', + 7357 => 'ჽ', + 7358 => 'ჾ', + 7359 => 'ჿ', + 7468 => 'a', + 7469 => 'æ', + 7470 => 'b', + 7472 => 'd', + 7473 => 'e', + 7474 => 'ǝ', + 7475 => 'g', + 7476 => 'h', + 7477 => 'i', + 7478 => 'j', + 7479 => 'k', + 7480 => 'l', + 7481 => 'm', + 7482 => 'n', + 7484 => 'o', + 7485 => 'ȣ', + 7486 => 'p', + 7487 => 'r', + 7488 => 't', + 7489 => 'u', + 7490 => 'w', + 7491 => 'a', + 7492 => 'ɐ', + 7493 => 'ɑ', + 7494 => 'ᴂ', + 7495 => 'b', + 7496 => 'd', + 7497 => 'e', + 7498 => 'ə', + 7499 => 'ɛ', + 7500 => 'ɜ', + 7501 => 'g', + 7503 => 'k', + 7504 => 'm', + 7505 => 'ŋ', + 7506 => 'o', + 7507 => 'ɔ', + 7508 => 'ᴖ', + 7509 => 'ᴗ', + 7510 => 'p', + 7511 => 't', + 7512 => 'u', + 7513 => 'ᴝ', + 7514 => 'ɯ', + 7515 => 'v', + 7516 => 'ᴥ', + 7517 => 'β', + 7518 => 'γ', + 7519 => 'δ', + 7520 => 'φ', + 7521 => 'χ', + 7522 => 'i', + 7523 => 'r', + 7524 => 'u', + 7525 => 'v', + 7526 => 'β', + 7527 => 'γ', + 7528 => 'ρ', + 7529 => 'φ', + 7530 => 'χ', + 7544 => 'н', + 7579 => 'ɒ', + 7580 => 'c', + 7581 => 'ɕ', + 7582 => 'ð', + 7583 => 'ɜ', + 7584 => 'f', + 7585 => 'ɟ', + 7586 => 'ɡ', + 7587 => 'ɥ', + 7588 => 'ɨ', + 7589 => 'ɩ', + 7590 => 'ɪ', + 7591 => 'ᵻ', + 7592 => 'ʝ', + 7593 => 'ɭ', + 7594 => 'ᶅ', + 7595 => 'ʟ', + 7596 => 'ɱ', + 7597 => 'ɰ', + 7598 => 'ɲ', + 7599 => 'ɳ', + 7600 => 'ɴ', + 7601 => 'ɵ', + 7602 => 'ɸ', + 7603 => 'ʂ', + 7604 => 'ʃ', + 7605 => 'ƫ', + 7606 => 'ʉ', + 7607 => 'ʊ', + 7608 => 'ᴜ', + 7609 => 'ʋ', + 7610 => 'ʌ', + 7611 => 'z', + 7612 => 'ʐ', + 7613 => 'ʑ', + 7614 => 'ʒ', + 7615 => 'θ', + 7680 => 'ḁ', + 7682 => 'ḃ', + 7684 => 'ḅ', + 7686 => 'ḇ', + 7688 => 'ḉ', + 7690 => 'ḋ', + 7692 => 'ḍ', + 7694 => 'ḏ', + 7696 => 'ḑ', + 7698 => 'ḓ', + 7700 => 'ḕ', + 7702 => 'ḗ', + 7704 => 'ḙ', + 7706 => 'ḛ', + 7708 => 'ḝ', + 7710 => 'ḟ', + 7712 => 'ḡ', + 7714 => 'ḣ', + 7716 => 'ḥ', + 7718 => 'ḧ', + 7720 => 'ḩ', + 7722 => 'ḫ', + 7724 => 'ḭ', + 7726 => 'ḯ', + 7728 => 'ḱ', + 7730 => 'ḳ', + 7732 => 'ḵ', + 7734 => 'ḷ', + 7736 => 'ḹ', + 7738 => 'ḻ', + 7740 => 'ḽ', + 7742 => 'ḿ', + 7744 => 'ṁ', + 7746 => 'ṃ', + 7748 => 'ṅ', + 7750 => 'ṇ', + 7752 => 'ṉ', + 7754 => 'ṋ', + 7756 => 'ṍ', + 7758 => 'ṏ', + 7760 => 'ṑ', + 7762 => 'ṓ', + 7764 => 'ṕ', + 7766 => 'ṗ', + 7768 => 'ṙ', + 7770 => 'ṛ', + 7772 => 'ṝ', + 7774 => 'ṟ', + 7776 => 'ṡ', + 7778 => 'ṣ', + 7780 => 'ṥ', + 7782 => 'ṧ', + 7784 => 'ṩ', + 7786 => 'ṫ', + 7788 => 'ṭ', + 7790 => 'ṯ', + 7792 => 'ṱ', + 7794 => 'ṳ', + 7796 => 'ṵ', + 7798 => 'ṷ', + 7800 => 'ṹ', + 7802 => 'ṻ', + 7804 => 'ṽ', + 7806 => 'ṿ', + 7808 => 'ẁ', + 7810 => 'ẃ', + 7812 => 'ẅ', + 7814 => 'ẇ', + 7816 => 'ẉ', + 7818 => 'ẋ', + 7820 => 'ẍ', + 7822 => 'ẏ', + 7824 => 'ẑ', + 7826 => 'ẓ', + 7828 => 'ẕ', + 7834 => 'aʾ', + 7835 => 'ṡ', + 7838 => 'ss', + 7840 => 'ạ', + 7842 => 'ả', + 7844 => 'ấ', + 7846 => 'ầ', + 7848 => 'ẩ', + 7850 => 'ẫ', + 7852 => 'ậ', + 7854 => 'ắ', + 7856 => 'ằ', + 7858 => 'ẳ', + 7860 => 'ẵ', + 7862 => 'ặ', + 7864 => 'ẹ', + 7866 => 'ẻ', + 7868 => 'ẽ', + 7870 => 'ế', + 7872 => 'ề', + 7874 => 'ể', + 7876 => 'ễ', + 7878 => 'ệ', + 7880 => 'ỉ', + 7882 => 'ị', + 7884 => 'ọ', + 7886 => 'ỏ', + 7888 => 'ố', + 7890 => 'ồ', + 7892 => 'ổ', + 7894 => 'ỗ', + 7896 => 'ộ', + 7898 => 'ớ', + 7900 => 'ờ', + 7902 => 'ở', + 7904 => 'ỡ', + 7906 => 'ợ', + 7908 => 'ụ', + 7910 => 'ủ', + 7912 => 'ứ', + 7914 => 'ừ', + 7916 => 'ử', + 7918 => 'ữ', + 7920 => 'ự', + 7922 => 'ỳ', + 7924 => 'ỵ', + 7926 => 'ỷ', + 7928 => 'ỹ', + 7930 => 'ỻ', + 7932 => 'ỽ', + 7934 => 'ỿ', + 7944 => 'ἀ', + 7945 => 'ἁ', + 7946 => 'ἂ', + 7947 => 'ἃ', + 7948 => 'ἄ', + 7949 => 'ἅ', + 7950 => 'ἆ', + 7951 => 'ἇ', + 7960 => 'ἐ', + 7961 => 'ἑ', + 7962 => 'ἒ', + 7963 => 'ἓ', + 7964 => 'ἔ', + 7965 => 'ἕ', + 7976 => 'ἠ', + 7977 => 'ἡ', + 7978 => 'ἢ', + 7979 => 'ἣ', + 7980 => 'ἤ', + 7981 => 'ἥ', + 7982 => 'ἦ', + 7983 => 'ἧ', + 7992 => 'ἰ', + 7993 => 'ἱ', + 7994 => 'ἲ', + 7995 => 'ἳ', + 7996 => 'ἴ', + 7997 => 'ἵ', + 7998 => 'ἶ', + 7999 => 'ἷ', + 8008 => 'ὀ', + 8009 => 'ὁ', + 8010 => 'ὂ', + 8011 => 'ὃ', + 8012 => 'ὄ', + 8013 => 'ὅ', + 8025 => 'ὑ', + 8027 => 'ὓ', + 8029 => 'ὕ', + 8031 => 'ὗ', + 8040 => 'ὠ', + 8041 => 'ὡ', + 8042 => 'ὢ', + 8043 => 'ὣ', + 8044 => 'ὤ', + 8045 => 'ὥ', + 8046 => 'ὦ', + 8047 => 'ὧ', + 8049 => 'ά', + 8051 => 'έ', + 8053 => 'ή', + 8055 => 'ί', + 8057 => 'ό', + 8059 => 'ύ', + 8061 => 'ώ', + 8064 => 'ἀι', + 8065 => 'ἁι', + 8066 => 'ἂι', + 8067 => 'ἃι', + 8068 => 'ἄι', + 8069 => 'ἅι', + 8070 => 'ἆι', + 8071 => 'ἇι', + 8072 => 'ἀι', + 8073 => 'ἁι', + 8074 => 'ἂι', + 8075 => 'ἃι', + 8076 => 'ἄι', + 8077 => 'ἅι', + 8078 => 'ἆι', + 8079 => 'ἇι', + 8080 => 'ἠι', + 8081 => 'ἡι', + 8082 => 'ἢι', + 8083 => 'ἣι', + 8084 => 'ἤι', + 8085 => 'ἥι', + 8086 => 'ἦι', + 8087 => 'ἧι', + 8088 => 'ἠι', + 8089 => 'ἡι', + 8090 => 'ἢι', + 8091 => 'ἣι', + 8092 => 'ἤι', + 8093 => 'ἥι', + 8094 => 'ἦι', + 8095 => 'ἧι', + 8096 => 'ὠι', + 8097 => 'ὡι', + 8098 => 'ὢι', + 8099 => 'ὣι', + 8100 => 'ὤι', + 8101 => 'ὥι', + 8102 => 'ὦι', + 8103 => 'ὧι', + 8104 => 'ὠι', + 8105 => 'ὡι', + 8106 => 'ὢι', + 8107 => 'ὣι', + 8108 => 'ὤι', + 8109 => 'ὥι', + 8110 => 'ὦι', + 8111 => 'ὧι', + 8114 => 'ὰι', + 8115 => 'αι', + 8116 => 'άι', + 8119 => 'ᾶι', + 8120 => 'ᾰ', + 8121 => 'ᾱ', + 8122 => 'ὰ', + 8123 => 'ά', + 8124 => 'αι', + 8126 => 'ι', + 8130 => 'ὴι', + 8131 => 'ηι', + 8132 => 'ήι', + 8135 => 'ῆι', + 8136 => 'ὲ', + 8137 => 'έ', + 8138 => 'ὴ', + 8139 => 'ή', + 8140 => 'ηι', + 8147 => 'ΐ', + 8152 => 'ῐ', + 8153 => 'ῑ', + 8154 => 'ὶ', + 8155 => 'ί', + 8163 => 'ΰ', + 8168 => 'ῠ', + 8169 => 'ῡ', + 8170 => 'ὺ', + 8171 => 'ύ', + 8172 => 'ῥ', + 8178 => 'ὼι', + 8179 => 'ωι', + 8180 => 'ώι', + 8183 => 'ῶι', + 8184 => 'ὸ', + 8185 => 'ό', + 8186 => 'ὼ', + 8187 => 'ώ', + 8188 => 'ωι', + 8209 => '‐', + 8243 => '′′', + 8244 => '′′′', + 8246 => '‵‵', + 8247 => '‵‵‵', + 8279 => '′′′′', + 8304 => '0', + 8305 => 'i', + 8308 => '4', + 8309 => '5', + 8310 => '6', + 8311 => '7', + 8312 => '8', + 8313 => '9', + 8315 => '−', + 8319 => 'n', + 8320 => '0', + 8321 => '1', + 8322 => '2', + 8323 => '3', + 8324 => '4', + 8325 => '5', + 8326 => '6', + 8327 => '7', + 8328 => '8', + 8329 => '9', + 8331 => '−', + 8336 => 'a', + 8337 => 'e', + 8338 => 'o', + 8339 => 'x', + 8340 => 'ə', + 8341 => 'h', + 8342 => 'k', + 8343 => 'l', + 8344 => 'm', + 8345 => 'n', + 8346 => 'p', + 8347 => 's', + 8348 => 't', + 8360 => 'rs', + 8450 => 'c', + 8451 => '°c', + 8455 => 'ɛ', + 8457 => '°f', + 8458 => 'g', + 8459 => 'h', + 8460 => 'h', + 8461 => 'h', + 8462 => 'h', + 8463 => 'ħ', + 8464 => 'i', + 8465 => 'i', + 8466 => 'l', + 8467 => 'l', + 8469 => 'n', + 8470 => 'no', + 8473 => 'p', + 8474 => 'q', + 8475 => 'r', + 8476 => 'r', + 8477 => 'r', + 8480 => 'sm', + 8481 => 'tel', + 8482 => 'tm', + 8484 => 'z', + 8486 => 'ω', + 8488 => 'z', + 8490 => 'k', + 8491 => 'å', + 8492 => 'b', + 8493 => 'c', + 8495 => 'e', + 8496 => 'e', + 8497 => 'f', + 8499 => 'm', + 8500 => 'o', + 8501 => 'א', + 8502 => 'ב', + 8503 => 'ג', + 8504 => 'ד', + 8505 => 'i', + 8507 => 'fax', + 8508 => 'π', + 8509 => 'γ', + 8510 => 'γ', + 8511 => 'π', + 8512 => '∑', + 8517 => 'd', + 8518 => 'd', + 8519 => 'e', + 8520 => 'i', + 8521 => 'j', + 8528 => '1⁄7', + 8529 => '1⁄9', + 8530 => '1⁄10', + 8531 => '1⁄3', + 8532 => '2⁄3', + 8533 => '1⁄5', + 8534 => '2⁄5', + 8535 => '3⁄5', + 8536 => '4⁄5', + 8537 => '1⁄6', + 8538 => '5⁄6', + 8539 => '1⁄8', + 8540 => '3⁄8', + 8541 => '5⁄8', + 8542 => '7⁄8', + 8543 => '1⁄', + 8544 => 'i', + 8545 => 'ii', + 8546 => 'iii', + 8547 => 'iv', + 8548 => 'v', + 8549 => 'vi', + 8550 => 'vii', + 8551 => 'viii', + 8552 => 'ix', + 8553 => 'x', + 8554 => 'xi', + 8555 => 'xii', + 8556 => 'l', + 8557 => 'c', + 8558 => 'd', + 8559 => 'm', + 8560 => 'i', + 8561 => 'ii', + 8562 => 'iii', + 8563 => 'iv', + 8564 => 'v', + 8565 => 'vi', + 8566 => 'vii', + 8567 => 'viii', + 8568 => 'ix', + 8569 => 'x', + 8570 => 'xi', + 8571 => 'xii', + 8572 => 'l', + 8573 => 'c', + 8574 => 'd', + 8575 => 'm', + 8585 => '0⁄3', + 8748 => '∫∫', + 8749 => '∫∫∫', + 8751 => '∮∮', + 8752 => '∮∮∮', + 9001 => '〈', + 9002 => '〉', + 9312 => '1', + 9313 => '2', + 9314 => '3', + 9315 => '4', + 9316 => '5', + 9317 => '6', + 9318 => '7', + 9319 => '8', + 9320 => '9', + 9321 => '10', + 9322 => '11', + 9323 => '12', + 9324 => '13', + 9325 => '14', + 9326 => '15', + 9327 => '16', + 9328 => '17', + 9329 => '18', + 9330 => '19', + 9331 => '20', + 9398 => 'a', + 9399 => 'b', + 9400 => 'c', + 9401 => 'd', + 9402 => 'e', + 9403 => 'f', + 9404 => 'g', + 9405 => 'h', + 9406 => 'i', + 9407 => 'j', + 9408 => 'k', + 9409 => 'l', + 9410 => 'm', + 9411 => 'n', + 9412 => 'o', + 9413 => 'p', + 9414 => 'q', + 9415 => 'r', + 9416 => 's', + 9417 => 't', + 9418 => 'u', + 9419 => 'v', + 9420 => 'w', + 9421 => 'x', + 9422 => 'y', + 9423 => 'z', + 9424 => 'a', + 9425 => 'b', + 9426 => 'c', + 9427 => 'd', + 9428 => 'e', + 9429 => 'f', + 9430 => 'g', + 9431 => 'h', + 9432 => 'i', + 9433 => 'j', + 9434 => 'k', + 9435 => 'l', + 9436 => 'm', + 9437 => 'n', + 9438 => 'o', + 9439 => 'p', + 9440 => 'q', + 9441 => 'r', + 9442 => 's', + 9443 => 't', + 9444 => 'u', + 9445 => 'v', + 9446 => 'w', + 9447 => 'x', + 9448 => 'y', + 9449 => 'z', + 9450 => '0', + 10764 => '∫∫∫∫', + 10972 => '⫝̸', + 11264 => 'ⰰ', + 11265 => 'ⰱ', + 11266 => 'ⰲ', + 11267 => 'ⰳ', + 11268 => 'ⰴ', + 11269 => 'ⰵ', + 11270 => 'ⰶ', + 11271 => 'ⰷ', + 11272 => 'ⰸ', + 11273 => 'ⰹ', + 11274 => 'ⰺ', + 11275 => 'ⰻ', + 11276 => 'ⰼ', + 11277 => 'ⰽ', + 11278 => 'ⰾ', + 11279 => 'ⰿ', + 11280 => 'ⱀ', + 11281 => 'ⱁ', + 11282 => 'ⱂ', + 11283 => 'ⱃ', + 11284 => 'ⱄ', + 11285 => 'ⱅ', + 11286 => 'ⱆ', + 11287 => 'ⱇ', + 11288 => 'ⱈ', + 11289 => 'ⱉ', + 11290 => 'ⱊ', + 11291 => 'ⱋ', + 11292 => 'ⱌ', + 11293 => 'ⱍ', + 11294 => 'ⱎ', + 11295 => 'ⱏ', + 11296 => 'ⱐ', + 11297 => 'ⱑ', + 11298 => 'ⱒ', + 11299 => 'ⱓ', + 11300 => 'ⱔ', + 11301 => 'ⱕ', + 11302 => 'ⱖ', + 11303 => 'ⱗ', + 11304 => 'ⱘ', + 11305 => 'ⱙ', + 11306 => 'ⱚ', + 11307 => 'ⱛ', + 11308 => 'ⱜ', + 11309 => 'ⱝ', + 11310 => 'ⱞ', + 11360 => 'ⱡ', + 11362 => 'ɫ', + 11363 => 'ᵽ', + 11364 => 'ɽ', + 11367 => 'ⱨ', + 11369 => 'ⱪ', + 11371 => 'ⱬ', + 11373 => 'ɑ', + 11374 => 'ɱ', + 11375 => 'ɐ', + 11376 => 'ɒ', + 11378 => 'ⱳ', + 11381 => 'ⱶ', + 11388 => 'j', + 11389 => 'v', + 11390 => 'ȿ', + 11391 => 'ɀ', + 11392 => 'ⲁ', + 11394 => 'ⲃ', + 11396 => 'ⲅ', + 11398 => 'ⲇ', + 11400 => 'ⲉ', + 11402 => 'ⲋ', + 11404 => 'ⲍ', + 11406 => 'ⲏ', + 11408 => 'ⲑ', + 11410 => 'ⲓ', + 11412 => 'ⲕ', + 11414 => 'ⲗ', + 11416 => 'ⲙ', + 11418 => 'ⲛ', + 11420 => 'ⲝ', + 11422 => 'ⲟ', + 11424 => 'ⲡ', + 11426 => 'ⲣ', + 11428 => 'ⲥ', + 11430 => 'ⲧ', + 11432 => 'ⲩ', + 11434 => 'ⲫ', + 11436 => 'ⲭ', + 11438 => 'ⲯ', + 11440 => 'ⲱ', + 11442 => 'ⲳ', + 11444 => 'ⲵ', + 11446 => 'ⲷ', + 11448 => 'ⲹ', + 11450 => 'ⲻ', + 11452 => 'ⲽ', + 11454 => 'ⲿ', + 11456 => 'ⳁ', + 11458 => 'ⳃ', + 11460 => 'ⳅ', + 11462 => 'ⳇ', + 11464 => 'ⳉ', + 11466 => 'ⳋ', + 11468 => 'ⳍ', + 11470 => 'ⳏ', + 11472 => 'ⳑ', + 11474 => 'ⳓ', + 11476 => 'ⳕ', + 11478 => 'ⳗ', + 11480 => 'ⳙ', + 11482 => 'ⳛ', + 11484 => 'ⳝ', + 11486 => 'ⳟ', + 11488 => 'ⳡ', + 11490 => 'ⳣ', + 11499 => 'ⳬ', + 11501 => 'ⳮ', + 11506 => 'ⳳ', + 11631 => 'ⵡ', + 11935 => '母', + 12019 => '龟', + 12032 => '一', + 12033 => '丨', + 12034 => '丶', + 12035 => '丿', + 12036 => '乙', + 12037 => '亅', + 12038 => '二', + 12039 => '亠', + 12040 => '人', + 12041 => '儿', + 12042 => '入', + 12043 => '八', + 12044 => '冂', + 12045 => '冖', + 12046 => '冫', + 12047 => '几', + 12048 => '凵', + 12049 => '刀', + 12050 => '力', + 12051 => '勹', + 12052 => '匕', + 12053 => '匚', + 12054 => '匸', + 12055 => '十', + 12056 => '卜', + 12057 => '卩', + 12058 => '厂', + 12059 => '厶', + 12060 => '又', + 12061 => '口', + 12062 => '囗', + 12063 => '土', + 12064 => '士', + 12065 => '夂', + 12066 => '夊', + 12067 => '夕', + 12068 => '大', + 12069 => '女', + 12070 => '子', + 12071 => '宀', + 12072 => '寸', + 12073 => '小', + 12074 => '尢', + 12075 => '尸', + 12076 => '屮', + 12077 => '山', + 12078 => '巛', + 12079 => '工', + 12080 => '己', + 12081 => '巾', + 12082 => '干', + 12083 => '幺', + 12084 => '广', + 12085 => '廴', + 12086 => '廾', + 12087 => '弋', + 12088 => '弓', + 12089 => '彐', + 12090 => '彡', + 12091 => '彳', + 12092 => '心', + 12093 => '戈', + 12094 => '戶', + 12095 => '手', + 12096 => '支', + 12097 => '攴', + 12098 => '文', + 12099 => '斗', + 12100 => '斤', + 12101 => '方', + 12102 => '无', + 12103 => '日', + 12104 => '曰', + 12105 => '月', + 12106 => '木', + 12107 => '欠', + 12108 => '止', + 12109 => '歹', + 12110 => '殳', + 12111 => '毋', + 12112 => '比', + 12113 => '毛', + 12114 => '氏', + 12115 => '气', + 12116 => '水', + 12117 => '火', + 12118 => '爪', + 12119 => '父', + 12120 => '爻', + 12121 => '爿', + 12122 => '片', + 12123 => '牙', + 12124 => '牛', + 12125 => '犬', + 12126 => '玄', + 12127 => '玉', + 12128 => '瓜', + 12129 => '瓦', + 12130 => '甘', + 12131 => '生', + 12132 => '用', + 12133 => '田', + 12134 => '疋', + 12135 => '疒', + 12136 => '癶', + 12137 => '白', + 12138 => '皮', + 12139 => '皿', + 12140 => '目', + 12141 => '矛', + 12142 => '矢', + 12143 => '石', + 12144 => '示', + 12145 => '禸', + 12146 => '禾', + 12147 => '穴', + 12148 => '立', + 12149 => '竹', + 12150 => '米', + 12151 => '糸', + 12152 => '缶', + 12153 => '网', + 12154 => '羊', + 12155 => '羽', + 12156 => '老', + 12157 => '而', + 12158 => '耒', + 12159 => '耳', + 12160 => '聿', + 12161 => '肉', + 12162 => '臣', + 12163 => '自', + 12164 => '至', + 12165 => '臼', + 12166 => '舌', + 12167 => '舛', + 12168 => '舟', + 12169 => '艮', + 12170 => '色', + 12171 => '艸', + 12172 => '虍', + 12173 => '虫', + 12174 => '血', + 12175 => '行', + 12176 => '衣', + 12177 => '襾', + 12178 => '見', + 12179 => '角', + 12180 => '言', + 12181 => '谷', + 12182 => '豆', + 12183 => '豕', + 12184 => '豸', + 12185 => '貝', + 12186 => '赤', + 12187 => '走', + 12188 => '足', + 12189 => '身', + 12190 => '車', + 12191 => '辛', + 12192 => '辰', + 12193 => '辵', + 12194 => '邑', + 12195 => '酉', + 12196 => '釆', + 12197 => '里', + 12198 => '金', + 12199 => '長', + 12200 => '門', + 12201 => '阜', + 12202 => '隶', + 12203 => '隹', + 12204 => '雨', + 12205 => '靑', + 12206 => '非', + 12207 => '面', + 12208 => '革', + 12209 => '韋', + 12210 => '韭', + 12211 => '音', + 12212 => '頁', + 12213 => '風', + 12214 => '飛', + 12215 => '食', + 12216 => '首', + 12217 => '香', + 12218 => '馬', + 12219 => '骨', + 12220 => '高', + 12221 => '髟', + 12222 => '鬥', + 12223 => '鬯', + 12224 => '鬲', + 12225 => '鬼', + 12226 => '魚', + 12227 => '鳥', + 12228 => '鹵', + 12229 => '鹿', + 12230 => '麥', + 12231 => '麻', + 12232 => '黃', + 12233 => '黍', + 12234 => '黑', + 12235 => '黹', + 12236 => '黽', + 12237 => '鼎', + 12238 => '鼓', + 12239 => '鼠', + 12240 => '鼻', + 12241 => '齊', + 12242 => '齒', + 12243 => '龍', + 12244 => '龜', + 12245 => '龠', + 12290 => '.', + 12342 => '〒', + 12344 => '十', + 12345 => '卄', + 12346 => '卅', + 12447 => 'より', + 12543 => 'コト', + 12593 => 'ᄀ', + 12594 => 'ᄁ', + 12595 => 'ᆪ', + 12596 => 'ᄂ', + 12597 => 'ᆬ', + 12598 => 'ᆭ', + 12599 => 'ᄃ', + 12600 => 'ᄄ', + 12601 => 'ᄅ', + 12602 => 'ᆰ', + 12603 => 'ᆱ', + 12604 => 'ᆲ', + 12605 => 'ᆳ', + 12606 => 'ᆴ', + 12607 => 'ᆵ', + 12608 => 'ᄚ', + 12609 => 'ᄆ', + 12610 => 'ᄇ', + 12611 => 'ᄈ', + 12612 => 'ᄡ', + 12613 => 'ᄉ', + 12614 => 'ᄊ', + 12615 => 'ᄋ', + 12616 => 'ᄌ', + 12617 => 'ᄍ', + 12618 => 'ᄎ', + 12619 => 'ᄏ', + 12620 => 'ᄐ', + 12621 => 'ᄑ', + 12622 => 'ᄒ', + 12623 => 'ᅡ', + 12624 => 'ᅢ', + 12625 => 'ᅣ', + 12626 => 'ᅤ', + 12627 => 'ᅥ', + 12628 => 'ᅦ', + 12629 => 'ᅧ', + 12630 => 'ᅨ', + 12631 => 'ᅩ', + 12632 => 'ᅪ', + 12633 => 'ᅫ', + 12634 => 'ᅬ', + 12635 => 'ᅭ', + 12636 => 'ᅮ', + 12637 => 'ᅯ', + 12638 => 'ᅰ', + 12639 => 'ᅱ', + 12640 => 'ᅲ', + 12641 => 'ᅳ', + 12642 => 'ᅴ', + 12643 => 'ᅵ', + 12645 => 'ᄔ', + 12646 => 'ᄕ', + 12647 => 'ᇇ', + 12648 => 'ᇈ', + 12649 => 'ᇌ', + 12650 => 'ᇎ', + 12651 => 'ᇓ', + 12652 => 'ᇗ', + 12653 => 'ᇙ', + 12654 => 'ᄜ', + 12655 => 'ᇝ', + 12656 => 'ᇟ', + 12657 => 'ᄝ', + 12658 => 'ᄞ', + 12659 => 'ᄠ', + 12660 => 'ᄢ', + 12661 => 'ᄣ', + 12662 => 'ᄧ', + 12663 => 'ᄩ', + 12664 => 'ᄫ', + 12665 => 'ᄬ', + 12666 => 'ᄭ', + 12667 => 'ᄮ', + 12668 => 'ᄯ', + 12669 => 'ᄲ', + 12670 => 'ᄶ', + 12671 => 'ᅀ', + 12672 => 'ᅇ', + 12673 => 'ᅌ', + 12674 => 'ᇱ', + 12675 => 'ᇲ', + 12676 => 'ᅗ', + 12677 => 'ᅘ', + 12678 => 'ᅙ', + 12679 => 'ᆄ', + 12680 => 'ᆅ', + 12681 => 'ᆈ', + 12682 => 'ᆑ', + 12683 => 'ᆒ', + 12684 => 'ᆔ', + 12685 => 'ᆞ', + 12686 => 'ᆡ', + 12690 => '一', + 12691 => '二', + 12692 => '三', + 12693 => '四', + 12694 => '上', + 12695 => '中', + 12696 => '下', + 12697 => '甲', + 12698 => '乙', + 12699 => '丙', + 12700 => '丁', + 12701 => '天', + 12702 => '地', + 12703 => '人', + 12868 => '問', + 12869 => '幼', + 12870 => '文', + 12871 => '箏', + 12880 => 'pte', + 12881 => '21', + 12882 => '22', + 12883 => '23', + 12884 => '24', + 12885 => '25', + 12886 => '26', + 12887 => '27', + 12888 => '28', + 12889 => '29', + 12890 => '30', + 12891 => '31', + 12892 => '32', + 12893 => '33', + 12894 => '34', + 12895 => '35', + 12896 => 'ᄀ', + 12897 => 'ᄂ', + 12898 => 'ᄃ', + 12899 => 'ᄅ', + 12900 => 'ᄆ', + 12901 => 'ᄇ', + 12902 => 'ᄉ', + 12903 => 'ᄋ', + 12904 => 'ᄌ', + 12905 => 'ᄎ', + 12906 => 'ᄏ', + 12907 => 'ᄐ', + 12908 => 'ᄑ', + 12909 => 'ᄒ', + 12910 => '가', + 12911 => '나', + 12912 => '다', + 12913 => '라', + 12914 => '마', + 12915 => '바', + 12916 => '사', + 12917 => '아', + 12918 => '자', + 12919 => '차', + 12920 => '카', + 12921 => '타', + 12922 => '파', + 12923 => '하', + 12924 => '참고', + 12925 => '주의', + 12926 => '우', + 12928 => '一', + 12929 => '二', + 12930 => '三', + 12931 => '四', + 12932 => '五', + 12933 => '六', + 12934 => '七', + 12935 => '八', + 12936 => '九', + 12937 => '十', + 12938 => '月', + 12939 => '火', + 12940 => '水', + 12941 => '木', + 12942 => '金', + 12943 => '土', + 12944 => '日', + 12945 => '株', + 12946 => '有', + 12947 => '社', + 12948 => '名', + 12949 => '特', + 12950 => '財', + 12951 => '祝', + 12952 => '労', + 12953 => '秘', + 12954 => '男', + 12955 => '女', + 12956 => '適', + 12957 => '優', + 12958 => '印', + 12959 => '注', + 12960 => '項', + 12961 => '休', + 12962 => '写', + 12963 => '正', + 12964 => '上', + 12965 => '中', + 12966 => '下', + 12967 => '左', + 12968 => '右', + 12969 => '医', + 12970 => '宗', + 12971 => '学', + 12972 => '監', + 12973 => '企', + 12974 => '資', + 12975 => '協', + 12976 => '夜', + 12977 => '36', + 12978 => '37', + 12979 => '38', + 12980 => '39', + 12981 => '40', + 12982 => '41', + 12983 => '42', + 12984 => '43', + 12985 => '44', + 12986 => '45', + 12987 => '46', + 12988 => '47', + 12989 => '48', + 12990 => '49', + 12991 => '50', + 12992 => '1月', + 12993 => '2月', + 12994 => '3月', + 12995 => '4月', + 12996 => '5月', + 12997 => '6月', + 12998 => '7月', + 12999 => '8月', + 13000 => '9月', + 13001 => '10月', + 13002 => '11月', + 13003 => '12月', + 13004 => 'hg', + 13005 => 'erg', + 13006 => 'ev', + 13007 => 'ltd', + 13008 => 'ア', + 13009 => 'イ', + 13010 => 'ウ', + 13011 => 'エ', + 13012 => 'オ', + 13013 => 'カ', + 13014 => 'キ', + 13015 => 'ク', + 13016 => 'ケ', + 13017 => 'コ', + 13018 => 'サ', + 13019 => 'シ', + 13020 => 'ス', + 13021 => 'セ', + 13022 => 'ソ', + 13023 => 'タ', + 13024 => 'チ', + 13025 => 'ツ', + 13026 => 'テ', + 13027 => 'ト', + 13028 => 'ナ', + 13029 => 'ニ', + 13030 => 'ヌ', + 13031 => 'ネ', + 13032 => 'ノ', + 13033 => 'ハ', + 13034 => 'ヒ', + 13035 => 'フ', + 13036 => 'ヘ', + 13037 => 'ホ', + 13038 => 'マ', + 13039 => 'ミ', + 13040 => 'ム', + 13041 => 'メ', + 13042 => 'モ', + 13043 => 'ヤ', + 13044 => 'ユ', + 13045 => 'ヨ', + 13046 => 'ラ', + 13047 => 'リ', + 13048 => 'ル', + 13049 => 'レ', + 13050 => 'ロ', + 13051 => 'ワ', + 13052 => 'ヰ', + 13053 => 'ヱ', + 13054 => 'ヲ', + 13055 => '令和', + 13056 => 'アパート', + 13057 => 'アルファ', + 13058 => 'アンペア', + 13059 => 'アール', + 13060 => 'イニング', + 13061 => 'インチ', + 13062 => 'ウォン', + 13063 => 'エスクード', + 13064 => 'エーカー', + 13065 => 'オンス', + 13066 => 'オーム', + 13067 => 'カイリ', + 13068 => 'カラット', + 13069 => 'カロリー', + 13070 => 'ガロン', + 13071 => 'ガンマ', + 13072 => 'ギガ', + 13073 => 'ギニー', + 13074 => 'キュリー', + 13075 => 'ギルダー', + 13076 => 'キロ', + 13077 => 'キログラム', + 13078 => 'キロメートル', + 13079 => 'キロワット', + 13080 => 'グラム', + 13081 => 'グラムトン', + 13082 => 'クルゼイロ', + 13083 => 'クローネ', + 13084 => 'ケース', + 13085 => 'コルナ', + 13086 => 'コーポ', + 13087 => 'サイクル', + 13088 => 'サンチーム', + 13089 => 'シリング', + 13090 => 'センチ', + 13091 => 'セント', + 13092 => 'ダース', + 13093 => 'デシ', + 13094 => 'ドル', + 13095 => 'トン', + 13096 => 'ナノ', + 13097 => 'ノット', + 13098 => 'ハイツ', + 13099 => 'パーセント', + 13100 => 'パーツ', + 13101 => 'バーレル', + 13102 => 'ピアストル', + 13103 => 'ピクル', + 13104 => 'ピコ', + 13105 => 'ビル', + 13106 => 'ファラッド', + 13107 => 'フィート', + 13108 => 'ブッシェル', + 13109 => 'フラン', + 13110 => 'ヘクタール', + 13111 => 'ペソ', + 13112 => 'ペニヒ', + 13113 => 'ヘルツ', + 13114 => 'ペンス', + 13115 => 'ページ', + 13116 => 'ベータ', + 13117 => 'ポイント', + 13118 => 'ボルト', + 13119 => 'ホン', + 13120 => 'ポンド', + 13121 => 'ホール', + 13122 => 'ホーン', + 13123 => 'マイクロ', + 13124 => 'マイル', + 13125 => 'マッハ', + 13126 => 'マルク', + 13127 => 'マンション', + 13128 => 'ミクロン', + 13129 => 'ミリ', + 13130 => 'ミリバール', + 13131 => 'メガ', + 13132 => 'メガトン', + 13133 => 'メートル', + 13134 => 'ヤード', + 13135 => 'ヤール', + 13136 => 'ユアン', + 13137 => 'リットル', + 13138 => 'リラ', + 13139 => 'ルピー', + 13140 => 'ルーブル', + 13141 => 'レム', + 13142 => 'レントゲン', + 13143 => 'ワット', + 13144 => '0点', + 13145 => '1点', + 13146 => '2点', + 13147 => '3点', + 13148 => '4点', + 13149 => '5点', + 13150 => '6点', + 13151 => '7点', + 13152 => '8点', + 13153 => '9点', + 13154 => '10点', + 13155 => '11点', + 13156 => '12点', + 13157 => '13点', + 13158 => '14点', + 13159 => '15点', + 13160 => '16点', + 13161 => '17点', + 13162 => '18点', + 13163 => '19点', + 13164 => '20点', + 13165 => '21点', + 13166 => '22点', + 13167 => '23点', + 13168 => '24点', + 13169 => 'hpa', + 13170 => 'da', + 13171 => 'au', + 13172 => 'bar', + 13173 => 'ov', + 13174 => 'pc', + 13175 => 'dm', + 13176 => 'dm2', + 13177 => 'dm3', + 13178 => 'iu', + 13179 => '平成', + 13180 => '昭和', + 13181 => '大正', + 13182 => '明治', + 13183 => '株式会社', + 13184 => 'pa', + 13185 => 'na', + 13186 => 'μa', + 13187 => 'ma', + 13188 => 'ka', + 13189 => 'kb', + 13190 => 'mb', + 13191 => 'gb', + 13192 => 'cal', + 13193 => 'kcal', + 13194 => 'pf', + 13195 => 'nf', + 13196 => 'μf', + 13197 => 'μg', + 13198 => 'mg', + 13199 => 'kg', + 13200 => 'hz', + 13201 => 'khz', + 13202 => 'mhz', + 13203 => 'ghz', + 13204 => 'thz', + 13205 => 'μl', + 13206 => 'ml', + 13207 => 'dl', + 13208 => 'kl', + 13209 => 'fm', + 13210 => 'nm', + 13211 => 'μm', + 13212 => 'mm', + 13213 => 'cm', + 13214 => 'km', + 13215 => 'mm2', + 13216 => 'cm2', + 13217 => 'm2', + 13218 => 'km2', + 13219 => 'mm3', + 13220 => 'cm3', + 13221 => 'm3', + 13222 => 'km3', + 13223 => 'm∕s', + 13224 => 'm∕s2', + 13225 => 'pa', + 13226 => 'kpa', + 13227 => 'mpa', + 13228 => 'gpa', + 13229 => 'rad', + 13230 => 'rad∕s', + 13231 => 'rad∕s2', + 13232 => 'ps', + 13233 => 'ns', + 13234 => 'μs', + 13235 => 'ms', + 13236 => 'pv', + 13237 => 'nv', + 13238 => 'μv', + 13239 => 'mv', + 13240 => 'kv', + 13241 => 'mv', + 13242 => 'pw', + 13243 => 'nw', + 13244 => 'μw', + 13245 => 'mw', + 13246 => 'kw', + 13247 => 'mw', + 13248 => 'kω', + 13249 => 'mω', + 13251 => 'bq', + 13252 => 'cc', + 13253 => 'cd', + 13254 => 'c∕kg', + 13256 => 'db', + 13257 => 'gy', + 13258 => 'ha', + 13259 => 'hp', + 13260 => 'in', + 13261 => 'kk', + 13262 => 'km', + 13263 => 'kt', + 13264 => 'lm', + 13265 => 'ln', + 13266 => 'log', + 13267 => 'lx', + 13268 => 'mb', + 13269 => 'mil', + 13270 => 'mol', + 13271 => 'ph', + 13273 => 'ppm', + 13274 => 'pr', + 13275 => 'sr', + 13276 => 'sv', + 13277 => 'wb', + 13278 => 'v∕m', + 13279 => 'a∕m', + 13280 => '1日', + 13281 => '2日', + 13282 => '3日', + 13283 => '4日', + 13284 => '5日', + 13285 => '6日', + 13286 => '7日', + 13287 => '8日', + 13288 => '9日', + 13289 => '10日', + 13290 => '11日', + 13291 => '12日', + 13292 => '13日', + 13293 => '14日', + 13294 => '15日', + 13295 => '16日', + 13296 => '17日', + 13297 => '18日', + 13298 => '19日', + 13299 => '20日', + 13300 => '21日', + 13301 => '22日', + 13302 => '23日', + 13303 => '24日', + 13304 => '25日', + 13305 => '26日', + 13306 => '27日', + 13307 => '28日', + 13308 => '29日', + 13309 => '30日', + 13310 => '31日', + 13311 => 'gal', + 42560 => 'ꙁ', + 42562 => 'ꙃ', + 42564 => 'ꙅ', + 42566 => 'ꙇ', + 42568 => 'ꙉ', + 42570 => 'ꙋ', + 42572 => 'ꙍ', + 42574 => 'ꙏ', + 42576 => 'ꙑ', + 42578 => 'ꙓ', + 42580 => 'ꙕ', + 42582 => 'ꙗ', + 42584 => 'ꙙ', + 42586 => 'ꙛ', + 42588 => 'ꙝ', + 42590 => 'ꙟ', + 42592 => 'ꙡ', + 42594 => 'ꙣ', + 42596 => 'ꙥ', + 42598 => 'ꙧ', + 42600 => 'ꙩ', + 42602 => 'ꙫ', + 42604 => 'ꙭ', + 42624 => 'ꚁ', + 42626 => 'ꚃ', + 42628 => 'ꚅ', + 42630 => 'ꚇ', + 42632 => 'ꚉ', + 42634 => 'ꚋ', + 42636 => 'ꚍ', + 42638 => 'ꚏ', + 42640 => 'ꚑ', + 42642 => 'ꚓ', + 42644 => 'ꚕ', + 42646 => 'ꚗ', + 42648 => 'ꚙ', + 42650 => 'ꚛ', + 42652 => 'ъ', + 42653 => 'ь', + 42786 => 'ꜣ', + 42788 => 'ꜥ', + 42790 => 'ꜧ', + 42792 => 'ꜩ', + 42794 => 'ꜫ', + 42796 => 'ꜭ', + 42798 => 'ꜯ', + 42802 => 'ꜳ', + 42804 => 'ꜵ', + 42806 => 'ꜷ', + 42808 => 'ꜹ', + 42810 => 'ꜻ', + 42812 => 'ꜽ', + 42814 => 'ꜿ', + 42816 => 'ꝁ', + 42818 => 'ꝃ', + 42820 => 'ꝅ', + 42822 => 'ꝇ', + 42824 => 'ꝉ', + 42826 => 'ꝋ', + 42828 => 'ꝍ', + 42830 => 'ꝏ', + 42832 => 'ꝑ', + 42834 => 'ꝓ', + 42836 => 'ꝕ', + 42838 => 'ꝗ', + 42840 => 'ꝙ', + 42842 => 'ꝛ', + 42844 => 'ꝝ', + 42846 => 'ꝟ', + 42848 => 'ꝡ', + 42850 => 'ꝣ', + 42852 => 'ꝥ', + 42854 => 'ꝧ', + 42856 => 'ꝩ', + 42858 => 'ꝫ', + 42860 => 'ꝭ', + 42862 => 'ꝯ', + 42864 => 'ꝯ', + 42873 => 'ꝺ', + 42875 => 'ꝼ', + 42877 => 'ᵹ', + 42878 => 'ꝿ', + 42880 => 'ꞁ', + 42882 => 'ꞃ', + 42884 => 'ꞅ', + 42886 => 'ꞇ', + 42891 => 'ꞌ', + 42893 => 'ɥ', + 42896 => 'ꞑ', + 42898 => 'ꞓ', + 42902 => 'ꞗ', + 42904 => 'ꞙ', + 42906 => 'ꞛ', + 42908 => 'ꞝ', + 42910 => 'ꞟ', + 42912 => 'ꞡ', + 42914 => 'ꞣ', + 42916 => 'ꞥ', + 42918 => 'ꞧ', + 42920 => 'ꞩ', + 42922 => 'ɦ', + 42923 => 'ɜ', + 42924 => 'ɡ', + 42925 => 'ɬ', + 42926 => 'ɪ', + 42928 => 'ʞ', + 42929 => 'ʇ', + 42930 => 'ʝ', + 42931 => 'ꭓ', + 42932 => 'ꞵ', + 42934 => 'ꞷ', + 42936 => 'ꞹ', + 42938 => 'ꞻ', + 42940 => 'ꞽ', + 42942 => 'ꞿ', + 42946 => 'ꟃ', + 42948 => 'ꞔ', + 42949 => 'ʂ', + 42950 => 'ᶎ', + 42951 => 'ꟈ', + 42953 => 'ꟊ', + 42997 => 'ꟶ', + 43000 => 'ħ', + 43001 => 'œ', + 43868 => 'ꜧ', + 43869 => 'ꬷ', + 43870 => 'ɫ', + 43871 => 'ꭒ', + 43881 => 'ʍ', + 43888 => 'Ꭰ', + 43889 => 'Ꭱ', + 43890 => 'Ꭲ', + 43891 => 'Ꭳ', + 43892 => 'Ꭴ', + 43893 => 'Ꭵ', + 43894 => 'Ꭶ', + 43895 => 'Ꭷ', + 43896 => 'Ꭸ', + 43897 => 'Ꭹ', + 43898 => 'Ꭺ', + 43899 => 'Ꭻ', + 43900 => 'Ꭼ', + 43901 => 'Ꭽ', + 43902 => 'Ꭾ', + 43903 => 'Ꭿ', + 43904 => 'Ꮀ', + 43905 => 'Ꮁ', + 43906 => 'Ꮂ', + 43907 => 'Ꮃ', + 43908 => 'Ꮄ', + 43909 => 'Ꮅ', + 43910 => 'Ꮆ', + 43911 => 'Ꮇ', + 43912 => 'Ꮈ', + 43913 => 'Ꮉ', + 43914 => 'Ꮊ', + 43915 => 'Ꮋ', + 43916 => 'Ꮌ', + 43917 => 'Ꮍ', + 43918 => 'Ꮎ', + 43919 => 'Ꮏ', + 43920 => 'Ꮐ', + 43921 => 'Ꮑ', + 43922 => 'Ꮒ', + 43923 => 'Ꮓ', + 43924 => 'Ꮔ', + 43925 => 'Ꮕ', + 43926 => 'Ꮖ', + 43927 => 'Ꮗ', + 43928 => 'Ꮘ', + 43929 => 'Ꮙ', + 43930 => 'Ꮚ', + 43931 => 'Ꮛ', + 43932 => 'Ꮜ', + 43933 => 'Ꮝ', + 43934 => 'Ꮞ', + 43935 => 'Ꮟ', + 43936 => 'Ꮠ', + 43937 => 'Ꮡ', + 43938 => 'Ꮢ', + 43939 => 'Ꮣ', + 43940 => 'Ꮤ', + 43941 => 'Ꮥ', + 43942 => 'Ꮦ', + 43943 => 'Ꮧ', + 43944 => 'Ꮨ', + 43945 => 'Ꮩ', + 43946 => 'Ꮪ', + 43947 => 'Ꮫ', + 43948 => 'Ꮬ', + 43949 => 'Ꮭ', + 43950 => 'Ꮮ', + 43951 => 'Ꮯ', + 43952 => 'Ꮰ', + 43953 => 'Ꮱ', + 43954 => 'Ꮲ', + 43955 => 'Ꮳ', + 43956 => 'Ꮴ', + 43957 => 'Ꮵ', + 43958 => 'Ꮶ', + 43959 => 'Ꮷ', + 43960 => 'Ꮸ', + 43961 => 'Ꮹ', + 43962 => 'Ꮺ', + 43963 => 'Ꮻ', + 43964 => 'Ꮼ', + 43965 => 'Ꮽ', + 43966 => 'Ꮾ', + 43967 => 'Ꮿ', + 63744 => '豈', + 63745 => '更', + 63746 => '車', + 63747 => '賈', + 63748 => '滑', + 63749 => '串', + 63750 => '句', + 63751 => '龜', + 63752 => '龜', + 63753 => '契', + 63754 => '金', + 63755 => '喇', + 63756 => '奈', + 63757 => '懶', + 63758 => '癩', + 63759 => '羅', + 63760 => '蘿', + 63761 => '螺', + 63762 => '裸', + 63763 => '邏', + 63764 => '樂', + 63765 => '洛', + 63766 => '烙', + 63767 => '珞', + 63768 => '落', + 63769 => '酪', + 63770 => '駱', + 63771 => '亂', + 63772 => '卵', + 63773 => '欄', + 63774 => '爛', + 63775 => '蘭', + 63776 => '鸞', + 63777 => '嵐', + 63778 => '濫', + 63779 => '藍', + 63780 => '襤', + 63781 => '拉', + 63782 => '臘', + 63783 => '蠟', + 63784 => '廊', + 63785 => '朗', + 63786 => '浪', + 63787 => '狼', + 63788 => '郎', + 63789 => '來', + 63790 => '冷', + 63791 => '勞', + 63792 => '擄', + 63793 => '櫓', + 63794 => '爐', + 63795 => '盧', + 63796 => '老', + 63797 => '蘆', + 63798 => '虜', + 63799 => '路', + 63800 => '露', + 63801 => '魯', + 63802 => '鷺', + 63803 => '碌', + 63804 => '祿', + 63805 => '綠', + 63806 => '菉', + 63807 => '錄', + 63808 => '鹿', + 63809 => '論', + 63810 => '壟', + 63811 => '弄', + 63812 => '籠', + 63813 => '聾', + 63814 => '牢', + 63815 => '磊', + 63816 => '賂', + 63817 => '雷', + 63818 => '壘', + 63819 => '屢', + 63820 => '樓', + 63821 => '淚', + 63822 => '漏', + 63823 => '累', + 63824 => '縷', + 63825 => '陋', + 63826 => '勒', + 63827 => '肋', + 63828 => '凜', + 63829 => '凌', + 63830 => '稜', + 63831 => '綾', + 63832 => '菱', + 63833 => '陵', + 63834 => '讀', + 63835 => '拏', + 63836 => '樂', + 63837 => '諾', + 63838 => '丹', + 63839 => '寧', + 63840 => '怒', + 63841 => '率', + 63842 => '異', + 63843 => '北', + 63844 => '磻', + 63845 => '便', + 63846 => '復', + 63847 => '不', + 63848 => '泌', + 63849 => '數', + 63850 => '索', + 63851 => '參', + 63852 => '塞', + 63853 => '省', + 63854 => '葉', + 63855 => '說', + 63856 => '殺', + 63857 => '辰', + 63858 => '沈', + 63859 => '拾', + 63860 => '若', + 63861 => '掠', + 63862 => '略', + 63863 => '亮', + 63864 => '兩', + 63865 => '凉', + 63866 => '梁', + 63867 => '糧', + 63868 => '良', + 63869 => '諒', + 63870 => '量', + 63871 => '勵', + 63872 => '呂', + 63873 => '女', + 63874 => '廬', + 63875 => '旅', + 63876 => '濾', + 63877 => '礪', + 63878 => '閭', + 63879 => '驪', + 63880 => '麗', + 63881 => '黎', + 63882 => '力', + 63883 => '曆', + 63884 => '歷', + 63885 => '轢', + 63886 => '年', + 63887 => '憐', + 63888 => '戀', + 63889 => '撚', + 63890 => '漣', + 63891 => '煉', + 63892 => '璉', + 63893 => '秊', + 63894 => '練', + 63895 => '聯', + 63896 => '輦', + 63897 => '蓮', + 63898 => '連', + 63899 => '鍊', + 63900 => '列', + 63901 => '劣', + 63902 => '咽', + 63903 => '烈', + 63904 => '裂', + 63905 => '說', + 63906 => '廉', + 63907 => '念', + 63908 => '捻', + 63909 => '殮', + 63910 => '簾', + 63911 => '獵', + 63912 => '令', + 63913 => '囹', + 63914 => '寧', + 63915 => '嶺', + 63916 => '怜', + 63917 => '玲', + 63918 => '瑩', + 63919 => '羚', + 63920 => '聆', + 63921 => '鈴', + 63922 => '零', + 63923 => '靈', + 63924 => '領', + 63925 => '例', + 63926 => '禮', + 63927 => '醴', + 63928 => '隸', + 63929 => '惡', + 63930 => '了', + 63931 => '僚', + 63932 => '寮', + 63933 => '尿', + 63934 => '料', + 63935 => '樂', + 63936 => '燎', + 63937 => '療', + 63938 => '蓼', + 63939 => '遼', + 63940 => '龍', + 63941 => '暈', + 63942 => '阮', + 63943 => '劉', + 63944 => '杻', + 63945 => '柳', + 63946 => '流', + 63947 => '溜', + 63948 => '琉', + 63949 => '留', + 63950 => '硫', + 63951 => '紐', + 63952 => '類', + 63953 => '六', + 63954 => '戮', + 63955 => '陸', + 63956 => '倫', + 63957 => '崙', + 63958 => '淪', + 63959 => '輪', + 63960 => '律', + 63961 => '慄', + 63962 => '栗', + 63963 => '率', + 63964 => '隆', + 63965 => '利', + 63966 => '吏', + 63967 => '履', + 63968 => '易', + 63969 => '李', + 63970 => '梨', + 63971 => '泥', + 63972 => '理', + 63973 => '痢', + 63974 => '罹', + 63975 => '裏', + 63976 => '裡', + 63977 => '里', + 63978 => '離', + 63979 => '匿', + 63980 => '溺', + 63981 => '吝', + 63982 => '燐', + 63983 => '璘', + 63984 => '藺', + 63985 => '隣', + 63986 => '鱗', + 63987 => '麟', + 63988 => '林', + 63989 => '淋', + 63990 => '臨', + 63991 => '立', + 63992 => '笠', + 63993 => '粒', + 63994 => '狀', + 63995 => '炙', + 63996 => '識', + 63997 => '什', + 63998 => '茶', + 63999 => '刺', + 64000 => '切', + 64001 => '度', + 64002 => '拓', + 64003 => '糖', + 64004 => '宅', + 64005 => '洞', + 64006 => '暴', + 64007 => '輻', + 64008 => '行', + 64009 => '降', + 64010 => '見', + 64011 => '廓', + 64012 => '兀', + 64013 => '嗀', + 64016 => '塚', + 64018 => '晴', + 64021 => '凞', + 64022 => '猪', + 64023 => '益', + 64024 => '礼', + 64025 => '神', + 64026 => '祥', + 64027 => '福', + 64028 => '靖', + 64029 => '精', + 64030 => '羽', + 64032 => '蘒', + 64034 => '諸', + 64037 => '逸', + 64038 => '都', + 64042 => '飯', + 64043 => '飼', + 64044 => '館', + 64045 => '鶴', + 64046 => '郞', + 64047 => '隷', + 64048 => '侮', + 64049 => '僧', + 64050 => '免', + 64051 => '勉', + 64052 => '勤', + 64053 => '卑', + 64054 => '喝', + 64055 => '嘆', + 64056 => '器', + 64057 => '塀', + 64058 => '墨', + 64059 => '層', + 64060 => '屮', + 64061 => '悔', + 64062 => '慨', + 64063 => '憎', + 64064 => '懲', + 64065 => '敏', + 64066 => '既', + 64067 => '暑', + 64068 => '梅', + 64069 => '海', + 64070 => '渚', + 64071 => '漢', + 64072 => '煮', + 64073 => '爫', + 64074 => '琢', + 64075 => '碑', + 64076 => '社', + 64077 => '祉', + 64078 => '祈', + 64079 => '祐', + 64080 => '祖', + 64081 => '祝', + 64082 => '禍', + 64083 => '禎', + 64084 => '穀', + 64085 => '突', + 64086 => '節', + 64087 => '練', + 64088 => '縉', + 64089 => '繁', + 64090 => '署', + 64091 => '者', + 64092 => '臭', + 64093 => '艹', + 64094 => '艹', + 64095 => '著', + 64096 => '褐', + 64097 => '視', + 64098 => '謁', + 64099 => '謹', + 64100 => '賓', + 64101 => '贈', + 64102 => '辶', + 64103 => '逸', + 64104 => '難', + 64105 => '響', + 64106 => '頻', + 64107 => '恵', + 64108 => '𤋮', + 64109 => '舘', + 64112 => '並', + 64113 => '况', + 64114 => '全', + 64115 => '侀', + 64116 => '充', + 64117 => '冀', + 64118 => '勇', + 64119 => '勺', + 64120 => '喝', + 64121 => '啕', + 64122 => '喙', + 64123 => '嗢', + 64124 => '塚', + 64125 => '墳', + 64126 => '奄', + 64127 => '奔', + 64128 => '婢', + 64129 => '嬨', + 64130 => '廒', + 64131 => '廙', + 64132 => '彩', + 64133 => '徭', + 64134 => '惘', + 64135 => '慎', + 64136 => '愈', + 64137 => '憎', + 64138 => '慠', + 64139 => '懲', + 64140 => '戴', + 64141 => '揄', + 64142 => '搜', + 64143 => '摒', + 64144 => '敖', + 64145 => '晴', + 64146 => '朗', + 64147 => '望', + 64148 => '杖', + 64149 => '歹', + 64150 => '殺', + 64151 => '流', + 64152 => '滛', + 64153 => '滋', + 64154 => '漢', + 64155 => '瀞', + 64156 => '煮', + 64157 => '瞧', + 64158 => '爵', + 64159 => '犯', + 64160 => '猪', + 64161 => '瑱', + 64162 => '甆', + 64163 => '画', + 64164 => '瘝', + 64165 => '瘟', + 64166 => '益', + 64167 => '盛', + 64168 => '直', + 64169 => '睊', + 64170 => '着', + 64171 => '磌', + 64172 => '窱', + 64173 => '節', + 64174 => '类', + 64175 => '絛', + 64176 => '練', + 64177 => '缾', + 64178 => '者', + 64179 => '荒', + 64180 => '華', + 64181 => '蝹', + 64182 => '襁', + 64183 => '覆', + 64184 => '視', + 64185 => '調', + 64186 => '諸', + 64187 => '請', + 64188 => '謁', + 64189 => '諾', + 64190 => '諭', + 64191 => '謹', + 64192 => '變', + 64193 => '贈', + 64194 => '輸', + 64195 => '遲', + 64196 => '醙', + 64197 => '鉶', + 64198 => '陼', + 64199 => '難', + 64200 => '靖', + 64201 => '韛', + 64202 => '響', + 64203 => '頋', + 64204 => '頻', + 64205 => '鬒', + 64206 => '龜', + 64207 => '𢡊', + 64208 => '𢡄', + 64209 => '𣏕', + 64210 => '㮝', + 64211 => '䀘', + 64212 => '䀹', + 64213 => '𥉉', + 64214 => '𥳐', + 64215 => '𧻓', + 64216 => '齃', + 64217 => '龎', + 64256 => 'ff', + 64257 => 'fi', + 64258 => 'fl', + 64259 => 'ffi', + 64260 => 'ffl', + 64261 => 'st', + 64262 => 'st', + 64275 => 'մն', + 64276 => 'մե', + 64277 => 'մի', + 64278 => 'վն', + 64279 => 'մխ', + 64285 => 'יִ', + 64287 => 'ײַ', + 64288 => 'ע', + 64289 => 'א', + 64290 => 'ד', + 64291 => 'ה', + 64292 => 'כ', + 64293 => 'ל', + 64294 => 'ם', + 64295 => 'ר', + 64296 => 'ת', + 64298 => 'שׁ', + 64299 => 'שׂ', + 64300 => 'שּׁ', + 64301 => 'שּׂ', + 64302 => 'אַ', + 64303 => 'אָ', + 64304 => 'אּ', + 64305 => 'בּ', + 64306 => 'גּ', + 64307 => 'דּ', + 64308 => 'הּ', + 64309 => 'וּ', + 64310 => 'זּ', + 64312 => 'טּ', + 64313 => 'יּ', + 64314 => 'ךּ', + 64315 => 'כּ', + 64316 => 'לּ', + 64318 => 'מּ', + 64320 => 'נּ', + 64321 => 'סּ', + 64323 => 'ףּ', + 64324 => 'פּ', + 64326 => 'צּ', + 64327 => 'קּ', + 64328 => 'רּ', + 64329 => 'שּ', + 64330 => 'תּ', + 64331 => 'וֹ', + 64332 => 'בֿ', + 64333 => 'כֿ', + 64334 => 'פֿ', + 64335 => 'אל', + 64336 => 'ٱ', + 64337 => 'ٱ', + 64338 => 'ٻ', + 64339 => 'ٻ', + 64340 => 'ٻ', + 64341 => 'ٻ', + 64342 => 'پ', + 64343 => 'پ', + 64344 => 'پ', + 64345 => 'پ', + 64346 => 'ڀ', + 64347 => 'ڀ', + 64348 => 'ڀ', + 64349 => 'ڀ', + 64350 => 'ٺ', + 64351 => 'ٺ', + 64352 => 'ٺ', + 64353 => 'ٺ', + 64354 => 'ٿ', + 64355 => 'ٿ', + 64356 => 'ٿ', + 64357 => 'ٿ', + 64358 => 'ٹ', + 64359 => 'ٹ', + 64360 => 'ٹ', + 64361 => 'ٹ', + 64362 => 'ڤ', + 64363 => 'ڤ', + 64364 => 'ڤ', + 64365 => 'ڤ', + 64366 => 'ڦ', + 64367 => 'ڦ', + 64368 => 'ڦ', + 64369 => 'ڦ', + 64370 => 'ڄ', + 64371 => 'ڄ', + 64372 => 'ڄ', + 64373 => 'ڄ', + 64374 => 'ڃ', + 64375 => 'ڃ', + 64376 => 'ڃ', + 64377 => 'ڃ', + 64378 => 'چ', + 64379 => 'چ', + 64380 => 'چ', + 64381 => 'چ', + 64382 => 'ڇ', + 64383 => 'ڇ', + 64384 => 'ڇ', + 64385 => 'ڇ', + 64386 => 'ڍ', + 64387 => 'ڍ', + 64388 => 'ڌ', + 64389 => 'ڌ', + 64390 => 'ڎ', + 64391 => 'ڎ', + 64392 => 'ڈ', + 64393 => 'ڈ', + 64394 => 'ژ', + 64395 => 'ژ', + 64396 => 'ڑ', + 64397 => 'ڑ', + 64398 => 'ک', + 64399 => 'ک', + 64400 => 'ک', + 64401 => 'ک', + 64402 => 'گ', + 64403 => 'گ', + 64404 => 'گ', + 64405 => 'گ', + 64406 => 'ڳ', + 64407 => 'ڳ', + 64408 => 'ڳ', + 64409 => 'ڳ', + 64410 => 'ڱ', + 64411 => 'ڱ', + 64412 => 'ڱ', + 64413 => 'ڱ', + 64414 => 'ں', + 64415 => 'ں', + 64416 => 'ڻ', + 64417 => 'ڻ', + 64418 => 'ڻ', + 64419 => 'ڻ', + 64420 => 'ۀ', + 64421 => 'ۀ', + 64422 => 'ہ', + 64423 => 'ہ', + 64424 => 'ہ', + 64425 => 'ہ', + 64426 => 'ھ', + 64427 => 'ھ', + 64428 => 'ھ', + 64429 => 'ھ', + 64430 => 'ے', + 64431 => 'ے', + 64432 => 'ۓ', + 64433 => 'ۓ', + 64467 => 'ڭ', + 64468 => 'ڭ', + 64469 => 'ڭ', + 64470 => 'ڭ', + 64471 => 'ۇ', + 64472 => 'ۇ', + 64473 => 'ۆ', + 64474 => 'ۆ', + 64475 => 'ۈ', + 64476 => 'ۈ', + 64477 => 'ۇٴ', + 64478 => 'ۋ', + 64479 => 'ۋ', + 64480 => 'ۅ', + 64481 => 'ۅ', + 64482 => 'ۉ', + 64483 => 'ۉ', + 64484 => 'ې', + 64485 => 'ې', + 64486 => 'ې', + 64487 => 'ې', + 64488 => 'ى', + 64489 => 'ى', + 64490 => 'ئا', + 64491 => 'ئا', + 64492 => 'ئە', + 64493 => 'ئە', + 64494 => 'ئو', + 64495 => 'ئو', + 64496 => 'ئۇ', + 64497 => 'ئۇ', + 64498 => 'ئۆ', + 64499 => 'ئۆ', + 64500 => 'ئۈ', + 64501 => 'ئۈ', + 64502 => 'ئې', + 64503 => 'ئې', + 64504 => 'ئې', + 64505 => 'ئى', + 64506 => 'ئى', + 64507 => 'ئى', + 64508 => 'ی', + 64509 => 'ی', + 64510 => 'ی', + 64511 => 'ی', + 64512 => 'ئج', + 64513 => 'ئح', + 64514 => 'ئم', + 64515 => 'ئى', + 64516 => 'ئي', + 64517 => 'بج', + 64518 => 'بح', + 64519 => 'بخ', + 64520 => 'بم', + 64521 => 'بى', + 64522 => 'بي', + 64523 => 'تج', + 64524 => 'تح', + 64525 => 'تخ', + 64526 => 'تم', + 64527 => 'تى', + 64528 => 'تي', + 64529 => 'ثج', + 64530 => 'ثم', + 64531 => 'ثى', + 64532 => 'ثي', + 64533 => 'جح', + 64534 => 'جم', + 64535 => 'حج', + 64536 => 'حم', + 64537 => 'خج', + 64538 => 'خح', + 64539 => 'خم', + 64540 => 'سج', + 64541 => 'سح', + 64542 => 'سخ', + 64543 => 'سم', + 64544 => 'صح', + 64545 => 'صم', + 64546 => 'ضج', + 64547 => 'ضح', + 64548 => 'ضخ', + 64549 => 'ضم', + 64550 => 'طح', + 64551 => 'طم', + 64552 => 'ظم', + 64553 => 'عج', + 64554 => 'عم', + 64555 => 'غج', + 64556 => 'غم', + 64557 => 'فج', + 64558 => 'فح', + 64559 => 'فخ', + 64560 => 'فم', + 64561 => 'فى', + 64562 => 'في', + 64563 => 'قح', + 64564 => 'قم', + 64565 => 'قى', + 64566 => 'قي', + 64567 => 'كا', + 64568 => 'كج', + 64569 => 'كح', + 64570 => 'كخ', + 64571 => 'كل', + 64572 => 'كم', + 64573 => 'كى', + 64574 => 'كي', + 64575 => 'لج', + 64576 => 'لح', + 64577 => 'لخ', + 64578 => 'لم', + 64579 => 'لى', + 64580 => 'لي', + 64581 => 'مج', + 64582 => 'مح', + 64583 => 'مخ', + 64584 => 'مم', + 64585 => 'مى', + 64586 => 'مي', + 64587 => 'نج', + 64588 => 'نح', + 64589 => 'نخ', + 64590 => 'نم', + 64591 => 'نى', + 64592 => 'ني', + 64593 => 'هج', + 64594 => 'هم', + 64595 => 'هى', + 64596 => 'هي', + 64597 => 'يج', + 64598 => 'يح', + 64599 => 'يخ', + 64600 => 'يم', + 64601 => 'يى', + 64602 => 'يي', + 64603 => 'ذٰ', + 64604 => 'رٰ', + 64605 => 'ىٰ', + 64612 => 'ئر', + 64613 => 'ئز', + 64614 => 'ئم', + 64615 => 'ئن', + 64616 => 'ئى', + 64617 => 'ئي', + 64618 => 'بر', + 64619 => 'بز', + 64620 => 'بم', + 64621 => 'بن', + 64622 => 'بى', + 64623 => 'بي', + 64624 => 'تر', + 64625 => 'تز', + 64626 => 'تم', + 64627 => 'تن', + 64628 => 'تى', + 64629 => 'تي', + 64630 => 'ثر', + 64631 => 'ثز', + 64632 => 'ثم', + 64633 => 'ثن', + 64634 => 'ثى', + 64635 => 'ثي', + 64636 => 'فى', + 64637 => 'في', + 64638 => 'قى', + 64639 => 'قي', + 64640 => 'كا', + 64641 => 'كل', + 64642 => 'كم', + 64643 => 'كى', + 64644 => 'كي', + 64645 => 'لم', + 64646 => 'لى', + 64647 => 'لي', + 64648 => 'ما', + 64649 => 'مم', + 64650 => 'نر', + 64651 => 'نز', + 64652 => 'نم', + 64653 => 'نن', + 64654 => 'نى', + 64655 => 'ني', + 64656 => 'ىٰ', + 64657 => 'ير', + 64658 => 'يز', + 64659 => 'يم', + 64660 => 'ين', + 64661 => 'يى', + 64662 => 'يي', + 64663 => 'ئج', + 64664 => 'ئح', + 64665 => 'ئخ', + 64666 => 'ئم', + 64667 => 'ئه', + 64668 => 'بج', + 64669 => 'بح', + 64670 => 'بخ', + 64671 => 'بم', + 64672 => 'به', + 64673 => 'تج', + 64674 => 'تح', + 64675 => 'تخ', + 64676 => 'تم', + 64677 => 'ته', + 64678 => 'ثم', + 64679 => 'جح', + 64680 => 'جم', + 64681 => 'حج', + 64682 => 'حم', + 64683 => 'خج', + 64684 => 'خم', + 64685 => 'سج', + 64686 => 'سح', + 64687 => 'سخ', + 64688 => 'سم', + 64689 => 'صح', + 64690 => 'صخ', + 64691 => 'صم', + 64692 => 'ضج', + 64693 => 'ضح', + 64694 => 'ضخ', + 64695 => 'ضم', + 64696 => 'طح', + 64697 => 'ظم', + 64698 => 'عج', + 64699 => 'عم', + 64700 => 'غج', + 64701 => 'غم', + 64702 => 'فج', + 64703 => 'فح', + 64704 => 'فخ', + 64705 => 'فم', + 64706 => 'قح', + 64707 => 'قم', + 64708 => 'كج', + 64709 => 'كح', + 64710 => 'كخ', + 64711 => 'كل', + 64712 => 'كم', + 64713 => 'لج', + 64714 => 'لح', + 64715 => 'لخ', + 64716 => 'لم', + 64717 => 'له', + 64718 => 'مج', + 64719 => 'مح', + 64720 => 'مخ', + 64721 => 'مم', + 64722 => 'نج', + 64723 => 'نح', + 64724 => 'نخ', + 64725 => 'نم', + 64726 => 'نه', + 64727 => 'هج', + 64728 => 'هم', + 64729 => 'هٰ', + 64730 => 'يج', + 64731 => 'يح', + 64732 => 'يخ', + 64733 => 'يم', + 64734 => 'يه', + 64735 => 'ئم', + 64736 => 'ئه', + 64737 => 'بم', + 64738 => 'به', + 64739 => 'تم', + 64740 => 'ته', + 64741 => 'ثم', + 64742 => 'ثه', + 64743 => 'سم', + 64744 => 'سه', + 64745 => 'شم', + 64746 => 'شه', + 64747 => 'كل', + 64748 => 'كم', + 64749 => 'لم', + 64750 => 'نم', + 64751 => 'نه', + 64752 => 'يم', + 64753 => 'يه', + 64754 => 'ـَّ', + 64755 => 'ـُّ', + 64756 => 'ـِّ', + 64757 => 'طى', + 64758 => 'طي', + 64759 => 'عى', + 64760 => 'عي', + 64761 => 'غى', + 64762 => 'غي', + 64763 => 'سى', + 64764 => 'سي', + 64765 => 'شى', + 64766 => 'شي', + 64767 => 'حى', + 64768 => 'حي', + 64769 => 'جى', + 64770 => 'جي', + 64771 => 'خى', + 64772 => 'خي', + 64773 => 'صى', + 64774 => 'صي', + 64775 => 'ضى', + 64776 => 'ضي', + 64777 => 'شج', + 64778 => 'شح', + 64779 => 'شخ', + 64780 => 'شم', + 64781 => 'شر', + 64782 => 'سر', + 64783 => 'صر', + 64784 => 'ضر', + 64785 => 'طى', + 64786 => 'طي', + 64787 => 'عى', + 64788 => 'عي', + 64789 => 'غى', + 64790 => 'غي', + 64791 => 'سى', + 64792 => 'سي', + 64793 => 'شى', + 64794 => 'شي', + 64795 => 'حى', + 64796 => 'حي', + 64797 => 'جى', + 64798 => 'جي', + 64799 => 'خى', + 64800 => 'خي', + 64801 => 'صى', + 64802 => 'صي', + 64803 => 'ضى', + 64804 => 'ضي', + 64805 => 'شج', + 64806 => 'شح', + 64807 => 'شخ', + 64808 => 'شم', + 64809 => 'شر', + 64810 => 'سر', + 64811 => 'صر', + 64812 => 'ضر', + 64813 => 'شج', + 64814 => 'شح', + 64815 => 'شخ', + 64816 => 'شم', + 64817 => 'سه', + 64818 => 'شه', + 64819 => 'طم', + 64820 => 'سج', + 64821 => 'سح', + 64822 => 'سخ', + 64823 => 'شج', + 64824 => 'شح', + 64825 => 'شخ', + 64826 => 'طم', + 64827 => 'ظم', + 64828 => 'اً', + 64829 => 'اً', + 64848 => 'تجم', + 64849 => 'تحج', + 64850 => 'تحج', + 64851 => 'تحم', + 64852 => 'تخم', + 64853 => 'تمج', + 64854 => 'تمح', + 64855 => 'تمخ', + 64856 => 'جمح', + 64857 => 'جمح', + 64858 => 'حمي', + 64859 => 'حمى', + 64860 => 'سحج', + 64861 => 'سجح', + 64862 => 'سجى', + 64863 => 'سمح', + 64864 => 'سمح', + 64865 => 'سمج', + 64866 => 'سمم', + 64867 => 'سمم', + 64868 => 'صحح', + 64869 => 'صحح', + 64870 => 'صمم', + 64871 => 'شحم', + 64872 => 'شحم', + 64873 => 'شجي', + 64874 => 'شمخ', + 64875 => 'شمخ', + 64876 => 'شمم', + 64877 => 'شمم', + 64878 => 'ضحى', + 64879 => 'ضخم', + 64880 => 'ضخم', + 64881 => 'طمح', + 64882 => 'طمح', + 64883 => 'طمم', + 64884 => 'طمي', + 64885 => 'عجم', + 64886 => 'عمم', + 64887 => 'عمم', + 64888 => 'عمى', + 64889 => 'غمم', + 64890 => 'غمي', + 64891 => 'غمى', + 64892 => 'فخم', + 64893 => 'فخم', + 64894 => 'قمح', + 64895 => 'قمم', + 64896 => 'لحم', + 64897 => 'لحي', + 64898 => 'لحى', + 64899 => 'لجج', + 64900 => 'لجج', + 64901 => 'لخم', + 64902 => 'لخم', + 64903 => 'لمح', + 64904 => 'لمح', + 64905 => 'محج', + 64906 => 'محم', + 64907 => 'محي', + 64908 => 'مجح', + 64909 => 'مجم', + 64910 => 'مخج', + 64911 => 'مخم', + 64914 => 'مجخ', + 64915 => 'همج', + 64916 => 'همم', + 64917 => 'نحم', + 64918 => 'نحى', + 64919 => 'نجم', + 64920 => 'نجم', + 64921 => 'نجى', + 64922 => 'نمي', + 64923 => 'نمى', + 64924 => 'يمم', + 64925 => 'يمم', + 64926 => 'بخي', + 64927 => 'تجي', + 64928 => 'تجى', + 64929 => 'تخي', + 64930 => 'تخى', + 64931 => 'تمي', + 64932 => 'تمى', + 64933 => 'جمي', + 64934 => 'جحى', + 64935 => 'جمى', + 64936 => 'سخى', + 64937 => 'صحي', + 64938 => 'شحي', + 64939 => 'ضحي', + 64940 => 'لجي', + 64941 => 'لمي', + 64942 => 'يحي', + 64943 => 'يجي', + 64944 => 'يمي', + 64945 => 'ممي', + 64946 => 'قمي', + 64947 => 'نحي', + 64948 => 'قمح', + 64949 => 'لحم', + 64950 => 'عمي', + 64951 => 'كمي', + 64952 => 'نجح', + 64953 => 'مخي', + 64954 => 'لجم', + 64955 => 'كمم', + 64956 => 'لجم', + 64957 => 'نجح', + 64958 => 'جحي', + 64959 => 'حجي', + 64960 => 'مجي', + 64961 => 'فمي', + 64962 => 'بحي', + 64963 => 'كمم', + 64964 => 'عجم', + 64965 => 'صمم', + 64966 => 'سخي', + 64967 => 'نجي', + 65008 => 'صلے', + 65009 => 'قلے', + 65010 => 'الله', + 65011 => 'اكبر', + 65012 => 'محمد', + 65013 => 'صلعم', + 65014 => 'رسول', + 65015 => 'عليه', + 65016 => 'وسلم', + 65017 => 'صلى', + 65020 => 'ریال', + 65041 => '、', + 65047 => '〖', + 65048 => '〗', + 65073 => '—', + 65074 => '–', + 65081 => '〔', + 65082 => '〕', + 65083 => '【', + 65084 => '】', + 65085 => '《', + 65086 => '》', + 65087 => '〈', + 65088 => '〉', + 65089 => '「', + 65090 => '」', + 65091 => '『', + 65092 => '』', + 65105 => '、', + 65112 => '—', + 65117 => '〔', + 65118 => '〕', + 65123 => '-', + 65137 => 'ـً', + 65143 => 'ـَ', + 65145 => 'ـُ', + 65147 => 'ـِ', + 65149 => 'ـّ', + 65151 => 'ـْ', + 65152 => 'ء', + 65153 => 'آ', + 65154 => 'آ', + 65155 => 'أ', + 65156 => 'أ', + 65157 => 'ؤ', + 65158 => 'ؤ', + 65159 => 'إ', + 65160 => 'إ', + 65161 => 'ئ', + 65162 => 'ئ', + 65163 => 'ئ', + 65164 => 'ئ', + 65165 => 'ا', + 65166 => 'ا', + 65167 => 'ب', + 65168 => 'ب', + 65169 => 'ب', + 65170 => 'ب', + 65171 => 'ة', + 65172 => 'ة', + 65173 => 'ت', + 65174 => 'ت', + 65175 => 'ت', + 65176 => 'ت', + 65177 => 'ث', + 65178 => 'ث', + 65179 => 'ث', + 65180 => 'ث', + 65181 => 'ج', + 65182 => 'ج', + 65183 => 'ج', + 65184 => 'ج', + 65185 => 'ح', + 65186 => 'ح', + 65187 => 'ح', + 65188 => 'ح', + 65189 => 'خ', + 65190 => 'خ', + 65191 => 'خ', + 65192 => 'خ', + 65193 => 'د', + 65194 => 'د', + 65195 => 'ذ', + 65196 => 'ذ', + 65197 => 'ر', + 65198 => 'ر', + 65199 => 'ز', + 65200 => 'ز', + 65201 => 'س', + 65202 => 'س', + 65203 => 'س', + 65204 => 'س', + 65205 => 'ش', + 65206 => 'ش', + 65207 => 'ش', + 65208 => 'ش', + 65209 => 'ص', + 65210 => 'ص', + 65211 => 'ص', + 65212 => 'ص', + 65213 => 'ض', + 65214 => 'ض', + 65215 => 'ض', + 65216 => 'ض', + 65217 => 'ط', + 65218 => 'ط', + 65219 => 'ط', + 65220 => 'ط', + 65221 => 'ظ', + 65222 => 'ظ', + 65223 => 'ظ', + 65224 => 'ظ', + 65225 => 'ع', + 65226 => 'ع', + 65227 => 'ع', + 65228 => 'ع', + 65229 => 'غ', + 65230 => 'غ', + 65231 => 'غ', + 65232 => 'غ', + 65233 => 'ف', + 65234 => 'ف', + 65235 => 'ف', + 65236 => 'ف', + 65237 => 'ق', + 65238 => 'ق', + 65239 => 'ق', + 65240 => 'ق', + 65241 => 'ك', + 65242 => 'ك', + 65243 => 'ك', + 65244 => 'ك', + 65245 => 'ل', + 65246 => 'ل', + 65247 => 'ل', + 65248 => 'ل', + 65249 => 'م', + 65250 => 'م', + 65251 => 'م', + 65252 => 'م', + 65253 => 'ن', + 65254 => 'ن', + 65255 => 'ن', + 65256 => 'ن', + 65257 => 'ه', + 65258 => 'ه', + 65259 => 'ه', + 65260 => 'ه', + 65261 => 'و', + 65262 => 'و', + 65263 => 'ى', + 65264 => 'ى', + 65265 => 'ي', + 65266 => 'ي', + 65267 => 'ي', + 65268 => 'ي', + 65269 => 'لآ', + 65270 => 'لآ', + 65271 => 'لأ', + 65272 => 'لأ', + 65273 => 'لإ', + 65274 => 'لإ', + 65275 => 'لا', + 65276 => 'لا', + 65293 => '-', + 65294 => '.', + 65296 => '0', + 65297 => '1', + 65298 => '2', + 65299 => '3', + 65300 => '4', + 65301 => '5', + 65302 => '6', + 65303 => '7', + 65304 => '8', + 65305 => '9', + 65313 => 'a', + 65314 => 'b', + 65315 => 'c', + 65316 => 'd', + 65317 => 'e', + 65318 => 'f', + 65319 => 'g', + 65320 => 'h', + 65321 => 'i', + 65322 => 'j', + 65323 => 'k', + 65324 => 'l', + 65325 => 'm', + 65326 => 'n', + 65327 => 'o', + 65328 => 'p', + 65329 => 'q', + 65330 => 'r', + 65331 => 's', + 65332 => 't', + 65333 => 'u', + 65334 => 'v', + 65335 => 'w', + 65336 => 'x', + 65337 => 'y', + 65338 => 'z', + 65345 => 'a', + 65346 => 'b', + 65347 => 'c', + 65348 => 'd', + 65349 => 'e', + 65350 => 'f', + 65351 => 'g', + 65352 => 'h', + 65353 => 'i', + 65354 => 'j', + 65355 => 'k', + 65356 => 'l', + 65357 => 'm', + 65358 => 'n', + 65359 => 'o', + 65360 => 'p', + 65361 => 'q', + 65362 => 'r', + 65363 => 's', + 65364 => 't', + 65365 => 'u', + 65366 => 'v', + 65367 => 'w', + 65368 => 'x', + 65369 => 'y', + 65370 => 'z', + 65375 => '⦅', + 65376 => '⦆', + 65377 => '.', + 65378 => '「', + 65379 => '」', + 65380 => '、', + 65381 => '・', + 65382 => 'ヲ', + 65383 => 'ァ', + 65384 => 'ィ', + 65385 => 'ゥ', + 65386 => 'ェ', + 65387 => 'ォ', + 65388 => 'ャ', + 65389 => 'ュ', + 65390 => 'ョ', + 65391 => 'ッ', + 65392 => 'ー', + 65393 => 'ア', + 65394 => 'イ', + 65395 => 'ウ', + 65396 => 'エ', + 65397 => 'オ', + 65398 => 'カ', + 65399 => 'キ', + 65400 => 'ク', + 65401 => 'ケ', + 65402 => 'コ', + 65403 => 'サ', + 65404 => 'シ', + 65405 => 'ス', + 65406 => 'セ', + 65407 => 'ソ', + 65408 => 'タ', + 65409 => 'チ', + 65410 => 'ツ', + 65411 => 'テ', + 65412 => 'ト', + 65413 => 'ナ', + 65414 => 'ニ', + 65415 => 'ヌ', + 65416 => 'ネ', + 65417 => 'ノ', + 65418 => 'ハ', + 65419 => 'ヒ', + 65420 => 'フ', + 65421 => 'ヘ', + 65422 => 'ホ', + 65423 => 'マ', + 65424 => 'ミ', + 65425 => 'ム', + 65426 => 'メ', + 65427 => 'モ', + 65428 => 'ヤ', + 65429 => 'ユ', + 65430 => 'ヨ', + 65431 => 'ラ', + 65432 => 'リ', + 65433 => 'ル', + 65434 => 'レ', + 65435 => 'ロ', + 65436 => 'ワ', + 65437 => 'ン', + 65438 => '゙', + 65439 => '゚', + 65441 => 'ᄀ', + 65442 => 'ᄁ', + 65443 => 'ᆪ', + 65444 => 'ᄂ', + 65445 => 'ᆬ', + 65446 => 'ᆭ', + 65447 => 'ᄃ', + 65448 => 'ᄄ', + 65449 => 'ᄅ', + 65450 => 'ᆰ', + 65451 => 'ᆱ', + 65452 => 'ᆲ', + 65453 => 'ᆳ', + 65454 => 'ᆴ', + 65455 => 'ᆵ', + 65456 => 'ᄚ', + 65457 => 'ᄆ', + 65458 => 'ᄇ', + 65459 => 'ᄈ', + 65460 => 'ᄡ', + 65461 => 'ᄉ', + 65462 => 'ᄊ', + 65463 => 'ᄋ', + 65464 => 'ᄌ', + 65465 => 'ᄍ', + 65466 => 'ᄎ', + 65467 => 'ᄏ', + 65468 => 'ᄐ', + 65469 => 'ᄑ', + 65470 => 'ᄒ', + 65474 => 'ᅡ', + 65475 => 'ᅢ', + 65476 => 'ᅣ', + 65477 => 'ᅤ', + 65478 => 'ᅥ', + 65479 => 'ᅦ', + 65482 => 'ᅧ', + 65483 => 'ᅨ', + 65484 => 'ᅩ', + 65485 => 'ᅪ', + 65486 => 'ᅫ', + 65487 => 'ᅬ', + 65490 => 'ᅭ', + 65491 => 'ᅮ', + 65492 => 'ᅯ', + 65493 => 'ᅰ', + 65494 => 'ᅱ', + 65495 => 'ᅲ', + 65498 => 'ᅳ', + 65499 => 'ᅴ', + 65500 => 'ᅵ', + 65504 => '¢', + 65505 => '£', + 65506 => '¬', + 65508 => '¦', + 65509 => '¥', + 65510 => '₩', + 65512 => '│', + 65513 => '←', + 65514 => '↑', + 65515 => '→', + 65516 => '↓', + 65517 => '■', + 65518 => '○', + 66560 => '𐐨', + 66561 => '𐐩', + 66562 => '𐐪', + 66563 => '𐐫', + 66564 => '𐐬', + 66565 => '𐐭', + 66566 => '𐐮', + 66567 => '𐐯', + 66568 => '𐐰', + 66569 => '𐐱', + 66570 => '𐐲', + 66571 => '𐐳', + 66572 => '𐐴', + 66573 => '𐐵', + 66574 => '𐐶', + 66575 => '𐐷', + 66576 => '𐐸', + 66577 => '𐐹', + 66578 => '𐐺', + 66579 => '𐐻', + 66580 => '𐐼', + 66581 => '𐐽', + 66582 => '𐐾', + 66583 => '𐐿', + 66584 => '𐑀', + 66585 => '𐑁', + 66586 => '𐑂', + 66587 => '𐑃', + 66588 => '𐑄', + 66589 => '𐑅', + 66590 => '𐑆', + 66591 => '𐑇', + 66592 => '𐑈', + 66593 => '𐑉', + 66594 => '𐑊', + 66595 => '𐑋', + 66596 => '𐑌', + 66597 => '𐑍', + 66598 => '𐑎', + 66599 => '𐑏', + 66736 => '𐓘', + 66737 => '𐓙', + 66738 => '𐓚', + 66739 => '𐓛', + 66740 => '𐓜', + 66741 => '𐓝', + 66742 => '𐓞', + 66743 => '𐓟', + 66744 => '𐓠', + 66745 => '𐓡', + 66746 => '𐓢', + 66747 => '𐓣', + 66748 => '𐓤', + 66749 => '𐓥', + 66750 => '𐓦', + 66751 => '𐓧', + 66752 => '𐓨', + 66753 => '𐓩', + 66754 => '𐓪', + 66755 => '𐓫', + 66756 => '𐓬', + 66757 => '𐓭', + 66758 => '𐓮', + 66759 => '𐓯', + 66760 => '𐓰', + 66761 => '𐓱', + 66762 => '𐓲', + 66763 => '𐓳', + 66764 => '𐓴', + 66765 => '𐓵', + 66766 => '𐓶', + 66767 => '𐓷', + 66768 => '𐓸', + 66769 => '𐓹', + 66770 => '𐓺', + 66771 => '𐓻', + 68736 => '𐳀', + 68737 => '𐳁', + 68738 => '𐳂', + 68739 => '𐳃', + 68740 => '𐳄', + 68741 => '𐳅', + 68742 => '𐳆', + 68743 => '𐳇', + 68744 => '𐳈', + 68745 => '𐳉', + 68746 => '𐳊', + 68747 => '𐳋', + 68748 => '𐳌', + 68749 => '𐳍', + 68750 => '𐳎', + 68751 => '𐳏', + 68752 => '𐳐', + 68753 => '𐳑', + 68754 => '𐳒', + 68755 => '𐳓', + 68756 => '𐳔', + 68757 => '𐳕', + 68758 => '𐳖', + 68759 => '𐳗', + 68760 => '𐳘', + 68761 => '𐳙', + 68762 => '𐳚', + 68763 => '𐳛', + 68764 => '𐳜', + 68765 => '𐳝', + 68766 => '𐳞', + 68767 => '𐳟', + 68768 => '𐳠', + 68769 => '𐳡', + 68770 => '𐳢', + 68771 => '𐳣', + 68772 => '𐳤', + 68773 => '𐳥', + 68774 => '𐳦', + 68775 => '𐳧', + 68776 => '𐳨', + 68777 => '𐳩', + 68778 => '𐳪', + 68779 => '𐳫', + 68780 => '𐳬', + 68781 => '𐳭', + 68782 => '𐳮', + 68783 => '𐳯', + 68784 => '𐳰', + 68785 => '𐳱', + 68786 => '𐳲', + 71840 => '𑣀', + 71841 => '𑣁', + 71842 => '𑣂', + 71843 => '𑣃', + 71844 => '𑣄', + 71845 => '𑣅', + 71846 => '𑣆', + 71847 => '𑣇', + 71848 => '𑣈', + 71849 => '𑣉', + 71850 => '𑣊', + 71851 => '𑣋', + 71852 => '𑣌', + 71853 => '𑣍', + 71854 => '𑣎', + 71855 => '𑣏', + 71856 => '𑣐', + 71857 => '𑣑', + 71858 => '𑣒', + 71859 => '𑣓', + 71860 => '𑣔', + 71861 => '𑣕', + 71862 => '𑣖', + 71863 => '𑣗', + 71864 => '𑣘', + 71865 => '𑣙', + 71866 => '𑣚', + 71867 => '𑣛', + 71868 => '𑣜', + 71869 => '𑣝', + 71870 => '𑣞', + 71871 => '𑣟', + 93760 => '𖹠', + 93761 => '𖹡', + 93762 => '𖹢', + 93763 => '𖹣', + 93764 => '𖹤', + 93765 => '𖹥', + 93766 => '𖹦', + 93767 => '𖹧', + 93768 => '𖹨', + 93769 => '𖹩', + 93770 => '𖹪', + 93771 => '𖹫', + 93772 => '𖹬', + 93773 => '𖹭', + 93774 => '𖹮', + 93775 => '𖹯', + 93776 => '𖹰', + 93777 => '𖹱', + 93778 => '𖹲', + 93779 => '𖹳', + 93780 => '𖹴', + 93781 => '𖹵', + 93782 => '𖹶', + 93783 => '𖹷', + 93784 => '𖹸', + 93785 => '𖹹', + 93786 => '𖹺', + 93787 => '𖹻', + 93788 => '𖹼', + 93789 => '𖹽', + 93790 => '𖹾', + 93791 => '𖹿', + 119134 => '𝅗𝅥', + 119135 => '𝅘𝅥', + 119136 => '𝅘𝅥𝅮', + 119137 => '𝅘𝅥𝅯', + 119138 => '𝅘𝅥𝅰', + 119139 => '𝅘𝅥𝅱', + 119140 => '𝅘𝅥𝅲', + 119227 => '𝆹𝅥', + 119228 => '𝆺𝅥', + 119229 => '𝆹𝅥𝅮', + 119230 => '𝆺𝅥𝅮', + 119231 => '𝆹𝅥𝅯', + 119232 => '𝆺𝅥𝅯', + 119808 => 'a', + 119809 => 'b', + 119810 => 'c', + 119811 => 'd', + 119812 => 'e', + 119813 => 'f', + 119814 => 'g', + 119815 => 'h', + 119816 => 'i', + 119817 => 'j', + 119818 => 'k', + 119819 => 'l', + 119820 => 'm', + 119821 => 'n', + 119822 => 'o', + 119823 => 'p', + 119824 => 'q', + 119825 => 'r', + 119826 => 's', + 119827 => 't', + 119828 => 'u', + 119829 => 'v', + 119830 => 'w', + 119831 => 'x', + 119832 => 'y', + 119833 => 'z', + 119834 => 'a', + 119835 => 'b', + 119836 => 'c', + 119837 => 'd', + 119838 => 'e', + 119839 => 'f', + 119840 => 'g', + 119841 => 'h', + 119842 => 'i', + 119843 => 'j', + 119844 => 'k', + 119845 => 'l', + 119846 => 'm', + 119847 => 'n', + 119848 => 'o', + 119849 => 'p', + 119850 => 'q', + 119851 => 'r', + 119852 => 's', + 119853 => 't', + 119854 => 'u', + 119855 => 'v', + 119856 => 'w', + 119857 => 'x', + 119858 => 'y', + 119859 => 'z', + 119860 => 'a', + 119861 => 'b', + 119862 => 'c', + 119863 => 'd', + 119864 => 'e', + 119865 => 'f', + 119866 => 'g', + 119867 => 'h', + 119868 => 'i', + 119869 => 'j', + 119870 => 'k', + 119871 => 'l', + 119872 => 'm', + 119873 => 'n', + 119874 => 'o', + 119875 => 'p', + 119876 => 'q', + 119877 => 'r', + 119878 => 's', + 119879 => 't', + 119880 => 'u', + 119881 => 'v', + 119882 => 'w', + 119883 => 'x', + 119884 => 'y', + 119885 => 'z', + 119886 => 'a', + 119887 => 'b', + 119888 => 'c', + 119889 => 'd', + 119890 => 'e', + 119891 => 'f', + 119892 => 'g', + 119894 => 'i', + 119895 => 'j', + 119896 => 'k', + 119897 => 'l', + 119898 => 'm', + 119899 => 'n', + 119900 => 'o', + 119901 => 'p', + 119902 => 'q', + 119903 => 'r', + 119904 => 's', + 119905 => 't', + 119906 => 'u', + 119907 => 'v', + 119908 => 'w', + 119909 => 'x', + 119910 => 'y', + 119911 => 'z', + 119912 => 'a', + 119913 => 'b', + 119914 => 'c', + 119915 => 'd', + 119916 => 'e', + 119917 => 'f', + 119918 => 'g', + 119919 => 'h', + 119920 => 'i', + 119921 => 'j', + 119922 => 'k', + 119923 => 'l', + 119924 => 'm', + 119925 => 'n', + 119926 => 'o', + 119927 => 'p', + 119928 => 'q', + 119929 => 'r', + 119930 => 's', + 119931 => 't', + 119932 => 'u', + 119933 => 'v', + 119934 => 'w', + 119935 => 'x', + 119936 => 'y', + 119937 => 'z', + 119938 => 'a', + 119939 => 'b', + 119940 => 'c', + 119941 => 'd', + 119942 => 'e', + 119943 => 'f', + 119944 => 'g', + 119945 => 'h', + 119946 => 'i', + 119947 => 'j', + 119948 => 'k', + 119949 => 'l', + 119950 => 'm', + 119951 => 'n', + 119952 => 'o', + 119953 => 'p', + 119954 => 'q', + 119955 => 'r', + 119956 => 's', + 119957 => 't', + 119958 => 'u', + 119959 => 'v', + 119960 => 'w', + 119961 => 'x', + 119962 => 'y', + 119963 => 'z', + 119964 => 'a', + 119966 => 'c', + 119967 => 'd', + 119970 => 'g', + 119973 => 'j', + 119974 => 'k', + 119977 => 'n', + 119978 => 'o', + 119979 => 'p', + 119980 => 'q', + 119982 => 's', + 119983 => 't', + 119984 => 'u', + 119985 => 'v', + 119986 => 'w', + 119987 => 'x', + 119988 => 'y', + 119989 => 'z', + 119990 => 'a', + 119991 => 'b', + 119992 => 'c', + 119993 => 'd', + 119995 => 'f', + 119997 => 'h', + 119998 => 'i', + 119999 => 'j', + 120000 => 'k', + 120001 => 'l', + 120002 => 'm', + 120003 => 'n', + 120005 => 'p', + 120006 => 'q', + 120007 => 'r', + 120008 => 's', + 120009 => 't', + 120010 => 'u', + 120011 => 'v', + 120012 => 'w', + 120013 => 'x', + 120014 => 'y', + 120015 => 'z', + 120016 => 'a', + 120017 => 'b', + 120018 => 'c', + 120019 => 'd', + 120020 => 'e', + 120021 => 'f', + 120022 => 'g', + 120023 => 'h', + 120024 => 'i', + 120025 => 'j', + 120026 => 'k', + 120027 => 'l', + 120028 => 'm', + 120029 => 'n', + 120030 => 'o', + 120031 => 'p', + 120032 => 'q', + 120033 => 'r', + 120034 => 's', + 120035 => 't', + 120036 => 'u', + 120037 => 'v', + 120038 => 'w', + 120039 => 'x', + 120040 => 'y', + 120041 => 'z', + 120042 => 'a', + 120043 => 'b', + 120044 => 'c', + 120045 => 'd', + 120046 => 'e', + 120047 => 'f', + 120048 => 'g', + 120049 => 'h', + 120050 => 'i', + 120051 => 'j', + 120052 => 'k', + 120053 => 'l', + 120054 => 'm', + 120055 => 'n', + 120056 => 'o', + 120057 => 'p', + 120058 => 'q', + 120059 => 'r', + 120060 => 's', + 120061 => 't', + 120062 => 'u', + 120063 => 'v', + 120064 => 'w', + 120065 => 'x', + 120066 => 'y', + 120067 => 'z', + 120068 => 'a', + 120069 => 'b', + 120071 => 'd', + 120072 => 'e', + 120073 => 'f', + 120074 => 'g', + 120077 => 'j', + 120078 => 'k', + 120079 => 'l', + 120080 => 'm', + 120081 => 'n', + 120082 => 'o', + 120083 => 'p', + 120084 => 'q', + 120086 => 's', + 120087 => 't', + 120088 => 'u', + 120089 => 'v', + 120090 => 'w', + 120091 => 'x', + 120092 => 'y', + 120094 => 'a', + 120095 => 'b', + 120096 => 'c', + 120097 => 'd', + 120098 => 'e', + 120099 => 'f', + 120100 => 'g', + 120101 => 'h', + 120102 => 'i', + 120103 => 'j', + 120104 => 'k', + 120105 => 'l', + 120106 => 'm', + 120107 => 'n', + 120108 => 'o', + 120109 => 'p', + 120110 => 'q', + 120111 => 'r', + 120112 => 's', + 120113 => 't', + 120114 => 'u', + 120115 => 'v', + 120116 => 'w', + 120117 => 'x', + 120118 => 'y', + 120119 => 'z', + 120120 => 'a', + 120121 => 'b', + 120123 => 'd', + 120124 => 'e', + 120125 => 'f', + 120126 => 'g', + 120128 => 'i', + 120129 => 'j', + 120130 => 'k', + 120131 => 'l', + 120132 => 'm', + 120134 => 'o', + 120138 => 's', + 120139 => 't', + 120140 => 'u', + 120141 => 'v', + 120142 => 'w', + 120143 => 'x', + 120144 => 'y', + 120146 => 'a', + 120147 => 'b', + 120148 => 'c', + 120149 => 'd', + 120150 => 'e', + 120151 => 'f', + 120152 => 'g', + 120153 => 'h', + 120154 => 'i', + 120155 => 'j', + 120156 => 'k', + 120157 => 'l', + 120158 => 'm', + 120159 => 'n', + 120160 => 'o', + 120161 => 'p', + 120162 => 'q', + 120163 => 'r', + 120164 => 's', + 120165 => 't', + 120166 => 'u', + 120167 => 'v', + 120168 => 'w', + 120169 => 'x', + 120170 => 'y', + 120171 => 'z', + 120172 => 'a', + 120173 => 'b', + 120174 => 'c', + 120175 => 'd', + 120176 => 'e', + 120177 => 'f', + 120178 => 'g', + 120179 => 'h', + 120180 => 'i', + 120181 => 'j', + 120182 => 'k', + 120183 => 'l', + 120184 => 'm', + 120185 => 'n', + 120186 => 'o', + 120187 => 'p', + 120188 => 'q', + 120189 => 'r', + 120190 => 's', + 120191 => 't', + 120192 => 'u', + 120193 => 'v', + 120194 => 'w', + 120195 => 'x', + 120196 => 'y', + 120197 => 'z', + 120198 => 'a', + 120199 => 'b', + 120200 => 'c', + 120201 => 'd', + 120202 => 'e', + 120203 => 'f', + 120204 => 'g', + 120205 => 'h', + 120206 => 'i', + 120207 => 'j', + 120208 => 'k', + 120209 => 'l', + 120210 => 'm', + 120211 => 'n', + 120212 => 'o', + 120213 => 'p', + 120214 => 'q', + 120215 => 'r', + 120216 => 's', + 120217 => 't', + 120218 => 'u', + 120219 => 'v', + 120220 => 'w', + 120221 => 'x', + 120222 => 'y', + 120223 => 'z', + 120224 => 'a', + 120225 => 'b', + 120226 => 'c', + 120227 => 'd', + 120228 => 'e', + 120229 => 'f', + 120230 => 'g', + 120231 => 'h', + 120232 => 'i', + 120233 => 'j', + 120234 => 'k', + 120235 => 'l', + 120236 => 'm', + 120237 => 'n', + 120238 => 'o', + 120239 => 'p', + 120240 => 'q', + 120241 => 'r', + 120242 => 's', + 120243 => 't', + 120244 => 'u', + 120245 => 'v', + 120246 => 'w', + 120247 => 'x', + 120248 => 'y', + 120249 => 'z', + 120250 => 'a', + 120251 => 'b', + 120252 => 'c', + 120253 => 'd', + 120254 => 'e', + 120255 => 'f', + 120256 => 'g', + 120257 => 'h', + 120258 => 'i', + 120259 => 'j', + 120260 => 'k', + 120261 => 'l', + 120262 => 'm', + 120263 => 'n', + 120264 => 'o', + 120265 => 'p', + 120266 => 'q', + 120267 => 'r', + 120268 => 's', + 120269 => 't', + 120270 => 'u', + 120271 => 'v', + 120272 => 'w', + 120273 => 'x', + 120274 => 'y', + 120275 => 'z', + 120276 => 'a', + 120277 => 'b', + 120278 => 'c', + 120279 => 'd', + 120280 => 'e', + 120281 => 'f', + 120282 => 'g', + 120283 => 'h', + 120284 => 'i', + 120285 => 'j', + 120286 => 'k', + 120287 => 'l', + 120288 => 'm', + 120289 => 'n', + 120290 => 'o', + 120291 => 'p', + 120292 => 'q', + 120293 => 'r', + 120294 => 's', + 120295 => 't', + 120296 => 'u', + 120297 => 'v', + 120298 => 'w', + 120299 => 'x', + 120300 => 'y', + 120301 => 'z', + 120302 => 'a', + 120303 => 'b', + 120304 => 'c', + 120305 => 'd', + 120306 => 'e', + 120307 => 'f', + 120308 => 'g', + 120309 => 'h', + 120310 => 'i', + 120311 => 'j', + 120312 => 'k', + 120313 => 'l', + 120314 => 'm', + 120315 => 'n', + 120316 => 'o', + 120317 => 'p', + 120318 => 'q', + 120319 => 'r', + 120320 => 's', + 120321 => 't', + 120322 => 'u', + 120323 => 'v', + 120324 => 'w', + 120325 => 'x', + 120326 => 'y', + 120327 => 'z', + 120328 => 'a', + 120329 => 'b', + 120330 => 'c', + 120331 => 'd', + 120332 => 'e', + 120333 => 'f', + 120334 => 'g', + 120335 => 'h', + 120336 => 'i', + 120337 => 'j', + 120338 => 'k', + 120339 => 'l', + 120340 => 'm', + 120341 => 'n', + 120342 => 'o', + 120343 => 'p', + 120344 => 'q', + 120345 => 'r', + 120346 => 's', + 120347 => 't', + 120348 => 'u', + 120349 => 'v', + 120350 => 'w', + 120351 => 'x', + 120352 => 'y', + 120353 => 'z', + 120354 => 'a', + 120355 => 'b', + 120356 => 'c', + 120357 => 'd', + 120358 => 'e', + 120359 => 'f', + 120360 => 'g', + 120361 => 'h', + 120362 => 'i', + 120363 => 'j', + 120364 => 'k', + 120365 => 'l', + 120366 => 'm', + 120367 => 'n', + 120368 => 'o', + 120369 => 'p', + 120370 => 'q', + 120371 => 'r', + 120372 => 's', + 120373 => 't', + 120374 => 'u', + 120375 => 'v', + 120376 => 'w', + 120377 => 'x', + 120378 => 'y', + 120379 => 'z', + 120380 => 'a', + 120381 => 'b', + 120382 => 'c', + 120383 => 'd', + 120384 => 'e', + 120385 => 'f', + 120386 => 'g', + 120387 => 'h', + 120388 => 'i', + 120389 => 'j', + 120390 => 'k', + 120391 => 'l', + 120392 => 'm', + 120393 => 'n', + 120394 => 'o', + 120395 => 'p', + 120396 => 'q', + 120397 => 'r', + 120398 => 's', + 120399 => 't', + 120400 => 'u', + 120401 => 'v', + 120402 => 'w', + 120403 => 'x', + 120404 => 'y', + 120405 => 'z', + 120406 => 'a', + 120407 => 'b', + 120408 => 'c', + 120409 => 'd', + 120410 => 'e', + 120411 => 'f', + 120412 => 'g', + 120413 => 'h', + 120414 => 'i', + 120415 => 'j', + 120416 => 'k', + 120417 => 'l', + 120418 => 'm', + 120419 => 'n', + 120420 => 'o', + 120421 => 'p', + 120422 => 'q', + 120423 => 'r', + 120424 => 's', + 120425 => 't', + 120426 => 'u', + 120427 => 'v', + 120428 => 'w', + 120429 => 'x', + 120430 => 'y', + 120431 => 'z', + 120432 => 'a', + 120433 => 'b', + 120434 => 'c', + 120435 => 'd', + 120436 => 'e', + 120437 => 'f', + 120438 => 'g', + 120439 => 'h', + 120440 => 'i', + 120441 => 'j', + 120442 => 'k', + 120443 => 'l', + 120444 => 'm', + 120445 => 'n', + 120446 => 'o', + 120447 => 'p', + 120448 => 'q', + 120449 => 'r', + 120450 => 's', + 120451 => 't', + 120452 => 'u', + 120453 => 'v', + 120454 => 'w', + 120455 => 'x', + 120456 => 'y', + 120457 => 'z', + 120458 => 'a', + 120459 => 'b', + 120460 => 'c', + 120461 => 'd', + 120462 => 'e', + 120463 => 'f', + 120464 => 'g', + 120465 => 'h', + 120466 => 'i', + 120467 => 'j', + 120468 => 'k', + 120469 => 'l', + 120470 => 'm', + 120471 => 'n', + 120472 => 'o', + 120473 => 'p', + 120474 => 'q', + 120475 => 'r', + 120476 => 's', + 120477 => 't', + 120478 => 'u', + 120479 => 'v', + 120480 => 'w', + 120481 => 'x', + 120482 => 'y', + 120483 => 'z', + 120484 => 'ı', + 120485 => 'ȷ', + 120488 => 'α', + 120489 => 'β', + 120490 => 'γ', + 120491 => 'δ', + 120492 => 'ε', + 120493 => 'ζ', + 120494 => 'η', + 120495 => 'θ', + 120496 => 'ι', + 120497 => 'κ', + 120498 => 'λ', + 120499 => 'μ', + 120500 => 'ν', + 120501 => 'ξ', + 120502 => 'ο', + 120503 => 'π', + 120504 => 'ρ', + 120505 => 'θ', + 120506 => 'σ', + 120507 => 'τ', + 120508 => 'υ', + 120509 => 'φ', + 120510 => 'χ', + 120511 => 'ψ', + 120512 => 'ω', + 120513 => '∇', + 120514 => 'α', + 120515 => 'β', + 120516 => 'γ', + 120517 => 'δ', + 120518 => 'ε', + 120519 => 'ζ', + 120520 => 'η', + 120521 => 'θ', + 120522 => 'ι', + 120523 => 'κ', + 120524 => 'λ', + 120525 => 'μ', + 120526 => 'ν', + 120527 => 'ξ', + 120528 => 'ο', + 120529 => 'π', + 120530 => 'ρ', + 120531 => 'σ', + 120532 => 'σ', + 120533 => 'τ', + 120534 => 'υ', + 120535 => 'φ', + 120536 => 'χ', + 120537 => 'ψ', + 120538 => 'ω', + 120539 => '∂', + 120540 => 'ε', + 120541 => 'θ', + 120542 => 'κ', + 120543 => 'φ', + 120544 => 'ρ', + 120545 => 'π', + 120546 => 'α', + 120547 => 'β', + 120548 => 'γ', + 120549 => 'δ', + 120550 => 'ε', + 120551 => 'ζ', + 120552 => 'η', + 120553 => 'θ', + 120554 => 'ι', + 120555 => 'κ', + 120556 => 'λ', + 120557 => 'μ', + 120558 => 'ν', + 120559 => 'ξ', + 120560 => 'ο', + 120561 => 'π', + 120562 => 'ρ', + 120563 => 'θ', + 120564 => 'σ', + 120565 => 'τ', + 120566 => 'υ', + 120567 => 'φ', + 120568 => 'χ', + 120569 => 'ψ', + 120570 => 'ω', + 120571 => '∇', + 120572 => 'α', + 120573 => 'β', + 120574 => 'γ', + 120575 => 'δ', + 120576 => 'ε', + 120577 => 'ζ', + 120578 => 'η', + 120579 => 'θ', + 120580 => 'ι', + 120581 => 'κ', + 120582 => 'λ', + 120583 => 'μ', + 120584 => 'ν', + 120585 => 'ξ', + 120586 => 'ο', + 120587 => 'π', + 120588 => 'ρ', + 120589 => 'σ', + 120590 => 'σ', + 120591 => 'τ', + 120592 => 'υ', + 120593 => 'φ', + 120594 => 'χ', + 120595 => 'ψ', + 120596 => 'ω', + 120597 => '∂', + 120598 => 'ε', + 120599 => 'θ', + 120600 => 'κ', + 120601 => 'φ', + 120602 => 'ρ', + 120603 => 'π', + 120604 => 'α', + 120605 => 'β', + 120606 => 'γ', + 120607 => 'δ', + 120608 => 'ε', + 120609 => 'ζ', + 120610 => 'η', + 120611 => 'θ', + 120612 => 'ι', + 120613 => 'κ', + 120614 => 'λ', + 120615 => 'μ', + 120616 => 'ν', + 120617 => 'ξ', + 120618 => 'ο', + 120619 => 'π', + 120620 => 'ρ', + 120621 => 'θ', + 120622 => 'σ', + 120623 => 'τ', + 120624 => 'υ', + 120625 => 'φ', + 120626 => 'χ', + 120627 => 'ψ', + 120628 => 'ω', + 120629 => '∇', + 120630 => 'α', + 120631 => 'β', + 120632 => 'γ', + 120633 => 'δ', + 120634 => 'ε', + 120635 => 'ζ', + 120636 => 'η', + 120637 => 'θ', + 120638 => 'ι', + 120639 => 'κ', + 120640 => 'λ', + 120641 => 'μ', + 120642 => 'ν', + 120643 => 'ξ', + 120644 => 'ο', + 120645 => 'π', + 120646 => 'ρ', + 120647 => 'σ', + 120648 => 'σ', + 120649 => 'τ', + 120650 => 'υ', + 120651 => 'φ', + 120652 => 'χ', + 120653 => 'ψ', + 120654 => 'ω', + 120655 => '∂', + 120656 => 'ε', + 120657 => 'θ', + 120658 => 'κ', + 120659 => 'φ', + 120660 => 'ρ', + 120661 => 'π', + 120662 => 'α', + 120663 => 'β', + 120664 => 'γ', + 120665 => 'δ', + 120666 => 'ε', + 120667 => 'ζ', + 120668 => 'η', + 120669 => 'θ', + 120670 => 'ι', + 120671 => 'κ', + 120672 => 'λ', + 120673 => 'μ', + 120674 => 'ν', + 120675 => 'ξ', + 120676 => 'ο', + 120677 => 'π', + 120678 => 'ρ', + 120679 => 'θ', + 120680 => 'σ', + 120681 => 'τ', + 120682 => 'υ', + 120683 => 'φ', + 120684 => 'χ', + 120685 => 'ψ', + 120686 => 'ω', + 120687 => '∇', + 120688 => 'α', + 120689 => 'β', + 120690 => 'γ', + 120691 => 'δ', + 120692 => 'ε', + 120693 => 'ζ', + 120694 => 'η', + 120695 => 'θ', + 120696 => 'ι', + 120697 => 'κ', + 120698 => 'λ', + 120699 => 'μ', + 120700 => 'ν', + 120701 => 'ξ', + 120702 => 'ο', + 120703 => 'π', + 120704 => 'ρ', + 120705 => 'σ', + 120706 => 'σ', + 120707 => 'τ', + 120708 => 'υ', + 120709 => 'φ', + 120710 => 'χ', + 120711 => 'ψ', + 120712 => 'ω', + 120713 => '∂', + 120714 => 'ε', + 120715 => 'θ', + 120716 => 'κ', + 120717 => 'φ', + 120718 => 'ρ', + 120719 => 'π', + 120720 => 'α', + 120721 => 'β', + 120722 => 'γ', + 120723 => 'δ', + 120724 => 'ε', + 120725 => 'ζ', + 120726 => 'η', + 120727 => 'θ', + 120728 => 'ι', + 120729 => 'κ', + 120730 => 'λ', + 120731 => 'μ', + 120732 => 'ν', + 120733 => 'ξ', + 120734 => 'ο', + 120735 => 'π', + 120736 => 'ρ', + 120737 => 'θ', + 120738 => 'σ', + 120739 => 'τ', + 120740 => 'υ', + 120741 => 'φ', + 120742 => 'χ', + 120743 => 'ψ', + 120744 => 'ω', + 120745 => '∇', + 120746 => 'α', + 120747 => 'β', + 120748 => 'γ', + 120749 => 'δ', + 120750 => 'ε', + 120751 => 'ζ', + 120752 => 'η', + 120753 => 'θ', + 120754 => 'ι', + 120755 => 'κ', + 120756 => 'λ', + 120757 => 'μ', + 120758 => 'ν', + 120759 => 'ξ', + 120760 => 'ο', + 120761 => 'π', + 120762 => 'ρ', + 120763 => 'σ', + 120764 => 'σ', + 120765 => 'τ', + 120766 => 'υ', + 120767 => 'φ', + 120768 => 'χ', + 120769 => 'ψ', + 120770 => 'ω', + 120771 => '∂', + 120772 => 'ε', + 120773 => 'θ', + 120774 => 'κ', + 120775 => 'φ', + 120776 => 'ρ', + 120777 => 'π', + 120778 => 'ϝ', + 120779 => 'ϝ', + 120782 => '0', + 120783 => '1', + 120784 => '2', + 120785 => '3', + 120786 => '4', + 120787 => '5', + 120788 => '6', + 120789 => '7', + 120790 => '8', + 120791 => '9', + 120792 => '0', + 120793 => '1', + 120794 => '2', + 120795 => '3', + 120796 => '4', + 120797 => '5', + 120798 => '6', + 120799 => '7', + 120800 => '8', + 120801 => '9', + 120802 => '0', + 120803 => '1', + 120804 => '2', + 120805 => '3', + 120806 => '4', + 120807 => '5', + 120808 => '6', + 120809 => '7', + 120810 => '8', + 120811 => '9', + 120812 => '0', + 120813 => '1', + 120814 => '2', + 120815 => '3', + 120816 => '4', + 120817 => '5', + 120818 => '6', + 120819 => '7', + 120820 => '8', + 120821 => '9', + 120822 => '0', + 120823 => '1', + 120824 => '2', + 120825 => '3', + 120826 => '4', + 120827 => '5', + 120828 => '6', + 120829 => '7', + 120830 => '8', + 120831 => '9', + 125184 => '𞤢', + 125185 => '𞤣', + 125186 => '𞤤', + 125187 => '𞤥', + 125188 => '𞤦', + 125189 => '𞤧', + 125190 => '𞤨', + 125191 => '𞤩', + 125192 => '𞤪', + 125193 => '𞤫', + 125194 => '𞤬', + 125195 => '𞤭', + 125196 => '𞤮', + 125197 => '𞤯', + 125198 => '𞤰', + 125199 => '𞤱', + 125200 => '𞤲', + 125201 => '𞤳', + 125202 => '𞤴', + 125203 => '𞤵', + 125204 => '𞤶', + 125205 => '𞤷', + 125206 => '𞤸', + 125207 => '𞤹', + 125208 => '𞤺', + 125209 => '𞤻', + 125210 => '𞤼', + 125211 => '𞤽', + 125212 => '𞤾', + 125213 => '𞤿', + 125214 => '𞥀', + 125215 => '𞥁', + 125216 => '𞥂', + 125217 => '𞥃', + 126464 => 'ا', + 126465 => 'ب', + 126466 => 'ج', + 126467 => 'د', + 126469 => 'و', + 126470 => 'ز', + 126471 => 'ح', + 126472 => 'ط', + 126473 => 'ي', + 126474 => 'ك', + 126475 => 'ل', + 126476 => 'م', + 126477 => 'ن', + 126478 => 'س', + 126479 => 'ع', + 126480 => 'ف', + 126481 => 'ص', + 126482 => 'ق', + 126483 => 'ر', + 126484 => 'ش', + 126485 => 'ت', + 126486 => 'ث', + 126487 => 'خ', + 126488 => 'ذ', + 126489 => 'ض', + 126490 => 'ظ', + 126491 => 'غ', + 126492 => 'ٮ', + 126493 => 'ں', + 126494 => 'ڡ', + 126495 => 'ٯ', + 126497 => 'ب', + 126498 => 'ج', + 126500 => 'ه', + 126503 => 'ح', + 126505 => 'ي', + 126506 => 'ك', + 126507 => 'ل', + 126508 => 'م', + 126509 => 'ن', + 126510 => 'س', + 126511 => 'ع', + 126512 => 'ف', + 126513 => 'ص', + 126514 => 'ق', + 126516 => 'ش', + 126517 => 'ت', + 126518 => 'ث', + 126519 => 'خ', + 126521 => 'ض', + 126523 => 'غ', + 126530 => 'ج', + 126535 => 'ح', + 126537 => 'ي', + 126539 => 'ل', + 126541 => 'ن', + 126542 => 'س', + 126543 => 'ع', + 126545 => 'ص', + 126546 => 'ق', + 126548 => 'ش', + 126551 => 'خ', + 126553 => 'ض', + 126555 => 'غ', + 126557 => 'ں', + 126559 => 'ٯ', + 126561 => 'ب', + 126562 => 'ج', + 126564 => 'ه', + 126567 => 'ح', + 126568 => 'ط', + 126569 => 'ي', + 126570 => 'ك', + 126572 => 'م', + 126573 => 'ن', + 126574 => 'س', + 126575 => 'ع', + 126576 => 'ف', + 126577 => 'ص', + 126578 => 'ق', + 126580 => 'ش', + 126581 => 'ت', + 126582 => 'ث', + 126583 => 'خ', + 126585 => 'ض', + 126586 => 'ظ', + 126587 => 'غ', + 126588 => 'ٮ', + 126590 => 'ڡ', + 126592 => 'ا', + 126593 => 'ب', + 126594 => 'ج', + 126595 => 'د', + 126596 => 'ه', + 126597 => 'و', + 126598 => 'ز', + 126599 => 'ح', + 126600 => 'ط', + 126601 => 'ي', + 126603 => 'ل', + 126604 => 'م', + 126605 => 'ن', + 126606 => 'س', + 126607 => 'ع', + 126608 => 'ف', + 126609 => 'ص', + 126610 => 'ق', + 126611 => 'ر', + 126612 => 'ش', + 126613 => 'ت', + 126614 => 'ث', + 126615 => 'خ', + 126616 => 'ذ', + 126617 => 'ض', + 126618 => 'ظ', + 126619 => 'غ', + 126625 => 'ب', + 126626 => 'ج', + 126627 => 'د', + 126629 => 'و', + 126630 => 'ز', + 126631 => 'ح', + 126632 => 'ط', + 126633 => 'ي', + 126635 => 'ل', + 126636 => 'م', + 126637 => 'ن', + 126638 => 'س', + 126639 => 'ع', + 126640 => 'ف', + 126641 => 'ص', + 126642 => 'ق', + 126643 => 'ر', + 126644 => 'ش', + 126645 => 'ت', + 126646 => 'ث', + 126647 => 'خ', + 126648 => 'ذ', + 126649 => 'ض', + 126650 => 'ظ', + 126651 => 'غ', + 127274 => '〔s〕', + 127275 => 'c', + 127276 => 'r', + 127277 => 'cd', + 127278 => 'wz', + 127280 => 'a', + 127281 => 'b', + 127282 => 'c', + 127283 => 'd', + 127284 => 'e', + 127285 => 'f', + 127286 => 'g', + 127287 => 'h', + 127288 => 'i', + 127289 => 'j', + 127290 => 'k', + 127291 => 'l', + 127292 => 'm', + 127293 => 'n', + 127294 => 'o', + 127295 => 'p', + 127296 => 'q', + 127297 => 'r', + 127298 => 's', + 127299 => 't', + 127300 => 'u', + 127301 => 'v', + 127302 => 'w', + 127303 => 'x', + 127304 => 'y', + 127305 => 'z', + 127306 => 'hv', + 127307 => 'mv', + 127308 => 'sd', + 127309 => 'ss', + 127310 => 'ppv', + 127311 => 'wc', + 127338 => 'mc', + 127339 => 'md', + 127340 => 'mr', + 127376 => 'dj', + 127488 => 'ほか', + 127489 => 'ココ', + 127490 => 'サ', + 127504 => '手', + 127505 => '字', + 127506 => '双', + 127507 => 'デ', + 127508 => '二', + 127509 => '多', + 127510 => '解', + 127511 => '天', + 127512 => '交', + 127513 => '映', + 127514 => '無', + 127515 => '料', + 127516 => '前', + 127517 => '後', + 127518 => '再', + 127519 => '新', + 127520 => '初', + 127521 => '終', + 127522 => '生', + 127523 => '販', + 127524 => '声', + 127525 => '吹', + 127526 => '演', + 127527 => '投', + 127528 => '捕', + 127529 => '一', + 127530 => '三', + 127531 => '遊', + 127532 => '左', + 127533 => '中', + 127534 => '右', + 127535 => '指', + 127536 => '走', + 127537 => '打', + 127538 => '禁', + 127539 => '空', + 127540 => '合', + 127541 => '満', + 127542 => '有', + 127543 => '月', + 127544 => '申', + 127545 => '割', + 127546 => '営', + 127547 => '配', + 127552 => '〔本〕', + 127553 => '〔三〕', + 127554 => '〔二〕', + 127555 => '〔安〕', + 127556 => '〔点〕', + 127557 => '〔打〕', + 127558 => '〔盗〕', + 127559 => '〔勝〕', + 127560 => '〔敗〕', + 127568 => '得', + 127569 => '可', + 130032 => '0', + 130033 => '1', + 130034 => '2', + 130035 => '3', + 130036 => '4', + 130037 => '5', + 130038 => '6', + 130039 => '7', + 130040 => '8', + 130041 => '9', + 194560 => '丽', + 194561 => '丸', + 194562 => '乁', + 194563 => '𠄢', + 194564 => '你', + 194565 => '侮', + 194566 => '侻', + 194567 => '倂', + 194568 => '偺', + 194569 => '備', + 194570 => '僧', + 194571 => '像', + 194572 => '㒞', + 194573 => '𠘺', + 194574 => '免', + 194575 => '兔', + 194576 => '兤', + 194577 => '具', + 194578 => '𠔜', + 194579 => '㒹', + 194580 => '內', + 194581 => '再', + 194582 => '𠕋', + 194583 => '冗', + 194584 => '冤', + 194585 => '仌', + 194586 => '冬', + 194587 => '况', + 194588 => '𩇟', + 194589 => '凵', + 194590 => '刃', + 194591 => '㓟', + 194592 => '刻', + 194593 => '剆', + 194594 => '割', + 194595 => '剷', + 194596 => '㔕', + 194597 => '勇', + 194598 => '勉', + 194599 => '勤', + 194600 => '勺', + 194601 => '包', + 194602 => '匆', + 194603 => '北', + 194604 => '卉', + 194605 => '卑', + 194606 => '博', + 194607 => '即', + 194608 => '卽', + 194609 => '卿', + 194610 => '卿', + 194611 => '卿', + 194612 => '𠨬', + 194613 => '灰', + 194614 => '及', + 194615 => '叟', + 194616 => '𠭣', + 194617 => '叫', + 194618 => '叱', + 194619 => '吆', + 194620 => '咞', + 194621 => '吸', + 194622 => '呈', + 194623 => '周', + 194624 => '咢', + 194625 => '哶', + 194626 => '唐', + 194627 => '啓', + 194628 => '啣', + 194629 => '善', + 194630 => '善', + 194631 => '喙', + 194632 => '喫', + 194633 => '喳', + 194634 => '嗂', + 194635 => '圖', + 194636 => '嘆', + 194637 => '圗', + 194638 => '噑', + 194639 => '噴', + 194640 => '切', + 194641 => '壮', + 194642 => '城', + 194643 => '埴', + 194644 => '堍', + 194645 => '型', + 194646 => '堲', + 194647 => '報', + 194648 => '墬', + 194649 => '𡓤', + 194650 => '売', + 194651 => '壷', + 194652 => '夆', + 194653 => '多', + 194654 => '夢', + 194655 => '奢', + 194656 => '𡚨', + 194657 => '𡛪', + 194658 => '姬', + 194659 => '娛', + 194660 => '娧', + 194661 => '姘', + 194662 => '婦', + 194663 => '㛮', + 194665 => '嬈', + 194666 => '嬾', + 194667 => '嬾', + 194668 => '𡧈', + 194669 => '寃', + 194670 => '寘', + 194671 => '寧', + 194672 => '寳', + 194673 => '𡬘', + 194674 => '寿', + 194675 => '将', + 194677 => '尢', + 194678 => '㞁', + 194679 => '屠', + 194680 => '屮', + 194681 => '峀', + 194682 => '岍', + 194683 => '𡷤', + 194684 => '嵃', + 194685 => '𡷦', + 194686 => '嵮', + 194687 => '嵫', + 194688 => '嵼', + 194689 => '巡', + 194690 => '巢', + 194691 => '㠯', + 194692 => '巽', + 194693 => '帨', + 194694 => '帽', + 194695 => '幩', + 194696 => '㡢', + 194697 => '𢆃', + 194698 => '㡼', + 194699 => '庰', + 194700 => '庳', + 194701 => '庶', + 194702 => '廊', + 194703 => '𪎒', + 194704 => '廾', + 194705 => '𢌱', + 194706 => '𢌱', + 194707 => '舁', + 194708 => '弢', + 194709 => '弢', + 194710 => '㣇', + 194711 => '𣊸', + 194712 => '𦇚', + 194713 => '形', + 194714 => '彫', + 194715 => '㣣', + 194716 => '徚', + 194717 => '忍', + 194718 => '志', + 194719 => '忹', + 194720 => '悁', + 194721 => '㤺', + 194722 => '㤜', + 194723 => '悔', + 194724 => '𢛔', + 194725 => '惇', + 194726 => '慈', + 194727 => '慌', + 194728 => '慎', + 194729 => '慌', + 194730 => '慺', + 194731 => '憎', + 194732 => '憲', + 194733 => '憤', + 194734 => '憯', + 194735 => '懞', + 194736 => '懲', + 194737 => '懶', + 194738 => '成', + 194739 => '戛', + 194740 => '扝', + 194741 => '抱', + 194742 => '拔', + 194743 => '捐', + 194744 => '𢬌', + 194745 => '挽', + 194746 => '拼', + 194747 => '捨', + 194748 => '掃', + 194749 => '揤', + 194750 => '𢯱', + 194751 => '搢', + 194752 => '揅', + 194753 => '掩', + 194754 => '㨮', + 194755 => '摩', + 194756 => '摾', + 194757 => '撝', + 194758 => '摷', + 194759 => '㩬', + 194760 => '敏', + 194761 => '敬', + 194762 => '𣀊', + 194763 => '旣', + 194764 => '書', + 194765 => '晉', + 194766 => '㬙', + 194767 => '暑', + 194768 => '㬈', + 194769 => '㫤', + 194770 => '冒', + 194771 => '冕', + 194772 => '最', + 194773 => '暜', + 194774 => '肭', + 194775 => '䏙', + 194776 => '朗', + 194777 => '望', + 194778 => '朡', + 194779 => '杞', + 194780 => '杓', + 194781 => '𣏃', + 194782 => '㭉', + 194783 => '柺', + 194784 => '枅', + 194785 => '桒', + 194786 => '梅', + 194787 => '𣑭', + 194788 => '梎', + 194789 => '栟', + 194790 => '椔', + 194791 => '㮝', + 194792 => '楂', + 194793 => '榣', + 194794 => '槪', + 194795 => '檨', + 194796 => '𣚣', + 194797 => '櫛', + 194798 => '㰘', + 194799 => '次', + 194800 => '𣢧', + 194801 => '歔', + 194802 => '㱎', + 194803 => '歲', + 194804 => '殟', + 194805 => '殺', + 194806 => '殻', + 194807 => '𣪍', + 194808 => '𡴋', + 194809 => '𣫺', + 194810 => '汎', + 194811 => '𣲼', + 194812 => '沿', + 194813 => '泍', + 194814 => '汧', + 194815 => '洖', + 194816 => '派', + 194817 => '海', + 194818 => '流', + 194819 => '浩', + 194820 => '浸', + 194821 => '涅', + 194822 => '𣴞', + 194823 => '洴', + 194824 => '港', + 194825 => '湮', + 194826 => '㴳', + 194827 => '滋', + 194828 => '滇', + 194829 => '𣻑', + 194830 => '淹', + 194831 => '潮', + 194832 => '𣽞', + 194833 => '𣾎', + 194834 => '濆', + 194835 => '瀹', + 194836 => '瀞', + 194837 => '瀛', + 194838 => '㶖', + 194839 => '灊', + 194840 => '災', + 194841 => '灷', + 194842 => '炭', + 194843 => '𠔥', + 194844 => '煅', + 194845 => '𤉣', + 194846 => '熜', + 194848 => '爨', + 194849 => '爵', + 194850 => '牐', + 194851 => '𤘈', + 194852 => '犀', + 194853 => '犕', + 194854 => '𤜵', + 194855 => '𤠔', + 194856 => '獺', + 194857 => '王', + 194858 => '㺬', + 194859 => '玥', + 194860 => '㺸', + 194861 => '㺸', + 194862 => '瑇', + 194863 => '瑜', + 194864 => '瑱', + 194865 => '璅', + 194866 => '瓊', + 194867 => '㼛', + 194868 => '甤', + 194869 => '𤰶', + 194870 => '甾', + 194871 => '𤲒', + 194872 => '異', + 194873 => '𢆟', + 194874 => '瘐', + 194875 => '𤾡', + 194876 => '𤾸', + 194877 => '𥁄', + 194878 => '㿼', + 194879 => '䀈', + 194880 => '直', + 194881 => '𥃳', + 194882 => '𥃲', + 194883 => '𥄙', + 194884 => '𥄳', + 194885 => '眞', + 194886 => '真', + 194887 => '真', + 194888 => '睊', + 194889 => '䀹', + 194890 => '瞋', + 194891 => '䁆', + 194892 => '䂖', + 194893 => '𥐝', + 194894 => '硎', + 194895 => '碌', + 194896 => '磌', + 194897 => '䃣', + 194898 => '𥘦', + 194899 => '祖', + 194900 => '𥚚', + 194901 => '𥛅', + 194902 => '福', + 194903 => '秫', + 194904 => '䄯', + 194905 => '穀', + 194906 => '穊', + 194907 => '穏', + 194908 => '𥥼', + 194909 => '𥪧', + 194910 => '𥪧', + 194912 => '䈂', + 194913 => '𥮫', + 194914 => '篆', + 194915 => '築', + 194916 => '䈧', + 194917 => '𥲀', + 194918 => '糒', + 194919 => '䊠', + 194920 => '糨', + 194921 => '糣', + 194922 => '紀', + 194923 => '𥾆', + 194924 => '絣', + 194925 => '䌁', + 194926 => '緇', + 194927 => '縂', + 194928 => '繅', + 194929 => '䌴', + 194930 => '𦈨', + 194931 => '𦉇', + 194932 => '䍙', + 194933 => '𦋙', + 194934 => '罺', + 194935 => '𦌾', + 194936 => '羕', + 194937 => '翺', + 194938 => '者', + 194939 => '𦓚', + 194940 => '𦔣', + 194941 => '聠', + 194942 => '𦖨', + 194943 => '聰', + 194944 => '𣍟', + 194945 => '䏕', + 194946 => '育', + 194947 => '脃', + 194948 => '䐋', + 194949 => '脾', + 194950 => '媵', + 194951 => '𦞧', + 194952 => '𦞵', + 194953 => '𣎓', + 194954 => '𣎜', + 194955 => '舁', + 194956 => '舄', + 194957 => '辞', + 194958 => '䑫', + 194959 => '芑', + 194960 => '芋', + 194961 => '芝', + 194962 => '劳', + 194963 => '花', + 194964 => '芳', + 194965 => '芽', + 194966 => '苦', + 194967 => '𦬼', + 194968 => '若', + 194969 => '茝', + 194970 => '荣', + 194971 => '莭', + 194972 => '茣', + 194973 => '莽', + 194974 => '菧', + 194975 => '著', + 194976 => '荓', + 194977 => '菊', + 194978 => '菌', + 194979 => '菜', + 194980 => '𦰶', + 194981 => '𦵫', + 194982 => '𦳕', + 194983 => '䔫', + 194984 => '蓱', + 194985 => '蓳', + 194986 => '蔖', + 194987 => '𧏊', + 194988 => '蕤', + 194989 => '𦼬', + 194990 => '䕝', + 194991 => '䕡', + 194992 => '𦾱', + 194993 => '𧃒', + 194994 => '䕫', + 194995 => '虐', + 194996 => '虜', + 194997 => '虧', + 194998 => '虩', + 194999 => '蚩', + 195000 => '蚈', + 195001 => '蜎', + 195002 => '蛢', + 195003 => '蝹', + 195004 => '蜨', + 195005 => '蝫', + 195006 => '螆', + 195008 => '蟡', + 195009 => '蠁', + 195010 => '䗹', + 195011 => '衠', + 195012 => '衣', + 195013 => '𧙧', + 195014 => '裗', + 195015 => '裞', + 195016 => '䘵', + 195017 => '裺', + 195018 => '㒻', + 195019 => '𧢮', + 195020 => '𧥦', + 195021 => '䚾', + 195022 => '䛇', + 195023 => '誠', + 195024 => '諭', + 195025 => '變', + 195026 => '豕', + 195027 => '𧲨', + 195028 => '貫', + 195029 => '賁', + 195030 => '贛', + 195031 => '起', + 195032 => '𧼯', + 195033 => '𠠄', + 195034 => '跋', + 195035 => '趼', + 195036 => '跰', + 195037 => '𠣞', + 195038 => '軔', + 195039 => '輸', + 195040 => '𨗒', + 195041 => '𨗭', + 195042 => '邔', + 195043 => '郱', + 195044 => '鄑', + 195045 => '𨜮', + 195046 => '鄛', + 195047 => '鈸', + 195048 => '鋗', + 195049 => '鋘', + 195050 => '鉼', + 195051 => '鏹', + 195052 => '鐕', + 195053 => '𨯺', + 195054 => '開', + 195055 => '䦕', + 195056 => '閷', + 195057 => '𨵷', + 195058 => '䧦', + 195059 => '雃', + 195060 => '嶲', + 195061 => '霣', + 195062 => '𩅅', + 195063 => '𩈚', + 195064 => '䩮', + 195065 => '䩶', + 195066 => '韠', + 195067 => '𩐊', + 195068 => '䪲', + 195069 => '𩒖', + 195070 => '頋', + 195071 => '頋', + 195072 => '頩', + 195073 => '𩖶', + 195074 => '飢', + 195075 => '䬳', + 195076 => '餩', + 195077 => '馧', + 195078 => '駂', + 195079 => '駾', + 195080 => '䯎', + 195081 => '𩬰', + 195082 => '鬒', + 195083 => '鱀', + 195084 => '鳽', + 195085 => '䳎', + 195086 => '䳭', + 195087 => '鵧', + 195088 => '𪃎', + 195089 => '䳸', + 195090 => '𪄅', + 195091 => '𪈎', + 195092 => '𪊑', + 195093 => '麻', + 195094 => '䵖', + 195095 => '黹', + 195096 => '黾', + 195097 => '鼅', + 195098 => '鼏', + 195099 => '鼖', + 195100 => '鼻', + 195101 => '𪘀', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/virama.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/virama.php new file mode 100644 index 0000000..1958e37 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/Resources/unidata/virama.php @@ -0,0 +1,65 @@ + 9, + 2509 => 9, + 2637 => 9, + 2765 => 9, + 2893 => 9, + 3021 => 9, + 3149 => 9, + 3277 => 9, + 3387 => 9, + 3388 => 9, + 3405 => 9, + 3530 => 9, + 3642 => 9, + 3770 => 9, + 3972 => 9, + 4153 => 9, + 4154 => 9, + 5908 => 9, + 5940 => 9, + 6098 => 9, + 6752 => 9, + 6980 => 9, + 7082 => 9, + 7083 => 9, + 7154 => 9, + 7155 => 9, + 11647 => 9, + 43014 => 9, + 43052 => 9, + 43204 => 9, + 43347 => 9, + 43456 => 9, + 43766 => 9, + 44013 => 9, + 68159 => 9, + 69702 => 9, + 69759 => 9, + 69817 => 9, + 69939 => 9, + 69940 => 9, + 70080 => 9, + 70197 => 9, + 70378 => 9, + 70477 => 9, + 70722 => 9, + 70850 => 9, + 71103 => 9, + 71231 => 9, + 71350 => 9, + 71467 => 9, + 71737 => 9, + 71997 => 9, + 71998 => 9, + 72160 => 9, + 72244 => 9, + 72263 => 9, + 72345 => 9, + 72767 => 9, + 73028 => 9, + 73029 => 9, + 73111 => 9, +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/bootstrap.php new file mode 100644 index 0000000..57c7835 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/bootstrap.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Idn as p; + +if (extension_loaded('intl')) { + return; +} + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!defined('U_IDNA_PROHIBITED_ERROR')) { + define('U_IDNA_PROHIBITED_ERROR', 66560); +} +if (!defined('U_IDNA_ERROR_START')) { + define('U_IDNA_ERROR_START', 66560); +} +if (!defined('U_IDNA_UNASSIGNED_ERROR')) { + define('U_IDNA_UNASSIGNED_ERROR', 66561); +} +if (!defined('U_IDNA_CHECK_BIDI_ERROR')) { + define('U_IDNA_CHECK_BIDI_ERROR', 66562); +} +if (!defined('U_IDNA_STD3_ASCII_RULES_ERROR')) { + define('U_IDNA_STD3_ASCII_RULES_ERROR', 66563); +} +if (!defined('U_IDNA_ACE_PREFIX_ERROR')) { + define('U_IDNA_ACE_PREFIX_ERROR', 66564); +} +if (!defined('U_IDNA_VERIFICATION_ERROR')) { + define('U_IDNA_VERIFICATION_ERROR', 66565); +} +if (!defined('U_IDNA_LABEL_TOO_LONG_ERROR')) { + define('U_IDNA_LABEL_TOO_LONG_ERROR', 66566); +} +if (!defined('U_IDNA_ZERO_LENGTH_LABEL_ERROR')) { + define('U_IDNA_ZERO_LENGTH_LABEL_ERROR', 66567); +} +if (!defined('U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR')) { + define('U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR', 66568); +} +if (!defined('U_IDNA_ERROR_LIMIT')) { + define('U_IDNA_ERROR_LIMIT', 66569); +} +if (!defined('U_STRINGPREP_PROHIBITED_ERROR')) { + define('U_STRINGPREP_PROHIBITED_ERROR', 66560); +} +if (!defined('U_STRINGPREP_UNASSIGNED_ERROR')) { + define('U_STRINGPREP_UNASSIGNED_ERROR', 66561); +} +if (!defined('U_STRINGPREP_CHECK_BIDI_ERROR')) { + define('U_STRINGPREP_CHECK_BIDI_ERROR', 66562); +} +if (!defined('IDNA_DEFAULT')) { + define('IDNA_DEFAULT', 0); +} +if (!defined('IDNA_ALLOW_UNASSIGNED')) { + define('IDNA_ALLOW_UNASSIGNED', 1); +} +if (!defined('IDNA_USE_STD3_RULES')) { + define('IDNA_USE_STD3_RULES', 2); +} +if (!defined('IDNA_CHECK_BIDI')) { + define('IDNA_CHECK_BIDI', 4); +} +if (!defined('IDNA_CHECK_CONTEXTJ')) { + define('IDNA_CHECK_CONTEXTJ', 8); +} +if (!defined('IDNA_NONTRANSITIONAL_TO_ASCII')) { + define('IDNA_NONTRANSITIONAL_TO_ASCII', 16); +} +if (!defined('IDNA_NONTRANSITIONAL_TO_UNICODE')) { + define('IDNA_NONTRANSITIONAL_TO_UNICODE', 32); +} +if (!defined('INTL_IDNA_VARIANT_2003')) { + define('INTL_IDNA_VARIANT_2003', 0); +} +if (!defined('INTL_IDNA_VARIANT_UTS46')) { + define('INTL_IDNA_VARIANT_UTS46', 1); +} +if (!defined('IDNA_ERROR_EMPTY_LABEL')) { + define('IDNA_ERROR_EMPTY_LABEL', 1); +} +if (!defined('IDNA_ERROR_LABEL_TOO_LONG')) { + define('IDNA_ERROR_LABEL_TOO_LONG', 2); +} +if (!defined('IDNA_ERROR_DOMAIN_NAME_TOO_LONG')) { + define('IDNA_ERROR_DOMAIN_NAME_TOO_LONG', 4); +} +if (!defined('IDNA_ERROR_LEADING_HYPHEN')) { + define('IDNA_ERROR_LEADING_HYPHEN', 8); +} +if (!defined('IDNA_ERROR_TRAILING_HYPHEN')) { + define('IDNA_ERROR_TRAILING_HYPHEN', 16); +} +if (!defined('IDNA_ERROR_HYPHEN_3_4')) { + define('IDNA_ERROR_HYPHEN_3_4', 32); +} +if (!defined('IDNA_ERROR_LEADING_COMBINING_MARK')) { + define('IDNA_ERROR_LEADING_COMBINING_MARK', 64); +} +if (!defined('IDNA_ERROR_DISALLOWED')) { + define('IDNA_ERROR_DISALLOWED', 128); +} +if (!defined('IDNA_ERROR_PUNYCODE')) { + define('IDNA_ERROR_PUNYCODE', 256); +} +if (!defined('IDNA_ERROR_LABEL_HAS_DOT')) { + define('IDNA_ERROR_LABEL_HAS_DOT', 512); +} +if (!defined('IDNA_ERROR_INVALID_ACE_LABEL')) { + define('IDNA_ERROR_INVALID_ACE_LABEL', 1024); +} +if (!defined('IDNA_ERROR_BIDI')) { + define('IDNA_ERROR_BIDI', 2048); +} +if (!defined('IDNA_ERROR_CONTEXTJ')) { + define('IDNA_ERROR_CONTEXTJ', 4096); +} + +if (\PHP_VERSION_ID < 70400) { + if (!function_exists('idn_to_ascii')) { + function idn_to_ascii($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_2003, &$idna_info = null) { return p\Idn::idn_to_ascii($domain, $flags, $variant, $idna_info); } + } + if (!function_exists('idn_to_utf8')) { + function idn_to_utf8($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_2003, &$idna_info = null) { return p\Idn::idn_to_utf8($domain, $flags, $variant, $idna_info); } + } +} else { + if (!function_exists('idn_to_ascii')) { + function idn_to_ascii($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_UTS46, &$idna_info = null) { return p\Idn::idn_to_ascii($domain, $flags, $variant, $idna_info); } + } + if (!function_exists('idn_to_utf8')) { + function idn_to_utf8($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_UTS46, &$idna_info = null) { return p\Idn::idn_to_utf8($domain, $flags, $variant, $idna_info); } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/bootstrap80.php b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/bootstrap80.php new file mode 100644 index 0000000..a62c2d6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/bootstrap80.php @@ -0,0 +1,125 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Idn as p; + +if (!defined('U_IDNA_PROHIBITED_ERROR')) { + define('U_IDNA_PROHIBITED_ERROR', 66560); +} +if (!defined('U_IDNA_ERROR_START')) { + define('U_IDNA_ERROR_START', 66560); +} +if (!defined('U_IDNA_UNASSIGNED_ERROR')) { + define('U_IDNA_UNASSIGNED_ERROR', 66561); +} +if (!defined('U_IDNA_CHECK_BIDI_ERROR')) { + define('U_IDNA_CHECK_BIDI_ERROR', 66562); +} +if (!defined('U_IDNA_STD3_ASCII_RULES_ERROR')) { + define('U_IDNA_STD3_ASCII_RULES_ERROR', 66563); +} +if (!defined('U_IDNA_ACE_PREFIX_ERROR')) { + define('U_IDNA_ACE_PREFIX_ERROR', 66564); +} +if (!defined('U_IDNA_VERIFICATION_ERROR')) { + define('U_IDNA_VERIFICATION_ERROR', 66565); +} +if (!defined('U_IDNA_LABEL_TOO_LONG_ERROR')) { + define('U_IDNA_LABEL_TOO_LONG_ERROR', 66566); +} +if (!defined('U_IDNA_ZERO_LENGTH_LABEL_ERROR')) { + define('U_IDNA_ZERO_LENGTH_LABEL_ERROR', 66567); +} +if (!defined('U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR')) { + define('U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR', 66568); +} +if (!defined('U_IDNA_ERROR_LIMIT')) { + define('U_IDNA_ERROR_LIMIT', 66569); +} +if (!defined('U_STRINGPREP_PROHIBITED_ERROR')) { + define('U_STRINGPREP_PROHIBITED_ERROR', 66560); +} +if (!defined('U_STRINGPREP_UNASSIGNED_ERROR')) { + define('U_STRINGPREP_UNASSIGNED_ERROR', 66561); +} +if (!defined('U_STRINGPREP_CHECK_BIDI_ERROR')) { + define('U_STRINGPREP_CHECK_BIDI_ERROR', 66562); +} +if (!defined('IDNA_DEFAULT')) { + define('IDNA_DEFAULT', 0); +} +if (!defined('IDNA_ALLOW_UNASSIGNED')) { + define('IDNA_ALLOW_UNASSIGNED', 1); +} +if (!defined('IDNA_USE_STD3_RULES')) { + define('IDNA_USE_STD3_RULES', 2); +} +if (!defined('IDNA_CHECK_BIDI')) { + define('IDNA_CHECK_BIDI', 4); +} +if (!defined('IDNA_CHECK_CONTEXTJ')) { + define('IDNA_CHECK_CONTEXTJ', 8); +} +if (!defined('IDNA_NONTRANSITIONAL_TO_ASCII')) { + define('IDNA_NONTRANSITIONAL_TO_ASCII', 16); +} +if (!defined('IDNA_NONTRANSITIONAL_TO_UNICODE')) { + define('IDNA_NONTRANSITIONAL_TO_UNICODE', 32); +} +if (!defined('INTL_IDNA_VARIANT_UTS46')) { + define('INTL_IDNA_VARIANT_UTS46', 1); +} +if (!defined('IDNA_ERROR_EMPTY_LABEL')) { + define('IDNA_ERROR_EMPTY_LABEL', 1); +} +if (!defined('IDNA_ERROR_LABEL_TOO_LONG')) { + define('IDNA_ERROR_LABEL_TOO_LONG', 2); +} +if (!defined('IDNA_ERROR_DOMAIN_NAME_TOO_LONG')) { + define('IDNA_ERROR_DOMAIN_NAME_TOO_LONG', 4); +} +if (!defined('IDNA_ERROR_LEADING_HYPHEN')) { + define('IDNA_ERROR_LEADING_HYPHEN', 8); +} +if (!defined('IDNA_ERROR_TRAILING_HYPHEN')) { + define('IDNA_ERROR_TRAILING_HYPHEN', 16); +} +if (!defined('IDNA_ERROR_HYPHEN_3_4')) { + define('IDNA_ERROR_HYPHEN_3_4', 32); +} +if (!defined('IDNA_ERROR_LEADING_COMBINING_MARK')) { + define('IDNA_ERROR_LEADING_COMBINING_MARK', 64); +} +if (!defined('IDNA_ERROR_DISALLOWED')) { + define('IDNA_ERROR_DISALLOWED', 128); +} +if (!defined('IDNA_ERROR_PUNYCODE')) { + define('IDNA_ERROR_PUNYCODE', 256); +} +if (!defined('IDNA_ERROR_LABEL_HAS_DOT')) { + define('IDNA_ERROR_LABEL_HAS_DOT', 512); +} +if (!defined('IDNA_ERROR_INVALID_ACE_LABEL')) { + define('IDNA_ERROR_INVALID_ACE_LABEL', 1024); +} +if (!defined('IDNA_ERROR_BIDI')) { + define('IDNA_ERROR_BIDI', 2048); +} +if (!defined('IDNA_ERROR_CONTEXTJ')) { + define('IDNA_ERROR_CONTEXTJ', 4096); +} + +if (!function_exists('idn_to_ascii')) { + function idn_to_ascii(?string $domain, ?int $flags = IDNA_DEFAULT, ?int $variant = INTL_IDNA_VARIANT_UTS46, &$idna_info = null): string|false { return p\Idn::idn_to_ascii((string) $domain, (int) $flags, (int) $variant, $idna_info); } +} +if (!function_exists('idn_to_utf8')) { + function idn_to_utf8(?string $domain, ?int $flags = IDNA_DEFAULT, ?int $variant = INTL_IDNA_VARIANT_UTS46, &$idna_info = null): string|false { return p\Idn::idn_to_utf8((string) $domain, (int) $flags, (int) $variant, $idna_info); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-idn/composer.json b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/composer.json new file mode 100644 index 0000000..12f75bc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-idn/composer.json @@ -0,0 +1,41 @@ +{ + "name": "symfony/polyfill-intl-idn", + "type": "library", + "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", + "keywords": ["polyfill", "shim", "compatibility", "portable", "intl", "idn"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Laurent Bassin", + "email": "laurent@bassin.info" + }, + { + "name": "Trevor Rowbotham", + "email": "trevor.rowbotham@pm.me" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1", + "symfony/polyfill-intl-normalizer": "^1.10", + "symfony/polyfill-php72": "^1.10" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Intl\\Idn\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-intl": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/LICENSE new file mode 100644 index 0000000..6e3afce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Normalizer.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Normalizer.php new file mode 100644 index 0000000..81704ab --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Normalizer.php @@ -0,0 +1,310 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Normalizer; + +/** + * Normalizer is a PHP fallback implementation of the Normalizer class provided by the intl extension. + * + * It has been validated with Unicode 6.3 Normalization Conformance Test. + * See http://www.unicode.org/reports/tr15/ for detailed info about Unicode normalizations. + * + * @author Nicolas Grekas + * + * @internal + */ +class Normalizer +{ + public const FORM_D = \Normalizer::FORM_D; + public const FORM_KD = \Normalizer::FORM_KD; + public const FORM_C = \Normalizer::FORM_C; + public const FORM_KC = \Normalizer::FORM_KC; + public const NFD = \Normalizer::NFD; + public const NFKD = \Normalizer::NFKD; + public const NFC = \Normalizer::NFC; + public const NFKC = \Normalizer::NFKC; + + private static $C; + private static $D; + private static $KD; + private static $cC; + private static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + private static $ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; + + public static function isNormalized(string $s, int $form = self::FORM_C) + { + if (!\in_array($form, [self::NFD, self::NFKD, self::NFC, self::NFKC])) { + return false; + } + if (!isset($s[strspn($s, self::$ASCII)])) { + return true; + } + if (self::NFC == $form && preg_match('//u', $s) && !preg_match('/[^\x00-\x{2FF}]/u', $s)) { + return true; + } + + return self::normalize($s, $form) === $s; + } + + public static function normalize(string $s, int $form = self::FORM_C) + { + if (!preg_match('//u', $s)) { + return false; + } + + switch ($form) { + case self::NFC: $C = true; $K = false; break; + case self::NFD: $C = false; $K = false; break; + case self::NFKC: $C = true; $K = true; break; + case self::NFKD: $C = false; $K = true; break; + default: + if (\defined('Normalizer::NONE') && \Normalizer::NONE == $form) { + return $s; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError('normalizer_normalize(): Argument #2 ($form) must be a a valid normalization form'); + } + + if ('' === $s) { + return ''; + } + + if ($K && null === self::$KD) { + self::$KD = self::getData('compatibilityDecomposition'); + } + + if (null === self::$D) { + self::$D = self::getData('canonicalDecomposition'); + self::$cC = self::getData('combiningClass'); + } + + if (null !== $mbEncoding = (2 /* MB_OVERLOAD_STRING */ & (int) \ini_get('mbstring.func_overload')) ? mb_internal_encoding() : null) { + mb_internal_encoding('8bit'); + } + + $r = self::decompose($s, $K); + + if ($C) { + if (null === self::$C) { + self::$C = self::getData('canonicalComposition'); + } + + $r = self::recompose($r); + } + if (null !== $mbEncoding) { + mb_internal_encoding($mbEncoding); + } + + return $r; + } + + private static function recompose($s) + { + $ASCII = self::$ASCII; + $compMap = self::$C; + $combClass = self::$cC; + $ulenMask = self::$ulenMask; + + $result = $tail = ''; + + $i = $s[0] < "\x80" ? 1 : $ulenMask[$s[0] & "\xF0"]; + $len = \strlen($s); + + $lastUchr = substr($s, 0, $i); + $lastUcls = isset($combClass[$lastUchr]) ? 256 : 0; + + while ($i < $len) { + if ($s[$i] < "\x80") { + // ASCII chars + + if ($tail) { + $lastUchr .= $tail; + $tail = ''; + } + + if ($j = strspn($s, $ASCII, $i + 1)) { + $lastUchr .= substr($s, $i, $j); + $i += $j; + } + + $result .= $lastUchr; + $lastUchr = $s[$i]; + $lastUcls = 0; + ++$i; + continue; + } + + $ulen = $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + + if ($lastUchr < "\xE1\x84\x80" || "\xE1\x84\x92" < $lastUchr + || $uchr < "\xE1\x85\xA1" || "\xE1\x85\xB5" < $uchr + || $lastUcls) { + // Table lookup and combining chars composition + + $ucls = $combClass[$uchr] ?? 0; + + if (isset($compMap[$lastUchr.$uchr]) && (!$lastUcls || $lastUcls < $ucls)) { + $lastUchr = $compMap[$lastUchr.$uchr]; + } elseif ($lastUcls = $ucls) { + $tail .= $uchr; + } else { + if ($tail) { + $lastUchr .= $tail; + $tail = ''; + } + + $result .= $lastUchr; + $lastUchr = $uchr; + } + } else { + // Hangul chars + + $L = \ord($lastUchr[2]) - 0x80; + $V = \ord($uchr[2]) - 0xA1; + $T = 0; + + $uchr = substr($s, $i + $ulen, 3); + + if ("\xE1\x86\xA7" <= $uchr && $uchr <= "\xE1\x87\x82") { + $T = \ord($uchr[2]) - 0xA7; + 0 > $T && $T += 0x40; + $ulen += 3; + } + + $L = 0xAC00 + ($L * 21 + $V) * 28 + $T; + $lastUchr = \chr(0xE0 | $L >> 12).\chr(0x80 | $L >> 6 & 0x3F).\chr(0x80 | $L & 0x3F); + } + + $i += $ulen; + } + + return $result.$lastUchr.$tail; + } + + private static function decompose($s, $c) + { + $result = ''; + + $ASCII = self::$ASCII; + $decompMap = self::$D; + $combClass = self::$cC; + $ulenMask = self::$ulenMask; + if ($c) { + $compatMap = self::$KD; + } + + $c = []; + $i = 0; + $len = \strlen($s); + + while ($i < $len) { + if ($s[$i] < "\x80") { + // ASCII chars + + if ($c) { + ksort($c); + $result .= implode('', $c); + $c = []; + } + + $j = 1 + strspn($s, $ASCII, $i + 1); + $result .= substr($s, $i, $j); + $i += $j; + continue; + } + + $ulen = $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + if ($uchr < "\xEA\xB0\x80" || "\xED\x9E\xA3" < $uchr) { + // Table lookup + + if ($uchr !== $j = $compatMap[$uchr] ?? ($decompMap[$uchr] ?? $uchr)) { + $uchr = $j; + + $j = \strlen($uchr); + $ulen = $uchr[0] < "\x80" ? 1 : $ulenMask[$uchr[0] & "\xF0"]; + + if ($ulen != $j) { + // Put trailing chars in $s + + $j -= $ulen; + $i -= $j; + + if (0 > $i) { + $s = str_repeat(' ', -$i).$s; + $len -= $i; + $i = 0; + } + + while ($j--) { + $s[$i + $j] = $uchr[$ulen + $j]; + } + + $uchr = substr($uchr, 0, $ulen); + } + } + if (isset($combClass[$uchr])) { + // Combining chars, for sorting + + if (!isset($c[$combClass[$uchr]])) { + $c[$combClass[$uchr]] = ''; + } + $c[$combClass[$uchr]] .= $uchr; + continue; + } + } else { + // Hangul chars + + $uchr = unpack('C*', $uchr); + $j = (($uchr[1] - 224) << 12) + (($uchr[2] - 128) << 6) + $uchr[3] - 0xAC80; + + $uchr = "\xE1\x84".\chr(0x80 + (int) ($j / 588)) + ."\xE1\x85".\chr(0xA1 + (int) (($j % 588) / 28)); + + if ($j %= 28) { + $uchr .= $j < 25 + ? ("\xE1\x86".\chr(0xA7 + $j)) + : ("\xE1\x87".\chr(0x67 + $j)); + } + } + if ($c) { + ksort($c); + $result .= implode('', $c); + $c = []; + } + + $result .= $uchr; + } + + if ($c) { + ksort($c); + $result .= implode('', $c); + } + + return $result; + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { + return require $file; + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/README.md b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/README.md new file mode 100644 index 0000000..b9b762e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/README.md @@ -0,0 +1,14 @@ +Symfony Polyfill / Intl: Normalizer +=================================== + +This component provides a fallback implementation for the +[`Normalizer`](https://php.net/Normalizer) class provided +by the [Intl](https://php.net/intl) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php new file mode 100644 index 0000000..0fdfc89 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php @@ -0,0 +1,17 @@ + 'À', + 'Á' => 'Á', + 'Â' => 'Â', + 'Ã' => 'Ã', + 'Ä' => 'Ä', + 'Å' => 'Å', + 'Ç' => 'Ç', + 'È' => 'È', + 'É' => 'É', + 'Ê' => 'Ê', + 'Ë' => 'Ë', + 'Ì' => 'Ì', + 'Í' => 'Í', + 'Î' => 'Î', + 'Ï' => 'Ï', + 'Ñ' => 'Ñ', + 'Ò' => 'Ò', + 'Ó' => 'Ó', + 'Ô' => 'Ô', + 'Õ' => 'Õ', + 'Ö' => 'Ö', + 'Ù' => 'Ù', + 'Ú' => 'Ú', + 'Û' => 'Û', + 'Ü' => 'Ü', + 'Ý' => 'Ý', + 'à' => 'à', + 'á' => 'á', + 'â' => 'â', + 'ã' => 'ã', + 'ä' => 'ä', + 'å' => 'å', + 'ç' => 'ç', + 'è' => 'è', + 'é' => 'é', + 'ê' => 'ê', + 'ë' => 'ë', + 'ì' => 'ì', + 'í' => 'í', + 'î' => 'î', + 'ï' => 'ï', + 'ñ' => 'ñ', + 'ò' => 'ò', + 'ó' => 'ó', + 'ô' => 'ô', + 'õ' => 'õ', + 'ö' => 'ö', + 'ù' => 'ù', + 'ú' => 'ú', + 'û' => 'û', + 'ü' => 'ü', + 'ý' => 'ý', + 'ÿ' => 'ÿ', + 'Ā' => 'Ā', + 'ā' => 'ā', + 'Ă' => 'Ă', + 'ă' => 'ă', + 'Ą' => 'Ą', + 'ą' => 'ą', + 'Ć' => 'Ć', + 'ć' => 'ć', + 'Ĉ' => 'Ĉ', + 'ĉ' => 'ĉ', + 'Ċ' => 'Ċ', + 'ċ' => 'ċ', + 'Č' => 'Č', + 'č' => 'č', + 'Ď' => 'Ď', + 'ď' => 'ď', + 'Ē' => 'Ē', + 'ē' => 'ē', + 'Ĕ' => 'Ĕ', + 'ĕ' => 'ĕ', + 'Ė' => 'Ė', + 'ė' => 'ė', + 'Ę' => 'Ę', + 'ę' => 'ę', + 'Ě' => 'Ě', + 'ě' => 'ě', + 'Ĝ' => 'Ĝ', + 'ĝ' => 'ĝ', + 'Ğ' => 'Ğ', + 'ğ' => 'ğ', + 'Ġ' => 'Ġ', + 'ġ' => 'ġ', + 'Ģ' => 'Ģ', + 'ģ' => 'ģ', + 'Ĥ' => 'Ĥ', + 'ĥ' => 'ĥ', + 'Ĩ' => 'Ĩ', + 'ĩ' => 'ĩ', + 'Ī' => 'Ī', + 'ī' => 'ī', + 'Ĭ' => 'Ĭ', + 'ĭ' => 'ĭ', + 'Į' => 'Į', + 'į' => 'į', + 'İ' => 'İ', + 'Ĵ' => 'Ĵ', + 'ĵ' => 'ĵ', + 'Ķ' => 'Ķ', + 'ķ' => 'ķ', + 'Ĺ' => 'Ĺ', + 'ĺ' => 'ĺ', + 'Ļ' => 'Ļ', + 'ļ' => 'ļ', + 'Ľ' => 'Ľ', + 'ľ' => 'ľ', + 'Ń' => 'Ń', + 'ń' => 'ń', + 'Ņ' => 'Ņ', + 'ņ' => 'ņ', + 'Ň' => 'Ň', + 'ň' => 'ň', + 'Ō' => 'Ō', + 'ō' => 'ō', + 'Ŏ' => 'Ŏ', + 'ŏ' => 'ŏ', + 'Ő' => 'Ő', + 'ő' => 'ő', + 'Ŕ' => 'Ŕ', + 'ŕ' => 'ŕ', + 'Ŗ' => 'Ŗ', + 'ŗ' => 'ŗ', + 'Ř' => 'Ř', + 'ř' => 'ř', + 'Ś' => 'Ś', + 'ś' => 'ś', + 'Ŝ' => 'Ŝ', + 'ŝ' => 'ŝ', + 'Ş' => 'Ş', + 'ş' => 'ş', + 'Š' => 'Š', + 'š' => 'š', + 'Ţ' => 'Ţ', + 'ţ' => 'ţ', + 'Ť' => 'Ť', + 'ť' => 'ť', + 'Ũ' => 'Ũ', + 'ũ' => 'ũ', + 'Ū' => 'Ū', + 'ū' => 'ū', + 'Ŭ' => 'Ŭ', + 'ŭ' => 'ŭ', + 'Ů' => 'Ů', + 'ů' => 'ů', + 'Ű' => 'Ű', + 'ű' => 'ű', + 'Ų' => 'Ų', + 'ų' => 'ų', + 'Ŵ' => 'Ŵ', + 'ŵ' => 'ŵ', + 'Ŷ' => 'Ŷ', + 'ŷ' => 'ŷ', + 'Ÿ' => 'Ÿ', + 'Ź' => 'Ź', + 'ź' => 'ź', + 'Ż' => 'Ż', + 'ż' => 'ż', + 'Ž' => 'Ž', + 'ž' => 'ž', + 'Ơ' => 'Ơ', + 'ơ' => 'ơ', + 'Ư' => 'Ư', + 'ư' => 'ư', + 'Ǎ' => 'Ǎ', + 'ǎ' => 'ǎ', + 'Ǐ' => 'Ǐ', + 'ǐ' => 'ǐ', + 'Ǒ' => 'Ǒ', + 'ǒ' => 'ǒ', + 'Ǔ' => 'Ǔ', + 'ǔ' => 'ǔ', + 'Ǖ' => 'Ǖ', + 'ǖ' => 'ǖ', + 'Ǘ' => 'Ǘ', + 'ǘ' => 'ǘ', + 'Ǚ' => 'Ǚ', + 'ǚ' => 'ǚ', + 'Ǜ' => 'Ǜ', + 'ǜ' => 'ǜ', + 'Ǟ' => 'Ǟ', + 'ǟ' => 'ǟ', + 'Ǡ' => 'Ǡ', + 'ǡ' => 'ǡ', + 'Ǣ' => 'Ǣ', + 'ǣ' => 'ǣ', + 'Ǧ' => 'Ǧ', + 'ǧ' => 'ǧ', + 'Ǩ' => 'Ǩ', + 'ǩ' => 'ǩ', + 'Ǫ' => 'Ǫ', + 'ǫ' => 'ǫ', + 'Ǭ' => 'Ǭ', + 'ǭ' => 'ǭ', + 'Ǯ' => 'Ǯ', + 'ǯ' => 'ǯ', + 'ǰ' => 'ǰ', + 'Ǵ' => 'Ǵ', + 'ǵ' => 'ǵ', + 'Ǹ' => 'Ǹ', + 'ǹ' => 'ǹ', + 'Ǻ' => 'Ǻ', + 'ǻ' => 'ǻ', + 'Ǽ' => 'Ǽ', + 'ǽ' => 'ǽ', + 'Ǿ' => 'Ǿ', + 'ǿ' => 'ǿ', + 'Ȁ' => 'Ȁ', + 'ȁ' => 'ȁ', + 'Ȃ' => 'Ȃ', + 'ȃ' => 'ȃ', + 'Ȅ' => 'Ȅ', + 'ȅ' => 'ȅ', + 'Ȇ' => 'Ȇ', + 'ȇ' => 'ȇ', + 'Ȉ' => 'Ȉ', + 'ȉ' => 'ȉ', + 'Ȋ' => 'Ȋ', + 'ȋ' => 'ȋ', + 'Ȍ' => 'Ȍ', + 'ȍ' => 'ȍ', + 'Ȏ' => 'Ȏ', + 'ȏ' => 'ȏ', + 'Ȑ' => 'Ȑ', + 'ȑ' => 'ȑ', + 'Ȓ' => 'Ȓ', + 'ȓ' => 'ȓ', + 'Ȕ' => 'Ȕ', + 'ȕ' => 'ȕ', + 'Ȗ' => 'Ȗ', + 'ȗ' => 'ȗ', + 'Ș' => 'Ș', + 'ș' => 'ș', + 'Ț' => 'Ț', + 'ț' => 'ț', + 'Ȟ' => 'Ȟ', + 'ȟ' => 'ȟ', + 'Ȧ' => 'Ȧ', + 'ȧ' => 'ȧ', + 'Ȩ' => 'Ȩ', + 'ȩ' => 'ȩ', + 'Ȫ' => 'Ȫ', + 'ȫ' => 'ȫ', + 'Ȭ' => 'Ȭ', + 'ȭ' => 'ȭ', + 'Ȯ' => 'Ȯ', + 'ȯ' => 'ȯ', + 'Ȱ' => 'Ȱ', + 'ȱ' => 'ȱ', + 'Ȳ' => 'Ȳ', + 'ȳ' => 'ȳ', + '΅' => '΅', + 'Ά' => 'Ά', + 'Έ' => 'Έ', + 'Ή' => 'Ή', + 'Ί' => 'Ί', + 'Ό' => 'Ό', + 'Ύ' => 'Ύ', + 'Ώ' => 'Ώ', + 'ΐ' => 'ΐ', + 'Ϊ' => 'Ϊ', + 'Ϋ' => 'Ϋ', + 'ά' => 'ά', + 'έ' => 'έ', + 'ή' => 'ή', + 'ί' => 'ί', + 'ΰ' => 'ΰ', + 'ϊ' => 'ϊ', + 'ϋ' => 'ϋ', + 'ό' => 'ό', + 'ύ' => 'ύ', + 'ώ' => 'ώ', + 'ϓ' => 'ϓ', + 'ϔ' => 'ϔ', + 'Ѐ' => 'Ѐ', + 'Ё' => 'Ё', + 'Ѓ' => 'Ѓ', + 'Ї' => 'Ї', + 'Ќ' => 'Ќ', + 'Ѝ' => 'Ѝ', + 'Ў' => 'Ў', + 'Й' => 'Й', + 'й' => 'й', + 'ѐ' => 'ѐ', + 'ё' => 'ё', + 'ѓ' => 'ѓ', + 'ї' => 'ї', + 'ќ' => 'ќ', + 'ѝ' => 'ѝ', + 'ў' => 'ў', + 'Ѷ' => 'Ѷ', + 'ѷ' => 'ѷ', + 'Ӂ' => 'Ӂ', + 'ӂ' => 'ӂ', + 'Ӑ' => 'Ӑ', + 'ӑ' => 'ӑ', + 'Ӓ' => 'Ӓ', + 'ӓ' => 'ӓ', + 'Ӗ' => 'Ӗ', + 'ӗ' => 'ӗ', + 'Ӛ' => 'Ӛ', + 'ӛ' => 'ӛ', + 'Ӝ' => 'Ӝ', + 'ӝ' => 'ӝ', + 'Ӟ' => 'Ӟ', + 'ӟ' => 'ӟ', + 'Ӣ' => 'Ӣ', + 'ӣ' => 'ӣ', + 'Ӥ' => 'Ӥ', + 'ӥ' => 'ӥ', + 'Ӧ' => 'Ӧ', + 'ӧ' => 'ӧ', + 'Ӫ' => 'Ӫ', + 'ӫ' => 'ӫ', + 'Ӭ' => 'Ӭ', + 'ӭ' => 'ӭ', + 'Ӯ' => 'Ӯ', + 'ӯ' => 'ӯ', + 'Ӱ' => 'Ӱ', + 'ӱ' => 'ӱ', + 'Ӳ' => 'Ӳ', + 'ӳ' => 'ӳ', + 'Ӵ' => 'Ӵ', + 'ӵ' => 'ӵ', + 'Ӹ' => 'Ӹ', + 'ӹ' => 'ӹ', + 'آ' => 'آ', + 'أ' => 'أ', + 'ؤ' => 'ؤ', + 'إ' => 'إ', + 'ئ' => 'ئ', + 'ۀ' => 'ۀ', + 'ۂ' => 'ۂ', + 'ۓ' => 'ۓ', + 'ऩ' => 'ऩ', + 'ऱ' => 'ऱ', + 'ऴ' => 'ऴ', + 'ো' => 'ো', + 'ৌ' => 'ৌ', + 'ୈ' => 'ୈ', + 'ୋ' => 'ୋ', + 'ୌ' => 'ୌ', + 'ஔ' => 'ஔ', + 'ொ' => 'ொ', + 'ோ' => 'ோ', + 'ௌ' => 'ௌ', + 'ై' => 'ై', + 'ೀ' => 'ೀ', + 'ೇ' => 'ೇ', + 'ೈ' => 'ೈ', + 'ೊ' => 'ೊ', + 'ೋ' => 'ೋ', + 'ൊ' => 'ൊ', + 'ോ' => 'ോ', + 'ൌ' => 'ൌ', + 'ේ' => 'ේ', + 'ො' => 'ො', + 'ෝ' => 'ෝ', + 'ෞ' => 'ෞ', + 'ဦ' => 'ဦ', + 'ᬆ' => 'ᬆ', + 'ᬈ' => 'ᬈ', + 'ᬊ' => 'ᬊ', + 'ᬌ' => 'ᬌ', + 'ᬎ' => 'ᬎ', + 'ᬒ' => 'ᬒ', + 'ᬻ' => 'ᬻ', + 'ᬽ' => 'ᬽ', + 'ᭀ' => 'ᭀ', + 'ᭁ' => 'ᭁ', + 'ᭃ' => 'ᭃ', + 'Ḁ' => 'Ḁ', + 'ḁ' => 'ḁ', + 'Ḃ' => 'Ḃ', + 'ḃ' => 'ḃ', + 'Ḅ' => 'Ḅ', + 'ḅ' => 'ḅ', + 'Ḇ' => 'Ḇ', + 'ḇ' => 'ḇ', + 'Ḉ' => 'Ḉ', + 'ḉ' => 'ḉ', + 'Ḋ' => 'Ḋ', + 'ḋ' => 'ḋ', + 'Ḍ' => 'Ḍ', + 'ḍ' => 'ḍ', + 'Ḏ' => 'Ḏ', + 'ḏ' => 'ḏ', + 'Ḑ' => 'Ḑ', + 'ḑ' => 'ḑ', + 'Ḓ' => 'Ḓ', + 'ḓ' => 'ḓ', + 'Ḕ' => 'Ḕ', + 'ḕ' => 'ḕ', + 'Ḗ' => 'Ḗ', + 'ḗ' => 'ḗ', + 'Ḙ' => 'Ḙ', + 'ḙ' => 'ḙ', + 'Ḛ' => 'Ḛ', + 'ḛ' => 'ḛ', + 'Ḝ' => 'Ḝ', + 'ḝ' => 'ḝ', + 'Ḟ' => 'Ḟ', + 'ḟ' => 'ḟ', + 'Ḡ' => 'Ḡ', + 'ḡ' => 'ḡ', + 'Ḣ' => 'Ḣ', + 'ḣ' => 'ḣ', + 'Ḥ' => 'Ḥ', + 'ḥ' => 'ḥ', + 'Ḧ' => 'Ḧ', + 'ḧ' => 'ḧ', + 'Ḩ' => 'Ḩ', + 'ḩ' => 'ḩ', + 'Ḫ' => 'Ḫ', + 'ḫ' => 'ḫ', + 'Ḭ' => 'Ḭ', + 'ḭ' => 'ḭ', + 'Ḯ' => 'Ḯ', + 'ḯ' => 'ḯ', + 'Ḱ' => 'Ḱ', + 'ḱ' => 'ḱ', + 'Ḳ' => 'Ḳ', + 'ḳ' => 'ḳ', + 'Ḵ' => 'Ḵ', + 'ḵ' => 'ḵ', + 'Ḷ' => 'Ḷ', + 'ḷ' => 'ḷ', + 'Ḹ' => 'Ḹ', + 'ḹ' => 'ḹ', + 'Ḻ' => 'Ḻ', + 'ḻ' => 'ḻ', + 'Ḽ' => 'Ḽ', + 'ḽ' => 'ḽ', + 'Ḿ' => 'Ḿ', + 'ḿ' => 'ḿ', + 'Ṁ' => 'Ṁ', + 'ṁ' => 'ṁ', + 'Ṃ' => 'Ṃ', + 'ṃ' => 'ṃ', + 'Ṅ' => 'Ṅ', + 'ṅ' => 'ṅ', + 'Ṇ' => 'Ṇ', + 'ṇ' => 'ṇ', + 'Ṉ' => 'Ṉ', + 'ṉ' => 'ṉ', + 'Ṋ' => 'Ṋ', + 'ṋ' => 'ṋ', + 'Ṍ' => 'Ṍ', + 'ṍ' => 'ṍ', + 'Ṏ' => 'Ṏ', + 'ṏ' => 'ṏ', + 'Ṑ' => 'Ṑ', + 'ṑ' => 'ṑ', + 'Ṓ' => 'Ṓ', + 'ṓ' => 'ṓ', + 'Ṕ' => 'Ṕ', + 'ṕ' => 'ṕ', + 'Ṗ' => 'Ṗ', + 'ṗ' => 'ṗ', + 'Ṙ' => 'Ṙ', + 'ṙ' => 'ṙ', + 'Ṛ' => 'Ṛ', + 'ṛ' => 'ṛ', + 'Ṝ' => 'Ṝ', + 'ṝ' => 'ṝ', + 'Ṟ' => 'Ṟ', + 'ṟ' => 'ṟ', + 'Ṡ' => 'Ṡ', + 'ṡ' => 'ṡ', + 'Ṣ' => 'Ṣ', + 'ṣ' => 'ṣ', + 'Ṥ' => 'Ṥ', + 'ṥ' => 'ṥ', + 'Ṧ' => 'Ṧ', + 'ṧ' => 'ṧ', + 'Ṩ' => 'Ṩ', + 'ṩ' => 'ṩ', + 'Ṫ' => 'Ṫ', + 'ṫ' => 'ṫ', + 'Ṭ' => 'Ṭ', + 'ṭ' => 'ṭ', + 'Ṯ' => 'Ṯ', + 'ṯ' => 'ṯ', + 'Ṱ' => 'Ṱ', + 'ṱ' => 'ṱ', + 'Ṳ' => 'Ṳ', + 'ṳ' => 'ṳ', + 'Ṵ' => 'Ṵ', + 'ṵ' => 'ṵ', + 'Ṷ' => 'Ṷ', + 'ṷ' => 'ṷ', + 'Ṹ' => 'Ṹ', + 'ṹ' => 'ṹ', + 'Ṻ' => 'Ṻ', + 'ṻ' => 'ṻ', + 'Ṽ' => 'Ṽ', + 'ṽ' => 'ṽ', + 'Ṿ' => 'Ṿ', + 'ṿ' => 'ṿ', + 'Ẁ' => 'Ẁ', + 'ẁ' => 'ẁ', + 'Ẃ' => 'Ẃ', + 'ẃ' => 'ẃ', + 'Ẅ' => 'Ẅ', + 'ẅ' => 'ẅ', + 'Ẇ' => 'Ẇ', + 'ẇ' => 'ẇ', + 'Ẉ' => 'Ẉ', + 'ẉ' => 'ẉ', + 'Ẋ' => 'Ẋ', + 'ẋ' => 'ẋ', + 'Ẍ' => 'Ẍ', + 'ẍ' => 'ẍ', + 'Ẏ' => 'Ẏ', + 'ẏ' => 'ẏ', + 'Ẑ' => 'Ẑ', + 'ẑ' => 'ẑ', + 'Ẓ' => 'Ẓ', + 'ẓ' => 'ẓ', + 'Ẕ' => 'Ẕ', + 'ẕ' => 'ẕ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẛ' => 'ẛ', + 'Ạ' => 'Ạ', + 'ạ' => 'ạ', + 'Ả' => 'Ả', + 'ả' => 'ả', + 'Ấ' => 'Ấ', + 'ấ' => 'ấ', + 'Ầ' => 'Ầ', + 'ầ' => 'ầ', + 'Ẩ' => 'Ẩ', + 'ẩ' => 'ẩ', + 'Ẫ' => 'Ẫ', + 'ẫ' => 'ẫ', + 'Ậ' => 'Ậ', + 'ậ' => 'ậ', + 'Ắ' => 'Ắ', + 'ắ' => 'ắ', + 'Ằ' => 'Ằ', + 'ằ' => 'ằ', + 'Ẳ' => 'Ẳ', + 'ẳ' => 'ẳ', + 'Ẵ' => 'Ẵ', + 'ẵ' => 'ẵ', + 'Ặ' => 'Ặ', + 'ặ' => 'ặ', + 'Ẹ' => 'Ẹ', + 'ẹ' => 'ẹ', + 'Ẻ' => 'Ẻ', + 'ẻ' => 'ẻ', + 'Ẽ' => 'Ẽ', + 'ẽ' => 'ẽ', + 'Ế' => 'Ế', + 'ế' => 'ế', + 'Ề' => 'Ề', + 'ề' => 'ề', + 'Ể' => 'Ể', + 'ể' => 'ể', + 'Ễ' => 'Ễ', + 'ễ' => 'ễ', + 'Ệ' => 'Ệ', + 'ệ' => 'ệ', + 'Ỉ' => 'Ỉ', + 'ỉ' => 'ỉ', + 'Ị' => 'Ị', + 'ị' => 'ị', + 'Ọ' => 'Ọ', + 'ọ' => 'ọ', + 'Ỏ' => 'Ỏ', + 'ỏ' => 'ỏ', + 'Ố' => 'Ố', + 'ố' => 'ố', + 'Ồ' => 'Ồ', + 'ồ' => 'ồ', + 'Ổ' => 'Ổ', + 'ổ' => 'ổ', + 'Ỗ' => 'Ỗ', + 'ỗ' => 'ỗ', + 'Ộ' => 'Ộ', + 'ộ' => 'ộ', + 'Ớ' => 'Ớ', + 'ớ' => 'ớ', + 'Ờ' => 'Ờ', + 'ờ' => 'ờ', + 'Ở' => 'Ở', + 'ở' => 'ở', + 'Ỡ' => 'Ỡ', + 'ỡ' => 'ỡ', + 'Ợ' => 'Ợ', + 'ợ' => 'ợ', + 'Ụ' => 'Ụ', + 'ụ' => 'ụ', + 'Ủ' => 'Ủ', + 'ủ' => 'ủ', + 'Ứ' => 'Ứ', + 'ứ' => 'ứ', + 'Ừ' => 'Ừ', + 'ừ' => 'ừ', + 'Ử' => 'Ử', + 'ử' => 'ử', + 'Ữ' => 'Ữ', + 'ữ' => 'ữ', + 'Ự' => 'Ự', + 'ự' => 'ự', + 'Ỳ' => 'Ỳ', + 'ỳ' => 'ỳ', + 'Ỵ' => 'Ỵ', + 'ỵ' => 'ỵ', + 'Ỷ' => 'Ỷ', + 'ỷ' => 'ỷ', + 'Ỹ' => 'Ỹ', + 'ỹ' => 'ỹ', + 'ἀ' => 'ἀ', + 'ἁ' => 'ἁ', + 'ἂ' => 'ἂ', + 'ἃ' => 'ἃ', + 'ἄ' => 'ἄ', + 'ἅ' => 'ἅ', + 'ἆ' => 'ἆ', + 'ἇ' => 'ἇ', + 'Ἀ' => 'Ἀ', + 'Ἁ' => 'Ἁ', + 'Ἂ' => 'Ἂ', + 'Ἃ' => 'Ἃ', + 'Ἄ' => 'Ἄ', + 'Ἅ' => 'Ἅ', + 'Ἆ' => 'Ἆ', + 'Ἇ' => 'Ἇ', + 'ἐ' => 'ἐ', + 'ἑ' => 'ἑ', + 'ἒ' => 'ἒ', + 'ἓ' => 'ἓ', + 'ἔ' => 'ἔ', + 'ἕ' => 'ἕ', + 'Ἐ' => 'Ἐ', + 'Ἑ' => 'Ἑ', + 'Ἒ' => 'Ἒ', + 'Ἓ' => 'Ἓ', + 'Ἔ' => 'Ἔ', + 'Ἕ' => 'Ἕ', + 'ἠ' => 'ἠ', + 'ἡ' => 'ἡ', + 'ἢ' => 'ἢ', + 'ἣ' => 'ἣ', + 'ἤ' => 'ἤ', + 'ἥ' => 'ἥ', + 'ἦ' => 'ἦ', + 'ἧ' => 'ἧ', + 'Ἠ' => 'Ἠ', + 'Ἡ' => 'Ἡ', + 'Ἢ' => 'Ἢ', + 'Ἣ' => 'Ἣ', + 'Ἤ' => 'Ἤ', + 'Ἥ' => 'Ἥ', + 'Ἦ' => 'Ἦ', + 'Ἧ' => 'Ἧ', + 'ἰ' => 'ἰ', + 'ἱ' => 'ἱ', + 'ἲ' => 'ἲ', + 'ἳ' => 'ἳ', + 'ἴ' => 'ἴ', + 'ἵ' => 'ἵ', + 'ἶ' => 'ἶ', + 'ἷ' => 'ἷ', + 'Ἰ' => 'Ἰ', + 'Ἱ' => 'Ἱ', + 'Ἲ' => 'Ἲ', + 'Ἳ' => 'Ἳ', + 'Ἴ' => 'Ἴ', + 'Ἵ' => 'Ἵ', + 'Ἶ' => 'Ἶ', + 'Ἷ' => 'Ἷ', + 'ὀ' => 'ὀ', + 'ὁ' => 'ὁ', + 'ὂ' => 'ὂ', + 'ὃ' => 'ὃ', + 'ὄ' => 'ὄ', + 'ὅ' => 'ὅ', + 'Ὀ' => 'Ὀ', + 'Ὁ' => 'Ὁ', + 'Ὂ' => 'Ὂ', + 'Ὃ' => 'Ὃ', + 'Ὄ' => 'Ὄ', + 'Ὅ' => 'Ὅ', + 'ὐ' => 'ὐ', + 'ὑ' => 'ὑ', + 'ὒ' => 'ὒ', + 'ὓ' => 'ὓ', + 'ὔ' => 'ὔ', + 'ὕ' => 'ὕ', + 'ὖ' => 'ὖ', + 'ὗ' => 'ὗ', + 'Ὑ' => 'Ὑ', + 'Ὓ' => 'Ὓ', + 'Ὕ' => 'Ὕ', + 'Ὗ' => 'Ὗ', + 'ὠ' => 'ὠ', + 'ὡ' => 'ὡ', + 'ὢ' => 'ὢ', + 'ὣ' => 'ὣ', + 'ὤ' => 'ὤ', + 'ὥ' => 'ὥ', + 'ὦ' => 'ὦ', + 'ὧ' => 'ὧ', + 'Ὠ' => 'Ὠ', + 'Ὡ' => 'Ὡ', + 'Ὢ' => 'Ὢ', + 'Ὣ' => 'Ὣ', + 'Ὤ' => 'Ὤ', + 'Ὥ' => 'Ὥ', + 'Ὦ' => 'Ὦ', + 'Ὧ' => 'Ὧ', + 'ὰ' => 'ὰ', + 'ὲ' => 'ὲ', + 'ὴ' => 'ὴ', + 'ὶ' => 'ὶ', + 'ὸ' => 'ὸ', + 'ὺ' => 'ὺ', + 'ὼ' => 'ὼ', + 'ᾀ' => 'ᾀ', + 'ᾁ' => 'ᾁ', + 'ᾂ' => 'ᾂ', + 'ᾃ' => 'ᾃ', + 'ᾄ' => 'ᾄ', + 'ᾅ' => 'ᾅ', + 'ᾆ' => 'ᾆ', + 'ᾇ' => 'ᾇ', + 'ᾈ' => 'ᾈ', + 'ᾉ' => 'ᾉ', + 'ᾊ' => 'ᾊ', + 'ᾋ' => 'ᾋ', + 'ᾌ' => 'ᾌ', + 'ᾍ' => 'ᾍ', + 'ᾎ' => 'ᾎ', + 'ᾏ' => 'ᾏ', + 'ᾐ' => 'ᾐ', + 'ᾑ' => 'ᾑ', + 'ᾒ' => 'ᾒ', + 'ᾓ' => 'ᾓ', + 'ᾔ' => 'ᾔ', + 'ᾕ' => 'ᾕ', + 'ᾖ' => 'ᾖ', + 'ᾗ' => 'ᾗ', + 'ᾘ' => 'ᾘ', + 'ᾙ' => 'ᾙ', + 'ᾚ' => 'ᾚ', + 'ᾛ' => 'ᾛ', + 'ᾜ' => 'ᾜ', + 'ᾝ' => 'ᾝ', + 'ᾞ' => 'ᾞ', + 'ᾟ' => 'ᾟ', + 'ᾠ' => 'ᾠ', + 'ᾡ' => 'ᾡ', + 'ᾢ' => 'ᾢ', + 'ᾣ' => 'ᾣ', + 'ᾤ' => 'ᾤ', + 'ᾥ' => 'ᾥ', + 'ᾦ' => 'ᾦ', + 'ᾧ' => 'ᾧ', + 'ᾨ' => 'ᾨ', + 'ᾩ' => 'ᾩ', + 'ᾪ' => 'ᾪ', + 'ᾫ' => 'ᾫ', + 'ᾬ' => 'ᾬ', + 'ᾭ' => 'ᾭ', + 'ᾮ' => 'ᾮ', + 'ᾯ' => 'ᾯ', + 'ᾰ' => 'ᾰ', + 'ᾱ' => 'ᾱ', + 'ᾲ' => 'ᾲ', + 'ᾳ' => 'ᾳ', + 'ᾴ' => 'ᾴ', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾷ', + 'Ᾰ' => 'Ᾰ', + 'Ᾱ' => 'Ᾱ', + 'Ὰ' => 'Ὰ', + 'ᾼ' => 'ᾼ', + '῁' => '῁', + 'ῂ' => 'ῂ', + 'ῃ' => 'ῃ', + 'ῄ' => 'ῄ', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῇ', + 'Ὲ' => 'Ὲ', + 'Ὴ' => 'Ὴ', + 'ῌ' => 'ῌ', + '῍' => '῍', + '῎' => '῎', + '῏' => '῏', + 'ῐ' => 'ῐ', + 'ῑ' => 'ῑ', + 'ῒ' => 'ῒ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'Ῐ' => 'Ῐ', + 'Ῑ' => 'Ῑ', + 'Ὶ' => 'Ὶ', + '῝' => '῝', + '῞' => '῞', + '῟' => '῟', + 'ῠ' => 'ῠ', + 'ῡ' => 'ῡ', + 'ῢ' => 'ῢ', + 'ῤ' => 'ῤ', + 'ῥ' => 'ῥ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'Ῠ' => 'Ῠ', + 'Ῡ' => 'Ῡ', + 'Ὺ' => 'Ὺ', + 'Ῥ' => 'Ῥ', + '῭' => '῭', + 'ῲ' => 'ῲ', + 'ῳ' => 'ῳ', + 'ῴ' => 'ῴ', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῷ', + 'Ὸ' => 'Ὸ', + 'Ὼ' => 'Ὼ', + 'ῼ' => 'ῼ', + '↚' => '↚', + '↛' => '↛', + '↮' => '↮', + '⇍' => '⇍', + '⇎' => '⇎', + '⇏' => '⇏', + '∄' => '∄', + '∉' => '∉', + '∌' => '∌', + '∤' => '∤', + '∦' => '∦', + '≁' => '≁', + '≄' => '≄', + '≇' => '≇', + '≉' => '≉', + '≠' => '≠', + '≢' => '≢', + '≭' => '≭', + '≮' => '≮', + '≯' => '≯', + '≰' => '≰', + '≱' => '≱', + '≴' => '≴', + '≵' => '≵', + '≸' => '≸', + '≹' => '≹', + '⊀' => '⊀', + '⊁' => '⊁', + '⊄' => '⊄', + '⊅' => '⊅', + '⊈' => '⊈', + '⊉' => '⊉', + '⊬' => '⊬', + '⊭' => '⊭', + '⊮' => '⊮', + '⊯' => '⊯', + '⋠' => '⋠', + '⋡' => '⋡', + '⋢' => '⋢', + '⋣' => '⋣', + '⋪' => '⋪', + '⋫' => '⋫', + '⋬' => '⋬', + '⋭' => '⋭', + 'が' => 'が', + 'ぎ' => 'ぎ', + 'ぐ' => 'ぐ', + 'げ' => 'げ', + 'ご' => 'ご', + 'ざ' => 'ざ', + 'じ' => 'じ', + 'ず' => 'ず', + 'ぜ' => 'ぜ', + 'ぞ' => 'ぞ', + 'だ' => 'だ', + 'ぢ' => 'ぢ', + 'づ' => 'づ', + 'で' => 'で', + 'ど' => 'ど', + 'ば' => 'ば', + 'ぱ' => 'ぱ', + 'び' => 'び', + 'ぴ' => 'ぴ', + 'ぶ' => 'ぶ', + 'ぷ' => 'ぷ', + 'べ' => 'べ', + 'ぺ' => 'ぺ', + 'ぼ' => 'ぼ', + 'ぽ' => 'ぽ', + 'ゔ' => 'ゔ', + 'ゞ' => 'ゞ', + 'ガ' => 'ガ', + 'ギ' => 'ギ', + 'グ' => 'グ', + 'ゲ' => 'ゲ', + 'ゴ' => 'ゴ', + 'ザ' => 'ザ', + 'ジ' => 'ジ', + 'ズ' => 'ズ', + 'ゼ' => 'ゼ', + 'ゾ' => 'ゾ', + 'ダ' => 'ダ', + 'ヂ' => 'ヂ', + 'ヅ' => 'ヅ', + 'デ' => 'デ', + 'ド' => 'ド', + 'バ' => 'バ', + 'パ' => 'パ', + 'ビ' => 'ビ', + 'ピ' => 'ピ', + 'ブ' => 'ブ', + 'プ' => 'プ', + 'ベ' => 'ベ', + 'ペ' => 'ペ', + 'ボ' => 'ボ', + 'ポ' => 'ポ', + 'ヴ' => 'ヴ', + 'ヷ' => 'ヷ', + 'ヸ' => 'ヸ', + 'ヹ' => 'ヹ', + 'ヺ' => 'ヺ', + 'ヾ' => 'ヾ', + '𑂚' => '𑂚', + '𑂜' => '𑂜', + '𑂫' => '𑂫', + '𑄮' => '𑄮', + '𑄯' => '𑄯', + '𑍋' => '𑍋', + '𑍌' => '𑍌', + '𑒻' => '𑒻', + '𑒼' => '𑒼', + '𑒾' => '𑒾', + '𑖺' => '𑖺', + '𑖻' => '𑖻', + '𑤸' => '𑤸', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/canonicalDecomposition.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/canonicalDecomposition.php new file mode 100644 index 0000000..5a3e8e0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/canonicalDecomposition.php @@ -0,0 +1,2065 @@ + 'À', + 'Á' => 'Á', + 'Â' => 'Â', + 'Ã' => 'Ã', + 'Ä' => 'Ä', + 'Å' => 'Å', + 'Ç' => 'Ç', + 'È' => 'È', + 'É' => 'É', + 'Ê' => 'Ê', + 'Ë' => 'Ë', + 'Ì' => 'Ì', + 'Í' => 'Í', + 'Î' => 'Î', + 'Ï' => 'Ï', + 'Ñ' => 'Ñ', + 'Ò' => 'Ò', + 'Ó' => 'Ó', + 'Ô' => 'Ô', + 'Õ' => 'Õ', + 'Ö' => 'Ö', + 'Ù' => 'Ù', + 'Ú' => 'Ú', + 'Û' => 'Û', + 'Ü' => 'Ü', + 'Ý' => 'Ý', + 'à' => 'à', + 'á' => 'á', + 'â' => 'â', + 'ã' => 'ã', + 'ä' => 'ä', + 'å' => 'å', + 'ç' => 'ç', + 'è' => 'è', + 'é' => 'é', + 'ê' => 'ê', + 'ë' => 'ë', + 'ì' => 'ì', + 'í' => 'í', + 'î' => 'î', + 'ï' => 'ï', + 'ñ' => 'ñ', + 'ò' => 'ò', + 'ó' => 'ó', + 'ô' => 'ô', + 'õ' => 'õ', + 'ö' => 'ö', + 'ù' => 'ù', + 'ú' => 'ú', + 'û' => 'û', + 'ü' => 'ü', + 'ý' => 'ý', + 'ÿ' => 'ÿ', + 'Ā' => 'Ā', + 'ā' => 'ā', + 'Ă' => 'Ă', + 'ă' => 'ă', + 'Ą' => 'Ą', + 'ą' => 'ą', + 'Ć' => 'Ć', + 'ć' => 'ć', + 'Ĉ' => 'Ĉ', + 'ĉ' => 'ĉ', + 'Ċ' => 'Ċ', + 'ċ' => 'ċ', + 'Č' => 'Č', + 'č' => 'č', + 'Ď' => 'Ď', + 'ď' => 'ď', + 'Ē' => 'Ē', + 'ē' => 'ē', + 'Ĕ' => 'Ĕ', + 'ĕ' => 'ĕ', + 'Ė' => 'Ė', + 'ė' => 'ė', + 'Ę' => 'Ę', + 'ę' => 'ę', + 'Ě' => 'Ě', + 'ě' => 'ě', + 'Ĝ' => 'Ĝ', + 'ĝ' => 'ĝ', + 'Ğ' => 'Ğ', + 'ğ' => 'ğ', + 'Ġ' => 'Ġ', + 'ġ' => 'ġ', + 'Ģ' => 'Ģ', + 'ģ' => 'ģ', + 'Ĥ' => 'Ĥ', + 'ĥ' => 'ĥ', + 'Ĩ' => 'Ĩ', + 'ĩ' => 'ĩ', + 'Ī' => 'Ī', + 'ī' => 'ī', + 'Ĭ' => 'Ĭ', + 'ĭ' => 'ĭ', + 'Į' => 'Į', + 'į' => 'į', + 'İ' => 'İ', + 'Ĵ' => 'Ĵ', + 'ĵ' => 'ĵ', + 'Ķ' => 'Ķ', + 'ķ' => 'ķ', + 'Ĺ' => 'Ĺ', + 'ĺ' => 'ĺ', + 'Ļ' => 'Ļ', + 'ļ' => 'ļ', + 'Ľ' => 'Ľ', + 'ľ' => 'ľ', + 'Ń' => 'Ń', + 'ń' => 'ń', + 'Ņ' => 'Ņ', + 'ņ' => 'ņ', + 'Ň' => 'Ň', + 'ň' => 'ň', + 'Ō' => 'Ō', + 'ō' => 'ō', + 'Ŏ' => 'Ŏ', + 'ŏ' => 'ŏ', + 'Ő' => 'Ő', + 'ő' => 'ő', + 'Ŕ' => 'Ŕ', + 'ŕ' => 'ŕ', + 'Ŗ' => 'Ŗ', + 'ŗ' => 'ŗ', + 'Ř' => 'Ř', + 'ř' => 'ř', + 'Ś' => 'Ś', + 'ś' => 'ś', + 'Ŝ' => 'Ŝ', + 'ŝ' => 'ŝ', + 'Ş' => 'Ş', + 'ş' => 'ş', + 'Š' => 'Š', + 'š' => 'š', + 'Ţ' => 'Ţ', + 'ţ' => 'ţ', + 'Ť' => 'Ť', + 'ť' => 'ť', + 'Ũ' => 'Ũ', + 'ũ' => 'ũ', + 'Ū' => 'Ū', + 'ū' => 'ū', + 'Ŭ' => 'Ŭ', + 'ŭ' => 'ŭ', + 'Ů' => 'Ů', + 'ů' => 'ů', + 'Ű' => 'Ű', + 'ű' => 'ű', + 'Ų' => 'Ų', + 'ų' => 'ų', + 'Ŵ' => 'Ŵ', + 'ŵ' => 'ŵ', + 'Ŷ' => 'Ŷ', + 'ŷ' => 'ŷ', + 'Ÿ' => 'Ÿ', + 'Ź' => 'Ź', + 'ź' => 'ź', + 'Ż' => 'Ż', + 'ż' => 'ż', + 'Ž' => 'Ž', + 'ž' => 'ž', + 'Ơ' => 'Ơ', + 'ơ' => 'ơ', + 'Ư' => 'Ư', + 'ư' => 'ư', + 'Ǎ' => 'Ǎ', + 'ǎ' => 'ǎ', + 'Ǐ' => 'Ǐ', + 'ǐ' => 'ǐ', + 'Ǒ' => 'Ǒ', + 'ǒ' => 'ǒ', + 'Ǔ' => 'Ǔ', + 'ǔ' => 'ǔ', + 'Ǖ' => 'Ǖ', + 'ǖ' => 'ǖ', + 'Ǘ' => 'Ǘ', + 'ǘ' => 'ǘ', + 'Ǚ' => 'Ǚ', + 'ǚ' => 'ǚ', + 'Ǜ' => 'Ǜ', + 'ǜ' => 'ǜ', + 'Ǟ' => 'Ǟ', + 'ǟ' => 'ǟ', + 'Ǡ' => 'Ǡ', + 'ǡ' => 'ǡ', + 'Ǣ' => 'Ǣ', + 'ǣ' => 'ǣ', + 'Ǧ' => 'Ǧ', + 'ǧ' => 'ǧ', + 'Ǩ' => 'Ǩ', + 'ǩ' => 'ǩ', + 'Ǫ' => 'Ǫ', + 'ǫ' => 'ǫ', + 'Ǭ' => 'Ǭ', + 'ǭ' => 'ǭ', + 'Ǯ' => 'Ǯ', + 'ǯ' => 'ǯ', + 'ǰ' => 'ǰ', + 'Ǵ' => 'Ǵ', + 'ǵ' => 'ǵ', + 'Ǹ' => 'Ǹ', + 'ǹ' => 'ǹ', + 'Ǻ' => 'Ǻ', + 'ǻ' => 'ǻ', + 'Ǽ' => 'Ǽ', + 'ǽ' => 'ǽ', + 'Ǿ' => 'Ǿ', + 'ǿ' => 'ǿ', + 'Ȁ' => 'Ȁ', + 'ȁ' => 'ȁ', + 'Ȃ' => 'Ȃ', + 'ȃ' => 'ȃ', + 'Ȅ' => 'Ȅ', + 'ȅ' => 'ȅ', + 'Ȇ' => 'Ȇ', + 'ȇ' => 'ȇ', + 'Ȉ' => 'Ȉ', + 'ȉ' => 'ȉ', + 'Ȋ' => 'Ȋ', + 'ȋ' => 'ȋ', + 'Ȍ' => 'Ȍ', + 'ȍ' => 'ȍ', + 'Ȏ' => 'Ȏ', + 'ȏ' => 'ȏ', + 'Ȑ' => 'Ȑ', + 'ȑ' => 'ȑ', + 'Ȓ' => 'Ȓ', + 'ȓ' => 'ȓ', + 'Ȕ' => 'Ȕ', + 'ȕ' => 'ȕ', + 'Ȗ' => 'Ȗ', + 'ȗ' => 'ȗ', + 'Ș' => 'Ș', + 'ș' => 'ș', + 'Ț' => 'Ț', + 'ț' => 'ț', + 'Ȟ' => 'Ȟ', + 'ȟ' => 'ȟ', + 'Ȧ' => 'Ȧ', + 'ȧ' => 'ȧ', + 'Ȩ' => 'Ȩ', + 'ȩ' => 'ȩ', + 'Ȫ' => 'Ȫ', + 'ȫ' => 'ȫ', + 'Ȭ' => 'Ȭ', + 'ȭ' => 'ȭ', + 'Ȯ' => 'Ȯ', + 'ȯ' => 'ȯ', + 'Ȱ' => 'Ȱ', + 'ȱ' => 'ȱ', + 'Ȳ' => 'Ȳ', + 'ȳ' => 'ȳ', + '̀' => '̀', + '́' => '́', + '̓' => '̓', + '̈́' => '̈́', + 'ʹ' => 'ʹ', + ';' => ';', + '΅' => '΅', + 'Ά' => 'Ά', + '·' => '·', + 'Έ' => 'Έ', + 'Ή' => 'Ή', + 'Ί' => 'Ί', + 'Ό' => 'Ό', + 'Ύ' => 'Ύ', + 'Ώ' => 'Ώ', + 'ΐ' => 'ΐ', + 'Ϊ' => 'Ϊ', + 'Ϋ' => 'Ϋ', + 'ά' => 'ά', + 'έ' => 'έ', + 'ή' => 'ή', + 'ί' => 'ί', + 'ΰ' => 'ΰ', + 'ϊ' => 'ϊ', + 'ϋ' => 'ϋ', + 'ό' => 'ό', + 'ύ' => 'ύ', + 'ώ' => 'ώ', + 'ϓ' => 'ϓ', + 'ϔ' => 'ϔ', + 'Ѐ' => 'Ѐ', + 'Ё' => 'Ё', + 'Ѓ' => 'Ѓ', + 'Ї' => 'Ї', + 'Ќ' => 'Ќ', + 'Ѝ' => 'Ѝ', + 'Ў' => 'Ў', + 'Й' => 'Й', + 'й' => 'й', + 'ѐ' => 'ѐ', + 'ё' => 'ё', + 'ѓ' => 'ѓ', + 'ї' => 'ї', + 'ќ' => 'ќ', + 'ѝ' => 'ѝ', + 'ў' => 'ў', + 'Ѷ' => 'Ѷ', + 'ѷ' => 'ѷ', + 'Ӂ' => 'Ӂ', + 'ӂ' => 'ӂ', + 'Ӑ' => 'Ӑ', + 'ӑ' => 'ӑ', + 'Ӓ' => 'Ӓ', + 'ӓ' => 'ӓ', + 'Ӗ' => 'Ӗ', + 'ӗ' => 'ӗ', + 'Ӛ' => 'Ӛ', + 'ӛ' => 'ӛ', + 'Ӝ' => 'Ӝ', + 'ӝ' => 'ӝ', + 'Ӟ' => 'Ӟ', + 'ӟ' => 'ӟ', + 'Ӣ' => 'Ӣ', + 'ӣ' => 'ӣ', + 'Ӥ' => 'Ӥ', + 'ӥ' => 'ӥ', + 'Ӧ' => 'Ӧ', + 'ӧ' => 'ӧ', + 'Ӫ' => 'Ӫ', + 'ӫ' => 'ӫ', + 'Ӭ' => 'Ӭ', + 'ӭ' => 'ӭ', + 'Ӯ' => 'Ӯ', + 'ӯ' => 'ӯ', + 'Ӱ' => 'Ӱ', + 'ӱ' => 'ӱ', + 'Ӳ' => 'Ӳ', + 'ӳ' => 'ӳ', + 'Ӵ' => 'Ӵ', + 'ӵ' => 'ӵ', + 'Ӹ' => 'Ӹ', + 'ӹ' => 'ӹ', + 'آ' => 'آ', + 'أ' => 'أ', + 'ؤ' => 'ؤ', + 'إ' => 'إ', + 'ئ' => 'ئ', + 'ۀ' => 'ۀ', + 'ۂ' => 'ۂ', + 'ۓ' => 'ۓ', + 'ऩ' => 'ऩ', + 'ऱ' => 'ऱ', + 'ऴ' => 'ऴ', + 'क़' => 'क़', + 'ख़' => 'ख़', + 'ग़' => 'ग़', + 'ज़' => 'ज़', + 'ड़' => 'ड़', + 'ढ़' => 'ढ़', + 'फ़' => 'फ़', + 'य़' => 'य़', + 'ো' => 'ো', + 'ৌ' => 'ৌ', + 'ড়' => 'ড়', + 'ঢ়' => 'ঢ়', + 'য়' => 'য়', + 'ਲ਼' => 'ਲ਼', + 'ਸ਼' => 'ਸ਼', + 'ਖ਼' => 'ਖ਼', + 'ਗ਼' => 'ਗ਼', + 'ਜ਼' => 'ਜ਼', + 'ਫ਼' => 'ਫ਼', + 'ୈ' => 'ୈ', + 'ୋ' => 'ୋ', + 'ୌ' => 'ୌ', + 'ଡ଼' => 'ଡ଼', + 'ଢ଼' => 'ଢ଼', + 'ஔ' => 'ஔ', + 'ொ' => 'ொ', + 'ோ' => 'ோ', + 'ௌ' => 'ௌ', + 'ై' => 'ై', + 'ೀ' => 'ೀ', + 'ೇ' => 'ೇ', + 'ೈ' => 'ೈ', + 'ೊ' => 'ೊ', + 'ೋ' => 'ೋ', + 'ൊ' => 'ൊ', + 'ോ' => 'ോ', + 'ൌ' => 'ൌ', + 'ේ' => 'ේ', + 'ො' => 'ො', + 'ෝ' => 'ෝ', + 'ෞ' => 'ෞ', + 'གྷ' => 'གྷ', + 'ཌྷ' => 'ཌྷ', + 'དྷ' => 'དྷ', + 'བྷ' => 'བྷ', + 'ཛྷ' => 'ཛྷ', + 'ཀྵ' => 'ཀྵ', + 'ཱི' => 'ཱི', + 'ཱུ' => 'ཱུ', + 'ྲྀ' => 'ྲྀ', + 'ླྀ' => 'ླྀ', + 'ཱྀ' => 'ཱྀ', + 'ྒྷ' => 'ྒྷ', + 'ྜྷ' => 'ྜྷ', + 'ྡྷ' => 'ྡྷ', + 'ྦྷ' => 'ྦྷ', + 'ྫྷ' => 'ྫྷ', + 'ྐྵ' => 'ྐྵ', + 'ဦ' => 'ဦ', + 'ᬆ' => 'ᬆ', + 'ᬈ' => 'ᬈ', + 'ᬊ' => 'ᬊ', + 'ᬌ' => 'ᬌ', + 'ᬎ' => 'ᬎ', + 'ᬒ' => 'ᬒ', + 'ᬻ' => 'ᬻ', + 'ᬽ' => 'ᬽ', + 'ᭀ' => 'ᭀ', + 'ᭁ' => 'ᭁ', + 'ᭃ' => 'ᭃ', + 'Ḁ' => 'Ḁ', + 'ḁ' => 'ḁ', + 'Ḃ' => 'Ḃ', + 'ḃ' => 'ḃ', + 'Ḅ' => 'Ḅ', + 'ḅ' => 'ḅ', + 'Ḇ' => 'Ḇ', + 'ḇ' => 'ḇ', + 'Ḉ' => 'Ḉ', + 'ḉ' => 'ḉ', + 'Ḋ' => 'Ḋ', + 'ḋ' => 'ḋ', + 'Ḍ' => 'Ḍ', + 'ḍ' => 'ḍ', + 'Ḏ' => 'Ḏ', + 'ḏ' => 'ḏ', + 'Ḑ' => 'Ḑ', + 'ḑ' => 'ḑ', + 'Ḓ' => 'Ḓ', + 'ḓ' => 'ḓ', + 'Ḕ' => 'Ḕ', + 'ḕ' => 'ḕ', + 'Ḗ' => 'Ḗ', + 'ḗ' => 'ḗ', + 'Ḙ' => 'Ḙ', + 'ḙ' => 'ḙ', + 'Ḛ' => 'Ḛ', + 'ḛ' => 'ḛ', + 'Ḝ' => 'Ḝ', + 'ḝ' => 'ḝ', + 'Ḟ' => 'Ḟ', + 'ḟ' => 'ḟ', + 'Ḡ' => 'Ḡ', + 'ḡ' => 'ḡ', + 'Ḣ' => 'Ḣ', + 'ḣ' => 'ḣ', + 'Ḥ' => 'Ḥ', + 'ḥ' => 'ḥ', + 'Ḧ' => 'Ḧ', + 'ḧ' => 'ḧ', + 'Ḩ' => 'Ḩ', + 'ḩ' => 'ḩ', + 'Ḫ' => 'Ḫ', + 'ḫ' => 'ḫ', + 'Ḭ' => 'Ḭ', + 'ḭ' => 'ḭ', + 'Ḯ' => 'Ḯ', + 'ḯ' => 'ḯ', + 'Ḱ' => 'Ḱ', + 'ḱ' => 'ḱ', + 'Ḳ' => 'Ḳ', + 'ḳ' => 'ḳ', + 'Ḵ' => 'Ḵ', + 'ḵ' => 'ḵ', + 'Ḷ' => 'Ḷ', + 'ḷ' => 'ḷ', + 'Ḹ' => 'Ḹ', + 'ḹ' => 'ḹ', + 'Ḻ' => 'Ḻ', + 'ḻ' => 'ḻ', + 'Ḽ' => 'Ḽ', + 'ḽ' => 'ḽ', + 'Ḿ' => 'Ḿ', + 'ḿ' => 'ḿ', + 'Ṁ' => 'Ṁ', + 'ṁ' => 'ṁ', + 'Ṃ' => 'Ṃ', + 'ṃ' => 'ṃ', + 'Ṅ' => 'Ṅ', + 'ṅ' => 'ṅ', + 'Ṇ' => 'Ṇ', + 'ṇ' => 'ṇ', + 'Ṉ' => 'Ṉ', + 'ṉ' => 'ṉ', + 'Ṋ' => 'Ṋ', + 'ṋ' => 'ṋ', + 'Ṍ' => 'Ṍ', + 'ṍ' => 'ṍ', + 'Ṏ' => 'Ṏ', + 'ṏ' => 'ṏ', + 'Ṑ' => 'Ṑ', + 'ṑ' => 'ṑ', + 'Ṓ' => 'Ṓ', + 'ṓ' => 'ṓ', + 'Ṕ' => 'Ṕ', + 'ṕ' => 'ṕ', + 'Ṗ' => 'Ṗ', + 'ṗ' => 'ṗ', + 'Ṙ' => 'Ṙ', + 'ṙ' => 'ṙ', + 'Ṛ' => 'Ṛ', + 'ṛ' => 'ṛ', + 'Ṝ' => 'Ṝ', + 'ṝ' => 'ṝ', + 'Ṟ' => 'Ṟ', + 'ṟ' => 'ṟ', + 'Ṡ' => 'Ṡ', + 'ṡ' => 'ṡ', + 'Ṣ' => 'Ṣ', + 'ṣ' => 'ṣ', + 'Ṥ' => 'Ṥ', + 'ṥ' => 'ṥ', + 'Ṧ' => 'Ṧ', + 'ṧ' => 'ṧ', + 'Ṩ' => 'Ṩ', + 'ṩ' => 'ṩ', + 'Ṫ' => 'Ṫ', + 'ṫ' => 'ṫ', + 'Ṭ' => 'Ṭ', + 'ṭ' => 'ṭ', + 'Ṯ' => 'Ṯ', + 'ṯ' => 'ṯ', + 'Ṱ' => 'Ṱ', + 'ṱ' => 'ṱ', + 'Ṳ' => 'Ṳ', + 'ṳ' => 'ṳ', + 'Ṵ' => 'Ṵ', + 'ṵ' => 'ṵ', + 'Ṷ' => 'Ṷ', + 'ṷ' => 'ṷ', + 'Ṹ' => 'Ṹ', + 'ṹ' => 'ṹ', + 'Ṻ' => 'Ṻ', + 'ṻ' => 'ṻ', + 'Ṽ' => 'Ṽ', + 'ṽ' => 'ṽ', + 'Ṿ' => 'Ṿ', + 'ṿ' => 'ṿ', + 'Ẁ' => 'Ẁ', + 'ẁ' => 'ẁ', + 'Ẃ' => 'Ẃ', + 'ẃ' => 'ẃ', + 'Ẅ' => 'Ẅ', + 'ẅ' => 'ẅ', + 'Ẇ' => 'Ẇ', + 'ẇ' => 'ẇ', + 'Ẉ' => 'Ẉ', + 'ẉ' => 'ẉ', + 'Ẋ' => 'Ẋ', + 'ẋ' => 'ẋ', + 'Ẍ' => 'Ẍ', + 'ẍ' => 'ẍ', + 'Ẏ' => 'Ẏ', + 'ẏ' => 'ẏ', + 'Ẑ' => 'Ẑ', + 'ẑ' => 'ẑ', + 'Ẓ' => 'Ẓ', + 'ẓ' => 'ẓ', + 'Ẕ' => 'Ẕ', + 'ẕ' => 'ẕ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẛ' => 'ẛ', + 'Ạ' => 'Ạ', + 'ạ' => 'ạ', + 'Ả' => 'Ả', + 'ả' => 'ả', + 'Ấ' => 'Ấ', + 'ấ' => 'ấ', + 'Ầ' => 'Ầ', + 'ầ' => 'ầ', + 'Ẩ' => 'Ẩ', + 'ẩ' => 'ẩ', + 'Ẫ' => 'Ẫ', + 'ẫ' => 'ẫ', + 'Ậ' => 'Ậ', + 'ậ' => 'ậ', + 'Ắ' => 'Ắ', + 'ắ' => 'ắ', + 'Ằ' => 'Ằ', + 'ằ' => 'ằ', + 'Ẳ' => 'Ẳ', + 'ẳ' => 'ẳ', + 'Ẵ' => 'Ẵ', + 'ẵ' => 'ẵ', + 'Ặ' => 'Ặ', + 'ặ' => 'ặ', + 'Ẹ' => 'Ẹ', + 'ẹ' => 'ẹ', + 'Ẻ' => 'Ẻ', + 'ẻ' => 'ẻ', + 'Ẽ' => 'Ẽ', + 'ẽ' => 'ẽ', + 'Ế' => 'Ế', + 'ế' => 'ế', + 'Ề' => 'Ề', + 'ề' => 'ề', + 'Ể' => 'Ể', + 'ể' => 'ể', + 'Ễ' => 'Ễ', + 'ễ' => 'ễ', + 'Ệ' => 'Ệ', + 'ệ' => 'ệ', + 'Ỉ' => 'Ỉ', + 'ỉ' => 'ỉ', + 'Ị' => 'Ị', + 'ị' => 'ị', + 'Ọ' => 'Ọ', + 'ọ' => 'ọ', + 'Ỏ' => 'Ỏ', + 'ỏ' => 'ỏ', + 'Ố' => 'Ố', + 'ố' => 'ố', + 'Ồ' => 'Ồ', + 'ồ' => 'ồ', + 'Ổ' => 'Ổ', + 'ổ' => 'ổ', + 'Ỗ' => 'Ỗ', + 'ỗ' => 'ỗ', + 'Ộ' => 'Ộ', + 'ộ' => 'ộ', + 'Ớ' => 'Ớ', + 'ớ' => 'ớ', + 'Ờ' => 'Ờ', + 'ờ' => 'ờ', + 'Ở' => 'Ở', + 'ở' => 'ở', + 'Ỡ' => 'Ỡ', + 'ỡ' => 'ỡ', + 'Ợ' => 'Ợ', + 'ợ' => 'ợ', + 'Ụ' => 'Ụ', + 'ụ' => 'ụ', + 'Ủ' => 'Ủ', + 'ủ' => 'ủ', + 'Ứ' => 'Ứ', + 'ứ' => 'ứ', + 'Ừ' => 'Ừ', + 'ừ' => 'ừ', + 'Ử' => 'Ử', + 'ử' => 'ử', + 'Ữ' => 'Ữ', + 'ữ' => 'ữ', + 'Ự' => 'Ự', + 'ự' => 'ự', + 'Ỳ' => 'Ỳ', + 'ỳ' => 'ỳ', + 'Ỵ' => 'Ỵ', + 'ỵ' => 'ỵ', + 'Ỷ' => 'Ỷ', + 'ỷ' => 'ỷ', + 'Ỹ' => 'Ỹ', + 'ỹ' => 'ỹ', + 'ἀ' => 'ἀ', + 'ἁ' => 'ἁ', + 'ἂ' => 'ἂ', + 'ἃ' => 'ἃ', + 'ἄ' => 'ἄ', + 'ἅ' => 'ἅ', + 'ἆ' => 'ἆ', + 'ἇ' => 'ἇ', + 'Ἀ' => 'Ἀ', + 'Ἁ' => 'Ἁ', + 'Ἂ' => 'Ἂ', + 'Ἃ' => 'Ἃ', + 'Ἄ' => 'Ἄ', + 'Ἅ' => 'Ἅ', + 'Ἆ' => 'Ἆ', + 'Ἇ' => 'Ἇ', + 'ἐ' => 'ἐ', + 'ἑ' => 'ἑ', + 'ἒ' => 'ἒ', + 'ἓ' => 'ἓ', + 'ἔ' => 'ἔ', + 'ἕ' => 'ἕ', + 'Ἐ' => 'Ἐ', + 'Ἑ' => 'Ἑ', + 'Ἒ' => 'Ἒ', + 'Ἓ' => 'Ἓ', + 'Ἔ' => 'Ἔ', + 'Ἕ' => 'Ἕ', + 'ἠ' => 'ἠ', + 'ἡ' => 'ἡ', + 'ἢ' => 'ἢ', + 'ἣ' => 'ἣ', + 'ἤ' => 'ἤ', + 'ἥ' => 'ἥ', + 'ἦ' => 'ἦ', + 'ἧ' => 'ἧ', + 'Ἠ' => 'Ἠ', + 'Ἡ' => 'Ἡ', + 'Ἢ' => 'Ἢ', + 'Ἣ' => 'Ἣ', + 'Ἤ' => 'Ἤ', + 'Ἥ' => 'Ἥ', + 'Ἦ' => 'Ἦ', + 'Ἧ' => 'Ἧ', + 'ἰ' => 'ἰ', + 'ἱ' => 'ἱ', + 'ἲ' => 'ἲ', + 'ἳ' => 'ἳ', + 'ἴ' => 'ἴ', + 'ἵ' => 'ἵ', + 'ἶ' => 'ἶ', + 'ἷ' => 'ἷ', + 'Ἰ' => 'Ἰ', + 'Ἱ' => 'Ἱ', + 'Ἲ' => 'Ἲ', + 'Ἳ' => 'Ἳ', + 'Ἴ' => 'Ἴ', + 'Ἵ' => 'Ἵ', + 'Ἶ' => 'Ἶ', + 'Ἷ' => 'Ἷ', + 'ὀ' => 'ὀ', + 'ὁ' => 'ὁ', + 'ὂ' => 'ὂ', + 'ὃ' => 'ὃ', + 'ὄ' => 'ὄ', + 'ὅ' => 'ὅ', + 'Ὀ' => 'Ὀ', + 'Ὁ' => 'Ὁ', + 'Ὂ' => 'Ὂ', + 'Ὃ' => 'Ὃ', + 'Ὄ' => 'Ὄ', + 'Ὅ' => 'Ὅ', + 'ὐ' => 'ὐ', + 'ὑ' => 'ὑ', + 'ὒ' => 'ὒ', + 'ὓ' => 'ὓ', + 'ὔ' => 'ὔ', + 'ὕ' => 'ὕ', + 'ὖ' => 'ὖ', + 'ὗ' => 'ὗ', + 'Ὑ' => 'Ὑ', + 'Ὓ' => 'Ὓ', + 'Ὕ' => 'Ὕ', + 'Ὗ' => 'Ὗ', + 'ὠ' => 'ὠ', + 'ὡ' => 'ὡ', + 'ὢ' => 'ὢ', + 'ὣ' => 'ὣ', + 'ὤ' => 'ὤ', + 'ὥ' => 'ὥ', + 'ὦ' => 'ὦ', + 'ὧ' => 'ὧ', + 'Ὠ' => 'Ὠ', + 'Ὡ' => 'Ὡ', + 'Ὢ' => 'Ὢ', + 'Ὣ' => 'Ὣ', + 'Ὤ' => 'Ὤ', + 'Ὥ' => 'Ὥ', + 'Ὦ' => 'Ὦ', + 'Ὧ' => 'Ὧ', + 'ὰ' => 'ὰ', + 'ά' => 'ά', + 'ὲ' => 'ὲ', + 'έ' => 'έ', + 'ὴ' => 'ὴ', + 'ή' => 'ή', + 'ὶ' => 'ὶ', + 'ί' => 'ί', + 'ὸ' => 'ὸ', + 'ό' => 'ό', + 'ὺ' => 'ὺ', + 'ύ' => 'ύ', + 'ὼ' => 'ὼ', + 'ώ' => 'ώ', + 'ᾀ' => 'ᾀ', + 'ᾁ' => 'ᾁ', + 'ᾂ' => 'ᾂ', + 'ᾃ' => 'ᾃ', + 'ᾄ' => 'ᾄ', + 'ᾅ' => 'ᾅ', + 'ᾆ' => 'ᾆ', + 'ᾇ' => 'ᾇ', + 'ᾈ' => 'ᾈ', + 'ᾉ' => 'ᾉ', + 'ᾊ' => 'ᾊ', + 'ᾋ' => 'ᾋ', + 'ᾌ' => 'ᾌ', + 'ᾍ' => 'ᾍ', + 'ᾎ' => 'ᾎ', + 'ᾏ' => 'ᾏ', + 'ᾐ' => 'ᾐ', + 'ᾑ' => 'ᾑ', + 'ᾒ' => 'ᾒ', + 'ᾓ' => 'ᾓ', + 'ᾔ' => 'ᾔ', + 'ᾕ' => 'ᾕ', + 'ᾖ' => 'ᾖ', + 'ᾗ' => 'ᾗ', + 'ᾘ' => 'ᾘ', + 'ᾙ' => 'ᾙ', + 'ᾚ' => 'ᾚ', + 'ᾛ' => 'ᾛ', + 'ᾜ' => 'ᾜ', + 'ᾝ' => 'ᾝ', + 'ᾞ' => 'ᾞ', + 'ᾟ' => 'ᾟ', + 'ᾠ' => 'ᾠ', + 'ᾡ' => 'ᾡ', + 'ᾢ' => 'ᾢ', + 'ᾣ' => 'ᾣ', + 'ᾤ' => 'ᾤ', + 'ᾥ' => 'ᾥ', + 'ᾦ' => 'ᾦ', + 'ᾧ' => 'ᾧ', + 'ᾨ' => 'ᾨ', + 'ᾩ' => 'ᾩ', + 'ᾪ' => 'ᾪ', + 'ᾫ' => 'ᾫ', + 'ᾬ' => 'ᾬ', + 'ᾭ' => 'ᾭ', + 'ᾮ' => 'ᾮ', + 'ᾯ' => 'ᾯ', + 'ᾰ' => 'ᾰ', + 'ᾱ' => 'ᾱ', + 'ᾲ' => 'ᾲ', + 'ᾳ' => 'ᾳ', + 'ᾴ' => 'ᾴ', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾷ', + 'Ᾰ' => 'Ᾰ', + 'Ᾱ' => 'Ᾱ', + 'Ὰ' => 'Ὰ', + 'Ά' => 'Ά', + 'ᾼ' => 'ᾼ', + 'ι' => 'ι', + '῁' => '῁', + 'ῂ' => 'ῂ', + 'ῃ' => 'ῃ', + 'ῄ' => 'ῄ', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῇ', + 'Ὲ' => 'Ὲ', + 'Έ' => 'Έ', + 'Ὴ' => 'Ὴ', + 'Ή' => 'Ή', + 'ῌ' => 'ῌ', + '῍' => '῍', + '῎' => '῎', + '῏' => '῏', + 'ῐ' => 'ῐ', + 'ῑ' => 'ῑ', + 'ῒ' => 'ῒ', + 'ΐ' => 'ΐ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'Ῐ' => 'Ῐ', + 'Ῑ' => 'Ῑ', + 'Ὶ' => 'Ὶ', + 'Ί' => 'Ί', + '῝' => '῝', + '῞' => '῞', + '῟' => '῟', + 'ῠ' => 'ῠ', + 'ῡ' => 'ῡ', + 'ῢ' => 'ῢ', + 'ΰ' => 'ΰ', + 'ῤ' => 'ῤ', + 'ῥ' => 'ῥ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'Ῠ' => 'Ῠ', + 'Ῡ' => 'Ῡ', + 'Ὺ' => 'Ὺ', + 'Ύ' => 'Ύ', + 'Ῥ' => 'Ῥ', + '῭' => '῭', + '΅' => '΅', + '`' => '`', + 'ῲ' => 'ῲ', + 'ῳ' => 'ῳ', + 'ῴ' => 'ῴ', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῷ', + 'Ὸ' => 'Ὸ', + 'Ό' => 'Ό', + 'Ὼ' => 'Ὼ', + 'Ώ' => 'Ώ', + 'ῼ' => 'ῼ', + '´' => '´', + ' ' => ' ', + ' ' => ' ', + 'Ω' => 'Ω', + 'K' => 'K', + 'Å' => 'Å', + '↚' => '↚', + '↛' => '↛', + '↮' => '↮', + '⇍' => '⇍', + '⇎' => '⇎', + '⇏' => '⇏', + '∄' => '∄', + '∉' => '∉', + '∌' => '∌', + '∤' => '∤', + '∦' => '∦', + '≁' => '≁', + '≄' => '≄', + '≇' => '≇', + '≉' => '≉', + '≠' => '≠', + '≢' => '≢', + '≭' => '≭', + '≮' => '≮', + '≯' => '≯', + '≰' => '≰', + '≱' => '≱', + '≴' => '≴', + '≵' => '≵', + '≸' => '≸', + '≹' => '≹', + '⊀' => '⊀', + '⊁' => '⊁', + '⊄' => '⊄', + '⊅' => '⊅', + '⊈' => '⊈', + '⊉' => '⊉', + '⊬' => '⊬', + '⊭' => '⊭', + '⊮' => '⊮', + '⊯' => '⊯', + '⋠' => '⋠', + '⋡' => '⋡', + '⋢' => '⋢', + '⋣' => '⋣', + '⋪' => '⋪', + '⋫' => '⋫', + '⋬' => '⋬', + '⋭' => '⋭', + '〈' => '〈', + '〉' => '〉', + '⫝̸' => '⫝̸', + 'が' => 'が', + 'ぎ' => 'ぎ', + 'ぐ' => 'ぐ', + 'げ' => 'げ', + 'ご' => 'ご', + 'ざ' => 'ざ', + 'じ' => 'じ', + 'ず' => 'ず', + 'ぜ' => 'ぜ', + 'ぞ' => 'ぞ', + 'だ' => 'だ', + 'ぢ' => 'ぢ', + 'づ' => 'づ', + 'で' => 'で', + 'ど' => 'ど', + 'ば' => 'ば', + 'ぱ' => 'ぱ', + 'び' => 'び', + 'ぴ' => 'ぴ', + 'ぶ' => 'ぶ', + 'ぷ' => 'ぷ', + 'べ' => 'べ', + 'ぺ' => 'ぺ', + 'ぼ' => 'ぼ', + 'ぽ' => 'ぽ', + 'ゔ' => 'ゔ', + 'ゞ' => 'ゞ', + 'ガ' => 'ガ', + 'ギ' => 'ギ', + 'グ' => 'グ', + 'ゲ' => 'ゲ', + 'ゴ' => 'ゴ', + 'ザ' => 'ザ', + 'ジ' => 'ジ', + 'ズ' => 'ズ', + 'ゼ' => 'ゼ', + 'ゾ' => 'ゾ', + 'ダ' => 'ダ', + 'ヂ' => 'ヂ', + 'ヅ' => 'ヅ', + 'デ' => 'デ', + 'ド' => 'ド', + 'バ' => 'バ', + 'パ' => 'パ', + 'ビ' => 'ビ', + 'ピ' => 'ピ', + 'ブ' => 'ブ', + 'プ' => 'プ', + 'ベ' => 'ベ', + 'ペ' => 'ペ', + 'ボ' => 'ボ', + 'ポ' => 'ポ', + 'ヴ' => 'ヴ', + 'ヷ' => 'ヷ', + 'ヸ' => 'ヸ', + 'ヹ' => 'ヹ', + 'ヺ' => 'ヺ', + 'ヾ' => 'ヾ', + '豈' => '豈', + '更' => '更', + '車' => '車', + '賈' => '賈', + '滑' => '滑', + '串' => '串', + '句' => '句', + '龜' => '龜', + '龜' => '龜', + '契' => '契', + '金' => '金', + '喇' => '喇', + '奈' => '奈', + '懶' => '懶', + '癩' => '癩', + '羅' => '羅', + '蘿' => '蘿', + '螺' => '螺', + '裸' => '裸', + '邏' => '邏', + '樂' => '樂', + '洛' => '洛', + '烙' => '烙', + '珞' => '珞', + '落' => '落', + '酪' => '酪', + '駱' => '駱', + '亂' => '亂', + '卵' => '卵', + '欄' => '欄', + '爛' => '爛', + '蘭' => '蘭', + '鸞' => '鸞', + '嵐' => '嵐', + '濫' => '濫', + '藍' => '藍', + '襤' => '襤', + '拉' => '拉', + '臘' => '臘', + '蠟' => '蠟', + '廊' => '廊', + '朗' => '朗', + '浪' => '浪', + '狼' => '狼', + '郎' => '郎', + '來' => '來', + '冷' => '冷', + '勞' => '勞', + '擄' => '擄', + '櫓' => '櫓', + '爐' => '爐', + '盧' => '盧', + '老' => '老', + '蘆' => '蘆', + '虜' => '虜', + '路' => '路', + '露' => '露', + '魯' => '魯', + '鷺' => '鷺', + '碌' => '碌', + '祿' => '祿', + '綠' => '綠', + '菉' => '菉', + '錄' => '錄', + '鹿' => '鹿', + '論' => '論', + '壟' => '壟', + '弄' => '弄', + '籠' => '籠', + '聾' => '聾', + '牢' => '牢', + '磊' => '磊', + '賂' => '賂', + '雷' => '雷', + '壘' => '壘', + '屢' => '屢', + '樓' => '樓', + '淚' => '淚', + '漏' => '漏', + '累' => '累', + '縷' => '縷', + '陋' => '陋', + '勒' => '勒', + '肋' => '肋', + '凜' => '凜', + '凌' => '凌', + '稜' => '稜', + '綾' => '綾', + '菱' => '菱', + '陵' => '陵', + '讀' => '讀', + '拏' => '拏', + '樂' => '樂', + '諾' => '諾', + '丹' => '丹', + '寧' => '寧', + '怒' => '怒', + '率' => '率', + '異' => '異', + '北' => '北', + '磻' => '磻', + '便' => '便', + '復' => '復', + '不' => '不', + '泌' => '泌', + '數' => '數', + '索' => '索', + '參' => '參', + '塞' => '塞', + '省' => '省', + '葉' => '葉', + '說' => '說', + '殺' => '殺', + '辰' => '辰', + '沈' => '沈', + '拾' => '拾', + '若' => '若', + '掠' => '掠', + '略' => '略', + '亮' => '亮', + '兩' => '兩', + '凉' => '凉', + '梁' => '梁', + '糧' => '糧', + '良' => '良', + '諒' => '諒', + '量' => '量', + '勵' => '勵', + '呂' => '呂', + '女' => '女', + '廬' => '廬', + '旅' => '旅', + '濾' => '濾', + '礪' => '礪', + '閭' => '閭', + '驪' => '驪', + '麗' => '麗', + '黎' => '黎', + '力' => '力', + '曆' => '曆', + '歷' => '歷', + '轢' => '轢', + '年' => '年', + '憐' => '憐', + '戀' => '戀', + '撚' => '撚', + '漣' => '漣', + '煉' => '煉', + '璉' => '璉', + '秊' => '秊', + '練' => '練', + '聯' => '聯', + '輦' => '輦', + '蓮' => '蓮', + '連' => '連', + '鍊' => '鍊', + '列' => '列', + '劣' => '劣', + '咽' => '咽', + '烈' => '烈', + '裂' => '裂', + '說' => '說', + '廉' => '廉', + '念' => '念', + '捻' => '捻', + '殮' => '殮', + '簾' => '簾', + '獵' => '獵', + '令' => '令', + '囹' => '囹', + '寧' => '寧', + '嶺' => '嶺', + '怜' => '怜', + '玲' => '玲', + '瑩' => '瑩', + '羚' => '羚', + '聆' => '聆', + '鈴' => '鈴', + '零' => '零', + '靈' => '靈', + '領' => '領', + '例' => '例', + '禮' => '禮', + '醴' => '醴', + '隸' => '隸', + '惡' => '惡', + '了' => '了', + '僚' => '僚', + '寮' => '寮', + '尿' => '尿', + '料' => '料', + '樂' => '樂', + '燎' => '燎', + '療' => '療', + '蓼' => '蓼', + '遼' => '遼', + '龍' => '龍', + '暈' => '暈', + '阮' => '阮', + '劉' => '劉', + '杻' => '杻', + '柳' => '柳', + '流' => '流', + '溜' => '溜', + '琉' => '琉', + '留' => '留', + '硫' => '硫', + '紐' => '紐', + '類' => '類', + '六' => '六', + '戮' => '戮', + '陸' => '陸', + '倫' => '倫', + '崙' => '崙', + '淪' => '淪', + '輪' => '輪', + '律' => '律', + '慄' => '慄', + '栗' => '栗', + '率' => '率', + '隆' => '隆', + '利' => '利', + '吏' => '吏', + '履' => '履', + '易' => '易', + '李' => '李', + '梨' => '梨', + '泥' => '泥', + '理' => '理', + '痢' => '痢', + '罹' => '罹', + '裏' => '裏', + '裡' => '裡', + '里' => '里', + '離' => '離', + '匿' => '匿', + '溺' => '溺', + '吝' => '吝', + '燐' => '燐', + '璘' => '璘', + '藺' => '藺', + '隣' => '隣', + '鱗' => '鱗', + '麟' => '麟', + '林' => '林', + '淋' => '淋', + '臨' => '臨', + '立' => '立', + '笠' => '笠', + '粒' => '粒', + '狀' => '狀', + '炙' => '炙', + '識' => '識', + '什' => '什', + '茶' => '茶', + '刺' => '刺', + '切' => '切', + '度' => '度', + '拓' => '拓', + '糖' => '糖', + '宅' => '宅', + '洞' => '洞', + '暴' => '暴', + '輻' => '輻', + '行' => '行', + '降' => '降', + '見' => '見', + '廓' => '廓', + '兀' => '兀', + '嗀' => '嗀', + '塚' => '塚', + '晴' => '晴', + '凞' => '凞', + '猪' => '猪', + '益' => '益', + '礼' => '礼', + '神' => '神', + '祥' => '祥', + '福' => '福', + '靖' => '靖', + '精' => '精', + '羽' => '羽', + '蘒' => '蘒', + '諸' => '諸', + '逸' => '逸', + '都' => '都', + '飯' => '飯', + '飼' => '飼', + '館' => '館', + '鶴' => '鶴', + '郞' => '郞', + '隷' => '隷', + '侮' => '侮', + '僧' => '僧', + '免' => '免', + '勉' => '勉', + '勤' => '勤', + '卑' => '卑', + '喝' => '喝', + '嘆' => '嘆', + '器' => '器', + '塀' => '塀', + '墨' => '墨', + '層' => '層', + '屮' => '屮', + '悔' => '悔', + '慨' => '慨', + '憎' => '憎', + '懲' => '懲', + '敏' => '敏', + '既' => '既', + '暑' => '暑', + '梅' => '梅', + '海' => '海', + '渚' => '渚', + '漢' => '漢', + '煮' => '煮', + '爫' => '爫', + '琢' => '琢', + '碑' => '碑', + '社' => '社', + '祉' => '祉', + '祈' => '祈', + '祐' => '祐', + '祖' => '祖', + '祝' => '祝', + '禍' => '禍', + '禎' => '禎', + '穀' => '穀', + '突' => '突', + '節' => '節', + '練' => '練', + '縉' => '縉', + '繁' => '繁', + '署' => '署', + '者' => '者', + '臭' => '臭', + '艹' => '艹', + '艹' => '艹', + '著' => '著', + '褐' => '褐', + '視' => '視', + '謁' => '謁', + '謹' => '謹', + '賓' => '賓', + '贈' => '贈', + '辶' => '辶', + '逸' => '逸', + '難' => '難', + '響' => '響', + '頻' => '頻', + '恵' => '恵', + '𤋮' => '𤋮', + '舘' => '舘', + '並' => '並', + '况' => '况', + '全' => '全', + '侀' => '侀', + '充' => '充', + '冀' => '冀', + '勇' => '勇', + '勺' => '勺', + '喝' => '喝', + '啕' => '啕', + '喙' => '喙', + '嗢' => '嗢', + '塚' => '塚', + '墳' => '墳', + '奄' => '奄', + '奔' => '奔', + '婢' => '婢', + '嬨' => '嬨', + '廒' => '廒', + '廙' => '廙', + '彩' => '彩', + '徭' => '徭', + '惘' => '惘', + '慎' => '慎', + '愈' => '愈', + '憎' => '憎', + '慠' => '慠', + '懲' => '懲', + '戴' => '戴', + '揄' => '揄', + '搜' => '搜', + '摒' => '摒', + '敖' => '敖', + '晴' => '晴', + '朗' => '朗', + '望' => '望', + '杖' => '杖', + '歹' => '歹', + '殺' => '殺', + '流' => '流', + '滛' => '滛', + '滋' => '滋', + '漢' => '漢', + '瀞' => '瀞', + '煮' => '煮', + '瞧' => '瞧', + '爵' => '爵', + '犯' => '犯', + '猪' => '猪', + '瑱' => '瑱', + '甆' => '甆', + '画' => '画', + '瘝' => '瘝', + '瘟' => '瘟', + '益' => '益', + '盛' => '盛', + '直' => '直', + '睊' => '睊', + '着' => '着', + '磌' => '磌', + '窱' => '窱', + '節' => '節', + '类' => '类', + '絛' => '絛', + '練' => '練', + '缾' => '缾', + '者' => '者', + '荒' => '荒', + '華' => '華', + '蝹' => '蝹', + '襁' => '襁', + '覆' => '覆', + '視' => '視', + '調' => '調', + '諸' => '諸', + '請' => '請', + '謁' => '謁', + '諾' => '諾', + '諭' => '諭', + '謹' => '謹', + '變' => '變', + '贈' => '贈', + '輸' => '輸', + '遲' => '遲', + '醙' => '醙', + '鉶' => '鉶', + '陼' => '陼', + '難' => '難', + '靖' => '靖', + '韛' => '韛', + '響' => '響', + '頋' => '頋', + '頻' => '頻', + '鬒' => '鬒', + '龜' => '龜', + '𢡊' => '𢡊', + '𢡄' => '𢡄', + '𣏕' => '𣏕', + '㮝' => '㮝', + '䀘' => '䀘', + '䀹' => '䀹', + '𥉉' => '𥉉', + '𥳐' => '𥳐', + '𧻓' => '𧻓', + '齃' => '齃', + '龎' => '龎', + 'יִ' => 'יִ', + 'ײַ' => 'ײַ', + 'שׁ' => 'שׁ', + 'שׂ' => 'שׂ', + 'שּׁ' => 'שּׁ', + 'שּׂ' => 'שּׂ', + 'אַ' => 'אַ', + 'אָ' => 'אָ', + 'אּ' => 'אּ', + 'בּ' => 'בּ', + 'גּ' => 'גּ', + 'דּ' => 'דּ', + 'הּ' => 'הּ', + 'וּ' => 'וּ', + 'זּ' => 'זּ', + 'טּ' => 'טּ', + 'יּ' => 'יּ', + 'ךּ' => 'ךּ', + 'כּ' => 'כּ', + 'לּ' => 'לּ', + 'מּ' => 'מּ', + 'נּ' => 'נּ', + 'סּ' => 'סּ', + 'ףּ' => 'ףּ', + 'פּ' => 'פּ', + 'צּ' => 'צּ', + 'קּ' => 'קּ', + 'רּ' => 'רּ', + 'שּ' => 'שּ', + 'תּ' => 'תּ', + 'וֹ' => 'וֹ', + 'בֿ' => 'בֿ', + 'כֿ' => 'כֿ', + 'פֿ' => 'פֿ', + '𑂚' => '𑂚', + '𑂜' => '𑂜', + '𑂫' => '𑂫', + '𑄮' => '𑄮', + '𑄯' => '𑄯', + '𑍋' => '𑍋', + '𑍌' => '𑍌', + '𑒻' => '𑒻', + '𑒼' => '𑒼', + '𑒾' => '𑒾', + '𑖺' => '𑖺', + '𑖻' => '𑖻', + '𑤸' => '𑤸', + '𝅗𝅥' => '𝅗𝅥', + '𝅘𝅥' => '𝅘𝅥', + '𝅘𝅥𝅮' => '𝅘𝅥𝅮', + '𝅘𝅥𝅯' => '𝅘𝅥𝅯', + '𝅘𝅥𝅰' => '𝅘𝅥𝅰', + '𝅘𝅥𝅱' => '𝅘𝅥𝅱', + '𝅘𝅥𝅲' => '𝅘𝅥𝅲', + '𝆹𝅥' => '𝆹𝅥', + '𝆺𝅥' => '𝆺𝅥', + '𝆹𝅥𝅮' => '𝆹𝅥𝅮', + '𝆺𝅥𝅮' => '𝆺𝅥𝅮', + '𝆹𝅥𝅯' => '𝆹𝅥𝅯', + '𝆺𝅥𝅯' => '𝆺𝅥𝅯', + '丽' => '丽', + '丸' => '丸', + '乁' => '乁', + '𠄢' => '𠄢', + '你' => '你', + '侮' => '侮', + '侻' => '侻', + '倂' => '倂', + '偺' => '偺', + '備' => '備', + '僧' => '僧', + '像' => '像', + '㒞' => '㒞', + '𠘺' => '𠘺', + '免' => '免', + '兔' => '兔', + '兤' => '兤', + '具' => '具', + '𠔜' => '𠔜', + '㒹' => '㒹', + '內' => '內', + '再' => '再', + '𠕋' => '𠕋', + '冗' => '冗', + '冤' => '冤', + '仌' => '仌', + '冬' => '冬', + '况' => '况', + '𩇟' => '𩇟', + '凵' => '凵', + '刃' => '刃', + '㓟' => '㓟', + '刻' => '刻', + '剆' => '剆', + '割' => '割', + '剷' => '剷', + '㔕' => '㔕', + '勇' => '勇', + '勉' => '勉', + '勤' => '勤', + '勺' => '勺', + '包' => '包', + '匆' => '匆', + '北' => '北', + '卉' => '卉', + '卑' => '卑', + '博' => '博', + '即' => '即', + '卽' => '卽', + '卿' => '卿', + '卿' => '卿', + '卿' => '卿', + '𠨬' => '𠨬', + '灰' => '灰', + '及' => '及', + '叟' => '叟', + '𠭣' => '𠭣', + '叫' => '叫', + '叱' => '叱', + '吆' => '吆', + '咞' => '咞', + '吸' => '吸', + '呈' => '呈', + '周' => '周', + '咢' => '咢', + '哶' => '哶', + '唐' => '唐', + '啓' => '啓', + '啣' => '啣', + '善' => '善', + '善' => '善', + '喙' => '喙', + '喫' => '喫', + '喳' => '喳', + '嗂' => '嗂', + '圖' => '圖', + '嘆' => '嘆', + '圗' => '圗', + '噑' => '噑', + '噴' => '噴', + '切' => '切', + '壮' => '壮', + '城' => '城', + '埴' => '埴', + '堍' => '堍', + '型' => '型', + '堲' => '堲', + '報' => '報', + '墬' => '墬', + '𡓤' => '𡓤', + '売' => '売', + '壷' => '壷', + '夆' => '夆', + '多' => '多', + '夢' => '夢', + '奢' => '奢', + '𡚨' => '𡚨', + '𡛪' => '𡛪', + '姬' => '姬', + '娛' => '娛', + '娧' => '娧', + '姘' => '姘', + '婦' => '婦', + '㛮' => '㛮', + '㛼' => '㛼', + '嬈' => '嬈', + '嬾' => '嬾', + '嬾' => '嬾', + '𡧈' => '𡧈', + '寃' => '寃', + '寘' => '寘', + '寧' => '寧', + '寳' => '寳', + '𡬘' => '𡬘', + '寿' => '寿', + '将' => '将', + '当' => '当', + '尢' => '尢', + '㞁' => '㞁', + '屠' => '屠', + '屮' => '屮', + '峀' => '峀', + '岍' => '岍', + '𡷤' => '𡷤', + '嵃' => '嵃', + '𡷦' => '𡷦', + '嵮' => '嵮', + '嵫' => '嵫', + '嵼' => '嵼', + '巡' => '巡', + '巢' => '巢', + '㠯' => '㠯', + '巽' => '巽', + '帨' => '帨', + '帽' => '帽', + '幩' => '幩', + '㡢' => '㡢', + '𢆃' => '𢆃', + '㡼' => '㡼', + '庰' => '庰', + '庳' => '庳', + '庶' => '庶', + '廊' => '廊', + '𪎒' => '𪎒', + '廾' => '廾', + '𢌱' => '𢌱', + '𢌱' => '𢌱', + '舁' => '舁', + '弢' => '弢', + '弢' => '弢', + '㣇' => '㣇', + '𣊸' => '𣊸', + '𦇚' => '𦇚', + '形' => '形', + '彫' => '彫', + '㣣' => '㣣', + '徚' => '徚', + '忍' => '忍', + '志' => '志', + '忹' => '忹', + '悁' => '悁', + '㤺' => '㤺', + '㤜' => '㤜', + '悔' => '悔', + '𢛔' => '𢛔', + '惇' => '惇', + '慈' => '慈', + '慌' => '慌', + '慎' => '慎', + '慌' => '慌', + '慺' => '慺', + '憎' => '憎', + '憲' => '憲', + '憤' => '憤', + '憯' => '憯', + '懞' => '懞', + '懲' => '懲', + '懶' => '懶', + '成' => '成', + '戛' => '戛', + '扝' => '扝', + '抱' => '抱', + '拔' => '拔', + '捐' => '捐', + '𢬌' => '𢬌', + '挽' => '挽', + '拼' => '拼', + '捨' => '捨', + '掃' => '掃', + '揤' => '揤', + '𢯱' => '𢯱', + '搢' => '搢', + '揅' => '揅', + '掩' => '掩', + '㨮' => '㨮', + '摩' => '摩', + '摾' => '摾', + '撝' => '撝', + '摷' => '摷', + '㩬' => '㩬', + '敏' => '敏', + '敬' => '敬', + '𣀊' => '𣀊', + '旣' => '旣', + '書' => '書', + '晉' => '晉', + '㬙' => '㬙', + '暑' => '暑', + '㬈' => '㬈', + '㫤' => '㫤', + '冒' => '冒', + '冕' => '冕', + '最' => '最', + '暜' => '暜', + '肭' => '肭', + '䏙' => '䏙', + '朗' => '朗', + '望' => '望', + '朡' => '朡', + '杞' => '杞', + '杓' => '杓', + '𣏃' => '𣏃', + '㭉' => '㭉', + '柺' => '柺', + '枅' => '枅', + '桒' => '桒', + '梅' => '梅', + '𣑭' => '𣑭', + '梎' => '梎', + '栟' => '栟', + '椔' => '椔', + '㮝' => '㮝', + '楂' => '楂', + '榣' => '榣', + '槪' => '槪', + '檨' => '檨', + '𣚣' => '𣚣', + '櫛' => '櫛', + '㰘' => '㰘', + '次' => '次', + '𣢧' => '𣢧', + '歔' => '歔', + '㱎' => '㱎', + '歲' => '歲', + '殟' => '殟', + '殺' => '殺', + '殻' => '殻', + '𣪍' => '𣪍', + '𡴋' => '𡴋', + '𣫺' => '𣫺', + '汎' => '汎', + '𣲼' => '𣲼', + '沿' => '沿', + '泍' => '泍', + '汧' => '汧', + '洖' => '洖', + '派' => '派', + '海' => '海', + '流' => '流', + '浩' => '浩', + '浸' => '浸', + '涅' => '涅', + '𣴞' => '𣴞', + '洴' => '洴', + '港' => '港', + '湮' => '湮', + '㴳' => '㴳', + '滋' => '滋', + '滇' => '滇', + '𣻑' => '𣻑', + '淹' => '淹', + '潮' => '潮', + '𣽞' => '𣽞', + '𣾎' => '𣾎', + '濆' => '濆', + '瀹' => '瀹', + '瀞' => '瀞', + '瀛' => '瀛', + '㶖' => '㶖', + '灊' => '灊', + '災' => '災', + '灷' => '灷', + '炭' => '炭', + '𠔥' => '𠔥', + '煅' => '煅', + '𤉣' => '𤉣', + '熜' => '熜', + '𤎫' => '𤎫', + '爨' => '爨', + '爵' => '爵', + '牐' => '牐', + '𤘈' => '𤘈', + '犀' => '犀', + '犕' => '犕', + '𤜵' => '𤜵', + '𤠔' => '𤠔', + '獺' => '獺', + '王' => '王', + '㺬' => '㺬', + '玥' => '玥', + '㺸' => '㺸', + '㺸' => '㺸', + '瑇' => '瑇', + '瑜' => '瑜', + '瑱' => '瑱', + '璅' => '璅', + '瓊' => '瓊', + '㼛' => '㼛', + '甤' => '甤', + '𤰶' => '𤰶', + '甾' => '甾', + '𤲒' => '𤲒', + '異' => '異', + '𢆟' => '𢆟', + '瘐' => '瘐', + '𤾡' => '𤾡', + '𤾸' => '𤾸', + '𥁄' => '𥁄', + '㿼' => '㿼', + '䀈' => '䀈', + '直' => '直', + '𥃳' => '𥃳', + '𥃲' => '𥃲', + '𥄙' => '𥄙', + '𥄳' => '𥄳', + '眞' => '眞', + '真' => '真', + '真' => '真', + '睊' => '睊', + '䀹' => '䀹', + '瞋' => '瞋', + '䁆' => '䁆', + '䂖' => '䂖', + '𥐝' => '𥐝', + '硎' => '硎', + '碌' => '碌', + '磌' => '磌', + '䃣' => '䃣', + '𥘦' => '𥘦', + '祖' => '祖', + '𥚚' => '𥚚', + '𥛅' => '𥛅', + '福' => '福', + '秫' => '秫', + '䄯' => '䄯', + '穀' => '穀', + '穊' => '穊', + '穏' => '穏', + '𥥼' => '𥥼', + '𥪧' => '𥪧', + '𥪧' => '𥪧', + '竮' => '竮', + '䈂' => '䈂', + '𥮫' => '𥮫', + '篆' => '篆', + '築' => '築', + '䈧' => '䈧', + '𥲀' => '𥲀', + '糒' => '糒', + '䊠' => '䊠', + '糨' => '糨', + '糣' => '糣', + '紀' => '紀', + '𥾆' => '𥾆', + '絣' => '絣', + '䌁' => '䌁', + '緇' => '緇', + '縂' => '縂', + '繅' => '繅', + '䌴' => '䌴', + '𦈨' => '𦈨', + '𦉇' => '𦉇', + '䍙' => '䍙', + '𦋙' => '𦋙', + '罺' => '罺', + '𦌾' => '𦌾', + '羕' => '羕', + '翺' => '翺', + '者' => '者', + '𦓚' => '𦓚', + '𦔣' => '𦔣', + '聠' => '聠', + '𦖨' => '𦖨', + '聰' => '聰', + '𣍟' => '𣍟', + '䏕' => '䏕', + '育' => '育', + '脃' => '脃', + '䐋' => '䐋', + '脾' => '脾', + '媵' => '媵', + '𦞧' => '𦞧', + '𦞵' => '𦞵', + '𣎓' => '𣎓', + '𣎜' => '𣎜', + '舁' => '舁', + '舄' => '舄', + '辞' => '辞', + '䑫' => '䑫', + '芑' => '芑', + '芋' => '芋', + '芝' => '芝', + '劳' => '劳', + '花' => '花', + '芳' => '芳', + '芽' => '芽', + '苦' => '苦', + '𦬼' => '𦬼', + '若' => '若', + '茝' => '茝', + '荣' => '荣', + '莭' => '莭', + '茣' => '茣', + '莽' => '莽', + '菧' => '菧', + '著' => '著', + '荓' => '荓', + '菊' => '菊', + '菌' => '菌', + '菜' => '菜', + '𦰶' => '𦰶', + '𦵫' => '𦵫', + '𦳕' => '𦳕', + '䔫' => '䔫', + '蓱' => '蓱', + '蓳' => '蓳', + '蔖' => '蔖', + '𧏊' => '𧏊', + '蕤' => '蕤', + '𦼬' => '𦼬', + '䕝' => '䕝', + '䕡' => '䕡', + '𦾱' => '𦾱', + '𧃒' => '𧃒', + '䕫' => '䕫', + '虐' => '虐', + '虜' => '虜', + '虧' => '虧', + '虩' => '虩', + '蚩' => '蚩', + '蚈' => '蚈', + '蜎' => '蜎', + '蛢' => '蛢', + '蝹' => '蝹', + '蜨' => '蜨', + '蝫' => '蝫', + '螆' => '螆', + '䗗' => '䗗', + '蟡' => '蟡', + '蠁' => '蠁', + '䗹' => '䗹', + '衠' => '衠', + '衣' => '衣', + '𧙧' => '𧙧', + '裗' => '裗', + '裞' => '裞', + '䘵' => '䘵', + '裺' => '裺', + '㒻' => '㒻', + '𧢮' => '𧢮', + '𧥦' => '𧥦', + '䚾' => '䚾', + '䛇' => '䛇', + '誠' => '誠', + '諭' => '諭', + '變' => '變', + '豕' => '豕', + '𧲨' => '𧲨', + '貫' => '貫', + '賁' => '賁', + '贛' => '贛', + '起' => '起', + '𧼯' => '𧼯', + '𠠄' => '𠠄', + '跋' => '跋', + '趼' => '趼', + '跰' => '跰', + '𠣞' => '𠣞', + '軔' => '軔', + '輸' => '輸', + '𨗒' => '𨗒', + '𨗭' => '𨗭', + '邔' => '邔', + '郱' => '郱', + '鄑' => '鄑', + '𨜮' => '𨜮', + '鄛' => '鄛', + '鈸' => '鈸', + '鋗' => '鋗', + '鋘' => '鋘', + '鉼' => '鉼', + '鏹' => '鏹', + '鐕' => '鐕', + '𨯺' => '𨯺', + '開' => '開', + '䦕' => '䦕', + '閷' => '閷', + '𨵷' => '𨵷', + '䧦' => '䧦', + '雃' => '雃', + '嶲' => '嶲', + '霣' => '霣', + '𩅅' => '𩅅', + '𩈚' => '𩈚', + '䩮' => '䩮', + '䩶' => '䩶', + '韠' => '韠', + '𩐊' => '𩐊', + '䪲' => '䪲', + '𩒖' => '𩒖', + '頋' => '頋', + '頋' => '頋', + '頩' => '頩', + '𩖶' => '𩖶', + '飢' => '飢', + '䬳' => '䬳', + '餩' => '餩', + '馧' => '馧', + '駂' => '駂', + '駾' => '駾', + '䯎' => '䯎', + '𩬰' => '𩬰', + '鬒' => '鬒', + '鱀' => '鱀', + '鳽' => '鳽', + '䳎' => '䳎', + '䳭' => '䳭', + '鵧' => '鵧', + '𪃎' => '𪃎', + '䳸' => '䳸', + '𪄅' => '𪄅', + '𪈎' => '𪈎', + '𪊑' => '𪊑', + '麻' => '麻', + '䵖' => '䵖', + '黹' => '黹', + '黾' => '黾', + '鼅' => '鼅', + '鼏' => '鼏', + '鼖' => '鼖', + '鼻' => '鼻', + '𪘀' => '𪘀', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/combiningClass.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/combiningClass.php new file mode 100644 index 0000000..ec90f36 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/combiningClass.php @@ -0,0 +1,876 @@ + 230, + '́' => 230, + '̂' => 230, + '̃' => 230, + '̄' => 230, + '̅' => 230, + '̆' => 230, + '̇' => 230, + '̈' => 230, + '̉' => 230, + '̊' => 230, + '̋' => 230, + '̌' => 230, + '̍' => 230, + '̎' => 230, + '̏' => 230, + '̐' => 230, + '̑' => 230, + '̒' => 230, + '̓' => 230, + '̔' => 230, + '̕' => 232, + '̖' => 220, + '̗' => 220, + '̘' => 220, + '̙' => 220, + '̚' => 232, + '̛' => 216, + '̜' => 220, + '̝' => 220, + '̞' => 220, + '̟' => 220, + '̠' => 220, + '̡' => 202, + '̢' => 202, + '̣' => 220, + '̤' => 220, + '̥' => 220, + '̦' => 220, + '̧' => 202, + '̨' => 202, + '̩' => 220, + '̪' => 220, + '̫' => 220, + '̬' => 220, + '̭' => 220, + '̮' => 220, + '̯' => 220, + '̰' => 220, + '̱' => 220, + '̲' => 220, + '̳' => 220, + '̴' => 1, + '̵' => 1, + '̶' => 1, + '̷' => 1, + '̸' => 1, + '̹' => 220, + '̺' => 220, + '̻' => 220, + '̼' => 220, + '̽' => 230, + '̾' => 230, + '̿' => 230, + '̀' => 230, + '́' => 230, + '͂' => 230, + '̓' => 230, + '̈́' => 230, + 'ͅ' => 240, + '͆' => 230, + '͇' => 220, + '͈' => 220, + '͉' => 220, + '͊' => 230, + '͋' => 230, + '͌' => 230, + '͍' => 220, + '͎' => 220, + '͐' => 230, + '͑' => 230, + '͒' => 230, + '͓' => 220, + '͔' => 220, + '͕' => 220, + '͖' => 220, + '͗' => 230, + '͘' => 232, + '͙' => 220, + '͚' => 220, + '͛' => 230, + '͜' => 233, + '͝' => 234, + '͞' => 234, + '͟' => 233, + '͠' => 234, + '͡' => 234, + '͢' => 233, + 'ͣ' => 230, + 'ͤ' => 230, + 'ͥ' => 230, + 'ͦ' => 230, + 'ͧ' => 230, + 'ͨ' => 230, + 'ͩ' => 230, + 'ͪ' => 230, + 'ͫ' => 230, + 'ͬ' => 230, + 'ͭ' => 230, + 'ͮ' => 230, + 'ͯ' => 230, + '҃' => 230, + '҄' => 230, + '҅' => 230, + '҆' => 230, + '҇' => 230, + '֑' => 220, + '֒' => 230, + '֓' => 230, + '֔' => 230, + '֕' => 230, + '֖' => 220, + '֗' => 230, + '֘' => 230, + '֙' => 230, + '֚' => 222, + '֛' => 220, + '֜' => 230, + '֝' => 230, + '֞' => 230, + '֟' => 230, + '֠' => 230, + '֡' => 230, + '֢' => 220, + '֣' => 220, + '֤' => 220, + '֥' => 220, + '֦' => 220, + '֧' => 220, + '֨' => 230, + '֩' => 230, + '֪' => 220, + '֫' => 230, + '֬' => 230, + '֭' => 222, + '֮' => 228, + '֯' => 230, + 'ְ' => 10, + 'ֱ' => 11, + 'ֲ' => 12, + 'ֳ' => 13, + 'ִ' => 14, + 'ֵ' => 15, + 'ֶ' => 16, + 'ַ' => 17, + 'ָ' => 18, + 'ֹ' => 19, + 'ֺ' => 19, + 'ֻ' => 20, + 'ּ' => 21, + 'ֽ' => 22, + 'ֿ' => 23, + 'ׁ' => 24, + 'ׂ' => 25, + 'ׄ' => 230, + 'ׅ' => 220, + 'ׇ' => 18, + 'ؐ' => 230, + 'ؑ' => 230, + 'ؒ' => 230, + 'ؓ' => 230, + 'ؔ' => 230, + 'ؕ' => 230, + 'ؖ' => 230, + 'ؗ' => 230, + 'ؘ' => 30, + 'ؙ' => 31, + 'ؚ' => 32, + 'ً' => 27, + 'ٌ' => 28, + 'ٍ' => 29, + 'َ' => 30, + 'ُ' => 31, + 'ِ' => 32, + 'ّ' => 33, + 'ْ' => 34, + 'ٓ' => 230, + 'ٔ' => 230, + 'ٕ' => 220, + 'ٖ' => 220, + 'ٗ' => 230, + '٘' => 230, + 'ٙ' => 230, + 'ٚ' => 230, + 'ٛ' => 230, + 'ٜ' => 220, + 'ٝ' => 230, + 'ٞ' => 230, + 'ٟ' => 220, + 'ٰ' => 35, + 'ۖ' => 230, + 'ۗ' => 230, + 'ۘ' => 230, + 'ۙ' => 230, + 'ۚ' => 230, + 'ۛ' => 230, + 'ۜ' => 230, + '۟' => 230, + '۠' => 230, + 'ۡ' => 230, + 'ۢ' => 230, + 'ۣ' => 220, + 'ۤ' => 230, + 'ۧ' => 230, + 'ۨ' => 230, + '۪' => 220, + '۫' => 230, + '۬' => 230, + 'ۭ' => 220, + 'ܑ' => 36, + 'ܰ' => 230, + 'ܱ' => 220, + 'ܲ' => 230, + 'ܳ' => 230, + 'ܴ' => 220, + 'ܵ' => 230, + 'ܶ' => 230, + 'ܷ' => 220, + 'ܸ' => 220, + 'ܹ' => 220, + 'ܺ' => 230, + 'ܻ' => 220, + 'ܼ' => 220, + 'ܽ' => 230, + 'ܾ' => 220, + 'ܿ' => 230, + '݀' => 230, + '݁' => 230, + '݂' => 220, + '݃' => 230, + '݄' => 220, + '݅' => 230, + '݆' => 220, + '݇' => 230, + '݈' => 220, + '݉' => 230, + '݊' => 230, + '߫' => 230, + '߬' => 230, + '߭' => 230, + '߮' => 230, + '߯' => 230, + '߰' => 230, + '߱' => 230, + '߲' => 220, + '߳' => 230, + '߽' => 220, + 'ࠖ' => 230, + 'ࠗ' => 230, + '࠘' => 230, + '࠙' => 230, + 'ࠛ' => 230, + 'ࠜ' => 230, + 'ࠝ' => 230, + 'ࠞ' => 230, + 'ࠟ' => 230, + 'ࠠ' => 230, + 'ࠡ' => 230, + 'ࠢ' => 230, + 'ࠣ' => 230, + 'ࠥ' => 230, + 'ࠦ' => 230, + 'ࠧ' => 230, + 'ࠩ' => 230, + 'ࠪ' => 230, + 'ࠫ' => 230, + 'ࠬ' => 230, + '࠭' => 230, + '࡙' => 220, + '࡚' => 220, + '࡛' => 220, + '࣓' => 220, + 'ࣔ' => 230, + 'ࣕ' => 230, + 'ࣖ' => 230, + 'ࣗ' => 230, + 'ࣘ' => 230, + 'ࣙ' => 230, + 'ࣚ' => 230, + 'ࣛ' => 230, + 'ࣜ' => 230, + 'ࣝ' => 230, + 'ࣞ' => 230, + 'ࣟ' => 230, + '࣠' => 230, + '࣡' => 230, + 'ࣣ' => 220, + 'ࣤ' => 230, + 'ࣥ' => 230, + 'ࣦ' => 220, + 'ࣧ' => 230, + 'ࣨ' => 230, + 'ࣩ' => 220, + '࣪' => 230, + '࣫' => 230, + '࣬' => 230, + '࣭' => 220, + '࣮' => 220, + '࣯' => 220, + 'ࣰ' => 27, + 'ࣱ' => 28, + 'ࣲ' => 29, + 'ࣳ' => 230, + 'ࣴ' => 230, + 'ࣵ' => 230, + 'ࣶ' => 220, + 'ࣷ' => 230, + 'ࣸ' => 230, + 'ࣹ' => 220, + 'ࣺ' => 220, + 'ࣻ' => 230, + 'ࣼ' => 230, + 'ࣽ' => 230, + 'ࣾ' => 230, + 'ࣿ' => 230, + '़' => 7, + '्' => 9, + '॑' => 230, + '॒' => 220, + '॓' => 230, + '॔' => 230, + '়' => 7, + '্' => 9, + '৾' => 230, + '਼' => 7, + '੍' => 9, + '઼' => 7, + '્' => 9, + '଼' => 7, + '୍' => 9, + '்' => 9, + '్' => 9, + 'ౕ' => 84, + 'ౖ' => 91, + '಼' => 7, + '್' => 9, + '഻' => 9, + '഼' => 9, + '്' => 9, + '්' => 9, + 'ุ' => 103, + 'ู' => 103, + 'ฺ' => 9, + '่' => 107, + '้' => 107, + '๊' => 107, + '๋' => 107, + 'ຸ' => 118, + 'ູ' => 118, + '຺' => 9, + '່' => 122, + '້' => 122, + '໊' => 122, + '໋' => 122, + '༘' => 220, + '༙' => 220, + '༵' => 220, + '༷' => 220, + '༹' => 216, + 'ཱ' => 129, + 'ི' => 130, + 'ུ' => 132, + 'ེ' => 130, + 'ཻ' => 130, + 'ོ' => 130, + 'ཽ' => 130, + 'ྀ' => 130, + 'ྂ' => 230, + 'ྃ' => 230, + '྄' => 9, + '྆' => 230, + '྇' => 230, + '࿆' => 220, + '့' => 7, + '္' => 9, + '်' => 9, + 'ႍ' => 220, + '፝' => 230, + '፞' => 230, + '፟' => 230, + '᜔' => 9, + '᜴' => 9, + '្' => 9, + '៝' => 230, + 'ᢩ' => 228, + '᤹' => 222, + '᤺' => 230, + '᤻' => 220, + 'ᨗ' => 230, + 'ᨘ' => 220, + '᩠' => 9, + '᩵' => 230, + '᩶' => 230, + '᩷' => 230, + '᩸' => 230, + '᩹' => 230, + '᩺' => 230, + '᩻' => 230, + '᩼' => 230, + '᩿' => 220, + '᪰' => 230, + '᪱' => 230, + '᪲' => 230, + '᪳' => 230, + '᪴' => 230, + '᪵' => 220, + '᪶' => 220, + '᪷' => 220, + '᪸' => 220, + '᪹' => 220, + '᪺' => 220, + '᪻' => 230, + '᪼' => 230, + '᪽' => 220, + 'ᪿ' => 220, + 'ᫀ' => 220, + '᬴' => 7, + '᭄' => 9, + '᭫' => 230, + '᭬' => 220, + '᭭' => 230, + '᭮' => 230, + '᭯' => 230, + '᭰' => 230, + '᭱' => 230, + '᭲' => 230, + '᭳' => 230, + '᮪' => 9, + '᮫' => 9, + '᯦' => 7, + '᯲' => 9, + '᯳' => 9, + '᰷' => 7, + '᳐' => 230, + '᳑' => 230, + '᳒' => 230, + '᳔' => 1, + '᳕' => 220, + '᳖' => 220, + '᳗' => 220, + '᳘' => 220, + '᳙' => 220, + '᳚' => 230, + '᳛' => 230, + '᳜' => 220, + '᳝' => 220, + '᳞' => 220, + '᳟' => 220, + '᳠' => 230, + '᳢' => 1, + '᳣' => 1, + '᳤' => 1, + '᳥' => 1, + '᳦' => 1, + '᳧' => 1, + '᳨' => 1, + '᳭' => 220, + '᳴' => 230, + '᳸' => 230, + '᳹' => 230, + '᷀' => 230, + '᷁' => 230, + '᷂' => 220, + '᷃' => 230, + '᷄' => 230, + '᷅' => 230, + '᷆' => 230, + '᷇' => 230, + '᷈' => 230, + '᷉' => 230, + '᷊' => 220, + '᷋' => 230, + '᷌' => 230, + '᷍' => 234, + '᷎' => 214, + '᷏' => 220, + '᷐' => 202, + '᷑' => 230, + '᷒' => 230, + 'ᷓ' => 230, + 'ᷔ' => 230, + 'ᷕ' => 230, + 'ᷖ' => 230, + 'ᷗ' => 230, + 'ᷘ' => 230, + 'ᷙ' => 230, + 'ᷚ' => 230, + 'ᷛ' => 230, + 'ᷜ' => 230, + 'ᷝ' => 230, + 'ᷞ' => 230, + 'ᷟ' => 230, + 'ᷠ' => 230, + 'ᷡ' => 230, + 'ᷢ' => 230, + 'ᷣ' => 230, + 'ᷤ' => 230, + 'ᷥ' => 230, + 'ᷦ' => 230, + 'ᷧ' => 230, + 'ᷨ' => 230, + 'ᷩ' => 230, + 'ᷪ' => 230, + 'ᷫ' => 230, + 'ᷬ' => 230, + 'ᷭ' => 230, + 'ᷮ' => 230, + 'ᷯ' => 230, + 'ᷰ' => 230, + 'ᷱ' => 230, + 'ᷲ' => 230, + 'ᷳ' => 230, + 'ᷴ' => 230, + '᷵' => 230, + '᷶' => 232, + '᷷' => 228, + '᷸' => 228, + '᷹' => 220, + '᷻' => 230, + '᷼' => 233, + '᷽' => 220, + '᷾' => 230, + '᷿' => 220, + '⃐' => 230, + '⃑' => 230, + '⃒' => 1, + '⃓' => 1, + '⃔' => 230, + '⃕' => 230, + '⃖' => 230, + '⃗' => 230, + '⃘' => 1, + '⃙' => 1, + '⃚' => 1, + '⃛' => 230, + '⃜' => 230, + '⃡' => 230, + '⃥' => 1, + '⃦' => 1, + '⃧' => 230, + '⃨' => 220, + '⃩' => 230, + '⃪' => 1, + '⃫' => 1, + '⃬' => 220, + '⃭' => 220, + '⃮' => 220, + '⃯' => 220, + '⃰' => 230, + '⳯' => 230, + '⳰' => 230, + '⳱' => 230, + '⵿' => 9, + 'ⷠ' => 230, + 'ⷡ' => 230, + 'ⷢ' => 230, + 'ⷣ' => 230, + 'ⷤ' => 230, + 'ⷥ' => 230, + 'ⷦ' => 230, + 'ⷧ' => 230, + 'ⷨ' => 230, + 'ⷩ' => 230, + 'ⷪ' => 230, + 'ⷫ' => 230, + 'ⷬ' => 230, + 'ⷭ' => 230, + 'ⷮ' => 230, + 'ⷯ' => 230, + 'ⷰ' => 230, + 'ⷱ' => 230, + 'ⷲ' => 230, + 'ⷳ' => 230, + 'ⷴ' => 230, + 'ⷵ' => 230, + 'ⷶ' => 230, + 'ⷷ' => 230, + 'ⷸ' => 230, + 'ⷹ' => 230, + 'ⷺ' => 230, + 'ⷻ' => 230, + 'ⷼ' => 230, + 'ⷽ' => 230, + 'ⷾ' => 230, + 'ⷿ' => 230, + '〪' => 218, + '〫' => 228, + '〬' => 232, + '〭' => 222, + '〮' => 224, + '〯' => 224, + '゙' => 8, + '゚' => 8, + '꙯' => 230, + 'ꙴ' => 230, + 'ꙵ' => 230, + 'ꙶ' => 230, + 'ꙷ' => 230, + 'ꙸ' => 230, + 'ꙹ' => 230, + 'ꙺ' => 230, + 'ꙻ' => 230, + '꙼' => 230, + '꙽' => 230, + 'ꚞ' => 230, + 'ꚟ' => 230, + '꛰' => 230, + '꛱' => 230, + '꠆' => 9, + '꠬' => 9, + '꣄' => 9, + '꣠' => 230, + '꣡' => 230, + '꣢' => 230, + '꣣' => 230, + '꣤' => 230, + '꣥' => 230, + '꣦' => 230, + '꣧' => 230, + '꣨' => 230, + '꣩' => 230, + '꣪' => 230, + '꣫' => 230, + '꣬' => 230, + '꣭' => 230, + '꣮' => 230, + '꣯' => 230, + '꣰' => 230, + '꣱' => 230, + '꤫' => 220, + '꤬' => 220, + '꤭' => 220, + '꥓' => 9, + '꦳' => 7, + '꧀' => 9, + 'ꪰ' => 230, + 'ꪲ' => 230, + 'ꪳ' => 230, + 'ꪴ' => 220, + 'ꪷ' => 230, + 'ꪸ' => 230, + 'ꪾ' => 230, + '꪿' => 230, + '꫁' => 230, + '꫶' => 9, + '꯭' => 9, + 'ﬞ' => 26, + '︠' => 230, + '︡' => 230, + '︢' => 230, + '︣' => 230, + '︤' => 230, + '︥' => 230, + '︦' => 230, + '︧' => 220, + '︨' => 220, + '︩' => 220, + '︪' => 220, + '︫' => 220, + '︬' => 220, + '︭' => 220, + '︮' => 230, + '︯' => 230, + '𐇽' => 220, + '𐋠' => 220, + '𐍶' => 230, + '𐍷' => 230, + '𐍸' => 230, + '𐍹' => 230, + '𐍺' => 230, + '𐨍' => 220, + '𐨏' => 230, + '𐨸' => 230, + '𐨹' => 1, + '𐨺' => 220, + '𐨿' => 9, + '𐫥' => 230, + '𐫦' => 220, + '𐴤' => 230, + '𐴥' => 230, + '𐴦' => 230, + '𐴧' => 230, + '𐺫' => 230, + '𐺬' => 230, + '𐽆' => 220, + '𐽇' => 220, + '𐽈' => 230, + '𐽉' => 230, + '𐽊' => 230, + '𐽋' => 220, + '𐽌' => 230, + '𐽍' => 220, + '𐽎' => 220, + '𐽏' => 220, + '𐽐' => 220, + '𑁆' => 9, + '𑁿' => 9, + '𑂹' => 9, + '𑂺' => 7, + '𑄀' => 230, + '𑄁' => 230, + '𑄂' => 230, + '𑄳' => 9, + '𑄴' => 9, + '𑅳' => 7, + '𑇀' => 9, + '𑇊' => 7, + '𑈵' => 9, + '𑈶' => 7, + '𑋩' => 7, + '𑋪' => 9, + '𑌻' => 7, + '𑌼' => 7, + '𑍍' => 9, + '𑍦' => 230, + '𑍧' => 230, + '𑍨' => 230, + '𑍩' => 230, + '𑍪' => 230, + '𑍫' => 230, + '𑍬' => 230, + '𑍰' => 230, + '𑍱' => 230, + '𑍲' => 230, + '𑍳' => 230, + '𑍴' => 230, + '𑑂' => 9, + '𑑆' => 7, + '𑑞' => 230, + '𑓂' => 9, + '𑓃' => 7, + '𑖿' => 9, + '𑗀' => 7, + '𑘿' => 9, + '𑚶' => 9, + '𑚷' => 7, + '𑜫' => 9, + '𑠹' => 9, + '𑠺' => 7, + '𑤽' => 9, + '𑤾' => 9, + '𑥃' => 7, + '𑧠' => 9, + '𑨴' => 9, + '𑩇' => 9, + '𑪙' => 9, + '𑰿' => 9, + '𑵂' => 7, + '𑵄' => 9, + '𑵅' => 9, + '𑶗' => 9, + '𖫰' => 1, + '𖫱' => 1, + '𖫲' => 1, + '𖫳' => 1, + '𖫴' => 1, + '𖬰' => 230, + '𖬱' => 230, + '𖬲' => 230, + '𖬳' => 230, + '𖬴' => 230, + '𖬵' => 230, + '𖬶' => 230, + '𖿰' => 6, + '𖿱' => 6, + '𛲞' => 1, + '𝅥' => 216, + '𝅦' => 216, + '𝅧' => 1, + '𝅨' => 1, + '𝅩' => 1, + '𝅭' => 226, + '𝅮' => 216, + '𝅯' => 216, + '𝅰' => 216, + '𝅱' => 216, + '𝅲' => 216, + '𝅻' => 220, + '𝅼' => 220, + '𝅽' => 220, + '𝅾' => 220, + '𝅿' => 220, + '𝆀' => 220, + '𝆁' => 220, + '𝆂' => 220, + '𝆅' => 230, + '𝆆' => 230, + '𝆇' => 230, + '𝆈' => 230, + '𝆉' => 230, + '𝆊' => 220, + '𝆋' => 220, + '𝆪' => 230, + '𝆫' => 230, + '𝆬' => 230, + '𝆭' => 230, + '𝉂' => 230, + '𝉃' => 230, + '𝉄' => 230, + '𞀀' => 230, + '𞀁' => 230, + '𞀂' => 230, + '𞀃' => 230, + '𞀄' => 230, + '𞀅' => 230, + '𞀆' => 230, + '𞀈' => 230, + '𞀉' => 230, + '𞀊' => 230, + '𞀋' => 230, + '𞀌' => 230, + '𞀍' => 230, + '𞀎' => 230, + '𞀏' => 230, + '𞀐' => 230, + '𞀑' => 230, + '𞀒' => 230, + '𞀓' => 230, + '𞀔' => 230, + '𞀕' => 230, + '𞀖' => 230, + '𞀗' => 230, + '𞀘' => 230, + '𞀛' => 230, + '𞀜' => 230, + '𞀝' => 230, + '𞀞' => 230, + '𞀟' => 230, + '𞀠' => 230, + '𞀡' => 230, + '𞀣' => 230, + '𞀤' => 230, + '𞀦' => 230, + '𞀧' => 230, + '𞀨' => 230, + '𞀩' => 230, + '𞀪' => 230, + '𞄰' => 230, + '𞄱' => 230, + '𞄲' => 230, + '𞄳' => 230, + '𞄴' => 230, + '𞄵' => 230, + '𞄶' => 230, + '𞋬' => 230, + '𞋭' => 230, + '𞋮' => 230, + '𞋯' => 230, + '𞣐' => 220, + '𞣑' => 220, + '𞣒' => 220, + '𞣓' => 220, + '𞣔' => 220, + '𞣕' => 220, + '𞣖' => 220, + '𞥄' => 230, + '𞥅' => 230, + '𞥆' => 230, + '𞥇' => 230, + '𞥈' => 230, + '𞥉' => 230, + '𞥊' => 7, +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/compatibilityDecomposition.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/compatibilityDecomposition.php new file mode 100644 index 0000000..1574902 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/compatibilityDecomposition.php @@ -0,0 +1,3695 @@ + ' ', + '¨' => ' ̈', + 'ª' => 'a', + '¯' => ' ̄', + '²' => '2', + '³' => '3', + '´' => ' ́', + 'µ' => 'μ', + '¸' => ' ̧', + '¹' => '1', + 'º' => 'o', + '¼' => '1⁄4', + '½' => '1⁄2', + '¾' => '3⁄4', + 'IJ' => 'IJ', + 'ij' => 'ij', + 'Ŀ' => 'L·', + 'ŀ' => 'l·', + 'ʼn' => 'ʼn', + 'ſ' => 's', + 'DŽ' => 'DŽ', + 'Dž' => 'Dž', + 'dž' => 'dž', + 'LJ' => 'LJ', + 'Lj' => 'Lj', + 'lj' => 'lj', + 'NJ' => 'NJ', + 'Nj' => 'Nj', + 'nj' => 'nj', + 'DZ' => 'DZ', + 'Dz' => 'Dz', + 'dz' => 'dz', + 'ʰ' => 'h', + 'ʱ' => 'ɦ', + 'ʲ' => 'j', + 'ʳ' => 'r', + 'ʴ' => 'ɹ', + 'ʵ' => 'ɻ', + 'ʶ' => 'ʁ', + 'ʷ' => 'w', + 'ʸ' => 'y', + '˘' => ' ̆', + '˙' => ' ̇', + '˚' => ' ̊', + '˛' => ' ̨', + '˜' => ' ̃', + '˝' => ' ̋', + 'ˠ' => 'ɣ', + 'ˡ' => 'l', + 'ˢ' => 's', + 'ˣ' => 'x', + 'ˤ' => 'ʕ', + 'ͺ' => ' ͅ', + '΄' => ' ́', + '΅' => ' ̈́', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϒ' => 'Υ', + 'ϓ' => 'Ύ', + 'ϔ' => 'Ϋ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϲ' => 'ς', + 'ϴ' => 'Θ', + 'ϵ' => 'ε', + 'Ϲ' => 'Σ', + 'և' => 'եւ', + 'ٵ' => 'اٴ', + 'ٶ' => 'وٴ', + 'ٷ' => 'ۇٴ', + 'ٸ' => 'يٴ', + 'ำ' => 'ํา', + 'ຳ' => 'ໍາ', + 'ໜ' => 'ຫນ', + 'ໝ' => 'ຫມ', + '༌' => '་', + 'ཷ' => 'ྲཱྀ', + 'ཹ' => 'ླཱྀ', + 'ჼ' => 'ნ', + 'ᴬ' => 'A', + 'ᴭ' => 'Æ', + 'ᴮ' => 'B', + 'ᴰ' => 'D', + 'ᴱ' => 'E', + 'ᴲ' => 'Ǝ', + 'ᴳ' => 'G', + 'ᴴ' => 'H', + 'ᴵ' => 'I', + 'ᴶ' => 'J', + 'ᴷ' => 'K', + 'ᴸ' => 'L', + 'ᴹ' => 'M', + 'ᴺ' => 'N', + 'ᴼ' => 'O', + 'ᴽ' => 'Ȣ', + 'ᴾ' => 'P', + 'ᴿ' => 'R', + 'ᵀ' => 'T', + 'ᵁ' => 'U', + 'ᵂ' => 'W', + 'ᵃ' => 'a', + 'ᵄ' => 'ɐ', + 'ᵅ' => 'ɑ', + 'ᵆ' => 'ᴂ', + 'ᵇ' => 'b', + 'ᵈ' => 'd', + 'ᵉ' => 'e', + 'ᵊ' => 'ə', + 'ᵋ' => 'ɛ', + 'ᵌ' => 'ɜ', + 'ᵍ' => 'g', + 'ᵏ' => 'k', + 'ᵐ' => 'm', + 'ᵑ' => 'ŋ', + 'ᵒ' => 'o', + 'ᵓ' => 'ɔ', + 'ᵔ' => 'ᴖ', + 'ᵕ' => 'ᴗ', + 'ᵖ' => 'p', + 'ᵗ' => 't', + 'ᵘ' => 'u', + 'ᵙ' => 'ᴝ', + 'ᵚ' => 'ɯ', + 'ᵛ' => 'v', + 'ᵜ' => 'ᴥ', + 'ᵝ' => 'β', + 'ᵞ' => 'γ', + 'ᵟ' => 'δ', + 'ᵠ' => 'φ', + 'ᵡ' => 'χ', + 'ᵢ' => 'i', + 'ᵣ' => 'r', + 'ᵤ' => 'u', + 'ᵥ' => 'v', + 'ᵦ' => 'β', + 'ᵧ' => 'γ', + 'ᵨ' => 'ρ', + 'ᵩ' => 'φ', + 'ᵪ' => 'χ', + 'ᵸ' => 'н', + 'ᶛ' => 'ɒ', + 'ᶜ' => 'c', + 'ᶝ' => 'ɕ', + 'ᶞ' => 'ð', + 'ᶟ' => 'ɜ', + 'ᶠ' => 'f', + 'ᶡ' => 'ɟ', + 'ᶢ' => 'ɡ', + 'ᶣ' => 'ɥ', + 'ᶤ' => 'ɨ', + 'ᶥ' => 'ɩ', + 'ᶦ' => 'ɪ', + 'ᶧ' => 'ᵻ', + 'ᶨ' => 'ʝ', + 'ᶩ' => 'ɭ', + 'ᶪ' => 'ᶅ', + 'ᶫ' => 'ʟ', + 'ᶬ' => 'ɱ', + 'ᶭ' => 'ɰ', + 'ᶮ' => 'ɲ', + 'ᶯ' => 'ɳ', + 'ᶰ' => 'ɴ', + 'ᶱ' => 'ɵ', + 'ᶲ' => 'ɸ', + 'ᶳ' => 'ʂ', + 'ᶴ' => 'ʃ', + 'ᶵ' => 'ƫ', + 'ᶶ' => 'ʉ', + 'ᶷ' => 'ʊ', + 'ᶸ' => 'ᴜ', + 'ᶹ' => 'ʋ', + 'ᶺ' => 'ʌ', + 'ᶻ' => 'z', + 'ᶼ' => 'ʐ', + 'ᶽ' => 'ʑ', + 'ᶾ' => 'ʒ', + 'ᶿ' => 'θ', + 'ẚ' => 'aʾ', + 'ẛ' => 'ṡ', + '᾽' => ' ̓', + '᾿' => ' ̓', + '῀' => ' ͂', + '῁' => ' ̈͂', + '῍' => ' ̓̀', + '῎' => ' ̓́', + '῏' => ' ̓͂', + '῝' => ' ̔̀', + '῞' => ' ̔́', + '῟' => ' ̔͂', + '῭' => ' ̈̀', + '΅' => ' ̈́', + '´' => ' ́', + '῾' => ' ̔', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + '‑' => '‐', + '‗' => ' ̳', + '․' => '.', + '‥' => '..', + '…' => '...', + ' ' => ' ', + '″' => '′′', + '‴' => '′′′', + '‶' => '‵‵', + '‷' => '‵‵‵', + '‼' => '!!', + '‾' => ' ̅', + '⁇' => '??', + '⁈' => '?!', + '⁉' => '!?', + '⁗' => '′′′′', + ' ' => ' ', + '⁰' => '0', + 'ⁱ' => 'i', + '⁴' => '4', + '⁵' => '5', + '⁶' => '6', + '⁷' => '7', + '⁸' => '8', + '⁹' => '9', + '⁺' => '+', + '⁻' => '−', + '⁼' => '=', + '⁽' => '(', + '⁾' => ')', + 'ⁿ' => 'n', + '₀' => '0', + '₁' => '1', + '₂' => '2', + '₃' => '3', + '₄' => '4', + '₅' => '5', + '₆' => '6', + '₇' => '7', + '₈' => '8', + '₉' => '9', + '₊' => '+', + '₋' => '−', + '₌' => '=', + '₍' => '(', + '₎' => ')', + 'ₐ' => 'a', + 'ₑ' => 'e', + 'ₒ' => 'o', + 'ₓ' => 'x', + 'ₔ' => 'ə', + 'ₕ' => 'h', + 'ₖ' => 'k', + 'ₗ' => 'l', + 'ₘ' => 'm', + 'ₙ' => 'n', + 'ₚ' => 'p', + 'ₛ' => 's', + 'ₜ' => 't', + '₨' => 'Rs', + '℀' => 'a/c', + '℁' => 'a/s', + 'ℂ' => 'C', + '℃' => '°C', + '℅' => 'c/o', + '℆' => 'c/u', + 'ℇ' => 'Ɛ', + '℉' => '°F', + 'ℊ' => 'g', + 'ℋ' => 'H', + 'ℌ' => 'H', + 'ℍ' => 'H', + 'ℎ' => 'h', + 'ℏ' => 'ħ', + 'ℐ' => 'I', + 'ℑ' => 'I', + 'ℒ' => 'L', + 'ℓ' => 'l', + 'ℕ' => 'N', + '№' => 'No', + 'ℙ' => 'P', + 'ℚ' => 'Q', + 'ℛ' => 'R', + 'ℜ' => 'R', + 'ℝ' => 'R', + '℠' => 'SM', + '℡' => 'TEL', + '™' => 'TM', + 'ℤ' => 'Z', + 'ℨ' => 'Z', + 'ℬ' => 'B', + 'ℭ' => 'C', + 'ℯ' => 'e', + 'ℰ' => 'E', + 'ℱ' => 'F', + 'ℳ' => 'M', + 'ℴ' => 'o', + 'ℵ' => 'א', + 'ℶ' => 'ב', + 'ℷ' => 'ג', + 'ℸ' => 'ד', + 'ℹ' => 'i', + '℻' => 'FAX', + 'ℼ' => 'π', + 'ℽ' => 'γ', + 'ℾ' => 'Γ', + 'ℿ' => 'Π', + '⅀' => '∑', + 'ⅅ' => 'D', + 'ⅆ' => 'd', + 'ⅇ' => 'e', + 'ⅈ' => 'i', + 'ⅉ' => 'j', + '⅐' => '1⁄7', + '⅑' => '1⁄9', + '⅒' => '1⁄10', + '⅓' => '1⁄3', + '⅔' => '2⁄3', + '⅕' => '1⁄5', + '⅖' => '2⁄5', + '⅗' => '3⁄5', + '⅘' => '4⁄5', + '⅙' => '1⁄6', + '⅚' => '5⁄6', + '⅛' => '1⁄8', + '⅜' => '3⁄8', + '⅝' => '5⁄8', + '⅞' => '7⁄8', + '⅟' => '1⁄', + 'Ⅰ' => 'I', + 'Ⅱ' => 'II', + 'Ⅲ' => 'III', + 'Ⅳ' => 'IV', + 'Ⅴ' => 'V', + 'Ⅵ' => 'VI', + 'Ⅶ' => 'VII', + 'Ⅷ' => 'VIII', + 'Ⅸ' => 'IX', + 'Ⅹ' => 'X', + 'Ⅺ' => 'XI', + 'Ⅻ' => 'XII', + 'Ⅼ' => 'L', + 'Ⅽ' => 'C', + 'Ⅾ' => 'D', + 'Ⅿ' => 'M', + 'ⅰ' => 'i', + 'ⅱ' => 'ii', + 'ⅲ' => 'iii', + 'ⅳ' => 'iv', + 'ⅴ' => 'v', + 'ⅵ' => 'vi', + 'ⅶ' => 'vii', + 'ⅷ' => 'viii', + 'ⅸ' => 'ix', + 'ⅹ' => 'x', + 'ⅺ' => 'xi', + 'ⅻ' => 'xii', + 'ⅼ' => 'l', + 'ⅽ' => 'c', + 'ⅾ' => 'd', + 'ⅿ' => 'm', + '↉' => '0⁄3', + '∬' => '∫∫', + '∭' => '∫∫∫', + '∯' => '∮∮', + '∰' => '∮∮∮', + '①' => '1', + '②' => '2', + '③' => '3', + '④' => '4', + '⑤' => '5', + '⑥' => '6', + '⑦' => '7', + '⑧' => '8', + '⑨' => '9', + '⑩' => '10', + '⑪' => '11', + '⑫' => '12', + '⑬' => '13', + '⑭' => '14', + '⑮' => '15', + '⑯' => '16', + '⑰' => '17', + '⑱' => '18', + '⑲' => '19', + '⑳' => '20', + '⑴' => '(1)', + '⑵' => '(2)', + '⑶' => '(3)', + '⑷' => '(4)', + '⑸' => '(5)', + '⑹' => '(6)', + '⑺' => '(7)', + '⑻' => '(8)', + '⑼' => '(9)', + '⑽' => '(10)', + '⑾' => '(11)', + '⑿' => '(12)', + '⒀' => '(13)', + '⒁' => '(14)', + '⒂' => '(15)', + '⒃' => '(16)', + '⒄' => '(17)', + '⒅' => '(18)', + '⒆' => '(19)', + '⒇' => '(20)', + '⒈' => '1.', + '⒉' => '2.', + '⒊' => '3.', + '⒋' => '4.', + '⒌' => '5.', + '⒍' => '6.', + '⒎' => '7.', + '⒏' => '8.', + '⒐' => '9.', + '⒑' => '10.', + '⒒' => '11.', + '⒓' => '12.', + '⒔' => '13.', + '⒕' => '14.', + '⒖' => '15.', + '⒗' => '16.', + '⒘' => '17.', + '⒙' => '18.', + '⒚' => '19.', + '⒛' => '20.', + '⒜' => '(a)', + '⒝' => '(b)', + '⒞' => '(c)', + '⒟' => '(d)', + '⒠' => '(e)', + '⒡' => '(f)', + '⒢' => '(g)', + '⒣' => '(h)', + '⒤' => '(i)', + '⒥' => '(j)', + '⒦' => '(k)', + '⒧' => '(l)', + '⒨' => '(m)', + '⒩' => '(n)', + '⒪' => '(o)', + '⒫' => '(p)', + '⒬' => '(q)', + '⒭' => '(r)', + '⒮' => '(s)', + '⒯' => '(t)', + '⒰' => '(u)', + '⒱' => '(v)', + '⒲' => '(w)', + '⒳' => '(x)', + '⒴' => '(y)', + '⒵' => '(z)', + 'Ⓐ' => 'A', + 'Ⓑ' => 'B', + 'Ⓒ' => 'C', + 'Ⓓ' => 'D', + 'Ⓔ' => 'E', + 'Ⓕ' => 'F', + 'Ⓖ' => 'G', + 'Ⓗ' => 'H', + 'Ⓘ' => 'I', + 'Ⓙ' => 'J', + 'Ⓚ' => 'K', + 'Ⓛ' => 'L', + 'Ⓜ' => 'M', + 'Ⓝ' => 'N', + 'Ⓞ' => 'O', + 'Ⓟ' => 'P', + 'Ⓠ' => 'Q', + 'Ⓡ' => 'R', + 'Ⓢ' => 'S', + 'Ⓣ' => 'T', + 'Ⓤ' => 'U', + 'Ⓥ' => 'V', + 'Ⓦ' => 'W', + 'Ⓧ' => 'X', + 'Ⓨ' => 'Y', + 'Ⓩ' => 'Z', + 'ⓐ' => 'a', + 'ⓑ' => 'b', + 'ⓒ' => 'c', + 'ⓓ' => 'd', + 'ⓔ' => 'e', + 'ⓕ' => 'f', + 'ⓖ' => 'g', + 'ⓗ' => 'h', + 'ⓘ' => 'i', + 'ⓙ' => 'j', + 'ⓚ' => 'k', + 'ⓛ' => 'l', + 'ⓜ' => 'm', + 'ⓝ' => 'n', + 'ⓞ' => 'o', + 'ⓟ' => 'p', + 'ⓠ' => 'q', + 'ⓡ' => 'r', + 'ⓢ' => 's', + 'ⓣ' => 't', + 'ⓤ' => 'u', + 'ⓥ' => 'v', + 'ⓦ' => 'w', + 'ⓧ' => 'x', + 'ⓨ' => 'y', + 'ⓩ' => 'z', + '⓪' => '0', + '⨌' => '∫∫∫∫', + '⩴' => '::=', + '⩵' => '==', + '⩶' => '===', + 'ⱼ' => 'j', + 'ⱽ' => 'V', + 'ⵯ' => 'ⵡ', + '⺟' => '母', + '⻳' => '龟', + '⼀' => '一', + '⼁' => '丨', + '⼂' => '丶', + '⼃' => '丿', + '⼄' => '乙', + '⼅' => '亅', + '⼆' => '二', + '⼇' => '亠', + '⼈' => '人', + '⼉' => '儿', + '⼊' => '入', + '⼋' => '八', + '⼌' => '冂', + '⼍' => '冖', + '⼎' => '冫', + '⼏' => '几', + '⼐' => '凵', + '⼑' => '刀', + '⼒' => '力', + '⼓' => '勹', + '⼔' => '匕', + '⼕' => '匚', + '⼖' => '匸', + '⼗' => '十', + '⼘' => '卜', + '⼙' => '卩', + '⼚' => '厂', + '⼛' => '厶', + '⼜' => '又', + '⼝' => '口', + '⼞' => '囗', + '⼟' => '土', + '⼠' => '士', + '⼡' => '夂', + '⼢' => '夊', + '⼣' => '夕', + '⼤' => '大', + '⼥' => '女', + '⼦' => '子', + '⼧' => '宀', + '⼨' => '寸', + '⼩' => '小', + '⼪' => '尢', + '⼫' => '尸', + '⼬' => '屮', + '⼭' => '山', + '⼮' => '巛', + '⼯' => '工', + '⼰' => '己', + '⼱' => '巾', + '⼲' => '干', + '⼳' => '幺', + '⼴' => '广', + '⼵' => '廴', + '⼶' => '廾', + '⼷' => '弋', + '⼸' => '弓', + '⼹' => '彐', + '⼺' => '彡', + '⼻' => '彳', + '⼼' => '心', + '⼽' => '戈', + '⼾' => '戶', + '⼿' => '手', + '⽀' => '支', + '⽁' => '攴', + '⽂' => '文', + '⽃' => '斗', + '⽄' => '斤', + '⽅' => '方', + '⽆' => '无', + '⽇' => '日', + '⽈' => '曰', + '⽉' => '月', + '⽊' => '木', + '⽋' => '欠', + '⽌' => '止', + '⽍' => '歹', + '⽎' => '殳', + '⽏' => '毋', + '⽐' => '比', + '⽑' => '毛', + '⽒' => '氏', + '⽓' => '气', + '⽔' => '水', + '⽕' => '火', + '⽖' => '爪', + '⽗' => '父', + '⽘' => '爻', + '⽙' => '爿', + '⽚' => '片', + '⽛' => '牙', + '⽜' => '牛', + '⽝' => '犬', + '⽞' => '玄', + '⽟' => '玉', + '⽠' => '瓜', + '⽡' => '瓦', + '⽢' => '甘', + '⽣' => '生', + '⽤' => '用', + '⽥' => '田', + '⽦' => '疋', + '⽧' => '疒', + '⽨' => '癶', + '⽩' => '白', + '⽪' => '皮', + '⽫' => '皿', + '⽬' => '目', + '⽭' => '矛', + '⽮' => '矢', + '⽯' => '石', + '⽰' => '示', + '⽱' => '禸', + '⽲' => '禾', + '⽳' => '穴', + '⽴' => '立', + '⽵' => '竹', + '⽶' => '米', + '⽷' => '糸', + '⽸' => '缶', + '⽹' => '网', + '⽺' => '羊', + '⽻' => '羽', + '⽼' => '老', + '⽽' => '而', + '⽾' => '耒', + '⽿' => '耳', + '⾀' => '聿', + '⾁' => '肉', + '⾂' => '臣', + '⾃' => '自', + '⾄' => '至', + '⾅' => '臼', + '⾆' => '舌', + '⾇' => '舛', + '⾈' => '舟', + '⾉' => '艮', + '⾊' => '色', + '⾋' => '艸', + '⾌' => '虍', + '⾍' => '虫', + '⾎' => '血', + '⾏' => '行', + '⾐' => '衣', + '⾑' => '襾', + '⾒' => '見', + '⾓' => '角', + '⾔' => '言', + '⾕' => '谷', + '⾖' => '豆', + '⾗' => '豕', + '⾘' => '豸', + '⾙' => '貝', + '⾚' => '赤', + '⾛' => '走', + '⾜' => '足', + '⾝' => '身', + '⾞' => '車', + '⾟' => '辛', + '⾠' => '辰', + '⾡' => '辵', + '⾢' => '邑', + '⾣' => '酉', + '⾤' => '釆', + '⾥' => '里', + '⾦' => '金', + '⾧' => '長', + '⾨' => '門', + '⾩' => '阜', + '⾪' => '隶', + '⾫' => '隹', + '⾬' => '雨', + '⾭' => '靑', + '⾮' => '非', + '⾯' => '面', + '⾰' => '革', + '⾱' => '韋', + '⾲' => '韭', + '⾳' => '音', + '⾴' => '頁', + '⾵' => '風', + '⾶' => '飛', + '⾷' => '食', + '⾸' => '首', + '⾹' => '香', + '⾺' => '馬', + '⾻' => '骨', + '⾼' => '高', + '⾽' => '髟', + '⾾' => '鬥', + '⾿' => '鬯', + '⿀' => '鬲', + '⿁' => '鬼', + '⿂' => '魚', + '⿃' => '鳥', + '⿄' => '鹵', + '⿅' => '鹿', + '⿆' => '麥', + '⿇' => '麻', + '⿈' => '黃', + '⿉' => '黍', + '⿊' => '黑', + '⿋' => '黹', + '⿌' => '黽', + '⿍' => '鼎', + '⿎' => '鼓', + '⿏' => '鼠', + '⿐' => '鼻', + '⿑' => '齊', + '⿒' => '齒', + '⿓' => '龍', + '⿔' => '龜', + '⿕' => '龠', + ' ' => ' ', + '〶' => '〒', + '〸' => '十', + '〹' => '卄', + '〺' => '卅', + '゛' => ' ゙', + '゜' => ' ゚', + 'ゟ' => 'より', + 'ヿ' => 'コト', + 'ㄱ' => 'ᄀ', + 'ㄲ' => 'ᄁ', + 'ㄳ' => 'ᆪ', + 'ㄴ' => 'ᄂ', + 'ㄵ' => 'ᆬ', + 'ㄶ' => 'ᆭ', + 'ㄷ' => 'ᄃ', + 'ㄸ' => 'ᄄ', + 'ㄹ' => 'ᄅ', + 'ㄺ' => 'ᆰ', + 'ㄻ' => 'ᆱ', + 'ㄼ' => 'ᆲ', + 'ㄽ' => 'ᆳ', + 'ㄾ' => 'ᆴ', + 'ㄿ' => 'ᆵ', + 'ㅀ' => 'ᄚ', + 'ㅁ' => 'ᄆ', + 'ㅂ' => 'ᄇ', + 'ㅃ' => 'ᄈ', + 'ㅄ' => 'ᄡ', + 'ㅅ' => 'ᄉ', + 'ㅆ' => 'ᄊ', + 'ㅇ' => 'ᄋ', + 'ㅈ' => 'ᄌ', + 'ㅉ' => 'ᄍ', + 'ㅊ' => 'ᄎ', + 'ㅋ' => 'ᄏ', + 'ㅌ' => 'ᄐ', + 'ㅍ' => 'ᄑ', + 'ㅎ' => 'ᄒ', + 'ㅏ' => 'ᅡ', + 'ㅐ' => 'ᅢ', + 'ㅑ' => 'ᅣ', + 'ㅒ' => 'ᅤ', + 'ㅓ' => 'ᅥ', + 'ㅔ' => 'ᅦ', + 'ㅕ' => 'ᅧ', + 'ㅖ' => 'ᅨ', + 'ㅗ' => 'ᅩ', + 'ㅘ' => 'ᅪ', + 'ㅙ' => 'ᅫ', + 'ㅚ' => 'ᅬ', + 'ㅛ' => 'ᅭ', + 'ㅜ' => 'ᅮ', + 'ㅝ' => 'ᅯ', + 'ㅞ' => 'ᅰ', + 'ㅟ' => 'ᅱ', + 'ㅠ' => 'ᅲ', + 'ㅡ' => 'ᅳ', + 'ㅢ' => 'ᅴ', + 'ㅣ' => 'ᅵ', + 'ㅤ' => 'ᅠ', + 'ㅥ' => 'ᄔ', + 'ㅦ' => 'ᄕ', + 'ㅧ' => 'ᇇ', + 'ㅨ' => 'ᇈ', + 'ㅩ' => 'ᇌ', + 'ㅪ' => 'ᇎ', + 'ㅫ' => 'ᇓ', + 'ㅬ' => 'ᇗ', + 'ㅭ' => 'ᇙ', + 'ㅮ' => 'ᄜ', + 'ㅯ' => 'ᇝ', + 'ㅰ' => 'ᇟ', + 'ㅱ' => 'ᄝ', + 'ㅲ' => 'ᄞ', + 'ㅳ' => 'ᄠ', + 'ㅴ' => 'ᄢ', + 'ㅵ' => 'ᄣ', + 'ㅶ' => 'ᄧ', + 'ㅷ' => 'ᄩ', + 'ㅸ' => 'ᄫ', + 'ㅹ' => 'ᄬ', + 'ㅺ' => 'ᄭ', + 'ㅻ' => 'ᄮ', + 'ㅼ' => 'ᄯ', + 'ㅽ' => 'ᄲ', + 'ㅾ' => 'ᄶ', + 'ㅿ' => 'ᅀ', + 'ㆀ' => 'ᅇ', + 'ㆁ' => 'ᅌ', + 'ㆂ' => 'ᇱ', + 'ㆃ' => 'ᇲ', + 'ㆄ' => 'ᅗ', + 'ㆅ' => 'ᅘ', + 'ㆆ' => 'ᅙ', + 'ㆇ' => 'ᆄ', + 'ㆈ' => 'ᆅ', + 'ㆉ' => 'ᆈ', + 'ㆊ' => 'ᆑ', + 'ㆋ' => 'ᆒ', + 'ㆌ' => 'ᆔ', + 'ㆍ' => 'ᆞ', + 'ㆎ' => 'ᆡ', + '㆒' => '一', + '㆓' => '二', + '㆔' => '三', + '㆕' => '四', + '㆖' => '上', + '㆗' => '中', + '㆘' => '下', + '㆙' => '甲', + '㆚' => '乙', + '㆛' => '丙', + '㆜' => '丁', + '㆝' => '天', + '㆞' => '地', + '㆟' => '人', + '㈀' => '(ᄀ)', + '㈁' => '(ᄂ)', + '㈂' => '(ᄃ)', + '㈃' => '(ᄅ)', + '㈄' => '(ᄆ)', + '㈅' => '(ᄇ)', + '㈆' => '(ᄉ)', + '㈇' => '(ᄋ)', + '㈈' => '(ᄌ)', + '㈉' => '(ᄎ)', + '㈊' => '(ᄏ)', + '㈋' => '(ᄐ)', + '㈌' => '(ᄑ)', + '㈍' => '(ᄒ)', + '㈎' => '(가)', + '㈏' => '(나)', + '㈐' => '(다)', + '㈑' => '(라)', + '㈒' => '(마)', + '㈓' => '(바)', + '㈔' => '(사)', + '㈕' => '(아)', + '㈖' => '(자)', + '㈗' => '(차)', + '㈘' => '(카)', + '㈙' => '(타)', + '㈚' => '(파)', + '㈛' => '(하)', + '㈜' => '(주)', + '㈝' => '(오전)', + '㈞' => '(오후)', + '㈠' => '(一)', + '㈡' => '(二)', + '㈢' => '(三)', + '㈣' => '(四)', + '㈤' => '(五)', + '㈥' => '(六)', + '㈦' => '(七)', + '㈧' => '(八)', + '㈨' => '(九)', + '㈩' => '(十)', + '㈪' => '(月)', + '㈫' => '(火)', + '㈬' => '(水)', + '㈭' => '(木)', + '㈮' => '(金)', + '㈯' => '(土)', + '㈰' => '(日)', + '㈱' => '(株)', + '㈲' => '(有)', + '㈳' => '(社)', + '㈴' => '(名)', + '㈵' => '(特)', + '㈶' => '(財)', + '㈷' => '(祝)', + '㈸' => '(労)', + '㈹' => '(代)', + '㈺' => '(呼)', + '㈻' => '(学)', + '㈼' => '(監)', + '㈽' => '(企)', + '㈾' => '(資)', + '㈿' => '(協)', + '㉀' => '(祭)', + '㉁' => '(休)', + '㉂' => '(自)', + '㉃' => '(至)', + '㉄' => '問', + '㉅' => '幼', + '㉆' => '文', + '㉇' => '箏', + '㉐' => 'PTE', + '㉑' => '21', + '㉒' => '22', + '㉓' => '23', + '㉔' => '24', + '㉕' => '25', + '㉖' => '26', + '㉗' => '27', + '㉘' => '28', + '㉙' => '29', + '㉚' => '30', + '㉛' => '31', + '㉜' => '32', + '㉝' => '33', + '㉞' => '34', + '㉟' => '35', + '㉠' => 'ᄀ', + '㉡' => 'ᄂ', + '㉢' => 'ᄃ', + '㉣' => 'ᄅ', + '㉤' => 'ᄆ', + '㉥' => 'ᄇ', + '㉦' => 'ᄉ', + '㉧' => 'ᄋ', + '㉨' => 'ᄌ', + '㉩' => 'ᄎ', + '㉪' => 'ᄏ', + '㉫' => 'ᄐ', + '㉬' => 'ᄑ', + '㉭' => 'ᄒ', + '㉮' => '가', + '㉯' => '나', + '㉰' => '다', + '㉱' => '라', + '㉲' => '마', + '㉳' => '바', + '㉴' => '사', + '㉵' => '아', + '㉶' => '자', + '㉷' => '차', + '㉸' => '카', + '㉹' => '타', + '㉺' => '파', + '㉻' => '하', + '㉼' => '참고', + '㉽' => '주의', + '㉾' => '우', + '㊀' => '一', + '㊁' => '二', + '㊂' => '三', + '㊃' => '四', + '㊄' => '五', + '㊅' => '六', + '㊆' => '七', + '㊇' => '八', + '㊈' => '九', + '㊉' => '十', + '㊊' => '月', + '㊋' => '火', + '㊌' => '水', + '㊍' => '木', + '㊎' => '金', + '㊏' => '土', + '㊐' => '日', + '㊑' => '株', + '㊒' => '有', + '㊓' => '社', + '㊔' => '名', + '㊕' => '特', + '㊖' => '財', + '㊗' => '祝', + '㊘' => '労', + '㊙' => '秘', + '㊚' => '男', + '㊛' => '女', + '㊜' => '適', + '㊝' => '優', + '㊞' => '印', + '㊟' => '注', + '㊠' => '項', + '㊡' => '休', + '㊢' => '写', + '㊣' => '正', + '㊤' => '上', + '㊥' => '中', + '㊦' => '下', + '㊧' => '左', + '㊨' => '右', + '㊩' => '医', + '㊪' => '宗', + '㊫' => '学', + '㊬' => '監', + '㊭' => '企', + '㊮' => '資', + '㊯' => '協', + '㊰' => '夜', + '㊱' => '36', + '㊲' => '37', + '㊳' => '38', + '㊴' => '39', + '㊵' => '40', + '㊶' => '41', + '㊷' => '42', + '㊸' => '43', + '㊹' => '44', + '㊺' => '45', + '㊻' => '46', + '㊼' => '47', + '㊽' => '48', + '㊾' => '49', + '㊿' => '50', + '㋀' => '1月', + '㋁' => '2月', + '㋂' => '3月', + '㋃' => '4月', + '㋄' => '5月', + '㋅' => '6月', + '㋆' => '7月', + '㋇' => '8月', + '㋈' => '9月', + '㋉' => '10月', + '㋊' => '11月', + '㋋' => '12月', + '㋌' => 'Hg', + '㋍' => 'erg', + '㋎' => 'eV', + '㋏' => 'LTD', + '㋐' => 'ア', + '㋑' => 'イ', + '㋒' => 'ウ', + '㋓' => 'エ', + '㋔' => 'オ', + '㋕' => 'カ', + '㋖' => 'キ', + '㋗' => 'ク', + '㋘' => 'ケ', + '㋙' => 'コ', + '㋚' => 'サ', + '㋛' => 'シ', + '㋜' => 'ス', + '㋝' => 'セ', + '㋞' => 'ソ', + '㋟' => 'タ', + '㋠' => 'チ', + '㋡' => 'ツ', + '㋢' => 'テ', + '㋣' => 'ト', + '㋤' => 'ナ', + '㋥' => 'ニ', + '㋦' => 'ヌ', + '㋧' => 'ネ', + '㋨' => 'ノ', + '㋩' => 'ハ', + '㋪' => 'ヒ', + '㋫' => 'フ', + '㋬' => 'ヘ', + '㋭' => 'ホ', + '㋮' => 'マ', + '㋯' => 'ミ', + '㋰' => 'ム', + '㋱' => 'メ', + '㋲' => 'モ', + '㋳' => 'ヤ', + '㋴' => 'ユ', + '㋵' => 'ヨ', + '㋶' => 'ラ', + '㋷' => 'リ', + '㋸' => 'ル', + '㋹' => 'レ', + '㋺' => 'ロ', + '㋻' => 'ワ', + '㋼' => 'ヰ', + '㋽' => 'ヱ', + '㋾' => 'ヲ', + '㋿' => '令和', + '㌀' => 'アパート', + '㌁' => 'アルファ', + '㌂' => 'アンペア', + '㌃' => 'アール', + '㌄' => 'イニング', + '㌅' => 'インチ', + '㌆' => 'ウォン', + '㌇' => 'エスクード', + '㌈' => 'エーカー', + '㌉' => 'オンス', + '㌊' => 'オーム', + '㌋' => 'カイリ', + '㌌' => 'カラット', + '㌍' => 'カロリー', + '㌎' => 'ガロン', + '㌏' => 'ガンマ', + '㌐' => 'ギガ', + '㌑' => 'ギニー', + '㌒' => 'キュリー', + '㌓' => 'ギルダー', + '㌔' => 'キロ', + '㌕' => 'キログラム', + '㌖' => 'キロメートル', + '㌗' => 'キロワット', + '㌘' => 'グラム', + '㌙' => 'グラムトン', + '㌚' => 'クルゼイロ', + '㌛' => 'クローネ', + '㌜' => 'ケース', + '㌝' => 'コルナ', + '㌞' => 'コーポ', + '㌟' => 'サイクル', + '㌠' => 'サンチーム', + '㌡' => 'シリング', + '㌢' => 'センチ', + '㌣' => 'セント', + '㌤' => 'ダース', + '㌥' => 'デシ', + '㌦' => 'ドル', + '㌧' => 'トン', + '㌨' => 'ナノ', + '㌩' => 'ノット', + '㌪' => 'ハイツ', + '㌫' => 'パーセント', + '㌬' => 'パーツ', + '㌭' => 'バーレル', + '㌮' => 'ピアストル', + '㌯' => 'ピクル', + '㌰' => 'ピコ', + '㌱' => 'ビル', + '㌲' => 'ファラッド', + '㌳' => 'フィート', + '㌴' => 'ブッシェル', + '㌵' => 'フラン', + '㌶' => 'ヘクタール', + '㌷' => 'ペソ', + '㌸' => 'ペニヒ', + '㌹' => 'ヘルツ', + '㌺' => 'ペンス', + '㌻' => 'ページ', + '㌼' => 'ベータ', + '㌽' => 'ポイント', + '㌾' => 'ボルト', + '㌿' => 'ホン', + '㍀' => 'ポンド', + '㍁' => 'ホール', + '㍂' => 'ホーン', + '㍃' => 'マイクロ', + '㍄' => 'マイル', + '㍅' => 'マッハ', + '㍆' => 'マルク', + '㍇' => 'マンション', + '㍈' => 'ミクロン', + '㍉' => 'ミリ', + '㍊' => 'ミリバール', + '㍋' => 'メガ', + '㍌' => 'メガトン', + '㍍' => 'メートル', + '㍎' => 'ヤード', + '㍏' => 'ヤール', + '㍐' => 'ユアン', + '㍑' => 'リットル', + '㍒' => 'リラ', + '㍓' => 'ルピー', + '㍔' => 'ルーブル', + '㍕' => 'レム', + '㍖' => 'レントゲン', + '㍗' => 'ワット', + '㍘' => '0点', + '㍙' => '1点', + '㍚' => '2点', + '㍛' => '3点', + '㍜' => '4点', + '㍝' => '5点', + '㍞' => '6点', + '㍟' => '7点', + '㍠' => '8点', + '㍡' => '9点', + '㍢' => '10点', + '㍣' => '11点', + '㍤' => '12点', + '㍥' => '13点', + '㍦' => '14点', + '㍧' => '15点', + '㍨' => '16点', + '㍩' => '17点', + '㍪' => '18点', + '㍫' => '19点', + '㍬' => '20点', + '㍭' => '21点', + '㍮' => '22点', + '㍯' => '23点', + '㍰' => '24点', + '㍱' => 'hPa', + '㍲' => 'da', + '㍳' => 'AU', + '㍴' => 'bar', + '㍵' => 'oV', + '㍶' => 'pc', + '㍷' => 'dm', + '㍸' => 'dm2', + '㍹' => 'dm3', + '㍺' => 'IU', + '㍻' => '平成', + '㍼' => '昭和', + '㍽' => '大正', + '㍾' => '明治', + '㍿' => '株式会社', + '㎀' => 'pA', + '㎁' => 'nA', + '㎂' => 'μA', + '㎃' => 'mA', + '㎄' => 'kA', + '㎅' => 'KB', + '㎆' => 'MB', + '㎇' => 'GB', + '㎈' => 'cal', + '㎉' => 'kcal', + '㎊' => 'pF', + '㎋' => 'nF', + '㎌' => 'μF', + '㎍' => 'μg', + '㎎' => 'mg', + '㎏' => 'kg', + '㎐' => 'Hz', + '㎑' => 'kHz', + '㎒' => 'MHz', + '㎓' => 'GHz', + '㎔' => 'THz', + '㎕' => 'μl', + '㎖' => 'ml', + '㎗' => 'dl', + '㎘' => 'kl', + '㎙' => 'fm', + '㎚' => 'nm', + '㎛' => 'μm', + '㎜' => 'mm', + '㎝' => 'cm', + '㎞' => 'km', + '㎟' => 'mm2', + '㎠' => 'cm2', + '㎡' => 'm2', + '㎢' => 'km2', + '㎣' => 'mm3', + '㎤' => 'cm3', + '㎥' => 'm3', + '㎦' => 'km3', + '㎧' => 'm∕s', + '㎨' => 'm∕s2', + '㎩' => 'Pa', + '㎪' => 'kPa', + '㎫' => 'MPa', + '㎬' => 'GPa', + '㎭' => 'rad', + '㎮' => 'rad∕s', + '㎯' => 'rad∕s2', + '㎰' => 'ps', + '㎱' => 'ns', + '㎲' => 'μs', + '㎳' => 'ms', + '㎴' => 'pV', + '㎵' => 'nV', + '㎶' => 'μV', + '㎷' => 'mV', + '㎸' => 'kV', + '㎹' => 'MV', + '㎺' => 'pW', + '㎻' => 'nW', + '㎼' => 'μW', + '㎽' => 'mW', + '㎾' => 'kW', + '㎿' => 'MW', + '㏀' => 'kΩ', + '㏁' => 'MΩ', + '㏂' => 'a.m.', + '㏃' => 'Bq', + '㏄' => 'cc', + '㏅' => 'cd', + '㏆' => 'C∕kg', + '㏇' => 'Co.', + '㏈' => 'dB', + '㏉' => 'Gy', + '㏊' => 'ha', + '㏋' => 'HP', + '㏌' => 'in', + '㏍' => 'KK', + '㏎' => 'KM', + '㏏' => 'kt', + '㏐' => 'lm', + '㏑' => 'ln', + '㏒' => 'log', + '㏓' => 'lx', + '㏔' => 'mb', + '㏕' => 'mil', + '㏖' => 'mol', + '㏗' => 'PH', + '㏘' => 'p.m.', + '㏙' => 'PPM', + '㏚' => 'PR', + '㏛' => 'sr', + '㏜' => 'Sv', + '㏝' => 'Wb', + '㏞' => 'V∕m', + '㏟' => 'A∕m', + '㏠' => '1日', + '㏡' => '2日', + '㏢' => '3日', + '㏣' => '4日', + '㏤' => '5日', + '㏥' => '6日', + '㏦' => '7日', + '㏧' => '8日', + '㏨' => '9日', + '㏩' => '10日', + '㏪' => '11日', + '㏫' => '12日', + '㏬' => '13日', + '㏭' => '14日', + '㏮' => '15日', + '㏯' => '16日', + '㏰' => '17日', + '㏱' => '18日', + '㏲' => '19日', + '㏳' => '20日', + '㏴' => '21日', + '㏵' => '22日', + '㏶' => '23日', + '㏷' => '24日', + '㏸' => '25日', + '㏹' => '26日', + '㏺' => '27日', + '㏻' => '28日', + '㏼' => '29日', + '㏽' => '30日', + '㏾' => '31日', + '㏿' => 'gal', + 'ꚜ' => 'ъ', + 'ꚝ' => 'ь', + 'ꝰ' => 'ꝯ', + 'ꟸ' => 'Ħ', + 'ꟹ' => 'œ', + 'ꭜ' => 'ꜧ', + 'ꭝ' => 'ꬷ', + 'ꭞ' => 'ɫ', + 'ꭟ' => 'ꭒ', + 'ꭩ' => 'ʍ', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'st', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', + 'ﬠ' => 'ע', + 'ﬡ' => 'א', + 'ﬢ' => 'ד', + 'ﬣ' => 'ה', + 'ﬤ' => 'כ', + 'ﬥ' => 'ל', + 'ﬦ' => 'ם', + 'ﬧ' => 'ר', + 'ﬨ' => 'ת', + '﬩' => '+', + 'ﭏ' => 'אל', + 'ﭐ' => 'ٱ', + 'ﭑ' => 'ٱ', + 'ﭒ' => 'ٻ', + 'ﭓ' => 'ٻ', + 'ﭔ' => 'ٻ', + 'ﭕ' => 'ٻ', + 'ﭖ' => 'پ', + 'ﭗ' => 'پ', + 'ﭘ' => 'پ', + 'ﭙ' => 'پ', + 'ﭚ' => 'ڀ', + 'ﭛ' => 'ڀ', + 'ﭜ' => 'ڀ', + 'ﭝ' => 'ڀ', + 'ﭞ' => 'ٺ', + 'ﭟ' => 'ٺ', + 'ﭠ' => 'ٺ', + 'ﭡ' => 'ٺ', + 'ﭢ' => 'ٿ', + 'ﭣ' => 'ٿ', + 'ﭤ' => 'ٿ', + 'ﭥ' => 'ٿ', + 'ﭦ' => 'ٹ', + 'ﭧ' => 'ٹ', + 'ﭨ' => 'ٹ', + 'ﭩ' => 'ٹ', + 'ﭪ' => 'ڤ', + 'ﭫ' => 'ڤ', + 'ﭬ' => 'ڤ', + 'ﭭ' => 'ڤ', + 'ﭮ' => 'ڦ', + 'ﭯ' => 'ڦ', + 'ﭰ' => 'ڦ', + 'ﭱ' => 'ڦ', + 'ﭲ' => 'ڄ', + 'ﭳ' => 'ڄ', + 'ﭴ' => 'ڄ', + 'ﭵ' => 'ڄ', + 'ﭶ' => 'ڃ', + 'ﭷ' => 'ڃ', + 'ﭸ' => 'ڃ', + 'ﭹ' => 'ڃ', + 'ﭺ' => 'چ', + 'ﭻ' => 'چ', + 'ﭼ' => 'چ', + 'ﭽ' => 'چ', + 'ﭾ' => 'ڇ', + 'ﭿ' => 'ڇ', + 'ﮀ' => 'ڇ', + 'ﮁ' => 'ڇ', + 'ﮂ' => 'ڍ', + 'ﮃ' => 'ڍ', + 'ﮄ' => 'ڌ', + 'ﮅ' => 'ڌ', + 'ﮆ' => 'ڎ', + 'ﮇ' => 'ڎ', + 'ﮈ' => 'ڈ', + 'ﮉ' => 'ڈ', + 'ﮊ' => 'ژ', + 'ﮋ' => 'ژ', + 'ﮌ' => 'ڑ', + 'ﮍ' => 'ڑ', + 'ﮎ' => 'ک', + 'ﮏ' => 'ک', + 'ﮐ' => 'ک', + 'ﮑ' => 'ک', + 'ﮒ' => 'گ', + 'ﮓ' => 'گ', + 'ﮔ' => 'گ', + 'ﮕ' => 'گ', + 'ﮖ' => 'ڳ', + 'ﮗ' => 'ڳ', + 'ﮘ' => 'ڳ', + 'ﮙ' => 'ڳ', + 'ﮚ' => 'ڱ', + 'ﮛ' => 'ڱ', + 'ﮜ' => 'ڱ', + 'ﮝ' => 'ڱ', + 'ﮞ' => 'ں', + 'ﮟ' => 'ں', + 'ﮠ' => 'ڻ', + 'ﮡ' => 'ڻ', + 'ﮢ' => 'ڻ', + 'ﮣ' => 'ڻ', + 'ﮤ' => 'ۀ', + 'ﮥ' => 'ۀ', + 'ﮦ' => 'ہ', + 'ﮧ' => 'ہ', + 'ﮨ' => 'ہ', + 'ﮩ' => 'ہ', + 'ﮪ' => 'ھ', + 'ﮫ' => 'ھ', + 'ﮬ' => 'ھ', + 'ﮭ' => 'ھ', + 'ﮮ' => 'ے', + 'ﮯ' => 'ے', + 'ﮰ' => 'ۓ', + 'ﮱ' => 'ۓ', + 'ﯓ' => 'ڭ', + 'ﯔ' => 'ڭ', + 'ﯕ' => 'ڭ', + 'ﯖ' => 'ڭ', + 'ﯗ' => 'ۇ', + 'ﯘ' => 'ۇ', + 'ﯙ' => 'ۆ', + 'ﯚ' => 'ۆ', + 'ﯛ' => 'ۈ', + 'ﯜ' => 'ۈ', + 'ﯝ' => 'ۇٴ', + 'ﯞ' => 'ۋ', + 'ﯟ' => 'ۋ', + 'ﯠ' => 'ۅ', + 'ﯡ' => 'ۅ', + 'ﯢ' => 'ۉ', + 'ﯣ' => 'ۉ', + 'ﯤ' => 'ې', + 'ﯥ' => 'ې', + 'ﯦ' => 'ې', + 'ﯧ' => 'ې', + 'ﯨ' => 'ى', + 'ﯩ' => 'ى', + 'ﯪ' => 'ئا', + 'ﯫ' => 'ئا', + 'ﯬ' => 'ئە', + 'ﯭ' => 'ئە', + 'ﯮ' => 'ئو', + 'ﯯ' => 'ئو', + 'ﯰ' => 'ئۇ', + 'ﯱ' => 'ئۇ', + 'ﯲ' => 'ئۆ', + 'ﯳ' => 'ئۆ', + 'ﯴ' => 'ئۈ', + 'ﯵ' => 'ئۈ', + 'ﯶ' => 'ئې', + 'ﯷ' => 'ئې', + 'ﯸ' => 'ئې', + 'ﯹ' => 'ئى', + 'ﯺ' => 'ئى', + 'ﯻ' => 'ئى', + 'ﯼ' => 'ی', + 'ﯽ' => 'ی', + 'ﯾ' => 'ی', + 'ﯿ' => 'ی', + 'ﰀ' => 'ئج', + 'ﰁ' => 'ئح', + 'ﰂ' => 'ئم', + 'ﰃ' => 'ئى', + 'ﰄ' => 'ئي', + 'ﰅ' => 'بج', + 'ﰆ' => 'بح', + 'ﰇ' => 'بخ', + 'ﰈ' => 'بم', + 'ﰉ' => 'بى', + 'ﰊ' => 'بي', + 'ﰋ' => 'تج', + 'ﰌ' => 'تح', + 'ﰍ' => 'تخ', + 'ﰎ' => 'تم', + 'ﰏ' => 'تى', + 'ﰐ' => 'تي', + 'ﰑ' => 'ثج', + 'ﰒ' => 'ثم', + 'ﰓ' => 'ثى', + 'ﰔ' => 'ثي', + 'ﰕ' => 'جح', + 'ﰖ' => 'جم', + 'ﰗ' => 'حج', + 'ﰘ' => 'حم', + 'ﰙ' => 'خج', + 'ﰚ' => 'خح', + 'ﰛ' => 'خم', + 'ﰜ' => 'سج', + 'ﰝ' => 'سح', + 'ﰞ' => 'سخ', + 'ﰟ' => 'سم', + 'ﰠ' => 'صح', + 'ﰡ' => 'صم', + 'ﰢ' => 'ضج', + 'ﰣ' => 'ضح', + 'ﰤ' => 'ضخ', + 'ﰥ' => 'ضم', + 'ﰦ' => 'طح', + 'ﰧ' => 'طم', + 'ﰨ' => 'ظم', + 'ﰩ' => 'عج', + 'ﰪ' => 'عم', + 'ﰫ' => 'غج', + 'ﰬ' => 'غم', + 'ﰭ' => 'فج', + 'ﰮ' => 'فح', + 'ﰯ' => 'فخ', + 'ﰰ' => 'فم', + 'ﰱ' => 'فى', + 'ﰲ' => 'في', + 'ﰳ' => 'قح', + 'ﰴ' => 'قم', + 'ﰵ' => 'قى', + 'ﰶ' => 'قي', + 'ﰷ' => 'كا', + 'ﰸ' => 'كج', + 'ﰹ' => 'كح', + 'ﰺ' => 'كخ', + 'ﰻ' => 'كل', + 'ﰼ' => 'كم', + 'ﰽ' => 'كى', + 'ﰾ' => 'كي', + 'ﰿ' => 'لج', + 'ﱀ' => 'لح', + 'ﱁ' => 'لخ', + 'ﱂ' => 'لم', + 'ﱃ' => 'لى', + 'ﱄ' => 'لي', + 'ﱅ' => 'مج', + 'ﱆ' => 'مح', + 'ﱇ' => 'مخ', + 'ﱈ' => 'مم', + 'ﱉ' => 'مى', + 'ﱊ' => 'مي', + 'ﱋ' => 'نج', + 'ﱌ' => 'نح', + 'ﱍ' => 'نخ', + 'ﱎ' => 'نم', + 'ﱏ' => 'نى', + 'ﱐ' => 'ني', + 'ﱑ' => 'هج', + 'ﱒ' => 'هم', + 'ﱓ' => 'هى', + 'ﱔ' => 'هي', + 'ﱕ' => 'يج', + 'ﱖ' => 'يح', + 'ﱗ' => 'يخ', + 'ﱘ' => 'يم', + 'ﱙ' => 'يى', + 'ﱚ' => 'يي', + 'ﱛ' => 'ذٰ', + 'ﱜ' => 'رٰ', + 'ﱝ' => 'ىٰ', + 'ﱞ' => ' ٌّ', + 'ﱟ' => ' ٍّ', + 'ﱠ' => ' َّ', + 'ﱡ' => ' ُّ', + 'ﱢ' => ' ِّ', + 'ﱣ' => ' ّٰ', + 'ﱤ' => 'ئر', + 'ﱥ' => 'ئز', + 'ﱦ' => 'ئم', + 'ﱧ' => 'ئن', + 'ﱨ' => 'ئى', + 'ﱩ' => 'ئي', + 'ﱪ' => 'بر', + 'ﱫ' => 'بز', + 'ﱬ' => 'بم', + 'ﱭ' => 'بن', + 'ﱮ' => 'بى', + 'ﱯ' => 'بي', + 'ﱰ' => 'تر', + 'ﱱ' => 'تز', + 'ﱲ' => 'تم', + 'ﱳ' => 'تن', + 'ﱴ' => 'تى', + 'ﱵ' => 'تي', + 'ﱶ' => 'ثر', + 'ﱷ' => 'ثز', + 'ﱸ' => 'ثم', + 'ﱹ' => 'ثن', + 'ﱺ' => 'ثى', + 'ﱻ' => 'ثي', + 'ﱼ' => 'فى', + 'ﱽ' => 'في', + 'ﱾ' => 'قى', + 'ﱿ' => 'قي', + 'ﲀ' => 'كا', + 'ﲁ' => 'كل', + 'ﲂ' => 'كم', + 'ﲃ' => 'كى', + 'ﲄ' => 'كي', + 'ﲅ' => 'لم', + 'ﲆ' => 'لى', + 'ﲇ' => 'لي', + 'ﲈ' => 'ما', + 'ﲉ' => 'مم', + 'ﲊ' => 'نر', + 'ﲋ' => 'نز', + 'ﲌ' => 'نم', + 'ﲍ' => 'نن', + 'ﲎ' => 'نى', + 'ﲏ' => 'ني', + 'ﲐ' => 'ىٰ', + 'ﲑ' => 'ير', + 'ﲒ' => 'يز', + 'ﲓ' => 'يم', + 'ﲔ' => 'ين', + 'ﲕ' => 'يى', + 'ﲖ' => 'يي', + 'ﲗ' => 'ئج', + 'ﲘ' => 'ئح', + 'ﲙ' => 'ئخ', + 'ﲚ' => 'ئم', + 'ﲛ' => 'ئه', + 'ﲜ' => 'بج', + 'ﲝ' => 'بح', + 'ﲞ' => 'بخ', + 'ﲟ' => 'بم', + 'ﲠ' => 'به', + 'ﲡ' => 'تج', + 'ﲢ' => 'تح', + 'ﲣ' => 'تخ', + 'ﲤ' => 'تم', + 'ﲥ' => 'ته', + 'ﲦ' => 'ثم', + 'ﲧ' => 'جح', + 'ﲨ' => 'جم', + 'ﲩ' => 'حج', + 'ﲪ' => 'حم', + 'ﲫ' => 'خج', + 'ﲬ' => 'خم', + 'ﲭ' => 'سج', + 'ﲮ' => 'سح', + 'ﲯ' => 'سخ', + 'ﲰ' => 'سم', + 'ﲱ' => 'صح', + 'ﲲ' => 'صخ', + 'ﲳ' => 'صم', + 'ﲴ' => 'ضج', + 'ﲵ' => 'ضح', + 'ﲶ' => 'ضخ', + 'ﲷ' => 'ضم', + 'ﲸ' => 'طح', + 'ﲹ' => 'ظم', + 'ﲺ' => 'عج', + 'ﲻ' => 'عم', + 'ﲼ' => 'غج', + 'ﲽ' => 'غم', + 'ﲾ' => 'فج', + 'ﲿ' => 'فح', + 'ﳀ' => 'فخ', + 'ﳁ' => 'فم', + 'ﳂ' => 'قح', + 'ﳃ' => 'قم', + 'ﳄ' => 'كج', + 'ﳅ' => 'كح', + 'ﳆ' => 'كخ', + 'ﳇ' => 'كل', + 'ﳈ' => 'كم', + 'ﳉ' => 'لج', + 'ﳊ' => 'لح', + 'ﳋ' => 'لخ', + 'ﳌ' => 'لم', + 'ﳍ' => 'له', + 'ﳎ' => 'مج', + 'ﳏ' => 'مح', + 'ﳐ' => 'مخ', + 'ﳑ' => 'مم', + 'ﳒ' => 'نج', + 'ﳓ' => 'نح', + 'ﳔ' => 'نخ', + 'ﳕ' => 'نم', + 'ﳖ' => 'نه', + 'ﳗ' => 'هج', + 'ﳘ' => 'هم', + 'ﳙ' => 'هٰ', + 'ﳚ' => 'يج', + 'ﳛ' => 'يح', + 'ﳜ' => 'يخ', + 'ﳝ' => 'يم', + 'ﳞ' => 'يه', + 'ﳟ' => 'ئم', + 'ﳠ' => 'ئه', + 'ﳡ' => 'بم', + 'ﳢ' => 'به', + 'ﳣ' => 'تم', + 'ﳤ' => 'ته', + 'ﳥ' => 'ثم', + 'ﳦ' => 'ثه', + 'ﳧ' => 'سم', + 'ﳨ' => 'سه', + 'ﳩ' => 'شم', + 'ﳪ' => 'شه', + 'ﳫ' => 'كل', + 'ﳬ' => 'كم', + 'ﳭ' => 'لم', + 'ﳮ' => 'نم', + 'ﳯ' => 'نه', + 'ﳰ' => 'يم', + 'ﳱ' => 'يه', + 'ﳲ' => 'ـَّ', + 'ﳳ' => 'ـُّ', + 'ﳴ' => 'ـِّ', + 'ﳵ' => 'طى', + 'ﳶ' => 'طي', + 'ﳷ' => 'عى', + 'ﳸ' => 'عي', + 'ﳹ' => 'غى', + 'ﳺ' => 'غي', + 'ﳻ' => 'سى', + 'ﳼ' => 'سي', + 'ﳽ' => 'شى', + 'ﳾ' => 'شي', + 'ﳿ' => 'حى', + 'ﴀ' => 'حي', + 'ﴁ' => 'جى', + 'ﴂ' => 'جي', + 'ﴃ' => 'خى', + 'ﴄ' => 'خي', + 'ﴅ' => 'صى', + 'ﴆ' => 'صي', + 'ﴇ' => 'ضى', + 'ﴈ' => 'ضي', + 'ﴉ' => 'شج', + 'ﴊ' => 'شح', + 'ﴋ' => 'شخ', + 'ﴌ' => 'شم', + 'ﴍ' => 'شر', + 'ﴎ' => 'سر', + 'ﴏ' => 'صر', + 'ﴐ' => 'ضر', + 'ﴑ' => 'طى', + 'ﴒ' => 'طي', + 'ﴓ' => 'عى', + 'ﴔ' => 'عي', + 'ﴕ' => 'غى', + 'ﴖ' => 'غي', + 'ﴗ' => 'سى', + 'ﴘ' => 'سي', + 'ﴙ' => 'شى', + 'ﴚ' => 'شي', + 'ﴛ' => 'حى', + 'ﴜ' => 'حي', + 'ﴝ' => 'جى', + 'ﴞ' => 'جي', + 'ﴟ' => 'خى', + 'ﴠ' => 'خي', + 'ﴡ' => 'صى', + 'ﴢ' => 'صي', + 'ﴣ' => 'ضى', + 'ﴤ' => 'ضي', + 'ﴥ' => 'شج', + 'ﴦ' => 'شح', + 'ﴧ' => 'شخ', + 'ﴨ' => 'شم', + 'ﴩ' => 'شر', + 'ﴪ' => 'سر', + 'ﴫ' => 'صر', + 'ﴬ' => 'ضر', + 'ﴭ' => 'شج', + 'ﴮ' => 'شح', + 'ﴯ' => 'شخ', + 'ﴰ' => 'شم', + 'ﴱ' => 'سه', + 'ﴲ' => 'شه', + 'ﴳ' => 'طم', + 'ﴴ' => 'سج', + 'ﴵ' => 'سح', + 'ﴶ' => 'سخ', + 'ﴷ' => 'شج', + 'ﴸ' => 'شح', + 'ﴹ' => 'شخ', + 'ﴺ' => 'طم', + 'ﴻ' => 'ظم', + 'ﴼ' => 'اً', + 'ﴽ' => 'اً', + 'ﵐ' => 'تجم', + 'ﵑ' => 'تحج', + 'ﵒ' => 'تحج', + 'ﵓ' => 'تحم', + 'ﵔ' => 'تخم', + 'ﵕ' => 'تمج', + 'ﵖ' => 'تمح', + 'ﵗ' => 'تمخ', + 'ﵘ' => 'جمح', + 'ﵙ' => 'جمح', + 'ﵚ' => 'حمي', + 'ﵛ' => 'حمى', + 'ﵜ' => 'سحج', + 'ﵝ' => 'سجح', + 'ﵞ' => 'سجى', + 'ﵟ' => 'سمح', + 'ﵠ' => 'سمح', + 'ﵡ' => 'سمج', + 'ﵢ' => 'سمم', + 'ﵣ' => 'سمم', + 'ﵤ' => 'صحح', + 'ﵥ' => 'صحح', + 'ﵦ' => 'صمم', + 'ﵧ' => 'شحم', + 'ﵨ' => 'شحم', + 'ﵩ' => 'شجي', + 'ﵪ' => 'شمخ', + 'ﵫ' => 'شمخ', + 'ﵬ' => 'شمم', + 'ﵭ' => 'شمم', + 'ﵮ' => 'ضحى', + 'ﵯ' => 'ضخم', + 'ﵰ' => 'ضخم', + 'ﵱ' => 'طمح', + 'ﵲ' => 'طمح', + 'ﵳ' => 'طمم', + 'ﵴ' => 'طمي', + 'ﵵ' => 'عجم', + 'ﵶ' => 'عمم', + 'ﵷ' => 'عمم', + 'ﵸ' => 'عمى', + 'ﵹ' => 'غمم', + 'ﵺ' => 'غمي', + 'ﵻ' => 'غمى', + 'ﵼ' => 'فخم', + 'ﵽ' => 'فخم', + 'ﵾ' => 'قمح', + 'ﵿ' => 'قمم', + 'ﶀ' => 'لحم', + 'ﶁ' => 'لحي', + 'ﶂ' => 'لحى', + 'ﶃ' => 'لجج', + 'ﶄ' => 'لجج', + 'ﶅ' => 'لخم', + 'ﶆ' => 'لخم', + 'ﶇ' => 'لمح', + 'ﶈ' => 'لمح', + 'ﶉ' => 'محج', + 'ﶊ' => 'محم', + 'ﶋ' => 'محي', + 'ﶌ' => 'مجح', + 'ﶍ' => 'مجم', + 'ﶎ' => 'مخج', + 'ﶏ' => 'مخم', + 'ﶒ' => 'مجخ', + 'ﶓ' => 'همج', + 'ﶔ' => 'همم', + 'ﶕ' => 'نحم', + 'ﶖ' => 'نحى', + 'ﶗ' => 'نجم', + 'ﶘ' => 'نجم', + 'ﶙ' => 'نجى', + 'ﶚ' => 'نمي', + 'ﶛ' => 'نمى', + 'ﶜ' => 'يمم', + 'ﶝ' => 'يمم', + 'ﶞ' => 'بخي', + 'ﶟ' => 'تجي', + 'ﶠ' => 'تجى', + 'ﶡ' => 'تخي', + 'ﶢ' => 'تخى', + 'ﶣ' => 'تمي', + 'ﶤ' => 'تمى', + 'ﶥ' => 'جمي', + 'ﶦ' => 'جحى', + 'ﶧ' => 'جمى', + 'ﶨ' => 'سخى', + 'ﶩ' => 'صحي', + 'ﶪ' => 'شحي', + 'ﶫ' => 'ضحي', + 'ﶬ' => 'لجي', + 'ﶭ' => 'لمي', + 'ﶮ' => 'يحي', + 'ﶯ' => 'يجي', + 'ﶰ' => 'يمي', + 'ﶱ' => 'ممي', + 'ﶲ' => 'قمي', + 'ﶳ' => 'نحي', + 'ﶴ' => 'قمح', + 'ﶵ' => 'لحم', + 'ﶶ' => 'عمي', + 'ﶷ' => 'كمي', + 'ﶸ' => 'نجح', + 'ﶹ' => 'مخي', + 'ﶺ' => 'لجم', + 'ﶻ' => 'كمم', + 'ﶼ' => 'لجم', + 'ﶽ' => 'نجح', + 'ﶾ' => 'جحي', + 'ﶿ' => 'حجي', + 'ﷀ' => 'مجي', + 'ﷁ' => 'فمي', + 'ﷂ' => 'بحي', + 'ﷃ' => 'كمم', + 'ﷄ' => 'عجم', + 'ﷅ' => 'صمم', + 'ﷆ' => 'سخي', + 'ﷇ' => 'نجي', + 'ﷰ' => 'صلے', + 'ﷱ' => 'قلے', + 'ﷲ' => 'الله', + 'ﷳ' => 'اكبر', + 'ﷴ' => 'محمد', + 'ﷵ' => 'صلعم', + 'ﷶ' => 'رسول', + 'ﷷ' => 'عليه', + 'ﷸ' => 'وسلم', + 'ﷹ' => 'صلى', + 'ﷺ' => 'صلى الله عليه وسلم', + 'ﷻ' => 'جل جلاله', + '﷼' => 'ریال', + '︐' => ',', + '︑' => '、', + '︒' => '。', + '︓' => ':', + '︔' => ';', + '︕' => '!', + '︖' => '?', + '︗' => '〖', + '︘' => '〗', + '︙' => '...', + '︰' => '..', + '︱' => '—', + '︲' => '–', + '︳' => '_', + '︴' => '_', + '︵' => '(', + '︶' => ')', + '︷' => '{', + '︸' => '}', + '︹' => '〔', + '︺' => '〕', + '︻' => '【', + '︼' => '】', + '︽' => '《', + '︾' => '》', + '︿' => '〈', + '﹀' => '〉', + '﹁' => '「', + '﹂' => '」', + '﹃' => '『', + '﹄' => '』', + '﹇' => '[', + '﹈' => ']', + '﹉' => ' ̅', + '﹊' => ' ̅', + '﹋' => ' ̅', + '﹌' => ' ̅', + '﹍' => '_', + '﹎' => '_', + '﹏' => '_', + '﹐' => ',', + '﹑' => '、', + '﹒' => '.', + '﹔' => ';', + '﹕' => ':', + '﹖' => '?', + '﹗' => '!', + '﹘' => '—', + '﹙' => '(', + '﹚' => ')', + '﹛' => '{', + '﹜' => '}', + '﹝' => '〔', + '﹞' => '〕', + '﹟' => '#', + '﹠' => '&', + '﹡' => '*', + '﹢' => '+', + '﹣' => '-', + '﹤' => '<', + '﹥' => '>', + '﹦' => '=', + '﹨' => '\\', + '﹩' => '$', + '﹪' => '%', + '﹫' => '@', + 'ﹰ' => ' ً', + 'ﹱ' => 'ـً', + 'ﹲ' => ' ٌ', + 'ﹴ' => ' ٍ', + 'ﹶ' => ' َ', + 'ﹷ' => 'ـَ', + 'ﹸ' => ' ُ', + 'ﹹ' => 'ـُ', + 'ﹺ' => ' ِ', + 'ﹻ' => 'ـِ', + 'ﹼ' => ' ّ', + 'ﹽ' => 'ـّ', + 'ﹾ' => ' ْ', + 'ﹿ' => 'ـْ', + 'ﺀ' => 'ء', + 'ﺁ' => 'آ', + 'ﺂ' => 'آ', + 'ﺃ' => 'أ', + 'ﺄ' => 'أ', + 'ﺅ' => 'ؤ', + 'ﺆ' => 'ؤ', + 'ﺇ' => 'إ', + 'ﺈ' => 'إ', + 'ﺉ' => 'ئ', + 'ﺊ' => 'ئ', + 'ﺋ' => 'ئ', + 'ﺌ' => 'ئ', + 'ﺍ' => 'ا', + 'ﺎ' => 'ا', + 'ﺏ' => 'ب', + 'ﺐ' => 'ب', + 'ﺑ' => 'ب', + 'ﺒ' => 'ب', + 'ﺓ' => 'ة', + 'ﺔ' => 'ة', + 'ﺕ' => 'ت', + 'ﺖ' => 'ت', + 'ﺗ' => 'ت', + 'ﺘ' => 'ت', + 'ﺙ' => 'ث', + 'ﺚ' => 'ث', + 'ﺛ' => 'ث', + 'ﺜ' => 'ث', + 'ﺝ' => 'ج', + 'ﺞ' => 'ج', + 'ﺟ' => 'ج', + 'ﺠ' => 'ج', + 'ﺡ' => 'ح', + 'ﺢ' => 'ح', + 'ﺣ' => 'ح', + 'ﺤ' => 'ح', + 'ﺥ' => 'خ', + 'ﺦ' => 'خ', + 'ﺧ' => 'خ', + 'ﺨ' => 'خ', + 'ﺩ' => 'د', + 'ﺪ' => 'د', + 'ﺫ' => 'ذ', + 'ﺬ' => 'ذ', + 'ﺭ' => 'ر', + 'ﺮ' => 'ر', + 'ﺯ' => 'ز', + 'ﺰ' => 'ز', + 'ﺱ' => 'س', + 'ﺲ' => 'س', + 'ﺳ' => 'س', + 'ﺴ' => 'س', + 'ﺵ' => 'ش', + 'ﺶ' => 'ش', + 'ﺷ' => 'ش', + 'ﺸ' => 'ش', + 'ﺹ' => 'ص', + 'ﺺ' => 'ص', + 'ﺻ' => 'ص', + 'ﺼ' => 'ص', + 'ﺽ' => 'ض', + 'ﺾ' => 'ض', + 'ﺿ' => 'ض', + 'ﻀ' => 'ض', + 'ﻁ' => 'ط', + 'ﻂ' => 'ط', + 'ﻃ' => 'ط', + 'ﻄ' => 'ط', + 'ﻅ' => 'ظ', + 'ﻆ' => 'ظ', + 'ﻇ' => 'ظ', + 'ﻈ' => 'ظ', + 'ﻉ' => 'ع', + 'ﻊ' => 'ع', + 'ﻋ' => 'ع', + 'ﻌ' => 'ع', + 'ﻍ' => 'غ', + 'ﻎ' => 'غ', + 'ﻏ' => 'غ', + 'ﻐ' => 'غ', + 'ﻑ' => 'ف', + 'ﻒ' => 'ف', + 'ﻓ' => 'ف', + 'ﻔ' => 'ف', + 'ﻕ' => 'ق', + 'ﻖ' => 'ق', + 'ﻗ' => 'ق', + 'ﻘ' => 'ق', + 'ﻙ' => 'ك', + 'ﻚ' => 'ك', + 'ﻛ' => 'ك', + 'ﻜ' => 'ك', + 'ﻝ' => 'ل', + 'ﻞ' => 'ل', + 'ﻟ' => 'ل', + 'ﻠ' => 'ل', + 'ﻡ' => 'م', + 'ﻢ' => 'م', + 'ﻣ' => 'م', + 'ﻤ' => 'م', + 'ﻥ' => 'ن', + 'ﻦ' => 'ن', + 'ﻧ' => 'ن', + 'ﻨ' => 'ن', + 'ﻩ' => 'ه', + 'ﻪ' => 'ه', + 'ﻫ' => 'ه', + 'ﻬ' => 'ه', + 'ﻭ' => 'و', + 'ﻮ' => 'و', + 'ﻯ' => 'ى', + 'ﻰ' => 'ى', + 'ﻱ' => 'ي', + 'ﻲ' => 'ي', + 'ﻳ' => 'ي', + 'ﻴ' => 'ي', + 'ﻵ' => 'لآ', + 'ﻶ' => 'لآ', + 'ﻷ' => 'لأ', + 'ﻸ' => 'لأ', + 'ﻹ' => 'لإ', + 'ﻺ' => 'لإ', + 'ﻻ' => 'لا', + 'ﻼ' => 'لا', + '!' => '!', + '"' => '"', + '#' => '#', + '$' => '$', + '%' => '%', + '&' => '&', + ''' => '\'', + '(' => '(', + ')' => ')', + '*' => '*', + '+' => '+', + ',' => ',', + '-' => '-', + '.' => '.', + '/' => '/', + '0' => '0', + '1' => '1', + '2' => '2', + '3' => '3', + '4' => '4', + '5' => '5', + '6' => '6', + '7' => '7', + '8' => '8', + '9' => '9', + ':' => ':', + ';' => ';', + '<' => '<', + '=' => '=', + '>' => '>', + '?' => '?', + '@' => '@', + 'A' => 'A', + 'B' => 'B', + 'C' => 'C', + 'D' => 'D', + 'E' => 'E', + 'F' => 'F', + 'G' => 'G', + 'H' => 'H', + 'I' => 'I', + 'J' => 'J', + 'K' => 'K', + 'L' => 'L', + 'M' => 'M', + 'N' => 'N', + 'O' => 'O', + 'P' => 'P', + 'Q' => 'Q', + 'R' => 'R', + 'S' => 'S', + 'T' => 'T', + 'U' => 'U', + 'V' => 'V', + 'W' => 'W', + 'X' => 'X', + 'Y' => 'Y', + 'Z' => 'Z', + '[' => '[', + '\' => '\\', + ']' => ']', + '^' => '^', + '_' => '_', + '`' => '`', + 'a' => 'a', + 'b' => 'b', + 'c' => 'c', + 'd' => 'd', + 'e' => 'e', + 'f' => 'f', + 'g' => 'g', + 'h' => 'h', + 'i' => 'i', + 'j' => 'j', + 'k' => 'k', + 'l' => 'l', + 'm' => 'm', + 'n' => 'n', + 'o' => 'o', + 'p' => 'p', + 'q' => 'q', + 'r' => 'r', + 's' => 's', + 't' => 't', + 'u' => 'u', + 'v' => 'v', + 'w' => 'w', + 'x' => 'x', + 'y' => 'y', + 'z' => 'z', + '{' => '{', + '|' => '|', + '}' => '}', + '~' => '~', + '⦅' => '⦅', + '⦆' => '⦆', + '。' => '。', + '「' => '「', + '」' => '」', + '、' => '、', + '・' => '・', + 'ヲ' => 'ヲ', + 'ァ' => 'ァ', + 'ィ' => 'ィ', + 'ゥ' => 'ゥ', + 'ェ' => 'ェ', + 'ォ' => 'ォ', + 'ャ' => 'ャ', + 'ュ' => 'ュ', + 'ョ' => 'ョ', + 'ッ' => 'ッ', + 'ー' => 'ー', + 'ア' => 'ア', + 'イ' => 'イ', + 'ウ' => 'ウ', + 'エ' => 'エ', + 'オ' => 'オ', + 'カ' => 'カ', + 'キ' => 'キ', + 'ク' => 'ク', + 'ケ' => 'ケ', + 'コ' => 'コ', + 'サ' => 'サ', + 'シ' => 'シ', + 'ス' => 'ス', + 'セ' => 'セ', + 'ソ' => 'ソ', + 'タ' => 'タ', + 'チ' => 'チ', + 'ツ' => 'ツ', + 'テ' => 'テ', + 'ト' => 'ト', + 'ナ' => 'ナ', + 'ニ' => 'ニ', + 'ヌ' => 'ヌ', + 'ネ' => 'ネ', + 'ノ' => 'ノ', + 'ハ' => 'ハ', + 'ヒ' => 'ヒ', + 'フ' => 'フ', + 'ヘ' => 'ヘ', + 'ホ' => 'ホ', + 'マ' => 'マ', + 'ミ' => 'ミ', + 'ム' => 'ム', + 'メ' => 'メ', + 'モ' => 'モ', + 'ヤ' => 'ヤ', + 'ユ' => 'ユ', + 'ヨ' => 'ヨ', + 'ラ' => 'ラ', + 'リ' => 'リ', + 'ル' => 'ル', + 'レ' => 'レ', + 'ロ' => 'ロ', + 'ワ' => 'ワ', + 'ン' => 'ン', + '゙' => '゙', + '゚' => '゚', + 'ᅠ' => 'ᅠ', + 'ᄀ' => 'ᄀ', + 'ᄁ' => 'ᄁ', + 'ᆪ' => 'ᆪ', + 'ᄂ' => 'ᄂ', + 'ᆬ' => 'ᆬ', + 'ᆭ' => 'ᆭ', + 'ᄃ' => 'ᄃ', + 'ᄄ' => 'ᄄ', + 'ᄅ' => 'ᄅ', + 'ᆰ' => 'ᆰ', + 'ᆱ' => 'ᆱ', + 'ᆲ' => 'ᆲ', + 'ᆳ' => 'ᆳ', + 'ᆴ' => 'ᆴ', + 'ᆵ' => 'ᆵ', + 'ᄚ' => 'ᄚ', + 'ᄆ' => 'ᄆ', + 'ᄇ' => 'ᄇ', + 'ᄈ' => 'ᄈ', + 'ᄡ' => 'ᄡ', + 'ᄉ' => 'ᄉ', + 'ᄊ' => 'ᄊ', + 'ᄋ' => 'ᄋ', + 'ᄌ' => 'ᄌ', + 'ᄍ' => 'ᄍ', + 'ᄎ' => 'ᄎ', + 'ᄏ' => 'ᄏ', + 'ᄐ' => 'ᄐ', + 'ᄑ' => 'ᄑ', + 'ᄒ' => 'ᄒ', + 'ᅡ' => 'ᅡ', + 'ᅢ' => 'ᅢ', + 'ᅣ' => 'ᅣ', + 'ᅤ' => 'ᅤ', + 'ᅥ' => 'ᅥ', + 'ᅦ' => 'ᅦ', + 'ᅧ' => 'ᅧ', + 'ᅨ' => 'ᅨ', + 'ᅩ' => 'ᅩ', + 'ᅪ' => 'ᅪ', + 'ᅫ' => 'ᅫ', + 'ᅬ' => 'ᅬ', + 'ᅭ' => 'ᅭ', + 'ᅮ' => 'ᅮ', + 'ᅯ' => 'ᅯ', + 'ᅰ' => 'ᅰ', + 'ᅱ' => 'ᅱ', + 'ᅲ' => 'ᅲ', + 'ᅳ' => 'ᅳ', + 'ᅴ' => 'ᅴ', + 'ᅵ' => 'ᅵ', + '¢' => '¢', + '£' => '£', + '¬' => '¬', + ' ̄' => ' ̄', + '¦' => '¦', + '¥' => '¥', + '₩' => '₩', + '│' => '│', + '←' => '←', + '↑' => '↑', + '→' => '→', + '↓' => '↓', + '■' => '■', + '○' => '○', + '𝐀' => 'A', + '𝐁' => 'B', + '𝐂' => 'C', + '𝐃' => 'D', + '𝐄' => 'E', + '𝐅' => 'F', + '𝐆' => 'G', + '𝐇' => 'H', + '𝐈' => 'I', + '𝐉' => 'J', + '𝐊' => 'K', + '𝐋' => 'L', + '𝐌' => 'M', + '𝐍' => 'N', + '𝐎' => 'O', + '𝐏' => 'P', + '𝐐' => 'Q', + '𝐑' => 'R', + '𝐒' => 'S', + '𝐓' => 'T', + '𝐔' => 'U', + '𝐕' => 'V', + '𝐖' => 'W', + '𝐗' => 'X', + '𝐘' => 'Y', + '𝐙' => 'Z', + '𝐚' => 'a', + '𝐛' => 'b', + '𝐜' => 'c', + '𝐝' => 'd', + '𝐞' => 'e', + '𝐟' => 'f', + '𝐠' => 'g', + '𝐡' => 'h', + '𝐢' => 'i', + '𝐣' => 'j', + '𝐤' => 'k', + '𝐥' => 'l', + '𝐦' => 'm', + '𝐧' => 'n', + '𝐨' => 'o', + '𝐩' => 'p', + '𝐪' => 'q', + '𝐫' => 'r', + '𝐬' => 's', + '𝐭' => 't', + '𝐮' => 'u', + '𝐯' => 'v', + '𝐰' => 'w', + '𝐱' => 'x', + '𝐲' => 'y', + '𝐳' => 'z', + '𝐴' => 'A', + '𝐵' => 'B', + '𝐶' => 'C', + '𝐷' => 'D', + '𝐸' => 'E', + '𝐹' => 'F', + '𝐺' => 'G', + '𝐻' => 'H', + '𝐼' => 'I', + '𝐽' => 'J', + '𝐾' => 'K', + '𝐿' => 'L', + '𝑀' => 'M', + '𝑁' => 'N', + '𝑂' => 'O', + '𝑃' => 'P', + '𝑄' => 'Q', + '𝑅' => 'R', + '𝑆' => 'S', + '𝑇' => 'T', + '𝑈' => 'U', + '𝑉' => 'V', + '𝑊' => 'W', + '𝑋' => 'X', + '𝑌' => 'Y', + '𝑍' => 'Z', + '𝑎' => 'a', + '𝑏' => 'b', + '𝑐' => 'c', + '𝑑' => 'd', + '𝑒' => 'e', + '𝑓' => 'f', + '𝑔' => 'g', + '𝑖' => 'i', + '𝑗' => 'j', + '𝑘' => 'k', + '𝑙' => 'l', + '𝑚' => 'm', + '𝑛' => 'n', + '𝑜' => 'o', + '𝑝' => 'p', + '𝑞' => 'q', + '𝑟' => 'r', + '𝑠' => 's', + '𝑡' => 't', + '𝑢' => 'u', + '𝑣' => 'v', + '𝑤' => 'w', + '𝑥' => 'x', + '𝑦' => 'y', + '𝑧' => 'z', + '𝑨' => 'A', + '𝑩' => 'B', + '𝑪' => 'C', + '𝑫' => 'D', + '𝑬' => 'E', + '𝑭' => 'F', + '𝑮' => 'G', + '𝑯' => 'H', + '𝑰' => 'I', + '𝑱' => 'J', + '𝑲' => 'K', + '𝑳' => 'L', + '𝑴' => 'M', + '𝑵' => 'N', + '𝑶' => 'O', + '𝑷' => 'P', + '𝑸' => 'Q', + '𝑹' => 'R', + '𝑺' => 'S', + '𝑻' => 'T', + '𝑼' => 'U', + '𝑽' => 'V', + '𝑾' => 'W', + '𝑿' => 'X', + '𝒀' => 'Y', + '𝒁' => 'Z', + '𝒂' => 'a', + '𝒃' => 'b', + '𝒄' => 'c', + '𝒅' => 'd', + '𝒆' => 'e', + '𝒇' => 'f', + '𝒈' => 'g', + '𝒉' => 'h', + '𝒊' => 'i', + '𝒋' => 'j', + '𝒌' => 'k', + '𝒍' => 'l', + '𝒎' => 'm', + '𝒏' => 'n', + '𝒐' => 'o', + '𝒑' => 'p', + '𝒒' => 'q', + '𝒓' => 'r', + '𝒔' => 's', + '𝒕' => 't', + '𝒖' => 'u', + '𝒗' => 'v', + '𝒘' => 'w', + '𝒙' => 'x', + '𝒚' => 'y', + '𝒛' => 'z', + '𝒜' => 'A', + '𝒞' => 'C', + '𝒟' => 'D', + '𝒢' => 'G', + '𝒥' => 'J', + '𝒦' => 'K', + '𝒩' => 'N', + '𝒪' => 'O', + '𝒫' => 'P', + '𝒬' => 'Q', + '𝒮' => 'S', + '𝒯' => 'T', + '𝒰' => 'U', + '𝒱' => 'V', + '𝒲' => 'W', + '𝒳' => 'X', + '𝒴' => 'Y', + '𝒵' => 'Z', + '𝒶' => 'a', + '𝒷' => 'b', + '𝒸' => 'c', + '𝒹' => 'd', + '𝒻' => 'f', + '𝒽' => 'h', + '𝒾' => 'i', + '𝒿' => 'j', + '𝓀' => 'k', + '𝓁' => 'l', + '𝓂' => 'm', + '𝓃' => 'n', + '𝓅' => 'p', + '𝓆' => 'q', + '𝓇' => 'r', + '𝓈' => 's', + '𝓉' => 't', + '𝓊' => 'u', + '𝓋' => 'v', + '𝓌' => 'w', + '𝓍' => 'x', + '𝓎' => 'y', + '𝓏' => 'z', + '𝓐' => 'A', + '𝓑' => 'B', + '𝓒' => 'C', + '𝓓' => 'D', + '𝓔' => 'E', + '𝓕' => 'F', + '𝓖' => 'G', + '𝓗' => 'H', + '𝓘' => 'I', + '𝓙' => 'J', + '𝓚' => 'K', + '𝓛' => 'L', + '𝓜' => 'M', + '𝓝' => 'N', + '𝓞' => 'O', + '𝓟' => 'P', + '𝓠' => 'Q', + '𝓡' => 'R', + '𝓢' => 'S', + '𝓣' => 'T', + '𝓤' => 'U', + '𝓥' => 'V', + '𝓦' => 'W', + '𝓧' => 'X', + '𝓨' => 'Y', + '𝓩' => 'Z', + '𝓪' => 'a', + '𝓫' => 'b', + '𝓬' => 'c', + '𝓭' => 'd', + '𝓮' => 'e', + '𝓯' => 'f', + '𝓰' => 'g', + '𝓱' => 'h', + '𝓲' => 'i', + '𝓳' => 'j', + '𝓴' => 'k', + '𝓵' => 'l', + '𝓶' => 'm', + '𝓷' => 'n', + '𝓸' => 'o', + '𝓹' => 'p', + '𝓺' => 'q', + '𝓻' => 'r', + '𝓼' => 's', + '𝓽' => 't', + '𝓾' => 'u', + '𝓿' => 'v', + '𝔀' => 'w', + '𝔁' => 'x', + '𝔂' => 'y', + '𝔃' => 'z', + '𝔄' => 'A', + '𝔅' => 'B', + '𝔇' => 'D', + '𝔈' => 'E', + '𝔉' => 'F', + '𝔊' => 'G', + '𝔍' => 'J', + '𝔎' => 'K', + '𝔏' => 'L', + '𝔐' => 'M', + '𝔑' => 'N', + '𝔒' => 'O', + '𝔓' => 'P', + '𝔔' => 'Q', + '𝔖' => 'S', + '𝔗' => 'T', + '𝔘' => 'U', + '𝔙' => 'V', + '𝔚' => 'W', + '𝔛' => 'X', + '𝔜' => 'Y', + '𝔞' => 'a', + '𝔟' => 'b', + '𝔠' => 'c', + '𝔡' => 'd', + '𝔢' => 'e', + '𝔣' => 'f', + '𝔤' => 'g', + '𝔥' => 'h', + '𝔦' => 'i', + '𝔧' => 'j', + '𝔨' => 'k', + '𝔩' => 'l', + '𝔪' => 'm', + '𝔫' => 'n', + '𝔬' => 'o', + '𝔭' => 'p', + '𝔮' => 'q', + '𝔯' => 'r', + '𝔰' => 's', + '𝔱' => 't', + '𝔲' => 'u', + '𝔳' => 'v', + '𝔴' => 'w', + '𝔵' => 'x', + '𝔶' => 'y', + '𝔷' => 'z', + '𝔸' => 'A', + '𝔹' => 'B', + '𝔻' => 'D', + '𝔼' => 'E', + '𝔽' => 'F', + '𝔾' => 'G', + '𝕀' => 'I', + '𝕁' => 'J', + '𝕂' => 'K', + '𝕃' => 'L', + '𝕄' => 'M', + '𝕆' => 'O', + '𝕊' => 'S', + '𝕋' => 'T', + '𝕌' => 'U', + '𝕍' => 'V', + '𝕎' => 'W', + '𝕏' => 'X', + '𝕐' => 'Y', + '𝕒' => 'a', + '𝕓' => 'b', + '𝕔' => 'c', + '𝕕' => 'd', + '𝕖' => 'e', + '𝕗' => 'f', + '𝕘' => 'g', + '𝕙' => 'h', + '𝕚' => 'i', + '𝕛' => 'j', + '𝕜' => 'k', + '𝕝' => 'l', + '𝕞' => 'm', + '𝕟' => 'n', + '𝕠' => 'o', + '𝕡' => 'p', + '𝕢' => 'q', + '𝕣' => 'r', + '𝕤' => 's', + '𝕥' => 't', + '𝕦' => 'u', + '𝕧' => 'v', + '𝕨' => 'w', + '𝕩' => 'x', + '𝕪' => 'y', + '𝕫' => 'z', + '𝕬' => 'A', + '𝕭' => 'B', + '𝕮' => 'C', + '𝕯' => 'D', + '𝕰' => 'E', + '𝕱' => 'F', + '𝕲' => 'G', + '𝕳' => 'H', + '𝕴' => 'I', + '𝕵' => 'J', + '𝕶' => 'K', + '𝕷' => 'L', + '𝕸' => 'M', + '𝕹' => 'N', + '𝕺' => 'O', + '𝕻' => 'P', + '𝕼' => 'Q', + '𝕽' => 'R', + '𝕾' => 'S', + '𝕿' => 'T', + '𝖀' => 'U', + '𝖁' => 'V', + '𝖂' => 'W', + '𝖃' => 'X', + '𝖄' => 'Y', + '𝖅' => 'Z', + '𝖆' => 'a', + '𝖇' => 'b', + '𝖈' => 'c', + '𝖉' => 'd', + '𝖊' => 'e', + '𝖋' => 'f', + '𝖌' => 'g', + '𝖍' => 'h', + '𝖎' => 'i', + '𝖏' => 'j', + '𝖐' => 'k', + '𝖑' => 'l', + '𝖒' => 'm', + '𝖓' => 'n', + '𝖔' => 'o', + '𝖕' => 'p', + '𝖖' => 'q', + '𝖗' => 'r', + '𝖘' => 's', + '𝖙' => 't', + '𝖚' => 'u', + '𝖛' => 'v', + '𝖜' => 'w', + '𝖝' => 'x', + '𝖞' => 'y', + '𝖟' => 'z', + '𝖠' => 'A', + '𝖡' => 'B', + '𝖢' => 'C', + '𝖣' => 'D', + '𝖤' => 'E', + '𝖥' => 'F', + '𝖦' => 'G', + '𝖧' => 'H', + '𝖨' => 'I', + '𝖩' => 'J', + '𝖪' => 'K', + '𝖫' => 'L', + '𝖬' => 'M', + '𝖭' => 'N', + '𝖮' => 'O', + '𝖯' => 'P', + '𝖰' => 'Q', + '𝖱' => 'R', + '𝖲' => 'S', + '𝖳' => 'T', + '𝖴' => 'U', + '𝖵' => 'V', + '𝖶' => 'W', + '𝖷' => 'X', + '𝖸' => 'Y', + '𝖹' => 'Z', + '𝖺' => 'a', + '𝖻' => 'b', + '𝖼' => 'c', + '𝖽' => 'd', + '𝖾' => 'e', + '𝖿' => 'f', + '𝗀' => 'g', + '𝗁' => 'h', + '𝗂' => 'i', + '𝗃' => 'j', + '𝗄' => 'k', + '𝗅' => 'l', + '𝗆' => 'm', + '𝗇' => 'n', + '𝗈' => 'o', + '𝗉' => 'p', + '𝗊' => 'q', + '𝗋' => 'r', + '𝗌' => 's', + '𝗍' => 't', + '𝗎' => 'u', + '𝗏' => 'v', + '𝗐' => 'w', + '𝗑' => 'x', + '𝗒' => 'y', + '𝗓' => 'z', + '𝗔' => 'A', + '𝗕' => 'B', + '𝗖' => 'C', + '𝗗' => 'D', + '𝗘' => 'E', + '𝗙' => 'F', + '𝗚' => 'G', + '𝗛' => 'H', + '𝗜' => 'I', + '𝗝' => 'J', + '𝗞' => 'K', + '𝗟' => 'L', + '𝗠' => 'M', + '𝗡' => 'N', + '𝗢' => 'O', + '𝗣' => 'P', + '𝗤' => 'Q', + '𝗥' => 'R', + '𝗦' => 'S', + '𝗧' => 'T', + '𝗨' => 'U', + '𝗩' => 'V', + '𝗪' => 'W', + '𝗫' => 'X', + '𝗬' => 'Y', + '𝗭' => 'Z', + '𝗮' => 'a', + '𝗯' => 'b', + '𝗰' => 'c', + '𝗱' => 'd', + '𝗲' => 'e', + '𝗳' => 'f', + '𝗴' => 'g', + '𝗵' => 'h', + '𝗶' => 'i', + '𝗷' => 'j', + '𝗸' => 'k', + '𝗹' => 'l', + '𝗺' => 'm', + '𝗻' => 'n', + '𝗼' => 'o', + '𝗽' => 'p', + '𝗾' => 'q', + '𝗿' => 'r', + '𝘀' => 's', + '𝘁' => 't', + '𝘂' => 'u', + '𝘃' => 'v', + '𝘄' => 'w', + '𝘅' => 'x', + '𝘆' => 'y', + '𝘇' => 'z', + '𝘈' => 'A', + '𝘉' => 'B', + '𝘊' => 'C', + '𝘋' => 'D', + '𝘌' => 'E', + '𝘍' => 'F', + '𝘎' => 'G', + '𝘏' => 'H', + '𝘐' => 'I', + '𝘑' => 'J', + '𝘒' => 'K', + '𝘓' => 'L', + '𝘔' => 'M', + '𝘕' => 'N', + '𝘖' => 'O', + '𝘗' => 'P', + '𝘘' => 'Q', + '𝘙' => 'R', + '𝘚' => 'S', + '𝘛' => 'T', + '𝘜' => 'U', + '𝘝' => 'V', + '𝘞' => 'W', + '𝘟' => 'X', + '𝘠' => 'Y', + '𝘡' => 'Z', + '𝘢' => 'a', + '𝘣' => 'b', + '𝘤' => 'c', + '𝘥' => 'd', + '𝘦' => 'e', + '𝘧' => 'f', + '𝘨' => 'g', + '𝘩' => 'h', + '𝘪' => 'i', + '𝘫' => 'j', + '𝘬' => 'k', + '𝘭' => 'l', + '𝘮' => 'm', + '𝘯' => 'n', + '𝘰' => 'o', + '𝘱' => 'p', + '𝘲' => 'q', + '𝘳' => 'r', + '𝘴' => 's', + '𝘵' => 't', + '𝘶' => 'u', + '𝘷' => 'v', + '𝘸' => 'w', + '𝘹' => 'x', + '𝘺' => 'y', + '𝘻' => 'z', + '𝘼' => 'A', + '𝘽' => 'B', + '𝘾' => 'C', + '𝘿' => 'D', + '𝙀' => 'E', + '𝙁' => 'F', + '𝙂' => 'G', + '𝙃' => 'H', + '𝙄' => 'I', + '𝙅' => 'J', + '𝙆' => 'K', + '𝙇' => 'L', + '𝙈' => 'M', + '𝙉' => 'N', + '𝙊' => 'O', + '𝙋' => 'P', + '𝙌' => 'Q', + '𝙍' => 'R', + '𝙎' => 'S', + '𝙏' => 'T', + '𝙐' => 'U', + '𝙑' => 'V', + '𝙒' => 'W', + '𝙓' => 'X', + '𝙔' => 'Y', + '𝙕' => 'Z', + '𝙖' => 'a', + '𝙗' => 'b', + '𝙘' => 'c', + '𝙙' => 'd', + '𝙚' => 'e', + '𝙛' => 'f', + '𝙜' => 'g', + '𝙝' => 'h', + '𝙞' => 'i', + '𝙟' => 'j', + '𝙠' => 'k', + '𝙡' => 'l', + '𝙢' => 'm', + '𝙣' => 'n', + '𝙤' => 'o', + '𝙥' => 'p', + '𝙦' => 'q', + '𝙧' => 'r', + '𝙨' => 's', + '𝙩' => 't', + '𝙪' => 'u', + '𝙫' => 'v', + '𝙬' => 'w', + '𝙭' => 'x', + '𝙮' => 'y', + '𝙯' => 'z', + '𝙰' => 'A', + '𝙱' => 'B', + '𝙲' => 'C', + '𝙳' => 'D', + '𝙴' => 'E', + '𝙵' => 'F', + '𝙶' => 'G', + '𝙷' => 'H', + '𝙸' => 'I', + '𝙹' => 'J', + '𝙺' => 'K', + '𝙻' => 'L', + '𝙼' => 'M', + '𝙽' => 'N', + '𝙾' => 'O', + '𝙿' => 'P', + '𝚀' => 'Q', + '𝚁' => 'R', + '𝚂' => 'S', + '𝚃' => 'T', + '𝚄' => 'U', + '𝚅' => 'V', + '𝚆' => 'W', + '𝚇' => 'X', + '𝚈' => 'Y', + '𝚉' => 'Z', + '𝚊' => 'a', + '𝚋' => 'b', + '𝚌' => 'c', + '𝚍' => 'd', + '𝚎' => 'e', + '𝚏' => 'f', + '𝚐' => 'g', + '𝚑' => 'h', + '𝚒' => 'i', + '𝚓' => 'j', + '𝚔' => 'k', + '𝚕' => 'l', + '𝚖' => 'm', + '𝚗' => 'n', + '𝚘' => 'o', + '𝚙' => 'p', + '𝚚' => 'q', + '𝚛' => 'r', + '𝚜' => 's', + '𝚝' => 't', + '𝚞' => 'u', + '𝚟' => 'v', + '𝚠' => 'w', + '𝚡' => 'x', + '𝚢' => 'y', + '𝚣' => 'z', + '𝚤' => 'ı', + '𝚥' => 'ȷ', + '𝚨' => 'Α', + '𝚩' => 'Β', + '𝚪' => 'Γ', + '𝚫' => 'Δ', + '𝚬' => 'Ε', + '𝚭' => 'Ζ', + '𝚮' => 'Η', + '𝚯' => 'Θ', + '𝚰' => 'Ι', + '𝚱' => 'Κ', + '𝚲' => 'Λ', + '𝚳' => 'Μ', + '𝚴' => 'Ν', + '𝚵' => 'Ξ', + '𝚶' => 'Ο', + '𝚷' => 'Π', + '𝚸' => 'Ρ', + '𝚹' => 'Θ', + '𝚺' => 'Σ', + '𝚻' => 'Τ', + '𝚼' => 'Υ', + '𝚽' => 'Φ', + '𝚾' => 'Χ', + '𝚿' => 'Ψ', + '𝛀' => 'Ω', + '𝛁' => '∇', + '𝛂' => 'α', + '𝛃' => 'β', + '𝛄' => 'γ', + '𝛅' => 'δ', + '𝛆' => 'ε', + '𝛇' => 'ζ', + '𝛈' => 'η', + '𝛉' => 'θ', + '𝛊' => 'ι', + '𝛋' => 'κ', + '𝛌' => 'λ', + '𝛍' => 'μ', + '𝛎' => 'ν', + '𝛏' => 'ξ', + '𝛐' => 'ο', + '𝛑' => 'π', + '𝛒' => 'ρ', + '𝛓' => 'ς', + '𝛔' => 'σ', + '𝛕' => 'τ', + '𝛖' => 'υ', + '𝛗' => 'φ', + '𝛘' => 'χ', + '𝛙' => 'ψ', + '𝛚' => 'ω', + '𝛛' => '∂', + '𝛜' => 'ε', + '𝛝' => 'θ', + '𝛞' => 'κ', + '𝛟' => 'φ', + '𝛠' => 'ρ', + '𝛡' => 'π', + '𝛢' => 'Α', + '𝛣' => 'Β', + '𝛤' => 'Γ', + '𝛥' => 'Δ', + '𝛦' => 'Ε', + '𝛧' => 'Ζ', + '𝛨' => 'Η', + '𝛩' => 'Θ', + '𝛪' => 'Ι', + '𝛫' => 'Κ', + '𝛬' => 'Λ', + '𝛭' => 'Μ', + '𝛮' => 'Ν', + '𝛯' => 'Ξ', + '𝛰' => 'Ο', + '𝛱' => 'Π', + '𝛲' => 'Ρ', + '𝛳' => 'Θ', + '𝛴' => 'Σ', + '𝛵' => 'Τ', + '𝛶' => 'Υ', + '𝛷' => 'Φ', + '𝛸' => 'Χ', + '𝛹' => 'Ψ', + '𝛺' => 'Ω', + '𝛻' => '∇', + '𝛼' => 'α', + '𝛽' => 'β', + '𝛾' => 'γ', + '𝛿' => 'δ', + '𝜀' => 'ε', + '𝜁' => 'ζ', + '𝜂' => 'η', + '𝜃' => 'θ', + '𝜄' => 'ι', + '𝜅' => 'κ', + '𝜆' => 'λ', + '𝜇' => 'μ', + '𝜈' => 'ν', + '𝜉' => 'ξ', + '𝜊' => 'ο', + '𝜋' => 'π', + '𝜌' => 'ρ', + '𝜍' => 'ς', + '𝜎' => 'σ', + '𝜏' => 'τ', + '𝜐' => 'υ', + '𝜑' => 'φ', + '𝜒' => 'χ', + '𝜓' => 'ψ', + '𝜔' => 'ω', + '𝜕' => '∂', + '𝜖' => 'ε', + '𝜗' => 'θ', + '𝜘' => 'κ', + '𝜙' => 'φ', + '𝜚' => 'ρ', + '𝜛' => 'π', + '𝜜' => 'Α', + '𝜝' => 'Β', + '𝜞' => 'Γ', + '𝜟' => 'Δ', + '𝜠' => 'Ε', + '𝜡' => 'Ζ', + '𝜢' => 'Η', + '𝜣' => 'Θ', + '𝜤' => 'Ι', + '𝜥' => 'Κ', + '𝜦' => 'Λ', + '𝜧' => 'Μ', + '𝜨' => 'Ν', + '𝜩' => 'Ξ', + '𝜪' => 'Ο', + '𝜫' => 'Π', + '𝜬' => 'Ρ', + '𝜭' => 'Θ', + '𝜮' => 'Σ', + '𝜯' => 'Τ', + '𝜰' => 'Υ', + '𝜱' => 'Φ', + '𝜲' => 'Χ', + '𝜳' => 'Ψ', + '𝜴' => 'Ω', + '𝜵' => '∇', + '𝜶' => 'α', + '𝜷' => 'β', + '𝜸' => 'γ', + '𝜹' => 'δ', + '𝜺' => 'ε', + '𝜻' => 'ζ', + '𝜼' => 'η', + '𝜽' => 'θ', + '𝜾' => 'ι', + '𝜿' => 'κ', + '𝝀' => 'λ', + '𝝁' => 'μ', + '𝝂' => 'ν', + '𝝃' => 'ξ', + '𝝄' => 'ο', + '𝝅' => 'π', + '𝝆' => 'ρ', + '𝝇' => 'ς', + '𝝈' => 'σ', + '𝝉' => 'τ', + '𝝊' => 'υ', + '𝝋' => 'φ', + '𝝌' => 'χ', + '𝝍' => 'ψ', + '𝝎' => 'ω', + '𝝏' => '∂', + '𝝐' => 'ε', + '𝝑' => 'θ', + '𝝒' => 'κ', + '𝝓' => 'φ', + '𝝔' => 'ρ', + '𝝕' => 'π', + '𝝖' => 'Α', + '𝝗' => 'Β', + '𝝘' => 'Γ', + '𝝙' => 'Δ', + '𝝚' => 'Ε', + '𝝛' => 'Ζ', + '𝝜' => 'Η', + '𝝝' => 'Θ', + '𝝞' => 'Ι', + '𝝟' => 'Κ', + '𝝠' => 'Λ', + '𝝡' => 'Μ', + '𝝢' => 'Ν', + '𝝣' => 'Ξ', + '𝝤' => 'Ο', + '𝝥' => 'Π', + '𝝦' => 'Ρ', + '𝝧' => 'Θ', + '𝝨' => 'Σ', + '𝝩' => 'Τ', + '𝝪' => 'Υ', + '𝝫' => 'Φ', + '𝝬' => 'Χ', + '𝝭' => 'Ψ', + '𝝮' => 'Ω', + '𝝯' => '∇', + '𝝰' => 'α', + '𝝱' => 'β', + '𝝲' => 'γ', + '𝝳' => 'δ', + '𝝴' => 'ε', + '𝝵' => 'ζ', + '𝝶' => 'η', + '𝝷' => 'θ', + '𝝸' => 'ι', + '𝝹' => 'κ', + '𝝺' => 'λ', + '𝝻' => 'μ', + '𝝼' => 'ν', + '𝝽' => 'ξ', + '𝝾' => 'ο', + '𝝿' => 'π', + '𝞀' => 'ρ', + '𝞁' => 'ς', + '𝞂' => 'σ', + '𝞃' => 'τ', + '𝞄' => 'υ', + '𝞅' => 'φ', + '𝞆' => 'χ', + '𝞇' => 'ψ', + '𝞈' => 'ω', + '𝞉' => '∂', + '𝞊' => 'ε', + '𝞋' => 'θ', + '𝞌' => 'κ', + '𝞍' => 'φ', + '𝞎' => 'ρ', + '𝞏' => 'π', + '𝞐' => 'Α', + '𝞑' => 'Β', + '𝞒' => 'Γ', + '𝞓' => 'Δ', + '𝞔' => 'Ε', + '𝞕' => 'Ζ', + '𝞖' => 'Η', + '𝞗' => 'Θ', + '𝞘' => 'Ι', + '𝞙' => 'Κ', + '𝞚' => 'Λ', + '𝞛' => 'Μ', + '𝞜' => 'Ν', + '𝞝' => 'Ξ', + '𝞞' => 'Ο', + '𝞟' => 'Π', + '𝞠' => 'Ρ', + '𝞡' => 'Θ', + '𝞢' => 'Σ', + '𝞣' => 'Τ', + '𝞤' => 'Υ', + '𝞥' => 'Φ', + '𝞦' => 'Χ', + '𝞧' => 'Ψ', + '𝞨' => 'Ω', + '𝞩' => '∇', + '𝞪' => 'α', + '𝞫' => 'β', + '𝞬' => 'γ', + '𝞭' => 'δ', + '𝞮' => 'ε', + '𝞯' => 'ζ', + '𝞰' => 'η', + '𝞱' => 'θ', + '𝞲' => 'ι', + '𝞳' => 'κ', + '𝞴' => 'λ', + '𝞵' => 'μ', + '𝞶' => 'ν', + '𝞷' => 'ξ', + '𝞸' => 'ο', + '𝞹' => 'π', + '𝞺' => 'ρ', + '𝞻' => 'ς', + '𝞼' => 'σ', + '𝞽' => 'τ', + '𝞾' => 'υ', + '𝞿' => 'φ', + '𝟀' => 'χ', + '𝟁' => 'ψ', + '𝟂' => 'ω', + '𝟃' => '∂', + '𝟄' => 'ε', + '𝟅' => 'θ', + '𝟆' => 'κ', + '𝟇' => 'φ', + '𝟈' => 'ρ', + '𝟉' => 'π', + '𝟊' => 'Ϝ', + '𝟋' => 'ϝ', + '𝟎' => '0', + '𝟏' => '1', + '𝟐' => '2', + '𝟑' => '3', + '𝟒' => '4', + '𝟓' => '5', + '𝟔' => '6', + '𝟕' => '7', + '𝟖' => '8', + '𝟗' => '9', + '𝟘' => '0', + '𝟙' => '1', + '𝟚' => '2', + '𝟛' => '3', + '𝟜' => '4', + '𝟝' => '5', + '𝟞' => '6', + '𝟟' => '7', + '𝟠' => '8', + '𝟡' => '9', + '𝟢' => '0', + '𝟣' => '1', + '𝟤' => '2', + '𝟥' => '3', + '𝟦' => '4', + '𝟧' => '5', + '𝟨' => '6', + '𝟩' => '7', + '𝟪' => '8', + '𝟫' => '9', + '𝟬' => '0', + '𝟭' => '1', + '𝟮' => '2', + '𝟯' => '3', + '𝟰' => '4', + '𝟱' => '5', + '𝟲' => '6', + '𝟳' => '7', + '𝟴' => '8', + '𝟵' => '9', + '𝟶' => '0', + '𝟷' => '1', + '𝟸' => '2', + '𝟹' => '3', + '𝟺' => '4', + '𝟻' => '5', + '𝟼' => '6', + '𝟽' => '7', + '𝟾' => '8', + '𝟿' => '9', + '𞸀' => 'ا', + '𞸁' => 'ب', + '𞸂' => 'ج', + '𞸃' => 'د', + '𞸅' => 'و', + '𞸆' => 'ز', + '𞸇' => 'ح', + '𞸈' => 'ط', + '𞸉' => 'ي', + '𞸊' => 'ك', + '𞸋' => 'ل', + '𞸌' => 'م', + '𞸍' => 'ن', + '𞸎' => 'س', + '𞸏' => 'ع', + '𞸐' => 'ف', + '𞸑' => 'ص', + '𞸒' => 'ق', + '𞸓' => 'ر', + '𞸔' => 'ش', + '𞸕' => 'ت', + '𞸖' => 'ث', + '𞸗' => 'خ', + '𞸘' => 'ذ', + '𞸙' => 'ض', + '𞸚' => 'ظ', + '𞸛' => 'غ', + '𞸜' => 'ٮ', + '𞸝' => 'ں', + '𞸞' => 'ڡ', + '𞸟' => 'ٯ', + '𞸡' => 'ب', + '𞸢' => 'ج', + '𞸤' => 'ه', + '𞸧' => 'ح', + '𞸩' => 'ي', + '𞸪' => 'ك', + '𞸫' => 'ل', + '𞸬' => 'م', + '𞸭' => 'ن', + '𞸮' => 'س', + '𞸯' => 'ع', + '𞸰' => 'ف', + '𞸱' => 'ص', + '𞸲' => 'ق', + '𞸴' => 'ش', + '𞸵' => 'ت', + '𞸶' => 'ث', + '𞸷' => 'خ', + '𞸹' => 'ض', + '𞸻' => 'غ', + '𞹂' => 'ج', + '𞹇' => 'ح', + '𞹉' => 'ي', + '𞹋' => 'ل', + '𞹍' => 'ن', + '𞹎' => 'س', + '𞹏' => 'ع', + '𞹑' => 'ص', + '𞹒' => 'ق', + '𞹔' => 'ش', + '𞹗' => 'خ', + '𞹙' => 'ض', + '𞹛' => 'غ', + '𞹝' => 'ں', + '𞹟' => 'ٯ', + '𞹡' => 'ب', + '𞹢' => 'ج', + '𞹤' => 'ه', + '𞹧' => 'ح', + '𞹨' => 'ط', + '𞹩' => 'ي', + '𞹪' => 'ك', + '𞹬' => 'م', + '𞹭' => 'ن', + '𞹮' => 'س', + '𞹯' => 'ع', + '𞹰' => 'ف', + '𞹱' => 'ص', + '𞹲' => 'ق', + '𞹴' => 'ش', + '𞹵' => 'ت', + '𞹶' => 'ث', + '𞹷' => 'خ', + '𞹹' => 'ض', + '𞹺' => 'ظ', + '𞹻' => 'غ', + '𞹼' => 'ٮ', + '𞹾' => 'ڡ', + '𞺀' => 'ا', + '𞺁' => 'ب', + '𞺂' => 'ج', + '𞺃' => 'د', + '𞺄' => 'ه', + '𞺅' => 'و', + '𞺆' => 'ز', + '𞺇' => 'ح', + '𞺈' => 'ط', + '𞺉' => 'ي', + '𞺋' => 'ل', + '𞺌' => 'م', + '𞺍' => 'ن', + '𞺎' => 'س', + '𞺏' => 'ع', + '𞺐' => 'ف', + '𞺑' => 'ص', + '𞺒' => 'ق', + '𞺓' => 'ر', + '𞺔' => 'ش', + '𞺕' => 'ت', + '𞺖' => 'ث', + '𞺗' => 'خ', + '𞺘' => 'ذ', + '𞺙' => 'ض', + '𞺚' => 'ظ', + '𞺛' => 'غ', + '𞺡' => 'ب', + '𞺢' => 'ج', + '𞺣' => 'د', + '𞺥' => 'و', + '𞺦' => 'ز', + '𞺧' => 'ح', + '𞺨' => 'ط', + '𞺩' => 'ي', + '𞺫' => 'ل', + '𞺬' => 'م', + '𞺭' => 'ن', + '𞺮' => 'س', + '𞺯' => 'ع', + '𞺰' => 'ف', + '𞺱' => 'ص', + '𞺲' => 'ق', + '𞺳' => 'ر', + '𞺴' => 'ش', + '𞺵' => 'ت', + '𞺶' => 'ث', + '𞺷' => 'خ', + '𞺸' => 'ذ', + '𞺹' => 'ض', + '𞺺' => 'ظ', + '𞺻' => 'غ', + '🄀' => '0.', + '🄁' => '0,', + '🄂' => '1,', + '🄃' => '2,', + '🄄' => '3,', + '🄅' => '4,', + '🄆' => '5,', + '🄇' => '6,', + '🄈' => '7,', + '🄉' => '8,', + '🄊' => '9,', + '🄐' => '(A)', + '🄑' => '(B)', + '🄒' => '(C)', + '🄓' => '(D)', + '🄔' => '(E)', + '🄕' => '(F)', + '🄖' => '(G)', + '🄗' => '(H)', + '🄘' => '(I)', + '🄙' => '(J)', + '🄚' => '(K)', + '🄛' => '(L)', + '🄜' => '(M)', + '🄝' => '(N)', + '🄞' => '(O)', + '🄟' => '(P)', + '🄠' => '(Q)', + '🄡' => '(R)', + '🄢' => '(S)', + '🄣' => '(T)', + '🄤' => '(U)', + '🄥' => '(V)', + '🄦' => '(W)', + '🄧' => '(X)', + '🄨' => '(Y)', + '🄩' => '(Z)', + '🄪' => '〔S〕', + '🄫' => 'C', + '🄬' => 'R', + '🄭' => 'CD', + '🄮' => 'WZ', + '🄰' => 'A', + '🄱' => 'B', + '🄲' => 'C', + '🄳' => 'D', + '🄴' => 'E', + '🄵' => 'F', + '🄶' => 'G', + '🄷' => 'H', + '🄸' => 'I', + '🄹' => 'J', + '🄺' => 'K', + '🄻' => 'L', + '🄼' => 'M', + '🄽' => 'N', + '🄾' => 'O', + '🄿' => 'P', + '🅀' => 'Q', + '🅁' => 'R', + '🅂' => 'S', + '🅃' => 'T', + '🅄' => 'U', + '🅅' => 'V', + '🅆' => 'W', + '🅇' => 'X', + '🅈' => 'Y', + '🅉' => 'Z', + '🅊' => 'HV', + '🅋' => 'MV', + '🅌' => 'SD', + '🅍' => 'SS', + '🅎' => 'PPV', + '🅏' => 'WC', + '🅪' => 'MC', + '🅫' => 'MD', + '🅬' => 'MR', + '🆐' => 'DJ', + '🈀' => 'ほか', + '🈁' => 'ココ', + '🈂' => 'サ', + '🈐' => '手', + '🈑' => '字', + '🈒' => '双', + '🈓' => 'デ', + '🈔' => '二', + '🈕' => '多', + '🈖' => '解', + '🈗' => '天', + '🈘' => '交', + '🈙' => '映', + '🈚' => '無', + '🈛' => '料', + '🈜' => '前', + '🈝' => '後', + '🈞' => '再', + '🈟' => '新', + '🈠' => '初', + '🈡' => '終', + '🈢' => '生', + '🈣' => '販', + '🈤' => '声', + '🈥' => '吹', + '🈦' => '演', + '🈧' => '投', + '🈨' => '捕', + '🈩' => '一', + '🈪' => '三', + '🈫' => '遊', + '🈬' => '左', + '🈭' => '中', + '🈮' => '右', + '🈯' => '指', + '🈰' => '走', + '🈱' => '打', + '🈲' => '禁', + '🈳' => '空', + '🈴' => '合', + '🈵' => '満', + '🈶' => '有', + '🈷' => '月', + '🈸' => '申', + '🈹' => '割', + '🈺' => '営', + '🈻' => '配', + '🉀' => '〔本〕', + '🉁' => '〔三〕', + '🉂' => '〔二〕', + '🉃' => '〔安〕', + '🉄' => '〔点〕', + '🉅' => '〔打〕', + '🉆' => '〔盗〕', + '🉇' => '〔勝〕', + '🉈' => '〔敗〕', + '🉐' => '得', + '🉑' => '可', + '🯰' => '0', + '🯱' => '1', + '🯲' => '2', + '🯳' => '3', + '🯴' => '4', + '🯵' => '5', + '🯶' => '6', + '🯷' => '7', + '🯸' => '8', + '🯹' => '9', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/bootstrap.php new file mode 100644 index 0000000..3608e5c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/bootstrap.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Normalizer as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('normalizer_is_normalized')) { + function normalizer_is_normalized($string, $form = p\Normalizer::FORM_C) { return p\Normalizer::isNormalized($string, $form); } +} +if (!function_exists('normalizer_normalize')) { + function normalizer_normalize($string, $form = p\Normalizer::FORM_C) { return p\Normalizer::normalize($string, $form); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/bootstrap80.php b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/bootstrap80.php new file mode 100644 index 0000000..e36d1a9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/bootstrap80.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Normalizer as p; + +if (!function_exists('normalizer_is_normalized')) { + function normalizer_is_normalized(?string $string, ?int $form = p\Normalizer::FORM_C): bool { return p\Normalizer::isNormalized((string) $string, (int) $form); } +} +if (!function_exists('normalizer_normalize')) { + function normalizer_normalize(?string $string, ?int $form = p\Normalizer::FORM_C): string|false { return p\Normalizer::normalize((string) $string, (int) $form); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/composer.json b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/composer.json new file mode 100644 index 0000000..1b93573 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-intl-normalizer/composer.json @@ -0,0 +1,36 @@ +{ + "name": "symfony/polyfill-intl-normalizer", + "type": "library", + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "keywords": ["polyfill", "shim", "compatibility", "portable", "intl", "normalizer"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Intl\\Normalizer\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "suggest": { + "ext-intl": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-mbstring/LICENSE new file mode 100644 index 0000000..6e3afce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/Mbstring.php b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Mbstring.php new file mode 100644 index 0000000..2e0b969 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Mbstring.php @@ -0,0 +1,947 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Mbstring; + +/** + * Partial mbstring implementation in PHP, iconv based, UTF-8 centric. + * + * Implemented: + * - mb_chr - Returns a specific character from its Unicode code point + * - mb_convert_encoding - Convert character encoding + * - mb_convert_variables - Convert character code in variable(s) + * - mb_decode_mimeheader - Decode string in MIME header field + * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED + * - mb_decode_numericentity - Decode HTML numeric string reference to character + * - mb_encode_numericentity - Encode character to HTML numeric string reference + * - mb_convert_case - Perform case folding on a string + * - mb_detect_encoding - Detect character encoding + * - mb_get_info - Get internal settings of mbstring + * - mb_http_input - Detect HTTP input character encoding + * - mb_http_output - Set/Get HTTP output character encoding + * - mb_internal_encoding - Set/Get internal character encoding + * - mb_list_encodings - Returns an array of all supported encodings + * - mb_ord - Returns the Unicode code point of a character + * - mb_output_handler - Callback function converts character encoding in output buffer + * - mb_scrub - Replaces ill-formed byte sequences with substitute characters + * - mb_strlen - Get string length + * - mb_strpos - Find position of first occurrence of string in a string + * - mb_strrpos - Find position of last occurrence of a string in a string + * - mb_str_split - Convert a string to an array + * - mb_strtolower - Make a string lowercase + * - mb_strtoupper - Make a string uppercase + * - mb_substitute_character - Set/Get substitution character + * - mb_substr - Get part of string + * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive + * - mb_stristr - Finds first occurrence of a string within another, case insensitive + * - mb_strrchr - Finds the last occurrence of a character in a string within another + * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive + * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive + * - mb_strstr - Finds first occurrence of a string within another + * - mb_strwidth - Return width of string + * - mb_substr_count - Count the number of substring occurrences + * + * Not implemented: + * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more) + * - mb_ereg_* - Regular expression with multibyte support + * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable + * - mb_preferred_mime_name - Get MIME charset string + * - mb_regex_encoding - Returns current encoding for multibyte regex as string + * - mb_regex_set_options - Set/Get the default options for mbregex functions + * - mb_send_mail - Send encoded mail + * - mb_split - Split multibyte string using regular expression + * - mb_strcut - Get part of string + * - mb_strimwidth - Get truncated string with specified width + * + * @author Nicolas Grekas + * + * @internal + */ +final class Mbstring +{ + public const MB_CASE_FOLD = \PHP_INT_MAX; + + private const SIMPLE_CASE_FOLD = [ + ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], + ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], + ]; + + private static $encodingList = ['ASCII', 'UTF-8']; + private static $language = 'neutral'; + private static $internalEncoding = 'UTF-8'; + + public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) + { + if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) { + $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); + } else { + $fromEncoding = self::getEncoding($fromEncoding); + } + + $toEncoding = self::getEncoding($toEncoding); + + if ('BASE64' === $fromEncoding) { + $s = base64_decode($s); + $fromEncoding = $toEncoding; + } + + if ('BASE64' === $toEncoding) { + return base64_encode($s); + } + + if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) { + if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) { + $fromEncoding = 'Windows-1252'; + } + if ('UTF-8' !== $fromEncoding) { + $s = iconv($fromEncoding, 'UTF-8//IGNORE', $s); + } + + return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s); + } + + if ('HTML-ENTITIES' === $fromEncoding) { + $s = html_entity_decode($s, \ENT_COMPAT, 'UTF-8'); + $fromEncoding = 'UTF-8'; + } + + return iconv($fromEncoding, $toEncoding.'//IGNORE', $s); + } + + public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars) + { + $ok = true; + array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) { + if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) { + $ok = false; + } + }); + + return $ok ? $fromEncoding : false; + } + + public static function mb_decode_mimeheader($s) + { + return iconv_mime_decode($s, 2, self::$internalEncoding); + } + + public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) + { + trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING); + } + + public static function mb_decode_numericentity($s, $convmap, $encoding = null) + { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !\is_scalar($encoding)) { + trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return ''; // Instead of null (cf. mb_encode_numericentity). + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + $cnt = floor(\count($convmap) / 4) * 4; + + for ($i = 0; $i < $cnt; $i += 4) { + // collector_decode_htmlnumericentity ignores $convmap[$i + 3] + $convmap[$i] += $convmap[$i + 2]; + $convmap[$i + 1] += $convmap[$i + 2]; + } + + $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) { + $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1]; + for ($i = 0; $i < $cnt; $i += 4) { + if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) { + return self::mb_chr($c - $convmap[$i + 2]); + } + } + + return $m[0]; + }, $s); + + if (null === $encoding) { + return $s; + } + + return iconv('UTF-8', $encoding.'//IGNORE', $s); + } + + public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) + { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !\is_scalar($encoding)) { + trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; // Instead of '' (cf. mb_decode_numericentity). + } + + if (null !== $is_hex && !\is_scalar($is_hex)) { + trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $cnt = floor(\count($convmap) / 4) * 4; + $i = 0; + $len = \strlen($s); + $result = ''; + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + $c = self::mb_ord($uchr); + + for ($j = 0; $j < $cnt; $j += 4) { + if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) { + $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3]; + $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';'; + continue 2; + } + } + $result .= $uchr; + } + + if (null === $encoding) { + return $result; + } + + return iconv('UTF-8', $encoding.'//IGNORE', $result); + } + + public static function mb_convert_case($s, $mode, $encoding = null) + { + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + if (\MB_CASE_TITLE == $mode) { + static $titleRegexp = null; + if (null === $titleRegexp) { + $titleRegexp = self::getData('titleCaseRegexp'); + } + $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s); + } else { + if (\MB_CASE_UPPER == $mode) { + static $upper = null; + if (null === $upper) { + $upper = self::getData('upperCase'); + } + $map = $upper; + } else { + if (self::MB_CASE_FOLD === $mode) { + static $caseFolding = null; + if (null === $caseFolding) { + $caseFolding = self::getData('caseFolding'); + } + $s = strtr($s, $caseFolding); + } + + static $lower = null; + if (null === $lower) { + $lower = self::getData('lowerCase'); + } + $map = $lower; + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $i = 0; + $len = \strlen($s); + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + if (isset($map[$uchr])) { + $uchr = $map[$uchr]; + $nlen = \strlen($uchr); + + if ($nlen == $ulen) { + $nlen = $i; + do { + $s[--$nlen] = $uchr[--$ulen]; + } while ($ulen); + } else { + $s = substr_replace($s, $uchr, $i - $ulen, $ulen); + $len += $nlen - $ulen; + $i += $nlen - $ulen; + } + } + } + } + + if (null === $encoding) { + return $s; + } + + return iconv('UTF-8', $encoding.'//IGNORE', $s); + } + + public static function mb_internal_encoding($encoding = null) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + $normalizedEncoding = self::getEncoding($encoding); + + if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) { + self::$internalEncoding = $normalizedEncoding; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + public static function mb_language($lang = null) + { + if (null === $lang) { + return self::$language; + } + + switch ($normalizedLang = strtolower($lang)) { + case 'uni': + case 'neutral': + self::$language = $normalizedLang; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang)); + } + + public static function mb_list_encodings() + { + return ['UTF-8']; + } + + public static function mb_encoding_aliases($encoding) + { + switch (strtoupper($encoding)) { + case 'UTF8': + case 'UTF-8': + return ['utf8']; + } + + return false; + } + + public static function mb_check_encoding($var = null, $encoding = null) + { + if (PHP_VERSION_ID < 70200 && \is_array($var)) { + trigger_error('mb_check_encoding() expects parameter 1 to be string, array given', \E_USER_WARNING); + + return null; + } + + if (null === $encoding) { + if (null === $var) { + return false; + } + $encoding = self::$internalEncoding; + } + + if (!\is_array($var)) { + return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var); + } + + foreach ($var as $key => $value) { + if (!self::mb_check_encoding($key, $encoding)) { + return false; + } + if (!self::mb_check_encoding($value, $encoding)) { + return false; + } + } + + return true; + + } + + public static function mb_detect_encoding($str, $encodingList = null, $strict = false) + { + if (null === $encodingList) { + $encodingList = self::$encodingList; + } else { + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + } + + foreach ($encodingList as $enc) { + switch ($enc) { + case 'ASCII': + if (!preg_match('/[\x80-\xFF]/', $str)) { + return $enc; + } + break; + + case 'UTF8': + case 'UTF-8': + if (preg_match('//u', $str)) { + return 'UTF-8'; + } + break; + + default: + if (0 === strncmp($enc, 'ISO-8859-', 9)) { + return $enc; + } + } + } + + return false; + } + + public static function mb_detect_order($encodingList = null) + { + if (null === $encodingList) { + return self::$encodingList; + } + + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + + foreach ($encodingList as $enc) { + switch ($enc) { + default: + if (strncmp($enc, 'ISO-8859-', 9)) { + return false; + } + // no break + case 'ASCII': + case 'UTF8': + case 'UTF-8': + } + } + + self::$encodingList = $encodingList; + + return true; + } + + public static function mb_strlen($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return \strlen($s); + } + + return @iconv_strlen($s, $encoding); + } + + public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return strpos($haystack, $needle, $offset); + } + + $needle = (string) $needle; + if ('' === $needle) { + if (80000 > \PHP_VERSION_ID) { + trigger_error(__METHOD__.': Empty delimiter', \E_USER_WARNING); + + return false; + } + + return 0; + } + + return iconv_strpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return strrpos($haystack, $needle, $offset); + } + + if ($offset != (int) $offset) { + $offset = 0; + } elseif ($offset = (int) $offset) { + if ($offset < 0) { + if (0 > $offset += self::mb_strlen($needle)) { + $haystack = self::mb_substr($haystack, 0, $offset, $encoding); + } + $offset = 0; + } else { + $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding); + } + } + + $pos = '' !== $needle || 80000 > \PHP_VERSION_ID + ? iconv_strrpos($haystack, $needle, $encoding) + : self::mb_strlen($haystack, $encoding); + + return false !== $pos ? $offset + $pos : false; + } + + public static function mb_str_split($string, $split_length = 1, $encoding = null) + { + if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { + trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING); + + return null; + } + + if (1 > $split_length = (int) $split_length) { + if (80000 > \PHP_VERSION_ID) { + trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('Argument #2 ($length) must be greater than 0'); + } + + if (null === $encoding) { + $encoding = mb_internal_encoding(); + } + + if ('UTF-8' === $encoding = self::getEncoding($encoding)) { + $rx = '/('; + while (65535 < $split_length) { + $rx .= '.{65535}'; + $split_length -= 65535; + } + $rx .= '.{'.$split_length.'})/us'; + + return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + } + + $result = []; + $length = mb_strlen($string, $encoding); + + for ($i = 0; $i < $length; $i += $split_length) { + $result[] = mb_substr($string, $i, $split_length, $encoding); + } + + return $result; + } + + public static function mb_strtolower($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding); + } + + public static function mb_strtoupper($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding); + } + + public static function mb_substitute_character($c = null) + { + if (null === $c) { + return 'none'; + } + if (0 === strcasecmp($c, 'none')) { + return true; + } + if (80000 > \PHP_VERSION_ID) { + return false; + } + if (\is_int($c) || 'long' === $c || 'entity' === $c) { + return false; + } + + throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint'); + } + + public static function mb_substr($s, $start, $length = null, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return (string) substr($s, $start, null === $length ? 2147483647 : $length); + } + + if ($start < 0) { + $start = iconv_strlen($s, $encoding) + $start; + if ($start < 0) { + $start = 0; + } + } + + if (null === $length) { + $length = 2147483647; + } elseif ($length < 0) { + $length = iconv_strlen($s, $encoding) + $length - $start; + if ($length < 0) { + return ''; + } + } + + return (string) iconv_substr($s, $start, $length, $encoding); + } + + public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) + { + [$haystack, $needle] = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], [ + self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding), + self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding), + ]); + + return self::mb_strpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_stristr($haystack, $needle, $part = false, $encoding = null) + { + $pos = self::mb_stripos($haystack, $needle, 0, $encoding); + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + $pos = strrpos($haystack, $needle); + } else { + $needle = self::mb_substr($needle, 0, 1, $encoding); + $pos = iconv_strrpos($haystack, $needle, $encoding); + } + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null) + { + $needle = self::mb_substr($needle, 0, 1, $encoding); + $pos = self::mb_strripos($haystack, $needle, $encoding); + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) + { + $haystack = self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding); + $needle = self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding); + + $haystack = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $haystack); + $needle = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $needle); + + return self::mb_strrpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_strstr($haystack, $needle, $part = false, $encoding = null) + { + $pos = strpos($haystack, $needle); + if (false === $pos) { + return false; + } + if ($part) { + return substr($haystack, 0, $pos); + } + + return substr($haystack, $pos); + } + + public static function mb_get_info($type = 'all') + { + $info = [ + 'internal_encoding' => self::$internalEncoding, + 'http_output' => 'pass', + 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)', + 'func_overload' => 0, + 'func_overload_list' => 'no overload', + 'mail_charset' => 'UTF-8', + 'mail_header_encoding' => 'BASE64', + 'mail_body_encoding' => 'BASE64', + 'illegal_chars' => 0, + 'encoding_translation' => 'Off', + 'language' => self::$language, + 'detect_order' => self::$encodingList, + 'substitute_character' => 'none', + 'strict_detection' => 'Off', + ]; + + if ('all' === $type) { + return $info; + } + if (isset($info[$type])) { + return $info[$type]; + } + + return false; + } + + public static function mb_http_input($type = '') + { + return false; + } + + public static function mb_http_output($encoding = null) + { + return null !== $encoding ? 'pass' === $encoding : 'pass'; + } + + public static function mb_strwidth($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + + if ('UTF-8' !== $encoding) { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide); + + return ($wide << 1) + iconv_strlen($s, 'UTF-8'); + } + + public static function mb_substr_count($haystack, $needle, $encoding = null) + { + return substr_count($haystack, $needle); + } + + public static function mb_output_handler($contents, $status) + { + return $contents; + } + + public static function mb_chr($code, $encoding = null) + { + if (0x80 > $code %= 0x200000) { + $s = \chr($code); + } elseif (0x800 > $code) { + $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, $encoding, 'UTF-8'); + } + + return $s; + } + + public static function mb_ord($s, $encoding = null) + { + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, 'UTF-8', $encoding); + } + + if (1 === \strlen($s)) { + return \ord($s); + } + + $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; + if (0xF0 <= $code) { + return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; + } + if (0xE0 <= $code) { + return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; + } + if (0xC0 <= $code) { + return (($code - 0xC0) << 6) + $s[2] - 0x80; + } + + return $code; + } + + public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, string $encoding = null): string + { + if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) { + throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH'); + } + + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } + + try { + $validEncoding = @self::mb_check_encoding('', $encoding); + } catch (\ValueError $e) { + throw new \ValueError(sprintf('mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + // BC for PHP 7.3 and lower + if (!$validEncoding) { + throw new \ValueError(sprintf('mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + if (self::mb_strlen($pad_string, $encoding) <= 0) { + throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string'); + } + + $paddingRequired = $length - self::mb_strlen($string, $encoding); + + if ($paddingRequired < 1) { + return $string; + } + + switch ($pad_type) { + case \STR_PAD_LEFT: + return self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding).$string; + case \STR_PAD_RIGHT: + return $string.self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding); + default: + $leftPaddingLength = floor($paddingRequired / 2); + $rightPaddingLength = $paddingRequired - $leftPaddingLength; + + return self::mb_substr(str_repeat($pad_string, $leftPaddingLength), 0, $leftPaddingLength, $encoding).$string.self::mb_substr(str_repeat($pad_string, $rightPaddingLength), 0, $rightPaddingLength, $encoding); + } + } + + private static function getSubpart($pos, $part, $haystack, $encoding) + { + if (false === $pos) { + return false; + } + if ($part) { + return self::mb_substr($haystack, 0, $pos, $encoding); + } + + return self::mb_substr($haystack, $pos, null, $encoding); + } + + private static function html_encoding_callback(array $m) + { + $i = 1; + $entities = ''; + $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8')); + + while (isset($m[$i])) { + if (0x80 > $m[$i]) { + $entities .= \chr($m[$i++]); + continue; + } + if (0xF0 <= $m[$i]) { + $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } elseif (0xE0 <= $m[$i]) { + $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } else { + $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80; + } + + $entities .= '&#'.$c.';'; + } + + return $entities; + } + + private static function title_case(array $s) + { + return self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8'); + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { + return require $file; + } + + return false; + } + + private static function getEncoding($encoding) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + if ('UTF-8' === $encoding) { + return 'UTF-8'; + } + + $encoding = strtoupper($encoding); + + if ('8BIT' === $encoding || 'BINARY' === $encoding) { + return 'CP850'; + } + + if ('UTF8' === $encoding) { + return 'UTF-8'; + } + + return $encoding; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/README.md b/php/libraries/composer/vendor/symfony/polyfill-mbstring/README.md new file mode 100644 index 0000000..478b40d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/README.md @@ -0,0 +1,13 @@ +Symfony Polyfill / Mbstring +=========================== + +This component provides a partial, native PHP implementation for the +[Mbstring](https://php.net/mbstring) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php new file mode 100644 index 0000000..512bba0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php @@ -0,0 +1,119 @@ + 'i̇', + 'µ' => 'μ', + 'ſ' => 's', + 'ͅ' => 'ι', + 'ς' => 'σ', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϵ' => 'ε', + 'ẛ' => 'ṡ', + 'ι' => 'ι', + 'ß' => 'ss', + 'ʼn' => 'ʼn', + 'ǰ' => 'ǰ', + 'ΐ' => 'ΐ', + 'ΰ' => 'ΰ', + 'և' => 'եւ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẚ' => 'aʾ', + 'ẞ' => 'ss', + 'ὐ' => 'ὐ', + 'ὒ' => 'ὒ', + 'ὔ' => 'ὔ', + 'ὖ' => 'ὖ', + 'ᾀ' => 'ἀι', + 'ᾁ' => 'ἁι', + 'ᾂ' => 'ἂι', + 'ᾃ' => 'ἃι', + 'ᾄ' => 'ἄι', + 'ᾅ' => 'ἅι', + 'ᾆ' => 'ἆι', + 'ᾇ' => 'ἇι', + 'ᾈ' => 'ἀι', + 'ᾉ' => 'ἁι', + 'ᾊ' => 'ἂι', + 'ᾋ' => 'ἃι', + 'ᾌ' => 'ἄι', + 'ᾍ' => 'ἅι', + 'ᾎ' => 'ἆι', + 'ᾏ' => 'ἇι', + 'ᾐ' => 'ἠι', + 'ᾑ' => 'ἡι', + 'ᾒ' => 'ἢι', + 'ᾓ' => 'ἣι', + 'ᾔ' => 'ἤι', + 'ᾕ' => 'ἥι', + 'ᾖ' => 'ἦι', + 'ᾗ' => 'ἧι', + 'ᾘ' => 'ἠι', + 'ᾙ' => 'ἡι', + 'ᾚ' => 'ἢι', + 'ᾛ' => 'ἣι', + 'ᾜ' => 'ἤι', + 'ᾝ' => 'ἥι', + 'ᾞ' => 'ἦι', + 'ᾟ' => 'ἧι', + 'ᾠ' => 'ὠι', + 'ᾡ' => 'ὡι', + 'ᾢ' => 'ὢι', + 'ᾣ' => 'ὣι', + 'ᾤ' => 'ὤι', + 'ᾥ' => 'ὥι', + 'ᾦ' => 'ὦι', + 'ᾧ' => 'ὧι', + 'ᾨ' => 'ὠι', + 'ᾩ' => 'ὡι', + 'ᾪ' => 'ὢι', + 'ᾫ' => 'ὣι', + 'ᾬ' => 'ὤι', + 'ᾭ' => 'ὥι', + 'ᾮ' => 'ὦι', + 'ᾯ' => 'ὧι', + 'ᾲ' => 'ὰι', + 'ᾳ' => 'αι', + 'ᾴ' => 'άι', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾶι', + 'ᾼ' => 'αι', + 'ῂ' => 'ὴι', + 'ῃ' => 'ηι', + 'ῄ' => 'ήι', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῆι', + 'ῌ' => 'ηι', + 'ῒ' => 'ῒ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'ῢ' => 'ῢ', + 'ῤ' => 'ῤ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'ῲ' => 'ὼι', + 'ῳ' => 'ωι', + 'ῴ' => 'ώι', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῶι', + 'ῼ' => 'ωι', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'st', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', +]; diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php new file mode 100644 index 0000000..fac60b0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php @@ -0,0 +1,1397 @@ + 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + 'À' => 'à', + 'Á' => 'á', + 'Â' => 'â', + 'Ã' => 'ã', + 'Ä' => 'ä', + 'Å' => 'å', + 'Æ' => 'æ', + 'Ç' => 'ç', + 'È' => 'è', + 'É' => 'é', + 'Ê' => 'ê', + 'Ë' => 'ë', + 'Ì' => 'ì', + 'Í' => 'í', + 'Î' => 'î', + 'Ï' => 'ï', + 'Ð' => 'ð', + 'Ñ' => 'ñ', + 'Ò' => 'ò', + 'Ó' => 'ó', + 'Ô' => 'ô', + 'Õ' => 'õ', + 'Ö' => 'ö', + 'Ø' => 'ø', + 'Ù' => 'ù', + 'Ú' => 'ú', + 'Û' => 'û', + 'Ü' => 'ü', + 'Ý' => 'ý', + 'Þ' => 'þ', + 'Ā' => 'ā', + 'Ă' => 'ă', + 'Ą' => 'ą', + 'Ć' => 'ć', + 'Ĉ' => 'ĉ', + 'Ċ' => 'ċ', + 'Č' => 'č', + 'Ď' => 'ď', + 'Đ' => 'đ', + 'Ē' => 'ē', + 'Ĕ' => 'ĕ', + 'Ė' => 'ė', + 'Ę' => 'ę', + 'Ě' => 'ě', + 'Ĝ' => 'ĝ', + 'Ğ' => 'ğ', + 'Ġ' => 'ġ', + 'Ģ' => 'ģ', + 'Ĥ' => 'ĥ', + 'Ħ' => 'ħ', + 'Ĩ' => 'ĩ', + 'Ī' => 'ī', + 'Ĭ' => 'ĭ', + 'Į' => 'į', + 'İ' => 'i̇', + 'IJ' => 'ij', + 'Ĵ' => 'ĵ', + 'Ķ' => 'ķ', + 'Ĺ' => 'ĺ', + 'Ļ' => 'ļ', + 'Ľ' => 'ľ', + 'Ŀ' => 'ŀ', + 'Ł' => 'ł', + 'Ń' => 'ń', + 'Ņ' => 'ņ', + 'Ň' => 'ň', + 'Ŋ' => 'ŋ', + 'Ō' => 'ō', + 'Ŏ' => 'ŏ', + 'Ő' => 'ő', + 'Œ' => 'œ', + 'Ŕ' => 'ŕ', + 'Ŗ' => 'ŗ', + 'Ř' => 'ř', + 'Ś' => 'ś', + 'Ŝ' => 'ŝ', + 'Ş' => 'ş', + 'Š' => 'š', + 'Ţ' => 'ţ', + 'Ť' => 'ť', + 'Ŧ' => 'ŧ', + 'Ũ' => 'ũ', + 'Ū' => 'ū', + 'Ŭ' => 'ŭ', + 'Ů' => 'ů', + 'Ű' => 'ű', + 'Ų' => 'ų', + 'Ŵ' => 'ŵ', + 'Ŷ' => 'ŷ', + 'Ÿ' => 'ÿ', + 'Ź' => 'ź', + 'Ż' => 'ż', + 'Ž' => 'ž', + 'Ɓ' => 'ɓ', + 'Ƃ' => 'ƃ', + 'Ƅ' => 'ƅ', + 'Ɔ' => 'ɔ', + 'Ƈ' => 'ƈ', + 'Ɖ' => 'ɖ', + 'Ɗ' => 'ɗ', + 'Ƌ' => 'ƌ', + 'Ǝ' => 'ǝ', + 'Ə' => 'ə', + 'Ɛ' => 'ɛ', + 'Ƒ' => 'ƒ', + 'Ɠ' => 'ɠ', + 'Ɣ' => 'ɣ', + 'Ɩ' => 'ɩ', + 'Ɨ' => 'ɨ', + 'Ƙ' => 'ƙ', + 'Ɯ' => 'ɯ', + 'Ɲ' => 'ɲ', + 'Ɵ' => 'ɵ', + 'Ơ' => 'ơ', + 'Ƣ' => 'ƣ', + 'Ƥ' => 'ƥ', + 'Ʀ' => 'ʀ', + 'Ƨ' => 'ƨ', + 'Ʃ' => 'ʃ', + 'Ƭ' => 'ƭ', + 'Ʈ' => 'ʈ', + 'Ư' => 'ư', + 'Ʊ' => 'ʊ', + 'Ʋ' => 'ʋ', + 'Ƴ' => 'ƴ', + 'Ƶ' => 'ƶ', + 'Ʒ' => 'ʒ', + 'Ƹ' => 'ƹ', + 'Ƽ' => 'ƽ', + 'DŽ' => 'dž', + 'Dž' => 'dž', + 'LJ' => 'lj', + 'Lj' => 'lj', + 'NJ' => 'nj', + 'Nj' => 'nj', + 'Ǎ' => 'ǎ', + 'Ǐ' => 'ǐ', + 'Ǒ' => 'ǒ', + 'Ǔ' => 'ǔ', + 'Ǖ' => 'ǖ', + 'Ǘ' => 'ǘ', + 'Ǚ' => 'ǚ', + 'Ǜ' => 'ǜ', + 'Ǟ' => 'ǟ', + 'Ǡ' => 'ǡ', + 'Ǣ' => 'ǣ', + 'Ǥ' => 'ǥ', + 'Ǧ' => 'ǧ', + 'Ǩ' => 'ǩ', + 'Ǫ' => 'ǫ', + 'Ǭ' => 'ǭ', + 'Ǯ' => 'ǯ', + 'DZ' => 'dz', + 'Dz' => 'dz', + 'Ǵ' => 'ǵ', + 'Ƕ' => 'ƕ', + 'Ƿ' => 'ƿ', + 'Ǹ' => 'ǹ', + 'Ǻ' => 'ǻ', + 'Ǽ' => 'ǽ', + 'Ǿ' => 'ǿ', + 'Ȁ' => 'ȁ', + 'Ȃ' => 'ȃ', + 'Ȅ' => 'ȅ', + 'Ȇ' => 'ȇ', + 'Ȉ' => 'ȉ', + 'Ȋ' => 'ȋ', + 'Ȍ' => 'ȍ', + 'Ȏ' => 'ȏ', + 'Ȑ' => 'ȑ', + 'Ȓ' => 'ȓ', + 'Ȕ' => 'ȕ', + 'Ȗ' => 'ȗ', + 'Ș' => 'ș', + 'Ț' => 'ț', + 'Ȝ' => 'ȝ', + 'Ȟ' => 'ȟ', + 'Ƞ' => 'ƞ', + 'Ȣ' => 'ȣ', + 'Ȥ' => 'ȥ', + 'Ȧ' => 'ȧ', + 'Ȩ' => 'ȩ', + 'Ȫ' => 'ȫ', + 'Ȭ' => 'ȭ', + 'Ȯ' => 'ȯ', + 'Ȱ' => 'ȱ', + 'Ȳ' => 'ȳ', + 'Ⱥ' => 'ⱥ', + 'Ȼ' => 'ȼ', + 'Ƚ' => 'ƚ', + 'Ⱦ' => 'ⱦ', + 'Ɂ' => 'ɂ', + 'Ƀ' => 'ƀ', + 'Ʉ' => 'ʉ', + 'Ʌ' => 'ʌ', + 'Ɇ' => 'ɇ', + 'Ɉ' => 'ɉ', + 'Ɋ' => 'ɋ', + 'Ɍ' => 'ɍ', + 'Ɏ' => 'ɏ', + 'Ͱ' => 'ͱ', + 'Ͳ' => 'ͳ', + 'Ͷ' => 'ͷ', + 'Ϳ' => 'ϳ', + 'Ά' => 'ά', + 'Έ' => 'έ', + 'Ή' => 'ή', + 'Ί' => 'ί', + 'Ό' => 'ό', + 'Ύ' => 'ύ', + 'Ώ' => 'ώ', + 'Α' => 'α', + 'Β' => 'β', + 'Γ' => 'γ', + 'Δ' => 'δ', + 'Ε' => 'ε', + 'Ζ' => 'ζ', + 'Η' => 'η', + 'Θ' => 'θ', + 'Ι' => 'ι', + 'Κ' => 'κ', + 'Λ' => 'λ', + 'Μ' => 'μ', + 'Ν' => 'ν', + 'Ξ' => 'ξ', + 'Ο' => 'ο', + 'Π' => 'π', + 'Ρ' => 'ρ', + 'Σ' => 'σ', + 'Τ' => 'τ', + 'Υ' => 'υ', + 'Φ' => 'φ', + 'Χ' => 'χ', + 'Ψ' => 'ψ', + 'Ω' => 'ω', + 'Ϊ' => 'ϊ', + 'Ϋ' => 'ϋ', + 'Ϗ' => 'ϗ', + 'Ϙ' => 'ϙ', + 'Ϛ' => 'ϛ', + 'Ϝ' => 'ϝ', + 'Ϟ' => 'ϟ', + 'Ϡ' => 'ϡ', + 'Ϣ' => 'ϣ', + 'Ϥ' => 'ϥ', + 'Ϧ' => 'ϧ', + 'Ϩ' => 'ϩ', + 'Ϫ' => 'ϫ', + 'Ϭ' => 'ϭ', + 'Ϯ' => 'ϯ', + 'ϴ' => 'θ', + 'Ϸ' => 'ϸ', + 'Ϲ' => 'ϲ', + 'Ϻ' => 'ϻ', + 'Ͻ' => 'ͻ', + 'Ͼ' => 'ͼ', + 'Ͽ' => 'ͽ', + 'Ѐ' => 'ѐ', + 'Ё' => 'ё', + 'Ђ' => 'ђ', + 'Ѓ' => 'ѓ', + 'Є' => 'є', + 'Ѕ' => 'ѕ', + 'І' => 'і', + 'Ї' => 'ї', + 'Ј' => 'ј', + 'Љ' => 'љ', + 'Њ' => 'њ', + 'Ћ' => 'ћ', + 'Ќ' => 'ќ', + 'Ѝ' => 'ѝ', + 'Ў' => 'ў', + 'Џ' => 'џ', + 'А' => 'а', + 'Б' => 'б', + 'В' => 'в', + 'Г' => 'г', + 'Д' => 'д', + 'Е' => 'е', + 'Ж' => 'ж', + 'З' => 'з', + 'И' => 'и', + 'Й' => 'й', + 'К' => 'к', + 'Л' => 'л', + 'М' => 'м', + 'Н' => 'н', + 'О' => 'о', + 'П' => 'п', + 'Р' => 'р', + 'С' => 'с', + 'Т' => 'т', + 'У' => 'у', + 'Ф' => 'ф', + 'Х' => 'х', + 'Ц' => 'ц', + 'Ч' => 'ч', + 'Ш' => 'ш', + 'Щ' => 'щ', + 'Ъ' => 'ъ', + 'Ы' => 'ы', + 'Ь' => 'ь', + 'Э' => 'э', + 'Ю' => 'ю', + 'Я' => 'я', + 'Ѡ' => 'ѡ', + 'Ѣ' => 'ѣ', + 'Ѥ' => 'ѥ', + 'Ѧ' => 'ѧ', + 'Ѩ' => 'ѩ', + 'Ѫ' => 'ѫ', + 'Ѭ' => 'ѭ', + 'Ѯ' => 'ѯ', + 'Ѱ' => 'ѱ', + 'Ѳ' => 'ѳ', + 'Ѵ' => 'ѵ', + 'Ѷ' => 'ѷ', + 'Ѹ' => 'ѹ', + 'Ѻ' => 'ѻ', + 'Ѽ' => 'ѽ', + 'Ѿ' => 'ѿ', + 'Ҁ' => 'ҁ', + 'Ҋ' => 'ҋ', + 'Ҍ' => 'ҍ', + 'Ҏ' => 'ҏ', + 'Ґ' => 'ґ', + 'Ғ' => 'ғ', + 'Ҕ' => 'ҕ', + 'Җ' => 'җ', + 'Ҙ' => 'ҙ', + 'Қ' => 'қ', + 'Ҝ' => 'ҝ', + 'Ҟ' => 'ҟ', + 'Ҡ' => 'ҡ', + 'Ң' => 'ң', + 'Ҥ' => 'ҥ', + 'Ҧ' => 'ҧ', + 'Ҩ' => 'ҩ', + 'Ҫ' => 'ҫ', + 'Ҭ' => 'ҭ', + 'Ү' => 'ү', + 'Ұ' => 'ұ', + 'Ҳ' => 'ҳ', + 'Ҵ' => 'ҵ', + 'Ҷ' => 'ҷ', + 'Ҹ' => 'ҹ', + 'Һ' => 'һ', + 'Ҽ' => 'ҽ', + 'Ҿ' => 'ҿ', + 'Ӏ' => 'ӏ', + 'Ӂ' => 'ӂ', + 'Ӄ' => 'ӄ', + 'Ӆ' => 'ӆ', + 'Ӈ' => 'ӈ', + 'Ӊ' => 'ӊ', + 'Ӌ' => 'ӌ', + 'Ӎ' => 'ӎ', + 'Ӑ' => 'ӑ', + 'Ӓ' => 'ӓ', + 'Ӕ' => 'ӕ', + 'Ӗ' => 'ӗ', + 'Ә' => 'ә', + 'Ӛ' => 'ӛ', + 'Ӝ' => 'ӝ', + 'Ӟ' => 'ӟ', + 'Ӡ' => 'ӡ', + 'Ӣ' => 'ӣ', + 'Ӥ' => 'ӥ', + 'Ӧ' => 'ӧ', + 'Ө' => 'ө', + 'Ӫ' => 'ӫ', + 'Ӭ' => 'ӭ', + 'Ӯ' => 'ӯ', + 'Ӱ' => 'ӱ', + 'Ӳ' => 'ӳ', + 'Ӵ' => 'ӵ', + 'Ӷ' => 'ӷ', + 'Ӹ' => 'ӹ', + 'Ӻ' => 'ӻ', + 'Ӽ' => 'ӽ', + 'Ӿ' => 'ӿ', + 'Ԁ' => 'ԁ', + 'Ԃ' => 'ԃ', + 'Ԅ' => 'ԅ', + 'Ԇ' => 'ԇ', + 'Ԉ' => 'ԉ', + 'Ԋ' => 'ԋ', + 'Ԍ' => 'ԍ', + 'Ԏ' => 'ԏ', + 'Ԑ' => 'ԑ', + 'Ԓ' => 'ԓ', + 'Ԕ' => 'ԕ', + 'Ԗ' => 'ԗ', + 'Ԙ' => 'ԙ', + 'Ԛ' => 'ԛ', + 'Ԝ' => 'ԝ', + 'Ԟ' => 'ԟ', + 'Ԡ' => 'ԡ', + 'Ԣ' => 'ԣ', + 'Ԥ' => 'ԥ', + 'Ԧ' => 'ԧ', + 'Ԩ' => 'ԩ', + 'Ԫ' => 'ԫ', + 'Ԭ' => 'ԭ', + 'Ԯ' => 'ԯ', + 'Ա' => 'ա', + 'Բ' => 'բ', + 'Գ' => 'գ', + 'Դ' => 'դ', + 'Ե' => 'ե', + 'Զ' => 'զ', + 'Է' => 'է', + 'Ը' => 'ը', + 'Թ' => 'թ', + 'Ժ' => 'ժ', + 'Ի' => 'ի', + 'Լ' => 'լ', + 'Խ' => 'խ', + 'Ծ' => 'ծ', + 'Կ' => 'կ', + 'Հ' => 'հ', + 'Ձ' => 'ձ', + 'Ղ' => 'ղ', + 'Ճ' => 'ճ', + 'Մ' => 'մ', + 'Յ' => 'յ', + 'Ն' => 'ն', + 'Շ' => 'շ', + 'Ո' => 'ո', + 'Չ' => 'չ', + 'Պ' => 'պ', + 'Ջ' => 'ջ', + 'Ռ' => 'ռ', + 'Ս' => 'ս', + 'Վ' => 'վ', + 'Տ' => 'տ', + 'Ր' => 'ր', + 'Ց' => 'ց', + 'Ւ' => 'ւ', + 'Փ' => 'փ', + 'Ք' => 'ք', + 'Օ' => 'օ', + 'Ֆ' => 'ֆ', + 'Ⴀ' => 'ⴀ', + 'Ⴁ' => 'ⴁ', + 'Ⴂ' => 'ⴂ', + 'Ⴃ' => 'ⴃ', + 'Ⴄ' => 'ⴄ', + 'Ⴅ' => 'ⴅ', + 'Ⴆ' => 'ⴆ', + 'Ⴇ' => 'ⴇ', + 'Ⴈ' => 'ⴈ', + 'Ⴉ' => 'ⴉ', + 'Ⴊ' => 'ⴊ', + 'Ⴋ' => 'ⴋ', + 'Ⴌ' => 'ⴌ', + 'Ⴍ' => 'ⴍ', + 'Ⴎ' => 'ⴎ', + 'Ⴏ' => 'ⴏ', + 'Ⴐ' => 'ⴐ', + 'Ⴑ' => 'ⴑ', + 'Ⴒ' => 'ⴒ', + 'Ⴓ' => 'ⴓ', + 'Ⴔ' => 'ⴔ', + 'Ⴕ' => 'ⴕ', + 'Ⴖ' => 'ⴖ', + 'Ⴗ' => 'ⴗ', + 'Ⴘ' => 'ⴘ', + 'Ⴙ' => 'ⴙ', + 'Ⴚ' => 'ⴚ', + 'Ⴛ' => 'ⴛ', + 'Ⴜ' => 'ⴜ', + 'Ⴝ' => 'ⴝ', + 'Ⴞ' => 'ⴞ', + 'Ⴟ' => 'ⴟ', + 'Ⴠ' => 'ⴠ', + 'Ⴡ' => 'ⴡ', + 'Ⴢ' => 'ⴢ', + 'Ⴣ' => 'ⴣ', + 'Ⴤ' => 'ⴤ', + 'Ⴥ' => 'ⴥ', + 'Ⴧ' => 'ⴧ', + 'Ⴭ' => 'ⴭ', + 'Ꭰ' => 'ꭰ', + 'Ꭱ' => 'ꭱ', + 'Ꭲ' => 'ꭲ', + 'Ꭳ' => 'ꭳ', + 'Ꭴ' => 'ꭴ', + 'Ꭵ' => 'ꭵ', + 'Ꭶ' => 'ꭶ', + 'Ꭷ' => 'ꭷ', + 'Ꭸ' => 'ꭸ', + 'Ꭹ' => 'ꭹ', + 'Ꭺ' => 'ꭺ', + 'Ꭻ' => 'ꭻ', + 'Ꭼ' => 'ꭼ', + 'Ꭽ' => 'ꭽ', + 'Ꭾ' => 'ꭾ', + 'Ꭿ' => 'ꭿ', + 'Ꮀ' => 'ꮀ', + 'Ꮁ' => 'ꮁ', + 'Ꮂ' => 'ꮂ', + 'Ꮃ' => 'ꮃ', + 'Ꮄ' => 'ꮄ', + 'Ꮅ' => 'ꮅ', + 'Ꮆ' => 'ꮆ', + 'Ꮇ' => 'ꮇ', + 'Ꮈ' => 'ꮈ', + 'Ꮉ' => 'ꮉ', + 'Ꮊ' => 'ꮊ', + 'Ꮋ' => 'ꮋ', + 'Ꮌ' => 'ꮌ', + 'Ꮍ' => 'ꮍ', + 'Ꮎ' => 'ꮎ', + 'Ꮏ' => 'ꮏ', + 'Ꮐ' => 'ꮐ', + 'Ꮑ' => 'ꮑ', + 'Ꮒ' => 'ꮒ', + 'Ꮓ' => 'ꮓ', + 'Ꮔ' => 'ꮔ', + 'Ꮕ' => 'ꮕ', + 'Ꮖ' => 'ꮖ', + 'Ꮗ' => 'ꮗ', + 'Ꮘ' => 'ꮘ', + 'Ꮙ' => 'ꮙ', + 'Ꮚ' => 'ꮚ', + 'Ꮛ' => 'ꮛ', + 'Ꮜ' => 'ꮜ', + 'Ꮝ' => 'ꮝ', + 'Ꮞ' => 'ꮞ', + 'Ꮟ' => 'ꮟ', + 'Ꮠ' => 'ꮠ', + 'Ꮡ' => 'ꮡ', + 'Ꮢ' => 'ꮢ', + 'Ꮣ' => 'ꮣ', + 'Ꮤ' => 'ꮤ', + 'Ꮥ' => 'ꮥ', + 'Ꮦ' => 'ꮦ', + 'Ꮧ' => 'ꮧ', + 'Ꮨ' => 'ꮨ', + 'Ꮩ' => 'ꮩ', + 'Ꮪ' => 'ꮪ', + 'Ꮫ' => 'ꮫ', + 'Ꮬ' => 'ꮬ', + 'Ꮭ' => 'ꮭ', + 'Ꮮ' => 'ꮮ', + 'Ꮯ' => 'ꮯ', + 'Ꮰ' => 'ꮰ', + 'Ꮱ' => 'ꮱ', + 'Ꮲ' => 'ꮲ', + 'Ꮳ' => 'ꮳ', + 'Ꮴ' => 'ꮴ', + 'Ꮵ' => 'ꮵ', + 'Ꮶ' => 'ꮶ', + 'Ꮷ' => 'ꮷ', + 'Ꮸ' => 'ꮸ', + 'Ꮹ' => 'ꮹ', + 'Ꮺ' => 'ꮺ', + 'Ꮻ' => 'ꮻ', + 'Ꮼ' => 'ꮼ', + 'Ꮽ' => 'ꮽ', + 'Ꮾ' => 'ꮾ', + 'Ꮿ' => 'ꮿ', + 'Ᏸ' => 'ᏸ', + 'Ᏹ' => 'ᏹ', + 'Ᏺ' => 'ᏺ', + 'Ᏻ' => 'ᏻ', + 'Ᏼ' => 'ᏼ', + 'Ᏽ' => 'ᏽ', + 'Ა' => 'ა', + 'Ბ' => 'ბ', + 'Გ' => 'გ', + 'Დ' => 'დ', + 'Ე' => 'ე', + 'Ვ' => 'ვ', + 'Ზ' => 'ზ', + 'Თ' => 'თ', + 'Ი' => 'ი', + 'Კ' => 'კ', + 'Ლ' => 'ლ', + 'Მ' => 'მ', + 'Ნ' => 'ნ', + 'Ო' => 'ო', + 'Პ' => 'პ', + 'Ჟ' => 'ჟ', + 'Რ' => 'რ', + 'Ს' => 'ს', + 'Ტ' => 'ტ', + 'Უ' => 'უ', + 'Ფ' => 'ფ', + 'Ქ' => 'ქ', + 'Ღ' => 'ღ', + 'Ყ' => 'ყ', + 'Შ' => 'შ', + 'Ჩ' => 'ჩ', + 'Ც' => 'ც', + 'Ძ' => 'ძ', + 'Წ' => 'წ', + 'Ჭ' => 'ჭ', + 'Ხ' => 'ხ', + 'Ჯ' => 'ჯ', + 'Ჰ' => 'ჰ', + 'Ჱ' => 'ჱ', + 'Ჲ' => 'ჲ', + 'Ჳ' => 'ჳ', + 'Ჴ' => 'ჴ', + 'Ჵ' => 'ჵ', + 'Ჶ' => 'ჶ', + 'Ჷ' => 'ჷ', + 'Ჸ' => 'ჸ', + 'Ჹ' => 'ჹ', + 'Ჺ' => 'ჺ', + 'Ჽ' => 'ჽ', + 'Ჾ' => 'ჾ', + 'Ჿ' => 'ჿ', + 'Ḁ' => 'ḁ', + 'Ḃ' => 'ḃ', + 'Ḅ' => 'ḅ', + 'Ḇ' => 'ḇ', + 'Ḉ' => 'ḉ', + 'Ḋ' => 'ḋ', + 'Ḍ' => 'ḍ', + 'Ḏ' => 'ḏ', + 'Ḑ' => 'ḑ', + 'Ḓ' => 'ḓ', + 'Ḕ' => 'ḕ', + 'Ḗ' => 'ḗ', + 'Ḙ' => 'ḙ', + 'Ḛ' => 'ḛ', + 'Ḝ' => 'ḝ', + 'Ḟ' => 'ḟ', + 'Ḡ' => 'ḡ', + 'Ḣ' => 'ḣ', + 'Ḥ' => 'ḥ', + 'Ḧ' => 'ḧ', + 'Ḩ' => 'ḩ', + 'Ḫ' => 'ḫ', + 'Ḭ' => 'ḭ', + 'Ḯ' => 'ḯ', + 'Ḱ' => 'ḱ', + 'Ḳ' => 'ḳ', + 'Ḵ' => 'ḵ', + 'Ḷ' => 'ḷ', + 'Ḹ' => 'ḹ', + 'Ḻ' => 'ḻ', + 'Ḽ' => 'ḽ', + 'Ḿ' => 'ḿ', + 'Ṁ' => 'ṁ', + 'Ṃ' => 'ṃ', + 'Ṅ' => 'ṅ', + 'Ṇ' => 'ṇ', + 'Ṉ' => 'ṉ', + 'Ṋ' => 'ṋ', + 'Ṍ' => 'ṍ', + 'Ṏ' => 'ṏ', + 'Ṑ' => 'ṑ', + 'Ṓ' => 'ṓ', + 'Ṕ' => 'ṕ', + 'Ṗ' => 'ṗ', + 'Ṙ' => 'ṙ', + 'Ṛ' => 'ṛ', + 'Ṝ' => 'ṝ', + 'Ṟ' => 'ṟ', + 'Ṡ' => 'ṡ', + 'Ṣ' => 'ṣ', + 'Ṥ' => 'ṥ', + 'Ṧ' => 'ṧ', + 'Ṩ' => 'ṩ', + 'Ṫ' => 'ṫ', + 'Ṭ' => 'ṭ', + 'Ṯ' => 'ṯ', + 'Ṱ' => 'ṱ', + 'Ṳ' => 'ṳ', + 'Ṵ' => 'ṵ', + 'Ṷ' => 'ṷ', + 'Ṹ' => 'ṹ', + 'Ṻ' => 'ṻ', + 'Ṽ' => 'ṽ', + 'Ṿ' => 'ṿ', + 'Ẁ' => 'ẁ', + 'Ẃ' => 'ẃ', + 'Ẅ' => 'ẅ', + 'Ẇ' => 'ẇ', + 'Ẉ' => 'ẉ', + 'Ẋ' => 'ẋ', + 'Ẍ' => 'ẍ', + 'Ẏ' => 'ẏ', + 'Ẑ' => 'ẑ', + 'Ẓ' => 'ẓ', + 'Ẕ' => 'ẕ', + 'ẞ' => 'ß', + 'Ạ' => 'ạ', + 'Ả' => 'ả', + 'Ấ' => 'ấ', + 'Ầ' => 'ầ', + 'Ẩ' => 'ẩ', + 'Ẫ' => 'ẫ', + 'Ậ' => 'ậ', + 'Ắ' => 'ắ', + 'Ằ' => 'ằ', + 'Ẳ' => 'ẳ', + 'Ẵ' => 'ẵ', + 'Ặ' => 'ặ', + 'Ẹ' => 'ẹ', + 'Ẻ' => 'ẻ', + 'Ẽ' => 'ẽ', + 'Ế' => 'ế', + 'Ề' => 'ề', + 'Ể' => 'ể', + 'Ễ' => 'ễ', + 'Ệ' => 'ệ', + 'Ỉ' => 'ỉ', + 'Ị' => 'ị', + 'Ọ' => 'ọ', + 'Ỏ' => 'ỏ', + 'Ố' => 'ố', + 'Ồ' => 'ồ', + 'Ổ' => 'ổ', + 'Ỗ' => 'ỗ', + 'Ộ' => 'ộ', + 'Ớ' => 'ớ', + 'Ờ' => 'ờ', + 'Ở' => 'ở', + 'Ỡ' => 'ỡ', + 'Ợ' => 'ợ', + 'Ụ' => 'ụ', + 'Ủ' => 'ủ', + 'Ứ' => 'ứ', + 'Ừ' => 'ừ', + 'Ử' => 'ử', + 'Ữ' => 'ữ', + 'Ự' => 'ự', + 'Ỳ' => 'ỳ', + 'Ỵ' => 'ỵ', + 'Ỷ' => 'ỷ', + 'Ỹ' => 'ỹ', + 'Ỻ' => 'ỻ', + 'Ỽ' => 'ỽ', + 'Ỿ' => 'ỿ', + 'Ἀ' => 'ἀ', + 'Ἁ' => 'ἁ', + 'Ἂ' => 'ἂ', + 'Ἃ' => 'ἃ', + 'Ἄ' => 'ἄ', + 'Ἅ' => 'ἅ', + 'Ἆ' => 'ἆ', + 'Ἇ' => 'ἇ', + 'Ἐ' => 'ἐ', + 'Ἑ' => 'ἑ', + 'Ἒ' => 'ἒ', + 'Ἓ' => 'ἓ', + 'Ἔ' => 'ἔ', + 'Ἕ' => 'ἕ', + 'Ἠ' => 'ἠ', + 'Ἡ' => 'ἡ', + 'Ἢ' => 'ἢ', + 'Ἣ' => 'ἣ', + 'Ἤ' => 'ἤ', + 'Ἥ' => 'ἥ', + 'Ἦ' => 'ἦ', + 'Ἧ' => 'ἧ', + 'Ἰ' => 'ἰ', + 'Ἱ' => 'ἱ', + 'Ἲ' => 'ἲ', + 'Ἳ' => 'ἳ', + 'Ἴ' => 'ἴ', + 'Ἵ' => 'ἵ', + 'Ἶ' => 'ἶ', + 'Ἷ' => 'ἷ', + 'Ὀ' => 'ὀ', + 'Ὁ' => 'ὁ', + 'Ὂ' => 'ὂ', + 'Ὃ' => 'ὃ', + 'Ὄ' => 'ὄ', + 'Ὅ' => 'ὅ', + 'Ὑ' => 'ὑ', + 'Ὓ' => 'ὓ', + 'Ὕ' => 'ὕ', + 'Ὗ' => 'ὗ', + 'Ὠ' => 'ὠ', + 'Ὡ' => 'ὡ', + 'Ὢ' => 'ὢ', + 'Ὣ' => 'ὣ', + 'Ὤ' => 'ὤ', + 'Ὥ' => 'ὥ', + 'Ὦ' => 'ὦ', + 'Ὧ' => 'ὧ', + 'ᾈ' => 'ᾀ', + 'ᾉ' => 'ᾁ', + 'ᾊ' => 'ᾂ', + 'ᾋ' => 'ᾃ', + 'ᾌ' => 'ᾄ', + 'ᾍ' => 'ᾅ', + 'ᾎ' => 'ᾆ', + 'ᾏ' => 'ᾇ', + 'ᾘ' => 'ᾐ', + 'ᾙ' => 'ᾑ', + 'ᾚ' => 'ᾒ', + 'ᾛ' => 'ᾓ', + 'ᾜ' => 'ᾔ', + 'ᾝ' => 'ᾕ', + 'ᾞ' => 'ᾖ', + 'ᾟ' => 'ᾗ', + 'ᾨ' => 'ᾠ', + 'ᾩ' => 'ᾡ', + 'ᾪ' => 'ᾢ', + 'ᾫ' => 'ᾣ', + 'ᾬ' => 'ᾤ', + 'ᾭ' => 'ᾥ', + 'ᾮ' => 'ᾦ', + 'ᾯ' => 'ᾧ', + 'Ᾰ' => 'ᾰ', + 'Ᾱ' => 'ᾱ', + 'Ὰ' => 'ὰ', + 'Ά' => 'ά', + 'ᾼ' => 'ᾳ', + 'Ὲ' => 'ὲ', + 'Έ' => 'έ', + 'Ὴ' => 'ὴ', + 'Ή' => 'ή', + 'ῌ' => 'ῃ', + 'Ῐ' => 'ῐ', + 'Ῑ' => 'ῑ', + 'Ὶ' => 'ὶ', + 'Ί' => 'ί', + 'Ῠ' => 'ῠ', + 'Ῡ' => 'ῡ', + 'Ὺ' => 'ὺ', + 'Ύ' => 'ύ', + 'Ῥ' => 'ῥ', + 'Ὸ' => 'ὸ', + 'Ό' => 'ό', + 'Ὼ' => 'ὼ', + 'Ώ' => 'ώ', + 'ῼ' => 'ῳ', + 'Ω' => 'ω', + 'K' => 'k', + 'Å' => 'å', + 'Ⅎ' => 'ⅎ', + 'Ⅰ' => 'ⅰ', + 'Ⅱ' => 'ⅱ', + 'Ⅲ' => 'ⅲ', + 'Ⅳ' => 'ⅳ', + 'Ⅴ' => 'ⅴ', + 'Ⅵ' => 'ⅵ', + 'Ⅶ' => 'ⅶ', + 'Ⅷ' => 'ⅷ', + 'Ⅸ' => 'ⅸ', + 'Ⅹ' => 'ⅹ', + 'Ⅺ' => 'ⅺ', + 'Ⅻ' => 'ⅻ', + 'Ⅼ' => 'ⅼ', + 'Ⅽ' => 'ⅽ', + 'Ⅾ' => 'ⅾ', + 'Ⅿ' => 'ⅿ', + 'Ↄ' => 'ↄ', + 'Ⓐ' => 'ⓐ', + 'Ⓑ' => 'ⓑ', + 'Ⓒ' => 'ⓒ', + 'Ⓓ' => 'ⓓ', + 'Ⓔ' => 'ⓔ', + 'Ⓕ' => 'ⓕ', + 'Ⓖ' => 'ⓖ', + 'Ⓗ' => 'ⓗ', + 'Ⓘ' => 'ⓘ', + 'Ⓙ' => 'ⓙ', + 'Ⓚ' => 'ⓚ', + 'Ⓛ' => 'ⓛ', + 'Ⓜ' => 'ⓜ', + 'Ⓝ' => 'ⓝ', + 'Ⓞ' => 'ⓞ', + 'Ⓟ' => 'ⓟ', + 'Ⓠ' => 'ⓠ', + 'Ⓡ' => 'ⓡ', + 'Ⓢ' => 'ⓢ', + 'Ⓣ' => 'ⓣ', + 'Ⓤ' => 'ⓤ', + 'Ⓥ' => 'ⓥ', + 'Ⓦ' => 'ⓦ', + 'Ⓧ' => 'ⓧ', + 'Ⓨ' => 'ⓨ', + 'Ⓩ' => 'ⓩ', + 'Ⰰ' => 'ⰰ', + 'Ⰱ' => 'ⰱ', + 'Ⰲ' => 'ⰲ', + 'Ⰳ' => 'ⰳ', + 'Ⰴ' => 'ⰴ', + 'Ⰵ' => 'ⰵ', + 'Ⰶ' => 'ⰶ', + 'Ⰷ' => 'ⰷ', + 'Ⰸ' => 'ⰸ', + 'Ⰹ' => 'ⰹ', + 'Ⰺ' => 'ⰺ', + 'Ⰻ' => 'ⰻ', + 'Ⰼ' => 'ⰼ', + 'Ⰽ' => 'ⰽ', + 'Ⰾ' => 'ⰾ', + 'Ⰿ' => 'ⰿ', + 'Ⱀ' => 'ⱀ', + 'Ⱁ' => 'ⱁ', + 'Ⱂ' => 'ⱂ', + 'Ⱃ' => 'ⱃ', + 'Ⱄ' => 'ⱄ', + 'Ⱅ' => 'ⱅ', + 'Ⱆ' => 'ⱆ', + 'Ⱇ' => 'ⱇ', + 'Ⱈ' => 'ⱈ', + 'Ⱉ' => 'ⱉ', + 'Ⱊ' => 'ⱊ', + 'Ⱋ' => 'ⱋ', + 'Ⱌ' => 'ⱌ', + 'Ⱍ' => 'ⱍ', + 'Ⱎ' => 'ⱎ', + 'Ⱏ' => 'ⱏ', + 'Ⱐ' => 'ⱐ', + 'Ⱑ' => 'ⱑ', + 'Ⱒ' => 'ⱒ', + 'Ⱓ' => 'ⱓ', + 'Ⱔ' => 'ⱔ', + 'Ⱕ' => 'ⱕ', + 'Ⱖ' => 'ⱖ', + 'Ⱗ' => 'ⱗ', + 'Ⱘ' => 'ⱘ', + 'Ⱙ' => 'ⱙ', + 'Ⱚ' => 'ⱚ', + 'Ⱛ' => 'ⱛ', + 'Ⱜ' => 'ⱜ', + 'Ⱝ' => 'ⱝ', + 'Ⱞ' => 'ⱞ', + 'Ⱡ' => 'ⱡ', + 'Ɫ' => 'ɫ', + 'Ᵽ' => 'ᵽ', + 'Ɽ' => 'ɽ', + 'Ⱨ' => 'ⱨ', + 'Ⱪ' => 'ⱪ', + 'Ⱬ' => 'ⱬ', + 'Ɑ' => 'ɑ', + 'Ɱ' => 'ɱ', + 'Ɐ' => 'ɐ', + 'Ɒ' => 'ɒ', + 'Ⱳ' => 'ⱳ', + 'Ⱶ' => 'ⱶ', + 'Ȿ' => 'ȿ', + 'Ɀ' => 'ɀ', + 'Ⲁ' => 'ⲁ', + 'Ⲃ' => 'ⲃ', + 'Ⲅ' => 'ⲅ', + 'Ⲇ' => 'ⲇ', + 'Ⲉ' => 'ⲉ', + 'Ⲋ' => 'ⲋ', + 'Ⲍ' => 'ⲍ', + 'Ⲏ' => 'ⲏ', + 'Ⲑ' => 'ⲑ', + 'Ⲓ' => 'ⲓ', + 'Ⲕ' => 'ⲕ', + 'Ⲗ' => 'ⲗ', + 'Ⲙ' => 'ⲙ', + 'Ⲛ' => 'ⲛ', + 'Ⲝ' => 'ⲝ', + 'Ⲟ' => 'ⲟ', + 'Ⲡ' => 'ⲡ', + 'Ⲣ' => 'ⲣ', + 'Ⲥ' => 'ⲥ', + 'Ⲧ' => 'ⲧ', + 'Ⲩ' => 'ⲩ', + 'Ⲫ' => 'ⲫ', + 'Ⲭ' => 'ⲭ', + 'Ⲯ' => 'ⲯ', + 'Ⲱ' => 'ⲱ', + 'Ⲳ' => 'ⲳ', + 'Ⲵ' => 'ⲵ', + 'Ⲷ' => 'ⲷ', + 'Ⲹ' => 'ⲹ', + 'Ⲻ' => 'ⲻ', + 'Ⲽ' => 'ⲽ', + 'Ⲿ' => 'ⲿ', + 'Ⳁ' => 'ⳁ', + 'Ⳃ' => 'ⳃ', + 'Ⳅ' => 'ⳅ', + 'Ⳇ' => 'ⳇ', + 'Ⳉ' => 'ⳉ', + 'Ⳋ' => 'ⳋ', + 'Ⳍ' => 'ⳍ', + 'Ⳏ' => 'ⳏ', + 'Ⳑ' => 'ⳑ', + 'Ⳓ' => 'ⳓ', + 'Ⳕ' => 'ⳕ', + 'Ⳗ' => 'ⳗ', + 'Ⳙ' => 'ⳙ', + 'Ⳛ' => 'ⳛ', + 'Ⳝ' => 'ⳝ', + 'Ⳟ' => 'ⳟ', + 'Ⳡ' => 'ⳡ', + 'Ⳣ' => 'ⳣ', + 'Ⳬ' => 'ⳬ', + 'Ⳮ' => 'ⳮ', + 'Ⳳ' => 'ⳳ', + 'Ꙁ' => 'ꙁ', + 'Ꙃ' => 'ꙃ', + 'Ꙅ' => 'ꙅ', + 'Ꙇ' => 'ꙇ', + 'Ꙉ' => 'ꙉ', + 'Ꙋ' => 'ꙋ', + 'Ꙍ' => 'ꙍ', + 'Ꙏ' => 'ꙏ', + 'Ꙑ' => 'ꙑ', + 'Ꙓ' => 'ꙓ', + 'Ꙕ' => 'ꙕ', + 'Ꙗ' => 'ꙗ', + 'Ꙙ' => 'ꙙ', + 'Ꙛ' => 'ꙛ', + 'Ꙝ' => 'ꙝ', + 'Ꙟ' => 'ꙟ', + 'Ꙡ' => 'ꙡ', + 'Ꙣ' => 'ꙣ', + 'Ꙥ' => 'ꙥ', + 'Ꙧ' => 'ꙧ', + 'Ꙩ' => 'ꙩ', + 'Ꙫ' => 'ꙫ', + 'Ꙭ' => 'ꙭ', + 'Ꚁ' => 'ꚁ', + 'Ꚃ' => 'ꚃ', + 'Ꚅ' => 'ꚅ', + 'Ꚇ' => 'ꚇ', + 'Ꚉ' => 'ꚉ', + 'Ꚋ' => 'ꚋ', + 'Ꚍ' => 'ꚍ', + 'Ꚏ' => 'ꚏ', + 'Ꚑ' => 'ꚑ', + 'Ꚓ' => 'ꚓ', + 'Ꚕ' => 'ꚕ', + 'Ꚗ' => 'ꚗ', + 'Ꚙ' => 'ꚙ', + 'Ꚛ' => 'ꚛ', + 'Ꜣ' => 'ꜣ', + 'Ꜥ' => 'ꜥ', + 'Ꜧ' => 'ꜧ', + 'Ꜩ' => 'ꜩ', + 'Ꜫ' => 'ꜫ', + 'Ꜭ' => 'ꜭ', + 'Ꜯ' => 'ꜯ', + 'Ꜳ' => 'ꜳ', + 'Ꜵ' => 'ꜵ', + 'Ꜷ' => 'ꜷ', + 'Ꜹ' => 'ꜹ', + 'Ꜻ' => 'ꜻ', + 'Ꜽ' => 'ꜽ', + 'Ꜿ' => 'ꜿ', + 'Ꝁ' => 'ꝁ', + 'Ꝃ' => 'ꝃ', + 'Ꝅ' => 'ꝅ', + 'Ꝇ' => 'ꝇ', + 'Ꝉ' => 'ꝉ', + 'Ꝋ' => 'ꝋ', + 'Ꝍ' => 'ꝍ', + 'Ꝏ' => 'ꝏ', + 'Ꝑ' => 'ꝑ', + 'Ꝓ' => 'ꝓ', + 'Ꝕ' => 'ꝕ', + 'Ꝗ' => 'ꝗ', + 'Ꝙ' => 'ꝙ', + 'Ꝛ' => 'ꝛ', + 'Ꝝ' => 'ꝝ', + 'Ꝟ' => 'ꝟ', + 'Ꝡ' => 'ꝡ', + 'Ꝣ' => 'ꝣ', + 'Ꝥ' => 'ꝥ', + 'Ꝧ' => 'ꝧ', + 'Ꝩ' => 'ꝩ', + 'Ꝫ' => 'ꝫ', + 'Ꝭ' => 'ꝭ', + 'Ꝯ' => 'ꝯ', + 'Ꝺ' => 'ꝺ', + 'Ꝼ' => 'ꝼ', + 'Ᵹ' => 'ᵹ', + 'Ꝿ' => 'ꝿ', + 'Ꞁ' => 'ꞁ', + 'Ꞃ' => 'ꞃ', + 'Ꞅ' => 'ꞅ', + 'Ꞇ' => 'ꞇ', + 'Ꞌ' => 'ꞌ', + 'Ɥ' => 'ɥ', + 'Ꞑ' => 'ꞑ', + 'Ꞓ' => 'ꞓ', + 'Ꞗ' => 'ꞗ', + 'Ꞙ' => 'ꞙ', + 'Ꞛ' => 'ꞛ', + 'Ꞝ' => 'ꞝ', + 'Ꞟ' => 'ꞟ', + 'Ꞡ' => 'ꞡ', + 'Ꞣ' => 'ꞣ', + 'Ꞥ' => 'ꞥ', + 'Ꞧ' => 'ꞧ', + 'Ꞩ' => 'ꞩ', + 'Ɦ' => 'ɦ', + 'Ɜ' => 'ɜ', + 'Ɡ' => 'ɡ', + 'Ɬ' => 'ɬ', + 'Ɪ' => 'ɪ', + 'Ʞ' => 'ʞ', + 'Ʇ' => 'ʇ', + 'Ʝ' => 'ʝ', + 'Ꭓ' => 'ꭓ', + 'Ꞵ' => 'ꞵ', + 'Ꞷ' => 'ꞷ', + 'Ꞹ' => 'ꞹ', + 'Ꞻ' => 'ꞻ', + 'Ꞽ' => 'ꞽ', + 'Ꞿ' => 'ꞿ', + 'Ꟃ' => 'ꟃ', + 'Ꞔ' => 'ꞔ', + 'Ʂ' => 'ʂ', + 'Ᶎ' => 'ᶎ', + 'Ꟈ' => 'ꟈ', + 'Ꟊ' => 'ꟊ', + 'Ꟶ' => 'ꟶ', + 'A' => 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + '𐐀' => '𐐨', + '𐐁' => '𐐩', + '𐐂' => '𐐪', + '𐐃' => '𐐫', + '𐐄' => '𐐬', + '𐐅' => '𐐭', + '𐐆' => '𐐮', + '𐐇' => '𐐯', + '𐐈' => '𐐰', + '𐐉' => '𐐱', + '𐐊' => '𐐲', + '𐐋' => '𐐳', + '𐐌' => '𐐴', + '𐐍' => '𐐵', + '𐐎' => '𐐶', + '𐐏' => '𐐷', + '𐐐' => '𐐸', + '𐐑' => '𐐹', + '𐐒' => '𐐺', + '𐐓' => '𐐻', + '𐐔' => '𐐼', + '𐐕' => '𐐽', + '𐐖' => '𐐾', + '𐐗' => '𐐿', + '𐐘' => '𐑀', + '𐐙' => '𐑁', + '𐐚' => '𐑂', + '𐐛' => '𐑃', + '𐐜' => '𐑄', + '𐐝' => '𐑅', + '𐐞' => '𐑆', + '𐐟' => '𐑇', + '𐐠' => '𐑈', + '𐐡' => '𐑉', + '𐐢' => '𐑊', + '𐐣' => '𐑋', + '𐐤' => '𐑌', + '𐐥' => '𐑍', + '𐐦' => '𐑎', + '𐐧' => '𐑏', + '𐒰' => '𐓘', + '𐒱' => '𐓙', + '𐒲' => '𐓚', + '𐒳' => '𐓛', + '𐒴' => '𐓜', + '𐒵' => '𐓝', + '𐒶' => '𐓞', + '𐒷' => '𐓟', + '𐒸' => '𐓠', + '𐒹' => '𐓡', + '𐒺' => '𐓢', + '𐒻' => '𐓣', + '𐒼' => '𐓤', + '𐒽' => '𐓥', + '𐒾' => '𐓦', + '𐒿' => '𐓧', + '𐓀' => '𐓨', + '𐓁' => '𐓩', + '𐓂' => '𐓪', + '𐓃' => '𐓫', + '𐓄' => '𐓬', + '𐓅' => '𐓭', + '𐓆' => '𐓮', + '𐓇' => '𐓯', + '𐓈' => '𐓰', + '𐓉' => '𐓱', + '𐓊' => '𐓲', + '𐓋' => '𐓳', + '𐓌' => '𐓴', + '𐓍' => '𐓵', + '𐓎' => '𐓶', + '𐓏' => '𐓷', + '𐓐' => '𐓸', + '𐓑' => '𐓹', + '𐓒' => '𐓺', + '𐓓' => '𐓻', + '𐲀' => '𐳀', + '𐲁' => '𐳁', + '𐲂' => '𐳂', + '𐲃' => '𐳃', + '𐲄' => '𐳄', + '𐲅' => '𐳅', + '𐲆' => '𐳆', + '𐲇' => '𐳇', + '𐲈' => '𐳈', + '𐲉' => '𐳉', + '𐲊' => '𐳊', + '𐲋' => '𐳋', + '𐲌' => '𐳌', + '𐲍' => '𐳍', + '𐲎' => '𐳎', + '𐲏' => '𐳏', + '𐲐' => '𐳐', + '𐲑' => '𐳑', + '𐲒' => '𐳒', + '𐲓' => '𐳓', + '𐲔' => '𐳔', + '𐲕' => '𐳕', + '𐲖' => '𐳖', + '𐲗' => '𐳗', + '𐲘' => '𐳘', + '𐲙' => '𐳙', + '𐲚' => '𐳚', + '𐲛' => '𐳛', + '𐲜' => '𐳜', + '𐲝' => '𐳝', + '𐲞' => '𐳞', + '𐲟' => '𐳟', + '𐲠' => '𐳠', + '𐲡' => '𐳡', + '𐲢' => '𐳢', + '𐲣' => '𐳣', + '𐲤' => '𐳤', + '𐲥' => '𐳥', + '𐲦' => '𐳦', + '𐲧' => '𐳧', + '𐲨' => '𐳨', + '𐲩' => '𐳩', + '𐲪' => '𐳪', + '𐲫' => '𐳫', + '𐲬' => '𐳬', + '𐲭' => '𐳭', + '𐲮' => '𐳮', + '𐲯' => '𐳯', + '𐲰' => '𐳰', + '𐲱' => '𐳱', + '𐲲' => '𐳲', + '𑢠' => '𑣀', + '𑢡' => '𑣁', + '𑢢' => '𑣂', + '𑢣' => '𑣃', + '𑢤' => '𑣄', + '𑢥' => '𑣅', + '𑢦' => '𑣆', + '𑢧' => '𑣇', + '𑢨' => '𑣈', + '𑢩' => '𑣉', + '𑢪' => '𑣊', + '𑢫' => '𑣋', + '𑢬' => '𑣌', + '𑢭' => '𑣍', + '𑢮' => '𑣎', + '𑢯' => '𑣏', + '𑢰' => '𑣐', + '𑢱' => '𑣑', + '𑢲' => '𑣒', + '𑢳' => '𑣓', + '𑢴' => '𑣔', + '𑢵' => '𑣕', + '𑢶' => '𑣖', + '𑢷' => '𑣗', + '𑢸' => '𑣘', + '𑢹' => '𑣙', + '𑢺' => '𑣚', + '𑢻' => '𑣛', + '𑢼' => '𑣜', + '𑢽' => '𑣝', + '𑢾' => '𑣞', + '𑢿' => '𑣟', + '𖹀' => '𖹠', + '𖹁' => '𖹡', + '𖹂' => '𖹢', + '𖹃' => '𖹣', + '𖹄' => '𖹤', + '𖹅' => '𖹥', + '𖹆' => '𖹦', + '𖹇' => '𖹧', + '𖹈' => '𖹨', + '𖹉' => '𖹩', + '𖹊' => '𖹪', + '𖹋' => '𖹫', + '𖹌' => '𖹬', + '𖹍' => '𖹭', + '𖹎' => '𖹮', + '𖹏' => '𖹯', + '𖹐' => '𖹰', + '𖹑' => '𖹱', + '𖹒' => '𖹲', + '𖹓' => '𖹳', + '𖹔' => '𖹴', + '𖹕' => '𖹵', + '𖹖' => '𖹶', + '𖹗' => '𖹷', + '𖹘' => '𖹸', + '𖹙' => '𖹹', + '𖹚' => '𖹺', + '𖹛' => '𖹻', + '𖹜' => '𖹼', + '𖹝' => '𖹽', + '𖹞' => '𖹾', + '𖹟' => '𖹿', + '𞤀' => '𞤢', + '𞤁' => '𞤣', + '𞤂' => '𞤤', + '𞤃' => '𞤥', + '𞤄' => '𞤦', + '𞤅' => '𞤧', + '𞤆' => '𞤨', + '𞤇' => '𞤩', + '𞤈' => '𞤪', + '𞤉' => '𞤫', + '𞤊' => '𞤬', + '𞤋' => '𞤭', + '𞤌' => '𞤮', + '𞤍' => '𞤯', + '𞤎' => '𞤰', + '𞤏' => '𞤱', + '𞤐' => '𞤲', + '𞤑' => '𞤳', + '𞤒' => '𞤴', + '𞤓' => '𞤵', + '𞤔' => '𞤶', + '𞤕' => '𞤷', + '𞤖' => '𞤸', + '𞤗' => '𞤹', + '𞤘' => '𞤺', + '𞤙' => '𞤻', + '𞤚' => '𞤼', + '𞤛' => '𞤽', + '𞤜' => '𞤾', + '𞤝' => '𞤿', + '𞤞' => '𞥀', + '𞤟' => '𞥁', + '𞤠' => '𞥂', + '𞤡' => '𞥃', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php new file mode 100644 index 0000000..2a8f6e7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php @@ -0,0 +1,5 @@ + 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + 'µ' => 'Μ', + 'à' => 'À', + 'á' => 'Á', + 'â' => 'Â', + 'ã' => 'Ã', + 'ä' => 'Ä', + 'å' => 'Å', + 'æ' => 'Æ', + 'ç' => 'Ç', + 'è' => 'È', + 'é' => 'É', + 'ê' => 'Ê', + 'ë' => 'Ë', + 'ì' => 'Ì', + 'í' => 'Í', + 'î' => 'Î', + 'ï' => 'Ï', + 'ð' => 'Ð', + 'ñ' => 'Ñ', + 'ò' => 'Ò', + 'ó' => 'Ó', + 'ô' => 'Ô', + 'õ' => 'Õ', + 'ö' => 'Ö', + 'ø' => 'Ø', + 'ù' => 'Ù', + 'ú' => 'Ú', + 'û' => 'Û', + 'ü' => 'Ü', + 'ý' => 'Ý', + 'þ' => 'Þ', + 'ÿ' => 'Ÿ', + 'ā' => 'Ā', + 'ă' => 'Ă', + 'ą' => 'Ą', + 'ć' => 'Ć', + 'ĉ' => 'Ĉ', + 'ċ' => 'Ċ', + 'č' => 'Č', + 'ď' => 'Ď', + 'đ' => 'Đ', + 'ē' => 'Ē', + 'ĕ' => 'Ĕ', + 'ė' => 'Ė', + 'ę' => 'Ę', + 'ě' => 'Ě', + 'ĝ' => 'Ĝ', + 'ğ' => 'Ğ', + 'ġ' => 'Ġ', + 'ģ' => 'Ģ', + 'ĥ' => 'Ĥ', + 'ħ' => 'Ħ', + 'ĩ' => 'Ĩ', + 'ī' => 'Ī', + 'ĭ' => 'Ĭ', + 'į' => 'Į', + 'ı' => 'I', + 'ij' => 'IJ', + 'ĵ' => 'Ĵ', + 'ķ' => 'Ķ', + 'ĺ' => 'Ĺ', + 'ļ' => 'Ļ', + 'ľ' => 'Ľ', + 'ŀ' => 'Ŀ', + 'ł' => 'Ł', + 'ń' => 'Ń', + 'ņ' => 'Ņ', + 'ň' => 'Ň', + 'ŋ' => 'Ŋ', + 'ō' => 'Ō', + 'ŏ' => 'Ŏ', + 'ő' => 'Ő', + 'œ' => 'Œ', + 'ŕ' => 'Ŕ', + 'ŗ' => 'Ŗ', + 'ř' => 'Ř', + 'ś' => 'Ś', + 'ŝ' => 'Ŝ', + 'ş' => 'Ş', + 'š' => 'Š', + 'ţ' => 'Ţ', + 'ť' => 'Ť', + 'ŧ' => 'Ŧ', + 'ũ' => 'Ũ', + 'ū' => 'Ū', + 'ŭ' => 'Ŭ', + 'ů' => 'Ů', + 'ű' => 'Ű', + 'ų' => 'Ų', + 'ŵ' => 'Ŵ', + 'ŷ' => 'Ŷ', + 'ź' => 'Ź', + 'ż' => 'Ż', + 'ž' => 'Ž', + 'ſ' => 'S', + 'ƀ' => 'Ƀ', + 'ƃ' => 'Ƃ', + 'ƅ' => 'Ƅ', + 'ƈ' => 'Ƈ', + 'ƌ' => 'Ƌ', + 'ƒ' => 'Ƒ', + 'ƕ' => 'Ƕ', + 'ƙ' => 'Ƙ', + 'ƚ' => 'Ƚ', + 'ƞ' => 'Ƞ', + 'ơ' => 'Ơ', + 'ƣ' => 'Ƣ', + 'ƥ' => 'Ƥ', + 'ƨ' => 'Ƨ', + 'ƭ' => 'Ƭ', + 'ư' => 'Ư', + 'ƴ' => 'Ƴ', + 'ƶ' => 'Ƶ', + 'ƹ' => 'Ƹ', + 'ƽ' => 'Ƽ', + 'ƿ' => 'Ƿ', + 'Dž' => 'DŽ', + 'dž' => 'DŽ', + 'Lj' => 'LJ', + 'lj' => 'LJ', + 'Nj' => 'NJ', + 'nj' => 'NJ', + 'ǎ' => 'Ǎ', + 'ǐ' => 'Ǐ', + 'ǒ' => 'Ǒ', + 'ǔ' => 'Ǔ', + 'ǖ' => 'Ǖ', + 'ǘ' => 'Ǘ', + 'ǚ' => 'Ǚ', + 'ǜ' => 'Ǜ', + 'ǝ' => 'Ǝ', + 'ǟ' => 'Ǟ', + 'ǡ' => 'Ǡ', + 'ǣ' => 'Ǣ', + 'ǥ' => 'Ǥ', + 'ǧ' => 'Ǧ', + 'ǩ' => 'Ǩ', + 'ǫ' => 'Ǫ', + 'ǭ' => 'Ǭ', + 'ǯ' => 'Ǯ', + 'Dz' => 'DZ', + 'dz' => 'DZ', + 'ǵ' => 'Ǵ', + 'ǹ' => 'Ǹ', + 'ǻ' => 'Ǻ', + 'ǽ' => 'Ǽ', + 'ǿ' => 'Ǿ', + 'ȁ' => 'Ȁ', + 'ȃ' => 'Ȃ', + 'ȅ' => 'Ȅ', + 'ȇ' => 'Ȇ', + 'ȉ' => 'Ȉ', + 'ȋ' => 'Ȋ', + 'ȍ' => 'Ȍ', + 'ȏ' => 'Ȏ', + 'ȑ' => 'Ȑ', + 'ȓ' => 'Ȓ', + 'ȕ' => 'Ȕ', + 'ȗ' => 'Ȗ', + 'ș' => 'Ș', + 'ț' => 'Ț', + 'ȝ' => 'Ȝ', + 'ȟ' => 'Ȟ', + 'ȣ' => 'Ȣ', + 'ȥ' => 'Ȥ', + 'ȧ' => 'Ȧ', + 'ȩ' => 'Ȩ', + 'ȫ' => 'Ȫ', + 'ȭ' => 'Ȭ', + 'ȯ' => 'Ȯ', + 'ȱ' => 'Ȱ', + 'ȳ' => 'Ȳ', + 'ȼ' => 'Ȼ', + 'ȿ' => 'Ȿ', + 'ɀ' => 'Ɀ', + 'ɂ' => 'Ɂ', + 'ɇ' => 'Ɇ', + 'ɉ' => 'Ɉ', + 'ɋ' => 'Ɋ', + 'ɍ' => 'Ɍ', + 'ɏ' => 'Ɏ', + 'ɐ' => 'Ɐ', + 'ɑ' => 'Ɑ', + 'ɒ' => 'Ɒ', + 'ɓ' => 'Ɓ', + 'ɔ' => 'Ɔ', + 'ɖ' => 'Ɖ', + 'ɗ' => 'Ɗ', + 'ə' => 'Ə', + 'ɛ' => 'Ɛ', + 'ɜ' => 'Ɜ', + 'ɠ' => 'Ɠ', + 'ɡ' => 'Ɡ', + 'ɣ' => 'Ɣ', + 'ɥ' => 'Ɥ', + 'ɦ' => 'Ɦ', + 'ɨ' => 'Ɨ', + 'ɩ' => 'Ɩ', + 'ɪ' => 'Ɪ', + 'ɫ' => 'Ɫ', + 'ɬ' => 'Ɬ', + 'ɯ' => 'Ɯ', + 'ɱ' => 'Ɱ', + 'ɲ' => 'Ɲ', + 'ɵ' => 'Ɵ', + 'ɽ' => 'Ɽ', + 'ʀ' => 'Ʀ', + 'ʂ' => 'Ʂ', + 'ʃ' => 'Ʃ', + 'ʇ' => 'Ʇ', + 'ʈ' => 'Ʈ', + 'ʉ' => 'Ʉ', + 'ʊ' => 'Ʊ', + 'ʋ' => 'Ʋ', + 'ʌ' => 'Ʌ', + 'ʒ' => 'Ʒ', + 'ʝ' => 'Ʝ', + 'ʞ' => 'Ʞ', + 'ͅ' => 'Ι', + 'ͱ' => 'Ͱ', + 'ͳ' => 'Ͳ', + 'ͷ' => 'Ͷ', + 'ͻ' => 'Ͻ', + 'ͼ' => 'Ͼ', + 'ͽ' => 'Ͽ', + 'ά' => 'Ά', + 'έ' => 'Έ', + 'ή' => 'Ή', + 'ί' => 'Ί', + 'α' => 'Α', + 'β' => 'Β', + 'γ' => 'Γ', + 'δ' => 'Δ', + 'ε' => 'Ε', + 'ζ' => 'Ζ', + 'η' => 'Η', + 'θ' => 'Θ', + 'ι' => 'Ι', + 'κ' => 'Κ', + 'λ' => 'Λ', + 'μ' => 'Μ', + 'ν' => 'Ν', + 'ξ' => 'Ξ', + 'ο' => 'Ο', + 'π' => 'Π', + 'ρ' => 'Ρ', + 'ς' => 'Σ', + 'σ' => 'Σ', + 'τ' => 'Τ', + 'υ' => 'Υ', + 'φ' => 'Φ', + 'χ' => 'Χ', + 'ψ' => 'Ψ', + 'ω' => 'Ω', + 'ϊ' => 'Ϊ', + 'ϋ' => 'Ϋ', + 'ό' => 'Ό', + 'ύ' => 'Ύ', + 'ώ' => 'Ώ', + 'ϐ' => 'Β', + 'ϑ' => 'Θ', + 'ϕ' => 'Φ', + 'ϖ' => 'Π', + 'ϗ' => 'Ϗ', + 'ϙ' => 'Ϙ', + 'ϛ' => 'Ϛ', + 'ϝ' => 'Ϝ', + 'ϟ' => 'Ϟ', + 'ϡ' => 'Ϡ', + 'ϣ' => 'Ϣ', + 'ϥ' => 'Ϥ', + 'ϧ' => 'Ϧ', + 'ϩ' => 'Ϩ', + 'ϫ' => 'Ϫ', + 'ϭ' => 'Ϭ', + 'ϯ' => 'Ϯ', + 'ϰ' => 'Κ', + 'ϱ' => 'Ρ', + 'ϲ' => 'Ϲ', + 'ϳ' => 'Ϳ', + 'ϵ' => 'Ε', + 'ϸ' => 'Ϸ', + 'ϻ' => 'Ϻ', + 'а' => 'А', + 'б' => 'Б', + 'в' => 'В', + 'г' => 'Г', + 'д' => 'Д', + 'е' => 'Е', + 'ж' => 'Ж', + 'з' => 'З', + 'и' => 'И', + 'й' => 'Й', + 'к' => 'К', + 'л' => 'Л', + 'м' => 'М', + 'н' => 'Н', + 'о' => 'О', + 'п' => 'П', + 'р' => 'Р', + 'с' => 'С', + 'т' => 'Т', + 'у' => 'У', + 'ф' => 'Ф', + 'х' => 'Х', + 'ц' => 'Ц', + 'ч' => 'Ч', + 'ш' => 'Ш', + 'щ' => 'Щ', + 'ъ' => 'Ъ', + 'ы' => 'Ы', + 'ь' => 'Ь', + 'э' => 'Э', + 'ю' => 'Ю', + 'я' => 'Я', + 'ѐ' => 'Ѐ', + 'ё' => 'Ё', + 'ђ' => 'Ђ', + 'ѓ' => 'Ѓ', + 'є' => 'Є', + 'ѕ' => 'Ѕ', + 'і' => 'І', + 'ї' => 'Ї', + 'ј' => 'Ј', + 'љ' => 'Љ', + 'њ' => 'Њ', + 'ћ' => 'Ћ', + 'ќ' => 'Ќ', + 'ѝ' => 'Ѝ', + 'ў' => 'Ў', + 'џ' => 'Џ', + 'ѡ' => 'Ѡ', + 'ѣ' => 'Ѣ', + 'ѥ' => 'Ѥ', + 'ѧ' => 'Ѧ', + 'ѩ' => 'Ѩ', + 'ѫ' => 'Ѫ', + 'ѭ' => 'Ѭ', + 'ѯ' => 'Ѯ', + 'ѱ' => 'Ѱ', + 'ѳ' => 'Ѳ', + 'ѵ' => 'Ѵ', + 'ѷ' => 'Ѷ', + 'ѹ' => 'Ѹ', + 'ѻ' => 'Ѻ', + 'ѽ' => 'Ѽ', + 'ѿ' => 'Ѿ', + 'ҁ' => 'Ҁ', + 'ҋ' => 'Ҋ', + 'ҍ' => 'Ҍ', + 'ҏ' => 'Ҏ', + 'ґ' => 'Ґ', + 'ғ' => 'Ғ', + 'ҕ' => 'Ҕ', + 'җ' => 'Җ', + 'ҙ' => 'Ҙ', + 'қ' => 'Қ', + 'ҝ' => 'Ҝ', + 'ҟ' => 'Ҟ', + 'ҡ' => 'Ҡ', + 'ң' => 'Ң', + 'ҥ' => 'Ҥ', + 'ҧ' => 'Ҧ', + 'ҩ' => 'Ҩ', + 'ҫ' => 'Ҫ', + 'ҭ' => 'Ҭ', + 'ү' => 'Ү', + 'ұ' => 'Ұ', + 'ҳ' => 'Ҳ', + 'ҵ' => 'Ҵ', + 'ҷ' => 'Ҷ', + 'ҹ' => 'Ҹ', + 'һ' => 'Һ', + 'ҽ' => 'Ҽ', + 'ҿ' => 'Ҿ', + 'ӂ' => 'Ӂ', + 'ӄ' => 'Ӄ', + 'ӆ' => 'Ӆ', + 'ӈ' => 'Ӈ', + 'ӊ' => 'Ӊ', + 'ӌ' => 'Ӌ', + 'ӎ' => 'Ӎ', + 'ӏ' => 'Ӏ', + 'ӑ' => 'Ӑ', + 'ӓ' => 'Ӓ', + 'ӕ' => 'Ӕ', + 'ӗ' => 'Ӗ', + 'ә' => 'Ә', + 'ӛ' => 'Ӛ', + 'ӝ' => 'Ӝ', + 'ӟ' => 'Ӟ', + 'ӡ' => 'Ӡ', + 'ӣ' => 'Ӣ', + 'ӥ' => 'Ӥ', + 'ӧ' => 'Ӧ', + 'ө' => 'Ө', + 'ӫ' => 'Ӫ', + 'ӭ' => 'Ӭ', + 'ӯ' => 'Ӯ', + 'ӱ' => 'Ӱ', + 'ӳ' => 'Ӳ', + 'ӵ' => 'Ӵ', + 'ӷ' => 'Ӷ', + 'ӹ' => 'Ӹ', + 'ӻ' => 'Ӻ', + 'ӽ' => 'Ӽ', + 'ӿ' => 'Ӿ', + 'ԁ' => 'Ԁ', + 'ԃ' => 'Ԃ', + 'ԅ' => 'Ԅ', + 'ԇ' => 'Ԇ', + 'ԉ' => 'Ԉ', + 'ԋ' => 'Ԋ', + 'ԍ' => 'Ԍ', + 'ԏ' => 'Ԏ', + 'ԑ' => 'Ԑ', + 'ԓ' => 'Ԓ', + 'ԕ' => 'Ԕ', + 'ԗ' => 'Ԗ', + 'ԙ' => 'Ԙ', + 'ԛ' => 'Ԛ', + 'ԝ' => 'Ԝ', + 'ԟ' => 'Ԟ', + 'ԡ' => 'Ԡ', + 'ԣ' => 'Ԣ', + 'ԥ' => 'Ԥ', + 'ԧ' => 'Ԧ', + 'ԩ' => 'Ԩ', + 'ԫ' => 'Ԫ', + 'ԭ' => 'Ԭ', + 'ԯ' => 'Ԯ', + 'ա' => 'Ա', + 'բ' => 'Բ', + 'գ' => 'Գ', + 'դ' => 'Դ', + 'ե' => 'Ե', + 'զ' => 'Զ', + 'է' => 'Է', + 'ը' => 'Ը', + 'թ' => 'Թ', + 'ժ' => 'Ժ', + 'ի' => 'Ի', + 'լ' => 'Լ', + 'խ' => 'Խ', + 'ծ' => 'Ծ', + 'կ' => 'Կ', + 'հ' => 'Հ', + 'ձ' => 'Ձ', + 'ղ' => 'Ղ', + 'ճ' => 'Ճ', + 'մ' => 'Մ', + 'յ' => 'Յ', + 'ն' => 'Ն', + 'շ' => 'Շ', + 'ո' => 'Ո', + 'չ' => 'Չ', + 'պ' => 'Պ', + 'ջ' => 'Ջ', + 'ռ' => 'Ռ', + 'ս' => 'Ս', + 'վ' => 'Վ', + 'տ' => 'Տ', + 'ր' => 'Ր', + 'ց' => 'Ց', + 'ւ' => 'Ւ', + 'փ' => 'Փ', + 'ք' => 'Ք', + 'օ' => 'Օ', + 'ֆ' => 'Ֆ', + 'ა' => 'Ა', + 'ბ' => 'Ბ', + 'გ' => 'Გ', + 'დ' => 'Დ', + 'ე' => 'Ე', + 'ვ' => 'Ვ', + 'ზ' => 'Ზ', + 'თ' => 'Თ', + 'ი' => 'Ი', + 'კ' => 'Კ', + 'ლ' => 'Ლ', + 'მ' => 'Მ', + 'ნ' => 'Ნ', + 'ო' => 'Ო', + 'პ' => 'Პ', + 'ჟ' => 'Ჟ', + 'რ' => 'Რ', + 'ს' => 'Ს', + 'ტ' => 'Ტ', + 'უ' => 'Უ', + 'ფ' => 'Ფ', + 'ქ' => 'Ქ', + 'ღ' => 'Ღ', + 'ყ' => 'Ყ', + 'შ' => 'Შ', + 'ჩ' => 'Ჩ', + 'ც' => 'Ც', + 'ძ' => 'Ძ', + 'წ' => 'Წ', + 'ჭ' => 'Ჭ', + 'ხ' => 'Ხ', + 'ჯ' => 'Ჯ', + 'ჰ' => 'Ჰ', + 'ჱ' => 'Ჱ', + 'ჲ' => 'Ჲ', + 'ჳ' => 'Ჳ', + 'ჴ' => 'Ჴ', + 'ჵ' => 'Ჵ', + 'ჶ' => 'Ჶ', + 'ჷ' => 'Ჷ', + 'ჸ' => 'Ჸ', + 'ჹ' => 'Ჹ', + 'ჺ' => 'Ჺ', + 'ჽ' => 'Ჽ', + 'ჾ' => 'Ჾ', + 'ჿ' => 'Ჿ', + 'ᏸ' => 'Ᏸ', + 'ᏹ' => 'Ᏹ', + 'ᏺ' => 'Ᏺ', + 'ᏻ' => 'Ᏻ', + 'ᏼ' => 'Ᏼ', + 'ᏽ' => 'Ᏽ', + 'ᲀ' => 'В', + 'ᲁ' => 'Д', + 'ᲂ' => 'О', + 'ᲃ' => 'С', + 'ᲄ' => 'Т', + 'ᲅ' => 'Т', + 'ᲆ' => 'Ъ', + 'ᲇ' => 'Ѣ', + 'ᲈ' => 'Ꙋ', + 'ᵹ' => 'Ᵹ', + 'ᵽ' => 'Ᵽ', + 'ᶎ' => 'Ᶎ', + 'ḁ' => 'Ḁ', + 'ḃ' => 'Ḃ', + 'ḅ' => 'Ḅ', + 'ḇ' => 'Ḇ', + 'ḉ' => 'Ḉ', + 'ḋ' => 'Ḋ', + 'ḍ' => 'Ḍ', + 'ḏ' => 'Ḏ', + 'ḑ' => 'Ḑ', + 'ḓ' => 'Ḓ', + 'ḕ' => 'Ḕ', + 'ḗ' => 'Ḗ', + 'ḙ' => 'Ḙ', + 'ḛ' => 'Ḛ', + 'ḝ' => 'Ḝ', + 'ḟ' => 'Ḟ', + 'ḡ' => 'Ḡ', + 'ḣ' => 'Ḣ', + 'ḥ' => 'Ḥ', + 'ḧ' => 'Ḧ', + 'ḩ' => 'Ḩ', + 'ḫ' => 'Ḫ', + 'ḭ' => 'Ḭ', + 'ḯ' => 'Ḯ', + 'ḱ' => 'Ḱ', + 'ḳ' => 'Ḳ', + 'ḵ' => 'Ḵ', + 'ḷ' => 'Ḷ', + 'ḹ' => 'Ḹ', + 'ḻ' => 'Ḻ', + 'ḽ' => 'Ḽ', + 'ḿ' => 'Ḿ', + 'ṁ' => 'Ṁ', + 'ṃ' => 'Ṃ', + 'ṅ' => 'Ṅ', + 'ṇ' => 'Ṇ', + 'ṉ' => 'Ṉ', + 'ṋ' => 'Ṋ', + 'ṍ' => 'Ṍ', + 'ṏ' => 'Ṏ', + 'ṑ' => 'Ṑ', + 'ṓ' => 'Ṓ', + 'ṕ' => 'Ṕ', + 'ṗ' => 'Ṗ', + 'ṙ' => 'Ṙ', + 'ṛ' => 'Ṛ', + 'ṝ' => 'Ṝ', + 'ṟ' => 'Ṟ', + 'ṡ' => 'Ṡ', + 'ṣ' => 'Ṣ', + 'ṥ' => 'Ṥ', + 'ṧ' => 'Ṧ', + 'ṩ' => 'Ṩ', + 'ṫ' => 'Ṫ', + 'ṭ' => 'Ṭ', + 'ṯ' => 'Ṯ', + 'ṱ' => 'Ṱ', + 'ṳ' => 'Ṳ', + 'ṵ' => 'Ṵ', + 'ṷ' => 'Ṷ', + 'ṹ' => 'Ṹ', + 'ṻ' => 'Ṻ', + 'ṽ' => 'Ṽ', + 'ṿ' => 'Ṿ', + 'ẁ' => 'Ẁ', + 'ẃ' => 'Ẃ', + 'ẅ' => 'Ẅ', + 'ẇ' => 'Ẇ', + 'ẉ' => 'Ẉ', + 'ẋ' => 'Ẋ', + 'ẍ' => 'Ẍ', + 'ẏ' => 'Ẏ', + 'ẑ' => 'Ẑ', + 'ẓ' => 'Ẓ', + 'ẕ' => 'Ẕ', + 'ẛ' => 'Ṡ', + 'ạ' => 'Ạ', + 'ả' => 'Ả', + 'ấ' => 'Ấ', + 'ầ' => 'Ầ', + 'ẩ' => 'Ẩ', + 'ẫ' => 'Ẫ', + 'ậ' => 'Ậ', + 'ắ' => 'Ắ', + 'ằ' => 'Ằ', + 'ẳ' => 'Ẳ', + 'ẵ' => 'Ẵ', + 'ặ' => 'Ặ', + 'ẹ' => 'Ẹ', + 'ẻ' => 'Ẻ', + 'ẽ' => 'Ẽ', + 'ế' => 'Ế', + 'ề' => 'Ề', + 'ể' => 'Ể', + 'ễ' => 'Ễ', + 'ệ' => 'Ệ', + 'ỉ' => 'Ỉ', + 'ị' => 'Ị', + 'ọ' => 'Ọ', + 'ỏ' => 'Ỏ', + 'ố' => 'Ố', + 'ồ' => 'Ồ', + 'ổ' => 'Ổ', + 'ỗ' => 'Ỗ', + 'ộ' => 'Ộ', + 'ớ' => 'Ớ', + 'ờ' => 'Ờ', + 'ở' => 'Ở', + 'ỡ' => 'Ỡ', + 'ợ' => 'Ợ', + 'ụ' => 'Ụ', + 'ủ' => 'Ủ', + 'ứ' => 'Ứ', + 'ừ' => 'Ừ', + 'ử' => 'Ử', + 'ữ' => 'Ữ', + 'ự' => 'Ự', + 'ỳ' => 'Ỳ', + 'ỵ' => 'Ỵ', + 'ỷ' => 'Ỷ', + 'ỹ' => 'Ỹ', + 'ỻ' => 'Ỻ', + 'ỽ' => 'Ỽ', + 'ỿ' => 'Ỿ', + 'ἀ' => 'Ἀ', + 'ἁ' => 'Ἁ', + 'ἂ' => 'Ἂ', + 'ἃ' => 'Ἃ', + 'ἄ' => 'Ἄ', + 'ἅ' => 'Ἅ', + 'ἆ' => 'Ἆ', + 'ἇ' => 'Ἇ', + 'ἐ' => 'Ἐ', + 'ἑ' => 'Ἑ', + 'ἒ' => 'Ἒ', + 'ἓ' => 'Ἓ', + 'ἔ' => 'Ἔ', + 'ἕ' => 'Ἕ', + 'ἠ' => 'Ἠ', + 'ἡ' => 'Ἡ', + 'ἢ' => 'Ἢ', + 'ἣ' => 'Ἣ', + 'ἤ' => 'Ἤ', + 'ἥ' => 'Ἥ', + 'ἦ' => 'Ἦ', + 'ἧ' => 'Ἧ', + 'ἰ' => 'Ἰ', + 'ἱ' => 'Ἱ', + 'ἲ' => 'Ἲ', + 'ἳ' => 'Ἳ', + 'ἴ' => 'Ἴ', + 'ἵ' => 'Ἵ', + 'ἶ' => 'Ἶ', + 'ἷ' => 'Ἷ', + 'ὀ' => 'Ὀ', + 'ὁ' => 'Ὁ', + 'ὂ' => 'Ὂ', + 'ὃ' => 'Ὃ', + 'ὄ' => 'Ὄ', + 'ὅ' => 'Ὅ', + 'ὑ' => 'Ὑ', + 'ὓ' => 'Ὓ', + 'ὕ' => 'Ὕ', + 'ὗ' => 'Ὗ', + 'ὠ' => 'Ὠ', + 'ὡ' => 'Ὡ', + 'ὢ' => 'Ὢ', + 'ὣ' => 'Ὣ', + 'ὤ' => 'Ὤ', + 'ὥ' => 'Ὥ', + 'ὦ' => 'Ὦ', + 'ὧ' => 'Ὧ', + 'ὰ' => 'Ὰ', + 'ά' => 'Ά', + 'ὲ' => 'Ὲ', + 'έ' => 'Έ', + 'ὴ' => 'Ὴ', + 'ή' => 'Ή', + 'ὶ' => 'Ὶ', + 'ί' => 'Ί', + 'ὸ' => 'Ὸ', + 'ό' => 'Ό', + 'ὺ' => 'Ὺ', + 'ύ' => 'Ύ', + 'ὼ' => 'Ὼ', + 'ώ' => 'Ώ', + 'ᾀ' => 'ἈΙ', + 'ᾁ' => 'ἉΙ', + 'ᾂ' => 'ἊΙ', + 'ᾃ' => 'ἋΙ', + 'ᾄ' => 'ἌΙ', + 'ᾅ' => 'ἍΙ', + 'ᾆ' => 'ἎΙ', + 'ᾇ' => 'ἏΙ', + 'ᾐ' => 'ἨΙ', + 'ᾑ' => 'ἩΙ', + 'ᾒ' => 'ἪΙ', + 'ᾓ' => 'ἫΙ', + 'ᾔ' => 'ἬΙ', + 'ᾕ' => 'ἭΙ', + 'ᾖ' => 'ἮΙ', + 'ᾗ' => 'ἯΙ', + 'ᾠ' => 'ὨΙ', + 'ᾡ' => 'ὩΙ', + 'ᾢ' => 'ὪΙ', + 'ᾣ' => 'ὫΙ', + 'ᾤ' => 'ὬΙ', + 'ᾥ' => 'ὭΙ', + 'ᾦ' => 'ὮΙ', + 'ᾧ' => 'ὯΙ', + 'ᾰ' => 'Ᾰ', + 'ᾱ' => 'Ᾱ', + 'ᾳ' => 'ΑΙ', + 'ι' => 'Ι', + 'ῃ' => 'ΗΙ', + 'ῐ' => 'Ῐ', + 'ῑ' => 'Ῑ', + 'ῠ' => 'Ῠ', + 'ῡ' => 'Ῡ', + 'ῥ' => 'Ῥ', + 'ῳ' => 'ΩΙ', + 'ⅎ' => 'Ⅎ', + 'ⅰ' => 'Ⅰ', + 'ⅱ' => 'Ⅱ', + 'ⅲ' => 'Ⅲ', + 'ⅳ' => 'Ⅳ', + 'ⅴ' => 'Ⅴ', + 'ⅵ' => 'Ⅵ', + 'ⅶ' => 'Ⅶ', + 'ⅷ' => 'Ⅷ', + 'ⅸ' => 'Ⅸ', + 'ⅹ' => 'Ⅹ', + 'ⅺ' => 'Ⅺ', + 'ⅻ' => 'Ⅻ', + 'ⅼ' => 'Ⅼ', + 'ⅽ' => 'Ⅽ', + 'ⅾ' => 'Ⅾ', + 'ⅿ' => 'Ⅿ', + 'ↄ' => 'Ↄ', + 'ⓐ' => 'Ⓐ', + 'ⓑ' => 'Ⓑ', + 'ⓒ' => 'Ⓒ', + 'ⓓ' => 'Ⓓ', + 'ⓔ' => 'Ⓔ', + 'ⓕ' => 'Ⓕ', + 'ⓖ' => 'Ⓖ', + 'ⓗ' => 'Ⓗ', + 'ⓘ' => 'Ⓘ', + 'ⓙ' => 'Ⓙ', + 'ⓚ' => 'Ⓚ', + 'ⓛ' => 'Ⓛ', + 'ⓜ' => 'Ⓜ', + 'ⓝ' => 'Ⓝ', + 'ⓞ' => 'Ⓞ', + 'ⓟ' => 'Ⓟ', + 'ⓠ' => 'Ⓠ', + 'ⓡ' => 'Ⓡ', + 'ⓢ' => 'Ⓢ', + 'ⓣ' => 'Ⓣ', + 'ⓤ' => 'Ⓤ', + 'ⓥ' => 'Ⓥ', + 'ⓦ' => 'Ⓦ', + 'ⓧ' => 'Ⓧ', + 'ⓨ' => 'Ⓨ', + 'ⓩ' => 'Ⓩ', + 'ⰰ' => 'Ⰰ', + 'ⰱ' => 'Ⰱ', + 'ⰲ' => 'Ⰲ', + 'ⰳ' => 'Ⰳ', + 'ⰴ' => 'Ⰴ', + 'ⰵ' => 'Ⰵ', + 'ⰶ' => 'Ⰶ', + 'ⰷ' => 'Ⰷ', + 'ⰸ' => 'Ⰸ', + 'ⰹ' => 'Ⰹ', + 'ⰺ' => 'Ⰺ', + 'ⰻ' => 'Ⰻ', + 'ⰼ' => 'Ⰼ', + 'ⰽ' => 'Ⰽ', + 'ⰾ' => 'Ⰾ', + 'ⰿ' => 'Ⰿ', + 'ⱀ' => 'Ⱀ', + 'ⱁ' => 'Ⱁ', + 'ⱂ' => 'Ⱂ', + 'ⱃ' => 'Ⱃ', + 'ⱄ' => 'Ⱄ', + 'ⱅ' => 'Ⱅ', + 'ⱆ' => 'Ⱆ', + 'ⱇ' => 'Ⱇ', + 'ⱈ' => 'Ⱈ', + 'ⱉ' => 'Ⱉ', + 'ⱊ' => 'Ⱊ', + 'ⱋ' => 'Ⱋ', + 'ⱌ' => 'Ⱌ', + 'ⱍ' => 'Ⱍ', + 'ⱎ' => 'Ⱎ', + 'ⱏ' => 'Ⱏ', + 'ⱐ' => 'Ⱐ', + 'ⱑ' => 'Ⱑ', + 'ⱒ' => 'Ⱒ', + 'ⱓ' => 'Ⱓ', + 'ⱔ' => 'Ⱔ', + 'ⱕ' => 'Ⱕ', + 'ⱖ' => 'Ⱖ', + 'ⱗ' => 'Ⱗ', + 'ⱘ' => 'Ⱘ', + 'ⱙ' => 'Ⱙ', + 'ⱚ' => 'Ⱚ', + 'ⱛ' => 'Ⱛ', + 'ⱜ' => 'Ⱜ', + 'ⱝ' => 'Ⱝ', + 'ⱞ' => 'Ⱞ', + 'ⱡ' => 'Ⱡ', + 'ⱥ' => 'Ⱥ', + 'ⱦ' => 'Ⱦ', + 'ⱨ' => 'Ⱨ', + 'ⱪ' => 'Ⱪ', + 'ⱬ' => 'Ⱬ', + 'ⱳ' => 'Ⱳ', + 'ⱶ' => 'Ⱶ', + 'ⲁ' => 'Ⲁ', + 'ⲃ' => 'Ⲃ', + 'ⲅ' => 'Ⲅ', + 'ⲇ' => 'Ⲇ', + 'ⲉ' => 'Ⲉ', + 'ⲋ' => 'Ⲋ', + 'ⲍ' => 'Ⲍ', + 'ⲏ' => 'Ⲏ', + 'ⲑ' => 'Ⲑ', + 'ⲓ' => 'Ⲓ', + 'ⲕ' => 'Ⲕ', + 'ⲗ' => 'Ⲗ', + 'ⲙ' => 'Ⲙ', + 'ⲛ' => 'Ⲛ', + 'ⲝ' => 'Ⲝ', + 'ⲟ' => 'Ⲟ', + 'ⲡ' => 'Ⲡ', + 'ⲣ' => 'Ⲣ', + 'ⲥ' => 'Ⲥ', + 'ⲧ' => 'Ⲧ', + 'ⲩ' => 'Ⲩ', + 'ⲫ' => 'Ⲫ', + 'ⲭ' => 'Ⲭ', + 'ⲯ' => 'Ⲯ', + 'ⲱ' => 'Ⲱ', + 'ⲳ' => 'Ⲳ', + 'ⲵ' => 'Ⲵ', + 'ⲷ' => 'Ⲷ', + 'ⲹ' => 'Ⲹ', + 'ⲻ' => 'Ⲻ', + 'ⲽ' => 'Ⲽ', + 'ⲿ' => 'Ⲿ', + 'ⳁ' => 'Ⳁ', + 'ⳃ' => 'Ⳃ', + 'ⳅ' => 'Ⳅ', + 'ⳇ' => 'Ⳇ', + 'ⳉ' => 'Ⳉ', + 'ⳋ' => 'Ⳋ', + 'ⳍ' => 'Ⳍ', + 'ⳏ' => 'Ⳏ', + 'ⳑ' => 'Ⳑ', + 'ⳓ' => 'Ⳓ', + 'ⳕ' => 'Ⳕ', + 'ⳗ' => 'Ⳗ', + 'ⳙ' => 'Ⳙ', + 'ⳛ' => 'Ⳛ', + 'ⳝ' => 'Ⳝ', + 'ⳟ' => 'Ⳟ', + 'ⳡ' => 'Ⳡ', + 'ⳣ' => 'Ⳣ', + 'ⳬ' => 'Ⳬ', + 'ⳮ' => 'Ⳮ', + 'ⳳ' => 'Ⳳ', + 'ⴀ' => 'Ⴀ', + 'ⴁ' => 'Ⴁ', + 'ⴂ' => 'Ⴂ', + 'ⴃ' => 'Ⴃ', + 'ⴄ' => 'Ⴄ', + 'ⴅ' => 'Ⴅ', + 'ⴆ' => 'Ⴆ', + 'ⴇ' => 'Ⴇ', + 'ⴈ' => 'Ⴈ', + 'ⴉ' => 'Ⴉ', + 'ⴊ' => 'Ⴊ', + 'ⴋ' => 'Ⴋ', + 'ⴌ' => 'Ⴌ', + 'ⴍ' => 'Ⴍ', + 'ⴎ' => 'Ⴎ', + 'ⴏ' => 'Ⴏ', + 'ⴐ' => 'Ⴐ', + 'ⴑ' => 'Ⴑ', + 'ⴒ' => 'Ⴒ', + 'ⴓ' => 'Ⴓ', + 'ⴔ' => 'Ⴔ', + 'ⴕ' => 'Ⴕ', + 'ⴖ' => 'Ⴖ', + 'ⴗ' => 'Ⴗ', + 'ⴘ' => 'Ⴘ', + 'ⴙ' => 'Ⴙ', + 'ⴚ' => 'Ⴚ', + 'ⴛ' => 'Ⴛ', + 'ⴜ' => 'Ⴜ', + 'ⴝ' => 'Ⴝ', + 'ⴞ' => 'Ⴞ', + 'ⴟ' => 'Ⴟ', + 'ⴠ' => 'Ⴠ', + 'ⴡ' => 'Ⴡ', + 'ⴢ' => 'Ⴢ', + 'ⴣ' => 'Ⴣ', + 'ⴤ' => 'Ⴤ', + 'ⴥ' => 'Ⴥ', + 'ⴧ' => 'Ⴧ', + 'ⴭ' => 'Ⴭ', + 'ꙁ' => 'Ꙁ', + 'ꙃ' => 'Ꙃ', + 'ꙅ' => 'Ꙅ', + 'ꙇ' => 'Ꙇ', + 'ꙉ' => 'Ꙉ', + 'ꙋ' => 'Ꙋ', + 'ꙍ' => 'Ꙍ', + 'ꙏ' => 'Ꙏ', + 'ꙑ' => 'Ꙑ', + 'ꙓ' => 'Ꙓ', + 'ꙕ' => 'Ꙕ', + 'ꙗ' => 'Ꙗ', + 'ꙙ' => 'Ꙙ', + 'ꙛ' => 'Ꙛ', + 'ꙝ' => 'Ꙝ', + 'ꙟ' => 'Ꙟ', + 'ꙡ' => 'Ꙡ', + 'ꙣ' => 'Ꙣ', + 'ꙥ' => 'Ꙥ', + 'ꙧ' => 'Ꙧ', + 'ꙩ' => 'Ꙩ', + 'ꙫ' => 'Ꙫ', + 'ꙭ' => 'Ꙭ', + 'ꚁ' => 'Ꚁ', + 'ꚃ' => 'Ꚃ', + 'ꚅ' => 'Ꚅ', + 'ꚇ' => 'Ꚇ', + 'ꚉ' => 'Ꚉ', + 'ꚋ' => 'Ꚋ', + 'ꚍ' => 'Ꚍ', + 'ꚏ' => 'Ꚏ', + 'ꚑ' => 'Ꚑ', + 'ꚓ' => 'Ꚓ', + 'ꚕ' => 'Ꚕ', + 'ꚗ' => 'Ꚗ', + 'ꚙ' => 'Ꚙ', + 'ꚛ' => 'Ꚛ', + 'ꜣ' => 'Ꜣ', + 'ꜥ' => 'Ꜥ', + 'ꜧ' => 'Ꜧ', + 'ꜩ' => 'Ꜩ', + 'ꜫ' => 'Ꜫ', + 'ꜭ' => 'Ꜭ', + 'ꜯ' => 'Ꜯ', + 'ꜳ' => 'Ꜳ', + 'ꜵ' => 'Ꜵ', + 'ꜷ' => 'Ꜷ', + 'ꜹ' => 'Ꜹ', + 'ꜻ' => 'Ꜻ', + 'ꜽ' => 'Ꜽ', + 'ꜿ' => 'Ꜿ', + 'ꝁ' => 'Ꝁ', + 'ꝃ' => 'Ꝃ', + 'ꝅ' => 'Ꝅ', + 'ꝇ' => 'Ꝇ', + 'ꝉ' => 'Ꝉ', + 'ꝋ' => 'Ꝋ', + 'ꝍ' => 'Ꝍ', + 'ꝏ' => 'Ꝏ', + 'ꝑ' => 'Ꝑ', + 'ꝓ' => 'Ꝓ', + 'ꝕ' => 'Ꝕ', + 'ꝗ' => 'Ꝗ', + 'ꝙ' => 'Ꝙ', + 'ꝛ' => 'Ꝛ', + 'ꝝ' => 'Ꝝ', + 'ꝟ' => 'Ꝟ', + 'ꝡ' => 'Ꝡ', + 'ꝣ' => 'Ꝣ', + 'ꝥ' => 'Ꝥ', + 'ꝧ' => 'Ꝧ', + 'ꝩ' => 'Ꝩ', + 'ꝫ' => 'Ꝫ', + 'ꝭ' => 'Ꝭ', + 'ꝯ' => 'Ꝯ', + 'ꝺ' => 'Ꝺ', + 'ꝼ' => 'Ꝼ', + 'ꝿ' => 'Ꝿ', + 'ꞁ' => 'Ꞁ', + 'ꞃ' => 'Ꞃ', + 'ꞅ' => 'Ꞅ', + 'ꞇ' => 'Ꞇ', + 'ꞌ' => 'Ꞌ', + 'ꞑ' => 'Ꞑ', + 'ꞓ' => 'Ꞓ', + 'ꞔ' => 'Ꞔ', + 'ꞗ' => 'Ꞗ', + 'ꞙ' => 'Ꞙ', + 'ꞛ' => 'Ꞛ', + 'ꞝ' => 'Ꞝ', + 'ꞟ' => 'Ꞟ', + 'ꞡ' => 'Ꞡ', + 'ꞣ' => 'Ꞣ', + 'ꞥ' => 'Ꞥ', + 'ꞧ' => 'Ꞧ', + 'ꞩ' => 'Ꞩ', + 'ꞵ' => 'Ꞵ', + 'ꞷ' => 'Ꞷ', + 'ꞹ' => 'Ꞹ', + 'ꞻ' => 'Ꞻ', + 'ꞽ' => 'Ꞽ', + 'ꞿ' => 'Ꞿ', + 'ꟃ' => 'Ꟃ', + 'ꟈ' => 'Ꟈ', + 'ꟊ' => 'Ꟊ', + 'ꟶ' => 'Ꟶ', + 'ꭓ' => 'Ꭓ', + 'ꭰ' => 'Ꭰ', + 'ꭱ' => 'Ꭱ', + 'ꭲ' => 'Ꭲ', + 'ꭳ' => 'Ꭳ', + 'ꭴ' => 'Ꭴ', + 'ꭵ' => 'Ꭵ', + 'ꭶ' => 'Ꭶ', + 'ꭷ' => 'Ꭷ', + 'ꭸ' => 'Ꭸ', + 'ꭹ' => 'Ꭹ', + 'ꭺ' => 'Ꭺ', + 'ꭻ' => 'Ꭻ', + 'ꭼ' => 'Ꭼ', + 'ꭽ' => 'Ꭽ', + 'ꭾ' => 'Ꭾ', + 'ꭿ' => 'Ꭿ', + 'ꮀ' => 'Ꮀ', + 'ꮁ' => 'Ꮁ', + 'ꮂ' => 'Ꮂ', + 'ꮃ' => 'Ꮃ', + 'ꮄ' => 'Ꮄ', + 'ꮅ' => 'Ꮅ', + 'ꮆ' => 'Ꮆ', + 'ꮇ' => 'Ꮇ', + 'ꮈ' => 'Ꮈ', + 'ꮉ' => 'Ꮉ', + 'ꮊ' => 'Ꮊ', + 'ꮋ' => 'Ꮋ', + 'ꮌ' => 'Ꮌ', + 'ꮍ' => 'Ꮍ', + 'ꮎ' => 'Ꮎ', + 'ꮏ' => 'Ꮏ', + 'ꮐ' => 'Ꮐ', + 'ꮑ' => 'Ꮑ', + 'ꮒ' => 'Ꮒ', + 'ꮓ' => 'Ꮓ', + 'ꮔ' => 'Ꮔ', + 'ꮕ' => 'Ꮕ', + 'ꮖ' => 'Ꮖ', + 'ꮗ' => 'Ꮗ', + 'ꮘ' => 'Ꮘ', + 'ꮙ' => 'Ꮙ', + 'ꮚ' => 'Ꮚ', + 'ꮛ' => 'Ꮛ', + 'ꮜ' => 'Ꮜ', + 'ꮝ' => 'Ꮝ', + 'ꮞ' => 'Ꮞ', + 'ꮟ' => 'Ꮟ', + 'ꮠ' => 'Ꮠ', + 'ꮡ' => 'Ꮡ', + 'ꮢ' => 'Ꮢ', + 'ꮣ' => 'Ꮣ', + 'ꮤ' => 'Ꮤ', + 'ꮥ' => 'Ꮥ', + 'ꮦ' => 'Ꮦ', + 'ꮧ' => 'Ꮧ', + 'ꮨ' => 'Ꮨ', + 'ꮩ' => 'Ꮩ', + 'ꮪ' => 'Ꮪ', + 'ꮫ' => 'Ꮫ', + 'ꮬ' => 'Ꮬ', + 'ꮭ' => 'Ꮭ', + 'ꮮ' => 'Ꮮ', + 'ꮯ' => 'Ꮯ', + 'ꮰ' => 'Ꮰ', + 'ꮱ' => 'Ꮱ', + 'ꮲ' => 'Ꮲ', + 'ꮳ' => 'Ꮳ', + 'ꮴ' => 'Ꮴ', + 'ꮵ' => 'Ꮵ', + 'ꮶ' => 'Ꮶ', + 'ꮷ' => 'Ꮷ', + 'ꮸ' => 'Ꮸ', + 'ꮹ' => 'Ꮹ', + 'ꮺ' => 'Ꮺ', + 'ꮻ' => 'Ꮻ', + 'ꮼ' => 'Ꮼ', + 'ꮽ' => 'Ꮽ', + 'ꮾ' => 'Ꮾ', + 'ꮿ' => 'Ꮿ', + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + '𐐨' => '𐐀', + '𐐩' => '𐐁', + '𐐪' => '𐐂', + '𐐫' => '𐐃', + '𐐬' => '𐐄', + '𐐭' => '𐐅', + '𐐮' => '𐐆', + '𐐯' => '𐐇', + '𐐰' => '𐐈', + '𐐱' => '𐐉', + '𐐲' => '𐐊', + '𐐳' => '𐐋', + '𐐴' => '𐐌', + '𐐵' => '𐐍', + '𐐶' => '𐐎', + '𐐷' => '𐐏', + '𐐸' => '𐐐', + '𐐹' => '𐐑', + '𐐺' => '𐐒', + '𐐻' => '𐐓', + '𐐼' => '𐐔', + '𐐽' => '𐐕', + '𐐾' => '𐐖', + '𐐿' => '𐐗', + '𐑀' => '𐐘', + '𐑁' => '𐐙', + '𐑂' => '𐐚', + '𐑃' => '𐐛', + '𐑄' => '𐐜', + '𐑅' => '𐐝', + '𐑆' => '𐐞', + '𐑇' => '𐐟', + '𐑈' => '𐐠', + '𐑉' => '𐐡', + '𐑊' => '𐐢', + '𐑋' => '𐐣', + '𐑌' => '𐐤', + '𐑍' => '𐐥', + '𐑎' => '𐐦', + '𐑏' => '𐐧', + '𐓘' => '𐒰', + '𐓙' => '𐒱', + '𐓚' => '𐒲', + '𐓛' => '𐒳', + '𐓜' => '𐒴', + '𐓝' => '𐒵', + '𐓞' => '𐒶', + '𐓟' => '𐒷', + '𐓠' => '𐒸', + '𐓡' => '𐒹', + '𐓢' => '𐒺', + '𐓣' => '𐒻', + '𐓤' => '𐒼', + '𐓥' => '𐒽', + '𐓦' => '𐒾', + '𐓧' => '𐒿', + '𐓨' => '𐓀', + '𐓩' => '𐓁', + '𐓪' => '𐓂', + '𐓫' => '𐓃', + '𐓬' => '𐓄', + '𐓭' => '𐓅', + '𐓮' => '𐓆', + '𐓯' => '𐓇', + '𐓰' => '𐓈', + '𐓱' => '𐓉', + '𐓲' => '𐓊', + '𐓳' => '𐓋', + '𐓴' => '𐓌', + '𐓵' => '𐓍', + '𐓶' => '𐓎', + '𐓷' => '𐓏', + '𐓸' => '𐓐', + '𐓹' => '𐓑', + '𐓺' => '𐓒', + '𐓻' => '𐓓', + '𐳀' => '𐲀', + '𐳁' => '𐲁', + '𐳂' => '𐲂', + '𐳃' => '𐲃', + '𐳄' => '𐲄', + '𐳅' => '𐲅', + '𐳆' => '𐲆', + '𐳇' => '𐲇', + '𐳈' => '𐲈', + '𐳉' => '𐲉', + '𐳊' => '𐲊', + '𐳋' => '𐲋', + '𐳌' => '𐲌', + '𐳍' => '𐲍', + '𐳎' => '𐲎', + '𐳏' => '𐲏', + '𐳐' => '𐲐', + '𐳑' => '𐲑', + '𐳒' => '𐲒', + '𐳓' => '𐲓', + '𐳔' => '𐲔', + '𐳕' => '𐲕', + '𐳖' => '𐲖', + '𐳗' => '𐲗', + '𐳘' => '𐲘', + '𐳙' => '𐲙', + '𐳚' => '𐲚', + '𐳛' => '𐲛', + '𐳜' => '𐲜', + '𐳝' => '𐲝', + '𐳞' => '𐲞', + '𐳟' => '𐲟', + '𐳠' => '𐲠', + '𐳡' => '𐲡', + '𐳢' => '𐲢', + '𐳣' => '𐲣', + '𐳤' => '𐲤', + '𐳥' => '𐲥', + '𐳦' => '𐲦', + '𐳧' => '𐲧', + '𐳨' => '𐲨', + '𐳩' => '𐲩', + '𐳪' => '𐲪', + '𐳫' => '𐲫', + '𐳬' => '𐲬', + '𐳭' => '𐲭', + '𐳮' => '𐲮', + '𐳯' => '𐲯', + '𐳰' => '𐲰', + '𐳱' => '𐲱', + '𐳲' => '𐲲', + '𑣀' => '𑢠', + '𑣁' => '𑢡', + '𑣂' => '𑢢', + '𑣃' => '𑢣', + '𑣄' => '𑢤', + '𑣅' => '𑢥', + '𑣆' => '𑢦', + '𑣇' => '𑢧', + '𑣈' => '𑢨', + '𑣉' => '𑢩', + '𑣊' => '𑢪', + '𑣋' => '𑢫', + '𑣌' => '𑢬', + '𑣍' => '𑢭', + '𑣎' => '𑢮', + '𑣏' => '𑢯', + '𑣐' => '𑢰', + '𑣑' => '𑢱', + '𑣒' => '𑢲', + '𑣓' => '𑢳', + '𑣔' => '𑢴', + '𑣕' => '𑢵', + '𑣖' => '𑢶', + '𑣗' => '𑢷', + '𑣘' => '𑢸', + '𑣙' => '𑢹', + '𑣚' => '𑢺', + '𑣛' => '𑢻', + '𑣜' => '𑢼', + '𑣝' => '𑢽', + '𑣞' => '𑢾', + '𑣟' => '𑢿', + '𖹠' => '𖹀', + '𖹡' => '𖹁', + '𖹢' => '𖹂', + '𖹣' => '𖹃', + '𖹤' => '𖹄', + '𖹥' => '𖹅', + '𖹦' => '𖹆', + '𖹧' => '𖹇', + '𖹨' => '𖹈', + '𖹩' => '𖹉', + '𖹪' => '𖹊', + '𖹫' => '𖹋', + '𖹬' => '𖹌', + '𖹭' => '𖹍', + '𖹮' => '𖹎', + '𖹯' => '𖹏', + '𖹰' => '𖹐', + '𖹱' => '𖹑', + '𖹲' => '𖹒', + '𖹳' => '𖹓', + '𖹴' => '𖹔', + '𖹵' => '𖹕', + '𖹶' => '𖹖', + '𖹷' => '𖹗', + '𖹸' => '𖹘', + '𖹹' => '𖹙', + '𖹺' => '𖹚', + '𖹻' => '𖹛', + '𖹼' => '𖹜', + '𖹽' => '𖹝', + '𖹾' => '𖹞', + '𖹿' => '𖹟', + '𞤢' => '𞤀', + '𞤣' => '𞤁', + '𞤤' => '𞤂', + '𞤥' => '𞤃', + '𞤦' => '𞤄', + '𞤧' => '𞤅', + '𞤨' => '𞤆', + '𞤩' => '𞤇', + '𞤪' => '𞤈', + '𞤫' => '𞤉', + '𞤬' => '𞤊', + '𞤭' => '𞤋', + '𞤮' => '𞤌', + '𞤯' => '𞤍', + '𞤰' => '𞤎', + '𞤱' => '𞤏', + '𞤲' => '𞤐', + '𞤳' => '𞤑', + '𞤴' => '𞤒', + '𞤵' => '𞤓', + '𞤶' => '𞤔', + '𞤷' => '𞤕', + '𞤸' => '𞤖', + '𞤹' => '𞤗', + '𞤺' => '𞤘', + '𞤻' => '𞤙', + '𞤼' => '𞤚', + '𞤽' => '𞤛', + '𞤾' => '𞤜', + '𞤿' => '𞤝', + '𞥀' => '𞤞', + '𞥁' => '𞤟', + '𞥂' => '𞤠', + '𞥃' => '𞤡', + 'ß' => 'SS', + 'ff' => 'FF', + 'fi' => 'FI', + 'fl' => 'FL', + 'ffi' => 'FFI', + 'ffl' => 'FFL', + 'ſt' => 'ST', + 'st' => 'ST', + 'և' => 'ԵՒ', + 'ﬓ' => 'ՄՆ', + 'ﬔ' => 'ՄԵ', + 'ﬕ' => 'ՄԻ', + 'ﬖ' => 'ՎՆ', + 'ﬗ' => 'ՄԽ', + 'ʼn' => 'ʼN', + 'ΐ' => 'Ϊ́', + 'ΰ' => 'Ϋ́', + 'ǰ' => 'J̌', + 'ẖ' => 'H̱', + 'ẗ' => 'T̈', + 'ẘ' => 'W̊', + 'ẙ' => 'Y̊', + 'ẚ' => 'Aʾ', + 'ὐ' => 'Υ̓', + 'ὒ' => 'Υ̓̀', + 'ὔ' => 'Υ̓́', + 'ὖ' => 'Υ̓͂', + 'ᾶ' => 'Α͂', + 'ῆ' => 'Η͂', + 'ῒ' => 'Ϊ̀', + 'ΐ' => 'Ϊ́', + 'ῖ' => 'Ι͂', + 'ῗ' => 'Ϊ͂', + 'ῢ' => 'Ϋ̀', + 'ΰ' => 'Ϋ́', + 'ῤ' => 'Ρ̓', + 'ῦ' => 'Υ͂', + 'ῧ' => 'Ϋ͂', + 'ῶ' => 'Ω͂', + 'ᾈ' => 'ἈΙ', + 'ᾉ' => 'ἉΙ', + 'ᾊ' => 'ἊΙ', + 'ᾋ' => 'ἋΙ', + 'ᾌ' => 'ἌΙ', + 'ᾍ' => 'ἍΙ', + 'ᾎ' => 'ἎΙ', + 'ᾏ' => 'ἏΙ', + 'ᾘ' => 'ἨΙ', + 'ᾙ' => 'ἩΙ', + 'ᾚ' => 'ἪΙ', + 'ᾛ' => 'ἫΙ', + 'ᾜ' => 'ἬΙ', + 'ᾝ' => 'ἭΙ', + 'ᾞ' => 'ἮΙ', + 'ᾟ' => 'ἯΙ', + 'ᾨ' => 'ὨΙ', + 'ᾩ' => 'ὩΙ', + 'ᾪ' => 'ὪΙ', + 'ᾫ' => 'ὫΙ', + 'ᾬ' => 'ὬΙ', + 'ᾭ' => 'ὭΙ', + 'ᾮ' => 'ὮΙ', + 'ᾯ' => 'ὯΙ', + 'ᾼ' => 'ΑΙ', + 'ῌ' => 'ΗΙ', + 'ῼ' => 'ΩΙ', + 'ᾲ' => 'ᾺΙ', + 'ᾴ' => 'ΆΙ', + 'ῂ' => 'ῊΙ', + 'ῄ' => 'ΉΙ', + 'ῲ' => 'ῺΙ', + 'ῴ' => 'ΏΙ', + 'ᾷ' => 'Α͂Ι', + 'ῇ' => 'Η͂Ι', + 'ῷ' => 'Ω͂Ι', +); diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-mbstring/bootstrap.php new file mode 100644 index 0000000..ecf1a03 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/bootstrap.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language($language = null) { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); } +} + +if (!function_exists('mb_str_pad')) { + function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/bootstrap80.php b/php/libraries/composer/vendor/symfony/polyfill-mbstring/bootstrap80.php new file mode 100644 index 0000000..2f9fb5b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/bootstrap80.php @@ -0,0 +1,147 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info(?string $type = 'all'): array|string|int|false { return p\Mbstring::mb_get_info((string) $type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub(?string $string, ?string $encoding = null): string { $encoding ??= mb_internal_encoding(); return mb_convert_encoding((string) $string, $encoding, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); } +} + +if (!function_exists('mb_str_pad')) { + function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-mbstring/composer.json b/php/libraries/composer/vendor/symfony/polyfill-mbstring/composer.json new file mode 100644 index 0000000..bd99d4b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-mbstring/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/polyfill-mbstring", + "type": "library", + "description": "Symfony polyfill for the Mbstring extension", + "keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php72/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-php72/LICENSE new file mode 100644 index 0000000..6e3afce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php72/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-php72/Php72.php b/php/libraries/composer/vendor/symfony/polyfill-php72/Php72.php new file mode 100644 index 0000000..7bf96c9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php72/Php72.php @@ -0,0 +1,217 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php72; + +/** + * @author Nicolas Grekas + * @author Dariusz Rumiński + * + * @internal + */ +final class Php72 +{ + private static $hashMask; + + public static function utf8_encode($s) + { + $s .= $s; + $len = \strlen($s); + + for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) { + switch (true) { + case $s[$i] < "\x80": $s[$j] = $s[$i]; break; + case $s[$i] < "\xC0": $s[$j] = "\xC2"; $s[++$j] = $s[$i]; break; + default: $s[$j] = "\xC3"; $s[++$j] = \chr(\ord($s[$i]) - 64); break; + } + } + + return substr($s, 0, $j); + } + + public static function utf8_decode($s) + { + $s = (string) $s; + $len = \strlen($s); + + for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) { + switch ($s[$i] & "\xF0") { + case "\xC0": + case "\xD0": + $c = (\ord($s[$i] & "\x1F") << 6) | \ord($s[++$i] & "\x3F"); + $s[$j] = $c < 256 ? \chr($c) : '?'; + break; + + case "\xF0": + ++$i; + // no break + + case "\xE0": + $s[$j] = '?'; + $i += 2; + break; + + default: + $s[$j] = $s[$i]; + } + } + + return substr($s, 0, $j); + } + + public static function php_os_family() + { + if ('\\' === \DIRECTORY_SEPARATOR) { + return 'Windows'; + } + + $map = [ + 'Darwin' => 'Darwin', + 'DragonFly' => 'BSD', + 'FreeBSD' => 'BSD', + 'NetBSD' => 'BSD', + 'OpenBSD' => 'BSD', + 'Linux' => 'Linux', + 'SunOS' => 'Solaris', + ]; + + return $map[\PHP_OS] ?? 'Unknown'; + } + + public static function spl_object_id($object) + { + if (null === self::$hashMask) { + self::initHashMask(); + } + if (null === $hash = spl_object_hash($object)) { + return; + } + + // On 32-bit systems, PHP_INT_SIZE is 4, + return self::$hashMask ^ hexdec(substr($hash, 16 - (\PHP_INT_SIZE * 2 - 1), \PHP_INT_SIZE * 2 - 1)); + } + + public static function sapi_windows_vt100_support($stream, $enable = null) + { + if (!\is_resource($stream)) { + trigger_error('sapi_windows_vt100_support() expects parameter 1 to be resource, '.\gettype($stream).' given', \E_USER_WARNING); + + return false; + } + + $meta = stream_get_meta_data($stream); + + if ('STDIO' !== $meta['stream_type']) { + trigger_error('sapi_windows_vt100_support() was not able to analyze the specified stream', \E_USER_WARNING); + + return false; + } + + // We cannot actually disable vt100 support if it is set + if (false === $enable || !self::stream_isatty($stream)) { + return false; + } + + // The native function does not apply to stdin + $meta = array_map('strtolower', $meta); + $stdin = 'php://stdin' === $meta['uri'] || 'php://fd/0' === $meta['uri']; + + return !$stdin + && (false !== getenv('ANSICON') + || 'ON' === getenv('ConEmuANSI') + || 'xterm' === getenv('TERM') + || 'Hyper' === getenv('TERM_PROGRAM')); + } + + public static function stream_isatty($stream) + { + if (!\is_resource($stream)) { + trigger_error('stream_isatty() expects parameter 1 to be resource, '.\gettype($stream).' given', \E_USER_WARNING); + + return false; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + $stat = @fstat($stream); + // Check if formatted mode is S_IFCHR + return $stat ? 0020000 === ($stat['mode'] & 0170000) : false; + } + + return \function_exists('posix_isatty') && @posix_isatty($stream); + } + + private static function initHashMask() + { + $obj = (object) []; + self::$hashMask = -1; + + // check if we are nested in an output buffering handler to prevent a fatal error with ob_start() below + $obFuncs = ['ob_clean', 'ob_end_clean', 'ob_flush', 'ob_end_flush', 'ob_get_contents', 'ob_get_flush']; + foreach (debug_backtrace(\PHP_VERSION_ID >= 50400 ? \DEBUG_BACKTRACE_IGNORE_ARGS : false) as $frame) { + if (isset($frame['function'][0]) && !isset($frame['class']) && 'o' === $frame['function'][0] && \in_array($frame['function'], $obFuncs)) { + $frame['line'] = 0; + break; + } + } + if (!empty($frame['line'])) { + ob_start(); + debug_zval_dump($obj); + self::$hashMask = (int) substr(ob_get_clean(), 17); + } + + self::$hashMask ^= hexdec(substr(spl_object_hash($obj), 16 - (\PHP_INT_SIZE * 2 - 1), \PHP_INT_SIZE * 2 - 1)); + } + + public static function mb_chr($code, $encoding = null) + { + if (0x80 > $code %= 0x200000) { + $s = \chr($code); + } elseif (0x800 > $code) { + $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + + if ('UTF-8' !== $encoding = $encoding ?? mb_internal_encoding()) { + $s = mb_convert_encoding($s, $encoding, 'UTF-8'); + } + + return $s; + } + + public static function mb_ord($s, $encoding = null) + { + if (null === $encoding) { + $s = mb_convert_encoding($s, 'UTF-8'); + } elseif ('UTF-8' !== $encoding) { + $s = mb_convert_encoding($s, 'UTF-8', $encoding); + } + + if (1 === \strlen($s)) { + return \ord($s); + } + + $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; + if (0xF0 <= $code) { + return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; + } + if (0xE0 <= $code) { + return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; + } + if (0xC0 <= $code) { + return (($code - 0xC0) << 6) + $s[2] - 0x80; + } + + return $code; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php72/README.md b/php/libraries/composer/vendor/symfony/polyfill-php72/README.md new file mode 100644 index 0000000..ed19050 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php72/README.md @@ -0,0 +1,35 @@ +Symfony Polyfill / Php72 +======================== + +This component provides functions added to PHP 7.2 core: + +- [`spl_object_id`](https://php.net/spl_object_id) +- [`stream_isatty`](https://php.net/stream_isatty) + +And also functions added to PHP 7.2 mbstring: + +- [`mb_ord`](https://php.net/mb_ord) +- [`mb_chr`](https://php.net/mb_chr) +- [`mb_scrub`](https://php.net/mb_scrub) + +On Windows only: + +- [`sapi_windows_vt100_support`](https://php.net/sapi_windows_vt100_support) + +Moved to core since 7.2 (was in the optional XML extension earlier): + +- [`utf8_encode`](https://php.net/utf8_encode) +- [`utf8_decode`](https://php.net/utf8_decode) + +Also, it provides constants added to PHP 7.2: + +- [`PHP_FLOAT_*`](https://php.net/reserved.constants#constant.php-float-dig) +- [`PHP_OS_FAMILY`](https://php.net/reserved.constants#constant.php-os-family) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-php72/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-php72/bootstrap.php new file mode 100644 index 0000000..b5c92d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php72/bootstrap.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php72 as p; + +if (\PHP_VERSION_ID >= 70200) { + return; +} + +if (!defined('PHP_FLOAT_DIG')) { + define('PHP_FLOAT_DIG', 15); +} +if (!defined('PHP_FLOAT_EPSILON')) { + define('PHP_FLOAT_EPSILON', 2.2204460492503E-16); +} +if (!defined('PHP_FLOAT_MIN')) { + define('PHP_FLOAT_MIN', 2.2250738585072E-308); +} +if (!defined('PHP_FLOAT_MAX')) { + define('PHP_FLOAT_MAX', 1.7976931348623157E+308); +} +if (!defined('PHP_OS_FAMILY')) { + define('PHP_OS_FAMILY', p\Php72::php_os_family()); +} + +if ('\\' === \DIRECTORY_SEPARATOR && !function_exists('sapi_windows_vt100_support')) { + function sapi_windows_vt100_support($stream, $enable = null) { return p\Php72::sapi_windows_vt100_support($stream, $enable); } +} +if (!function_exists('stream_isatty')) { + function stream_isatty($stream) { return p\Php72::stream_isatty($stream); } +} +if (!function_exists('utf8_encode')) { + function utf8_encode($string) { return p\Php72::utf8_encode($string); } +} +if (!function_exists('utf8_decode')) { + function utf8_decode($string) { return p\Php72::utf8_decode($string); } +} +if (!function_exists('spl_object_id')) { + function spl_object_id($object) { return p\Php72::spl_object_id($object); } +} +if (!function_exists('mb_ord')) { + function mb_ord($string, $encoding = null) { return p\Php72::mb_ord($string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr($codepoint, $encoding = null) { return p\Php72::mb_chr($codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php72/composer.json b/php/libraries/composer/vendor/symfony/polyfill-php72/composer.json new file mode 100644 index 0000000..1882576 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php72/composer.json @@ -0,0 +1,32 @@ +{ + "name": "symfony/polyfill-php72", + "type": "library", + "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php72\\": "" }, + "files": [ "bootstrap.php" ] + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php73/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-php73/LICENSE new file mode 100644 index 0000000..7536cae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php73/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-php73/Php73.php b/php/libraries/composer/vendor/symfony/polyfill-php73/Php73.php new file mode 100644 index 0000000..65c35a6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php73/Php73.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php73; + +/** + * @author Gabriel Caruso + * @author Ion Bazan + * + * @internal + */ +final class Php73 +{ + public static $startAt = 1533462603; + + /** + * @param bool $asNum + * + * @return array|float|int + */ + public static function hrtime($asNum = false) + { + $ns = microtime(false); + $s = substr($ns, 11) - self::$startAt; + $ns = 1E9 * (float) $ns; + + if ($asNum) { + $ns += $s * 1E9; + + return \PHP_INT_SIZE === 4 ? $ns : (int) $ns; + } + + return [$s, (int) $ns]; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php73/README.md b/php/libraries/composer/vendor/symfony/polyfill-php73/README.md new file mode 100644 index 0000000..032fafb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php73/README.md @@ -0,0 +1,18 @@ +Symfony Polyfill / Php73 +======================== + +This component provides functions added to PHP 7.3 core: + +- [`array_key_first`](https://php.net/array_key_first) +- [`array_key_last`](https://php.net/array_key_last) +- [`hrtime`](https://php.net/function.hrtime) +- [`is_countable`](https://php.net/is_countable) +- [`JsonException`](https://php.net/JsonException) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-php73/Resources/stubs/JsonException.php b/php/libraries/composer/vendor/symfony/polyfill-php73/Resources/stubs/JsonException.php new file mode 100644 index 0000000..f06d6c2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php73/Resources/stubs/JsonException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 70300) { + class JsonException extends Exception + { + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php73/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-php73/bootstrap.php new file mode 100644 index 0000000..d6b2153 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php73/bootstrap.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php73 as p; + +if (\PHP_VERSION_ID >= 70300) { + return; +} + +if (!function_exists('is_countable')) { + function is_countable($value) { return is_array($value) || $value instanceof Countable || $value instanceof ResourceBundle || $value instanceof SimpleXmlElement; } +} +if (!function_exists('hrtime')) { + require_once __DIR__.'/Php73.php'; + p\Php73::$startAt = (int) microtime(true); + function hrtime($as_number = false) { return p\Php73::hrtime($as_number); } +} +if (!function_exists('array_key_first')) { + function array_key_first(array $array) { foreach ($array as $key => $value) { return $key; } } +} +if (!function_exists('array_key_last')) { + function array_key_last(array $array) { return key(array_slice($array, -1, 1, true)); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php73/composer.json b/php/libraries/composer/vendor/symfony/polyfill-php73/composer.json new file mode 100644 index 0000000..3d47d15 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php73/composer.json @@ -0,0 +1,33 @@ +{ + "name": "symfony/polyfill-php73", + "type": "library", + "description": "Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php73\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/LICENSE b/php/libraries/composer/vendor/symfony/polyfill-php80/LICENSE new file mode 100644 index 0000000..0ed3a24 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/Php80.php b/php/libraries/composer/vendor/symfony/polyfill-php80/Php80.php new file mode 100644 index 0000000..362dd1a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/Php80.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Ion Bazan + * @author Nico Oelgart + * @author Nicolas Grekas + * + * @internal + */ +final class Php80 +{ + public static function fdiv(float $dividend, float $divisor): float + { + return @($dividend / $divisor); + } + + public static function get_debug_type($value): string + { + switch (true) { + case null === $value: return 'null'; + case \is_bool($value): return 'bool'; + case \is_string($value): return 'string'; + case \is_array($value): return 'array'; + case \is_int($value): return 'int'; + case \is_float($value): return 'float'; + case \is_object($value): break; + case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class'; + default: + if (null === $type = @get_resource_type($value)) { + return 'unknown'; + } + + if ('Unknown' === $type) { + $type = 'closed'; + } + + return "resource ($type)"; + } + + $class = \get_class($value); + + if (false === strpos($class, '@')) { + return $class; + } + + return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous'; + } + + public static function get_resource_id($res): int + { + if (!\is_resource($res) && null === @get_resource_type($res)) { + throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res))); + } + + return (int) $res; + } + + public static function preg_last_error_msg(): string + { + switch (preg_last_error()) { + case \PREG_INTERNAL_ERROR: + return 'Internal error'; + case \PREG_BAD_UTF8_ERROR: + return 'Malformed UTF-8 characters, possibly incorrectly encoded'; + case \PREG_BAD_UTF8_OFFSET_ERROR: + return 'The offset did not correspond to the beginning of a valid UTF-8 code point'; + case \PREG_BACKTRACK_LIMIT_ERROR: + return 'Backtrack limit exhausted'; + case \PREG_RECURSION_LIMIT_ERROR: + return 'Recursion limit exhausted'; + case \PREG_JIT_STACKLIMIT_ERROR: + return 'JIT stack limit exhausted'; + case \PREG_NO_ERROR: + return 'No error'; + default: + return 'Unknown error'; + } + } + + public static function str_contains(string $haystack, string $needle): bool + { + return '' === $needle || false !== strpos($haystack, $needle); + } + + public static function str_starts_with(string $haystack, string $needle): bool + { + return 0 === strncmp($haystack, $needle, \strlen($needle)); + } + + public static function str_ends_with(string $haystack, string $needle): bool + { + if ('' === $needle || $needle === $haystack) { + return true; + } + + if ('' === $haystack) { + return false; + } + + $needleLength = \strlen($needle); + + return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength); + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/PhpToken.php b/php/libraries/composer/vendor/symfony/polyfill-php80/PhpToken.php new file mode 100644 index 0000000..fe6e691 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/PhpToken.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Fedonyuk Anton + * + * @internal + */ +class PhpToken implements \Stringable +{ + /** + * @var int + */ + public $id; + + /** + * @var string + */ + public $text; + + /** + * @var int + */ + public $line; + + /** + * @var int + */ + public $pos; + + public function __construct(int $id, string $text, int $line = -1, int $position = -1) + { + $this->id = $id; + $this->text = $text; + $this->line = $line; + $this->pos = $position; + } + + public function getTokenName(): ?string + { + if ('UNKNOWN' === $name = token_name($this->id)) { + $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text; + } + + return $name; + } + + /** + * @param int|string|array $kind + */ + public function is($kind): bool + { + foreach ((array) $kind as $value) { + if (\in_array($value, [$this->id, $this->text], true)) { + return true; + } + } + + return false; + } + + public function isIgnorable(): bool + { + return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true); + } + + public function __toString(): string + { + return (string) $this->text; + } + + /** + * @return static[] + */ + public static function tokenize(string $code, int $flags = 0): array + { + $line = 1; + $position = 0; + $tokens = token_get_all($code, $flags); + foreach ($tokens as $index => $token) { + if (\is_string($token)) { + $id = \ord($token); + $text = $token; + } else { + [$id, $text, $line] = $token; + } + $tokens[$index] = new static($id, $text, $line, $position); + $position += \strlen($text); + } + + return $tokens; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/README.md b/php/libraries/composer/vendor/symfony/polyfill-php80/README.md new file mode 100644 index 0000000..3816c55 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/README.md @@ -0,0 +1,25 @@ +Symfony Polyfill / Php80 +======================== + +This component provides features added to PHP 8.0 core: + +- [`Stringable`](https://php.net/stringable) interface +- [`fdiv`](https://php.net/fdiv) +- [`ValueError`](https://php.net/valueerror) class +- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class +- `FILTER_VALIDATE_BOOL` constant +- [`get_debug_type`](https://php.net/get_debug_type) +- [`PhpToken`](https://php.net/phptoken) class +- [`preg_last_error_msg`](https://php.net/preg_last_error_msg) +- [`str_contains`](https://php.net/str_contains) +- [`str_starts_with`](https://php.net/str_starts_with) +- [`str_ends_with`](https://php.net/str_ends_with) +- [`get_resource_id`](https://php.net/get_resource_id) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php new file mode 100644 index 0000000..2b95542 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#[Attribute(Attribute::TARGET_CLASS)] +final class Attribute +{ + public const TARGET_CLASS = 1; + public const TARGET_FUNCTION = 2; + public const TARGET_METHOD = 4; + public const TARGET_PROPERTY = 8; + public const TARGET_CLASS_CONSTANT = 16; + public const TARGET_PARAMETER = 32; + public const TARGET_ALL = 63; + public const IS_REPEATABLE = 64; + + /** @var int */ + public $flags; + + public function __construct(int $flags = self::TARGET_ALL) + { + $this->flags = $flags; + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php new file mode 100644 index 0000000..bd1212f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) { + class PhpToken extends Symfony\Polyfill\Php80\PhpToken + { + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php new file mode 100644 index 0000000..7c62d75 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + interface Stringable + { + /** + * @return string + */ + public function __toString(); + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php new file mode 100644 index 0000000..01c6c6c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class UnhandledMatchError extends Error + { + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php new file mode 100644 index 0000000..783dbc2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class ValueError extends Error + { + } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/bootstrap.php b/php/libraries/composer/vendor/symfony/polyfill-php80/bootstrap.php new file mode 100644 index 0000000..e5f7dbc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/bootstrap.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php80 as p; + +if (\PHP_VERSION_ID >= 80000) { + return; +} + +if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) { + define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN); +} + +if (!function_exists('fdiv')) { + function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); } +} +if (!function_exists('preg_last_error_msg')) { + function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); } +} +if (!function_exists('str_contains')) { + function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_starts_with')) { + function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_ends_with')) { + function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('get_debug_type')) { + function get_debug_type($value): string { return p\Php80::get_debug_type($value); } +} +if (!function_exists('get_resource_id')) { + function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); } +} diff --git a/php/libraries/composer/vendor/symfony/polyfill-php80/composer.json b/php/libraries/composer/vendor/symfony/polyfill-php80/composer.json new file mode 100644 index 0000000..46ccde2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/polyfill-php80/composer.json @@ -0,0 +1,37 @@ +{ + "name": "symfony/polyfill-php80", + "type": "library", + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php80\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/process/CHANGELOG.md b/php/libraries/composer/vendor/symfony/process/CHANGELOG.md new file mode 100644 index 0000000..31b9ee6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/CHANGELOG.md @@ -0,0 +1,116 @@ +CHANGELOG +========= + +5.2.0 +----- + + * added `Process::setOptions()` to set `Process` specific options + * added option `create_new_console` to allow a subprocess to continue + to run after the main script exited, both on Linux and on Windows + +5.1.0 +----- + + * added `Process::getStartTime()` to retrieve the start time of the process as float + +5.0.0 +----- + + * removed `Process::inheritEnvironmentVariables()` + * removed `PhpProcess::setPhpBinary()` + * `Process` must be instantiated with a command array, use `Process::fromShellCommandline()` when the command should be parsed by the shell + * removed `Process::setCommandLine()` + +4.4.0 +----- + + * deprecated `Process::inheritEnvironmentVariables()`: env variables are always inherited. + * added `Process::getLastOutputTime()` method + +4.2.0 +----- + + * added the `Process::fromShellCommandline()` to run commands in a shell wrapper + * deprecated passing a command as string when creating a `Process` instance + * deprecated the `Process::setCommandline()` and the `PhpProcess::setPhpBinary()` methods + * added the `Process::waitUntil()` method to wait for the process only for a + specific output, then continue the normal execution of your application + +4.1.0 +----- + + * added the `Process::isTtySupported()` method that allows to check for TTY support + * made `PhpExecutableFinder` look for the `PHP_BINARY` env var when searching the php binary + * added the `ProcessSignaledException` class to properly catch signaled process errors + +4.0.0 +----- + + * environment variables will always be inherited + * added a second `array $env = []` argument to the `start()`, `run()`, + `mustRun()`, and `restart()` methods of the `Process` class + * added a second `array $env = []` argument to the `start()` method of the + `PhpProcess` class + * the `ProcessUtils::escapeArgument()` method has been removed + * the `areEnvironmentVariablesInherited()`, `getOptions()`, and `setOptions()` + methods of the `Process` class have been removed + * support for passing `proc_open()` options has been removed + * removed the `ProcessBuilder` class, use the `Process` class instead + * removed the `getEnhanceWindowsCompatibility()` and `setEnhanceWindowsCompatibility()` methods of the `Process` class + * passing a not existing working directory to the constructor of the `Symfony\Component\Process\Process` class is not + supported anymore + +3.4.0 +----- + + * deprecated the ProcessBuilder class + * deprecated calling `Process::start()` without setting a valid working directory beforehand (via `setWorkingDirectory()` or constructor) + +3.3.0 +----- + + * added command line arrays in the `Process` class + * added `$env` argument to `Process::start()`, `run()`, `mustRun()` and `restart()` methods + * deprecated the `ProcessUtils::escapeArgument()` method + * deprecated not inheriting environment variables + * deprecated configuring `proc_open()` options + * deprecated configuring enhanced Windows compatibility + * deprecated configuring enhanced sigchild compatibility + +2.5.0 +----- + + * added support for PTY mode + * added the convenience method "mustRun" + * deprecation: Process::setStdin() is deprecated in favor of Process::setInput() + * deprecation: Process::getStdin() is deprecated in favor of Process::getInput() + * deprecation: Process::setInput() and ProcessBuilder::setInput() do not accept non-scalar types + +2.4.0 +----- + + * added the ability to define an idle timeout + +2.3.0 +----- + + * added ProcessUtils::escapeArgument() to fix the bug in escapeshellarg() function on Windows + * added Process::signal() + * added Process::getPid() + * added support for a TTY mode + +2.2.0 +----- + + * added ProcessBuilder::setArguments() to reset the arguments on a builder + * added a way to retrieve the standard and error output incrementally + * added Process:restart() + +2.1.0 +----- + + * added support for non-blocking processes (start(), wait(), isRunning(), stop()) + * enhanced Windows compatibility + * added Process::getExitCodeText() that returns a string representation for + the exit code returned by the process + * added ProcessBuilder diff --git a/php/libraries/composer/vendor/symfony/process/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/process/Exception/ExceptionInterface.php new file mode 100644 index 0000000..bd4a604 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * Marker Interface for the Process Component. + * + * @author Johannes M. Schmitt + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/process/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/symfony/process/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..926ee21 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/InvalidArgumentException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * InvalidArgumentException for the Process Component. + * + * @author Romain Neutron + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/process/Exception/LogicException.php b/php/libraries/composer/vendor/symfony/process/Exception/LogicException.php new file mode 100644 index 0000000..be3d490 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/LogicException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * LogicException for the Process Component. + * + * @author Romain Neutron + */ +class LogicException extends \LogicException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/process/Exception/ProcessFailedException.php b/php/libraries/composer/vendor/symfony/process/Exception/ProcessFailedException.php new file mode 100644 index 0000000..328acfd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/ProcessFailedException.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Process; + +/** + * Exception for failed processes. + * + * @author Johannes M. Schmitt + */ +class ProcessFailedException extends RuntimeException +{ + private $process; + + public function __construct(Process $process) + { + if ($process->isSuccessful()) { + throw new InvalidArgumentException('Expected a failed process, but the given process was successful.'); + } + + $error = sprintf('The command "%s" failed.'."\n\nExit Code: %s(%s)\n\nWorking directory: %s", + $process->getCommandLine(), + $process->getExitCode(), + $process->getExitCodeText(), + $process->getWorkingDirectory() + ); + + if (!$process->isOutputDisabled()) { + $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s", + $process->getOutput(), + $process->getErrorOutput() + ); + } + + parent::__construct($error); + + $this->process = $process; + } + + public function getProcess() + { + return $this->process; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Exception/ProcessSignaledException.php b/php/libraries/composer/vendor/symfony/process/Exception/ProcessSignaledException.php new file mode 100644 index 0000000..d4d3227 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/ProcessSignaledException.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Process; + +/** + * Exception that is thrown when a process has been signaled. + * + * @author Sullivan Senechal + */ +final class ProcessSignaledException extends RuntimeException +{ + private $process; + + public function __construct(Process $process) + { + $this->process = $process; + + parent::__construct(sprintf('The process has been signaled with signal "%s".', $process->getTermSignal())); + } + + public function getProcess(): Process + { + return $this->process; + } + + public function getSignal(): int + { + return $this->getProcess()->getTermSignal(); + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Exception/ProcessTimedOutException.php b/php/libraries/composer/vendor/symfony/process/Exception/ProcessTimedOutException.php new file mode 100644 index 0000000..94391a4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/ProcessTimedOutException.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Process; + +/** + * Exception that is thrown when a process times out. + * + * @author Johannes M. Schmitt + */ +class ProcessTimedOutException extends RuntimeException +{ + public const TYPE_GENERAL = 1; + public const TYPE_IDLE = 2; + + private $process; + private $timeoutType; + + public function __construct(Process $process, int $timeoutType) + { + $this->process = $process; + $this->timeoutType = $timeoutType; + + parent::__construct(sprintf( + 'The process "%s" exceeded the timeout of %s seconds.', + $process->getCommandLine(), + $this->getExceededTimeout() + )); + } + + public function getProcess() + { + return $this->process; + } + + public function isGeneralTimeout() + { + return self::TYPE_GENERAL === $this->timeoutType; + } + + public function isIdleTimeout() + { + return self::TYPE_IDLE === $this->timeoutType; + } + + public function getExceededTimeout() + { + switch ($this->timeoutType) { + case self::TYPE_GENERAL: + return $this->process->getTimeout(); + + case self::TYPE_IDLE: + return $this->process->getIdleTimeout(); + + default: + throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType)); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Exception/RuntimeException.php b/php/libraries/composer/vendor/symfony/process/Exception/RuntimeException.php new file mode 100644 index 0000000..adead25 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Exception/RuntimeException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * RuntimeException for the Process Component. + * + * @author Johannes M. Schmitt + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/process/ExecutableFinder.php b/php/libraries/composer/vendor/symfony/process/ExecutableFinder.php new file mode 100644 index 0000000..f392c96 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/ExecutableFinder.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +/** + * Generic executable finder. + * + * @author Fabien Potencier + * @author Johannes M. Schmitt + */ +class ExecutableFinder +{ + private $suffixes = ['.exe', '.bat', '.cmd', '.com']; + + /** + * Replaces default suffixes of executable. + */ + public function setSuffixes(array $suffixes) + { + $this->suffixes = $suffixes; + } + + /** + * Adds new possible suffix to check for executable. + */ + public function addSuffix(string $suffix) + { + $this->suffixes[] = $suffix; + } + + /** + * Finds an executable by name. + * + * @param string $name The executable name (without the extension) + * @param string|null $default The default to return if no executable is found + * @param array $extraDirs Additional dirs to check into + * + * @return string|null + */ + public function find(string $name, ?string $default = null, array $extraDirs = []) + { + if (\ini_get('open_basedir')) { + $searchPath = array_merge(explode(\PATH_SEPARATOR, \ini_get('open_basedir')), $extraDirs); + $dirs = []; + foreach ($searchPath as $path) { + // Silencing against https://bugs.php.net/69240 + if (@is_dir($path)) { + $dirs[] = $path; + } else { + if (basename($path) == $name && @is_executable($path)) { + return $path; + } + } + } + } else { + $dirs = array_merge( + explode(\PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')), + $extraDirs + ); + } + + $suffixes = ['']; + if ('\\' === \DIRECTORY_SEPARATOR) { + $pathExt = getenv('PATHEXT'); + $suffixes = array_merge($pathExt ? explode(\PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes); + } + foreach ($suffixes as $suffix) { + foreach ($dirs as $dir) { + if (@is_file($file = $dir.\DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === \DIRECTORY_SEPARATOR || @is_executable($file))) { + return $file; + } + } + } + + return $default; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/InputStream.php b/php/libraries/composer/vendor/symfony/process/InputStream.php new file mode 100644 index 0000000..0c45b52 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/InputStream.php @@ -0,0 +1,96 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\RuntimeException; + +/** + * Provides a way to continuously write to the input of a Process until the InputStream is closed. + * + * @author Nicolas Grekas + * + * @implements \IteratorAggregate + */ +class InputStream implements \IteratorAggregate +{ + /** @var callable|null */ + private $onEmpty = null; + private $input = []; + private $open = true; + + /** + * Sets a callback that is called when the write buffer becomes empty. + */ + public function onEmpty(?callable $onEmpty = null) + { + $this->onEmpty = $onEmpty; + } + + /** + * Appends an input to the write buffer. + * + * @param resource|string|int|float|bool|\Traversable|null $input The input to append as scalar, + * stream resource or \Traversable + */ + public function write($input) + { + if (null === $input) { + return; + } + if ($this->isClosed()) { + throw new RuntimeException(sprintf('"%s" is closed.', static::class)); + } + $this->input[] = ProcessUtils::validateInput(__METHOD__, $input); + } + + /** + * Closes the write buffer. + */ + public function close() + { + $this->open = false; + } + + /** + * Tells whether the write buffer is closed or not. + */ + public function isClosed() + { + return !$this->open; + } + + /** + * @return \Traversable + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + $this->open = true; + + while ($this->open || $this->input) { + if (!$this->input) { + yield ''; + continue; + } + $current = array_shift($this->input); + + if ($current instanceof \Iterator) { + yield from $current; + } else { + yield $current; + } + if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) { + $this->write($onEmpty($this)); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/process/LICENSE b/php/libraries/composer/vendor/symfony/process/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/process/PhpExecutableFinder.php b/php/libraries/composer/vendor/symfony/process/PhpExecutableFinder.php new file mode 100644 index 0000000..45dbcca --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/PhpExecutableFinder.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +/** + * An executable finder specifically designed for the PHP executable. + * + * @author Fabien Potencier + * @author Johannes M. Schmitt + */ +class PhpExecutableFinder +{ + private $executableFinder; + + public function __construct() + { + $this->executableFinder = new ExecutableFinder(); + } + + /** + * Finds The PHP executable. + * + * @return string|false + */ + public function find(bool $includeArgs = true) + { + if ($php = getenv('PHP_BINARY')) { + if (!is_executable($php)) { + $command = '\\' === \DIRECTORY_SEPARATOR ? 'where' : 'command -v --'; + if ($php = strtok(exec($command.' '.escapeshellarg($php)), \PHP_EOL)) { + if (!is_executable($php)) { + return false; + } + } else { + return false; + } + } + + if (@is_dir($php)) { + return false; + } + + return $php; + } + + $args = $this->findArguments(); + $args = $includeArgs && $args ? ' '.implode(' ', $args) : ''; + + // PHP_BINARY return the current sapi executable + if (\PHP_BINARY && \in_array(\PHP_SAPI, ['cli', 'cli-server', 'phpdbg'], true)) { + return \PHP_BINARY.$args; + } + + if ($php = getenv('PHP_PATH')) { + if (!@is_executable($php) || @is_dir($php)) { + return false; + } + + return $php; + } + + if ($php = getenv('PHP_PEAR_PHP_BIN')) { + if (@is_executable($php) && !@is_dir($php)) { + return $php; + } + } + + if (@is_executable($php = \PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php')) && !@is_dir($php)) { + return $php; + } + + $dirs = [\PHP_BINDIR]; + if ('\\' === \DIRECTORY_SEPARATOR) { + $dirs[] = 'C:\xampp\php\\'; + } + + return $this->executableFinder->find('php', false, $dirs); + } + + /** + * Finds the PHP executable arguments. + * + * @return array + */ + public function findArguments() + { + $arguments = []; + if ('phpdbg' === \PHP_SAPI) { + $arguments[] = '-qrr'; + } + + return $arguments; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/PhpProcess.php b/php/libraries/composer/vendor/symfony/process/PhpProcess.php new file mode 100644 index 0000000..3a1d147 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/PhpProcess.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\LogicException; +use Symfony\Component\Process\Exception\RuntimeException; + +/** + * PhpProcess runs a PHP script in an independent process. + * + * $p = new PhpProcess(''); + * $p->run(); + * print $p->getOutput()."\n"; + * + * @author Fabien Potencier + */ +class PhpProcess extends Process +{ + /** + * @param string $script The PHP script to run (as a string) + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param int $timeout The timeout in seconds + * @param array|null $php Path to the PHP binary to use with any additional arguments + */ + public function __construct(string $script, ?string $cwd = null, ?array $env = null, int $timeout = 60, ?array $php = null) + { + if (null === $php) { + $executableFinder = new PhpExecutableFinder(); + $php = $executableFinder->find(false); + $php = false === $php ? null : array_merge([$php], $executableFinder->findArguments()); + } + if ('phpdbg' === \PHP_SAPI) { + $file = tempnam(sys_get_temp_dir(), 'dbg'); + file_put_contents($file, $script); + register_shutdown_function('unlink', $file); + $php[] = $file; + $script = null; + } + + parent::__construct($php, $cwd, $env, $script, $timeout); + } + + /** + * {@inheritdoc} + */ + public static function fromShellCommandline(string $command, ?string $cwd = null, ?array $env = null, $input = null, ?float $timeout = 60) + { + throw new LogicException(sprintf('The "%s()" method cannot be called when using "%s".', __METHOD__, self::class)); + } + + /** + * {@inheritdoc} + */ + public function start(?callable $callback = null, array $env = []) + { + if (null === $this->getCommandLine()) { + throw new RuntimeException('Unable to find the PHP executable.'); + } + + parent::start($callback, $env); + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Pipes/AbstractPipes.php b/php/libraries/composer/vendor/symfony/process/Pipes/AbstractPipes.php new file mode 100644 index 0000000..656dc03 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Pipes/AbstractPipes.php @@ -0,0 +1,180 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +use Symfony\Component\Process\Exception\InvalidArgumentException; + +/** + * @author Romain Neutron + * + * @internal + */ +abstract class AbstractPipes implements PipesInterface +{ + public $pipes = []; + + private $inputBuffer = ''; + private $input; + private $blocked = true; + private $lastError; + + /** + * @param resource|string|int|float|bool|\Iterator|null $input + */ + public function __construct($input) + { + if (\is_resource($input) || $input instanceof \Iterator) { + $this->input = $input; + } elseif (\is_string($input)) { + $this->inputBuffer = $input; + } else { + $this->inputBuffer = (string) $input; + } + } + + /** + * {@inheritdoc} + */ + public function close() + { + foreach ($this->pipes as $pipe) { + if (\is_resource($pipe)) { + fclose($pipe); + } + } + $this->pipes = []; + } + + /** + * Returns true if a system call has been interrupted. + */ + protected function hasSystemCallBeenInterrupted(): bool + { + $lastError = $this->lastError; + $this->lastError = null; + + // stream_select returns false when the `select` system call is interrupted by an incoming signal + return null !== $lastError && false !== stripos($lastError, 'interrupted system call'); + } + + /** + * Unblocks streams. + */ + protected function unblock() + { + if (!$this->blocked) { + return; + } + + foreach ($this->pipes as $pipe) { + stream_set_blocking($pipe, 0); + } + if (\is_resource($this->input)) { + stream_set_blocking($this->input, 0); + } + + $this->blocked = false; + } + + /** + * Writes input to stdin. + * + * @throws InvalidArgumentException When an input iterator yields a non supported value + */ + protected function write(): ?array + { + if (!isset($this->pipes[0])) { + return null; + } + $input = $this->input; + + if ($input instanceof \Iterator) { + if (!$input->valid()) { + $input = null; + } elseif (\is_resource($input = $input->current())) { + stream_set_blocking($input, 0); + } elseif (!isset($this->inputBuffer[0])) { + if (!\is_string($input)) { + if (!\is_scalar($input)) { + throw new InvalidArgumentException(sprintf('"%s" yielded a value of type "%s", but only scalars and stream resources are supported.', get_debug_type($this->input), get_debug_type($input))); + } + $input = (string) $input; + } + $this->inputBuffer = $input; + $this->input->next(); + $input = null; + } else { + $input = null; + } + } + + $r = $e = []; + $w = [$this->pipes[0]]; + + // let's have a look if something changed in streams + if (false === @stream_select($r, $w, $e, 0, 0)) { + return null; + } + + foreach ($w as $stdin) { + if (isset($this->inputBuffer[0])) { + $written = fwrite($stdin, $this->inputBuffer); + $this->inputBuffer = substr($this->inputBuffer, $written); + if (isset($this->inputBuffer[0])) { + return [$this->pipes[0]]; + } + } + + if ($input) { + while (true) { + $data = fread($input, self::CHUNK_SIZE); + if (!isset($data[0])) { + break; + } + $written = fwrite($stdin, $data); + $data = substr($data, $written); + if (isset($data[0])) { + $this->inputBuffer = $data; + + return [$this->pipes[0]]; + } + } + if (feof($input)) { + if ($this->input instanceof \Iterator) { + $this->input->next(); + } else { + $this->input = null; + } + } + } + } + + // no input to read on resource, buffer is empty + if (!isset($this->inputBuffer[0]) && !($this->input instanceof \Iterator ? $this->input->valid() : $this->input)) { + $this->input = null; + fclose($this->pipes[0]); + unset($this->pipes[0]); + } elseif (!$w) { + return [$this->pipes[0]]; + } + + return null; + } + + /** + * @internal + */ + public function handleError(int $type, string $msg) + { + $this->lastError = $msg; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Pipes/PipesInterface.php b/php/libraries/composer/vendor/symfony/process/Pipes/PipesInterface.php new file mode 100644 index 0000000..50eb5c4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Pipes/PipesInterface.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +/** + * PipesInterface manages descriptors and pipes for the use of proc_open. + * + * @author Romain Neutron + * + * @internal + */ +interface PipesInterface +{ + public const CHUNK_SIZE = 16384; + + /** + * Returns an array of descriptors for the use of proc_open. + */ + public function getDescriptors(): array; + + /** + * Returns an array of filenames indexed by their related stream in case these pipes use temporary files. + * + * @return string[] + */ + public function getFiles(): array; + + /** + * Reads data in file handles and pipes. + * + * @param bool $blocking Whether to use blocking calls or not + * @param bool $close Whether to close pipes if they've reached EOF + * + * @return string[] An array of read data indexed by their fd + */ + public function readAndWrite(bool $blocking, bool $close = false): array; + + /** + * Returns if the current state has open file handles or pipes. + */ + public function areOpen(): bool; + + /** + * Returns if pipes are able to read output. + */ + public function haveReadSupport(): bool; + + /** + * Closes file handles and pipes. + */ + public function close(); +} diff --git a/php/libraries/composer/vendor/symfony/process/Pipes/UnixPipes.php b/php/libraries/composer/vendor/symfony/process/Pipes/UnixPipes.php new file mode 100644 index 0000000..5a0e9d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Pipes/UnixPipes.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\Process\Pipes; + +use Symfony\Component\Process\Process; + +/** + * UnixPipes implementation uses unix pipes as handles. + * + * @author Romain Neutron + * + * @internal + */ +class UnixPipes extends AbstractPipes +{ + private $ttyMode; + private $ptyMode; + private $haveReadSupport; + + public function __construct(?bool $ttyMode, bool $ptyMode, $input, bool $haveReadSupport) + { + $this->ttyMode = $ttyMode; + $this->ptyMode = $ptyMode; + $this->haveReadSupport = $haveReadSupport; + + parent::__construct($input); + } + + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + $this->close(); + } + + /** + * {@inheritdoc} + */ + public function getDescriptors(): array + { + if (!$this->haveReadSupport) { + $nullstream = fopen('/dev/null', 'c'); + + return [ + ['pipe', 'r'], + $nullstream, + $nullstream, + ]; + } + + if ($this->ttyMode) { + return [ + ['file', '/dev/tty', 'r'], + ['file', '/dev/tty', 'w'], + ['file', '/dev/tty', 'w'], + ]; + } + + if ($this->ptyMode && Process::isPtySupported()) { + return [ + ['pty'], + ['pty'], + ['pty'], + ]; + } + + return [ + ['pipe', 'r'], + ['pipe', 'w'], // stdout + ['pipe', 'w'], // stderr + ]; + } + + /** + * {@inheritdoc} + */ + public function getFiles(): array + { + return []; + } + + /** + * {@inheritdoc} + */ + public function readAndWrite(bool $blocking, bool $close = false): array + { + $this->unblock(); + $w = $this->write(); + + $read = $e = []; + $r = $this->pipes; + unset($r[0]); + + // let's have a look if something changed in streams + set_error_handler([$this, 'handleError']); + if (($r || $w) && false === stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) { + restore_error_handler(); + // if a system call has been interrupted, forget about it, let's try again + // otherwise, an error occurred, let's reset pipes + if (!$this->hasSystemCallBeenInterrupted()) { + $this->pipes = []; + } + + return $read; + } + restore_error_handler(); + + foreach ($r as $pipe) { + // prior PHP 5.4 the array passed to stream_select is modified and + // lose key association, we have to find back the key + $read[$type = array_search($pipe, $this->pipes, true)] = ''; + + do { + $data = @fread($pipe, self::CHUNK_SIZE); + $read[$type] .= $data; + } while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1]))); + + if (!isset($read[$type][0])) { + unset($read[$type]); + } + + if ($close && feof($pipe)) { + fclose($pipe); + unset($this->pipes[$type]); + } + } + + return $read; + } + + /** + * {@inheritdoc} + */ + public function haveReadSupport(): bool + { + return $this->haveReadSupport; + } + + /** + * {@inheritdoc} + */ + public function areOpen(): bool + { + return (bool) $this->pipes; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Pipes/WindowsPipes.php b/php/libraries/composer/vendor/symfony/process/Pipes/WindowsPipes.php new file mode 100644 index 0000000..968dd02 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Pipes/WindowsPipes.php @@ -0,0 +1,204 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +use Symfony\Component\Process\Exception\RuntimeException; +use Symfony\Component\Process\Process; + +/** + * WindowsPipes implementation uses temporary files as handles. + * + * @see https://bugs.php.net/51800 + * @see https://bugs.php.net/65650 + * + * @author Romain Neutron + * + * @internal + */ +class WindowsPipes extends AbstractPipes +{ + private $files = []; + private $fileHandles = []; + private $lockHandles = []; + private $readBytes = [ + Process::STDOUT => 0, + Process::STDERR => 0, + ]; + private $haveReadSupport; + + public function __construct($input, bool $haveReadSupport) + { + $this->haveReadSupport = $haveReadSupport; + + if ($this->haveReadSupport) { + // Fix for PHP bug #51800: reading from STDOUT pipe hangs forever on Windows if the output is too big. + // Workaround for this problem is to use temporary files instead of pipes on Windows platform. + // + // @see https://bugs.php.net/51800 + $pipes = [ + Process::STDOUT => Process::OUT, + Process::STDERR => Process::ERR, + ]; + $tmpDir = sys_get_temp_dir(); + $lastError = 'unknown reason'; + set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; }); + for ($i = 0;; ++$i) { + foreach ($pipes as $pipe => $name) { + $file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name); + + if (!$h = fopen($file.'.lock', 'w')) { + if (file_exists($file.'.lock')) { + continue 2; + } + restore_error_handler(); + throw new RuntimeException('A temporary file could not be opened to write the process output: '.$lastError); + } + if (!flock($h, \LOCK_EX | \LOCK_NB)) { + continue 2; + } + if (isset($this->lockHandles[$pipe])) { + flock($this->lockHandles[$pipe], \LOCK_UN); + fclose($this->lockHandles[$pipe]); + } + $this->lockHandles[$pipe] = $h; + + if (!($h = fopen($file, 'w')) || !fclose($h) || !$h = fopen($file, 'r')) { + flock($this->lockHandles[$pipe], \LOCK_UN); + fclose($this->lockHandles[$pipe]); + unset($this->lockHandles[$pipe]); + continue 2; + } + $this->fileHandles[$pipe] = $h; + $this->files[$pipe] = $file; + } + break; + } + restore_error_handler(); + } + + parent::__construct($input); + } + + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + $this->close(); + } + + /** + * {@inheritdoc} + */ + public function getDescriptors(): array + { + if (!$this->haveReadSupport) { + $nullstream = fopen('NUL', 'c'); + + return [ + ['pipe', 'r'], + $nullstream, + $nullstream, + ]; + } + + // We're not using pipe on Windows platform as it hangs (https://bugs.php.net/51800) + // We're not using file handles as it can produce corrupted output https://bugs.php.net/65650 + // So we redirect output within the commandline and pass the nul device to the process + return [ + ['pipe', 'r'], + ['file', 'NUL', 'w'], + ['file', 'NUL', 'w'], + ]; + } + + /** + * {@inheritdoc} + */ + public function getFiles(): array + { + return $this->files; + } + + /** + * {@inheritdoc} + */ + public function readAndWrite(bool $blocking, bool $close = false): array + { + $this->unblock(); + $w = $this->write(); + $read = $r = $e = []; + + if ($blocking) { + if ($w) { + @stream_select($r, $w, $e, 0, Process::TIMEOUT_PRECISION * 1E6); + } elseif ($this->fileHandles) { + usleep((int) (Process::TIMEOUT_PRECISION * 1E6)); + } + } + foreach ($this->fileHandles as $type => $fileHandle) { + $data = stream_get_contents($fileHandle, -1, $this->readBytes[$type]); + + if (isset($data[0])) { + $this->readBytes[$type] += \strlen($data); + $read[$type] = $data; + } + if ($close) { + ftruncate($fileHandle, 0); + fclose($fileHandle); + flock($this->lockHandles[$type], \LOCK_UN); + fclose($this->lockHandles[$type]); + unset($this->fileHandles[$type], $this->lockHandles[$type]); + } + } + + return $read; + } + + /** + * {@inheritdoc} + */ + public function haveReadSupport(): bool + { + return $this->haveReadSupport; + } + + /** + * {@inheritdoc} + */ + public function areOpen(): bool + { + return $this->pipes && $this->fileHandles; + } + + /** + * {@inheritdoc} + */ + public function close() + { + parent::close(); + foreach ($this->fileHandles as $type => $handle) { + ftruncate($handle, 0); + fclose($handle); + flock($this->lockHandles[$type], \LOCK_UN); + fclose($this->lockHandles[$type]); + } + $this->fileHandles = $this->lockHandles = []; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/Process.php b/php/libraries/composer/vendor/symfony/process/Process.php new file mode 100644 index 0000000..a4b0a78 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/Process.php @@ -0,0 +1,1666 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\InvalidArgumentException; +use Symfony\Component\Process\Exception\LogicException; +use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Exception\ProcessSignaledException; +use Symfony\Component\Process\Exception\ProcessTimedOutException; +use Symfony\Component\Process\Exception\RuntimeException; +use Symfony\Component\Process\Pipes\PipesInterface; +use Symfony\Component\Process\Pipes\UnixPipes; +use Symfony\Component\Process\Pipes\WindowsPipes; + +/** + * Process is a thin wrapper around proc_* functions to easily + * start independent PHP processes. + * + * @author Fabien Potencier + * @author Romain Neutron + * + * @implements \IteratorAggregate + */ +class Process implements \IteratorAggregate +{ + public const ERR = 'err'; + public const OUT = 'out'; + + public const STATUS_READY = 'ready'; + public const STATUS_STARTED = 'started'; + public const STATUS_TERMINATED = 'terminated'; + + public const STDIN = 0; + public const STDOUT = 1; + public const STDERR = 2; + + // Timeout Precision in seconds. + public const TIMEOUT_PRECISION = 0.2; + + public const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking + public const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory + public const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating + public const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating + + private $callback; + private $hasCallback = false; + private $commandline; + private $cwd; + private $env = []; + private $input; + private $starttime; + private $lastOutputTime; + private $timeout; + private $idleTimeout; + private $exitcode; + private $fallbackStatus = []; + private $processInformation; + private $outputDisabled = false; + private $stdout; + private $stderr; + private $process; + private $status = self::STATUS_READY; + private $incrementalOutputOffset = 0; + private $incrementalErrorOutputOffset = 0; + private $tty = false; + private $pty; + private $options = ['suppress_errors' => true, 'bypass_shell' => true]; + + private $useFileHandles = false; + /** @var PipesInterface */ + private $processPipes; + + private $latestSignal; + private $cachedExitCode; + + private static $sigchild; + + /** + * Exit codes translation table. + * + * User-defined errors must use exit codes in the 64-113 range. + */ + public static $exitCodes = [ + 0 => 'OK', + 1 => 'General error', + 2 => 'Misuse of shell builtins', + + 126 => 'Invoked command cannot execute', + 127 => 'Command not found', + 128 => 'Invalid exit argument', + + // signals + 129 => 'Hangup', + 130 => 'Interrupt', + 131 => 'Quit and dump core', + 132 => 'Illegal instruction', + 133 => 'Trace/breakpoint trap', + 134 => 'Process aborted', + 135 => 'Bus error: "access to undefined portion of memory object"', + 136 => 'Floating point exception: "erroneous arithmetic operation"', + 137 => 'Kill (terminate immediately)', + 138 => 'User-defined 1', + 139 => 'Segmentation violation', + 140 => 'User-defined 2', + 141 => 'Write to pipe with no one reading', + 142 => 'Signal raised by alarm', + 143 => 'Termination (request to terminate)', + // 144 - not defined + 145 => 'Child process terminated, stopped (or continued*)', + 146 => 'Continue if stopped', + 147 => 'Stop executing temporarily', + 148 => 'Terminal stop signal', + 149 => 'Background process attempting to read from tty ("in")', + 150 => 'Background process attempting to write to tty ("out")', + 151 => 'Urgent data available on socket', + 152 => 'CPU time limit exceeded', + 153 => 'File size limit exceeded', + 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"', + 155 => 'Profiling timer expired', + // 156 - not defined + 157 => 'Pollable event', + // 158 - not defined + 159 => 'Bad syscall', + ]; + + /** + * @param array $command The command to run and its arguments listed as separate entries + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input + * @param int|float|null $timeout The timeout in seconds or null to disable + * + * @throws LogicException When proc_open is not installed + */ + public function __construct(array $command, ?string $cwd = null, ?array $env = null, $input = null, ?float $timeout = 60) + { + if (!\function_exists('proc_open')) { + throw new LogicException('The Process class relies on proc_open, which is not available on your PHP installation.'); + } + + $this->commandline = $command; + $this->cwd = $cwd; + + // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started + // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected + // @see : https://bugs.php.net/51800 + // @see : https://bugs.php.net/50524 + if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) { + $this->cwd = getcwd(); + } + if (null !== $env) { + $this->setEnv($env); + } + + $this->setInput($input); + $this->setTimeout($timeout); + $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR; + $this->pty = false; + } + + /** + * Creates a Process instance as a command-line to be run in a shell wrapper. + * + * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.) + * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the + * shell wrapper and not to your commands. + * + * In order to inject dynamic values into command-lines, we strongly recommend using placeholders. + * This will save escaping values, which is not portable nor secure anyway: + * + * $process = Process::fromShellCommandline('my_command "${:MY_VAR}"'); + * $process->run(null, ['MY_VAR' => $theValue]); + * + * @param string $command The command line to pass to the shell of the OS + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input + * @param int|float|null $timeout The timeout in seconds or null to disable + * + * @return static + * + * @throws LogicException When proc_open is not installed + */ + public static function fromShellCommandline(string $command, ?string $cwd = null, ?array $env = null, $input = null, ?float $timeout = 60) + { + $process = new static([], $cwd, $env, $input, $timeout); + $process->commandline = $command; + + return $process; + } + + /** + * @return array + */ + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + if ($this->options['create_new_console'] ?? false) { + $this->processPipes->close(); + } else { + $this->stop(0); + } + } + + public function __clone() + { + $this->resetProcessData(); + } + + /** + * Runs the process. + * + * The callback receives the type of output (out or err) and + * some bytes from the output in real-time. It allows to have feedback + * from the independent process during execution. + * + * The STDOUT and STDERR are also available after the process is finished + * via the getOutput() and getErrorOutput() methods. + * + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @return int The exit status code + * + * @throws RuntimeException When process can't be launched + * @throws RuntimeException When process is already running + * @throws ProcessTimedOutException When process timed out + * @throws ProcessSignaledException When process stopped after receiving signal + * @throws LogicException In case a callback is provided and output has been disabled + * + * @final + */ + public function run(?callable $callback = null, array $env = []): int + { + $this->start($callback, $env); + + return $this->wait(); + } + + /** + * Runs the process. + * + * This is identical to run() except that an exception is thrown if the process + * exits with a non-zero exit code. + * + * @return $this + * + * @throws ProcessFailedException if the process didn't terminate successfully + * + * @final + */ + public function mustRun(?callable $callback = null, array $env = []): self + { + if (0 !== $this->run($callback, $env)) { + throw new ProcessFailedException($this); + } + + return $this; + } + + /** + * Starts the process and returns after writing the input to STDIN. + * + * This method blocks until all STDIN data is sent to the process then it + * returns while the process runs in the background. + * + * The termination of the process can be awaited with wait(). + * + * The callback receives the type of output (out or err) and some bytes from + * the output in real-time while writing the standard input to the process. + * It allows to have feedback from the independent process during execution. + * + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @throws RuntimeException When process can't be launched + * @throws RuntimeException When process is already running + * @throws LogicException In case a callback is provided and output has been disabled + */ + public function start(?callable $callback = null, array $env = []) + { + if ($this->isRunning()) { + throw new RuntimeException('Process is already running.'); + } + + $this->resetProcessData(); + $this->starttime = $this->lastOutputTime = microtime(true); + $this->callback = $this->buildCallback($callback); + $this->hasCallback = null !== $callback; + $descriptors = $this->getDescriptors(); + + if ($this->env) { + $env += '\\' === \DIRECTORY_SEPARATOR ? array_diff_ukey($this->env, $env, 'strcasecmp') : $this->env; + } + + $env += '\\' === \DIRECTORY_SEPARATOR ? array_diff_ukey($this->getDefaultEnv(), $env, 'strcasecmp') : $this->getDefaultEnv(); + + if (\is_array($commandline = $this->commandline)) { + $commandline = implode(' ', array_map([$this, 'escapeArgument'], $commandline)); + + if ('\\' !== \DIRECTORY_SEPARATOR) { + // exec is mandatory to deal with sending a signal to the process + $commandline = 'exec '.$commandline; + } + } else { + $commandline = $this->replacePlaceholders($commandline, $env); + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + $commandline = $this->prepareWindowsCommandLine($commandline, $env); + } elseif (!$this->useFileHandles && $this->isSigchildEnabled()) { + // last exit code is output on the fourth pipe and caught to work around --enable-sigchild + $descriptors[3] = ['pipe', 'w']; + + // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input + $commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;'; + $commandline .= 'pid=$!; echo $pid >&3; wait $pid 2>/dev/null; code=$?; echo $code >&3; exit $code'; + + // Workaround for the bug, when PTS functionality is enabled. + // @see : https://bugs.php.net/69442 + $ptsWorkaround = fopen(__FILE__, 'r'); + } + + $envPairs = []; + foreach ($env as $k => $v) { + if (false !== $v && false === \in_array($k, ['argc', 'argv', 'ARGC', 'ARGV'], true)) { + $envPairs[] = $k.'='.$v; + } + } + + if (!is_dir($this->cwd)) { + throw new RuntimeException(sprintf('The provided cwd "%s" does not exist.', $this->cwd)); + } + + $this->process = @proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $this->options); + + if (!\is_resource($this->process)) { + throw new RuntimeException('Unable to launch a new process.'); + } + $this->status = self::STATUS_STARTED; + + if (isset($descriptors[3])) { + $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]); + } + + if ($this->tty) { + return; + } + + $this->updateStatus(false); + $this->checkTimeout(); + } + + /** + * Restarts the process. + * + * Be warned that the process is cloned before being started. + * + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @return static + * + * @throws RuntimeException When process can't be launched + * @throws RuntimeException When process is already running + * + * @see start() + * + * @final + */ + public function restart(?callable $callback = null, array $env = []): self + { + if ($this->isRunning()) { + throw new RuntimeException('Process is already running.'); + } + + $process = clone $this; + $process->start($callback, $env); + + return $process; + } + + /** + * Waits for the process to terminate. + * + * The callback receives the type of output (out or err) and some bytes + * from the output in real-time while writing the standard input to the process. + * It allows to have feedback from the independent process during execution. + * + * @param callable|null $callback A valid PHP callback + * + * @return int The exitcode of the process + * + * @throws ProcessTimedOutException When process timed out + * @throws ProcessSignaledException When process stopped after receiving signal + * @throws LogicException When process is not yet started + */ + public function wait(?callable $callback = null) + { + $this->requireProcessIsStarted(__FUNCTION__); + + $this->updateStatus(false); + + if (null !== $callback) { + if (!$this->processPipes->haveReadSupport()) { + $this->stop(0); + throw new LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::wait".'); + } + $this->callback = $this->buildCallback($callback); + } + + do { + $this->checkTimeout(); + $running = $this->isRunning() && ('\\' === \DIRECTORY_SEPARATOR || $this->processPipes->areOpen()); + $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running); + } while ($running); + + while ($this->isRunning()) { + $this->checkTimeout(); + usleep(1000); + } + + if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) { + throw new ProcessSignaledException($this); + } + + return $this->exitcode; + } + + /** + * Waits until the callback returns true. + * + * The callback receives the type of output (out or err) and some bytes + * from the output in real-time while writing the standard input to the process. + * It allows to have feedback from the independent process during execution. + * + * @throws RuntimeException When process timed out + * @throws LogicException When process is not yet started + * @throws ProcessTimedOutException In case the timeout was reached + */ + public function waitUntil(callable $callback): bool + { + $this->requireProcessIsStarted(__FUNCTION__); + $this->updateStatus(false); + + if (!$this->processPipes->haveReadSupport()) { + $this->stop(0); + throw new LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::waitUntil".'); + } + $callback = $this->buildCallback($callback); + + $ready = false; + while (true) { + $this->checkTimeout(); + $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen(); + $output = $this->processPipes->readAndWrite($running, '\\' !== \DIRECTORY_SEPARATOR || !$running); + + foreach ($output as $type => $data) { + if (3 !== $type) { + $ready = $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data) || $ready; + } elseif (!isset($this->fallbackStatus['signaled'])) { + $this->fallbackStatus['exitcode'] = (int) $data; + } + } + if ($ready) { + return true; + } + if (!$running) { + return false; + } + + usleep(1000); + } + } + + /** + * Returns the Pid (process identifier), if applicable. + * + * @return int|null The process id if running, null otherwise + */ + public function getPid() + { + return $this->isRunning() ? $this->processInformation['pid'] : null; + } + + /** + * Sends a POSIX signal to the process. + * + * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants) + * + * @return $this + * + * @throws LogicException In case the process is not running + * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed + * @throws RuntimeException In case of failure + */ + public function signal(int $signal) + { + $this->doSignal($signal, true); + + return $this; + } + + /** + * Disables fetching output and error output from the underlying process. + * + * @return $this + * + * @throws RuntimeException In case the process is already running + * @throws LogicException if an idle timeout is set + */ + public function disableOutput() + { + if ($this->isRunning()) { + throw new RuntimeException('Disabling output while the process is running is not possible.'); + } + if (null !== $this->idleTimeout) { + throw new LogicException('Output cannot be disabled while an idle timeout is set.'); + } + + $this->outputDisabled = true; + + return $this; + } + + /** + * Enables fetching output and error output from the underlying process. + * + * @return $this + * + * @throws RuntimeException In case the process is already running + */ + public function enableOutput() + { + if ($this->isRunning()) { + throw new RuntimeException('Enabling output while the process is running is not possible.'); + } + + $this->outputDisabled = false; + + return $this; + } + + /** + * Returns true in case the output is disabled, false otherwise. + * + * @return bool + */ + public function isOutputDisabled() + { + return $this->outputDisabled; + } + + /** + * Returns the current output of the process (STDOUT). + * + * @return string + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getOutput() + { + $this->readPipesForOutput(__FUNCTION__); + + if (false === $ret = stream_get_contents($this->stdout, -1, 0)) { + return ''; + } + + return $ret; + } + + /** + * Returns the output incrementally. + * + * In comparison with the getOutput method which always return the whole + * output, this one returns the new output since the last call. + * + * @return string + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getIncrementalOutput() + { + $this->readPipesForOutput(__FUNCTION__); + + $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset); + $this->incrementalOutputOffset = ftell($this->stdout); + + if (false === $latest) { + return ''; + } + + return $latest; + } + + /** + * Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR). + * + * @param int $flags A bit field of Process::ITER_* flags + * + * @return \Generator + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + #[\ReturnTypeWillChange] + public function getIterator(int $flags = 0) + { + $this->readPipesForOutput(__FUNCTION__, false); + + $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags); + $blocking = !(self::ITER_NON_BLOCKING & $flags); + $yieldOut = !(self::ITER_SKIP_OUT & $flags); + $yieldErr = !(self::ITER_SKIP_ERR & $flags); + + while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) { + if ($yieldOut) { + $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset); + + if (isset($out[0])) { + if ($clearOutput) { + $this->clearOutput(); + } else { + $this->incrementalOutputOffset = ftell($this->stdout); + } + + yield self::OUT => $out; + } + } + + if ($yieldErr) { + $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset); + + if (isset($err[0])) { + if ($clearOutput) { + $this->clearErrorOutput(); + } else { + $this->incrementalErrorOutputOffset = ftell($this->stderr); + } + + yield self::ERR => $err; + } + } + + if (!$blocking && !isset($out[0]) && !isset($err[0])) { + yield self::OUT => ''; + } + + $this->checkTimeout(); + $this->readPipesForOutput(__FUNCTION__, $blocking); + } + } + + /** + * Clears the process output. + * + * @return $this + */ + public function clearOutput() + { + ftruncate($this->stdout, 0); + fseek($this->stdout, 0); + $this->incrementalOutputOffset = 0; + + return $this; + } + + /** + * Returns the current error output of the process (STDERR). + * + * @return string + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getErrorOutput() + { + $this->readPipesForOutput(__FUNCTION__); + + if (false === $ret = stream_get_contents($this->stderr, -1, 0)) { + return ''; + } + + return $ret; + } + + /** + * Returns the errorOutput incrementally. + * + * In comparison with the getErrorOutput method which always return the + * whole error output, this one returns the new error output since the last + * call. + * + * @return string + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getIncrementalErrorOutput() + { + $this->readPipesForOutput(__FUNCTION__); + + $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset); + $this->incrementalErrorOutputOffset = ftell($this->stderr); + + if (false === $latest) { + return ''; + } + + return $latest; + } + + /** + * Clears the process output. + * + * @return $this + */ + public function clearErrorOutput() + { + ftruncate($this->stderr, 0); + fseek($this->stderr, 0); + $this->incrementalErrorOutputOffset = 0; + + return $this; + } + + /** + * Returns the exit code returned by the process. + * + * @return int|null The exit status code, null if the Process is not terminated + */ + public function getExitCode() + { + $this->updateStatus(false); + + return $this->exitcode; + } + + /** + * Returns a string representation for the exit code returned by the process. + * + * This method relies on the Unix exit code status standardization + * and might not be relevant for other operating systems. + * + * @return string|null A string representation for the exit status code, null if the Process is not terminated + * + * @see http://tldp.org/LDP/abs/html/exitcodes.html + * @see http://en.wikipedia.org/wiki/Unix_signal + */ + public function getExitCodeText() + { + if (null === $exitcode = $this->getExitCode()) { + return null; + } + + return self::$exitCodes[$exitcode] ?? 'Unknown error'; + } + + /** + * Checks if the process ended successfully. + * + * @return bool + */ + public function isSuccessful() + { + return 0 === $this->getExitCode(); + } + + /** + * Returns true if the child process has been terminated by an uncaught signal. + * + * It always returns false on Windows. + * + * @return bool + * + * @throws LogicException In case the process is not terminated + */ + public function hasBeenSignaled() + { + $this->requireProcessIsTerminated(__FUNCTION__); + + return $this->processInformation['signaled']; + } + + /** + * Returns the number of the signal that caused the child process to terminate its execution. + * + * It is only meaningful if hasBeenSignaled() returns true. + * + * @return int + * + * @throws RuntimeException In case --enable-sigchild is activated + * @throws LogicException In case the process is not terminated + */ + public function getTermSignal() + { + $this->requireProcessIsTerminated(__FUNCTION__); + + if ($this->isSigchildEnabled() && -1 === $this->processInformation['termsig']) { + throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal cannot be retrieved.'); + } + + return $this->processInformation['termsig']; + } + + /** + * Returns true if the child process has been stopped by a signal. + * + * It always returns false on Windows. + * + * @return bool + * + * @throws LogicException In case the process is not terminated + */ + public function hasBeenStopped() + { + $this->requireProcessIsTerminated(__FUNCTION__); + + return $this->processInformation['stopped']; + } + + /** + * Returns the number of the signal that caused the child process to stop its execution. + * + * It is only meaningful if hasBeenStopped() returns true. + * + * @return int + * + * @throws LogicException In case the process is not terminated + */ + public function getStopSignal() + { + $this->requireProcessIsTerminated(__FUNCTION__); + + return $this->processInformation['stopsig']; + } + + /** + * Checks if the process is currently running. + * + * @return bool + */ + public function isRunning() + { + if (self::STATUS_STARTED !== $this->status) { + return false; + } + + $this->updateStatus(false); + + return $this->processInformation['running']; + } + + /** + * Checks if the process has been started with no regard to the current state. + * + * @return bool + */ + public function isStarted() + { + return self::STATUS_READY != $this->status; + } + + /** + * Checks if the process is terminated. + * + * @return bool + */ + public function isTerminated() + { + $this->updateStatus(false); + + return self::STATUS_TERMINATED == $this->status; + } + + /** + * Gets the process status. + * + * The status is one of: ready, started, terminated. + * + * @return string + */ + public function getStatus() + { + $this->updateStatus(false); + + return $this->status; + } + + /** + * Stops the process. + * + * @param int|float $timeout The timeout in seconds + * @param int|null $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9) + * + * @return int|null The exit-code of the process or null if it's not running + */ + public function stop(float $timeout = 10, ?int $signal = null) + { + $timeoutMicro = microtime(true) + $timeout; + if ($this->isRunning()) { + // given SIGTERM may not be defined and that "proc_terminate" uses the constant value and not the constant itself, we use the same here + $this->doSignal(15, false); + do { + usleep(1000); + } while ($this->isRunning() && microtime(true) < $timeoutMicro); + + if ($this->isRunning()) { + // Avoid exception here: process is supposed to be running, but it might have stopped just + // after this line. In any case, let's silently discard the error, we cannot do anything. + $this->doSignal($signal ?: 9, false); + } + } + + if ($this->isRunning()) { + if (isset($this->fallbackStatus['pid'])) { + unset($this->fallbackStatus['pid']); + + return $this->stop(0, $signal); + } + $this->close(); + } + + return $this->exitcode; + } + + /** + * Adds a line to the STDOUT stream. + * + * @internal + */ + public function addOutput(string $line) + { + $this->lastOutputTime = microtime(true); + + fseek($this->stdout, 0, \SEEK_END); + fwrite($this->stdout, $line); + fseek($this->stdout, $this->incrementalOutputOffset); + } + + /** + * Adds a line to the STDERR stream. + * + * @internal + */ + public function addErrorOutput(string $line) + { + $this->lastOutputTime = microtime(true); + + fseek($this->stderr, 0, \SEEK_END); + fwrite($this->stderr, $line); + fseek($this->stderr, $this->incrementalErrorOutputOffset); + } + + /** + * Gets the last output time in seconds. + */ + public function getLastOutputTime(): ?float + { + return $this->lastOutputTime; + } + + /** + * Gets the command line to be executed. + * + * @return string + */ + public function getCommandLine() + { + return \is_array($this->commandline) ? implode(' ', array_map([$this, 'escapeArgument'], $this->commandline)) : $this->commandline; + } + + /** + * Gets the process timeout in seconds (max. runtime). + * + * @return float|null + */ + public function getTimeout() + { + return $this->timeout; + } + + /** + * Gets the process idle timeout in seconds (max. time since last output). + * + * @return float|null + */ + public function getIdleTimeout() + { + return $this->idleTimeout; + } + + /** + * Sets the process timeout (max. runtime) in seconds. + * + * To disable the timeout, set this value to null. + * + * @return $this + * + * @throws InvalidArgumentException if the timeout is negative + */ + public function setTimeout(?float $timeout) + { + $this->timeout = $this->validateTimeout($timeout); + + return $this; + } + + /** + * Sets the process idle timeout (max. time since last output) in seconds. + * + * To disable the timeout, set this value to null. + * + * @return $this + * + * @throws LogicException if the output is disabled + * @throws InvalidArgumentException if the timeout is negative + */ + public function setIdleTimeout(?float $timeout) + { + if (null !== $timeout && $this->outputDisabled) { + throw new LogicException('Idle timeout cannot be set while the output is disabled.'); + } + + $this->idleTimeout = $this->validateTimeout($timeout); + + return $this; + } + + /** + * Enables or disables the TTY mode. + * + * @return $this + * + * @throws RuntimeException In case the TTY mode is not supported + */ + public function setTty(bool $tty) + { + if ('\\' === \DIRECTORY_SEPARATOR && $tty) { + throw new RuntimeException('TTY mode is not supported on Windows platform.'); + } + + if ($tty && !self::isTtySupported()) { + throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.'); + } + + $this->tty = $tty; + + return $this; + } + + /** + * Checks if the TTY mode is enabled. + * + * @return bool + */ + public function isTty() + { + return $this->tty; + } + + /** + * Sets PTY mode. + * + * @return $this + */ + public function setPty(bool $bool) + { + $this->pty = $bool; + + return $this; + } + + /** + * Returns PTY state. + * + * @return bool + */ + public function isPty() + { + return $this->pty; + } + + /** + * Gets the working directory. + * + * @return string|null + */ + public function getWorkingDirectory() + { + if (null === $this->cwd) { + // getcwd() will return false if any one of the parent directories does not have + // the readable or search mode set, even if the current directory does + return getcwd() ?: null; + } + + return $this->cwd; + } + + /** + * Sets the current working directory. + * + * @return $this + */ + public function setWorkingDirectory(string $cwd) + { + $this->cwd = $cwd; + + return $this; + } + + /** + * Gets the environment variables. + * + * @return array + */ + public function getEnv() + { + return $this->env; + } + + /** + * Sets the environment variables. + * + * @param array $env The new environment variables + * + * @return $this + */ + public function setEnv(array $env) + { + $this->env = $env; + + return $this; + } + + /** + * Gets the Process input. + * + * @return resource|string|\Iterator|null + */ + public function getInput() + { + return $this->input; + } + + /** + * Sets the input. + * + * This content will be passed to the underlying process standard input. + * + * @param string|int|float|bool|resource|\Traversable|null $input The content + * + * @return $this + * + * @throws LogicException In case the process is running + */ + public function setInput($input) + { + if ($this->isRunning()) { + throw new LogicException('Input cannot be set while the process is running.'); + } + + $this->input = ProcessUtils::validateInput(__METHOD__, $input); + + return $this; + } + + /** + * Performs a check between the timeout definition and the time the process started. + * + * In case you run a background process (with the start method), you should + * trigger this method regularly to ensure the process timeout + * + * @throws ProcessTimedOutException In case the timeout was reached + */ + public function checkTimeout() + { + if (self::STATUS_STARTED !== $this->status) { + return; + } + + if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) { + $this->stop(0); + + throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL); + } + + if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) { + $this->stop(0); + + throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE); + } + } + + /** + * @throws LogicException in case process is not started + */ + public function getStartTime(): float + { + if (!$this->isStarted()) { + throw new LogicException('Start time is only available after process start.'); + } + + return $this->starttime; + } + + /** + * Defines options to pass to the underlying proc_open(). + * + * @see https://php.net/proc_open for the options supported by PHP. + * + * Enabling the "create_new_console" option allows a subprocess to continue + * to run after the main process exited, on both Windows and *nix + */ + public function setOptions(array $options) + { + if ($this->isRunning()) { + throw new RuntimeException('Setting options while the process is running is not possible.'); + } + + $defaultOptions = $this->options; + $existingOptions = ['blocking_pipes', 'create_process_group', 'create_new_console']; + + foreach ($options as $key => $value) { + if (!\in_array($key, $existingOptions)) { + $this->options = $defaultOptions; + throw new LogicException(sprintf('Invalid option "%s" passed to "%s()". Supported options are "%s".', $key, __METHOD__, implode('", "', $existingOptions))); + } + $this->options[$key] = $value; + } + } + + /** + * Returns whether TTY is supported on the current operating system. + */ + public static function isTtySupported(): bool + { + static $isTtySupported; + + if (null === $isTtySupported) { + $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes); + } + + return $isTtySupported; + } + + /** + * Returns whether PTY is supported on the current operating system. + * + * @return bool + */ + public static function isPtySupported() + { + static $result; + + if (null !== $result) { + return $result; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + return $result = false; + } + + return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes); + } + + /** + * Creates the descriptors needed by the proc_open. + */ + private function getDescriptors(): array + { + if ($this->input instanceof \Iterator) { + $this->input->rewind(); + } + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback); + } else { + $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback); + } + + return $this->processPipes->getDescriptors(); + } + + /** + * Builds up the callback used by wait(). + * + * The callbacks adds all occurred output to the specific buffer and calls + * the user callback (if present) with the received output. + * + * @param callable|null $callback The user defined PHP callback + * + * @return \Closure + */ + protected function buildCallback(?callable $callback = null) + { + if ($this->outputDisabled) { + return function ($type, $data) use ($callback): bool { + return null !== $callback && $callback($type, $data); + }; + } + + $out = self::OUT; + + return function ($type, $data) use ($callback, $out): bool { + if ($out == $type) { + $this->addOutput($data); + } else { + $this->addErrorOutput($data); + } + + return null !== $callback && $callback($type, $data); + }; + } + + /** + * Updates the status of the process, reads pipes. + * + * @param bool $blocking Whether to use a blocking read call + */ + protected function updateStatus(bool $blocking) + { + if (self::STATUS_STARTED !== $this->status) { + return; + } + + $this->processInformation = proc_get_status($this->process); + $running = $this->processInformation['running']; + + // In PHP < 8.3, "proc_get_status" only returns the correct exit status on the first call. + // Subsequent calls return -1 as the process is discarded. This workaround caches the first + // retrieved exit status for consistent results in later calls, mimicking PHP 8.3 behavior. + if (\PHP_VERSION_ID < 80300) { + if (!isset($this->cachedExitCode) && !$running && -1 !== $this->processInformation['exitcode']) { + $this->cachedExitCode = $this->processInformation['exitcode']; + } + + if (isset($this->cachedExitCode) && !$running && -1 === $this->processInformation['exitcode']) { + $this->processInformation['exitcode'] = $this->cachedExitCode; + } + } + + $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running); + + if ($this->fallbackStatus && $this->isSigchildEnabled()) { + $this->processInformation = $this->fallbackStatus + $this->processInformation; + } + + if (!$running) { + $this->close(); + } + } + + /** + * Returns whether PHP has been compiled with the '--enable-sigchild' option or not. + * + * @return bool + */ + protected function isSigchildEnabled() + { + if (null !== self::$sigchild) { + return self::$sigchild; + } + + if (!\function_exists('phpinfo')) { + return self::$sigchild = false; + } + + ob_start(); + phpinfo(\INFO_GENERAL); + + return self::$sigchild = str_contains(ob_get_clean(), '--enable-sigchild'); + } + + /** + * Reads pipes for the freshest output. + * + * @param string $caller The name of the method that needs fresh outputs + * @param bool $blocking Whether to use blocking calls or not + * + * @throws LogicException in case output has been disabled or process is not started + */ + private function readPipesForOutput(string $caller, bool $blocking = false) + { + if ($this->outputDisabled) { + throw new LogicException('Output has been disabled.'); + } + + $this->requireProcessIsStarted($caller); + + $this->updateStatus($blocking); + } + + /** + * Validates and returns the filtered timeout. + * + * @throws InvalidArgumentException if the given timeout is a negative number + */ + private function validateTimeout(?float $timeout): ?float + { + $timeout = (float) $timeout; + + if (0.0 === $timeout) { + $timeout = null; + } elseif ($timeout < 0) { + throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.'); + } + + return $timeout; + } + + /** + * Reads pipes, executes callback. + * + * @param bool $blocking Whether to use blocking calls or not + * @param bool $close Whether to close file handles or not + */ + private function readPipes(bool $blocking, bool $close) + { + $result = $this->processPipes->readAndWrite($blocking, $close); + + $callback = $this->callback; + foreach ($result as $type => $data) { + if (3 !== $type) { + $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data); + } elseif (!isset($this->fallbackStatus['signaled'])) { + $this->fallbackStatus['exitcode'] = (int) $data; + } + } + } + + /** + * Closes process resource, closes file handles, sets the exitcode. + * + * @return int The exitcode + */ + private function close(): int + { + $this->processPipes->close(); + if (\is_resource($this->process)) { + proc_close($this->process); + } + $this->exitcode = $this->processInformation['exitcode']; + $this->status = self::STATUS_TERMINATED; + + if (-1 === $this->exitcode) { + if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) { + // if process has been signaled, no exitcode but a valid termsig, apply Unix convention + $this->exitcode = 128 + $this->processInformation['termsig']; + } elseif ($this->isSigchildEnabled()) { + $this->processInformation['signaled'] = true; + $this->processInformation['termsig'] = -1; + } + } + + // Free memory from self-reference callback created by buildCallback + // Doing so in other contexts like __destruct or by garbage collector is ineffective + // Now pipes are closed, so the callback is no longer necessary + $this->callback = null; + + return $this->exitcode; + } + + /** + * Resets data related to the latest run of the process. + */ + private function resetProcessData() + { + $this->starttime = null; + $this->callback = null; + $this->exitcode = null; + $this->fallbackStatus = []; + $this->processInformation = null; + $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+'); + $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+'); + $this->process = null; + $this->latestSignal = null; + $this->status = self::STATUS_READY; + $this->incrementalOutputOffset = 0; + $this->incrementalErrorOutputOffset = 0; + } + + /** + * Sends a POSIX signal to the process. + * + * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants) + * @param bool $throwException Whether to throw exception in case signal failed + * + * @throws LogicException In case the process is not running + * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed + * @throws RuntimeException In case of failure + */ + private function doSignal(int $signal, bool $throwException): bool + { + if (null === $pid = $this->getPid()) { + if ($throwException) { + throw new LogicException('Cannot send signal on a non running process.'); + } + + return false; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode); + if ($exitCode && $this->isRunning()) { + if ($throwException) { + throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output))); + } + + return false; + } + } else { + if (!$this->isSigchildEnabled()) { + $ok = @proc_terminate($this->process, $signal); + } elseif (\function_exists('posix_kill')) { + $ok = @posix_kill($pid, $signal); + } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) { + $ok = false === fgets($pipes[2]); + } + if (!$ok) { + if ($throwException) { + throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal)); + } + + return false; + } + } + + $this->latestSignal = $signal; + $this->fallbackStatus['signaled'] = true; + $this->fallbackStatus['exitcode'] = -1; + $this->fallbackStatus['termsig'] = $this->latestSignal; + + return true; + } + + private function prepareWindowsCommandLine(string $cmd, array &$env): string + { + $uid = uniqid('', true); + $varCount = 0; + $varCache = []; + $cmd = preg_replace_callback( + '/"(?:( + [^"%!^]*+ + (?: + (?: !LF! | "(?:\^[%!^])?+" ) + [^"%!^]*+ + )++ + ) | [^"]*+ )"/x', + function ($m) use (&$env, &$varCache, &$varCount, $uid) { + if (!isset($m[1])) { + return $m[0]; + } + if (isset($varCache[$m[0]])) { + return $varCache[$m[0]]; + } + if (str_contains($value = $m[1], "\0")) { + $value = str_replace("\0", '?', $value); + } + if (false === strpbrk($value, "\"%!\n")) { + return '"'.$value.'"'; + } + + $value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value); + $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"'; + $var = $uid.++$varCount; + + $env[$var] = $value; + + return $varCache[$m[0]] = '!'.$var.'!'; + }, + $cmd + ); + + $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')'; + foreach ($this->processPipes->getFiles() as $offset => $filename) { + $cmd .= ' '.$offset.'>"'.$filename.'"'; + } + + return $cmd; + } + + /** + * Ensures the process is running or terminated, throws a LogicException if the process has a not started. + * + * @throws LogicException if the process has not run + */ + private function requireProcessIsStarted(string $functionName) + { + if (!$this->isStarted()) { + throw new LogicException(sprintf('Process must be started before calling "%s()".', $functionName)); + } + } + + /** + * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated". + * + * @throws LogicException if the process is not yet terminated + */ + private function requireProcessIsTerminated(string $functionName) + { + if (!$this->isTerminated()) { + throw new LogicException(sprintf('Process must be terminated before calling "%s()".', $functionName)); + } + } + + /** + * Escapes a string to be used as a shell argument. + */ + private function escapeArgument(?string $argument): string + { + if ('' === $argument || null === $argument) { + return '""'; + } + if ('\\' !== \DIRECTORY_SEPARATOR) { + return "'".str_replace("'", "'\\''", $argument)."'"; + } + if (str_contains($argument, "\0")) { + $argument = str_replace("\0", '?', $argument); + } + if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) { + return $argument; + } + $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument); + + return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"'; + } + + private function replacePlaceholders(string $commandline, array $env) + { + return preg_replace_callback('/"\$\{:([_a-zA-Z]++[_a-zA-Z0-9]*+)\}"/', function ($matches) use ($commandline, $env) { + if (!isset($env[$matches[1]]) || false === $env[$matches[1]]) { + throw new InvalidArgumentException(sprintf('Command line is missing a value for parameter "%s": ', $matches[1]).$commandline); + } + + return $this->escapeArgument($env[$matches[1]]); + }, $commandline); + } + + private function getDefaultEnv(): array + { + $env = getenv(); + $env = ('\\' === \DIRECTORY_SEPARATOR ? array_intersect_ukey($env, $_SERVER, 'strcasecmp') : array_intersect_key($env, $_SERVER)) ?: $env; + + return $_ENV + ('\\' === \DIRECTORY_SEPARATOR ? array_diff_ukey($env, $_ENV, 'strcasecmp') : $env); + } +} diff --git a/php/libraries/composer/vendor/symfony/process/ProcessUtils.php b/php/libraries/composer/vendor/symfony/process/ProcessUtils.php new file mode 100644 index 0000000..2a7aff7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/ProcessUtils.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\InvalidArgumentException; + +/** + * ProcessUtils is a bunch of utility methods. + * + * This class contains static methods only and is not meant to be instantiated. + * + * @author Martin Hasoň + */ +class ProcessUtils +{ + /** + * This class should not be instantiated. + */ + private function __construct() + { + } + + /** + * Validates and normalizes a Process input. + * + * @param string $caller The name of method call that validates the input + * @param mixed $input The input to validate + * + * @return mixed + * + * @throws InvalidArgumentException In case the input is not valid + */ + public static function validateInput(string $caller, $input) + { + if (null !== $input) { + if (\is_resource($input)) { + return $input; + } + if (\is_string($input)) { + return $input; + } + if (\is_scalar($input)) { + return (string) $input; + } + if ($input instanceof Process) { + return $input->getIterator($input::ITER_SKIP_ERR); + } + if ($input instanceof \Iterator) { + return $input; + } + if ($input instanceof \Traversable) { + return new \IteratorIterator($input); + } + + throw new InvalidArgumentException(sprintf('"%s" only accepts strings, Traversable objects or stream resources.', $caller)); + } + + return $input; + } +} diff --git a/php/libraries/composer/vendor/symfony/process/README.md b/php/libraries/composer/vendor/symfony/process/README.md new file mode 100644 index 0000000..8777de4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/README.md @@ -0,0 +1,28 @@ +Process Component +================= + +The Process component executes commands in sub-processes. + +Sponsor +------- + +The Process component for Symfony 5.4/6.0 is [backed][1] by [SensioLabs][2]. + +As the creator of Symfony, SensioLabs supports companies using Symfony, with an +offering encompassing consultancy, expertise, services, training, and technical +assistance to ensure the success of web application development projects. + +Help Symfony by [sponsoring][3] its development! + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/process.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +[1]: https://symfony.com/backers +[2]: https://sensiolabs.com +[3]: https://symfony.com/sponsor diff --git a/php/libraries/composer/vendor/symfony/process/composer.json b/php/libraries/composer/vendor/symfony/process/composer.json new file mode 100644 index 0000000..1669eba --- /dev/null +++ b/php/libraries/composer/vendor/symfony/process/composer.json @@ -0,0 +1,29 @@ +{ + "name": "symfony/process", + "type": "library", + "description": "Executes commands in sub-processes", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/polyfill-php80": "^1.16" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Process\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/routing/Alias.php b/php/libraries/composer/vendor/symfony/routing/Alias.php new file mode 100644 index 0000000..f3e1d5a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Alias.php @@ -0,0 +1,96 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +use Symfony\Component\Routing\Exception\InvalidArgumentException; + +class Alias +{ + private $id; + private $deprecation = []; + + public function __construct(string $id) + { + $this->id = $id; + } + + /** + * @return static + */ + public function withId(string $id): self + { + $new = clone $this; + + $new->id = $id; + + return $new; + } + + /** + * Returns the target name of this alias. + * + * @return string The target name + */ + public function getId(): string + { + return $this->id; + } + + /** + * Whether this alias is deprecated, that means it should not be referenced anymore. + * + * @param string $package The name of the composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The deprecation message to use + * + * @return $this + * + * @throws InvalidArgumentException when the message template is invalid + */ + public function setDeprecated(string $package, string $version, string $message): self + { + if ('' !== $message) { + if (preg_match('#[\r\n]|\*/#', $message)) { + throw new InvalidArgumentException('Invalid characters found in deprecation template.'); + } + + if (!str_contains($message, '%alias_id%')) { + throw new InvalidArgumentException('The deprecation template must contain the "%alias_id%" placeholder.'); + } + } + + $this->deprecation = [ + 'package' => $package, + 'version' => $version, + 'message' => $message ?: 'The "%alias_id%" route alias is deprecated. You should stop using it, as it will be removed in the future.', + ]; + + return $this; + } + + public function isDeprecated(): bool + { + return (bool) $this->deprecation; + } + + /** + * @param string $name Route name relying on this alias + */ + public function getDeprecation(string $name): array + { + return [ + 'package' => $this->deprecation['package'], + 'version' => $this->deprecation['version'], + 'message' => str_replace('%alias_id%', $name, $this->deprecation['message']), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Annotation/Route.php b/php/libraries/composer/vendor/symfony/routing/Annotation/Route.php new file mode 100644 index 0000000..957344f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Annotation/Route.php @@ -0,0 +1,272 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Annotation; + +/** + * Annotation class for @Route(). + * + * @Annotation + * @NamedArgumentConstructor + * @Target({"CLASS", "METHOD"}) + * + * @author Fabien Potencier + * @author Alexander M. Turek + */ +#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)] +class Route +{ + private $path; + private $localizedPaths = []; + private $name; + private $requirements = []; + private $options = []; + private $defaults = []; + private $host; + private $methods = []; + private $schemes = []; + private $condition; + private $priority; + private $env; + + /** + * @param array|string $data data array managed by the Doctrine Annotations library or the path + * @param array|string|null $path + * @param string[] $requirements + * @param string[]|string $methods + * @param string[]|string $schemes + * + * @throws \BadMethodCallException + */ + public function __construct( + $data = [], + $path = null, + ?string $name = null, + array $requirements = [], + array $options = [], + array $defaults = [], + ?string $host = null, + $methods = [], + $schemes = [], + ?string $condition = null, + ?int $priority = null, + ?string $locale = null, + ?string $format = null, + ?bool $utf8 = null, + ?bool $stateless = null, + ?string $env = null + ) { + if (\is_string($data)) { + $data = ['path' => $data]; + } elseif (!\is_array($data)) { + throw new \TypeError(sprintf('"%s": Argument $data is expected to be a string or array, got "%s".', __METHOD__, get_debug_type($data))); + } elseif ([] !== $data) { + $deprecation = false; + foreach ($data as $key => $val) { + if (\in_array($key, ['path', 'name', 'requirements', 'options', 'defaults', 'host', 'methods', 'schemes', 'condition', 'priority', 'locale', 'format', 'utf8', 'stateless', 'env', 'value'])) { + $deprecation = true; + } + } + + if ($deprecation) { + trigger_deprecation('symfony/routing', '5.3', 'Passing an array as first argument to "%s" is deprecated. Use named arguments instead.', __METHOD__); + } else { + $localizedPaths = $data; + $data = ['path' => $localizedPaths]; + } + } + if (null !== $path && !\is_string($path) && !\is_array($path)) { + throw new \TypeError(sprintf('"%s": Argument $path is expected to be a string, array or null, got "%s".', __METHOD__, get_debug_type($path))); + } + + $data['path'] = $data['path'] ?? $path; + $data['name'] = $data['name'] ?? $name; + $data['requirements'] = $data['requirements'] ?? $requirements; + $data['options'] = $data['options'] ?? $options; + $data['defaults'] = $data['defaults'] ?? $defaults; + $data['host'] = $data['host'] ?? $host; + $data['methods'] = $data['methods'] ?? $methods; + $data['schemes'] = $data['schemes'] ?? $schemes; + $data['condition'] = $data['condition'] ?? $condition; + $data['priority'] = $data['priority'] ?? $priority; + $data['locale'] = $data['locale'] ?? $locale; + $data['format'] = $data['format'] ?? $format; + $data['utf8'] = $data['utf8'] ?? $utf8; + $data['stateless'] = $data['stateless'] ?? $stateless; + $data['env'] = $data['env'] ?? $env; + + $data = array_filter($data, static function ($value): bool { + return null !== $value; + }); + + if (isset($data['localized_paths'])) { + throw new \BadMethodCallException(sprintf('Unknown property "localized_paths" on annotation "%s".', static::class)); + } + + if (isset($data['value'])) { + $data[\is_array($data['value']) ? 'localized_paths' : 'path'] = $data['value']; + unset($data['value']); + } + + if (isset($data['path']) && \is_array($data['path'])) { + $data['localized_paths'] = $data['path']; + unset($data['path']); + } + + if (isset($data['locale'])) { + $data['defaults']['_locale'] = $data['locale']; + unset($data['locale']); + } + + if (isset($data['format'])) { + $data['defaults']['_format'] = $data['format']; + unset($data['format']); + } + + if (isset($data['utf8'])) { + $data['options']['utf8'] = filter_var($data['utf8'], \FILTER_VALIDATE_BOOLEAN) ?: false; + unset($data['utf8']); + } + + if (isset($data['stateless'])) { + $data['defaults']['_stateless'] = filter_var($data['stateless'], \FILTER_VALIDATE_BOOLEAN) ?: false; + unset($data['stateless']); + } + + foreach ($data as $key => $value) { + $method = 'set'.str_replace('_', '', $key); + if (!method_exists($this, $method)) { + throw new \BadMethodCallException(sprintf('Unknown property "%s" on annotation "%s".', $key, static::class)); + } + $this->$method($value); + } + } + + public function setPath(string $path) + { + $this->path = $path; + } + + public function getPath() + { + return $this->path; + } + + public function setLocalizedPaths(array $localizedPaths) + { + $this->localizedPaths = $localizedPaths; + } + + public function getLocalizedPaths(): array + { + return $this->localizedPaths; + } + + public function setHost(string $pattern) + { + $this->host = $pattern; + } + + public function getHost() + { + return $this->host; + } + + public function setName(string $name) + { + $this->name = $name; + } + + public function getName() + { + return $this->name; + } + + public function setRequirements(array $requirements) + { + $this->requirements = $requirements; + } + + public function getRequirements() + { + return $this->requirements; + } + + public function setOptions(array $options) + { + $this->options = $options; + } + + public function getOptions() + { + return $this->options; + } + + public function setDefaults(array $defaults) + { + $this->defaults = $defaults; + } + + public function getDefaults() + { + return $this->defaults; + } + + public function setSchemes($schemes) + { + $this->schemes = \is_array($schemes) ? $schemes : [$schemes]; + } + + public function getSchemes() + { + return $this->schemes; + } + + public function setMethods($methods) + { + $this->methods = \is_array($methods) ? $methods : [$methods]; + } + + public function getMethods() + { + return $this->methods; + } + + public function setCondition(?string $condition) + { + $this->condition = $condition; + } + + public function getCondition() + { + return $this->condition; + } + + public function setPriority(int $priority): void + { + $this->priority = $priority; + } + + public function getPriority(): ?int + { + return $this->priority; + } + + public function setEnv(?string $env): void + { + $this->env = $env; + } + + public function getEnv(): ?string + { + return $this->env; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/CHANGELOG.md b/php/libraries/composer/vendor/symfony/routing/CHANGELOG.md new file mode 100644 index 0000000..b966389 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/CHANGELOG.md @@ -0,0 +1,296 @@ +CHANGELOG +========= + +5.3 +--- + + * Already encoded slashes are not decoded nor double-encoded anymore when generating URLs + * Add support for per-env configuration in XML and Yaml loaders + * Deprecate creating instances of the `Route` annotation class by passing an array of parameters + * Add `RoutingConfigurator::env()` to get the current environment + +5.2.0 +----- + + * Added support for inline definition of requirements and defaults for host + * Added support for `\A` and `\z` as regex start and end for route requirement + * Added support for `#[Route]` attributes + +5.1.0 +----- + + * added the protected method `PhpFileLoader::callConfigurator()` as extension point to ease custom routing configuration + * deprecated `RouteCollectionBuilder` in favor of `RoutingConfigurator`. + * added "priority" option to annotated routes + * added argument `$priority` to `RouteCollection::add()` + * deprecated the `RouteCompiler::REGEX_DELIMITER` constant + * added `ExpressionLanguageProvider` to expose extra functions to route conditions + * added support for a `stateless` keyword for configuring route stateless in PHP, YAML and XML configurations. + * added the "hosts" option to be able to configure the host per locale. + * added `RequestContext::fromUri()` to ease building the default context + +5.0.0 +----- + + * removed `PhpGeneratorDumper` and `PhpMatcherDumper` + * removed `generator_base_class`, `generator_cache_class`, `matcher_base_class` and `matcher_cache_class` router options + * `Serializable` implementing methods for `Route` and `CompiledRoute` are final + * removed referencing service route loaders with a single colon + * Removed `ServiceRouterLoader` and `ObjectRouteLoader`. + +4.4.0 +----- + + * Deprecated `ServiceRouterLoader` in favor of `ContainerLoader`. + * Deprecated `ObjectRouteLoader` in favor of `ObjectLoader`. + * Added a way to exclude patterns of resources from being imported by the `import()` method + +4.3.0 +----- + + * added `CompiledUrlMatcher` and `CompiledUrlMatcherDumper` + * added `CompiledUrlGenerator` and `CompiledUrlGeneratorDumper` + * deprecated `PhpGeneratorDumper` and `PhpMatcherDumper` + * deprecated `generator_base_class`, `generator_cache_class`, `matcher_base_class` and `matcher_cache_class` router options + * `Serializable` implementing methods for `Route` and `CompiledRoute` are marked as `@internal` and `@final`. + Instead of overwriting them, use `__serialize` and `__unserialize` as extension points which are forward compatible + with the new serialization methods in PHP 7.4. + * exposed `utf8` Route option, defaults "locale" and "format" in configuration loaders and configurators + * added support for invokable service route loaders + +4.2.0 +----- + + * added fallback to cultureless locale for internationalized routes + +4.0.0 +----- + + * dropped support for using UTF-8 route patterns without using the `utf8` option + * dropped support for using UTF-8 route requirements without using the `utf8` option + +3.4.0 +----- + + * Added `NoConfigurationException`. + * Added the possibility to define a prefix for all routes of a controller via @Route(name="prefix_") + * Added support for prioritized routing loaders. + * Add matched and default parameters to redirect responses + * Added support for a `controller` keyword for configuring route controllers in YAML and XML configurations. + +3.3.0 +----- + + * [DEPRECATION] Class parameters have been deprecated and will be removed in 4.0. + * router.options.generator_class + * router.options.generator_base_class + * router.options.generator_dumper_class + * router.options.matcher_class + * router.options.matcher_base_class + * router.options.matcher_dumper_class + * router.options.matcher.cache_class + * router.options.generator.cache_class + +3.2.0 +----- + + * Added support for `bool`, `int`, `float`, `string`, `list` and `map` defaults in XML configurations. + * Added support for UTF-8 requirements + +2.8.0 +----- + + * allowed specifying a directory to recursively load all routing configuration files it contains + * Added ObjectRouteLoader and ServiceRouteLoader that allow routes to be loaded + by calling a method on an object/service. + * [DEPRECATION] Deprecated the hardcoded value for the `$referenceType` argument of the `UrlGeneratorInterface::generate` method. + Use the constants defined in the `UrlGeneratorInterface` instead. + + Before: + + ```php + $router->generate('blog_show', ['slug' => 'my-blog-post'], true); + ``` + + After: + + ```php + use Symfony\Component\Routing\Generator\UrlGeneratorInterface; + + $router->generate('blog_show', ['slug' => 'my-blog-post'], UrlGeneratorInterface::ABSOLUTE_URL); + ``` + +2.5.0 +----- + + * [DEPRECATION] The `ApacheMatcherDumper` and `ApacheUrlMatcher` were deprecated and + will be removed in Symfony 3.0, since the performance gains were minimal and + it's hard to replicate the behavior of PHP implementation. + +2.3.0 +----- + + * added RequestContext::getQueryString() + +2.2.0 +----- + + * [DEPRECATION] Several route settings have been renamed (the old ones will be removed in 3.0): + + * The `pattern` setting for a route has been deprecated in favor of `path` + * The `_scheme` and `_method` requirements have been moved to the `schemes` and `methods` settings + + Before: + + ```yaml + article_edit: + pattern: /article/{id} + requirements: { '_method': 'POST|PUT', '_scheme': 'https', 'id': '\d+' } + ``` + + ```xml + + POST|PUT + https + \d+ + + ``` + + ```php + $route = new Route(); + $route->setPattern('/article/{id}'); + $route->setRequirement('_method', 'POST|PUT'); + $route->setRequirement('_scheme', 'https'); + ``` + + After: + + ```yaml + article_edit: + path: /article/{id} + methods: [POST, PUT] + schemes: https + requirements: { 'id': '\d+' } + ``` + + ```xml + + \d+ + + ``` + + ```php + $route = new Route(); + $route->setPath('/article/{id}'); + $route->setMethods(['POST', 'PUT']); + $route->setSchemes('https'); + ``` + + * [BC BREAK] RouteCollection does not behave like a tree structure anymore but as + a flat array of Routes. So when using PHP to build the RouteCollection, you must + make sure to add routes to the sub-collection before adding it to the parent + collection (this is not relevant when using YAML or XML for Route definitions). + + Before: + + ```php + $rootCollection = new RouteCollection(); + $subCollection = new RouteCollection(); + $rootCollection->addCollection($subCollection); + $subCollection->add('foo', new Route('/foo')); + ``` + + After: + + ```php + $rootCollection = new RouteCollection(); + $subCollection = new RouteCollection(); + $subCollection->add('foo', new Route('/foo')); + $rootCollection->addCollection($subCollection); + ``` + + Also one must call `addCollection` from the bottom to the top hierarchy. + So the correct sequence is the following (and not the reverse): + + ```php + $childCollection->addCollection($grandchildCollection); + $rootCollection->addCollection($childCollection); + ``` + + * [DEPRECATION] The methods `RouteCollection::getParent()` and `RouteCollection::getRoot()` + have been deprecated and will be removed in Symfony 2.3. + * [BC BREAK] Misusing the `RouteCollection::addPrefix` method to add defaults, requirements + or options without adding a prefix is not supported anymore. So if you called `addPrefix` + with an empty prefix or `/` only (both have no relevance), like + `addPrefix('', $defaultsArray, $requirementsArray, $optionsArray)` + you need to use the new dedicated methods `addDefaults($defaultsArray)`, + `addRequirements($requirementsArray)` or `addOptions($optionsArray)` instead. + * [DEPRECATION] The `$options` parameter to `RouteCollection::addPrefix()` has been deprecated + because adding options has nothing to do with adding a path prefix. If you want to add options + to all child routes of a RouteCollection, you can use `addOptions()`. + * [DEPRECATION] The method `RouteCollection::getPrefix()` has been deprecated + because it suggested that all routes in the collection would have this prefix, which is + not necessarily true. On top of that, since there is no tree structure anymore, this method + is also useless. Don't worry about performance, prefix optimization for matching is still done + in the dumper, which was also improved in 2.2.0 to find even more grouping possibilities. + * [DEPRECATION] `RouteCollection::addCollection(RouteCollection $collection)` should now only be + used with a single parameter. The other params `$prefix`, `$default`, `$requirements` and `$options` + will still work, but have been deprecated. The `addPrefix` method should be used for this + use-case instead. + Before: `$parentCollection->addCollection($collection, '/prefix', [...], [...])` + After: + ```php + $collection->addPrefix('/prefix', [...], [...]); + $parentCollection->addCollection($collection); + ``` + * added support for the method default argument values when defining a @Route + * Adjacent placeholders without separator work now, e.g. `/{x}{y}{z}.{_format}`. + * Characters that function as separator between placeholders are now whitelisted + to fix routes with normal text around a variable, e.g. `/prefix{var}suffix`. + * [BC BREAK] The default requirement of a variable has been changed slightly. + Previously it disallowed the previous and the next char around a variable. Now + it disallows the slash (`/`) and the next char. Using the previous char added + no value and was problematic because the route `/index.{_format}` would be + matched by `/index.ht/ml`. + * The default requirement now uses possessive quantifiers when possible which + improves matching performance by up to 20% because it prevents backtracking + when it's not needed. + * The ConfigurableRequirementsInterface can now also be used to disable the requirements + check on URL generation completely by calling `setStrictRequirements(null)`. It + improves performance in production environment as you should know that params always + pass the requirements (otherwise it would break your link anyway). + * There is no restriction on the route name anymore. So non-alphanumeric characters + are now also allowed. + * [BC BREAK] `RouteCompilerInterface::compile(Route $route)` was made static + (only relevant if you implemented your own RouteCompiler). + * Added possibility to generate relative paths and network paths in the UrlGenerator, e.g. + "../parent-file" and "//example.com/dir/file". The third parameter in + `UrlGeneratorInterface::generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)` + now accepts more values and you should use the constants defined in `UrlGeneratorInterface` for + claritiy. The old method calls with a Boolean parameter will continue to work because they + equal the signature using the constants. + +2.1.0 +----- + + * added RequestMatcherInterface + * added RequestContext::fromRequest() + * the UrlMatcher does not throw a \LogicException anymore when the required + scheme is not the current one + * added TraceableUrlMatcher + * added the possibility to define options, default values and requirements + for placeholders in prefix, including imported routes + * added RouterInterface::getRouteCollection + * [BC BREAK] the UrlMatcher urldecodes the route parameters only once, they + were decoded twice before. Note that the `urldecode()` calls have been + changed for a single `rawurldecode()` in order to support `+` for input + paths. + * added RouteCollection::getRoot method to retrieve the root of a + RouteCollection tree + * [BC BREAK] made RouteCollection::setParent private which could not have + been used anyway without creating inconsistencies + * [BC BREAK] RouteCollection::remove also removes a route from parent + collections (not only from its children) + * added ConfigurableRequirementsInterface that allows to disable exceptions + (and generate empty URLs instead) when generating a route with an invalid + parameter value diff --git a/php/libraries/composer/vendor/symfony/routing/CompiledRoute.php b/php/libraries/composer/vendor/symfony/routing/CompiledRoute.php new file mode 100644 index 0000000..64bf9ca --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/CompiledRoute.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\Routing; + +/** + * CompiledRoutes are returned by the RouteCompiler class. + * + * @author Fabien Potencier + */ +class CompiledRoute implements \Serializable +{ + private $variables; + private $tokens; + private $staticPrefix; + private $regex; + private $pathVariables; + private $hostVariables; + private $hostRegex; + private $hostTokens; + + /** + * @param string $staticPrefix The static prefix of the compiled route + * @param string $regex The regular expression to use to match this route + * @param array $tokens An array of tokens to use to generate URL for this route + * @param array $pathVariables An array of path variables + * @param string|null $hostRegex Host regex + * @param array $hostTokens Host tokens + * @param array $hostVariables An array of host variables + * @param array $variables An array of variables (variables defined in the path and in the host patterns) + */ + public function __construct(string $staticPrefix, string $regex, array $tokens, array $pathVariables, ?string $hostRegex = null, array $hostTokens = [], array $hostVariables = [], array $variables = []) + { + $this->staticPrefix = $staticPrefix; + $this->regex = $regex; + $this->tokens = $tokens; + $this->pathVariables = $pathVariables; + $this->hostRegex = $hostRegex; + $this->hostTokens = $hostTokens; + $this->hostVariables = $hostVariables; + $this->variables = $variables; + } + + public function __serialize(): array + { + return [ + 'vars' => $this->variables, + 'path_prefix' => $this->staticPrefix, + 'path_regex' => $this->regex, + 'path_tokens' => $this->tokens, + 'path_vars' => $this->pathVariables, + 'host_regex' => $this->hostRegex, + 'host_tokens' => $this->hostTokens, + 'host_vars' => $this->hostVariables, + ]; + } + + /** + * @internal + */ + final public function serialize(): string + { + return serialize($this->__serialize()); + } + + public function __unserialize(array $data): void + { + $this->variables = $data['vars']; + $this->staticPrefix = $data['path_prefix']; + $this->regex = $data['path_regex']; + $this->tokens = $data['path_tokens']; + $this->pathVariables = $data['path_vars']; + $this->hostRegex = $data['host_regex']; + $this->hostTokens = $data['host_tokens']; + $this->hostVariables = $data['host_vars']; + } + + /** + * @internal + */ + final public function unserialize($serialized) + { + $this->__unserialize(unserialize($serialized, ['allowed_classes' => false])); + } + + /** + * Returns the static prefix. + * + * @return string + */ + public function getStaticPrefix() + { + return $this->staticPrefix; + } + + /** + * Returns the regex. + * + * @return string + */ + public function getRegex() + { + return $this->regex; + } + + /** + * Returns the host regex. + * + * @return string|null + */ + public function getHostRegex() + { + return $this->hostRegex; + } + + /** + * Returns the tokens. + * + * @return array + */ + public function getTokens() + { + return $this->tokens; + } + + /** + * Returns the host tokens. + * + * @return array + */ + public function getHostTokens() + { + return $this->hostTokens; + } + + /** + * Returns the variables. + * + * @return array + */ + public function getVariables() + { + return $this->variables; + } + + /** + * Returns the path variables. + * + * @return array + */ + public function getPathVariables() + { + return $this->pathVariables; + } + + /** + * Returns the host variables. + * + * @return array + */ + public function getHostVariables() + { + return $this->hostVariables; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/DependencyInjection/RoutingResolverPass.php b/php/libraries/composer/vendor/symfony/routing/DependencyInjection/RoutingResolverPass.php new file mode 100644 index 0000000..0e9b9c8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/DependencyInjection/RoutingResolverPass.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Adds tagged routing.loader services to routing.resolver service. + * + * @author Fabien Potencier + */ +class RoutingResolverPass implements CompilerPassInterface +{ + use PriorityTaggedServiceTrait; + + private $resolverServiceId; + private $loaderTag; + + public function __construct(string $resolverServiceId = 'routing.resolver', string $loaderTag = 'routing.loader') + { + if (0 < \func_num_args()) { + trigger_deprecation('symfony/routing', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); + } + + $this->resolverServiceId = $resolverServiceId; + $this->loaderTag = $loaderTag; + } + + public function process(ContainerBuilder $container) + { + if (false === $container->hasDefinition($this->resolverServiceId)) { + return; + } + + $definition = $container->getDefinition($this->resolverServiceId); + + foreach ($this->findAndSortTaggedServices($this->loaderTag, $container) as $id) { + $definition->addMethodCall('addLoader', [new Reference($id)]); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/routing/Exception/ExceptionInterface.php new file mode 100644 index 0000000..22e72b1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Exception; + +/** + * ExceptionInterface. + * + * @author Alexandre Salomé + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/symfony/routing/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..950b9b1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/InvalidArgumentException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Exception; + +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/InvalidParameterException.php b/php/libraries/composer/vendor/symfony/routing/Exception/InvalidParameterException.php new file mode 100644 index 0000000..94d841f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/InvalidParameterException.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\Routing\Exception; + +/** + * Exception thrown when a parameter is not valid. + * + * @author Alexandre Salomé + */ +class InvalidParameterException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/MethodNotAllowedException.php b/php/libraries/composer/vendor/symfony/routing/Exception/MethodNotAllowedException.php new file mode 100644 index 0000000..a73e1e6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/MethodNotAllowedException.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Exception; + +/** + * The resource was found but the request method is not allowed. + * + * This exception should trigger an HTTP 405 response in your application code. + * + * @author Kris Wallsmith + */ +class MethodNotAllowedException extends \RuntimeException implements ExceptionInterface +{ + protected $allowedMethods = []; + + /** + * @param string[] $allowedMethods + */ + public function __construct(array $allowedMethods, ?string $message = '', int $code = 0, ?\Throwable $previous = null) + { + if (null === $message) { + trigger_deprecation('symfony/routing', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__); + + $message = ''; + } + + $this->allowedMethods = array_map('strtoupper', $allowedMethods); + + parent::__construct($message, $code, $previous); + } + + /** + * Gets the allowed HTTP methods. + * + * @return string[] + */ + public function getAllowedMethods() + { + return $this->allowedMethods; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/MissingMandatoryParametersException.php b/php/libraries/composer/vendor/symfony/routing/Exception/MissingMandatoryParametersException.php new file mode 100644 index 0000000..57f3a40 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/MissingMandatoryParametersException.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Exception; + +/** + * Exception thrown when a route cannot be generated because of missing + * mandatory parameters. + * + * @author Alexandre Salomé + */ +class MissingMandatoryParametersException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/NoConfigurationException.php b/php/libraries/composer/vendor/symfony/routing/Exception/NoConfigurationException.php new file mode 100644 index 0000000..333bc74 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/NoConfigurationException.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\Routing\Exception; + +/** + * Exception thrown when no routes are configured. + * + * @author Yonel Ceruto + */ +class NoConfigurationException extends ResourceNotFoundException +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/ResourceNotFoundException.php b/php/libraries/composer/vendor/symfony/routing/Exception/ResourceNotFoundException.php new file mode 100644 index 0000000..ccbca15 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/ResourceNotFoundException.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Exception; + +/** + * The resource was not found. + * + * This exception should trigger an HTTP 404 response in your application code. + * + * @author Kris Wallsmith + */ +class ResourceNotFoundException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/RouteCircularReferenceException.php b/php/libraries/composer/vendor/symfony/routing/Exception/RouteCircularReferenceException.php new file mode 100644 index 0000000..841e359 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/RouteCircularReferenceException.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\Routing\Exception; + +class RouteCircularReferenceException extends RuntimeException +{ + public function __construct(string $routeId, array $path) + { + parent::__construct(sprintf('Circular reference detected for route "%s", path: "%s".', $routeId, implode(' -> ', $path))); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/RouteNotFoundException.php b/php/libraries/composer/vendor/symfony/routing/Exception/RouteNotFoundException.php new file mode 100644 index 0000000..24ab0b4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/RouteNotFoundException.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\Routing\Exception; + +/** + * Exception thrown when a route does not exist. + * + * @author Alexandre Salomé + */ +class RouteNotFoundException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Exception/RuntimeException.php b/php/libraries/composer/vendor/symfony/routing/Exception/RuntimeException.php new file mode 100644 index 0000000..48da62e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Exception/RuntimeException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Exception; + +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/CompiledUrlGenerator.php b/php/libraries/composer/vendor/symfony/routing/Generator/CompiledUrlGenerator.php new file mode 100644 index 0000000..8af3ae7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/CompiledUrlGenerator.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Generator; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Routing\Exception\RouteNotFoundException; +use Symfony\Component\Routing\RequestContext; + +/** + * Generates URLs based on rules dumped by CompiledUrlGeneratorDumper. + */ +class CompiledUrlGenerator extends UrlGenerator +{ + private $compiledRoutes = []; + private $defaultLocale; + + public function __construct(array $compiledRoutes, RequestContext $context, ?LoggerInterface $logger = null, ?string $defaultLocale = null) + { + $this->compiledRoutes = $compiledRoutes; + $this->context = $context; + $this->logger = $logger; + $this->defaultLocale = $defaultLocale; + } + + public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH) + { + $locale = $parameters['_locale'] + ?? $this->context->getParameter('_locale') + ?: $this->defaultLocale; + + if (null !== $locale) { + do { + if (($this->compiledRoutes[$name.'.'.$locale][1]['_canonical_route'] ?? null) === $name) { + $name .= '.'.$locale; + break; + } + } while (false !== $locale = strstr($locale, '_', true)); + } + + if (!isset($this->compiledRoutes[$name])) { + throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); + } + + [$variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes, $deprecations] = $this->compiledRoutes[$name] + [6 => []]; + + foreach ($deprecations as $deprecation) { + trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']); + } + + if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) { + if (!\in_array('_locale', $variables, true)) { + unset($parameters['_locale']); + } elseif (!isset($parameters['_locale'])) { + $parameters['_locale'] = $defaults['_locale']; + } + } + + return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/ConfigurableRequirementsInterface.php b/php/libraries/composer/vendor/symfony/routing/Generator/ConfigurableRequirementsInterface.php new file mode 100644 index 0000000..568f7f7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/ConfigurableRequirementsInterface.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Generator; + +/** + * ConfigurableRequirementsInterface must be implemented by URL generators that + * can be configured whether an exception should be generated when the parameters + * do not match the requirements. It is also possible to disable the requirements + * check for URL generation completely. + * + * The possible configurations and use-cases: + * - setStrictRequirements(true): Throw an exception for mismatching requirements. This + * is mostly useful in development environment. + * - setStrictRequirements(false): Don't throw an exception but return an empty string as URL for + * mismatching requirements and log the problem. Useful when you cannot control all + * params because they come from third party libs but don't want to have a 404 in + * production environment. It should log the mismatch so one can review it. + * - setStrictRequirements(null): Return the URL with the given parameters without + * checking the requirements at all. When generating a URL you should either trust + * your params or you validated them beforehand because otherwise it would break your + * link anyway. So in production environment you should know that params always pass + * the requirements. Thus this option allows to disable the check on URL generation for + * performance reasons (saving a preg_match for each requirement every time a URL is + * generated). + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +interface ConfigurableRequirementsInterface +{ + /** + * Enables or disables the exception on incorrect parameters. + * Passing null will deactivate the requirements check completely. + */ + public function setStrictRequirements(?bool $enabled); + + /** + * Returns whether to throw an exception on incorrect parameters. + * Null means the requirements check is deactivated completely. + * + * @return bool|null + */ + public function isStrictRequirements(); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/CompiledUrlGeneratorDumper.php b/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/CompiledUrlGeneratorDumper.php new file mode 100644 index 0000000..9c6740b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/CompiledUrlGeneratorDumper.php @@ -0,0 +1,124 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Generator\Dumper; + +use Symfony\Component\Routing\Exception\RouteCircularReferenceException; +use Symfony\Component\Routing\Exception\RouteNotFoundException; +use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper; + +/** + * CompiledUrlGeneratorDumper creates a PHP array to be used with CompiledUrlGenerator. + * + * @author Fabien Potencier + * @author Tobias Schultze + * @author Nicolas Grekas + */ +class CompiledUrlGeneratorDumper extends GeneratorDumper +{ + public function getCompiledRoutes(): array + { + $compiledRoutes = []; + foreach ($this->getRoutes()->all() as $name => $route) { + $compiledRoute = $route->compile(); + + $compiledRoutes[$name] = [ + $compiledRoute->getVariables(), + $route->getDefaults(), + $route->getRequirements(), + $compiledRoute->getTokens(), + $compiledRoute->getHostTokens(), + $route->getSchemes(), + [], + ]; + } + + return $compiledRoutes; + } + + public function getCompiledAliases(): array + { + $routes = $this->getRoutes(); + $compiledAliases = []; + foreach ($routes->getAliases() as $name => $alias) { + $deprecations = $alias->isDeprecated() ? [$alias->getDeprecation($name)] : []; + $currentId = $alias->getId(); + $visited = []; + while (null !== $alias = $routes->getAlias($currentId) ?? null) { + if (false !== $searchKey = array_search($currentId, $visited)) { + $visited[] = $currentId; + + throw new RouteCircularReferenceException($currentId, \array_slice($visited, $searchKey)); + } + + if ($alias->isDeprecated()) { + $deprecations[] = $deprecation = $alias->getDeprecation($currentId); + trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']); + } + + $visited[] = $currentId; + $currentId = $alias->getId(); + } + + if (null === $target = $routes->get($currentId)) { + throw new RouteNotFoundException(sprintf('Target route "%s" for alias "%s" does not exist.', $currentId, $name)); + } + + $compiledTarget = $target->compile(); + + $compiledAliases[$name] = [ + $compiledTarget->getVariables(), + $target->getDefaults(), + $target->getRequirements(), + $compiledTarget->getTokens(), + $compiledTarget->getHostTokens(), + $target->getSchemes(), + $deprecations, + ]; + } + + return $compiledAliases; + } + + /** + * {@inheritdoc} + */ + public function dump(array $options = []) + { + return <<generateDeclaredRoutes()} +]; + +EOF; + } + + /** + * Generates PHP code representing an array of defined routes + * together with the routes properties (e.g. requirements). + */ + private function generateDeclaredRoutes(): string + { + $routes = ''; + foreach ($this->getCompiledRoutes() as $name => $properties) { + $routes .= sprintf("\n '%s' => %s,", $name, CompiledUrlMatcherDumper::export($properties)); + } + + foreach ($this->getCompiledAliases() as $alias => $properties) { + $routes .= sprintf("\n '%s' => %s,", $alias, CompiledUrlMatcherDumper::export($properties)); + } + + return $routes; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/GeneratorDumper.php b/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/GeneratorDumper.php new file mode 100644 index 0000000..659c5ba --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/GeneratorDumper.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\Routing\Generator\Dumper; + +use Symfony\Component\Routing\RouteCollection; + +/** + * GeneratorDumper is the base class for all built-in generator dumpers. + * + * @author Fabien Potencier + */ +abstract class GeneratorDumper implements GeneratorDumperInterface +{ + private $routes; + + public function __construct(RouteCollection $routes) + { + $this->routes = $routes; + } + + /** + * {@inheritdoc} + */ + public function getRoutes() + { + return $this->routes; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/GeneratorDumperInterface.php b/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/GeneratorDumperInterface.php new file mode 100644 index 0000000..d4a248a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/Dumper/GeneratorDumperInterface.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\Routing\Generator\Dumper; + +use Symfony\Component\Routing\RouteCollection; + +/** + * GeneratorDumperInterface is the interface that all generator dumper classes must implement. + * + * @author Fabien Potencier + */ +interface GeneratorDumperInterface +{ + /** + * Dumps a set of routes to a string representation of executable code + * that can then be used to generate a URL of such a route. + * + * @return string + */ + public function dump(array $options = []); + + /** + * Gets the routes to dump. + * + * @return RouteCollection + */ + public function getRoutes(); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/UrlGenerator.php b/php/libraries/composer/vendor/symfony/routing/Generator/UrlGenerator.php new file mode 100644 index 0000000..4419e9e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/UrlGenerator.php @@ -0,0 +1,378 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Generator; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Routing\Exception\InvalidParameterException; +use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; +use Symfony\Component\Routing\Exception\RouteNotFoundException; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\RouteCollection; + +/** + * UrlGenerator can generate a URL or a path for any route in the RouteCollection + * based on the passed parameters. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface +{ + private const QUERY_FRAGMENT_DECODED = [ + // RFC 3986 explicitly allows those in the query/fragment to reference other URIs unencoded + '%2F' => '/', + '%3F' => '?', + // reserved chars that have no special meaning for HTTP URIs in a query or fragment + // this excludes esp. "&", "=" and also "+" because PHP would treat it as a space (form-encoded) + '%40' => '@', + '%3A' => ':', + '%21' => '!', + '%3B' => ';', + '%2C' => ',', + '%2A' => '*', + ]; + + protected $routes; + protected $context; + + /** + * @var bool|null + */ + protected $strictRequirements = true; + + protected $logger; + + private $defaultLocale; + + /** + * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL. + * + * PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars + * to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g. + * "?" and "#" (would be interpreted wrongly as query and fragment identifier), + * "'" and """ (are used as delimiters in HTML). + */ + protected $decodedChars = [ + // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning + // some webservers don't allow the slash in encoded form in the path for security reasons anyway + // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss + '%2F' => '/', + '%252F' => '%2F', + // the following chars are general delimiters in the URI specification but have only special meaning in the authority component + // so they can safely be used in the path in unencoded form + '%40' => '@', + '%3A' => ':', + // these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally + // so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability + '%3B' => ';', + '%2C' => ',', + '%3D' => '=', + '%2B' => '+', + '%21' => '!', + '%2A' => '*', + '%7C' => '|', + ]; + + public function __construct(RouteCollection $routes, RequestContext $context, ?LoggerInterface $logger = null, ?string $defaultLocale = null) + { + $this->routes = $routes; + $this->context = $context; + $this->logger = $logger; + $this->defaultLocale = $defaultLocale; + } + + /** + * {@inheritdoc} + */ + public function setContext(RequestContext $context) + { + $this->context = $context; + } + + /** + * {@inheritdoc} + */ + public function getContext() + { + return $this->context; + } + + /** + * {@inheritdoc} + */ + public function setStrictRequirements(?bool $enabled) + { + $this->strictRequirements = $enabled; + } + + /** + * {@inheritdoc} + */ + public function isStrictRequirements() + { + return $this->strictRequirements; + } + + /** + * {@inheritdoc} + */ + public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH) + { + $route = null; + $locale = $parameters['_locale'] + ?? $this->context->getParameter('_locale') + ?: $this->defaultLocale; + + if (null !== $locale) { + do { + if (null !== ($route = $this->routes->get($name.'.'.$locale)) && $route->getDefault('_canonical_route') === $name) { + break; + } + } while (false !== $locale = strstr($locale, '_', true)); + } + + if (null === $route = $route ?? $this->routes->get($name)) { + throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); + } + + // the Route has a cache of its own and is not recompiled as long as it does not get modified + $compiledRoute = $route->compile(); + + $defaults = $route->getDefaults(); + $variables = $compiledRoute->getVariables(); + + if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) { + if (!\in_array('_locale', $variables, true)) { + unset($parameters['_locale']); + } elseif (!isset($parameters['_locale'])) { + $parameters['_locale'] = $defaults['_locale']; + } + } + + return $this->doGenerate($variables, $defaults, $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes()); + } + + /** + * @return string + * + * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route + * @throws InvalidParameterException When a parameter value for a placeholder is not correct because + * it does not match the requirement + */ + protected function doGenerate(array $variables, array $defaults, array $requirements, array $tokens, array $parameters, string $name, int $referenceType, array $hostTokens, array $requiredSchemes = []) + { + $variables = array_flip($variables); + $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); + + // all params must be given + if ($diff = array_diff_key($variables, $mergedParams)) { + throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); + } + + $url = ''; + $optional = true; + $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.'; + foreach ($tokens as $token) { + if ('variable' === $token[0]) { + $varName = $token[3]; + // variable is not important by default + $important = $token[5] ?? false; + + if (!$optional || $important || !\array_key_exists($varName, $defaults) || (null !== $mergedParams[$varName] && (string) $mergedParams[$varName] !== (string) $defaults[$varName])) { + // check requirement (while ignoring look-around patterns) + if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\(\?(?:=|<=|!|strictRequirements) { + throw new InvalidParameterException(strtr($message, ['{parameter}' => $varName, '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$varName]])); + } + + if ($this->logger) { + $this->logger->error($message, ['parameter' => $varName, 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$varName]]); + } + + return ''; + } + + $url = $token[1].$mergedParams[$varName].$url; + $optional = false; + } + } else { + // static text + $url = $token[1].$url; + $optional = false; + } + } + + if ('' === $url) { + $url = '/'; + } + + // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request) + $url = strtr(rawurlencode($url), $this->decodedChars); + + // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 + // so we need to encode them as they are not used for this purpose here + // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route + $url = strtr($url, ['/../' => '/%2E%2E/', '/./' => '/%2E/']); + if (str_ends_with($url, '/..')) { + $url = substr($url, 0, -2).'%2E%2E'; + } elseif (str_ends_with($url, '/.')) { + $url = substr($url, 0, -1).'%2E'; + } + + $schemeAuthority = ''; + $host = $this->context->getHost(); + $scheme = $this->context->getScheme(); + + if ($requiredSchemes) { + if (!\in_array($scheme, $requiredSchemes, true)) { + $referenceType = self::ABSOLUTE_URL; + $scheme = current($requiredSchemes); + } + } + + if ($hostTokens) { + $routeHost = ''; + foreach ($hostTokens as $token) { + if ('variable' === $token[0]) { + // check requirement (while ignoring look-around patterns) + if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\(\?(?:=|<=|!|strictRequirements) { + throw new InvalidParameterException(strtr($message, ['{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]])); + } + + if ($this->logger) { + $this->logger->error($message, ['parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]]); + } + + return ''; + } + + $routeHost = $token[1].$mergedParams[$token[3]].$routeHost; + } else { + $routeHost = $token[1].$routeHost; + } + } + + if ($routeHost !== $host) { + $host = $routeHost; + if (self::ABSOLUTE_URL !== $referenceType) { + $referenceType = self::NETWORK_PATH; + } + } + } + + if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { + if ('' !== $host || ('' !== $scheme && 'http' !== $scheme && 'https' !== $scheme)) { + $port = ''; + if ('http' === $scheme && 80 !== $this->context->getHttpPort()) { + $port = ':'.$this->context->getHttpPort(); + } elseif ('https' === $scheme && 443 !== $this->context->getHttpsPort()) { + $port = ':'.$this->context->getHttpsPort(); + } + + $schemeAuthority = self::NETWORK_PATH === $referenceType || '' === $scheme ? '//' : "$scheme://"; + $schemeAuthority .= $host.$port; + } + } + + if (self::RELATIVE_PATH === $referenceType) { + $url = self::getRelativePath($this->context->getPathInfo(), $url); + } else { + $url = $schemeAuthority.$this->context->getBaseUrl().$url; + } + + // add a query string if needed + $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) { + return $a == $b ? 0 : 1; + }); + + array_walk_recursive($extra, $caster = static function (&$v) use (&$caster) { + if (\is_object($v)) { + if ($vars = get_object_vars($v)) { + array_walk_recursive($vars, $caster); + $v = $vars; + } elseif (method_exists($v, '__toString')) { + $v = (string) $v; + } + } + }); + + // extract fragment + $fragment = $defaults['_fragment'] ?? ''; + + if (isset($extra['_fragment'])) { + $fragment = $extra['_fragment']; + unset($extra['_fragment']); + } + + if ($extra && $query = http_build_query($extra, '', '&', \PHP_QUERY_RFC3986)) { + $url .= '?'.strtr($query, self::QUERY_FRAGMENT_DECODED); + } + + if ('' !== $fragment) { + $url .= '#'.strtr(rawurlencode($fragment), self::QUERY_FRAGMENT_DECODED); + } + + return $url; + } + + /** + * Returns the target path as relative reference from the base path. + * + * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash. + * Both paths must be absolute and not contain relative parts. + * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. + * Furthermore, they can be used to reduce the link size in documents. + * + * Example target paths, given a base path of "/a/b/c/d": + * - "/a/b/c/d" -> "" + * - "/a/b/c/" -> "./" + * - "/a/b/" -> "../" + * - "/a/b/c/other" -> "other" + * - "/a/x/y" -> "../../x/y" + * + * @param string $basePath The base path + * @param string $targetPath The target path + * + * @return string + */ + public static function getRelativePath(string $basePath, string $targetPath) + { + if ($basePath === $targetPath) { + return ''; + } + + $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath); + $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath); + array_pop($sourceDirs); + $targetFile = array_pop($targetDirs); + + foreach ($sourceDirs as $i => $dir) { + if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) { + unset($sourceDirs[$i], $targetDirs[$i]); + } else { + break; + } + } + + $targetDirs[] = $targetFile; + $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs); + + // A reference to the same base directory or an empty subdirectory must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name + // (see http://tools.ietf.org/html/rfc3986#section-4.2). + return '' === $path || '/' === $path[0] + || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) + ? "./$path" : $path; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Generator/UrlGeneratorInterface.php b/php/libraries/composer/vendor/symfony/routing/Generator/UrlGeneratorInterface.php new file mode 100644 index 0000000..c6d5005 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Generator/UrlGeneratorInterface.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Generator; + +use Symfony\Component\Routing\Exception\InvalidParameterException; +use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; +use Symfony\Component\Routing\Exception\RouteNotFoundException; +use Symfony\Component\Routing\RequestContextAwareInterface; + +/** + * UrlGeneratorInterface is the interface that all URL generator classes must implement. + * + * The constants in this interface define the different types of resource references that + * are declared in RFC 3986: http://tools.ietf.org/html/rfc3986 + * We are using the term "URL" instead of "URI" as this is more common in web applications + * and we do not need to distinguish them as the difference is mostly semantical and + * less technical. Generating URIs, i.e. representation-independent resource identifiers, + * is also possible. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +interface UrlGeneratorInterface extends RequestContextAwareInterface +{ + /** + * Generates an absolute URL, e.g. "http://example.com/dir/file". + */ + public const ABSOLUTE_URL = 0; + + /** + * Generates an absolute path, e.g. "/dir/file". + */ + public const ABSOLUTE_PATH = 1; + + /** + * Generates a relative path based on the current request path, e.g. "../parent-file". + * + * @see UrlGenerator::getRelativePath() + */ + public const RELATIVE_PATH = 2; + + /** + * Generates a network path, e.g. "//example.com/dir/file". + * Such reference reuses the current scheme but specifies the host. + */ + public const NETWORK_PATH = 3; + + /** + * Generates a URL or path for a specific route based on the given parameters. + * + * Parameters that reference placeholders in the route pattern will substitute them in the + * path or host. Extra params are added as query string to the URL. + * + * When the passed reference type cannot be generated for the route because it requires a different + * host or scheme than the current one, the method will return a more comprehensive reference + * that includes the required params. For example, when you call this method with $referenceType = ABSOLUTE_PATH + * but the route requires the https scheme whereas the current scheme is http, it will instead return an + * ABSOLUTE_URL with the https scheme and the current host. This makes sure the generated URL matches + * the route in any case. + * + * If there is no route with the given name, the generator must throw the RouteNotFoundException. + * + * The special parameter _fragment will be used as the document fragment suffixed to the final URL. + * + * @return string + * + * @throws RouteNotFoundException If the named route doesn't exist + * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route + * @throws InvalidParameterException When a parameter value for a placeholder is not correct because + * it does not match the requirement + */ + public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH); +} diff --git a/php/libraries/composer/vendor/symfony/routing/LICENSE b/php/libraries/composer/vendor/symfony/routing/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationClassLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationClassLoader.php new file mode 100644 index 0000000..c0bcb47 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationClassLoader.php @@ -0,0 +1,394 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Doctrine\Common\Annotations\Reader; +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\Config\Loader\LoaderResolverInterface; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\Annotation\Route as RouteAnnotation; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * AnnotationClassLoader loads routing information from a PHP class and its methods. + * + * You need to define an implementation for the configureRoute() method. Most of the + * time, this method should define some PHP callable to be called for the route + * (a controller in MVC speak). + * + * The @Route annotation can be set on the class (for global parameters), + * and on each method. + * + * The @Route annotation main value is the route path. The annotation also + * recognizes several parameters: requirements, options, defaults, schemes, + * methods, host, and name. The name parameter is mandatory. + * Here is an example of how you should be able to use it: + * /** + * * @Route("/Blog") + * * / + * class Blog + * { + * /** + * * @Route("/", name="blog_index") + * * / + * public function index() + * { + * } + * /** + * * @Route("/{id}", name="blog_post", requirements = {"id" = "\d+"}) + * * / + * public function show() + * { + * } + * } + * + * On PHP 8, the annotation class can be used as an attribute as well: + * #[Route('/Blog')] + * class Blog + * { + * #[Route('/', name: 'blog_index')] + * public function index() + * { + * } + * #[Route('/{id}', name: 'blog_post', requirements: ["id" => '\d+'])] + * public function show() + * { + * } + * } + + * + * @author Fabien Potencier + * @author Alexander M. Turek + */ +abstract class AnnotationClassLoader implements LoaderInterface +{ + protected $reader; + protected $env; + + /** + * @var string + */ + protected $routeAnnotationClass = RouteAnnotation::class; + + /** + * @var int + */ + protected $defaultRouteIndex = 0; + + public function __construct(?Reader $reader = null, ?string $env = null) + { + $this->reader = $reader; + $this->env = $env; + } + + /** + * Sets the annotation class to read route properties from. + */ + public function setRouteAnnotationClass(string $class) + { + $this->routeAnnotationClass = $class; + } + + /** + * Loads from annotations from a class. + * + * @param string $class A class name + * + * @return RouteCollection + * + * @throws \InvalidArgumentException When route can't be parsed + */ + public function load($class, ?string $type = null) + { + if (!class_exists($class)) { + throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class)); + } + + $class = new \ReflectionClass($class); + if ($class->isAbstract()) { + throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName())); + } + + $globals = $this->getGlobals($class); + + $collection = new RouteCollection(); + $collection->addResource(new FileResource($class->getFileName())); + + if ($globals['env'] && $this->env !== $globals['env']) { + return $collection; + } + + foreach ($class->getMethods() as $method) { + $this->defaultRouteIndex = 0; + foreach ($this->getAnnotations($method) as $annot) { + $this->addRoute($collection, $annot, $globals, $class, $method); + } + } + + if (0 === $collection->count() && $class->hasMethod('__invoke')) { + $globals = $this->resetGlobals(); + foreach ($this->getAnnotations($class) as $annot) { + $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke')); + } + } + + return $collection; + } + + /** + * @param RouteAnnotation $annot or an object that exposes a similar interface + */ + protected function addRoute(RouteCollection $collection, object $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method) + { + if ($annot->getEnv() && $annot->getEnv() !== $this->env) { + return; + } + + $name = $annot->getName(); + if (null === $name) { + $name = $this->getDefaultRouteName($class, $method); + } + $name = $globals['name'].$name; + + $requirements = $annot->getRequirements(); + + foreach ($requirements as $placeholder => $requirement) { + if (\is_int($placeholder)) { + throw new \InvalidArgumentException(sprintf('A placeholder name must be a string (%d given). Did you forget to specify the placeholder key for the requirement "%s" of route "%s" in "%s::%s()"?', $placeholder, $requirement, $name, $class->getName(), $method->getName())); + } + } + + $defaults = array_replace($globals['defaults'], $annot->getDefaults()); + $requirements = array_replace($globals['requirements'], $requirements); + $options = array_replace($globals['options'], $annot->getOptions()); + $schemes = array_merge($globals['schemes'], $annot->getSchemes()); + $methods = array_merge($globals['methods'], $annot->getMethods()); + + $host = $annot->getHost(); + if (null === $host) { + $host = $globals['host']; + } + + $condition = $annot->getCondition() ?? $globals['condition']; + $priority = $annot->getPriority() ?? $globals['priority']; + + $path = $annot->getLocalizedPaths() ?: $annot->getPath(); + $prefix = $globals['localized_paths'] ?: $globals['path']; + $paths = []; + + if (\is_array($path)) { + if (!\is_array($prefix)) { + foreach ($path as $locale => $localePath) { + $paths[$locale] = $prefix.$localePath; + } + } elseif ($missing = array_diff_key($prefix, $path)) { + throw new \LogicException(sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing)))); + } else { + foreach ($path as $locale => $localePath) { + if (!isset($prefix[$locale])) { + throw new \LogicException(sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name)); + } + + $paths[$locale] = $prefix[$locale].$localePath; + } + } + } elseif (\is_array($prefix)) { + foreach ($prefix as $locale => $localePrefix) { + $paths[$locale] = $localePrefix.$path; + } + } else { + $paths[] = $prefix.$path; + } + + foreach ($method->getParameters() as $param) { + if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) { + continue; + } + foreach ($paths as $locale => $path) { + if (preg_match(sprintf('/\{%s(?:<.*?>)?\}/', preg_quote($param->name)), $path)) { + $defaults[$param->name] = $param->getDefaultValue(); + break; + } + } + } + + foreach ($paths as $locale => $path) { + $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition); + $this->configureRoute($route, $class, $method, $annot); + if (0 !== $locale) { + $route->setDefault('_locale', $locale); + $route->setRequirement('_locale', preg_quote($locale)); + $route->setDefault('_canonical_route', $name); + $collection->add($name.'.'.$locale, $route, $priority); + } else { + $collection->add($name, $route, $priority); + } + } + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'annotation' === $type); + } + + /** + * {@inheritdoc} + */ + public function setResolver(LoaderResolverInterface $resolver) + { + } + + /** + * {@inheritdoc} + */ + public function getResolver() + { + } + + /** + * Gets the default route name for a class method. + * + * @return string + */ + protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method) + { + $name = str_replace('\\', '_', $class->name).'_'.$method->name; + $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name); + if ($this->defaultRouteIndex > 0) { + $name .= '_'.$this->defaultRouteIndex; + } + ++$this->defaultRouteIndex; + + return $name; + } + + protected function getGlobals(\ReflectionClass $class) + { + $globals = $this->resetGlobals(); + + $annot = null; + if (\PHP_VERSION_ID >= 80000 && ($attribute = $class->getAttributes($this->routeAnnotationClass, \ReflectionAttribute::IS_INSTANCEOF)[0] ?? null)) { + $annot = $attribute->newInstance(); + } + if (!$annot && $this->reader) { + $annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass); + } + + if ($annot) { + if (null !== $annot->getName()) { + $globals['name'] = $annot->getName(); + } + + if (null !== $annot->getPath()) { + $globals['path'] = $annot->getPath(); + } + + $globals['localized_paths'] = $annot->getLocalizedPaths(); + + if (null !== $annot->getRequirements()) { + $globals['requirements'] = $annot->getRequirements(); + } + + if (null !== $annot->getOptions()) { + $globals['options'] = $annot->getOptions(); + } + + if (null !== $annot->getDefaults()) { + $globals['defaults'] = $annot->getDefaults(); + } + + if (null !== $annot->getSchemes()) { + $globals['schemes'] = $annot->getSchemes(); + } + + if (null !== $annot->getMethods()) { + $globals['methods'] = $annot->getMethods(); + } + + if (null !== $annot->getHost()) { + $globals['host'] = $annot->getHost(); + } + + if (null !== $annot->getCondition()) { + $globals['condition'] = $annot->getCondition(); + } + + $globals['priority'] = $annot->getPriority() ?? 0; + $globals['env'] = $annot->getEnv(); + + foreach ($globals['requirements'] as $placeholder => $requirement) { + if (\is_int($placeholder)) { + throw new \InvalidArgumentException(sprintf('A placeholder name must be a string (%d given). Did you forget to specify the placeholder key for the requirement "%s" in "%s"?', $placeholder, $requirement, $class->getName())); + } + } + } + + return $globals; + } + + private function resetGlobals(): array + { + return [ + 'path' => null, + 'localized_paths' => [], + 'requirements' => [], + 'options' => [], + 'defaults' => [], + 'schemes' => [], + 'methods' => [], + 'host' => '', + 'condition' => '', + 'name' => '', + 'priority' => 0, + 'env' => null, + ]; + } + + protected function createRoute(string $path, array $defaults, array $requirements, array $options, ?string $host, array $schemes, array $methods, ?string $condition) + { + return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition); + } + + abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot); + + /** + * @param \ReflectionClass|\ReflectionMethod $reflection + * + * @return iterable + */ + private function getAnnotations(object $reflection): iterable + { + if (\PHP_VERSION_ID >= 80000) { + foreach ($reflection->getAttributes($this->routeAnnotationClass, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { + yield $attribute->newInstance(); + } + } + + if (!$this->reader) { + return; + } + + $anntotations = $reflection instanceof \ReflectionClass + ? $this->reader->getClassAnnotations($reflection) + : $this->reader->getMethodAnnotations($reflection); + + foreach ($anntotations as $annotation) { + if ($annotation instanceof $this->routeAnnotationClass) { + yield $annotation; + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationDirectoryLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationDirectoryLoader.php new file mode 100644 index 0000000..8cd60f8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationDirectoryLoader.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Resource\DirectoryResource; +use Symfony\Component\Routing\RouteCollection; + +/** + * AnnotationDirectoryLoader loads routing information from annotations set + * on PHP classes and methods. + * + * @author Fabien Potencier + */ +class AnnotationDirectoryLoader extends AnnotationFileLoader +{ + /** + * Loads from annotations from a directory. + * + * @param string $path A directory path + * @param string|null $type The resource type + * + * @return RouteCollection + * + * @throws \InvalidArgumentException When the directory does not exist or its routes cannot be parsed + */ + public function load($path, ?string $type = null) + { + if (!is_dir($dir = $this->locator->locate($path))) { + return parent::supports($path, $type) ? parent::load($path, $type) : new RouteCollection(); + } + + $collection = new RouteCollection(); + $collection->addResource(new DirectoryResource($dir, '/\.php$/')); + $files = iterator_to_array(new \RecursiveIteratorIterator( + new \RecursiveCallbackFilterIterator( + new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), + function (\SplFileInfo $current) { + return '.' !== substr($current->getBasename(), 0, 1); + } + ), + \RecursiveIteratorIterator::LEAVES_ONLY + )); + usort($files, function (\SplFileInfo $a, \SplFileInfo $b) { + return (string) $a > (string) $b ? 1 : -1; + }); + + foreach ($files as $file) { + if (!$file->isFile() || !str_ends_with($file->getFilename(), '.php')) { + continue; + } + + if ($class = $this->findClass($file)) { + $refl = new \ReflectionClass($class); + if ($refl->isAbstract()) { + continue; + } + + $collection->addCollection($this->loader->load($class, $type)); + } + } + + return $collection; + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + if ('annotation' === $type) { + return true; + } + + if ($type || !\is_string($resource)) { + return false; + } + + try { + return is_dir($this->locator->locate($resource)); + } catch (\Exception $e) { + return false; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationFileLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationFileLoader.php new file mode 100644 index 0000000..a1d70c0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/AnnotationFileLoader.php @@ -0,0 +1,146 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\FileLocatorInterface; +use Symfony\Component\Config\Loader\FileLoader; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\RouteCollection; + +/** + * AnnotationFileLoader loads routing information from annotations set + * on a PHP class and its methods. + * + * @author Fabien Potencier + */ +class AnnotationFileLoader extends FileLoader +{ + protected $loader; + + public function __construct(FileLocatorInterface $locator, AnnotationClassLoader $loader) + { + if (!\function_exists('token_get_all')) { + throw new \LogicException('The Tokenizer extension is required for the routing annotation loaders.'); + } + + parent::__construct($locator); + + $this->loader = $loader; + } + + /** + * Loads from annotations from a file. + * + * @param string $file A PHP file path + * @param string|null $type The resource type + * + * @return RouteCollection|null + * + * @throws \InvalidArgumentException When the file does not exist or its routes cannot be parsed + */ + public function load($file, ?string $type = null) + { + $path = $this->locator->locate($file); + + $collection = new RouteCollection(); + if ($class = $this->findClass($path)) { + $refl = new \ReflectionClass($class); + if ($refl->isAbstract()) { + return null; + } + + $collection->addResource(new FileResource($path)); + $collection->addCollection($this->loader->load($class, $type)); + } + + gc_mem_caches(); + + return $collection; + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'annotation' === $type); + } + + /** + * Returns the full class name for the first class in the file. + * + * @return string|false + */ + protected function findClass(string $file) + { + $class = false; + $namespace = false; + $tokens = token_get_all(file_get_contents($file)); + + if (1 === \count($tokens) && \T_INLINE_HTML === $tokens[0][0]) { + throw new \InvalidArgumentException(sprintf('The file "%s" does not contain PHP code. Did you forgot to add the " true, \T_STRING => true]; + if (\defined('T_NAME_QUALIFIED')) { + $nsTokens[\T_NAME_QUALIFIED] = true; + } + for ($i = 0; isset($tokens[$i]); ++$i) { + $token = $tokens[$i]; + if (!isset($token[1])) { + continue; + } + + if (true === $class && \T_STRING === $token[0]) { + return $namespace.'\\'.$token[1]; + } + + if (true === $namespace && isset($nsTokens[$token[0]])) { + $namespace = $token[1]; + while (isset($tokens[++$i][1], $nsTokens[$tokens[$i][0]])) { + $namespace .= $tokens[$i][1]; + } + $token = $tokens[$i]; + } + + if (\T_CLASS === $token[0]) { + // Skip usage of ::class constant and anonymous classes + $skipClassToken = false; + for ($j = $i - 1; $j > 0; --$j) { + if (!isset($tokens[$j][1])) { + if ('(' === $tokens[$j] || ',' === $tokens[$j]) { + $skipClassToken = true; + } + break; + } + + if (\T_DOUBLE_COLON === $tokens[$j][0] || \T_NEW === $tokens[$j][0]) { + $skipClassToken = true; + break; + } elseif (!\in_array($tokens[$j][0], [\T_WHITESPACE, \T_DOC_COMMENT, \T_COMMENT])) { + break; + } + } + + if (!$skipClassToken) { + $class = true; + } + } + + if (\T_NAMESPACE === $token[0]) { + $namespace = true; + } + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/ClosureLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/ClosureLoader.php new file mode 100644 index 0000000..a5081ca --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/ClosureLoader.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 Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\Loader; +use Symfony\Component\Routing\RouteCollection; + +/** + * ClosureLoader loads routes from a PHP closure. + * + * The Closure must return a RouteCollection instance. + * + * @author Fabien Potencier + */ +class ClosureLoader extends Loader +{ + /** + * Loads a Closure. + * + * @param \Closure $closure A Closure + * @param string|null $type The resource type + * + * @return RouteCollection + */ + public function load($closure, ?string $type = null) + { + return $closure($this->env); + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return $resource instanceof \Closure && (!$type || 'closure' === $type); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/AliasConfigurator.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/AliasConfigurator.php new file mode 100644 index 0000000..4b2206e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/AliasConfigurator.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader\Configurator; + +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\Routing\Alias; + +class AliasConfigurator +{ + private $alias; + + public function __construct(Alias $alias) + { + $this->alias = $alias; + } + + /** + * Whether this alias is deprecated, that means it should not be called anymore. + * + * @param string $package The name of the composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The deprecation message to use + * + * @return $this + * + * @throws InvalidArgumentException when the message template is invalid + */ + public function deprecate(string $package, string $version, string $message): self + { + $this->alias->setDeprecated($package, $version, $message); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/CollectionConfigurator.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/CollectionConfigurator.php new file mode 100644 index 0000000..ec59f7e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/CollectionConfigurator.php @@ -0,0 +1,125 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader\Configurator; + +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * @author Nicolas Grekas + */ +class CollectionConfigurator +{ + use Traits\AddTrait; + use Traits\HostTrait; + use Traits\RouteTrait; + + private $parent; + private $parentConfigurator; + private $parentPrefixes; + private $host; + + public function __construct(RouteCollection $parent, string $name, ?self $parentConfigurator = null, ?array $parentPrefixes = null) + { + $this->parent = $parent; + $this->name = $name; + $this->collection = new RouteCollection(); + $this->route = new Route(''); + $this->parentConfigurator = $parentConfigurator; // for GC control + $this->parentPrefixes = $parentPrefixes; + } + + /** + * @return array + */ + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + if (null === $this->prefixes) { + $this->collection->addPrefix($this->route->getPath()); + } + if (null !== $this->host) { + $this->addHost($this->collection, $this->host); + } + + $this->parent->addCollection($this->collection); + } + + /** + * Creates a sub-collection. + */ + final public function collection(string $name = ''): self + { + return new self($this->collection, $this->name.$name, $this, $this->prefixes); + } + + /** + * Sets the prefix to add to the path of all child routes. + * + * @param string|array $prefix the prefix, or the localized prefixes + * + * @return $this + */ + final public function prefix($prefix): self + { + if (\is_array($prefix)) { + if (null === $this->parentPrefixes) { + // no-op + } elseif ($missing = array_diff_key($this->parentPrefixes, $prefix)) { + throw new \LogicException(sprintf('Collection "%s" is missing prefixes for locale(s) "%s".', $this->name, implode('", "', array_keys($missing)))); + } else { + foreach ($prefix as $locale => $localePrefix) { + if (!isset($this->parentPrefixes[$locale])) { + throw new \LogicException(sprintf('Collection "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $this->name, $locale)); + } + + $prefix[$locale] = $this->parentPrefixes[$locale].$localePrefix; + } + } + $this->prefixes = $prefix; + $this->route->setPath('/'); + } else { + $this->prefixes = null; + $this->route->setPath($prefix); + } + + return $this; + } + + /** + * Sets the host to use for all child routes. + * + * @param string|array $host the host, or the localized hosts + * + * @return $this + */ + final public function host($host): self + { + $this->host = $host; + + return $this; + } + + private function createRoute(string $path): Route + { + return (clone $this->route)->setPath($path); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/ImportConfigurator.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/ImportConfigurator.php new file mode 100644 index 0000000..32f3efe --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/ImportConfigurator.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\Routing\Loader\Configurator; + +use Symfony\Component\Routing\RouteCollection; + +/** + * @author Nicolas Grekas + */ +class ImportConfigurator +{ + use Traits\HostTrait; + use Traits\PrefixTrait; + use Traits\RouteTrait; + + private $parent; + + public function __construct(RouteCollection $parent, RouteCollection $route) + { + $this->parent = $parent; + $this->route = $route; + } + + /** + * @return array + */ + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + $this->parent->addCollection($this->route); + } + + /** + * Sets the prefix to add to the path of all child routes. + * + * @param string|array $prefix the prefix, or the localized prefixes + * + * @return $this + */ + final public function prefix($prefix, bool $trailingSlashOnRoot = true): self + { + $this->addPrefix($this->route, $prefix, $trailingSlashOnRoot); + + return $this; + } + + /** + * Sets the prefix to add to the name of all child routes. + * + * @return $this + */ + final public function namePrefix(string $namePrefix): self + { + $this->route->addNamePrefix($namePrefix); + + return $this; + } + + /** + * Sets the host to use for all child routes. + * + * @param string|array $host the host, or the localized hosts + * + * @return $this + */ + final public function host($host): self + { + $this->addHost($this->route, $host); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/RouteConfigurator.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/RouteConfigurator.php new file mode 100644 index 0000000..fcd1c21 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/RouteConfigurator.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\Routing\Loader\Configurator; + +use Symfony\Component\Routing\RouteCollection; + +/** + * @author Nicolas Grekas + */ +class RouteConfigurator +{ + use Traits\AddTrait; + use Traits\HostTrait; + use Traits\RouteTrait; + + protected $parentConfigurator; + + public function __construct(RouteCollection $collection, RouteCollection $route, string $name = '', ?CollectionConfigurator $parentConfigurator = null, ?array $prefixes = null) + { + $this->collection = $collection; + $this->route = $route; + $this->name = $name; + $this->parentConfigurator = $parentConfigurator; // for GC control + $this->prefixes = $prefixes; + } + + /** + * Sets the host to use for all child routes. + * + * @param string|array $host the host, or the localized hosts + * + * @return $this + */ + final public function host($host): self + { + $this->addHost($this->route, $host); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/RoutingConfigurator.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/RoutingConfigurator.php new file mode 100644 index 0000000..620b2d5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/RoutingConfigurator.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\Routing\Loader\Configurator; + +use Symfony\Component\Routing\Loader\PhpFileLoader; +use Symfony\Component\Routing\RouteCollection; + +/** + * @author Nicolas Grekas + */ +class RoutingConfigurator +{ + use Traits\AddTrait; + + private $loader; + private $path; + private $file; + private $env; + + public function __construct(RouteCollection $collection, PhpFileLoader $loader, string $path, string $file, ?string $env = null) + { + $this->collection = $collection; + $this->loader = $loader; + $this->path = $path; + $this->file = $file; + $this->env = $env; + } + + /** + * @param string|string[]|null $exclude Glob patterns to exclude from the import + */ + final public function import($resource, ?string $type = null, bool $ignoreErrors = false, $exclude = null): ImportConfigurator + { + $this->loader->setCurrentDir(\dirname($this->path)); + + $imported = $this->loader->import($resource, $type, $ignoreErrors, $this->file, $exclude) ?: []; + if (!\is_array($imported)) { + return new ImportConfigurator($this->collection, $imported); + } + + $mergedCollection = new RouteCollection(); + foreach ($imported as $subCollection) { + $mergedCollection->addCollection($subCollection); + } + + return new ImportConfigurator($this->collection, $mergedCollection); + } + + final public function collection(string $name = ''): CollectionConfigurator + { + return new CollectionConfigurator($this->collection, $name); + } + + /** + * Get the current environment to be able to write conditional configuration. + */ + final public function env(): ?string + { + return $this->env; + } + + /** + * @return static + */ + final public function withPath(string $path): self + { + $clone = clone $this; + $clone->path = $clone->file = $path; + + return $clone; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/AddTrait.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/AddTrait.php new file mode 100644 index 0000000..92b1bd0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/AddTrait.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\Routing\Loader\Configurator\Traits; + +use Symfony\Component\Routing\Loader\Configurator\AliasConfigurator; +use Symfony\Component\Routing\Loader\Configurator\CollectionConfigurator; +use Symfony\Component\Routing\Loader\Configurator\RouteConfigurator; +use Symfony\Component\Routing\RouteCollection; + +/** + * @author Nicolas Grekas + */ +trait AddTrait +{ + use LocalizedRouteTrait; + + /** + * @var RouteCollection + */ + protected $collection; + protected $name = ''; + protected $prefixes; + + /** + * Adds a route. + * + * @param string|array $path the path, or the localized paths of the route + */ + public function add(string $name, $path): RouteConfigurator + { + $parentConfigurator = $this instanceof CollectionConfigurator ? $this : ($this instanceof RouteConfigurator ? $this->parentConfigurator : null); + $route = $this->createLocalizedRoute($this->collection, $name, $path, $this->name, $this->prefixes); + + return new RouteConfigurator($this->collection, $route, $this->name, $parentConfigurator, $this->prefixes); + } + + public function alias(string $name, string $alias): AliasConfigurator + { + return new AliasConfigurator($this->collection->addAlias($name, $alias)); + } + + /** + * Adds a route. + * + * @param string|array $path the path, or the localized paths of the route + */ + public function __invoke(string $name, $path): RouteConfigurator + { + return $this->add($name, $path); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/HostTrait.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/HostTrait.php new file mode 100644 index 0000000..54ae656 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/HostTrait.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\Routing\Loader\Configurator\Traits; + +use Symfony\Component\Routing\RouteCollection; + +/** + * @internal + */ +trait HostTrait +{ + final protected function addHost(RouteCollection $routes, $hosts) + { + if (!$hosts || !\is_array($hosts)) { + $routes->setHost($hosts ?: ''); + + return; + } + + foreach ($routes->all() as $name => $route) { + if (null === $locale = $route->getDefault('_locale')) { + $routes->remove($name); + foreach ($hosts as $locale => $host) { + $localizedRoute = clone $route; + $localizedRoute->setDefault('_locale', $locale); + $localizedRoute->setRequirement('_locale', preg_quote($locale)); + $localizedRoute->setDefault('_canonical_route', $name); + $localizedRoute->setHost($host); + $routes->add($name.'.'.$locale, $localizedRoute); + } + } elseif (!isset($hosts[$locale])) { + throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding host in its parent collection.', $name, $locale)); + } else { + $route->setHost($hosts[$locale]); + $route->setRequirement('_locale', preg_quote($locale)); + $routes->add($name, $route); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/LocalizedRouteTrait.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/LocalizedRouteTrait.php new file mode 100644 index 0000000..44fb047 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/LocalizedRouteTrait.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader\Configurator\Traits; + +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * @internal + * + * @author Nicolas Grekas + * @author Jules Pietri + */ +trait LocalizedRouteTrait +{ + /** + * Creates one or many routes. + * + * @param string|array $path the path, or the localized paths of the route + */ + final protected function createLocalizedRoute(RouteCollection $collection, string $name, $path, string $namePrefix = '', ?array $prefixes = null): RouteCollection + { + $paths = []; + + $routes = new RouteCollection(); + + if (\is_array($path)) { + if (null === $prefixes) { + $paths = $path; + } elseif ($missing = array_diff_key($prefixes, $path)) { + throw new \LogicException(sprintf('Route "%s" is missing routes for locale(s) "%s".', $name, implode('", "', array_keys($missing)))); + } else { + foreach ($path as $locale => $localePath) { + if (!isset($prefixes[$locale])) { + throw new \LogicException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $name, $locale)); + } + + $paths[$locale] = $prefixes[$locale].$localePath; + } + } + } elseif (null !== $prefixes) { + foreach ($prefixes as $locale => $prefix) { + $paths[$locale] = $prefix.$path; + } + } else { + $routes->add($namePrefix.$name, $route = $this->createRoute($path)); + $collection->add($namePrefix.$name, $route); + + return $routes; + } + + foreach ($paths as $locale => $path) { + $routes->add($name.'.'.$locale, $route = $this->createRoute($path)); + $collection->add($namePrefix.$name.'.'.$locale, $route); + $route->setDefault('_locale', $locale); + $route->setRequirement('_locale', preg_quote($locale)); + $route->setDefault('_canonical_route', $namePrefix.$name); + } + + return $routes; + } + + private function createRoute(string $path): Route + { + return new Route($path); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/PrefixTrait.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/PrefixTrait.php new file mode 100644 index 0000000..0b19573 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/PrefixTrait.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader\Configurator\Traits; + +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * @internal + * + * @author Nicolas Grekas + */ +trait PrefixTrait +{ + final protected function addPrefix(RouteCollection $routes, $prefix, bool $trailingSlashOnRoot) + { + if (\is_array($prefix)) { + foreach ($prefix as $locale => $localePrefix) { + $prefix[$locale] = trim(trim($localePrefix), '/'); + } + foreach ($routes->all() as $name => $route) { + if (null === $locale = $route->getDefault('_locale')) { + $priority = $routes->getPriority($name) ?? 0; + $routes->remove($name); + foreach ($prefix as $locale => $localePrefix) { + $localizedRoute = clone $route; + $localizedRoute->setDefault('_locale', $locale); + $localizedRoute->setRequirement('_locale', preg_quote($locale)); + $localizedRoute->setDefault('_canonical_route', $name); + $localizedRoute->setPath($localePrefix.(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath())); + $routes->add($name.'.'.$locale, $localizedRoute, $priority); + } + } elseif (!isset($prefix[$locale])) { + throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $name, $locale)); + } else { + $route->setPath($prefix[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath())); + $routes->add($name, $route, $routes->getPriority($name) ?? 0); + } + } + + return; + } + + $routes->addPrefix($prefix); + if (!$trailingSlashOnRoot) { + $rootPath = (new Route(trim(trim($prefix), '/').'/'))->getPath(); + foreach ($routes->all() as $route) { + if ($route->getPath() === $rootPath) { + $route->setPath(rtrim($rootPath, '/')); + } + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/RouteTrait.php b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/RouteTrait.php new file mode 100644 index 0000000..ac05d10 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/Configurator/Traits/RouteTrait.php @@ -0,0 +1,175 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader\Configurator\Traits; + +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +trait RouteTrait +{ + /** + * @var RouteCollection|Route + */ + protected $route; + + /** + * Adds defaults. + * + * @return $this + */ + final public function defaults(array $defaults): self + { + $this->route->addDefaults($defaults); + + return $this; + } + + /** + * Adds requirements. + * + * @return $this + */ + final public function requirements(array $requirements): self + { + $this->route->addRequirements($requirements); + + return $this; + } + + /** + * Adds options. + * + * @return $this + */ + final public function options(array $options): self + { + $this->route->addOptions($options); + + return $this; + } + + /** + * Whether paths should accept utf8 encoding. + * + * @return $this + */ + final public function utf8(bool $utf8 = true): self + { + $this->route->addOptions(['utf8' => $utf8]); + + return $this; + } + + /** + * Sets the condition. + * + * @return $this + */ + final public function condition(string $condition): self + { + $this->route->setCondition($condition); + + return $this; + } + + /** + * Sets the pattern for the host. + * + * @return $this + */ + final public function host(string $pattern): self + { + $this->route->setHost($pattern); + + return $this; + } + + /** + * Sets the schemes (e.g. 'https') this route is restricted to. + * So an empty array means that any scheme is allowed. + * + * @param string[] $schemes + * + * @return $this + */ + final public function schemes(array $schemes): self + { + $this->route->setSchemes($schemes); + + return $this; + } + + /** + * Sets the HTTP methods (e.g. 'POST') this route is restricted to. + * So an empty array means that any method is allowed. + * + * @param string[] $methods + * + * @return $this + */ + final public function methods(array $methods): self + { + $this->route->setMethods($methods); + + return $this; + } + + /** + * Adds the "_controller" entry to defaults. + * + * @param callable|string|array $controller a callable or parseable pseudo-callable + * + * @return $this + */ + final public function controller($controller): self + { + $this->route->addDefaults(['_controller' => $controller]); + + return $this; + } + + /** + * Adds the "_locale" entry to defaults. + * + * @return $this + */ + final public function locale(string $locale): self + { + $this->route->addDefaults(['_locale' => $locale]); + + return $this; + } + + /** + * Adds the "_format" entry to defaults. + * + * @return $this + */ + final public function format(string $format): self + { + $this->route->addDefaults(['_format' => $format]); + + return $this; + } + + /** + * Adds the "_stateless" entry to defaults. + * + * @return $this + */ + final public function stateless(bool $stateless = true): self + { + $this->route->addDefaults(['_stateless' => $stateless]); + + return $this; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/ContainerLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/ContainerLoader.php new file mode 100644 index 0000000..a03d465 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/ContainerLoader.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 Symfony\Component\Routing\Loader; + +use Psr\Container\ContainerInterface; + +/** + * A route loader that executes a service from a PSR-11 container to load the routes. + * + * @author Ryan Weaver + */ +class ContainerLoader extends ObjectLoader +{ + private $container; + + public function __construct(ContainerInterface $container, ?string $env = null) + { + $this->container = $container; + parent::__construct($env); + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return 'service' === $type && \is_string($resource); + } + + /** + * {@inheritdoc} + */ + protected function getObject(string $id) + { + return $this->container->get($id); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/DirectoryLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/DirectoryLoader.php new file mode 100644 index 0000000..24cf185 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/DirectoryLoader.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\FileLoader; +use Symfony\Component\Config\Resource\DirectoryResource; +use Symfony\Component\Routing\RouteCollection; + +class DirectoryLoader extends FileLoader +{ + /** + * {@inheritdoc} + */ + public function load($file, ?string $type = null) + { + $path = $this->locator->locate($file); + + $collection = new RouteCollection(); + $collection->addResource(new DirectoryResource($path)); + + foreach (scandir($path) as $dir) { + if ('.' !== $dir[0]) { + $this->setCurrentDir($path); + $subPath = $path.'/'.$dir; + $subType = null; + + if (is_dir($subPath)) { + $subPath .= '/'; + $subType = 'directory'; + } + + $subCollection = $this->import($subPath, $subType, false, $path); + $collection->addCollection($subCollection); + } + } + + return $collection; + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + // only when type is forced to directory, not to conflict with AnnotationLoader + + return 'directory' === $type; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/GlobFileLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/GlobFileLoader.php new file mode 100644 index 0000000..9c2f4ed --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/GlobFileLoader.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\FileLoader; +use Symfony\Component\Routing\RouteCollection; + +/** + * GlobFileLoader loads files from a glob pattern. + * + * @author Nicolas Grekas + */ +class GlobFileLoader extends FileLoader +{ + /** + * {@inheritdoc} + */ + public function load($resource, ?string $type = null) + { + $collection = new RouteCollection(); + + foreach ($this->glob($resource, false, $globResource) as $path => $info) { + $collection->addCollection($this->import($path)); + } + + $collection->addResource($globResource); + + return $collection; + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return 'glob' === $type; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/ObjectLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/ObjectLoader.php new file mode 100644 index 0000000..d212f8e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/ObjectLoader.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\Loader; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\RouteCollection; + +/** + * A route loader that calls a method on an object to load the routes. + * + * @author Ryan Weaver + */ +abstract class ObjectLoader extends Loader +{ + /** + * Returns the object that the method will be called on to load routes. + * + * For example, if your application uses a service container, + * the $id may be a service id. + * + * @return object + */ + abstract protected function getObject(string $id); + + /** + * Calls the object method that will load the routes. + * + * @param string $resource object_id::method + * @param string|null $type The resource type + * + * @return RouteCollection + */ + public function load($resource, ?string $type = null) + { + if (!preg_match('/^[^\:]+(?:::(?:[^\:]+))?$/', $resource)) { + throw new \InvalidArgumentException(sprintf('Invalid resource "%s" passed to the %s route loader: use the format "object_id::method" or "object_id" if your object class has an "__invoke" method.', $resource, \is_string($type) ? '"'.$type.'"' : 'object')); + } + + $parts = explode('::', $resource); + $method = $parts[1] ?? '__invoke'; + + $loaderObject = $this->getObject($parts[0]); + + if (!\is_object($loaderObject)) { + throw new \TypeError(sprintf('"%s:getObject()" must return an object: "%s" returned.', static::class, get_debug_type($loaderObject))); + } + + if (!\is_callable([$loaderObject, $method])) { + throw new \BadMethodCallException(sprintf('Method "%s" not found on "%s" when importing routing resource "%s".', $method, get_debug_type($loaderObject), $resource)); + } + + $routeCollection = $loaderObject->$method($this, $this->env); + + if (!$routeCollection instanceof RouteCollection) { + $type = get_debug_type($routeCollection); + + throw new \LogicException(sprintf('The "%s::%s()" method must return a RouteCollection: "%s" returned.', get_debug_type($loaderObject), $method, $type)); + } + + // make the object file tracked so that if it changes, the cache rebuilds + $this->addClassResource(new \ReflectionClass($loaderObject), $routeCollection); + + return $routeCollection; + } + + private function addClassResource(\ReflectionClass $class, RouteCollection $collection) + { + do { + if (is_file($class->getFileName())) { + $collection->addResource(new FileResource($class->getFileName())); + } + } while ($class = $class->getParentClass()); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/PhpFileLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/PhpFileLoader.php new file mode 100644 index 0000000..3f1cf9c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/PhpFileLoader.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\FileLoader; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; +use Symfony\Component\Routing\RouteCollection; + +/** + * PhpFileLoader loads routes from a PHP file. + * + * The file must return a RouteCollection instance. + * + * @author Fabien Potencier + * @author Nicolas grekas + * @author Jules Pietri + */ +class PhpFileLoader extends FileLoader +{ + /** + * Loads a PHP file. + * + * @param string $file A PHP file path + * @param string|null $type The resource type + * + * @return RouteCollection + */ + public function load($file, ?string $type = null) + { + $path = $this->locator->locate($file); + $this->setCurrentDir(\dirname($path)); + + // the closure forbids access to the private scope in the included file + $loader = $this; + $load = \Closure::bind(static function ($file) use ($loader) { + return include $file; + }, null, ProtectedPhpFileLoader::class); + + $result = $load($path); + + if (\is_object($result) && \is_callable($result)) { + $collection = $this->callConfigurator($result, $path, $file); + } else { + $collection = $result; + } + + $collection->addResource(new FileResource($path)); + + return $collection; + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'php' === $type); + } + + protected function callConfigurator(callable $result, string $path, string $file): RouteCollection + { + $collection = new RouteCollection(); + + $result(new RoutingConfigurator($collection, $this, $path, $file, $this->env)); + + return $collection; + } +} + +/** + * @internal + */ +final class ProtectedPhpFileLoader extends PhpFileLoader +{ +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/XmlFileLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/XmlFileLoader.php new file mode 100644 index 0000000..85bb0ee --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/XmlFileLoader.php @@ -0,0 +1,469 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\FileLoader; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Util\XmlUtils; +use Symfony\Component\Routing\Loader\Configurator\Traits\HostTrait; +use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait; +use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait; +use Symfony\Component\Routing\RouteCollection; + +/** + * XmlFileLoader loads XML routing files. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class XmlFileLoader extends FileLoader +{ + use HostTrait; + use LocalizedRouteTrait; + use PrefixTrait; + + public const NAMESPACE_URI = 'http://symfony.com/schema/routing'; + public const SCHEME_PATH = '/schema/routing/routing-1.0.xsd'; + + /** + * Loads an XML file. + * + * @param string $file An XML file path + * @param string|null $type The resource type + * + * @return RouteCollection + * + * @throws \InvalidArgumentException when the file cannot be loaded or when the XML cannot be + * parsed because it does not validate against the scheme + */ + public function load($file, ?string $type = null) + { + $path = $this->locator->locate($file); + + $xml = $this->loadFile($path); + + $collection = new RouteCollection(); + $collection->addResource(new FileResource($path)); + + // process routes and imports + foreach ($xml->documentElement->childNodes as $node) { + if (!$node instanceof \DOMElement) { + continue; + } + + $this->parseNode($collection, $node, $path, $file); + } + + return $collection; + } + + /** + * Parses a node from a loaded XML file. + * + * @throws \InvalidArgumentException When the XML is invalid + */ + protected function parseNode(RouteCollection $collection, \DOMElement $node, string $path, string $file) + { + if (self::NAMESPACE_URI !== $node->namespaceURI) { + return; + } + + switch ($node->localName) { + case 'route': + $this->parseRoute($collection, $node, $path); + break; + case 'import': + $this->parseImport($collection, $node, $path, $file); + break; + case 'when': + if (!$this->env || $node->getAttribute('env') !== $this->env) { + break; + } + foreach ($node->childNodes as $node) { + if ($node instanceof \DOMElement) { + $this->parseNode($collection, $node, $path, $file); + } + } + break; + default: + throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "route" or "import".', $node->localName, $path)); + } + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return \is_string($resource) && 'xml' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'xml' === $type); + } + + /** + * Parses a route and adds it to the RouteCollection. + * + * @throws \InvalidArgumentException When the XML is invalid + */ + protected function parseRoute(RouteCollection $collection, \DOMElement $node, string $path) + { + if ('' === $id = $node->getAttribute('id')) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must have an "id" attribute.', $path)); + } + + if ('' !== $alias = $node->getAttribute('alias')) { + $alias = $collection->addAlias($id, $alias); + + if ($deprecationInfo = $this->parseDeprecation($node, $path)) { + $alias->setDeprecated($deprecationInfo['package'], $deprecationInfo['version'], $deprecationInfo['message']); + } + + return; + } + + $schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY); + $methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY); + + [$defaults, $requirements, $options, $condition, $paths, /* $prefixes */, $hosts] = $this->parseConfigs($node, $path); + + if (!$paths && '' === $node->getAttribute('path')) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must have a "path" attribute or child nodes.', $path)); + } + + if ($paths && '' !== $node->getAttribute('path')) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must not have both a "path" attribute and child nodes.', $path)); + } + + $routes = $this->createLocalizedRoute($collection, $id, $paths ?: $node->getAttribute('path')); + $routes->addDefaults($defaults); + $routes->addRequirements($requirements); + $routes->addOptions($options); + $routes->setSchemes($schemes); + $routes->setMethods($methods); + $routes->setCondition($condition); + + if (null !== $hosts) { + $this->addHost($routes, $hosts); + } + } + + /** + * Parses an import and adds the routes in the resource to the RouteCollection. + * + * @throws \InvalidArgumentException When the XML is invalid + */ + protected function parseImport(RouteCollection $collection, \DOMElement $node, string $path, string $file) + { + if ('' === $resource = $node->getAttribute('resource')) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must have a "resource" attribute.', $path)); + } + + $type = $node->getAttribute('type'); + $prefix = $node->getAttribute('prefix'); + $schemes = $node->hasAttribute('schemes') ? preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY) : null; + $methods = $node->hasAttribute('methods') ? preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY) : null; + $trailingSlashOnRoot = $node->hasAttribute('trailing-slash-on-root') ? XmlUtils::phpize($node->getAttribute('trailing-slash-on-root')) : true; + $namePrefix = $node->getAttribute('name-prefix') ?: null; + + [$defaults, $requirements, $options, $condition, /* $paths */, $prefixes, $hosts] = $this->parseConfigs($node, $path); + + if ('' !== $prefix && $prefixes) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must not have both a "prefix" attribute and child nodes.', $path)); + } + + $exclude = []; + foreach ($node->childNodes as $child) { + if ($child instanceof \DOMElement && $child->localName === $exclude && self::NAMESPACE_URI === $child->namespaceURI) { + $exclude[] = $child->nodeValue; + } + } + + if ($node->hasAttribute('exclude')) { + if ($exclude) { + throw new \InvalidArgumentException('You cannot use both the attribute "exclude" and tags at the same time.'); + } + $exclude = [$node->getAttribute('exclude')]; + } + + $this->setCurrentDir(\dirname($path)); + + /** @var RouteCollection[] $imported */ + $imported = $this->import($resource, '' !== $type ? $type : null, false, $file, $exclude) ?: []; + + if (!\is_array($imported)) { + $imported = [$imported]; + } + + foreach ($imported as $subCollection) { + $this->addPrefix($subCollection, $prefixes ?: $prefix, $trailingSlashOnRoot); + + if (null !== $hosts) { + $this->addHost($subCollection, $hosts); + } + + if (null !== $condition) { + $subCollection->setCondition($condition); + } + if (null !== $schemes) { + $subCollection->setSchemes($schemes); + } + if (null !== $methods) { + $subCollection->setMethods($methods); + } + if (null !== $namePrefix) { + $subCollection->addNamePrefix($namePrefix); + } + $subCollection->addDefaults($defaults); + $subCollection->addRequirements($requirements); + $subCollection->addOptions($options); + + $collection->addCollection($subCollection); + } + } + + /** + * @return \DOMDocument + * + * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors + * or when the XML structure is not as expected by the scheme - + * see validate() + */ + protected function loadFile(string $file) + { + return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH); + } + + /** + * Parses the config elements (default, requirement, option). + * + * @throws \InvalidArgumentException When the XML is invalid + */ + private function parseConfigs(\DOMElement $node, string $path): array + { + $defaults = []; + $requirements = []; + $options = []; + $condition = null; + $prefixes = []; + $paths = []; + $hosts = []; + + /** @var \DOMElement $n */ + foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) { + if ($node !== $n->parentNode) { + continue; + } + + switch ($n->localName) { + case 'path': + $paths[$n->getAttribute('locale')] = trim($n->textContent); + break; + case 'host': + $hosts[$n->getAttribute('locale')] = trim($n->textContent); + break; + case 'prefix': + $prefixes[$n->getAttribute('locale')] = trim($n->textContent); + break; + case 'default': + if ($this->isElementValueNull($n)) { + $defaults[$n->getAttribute('key')] = null; + } else { + $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path); + } + + break; + case 'requirement': + $requirements[$n->getAttribute('key')] = trim($n->textContent); + break; + case 'option': + $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent)); + break; + case 'condition': + $condition = trim($n->textContent); + break; + default: + throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path)); + } + } + + if ($controller = $node->getAttribute('controller')) { + if (isset($defaults['_controller'])) { + $name = $node->hasAttribute('id') ? sprintf('"%s".', $node->getAttribute('id')) : sprintf('the "%s" tag.', $node->tagName); + + throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for ', $path).$name); + } + + $defaults['_controller'] = $controller; + } + if ($node->hasAttribute('locale')) { + $defaults['_locale'] = $node->getAttribute('locale'); + } + if ($node->hasAttribute('format')) { + $defaults['_format'] = $node->getAttribute('format'); + } + if ($node->hasAttribute('utf8')) { + $options['utf8'] = XmlUtils::phpize($node->getAttribute('utf8')); + } + if ($stateless = $node->getAttribute('stateless')) { + if (isset($defaults['_stateless'])) { + $name = $node->hasAttribute('id') ? sprintf('"%s".', $node->getAttribute('id')) : sprintf('the "%s" tag.', $node->tagName); + + throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "stateless" attribute and the defaults key "_stateless" for ', $path).$name); + } + + $defaults['_stateless'] = XmlUtils::phpize($stateless); + } + + if (!$hosts) { + $hosts = $node->hasAttribute('host') ? $node->getAttribute('host') : null; + } + + return [$defaults, $requirements, $options, $condition, $paths, $prefixes, $hosts]; + } + + /** + * Parses the "default" elements. + * + * @return array|bool|float|int|string|null + */ + private function parseDefaultsConfig(\DOMElement $element, string $path) + { + if ($this->isElementValueNull($element)) { + return null; + } + + // Check for existing element nodes in the default element. There can + // only be a single element inside a default element. So this element + // (if one was found) can safely be returned. + foreach ($element->childNodes as $child) { + if (!$child instanceof \DOMElement) { + continue; + } + + if (self::NAMESPACE_URI !== $child->namespaceURI) { + continue; + } + + return $this->parseDefaultNode($child, $path); + } + + // If the default element doesn't contain a nested "bool", "int", "float", + // "string", "list", or "map" element, the element contents will be treated + // as the string value of the associated default option. + return trim($element->textContent); + } + + /** + * Recursively parses the value of a "default" element. + * + * @return array|bool|float|int|string|null + * + * @throws \InvalidArgumentException when the XML is invalid + */ + private function parseDefaultNode(\DOMElement $node, string $path) + { + if ($this->isElementValueNull($node)) { + return null; + } + + switch ($node->localName) { + case 'bool': + return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue); + case 'int': + return (int) trim($node->nodeValue); + case 'float': + return (float) trim($node->nodeValue); + case 'string': + return trim($node->nodeValue); + case 'list': + $list = []; + + foreach ($node->childNodes as $element) { + if (!$element instanceof \DOMElement) { + continue; + } + + if (self::NAMESPACE_URI !== $element->namespaceURI) { + continue; + } + + $list[] = $this->parseDefaultNode($element, $path); + } + + return $list; + case 'map': + $map = []; + + foreach ($node->childNodes as $element) { + if (!$element instanceof \DOMElement) { + continue; + } + + if (self::NAMESPACE_URI !== $element->namespaceURI) { + continue; + } + + $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path); + } + + return $map; + default: + throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path)); + } + } + + private function isElementValueNull(\DOMElement $element): bool + { + $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance'; + + if (!$element->hasAttributeNS($namespaceUri, 'nil')) { + return false; + } + + return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil'); + } + + /** + * Parses the deprecation elements. + * + * @throws \InvalidArgumentException When the XML is invalid + */ + private function parseDeprecation(\DOMElement $node, string $path): array + { + $deprecatedNode = null; + foreach ($node->childNodes as $child) { + if (!$child instanceof \DOMElement || self::NAMESPACE_URI !== $child->namespaceURI) { + continue; + } + if ('deprecated' !== $child->localName) { + throw new \InvalidArgumentException(sprintf('Invalid child element "%s" defined for alias "%s" in "%s".', $child->localName, $node->getAttribute('id'), $path)); + } + + $deprecatedNode = $child; + } + + if (null === $deprecatedNode) { + return []; + } + + if (!$deprecatedNode->hasAttribute('package')) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must have a "package" attribute.', $path)); + } + if (!$deprecatedNode->hasAttribute('version')) { + throw new \InvalidArgumentException(sprintf('The element in file "%s" must have a "version" attribute.', $path)); + } + + return [ + 'package' => $deprecatedNode->getAttribute('package'), + 'version' => $deprecatedNode->getAttribute('version'), + 'message' => trim($deprecatedNode->nodeValue), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/YamlFileLoader.php b/php/libraries/composer/vendor/symfony/routing/Loader/YamlFileLoader.php new file mode 100644 index 0000000..1087817 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/YamlFileLoader.php @@ -0,0 +1,314 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader; + +use Symfony\Component\Config\Loader\FileLoader; +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\Loader\Configurator\Traits\HostTrait; +use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait; +use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait; +use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Parser as YamlParser; +use Symfony\Component\Yaml\Yaml; + +/** + * YamlFileLoader loads Yaml routing files. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class YamlFileLoader extends FileLoader +{ + use HostTrait; + use LocalizedRouteTrait; + use PrefixTrait; + + private const AVAILABLE_KEYS = [ + 'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude', 'stateless', + ]; + private $yamlParser; + + /** + * Loads a Yaml file. + * + * @param string $file A Yaml file path + * @param string|null $type The resource type + * + * @return RouteCollection + * + * @throws \InvalidArgumentException When a route can't be parsed because YAML is invalid + */ + public function load($file, ?string $type = null) + { + $path = $this->locator->locate($file); + + if (!stream_is_local($path)) { + throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path)); + } + + if (!file_exists($path)) { + throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path)); + } + + if (null === $this->yamlParser) { + $this->yamlParser = new YamlParser(); + } + + try { + $parsedConfig = $this->yamlParser->parseFile($path, Yaml::PARSE_CONSTANT); + } catch (ParseException $e) { + throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: ', $path).$e->getMessage(), 0, $e); + } + + $collection = new RouteCollection(); + $collection->addResource(new FileResource($path)); + + // empty file + if (null === $parsedConfig) { + return $collection; + } + + // not an array + if (!\is_array($parsedConfig)) { + throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path)); + } + + foreach ($parsedConfig as $name => $config) { + if (0 === strpos($name, 'when@')) { + if (!$this->env || 'when@'.$this->env !== $name) { + continue; + } + + foreach ($config as $name => $config) { + $this->validate($config, $name.'" when "@'.$this->env, $path); + + if (isset($config['resource'])) { + $this->parseImport($collection, $config, $path, $file); + } else { + $this->parseRoute($collection, $name, $config, $path); + } + } + + continue; + } + + $this->validate($config, $name, $path); + + if (isset($config['resource'])) { + $this->parseImport($collection, $config, $path, $file); + } else { + $this->parseRoute($collection, $name, $config, $path); + } + } + + return $collection; + } + + /** + * {@inheritdoc} + */ + public function supports($resource, ?string $type = null) + { + return \is_string($resource) && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yml', 'yaml'], true) && (!$type || 'yaml' === $type); + } + + /** + * Parses a route and adds it to the RouteCollection. + */ + protected function parseRoute(RouteCollection $collection, string $name, array $config, string $path) + { + if (isset($config['alias'])) { + $alias = $collection->addAlias($name, $config['alias']); + $deprecation = $config['deprecated'] ?? null; + if (null !== $deprecation) { + $alias->setDeprecated( + $deprecation['package'], + $deprecation['version'], + $deprecation['message'] ?? '' + ); + } + + return; + } + + $defaults = $config['defaults'] ?? []; + $requirements = $config['requirements'] ?? []; + $options = $config['options'] ?? []; + + foreach ($requirements as $placeholder => $requirement) { + if (\is_int($placeholder)) { + throw new \InvalidArgumentException(sprintf('A placeholder name must be a string (%d given). Did you forget to specify the placeholder key for the requirement "%s" of route "%s" in "%s"?', $placeholder, $requirement, $name, $path)); + } + } + + if (isset($config['controller'])) { + $defaults['_controller'] = $config['controller']; + } + if (isset($config['locale'])) { + $defaults['_locale'] = $config['locale']; + } + if (isset($config['format'])) { + $defaults['_format'] = $config['format']; + } + if (isset($config['utf8'])) { + $options['utf8'] = $config['utf8']; + } + if (isset($config['stateless'])) { + $defaults['_stateless'] = $config['stateless']; + } + + $routes = $this->createLocalizedRoute($collection, $name, $config['path']); + $routes->addDefaults($defaults); + $routes->addRequirements($requirements); + $routes->addOptions($options); + $routes->setSchemes($config['schemes'] ?? []); + $routes->setMethods($config['methods'] ?? []); + $routes->setCondition($config['condition'] ?? null); + + if (isset($config['host'])) { + $this->addHost($routes, $config['host']); + } + } + + /** + * Parses an import and adds the routes in the resource to the RouteCollection. + */ + protected function parseImport(RouteCollection $collection, array $config, string $path, string $file) + { + $type = $config['type'] ?? null; + $prefix = $config['prefix'] ?? ''; + $defaults = $config['defaults'] ?? []; + $requirements = $config['requirements'] ?? []; + $options = $config['options'] ?? []; + $host = $config['host'] ?? null; + $condition = $config['condition'] ?? null; + $schemes = $config['schemes'] ?? null; + $methods = $config['methods'] ?? null; + $trailingSlashOnRoot = $config['trailing_slash_on_root'] ?? true; + $namePrefix = $config['name_prefix'] ?? null; + $exclude = $config['exclude'] ?? null; + + if (isset($config['controller'])) { + $defaults['_controller'] = $config['controller']; + } + if (isset($config['locale'])) { + $defaults['_locale'] = $config['locale']; + } + if (isset($config['format'])) { + $defaults['_format'] = $config['format']; + } + if (isset($config['utf8'])) { + $options['utf8'] = $config['utf8']; + } + if (isset($config['stateless'])) { + $defaults['_stateless'] = $config['stateless']; + } + + $this->setCurrentDir(\dirname($path)); + + /** @var RouteCollection[] $imported */ + $imported = $this->import($config['resource'], $type, false, $file, $exclude) ?: []; + + if (!\is_array($imported)) { + $imported = [$imported]; + } + + foreach ($imported as $subCollection) { + $this->addPrefix($subCollection, $prefix, $trailingSlashOnRoot); + + if (null !== $host) { + $this->addHost($subCollection, $host); + } + if (null !== $condition) { + $subCollection->setCondition($condition); + } + if (null !== $schemes) { + $subCollection->setSchemes($schemes); + } + if (null !== $methods) { + $subCollection->setMethods($methods); + } + if (null !== $namePrefix) { + $subCollection->addNamePrefix($namePrefix); + } + $subCollection->addDefaults($defaults); + $subCollection->addRequirements($requirements); + $subCollection->addOptions($options); + + $collection->addCollection($subCollection); + } + } + + /** + * Validates the route configuration. + * + * @param array $config A resource config + * @param string $name The config key + * @param string $path The loaded file path + * + * @throws \InvalidArgumentException If one of the provided config keys is not supported, + * something is missing or the combination is nonsense + */ + protected function validate($config, string $name, string $path) + { + if (!\is_array($config)) { + throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path)); + } + if (isset($config['alias'])) { + $this->validateAlias($config, $name, $path); + + return; + } + if ($extraKeys = array_diff(array_keys($config), self::AVAILABLE_KEYS)) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".', $path, $name, implode('", "', $extraKeys), implode('", "', self::AVAILABLE_KEYS))); + } + if (isset($config['resource']) && isset($config['path'])) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.', $path, $name)); + } + if (!isset($config['resource']) && isset($config['type'])) { + throw new \InvalidArgumentException(sprintf('The "type" key for the route definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.', $name, $path)); + } + if (!isset($config['resource']) && !isset($config['path'])) { + throw new \InvalidArgumentException(sprintf('You must define a "path" for the route "%s" in file "%s".', $name, $path)); + } + if (isset($config['controller']) && isset($config['defaults']['_controller'])) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" key and the defaults key "_controller" for "%s".', $path, $name)); + } + if (isset($config['stateless']) && isset($config['defaults']['_stateless'])) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "stateless" key and the defaults key "_stateless" for "%s".', $path, $name)); + } + } + + /** + * @throws \InvalidArgumentException If one of the provided config keys is not supported, + * something is missing or the combination is nonsense + */ + private function validateAlias(array $config, string $name, string $path): void + { + foreach ($config as $key => $value) { + if (!\in_array($key, ['alias', 'deprecated'], true)) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify other keys than "alias" and "deprecated" for "%s".', $path, $name)); + } + + if ('deprecated' === $key) { + if (!isset($value['package'])) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" must specify the attribute "package" of the "deprecated" option for "%s".', $path, $name)); + } + + if (!isset($value['version'])) { + throw new \InvalidArgumentException(sprintf('The routing file "%s" must specify the attribute "version" of the "deprecated" option for "%s".', $path, $name)); + } + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Loader/schema/routing/routing-1.0.xsd b/php/libraries/composer/vendor/symfony/routing/Loader/schema/routing/routing-1.0.xsd new file mode 100644 index 0000000..66c40a0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Loader/schema/routing/routing-1.0.xsd @@ -0,0 +1,194 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/CompiledUrlMatcher.php b/php/libraries/composer/vendor/symfony/routing/Matcher/CompiledUrlMatcher.php new file mode 100644 index 0000000..ae13fd7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/CompiledUrlMatcher.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherTrait; +use Symfony\Component\Routing\RequestContext; + +/** + * Matches URLs based on rules dumped by CompiledUrlMatcherDumper. + * + * @author Nicolas Grekas + */ +class CompiledUrlMatcher extends UrlMatcher +{ + use CompiledUrlMatcherTrait; + + public function __construct(array $compiledRoutes, RequestContext $context) + { + $this->context = $context; + [$this->matchHost, $this->staticRoutes, $this->regexpList, $this->dynamicRoutes, $this->checkCondition] = $compiledRoutes; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php new file mode 100644 index 0000000..ddf231f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php @@ -0,0 +1,501 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher\Dumper; + +use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; +use Symfony\Component\ExpressionLanguage\ExpressionLanguage; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * CompiledUrlMatcherDumper creates PHP arrays to be used with CompiledUrlMatcher. + * + * @author Fabien Potencier + * @author Tobias Schultze + * @author Arnaud Le Blanc + * @author Nicolas Grekas + */ +class CompiledUrlMatcherDumper extends MatcherDumper +{ + private $expressionLanguage; + private $signalingException; + + /** + * @var ExpressionFunctionProviderInterface[] + */ + private $expressionLanguageProviders = []; + + /** + * {@inheritdoc} + */ + public function dump(array $options = []) + { + return <<generateCompiledRoutes()}]; + +EOF; + } + + public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) + { + $this->expressionLanguageProviders[] = $provider; + } + + /** + * Generates the arrays for CompiledUrlMatcher's constructor. + */ + public function getCompiledRoutes(bool $forDump = false): array + { + // Group hosts by same-suffix, re-order when possible + $matchHost = false; + $routes = new StaticPrefixCollection(); + foreach ($this->getRoutes()->all() as $name => $route) { + if ($host = $route->getHost()) { + $matchHost = true; + $host = '/'.strtr(strrev($host), '}.{', '(/)'); + } + + $routes->addRoute($host ?: '/(.*)', [$name, $route]); + } + + if ($matchHost) { + $compiledRoutes = [true]; + $routes = $routes->populateCollection(new RouteCollection()); + } else { + $compiledRoutes = [false]; + $routes = $this->getRoutes(); + } + + [$staticRoutes, $dynamicRoutes] = $this->groupStaticRoutes($routes); + + $conditions = [null]; + $compiledRoutes[] = $this->compileStaticRoutes($staticRoutes, $conditions); + $chunkLimit = \count($dynamicRoutes); + + while (true) { + try { + $this->signalingException = new \RuntimeException('Compilation failed: regular expression is too large'); + $compiledRoutes = array_merge($compiledRoutes, $this->compileDynamicRoutes($dynamicRoutes, $matchHost, $chunkLimit, $conditions)); + + break; + } catch (\Exception $e) { + if (1 < $chunkLimit && $this->signalingException === $e) { + $chunkLimit = 1 + ($chunkLimit >> 1); + continue; + } + throw $e; + } + } + + if ($forDump) { + $compiledRoutes[2] = $compiledRoutes[4]; + } + unset($conditions[0]); + + if ($conditions) { + foreach ($conditions as $expression => $condition) { + $conditions[$expression] = "case {$condition}: return {$expression};"; + } + + $checkConditionCode = <<indent(implode("\n", $conditions), 3)} + } + } +EOF; + $compiledRoutes[4] = $forDump ? $checkConditionCode.",\n" : eval('return '.$checkConditionCode.';'); + } else { + $compiledRoutes[4] = $forDump ? " null, // \$checkCondition\n" : null; + } + + return $compiledRoutes; + } + + private function generateCompiledRoutes(): string + { + [$matchHost, $staticRoutes, $regexpCode, $dynamicRoutes, $checkConditionCode] = $this->getCompiledRoutes(true); + + $code = self::export($matchHost).', // $matchHost'."\n"; + + $code .= '[ // $staticRoutes'."\n"; + foreach ($staticRoutes as $path => $routes) { + $code .= sprintf(" %s => [\n", self::export($path)); + foreach ($routes as $route) { + $code .= vsprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", array_map([__CLASS__, 'export'], $route)); + } + $code .= " ],\n"; + } + $code .= "],\n"; + + $code .= sprintf("[ // \$regexpList%s\n],\n", $regexpCode); + + $code .= '[ // $dynamicRoutes'."\n"; + foreach ($dynamicRoutes as $path => $routes) { + $code .= sprintf(" %s => [\n", self::export($path)); + foreach ($routes as $route) { + $code .= vsprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", array_map([__CLASS__, 'export'], $route)); + } + $code .= " ],\n"; + } + $code .= "],\n"; + $code = preg_replace('/ => \[\n (\[.+?),\n \],/', ' => [$1],', $code); + + return $this->indent($code, 1).$checkConditionCode; + } + + /** + * Splits static routes from dynamic routes, so that they can be matched first, using a simple switch. + */ + private function groupStaticRoutes(RouteCollection $collection): array + { + $staticRoutes = $dynamicRegex = []; + $dynamicRoutes = new RouteCollection(); + + foreach ($collection->all() as $name => $route) { + $compiledRoute = $route->compile(); + $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/'); + $hostRegex = $compiledRoute->getHostRegex(); + $regex = $compiledRoute->getRegex(); + if ($hasTrailingSlash = '/' !== $route->getPath()) { + $pos = strrpos($regex, '$'); + $hasTrailingSlash = '/' === $regex[$pos - 1]; + $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash); + } + + if (!$compiledRoute->getPathVariables()) { + $host = !$compiledRoute->getHostVariables() ? $route->getHost() : ''; + $url = $route->getPath(); + if ($hasTrailingSlash) { + $url = substr($url, 0, -1); + } + foreach ($dynamicRegex as [$hostRx, $rx, $prefix]) { + if (('' === $prefix || str_starts_with($url, $prefix)) && (preg_match($rx, $url) || preg_match($rx, $url.'/')) && (!$host || !$hostRx || preg_match($hostRx, $host))) { + $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix]; + $dynamicRoutes->add($name, $route); + continue 2; + } + } + + $staticRoutes[$url][$name] = [$route, $hasTrailingSlash]; + } else { + $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix]; + $dynamicRoutes->add($name, $route); + } + } + + return [$staticRoutes, $dynamicRoutes]; + } + + /** + * Compiles static routes in a switch statement. + * + * Condition-less paths are put in a static array in the switch's default, with generic matching logic. + * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases. + * + * @throws \LogicException + */ + private function compileStaticRoutes(array $staticRoutes, array &$conditions): array + { + if (!$staticRoutes) { + return []; + } + $compiledRoutes = []; + + foreach ($staticRoutes as $url => $routes) { + $compiledRoutes[$url] = []; + foreach ($routes as $name => [$route, $hasTrailingSlash]) { + $compiledRoutes[$url][] = $this->compileRoute($route, $name, (!$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex()) ?: null, $hasTrailingSlash, false, $conditions); + } + } + + return $compiledRoutes; + } + + /** + * Compiles a regular expression followed by a switch statement to match dynamic routes. + * + * The regular expression matches both the host and the pathinfo at the same time. For stellar performance, + * it is built as a tree of patterns, with re-ordering logic to group same-prefix routes together when possible. + * + * Patterns are named so that we know which one matched (https://pcre.org/current/doc/html/pcre2syntax.html#SEC23). + * This name is used to "switch" to the additional logic required to match the final route. + * + * Condition-less paths are put in a static array in the switch's default, with generic matching logic. + * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases. + * + * Last but not least: + * - Because it is not possible to mix unicode/non-unicode patterns in a single regexp, several of them can be generated. + * - The same regexp can be used several times when the logic in the switch rejects the match. When this happens, the + * matching-but-failing subpattern is excluded by replacing its name by "(*F)", which forces a failure-to-match. + * To ease this backlisting operation, the name of subpatterns is also the string offset where the replacement should occur. + */ + private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): array + { + if (!$collection->all()) { + return [[], [], '']; + } + $regexpList = []; + $code = ''; + $state = (object) [ + 'regexMark' => 0, + 'regex' => [], + 'routes' => [], + 'mark' => 0, + 'markTail' => 0, + 'hostVars' => [], + 'vars' => [], + ]; + $state->getVars = static function ($m) use ($state) { + if ('_route' === $m[1]) { + return '?:'; + } + + $state->vars[] = $m[1]; + + return ''; + }; + + $chunkSize = 0; + $prev = null; + $perModifiers = []; + foreach ($collection->all() as $name => $route) { + preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx); + if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) { + $chunkSize = 1; + $routes = new RouteCollection(); + $perModifiers[] = [$rx[0], $routes]; + $prev = $rx[0]; + } + $routes->add($name, $route); + } + + foreach ($perModifiers as [$modifiers, $routes]) { + $prev = false; + $perHost = []; + foreach ($routes->all() as $name => $route) { + $regex = $route->compile()->getHostRegex(); + if ($prev !== $regex) { + $routes = new RouteCollection(); + $perHost[] = [$regex, $routes]; + $prev = $regex; + } + $routes->add($name, $route); + } + $prev = false; + $rx = '{^(?'; + $code .= "\n {$state->mark} => ".self::export($rx); + $startingMark = $state->mark; + $state->mark += \strlen($rx); + $state->regex = $rx; + + foreach ($perHost as [$hostRegex, $routes]) { + if ($matchHost) { + if ($hostRegex) { + preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx); + $state->vars = []; + $hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.'; + $state->hostVars = $state->vars; + } else { + $hostRegex = '(?:(?:[^./]*+\.)++)'; + $state->hostVars = []; + } + $state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?"); + $code .= "\n .".self::export($rx); + $state->regex .= $rx; + $prev = true; + } + + $tree = new StaticPrefixCollection(); + foreach ($routes->all() as $name => $route) { + preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx); + + $state->vars = []; + $regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]); + if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) { + $regex = substr($regex, 0, -1); + } + $hasTrailingVar = (bool) preg_match('#\{\w+\}/?$#', $route->getPath()); + + $tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]); + } + + $code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions); + } + if ($matchHost) { + $code .= "\n .')'"; + $state->regex .= ')'; + } + $rx = ")/?$}{$modifiers}"; + $code .= "\n .'{$rx}',"; + $state->regex .= $rx; + $state->markTail = 0; + + // if the regex is too large, throw a signaling exception to recompute with smaller chunk size + set_error_handler(function ($type, $message) { throw str_contains($message, $this->signalingException->getMessage()) ? $this->signalingException : new \ErrorException($message); }); + try { + preg_match($state->regex, ''); + } finally { + restore_error_handler(); + } + + $regexpList[$startingMark] = $state->regex; + } + + $state->routes[$state->mark][] = [null, null, null, null, false, false, 0]; + unset($state->getVars); + + return [$regexpList, $state->routes, $code]; + } + + /** + * Compiles a regexp tree of subpatterns that matches nested same-prefix routes. + * + * @param \stdClass $state A simple state object that keeps track of the progress of the compilation, + * and gathers the generated switch's "case" and "default" statements + */ + private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \stdClass $state, int $prefixLen, array &$conditions): string + { + $code = ''; + $prevRegex = null; + $routes = $tree->getRoutes(); + + foreach ($routes as $i => $route) { + if ($route instanceof StaticPrefixCollection) { + $prevRegex = null; + $prefix = substr($route->getPrefix(), $prefixLen); + $state->mark += \strlen($rx = "|{$prefix}(?"); + $code .= "\n .".self::export($rx); + $state->regex .= $rx; + $code .= $this->indent($this->compileStaticPrefixCollection($route, $state, $prefixLen + \strlen($prefix), $conditions)); + $code .= "\n .')'"; + $state->regex .= ')'; + ++$state->markTail; + continue; + } + + [$name, $regex, $vars, $route, $hasTrailingSlash, $hasTrailingVar] = $route; + $compiledRoute = $route->compile(); + $vars = array_merge($state->hostVars, $vars); + + if ($compiledRoute->getRegex() === $prevRegex) { + $state->routes[$state->mark][] = $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions); + continue; + } + + $state->mark += 3 + $state->markTail + \strlen($regex) - $prefixLen; + $state->markTail = 2 + \strlen($state->mark); + $rx = sprintf('|%s(*:%s)', substr($regex, $prefixLen), $state->mark); + $code .= "\n .".self::export($rx); + $state->regex .= $rx; + + $prevRegex = $compiledRoute->getRegex(); + $state->routes[$state->mark] = [$this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions)]; + } + + return $code; + } + + /** + * Compiles a single Route to PHP code used to match it against the path info. + */ + private function compileRoute(Route $route, string $name, $vars, bool $hasTrailingSlash, bool $hasTrailingVar, array &$conditions): array + { + $defaults = $route->getDefaults(); + + if (isset($defaults['_canonical_route'])) { + $name = $defaults['_canonical_route']; + unset($defaults['_canonical_route']); + } + + if ($condition = $route->getCondition()) { + $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request']); + $condition = $conditions[$condition] ?? $conditions[$condition] = (str_contains($condition, '$request') ? 1 : -1) * \count($conditions); + } else { + $condition = null; + } + + return [ + ['_route' => $name] + $defaults, + $vars, + array_flip($route->getMethods()) ?: null, + array_flip($route->getSchemes()) ?: null, + $hasTrailingSlash, + $hasTrailingVar, + $condition, + ]; + } + + private function getExpressionLanguage(): ExpressionLanguage + { + if (null === $this->expressionLanguage) { + if (!class_exists(ExpressionLanguage::class)) { + throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); + } + $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders); + } + + return $this->expressionLanguage; + } + + private function indent(string $code, int $level = 1): string + { + return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code); + } + + /** + * @internal + */ + public static function export($value): string + { + if (null === $value) { + return 'null'; + } + if (!\is_array($value)) { + if (\is_object($value)) { + throw new \InvalidArgumentException('Symfony\Component\Routing\Route cannot contain objects.'); + } + + return str_replace("\n", '\'."\n".\'', var_export($value, true)); + } + if (!$value) { + return '[]'; + } + + $i = 0; + $export = '['; + + foreach ($value as $k => $v) { + if ($i === $k) { + ++$i; + } else { + $export .= self::export($k).' => '; + + if (\is_int($k) && $i < $k) { + $i = 1 + $k; + } + } + + $export .= self::export($v).', '; + } + + return substr_replace($export, ']', -2); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php new file mode 100644 index 0000000..bdb7ba3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php @@ -0,0 +1,191 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher\Dumper; + +use Symfony\Component\Routing\Exception\MethodNotAllowedException; +use Symfony\Component\Routing\Exception\NoConfigurationException; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface; +use Symfony\Component\Routing\RequestContext; + +/** + * @author Nicolas Grekas + * + * @internal + * + * @property RequestContext $context + */ +trait CompiledUrlMatcherTrait +{ + private $matchHost = false; + private $staticRoutes = []; + private $regexpList = []; + private $dynamicRoutes = []; + + /** + * @var callable|null + */ + private $checkCondition; + + public function match(string $pathinfo): array + { + $allow = $allowSchemes = []; + if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) { + return $ret; + } + if ($allow) { + throw new MethodNotAllowedException(array_keys($allow)); + } + if (!$this instanceof RedirectableUrlMatcherInterface) { + throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo)); + } + if (!\in_array($this->context->getMethod(), ['HEAD', 'GET'], true)) { + // no-op + } elseif ($allowSchemes) { + redirect_scheme: + $scheme = $this->context->getScheme(); + $this->context->setScheme(key($allowSchemes)); + try { + if ($ret = $this->doMatch($pathinfo)) { + return $this->redirect($pathinfo, $ret['_route'], $this->context->getScheme()) + $ret; + } + } finally { + $this->context->setScheme($scheme); + } + } elseif ('/' !== $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/') { + $pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo; + if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) { + return $this->redirect($pathinfo, $ret['_route']) + $ret; + } + if ($allowSchemes) { + goto redirect_scheme; + } + } + + throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo)); + } + + private function doMatch(string $pathinfo, array &$allow = [], array &$allowSchemes = []): array + { + $allow = $allowSchemes = []; + $pathinfo = rawurldecode($pathinfo) ?: '/'; + $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/'; + $context = $this->context; + $requestMethod = $canonicalMethod = $context->getMethod(); + + if ($this->matchHost) { + $host = strtolower($context->getHost()); + } + + if ('HEAD' === $requestMethod) { + $canonicalMethod = 'GET'; + } + $supportsRedirections = 'GET' === $canonicalMethod && $this instanceof RedirectableUrlMatcherInterface; + + foreach ($this->staticRoutes[$trimmedPathinfo] ?? [] as [$ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, , $condition]) { + if ($condition && !($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) { + continue; + } + + if ($requiredHost) { + if ('{' !== $requiredHost[0] ? $requiredHost !== $host : !preg_match($requiredHost, $host, $hostMatches)) { + continue; + } + if ('{' === $requiredHost[0] && $hostMatches) { + $hostMatches['_route'] = $ret['_route']; + $ret = $this->mergeDefaults($hostMatches, $ret); + } + } + + if ('/' !== $pathinfo && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { + if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { + return $allow = $allowSchemes = []; + } + continue; + } + + $hasRequiredScheme = !$requiredSchemes || isset($requiredSchemes[$context->getScheme()]); + if ($hasRequiredScheme && $requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) { + $allow += $requiredMethods; + continue; + } + + if (!$hasRequiredScheme) { + $allowSchemes += $requiredSchemes; + continue; + } + + return $ret; + } + + $matchedPathinfo = $this->matchHost ? $host.'.'.$pathinfo : $pathinfo; + + foreach ($this->regexpList as $offset => $regex) { + while (preg_match($regex, $matchedPathinfo, $matches)) { + foreach ($this->dynamicRoutes[$m = (int) $matches['MARK']] as [$ret, $vars, $requiredMethods, $requiredSchemes, $hasTrailingSlash, $hasTrailingVar, $condition]) { + if (null !== $condition) { + if (0 === $condition) { // marks the last route in the regexp + continue 3; + } + if (!($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) { + continue; + } + } + + $hasTrailingVar = $trimmedPathinfo !== $pathinfo && $hasTrailingVar; + + if ($hasTrailingVar && ($hasTrailingSlash || (null === $n = $matches[\count($vars)] ?? null) || '/' !== ($n[-1] ?? '/')) && preg_match($regex, $this->matchHost ? $host.'.'.$trimmedPathinfo : $trimmedPathinfo, $n) && $m === (int) $n['MARK']) { + if ($hasTrailingSlash) { + $matches = $n; + } else { + $hasTrailingVar = false; + } + } + + if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { + if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { + return $allow = $allowSchemes = []; + } + continue; + } + + foreach ($vars as $i => $v) { + if (isset($matches[1 + $i])) { + $ret[$v] = $matches[1 + $i]; + } + } + + if ($requiredSchemes && !isset($requiredSchemes[$context->getScheme()])) { + $allowSchemes += $requiredSchemes; + continue; + } + + if ($requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) { + $allow += $requiredMethods; + continue; + } + + return $ret; + } + + $regex = substr_replace($regex, 'F', $m - $offset, 1 + \strlen($m)); + $offset += \strlen($m); + } + } + + if ('/' === $pathinfo && !$allow && !$allowSchemes) { + throw new NoConfigurationException(); + } + + return []; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/MatcherDumper.php b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/MatcherDumper.php new file mode 100644 index 0000000..ea51ab4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/MatcherDumper.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\Routing\Matcher\Dumper; + +use Symfony\Component\Routing\RouteCollection; + +/** + * MatcherDumper is the abstract class for all built-in matcher dumpers. + * + * @author Fabien Potencier + */ +abstract class MatcherDumper implements MatcherDumperInterface +{ + private $routes; + + public function __construct(RouteCollection $routes) + { + $this->routes = $routes; + } + + /** + * {@inheritdoc} + */ + public function getRoutes() + { + return $this->routes; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/MatcherDumperInterface.php b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/MatcherDumperInterface.php new file mode 100644 index 0000000..8e33802 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/MatcherDumperInterface.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\Routing\Matcher\Dumper; + +use Symfony\Component\Routing\RouteCollection; + +/** + * MatcherDumperInterface is the interface that all matcher dumper classes must implement. + * + * @author Fabien Potencier + */ +interface MatcherDumperInterface +{ + /** + * Dumps a set of routes to a string representation of executable code + * that can then be used to match a request against these routes. + * + * @return string + */ + public function dump(array $options = []); + + /** + * Gets the routes to dump. + * + * @return RouteCollection + */ + public function getRoutes(); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php new file mode 100644 index 0000000..47d923c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php @@ -0,0 +1,206 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher\Dumper; + +use Symfony\Component\Routing\RouteCollection; + +/** + * Prefix tree of routes preserving routes order. + * + * @author Frank de Jonge + * @author Nicolas Grekas + * + * @internal + */ +class StaticPrefixCollection +{ + private $prefix; + + /** + * @var string[] + */ + private $staticPrefixes = []; + + /** + * @var string[] + */ + private $prefixes = []; + + /** + * @var array[]|self[] + */ + private $items = []; + + public function __construct(string $prefix = '/') + { + $this->prefix = $prefix; + } + + public function getPrefix(): string + { + return $this->prefix; + } + + /** + * @return array[]|self[] + */ + public function getRoutes(): array + { + return $this->items; + } + + /** + * Adds a route to a group. + * + * @param array|self $route + */ + public function addRoute(string $prefix, $route) + { + [$prefix, $staticPrefix] = $this->getCommonPrefix($prefix, $prefix); + + for ($i = \count($this->items) - 1; 0 <= $i; --$i) { + $item = $this->items[$i]; + + [$commonPrefix, $commonStaticPrefix] = $this->getCommonPrefix($prefix, $this->prefixes[$i]); + + if ($this->prefix === $commonPrefix) { + // the new route and a previous one have no common prefix, let's see if they are exclusive to each others + + if ($this->prefix !== $staticPrefix && $this->prefix !== $this->staticPrefixes[$i]) { + // the new route and the previous one have exclusive static prefixes + continue; + } + + if ($this->prefix === $staticPrefix && $this->prefix === $this->staticPrefixes[$i]) { + // the new route and the previous one have no static prefix + break; + } + + if ($this->prefixes[$i] !== $this->staticPrefixes[$i] && $this->prefix === $this->staticPrefixes[$i]) { + // the previous route is non-static and has no static prefix + break; + } + + if ($prefix !== $staticPrefix && $this->prefix === $staticPrefix) { + // the new route is non-static and has no static prefix + break; + } + + continue; + } + + if ($item instanceof self && $this->prefixes[$i] === $commonPrefix) { + // the new route is a child of a previous one, let's nest it + $item->addRoute($prefix, $route); + } else { + // the new route and a previous one have a common prefix, let's merge them + $child = new self($commonPrefix); + [$child->prefixes[0], $child->staticPrefixes[0]] = $child->getCommonPrefix($this->prefixes[$i], $this->prefixes[$i]); + [$child->prefixes[1], $child->staticPrefixes[1]] = $child->getCommonPrefix($prefix, $prefix); + $child->items = [$this->items[$i], $route]; + + $this->staticPrefixes[$i] = $commonStaticPrefix; + $this->prefixes[$i] = $commonPrefix; + $this->items[$i] = $child; + } + + return; + } + + // No optimised case was found, in this case we simple add the route for possible + // grouping when new routes are added. + $this->staticPrefixes[] = $staticPrefix; + $this->prefixes[] = $prefix; + $this->items[] = $route; + } + + /** + * Linearizes back a set of nested routes into a collection. + */ + public function populateCollection(RouteCollection $routes): RouteCollection + { + foreach ($this->items as $route) { + if ($route instanceof self) { + $route->populateCollection($routes); + } else { + $routes->add(...$route); + } + } + + return $routes; + } + + /** + * Gets the full and static common prefixes between two route patterns. + * + * The static prefix stops at last at the first opening bracket. + */ + private function getCommonPrefix(string $prefix, string $anotherPrefix): array + { + $baseLength = \strlen($this->prefix); + $end = min(\strlen($prefix), \strlen($anotherPrefix)); + $staticLength = null; + set_error_handler([__CLASS__, 'handleError']); + + try { + for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) { + if ('(' === $prefix[$i]) { + $staticLength = $staticLength ?? $i; + for ($j = 1 + $i, $n = 1; $j < $end && 0 < $n; ++$j) { + if ($prefix[$j] !== $anotherPrefix[$j]) { + break 2; + } + if ('(' === $prefix[$j]) { + ++$n; + } elseif (')' === $prefix[$j]) { + --$n; + } elseif ('\\' === $prefix[$j] && (++$j === $end || $prefix[$j] !== $anotherPrefix[$j])) { + --$j; + break; + } + } + if (0 < $n) { + break; + } + if (('?' === ($prefix[$j] ?? '') || '?' === ($anotherPrefix[$j] ?? '')) && ($prefix[$j] ?? '') !== ($anotherPrefix[$j] ?? '')) { + break; + } + $subPattern = substr($prefix, $i, $j - $i); + if ($prefix !== $anotherPrefix && !preg_match('/^\(\[[^\]]++\]\+\+\)$/', $subPattern) && !preg_match('{(?> 6) && preg_match('//u', $prefix.' '.$anotherPrefix)) { + do { + // Prevent cutting in the middle of an UTF-8 characters + --$i; + } while (0b10 === (\ord($prefix[$i]) >> 6)); + } + + return [substr($prefix, 0, $i), substr($prefix, 0, $staticLength ?? $i)]; + } + + public static function handleError(int $type, string $msg) + { + return str_contains($msg, 'Compilation failed: lookbehind assertion is not fixed length') + || str_contains($msg, 'Compilation failed: length of lookbehind assertion is not limited'); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/ExpressionLanguageProvider.php b/php/libraries/composer/vendor/symfony/routing/Matcher/ExpressionLanguageProvider.php new file mode 100644 index 0000000..96bb7ba --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/ExpressionLanguageProvider.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\ExpressionLanguage\ExpressionFunction; +use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; +use Symfony\Contracts\Service\ServiceProviderInterface; + +/** + * Exposes functions defined in the request context to route conditions. + * + * @author Ahmed TAILOULOUTE + */ +class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface +{ + private $functions; + + public function __construct(ServiceProviderInterface $functions) + { + $this->functions = $functions; + } + + /** + * {@inheritdoc} + */ + public function getFunctions() + { + $functions = []; + + foreach ($this->functions->getProvidedServices() as $function => $type) { + $functions[] = new ExpressionFunction( + $function, + static function (...$args) use ($function) { + return sprintf('($context->getParameter(\'_functions\')->get(%s)(%s))', var_export($function, true), implode(', ', $args)); + }, + function ($values, ...$args) use ($function) { + return $values['context']->getParameter('_functions')->get($function)(...$args); + } + ); + } + + return $functions; + } + + public function get(string $function): callable + { + return $this->functions->get($function); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/RedirectableUrlMatcher.php b/php/libraries/composer/vendor/symfony/routing/Matcher/RedirectableUrlMatcher.php new file mode 100644 index 0000000..3cd7c81 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/RedirectableUrlMatcher.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\Routing\Exception\ExceptionInterface; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; + +/** + * @author Fabien Potencier + */ +abstract class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface +{ + /** + * {@inheritdoc} + */ + public function match(string $pathinfo) + { + try { + return parent::match($pathinfo); + } catch (ResourceNotFoundException $e) { + if (!\in_array($this->context->getMethod(), ['HEAD', 'GET'], true)) { + throw $e; + } + + if ($this->allowSchemes) { + redirect_scheme: + $scheme = $this->context->getScheme(); + $this->context->setScheme(current($this->allowSchemes)); + try { + $ret = parent::match($pathinfo); + + return $this->redirect($pathinfo, $ret['_route'] ?? null, $this->context->getScheme()) + $ret; + } catch (ExceptionInterface $e2) { + throw $e; + } finally { + $this->context->setScheme($scheme); + } + } elseif ('/' === $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/') { + throw $e; + } else { + try { + $pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo; + $ret = parent::match($pathinfo); + + return $this->redirect($pathinfo, $ret['_route'] ?? null) + $ret; + } catch (ExceptionInterface $e2) { + if ($this->allowSchemes) { + goto redirect_scheme; + } + throw $e; + } + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/RedirectableUrlMatcherInterface.php b/php/libraries/composer/vendor/symfony/routing/Matcher/RedirectableUrlMatcherInterface.php new file mode 100644 index 0000000..a43888b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/RedirectableUrlMatcherInterface.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +/** + * RedirectableUrlMatcherInterface knows how to redirect the user. + * + * @author Fabien Potencier + */ +interface RedirectableUrlMatcherInterface +{ + /** + * Redirects the user to another URL and returns the parameters for the redirection. + * + * @param string $path The path info to redirect to + * @param string $route The route name that matched + * @param string|null $scheme The URL scheme (null to keep the current one) + * + * @return array + */ + public function redirect(string $path, string $route, ?string $scheme = null); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/RequestMatcherInterface.php b/php/libraries/composer/vendor/symfony/routing/Matcher/RequestMatcherInterface.php new file mode 100644 index 0000000..c05016e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/RequestMatcherInterface.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Exception\MethodNotAllowedException; +use Symfony\Component\Routing\Exception\NoConfigurationException; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; + +/** + * RequestMatcherInterface is the interface that all request matcher classes must implement. + * + * @author Fabien Potencier + */ +interface RequestMatcherInterface +{ + /** + * Tries to match a request with a set of routes. + * + * If the matcher cannot find information, it must throw one of the exceptions documented + * below. + * + * @return array + * + * @throws NoConfigurationException If no routing configuration could be found + * @throws ResourceNotFoundException If no matching resource could be found + * @throws MethodNotAllowedException If a matching resource was found but the request method is not allowed + */ + public function matchRequest(Request $request); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/TraceableUrlMatcher.php b/php/libraries/composer/vendor/symfony/routing/Matcher/TraceableUrlMatcher.php new file mode 100644 index 0000000..cddfe02 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/TraceableUrlMatcher.php @@ -0,0 +1,164 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Exception\ExceptionInterface; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * TraceableUrlMatcher helps debug path info matching by tracing the match. + * + * @author Fabien Potencier + */ +class TraceableUrlMatcher extends UrlMatcher +{ + public const ROUTE_DOES_NOT_MATCH = 0; + public const ROUTE_ALMOST_MATCHES = 1; + public const ROUTE_MATCHES = 2; + + protected $traces; + + public function getTraces(string $pathinfo) + { + $this->traces = []; + + try { + $this->match($pathinfo); + } catch (ExceptionInterface $e) { + } + + return $this->traces; + } + + public function getTracesForRequest(Request $request) + { + $this->request = $request; + $traces = $this->getTraces($request->getPathInfo()); + $this->request = null; + + return $traces; + } + + protected function matchCollection(string $pathinfo, RouteCollection $routes) + { + // HEAD and GET are equivalent as per RFC + if ('HEAD' === $method = $this->context->getMethod()) { + $method = 'GET'; + } + $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface; + $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/'; + + foreach ($routes as $name => $route) { + $compiledRoute = $route->compile(); + $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/'); + $requiredMethods = $route->getMethods(); + + // check the static prefix of the URL first. Only use the more expensive preg_match when it matches + if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) { + $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route); + continue; + } + $regex = $compiledRoute->getRegex(); + + $pos = strrpos($regex, '$'); + $hasTrailingSlash = '/' === $regex[$pos - 1]; + $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash); + + if (!preg_match($regex, $pathinfo, $matches)) { + // does it match without any requirements? + $r = new Route($route->getPath(), $route->getDefaults(), [], $route->getOptions()); + $cr = $r->compile(); + if (!preg_match($cr->getRegex(), $pathinfo)) { + $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route); + + continue; + } + + foreach ($route->getRequirements() as $n => $regex) { + $r = new Route($route->getPath(), $route->getDefaults(), [$n => $regex], $route->getOptions()); + $cr = $r->compile(); + + if (\in_array($n, $cr->getVariables()) && !preg_match($cr->getRegex(), $pathinfo)) { + $this->addTrace(sprintf('Requirement for "%s" does not match (%s)', $n, $regex), self::ROUTE_ALMOST_MATCHES, $name, $route); + + continue 2; + } + } + + continue; + } + + $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath()); + + if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) { + if ($hasTrailingSlash) { + $matches = $m; + } else { + $hasTrailingVar = false; + } + } + + $hostMatches = []; + if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) { + $this->addTrace(sprintf('Host "%s" does not match the requirement ("%s")', $this->context->getHost(), $route->getHost()), self::ROUTE_ALMOST_MATCHES, $name, $route); + continue; + } + + $status = $this->handleRouteRequirements($pathinfo, $name, $route); + + if (self::REQUIREMENT_MISMATCH === $status[0]) { + $this->addTrace(sprintf('Condition "%s" does not evaluate to "true"', $route->getCondition()), self::ROUTE_ALMOST_MATCHES, $name, $route); + continue; + } + + if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { + if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) { + $this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route); + + return $this->allow = $this->allowSchemes = []; + } + $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route); + continue; + } + + if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) { + $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes()); + $this->addTrace(sprintf('Scheme "%s" does not match any of the required schemes (%s)', $this->context->getScheme(), implode(', ', $route->getSchemes())), self::ROUTE_ALMOST_MATCHES, $name, $route); + continue; + } + + if ($requiredMethods && !\in_array($method, $requiredMethods)) { + $this->allow = array_merge($this->allow, $requiredMethods); + $this->addTrace(sprintf('Method "%s" does not match any of the required methods (%s)', $this->context->getMethod(), implode(', ', $requiredMethods)), self::ROUTE_ALMOST_MATCHES, $name, $route); + continue; + } + + $this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route); + + return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, $status[1] ?? [])); + } + + return []; + } + + private function addTrace(string $log, int $level = self::ROUTE_DOES_NOT_MATCH, ?string $name = null, ?Route $route = null) + { + $this->traces[] = [ + 'log' => $log, + 'name' => $name, + 'level' => $level, + 'path' => null !== $route ? $route->getPath() : null, + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/UrlMatcher.php b/php/libraries/composer/vendor/symfony/routing/Matcher/UrlMatcher.php new file mode 100644 index 0000000..f076a2f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/UrlMatcher.php @@ -0,0 +1,279 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; +use Symfony\Component\ExpressionLanguage\ExpressionLanguage; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Exception\MethodNotAllowedException; +use Symfony\Component\Routing\Exception\NoConfigurationException; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * UrlMatcher matches URL based on a set of routes. + * + * @author Fabien Potencier + */ +class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface +{ + public const REQUIREMENT_MATCH = 0; + public const REQUIREMENT_MISMATCH = 1; + public const ROUTE_MATCH = 2; + + /** @var RequestContext */ + protected $context; + + /** + * Collects HTTP methods that would be allowed for the request. + */ + protected $allow = []; + + /** + * Collects URI schemes that would be allowed for the request. + * + * @internal + */ + protected $allowSchemes = []; + + protected $routes; + protected $request; + protected $expressionLanguage; + + /** + * @var ExpressionFunctionProviderInterface[] + */ + protected $expressionLanguageProviders = []; + + public function __construct(RouteCollection $routes, RequestContext $context) + { + $this->routes = $routes; + $this->context = $context; + } + + /** + * {@inheritdoc} + */ + public function setContext(RequestContext $context) + { + $this->context = $context; + } + + /** + * {@inheritdoc} + */ + public function getContext() + { + return $this->context; + } + + /** + * {@inheritdoc} + */ + public function match(string $pathinfo) + { + $this->allow = $this->allowSchemes = []; + + if ($ret = $this->matchCollection(rawurldecode($pathinfo) ?: '/', $this->routes)) { + return $ret; + } + + if ('/' === $pathinfo && !$this->allow && !$this->allowSchemes) { + throw new NoConfigurationException(); + } + + throw 0 < \count($this->allow) ? new MethodNotAllowedException(array_unique($this->allow)) : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo)); + } + + /** + * {@inheritdoc} + */ + public function matchRequest(Request $request) + { + $this->request = $request; + + $ret = $this->match($request->getPathInfo()); + + $this->request = null; + + return $ret; + } + + public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) + { + $this->expressionLanguageProviders[] = $provider; + } + + /** + * Tries to match a URL with a set of routes. + * + * @param string $pathinfo The path info to be parsed + * + * @return array + * + * @throws NoConfigurationException If no routing configuration could be found + * @throws ResourceNotFoundException If the resource could not be found + * @throws MethodNotAllowedException If the resource was found but the request method is not allowed + */ + protected function matchCollection(string $pathinfo, RouteCollection $routes) + { + // HEAD and GET are equivalent as per RFC + if ('HEAD' === $method = $this->context->getMethod()) { + $method = 'GET'; + } + $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface; + $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/'; + + foreach ($routes as $name => $route) { + $compiledRoute = $route->compile(); + $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/'); + $requiredMethods = $route->getMethods(); + + // check the static prefix of the URL first. Only use the more expensive preg_match when it matches + if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) { + continue; + } + $regex = $compiledRoute->getRegex(); + + $pos = strrpos($regex, '$'); + $hasTrailingSlash = '/' === $regex[$pos - 1]; + $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash); + + if (!preg_match($regex, $pathinfo, $matches)) { + continue; + } + + $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath()); + + if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) { + if ($hasTrailingSlash) { + $matches = $m; + } else { + $hasTrailingVar = false; + } + } + + $hostMatches = []; + if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) { + continue; + } + + $status = $this->handleRouteRequirements($pathinfo, $name, $route); + + if (self::REQUIREMENT_MISMATCH === $status[0]) { + continue; + } + + if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { + if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) { + return $this->allow = $this->allowSchemes = []; + } + continue; + } + + if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) { + $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes()); + continue; + } + + if ($requiredMethods && !\in_array($method, $requiredMethods)) { + $this->allow = array_merge($this->allow, $requiredMethods); + continue; + } + + return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, $status[1] ?? [])); + } + + return []; + } + + /** + * Returns an array of values to use as request attributes. + * + * As this method requires the Route object, it is not available + * in matchers that do not have access to the matched Route instance + * (like the PHP and Apache matcher dumpers). + * + * @return array + */ + protected function getAttributes(Route $route, string $name, array $attributes) + { + $defaults = $route->getDefaults(); + if (isset($defaults['_canonical_route'])) { + $name = $defaults['_canonical_route']; + unset($defaults['_canonical_route']); + } + $attributes['_route'] = $name; + + return $this->mergeDefaults($attributes, $defaults); + } + + /** + * Handles specific route requirements. + * + * @return array The first element represents the status, the second contains additional information + */ + protected function handleRouteRequirements(string $pathinfo, string $name, Route $route) + { + // expression condition + if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) { + return [self::REQUIREMENT_MISMATCH, null]; + } + + return [self::REQUIREMENT_MATCH, null]; + } + + /** + * Get merged default parameters. + * + * @return array + */ + protected function mergeDefaults(array $params, array $defaults) + { + foreach ($params as $key => $value) { + if (!\is_int($key) && null !== $value) { + $defaults[$key] = $value; + } + } + + return $defaults; + } + + protected function getExpressionLanguage() + { + if (null === $this->expressionLanguage) { + if (!class_exists(ExpressionLanguage::class)) { + throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); + } + $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders); + } + + return $this->expressionLanguage; + } + + /** + * @internal + */ + protected function createRequest(string $pathinfo): ?Request + { + if (!class_exists(Request::class)) { + return null; + } + + return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [ + 'SCRIPT_FILENAME' => $this->context->getBaseUrl(), + 'SCRIPT_NAME' => $this->context->getBaseUrl(), + ]); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/Matcher/UrlMatcherInterface.php b/php/libraries/composer/vendor/symfony/routing/Matcher/UrlMatcherInterface.php new file mode 100644 index 0000000..0a5be97 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Matcher/UrlMatcherInterface.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\Routing\Exception\MethodNotAllowedException; +use Symfony\Component\Routing\Exception\NoConfigurationException; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\RequestContextAwareInterface; + +/** + * UrlMatcherInterface is the interface that all URL matcher classes must implement. + * + * @author Fabien Potencier + */ +interface UrlMatcherInterface extends RequestContextAwareInterface +{ + /** + * Tries to match a URL path with a set of routes. + * + * If the matcher cannot find information, it must throw one of the exceptions documented + * below. + * + * @param string $pathinfo The path info to be parsed (raw format, i.e. not urldecoded) + * + * @return array + * + * @throws NoConfigurationException If no routing configuration could be found + * @throws ResourceNotFoundException If the resource could not be found + * @throws MethodNotAllowedException If the resource was found but the request method is not allowed + */ + public function match(string $pathinfo); +} diff --git a/php/libraries/composer/vendor/symfony/routing/README.md b/php/libraries/composer/vendor/symfony/routing/README.md new file mode 100644 index 0000000..ae8284f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/README.md @@ -0,0 +1,51 @@ +Routing Component +================= + +The Routing component maps an HTTP request to a set of configuration variables. + +Getting Started +--------------- + +``` +$ composer require symfony/routing +``` + +```php +use App\Controller\BlogController; +use Symfony\Component\Routing\Generator\UrlGenerator; +use Symfony\Component\Routing\Matcher\UrlMatcher; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +$route = new Route('/blog/{slug}', ['_controller' => BlogController::class]); +$routes = new RouteCollection(); +$routes->add('blog_show', $route); + +$context = new RequestContext(); + +// Routing can match routes with incoming requests +$matcher = new UrlMatcher($routes, $context); +$parameters = $matcher->match('/blog/lorem-ipsum'); +// $parameters = [ +// '_controller' => 'App\Controller\BlogController', +// 'slug' => 'lorem-ipsum', +// '_route' => 'blog_show' +// ] + +// Routing can also generate URLs for a given route +$generator = new UrlGenerator($routes, $context); +$url = $generator->generate('blog_show', [ + 'slug' => 'my-blog-post', +]); +// $url = '/blog/my-blog-post' +``` + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/routing.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/routing/RequestContext.php b/php/libraries/composer/vendor/symfony/routing/RequestContext.php new file mode 100644 index 0000000..f54c430 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RequestContext.php @@ -0,0 +1,327 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +use Symfony\Component\HttpFoundation\Request; + +/** + * Holds information about the current request. + * + * This class implements a fluent interface. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class RequestContext +{ + private $baseUrl; + private $pathInfo; + private $method; + private $host; + private $scheme; + private $httpPort; + private $httpsPort; + private $queryString; + private $parameters = []; + + public function __construct(string $baseUrl = '', string $method = 'GET', string $host = 'localhost', string $scheme = 'http', int $httpPort = 80, int $httpsPort = 443, string $path = '/', string $queryString = '') + { + $this->setBaseUrl($baseUrl); + $this->setMethod($method); + $this->setHost($host); + $this->setScheme($scheme); + $this->setHttpPort($httpPort); + $this->setHttpsPort($httpsPort); + $this->setPathInfo($path); + $this->setQueryString($queryString); + } + + public static function fromUri(string $uri, string $host = 'localhost', string $scheme = 'http', int $httpPort = 80, int $httpsPort = 443): self + { + $uri = parse_url($uri); + $scheme = $uri['scheme'] ?? $scheme; + $host = $uri['host'] ?? $host; + + if (isset($uri['port'])) { + if ('http' === $scheme) { + $httpPort = $uri['port']; + } elseif ('https' === $scheme) { + $httpsPort = $uri['port']; + } + } + + return new self($uri['path'] ?? '', 'GET', $host, $scheme, $httpPort, $httpsPort); + } + + /** + * Updates the RequestContext information based on a HttpFoundation Request. + * + * @return $this + */ + public function fromRequest(Request $request) + { + $this->setBaseUrl($request->getBaseUrl()); + $this->setPathInfo($request->getPathInfo()); + $this->setMethod($request->getMethod()); + $this->setHost($request->getHost()); + $this->setScheme($request->getScheme()); + $this->setHttpPort($request->isSecure() || null === $request->getPort() ? $this->httpPort : $request->getPort()); + $this->setHttpsPort($request->isSecure() && null !== $request->getPort() ? $request->getPort() : $this->httpsPort); + $this->setQueryString($request->server->get('QUERY_STRING', '')); + + return $this; + } + + /** + * Gets the base URL. + * + * @return string + */ + public function getBaseUrl() + { + return $this->baseUrl; + } + + /** + * Sets the base URL. + * + * @return $this + */ + public function setBaseUrl(string $baseUrl) + { + $this->baseUrl = rtrim($baseUrl, '/'); + + return $this; + } + + /** + * Gets the path info. + * + * @return string + */ + public function getPathInfo() + { + return $this->pathInfo; + } + + /** + * Sets the path info. + * + * @return $this + */ + public function setPathInfo(string $pathInfo) + { + $this->pathInfo = $pathInfo; + + return $this; + } + + /** + * Gets the HTTP method. + * + * The method is always an uppercased string. + * + * @return string + */ + public function getMethod() + { + return $this->method; + } + + /** + * Sets the HTTP method. + * + * @return $this + */ + public function setMethod(string $method) + { + $this->method = strtoupper($method); + + return $this; + } + + /** + * Gets the HTTP host. + * + * The host is always lowercased because it must be treated case-insensitive. + * + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the HTTP host. + * + * @return $this + */ + public function setHost(string $host) + { + $this->host = strtolower($host); + + return $this; + } + + /** + * Gets the HTTP scheme. + * + * @return string + */ + public function getScheme() + { + return $this->scheme; + } + + /** + * Sets the HTTP scheme. + * + * @return $this + */ + public function setScheme(string $scheme) + { + $this->scheme = strtolower($scheme); + + return $this; + } + + /** + * Gets the HTTP port. + * + * @return int + */ + public function getHttpPort() + { + return $this->httpPort; + } + + /** + * Sets the HTTP port. + * + * @return $this + */ + public function setHttpPort(int $httpPort) + { + $this->httpPort = $httpPort; + + return $this; + } + + /** + * Gets the HTTPS port. + * + * @return int + */ + public function getHttpsPort() + { + return $this->httpsPort; + } + + /** + * Sets the HTTPS port. + * + * @return $this + */ + public function setHttpsPort(int $httpsPort) + { + $this->httpsPort = $httpsPort; + + return $this; + } + + /** + * Gets the query string without the "?". + * + * @return string + */ + public function getQueryString() + { + return $this->queryString; + } + + /** + * Sets the query string. + * + * @return $this + */ + public function setQueryString(?string $queryString) + { + // string cast to be fault-tolerant, accepting null + $this->queryString = (string) $queryString; + + return $this; + } + + /** + * Returns the parameters. + * + * @return array + */ + public function getParameters() + { + return $this->parameters; + } + + /** + * Sets the parameters. + * + * @param array $parameters The parameters + * + * @return $this + */ + public function setParameters(array $parameters) + { + $this->parameters = $parameters; + + return $this; + } + + /** + * Gets a parameter value. + * + * @return mixed + */ + public function getParameter(string $name) + { + return $this->parameters[$name] ?? null; + } + + /** + * Checks if a parameter value is set for the given parameter. + * + * @return bool + */ + public function hasParameter(string $name) + { + return \array_key_exists($name, $this->parameters); + } + + /** + * Sets a parameter value. + * + * @param mixed $parameter The parameter value + * + * @return $this + */ + public function setParameter(string $name, $parameter) + { + $this->parameters[$name] = $parameter; + + return $this; + } + + public function isSecure(): bool + { + return 'https' === $this->scheme; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/RequestContextAwareInterface.php b/php/libraries/composer/vendor/symfony/routing/RequestContextAwareInterface.php new file mode 100644 index 0000000..270a2b0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RequestContextAwareInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +interface RequestContextAwareInterface +{ + /** + * Sets the request context. + */ + public function setContext(RequestContext $context); + + /** + * Gets the request context. + * + * @return RequestContext + */ + public function getContext(); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Route.php b/php/libraries/composer/vendor/symfony/routing/Route.php new file mode 100644 index 0000000..c67bd2d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Route.php @@ -0,0 +1,507 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +/** + * A Route describes a route and its parameters. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class Route implements \Serializable +{ + private $path = '/'; + private $host = ''; + private $schemes = []; + private $methods = []; + private $defaults = []; + private $requirements = []; + private $options = []; + private $condition = ''; + + /** + * @var CompiledRoute|null + */ + private $compiled; + + /** + * Constructor. + * + * Available options: + * + * * compiler_class: A class name able to compile this route instance (RouteCompiler by default) + * * utf8: Whether UTF-8 matching is enforced ot not + * + * @param string $path The path pattern to match + * @param array $defaults An array of default parameter values + * @param array $requirements An array of requirements for parameters (regexes) + * @param array $options An array of options + * @param string|null $host The host pattern to match + * @param string|string[] $schemes A required URI scheme or an array of restricted schemes + * @param string|string[] $methods A required HTTP method or an array of restricted methods + * @param string|null $condition A condition that should evaluate to true for the route to match + */ + public function __construct(string $path, array $defaults = [], array $requirements = [], array $options = [], ?string $host = '', $schemes = [], $methods = [], ?string $condition = '') + { + $this->setPath($path); + $this->addDefaults($defaults); + $this->addRequirements($requirements); + $this->setOptions($options); + $this->setHost($host); + $this->setSchemes($schemes); + $this->setMethods($methods); + $this->setCondition($condition); + } + + public function __serialize(): array + { + return [ + 'path' => $this->path, + 'host' => $this->host, + 'defaults' => $this->defaults, + 'requirements' => $this->requirements, + 'options' => $this->options, + 'schemes' => $this->schemes, + 'methods' => $this->methods, + 'condition' => $this->condition, + 'compiled' => $this->compiled, + ]; + } + + /** + * @internal + */ + final public function serialize(): string + { + return serialize($this->__serialize()); + } + + public function __unserialize(array $data): void + { + $this->path = $data['path']; + $this->host = $data['host']; + $this->defaults = $data['defaults']; + $this->requirements = $data['requirements']; + $this->options = $data['options']; + $this->schemes = $data['schemes']; + $this->methods = $data['methods']; + + if (isset($data['condition'])) { + $this->condition = $data['condition']; + } + if (isset($data['compiled'])) { + $this->compiled = $data['compiled']; + } + } + + /** + * @internal + */ + final public function unserialize($serialized) + { + $this->__unserialize(unserialize($serialized)); + } + + /** + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * @return $this + */ + public function setPath(string $pattern) + { + $pattern = $this->extractInlineDefaultsAndRequirements($pattern); + + // A pattern must start with a slash and must not have multiple slashes at the beginning because the + // generated path for this route would be confused with a network path, e.g. '//domain.com/path'. + $this->path = '/'.ltrim(trim($pattern), '/'); + $this->compiled = null; + + return $this; + } + + /** + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * @return $this + */ + public function setHost(?string $pattern) + { + $this->host = $this->extractInlineDefaultsAndRequirements((string) $pattern); + $this->compiled = null; + + return $this; + } + + /** + * Returns the lowercased schemes this route is restricted to. + * So an empty array means that any scheme is allowed. + * + * @return string[] + */ + public function getSchemes() + { + return $this->schemes; + } + + /** + * Sets the schemes (e.g. 'https') this route is restricted to. + * So an empty array means that any scheme is allowed. + * + * @param string|string[] $schemes The scheme or an array of schemes + * + * @return $this + */ + public function setSchemes($schemes) + { + $this->schemes = array_map('strtolower', (array) $schemes); + $this->compiled = null; + + return $this; + } + + /** + * Checks if a scheme requirement has been set. + * + * @return bool + */ + public function hasScheme(string $scheme) + { + return \in_array(strtolower($scheme), $this->schemes, true); + } + + /** + * Returns the uppercased HTTP methods this route is restricted to. + * So an empty array means that any method is allowed. + * + * @return string[] + */ + public function getMethods() + { + return $this->methods; + } + + /** + * Sets the HTTP methods (e.g. 'POST') this route is restricted to. + * So an empty array means that any method is allowed. + * + * @param string|string[] $methods The method or an array of methods + * + * @return $this + */ + public function setMethods($methods) + { + $this->methods = array_map('strtoupper', (array) $methods); + $this->compiled = null; + + return $this; + } + + /** + * @return array + */ + public function getOptions() + { + return $this->options; + } + + /** + * @return $this + */ + public function setOptions(array $options) + { + $this->options = [ + 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler', + ]; + + return $this->addOptions($options); + } + + /** + * @return $this + */ + public function addOptions(array $options) + { + foreach ($options as $name => $option) { + $this->options[$name] = $option; + } + $this->compiled = null; + + return $this; + } + + /** + * Sets an option value. + * + * @param mixed $value The option value + * + * @return $this + */ + public function setOption(string $name, $value) + { + $this->options[$name] = $value; + $this->compiled = null; + + return $this; + } + + /** + * Returns the option value or null when not found. + * + * @return mixed + */ + public function getOption(string $name) + { + return $this->options[$name] ?? null; + } + + /** + * @return bool + */ + public function hasOption(string $name) + { + return \array_key_exists($name, $this->options); + } + + /** + * @return array + */ + public function getDefaults() + { + return $this->defaults; + } + + /** + * @return $this + */ + public function setDefaults(array $defaults) + { + $this->defaults = []; + + return $this->addDefaults($defaults); + } + + /** + * @return $this + */ + public function addDefaults(array $defaults) + { + if (isset($defaults['_locale']) && $this->isLocalized()) { + unset($defaults['_locale']); + } + + foreach ($defaults as $name => $default) { + $this->defaults[$name] = $default; + } + $this->compiled = null; + + return $this; + } + + /** + * @return mixed + */ + public function getDefault(string $name) + { + return $this->defaults[$name] ?? null; + } + + /** + * @return bool + */ + public function hasDefault(string $name) + { + return \array_key_exists($name, $this->defaults); + } + + /** + * Sets a default value. + * + * @param mixed $default The default value + * + * @return $this + */ + public function setDefault(string $name, $default) + { + if ('_locale' === $name && $this->isLocalized()) { + return $this; + } + + $this->defaults[$name] = $default; + $this->compiled = null; + + return $this; + } + + /** + * @return array + */ + public function getRequirements() + { + return $this->requirements; + } + + /** + * @return $this + */ + public function setRequirements(array $requirements) + { + $this->requirements = []; + + return $this->addRequirements($requirements); + } + + /** + * @return $this + */ + public function addRequirements(array $requirements) + { + if (isset($requirements['_locale']) && $this->isLocalized()) { + unset($requirements['_locale']); + } + + foreach ($requirements as $key => $regex) { + $this->requirements[$key] = $this->sanitizeRequirement($key, $regex); + } + $this->compiled = null; + + return $this; + } + + /** + * @return string|null + */ + public function getRequirement(string $key) + { + return $this->requirements[$key] ?? null; + } + + /** + * @return bool + */ + public function hasRequirement(string $key) + { + return \array_key_exists($key, $this->requirements); + } + + /** + * @return $this + */ + public function setRequirement(string $key, string $regex) + { + if ('_locale' === $key && $this->isLocalized()) { + return $this; + } + + $this->requirements[$key] = $this->sanitizeRequirement($key, $regex); + $this->compiled = null; + + return $this; + } + + /** + * @return string + */ + public function getCondition() + { + return $this->condition; + } + + /** + * @return $this + */ + public function setCondition(?string $condition) + { + $this->condition = (string) $condition; + $this->compiled = null; + + return $this; + } + + /** + * Compiles the route. + * + * @return CompiledRoute + * + * @throws \LogicException If the Route cannot be compiled because the + * path or host pattern is invalid + * + * @see RouteCompiler which is responsible for the compilation process + */ + public function compile() + { + if (null !== $this->compiled) { + return $this->compiled; + } + + $class = $this->getOption('compiler_class'); + + return $this->compiled = $class::compile($this); + } + + private function extractInlineDefaultsAndRequirements(string $pattern): string + { + if (false === strpbrk($pattern, '?<')) { + return $pattern; + } + + return preg_replace_callback('#\{(!?)(\w++)(<.*?>)?(\?[^\}]*+)?\}#', function ($m) { + if (isset($m[4][0])) { + $this->setDefault($m[2], '?' !== $m[4] ? substr($m[4], 1) : null); + } + if (isset($m[3][0])) { + $this->setRequirement($m[2], substr($m[3], 1, -1)); + } + + return '{'.$m[1].$m[2].'}'; + }, $pattern); + } + + private function sanitizeRequirement(string $key, string $regex) + { + if ('' !== $regex) { + if ('^' === $regex[0]) { + $regex = substr($regex, 1); + } elseif (0 === strpos($regex, '\\A')) { + $regex = substr($regex, 2); + } + } + + if (str_ends_with($regex, '$')) { + $regex = substr($regex, 0, -1); + } elseif (\strlen($regex) - 2 === strpos($regex, '\\z')) { + $regex = substr($regex, 0, -2); + } + + if ('' === $regex) { + throw new \InvalidArgumentException(sprintf('Routing requirement for "%s" cannot be empty.', $key)); + } + + return $regex; + } + + private function isLocalized(): bool + { + return isset($this->defaults['_locale']) && isset($this->defaults['_canonical_route']) && ($this->requirements['_locale'] ?? null) === preg_quote($this->defaults['_locale']); + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/RouteCollection.php b/php/libraries/composer/vendor/symfony/routing/RouteCollection.php new file mode 100644 index 0000000..95faead --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RouteCollection.php @@ -0,0 +1,403 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +use Symfony\Component\Config\Resource\ResourceInterface; +use Symfony\Component\Routing\Exception\InvalidArgumentException; +use Symfony\Component\Routing\Exception\RouteCircularReferenceException; + +/** + * A RouteCollection represents a set of Route instances. + * + * When adding a route at the end of the collection, an existing route + * with the same name is removed first. So there can only be one route + * with a given name. + * + * @author Fabien Potencier + * @author Tobias Schultze + * + * @implements \IteratorAggregate + */ +class RouteCollection implements \IteratorAggregate, \Countable +{ + /** + * @var array + */ + private $routes = []; + + /** + * @var array + */ + private $aliases = []; + + /** + * @var array + */ + private $resources = []; + + /** + * @var array + */ + private $priorities = []; + + public function __clone() + { + foreach ($this->routes as $name => $route) { + $this->routes[$name] = clone $route; + } + + foreach ($this->aliases as $name => $alias) { + $this->aliases[$name] = clone $alias; + } + } + + /** + * Gets the current RouteCollection as an Iterator that includes all routes. + * + * It implements \IteratorAggregate. + * + * @see all() + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new \ArrayIterator($this->all()); + } + + /** + * Gets the number of Routes in this collection. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return \count($this->routes); + } + + /** + * @param int $priority + */ + public function add(string $name, Route $route/* , int $priority = 0 */) + { + if (\func_num_args() < 3 && __CLASS__ !== static::class && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface && !$this instanceof \Mockery\MockInterface) { + trigger_deprecation('symfony/routing', '5.1', 'The "%s()" method will have a new "int $priority = 0" argument in version 6.0, not defining it is deprecated.', __METHOD__); + } + + unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]); + + $this->routes[$name] = $route; + + if ($priority = 3 <= \func_num_args() ? func_get_arg(2) : 0) { + $this->priorities[$name] = $priority; + } + } + + /** + * Returns all routes in this collection. + * + * @return array + */ + public function all() + { + if ($this->priorities) { + $priorities = $this->priorities; + $keysOrder = array_flip(array_keys($this->routes)); + uksort($this->routes, static function ($n1, $n2) use ($priorities, $keysOrder) { + return (($priorities[$n2] ?? 0) <=> ($priorities[$n1] ?? 0)) ?: ($keysOrder[$n1] <=> $keysOrder[$n2]); + }); + } + + return $this->routes; + } + + /** + * Gets a route by name. + * + * @return Route|null + */ + public function get(string $name) + { + $visited = []; + while (null !== $alias = $this->aliases[$name] ?? null) { + if (false !== $searchKey = array_search($name, $visited)) { + $visited[] = $name; + + throw new RouteCircularReferenceException($name, \array_slice($visited, $searchKey)); + } + + if ($alias->isDeprecated()) { + $deprecation = $alias->getDeprecation($name); + + trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']); + } + + $visited[] = $name; + $name = $alias->getId(); + } + + return $this->routes[$name] ?? null; + } + + /** + * Removes a route or an array of routes by name from the collection. + * + * @param string|string[] $name The route name or an array of route names + */ + public function remove($name) + { + $routes = []; + foreach ((array) $name as $n) { + if (isset($this->routes[$n])) { + $routes[] = $n; + } + + unset($this->routes[$n], $this->priorities[$n], $this->aliases[$n]); + } + + if (!$routes) { + return; + } + + foreach ($this->aliases as $k => $alias) { + if (\in_array($alias->getId(), $routes, true)) { + unset($this->aliases[$k]); + } + } + } + + /** + * Adds a route collection at the end of the current set by appending all + * routes of the added collection. + */ + public function addCollection(self $collection) + { + // we need to remove all routes with the same names first because just replacing them + // would not place the new route at the end of the merged array + foreach ($collection->all() as $name => $route) { + unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]); + $this->routes[$name] = $route; + + if (isset($collection->priorities[$name])) { + $this->priorities[$name] = $collection->priorities[$name]; + } + } + + foreach ($collection->getAliases() as $name => $alias) { + unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]); + + $this->aliases[$name] = $alias; + } + + foreach ($collection->getResources() as $resource) { + $this->addResource($resource); + } + } + + /** + * Adds a prefix to the path of all child routes. + */ + public function addPrefix(string $prefix, array $defaults = [], array $requirements = []) + { + $prefix = trim(trim($prefix), '/'); + + if ('' === $prefix) { + return; + } + + foreach ($this->routes as $route) { + $route->setPath('/'.$prefix.$route->getPath()); + $route->addDefaults($defaults); + $route->addRequirements($requirements); + } + } + + /** + * Adds a prefix to the name of all the routes within in the collection. + */ + public function addNamePrefix(string $prefix) + { + $prefixedRoutes = []; + $prefixedPriorities = []; + $prefixedAliases = []; + + foreach ($this->routes as $name => $route) { + $prefixedRoutes[$prefix.$name] = $route; + if (null !== $canonicalName = $route->getDefault('_canonical_route')) { + $route->setDefault('_canonical_route', $prefix.$canonicalName); + } + if (isset($this->priorities[$name])) { + $prefixedPriorities[$prefix.$name] = $this->priorities[$name]; + } + } + + foreach ($this->aliases as $name => $alias) { + $prefixedAliases[$prefix.$name] = $alias->withId($prefix.$alias->getId()); + } + + $this->routes = $prefixedRoutes; + $this->priorities = $prefixedPriorities; + $this->aliases = $prefixedAliases; + } + + /** + * Sets the host pattern on all routes. + */ + public function setHost(?string $pattern, array $defaults = [], array $requirements = []) + { + foreach ($this->routes as $route) { + $route->setHost($pattern); + $route->addDefaults($defaults); + $route->addRequirements($requirements); + } + } + + /** + * Sets a condition on all routes. + * + * Existing conditions will be overridden. + */ + public function setCondition(?string $condition) + { + foreach ($this->routes as $route) { + $route->setCondition($condition); + } + } + + /** + * Adds defaults to all routes. + * + * An existing default value under the same name in a route will be overridden. + */ + public function addDefaults(array $defaults) + { + if ($defaults) { + foreach ($this->routes as $route) { + $route->addDefaults($defaults); + } + } + } + + /** + * Adds requirements to all routes. + * + * An existing requirement under the same name in a route will be overridden. + */ + public function addRequirements(array $requirements) + { + if ($requirements) { + foreach ($this->routes as $route) { + $route->addRequirements($requirements); + } + } + } + + /** + * Adds options to all routes. + * + * An existing option value under the same name in a route will be overridden. + */ + public function addOptions(array $options) + { + if ($options) { + foreach ($this->routes as $route) { + $route->addOptions($options); + } + } + } + + /** + * Sets the schemes (e.g. 'https') all child routes are restricted to. + * + * @param string|string[] $schemes The scheme or an array of schemes + */ + public function setSchemes($schemes) + { + foreach ($this->routes as $route) { + $route->setSchemes($schemes); + } + } + + /** + * Sets the HTTP methods (e.g. 'POST') all child routes are restricted to. + * + * @param string|string[] $methods The method or an array of methods + */ + public function setMethods($methods) + { + foreach ($this->routes as $route) { + $route->setMethods($methods); + } + } + + /** + * Returns an array of resources loaded to build this collection. + * + * @return ResourceInterface[] + */ + public function getResources() + { + return array_values($this->resources); + } + + /** + * Adds a resource for this collection. If the resource already exists + * it is not added. + */ + public function addResource(ResourceInterface $resource) + { + $key = (string) $resource; + + if (!isset($this->resources[$key])) { + $this->resources[$key] = $resource; + } + } + + /** + * Sets an alias for an existing route. + * + * @param string $name The alias to create + * @param string $alias The route to alias + * + * @throws InvalidArgumentException if the alias is for itself + */ + public function addAlias(string $name, string $alias): Alias + { + if ($name === $alias) { + throw new InvalidArgumentException(sprintf('Route alias "%s" can not reference itself.', $name)); + } + + unset($this->routes[$name], $this->priorities[$name]); + + return $this->aliases[$name] = new Alias($alias); + } + + /** + * @return array + */ + public function getAliases(): array + { + return $this->aliases; + } + + public function getAlias(string $name): ?Alias + { + return $this->aliases[$name] ?? null; + } + + public function getPriority(string $name): ?int + { + return $this->priorities[$name] ?? null; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/RouteCollectionBuilder.php b/php/libraries/composer/vendor/symfony/routing/RouteCollectionBuilder.php new file mode 100644 index 0000000..04a4439 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RouteCollectionBuilder.php @@ -0,0 +1,364 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +use Symfony\Component\Config\Exception\LoaderLoadException; +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\Config\Resource\ResourceInterface; +use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; + +trigger_deprecation('symfony/routing', '5.1', 'The "%s" class is deprecated, use "%s" instead.', RouteCollectionBuilder::class, RoutingConfigurator::class); + +/** + * Helps add and import routes into a RouteCollection. + * + * @author Ryan Weaver + * + * @deprecated since Symfony 5.1, use RoutingConfigurator instead + */ +class RouteCollectionBuilder +{ + /** + * @var Route[]|RouteCollectionBuilder[] + */ + private $routes = []; + + private $loader; + private $defaults = []; + private $prefix; + private $host; + private $condition; + private $requirements = []; + private $options = []; + private $schemes; + private $methods; + private $resources = []; + + public function __construct(?LoaderInterface $loader = null) + { + $this->loader = $loader; + } + + /** + * Import an external routing resource and returns the RouteCollectionBuilder. + * + * $routes->import('blog.yml', '/blog'); + * + * @param mixed $resource + * + * @return self + * + * @throws LoaderLoadException + */ + public function import($resource, string $prefix = '/', ?string $type = null) + { + /** @var RouteCollection[] $collections */ + $collections = $this->load($resource, $type); + + // create a builder from the RouteCollection + $builder = $this->createBuilder(); + + foreach ($collections as $collection) { + if (null === $collection) { + continue; + } + + foreach ($collection->all() as $name => $route) { + $builder->addRoute($route, $name); + } + + foreach ($collection->getResources() as $resource) { + $builder->addResource($resource); + } + } + + // mount into this builder + $this->mount($prefix, $builder); + + return $builder; + } + + /** + * Adds a route and returns it for future modification. + * + * @return Route + */ + public function add(string $path, string $controller, ?string $name = null) + { + $route = new Route($path); + $route->setDefault('_controller', $controller); + $this->addRoute($route, $name); + + return $route; + } + + /** + * Returns a RouteCollectionBuilder that can be configured and then added with mount(). + * + * @return self + */ + public function createBuilder() + { + return new self($this->loader); + } + + /** + * Add a RouteCollectionBuilder. + */ + public function mount(string $prefix, self $builder) + { + $builder->prefix = trim(trim($prefix), '/'); + $this->routes[] = $builder; + } + + /** + * Adds a Route object to the builder. + * + * @return $this + */ + public function addRoute(Route $route, ?string $name = null) + { + if (null === $name) { + // used as a flag to know which routes will need a name later + $name = '_unnamed_route_'.spl_object_hash($route); + } + + $this->routes[$name] = $route; + + return $this; + } + + /** + * Sets the host on all embedded routes (unless already set). + * + * @return $this + */ + public function setHost(?string $pattern) + { + $this->host = $pattern; + + return $this; + } + + /** + * Sets a condition on all embedded routes (unless already set). + * + * @return $this + */ + public function setCondition(?string $condition) + { + $this->condition = $condition; + + return $this; + } + + /** + * Sets a default value that will be added to all embedded routes (unless that + * default value is already set). + * + * @param mixed $value + * + * @return $this + */ + public function setDefault(string $key, $value) + { + $this->defaults[$key] = $value; + + return $this; + } + + /** + * Sets a requirement that will be added to all embedded routes (unless that + * requirement is already set). + * + * @param mixed $regex + * + * @return $this + */ + public function setRequirement(string $key, $regex) + { + $this->requirements[$key] = $regex; + + return $this; + } + + /** + * Sets an option that will be added to all embedded routes (unless that + * option is already set). + * + * @param mixed $value + * + * @return $this + */ + public function setOption(string $key, $value) + { + $this->options[$key] = $value; + + return $this; + } + + /** + * Sets the schemes on all embedded routes (unless already set). + * + * @param array|string $schemes + * + * @return $this + */ + public function setSchemes($schemes) + { + $this->schemes = $schemes; + + return $this; + } + + /** + * Sets the methods on all embedded routes (unless already set). + * + * @param array|string $methods + * + * @return $this + */ + public function setMethods($methods) + { + $this->methods = $methods; + + return $this; + } + + /** + * Adds a resource for this collection. + * + * @return $this + */ + private function addResource(ResourceInterface $resource): self + { + $this->resources[] = $resource; + + return $this; + } + + /** + * Creates the final RouteCollection and returns it. + * + * @return RouteCollection + */ + public function build() + { + $routeCollection = new RouteCollection(); + + foreach ($this->routes as $name => $route) { + if ($route instanceof Route) { + $route->setDefaults(array_merge($this->defaults, $route->getDefaults())); + $route->setOptions(array_merge($this->options, $route->getOptions())); + + foreach ($this->requirements as $key => $val) { + if (!$route->hasRequirement($key)) { + $route->setRequirement($key, $val); + } + } + + if (null !== $this->prefix) { + $route->setPath('/'.$this->prefix.$route->getPath()); + } + + if (!$route->getHost()) { + $route->setHost($this->host); + } + + if (!$route->getCondition()) { + $route->setCondition($this->condition); + } + + if (!$route->getSchemes()) { + $route->setSchemes($this->schemes); + } + + if (!$route->getMethods()) { + $route->setMethods($this->methods); + } + + // auto-generate the route name if it's been marked + if ('_unnamed_route_' === substr($name, 0, 15)) { + $name = $this->generateRouteName($route); + } + + $routeCollection->add($name, $route); + } else { + /* @var self $route */ + $subCollection = $route->build(); + if (null !== $this->prefix) { + $subCollection->addPrefix($this->prefix); + } + + $routeCollection->addCollection($subCollection); + } + } + + foreach ($this->resources as $resource) { + $routeCollection->addResource($resource); + } + + return $routeCollection; + } + + /** + * Generates a route name based on details of this route. + */ + private function generateRouteName(Route $route): string + { + $methods = implode('_', $route->getMethods()).'_'; + + $routeName = $methods.$route->getPath(); + $routeName = str_replace(['/', ':', '|', '-'], '_', $routeName); + $routeName = preg_replace('/[^a-z0-9A-Z_.]+/', '', $routeName); + + // Collapse consecutive underscores down into a single underscore. + $routeName = preg_replace('/_+/', '_', $routeName); + + return $routeName; + } + + /** + * Finds a loader able to load an imported resource and loads it. + * + * @param mixed $resource A resource + * @param string|null $type The resource type or null if unknown + * + * @return RouteCollection[] + * + * @throws LoaderLoadException If no loader is found + */ + private function load($resource, ?string $type = null): array + { + if (null === $this->loader) { + throw new \BadMethodCallException('Cannot import other routing resources: you must pass a LoaderInterface when constructing RouteCollectionBuilder.'); + } + + if ($this->loader->supports($resource, $type)) { + $collections = $this->loader->load($resource, $type); + + return \is_array($collections) ? $collections : [$collections]; + } + + if (null === $resolver = $this->loader->getResolver()) { + throw new LoaderLoadException($resource, null, 0, null, $type); + } + + if (false === $loader = $resolver->resolve($resource, $type)) { + throw new LoaderLoadException($resource, null, 0, null, $type); + } + + $collections = $loader->load($resource, $type); + + return \is_array($collections) ? $collections : [$collections]; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/RouteCompiler.php b/php/libraries/composer/vendor/symfony/routing/RouteCompiler.php new file mode 100644 index 0000000..7e78c29 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RouteCompiler.php @@ -0,0 +1,346 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +/** + * RouteCompiler compiles Route instances to CompiledRoute instances. + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class RouteCompiler implements RouteCompilerInterface +{ + /** + * @deprecated since Symfony 5.1, to be removed in 6.0 + */ + public const REGEX_DELIMITER = '#'; + + /** + * This string defines the characters that are automatically considered separators in front of + * optional placeholders (with default and no static text following). Such a single separator + * can be left out together with the optional placeholder from matching and generating URLs. + */ + public const SEPARATORS = '/,;.:-_~+*=@|'; + + /** + * The maximum supported length of a PCRE subpattern name + * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16. + * + * @internal + */ + public const VARIABLE_MAXIMUM_LENGTH = 32; + + /** + * {@inheritdoc} + * + * @throws \InvalidArgumentException if a path variable is named _fragment + * @throws \LogicException if a variable is referenced more than once + * @throws \DomainException if a variable name starts with a digit or if it is too long to be successfully used as + * a PCRE subpattern + */ + public static function compile(Route $route) + { + $hostVariables = []; + $variables = []; + $hostRegex = null; + $hostTokens = []; + + if ('' !== $host = $route->getHost()) { + $result = self::compilePattern($route, $host, true); + + $hostVariables = $result['variables']; + $variables = $hostVariables; + + $hostTokens = $result['tokens']; + $hostRegex = $result['regex']; + } + + $locale = $route->getDefault('_locale'); + if (null !== $locale && null !== $route->getDefault('_canonical_route') && preg_quote($locale) === $route->getRequirement('_locale')) { + $requirements = $route->getRequirements(); + unset($requirements['_locale']); + $route->setRequirements($requirements); + $route->setPath(str_replace('{_locale}', $locale, $route->getPath())); + } + + $path = $route->getPath(); + + $result = self::compilePattern($route, $path, false); + + $staticPrefix = $result['staticPrefix']; + + $pathVariables = $result['variables']; + + foreach ($pathVariables as $pathParam) { + if ('_fragment' === $pathParam) { + throw new \InvalidArgumentException(sprintf('Route pattern "%s" cannot contain "_fragment" as a path parameter.', $route->getPath())); + } + } + + $variables = array_merge($variables, $pathVariables); + + $tokens = $result['tokens']; + $regex = $result['regex']; + + return new CompiledRoute( + $staticPrefix, + $regex, + $tokens, + $pathVariables, + $hostRegex, + $hostTokens, + $hostVariables, + array_unique($variables) + ); + } + + private static function compilePattern(Route $route, string $pattern, bool $isHost): array + { + $tokens = []; + $variables = []; + $matches = []; + $pos = 0; + $defaultSeparator = $isHost ? '.' : '/'; + $useUtf8 = preg_match('//u', $pattern); + $needsUtf8 = $route->getOption('utf8'); + + if (!$needsUtf8 && $useUtf8 && preg_match('/[\x80-\xFF]/', $pattern)) { + throw new \LogicException(sprintf('Cannot use UTF-8 route patterns without setting the "utf8" option for route "%s".', $route->getPath())); + } + if (!$useUtf8 && $needsUtf8) { + throw new \LogicException(sprintf('Cannot mix UTF-8 requirements with non-UTF-8 pattern "%s".', $pattern)); + } + + // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable + // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself. + preg_match_all('#\{(!)?(\w+)\}#', $pattern, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER); + foreach ($matches as $match) { + $important = $match[1][1] >= 0; + $varName = $match[2][0]; + // get all static text preceding the current variable + $precedingText = substr($pattern, $pos, $match[0][1] - $pos); + $pos = $match[0][1] + \strlen($match[0][0]); + + if (!\strlen($precedingText)) { + $precedingChar = ''; + } elseif ($useUtf8) { + preg_match('/.$/u', $precedingText, $precedingChar); + $precedingChar = $precedingChar[0]; + } else { + $precedingChar = substr($precedingText, -1); + } + $isSeparator = '' !== $precedingChar && str_contains(static::SEPARATORS, $precedingChar); + + // A PCRE subpattern name must start with a non-digit. Also a PHP variable cannot start with a digit so the + // variable would not be usable as a Controller action argument. + if (preg_match('/^\d/', $varName)) { + throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.', $varName, $pattern)); + } + if (\in_array($varName, $variables)) { + throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName)); + } + + if (\strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) { + throw new \DomainException(sprintf('Variable name "%s" cannot be longer than %d characters in route pattern "%s". Please use a shorter name.', $varName, self::VARIABLE_MAXIMUM_LENGTH, $pattern)); + } + + if ($isSeparator && $precedingText !== $precedingChar) { + $tokens[] = ['text', substr($precedingText, 0, -\strlen($precedingChar))]; + } elseif (!$isSeparator && '' !== $precedingText) { + $tokens[] = ['text', $precedingText]; + } + + $regexp = $route->getRequirement($varName); + if (null === $regexp) { + $followingPattern = (string) substr($pattern, $pos); + // Find the next static character after the variable that functions as a separator. By default, this separator and '/' + // are disallowed for the variable. This default requirement makes sure that optional variables can be matched at all + // and that the generating-matching-combination of URLs unambiguous, i.e. the params used for generating the URL are + // the same that will be matched. Example: new Route('/{page}.{_format}', ['_format' => 'html']) + // If {page} would also match the separating dot, {_format} would never match as {page} will eagerly consume everything. + // Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally + // part of {_format} when generating the URL, e.g. _format = 'mobile.html'. + $nextSeparator = self::findNextSeparator($followingPattern, $useUtf8); + $regexp = sprintf( + '[^%s%s]+', + preg_quote($defaultSeparator), + $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator) : '' + ); + if (('' !== $nextSeparator && !preg_match('#^\{\w+\}#', $followingPattern)) || '' === $followingPattern) { + // When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive + // quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns. + // Given the above example, there is no point in backtracking into {page} (that forbids the dot) when a dot must follow + // after it. This optimization cannot be applied when the next char is no real separator or when the next variable is + // directly adjacent, e.g. '/{x}{y}'. + $regexp .= '+'; + } + } else { + if (!preg_match('//u', $regexp)) { + $useUtf8 = false; + } elseif (!$needsUtf8 && preg_match('/[\x80-\xFF]|(?= 0; --$i) { + $token = $tokens[$i]; + // variable is optional when it is not important and has a default value + if ('variable' === $token[0] && !($token[5] ?? false) && $route->hasDefault($token[3])) { + $firstOptional = $i; + } else { + break; + } + } + } + + // compute the matching regexp + $regexp = ''; + for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) { + $regexp .= self::computeRegexp($tokens, $i, $firstOptional); + } + $regexp = '{^'.$regexp.'$}sD'.($isHost ? 'i' : ''); + + // enable Utf8 matching if really required + if ($needsUtf8) { + $regexp .= 'u'; + for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) { + if ('variable' === $tokens[$i][0]) { + $tokens[$i][4] = true; + } + } + } + + return [ + 'staticPrefix' => self::determineStaticPrefix($route, $tokens), + 'regex' => $regexp, + 'tokens' => array_reverse($tokens), + 'variables' => $variables, + ]; + } + + /** + * Determines the longest static prefix possible for a route. + */ + private static function determineStaticPrefix(Route $route, array $tokens): string + { + if ('text' !== $tokens[0][0]) { + return ($route->hasDefault($tokens[0][3]) || '/' === $tokens[0][1]) ? '' : $tokens[0][1]; + } + + $prefix = $tokens[0][1]; + + if (isset($tokens[1][1]) && '/' !== $tokens[1][1] && false === $route->hasDefault($tokens[1][3])) { + $prefix .= $tokens[1][1]; + } + + return $prefix; + } + + /** + * Returns the next static character in the Route pattern that will serve as a separator (or the empty string when none available). + */ + private static function findNextSeparator(string $pattern, bool $useUtf8): string + { + if ('' == $pattern) { + // return empty string if pattern is empty or false (false which can be returned by substr) + return ''; + } + // first remove all placeholders from the pattern so we can find the next real static character + if ('' === $pattern = preg_replace('#\{\w+\}#', '', $pattern)) { + return ''; + } + if ($useUtf8) { + preg_match('/^./u', $pattern, $pattern); + } + + return str_contains(static::SEPARATORS, $pattern[0]) ? $pattern[0] : ''; + } + + /** + * Computes the regexp used to match a specific token. It can be static text or a subpattern. + * + * @param array $tokens The route tokens + * @param int $index The index of the current token + * @param int $firstOptional The index of the first optional token + */ + private static function computeRegexp(array $tokens, int $index, int $firstOptional): string + { + $token = $tokens[$index]; + if ('text' === $token[0]) { + // Text tokens + return preg_quote($token[1]); + } else { + // Variable tokens + if (0 === $index && 0 === $firstOptional) { + // When the only token is an optional variable token, the separator is required + return sprintf('%s(?P<%s>%s)?', preg_quote($token[1]), $token[3], $token[2]); + } else { + $regexp = sprintf('%s(?P<%s>%s)', preg_quote($token[1]), $token[3], $token[2]); + if ($index >= $firstOptional) { + // Enclose each optional token in a subpattern to make it optional. + // "?:" means it is non-capturing, i.e. the portion of the subject string that + // matched the optional subpattern is not passed back. + $regexp = "(?:$regexp"; + $nbTokens = \count($tokens); + if ($nbTokens - 1 == $index) { + // Close the optional subpatterns + $regexp .= str_repeat(')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0)); + } + } + + return $regexp; + } + } + } + + private static function transformCapturingGroupsToNonCapturings(string $regexp): string + { + for ($i = 0; $i < \strlen($regexp); ++$i) { + if ('\\' === $regexp[$i]) { + ++$i; + continue; + } + if ('(' !== $regexp[$i] || !isset($regexp[$i + 2])) { + continue; + } + if ('*' === $regexp[++$i] || '?' === $regexp[$i]) { + ++$i; + continue; + } + $regexp = substr_replace($regexp, '?:', $i, 0); + ++$i; + } + + return $regexp; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/RouteCompilerInterface.php b/php/libraries/composer/vendor/symfony/routing/RouteCompilerInterface.php new file mode 100644 index 0000000..9bae33a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RouteCompilerInterface.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\Routing; + +/** + * RouteCompilerInterface is the interface that all RouteCompiler classes must implement. + * + * @author Fabien Potencier + */ +interface RouteCompilerInterface +{ + /** + * Compiles the current route instance. + * + * @return CompiledRoute + * + * @throws \LogicException If the Route cannot be compiled because the + * path or host pattern is invalid + */ + public static function compile(Route $route); +} diff --git a/php/libraries/composer/vendor/symfony/routing/Router.php b/php/libraries/composer/vendor/symfony/routing/Router.php new file mode 100644 index 0000000..48ec101 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/Router.php @@ -0,0 +1,391 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Config\ConfigCacheFactory; +use Symfony\Component\Config\ConfigCacheFactoryInterface; +use Symfony\Component\Config\ConfigCacheInterface; +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Generator\CompiledUrlGenerator; +use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface; +use Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper; +use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Routing\Matcher\CompiledUrlMatcher; +use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper; +use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface; +use Symfony\Component\Routing\Matcher\RequestMatcherInterface; +use Symfony\Component\Routing\Matcher\UrlMatcherInterface; + +/** + * The Router class is an example of the integration of all pieces of the + * routing system for easier use. + * + * @author Fabien Potencier + */ +class Router implements RouterInterface, RequestMatcherInterface +{ + /** + * @var UrlMatcherInterface|null + */ + protected $matcher; + + /** + * @var UrlGeneratorInterface|null + */ + protected $generator; + + /** + * @var RequestContext + */ + protected $context; + + /** + * @var LoaderInterface + */ + protected $loader; + + /** + * @var RouteCollection|null + */ + protected $collection; + + /** + * @var mixed + */ + protected $resource; + + /** + * @var array + */ + protected $options = []; + + /** + * @var LoggerInterface|null + */ + protected $logger; + + /** + * @var string|null + */ + protected $defaultLocale; + + /** + * @var ConfigCacheFactoryInterface|null + */ + private $configCacheFactory; + + /** + * @var ExpressionFunctionProviderInterface[] + */ + private $expressionLanguageProviders = []; + + private static $cache = []; + + /** + * @param mixed $resource The main resource to load + */ + public function __construct(LoaderInterface $loader, $resource, array $options = [], ?RequestContext $context = null, ?LoggerInterface $logger = null, ?string $defaultLocale = null) + { + $this->loader = $loader; + $this->resource = $resource; + $this->logger = $logger; + $this->context = $context ?? new RequestContext(); + $this->setOptions($options); + $this->defaultLocale = $defaultLocale; + } + + /** + * Sets options. + * + * Available options: + * + * * cache_dir: The cache directory (or null to disable caching) + * * debug: Whether to enable debugging or not (false by default) + * * generator_class: The name of a UrlGeneratorInterface implementation + * * generator_dumper_class: The name of a GeneratorDumperInterface implementation + * * matcher_class: The name of a UrlMatcherInterface implementation + * * matcher_dumper_class: The name of a MatcherDumperInterface implementation + * * resource_type: Type hint for the main resource (optional) + * * strict_requirements: Configure strict requirement checking for generators + * implementing ConfigurableRequirementsInterface (default is true) + * + * @throws \InvalidArgumentException When unsupported option is provided + */ + public function setOptions(array $options) + { + $this->options = [ + 'cache_dir' => null, + 'debug' => false, + 'generator_class' => CompiledUrlGenerator::class, + 'generator_dumper_class' => CompiledUrlGeneratorDumper::class, + 'matcher_class' => CompiledUrlMatcher::class, + 'matcher_dumper_class' => CompiledUrlMatcherDumper::class, + 'resource_type' => null, + 'strict_requirements' => true, + ]; + + // check option names and live merge, if errors are encountered Exception will be thrown + $invalid = []; + foreach ($options as $key => $value) { + if (\array_key_exists($key, $this->options)) { + $this->options[$key] = $value; + } else { + $invalid[] = $key; + } + } + + if ($invalid) { + throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid))); + } + } + + /** + * Sets an option. + * + * @param mixed $value The value + * + * @throws \InvalidArgumentException + */ + public function setOption(string $key, $value) + { + if (!\array_key_exists($key, $this->options)) { + throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key)); + } + + $this->options[$key] = $value; + } + + /** + * Gets an option value. + * + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function getOption(string $key) + { + if (!\array_key_exists($key, $this->options)) { + throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key)); + } + + return $this->options[$key]; + } + + /** + * {@inheritdoc} + */ + public function getRouteCollection() + { + if (null === $this->collection) { + $this->collection = $this->loader->load($this->resource, $this->options['resource_type']); + } + + return $this->collection; + } + + /** + * {@inheritdoc} + */ + public function setContext(RequestContext $context) + { + $this->context = $context; + + if (null !== $this->matcher) { + $this->getMatcher()->setContext($context); + } + if (null !== $this->generator) { + $this->getGenerator()->setContext($context); + } + } + + /** + * {@inheritdoc} + */ + public function getContext() + { + return $this->context; + } + + /** + * Sets the ConfigCache factory to use. + */ + public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory) + { + $this->configCacheFactory = $configCacheFactory; + } + + /** + * {@inheritdoc} + */ + public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH) + { + return $this->getGenerator()->generate($name, $parameters, $referenceType); + } + + /** + * {@inheritdoc} + */ + public function match(string $pathinfo) + { + return $this->getMatcher()->match($pathinfo); + } + + /** + * {@inheritdoc} + */ + public function matchRequest(Request $request) + { + $matcher = $this->getMatcher(); + if (!$matcher instanceof RequestMatcherInterface) { + // fallback to the default UrlMatcherInterface + return $matcher->match($request->getPathInfo()); + } + + return $matcher->matchRequest($request); + } + + /** + * Gets the UrlMatcher or RequestMatcher instance associated with this Router. + * + * @return UrlMatcherInterface|RequestMatcherInterface + */ + public function getMatcher() + { + if (null !== $this->matcher) { + return $this->matcher; + } + + if (null === $this->options['cache_dir']) { + $routes = $this->getRouteCollection(); + $compiled = is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true); + if ($compiled) { + $routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes(); + } + $this->matcher = new $this->options['matcher_class']($routes, $this->context); + if (method_exists($this->matcher, 'addExpressionLanguageProvider')) { + foreach ($this->expressionLanguageProviders as $provider) { + $this->matcher->addExpressionLanguageProvider($provider); + } + } + + return $this->matcher; + } + + $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_matching_routes.php', + function (ConfigCacheInterface $cache) { + $dumper = $this->getMatcherDumperInstance(); + if (method_exists($dumper, 'addExpressionLanguageProvider')) { + foreach ($this->expressionLanguageProviders as $provider) { + $dumper->addExpressionLanguageProvider($provider); + } + } + + $cache->write($dumper->dump(), $this->getRouteCollection()->getResources()); + } + ); + + return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context); + } + + /** + * Gets the UrlGenerator instance associated with this Router. + * + * @return UrlGeneratorInterface + */ + public function getGenerator() + { + if (null !== $this->generator) { + return $this->generator; + } + + if (null === $this->options['cache_dir']) { + $routes = $this->getRouteCollection(); + $compiled = is_a($this->options['generator_class'], CompiledUrlGenerator::class, true); + if ($compiled) { + $generatorDumper = new CompiledUrlGeneratorDumper($routes); + $routes = array_merge($generatorDumper->getCompiledRoutes(), $generatorDumper->getCompiledAliases()); + } + $this->generator = new $this->options['generator_class']($routes, $this->context, $this->logger, $this->defaultLocale); + } else { + $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_generating_routes.php', + function (ConfigCacheInterface $cache) { + $dumper = $this->getGeneratorDumperInstance(); + + $cache->write($dumper->dump(), $this->getRouteCollection()->getResources()); + } + ); + + $this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale); + } + + if ($this->generator instanceof ConfigurableRequirementsInterface) { + $this->generator->setStrictRequirements($this->options['strict_requirements']); + } + + return $this->generator; + } + + public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) + { + $this->expressionLanguageProviders[] = $provider; + } + + /** + * @return GeneratorDumperInterface + */ + protected function getGeneratorDumperInstance() + { + return new $this->options['generator_dumper_class']($this->getRouteCollection()); + } + + /** + * @return MatcherDumperInterface + */ + protected function getMatcherDumperInstance() + { + return new $this->options['matcher_dumper_class']($this->getRouteCollection()); + } + + /** + * Provides the ConfigCache factory implementation, falling back to a + * default implementation if necessary. + */ + private function getConfigCacheFactory(): ConfigCacheFactoryInterface + { + if (null === $this->configCacheFactory) { + $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']); + } + + return $this->configCacheFactory; + } + + private static function getCompiledRoutes(string $path): array + { + if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) { + self::$cache = null; + } + + if (null === self::$cache) { + return require $path; + } + + if (isset(self::$cache[$path])) { + return self::$cache[$path]; + } + + return self::$cache[$path] = require $path; + } +} diff --git a/php/libraries/composer/vendor/symfony/routing/RouterInterface.php b/php/libraries/composer/vendor/symfony/routing/RouterInterface.php new file mode 100644 index 0000000..6912f8a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/RouterInterface.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Routing\Matcher\UrlMatcherInterface; + +/** + * RouterInterface is the interface that all Router classes must implement. + * + * This interface is the concatenation of UrlMatcherInterface and UrlGeneratorInterface. + * + * @author Fabien Potencier + */ +interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface +{ + /** + * Gets the RouteCollection instance associated with this Router. + * + * WARNING: This method should never be used at runtime as it is SLOW. + * You might use it in a cache warmer though. + * + * @return RouteCollection + */ + public function getRouteCollection(); +} diff --git a/php/libraries/composer/vendor/symfony/routing/composer.json b/php/libraries/composer/vendor/symfony/routing/composer.json new file mode 100644 index 0000000..c32219e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/routing/composer.json @@ -0,0 +1,51 @@ +{ + "name": "symfony/routing", + "type": "library", + "description": "Maps an HTTP request to a set of configuration variables", + "keywords": ["routing", "router", "url", "uri"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "symfony/config": "^5.3|^6.0", + "symfony/http-foundation": "^4.4|^5.0|^6.0", + "symfony/yaml": "^4.4|^5.0|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^4.4|^5.0|^6.0", + "doctrine/annotations": "^1.12|^2", + "psr/log": "^1|^2|^3" + }, + "conflict": { + "doctrine/annotations": "<1.12", + "symfony/config": "<5.3", + "symfony/dependency-injection": "<4.4", + "symfony/yaml": "<4.4" + }, + "suggest": { + "symfony/http-foundation": "For using a Symfony Request object", + "symfony/config": "For using the all-in-one router or any loader", + "symfony/yaml": "For using the YAML loader", + "symfony/expression-language": "For using expression matching" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Routing\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/Attribute/Required.php b/php/libraries/composer/vendor/symfony/service-contracts/Attribute/Required.php new file mode 100644 index 0000000..9df8511 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/Attribute/Required.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Attribute; + +/** + * A required dependency. + * + * This attribute indicates that a property holds a required dependency. The annotated property or method should be + * considered during the instantiation process of the containing class. + * + * @author Alexander M. Turek + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY)] +final class Required +{ +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/Attribute/SubscribedService.php b/php/libraries/composer/vendor/symfony/service-contracts/Attribute/SubscribedService.php new file mode 100644 index 0000000..d98e1df --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/Attribute/SubscribedService.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Attribute; + +use Symfony\Contracts\Service\ServiceSubscriberInterface; +use Symfony\Contracts\Service\ServiceSubscriberTrait; + +/** + * For use as the return value for {@see ServiceSubscriberInterface}. + * + * @example new SubscribedService('http_client', HttpClientInterface::class, false, new Target('githubApi')) + * + * Use with {@see ServiceSubscriberTrait} to mark a method's return type + * as a subscribed service. + * + * @author Kevin Bond + */ +#[\Attribute(\Attribute::TARGET_METHOD)] +final class SubscribedService +{ + /** @var object[] */ + public array $attributes; + + /** + * @param string|null $key The key to use for the service + * @param class-string|null $type The service class + * @param bool $nullable Whether the service is optional + * @param object|object[] $attributes One or more dependency injection attributes to use + */ + public function __construct( + public ?string $key = null, + public ?string $type = null, + public bool $nullable = false, + array|object $attributes = [], + ) { + $this->attributes = \is_array($attributes) ? $attributes : [$attributes]; + } +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/CHANGELOG.md b/php/libraries/composer/vendor/symfony/service-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/php/libraries/composer/vendor/symfony/service-contracts/LICENSE b/php/libraries/composer/vendor/symfony/service-contracts/LICENSE new file mode 100644 index 0000000..7536cae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/service-contracts/README.md b/php/libraries/composer/vendor/symfony/service-contracts/README.md new file mode 100644 index 0000000..42841a5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/README.md @@ -0,0 +1,9 @@ +Symfony Service Contracts +========================= + +A set of abstractions extracted out of the Symfony components. + +Can be used to build on semantics that the Symfony components proved useful and +that already have battle tested implementations. + +See https://github.com/symfony/contracts/blob/main/README.md for more information. diff --git a/php/libraries/composer/vendor/symfony/service-contracts/ResetInterface.php b/php/libraries/composer/vendor/symfony/service-contracts/ResetInterface.php new file mode 100644 index 0000000..a4f389b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/ResetInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +/** + * Provides a way to reset an object to its initial state. + * + * When calling the "reset()" method on an object, it should be put back to its + * initial state. This usually means clearing any internal buffers and forwarding + * the call to internal dependencies. All properties of the object should be put + * back to the same state it had when it was first ready to use. + * + * This method could be called, for example, to recycle objects that are used as + * services, so that they can be used to handle several requests in the same + * process loop (note that we advise making your services stateless instead of + * implementing this interface when possible.) + */ +interface ResetInterface +{ + /** + * @return void + */ + public function reset(); +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/ServiceLocatorTrait.php b/php/libraries/composer/vendor/symfony/service-contracts/ServiceLocatorTrait.php new file mode 100644 index 0000000..b62ec3e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/ServiceLocatorTrait.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(ContainerExceptionInterface::class); +class_exists(NotFoundExceptionInterface::class); + +/** + * A trait to help implement ServiceProviderInterface. + * + * @author Robin Chalas + * @author Nicolas Grekas + */ +trait ServiceLocatorTrait +{ + private array $factories; + private array $loading = []; + private array $providedTypes; + + /** + * @param array $factories + */ + public function __construct(array $factories) + { + $this->factories = $factories; + } + + public function has(string $id): bool + { + return isset($this->factories[$id]); + } + + public function get(string $id): mixed + { + if (!isset($this->factories[$id])) { + throw $this->createNotFoundException($id); + } + + if (isset($this->loading[$id])) { + $ids = array_values($this->loading); + $ids = \array_slice($this->loading, array_search($id, $ids)); + $ids[] = $id; + + throw $this->createCircularReferenceException($id, $ids); + } + + $this->loading[$id] = $id; + try { + return $this->factories[$id]($this); + } finally { + unset($this->loading[$id]); + } + } + + public function getProvidedServices(): array + { + if (!isset($this->providedTypes)) { + $this->providedTypes = []; + + foreach ($this->factories as $name => $factory) { + if (!\is_callable($factory)) { + $this->providedTypes[$name] = '?'; + } else { + $type = (new \ReflectionFunction($factory))->getReturnType(); + + $this->providedTypes[$name] = $type ? ($type->allowsNull() ? '?' : '').($type instanceof \ReflectionNamedType ? $type->getName() : $type) : '?'; + } + } + } + + return $this->providedTypes; + } + + private function createNotFoundException(string $id): NotFoundExceptionInterface + { + if (!$alternatives = array_keys($this->factories)) { + $message = 'is empty...'; + } else { + $last = array_pop($alternatives); + if ($alternatives) { + $message = sprintf('only knows about the "%s" and "%s" services.', implode('", "', $alternatives), $last); + } else { + $message = sprintf('only knows about the "%s" service.', $last); + } + } + + if ($this->loading) { + $message = sprintf('The service "%s" has a dependency on a non-existent service "%s". This locator %s', end($this->loading), $id, $message); + } else { + $message = sprintf('Service "%s" not found: the current service locator %s', $id, $message); + } + + return new class($message) extends \InvalidArgumentException implements NotFoundExceptionInterface { + }; + } + + private function createCircularReferenceException(string $id, array $path): ContainerExceptionInterface + { + return new class(sprintf('Circular reference detected for service "%s", path: "%s".', $id, implode(' -> ', $path))) extends \RuntimeException implements ContainerExceptionInterface { + }; + } +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/ServiceProviderInterface.php b/php/libraries/composer/vendor/symfony/service-contracts/ServiceProviderInterface.php new file mode 100644 index 0000000..2e71f00 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/ServiceProviderInterface.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Psr\Container\ContainerInterface; + +/** + * A ServiceProviderInterface exposes the identifiers and the types of services provided by a container. + * + * @author Nicolas Grekas + * @author Mateusz Sip + * + * @template-covariant T of mixed + */ +interface ServiceProviderInterface extends ContainerInterface +{ + /** + * @return T + */ + public function get(string $id): mixed; + + public function has(string $id): bool; + + /** + * Returns an associative array of service types keyed by the identifiers provided by the current container. + * + * Examples: + * + * * ['logger' => 'Psr\Log\LoggerInterface'] means the object provides a service named "logger" that implements Psr\Log\LoggerInterface + * * ['foo' => '?'] means the container provides service name "foo" of unspecified type + * * ['bar' => '?Bar\Baz'] means the container provides a service "bar" of type Bar\Baz|null + * + * @return array The provided service types, keyed by service names + */ + public function getProvidedServices(): array; +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/ServiceSubscriberInterface.php b/php/libraries/composer/vendor/symfony/service-contracts/ServiceSubscriberInterface.php new file mode 100644 index 0000000..3da1916 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/ServiceSubscriberInterface.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Symfony\Contracts\Service\Attribute\SubscribedService; + +/** + * A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method. + * + * The getSubscribedServices method returns an array of service types required by such instances, + * optionally keyed by the service names used internally. Service types that start with an interrogation + * mark "?" are optional, while the other ones are mandatory service dependencies. + * + * The injected service locators SHOULD NOT allow access to any other services not specified by the method. + * + * It is expected that ServiceSubscriber instances consume PSR-11-based service locators internally. + * This interface does not dictate any injection method for these service locators, although constructor + * injection is recommended. + * + * @author Nicolas Grekas + */ +interface ServiceSubscriberInterface +{ + /** + * Returns an array of service types (or {@see SubscribedService} objects) required + * by such instances, optionally keyed by the service names used internally. + * + * For mandatory dependencies: + * + * * ['logger' => 'Psr\Log\LoggerInterface'] means the objects use the "logger" name + * internally to fetch a service which must implement Psr\Log\LoggerInterface. + * * ['loggers' => 'Psr\Log\LoggerInterface[]'] means the objects use the "loggers" name + * internally to fetch an iterable of Psr\Log\LoggerInterface instances. + * * ['Psr\Log\LoggerInterface'] is a shortcut for + * * ['Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface'] + * + * otherwise: + * + * * ['logger' => '?Psr\Log\LoggerInterface'] denotes an optional dependency + * * ['loggers' => '?Psr\Log\LoggerInterface[]'] denotes an optional iterable dependency + * * ['?Psr\Log\LoggerInterface'] is a shortcut for + * * ['Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface'] + * + * additionally, an array of {@see SubscribedService}'s can be returned: + * + * * [new SubscribedService('logger', Psr\Log\LoggerInterface::class)] + * * [new SubscribedService(type: Psr\Log\LoggerInterface::class, nullable: true)] + * * [new SubscribedService('http_client', HttpClientInterface::class, attributes: new Target('githubApi'))] + * + * @return string[]|SubscribedService[] The required service types, optionally keyed by service names + */ + public static function getSubscribedServices(): array; +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/ServiceSubscriberTrait.php b/php/libraries/composer/vendor/symfony/service-contracts/ServiceSubscriberTrait.php new file mode 100644 index 0000000..f3b450c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/ServiceSubscriberTrait.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Psr\Container\ContainerInterface; +use Symfony\Contracts\Service\Attribute\Required; +use Symfony\Contracts\Service\Attribute\SubscribedService; + +/** + * Implementation of ServiceSubscriberInterface that determines subscribed services from + * method return types. Service ids are available as "ClassName::methodName". + * + * @author Kevin Bond + */ +trait ServiceSubscriberTrait +{ + /** @var ContainerInterface */ + protected $container; + + public static function getSubscribedServices(): array + { + $services = method_exists(get_parent_class(self::class) ?: '', __FUNCTION__) ? parent::getSubscribedServices() : []; + + foreach ((new \ReflectionClass(self::class))->getMethods() as $method) { + if (self::class !== $method->getDeclaringClass()->name) { + continue; + } + + if (!$attribute = $method->getAttributes(SubscribedService::class)[0] ?? null) { + continue; + } + + if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) { + throw new \LogicException(sprintf('Cannot use "%s" on method "%s::%s()" (can only be used on non-static, non-abstract methods with no parameters).', SubscribedService::class, self::class, $method->name)); + } + + if (!$returnType = $method->getReturnType()) { + throw new \LogicException(sprintf('Cannot use "%s" on methods without a return type in "%s::%s()".', SubscribedService::class, $method->name, self::class)); + } + + /* @var SubscribedService $attribute */ + $attribute = $attribute->newInstance(); + $attribute->key ??= self::class.'::'.$method->name; + $attribute->type ??= $returnType instanceof \ReflectionNamedType ? $returnType->getName() : (string) $returnType; + $attribute->nullable = $returnType->allowsNull(); + + if ($attribute->attributes) { + $services[] = $attribute; + } else { + $services[$attribute->key] = ($attribute->nullable ? '?' : '').$attribute->type; + } + } + + return $services; + } + + #[Required] + public function setContainer(ContainerInterface $container): ?ContainerInterface + { + $ret = null; + if (method_exists(get_parent_class(self::class) ?: '', __FUNCTION__)) { + $ret = parent::setContainer($container); + } + + $this->container = $container; + + return $ret; + } +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/Test/ServiceLocatorTest.php b/php/libraries/composer/vendor/symfony/service-contracts/Test/ServiceLocatorTest.php new file mode 100644 index 0000000..07d12b4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/Test/ServiceLocatorTest.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Test; + +class_alias(ServiceLocatorTestCase::class, ServiceLocatorTest::class); + +if (false) { + /** + * @deprecated since PHPUnit 9.6 + */ + class ServiceLocatorTest + { + } +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php b/php/libraries/composer/vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php new file mode 100644 index 0000000..65a3fe3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php @@ -0,0 +1,96 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Test; + +use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; +use Symfony\Contracts\Service\ServiceLocatorTrait; + +abstract class ServiceLocatorTestCase extends TestCase +{ + protected function getServiceLocator(array $factories): ContainerInterface + { + return new class($factories) implements ContainerInterface { + use ServiceLocatorTrait; + }; + } + + public function testHas() + { + $locator = $this->getServiceLocator([ + 'foo' => fn () => 'bar', + 'bar' => fn () => 'baz', + fn () => 'dummy', + ]); + + $this->assertTrue($locator->has('foo')); + $this->assertTrue($locator->has('bar')); + $this->assertFalse($locator->has('dummy')); + } + + public function testGet() + { + $locator = $this->getServiceLocator([ + 'foo' => fn () => 'bar', + 'bar' => fn () => 'baz', + ]); + + $this->assertSame('bar', $locator->get('foo')); + $this->assertSame('baz', $locator->get('bar')); + } + + public function testGetDoesNotMemoize() + { + $i = 0; + $locator = $this->getServiceLocator([ + 'foo' => function () use (&$i) { + ++$i; + + return 'bar'; + }, + ]); + + $this->assertSame('bar', $locator->get('foo')); + $this->assertSame('bar', $locator->get('foo')); + $this->assertSame(2, $i); + } + + public function testThrowsOnUndefinedInternalService() + { + $locator = $this->getServiceLocator([ + 'foo' => function () use (&$locator) { return $locator->get('bar'); }, + ]); + + if (!$this->getExpectedException()) { + $this->expectException(NotFoundExceptionInterface::class); + $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); + } + + $locator->get('foo'); + } + + public function testThrowsOnCircularReference() + { + $locator = $this->getServiceLocator([ + 'foo' => function () use (&$locator) { return $locator->get('bar'); }, + 'bar' => function () use (&$locator) { return $locator->get('baz'); }, + 'baz' => function () use (&$locator) { return $locator->get('bar'); }, + ]); + + $this->expectException(ContainerExceptionInterface::class); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); + + $locator->get('foo'); + } +} diff --git a/php/libraries/composer/vendor/symfony/service-contracts/composer.json b/php/libraries/composer/vendor/symfony/service-contracts/composer.json new file mode 100644 index 0000000..32bb8a3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/service-contracts/composer.json @@ -0,0 +1,41 @@ +{ + "name": "symfony/service-contracts", + "type": "library", + "description": "Generic abstractions related to writing services", + "keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "autoload": { + "psr-4": { "Symfony\\Contracts\\Service\\": "" }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/string/AbstractString.php b/php/libraries/composer/vendor/symfony/string/AbstractString.php new file mode 100644 index 0000000..f55c721 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/AbstractString.php @@ -0,0 +1,702 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; +use Symfony\Component\String\Exception\RuntimeException; + +/** + * Represents a string of abstract characters. + * + * Unicode defines 3 types of "characters" (bytes, code points and grapheme clusters). + * This class is the abstract type to use as a type-hint when the logic you want to + * implement doesn't care about the exact variant it deals with. + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +abstract class AbstractString implements \Stringable, \JsonSerializable +{ + public const PREG_PATTERN_ORDER = \PREG_PATTERN_ORDER; + public const PREG_SET_ORDER = \PREG_SET_ORDER; + public const PREG_OFFSET_CAPTURE = \PREG_OFFSET_CAPTURE; + public const PREG_UNMATCHED_AS_NULL = \PREG_UNMATCHED_AS_NULL; + + public const PREG_SPLIT = 0; + public const PREG_SPLIT_NO_EMPTY = \PREG_SPLIT_NO_EMPTY; + public const PREG_SPLIT_DELIM_CAPTURE = \PREG_SPLIT_DELIM_CAPTURE; + public const PREG_SPLIT_OFFSET_CAPTURE = \PREG_SPLIT_OFFSET_CAPTURE; + + protected $string = ''; + protected $ignoreCase = false; + + abstract public function __construct(string $string = ''); + + /** + * Unwraps instances of AbstractString back to strings. + * + * @return string[]|array + */ + public static function unwrap(array $values): array + { + foreach ($values as $k => $v) { + if ($v instanceof self) { + $values[$k] = $v->__toString(); + } elseif (\is_array($v) && $values[$k] !== $v = static::unwrap($v)) { + $values[$k] = $v; + } + } + + return $values; + } + + /** + * Wraps (and normalizes) strings in instances of AbstractString. + * + * @return static[]|array + */ + public static function wrap(array $values): array + { + $i = 0; + $keys = null; + + foreach ($values as $k => $v) { + if (\is_string($k) && '' !== $k && $k !== $j = (string) new static($k)) { + $keys ??= array_keys($values); + $keys[$i] = $j; + } + + if (\is_string($v)) { + $values[$k] = new static($v); + } elseif (\is_array($v) && $values[$k] !== $v = static::wrap($v)) { + $values[$k] = $v; + } + + ++$i; + } + + return null !== $keys ? array_combine($keys, $values) : $values; + } + + /** + * @param string|string[] $needle + */ + public function after(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = \PHP_INT_MAX; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOf($n, $offset); + + if (null !== $j && $j < $i) { + $i = $j; + $str->string = $n; + } + } + + if (\PHP_INT_MAX === $i) { + return $str; + } + + if (!$includeNeedle) { + $i += $str->length(); + } + + return $this->slice($i); + } + + /** + * @param string|string[] $needle + */ + public function afterLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = null; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOfLast($n, $offset); + + if (null !== $j && $j >= $i) { + $i = $offset = $j; + $str->string = $n; + } + } + + if (null === $i) { + return $str; + } + + if (!$includeNeedle) { + $i += $str->length(); + } + + return $this->slice($i); + } + + abstract public function append(string ...$suffix): static; + + /** + * @param string|string[] $needle + */ + public function before(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = \PHP_INT_MAX; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOf($n, $offset); + + if (null !== $j && $j < $i) { + $i = $j; + $str->string = $n; + } + } + + if (\PHP_INT_MAX === $i) { + return $str; + } + + if ($includeNeedle) { + $i += $str->length(); + } + + return $this->slice(0, $i); + } + + /** + * @param string|string[] $needle + */ + public function beforeLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = null; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOfLast($n, $offset); + + if (null !== $j && $j >= $i) { + $i = $offset = $j; + $str->string = $n; + } + } + + if (null === $i) { + return $str; + } + + if ($includeNeedle) { + $i += $str->length(); + } + + return $this->slice(0, $i); + } + + /** + * @return int[] + */ + public function bytesAt(int $offset): array + { + $str = $this->slice($offset, 1); + + return '' === $str->string ? [] : array_values(unpack('C*', $str->string)); + } + + abstract public function camel(): static; + + /** + * @return static[] + */ + abstract public function chunk(int $length = 1): array; + + public function collapseWhitespace(): static + { + $str = clone $this; + $str->string = trim(preg_replace("/(?:[ \n\r\t\x0C]{2,}+|[\n\r\t\x0C])/", ' ', $str->string), " \n\r\t\x0C"); + + return $str; + } + + /** + * @param string|string[] $needle + */ + public function containsAny(string|iterable $needle): bool + { + return null !== $this->indexOf($needle); + } + + /** + * @param string|string[] $suffix + */ + public function endsWith(string|iterable $suffix): bool + { + if (\is_string($suffix)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + foreach ($suffix as $s) { + if ($this->endsWith((string) $s)) { + return true; + } + } + + return false; + } + + public function ensureEnd(string $suffix): static + { + if (!$this->endsWith($suffix)) { + return $this->append($suffix); + } + + $suffix = preg_quote($suffix); + $regex = '{('.$suffix.')(?:'.$suffix.')++$}D'; + + return $this->replaceMatches($regex.($this->ignoreCase ? 'i' : ''), '$1'); + } + + public function ensureStart(string $prefix): static + { + $prefix = new static($prefix); + + if (!$this->startsWith($prefix)) { + return $this->prepend($prefix); + } + + $str = clone $this; + $i = $prefixLen = $prefix->length(); + + while ($this->indexOf($prefix, $i) === $i) { + $str = $str->slice($prefixLen); + $i += $prefixLen; + } + + return $str; + } + + /** + * @param string|string[] $string + */ + public function equalsTo(string|iterable $string): bool + { + if (\is_string($string)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + foreach ($string as $s) { + if ($this->equalsTo((string) $s)) { + return true; + } + } + + return false; + } + + abstract public function folded(): static; + + public function ignoreCase(): static + { + $str = clone $this; + $str->ignoreCase = true; + + return $str; + } + + /** + * @param string|string[] $needle + */ + public function indexOf(string|iterable $needle, int $offset = 0): ?int + { + if (\is_string($needle)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + $i = \PHP_INT_MAX; + + foreach ($needle as $n) { + $j = $this->indexOf((string) $n, $offset); + + if (null !== $j && $j < $i) { + $i = $j; + } + } + + return \PHP_INT_MAX === $i ? null : $i; + } + + /** + * @param string|string[] $needle + */ + public function indexOfLast(string|iterable $needle, int $offset = 0): ?int + { + if (\is_string($needle)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + $i = null; + + foreach ($needle as $n) { + $j = $this->indexOfLast((string) $n, $offset); + + if (null !== $j && $j >= $i) { + $i = $offset = $j; + } + } + + return $i; + } + + public function isEmpty(): bool + { + return '' === $this->string; + } + + abstract public function join(array $strings, ?string $lastGlue = null): static; + + public function jsonSerialize(): string + { + return $this->string; + } + + abstract public function length(): int; + + abstract public function lower(): static; + + /** + * Matches the string using a regular expression. + * + * Pass PREG_PATTERN_ORDER or PREG_SET_ORDER as $flags to get all occurrences matching the regular expression. + * + * @return array All matches in a multi-dimensional array ordered according to flags + */ + abstract public function match(string $regexp, int $flags = 0, int $offset = 0): array; + + abstract public function padBoth(int $length, string $padStr = ' '): static; + + abstract public function padEnd(int $length, string $padStr = ' '): static; + + abstract public function padStart(int $length, string $padStr = ' '): static; + + abstract public function prepend(string ...$prefix): static; + + public function repeat(int $multiplier): static + { + if (0 > $multiplier) { + throw new InvalidArgumentException(sprintf('Multiplier must be positive, %d given.', $multiplier)); + } + + $str = clone $this; + $str->string = str_repeat($str->string, $multiplier); + + return $str; + } + + abstract public function replace(string $from, string $to): static; + + abstract public function replaceMatches(string $fromRegexp, string|callable $to): static; + + abstract public function reverse(): static; + + abstract public function slice(int $start = 0, ?int $length = null): static; + + abstract public function snake(): static; + + abstract public function splice(string $replacement, int $start = 0, ?int $length = null): static; + + /** + * @return static[] + */ + public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array + { + if (null === $flags) { + throw new \TypeError('Split behavior when $flags is null must be implemented by child classes.'); + } + + if ($this->ignoreCase) { + $delimiter .= 'i'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (false === $chunks = preg_split($delimiter, $this->string, $limit, $flags)) { + throw new RuntimeException('Splitting failed with error: '.preg_last_error_msg()); + } + } finally { + restore_error_handler(); + } + + $str = clone $this; + + if (self::PREG_SPLIT_OFFSET_CAPTURE & $flags) { + foreach ($chunks as &$chunk) { + $str->string = $chunk[0]; + $chunk[0] = clone $str; + } + } else { + foreach ($chunks as &$chunk) { + $str->string = $chunk; + $chunk = clone $str; + } + } + + return $chunks; + } + + /** + * @param string|string[] $prefix + */ + public function startsWith(string|iterable $prefix): bool + { + if (\is_string($prefix)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + foreach ($prefix as $prefix) { + if ($this->startsWith((string) $prefix)) { + return true; + } + } + + return false; + } + + abstract public function title(bool $allWords = false): static; + + public function toByteString(?string $toEncoding = null): ByteString + { + $b = new ByteString(); + + $toEncoding = \in_array($toEncoding, ['utf8', 'utf-8', 'UTF8'], true) ? 'UTF-8' : $toEncoding; + + if (null === $toEncoding || $toEncoding === $fromEncoding = $this instanceof AbstractUnicodeString || preg_match('//u', $b->string) ? 'UTF-8' : 'Windows-1252') { + $b->string = $this->string; + + return $b; + } + + try { + $b->string = mb_convert_encoding($this->string, $toEncoding, 'UTF-8'); + } catch (\ValueError $e) { + if (!\function_exists('iconv')) { + throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); + } + + $b->string = iconv('UTF-8', $toEncoding, $this->string); + } + + return $b; + } + + public function toCodePointString(): CodePointString + { + return new CodePointString($this->string); + } + + public function toString(): string + { + return $this->string; + } + + public function toUnicodeString(): UnicodeString + { + return new UnicodeString($this->string); + } + + abstract public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static; + + abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static; + + /** + * @param string|string[] $prefix + */ + public function trimPrefix($prefix): static + { + if (\is_array($prefix) || $prefix instanceof \Traversable) { // don't use is_iterable(), it's slow + foreach ($prefix as $s) { + $t = $this->trimPrefix($s); + + if ($t->string !== $this->string) { + return $t; + } + } + + return clone $this; + } + + $str = clone $this; + + if ($prefix instanceof self) { + $prefix = $prefix->string; + } else { + $prefix = (string) $prefix; + } + + if ('' !== $prefix && \strlen($this->string) >= \strlen($prefix) && 0 === substr_compare($this->string, $prefix, 0, \strlen($prefix), $this->ignoreCase)) { + $str->string = substr($this->string, \strlen($prefix)); + } + + return $str; + } + + abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static; + + /** + * @param string|string[] $suffix + */ + public function trimSuffix($suffix): static + { + if (\is_array($suffix) || $suffix instanceof \Traversable) { // don't use is_iterable(), it's slow + foreach ($suffix as $s) { + $t = $this->trimSuffix($s); + + if ($t->string !== $this->string) { + return $t; + } + } + + return clone $this; + } + + $str = clone $this; + + if ($suffix instanceof self) { + $suffix = $suffix->string; + } else { + $suffix = (string) $suffix; + } + + if ('' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase)) { + $str->string = substr($this->string, 0, -\strlen($suffix)); + } + + return $str; + } + + public function truncate(int $length, string $ellipsis = '', bool $cut = true): static + { + $stringLength = $this->length(); + + if ($stringLength <= $length) { + return clone $this; + } + + $ellipsisLength = '' !== $ellipsis ? (new static($ellipsis))->length() : 0; + + if ($length < $ellipsisLength) { + $ellipsisLength = 0; + } + + if (!$cut) { + if (null === $length = $this->indexOf([' ', "\r", "\n", "\t"], ($length ?: 1) - 1)) { + return clone $this; + } + + $length += $ellipsisLength; + } + + $str = $this->slice(0, $length - $ellipsisLength); + + return $ellipsisLength ? $str->trimEnd()->append($ellipsis) : $str; + } + + abstract public function upper(): static; + + /** + * Returns the printable length on a terminal. + */ + abstract public function width(bool $ignoreAnsiDecoration = true): int; + + public function wordwrap(int $width = 75, string $break = "\n", bool $cut = false): static + { + $lines = '' !== $break ? $this->split($break) : [clone $this]; + $chars = []; + $mask = ''; + + if (1 === \count($lines) && '' === $lines[0]->string) { + return $lines[0]; + } + + foreach ($lines as $i => $line) { + if ($i) { + $chars[] = $break; + $mask .= '#'; + } + + foreach ($line->chunk() as $char) { + $chars[] = $char->string; + $mask .= ' ' === $char->string ? ' ' : '?'; + } + } + + $string = ''; + $j = 0; + $b = $i = -1; + $mask = wordwrap($mask, $width, '#', $cut); + + while (false !== $b = strpos($mask, '#', $b + 1)) { + for (++$i; $i < $b; ++$i) { + $string .= $chars[$j]; + unset($chars[$j++]); + } + + if ($break === $chars[$j] || ' ' === $chars[$j]) { + unset($chars[$j++]); + } + + $string .= $break; + } + + $str = clone $this; + $str->string = $string.implode('', $chars); + + return $str; + } + + public function __sleep(): array + { + return ['string']; + } + + public function __clone() + { + $this->ignoreCase = false; + } + + public function __toString(): string + { + return $this->string; + } +} diff --git a/php/libraries/composer/vendor/symfony/string/AbstractUnicodeString.php b/php/libraries/composer/vendor/symfony/string/AbstractUnicodeString.php new file mode 100644 index 0000000..673ad8c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/AbstractUnicodeString.php @@ -0,0 +1,590 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; +use Symfony\Component\String\Exception\RuntimeException; + +/** + * Represents a string of abstract Unicode characters. + * + * Unicode defines 3 types of "characters" (bytes, code points and grapheme clusters). + * This class is the abstract type to use as a type-hint when the logic you want to + * implement is Unicode-aware but doesn't care about code points vs grapheme clusters. + * + * @author Nicolas Grekas + * + * @throws ExceptionInterface + */ +abstract class AbstractUnicodeString extends AbstractString +{ + public const NFC = \Normalizer::NFC; + public const NFD = \Normalizer::NFD; + public const NFKC = \Normalizer::NFKC; + public const NFKD = \Normalizer::NFKD; + + // all ASCII letters sorted by typical frequency of occurrence + private const ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; + + // the subset of folded case mappings that is not in lower case mappings + private const FOLD_FROM = ['İ', 'µ', 'ſ', "\xCD\x85", 'ς', 'ϐ', 'ϑ', 'ϕ', 'ϖ', 'ϰ', 'ϱ', 'ϵ', 'ẛ', "\xE1\xBE\xBE", 'ß', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'և', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'ẚ', 'ẞ', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'ᾐ', 'ᾑ', 'ᾒ', 'ᾓ', 'ᾔ', 'ᾕ', 'ᾖ', 'ᾗ', 'ᾘ', 'ᾙ', 'ᾚ', 'ᾛ', 'ᾜ', 'ᾝ', 'ᾞ', 'ᾟ', 'ᾠ', 'ᾡ', 'ᾢ', 'ᾣ', 'ᾤ', 'ᾥ', 'ᾦ', 'ᾧ', 'ᾨ', 'ᾩ', 'ᾪ', 'ᾫ', 'ᾬ', 'ᾭ', 'ᾮ', 'ᾯ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'ᾼ', 'ῂ', 'ῃ', 'ῄ', 'ῆ', 'ῇ', 'ῌ', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ῲ', 'ῳ', 'ῴ', 'ῶ', 'ῷ', 'ῼ', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'ſt', 'st', 'ﬓ', 'ﬔ', 'ﬕ', 'ﬖ', 'ﬗ']; + private const FOLD_TO = ['i̇', 'μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', 'ṡ', 'ι', 'ss', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'եւ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'aʾ', 'ss', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὰι', 'αι', 'άι', 'ᾶ', 'ᾶι', 'αι', 'ὴι', 'ηι', 'ήι', 'ῆ', 'ῆι', 'ηι', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ὼι', 'ωι', 'ώι', 'ῶ', 'ῶι', 'ωι', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'st', 'st', 'մն', 'մե', 'մի', 'վն', 'մխ']; + + // the subset of https://github.com/unicode-org/cldr/blob/master/common/transforms/Latin-ASCII.xml that is not in NFKD + private const TRANSLIT_FROM = ['Æ', 'Ð', 'Ø', 'Þ', 'ß', 'æ', 'ð', 'ø', 'þ', 'Đ', 'đ', 'Ħ', 'ħ', 'ı', 'ĸ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'ʼn', 'Ŋ', 'ŋ', 'Œ', 'œ', 'Ŧ', 'ŧ', 'ƀ', 'Ɓ', 'Ƃ', 'ƃ', 'Ƈ', 'ƈ', 'Ɖ', 'Ɗ', 'Ƌ', 'ƌ', 'Ɛ', 'Ƒ', 'ƒ', 'Ɠ', 'ƕ', 'Ɩ', 'Ɨ', 'Ƙ', 'ƙ', 'ƚ', 'Ɲ', 'ƞ', 'Ƣ', 'ƣ', 'Ƥ', 'ƥ', 'ƫ', 'Ƭ', 'ƭ', 'Ʈ', 'Ʋ', 'Ƴ', 'ƴ', 'Ƶ', 'ƶ', 'DŽ', 'Dž', 'dž', 'Ǥ', 'ǥ', 'ȡ', 'Ȥ', 'ȥ', 'ȴ', 'ȵ', 'ȶ', 'ȷ', 'ȸ', 'ȹ', 'Ⱥ', 'Ȼ', 'ȼ', 'Ƚ', 'Ⱦ', 'ȿ', 'ɀ', 'Ƀ', 'Ʉ', 'Ɇ', 'ɇ', 'Ɉ', 'ɉ', 'Ɍ', 'ɍ', 'Ɏ', 'ɏ', 'ɓ', 'ɕ', 'ɖ', 'ɗ', 'ɛ', 'ɟ', 'ɠ', 'ɡ', 'ɢ', 'ɦ', 'ɧ', 'ɨ', 'ɪ', 'ɫ', 'ɬ', 'ɭ', 'ɱ', 'ɲ', 'ɳ', 'ɴ', 'ɶ', 'ɼ', 'ɽ', 'ɾ', 'ʀ', 'ʂ', 'ʈ', 'ʉ', 'ʋ', 'ʏ', 'ʐ', 'ʑ', 'ʙ', 'ʛ', 'ʜ', 'ʝ', 'ʟ', 'ʠ', 'ʣ', 'ʥ', 'ʦ', 'ʪ', 'ʫ', 'ᴀ', 'ᴁ', 'ᴃ', 'ᴄ', 'ᴅ', 'ᴆ', 'ᴇ', 'ᴊ', 'ᴋ', 'ᴌ', 'ᴍ', 'ᴏ', 'ᴘ', 'ᴛ', 'ᴜ', 'ᴠ', 'ᴡ', 'ᴢ', 'ᵫ', 'ᵬ', 'ᵭ', 'ᵮ', 'ᵯ', 'ᵰ', 'ᵱ', 'ᵲ', 'ᵳ', 'ᵴ', 'ᵵ', 'ᵶ', 'ᵺ', 'ᵻ', 'ᵽ', 'ᵾ', 'ᶀ', 'ᶁ', 'ᶂ', 'ᶃ', 'ᶄ', 'ᶅ', 'ᶆ', 'ᶇ', 'ᶈ', 'ᶉ', 'ᶊ', 'ᶌ', 'ᶍ', 'ᶎ', 'ᶏ', 'ᶑ', 'ᶒ', 'ᶓ', 'ᶖ', 'ᶙ', 'ẚ', 'ẜ', 'ẝ', 'ẞ', 'Ỻ', 'ỻ', 'Ỽ', 'ỽ', 'Ỿ', 'ỿ', '©', '®', '₠', '₢', '₣', '₤', '₧', '₺', '₹', 'ℌ', '℞', '㎧', '㎮', '㏆', '㏗', '㏞', '㏟', '¼', '½', '¾', '⅓', '⅔', '⅕', '⅖', '⅗', '⅘', '⅙', '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '〇', '‘', '’', '‚', '‛', '“', '”', '„', '‟', '′', '″', '〝', '〞', '«', '»', '‹', '›', '‐', '‑', '‒', '–', '—', '―', '︱', '︲', '﹘', '‖', '⁄', '⁅', '⁆', '⁎', '、', '。', '〈', '〉', '《', '》', '〔', '〕', '〘', '〙', '〚', '〛', '︑', '︒', '︹', '︺', '︽', '︾', '︿', '﹀', '﹑', '﹝', '﹞', '⦅', '⦆', '。', '、', '×', '÷', '−', '∕', '∖', '∣', '∥', '≪', '≫', '⦅', '⦆']; + private const TRANSLIT_TO = ['AE', 'D', 'O', 'TH', 'ss', 'ae', 'd', 'o', 'th', 'D', 'd', 'H', 'h', 'i', 'q', 'L', 'l', 'L', 'l', '\'n', 'N', 'n', 'OE', 'oe', 'T', 't', 'b', 'B', 'B', 'b', 'C', 'c', 'D', 'D', 'D', 'd', 'E', 'F', 'f', 'G', 'hv', 'I', 'I', 'K', 'k', 'l', 'N', 'n', 'OI', 'oi', 'P', 'p', 't', 'T', 't', 'T', 'V', 'Y', 'y', 'Z', 'z', 'DZ', 'Dz', 'dz', 'G', 'g', 'd', 'Z', 'z', 'l', 'n', 't', 'j', 'db', 'qp', 'A', 'C', 'c', 'L', 'T', 's', 'z', 'B', 'U', 'E', 'e', 'J', 'j', 'R', 'r', 'Y', 'y', 'b', 'c', 'd', 'd', 'e', 'j', 'g', 'g', 'G', 'h', 'h', 'i', 'I', 'l', 'l', 'l', 'm', 'n', 'n', 'N', 'OE', 'r', 'r', 'r', 'R', 's', 't', 'u', 'v', 'Y', 'z', 'z', 'B', 'G', 'H', 'j', 'L', 'q', 'dz', 'dz', 'ts', 'ls', 'lz', 'A', 'AE', 'B', 'C', 'D', 'D', 'E', 'J', 'K', 'L', 'M', 'O', 'P', 'T', 'U', 'V', 'W', 'Z', 'ue', 'b', 'd', 'f', 'm', 'n', 'p', 'r', 'r', 's', 't', 'z', 'th', 'I', 'p', 'U', 'b', 'd', 'f', 'g', 'k', 'l', 'm', 'n', 'p', 'r', 's', 'v', 'x', 'z', 'a', 'd', 'e', 'e', 'i', 'u', 'a', 's', 's', 'SS', 'LL', 'll', 'V', 'v', 'Y', 'y', '(C)', '(R)', 'CE', 'Cr', 'Fr.', 'L.', 'Pts', 'TL', 'Rs', 'x', 'Rx', 'm/s', 'rad/s', 'C/kg', 'pH', 'V/m', 'A/m', ' 1/4', ' 1/2', ' 3/4', ' 1/3', ' 2/3', ' 1/5', ' 2/5', ' 3/5', ' 4/5', ' 1/6', ' 5/6', ' 1/8', ' 3/8', ' 5/8', ' 7/8', ' 1/', '0', '\'', '\'', ',', '\'', '"', '"', ',,', '"', '\'', '"', '"', '"', '<<', '>>', '<', '>', '-', '-', '-', '-', '-', '-', '-', '-', '-', '||', '/', '[', ']', '*', ',', '.', '<', '>', '<<', '>>', '[', ']', '[', ']', '[', ']', ',', '.', '[', ']', '<<', '>>', '<', '>', ',', '[', ']', '((', '))', '.', ',', '*', '/', '-', '/', '\\', '|', '||', '<<', '>>', '((', '))']; + + private static array $transliterators = []; + private static array $tableZero; + private static array $tableWide; + + public static function fromCodePoints(int ...$codes): static + { + $string = ''; + + foreach ($codes as $code) { + if (0x80 > $code %= 0x200000) { + $string .= \chr($code); + } elseif (0x800 > $code) { + $string .= \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $string .= \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $string .= \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + } + + return new static($string); + } + + /** + * Generic UTF-8 to ASCII transliteration. + * + * Install the intl extension for best results. + * + * @param string[]|\Transliterator[]|\Closure[] $rules See "*-Latin" rules from Transliterator::listIDs() + */ + public function ascii(array $rules = []): self + { + $str = clone $this; + $s = $str->string; + $str->string = ''; + + array_unshift($rules, 'nfd'); + $rules[] = 'latin-ascii'; + + if (\function_exists('transliterator_transliterate')) { + $rules[] = 'any-latin/bgn'; + } + + $rules[] = 'nfkd'; + $rules[] = '[:nonspacing mark:] remove'; + + while (\strlen($s) - 1 > $i = strspn($s, self::ASCII)) { + if (0 < --$i) { + $str->string .= substr($s, 0, $i); + $s = substr($s, $i); + } + + if (!$rule = array_shift($rules)) { + $rules = []; // An empty rule interrupts the next ones + } + + if ($rule instanceof \Transliterator) { + $s = $rule->transliterate($s); + } elseif ($rule instanceof \Closure) { + $s = $rule($s); + } elseif ($rule) { + if ('nfd' === $rule = strtolower($rule)) { + normalizer_is_normalized($s, self::NFD) ?: $s = normalizer_normalize($s, self::NFD); + } elseif ('nfkd' === $rule) { + normalizer_is_normalized($s, self::NFKD) ?: $s = normalizer_normalize($s, self::NFKD); + } elseif ('[:nonspacing mark:] remove' === $rule) { + $s = preg_replace('/\p{Mn}++/u', '', $s); + } elseif ('latin-ascii' === $rule) { + $s = str_replace(self::TRANSLIT_FROM, self::TRANSLIT_TO, $s); + } elseif ('de-ascii' === $rule) { + $s = preg_replace("/([AUO])\u{0308}(?=\p{Ll})/u", '$1e', $s); + $s = str_replace(["a\u{0308}", "o\u{0308}", "u\u{0308}", "A\u{0308}", "O\u{0308}", "U\u{0308}"], ['ae', 'oe', 'ue', 'AE', 'OE', 'UE'], $s); + } elseif (\function_exists('transliterator_transliterate')) { + if (null === $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule)) { + if ('any-latin/bgn' === $rule) { + $rule = 'any-latin'; + $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule); + } + + if (null === $transliterator) { + throw new InvalidArgumentException(sprintf('Unknown transliteration rule "%s".', $rule)); + } + + self::$transliterators['any-latin/bgn'] = $transliterator; + } + + $s = $transliterator->transliterate($s); + } + } elseif (!\function_exists('iconv')) { + $s = preg_replace('/[^\x00-\x7F]/u', '?', $s); + } else { + $s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) { + $c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]); + + if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) { + throw new \LogicException(sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class)); + } + + return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?'); + }, $s); + } + } + + $str->string .= $s; + + return $str; + } + + public function camel(): static + { + $str = clone $this; + $str->string = str_replace(' ', '', preg_replace_callback('/\b.(?![A-Z]{2,})/u', static function ($m) { + static $i = 0; + + return 1 === ++$i ? ('İ' === $m[0] ? 'i̇' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'); + }, preg_replace('/[^\pL0-9]++/u', ' ', $this->string))); + + return $str; + } + + /** + * @return int[] + */ + public function codePointsAt(int $offset): array + { + $str = $this->slice($offset, 1); + + if ('' === $str->string) { + return []; + } + + $codePoints = []; + + foreach (preg_split('//u', $str->string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { + $codePoints[] = mb_ord($c, 'UTF-8'); + } + + return $codePoints; + } + + public function folded(bool $compat = true): static + { + $str = clone $this; + + if (!$compat || !\defined('Normalizer::NFKC_CF')) { + $str->string = normalizer_normalize($str->string, $compat ? \Normalizer::NFKC : \Normalizer::NFC); + $str->string = mb_strtolower(str_replace(self::FOLD_FROM, self::FOLD_TO, $this->string), 'UTF-8'); + } else { + $str->string = normalizer_normalize($str->string, \Normalizer::NFKC_CF); + } + + return $str; + } + + public function join(array $strings, ?string $lastGlue = null): static + { + $str = clone $this; + + $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : ''; + $str->string = implode($this->string, $strings).$tail; + + if (!preg_match('//u', $str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + return $str; + } + + public function lower(): static + { + $str = clone $this; + $str->string = mb_strtolower(str_replace('İ', 'i̇', $str->string), 'UTF-8'); + + return $str; + } + + public function match(string $regexp, int $flags = 0, int $offset = 0): array + { + $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; + + if ($this->ignoreCase) { + $regexp .= 'i'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (false === $match($regexp.'u', $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) { + throw new RuntimeException('Matching failed with error: '.preg_last_error_msg()); + } + } finally { + restore_error_handler(); + } + + return $matches; + } + + public function normalize(int $form = self::NFC): static + { + if (!\in_array($form, [self::NFC, self::NFD, self::NFKC, self::NFKD])) { + throw new InvalidArgumentException('Unsupported normalization form.'); + } + + $str = clone $this; + normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form); + + return $str; + } + + public function padBoth(int $length, string $padStr = ' '): static + { + if ('' === $padStr || !preg_match('//u', $padStr)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $pad = clone $this; + $pad->string = $padStr; + + return $this->pad($length, $pad, \STR_PAD_BOTH); + } + + public function padEnd(int $length, string $padStr = ' '): static + { + if ('' === $padStr || !preg_match('//u', $padStr)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $pad = clone $this; + $pad->string = $padStr; + + return $this->pad($length, $pad, \STR_PAD_RIGHT); + } + + public function padStart(int $length, string $padStr = ' '): static + { + if ('' === $padStr || !preg_match('//u', $padStr)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $pad = clone $this; + $pad->string = $padStr; + + return $this->pad($length, $pad, \STR_PAD_LEFT); + } + + public function replaceMatches(string $fromRegexp, string|callable $to): static + { + if ($this->ignoreCase) { + $fromRegexp .= 'i'; + } + + if (\is_array($to) || $to instanceof \Closure) { + $replace = 'preg_replace_callback'; + $to = static function (array $m) use ($to): string { + $to = $to($m); + + if ('' !== $to && (!\is_string($to) || !preg_match('//u', $to))) { + throw new InvalidArgumentException('Replace callback must return a valid UTF-8 string.'); + } + + return $to; + }; + } elseif ('' !== $to && !preg_match('//u', $to)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } else { + $replace = 'preg_replace'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (null === $string = $replace($fromRegexp.'u', $to, $this->string)) { + $lastError = preg_last_error(); + + foreach (get_defined_constants(true)['pcre'] as $k => $v) { + if ($lastError === $v && str_ends_with($k, '_ERROR')) { + throw new RuntimeException('Matching failed with '.$k.'.'); + } + } + + throw new RuntimeException('Matching failed with unknown error code.'); + } + } finally { + restore_error_handler(); + } + + $str = clone $this; + $str->string = $string; + + return $str; + } + + public function reverse(): static + { + $str = clone $this; + $str->string = implode('', array_reverse(preg_split('/(\X)/u', $str->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY))); + + return $str; + } + + public function snake(): static + { + $str = $this->camel(); + $str->string = mb_strtolower(preg_replace(['/(\p{Lu}+)(\p{Lu}\p{Ll})/u', '/([\p{Ll}0-9])(\p{Lu})/u'], '\1_\2', $str->string), 'UTF-8'); + + return $str; + } + + public function title(bool $allWords = false): static + { + $str = clone $this; + + $limit = $allWords ? -1 : 1; + + $str->string = preg_replace_callback('/\b./u', static fn (array $m): string => mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'), $str->string, $limit); + + return $str; + } + + public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static + { + if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) { + throw new InvalidArgumentException('Invalid UTF-8 chars.'); + } + $chars = preg_quote($chars); + + $str = clone $this; + $str->string = preg_replace("{^[$chars]++|[$chars]++$}uD", '', $str->string); + + return $str; + } + + public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static + { + if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) { + throw new InvalidArgumentException('Invalid UTF-8 chars.'); + } + $chars = preg_quote($chars); + + $str = clone $this; + $str->string = preg_replace("{[$chars]++$}uD", '', $str->string); + + return $str; + } + + public function trimPrefix($prefix): static + { + if (!$this->ignoreCase) { + return parent::trimPrefix($prefix); + } + + $str = clone $this; + + if ($prefix instanceof \Traversable) { + $prefix = iterator_to_array($prefix, false); + } elseif ($prefix instanceof parent) { + $prefix = $prefix->string; + } + + $prefix = implode('|', array_map('preg_quote', (array) $prefix)); + $str->string = preg_replace("{^(?:$prefix)}iuD", '', $this->string); + + return $str; + } + + public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static + { + if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) { + throw new InvalidArgumentException('Invalid UTF-8 chars.'); + } + $chars = preg_quote($chars); + + $str = clone $this; + $str->string = preg_replace("{^[$chars]++}uD", '', $str->string); + + return $str; + } + + public function trimSuffix($suffix): static + { + if (!$this->ignoreCase) { + return parent::trimSuffix($suffix); + } + + $str = clone $this; + + if ($suffix instanceof \Traversable) { + $suffix = iterator_to_array($suffix, false); + } elseif ($suffix instanceof parent) { + $suffix = $suffix->string; + } + + $suffix = implode('|', array_map('preg_quote', (array) $suffix)); + $str->string = preg_replace("{(?:$suffix)$}iuD", '', $this->string); + + return $str; + } + + public function upper(): static + { + $str = clone $this; + $str->string = mb_strtoupper($str->string, 'UTF-8'); + + return $str; + } + + public function width(bool $ignoreAnsiDecoration = true): int + { + $width = 0; + $s = str_replace(["\x00", "\x05", "\x07"], '', $this->string); + + if (str_contains($s, "\r")) { + $s = str_replace(["\r\n", "\r"], "\n", $s); + } + + if (!$ignoreAnsiDecoration) { + $s = preg_replace('/[\p{Cc}\x7F]++/u', '', $s); + } + + foreach (explode("\n", $s) as $s) { + if ($ignoreAnsiDecoration) { + $s = preg_replace('/(?:\x1B(?: + \[ [\x30-\x3F]*+ [\x20-\x2F]*+ [\x40-\x7E] + | [P\]X^_] .*? \x1B\\\\ + | [\x41-\x7E] + )|[\p{Cc}\x7F]++)/xu', '', $s); + } + + $lineWidth = $this->wcswidth($s); + + if ($lineWidth > $width) { + $width = $lineWidth; + } + } + + return $width; + } + + private function pad(int $len, self $pad, int $type): static + { + $sLen = $this->length(); + + if ($len <= $sLen) { + return clone $this; + } + + $padLen = $pad->length(); + $freeLen = $len - $sLen; + $len = $freeLen % $padLen; + + switch ($type) { + case \STR_PAD_RIGHT: + return $this->append(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + case \STR_PAD_LEFT: + return $this->prepend(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + case \STR_PAD_BOTH: + $freeLen /= 2; + + $rightLen = ceil($freeLen); + $len = $rightLen % $padLen; + $str = $this->append(str_repeat($pad->string, intdiv($rightLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + $leftLen = floor($freeLen); + $len = $leftLen % $padLen; + + return $str->prepend(str_repeat($pad->string, intdiv($leftLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + default: + throw new InvalidArgumentException('Invalid padding type.'); + } + } + + /** + * Based on https://github.com/jquast/wcwidth, a Python implementation of https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c. + */ + private function wcswidth(string $string): int + { + $width = 0; + + foreach (preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { + $codePoint = mb_ord($c, 'UTF-8'); + + if (0 === $codePoint // NULL + || 0x034F === $codePoint // COMBINING GRAPHEME JOINER + || (0x200B <= $codePoint && 0x200F >= $codePoint) // ZERO WIDTH SPACE to RIGHT-TO-LEFT MARK + || 0x2028 === $codePoint // LINE SEPARATOR + || 0x2029 === $codePoint // PARAGRAPH SEPARATOR + || (0x202A <= $codePoint && 0x202E >= $codePoint) // LEFT-TO-RIGHT EMBEDDING to RIGHT-TO-LEFT OVERRIDE + || (0x2060 <= $codePoint && 0x2063 >= $codePoint) // WORD JOINER to INVISIBLE SEPARATOR + ) { + continue; + } + + // Non printable characters + if (32 > $codePoint // C0 control characters + || (0x07F <= $codePoint && 0x0A0 > $codePoint) // C1 control characters and DEL + ) { + return -1; + } + + self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php'; + + if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) { + $lbound = 0; + while ($ubound >= $lbound) { + $mid = floor(($lbound + $ubound) / 2); + + if ($codePoint > self::$tableZero[$mid][1]) { + $lbound = $mid + 1; + } elseif ($codePoint < self::$tableZero[$mid][0]) { + $ubound = $mid - 1; + } else { + continue 2; + } + } + } + + self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php'; + + if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) { + $lbound = 0; + while ($ubound >= $lbound) { + $mid = floor(($lbound + $ubound) / 2); + + if ($codePoint > self::$tableWide[$mid][1]) { + $lbound = $mid + 1; + } elseif ($codePoint < self::$tableWide[$mid][0]) { + $ubound = $mid - 1; + } else { + $width += 2; + + continue 2; + } + } + } + + ++$width; + } + + return $width; + } +} diff --git a/php/libraries/composer/vendor/symfony/string/ByteString.php b/php/libraries/composer/vendor/symfony/string/ByteString.php new file mode 100644 index 0000000..3ebe43c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/ByteString.php @@ -0,0 +1,485 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; +use Symfony\Component\String\Exception\RuntimeException; + +/** + * Represents a binary-safe string of bytes. + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +class ByteString extends AbstractString +{ + private const ALPHABET_ALPHANUMERIC = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + + public function __construct(string $string = '') + { + $this->string = $string; + } + + /* + * The following method was derived from code of the Hack Standard Library (v4.40 - 2020-05-03) + * + * https://github.com/hhvm/hsl/blob/80a42c02f036f72a42f0415e80d6b847f4bf62d5/src/random/private.php#L16 + * + * Code subject to the MIT license (https://github.com/hhvm/hsl/blob/master/LICENSE). + * + * Copyright (c) 2004-2020, Facebook, Inc. (https://www.facebook.com/) + */ + + public static function fromRandom(int $length = 16, ?string $alphabet = null): self + { + if ($length <= 0) { + throw new InvalidArgumentException(sprintf('A strictly positive length is expected, "%d" given.', $length)); + } + + $alphabet ??= self::ALPHABET_ALPHANUMERIC; + $alphabetSize = \strlen($alphabet); + $bits = (int) ceil(log($alphabetSize, 2.0)); + if ($bits <= 0 || $bits > 56) { + throw new InvalidArgumentException('The length of the alphabet must in the [2^1, 2^56] range.'); + } + + $ret = ''; + while ($length > 0) { + $urandomLength = (int) ceil(2 * $length * $bits / 8.0); + $data = random_bytes($urandomLength); + $unpackedData = 0; + $unpackedBits = 0; + for ($i = 0; $i < $urandomLength && $length > 0; ++$i) { + // Unpack 8 bits + $unpackedData = ($unpackedData << 8) | \ord($data[$i]); + $unpackedBits += 8; + + // While we have enough bits to select a character from the alphabet, keep + // consuming the random data + for (; $unpackedBits >= $bits && $length > 0; $unpackedBits -= $bits) { + $index = ($unpackedData & ((1 << $bits) - 1)); + $unpackedData >>= $bits; + // Unfortunately, the alphabet size is not necessarily a power of two. + // Worst case, it is 2^k + 1, which means we need (k+1) bits and we + // have around a 50% chance of missing as k gets larger + if ($index < $alphabetSize) { + $ret .= $alphabet[$index]; + --$length; + } + } + } + } + + return new static($ret); + } + + public function bytesAt(int $offset): array + { + $str = $this->string[$offset] ?? ''; + + return '' === $str ? [] : [\ord($str)]; + } + + public function append(string ...$suffix): static + { + $str = clone $this; + $str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix); + + return $str; + } + + public function camel(): static + { + $str = clone $this; + + $parts = explode(' ', trim(ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $this->string)))); + $parts[0] = 1 !== \strlen($parts[0]) && ctype_upper($parts[0]) ? $parts[0] : lcfirst($parts[0]); + $str->string = implode('', $parts); + + return $str; + } + + public function chunk(int $length = 1): array + { + if (1 > $length) { + throw new InvalidArgumentException('The chunk length must be greater than zero.'); + } + + if ('' === $this->string) { + return []; + } + + $str = clone $this; + $chunks = []; + + foreach (str_split($this->string, $length) as $chunk) { + $str->string = $chunk; + $chunks[] = clone $str; + } + + return $chunks; + } + + public function endsWith(string|iterable|AbstractString $suffix): bool + { + if ($suffix instanceof AbstractString) { + $suffix = $suffix->string; + } elseif (!\is_string($suffix)) { + return parent::endsWith($suffix); + } + + return '' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase); + } + + public function equalsTo(string|iterable|AbstractString $string): bool + { + if ($string instanceof AbstractString) { + $string = $string->string; + } elseif (!\is_string($string)) { + return parent::equalsTo($string); + } + + if ('' !== $string && $this->ignoreCase) { + return 0 === strcasecmp($string, $this->string); + } + + return $string === $this->string; + } + + public function folded(): static + { + $str = clone $this; + $str->string = strtolower($str->string); + + return $str; + } + + public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOf($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? stripos($this->string, $needle, $offset) : strpos($this->string, $needle, $offset); + + return false === $i ? null : $i; + } + + public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOfLast($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? strripos($this->string, $needle, $offset) : strrpos($this->string, $needle, $offset); + + return false === $i ? null : $i; + } + + public function isUtf8(): bool + { + return '' === $this->string || preg_match('//u', $this->string); + } + + public function join(array $strings, ?string $lastGlue = null): static + { + $str = clone $this; + + $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : ''; + $str->string = implode($this->string, $strings).$tail; + + return $str; + } + + public function length(): int + { + return \strlen($this->string); + } + + public function lower(): static + { + $str = clone $this; + $str->string = strtolower($str->string); + + return $str; + } + + public function match(string $regexp, int $flags = 0, int $offset = 0): array + { + $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; + + if ($this->ignoreCase) { + $regexp .= 'i'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (false === $match($regexp, $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) { + throw new RuntimeException('Matching failed with error: '.preg_last_error_msg()); + } + } finally { + restore_error_handler(); + } + + return $matches; + } + + public function padBoth(int $length, string $padStr = ' '): static + { + $str = clone $this; + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_BOTH); + + return $str; + } + + public function padEnd(int $length, string $padStr = ' '): static + { + $str = clone $this; + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_RIGHT); + + return $str; + } + + public function padStart(int $length, string $padStr = ' '): static + { + $str = clone $this; + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_LEFT); + + return $str; + } + + public function prepend(string ...$prefix): static + { + $str = clone $this; + $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$str->string; + + return $str; + } + + public function replace(string $from, string $to): static + { + $str = clone $this; + + if ('' !== $from) { + $str->string = $this->ignoreCase ? str_ireplace($from, $to, $this->string) : str_replace($from, $to, $this->string); + } + + return $str; + } + + public function replaceMatches(string $fromRegexp, string|callable $to): static + { + if ($this->ignoreCase) { + $fromRegexp .= 'i'; + } + + $replace = \is_array($to) || $to instanceof \Closure ? 'preg_replace_callback' : 'preg_replace'; + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (null === $string = $replace($fromRegexp, $to, $this->string)) { + $lastError = preg_last_error(); + + foreach (get_defined_constants(true)['pcre'] as $k => $v) { + if ($lastError === $v && str_ends_with($k, '_ERROR')) { + throw new RuntimeException('Matching failed with '.$k.'.'); + } + } + + throw new RuntimeException('Matching failed with unknown error code.'); + } + } finally { + restore_error_handler(); + } + + $str = clone $this; + $str->string = $string; + + return $str; + } + + public function reverse(): static + { + $str = clone $this; + $str->string = strrev($str->string); + + return $str; + } + + public function slice(int $start = 0, ?int $length = null): static + { + $str = clone $this; + $str->string = (string) substr($this->string, $start, $length ?? \PHP_INT_MAX); + + return $str; + } + + public function snake(): static + { + $str = $this->camel(); + $str->string = strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $str->string)); + + return $str; + } + + public function splice(string $replacement, int $start = 0, ?int $length = null): static + { + $str = clone $this; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); + + return $str; + } + + public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array + { + if (1 > $limit ??= \PHP_INT_MAX) { + throw new InvalidArgumentException('Split limit must be a positive integer.'); + } + + if ('' === $delimiter) { + throw new InvalidArgumentException('Split delimiter is empty.'); + } + + if (null !== $flags) { + return parent::split($delimiter, $limit, $flags); + } + + $str = clone $this; + $chunks = $this->ignoreCase + ? preg_split('{'.preg_quote($delimiter).'}iD', $this->string, $limit) + : explode($delimiter, $this->string, $limit); + + foreach ($chunks as &$chunk) { + $str->string = $chunk; + $chunk = clone $str; + } + + return $chunks; + } + + public function startsWith(string|iterable|AbstractString $prefix): bool + { + if ($prefix instanceof AbstractString) { + $prefix = $prefix->string; + } elseif (!\is_string($prefix)) { + return parent::startsWith($prefix); + } + + return '' !== $prefix && 0 === ($this->ignoreCase ? strncasecmp($this->string, $prefix, \strlen($prefix)) : strncmp($this->string, $prefix, \strlen($prefix))); + } + + public function title(bool $allWords = false): static + { + $str = clone $this; + $str->string = $allWords ? ucwords($str->string) : ucfirst($str->string); + + return $str; + } + + public function toUnicodeString(?string $fromEncoding = null): UnicodeString + { + return new UnicodeString($this->toCodePointString($fromEncoding)->string); + } + + public function toCodePointString(?string $fromEncoding = null): CodePointString + { + $u = new CodePointString(); + + if (\in_array($fromEncoding, [null, 'utf8', 'utf-8', 'UTF8', 'UTF-8'], true) && preg_match('//u', $this->string)) { + $u->string = $this->string; + + return $u; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + try { + $validEncoding = false !== mb_detect_encoding($this->string, $fromEncoding ?? 'Windows-1252', true); + } catch (InvalidArgumentException $e) { + if (!\function_exists('iconv')) { + throw $e; + } + + $u->string = iconv($fromEncoding ?? 'Windows-1252', 'UTF-8', $this->string); + + return $u; + } + } finally { + restore_error_handler(); + } + + if (!$validEncoding) { + throw new InvalidArgumentException(sprintf('Invalid "%s" string.', $fromEncoding ?? 'Windows-1252')); + } + + $u->string = mb_convert_encoding($this->string, 'UTF-8', $fromEncoding ?? 'Windows-1252'); + + return $u; + } + + public function trim(string $chars = " \t\n\r\0\x0B\x0C"): static + { + $str = clone $this; + $str->string = trim($str->string, $chars); + + return $str; + } + + public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C"): static + { + $str = clone $this; + $str->string = rtrim($str->string, $chars); + + return $str; + } + + public function trimStart(string $chars = " \t\n\r\0\x0B\x0C"): static + { + $str = clone $this; + $str->string = ltrim($str->string, $chars); + + return $str; + } + + public function upper(): static + { + $str = clone $this; + $str->string = strtoupper($str->string); + + return $str; + } + + public function width(bool $ignoreAnsiDecoration = true): int + { + $string = preg_match('//u', $this->string) ? $this->string : preg_replace('/[\x80-\xFF]/', '?', $this->string); + + return (new CodePointString($string))->width($ignoreAnsiDecoration); + } +} diff --git a/php/libraries/composer/vendor/symfony/string/CHANGELOG.md b/php/libraries/composer/vendor/symfony/string/CHANGELOG.md new file mode 100644 index 0000000..31a3b54 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/CHANGELOG.md @@ -0,0 +1,40 @@ +CHANGELOG +========= + +6.2 +--- + + * Add support for emoji in `AsciiSlugger` + +5.4 +--- + + * Add `trimSuffix()` and `trimPrefix()` methods + +5.3 +--- + + * Made `AsciiSlugger` fallback to parent locale's symbolsMap + +5.2.0 +----- + + * added a `FrenchInflector` class + +5.1.0 +----- + + * added the `AbstractString::reverse()` method + * made `AbstractString::width()` follow POSIX.1-2001 + * added `LazyString` which provides memoizing stringable objects + * The component is not marked as `@experimental` anymore + * added the `s()` helper method to get either an `UnicodeString` or `ByteString` instance, + depending of the input string UTF-8 compliancy + * added `$cut` parameter to `Symfony\Component\String\AbstractString::truncate()` + * added `AbstractString::containsAny()` + * allow passing a string of custom characters to `ByteString::fromRandom()` + +5.0.0 +----- + + * added the component as experimental diff --git a/php/libraries/composer/vendor/symfony/string/CodePointString.php b/php/libraries/composer/vendor/symfony/string/CodePointString.php new file mode 100644 index 0000000..337bfc1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/CodePointString.php @@ -0,0 +1,260 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; + +/** + * Represents a string of Unicode code points encoded as UTF-8. + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +class CodePointString extends AbstractUnicodeString +{ + public function __construct(string $string = '') + { + if ('' !== $string && !preg_match('//u', $string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $this->string = $string; + } + + public function append(string ...$suffix): static + { + $str = clone $this; + $str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix); + + if (!preg_match('//u', $str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + return $str; + } + + public function chunk(int $length = 1): array + { + if (1 > $length) { + throw new InvalidArgumentException('The chunk length must be greater than zero.'); + } + + if ('' === $this->string) { + return []; + } + + $rx = '/('; + while (65535 < $length) { + $rx .= '.{65535}'; + $length -= 65535; + } + $rx .= '.{'.$length.'})/us'; + + $str = clone $this; + $chunks = []; + + foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) { + $str->string = $chunk; + $chunks[] = clone $str; + } + + return $chunks; + } + + public function codePointsAt(int $offset): array + { + $str = $offset ? $this->slice($offset, 1) : $this; + + return '' === $str->string ? [] : [mb_ord($str->string, 'UTF-8')]; + } + + public function endsWith(string|iterable|AbstractString $suffix): bool + { + if ($suffix instanceof AbstractString) { + $suffix = $suffix->string; + } elseif (!\is_string($suffix)) { + return parent::endsWith($suffix); + } + + if ('' === $suffix || !preg_match('//u', $suffix)) { + return false; + } + + if ($this->ignoreCase) { + return preg_match('{'.preg_quote($suffix).'$}iuD', $this->string); + } + + return \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix)); + } + + public function equalsTo(string|iterable|AbstractString $string): bool + { + if ($string instanceof AbstractString) { + $string = $string->string; + } elseif (!\is_string($string)) { + return parent::equalsTo($string); + } + + if ('' !== $string && $this->ignoreCase) { + return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8'); + } + + return $string === $this->string; + } + + public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOf($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? mb_stripos($this->string, $needle, $offset, 'UTF-8') : mb_strpos($this->string, $needle, $offset, 'UTF-8'); + + return false === $i ? null : $i; + } + + public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOfLast($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? mb_strripos($this->string, $needle, $offset, 'UTF-8') : mb_strrpos($this->string, $needle, $offset, 'UTF-8'); + + return false === $i ? null : $i; + } + + public function length(): int + { + return mb_strlen($this->string, 'UTF-8'); + } + + public function prepend(string ...$prefix): static + { + $str = clone $this; + $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string; + + if (!preg_match('//u', $str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + return $str; + } + + public function replace(string $from, string $to): static + { + $str = clone $this; + + if ('' === $from || !preg_match('//u', $from)) { + return $str; + } + + if ('' !== $to && !preg_match('//u', $to)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + if ($this->ignoreCase) { + $str->string = implode($to, preg_split('{'.preg_quote($from).'}iuD', $this->string)); + } else { + $str->string = str_replace($from, $to, $this->string); + } + + return $str; + } + + public function slice(int $start = 0, ?int $length = null): static + { + $str = clone $this; + $str->string = mb_substr($this->string, $start, $length, 'UTF-8'); + + return $str; + } + + public function splice(string $replacement, int $start = 0, ?int $length = null): static + { + if (!preg_match('//u', $replacement)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str = clone $this; + $start = $start ? \strlen(mb_substr($this->string, 0, $start, 'UTF-8')) : 0; + $length = $length ? \strlen(mb_substr($this->string, $start, $length, 'UTF-8')) : $length; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); + + return $str; + } + + public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array + { + if (1 > $limit ??= \PHP_INT_MAX) { + throw new InvalidArgumentException('Split limit must be a positive integer.'); + } + + if ('' === $delimiter) { + throw new InvalidArgumentException('Split delimiter is empty.'); + } + + if (null !== $flags) { + return parent::split($delimiter.'u', $limit, $flags); + } + + if (!preg_match('//u', $delimiter)) { + throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.'); + } + + $str = clone $this; + $chunks = $this->ignoreCase + ? preg_split('{'.preg_quote($delimiter).'}iuD', $this->string, $limit) + : explode($delimiter, $this->string, $limit); + + foreach ($chunks as &$chunk) { + $str->string = $chunk; + $chunk = clone $str; + } + + return $chunks; + } + + public function startsWith(string|iterable|AbstractString $prefix): bool + { + if ($prefix instanceof AbstractString) { + $prefix = $prefix->string; + } elseif (!\is_string($prefix)) { + return parent::startsWith($prefix); + } + + if ('' === $prefix || !preg_match('//u', $prefix)) { + return false; + } + + if ($this->ignoreCase) { + return 0 === mb_stripos($this->string, $prefix, 0, 'UTF-8'); + } + + return 0 === strncmp($this->string, $prefix, \strlen($prefix)); + } +} diff --git a/php/libraries/composer/vendor/symfony/string/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/string/Exception/ExceptionInterface.php new file mode 100644 index 0000000..3619786 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Exception/ExceptionInterface.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Exception; + +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/string/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/symfony/string/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..6aa586b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Exception/InvalidArgumentException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Exception; + +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/string/Exception/RuntimeException.php b/php/libraries/composer/vendor/symfony/string/Exception/RuntimeException.php new file mode 100644 index 0000000..77cb091 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Exception/RuntimeException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Exception; + +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/string/Inflector/EnglishInflector.php b/php/libraries/composer/vendor/symfony/string/Inflector/EnglishInflector.php new file mode 100644 index 0000000..dc7b08e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Inflector/EnglishInflector.php @@ -0,0 +1,553 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Inflector; + +final class EnglishInflector implements InflectorInterface +{ + /** + * Map English plural to singular suffixes. + * + * @see http://english-zone.com/spelling/plurals.html + */ + private const PLURAL_MAP = [ + // First entry: plural suffix, reversed + // Second entry: length of plural suffix + // Third entry: Whether the suffix may succeed a vowel + // Fourth entry: Whether the suffix may succeed a consonant + // Fifth entry: singular suffix, normal + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['a', 1, true, true, ['on', 'um']], + + // nebulae (nebula) + ['ea', 2, true, true, 'a'], + + // services (service) + ['secivres', 8, true, true, 'service'], + + // mice (mouse), lice (louse) + ['eci', 3, false, true, 'ouse'], + + // geese (goose) + ['esee', 4, false, true, 'oose'], + + // fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius) + ['i', 1, true, true, 'us'], + + // men (man), women (woman) + ['nem', 3, true, true, 'man'], + + // children (child) + ['nerdlihc', 8, true, true, 'child'], + + // oxen (ox) + ['nexo', 4, false, false, 'ox'], + + // indices (index), appendices (appendix), prices (price) + ['seci', 4, false, true, ['ex', 'ix', 'ice']], + + // codes (code) + ['sedoc', 5, false, true, 'code'], + + // selfies (selfie) + ['seifles', 7, true, true, 'selfie'], + + // zombies (zombie) + ['seibmoz', 7, true, true, 'zombie'], + + // movies (movie) + ['seivom', 6, true, true, 'movie'], + + // names (name) + ['seman', 5, true, false, 'name'], + + // conspectuses (conspectus), prospectuses (prospectus) + ['sesutcep', 8, true, true, 'pectus'], + + // feet (foot) + ['teef', 4, true, true, 'foot'], + + // geese (goose) + ['eseeg', 5, true, true, 'goose'], + + // teeth (tooth) + ['hteet', 5, true, true, 'tooth'], + + // news (news) + ['swen', 4, true, true, 'news'], + + // series (series) + ['seires', 6, true, true, 'series'], + + // babies (baby) + ['sei', 3, false, true, 'y'], + + // accesses (access), addresses (address), kisses (kiss) + ['sess', 4, true, false, 'ss'], + + // statuses (status) + ['sesutats', 8, true, true, 'status'], + + // analyses (analysis), ellipses (ellipsis), fungi (fungus), + // neuroses (neurosis), theses (thesis), emphases (emphasis), + // oases (oasis), crises (crisis), houses (house), bases (base), + // atlases (atlas) + ['ses', 3, true, true, ['s', 'se', 'sis']], + + // objectives (objective), alternative (alternatives) + ['sevit', 5, true, true, 'tive'], + + // drives (drive) + ['sevird', 6, false, true, 'drive'], + + // lives (life), wives (wife) + ['sevi', 4, false, true, 'ife'], + + // moves (move) + ['sevom', 5, true, true, 'move'], + + // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf), caves (cave), staves (staff) + ['sev', 3, true, true, ['f', 've', 'ff']], + + // axes (axis), axes (ax), axes (axe) + ['sexa', 4, false, false, ['ax', 'axe', 'axis']], + + // indexes (index), matrixes (matrix) + ['sex', 3, true, false, 'x'], + + // quizzes (quiz) + ['sezz', 4, true, false, 'z'], + + // bureaus (bureau) + ['suae', 4, false, true, 'eau'], + + // fees (fee), trees (tree), employees (employee) + ['see', 3, true, true, 'ee'], + + // edges (edge) + ['segd', 4, true, true, 'dge'], + + // roses (rose), garages (garage), cassettes (cassette), + // waltzes (waltz), heroes (hero), bushes (bush), arches (arch), + // shoes (shoe) + ['se', 2, true, true, ['', 'e']], + + // status (status) + ['sutats', 6, true, true, 'status'], + + // tags (tag) + ['s', 1, true, true, ''], + + // chateaux (chateau) + ['xuae', 4, false, true, 'eau'], + + // people (person) + ['elpoep', 6, true, true, 'person'], + ]; + + /** + * Map English singular to plural suffixes. + * + * @see http://english-zone.com/spelling/plurals.html + */ + private const SINGULAR_MAP = [ + // First entry: singular suffix, reversed + // Second entry: length of singular suffix + // Third entry: Whether the suffix may succeed a vowel + // Fourth entry: Whether the suffix may succeed a consonant + // Fifth entry: plural suffix, normal + + // axes (axis) + ['sixa', 4, false, false, 'axes'], + + // criterion (criteria) + ['airetirc', 8, false, false, 'criterion'], + + // nebulae (nebula) + ['aluben', 6, false, false, 'nebulae'], + + // children (child) + ['dlihc', 5, true, true, 'children'], + + // prices (price) + ['eci', 3, false, true, 'ices'], + + // services (service) + ['ecivres', 7, true, true, 'services'], + + // lives (life), wives (wife) + ['efi', 3, false, true, 'ives'], + + // selfies (selfie) + ['eifles', 6, true, true, 'selfies'], + + // movies (movie) + ['eivom', 5, true, true, 'movies'], + + // lice (louse) + ['esuol', 5, false, true, 'lice'], + + // mice (mouse) + ['esuom', 5, false, true, 'mice'], + + // geese (goose) + ['esoo', 4, false, true, 'eese'], + + // houses (house), bases (base) + ['es', 2, true, true, 'ses'], + + // geese (goose) + ['esoog', 5, true, true, 'geese'], + + // caves (cave) + ['ev', 2, true, true, 'ves'], + + // drives (drive) + ['evird', 5, false, true, 'drives'], + + // objectives (objective), alternative (alternatives) + ['evit', 4, true, true, 'tives'], + + // moves (move) + ['evom', 4, true, true, 'moves'], + + // staves (staff) + ['ffats', 5, true, true, 'staves'], + + // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf) + ['ff', 2, true, true, 'ffs'], + + // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf) + ['f', 1, true, true, ['fs', 'ves']], + + // arches (arch) + ['hc', 2, true, true, 'ches'], + + // bushes (bush) + ['hs', 2, true, true, 'shes'], + + // teeth (tooth) + ['htoot', 5, true, true, 'teeth'], + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['mu', 2, true, true, 'a'], + + // men (man), women (woman) + ['nam', 3, true, true, 'men'], + + // people (person) + ['nosrep', 6, true, true, ['persons', 'people']], + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['noi', 3, true, true, 'ions'], + + // coupon (coupons) + ['nop', 3, true, true, 'pons'], + + // seasons (season), treasons (treason), poisons (poison), lessons (lesson) + ['nos', 3, true, true, 'sons'], + + // icons (icon) + ['noc', 3, true, true, 'cons'], + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['no', 2, true, true, 'a'], + + // echoes (echo) + ['ohce', 4, true, true, 'echoes'], + + // heroes (hero) + ['oreh', 4, true, true, 'heroes'], + + // atlases (atlas) + ['salta', 5, true, true, 'atlases'], + + // irises (iris) + ['siri', 4, true, true, 'irises'], + + // analyses (analysis), ellipses (ellipsis), neuroses (neurosis) + // theses (thesis), emphases (emphasis), oases (oasis), + // crises (crisis) + ['sis', 3, true, true, 'ses'], + + // accesses (access), addresses (address), kisses (kiss) + ['ss', 2, true, false, 'sses'], + + // syllabi (syllabus) + ['suballys', 8, true, true, 'syllabi'], + + // buses (bus) + ['sub', 3, true, true, 'buses'], + + // circuses (circus) + ['suc', 3, true, true, 'cuses'], + + // hippocampi (hippocampus) + ['supmacoppih', 11, false, false, 'hippocampi'], + + // campuses (campus) + ['sup', 3, true, true, 'puses'], + + // status (status) + ['sutats', 6, true, true, ['status', 'statuses']], + + // conspectuses (conspectus), prospectuses (prospectus) + ['sutcep', 6, true, true, 'pectuses'], + + // fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius) + ['su', 2, true, true, 'i'], + + // news (news) + ['swen', 4, true, true, 'news'], + + // feet (foot) + ['toof', 4, true, true, 'feet'], + + // chateaux (chateau), bureaus (bureau) + ['uae', 3, false, true, ['eaus', 'eaux']], + + // oxen (ox) + ['xo', 2, false, false, 'oxen'], + + // hoaxes (hoax) + ['xaoh', 4, true, false, 'hoaxes'], + + // indices (index) + ['xedni', 5, false, true, ['indicies', 'indexes']], + + // boxes (box) + ['xo', 2, false, true, 'oxes'], + + // indexes (index), matrixes (matrix) + ['x', 1, true, false, ['cies', 'xes']], + + // appendices (appendix) + ['xi', 2, false, true, 'ices'], + + // babies (baby) + ['y', 1, false, true, 'ies'], + + // quizzes (quiz) + ['ziuq', 4, true, false, 'quizzes'], + + // waltzes (waltz) + ['z', 1, true, true, 'zes'], + ]; + + /** + * A list of words which should not be inflected, reversed. + */ + private const UNINFLECTED = [ + '', + + // data + 'atad', + + // deer + 'reed', + + // equipment + 'tnempiuqe', + + // feedback + 'kcabdeef', + + // fish + 'hsif', + + // health + 'htlaeh', + + // history + 'yrotsih', + + // info + 'ofni', + + // information + 'noitamrofni', + + // money + 'yenom', + + // moose + 'esoom', + + // series + 'seires', + + // sheep + 'peehs', + + // species + 'seiceps', + + // traffic + 'ciffart', + + // aircraft + 'tfarcria', + ]; + + public function singularize(string $plural): array + { + $pluralRev = strrev($plural); + $lowerPluralRev = strtolower($pluralRev); + $pluralLength = \strlen($lowerPluralRev); + + // Check if the word is one which is not inflected, return early if so + if (\in_array($lowerPluralRev, self::UNINFLECTED, true)) { + return [$plural]; + } + + // The outer loop iterates over the entries of the plural table + // The inner loop $j iterates over the characters of the plural suffix + // in the plural table to compare them with the characters of the actual + // given plural suffix + foreach (self::PLURAL_MAP as $map) { + $suffix = $map[0]; + $suffixLength = $map[1]; + $j = 0; + + // Compare characters in the plural table and of the suffix of the + // given plural one by one + while ($suffix[$j] === $lowerPluralRev[$j]) { + // Let $j point to the next character + ++$j; + + // Successfully compared the last character + // Add an entry with the singular suffix to the singular array + if ($j === $suffixLength) { + // Is there any character preceding the suffix in the plural string? + if ($j < $pluralLength) { + $nextIsVowel = str_contains('aeiou', $lowerPluralRev[$j]); + + if (!$map[2] && $nextIsVowel) { + // suffix may not succeed a vowel but next char is one + break; + } + + if (!$map[3] && !$nextIsVowel) { + // suffix may not succeed a consonant but next char is one + break; + } + } + + $newBase = substr($plural, 0, $pluralLength - $suffixLength); + $newSuffix = $map[4]; + + // Check whether the first character in the plural suffix + // is uppercased. If yes, uppercase the first character in + // the singular suffix too + $firstUpper = ctype_upper($pluralRev[$j - 1]); + + if (\is_array($newSuffix)) { + $singulars = []; + + foreach ($newSuffix as $newSuffixEntry) { + $singulars[] = $newBase.($firstUpper ? ucfirst($newSuffixEntry) : $newSuffixEntry); + } + + return $singulars; + } + + return [$newBase.($firstUpper ? ucfirst($newSuffix) : $newSuffix)]; + } + + // Suffix is longer than word + if ($j === $pluralLength) { + break; + } + } + } + + // Assume that plural and singular is identical + return [$plural]; + } + + public function pluralize(string $singular): array + { + $singularRev = strrev($singular); + $lowerSingularRev = strtolower($singularRev); + $singularLength = \strlen($lowerSingularRev); + + // Check if the word is one which is not inflected, return early if so + if (\in_array($lowerSingularRev, self::UNINFLECTED, true)) { + return [$singular]; + } + + // The outer loop iterates over the entries of the singular table + // The inner loop $j iterates over the characters of the singular suffix + // in the singular table to compare them with the characters of the actual + // given singular suffix + foreach (self::SINGULAR_MAP as $map) { + $suffix = $map[0]; + $suffixLength = $map[1]; + $j = 0; + + // Compare characters in the singular table and of the suffix of the + // given plural one by one + + while ($suffix[$j] === $lowerSingularRev[$j]) { + // Let $j point to the next character + ++$j; + + // Successfully compared the last character + // Add an entry with the plural suffix to the plural array + if ($j === $suffixLength) { + // Is there any character preceding the suffix in the plural string? + if ($j < $singularLength) { + $nextIsVowel = str_contains('aeiou', $lowerSingularRev[$j]); + + if (!$map[2] && $nextIsVowel) { + // suffix may not succeed a vowel but next char is one + break; + } + + if (!$map[3] && !$nextIsVowel) { + // suffix may not succeed a consonant but next char is one + break; + } + } + + $newBase = substr($singular, 0, $singularLength - $suffixLength); + $newSuffix = $map[4]; + + // Check whether the first character in the singular suffix + // is uppercased. If yes, uppercase the first character in + // the singular suffix too + $firstUpper = ctype_upper($singularRev[$j - 1]); + + if (\is_array($newSuffix)) { + $plurals = []; + + foreach ($newSuffix as $newSuffixEntry) { + $plurals[] = $newBase.($firstUpper ? ucfirst($newSuffixEntry) : $newSuffixEntry); + } + + return $plurals; + } + + return [$newBase.($firstUpper ? ucfirst($newSuffix) : $newSuffix)]; + } + + // Suffix is longer than word + if ($j === $singularLength) { + break; + } + } + } + + // Assume that plural is singular with a trailing `s` + return [$singular.'s']; + } +} diff --git a/php/libraries/composer/vendor/symfony/string/Inflector/FrenchInflector.php b/php/libraries/composer/vendor/symfony/string/Inflector/FrenchInflector.php new file mode 100644 index 0000000..955abbf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Inflector/FrenchInflector.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Inflector; + +/** + * French inflector. + * + * This class does only inflect nouns; not adjectives nor composed words like "soixante-dix". + */ +final class FrenchInflector implements InflectorInterface +{ + /** + * A list of all rules for pluralise. + * + * @see https://la-conjugaison.nouvelobs.com/regles/grammaire/le-pluriel-des-noms-121.php + */ + private const PLURALIZE_REGEXP = [ + // First entry: regexp + // Second entry: replacement + + // Words finishing with "s", "x" or "z" are invariables + // Les mots finissant par "s", "x" ou "z" sont invariables + ['/(s|x|z)$/i', '\1'], + + // Words finishing with "eau" are pluralized with a "x" + // Les mots finissant par "eau" prennent tous un "x" au pluriel + ['/(eau)$/i', '\1x'], + + // Words finishing with "au" are pluralized with a "x" excepted "landau" + // Les mots finissant par "au" prennent un "x" au pluriel sauf "landau" + ['/^(landau)$/i', '\1s'], + ['/(au)$/i', '\1x'], + + // Words finishing with "eu" are pluralized with a "x" excepted "pneu", "bleu", "émeu" + // Les mots finissant en "eu" prennent un "x" au pluriel sauf "pneu", "bleu", "émeu" + ['/^(pneu|bleu|émeu)$/i', '\1s'], + ['/(eu)$/i', '\1x'], + + // Words finishing with "al" are pluralized with a "aux" excepted + // Les mots finissant en "al" se terminent en "aux" sauf + ['/^(bal|carnaval|caracal|chacal|choral|corral|étal|festival|récital|val)$/i', '\1s'], + ['/al$/i', '\1aux'], + + // Aspirail, bail, corail, émail, fermail, soupirail, travail, vantail et vitrail font leur pluriel en -aux + ['/^(aspir|b|cor|ém|ferm|soupir|trav|vant|vitr)ail$/i', '\1aux'], + + // Bijou, caillou, chou, genou, hibou, joujou et pou qui prennent un x au pluriel + ['/^(bij|caill|ch|gen|hib|jouj|p)ou$/i', '\1oux'], + + // Invariable words + ['/^(cinquante|soixante|mille)$/i', '\1'], + + // French titles + ['/^(mon|ma)(sieur|dame|demoiselle|seigneur)$/', 'mes\2s'], + ['/^(Mon|Ma)(sieur|dame|demoiselle|seigneur)$/', 'Mes\2s'], + ]; + + /** + * A list of all rules for singularize. + */ + private const SINGULARIZE_REGEXP = [ + // First entry: regexp + // Second entry: replacement + + // Aspirail, bail, corail, émail, fermail, soupirail, travail, vantail et vitrail font leur pluriel en -aux + ['/((aspir|b|cor|ém|ferm|soupir|trav|vant|vitr))aux$/i', '\1ail'], + + // Words finishing with "eau" are pluralized with a "x" + // Les mots finissant par "eau" prennent tous un "x" au pluriel + ['/(eau)x$/i', '\1'], + + // Words finishing with "al" are pluralized with a "aux" expected + // Les mots finissant en "al" se terminent en "aux" sauf + ['/(amir|anim|arsen|boc|can|capit|capor|chev|crist|génér|hopit|hôpit|idé|journ|littor|loc|m|mét|minér|princip|radic|termin)aux$/i', '\1al'], + + // Words finishing with "au" are pluralized with a "x" excepted "landau" + // Les mots finissant par "au" prennent un "x" au pluriel sauf "landau" + ['/(au)x$/i', '\1'], + + // Words finishing with "eu" are pluralized with a "x" excepted "pneu", "bleu", "émeu" + // Les mots finissant en "eu" prennent un "x" au pluriel sauf "pneu", "bleu", "émeu" + ['/(eu)x$/i', '\1'], + + // Words finishing with "ou" are pluralized with a "s" excepted bijou, caillou, chou, genou, hibou, joujou, pou + // Les mots finissant par "ou" prennent un "s" sauf bijou, caillou, chou, genou, hibou, joujou, pou + ['/(bij|caill|ch|gen|hib|jouj|p)oux$/i', '\1ou'], + + // French titles + ['/^mes(dame|demoiselle)s$/', 'ma\1'], + ['/^Mes(dame|demoiselle)s$/', 'Ma\1'], + ['/^mes(sieur|seigneur)s$/', 'mon\1'], + ['/^Mes(sieur|seigneur)s$/', 'Mon\1'], + + // Default rule + ['/s$/i', ''], + ]; + + /** + * A list of words which should not be inflected. + * This list is only used by singularize. + */ + private const UNINFLECTED = '/^(abcès|accès|abus|albatros|anchois|anglais|autobus|bois|brebis|carquois|cas|chas|colis|concours|corps|cours|cyprès|décès|devis|discours|dos|embarras|engrais|entrelacs|excès|fils|fois|gâchis|gars|glas|héros|intrus|jars|jus|kermès|lacis|legs|lilas|marais|mars|matelas|mépris|mets|mois|mors|obus|os|palais|paradis|parcours|pardessus|pays|plusieurs|poids|pois|pouls|printemps|processus|progrès|puits|pus|rabais|radis|recors|recours|refus|relais|remords|remous|rictus|rhinocéros|repas|rubis|sans|sas|secours|sens|souris|succès|talus|tapis|tas|taudis|temps|tiers|univers|velours|verglas|vernis|virus)$/i'; + + public function singularize(string $plural): array + { + if ($this->isInflectedWord($plural)) { + return [$plural]; + } + + foreach (self::SINGULARIZE_REGEXP as $rule) { + [$regexp, $replace] = $rule; + + if (1 === preg_match($regexp, $plural)) { + return [preg_replace($regexp, $replace, $plural)]; + } + } + + return [$plural]; + } + + public function pluralize(string $singular): array + { + if ($this->isInflectedWord($singular)) { + return [$singular]; + } + + foreach (self::PLURALIZE_REGEXP as $rule) { + [$regexp, $replace] = $rule; + + if (1 === preg_match($regexp, $singular)) { + return [preg_replace($regexp, $replace, $singular)]; + } + } + + return [$singular.'s']; + } + + private function isInflectedWord(string $word): bool + { + return 1 === preg_match(self::UNINFLECTED, $word); + } +} diff --git a/php/libraries/composer/vendor/symfony/string/Inflector/InflectorInterface.php b/php/libraries/composer/vendor/symfony/string/Inflector/InflectorInterface.php new file mode 100644 index 0000000..67f2834 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Inflector/InflectorInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Inflector; + +interface InflectorInterface +{ + /** + * Returns the singular forms of a string. + * + * If the method can't determine the form with certainty, several possible singulars are returned. + * + * @return string[] + */ + public function singularize(string $plural): array; + + /** + * Returns the plural forms of a string. + * + * If the method can't determine the form with certainty, several possible plurals are returned. + * + * @return string[] + */ + public function pluralize(string $singular): array; +} diff --git a/php/libraries/composer/vendor/symfony/string/LICENSE b/php/libraries/composer/vendor/symfony/string/LICENSE new file mode 100644 index 0000000..f37c76b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2019-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/string/LazyString.php b/php/libraries/composer/vendor/symfony/string/LazyString.php new file mode 100644 index 0000000..1af3769 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/LazyString.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +/** + * A string whose value is computed lazily by a callback. + * + * @author Nicolas Grekas + */ +class LazyString implements \Stringable, \JsonSerializable +{ + private \Closure|string $value; + + /** + * @param callable|array $callback A callable or a [Closure, method] lazy-callable + */ + public static function fromCallable(callable|array $callback, mixed ...$arguments): static + { + if (\is_array($callback) && !\is_callable($callback) && !(($callback[0] ?? null) instanceof \Closure || 2 < \count($callback))) { + throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a callable or a [Closure, method] lazy-callable, "%s" given.', __METHOD__, '['.implode(', ', array_map('get_debug_type', $callback)).']')); + } + + $lazyString = new static(); + $lazyString->value = static function () use (&$callback, &$arguments): string { + static $value; + + if (null !== $arguments) { + if (!\is_callable($callback)) { + $callback[0] = $callback[0](); + $callback[1] ??= '__invoke'; + } + $value = $callback(...$arguments); + $callback = !\is_scalar($value) && !$value instanceof \Stringable ? self::getPrettyName($callback) : 'callable'; + $arguments = null; + } + + return $value ?? ''; + }; + + return $lazyString; + } + + public static function fromStringable(string|int|float|bool|\Stringable $value): static + { + if (\is_object($value)) { + return static::fromCallable($value->__toString(...)); + } + + $lazyString = new static(); + $lazyString->value = (string) $value; + + return $lazyString; + } + + /** + * Tells whether the provided value can be cast to string. + */ + final public static function isStringable(mixed $value): bool + { + return \is_string($value) || $value instanceof \Stringable || \is_scalar($value); + } + + /** + * Casts scalars and stringable objects to strings. + * + * @throws \TypeError When the provided value is not stringable + */ + final public static function resolve(\Stringable|string|int|float|bool $value): string + { + return $value; + } + + public function __toString(): string + { + if (\is_string($this->value)) { + return $this->value; + } + + try { + return $this->value = ($this->value)(); + } catch (\Throwable $e) { + if (\TypeError::class === $e::class && __FILE__ === $e->getFile()) { + $type = explode(', ', $e->getMessage()); + $type = substr(array_pop($type), 0, -\strlen(' returned')); + $r = new \ReflectionFunction($this->value); + $callback = $r->getStaticVariables()['callback']; + + $e = new \TypeError(sprintf('Return value of %s() passed to %s::fromCallable() must be of the type string, %s returned.', $callback, static::class, $type)); + } + + throw $e; + } + } + + public function __sleep(): array + { + $this->__toString(); + + return ['value']; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + private function __construct() + { + } + + private static function getPrettyName(callable $callback): string + { + if (\is_string($callback)) { + return $callback; + } + + if (\is_array($callback)) { + $class = \is_object($callback[0]) ? get_debug_type($callback[0]) : $callback[0]; + $method = $callback[1]; + } elseif ($callback instanceof \Closure) { + $r = new \ReflectionFunction($callback); + + if (str_contains($r->name, '{closure}') || !$class = \PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass()) { + return $r->name; + } + + $class = $class->name; + $method = $r->name; + } else { + $class = get_debug_type($callback); + $method = '__invoke'; + } + + return $class.'::'.$method; + } +} diff --git a/php/libraries/composer/vendor/symfony/string/README.md b/php/libraries/composer/vendor/symfony/string/README.md new file mode 100644 index 0000000..9c7e1e1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/README.md @@ -0,0 +1,14 @@ +String Component +================ + +The String component provides an object-oriented API to strings and deals +with bytes, UTF-8 code points and grapheme clusters in a unified way. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/string.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/string/Resources/data/wcswidth_table_wide.php b/php/libraries/composer/vendor/symfony/string/Resources/data/wcswidth_table_wide.php new file mode 100644 index 0000000..8314c8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Resources/data/wcswidth_table_wide.php @@ -0,0 +1,1155 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +if (!\function_exists(u::class)) { + function u(?string $string = ''): UnicodeString + { + return new UnicodeString($string ?? ''); + } +} + +if (!\function_exists(b::class)) { + function b(?string $string = ''): ByteString + { + return new ByteString($string ?? ''); + } +} + +if (!\function_exists(s::class)) { + /** + * @return UnicodeString|ByteString + */ + function s(?string $string = ''): AbstractString + { + $string ??= ''; + + return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string); + } +} diff --git a/php/libraries/composer/vendor/symfony/string/Slugger/AsciiSlugger.php b/php/libraries/composer/vendor/symfony/string/Slugger/AsciiSlugger.php new file mode 100644 index 0000000..a9693d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Slugger/AsciiSlugger.php @@ -0,0 +1,210 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Slugger; + +use Symfony\Component\Intl\Transliterator\EmojiTransliterator; +use Symfony\Component\String\AbstractUnicodeString; +use Symfony\Component\String\UnicodeString; +use Symfony\Contracts\Translation\LocaleAwareInterface; + +if (!interface_exists(LocaleAwareInterface::class)) { + throw new \LogicException('You cannot use the "Symfony\Component\String\Slugger\AsciiSlugger" as the "symfony/translation-contracts" package is not installed. Try running "composer require symfony/translation-contracts".'); +} + +/** + * @author Titouan Galopin + */ +class AsciiSlugger implements SluggerInterface, LocaleAwareInterface +{ + private const LOCALE_TO_TRANSLITERATOR_ID = [ + 'am' => 'Amharic-Latin', + 'ar' => 'Arabic-Latin', + 'az' => 'Azerbaijani-Latin', + 'be' => 'Belarusian-Latin', + 'bg' => 'Bulgarian-Latin', + 'bn' => 'Bengali-Latin', + 'de' => 'de-ASCII', + 'el' => 'Greek-Latin', + 'fa' => 'Persian-Latin', + 'he' => 'Hebrew-Latin', + 'hy' => 'Armenian-Latin', + 'ka' => 'Georgian-Latin', + 'kk' => 'Kazakh-Latin', + 'ky' => 'Kirghiz-Latin', + 'ko' => 'Korean-Latin', + 'mk' => 'Macedonian-Latin', + 'mn' => 'Mongolian-Latin', + 'or' => 'Oriya-Latin', + 'ps' => 'Pashto-Latin', + 'ru' => 'Russian-Latin', + 'sr' => 'Serbian-Latin', + 'sr_Cyrl' => 'Serbian-Latin', + 'th' => 'Thai-Latin', + 'tk' => 'Turkmen-Latin', + 'uk' => 'Ukrainian-Latin', + 'uz' => 'Uzbek-Latin', + 'zh' => 'Han-Latin', + ]; + + private ?string $defaultLocale; + private \Closure|array $symbolsMap = [ + 'en' => ['@' => 'at', '&' => 'and'], + ]; + private bool|string $emoji = false; + + /** + * Cache of transliterators per locale. + * + * @var \Transliterator[] + */ + private array $transliterators = []; + + public function __construct(?string $defaultLocale = null, array|\Closure|null $symbolsMap = null) + { + $this->defaultLocale = $defaultLocale; + $this->symbolsMap = $symbolsMap ?? $this->symbolsMap; + } + + /** + * @return void + */ + public function setLocale(string $locale) + { + $this->defaultLocale = $locale; + } + + public function getLocale(): string + { + return $this->defaultLocale; + } + + /** + * @param bool|string $emoji true will use the same locale, + * false will disable emoji, + * and a string to use a specific locale + */ + public function withEmoji(bool|string $emoji = true): static + { + if (false !== $emoji && !class_exists(EmojiTransliterator::class)) { + throw new \LogicException(sprintf('You cannot use the "%s()" method as the "symfony/intl" package is not installed. Try running "composer require symfony/intl".', __METHOD__)); + } + + $new = clone $this; + $new->emoji = $emoji; + + return $new; + } + + public function slug(string $string, string $separator = '-', ?string $locale = null): AbstractUnicodeString + { + $locale ??= $this->defaultLocale; + + $transliterator = []; + if ($locale && ('de' === $locale || str_starts_with($locale, 'de_'))) { + // Use the shortcut for German in UnicodeString::ascii() if possible (faster and no requirement on intl) + $transliterator = ['de-ASCII']; + } elseif (\function_exists('transliterator_transliterate') && $locale) { + $transliterator = (array) $this->createTransliterator($locale); + } + + if ($emojiTransliterator = $this->createEmojiTransliterator($locale)) { + $transliterator[] = $emojiTransliterator; + } + + if ($this->symbolsMap instanceof \Closure) { + // If the symbols map is passed as a closure, there is no need to fallback to the parent locale + // as the closure can just provide substitutions for all locales of interest. + $symbolsMap = $this->symbolsMap; + array_unshift($transliterator, static fn ($s) => $symbolsMap($s, $locale)); + } + + $unicodeString = (new UnicodeString($string))->ascii($transliterator); + + if (\is_array($this->symbolsMap)) { + $map = null; + if (isset($this->symbolsMap[$locale])) { + $map = $this->symbolsMap[$locale]; + } else { + $parent = self::getParentLocale($locale); + if ($parent && isset($this->symbolsMap[$parent])) { + $map = $this->symbolsMap[$parent]; + } + } + if ($map) { + foreach ($map as $char => $replace) { + $unicodeString = $unicodeString->replace($char, ' '.$replace.' '); + } + } + } + + return $unicodeString + ->replaceMatches('/[^A-Za-z0-9]++/', $separator) + ->trim($separator) + ; + } + + private function createTransliterator(string $locale): ?\Transliterator + { + if (\array_key_exists($locale, $this->transliterators)) { + return $this->transliterators[$locale]; + } + + // Exact locale supported, cache and return + if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$locale] ?? null) { + return $this->transliterators[$locale] = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id); + } + + // Locale not supported and no parent, fallback to any-latin + if (!$parent = self::getParentLocale($locale)) { + return $this->transliterators[$locale] = null; + } + + // Try to use the parent locale (ie. try "de" for "de_AT") and cache both locales + if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$parent] ?? null) { + $transliterator = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id); + } + + return $this->transliterators[$locale] = $this->transliterators[$parent] = $transliterator ?? null; + } + + private function createEmojiTransliterator(?string $locale): ?EmojiTransliterator + { + if (\is_string($this->emoji)) { + $locale = $this->emoji; + } elseif (!$this->emoji) { + return null; + } + + while (null !== $locale) { + try { + return EmojiTransliterator::create("emoji-$locale"); + } catch (\IntlException) { + $locale = self::getParentLocale($locale); + } + } + + return null; + } + + private static function getParentLocale(?string $locale): ?string + { + if (!$locale) { + return null; + } + if (false === $str = strrchr($locale, '_')) { + // no parent locale + return null; + } + + return substr($locale, 0, -\strlen($str)); + } +} diff --git a/php/libraries/composer/vendor/symfony/string/Slugger/SluggerInterface.php b/php/libraries/composer/vendor/symfony/string/Slugger/SluggerInterface.php new file mode 100644 index 0000000..dd0d581 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/Slugger/SluggerInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Slugger; + +use Symfony\Component\String\AbstractUnicodeString; + +/** + * Creates a URL-friendly slug from a given string. + * + * @author Titouan Galopin + */ +interface SluggerInterface +{ + /** + * Creates a slug for the given string and locale, using appropriate transliteration when needed. + */ + public function slug(string $string, string $separator = '-', ?string $locale = null): AbstractUnicodeString; +} diff --git a/php/libraries/composer/vendor/symfony/string/UnicodeString.php b/php/libraries/composer/vendor/symfony/string/UnicodeString.php new file mode 100644 index 0000000..75af2da --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/UnicodeString.php @@ -0,0 +1,385 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; + +/** + * Represents a string of Unicode grapheme clusters encoded as UTF-8. + * + * A letter followed by combining characters (accents typically) form what Unicode defines + * as a grapheme cluster: a character as humans mean it in written texts. This class knows + * about the concept and won't split a letter apart from its combining accents. It also + * ensures all string comparisons happen on their canonically-composed representation, + * ignoring e.g. the order in which accents are listed when a letter has many of them. + * + * @see https://unicode.org/reports/tr15/ + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +class UnicodeString extends AbstractUnicodeString +{ + public function __construct(string $string = '') + { + if ('' === $string || normalizer_is_normalized($this->string = $string)) { + return; + } + + if (false === $string = normalizer_normalize($string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $this->string = $string; + } + + public function append(string ...$suffix): static + { + $str = clone $this; + $str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix)); + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + + return $str; + } + + public function chunk(int $length = 1): array + { + if (1 > $length) { + throw new InvalidArgumentException('The chunk length must be greater than zero.'); + } + + if ('' === $this->string) { + return []; + } + + $rx = '/('; + while (65535 < $length) { + $rx .= '\X{65535}'; + $length -= 65535; + } + $rx .= '\X{'.$length.'})/u'; + + $str = clone $this; + $chunks = []; + + foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) { + $str->string = $chunk; + $chunks[] = clone $str; + } + + return $chunks; + } + + public function endsWith(string|iterable|AbstractString $suffix): bool + { + if ($suffix instanceof AbstractString) { + $suffix = $suffix->string; + } elseif (!\is_string($suffix)) { + return parent::endsWith($suffix); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($suffix, $form) ?: $suffix = normalizer_normalize($suffix, $form); + + if ('' === $suffix || false === $suffix) { + return false; + } + + if ($this->ignoreCase) { + return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8'); + } + + return $suffix === grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)); + } + + public function equalsTo(string|iterable|AbstractString $string): bool + { + if ($string instanceof AbstractString) { + $string = $string->string; + } elseif (!\is_string($string)) { + return parent::equalsTo($string); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form); + + if ('' !== $string && false !== $string && $this->ignoreCase) { + return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8'); + } + + return $string === $this->string; + } + + public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOf($needle, $offset); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form); + + if ('' === $needle || false === $needle) { + return null; + } + + try { + $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset); + } catch (\ValueError) { + return null; + } + + return false === $i ? null : $i; + } + + public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOfLast($needle, $offset); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form); + + if ('' === $needle || false === $needle) { + return null; + } + + $string = $this->string; + + if (0 > $offset) { + // workaround https://bugs.php.net/74264 + if (0 > $offset += grapheme_strlen($needle)) { + $string = grapheme_substr($string, 0, $offset); + } + $offset = 0; + } + + $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset); + + return false === $i ? null : $i; + } + + public function join(array $strings, ?string $lastGlue = null): static + { + $str = parent::join($strings, $lastGlue); + normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string); + + return $str; + } + + public function length(): int + { + return grapheme_strlen($this->string); + } + + public function normalize(int $form = self::NFC): static + { + $str = clone $this; + + if (\in_array($form, [self::NFC, self::NFKC], true)) { + normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form); + } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) { + throw new InvalidArgumentException('Unsupported normalization form.'); + } elseif (!normalizer_is_normalized($str->string, $form)) { + $str->string = normalizer_normalize($str->string, $form); + $str->ignoreCase = null; + } + + return $str; + } + + public function prepend(string ...$prefix): static + { + $str = clone $this; + $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string; + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + + return $str; + } + + public function replace(string $from, string $to): static + { + $str = clone $this; + normalizer_is_normalized($from) ?: $from = normalizer_normalize($from); + + if ('' !== $from && false !== $from) { + $tail = $str->string; + $result = ''; + $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos'; + + while ('' !== $tail && false !== $i = $indexOf($tail, $from)) { + $slice = grapheme_substr($tail, 0, $i); + $result .= $slice.$to; + $tail = substr($tail, \strlen($slice) + \strlen($from)); + } + + $str->string = $result.$tail; + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + } + + return $str; + } + + public function replaceMatches(string $fromRegexp, string|callable $to): static + { + $str = parent::replaceMatches($fromRegexp, $to); + normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string); + + return $str; + } + + public function slice(int $start = 0, ?int $length = null): static + { + $str = clone $this; + + $str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647); + + return $str; + } + + public function splice(string $replacement, int $start = 0, ?int $length = null): static + { + $str = clone $this; + + $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0; + $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? 2147483647)) : $length; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647); + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + + return $str; + } + + public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array + { + if (1 > $limit ??= 2147483647) { + throw new InvalidArgumentException('Split limit must be a positive integer.'); + } + + if ('' === $delimiter) { + throw new InvalidArgumentException('Split delimiter is empty.'); + } + + if (null !== $flags) { + return parent::split($delimiter.'u', $limit, $flags); + } + + normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter); + + if (false === $delimiter) { + throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.'); + } + + $str = clone $this; + $tail = $this->string; + $chunks = []; + $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos'; + + while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) { + $str->string = grapheme_substr($tail, 0, $i); + $chunks[] = clone $str; + $tail = substr($tail, \strlen($str->string) + \strlen($delimiter)); + --$limit; + } + + $str->string = $tail; + $chunks[] = clone $str; + + return $chunks; + } + + public function startsWith(string|iterable|AbstractString $prefix): bool + { + if ($prefix instanceof AbstractString) { + $prefix = $prefix->string; + } elseif (!\is_string($prefix)) { + return parent::startsWith($prefix); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form); + + if ('' === $prefix || false === $prefix) { + return false; + } + + if ($this->ignoreCase) { + return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8'); + } + + return $prefix === grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES); + } + + /** + * @return void + */ + public function __wakeup() + { + if (!\is_string($this->string)) { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string); + } + + public function __clone() + { + if (null === $this->ignoreCase) { + normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string); + } + + $this->ignoreCase = false; + } +} diff --git a/php/libraries/composer/vendor/symfony/string/composer.json b/php/libraries/composer/vendor/symfony/string/composer.json new file mode 100644 index 0000000..56c1368 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/string/composer.json @@ -0,0 +1,43 @@ +{ + "name": "symfony/string", + "type": "library", + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "keywords": ["string", "utf8", "utf-8", "grapheme", "i18n", "unicode"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/intl": "^6.2|^7.0", + "symfony/http-client": "^5.4|^6.0|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^5.4|^6.0|^7.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\String\\": "" }, + "files": [ "Resources/functions.php" ], + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/CHANGELOG.md b/php/libraries/composer/vendor/symfony/translation-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/LICENSE b/php/libraries/composer/vendor/symfony/translation-contracts/LICENSE new file mode 100644 index 0000000..7536cae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/LocaleAwareInterface.php b/php/libraries/composer/vendor/symfony/translation-contracts/LocaleAwareInterface.php new file mode 100644 index 0000000..db40ba1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/LocaleAwareInterface.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Translation; + +interface LocaleAwareInterface +{ + /** + * Sets the current locale. + * + * @return void + * + * @throws \InvalidArgumentException If the locale contains invalid characters + */ + public function setLocale(string $locale); + + /** + * Returns the current locale. + */ + public function getLocale(): string; +} diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/README.md b/php/libraries/composer/vendor/symfony/translation-contracts/README.md new file mode 100644 index 0000000..b211d58 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/README.md @@ -0,0 +1,9 @@ +Symfony Translation Contracts +============================= + +A set of abstractions extracted out of the Symfony components. + +Can be used to build on semantics that the Symfony components proved useful and +that already have battle tested implementations. + +See https://github.com/symfony/contracts/blob/main/README.md for more information. diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/Test/TranslatorTest.php b/php/libraries/composer/vendor/symfony/translation-contracts/Test/TranslatorTest.php new file mode 100644 index 0000000..756228a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/Test/TranslatorTest.php @@ -0,0 +1,385 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Translation\Test; + +use PHPUnit\Framework\TestCase; +use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorTrait; + +/** + * Test should cover all languages mentioned on http://translate.sourceforge.net/wiki/l10n/pluralforms + * and Plural forms mentioned on http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms. + * + * See also https://developer.mozilla.org/en/Localization_and_Plurals which mentions 15 rules having a maximum of 6 forms. + * The mozilla code is also interesting to check for. + * + * As mentioned by chx http://drupal.org/node/1273968 we can cover all by testing number from 0 to 199 + * + * The goal to cover all languages is to far fetched so this test case is smaller. + * + * @author Clemens Tolboom clemens@build2be.nl + */ +class TranslatorTest extends TestCase +{ + private string $defaultLocale; + + protected function setUp(): void + { + $this->defaultLocale = \Locale::getDefault(); + \Locale::setDefault('en'); + } + + protected function tearDown(): void + { + \Locale::setDefault($this->defaultLocale); + } + + public function getTranslator(): TranslatorInterface + { + return new class() implements TranslatorInterface { + use TranslatorTrait; + }; + } + + /** + * @dataProvider getTransTests + */ + public function testTrans($expected, $id, $parameters) + { + $translator = $this->getTranslator(); + + $this->assertEquals($expected, $translator->trans($id, $parameters)); + } + + /** + * @dataProvider getTransChoiceTests + */ + public function testTransChoiceWithExplicitLocale($expected, $id, $number) + { + $translator = $this->getTranslator(); + + $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number])); + } + + /** + * @requires extension intl + * + * @dataProvider getTransChoiceTests + */ + public function testTransChoiceWithDefaultLocale($expected, $id, $number) + { + $translator = $this->getTranslator(); + + $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number])); + } + + /** + * @dataProvider getTransChoiceTests + */ + public function testTransChoiceWithEnUsPosix($expected, $id, $number) + { + $translator = $this->getTranslator(); + $translator->setLocale('en_US_POSIX'); + + $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number])); + } + + public function testGetSetLocale() + { + $translator = $this->getTranslator(); + + $this->assertEquals('en', $translator->getLocale()); + } + + /** + * @requires extension intl + */ + public function testGetLocaleReturnsDefaultLocaleIfNotSet() + { + $translator = $this->getTranslator(); + + \Locale::setDefault('pt_BR'); + $this->assertEquals('pt_BR', $translator->getLocale()); + + \Locale::setDefault('en'); + $this->assertEquals('en', $translator->getLocale()); + } + + public static function getTransTests() + { + return [ + ['Symfony is great!', 'Symfony is great!', []], + ['Symfony is awesome!', 'Symfony is %what%!', ['%what%' => 'awesome']], + ]; + } + + public static function getTransChoiceTests() + { + return [ + ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0], + ['There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1], + ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10], + ['There are 0 apples', 'There is 1 apple|There are %count% apples', 0], + ['There is 1 apple', 'There is 1 apple|There are %count% apples', 1], + ['There are 10 apples', 'There is 1 apple|There are %count% apples', 10], + // custom validation messages may be coded with a fixed value + ['There are 2 apples', 'There are 2 apples', 2], + ]; + } + + /** + * @dataProvider getInterval + */ + public function testInterval($expected, $number, $interval) + { + $translator = $this->getTranslator(); + + $this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', ['%count%' => $number])); + } + + public static function getInterval() + { + return [ + ['foo', 3, '{1,2, 3 ,4}'], + ['bar', 10, '{1,2, 3 ,4}'], + ['bar', 3, '[1,2]'], + ['foo', 1, '[1,2]'], + ['foo', 2, '[1,2]'], + ['bar', 1, ']1,2['], + ['bar', 2, ']1,2['], + ['foo', log(0), '[-Inf,2['], + ['foo', -log(0), '[-2,+Inf]'], + ]; + } + + /** + * @dataProvider getChooseTests + */ + public function testChoose($expected, $id, $number, $locale = null) + { + $translator = $this->getTranslator(); + + $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number], null, $locale)); + } + + public function testReturnMessageIfExactlyOneStandardRuleIsGiven() + { + $translator = $this->getTranslator(); + + $this->assertEquals('There are two apples', $translator->trans('There are two apples', ['%count%' => 2])); + } + + /** + * @dataProvider getNonMatchingMessages + */ + public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number) + { + $translator = $this->getTranslator(); + + $this->expectException(\InvalidArgumentException::class); + + $translator->trans($id, ['%count%' => $number]); + } + + public static function getNonMatchingMessages() + { + return [ + ['{0} There are no apples|{1} There is one apple', 2], + ['{1} There is one apple|]1,Inf] There are %count% apples', 0], + ['{1} There is one apple|]2,Inf] There are %count% apples', 2], + ['{0} There are no apples|There is one apple', 2], + ]; + } + + public static function getChooseTests() + { + return [ + ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0], + ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0], + ['There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0], + + ['There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1], + + ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10], + ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10], + ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10], + + ['There are 0 apples', 'There is one apple|There are %count% apples', 0], + ['There is one apple', 'There is one apple|There are %count% apples', 1], + ['There are 10 apples', 'There is one apple|There are %count% apples', 10], + + ['There are 0 apples', 'one: There is one apple|more: There are %count% apples', 0], + ['There is one apple', 'one: There is one apple|more: There are %count% apples', 1], + ['There are 10 apples', 'one: There is one apple|more: There are %count% apples', 10], + + ['There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0], + ['There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1], + ['There are 10 apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10], + + ['', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0], + ['', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1], + + // Indexed only tests which are Gettext PoFile* compatible strings. + ['There are 0 apples', 'There is one apple|There are %count% apples', 0], + ['There is one apple', 'There is one apple|There are %count% apples', 1], + ['There are 2 apples', 'There is one apple|There are %count% apples', 2], + + // Tests for float numbers + ['There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7], + ['There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1], + ['There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7], + ['There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0], + ['There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0], + ['There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0], + + // Test texts with new-lines + // with double-quotes and \n in id & double-quotes and actual newlines in text + ["This is a text with a\n new-line in it. Selector = 0.", '{0}This is a text with a + new-line in it. Selector = 0.|{1}This is a text with a + new-line in it. Selector = 1.|[1,Inf]This is a text with a + new-line in it. Selector > 1.', 0], + // with double-quotes and \n in id and single-quotes and actual newlines in text + ["This is a text with a\n new-line in it. Selector = 1.", '{0}This is a text with a + new-line in it. Selector = 0.|{1}This is a text with a + new-line in it. Selector = 1.|[1,Inf]This is a text with a + new-line in it. Selector > 1.', 1], + ["This is a text with a\n new-line in it. Selector > 1.", '{0}This is a text with a + new-line in it. Selector = 0.|{1}This is a text with a + new-line in it. Selector = 1.|[1,Inf]This is a text with a + new-line in it. Selector > 1.', 5], + // with double-quotes and id split across lines + ['This is a text with a + new-line in it. Selector = 1.', '{0}This is a text with a + new-line in it. Selector = 0.|{1}This is a text with a + new-line in it. Selector = 1.|[1,Inf]This is a text with a + new-line in it. Selector > 1.', 1], + // with single-quotes and id split across lines + ['This is a text with a + new-line in it. Selector > 1.', '{0}This is a text with a + new-line in it. Selector = 0.|{1}This is a text with a + new-line in it. Selector = 1.|[1,Inf]This is a text with a + new-line in it. Selector > 1.', 5], + // with single-quotes and \n in text + ['This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0], + // with double-quotes and id split across lines + ["This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1], + // escape pipe + ['This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0], + // Empty plural set (2 plural forms) from a .PO file + ['', '|', 1], + // Empty plural set (3 plural forms) from a .PO file + ['', '||', 1], + + // Floating values + ['1.5 liters', '%count% liter|%count% liters', 1.5], + ['1.5 litre', '%count% litre|%count% litres', 1.5, 'fr'], + + // Negative values + ['-1 degree', '%count% degree|%count% degrees', -1], + ['-1 degré', '%count% degré|%count% degrés', -1], + ['-1.5 degrees', '%count% degree|%count% degrees', -1.5], + ['-1.5 degré', '%count% degré|%count% degrés', -1.5, 'fr'], + ['-2 degrees', '%count% degree|%count% degrees', -2], + ['-2 degrés', '%count% degré|%count% degrés', -2], + ]; + } + + /** + * @dataProvider failingLangcodes + */ + public function testFailedLangcodes($nplural, $langCodes) + { + $matrix = $this->generateTestData($langCodes); + $this->validateMatrix($nplural, $matrix, false); + } + + /** + * @dataProvider successLangcodes + */ + public function testLangcodes($nplural, $langCodes) + { + $matrix = $this->generateTestData($langCodes); + $this->validateMatrix($nplural, $matrix); + } + + /** + * This array should contain all currently known langcodes. + * + * As it is impossible to have this ever complete we should try as hard as possible to have it almost complete. + */ + public static function successLangcodes(): array + { + return [ + ['1', ['ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky']], + ['2', ['nl', 'fr', 'en', 'de', 'de_GE', 'hy', 'hy_AM', 'en_US_POSIX']], + ['3', ['be', 'bs', 'cs', 'hr']], + ['4', ['cy', 'mt', 'sl']], + ['6', ['ar']], + ]; + } + + /** + * This array should be at least empty within the near future. + * + * This both depends on a complete list trying to add above as understanding + * the plural rules of the current failing languages. + * + * @return array with nplural together with langcodes + */ + public static function failingLangcodes(): array + { + return [ + ['1', ['fa']], + ['2', ['jbo']], + ['3', ['cbs']], + ['4', ['gd', 'kw']], + ['5', ['ga']], + ]; + } + + /** + * We validate only on the plural coverage. Thus the real rules is not tested. + * + * @param string $nplural Plural expected + * @param array $matrix Containing langcodes and their plural index values + */ + protected function validateMatrix(string $nplural, array $matrix, bool $expectSuccess = true) + { + foreach ($matrix as $langCode => $data) { + $indexes = array_flip($data); + if ($expectSuccess) { + $this->assertCount($nplural, $indexes, "Langcode '$langCode' has '$nplural' plural forms."); + } else { + $this->assertNotEquals((int) $nplural, \count($indexes), "Langcode '$langCode' has '$nplural' plural forms."); + } + } + } + + protected function generateTestData($langCodes) + { + $translator = new class() { + use TranslatorTrait { + getPluralizationRule as public; + } + }; + + $matrix = []; + foreach ($langCodes as $langCode) { + for ($count = 0; $count < 200; ++$count) { + $plural = $translator->getPluralizationRule($count, $langCode); + $matrix[$langCode][$count] = $plural; + } + } + + return $matrix; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/TranslatableInterface.php b/php/libraries/composer/vendor/symfony/translation-contracts/TranslatableInterface.php new file mode 100644 index 0000000..47fd6fa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/TranslatableInterface.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\Contracts\Translation; + +/** + * @author Nicolas Grekas + */ +interface TranslatableInterface +{ + public function trans(TranslatorInterface $translator, string $locale = null): string; +} diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/TranslatorInterface.php b/php/libraries/composer/vendor/symfony/translation-contracts/TranslatorInterface.php new file mode 100644 index 0000000..018db07 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/TranslatorInterface.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Translation; + +/** + * @author Fabien Potencier + */ +interface TranslatorInterface +{ + /** + * Translates the given message. + * + * When a number is provided as a parameter named "%count%", the message is parsed for plural + * forms and a translation is chosen according to this number using the following rules: + * + * Given a message with different plural translations separated by a + * pipe (|), this method returns the correct portion of the message based + * on the given number, locale and the pluralization rules in the message + * itself. + * + * The message supports two different types of pluralization rules: + * + * interval: {0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples + * indexed: There is one apple|There are %count% apples + * + * The indexed solution can also contain labels (e.g. one: There is one apple). + * This is purely for making the translations more clear - it does not + * affect the functionality. + * + * The two methods can also be mixed: + * {0} There are no apples|one: There is one apple|more: There are %count% apples + * + * An interval can represent a finite set of numbers: + * {1,2,3,4} + * + * An interval can represent numbers between two numbers: + * [1, +Inf] + * ]-1,2[ + * + * The left delimiter can be [ (inclusive) or ] (exclusive). + * The right delimiter can be [ (exclusive) or ] (inclusive). + * Beside numbers, you can use -Inf and +Inf for the infinite. + * + * @see https://en.wikipedia.org/wiki/ISO_31-11 + * + * @param string $id The message id (may also be an object that can be cast to string) + * @param array $parameters An array of parameters for the message + * @param string|null $domain The domain for the message or null to use the default + * @param string|null $locale The locale or null to use the default + * + * @throws \InvalidArgumentException If the locale contains invalid characters + */ + public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string; + + /** + * Returns the default locale. + */ + public function getLocale(): string; +} diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/TranslatorTrait.php b/php/libraries/composer/vendor/symfony/translation-contracts/TranslatorTrait.php new file mode 100644 index 0000000..e3b0adf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/TranslatorTrait.php @@ -0,0 +1,225 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Translation; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; + +/** + * A trait to help implement TranslatorInterface and LocaleAwareInterface. + * + * @author Fabien Potencier + */ +trait TranslatorTrait +{ + private ?string $locale = null; + + /** + * @return void + */ + public function setLocale(string $locale) + { + $this->locale = $locale; + } + + public function getLocale(): string + { + return $this->locale ?: (class_exists(\Locale::class) ? \Locale::getDefault() : 'en'); + } + + public function trans(?string $id, array $parameters = [], string $domain = null, string $locale = null): string + { + if (null === $id || '' === $id) { + return ''; + } + + if (!isset($parameters['%count%']) || !is_numeric($parameters['%count%'])) { + return strtr($id, $parameters); + } + + $number = (float) $parameters['%count%']; + $locale = $locale ?: $this->getLocale(); + + $parts = []; + if (preg_match('/^\|++$/', $id)) { + $parts = explode('|', $id); + } elseif (preg_match_all('/(?:\|\||[^\|])++/', $id, $matches)) { + $parts = $matches[0]; + } + + $intervalRegexp = <<<'EOF' +/^(?P + ({\s* + (\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*) + \s*}) + + | + + (?P[\[\]]) + \s* + (?P-Inf|\-?\d+(\.\d+)?) + \s*,\s* + (?P\+?Inf|\-?\d+(\.\d+)?) + \s* + (?P[\[\]]) +)\s*(?P.*?)$/xs +EOF; + + $standardRules = []; + foreach ($parts as $part) { + $part = trim(str_replace('||', '|', $part)); + + // try to match an explicit rule, then fallback to the standard ones + if (preg_match($intervalRegexp, $part, $matches)) { + if ($matches[2]) { + foreach (explode(',', $matches[3]) as $n) { + if ($number == $n) { + return strtr($matches['message'], $parameters); + } + } + } else { + $leftNumber = '-Inf' === $matches['left'] ? -\INF : (float) $matches['left']; + $rightNumber = is_numeric($matches['right']) ? (float) $matches['right'] : \INF; + + if (('[' === $matches['left_delimiter'] ? $number >= $leftNumber : $number > $leftNumber) + && (']' === $matches['right_delimiter'] ? $number <= $rightNumber : $number < $rightNumber) + ) { + return strtr($matches['message'], $parameters); + } + } + } elseif (preg_match('/^\w+\:\s*(.*?)$/', $part, $matches)) { + $standardRules[] = $matches[1]; + } else { + $standardRules[] = $part; + } + } + + $position = $this->getPluralizationRule($number, $locale); + + if (!isset($standardRules[$position])) { + // when there's exactly one rule given, and that rule is a standard + // rule, use this rule + if (1 === \count($parts) && isset($standardRules[0])) { + return strtr($standardRules[0], $parameters); + } + + $message = sprintf('Unable to choose a translation for "%s" with locale "%s" for value "%d". Double check that this translation has the correct plural options (e.g. "There is one apple|There are %%count%% apples").', $id, $locale, $number); + + if (class_exists(InvalidArgumentException::class)) { + throw new InvalidArgumentException($message); + } + + throw new \InvalidArgumentException($message); + } + + return strtr($standardRules[$position], $parameters); + } + + /** + * Returns the plural position to use for the given locale and number. + * + * The plural rules are derived from code of the Zend Framework (2010-09-25), + * which is subject to the new BSD license (http://framework.zend.com/license/new-bsd). + * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + */ + private function getPluralizationRule(float $number, string $locale): int + { + $number = abs($number); + + return match ('pt_BR' !== $locale && 'en_US_POSIX' !== $locale && \strlen($locale) > 3 ? substr($locale, 0, strrpos($locale, '_')) : $locale) { + 'af', + 'bn', + 'bg', + 'ca', + 'da', + 'de', + 'el', + 'en', + 'en_US_POSIX', + 'eo', + 'es', + 'et', + 'eu', + 'fa', + 'fi', + 'fo', + 'fur', + 'fy', + 'gl', + 'gu', + 'ha', + 'he', + 'hu', + 'is', + 'it', + 'ku', + 'lb', + 'ml', + 'mn', + 'mr', + 'nah', + 'nb', + 'ne', + 'nl', + 'nn', + 'no', + 'oc', + 'om', + 'or', + 'pa', + 'pap', + 'ps', + 'pt', + 'so', + 'sq', + 'sv', + 'sw', + 'ta', + 'te', + 'tk', + 'ur', + 'zu' => (1 == $number) ? 0 : 1, + 'am', + 'bh', + 'fil', + 'fr', + 'gun', + 'hi', + 'hy', + 'ln', + 'mg', + 'nso', + 'pt_BR', + 'ti', + 'wa' => ($number < 2) ? 0 : 1, + 'be', + 'bs', + 'hr', + 'ru', + 'sh', + 'sr', + 'uk' => ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2), + 'cs', + 'sk' => (1 == $number) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2), + 'ga' => (1 == $number) ? 0 : ((2 == $number) ? 1 : 2), + 'lt' => ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2), + 'sl' => (1 == $number % 100) ? 0 : ((2 == $number % 100) ? 1 : (((3 == $number % 100) || (4 == $number % 100)) ? 2 : 3)), + 'mk' => (1 == $number % 10) ? 0 : 1, + 'mt' => (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3)), + 'lv' => (0 == $number) ? 0 : (((1 == $number % 10) && (11 != $number % 100)) ? 1 : 2), + 'pl' => (1 == $number) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2), + 'cy' => (1 == $number) ? 0 : ((2 == $number) ? 1 : (((8 == $number) || (11 == $number)) ? 2 : 3)), + 'ro' => (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2), + 'ar' => (0 == $number) ? 0 : ((1 == $number) ? 1 : ((2 == $number) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5)))), + default => 0, + }; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation-contracts/composer.json b/php/libraries/composer/vendor/symfony/translation-contracts/composer.json new file mode 100644 index 0000000..213b5cd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation-contracts/composer.json @@ -0,0 +1,37 @@ +{ + "name": "symfony/translation-contracts", + "type": "library", + "description": "Generic abstractions related to translation", + "keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1" + }, + "autoload": { + "psr-4": { "Symfony\\Contracts\\Translation\\": "" }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/CHANGELOG.md b/php/libraries/composer/vendor/symfony/translation/CHANGELOG.md new file mode 100644 index 0000000..5f9098c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/CHANGELOG.md @@ -0,0 +1,205 @@ +CHANGELOG +========= + +6.4 +--- + + * Give current locale to `LocaleSwitcher::runWithLocale()`'s callback + * Add `--as-tree` option to `translation:pull` command to write YAML messages as a tree-like structure + * [BC BREAK] Add argument `$buildDir` to `DataCollectorTranslator::warmUp()` + * Add `DataCollectorTranslatorPass` and `LoggingTranslatorPass` (moved from `FrameworkBundle`) + * Add `PhraseTranslationProvider` + +6.2.7 +----- + + * [BC BREAK] The following data providers for `ProviderFactoryTestCase` are now static: + `supportsProvider()`, `createProvider()`, `unsupportedSchemeProvider()`and `incompleteDsnProvider()` + * [BC BREAK] `ProviderTestCase::toStringProvider()` is now static + +6.2 +--- + + * Deprecate `PhpStringTokenParser` + * Deprecate `PhpExtractor` in favor of `PhpAstExtractor` + * Add `PhpAstExtractor` (requires [nikic/php-parser](https://github.com/nikic/php-parser) to be installed) + +6.1 +--- + + * Parameters implementing `TranslatableInterface` are processed + * Add the file extension to the `XliffFileDumper` constructor + +5.4 +--- + + * Add `github` format & autodetection to render errors as annotations when + running the XLIFF linter command in a Github Actions environment. + * Translation providers are not experimental anymore + +5.3 +--- + + * Add `translation:pull` and `translation:push` commands to manage translations with third-party providers + * Add `TranslatorBagInterface::getCatalogues` method + * Add support to load XLIFF string in `XliffFileLoader` + +5.2.0 +----- + + * added support for calling `trans` with ICU formatted messages + * added `PseudoLocalizationTranslator` + * added `TranslatableMessage` objects that represent a message that can be translated + * added the `t()` function to easily create `TranslatableMessage` objects + * Added support for extracting messages from `TranslatableMessage` objects + +5.1.0 +----- + + * added support for `name` attribute on `unit` element from xliff2 to be used as a translation key instead of always the `source` element + +5.0.0 +----- + + * removed support for using `null` as the locale in `Translator` + * removed `TranslatorInterface` + * removed `MessageSelector` + * removed `ChoiceMessageFormatterInterface` + * removed `PluralizationRule` + * removed `Interval` + * removed `transChoice()` methods, use the trans() method instead with a %count% parameter + * removed `FileDumper::setBackup()` and `TranslationWriter::disableBackup()` + * removed `MessageFormatter::choiceFormat()` + * added argument `$filename` to `PhpExtractor::parseTokens()` + * removed support for implicit STDIN usage in the `lint:xliff` command, use `lint:xliff -` (append a dash) instead to make it explicit. + +4.4.0 +----- + + * deprecated support for using `null` as the locale in `Translator` + * deprecated accepting STDIN implicitly when using the `lint:xliff` command, use `lint:xliff -` (append a dash) instead to make it explicit. + * Marked the `TranslationDataCollector` class as `@final`. + +4.3.0 +----- + + * Improved Xliff 1.2 loader to load the original file's metadata + * Added `TranslatorPathsPass` + +4.2.0 +----- + + * Started using ICU parent locales as fallback locales. + * allow using the ICU message format using domains with the "+intl-icu" suffix + * deprecated `Translator::transChoice()` in favor of using `Translator::trans()` with a `%count%` parameter + * deprecated `TranslatorInterface` in favor of `Symfony\Contracts\Translation\TranslatorInterface` + * deprecated `MessageSelector`, `Interval` and `PluralizationRules`; use `IdentityTranslator` instead + * Added `IntlFormatter` and `IntlFormatterInterface` + * added support for multiple files and directories in `XliffLintCommand` + * Marked `Translator::getFallbackLocales()` and `TranslationDataCollector::getFallbackLocales()` as internal + +4.1.0 +----- + + * The `FileDumper::setBackup()` method is deprecated. + * The `TranslationWriter::disableBackup()` method is deprecated. + * The `XliffFileDumper` will write "name" on the "unit" node when dumping XLIFF 2.0. + +4.0.0 +----- + + * removed the backup feature of the `FileDumper` class + * removed `TranslationWriter::writeTranslations()` method + * removed support for passing `MessageSelector` instances to the constructor of the `Translator` class + +3.4.0 +----- + + * Added `TranslationDumperPass` + * Added `TranslationExtractorPass` + * Added `TranslatorPass` + * Added `TranslationReader` and `TranslationReaderInterface` + * Added `` section to the Xliff 2.0 dumper. + * Improved Xliff 2.0 loader to load `` section. + * Added `TranslationWriterInterface` + * Deprecated `TranslationWriter::writeTranslations` in favor of `TranslationWriter::write` + * added support for adding custom message formatter and decoupling the default one. + * Added `PhpExtractor` + * Added `PhpStringTokenParser` + +3.2.0 +----- + + * Added support for escaping `|` in plural translations with double pipe. + +3.1.0 +----- + + * Deprecated the backup feature of the file dumper classes. + +3.0.0 +----- + + * removed `FileDumper::format()` method. + * Changed the visibility of the locale property in `Translator` from protected to private. + +2.8.0 +----- + + * deprecated FileDumper::format(), overwrite FileDumper::formatCatalogue() instead. + * deprecated Translator::getMessages(), rely on TranslatorBagInterface::getCatalogue() instead. + * added `FileDumper::formatCatalogue` which allows format the catalogue without dumping it into file. + * added option `json_encoding` to JsonFileDumper + * added options `as_tree`, `inline` to YamlFileDumper + * added support for XLIFF 2.0. + * added support for XLIFF target and tool attributes. + * added message parameters to DataCollectorTranslator. + * [DEPRECATION] The `DiffOperation` class has been deprecated and + will be removed in Symfony 3.0, since its operation has nothing to do with 'diff', + so the class name is misleading. The `TargetOperation` class should be used for + this use-case instead. + +2.7.0 +----- + + * added DataCollectorTranslator for collecting the translated messages. + +2.6.0 +----- + + * added possibility to cache catalogues + * added TranslatorBagInterface + * added LoggingTranslator + * added Translator::getMessages() for retrieving the message catalogue as an array + +2.5.0 +----- + + * added relative file path template to the file dumpers + * added optional backup to the file dumpers + * changed IcuResFileDumper to extend FileDumper + +2.3.0 +----- + + * added classes to make operations on catalogues (like making a diff or a merge on 2 catalogues) + * added Translator::getFallbackLocales() + * deprecated Translator::setFallbackLocale() in favor of the new Translator::setFallbackLocales() method + +2.2.0 +----- + + * QtTranslationsLoader class renamed to QtFileLoader. QtTranslationsLoader is deprecated and will be removed in 2.3. + * [BC BREAK] uniformized the exception thrown by the load() method when an error occurs. The load() method now + throws Symfony\Component\Translation\Exception\NotFoundResourceException when a resource cannot be found + and Symfony\Component\Translation\Exception\InvalidResourceException when a resource is invalid. + * changed the exception class thrown by some load() methods from \RuntimeException to \InvalidArgumentException + (IcuDatFileLoader, IcuResFileLoader and QtFileLoader) + +2.1.0 +----- + + * added support for more than one fallback locale + * added support for extracting translation messages from templates (Twig and PHP) + * added dumpers for translation catalogs + * added support for QT, gettext, and ResourceBundles diff --git a/php/libraries/composer/vendor/symfony/translation/Catalogue/AbstractOperation.php b/php/libraries/composer/vendor/symfony/translation/Catalogue/AbstractOperation.php new file mode 100644 index 0000000..7dff58f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Catalogue/AbstractOperation.php @@ -0,0 +1,187 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Catalogue; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\LogicException; +use Symfony\Component\Translation\MessageCatalogue; +use Symfony\Component\Translation\MessageCatalogueInterface; + +/** + * Base catalogues binary operation class. + * + * A catalogue binary operation performs operation on + * source (the left argument) and target (the right argument) catalogues. + * + * @author Jean-François Simon + */ +abstract class AbstractOperation implements OperationInterface +{ + public const OBSOLETE_BATCH = 'obsolete'; + public const NEW_BATCH = 'new'; + public const ALL_BATCH = 'all'; + + protected $source; + protected $target; + protected $result; + + /** + * This array stores 'all', 'new' and 'obsolete' messages for all valid domains. + * + * The data structure of this array is as follows: + * + * [ + * 'domain 1' => [ + * 'all' => [...], + * 'new' => [...], + * 'obsolete' => [...] + * ], + * 'domain 2' => [ + * 'all' => [...], + * 'new' => [...], + * 'obsolete' => [...] + * ], + * ... + * ] + * + * @var array The array that stores 'all', 'new' and 'obsolete' messages + */ + protected $messages; + + private array $domains; + + /** + * @throws LogicException + */ + public function __construct(MessageCatalogueInterface $source, MessageCatalogueInterface $target) + { + if ($source->getLocale() !== $target->getLocale()) { + throw new LogicException('Operated catalogues must belong to the same locale.'); + } + + $this->source = $source; + $this->target = $target; + $this->result = new MessageCatalogue($source->getLocale()); + $this->messages = []; + } + + public function getDomains(): array + { + if (!isset($this->domains)) { + $domains = []; + foreach ([$this->source, $this->target] as $catalogue) { + foreach ($catalogue->getDomains() as $domain) { + $domains[$domain] = $domain; + + if ($catalogue->all($domainIcu = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX)) { + $domains[$domainIcu] = $domainIcu; + } + } + } + + $this->domains = array_values($domains); + } + + return $this->domains; + } + + public function getMessages(string $domain): array + { + if (!\in_array($domain, $this->getDomains())) { + throw new InvalidArgumentException(sprintf('Invalid domain: "%s".', $domain)); + } + + if (!isset($this->messages[$domain][self::ALL_BATCH])) { + $this->processDomain($domain); + } + + return $this->messages[$domain][self::ALL_BATCH]; + } + + public function getNewMessages(string $domain): array + { + if (!\in_array($domain, $this->getDomains())) { + throw new InvalidArgumentException(sprintf('Invalid domain: "%s".', $domain)); + } + + if (!isset($this->messages[$domain][self::NEW_BATCH])) { + $this->processDomain($domain); + } + + return $this->messages[$domain][self::NEW_BATCH]; + } + + public function getObsoleteMessages(string $domain): array + { + if (!\in_array($domain, $this->getDomains())) { + throw new InvalidArgumentException(sprintf('Invalid domain: "%s".', $domain)); + } + + if (!isset($this->messages[$domain][self::OBSOLETE_BATCH])) { + $this->processDomain($domain); + } + + return $this->messages[$domain][self::OBSOLETE_BATCH]; + } + + public function getResult(): MessageCatalogueInterface + { + foreach ($this->getDomains() as $domain) { + if (!isset($this->messages[$domain])) { + $this->processDomain($domain); + } + } + + return $this->result; + } + + /** + * @param self::*_BATCH $batch + */ + public function moveMessagesToIntlDomainsIfPossible(string $batch = self::ALL_BATCH): void + { + // If MessageFormatter class does not exists, intl domains are not supported. + if (!class_exists(\MessageFormatter::class)) { + return; + } + + foreach ($this->getDomains() as $domain) { + $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; + $messages = match ($batch) { + self::OBSOLETE_BATCH => $this->getObsoleteMessages($domain), + self::NEW_BATCH => $this->getNewMessages($domain), + self::ALL_BATCH => $this->getMessages($domain), + default => throw new \InvalidArgumentException(sprintf('$batch argument must be one of ["%s", "%s", "%s"].', self::ALL_BATCH, self::NEW_BATCH, self::OBSOLETE_BATCH)), + }; + + if (!$messages || (!$this->source->all($intlDomain) && $this->source->all($domain))) { + continue; + } + + $result = $this->getResult(); + $allIntlMessages = $result->all($intlDomain); + $currentMessages = array_diff_key($messages, $result->all($domain)); + $result->replace($currentMessages, $domain); + $result->replace($allIntlMessages + $messages, $intlDomain); + } + } + + /** + * Performs operation on source and target catalogues for the given domain and + * stores the results. + * + * @param string $domain The domain which the operation will be performed for + * + * @return void + */ + abstract protected function processDomain(string $domain); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Catalogue/MergeOperation.php b/php/libraries/composer/vendor/symfony/translation/Catalogue/MergeOperation.php new file mode 100644 index 0000000..1b777a8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Catalogue/MergeOperation.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Catalogue; + +use Symfony\Component\Translation\MessageCatalogueInterface; + +/** + * Merge operation between two catalogues as follows: + * all = source ∪ target = {x: x ∈ source ∨ x ∈ target} + * new = all ∖ source = {x: x ∈ target ∧ x ∉ source} + * obsolete = source ∖ all = {x: x ∈ source ∧ x ∉ source ∧ x ∉ target} = ∅ + * Basically, the result contains messages from both catalogues. + * + * @author Jean-François Simon + */ +class MergeOperation extends AbstractOperation +{ + /** + * @return void + */ + protected function processDomain(string $domain) + { + $this->messages[$domain] = [ + 'all' => [], + 'new' => [], + 'obsolete' => [], + ]; + $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; + + foreach ($this->target->getCatalogueMetadata('', $domain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $domain)) { + $this->result->setCatalogueMetadata($key, $value, $domain); + } + } + + foreach ($this->target->getCatalogueMetadata('', $intlDomain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $intlDomain)) { + $this->result->setCatalogueMetadata($key, $value, $intlDomain); + } + } + + foreach ($this->source->all($domain) as $id => $message) { + $this->messages[$domain]['all'][$id] = $message; + $d = $this->source->defines($id, $intlDomain) ? $intlDomain : $domain; + $this->result->add([$id => $message], $d); + if (null !== $keyMetadata = $this->source->getMetadata($id, $d)) { + $this->result->setMetadata($id, $keyMetadata, $d); + } + } + + foreach ($this->target->all($domain) as $id => $message) { + if (!$this->source->has($id, $domain)) { + $this->messages[$domain]['all'][$id] = $message; + $this->messages[$domain]['new'][$id] = $message; + $d = $this->target->defines($id, $intlDomain) ? $intlDomain : $domain; + $this->result->add([$id => $message], $d); + if (null !== $keyMetadata = $this->target->getMetadata($id, $d)) { + $this->result->setMetadata($id, $keyMetadata, $d); + } + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Catalogue/OperationInterface.php b/php/libraries/composer/vendor/symfony/translation/Catalogue/OperationInterface.php new file mode 100644 index 0000000..1fe9534 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Catalogue/OperationInterface.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Catalogue; + +use Symfony\Component\Translation\MessageCatalogueInterface; + +/** + * Represents an operation on catalogue(s). + * + * An instance of this interface performs an operation on one or more catalogues and + * stores intermediate and final results of the operation. + * + * The first catalogue in its argument(s) is called the 'source catalogue' or 'source' and + * the following results are stored: + * + * Messages: also called 'all', are valid messages for the given domain after the operation is performed. + * + * New Messages: also called 'new' (new = all ∖ source = {x: x ∈ all ∧ x ∉ source}). + * + * Obsolete Messages: also called 'obsolete' (obsolete = source ∖ all = {x: x ∈ source ∧ x ∉ all}). + * + * Result: also called 'result', is the resulting catalogue for the given domain that holds the same messages as 'all'. + * + * @author Jean-François Simon + */ +interface OperationInterface +{ + /** + * Returns domains affected by operation. + */ + public function getDomains(): array; + + /** + * Returns all valid messages ('all') after operation. + */ + public function getMessages(string $domain): array; + + /** + * Returns new messages ('new') after operation. + */ + public function getNewMessages(string $domain): array; + + /** + * Returns obsolete messages ('obsolete') after operation. + */ + public function getObsoleteMessages(string $domain): array; + + /** + * Returns resulting catalogue ('result'). + */ + public function getResult(): MessageCatalogueInterface; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Catalogue/TargetOperation.php b/php/libraries/composer/vendor/symfony/translation/Catalogue/TargetOperation.php new file mode 100644 index 0000000..2c0ec72 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Catalogue/TargetOperation.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Catalogue; + +use Symfony\Component\Translation\MessageCatalogueInterface; + +/** + * Target operation between two catalogues: + * intersection = source ∩ target = {x: x ∈ source ∧ x ∈ target} + * all = intersection ∪ (target ∖ intersection) = target + * new = all ∖ source = {x: x ∈ target ∧ x ∉ source} + * obsolete = source ∖ all = source ∖ target = {x: x ∈ source ∧ x ∉ target} + * Basically, the result contains messages from the target catalogue. + * + * @author Michael Lee + */ +class TargetOperation extends AbstractOperation +{ + /** + * @return void + */ + protected function processDomain(string $domain) + { + $this->messages[$domain] = [ + 'all' => [], + 'new' => [], + 'obsolete' => [], + ]; + $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; + + foreach ($this->target->getCatalogueMetadata('', $domain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $domain)) { + $this->result->setCatalogueMetadata($key, $value, $domain); + } + } + + foreach ($this->target->getCatalogueMetadata('', $intlDomain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $intlDomain)) { + $this->result->setCatalogueMetadata($key, $value, $intlDomain); + } + } + + // For 'all' messages, the code can't be simplified as ``$this->messages[$domain]['all'] = $target->all($domain);``, + // because doing so will drop messages like {x: x ∈ source ∧ x ∉ target.all ∧ x ∈ target.fallback} + // + // For 'new' messages, the code can't be simplified as ``array_diff_assoc($this->target->all($domain), $this->source->all($domain));`` + // because doing so will not exclude messages like {x: x ∈ target ∧ x ∉ source.all ∧ x ∈ source.fallback} + // + // For 'obsolete' messages, the code can't be simplified as ``array_diff_assoc($this->source->all($domain), $this->target->all($domain))`` + // because doing so will not exclude messages like {x: x ∈ source ∧ x ∉ target.all ∧ x ∈ target.fallback} + + foreach ($this->source->all($domain) as $id => $message) { + if ($this->target->has($id, $domain)) { + $this->messages[$domain]['all'][$id] = $message; + $d = $this->source->defines($id, $intlDomain) ? $intlDomain : $domain; + $this->result->add([$id => $message], $d); + if (null !== $keyMetadata = $this->source->getMetadata($id, $d)) { + $this->result->setMetadata($id, $keyMetadata, $d); + } + } else { + $this->messages[$domain]['obsolete'][$id] = $message; + } + } + + foreach ($this->target->all($domain) as $id => $message) { + if (!$this->source->has($id, $domain)) { + $this->messages[$domain]['all'][$id] = $message; + $this->messages[$domain]['new'][$id] = $message; + $d = $this->target->defines($id, $intlDomain) ? $intlDomain : $domain; + $this->result->add([$id => $message], $d); + if (null !== $keyMetadata = $this->target->getMetadata($id, $d)) { + $this->result->setMetadata($id, $keyMetadata, $d); + } + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/CatalogueMetadataAwareInterface.php b/php/libraries/composer/vendor/symfony/translation/CatalogueMetadataAwareInterface.php new file mode 100644 index 0000000..c845959 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/CatalogueMetadataAwareInterface.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +/** + * This interface is used to get, set, and delete metadata about the Catalogue. + * + * @author Hugo Alliaume + */ +interface CatalogueMetadataAwareInterface +{ + /** + * Gets catalogue metadata for the given domain and key. + * + * Passing an empty domain will return an array with all catalogue metadata indexed by + * domain and then by key. Passing an empty key will return an array with all + * catalogue metadata for the given domain. + * + * @return mixed The value that was set or an array with the domains/keys or null + */ + public function getCatalogueMetadata(string $key = '', string $domain = 'messages'): mixed; + + /** + * Adds catalogue metadata to a message domain. + * + * @return void + */ + public function setCatalogueMetadata(string $key, mixed $value, string $domain = 'messages'); + + /** + * Deletes catalogue metadata for the given key and domain. + * + * Passing an empty domain will delete all catalogue metadata. Passing an empty key will + * delete all metadata for the given domain. + * + * @return void + */ + public function deleteCatalogueMetadata(string $key = '', string $domain = 'messages'); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Command/TranslationPullCommand.php b/php/libraries/composer/vendor/symfony/translation/Command/TranslationPullCommand.php new file mode 100644 index 0000000..5d9c092 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Command/TranslationPullCommand.php @@ -0,0 +1,184 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Command; + +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Translation\Catalogue\TargetOperation; +use Symfony\Component\Translation\MessageCatalogue; +use Symfony\Component\Translation\Provider\TranslationProviderCollection; +use Symfony\Component\Translation\Reader\TranslationReaderInterface; +use Symfony\Component\Translation\Writer\TranslationWriterInterface; + +/** + * @author Mathieu Santostefano + */ +#[AsCommand(name: 'translation:pull', description: 'Pull translations from a given provider.')] +final class TranslationPullCommand extends Command +{ + use TranslationTrait; + + private TranslationProviderCollection $providerCollection; + private TranslationWriterInterface $writer; + private TranslationReaderInterface $reader; + private string $defaultLocale; + private array $transPaths; + private array $enabledLocales; + + public function __construct(TranslationProviderCollection $providerCollection, TranslationWriterInterface $writer, TranslationReaderInterface $reader, string $defaultLocale, array $transPaths = [], array $enabledLocales = []) + { + $this->providerCollection = $providerCollection; + $this->writer = $writer; + $this->reader = $reader; + $this->defaultLocale = $defaultLocale; + $this->transPaths = $transPaths; + $this->enabledLocales = $enabledLocales; + + parent::__construct(); + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestArgumentValuesFor('provider')) { + $suggestions->suggestValues($this->providerCollection->keys()); + + return; + } + + if ($input->mustSuggestOptionValuesFor('domains')) { + $provider = $this->providerCollection->get($input->getArgument('provider')); + + if (method_exists($provider, 'getDomains')) { + $suggestions->suggestValues($provider->getDomains()); + } + + return; + } + + if ($input->mustSuggestOptionValuesFor('locales')) { + $suggestions->suggestValues($this->enabledLocales); + + return; + } + + if ($input->mustSuggestOptionValuesFor('format')) { + $suggestions->suggestValues(['php', 'xlf', 'xlf12', 'xlf20', 'po', 'mo', 'yml', 'yaml', 'ts', 'csv', 'json', 'ini', 'res']); + } + } + + protected function configure(): void + { + $keys = $this->providerCollection->keys(); + $defaultProvider = 1 === \count($keys) ? $keys[0] : null; + + $this + ->setDefinition([ + new InputArgument('provider', null !== $defaultProvider ? InputArgument::OPTIONAL : InputArgument::REQUIRED, 'The provider to pull translations from.', $defaultProvider), + new InputOption('force', null, InputOption::VALUE_NONE, 'Override existing translations with provider ones (it will delete not synchronized messages).'), + new InputOption('intl-icu', null, InputOption::VALUE_NONE, 'Associated to --force option, it will write messages in "%domain%+intl-icu.%locale%.xlf" files.'), + new InputOption('domains', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify the domains to pull.'), + new InputOption('locales', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify the locales to pull.'), + new InputOption('format', null, InputOption::VALUE_OPTIONAL, 'Override the default output format.', 'xlf12'), + new InputOption('as-tree', null, InputOption::VALUE_OPTIONAL, 'Write messages as a tree-like structure. Needs --format=yaml. The given value defines the level where to switch to inline YAML'), + ]) + ->setHelp(<<<'EOF' +The %command.name% command pulls translations from the given provider. Only +new translations are pulled, existing ones are not overwritten. + +You can overwrite existing translations (and remove the missing ones on local side) by using the --force flag: + + php %command.full_name% --force provider + +Full example: + + php %command.full_name% provider --force --domains=messages --domains=validators --locales=en + +This command pulls all translations associated with the messages and validators domains for the en locale. +Local translations for the specified domains and locale are deleted if they're not present on the provider and overwritten if it's the case. +Local translations for others domains and locales are ignored. +EOF + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $provider = $this->providerCollection->get($input->getArgument('provider')); + $force = $input->getOption('force'); + $intlIcu = $input->getOption('intl-icu'); + $locales = $input->getOption('locales') ?: $this->enabledLocales; + $domains = $input->getOption('domains'); + $format = $input->getOption('format'); + $asTree = (int) $input->getOption('as-tree'); + $xliffVersion = '1.2'; + + if ($intlIcu && !$force) { + $io->note('--intl-icu option only has an effect when used with --force. Here, it will be ignored.'); + } + + switch ($format) { + case 'xlf20': $xliffVersion = '2.0'; + // no break + case 'xlf12': $format = 'xlf'; + } + + $writeOptions = [ + 'path' => end($this->transPaths), + 'xliff_version' => $xliffVersion, + 'default_locale' => $this->defaultLocale, + 'as_tree' => (bool) $asTree, + 'inline' => $asTree, + ]; + + if (!$domains) { + $domains = $provider->getDomains(); + } + + $providerTranslations = $provider->read($domains, $locales); + + if ($force) { + foreach ($providerTranslations->getCatalogues() as $catalogue) { + $operation = new TargetOperation(new MessageCatalogue($catalogue->getLocale()), $catalogue); + if ($intlIcu) { + $operation->moveMessagesToIntlDomainsIfPossible(); + } + $this->writer->write($operation->getResult(), $format, $writeOptions); + } + + $io->success(sprintf('Local translations has been updated from "%s" (for "%s" locale(s), and "%s" domain(s)).', parse_url($provider, \PHP_URL_SCHEME), implode(', ', $locales), implode(', ', $domains))); + + return 0; + } + + $localTranslations = $this->readLocalTranslations($locales, $domains, $this->transPaths); + + // Append pulled translations to local ones. + $localTranslations->addBag($providerTranslations->diff($localTranslations)); + + foreach ($localTranslations->getCatalogues() as $catalogue) { + $this->writer->write($catalogue, $format, $writeOptions); + } + + $io->success(sprintf('New translations from "%s" has been written locally (for "%s" locale(s), and "%s" domain(s)).', parse_url($provider, \PHP_URL_SCHEME), implode(', ', $locales), implode(', ', $domains))); + + return 0; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Command/TranslationPushCommand.php b/php/libraries/composer/vendor/symfony/translation/Command/TranslationPushCommand.php new file mode 100644 index 0000000..1d04adb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Command/TranslationPushCommand.php @@ -0,0 +1,182 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Command; + +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Translation\Provider\FilteringProvider; +use Symfony\Component\Translation\Provider\TranslationProviderCollection; +use Symfony\Component\Translation\Reader\TranslationReaderInterface; +use Symfony\Component\Translation\TranslatorBag; + +/** + * @author Mathieu Santostefano + */ +#[AsCommand(name: 'translation:push', description: 'Push translations to a given provider.')] +final class TranslationPushCommand extends Command +{ + use TranslationTrait; + + private TranslationProviderCollection $providers; + private TranslationReaderInterface $reader; + private array $transPaths; + private array $enabledLocales; + + public function __construct(TranslationProviderCollection $providers, TranslationReaderInterface $reader, array $transPaths = [], array $enabledLocales = []) + { + $this->providers = $providers; + $this->reader = $reader; + $this->transPaths = $transPaths; + $this->enabledLocales = $enabledLocales; + + parent::__construct(); + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestArgumentValuesFor('provider')) { + $suggestions->suggestValues($this->providers->keys()); + + return; + } + + if ($input->mustSuggestOptionValuesFor('domains')) { + $provider = $this->providers->get($input->getArgument('provider')); + + if ($provider && method_exists($provider, 'getDomains')) { + $domains = $provider->getDomains(); + $suggestions->suggestValues($domains); + } + + return; + } + + if ($input->mustSuggestOptionValuesFor('locales')) { + $suggestions->suggestValues($this->enabledLocales); + } + } + + protected function configure(): void + { + $keys = $this->providers->keys(); + $defaultProvider = 1 === \count($keys) ? $keys[0] : null; + + $this + ->setDefinition([ + new InputArgument('provider', null !== $defaultProvider ? InputArgument::OPTIONAL : InputArgument::REQUIRED, 'The provider to push translations to.', $defaultProvider), + new InputOption('force', null, InputOption::VALUE_NONE, 'Override existing translations with local ones (it will delete not synchronized messages).'), + new InputOption('delete-missing', null, InputOption::VALUE_NONE, 'Delete translations available on provider but not locally.'), + new InputOption('domains', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify the domains to push.'), + new InputOption('locales', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify the locales to push.', $this->enabledLocales), + ]) + ->setHelp(<<<'EOF' +The %command.name% command pushes translations to the given provider. Only new +translations are pushed, existing ones are not overwritten. + +You can overwrite existing translations by using the --force flag: + + php %command.full_name% --force provider + +You can delete provider translations which are not present locally by using the --delete-missing flag: + + php %command.full_name% --delete-missing provider + +Full example: + + php %command.full_name% provider --force --delete-missing --domains=messages --domains=validators --locales=en + +This command pushes all translations associated with the messages and validators domains for the en locale. +Provider translations for the specified domains and locale are deleted if they're not present locally and overwritten if it's the case. +Provider translations for others domains and locales are ignored. +EOF + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $provider = $this->providers->get($input->getArgument('provider')); + + if (!$this->enabledLocales) { + throw new InvalidArgumentException(sprintf('You must define "framework.enabled_locales" or "framework.translator.providers.%s.locales" config key in order to work with translation providers.', parse_url($provider, \PHP_URL_SCHEME))); + } + + $io = new SymfonyStyle($input, $output); + $domains = $input->getOption('domains'); + $locales = $input->getOption('locales'); + $force = $input->getOption('force'); + $deleteMissing = $input->getOption('delete-missing'); + + if (!$domains && $provider instanceof FilteringProvider) { + $domains = $provider->getDomains(); + } + + // Reading local translations must be done after retrieving the domains from the provider + // in order to manage only translations from configured domains + $localTranslations = $this->readLocalTranslations($locales, $domains, $this->transPaths); + + if (!$domains) { + $domains = $this->getDomainsFromTranslatorBag($localTranslations); + } + + if (!$deleteMissing && $force) { + $provider->write($localTranslations); + + $io->success(sprintf('All local translations has been sent to "%s" (for "%s" locale(s), and "%s" domain(s)).', parse_url($provider, \PHP_URL_SCHEME), implode(', ', $locales), implode(', ', $domains))); + + return 0; + } + + $providerTranslations = $provider->read($domains, $locales); + + if ($deleteMissing) { + $provider->delete($providerTranslations->diff($localTranslations)); + + $io->success(sprintf('Missing translations on "%s" has been deleted (for "%s" locale(s), and "%s" domain(s)).', parse_url($provider, \PHP_URL_SCHEME), implode(', ', $locales), implode(', ', $domains))); + + // Read provider translations again, after missing translations deletion, + // to avoid push freshly deleted translations. + $providerTranslations = $provider->read($domains, $locales); + } + + $translationsToWrite = $localTranslations->diff($providerTranslations); + + if ($force) { + $translationsToWrite->addBag($localTranslations->intersect($providerTranslations)); + } + + $provider->write($translationsToWrite); + + $io->success(sprintf('%s local translations has been sent to "%s" (for "%s" locale(s), and "%s" domain(s)).', $force ? 'All' : 'New', parse_url($provider, \PHP_URL_SCHEME), implode(', ', $locales), implode(', ', $domains))); + + return 0; + } + + private function getDomainsFromTranslatorBag(TranslatorBag $translatorBag): array + { + $domains = []; + + foreach ($translatorBag->getCatalogues() as $catalogue) { + $domains += $catalogue->getDomains(); + } + + return array_unique($domains); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Command/TranslationTrait.php b/php/libraries/composer/vendor/symfony/translation/Command/TranslationTrait.php new file mode 100644 index 0000000..eafaffd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Command/TranslationTrait.php @@ -0,0 +1,77 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Command; + +use Symfony\Component\Translation\MessageCatalogue; +use Symfony\Component\Translation\MessageCatalogueInterface; +use Symfony\Component\Translation\TranslatorBag; + +/** + * @internal + */ +trait TranslationTrait +{ + private function readLocalTranslations(array $locales, array $domains, array $transPaths): TranslatorBag + { + $bag = new TranslatorBag(); + + foreach ($locales as $locale) { + $catalogue = new MessageCatalogue($locale); + foreach ($transPaths as $path) { + $this->reader->read($path, $catalogue); + } + + if ($domains) { + foreach ($domains as $domain) { + $bag->addCatalogue($this->filterCatalogue($catalogue, $domain)); + } + } else { + $bag->addCatalogue($catalogue); + } + } + + return $bag; + } + + private function filterCatalogue(MessageCatalogue $catalogue, string $domain): MessageCatalogue + { + $filteredCatalogue = new MessageCatalogue($catalogue->getLocale()); + + // extract intl-icu messages only + $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; + if ($intlMessages = $catalogue->all($intlDomain)) { + $filteredCatalogue->add($intlMessages, $intlDomain); + } + + // extract all messages and subtract intl-icu messages + if ($messages = array_diff($catalogue->all($domain), $intlMessages)) { + $filteredCatalogue->add($messages, $domain); + } + foreach ($catalogue->getResources() as $resource) { + $filteredCatalogue->addResource($resource); + } + + if ($metadata = $catalogue->getMetadata('', $intlDomain)) { + foreach ($metadata as $k => $v) { + $filteredCatalogue->setMetadata($k, $v, $intlDomain); + } + } + + if ($metadata = $catalogue->getMetadata('', $domain)) { + foreach ($metadata as $k => $v) { + $filteredCatalogue->setMetadata($k, $v, $domain); + } + } + + return $filteredCatalogue; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Command/XliffLintCommand.php b/php/libraries/composer/vendor/symfony/translation/Command/XliffLintCommand.php new file mode 100644 index 0000000..ba94638 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Command/XliffLintCommand.php @@ -0,0 +1,285 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Command; + +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\CI\GithubActionReporter; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Util\XliffUtils; + +/** + * Validates XLIFF files syntax and outputs encountered errors. + * + * @author Grégoire Pineau + * @author Robin Chalas + * @author Javier Eguiluz + */ +#[AsCommand(name: 'lint:xliff', description: 'Lint an XLIFF file and outputs encountered errors')] +class XliffLintCommand extends Command +{ + private string $format; + private bool $displayCorrectFiles; + private ?\Closure $directoryIteratorProvider; + private ?\Closure $isReadableProvider; + private bool $requireStrictFileNames; + + public function __construct(?string $name = null, ?callable $directoryIteratorProvider = null, ?callable $isReadableProvider = null, bool $requireStrictFileNames = true) + { + parent::__construct($name); + + $this->directoryIteratorProvider = null === $directoryIteratorProvider ? null : $directoryIteratorProvider(...); + $this->isReadableProvider = null === $isReadableProvider ? null : $isReadableProvider(...); + $this->requireStrictFileNames = $requireStrictFileNames; + } + + /** + * @return void + */ + protected function configure() + { + $this + ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN') + ->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions()))) + ->setHelp(<<%command.name% command lints an XLIFF file and outputs to STDOUT +the first encountered syntax error. + +You can validates XLIFF contents passed from STDIN: + + cat filename | php %command.full_name% - + +You can also validate the syntax of a file: + + php %command.full_name% filename + +Or of a whole directory: + + php %command.full_name% dirname + php %command.full_name% dirname --format=json + +EOF + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $filenames = (array) $input->getArgument('filename'); + $this->format = $input->getOption('format') ?? (GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt'); + $this->displayCorrectFiles = $output->isVerbose(); + + if (['-'] === $filenames) { + return $this->display($io, [$this->validate(file_get_contents('php://stdin'))]); + } + + if (!$filenames) { + throw new RuntimeException('Please provide a filename or pipe file content to STDIN.'); + } + + $filesInfo = []; + foreach ($filenames as $filename) { + if (!$this->isReadable($filename)) { + throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename)); + } + + foreach ($this->getFiles($filename) as $file) { + $filesInfo[] = $this->validate(file_get_contents($file), $file); + } + } + + return $this->display($io, $filesInfo); + } + + private function validate(string $content, ?string $file = null): array + { + $errors = []; + + // Avoid: Warning DOMDocument::loadXML(): Empty string supplied as input + if ('' === trim($content)) { + return ['file' => $file, 'valid' => true]; + } + + $internal = libxml_use_internal_errors(true); + + $document = new \DOMDocument(); + $document->loadXML($content); + + if (null !== $targetLanguage = $this->getTargetLanguageFromFile($document)) { + $normalizedLocalePattern = sprintf('(%s|%s)', preg_quote($targetLanguage, '/'), preg_quote(str_replace('-', '_', $targetLanguage), '/')); + // strict file names require translation files to be named '____.locale.xlf' + // otherwise, both '____.locale.xlf' and 'locale.____.xlf' are allowed + // also, the regexp matching must be case-insensitive, as defined for 'target-language' values + // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#target-language + $expectedFilenamePattern = $this->requireStrictFileNames ? sprintf('/^.*\.(?i:%s)\.(?:xlf|xliff)/', $normalizedLocalePattern) : sprintf('/^(?:.*\.(?i:%s)|(?i:%s)\..*)\.(?:xlf|xliff)/', $normalizedLocalePattern, $normalizedLocalePattern); + + if (0 === preg_match($expectedFilenamePattern, basename($file))) { + $errors[] = [ + 'line' => -1, + 'column' => -1, + 'message' => sprintf('There is a mismatch between the language included in the file name ("%s") and the "%s" value used in the "target-language" attribute of the file.', basename($file), $targetLanguage), + ]; + } + } + + foreach (XliffUtils::validateSchema($document) as $xmlError) { + $errors[] = [ + 'line' => $xmlError['line'], + 'column' => $xmlError['column'], + 'message' => $xmlError['message'], + ]; + } + + libxml_clear_errors(); + libxml_use_internal_errors($internal); + + return ['file' => $file, 'valid' => 0 === \count($errors), 'messages' => $errors]; + } + + private function display(SymfonyStyle $io, array $files): int + { + return match ($this->format) { + 'txt' => $this->displayTxt($io, $files), + 'json' => $this->displayJson($io, $files), + 'github' => $this->displayTxt($io, $files, true), + default => throw new InvalidArgumentException(sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions()))), + }; + } + + private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int + { + $countFiles = \count($filesInfo); + $erroredFiles = 0; + $githubReporter = $errorAsGithubAnnotations ? new GithubActionReporter($io) : null; + + foreach ($filesInfo as $info) { + if ($info['valid'] && $this->displayCorrectFiles) { + $io->comment('OK'.($info['file'] ? sprintf(' in %s', $info['file']) : '')); + } elseif (!$info['valid']) { + ++$erroredFiles; + $io->text(' ERROR '.($info['file'] ? sprintf(' in %s', $info['file']) : '')); + $io->listing(array_map(function ($error) use ($info, $githubReporter) { + // general document errors have a '-1' line number + $line = -1 === $error['line'] ? null : $error['line']; + + $githubReporter?->error($error['message'], $info['file'], $line, null !== $line ? $error['column'] : null); + + return null === $line ? $error['message'] : sprintf('Line %d, Column %d: %s', $line, $error['column'], $error['message']); + }, $info['messages'])); + } + } + + if (0 === $erroredFiles) { + $io->success(sprintf('All %d XLIFF files contain valid syntax.', $countFiles)); + } else { + $io->warning(sprintf('%d XLIFF files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles)); + } + + return min($erroredFiles, 1); + } + + private function displayJson(SymfonyStyle $io, array $filesInfo): int + { + $errors = 0; + + array_walk($filesInfo, function (&$v) use (&$errors) { + $v['file'] = (string) $v['file']; + if (!$v['valid']) { + ++$errors; + } + }); + + $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)); + + return min($errors, 1); + } + + /** + * @return iterable<\SplFileInfo> + */ + private function getFiles(string $fileOrDirectory): iterable + { + if (is_file($fileOrDirectory)) { + yield new \SplFileInfo($fileOrDirectory); + + return; + } + + foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) { + if (!\in_array($file->getExtension(), ['xlf', 'xliff'])) { + continue; + } + + yield $file; + } + } + + /** + * @return iterable<\SplFileInfo> + */ + private function getDirectoryIterator(string $directory): iterable + { + $default = fn ($directory) => new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), + \RecursiveIteratorIterator::LEAVES_ONLY + ); + + if (null !== $this->directoryIteratorProvider) { + return ($this->directoryIteratorProvider)($directory, $default); + } + + return $default($directory); + } + + private function isReadable(string $fileOrDirectory): bool + { + $default = fn ($fileOrDirectory) => is_readable($fileOrDirectory); + + if (null !== $this->isReadableProvider) { + return ($this->isReadableProvider)($fileOrDirectory, $default); + } + + return $default($fileOrDirectory); + } + + private function getTargetLanguageFromFile(\DOMDocument $xliffContents): ?string + { + foreach ($xliffContents->getElementsByTagName('file')[0]->attributes ?? [] as $attribute) { + if ('target-language' === $attribute->nodeName) { + return $attribute->nodeValue; + } + } + + return null; + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestOptionValuesFor('format')) { + $suggestions->suggestValues($this->getAvailableFormatOptions()); + } + } + + private function getAvailableFormatOptions(): array + { + return ['txt', 'json', 'github']; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DataCollector/TranslationDataCollector.php b/php/libraries/composer/vendor/symfony/translation/DataCollector/TranslationDataCollector.php new file mode 100644 index 0000000..d4f49cc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DataCollector/TranslationDataCollector.php @@ -0,0 +1,148 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\DataCollector; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\DataCollector\DataCollector; +use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface; +use Symfony\Component\Translation\DataCollectorTranslator; +use Symfony\Component\VarDumper\Cloner\Data; + +/** + * @author Abdellatif Ait boudad + * + * @final + */ +class TranslationDataCollector extends DataCollector implements LateDataCollectorInterface +{ + private DataCollectorTranslator $translator; + + public function __construct(DataCollectorTranslator $translator) + { + $this->translator = $translator; + } + + public function lateCollect(): void + { + $messages = $this->sanitizeCollectedMessages($this->translator->getCollectedMessages()); + + $this->data += $this->computeCount($messages); + $this->data['messages'] = $messages; + + $this->data = $this->cloneVar($this->data); + } + + public function collect(Request $request, Response $response, ?\Throwable $exception = null): void + { + $this->data['locale'] = $this->translator->getLocale(); + $this->data['fallback_locales'] = $this->translator->getFallbackLocales(); + } + + public function reset(): void + { + $this->data = []; + } + + public function getMessages(): array|Data + { + return $this->data['messages'] ?? []; + } + + public function getCountMissings(): int + { + return $this->data[DataCollectorTranslator::MESSAGE_MISSING] ?? 0; + } + + public function getCountFallbacks(): int + { + return $this->data[DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK] ?? 0; + } + + public function getCountDefines(): int + { + return $this->data[DataCollectorTranslator::MESSAGE_DEFINED] ?? 0; + } + + public function getLocale(): ?string + { + return !empty($this->data['locale']) ? $this->data['locale'] : null; + } + + /** + * @internal + */ + public function getFallbackLocales(): Data|array + { + return (isset($this->data['fallback_locales']) && \count($this->data['fallback_locales']) > 0) ? $this->data['fallback_locales'] : []; + } + + public function getName(): string + { + return 'translation'; + } + + private function sanitizeCollectedMessages(array $messages): array + { + $result = []; + foreach ($messages as $key => $message) { + $messageId = $message['locale'].$message['domain'].$message['id']; + + if (!isset($result[$messageId])) { + $message['count'] = 1; + $message['parameters'] = !empty($message['parameters']) ? [$message['parameters']] : []; + $messages[$key]['translation'] = $this->sanitizeString($message['translation']); + $result[$messageId] = $message; + } else { + if (!empty($message['parameters'])) { + $result[$messageId]['parameters'][] = $message['parameters']; + } + + ++$result[$messageId]['count']; + } + + unset($messages[$key]); + } + + return $result; + } + + private function computeCount(array $messages): array + { + $count = [ + DataCollectorTranslator::MESSAGE_DEFINED => 0, + DataCollectorTranslator::MESSAGE_MISSING => 0, + DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK => 0, + ]; + + foreach ($messages as $message) { + ++$count[$message['state']]; + } + + return $count; + } + + private function sanitizeString(string $string, int $length = 80): string + { + $string = trim(preg_replace('/\s+/', ' ', $string)); + + if (false !== $encoding = mb_detect_encoding($string, null, true)) { + if (mb_strlen($string, $encoding) > $length) { + return mb_substr($string, 0, $length - 3, $encoding).'...'; + } + } elseif (\strlen($string) > $length) { + return substr($string, 0, $length - 3).'...'; + } + + return $string; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DataCollectorTranslator.php b/php/libraries/composer/vendor/symfony/translation/DataCollectorTranslator.php new file mode 100644 index 0000000..a2832ee --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DataCollectorTranslator.php @@ -0,0 +1,143 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface; +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Contracts\Translation\LocaleAwareInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +/** + * @author Abdellatif Ait boudad + */ +class DataCollectorTranslator implements TranslatorInterface, TranslatorBagInterface, LocaleAwareInterface, WarmableInterface +{ + public const MESSAGE_DEFINED = 0; + public const MESSAGE_MISSING = 1; + public const MESSAGE_EQUALS_FALLBACK = 2; + + private TranslatorInterface $translator; + private array $messages = []; + + /** + * @param TranslatorInterface&TranslatorBagInterface&LocaleAwareInterface $translator + */ + public function __construct(TranslatorInterface $translator) + { + if (!$translator instanceof TranslatorBagInterface || !$translator instanceof LocaleAwareInterface) { + throw new InvalidArgumentException(sprintf('The Translator "%s" must implement TranslatorInterface, TranslatorBagInterface and LocaleAwareInterface.', get_debug_type($translator))); + } + + $this->translator = $translator; + } + + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + $trans = $this->translator->trans($id = (string) $id, $parameters, $domain, $locale); + $this->collectMessage($locale, $domain, $id, $trans, $parameters); + + return $trans; + } + + /** + * @return void + */ + public function setLocale(string $locale) + { + $this->translator->setLocale($locale); + } + + public function getLocale(): string + { + return $this->translator->getLocale(); + } + + public function getCatalogue(?string $locale = null): MessageCatalogueInterface + { + return $this->translator->getCatalogue($locale); + } + + public function getCatalogues(): array + { + return $this->translator->getCatalogues(); + } + + public function warmUp(string $cacheDir, ?string $buildDir = null): array + { + if ($this->translator instanceof WarmableInterface) { + return (array) $this->translator->warmUp($cacheDir, $buildDir); + } + + return []; + } + + /** + * Gets the fallback locales. + */ + public function getFallbackLocales(): array + { + if ($this->translator instanceof Translator || method_exists($this->translator, 'getFallbackLocales')) { + return $this->translator->getFallbackLocales(); + } + + return []; + } + + /** + * @return mixed + */ + public function __call(string $method, array $args) + { + return $this->translator->{$method}(...$args); + } + + public function getCollectedMessages(): array + { + return $this->messages; + } + + private function collectMessage(?string $locale, ?string $domain, string $id, string $translation, ?array $parameters = []): void + { + $domain ??= 'messages'; + + $catalogue = $this->translator->getCatalogue($locale); + $locale = $catalogue->getLocale(); + $fallbackLocale = null; + if ($catalogue->defines($id, $domain)) { + $state = self::MESSAGE_DEFINED; + } elseif ($catalogue->has($id, $domain)) { + $state = self::MESSAGE_EQUALS_FALLBACK; + + $fallbackCatalogue = $catalogue->getFallbackCatalogue(); + while ($fallbackCatalogue) { + if ($fallbackCatalogue->defines($id, $domain)) { + $fallbackLocale = $fallbackCatalogue->getLocale(); + break; + } + $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue(); + } + } else { + $state = self::MESSAGE_MISSING; + } + + $this->messages[] = [ + 'locale' => $locale, + 'fallbackLocale' => $fallbackLocale, + 'domain' => $domain, + 'id' => $id, + 'translation' => $translation, + 'parameters' => $parameters, + 'state' => $state, + 'transChoiceNumber' => isset($parameters['%count%']) && is_numeric($parameters['%count%']) ? $parameters['%count%'] : null, + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DependencyInjection/DataCollectorTranslatorPass.php b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/DataCollectorTranslatorPass.php new file mode 100644 index 0000000..cdf63be --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/DataCollectorTranslatorPass.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\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\Translation\TranslatorBagInterface; + +/** + * @author Christian Flothmann + */ +class DataCollectorTranslatorPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + if (!$container->has('translator')) { + return; + } + + $translatorClass = $container->getParameterBag()->resolveValue($container->findDefinition('translator')->getClass()); + + if (!is_subclass_of($translatorClass, TranslatorBagInterface::class)) { + $container->removeDefinition('translator.data_collector'); + $container->removeDefinition('data_collector.translation'); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DependencyInjection/LoggingTranslatorPass.php b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/LoggingTranslatorPass.php new file mode 100644 index 0000000..c21552f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/LoggingTranslatorPass.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\Translation\TranslatorBagInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +/** + * @author Abdellatif Ait boudad + */ +class LoggingTranslatorPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + if (!$container->hasAlias('logger') || !$container->hasAlias('translator')) { + return; + } + + if (!$container->hasParameter('translator.logging') || !$container->getParameter('translator.logging')) { + return; + } + + $translatorAlias = $container->getAlias('translator'); + $definition = $container->getDefinition((string) $translatorAlias); + $class = $container->getParameterBag()->resolveValue($definition->getClass()); + + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $translatorAlias)); + } + + if (!$r->isSubclassOf(TranslatorInterface::class) || !$r->isSubclassOf(TranslatorBagInterface::class)) { + return; + } + + $container->getDefinition('translator.logging')->setDecoratedService('translator'); + $warmer = $container->getDefinition('translation.warmer'); + $subscriberAttributes = $warmer->getTag('container.service_subscriber'); + $warmer->clearTag('container.service_subscriber'); + + foreach ($subscriberAttributes as $k => $v) { + if ((!isset($v['id']) || 'translator' !== $v['id']) && (!isset($v['key']) || 'translator' !== $v['key'])) { + $warmer->addTag('container.service_subscriber', $v); + } + } + $warmer->addTag('container.service_subscriber', ['key' => 'translator', 'id' => 'translator.logging.inner']); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.php b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.php new file mode 100644 index 0000000..2ece6ac --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.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\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Adds tagged translation.formatter services to translation writer. + */ +class TranslationDumperPass implements CompilerPassInterface +{ + /** + * @return void + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition('translation.writer')) { + return; + } + + $definition = $container->getDefinition('translation.writer'); + + foreach ($container->findTaggedServiceIds('translation.dumper', true) as $id => $attributes) { + $definition->addMethodCall('addDumper', [$attributes[0]['alias'], new Reference($id)]); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php new file mode 100644 index 0000000..1baf934 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Adds tagged translation.extractor services to translation extractor. + */ +class TranslationExtractorPass implements CompilerPassInterface +{ + /** + * @return void + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition('translation.extractor')) { + return; + } + + $definition = $container->getDefinition('translation.extractor'); + + foreach ($container->findTaggedServiceIds('translation.extractor', true) as $id => $attributes) { + if (!isset($attributes[0]['alias'])) { + throw new RuntimeException(sprintf('The alias for the tag "translation.extractor" of service "%s" must be set.', $id)); + } + + $definition->addMethodCall('addExtractor', [$attributes[0]['alias'], new Reference($id)]); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslatorPass.php b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslatorPass.php new file mode 100644 index 0000000..dd6ea3c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslatorPass.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 Symfony\Component\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +class TranslatorPass implements CompilerPassInterface +{ + /** + * @return void + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition('translator.default')) { + return; + } + + $loaders = []; + $loaderRefs = []; + foreach ($container->findTaggedServiceIds('translation.loader', true) as $id => $attributes) { + $loaderRefs[$id] = new Reference($id); + $loaders[$id][] = $attributes[0]['alias']; + if (isset($attributes[0]['legacy-alias'])) { + $loaders[$id][] = $attributes[0]['legacy-alias']; + } + } + + if ($container->hasDefinition('translation.reader')) { + $definition = $container->getDefinition('translation.reader'); + foreach ($loaders as $id => $formats) { + foreach ($formats as $format) { + $definition->addMethodCall('addLoader', [$format, $loaderRefs[$id]]); + } + } + } + + $container + ->findDefinition('translator.default') + ->replaceArgument(0, ServiceLocatorTagPass::register($container, $loaderRefs)) + ->replaceArgument(3, $loaders) + ; + + if ($container->hasDefinition('validator') && $container->hasDefinition('translation.extractor.visitor.constraint')) { + $constraintVisitorDefinition = $container->getDefinition('translation.extractor.visitor.constraint'); + $constraintClassNames = []; + + foreach ($container->getDefinitions() as $definition) { + if (!$definition->hasTag('validator.constraint_validator')) { + continue; + } + // Resolve constraint validator FQCN even if defined as %foo.validator.class% parameter + $className = $container->getParameterBag()->resolveValue($definition->getClass()); + // Extraction of the constraint class name from the Constraint Validator FQCN + $constraintClassNames[] = str_replace('Validator', '', substr(strrchr($className, '\\'), 1)); + } + + $constraintVisitorDefinition->setArgument(0, $constraintClassNames); + } + + if (!$container->hasParameter('twig.default_path')) { + return; + } + + $paths = array_keys($container->getDefinition('twig.template_iterator')->getArgument(1)); + if ($container->hasDefinition('console.command.translation_debug')) { + $definition = $container->getDefinition('console.command.translation_debug'); + $definition->replaceArgument(4, $container->getParameter('twig.default_path')); + + if (\count($definition->getArguments()) > 6) { + $definition->replaceArgument(6, $paths); + } + } + if ($container->hasDefinition('console.command.translation_extract')) { + $definition = $container->getDefinition('console.command.translation_extract'); + $definition->replaceArgument(5, $container->getParameter('twig.default_path')); + + if (\count($definition->getArguments()) > 7) { + $definition->replaceArgument(7, $paths); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php new file mode 100644 index 0000000..1756e3c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\AbstractRecursivePass; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\ServiceLocator; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\TraceableValueResolver; + +/** + * @author Yonel Ceruto + */ +class TranslatorPathsPass extends AbstractRecursivePass +{ + protected bool $skipScalars = true; + + private int $level = 0; + + /** + * @var array + */ + private array $paths = []; + + /** + * @var array + */ + private array $definitions = []; + + /** + * @var array> + */ + private array $controllers = []; + + /** + * @return void + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition('translator')) { + return; + } + + foreach ($this->findControllerArguments($container) as $controller => $argument) { + $id = substr($controller, 0, strpos($controller, ':') ?: \strlen($controller)); + if ($container->hasDefinition($id)) { + [$locatorRef] = $argument->getValues(); + $this->controllers[(string) $locatorRef][$container->getDefinition($id)->getClass()] = true; + } + } + + try { + parent::process($container); + + $paths = []; + foreach ($this->paths as $class => $_) { + if (($r = $container->getReflectionClass($class)) && !$r->isInterface()) { + $paths[] = $r->getFileName(); + foreach ($r->getTraits() as $trait) { + $paths[] = $trait->getFileName(); + } + } + } + if ($paths) { + if ($container->hasDefinition('console.command.translation_debug')) { + $definition = $container->getDefinition('console.command.translation_debug'); + $definition->replaceArgument(6, array_merge($definition->getArgument(6), $paths)); + } + if ($container->hasDefinition('console.command.translation_extract')) { + $definition = $container->getDefinition('console.command.translation_extract'); + $definition->replaceArgument(7, array_merge($definition->getArgument(7), $paths)); + } + } + } finally { + $this->level = 0; + $this->paths = []; + $this->definitions = []; + } + } + + protected function processValue(mixed $value, bool $isRoot = false): mixed + { + if ($value instanceof Reference) { + if ('translator' === (string) $value) { + for ($i = $this->level - 1; $i >= 0; --$i) { + $class = $this->definitions[$i]->getClass(); + + if (ServiceLocator::class === $class) { + if (!isset($this->controllers[$this->currentId])) { + continue; + } + foreach ($this->controllers[$this->currentId] as $class => $_) { + $this->paths[$class] = true; + } + } else { + $this->paths[$class] = true; + } + + break; + } + } + + return $value; + } + + if ($value instanceof Definition) { + $this->definitions[$this->level++] = $value; + $value = parent::processValue($value, $isRoot); + unset($this->definitions[--$this->level]); + + return $value; + } + + return parent::processValue($value, $isRoot); + } + + private function findControllerArguments(ContainerBuilder $container): array + { + if (!$container->has('argument_resolver.service')) { + return []; + } + $resolverDef = $container->findDefinition('argument_resolver.service'); + + if (TraceableValueResolver::class === $resolverDef->getClass()) { + $resolverDef = $container->getDefinition($resolverDef->getArgument(0)); + } + + $argument = $resolverDef->getArgument(0); + if ($argument instanceof Reference) { + $argument = $container->getDefinition($argument); + } + + return $argument->getArgument(0); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/CsvFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/CsvFileDumper.php new file mode 100644 index 0000000..8f54752 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/CsvFileDumper.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * CsvFileDumper generates a csv formatted string representation of a message catalogue. + * + * @author Stealth35 + */ +class CsvFileDumper extends FileDumper +{ + private string $delimiter = ';'; + private string $enclosure = '"'; + + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $handle = fopen('php://memory', 'r+'); + + foreach ($messages->all($domain) as $source => $target) { + fputcsv($handle, [$source, $target], $this->delimiter, $this->enclosure); + } + + rewind($handle); + $output = stream_get_contents($handle); + fclose($handle); + + return $output; + } + + /** + * Sets the delimiter and escape character for CSV. + * + * @return void + */ + public function setCsvControl(string $delimiter = ';', string $enclosure = '"') + { + $this->delimiter = $delimiter; + $this->enclosure = $enclosure; + } + + protected function getExtension(): string + { + return 'csv'; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/DumperInterface.php b/php/libraries/composer/vendor/symfony/translation/Dumper/DumperInterface.php new file mode 100644 index 0000000..6bf4293 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/DumperInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * DumperInterface is the interface implemented by all translation dumpers. + * There is no common option. + * + * @author Michel Salib + */ +interface DumperInterface +{ + /** + * Dumps the message catalogue. + * + * @param array $options Options that are used by the dumper + * + * @return void + */ + public function dump(MessageCatalogue $messages, array $options = []); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/FileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/FileDumper.php new file mode 100644 index 0000000..e30d477 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/FileDumper.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\RuntimeException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * FileDumper is an implementation of DumperInterface that dump a message catalogue to file(s). + * + * Options: + * - path (mandatory): the directory where the files should be saved + * + * @author Michel Salib + */ +abstract class FileDumper implements DumperInterface +{ + /** + * A template for the relative paths to files. + * + * @var string + */ + protected $relativePathTemplate = '%domain%.%locale%.%extension%'; + + /** + * Sets the template for the relative paths to files. + * + * @return void + */ + public function setRelativePathTemplate(string $relativePathTemplate) + { + $this->relativePathTemplate = $relativePathTemplate; + } + + /** + * @return void + */ + public function dump(MessageCatalogue $messages, array $options = []) + { + if (!\array_key_exists('path', $options)) { + throw new InvalidArgumentException('The file dumper needs a path option.'); + } + + // save a file for each domain + foreach ($messages->getDomains() as $domain) { + $fullpath = $options['path'].'/'.$this->getRelativePath($domain, $messages->getLocale()); + if (!file_exists($fullpath)) { + $directory = \dirname($fullpath); + if (!file_exists($directory) && !@mkdir($directory, 0777, true)) { + throw new RuntimeException(sprintf('Unable to create directory "%s".', $directory)); + } + } + + $intlDomain = $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX; + $intlMessages = $messages->all($intlDomain); + + if ($intlMessages) { + $intlPath = $options['path'].'/'.$this->getRelativePath($intlDomain, $messages->getLocale()); + file_put_contents($intlPath, $this->formatCatalogue($messages, $intlDomain, $options)); + + $messages->replace([], $intlDomain); + + try { + if ($messages->all($domain)) { + file_put_contents($fullpath, $this->formatCatalogue($messages, $domain, $options)); + } + continue; + } finally { + $messages->replace($intlMessages, $intlDomain); + } + } + + file_put_contents($fullpath, $this->formatCatalogue($messages, $domain, $options)); + } + } + + /** + * Transforms a domain of a message catalogue to its string representation. + */ + abstract public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string; + + /** + * Gets the file extension of the dumper. + */ + abstract protected function getExtension(): string; + + /** + * Gets the relative file path using the template. + */ + private function getRelativePath(string $domain, string $locale): string + { + return strtr($this->relativePathTemplate, [ + '%domain%' => $domain, + '%locale%' => $locale, + '%extension%' => $this->getExtension(), + ]); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/IcuResFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/IcuResFileDumper.php new file mode 100644 index 0000000..72c1ec0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/IcuResFileDumper.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * IcuResDumper generates an ICU ResourceBundle formatted string representation of a message catalogue. + * + * @author Stealth35 + */ +class IcuResFileDumper extends FileDumper +{ + protected $relativePathTemplate = '%domain%/%locale%.%extension%'; + + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $data = $indexes = $resources = ''; + + foreach ($messages->all($domain) as $source => $target) { + $indexes .= pack('v', \strlen($data) + 28); + $data .= $source."\0"; + } + + $data .= $this->writePadding($data); + + $keyTop = $this->getPosition($data); + + foreach ($messages->all($domain) as $source => $target) { + $resources .= pack('V', $this->getPosition($data)); + + $data .= pack('V', \strlen($target)) + .mb_convert_encoding($target."\0", 'UTF-16LE', 'UTF-8') + .$this->writePadding($data) + ; + } + + $resOffset = $this->getPosition($data); + + $data .= pack('v', \count($messages->all($domain))) + .$indexes + .$this->writePadding($data) + .$resources + ; + + $bundleTop = $this->getPosition($data); + + $root = pack('V7', + $resOffset + (2 << 28), // Resource Offset + Resource Type + 6, // Index length + $keyTop, // Index keys top + $bundleTop, // Index resources top + $bundleTop, // Index bundle top + \count($messages->all($domain)), // Index max table length + 0 // Index attributes + ); + + $header = pack('vC2v4C12@32', + 32, // Header size + 0xDA, 0x27, // Magic number 1 and 2 + 20, 0, 0, 2, // Rest of the header, ..., Size of a char + 0x52, 0x65, 0x73, 0x42, // Data format identifier + 1, 2, 0, 0, // Data version + 1, 4, 0, 0 // Unicode version + ); + + return $header.$root.$data; + } + + private function writePadding(string $data): ?string + { + $padding = \strlen($data) % 4; + + return $padding ? str_repeat("\xAA", 4 - $padding) : null; + } + + private function getPosition(string $data): float|int + { + return (\strlen($data) + 28) / 4; + } + + protected function getExtension(): string + { + return 'res'; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/IniFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/IniFileDumper.php new file mode 100644 index 0000000..6cbdef6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/IniFileDumper.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * IniFileDumper generates an ini formatted string representation of a message catalogue. + * + * @author Stealth35 + */ +class IniFileDumper extends FileDumper +{ + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $output = ''; + + foreach ($messages->all($domain) as $source => $target) { + $escapeTarget = str_replace('"', '\"', $target); + $output .= $source.'="'.$escapeTarget."\"\n"; + } + + return $output; + } + + protected function getExtension(): string + { + return 'ini'; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/JsonFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/JsonFileDumper.php new file mode 100644 index 0000000..e503539 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/JsonFileDumper.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * JsonFileDumper generates an json formatted string representation of a message catalogue. + * + * @author singles + */ +class JsonFileDumper extends FileDumper +{ + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $flags = $options['json_encoding'] ?? \JSON_PRETTY_PRINT; + + return json_encode($messages->all($domain), $flags); + } + + protected function getExtension(): string + { + return 'json'; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/MoFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/MoFileDumper.php new file mode 100644 index 0000000..9ded5f4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/MoFileDumper.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\Loader\MoFileLoader; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * MoFileDumper generates a gettext formatted string representation of a message catalogue. + * + * @author Stealth35 + */ +class MoFileDumper extends FileDumper +{ + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $sources = $targets = $sourceOffsets = $targetOffsets = ''; + $offsets = []; + $size = 0; + + foreach ($messages->all($domain) as $source => $target) { + $offsets[] = array_map('strlen', [$sources, $source, $targets, $target]); + $sources .= "\0".$source; + $targets .= "\0".$target; + ++$size; + } + + $header = [ + 'magicNumber' => MoFileLoader::MO_LITTLE_ENDIAN_MAGIC, + 'formatRevision' => 0, + 'count' => $size, + 'offsetId' => MoFileLoader::MO_HEADER_SIZE, + 'offsetTranslated' => MoFileLoader::MO_HEADER_SIZE + (8 * $size), + 'sizeHashes' => 0, + 'offsetHashes' => MoFileLoader::MO_HEADER_SIZE + (16 * $size), + ]; + + $sourcesSize = \strlen($sources); + $sourcesStart = $header['offsetHashes'] + 1; + + foreach ($offsets as $offset) { + $sourceOffsets .= $this->writeLong($offset[1]) + .$this->writeLong($offset[0] + $sourcesStart); + $targetOffsets .= $this->writeLong($offset[3]) + .$this->writeLong($offset[2] + $sourcesStart + $sourcesSize); + } + + $output = implode('', array_map($this->writeLong(...), $header)) + .$sourceOffsets + .$targetOffsets + .$sources + .$targets + ; + + return $output; + } + + protected function getExtension(): string + { + return 'mo'; + } + + private function writeLong(mixed $str): string + { + return pack('V*', $str); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/PhpFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/PhpFileDumper.php new file mode 100644 index 0000000..51e9066 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/PhpFileDumper.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * PhpFileDumper generates PHP files from a message catalogue. + * + * @author Michel Salib + */ +class PhpFileDumper extends FileDumper +{ + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + return "all($domain), true).";\n"; + } + + protected function getExtension(): string + { + return 'php'; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/PoFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/PoFileDumper.php new file mode 100644 index 0000000..a2d0deb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/PoFileDumper.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * PoFileDumper generates a gettext formatted string representation of a message catalogue. + * + * @author Stealth35 + */ +class PoFileDumper extends FileDumper +{ + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $output = 'msgid ""'."\n"; + $output .= 'msgstr ""'."\n"; + $output .= '"Content-Type: text/plain; charset=UTF-8\n"'."\n"; + $output .= '"Content-Transfer-Encoding: 8bit\n"'."\n"; + $output .= '"Language: '.$messages->getLocale().'\n"'."\n"; + $output .= "\n"; + + $newLine = false; + foreach ($messages->all($domain) as $source => $target) { + if ($newLine) { + $output .= "\n"; + } else { + $newLine = true; + } + $metadata = $messages->getMetadata($source, $domain); + + if (isset($metadata['comments'])) { + $output .= $this->formatComments($metadata['comments']); + } + if (isset($metadata['flags'])) { + $output .= $this->formatComments(implode(',', (array) $metadata['flags']), ','); + } + if (isset($metadata['sources'])) { + $output .= $this->formatComments(implode(' ', (array) $metadata['sources']), ':'); + } + + $sourceRules = $this->getStandardRules($source); + $targetRules = $this->getStandardRules($target); + if (2 == \count($sourceRules) && [] !== $targetRules) { + $output .= sprintf('msgid "%s"'."\n", $this->escape($sourceRules[0])); + $output .= sprintf('msgid_plural "%s"'."\n", $this->escape($sourceRules[1])); + foreach ($targetRules as $i => $targetRule) { + $output .= sprintf('msgstr[%d] "%s"'."\n", $i, $this->escape($targetRule)); + } + } else { + $output .= sprintf('msgid "%s"'."\n", $this->escape($source)); + $output .= sprintf('msgstr "%s"'."\n", $this->escape($target)); + } + } + + return $output; + } + + private function getStandardRules(string $id): array + { + // Partly copied from TranslatorTrait::trans. + $parts = []; + if (preg_match('/^\|++$/', $id)) { + $parts = explode('|', $id); + } elseif (preg_match_all('/(?:\|\||[^\|])++/', $id, $matches)) { + $parts = $matches[0]; + } + + $intervalRegexp = <<<'EOF' +/^(?P + ({\s* + (\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*) + \s*}) + + | + + (?P[\[\]]) + \s* + (?P-Inf|\-?\d+(\.\d+)?) + \s*,\s* + (?P\+?Inf|\-?\d+(\.\d+)?) + \s* + (?P[\[\]]) +)\s*(?P.*?)$/xs +EOF; + + $standardRules = []; + foreach ($parts as $part) { + $part = trim(str_replace('||', '|', $part)); + + if (preg_match($intervalRegexp, $part)) { + // Explicit rule is not a standard rule. + return []; + } else { + $standardRules[] = $part; + } + } + + return $standardRules; + } + + protected function getExtension(): string + { + return 'po'; + } + + private function escape(string $str): string + { + return addcslashes($str, "\0..\37\42\134"); + } + + private function formatComments(string|array $comments, string $prefix = ''): ?string + { + $output = null; + + foreach ((array) $comments as $comment) { + $output .= sprintf('#%s %s'."\n", $prefix, $comment); + } + + return $output; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/QtFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/QtFileDumper.php new file mode 100644 index 0000000..0373e9c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/QtFileDumper.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * QtFileDumper generates ts files from a message catalogue. + * + * @author Benjamin Eberlei + */ +class QtFileDumper extends FileDumper +{ + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $dom = new \DOMDocument('1.0', 'utf-8'); + $dom->formatOutput = true; + $ts = $dom->appendChild($dom->createElement('TS')); + $context = $ts->appendChild($dom->createElement('context')); + $context->appendChild($dom->createElement('name', $domain)); + + foreach ($messages->all($domain) as $source => $target) { + $message = $context->appendChild($dom->createElement('message')); + $metadata = $messages->getMetadata($source, $domain); + if (isset($metadata['sources'])) { + foreach ((array) $metadata['sources'] as $location) { + $loc = explode(':', $location, 2); + $location = $message->appendChild($dom->createElement('location')); + $location->setAttribute('filename', $loc[0]); + if (isset($loc[1])) { + $location->setAttribute('line', $loc[1]); + } + } + } + $message->appendChild($dom->createElement('source', $source)); + $message->appendChild($dom->createElement('translation', $target)); + } + + return $dom->saveXML(); + } + + protected function getExtension(): string + { + return 'ts'; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/XliffFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/XliffFileDumper.php new file mode 100644 index 0000000..d0f016b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/XliffFileDumper.php @@ -0,0 +1,221 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * XliffFileDumper generates xliff files from a message catalogue. + * + * @author Michel Salib + */ +class XliffFileDumper extends FileDumper +{ + public function __construct( + private string $extension = 'xlf', + ) { + } + + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + $xliffVersion = '1.2'; + if (\array_key_exists('xliff_version', $options)) { + $xliffVersion = $options['xliff_version']; + } + + if (\array_key_exists('default_locale', $options)) { + $defaultLocale = $options['default_locale']; + } else { + $defaultLocale = \Locale::getDefault(); + } + + if ('1.2' === $xliffVersion) { + return $this->dumpXliff1($defaultLocale, $messages, $domain, $options); + } + if ('2.0' === $xliffVersion) { + return $this->dumpXliff2($defaultLocale, $messages, $domain); + } + + throw new InvalidArgumentException(sprintf('No support implemented for dumping XLIFF version "%s".', $xliffVersion)); + } + + protected function getExtension(): string + { + return $this->extension; + } + + private function dumpXliff1(string $defaultLocale, MessageCatalogue $messages, ?string $domain, array $options = []): string + { + $toolInfo = ['tool-id' => 'symfony', 'tool-name' => 'Symfony']; + if (\array_key_exists('tool_info', $options)) { + $toolInfo = array_merge($toolInfo, $options['tool_info']); + } + + $dom = new \DOMDocument('1.0', 'utf-8'); + $dom->formatOutput = true; + + $xliff = $dom->appendChild($dom->createElement('xliff')); + $xliff->setAttribute('version', '1.2'); + $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:1.2'); + + $xliffFile = $xliff->appendChild($dom->createElement('file')); + $xliffFile->setAttribute('source-language', str_replace('_', '-', $defaultLocale)); + $xliffFile->setAttribute('target-language', str_replace('_', '-', $messages->getLocale())); + $xliffFile->setAttribute('datatype', 'plaintext'); + $xliffFile->setAttribute('original', 'file.ext'); + + $xliffHead = $xliffFile->appendChild($dom->createElement('header')); + $xliffTool = $xliffHead->appendChild($dom->createElement('tool')); + foreach ($toolInfo as $id => $value) { + $xliffTool->setAttribute($id, $value); + } + + if ($catalogueMetadata = $messages->getCatalogueMetadata('', $domain) ?? []) { + $xliffPropGroup = $xliffHead->appendChild($dom->createElement('prop-group')); + foreach ($catalogueMetadata as $key => $value) { + $xliffProp = $xliffPropGroup->appendChild($dom->createElement('prop')); + $xliffProp->setAttribute('prop-type', $key); + $xliffProp->appendChild($dom->createTextNode($value)); + } + } + + $xliffBody = $xliffFile->appendChild($dom->createElement('body')); + foreach ($messages->all($domain) as $source => $target) { + $translation = $dom->createElement('trans-unit'); + + $translation->setAttribute('id', strtr(substr(base64_encode(hash('sha256', $source, true)), 0, 7), '/+', '._')); + $translation->setAttribute('resname', $source); + + $s = $translation->appendChild($dom->createElement('source')); + $s->appendChild($dom->createTextNode($source)); + + // Does the target contain characters requiring a CDATA section? + $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target); + + $targetElement = $dom->createElement('target'); + $metadata = $messages->getMetadata($source, $domain); + if ($this->hasMetadataArrayInfo('target-attributes', $metadata)) { + foreach ($metadata['target-attributes'] as $name => $value) { + $targetElement->setAttribute($name, $value); + } + } + $t = $translation->appendChild($targetElement); + $t->appendChild($text); + + if ($this->hasMetadataArrayInfo('notes', $metadata)) { + foreach ($metadata['notes'] as $note) { + if (!isset($note['content'])) { + continue; + } + + $n = $translation->appendChild($dom->createElement('note')); + $n->appendChild($dom->createTextNode($note['content'])); + + if (isset($note['priority'])) { + $n->setAttribute('priority', $note['priority']); + } + + if (isset($note['from'])) { + $n->setAttribute('from', $note['from']); + } + } + } + + $xliffBody->appendChild($translation); + } + + return $dom->saveXML(); + } + + private function dumpXliff2(string $defaultLocale, MessageCatalogue $messages, ?string $domain): string + { + $dom = new \DOMDocument('1.0', 'utf-8'); + $dom->formatOutput = true; + + $xliff = $dom->appendChild($dom->createElement('xliff')); + $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:2.0'); + $xliff->setAttribute('version', '2.0'); + $xliff->setAttribute('srcLang', str_replace('_', '-', $defaultLocale)); + $xliff->setAttribute('trgLang', str_replace('_', '-', $messages->getLocale())); + + $xliffFile = $xliff->appendChild($dom->createElement('file')); + if (str_ends_with($domain, MessageCatalogue::INTL_DOMAIN_SUFFIX)) { + $xliffFile->setAttribute('id', substr($domain, 0, -\strlen(MessageCatalogue::INTL_DOMAIN_SUFFIX)).'.'.$messages->getLocale()); + } else { + $xliffFile->setAttribute('id', $domain.'.'.$messages->getLocale()); + } + + if ($catalogueMetadata = $messages->getCatalogueMetadata('', $domain) ?? []) { + $xliff->setAttribute('xmlns:m', 'urn:oasis:names:tc:xliff:metadata:2.0'); + $xliffMetadata = $xliffFile->appendChild($dom->createElement('m:metadata')); + foreach ($catalogueMetadata as $key => $value) { + $xliffMeta = $xliffMetadata->appendChild($dom->createElement('prop')); + $xliffMeta->setAttribute('type', $key); + $xliffMeta->appendChild($dom->createTextNode($value)); + } + } + + foreach ($messages->all($domain) as $source => $target) { + $translation = $dom->createElement('unit'); + $translation->setAttribute('id', strtr(substr(base64_encode(hash('sha256', $source, true)), 0, 7), '/+', '._')); + + if (\strlen($source) <= 80) { + $translation->setAttribute('name', $source); + } + + $metadata = $messages->getMetadata($source, $domain); + + // Add notes section + if ($this->hasMetadataArrayInfo('notes', $metadata)) { + $notesElement = $dom->createElement('notes'); + foreach ($metadata['notes'] as $note) { + $n = $dom->createElement('note'); + $n->appendChild($dom->createTextNode($note['content'] ?? '')); + unset($note['content']); + + foreach ($note as $name => $value) { + $n->setAttribute($name, $value); + } + $notesElement->appendChild($n); + } + $translation->appendChild($notesElement); + } + + $segment = $translation->appendChild($dom->createElement('segment')); + + $s = $segment->appendChild($dom->createElement('source')); + $s->appendChild($dom->createTextNode($source)); + + // Does the target contain characters requiring a CDATA section? + $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target); + + $targetElement = $dom->createElement('target'); + if ($this->hasMetadataArrayInfo('target-attributes', $metadata)) { + foreach ($metadata['target-attributes'] as $name => $value) { + $targetElement->setAttribute($name, $value); + } + } + $t = $segment->appendChild($targetElement); + $t->appendChild($text); + + $xliffFile->appendChild($translation); + } + + return $dom->saveXML(); + } + + private function hasMetadataArrayInfo(string $key, ?array $metadata = null): bool + { + return is_iterable($metadata[$key] ?? null); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Dumper/YamlFileDumper.php b/php/libraries/composer/vendor/symfony/translation/Dumper/YamlFileDumper.php new file mode 100644 index 0000000..d267033 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Dumper/YamlFileDumper.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Dumper; + +use Symfony\Component\Translation\Exception\LogicException; +use Symfony\Component\Translation\MessageCatalogue; +use Symfony\Component\Translation\Util\ArrayConverter; +use Symfony\Component\Yaml\Yaml; + +/** + * YamlFileDumper generates yaml files from a message catalogue. + * + * @author Michel Salib + */ +class YamlFileDumper extends FileDumper +{ + private string $extension; + + public function __construct(string $extension = 'yml') + { + $this->extension = $extension; + } + + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string + { + if (!class_exists(Yaml::class)) { + throw new LogicException('Dumping translations in the YAML format requires the Symfony Yaml component.'); + } + + $data = $messages->all($domain); + + if (isset($options['as_tree']) && $options['as_tree']) { + $data = ArrayConverter::expandToTree($data); + } + + if (isset($options['inline']) && ($inline = (int) $options['inline']) > 0) { + return Yaml::dump($data, $inline); + } + + return Yaml::dump($data); + } + + protected function getExtension(): string + { + return $this->extension; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/ExceptionInterface.php b/php/libraries/composer/vendor/symfony/translation/Exception/ExceptionInterface.php new file mode 100644 index 0000000..8f9c54e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +/** + * Exception interface for all exceptions thrown by the component. + * + * @author Fabien Potencier + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/IncompleteDsnException.php b/php/libraries/composer/vendor/symfony/translation/Exception/IncompleteDsnException.php new file mode 100644 index 0000000..b304bde --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/IncompleteDsnException.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +class IncompleteDsnException extends InvalidArgumentException +{ + public function __construct(string $message, ?string $dsn = null, ?\Throwable $previous = null) + { + if ($dsn) { + $message = sprintf('Invalid "%s" provider DSN: ', $dsn).$message; + } + + parent::__construct($message, 0, $previous); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/InvalidArgumentException.php b/php/libraries/composer/vendor/symfony/translation/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..90d0669 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/InvalidArgumentException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +/** + * Base InvalidArgumentException for the Translation component. + * + * @author Abdellatif Ait boudad + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/InvalidResourceException.php b/php/libraries/composer/vendor/symfony/translation/Exception/InvalidResourceException.php new file mode 100644 index 0000000..cf07943 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/InvalidResourceException.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\Translation\Exception; + +/** + * Thrown when a resource cannot be loaded. + * + * @author Fabien Potencier + */ +class InvalidResourceException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/LogicException.php b/php/libraries/composer/vendor/symfony/translation/Exception/LogicException.php new file mode 100644 index 0000000..9019c7e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/LogicException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +/** + * Base LogicException for Translation component. + * + * @author Abdellatif Ait boudad + */ +class LogicException extends \LogicException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/MissingRequiredOptionException.php b/php/libraries/composer/vendor/symfony/translation/Exception/MissingRequiredOptionException.php new file mode 100644 index 0000000..46152e2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/MissingRequiredOptionException.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +/** + * @author Oskar Stark + */ +class MissingRequiredOptionException extends IncompleteDsnException +{ + public function __construct(string $option, ?string $dsn = null, ?\Throwable $previous = null) + { + $message = sprintf('The option "%s" is required but missing.', $option); + + parent::__construct($message, $dsn, $previous); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/NotFoundResourceException.php b/php/libraries/composer/vendor/symfony/translation/Exception/NotFoundResourceException.php new file mode 100644 index 0000000..cff73ae --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/NotFoundResourceException.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\Translation\Exception; + +/** + * Thrown when a resource does not exist. + * + * @author Fabien Potencier + */ +class NotFoundResourceException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/ProviderException.php b/php/libraries/composer/vendor/symfony/translation/Exception/ProviderException.php new file mode 100644 index 0000000..f2981f5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/ProviderException.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +use Symfony\Contracts\HttpClient\ResponseInterface; + +/** + * @author Fabien Potencier + */ +class ProviderException extends RuntimeException implements ProviderExceptionInterface +{ + private ResponseInterface $response; + private string $debug; + + public function __construct(string $message, ResponseInterface $response, int $code = 0, ?\Exception $previous = null) + { + $this->response = $response; + $this->debug = $response->getInfo('debug') ?? ''; + + parent::__construct($message, $code, $previous); + } + + public function getResponse(): ResponseInterface + { + return $this->response; + } + + public function getDebug(): string + { + return $this->debug; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/ProviderExceptionInterface.php b/php/libraries/composer/vendor/symfony/translation/Exception/ProviderExceptionInterface.php new file mode 100644 index 0000000..922e827 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/ProviderExceptionInterface.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +/** + * @author Fabien Potencier + */ +interface ProviderExceptionInterface extends ExceptionInterface +{ + /* + * Returns debug info coming from the Symfony\Contracts\HttpClient\ResponseInterface + */ + public function getDebug(): string; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/RuntimeException.php b/php/libraries/composer/vendor/symfony/translation/Exception/RuntimeException.php new file mode 100644 index 0000000..dcd7940 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/RuntimeException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +/** + * Base RuntimeException for the Translation component. + * + * @author Abdellatif Ait boudad + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/php/libraries/composer/vendor/symfony/translation/Exception/UnsupportedSchemeException.php b/php/libraries/composer/vendor/symfony/translation/Exception/UnsupportedSchemeException.php new file mode 100644 index 0000000..8d32951 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Exception/UnsupportedSchemeException.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Exception; + +use Symfony\Component\Translation\Bridge; +use Symfony\Component\Translation\Provider\Dsn; + +class UnsupportedSchemeException extends LogicException +{ + private const SCHEME_TO_PACKAGE_MAP = [ + 'crowdin' => [ + 'class' => Bridge\Crowdin\CrowdinProviderFactory::class, + 'package' => 'symfony/crowdin-translation-provider', + ], + 'loco' => [ + 'class' => Bridge\Loco\LocoProviderFactory::class, + 'package' => 'symfony/loco-translation-provider', + ], + 'lokalise' => [ + 'class' => Bridge\Lokalise\LokaliseProviderFactory::class, + 'package' => 'symfony/lokalise-translation-provider', + ], + 'phrase' => [ + 'class' => Bridge\Phrase\PhraseProviderFactory::class, + 'package' => 'symfony/phrase-translation-provider', + ], + ]; + + public function __construct(Dsn $dsn, ?string $name = null, array $supported = []) + { + $provider = $dsn->getScheme(); + if (false !== $pos = strpos($provider, '+')) { + $provider = substr($provider, 0, $pos); + } + $package = self::SCHEME_TO_PACKAGE_MAP[$provider] ?? null; + if ($package && !class_exists($package['class'])) { + parent::__construct(sprintf('Unable to synchronize translations via "%s" as the provider is not installed. Try running "composer require %s".', $provider, $package['package'])); + + return; + } + + $message = sprintf('The "%s" scheme is not supported', $dsn->getScheme()); + if ($name && $supported) { + $message .= sprintf('; supported schemes for translation provider "%s" are: "%s"', $name, implode('", "', $supported)); + } + + parent::__construct($message.'.'); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/AbstractFileExtractor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/AbstractFileExtractor.php new file mode 100644 index 0000000..4c088b9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/AbstractFileExtractor.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; + +/** + * Base class used by classes that extract translation messages from files. + * + * @author Marcos D. Sánchez + */ +abstract class AbstractFileExtractor +{ + protected function extractFiles(string|iterable $resource): iterable + { + if (is_iterable($resource)) { + $files = []; + foreach ($resource as $file) { + if ($this->canBeExtracted($file)) { + $files[] = $this->toSplFileInfo($file); + } + } + } elseif (is_file($resource)) { + $files = $this->canBeExtracted($resource) ? [$this->toSplFileInfo($resource)] : []; + } else { + $files = $this->extractFromDirectory($resource); + } + + return $files; + } + + private function toSplFileInfo(string $file): \SplFileInfo + { + return new \SplFileInfo($file); + } + + /** + * @throws InvalidArgumentException + */ + protected function isFile(string $file): bool + { + if (!is_file($file)) { + throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file)); + } + + return true; + } + + /** + * @return bool + */ + abstract protected function canBeExtracted(string $file); + + /** + * @return iterable + */ + abstract protected function extractFromDirectory(string|array $resource); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/ChainExtractor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/ChainExtractor.php new file mode 100644 index 0000000..d36f7f3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/ChainExtractor.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * ChainExtractor extracts translation messages from template files. + * + * @author Michel Salib + */ +class ChainExtractor implements ExtractorInterface +{ + /** + * The extractors. + * + * @var ExtractorInterface[] + */ + private array $extractors = []; + + /** + * Adds a loader to the translation extractor. + * + * @return void + */ + public function addExtractor(string $format, ExtractorInterface $extractor) + { + $this->extractors[$format] = $extractor; + } + + /** + * @return void + */ + public function setPrefix(string $prefix) + { + foreach ($this->extractors as $extractor) { + $extractor->setPrefix($prefix); + } + } + + /** + * @return void + */ + public function extract(string|iterable $directory, MessageCatalogue $catalogue) + { + foreach ($this->extractors as $extractor) { + $extractor->extract($directory, $catalogue); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/ExtractorInterface.php b/php/libraries/composer/vendor/symfony/translation/Extractor/ExtractorInterface.php new file mode 100644 index 0000000..642130a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/ExtractorInterface.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * Extracts translation messages from a directory or files to the catalogue. + * New found messages are injected to the catalogue using the prefix. + * + * @author Michel Salib + */ +interface ExtractorInterface +{ + /** + * Extracts translation messages from files, a file or a directory to the catalogue. + * + * @param string|iterable $resource Files, a file or a directory + * + * @return void + */ + public function extract(string|iterable $resource, MessageCatalogue $catalogue); + + /** + * Sets the prefix that should be used for new found messages. + * + * @return void + */ + public function setPrefix(string $prefix); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/PhpAstExtractor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/PhpAstExtractor.php new file mode 100644 index 0000000..06fc77d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/PhpAstExtractor.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +use PhpParser\NodeTraverser; +use PhpParser\NodeVisitor; +use PhpParser\Parser; +use PhpParser\ParserFactory; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Translation\Extractor\Visitor\AbstractVisitor; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * PhpAstExtractor extracts translation messages from a PHP AST. + * + * @author Mathieu Santostefano + */ +final class PhpAstExtractor extends AbstractFileExtractor implements ExtractorInterface +{ + private Parser $parser; + + public function __construct( + /** + * @param iterable $visitors + */ + private readonly iterable $visitors, + private string $prefix = '', + ) { + if (!class_exists(ParserFactory::class)) { + throw new \LogicException(sprintf('You cannot use "%s" as the "nikic/php-parser" package is not installed. Try running "composer require nikic/php-parser".', static::class)); + } + + $this->parser = (new ParserFactory())->createForHostVersion(); + } + + public function extract(iterable|string $resource, MessageCatalogue $catalogue): void + { + foreach ($this->extractFiles($resource) as $file) { + $traverser = new NodeTraverser(); + + // This is needed to resolve namespaces in class methods/constants. + $nameResolver = new NodeVisitor\NameResolver(); + $traverser->addVisitor($nameResolver); + + /** @var AbstractVisitor&NodeVisitor $visitor */ + foreach ($this->visitors as $visitor) { + $visitor->initialize($catalogue, $file, $this->prefix); + $traverser->addVisitor($visitor); + } + + $nodes = $this->parser->parse(file_get_contents($file)); + $traverser->traverse($nodes); + } + } + + public function setPrefix(string $prefix): void + { + $this->prefix = $prefix; + } + + protected function canBeExtracted(string $file): bool + { + return 'php' === pathinfo($file, \PATHINFO_EXTENSION) + && $this->isFile($file) + && preg_match('/\bt\(|->trans\(|TranslatableMessage|Symfony\\\\Component\\\\Validator\\\\Constraints/i', file_get_contents($file)); + } + + protected function extractFromDirectory(array|string $resource): iterable|Finder + { + if (!class_exists(Finder::class)) { + throw new \LogicException(sprintf('You cannot use "%s" as the "symfony/finder" package is not installed. Try running "composer require symfony/finder".', static::class)); + } + + return (new Finder())->files()->name('*.php')->in($resource); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/PhpExtractor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/PhpExtractor.php new file mode 100644 index 0000000..7ff27f7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/PhpExtractor.php @@ -0,0 +1,333 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +trigger_deprecation('symfony/translation', '6.2', '"%s" is deprecated, use "%s" instead.', PhpExtractor::class, PhpAstExtractor::class); + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * PhpExtractor extracts translation messages from a PHP template. + * + * @author Michel Salib + * + * @deprecated since Symfony 6.2, use the PhpAstExtractor instead + */ +class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface +{ + public const MESSAGE_TOKEN = 300; + public const METHOD_ARGUMENTS_TOKEN = 1000; + public const DOMAIN_TOKEN = 1001; + + /** + * Prefix for new found message. + */ + private string $prefix = ''; + + /** + * The sequence that captures translation messages. + */ + protected $sequences = [ + [ + '->', + 'trans', + '(', + self::MESSAGE_TOKEN, + ',', + self::METHOD_ARGUMENTS_TOKEN, + ',', + self::DOMAIN_TOKEN, + ], + [ + '->', + 'trans', + '(', + self::MESSAGE_TOKEN, + ], + [ + 'new', + 'TranslatableMessage', + '(', + self::MESSAGE_TOKEN, + ',', + self::METHOD_ARGUMENTS_TOKEN, + ',', + self::DOMAIN_TOKEN, + ], + [ + 'new', + 'TranslatableMessage', + '(', + self::MESSAGE_TOKEN, + ], + [ + 'new', + '\\', + 'Symfony', + '\\', + 'Component', + '\\', + 'Translation', + '\\', + 'TranslatableMessage', + '(', + self::MESSAGE_TOKEN, + ',', + self::METHOD_ARGUMENTS_TOKEN, + ',', + self::DOMAIN_TOKEN, + ], + [ + 'new', + '\Symfony\Component\Translation\TranslatableMessage', + '(', + self::MESSAGE_TOKEN, + ',', + self::METHOD_ARGUMENTS_TOKEN, + ',', + self::DOMAIN_TOKEN, + ], + [ + 'new', + '\\', + 'Symfony', + '\\', + 'Component', + '\\', + 'Translation', + '\\', + 'TranslatableMessage', + '(', + self::MESSAGE_TOKEN, + ], + [ + 'new', + '\Symfony\Component\Translation\TranslatableMessage', + '(', + self::MESSAGE_TOKEN, + ], + [ + 't', + '(', + self::MESSAGE_TOKEN, + ',', + self::METHOD_ARGUMENTS_TOKEN, + ',', + self::DOMAIN_TOKEN, + ], + [ + 't', + '(', + self::MESSAGE_TOKEN, + ], + ]; + + /** + * @return void + */ + public function extract(string|iterable $resource, MessageCatalogue $catalog) + { + $files = $this->extractFiles($resource); + foreach ($files as $file) { + $this->parseTokens(token_get_all(file_get_contents($file)), $catalog, $file); + + gc_mem_caches(); + } + } + + /** + * @return void + */ + public function setPrefix(string $prefix) + { + $this->prefix = $prefix; + } + + /** + * Normalizes a token. + */ + protected function normalizeToken(mixed $token): ?string + { + if (isset($token[1]) && 'b"' !== $token) { + return $token[1]; + } + + return $token; + } + + /** + * Seeks to a non-whitespace token. + */ + private function seekToNextRelevantToken(\Iterator $tokenIterator): void + { + for (; $tokenIterator->valid(); $tokenIterator->next()) { + $t = $tokenIterator->current(); + if (\T_WHITESPACE !== $t[0]) { + break; + } + } + } + + private function skipMethodArgument(\Iterator $tokenIterator): void + { + $openBraces = 0; + + for (; $tokenIterator->valid(); $tokenIterator->next()) { + $t = $tokenIterator->current(); + + if ('[' === $t[0] || '(' === $t[0]) { + ++$openBraces; + } + + if (']' === $t[0] || ')' === $t[0]) { + --$openBraces; + } + + if ((0 === $openBraces && ',' === $t[0]) || (-1 === $openBraces && ')' === $t[0])) { + break; + } + } + } + + /** + * Extracts the message from the iterator while the tokens + * match allowed message tokens. + */ + private function getValue(\Iterator $tokenIterator): string + { + $message = ''; + $docToken = ''; + $docPart = ''; + + for (; $tokenIterator->valid(); $tokenIterator->next()) { + $t = $tokenIterator->current(); + if ('.' === $t) { + // Concatenate with next token + continue; + } + if (!isset($t[1])) { + break; + } + + switch ($t[0]) { + case \T_START_HEREDOC: + $docToken = $t[1]; + break; + case \T_ENCAPSED_AND_WHITESPACE: + case \T_CONSTANT_ENCAPSED_STRING: + if ('' === $docToken) { + $message .= PhpStringTokenParser::parse($t[1]); + } else { + $docPart = $t[1]; + } + break; + case \T_END_HEREDOC: + if ($indentation = strspn($t[1], ' ')) { + $docPartWithLineBreaks = $docPart; + $docPart = ''; + + foreach (preg_split('~(\r\n|\n|\r)~', $docPartWithLineBreaks, -1, \PREG_SPLIT_DELIM_CAPTURE) as $str) { + if (\in_array($str, ["\r\n", "\n", "\r"], true)) { + $docPart .= $str; + } else { + $docPart .= substr($str, $indentation); + } + } + } + + $message .= PhpStringTokenParser::parseDocString($docToken, $docPart); + $docToken = ''; + $docPart = ''; + break; + case \T_WHITESPACE: + break; + default: + break 2; + } + } + + return $message; + } + + /** + * Extracts trans message from PHP tokens. + * + * @return void + */ + protected function parseTokens(array $tokens, MessageCatalogue $catalog, string $filename) + { + $tokenIterator = new \ArrayIterator($tokens); + + for ($key = 0; $key < $tokenIterator->count(); ++$key) { + foreach ($this->sequences as $sequence) { + $message = ''; + $domain = 'messages'; + $tokenIterator->seek($key); + + foreach ($sequence as $sequenceKey => $item) { + $this->seekToNextRelevantToken($tokenIterator); + + if ($this->normalizeToken($tokenIterator->current()) === $item) { + $tokenIterator->next(); + continue; + } elseif (self::MESSAGE_TOKEN === $item) { + $message = $this->getValue($tokenIterator); + + if (\count($sequence) === ($sequenceKey + 1)) { + break; + } + } elseif (self::METHOD_ARGUMENTS_TOKEN === $item) { + $this->skipMethodArgument($tokenIterator); + } elseif (self::DOMAIN_TOKEN === $item) { + $domainToken = $this->getValue($tokenIterator); + if ('' !== $domainToken) { + $domain = $domainToken; + } + + break; + } else { + break; + } + } + + if ($message) { + $catalog->set($message, $this->prefix.$message, $domain); + $metadata = $catalog->getMetadata($message, $domain) ?? []; + $normalizedFilename = preg_replace('{[\\\\/]+}', '/', $filename); + $metadata['sources'][] = $normalizedFilename.':'.$tokens[$key][2]; + $catalog->setMetadata($message, $metadata, $domain); + break; + } + } + } + } + + /** + * @throws \InvalidArgumentException + */ + protected function canBeExtracted(string $file): bool + { + return $this->isFile($file) && 'php' === pathinfo($file, \PATHINFO_EXTENSION); + } + + protected function extractFromDirectory(string|array $directory): iterable + { + if (!class_exists(Finder::class)) { + throw new \LogicException(sprintf('You cannot use "%s" as the "symfony/finder" package is not installed. Try running "composer require symfony/finder".', static::class)); + } + + $finder = new Finder(); + + return $finder->files()->name('*.php')->in($directory); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/PhpStringTokenParser.php b/php/libraries/composer/vendor/symfony/translation/Extractor/PhpStringTokenParser.php new file mode 100644 index 0000000..2dfc1e3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/PhpStringTokenParser.php @@ -0,0 +1,141 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +trigger_deprecation('symfony/translation', '6.2', '"%s" is deprecated.', PhpStringTokenParser::class); + +/* + * The following is derived from code at http://github.com/nikic/PHP-Parser + * + * Copyright (c) 2011 by Nikita Popov + * + * Some rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * * The names of the contributors may not be used to endorse or + * promote products derived from this software without specific + * prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @deprecated since Symfony 6.2 + */ +class PhpStringTokenParser +{ + protected static $replacements = [ + '\\' => '\\', + '$' => '$', + 'n' => "\n", + 'r' => "\r", + 't' => "\t", + 'f' => "\f", + 'v' => "\v", + 'e' => "\x1B", + ]; + + /** + * Parses a string token. + * + * @param string $str String token content + */ + public static function parse(string $str): string + { + $bLength = 0; + if ('b' === $str[0]) { + $bLength = 1; + } + + if ('\'' === $str[$bLength]) { + return str_replace( + ['\\\\', '\\\''], + ['\\', '\''], + substr($str, $bLength + 1, -1) + ); + } else { + return self::parseEscapeSequences(substr($str, $bLength + 1, -1), '"'); + } + } + + /** + * Parses escape sequences in strings (all string types apart from single quoted). + * + * @param string $str String without quotes + * @param string|null $quote Quote type + */ + public static function parseEscapeSequences(string $str, ?string $quote = null): string + { + if (null !== $quote) { + $str = str_replace('\\'.$quote, $quote, $str); + } + + return preg_replace_callback( + '~\\\\([\\\\$nrtfve]|[xX][0-9a-fA-F]{1,2}|[0-7]{1,3})~', + [__CLASS__, 'parseCallback'], + $str + ); + } + + private static function parseCallback(array $matches): string + { + $str = $matches[1]; + + if (isset(self::$replacements[$str])) { + return self::$replacements[$str]; + } elseif ('x' === $str[0] || 'X' === $str[0]) { + return \chr(hexdec($str)); + } else { + return \chr(octdec($str)); + } + } + + /** + * Parses a constant doc string. + * + * @param string $startToken Doc string start token content (<< + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * @author Mathieu Santostefano + */ +abstract class AbstractVisitor +{ + private MessageCatalogue $catalogue; + private \SplFileInfo $file; + private string $messagePrefix; + + public function initialize(MessageCatalogue $catalogue, \SplFileInfo $file, string $messagePrefix): void + { + $this->catalogue = $catalogue; + $this->file = $file; + $this->messagePrefix = $messagePrefix; + } + + protected function addMessageToCatalogue(string $message, ?string $domain, int $line): void + { + $domain ??= 'messages'; + $this->catalogue->set($message, $this->messagePrefix.$message, $domain); + $metadata = $this->catalogue->getMetadata($message, $domain) ?? []; + $normalizedFilename = preg_replace('{[\\\\/]+}', '/', $this->file); + $metadata['sources'][] = $normalizedFilename.':'.$line; + $this->catalogue->setMetadata($message, $metadata, $domain); + } + + protected function getStringArguments(Node\Expr\CallLike|Node\Attribute|Node\Expr\New_ $node, int|string $index, bool $indexIsRegex = false): array + { + if (\is_string($index)) { + return $this->getStringNamedArguments($node, $index, $indexIsRegex); + } + + $args = $node instanceof Node\Expr\CallLike ? $node->getRawArgs() : $node->args; + + if (!($arg = $args[$index] ?? null) instanceof Node\Arg) { + return []; + } + + return (array) $this->getStringValue($arg->value); + } + + protected function hasNodeNamedArguments(Node\Expr\CallLike|Node\Attribute|Node\Expr\New_ $node): bool + { + $args = $node instanceof Node\Expr\CallLike ? $node->getRawArgs() : $node->args; + + foreach ($args as $arg) { + if ($arg instanceof Node\Arg && null !== $arg->name) { + return true; + } + } + + return false; + } + + protected function nodeFirstNamedArgumentIndex(Node\Expr\CallLike|Node\Attribute|Node\Expr\New_ $node): int + { + $args = $node instanceof Node\Expr\CallLike ? $node->getRawArgs() : $node->args; + + foreach ($args as $i => $arg) { + if ($arg instanceof Node\Arg && null !== $arg->name) { + return $i; + } + } + + return \PHP_INT_MAX; + } + + private function getStringNamedArguments(Node\Expr\CallLike|Node\Attribute $node, ?string $argumentName = null, bool $isArgumentNamePattern = false): array + { + $args = $node instanceof Node\Expr\CallLike ? $node->getArgs() : $node->args; + $argumentValues = []; + + foreach ($args as $arg) { + if (!$isArgumentNamePattern && $arg->name?->toString() === $argumentName) { + $argumentValues[] = $this->getStringValue($arg->value); + } elseif ($isArgumentNamePattern && preg_match($argumentName, $arg->name?->toString() ?? '') > 0) { + $argumentValues[] = $this->getStringValue($arg->value); + } + } + + return array_filter($argumentValues); + } + + private function getStringValue(Node $node): ?string + { + if ($node instanceof Node\Scalar\String_) { + return $node->value; + } + + if ($node instanceof Node\Expr\BinaryOp\Concat) { + if (null === $left = $this->getStringValue($node->left)) { + return null; + } + + if (null === $right = $this->getStringValue($node->right)) { + return null; + } + + return $left.$right; + } + + if ($node instanceof Node\Expr\Assign && $node->expr instanceof Node\Scalar\String_) { + return $node->expr->value; + } + + if ($node instanceof Node\Expr\ClassConstFetch) { + try { + $reflection = new \ReflectionClass($node->class->toString()); + $constant = $reflection->getReflectionConstant($node->name->toString()); + if (false !== $constant && \is_string($constant->getValue())) { + return $constant->getValue(); + } + } catch (\ReflectionException) { + } + } + + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/ConstraintVisitor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/ConstraintVisitor.php new file mode 100644 index 0000000..00fb9ee --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/ConstraintVisitor.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; + +/** + * @author Mathieu Santostefano + * + * Code mostly comes from https://github.com/php-translation/extractor/blob/master/src/Visitor/Php/Symfony/Constraint.php + */ +final class ConstraintVisitor extends AbstractVisitor implements NodeVisitor +{ + public function __construct( + private readonly array $constraintClassNames = [] + ) { + } + + public function beforeTraverse(array $nodes): ?Node + { + return null; + } + + public function enterNode(Node $node): ?Node + { + return null; + } + + public function leaveNode(Node $node): ?Node + { + if (!$node instanceof Node\Expr\New_ && !$node instanceof Node\Attribute) { + return null; + } + + $className = $node instanceof Node\Attribute ? $node->name : $node->class; + if (!$className instanceof Node\Name) { + return null; + } + + $parts = $className->getParts(); + $isConstraintClass = false; + + foreach ($parts as $part) { + if (\in_array($part, $this->constraintClassNames, true)) { + $isConstraintClass = true; + + break; + } + } + + if (!$isConstraintClass) { + return null; + } + + $arg = $node->args[0] ?? null; + if (!$arg instanceof Node\Arg) { + return null; + } + + if ($this->hasNodeNamedArguments($node)) { + $messages = $this->getStringArguments($node, '/message/i', true); + } else { + if (!$arg->value instanceof Node\Expr\Array_) { + // There is no way to guess which argument is a message to be translated. + return null; + } + + $messages = []; + $options = $arg->value; + + /** @var Node\Expr\ArrayItem $item */ + foreach ($options->items as $item) { + if (!$item->key instanceof Node\Scalar\String_) { + continue; + } + + if (false === stripos($item->key->value ?? '', 'message')) { + continue; + } + + if (!$item->value instanceof Node\Scalar\String_) { + continue; + } + + $messages[] = $item->value->value; + + break; + } + } + + foreach ($messages as $message) { + $this->addMessageToCatalogue($message, 'validators', $node->getStartLine()); + } + + return null; + } + + public function afterTraverse(array $nodes): ?Node + { + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/TransMethodVisitor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/TransMethodVisitor.php new file mode 100644 index 0000000..011bf3b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/TransMethodVisitor.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; + +/** + * @author Mathieu Santostefano + */ +final class TransMethodVisitor extends AbstractVisitor implements NodeVisitor +{ + public function beforeTraverse(array $nodes): ?Node + { + return null; + } + + public function enterNode(Node $node): ?Node + { + return null; + } + + public function leaveNode(Node $node): ?Node + { + if (!$node instanceof Node\Expr\MethodCall && !$node instanceof Node\Expr\FuncCall) { + return null; + } + + if (!\is_string($node->name) && !$node->name instanceof Node\Identifier && !$node->name instanceof Node\Name) { + return null; + } + + $name = $node->name instanceof Node\Name ? $node->name->getLast() : (string) $node->name; + + if ('trans' === $name || 't' === $name) { + $firstNamedArgumentIndex = $this->nodeFirstNamedArgumentIndex($node); + + if (!$messages = $this->getStringArguments($node, 0 < $firstNamedArgumentIndex ? 0 : 'message')) { + return null; + } + + $domain = $this->getStringArguments($node, 2 < $firstNamedArgumentIndex ? 2 : 'domain')[0] ?? null; + + foreach ($messages as $message) { + $this->addMessageToCatalogue($message, $domain, $node->getStartLine()); + } + } + + return null; + } + + public function afterTraverse(array $nodes): ?Node + { + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/TranslatableMessageVisitor.php b/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/TranslatableMessageVisitor.php new file mode 100644 index 0000000..6bd8bb0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Extractor/Visitor/TranslatableMessageVisitor.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; + +/** + * @author Mathieu Santostefano + */ +final class TranslatableMessageVisitor extends AbstractVisitor implements NodeVisitor +{ + public function beforeTraverse(array $nodes): ?Node + { + return null; + } + + public function enterNode(Node $node): ?Node + { + return null; + } + + public function leaveNode(Node $node): ?Node + { + if (!$node instanceof Node\Expr\New_) { + return null; + } + + if (!($className = $node->class) instanceof Node\Name) { + return null; + } + + if (!\in_array('TranslatableMessage', $className->getParts(), true)) { + return null; + } + + $firstNamedArgumentIndex = $this->nodeFirstNamedArgumentIndex($node); + + if (!$messages = $this->getStringArguments($node, 0 < $firstNamedArgumentIndex ? 0 : 'message')) { + return null; + } + + $domain = $this->getStringArguments($node, 2 < $firstNamedArgumentIndex ? 2 : 'domain')[0] ?? null; + + foreach ($messages as $message) { + $this->addMessageToCatalogue($message, $domain, $node->getStartLine()); + } + + return null; + } + + public function afterTraverse(array $nodes): ?Node + { + return null; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Formatter/IntlFormatter.php b/php/libraries/composer/vendor/symfony/translation/Formatter/IntlFormatter.php new file mode 100644 index 0000000..e62de25 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Formatter/IntlFormatter.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Formatter; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\LogicException; + +/** + * @author Guilherme Blanco + * @author Abdellatif Ait boudad + */ +class IntlFormatter implements IntlFormatterInterface +{ + private bool $hasMessageFormatter; + private array $cache = []; + + public function formatIntl(string $message, string $locale, array $parameters = []): string + { + // MessageFormatter constructor throws an exception if the message is empty + if ('' === $message) { + return ''; + } + + if (!$formatter = $this->cache[$locale][$message] ?? null) { + if (!$this->hasMessageFormatter ??= class_exists(\MessageFormatter::class)) { + throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.'); + } + try { + $this->cache[$locale][$message] = $formatter = new \MessageFormatter($locale, $message); + } catch (\IntlException $e) { + throw new InvalidArgumentException(sprintf('Invalid message format (error #%d): ', intl_get_error_code()).intl_get_error_message(), 0, $e); + } + } + + foreach ($parameters as $key => $value) { + if (\in_array($key[0] ?? null, ['%', '{'], true)) { + unset($parameters[$key]); + $parameters[trim($key, '%{ }')] = $value; + } + } + + if (false === $message = $formatter->format($parameters)) { + throw new InvalidArgumentException(sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()).$formatter->getErrorMessage()); + } + + return $message; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Formatter/IntlFormatterInterface.php b/php/libraries/composer/vendor/symfony/translation/Formatter/IntlFormatterInterface.php new file mode 100644 index 0000000..02fc6ac --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Formatter/IntlFormatterInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Formatter; + +/** + * Formats ICU message patterns. + * + * @author Nicolas Grekas + */ +interface IntlFormatterInterface +{ + /** + * Formats a localized message using rules defined by ICU MessageFormat. + * + * @see http://icu-project.org/apiref/icu4c/classMessageFormat.html#details + */ + public function formatIntl(string $message, string $locale, array $parameters = []): string; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Formatter/MessageFormatter.php b/php/libraries/composer/vendor/symfony/translation/Formatter/MessageFormatter.php new file mode 100644 index 0000000..d5255bd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Formatter/MessageFormatter.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 Symfony\Component\Translation\Formatter; + +use Symfony\Component\Translation\IdentityTranslator; +use Symfony\Contracts\Translation\TranslatorInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(IntlFormatter::class); + +/** + * @author Abdellatif Ait boudad + */ +class MessageFormatter implements MessageFormatterInterface, IntlFormatterInterface +{ + private TranslatorInterface $translator; + private IntlFormatterInterface $intlFormatter; + + /** + * @param TranslatorInterface|null $translator An identity translator to use as selector for pluralization + */ + public function __construct(?TranslatorInterface $translator = null, ?IntlFormatterInterface $intlFormatter = null) + { + $this->translator = $translator ?? new IdentityTranslator(); + $this->intlFormatter = $intlFormatter ?? new IntlFormatter(); + } + + public function format(string $message, string $locale, array $parameters = []): string + { + return $this->translator->trans($message, $parameters, null, $locale); + } + + public function formatIntl(string $message, string $locale, array $parameters = []): string + { + return $this->intlFormatter->formatIntl($message, $locale, $parameters); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Formatter/MessageFormatterInterface.php b/php/libraries/composer/vendor/symfony/translation/Formatter/MessageFormatterInterface.php new file mode 100644 index 0000000..d5c41c1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Formatter/MessageFormatterInterface.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Formatter; + +/** + * @author Guilherme Blanco + * @author Abdellatif Ait boudad + */ +interface MessageFormatterInterface +{ + /** + * Formats a localized message pattern with given arguments. + * + * @param string $message The message (may also be an object that can be cast to string) + * @param string $locale The message locale + * @param array $parameters An array of parameters for the message + */ + public function format(string $message, string $locale, array $parameters = []): string; +} diff --git a/php/libraries/composer/vendor/symfony/translation/IdentityTranslator.php b/php/libraries/composer/vendor/symfony/translation/IdentityTranslator.php new file mode 100644 index 0000000..46875ed --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/IdentityTranslator.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\Translation; + +use Symfony\Contracts\Translation\LocaleAwareInterface; +use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorTrait; + +/** + * IdentityTranslator does not translate anything. + * + * @author Fabien Potencier + */ +class IdentityTranslator implements TranslatorInterface, LocaleAwareInterface +{ + use TranslatorTrait; +} diff --git a/php/libraries/composer/vendor/symfony/translation/LICENSE b/php/libraries/composer/vendor/symfony/translation/LICENSE new file mode 100644 index 0000000..0138f8f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/ArrayLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/ArrayLoader.php new file mode 100644 index 0000000..e63a7d0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/ArrayLoader.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * ArrayLoader loads translations from a PHP array. + * + * @author Fabien Potencier + */ +class ArrayLoader implements LoaderInterface +{ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue + { + $resource = $this->flatten($resource); + $catalogue = new MessageCatalogue($locale); + $catalogue->add($resource, $domain); + + return $catalogue; + } + + /** + * Flattens an nested array of translations. + * + * The scheme used is: + * 'key' => ['key2' => ['key3' => 'value']] + * Becomes: + * 'key.key2.key3' => 'value' + */ + private function flatten(array $messages): array + { + $result = []; + foreach ($messages as $key => $value) { + if (\is_array($value)) { + foreach ($this->flatten($value) as $k => $v) { + if (null !== $v) { + $result[$key.'.'.$k] = $v; + } + } + } elseif (null !== $value) { + $result[$key] = $value; + } + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/CsvFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/CsvFileLoader.php new file mode 100644 index 0000000..7f2f96b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/CsvFileLoader.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Translation\Exception\NotFoundResourceException; + +/** + * CsvFileLoader loads translations from CSV files. + * + * @author Saša Stamenković + */ +class CsvFileLoader extends FileLoader +{ + private string $delimiter = ';'; + private string $enclosure = '"'; + private string $escape = '\\'; + + protected function loadResource(string $resource): array + { + $messages = []; + + try { + $file = new \SplFileObject($resource, 'rb'); + } catch (\RuntimeException $e) { + throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e); + } + + $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY); + $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape); + + foreach ($file as $data) { + if (false === $data) { + continue; + } + + if (!str_starts_with($data[0], '#') && isset($data[1]) && 2 === \count($data)) { + $messages[$data[0]] = $data[1]; + } + } + + return $messages; + } + + /** + * Sets the delimiter, enclosure, and escape character for CSV. + * + * @return void + */ + public function setCsvControl(string $delimiter = ';', string $enclosure = '"', string $escape = '\\') + { + $this->delimiter = $delimiter; + $this->enclosure = $enclosure; + $this->escape = $escape; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/FileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/FileLoader.php new file mode 100644 index 0000000..877c3bb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/FileLoader.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * @author Abdellatif Ait boudad + */ +abstract class FileLoader extends ArrayLoader +{ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue + { + if (!stream_is_local($resource)) { + throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); + } + + if (!file_exists($resource)) { + throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); + } + + $messages = $this->loadResource($resource); + + // empty resource + $messages ??= []; + + // not an array + if (!\is_array($messages)) { + throw new InvalidResourceException(sprintf('Unable to load file "%s".', $resource)); + } + + $catalogue = parent::load($messages, $locale, $domain); + + if (class_exists(FileResource::class)) { + $catalogue->addResource(new FileResource($resource)); + } + + return $catalogue; + } + + /** + * @throws InvalidResourceException if stream content has an invalid format + */ + abstract protected function loadResource(string $resource): array; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/IcuDatFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/IcuDatFileLoader.php new file mode 100644 index 0000000..76e4e7f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/IcuDatFileLoader.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * IcuResFileLoader loads translations from a resource bundle. + * + * @author stealth35 + */ +class IcuDatFileLoader extends IcuResFileLoader +{ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue + { + if (!stream_is_local($resource.'.dat')) { + throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); + } + + if (!file_exists($resource.'.dat')) { + throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); + } + + try { + $rb = new \ResourceBundle($locale, $resource); + } catch (\Exception) { + $rb = null; + } + + if (!$rb) { + throw new InvalidResourceException(sprintf('Cannot load resource "%s".', $resource)); + } elseif (intl_is_failure($rb->getErrorCode())) { + throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode()); + } + + $messages = $this->flatten($rb); + $catalogue = new MessageCatalogue($locale); + $catalogue->add($messages, $domain); + + if (class_exists(FileResource::class)) { + $catalogue->addResource(new FileResource($resource.'.dat')); + } + + return $catalogue; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/IcuResFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/IcuResFileLoader.php new file mode 100644 index 0000000..949dd97 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/IcuResFileLoader.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Config\Resource\DirectoryResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * IcuResFileLoader loads translations from a resource bundle. + * + * @author stealth35 + */ +class IcuResFileLoader implements LoaderInterface +{ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue + { + if (!stream_is_local($resource)) { + throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); + } + + if (!is_dir($resource)) { + throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); + } + + try { + $rb = new \ResourceBundle($locale, $resource); + } catch (\Exception) { + $rb = null; + } + + if (!$rb) { + throw new InvalidResourceException(sprintf('Cannot load resource "%s".', $resource)); + } elseif (intl_is_failure($rb->getErrorCode())) { + throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode()); + } + + $messages = $this->flatten($rb); + $catalogue = new MessageCatalogue($locale); + $catalogue->add($messages, $domain); + + if (class_exists(DirectoryResource::class)) { + $catalogue->addResource(new DirectoryResource($resource)); + } + + return $catalogue; + } + + /** + * Flattens an ResourceBundle. + * + * The scheme used is: + * key { key2 { key3 { "value" } } } + * Becomes: + * 'key.key2.key3' => 'value' + * + * This function takes an array by reference and will modify it + * + * @param \ResourceBundle $rb The ResourceBundle that will be flattened + * @param array $messages Used internally for recursive calls + * @param string|null $path Current path being parsed, used internally for recursive calls + */ + protected function flatten(\ResourceBundle $rb, array &$messages = [], ?string $path = null): array + { + foreach ($rb as $key => $value) { + $nodePath = $path ? $path.'.'.$key : $key; + if ($value instanceof \ResourceBundle) { + $this->flatten($value, $messages, $nodePath); + } else { + $messages[$nodePath] = $value; + } + } + + return $messages; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/IniFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/IniFileLoader.php new file mode 100644 index 0000000..3126896 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/IniFileLoader.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +/** + * IniFileLoader loads translations from an ini file. + * + * @author stealth35 + */ +class IniFileLoader extends FileLoader +{ + protected function loadResource(string $resource): array + { + return parse_ini_file($resource, true); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/JsonFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/JsonFileLoader.php new file mode 100644 index 0000000..385553e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/JsonFileLoader.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\Translation\Loader; + +use Symfony\Component\Translation\Exception\InvalidResourceException; + +/** + * JsonFileLoader loads translations from an json file. + * + * @author singles + */ +class JsonFileLoader extends FileLoader +{ + protected function loadResource(string $resource): array + { + $messages = []; + if ($data = file_get_contents($resource)) { + $messages = json_decode($data, true); + + if (0 < $errorCode = json_last_error()) { + throw new InvalidResourceException('Error parsing JSON: '.$this->getJSONErrorMessage($errorCode)); + } + } + + return $messages; + } + + /** + * Translates JSON_ERROR_* constant into meaningful message. + */ + private function getJSONErrorMessage(int $errorCode): string + { + return match ($errorCode) { + \JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + \JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', + \JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + \JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + \JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', + default => 'Unknown error', + }; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/LoaderInterface.php b/php/libraries/composer/vendor/symfony/translation/Loader/LoaderInterface.php new file mode 100644 index 0000000..29d5560 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/LoaderInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * LoaderInterface is the interface implemented by all translation loaders. + * + * @author Fabien Potencier + */ +interface LoaderInterface +{ + /** + * Loads a locale. + * + * @throws NotFoundResourceException when the resource cannot be found + * @throws InvalidResourceException when the resource cannot be loaded + */ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/MoFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/MoFileLoader.php new file mode 100644 index 0000000..8427c39 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/MoFileLoader.php @@ -0,0 +1,138 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Translation\Exception\InvalidResourceException; + +/** + * @copyright Copyright (c) 2010, Union of RAD http://union-of-rad.org (http://lithify.me/) + */ +class MoFileLoader extends FileLoader +{ + /** + * Magic used for validating the format of an MO file as well as + * detecting if the machine used to create that file was little endian. + */ + public const MO_LITTLE_ENDIAN_MAGIC = 0x950412DE; + + /** + * Magic used for validating the format of an MO file as well as + * detecting if the machine used to create that file was big endian. + */ + public const MO_BIG_ENDIAN_MAGIC = 0xDE120495; + + /** + * The size of the header of an MO file in bytes. + */ + public const MO_HEADER_SIZE = 28; + + /** + * Parses machine object (MO) format, independent of the machine's endian it + * was created on. Both 32bit and 64bit systems are supported. + */ + protected function loadResource(string $resource): array + { + $stream = fopen($resource, 'r'); + + $stat = fstat($stream); + + if ($stat['size'] < self::MO_HEADER_SIZE) { + throw new InvalidResourceException('MO stream content has an invalid format.'); + } + $magic = unpack('V1', fread($stream, 4)); + $magic = hexdec(substr(dechex(current($magic)), -8)); + + if (self::MO_LITTLE_ENDIAN_MAGIC == $magic) { + $isBigEndian = false; + } elseif (self::MO_BIG_ENDIAN_MAGIC == $magic) { + $isBigEndian = true; + } else { + throw new InvalidResourceException('MO stream content has an invalid format.'); + } + + // formatRevision + $this->readLong($stream, $isBigEndian); + $count = $this->readLong($stream, $isBigEndian); + $offsetId = $this->readLong($stream, $isBigEndian); + $offsetTranslated = $this->readLong($stream, $isBigEndian); + // sizeHashes + $this->readLong($stream, $isBigEndian); + // offsetHashes + $this->readLong($stream, $isBigEndian); + + $messages = []; + + for ($i = 0; $i < $count; ++$i) { + $pluralId = null; + $translated = null; + + fseek($stream, $offsetId + $i * 8); + + $length = $this->readLong($stream, $isBigEndian); + $offset = $this->readLong($stream, $isBigEndian); + + if ($length < 1) { + continue; + } + + fseek($stream, $offset); + $singularId = fread($stream, $length); + + if (str_contains($singularId, "\000")) { + [$singularId, $pluralId] = explode("\000", $singularId); + } + + fseek($stream, $offsetTranslated + $i * 8); + $length = $this->readLong($stream, $isBigEndian); + $offset = $this->readLong($stream, $isBigEndian); + + if ($length < 1) { + continue; + } + + fseek($stream, $offset); + $translated = fread($stream, $length); + + if (str_contains($translated, "\000")) { + $translated = explode("\000", $translated); + } + + $ids = ['singular' => $singularId, 'plural' => $pluralId]; + $item = compact('ids', 'translated'); + + if (!empty($item['ids']['singular'])) { + $id = $item['ids']['singular']; + if (isset($item['ids']['plural'])) { + $id .= '|'.$item['ids']['plural']; + } + $messages[$id] = stripcslashes(implode('|', (array) $item['translated'])); + } + } + + fclose($stream); + + return array_filter($messages); + } + + /** + * Reads an unsigned long from stream respecting endianness. + * + * @param resource $stream + */ + private function readLong($stream, bool $isBigEndian): int + { + $result = unpack($isBigEndian ? 'N1' : 'V1', fread($stream, 4)); + $result = current($result); + + return (int) substr($result, -8); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/PhpFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/PhpFileLoader.php new file mode 100644 index 0000000..541b6c8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/PhpFileLoader.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +/** + * PhpFileLoader loads translations from PHP files returning an array of translations. + * + * @author Fabien Potencier + */ +class PhpFileLoader extends FileLoader +{ + private static ?array $cache = []; + + protected function loadResource(string $resource): array + { + if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOL))) { + self::$cache = null; + } + + if (null === self::$cache) { + return require $resource; + } + + return self::$cache[$resource] ??= require $resource; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/PoFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/PoFileLoader.php new file mode 100644 index 0000000..620d973 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/PoFileLoader.php @@ -0,0 +1,147 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +/** + * @copyright Copyright (c) 2010, Union of RAD https://github.com/UnionOfRAD/lithium + * @copyright Copyright (c) 2012, Clemens Tolboom + */ +class PoFileLoader extends FileLoader +{ + /** + * Parses portable object (PO) format. + * + * From https://www.gnu.org/software/gettext/manual/gettext.html#PO-Files + * we should be able to parse files having: + * + * white-space + * # translator-comments + * #. extracted-comments + * #: reference... + * #, flag... + * #| msgid previous-untranslated-string + * msgid untranslated-string + * msgstr translated-string + * + * extra or different lines are: + * + * #| msgctxt previous-context + * #| msgid previous-untranslated-string + * msgctxt context + * + * #| msgid previous-untranslated-string-singular + * #| msgid_plural previous-untranslated-string-plural + * msgid untranslated-string-singular + * msgid_plural untranslated-string-plural + * msgstr[0] translated-string-case-0 + * ... + * msgstr[N] translated-string-case-n + * + * The definition states: + * - white-space and comments are optional. + * - msgid "" that an empty singleline defines a header. + * + * This parser sacrifices some features of the reference implementation the + * differences to that implementation are as follows. + * - No support for comments spanning multiple lines. + * - Translator and extracted comments are treated as being the same type. + * - Message IDs are allowed to have other encodings as just US-ASCII. + * + * Items with an empty id are ignored. + */ + protected function loadResource(string $resource): array + { + $stream = fopen($resource, 'r'); + + $defaults = [ + 'ids' => [], + 'translated' => null, + ]; + + $messages = []; + $item = $defaults; + $flags = []; + + while ($line = fgets($stream)) { + $line = trim($line); + + if ('' === $line) { + // Whitespace indicated current item is done + if (!\in_array('fuzzy', $flags)) { + $this->addMessage($messages, $item); + } + $item = $defaults; + $flags = []; + } elseif (str_starts_with($line, '#,')) { + $flags = array_map('trim', explode(',', substr($line, 2))); + } elseif (str_starts_with($line, 'msgid "')) { + // We start a new msg so save previous + // TODO: this fails when comments or contexts are added + $this->addMessage($messages, $item); + $item = $defaults; + $item['ids']['singular'] = substr($line, 7, -1); + } elseif (str_starts_with($line, 'msgstr "')) { + $item['translated'] = substr($line, 8, -1); + } elseif ('"' === $line[0]) { + $continues = isset($item['translated']) ? 'translated' : 'ids'; + + if (\is_array($item[$continues])) { + end($item[$continues]); + $item[$continues][key($item[$continues])] .= substr($line, 1, -1); + } else { + $item[$continues] .= substr($line, 1, -1); + } + } elseif (str_starts_with($line, 'msgid_plural "')) { + $item['ids']['plural'] = substr($line, 14, -1); + } elseif (str_starts_with($line, 'msgstr[')) { + $size = strpos($line, ']'); + $item['translated'][(int) substr($line, 7, 1)] = substr($line, $size + 3, -1); + } + } + // save last item + if (!\in_array('fuzzy', $flags)) { + $this->addMessage($messages, $item); + } + fclose($stream); + + return $messages; + } + + /** + * Save a translation item to the messages. + * + * A .po file could contain by error missing plural indexes. We need to + * fix these before saving them. + */ + private function addMessage(array &$messages, array $item): void + { + if (!empty($item['ids']['singular'])) { + $id = stripcslashes($item['ids']['singular']); + if (isset($item['ids']['plural'])) { + $id .= '|'.stripcslashes($item['ids']['plural']); + } + + $translated = (array) $item['translated']; + // PO are by definition indexed so sort by index. + ksort($translated); + // Make sure every index is filled. + end($translated); + $count = key($translated); + // Fill missing spots with '-'. + $empties = array_fill(0, $count + 1, '-'); + $translated += $empties; + ksort($translated); + + $messages[$id] = stripcslashes(implode('|', $translated)); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/QtFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/QtFileLoader.php new file mode 100644 index 0000000..235f85e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/QtFileLoader.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Util\XmlUtils; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\Exception\RuntimeException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * QtFileLoader loads translations from QT Translations XML files. + * + * @author Benjamin Eberlei + */ +class QtFileLoader implements LoaderInterface +{ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue + { + if (!class_exists(XmlUtils::class)) { + throw new RuntimeException('Loading translations from the QT format requires the Symfony Config component.'); + } + + if (!stream_is_local($resource)) { + throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); + } + + if (!file_exists($resource)) { + throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); + } + + try { + $dom = XmlUtils::loadFile($resource); + } catch (\InvalidArgumentException $e) { + throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e); + } + + $internalErrors = libxml_use_internal_errors(true); + libxml_clear_errors(); + + $xpath = new \DOMXPath($dom); + $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]'); + + $catalogue = new MessageCatalogue($locale); + if (1 == $nodes->length) { + $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message'); + foreach ($translations as $translation) { + $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue; + + if (!empty($translationValue)) { + $catalogue->set( + (string) $translation->getElementsByTagName('source')->item(0)->nodeValue, + $translationValue, + $domain + ); + } + } + + if (class_exists(FileResource::class)) { + $catalogue->addResource(new FileResource($resource)); + } + } + + libxml_use_internal_errors($internalErrors); + + return $catalogue; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Loader/XliffFileLoader.php b/php/libraries/composer/vendor/symfony/translation/Loader/XliffFileLoader.php new file mode 100644 index 0000000..31b3251 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Loader/XliffFileLoader.php @@ -0,0 +1,237 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Util\Exception\InvalidXmlException; +use Symfony\Component\Config\Util\Exception\XmlParsingException; +use Symfony\Component\Config\Util\XmlUtils; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\Exception\RuntimeException; +use Symfony\Component\Translation\MessageCatalogue; +use Symfony\Component\Translation\Util\XliffUtils; + +/** + * XliffFileLoader loads translations from XLIFF files. + * + * @author Fabien Potencier + */ +class XliffFileLoader implements LoaderInterface +{ + public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue + { + if (!class_exists(XmlUtils::class)) { + throw new RuntimeException('Loading translations from the Xliff format requires the Symfony Config component.'); + } + + if (!$this->isXmlString($resource)) { + if (!stream_is_local($resource)) { + throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); + } + + if (!file_exists($resource)) { + throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); + } + + if (!is_file($resource)) { + throw new InvalidResourceException(sprintf('This is neither a file nor an XLIFF string "%s".', $resource)); + } + } + + try { + if ($this->isXmlString($resource)) { + $dom = XmlUtils::parse($resource); + } else { + $dom = XmlUtils::loadFile($resource); + } + } catch (\InvalidArgumentException|XmlParsingException|InvalidXmlException $e) { + throw new InvalidResourceException(sprintf('Unable to load "%s": ', $resource).$e->getMessage(), $e->getCode(), $e); + } + + if ($errors = XliffUtils::validateSchema($dom)) { + throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: ', $resource).XliffUtils::getErrorsAsString($errors)); + } + + $catalogue = new MessageCatalogue($locale); + $this->extract($dom, $catalogue, $domain); + + if (is_file($resource) && class_exists(FileResource::class)) { + $catalogue->addResource(new FileResource($resource)); + } + + return $catalogue; + } + + private function extract(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void + { + $xliffVersion = XliffUtils::getVersionNumber($dom); + + if ('1.2' === $xliffVersion) { + $this->extractXliff1($dom, $catalogue, $domain); + } + + if ('2.0' === $xliffVersion) { + $this->extractXliff2($dom, $catalogue, $domain); + } + } + + /** + * Extract messages and metadata from DOMDocument into a MessageCatalogue. + */ + private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void + { + $xml = simplexml_import_dom($dom); + $encoding = $dom->encoding ? strtoupper($dom->encoding) : null; + + $namespace = 'urn:oasis:names:tc:xliff:document:1.2'; + $xml->registerXPathNamespace('xliff', $namespace); + + foreach ($xml->xpath('//xliff:file') as $file) { + $fileAttributes = $file->attributes(); + + $file->registerXPathNamespace('xliff', $namespace); + + foreach ($file->xpath('.//xliff:prop') as $prop) { + $catalogue->setCatalogueMetadata($prop->attributes()['prop-type'], (string) $prop, $domain); + } + + foreach ($file->xpath('.//xliff:trans-unit') as $translation) { + $attributes = $translation->attributes(); + + if (!(isset($attributes['resname']) || isset($translation->source))) { + continue; + } + + if (isset($translation->target) && 'needs-translation' === (string) $translation->target->attributes()['state']) { + continue; + } + + $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source; + // If the xlf file has another encoding specified, try to convert it because + // simple_xml will always return utf-8 encoded values + $target = $this->utf8ToCharset((string) ($translation->target ?? $translation->source), $encoding); + + $catalogue->set((string) $source, $target, $domain); + + $metadata = [ + 'source' => (string) $translation->source, + 'file' => [ + 'original' => (string) $fileAttributes['original'], + ], + ]; + if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) { + $metadata['notes'] = $notes; + } + + if (isset($translation->target) && $translation->target->attributes()) { + $metadata['target-attributes'] = []; + foreach ($translation->target->attributes() as $key => $value) { + $metadata['target-attributes'][$key] = (string) $value; + } + } + + if (isset($attributes['id'])) { + $metadata['id'] = (string) $attributes['id']; + } + + $catalogue->setMetadata((string) $source, $metadata, $domain); + } + } + } + + private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void + { + $xml = simplexml_import_dom($dom); + $encoding = $dom->encoding ? strtoupper($dom->encoding) : null; + + $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0'); + + foreach ($xml->xpath('//xliff:unit') as $unit) { + foreach ($unit->segment as $segment) { + $attributes = $unit->attributes(); + $source = $attributes['name'] ?? $segment->source; + + // If the xlf file has another encoding specified, try to convert it because + // simple_xml will always return utf-8 encoded values + $target = $this->utf8ToCharset((string) ($segment->target ?? $segment->source), $encoding); + + $catalogue->set((string) $source, $target, $domain); + + $metadata = []; + if (isset($segment->target) && $segment->target->attributes()) { + $metadata['target-attributes'] = []; + foreach ($segment->target->attributes() as $key => $value) { + $metadata['target-attributes'][$key] = (string) $value; + } + } + + if (isset($unit->notes)) { + $metadata['notes'] = []; + foreach ($unit->notes->note as $noteNode) { + $note = []; + foreach ($noteNode->attributes() as $key => $value) { + $note[$key] = (string) $value; + } + $note['content'] = (string) $noteNode; + $metadata['notes'][] = $note; + } + } + + $catalogue->setMetadata((string) $source, $metadata, $domain); + } + } + } + + /** + * Convert a UTF8 string to the specified encoding. + */ + private function utf8ToCharset(string $content, ?string $encoding = null): string + { + if ('UTF-8' !== $encoding && !empty($encoding)) { + return mb_convert_encoding($content, $encoding, 'UTF-8'); + } + + return $content; + } + + private function parseNotesMetadata(?\SimpleXMLElement $noteElement = null, ?string $encoding = null): array + { + $notes = []; + + if (null === $noteElement) { + return $notes; + } + + /** @var \SimpleXMLElement $xmlNote */ + foreach ($noteElement as $xmlNote) { + $noteAttributes = $xmlNote->attributes(); + $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)]; + if (isset($noteAttributes['priority'])) { + $note['priority'] = (int) $noteAttributes['priority']; + } + + if (isset($noteAttributes['from'])) { + $note['from'] = (string) $noteAttributes['from']; + } + + $notes[] = $note; + } + + return $notes; + } + + private function isXmlString(string $resource): bool + { + return str_starts_with($resource, ' + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Loader; + +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\LogicException; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Parser as YamlParser; +use Symfony\Component\Yaml\Yaml; + +/** + * YamlFileLoader loads translations from Yaml files. + * + * @author Fabien Potencier + */ +class YamlFileLoader extends FileLoader +{ + private YamlParser $yamlParser; + + protected function loadResource(string $resource): array + { + if (!isset($this->yamlParser)) { + if (!class_exists(\Symfony\Component\Yaml\Parser::class)) { + throw new LogicException('Loading translations from the YAML format requires the Symfony Yaml component.'); + } + + $this->yamlParser = new YamlParser(); + } + + try { + $messages = $this->yamlParser->parseFile($resource, Yaml::PARSE_CONSTANT); + } catch (ParseException $e) { + throw new InvalidResourceException(sprintf('The file "%s" does not contain valid YAML: ', $resource).$e->getMessage(), 0, $e); + } + + if (null !== $messages && !\is_array($messages)) { + throw new InvalidResourceException(sprintf('Unable to load file "%s".', $resource)); + } + + return $messages ?: []; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/LocaleSwitcher.php b/php/libraries/composer/vendor/symfony/translation/LocaleSwitcher.php new file mode 100644 index 0000000..c07809c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/LocaleSwitcher.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\Routing\RequestContext; +use Symfony\Contracts\Translation\LocaleAwareInterface; + +/** + * @author Kevin Bond + */ +class LocaleSwitcher implements LocaleAwareInterface +{ + private string $defaultLocale; + + /** + * @param LocaleAwareInterface[] $localeAwareServices + */ + public function __construct( + private string $locale, + private iterable $localeAwareServices, + private ?RequestContext $requestContext = null, + ) { + $this->defaultLocale = $locale; + } + + public function setLocale(string $locale): void + { + if (class_exists(\Locale::class)) { + \Locale::setDefault($locale); + } + $this->locale = $locale; + $this->requestContext?->setParameter('_locale', $locale); + + foreach ($this->localeAwareServices as $service) { + $service->setLocale($locale); + } + } + + public function getLocale(): string + { + return $this->locale; + } + + /** + * Switch to a new locale, execute a callback, then switch back to the original. + * + * @template T + * + * @param callable(string $locale):T $callback + * + * @return T + */ + public function runWithLocale(string $locale, callable $callback): mixed + { + $original = $this->getLocale(); + $this->setLocale($locale); + + try { + return $callback($locale); + } finally { + $this->setLocale($original); + } + } + + public function reset(): void + { + $this->setLocale($this->defaultLocale); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/LoggingTranslator.php b/php/libraries/composer/vendor/symfony/translation/LoggingTranslator.php new file mode 100644 index 0000000..4a560bd --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/LoggingTranslator.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Contracts\Translation\LocaleAwareInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +/** + * @author Abdellatif Ait boudad + */ +class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, LocaleAwareInterface +{ + private TranslatorInterface $translator; + private LoggerInterface $logger; + + /** + * @param TranslatorInterface&TranslatorBagInterface&LocaleAwareInterface $translator The translator must implement TranslatorBagInterface + */ + public function __construct(TranslatorInterface $translator, LoggerInterface $logger) + { + if (!$translator instanceof TranslatorBagInterface || !$translator instanceof LocaleAwareInterface) { + throw new InvalidArgumentException(sprintf('The Translator "%s" must implement TranslatorInterface, TranslatorBagInterface and LocaleAwareInterface.', get_debug_type($translator))); + } + + $this->translator = $translator; + $this->logger = $logger; + } + + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + $trans = $this->translator->trans($id = (string) $id, $parameters, $domain, $locale); + $this->log($id, $domain, $locale); + + return $trans; + } + + /** + * @return void + */ + public function setLocale(string $locale) + { + $prev = $this->translator->getLocale(); + $this->translator->setLocale($locale); + if ($prev === $locale) { + return; + } + + $this->logger->debug(sprintf('The locale of the translator has changed from "%s" to "%s".', $prev, $locale)); + } + + public function getLocale(): string + { + return $this->translator->getLocale(); + } + + public function getCatalogue(?string $locale = null): MessageCatalogueInterface + { + return $this->translator->getCatalogue($locale); + } + + public function getCatalogues(): array + { + return $this->translator->getCatalogues(); + } + + /** + * Gets the fallback locales. + */ + public function getFallbackLocales(): array + { + if ($this->translator instanceof Translator || method_exists($this->translator, 'getFallbackLocales')) { + return $this->translator->getFallbackLocales(); + } + + return []; + } + + /** + * @return mixed + */ + public function __call(string $method, array $args) + { + return $this->translator->{$method}(...$args); + } + + /** + * Logs for missing translations. + */ + private function log(string $id, ?string $domain, ?string $locale): void + { + $domain ??= 'messages'; + + $catalogue = $this->translator->getCatalogue($locale); + if ($catalogue->defines($id, $domain)) { + return; + } + + if ($catalogue->has($id, $domain)) { + $this->logger->debug('Translation use fallback catalogue.', ['id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale()]); + } else { + $this->logger->warning('Translation not found.', ['id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale()]); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/MessageCatalogue.php b/php/libraries/composer/vendor/symfony/translation/MessageCatalogue.php new file mode 100644 index 0000000..d56f043 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/MessageCatalogue.php @@ -0,0 +1,338 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\Config\Resource\ResourceInterface; +use Symfony\Component\Translation\Exception\LogicException; + +/** + * @author Fabien Potencier + */ +class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterface, CatalogueMetadataAwareInterface +{ + private array $messages = []; + private array $metadata = []; + private array $catalogueMetadata = []; + private array $resources = []; + private string $locale; + private ?MessageCatalogueInterface $fallbackCatalogue = null; + private ?self $parent = null; + + /** + * @param array $messages An array of messages classified by domain + */ + public function __construct(string $locale, array $messages = []) + { + $this->locale = $locale; + $this->messages = $messages; + } + + public function getLocale(): string + { + return $this->locale; + } + + public function getDomains(): array + { + $domains = []; + + foreach ($this->messages as $domain => $messages) { + if (str_ends_with($domain, self::INTL_DOMAIN_SUFFIX)) { + $domain = substr($domain, 0, -\strlen(self::INTL_DOMAIN_SUFFIX)); + } + $domains[$domain] = $domain; + } + + return array_values($domains); + } + + public function all(?string $domain = null): array + { + if (null !== $domain) { + // skip messages merge if intl-icu requested explicitly + if (str_ends_with($domain, self::INTL_DOMAIN_SUFFIX)) { + return $this->messages[$domain] ?? []; + } + + return ($this->messages[$domain.self::INTL_DOMAIN_SUFFIX] ?? []) + ($this->messages[$domain] ?? []); + } + + $allMessages = []; + + foreach ($this->messages as $domain => $messages) { + if (str_ends_with($domain, self::INTL_DOMAIN_SUFFIX)) { + $domain = substr($domain, 0, -\strlen(self::INTL_DOMAIN_SUFFIX)); + $allMessages[$domain] = $messages + ($allMessages[$domain] ?? []); + } else { + $allMessages[$domain] = ($allMessages[$domain] ?? []) + $messages; + } + } + + return $allMessages; + } + + /** + * @return void + */ + public function set(string $id, string $translation, string $domain = 'messages') + { + $this->add([$id => $translation], $domain); + } + + public function has(string $id, string $domain = 'messages'): bool + { + if (isset($this->messages[$domain][$id]) || isset($this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id])) { + return true; + } + + if (null !== $this->fallbackCatalogue) { + return $this->fallbackCatalogue->has($id, $domain); + } + + return false; + } + + public function defines(string $id, string $domain = 'messages'): bool + { + return isset($this->messages[$domain][$id]) || isset($this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id]); + } + + public function get(string $id, string $domain = 'messages'): string + { + if (isset($this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id])) { + return $this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id]; + } + + if (isset($this->messages[$domain][$id])) { + return $this->messages[$domain][$id]; + } + + if (null !== $this->fallbackCatalogue) { + return $this->fallbackCatalogue->get($id, $domain); + } + + return $id; + } + + /** + * @return void + */ + public function replace(array $messages, string $domain = 'messages') + { + unset($this->messages[$domain], $this->messages[$domain.self::INTL_DOMAIN_SUFFIX]); + + $this->add($messages, $domain); + } + + /** + * @return void + */ + public function add(array $messages, string $domain = 'messages') + { + $altDomain = str_ends_with($domain, self::INTL_DOMAIN_SUFFIX) ? substr($domain, 0, -\strlen(self::INTL_DOMAIN_SUFFIX)) : $domain.self::INTL_DOMAIN_SUFFIX; + foreach ($messages as $id => $message) { + unset($this->messages[$altDomain][$id]); + $this->messages[$domain][$id] = $message; + } + + if ([] === ($this->messages[$altDomain] ?? null)) { + unset($this->messages[$altDomain]); + } + } + + /** + * @return void + */ + public function addCatalogue(MessageCatalogueInterface $catalogue) + { + if ($catalogue->getLocale() !== $this->locale) { + throw new LogicException(sprintf('Cannot add a catalogue for locale "%s" as the current locale for this catalogue is "%s".', $catalogue->getLocale(), $this->locale)); + } + + foreach ($catalogue->all() as $domain => $messages) { + if ($intlMessages = $catalogue->all($domain.self::INTL_DOMAIN_SUFFIX)) { + $this->add($intlMessages, $domain.self::INTL_DOMAIN_SUFFIX); + $messages = array_diff_key($messages, $intlMessages); + } + $this->add($messages, $domain); + } + + foreach ($catalogue->getResources() as $resource) { + $this->addResource($resource); + } + + if ($catalogue instanceof MetadataAwareInterface) { + $metadata = $catalogue->getMetadata('', ''); + $this->addMetadata($metadata); + } + + if ($catalogue instanceof CatalogueMetadataAwareInterface) { + $catalogueMetadata = $catalogue->getCatalogueMetadata('', ''); + $this->addCatalogueMetadata($catalogueMetadata); + } + } + + /** + * @return void + */ + public function addFallbackCatalogue(MessageCatalogueInterface $catalogue) + { + // detect circular references + $c = $catalogue; + while ($c = $c->getFallbackCatalogue()) { + if ($c->getLocale() === $this->getLocale()) { + throw new LogicException(sprintf('Circular reference detected when adding a fallback catalogue for locale "%s".', $catalogue->getLocale())); + } + } + + $c = $this; + do { + if ($c->getLocale() === $catalogue->getLocale()) { + throw new LogicException(sprintf('Circular reference detected when adding a fallback catalogue for locale "%s".', $catalogue->getLocale())); + } + + foreach ($catalogue->getResources() as $resource) { + $c->addResource($resource); + } + } while ($c = $c->parent); + + $catalogue->parent = $this; + $this->fallbackCatalogue = $catalogue; + + foreach ($catalogue->getResources() as $resource) { + $this->addResource($resource); + } + } + + public function getFallbackCatalogue(): ?MessageCatalogueInterface + { + return $this->fallbackCatalogue; + } + + public function getResources(): array + { + return array_values($this->resources); + } + + /** + * @return void + */ + public function addResource(ResourceInterface $resource) + { + $this->resources[$resource->__toString()] = $resource; + } + + public function getMetadata(string $key = '', string $domain = 'messages'): mixed + { + if ('' == $domain) { + return $this->metadata; + } + + if (isset($this->metadata[$domain])) { + if ('' == $key) { + return $this->metadata[$domain]; + } + + if (isset($this->metadata[$domain][$key])) { + return $this->metadata[$domain][$key]; + } + } + + return null; + } + + /** + * @return void + */ + public function setMetadata(string $key, mixed $value, string $domain = 'messages') + { + $this->metadata[$domain][$key] = $value; + } + + /** + * @return void + */ + public function deleteMetadata(string $key = '', string $domain = 'messages') + { + if ('' == $domain) { + $this->metadata = []; + } elseif ('' == $key) { + unset($this->metadata[$domain]); + } else { + unset($this->metadata[$domain][$key]); + } + } + + public function getCatalogueMetadata(string $key = '', string $domain = 'messages'): mixed + { + if (!$domain) { + return $this->catalogueMetadata; + } + + if (isset($this->catalogueMetadata[$domain])) { + if (!$key) { + return $this->catalogueMetadata[$domain]; + } + + if (isset($this->catalogueMetadata[$domain][$key])) { + return $this->catalogueMetadata[$domain][$key]; + } + } + + return null; + } + + /** + * @return void + */ + public function setCatalogueMetadata(string $key, mixed $value, string $domain = 'messages') + { + $this->catalogueMetadata[$domain][$key] = $value; + } + + /** + * @return void + */ + public function deleteCatalogueMetadata(string $key = '', string $domain = 'messages') + { + if (!$domain) { + $this->catalogueMetadata = []; + } elseif (!$key) { + unset($this->catalogueMetadata[$domain]); + } else { + unset($this->catalogueMetadata[$domain][$key]); + } + } + + /** + * Adds current values with the new values. + * + * @param array $values Values to add + */ + private function addMetadata(array $values): void + { + foreach ($values as $domain => $keys) { + foreach ($keys as $key => $value) { + $this->setMetadata($key, $value, $domain); + } + } + } + + private function addCatalogueMetadata(array $values): void + { + foreach ($values as $domain => $keys) { + foreach ($keys as $key => $value) { + $this->setCatalogueMetadata($key, $value, $domain); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/MessageCatalogueInterface.php b/php/libraries/composer/vendor/symfony/translation/MessageCatalogueInterface.php new file mode 100644 index 0000000..fd0d26d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/MessageCatalogueInterface.php @@ -0,0 +1,134 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\Config\Resource\ResourceInterface; + +/** + * MessageCatalogueInterface. + * + * @author Fabien Potencier + */ +interface MessageCatalogueInterface +{ + public const INTL_DOMAIN_SUFFIX = '+intl-icu'; + + /** + * Gets the catalogue locale. + */ + public function getLocale(): string; + + /** + * Gets the domains. + */ + public function getDomains(): array; + + /** + * Gets the messages within a given domain. + * + * If $domain is null, it returns all messages. + */ + public function all(?string $domain = null): array; + + /** + * Sets a message translation. + * + * @param string $id The message id + * @param string $translation The messages translation + * @param string $domain The domain name + * + * @return void + */ + public function set(string $id, string $translation, string $domain = 'messages'); + + /** + * Checks if a message has a translation. + * + * @param string $id The message id + * @param string $domain The domain name + */ + public function has(string $id, string $domain = 'messages'): bool; + + /** + * Checks if a message has a translation (it does not take into account the fallback mechanism). + * + * @param string $id The message id + * @param string $domain The domain name + */ + public function defines(string $id, string $domain = 'messages'): bool; + + /** + * Gets a message translation. + * + * @param string $id The message id + * @param string $domain The domain name + */ + public function get(string $id, string $domain = 'messages'): string; + + /** + * Sets translations for a given domain. + * + * @param array $messages An array of translations + * @param string $domain The domain name + * + * @return void + */ + public function replace(array $messages, string $domain = 'messages'); + + /** + * Adds translations for a given domain. + * + * @param array $messages An array of translations + * @param string $domain The domain name + * + * @return void + */ + public function add(array $messages, string $domain = 'messages'); + + /** + * Merges translations from the given Catalogue into the current one. + * + * The two catalogues must have the same locale. + * + * @return void + */ + public function addCatalogue(self $catalogue); + + /** + * Merges translations from the given Catalogue into the current one + * only when the translation does not exist. + * + * This is used to provide default translations when they do not exist for the current locale. + * + * @return void + */ + public function addFallbackCatalogue(self $catalogue); + + /** + * Gets the fallback catalogue. + */ + public function getFallbackCatalogue(): ?self; + + /** + * Returns an array of resources loaded to build this collection. + * + * @return ResourceInterface[] + */ + public function getResources(): array; + + /** + * Adds a resource for this collection. + * + * @return void + */ + public function addResource(ResourceInterface $resource); +} diff --git a/php/libraries/composer/vendor/symfony/translation/MetadataAwareInterface.php b/php/libraries/composer/vendor/symfony/translation/MetadataAwareInterface.php new file mode 100644 index 0000000..39e5326 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/MetadataAwareInterface.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +/** + * This interface is used to get, set, and delete metadata about the translation messages. + * + * @author Fabien Potencier + */ +interface MetadataAwareInterface +{ + /** + * Gets metadata for the given domain and key. + * + * Passing an empty domain will return an array with all metadata indexed by + * domain and then by key. Passing an empty key will return an array with all + * metadata for the given domain. + * + * @return mixed The value that was set or an array with the domains/keys or null + */ + public function getMetadata(string $key = '', string $domain = 'messages'): mixed; + + /** + * Adds metadata to a message domain. + * + * @return void + */ + public function setMetadata(string $key, mixed $value, string $domain = 'messages'); + + /** + * Deletes metadata for the given key and domain. + * + * Passing an empty domain will delete all metadata. Passing an empty key will + * delete all metadata for the given domain. + * + * @return void + */ + public function deleteMetadata(string $key = '', string $domain = 'messages'); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/AbstractProviderFactory.php b/php/libraries/composer/vendor/symfony/translation/Provider/AbstractProviderFactory.php new file mode 100644 index 0000000..f0c11d8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/AbstractProviderFactory.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\Translation\Provider; + +use Symfony\Component\Translation\Exception\IncompleteDsnException; + +abstract class AbstractProviderFactory implements ProviderFactoryInterface +{ + public function supports(Dsn $dsn): bool + { + return \in_array($dsn->getScheme(), $this->getSupportedSchemes(), true); + } + + /** + * @return string[] + */ + abstract protected function getSupportedSchemes(): array; + + protected function getUser(Dsn $dsn): string + { + return $dsn->getUser() ?? throw new IncompleteDsnException('User is not set.', $dsn->getScheme().'://'.$dsn->getHost()); + } + + protected function getPassword(Dsn $dsn): string + { + return $dsn->getPassword() ?? throw new IncompleteDsnException('Password is not set.', $dsn->getOriginalDsn()); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/Dsn.php b/php/libraries/composer/vendor/symfony/translation/Provider/Dsn.php new file mode 100644 index 0000000..1d90e27 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/Dsn.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Provider; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\MissingRequiredOptionException; + +/** + * @author Fabien Potencier + * @author Oskar Stark + */ +final class Dsn +{ + private ?string $scheme; + private ?string $host; + private ?string $user; + private ?string $password; + private ?int $port; + private ?string $path; + private array $options = []; + private string $originalDsn; + + public function __construct(#[\SensitiveParameter] string $dsn) + { + $this->originalDsn = $dsn; + + if (false === $params = parse_url($dsn)) { + throw new InvalidArgumentException('The translation provider DSN is invalid.'); + } + + if (!isset($params['scheme'])) { + throw new InvalidArgumentException('The translation provider DSN must contain a scheme.'); + } + $this->scheme = $params['scheme']; + + if (!isset($params['host'])) { + throw new InvalidArgumentException('The translation provider DSN must contain a host (use "default" by default).'); + } + $this->host = $params['host']; + + $this->user = '' !== ($params['user'] ?? '') ? rawurldecode($params['user']) : null; + $this->password = '' !== ($params['pass'] ?? '') ? rawurldecode($params['pass']) : null; + $this->port = $params['port'] ?? null; + $this->path = $params['path'] ?? null; + parse_str($params['query'] ?? '', $this->options); + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getHost(): string + { + return $this->host; + } + + public function getUser(): ?string + { + return $this->user; + } + + public function getPassword(): ?string + { + return $this->password; + } + + public function getPort(?int $default = null): ?int + { + return $this->port ?? $default; + } + + public function getOption(string $key, mixed $default = null): mixed + { + return $this->options[$key] ?? $default; + } + + public function getRequiredOption(string $key): mixed + { + if (!\array_key_exists($key, $this->options) || '' === trim($this->options[$key])) { + throw new MissingRequiredOptionException($key); + } + + return $this->options[$key]; + } + + public function getOptions(): array + { + return $this->options; + } + + public function getPath(): ?string + { + return $this->path; + } + + public function getOriginalDsn(): string + { + return $this->originalDsn; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/FilteringProvider.php b/php/libraries/composer/vendor/symfony/translation/Provider/FilteringProvider.php new file mode 100644 index 0000000..d4465b9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/FilteringProvider.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Provider; + +use Symfony\Component\Translation\TranslatorBag; +use Symfony\Component\Translation\TranslatorBagInterface; + +/** + * Filters domains and locales between the Translator config values and those specific to each provider. + * + * @author Mathieu Santostefano + */ +class FilteringProvider implements ProviderInterface +{ + private ProviderInterface $provider; + private array $locales; + private array $domains; + + public function __construct(ProviderInterface $provider, array $locales, array $domains = []) + { + $this->provider = $provider; + $this->locales = $locales; + $this->domains = $domains; + } + + public function __toString(): string + { + return (string) $this->provider; + } + + public function write(TranslatorBagInterface $translatorBag): void + { + $this->provider->write($translatorBag); + } + + public function read(array $domains, array $locales): TranslatorBag + { + $domains = !$this->domains ? $domains : array_intersect($this->domains, $domains); + $locales = array_intersect($this->locales, $locales); + + return $this->provider->read($domains, $locales); + } + + public function delete(TranslatorBagInterface $translatorBag): void + { + $this->provider->delete($translatorBag); + } + + public function getDomains(): array + { + return $this->domains; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/NullProvider.php b/php/libraries/composer/vendor/symfony/translation/Provider/NullProvider.php new file mode 100644 index 0000000..f00392e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/NullProvider.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Provider; + +use Symfony\Component\Translation\TranslatorBag; +use Symfony\Component\Translation\TranslatorBagInterface; + +/** + * @author Mathieu Santostefano + */ +class NullProvider implements ProviderInterface +{ + public function __toString(): string + { + return 'null'; + } + + public function write(TranslatorBagInterface $translatorBag, bool $override = false): void + { + } + + public function read(array $domains, array $locales): TranslatorBag + { + return new TranslatorBag(); + } + + public function delete(TranslatorBagInterface $translatorBag): void + { + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/NullProviderFactory.php b/php/libraries/composer/vendor/symfony/translation/Provider/NullProviderFactory.php new file mode 100644 index 0000000..f350f16 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/NullProviderFactory.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Provider; + +use Symfony\Component\Translation\Exception\UnsupportedSchemeException; + +/** + * @author Mathieu Santostefano + */ +final class NullProviderFactory extends AbstractProviderFactory +{ + public function create(Dsn $dsn): ProviderInterface + { + if ('null' === $dsn->getScheme()) { + return new NullProvider(); + } + + throw new UnsupportedSchemeException($dsn, 'null', $this->getSupportedSchemes()); + } + + protected function getSupportedSchemes(): array + { + return ['null']; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/ProviderFactoryInterface.php b/php/libraries/composer/vendor/symfony/translation/Provider/ProviderFactoryInterface.php new file mode 100644 index 0000000..3fd4494 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/ProviderFactoryInterface.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\Translation\Provider; + +use Symfony\Component\Translation\Exception\IncompleteDsnException; +use Symfony\Component\Translation\Exception\UnsupportedSchemeException; + +interface ProviderFactoryInterface +{ + /** + * @throws UnsupportedSchemeException + * @throws IncompleteDsnException + */ + public function create(Dsn $dsn): ProviderInterface; + + public function supports(Dsn $dsn): bool; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/ProviderInterface.php b/php/libraries/composer/vendor/symfony/translation/Provider/ProviderInterface.php new file mode 100644 index 0000000..0e47083 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/ProviderInterface.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\Translation\Provider; + +use Symfony\Component\Translation\TranslatorBag; +use Symfony\Component\Translation\TranslatorBagInterface; + +interface ProviderInterface extends \Stringable +{ + /** + * Translations available in the TranslatorBag only must be created. + * Translations available in both the TranslatorBag and on the provider + * must be overwritten. + * Translations available on the provider only must be kept. + */ + public function write(TranslatorBagInterface $translatorBag): void; + + public function read(array $domains, array $locales): TranslatorBag; + + public function delete(TranslatorBagInterface $translatorBag): void; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/TranslationProviderCollection.php b/php/libraries/composer/vendor/symfony/translation/Provider/TranslationProviderCollection.php new file mode 100644 index 0000000..b917415 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/TranslationProviderCollection.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Provider; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; + +/** + * @author Mathieu Santostefano + */ +final class TranslationProviderCollection +{ + /** + * @var array + */ + private array $providers; + + /** + * @param array $providers + */ + public function __construct(iterable $providers) + { + $this->providers = \is_array($providers) ? $providers : iterator_to_array($providers); + } + + public function __toString(): string + { + return '['.implode(',', array_keys($this->providers)).']'; + } + + public function has(string $name): bool + { + return isset($this->providers[$name]); + } + + public function get(string $name): ProviderInterface + { + if (!$this->has($name)) { + throw new InvalidArgumentException(sprintf('Provider "%s" not found. Available: "%s".', $name, (string) $this)); + } + + return $this->providers[$name]; + } + + public function keys(): array + { + return array_keys($this->providers); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Provider/TranslationProviderCollectionFactory.php b/php/libraries/composer/vendor/symfony/translation/Provider/TranslationProviderCollectionFactory.php new file mode 100644 index 0000000..6300c87 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Provider/TranslationProviderCollectionFactory.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Provider; + +use Symfony\Component\Translation\Exception\UnsupportedSchemeException; + +/** + * @author Mathieu Santostefano + */ +class TranslationProviderCollectionFactory +{ + private iterable $factories; + private array $enabledLocales; + + /** + * @param iterable $factories + */ + public function __construct(iterable $factories, array $enabledLocales) + { + $this->factories = $factories; + $this->enabledLocales = $enabledLocales; + } + + public function fromConfig(array $config): TranslationProviderCollection + { + $providers = []; + foreach ($config as $name => $currentConfig) { + $providers[$name] = $this->fromDsnObject( + new Dsn($currentConfig['dsn']), + !$currentConfig['locales'] ? $this->enabledLocales : $currentConfig['locales'], + !$currentConfig['domains'] ? [] : $currentConfig['domains'] + ); + } + + return new TranslationProviderCollection($providers); + } + + public function fromDsnObject(Dsn $dsn, array $locales, array $domains = []): ProviderInterface + { + foreach ($this->factories as $factory) { + if ($factory->supports($dsn)) { + return new FilteringProvider($factory->create($dsn), $locales, $domains); + } + } + + throw new UnsupportedSchemeException($dsn); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/PseudoLocalizationTranslator.php b/php/libraries/composer/vendor/symfony/translation/PseudoLocalizationTranslator.php new file mode 100644 index 0000000..f26909f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/PseudoLocalizationTranslator.php @@ -0,0 +1,365 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Contracts\Translation\TranslatorInterface; + +/** + * This translator should only be used in a development environment. + */ +final class PseudoLocalizationTranslator implements TranslatorInterface +{ + private const EXPANSION_CHARACTER = '~'; + + private TranslatorInterface $translator; + private bool $accents; + private float $expansionFactor; + private bool $brackets; + private bool $parseHTML; + + /** + * @var string[] + */ + private array $localizableHTMLAttributes; + + /** + * Available options: + * * accents: + * type: boolean + * default: true + * description: replace ASCII characters of the translated string with accented versions or similar characters + * example: if true, "foo" => "ƒöö". + * + * * expansion_factor: + * type: float + * default: 1 + * validation: it must be greater than or equal to 1 + * description: expand the translated string by the given factor with spaces and tildes + * example: if 2, "foo" => "~foo ~" + * + * * brackets: + * type: boolean + * default: true + * description: wrap the translated string with brackets + * example: if true, "foo" => "[foo]" + * + * * parse_html: + * type: boolean + * default: false + * description: parse the translated string as HTML - looking for HTML tags has a performance impact but allows to preserve them from alterations - it also allows to compute the visible translated string length which is useful to correctly expand ot when it contains HTML + * warning: unclosed tags are unsupported, they will be fixed (closed) by the parser - eg, "foo
bar" => "foo
bar
" + * + * * localizable_html_attributes: + * type: string[] + * default: [] + * description: the list of HTML attributes whose values can be altered - it is only useful when the "parse_html" option is set to true + * example: if ["title"], and with the "accents" option set to true, "Profile" => "Þŕöƒîļé" - if "title" was not in the "localizable_html_attributes" list, the title attribute data would be left unchanged. + */ + public function __construct(TranslatorInterface $translator, array $options = []) + { + $this->translator = $translator; + $this->accents = $options['accents'] ?? true; + + if (1.0 > ($this->expansionFactor = $options['expansion_factor'] ?? 1.0)) { + throw new \InvalidArgumentException('The expansion factor must be greater than or equal to 1.'); + } + + $this->brackets = $options['brackets'] ?? true; + + $this->parseHTML = $options['parse_html'] ?? false; + if ($this->parseHTML && !$this->accents && 1.0 === $this->expansionFactor) { + $this->parseHTML = false; + } + + $this->localizableHTMLAttributes = $options['localizable_html_attributes'] ?? []; + } + + public function trans(string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + $trans = ''; + $visibleText = ''; + + foreach ($this->getParts($this->translator->trans($id, $parameters, $domain, $locale)) as [$visible, $localizable, $text]) { + if ($visible) { + $visibleText .= $text; + } + + if (!$localizable) { + $trans .= $text; + + continue; + } + + $this->addAccents($trans, $text); + } + + $this->expand($trans, $visibleText); + + $this->addBrackets($trans); + + return $trans; + } + + public function getLocale(): string + { + return $this->translator->getLocale(); + } + + private function getParts(string $originalTrans): array + { + if (!$this->parseHTML) { + return [[true, true, $originalTrans]]; + } + + $html = mb_encode_numericentity($originalTrans, [0x80, 0x10FFFF, 0, 0x1FFFFF], mb_detect_encoding($originalTrans, null, true) ?: 'UTF-8'); + + $useInternalErrors = libxml_use_internal_errors(true); + + $dom = new \DOMDocument(); + $dom->loadHTML(''.$html.''); + + libxml_clear_errors(); + libxml_use_internal_errors($useInternalErrors); + + return $this->parseNode($dom->childNodes->item(1)->childNodes->item(0)->childNodes->item(0)); + } + + private function parseNode(\DOMNode $node): array + { + $parts = []; + + foreach ($node->childNodes as $childNode) { + if (!$childNode instanceof \DOMElement) { + $parts[] = [true, true, $childNode->nodeValue]; + + continue; + } + + $parts[] = [false, false, '<'.$childNode->tagName]; + + /** @var \DOMAttr $attribute */ + foreach ($childNode->attributes as $attribute) { + $parts[] = [false, false, ' '.$attribute->nodeName.'="']; + + $localizableAttribute = \in_array($attribute->nodeName, $this->localizableHTMLAttributes, true); + foreach (preg_split('/(&(?:amp|quot|#039|lt|gt);+)/', htmlspecialchars($attribute->nodeValue, \ENT_QUOTES, 'UTF-8'), -1, \PREG_SPLIT_DELIM_CAPTURE) as $i => $match) { + if ('' === $match) { + continue; + } + + $parts[] = [false, $localizableAttribute && 0 === $i % 2, $match]; + } + + $parts[] = [false, false, '"']; + } + + $parts[] = [false, false, '>']; + + $parts = array_merge($parts, $this->parseNode($childNode, $parts)); + + $parts[] = [false, false, 'tagName.'>']; + } + + return $parts; + } + + private function addAccents(string &$trans, string $text): void + { + $trans .= $this->accents ? strtr($text, [ + ' ' => ' ', + '!' => '¡', + '"' => '″', + '#' => '♯', + '$' => '€', + '%' => '‰', + '&' => '⅋', + '\'' => '´', + '(' => '{', + ')' => '}', + '*' => '⁎', + '+' => '⁺', + ',' => '،', + '-' => '‐', + '.' => '·', + '/' => '⁄', + '0' => '⓪', + '1' => '①', + '2' => '②', + '3' => '③', + '4' => '④', + '5' => '⑤', + '6' => '⑥', + '7' => '⑦', + '8' => '⑧', + '9' => '⑨', + ':' => '∶', + ';' => '⁏', + '<' => '≤', + '=' => '≂', + '>' => '≥', + '?' => '¿', + '@' => '՞', + 'A' => 'Å', + 'B' => 'Ɓ', + 'C' => 'Ç', + 'D' => 'Ð', + 'E' => 'É', + 'F' => 'Ƒ', + 'G' => 'Ĝ', + 'H' => 'Ĥ', + 'I' => 'Î', + 'J' => 'Ĵ', + 'K' => 'Ķ', + 'L' => 'Ļ', + 'M' => 'Ṁ', + 'N' => 'Ñ', + 'O' => 'Ö', + 'P' => 'Þ', + 'Q' => 'Ǫ', + 'R' => 'Ŕ', + 'S' => 'Š', + 'T' => 'Ţ', + 'U' => 'Û', + 'V' => 'Ṽ', + 'W' => 'Ŵ', + 'X' => 'Ẋ', + 'Y' => 'Ý', + 'Z' => 'Ž', + '[' => '⁅', + '\\' => '∖', + ']' => '⁆', + '^' => '˄', + '_' => '‿', + '`' => '‵', + 'a' => 'å', + 'b' => 'ƀ', + 'c' => 'ç', + 'd' => 'ð', + 'e' => 'é', + 'f' => 'ƒ', + 'g' => 'ĝ', + 'h' => 'ĥ', + 'i' => 'î', + 'j' => 'ĵ', + 'k' => 'ķ', + 'l' => 'ļ', + 'm' => 'ɱ', + 'n' => 'ñ', + 'o' => 'ö', + 'p' => 'þ', + 'q' => 'ǫ', + 'r' => 'ŕ', + 's' => 'š', + 't' => 'ţ', + 'u' => 'û', + 'v' => 'ṽ', + 'w' => 'ŵ', + 'x' => 'ẋ', + 'y' => 'ý', + 'z' => 'ž', + '{' => '(', + '|' => '¦', + '}' => ')', + '~' => '˞', + ]) : $text; + } + + private function expand(string &$trans, string $visibleText): void + { + if (1.0 >= $this->expansionFactor) { + return; + } + + $visibleLength = $this->strlen($visibleText); + $missingLength = (int) ceil($visibleLength * $this->expansionFactor) - $visibleLength; + if ($this->brackets) { + $missingLength -= 2; + } + + if (0 >= $missingLength) { + return; + } + + $words = []; + $wordsCount = 0; + foreach (preg_split('/ +/', $visibleText, -1, \PREG_SPLIT_NO_EMPTY) as $word) { + $wordLength = $this->strlen($word); + + if ($wordLength >= $missingLength) { + continue; + } + + if (!isset($words[$wordLength])) { + $words[$wordLength] = 0; + } + + ++$words[$wordLength]; + ++$wordsCount; + } + + if (!$words) { + $trans .= 1 === $missingLength ? self::EXPANSION_CHARACTER : ' '.str_repeat(self::EXPANSION_CHARACTER, $missingLength - 1); + + return; + } + + arsort($words, \SORT_NUMERIC); + + $longestWordLength = max(array_keys($words)); + + while (true) { + $r = mt_rand(1, $wordsCount); + + foreach ($words as $length => $count) { + $r -= $count; + if ($r <= 0) { + break; + } + } + + $trans .= ' '.str_repeat(self::EXPANSION_CHARACTER, $length); + + $missingLength -= $length + 1; + + if (0 === $missingLength) { + return; + } + + while ($longestWordLength >= $missingLength) { + $wordsCount -= $words[$longestWordLength]; + unset($words[$longestWordLength]); + + if (!$words) { + $trans .= 1 === $missingLength ? self::EXPANSION_CHARACTER : ' '.str_repeat(self::EXPANSION_CHARACTER, $missingLength - 1); + + return; + } + + $longestWordLength = max(array_keys($words)); + } + } + } + + private function addBrackets(string &$trans): void + { + if (!$this->brackets) { + return; + } + + $trans = '['.$trans.']'; + } + + private function strlen(string $s): int + { + return false === ($encoding = mb_detect_encoding($s, null, true)) ? \strlen($s) : mb_strlen($s, $encoding); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/README.md b/php/libraries/composer/vendor/symfony/translation/README.md new file mode 100644 index 0000000..32e4017 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/README.md @@ -0,0 +1,40 @@ +Translation Component +===================== + +The Translation component provides tools to internationalize your application. + +Getting Started +--------------- + +``` +$ composer require symfony/translation +``` + +```php +use Symfony\Component\Translation\Translator; +use Symfony\Component\Translation\Loader\ArrayLoader; + +$translator = new Translator('fr_FR'); +$translator->addLoader('array', new ArrayLoader()); +$translator->addResource('array', [ + 'Hello World!' => 'Bonjour !', +], 'fr_FR'); + +echo $translator->trans('Hello World!'); // outputs « Bonjour ! » +``` + +Sponsor +------- + +Help Symfony by [sponsoring][1] its development! + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/translation.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +[1]: https://symfony.com/sponsor diff --git a/php/libraries/composer/vendor/symfony/translation/Reader/TranslationReader.php b/php/libraries/composer/vendor/symfony/translation/Reader/TranslationReader.php new file mode 100644 index 0000000..01408d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Reader/TranslationReader.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Reader; + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Translation\Loader\LoaderInterface; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * TranslationReader reads translation messages from translation files. + * + * @author Michel Salib + */ +class TranslationReader implements TranslationReaderInterface +{ + /** + * Loaders used for import. + * + * @var array + */ + private array $loaders = []; + + /** + * Adds a loader to the translation extractor. + * + * @param string $format The format of the loader + * + * @return void + */ + public function addLoader(string $format, LoaderInterface $loader) + { + $this->loaders[$format] = $loader; + } + + /** + * @return void + */ + public function read(string $directory, MessageCatalogue $catalogue) + { + if (!is_dir($directory)) { + return; + } + + foreach ($this->loaders as $format => $loader) { + // load any existing translation files + $finder = new Finder(); + $extension = $catalogue->getLocale().'.'.$format; + $files = $finder->files()->name('*.'.$extension)->in($directory); + foreach ($files as $file) { + $domain = substr($file->getFilename(), 0, -1 * \strlen($extension) - 1); + $catalogue->addCatalogue($loader->load($file->getPathname(), $catalogue->getLocale(), $domain)); + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Reader/TranslationReaderInterface.php b/php/libraries/composer/vendor/symfony/translation/Reader/TranslationReaderInterface.php new file mode 100644 index 0000000..ea74dc2 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Reader/TranslationReaderInterface.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Reader; + +use Symfony\Component\Translation\MessageCatalogue; + +/** + * TranslationReader reads translation messages from translation files. + * + * @author Tobias Nyholm + */ +interface TranslationReaderInterface +{ + /** + * Reads translation messages from a directory to the catalogue. + * + * @return void + */ + public function read(string $directory, MessageCatalogue $catalogue); +} diff --git a/php/libraries/composer/vendor/symfony/translation/Resources/bin/translation-status.php b/php/libraries/composer/vendor/symfony/translation/Resources/bin/translation-status.php new file mode 100644 index 0000000..8064190 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Resources/bin/translation-status.php @@ -0,0 +1,274 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if ('cli' !== \PHP_SAPI) { + throw new Exception('This script must be run from the command line.'); +} + +$usageInstructions = << false, + // NULL = analyze all locales + 'locale_to_analyze' => null, + // append --incomplete to only show incomplete languages + 'include_completed_languages' => true, + // the reference files all the other translations are compared to + 'original_files' => [ + 'src/Symfony/Component/Form/Resources/translations/validators.en.xlf', + 'src/Symfony/Component/Security/Core/Resources/translations/security.en.xlf', + 'src/Symfony/Component/Validator/Resources/translations/validators.en.xlf', + ], +]; + +$argc = $_SERVER['argc']; +$argv = $_SERVER['argv']; + +if ($argc > 4) { + echo str_replace('translation-status.php', $argv[0], $usageInstructions); + exit(1); +} + +foreach (array_slice($argv, 1) as $argumentOrOption) { + if ('--incomplete' === $argumentOrOption) { + $config['include_completed_languages'] = false; + continue; + } + + if (str_starts_with($argumentOrOption, '-')) { + $config['verbose_output'] = true; + } else { + $config['locale_to_analyze'] = $argumentOrOption; + } +} + +foreach ($config['original_files'] as $originalFilePath) { + if (!file_exists($originalFilePath)) { + echo sprintf('The following file does not exist. Make sure that you execute this command at the root dir of the Symfony code repository.%s %s', \PHP_EOL, $originalFilePath); + exit(1); + } +} + +$totalMissingTranslations = 0; +$totalTranslationMismatches = 0; + +foreach ($config['original_files'] as $originalFilePath) { + $translationFilePaths = findTranslationFiles($originalFilePath, $config['locale_to_analyze']); + $translationStatus = calculateTranslationStatus($originalFilePath, $translationFilePaths); + + $totalMissingTranslations += array_sum(array_map(fn ($translation) => count($translation['missingKeys']), array_values($translationStatus))); + $totalTranslationMismatches += array_sum(array_map(fn ($translation) => count($translation['mismatches']), array_values($translationStatus))); + + printTranslationStatus($originalFilePath, $translationStatus, $config['verbose_output'], $config['include_completed_languages']); +} + +exit($totalTranslationMismatches > 0 ? 1 : 0); + +function findTranslationFiles($originalFilePath, $localeToAnalyze): array +{ + $translations = []; + + $translationsDir = dirname($originalFilePath); + $originalFileName = basename($originalFilePath); + $translationFileNamePattern = str_replace('.en.', '.*.', $originalFileName); + + $translationFiles = glob($translationsDir.'/'.$translationFileNamePattern, \GLOB_NOSORT); + sort($translationFiles); + foreach ($translationFiles as $filePath) { + $locale = extractLocaleFromFilePath($filePath); + + if (null !== $localeToAnalyze && $locale !== $localeToAnalyze) { + continue; + } + + $translations[$locale] = $filePath; + } + + return $translations; +} + +function calculateTranslationStatus($originalFilePath, $translationFilePaths): array +{ + $translationStatus = []; + $allTranslationKeys = extractTranslationKeys($originalFilePath); + + foreach ($translationFilePaths as $locale => $translationPath) { + $translatedKeys = extractTranslationKeys($translationPath); + $missingKeys = array_diff_key($allTranslationKeys, $translatedKeys); + $mismatches = findTransUnitMismatches($allTranslationKeys, $translatedKeys); + + $translationStatus[$locale] = [ + 'total' => count($allTranslationKeys), + 'translated' => count($translatedKeys), + 'missingKeys' => $missingKeys, + 'mismatches' => $mismatches, + ]; + $translationStatus[$locale]['is_completed'] = isTranslationCompleted($translationStatus[$locale]); + } + + return $translationStatus; +} + +function isTranslationCompleted(array $translationStatus): bool +{ + return $translationStatus['total'] === $translationStatus['translated'] && 0 === count($translationStatus['mismatches']); +} + +function printTranslationStatus($originalFilePath, $translationStatus, $verboseOutput, $includeCompletedLanguages) +{ + printTitle($originalFilePath); + printTable($translationStatus, $verboseOutput, $includeCompletedLanguages); + echo \PHP_EOL.\PHP_EOL; +} + +function extractLocaleFromFilePath($filePath) +{ + $parts = explode('.', $filePath); + + return $parts[count($parts) - 2]; +} + +function extractTranslationKeys($filePath): array +{ + $translationKeys = []; + $contents = new \SimpleXMLElement(file_get_contents($filePath)); + + foreach ($contents->file->body->{'trans-unit'} as $translationKey) { + $translationId = (string) $translationKey['id']; + $translationKey = (string) $translationKey->source; + + $translationKeys[$translationId] = $translationKey; + } + + return $translationKeys; +} + +/** + * Check whether the trans-unit id and source match with the base translation. + */ +function findTransUnitMismatches(array $baseTranslationKeys, array $translatedKeys): array +{ + $mismatches = []; + + foreach ($baseTranslationKeys as $translationId => $translationKey) { + if (!isset($translatedKeys[$translationId])) { + continue; + } + if ($translatedKeys[$translationId] !== $translationKey) { + $mismatches[$translationId] = [ + 'found' => $translatedKeys[$translationId], + 'expected' => $translationKey, + ]; + } + } + + return $mismatches; +} + +function printTitle($title) +{ + echo $title.\PHP_EOL; + echo str_repeat('=', strlen($title)).\PHP_EOL.\PHP_EOL; +} + +function printTable($translations, $verboseOutput, bool $includeCompletedLanguages) +{ + if (0 === count($translations)) { + echo 'No translations found'; + + return; + } + $longestLocaleNameLength = max(array_map('strlen', array_keys($translations))); + + foreach ($translations as $locale => $translation) { + if (!$includeCompletedLanguages && $translation['is_completed']) { + continue; + } + + if ($translation['translated'] > $translation['total']) { + textColorRed(); + } elseif (count($translation['mismatches']) > 0) { + textColorRed(); + } elseif ($translation['is_completed']) { + textColorGreen(); + } + + echo sprintf( + '| Locale: %-'.$longestLocaleNameLength.'s | Translated: %2d/%2d | Mismatches: %d |', + $locale, + $translation['translated'], + $translation['total'], + count($translation['mismatches']) + ).\PHP_EOL; + + textColorNormal(); + + $shouldBeClosed = false; + if (true === $verboseOutput && count($translation['missingKeys']) > 0) { + echo '| Missing Translations:'.\PHP_EOL; + + foreach ($translation['missingKeys'] as $id => $content) { + echo sprintf('| (id=%s) %s', $id, $content).\PHP_EOL; + } + $shouldBeClosed = true; + } + if (true === $verboseOutput && count($translation['mismatches']) > 0) { + echo '| Mismatches between trans-unit id and source:'.\PHP_EOL; + + foreach ($translation['mismatches'] as $id => $content) { + echo sprintf('| (id=%s) Expected: %s', $id, $content['expected']).\PHP_EOL; + echo sprintf('| Found: %s', $content['found']).\PHP_EOL; + } + $shouldBeClosed = true; + } + if ($shouldBeClosed) { + echo str_repeat('-', 80).\PHP_EOL; + } + } +} + +function textColorGreen() +{ + echo "\033[32m"; +} + +function textColorRed() +{ + echo "\033[31m"; +} + +function textColorNormal() +{ + echo "\033[0m"; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Resources/data/parents.json b/php/libraries/composer/vendor/symfony/translation/Resources/data/parents.json new file mode 100644 index 0000000..24d4d11 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Resources/data/parents.json @@ -0,0 +1,142 @@ +{ + "az_Cyrl": "root", + "bs_Cyrl": "root", + "en_150": "en_001", + "en_AG": "en_001", + "en_AI": "en_001", + "en_AT": "en_150", + "en_AU": "en_001", + "en_BB": "en_001", + "en_BE": "en_150", + "en_BM": "en_001", + "en_BS": "en_001", + "en_BW": "en_001", + "en_BZ": "en_001", + "en_CC": "en_001", + "en_CH": "en_150", + "en_CK": "en_001", + "en_CM": "en_001", + "en_CX": "en_001", + "en_CY": "en_001", + "en_DE": "en_150", + "en_DG": "en_001", + "en_DK": "en_150", + "en_DM": "en_001", + "en_ER": "en_001", + "en_FI": "en_150", + "en_FJ": "en_001", + "en_FK": "en_001", + "en_FM": "en_001", + "en_GB": "en_001", + "en_GD": "en_001", + "en_GG": "en_001", + "en_GH": "en_001", + "en_GI": "en_001", + "en_GM": "en_001", + "en_GY": "en_001", + "en_HK": "en_001", + "en_ID": "en_001", + "en_IE": "en_001", + "en_IL": "en_001", + "en_IM": "en_001", + "en_IN": "en_001", + "en_IO": "en_001", + "en_JE": "en_001", + "en_JM": "en_001", + "en_KE": "en_001", + "en_KI": "en_001", + "en_KN": "en_001", + "en_KY": "en_001", + "en_LC": "en_001", + "en_LR": "en_001", + "en_LS": "en_001", + "en_MG": "en_001", + "en_MO": "en_001", + "en_MS": "en_001", + "en_MT": "en_001", + "en_MU": "en_001", + "en_MV": "en_001", + "en_MW": "en_001", + "en_MY": "en_001", + "en_NA": "en_001", + "en_NF": "en_001", + "en_NG": "en_001", + "en_NL": "en_150", + "en_NR": "en_001", + "en_NU": "en_001", + "en_NZ": "en_001", + "en_PG": "en_001", + "en_PK": "en_001", + "en_PN": "en_001", + "en_PW": "en_001", + "en_RW": "en_001", + "en_SB": "en_001", + "en_SC": "en_001", + "en_SD": "en_001", + "en_SE": "en_150", + "en_SG": "en_001", + "en_SH": "en_001", + "en_SI": "en_150", + "en_SL": "en_001", + "en_SS": "en_001", + "en_SX": "en_001", + "en_SZ": "en_001", + "en_TC": "en_001", + "en_TK": "en_001", + "en_TO": "en_001", + "en_TT": "en_001", + "en_TV": "en_001", + "en_TZ": "en_001", + "en_UG": "en_001", + "en_VC": "en_001", + "en_VG": "en_001", + "en_VU": "en_001", + "en_WS": "en_001", + "en_ZA": "en_001", + "en_ZM": "en_001", + "en_ZW": "en_001", + "es_AR": "es_419", + "es_BO": "es_419", + "es_BR": "es_419", + "es_BZ": "es_419", + "es_CL": "es_419", + "es_CO": "es_419", + "es_CR": "es_419", + "es_CU": "es_419", + "es_DO": "es_419", + "es_EC": "es_419", + "es_GT": "es_419", + "es_HN": "es_419", + "es_MX": "es_419", + "es_NI": "es_419", + "es_PA": "es_419", + "es_PE": "es_419", + "es_PR": "es_419", + "es_PY": "es_419", + "es_SV": "es_419", + "es_US": "es_419", + "es_UY": "es_419", + "es_VE": "es_419", + "ff_Adlm": "root", + "hi_Latn": "en_IN", + "ks_Deva": "root", + "nb": "no", + "nn": "no", + "pa_Arab": "root", + "pt_AO": "pt_PT", + "pt_CH": "pt_PT", + "pt_CV": "pt_PT", + "pt_GQ": "pt_PT", + "pt_GW": "pt_PT", + "pt_LU": "pt_PT", + "pt_MO": "pt_PT", + "pt_MZ": "pt_PT", + "pt_ST": "pt_PT", + "pt_TL": "pt_PT", + "sd_Deva": "root", + "sr_Latn": "root", + "uz_Arab": "root", + "uz_Cyrl": "root", + "zh_Hant": "root", + "zh_Hant_MO": "zh_Hant_HK" +} diff --git a/php/libraries/composer/vendor/symfony/translation/Resources/functions.php b/php/libraries/composer/vendor/symfony/translation/Resources/functions.php new file mode 100644 index 0000000..0d2a037 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Resources/functions.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +if (!\function_exists(t::class)) { + /** + * @author Nate Wiebe + */ + function t(string $message, array $parameters = [], ?string $domain = null): TranslatableMessage + { + return new TranslatableMessage($message, $parameters, $domain); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-transitional.xsd b/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-transitional.xsd new file mode 100644 index 0000000..1f38de7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-transitional.xsd @@ -0,0 +1,2261 @@ + + + + + + + + + + + + + + Values for the attribute 'context-type'. + + + + + Indicates a database content. + + + + + Indicates the content of an element within an XML document. + + + + + Indicates the name of an element within an XML document. + + + + + Indicates the line number from the sourcefile (see context-type="sourcefile") where the <source> is found. + + + + + Indicates a the number of parameters contained within the <source>. + + + + + Indicates notes pertaining to the parameters in the <source>. + + + + + Indicates the content of a record within a database. + + + + + Indicates the name of a record within a database. + + + + + Indicates the original source file in the case that multiple files are merged to form the original file from which the XLIFF file is created. This differs from the original <file> attribute in that this sourcefile is one of many that make up that file. + + + + + + + Values for the attribute 'count-type'. + + + + + Indicates the count units are items that are used X times in a certain context; example: this is a reusable text unit which is used 42 times in other texts. + + + + + Indicates the count units are translation units existing already in the same document. + + + + + Indicates a total count. + + + + + + + Values for the attribute 'ctype' when used other elements than <ph> or <x>. + + + + + Indicates a run of bolded text. + + + + + Indicates a run of text in italics. + + + + + Indicates a run of underlined text. + + + + + Indicates a run of hyper-text. + + + + + + + Values for the attribute 'ctype' when used with <ph> or <x>. + + + + + Indicates a inline image. + + + + + Indicates a page break. + + + + + Indicates a line break. + + + + + + + + + + + + Values for the attribute 'datatype'. + + + + + Indicates Active Server Page data. + + + + + Indicates C source file data. + + + + + Indicates Channel Definition Format (CDF) data. + + + + + Indicates ColdFusion data. + + + + + Indicates C++ source file data. + + + + + Indicates C-Sharp data. + + + + + Indicates strings from C, ASM, and driver files data. + + + + + Indicates comma-separated values data. + + + + + Indicates database data. + + + + + Indicates portions of document that follows data and contains metadata. + + + + + Indicates portions of document that precedes data and contains metadata. + + + + + Indicates data from standard UI file operations dialogs (e.g., Open, Save, Save As, Export, Import). + + + + + Indicates standard user input screen data. + + + + + Indicates HyperText Markup Language (HTML) data - document instance. + + + + + Indicates content within an HTML document’s <body> element. + + + + + Indicates Windows INI file data. + + + + + Indicates Interleaf data. + + + + + Indicates Java source file data (extension '.java'). + + + + + Indicates Java property resource bundle data. + + + + + Indicates Java list resource bundle data. + + + + + Indicates JavaScript source file data. + + + + + Indicates JScript source file data. + + + + + Indicates information relating to formatting. + + + + + Indicates LISP source file data. + + + + + Indicates information relating to margin formats. + + + + + Indicates a file containing menu. + + + + + Indicates numerically identified string table. + + + + + Indicates Maker Interchange Format (MIF) data. + + + + + Indicates that the datatype attribute value is a MIME Type value and is defined in the mime-type attribute. + + + + + Indicates GNU Machine Object data. + + + + + Indicates Message Librarian strings created by Novell's Message Librarian Tool. + + + + + Indicates information to be displayed at the bottom of each page of a document. + + + + + Indicates information to be displayed at the top of each page of a document. + + + + + Indicates a list of property values (e.g., settings within INI files or preferences dialog). + + + + + Indicates Pascal source file data. + + + + + Indicates Hypertext Preprocessor data. + + + + + Indicates plain text file (no formatting other than, possibly, wrapping). + + + + + Indicates GNU Portable Object file. + + + + + Indicates dynamically generated user defined document. e.g. Oracle Report, Crystal Report, etc. + + + + + Indicates Windows .NET binary resources. + + + + + Indicates Windows .NET Resources. + + + + + Indicates Rich Text Format (RTF) data. + + + + + Indicates Standard Generalized Markup Language (SGML) data - document instance. + + + + + Indicates Standard Generalized Markup Language (SGML) data - Document Type Definition (DTD). + + + + + Indicates Scalable Vector Graphic (SVG) data. + + + + + Indicates VisualBasic Script source file. + + + + + Indicates warning message. + + + + + Indicates Windows (Win32) resources (i.e. resources extracted from an RC script, a message file, or a compiled file). + + + + + Indicates Extensible HyperText Markup Language (XHTML) data - document instance. + + + + + Indicates Extensible Markup Language (XML) data - document instance. + + + + + Indicates Extensible Markup Language (XML) data - Document Type Definition (DTD). + + + + + Indicates Extensible Stylesheet Language (XSL) data. + + + + + Indicates XUL elements. + + + + + + + Values for the attribute 'mtype'. + + + + + Indicates the marked text is an abbreviation. + + + + + ISO-12620 2.1.8: A term resulting from the omission of any part of the full term while designating the same concept. + + + + + ISO-12620 2.1.8.1: An abbreviated form of a simple term resulting from the omission of some of its letters (e.g. 'adj.' for 'adjective'). + + + + + ISO-12620 2.1.8.4: An abbreviated form of a term made up of letters from the full form of a multiword term strung together into a sequence pronounced only syllabically (e.g. 'radar' for 'radio detecting and ranging'). + + + + + ISO-12620: A proper-name term, such as the name of an agency or other proper entity. + + + + + ISO-12620 2.1.18.1: A recurrent word combination characterized by cohesion in that the components of the collocation must co-occur within an utterance or series of utterances, even though they do not necessarily have to maintain immediate proximity to one another. + + + + + ISO-12620 2.1.5: A synonym for an international scientific term that is used in general discourse in a given language. + + + + + Indicates the marked text is a date and/or time. + + + + + ISO-12620 2.1.15: An expression used to represent a concept based on a statement that two mathematical expressions are, for instance, equal as identified by the equal sign (=), or assigned to one another by a similar sign. + + + + + ISO-12620 2.1.7: The complete representation of a term for which there is an abbreviated form. + + + + + ISO-12620 2.1.14: Figures, symbols or the like used to express a concept briefly, such as a mathematical or chemical formula. + + + + + ISO-12620 2.1.1: The concept designation that has been chosen to head a terminological record. + + + + + ISO-12620 2.1.8.3: An abbreviated form of a term consisting of some of the initial letters of the words making up a multiword term or the term elements making up a compound term when these letters are pronounced individually (e.g. 'BSE' for 'bovine spongiform encephalopathy'). + + + + + ISO-12620 2.1.4: A term that is part of an international scientific nomenclature as adopted by an appropriate scientific body. + + + + + ISO-12620 2.1.6: A term that has the same or nearly identical orthographic or phonemic form in many languages. + + + + + ISO-12620 2.1.16: An expression used to represent a concept based on mathematical or logical relations, such as statements of inequality, set relationships, Boolean operations, and the like. + + + + + ISO-12620 2.1.17: A unit to track object. + + + + + Indicates the marked text is a name. + + + + + ISO-12620 2.1.3: A term that represents the same or a very similar concept as another term in the same language, but for which interchangeability is limited to some contexts and inapplicable in others. + + + + + ISO-12620 2.1.17.2: A unique alphanumeric designation assigned to an object in a manufacturing system. + + + + + Indicates the marked text is a phrase. + + + + + ISO-12620 2.1.18: Any group of two or more words that form a unit, the meaning of which frequently cannot be deduced based on the combined sense of the words making up the phrase. + + + + + Indicates the marked text should not be translated. + + + + + ISO-12620 2.1.12: A form of a term resulting from an operation whereby non-Latin writing systems are converted to the Latin alphabet. + + + + + Indicates that the marked text represents a segment. + + + + + ISO-12620 2.1.18.2: A fixed, lexicalized phrase. + + + + + ISO-12620 2.1.8.2: A variant of a multiword term that includes fewer words than the full form of the term (e.g. 'Group of Twenty-four' for 'Intergovernmental Group of Twenty-four on International Monetary Affairs'). + + + + + ISO-12620 2.1.17.1: Stock keeping unit, an inventory item identified by a unique alphanumeric designation assigned to an object in an inventory control system. + + + + + ISO-12620 2.1.19: A fixed chunk of recurring text. + + + + + ISO-12620 2.1.13: A designation of a concept by letters, numerals, pictograms or any combination thereof. + + + + + ISO-12620 2.1.2: Any term that represents the same or a very similar concept as the main entry term in a term entry. + + + + + ISO-12620 2.1.18.3: Phraseological unit in a language that expresses the same semantic content as another phrase in that same language. + + + + + Indicates the marked text is a term. + + + + + ISO-12620 2.1.11: A form of a term resulting from an operation whereby the characters of one writing system are represented by characters from another writing system, taking into account the pronunciation of the characters converted. + + + + + ISO-12620 2.1.10: A form of a term resulting from an operation whereby the characters of an alphabetic writing system are represented by characters from another alphabetic writing system. + + + + + ISO-12620 2.1.8.5: An abbreviated form of a term resulting from the omission of one or more term elements or syllables (e.g. 'flu' for 'influenza'). + + + + + ISO-12620 2.1.9: One of the alternate forms of a term. + + + + + + + Values for the attribute 'restype'. + + + + + Indicates a Windows RC AUTO3STATE control. + + + + + Indicates a Windows RC AUTOCHECKBOX control. + + + + + Indicates a Windows RC AUTORADIOBUTTON control. + + + + + Indicates a Windows RC BEDIT control. + + + + + Indicates a bitmap, for example a BITMAP resource in Windows. + + + + + Indicates a button object, for example a BUTTON control Windows. + + + + + Indicates a caption, such as the caption of a dialog box. + + + + + Indicates the cell in a table, for example the content of the <td> element in HTML. + + + + + Indicates check box object, for example a CHECKBOX control in Windows. + + + + + Indicates a menu item with an associated checkbox. + + + + + Indicates a list box, but with a check-box for each item. + + + + + Indicates a color selection dialog. + + + + + Indicates a combination of edit box and listbox object, for example a COMBOBOX control in Windows. + + + + + Indicates an initialization entry of an extended combobox DLGINIT resource block. (code 0x1234). + + + + + Indicates an initialization entry of a combobox DLGINIT resource block (code 0x0403). + + + + + Indicates a UI base class element that cannot be represented by any other element. + + + + + Indicates a context menu. + + + + + Indicates a Windows RC CTEXT control. + + + + + Indicates a cursor, for example a CURSOR resource in Windows. + + + + + Indicates a date/time picker. + + + + + Indicates a Windows RC DEFPUSHBUTTON control. + + + + + Indicates a dialog box. + + + + + Indicates a Windows RC DLGINIT resource block. + + + + + Indicates an edit box object, for example an EDIT control in Windows. + + + + + Indicates a filename. + + + + + Indicates a file dialog. + + + + + Indicates a footnote. + + + + + Indicates a font name. + + + + + Indicates a footer. + + + + + Indicates a frame object. + + + + + Indicates a XUL grid element. + + + + + Indicates a groupbox object, for example a GROUPBOX control in Windows. + + + + + Indicates a header item. + + + + + Indicates a heading, such has the content of <h1>, <h2>, etc. in HTML. + + + + + Indicates a Windows RC HEDIT control. + + + + + Indicates a horizontal scrollbar. + + + + + Indicates an icon, for example an ICON resource in Windows. + + + + + Indicates a Windows RC IEDIT control. + + + + + Indicates keyword list, such as the content of the Keywords meta-data in HTML, or a K footnote in WinHelp RTF. + + + + + Indicates a label object. + + + + + Indicates a label that is also a HTML link (not necessarily a URL). + + + + + Indicates a list (a group of list-items, for example an <ol> or <ul> element in HTML). + + + + + Indicates a listbox object, for example an LISTBOX control in Windows. + + + + + Indicates an list item (an entry in a list). + + + + + Indicates a Windows RC LTEXT control. + + + + + Indicates a menu (a group of menu-items). + + + + + Indicates a toolbar containing one or more tope level menus. + + + + + Indicates a menu item (an entry in a menu). + + + + + Indicates a XUL menuseparator element. + + + + + Indicates a message, for example an entry in a MESSAGETABLE resource in Windows. + + + + + Indicates a calendar control. + + + + + Indicates an edit box beside a spin control. + + + + + Indicates a catch all for rectangular areas. + + + + + Indicates a standalone menu not necessarily associated with a menubar. + + + + + Indicates a pushbox object, for example a PUSHBOX control in Windows. + + + + + Indicates a Windows RC PUSHBUTTON control. + + + + + Indicates a radio button object. + + + + + Indicates a menuitem with associated radio button. + + + + + Indicates raw data resources for an application. + + + + + Indicates a row in a table. + + + + + Indicates a Windows RC RTEXT control. + + + + + Indicates a user navigable container used to show a portion of a document. + + + + + Indicates a generic divider object (e.g. menu group separator). + + + + + Windows accelerators, shortcuts in resource or property files. + + + + + Indicates a UI control to indicate process activity but not progress. + + + + + Indicates a splitter bar. + + + + + Indicates a Windows RC STATE3 control. + + + + + Indicates a window for providing feedback to the users, like 'read-only', etc. + + + + + Indicates a string, for example an entry in a STRINGTABLE resource in Windows. + + + + + Indicates a layers of controls with a tab to select layers. + + + + + Indicates a display and edits regular two-dimensional tables of cells. + + + + + Indicates a XUL textbox element. + + + + + Indicates a UI button that can be toggled to on or off state. + + + + + Indicates an array of controls, usually buttons. + + + + + Indicates a pop up tool tip text. + + + + + Indicates a bar with a pointer indicating a position within a certain range. + + + + + Indicates a control that displays a set of hierarchical data. + + + + + Indicates a URI (URN or URL). + + + + + Indicates a Windows RC USERBUTTON control. + + + + + Indicates a user-defined control like CONTROL control in Windows. + + + + + Indicates the text of a variable. + + + + + Indicates version information about a resource like VERSIONINFO in Windows. + + + + + Indicates a vertical scrollbar. + + + + + Indicates a graphical window. + + + + + + + Values for the attribute 'size-unit'. + + + + + Indicates a size in 8-bit bytes. + + + + + Indicates a size in Unicode characters. + + + + + Indicates a size in columns. Used for HTML text area. + + + + + Indicates a size in centimeters. + + + + + Indicates a size in dialog units, as defined in Windows resources. + + + + + Indicates a size in 'font-size' units (as defined in CSS). + + + + + Indicates a size in 'x-height' units (as defined in CSS). + + + + + Indicates a size in glyphs. A glyph is considered to be one or more combined Unicode characters that represent a single displayable text character. Sometimes referred to as a 'grapheme cluster' + + + + + Indicates a size in inches. + + + + + Indicates a size in millimeters. + + + + + Indicates a size in percentage. + + + + + Indicates a size in pixels. + + + + + Indicates a size in point. + + + + + Indicates a size in rows. Used for HTML text area. + + + + + + + Values for the attribute 'state'. + + + + + Indicates the terminating state. + + + + + Indicates only non-textual information needs adaptation. + + + + + Indicates both text and non-textual information needs adaptation. + + + + + Indicates only non-textual information needs review. + + + + + Indicates both text and non-textual information needs review. + + + + + Indicates that only the text of the item needs to be reviewed. + + + + + Indicates that the item needs to be translated. + + + + + Indicates that the item is new. For example, translation units that were not in a previous version of the document. + + + + + Indicates that changes are reviewed and approved. + + + + + Indicates that the item has been translated. + + + + + + + Values for the attribute 'state-qualifier'. + + + + + Indicates an exact match. An exact match occurs when a source text of a segment is exactly the same as the source text of a segment that was translated previously. + + + + + Indicates a fuzzy match. A fuzzy match occurs when a source text of a segment is very similar to the source text of a segment that was translated previously (e.g. when the difference is casing, a few changed words, white-space discripancy, etc.). + + + + + Indicates a match based on matching IDs (in addition to matching text). + + + + + Indicates a translation derived from a glossary. + + + + + Indicates a translation derived from existing translation. + + + + + Indicates a translation derived from machine translation. + + + + + Indicates a translation derived from a translation repository. + + + + + Indicates a translation derived from a translation memory. + + + + + Indicates the translation is suggested by machine translation. + + + + + Indicates that the item has been rejected because of incorrect grammar. + + + + + Indicates that the item has been rejected because it is incorrect. + + + + + Indicates that the item has been rejected because it is too long or too short. + + + + + Indicates that the item has been rejected because of incorrect spelling. + + + + + Indicates the translation is suggested by translation memory. + + + + + + + Values for the attribute 'unit'. + + + + + Refers to words. + + + + + Refers to pages. + + + + + Refers to <trans-unit> elements. + + + + + Refers to <bin-unit> elements. + + + + + Refers to glyphs. + + + + + Refers to <trans-unit> and/or <bin-unit> elements. + + + + + Refers to the occurrences of instances defined by the count-type value. + + + + + Refers to characters. + + + + + Refers to lines. + + + + + Refers to sentences. + + + + + Refers to paragraphs. + + + + + Refers to segments. + + + + + Refers to placeables (inline elements). + + + + + + + Values for the attribute 'priority'. + + + + + Highest priority. + + + + + High priority. + + + + + High priority, but not as important as 2. + + + + + High priority, but not as important as 3. + + + + + Medium priority, but more important than 6. + + + + + Medium priority, but less important than 5. + + + + + Low priority, but more important than 8. + + + + + Low priority, but more important than 9. + + + + + Low priority. + + + + + Lowest priority. + + + + + + + + + This value indicates that all properties can be reformatted. This value must be used alone. + + + + + This value indicates that no properties should be reformatted. This value must be used alone. + + + + + + + + + + + + + This value indicates that all information in the coord attribute can be modified. + + + + + This value indicates that the x information in the coord attribute can be modified. + + + + + This value indicates that the y information in the coord attribute can be modified. + + + + + This value indicates that the cx information in the coord attribute can be modified. + + + + + This value indicates that the cy information in the coord attribute can be modified. + + + + + This value indicates that all the information in the font attribute can be modified. + + + + + This value indicates that the name information in the font attribute can be modified. + + + + + This value indicates that the size information in the font attribute can be modified. + + + + + This value indicates that the weight information in the font attribute can be modified. + + + + + This value indicates that the information in the css-style attribute can be modified. + + + + + This value indicates that the information in the style attribute can be modified. + + + + + This value indicates that the information in the exstyle attribute can be modified. + + + + + + + + + + + + + Indicates that the context is informational in nature, specifying for example, how a term should be translated. Thus, should be displayed to anyone editing the XLIFF document. + + + + + Indicates that the context-group is used to specify where the term was found in the translatable source. Thus, it is not displayed. + + + + + Indicates that the context information should be used during translation memory lookups. Thus, it is not displayed. + + + + + + + + + Represents a translation proposal from a translation memory or other resource. + + + + + Represents a previous version of the target element. + + + + + Represents a rejected version of the target element. + + + + + Represents a translation to be used for reference purposes only, for example from a related product or a different language. + + + + + Represents a proposed translation that was used for the translation of the trans-unit, possibly modified. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Values for the attribute 'coord'. + + + + + + + + Version values: 1.0 and 1.1 are allowed for backward compatibility. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xliff-core-2.0.xsd b/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xliff-core-2.0.xsd new file mode 100644 index 0000000..963232f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xliff-core-2.0.xsd @@ -0,0 +1,411 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xml.xsd b/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xml.xsd new file mode 100644 index 0000000..a46162a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Resources/schemas/xml.xsd @@ -0,0 +1,309 @@ + + + + + + +
+

About the XML namespace

+ +
+

+ + This schema document describes the XML namespace, in a form + suitable for import by other schema documents. +

+

+ See + http://www.w3.org/XML/1998/namespace.html and + + http://www.w3.org/TR/REC-xml for information + about this namespace. +

+ +

+ Note that local names in this namespace are intended to be + defined only by the World Wide Web Consortium or its subgroups. + The names currently defined in this namespace are listed below. + They should not be used with conflicting semantics by any Working + Group, specification, or document instance. +

+

+ See further below in this document for more information about how to refer to this schema document from your own + XSD schema documents and about the + namespace-versioning policy governing this schema document. +

+
+
+ +
+
+ + + + +
+ +

lang (as an attribute name)

+

+ + denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification.

+ +
+
+

Notes

+

+ Attempting to install the relevant ISO 2- and 3-letter + codes as the enumerated possible values is probably never + going to be a realistic possibility. +

+

+ + See BCP 47 at + http://www.rfc-editor.org/rfc/bcp/bcp47.txt + and the IANA language subtag registry at + + http://www.iana.org/assignments/language-subtag-registry + for further information. +

+

+ + The union allows for the 'un-declaration' of xml:lang with + the empty string. +

+
+
+
+ + + + + + + + + + +
+ + + + + +
+ +

space (as an attribute name)

+

+ denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification.

+ +
+
+
+ + + + + + + +
+ + + + +
+ +

base (as an attribute name)

+

+ denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification.

+ +

+ See http://www.w3.org/TR/xmlbase/ + for information about this attribute. +

+ +
+
+
+
+ + + + +
+ +

id (as an attribute name)

+

+ + denotes an attribute whose value + should be interpreted as if declared to be of type ID. + This name is reserved by virtue of its definition in the + xml:id specification.

+ +

+ See http://www.w3.org/TR/xml-id/ + for information about this attribute. +

+
+
+
+ +
+ + + + + + + + + + + +
+ +

Father (in any context at all)

+ +
+

+ denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: +

+
+

+ + In appreciation for his vision, leadership and + dedication the W3C XML Plenary on this 10th day of + February, 2000, reserves for Jon Bosak in perpetuity + the XML name "xml:Father". +

+
+
+
+
+
+ + + + +
+

About this schema document

+ +
+

+ This schema defines attributes and an attribute group suitable + for use by schemas wishing to allow xml:base, + xml:lang, xml:space or + xml:id attributes on elements they define. +

+ +

+ To enable this, such a schema must import this schema for + the XML namespace, e.g. as follows: +

+
+          <schema.. .>
+          .. .
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2001/xml.xsd"/>
+     
+

+ or +

+
+
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
+     
+

+ Subsequently, qualified reference to any of the attributes or the + group defined below will have the desired effect, e.g. +

+
+          <type.. .>
+          .. .
+           <attributeGroup ref="xml:specialAttrs"/>
+     
+

+ will define a type which will schema-validate an instance element + with any of those attributes. +

+ +
+
+
+
+ + + +
+

Versioning policy for this schema document

+ +
+

+ In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + + http://www.w3.org/2009/01/xml.xsd. +

+

+ At the date of issue it can also be found at + + http://www.w3.org/2001/xml.xsd. +

+ +

+ The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML + Schema itself, or with the XML namespace itself. In other words, + if the XML Schema or XML namespaces change, the version of this + document at + http://www.w3.org/2001/xml.xsd + + will change accordingly; the version at + + http://www.w3.org/2009/01/xml.xsd + + will not change. +

+

+ + Previous dated (and unchanging) versions of this schema + document are at: +

+ +
+
+
+
+ +
diff --git a/php/libraries/composer/vendor/symfony/translation/Test/ProviderFactoryTestCase.php b/php/libraries/composer/vendor/symfony/translation/Test/ProviderFactoryTestCase.php new file mode 100644 index 0000000..95ffcb1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Test/ProviderFactoryTestCase.php @@ -0,0 +1,153 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Test; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\Translation\Dumper\XliffFileDumper; +use Symfony\Component\Translation\Exception\IncompleteDsnException; +use Symfony\Component\Translation\Exception\UnsupportedSchemeException; +use Symfony\Component\Translation\Loader\LoaderInterface; +use Symfony\Component\Translation\Provider\Dsn; +use Symfony\Component\Translation\Provider\ProviderFactoryInterface; +use Symfony\Component\Translation\TranslatorBagInterface; +use Symfony\Contracts\HttpClient\HttpClientInterface; + +/** + * A test case to ease testing a translation provider factory. + * + * @author Mathieu Santostefano + */ +abstract class ProviderFactoryTestCase extends TestCase +{ + protected HttpClientInterface $client; + protected LoggerInterface|MockObject $logger; + protected string $defaultLocale; + protected LoaderInterface|MockObject $loader; + protected XliffFileDumper|MockObject $xliffFileDumper; + protected TranslatorBagInterface|MockObject $translatorBag; + + abstract public function createFactory(): ProviderFactoryInterface; + + /** + * @return iterable + */ + abstract public static function supportsProvider(): iterable; + + /** + * @return iterable + */ + abstract public static function createProvider(): iterable; + + /** + * @return iterable + */ + public static function unsupportedSchemeProvider(): iterable + { + return []; + } + + /** + * @return iterable + */ + public static function incompleteDsnProvider(): iterable + { + return []; + } + + /** + * @dataProvider supportsProvider + */ + public function testSupports(bool $expected, string $dsn) + { + $factory = $this->createFactory(); + + $this->assertSame($expected, $factory->supports(new Dsn($dsn))); + } + + /** + * @dataProvider createProvider + */ + public function testCreate(string $expected, string $dsn) + { + $factory = $this->createFactory(); + $provider = $factory->create(new Dsn($dsn)); + + $this->assertSame($expected, (string) $provider); + } + + /** + * @dataProvider unsupportedSchemeProvider + */ + public function testUnsupportedSchemeException(string $dsn, ?string $message = null) + { + $factory = $this->createFactory(); + + $dsn = new Dsn($dsn); + + $this->expectException(UnsupportedSchemeException::class); + if (null !== $message) { + $this->expectExceptionMessage($message); + } + + $factory->create($dsn); + } + + /** + * @dataProvider incompleteDsnProvider + */ + public function testIncompleteDsnException(string $dsn, ?string $message = null) + { + $factory = $this->createFactory(); + + $dsn = new Dsn($dsn); + + $this->expectException(IncompleteDsnException::class); + if (null !== $message) { + $this->expectExceptionMessage($message); + } + + $factory->create($dsn); + } + + protected function getClient(): HttpClientInterface + { + return $this->client ??= new MockHttpClient(); + } + + protected function getLogger(): LoggerInterface + { + return $this->logger ??= $this->createMock(LoggerInterface::class); + } + + protected function getDefaultLocale(): string + { + return $this->defaultLocale ??= 'en'; + } + + protected function getLoader(): LoaderInterface + { + return $this->loader ??= $this->createMock(LoaderInterface::class); + } + + protected function getXliffFileDumper(): XliffFileDumper + { + return $this->xliffFileDumper ??= $this->createMock(XliffFileDumper::class); + } + + protected function getTranslatorBag(): TranslatorBagInterface + { + return $this->translatorBag ??= $this->createMock(TranslatorBagInterface::class); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Test/ProviderTestCase.php b/php/libraries/composer/vendor/symfony/translation/Test/ProviderTestCase.php new file mode 100644 index 0000000..a8fa0b8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Test/ProviderTestCase.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Test; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\Translation\Dumper\XliffFileDumper; +use Symfony\Component\Translation\Loader\LoaderInterface; +use Symfony\Component\Translation\Provider\ProviderInterface; +use Symfony\Component\Translation\TranslatorBagInterface; +use Symfony\Contracts\HttpClient\HttpClientInterface; + +/** + * A test case to ease testing a translation provider. + * + * @author Mathieu Santostefano + */ +abstract class ProviderTestCase extends TestCase +{ + protected HttpClientInterface $client; + protected LoggerInterface|MockObject $logger; + protected string $defaultLocale; + protected LoaderInterface|MockObject $loader; + protected XliffFileDumper|MockObject $xliffFileDumper; + protected TranslatorBagInterface|MockObject $translatorBag; + + abstract public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint): ProviderInterface; + + /** + * @return iterable + */ + abstract public static function toStringProvider(): iterable; + + /** + * @dataProvider toStringProvider + */ + public function testToString(ProviderInterface $provider, string $expected) + { + $this->assertSame($expected, (string) $provider); + } + + protected function getClient(): MockHttpClient + { + return $this->client ??= new MockHttpClient(); + } + + protected function getLoader(): LoaderInterface + { + return $this->loader ??= $this->createMock(LoaderInterface::class); + } + + protected function getLogger(): LoggerInterface + { + return $this->logger ??= $this->createMock(LoggerInterface::class); + } + + protected function getDefaultLocale(): string + { + return $this->defaultLocale ??= 'en'; + } + + protected function getXliffFileDumper(): XliffFileDumper + { + return $this->xliffFileDumper ??= $this->createMock(XliffFileDumper::class); + } + + protected function getTranslatorBag(): TranslatorBagInterface + { + return $this->translatorBag ??= $this->createMock(TranslatorBagInterface::class); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/TranslatableMessage.php b/php/libraries/composer/vendor/symfony/translation/TranslatableMessage.php new file mode 100644 index 0000000..c591e68 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/TranslatableMessage.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\Translation; + +use Symfony\Contracts\Translation\TranslatableInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +/** + * @author Nate Wiebe + */ +class TranslatableMessage implements TranslatableInterface +{ + private string $message; + private array $parameters; + private ?string $domain; + + public function __construct(string $message, array $parameters = [], ?string $domain = null) + { + $this->message = $message; + $this->parameters = $parameters; + $this->domain = $domain; + } + + public function __toString(): string + { + return $this->getMessage(); + } + + public function getMessage(): string + { + return $this->message; + } + + public function getParameters(): array + { + return $this->parameters; + } + + public function getDomain(): ?string + { + return $this->domain; + } + + public function trans(TranslatorInterface $translator, ?string $locale = null): string + { + return $translator->trans($this->getMessage(), array_map( + static fn ($parameter) => $parameter instanceof TranslatableInterface ? $parameter->trans($translator, $locale) : $parameter, + $this->getParameters() + ), $this->getDomain(), $locale); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Translator.php b/php/libraries/composer/vendor/symfony/translation/Translator.php new file mode 100644 index 0000000..1973d07 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Translator.php @@ -0,0 +1,472 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\Config\ConfigCacheFactory; +use Symfony\Component\Config\ConfigCacheFactoryInterface; +use Symfony\Component\Config\ConfigCacheInterface; +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Symfony\Component\Translation\Exception\RuntimeException; +use Symfony\Component\Translation\Formatter\IntlFormatterInterface; +use Symfony\Component\Translation\Formatter\MessageFormatter; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; +use Symfony\Component\Translation\Loader\LoaderInterface; +use Symfony\Contracts\Translation\LocaleAwareInterface; +use Symfony\Contracts\Translation\TranslatableInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(MessageCatalogue::class); + +/** + * @author Fabien Potencier + */ +class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleAwareInterface +{ + /** + * @var MessageCatalogueInterface[] + */ + protected $catalogues = []; + + private string $locale; + + /** + * @var string[] + */ + private array $fallbackLocales = []; + + /** + * @var LoaderInterface[] + */ + private array $loaders = []; + + private array $resources = []; + + private MessageFormatterInterface $formatter; + + private ?string $cacheDir; + + private bool $debug; + + private array $cacheVary; + + private ?ConfigCacheFactoryInterface $configCacheFactory; + + private array $parentLocales; + + private bool $hasIntlFormatter; + + /** + * @throws InvalidArgumentException If a locale contains invalid characters + */ + public function __construct(string $locale, ?MessageFormatterInterface $formatter = null, ?string $cacheDir = null, bool $debug = false, array $cacheVary = []) + { + $this->setLocale($locale); + + $this->formatter = $formatter ??= new MessageFormatter(); + $this->cacheDir = $cacheDir; + $this->debug = $debug; + $this->cacheVary = $cacheVary; + $this->hasIntlFormatter = $formatter instanceof IntlFormatterInterface; + } + + /** + * @return void + */ + public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory) + { + $this->configCacheFactory = $configCacheFactory; + } + + /** + * Adds a Loader. + * + * @param string $format The name of the loader (@see addResource()) + * + * @return void + */ + public function addLoader(string $format, LoaderInterface $loader) + { + $this->loaders[$format] = $loader; + } + + /** + * Adds a Resource. + * + * @param string $format The name of the loader (@see addLoader()) + * @param mixed $resource The resource name + * + * @return void + * + * @throws InvalidArgumentException If the locale contains invalid characters + */ + public function addResource(string $format, mixed $resource, string $locale, ?string $domain = null) + { + $domain ??= 'messages'; + + $this->assertValidLocale($locale); + $locale ?: $locale = class_exists(\Locale::class) ? \Locale::getDefault() : 'en'; + + $this->resources[$locale][] = [$format, $resource, $domain]; + + if (\in_array($locale, $this->fallbackLocales)) { + $this->catalogues = []; + } else { + unset($this->catalogues[$locale]); + } + } + + /** + * @return void + */ + public function setLocale(string $locale) + { + $this->assertValidLocale($locale); + $this->locale = $locale; + } + + public function getLocale(): string + { + return $this->locale ?: (class_exists(\Locale::class) ? \Locale::getDefault() : 'en'); + } + + /** + * Sets the fallback locales. + * + * @param string[] $locales + * + * @return void + * + * @throws InvalidArgumentException If a locale contains invalid characters + */ + public function setFallbackLocales(array $locales) + { + // needed as the fallback locales are linked to the already loaded catalogues + $this->catalogues = []; + + foreach ($locales as $locale) { + $this->assertValidLocale($locale); + } + + $this->fallbackLocales = $this->cacheVary['fallback_locales'] = $locales; + } + + /** + * Gets the fallback locales. + * + * @internal + */ + public function getFallbackLocales(): array + { + return $this->fallbackLocales; + } + + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + if (null === $id || '' === $id) { + return ''; + } + + $domain ??= 'messages'; + + $catalogue = $this->getCatalogue($locale); + $locale = $catalogue->getLocale(); + while (!$catalogue->defines($id, $domain)) { + if ($cat = $catalogue->getFallbackCatalogue()) { + $catalogue = $cat; + $locale = $catalogue->getLocale(); + } else { + break; + } + } + + $parameters = array_map(fn ($parameter) => $parameter instanceof TranslatableInterface ? $parameter->trans($this, $locale) : $parameter, $parameters); + + $len = \strlen(MessageCatalogue::INTL_DOMAIN_SUFFIX); + if ($this->hasIntlFormatter + && ($catalogue->defines($id, $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX) + || (\strlen($domain) > $len && 0 === substr_compare($domain, MessageCatalogue::INTL_DOMAIN_SUFFIX, -$len, $len))) + ) { + return $this->formatter->formatIntl($catalogue->get($id, $domain), $locale, $parameters); + } + + return $this->formatter->format($catalogue->get($id, $domain), $locale, $parameters); + } + + public function getCatalogue(?string $locale = null): MessageCatalogueInterface + { + if (!$locale) { + $locale = $this->getLocale(); + } else { + $this->assertValidLocale($locale); + } + + if (!isset($this->catalogues[$locale])) { + $this->loadCatalogue($locale); + } + + return $this->catalogues[$locale]; + } + + public function getCatalogues(): array + { + return array_values($this->catalogues); + } + + /** + * Gets the loaders. + * + * @return LoaderInterface[] + */ + protected function getLoaders(): array + { + return $this->loaders; + } + + /** + * @return void + */ + protected function loadCatalogue(string $locale) + { + if (null === $this->cacheDir) { + $this->initializeCatalogue($locale); + } else { + $this->initializeCacheCatalogue($locale); + } + } + + /** + * @return void + */ + protected function initializeCatalogue(string $locale) + { + $this->assertValidLocale($locale); + + try { + $this->doLoadCatalogue($locale); + } catch (NotFoundResourceException $e) { + if (!$this->computeFallbackLocales($locale)) { + throw $e; + } + } + $this->loadFallbackCatalogues($locale); + } + + private function initializeCacheCatalogue(string $locale): void + { + if (isset($this->catalogues[$locale])) { + /* Catalogue already initialized. */ + return; + } + + $this->assertValidLocale($locale); + $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale), + function (ConfigCacheInterface $cache) use ($locale) { + $this->dumpCatalogue($locale, $cache); + } + ); + + if (isset($this->catalogues[$locale])) { + /* Catalogue has been initialized as it was written out to cache. */ + return; + } + + /* Read catalogue from cache. */ + $this->catalogues[$locale] = include $cache->getPath(); + } + + private function dumpCatalogue(string $locale, ConfigCacheInterface $cache): void + { + $this->initializeCatalogue($locale); + $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]); + + $content = sprintf(<<getAllMessages($this->catalogues[$locale]), true), + $fallbackContent + ); + + $cache->write($content, $this->catalogues[$locale]->getResources()); + } + + private function getFallbackContent(MessageCatalogue $catalogue): string + { + $fallbackContent = ''; + $current = ''; + $replacementPattern = '/[^a-z0-9_]/i'; + $fallbackCatalogue = $catalogue->getFallbackCatalogue(); + while ($fallbackCatalogue) { + $fallback = $fallbackCatalogue->getLocale(); + $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback)); + $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current)); + + $fallbackContent .= sprintf(<<<'EOF' +$catalogue%s = new MessageCatalogue('%s', %s); +$catalogue%s->addFallbackCatalogue($catalogue%s); + +EOF + , + $fallbackSuffix, + $fallback, + var_export($this->getAllMessages($fallbackCatalogue), true), + $currentSuffix, + $fallbackSuffix + ); + $current = $fallbackCatalogue->getLocale(); + $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue(); + } + + return $fallbackContent; + } + + private function getCatalogueCachePath(string $locale): string + { + return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->cacheVary), true)), 0, 7), '/', '_').'.php'; + } + + /** + * @internal + */ + protected function doLoadCatalogue(string $locale): void + { + $this->catalogues[$locale] = new MessageCatalogue($locale); + + if (isset($this->resources[$locale])) { + foreach ($this->resources[$locale] as $resource) { + if (!isset($this->loaders[$resource[0]])) { + if (\is_string($resource[1])) { + throw new RuntimeException(sprintf('No loader is registered for the "%s" format when loading the "%s" resource.', $resource[0], $resource[1])); + } + + throw new RuntimeException(sprintf('No loader is registered for the "%s" format.', $resource[0])); + } + $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2])); + } + } + } + + private function loadFallbackCatalogues(string $locale): void + { + $current = $this->catalogues[$locale]; + + foreach ($this->computeFallbackLocales($locale) as $fallback) { + if (!isset($this->catalogues[$fallback])) { + $this->initializeCatalogue($fallback); + } + + $fallbackCatalogue = new MessageCatalogue($fallback, $this->getAllMessages($this->catalogues[$fallback])); + foreach ($this->catalogues[$fallback]->getResources() as $resource) { + $fallbackCatalogue->addResource($resource); + } + $current->addFallbackCatalogue($fallbackCatalogue); + $current = $fallbackCatalogue; + } + } + + /** + * @return array + */ + protected function computeFallbackLocales(string $locale) + { + $this->parentLocales ??= json_decode(file_get_contents(__DIR__.'/Resources/data/parents.json'), true); + + $originLocale = $locale; + $locales = []; + + while ($locale) { + $parent = $this->parentLocales[$locale] ?? null; + + if ($parent) { + $locale = 'root' !== $parent ? $parent : null; + } elseif (\function_exists('locale_parse')) { + $localeSubTags = locale_parse($locale); + $locale = null; + if (1 < \count($localeSubTags)) { + array_pop($localeSubTags); + $locale = locale_compose($localeSubTags) ?: null; + } + } elseif ($i = strrpos($locale, '_') ?: strrpos($locale, '-')) { + $locale = substr($locale, 0, $i); + } else { + $locale = null; + } + + if (null !== $locale) { + $locales[] = $locale; + } + } + + foreach ($this->fallbackLocales as $fallback) { + if ($fallback === $originLocale) { + continue; + } + + $locales[] = $fallback; + } + + return array_unique($locales); + } + + /** + * Asserts that the locale is valid, throws an Exception if not. + * + * @return void + * + * @throws InvalidArgumentException If the locale contains invalid characters + */ + protected function assertValidLocale(string $locale) + { + if (!preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) { + throw new InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale)); + } + } + + /** + * Provides the ConfigCache factory implementation, falling back to a + * default implementation if necessary. + */ + private function getConfigCacheFactory(): ConfigCacheFactoryInterface + { + $this->configCacheFactory ??= new ConfigCacheFactory($this->debug); + + return $this->configCacheFactory; + } + + private function getAllMessages(MessageCatalogueInterface $catalogue): array + { + $allMessages = []; + + foreach ($catalogue->all() as $domain => $messages) { + if ($intlMessages = $catalogue->all($domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) { + $allMessages[$domain.MessageCatalogue::INTL_DOMAIN_SUFFIX] = $intlMessages; + $messages = array_diff_key($messages, $intlMessages); + } + if ($messages) { + $allMessages[$domain] = $messages; + } + } + + return $allMessages; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/TranslatorBag.php b/php/libraries/composer/vendor/symfony/translation/TranslatorBag.php new file mode 100644 index 0000000..3b47aec --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/TranslatorBag.php @@ -0,0 +1,102 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\Translation\Catalogue\AbstractOperation; +use Symfony\Component\Translation\Catalogue\TargetOperation; + +final class TranslatorBag implements TranslatorBagInterface +{ + /** @var MessageCatalogue[] */ + private array $catalogues = []; + + public function addCatalogue(MessageCatalogue $catalogue): void + { + if (null !== $existingCatalogue = $this->getCatalogue($catalogue->getLocale())) { + $catalogue->addCatalogue($existingCatalogue); + } + + $this->catalogues[$catalogue->getLocale()] = $catalogue; + } + + public function addBag(TranslatorBagInterface $bag): void + { + foreach ($bag->getCatalogues() as $catalogue) { + $this->addCatalogue($catalogue); + } + } + + public function getCatalogue(?string $locale = null): MessageCatalogueInterface + { + if (null === $locale || !isset($this->catalogues[$locale])) { + $this->catalogues[$locale] = new MessageCatalogue($locale); + } + + return $this->catalogues[$locale]; + } + + public function getCatalogues(): array + { + return array_values($this->catalogues); + } + + public function diff(TranslatorBagInterface $diffBag): self + { + $diff = new self(); + + foreach ($this->catalogues as $locale => $catalogue) { + if (null === $diffCatalogue = $diffBag->getCatalogue($locale)) { + $diff->addCatalogue($catalogue); + + continue; + } + + $operation = new TargetOperation($diffCatalogue, $catalogue); + $operation->moveMessagesToIntlDomainsIfPossible(AbstractOperation::NEW_BATCH); + $newCatalogue = new MessageCatalogue($locale); + + foreach ($catalogue->getDomains() as $domain) { + $newCatalogue->add($operation->getNewMessages($domain), $domain); + } + + $diff->addCatalogue($newCatalogue); + } + + return $diff; + } + + public function intersect(TranslatorBagInterface $intersectBag): self + { + $diff = new self(); + + foreach ($this->catalogues as $locale => $catalogue) { + if (null === $intersectCatalogue = $intersectBag->getCatalogue($locale)) { + continue; + } + + $operation = new TargetOperation($catalogue, $intersectCatalogue); + $operation->moveMessagesToIntlDomainsIfPossible(AbstractOperation::OBSOLETE_BATCH); + $obsoleteCatalogue = new MessageCatalogue($locale); + + foreach ($operation->getDomains() as $domain) { + $obsoleteCatalogue->add( + array_diff($operation->getMessages($domain), $operation->getNewMessages($domain)), + $domain + ); + } + + $diff->addCatalogue($obsoleteCatalogue); + } + + return $diff; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/TranslatorBagInterface.php b/php/libraries/composer/vendor/symfony/translation/TranslatorBagInterface.php new file mode 100644 index 0000000..365d1f1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/TranslatorBagInterface.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\Translation; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; + +/** + * @author Abdellatif Ait boudad + */ +interface TranslatorBagInterface +{ + /** + * Gets the catalogue by locale. + * + * @param string|null $locale The locale or null to use the default + * + * @throws InvalidArgumentException If the locale contains invalid characters + */ + public function getCatalogue(?string $locale = null): MessageCatalogueInterface; + + /** + * Returns all catalogues of the instance. + * + * @return MessageCatalogueInterface[] + */ + public function getCatalogues(): array; +} diff --git a/php/libraries/composer/vendor/symfony/translation/Util/ArrayConverter.php b/php/libraries/composer/vendor/symfony/translation/Util/ArrayConverter.php new file mode 100644 index 0000000..64e15b4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Util/ArrayConverter.php @@ -0,0 +1,142 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Util; + +/** + * ArrayConverter generates tree like structure from a message catalogue. + * e.g. this + * 'foo.bar1' => 'test1', + * 'foo.bar2' => 'test2' + * converts to follows: + * foo: + * bar1: test1 + * bar2: test2. + * + * @author Gennady Telegin + */ +class ArrayConverter +{ + /** + * Converts linear messages array to tree-like array. + * For example this array('foo.bar' => 'value') will be converted to ['foo' => ['bar' => 'value']]. + * + * @param array $messages Linear messages array + */ + public static function expandToTree(array $messages): array + { + $tree = []; + + foreach ($messages as $id => $value) { + $referenceToElement = &self::getElementByPath($tree, self::getKeyParts($id)); + + $referenceToElement = $value; + + unset($referenceToElement); + } + + return $tree; + } + + private static function &getElementByPath(array &$tree, array $parts): mixed + { + $elem = &$tree; + $parentOfElem = null; + + foreach ($parts as $i => $part) { + if (isset($elem[$part]) && \is_string($elem[$part])) { + /* Process next case: + * 'foo': 'test1', + * 'foo.bar': 'test2' + * + * $tree['foo'] was string before we found array {bar: test2}. + * Treat new element as string too, e.g. add $tree['foo.bar'] = 'test2'; + */ + $elem = &$elem[implode('.', \array_slice($parts, $i))]; + break; + } + + $parentOfElem = &$elem; + $elem = &$elem[$part]; + } + + if ($elem && \is_array($elem) && $parentOfElem) { + /* Process next case: + * 'foo.bar': 'test1' + * 'foo': 'test2' + * + * $tree['foo'] was array = {bar: 'test1'} before we found string constant `foo`. + * Cancel treating $tree['foo'] as array and cancel back it expansion, + * e.g. make it $tree['foo.bar'] = 'test1' again. + */ + self::cancelExpand($parentOfElem, $part, $elem); + } + + return $elem; + } + + private static function cancelExpand(array &$tree, string $prefix, array $node): void + { + $prefix .= '.'; + + foreach ($node as $id => $value) { + if (\is_string($value)) { + $tree[$prefix.$id] = $value; + } else { + self::cancelExpand($tree, $prefix.$id, $value); + } + } + } + + /** + * @return string[] + */ + private static function getKeyParts(string $key): array + { + $parts = explode('.', $key); + $partsCount = \count($parts); + + $result = []; + $buffer = ''; + + foreach ($parts as $index => $part) { + if (0 === $index && '' === $part) { + $buffer = '.'; + + continue; + } + + if ($index === $partsCount - 1 && '' === $part) { + $buffer .= '.'; + $result[] = $buffer; + + continue; + } + + if (isset($parts[$index + 1]) && '' === $parts[$index + 1]) { + $buffer .= $part; + + continue; + } + + if ($buffer) { + $result[] = $buffer.$part; + $buffer = ''; + + continue; + } + + $result[] = $part; + } + + return $result; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Util/XliffUtils.php b/php/libraries/composer/vendor/symfony/translation/Util/XliffUtils.php new file mode 100644 index 0000000..335c34b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Util/XliffUtils.php @@ -0,0 +1,191 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Util; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\InvalidResourceException; + +/** + * Provides some utility methods for XLIFF translation files, such as validating + * their contents according to the XSD schema. + * + * @author Fabien Potencier + */ +class XliffUtils +{ + /** + * Gets xliff file version based on the root "version" attribute. + * + * Defaults to 1.2 for backwards compatibility. + * + * @throws InvalidArgumentException + */ + public static function getVersionNumber(\DOMDocument $dom): string + { + /** @var \DOMNode $xliff */ + foreach ($dom->getElementsByTagName('xliff') as $xliff) { + $version = $xliff->attributes->getNamedItem('version'); + if ($version) { + return $version->nodeValue; + } + + $namespace = $xliff->attributes->getNamedItem('xmlns'); + if ($namespace) { + if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) { + throw new InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s".', $namespace)); + } + + return substr($namespace, 34); + } + } + + // Falls back to v1.2 + return '1.2'; + } + + /** + * Validates and parses the given file into a DOMDocument. + * + * @throws InvalidResourceException + */ + public static function validateSchema(\DOMDocument $dom): array + { + $xliffVersion = static::getVersionNumber($dom); + $internalErrors = libxml_use_internal_errors(true); + if ($shouldEnable = self::shouldEnableEntityLoader()) { + $disableEntities = libxml_disable_entity_loader(false); + } + try { + $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion)); + if (!$isValid) { + return self::getXmlErrors($internalErrors); + } + } finally { + if ($shouldEnable) { + libxml_disable_entity_loader($disableEntities); + } + } + + $dom->normalizeDocument(); + + libxml_clear_errors(); + libxml_use_internal_errors($internalErrors); + + return []; + } + + private static function shouldEnableEntityLoader(): bool + { + static $dom, $schema; + if (null === $dom) { + $dom = new \DOMDocument(); + $dom->loadXML(''); + + $tmpfile = tempnam(sys_get_temp_dir(), 'symfony'); + register_shutdown_function(static function () use ($tmpfile) { + @unlink($tmpfile); + }); + $schema = ' + + +'; + file_put_contents($tmpfile, ' + + + +'); + } + + return !@$dom->schemaValidateSource($schema); + } + + public static function getErrorsAsString(array $xmlErrors): string + { + $errorsAsString = ''; + + foreach ($xmlErrors as $error) { + $errorsAsString .= sprintf("[%s %s] %s (in %s - line %d, column %d)\n", + \LIBXML_ERR_WARNING === $error['level'] ? 'WARNING' : 'ERROR', + $error['code'], + $error['message'], + $error['file'], + $error['line'], + $error['column'] + ); + } + + return $errorsAsString; + } + + private static function getSchema(string $xliffVersion): string + { + if ('1.2' === $xliffVersion) { + $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-1.2-transitional.xsd'); + $xmlUri = 'http://www.w3.org/2001/xml.xsd'; + } elseif ('2.0' === $xliffVersion) { + $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-2.0.xsd'); + $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd'; + } else { + throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion)); + } + + return self::fixXmlLocation($schemaSource, $xmlUri); + } + + /** + * Internally changes the URI of a dependent xsd to be loaded locally. + */ + private static function fixXmlLocation(string $schemaSource, string $xmlUri): string + { + $newPath = str_replace('\\', '/', __DIR__).'/../Resources/schemas/xml.xsd'; + $parts = explode('/', $newPath); + $locationstart = 'file:///'; + if (0 === stripos($newPath, 'phar://')) { + $tmpfile = tempnam(sys_get_temp_dir(), 'symfony'); + if ($tmpfile) { + copy($newPath, $tmpfile); + $parts = explode('/', str_replace('\\', '/', $tmpfile)); + } else { + array_shift($parts); + $locationstart = 'phar:///'; + } + } + + $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : ''; + $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts)); + + return str_replace($xmlUri, $newPath, $schemaSource); + } + + /** + * Returns the XML errors of the internal XML parser. + */ + private static function getXmlErrors(bool $internalErrors): array + { + $errors = []; + foreach (libxml_get_errors() as $error) { + $errors[] = [ + 'level' => \LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', + 'code' => $error->code, + 'message' => trim($error->message), + 'file' => $error->file ?: 'n/a', + 'line' => $error->line, + 'column' => $error->column, + ]; + } + + libxml_clear_errors(); + libxml_use_internal_errors($internalErrors); + + return $errors; + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Writer/TranslationWriter.php b/php/libraries/composer/vendor/symfony/translation/Writer/TranslationWriter.php new file mode 100644 index 0000000..61e03cb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Writer/TranslationWriter.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\Translation\Writer; + +use Symfony\Component\Translation\Dumper\DumperInterface; +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\RuntimeException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * TranslationWriter writes translation messages. + * + * @author Michel Salib + */ +class TranslationWriter implements TranslationWriterInterface +{ + /** + * @var array + */ + private array $dumpers = []; + + /** + * Adds a dumper to the writer. + * + * @return void + */ + public function addDumper(string $format, DumperInterface $dumper) + { + $this->dumpers[$format] = $dumper; + } + + /** + * Obtains the list of supported formats. + */ + public function getFormats(): array + { + return array_keys($this->dumpers); + } + + /** + * Writes translation from the catalogue according to the selected format. + * + * @param string $format The format to use to dump the messages + * @param array $options Options that are passed to the dumper + * + * @return void + * + * @throws InvalidArgumentException + */ + public function write(MessageCatalogue $catalogue, string $format, array $options = []) + { + if (!isset($this->dumpers[$format])) { + throw new InvalidArgumentException(sprintf('There is no dumper associated with format "%s".', $format)); + } + + // get the right dumper + $dumper = $this->dumpers[$format]; + + if (isset($options['path']) && !is_dir($options['path']) && !@mkdir($options['path'], 0777, true) && !is_dir($options['path'])) { + throw new RuntimeException(sprintf('Translation Writer was not able to create directory "%s".', $options['path'])); + } + + // save + $dumper->dump($catalogue, $options); + } +} diff --git a/php/libraries/composer/vendor/symfony/translation/Writer/TranslationWriterInterface.php b/php/libraries/composer/vendor/symfony/translation/Writer/TranslationWriterInterface.php new file mode 100644 index 0000000..5ebb979 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/Writer/TranslationWriterInterface.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Writer; + +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * TranslationWriter writes translation messages. + * + * @author Michel Salib + */ +interface TranslationWriterInterface +{ + /** + * Writes translation from the catalogue according to the selected format. + * + * @param string $format The format to use to dump the messages + * @param array $options Options that are passed to the dumper + * + * @return void + * + * @throws InvalidArgumentException + */ + public function write(MessageCatalogue $catalogue, string $format, array $options = []); +} diff --git a/php/libraries/composer/vendor/symfony/translation/composer.json b/php/libraries/composer/vendor/symfony/translation/composer.json new file mode 100644 index 0000000..af6f7a3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/translation/composer.json @@ -0,0 +1,60 @@ +{ + "name": "symfony/translation", + "type": "library", + "description": "Provides tools to internationalize your application", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/translation-contracts": "^2.5|^3.0" + }, + "require-dev": { + "nikic/php-parser": "^4.18|^5.0", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/http-client-contracts": "^2.5|^3.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", + "symfony/polyfill-intl-icu": "^1.21", + "symfony/routing": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^5.4|^6.0|^7.0", + "symfony/finder": "^5.4|^6.0|^7.0", + "psr/log": "^1|^2|^3" + }, + "conflict": { + "symfony/config": "<5.4", + "symfony/dependency-injection": "<5.4", + "symfony/http-client-contracts": "<2.5", + "symfony/http-kernel": "<5.4", + "symfony/service-contracts": "<2.5", + "symfony/twig-bundle": "<5.4", + "symfony/yaml": "<5.4", + "symfony/console": "<5.4" + }, + "provide": { + "symfony/translation-implementation": "2.3|3.0" + }, + "autoload": { + "files": [ "Resources/functions.php" ], + "psr-4": { "Symfony\\Component\\Translation\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/CHANGELOG.md b/php/libraries/composer/vendor/symfony/var-dumper/CHANGELOG.md new file mode 100644 index 0000000..f58ed31 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/CHANGELOG.md @@ -0,0 +1,72 @@ +CHANGELOG +========= + +5.4 +--- + + * Add ability to style integer and double values independently + * Add casters for Symfony's UUIDs and ULIDs + * Add support for `Fiber` + +5.2.0 +----- + + * added support for PHPUnit `--colors` option + * added `VAR_DUMPER_FORMAT=server` env var value support + * prevent replacing the handler when the `VAR_DUMPER_FORMAT` env var is set + +5.1.0 +----- + + * added `RdKafka` support + +4.4.0 +----- + + * added `VarDumperTestTrait::setUpVarDumper()` and `VarDumperTestTrait::tearDownVarDumper()` + to configure casters & flags to use in tests + * added `ImagineCaster` and infrastructure to dump images + * added the stamps of a message after it is dispatched in `TraceableMessageBus` and `MessengerDataCollector` collected data + * added `UuidCaster` + * made all casters final + * added support for the `NO_COLOR` env var (https://no-color.org/) + +4.3.0 +----- + + * added `DsCaster` to support dumping the contents of data structures from the Ds extension + +4.2.0 +----- + + * support selecting the format to use by setting the environment variable `VAR_DUMPER_FORMAT` to `html` or `cli` + +4.1.0 +----- + + * added a `ServerDumper` to send serialized Data clones to a server + * added a `ServerDumpCommand` and `DumpServer` to run a server collecting + and displaying dumps on a single place with multiple formats support + * added `CliDescriptor` and `HtmlDescriptor` descriptors for `server:dump` CLI and HTML formats support + +4.0.0 +----- + + * support for passing `\ReflectionClass` instances to the `Caster::castObject()` + method has been dropped, pass class names as strings instead + * the `Data::getRawData()` method has been removed + * the `VarDumperTestTrait::assertDumpEquals()` method expects a 3rd `$filter = 0` + argument and moves `$message = ''` argument at 4th position. + * the `VarDumperTestTrait::assertDumpMatchesFormat()` method expects a 3rd `$filter = 0` + argument and moves `$message = ''` argument at 4th position. + +3.4.0 +----- + + * added `AbstractCloner::setMinDepth()` function to ensure minimum tree depth + * deprecated `MongoCaster` + +2.7.0 +----- + + * deprecated `Cloner\Data::getLimitedClone()`. Use `withMaxDepth`, `withMaxItemsPerDepth` or `withRefHandles` instead. diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/AmqpCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/AmqpCaster.php new file mode 100644 index 0000000..dc3b621 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/AmqpCaster.php @@ -0,0 +1,212 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts Amqp related classes to array representation. + * + * @author Grégoire Pineau + * + * @final + */ +class AmqpCaster +{ + private const FLAGS = [ + \AMQP_DURABLE => 'AMQP_DURABLE', + \AMQP_PASSIVE => 'AMQP_PASSIVE', + \AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE', + \AMQP_AUTODELETE => 'AMQP_AUTODELETE', + \AMQP_INTERNAL => 'AMQP_INTERNAL', + \AMQP_NOLOCAL => 'AMQP_NOLOCAL', + \AMQP_AUTOACK => 'AMQP_AUTOACK', + \AMQP_IFEMPTY => 'AMQP_IFEMPTY', + \AMQP_IFUNUSED => 'AMQP_IFUNUSED', + \AMQP_MANDATORY => 'AMQP_MANDATORY', + \AMQP_IMMEDIATE => 'AMQP_IMMEDIATE', + \AMQP_MULTIPLE => 'AMQP_MULTIPLE', + \AMQP_NOWAIT => 'AMQP_NOWAIT', + \AMQP_REQUEUE => 'AMQP_REQUEUE', + ]; + + private const EXCHANGE_TYPES = [ + \AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT', + \AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT', + \AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC', + \AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS', + ]; + + public static function castConnection(\AMQPConnection $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'is_connected' => $c->isConnected(), + ]; + + // Recent version of the extension already expose private properties + if (isset($a["\x00AMQPConnection\x00login"])) { + return $a; + } + + // BC layer in the amqp lib + if (method_exists($c, 'getReadTimeout')) { + $timeout = $c->getReadTimeout(); + } else { + $timeout = $c->getTimeout(); + } + + $a += [ + $prefix.'is_connected' => $c->isConnected(), + $prefix.'login' => $c->getLogin(), + $prefix.'password' => $c->getPassword(), + $prefix.'host' => $c->getHost(), + $prefix.'vhost' => $c->getVhost(), + $prefix.'port' => $c->getPort(), + $prefix.'read_timeout' => $timeout, + ]; + + return $a; + } + + public static function castChannel(\AMQPChannel $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'is_connected' => $c->isConnected(), + $prefix.'channel_id' => $c->getChannelId(), + ]; + + // Recent version of the extension already expose private properties + if (isset($a["\x00AMQPChannel\x00connection"])) { + return $a; + } + + $a += [ + $prefix.'connection' => $c->getConnection(), + $prefix.'prefetch_size' => $c->getPrefetchSize(), + $prefix.'prefetch_count' => $c->getPrefetchCount(), + ]; + + return $a; + } + + public static function castQueue(\AMQPQueue $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'flags' => self::extractFlags($c->getFlags()), + ]; + + // Recent version of the extension already expose private properties + if (isset($a["\x00AMQPQueue\x00name"])) { + return $a; + } + + $a += [ + $prefix.'connection' => $c->getConnection(), + $prefix.'channel' => $c->getChannel(), + $prefix.'name' => $c->getName(), + $prefix.'arguments' => $c->getArguments(), + ]; + + return $a; + } + + public static function castExchange(\AMQPExchange $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'flags' => self::extractFlags($c->getFlags()), + ]; + + $type = isset(self::EXCHANGE_TYPES[$c->getType()]) ? new ConstStub(self::EXCHANGE_TYPES[$c->getType()], $c->getType()) : $c->getType(); + + // Recent version of the extension already expose private properties + if (isset($a["\x00AMQPExchange\x00name"])) { + $a["\x00AMQPExchange\x00type"] = $type; + + return $a; + } + + $a += [ + $prefix.'connection' => $c->getConnection(), + $prefix.'channel' => $c->getChannel(), + $prefix.'name' => $c->getName(), + $prefix.'type' => $type, + $prefix.'arguments' => $c->getArguments(), + ]; + + return $a; + } + + public static function castEnvelope(\AMQPEnvelope $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $deliveryMode = new ConstStub($c->getDeliveryMode().(2 === $c->getDeliveryMode() ? ' (persistent)' : ' (non-persistent)'), $c->getDeliveryMode()); + + // Recent version of the extension already expose private properties + if (isset($a["\x00AMQPEnvelope\x00body"])) { + $a["\0AMQPEnvelope\0delivery_mode"] = $deliveryMode; + + return $a; + } + + if (!($filter & Caster::EXCLUDE_VERBOSE)) { + $a += [$prefix.'body' => $c->getBody()]; + } + + $a += [ + $prefix.'delivery_tag' => $c->getDeliveryTag(), + $prefix.'is_redelivery' => $c->isRedelivery(), + $prefix.'exchange_name' => $c->getExchangeName(), + $prefix.'routing_key' => $c->getRoutingKey(), + $prefix.'content_type' => $c->getContentType(), + $prefix.'content_encoding' => $c->getContentEncoding(), + $prefix.'headers' => $c->getHeaders(), + $prefix.'delivery_mode' => $deliveryMode, + $prefix.'priority' => $c->getPriority(), + $prefix.'correlation_id' => $c->getCorrelationId(), + $prefix.'reply_to' => $c->getReplyTo(), + $prefix.'expiration' => $c->getExpiration(), + $prefix.'message_id' => $c->getMessageId(), + $prefix.'timestamp' => $c->getTimeStamp(), + $prefix.'type' => $c->getType(), + $prefix.'user_id' => $c->getUserId(), + $prefix.'app_id' => $c->getAppId(), + ]; + + return $a; + } + + private static function extractFlags(int $flags): ConstStub + { + $flagsArray = []; + + foreach (self::FLAGS as $value => $name) { + if ($flags & $value) { + $flagsArray[] = $name; + } + } + + if (!$flagsArray) { + $flagsArray = ['AMQP_NOPARAM']; + } + + return new ConstStub(implode('|', $flagsArray), $flags); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ArgsStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ArgsStub.php new file mode 100644 index 0000000..b3f7bbe --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ArgsStub.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents a list of function arguments. + * + * @author Nicolas Grekas + */ +class ArgsStub extends EnumStub +{ + private static $parameters = []; + + public function __construct(array $args, string $function, ?string $class) + { + [$variadic, $params] = self::getParameters($function, $class); + + $values = []; + foreach ($args as $k => $v) { + $values[$k] = !\is_scalar($v) && !$v instanceof Stub ? new CutStub($v) : $v; + } + if (null === $params) { + parent::__construct($values, false); + + return; + } + if (\count($values) < \count($params)) { + $params = \array_slice($params, 0, \count($values)); + } elseif (\count($values) > \count($params)) { + $values[] = new EnumStub(array_splice($values, \count($params)), false); + $params[] = $variadic; + } + if (['...'] === $params) { + $this->dumpKeys = false; + $this->value = $values[0]->value; + } else { + $this->value = array_combine($params, $values); + } + } + + private static function getParameters(string $function, ?string $class): array + { + if (isset(self::$parameters[$k = $class.'::'.$function])) { + return self::$parameters[$k]; + } + + try { + $r = null !== $class ? new \ReflectionMethod($class, $function) : new \ReflectionFunction($function); + } catch (\ReflectionException $e) { + return [null, null]; + } + + $variadic = '...'; + $params = []; + foreach ($r->getParameters() as $v) { + $k = '$'.$v->name; + if ($v->isPassedByReference()) { + $k = '&'.$k; + } + if ($v->isVariadic()) { + $variadic .= $k; + } else { + $params[] = $k; + } + } + + return self::$parameters[$k] = [$variadic, $params]; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/Caster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/Caster.php new file mode 100644 index 0000000..0923809 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/Caster.php @@ -0,0 +1,170 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Helper for filtering out properties in casters. + * + * @author Nicolas Grekas + * + * @final + */ +class Caster +{ + public const EXCLUDE_VERBOSE = 1; + public const EXCLUDE_VIRTUAL = 2; + public const EXCLUDE_DYNAMIC = 4; + public const EXCLUDE_PUBLIC = 8; + public const EXCLUDE_PROTECTED = 16; + public const EXCLUDE_PRIVATE = 32; + public const EXCLUDE_NULL = 64; + public const EXCLUDE_EMPTY = 128; + public const EXCLUDE_NOT_IMPORTANT = 256; + public const EXCLUDE_STRICT = 512; + + public const PREFIX_VIRTUAL = "\0~\0"; + public const PREFIX_DYNAMIC = "\0+\0"; + public const PREFIX_PROTECTED = "\0*\0"; + + /** + * Casts objects to arrays and adds the dynamic property prefix. + * + * @param bool $hasDebugInfo Whether the __debugInfo method exists on $obj or not + */ + public static function castObject(object $obj, string $class, bool $hasDebugInfo = false, ?string $debugClass = null): array + { + if ($hasDebugInfo) { + try { + $debugInfo = $obj->__debugInfo(); + } catch (\Throwable $e) { + // ignore failing __debugInfo() + $hasDebugInfo = false; + } + } + + $a = $obj instanceof \Closure ? [] : (array) $obj; + + if ($obj instanceof \__PHP_Incomplete_Class) { + return $a; + } + + if ($a) { + static $publicProperties = []; + $debugClass = $debugClass ?? get_debug_type($obj); + + $i = 0; + $prefixedKeys = []; + foreach ($a as $k => $v) { + if ("\0" !== ($k[0] ?? '')) { + if (!isset($publicProperties[$class])) { + foreach ((new \ReflectionClass($class))->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop) { + $publicProperties[$class][$prop->name] = true; + } + } + if (!isset($publicProperties[$class][$k])) { + $prefixedKeys[$i] = self::PREFIX_DYNAMIC.$k; + } + } elseif ($debugClass !== $class && 1 === strpos($k, $class)) { + $prefixedKeys[$i] = "\0".$debugClass.strrchr($k, "\0"); + } + ++$i; + } + if ($prefixedKeys) { + $keys = array_keys($a); + foreach ($prefixedKeys as $i => $k) { + $keys[$i] = $k; + } + $a = array_combine($keys, $a); + } + } + + if ($hasDebugInfo && \is_array($debugInfo)) { + foreach ($debugInfo as $k => $v) { + if (!isset($k[0]) || "\0" !== $k[0]) { + if (\array_key_exists(self::PREFIX_DYNAMIC.$k, $a)) { + continue; + } + $k = self::PREFIX_VIRTUAL.$k; + } + + unset($a[$k]); + $a[$k] = $v; + } + } + + return $a; + } + + /** + * Filters out the specified properties. + * + * By default, a single match in the $filter bit field filters properties out, following an "or" logic. + * When EXCLUDE_STRICT is set, an "and" logic is applied: all bits must match for a property to be removed. + * + * @param array $a The array containing the properties to filter + * @param int $filter A bit field of Caster::EXCLUDE_* constants specifying which properties to filter out + * @param string[] $listedProperties List of properties to exclude when Caster::EXCLUDE_VERBOSE is set, and to preserve when Caster::EXCLUDE_NOT_IMPORTANT is set + * @param int|null &$count Set to the number of removed properties + */ + public static function filter(array $a, int $filter, array $listedProperties = [], ?int &$count = 0): array + { + $count = 0; + + foreach ($a as $k => $v) { + $type = self::EXCLUDE_STRICT & $filter; + + if (null === $v) { + $type |= self::EXCLUDE_NULL & $filter; + $type |= self::EXCLUDE_EMPTY & $filter; + } elseif (false === $v || '' === $v || '0' === $v || 0 === $v || 0.0 === $v || [] === $v) { + $type |= self::EXCLUDE_EMPTY & $filter; + } + if ((self::EXCLUDE_NOT_IMPORTANT & $filter) && !\in_array($k, $listedProperties, true)) { + $type |= self::EXCLUDE_NOT_IMPORTANT; + } + if ((self::EXCLUDE_VERBOSE & $filter) && \in_array($k, $listedProperties, true)) { + $type |= self::EXCLUDE_VERBOSE; + } + + if (!isset($k[1]) || "\0" !== $k[0]) { + $type |= self::EXCLUDE_PUBLIC & $filter; + } elseif ('~' === $k[1]) { + $type |= self::EXCLUDE_VIRTUAL & $filter; + } elseif ('+' === $k[1]) { + $type |= self::EXCLUDE_DYNAMIC & $filter; + } elseif ('*' === $k[1]) { + $type |= self::EXCLUDE_PROTECTED & $filter; + } else { + $type |= self::EXCLUDE_PRIVATE & $filter; + } + + if ((self::EXCLUDE_STRICT & $filter) ? $type === $filter : $type) { + unset($a[$k]); + ++$count; + } + } + + return $a; + } + + public static function castPhpIncompleteClass(\__PHP_Incomplete_Class $c, array $a, Stub $stub, bool $isNested): array + { + if (isset($a['__PHP_Incomplete_Class_Name'])) { + $stub->class .= '('.$a['__PHP_Incomplete_Class_Name'].')'; + unset($a['__PHP_Incomplete_Class_Name']); + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ClassStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ClassStub.php new file mode 100644 index 0000000..48f8483 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ClassStub.php @@ -0,0 +1,106 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents a PHP class identifier. + * + * @author Nicolas Grekas + */ +class ClassStub extends ConstStub +{ + /** + * @param string $identifier A PHP identifier, e.g. a class, method, interface, etc. name + * @param callable $callable The callable targeted by the identifier when it is ambiguous or not a real PHP identifier + */ + public function __construct(string $identifier, $callable = null) + { + $this->value = $identifier; + + try { + if (null !== $callable) { + if ($callable instanceof \Closure) { + $r = new \ReflectionFunction($callable); + } elseif (\is_object($callable)) { + $r = [$callable, '__invoke']; + } elseif (\is_array($callable)) { + $r = $callable; + } elseif (false !== $i = strpos($callable, '::')) { + $r = [substr($callable, 0, $i), substr($callable, 2 + $i)]; + } else { + $r = new \ReflectionFunction($callable); + } + } elseif (0 < $i = strpos($identifier, '::') ?: strpos($identifier, '->')) { + $r = [substr($identifier, 0, $i), substr($identifier, 2 + $i)]; + } else { + $r = new \ReflectionClass($identifier); + } + + if (\is_array($r)) { + try { + $r = new \ReflectionMethod($r[0], $r[1]); + } catch (\ReflectionException $e) { + $r = new \ReflectionClass($r[0]); + } + } + + if (str_contains($identifier, "@anonymous\0")) { + $this->value = $identifier = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) { + return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0]; + }, $identifier); + } + + if (null !== $callable && $r instanceof \ReflectionFunctionAbstract) { + $s = ReflectionCaster::castFunctionAbstract($r, [], new Stub(), true, Caster::EXCLUDE_VERBOSE); + $s = ReflectionCaster::getSignature($s); + + if (str_ends_with($identifier, '()')) { + $this->value = substr_replace($identifier, $s, -2); + } else { + $this->value .= $s; + } + } + } catch (\ReflectionException $e) { + return; + } finally { + if (0 < $i = strrpos($this->value, '\\')) { + $this->attr['ellipsis'] = \strlen($this->value) - $i; + $this->attr['ellipsis-type'] = 'class'; + $this->attr['ellipsis-tail'] = 1; + } + } + + if ($f = $r->getFileName()) { + $this->attr['file'] = $f; + $this->attr['line'] = $r->getStartLine(); + } + } + + public static function wrapCallable($callable) + { + if (\is_object($callable) || !\is_callable($callable)) { + return $callable; + } + + if (!\is_array($callable)) { + $callable = new static($callable, $callable); + } elseif (\is_string($callable[0])) { + $callable[0] = new static($callable[0], $callable); + } else { + $callable[1] = new static($callable[1], $callable); + } + + return $callable; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ConstStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ConstStub.php new file mode 100644 index 0000000..8b01797 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ConstStub.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\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents a PHP constant and its value. + * + * @author Nicolas Grekas + */ +class ConstStub extends Stub +{ + public function __construct(string $name, $value = null) + { + $this->class = $name; + $this->value = 1 < \func_num_args() ? $value : $name; + } + + /** + * @return string + */ + public function __toString() + { + return (string) $this->value; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/CutArrayStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/CutArrayStub.php new file mode 100644 index 0000000..0e4fb36 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/CutArrayStub.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\VarDumper\Caster; + +/** + * Represents a cut array. + * + * @author Nicolas Grekas + */ +class CutArrayStub extends CutStub +{ + public $preservedSubset; + + public function __construct(array $value, array $preservedKeys) + { + parent::__construct($value); + + $this->preservedSubset = array_intersect_key($value, array_flip($preservedKeys)); + $this->cut -= \count($this->preservedSubset); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/CutStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/CutStub.php new file mode 100644 index 0000000..464c6db --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/CutStub.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents the main properties of a PHP variable, pre-casted by a caster. + * + * @author Nicolas Grekas + */ +class CutStub extends Stub +{ + public function __construct($value) + { + $this->value = $value; + + switch (\gettype($value)) { + case 'object': + $this->type = self::TYPE_OBJECT; + $this->class = \get_class($value); + + if ($value instanceof \Closure) { + ReflectionCaster::castClosure($value, [], $this, true, Caster::EXCLUDE_VERBOSE); + } + + $this->cut = -1; + break; + + case 'array': + $this->type = self::TYPE_ARRAY; + $this->class = self::ARRAY_ASSOC; + $this->cut = $this->value = \count($value); + break; + + case 'resource': + case 'unknown type': + case 'resource (closed)': + $this->type = self::TYPE_RESOURCE; + $this->handle = (int) $value; + if ('Unknown' === $this->class = @get_resource_type($value)) { + $this->class = 'Closed'; + } + $this->cut = -1; + break; + + case 'string': + $this->type = self::TYPE_STRING; + $this->class = preg_match('//u', $value) ? self::STRING_UTF8 : self::STRING_BINARY; + $this->cut = self::STRING_BINARY === $this->class ? \strlen($value) : mb_strlen($value, 'UTF-8'); + $this->value = ''; + break; + } + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/DOMCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DOMCaster.php new file mode 100644 index 0000000..4dd16e0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DOMCaster.php @@ -0,0 +1,304 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts DOM related classes to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class DOMCaster +{ + private const ERROR_CODES = [ + \DOM_PHP_ERR => 'DOM_PHP_ERR', + \DOM_INDEX_SIZE_ERR => 'DOM_INDEX_SIZE_ERR', + \DOMSTRING_SIZE_ERR => 'DOMSTRING_SIZE_ERR', + \DOM_HIERARCHY_REQUEST_ERR => 'DOM_HIERARCHY_REQUEST_ERR', + \DOM_WRONG_DOCUMENT_ERR => 'DOM_WRONG_DOCUMENT_ERR', + \DOM_INVALID_CHARACTER_ERR => 'DOM_INVALID_CHARACTER_ERR', + \DOM_NO_DATA_ALLOWED_ERR => 'DOM_NO_DATA_ALLOWED_ERR', + \DOM_NO_MODIFICATION_ALLOWED_ERR => 'DOM_NO_MODIFICATION_ALLOWED_ERR', + \DOM_NOT_FOUND_ERR => 'DOM_NOT_FOUND_ERR', + \DOM_NOT_SUPPORTED_ERR => 'DOM_NOT_SUPPORTED_ERR', + \DOM_INUSE_ATTRIBUTE_ERR => 'DOM_INUSE_ATTRIBUTE_ERR', + \DOM_INVALID_STATE_ERR => 'DOM_INVALID_STATE_ERR', + \DOM_SYNTAX_ERR => 'DOM_SYNTAX_ERR', + \DOM_INVALID_MODIFICATION_ERR => 'DOM_INVALID_MODIFICATION_ERR', + \DOM_NAMESPACE_ERR => 'DOM_NAMESPACE_ERR', + \DOM_INVALID_ACCESS_ERR => 'DOM_INVALID_ACCESS_ERR', + \DOM_VALIDATION_ERR => 'DOM_VALIDATION_ERR', + ]; + + private const NODE_TYPES = [ + \XML_ELEMENT_NODE => 'XML_ELEMENT_NODE', + \XML_ATTRIBUTE_NODE => 'XML_ATTRIBUTE_NODE', + \XML_TEXT_NODE => 'XML_TEXT_NODE', + \XML_CDATA_SECTION_NODE => 'XML_CDATA_SECTION_NODE', + \XML_ENTITY_REF_NODE => 'XML_ENTITY_REF_NODE', + \XML_ENTITY_NODE => 'XML_ENTITY_NODE', + \XML_PI_NODE => 'XML_PI_NODE', + \XML_COMMENT_NODE => 'XML_COMMENT_NODE', + \XML_DOCUMENT_NODE => 'XML_DOCUMENT_NODE', + \XML_DOCUMENT_TYPE_NODE => 'XML_DOCUMENT_TYPE_NODE', + \XML_DOCUMENT_FRAG_NODE => 'XML_DOCUMENT_FRAG_NODE', + \XML_NOTATION_NODE => 'XML_NOTATION_NODE', + \XML_HTML_DOCUMENT_NODE => 'XML_HTML_DOCUMENT_NODE', + \XML_DTD_NODE => 'XML_DTD_NODE', + \XML_ELEMENT_DECL_NODE => 'XML_ELEMENT_DECL_NODE', + \XML_ATTRIBUTE_DECL_NODE => 'XML_ATTRIBUTE_DECL_NODE', + \XML_ENTITY_DECL_NODE => 'XML_ENTITY_DECL_NODE', + \XML_NAMESPACE_DECL_NODE => 'XML_NAMESPACE_DECL_NODE', + ]; + + public static function castException(\DOMException $e, array $a, Stub $stub, bool $isNested) + { + $k = Caster::PREFIX_PROTECTED.'code'; + if (isset($a[$k], self::ERROR_CODES[$a[$k]])) { + $a[$k] = new ConstStub(self::ERROR_CODES[$a[$k]], $a[$k]); + } + + return $a; + } + + public static function castLength($dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'length' => $dom->length, + ]; + + return $a; + } + + public static function castImplementation(\DOMImplementation $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + Caster::PREFIX_VIRTUAL.'Core' => '1.0', + Caster::PREFIX_VIRTUAL.'XML' => '2.0', + ]; + + return $a; + } + + public static function castNode(\DOMNode $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'nodeName' => $dom->nodeName, + 'nodeValue' => new CutStub($dom->nodeValue), + 'nodeType' => new ConstStub(self::NODE_TYPES[$dom->nodeType], $dom->nodeType), + 'parentNode' => new CutStub($dom->parentNode), + 'childNodes' => $dom->childNodes, + 'firstChild' => new CutStub($dom->firstChild), + 'lastChild' => new CutStub($dom->lastChild), + 'previousSibling' => new CutStub($dom->previousSibling), + 'nextSibling' => new CutStub($dom->nextSibling), + 'attributes' => $dom->attributes, + 'ownerDocument' => new CutStub($dom->ownerDocument), + 'namespaceURI' => $dom->namespaceURI, + 'prefix' => $dom->prefix, + 'localName' => $dom->localName, + 'baseURI' => $dom->baseURI ? new LinkStub($dom->baseURI) : $dom->baseURI, + 'textContent' => new CutStub($dom->textContent), + ]; + + return $a; + } + + public static function castNameSpaceNode(\DOMNameSpaceNode $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'nodeName' => $dom->nodeName, + 'nodeValue' => new CutStub($dom->nodeValue), + 'nodeType' => new ConstStub(self::NODE_TYPES[$dom->nodeType], $dom->nodeType), + 'prefix' => $dom->prefix, + 'localName' => $dom->localName, + 'namespaceURI' => $dom->namespaceURI, + 'ownerDocument' => new CutStub($dom->ownerDocument), + 'parentNode' => new CutStub($dom->parentNode), + ]; + + return $a; + } + + public static function castDocument(\DOMDocument $dom, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $a += [ + 'doctype' => $dom->doctype, + 'implementation' => $dom->implementation, + 'documentElement' => new CutStub($dom->documentElement), + 'actualEncoding' => $dom->actualEncoding, + 'encoding' => $dom->encoding, + 'xmlEncoding' => $dom->xmlEncoding, + 'standalone' => $dom->standalone, + 'xmlStandalone' => $dom->xmlStandalone, + 'version' => $dom->version, + 'xmlVersion' => $dom->xmlVersion, + 'strictErrorChecking' => $dom->strictErrorChecking, + 'documentURI' => $dom->documentURI ? new LinkStub($dom->documentURI) : $dom->documentURI, + 'config' => $dom->config, + 'formatOutput' => $dom->formatOutput, + 'validateOnParse' => $dom->validateOnParse, + 'resolveExternals' => $dom->resolveExternals, + 'preserveWhiteSpace' => $dom->preserveWhiteSpace, + 'recover' => $dom->recover, + 'substituteEntities' => $dom->substituteEntities, + ]; + + if (!($filter & Caster::EXCLUDE_VERBOSE)) { + $formatOutput = $dom->formatOutput; + $dom->formatOutput = true; + $a += [Caster::PREFIX_VIRTUAL.'xml' => $dom->saveXML()]; + $dom->formatOutput = $formatOutput; + } + + return $a; + } + + public static function castCharacterData(\DOMCharacterData $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'data' => $dom->data, + 'length' => $dom->length, + ]; + + return $a; + } + + public static function castAttr(\DOMAttr $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'name' => $dom->name, + 'specified' => $dom->specified, + 'value' => $dom->value, + 'ownerElement' => $dom->ownerElement, + 'schemaTypeInfo' => $dom->schemaTypeInfo, + ]; + + return $a; + } + + public static function castElement(\DOMElement $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'tagName' => $dom->tagName, + 'schemaTypeInfo' => $dom->schemaTypeInfo, + ]; + + return $a; + } + + public static function castText(\DOMText $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'wholeText' => $dom->wholeText, + ]; + + return $a; + } + + public static function castTypeinfo(\DOMTypeinfo $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'typeName' => $dom->typeName, + 'typeNamespace' => $dom->typeNamespace, + ]; + + return $a; + } + + public static function castDomError(\DOMDomError $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'severity' => $dom->severity, + 'message' => $dom->message, + 'type' => $dom->type, + 'relatedException' => $dom->relatedException, + 'related_data' => $dom->related_data, + 'location' => $dom->location, + ]; + + return $a; + } + + public static function castLocator(\DOMLocator $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'lineNumber' => $dom->lineNumber, + 'columnNumber' => $dom->columnNumber, + 'offset' => $dom->offset, + 'relatedNode' => $dom->relatedNode, + 'uri' => $dom->uri ? new LinkStub($dom->uri, $dom->lineNumber) : $dom->uri, + ]; + + return $a; + } + + public static function castDocumentType(\DOMDocumentType $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'name' => $dom->name, + 'entities' => $dom->entities, + 'notations' => $dom->notations, + 'publicId' => $dom->publicId, + 'systemId' => $dom->systemId, + 'internalSubset' => $dom->internalSubset, + ]; + + return $a; + } + + public static function castNotation(\DOMNotation $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'publicId' => $dom->publicId, + 'systemId' => $dom->systemId, + ]; + + return $a; + } + + public static function castEntity(\DOMEntity $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'publicId' => $dom->publicId, + 'systemId' => $dom->systemId, + 'notationName' => $dom->notationName, + 'actualEncoding' => $dom->actualEncoding, + 'encoding' => $dom->encoding, + 'version' => $dom->version, + ]; + + return $a; + } + + public static function castProcessingInstruction(\DOMProcessingInstruction $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'target' => $dom->target, + 'data' => $dom->data, + ]; + + return $a; + } + + public static function castXPath(\DOMXPath $dom, array $a, Stub $stub, bool $isNested) + { + $a += [ + 'document' => $dom->document, + ]; + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/DateCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DateCaster.php new file mode 100644 index 0000000..d07bac5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DateCaster.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\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts DateTimeInterface related classes to array representation. + * + * @author Dany Maillard + * + * @final + */ +class DateCaster +{ + private const PERIOD_LIMIT = 3; + + public static function castDateTime(\DateTimeInterface $d, array $a, Stub $stub, bool $isNested, int $filter) + { + $prefix = Caster::PREFIX_VIRTUAL; + $location = $d->getTimezone() ? $d->getTimezone()->getLocation() : null; + $fromNow = (new \DateTime())->diff($d); + + $title = $d->format('l, F j, Y') + ."\n".self::formatInterval($fromNow).' from now' + .($location ? ($d->format('I') ? "\nDST On" : "\nDST Off") : '') + ; + + unset( + $a[Caster::PREFIX_DYNAMIC.'date'], + $a[Caster::PREFIX_DYNAMIC.'timezone'], + $a[Caster::PREFIX_DYNAMIC.'timezone_type'] + ); + $a[$prefix.'date'] = new ConstStub(self::formatDateTime($d, $location ? ' e (P)' : ' P'), $title); + + $stub->class .= $d->format(' @U'); + + return $a; + } + + public static function castInterval(\DateInterval $interval, array $a, Stub $stub, bool $isNested, int $filter) + { + $now = new \DateTimeImmutable('@0', new \DateTimeZone('UTC')); + $numberOfSeconds = $now->add($interval)->getTimestamp() - $now->getTimestamp(); + $title = number_format($numberOfSeconds, 0, '.', ' ').'s'; + + $i = [Caster::PREFIX_VIRTUAL.'interval' => new ConstStub(self::formatInterval($interval), $title)]; + + return $filter & Caster::EXCLUDE_VERBOSE ? $i : $i + $a; + } + + private static function formatInterval(\DateInterval $i): string + { + $format = '%R '; + + if (0 === $i->y && 0 === $i->m && ($i->h >= 24 || $i->i >= 60 || $i->s >= 60)) { + $d = new \DateTimeImmutable('@0', new \DateTimeZone('UTC')); + $i = $d->diff($d->add($i)); // recalculate carry over points + $format .= 0 < $i->days ? '%ad ' : ''; + } else { + $format .= ($i->y ? '%yy ' : '').($i->m ? '%mm ' : '').($i->d ? '%dd ' : ''); + } + + $format .= $i->h || $i->i || $i->s || $i->f ? '%H:%I:'.self::formatSeconds($i->s, substr($i->f, 2)) : ''; + $format = '%R ' === $format ? '0s' : $format; + + return $i->format(rtrim($format)); + } + + public static function castTimeZone(\DateTimeZone $timeZone, array $a, Stub $stub, bool $isNested, int $filter) + { + $location = $timeZone->getLocation(); + $formatted = (new \DateTime('now', $timeZone))->format($location ? 'e (P)' : 'P'); + $title = $location && \extension_loaded('intl') ? \Locale::getDisplayRegion('-'.$location['country_code']) : ''; + + $z = [Caster::PREFIX_VIRTUAL.'timezone' => new ConstStub($formatted, $title)]; + + return $filter & Caster::EXCLUDE_VERBOSE ? $z : $z + $a; + } + + public static function castPeriod(\DatePeriod $p, array $a, Stub $stub, bool $isNested, int $filter) + { + $dates = []; + foreach (clone $p as $i => $d) { + if (self::PERIOD_LIMIT === $i) { + $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); + $dates[] = sprintf('%s more', ($end = $p->getEndDate()) + ? ceil(($end->format('U.u') - $d->format('U.u')) / ((int) $now->add($p->getDateInterval())->format('U.u') - (int) $now->format('U.u'))) + : $p->recurrences - $i + ); + break; + } + $dates[] = sprintf('%s) %s', $i + 1, self::formatDateTime($d)); + } + + $period = sprintf( + 'every %s, from %s%s %s', + self::formatInterval($p->getDateInterval()), + $p->include_start_date ? '[' : ']', + self::formatDateTime($p->getStartDate()), + ($end = $p->getEndDate()) ? 'to '.self::formatDateTime($end).(\PHP_VERSION_ID >= 80200 && $p->include_end_date ? ']' : '[') : 'recurring '.$p->recurrences.' time/s' + ); + + $p = [Caster::PREFIX_VIRTUAL.'period' => new ConstStub($period, implode("\n", $dates))]; + + return $filter & Caster::EXCLUDE_VERBOSE ? $p : $p + $a; + } + + private static function formatDateTime(\DateTimeInterface $d, string $extra = ''): string + { + return $d->format('Y-m-d H:i:'.self::formatSeconds($d->format('s'), $d->format('u')).$extra); + } + + private static function formatSeconds(string $s, string $us): string + { + return sprintf('%02d.%s', $s, 0 === ($len = \strlen($t = rtrim($us, '0'))) ? '0' : ($len <= 3 ? str_pad($t, 3, '0') : $us)); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/DoctrineCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DoctrineCaster.php new file mode 100644 index 0000000..129b2cb --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DoctrineCaster.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Doctrine\Common\Proxy\Proxy as CommonProxy; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Proxy\Proxy as OrmProxy; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts Doctrine related classes to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class DoctrineCaster +{ + public static function castCommonProxy(CommonProxy $proxy, array $a, Stub $stub, bool $isNested) + { + foreach (['__cloner__', '__initializer__'] as $k) { + if (\array_key_exists($k, $a)) { + unset($a[$k]); + ++$stub->cut; + } + } + + return $a; + } + + public static function castOrmProxy(OrmProxy $proxy, array $a, Stub $stub, bool $isNested) + { + foreach (['_entityPersister', '_identifier'] as $k) { + if (\array_key_exists($k = "\0Doctrine\\ORM\\Proxy\\Proxy\0".$k, $a)) { + unset($a[$k]); + ++$stub->cut; + } + } + + return $a; + } + + public static function castPersistentCollection(PersistentCollection $coll, array $a, Stub $stub, bool $isNested) + { + foreach (['snapshot', 'association', 'typeClass'] as $k) { + if (\array_key_exists($k = "\0Doctrine\\ORM\\PersistentCollection\0".$k, $a)) { + $a[$k] = new CutStub($a[$k]); + } + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/DsCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DsCaster.php new file mode 100644 index 0000000..b34b670 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DsCaster.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Ds\Collection; +use Ds\Map; +use Ds\Pair; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts Ds extension classes to array representation. + * + * @author Jáchym Toušek + * + * @final + */ +class DsCaster +{ + public static function castCollection(Collection $c, array $a, Stub $stub, bool $isNested): array + { + $a[Caster::PREFIX_VIRTUAL.'count'] = $c->count(); + $a[Caster::PREFIX_VIRTUAL.'capacity'] = $c->capacity(); + + if (!$c instanceof Map) { + $a += $c->toArray(); + } + + return $a; + } + + public static function castMap(Map $c, array $a, Stub $stub, bool $isNested): array + { + foreach ($c as $k => $v) { + $a[] = new DsPairStub($k, $v); + } + + return $a; + } + + public static function castPair(Pair $c, array $a, Stub $stub, bool $isNested): array + { + foreach ($c->toArray() as $k => $v) { + $a[Caster::PREFIX_VIRTUAL.$k] = $v; + } + + return $a; + } + + public static function castPairStub(DsPairStub $c, array $a, Stub $stub, bool $isNested): array + { + if ($isNested) { + $stub->class = Pair::class; + $stub->value = null; + $stub->handle = 0; + + $a = $c->value; + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/DsPairStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DsPairStub.php new file mode 100644 index 0000000..a1dcc15 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/DsPairStub.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Nicolas Grekas + */ +class DsPairStub extends Stub +{ + public function __construct($key, $value) + { + $this->value = [ + Caster::PREFIX_VIRTUAL.'key' => $key, + Caster::PREFIX_VIRTUAL.'value' => $value, + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/EnumStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/EnumStub.php new file mode 100644 index 0000000..7a4e98a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/EnumStub.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\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents an enumeration of values. + * + * @author Nicolas Grekas + */ +class EnumStub extends Stub +{ + public $dumpKeys = true; + + public function __construct(array $values, bool $dumpKeys = true) + { + $this->value = $values; + $this->dumpKeys = $dumpKeys; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ExceptionCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ExceptionCaster.php new file mode 100644 index 0000000..7f5cb65 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ExceptionCaster.php @@ -0,0 +1,388 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext; +use Symfony\Component\VarDumper\Cloner\Stub; +use Symfony\Component\VarDumper\Exception\ThrowingCasterException; + +/** + * Casts common Exception classes to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class ExceptionCaster +{ + public static $srcContext = 1; + public static $traceArgs = true; + public static $errorTypes = [ + \E_DEPRECATED => 'E_DEPRECATED', + \E_USER_DEPRECATED => 'E_USER_DEPRECATED', + \E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', + \E_ERROR => 'E_ERROR', + \E_WARNING => 'E_WARNING', + \E_PARSE => 'E_PARSE', + \E_NOTICE => 'E_NOTICE', + \E_CORE_ERROR => 'E_CORE_ERROR', + \E_CORE_WARNING => 'E_CORE_WARNING', + \E_COMPILE_ERROR => 'E_COMPILE_ERROR', + \E_COMPILE_WARNING => 'E_COMPILE_WARNING', + \E_USER_ERROR => 'E_USER_ERROR', + \E_USER_WARNING => 'E_USER_WARNING', + \E_USER_NOTICE => 'E_USER_NOTICE', + \E_STRICT => 'E_STRICT', + ]; + + private static $framesCache = []; + + public static function castError(\Error $e, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + return self::filterExceptionArray($stub->class, $a, "\0Error\0", $filter); + } + + public static function castException(\Exception $e, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + return self::filterExceptionArray($stub->class, $a, "\0Exception\0", $filter); + } + + public static function castErrorException(\ErrorException $e, array $a, Stub $stub, bool $isNested) + { + if (isset($a[$s = Caster::PREFIX_PROTECTED.'severity'], self::$errorTypes[$a[$s]])) { + $a[$s] = new ConstStub(self::$errorTypes[$a[$s]], $a[$s]); + } + + return $a; + } + + public static function castThrowingCasterException(ThrowingCasterException $e, array $a, Stub $stub, bool $isNested) + { + $trace = Caster::PREFIX_VIRTUAL.'trace'; + $prefix = Caster::PREFIX_PROTECTED; + $xPrefix = "\0Exception\0"; + + if (isset($a[$xPrefix.'previous'], $a[$trace]) && $a[$xPrefix.'previous'] instanceof \Exception) { + $b = (array) $a[$xPrefix.'previous']; + $class = get_debug_type($a[$xPrefix.'previous']); + self::traceUnshift($b[$xPrefix.'trace'], $class, $b[$prefix.'file'], $b[$prefix.'line']); + $a[$trace] = new TraceStub($b[$xPrefix.'trace'], false, 0, -\count($a[$trace]->value)); + } + + unset($a[$xPrefix.'previous'], $a[$prefix.'code'], $a[$prefix.'file'], $a[$prefix.'line']); + + return $a; + } + + public static function castSilencedErrorContext(SilencedErrorContext $e, array $a, Stub $stub, bool $isNested) + { + $sPrefix = "\0".SilencedErrorContext::class."\0"; + + if (!isset($a[$s = $sPrefix.'severity'])) { + return $a; + } + + if (isset(self::$errorTypes[$a[$s]])) { + $a[$s] = new ConstStub(self::$errorTypes[$a[$s]], $a[$s]); + } + + $trace = [[ + 'file' => $a[$sPrefix.'file'], + 'line' => $a[$sPrefix.'line'], + ]]; + + if (isset($a[$sPrefix.'trace'])) { + $trace = array_merge($trace, $a[$sPrefix.'trace']); + } + + unset($a[$sPrefix.'file'], $a[$sPrefix.'line'], $a[$sPrefix.'trace']); + $a[Caster::PREFIX_VIRTUAL.'trace'] = new TraceStub($trace, self::$traceArgs); + + return $a; + } + + public static function castTraceStub(TraceStub $trace, array $a, Stub $stub, bool $isNested) + { + if (!$isNested) { + return $a; + } + $stub->class = ''; + $stub->handle = 0; + $frames = $trace->value; + $prefix = Caster::PREFIX_VIRTUAL; + + $a = []; + $j = \count($frames); + if (0 > $i = $trace->sliceOffset) { + $i = max(0, $j + $i); + } + if (!isset($trace->value[$i])) { + return []; + } + $lastCall = isset($frames[$i]['function']) ? (isset($frames[$i]['class']) ? $frames[0]['class'].$frames[$i]['type'] : '').$frames[$i]['function'].'()' : ''; + $frames[] = ['function' => '']; + $collapse = false; + + for ($j += $trace->numberingOffset - $i++; isset($frames[$i]); ++$i, --$j) { + $f = $frames[$i]; + $call = isset($f['function']) ? (isset($f['class']) ? $f['class'].$f['type'] : '').$f['function'] : '???'; + + $frame = new FrameStub( + [ + 'object' => $f['object'] ?? null, + 'class' => $f['class'] ?? null, + 'type' => $f['type'] ?? null, + 'function' => $f['function'] ?? null, + ] + $frames[$i - 1], + false, + true + ); + $f = self::castFrameStub($frame, [], $frame, true); + if (isset($f[$prefix.'src'])) { + foreach ($f[$prefix.'src']->value as $label => $frame) { + if (str_starts_with($label, "\0~collapse=0")) { + if ($collapse) { + $label = substr_replace($label, '1', 11, 1); + } else { + $collapse = true; + } + } + $label = substr_replace($label, "title=Stack level $j.&", 2, 0); + } + $f = $frames[$i - 1]; + if ($trace->keepArgs && !empty($f['args']) && $frame instanceof EnumStub) { + $frame->value['arguments'] = new ArgsStub($f['args'], $f['function'] ?? null, $f['class'] ?? null); + } + } elseif ('???' !== $lastCall) { + $label = new ClassStub($lastCall); + if (isset($label->attr['ellipsis'])) { + $label->attr['ellipsis'] += 2; + $label = substr_replace($prefix, "ellipsis-type=class&ellipsis={$label->attr['ellipsis']}&ellipsis-tail=1&title=Stack level $j.", 2, 0).$label->value.'()'; + } else { + $label = substr_replace($prefix, "title=Stack level $j.", 2, 0).$label->value.'()'; + } + } else { + $label = substr_replace($prefix, "title=Stack level $j.", 2, 0).$lastCall; + } + $a[substr_replace($label, sprintf('separator=%s&', $frame instanceof EnumStub ? ' ' : ':'), 2, 0)] = $frame; + + $lastCall = $call; + } + if (null !== $trace->sliceLength) { + $a = \array_slice($a, 0, $trace->sliceLength, true); + } + + return $a; + } + + public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, bool $isNested) + { + if (!$isNested) { + return $a; + } + $f = $frame->value; + $prefix = Caster::PREFIX_VIRTUAL; + + if (isset($f['file'], $f['line'])) { + $cacheKey = $f; + unset($cacheKey['object'], $cacheKey['args']); + $cacheKey[] = self::$srcContext; + $cacheKey = implode('-', $cacheKey); + + if (isset(self::$framesCache[$cacheKey])) { + $a[$prefix.'src'] = self::$framesCache[$cacheKey]; + } else { + if (preg_match('/\((\d+)\)(?:\([\da-f]{32}\))? : (?:eval\(\)\'d code|runtime-created function)$/', $f['file'], $match)) { + $f['file'] = substr($f['file'], 0, -\strlen($match[0])); + $f['line'] = (int) $match[1]; + } + $src = $f['line']; + $srcKey = $f['file']; + $ellipsis = new LinkStub($srcKey, 0); + $srcAttr = 'collapse='.(int) $ellipsis->inVendor; + $ellipsisTail = $ellipsis->attr['ellipsis-tail'] ?? 0; + $ellipsis = $ellipsis->attr['ellipsis'] ?? 0; + + if (is_file($f['file']) && 0 <= self::$srcContext) { + if (!empty($f['class']) && (is_subclass_of($f['class'], 'Twig\Template') || is_subclass_of($f['class'], 'Twig_Template')) && method_exists($f['class'], 'getDebugInfo')) { + $template = null; + if (isset($f['object'])) { + $template = $f['object']; + } elseif ((new \ReflectionClass($f['class']))->isInstantiable()) { + $template = unserialize(sprintf('O:%d:"%s":0:{}', \strlen($f['class']), $f['class'])); + } + if (null !== $template) { + $ellipsis = 0; + $templateSrc = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : ''); + $templateInfo = $template->getDebugInfo(); + if (isset($templateInfo[$f['line']])) { + if (!method_exists($template, 'getSourceContext') || !is_file($templatePath = $template->getSourceContext()->getPath())) { + $templatePath = null; + } + if ($templateSrc) { + $src = self::extractSource($templateSrc, $templateInfo[$f['line']], self::$srcContext, 'twig', $templatePath, $f); + $srcKey = ($templatePath ?: $template->getTemplateName()).':'.$templateInfo[$f['line']]; + } + } + } + } + if ($srcKey == $f['file']) { + $src = self::extractSource(file_get_contents($f['file']), $f['line'], self::$srcContext, 'php', $f['file'], $f); + $srcKey .= ':'.$f['line']; + if ($ellipsis) { + $ellipsis += 1 + \strlen($f['line']); + } + } + $srcAttr .= sprintf('&separator= &file=%s&line=%d', rawurlencode($f['file']), $f['line']); + } else { + $srcAttr .= '&separator=:'; + } + $srcAttr .= $ellipsis ? '&ellipsis-type=path&ellipsis='.$ellipsis.'&ellipsis-tail='.$ellipsisTail : ''; + self::$framesCache[$cacheKey] = $a[$prefix.'src'] = new EnumStub(["\0~$srcAttr\0$srcKey" => $src]); + } + } + + unset($a[$prefix.'args'], $a[$prefix.'line'], $a[$prefix.'file']); + if ($frame->inTraceStub) { + unset($a[$prefix.'class'], $a[$prefix.'type'], $a[$prefix.'function']); + } + foreach ($a as $k => $v) { + if (!$v) { + unset($a[$k]); + } + } + if ($frame->keepArgs && !empty($f['args'])) { + $a[$prefix.'arguments'] = new ArgsStub($f['args'], $f['function'], $f['class']); + } + + return $a; + } + + private static function filterExceptionArray(string $xClass, array $a, string $xPrefix, int $filter): array + { + if (isset($a[$xPrefix.'trace'])) { + $trace = $a[$xPrefix.'trace']; + unset($a[$xPrefix.'trace']); // Ensures the trace is always last + } else { + $trace = []; + } + + if (!($filter & Caster::EXCLUDE_VERBOSE) && $trace) { + if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) { + self::traceUnshift($trace, $xClass, $a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line']); + } + $a[Caster::PREFIX_VIRTUAL.'trace'] = new TraceStub($trace, self::$traceArgs); + } + if (empty($a[$xPrefix.'previous'])) { + unset($a[$xPrefix.'previous']); + } + unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message'], $a[Caster::PREFIX_DYNAMIC.'__destructorException']); + + if (isset($a[Caster::PREFIX_PROTECTED.'message']) && str_contains($a[Caster::PREFIX_PROTECTED.'message'], "@anonymous\0")) { + $a[Caster::PREFIX_PROTECTED.'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]++/', function ($m) { + return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0]; + }, $a[Caster::PREFIX_PROTECTED.'message']); + } + + if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) { + $a[Caster::PREFIX_PROTECTED.'file'] = new LinkStub($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line']); + } + + return $a; + } + + private static function traceUnshift(array &$trace, ?string $class, string $file, int $line): void + { + if (isset($trace[0]['file'], $trace[0]['line']) && $trace[0]['file'] === $file && $trace[0]['line'] === $line) { + return; + } + array_unshift($trace, [ + 'function' => $class ? 'new '.$class : null, + 'file' => $file, + 'line' => $line, + ]); + } + + private static function extractSource(string $srcLines, int $line, int $srcContext, string $lang, ?string $file, array $frame): EnumStub + { + $srcLines = explode("\n", $srcLines); + $src = []; + + for ($i = $line - 1 - $srcContext; $i <= $line - 1 + $srcContext; ++$i) { + $src[] = ($srcLines[$i] ?? '')."\n"; + } + + if ($frame['function'] ?? false) { + $stub = new CutStub(new \stdClass()); + $stub->class = (isset($frame['class']) ? $frame['class'].$frame['type'] : '').$frame['function']; + $stub->type = Stub::TYPE_OBJECT; + $stub->attr['cut_hash'] = true; + $stub->attr['file'] = $frame['file']; + $stub->attr['line'] = $frame['line']; + + try { + $caller = isset($frame['class']) ? new \ReflectionMethod($frame['class'], $frame['function']) : new \ReflectionFunction($frame['function']); + $stub->class .= ReflectionCaster::getSignature(ReflectionCaster::castFunctionAbstract($caller, [], $stub, true, Caster::EXCLUDE_VERBOSE)); + + if ($f = $caller->getFileName()) { + $stub->attr['file'] = $f; + $stub->attr['line'] = $caller->getStartLine(); + } + } catch (\ReflectionException $e) { + // ignore fake class/function + } + + $srcLines = ["\0~separator=\0" => $stub]; + } else { + $stub = null; + $srcLines = []; + } + + $ltrim = 0; + do { + $pad = null; + for ($i = $srcContext << 1; $i >= 0; --$i) { + if (isset($src[$i][$ltrim]) && "\r" !== ($c = $src[$i][$ltrim]) && "\n" !== $c) { + if (null === $pad) { + $pad = $c; + } + if ((' ' !== $c && "\t" !== $c) || $pad !== $c) { + break; + } + } + } + ++$ltrim; + } while (0 > $i && null !== $pad); + + --$ltrim; + + foreach ($src as $i => $c) { + if ($ltrim) { + $c = isset($c[$ltrim]) && "\r" !== $c[$ltrim] ? substr($c, $ltrim) : ltrim($c, " \t"); + } + $c = substr($c, 0, -1); + if ($i !== $srcContext) { + $c = new ConstStub('default', $c); + } else { + $c = new ConstStub($c, $stub ? 'in '.$stub->class : ''); + if (null !== $file) { + $c->attr['file'] = $file; + $c->attr['line'] = $line; + } + } + $c->attr['lang'] = $lang; + $srcLines[sprintf("\0~separator=› &%d\0", $i + $line - $srcContext)] = $c; + } + + return new EnumStub($srcLines); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/FiberCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/FiberCaster.php new file mode 100644 index 0000000..c74a9e5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/FiberCaster.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts Fiber related classes to array representation. + * + * @author Grégoire Pineau + */ +final class FiberCaster +{ + public static function castFiber(\Fiber $fiber, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $prefix = Caster::PREFIX_VIRTUAL; + + if ($fiber->isTerminated()) { + $status = 'terminated'; + } elseif ($fiber->isRunning()) { + $status = 'running'; + } elseif ($fiber->isSuspended()) { + $status = 'suspended'; + } elseif ($fiber->isStarted()) { + $status = 'started'; + } else { + $status = 'not started'; + } + + $a[$prefix.'status'] = $status; + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/FrameStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/FrameStub.php new file mode 100644 index 0000000..8786755 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/FrameStub.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\VarDumper\Caster; + +/** + * Represents a single backtrace frame as returned by debug_backtrace() or Exception->getTrace(). + * + * @author Nicolas Grekas + */ +class FrameStub extends EnumStub +{ + public $keepArgs; + public $inTraceStub; + + public function __construct(array $frame, bool $keepArgs = true, bool $inTraceStub = false) + { + $this->value = $frame; + $this->keepArgs = $keepArgs; + $this->inTraceStub = $inTraceStub; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/GmpCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/GmpCaster.php new file mode 100644 index 0000000..b018cc7 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/GmpCaster.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts GMP objects to array representation. + * + * @author Hamza Amrouche + * @author Nicolas Grekas + * + * @final + */ +class GmpCaster +{ + public static function castGmp(\GMP $gmp, array $a, Stub $stub, bool $isNested, int $filter): array + { + $a[Caster::PREFIX_VIRTUAL.'value'] = new ConstStub(gmp_strval($gmp), gmp_strval($gmp)); + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ImagineCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ImagineCaster.php new file mode 100644 index 0000000..d1289da --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ImagineCaster.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\VarDumper\Caster; + +use Imagine\Image\ImageInterface; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Grégoire Pineau + */ +final class ImagineCaster +{ + public static function castImage(ImageInterface $c, array $a, Stub $stub, bool $isNested): array + { + $imgData = $c->get('png'); + if (\strlen($imgData) > 1 * 1000 * 1000) { + $a += [ + Caster::PREFIX_VIRTUAL.'image' => new ConstStub($c->getSize()), + ]; + } else { + $a += [ + Caster::PREFIX_VIRTUAL.'image' => new ImgStub($imgData, 'image/png', $c->getSize()), + ]; + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ImgStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ImgStub.php new file mode 100644 index 0000000..a16681f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ImgStub.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\VarDumper\Caster; + +/** + * @author Grégoire Pineau + */ +class ImgStub extends ConstStub +{ + public function __construct(string $data, string $contentType, string $size = '') + { + $this->value = ''; + $this->attr['img-data'] = $data; + $this->attr['img-size'] = $size; + $this->attr['content-type'] = $contentType; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/IntlCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/IntlCaster.php new file mode 100644 index 0000000..1ed91d4 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/IntlCaster.php @@ -0,0 +1,172 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Nicolas Grekas + * @author Jan Schädlich + * + * @final + */ +class IntlCaster +{ + public static function castMessageFormatter(\MessageFormatter $c, array $a, Stub $stub, bool $isNested) + { + $a += [ + Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(), + Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(), + ]; + + return self::castError($c, $a); + } + + public static function castNumberFormatter(\NumberFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $a += [ + Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(), + Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(), + ]; + + if ($filter & Caster::EXCLUDE_VERBOSE) { + $stub->cut += 3; + + return self::castError($c, $a); + } + + $a += [ + Caster::PREFIX_VIRTUAL.'attributes' => new EnumStub( + [ + 'PARSE_INT_ONLY' => $c->getAttribute(\NumberFormatter::PARSE_INT_ONLY), + 'GROUPING_USED' => $c->getAttribute(\NumberFormatter::GROUPING_USED), + 'DECIMAL_ALWAYS_SHOWN' => $c->getAttribute(\NumberFormatter::DECIMAL_ALWAYS_SHOWN), + 'MAX_INTEGER_DIGITS' => $c->getAttribute(\NumberFormatter::MAX_INTEGER_DIGITS), + 'MIN_INTEGER_DIGITS' => $c->getAttribute(\NumberFormatter::MIN_INTEGER_DIGITS), + 'INTEGER_DIGITS' => $c->getAttribute(\NumberFormatter::INTEGER_DIGITS), + 'MAX_FRACTION_DIGITS' => $c->getAttribute(\NumberFormatter::MAX_FRACTION_DIGITS), + 'MIN_FRACTION_DIGITS' => $c->getAttribute(\NumberFormatter::MIN_FRACTION_DIGITS), + 'FRACTION_DIGITS' => $c->getAttribute(\NumberFormatter::FRACTION_DIGITS), + 'MULTIPLIER' => $c->getAttribute(\NumberFormatter::MULTIPLIER), + 'GROUPING_SIZE' => $c->getAttribute(\NumberFormatter::GROUPING_SIZE), + 'ROUNDING_MODE' => $c->getAttribute(\NumberFormatter::ROUNDING_MODE), + 'ROUNDING_INCREMENT' => $c->getAttribute(\NumberFormatter::ROUNDING_INCREMENT), + 'FORMAT_WIDTH' => $c->getAttribute(\NumberFormatter::FORMAT_WIDTH), + 'PADDING_POSITION' => $c->getAttribute(\NumberFormatter::PADDING_POSITION), + 'SECONDARY_GROUPING_SIZE' => $c->getAttribute(\NumberFormatter::SECONDARY_GROUPING_SIZE), + 'SIGNIFICANT_DIGITS_USED' => $c->getAttribute(\NumberFormatter::SIGNIFICANT_DIGITS_USED), + 'MIN_SIGNIFICANT_DIGITS' => $c->getAttribute(\NumberFormatter::MIN_SIGNIFICANT_DIGITS), + 'MAX_SIGNIFICANT_DIGITS' => $c->getAttribute(\NumberFormatter::MAX_SIGNIFICANT_DIGITS), + 'LENIENT_PARSE' => $c->getAttribute(\NumberFormatter::LENIENT_PARSE), + ] + ), + Caster::PREFIX_VIRTUAL.'text_attributes' => new EnumStub( + [ + 'POSITIVE_PREFIX' => $c->getTextAttribute(\NumberFormatter::POSITIVE_PREFIX), + 'POSITIVE_SUFFIX' => $c->getTextAttribute(\NumberFormatter::POSITIVE_SUFFIX), + 'NEGATIVE_PREFIX' => $c->getTextAttribute(\NumberFormatter::NEGATIVE_PREFIX), + 'NEGATIVE_SUFFIX' => $c->getTextAttribute(\NumberFormatter::NEGATIVE_SUFFIX), + 'PADDING_CHARACTER' => $c->getTextAttribute(\NumberFormatter::PADDING_CHARACTER), + 'CURRENCY_CODE' => $c->getTextAttribute(\NumberFormatter::CURRENCY_CODE), + 'DEFAULT_RULESET' => $c->getTextAttribute(\NumberFormatter::DEFAULT_RULESET), + 'PUBLIC_RULESETS' => $c->getTextAttribute(\NumberFormatter::PUBLIC_RULESETS), + ] + ), + Caster::PREFIX_VIRTUAL.'symbols' => new EnumStub( + [ + 'DECIMAL_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL), + 'GROUPING_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL), + 'PATTERN_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::PATTERN_SEPARATOR_SYMBOL), + 'PERCENT_SYMBOL' => $c->getSymbol(\NumberFormatter::PERCENT_SYMBOL), + 'ZERO_DIGIT_SYMBOL' => $c->getSymbol(\NumberFormatter::ZERO_DIGIT_SYMBOL), + 'DIGIT_SYMBOL' => $c->getSymbol(\NumberFormatter::DIGIT_SYMBOL), + 'MINUS_SIGN_SYMBOL' => $c->getSymbol(\NumberFormatter::MINUS_SIGN_SYMBOL), + 'PLUS_SIGN_SYMBOL' => $c->getSymbol(\NumberFormatter::PLUS_SIGN_SYMBOL), + 'CURRENCY_SYMBOL' => $c->getSymbol(\NumberFormatter::CURRENCY_SYMBOL), + 'INTL_CURRENCY_SYMBOL' => $c->getSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL), + 'MONETARY_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL), + 'EXPONENTIAL_SYMBOL' => $c->getSymbol(\NumberFormatter::EXPONENTIAL_SYMBOL), + 'PERMILL_SYMBOL' => $c->getSymbol(\NumberFormatter::PERMILL_SYMBOL), + 'PAD_ESCAPE_SYMBOL' => $c->getSymbol(\NumberFormatter::PAD_ESCAPE_SYMBOL), + 'INFINITY_SYMBOL' => $c->getSymbol(\NumberFormatter::INFINITY_SYMBOL), + 'NAN_SYMBOL' => $c->getSymbol(\NumberFormatter::NAN_SYMBOL), + 'SIGNIFICANT_DIGIT_SYMBOL' => $c->getSymbol(\NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL), + 'MONETARY_GROUPING_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL), + ] + ), + ]; + + return self::castError($c, $a); + } + + public static function castIntlTimeZone(\IntlTimeZone $c, array $a, Stub $stub, bool $isNested) + { + $a += [ + Caster::PREFIX_VIRTUAL.'display_name' => $c->getDisplayName(), + Caster::PREFIX_VIRTUAL.'id' => $c->getID(), + Caster::PREFIX_VIRTUAL.'raw_offset' => $c->getRawOffset(), + ]; + + if ($c->useDaylightTime()) { + $a += [ + Caster::PREFIX_VIRTUAL.'dst_savings' => $c->getDSTSavings(), + ]; + } + + return self::castError($c, $a); + } + + public static function castIntlCalendar(\IntlCalendar $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $a += [ + Caster::PREFIX_VIRTUAL.'type' => $c->getType(), + Caster::PREFIX_VIRTUAL.'first_day_of_week' => $c->getFirstDayOfWeek(), + Caster::PREFIX_VIRTUAL.'minimal_days_in_first_week' => $c->getMinimalDaysInFirstWeek(), + Caster::PREFIX_VIRTUAL.'repeated_wall_time_option' => $c->getRepeatedWallTimeOption(), + Caster::PREFIX_VIRTUAL.'skipped_wall_time_option' => $c->getSkippedWallTimeOption(), + Caster::PREFIX_VIRTUAL.'time' => $c->getTime(), + Caster::PREFIX_VIRTUAL.'in_daylight_time' => $c->inDaylightTime(), + Caster::PREFIX_VIRTUAL.'is_lenient' => $c->isLenient(), + Caster::PREFIX_VIRTUAL.'time_zone' => ($filter & Caster::EXCLUDE_VERBOSE) ? new CutStub($c->getTimeZone()) : $c->getTimeZone(), + ]; + + return self::castError($c, $a); + } + + public static function castIntlDateFormatter(\IntlDateFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $a += [ + Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(), + Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(), + Caster::PREFIX_VIRTUAL.'calendar' => $c->getCalendar(), + Caster::PREFIX_VIRTUAL.'time_zone_id' => $c->getTimeZoneId(), + Caster::PREFIX_VIRTUAL.'time_type' => $c->getTimeType(), + Caster::PREFIX_VIRTUAL.'date_type' => $c->getDateType(), + Caster::PREFIX_VIRTUAL.'calendar_object' => ($filter & Caster::EXCLUDE_VERBOSE) ? new CutStub($c->getCalendarObject()) : $c->getCalendarObject(), + Caster::PREFIX_VIRTUAL.'time_zone' => ($filter & Caster::EXCLUDE_VERBOSE) ? new CutStub($c->getTimeZone()) : $c->getTimeZone(), + ]; + + return self::castError($c, $a); + } + + private static function castError(object $c, array $a): array + { + if ($errorCode = $c->getErrorCode()) { + $a += [ + Caster::PREFIX_VIRTUAL.'error_code' => $errorCode, + Caster::PREFIX_VIRTUAL.'error_message' => $c->getErrorMessage(), + ]; + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/LinkStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/LinkStub.php new file mode 100644 index 0000000..bd4c796 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/LinkStub.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +/** + * Represents a file or a URL. + * + * @author Nicolas Grekas + */ +class LinkStub extends ConstStub +{ + public $inVendor = false; + + private static $vendorRoots; + private static $composerRoots; + + public function __construct(string $label, int $line = 0, ?string $href = null) + { + $this->value = $label; + + if (null === $href) { + $href = $label; + } + if (!\is_string($href)) { + return; + } + if (str_starts_with($href, 'file://')) { + if ($href === $label) { + $label = substr($label, 7); + } + $href = substr($href, 7); + } elseif (str_contains($href, '://')) { + $this->attr['href'] = $href; + + return; + } + if (!is_file($href)) { + return; + } + if ($line) { + $this->attr['line'] = $line; + } + if ($label !== $this->attr['file'] = realpath($href) ?: $href) { + return; + } + if ($composerRoot = $this->getComposerRoot($href, $this->inVendor)) { + $this->attr['ellipsis'] = \strlen($href) - \strlen($composerRoot) + 1; + $this->attr['ellipsis-type'] = 'path'; + $this->attr['ellipsis-tail'] = 1 + ($this->inVendor ? 2 + \strlen(implode('', \array_slice(explode(\DIRECTORY_SEPARATOR, substr($href, 1 - $this->attr['ellipsis'])), 0, 2))) : 0); + } elseif (3 < \count($ellipsis = explode(\DIRECTORY_SEPARATOR, $href))) { + $this->attr['ellipsis'] = 2 + \strlen(implode('', \array_slice($ellipsis, -2))); + $this->attr['ellipsis-type'] = 'path'; + $this->attr['ellipsis-tail'] = 1; + } + } + + private function getComposerRoot(string $file, bool &$inVendor) + { + if (null === self::$vendorRoots) { + self::$vendorRoots = []; + + foreach (get_declared_classes() as $class) { + if ('C' === $class[0] && str_starts_with($class, 'ComposerAutoloaderInit')) { + $r = new \ReflectionClass($class); + $v = \dirname($r->getFileName(), 2); + if (is_file($v.'/composer/installed.json')) { + self::$vendorRoots[] = $v.\DIRECTORY_SEPARATOR; + } + } + } + } + $inVendor = false; + + if (isset(self::$composerRoots[$dir = \dirname($file)])) { + return self::$composerRoots[$dir]; + } + + foreach (self::$vendorRoots as $root) { + if ($inVendor = str_starts_with($file, $root)) { + return $root; + } + } + + $parent = $dir; + while (!@is_file($parent.'/composer.json')) { + if (!@file_exists($parent)) { + // open_basedir restriction in effect + break; + } + if ($parent === \dirname($parent)) { + return self::$composerRoots[$dir] = false; + } + + $parent = \dirname($parent); + } + + return self::$composerRoots[$dir] = $parent.\DIRECTORY_SEPARATOR; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/MemcachedCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/MemcachedCaster.php new file mode 100644 index 0000000..cfef19a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/MemcachedCaster.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\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Jan Schädlich + * + * @final + */ +class MemcachedCaster +{ + private static $optionConstants; + private static $defaultOptions; + + public static function castMemcached(\Memcached $c, array $a, Stub $stub, bool $isNested) + { + $a += [ + Caster::PREFIX_VIRTUAL.'servers' => $c->getServerList(), + Caster::PREFIX_VIRTUAL.'options' => new EnumStub( + self::getNonDefaultOptions($c) + ), + ]; + + return $a; + } + + private static function getNonDefaultOptions(\Memcached $c): array + { + self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions(); + self::$optionConstants = self::$optionConstants ?? self::getOptionConstants(); + + $nonDefaultOptions = []; + foreach (self::$optionConstants as $constantKey => $value) { + if (self::$defaultOptions[$constantKey] !== $option = $c->getOption($value)) { + $nonDefaultOptions[$constantKey] = $option; + } + } + + return $nonDefaultOptions; + } + + private static function discoverDefaultOptions(): array + { + $defaultMemcached = new \Memcached(); + $defaultMemcached->addServer('127.0.0.1', 11211); + + $defaultOptions = []; + self::$optionConstants = self::$optionConstants ?? self::getOptionConstants(); + + foreach (self::$optionConstants as $constantKey => $value) { + $defaultOptions[$constantKey] = $defaultMemcached->getOption($value); + } + + return $defaultOptions; + } + + private static function getOptionConstants(): array + { + $reflectedMemcached = new \ReflectionClass(\Memcached::class); + + $optionConstants = []; + foreach ($reflectedMemcached->getConstants() as $constantKey => $value) { + if (str_starts_with($constantKey, 'OPT_')) { + $optionConstants[$constantKey] = $value; + } + } + + return $optionConstants; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/MysqliCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/MysqliCaster.php new file mode 100644 index 0000000..bfe6f08 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/MysqliCaster.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\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Nicolas Grekas + * + * @internal + */ +final class MysqliCaster +{ + public static function castMysqliDriver(\mysqli_driver $c, array $a, Stub $stub, bool $isNested): array + { + foreach ($a as $k => $v) { + if (isset($c->$k)) { + $a[$k] = $c->$k; + } + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/PdoCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/PdoCaster.php new file mode 100644 index 0000000..140473b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/PdoCaster.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 Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts PDO related classes to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class PdoCaster +{ + private const PDO_ATTRIBUTES = [ + 'CASE' => [ + \PDO::CASE_LOWER => 'LOWER', + \PDO::CASE_NATURAL => 'NATURAL', + \PDO::CASE_UPPER => 'UPPER', + ], + 'ERRMODE' => [ + \PDO::ERRMODE_SILENT => 'SILENT', + \PDO::ERRMODE_WARNING => 'WARNING', + \PDO::ERRMODE_EXCEPTION => 'EXCEPTION', + ], + 'TIMEOUT', + 'PREFETCH', + 'AUTOCOMMIT', + 'PERSISTENT', + 'DRIVER_NAME', + 'SERVER_INFO', + 'ORACLE_NULLS' => [ + \PDO::NULL_NATURAL => 'NATURAL', + \PDO::NULL_EMPTY_STRING => 'EMPTY_STRING', + \PDO::NULL_TO_STRING => 'TO_STRING', + ], + 'CLIENT_VERSION', + 'SERVER_VERSION', + 'STATEMENT_CLASS', + 'EMULATE_PREPARES', + 'CONNECTION_STATUS', + 'STRINGIFY_FETCHES', + 'DEFAULT_FETCH_MODE' => [ + \PDO::FETCH_ASSOC => 'ASSOC', + \PDO::FETCH_BOTH => 'BOTH', + \PDO::FETCH_LAZY => 'LAZY', + \PDO::FETCH_NUM => 'NUM', + \PDO::FETCH_OBJ => 'OBJ', + ], + ]; + + public static function castPdo(\PDO $c, array $a, Stub $stub, bool $isNested) + { + $attr = []; + $errmode = $c->getAttribute(\PDO::ATTR_ERRMODE); + $c->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + + foreach (self::PDO_ATTRIBUTES as $k => $v) { + if (!isset($k[0])) { + $k = $v; + $v = []; + } + + try { + $attr[$k] = 'ERRMODE' === $k ? $errmode : $c->getAttribute(\constant('PDO::ATTR_'.$k)); + if ($v && isset($v[$attr[$k]])) { + $attr[$k] = new ConstStub($v[$attr[$k]], $attr[$k]); + } + } catch (\Exception $e) { + } + } + if (isset($attr[$k = 'STATEMENT_CLASS'][1])) { + if ($attr[$k][1]) { + $attr[$k][1] = new ArgsStub($attr[$k][1], '__construct', $attr[$k][0]); + } + $attr[$k][0] = new ClassStub($attr[$k][0]); + } + + $prefix = Caster::PREFIX_VIRTUAL; + $a += [ + $prefix.'inTransaction' => method_exists($c, 'inTransaction'), + $prefix.'errorInfo' => $c->errorInfo(), + $prefix.'attributes' => new EnumStub($attr), + ]; + + if ($a[$prefix.'inTransaction']) { + $a[$prefix.'inTransaction'] = $c->inTransaction(); + } else { + unset($a[$prefix.'inTransaction']); + } + + if (!isset($a[$prefix.'errorInfo'][1], $a[$prefix.'errorInfo'][2])) { + unset($a[$prefix.'errorInfo']); + } + + $c->setAttribute(\PDO::ATTR_ERRMODE, $errmode); + + return $a; + } + + public static function castPdoStatement(\PDOStatement $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + $a[$prefix.'errorInfo'] = $c->errorInfo(); + + if (!isset($a[$prefix.'errorInfo'][1], $a[$prefix.'errorInfo'][2])) { + unset($a[$prefix.'errorInfo']); + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/PgSqlCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/PgSqlCaster.php new file mode 100644 index 0000000..d8e5b52 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/PgSqlCaster.php @@ -0,0 +1,156 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts pqsql resources to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class PgSqlCaster +{ + private const PARAM_CODES = [ + 'server_encoding', + 'client_encoding', + 'is_superuser', + 'session_authorization', + 'DateStyle', + 'TimeZone', + 'IntervalStyle', + 'integer_datetimes', + 'application_name', + 'standard_conforming_strings', + ]; + + private const TRANSACTION_STATUS = [ + \PGSQL_TRANSACTION_IDLE => 'PGSQL_TRANSACTION_IDLE', + \PGSQL_TRANSACTION_ACTIVE => 'PGSQL_TRANSACTION_ACTIVE', + \PGSQL_TRANSACTION_INTRANS => 'PGSQL_TRANSACTION_INTRANS', + \PGSQL_TRANSACTION_INERROR => 'PGSQL_TRANSACTION_INERROR', + \PGSQL_TRANSACTION_UNKNOWN => 'PGSQL_TRANSACTION_UNKNOWN', + ]; + + private const RESULT_STATUS = [ + \PGSQL_EMPTY_QUERY => 'PGSQL_EMPTY_QUERY', + \PGSQL_COMMAND_OK => 'PGSQL_COMMAND_OK', + \PGSQL_TUPLES_OK => 'PGSQL_TUPLES_OK', + \PGSQL_COPY_OUT => 'PGSQL_COPY_OUT', + \PGSQL_COPY_IN => 'PGSQL_COPY_IN', + \PGSQL_BAD_RESPONSE => 'PGSQL_BAD_RESPONSE', + \PGSQL_NONFATAL_ERROR => 'PGSQL_NONFATAL_ERROR', + \PGSQL_FATAL_ERROR => 'PGSQL_FATAL_ERROR', + ]; + + private const DIAG_CODES = [ + 'severity' => \PGSQL_DIAG_SEVERITY, + 'sqlstate' => \PGSQL_DIAG_SQLSTATE, + 'message' => \PGSQL_DIAG_MESSAGE_PRIMARY, + 'detail' => \PGSQL_DIAG_MESSAGE_DETAIL, + 'hint' => \PGSQL_DIAG_MESSAGE_HINT, + 'statement position' => \PGSQL_DIAG_STATEMENT_POSITION, + 'internal position' => \PGSQL_DIAG_INTERNAL_POSITION, + 'internal query' => \PGSQL_DIAG_INTERNAL_QUERY, + 'context' => \PGSQL_DIAG_CONTEXT, + 'file' => \PGSQL_DIAG_SOURCE_FILE, + 'line' => \PGSQL_DIAG_SOURCE_LINE, + 'function' => \PGSQL_DIAG_SOURCE_FUNCTION, + ]; + + public static function castLargeObject($lo, array $a, Stub $stub, bool $isNested) + { + $a['seek position'] = pg_lo_tell($lo); + + return $a; + } + + public static function castLink($link, array $a, Stub $stub, bool $isNested) + { + $a['status'] = pg_connection_status($link); + $a['status'] = new ConstStub(\PGSQL_CONNECTION_OK === $a['status'] ? 'PGSQL_CONNECTION_OK' : 'PGSQL_CONNECTION_BAD', $a['status']); + $a['busy'] = pg_connection_busy($link); + + $a['transaction'] = pg_transaction_status($link); + if (isset(self::TRANSACTION_STATUS[$a['transaction']])) { + $a['transaction'] = new ConstStub(self::TRANSACTION_STATUS[$a['transaction']], $a['transaction']); + } + + $a['pid'] = pg_get_pid($link); + $a['last error'] = pg_last_error($link); + $a['last notice'] = pg_last_notice($link); + $a['host'] = pg_host($link); + $a['port'] = pg_port($link); + $a['dbname'] = pg_dbname($link); + $a['options'] = pg_options($link); + $a['version'] = pg_version($link); + + foreach (self::PARAM_CODES as $v) { + if (false !== $s = pg_parameter_status($link, $v)) { + $a['param'][$v] = $s; + } + } + + $a['param']['client_encoding'] = pg_client_encoding($link); + $a['param'] = new EnumStub($a['param']); + + return $a; + } + + public static function castResult($result, array $a, Stub $stub, bool $isNested) + { + $a['num rows'] = pg_num_rows($result); + $a['status'] = pg_result_status($result); + if (isset(self::RESULT_STATUS[$a['status']])) { + $a['status'] = new ConstStub(self::RESULT_STATUS[$a['status']], $a['status']); + } + $a['command-completion tag'] = pg_result_status($result, \PGSQL_STATUS_STRING); + + if (-1 === $a['num rows']) { + foreach (self::DIAG_CODES as $k => $v) { + $a['error'][$k] = pg_result_error_field($result, $v); + } + } + + $a['affected rows'] = pg_affected_rows($result); + $a['last OID'] = pg_last_oid($result); + + $fields = pg_num_fields($result); + + for ($i = 0; $i < $fields; ++$i) { + $field = [ + 'name' => pg_field_name($result, $i), + 'table' => sprintf('%s (OID: %s)', pg_field_table($result, $i), pg_field_table($result, $i, true)), + 'type' => sprintf('%s (OID: %s)', pg_field_type($result, $i), pg_field_type_oid($result, $i)), + 'nullable' => (bool) pg_field_is_null($result, $i), + 'storage' => pg_field_size($result, $i).' bytes', + 'display' => pg_field_prtlen($result, $i).' chars', + ]; + if (' (OID: )' === $field['table']) { + $field['table'] = null; + } + if ('-1 bytes' === $field['storage']) { + $field['storage'] = 'variable size'; + } elseif ('1 bytes' === $field['storage']) { + $field['storage'] = '1 byte'; + } + if ('1 chars' === $field['display']) { + $field['display'] = '1 char'; + } + $a['fields'][] = new EnumStub($field); + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.php new file mode 100644 index 0000000..e712019 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.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\VarDumper\Caster; + +use ProxyManager\Proxy\ProxyInterface; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Nicolas Grekas + * + * @final + */ +class ProxyManagerCaster +{ + public static function castProxy(ProxyInterface $c, array $a, Stub $stub, bool $isNested) + { + if ($parent = get_parent_class($c)) { + $stub->class .= ' - '.$parent; + } + $stub->class .= '@proxy'; + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php new file mode 100644 index 0000000..db4bba8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php @@ -0,0 +1,186 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use RdKafka\Conf; +use RdKafka\Exception as RdKafkaException; +use RdKafka\KafkaConsumer; +use RdKafka\Message; +use RdKafka\Metadata\Broker as BrokerMetadata; +use RdKafka\Metadata\Collection as CollectionMetadata; +use RdKafka\Metadata\Partition as PartitionMetadata; +use RdKafka\Metadata\Topic as TopicMetadata; +use RdKafka\Topic; +use RdKafka\TopicConf; +use RdKafka\TopicPartition; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts RdKafka related classes to array representation. + * + * @author Romain Neutron + */ +class RdKafkaCaster +{ + public static function castKafkaConsumer(KafkaConsumer $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + try { + $assignment = $c->getAssignment(); + } catch (RdKafkaException $e) { + $assignment = []; + } + + $a += [ + $prefix.'subscription' => $c->getSubscription(), + $prefix.'assignment' => $assignment, + ]; + + $a += self::extractMetadata($c); + + return $a; + } + + public static function castTopic(Topic $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'name' => $c->getName(), + ]; + + return $a; + } + + public static function castTopicPartition(TopicPartition $c, array $a) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'offset' => $c->getOffset(), + $prefix.'partition' => $c->getPartition(), + $prefix.'topic' => $c->getTopic(), + ]; + + return $a; + } + + public static function castMessage(Message $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'errstr' => $c->errstr(), + ]; + + return $a; + } + + public static function castConf(Conf $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + foreach ($c->dump() as $key => $value) { + $a[$prefix.$key] = $value; + } + + return $a; + } + + public static function castTopicConf(TopicConf $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + foreach ($c->dump() as $key => $value) { + $a[$prefix.$key] = $value; + } + + return $a; + } + + public static function castRdKafka(\RdKafka $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'out_q_len' => $c->getOutQLen(), + ]; + + $a += self::extractMetadata($c); + + return $a; + } + + public static function castCollectionMetadata(CollectionMetadata $c, array $a, Stub $stub, bool $isNested) + { + $a += iterator_to_array($c); + + return $a; + } + + public static function castTopicMetadata(TopicMetadata $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'name' => $c->getTopic(), + $prefix.'partitions' => $c->getPartitions(), + ]; + + return $a; + } + + public static function castPartitionMetadata(PartitionMetadata $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'id' => $c->getId(), + $prefix.'err' => $c->getErr(), + $prefix.'leader' => $c->getLeader(), + ]; + + return $a; + } + + public static function castBrokerMetadata(BrokerMetadata $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + $a += [ + $prefix.'id' => $c->getId(), + $prefix.'host' => $c->getHost(), + $prefix.'port' => $c->getPort(), + ]; + + return $a; + } + + private static function extractMetadata($c) + { + $prefix = Caster::PREFIX_VIRTUAL; + + try { + $m = $c->getMetadata(true, null, 500); + } catch (RdKafkaException $e) { + return []; + } + + return [ + $prefix.'orig_broker_id' => $m->getOrigBrokerId(), + $prefix.'orig_broker_name' => $m->getOrigBrokerName(), + $prefix.'brokers' => $m->getBrokers(), + $prefix.'topics' => $m->getTopics(), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/RedisCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/RedisCaster.php new file mode 100644 index 0000000..8f97eaa --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/RedisCaster.php @@ -0,0 +1,152 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts Redis class from ext-redis to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class RedisCaster +{ + private const SERIALIZERS = [ + \Redis::SERIALIZER_NONE => 'NONE', + \Redis::SERIALIZER_PHP => 'PHP', + 2 => 'IGBINARY', // Optional Redis::SERIALIZER_IGBINARY + ]; + + private const MODES = [ + \Redis::ATOMIC => 'ATOMIC', + \Redis::MULTI => 'MULTI', + \Redis::PIPELINE => 'PIPELINE', + ]; + + private const COMPRESSION_MODES = [ + 0 => 'NONE', // Redis::COMPRESSION_NONE + 1 => 'LZF', // Redis::COMPRESSION_LZF + ]; + + private const FAILOVER_OPTIONS = [ + \RedisCluster::FAILOVER_NONE => 'NONE', + \RedisCluster::FAILOVER_ERROR => 'ERROR', + \RedisCluster::FAILOVER_DISTRIBUTE => 'DISTRIBUTE', + \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES => 'DISTRIBUTE_SLAVES', + ]; + + public static function castRedis(\Redis $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + if (!$connected = $c->isConnected()) { + return $a + [ + $prefix.'isConnected' => $connected, + ]; + } + + $mode = $c->getMode(); + + return $a + [ + $prefix.'isConnected' => $connected, + $prefix.'host' => $c->getHost(), + $prefix.'port' => $c->getPort(), + $prefix.'auth' => $c->getAuth(), + $prefix.'mode' => isset(self::MODES[$mode]) ? new ConstStub(self::MODES[$mode], $mode) : $mode, + $prefix.'dbNum' => $c->getDbNum(), + $prefix.'timeout' => $c->getTimeout(), + $prefix.'lastError' => $c->getLastError(), + $prefix.'persistentId' => $c->getPersistentID(), + $prefix.'options' => self::getRedisOptions($c), + ]; + } + + public static function castRedisArray(\RedisArray $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + return $a + [ + $prefix.'hosts' => $c->_hosts(), + $prefix.'function' => ClassStub::wrapCallable($c->_function()), + $prefix.'lastError' => $c->getLastError(), + $prefix.'options' => self::getRedisOptions($c), + ]; + } + + public static function castRedisCluster(\RedisCluster $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + $failover = $c->getOption(\RedisCluster::OPT_SLAVE_FAILOVER); + + $a += [ + $prefix.'_masters' => $c->_masters(), + $prefix.'_redir' => $c->_redir(), + $prefix.'mode' => new ConstStub($c->getMode() ? 'MULTI' : 'ATOMIC', $c->getMode()), + $prefix.'lastError' => $c->getLastError(), + $prefix.'options' => self::getRedisOptions($c, [ + 'SLAVE_FAILOVER' => isset(self::FAILOVER_OPTIONS[$failover]) ? new ConstStub(self::FAILOVER_OPTIONS[$failover], $failover) : $failover, + ]), + ]; + + return $a; + } + + /** + * @param \Redis|\RedisArray|\RedisCluster $redis + */ + private static function getRedisOptions($redis, array $options = []): EnumStub + { + $serializer = $redis->getOption(\Redis::OPT_SERIALIZER); + if (\is_array($serializer)) { + foreach ($serializer as &$v) { + if (isset(self::SERIALIZERS[$v])) { + $v = new ConstStub(self::SERIALIZERS[$v], $v); + } + } + } elseif (isset(self::SERIALIZERS[$serializer])) { + $serializer = new ConstStub(self::SERIALIZERS[$serializer], $serializer); + } + + $compression = \defined('Redis::OPT_COMPRESSION') ? $redis->getOption(\Redis::OPT_COMPRESSION) : 0; + if (\is_array($compression)) { + foreach ($compression as &$v) { + if (isset(self::COMPRESSION_MODES[$v])) { + $v = new ConstStub(self::COMPRESSION_MODES[$v], $v); + } + } + } elseif (isset(self::COMPRESSION_MODES[$compression])) { + $compression = new ConstStub(self::COMPRESSION_MODES[$compression], $compression); + } + + $retry = \defined('Redis::OPT_SCAN') ? $redis->getOption(\Redis::OPT_SCAN) : 0; + if (\is_array($retry)) { + foreach ($retry as &$v) { + $v = new ConstStub($v ? 'RETRY' : 'NORETRY', $v); + } + } else { + $retry = new ConstStub($retry ? 'RETRY' : 'NORETRY', $retry); + } + + $options += [ + 'TCP_KEEPALIVE' => \defined('Redis::OPT_TCP_KEEPALIVE') ? $redis->getOption(\Redis::OPT_TCP_KEEPALIVE) : 0, + 'READ_TIMEOUT' => $redis->getOption(\Redis::OPT_READ_TIMEOUT), + 'COMPRESSION' => $compression, + 'SERIALIZER' => $serializer, + 'PREFIX' => $redis->getOption(\Redis::OPT_PREFIX), + 'SCAN' => $retry, + ]; + + return new EnumStub($options); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ReflectionCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ReflectionCaster.php new file mode 100644 index 0000000..ef6a85e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ReflectionCaster.php @@ -0,0 +1,442 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts Reflector related classes to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class ReflectionCaster +{ + public const UNSET_CLOSURE_FILE_INFO = ['Closure' => __CLASS__.'::unsetClosureFileInfo']; + + private const EXTRA_MAP = [ + 'docComment' => 'getDocComment', + 'extension' => 'getExtensionName', + 'isDisabled' => 'isDisabled', + 'isDeprecated' => 'isDeprecated', + 'isInternal' => 'isInternal', + 'isUserDefined' => 'isUserDefined', + 'isGenerator' => 'isGenerator', + 'isVariadic' => 'isVariadic', + ]; + + public static function castClosure(\Closure $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $prefix = Caster::PREFIX_VIRTUAL; + $c = new \ReflectionFunction($c); + + $a = static::castFunctionAbstract($c, $a, $stub, $isNested, $filter); + + if (!str_contains($c->name, '{closure}')) { + $stub->class = isset($a[$prefix.'class']) ? $a[$prefix.'class']->value.'::'.$c->name : $c->name; + unset($a[$prefix.'class']); + } + unset($a[$prefix.'extra']); + + $stub->class .= self::getSignature($a); + + if ($f = $c->getFileName()) { + $stub->attr['file'] = $f; + $stub->attr['line'] = $c->getStartLine(); + } + + unset($a[$prefix.'parameters']); + + if ($filter & Caster::EXCLUDE_VERBOSE) { + $stub->cut += ($c->getFileName() ? 2 : 0) + \count($a); + + return []; + } + + if ($f) { + $a[$prefix.'file'] = new LinkStub($f, $c->getStartLine()); + $a[$prefix.'line'] = $c->getStartLine().' to '.$c->getEndLine(); + } + + return $a; + } + + public static function unsetClosureFileInfo(\Closure $c, array $a) + { + unset($a[Caster::PREFIX_VIRTUAL.'file'], $a[Caster::PREFIX_VIRTUAL.'line']); + + return $a; + } + + public static function castGenerator(\Generator $c, array $a, Stub $stub, bool $isNested) + { + // Cannot create ReflectionGenerator based on a terminated Generator + try { + $reflectionGenerator = new \ReflectionGenerator($c); + } catch (\Exception $e) { + $a[Caster::PREFIX_VIRTUAL.'closed'] = true; + + return $a; + } + + return self::castReflectionGenerator($reflectionGenerator, $a, $stub, $isNested); + } + + public static function castType(\ReflectionType $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + if ($c instanceof \ReflectionNamedType || \PHP_VERSION_ID < 80000) { + $a += [ + $prefix.'name' => $c instanceof \ReflectionNamedType ? $c->getName() : (string) $c, + $prefix.'allowsNull' => $c->allowsNull(), + $prefix.'isBuiltin' => $c->isBuiltin(), + ]; + } elseif ($c instanceof \ReflectionUnionType || $c instanceof \ReflectionIntersectionType) { + $a[$prefix.'allowsNull'] = $c->allowsNull(); + self::addMap($a, $c, [ + 'types' => 'getTypes', + ]); + } else { + $a[$prefix.'allowsNull'] = $c->allowsNull(); + } + + return $a; + } + + public static function castAttribute(\ReflectionAttribute $c, array $a, Stub $stub, bool $isNested) + { + self::addMap($a, $c, [ + 'name' => 'getName', + 'arguments' => 'getArguments', + ]); + + return $a; + } + + public static function castReflectionGenerator(\ReflectionGenerator $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + if ($c->getThis()) { + $a[$prefix.'this'] = new CutStub($c->getThis()); + } + $function = $c->getFunction(); + $frame = [ + 'class' => $function->class ?? null, + 'type' => isset($function->class) ? ($function->isStatic() ? '::' : '->') : null, + 'function' => $function->name, + 'file' => $c->getExecutingFile(), + 'line' => $c->getExecutingLine(), + ]; + if ($trace = $c->getTrace(\DEBUG_BACKTRACE_IGNORE_ARGS)) { + $function = new \ReflectionGenerator($c->getExecutingGenerator()); + array_unshift($trace, [ + 'function' => 'yield', + 'file' => $function->getExecutingFile(), + 'line' => $function->getExecutingLine() - (int) (\PHP_VERSION_ID < 80100), + ]); + $trace[] = $frame; + $a[$prefix.'trace'] = new TraceStub($trace, false, 0, -1, -1); + } else { + $function = new FrameStub($frame, false, true); + $function = ExceptionCaster::castFrameStub($function, [], $function, true); + $a[$prefix.'executing'] = $function[$prefix.'src']; + } + + $a[Caster::PREFIX_VIRTUAL.'closed'] = false; + + return $a; + } + + public static function castClass(\ReflectionClass $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $prefix = Caster::PREFIX_VIRTUAL; + + if ($n = \Reflection::getModifierNames($c->getModifiers())) { + $a[$prefix.'modifiers'] = implode(' ', $n); + } + + self::addMap($a, $c, [ + 'extends' => 'getParentClass', + 'implements' => 'getInterfaceNames', + 'constants' => 'getReflectionConstants', + ]); + + foreach ($c->getProperties() as $n) { + $a[$prefix.'properties'][$n->name] = $n; + } + + foreach ($c->getMethods() as $n) { + $a[$prefix.'methods'][$n->name] = $n; + } + + self::addAttributes($a, $c, $prefix); + + if (!($filter & Caster::EXCLUDE_VERBOSE) && !$isNested) { + self::addExtra($a, $c); + } + + return $a; + } + + public static function castFunctionAbstract(\ReflectionFunctionAbstract $c, array $a, Stub $stub, bool $isNested, int $filter = 0) + { + $prefix = Caster::PREFIX_VIRTUAL; + + self::addMap($a, $c, [ + 'returnsReference' => 'returnsReference', + 'returnType' => 'getReturnType', + 'class' => \PHP_VERSION_ID >= 80111 ? 'getClosureCalledClass' : 'getClosureScopeClass', + 'this' => 'getClosureThis', + ]); + + if (isset($a[$prefix.'returnType'])) { + $v = $a[$prefix.'returnType']; + $v = $v instanceof \ReflectionNamedType ? $v->getName() : (string) $v; + $a[$prefix.'returnType'] = new ClassStub($a[$prefix.'returnType'] instanceof \ReflectionNamedType && $a[$prefix.'returnType']->allowsNull() && 'mixed' !== $v ? '?'.$v : $v, [class_exists($v, false) || interface_exists($v, false) || trait_exists($v, false) ? $v : '', '']); + } + if (isset($a[$prefix.'class'])) { + $a[$prefix.'class'] = new ClassStub($a[$prefix.'class']); + } + if (isset($a[$prefix.'this'])) { + $a[$prefix.'this'] = new CutStub($a[$prefix.'this']); + } + + foreach ($c->getParameters() as $v) { + $k = '$'.$v->name; + if ($v->isVariadic()) { + $k = '...'.$k; + } + if ($v->isPassedByReference()) { + $k = '&'.$k; + } + $a[$prefix.'parameters'][$k] = $v; + } + if (isset($a[$prefix.'parameters'])) { + $a[$prefix.'parameters'] = new EnumStub($a[$prefix.'parameters']); + } + + self::addAttributes($a, $c, $prefix); + + if (!($filter & Caster::EXCLUDE_VERBOSE) && $v = $c->getStaticVariables()) { + foreach ($v as $k => &$v) { + if (\is_object($v)) { + $a[$prefix.'use']['$'.$k] = new CutStub($v); + } else { + $a[$prefix.'use']['$'.$k] = &$v; + } + } + unset($v); + $a[$prefix.'use'] = new EnumStub($a[$prefix.'use']); + } + + if (!($filter & Caster::EXCLUDE_VERBOSE) && !$isNested) { + self::addExtra($a, $c); + } + + return $a; + } + + public static function castClassConstant(\ReflectionClassConstant $c, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers())); + $a[Caster::PREFIX_VIRTUAL.'value'] = $c->getValue(); + + self::addAttributes($a, $c); + + return $a; + } + + public static function castMethod(\ReflectionMethod $c, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers())); + + return $a; + } + + public static function castParameter(\ReflectionParameter $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + + self::addMap($a, $c, [ + 'position' => 'getPosition', + 'isVariadic' => 'isVariadic', + 'byReference' => 'isPassedByReference', + 'allowsNull' => 'allowsNull', + ]); + + self::addAttributes($a, $c, $prefix); + + if ($v = $c->getType()) { + $a[$prefix.'typeHint'] = $v instanceof \ReflectionNamedType ? $v->getName() : (string) $v; + } + + if (isset($a[$prefix.'typeHint'])) { + $v = $a[$prefix.'typeHint']; + $a[$prefix.'typeHint'] = new ClassStub($v, [class_exists($v, false) || interface_exists($v, false) || trait_exists($v, false) ? $v : '', '']); + } else { + unset($a[$prefix.'allowsNull']); + } + + if ($c->isOptional()) { + try { + $a[$prefix.'default'] = $v = $c->getDefaultValue(); + if ($c->isDefaultValueConstant() && !\is_object($v)) { + $a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName(), $v); + } + if (null === $v) { + unset($a[$prefix.'allowsNull']); + } + } catch (\ReflectionException $e) { + } + } + + return $a; + } + + public static function castProperty(\ReflectionProperty $c, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers())); + + self::addAttributes($a, $c); + self::addExtra($a, $c); + + return $a; + } + + public static function castReference(\ReflectionReference $c, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'id'] = $c->getId(); + + return $a; + } + + public static function castExtension(\ReflectionExtension $c, array $a, Stub $stub, bool $isNested) + { + self::addMap($a, $c, [ + 'version' => 'getVersion', + 'dependencies' => 'getDependencies', + 'iniEntries' => 'getIniEntries', + 'isPersistent' => 'isPersistent', + 'isTemporary' => 'isTemporary', + 'constants' => 'getConstants', + 'functions' => 'getFunctions', + 'classes' => 'getClasses', + ]); + + return $a; + } + + public static function castZendExtension(\ReflectionZendExtension $c, array $a, Stub $stub, bool $isNested) + { + self::addMap($a, $c, [ + 'version' => 'getVersion', + 'author' => 'getAuthor', + 'copyright' => 'getCopyright', + 'url' => 'getURL', + ]); + + return $a; + } + + public static function getSignature(array $a) + { + $prefix = Caster::PREFIX_VIRTUAL; + $signature = ''; + + if (isset($a[$prefix.'parameters'])) { + foreach ($a[$prefix.'parameters']->value as $k => $param) { + $signature .= ', '; + if ($type = $param->getType()) { + if (!$type instanceof \ReflectionNamedType) { + $signature .= $type.' '; + } else { + if (!$param->isOptional() && $param->allowsNull() && 'mixed' !== $type->getName()) { + $signature .= '?'; + } + $signature .= substr(strrchr('\\'.$type->getName(), '\\'), 1).' '; + } + } + $signature .= $k; + + if (!$param->isDefaultValueAvailable()) { + continue; + } + $v = $param->getDefaultValue(); + $signature .= ' = '; + + if ($param->isDefaultValueConstant()) { + $signature .= substr(strrchr('\\'.$param->getDefaultValueConstantName(), '\\'), 1); + } elseif (null === $v) { + $signature .= 'null'; + } elseif (\is_array($v)) { + $signature .= $v ? '[…'.\count($v).']' : '[]'; + } elseif (\is_string($v)) { + $signature .= 10 > \strlen($v) && !str_contains($v, '\\') ? "'{$v}'" : "'…".\strlen($v)."'"; + } elseif (\is_bool($v)) { + $signature .= $v ? 'true' : 'false'; + } elseif (\is_object($v)) { + $signature .= 'new '.substr(strrchr('\\'.get_debug_type($v), '\\'), 1); + } else { + $signature .= $v; + } + } + } + $signature = (empty($a[$prefix.'returnsReference']) ? '' : '&').'('.substr($signature, 2).')'; + + if (isset($a[$prefix.'returnType'])) { + $signature .= ': '.substr(strrchr('\\'.$a[$prefix.'returnType'], '\\'), 1); + } + + return $signature; + } + + private static function addExtra(array &$a, \Reflector $c) + { + $x = isset($a[Caster::PREFIX_VIRTUAL.'extra']) ? $a[Caster::PREFIX_VIRTUAL.'extra']->value : []; + + if (method_exists($c, 'getFileName') && $m = $c->getFileName()) { + $x['file'] = new LinkStub($m, $c->getStartLine()); + $x['line'] = $c->getStartLine().' to '.$c->getEndLine(); + } + + self::addMap($x, $c, self::EXTRA_MAP, ''); + + if ($x) { + $a[Caster::PREFIX_VIRTUAL.'extra'] = new EnumStub($x); + } + } + + private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL) + { + foreach ($map as $k => $m) { + if (\PHP_VERSION_ID >= 80000 && 'isDisabled' === $k) { + continue; + } + + if (method_exists($c, $m) && false !== ($m = $c->$m()) && null !== $m) { + $a[$prefix.$k] = $m instanceof \Reflector ? $m->name : $m; + } + } + } + + private static function addAttributes(array &$a, \Reflector $c, string $prefix = Caster::PREFIX_VIRTUAL): void + { + if (\PHP_VERSION_ID >= 80000) { + foreach ($c->getAttributes() as $n) { + $a[$prefix.'attributes'][] = $n; + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/ResourceCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ResourceCaster.php new file mode 100644 index 0000000..2c34ca9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/ResourceCaster.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts common resource types to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class ResourceCaster +{ + /** + * @param \CurlHandle|resource $h + */ + public static function castCurl($h, array $a, Stub $stub, bool $isNested): array + { + return curl_getinfo($h); + } + + public static function castDba($dba, array $a, Stub $stub, bool $isNested) + { + $list = dba_list(); + $a['file'] = $list[(int) $dba]; + + return $a; + } + + public static function castProcess($process, array $a, Stub $stub, bool $isNested) + { + return proc_get_status($process); + } + + public static function castStream($stream, array $a, Stub $stub, bool $isNested) + { + $a = stream_get_meta_data($stream) + static::castStreamContext($stream, $a, $stub, $isNested); + if ($a['uri'] ?? false) { + $a['uri'] = new LinkStub($a['uri']); + } + + return $a; + } + + public static function castStreamContext($stream, array $a, Stub $stub, bool $isNested) + { + return @stream_context_get_params($stream) ?: $a; + } + + public static function castGd($gd, array $a, Stub $stub, bool $isNested) + { + $a['size'] = imagesx($gd).'x'.imagesy($gd); + $a['trueColor'] = imageistruecolor($gd); + + return $a; + } + + public static function castMysqlLink($h, array $a, Stub $stub, bool $isNested) + { + $a['host'] = mysql_get_host_info($h); + $a['protocol'] = mysql_get_proto_info($h); + $a['server'] = mysql_get_server_info($h); + + return $a; + } + + public static function castOpensslX509($h, array $a, Stub $stub, bool $isNested) + { + $stub->cut = -1; + $info = openssl_x509_parse($h, false); + + $pin = openssl_pkey_get_public($h); + $pin = openssl_pkey_get_details($pin)['key']; + $pin = \array_slice(explode("\n", $pin), 1, -2); + $pin = base64_decode(implode('', $pin)); + $pin = base64_encode(hash('sha256', $pin, true)); + + $a += [ + 'subject' => new EnumStub(array_intersect_key($info['subject'], ['organizationName' => true, 'commonName' => true])), + 'issuer' => new EnumStub(array_intersect_key($info['issuer'], ['organizationName' => true, 'commonName' => true])), + 'expiry' => new ConstStub(date(\DateTime::ISO8601, $info['validTo_time_t']), $info['validTo_time_t']), + 'fingerprint' => new EnumStub([ + 'md5' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'md5')), 2, ':', true)), + 'sha1' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'sha1')), 2, ':', true)), + 'sha256' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'sha256')), 2, ':', true)), + 'pin-sha256' => new ConstStub($pin), + ]), + ]; + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/SplCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/SplCaster.php new file mode 100644 index 0000000..d7db8f8 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/SplCaster.php @@ -0,0 +1,246 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts SPL related classes to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class SplCaster +{ + private const SPL_FILE_OBJECT_FLAGS = [ + \SplFileObject::DROP_NEW_LINE => 'DROP_NEW_LINE', + \SplFileObject::READ_AHEAD => 'READ_AHEAD', + \SplFileObject::SKIP_EMPTY => 'SKIP_EMPTY', + \SplFileObject::READ_CSV => 'READ_CSV', + ]; + + public static function castArrayObject(\ArrayObject $c, array $a, Stub $stub, bool $isNested) + { + return self::castSplArray($c, $a, $stub, $isNested); + } + + public static function castArrayIterator(\ArrayIterator $c, array $a, Stub $stub, bool $isNested) + { + return self::castSplArray($c, $a, $stub, $isNested); + } + + public static function castHeap(\Iterator $c, array $a, Stub $stub, bool $isNested) + { + $a += [ + Caster::PREFIX_VIRTUAL.'heap' => iterator_to_array(clone $c), + ]; + + return $a; + } + + public static function castDoublyLinkedList(\SplDoublyLinkedList $c, array $a, Stub $stub, bool $isNested) + { + $prefix = Caster::PREFIX_VIRTUAL; + $mode = $c->getIteratorMode(); + $c->setIteratorMode(\SplDoublyLinkedList::IT_MODE_KEEP | $mode & ~\SplDoublyLinkedList::IT_MODE_DELETE); + + $a += [ + $prefix.'mode' => new ConstStub((($mode & \SplDoublyLinkedList::IT_MODE_LIFO) ? 'IT_MODE_LIFO' : 'IT_MODE_FIFO').' | '.(($mode & \SplDoublyLinkedList::IT_MODE_DELETE) ? 'IT_MODE_DELETE' : 'IT_MODE_KEEP'), $mode), + $prefix.'dllist' => iterator_to_array($c), + ]; + $c->setIteratorMode($mode); + + return $a; + } + + public static function castFileInfo(\SplFileInfo $c, array $a, Stub $stub, bool $isNested) + { + static $map = [ + 'path' => 'getPath', + 'filename' => 'getFilename', + 'basename' => 'getBasename', + 'pathname' => 'getPathname', + 'extension' => 'getExtension', + 'realPath' => 'getRealPath', + 'aTime' => 'getATime', + 'mTime' => 'getMTime', + 'cTime' => 'getCTime', + 'inode' => 'getInode', + 'size' => 'getSize', + 'perms' => 'getPerms', + 'owner' => 'getOwner', + 'group' => 'getGroup', + 'type' => 'getType', + 'writable' => 'isWritable', + 'readable' => 'isReadable', + 'executable' => 'isExecutable', + 'file' => 'isFile', + 'dir' => 'isDir', + 'link' => 'isLink', + 'linkTarget' => 'getLinkTarget', + ]; + + $prefix = Caster::PREFIX_VIRTUAL; + unset($a["\0SplFileInfo\0fileName"]); + unset($a["\0SplFileInfo\0pathName"]); + + if (\PHP_VERSION_ID < 80000) { + if (false === $c->getPathname()) { + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + + return $a; + } + } else { + try { + $c->isReadable(); + } catch (\RuntimeException $e) { + if ('Object not initialized' !== $e->getMessage()) { + throw $e; + } + + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + + return $a; + } catch (\Error $e) { + if ('Object not initialized' !== $e->getMessage()) { + throw $e; + } + + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + + return $a; + } + } + + foreach ($map as $key => $accessor) { + try { + $a[$prefix.$key] = $c->$accessor(); + } catch (\Exception $e) { + } + } + + if ($a[$prefix.'realPath'] ?? false) { + $a[$prefix.'realPath'] = new LinkStub($a[$prefix.'realPath']); + } + + if (isset($a[$prefix.'perms'])) { + $a[$prefix.'perms'] = new ConstStub(sprintf('0%o', $a[$prefix.'perms']), $a[$prefix.'perms']); + } + + static $mapDate = ['aTime', 'mTime', 'cTime']; + foreach ($mapDate as $key) { + if (isset($a[$prefix.$key])) { + $a[$prefix.$key] = new ConstStub(date('Y-m-d H:i:s', $a[$prefix.$key]), $a[$prefix.$key]); + } + } + + return $a; + } + + public static function castFileObject(\SplFileObject $c, array $a, Stub $stub, bool $isNested) + { + static $map = [ + 'csvControl' => 'getCsvControl', + 'flags' => 'getFlags', + 'maxLineLen' => 'getMaxLineLen', + 'fstat' => 'fstat', + 'eof' => 'eof', + 'key' => 'key', + ]; + + $prefix = Caster::PREFIX_VIRTUAL; + + foreach ($map as $key => $accessor) { + try { + $a[$prefix.$key] = $c->$accessor(); + } catch (\Exception $e) { + } + } + + if (isset($a[$prefix.'flags'])) { + $flagsArray = []; + foreach (self::SPL_FILE_OBJECT_FLAGS as $value => $name) { + if ($a[$prefix.'flags'] & $value) { + $flagsArray[] = $name; + } + } + $a[$prefix.'flags'] = new ConstStub(implode('|', $flagsArray), $a[$prefix.'flags']); + } + + if (isset($a[$prefix.'fstat'])) { + $a[$prefix.'fstat'] = new CutArrayStub($a[$prefix.'fstat'], ['dev', 'ino', 'nlink', 'rdev', 'blksize', 'blocks']); + } + + return $a; + } + + public static function castObjectStorage(\SplObjectStorage $c, array $a, Stub $stub, bool $isNested) + { + $storage = []; + unset($a[Caster::PREFIX_DYNAMIC."\0gcdata"]); // Don't hit https://bugs.php.net/65967 + unset($a["\0SplObjectStorage\0storage"]); + + $clone = clone $c; + foreach ($clone as $obj) { + $storage[] = [ + 'object' => $obj, + 'info' => $clone->getInfo(), + ]; + } + + $a += [ + Caster::PREFIX_VIRTUAL.'storage' => $storage, + ]; + + return $a; + } + + public static function castOuterIterator(\OuterIterator $c, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'innerIterator'] = $c->getInnerIterator(); + + return $a; + } + + public static function castWeakReference(\WeakReference $c, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'object'] = $c->get(); + + return $a; + } + + private static function castSplArray($c, array $a, Stub $stub, bool $isNested): array + { + $prefix = Caster::PREFIX_VIRTUAL; + $flags = $c->getFlags(); + + if (!($flags & \ArrayObject::STD_PROP_LIST)) { + $c->setFlags(\ArrayObject::STD_PROP_LIST); + $a = Caster::castObject($c, \get_class($c), method_exists($c, '__debugInfo'), $stub->class); + $c->setFlags($flags); + } + + unset($a["\0ArrayObject\0storage"], $a["\0ArrayIterator\0storage"]); + + $a += [ + $prefix.'storage' => $c->getArrayCopy(), + $prefix.'flag::STD_PROP_LIST' => (bool) ($flags & \ArrayObject::STD_PROP_LIST), + $prefix.'flag::ARRAY_AS_PROPS' => (bool) ($flags & \ArrayObject::ARRAY_AS_PROPS), + ]; + if ($c instanceof \ArrayObject) { + $a[$prefix.'iteratorClass'] = new ClassStub($c->getIteratorClass()); + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/StubCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/StubCaster.php new file mode 100644 index 0000000..32ead7c --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/StubCaster.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts a caster's Stub. + * + * @author Nicolas Grekas + * + * @final + */ +class StubCaster +{ + public static function castStub(Stub $c, array $a, Stub $stub, bool $isNested) + { + if ($isNested) { + $stub->type = $c->type; + $stub->class = $c->class; + $stub->value = $c->value; + $stub->handle = $c->handle; + $stub->cut = $c->cut; + $stub->attr = $c->attr; + + if (Stub::TYPE_REF === $c->type && !$c->class && \is_string($c->value) && !preg_match('//u', $c->value)) { + $stub->type = Stub::TYPE_STRING; + $stub->class = Stub::STRING_BINARY; + } + + $a = []; + } + + return $a; + } + + public static function castCutArray(CutArrayStub $c, array $a, Stub $stub, bool $isNested) + { + return $isNested ? $c->preservedSubset : $a; + } + + public static function cutInternals($obj, array $a, Stub $stub, bool $isNested) + { + if ($isNested) { + $stub->cut += \count($a); + + return []; + } + + return $a; + } + + public static function castEnum(EnumStub $c, array $a, Stub $stub, bool $isNested) + { + if ($isNested) { + $stub->class = $c->dumpKeys ? '' : null; + $stub->handle = 0; + $stub->value = null; + $stub->cut = $c->cut; + $stub->attr = $c->attr; + + $a = []; + + if ($c->value) { + foreach (array_keys($c->value) as $k) { + $keys[] = !isset($k[0]) || "\0" !== $k[0] ? Caster::PREFIX_VIRTUAL.$k : $k; + } + // Preserve references with array_combine() + $a = array_combine($keys, $c->value); + } + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/SymfonyCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/SymfonyCaster.php new file mode 100644 index 0000000..08428b9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/SymfonyCaster.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Uid\Ulid; +use Symfony\Component\Uid\Uuid; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @final + */ +class SymfonyCaster +{ + private const REQUEST_GETTERS = [ + 'pathInfo' => 'getPathInfo', + 'requestUri' => 'getRequestUri', + 'baseUrl' => 'getBaseUrl', + 'basePath' => 'getBasePath', + 'method' => 'getMethod', + 'format' => 'getRequestFormat', + ]; + + public static function castRequest(Request $request, array $a, Stub $stub, bool $isNested) + { + $clone = null; + + foreach (self::REQUEST_GETTERS as $prop => $getter) { + $key = Caster::PREFIX_PROTECTED.$prop; + if (\array_key_exists($key, $a) && null === $a[$key]) { + if (null === $clone) { + $clone = clone $request; + } + $a[Caster::PREFIX_VIRTUAL.$prop] = $clone->{$getter}(); + } + } + + return $a; + } + + public static function castHttpClient($client, array $a, Stub $stub, bool $isNested) + { + $multiKey = sprintf("\0%s\0multi", \get_class($client)); + if (isset($a[$multiKey])) { + $a[$multiKey] = new CutStub($a[$multiKey]); + } + + return $a; + } + + public static function castHttpClientResponse($response, array $a, Stub $stub, bool $isNested) + { + $stub->cut += \count($a); + $a = []; + + foreach ($response->getInfo() as $k => $v) { + $a[Caster::PREFIX_VIRTUAL.$k] = $v; + } + + return $a; + } + + public static function castUuid(Uuid $uuid, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $uuid->toBase58(); + $a[Caster::PREFIX_VIRTUAL.'toBase32'] = $uuid->toBase32(); + + // symfony/uid >= 5.3 + if (method_exists($uuid, 'getDateTime')) { + $a[Caster::PREFIX_VIRTUAL.'time'] = $uuid->getDateTime()->format('Y-m-d H:i:s.u \U\T\C'); + } + + return $a; + } + + public static function castUlid(Ulid $ulid, array $a, Stub $stub, bool $isNested) + { + $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $ulid->toBase58(); + $a[Caster::PREFIX_VIRTUAL.'toRfc4122'] = $ulid->toRfc4122(); + + // symfony/uid >= 5.3 + if (method_exists($ulid, 'getDateTime')) { + $a[Caster::PREFIX_VIRTUAL.'time'] = $ulid->getDateTime()->format('Y-m-d H:i:s.v \U\T\C'); + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/TraceStub.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/TraceStub.php new file mode 100644 index 0000000..d215d8d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/TraceStub.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\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents a backtrace as returned by debug_backtrace() or Exception->getTrace(). + * + * @author Nicolas Grekas + */ +class TraceStub extends Stub +{ + public $keepArgs; + public $sliceOffset; + public $sliceLength; + public $numberingOffset; + + public function __construct(array $trace, bool $keepArgs = true, int $sliceOffset = 0, ?int $sliceLength = null, int $numberingOffset = 0) + { + $this->value = $trace; + $this->keepArgs = $keepArgs; + $this->sliceOffset = $sliceOffset; + $this->sliceLength = $sliceLength; + $this->numberingOffset = $numberingOffset; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/UuidCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/UuidCaster.php new file mode 100644 index 0000000..b102774 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/UuidCaster.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\VarDumper\Caster; + +use Ramsey\Uuid\UuidInterface; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * @author Grégoire Pineau + */ +final class UuidCaster +{ + public static function castRamseyUuid(UuidInterface $c, array $a, Stub $stub, bool $isNested): array + { + $a += [ + Caster::PREFIX_VIRTUAL.'uuid' => (string) $c, + ]; + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php new file mode 100644 index 0000000..5b45565 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts XmlReader class to array representation. + * + * @author Baptiste Clavié + * + * @final + */ +class XmlReaderCaster +{ + private const NODE_TYPES = [ + \XMLReader::NONE => 'NONE', + \XMLReader::ELEMENT => 'ELEMENT', + \XMLReader::ATTRIBUTE => 'ATTRIBUTE', + \XMLReader::TEXT => 'TEXT', + \XMLReader::CDATA => 'CDATA', + \XMLReader::ENTITY_REF => 'ENTITY_REF', + \XMLReader::ENTITY => 'ENTITY', + \XMLReader::PI => 'PI (Processing Instruction)', + \XMLReader::COMMENT => 'COMMENT', + \XMLReader::DOC => 'DOC', + \XMLReader::DOC_TYPE => 'DOC_TYPE', + \XMLReader::DOC_FRAGMENT => 'DOC_FRAGMENT', + \XMLReader::NOTATION => 'NOTATION', + \XMLReader::WHITESPACE => 'WHITESPACE', + \XMLReader::SIGNIFICANT_WHITESPACE => 'SIGNIFICANT_WHITESPACE', + \XMLReader::END_ELEMENT => 'END_ELEMENT', + \XMLReader::END_ENTITY => 'END_ENTITY', + \XMLReader::XML_DECLARATION => 'XML_DECLARATION', + ]; + + public static function castXmlReader(\XMLReader $reader, array $a, Stub $stub, bool $isNested) + { + try { + $properties = [ + 'LOADDTD' => @$reader->getParserProperty(\XMLReader::LOADDTD), + 'DEFAULTATTRS' => @$reader->getParserProperty(\XMLReader::DEFAULTATTRS), + 'VALIDATE' => @$reader->getParserProperty(\XMLReader::VALIDATE), + 'SUBST_ENTITIES' => @$reader->getParserProperty(\XMLReader::SUBST_ENTITIES), + ]; + } catch (\Error $e) { + $properties = [ + 'LOADDTD' => false, + 'DEFAULTATTRS' => false, + 'VALIDATE' => false, + 'SUBST_ENTITIES' => false, + ]; + } + + $props = Caster::PREFIX_VIRTUAL.'parserProperties'; + $info = [ + 'localName' => $reader->localName, + 'prefix' => $reader->prefix, + 'nodeType' => new ConstStub(self::NODE_TYPES[$reader->nodeType], $reader->nodeType), + 'depth' => $reader->depth, + 'isDefault' => $reader->isDefault, + 'isEmptyElement' => \XMLReader::NONE === $reader->nodeType ? null : $reader->isEmptyElement, + 'xmlLang' => $reader->xmlLang, + 'attributeCount' => $reader->attributeCount, + 'value' => $reader->value, + 'namespaceURI' => $reader->namespaceURI, + 'baseURI' => $reader->baseURI ? new LinkStub($reader->baseURI) : $reader->baseURI, + $props => $properties, + ]; + + if ($info[$props] = Caster::filter($info[$props], Caster::EXCLUDE_EMPTY, [], $count)) { + $info[$props] = new EnumStub($info[$props]); + $info[$props]->cut = $count; + } + + $info = Caster::filter($info, Caster::EXCLUDE_EMPTY, [], $count); + // +2 because hasValue and hasAttributes are always filtered + $stub->cut += $count + 2; + + return $a + $info; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php b/php/libraries/composer/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php new file mode 100644 index 0000000..ba55fce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts XML resources to array representation. + * + * @author Nicolas Grekas + * + * @final + */ +class XmlResourceCaster +{ + private const XML_ERRORS = [ + \XML_ERROR_NONE => 'XML_ERROR_NONE', + \XML_ERROR_NO_MEMORY => 'XML_ERROR_NO_MEMORY', + \XML_ERROR_SYNTAX => 'XML_ERROR_SYNTAX', + \XML_ERROR_NO_ELEMENTS => 'XML_ERROR_NO_ELEMENTS', + \XML_ERROR_INVALID_TOKEN => 'XML_ERROR_INVALID_TOKEN', + \XML_ERROR_UNCLOSED_TOKEN => 'XML_ERROR_UNCLOSED_TOKEN', + \XML_ERROR_PARTIAL_CHAR => 'XML_ERROR_PARTIAL_CHAR', + \XML_ERROR_TAG_MISMATCH => 'XML_ERROR_TAG_MISMATCH', + \XML_ERROR_DUPLICATE_ATTRIBUTE => 'XML_ERROR_DUPLICATE_ATTRIBUTE', + \XML_ERROR_JUNK_AFTER_DOC_ELEMENT => 'XML_ERROR_JUNK_AFTER_DOC_ELEMENT', + \XML_ERROR_PARAM_ENTITY_REF => 'XML_ERROR_PARAM_ENTITY_REF', + \XML_ERROR_UNDEFINED_ENTITY => 'XML_ERROR_UNDEFINED_ENTITY', + \XML_ERROR_RECURSIVE_ENTITY_REF => 'XML_ERROR_RECURSIVE_ENTITY_REF', + \XML_ERROR_ASYNC_ENTITY => 'XML_ERROR_ASYNC_ENTITY', + \XML_ERROR_BAD_CHAR_REF => 'XML_ERROR_BAD_CHAR_REF', + \XML_ERROR_BINARY_ENTITY_REF => 'XML_ERROR_BINARY_ENTITY_REF', + \XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF => 'XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF', + \XML_ERROR_MISPLACED_XML_PI => 'XML_ERROR_MISPLACED_XML_PI', + \XML_ERROR_UNKNOWN_ENCODING => 'XML_ERROR_UNKNOWN_ENCODING', + \XML_ERROR_INCORRECT_ENCODING => 'XML_ERROR_INCORRECT_ENCODING', + \XML_ERROR_UNCLOSED_CDATA_SECTION => 'XML_ERROR_UNCLOSED_CDATA_SECTION', + \XML_ERROR_EXTERNAL_ENTITY_HANDLING => 'XML_ERROR_EXTERNAL_ENTITY_HANDLING', + ]; + + public static function castXml($h, array $a, Stub $stub, bool $isNested) + { + $a['current_byte_index'] = xml_get_current_byte_index($h); + $a['current_column_number'] = xml_get_current_column_number($h); + $a['current_line_number'] = xml_get_current_line_number($h); + $a['error_code'] = xml_get_error_code($h); + + if (isset(self::XML_ERRORS[$a['error_code']])) { + $a['error_code'] = new ConstStub(self::XML_ERRORS[$a['error_code']], $a['error_code']); + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/AbstractCloner.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/AbstractCloner.php new file mode 100644 index 0000000..e811fbf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/AbstractCloner.php @@ -0,0 +1,400 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +use Symfony\Component\VarDumper\Caster\Caster; +use Symfony\Component\VarDumper\Exception\ThrowingCasterException; + +/** + * AbstractCloner implements a generic caster mechanism for objects and resources. + * + * @author Nicolas Grekas + */ +abstract class AbstractCloner implements ClonerInterface +{ + public static $defaultCasters = [ + '__PHP_Incomplete_Class' => ['Symfony\Component\VarDumper\Caster\Caster', 'castPhpIncompleteClass'], + + 'Symfony\Component\VarDumper\Caster\CutStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'], + 'Symfony\Component\VarDumper\Caster\CutArrayStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castCutArray'], + 'Symfony\Component\VarDumper\Caster\ConstStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'], + 'Symfony\Component\VarDumper\Caster\EnumStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castEnum'], + + 'Fiber' => ['Symfony\Component\VarDumper\Caster\FiberCaster', 'castFiber'], + + 'Closure' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClosure'], + 'Generator' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castGenerator'], + 'ReflectionType' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castType'], + 'ReflectionAttribute' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castAttribute'], + 'ReflectionGenerator' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castReflectionGenerator'], + 'ReflectionClass' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClass'], + 'ReflectionClassConstant' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClassConstant'], + 'ReflectionFunctionAbstract' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castFunctionAbstract'], + 'ReflectionMethod' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castMethod'], + 'ReflectionParameter' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castParameter'], + 'ReflectionProperty' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castProperty'], + 'ReflectionReference' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castReference'], + 'ReflectionExtension' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castExtension'], + 'ReflectionZendExtension' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castZendExtension'], + + 'Doctrine\Common\Persistence\ObjectManager' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Doctrine\Common\Proxy\Proxy' => ['Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castCommonProxy'], + 'Doctrine\ORM\Proxy\Proxy' => ['Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castOrmProxy'], + 'Doctrine\ORM\PersistentCollection' => ['Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castPersistentCollection'], + 'Doctrine\Persistence\ObjectManager' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + + 'DOMException' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castException'], + 'DOMStringList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMNameList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMImplementation' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castImplementation'], + 'DOMImplementationList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMNode' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNode'], + 'DOMNameSpaceNode' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNameSpaceNode'], + 'DOMDocument' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocument'], + 'DOMNodeList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMNamedNodeMap' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMCharacterData' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castCharacterData'], + 'DOMAttr' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castAttr'], + 'DOMElement' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castElement'], + 'DOMText' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castText'], + 'DOMTypeinfo' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castTypeinfo'], + 'DOMDomError' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDomError'], + 'DOMLocator' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLocator'], + 'DOMDocumentType' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocumentType'], + 'DOMNotation' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNotation'], + 'DOMEntity' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castEntity'], + 'DOMProcessingInstruction' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castProcessingInstruction'], + 'DOMXPath' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castXPath'], + + 'XMLReader' => ['Symfony\Component\VarDumper\Caster\XmlReaderCaster', 'castXmlReader'], + + 'ErrorException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castErrorException'], + 'Exception' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castException'], + 'Error' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castError'], + 'Symfony\Bridge\Monolog\Logger' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Symfony\Component\DependencyInjection\ContainerInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Symfony\Component\EventDispatcher\EventDispatcherInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Symfony\Component\HttpClient\AmpHttpClient' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castHttpClient'], + 'Symfony\Component\HttpClient\CurlHttpClient' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castHttpClient'], + 'Symfony\Component\HttpClient\NativeHttpClient' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castHttpClient'], + 'Symfony\Component\HttpClient\Response\AmpResponse' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castHttpClientResponse'], + 'Symfony\Component\HttpClient\Response\CurlResponse' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castHttpClientResponse'], + 'Symfony\Component\HttpClient\Response\NativeResponse' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castHttpClientResponse'], + 'Symfony\Component\HttpFoundation\Request' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castRequest'], + 'Symfony\Component\Uid\Ulid' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castUlid'], + 'Symfony\Component\Uid\Uuid' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castUuid'], + 'Symfony\Component\VarDumper\Exception\ThrowingCasterException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castThrowingCasterException'], + 'Symfony\Component\VarDumper\Caster\TraceStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castTraceStub'], + 'Symfony\Component\VarDumper\Caster\FrameStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFrameStub'], + 'Symfony\Component\VarDumper\Cloner\AbstractCloner' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Symfony\Component\ErrorHandler\Exception\SilencedErrorContext' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castSilencedErrorContext'], + + 'Imagine\Image\ImageInterface' => ['Symfony\Component\VarDumper\Caster\ImagineCaster', 'castImage'], + + 'Ramsey\Uuid\UuidInterface' => ['Symfony\Component\VarDumper\Caster\UuidCaster', 'castRamseyUuid'], + + 'ProxyManager\Proxy\ProxyInterface' => ['Symfony\Component\VarDumper\Caster\ProxyManagerCaster', 'castProxy'], + 'PHPUnit_Framework_MockObject_MockObject' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'PHPUnit\Framework\MockObject\MockObject' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'PHPUnit\Framework\MockObject\Stub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Prophecy\Prophecy\ProphecySubjectInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Mockery\MockInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + + 'PDO' => ['Symfony\Component\VarDumper\Caster\PdoCaster', 'castPdo'], + 'PDOStatement' => ['Symfony\Component\VarDumper\Caster\PdoCaster', 'castPdoStatement'], + + 'AMQPConnection' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castConnection'], + 'AMQPChannel' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castChannel'], + 'AMQPQueue' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castQueue'], + 'AMQPExchange' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castExchange'], + 'AMQPEnvelope' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castEnvelope'], + + 'ArrayObject' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castArrayObject'], + 'ArrayIterator' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castArrayIterator'], + 'SplDoublyLinkedList' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castDoublyLinkedList'], + 'SplFileInfo' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castFileInfo'], + 'SplFileObject' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castFileObject'], + 'SplHeap' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'], + 'SplObjectStorage' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castObjectStorage'], + 'SplPriorityQueue' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'], + 'OuterIterator' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castOuterIterator'], + 'WeakReference' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castWeakReference'], + + 'Redis' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'], + 'RedisArray' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisArray'], + 'RedisCluster' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisCluster'], + + 'DateTimeInterface' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castDateTime'], + 'DateInterval' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castInterval'], + 'DateTimeZone' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castTimeZone'], + 'DatePeriod' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castPeriod'], + + 'GMP' => ['Symfony\Component\VarDumper\Caster\GmpCaster', 'castGmp'], + + 'MessageFormatter' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castMessageFormatter'], + 'NumberFormatter' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castNumberFormatter'], + 'IntlTimeZone' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlTimeZone'], + 'IntlCalendar' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlCalendar'], + 'IntlDateFormatter' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlDateFormatter'], + + 'Memcached' => ['Symfony\Component\VarDumper\Caster\MemcachedCaster', 'castMemcached'], + + 'Ds\Collection' => ['Symfony\Component\VarDumper\Caster\DsCaster', 'castCollection'], + 'Ds\Map' => ['Symfony\Component\VarDumper\Caster\DsCaster', 'castMap'], + 'Ds\Pair' => ['Symfony\Component\VarDumper\Caster\DsCaster', 'castPair'], + 'Symfony\Component\VarDumper\Caster\DsPairStub' => ['Symfony\Component\VarDumper\Caster\DsCaster', 'castPairStub'], + + 'mysqli_driver' => ['Symfony\Component\VarDumper\Caster\MysqliCaster', 'castMysqliDriver'], + + 'CurlHandle' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castCurl'], + ':curl' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castCurl'], + + ':dba' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'], + ':dba persistent' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'], + + 'GdImage' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'], + ':gd' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'], + + ':mysql link' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castMysqlLink'], + ':pgsql large object' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLargeObject'], + ':pgsql link' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'], + ':pgsql link persistent' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'], + ':pgsql result' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castResult'], + ':process' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castProcess'], + ':stream' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStream'], + + 'OpenSSLCertificate' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castOpensslX509'], + ':OpenSSL X.509' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castOpensslX509'], + + ':persistent stream' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStream'], + ':stream-context' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStreamContext'], + + 'XmlParser' => ['Symfony\Component\VarDumper\Caster\XmlResourceCaster', 'castXml'], + ':xml' => ['Symfony\Component\VarDumper\Caster\XmlResourceCaster', 'castXml'], + + 'RdKafka' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castRdKafka'], + 'RdKafka\Conf' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castConf'], + 'RdKafka\KafkaConsumer' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castKafkaConsumer'], + 'RdKafka\Metadata\Broker' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castBrokerMetadata'], + 'RdKafka\Metadata\Collection' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castCollectionMetadata'], + 'RdKafka\Metadata\Partition' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castPartitionMetadata'], + 'RdKafka\Metadata\Topic' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicMetadata'], + 'RdKafka\Message' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castMessage'], + 'RdKafka\Topic' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopic'], + 'RdKafka\TopicPartition' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicPartition'], + 'RdKafka\TopicConf' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicConf'], + ]; + + protected $maxItems = 2500; + protected $maxString = -1; + protected $minDepth = 1; + + /** + * @var array> + */ + private $casters = []; + + /** + * @var callable|null + */ + private $prevErrorHandler; + + private $classInfo = []; + private $filter = 0; + + /** + * @param callable[]|null $casters A map of casters + * + * @see addCasters + */ + public function __construct(?array $casters = null) + { + if (null === $casters) { + $casters = static::$defaultCasters; + } + $this->addCasters($casters); + } + + /** + * Adds casters for resources and objects. + * + * Maps resources or objects types to a callback. + * Types are in the key, with a callable caster for value. + * Resource types are to be prefixed with a `:`, + * see e.g. static::$defaultCasters. + * + * @param callable[] $casters A map of casters + */ + public function addCasters(array $casters) + { + foreach ($casters as $type => $callback) { + $this->casters[$type][] = $callback; + } + } + + /** + * Sets the maximum number of items to clone past the minimum depth in nested structures. + */ + public function setMaxItems(int $maxItems) + { + $this->maxItems = $maxItems; + } + + /** + * Sets the maximum cloned length for strings. + */ + public function setMaxString(int $maxString) + { + $this->maxString = $maxString; + } + + /** + * Sets the minimum tree depth where we are guaranteed to clone all the items. After this + * depth is reached, only setMaxItems items will be cloned. + */ + public function setMinDepth(int $minDepth) + { + $this->minDepth = $minDepth; + } + + /** + * Clones a PHP variable. + * + * @param mixed $var Any PHP variable + * @param int $filter A bit field of Caster::EXCLUDE_* constants + * + * @return Data + */ + public function cloneVar($var, int $filter = 0) + { + $this->prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) { + if (\E_RECOVERABLE_ERROR === $type || \E_USER_ERROR === $type) { + // Cloner never dies + throw new \ErrorException($msg, 0, $type, $file, $line); + } + + if ($this->prevErrorHandler) { + return ($this->prevErrorHandler)($type, $msg, $file, $line, $context); + } + + return false; + }); + $this->filter = $filter; + + if ($gc = gc_enabled()) { + gc_disable(); + } + try { + return new Data($this->doClone($var)); + } finally { + if ($gc) { + gc_enable(); + } + restore_error_handler(); + $this->prevErrorHandler = null; + } + } + + /** + * Effectively clones the PHP variable. + * + * @param mixed $var Any PHP variable + * + * @return array + */ + abstract protected function doClone($var); + + /** + * Casts an object to an array representation. + * + * @param bool $isNested True if the object is nested in the dumped structure + * + * @return array + */ + protected function castObject(Stub $stub, bool $isNested) + { + $obj = $stub->value; + $class = $stub->class; + + if (\PHP_VERSION_ID < 80000 ? "\0" === ($class[15] ?? null) : str_contains($class, "@anonymous\0")) { + $stub->class = get_debug_type($obj); + } + if (isset($this->classInfo[$class])) { + [$i, $parents, $hasDebugInfo, $fileInfo] = $this->classInfo[$class]; + } else { + $i = 2; + $parents = [$class]; + $hasDebugInfo = method_exists($class, '__debugInfo'); + + foreach (class_parents($class) as $p) { + $parents[] = $p; + ++$i; + } + foreach (class_implements($class) as $p) { + $parents[] = $p; + ++$i; + } + $parents[] = '*'; + + $r = new \ReflectionClass($class); + $fileInfo = $r->isInternal() || $r->isSubclassOf(Stub::class) ? [] : [ + 'file' => $r->getFileName(), + 'line' => $r->getStartLine(), + ]; + + $this->classInfo[$class] = [$i, $parents, $hasDebugInfo, $fileInfo]; + } + + $stub->attr += $fileInfo; + $a = Caster::castObject($obj, $class, $hasDebugInfo, $stub->class); + + try { + while ($i--) { + if (!empty($this->casters[$p = $parents[$i]])) { + foreach ($this->casters[$p] as $callback) { + $a = $callback($obj, $a, $stub, $isNested, $this->filter); + } + } + } + } catch (\Exception $e) { + $a = [(Stub::TYPE_OBJECT === $stub->type ? Caster::PREFIX_VIRTUAL : '').'⚠' => new ThrowingCasterException($e)] + $a; + } + + return $a; + } + + /** + * Casts a resource to an array representation. + * + * @param bool $isNested True if the object is nested in the dumped structure + * + * @return array + */ + protected function castResource(Stub $stub, bool $isNested) + { + $a = []; + $res = $stub->value; + $type = $stub->class; + + try { + if (!empty($this->casters[':'.$type])) { + foreach ($this->casters[':'.$type] as $callback) { + $a = $callback($res, $a, $stub, $isNested, $this->filter); + } + } + } catch (\Exception $e) { + $a = [(Stub::TYPE_OBJECT === $stub->type ? Caster::PREFIX_VIRTUAL : '').'⚠' => new ThrowingCasterException($e)] + $a; + } + + return $a; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/ClonerInterface.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/ClonerInterface.php new file mode 100644 index 0000000..90b1495 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/ClonerInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +/** + * @author Nicolas Grekas + */ +interface ClonerInterface +{ + /** + * Clones a PHP variable. + * + * @param mixed $var Any PHP variable + * + * @return Data + */ + public function cloneVar($var); +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Cursor.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Cursor.php new file mode 100644 index 0000000..1fd796d --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Cursor.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +/** + * Represents the current state of a dumper while dumping. + * + * @author Nicolas Grekas + */ +class Cursor +{ + public const HASH_INDEXED = Stub::ARRAY_INDEXED; + public const HASH_ASSOC = Stub::ARRAY_ASSOC; + public const HASH_OBJECT = Stub::TYPE_OBJECT; + public const HASH_RESOURCE = Stub::TYPE_RESOURCE; + + public $depth = 0; + public $refIndex = 0; + public $softRefTo = 0; + public $softRefCount = 0; + public $softRefHandle = 0; + public $hardRefTo = 0; + public $hardRefCount = 0; + public $hardRefHandle = 0; + public $hashType; + public $hashKey; + public $hashKeyIsBinary; + public $hashIndex = 0; + public $hashLength = 0; + public $hashCut = 0; + public $stop = false; + public $attr = []; + public $skipChildren = false; +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Data.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Data.php new file mode 100644 index 0000000..ea8f0f3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Data.php @@ -0,0 +1,468 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +use Symfony\Component\VarDumper\Caster\Caster; +use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider; + +/** + * @author Nicolas Grekas + */ +class Data implements \ArrayAccess, \Countable, \IteratorAggregate +{ + private $data; + private $position = 0; + private $key = 0; + private $maxDepth = 20; + private $maxItemsPerDepth = -1; + private $useRefHandles = -1; + private $context = []; + + /** + * @param array $data An array as returned by ClonerInterface::cloneVar() + */ + public function __construct(array $data) + { + $this->data = $data; + } + + /** + * @return string|null + */ + public function getType() + { + $item = $this->data[$this->position][$this->key]; + + if ($item instanceof Stub && Stub::TYPE_REF === $item->type && !$item->position) { + $item = $item->value; + } + if (!$item instanceof Stub) { + return \gettype($item); + } + if (Stub::TYPE_STRING === $item->type) { + return 'string'; + } + if (Stub::TYPE_ARRAY === $item->type) { + return 'array'; + } + if (Stub::TYPE_OBJECT === $item->type) { + return $item->class; + } + if (Stub::TYPE_RESOURCE === $item->type) { + return $item->class.' resource'; + } + + return null; + } + + /** + * Returns a native representation of the original value. + * + * @param array|bool $recursive Whether values should be resolved recursively or not + * + * @return string|int|float|bool|array|Data[]|null + */ + public function getValue($recursive = false) + { + $item = $this->data[$this->position][$this->key]; + + if ($item instanceof Stub && Stub::TYPE_REF === $item->type && !$item->position) { + $item = $item->value; + } + if (!($item = $this->getStub($item)) instanceof Stub) { + return $item; + } + if (Stub::TYPE_STRING === $item->type) { + return $item->value; + } + + $children = $item->position ? $this->data[$item->position] : []; + + foreach ($children as $k => $v) { + if ($recursive && !($v = $this->getStub($v)) instanceof Stub) { + continue; + } + $children[$k] = clone $this; + $children[$k]->key = $k; + $children[$k]->position = $item->position; + + if ($recursive) { + if (Stub::TYPE_REF === $v->type && ($v = $this->getStub($v->value)) instanceof Stub) { + $recursive = (array) $recursive; + if (isset($recursive[$v->position])) { + continue; + } + $recursive[$v->position] = true; + } + $children[$k] = $children[$k]->getValue($recursive); + } + } + + return $children; + } + + /** + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return \count($this->getValue()); + } + + /** + * @return \Traversable + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + if (!\is_array($value = $this->getValue())) { + throw new \LogicException(sprintf('"%s" object holds non-iterable type "%s".', self::class, get_debug_type($value))); + } + + yield from $value; + } + + public function __get(string $key) + { + if (null !== $data = $this->seek($key)) { + $item = $this->getStub($data->data[$data->position][$data->key]); + + return $item instanceof Stub || [] === $item ? $data : $item; + } + + return null; + } + + /** + * @return bool + */ + public function __isset(string $key) + { + return null !== $this->seek($key); + } + + /** + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->__isset($key); + } + + /** + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->__get($key); + } + + /** + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + throw new \BadMethodCallException(self::class.' objects are immutable.'); + } + + /** + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + throw new \BadMethodCallException(self::class.' objects are immutable.'); + } + + /** + * @return string + */ + public function __toString() + { + $value = $this->getValue(); + + if (!\is_array($value)) { + return (string) $value; + } + + return sprintf('%s (count=%d)', $this->getType(), \count($value)); + } + + /** + * Returns a depth limited clone of $this. + * + * @return static + */ + public function withMaxDepth(int $maxDepth) + { + $data = clone $this; + $data->maxDepth = $maxDepth; + + return $data; + } + + /** + * Limits the number of elements per depth level. + * + * @return static + */ + public function withMaxItemsPerDepth(int $maxItemsPerDepth) + { + $data = clone $this; + $data->maxItemsPerDepth = $maxItemsPerDepth; + + return $data; + } + + /** + * Enables/disables objects' identifiers tracking. + * + * @param bool $useRefHandles False to hide global ref. handles + * + * @return static + */ + public function withRefHandles(bool $useRefHandles) + { + $data = clone $this; + $data->useRefHandles = $useRefHandles ? -1 : 0; + + return $data; + } + + /** + * @return static + */ + public function withContext(array $context) + { + $data = clone $this; + $data->context = $context; + + return $data; + } + + /** + * Seeks to a specific key in nested data structures. + * + * @param string|int $key The key to seek to + * + * @return static|null + */ + public function seek($key) + { + $item = $this->data[$this->position][$this->key]; + + if ($item instanceof Stub && Stub::TYPE_REF === $item->type && !$item->position) { + $item = $item->value; + } + if (!($item = $this->getStub($item)) instanceof Stub || !$item->position) { + return null; + } + $keys = [$key]; + + switch ($item->type) { + case Stub::TYPE_OBJECT: + $keys[] = Caster::PREFIX_DYNAMIC.$key; + $keys[] = Caster::PREFIX_PROTECTED.$key; + $keys[] = Caster::PREFIX_VIRTUAL.$key; + $keys[] = "\0$item->class\0$key"; + // no break + case Stub::TYPE_ARRAY: + case Stub::TYPE_RESOURCE: + break; + default: + return null; + } + + $data = null; + $children = $this->data[$item->position]; + + foreach ($keys as $key) { + if (isset($children[$key]) || \array_key_exists($key, $children)) { + $data = clone $this; + $data->key = $key; + $data->position = $item->position; + break; + } + } + + return $data; + } + + /** + * Dumps data with a DumperInterface dumper. + */ + public function dump(DumperInterface $dumper) + { + $refs = [0]; + $cursor = new Cursor(); + + if ($cursor->attr = $this->context[SourceContextProvider::class] ?? []) { + $cursor->attr['if_links'] = true; + $cursor->hashType = -1; + $dumper->dumpScalar($cursor, 'default', '^'); + $cursor->attr = ['if_links' => true]; + $dumper->dumpScalar($cursor, 'default', ' '); + $cursor->hashType = 0; + } + + $this->dumpItem($dumper, $cursor, $refs, $this->data[$this->position][$this->key]); + } + + /** + * Depth-first dumping of items. + * + * @param mixed $item A Stub object or the original value being dumped + */ + private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, $item) + { + $cursor->refIndex = 0; + $cursor->softRefTo = $cursor->softRefHandle = $cursor->softRefCount = 0; + $cursor->hardRefTo = $cursor->hardRefHandle = $cursor->hardRefCount = 0; + $firstSeen = true; + + if (!$item instanceof Stub) { + $cursor->attr = []; + $type = \gettype($item); + if ($item && 'array' === $type) { + $item = $this->getStub($item); + } + } elseif (Stub::TYPE_REF === $item->type) { + if ($item->handle) { + if (!isset($refs[$r = $item->handle - (\PHP_INT_MAX >> 1)])) { + $cursor->refIndex = $refs[$r] = $cursor->refIndex ?: ++$refs[0]; + } else { + $firstSeen = false; + } + $cursor->hardRefTo = $refs[$r]; + $cursor->hardRefHandle = $this->useRefHandles & $item->handle; + $cursor->hardRefCount = 0 < $item->handle ? $item->refCount : 0; + } + $cursor->attr = $item->attr; + $type = $item->class ?: \gettype($item->value); + $item = $this->getStub($item->value); + } + if ($item instanceof Stub) { + if ($item->refCount) { + if (!isset($refs[$r = $item->handle])) { + $cursor->refIndex = $refs[$r] = $cursor->refIndex ?: ++$refs[0]; + } else { + $firstSeen = false; + } + $cursor->softRefTo = $refs[$r]; + } + $cursor->softRefHandle = $this->useRefHandles & $item->handle; + $cursor->softRefCount = $item->refCount; + $cursor->attr = $item->attr; + $cut = $item->cut; + + if ($item->position && $firstSeen) { + $children = $this->data[$item->position]; + + if ($cursor->stop) { + if ($cut >= 0) { + $cut += \count($children); + } + $children = []; + } + } else { + $children = []; + } + switch ($item->type) { + case Stub::TYPE_STRING: + $dumper->dumpString($cursor, $item->value, Stub::STRING_BINARY === $item->class, $cut); + break; + + case Stub::TYPE_ARRAY: + $item = clone $item; + $item->type = $item->class; + $item->class = $item->value; + // no break + case Stub::TYPE_OBJECT: + case Stub::TYPE_RESOURCE: + $withChildren = $children && $cursor->depth !== $this->maxDepth && $this->maxItemsPerDepth; + $dumper->enterHash($cursor, $item->type, $item->class, $withChildren); + if ($withChildren) { + if ($cursor->skipChildren) { + $withChildren = false; + $cut = -1; + } else { + $cut = $this->dumpChildren($dumper, $cursor, $refs, $children, $cut, $item->type, null !== $item->class); + } + } elseif ($children && 0 <= $cut) { + $cut += \count($children); + } + $cursor->skipChildren = false; + $dumper->leaveHash($cursor, $item->type, $item->class, $withChildren, $cut); + break; + + default: + throw new \RuntimeException(sprintf('Unexpected Stub type: "%s".', $item->type)); + } + } elseif ('array' === $type) { + $dumper->enterHash($cursor, Cursor::HASH_INDEXED, 0, false); + $dumper->leaveHash($cursor, Cursor::HASH_INDEXED, 0, false, 0); + } elseif ('string' === $type) { + $dumper->dumpString($cursor, $item, false, 0); + } else { + $dumper->dumpScalar($cursor, $type, $item); + } + } + + /** + * Dumps children of hash structures. + * + * @return int The final number of removed items + */ + private function dumpChildren(DumperInterface $dumper, Cursor $parentCursor, array &$refs, array $children, int $hashCut, int $hashType, bool $dumpKeys): int + { + $cursor = clone $parentCursor; + ++$cursor->depth; + $cursor->hashType = $hashType; + $cursor->hashIndex = 0; + $cursor->hashLength = \count($children); + $cursor->hashCut = $hashCut; + foreach ($children as $key => $child) { + $cursor->hashKeyIsBinary = isset($key[0]) && !preg_match('//u', $key); + $cursor->hashKey = $dumpKeys ? $key : null; + $this->dumpItem($dumper, $cursor, $refs, $child); + if (++$cursor->hashIndex === $this->maxItemsPerDepth || $cursor->stop) { + $parentCursor->stop = true; + + return $hashCut >= 0 ? $hashCut + $cursor->hashLength - $cursor->hashIndex : $hashCut; + } + } + + return $hashCut; + } + + private function getStub($item) + { + if (!$item || !\is_array($item)) { + return $item; + } + + $stub = new Stub(); + $stub->type = Stub::TYPE_ARRAY; + foreach ($item as $stub->class => $stub->position) { + } + if (isset($item[0])) { + $stub->cut = $item[0]; + } + $stub->value = $stub->cut + ($stub->position ? \count($this->data[$stub->position]) : 0); + + return $stub; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/DumperInterface.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/DumperInterface.php new file mode 100644 index 0000000..6d60b72 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/DumperInterface.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +/** + * DumperInterface used by Data objects. + * + * @author Nicolas Grekas + */ +interface DumperInterface +{ + /** + * Dumps a scalar value. + * + * @param string $type The PHP type of the value being dumped + * @param string|int|float|bool $value The scalar value being dumped + */ + public function dumpScalar(Cursor $cursor, string $type, $value); + + /** + * Dumps a string. + * + * @param string $str The string being dumped + * @param bool $bin Whether $str is UTF-8 or binary encoded + * @param int $cut The number of characters $str has been cut by + */ + public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut); + + /** + * Dumps while entering an hash. + * + * @param int $type A Cursor::HASH_* const for the type of hash + * @param string|int $class The object class, resource type or array count + * @param bool $hasChild When the dump of the hash has child item + */ + public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild); + + /** + * Dumps while leaving an hash. + * + * @param int $type A Cursor::HASH_* const for the type of hash + * @param string|int $class The object class, resource type or array count + * @param bool $hasChild When the dump of the hash has child item + * @param int $cut The number of items the hash has been cut by + */ + public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut); +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Stub.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Stub.php new file mode 100644 index 0000000..073c56e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/Stub.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +/** + * Represents the main properties of a PHP variable. + * + * @author Nicolas Grekas + */ +class Stub +{ + public const TYPE_REF = 1; + public const TYPE_STRING = 2; + public const TYPE_ARRAY = 3; + public const TYPE_OBJECT = 4; + public const TYPE_RESOURCE = 5; + + public const STRING_BINARY = 1; + public const STRING_UTF8 = 2; + + public const ARRAY_ASSOC = 1; + public const ARRAY_INDEXED = 2; + + public $type = self::TYPE_REF; + public $class = ''; + public $value; + public $cut = 0; + public $handle = 0; + public $refCount = 0; + public $position = 0; + public $attr = []; + + private static $defaultProperties = []; + + /** + * @internal + */ + public function __sleep(): array + { + $properties = []; + + if (!isset(self::$defaultProperties[$c = static::class])) { + self::$defaultProperties[$c] = get_class_vars($c); + + foreach ((new \ReflectionClass($c))->getStaticProperties() as $k => $v) { + unset(self::$defaultProperties[$c][$k]); + } + } + + foreach (self::$defaultProperties[$c] as $k => $v) { + if ($this->$k !== $v) { + $properties[] = $k; + } + } + + return $properties; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Cloner/VarCloner.php b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/VarCloner.php new file mode 100644 index 0000000..80c4a2f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Cloner/VarCloner.php @@ -0,0 +1,311 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Cloner; + +/** + * @author Nicolas Grekas + */ +class VarCloner extends AbstractCloner +{ + private static $gid; + private static $arrayCache = []; + + /** + * {@inheritdoc} + */ + protected function doClone($var) + { + $len = 1; // Length of $queue + $pos = 0; // Number of cloned items past the minimum depth + $refsCounter = 0; // Hard references counter + $queue = [[$var]]; // This breadth-first queue is the return value + $hardRefs = []; // Map of original zval ids to stub objects + $objRefs = []; // Map of original object handles to their stub object counterpart + $objects = []; // Keep a ref to objects to ensure their handle cannot be reused while cloning + $resRefs = []; // Map of original resource handles to their stub object counterpart + $values = []; // Map of stub objects' ids to original values + $maxItems = $this->maxItems; + $maxString = $this->maxString; + $minDepth = $this->minDepth; + $currentDepth = 0; // Current tree depth + $currentDepthFinalIndex = 0; // Final $queue index for current tree depth + $minimumDepthReached = 0 === $minDepth; // Becomes true when minimum tree depth has been reached + $cookie = (object) []; // Unique object used to detect hard references + $a = null; // Array cast for nested structures + $stub = null; // Stub capturing the main properties of an original item value + // or null if the original value is used directly + + if (!$gid = self::$gid) { + $gid = self::$gid = md5(random_bytes(6)); // Unique string used to detect the special $GLOBALS variable + } + $arrayStub = new Stub(); + $arrayStub->type = Stub::TYPE_ARRAY; + $fromObjCast = false; + + for ($i = 0; $i < $len; ++$i) { + // Detect when we move on to the next tree depth + if ($i > $currentDepthFinalIndex) { + ++$currentDepth; + $currentDepthFinalIndex = $len - 1; + if ($currentDepth >= $minDepth) { + $minimumDepthReached = true; + } + } + + $refs = $vals = $queue[$i]; + foreach ($vals as $k => $v) { + // $v is the original value or a stub object in case of hard references + + if (\PHP_VERSION_ID >= 70400) { + $zvalRef = ($r = \ReflectionReference::fromArrayElement($vals, $k)) ? $r->getId() : null; + } else { + $refs[$k] = $cookie; + $zvalRef = $vals[$k] === $cookie; + } + + if ($zvalRef) { + $vals[$k] = &$stub; // Break hard references to make $queue completely + unset($stub); // independent from the original structure + if (\PHP_VERSION_ID >= 70400 ? null !== $vals[$k] = $hardRefs[$zvalRef] ?? null : $v instanceof Stub && isset($hardRefs[spl_object_id($v)])) { + if (\PHP_VERSION_ID >= 70400) { + $v = $vals[$k]; + } else { + $refs[$k] = $vals[$k] = $v; + } + if ($v->value instanceof Stub && (Stub::TYPE_OBJECT === $v->value->type || Stub::TYPE_RESOURCE === $v->value->type)) { + ++$v->value->refCount; + } + ++$v->refCount; + continue; + } + $vals[$k] = new Stub(); + $vals[$k]->value = $v; + $vals[$k]->handle = ++$refsCounter; + + if (\PHP_VERSION_ID >= 70400) { + $hardRefs[$zvalRef] = $vals[$k]; + } else { + $refs[$k] = $vals[$k]; + $h = spl_object_id($refs[$k]); + $hardRefs[$h] = &$refs[$k]; + $values[$h] = $v; + } + } + // Create $stub when the original value $v cannot be used directly + // If $v is a nested structure, put that structure in array $a + switch (true) { + case null === $v: + case \is_bool($v): + case \is_int($v): + case \is_float($v): + continue 2; + case \is_string($v): + if ('' === $v) { + continue 2; + } + if (!preg_match('//u', $v)) { + $stub = new Stub(); + $stub->type = Stub::TYPE_STRING; + $stub->class = Stub::STRING_BINARY; + if (0 <= $maxString && 0 < $cut = \strlen($v) - $maxString) { + $stub->cut = $cut; + $stub->value = substr($v, 0, -$cut); + } else { + $stub->value = $v; + } + } elseif (0 <= $maxString && isset($v[1 + ($maxString >> 2)]) && 0 < $cut = mb_strlen($v, 'UTF-8') - $maxString) { + $stub = new Stub(); + $stub->type = Stub::TYPE_STRING; + $stub->class = Stub::STRING_UTF8; + $stub->cut = $cut; + $stub->value = mb_substr($v, 0, $maxString, 'UTF-8'); + } else { + continue 2; + } + $a = null; + break; + + case \is_array($v): + if (!$v) { + continue 2; + } + $stub = $arrayStub; + + if (\PHP_VERSION_ID >= 80100) { + $stub->class = array_is_list($v) ? Stub::ARRAY_INDEXED : Stub::ARRAY_ASSOC; + $a = $v; + break; + } + + $stub->class = Stub::ARRAY_INDEXED; + + $j = -1; + foreach ($v as $gk => $gv) { + if ($gk !== ++$j) { + $stub->class = Stub::ARRAY_ASSOC; + $a = $v; + $a[$gid] = true; + break; + } + } + + // Copies of $GLOBALS have very strange behavior, + // let's detect them with some black magic + if (isset($v[$gid])) { + unset($v[$gid]); + $a = []; + foreach ($v as $gk => &$gv) { + if ($v === $gv && (\PHP_VERSION_ID < 70400 || !isset($hardRefs[\ReflectionReference::fromArrayElement($v, $gk)->getId()]))) { + unset($v); + $v = new Stub(); + $v->value = [$v->cut = \count($gv), Stub::TYPE_ARRAY => 0]; + $v->handle = -1; + if (\PHP_VERSION_ID >= 70400) { + $gv = &$a[$gk]; + $hardRefs[\ReflectionReference::fromArrayElement($a, $gk)->getId()] = &$gv; + } else { + $gv = &$hardRefs[spl_object_id($v)]; + } + $gv = $v; + } + + $a[$gk] = &$gv; + } + unset($gv); + } else { + $a = $v; + } + break; + + case \is_object($v): + if (empty($objRefs[$h = spl_object_id($v)])) { + $stub = new Stub(); + $stub->type = Stub::TYPE_OBJECT; + $stub->class = \get_class($v); + $stub->value = $v; + $stub->handle = $h; + $a = $this->castObject($stub, 0 < $i); + if ($v !== $stub->value) { + if (Stub::TYPE_OBJECT !== $stub->type || null === $stub->value) { + break; + } + $stub->handle = $h = spl_object_id($stub->value); + } + $stub->value = null; + if (0 <= $maxItems && $maxItems <= $pos && $minimumDepthReached) { + $stub->cut = \count($a); + $a = null; + } + } + if (empty($objRefs[$h])) { + $objRefs[$h] = $stub; + $objects[] = $v; + } else { + $stub = $objRefs[$h]; + ++$stub->refCount; + $a = null; + } + break; + + default: // resource + if (empty($resRefs[$h = (int) $v])) { + $stub = new Stub(); + $stub->type = Stub::TYPE_RESOURCE; + if ('Unknown' === $stub->class = @get_resource_type($v)) { + $stub->class = 'Closed'; + } + $stub->value = $v; + $stub->handle = $h; + $a = $this->castResource($stub, 0 < $i); + $stub->value = null; + if (0 <= $maxItems && $maxItems <= $pos && $minimumDepthReached) { + $stub->cut = \count($a); + $a = null; + } + } + if (empty($resRefs[$h])) { + $resRefs[$h] = $stub; + } else { + $stub = $resRefs[$h]; + ++$stub->refCount; + $a = null; + } + break; + } + + if ($a) { + if (!$minimumDepthReached || 0 > $maxItems) { + $queue[$len] = $a; + $stub->position = $len++; + } elseif ($pos < $maxItems) { + if ($maxItems < $pos += \count($a)) { + $a = \array_slice($a, 0, $maxItems - $pos, true); + if ($stub->cut >= 0) { + $stub->cut += $pos - $maxItems; + } + } + $queue[$len] = $a; + $stub->position = $len++; + } elseif ($stub->cut >= 0) { + $stub->cut += \count($a); + $stub->position = 0; + } + } + + if ($arrayStub === $stub) { + if ($arrayStub->cut) { + $stub = [$arrayStub->cut, $arrayStub->class => $arrayStub->position]; + $arrayStub->cut = 0; + } elseif (isset(self::$arrayCache[$arrayStub->class][$arrayStub->position])) { + $stub = self::$arrayCache[$arrayStub->class][$arrayStub->position]; + } else { + self::$arrayCache[$arrayStub->class][$arrayStub->position] = $stub = [$arrayStub->class => $arrayStub->position]; + } + } + + if (!$zvalRef) { + $vals[$k] = $stub; + } elseif (\PHP_VERSION_ID >= 70400) { + $hardRefs[$zvalRef]->value = $stub; + } else { + $refs[$k]->value = $stub; + } + } + + if ($fromObjCast) { + $fromObjCast = false; + $refs = $vals; + $vals = []; + $j = -1; + foreach ($queue[$i] as $k => $v) { + foreach ([$k => true] as $gk => $gv) { + } + if ($gk !== $k) { + $vals = (object) $vals; + $vals->{$k} = $refs[++$j]; + $vals = (array) $vals; + } else { + $vals[$k] = $refs[++$j]; + } + } + } + + $queue[$i] = $vals; + } + + foreach ($values as $h => $v) { + $hardRefs[$h] = $v; + } + + return $queue; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php b/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php new file mode 100644 index 0000000..2afaa7b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Command\Descriptor; + +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Dumper\CliDumper; + +/** + * Describe collected data clones for cli output. + * + * @author Maxime Steinhausser + * + * @final + */ +class CliDescriptor implements DumpDescriptorInterface +{ + private $dumper; + private $lastIdentifier; + + public function __construct(CliDumper $dumper) + { + $this->dumper = $dumper; + } + + public function describe(OutputInterface $output, Data $data, array $context, int $clientId): void + { + $io = $output instanceof SymfonyStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output); + $this->dumper->setColors($output->isDecorated()); + + $rows = [['date', date('r', (int) $context['timestamp'])]]; + $lastIdentifier = $this->lastIdentifier; + $this->lastIdentifier = $clientId; + + $section = "Received from client #$clientId"; + if (isset($context['request'])) { + $request = $context['request']; + $this->lastIdentifier = $request['identifier']; + $section = sprintf('%s %s', $request['method'], $request['uri']); + if ($controller = $request['controller']) { + $rows[] = ['controller', rtrim($this->dumper->dump($controller, true), "\n")]; + } + } elseif (isset($context['cli'])) { + $this->lastIdentifier = $context['cli']['identifier']; + $section = '$ '.$context['cli']['command_line']; + } + + if ($this->lastIdentifier !== $lastIdentifier) { + $io->section($section); + } + + if (isset($context['source'])) { + $source = $context['source']; + $sourceInfo = sprintf('%s on line %d', $source['name'], $source['line']); + if ($fileLink = $source['file_link'] ?? null) { + $sourceInfo = sprintf('%s', $fileLink, $sourceInfo); + } + $rows[] = ['source', $sourceInfo]; + $file = $source['file_relative'] ?? $source['file']; + $rows[] = ['file', $file]; + } + + $io->table([], $rows); + + $this->dumper->dump($data); + $io->newLine(); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/DumpDescriptorInterface.php b/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/DumpDescriptorInterface.php new file mode 100644 index 0000000..267d27b --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/DumpDescriptorInterface.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Command\Descriptor; + +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\VarDumper\Cloner\Data; + +/** + * @author Maxime Steinhausser + */ +interface DumpDescriptorInterface +{ + public function describe(OutputInterface $output, Data $data, array $context, int $clientId): void; +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php b/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php new file mode 100644 index 0000000..636b618 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php @@ -0,0 +1,119 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Command\Descriptor; + +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Dumper\HtmlDumper; + +/** + * Describe collected data clones for html output. + * + * @author Maxime Steinhausser + * + * @final + */ +class HtmlDescriptor implements DumpDescriptorInterface +{ + private $dumper; + private $initialized = false; + + public function __construct(HtmlDumper $dumper) + { + $this->dumper = $dumper; + } + + public function describe(OutputInterface $output, Data $data, array $context, int $clientId): void + { + if (!$this->initialized) { + $styles = file_get_contents(__DIR__.'/../../Resources/css/htmlDescriptor.css'); + $scripts = file_get_contents(__DIR__.'/../../Resources/js/htmlDescriptor.js'); + $output->writeln(""); + $this->initialized = true; + } + + $title = '-'; + if (isset($context['request'])) { + $request = $context['request']; + $controller = "{$this->dumper->dump($request['controller'], true, ['maxDepth' => 0])}"; + $title = sprintf('%s %s', $request['method'], $uri = $request['uri'], $uri); + $dedupIdentifier = $request['identifier']; + } elseif (isset($context['cli'])) { + $title = '$ '.$context['cli']['command_line']; + $dedupIdentifier = $context['cli']['identifier']; + } else { + $dedupIdentifier = uniqid('', true); + } + + $sourceDescription = ''; + if (isset($context['source'])) { + $source = $context['source']; + $projectDir = $source['project_dir'] ?? null; + $sourceDescription = sprintf('%s on line %d', $source['name'], $source['line']); + if (isset($source['file_link'])) { + $sourceDescription = sprintf('%s', $source['file_link'], $sourceDescription); + } + } + + $isoDate = $this->extractDate($context, 'c'); + $tags = array_filter([ + 'controller' => $controller ?? null, + 'project dir' => $projectDir ?? null, + ]); + + $output->writeln(<< +
+
+

$title

+ +
+ {$this->renderTags($tags)} +
+
+

+ $sourceDescription +

+ {$this->dumper->dump($data, true)} +
+ +HTML + ); + } + + private function extractDate(array $context, string $format = 'r'): string + { + return date($format, (int) $context['timestamp']); + } + + private function renderTags(array $tags): string + { + if (!$tags) { + return ''; + } + + $renderedTags = ''; + foreach ($tags as $key => $value) { + $renderedTags .= sprintf('
  • %s%s
  • ', $key, $value); + } + + return << +
      + $renderedTags +
    +
    +HTML; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Command/ServerDumpCommand.php b/php/libraries/composer/vendor/symfony/var-dumper/Command/ServerDumpCommand.php new file mode 100644 index 0000000..3a69595 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Command/ServerDumpCommand.php @@ -0,0 +1,114 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Command; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Command\Descriptor\CliDescriptor; +use Symfony\Component\VarDumper\Command\Descriptor\DumpDescriptorInterface; +use Symfony\Component\VarDumper\Command\Descriptor\HtmlDescriptor; +use Symfony\Component\VarDumper\Dumper\CliDumper; +use Symfony\Component\VarDumper\Dumper\HtmlDumper; +use Symfony\Component\VarDumper\Server\DumpServer; + +/** + * Starts a dump server to collect and output dumps on a single place with multiple formats support. + * + * @author Maxime Steinhausser + * + * @final + */ +class ServerDumpCommand extends Command +{ + protected static $defaultName = 'server:dump'; + protected static $defaultDescription = 'Start a dump server that collects and displays dumps in a single place'; + + private $server; + + /** @var DumpDescriptorInterface[] */ + private $descriptors; + + public function __construct(DumpServer $server, array $descriptors = []) + { + $this->server = $server; + $this->descriptors = $descriptors + [ + 'cli' => new CliDescriptor(new CliDumper()), + 'html' => new HtmlDescriptor(new HtmlDumper()), + ]; + + parent::__construct(); + } + + protected function configure() + { + $this + ->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format (%s)', implode(', ', $this->getAvailableFormats())), 'cli') + ->setDescription(self::$defaultDescription) + ->setHelp(<<<'EOF' +%command.name% starts a dump server that collects and displays +dumps in a single place for debugging you application: + + php %command.full_name% + +You can consult dumped data in HTML format in your browser by providing the --format=html option +and redirecting the output to a file: + + php %command.full_name% --format="html" > dump.html + +EOF + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $format = $input->getOption('format'); + + if (!$descriptor = $this->descriptors[$format] ?? null) { + throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $format)); + } + + $errorIo = $io->getErrorStyle(); + $errorIo->title('Symfony Var Dumper Server'); + + $this->server->start(); + + $errorIo->success(sprintf('Server listening on %s', $this->server->getHost())); + $errorIo->comment('Quit the server with CONTROL-C.'); + + $this->server->listen(function (Data $data, array $context, int $clientId) use ($descriptor, $io) { + $descriptor->describe($io, $data, $context, $clientId); + }); + + return 0; + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ($input->mustSuggestOptionValuesFor('format')) { + $suggestions->suggestValues($this->getAvailableFormats()); + } + } + + private function getAvailableFormats(): array + { + return array_keys($this->descriptors); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/AbstractDumper.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/AbstractDumper.php new file mode 100644 index 0000000..66da669 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/AbstractDumper.php @@ -0,0 +1,202 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper; + +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Cloner\DumperInterface; + +/** + * Abstract mechanism for dumping a Data object. + * + * @author Nicolas Grekas + */ +abstract class AbstractDumper implements DataDumperInterface, DumperInterface +{ + public const DUMP_LIGHT_ARRAY = 1; + public const DUMP_STRING_LENGTH = 2; + public const DUMP_COMMA_SEPARATOR = 4; + public const DUMP_TRAILING_COMMA = 8; + + public static $defaultOutput = 'php://output'; + + protected $line = ''; + protected $lineDumper; + protected $outputStream; + protected $decimalPoint; // This is locale dependent + protected $indentPad = ' '; + protected $flags; + + private $charset = ''; + + /** + * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput + * @param string|null $charset The default character encoding to use for non-UTF8 strings + * @param int $flags A bit field of static::DUMP_* constants to fine tune dumps representation + */ + public function __construct($output = null, ?string $charset = null, int $flags = 0) + { + $this->flags = $flags; + $this->setCharset($charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8'); + $this->decimalPoint = \PHP_VERSION_ID >= 80000 ? '.' : localeconv()['decimal_point']; + $this->setOutput($output ?: static::$defaultOutput); + if (!$output && \is_string(static::$defaultOutput)) { + static::$defaultOutput = $this->outputStream; + } + } + + /** + * Sets the output destination of the dumps. + * + * @param callable|resource|string $output A line dumper callable, an opened stream or an output path + * + * @return callable|resource|string The previous output destination + */ + public function setOutput($output) + { + $prev = $this->outputStream ?? $this->lineDumper; + + if (\is_callable($output)) { + $this->outputStream = null; + $this->lineDumper = $output; + } else { + if (\is_string($output)) { + $output = fopen($output, 'w'); + } + $this->outputStream = $output; + $this->lineDumper = [$this, 'echoLine']; + } + + return $prev; + } + + /** + * Sets the default character encoding to use for non-UTF8 strings. + * + * @return string The previous charset + */ + public function setCharset(string $charset) + { + $prev = $this->charset; + + $charset = strtoupper($charset); + $charset = null === $charset || 'UTF-8' === $charset || 'UTF8' === $charset ? 'CP1252' : $charset; + + $this->charset = $charset; + + return $prev; + } + + /** + * Sets the indentation pad string. + * + * @param string $pad A string that will be prepended to dumped lines, repeated by nesting level + * + * @return string The previous indent pad + */ + public function setIndentPad(string $pad) + { + $prev = $this->indentPad; + $this->indentPad = $pad; + + return $prev; + } + + /** + * Dumps a Data object. + * + * @param callable|resource|string|true|null $output A line dumper callable, an opened stream, an output path or true to return the dump + * + * @return string|null The dump as string when $output is true + */ + public function dump(Data $data, $output = null) + { + $this->decimalPoint = \PHP_VERSION_ID >= 80000 ? '.' : localeconv()['decimal_point']; + + if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(\LC_NUMERIC, 0) : null) { + setlocale(\LC_NUMERIC, 'C'); + } + + if ($returnDump = true === $output) { + $output = fopen('php://memory', 'r+'); + } + if ($output) { + $prevOutput = $this->setOutput($output); + } + try { + $data->dump($this); + $this->dumpLine(-1); + + if ($returnDump) { + $result = stream_get_contents($output, -1, 0); + fclose($output); + + return $result; + } + } finally { + if ($output) { + $this->setOutput($prevOutput); + } + if ($locale) { + setlocale(\LC_NUMERIC, $locale); + } + } + + return null; + } + + /** + * Dumps the current line. + * + * @param int $depth The recursive depth in the dumped structure for the line being dumped, + * or -1 to signal the end-of-dump to the line dumper callable + */ + protected function dumpLine(int $depth) + { + ($this->lineDumper)($this->line, $depth, $this->indentPad); + $this->line = ''; + } + + /** + * Generic line dumper callback. + */ + protected function echoLine(string $line, int $depth, string $indentPad) + { + if (-1 !== $depth) { + fwrite($this->outputStream, str_repeat($indentPad, $depth).$line."\n"); + } + } + + /** + * Converts a non-UTF-8 string to UTF-8. + * + * @return string|null + */ + protected function utf8Encode(?string $s) + { + if (null === $s || preg_match('//u', $s)) { + return $s; + } + + if (!\function_exists('iconv')) { + throw new \RuntimeException('Unable to convert a non-UTF-8 string to UTF-8: required function iconv() does not exist. You should install ext-iconv or symfony/polyfill-iconv.'); + } + + if (false !== $c = @iconv($this->charset, 'UTF-8', $s)) { + return $c; + } + if ('CP1252' !== $this->charset && false !== $c = @iconv('CP1252', 'UTF-8', $s)) { + return $c; + } + + return iconv('CP850', 'UTF-8', $s); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/CliDumper.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/CliDumper.php new file mode 100644 index 0000000..3e86e4a --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/CliDumper.php @@ -0,0 +1,674 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper; + +use Symfony\Component\VarDumper\Cloner\Cursor; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * CliDumper dumps variables for command line output. + * + * @author Nicolas Grekas + */ +class CliDumper extends AbstractDumper +{ + public static $defaultColors; + public static $defaultOutput = 'php://stdout'; + + protected $colors; + protected $maxStringWidth = 0; + protected $styles = [ + // See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + 'default' => '0;38;5;208', + 'num' => '1;38;5;38', + 'const' => '1;38;5;208', + 'str' => '1;38;5;113', + 'note' => '38;5;38', + 'ref' => '38;5;247', + 'public' => '', + 'protected' => '', + 'private' => '', + 'meta' => '38;5;170', + 'key' => '38;5;113', + 'index' => '38;5;38', + ]; + + protected static $controlCharsRx = '/[\x00-\x1F\x7F]+/'; + protected static $controlCharsMap = [ + "\t" => '\t', + "\n" => '\n', + "\v" => '\v', + "\f" => '\f', + "\r" => '\r', + "\033" => '\e', + ]; + + protected $collapseNextHash = false; + protected $expandNextHash = false; + + private $displayOptions = [ + 'fileLinkFormat' => null, + ]; + + private $handlesHrefGracefully; + + /** + * {@inheritdoc} + */ + public function __construct($output = null, ?string $charset = null, int $flags = 0) + { + parent::__construct($output, $charset, $flags); + + if ('\\' === \DIRECTORY_SEPARATOR && !$this->isWindowsTrueColor()) { + // Use only the base 16 xterm colors when using ANSICON or standard Windows 10 CLI + $this->setStyles([ + 'default' => '31', + 'num' => '1;34', + 'const' => '1;31', + 'str' => '1;32', + 'note' => '34', + 'ref' => '1;30', + 'meta' => '35', + 'key' => '32', + 'index' => '34', + ]); + } + + $this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l'; + } + + /** + * Enables/disables colored output. + */ + public function setColors(bool $colors) + { + $this->colors = $colors; + } + + /** + * Sets the maximum number of characters per line for dumped strings. + */ + public function setMaxStringWidth(int $maxStringWidth) + { + $this->maxStringWidth = $maxStringWidth; + } + + /** + * Configures styles. + * + * @param array $styles A map of style names to style definitions + */ + public function setStyles(array $styles) + { + $this->styles = $styles + $this->styles; + } + + /** + * Configures display options. + * + * @param array $displayOptions A map of display options to customize the behavior + */ + public function setDisplayOptions(array $displayOptions) + { + $this->displayOptions = $displayOptions + $this->displayOptions; + } + + /** + * {@inheritdoc} + */ + public function dumpScalar(Cursor $cursor, string $type, $value) + { + $this->dumpKey($cursor); + $this->collapseNextHash = $this->expandNextHash = false; + + $style = 'const'; + $attr = $cursor->attr; + + switch ($type) { + case 'default': + $style = 'default'; + break; + + case 'integer': + $style = 'num'; + + if (isset($this->styles['integer'])) { + $style = 'integer'; + } + + break; + + case 'double': + $style = 'num'; + + if (isset($this->styles['float'])) { + $style = 'float'; + } + + switch (true) { + case \INF === $value: $value = 'INF'; break; + case -\INF === $value: $value = '-INF'; break; + case is_nan($value): $value = 'NAN'; break; + default: + $value = (string) $value; + if (!str_contains($value, $this->decimalPoint)) { + $value .= $this->decimalPoint.'0'; + } + break; + } + break; + + case 'NULL': + $value = 'null'; + break; + + case 'boolean': + $value = $value ? 'true' : 'false'; + break; + + default: + $attr += ['value' => $this->utf8Encode($value)]; + $value = $this->utf8Encode($type); + break; + } + + $this->line .= $this->style($style, $value, $attr); + + $this->endValue($cursor); + } + + /** + * {@inheritdoc} + */ + public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut) + { + $this->dumpKey($cursor); + $this->collapseNextHash = $this->expandNextHash = false; + $attr = $cursor->attr; + + if ($bin) { + $str = $this->utf8Encode($str); + } + if ('' === $str) { + $this->line .= '""'; + if ($cut) { + $this->line .= '…'.$cut; + } + $this->endValue($cursor); + } else { + $attr += [ + 'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0, + 'binary' => $bin, + ]; + $str = $bin && false !== strpos($str, "\0") ? [$str] : explode("\n", $str); + if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) { + unset($str[1]); + $str[0] .= "\n"; + } + $m = \count($str) - 1; + $i = $lineCut = 0; + + if (self::DUMP_STRING_LENGTH & $this->flags) { + $this->line .= '('.$attr['length'].') '; + } + if ($bin) { + $this->line .= 'b'; + } + + if ($m) { + $this->line .= '"""'; + $this->dumpLine($cursor->depth); + } else { + $this->line .= '"'; + } + + foreach ($str as $str) { + if ($i < $m) { + $str .= "\n"; + } + if (0 < $this->maxStringWidth && $this->maxStringWidth < $len = mb_strlen($str, 'UTF-8')) { + $str = mb_substr($str, 0, $this->maxStringWidth, 'UTF-8'); + $lineCut = $len - $this->maxStringWidth; + } + if ($m && 0 < $cursor->depth) { + $this->line .= $this->indentPad; + } + if ('' !== $str) { + $this->line .= $this->style('str', $str, $attr); + } + if ($i++ == $m) { + if ($m) { + if ('' !== $str) { + $this->dumpLine($cursor->depth); + if (0 < $cursor->depth) { + $this->line .= $this->indentPad; + } + } + $this->line .= '"""'; + } else { + $this->line .= '"'; + } + if ($cut < 0) { + $this->line .= '…'; + $lineCut = 0; + } elseif ($cut) { + $lineCut += $cut; + } + } + if ($lineCut) { + $this->line .= '…'.$lineCut; + $lineCut = 0; + } + + if ($i > $m) { + $this->endValue($cursor); + } else { + $this->dumpLine($cursor->depth); + } + } + } + } + + /** + * {@inheritdoc} + */ + public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild) + { + if (null === $this->colors) { + $this->colors = $this->supportsColors(); + } + + $this->dumpKey($cursor); + $this->expandNextHash = false; + $attr = $cursor->attr; + + if ($this->collapseNextHash) { + $cursor->skipChildren = true; + $this->collapseNextHash = $hasChild = false; + } + + $class = $this->utf8Encode($class); + if (Cursor::HASH_OBJECT === $type) { + $prefix = $class && 'stdClass' !== $class ? $this->style('note', $class, $attr).(empty($attr['cut_hash']) ? ' {' : '') : '{'; + } elseif (Cursor::HASH_RESOURCE === $type) { + $prefix = $this->style('note', $class.' resource', $attr).($hasChild ? ' {' : ' '); + } else { + $prefix = $class && !(self::DUMP_LIGHT_ARRAY & $this->flags) ? $this->style('note', 'array:'.$class).' [' : '['; + } + + if (($cursor->softRefCount || 0 < $cursor->softRefHandle) && empty($attr['cut_hash'])) { + $prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), ['count' => $cursor->softRefCount]); + } elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) { + $prefix .= $this->style('ref', '&'.$cursor->hardRefTo, ['count' => $cursor->hardRefCount]); + } elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) { + $prefix = substr($prefix, 0, -1); + } + + $this->line .= $prefix; + + if ($hasChild) { + $this->dumpLine($cursor->depth); + } + } + + /** + * {@inheritdoc} + */ + public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut) + { + if (empty($cursor->attr['cut_hash'])) { + $this->dumpEllipsis($cursor, $hasChild, $cut); + $this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : '')); + } + + $this->endValue($cursor); + } + + /** + * Dumps an ellipsis for cut children. + * + * @param bool $hasChild When the dump of the hash has child item + * @param int $cut The number of items the hash has been cut by + */ + protected function dumpEllipsis(Cursor $cursor, bool $hasChild, int $cut) + { + if ($cut) { + $this->line .= ' …'; + if (0 < $cut) { + $this->line .= $cut; + } + if ($hasChild) { + $this->dumpLine($cursor->depth + 1); + } + } + } + + /** + * Dumps a key in a hash structure. + */ + protected function dumpKey(Cursor $cursor) + { + if (null !== $key = $cursor->hashKey) { + if ($cursor->hashKeyIsBinary) { + $key = $this->utf8Encode($key); + } + $attr = ['binary' => $cursor->hashKeyIsBinary]; + $bin = $cursor->hashKeyIsBinary ? 'b' : ''; + $style = 'key'; + switch ($cursor->hashType) { + default: + case Cursor::HASH_INDEXED: + if (self::DUMP_LIGHT_ARRAY & $this->flags) { + break; + } + $style = 'index'; + // no break + case Cursor::HASH_ASSOC: + if (\is_int($key)) { + $this->line .= $this->style($style, $key).' => '; + } else { + $this->line .= $bin.'"'.$this->style($style, $key).'" => '; + } + break; + + case Cursor::HASH_RESOURCE: + $key = "\0~\0".$key; + // no break + case Cursor::HASH_OBJECT: + if (!isset($key[0]) || "\0" !== $key[0]) { + $this->line .= '+'.$bin.$this->style('public', $key).': '; + } elseif (0 < strpos($key, "\0", 1)) { + $key = explode("\0", substr($key, 1), 2); + + switch ($key[0][0]) { + case '+': // User inserted keys + $attr['dynamic'] = true; + $this->line .= '+'.$bin.'"'.$this->style('public', $key[1], $attr).'": '; + break 2; + case '~': + $style = 'meta'; + if (isset($key[0][1])) { + parse_str(substr($key[0], 1), $attr); + $attr += ['binary' => $cursor->hashKeyIsBinary]; + } + break; + case '*': + $style = 'protected'; + $bin = '#'.$bin; + break; + default: + $attr['class'] = $key[0]; + $style = 'private'; + $bin = '-'.$bin; + break; + } + + if (isset($attr['collapse'])) { + if ($attr['collapse']) { + $this->collapseNextHash = true; + } else { + $this->expandNextHash = true; + } + } + + $this->line .= $bin.$this->style($style, $key[1], $attr).($attr['separator'] ?? ': '); + } else { + // This case should not happen + $this->line .= '-'.$bin.'"'.$this->style('private', $key, ['class' => '']).'": '; + } + break; + } + + if ($cursor->hardRefTo) { + $this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), ['count' => $cursor->hardRefCount]).' '; + } + } + } + + /** + * Decorates a value with some style. + * + * @param string $style The type of style being applied + * @param string $value The value being styled + * @param array $attr Optional context information + * + * @return string + */ + protected function style(string $style, string $value, array $attr = []) + { + if (null === $this->colors) { + $this->colors = $this->supportsColors(); + } + + if (null === $this->handlesHrefGracefully) { + $this->handlesHrefGracefully = 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR') + && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100) + && !isset($_SERVER['IDEA_INITIAL_DIRECTORY']); + } + + if (isset($attr['ellipsis'], $attr['ellipsis-type'])) { + $prefix = substr($value, 0, -$attr['ellipsis']); + if ('cli' === \PHP_SAPI && 'path' === $attr['ellipsis-type'] && isset($_SERVER[$pwd = '\\' === \DIRECTORY_SEPARATOR ? 'CD' : 'PWD']) && str_starts_with($prefix, $_SERVER[$pwd])) { + $prefix = '.'.substr($prefix, \strlen($_SERVER[$pwd])); + } + if (!empty($attr['ellipsis-tail'])) { + $prefix .= substr($value, -$attr['ellipsis'], $attr['ellipsis-tail']); + $value = substr($value, -$attr['ellipsis'] + $attr['ellipsis-tail']); + } else { + $value = substr($value, -$attr['ellipsis']); + } + + $value = $this->style('default', $prefix).$this->style($style, $value); + + goto href; + } + + $map = static::$controlCharsMap; + $startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : ''; + $endCchr = $this->colors ? "\033[m\033[{$this->styles[$style]}m" : ''; + $value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) { + $s = $startCchr; + $c = $c[$i = 0]; + do { + $s .= $map[$c[$i]] ?? sprintf('\x%02X', \ord($c[$i])); + } while (isset($c[++$i])); + + return $s.$endCchr; + }, $value, -1, $cchrCount); + + if ($this->colors) { + if ($cchrCount && "\033" === $value[0]) { + $value = substr($value, \strlen($startCchr)); + } else { + $value = "\033[{$this->styles[$style]}m".$value; + } + if ($cchrCount && str_ends_with($value, $endCchr)) { + $value = substr($value, 0, -\strlen($endCchr)); + } else { + $value .= "\033[{$this->styles['default']}m"; + } + } + + href: + if ($this->colors && $this->handlesHrefGracefully) { + if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) { + if ('note' === $style) { + $value .= "\033]8;;{$href}\033\\^\033]8;;\033\\"; + } else { + $attr['href'] = $href; + } + } + if (isset($attr['href'])) { + $value = "\033]8;;{$attr['href']}\033\\{$value}\033]8;;\033\\"; + } + } elseif ($attr['if_links'] ?? false) { + return ''; + } + + return $value; + } + + /** + * @return bool + */ + protected function supportsColors() + { + if ($this->outputStream !== static::$defaultOutput) { + return $this->hasColorSupport($this->outputStream); + } + if (null !== static::$defaultColors) { + return static::$defaultColors; + } + if (isset($_SERVER['argv'][1])) { + $colors = $_SERVER['argv']; + $i = \count($colors); + while (--$i > 0) { + if (isset($colors[$i][5])) { + switch ($colors[$i]) { + case '--ansi': + case '--color': + case '--color=yes': + case '--color=force': + case '--color=always': + case '--colors=always': + return static::$defaultColors = true; + + case '--no-ansi': + case '--color=no': + case '--color=none': + case '--color=never': + case '--colors=never': + return static::$defaultColors = false; + } + } + } + } + + $h = stream_get_meta_data($this->outputStream) + ['wrapper_type' => null]; + $h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'w') : $this->outputStream; + + return static::$defaultColors = $this->hasColorSupport($h); + } + + /** + * {@inheritdoc} + */ + protected function dumpLine(int $depth, bool $endOfValue = false) + { + if (null === $this->colors) { + $this->colors = $this->supportsColors(); + } + + if ($this->colors) { + $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line); + } + parent::dumpLine($depth); + } + + protected function endValue(Cursor $cursor) + { + if (-1 === $cursor->hashType) { + return; + } + + if (Stub::ARRAY_INDEXED === $cursor->hashType || Stub::ARRAY_ASSOC === $cursor->hashType) { + if (self::DUMP_TRAILING_COMMA & $this->flags && 0 < $cursor->depth) { + $this->line .= ','; + } elseif (self::DUMP_COMMA_SEPARATOR & $this->flags && 1 < $cursor->hashLength - $cursor->hashIndex) { + $this->line .= ','; + } + } + + $this->dumpLine($cursor->depth, true); + } + + /** + * Returns true if the stream supports colorization. + * + * Reference: Composer\XdebugHandler\Process::supportsColor + * https://github.com/composer/xdebug-handler + * + * @param mixed $stream A CLI output stream + */ + private function hasColorSupport($stream): bool + { + if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) { + return false; + } + + // Follow https://no-color.org/ + if (isset($_SERVER['NO_COLOR']) || false !== getenv('NO_COLOR')) { + return false; + } + + // Detect msysgit/mingw and assume this is a tty because detection + // does not work correctly, see https://github.com/composer/composer/issues/9690 + if (!@stream_isatty($stream) && !\in_array(strtoupper((string) getenv('MSYSTEM')), ['MINGW32', 'MINGW64'], true)) { + return false; + } + + if ('\\' === \DIRECTORY_SEPARATOR && @sapi_windows_vt100_support($stream)) { + return true; + } + + if ('Hyper' === getenv('TERM_PROGRAM') + || false !== getenv('COLORTERM') + || false !== getenv('ANSICON') + || 'ON' === getenv('ConEmuANSI') + ) { + return true; + } + + if ('dumb' === $term = (string) getenv('TERM')) { + return false; + } + + // See https://github.com/chalk/supports-color/blob/d4f413efaf8da045c5ab440ed418ef02dbb28bf1/index.js#L157 + return preg_match('/^((screen|xterm|vt100|vt220|putty|rxvt|ansi|cygwin|linux).*)|(.*-256(color)?(-bce)?)$/', $term); + } + + /** + * Returns true if the Windows terminal supports true color. + * + * Note that this does not check an output stream, but relies on environment + * variables from known implementations, or a PHP and Windows version that + * supports true color. + */ + private function isWindowsTrueColor(): bool + { + $result = 183 <= getenv('ANSICON_VER') + || 'ON' === getenv('ConEmuANSI') + || 'xterm' === getenv('TERM') + || 'Hyper' === getenv('TERM_PROGRAM'); + + if (!$result) { + $version = sprintf( + '%s.%s.%s', + PHP_WINDOWS_VERSION_MAJOR, + PHP_WINDOWS_VERSION_MINOR, + PHP_WINDOWS_VERSION_BUILD + ); + $result = $version >= '10.0.15063'; + } + + return $result; + } + + private function getSourceLink(string $file, int $line) + { + if ($fmt = $this->displayOptions['fileLinkFormat']) { + return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : ($fmt->format($file, $line) ?: 'file://'.$file.'#L'.$line); + } + + return false; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/CliContextProvider.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/CliContextProvider.php new file mode 100644 index 0000000..38f8789 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/CliContextProvider.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper\ContextProvider; + +/** + * Tries to provide context on CLI. + * + * @author Maxime Steinhausser + */ +final class CliContextProvider implements ContextProviderInterface +{ + public function getContext(): ?array + { + if ('cli' !== \PHP_SAPI) { + return null; + } + + return [ + 'command_line' => $commandLine = implode(' ', $_SERVER['argv'] ?? []), + 'identifier' => hash('crc32b', $commandLine.$_SERVER['REQUEST_TIME_FLOAT']), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/ContextProviderInterface.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/ContextProviderInterface.php new file mode 100644 index 0000000..532aa0f --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/ContextProviderInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper\ContextProvider; + +/** + * Interface to provide contextual data about dump data clones sent to a server. + * + * @author Maxime Steinhausser + */ +interface ContextProviderInterface +{ + public function getContext(): ?array; +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.php new file mode 100644 index 0000000..3684a47 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.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\VarDumper\Dumper\ContextProvider; + +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\VarDumper\Caster\ReflectionCaster; +use Symfony\Component\VarDumper\Cloner\VarCloner; + +/** + * Tries to provide context from a request. + * + * @author Maxime Steinhausser + */ +final class RequestContextProvider implements ContextProviderInterface +{ + private $requestStack; + private $cloner; + + public function __construct(RequestStack $requestStack) + { + $this->requestStack = $requestStack; + $this->cloner = new VarCloner(); + $this->cloner->setMaxItems(0); + $this->cloner->addCasters(ReflectionCaster::UNSET_CLOSURE_FILE_INFO); + } + + public function getContext(): ?array + { + if (null === $request = $this->requestStack->getCurrentRequest()) { + return null; + } + + $controller = $request->attributes->get('_controller'); + + return [ + 'uri' => $request->getUri(), + 'method' => $request->getMethod(), + 'controller' => $controller ? $this->cloner->cloneVar($controller) : $controller, + 'identifier' => spl_object_hash($request), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.php new file mode 100644 index 0000000..dee887e --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.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 Symfony\Component\VarDumper\Dumper\ContextProvider; + +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\HtmlDumper; +use Symfony\Component\VarDumper\VarDumper; +use Twig\Template; + +/** + * Tries to provide context from sources (class name, file, line, code excerpt, ...). + * + * @author Nicolas Grekas + * @author Maxime Steinhausser + */ +final class SourceContextProvider implements ContextProviderInterface +{ + private $limit; + private $charset; + private $projectDir; + private $fileLinkFormatter; + + public function __construct(?string $charset = null, ?string $projectDir = null, ?FileLinkFormatter $fileLinkFormatter = null, int $limit = 9) + { + $this->charset = $charset; + $this->projectDir = $projectDir; + $this->fileLinkFormatter = $fileLinkFormatter; + $this->limit = $limit; + } + + public function getContext(): ?array + { + $trace = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, $this->limit); + + $file = $trace[1]['file']; + $line = $trace[1]['line']; + $name = '-' === $file || 'Standard input code' === $file ? 'Standard input code' : false; + $fileExcerpt = false; + + for ($i = 2; $i < $this->limit; ++$i) { + if (isset($trace[$i]['class'], $trace[$i]['function']) + && 'dump' === $trace[$i]['function'] + && VarDumper::class === $trace[$i]['class'] + ) { + $file = $trace[$i]['file'] ?? $file; + $line = $trace[$i]['line'] ?? $line; + + while (++$i < $this->limit) { + if (isset($trace[$i]['function'], $trace[$i]['file']) && empty($trace[$i]['class']) && !str_starts_with($trace[$i]['function'], 'call_user_func')) { + $file = $trace[$i]['file']; + $line = $trace[$i]['line']; + + break; + } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) { + $template = $trace[$i]['object']; + $name = $template->getTemplateName(); + $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false); + $info = $template->getDebugInfo(); + if (isset($info[$trace[$i - 1]['line']])) { + $line = $info[$trace[$i - 1]['line']]; + $file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null; + + if ($src) { + $src = explode("\n", $src); + $fileExcerpt = []; + + for ($i = max($line - 3, 1), $max = min($line + 3, \count($src)); $i <= $max; ++$i) { + $fileExcerpt[] = ''.$this->htmlEncode($src[$i - 1]).''; + } + + $fileExcerpt = '
      '.implode("\n", $fileExcerpt).'
    '; + } + } + break; + } + } + break; + } + } + + if (false === $name) { + $name = str_replace('\\', '/', $file); + $name = substr($name, strrpos($name, '/') + 1); + } + + $context = ['name' => $name, 'file' => $file, 'line' => $line]; + $context['file_excerpt'] = $fileExcerpt; + + if (null !== $this->projectDir) { + $context['project_dir'] = $this->projectDir; + if (str_starts_with($file, $this->projectDir)) { + $context['file_relative'] = ltrim(substr($file, \strlen($this->projectDir)), \DIRECTORY_SEPARATOR); + } + } + + if ($this->fileLinkFormatter && $fileLink = $this->fileLinkFormatter->format($context['file'], $context['line'])) { + $context['file_link'] = $fileLink; + } + + return $context; + } + + private function htmlEncode(string $s): string + { + $html = ''; + + $dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset); + $dumper->setDumpHeader(''); + $dumper->setDumpBoundaries('', ''); + + $cloner = new VarCloner(); + $dumper->dump($cloner->cloneVar($s)); + + return substr(strip_tags($html), 1, -1); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php new file mode 100644 index 0000000..7638417 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper; + +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface; + +/** + * @author Kévin Thérage + */ +class ContextualizedDumper implements DataDumperInterface +{ + private $wrappedDumper; + private $contextProviders; + + /** + * @param ContextProviderInterface[] $contextProviders + */ + public function __construct(DataDumperInterface $wrappedDumper, array $contextProviders) + { + $this->wrappedDumper = $wrappedDumper; + $this->contextProviders = $contextProviders; + } + + public function dump(Data $data) + { + $context = []; + foreach ($this->contextProviders as $contextProvider) { + $context[\get_class($contextProvider)] = $contextProvider->getContext(); + } + + $this->wrappedDumper->dump($data->withContext($context)); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php new file mode 100644 index 0000000..b173bcc --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper; + +use Symfony\Component\VarDumper\Cloner\Data; + +/** + * DataDumperInterface for dumping Data objects. + * + * @author Nicolas Grekas + */ +interface DataDumperInterface +{ + public function dump(Data $data); +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/HtmlDumper.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/HtmlDumper.php new file mode 100644 index 0000000..55030cf --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/HtmlDumper.php @@ -0,0 +1,986 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper; + +use Symfony\Component\VarDumper\Cloner\Cursor; +use Symfony\Component\VarDumper\Cloner\Data; + +/** + * HtmlDumper dumps variables as HTML. + * + * @author Nicolas Grekas + */ +class HtmlDumper extends CliDumper +{ + public static $defaultOutput = 'php://output'; + + protected static $themes = [ + 'dark' => [ + 'default' => 'background-color:#18171B; color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: break-all', + 'num' => 'font-weight:bold; color:#1299DA', + 'const' => 'font-weight:bold', + 'str' => 'font-weight:bold; color:#56DB3A', + 'note' => 'color:#1299DA', + 'ref' => 'color:#A0A0A0', + 'public' => 'color:#FFFFFF', + 'protected' => 'color:#FFFFFF', + 'private' => 'color:#FFFFFF', + 'meta' => 'color:#B729D9', + 'key' => 'color:#56DB3A', + 'index' => 'color:#1299DA', + 'ellipsis' => 'color:#FF8400', + 'ns' => 'user-select:none;', + ], + 'light' => [ + 'default' => 'background:none; color:#CC7832; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: break-all', + 'num' => 'font-weight:bold; color:#1299DA', + 'const' => 'font-weight:bold', + 'str' => 'font-weight:bold; color:#629755;', + 'note' => 'color:#6897BB', + 'ref' => 'color:#6E6E6E', + 'public' => 'color:#262626', + 'protected' => 'color:#262626', + 'private' => 'color:#262626', + 'meta' => 'color:#B729D9', + 'key' => 'color:#789339', + 'index' => 'color:#1299DA', + 'ellipsis' => 'color:#CC7832', + 'ns' => 'user-select:none;', + ], + ]; + + protected $dumpHeader; + protected $dumpPrefix = '
    ';
    +    protected $dumpSuffix = '
    '; + protected $dumpId = 'sf-dump'; + protected $colors = true; + protected $headerIsDumped = false; + protected $lastDepth = -1; + protected $styles; + + private $displayOptions = [ + 'maxDepth' => 1, + 'maxStringLength' => 160, + 'fileLinkFormat' => null, + ]; + private $extraDisplayOptions = []; + + /** + * {@inheritdoc} + */ + public function __construct($output = null, ?string $charset = null, int $flags = 0) + { + AbstractDumper::__construct($output, $charset, $flags); + $this->dumpId = 'sf-dump-'.mt_rand(); + $this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'); + $this->styles = static::$themes['dark'] ?? self::$themes['dark']; + } + + /** + * {@inheritdoc} + */ + public function setStyles(array $styles) + { + $this->headerIsDumped = false; + $this->styles = $styles + $this->styles; + } + + public function setTheme(string $themeName) + { + if (!isset(static::$themes[$themeName])) { + throw new \InvalidArgumentException(sprintf('Theme "%s" does not exist in class "%s".', $themeName, static::class)); + } + + $this->setStyles(static::$themes[$themeName]); + } + + /** + * Configures display options. + * + * @param array $displayOptions A map of display options to customize the behavior + */ + public function setDisplayOptions(array $displayOptions) + { + $this->headerIsDumped = false; + $this->displayOptions = $displayOptions + $this->displayOptions; + } + + /** + * Sets an HTML header that will be dumped once in the output stream. + */ + public function setDumpHeader(?string $header) + { + $this->dumpHeader = $header; + } + + /** + * Sets an HTML prefix and suffix that will encapse every single dump. + */ + public function setDumpBoundaries(string $prefix, string $suffix) + { + $this->dumpPrefix = $prefix; + $this->dumpSuffix = $suffix; + } + + /** + * {@inheritdoc} + */ + public function dump(Data $data, $output = null, array $extraDisplayOptions = []) + { + $this->extraDisplayOptions = $extraDisplayOptions; + $result = parent::dump($data, $output); + $this->dumpId = 'sf-dump-'.mt_rand(); + + return $result; + } + + /** + * Dumps the HTML header. + */ + protected function getDumpHeader() + { + $this->headerIsDumped = $this->outputStream ?? $this->lineDumper; + + if (null !== $this->dumpHeader) { + return $this->dumpHeader; + } + + $line = str_replace('{$options}', json_encode($this->displayOptions, \JSON_FORCE_OBJECT), <<<'EOHTML' +'.$this->dumpHeader; + } + + /** + * {@inheritdoc} + */ + public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut) + { + if ('' === $str && isset($cursor->attr['img-data'], $cursor->attr['content-type'])) { + $this->dumpKey($cursor); + $this->line .= $this->style('default', $cursor->attr['img-size'] ?? '', []); + $this->line .= $cursor->depth >= $this->displayOptions['maxDepth'] ? ' ' : ' '; + $this->endValue($cursor); + $this->line .= $this->indentPad; + $this->line .= sprintf('', $cursor->attr['content-type'], base64_encode($cursor->attr['img-data'])); + $this->endValue($cursor); + } else { + parent::dumpString($cursor, $str, $bin, $cut); + } + } + + /** + * {@inheritdoc} + */ + public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild) + { + if (Cursor::HASH_OBJECT === $type) { + $cursor->attr['depth'] = $cursor->depth; + } + parent::enterHash($cursor, $type, $class, false); + + if ($cursor->skipChildren || $cursor->depth >= $this->displayOptions['maxDepth']) { + $cursor->skipChildren = false; + $eol = ' class=sf-dump-compact>'; + } else { + $this->expandNextHash = false; + $eol = ' class=sf-dump-expanded>'; + } + + if ($hasChild) { + $this->line .= 'dumpId, $r); + } + $this->line .= $eol; + $this->dumpLine($cursor->depth); + } + } + + /** + * {@inheritdoc} + */ + public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut) + { + $this->dumpEllipsis($cursor, $hasChild, $cut); + if ($hasChild) { + $this->line .= ''; + } + parent::leaveHash($cursor, $type, $class, $hasChild, 0); + } + + /** + * {@inheritdoc} + */ + protected function style(string $style, string $value, array $attr = []) + { + if ('' === $value) { + return ''; + } + + $v = esc($value); + + if ('ref' === $style) { + if (empty($attr['count'])) { + return sprintf('%s', $v); + } + $r = ('#' !== $v[0] ? 1 - ('@' !== $v[0]) : 2).substr($value, 1); + + return sprintf('%s', $this->dumpId, $r, 1 + $attr['count'], $v); + } + + if ('const' === $style && isset($attr['value'])) { + $style .= sprintf(' title="%s"', esc(\is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value']))); + } elseif ('public' === $style) { + $style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property'); + } elseif ('str' === $style && 1 < $attr['length']) { + $style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : ''); + } elseif ('note' === $style && 0 < ($attr['depth'] ?? 0) && false !== $c = strrpos($value, '\\')) { + $style .= ' title=""'; + $attr += [ + 'ellipsis' => \strlen($value) - $c, + 'ellipsis-type' => 'note', + 'ellipsis-tail' => 1, + ]; + } elseif ('protected' === $style) { + $style .= ' title="Protected property"'; + } elseif ('meta' === $style && isset($attr['title'])) { + $style .= sprintf(' title="%s"', esc($this->utf8Encode($attr['title']))); + } elseif ('private' === $style) { + $style .= sprintf(' title="Private property defined in class: `%s`"', esc($this->utf8Encode($attr['class']))); + } + $map = static::$controlCharsMap; + + if (isset($attr['ellipsis'])) { + $class = 'sf-dump-ellipsis'; + if (isset($attr['ellipsis-type'])) { + $class = sprintf('"%s sf-dump-ellipsis-%s"', $class, $attr['ellipsis-type']); + } + $label = esc(substr($value, -$attr['ellipsis'])); + $style = str_replace(' title="', " title=\"$v\n", $style); + $v = sprintf('%s', $class, substr($v, 0, -\strlen($label))); + + if (!empty($attr['ellipsis-tail'])) { + $tail = \strlen(esc(substr($value, -$attr['ellipsis'], $attr['ellipsis-tail']))); + $v .= sprintf('%s%s', $class, substr($label, 0, $tail), substr($label, $tail)); + } else { + $v .= $label; + } + } + + $v = "".preg_replace_callback(static::$controlCharsRx, function ($c) use ($map) { + $s = $b = ''; + }, $v).''; + + if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) { + $attr['href'] = $href; + } + if (isset($attr['href'])) { + $target = isset($attr['file']) ? '' : ' target="_blank"'; + $v = sprintf('%s', esc($this->utf8Encode($attr['href'])), $target, $v); + } + if (isset($attr['lang'])) { + $v = sprintf('%s', esc($attr['lang']), $v); + } + + return $v; + } + + /** + * {@inheritdoc} + */ + protected function dumpLine(int $depth, bool $endOfValue = false) + { + if (-1 === $this->lastDepth) { + $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line; + } + if ($this->headerIsDumped !== ($this->outputStream ?? $this->lineDumper)) { + $this->line = $this->getDumpHeader().$this->line; + } + + if (-1 === $depth) { + $args = ['"'.$this->dumpId.'"']; + if ($this->extraDisplayOptions) { + $args[] = json_encode($this->extraDisplayOptions, \JSON_FORCE_OBJECT); + } + // Replace is for BC + $this->line .= sprintf(str_replace('"%s"', '%s', $this->dumpSuffix), implode(', ', $args)); + } + $this->lastDepth = $depth; + + $this->line = mb_encode_numericentity($this->line, [0x80, 0x10FFFF, 0, 0x1FFFFF], 'UTF-8'); + + if (-1 === $depth) { + AbstractDumper::dumpLine(0); + } + AbstractDumper::dumpLine($depth); + } + + private function getSourceLink(string $file, int $line) + { + $options = $this->extraDisplayOptions + $this->displayOptions; + + if ($fmt = $options['fileLinkFormat']) { + return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line); + } + + return false; + } +} + +function esc(string $str) +{ + return htmlspecialchars($str, \ENT_QUOTES, 'UTF-8'); +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ServerDumper.php b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ServerDumper.php new file mode 100644 index 0000000..b8871b0 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Dumper/ServerDumper.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Dumper; + +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface; +use Symfony\Component\VarDumper\Server\Connection; + +/** + * ServerDumper forwards serialized Data clones to a server. + * + * @author Maxime Steinhausser + */ +class ServerDumper implements DataDumperInterface +{ + private $connection; + private $wrappedDumper; + + /** + * @param string $host The server host + * @param DataDumperInterface|null $wrappedDumper A wrapped instance used whenever we failed contacting the server + * @param ContextProviderInterface[] $contextProviders Context providers indexed by context name + */ + public function __construct(string $host, ?DataDumperInterface $wrappedDumper = null, array $contextProviders = []) + { + $this->connection = new Connection($host, $contextProviders); + $this->wrappedDumper = $wrappedDumper; + } + + public function getContextProviders(): array + { + return $this->connection->getContextProviders(); + } + + /** + * {@inheritdoc} + */ + public function dump(Data $data) + { + if (!$this->connection->write($data) && $this->wrappedDumper) { + $this->wrappedDumper->dump($data); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Exception/ThrowingCasterException.php b/php/libraries/composer/vendor/symfony/var-dumper/Exception/ThrowingCasterException.php new file mode 100644 index 0000000..122f0d3 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Exception/ThrowingCasterException.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\VarDumper\Exception; + +/** + * @author Nicolas Grekas + */ +class ThrowingCasterException extends \Exception +{ + /** + * @param \Throwable $prev The exception thrown from the caster + */ + public function __construct(\Throwable $prev) + { + parent::__construct('Unexpected '.\get_class($prev).' thrown from a caster: '.$prev->getMessage(), 0, $prev); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/LICENSE b/php/libraries/composer/vendor/symfony/var-dumper/LICENSE new file mode 100644 index 0000000..29f72d5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/php/libraries/composer/vendor/symfony/var-dumper/README.md b/php/libraries/composer/vendor/symfony/var-dumper/README.md new file mode 100644 index 0000000..a0da8c9 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/README.md @@ -0,0 +1,15 @@ +VarDumper Component +=================== + +The VarDumper component provides mechanisms for walking through any arbitrary +PHP variable. It provides a better `dump()` function that you can use instead +of `var_dump()`. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/var_dumper/introduction.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Resources/bin/var-dump-server b/php/libraries/composer/vendor/symfony/var-dumper/Resources/bin/var-dump-server new file mode 100755 index 0000000..f398fce --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Resources/bin/var-dump-server @@ -0,0 +1,67 @@ +#!/usr/bin/env php + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if ('cli' !== PHP_SAPI) { + throw new Exception('This script must be run from the command line.'); +} + +/** + * Starts a dump server to collect and output dumps on a single place with multiple formats support. + * + * @author Maxime Steinhausser + */ + +use Psr\Log\LoggerInterface; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Logger\ConsoleLogger; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\VarDumper\Command\ServerDumpCommand; +use Symfony\Component\VarDumper\Server\DumpServer; + +function includeIfExists(string $file): bool +{ + return file_exists($file) && include $file; +} + +if ( + !includeIfExists(__DIR__ . '/../../../../autoload.php') && + !includeIfExists(__DIR__ . '/../../vendor/autoload.php') && + !includeIfExists(__DIR__ . '/../../../../../../vendor/autoload.php') +) { + fwrite(STDERR, 'Install dependencies using Composer.'.PHP_EOL); + exit(1); +} + +if (!class_exists(Application::class)) { + fwrite(STDERR, 'You need the "symfony/console" component in order to run the VarDumper server.'.PHP_EOL); + exit(1); +} + +$input = new ArgvInput(); +$output = new ConsoleOutput(); +$defaultHost = '127.0.0.1:9912'; +$host = $input->getParameterOption(['--host'], $_SERVER['VAR_DUMPER_SERVER'] ?? $defaultHost, true); +$logger = interface_exists(LoggerInterface::class) ? new ConsoleLogger($output->getErrorOutput()) : null; + +$app = new Application(); + +$app->getDefinition()->addOption( + new InputOption('--host', null, InputOption::VALUE_REQUIRED, 'The address the server should listen to', $defaultHost) +); + +$app->add($command = new ServerDumpCommand(new DumpServer($host, $logger))) + ->getApplication() + ->setDefaultCommand($command->getName(), true) + ->run($input, $output) +; diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Resources/css/htmlDescriptor.css b/php/libraries/composer/vendor/symfony/var-dumper/Resources/css/htmlDescriptor.css new file mode 100644 index 0000000..8f706d6 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Resources/css/htmlDescriptor.css @@ -0,0 +1,130 @@ +body { + display: flex; + flex-direction: column-reverse; + justify-content: flex-end; + max-width: 1140px; + margin: auto; + padding: 15px; + word-wrap: break-word; + background-color: #F9F9F9; + color: #222; + font-family: Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.4; +} +p { + margin: 0; +} +a { + color: #218BC3; + text-decoration: none; +} +a:hover { + text-decoration: underline; +} +.text-small { + font-size: 12px !important; +} +article { + margin: 5px; + margin-bottom: 10px; +} +article > header > .row { + display: flex; + flex-direction: row; + align-items: baseline; + margin-bottom: 10px; +} +article > header > .row > .col { + flex: 1; + display: flex; + align-items: baseline; +} +article > header > .row > h2 { + font-size: 14px; + color: #222; + font-weight: normal; + font-family: "Lucida Console", monospace, sans-serif; + word-break: break-all; + margin: 20px 5px 0 0; + user-select: all; +} +article > header > .row > h2 > code { + white-space: nowrap; + user-select: none; + color: #cc2255; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; + border-radius: 3px; + margin-right: 5px; + padding: 0 3px; +} +article > header > .row > time.col { + flex: 0; + text-align: right; + white-space: nowrap; + color: #999; + font-style: italic; +} +article > header ul.tags { + list-style: none; + padding: 0; + margin: 0; + font-size: 12px; +} +article > header ul.tags > li { + user-select: all; + margin-bottom: 2px; +} +article > header ul.tags > li > span.badge { + display: inline-block; + padding: .25em .4em; + margin-right: 5px; + border-radius: 4px; + background-color: #6c757d3b; + color: #524d4d; + font-size: 12px; + text-align: center; + font-weight: 700; + line-height: 1; + white-space: nowrap; + vertical-align: baseline; + user-select: none; +} +article > section.body { + border: 1px solid #d8d8d8; + background: #FFF; + padding: 10px; + border-radius: 3px; +} +pre.sf-dump { + border-radius: 3px; + margin-bottom: 0; +} +.hidden { + display: none !important; +} +.dumped-tag > .sf-dump { + display: inline-block; + margin: 0; + padding: 1px 5px; + line-height: 1.4; + vertical-align: top; + background-color: transparent; + user-select: auto; +} +.dumped-tag > pre.sf-dump, +.dumped-tag > .sf-dump-default { + color: #CC7832; + background: none; +} +.dumped-tag > .sf-dump .sf-dump-str { color: #629755; } +.dumped-tag > .sf-dump .sf-dump-private, +.dumped-tag > .sf-dump .sf-dump-protected, +.dumped-tag > .sf-dump .sf-dump-public { color: #262626; } +.dumped-tag > .sf-dump .sf-dump-note { color: #6897BB; } +.dumped-tag > .sf-dump .sf-dump-key { color: #789339; } +.dumped-tag > .sf-dump .sf-dump-ref { color: #6E6E6E; } +.dumped-tag > .sf-dump .sf-dump-ellipsis { color: #CC7832; max-width: 100em; } +.dumped-tag > .sf-dump .sf-dump-ellipsis-path { max-width: 5em; } +.dumped-tag > .sf-dump .sf-dump-ns { user-select: none; } diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Resources/functions/dump.php b/php/libraries/composer/vendor/symfony/var-dumper/Resources/functions/dump.php new file mode 100644 index 0000000..f26aad5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Resources/functions/dump.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Component\VarDumper\VarDumper; + +if (!function_exists('dump')) { + /** + * @author Nicolas Grekas + */ + function dump($var, ...$moreVars) + { + VarDumper::dump($var); + + foreach ($moreVars as $v) { + VarDumper::dump($v); + } + + if (1 < func_num_args()) { + return func_get_args(); + } + + return $var; + } +} + +if (!function_exists('dd')) { + /** + * @return never + */ + function dd(...$vars) + { + if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + + foreach ($vars as $v) { + VarDumper::dump($v); + } + + exit(1); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Resources/js/htmlDescriptor.js b/php/libraries/composer/vendor/symfony/var-dumper/Resources/js/htmlDescriptor.js new file mode 100644 index 0000000..63101e5 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Resources/js/htmlDescriptor.js @@ -0,0 +1,10 @@ +document.addEventListener('DOMContentLoaded', function() { + let prev = null; + Array.from(document.getElementsByTagName('article')).reverse().forEach(function (article) { + const dedupId = article.dataset.dedupId; + if (dedupId === prev) { + article.getElementsByTagName('header')[0].classList.add('hidden'); + } + prev = dedupId; + }); +}); diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Server/Connection.php b/php/libraries/composer/vendor/symfony/var-dumper/Server/Connection.php new file mode 100644 index 0000000..ebfc650 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Server/Connection.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Server; + +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface; + +/** + * Forwards serialized Data clones to a server. + * + * @author Maxime Steinhausser + */ +class Connection +{ + private $host; + private $contextProviders; + + /** + * @var resource|null + */ + private $socket; + + /** + * @param string $host The server host + * @param ContextProviderInterface[] $contextProviders Context providers indexed by context name + */ + public function __construct(string $host, array $contextProviders = []) + { + if (!str_contains($host, '://')) { + $host = 'tcp://'.$host; + } + + $this->host = $host; + $this->contextProviders = $contextProviders; + } + + public function getContextProviders(): array + { + return $this->contextProviders; + } + + public function write(Data $data): bool + { + $socketIsFresh = !$this->socket; + if (!$this->socket = $this->socket ?: $this->createSocket()) { + return false; + } + + $context = ['timestamp' => microtime(true)]; + foreach ($this->contextProviders as $name => $provider) { + $context[$name] = $provider->getContext(); + } + $context = array_filter($context); + $encodedPayload = base64_encode(serialize([$data, $context]))."\n"; + + set_error_handler([self::class, 'nullErrorHandler']); + try { + if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) { + return true; + } + if (!$socketIsFresh) { + stream_socket_shutdown($this->socket, \STREAM_SHUT_RDWR); + fclose($this->socket); + $this->socket = $this->createSocket(); + } + if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) { + return true; + } + } finally { + restore_error_handler(); + } + + return false; + } + + private static function nullErrorHandler(int $t, string $m) + { + // no-op + } + + private function createSocket() + { + set_error_handler([self::class, 'nullErrorHandler']); + try { + return stream_socket_client($this->host, $errno, $errstr, 3); + } finally { + restore_error_handler(); + } + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Server/DumpServer.php b/php/libraries/composer/vendor/symfony/var-dumper/Server/DumpServer.php new file mode 100644 index 0000000..b006ea1 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Server/DumpServer.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Server; + +use Psr\Log\LoggerInterface; +use Symfony\Component\VarDumper\Cloner\Data; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * A server collecting Data clones sent by a ServerDumper. + * + * @author Maxime Steinhausser + * + * @final + */ +class DumpServer +{ + private $host; + private $logger; + + /** + * @var resource|null + */ + private $socket; + + public function __construct(string $host, ?LoggerInterface $logger = null) + { + if (!str_contains($host, '://')) { + $host = 'tcp://'.$host; + } + + $this->host = $host; + $this->logger = $logger; + } + + public function start(): void + { + if (!$this->socket = stream_socket_server($this->host, $errno, $errstr)) { + throw new \RuntimeException(sprintf('Server start failed on "%s": ', $this->host).$errstr.' '.$errno); + } + } + + public function listen(callable $callback): void + { + if (null === $this->socket) { + $this->start(); + } + + foreach ($this->getMessages() as $clientId => $message) { + if ($this->logger) { + $this->logger->info('Received a payload from client {clientId}', ['clientId' => $clientId]); + } + + $payload = @unserialize(base64_decode($message), ['allowed_classes' => [Data::class, Stub::class]]); + + // Impossible to decode the message, give up. + if (false === $payload) { + if ($this->logger) { + $this->logger->warning('Unable to decode a message from {clientId} client.', ['clientId' => $clientId]); + } + + continue; + } + + if (!\is_array($payload) || \count($payload) < 2 || !$payload[0] instanceof Data || !\is_array($payload[1])) { + if ($this->logger) { + $this->logger->warning('Invalid payload from {clientId} client. Expected an array of two elements (Data $data, array $context)', ['clientId' => $clientId]); + } + + continue; + } + + [$data, $context] = $payload; + + $callback($data, $context, $clientId); + } + } + + public function getHost(): string + { + return $this->host; + } + + private function getMessages(): iterable + { + $sockets = [(int) $this->socket => $this->socket]; + $write = []; + + while (true) { + $read = $sockets; + stream_select($read, $write, $write, null); + + foreach ($read as $stream) { + if ($this->socket === $stream) { + $stream = stream_socket_accept($this->socket); + $sockets[(int) $stream] = $stream; + } elseif (feof($stream)) { + unset($sockets[(int) $stream]); + fclose($stream); + } else { + yield (int) $stream => fgets($stream); + } + } + } + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/Test/VarDumperTestTrait.php b/php/libraries/composer/vendor/symfony/var-dumper/Test/VarDumperTestTrait.php new file mode 100644 index 0000000..5959195 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/Test/VarDumperTestTrait.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Test; + +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\CliDumper; + +/** + * @author Nicolas Grekas + */ +trait VarDumperTestTrait +{ + /** + * @internal + */ + private $varDumperConfig = [ + 'casters' => [], + 'flags' => null, + ]; + + protected function setUpVarDumper(array $casters, ?int $flags = null): void + { + $this->varDumperConfig['casters'] = $casters; + $this->varDumperConfig['flags'] = $flags; + } + + /** + * @after + */ + protected function tearDownVarDumper(): void + { + $this->varDumperConfig['casters'] = []; + $this->varDumperConfig['flags'] = null; + } + + public function assertDumpEquals($expected, $data, int $filter = 0, string $message = '') + { + $this->assertSame($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message); + } + + public function assertDumpMatchesFormat($expected, $data, int $filter = 0, string $message = '') + { + $this->assertStringMatchesFormat($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message); + } + + protected function getDump($data, $key = null, int $filter = 0): ?string + { + if (null === $flags = $this->varDumperConfig['flags']) { + $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0; + $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0; + $flags |= getenv('DUMP_COMMA_SEPARATOR') ? CliDumper::DUMP_COMMA_SEPARATOR : 0; + } + + $cloner = new VarCloner(); + $cloner->addCasters($this->varDumperConfig['casters']); + $cloner->setMaxItems(-1); + $dumper = new CliDumper(null, null, $flags); + $dumper->setColors(false); + $data = $cloner->cloneVar($data, $filter)->withRefHandles(false); + if (null !== $key && null === $data = $data->seek($key)) { + return null; + } + + return rtrim($dumper->dump($data, true)); + } + + private function prepareExpectation($expected, int $filter): string + { + if (!\is_string($expected)) { + $expected = $this->getDump($expected, null, $filter); + } + + return rtrim($expected); + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/VarDumper.php b/php/libraries/composer/vendor/symfony/var-dumper/VarDumper.php new file mode 100644 index 0000000..9db5811 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/VarDumper.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\VarDumper\Caster\ReflectionCaster; +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\CliDumper; +use Symfony\Component\VarDumper\Dumper\ContextProvider\CliContextProvider; +use Symfony\Component\VarDumper\Dumper\ContextProvider\RequestContextProvider; +use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider; +use Symfony\Component\VarDumper\Dumper\ContextualizedDumper; +use Symfony\Component\VarDumper\Dumper\HtmlDumper; +use Symfony\Component\VarDumper\Dumper\ServerDumper; + +// Load the global dump() function +require_once __DIR__.'/Resources/functions/dump.php'; + +/** + * @author Nicolas Grekas + */ +class VarDumper +{ + /** + * @var callable|null + */ + private static $handler; + + public static function dump($var) + { + if (null === self::$handler) { + self::register(); + } + + return (self::$handler)($var); + } + + /** + * @return callable|null + */ + public static function setHandler(?callable $callable = null) + { + $prevHandler = self::$handler; + + // Prevent replacing the handler with expected format as soon as the env var was set: + if (isset($_SERVER['VAR_DUMPER_FORMAT'])) { + return $prevHandler; + } + + self::$handler = $callable; + + return $prevHandler; + } + + private static function register(): void + { + $cloner = new VarCloner(); + $cloner->addCasters(ReflectionCaster::UNSET_CLOSURE_FILE_INFO); + + $format = $_SERVER['VAR_DUMPER_FORMAT'] ?? null; + switch (true) { + case 'html' === $format: + $dumper = new HtmlDumper(); + break; + case 'cli' === $format: + $dumper = new CliDumper(); + break; + case 'server' === $format: + case $format && 'tcp' === parse_url($format, \PHP_URL_SCHEME): + $host = 'server' === $format ? $_SERVER['VAR_DUMPER_SERVER'] ?? '127.0.0.1:9912' : $format; + $dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliDumper() : new HtmlDumper(); + $dumper = new ServerDumper($host, $dumper, self::getDefaultContextProviders()); + break; + default: + $dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliDumper() : new HtmlDumper(); + } + + if (!$dumper instanceof ServerDumper) { + $dumper = new ContextualizedDumper($dumper, [new SourceContextProvider()]); + } + + self::$handler = function ($var) use ($cloner, $dumper) { + $dumper->dump($cloner->cloneVar($var)); + }; + } + + private static function getDefaultContextProviders(): array + { + $contextProviders = []; + + if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && class_exists(Request::class)) { + $requestStack = new RequestStack(); + $requestStack->push(Request::createFromGlobals()); + $contextProviders['request'] = new RequestContextProvider($requestStack); + } + + $fileLinkFormatter = class_exists(FileLinkFormatter::class) ? new FileLinkFormatter(null, $requestStack ?? null) : null; + + return $contextProviders + [ + 'cli' => new CliContextProvider(), + 'source' => new SourceContextProvider(null, null, $fileLinkFormatter), + ]; + } +} diff --git a/php/libraries/composer/vendor/symfony/var-dumper/composer.json b/php/libraries/composer/vendor/symfony/var-dumper/composer.json new file mode 100644 index 0000000..ea46a72 --- /dev/null +++ b/php/libraries/composer/vendor/symfony/var-dumper/composer.json @@ -0,0 +1,50 @@ +{ + "name": "symfony/var-dumper", + "type": "library", + "description": "Provides mechanisms for walking through any arbitrary PHP variable", + "keywords": ["dump", "debug"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2.5", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "ext-iconv": "*", + "symfony/console": "^4.4|^5.0|^6.0", + "symfony/http-kernel": "^4.4|^5.0|^6.0", + "symfony/process": "^4.4|^5.0|^6.0", + "symfony/uid": "^5.1|^6.0", + "twig/twig": "^2.13|^3.0.4" + }, + "conflict": { + "symfony/console": "<4.4" + }, + "suggest": { + "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", + "ext-intl": "To show region name in time zone dump", + "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" + }, + "autoload": { + "files": [ "Resources/functions/dump.php" ], + "psr-4": { "Symfony\\Component\\VarDumper\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "bin": [ + "Resources/bin/var-dump-server" + ], + "minimum-stability": "dev" +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/LICENSE.md b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/LICENSE.md new file mode 100644 index 0000000..5f40959 --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/LICENSE.md @@ -0,0 +1,23 @@ +Copyright (c) Tijs Verkoyen. 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/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/composer.json b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/composer.json new file mode 100644 index 0000000..055ba41 --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/composer.json @@ -0,0 +1,38 @@ +{ + "name": "tijsverkoyen/css-to-inline-styles", + "type": "library", + "description": "CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.", + "homepage": "https://github.com/tijsverkoyen/CssToInlineStyles", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Tijs Verkoyen", + "email": "css_to_inline_styles@verkoyen.eu", + "role": "Developer" + } + ], + "require": { + "php": "^5.5 || ^7.0 || ^8.0", + "ext-dom": "*", + "ext-libxml": "*", + "symfony/css-selector": "^2.7 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0 || ^7.5 || ^8.5.21 || ^9.5.10" + }, + "autoload": { + "psr-4": { + "TijsVerkoyen\\CssToInlineStyles\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "TijsVerkoyen\\CssToInlineStyles\\Tests\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.2.x-dev" + } + } +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Processor.php b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Processor.php new file mode 100644 index 0000000..0c5ceb1 --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Processor.php @@ -0,0 +1,71 @@ +doCleanup($css); + $rulesProcessor = new RuleProcessor(); + $rules = $rulesProcessor->splitIntoSeparateRules($css); + + return $rulesProcessor->convertArrayToObjects($rules, $existingRules); + } + + /** + * Get the CSS from the style-tags in the given HTML-string + * + * @param string $html + * + * @return string + */ + public function getCssFromStyleTags($html) + { + $css = ''; + $matches = array(); + $htmlNoComments = preg_replace('||s', '', $html); + preg_match_all('|(.*)|isU', $htmlNoComments, $matches); + + if (!empty($matches[1])) { + foreach ($matches[1] as $match) { + $css .= trim($match) . "\n"; + } + } + + return $css; + } + + /** + * @param string $css + * + * @return string + */ + private function doCleanup($css) + { + // remove charset + $css = preg_replace('/@charset "[^"]++";/', '', $css); + // remove media queries + $css = preg_replace('/@media [^{]*+{([^{}]++|{[^{}]*+})*+}/', '', $css); + + $css = str_replace(array("\r", "\n"), '', $css); + $css = str_replace(array("\t"), ' ', $css); + $css = str_replace('"', '\'', $css); + $css = preg_replace('|/\*.*?\*/|', '', $css); + $css = preg_replace('/\s\s++/', ' ', $css); + $css = trim($css); + + return $css; + } +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Property/Processor.php b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Property/Processor.php new file mode 100644 index 0000000..3b01861 --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Property/Processor.php @@ -0,0 +1,127 @@ +cleanup($propertiesString); + + $properties = (array) explode(';', $propertiesString); + $keysToRemove = array(); + $numberOfProperties = count($properties); + + for ($i = 0; $i < $numberOfProperties; $i++) { + $properties[$i] = trim($properties[$i]); + + // if the new property begins with base64 it is part of the current property + if (isset($properties[$i + 1]) && strpos(trim($properties[$i + 1]), 'base64,') === 0) { + $properties[$i] .= ';' . trim($properties[$i + 1]); + $keysToRemove[] = $i + 1; + } + } + + if (!empty($keysToRemove)) { + foreach ($keysToRemove as $key) { + unset($properties[$key]); + } + } + + return array_values($properties); + } + + /** + * @param string $string + * + * @return string + */ + private function cleanup($string) + { + $string = str_replace(array("\r", "\n"), '', $string); + $string = str_replace(array("\t"), ' ', $string); + $string = str_replace('"', '\'', $string); + $string = preg_replace('|/\*.*?\*/|', '', $string); + $string = preg_replace('/\s\s+/', ' ', $string); + + $string = trim($string); + $string = rtrim($string, ';'); + + return $string; + } + + /** + * Converts a property-string into an object + * + * @param string $property + * + * @return Property|null + */ + public function convertToObject($property, Specificity $specificity = null) + { + if (strpos($property, ':') === false) { + return null; + } + + list($name, $value) = explode(':', $property, 2); + + $name = trim($name); + $value = trim($value); + + if ($value === '') { + return null; + } + + return new Property($name, $value, $specificity); + } + + /** + * Converts an array of property-strings into objects + * + * @param string[] $properties + * + * @return Property[] + */ + public function convertArrayToObjects(array $properties, Specificity $specificity = null) + { + $objects = array(); + + foreach ($properties as $property) { + $object = $this->convertToObject($property, $specificity); + if ($object === null) { + continue; + } + + $objects[] = $object; + } + + return $objects; + } + + /** + * Build the property-string for multiple properties + * + * @param Property[] $properties + * + * @return string + */ + public function buildPropertiesString(array $properties) + { + $chunks = array(); + + foreach ($properties as $property) { + $chunks[] = $property->toString(); + } + + return implode(' ', $chunks); + } +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Property/Property.php b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Property/Property.php new file mode 100644 index 0000000..c8970cf --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Property/Property.php @@ -0,0 +1,90 @@ +name = $name; + $this->value = $value; + $this->originalSpecificity = $specificity; + } + + /** + * Get name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Get value + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Get originalSpecificity + * + * @return Specificity + */ + public function getOriginalSpecificity() + { + return $this->originalSpecificity; + } + + /** + * Is this property important? + * + * @return bool + */ + public function isImportant() + { + return (stripos($this->value, '!important') !== false); + } + + /** + * Get the textual representation of the property + * + * @return string + */ + public function toString() + { + return sprintf( + '%1$s: %2$s;', + $this->name, + $this->value + ); + } +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Rule/Processor.php b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Rule/Processor.php new file mode 100644 index 0000000..d183262 --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Rule/Processor.php @@ -0,0 +1,163 @@ +cleanup($rulesString); + + return (array) explode('}', $rulesString); + } + + /** + * @param string $string + * + * @return string + */ + private function cleanup($string) + { + $string = str_replace(array("\r", "\n"), '', $string); + $string = str_replace(array("\t"), ' ', $string); + $string = str_replace('"', '\'', $string); + $string = preg_replace('|/\*.*?\*/|', '', $string); + $string = preg_replace('/\s\s+/', ' ', $string); + + $string = trim($string); + $string = rtrim($string, '}'); + + return $string; + } + + /** + * Converts a rule-string into an object + * + * @param string $rule + * @param int $originalOrder + * + * @return Rule[] + */ + public function convertToObjects($rule, $originalOrder) + { + $rule = $this->cleanup($rule); + + $chunks = explode('{', $rule); + if (!isset($chunks[1])) { + return array(); + } + $propertiesProcessor = new PropertyProcessor(); + $rules = array(); + $selectors = (array) explode(',', trim($chunks[0])); + $properties = $propertiesProcessor->splitIntoSeparateProperties($chunks[1]); + + foreach ($selectors as $selector) { + $selector = trim($selector); + $specificity = $this->calculateSpecificityBasedOnASelector($selector); + + $rules[] = new Rule( + $selector, + $propertiesProcessor->convertArrayToObjects($properties, $specificity), + $specificity, + $originalOrder + ); + } + + return $rules; + } + + /** + * Calculates the specificity based on a CSS Selector string, + * Based on the patterns from premailer/css_parser by Alex Dunae + * + * @see https://github.com/premailer/css_parser/blob/master/lib/css_parser/regexps.rb + * + * @param string $selector + * + * @return Specificity + */ + public function calculateSpecificityBasedOnASelector($selector) + { + $idSelectorsPattern = " \#"; + $classAttributesPseudoClassesSelectorsPattern = " (\.[\w]+) # classes + | + \[(\w+) # attributes + | + (\:( # pseudo classes + link|visited|active + |hover|focus + |lang + |target + |enabled|disabled|checked|indeterminate + |root + |nth-child|nth-last-child|nth-of-type|nth-last-of-type + |first-child|last-child|first-of-type|last-of-type + |only-child|only-of-type + |empty|contains + ))"; + + $typePseudoElementsSelectorPattern = " ((^|[\s\+\>\~]+)[\w]+ # elements + | + \:{1,2}( # pseudo-elements + after|before + |first-letter|first-line + |selection + ) + )"; + + return new Specificity( + preg_match_all("/{$idSelectorsPattern}/ix", $selector, $matches), + preg_match_all("/{$classAttributesPseudoClassesSelectorsPattern}/ix", $selector, $matches), + preg_match_all("/{$typePseudoElementsSelectorPattern}/ix", $selector, $matches) + ); + } + + /** + * @param string[] $rules + * @param Rule[] $objects + * + * @return Rule[] + */ + public function convertArrayToObjects(array $rules, array $objects = array()) + { + $order = 1; + foreach ($rules as $rule) { + $objects = array_merge($objects, $this->convertToObjects($rule, $order)); + $order++; + } + + return $objects; + } + + /** + * Sorts an array on the specificity element in an ascending way + * Lower specificity will be sorted to the beginning of the array + * + * @param Rule $e1 The first element. + * @param Rule $e2 The second element. + * + * @return int + */ + public static function sortOnSpecificity(Rule $e1, Rule $e2) + { + $e1Specificity = $e1->getSpecificity(); + $value = $e1Specificity->compareTo($e2->getSpecificity()); + + // if the specificity is the same, use the order in which the element appeared + if ($value === 0) { + $value = $e1->getOrder() - $e2->getOrder(); + } + + return $value; + } +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Rule/Rule.php b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Rule/Rule.php new file mode 100644 index 0000000..563889e --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/Css/Rule/Rule.php @@ -0,0 +1,85 @@ +selector = $selector; + $this->properties = $properties; + $this->specificity = $specificity; + $this->order = $order; + } + + /** + * Get selector + * + * @return string + */ + public function getSelector() + { + return $this->selector; + } + + /** + * Get properties + * + * @return Property[] + */ + public function getProperties() + { + return $this->properties; + } + + /** + * Get specificity + * + * @return Specificity + */ + public function getSpecificity() + { + return $this->specificity; + } + + /** + * Get order + * + * @return int + */ + public function getOrder() + { + return $this->order; + } +} diff --git a/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php new file mode 100644 index 0000000..e40ae25 --- /dev/null +++ b/php/libraries/composer/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php @@ -0,0 +1,240 @@ +cssConverter = new CssSelectorConverter(); + } + } + + /** + * Will inline the $css into the given $html + * + * Remark: if the html contains